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

fix: run database contracts for scoped CI changes (#9872)

Adam Eivyf9578dea82d0
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.js
index 1e867770e3..bea066c89d 100644
--- a/scripts/ci-test-plan.js
+++ b/scripts/ci-test-plan.js
@@ -6,6 +6,7 @@ import { join, posix } from 'path';
import { staticImportSpecifiersFromSource } from '../server/lib/staticImportGraph.js';
import { isDirectlyInvoked } from './lib/directInvocation.js';
import { writeStepOutput } from './lib/githubOutput.js';
+import { resolveDbTestFiles } from './lib/dbTestFiles.js';
const TEST_FILE_RE = /\.(?:test|spec)\.[cm]?[jt]sx?$/i;
const MODULE_SOURCE_RE = /\.[cm]?[jt]sx?$/i;
@@ -609,6 +610,8 @@ export function buildCiTestPlan(changedFiles, {
// Repository-derived browser dependencies; null means discovery failed and
// a shared-source change must retain conservative full coverage.
clientDependencies = [],
+ // Includes literal deferred imports; null means discovery was inconclusive.
+ dbDependencies = [],
} = {}) {
const changed = uniqueSorted(changedFiles.filter(Boolean));
const trackedSet = new Set(trackedFiles);
@@ -805,6 +808,11 @@ export function buildCiTestPlan(changedFiles, {
? { mode: clientSources.length > 0 ? 'related' : 'files', files: [], sources: clientSources }
: skippedRunner();
+ const dbTests = new Set(resolveDbTestFiles(trackedFiles));
+ const db = serverFiles.some((path) => dbTests.has(path))
+ || executable.some((path) => DB_RISK_RULES.some((rule) => rule.test(path)))
+ || serverSources.some((path) => dbDependencies === null || dbDependencies.includes(path));
+
const windows = hasWindowsRiskFile(changed);
const windowsMode = windows
? (serverSources.length > 0 ? 'related' : 'files')
@@ -820,7 +828,7 @@ export function buildCiTestPlan(changedFiles, {
changedFiles: changed,
server,
client,
- db: executable.some((path) => DB_RISK_RULES.some((rule) => rule.test(path))),
+ db,
lint: {
// Same deleted-path guard as directTests above — ESLint given a
// nonexistent explicit path exits non-zero instead of skipping it.
@@ -983,6 +991,47 @@ function collectClientDependencies(trackedFiles, cwd) {
return uniqueSorted([...seen].filter((path) => path.startsWith('server/lib/')));
}
+// DB suites are excluded from ordinary Vitest related selection. Walk their
+// imports separately, including deferred literals, without importing test code
+// or Vitest (the planner runs before npm installation). Unreadable or unresolved
+// local imports and computed imports retain DB coverage for server sources.
+function collectDbDependencies(files, cwd) {
+ const known = new Set(files);
+ const pending = resolveDbTestFiles(files);
+ const seen = new Set();
+ const extensions = ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.mts', '.cts', '.json'];
+ let inconclusive = false;
+ try {
+ for (let index = 0; index < pending.length; index++) {
+ const file = pending[index];
+ if (seen.has(file)) continue;
+ seen.add(file);
+ if (!MODULE_SOURCE_RE.test(file)) continue;
+ const source = readFileSync(join(cwd, file), 'utf8');
+ const specifiers = staticImportSpecifiersFromSource(source);
+ // Scan all import calls. A nonliteral expression cannot safely prove
+ // absence of a dependency; template literals are resolvable only when
+ // they contain no interpolation. Extra matches in comments widen safely.
+ for (const match of source.matchAll(/\bimport\s*\(\s*([^)]*)\)/g)) {
+ const literal = match[1].trim().match(/^(['"`])([^'"`]*?)\1\s*(?:,.*)?$/s);
+ if (!literal || literal[2].includes('${')) inconclusive = true;
+ else specifiers.push(literal[2]);
+ }
+ for (const specifier of specifiers) {
+ if (!specifier.startsWith('.')) continue;
+ const path = posix.normalize(posix.join(posix.dirname(file), specifier.split(/[?#]/)[0]));
+ const dependencies = [path, ...extensions.map((extension) => `${path}${extension}`),
+ ...extensions.map((extension) => `${path}/index${extension}`)].filter((candidate) => known.has(candidate));
+ if (dependencies.length === 0) inconclusive = true;
+ pending.push(...dependencies);
+ }
+ }
+ } catch {
+ return null;
+ }
+ return inconclusive ? null : uniqueSorted([...seen]);
+}
+
/**
* Collect the repository-derived inputs that surround the pure plan builder.
*
@@ -1042,7 +1091,12 @@ export function collectPlanInputs({ baseSha, forceFull = false, changedFiles, cw
? collectClientDependencies(hasChangedFilesOverride ? uniqueSorted([...presentFiles, ...untrackedFiles]) : presentFiles, cwd)
: [];
- return { changedFiles: collectedChangedFiles, trackedFiles: presentFiles, appDiff, pathContractTests, clientDependencies };
+ const dbDependencies = collectedChangedFiles.some((path) => isServerRunnerFile(path)
+ && MODULE_SOURCE_RE.test(path) && !isTestFile(path) && !isStructuralBarrel(path))
+ ? collectDbDependencies(hasChangedFilesOverride ? uniqueSorted([...presentFiles, ...untrackedFiles]) : presentFiles, cwd)
+ : [];
+
+ return { changedFiles: collectedChangedFiles, trackedFiles: presentFiles, appDiff, pathContractTests, clientDependencies, dbDependencies };
}
function main() {
@@ -1066,7 +1120,7 @@ function main() {
&& (!Array.isArray(changedFilesOverride) || changedFilesOverride.some((path) => typeof path !== 'string'))) {
throw new Error('CI_CHANGED_FILES must be a JSON array of repository-relative path strings.');
}
- const { changedFiles, trackedFiles, appDiff, pathContractTests, clientDependencies } = collectPlanInputs({
+ const { changedFiles, trackedFiles, appDiff, pathContractTests, clientDependencies, dbDependencies } = collectPlanInputs({
baseSha: base,
forceFull,
changedFiles: changedFilesOverride,
@@ -1078,6 +1132,7 @@ function main() {
appRouteOnly: isRouteOnlyAppDiff(appDiff),
pathContractTests,
clientDependencies,
+ dbDependencies,
}));
}
diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.js
index 1626f26f0e..4d0737d277 100644
--- a/scripts/ci-test-plan.test.js
+++ b/scripts/ci-test-plan.test.js
@@ -4,6 +4,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { resolveDbTestFiles } from './lib/dbTestFiles.js';
import { staticImportClosure } from '../server/lib/staticImportGraph.js';
import {
@@ -311,6 +312,77 @@ it('resolves local client imports of present untracked modules and still fails c
}
});
+it('requests DB verification for every suite in the real canonical inventory without widening the matrix', () => {
+ const cwd = fileURLToPath(new URL('../', import.meta.url));
+ const inputs = collectPlanInputs({ baseSha: 'HEAD', changedFiles: [], cwd });
+ const dbTests = resolveDbTestFiles(inputs.trackedFiles);
+ expect(dbTests.length).toBeGreaterThan(50);
+ for (const suite of dbTests) {
+ const plan = buildCiTestPlan([suite], inputs);
+ expect(plan, suite).toMatchObject({ full: false, db: true, server: { mode: 'files' } });
+ expect(plan.server.files, suite).toContain(suite);
+ }
+});
+
+it('requests DB verification for the real deck, model pin and backup source contracts', () => {
+ const cwd = fileURLToPath(new URL('../', import.meta.url));
+ for (const source of ['server/routes/decks.js', 'server/services/modelPinRecords.js', 'server/services/backup.js']) {
+ const inputs = collectPlanInputs({ baseSha: 'HEAD', changedFiles: [source], cwd });
+ expect(buildCiTestPlan(inputs.changedFiles, inputs), source).toMatchObject({ full: false, db: true });
+ }
+});
+
+it('follows DB-only deferred dependencies through the pre-install CLI and preserves conservative and unrelated plans', () => {
+ const root = mkdtempSync(join(tmpdir(), 'portos-ci-db-deps-'));
+ const planner = fileURLToPath(new URL('./ci-test-plan.js', import.meta.url));
+ const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8' }).trim();
+ const write = (path, source) => {
+ mkdirSync(dirname(join(root, path)), { recursive: true });
+ writeFileSync(join(root, path), source);
+ };
+ const leaf = 'server/services/example/leaf.js';
+ const contract = 'server/routes/decks.db.test.js';
+ const plan = (changedFiles) => JSON.parse(execFileSync(process.execPath, [planner], {
+ cwd: root,
+ encoding: 'utf8',
+ env: { ...process.env, CI_BASE_SHA: 'HEAD', CI_BASE_REF: 'main', CI_FORCE_FULL: 'false',
+ CI_CHANGED_FILES: JSON.stringify(changedFiles), GITHUB_OUTPUT: '', GITHUB_STEP_SUMMARY: '' },
+ }));
+ try {
+ git('init', '-q');
+ write(leaf, 'export const value = 1;\n');
+ write('server/services/bridge.js', "export const load = () => import('./example/leaf.js');\n");
+ write(contract, "import '../services/bridge.js';\n");
+ write('server/services/unrelated.js', 'export const value = 2;\n');
+ git('add', '--all');
+
+ // The contract neither names leaf.js nor shares its feature; only the
+ // dependency walk can request the otherwise excluded database suite.
+ const related = plan([leaf]);
+ expect(related).toMatchObject({ full: false, db: true, server_mode: 'related' });
+ expect(JSON.parse(related.server_files)).not.toContain(contract);
+ expect(plan(['server/services/unrelated.js'])).toMatchObject({ full: false, db: false });
+ expect(plan(['docs/README.md'])).toMatchObject({ full: false, db: false });
+
+ // Basename and feature selectors must trigger DB coverage too.
+ write('server/services/bridge.js', 'export const value = 2;\n');
+ write(contract, '// Reads leaf.js as text.\n');
+ expect(plan([leaf])).toMatchObject({ full: false, db: true });
+ write(contract, '// A deck contract.\n');
+ write('server/services/decks/leaf.js', 'export const value = 1;\n');
+ git('add', '--all');
+ expect(plan(['server/services/decks/leaf.js'])).toMatchObject({ full: false, db: true });
+
+ for (const importExpression of ["'./missing.js'", 'modulePath']) {
+ write(contract, "import '../services/bridge.js';\n");
+ write('server/services/bridge.js', `export const load = () => import(${importExpression});\n`);
+ expect(plan([leaf])).toMatchObject({ full: false, db: true });
+ }
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
describe('CI test impact planner', () => {
it('selects executable documentation tests, including contracts outside the always-run list', () => {
const paths = ['docs/features/product-surfaces.test.js', 'docs/example.test.js'];
diff --git a/scripts/lib/dbTestFiles.js b/scripts/lib/dbTestFiles.js
new file mode 100644
index 0000000000..8480b35106
--- /dev/null
+++ b/scripts/lib/dbTestFiles.js
@@ -0,0 +1,69 @@
+import { posix } from 'node:path';
+
+/**
+ * The DB-backed test files, relative to the Vitest root (server/). Exported
+ * as the single source of truth: the DB config's `include` uses it, and the drift
+ * guard in lib/db.guards.test.js imports it to assert no checkHealth()-gated
+ * suite is left out. `**\/db.test.js` only matches a file named exactly
+ * `db.test.js` — a `<name>.db.test.js` suite is NOT auto-included and must be
+ * listed explicitly below (the drift guard fails the build if you forget).
+ */
+export const DB_TEST_INCLUDE = [
+ 'services/voice/profiles.db.test.js',
+ 'services/voice/studio.db.test.js',
+ '../scripts/perf/collectionFixture.db.test.js',
+ 'services/appQuality.db.test.js',
+ '**/db.test.js',
+ 'services/codeAnimation/stages.db.test.js',
+ 'services/codeAnimation/sound.db.test.js',
+ 'services/codeAnimation/acceptance.db.test.js',
+ 'services/codeAnimation/stages.realBrowser.db.test.js',
+ 'services/mediaAssetIndex/galleryCollections.db.test.js',
+ 'services/dbAdmin.db.test.js',
+ 'services/backup.db.test.js',
+ 'services/catalogDB.test.js',
+ 'services/catalogDB.facets.db.test.js',
+ 'services/catalogDB.media.db.test.js',
+ 'services/catalogSync.tombstoneRevival.db.test.js',
+ 'services/catalogSync.pendingParents.db.test.js',
+ 'services/humanActivity.db.test.js',
+ 'services/postRunDb.db.test.js',
+ 'services/userActions.db.test.js',
+ 'services/memoryDB.db.test.js',
+ 'services/memorySync.db.test.js',
+ 'services/privacySubjects.db.test.js',
+ 'services/privacyVault.db.test.js',
+ 'services/privacyOrgs.db.test.js',
+ 'services/privacyChanges.db.test.js',
+ 'services/privacyBrokers.db.test.js',
+ 'services/privacyOptOut.db.test.js',
+ 'services/providerGraphStore.db.test.js',
+ 'services/catalogCanonProjection.test.js',
+ 'services/catalogRefResolver.test.js',
+ 'lib/db/schema/beeper.db.test.js',
+ 'services/beeperConversations.db.test.js',
+ 'services/beeperTribe.db.test.js',
+ 'services/tribe.db.test.js',
+ 'services/tribePurge.db.test.js',
+ 'services/beeperSync.db.test.js',
+ 'services/creativeDirector/projectsDB.test.js',
+ 'services/musicVideo/projectsDB.test.js',
+ 'routes/catalog.test.js',
+ 'routes/mindToolRecipes.db.test.js',
+ 'routes/decks.db.test.js',
+ 'services/decksSync.db.test.js',
+ 'services/modelPinRecords.db.test.js',
+ 'scripts/run-db-migrations.test.js',
+ 'scripts/migrateMemoryToPg.db.test.js',
+ 'lib/db/schema/audit.db.test.js',
+ 'lib/db/schema/syncFeed.db.test.js',
+];
+
+const patterns = DB_TEST_INCLUDE.map((pattern) => posix.normalize(posix.join('server', pattern)));
+const exactFiles = new Set(patterns.filter((pattern) => !pattern.includes('*')));
+const globs = patterns.filter((pattern) => pattern.includes('*'));
+
+/** Resolve the canonical, server-rooted include patterns without loading Vitest. */
+export const resolveDbTestFiles = (files) => files.filter((file) => (
+ exactFiles.has(file) || globs.some((pattern) => posix.matchesGlob(file, pattern))
+));
diff --git a/scripts/pregate.test.js b/scripts/pregate.test.js
index fb5f9f97da..254172f12c 100644
--- a/scripts/pregate.test.js
+++ b/scripts/pregate.test.js
@@ -120,7 +120,7 @@ describe('pregate hidden-content invocation', () => {
for (const path of [
'scripts/pregate.js', 'scripts/checkNodeVersion.js', 'scripts/scan-diff-hidden-content.js',
'scripts/ci-test-plan.js', 'scripts/ci-base-sha.js', 'server/lib/staticImportGraph.js',
- 'scripts/lib/directInvocation.js', 'scripts/lib/githubOutput.js',
+ 'scripts/lib/directInvocation.js', 'scripts/lib/githubOutput.js', 'scripts/lib/dbTestFiles.js',
'server/lib/diffHiddenContentScan.js', 'server/lib/modelAbuseGuard.js',
'server/lib/textUtils.js',
]) {
@@ -206,6 +206,16 @@ describe('pregate hidden-content invocation', () => {
expect(snapshot()).toEqual(before);
});
+ it('reports database validation for an excluded DB-only suite in a scoped working-tree plan', () => {
+ mkdirSync(join(root, 'server/routes'), { recursive: true });
+ write('server/routes/decks.db.test.js', "import { it } from 'vitest';\nit('db contract', () => {});\n");
+ const result = run('--plan-only');
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).toContain('CI will also run: db');
+ expect(result.stdout).toContain('npm run test:db');
+ expect(result.stdout).not.toContain('FULL suite');
+ });
+
it('preserves binary, empty-file, and stdin-like path findings for untracked additions', () => {
const emptyPath = 'docs/empty\u200B.md';
write(emptyPath, '');
@@ -406,7 +416,7 @@ describe('the gate end to end', () => {
for (const path of [
'scripts/pregate.js', 'scripts/checkNodeVersion.js', 'scripts/scan-diff-hidden-content.js',
'scripts/ci-test-plan.js', 'scripts/ci-base-sha.js', 'server/lib/staticImportGraph.js',
- 'scripts/lib/directInvocation.js', 'scripts/lib/githubOutput.js',
+ 'scripts/lib/directInvocation.js', 'scripts/lib/githubOutput.js', 'scripts/lib/dbTestFiles.js',
'server/lib/diffHiddenContentScan.js', 'server/lib/modelAbuseGuard.js',
'server/lib/textUtils.js',
]) {
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index 4d6b0e986d..7c1f90b5ea 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -1,4 +1,5 @@
import { defineConfig } from 'vitest/config';
+import { DB_TEST_INCLUDE } from '../scripts/lib/dbTestFiles.js';
// Same reason as vitest.config.js: an inherited NODE_ENV (PM2 exports
// 'development') is NOT overridden by vitest's own default, and the DB guards
@@ -6,64 +7,8 @@ import { defineConfig } from 'vitest/config';
// wherever it is launched from (#4554).
process.env.NODE_ENV = 'test';
-/**
- * The DB-backed test files, relative to this config's root (server/). Exported
- * as the single source of truth: this config's `include` uses it, and the drift
- * guard in lib/db.guards.test.js imports it to assert no checkHealth()-gated
- * suite is left out. `**\/db.test.js` only matches a file named exactly
- * `db.test.js` — a `<name>.db.test.js` suite is NOT auto-included and must be
- * listed explicitly below (the drift guard fails the build if you forget).
- */
-export const DB_TEST_INCLUDE = [
- 'services/voice/profiles.db.test.js',
- 'services/voice/studio.db.test.js',
- '../scripts/perf/collectionFixture.db.test.js',
- 'services/appQuality.db.test.js',
- '**/db.test.js',
- 'services/codeAnimation/stages.db.test.js',
- 'services/codeAnimation/sound.db.test.js',
- 'services/codeAnimation/acceptance.db.test.js',
- 'services/codeAnimation/stages.realBrowser.db.test.js',
- 'services/mediaAssetIndex/galleryCollections.db.test.js',
- 'services/dbAdmin.db.test.js',
- 'services/backup.db.test.js',
- 'services/catalogDB.test.js',
- 'services/catalogDB.facets.db.test.js',
- 'services/catalogDB.media.db.test.js',
- 'services/catalogSync.tombstoneRevival.db.test.js',
- 'services/catalogSync.pendingParents.db.test.js',
- 'services/humanActivity.db.test.js',
- 'services/postRunDb.db.test.js',
- 'services/userActions.db.test.js',
- 'services/memoryDB.db.test.js',
- 'services/memorySync.db.test.js',
- 'services/privacySubjects.db.test.js',
- 'services/privacyVault.db.test.js',
- 'services/privacyOrgs.db.test.js',
- 'services/privacyChanges.db.test.js',
- 'services/privacyBrokers.db.test.js',
- 'services/privacyOptOut.db.test.js',
- 'services/providerGraphStore.db.test.js',
- 'services/catalogCanonProjection.test.js',
- 'services/catalogRefResolver.test.js',
- 'lib/db/schema/beeper.db.test.js',
- 'services/beeperConversations.db.test.js',
- 'services/beeperTribe.db.test.js',
- 'services/tribe.db.test.js',
- 'services/tribePurge.db.test.js',
- 'services/beeperSync.db.test.js',
- 'services/creativeDirector/projectsDB.test.js',
- 'services/musicVideo/projectsDB.test.js',
- 'routes/catalog.test.js',
- 'routes/mindToolRecipes.db.test.js',
- 'routes/decks.db.test.js',
- 'services/decksSync.db.test.js',
- 'services/modelPinRecords.db.test.js',
- 'scripts/run-db-migrations.test.js',
- 'scripts/migrateMemoryToPg.db.test.js',
- 'lib/db/schema/audit.db.test.js',
- 'lib/db/schema/syncFeed.db.test.js',
-];
+// Compatibility export for the existing DB inventory guard.
+export { DB_TEST_INCLUDE } from '../scripts/lib/dbTestFiles.js';
/**
* DB-backed test config — runs ONLY the suites that talk to a real Postgres
@@ -79,11 +24,10 @@ export const DB_TEST_INCLUDE = [
* recognizes the `_test` suffix, so checkHealth() lets them connect and run
* (against the real `portos` DB they would skip — that's the safety guard).
*
- * The default `vitest.config.js` ALSO matches these files, but there they skip
- * (PGDATABASE is unset → resolves to non-test `portos`). So `npm test` never
- * runs them; `npm run test:db` does, after `npm run setup:db:test`.
+ * The default `vitest.config.js` excludes the same inventory, so `npm test`
+ * never runs them; `npm run test:db` does, after `npm run setup:db:test`.
*
- * Adding a new DB-backed test? Add it to `DB_TEST_INCLUDE` above — the
+ * Adding a new DB-backed test? Add it to `DB_TEST_INCLUDE` in scripts/lib/dbTestFiles.js — the
* `*.db.test.js` naming convention is documentation, not a glob match, so a new
* suite silently never runs until it's listed. db.guards.test.js fails if a
* checkHealth consumer is left out.
diff --git a/server/vitest.config.js b/server/vitest.config.js
index d9e76fddab..ce5b243908 100644
--- a/server/vitest.config.js
+++ b/server/vitest.config.js
@@ -1,7 +1,7 @@
import { defineConfig } from 'vitest/config';
import { fileURLToPath } from 'node:url';
import { vitestCaptureProjects, vitestCiPool } from '../scripts/vitestCiPool.js';
-import { DB_TEST_INCLUDE } from './vitest.config.db.js';
+import { DB_TEST_INCLUDE } from '../scripts/lib/dbTestFiles.js';
import { bootstrapVitestTempRoot } from '../scripts/lib/vitestTempRoot.js';
// `npm run test:fast` is the Windows-safe way to set the flag (a