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
ci: stop rediscovering related tests (#5298)
[._.]/ Adam Eivyd98e98157d98
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 594f3d12c0..8f6e7d5137 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -38,8 +38,10 @@ jobs:reason: ${{ steps.plan.outputs.reason }}server_mode: ${{ steps.plan.outputs.server_mode }}server_files: ${{ steps.plan.outputs.server_files }}+ server_sources: ${{ steps.plan.outputs.server_sources }}client_mode: ${{ steps.plan.outputs.client_mode }}client_files: ${{ steps.plan.outputs.client_files }}+ client_sources: ${{ steps.plan.outputs.client_sources }}db: ${{ steps.plan.outputs.db }}lint_mode: ${{ steps.plan.outputs.lint_mode }}lint_files: ${{ steps.plan.outputs.lint_files }}@@ -48,6 +50,7 @@ jobs:windows: ${{ steps.plan.outputs.windows }}windows_mode: ${{ steps.plan.outputs.windows_mode }}windows_files: ${{ steps.plan.outputs.windows_files }}+ windows_sources: ${{ steps.plan.outputs.windows_sources }}steps:- uses: actions/checkout@v7with:@@ -110,7 +113,7 @@ jobs:- uses: actions/checkout@v7with:# See the impact job: depth 2 is the whole PR merge ref, which is all- # Vitest's `--changed <sha>` three-dot diff reads.+ # the planner needs to identify changed sources.fetch-depth: 2- name: Resolve the pull-request diff base@@ -229,6 +232,13 @@ jobs:env:CI_TEST_MODE: ${{ needs.impact.outputs.server_mode }}CI_TEST_FILES: ${{ needs.impact.outputs.server_files }}+ CI_TEST_SOURCES: ${{ needs.impact.outputs.server_sources }}+ # Keep successful-test output signal-dense. Developers can reproduce+ # locally without this flag when assertion context needs app logs.+ PORTOS_TEST_QUIET: 1+ # The documented local fallback; setting it avoids one warning per+ # isolated test file without changing DB selection or credentials.+ PGPASSWORD: portosrun: node scripts/run-ci-tests.js server# Smoke-boot does not need Postgres: NODE_ENV=test selects the file@@ -247,7 +257,7 @@ jobs:- uses: actions/checkout@v7with:# See the impact job: depth 2 is the whole PR merge ref, which is all- # Vitest's `--changed <sha>` three-dot diff reads.+ # the planner needs to identify changed sources.fetch-depth: 2- name: Resolve the pull-request diff base@@ -286,6 +296,7 @@ jobs:env:CI_TEST_MODE: ${{ needs.impact.outputs.client_mode }}CI_TEST_FILES: ${{ needs.impact.outputs.client_files }}+ CI_TEST_SOURCES: ${{ needs.impact.outputs.client_sources }}run: node scripts/run-ci-tests.js client- name: Build client@@ -433,7 +444,7 @@ jobs:- uses: actions/checkout@v7with:# See the impact job: depth 2 is the whole PR merge ref, which is all- # Vitest's `--changed <sha>` three-dot diff reads.+ # the planner needs to identify changed sources.fetch-depth: 2- name: Resolve the pull-request diff base@@ -536,6 +547,9 @@ jobs:env:CI_TEST_MODE: ${{ needs.impact.outputs.windows_mode }}CI_TEST_FILES: ${{ needs.impact.outputs.windows_files }}+ CI_TEST_SOURCES: ${{ needs.impact.outputs.windows_sources }}+ PORTOS_TEST_QUIET: 1+ PGPASSWORD: portosrun: node scripts/run-ci-tests.js servergate:diff --git a/AGENTS.md b/AGENTS.mdindex 23518496c3..6181632b1d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -21,6 +21,36 @@ cd client && npm test # Vitest (jsdom) — component/unit testsnpm run test:db # DB-backed suites → portos_test ONLY (see Security Model)```+## Test Strategy: Value Over Assertion Count++PortOS tests move **up the stack as behavior stabilizes**. The default new test+is the highest practical public boundary: an Express route, service workflow,+persisted-store adapter, socket exchange, or rendered user interaction. A+boundary test should cover the success path plus the materially different+failure/compatibility paths; it should not enumerate every internal branch just+because the branch exists.++Do not add or retain a unit test merely to raise coverage for a deterministic+helper whose behavior is already exercised through a stable caller. When a+helper's signature and every caller would have to change together, prefer the+caller's integration contract and delete redundant helper-level examples.+Table-driven permutations are still duplication when they all prove the same+product outcome.++Focused unit tests remain valuable for behavior that a higher-level test cannot+pin precisely or cheaply: parsers and algorithms with a real input matrix;+security, privacy, data-isolation, and destructive-action guards; migrations and+cross-version compatibility; serialization/schema boundaries; retry, timeout,+and process-lifecycle state machines; and pure edge cases whose failure would be+ambiguous through an integration test. Real timeout behavior gets one focused+contract test with injected/fake time — never repeated production sleeps.++Before adding a test, name the regression it uniquely catches. During review,+remove tests that duplicate a stronger boundary assertion, mirror implementation+details, only verify mocks called other mocks, or cover impossible states. Test+count and line coverage are diagnostics, not goals; CI time, determinism, and+regression-detection value are the goals.+## Security Model**Trust model (within one install).** Each PortOS install serves exactly one human user, on a private network behind Tailscale VPN, never exposed to the public internet. Within an install there is one server process and one user — so concurrent *request* races, mutex locking on file I/O, and atomic write patterns are unnecessary as defenses against competing actors and should not be added or flagged as concerns. Simple re-entrancy guards (per-account sync locks preventing duplicate in-flight operations; serializing two write paths that mutate the same record) are fine and expected. PortOS intentionally omits CORS restrictions, rate limiting, and full concurrency controls by default — non-issues for a single-user private-network deployment. Do not add them or flag their absence. **"Single-user" means: do not defend against multiple competing humans inside one install. It does NOT mean "assume only one install exists."**diff --git a/client/package.json b/client/package.jsonindex 8a7bef876c..561c41dccc 100644--- a/client/package.json+++ b/client/package.json@@ -15,6 +15,7 @@"preview": "vite preview","test": "vitest run","test:ci": "vitest run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions",+ "test:ci:related": "vitest related --run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions","test:watch": "vitest"},"dependencies": {diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.mdindex c5cd676093..700ae2d653 100644--- a/docs/GITHUB_ACTIONS.md+++ b/docs/GITHUB_ACTIONS.md@@ -32,7 +32,8 @@ A release therefore pays for one full run (on its PR), not three.PRs into `main` use `scripts/ci-test-plan.js` to classify the changed filesbefore installing dependencies. Directory-scoped features run their server andclient feature tests; flat modules fall back to Vitest's import-graph-aware-`--changed` mode. The planner deliberately chooses full CI for shared+`related` mode, fed only the changed behavioral source paths. The planner+deliberately chooses full CI for sharedcomposition roots, test configuration, dependency manifests, workflow changes,unknown artifacts, or wide diffs.@@ -185,11 +186,9 @@ No job clones full history. `actions/checkout` runs at `fetch-depth: 2`,which on a pull request is the merge ref plus both of its parents — and thefirst parent *is* the base-branch commit the pull request is diffed against.`scripts/ci-base-sha.js` reads it (`HEAD^1`) and exports `CI_BASE_SHA` for the-rest of the job, so both three-dot diffs that matter resolve without deeper-history:--- the planner's `git diff <base>...HEAD`;-- Vitest's own `--changed <sha>`, which is also a three-dot diff internally.+rest of the job, so the planner's `git diff <base>...HEAD` resolves without+deeper history. The planner passes the resulting source paths directly to+`vitest related`; Vitest no longer performs its own Git diff.Reading the base off the checkout rather than `github.event.pull_request.base.sha`is also more correct: GitHub rebuilds the merge ref when the base branch moves,@@ -230,10 +229,12 @@ The selected work is split across parallel jobs:mirrors `CI Gate`'s result. This is the check the release workflow looks for;see "Reusing the release PR's CI run" below.-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.+Targeted `files` plans run the planner's exact test files once. `related` plans+run `vitest related` directly against changed behavioral source paths, then run+the cheap structural/repository contracts that cannot be found through imports.+There is no buffered discovery pass: the old `vitest list --changed` path could+spend minutes printing every test name, overflow Node's buffer, discard the+result, and rerun the same graph.No third-party change-filter action is used. The planner passes test paths as aJSON argument array to `spawnSync`, never through shell interpolation.@@ -258,12 +259,14 @@ Changes to CI/test configuration also force the full suite on their own PR.### Impact-planner safety rules- A directory feature such as `server/services/sprites/` selects tests carrying- the same feature segment across server and client, plus every test Vitest's- import graph relates to the changed files.-- Directly changed tests and co-located sibling tests are always included.+ the same feature segment across server and client.+- Flat/shared behavioral modules use Vitest's import graph, driven by their+ exact changed source paths. Directly changed tests are always included.- Barrel/catalog guards are added when reusable `lib`, `hooks`, or `utils`- directories change; JSX changes include the global accessibility convention- guard.+ directories change, and catalog-only barrels are excluded from import-graph+ expansion. JSX changes include the global accessibility convention guard.+- A deleted executable source cannot be handed to `vitest related`, so that+ case fails closed to the complete suite.- Database adapters, DB scripts, and relevant migrations add the completeserial DB suite.- Unmapped executable files use related-test mode. Unclassified artifacts,diff --git a/scripts/ci-base-sha.js b/scripts/ci-base-sha.jsindex c2a0319e25..c8289e1b41 100644--- a/scripts/ci-base-sha.js+++ b/scripts/ci-base-sha.js@@ -12,10 +12,10 @@* `github.event.pull_request.base.sha` twice over:** - It needs no history. `merge-base(HEAD^1, HEAD)` is HEAD^1 by- * construction, so `fetch-depth: 2` is enough for both the impact plan's- * `<base>...HEAD` diff and Vitest's `--changed <sha>` (which also runs a- * three-dot diff internally). Every job used to clone all ~13k commits to- * get the same answer.+ * construction, so `fetch-depth: 2` is enough for the impact plan's+ * `<base>...HEAD` diff. The planner passes those changed source paths to+ * Vitest directly. Every job used to clone all ~13k commits to get the+ * same answer.* - It cannot drift. The payload's `base.sha` is the base tip when the event* fired, and GitHub rebuilds the merge ref when the base branch moves, so* the two can disagree — at which point a three-dot diff attributesdiff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex 1f6b7cb51f..10f65cab63 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -215,18 +215,6 @@ const featureDirectory = (path) => {return null;};-const siblingTestCandidates = (path) => {- const extMatch = path.match(/(\.[cm]?[jt]sx?)$/i);- if (!extMatch || isTestFile(path)) return [];- const stem = path.slice(0, -extMatch[1].length);- return [- `${stem}.test${extMatch[1]}`,- `${stem}.spec${extMatch[1]}`,- `${stem}.test.js`,- `${stem}.test.jsx`,- ];-};-const structuralTestsFor = (changedFiles, trackedSet) => {const selected = [];const add = (path) => {@@ -281,7 +269,19 @@ export const splitByRunner = (paths) => ({});const windowsContractTests = (trackedSet) => WINDOWS_CONTRACT_TESTS.filter((path) => trackedSet.has(path));-const skippedRunner = () => ({ mode: 'skip', files: [] });+const skippedRunner = () => ({ mode: 'skip', files: [], sources: [] });++// Catalog barrels are validated by structural export guards. Feeding one to+// Vitest's import graph selects nearly every consumer even though the barrel+// contains no behavior; PR #5296 changed server/lib/index.js and consequently+// selected 1,244 files / 27,491 tests. Behavioral source files in the same diff+// still drive related-test selection normally.+const isStructuralBarrel = (path) => [+ 'server/lib/index.js',+ 'client/src/lib/index.js',+ 'client/src/hooks/index.js',+ 'client/src/utils/index.js',+].includes(path);/*** Build a conservative PR test plan.@@ -304,8 +304,8 @@ export function buildCiTestPlan(changedFiles, {full: true,reason: forceFullReason,changedFiles: changed,- server: { mode: 'full', files: [] },- client: { mode: 'full', files: [] },+ server: { mode: 'full', files: [], sources: [] },+ client: { mode: 'full', files: [], sources: [] },db: true,lint: { mode: 'full', files: [] },build: true,@@ -313,6 +313,7 @@ export function buildCiTestPlan(changedFiles, {windows: true,windowsMode: 'full',windowsFiles: [],+ windowsSources: [],};}@@ -335,8 +336,8 @@ export function buildCiTestPlan(changedFiles, {full: false,reason: changed.length ? 'documentation-only change' : 'no changed files',changedFiles: changed,- server: alwaysRunServer.length > 0 ? { mode: 'files', files: alwaysRunServer } : skippedRunner(),- client: alwaysRunClient.length > 0 ? { mode: 'files', files: alwaysRunClient } : skippedRunner(),+ server: alwaysRunServer.length > 0 ? { mode: 'files', files: alwaysRunServer, sources: [] } : skippedRunner(),+ client: alwaysRunClient.length > 0 ? { mode: 'files', files: alwaysRunClient, sources: [] } : skippedRunner(),db: false,lint: { mode: 'skip', files: [] },build: false,@@ -344,6 +345,7 @@ export function buildCiTestPlan(changedFiles, {windows: false,windowsMode: 'skip',windowsFiles: [],+ windowsSources: [],};}@@ -367,11 +369,17 @@ export function buildCiTestPlan(changedFiles, {if (unsupportedSources.length > 0) {return fullPlan(changed, `unmapped executable surface: ${unsupportedSources[0]}`);}+ const deletedSources = sourceFiles.filter((path) => !trackedSet.has(path));+ if (deletedSources.length > 0) {+ // `vitest related` needs a real source path. A deleted module can still+ // affect importers, so widening is safer than silently dropping its side of+ // the graph.+ return fullPlan(changed, `deleted executable source: ${deletedSources[0]}`);+ }const features = uniqueSorted(sourceFiles.map(featureDirectory).filter(Boolean));const unscopedSources = sourceFiles.filter((path) => !featureDirectory(path));const selectedTests = [...directTests,- ...sourceFiles.flatMap(siblingTestCandidates).filter((path) => trackedSet.has(path)),...structuralTestsFor(changed, trackedSet),...alwaysRun,];@@ -394,18 +402,34 @@ export function buildCiTestPlan(changedFiles, {const hasUnscopedServer = unscopedSources.some(isServerRunnerFile);const hasUnscopedClient = unscopedSources.some((path) => path.startsWith('client/'));+ const serverSources = sourceFiles+ .filter(isServerRunnerFile)+ .filter((path) => !isStructuralBarrel(path));+ const clientSources = sourceFiles+ .filter((path) => path.startsWith('client/'))+ .filter((path) => !isStructuralBarrel(path));++ // Feature-directory plans already enumerate their boundary tests. Flat and+ // shared modules use Vitest's import graph, except a barrel-only edit whose+ // contract is completely covered by the structural export guard.+ const serverMode = hasUnscopedServer && serverSources.length > 0 ? 'related' : 'files';+ const clientMode = hasUnscopedClient && clientSources.length > 0 ? 'related' : 'files';+const server = serverFiles.length > 0- ? { mode: hasUnscopedServer ? 'related' : 'files', files: serverFiles }+ ? { mode: serverMode, files: serverFiles, sources: serverMode === 'related' ? serverSources : [] }: hasServerSource- ? { mode: 'related', files: [] }+ ? { mode: serverSources.length > 0 ? 'related' : 'files', files: [], sources: serverSources }: skippedRunner();const client = clientFiles.length > 0- ? { mode: hasUnscopedClient ? 'related' : 'files', files: clientFiles }+ ? { mode: clientMode, files: clientFiles, sources: clientMode === 'related' ? clientSources : [] }: hasClientSource- ? { mode: 'related', files: [] }+ ? { mode: clientSources.length > 0 ? 'related' : 'files', files: [], sources: clientSources }: skippedRunner();const windows = executable.some((path) => WINDOWS_RISK_RULES.some((rule) => rule.test(path)));+ const windowsMode = windows+ ? (serverSources.length > 0 ? 'related' : 'files')+ : 'skip';return {full: false,@@ -425,8 +449,9 @@ export function buildCiTestPlan(changedFiles, {build: hasClientSource,smoke: hasServerSource,windows,- windowsMode: windows ? 'related' : 'skip',+ windowsMode,windowsFiles: windows ? windowsContractTests(trackedSet) : [],+ windowsSources: windowsMode === 'related' ? serverSources : [],};}@@ -435,8 +460,8 @@ function fullPlan(changedFiles, reason) {full: true,reason,changedFiles,- server: { mode: 'full', files: [] },- client: { mode: 'full', files: [] },+ server: { mode: 'full', files: [], sources: [] },+ client: { mode: 'full', files: [], sources: [] },db: true,lint: { mode: 'full', files: [] },build: true,@@ -444,6 +469,7 @@ function fullPlan(changedFiles, reason) {windows: true,windowsMode: 'full',windowsFiles: [],+ windowsSources: [],};}@@ -458,8 +484,10 @@ export function emitGitHubPlan(plan) {reason: plan.reason.replace(/[`<>\r\n]+/g, ' '),server_mode: plan.server.mode,server_files: JSON.stringify(plan.server.files),+ server_sources: JSON.stringify(plan.server.sources),client_mode: plan.client.mode,client_files: JSON.stringify(plan.client.files),+ client_sources: JSON.stringify(plan.client.sources),db: plan.db,lint_mode: plan.lint.mode,lint_files: JSON.stringify(plan.lint.files),@@ -468,6 +496,7 @@ export function emitGitHubPlan(plan) {windows: plan.windows,windows_mode: plan.windowsMode,windows_files: JSON.stringify(plan.windowsFiles),+ windows_sources: JSON.stringify(plan.windowsSources),};Object.entries(outputs).forEach(([name, value]) => writeStepOutput(name, value));diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.jsindex 10c86ab68b..1c315d9f64 100644--- a/scripts/ci-test-plan.test.js+++ b/scripts/ci-test-plan.test.js@@ -9,29 +9,41 @@ import {} from './ci-test-plan.js';const TRACKED = [+ 'server/lib/index.js','server/lib/index.test.js',+ 'server/lib/bufferedSpawn.js','server/routes/auth.test.js','server/routes/sprites.test.js',+ 'server/services/auth.js','server/services/auth.test.js',+ 'server/services/catalogDB/facets.js','server/services/catalogDB/facets.db.test.js',+ 'server/services/sprites/animationTracks.js','server/services/sprites/animationTracks.test.js',+ 'server/services/sprites/atlas.js','server/services/sprites/atlas.test.js',+ 'server/services/sprites/atlasGrid.js','server/services/sprites/atlasGrid.test.js',+ 'server/services/sprites/atlasLayout.js','server/services/sprites/atlasLayout.test.js','server/services/taskPromptDefaults.test.js','server/lib/bufferedSpawn.test.js','server/lib/platform.test.js','server/lib/shellCd.test.js',+ 'server/lib/shellCd.js','server/services/agentTuiSpawning.test.js','client/src/a11yConventions.test.js','client/src/hooks/mountedRefConventions.test.js','client/src/components/catalog/CatalogCard.jsx','client/src/components/catalog/CatalogCard.test.jsx','client/src/components/sprites/WalkWorkflow.test.jsx',+ 'client/src/hooks/useAsyncAction.js','client/src/lib/catalogLinks.js','client/src/lib/index.test.js','client/src/services/apiSprites.test.js',+ 'scripts/migrations/210-example.js','scripts/migrations/210-example.test.js',+ 'scripts/fix-windows-console.js',];describe('CI test impact planner', () => {@@ -131,7 +143,7 @@ describe('CI test impact planner', () => {trackedFiles: TRACKED.filter((path) => path !== 'server/services/taskPromptDefaults.test.js'),});- expect(plan.server).toEqual({ mode: 'skip', files: [] });+ expect(plan.server).toEqual({ mode: 'skip', files: [], sources: [] });});it('forces the full suite when CI or shared test configuration changes', () => {@@ -159,11 +171,13 @@ describe('CI test impact planner', () => {}});- it('uses related server coverage, not every CI surface, for a server barrel edit', () => {+ it('uses only the structural contract for a server barrel edit', () => {const plan = buildCiTestPlan(['server/lib/index.js'], { trackedFiles: TRACKED });expect(plan.full).toBe(false);- expect(plan.server.mode).toBe('related');+ expect(plan.server.mode).toBe('files');+ expect(plan.server.sources).toEqual([]);+ expect(plan.server.files).toContain('server/lib/index.test.js');expect(plan.client.mode).toBe('skip');expect(plan.db).toBe(false);expect(plan.windows).toBe(false);@@ -224,7 +238,8 @@ describe('CI test impact planner', () => {expect(plan.full).toBe(false);expect(plan.server).toEqual({mode: 'related',- files: ['server/services/auth.test.js', 'server/services/taskPromptDefaults.test.js'],+ files: ['server/services/taskPromptDefaults.test.js'],+ sources: ['server/services/auth.js'],});expect(plan.client.mode).toBe('skip');expect(plan.smoke).toBe(true);@@ -238,6 +253,10 @@ describe('CI test impact planner', () => {expect(plan.full).toBe(false);expect(plan.client.mode).toBe('related');+ expect(plan.client.sources).toEqual([+ 'client/src/components/catalog/CatalogCard.jsx',+ 'client/src/lib/catalogLinks.js',+ ]);expect(plan.client.files).toContain('client/src/lib/index.test.js');expect(plan.client.files).toContain('client/src/a11yConventions.test.js');expect(plan.client.files).toContain('client/src/hooks/mountedRefConventions.test.js');@@ -282,10 +301,11 @@ describe('CI test impact planner', () => {expect(plan.server).toEqual({mode: 'related',files: ['scripts/migrations/210-example.test.js', 'server/services/taskPromptDefaults.test.js'],+ sources: ['scripts/migrations/210-example.js'],});});- it('excludes a deleted test file from the exact server selector list, and a deleted client file from lint', () => {+ it('excludes deleted test files from exact selectors', () => {// `changed` includes deleted paths (diff-filter ACMRD), but neither// `TRACKED` (git ls-files) nor the trackedFiles fixture below lists them// — a deletion-only PR must not hand a nonexistent path to Vitest/ESLint@@ -293,16 +313,22 @@ describe('CI test impact planner', () => {const plan = buildCiTestPlan(['server/services/sprites/atlas.test.js', // deleted alongside its source'client/src/components/catalog/CatalogCard.test.jsx', // deleted test- 'client/src/lib/catalogLinks.js', // deleted lint-relevant client file], { trackedFiles: TRACKED.filter((path) => !['server/services/sprites/atlas.test.js','client/src/components/catalog/CatalogCard.test.jsx',- 'client/src/lib/catalogLinks.js',].includes(path)) });expect(plan.full).toBe(false);expect(plan.server.files).not.toContain('server/services/sprites/atlas.test.js');- expect(plan.lint.files).not.toContain('client/src/lib/catalogLinks.js');+ });++ it('widens when a changed executable source was deleted', () => {+ const plan = buildCiTestPlan(['client/src/lib/catalogLinks.js'], {+ trackedFiles: TRACKED.filter((path) => path !== 'client/src/lib/catalogLinks.js'),+ });++ expect(plan.full).toBe(true);+ expect(plan.reason).toMatch(/deleted executable source/);});it('falls back to full CI for unknown artifacts and wide changes', () => {@@ -395,6 +421,7 @@ describe('CI test impact planner', () => {expect(spawn.full).toBe(false);expect(spawn.windows).toBe(true);expect(spawn.windowsMode).toBe('related');+ expect(spawn.windowsSources).toEqual(['server/lib/bufferedSpawn.js']);expect(spawn.windowsFiles).toEqual(['server/lib/bufferedSpawn.test.js','server/lib/platform.test.js',@@ -432,4 +459,14 @@ describe('CI test impact planner', () => {expect(plan.windowsFiles.every((path) => WINDOWS_CONTRACT_TESTS.includes(path))).toBe(true);});++ it('uses exact Windows contracts when only a Windows-sensitive test changed', () => {+ const plan = buildCiTestPlan(['server/lib/bufferedSpawn.test.js'], {+ trackedFiles: TRACKED,+ });++ expect(plan.windows).toBe(true);+ expect(plan.windowsMode).toBe('files');+ expect(plan.windowsSources).toEqual([]);+ });});diff --git a/scripts/repo-scan-guards.test.js b/scripts/repo-scan-guards.test.jsindex 89ed40ea3e..b231955ffc 100644--- a/scripts/repo-scan-guards.test.js+++ b/scripts/repo-scan-guards.test.js@@ -6,9 +6,9 @@* files as text, and fail when some unrelated file anywhere in the repo breaks* a convention. `scripts/agent-instructions-files.test.js` is the archetype.*- * CI selects tests by impact (`scripts/ci-test-plan.js`), and both scoped modes- * are import-graph-driven — Vitest's `--changed` walk plus sibling/feature path- * matching. Neither can reach a scanner: the file that violates the convention+ * CI selects tests by impact (`scripts/ci-test-plan.js`) through Vitest's+ * changed-source import graph or feature-path matching. Neither can reach a+ * scanner: the file that violates the convention* is never imported by the guard, so no edge exists to follow. The consequence* is not a flaky selection, it is a structural one — a scanner can sit red on* `main` indefinitely while every PR reports green, which is exactly whatdiff --git a/scripts/run-ci-tests.js b/scripts/run-ci-tests.jsindex b49c284db8..b38e601360 100644--- a/scripts/run-ci-tests.js+++ b/scripts/run-ci-tests.js@@ -5,67 +5,12 @@ import { appendFileSync } from 'fs';import { dirname, join } from 'path';import { fileURLToPath } from 'url';import { prepareCliSpawn } from '../server/lib/bufferedSpawn.js';-import { ALWAYS_RUN_TESTS } from './ci-test-plan.js';import { isDirectlyInvoked } from './lib/directInvocation.js';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;-}--export function canonicalizeRunnerPath(path) {- if (path.startsWith('../')) return path;- return `./${String(path).replace(/^\.\//, '')}`;-}--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));-}--/**- * Does this plan need the diff base to select the right tests?- *- * Both scoped modes union the planner's explicit files with Vitest's- * import-graph `--changed` set, and that half needs a base commit. Without one- * a `files` plan used to quietly run the explicit half alone — a narrower- * suite that still reports green, which is exactly the failure a shallow- * checkout would introduce if scripts/ci-base-sha.js ever stopped exporting- * CI_BASE_SHA. Only an always-run-only plan genuinely needs no base.- */-export function requiresBaseSha(mode, repoFiles) {- if (mode === 'full') return false;- return !shouldSkipRelatedList(mode, repoFiles);+export function requiresSourceFiles(mode, repoSources) {+ return mode === 'related' && repoSources.length === 0;}export function toRunnerPath(scope, path) {@@ -85,8 +30,8 @@ export function recordVitestDuration(scope, label, startedAt) {}}-function spawnNpm(scope, extraArgs, label) {- const args = ['run', 'test:ci', '--prefix', scope];+function spawnNpm(scope, script, extraArgs, label) {+ const args = ['run', script, '--prefix', scope];if (extraArgs.length > 0) args.push('--', ...extraArgs);console.log(`Running ${scope} ${label}${extraArgs.length ? ` (${extraArgs.length} selector argument(s))` : ''}.`);// Wrapped, not a bare `npm.cmd`: Node refuses to spawn a `.cmd` under@@ -107,32 +52,6 @@ function spawnNpm(scope, extraArgs, label) {return result.status ?? 1;}-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);-}--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;- }- return parseVitestListOutput(result.stdout);-}-function main() {const scope = process.argv[2];if (!['server', 'client'].includes(scope)) {@@ -141,57 +60,47 @@ function main() {}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 repoSources = JSON.parse(process.env.CI_TEST_SOURCES || '[]');const selectedFiles = repoFiles.map((path) => toRunnerPath(scope, path));+ const sourceFiles = repoSources.map((path) => toRunnerPath(scope, path));if (!['full', 'files', 'related'].includes(mode)) {console.error(`Unsupported CI test mode: ${mode}`);process.exit(2);}- if (!baseSha && requiresBaseSha(mode, repoFiles)) {- console.error(`CI_BASE_SHA is required for ${mode}-test mode.`);+ if (requiresSourceFiles(mode, repoSources)) {+ console.error('CI_TEST_SOURCES must name at least one changed source file in related-test mode.');process.exit(2);}if (mode === 'full') {- process.exit(spawnNpm(scope, [], 'full suite'));+ process.exit(spawnNpm(scope, 'test:ci', [], 'full suite'));}- 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.- // Skipping the list entirely only happens on an always-run-only plan, which- // requiresBaseSha() already established names every file it needs.- let relatedFiles = [];- if (!shouldSkipRelatedList(mode, repoFiles)) {- const listed = listRelatedFiles(scope, baseSha);- if (listed) {- relatedFiles = listed;- } else {- // The list failed, so the union cannot be built. Run the import-graph- // half through Vitest directly and the planner's explicit half after- // it — two processes instead of one, but never a green run that- // quietly dropped every related test. This fallback covers a `files`- // plan as much as a `related` one: both union the same two halves.- 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);+ if (mode === 'files') {+ if (selectedFiles.length === 0) {+ console.log(`No ${scope} tests selected.`);+ process.exit(0);}+ process.exit(spawnNpm(scope, 'test:ci', selectedFiles, 'selected 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'));+ // Feed Vitest the actual changed source files instead of asking `list+ // --changed` to print every individual test name into a buffered subprocess.+ // The old discovery pass took 282 seconds on PR #5296, overflowed Node's+ // spawnSync buffer, discarded its work, then reran the same graph. `related`+ // builds that graph once and immediately executes it.+ const relatedStatus = spawnNpm(scope, 'test:ci:related', sourceFiles, 'source-related tests');+ if (relatedStatus !== 0) process.exit(relatedStatus);++ // Structural and repository-wide guards do not import the source they scan,+ // so the import graph cannot discover them. They are deliberately cheap and+ // run once after the related set.+ process.exit(selectedFiles.length+ ? spawnNpm(scope, 'test:ci', selectedFiles, 'explicit contract guards')+ : 0);}if (isDirectlyInvoked(import.meta.url)) main();diff --git a/scripts/run-ci-tests.test.js b/scripts/run-ci-tests.test.jsindex a71154c22e..a29ce45655 100644--- a/scripts/run-ci-tests.test.js+++ b/scripts/run-ci-tests.test.js@@ -3,89 +3,12 @@ import { tmpdir } from 'os';import { join } from 'path';import { afterEach, describe, expect, it } from 'vitest';-import { ALWAYS_RUN_TESTS } from './ci-test-plan.js';import {- listRelatedCwd,- parseVitestListOutput,recordVitestDuration,- requiresBaseSha,- shouldSkipRelatedList,+ requiresSourceFiles,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/checkNodeVersion.test.js'],- ['lib/ports.test.js'],- )).toEqual([- './lib/ports.test.js',- '../scripts/checkNodeVersion.test.js',- ]);- });-});--describe('shouldSkipRelatedList', () => {- it('skips the import-graph walk for always-run-only plans', () => {- expect(shouldSkipRelatedList('files', [- 'server/services/taskPromptDefaults.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');@@ -116,19 +39,11 @@ describe('recordVitestDuration', () => {});});-describe('requiresBaseSha', () => {- it('needs no base for the complete suite', () => {- expect(requiresBaseSha('full', [])).toBe(false);- });-- it('needs a base for both scoped modes', () => {- // A 'files' plan unions the planner's list with Vitest's import graph, so- // running it without a base silently drops the second half.- expect(requiresBaseSha('files', ['server/services/shell.test.js'])).toBe(true);- expect(requiresBaseSha('related', [])).toBe(true);- });-- it('needs no base for an always-run-only plan', () => {- expect(requiresBaseSha('files', ALWAYS_RUN_TESTS)).toBe(false);+describe('requiresSourceFiles', () => {+ it('fails closed only when related mode has no source selector', () => {+ expect(requiresSourceFiles('related', [])).toBe(true);+ expect(requiresSourceFiles('related', ['server/services/auth.js'])).toBe(false);+ expect(requiresSourceFiles('files', [])).toBe(false);+ expect(requiresSourceFiles('full', [])).toBe(false);});});diff --git a/server/package.json b/server/package.jsonindex c6b77024ae..3cf80b082e 100644--- a/server/package.json+++ b/server/package.json@@ -14,6 +14,7 @@"test:fast": "vitest run","test:watch": "vitest","test:ci": "vitest run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions",+ "test:ci:related": "vitest related --run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions","test:coverage": "vitest run --coverage","setup:db:test": "node scripts/setup-db-test.mjs","test:db": "vitest run --config vitest.config.db.js",diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.jsindex a3b44371f0..a8e919051a 100644--- a/server/services/llamaServerManager.js+++ b/server/services/llamaServerManager.js@@ -34,6 +34,9 @@ export { LLAMA_APP };const PROBE_TIMEOUT_MS = 1500;const STARTUP_WAIT_TIMEOUT_MS = 4000;+const STARTUP_POLL_DELAY_MS = 500;+const RELAUNCH_READY_TIMEOUT_MS = 120000;+const RELAUNCH_POLL_DELAY_MS = 1000;const LLAMA_CPP_FORMULA = 'llama.cpp';const LLAMA_CPP_DOWNLOAD_URL = 'https://github.com/ggml-org/llama.cpp/releases';const VERSION_PROBE_TIMEOUT_MS = 5000;@@ -56,7 +59,10 @@ const PORT_RELEASE_TIMEOUT_MS = 5000;// while loading — so a relaunch must not read "not ready yet" as "wedged".// Mutable only through the test seam below: a suite asserting the give-up path// cannot sit through two real minutes of polling.-let relaunchReadyTimeoutMs = 120000;+let startupWaitTimeoutMs = STARTUP_WAIT_TIMEOUT_MS;+let startupPollDelayMs = STARTUP_POLL_DELAY_MS;+let relaunchReadyTimeoutMs = RELAUNCH_READY_TIMEOUT_MS;+let relaunchPollDelayMs = RELAUNCH_POLL_DELAY_MS;// How many times a path that would REFUSE on an unreadable PM2 re-reads it// first. See `readLlamaServerStatusRetrying`.const PM2_READ_RETRIES = 2;@@ -634,8 +640,8 @@ export async function startLlamaServer(options = {}) {const startTime = Date.now();let online = false;let currentProc = null;- while (Date.now() - startTime < STARTUP_WAIT_TIMEOUT_MS) {- await sleep(500);+ while (Date.now() - startTime < startupWaitTimeoutMs) {+ await sleep(startupPollDelayMs);clearJlistCache();currentProc = await getAppStatusStrict(LLAMA_APP);if (currentProc && (currentProc.status === 'errored' || currentProc.status === 'stopped' || currentProc.status === 'not_found')) {@@ -894,7 +900,7 @@ async function waitForEndpoint(endpoint) {const deadline = Date.now() + relaunchReadyTimeoutMs;while (Date.now() < deadline) {if (await probeEndpoint(endpoint)) return true;- await sleep(1000);+ await sleep(relaunchPollDelayMs);}return false;}@@ -1431,7 +1437,14 @@ export async function installLlamaServer({ onProgress = () => {} } = {}) {/*** Clears in-memory test state (used by test suites).*/-export function _resetLlamaServerStateForTests({ relaunchReadyTimeout, pm2ReadRetryDelay, sleepIdleMinutes = 0 } = {}) {+export function _resetLlamaServerStateForTests({+ startupWaitTimeout,+ startupPollDelay,+ relaunchReadyTimeout,+ relaunchPollDelay,+ pm2ReadRetryDelay,+ sleepIdleMinutes = 0,+} = {}) {sleepIdleSupport.clear();// Pinned rather than read from disk — see `configuredSleepIdleMinutes`.sleepIdleMinutesOverride = sleepIdleMinutes;@@ -1440,6 +1453,9 @@ export function _resetLlamaServerStateForTests({ relaunchReadyTimeout, pm2ReadRedaemon.resetLogs();lastExitError = null;// Restored to the production budget unless a suite asks for a shorter one.- relaunchReadyTimeoutMs = Number.isFinite(relaunchReadyTimeout) ? relaunchReadyTimeout : 120000;+ startupWaitTimeoutMs = Number.isFinite(startupWaitTimeout) ? startupWaitTimeout : STARTUP_WAIT_TIMEOUT_MS;+ startupPollDelayMs = Number.isFinite(startupPollDelay) ? startupPollDelay : STARTUP_POLL_DELAY_MS;+ relaunchReadyTimeoutMs = Number.isFinite(relaunchReadyTimeout) ? relaunchReadyTimeout : RELAUNCH_READY_TIMEOUT_MS;+ relaunchPollDelayMs = Number.isFinite(relaunchPollDelay) ? relaunchPollDelay : RELAUNCH_POLL_DELAY_MS;pm2ReadRetryDelayMs = Number.isFinite(pm2ReadRetryDelay) ? pm2ReadRetryDelay : PM2_READ_RETRY_DELAY_MS;}diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.jsindex dc670090a7..3d0721fe4c 100644--- a/server/services/llamaServerManager.test.js+++ b/server/services/llamaServerManager.test.js@@ -42,6 +42,18 @@ function endProcess(child, code) {child.emit('close', code);}+const FAST_TIMING = {+ startupWaitTimeout: 50,+ startupPollDelay: 0,+ relaunchReadyTimeout: 50,+ relaunchPollDelay: 0,+ pm2ReadRetryDelay: 0,+};++const resetForTest = (overrides = {}) => {+ _resetLlamaServerStateForTests({ ...FAST_TIMING, ...overrides });+};+const brewInfoJson = ({ installedVersion = 'build-100', latestVersion = '0.3.0', outdated = true, pinned = false, linkedKeg = 'build-100' } = {}) => JSON.stringify({formulae: [{name: 'llama.cpp',@@ -95,7 +107,7 @@ describe('llamaServerManager', () => {beforeEach(() => {// Zero retry delay: the paths that re-read an unreadable PM2 are asserted// here, and a suite must not sit through the production backoff to see them.- _resetLlamaServerStateForTests({ pm2ReadRetryDelay: 0 });+ resetForTest();vi.restoreAllMocks();pm2State = null;execPm2Calls = [];@@ -110,13 +122,8 @@ describe('llamaServerManager', () => {// PortOS's own extension port failed five of these for reasons that have// nothing to do with the code under test, so pin the probe too. Tests that// need a reachable endpoint re-mock this with `{ reachable: true }`.- vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: false, models: [] });-- // Status and start both probe the endpoint over the network. On a developer- // machine that is running PortOS's own llama-server the probe answers for- // real on :5568 and every lifecycle test reports "already running", so pin- // it unreachable for the same reason the port probe above is pinned.- vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: false });+ vi.spyOn(openAiModelsProbe, 'probeOpenAiModels')+ .mockImplementation(async () => ({ reachable: pm2State?.status === 'online', models: [] }));vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {execPm2Calls.push(args);@@ -698,7 +705,7 @@ describe('llamaServerManager', () => {return fakeSpawnProcess();});vi.spyOn(streamingSpawnModule, 'runStreamingCommand').mockResolvedValue({ success: true });- _resetLlamaServerStateForTests({ sleepIdleMinutes: 30 });+ resetForTest({ sleepIdleMinutes: 30 });const result = await upgradeLlamaServer();@@ -746,7 +753,7 @@ describe('llamaServerManager', () => {};openAiModelsProbe.probeOpenAiModels.mockResolvedValue({ reachable: false });vi.spyOn(streamingSpawnModule, 'runStreamingCommand').mockResolvedValue({ success: true });- _resetLlamaServerStateForTests({ relaunchReadyTimeout: 0, pm2ReadRetryDelay: 0 });+ resetForTest({ startupWaitTimeout: 0, relaunchReadyTimeout: 0 });const result = await upgradeLlamaServer();@@ -1294,7 +1301,7 @@ describe('llamaServerManager', () => {vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: false });// Shrink the readiness budget: the give-up path is what's under test, and// the production two minutes would just be two minutes of sleeping.- _resetLlamaServerStateForTests({ relaunchReadyTimeout: 1500 });+ resetForTest({ startupWaitTimeout: 0, relaunchReadyTimeout: 0 });execPm2Calls = [];const result = await relaunchLlamaServerWithTuning({ ubatchSize: 512 });expect(result.applied).toBe(false);@@ -1305,9 +1312,9 @@ describe('llamaServerManager', () => {const restore = execPm2Calls.filter((c) => c[0] === 'start').at(-1);expect(restore).not.toContain('-ub');expect(restore[restore.indexOf('-m') + 1]).toBe(modelPath);- // Two full start cycles (each polling `STARTUP_WAIT_TIMEOUT_MS` against a- // deliberately-silent probe) plus the readiness budget — slow by design,- // not by accident, so this one test buys the room rather than the suite.+ // The timeout budgets are injected through the lifecycle seam: this+ // verifies the give-up/restore behavior without sleeping through the+ // production startup and readiness windows.}, 30000);});diff --git a/server/vitest.setup.js b/server/vitest.setup.jsindex 3ad178e221..f3d392918b 100644--- a/server/vitest.setup.js+++ b/server/vitest.setup.js@@ -52,6 +52,18 @@import { mockNoPeers } from './lib/mockPathsDataRoot.js';+// The server intentionally logs expected error paths, lifecycle transitions,+// and fallback decisions. With console interception disabled (see the config),+// `--silent=passed-only` cannot suppress those lines: PR #5296 emitted 15,355+// log lines for a completely green run. CI sets this opt-in flag so reporter+// output stays useful; local runs retain every log for debugging. Tests that+// assert logging still work because vi.spyOn records calls to these no-ops.+if (process.env.PORTOS_TEST_QUIET === '1') {+ for (const method of ['log', 'info', 'warn', 'error']) {+ console[method] = () => {};+ }+}+// Path is relative to the project root (server/) as required by Vitest// setupFiles resolution — it resolves to the same module as any// `./instances.js` or `../instances.js` reference used in test files.