Skip to content

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

ci: target pull request test execution

[._.]/ Adam Eivye9df6c16b959
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 9a340ea350..1e5a001179 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -5,25 +5,145 @@ on:
branches: [main, release]
push:
branches: [main]
+ schedule:
+ - cron: '17 9 * * *'
+ workflow_dispatch:
+ workflow_call:
+ inputs:
+ full:
+ description: Run the complete server, client, DB, lint, build, and smoke suite
+ required: false
+ type: boolean
+ default: true
permissions:
contents: read
+concurrency:
+ group: ci-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
jobs:
- test:
+ impact:
+ name: Plan test impact
+ runs-on: ubuntu-latest
+ if: github.event_name != 'push' || !contains(github.event.head_commit.message, '[skip ci]')
+ outputs:
+ full: ${{ steps.plan.outputs.full }}
+ reason: ${{ steps.plan.outputs.reason }}
+ server_mode: ${{ steps.plan.outputs.server_mode }}
+ server_files: ${{ steps.plan.outputs.server_files }}
+ client_mode: ${{ steps.plan.outputs.client_mode }}
+ client_files: ${{ steps.plan.outputs.client_files }}
+ db: ${{ steps.plan.outputs.db }}
+ lint_mode: ${{ steps.plan.outputs.lint_mode }}
+ lint_files: ${{ steps.plan.outputs.lint_files }}
+ build: ${{ steps.plan.outputs.build }}
+ smoke: ${{ steps.plan.outputs.smoke }}
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ fetch-depth: 0
+
+ - name: Select affected test surfaces
+ id: plan
+ env:
+ CI_FORCE_FULL: ${{ github.event_name != 'pull_request' || inputs.full }}
+ CI_BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ CI_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: node scripts/ci-test-plan.js
+
+ - name: Publish plan summary
+ env:
+ PLAN_REASON: ${{ steps.plan.outputs.reason }}
+ SERVER_MODE: ${{ steps.plan.outputs.server_mode }}
+ CLIENT_MODE: ${{ steps.plan.outputs.client_mode }}
+ DB_MODE: ${{ steps.plan.outputs.db }}
+ LINT_MODE: ${{ steps.plan.outputs.lint_mode }}
+ BUILD_MODE: ${{ steps.plan.outputs.build }}
+ SMOKE_MODE: ${{ steps.plan.outputs.smoke }}
+ run: |
+ {
+ echo "### CI impact plan"
+ echo
+ echo "- Reason: \`${PLAN_REASON}\`"
+ echo "- Server tests: \`${SERVER_MODE}\`"
+ echo "- Client tests: \`${CLIENT_MODE}\`"
+ echo "- DB tests: \`${DB_MODE}\`"
+ echo "- Client lint: \`${LINT_MODE}\`"
+ echo "- Client build: \`${BUILD_MODE}\`"
+ echo "- Server smoke: \`${SMOKE_MODE}\`"
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ server:
+ # Preserve the historical required-check context while branch protection
+ # transitions to the stable aggregate "CI Gate" check.
+ name: test (24.x)
+ needs: impact
+ if: needs.impact.outputs.server_mode != 'skip'
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ fetch-depth: 0
+
+ - name: Use Node.js 24.x
+ uses: actions/setup-node@v7
+ with:
+ node-version: 24.x
+ cache: npm
+ cache-dependency-path: server/package-lock.json
+
+ - name: Install server dependencies
+ run: npm ci --prefix server
+
+ - name: Check server entry-point syntax
+ run: node --check server/index.js
+
+ - name: Run server tests
+ 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
+
+ client:
+ name: Client tests and build
+ needs: impact
+ if: needs.impact.outputs.client_mode != 'skip' || needs.impact.outputs.build == 'true'
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ fetch-depth: 0
+
+ - 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: Run client tests
+ if: needs.impact.outputs.client_mode != 'skip'
+ env:
+ CI_TEST_MODE: ${{ needs.impact.outputs.client_mode }}
+ CI_TEST_FILES: ${{ needs.impact.outputs.client_files }}
+ CI_BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ run: node scripts/run-ci-tests.js client
+
+ - name: Build client
+ if: needs.impact.outputs.build == 'true'
+ run: npm run build --prefix client
+
+ database:
+ name: DB tests and server smoke
+ needs: impact
+ if: needs.impact.outputs.db == 'true' || needs.impact.outputs.smoke == 'true'
runs-on: ubuntu-latest
- # Skip if commit message contains [skip ci]
- if: "!contains(github.event.head_commit.message, '[skip ci]')"
-
- strategy:
- matrix:
- node-version: [24.x]
-
- # Postgres (with pgvector) for the DB-backed adapter suites. The image ships
- # the `vector` extension that init-db.sql requires. The default `portos` DB
- # exists so setup:db:test has a maintenance connection to CREATE portos_test
- # from; the suites themselves only ever touch portos_test (the production
- # `portos` name is hard-blocked by isTestDatabase()).
services:
postgres:
image: pgvector/pgvector:pg17
@@ -38,62 +158,44 @@ jobs:
--health-interval 10s
--health-timeout 5s
--health-retries 5
-
env:
PGHOST: localhost
PGPORT: 5432
PGUSER: portos
PGPASSWORD: portos
-
steps:
- uses: actions/checkout@v7
- - name: Use Node.js ${{ matrix.node-version }}
+ - name: Use Node.js 24.x
uses: actions/setup-node@v7
with:
- node-version: ${{ matrix.node-version }}
- cache: 'npm'
- cache-dependency-path: |
- package-lock.json
- server/package-lock.json
- client/package-lock.json
-
- - name: Install root dependencies
- run: npm ci
+ node-version: 24.x
+ cache: npm
+ cache-dependency-path: server/package-lock.json
- name: Install server dependencies
run: npm ci --prefix server
- - name: Install client dependencies
- run: npm ci --prefix client
-
- # Main server suite runs WITHOUT PGDATABASE pointing at a test DB, so the
- # DB-backed suites skip here (they'd see the non-test `portos` name). They
- # run in their own serial step below against portos_test.
- - name: Run server tests
- run: npm run test:ci --prefix 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 server
env:
PGDATABASE: portos_test
- - name: Run client tests
- run: npm test --prefix client
-
- - name: Build client
- run: npm run build --prefix client
-
- - name: Smoke-boot server (fail if top-level init crashes)
+ - 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.
+ name: lint
+ needs: impact
+ if: needs.impact.outputs.lint_mode != 'skip'
runs-on: ubuntu-latest
- if: "!contains(github.event.head_commit.message, '[skip ci]')"
-
steps:
- uses: actions/checkout@v7
@@ -101,23 +203,45 @@ jobs:
uses: actions/setup-node@v7
with:
node-version: 24.x
- cache: 'npm'
- cache-dependency-path: |
- package-lock.json
- server/package-lock.json
- client/package-lock.json
-
- - name: Install root dependencies
- run: npm ci
-
- - name: Install server dependencies
- run: npm ci --prefix server
+ cache: npm
+ cache-dependency-path: client/package-lock.json
- name: Install client dependencies
run: npm ci --prefix client
- - name: Check for syntax errors
- run: node --check server/index.js
-
- name: Lint client
- run: npm run lint --prefix client
+ env:
+ CI_LINT_MODE: ${{ needs.impact.outputs.lint_mode }}
+ CI_LINT_FILES: ${{ needs.impact.outputs.lint_files }}
+ run: node scripts/run-ci-lint.js
+
+ gate:
+ name: CI Gate
+ if: always()
+ needs: [impact, server, client, database, lint]
+ runs-on: ubuntu-latest
+ steps:
+ - name: Require every selected job to pass
+ env:
+ IMPACT_RESULT: ${{ needs.impact.result }}
+ SERVER_RESULT: ${{ needs.server.result }}
+ CLIENT_RESULT: ${{ needs.client.result }}
+ DATABASE_RESULT: ${{ needs.database.result }}
+ LINT_RESULT: ${{ needs.lint.result }}
+ run: |
+ node -e '
+ const results = {
+ impact: process.env.IMPACT_RESULT,
+ server: process.env.SERVER_RESULT,
+ client: process.env.CLIENT_RESULT,
+ database: process.env.DATABASE_RESULT,
+ lint: process.env.LINT_RESULT,
+ };
+ const failed = Object.entries(results)
+ .filter(([, result]) => !["success", "skipped"].includes(result));
+ if (failed.length) {
+ console.error("Selected CI jobs did not pass:", failed);
+ process.exit(1);
+ }
+ console.log("CI gate passed:", results);
+ '
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index ee84a576a5..8b3c4a6848 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -8,7 +8,14 @@ permissions:
contents: write
jobs:
+ full-ci:
+ if: "!contains(github.event.head_commit.message, '[skip ci]')"
+ uses: ./.github/workflows/ci.yml
+ with:
+ full: true
+
release:
+ needs: full-ci
runs-on: ubuntu-latest
# Skip version bump commits
if: "!contains(github.event.head_commit.message, '[skip ci]')"
diff --git a/client/package.json b/client/package.json
index 129955d3ca..d166b87f61 100644
--- a/client/package.json
+++ b/client/package.json
@@ -10,6 +10,7 @@
"lint": "eslint src --ext .js,.jsx",
"preview": "vite preview",
"test": "vitest run",
+ "test:ci": "vitest run --bail=1 --reporter=default --reporter=github-actions",
"test:watch": "vitest"
},
"dependencies": {
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md
index 935ed7a34b..eebc25ae02 100644
--- a/docs/CONTRIBUTING.md
+++ b/docs/CONTRIBUTING.md
@@ -101,10 +101,23 @@ PortOS/
# Run server tests
cd server && npm test
+# Run client tests
+cd client && npm test
+
+# Provision and run the isolated DB-backed suites
+npm run setup:db:test
+npm run test:db
+
# Watch mode
cd server && npm run test:watch
```
+Pull requests run the tests for affected feature directories, with conservative
+fallbacks to Vitest related-test mode or the complete suite. Pushes to `main`,
+nightly CI, manual CI runs, and releases always run the complete server, client,
+DB, lint, build, and smoke checks. Release publication is blocked until that
+full CI gate succeeds.
+
## API Documentation
See [API.md](./API.md) for the complete REST API and WebSocket event reference.
diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.md
index d5f2492a11..eee015dcea 100644
--- a/docs/GITHUB_ACTIONS.md
+++ b/docs/GITHUB_ACTIONS.md
@@ -1,6 +1,7 @@
# GitHub Actions Workflows
-PortOS uses two GitHub Actions workflows for CI and releases.
+PortOS uses a test-impact-aware CI workflow plus a release workflow that cannot
+publish until the complete CI suite passes.
## Branch Strategy
@@ -11,41 +12,85 @@ PortOS uses two GitHub Actions workflows for CI and releases.
## CI Workflow (`ci.yml`)
-Triggers on PRs to `main`/`release` and pushes to `main`. Runs two parallel jobs:
-
-### Test Job
-
-- Starts a PostgreSQL service container (`pgvector/pgvector:pg17`) and provisions the test database (`npm run setup:db:test`)
-- Installs root, server, and client dependencies
-- Runs server tests (`npm run test:ci --prefix server`) and DB-backed tests (`npm run test:db:ci --prefix server`)
-- Runs client tests (`npm test --prefix client`)
-- Builds client (`npm run build --prefix client`) and smoke-boots the server (`npm run smoke`)
-- Skips on `[skip ci]` commits (push events only; PR CI always runs)
-
-### Lint Job
-
-- Checks server entry point for syntax errors (`node --check server/index.js`)
-- Runs client lint (`npm run lint --prefix client`)
+PRs to `main`/`release` use `scripts/ci-test-plan.js` to classify the changed
+files before installing dependencies. Directory-scoped features run their
+server and client feature tests; flat modules fall back to Vitest's
+import-graph-aware `--changed` mode. The planner deliberately chooses full CI
+for shared composition roots, test configuration, dependency manifests,
+workflow changes, unknown artifacts, or wide diffs.
+
+The selected work is split across parallel jobs:
+
+- **Server tests** — full, related, or explicit feature test files.
+- **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.
+- **CI Gate** — always reports one stable required-check result and fails if any
+ selected job failed or was cancelled.
+
+No third-party change-filter action is used. The planner passes test paths as a
+JSON argument array to `spawnSync`, never through shell interpolation.
+
+### Full CI
+
+The complete server, client, DB, lint, build, and smoke suite runs:
+
+- after every push to `main`;
+- nightly at 09:17 UTC;
+- from manual workflow dispatch;
+- as a reusable workflow called by every release.
+
+Changes to CI/test configuration also force the full suite on their own PR.
+`[skip ci]` remains honored for push events only; PR CI always runs.
+
+### 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.
+- Barrel/catalog guards are added when reusable `lib`, `hooks`, or `utils`
+ directories change; JSX changes include the global accessibility convention
+ guard.
+- Database adapters, DB scripts, and relevant migrations add the complete
+ serial DB suite.
+- Unmapped executable files use related-test mode. Unclassified artifacts,
+ shared roots/config, more than 30 executable changes, or more than 120
+ selected tests fail safe to full CI.
## Release Workflow (`release.yml`)
Triggers on push to `release` branch. Steps:
-1. Reads version from `package.json`
-2. Checks if git tag already exists (skips if so)
-3. Looks for changelog file:
+1. Calls `ci.yml` with `full: true` and waits for the complete CI gate.
+2. Reads version from `package.json`.
+3. Checks if the git tag already exists (skips release creation if so).
+4. Looks for a changelog file:
- First: `.changelog/v{version}.md` (exact match)
- Then: `.changelog/v{major}.{minor}.x.md` (pattern match, replaces placeholders)
- Fallback: generates changelog from commit messages
-4. Creates GitHub release with tag `v{version}`
-5. If a pattern changelog file (`.changelog/v{major}.{minor}.x.md`) was used, archives it on `main` (renames `.x.md` → exact version)
-6. If the archive step ran, fast-forwards `release` to match `main`
+5. Creates the GitHub release with tag `v{version}`.
+6. If a pattern changelog file (`.changelog/v{major}.{minor}.x.md`) was used,
+ archives it on `main` (renames `.x.md` to the exact version).
+7. If the archive step ran, fast-forwards `release` to match `main`.
## Working with CI
### Skip CI
-Add `[skip ci]` to commit messages for non-code changes (docs, configs). Auto-generated commits from the release workflow include this automatically.
+Add `[skip ci]` to push commit messages for generated documentation-only
+changes. Auto-generated commits from the release workflow include this
+automatically. Pull-request checks ignore this marker so a PR cannot bypass its
+required CI gate.
+
+### Force Full CI
+
+Use the workflow-dispatch button for an immediate full run. A PR also chooses
+full CI automatically when its impact cannot be classified safely.
### Rebase Before Push
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.js
new file mode 100644
index 0000000000..ca875d1aa4
--- /dev/null
+++ b/scripts/ci-test-plan.js
@@ -0,0 +1,332 @@
+#!/usr/bin/env node
+
+import { appendFileSync } from 'fs';
+import { execFileSync } from 'child_process';
+import { fileURLToPath } from 'url';
+import { resolve } from 'path';
+
+const TEST_FILE_RE = /\.(?:test|spec)\.[cm]?[jt]sx?$/i;
+const CLIENT_LINT_RE = /^client\/src\/.*\.(?:js|jsx)$/i;
+const EXECUTABLE_RE = /\.(?:cjs|css|html|js|jsx|json|mjs|sql|ts|tsx|ya?ml)$/i;
+const MAX_CHANGED_CODE_FILES = 30;
+const MAX_TARGETED_TEST_FILES = 120;
+
+const FULL_TRIGGER_RULES = [
+ { re: /^\.github\/workflows\//, reason: 'workflow definition changed' },
+ { re: /^(?:package|server\/package|client\/package)(?:-lock)?\.json$/, reason: 'dependency manifest changed' },
+ { re: /^(?:server|client)\/vitest\.config(?:\.db)?\.js$/, reason: 'test runner configuration changed' },
+ { re: /^server\/vitest\.setup\.js$/, reason: 'server test setup changed' },
+ { re: /^client\/src\/test\/setup\.js$/, reason: 'client test setup changed' },
+ { re: /^client\/eslint\.config\.js$/, reason: 'lint configuration changed' },
+ { re: /^client\/vite\.config\.js$/, reason: 'client build configuration changed' },
+ { re: /^server\/index\.js$/, reason: 'server composition root changed' },
+ { re: /^client\/src\/App\.jsx$/, reason: 'client composition root changed' },
+ { 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' },
+];
+
+const DB_RISK_RULES = [
+ /^server\/lib\/db(?:\/|\.|$)/i,
+ /^server\/scripts\/.*db/i,
+ /^server\/services\/(?:.*\/)?[^/]*DB(?:\/|\.|$)/i,
+ /^server\/services\/.*\.db\.test\.js$/i,
+ /^server\/routes\/catalog\.js$/i,
+ /^scripts\/(?:init-db\.sql|migrations\/.*(?:db|postgres|catalog|privacy))/i,
+];
+
+const DOCUMENTATION_RULES = [
+ /^\.changelog\//,
+ /^docs\//,
+ /^(?:README|CHANGELOG|CONTRIBUTING|LICENSE)(?:\.|$)/i,
+ /\.(?:md|mdx|png|jpe?g|gif|webp|svg|ico)$/i,
+];
+
+const RUNNER_ROOTS = {
+ server: [
+ 'server/',
+ 'scripts/',
+ 'lib/',
+ 'autofixer/',
+ ],
+ client: ['client/src/'],
+};
+
+const FEATURE_DIRECTORY_RULES = [
+ /^server\/(?:integrations|lib|routes|services|sockets)\/([^/]+)\//,
+ /^client\/src\/components\/([^/]+)\//,
+];
+
+const normalizeFeature = (value) => String(value || '')
+ .replace(/\.(?:test|spec)$/i, '')
+ .replace(/[^a-z0-9]/gi, '')
+ .toLowerCase();
+
+const featureVariants = (feature) => {
+ const normalized = normalizeFeature(feature);
+ const singular = normalized.endsWith('s') ? normalized.slice(0, -1) : normalized;
+ return new Set([normalized, singular].filter(Boolean));
+};
+
+const normalizedPathParts = (path) => path
+ .split('/')
+ .flatMap((part) => {
+ const withoutExt = part.replace(/\.[^.]+$/, '').replace(/\.(?:test|spec)$/i, '');
+ const camelParts = withoutExt.split(/[-_.]|(?=[A-Z])/).filter(Boolean);
+ const normalized = normalizeFeature(withoutExt);
+ const withoutPrefix = normalizeFeature(withoutExt.replace(/^(?:api|use)/i, ''));
+ return [normalized, withoutPrefix, ...camelParts.map(normalizeFeature)].filter(Boolean);
+ });
+
+const pathMatchesFeature = (path, feature) => {
+ const variants = featureVariants(feature);
+ return normalizedPathParts(path).some((part) => variants.has(part));
+};
+
+const isTestFile = (path) => TEST_FILE_RE.test(path);
+const isDocumentationOnly = (path) => DOCUMENTATION_RULES.some((rule) => rule.test(path));
+const isExecutable = (path) => EXECUTABLE_RE.test(path);
+const isServerRunnerFile = (path) => RUNNER_ROOTS.server.some((root) => path.startsWith(root));
+const isClientRunnerFile = (path) => RUNNER_ROOTS.client.some((root) => path.startsWith(root));
+
+const runnerForTest = (path) => {
+ if (!isTestFile(path)) return null;
+ if (isClientRunnerFile(path)) return 'client';
+ if (isServerRunnerFile(path)) return 'server';
+ return null;
+};
+
+const featureDirectory = (path) => {
+ for (const rule of FEATURE_DIRECTORY_RULES) {
+ const match = path.match(rule);
+ if (match) return normalizeFeature(match[1]);
+ }
+ 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) => {
+ if (trackedSet.has(path)) selected.push(path);
+ };
+
+ if (changedFiles.some((path) => /^server\/lib\//.test(path))) {
+ add('server/lib/index.test.js');
+ }
+ if (changedFiles.some((path) => /^client\/src\/lib\//.test(path))) {
+ add('client/src/lib/index.test.js');
+ }
+ if (changedFiles.some((path) => /^client\/src\/hooks\//.test(path))) {
+ add('client/src/hooks/index.test.js');
+ }
+ if (changedFiles.some((path) => /^client\/src\/utils\//.test(path))) {
+ add('client/src/utils/index.test.js');
+ }
+ if (changedFiles.some((path) => /^client\/src\/.*\.jsx$/.test(path))) {
+ add('client/src/a11yConventions.test.js');
+ }
+
+ return selected;
+};
+
+const uniqueSorted = (values) => [...new Set(values)].sort();
+
+const skippedRunner = () => ({ mode: 'skip', files: [] });
+
+/**
+ * Build a conservative PR test plan.
+ *
+ * "files" mode is used only when every executable change belongs to a
+ * directory-scoped feature (for example services/sprites + components/sprites).
+ * Flat/shared files fall back to Vitest's import-graph-aware "related" mode,
+ * while composition roots and test configuration force the complete suite.
+ */
+export function buildCiTestPlan(changedFiles, { trackedFiles = [], forceFull = false } = {}) {
+ const changed = uniqueSorted(changedFiles.filter(Boolean));
+ const trackedSet = new Set(trackedFiles);
+
+ if (forceFull) {
+ return {
+ full: true,
+ reason: 'full CI requested',
+ changedFiles: changed,
+ server: { mode: 'full', files: [] },
+ client: { mode: 'full', files: [] },
+ db: true,
+ lint: { mode: 'full', files: [] },
+ build: true,
+ smoke: true,
+ };
+ }
+
+ const fullTrigger = changed
+ .flatMap((path) => FULL_TRIGGER_RULES
+ .filter(({ re }) => re.test(path))
+ .map(({ reason }) => ({ path, reason })))
+ .at(0);
+
+ if (fullTrigger) {
+ return fullPlan(changed, `${fullTrigger.reason}: ${fullTrigger.path}`);
+ }
+
+ const relevant = changed.filter((path) => !isDocumentationOnly(path));
+ if (relevant.length === 0) {
+ return {
+ full: false,
+ reason: changed.length ? 'documentation-only change' : 'no changed files',
+ changedFiles: changed,
+ server: skippedRunner(),
+ client: skippedRunner(),
+ db: false,
+ lint: { mode: 'skip', files: [] },
+ build: false,
+ smoke: false,
+ };
+ }
+
+ const executable = relevant.filter(isExecutable);
+ const unknown = relevant.filter((path) => !isExecutable(path));
+ if (unknown.length > 0) {
+ return fullPlan(changed, `unclassified changed file: ${unknown[0]}`);
+ }
+ if (executable.length > MAX_CHANGED_CODE_FILES) {
+ return fullPlan(changed, `wide change (${executable.length} executable files)`);
+ }
+
+ const directTests = executable.filter(isTestFile);
+ const sourceFiles = executable.filter((path) => !isTestFile(path));
+ const unsupportedSources = sourceFiles.filter((path) => (
+ !isServerRunnerFile(path) && !path.startsWith('client/')
+ ));
+ if (unsupportedSources.length > 0) {
+ return fullPlan(changed, `unmapped executable surface: ${unsupportedSources[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),
+ ];
+
+ for (const testFile of trackedFiles.filter(isTestFile)) {
+ if (features.some((feature) => pathMatchesFeature(testFile, feature))) {
+ selectedTests.push(testFile);
+ }
+ }
+
+ const serverFiles = uniqueSorted(selectedTests.filter((path) => runnerForTest(path) === 'server'));
+ const clientFiles = uniqueSorted(selectedTests.filter((path) => runnerForTest(path) === 'client'));
+
+ if (serverFiles.length > MAX_TARGETED_TEST_FILES || clientFiles.length > MAX_TARGETED_TEST_FILES) {
+ return fullPlan(changed, 'targeted test set exceeded safety cap');
+ }
+
+ const hasServerSource = sourceFiles.some(isServerRunnerFile);
+ const hasClientSource = sourceFiles.some((path) => path.startsWith('client/'));
+ const hasUnscopedServer = unscopedSources.some(isServerRunnerFile);
+ const hasUnscopedClient = unscopedSources.some((path) => path.startsWith('client/'));
+
+ const server = serverFiles.length > 0
+ ? { mode: hasUnscopedServer ? 'related' : 'files', files: serverFiles }
+ : hasServerSource
+ ? { mode: 'related', files: [] }
+ : skippedRunner();
+ const client = clientFiles.length > 0
+ ? { mode: hasUnscopedClient ? 'related' : 'files', files: clientFiles }
+ : hasClientSource
+ ? { mode: 'related', files: [] }
+ : skippedRunner();
+
+ return {
+ full: false,
+ reason: features.length
+ ? `targeted features: ${features.join(', ')}`
+ : 'Vitest related-test fallback',
+ changedFiles: changed,
+ server,
+ client,
+ db: executable.some((path) => DB_RISK_RULES.some((rule) => rule.test(path))),
+ lint: {
+ mode: changed.some((path) => CLIENT_LINT_RE.test(path)) ? 'files' : 'skip',
+ files: changed.filter((path) => CLIENT_LINT_RE.test(path)),
+ },
+ build: hasClientSource,
+ smoke: hasServerSource,
+ };
+}
+
+function fullPlan(changedFiles, reason) {
+ return {
+ full: true,
+ reason,
+ changedFiles,
+ server: { mode: 'full', files: [] },
+ client: { mode: 'full', files: [] },
+ db: true,
+ lint: { mode: 'full', files: [] },
+ build: true,
+ smoke: true,
+ };
+}
+
+const gitLines = (args) => execFileSync('git', args, { encoding: 'utf8' })
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean);
+
+const writeOutput = (name, value) => {
+ const outputPath = process.env.GITHUB_OUTPUT;
+ if (!outputPath) return;
+ appendFileSync(outputPath, `${name}=${String(value)}\n`);
+};
+
+export function emitGitHubPlan(plan) {
+ const outputs = {
+ full: plan.full,
+ reason: plan.reason.replace(/[`<>\r\n]+/g, ' '),
+ server_mode: plan.server.mode,
+ server_files: JSON.stringify(plan.server.files),
+ client_mode: plan.client.mode,
+ client_files: JSON.stringify(plan.client.files),
+ db: plan.db,
+ lint_mode: plan.lint.mode,
+ lint_files: JSON.stringify(plan.lint.files),
+ build: plan.build,
+ smoke: plan.smoke,
+ };
+
+ Object.entries(outputs).forEach(([name, value]) => writeOutput(name, value));
+ console.log(JSON.stringify({ ...outputs, changed_files: plan.changedFiles }, null, 2));
+}
+
+function main() {
+ const forceFull = process.env.CI_FORCE_FULL === 'true';
+ const base = process.env.CI_BASE_SHA;
+ const head = process.env.CI_HEAD_SHA || 'HEAD';
+ if (!forceFull && !base) {
+ throw new Error('CI_BASE_SHA is required unless CI_FORCE_FULL=true.');
+ }
+ const changedFiles = forceFull
+ ? []
+ : gitLines(['diff', '--name-only', '--diff-filter=ACMRD', `${base}...${head}`]);
+ const trackedFiles = gitLines(['ls-files']);
+ emitGitHubPlan(buildCiTestPlan(changedFiles, { trackedFiles, forceFull }));
+}
+
+const isMain = process.argv[1]
+ && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url));
+
+if (isMain) main();
diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.js
new file mode 100644
index 0000000000..e519c9a157
--- /dev/null
+++ b/scripts/ci-test-plan.test.js
@@ -0,0 +1,190 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildCiTestPlan } from './ci-test-plan.js';
+
+const TRACKED = [
+ 'server/lib/index.test.js',
+ 'server/routes/auth.test.js',
+ 'server/routes/sprites.test.js',
+ 'server/services/auth.test.js',
+ 'server/services/catalogDB/facets.db.test.js',
+ 'server/services/sprites/animationTracks.test.js',
+ 'server/services/sprites/atlas.test.js',
+ 'server/services/sprites/atlasGrid.test.js',
+ 'server/services/sprites/atlasLayout.test.js',
+ 'client/src/a11yConventions.test.js',
+ 'client/src/components/catalog/CatalogCard.test.jsx',
+ 'client/src/components/sprites/WalkWorkflow.test.jsx',
+ 'client/src/lib/index.test.js',
+ 'client/src/services/apiSprites.test.js',
+ 'scripts/migrations/210-example.test.js',
+];
+
+describe('CI test impact planner', () => {
+ it('skips all expensive jobs for documentation-only changes', () => {
+ const plan = buildCiTestPlan([
+ '.changelog/NEXT.md',
+ 'docs/GITHUB_ACTIONS.md',
+ ], { trackedFiles: TRACKED });
+
+ expect(plan).toMatchObject({
+ full: false,
+ reason: 'documentation-only change',
+ server: { mode: 'skip' },
+ client: { mode: 'skip' },
+ db: false,
+ lint: { mode: 'skip' },
+ build: false,
+ smoke: false,
+ });
+ });
+
+ it('forces the full suite when CI or shared test configuration changes', () => {
+ for (const path of [
+ '.github/workflows/ci.yml',
+ 'server/vitest.config.js',
+ 'client/src/test/setup.js',
+ 'server/lib/validation.js',
+ ]) {
+ const plan = buildCiTestPlan([path], { trackedFiles: TRACKED });
+ expect(plan.full, path).toBe(true);
+ expect(plan.server.mode, path).toBe('full');
+ expect(plan.client.mode, path).toBe('full');
+ expect(plan.db, path).toBe(true);
+ }
+ });
+
+ it('selects the touched feature across server and client without pulling unrelated tests', () => {
+ const plan = buildCiTestPlan([
+ '.changelog/NEXT.md',
+ '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',
+ ], { trackedFiles: TRACKED });
+
+ expect(plan).toMatchObject({
+ full: false,
+ reason: 'targeted features: sprites',
+ server: { mode: 'files' },
+ client: { mode: 'files' },
+ db: false,
+ lint: { mode: 'skip' },
+ build: false,
+ smoke: true,
+ });
+ expect(plan.server.files).toEqual([
+ 'server/routes/sprites.test.js',
+ 'server/services/sprites/animationTracks.test.js',
+ 'server/services/sprites/atlas.test.js',
+ 'server/services/sprites/atlasGrid.test.js',
+ 'server/services/sprites/atlasLayout.test.js',
+ ]);
+ expect(plan.client.files).toEqual([
+ 'client/src/components/sprites/WalkWorkflow.test.jsx',
+ 'client/src/services/apiSprites.test.js',
+ ]);
+ expect(plan.server.files).not.toContain('server/services/auth.test.js');
+ });
+
+ it('uses Vitest related mode for flat modules whose impact is defined by imports', () => {
+ const plan = buildCiTestPlan(['server/services/auth.js'], {
+ trackedFiles: TRACKED,
+ });
+
+ expect(plan.full).toBe(false);
+ expect(plan.server).toEqual({
+ mode: 'related',
+ files: ['server/services/auth.test.js'],
+ });
+ expect(plan.client.mode).toBe('skip');
+ expect(plan.smoke).toBe(true);
+ });
+
+ it('adds structural guard tests and changed-file linting for client modules', () => {
+ const plan = buildCiTestPlan([
+ 'client/src/components/catalog/CatalogCard.jsx',
+ 'client/src/lib/catalogLinks.js',
+ ], { trackedFiles: TRACKED });
+
+ expect(plan.full).toBe(false);
+ expect(plan.client.mode).toBe('related');
+ expect(plan.client.files).toContain('client/src/lib/index.test.js');
+ expect(plan.client.files).toContain('client/src/a11yConventions.test.js');
+ expect(plan.lint).toEqual({
+ mode: 'files',
+ files: [
+ 'client/src/components/catalog/CatalogCard.jsx',
+ 'client/src/lib/catalogLinks.js',
+ ],
+ });
+ expect(plan.build).toBe(true);
+ });
+
+ it('runs the DB suite when a database-backed adapter changes', () => {
+ const plan = buildCiTestPlan([
+ 'server/services/catalogDB/facets.js',
+ 'server/services/catalogDB/facets.db.test.js',
+ ], { trackedFiles: TRACKED });
+
+ expect(plan.full).toBe(false);
+ expect(plan.server.mode).toBe('files');
+ expect(plan.db).toBe(true);
+ });
+
+ it('runs a directly changed migration test without broadening to the full suite', () => {
+ const plan = buildCiTestPlan([
+ 'scripts/migrations/210-example.js',
+ 'scripts/migrations/210-example.test.js',
+ ], { trackedFiles: TRACKED });
+
+ expect(plan.full).toBe(false);
+ expect(plan.server).toEqual({
+ mode: 'related',
+ files: ['scripts/migrations/210-example.test.js'],
+ });
+ });
+
+ it('falls back to full CI for unknown artifacts and wide changes', () => {
+ const unknown = buildCiTestPlan(['data.reference/bootstrap.bin'], {
+ trackedFiles: TRACKED,
+ });
+ expect(unknown.full).toBe(true);
+ expect(unknown.reason).toMatch(/unclassified/);
+
+ const unmappedExecutable = buildCiTestPlan(['ecosystem.config.cjs'], {
+ trackedFiles: TRACKED,
+ });
+ expect(unmappedExecutable.full).toBe(true);
+ expect(unmappedExecutable.reason).toMatch(/unmapped executable/);
+
+ const wide = buildCiTestPlan(
+ Array.from({ length: 31 }, (_, i) => `server/services/feature${i}.js`),
+ { trackedFiles: TRACKED },
+ );
+ expect(wide.full).toBe(true);
+ expect(wide.reason).toMatch(/wide change/);
+ });
+
+ it('honors an explicit full-CI request', () => {
+ const plan = buildCiTestPlan(['docs/README.md'], {
+ trackedFiles: TRACKED,
+ forceFull: true,
+ });
+
+ expect(plan).toMatchObject({
+ full: true,
+ reason: 'full CI requested',
+ server: { mode: 'full' },
+ client: { mode: 'full' },
+ db: true,
+ lint: { mode: 'full' },
+ build: true,
+ smoke: true,
+ });
+ });
+});
diff --git a/scripts/run-ci-lint.js b/scripts/run-ci-lint.js
new file mode 100644
index 0000000000..78d6d67f9a
--- /dev/null
+++ b/scripts/run-ci-lint.js
@@ -0,0 +1,39 @@
+#!/usr/bin/env node
+
+import { spawnSync } from 'child_process';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+const mode = process.env.CI_LINT_MODE || 'full';
+const repoFiles = JSON.parse(process.env.CI_LINT_FILES || '[]');
+const clientFiles = repoFiles
+ .filter((path) => /^client\/src\/.*\.(?:js|jsx)$/i.test(path))
+ .map((path) => path.replace(/^client\//, ''));
+
+if (mode === 'files' && clientFiles.length === 0) {
+ console.log('No changed client JavaScript files require linting.');
+ process.exit(0);
+}
+if (!['files', 'full'].includes(mode)) {
+ console.error(`Unsupported CI lint mode: ${mode}`);
+ process.exit(2);
+}
+
+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..');
+const eslintBin = join(repoRoot, 'client', 'node_modules', 'eslint', 'bin', 'eslint.js');
+const args = mode === 'full'
+ ? [eslintBin, 'src', '--ext', '.js,.jsx']
+ : [eslintBin, ...clientFiles];
+
+console.log(`Running client lint in ${mode} mode${mode === 'files' ? ` (${clientFiles.length} file(s))` : ''}.`);
+const result = spawnSync(process.execPath, args, {
+ cwd: join(repoRoot, 'client'),
+ stdio: 'inherit',
+ env: process.env,
+});
+
+if (result.error) {
+ console.error(result.error.message);
+ process.exit(1);
+}
+process.exit(result.status ?? 1);
diff --git a/scripts/run-ci-tests.js b/scripts/run-ci-tests.js
new file mode 100644
index 0000000000..ea5c11fb25
--- /dev/null
+++ b/scripts/run-ci-tests.js
@@ -0,0 +1,81 @@
+#!/usr/bin/env node
+
+import { spawnSync } from 'child_process';
+
+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 toRunnerPath = (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 npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm';
+const run = (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))` : ''}.`);
+ const result = spawnSync(npmCommand, args, {
+ stdio: 'inherit',
+ env: process.env,
+ });
+ if (result.error) {
+ console.error(result.error.message);
+ return 1;
+ }
+ return result.status ?? 1;
+};
+
+if (mode === 'full') {
+ process.exit(run([], 'full suite'));
+}
+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);
+ }
+ process.exit(run(selectedFiles, 'feature tests'));
+}
+
+const relatedStatus = run(relatedArgs, 'related tests');
+if (relatedStatus !== 0) process.exit(relatedStatus);
+
+// 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'));
+}
+process.exit(0);