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

address review (codex): fail boot on mandatory store warmup failure, skip embedding defaultModel, probe last init-db table

Adam Eivyd31ed37ad023
diff --git a/scripts/setup-db.js b/scripts/setup-db.js
index ea71ea2709..22d56c0cdc 100644
--- a/scripts/setup-db.js
+++ b/scripts/setup-db.js
@@ -141,17 +141,22 @@ function isPortOSDbReady(port = PG_PORT_NATIVE) {
// Whether the Docker container has finished applying init-db.sql. pg_isready
// only proves the server accepts connections — it can pass while the
-// docker-entrypoint-initdb.d schema load is still running, so the `memories`
-// table (and the rest of the required schema) may not exist yet. Probing the
-// schema inside the container avoids reporting "ready" to a server that would
-// then fail-fast on its own boot-time schema gate. `psql -tAc` exits 0 even on
-// an empty result, so we require the literal "1".
+// docker-entrypoint-initdb.d schema load is still running, so the schema may
+// not exist yet. Probing the schema inside the container avoids reporting
+// "ready" to a server that would then fail-fast on its own boot-time schema
+// gate. We probe the LAST table created by init-db.sql (writers_room_exercises),
+// NOT an early one like `memories`: the entrypoint applies the file top-to-bottom
+// in a single connection, so the last table existing proves the whole 800-line
+// schema landed — probing `memories` (first table) would report ready while the
+// later store tables (#1014–1017) are still being created, letting `npm start`
+// race a half-applied schema. `psql -tAc` exits 0 even on an empty result, so we
+// require the literal "1".
function isDockerSchemaReady() {
try {
const output = execFileSync(
'docker',
['compose', 'exec', '-T', 'db', 'psql', '-X', '-U', 'portos', '-d', 'portos', '-tAc',
- "SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'memories' LIMIT 1"],
+ "SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'writers_room_exercises' LIMIT 1"],
{ stdio: 'pipe', cwd: rootDir }
).toString();
return output.trim() === '1';
diff --git a/server/index.js b/server/index.js
index 0a2cf5d049..bc550f7dd8 100644
--- a/server/index.js
+++ b/server/index.js
@@ -865,63 +865,67 @@ ensureSelf()
// queryable index over them. Idempotent, safe to run every boot.
const { initMediaAssetIndex } = await import('./services/mediaAssetIndex/index.js');
await initMediaAssetIndex();
- // Universe Builder PG warm (#1014): with the DB confirmed + schema ensured,
- // touch the universe store so it selects the Postgres backend and runs the
- // one-time data/universes file→DB import (migrateUniversesToDB) BEFORE
- // httpServer.listen — so the first request/sync sees migrated records, not
- // a half-applied import racing a request. listIds() is the cheapest call
- // that forces backend selection. Idempotent (marker-gated import).
- await universeStore().listIds();
- // Pipeline series + issues PG warm (#1015): same contract as the universe
- // warm — touch each store so it selects Postgres and runs its one-time
- // file→DB import (migrateSeriesToDB / migrateIssuesToDB) BEFORE
- // httpServer.listen, so the first request/sync sees migrated records.
- // Series first (issues soft-ref it for universe resolution / lists).
- await seriesStore().listIds();
- await issueStore().listIds();
- // Story Builder sessions PG warm (#1016): same contract — touch the store
- // so it selects Postgres and runs its one-time file→DB import
- // (migrateStoryBuilderToDB) BEFORE httpServer.listen, so the first
- // request/sync sees migrated sessions. Universe + series warmed first
- // (sessions soft-ref both for the staleness recompute / linked-record view).
- await storyBuilderStore().listIds();
- // Writers Room PG warm (#1017): same contract — touch the store so it
- // selects Postgres and runs its one-time file→DB import
- // (migrateWritersRoomToDB) BEFORE httpServer.listen. listWorkIds() is the
- // cheapest call that forces backend selection. The draft .md bodies stay on
- // disk (file-primary); only the metadata migrates. Idempotent (marker-gated).
- await writersRoomStore().listWorkIds();
- // Authoritative catalog user-type warm (#1001): with the DB confirmed +
- // schema ensured, load the registry from the catalog_user_types store
- // (running the one-time settings→DB import on first access). This runs
- // BEFORE httpServer.listen, so a normal install always serves with the
- // registry warm even if the early fire-and-forget warm above raced a cold
- // DB. Idempotent with that early warm (same setUserCatalogTypes result).
- const warmTypes = await readUserTypeSlice();
- setUserCatalogTypes(Array.isArray(warmTypes) ? warmTypes : []);
- // Creative Director PG warm (#997): unlike the other stores, CD's file→DB
- // import (migrateCreativeDirectorToDB) is triggered lazily on first
- // backend access, and at boot the only trigger is the fire-and-forget
- // recoverInFlightProjects() in an earlier .then() — NOT awaited, so it can
- // still be in flight here. The prune below stamps a single completion
- // marker once no domain is blocked, so it must not run while CD's import
- // (and its creative-director-projects.migrated.json marker) is unfinished,
- // or CD's .imported file would never be pruned. listProjects() forces
- // selectBackend() → the (idempotent, marker-gated) import to completion.
- const { listProjects: warmCdProjects } = await import('./services/creativeDirector/local.js');
- await warmCdProjects();
- // Legacy artifact prune: runs LAST, after every file→DB warm above has
- // imported + stamped its marker, so both the migration markers AND the
- // authoritative DB rows exist. Removes the `.imported` / `.bak-NNN`
- // recovery copies the migrators parked aside, but ONLY when the live row
- // count matches the marker's recorded import (a wiped/restored DB keeps
- // the recovery files). Marker-gated in data/legacy-prune.applied.json;
- // never runs under the file escape hatch (gated by the dbReady block).
- const { pruneImportedLegacyFiles } = await import('./scripts/pruneImportedLegacyFiles.js');
- await pruneImportedLegacyFiles();
} catch (err) {
console.error(`🪄 catalog migrations failed at boot: ${err.message}`);
}
+
+ // Mandatory PostgreSQL store warmups (#1014–1017, #1001, #997) + legacy
+ // prune. Each touch forces backend selection and runs a one-time, marker-
+ // gated file→DB import that MUST complete before httpServer.listen — so the
+ // first request/sync sees fully-migrated records, never a half-applied
+ // import racing a request. Unlike the best-effort catalog migrations above
+ // (which log-and-continue), a failure here is FATAL: a store that couldn't
+ // select its backend or finish its import would serve unmigrated/empty data,
+ // which is worse than a hard stop. So this gets its own try/catch (a process
+ // boundary, like runDbMigrations above) that exits loudly instead of
+ // swallowing the error and booting a partially-migrated install. Skipped
+ // when not dbReady (escape hatch), matching the early return above.
+ if (dbReady) {
+ try {
+ // Universe Builder PG warm (#1014): listIds() is the cheapest call that
+ // forces backend selection + the migrateUniversesToDB import.
+ await universeStore().listIds();
+ // Pipeline series + issues PG warm (#1015): same contract. Series first
+ // (issues soft-ref it for universe resolution / lists).
+ await seriesStore().listIds();
+ await issueStore().listIds();
+ // Story Builder sessions PG warm (#1016): same contract. Universe +
+ // series warmed first (sessions soft-ref both for staleness recompute).
+ await storyBuilderStore().listIds();
+ // Writers Room PG warm (#1017): listWorkIds() forces backend selection +
+ // migrateWritersRoomToDB. Draft .md bodies stay on disk (file-primary);
+ // only the metadata migrates.
+ await writersRoomStore().listWorkIds();
+ // Authoritative catalog user-type warm (#1001): load the registry from
+ // the catalog_user_types store (runs the one-time settings→DB import on
+ // first access), so a normal install always serves with the registry
+ // warm even if the early fire-and-forget warm raced a cold DB.
+ const warmTypes = await readUserTypeSlice();
+ setUserCatalogTypes(Array.isArray(warmTypes) ? warmTypes : []);
+ // Creative Director PG warm (#997): unlike the other stores, CD's file→DB
+ // import is triggered lazily on first backend access; at boot the only
+ // other trigger is a NOT-awaited fire-and-forget recoverInFlightProjects()
+ // in an earlier .then(), so it can still be in flight here. The prune
+ // below stamps a single completion marker once no domain is blocked, so
+ // it must not run while CD's import (and its
+ // creative-director-projects.migrated.json marker) is unfinished, or CD's
+ // .imported file would never be pruned. listProjects() forces
+ // selectBackend() → the (idempotent, marker-gated) import to completion.
+ const { listProjects: warmCdProjects } = await import('./services/creativeDirector/local.js');
+ await warmCdProjects();
+ // Legacy artifact prune: runs LAST, after every file→DB warm above has
+ // imported + stamped its marker, so both the migration markers AND the
+ // authoritative DB rows exist. Removes the `.imported` / `.bak-NNN`
+ // recovery copies the migrators parked aside, but ONLY when the live row
+ // count matches the marker's recorded import (a wiped/restored DB keeps
+ // the recovery files). Marker-gated in data/legacy-prune.applied.json.
+ const { pruneImportedLegacyFiles } = await import('./scripts/pruneImportedLegacyFiles.js');
+ await pruneImportedLegacyFiles();
+ } catch (err) {
+ console.error(`❌ Mandatory store warmup failed at boot — refusing to start: ${err?.stack ?? err.message}`);
+ process.exit(1);
+ }
+ }
})
.then(() => {
// Start server only after sync log + media job queue are initialized.
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index 01069ed3b7..aaf16ca258 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -107,13 +107,28 @@ export const providerHonorsModelOverride = (provider) => (
*/
export function resolveEffectiveModel(provider, callerModel) {
if (providerHonorsModelOverride(provider)) {
- return callerModel || provider?.defaultModel || firstGenerationModel(provider) || null;
+ // A stale config can leave an embedding-only id in callerModel/defaultModel
+ // (the UI only hides+clears embedding models when the provider is edited);
+ // skip those so an unchanged older provider can't route a generation/fallback
+ // run to e.g. nomic-embed-text. Falls through to the first generation model.
+ return firstNonEmbedding(callerModel, provider?.defaultModel)
+ || firstGenerationModel(provider) || null;
}
// Non-honoring CLI/TUI path: args-baked model id wins over defaultModel.
const baked = (provider?.type === PROVIDER_TYPES.CLI || provider?.type === PROVIDER_TYPES.TUI) && hasModelFlag(provider?.args)
? extractBakedModel(provider.args)
: null;
- return baked || provider?.defaultModel || firstGenerationModel(provider) || null;
+ return firstNonEmbedding(baked, provider?.defaultModel)
+ || firstGenerationModel(provider) || null;
+}
+
+/**
+ * First of the given candidate model ids that is a usable generation model
+ * (skips null/empty and embedding-only ids). Returns null when none qualify, so
+ * callers can fall through to `firstGenerationModel(provider)`.
+ */
+function firstNonEmbedding(...candidates) {
+ return candidates.find((m) => m && isGenerationModel(m)) || null;
}
/**
diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.js
index 9275b4bc42..fd748f7a6b 100644
--- a/server/lib/promptRunner.test.js
+++ b/server/lib/promptRunner.test.js
@@ -1114,6 +1114,19 @@ describe('resolveEffectiveModel — embedding-model skip', () => {
const p = { id: 'ollama', type: 'api', defaultModel: null, models: ['nomic-embed-text:latest', 'mxbai-embed-large'] };
expect(resolveEffectiveModel(p, null)).toBe('nomic-embed-text:latest');
});
+
+ it('skips a stale embedding-only defaultModel (older config the UI never re-edited)', () => {
+ // A pre-existing local provider can carry an embedding id in defaultModel;
+ // a generation/fallback run must not route to it — fall through to the
+ // first generation model in the list.
+ const p = { id: 'ollama', type: 'api', defaultModel: 'nomic-embed-text:latest', models: ['nomic-embed-text:latest', 'qwen3.6:35b'] };
+ expect(resolveEffectiveModel(p, null)).toBe('qwen3.6:35b');
+ });
+
+ it('skips an embedding-only callerModel and falls through to a generation model', () => {
+ const p = { id: 'ollama', type: 'api', defaultModel: 'qwen3.6:35b', models: ['nomic-embed-text:latest', 'qwen3.6:35b'] };
+ expect(resolveEffectiveModel(p, 'nomic-embed-text:latest')).toBe('qwen3.6:35b');
+ });
});
describe('resolveProviderAndModel', () => {