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
Stop CI from re-running tests that already proved themselves (#4367)
[._.]/ Adam Eivy3a0667ba8970
diff --git a/.changelog/next/changed-meaningful-tests.md b/.changelog/next/changed-meaningful-tests.mdnew file mode 100644index 0000000000..81ab347c7e--- /dev/null+++ b/.changelog/next/changed-meaningful-tests.md@@ -0,0 +1 @@+- CI skips Windows and a second Vitest pass unless they add signal; tests that only re-ran a copy of the code now exercise the real modules.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 653d0beda7..4ee5a6bdce 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -40,6 +40,8 @@ jobs:lint_files: ${{ steps.plan.outputs.lint_files }}build: ${{ steps.plan.outputs.build }}smoke: ${{ steps.plan.outputs.smoke }}+ windows: ${{ steps.plan.outputs.windows }}+ server_native: ${{ steps.plan.outputs.server_native }}steps:- uses: actions/checkout@v7with:@@ -62,6 +64,8 @@ jobs:LINT_MODE: ${{ steps.plan.outputs.lint_mode }}BUILD_MODE: ${{ steps.plan.outputs.build }}SMOKE_MODE: ${{ steps.plan.outputs.smoke }}+ WINDOWS_MODE: ${{ steps.plan.outputs.windows }}+ SERVER_NATIVE: ${{ steps.plan.outputs.server_native }}run: |{echo "### CI impact plan"@@ -73,6 +77,8 @@ jobs:echo "- Client lint: \`${LINT_MODE}\`"echo "- Client build: \`${BUILD_MODE}\`"echo "- Server smoke: \`${SMOKE_MODE}\`"+ echo "- Windows server tests: \`${WINDOWS_MODE}\`"+ echo "- Server native rebuild: \`${SERVER_NATIVE}\`"} >> "$GITHUB_STEP_SUMMARY"server:@@ -99,23 +105,34 @@ jobs:# 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- name: Run server tests+ if: needs.impact.outputs.server_mode != 'skip'env:CI_TEST_MODE: ${{ needs.impact.outputs.server_mode }}CI_TEST_FILES: ${{ needs.impact.outputs.server_files }}CI_BASE_SHA: ${{ github.event.pull_request.base.sha }}run: node scripts/run-ci-tests.js server+ # Smoke-boot does not need Postgres: NODE_ENV=test selects the file+ # backend. It does need the native rebuild (server boot loads node-pty),+ # which is why it lives on this job rather than a third installer.+ - name: Smoke-boot server+ if: needs.impact.outputs.smoke == 'true'+ run: npm run smoke+client:name: Client tests and buildneeds: impact- if: needs.impact.outputs.client_mode != 'skip' || needs.impact.outputs.build == 'true'+ if: needs.impact.outputs.client_mode != 'skip' || needs.impact.outputs.build == 'true' || needs.impact.outputs.lint_mode != 'skip'runs-on: ubuntu-lateststeps:- uses: actions/checkout@v7@@ -132,6 +149,13 @@ jobs:- name: Install client dependenciesrun: npm ci --prefix client+ - name: Lint client+ if: needs.impact.outputs.lint_mode != 'skip'+ env:+ CI_LINT_MODE: ${{ needs.impact.outputs.lint_mode }}+ CI_LINT_FILES: ${{ needs.impact.outputs.lint_files }}+ run: node scripts/run-ci-lint.js+- name: Run client testsif: needs.impact.outputs.client_mode != 'skip'env:@@ -145,9 +169,9 @@ jobs:run: npm run build --prefix clientdatabase:- name: DB tests and server smoke+ name: DB testsneeds: impact- if: needs.impact.outputs.db == 'true' || needs.impact.outputs.smoke == 'true'+ if: needs.impact.outputs.db == 'true'runs-on: ubuntu-latestservices:postgres:@@ -181,54 +205,46 @@ jobs:- name: Install server dependenciesrun: npm ci --prefix server- # server/.npmrc pins ignore-scripts=true — the smoke-boot below needs the- # native bindings, so run the explicit allowlist rebuild first.+ # server/.npmrc pins ignore-scripts=true — DB suites that touch sharp /+ # node-pty still need the explicit allowlist rebuild.- name: Rebuild trusted native dependenciesrun: node scripts/trusted-rebuilds.js server- name: Provision test database (portos_test)- if: needs.impact.outputs.db == 'true'run: npm run setup:db:test --prefix server- name: Run DB-backed tests (portos_test)- if: needs.impact.outputs.db == 'true'run: npm run test:db:ci --prefix serverenv:PGDATABASE: portos_test- - name: Smoke-boot server- if: needs.impact.outputs.smoke == 'true'- run: npm run smoke-lint:- # Preserve the historical required-check context during the CI migration.+ # Historical required-check name. Lint itself now runs inside the client+ # job so we do not pay a second `npm ci --prefix client`. This job only+ # mirrors that result so branch protection can keep requiring "lint".name: lint- needs: impact- if: needs.impact.outputs.lint_mode != 'skip'+ needs: [impact, client]+ if: always() && needs.impact.result == 'success'runs-on: ubuntu-lateststeps:- - uses: actions/checkout@v7-- - name: Use Node.js 24.x- uses: actions/setup-node@v7- with:- node-version: 24.x- cache: npm- cache-dependency-path: client/package-lock.json-- - name: Install client dependencies- run: npm ci --prefix client-- - name: Lint client+ - name: Require client-job lint when it was selected+ if: needs.impact.outputs.lint_mode != 'skip'env:- CI_LINT_MODE: ${{ needs.impact.outputs.lint_mode }}- CI_LINT_FILES: ${{ needs.impact.outputs.lint_files }}- run: node scripts/run-ci-lint.js+ CLIENT_RESULT: ${{ needs.client.result }}+ run: |+ if [ "$CLIENT_RESULT" != "success" ]; then+ echo "Lint ran inside the client job, which did not succeed ($CLIENT_RESULT)."+ exit 1+ fi++ - name: Lint not selected+ if: needs.impact.outputs.lint_mode == 'skip'+ run: echo "Lint skipped by impact plan"windows-server:name: Windows server unit testsneeds: impact- if: needs.impact.outputs.server_mode != 'skip'+ if: needs.impact.outputs.windows == 'true'runs-on: windows-lateststeps:- uses: actions/checkout@v7diff --git a/client/package.json b/client/package.jsonindex 57d6e94edd..3c594fc980 100644--- a/client/package.json+++ b/client/package.json@@ -13,7 +13,7 @@"lint": "biome lint --error-on-warnings src","preview": "vite preview","test": "vitest run",- "test:ci": "vitest run --bail=1 --reporter=default --reporter=github-actions",+ "test:ci": "vitest run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions","test:watch": "vitest"},"dependencies": {diff --git a/client/src/hooks/index.test.js b/client/src/hooks/index.test.jsindex cee58844e5..4244d67ae5 100644--- a/client/src/hooks/index.test.js+++ b/client/src/hooks/index.test.js@@ -15,21 +15,8 @@ const sourceFiles = readdirSync(HERE).filter();describe('client/src/hooks/ barrel', () => {- it('resolves every re-export', () => {- expect(Object.keys(barrel).length).toBeGreaterThan(0);- });-- it('exposes hooks under their canonical names', () => {- // Both default-exported and named-exported hooks should surface as `useX`.- expect(typeof barrel.useLockToggle).toBe('function');- expect(typeof barrel.useMounted).toBe('function');- expect(typeof barrel.useAsyncAction).toBe('function');- expect(typeof barrel.useSseProgress).toBe('function');- expect(typeof barrel.useSocket).toBe('function');- expect(typeof barrel.useClickOutside).toBe('function');- });-it('re-exports every non-test hook file from index.js', () => {+ expect(Object.keys(barrel).length).toBeGreaterThan(0);for (const f of sourceFiles) {expect(BARREL_SRC, `missing barrel re-export for ${f}`).toContain(`'./${f}'`);}diff --git a/client/src/hooks/useMediaJobProgress.test.js b/client/src/hooks/useMediaJobProgress.test.jsdeleted file mode 100644index 1a5a7aab53..0000000000--- a/client/src/hooks/useMediaJobProgress.test.js+++ /dev/null@@ -1,67 +0,0 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';-import { renderHook, act, waitFor } from '@testing-library/react';--const handlers = new Map();-const mediaJob = { current: { status: 'running' } };-vi.mock('../services/socket', () => ({- default: {- on: (event, fn) => { handlers.set(event, fn); },- off: (event, fn) => { if (handlers.get(event) === fn) handlers.delete(event); },- },-}));-vi.mock('../services/apiMediaJobs', () => ({- getMediaJob: vi.fn(async () => mediaJob.current),-}));--import useMediaJobProgress from './useMediaJobProgress';--const fire = (event, payload) => act(() => { handlers.get(event)?.(payload); });--describe('useMediaJobProgress — render ETA (#3801)', () => {- beforeEach(() => { handlers.clear(); mediaJob.current = { status: 'running' }; });-- it('starts with no estimate', async () => {- const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));- // Settle the mount-time GET /api/media-jobs/:id hydration.- await act(async () => {});- expect(result.current.etaMs).toBeNull();- });-- it('picks up the estimate from the started event and repeats it on progress', async () => {- const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));- await waitFor(() => expect(handlers.has('video-gen:started')).toBe(true));- fire('video-gen:started', { generationId: 'job-1', totalSteps: 30, etaMs: 1_800_000 });- expect(result.current.etaMs).toBe(1_800_000);- fire('video-gen:progress', { generationId: 'job-1', progress: 0.5, etaMs: 1_800_000 });- expect(result.current.etaMs).toBe(1_800_000);- });-- it('keeps the last estimate when a progress frame omits the key', async () => {- const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));- await waitFor(() => expect(handlers.has('video-gen:started')).toBe(true));- fire('video-gen:started', { generationId: 'job-1', etaMs: 600_000 });- fire('video-gen:progress', { generationId: 'job-1', progress: 0.2 });- expect(result.current.etaMs).toBe(600_000);- });-- it('treats an explicit null estimate as "unknown", not as a stale value to keep', async () => {- const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));- await waitFor(() => expect(handlers.has('video-gen:started')).toBe(true));- fire('video-gen:started', { generationId: 'job-1', etaMs: 600_000 });- fire('video-gen:started', { generationId: 'job-1', etaMs: null });- expect(result.current.etaMs).toBeNull();- });-- it('hydrates the estimate from the queue snapshot on reload', async () => {- mediaJob.current = { status: 'running', progress: 0.3, etaMs: 900_000 };- const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));- await waitFor(() => expect(result.current.etaMs).toBe(900_000));- });-- it('ignores events for a different job', async () => {- const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));- await waitFor(() => expect(handlers.has('video-gen:started')).toBe(true));- fire('video-gen:started', { generationId: 'job-2', etaMs: 600_000 });- expect(result.current.etaMs).toBeNull();- });-});diff --git a/client/src/hooks/useMediaJobProgress.test.jsx b/client/src/hooks/useMediaJobProgress.test.jsxindex bbbfec2b1d..4827854268 100644--- a/client/src/hooks/useMediaJobProgress.test.jsx+++ b/client/src/hooks/useMediaJobProgress.test.jsx@@ -82,3 +82,52 @@ describe('useMediaJobProgress — canceled handling (#1791)', () => {await waitFor(() => expect(result.current.status).toBe('canceled'));});});++describe('useMediaJobProgress — render ETA (#3801)', () => {+ beforeEach(() => { handlers.clear(); getMediaJob.mockClear(); getMediaJob.mockResolvedValue({ status: 'running' }); });+ afterEach(cleanup);++ it('starts with no estimate', async () => {+ const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));+ await settle();+ expect(result.current.etaMs).toBeNull();+ });++ it('picks up the estimate from the started event and repeats it on progress', async () => {+ const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));+ await waitFor(() => expect(handlers.has('video-gen:started')).toBe(true));+ fire('video-gen:started', { generationId: 'job-1', totalSteps: 30, etaMs: 1_800_000 });+ expect(result.current.etaMs).toBe(1_800_000);+ fire('video-gen:progress', { generationId: 'job-1', progress: 0.5, etaMs: 1_800_000 });+ expect(result.current.etaMs).toBe(1_800_000);+ });++ it('keeps the last estimate when a progress frame omits the key', async () => {+ const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));+ await waitFor(() => expect(handlers.has('video-gen:started')).toBe(true));+ fire('video-gen:started', { generationId: 'job-1', etaMs: 600_000 });+ fire('video-gen:progress', { generationId: 'job-1', progress: 0.2 });+ expect(result.current.etaMs).toBe(600_000);+ });++ it('treats an explicit null estimate as "unknown", not as a stale value to keep', async () => {+ const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));+ await waitFor(() => expect(handlers.has('video-gen:started')).toBe(true));+ fire('video-gen:started', { generationId: 'job-1', etaMs: 600_000 });+ fire('video-gen:started', { generationId: 'job-1', etaMs: null });+ expect(result.current.etaMs).toBeNull();+ });++ it('hydrates the estimate from the queue snapshot on reload', async () => {+ getMediaJob.mockResolvedValue({ status: 'running', progress: 0.3, etaMs: 900_000 });+ const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));+ await waitFor(() => expect(result.current.etaMs).toBe(900_000));+ });++ it('ignores events for a different job', async () => {+ const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));+ await waitFor(() => expect(handlers.has('video-gen:started')).toBe(true));+ fire('video-gen:started', { generationId: 'job-2', etaMs: 600_000 });+ expect(result.current.etaMs).toBeNull();+ });+});diff --git a/client/src/hooks/useVideoGenQueue.test.jsx b/client/src/hooks/useVideoGenQueue.test.jsxnew file mode 100644index 0000000000..58e5bad315--- /dev/null+++ b/client/src/hooks/useVideoGenQueue.test.jsx@@ -0,0 +1,119 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { renderHook, act, waitFor } from '@testing-library/react';++vi.mock('../components/ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() },+}));++import { useVideoGenQueue } from './useVideoGenQueue.js';+import toast from '../components/ui/Toast';++const flush = () => act(async () => {});++describe('useVideoGenQueue', () => {+ beforeEach(() => {+ toast.success.mockClear();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it('preserves string filenames and File/Blob objects when a queued item is dispatched', async () => {+ const sourceImageFile = new File(['x'], 'source.png', { type: 'image/png' });+ const seen = [];+ const runGeneration = vi.fn(async (payload) => {+ seen.push(payload);+ return { ok: true };+ });++ const { result } = renderHook(() => useVideoGenQueue({+ generating: false,+ runGeneration,+ }));++ act(() => {+ result.current.enqueue({+ prompt: 'a cinematic scene',+ sourceImage: 'gallery_source.png',+ lastImage: 'gallery_last.png',+ icReferenceImageFiles: ['ref1.png', 'ref2.png'],+ keyframes: [{ frame: 0, image: 'f1.png' }],+ sourceImageFile,+ });+ });++ await waitFor(() => expect(runGeneration).toHaveBeenCalledTimes(1));+ expect(seen[0].sourceImage).toBe('gallery_source.png');+ expect(seen[0].lastImage).toBe('gallery_last.png');+ expect(seen[0].icReferenceImageFiles).toEqual(['ref1.png', 'ref2.png']);+ expect(seen[0].keyframes).toEqual([{ frame: 0, image: 'f1.png' }]);+ expect(seen[0].sourceImageFile).toBe(sourceImageFile);+ });++ it('retries a BUSY item after the backoff instead of marking it errored', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ let calls = 0;+ const runGeneration = vi.fn(() => {+ calls += 1;+ if (calls === 1) return Promise.reject(new Error('VIDEO_GEN_BUSY'));+ return Promise.resolve({ ok: true });+ });+ const { result } = renderHook(() => useVideoGenQueue({+ generating: false,+ runGeneration,+ }));++ act(() => {+ result.current.enqueue({ prompt: 'one' });+ });+ await waitFor(() => expect(result.current.queue[0]?.status).toBe('pending'));+ expect(result.current.runningQueueId).not.toBeNull();++ await act(async () => {+ vi.advanceTimersByTime(1500);+ });+ await waitFor(() => expect(result.current.queue[0]?.status).toBe('complete'));+ expect(runGeneration).toHaveBeenCalledTimes(2);+ expect(result.current.runningQueueId).toBeNull();+ });++ it('does not release the slot from a stale BUSY timer after unmount', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const runGeneration = vi.fn(() => Promise.reject(new Error('409 already in progress')));+ const { result, unmount } = renderHook(() => useVideoGenQueue({+ generating: false,+ runGeneration,+ }));++ act(() => {+ result.current.enqueue({ prompt: 'one' });+ });+ await waitFor(() => expect(result.current.runningQueueId).not.toBeNull());+ await flush();+ const idAtUnmount = result.current.runningQueueId;+ unmount();++ await act(async () => {+ vi.advanceTimersByTime(5000);+ });+ // Hook is unmounted — the timer must not throw, and the last observed+ // slot is whatever was running at teardown (not cleared by a leaked fire).+ expect(idAtUnmount).not.toBeNull();+ vi.useRealTimers();+ });++ it('marks a non-BUSY failure as error and releases the slot immediately', async () => {+ const runGeneration = vi.fn(() => Promise.reject(new Error('boom')));+ const { result } = renderHook(() => useVideoGenQueue({+ generating: false,+ runGeneration,+ }));++ act(() => {+ result.current.enqueue({ prompt: 'one' });+ });+ await waitFor(() => expect(result.current.queue[0]?.status).toBe('error'));+ expect(result.current.queue[0].error).toBe('boom');+ expect(result.current.runningQueueId).toBeNull();+ });+});diff --git a/client/src/lib/index.test.js b/client/src/lib/index.test.jsindex c676f38a4b..1b2411bb95 100644--- a/client/src/lib/index.test.js+++ b/client/src/lib/index.test.js@@ -13,20 +13,8 @@ const sourceFiles = readdirSync(HERE).filter();describe('client/src/lib/ barrel', () => {- it('resolves every re-export', () => {- expect(Object.keys(barrel).length).toBeGreaterThan(0);- });-- it('exposes a representative sample of helpers', () => {- expect(typeof barrel.copyToClipboard).toBe('function');- expect(typeof barrel.flattenCanonDescriptorFragments).toBe('function');- expect(typeof barrel.mapCanonDescriptorFragments).toBe('function');- expect(typeof barrel.descriptorForCanonEntry).toBe('function');- expect(typeof barrel.composeCleanPlatePrompt).toBe('function');- expect(typeof barrel.getAdjacentMedia).toBe('function');- });-it('re-exports every non-test .js file from index.js', () => {+ expect(Object.keys(barrel).length).toBeGreaterThan(0);for (const f of sourceFiles) {expect(BARREL_SRC, `missing barrel re-export for ${f}`).toContain(`'./${f}'`);}diff --git a/client/src/pages/VideoGen.queueWorker.test.js b/client/src/pages/VideoGen.queueWorker.test.jsdeleted file mode 100644index c0dd4bb861..0000000000--- a/client/src/pages/VideoGen.queueWorker.test.js+++ /dev/null@@ -1,170 +0,0 @@-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';--// Faithful model of VideoGen's queue-worker BUSY-retry guard (see the effect in-// client/src/pages/VideoGen.jsx). VideoGen is a >1400-line component with heavy-// imports and an internal runGeneration(), so per the repo convention for-// hard-to-mock logic (server subAgentSpawner.test.js) we exercise the exact-// staleness/unmount guard here rather than full-rendering the page.-//-// The regression this locks in: the BUSY-retry setTimeout used to be a local-// `let busyRetryTimer` assigned inside an async .catch. The effect re-runs on-// every setQueue/setRunningQueueId, so its cleanup was consumed before the-// timer was ever assigned — leaving the timer to fire setRunningQueueId after-// unmount / after a newer dispatch owned the slot. The fix: timer on a ref,-// cleared by a dedicated unmount cleanup, plus a generation token + mountedRef-// guard on every deferred callback.--function makeWorker() {- const busyRetryTimerRef = { current: null };- const queueWorkerGenRef = { current: 0 };- const mountedRef = { current: true };- let runningQueueId = null;- const setRunningQueueId = (fnOrVal) => {- runningQueueId = typeof fnOrVal === 'function' ? fnOrVal(runningQueueId) : fnOrVal;- };-- // Dispatch one item; runGeneration is injected so the test controls resolution.- function dispatch(itemId, runGeneration) {- const myGen = ++queueWorkerGenRef.current;- const isCurrent = () => mountedRef.current && myGen === queueWorkerGenRef.current;- setRunningQueueId(itemId);- let busyRetry = false;- return runGeneration().then(() => {- if (!isCurrent()) return;- }).catch((err) => {- if (!isCurrent()) return;- const isBusy = /already in progress|VIDEO_GEN_BUSY|409/i.test(err?.message || '');- if (isBusy) {- busyRetry = true;- busyRetryTimerRef.current = setTimeout(() => {- busyRetryTimerRef.current = null;- if (!isCurrent()) return;- setRunningQueueId((curr) => (curr === itemId ? null : curr));- }, 1500);- return;- }- }).finally(() => {- if (isCurrent() && !busyRetry) setRunningQueueId(null);- });- }-- function unmount() {- mountedRef.current = false;- if (busyRetryTimerRef.current) {- clearTimeout(busyRetryTimerRef.current);- busyRetryTimerRef.current = null;- }- }-- return {- dispatch,- unmount,- get runningQueueId() { return runningQueueId; },- get timer() { return busyRetryTimerRef.current; },- get gen() { return queueWorkerGenRef.current; },- };-}--describe('VideoGen queue-worker BUSY-retry guard', () => {- beforeEach(() => { vi.useFakeTimers(); });- afterEach(() => { vi.useRealTimers(); });-- it('releases the slot after the BUSY backoff when still current', async () => {- const w = makeWorker();- await w.dispatch('a', () => Promise.reject(new Error('VIDEO_GEN_BUSY')));- expect(w.runningQueueId).toBe('a');- expect(w.timer).not.toBeNull();- vi.advanceTimersByTime(1500);- expect(w.runningQueueId).toBeNull();- expect(w.timer).toBeNull();- });-- it('does NOT release the slot when unmounted during the backoff', async () => {- const w = makeWorker();- await w.dispatch('a', () => Promise.reject(new Error('409 already in progress')));- expect(w.timer).not.toBeNull();- w.unmount(); // teardown clears the ref timer- expect(w.timer).toBeNull();- vi.advanceTimersByTime(5000);- // Nothing to fire — and even a leaked fire would bail on mountedRef.- expect(w.runningQueueId).toBe('a');- });-- it('a stale BUSY timer never releases a slot a newer dispatch now owns', async () => {- const w = makeWorker();- // Dispatch A → BUSY, timer scheduled for gen 1.- await w.dispatch('a', () => Promise.reject(new Error('VIDEO_GEN_BUSY')));- const genAfterA = w.gen;- // Before the timer fires, a newer dispatch (B) supersedes it.- await w.dispatch('b', () => Promise.resolve());- expect(w.gen).toBeGreaterThan(genAfterA);- // B resolved current and released, so slot is null; then A's stale timer fires.- vi.advanceTimersByTime(1500);- // The stale timer must NOT touch the slot (its isCurrent() is false).- expect(w.runningQueueId).toBeNull();- });-- it('marks a non-BUSY failure as done and releases the slot immediately', async () => {- const w = makeWorker();- await w.dispatch('a', () => Promise.reject(new Error('boom')));- expect(w.timer).toBeNull();- expect(w.runningQueueId).toBeNull();- });-});--describe('useVideoGenQueue parameter preservation', () => {- it('preserves string filenames, arrays, objects, and File/Blob objects when enqueued and restored', () => {- // Import helper logic corresponding to useVideoGenQueue's enqueue and dequeue restoration- const fakeFile = { name: 'source.png', size: 100 };- // Simulated instanceof File / Blob check logic- const isBlob = (v) => v === fakeFile || (typeof Blob !== 'undefined' && (v instanceof File || v instanceof Blob));-- const payload = {- prompt: 'a cinematic scene',- mode: 'image',- sourceImage: 'gallery_source.png',- lastImage: 'gallery_last.png',- audioFile: 'track.mp3',- icReference: 'ic_ref.mp4',- icReferenceImageFiles: ['ref1.png', 'ref2.png'],- keyframes: [{ frame: 0, image: 'f1.png' }],- sourceImageFile: fakeFile,- };-- const _blobs = {};- const params = {};- for (const [k, v] of Object.entries(payload)) {- if (isBlob(v)) {- _blobs[k] = v;- } else if (Array.isArray(v) && v.some((item) => isBlob(item))) {- _blobs[k] = v;- } else {- params[k] = v;- }- }-- // Verify params keeps all non-File properties- expect(params.sourceImage).toBe('gallery_source.png');- expect(params.lastImage).toBe('gallery_last.png');- expect(params.audioFile).toBe('track.mp3');- expect(params.icReference).toBe('ic_ref.mp4');- expect(params.icReferenceImageFiles).toEqual(['ref1.png', 'ref2.png']);- expect(params.keyframes).toEqual([{ frame: 0, image: 'f1.png' }]);-- // Verify _blobs holds the File object- expect(_blobs.sourceImageFile).toBe(fakeFile);-- // Dequeue restoration- const restoredPayload = { ...params };- for (const [k, v] of Object.entries(_blobs)) {- if (v != null) restoredPayload[k] = v;- }-- expect(restoredPayload.sourceImage).toBe('gallery_source.png');- expect(restoredPayload.lastImage).toBe('gallery_last.png');- expect(restoredPayload.audioFile).toBe('track.mp3');- expect(restoredPayload.icReference).toBe('ic_ref.mp4');- expect(restoredPayload.sourceImageFile).toBe(fakeFile);- });-});-diff --git a/client/src/utils/index.test.js b/client/src/utils/index.test.jsindex 38dca16ceb..a39087a5dc 100644--- a/client/src/utils/index.test.js+++ b/client/src/utils/index.test.js@@ -27,22 +27,8 @@ for (const f of sourceFiles) {}describe('client/src/utils/ barrel', () => {- it('resolves every re-export', () => {- expect(Object.keys(barrel).length).toBeGreaterThan(0);- });-- it('exposes a representative sample of helpers', () => {- expect(typeof barrel.formatBytes).toBe('function');- expect(typeof barrel.timeAgo).toBe('function');- expect(typeof barrel.describeCron).toBe('function');- expect(typeof barrel.hashString).toBe('function');- expect(typeof barrel.normalizeUrl).toBe('function');- expect(typeof barrel.levelFromXP).toBe('function');- expect(typeof barrel.computeAiCore).toBe('function');- expect(typeof barrel.computeGoalMonuments).toBe('function');- });-it('re-exports every non-test .js file from index.js', () => {+ expect(Object.keys(barrel).length).toBeGreaterThan(0);for (const f of sourceFiles) {expect(BARREL_SRC, `missing barrel re-export for ${f}`).toContain(`'./${f}'`);}diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.mdindex 959de1a2d1..9ca01c8664 100644--- a/docs/GITHUB_ACTIONS.md+++ b/docs/GITHUB_ACTIONS.md@@ -20,24 +20,39 @@ for shared composition roots, test configuration, dependency manifests,workflow changes, unknown artifacts, or wide diffs.A short always-run list (`ALWAYS_RUN_TESTS` in the planner) is added to every-plan, so no impact scope can drop it — currently just-`server/services/taskPromptDefaults.test.js`, which pins the cross-install-prompt-upgrade contract nothing else in the suite covers. A documentation-only-PR therefore still runs the server job with that one file selected.+plan, so no impact scope can drop it — currently+`server/services/taskPromptDefaults.test.js` (cross-install prompt-upgrade) and+`scripts/changelogFragments.test.js` (release-note fragment parse). A+documentation-only PR therefore still runs the server job with those files+selected.The selected work is split across parallel jobs:-- **Server tests** — full, related, or explicit feature test files.+- **Server tests** — full, related, or explicit feature test files. Smoke-boots+ the 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.- **Client tests and build** — affected client tests; production build whenever- client source changed.-- **DB tests and server smoke** — provisions only the isolated `portos_test`- database and runs DB tests when database-sensitive files changed; smoke-boots- for server source changes.-- **Client lint** — only changed JS/JSX files on targeted PRs, the complete- client tree during full CI.+ client source changed; client lint on the same install so Biome does not pay a+ second `npm ci`.+- **DB tests** — provisions only the isolated `portos_test` database and runs+ the serial DB suite when database-sensitive files changed.+- **Windows server tests** — the same server selection, but only on full CI+ (push to `main`, nightly, release, workflow dispatch) or when a+ Windows-sensitive surface changed (`.ps1` / `.cmd` spawn, PowerShell BOM,+ `bufferedSpawn`, `cos-runner`, shell/PM2, etc.). Docs-only and ordinary+ Linux-faithful PRs skip this job. `pinPlatform('win32')` tests still run on+ Linux.+- **lint** — historical required-check name. The real lint step lives in the+ client job; this job only mirrors that result.- **CI Gate** — always reports one stable required-check result and fails if anyselected job failed or was cancelled.+Targeted `files` / `related` plans run **one** Vitest process for the union of+planner-selected files and Vitest's `--changed` import graph. The two sets are+listed then merged — they cannot share one argv, because Vitest ANDs+`--changed` with path selectors.+No third-party change-filter action is used. The planner passes test paths as aJSON argument array to `spawnSync`, never through shell interpolation.diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex 3c62051eb9..283a7e0e90 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -26,7 +26,24 @@ const FULL_TRIGGER_RULES = [{ re: /^client\/src\/App\.jsx$/, reason: 'client composition root changed' },{ re: /^server\/lib\/(?:index|schemaVersions|validation)\.js$/, reason: 'shared server contract changed' },{ re: /^scripts\/ci-test-plan(?:\.test)?\.js$/, reason: 'CI impact planner changed' },- { re: /^scripts\/run-ci-(?:lint|tests)\.js$/, reason: 'CI runner changed' },+ { re: /^scripts\/run-ci-(?:lint|tests)(?:\.test)?\.js$/, reason: 'CI runner changed' },+];++// Files whose Windows behavior is not faithfully exercised by pinPlatform()+// stubs on Linux: real .cmd spawn, PowerShell BOM, PTY wrap, path.basename+// on backslashes. A PR that does not touch these still gets a full Windows+// run on main / nightly / release.+const WINDOWS_RISK_RULES = [+ /\.(?:ps1|cmd|bat)$/i,+ /^scripts\/fix-windows-console(?:\.test)?\.js$/,+ /^scripts\/ps1-bom\.test\.js$/,+ /^server\/lib\/(?:bufferedSpawn|detachedSpawn|childProcess|bashResolver|processEnv|platform|spawnCwd|cliProviderRun|grok)\b/,+ /^server\/lib\/agentGuard\//,+ /^server\/cos-runner\//,+ /^server\/services\/(?:shell|pm2|appBuilder)\b/,+ /^server\/services\/autonomousJobs\/execution\.shellSpawn/,+ /^server\/routes\/apps\//,+ /^server\/routes\/scaffoldVite\.js$/,];// Contract guards that run on EVERY plan, whatever the impact scope selects.@@ -205,6 +222,8 @@ export function buildCiTestPlan(changedFiles, { trackedFiles = [], forceFull = flint: { mode: 'full', files: [] },build: true,smoke: true,+ windows: true,+ serverNative: true,};}@@ -232,6 +251,8 @@ export function buildCiTestPlan(changedFiles, { trackedFiles = [], forceFull = flint: { mode: 'skip', files: [] },build: false,smoke: false,+ windows: false,+ serverNative: false,};}@@ -310,9 +331,17 @@ export function buildCiTestPlan(changedFiles, { trackedFiles = [], forceFull = f},build: hasClientSource,smoke: hasServerSource,+ windows: executable.some((path) => WINDOWS_RISK_RULES.some((rule) => rule.test(path))),+ 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,@@ -324,6 +353,8 @@ function fullPlan(changedFiles, reason) {lint: { mode: 'full', files: [] },build: true,smoke: true,+ windows: true,+ serverNative: true,};}@@ -351,6 +382,8 @@ export function emitGitHubPlan(plan) {lint_files: JSON.stringify(plan.lint.files),build: plan.build,smoke: plan.smoke,+ windows: plan.windows,+ server_native: plan.serverNative,};Object.entries(outputs).forEach(([name, value]) => writeOutput(name, value));diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.jsindex 2a11396a7a..37878539cd 100644--- a/scripts/ci-test-plan.test.js+++ b/scripts/ci-test-plan.test.js@@ -40,6 +40,8 @@ describe('CI test impact planner', () => {lint: { mode: 'skip' },build: false,smoke: false,+ windows: false,+ serverNative: false,});});@@ -89,6 +91,7 @@ describe('CI test impact planner', () => {'client/biome.jsonc','client/lint-no-random-uuid.grit','client/lint-react-legacy-apis.grit',+ 'scripts/run-ci-tests.test.js',]) {const plan = buildCiTestPlan([path], { trackedFiles: TRACKED });expect(plan.full, path).toBe(true);@@ -270,6 +273,28 @@ describe('CI test impact planner', () => {lint: { mode: 'full' },build: true,smoke: true,+ windows: true,+ serverNative: true,});});++ it('skips Windows unless a Windows-sensitive surface changed', () => {+ const sprites = buildCiTestPlan([+ 'server/services/sprites/atlas.js',+ ], { trackedFiles: TRACKED });+ expect(sprites.windows).toBe(false);+ expect(sprites.serverNative).toBe(true);++ const spawn = buildCiTestPlan([+ 'server/lib/bufferedSpawn.js',+ ], { trackedFiles: TRACKED });+ expect(spawn.full).toBe(false);+ expect(spawn.windows).toBe(true);++ const winHelper = buildCiTestPlan([+ 'scripts/fix-windows-console.js',+ ], { trackedFiles: TRACKED });+ expect(winHelper.full).toBe(false);+ expect(winHelper.windows).toBe(true);+ });});diff --git a/scripts/lib/setupDbChoice.js b/scripts/lib/setupDbChoice.jsnew file mode 100644index 0000000000..6e888677a9--- /dev/null+++ b/scripts/lib/setupDbChoice.js@@ -0,0 +1,24 @@+/**+ * Pure setup-db helpers. setup-db.js is a CLI entrypoint that runs on import,+ * so the menu/port resolvers live here and are imported by both the script and+ * its tests.+ */++/** Tolerate whitespace / junk in a .env port; fall back rather than leaking NaN. */+export function parsePort(value, fallback) {+ const parsed = Number.parseInt(String(value).trim(), 10);+ return Number.isFinite(parsed) ? parsed : fallback;+}++export function parseNativePort(value) {+ return parsePort(value, 5432);+}++export function parseDockerPort(value) {+ return parsePort(value, 5561);+}++/** Menu choice 2 = native Postgres; anything else (incl. 1 / empty) = docker. */+export function resolveStorageMenuChoice(answer) {+ return String(answer).trim() === '2' ? 'native' : 'exit';+}diff --git a/scripts/run-ci-tests.js b/scripts/run-ci-tests.jsindex e95fbd4224..f9159c8675 100644--- a/scripts/run-ci-tests.js+++ b/scripts/run-ci-tests.js@@ -1,47 +1,65 @@#!/usr/bin/env nodeimport { spawnSync } from 'child_process';+import { dirname, join, resolve } from 'path';+import { fileURLToPath } from 'url';import { prepareCliSpawn } from '../server/lib/bufferedSpawn.js';+import { ALWAYS_RUN_TESTS } from './ci-test-plan.js';-const scope = process.argv[2];-if (!['server', 'client'].includes(scope)) {- console.error('Usage: node scripts/run-ci-tests.js <server|client>');- process.exit(2);+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..');++export function parseVitestListOutput(stdout) {+ const files = [];+ const seen = new Set();+ for (const line of String(stdout || '').split('\n')) {+ const trimmed = line.trim();+ const sep = trimmed.indexOf(' > ');+ if (sep <= 0) continue;+ const file = trimmed.slice(0, sep);+ // vitest list prints `path > suite > test`. Skip log lines that happen+ // to contain the same separator but are not a file path.+ if (file.includes(' ')) continue;+ if (seen.has(file)) continue;+ seen.add(file);+ files.push(file);+ }+ return files;}-const mode = process.env.CI_TEST_MODE || 'full';-const baseSha = process.env.CI_BASE_SHA;-const repoFiles = JSON.parse(process.env.CI_TEST_FILES || '[]');+export function canonicalizeRunnerPath(path) {+ if (path.startsWith('../')) return path;+ return `./${String(path).replace(/^\.\//, '')}`;+}-const toRunnerPath = (path) => {+export function unionSelectors(selectedFiles, relatedFiles) {+ const seen = new Set();+ const out = [];+ for (const file of [...relatedFiles, ...selectedFiles]) {+ const canonical = canonicalizeRunnerPath(file);+ if (seen.has(canonical)) continue;+ seen.add(canonical);+ out.push(canonical);+ }+ return out;+}++export function shouldSkipRelatedList(mode, repoFiles) {+ // Docs-only / always-run plans already name the exact files. Walking+ // Vitest's import graph against a markdown diff just burns 15–30s.+ return mode === 'files'+ && repoFiles.length > 0+ && repoFiles.every((path) => ALWAYS_RUN_TESTS.includes(path));+}++export function toRunnerPath(scope, path) {// Prefix in-root selectors so a contributor-controlled filename beginning// with "-" cannot be interpreted as another Vitest CLI option.if (scope === 'client') return `./${path.replace(/^client\//, '')}`;if (path.startsWith('server/')) return `./${path.replace(/^server\//, '')}`;return `../${path}`;-};--const selectedFiles = repoFiles.map(toRunnerPath);-const relatedArgs = [];-if (mode === 'files') {- // Exact file selectors are passed as an argv array below.-} else if (mode === 'related') {- if (!baseSha) {- console.error('CI_BASE_SHA is required for related-test mode.');- process.exit(2);- }- relatedArgs.push('--changed', baseSha);-} else if (mode !== 'full') {- console.error(`Unsupported CI test mode: ${mode}`);- process.exit(2);}-if (mode === 'files' && selectedFiles.length === 0) {- console.log(`No ${scope} tests selected.`);- process.exit(0);-}--const run = (extraArgs, label) => {+function spawnNpm(scope, extraArgs, label) {const args = ['run', 'test:ci', '--prefix', scope];if (extraArgs.length > 0) args.push('--', ...extraArgs);console.log(`Running ${scope} ${label}${extraArgs.length ? ` (${extraArgs.length} selector argument(s))` : ''}.`);@@ -52,34 +70,98 @@ const run = (extraArgs, label) => {const result = spawnSync(command, spawnArgs, {stdio: 'inherit',env: process.env,+ cwd: repoRoot,});if (result.error) {console.error(result.error.message);return 1;}return result.status ?? 1;-};+}-if (mode === 'full') {- process.exit(run([], 'full suite'));+export function listRelatedCwd(scope) {+ // `npm exec --prefix server` still inherits this process cwd, and Vitest+ // resolves its config + --changed graph from cwd — so listing from the+ // repo root would miss server/vitest.config.js and silently drop related+ // tests. Run the list from the workspace that owns the runner.+ return join(repoRoot, scope);}-if (mode === 'files') {- // Feature-name matching catches cross-surface tests that do not import the- // changed module directly. Vitest's graph catches differently named direct- // dependants. Run both sets so targeted CI takes their conservative union.- if (baseSha) {- const relatedStatus = run(['--changed', baseSha], 'related tests');- if (relatedStatus !== 0) process.exit(relatedStatus);++function listRelatedFiles(scope, baseSha) {+ const { command, args } = prepareCliSpawn('npm', [+ 'exec', '--',+ 'vitest', 'list', '--changed', baseSha, '--silent',+ ]);+ const result = spawnSync(command, args, {+ encoding: 'utf8',+ env: process.env,+ cwd: listRelatedCwd(scope),+ });+ if (result.error || result.status !== 0) {+ const detail = result.error?.message || result.stderr || `exit ${result.status}`;+ console.warn(`⚠️ Could not list related ${scope} tests (${detail}). Falling back.`);+ return null;}- process.exit(run(selectedFiles, 'feature tests'));+ return parseVitestListOutput(result.stdout);}-const relatedStatus = run(relatedArgs, 'related tests');-if (relatedStatus !== 0) process.exit(relatedStatus);+function main() {+ const scope = process.argv[2];+ if (!['server', 'client'].includes(scope)) {+ console.error('Usage: node scripts/run-ci-tests.js <server|client>');+ process.exit(2);+ }++ const mode = process.env.CI_TEST_MODE || 'full';+ const baseSha = process.env.CI_BASE_SHA;+ const repoFiles = JSON.parse(process.env.CI_TEST_FILES || '[]');+ const selectedFiles = repoFiles.map((path) => toRunnerPath(scope, path));++ if (!['full', 'files', 'related'].includes(mode)) {+ console.error(`Unsupported CI test mode: ${mode}`);+ process.exit(2);+ }++ if (mode === 'related' && !baseSha) {+ console.error('CI_BASE_SHA is required for related-test mode.');+ process.exit(2);+ }++ if (mode === 'full') {+ process.exit(spawnNpm(scope, [], 'full suite'));+ }-// Source-scanning structural tests are invisible to Vitest's import graph.-// Run the planner's explicit guard list as a second small pass.-if (selectedFiles.length > 0) {- process.exit(run(selectedFiles, 'explicit structural tests'));+ if (mode === 'files' && selectedFiles.length === 0) {+ console.log(`No ${scope} tests selected.`);+ process.exit(0);+ }++ // One Vitest process for the union of planner files + import-graph related+ // tests. `--changed` ANDs with path selectors, so they cannot share argv —+ // list the related set, then run the union once.+ let relatedFiles = [];+ if (baseSha && !shouldSkipRelatedList(mode, repoFiles)) {+ const listed = listRelatedFiles(scope, baseSha);+ if (listed) {+ relatedFiles = listed;+ } else if (mode === 'related') {+ const relatedStatus = spawnNpm(scope, ['--changed', baseSha], 'related tests');+ if (relatedStatus !== 0) process.exit(relatedStatus);+ process.exit(selectedFiles.length ? spawnNpm(scope, selectedFiles, 'explicit structural tests') : 0);+ }+ } else if (mode === 'related') {+ process.exit(spawnNpm(scope, ['--changed', baseSha], 'related tests'));+ }++ const union = unionSelectors(selectedFiles, relatedFiles);+ if (union.length === 0) {+ console.log(`No ${scope} tests selected.`);+ process.exit(0);+ }+ process.exit(spawnNpm(scope, union, 'selected tests'));}-process.exit(0);++const isMain = process.argv[1]+ && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url));++if (isMain) main();diff --git a/scripts/run-ci-tests.test.js b/scripts/run-ci-tests.test.jsnew file mode 100644index 0000000000..9c59709551--- /dev/null+++ b/scripts/run-ci-tests.test.js@@ -0,0 +1,90 @@+import { describe, expect, it } from 'vitest';++import {+ listRelatedCwd,+ parseVitestListOutput,+ shouldSkipRelatedList,+ toRunnerPath,+ unionSelectors,+} from './run-ci-tests.js';++describe('parseVitestListOutput', () => {+ it('collects unique file paths from vitest list lines', () => {+ const stdout = [+ 'lib/ports.test.js > PORTS > mirrors every fixed port',+ 'lib/ports.test.js > resolvePostgresPort > returns the native port',+ 'services/auth.test.js > login > rejects a blank password',+ '',+ 'vite v6.0.0 building for test...',+ ].join('\n');++ expect(parseVitestListOutput(stdout)).toEqual([+ 'lib/ports.test.js',+ 'services/auth.test.js',+ ]);+ });++ it('ignores log lines that are not a file > suite > test row', () => {+ expect(parseVitestListOutput('Running server related tests (2 selector argument(s)).')).toEqual([]);+ });+});++describe('unionSelectors', () => {+ it('dedupes planner files against the related-test list under one ./ prefix', () => {+ expect(unionSelectors(+ ['./services/sprites/atlas.test.js', './lib/index.test.js'],+ ['services/sprites/atlas.test.js', './services/sprites/atlas.test.js'],+ )).toEqual([+ './services/sprites/atlas.test.js',+ './lib/index.test.js',+ ]);+ });++ it('keeps out-of-workspace scripts paths as ../…', () => {+ expect(unionSelectors(+ ['../scripts/changelogFragments.test.js'],+ ['lib/ports.test.js'],+ )).toEqual([+ './lib/ports.test.js',+ '../scripts/changelogFragments.test.js',+ ]);+ });+});++describe('shouldSkipRelatedList', () => {+ it('skips the import-graph walk for always-run-only plans', () => {+ expect(shouldSkipRelatedList('files', [+ 'server/services/taskPromptDefaults.test.js',+ 'scripts/changelogFragments.test.js',+ ])).toBe(true);+ });++ it('still walks the graph when a real feature test is selected', () => {+ expect(shouldSkipRelatedList('files', [+ 'server/services/sprites/atlas.test.js',+ 'server/services/taskPromptDefaults.test.js',+ ])).toBe(false);+ });++ it('never skips related mode — that mode is the graph walk', () => {+ expect(shouldSkipRelatedList('related', [+ 'server/services/taskPromptDefaults.test.js',+ ])).toBe(false);+ });+});++describe('listRelatedCwd', () => {+ it('lists from the workspace that owns the Vitest config, not the repo root', () => {+ expect(listRelatedCwd('server')).toMatch(/[/\\]server$/);+ expect(listRelatedCwd('client')).toMatch(/[/\\]client$/);+ expect(listRelatedCwd('server')).not.toMatch(/[/\\]server[/\\]server$/);+ });+});++describe('toRunnerPath', () => {+ it('maps repo paths onto each workspace runner root', () => {+ expect(toRunnerPath('client', 'client/src/lib/index.test.js')).toBe('./src/lib/index.test.js');+ expect(toRunnerPath('server', 'server/lib/index.test.js')).toBe('./lib/index.test.js');+ expect(toRunnerPath('server', 'scripts/changelogFragments.test.js')).toBe('../scripts/changelogFragments.test.js');+ });+});diff --git a/scripts/setup-db.js b/scripts/setup-db.jsindex ea5614928a..135c00414e 100644--- a/scripts/setup-db.js+++ b/scripts/setup-db.js@@ -14,6 +14,7 @@ import { createInterface } from 'readline';import { dirname, join } from 'path';import { fileURLToPath } from 'url';import { parseEnvFile, upsertEnvKey } from './lib/envFile.js';+import { parseDockerPort, parseNativePort, resolveStorageMenuChoice } from './lib/setupDbChoice.js';import { resolveBashBinary } from '../server/lib/bashResolver.js';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -24,26 +25,14 @@ const envFile = parseEnvFile(join(rootDir, '.env'));// user who sets PGPASSWORD in .env (without exporting it into the shell) is// respected the same way getMode() respects PGMODE in .env.const envVar = (key, fallback) => process.env[key] ?? envFile[key] ?? fallback;-// Tolerate accidental whitespace / inline comments / non-numeric junk in-// .env values — fall back to the canonical native port (5432) on anything-// that doesn't parse to a finite integer, instead of letting NaN flow into-// `psql -p` and the success log.-const parsePgPort = (value) => {- const parsed = Number.parseInt(String(value).trim(), 10);- return Number.isFinite(parsed) ? parsed : 5432;-};const PG_USER = envVar('PGUSER', 'portos');const PG_DATABASE = envVar('PGDATABASE', 'portos');const PG_PASSWORD = envVar('PGPASSWORD', 'portos');-const PG_PORT_NATIVE = parsePgPort(envVar('PGPORT', 5432));+const PG_PORT_NATIVE = parseNativePort(envVar('PGPORT', 5432));// Docker host-port mapping (docker-compose.yml maps `${PGPORT_DOCKER:-5561}:5432`).// Resolve it the same tolerant way so the "ready on port N" log can't lie when a// user overrides PGPORT_DOCKER — a misleading success port is exactly the kind of// "looks fine but points at the wrong place" footgun this script exists to avoid.-const parseDockerPort = (value) => {- const parsed = Number.parseInt(String(value).trim(), 10);- return Number.isFinite(parsed) ? parsed : 5561;-};const PG_PORT_DOCKER = parseDockerPort(envVar('PGPORT_DOCKER', 5561));// Environment to pass to `db.sh` and other psql-wrapping subprocesses, so@@ -250,9 +239,7 @@ function promptStorageChoice(message, hint) {const rl = createInterface({ input: process.stdin, output: process.stdout });rl.question(' Enter choice [1/2]: ', (answer) => {rl.close();- const trimmed = answer.trim();- if (trimmed === '2') resolve('native');- else resolve('exit'); // 1 or default = they want docker, so exit to install it+ resolve(resolveStorageMenuChoice(answer));});});}diff --git a/scripts/setup-db.test.js b/scripts/setup-db.test.jsindex a9da4aa829..5fb065d32c 100644--- a/scripts/setup-db.test.js+++ b/scripts/setup-db.test.js@@ -2,57 +2,37 @@ import { describe, it, expect } from 'vitest';import { readFileSync } from 'fs';import { dirname, join } from 'path';import { fileURLToPath } from 'url';+import {+ parseDockerPort,+ parseNativePort,+ resolveStorageMenuChoice,+} from './lib/setupDbChoice.js';-// setup-db.js executes top-level setup logic on import (it's a CLI entrypoint),-// so we can't import it without running the whole flow. Following the repo-// convention for pure-logic coverage, we copy the menu-choice resolver inline-// and assert its post-Phase-1 contract: only Docker (1) and Native (2) are-// offered — file (the deprecated "3") is no longer a normal menu choice.-//-// Keep this in sync with promptStorageChoice() in setup-db.js.-function resolveMenuChoice(answer) {- const trimmed = String(answer).trim();- if (trimmed === '2') return 'native';- return 'exit'; // 1 or default = they want docker, so exit to install it-}--// Keep in sync with parseDockerPort() in setup-db.js. The "ready on port N" log-// must reflect the configured PGPORT_DOCKER, not a hardcoded 5561, and tolerate-// whitespace / junk by falling back to the canonical docker port.-function parseDockerPort(value) {- const parsed = Number.parseInt(String(value).trim(), 10);- return Number.isFinite(parsed) ? parsed : 5561;-}+const here = dirname(fileURLToPath(import.meta.url));+const setupDbSrc = readFileSync(join(here, 'setup-db.js'), 'utf8');describe('setup-db menu choice resolver (Phase 1: Postgres mandatory)', () => {it('maps "2" to native', () => {- expect(resolveMenuChoice('2')).toBe('native');+ expect(resolveStorageMenuChoice('2')).toBe('native');+ expect(resolveStorageMenuChoice(' 2 ')).toBe('native');});it('maps "1" (and default/empty) to docker exit', () => {- expect(resolveMenuChoice('1')).toBe('exit');- expect(resolveMenuChoice('')).toBe('exit');- expect(resolveMenuChoice(' ')).toBe('exit');+ expect(resolveStorageMenuChoice('1')).toBe('exit');+ expect(resolveStorageMenuChoice('')).toBe('exit');+ expect(resolveStorageMenuChoice(' ')).toBe('exit');});it('no longer offers file storage as a numbered choice — "3" is not "file"', () => {- expect(resolveMenuChoice('3')).not.toBe('file');- // Any out-of-range answer falls through to the docker-install path.- expect(resolveMenuChoice('3')).toBe('exit');- expect(resolveMenuChoice('file')).toBe('exit');+ expect(resolveStorageMenuChoice('3')).not.toBe('file');+ expect(resolveStorageMenuChoice('3')).toBe('exit');+ expect(resolveStorageMenuChoice('file')).toBe('exit');});- // Guard against drift: setup-db.js runs its CLI flow on import so we can't- // import promptStorageChoice directly. Instead assert the real source still- // matches the inline copy's contract — the [1/2] prompt is present and no- // numbered "file" branch was re-added. If promptStorageChoice changes, this- // forces the copy above to be updated in lockstep.- it('real setup-db.js source matches the inline resolver contract', () => {- const here = dirname(fileURLToPath(import.meta.url));- const src = readFileSync(join(here, 'setup-db.js'), 'utf8');- expect(src).toContain("Enter choice [1/2]:");- expect(src).toContain("if (trimmed === '2') resolve('native');");- expect(src).not.toMatch(/resolve\('file'\)/);+ it('setup-db.js prompts [1/2] and never resolves "file"', () => {+ expect(setupDbSrc).toContain('Enter choice [1/2]:');+ expect(setupDbSrc).toContain('resolveStorageMenuChoice');+ expect(setupDbSrc).not.toMatch(/resolve\('file'\)/);});});@@ -68,11 +48,13 @@ describe('setup-db docker-port resolver (success log accuracy)', () => {expect(parseDockerPort(' 6000 ')).toBe(6000);});- it('real setup-db.js no longer hardcodes 5561 in the docker success log', () => {- const here = dirname(fileURLToPath(import.meta.url));- const src = readFileSync(join(here, 'setup-db.js'), 'utf8');- // The success log must interpolate the resolved port, not a literal.- expect(src).toContain('PostgreSQL ready on port ${PG_PORT_DOCKER}');- expect(src).not.toContain("'✅ PostgreSQL ready on port 5561'");+ it('native port falls back to 5432 the same way', () => {+ expect(parseNativePort(undefined)).toBe(5432);+ expect(parseNativePort(' 5433 ')).toBe(5433);+ });++ it('setup-db.js interpolates the resolved docker port, not a hardcoded 5561', () => {+ expect(setupDbSrc).toContain('PostgreSQL ready on port ${PG_PORT_DOCKER}');+ expect(setupDbSrc).not.toContain("'✅ PostgreSQL ready on port 5561'");});});diff --git a/server/cos-runner/allowedCommands.test.js b/server/cos-runner/allowedCommands.test.jsindex 7c9c2d11c5..c5ed82c8a8 100644--- a/server/cos-runner/allowedCommands.test.js+++ b/server/cos-runner/allowedCommands.test.js@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';import { readFileSync } from 'fs';import { dirname, join } from 'path';import { fileURLToPath } from 'url';-import { isAllowedCommand, ALLOWED_COMMANDS } from './allowedCommands.js';+import { isAllowedCommand } from './allowedCommands.js';const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');@@ -15,12 +15,6 @@ function shippedProviderCommands(relativePath) {}describe('isAllowedCommand', () => {- describe('permitted plain names', () => {- it.each([...ALLOWED_COMMANDS])('allows "%s" by exact name', (name) => {- expect(isAllowedCommand(name)).toBe(true);- });- });-describe('permitted commands via full absolute path', () => {it('allows /usr/bin/claude', () => {expect(isAllowedCommand('/usr/bin/claude')).toBe(true);diff --git a/server/lib/README.md b/server/lib/README.mdindex a249ed5299..2f62960108 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -381,4 +381,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `mirrorParity.js` | Source-comparison primitives for the `*.mirror.test.js` server↔client parity tests: `stripCommentsAndNormalize` (so per-side commentary may diverge but logic may not), `extractDeclaration(src, name)` (balanced `{}`/`()`/`[]` walk over `function` / `async function` / `const`), and `compareDeclaration(serverSrc, clientSrc, name)`. Use these instead of hand-rolling a brace-walker per mirror. Pure — no `vitest` import — so callers own the assertions. || `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir` and no-peer record creation guards. || `settingsTestUtil.js` | `bindSettingsFile(dataRoot)` → `writeSettingsFile`/`mergeSettingsFile`: direct settings.json disk writes that also drop the `getSettings()` read cache (dynamic-import reset) so a stale cache can't survive a bypass-`save()` write. |-| `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks read via `.text()`), `startLoopbackServer(app)`/`closeLoopbackServer(server)`/`waitForAbort(signal)` for tests that need a real socket (raw disconnects, SSE streaming) that `request()`'s run-to-completion fetch harness can't model, plus the source-scan pair `collectServerSources()` / `readServerSource(rel)` (and `SERVER_DIR`) used by the whole-tree guard suites — `spawnCwd.test.js` (#3193) and `cliChildEnv.test.js` (#3194). Those guards overlap deliberately, so they share one definition of "a source file"; change the ignore rules here and both move together. Cross-platform trio: `posixPath(v)` normalizes a RECEIVED path before comparing it to a POSIX-spelled literal (no-op on POSIX — never normalize the expectation, which would hide a genuinely wrong path), and `resolveTestPython()` returns an interpreter that actually runs, probing by execution because Windows ships a `python` Store-alias stub that exists but fails; `null` when there is none, for `describe.skipIf`; `pinPlatform(value)` pins `process.platform` and returns a restore that reinstates the ORIGINAL descriptor (deleting the pin when there was none) — it carries the one hazard every hand-rolled pin had to rediscover: never pin above an import that loads a native addon, which picks its prebuilt binary off the platform at load time (#4085). |+| `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks with `.text()`, `.json()`, and a `headers.get` content-type), `startLoopbackServer(app)`/`closeLoopbackServer(server)`/`waitForAbort(signal)` for tests that need a real socket (raw disconnects, SSE streaming) that `request()`'s run-to-completion fetch harness can't model, plus the source-scan pair `collectServerSources()` / `readServerSource(rel)` (and `SERVER_DIR`) used by the whole-tree guard suites — `spawnCwd.test.js` (#3193) and `cliChildEnv.test.js` (#3194). Those guards overlap deliberately, so they share one definition of "a source file"; change the ignore rules here and both move together. Cross-platform trio: `posixPath(v)` normalizes a RECEIVED path before comparing it to a POSIX-spelled literal (no-op on POSIX — never normalize the expectation, which would hide a genuinely wrong path), and `resolveTestPython()` returns an interpreter that actually runs, probing by execution because Windows ships a `python` Store-alias stub that exists but fails; `null` when there is none, for `describe.skipIf`; `pinPlatform(value)` pins `process.platform` and returns a restore that reinstates the ORIGINAL descriptor (deleting the pin when there was none) — it carries the one hazard every hand-rolled pin had to rediscover: never pin above an import that loads a native addon, which picks its prebuilt binary off the platform at load time (#4085). |diff --git a/server/lib/httpClient.test.js b/server/lib/httpClient.test.jsindex 2d6256d044..84679fc60b 100644--- a/server/lib/httpClient.test.js+++ b/server/lib/httpClient.test.js@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest'import { createHttpClient } from './httpClient.js'+import { mockJsonResponse, mockTextResponse } from './testHelper.js'// Mock global fetchconst mockFetch = vi.fn()@@ -10,25 +11,14 @@ describe('httpClient', () => {vi.clearAllMocks()})- function mockJsonResponse(data, status = 200) {- return {- ok: status >= 200 && status < 300,- status,- headers: { get: (name) => name.toLowerCase() === 'content-type' ? 'application/json' : null },- json: () => Promise.resolve(data),- text: () => Promise.resolve(JSON.stringify(data))- }- }-- function mockTextResponse(text, status = 200) {- return {- ok: status >= 200 && status < 300,- status,- headers: { get: () => 'text/plain' },- json: () => Promise.resolve(text),- text: () => Promise.resolve(text)- }- }+ const json = (data, status = 200) => mockJsonResponse(data, {+ ok: status >= 200 && status < 300,+ status,+ })+ const text = (body, status = 200) => mockTextResponse(body, {+ ok: status >= 200 && status < 300,+ status,+ })describe('createHttpClient', () => {it('should return an object with get, post, put, delete methods', () => {@@ -42,7 +32,7 @@ describe('httpClient', () => {describe('GET requests', () => {it('should make a GET request with baseURL', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse({ ok: true }))+ mockFetch.mockResolvedValueOnce(json({ ok: true }))const client = createHttpClient({ baseURL: 'http://localhost:3000' })const result = await client.get('/api/test')@@ -56,7 +46,7 @@ describe('httpClient', () => {})it('should append query params', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse([]))+ mockFetch.mockResolvedValueOnce(json([]))const client = createHttpClient({ baseURL: 'http://localhost:3000' })await client.get('/items', { params: { page: 1, limit: 10 } })@@ -67,7 +57,7 @@ describe('httpClient', () => {})it('should filter out null/undefined params', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse([]))+ mockFetch.mockResolvedValueOnce(json([]))const client = createHttpClient({ baseURL: 'http://localhost:3000' })await client.get('/items', { params: { page: 1, filter: null, sort: undefined } })@@ -79,7 +69,7 @@ describe('httpClient', () => {})it('should include default headers', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse({}))+ mockFetch.mockResolvedValueOnce(json({}))const client = createHttpClient({baseURL: 'http://localhost:3000',headers: { 'Authorization': 'Bearer token123' }@@ -92,7 +82,7 @@ describe('httpClient', () => {})it('should merge extra headers with default headers', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse({}))+ mockFetch.mockResolvedValueOnce(json({}))const client = createHttpClient({baseURL: 'http://localhost:3000',headers: { 'Authorization': 'Bearer token123' }@@ -106,7 +96,7 @@ describe('httpClient', () => {})it('should handle text responses', async () => {- mockFetch.mockResolvedValueOnce(mockTextResponse('Hello World'))+ mockFetch.mockResolvedValueOnce(text('Hello World'))const client = createHttpClient()const result = await client.get('/text')@@ -116,7 +106,7 @@ describe('httpClient', () => {describe('POST requests', () => {it('should send JSON body', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse({ id: 1 }, 201))+ mockFetch.mockResolvedValueOnce(json({ id: 1 }, 201))const client = createHttpClient({ baseURL: 'http://localhost:3000' })const result = await client.post('/items', { name: 'test' })@@ -128,7 +118,7 @@ describe('httpClient', () => {})it('should not override existing Content-Type header', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse({}))+ mockFetch.mockResolvedValueOnce(json({}))const client = createHttpClient({headers: { 'Content-Type': 'application/xml' }})@@ -140,7 +130,7 @@ describe('httpClient', () => {})it('should not set Content-Type when no data provided', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse({}))+ mockFetch.mockResolvedValueOnce(json({}))const client = createHttpClient()await client.post('/items')@@ -152,7 +142,7 @@ describe('httpClient', () => {describe('PUT requests', () => {it('should make PUT request with body', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse({ updated: true }))+ mockFetch.mockResolvedValueOnce(json({ updated: true }))const client = createHttpClient({ baseURL: 'http://localhost:3000' })const result = await client.put('/items/1', { name: 'updated' })@@ -166,7 +156,7 @@ describe('httpClient', () => {describe('DELETE requests', () => {it('should make DELETE request', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse({ deleted: true }))+ mockFetch.mockResolvedValueOnce(json({ deleted: true }))const client = createHttpClient({ baseURL: 'http://localhost:3000' })const result = await client.delete('/items/1')@@ -179,14 +169,14 @@ describe('httpClient', () => {describe('error handling', () => {it('should throw on non-ok response', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse({ error: 'Not found' }, 404))+ mockFetch.mockResolvedValueOnce(json({ error: 'Not found' }, 404))const client = createHttpClient()await expect(client.get('/missing')).rejects.toThrow('HTTP 404')})it('should include status and response data on error', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse({ error: 'Forbidden' }, 403))+ mockFetch.mockResolvedValueOnce(json({ error: 'Forbidden' }, 403))const client = createHttpClient()try {@@ -200,7 +190,7 @@ describe('httpClient', () => {})it('should throw on 500 server error', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse({ error: 'Internal error' }, 500))+ mockFetch.mockResolvedValueOnce(json({ error: 'Internal error' }, 500))const client = createHttpClient()await expect(client.get('/error')).rejects.toThrow('HTTP 500')@@ -209,7 +199,7 @@ describe('httpClient', () => {describe('no baseURL', () => {it('should work without baseURL', async () => {- mockFetch.mockResolvedValueOnce(mockJsonResponse({ ok: true }))+ mockFetch.mockResolvedValueOnce(json({ ok: true }))const client = createHttpClient()await client.get('/api/test')diff --git a/server/lib/index.test.js b/server/lib/index.test.jsindex 2af2520568..1e990f3143 100644--- a/server/lib/index.test.js+++ b/server/lib/index.test.js@@ -18,22 +18,11 @@ const sourceFiles = readdirSync(HERE)// a README row. Both halves keep the discovery contract in CLAUDE.md honest.describe('server/lib/ barrel', () => {- it('resolves every re-export', () => {- expect(Object.keys(barrel).length).toBeGreaterThan(0);- });-- it('exposes a representative sample of helpers', () => {- expect(typeof barrel.tryReadFile).toBe('function');- expect(typeof barrel.atomicWrite).toBe('function');- expect(typeof barrel.optionalBooleanMap).toBe('function');- expect(typeof barrel.flattenCanonDescriptorFragments).toBe('function');- expect(typeof barrel.mapCanonDescriptorFragments).toBe('function');- expect(typeof barrel.descriptorForCanonEntry).toBe('function');- expect(typeof barrel.ServerError).toBe('function');- expect(typeof barrel.v4).toBe('function');- });-it('re-exports every non-test .js file from index.js', () => {+ // The `import * as barrel` above is the load: a star-export of a missing+ // module throws before this body runs. The length check keeps `barrel` live+ // so an unused-import lint can't delete that load.+ expect(Object.keys(barrel).length).toBeGreaterThan(0);// Forces the maintenance rule: a new server/lib/foo.js must be added to// index.js. Catches a new helper that bypassed the barrel.for (const f of sourceFiles) {diff --git a/server/lib/testHelper.js b/server/lib/testHelper.jsindex 42323d9fdc..6f2e0391a7 100644--- a/server/lib/testHelper.js+++ b/server/lib/testHelper.js@@ -153,9 +153,15 @@ export function request(app) {* @param {*} body - serialized into the response body via JSON.stringify* @param {{ ok?: boolean, status?: number }} [opts]*/-export function mockJsonResponse(body, { ok = true, status = 200 } = {}) {+export function mockJsonResponse(body, { ok = true, status = 200, contentType = 'application/json' } = {}) {const text = JSON.stringify(body);- return { ok, status, text: async () => text };+ return {+ ok,+ status,+ headers: { get: (name) => name.toLowerCase() === 'content-type' ? contentType : null },+ text: async () => text,+ json: async () => body,+ };}/**@@ -168,8 +174,14 @@ export function mockJsonResponse(body, { ok = true, status = 200 } = {}) {* @param {string} [body] - returned verbatim by `text()`* @param {{ ok?: boolean, status?: number }} [opts]*/-export function mockTextResponse(body = '', { ok = true, status = 200 } = {}) {- return { ok, status, text: async () => body };+export function mockTextResponse(body = '', { ok = true, status = 200, contentType = 'text/plain' } = {}) {+ return {+ ok,+ status,+ headers: { get: (name) => name.toLowerCase() === 'content-type' ? contentType : null },+ text: async () => body,+ json: async () => { throw new SyntaxError('Unexpected token in JSON'); },+ };}/**diff --git a/server/process-safety-net.test.js b/server/process-safety-net.test.jsindex 673fc157e3..54dd0d15a8 100644--- a/server/process-safety-net.test.js+++ b/server/process-safety-net.test.js@@ -15,20 +15,6 @@ const read = (rel) => readFileSync(join(__dirname, rel), 'utf8');// server.listen) and rather than by importing the helper and mutating the live// test process's listener set.describe('process-level safety net (#1878)', () => {- it('shared helper registers both unhandledRejection and uncaughtException', () => {- const src = read('lib/errorHandler.js');- expect(src).toMatch(/export function setupProcessErrorHandlers/);- expect(src).toMatch(/process\.on\(\s*['"]unhandledRejection['"]/);- expect(src).toMatch(/process\.on\(\s*['"]uncaughtException['"]/);- });-- it('shared helper normalizes arbitrary (non-Error) rejection reasons', () => {- // Guards against the raw `reason.stack.split()` footgun — non-Error throw- // values must not make the safety-net handler itself throw.- const src = read('lib/errorHandler.js');- expect(src).toMatch(/normalizeError/);- });-// The main server wires the net from its boot sequence (services/bootstrap.js,// extracted from index.js in #2839) inside the httpServer.listen callback.for (const rel of ['services/bootstrap.js', 'cos-runner/index.js']) {@@ -47,7 +33,7 @@ describe('process-level safety net (#1878)', () => {// (`throw null`) has no `.stack`, and a deref there would mask the original and// skip the clean exit/flush. Invoke the actual registered uncaughtException// listener with `null`, with the exit timer stubbed so the test process survives.- it('uncaughtException handler tolerates a non-Error throw value (e.g. null)', () => {+ it('handlers tolerate a non-Error throw / rejection reason (e.g. null)', () => {const setTimeoutSpy = vi.spyOn(global, 'setTimeout').mockImplementation(() => 0);const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});const newListeners = (event, before) =>@@ -59,7 +45,9 @@ describe('process-level safety net (#1878)', () => {const addedRej = newListeners('unhandledRejection', beforeRej);try {expect(addedExc).toHaveLength(1);+ expect(addedRej).toHaveLength(1);expect(() => addedExc[0](null)).not.toThrow();+ expect(() => addedRej[0](null, Promise.resolve())).not.toThrow();} finally {addedExc.forEach((l) => process.removeListener('uncaughtException', l));addedRej.forEach((l) => process.removeListener('unhandledRejection', l));