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: clear VITEST when tests simulate a production store backend

[._.]/ Adam Eivy7da5f734509a
diff --git a/server/lib/README.md b/server/lib/README.md
index 4083bc7431..85a28874ee 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -362,7 +362,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `threejsModelPlayerSource.js` | `THREEJS_PLAYER_SOURCE` — the fixed clip-player source `buildThreejsFactorySource` emits into every exported Three.js module, giving a standalone consumer `createSculptAnimationPlayer(root, { onCue })` (plus `evaluateSculptClipPose` / `collectSculptCues`) over the node map and validated `animation` block the factory already carries. A STRING constant, not generated text: nothing provider-authored is interpolated into it, so the export stays data-plus-PortOS-code. It takes `update(deltaSeconds)` from the host render loop rather than owning one, scrubs silently and fires cues only on playback (mirroring the preview), and clones a shared material before driving `opacity`. Semantics mirror `client/src/lib/threejsAnimation.js` — change one and change the other. |
| `threejsModelRig.js` | `evaluateThreejsRigReadiness(spec)` — honest rig-readiness report over an already-validated Three.js spec: `{ articulationReady, reasons, jointCount, socketCount, attachmentCount, anchoredAttachmentCount, unanchoredAttachmentCount, rootJointId, subjectType }`. The schema proves the optional `articulation` graph is well *formed* (one root, no cycles or forward refs, joints and pivots pointed at real parts/sockets); this reports whether it is *useful* (more than a lone root, every child joint carrying a pivot axis, every declared attachment naming what it hangs from) and names the reason when it is not. It reports rather than rejects, and never claims skinning: PortOS generates static assemblies and declared articulation intent, not skeletons or bind poses. |
| `threejsTransform.js` | Affine transform primitives shared by every server-side gate that reconstructs where a Three.js scene-spec part sits in the world — `rotationMatrix` (row-major 3×3 matching `THREE.Euler` order `XYZ`, the composition the preview canvas and exported factory both apply), `scaleLinear`, `multiplyLinear`, `applyLinear`, `applyTransform`, `composeTransform(parent, { position, rotationDegrees, scale })`, `vectorLength`, `degreesToRadians`, `IDENTITY_LINEAR` / `IDENTITY_TRANSFORM`. One owner for math `threejsModel.js`, `threejsModelPenetration.js` and `threejsModelPhysicalAudit.js` each used to spell separately. A non-finite rotation component reads as `0` degrees and a non-finite scale component as `1`, matching what the renderer does with a malformed stored spec — feeding `null`/`NaN` through instead produced `NaN` bounds that the audits read as "no overlap" and "no defect". |
-| `pgFileFacade.js` | Shared PG/file store-backend backbone for the six storage dispatchers (pipeline series/issues, story builder, universe builder, catalog user-types, writers room). `isFileBackend()` (dev/test escape-hatch predicate) · `resolvePgBackend({ requirement, migrate?, loadDb, makePg })` (health-check → `ensureSchema` → one-time migration → import `db.js` → build the PG backend) · `createPgFileFacade({ makeFile, makePg })` (promise-memoized lazy selection so concurrent first calls don't run the migration twice; returns `{ getBackend, getBackendName, reset }`). Each store keeps its own `makeFile`/`makePg` factories + public surface. `createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? })` wraps the same backbone for the stores whose backends are whole MODULES rather than built objects (Creative Director, Music Video, Sprites) → `{ selectBackend, getBackendName }` where the name is `'file'`/`'postgres'`; `isTestMode` lets a store use the stronger `isTestRunner()` signal (Sprites). |
+| `pgFileFacade.js` | Shared PG/file store-backend backbone for the six storage dispatchers (pipeline series/issues, story builder, universe builder, catalog user-types, writers room). `isFileBackend()` (dev/test escape-hatch predicate) · `resolvePgBackend({ requirement, migrate?, loadDb, makePg })` (health-check → `ensureSchema` → one-time migration → import `db.js` → build the PG backend) · `createPgFileFacade({ makeFile, makePg })` (promise-memoized lazy selection so concurrent first calls don't run the migration twice; returns `{ getBackend, getBackendName, reset }`). Each store keeps its own `makeFile`/`makePg` factories + public surface. `createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? })` wraps the same backbone for the stores whose backends are whole MODULES rather than built objects (Creative Director, Music Video, Sprites) → `{ selectBackend, getBackendName }` where the name is `'file'`/`'postgres'`; `isFileBackend()` is `MEMORY_BACKEND=file` or `isTestRunner()`; `isTestMode` replaces that test signal (Sprites passes `isTestRunner()`). |
| `multipart.js` | Streaming multipart/form-data parser. |
| `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. `classifyLoraKeyLayoutFromHeader(header)` / `classifyLoraKeyLayout(path)` classify the key layout as `LORA_KEY_LAYOUTS` (`bare` / `comfyui` / `diffusers` / `kohya` / `not_a_lora`, `null` = unreadable), `isKnownLoraKeyLayout(layout)` validates a layout read back out of persisted state, and `videoLoraLayoutIssue(layout)` returns the user-facing reason a layout can't fuse into the LTX-2 video transformer (or `null` when it can). |
| `loraEffect.js` | LoRA adapter-effect report rules — the JS half of the `scripts/lora_effect_probe.py` diagnostic (#4872). `client/src/lib/loraEffect.js` re-exports `LORA_EFFECT_STATUSES` from here; `loraEffect.test.js` holds `LORA_EFFECT_PROBE_VERSION` in lockstep with the probe`s `PROBE_VERSION` — drift silently disables the cache. `LORA_EFFECT_STATUSES` (`ok`/`zero`/`nonfinite`/`unreadable`/`unmeasurable`) + `isKnownLoraEffectStatus`; `normalizeLoraEffectReport(raw,{sizeBytes,mtimeMs,measuredAt})` coerces every non-finite number to `null`, drops statistics when nothing was measured so "no data" can never read as "measured 0.0", and downgrades a `zero` status that no measurement backs; `readCachedLoraEffectReport(raw,{sizeBytes,mtimeMs})` returns a stored report only while its probe version, file size AND mtime all still match, which is what lets `listLoras()` surface one without ever spawning a probe; `loraEffectIssue(report)` is the user-facing refusal phrase for a measured entirely-zero adapter and `null` for EVERY other status; `formatLoraEffect(report)` is the one-line log/UI summary. |
diff --git a/server/lib/pgFileFacade.js b/server/lib/pgFileFacade.js
index 2dbe8598c0..84a9e97845 100644
--- a/server/lib/pgFileFacade.js
+++ b/server/lib/pgFileFacade.js
@@ -102,13 +102,12 @@ export function createPgFileFacade({ makeFile, makePg, isFile = isFileBackend })
* may be called before the boot DB gate, e.g. CD's boot recovery scan), runs the
* optional one-time migration, then loads the PG module.
*
- * Test-mode detection stays per-store (`isTestMode`) because the stores
- * genuinely differ today: Sprites keys on `isTestRunner()` (`NODE_ENV==='test'`
- * OR `VITEST` — the stronger signal), CD/Music Video on `isTestRunner()` too
- * via the shared `isFileBackend()`. Unifying on `isTestRunner()` would be a
- * strengthening, but it changes what their existing backend-selection suites
- * observe (vitest always sets `VITEST`), so semantics are preserved exactly here
- * and the unification is left as a separate decision.
+ * The default escape hatch is `isFileBackend()`: `MEMORY_BACKEND=file` or
+ * `isTestRunner()` (`NODE_ENV==='test'` OR `VITEST` is set). A store may pass
+ * `isTestMode` to replace that test signal; the file escape hatch is still
+ * OR-ed in. Sprites passes `isTestRunner`, which matches the default. Vitest
+ * always sets `VITEST`, so a suite that wants Postgres must clear it — setting
+ * `NODE_ENV` away from `test` is not enough.
*
* @param {object} opts
* @param {string} [opts.label] Store name used in the default unreachable-DB error.
@@ -116,7 +115,7 @@ export function createPgFileFacade({ makeFile, makePg, isFile = isFileBackend })
* @param {() => Promise<object>} opts.loadDbBackend Loader for the PostgreSQL backend module.
* @param {string} [opts.requireDbMessage] Override for the unreachable-DB error message.
* @param {() => boolean} [opts.isTestMode] Test-mode predicate; when omitted the shared
- * `isFileBackend()` (MEMORY_BACKEND=file OR NODE_ENV=test) is used as-is.
+ * `isFileBackend()` (`MEMORY_BACKEND=file` OR `isTestRunner()`) is used as-is.
* @param {() => Promise<void>} [opts.onDbReady] One-time migration run after `ensureSchema()`
* and before the DB backend import (CD's legacy JSON → table import).
* @returns {{ selectBackend: () => Promise<object>, getBackendName: () => ('file'|'postgres'|null) }}
diff --git a/server/lib/pgFileFacade.test.js b/server/lib/pgFileFacade.test.js
index fa33c13435..05b2a769f9 100644
--- a/server/lib/pgFileFacade.test.js
+++ b/server/lib/pgFileFacade.test.js
@@ -23,11 +23,13 @@ describe('isFileBackend', () => {
it('is true under NODE_ENV=test', () => {
process.env.NODE_ENV = 'test';
delete process.env.MEMORY_BACKEND;
+ delete process.env.VITEST;
expect(isFileBackend()).toBe(true);
});
it('is true under MEMORY_BACKEND=file even when not test', () => {
process.env.NODE_ENV = 'production';
+ delete process.env.VITEST;
process.env.MEMORY_BACKEND = 'file';
expect(isFileBackend()).toBe(true);
});
@@ -45,6 +47,13 @@ describe('isFileBackend', () => {
process.env.VITEST = 'true';
expect(isFileBackend()).toBe(true);
});
+
+ it('is true when VITEST is set even if NODE_ENV is production', () => {
+ process.env.NODE_ENV = 'production';
+ delete process.env.MEMORY_BACKEND;
+ process.env.VITEST = '1';
+ expect(isFileBackend()).toBe(true);
+ });
});
describe('createPgFileFacade', () => {
@@ -169,6 +178,7 @@ describe('createRecordStoreBackendSelector', () => {
it('selects the file backend under MEMORY_BACKEND=file outside test mode', async () => {
process.env.NODE_ENV = 'production';
+ delete process.env.VITEST;
process.env.MEMORY_BACKEND = 'file';
const { loadFileBackend, loadDbBackend } = loaders();
const { selectBackend, getBackendName } = createRecordStoreBackendSelector({ label: 'Demo', loadFileBackend, loadDbBackend });
@@ -179,6 +189,7 @@ describe('createRecordStoreBackendSelector', () => {
it('honors a custom isTestMode predicate (the isTestRunner posture) and keeps the file escape hatch', async () => {
process.env.NODE_ENV = 'production';
+ delete process.env.VITEST;
delete process.env.MEMORY_BACKEND;
const { loadFileBackend, loadDbBackend } = loaders();
const { selectBackend, getBackendName } = createRecordStoreBackendSelector({
diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.js
index 299924a586..0a4f6b6491 100644
--- a/server/services/creativeDirector/local.js
+++ b/server/services/creativeDirector/local.js
@@ -10,8 +10,10 @@
* Backend selection (same posture as the memory backend):
* - PostgreSQL (projectsDB.js) for normal installs.
* - File (projectsFile.js) only via MEMORY_BACKEND=file (escape hatch) or
- * NODE_ENV=test — both UNSUPPORTED for production. Tests boot without a DB,
- * so they exercise the file backend and need no Postgres.
+ * isTestRunner() (NODE_ENV=test OR VITEST) — both UNSUPPORTED for
+ * production. Tests boot without a DB, so they exercise the file backend
+ * and need no Postgres. A suite that simulates production must clear
+ * VITEST; Vitest sets it in every worker.
*
* The first PG init runs a one-time, marker-gated import of any legacy
* data/creative-director-projects.json rows into the table (see
diff --git a/server/services/creativeDirector/localBackend.test.js b/server/services/creativeDirector/localBackend.test.js
index 5bb3cd94f1..282bceaefe 100644
--- a/server/services/creativeDirector/localBackend.test.js
+++ b/server/services/creativeDirector/localBackend.test.js
@@ -1,10 +1,12 @@
/**
* Backend-selection tests for the Creative Director dispatcher (local.js).
*
- * Mirrors memoryBackend's contract: file backend under MEMORY_BACKEND=file or
- * NODE_ENV=test; Postgres otherwise (gated on a healthy DB). We assert the
- * SELECTION, not the storage round-trip — the file/PG round-trips are covered
- * by local.test.js (file) and projectsDB.test.js (PG, skip-if-no-DB).
+ * File backend under MEMORY_BACKEND=file or isTestRunner() (NODE_ENV=test OR
+ * VITEST); Postgres otherwise (gated on a healthy DB). Cases that simulate
+ * production clear VITEST — Vitest sets it in every worker, and leaving it
+ * set selects the file backend. We assert the SELECTION, not the storage
+ * round-trip — the file/PG round-trips are covered by local.test.js (file)
+ * and projectsDB.test.js (PG, skip-if-no-DB).
*
* vi.resetModules() + dynamic re-import isolates the module-level backend cache
* between cases (same approach as memoryBackend.test.js).
@@ -35,9 +37,16 @@ beforeEach(() => {
afterEach(() => { process.env = { ...ORIG_ENV }; });
+function leaveTestRunner() {
+ process.env.NODE_ENV = 'production';
+ delete process.env.VITEST;
+ delete process.env.MEMORY_BACKEND;
+}
+
describe('local.js backend selection', () => {
it('uses the file backend under NODE_ENV=test', async () => {
process.env.NODE_ENV = 'test';
+ delete process.env.VITEST;
delete process.env.MEMORY_BACKEND;
const local = await import('./local.js');
expect(await local.listProjects()).toEqual(['file']);
@@ -46,16 +55,25 @@ describe('local.js backend selection', () => {
});
it('uses the file backend under MEMORY_BACKEND=file even when not in test mode', async () => {
- process.env.NODE_ENV = 'production';
+ leaveTestRunner();
process.env.MEMORY_BACKEND = 'file';
const local = await import('./local.js');
expect(await local.listProjects()).toEqual(['file']);
expect(local.getProjectsBackendName()).toBe('file');
});
- it('uses Postgres (ensureSchema + import) when DB is healthy and not in test/file mode', async () => {
+ it('uses the file backend when VITEST is set even if NODE_ENV is production', async () => {
process.env.NODE_ENV = 'production';
+ process.env.VITEST = '1';
delete process.env.MEMORY_BACKEND;
+ const local = await import('./local.js');
+ expect(await local.listProjects()).toEqual(['file']);
+ expect(local.getProjectsBackendName()).toBe('file');
+ expect(checkHealth).not.toHaveBeenCalled();
+ });
+
+ it('uses Postgres (ensureSchema + import) when DB is healthy and not in test/file mode', async () => {
+ leaveTestRunner();
checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
const local = await import('./local.js');
expect(await local.listProjects()).toEqual(['db']);
@@ -65,8 +83,7 @@ describe('local.js backend selection', () => {
});
it('throws when Postgres is required but unreachable', async () => {
- process.env.NODE_ENV = 'production';
- delete process.env.MEMORY_BACKEND;
+ leaveTestRunner();
checkHealth.mockResolvedValue({ connected: false, error: 'ECONNREFUSED' });
const local = await import('./local.js');
await expect(local.listProjects()).rejects.toThrow(/requires PostgreSQL/);
@@ -74,8 +91,7 @@ describe('local.js backend selection', () => {
});
it('caches the backend after first selection (one health check)', async () => {
- process.env.NODE_ENV = 'production';
- delete process.env.MEMORY_BACKEND;
+ leaveTestRunner();
checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
const local = await import('./local.js');
await local.listProjects();