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
refactor: extract bootstrap's load-bearing boot order into a testable, injected sequence (#3451)
[._.]/ Adam Eivyd3ae21ff5f6f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 323982abae..9bd910ffd0 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,6 +20,8 @@- **Covered the production memory backend, which had zero tests.** `server/services/memoryDB.js` — the Postgres + pgvector backend every real install runs — had no suite at all; the only "memory" coverage was `memory.test.js`, which exercises the dev/test-only file backend. The new `server/services/memoryDB.db.test.js` runs against the throwaway `portos_test` database via `npm run test:db` and covers the CRUD/embedding round-trip, listing filters and stats, `searchMemories`/`hybridSearchMemories` (vector, full-text and fused rankings, plus zero-result queries proven to be searched-and-empty rather than never-searched), `consolidateMemories` cluster merging, `applyDecay` boundaries (the 30-day archive gate, the 0.15 cut-off and the 0.1 importance floor), and `getGraphData`'s node/edge shape. It caught one live bug: `createMemory` echoed a wrong-dimension embedding back to the caller even though the column had stored NULL, so a re-embed check gated on the returned value would skip the record — it now mirrors `updateMemoryEmbedding` and returns `null`.+- **The boot order every install depends on is now executed by tests instead of only described in comments.** `server/services/bootstrap.js` opened with "ordering inside each phase is load-bearing" — and nothing tested it: the file can't be imported under test (it pulls the whole service graph and its steps open a listener, a database, and agent workers), so `bootstrapServices()` and `runBootSequence()` had no regression net at all. The ordering now lives in `server/services/bootstrapSequence.js`, which imports nothing and takes every step as a parameter; `bootstrap.js` supplies the real migration runner, toolkit, stores and listener, and the sequence module decides when each runs. 41 new tests assert the recorded call sequence — migrations before the toolkit reads its config, sync log before brain recovery appends to it, the media job queue before its completion hooks, the whole database phase before `listen()` — plus which steps are awaited and which are deliberately fire-and-forget, the fatal-vs-log-and-continue split at each failure point, and a source guard that fails if any AI-provider entry point is ever invoked from the boot path (CLAUDE.md "No cold-bootstrap LLM calls").+## Fixed- **`PUT /api/lmstudio/config` validated nothing.** It read `baseUrl`/`timeout`/`defaultThinkingModel` straight off `req.body`, and `updateConfig()` assigned any truthy value into module-level config that every other LM Studio call then interpolates into fetch URLs — so one malformed request degraded local-LLM connectivity until restart. All eight routes in the file now validate through `lib/validation.js` schemas, matching the rest of `server/routes/`. The schemas are non-`.strict()`, so incidental extra fields still pass through.diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex a2ef065067..35fa959403 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -12,8 +12,11 @@* ends in `httpServer.listen()`.* 3. `registerShutdownHandlers()` — the graceful-shutdown state machine.*- * Ordering inside each phase is load-bearing and documented inline — read the- * comments before reordering anything.+ * Ordering inside each phase is load-bearing. It lives in `bootstrapSequence.js`+ * — a dependency-injected, service-free module — so it can be executed and+ * asserted under test (#3451) without opening a listener or touching a real+ * database. This file supplies the real implementations; that file decides when+ * each one runs and which are awaited. Read both before reordering anything.** NOTE (CLAUDE.md "No cold-bootstrap LLM calls"): nothing in this file may* queue an AI provider call. Boot only loads on-disk state and ARMS schedulers;@@ -32,6 +35,18 @@ import { markHostShuttingDown, writeHostShutdownMarker } from '../lib/hostShutdoimport { setUserCatalogTypes } from '../lib/catalogTypes.js';import { runMigrations } from '../../scripts/run-migrations.js';+import {+ runPreRouteSequence,+ runPostRouteSequence,+ runPostListenSequence,+ runDatabasePhase,+ gateOnDatabase,+ runDbAndCatalogMigrations,+ warmMandatoryStores,+ initCosAfterSpawner,+ armCommissionScheduler+} from './bootstrapSequence.js';+import { ensureBackendProvider, getBackend as getLocalLlmBackend } from './localLlm.js';import { ensureProviderReady as ensureOllamaProviderReady, ensureRunning as ensureOllamaRunning } from './ollamaManager.js';import { recordSession } from './usage.js';@@ -131,32 +146,6 @@ import * as gameStore from './games/store.js';* `runBootSequence` below.*/export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverDir }) => {- // Apply pending data migrations BEFORE the AI toolkit reads stage-config.json- // and providers.json. Without this, a plain pull-and-restart (no update.sh)- // leaves new prompt stages and other shipped data changes unregistered —- // existing installs hit "Stage X not found" until the user manually runs- // `npm run migrations` or `npm run update`. Idempotent and cheap when the- // applied-list is already current.- // Prefer PORTOS_DATA_ROOT (set at real launch in ecosystem.config.cjs) over the- // import.meta.url-derived path so a server booted from inside a CoS agent- // worktree still resolves to the real install; runMigrations also skips a- // worktree-rooted path as a backstop (#1947).- await runMigrations({ rootDir: resolveInstallRoot(join(serverDir, '..')) }).catch(err => {- // Log the full stack (or stringified err for non-Error throws) so failures- // during boot are diagnosable without rerunning under a debugger.- console.error(`❌ Migration run failed at startup: ${err?.stack ?? err}`);- });-- // Verify every registered collection's on-disk type-level schemaVersion- // matches what the code expects. Mismatches mean a migration didn't run (or- // the user rolled the code back below a forward-only migration) — log loudly- // but DO NOT crash the server. PortOS is single-user (CLAUDE.md "Security- // Model"); a hard exit on startup is worse than a noisy log the user can act- // on. Returns per-store statuses for downstream telemetry; we discard them.- await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore(), loraDatasetStore, liOutcomesStore(), commissionStore(), gameStore, ...brainCollectionStores()]).catch(err => {- console.error(`❌ Collection version check failed at startup: ${err?.stack ?? err}`);- });-// Lifecycle hooks shared between AI Toolkit and PortOS runner shimconst aiToolkitHooks = {ensureProviderReady: (provider) => ensureOllamaProviderReady(provider),@@ -206,78 +195,95 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD}};- // Initialize AI Toolkit with PortOS configuration and hooks- const aiToolkit = createAIToolkit({- dataDir,- providersFile: 'providers.json',- runsDir: 'runs',- promptsDir: 'prompts',- screenshotsDir: join(dataDir, 'screenshots'),- sampleProvidersFile: join(dataReferenceDir, 'providers.json'),- io,- asyncHandler,- // Inject PortOS's ServerError so toolkit route errors normalize into the- // canonical `{ error, code, timestamp, context? }` envelope (issue #1084).- ServerError,- hooks: aiToolkitHooks- });+ // The ORDER these run in is `runPreRouteSequence`'s contract (see+ // bootstrapSequence.js); this object is only the "what".+ return runPreRouteSequence({+ // Apply pending data migrations BEFORE the AI toolkit reads stage-config.json+ // and providers.json. Without this, a plain pull-and-restart (no update.sh)+ // leaves new prompt stages and other shipped data changes unregistered —+ // existing installs hit "Stage X not found" until the user manually runs+ // `npm run migrations` or `npm run update`. Idempotent and cheap when the+ // applied-list is already current.+ // Prefer PORTOS_DATA_ROOT (set at real launch in ecosystem.config.cjs) over the+ // import.meta.url-derived path so a server booted from inside a CoS agent+ // worktree still resolves to the real install; runMigrations also skips a+ // worktree-rooted path as a backstop (#1947).+ applyDataMigrations: () => runMigrations({ rootDir: resolveInstallRoot(join(serverDir, '..')) }),++ // Verify every registered collection's on-disk type-level schemaVersion+ // matches what the code expects. Mismatches mean a migration didn't run (or+ // the user rolled the code back below a forward-only migration) — log loudly+ // but DO NOT crash the server. PortOS is single-user (CLAUDE.md "Security+ // Model"); a hard exit on startup is worse than a noisy log the user can act+ // on. Returns per-store statuses for downstream telemetry; we discard them.+ verifyCollections: () => verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore(), loraDatasetStore, liOutcomesStore(), commissionStore(), gameStore, ...brainCollectionStores()]),++ createToolkit: () => createAIToolkit({+ dataDir,+ providersFile: 'providers.json',+ runsDir: 'runs',+ promptsDir: 'prompts',+ screenshotsDir: join(dataDir, 'screenshots'),+ sampleProvidersFile: join(dataReferenceDir, 'providers.json'),+ io,+ asyncHandler,+ // Inject PortOS's ServerError so toolkit route errors normalize into the+ // canonical `{ error, code, timestamp, context? }` envelope (issue #1084).+ ServerError,+ hooks: aiToolkitHooks+ }),++ // Compatibility shims for services that import from the old service files.+ registerToolkitShims: (aiToolkit) => {+ setProvidersToolkit(aiToolkit);+ setRunnerToolkit(aiToolkit, { dataDir, hooks: aiToolkitHooks });+ setPromptsToolkit(aiToolkit);+ // Note: the prompts service is initialized automatically by createAIToolkit().+ },- // Initialize compatibility shims for services that import from old service files- setProvidersToolkit(aiToolkit);- setRunnerToolkit(aiToolkit, { dataDir, hooks: aiToolkitHooks });- setPromptsToolkit(aiToolkit);-- // Warm the providers file at startup so the codex-sentinel migration runs- // before any inbound request can hit the providers cache. Awaited so the- // migration write completes deterministically before request handlers- // start consulting providers state.- await aiToolkit.services.providers.getAllProviders().catch(err => {- console.error(`❌ Failed to load providers at startup: ${err.message}`);- });+ // Warm the providers file at startup so the codex-sentinel migration runs+ // before any inbound request can hit the providers cache. A pure READ of+ // on-disk provider config — it dispatches nothing to a provider.+ warmProviders: (aiToolkit) => aiToolkit.services.providers.getAllProviders(),++ // Ensure the provider paired with the active local-LLM backend (LLM_BACKEND in+ // .env, chosen at setup time) is enabled, so a fresh install can use Ollama /+ // LM Studio for runs without hand-toggling it in the Providers UI. Starting+ // the Ollama server is not a provider CALL — nothing is inferred until the+ // user asks for it.+ ensureLocalLlmBackend: () => {+ const activeLocalLlmBackend = getLocalLlmBackend();+ ensureBackendProvider(activeLocalLlmBackend).catch((err) =>+ console.error(`⚠️ Failed to enable local LLM backend provider: ${err.message}`));+ if (activeLocalLlmBackend === 'ollama') {+ ensureOllamaRunning({ preferPersistent: true }).catch((err) =>+ console.error(`⚠️ Failed to start Ollama for active local LLM backend: ${err.message}`));+ }+ },- // Ensure the provider paired with the active local-LLM backend (LLM_BACKEND in- // .env, chosen at setup time) is enabled, so a fresh install can use Ollama /- // LM Studio for runs without hand-toggling it in the Providers UI.- const activeLocalLlmBackend = getLocalLlmBackend();- ensureBackendProvider(activeLocalLlmBackend).catch((err) =>- console.error(`⚠️ Failed to enable local LLM backend provider: ${err.message}`));- if (activeLocalLlmBackend === 'ollama') {- ensureOllamaRunning({ preferPersistent: true }).catch((err) =>- console.error(`⚠️ Failed to start Ollama for active local LLM backend: ${err.message}`));- }+ // Register PortOS's CLI + TUI runners through the toolkit's declared extension+ // points (setCliRunner / setTuiRunner) instead of overwriting private props.+ // The CLI variant adds per-provider argv building (Codex `exec -`, Antigravity+ // `agy --print`, Claude Code `-p -`); the toolkit's in-tree implementation is+ // also safe (no shell, prompt via stdin) — the variant exists for the per-CLI+ // invocation conventions, not for security. The TUI runner has no toolkit+ // built-in: registering it lets POST /api/runs with a TUI provider dispatch+ // here instead of 400ing. Both runners track their child process / pty via the+ // toolkit's external-run registry, so the toolkit's own stopRun/isRunActive/+ // deleteRun account for live runs without any sibling-method monkey-patching.+ registerRunners: (aiToolkit) => {+ aiToolkit.services.runner.setCliRunner(executeCliRunFixed);+ aiToolkit.services.runner.setTuiRunner(executeTuiRunFixed);+ },- // Register PortOS's CLI + TUI runners through the toolkit's declared extension- // points (setCliRunner / setTuiRunner) instead of overwriting private props.- // The CLI variant adds per-provider argv building (Codex `exec -`, Antigravity- // `agy --print`, Claude Code `-p -`); the toolkit's in-tree implementation is- // also safe (no shell, prompt via stdin) — the variant exists for the per-CLI- // invocation conventions, not for security. The TUI runner has no toolkit- // built-in: registering it lets POST /api/runs with a TUI provider dispatch- // here instead of 400ing. Both runners track their child process / pty via the- // toolkit's external-run registry, so the toolkit's own stopRun/isRunActive/- // deleteRun account for live runs without any sibling-method monkey-patching.- aiToolkit.services.runner.setCliRunner(executeCliRunFixed);- aiToolkit.services.runner.setTuiRunner(executeTuiRunFixed);- console.log('🔧 Registered PortOS CLI + TUI runners via aiToolkit runner extension points');-- // Note: prompts service is initialized automatically by createAIToolkit()-- // Initialize auto-fixer for error recovery- initAutoFixer();-- // Initialize task learning system to track agent completions- initTaskLearning();-- // Initialize the CoS agent spawner (event wiring + orphan cleanup) explicitly,- // now that the runner patch + task learning are ready. Capture the promise so- // CoS auto-start can wait for the spawner's `task:ready` listener before it- // emits (see cos.init below). The `.catch` resolves the chain even on failure,- // so a spawner init error never blocks CoS init.- const spawnerReady = initSpawner().catch(err => {- console.error(`❌ Failed to initialize spawner: ${err.message}`);+ // Auto-fixer for error recovery.+ initAutoFixer,+ // Task learning system, tracking agent completions.+ initTaskLearning,+ // The CoS agent spawner (event wiring + orphan cleanup), initialized+ // explicitly now that the runner registration + task learning are ready.+ startSpawner: initSpawner});-- return { aiToolkit, spawnerReady };};/**@@ -286,13 +292,9 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD*/const startBackgroundServices = ({ spawnerReady }) => {// Explicit call (not a module-level side effect) so test imports of cos.js- // don't spin up its event listeners and timers. Gated on the spawner being- // ready: CoS auto-start (alwaysOn) can emit `task:ready` for pending tasks- // during init, which would be dropped if the spawner hadn't yet registered its- // listener — so wait for `spawnerReady` before kicking off CoS init.- spawnerReady- .then(() => cos.init())- .catch(err => console.error(`❌ CoS init failed: ${err.message}`));+ // don't spin up its event listeners and timers. The spawner gate itself lives+ // in bootstrapSequence.js.+ initCosAfterSpawner({ spawnerReady, initCos: () => cos.init() });// Initialize agent automation scheduler and action executorautomationScheduler.init().catch(err => console.error(`❌ Agent scheduler init failed: ${err.message}`));@@ -359,13 +361,15 @@ const startBackgroundServices = ({ spawnerReady }) => {// Commission. Boot only ARMS timers; nothing fires until a cadence elapses, and// each fire gates on creative autonomy `execute` + the daily cos budget (so an// `off`/`dry-run` install generates nothing). Sanctioned scheduled-automation.- // Split any legacy INLINE commission feedback into the federated commissionFeedback- // store (#2686) BEFORE arming the scheduler, so a fire reads the federated view.- // Pure data movement (no LLM), idempotent, best-effort. The scripts/migrations- // runner executes before the DB pool is up, so the data move lives here (see the- // migration 194 registration stub); the table itself is created by ensureSchema.- backfillAllCommissionFeedback().catch(err => console.error(`❌ Commission feedback backfill failed: ${err.message}`));- startCommissionScheduler().catch(err => console.error(`❌ Creative Commission scheduler init failed: ${err.message}`));+ // The backfill is pure data movement (no LLM), idempotent, best-effort. The+ // scripts/migrations runner executes before the DB pool is up, so the data move+ // lives here (see the migration 194 registration stub); the table itself is+ // created by ensureSchema. Backfill-before-arm ordering lives in+ // bootstrapSequence.js.+ armCommissionScheduler({+ backfillCommissionFeedback: backfillAllCommissionFeedback,+ startCommissionScheduler+ });// Initialize CyberCity snapshot scheduler — records periodic city-state frames// for the historical timeline scrubber (issue #877).startCitySnapshotScheduler().catch(err => console.error(`❌ City snapshot scheduler init failed: ${err.message}`));@@ -500,186 +504,98 @@ const initMediaJobDependentHooks = () => {};/**- * Verify PostgreSQL is reachable + at the current schema, upgrading it if it- * merely lags. Returns `{ dbReady }`.+ * The database phase's dependencies. `runDatabasePhase` (bootstrapSequence.js)+ * owns the gate → migrate → warm → arm ordering; this supplies the real db.js,+ * the real migration scripts, and the real stores.*- * PostgreSQL is a mandatory dependency. If the DB is unusable and we're NOT in- * a sanctioned escape-hatch/test mode this is a fatal misconfiguration: the- * creative catalog has no file-backed equivalent, so booting "successfully"- * would silently serve a broken install. Fail fast with an actionable message.+ * Escape hatches for the health gate (dev/tests only, UNSUPPORTED for+ * production): `MEMORY_BACKEND=file` (explicit file backend) and `NODE_ENV=test`+ * (test suites boot without a database). Both downgrade "PostgreSQL is required"+ * from a fail-fast to a warning.*- * Escape hatches (dev/tests only, UNSUPPORTED for production):- * - MEMORY_BACKEND=file (explicit file backend)- * - NODE_ENV=test (test suites boot without a database)- */-const gateOnDatabase = async () => {- const dbEscapeHatch =- process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test';- const { checkHealth, ensureSchema } = await import('../lib/db.js');- let health = await checkHealth();- // An EXISTING install can be reachable but lag the current schema — e.g.- // `memories` exists but a newer column (`sync_sequence`) is missing, which- // is exactly what checkHealth() requires for hasSchema. ensureSchema() is- // idempotent and exists to bring such installs up to date, so when the DB- // is connected but reports incomplete schema, run the upgrade and re-probe- // BEFORE declaring the install unbootable. A truly uninitialized DB (base- // tables absent) makes ensureSchema() throw — we catch, log, and fall- // through to the fail-fast below. (try/catch is appropriate here: this runs- // outside the request lifecycle, so an uncaught throw would crash boot.)- if (health.connected && (!health.hasSchema || !health.hasCatalogSchema)) {- try {- await ensureSchema();- health = await checkHealth();- } catch (err) {- console.error(`🗄️ Schema upgrade on boot failed: ${err.message}`);- }- }- // Both the memory schema AND the creative-catalog schema are required —- // the catalog has no file-backed equivalent. ensureSchema() creates the- // catalog tables idempotently, but if that DDL fails (e.g. the role can't- // CREATE) the swallowed error in the migration block below would otherwise- // let the server boot with the catalog missing. Gate boot on both.- const dbReady = health.connected && health.hasSchema && health.hasCatalogSchema;- if (!dbEscapeHatch && !dbReady) {- const reason = health.connected ? 'required schema missing' : `unreachable (${health.error || 'connection failed'})`;- console.error(`❌ PostgreSQL is required but ${reason} — refusing to start.`);- console.error(' Set up the database with: npm run setup:db');- console.error(' Dev/test only: set PGMODE=file in .env to boot without PostgreSQL (unsupported for production).');- process.exit(1);- }- if (dbEscapeHatch && !dbReady) {- console.warn(`⚠️ PostgreSQL unavailable (${health.error || 'no schema'}) — booting via escape hatch; catalog/DB features are disabled.`);- }- return { dbReady, ensureSchema };-};--/**- * DB schema + catalog/media migrations. Best-effort as a group (a transient- * hiccup mid-walk shouldn't crash an otherwise-healthy boot; the route surface- * tolerates an empty catalog and the user can re-trigger via the admin- * endpoint) EXCEPT the versioned DB-migration runner, which is fatal.+ * Every migration/warm step is imported lazily, at the moment it runs, exactly+ * as before the extraction — nothing in this phase is pulled into the module+ * graph on a boot that never reaches it.*/-const runDbAndCatalogMigrations = async (dbReady, ensureSchema) => {- try {- // Two early exits guard the migrations below: (1) the fail-fast- // process.exit(1) in gateOnDatabase when the DB is required but missing,- // and (2) this return when on the escape hatch with no healthy DB —- // ensureSchema and the migrations would throw otherwise.- if (!dbReady) {- return;- }- await ensureSchema();- // Versioned DB-migration runner (#1029): apply ordered schema-DELTA- // migrations (renames / type changes / data transforms / embedding-dim- // changes) that ensureSchema()'s additive IF NOT EXISTS gates can't- // express. Runs AFTER ensureSchema() (base schema + schema_migrations- // tracking table present) and AFTER the DB-ready gate, but BEFORE any- // store warm or httpServer.listen — so a half-applied delta can't race a- // request. Skipped under the file backend by the !dbReady early return- // above. A FAILED migration is FATAL: each migration runs in a transaction- // so a failure rolls back (NOT marked applied), but we must NOT let boot- // continue — a partially-migrated install serving requests is worse than a- // hard stop. So this gets its own try/catch (not the generic catalog one- // below, which only logs and continues) that exits the process loudly.- // This is a process boundary, so the explicit try/catch is sanctioned.- const { runDbMigrations } = await import('../scripts/run-db-migrations.js');- try {- await runDbMigrations();- } catch (err) {- console.error(`❌ DB migration failed at boot — refusing to start: ${err?.stack ?? err.message}`);- process.exit(1);- }- const { migrateBibleToCatalog } = await import('../scripts/migrateBibleToCatalog.js');- await migrateBibleToCatalog();+const runDatabaseBootPhase = () => runDatabasePhase({+ gate: async () => {+ const { checkHealth, ensureSchema } = await import('../lib/db.js');+ const { dbReady } = await gateOnDatabase({+ checkHealth,+ ensureSchema,+ escapeHatch: process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test'+ });+ // ensureSchema is threaded through to the migrations below so the phase+ // resolves the db.js module exactly once.+ return { dbReady, ensureSchema };+ },++ migrate: ({ dbReady, ensureSchema }) => runDbAndCatalogMigrations({+ dbReady,+ ensureSchema,+ // Versioned DB-migration runner (#1029): ordered schema-DELTA migrations+ // (renames / type changes / data transforms / embedding-dim changes) that+ // ensureSchema()'s additive IF NOT EXISTS gates can't express.+ runDbMigrations: async () => (await import('../scripts/run-db-migrations.js')).runDbMigrations(),+ migrateBibleToCatalog: async () => (await import('../scripts/migrateBibleToCatalog.js')).migrateBibleToCatalog(),// One-time data repair: rewrite legacy machine universe tags// (`from-universe`, `universe:<id>`) on backfilled rows into the friendly- // universe NAME tag. Runs after the backfill so promoted rows exist;- // marker-gated in data/catalog-universe-tags.applied.json.- const { repairUniverseTags } = await import('../scripts/repairUniverseTags.js');- await repairUniverseTags();+ // universe NAME tag. Marker-gated in data/catalog-universe-tags.applied.json.+ repairUniverseTags: async () => (await import('../scripts/repairUniverseTags.js')).repairUniverseTags(),// Per-record catalog payload-shape migration — walks rows whose stored// payload.schemaVersion lags the registry-current and applies registered- // upgraders. No-ops via marker once an install is at the high-water- // version, so this is free on steady-state boots.- const { migrateCatalogPayload } = await import('../scripts/migrateCatalogPayload.js');- await migrateCatalogPayload();+ // upgraders. No-ops via marker once an install is at the high-water version.+ migrateCatalogPayload: async () => (await import('../scripts/migrateCatalogPayload.js')).migrateCatalogPayload(),// One-time canon↔catalog reconciliation: collapse any pre-existing- // divergence between an embedded universe-canon entry and its catalog- // row (they were copy-on-write mirrors before the bidirectional- // projection landed). LWW on updatedAt; writes the winner to both sides.- // Runs LAST so promoted rows exist and are at current payload-shape- // version; marker-gated in data/catalog-canon-reconcile.applied.json.- const { reconcileCanonCatalog } = await import('../scripts/reconcileCanonCatalog.js');- await reconcileCanonCatalog();+ // divergence between an embedded universe-canon entry and its catalog row+ // (they were copy-on-write mirrors before the bidirectional projection+ // landed). LWW on updatedAt; writes the winner to both sides. Marker-gated+ // in data/catalog-canon-reconcile.applied.json.+ reconcileCanonCatalog: async () => (await import('../scripts/reconcileCanonCatalog.js')).reconcileCanonCatalog(),// Media asset index (#1000): subscribe the generation-completed hooks +// reconcile the derived media_assets table against on-disk images/videos.// Bytes + sidecars + video-history.json stay authoritative; this builds a// queryable index over them. Idempotent, safe to run every boot.- const { initMediaAssetIndex } = await import('./mediaAssetIndex/index.js');- await initMediaAssetIndex();- } catch (err) {- console.error(`🪄 catalog migrations failed at boot: ${err.message}`);- }-};+ initMediaAssetIndex: async () => (await import('./mediaAssetIndex/index.js')).initMediaAssetIndex()+ }),-/**- * 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 (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) that exits- * loudly instead of swallowing the error and booting a partially-migrated- * install.- */-const warmMandatoryStores = async () => {- try {+ warmStores: () => warmMandatoryStores({// 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();+ warmUniverses: () => universeStore().listIds(),+ // Pipeline series + issues PG warm (#1015): same contract.+ warmSeries: () => seriesStore().listIds(),+ warmIssues: () => issueStore().listIds(),+ // Story Builder sessions PG warm (#1016): same contract.+ warmStoryBuilder: () => 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 : []);+ warmWritersRoom: () => 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.+ warmCatalogUserTypes: async () => {+ 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 step, 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('./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);- }-};+ // 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 step, so it can still be in flight here. listProjects() forces+ // selectBackend() → the (idempotent, marker-gated) import to completion,+ // which the prune below depends on.+ warmCreativeDirector: async () => (await import('./creativeDirector/local.js')).listProjects(),+ // Legacy artifact prune: 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.+ pruneLegacyFiles: async () => (await import('../scripts/pruneImportedLegacyFiles.js')).pruneImportedLegacyFiles()+ }),++ reconcileStackerNews: reconcileStackerNewsSchedulers+});/** Log the canonical "where do I open this" banner and wire the HTTPS extras. */const announceListening = ({ io, httpServer, localHttpServer, httpsEnabled, port }) => {@@ -718,106 +634,74 @@ const announceListening = ({ io, httpServer, localHttpServer, httpsEnabled, port/*** Post-route boot. Kicks off the background services, then walks the ordered- * boot chain that ends in `httpServer.listen()`. Returns the chain's promise so- * a caller can await it; index.js intentionally does not (boot proceeds in the- * background and any fatal step exits the process itself).+ * boot chain that ends in `httpServer.listen()` — the walk itself is+ * `runPostRouteSequence` in bootstrapSequence.js, which owns which of these+ * steps are awaited and which are fire-and-forget. Returns the chain's promise+ * so a caller can await it; index.js intentionally does not (boot proceeds in+ * the background and any fatal step exits the process itself).*/-export const runBootSequence = ({ io, httpServer, localHttpServer, httpsEnabled, port, host, spawnerReady }) => {- startBackgroundServices({ spawnerReady });-- // Initialize instance identity + sync log before accepting requests to prevent- // race conditions where brain mutations arrive before the sync log is ready- return ensureSelf()- .then(() => initSyncLog())- .then(() => {- // Recover inbox entries stuck in 'classifying' from a previous crash. Runs- // AFTER initSyncLog() because updateInboxLog() now appends to the brain sync- // log — running it before currentSeq is loaded would mint colliding seqs and- // corrupt peer cursors. Fire-and-forget; failures are logged.- recoverStuckClassifications().catch(err => console.error(`❌ Brain recovery failed: ${err.message}`));- })- // initMediaJobQueue is awaited here so that data/ exists and the worker loop- // is running before /api/video-gen or /api/image-gen can enqueue (otherwise- // persist() can race with ensureDir).- .then(() => initMediaJobQueue())- .then(() => initMediaJobDependentHooks())- .then(() => {- // Sharing: attach chokidar watchers to every registered share bucket so- // incoming manifests from peers are picked up live. Backlog processing- // (manifests that arrived while the server was offline) runs as part of- // initSharing. Fire-and-forget — a failed bucket shouldn't block boot.- initSharing({ io }).catch((err) => {- console.error(`❌ Sharing init failed: ${err.message}`);- });- })- .then(() => {- // Fire-and-forget — resume any Creative Director projects that were mid-- // flight when the server died. The queue reload above just reclassified- // their renders as 'failed (interrupted by restart)'; this nudges the- // orchestrator so projects don't sit frozen waiting for listeners that- // no longer exist. Doesn't block startup.- // recoverInFlightProjects resolves cdRecoveryDone on success. On any- // failure path here, explicitly resolve it so cos.start's gate doesn't- // hit the 60s timeout fallback for nothing.- recoverInFlightProjects().catch(async (e) => {- console.log(`⚠️ CD boot recovery failed: ${e.message}`);- const { markRecoveryDone } = await import('./creativeDirector/recovery.js');- markRecoveryDone();- });- })- .then(async () => {- const { dbReady, ensureSchema } = await gateOnDatabase();- await runDbAndCatalogMigrations(dbReady, ensureSchema);- // Skipped when not dbReady (escape hatch), matching the migrations above.- if (dbReady) {- await warmMandatoryStores();- // OFF by default. This only arms timers for explicitly opted-in- // accounts after their tables exist; it does not perform an initial- // sync or local-LLM call.- await reconcileStackerNewsSchedulers();- }- })- .then(async () => {- // One-time series cover-thumbnail backfill: derive `series.coverImage` (the- // rendered volume/issue cover shown on the pipeline list) for series whose- // covers rendered before the feature shipped. Runs after the series + issues- // stores are warmed above so the derivation reads migrated records. Drives- // the services, so it works on both the PG backend and the file escape hatch.- // FIRE-AND-FORGET (not awaited): a cosmetic thumbnail backfill must never- // delay the server accepting requests, and it's marker-gated so it runs at- // most once regardless.- const { backfillSeriesCoverImages } = await import('../scripts/backfillSeriesCoverImages.js');- backfillSeriesCoverImages().catch((err) => {- console.error(`❌ series cover backfill failed at boot: ${err?.message ?? err}`);- });- })- .then(() => {- // Start server only after sync log + media job queue are initialized.- // initMediaJobQueue failure is fatal: the queue owns persistence + SSE- // + temp-file cleanup for /api/video-gen and local /api/image-gen, and- // accepting requests with a half-init queue silently corrupts state- // (persist() throws, SSE streams degrade). Catch + crash via the- // outer .catch(...process.exit) below.- httpServer.listen(port, host, () => {- announceListening({ io, httpServer, localHttpServer, httpsEnabled, port });-- // Set up process error handlers with io instance- setupProcessErrorHandlers(io);-- // Backfill origin tags and start peer polling + sync (non-blocking)- backfillOriginInstanceId()- .then(() => {- startPolling();- initSyncOrchestrator();- })- .catch(err => console.error(`❌ Post-startup init failed: ${err.message}`));- });- })- .catch(err => {- console.error(`❌ Instance init failed: ${err.message}`);- process.exit(1);- });-};+export const runBootSequence = ({ io, httpServer, localHttpServer, httpsEnabled, port, host, spawnerReady }) =>+ runPostRouteSequence({+ startBackgroundServices: () => startBackgroundServices({ spawnerReady }),++ // Instance identity + sync log come up before requests are accepted, so a+ // brain mutation can't arrive before the sync log is ready.+ ensureSelf,+ initSyncLog,++ // Recover inbox entries stuck in 'classifying' from a previous crash. Must+ // run AFTER initSyncLog() because updateInboxLog() appends to the brain sync+ // log — running it before currentSeq is loaded would mint colliding seqs and+ // corrupt peer cursors.+ recoverStuckClassifications,++ // Awaited by the sequence so data/ exists and the worker loop is running+ // before /api/video-gen or /api/image-gen can enqueue (otherwise persist()+ // can race with ensureDir). A failure here is fatal: the queue owns+ // persistence + SSE + temp-file cleanup, and accepting requests with a+ // half-init queue silently corrupts state.+ initMediaJobQueue,+ initMediaJobDependentHooks,++ // Sharing: attach chokidar watchers to every registered share bucket so+ // incoming manifests from peers are picked up live. Backlog processing+ // (manifests that arrived while the server was offline) runs as part of+ // initSharing.+ initSharing: () => initSharing({ io }),++ // Resume any Creative Director projects that were mid-flight when the server+ // died. The queue reload above just reclassified their renders as 'failed+ // (interrupted by restart)'; this nudges the orchestrator so projects don't+ // sit frozen waiting for listeners that no longer exist.+ // recoverInFlightProjects resolves cdRecoveryDone on success. On any failure+ // path here, explicitly resolve it so cos.start's gate doesn't hit the 60s+ // timeout fallback for nothing.+ recoverCreativeDirectorProjects: () => recoverInFlightProjects().catch(async (e) => {+ console.log(`⚠️ CD boot recovery failed: ${e.message}`);+ const { markRecoveryDone } = await import('./creativeDirector/recovery.js');+ markRecoveryDone();+ }),++ runDatabasePhase: runDatabaseBootPhase,++ // One-time series cover-thumbnail backfill: derive `series.coverImage` (the+ // rendered volume/issue cover shown on the pipeline list) for series whose+ // covers rendered before the feature shipped. Runs after the series + issues+ // stores are warmed above so the derivation reads migrated records. Drives+ // the services, so it works on both the PG backend and the file escape hatch.+ // Marker-gated, so it runs at most once regardless.+ backfillSeriesCoverImages: async () => (await import('../scripts/backfillSeriesCoverImages.js')).backfillSeriesCoverImages(),++ startListening: () => httpServer.listen(port, host, () => runPostListenSequence({+ announceListening: () => announceListening({ io, httpServer, localHttpServer, httpsEnabled, port }),+ // Process-level safety net, wired with the io instance so unhandled+ // failures also surface in the UI.+ setupProcessErrorHandlers: () => setupProcessErrorHandlers(io),+ backfillOriginInstanceId,+ startPolling,+ initSyncOrchestrator+ }))+ });// Run an async close but resolve anyway after `ms` — so a close that never// settles (e.g. a WebSocket-upgraded socket the server no longer tracks, or adiff --git a/server/services/bootstrapSequence.js b/server/services/bootstrapSequence.jsnew file mode 100644index 0000000000..54017ce387--- /dev/null+++ b/server/services/bootstrapSequence.js@@ -0,0 +1,346 @@+/**+ * The load-bearing ORDER of server boot, extracted from `bootstrap.js` (#3451).+ *+ * `bootstrap.js` owns *what* each boot step is — the real migration runner, the+ * real AI Toolkit, the real stores, the real listener. This module owns *when*+ * each step runs relative to its neighbours, and receives every step as an+ * injected parameter. That split is the whole point: the ordering contract the+ * `bootstrap.js` header describes ("ordering inside each phase is load-bearing")+ * can then be executed and asserted by `bootstrapSequence.test.js` without+ * importing a module graph that would open a real listener, touch the real+ * database, or reach a provider.+ *+ * Rules for editing:+ * - Nothing here may import a PortOS service, `db.js`, or the AI Toolkit.+ * Every dependency arrives as a parameter; that is what keeps this testable.+ * - `await` vs fire-and-forget is part of the contract, not an accident: an+ * awaited step blocks every later step, and the tests assert which is which.+ * - No step here may reach an AI provider (CLAUDE.md "No cold-bootstrap LLM+ * calls"). Boot loads on-disk state and ARMS schedulers, nothing more.+ */++/**+ * Run a best-effort step, logging and continuing on failure. Wrapped in+ * `Promise.resolve` so a synchronous step (or an injected double that returns+ * nothing) flows through the same path as an async one.+ */+const bestEffort = (result, onError) => Promise.resolve(result).catch(onError);++/** Shared shape for the "log it and keep booting" handlers below. */+const logFailure = (label) => (err) => console.error(`❌ ${label}: ${err?.message ?? err}`);++/** Same, but keeping the stack — used where a failure is worth a full trace. */+const logFailureWithStack = (label) => (err) => console.error(`❌ ${label}: ${err?.stack ?? err}`);++/**+ * Pre-route boot ordering (`bootstrapServices`).+ *+ * Load-bearing points, in order:+ * 1. `applyDataMigrations` runs FIRST and is awaited — the toolkit reads+ * stage-config.json / providers.json, so a pull-and-restart that skipped+ * `npm run migrations` must still land new prompt stages before then.+ * 2. `verifyCollections` runs before anything can serve a request, and only+ * logs: a hard exit on a schema mismatch is worse than a noisy log.+ * 3. `createToolkit` → `registerToolkitShims` → `warmProviders`: the shims+ * hand the toolkit to the compatibility modules before the providers file+ * is warmed, so the codex-sentinel migration write completes before any+ * request can consult providers state (hence the await).+ * 4. `registerRunners` before the workers below, so a run dispatched by the+ * spawner cannot land on a toolkit without PortOS's CLI/TUI runners.+ * 5. `startSpawner` LAST, and its promise is returned (not awaited): CoS init+ * in the post-route phase gates on it so `task:ready` can't be emitted+ * before the spawner registered its listener.+ *+ * Returns `{ aiToolkit, spawnerReady }`.+ */+export const runPreRouteSequence = async ({+ applyDataMigrations,+ verifyCollections,+ createToolkit,+ registerToolkitShims,+ warmProviders,+ ensureLocalLlmBackend,+ registerRunners,+ initAutoFixer,+ initTaskLearning,+ startSpawner+}) => {+ await bestEffort(applyDataMigrations(), logFailureWithStack('Migration run failed at startup'));+ await bestEffort(verifyCollections(), logFailureWithStack('Collection version check failed at startup'));++ const aiToolkit = createToolkit();+ registerToolkitShims(aiToolkit);+ await bestEffort(warmProviders(aiToolkit), logFailure('Failed to load providers at startup'));++ // Fire-and-forget: a local backend that won't start must not delay the boot.+ ensureLocalLlmBackend();++ registerRunners(aiToolkit);+ console.log('🔧 Registered PortOS CLI + TUI runners via aiToolkit runner extension points');++ initAutoFixer();+ initTaskLearning();++ const spawnerReady = bestEffort(startSpawner(), logFailure('Failed to initialize spawner'));+ return { aiToolkit, spawnerReady };+};++/**+ * CoS auto-start must wait for the spawner. `cos.init()` can emit `task:ready`+ * for pending tasks while it initializes; emitted before the spawner registered+ * its listener, those events are dropped and the tasks sit forever.+ */+export const initCosAfterSpawner = ({ spawnerReady, initCos }) =>+ Promise.resolve(spawnerReady)+ .then(() => initCos())+ .catch(logFailure('CoS init failed'));++/**+ * Legacy INLINE commission feedback is split into the federated store BEFORE the+ * per-commission crons are armed (#2686), so a fire reads the federated view.+ * Both are best-effort and neither blocks boot.+ */+export const armCommissionScheduler = ({ backfillCommissionFeedback, startCommissionScheduler }) => {+ bestEffort(backfillCommissionFeedback(), logFailure('Commission feedback backfill failed'));+ bestEffort(startCommissionScheduler(), logFailure('Creative Commission scheduler init failed'));+};++/**+ * PostgreSQL health gate. An EXISTING install can be reachable but lag the+ * current schema, so a connected-but-incomplete DB gets one `ensureSchema()`+ * upgrade + re-probe BEFORE we declare it unbootable. Both the memory schema and+ * the creative-catalog schema are required — the catalog has no file-backed+ * equivalent.+ *+ * `escapeHatch` (MEMORY_BACKEND=file / NODE_ENV=test, dev+test only) downgrades+ * the fail-fast to a warning. `onUnbootable` defaults to exiting the process;+ * it is injected so the gate can be exercised without killing the test runner.+ */+export const gateOnDatabase = async ({+ checkHealth,+ ensureSchema,+ escapeHatch,+ onUnbootable = () => process.exit(1)+}) => {+ let health = await checkHealth();+ if (health.connected && (!health.hasSchema || !health.hasCatalogSchema)) {+ // try/catch is appropriate here: this runs outside the request lifecycle, so+ // an uncaught throw would crash boot. A truly uninitialized DB (base tables+ // absent) makes ensureSchema() throw — log and fall through to the gate.+ try {+ await ensureSchema();+ health = await checkHealth();+ } catch (err) {+ console.error(`🗄️ Schema upgrade on boot failed: ${err.message}`);+ }+ }+ const dbReady = Boolean(health.connected && health.hasSchema && health.hasCatalogSchema);+ if (!escapeHatch && !dbReady) {+ const reason = health.connected ? 'required schema missing' : `unreachable (${health.error || 'connection failed'})`;+ console.error(`❌ PostgreSQL is required but ${reason} — refusing to start.`);+ console.error(' Set up the database with: npm run setup:db');+ console.error(' Dev/test only: set PGMODE=file in .env to boot without PostgreSQL (unsupported for production).');+ onUnbootable();+ } else if (escapeHatch && !dbReady) {+ console.warn(`⚠️ PostgreSQL unavailable (${health.error || 'no schema'}) — booting via escape hatch; catalog/DB features are disabled.`);+ }+ return { dbReady };+};++/**+ * DB schema + catalog/media migrations, in dependency order. Best-effort as a+ * group (a transient hiccup mid-walk shouldn't crash an otherwise-healthy boot)+ * EXCEPT `runDbMigrations`, which is FATAL: each migration is transactional so a+ * failure rolls back un-applied, but a partially-migrated install serving+ * requests is worse than a hard stop.+ *+ * Order notes: `ensureSchema` first (base tables + the schema_migrations+ * tracking table); the versioned delta runner next, before any store warm or+ * `listen()`, so a half-applied delta can't race a request; `repairUniverseTags`+ * after the bible→catalog promotion so the rows it rewrites exist;+ * `reconcileCanonCatalog` last so it reconciles rows already at the current+ * payload-shape version.+ *+ * Skipped entirely when `!dbReady` (escape hatch) — every step below would throw.+ */+export const runDbAndCatalogMigrations = async ({+ dbReady,+ ensureSchema,+ runDbMigrations,+ migrateBibleToCatalog,+ repairUniverseTags,+ migrateCatalogPayload,+ reconcileCanonCatalog,+ initMediaAssetIndex,+ onMigrationFailure = () => process.exit(1)+}) => {+ if (!dbReady) return;+ try {+ await ensureSchema();+ try {+ await runDbMigrations();+ } catch (err) {+ console.error(`❌ DB migration failed at boot — refusing to start: ${err?.stack ?? err.message}`);+ onMigrationFailure();+ return;+ }+ await migrateBibleToCatalog();+ await repairUniverseTags();+ await migrateCatalogPayload();+ await reconcileCanonCatalog();+ await initMediaAssetIndex();+ } 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 `listen()` — so the first request/sync sees+ * fully-migrated records, never a half-applied import racing a request.+ *+ * Order is load-bearing: series before issues (issues soft-ref series), both+ * before Story Builder (sessions soft-ref both), Creative Director before the+ * prune (the prune stamps a single completion marker once no domain is blocked,+ * so CD's marker must already exist), and `pruneLegacyFiles` LAST for the same+ * reason.+ *+ * A failure here is FATAL, unlike the best-effort catalog migrations above: a+ * store that couldn't select its backend would serve unmigrated/empty data.+ */+export const warmMandatoryStores = async ({+ warmUniverses,+ warmSeries,+ warmIssues,+ warmStoryBuilder,+ warmWritersRoom,+ warmCatalogUserTypes,+ warmCreativeDirector,+ pruneLegacyFiles,+ onWarmFailure = () => process.exit(1)+}) => {+ try {+ await warmUniverses();+ await warmSeries();+ await warmIssues();+ await warmStoryBuilder();+ await warmWritersRoom();+ await warmCatalogUserTypes();+ await warmCreativeDirector();+ await pruneLegacyFiles();+ } catch (err) {+ console.error(`❌ Mandatory store warmup failed at boot — refusing to start: ${err?.stack ?? err.message}`);+ onWarmFailure();+ }+};++/**+ * Database phase: gate, then migrate, then (only on a real DB) warm the stores+ * and arm the Stacker News schedulers. The warm/arm pair is skipped on the+ * escape hatch for the same reason the migrations are — there is no DB to read.+ *+ * Returns the gate result so a caller can branch on `dbReady`.+ */+export const runDatabasePhase = async ({ gate, migrate, warmStores, reconcileStackerNews }) => {+ const gateResult = await gate();+ await migrate(gateResult);+ if (gateResult.dbReady) {+ await warmStores();+ // OFF by default — arms timers for opted-in accounts only, after their+ // tables exist. No initial sync, no local-LLM call.+ await reconcileStackerNews();+ }+ return gateResult;+};++/**+ * Post-route boot ordering (`runBootSequence`), ending in `startListening()`.+ *+ * Load-bearing points, in order:+ * 1. `startBackgroundServices` first and NOT awaited — every scheduler in it+ * is armed, never fired, so nothing below depends on it.+ * 2. `ensureSelf` → `initSyncLog` awaited before anything can mutate brain+ * records, so sync sequence numbers are loaded before the first append.+ * 3. `recoverStuckClassifications` AFTER `initSyncLog` (it appends to the sync+ * log; running it earlier mints colliding seqs and corrupts peer cursors)+ * but fire-and-forget, since nothing below reads its result.+ * 4. `initMediaJobQueue` awaited before `initMediaJobDependentHooks` — the+ * hooks must be listening before the queue replays `completed` events for+ * reloaded jobs, and before a route can enqueue against a half-init queue.+ * 5. The database phase before `startListening`, so no request can land on a+ * partially-migrated install.+ * 6. `backfillSeriesCoverImages` fire-and-forget: a cosmetic thumbnail+ * backfill must never delay the server accepting requests.+ *+ * Returns the chain's promise; a rejection anywhere in it is fatal.+ */+export const runPostRouteSequence = ({+ startBackgroundServices,+ ensureSelf,+ initSyncLog,+ recoverStuckClassifications,+ initMediaJobQueue,+ initMediaJobDependentHooks,+ initSharing,+ recoverCreativeDirectorProjects,+ runDatabasePhase: databasePhase,+ backfillSeriesCoverImages,+ startListening,+ onFatal = () => process.exit(1)+}) => {+ startBackgroundServices();++ return Promise.resolve()+ .then(() => ensureSelf())+ .then(() => initSyncLog())+ .then(() => {+ bestEffort(recoverStuckClassifications(), logFailure('Brain recovery failed'));+ })+ .then(() => initMediaJobQueue())+ .then(() => initMediaJobDependentHooks())+ .then(() => {+ // Sharing attaches chokidar watchers + drains the offline manifest+ // backlog. Fire-and-forget — a failed bucket shouldn't block boot.+ bestEffort(initSharing(), logFailure('Sharing init failed'));+ })+ .then(() => {+ // Nudges Creative Director projects the media-queue reload just marked+ // 'failed (interrupted by restart)' so they don't sit frozen. Owns its own+ // failure path (it must resolve the CD recovery gate either way).+ recoverCreativeDirectorProjects();+ })+ .then(() => databasePhase())+ .then(() => {+ bestEffort(backfillSeriesCoverImages(), logFailure('series cover backfill failed at boot'));+ })+ .then(() => startListening())+ .catch((err) => {+ console.error(`❌ Instance init failed: ${err.message}`);+ onFatal();+ });+};++/**+ * Inside the `listen()` callback: announce the URLs, arm the process-level+ * safety net, then backfill origin tags before peer polling + sync start — the+ * backfill stamps `originInstanceId` on legacy rows, and polling a peer before+ * it completes would ship untagged records.+ */+export const runPostListenSequence = ({+ announceListening,+ setupProcessErrorHandlers,+ backfillOriginInstanceId,+ startPolling,+ initSyncOrchestrator+}) => {+ announceListening();+ setupProcessErrorHandlers();+ return bestEffort(+ Promise.resolve(backfillOriginInstanceId()).then(() => {+ startPolling();+ initSyncOrchestrator();+ }),+ logFailure('Post-startup init failed')+ );+};diff --git a/server/services/bootstrapSequence.test.js b/server/services/bootstrapSequence.test.jsnew file mode 100644index 0000000000..2c8cbe93a0--- /dev/null+++ b/server/services/bootstrapSequence.test.js@@ -0,0 +1,687 @@+/**+ * Executable coverage for the boot ORDER (#3451).+ *+ * `bootstrap.js` says its ordering is load-bearing, and every install depends on+ * that ordering being right — but the file can't be imported under test (it+ * pulls the whole service graph, and its steps open a listener, a database, and+ * agent workers). `bootstrapSequence.js` exists so the ordering can be run for+ * real with injected doubles: nothing here touches the network, the filesystem,+ * PostgreSQL, or an AI provider.+ *+ * Assertions are on the recorded CALL SEQUENCE, not on "each step ran" — a+ * refactor that reorders two steps is exactly the regression this guards.+ * `await` vs fire-and-forget is asserted too, with deferred promises: several+ * steps are correct only because a later one waits (or deliberately doesn't).+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { readFileSync } from 'fs';+import { fileURLToPath } from 'url';+import { dirname, join } from 'path';+import { stripCommentsAndNormalize } from '../lib/mirrorParity.js';+import {+ runPreRouteSequence,+ initCosAfterSpawner,+ armCommissionScheduler,+ gateOnDatabase,+ runDbAndCatalogMigrations,+ warmMandatoryStores,+ runDatabasePhase,+ runPostRouteSequence,+ runPostListenSequence+} from './bootstrapSequence.js';++const __dirname = dirname(fileURLToPath(import.meta.url));++/** Records the order steps run in. `impl` lets a step return a value/promise. */+const createRecorder = () => {+ const calls = [];+ const step = (name, impl) => vi.fn((...args) => {+ calls.push(name);+ return impl ? impl(...args) : undefined;+ });+ return { calls, step };+};++const deferred = () => {+ let resolve;+ let reject;+ const promise = new Promise((res, rej) => {+ resolve = res;+ reject = rej;+ });+ // Pre-attached no-op catch would swallow the rejection the code under test+ // must handle, so callers reject only where the sequence has a handler.+ return { promise, resolve, reject };+};++/** Let every already-queued microtask + promise continuation drain. */+const flush = () => new Promise((resolve) => setImmediate(resolve));++beforeEach(() => {+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('runPreRouteSequence — pre-route boot order', () => {+ const buildDeps = (recorder, overrides = {}) => {+ const { step } = recorder;+ return {+ applyDataMigrations: step('applyDataMigrations', () => Promise.resolve()),+ verifyCollections: step('verifyCollections', () => Promise.resolve()),+ createToolkit: step('createToolkit', () => ({ id: 'toolkit' })),+ registerToolkitShims: step('registerToolkitShims'),+ warmProviders: step('warmProviders', () => Promise.resolve([])),+ ensureLocalLlmBackend: step('ensureLocalLlmBackend'),+ registerRunners: step('registerRunners'),+ initAutoFixer: step('initAutoFixer'),+ initTaskLearning: step('initTaskLearning'),+ startSpawner: step('startSpawner', () => Promise.resolve()),+ ...overrides+ };+ };++ it('runs every step exactly once, in the documented order', async () => {+ const recorder = createRecorder();+ await runPreRouteSequence(buildDeps(recorder));+ expect(recorder.calls).toEqual([+ 'applyDataMigrations',+ 'verifyCollections',+ 'createToolkit',+ 'registerToolkitShims',+ 'warmProviders',+ 'ensureLocalLlmBackend',+ 'registerRunners',+ 'initAutoFixer',+ 'initTaskLearning',+ 'startSpawner'+ ]);+ });++ it('returns the constructed toolkit and a spawner promise', async () => {+ const recorder = createRecorder();+ const { aiToolkit, spawnerReady } = await runPreRouteSequence(buildDeps(recorder));+ expect(aiToolkit).toEqual({ id: 'toolkit' });+ await expect(spawnerReady).resolves.toBeUndefined();+ });++ it('hands the SAME toolkit instance to the shims, the provider warm, and the runners', async () => {+ const recorder = createRecorder();+ const deps = buildDeps(recorder);+ const { aiToolkit } = await runPreRouteSequence(deps);+ expect(deps.registerToolkitShims).toHaveBeenCalledWith(aiToolkit);+ expect(deps.warmProviders).toHaveBeenCalledWith(aiToolkit);+ expect(deps.registerRunners).toHaveBeenCalledWith(aiToolkit);+ });++ it('awaits the data migrations before the toolkit reads its config files', async () => {+ const recorder = createRecorder();+ const gate = deferred();+ const deps = buildDeps(recorder, {+ applyDataMigrations: recorder.step('applyDataMigrations', () => gate.promise)+ });+ const done = runPreRouteSequence(deps);+ await flush();+ // The toolkit reads stage-config.json / providers.json — a migration that+ // hasn't landed yet means "Stage X not found" on an updated install.+ expect(recorder.calls).toEqual(['applyDataMigrations']);+ gate.resolve();+ await done;+ expect(recorder.calls).toContain('createToolkit');+ });++ it('awaits the provider warm before registering runners', async () => {+ const recorder = createRecorder();+ const gate = deferred();+ const deps = buildDeps(recorder, {+ warmProviders: recorder.step('warmProviders', () => gate.promise)+ });+ const done = runPreRouteSequence(deps);+ await flush();+ expect(recorder.calls).not.toContain('registerRunners');+ gate.resolve([]);+ await done;+ expect(recorder.calls).toContain('registerRunners');+ });++ it('keeps booting when the migration run and the collection check both fail', async () => {+ const recorder = createRecorder();+ const deps = buildDeps(recorder, {+ applyDataMigrations: recorder.step('applyDataMigrations', () => Promise.reject(new Error('migrations exploded'))),+ verifyCollections: recorder.step('verifyCollections', () => Promise.reject(new Error('schema drift')))+ });+ await expect(runPreRouteSequence(deps)).resolves.toMatchObject({ aiToolkit: { id: 'toolkit' } });+ // A noisy log the user can act on beats a server that refuses to start.+ expect(recorder.calls).toContain('createToolkit');+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Migration run failed at startup'));+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Collection version check failed at startup'));+ });++ it('resolves spawnerReady even when the spawner fails, so CoS init is never blocked', async () => {+ const recorder = createRecorder();+ const deps = buildDeps(recorder, {+ startSpawner: recorder.step('startSpawner', () => Promise.reject(new Error('spawner down')))+ });+ const { spawnerReady } = await runPreRouteSequence(deps);+ await expect(spawnerReady).resolves.toBeUndefined();+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Failed to initialize spawner'));+ });++ it('does not reach the toolkit itself — every touch goes through an injected step', async () => {+ // CLAUDE.md "No cold-bootstrap LLM calls": the sequence may construct and+ // hand off the toolkit, never dispatch a run through it.+ const executeRun = vi.fn();+ const recorder = createRecorder();+ const deps = buildDeps(recorder, {+ createToolkit: recorder.step('createToolkit', () => ({+ services: { runner: { executeRun }, providers: { executeRun }, prompts: { executeRun } }+ }))+ });+ await runPreRouteSequence(deps);+ expect(executeRun).not.toHaveBeenCalled();+ });+});++describe('initCosAfterSpawner', () => {+ it('waits for the spawner before CoS init, so task:ready listeners exist', async () => {+ const spawner = deferred();+ const initCos = vi.fn(() => Promise.resolve());+ const done = initCosAfterSpawner({ spawnerReady: spawner.promise, initCos });+ await flush();+ expect(initCos).not.toHaveBeenCalled();+ spawner.resolve();+ await done;+ expect(initCos).toHaveBeenCalledTimes(1);+ });++ it('logs instead of throwing when CoS init fails', async () => {+ await initCosAfterSpawner({+ spawnerReady: Promise.resolve(),+ initCos: () => Promise.reject(new Error('cos boom'))+ });+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('CoS init failed'));+ });+});++describe('armCommissionScheduler', () => {+ it('splits legacy inline feedback before arming the per-commission crons', () => {+ const { calls, step } = createRecorder();+ armCommissionScheduler({+ backfillCommissionFeedback: step('backfill', () => Promise.resolve()),+ startCommissionScheduler: step('arm', () => Promise.resolve())+ });+ expect(calls).toEqual(['backfill', 'arm']);+ });++ it('arms the scheduler even if the backfill fails, and logs both', async () => {+ const arm = vi.fn(() => Promise.reject(new Error('cron boom')));+ armCommissionScheduler({+ backfillCommissionFeedback: () => Promise.reject(new Error('backfill boom')),+ startCommissionScheduler: arm+ });+ await flush();+ expect(arm).toHaveBeenCalledTimes(1);+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Commission feedback backfill failed'));+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Creative Commission scheduler init failed'));+ });+});++describe('gateOnDatabase', () => {+ const healthy = { connected: true, hasSchema: true, hasCatalogSchema: true };++ it('reports ready without touching ensureSchema when the DB is current', async () => {+ const ensureSchema = vi.fn();+ const onUnbootable = vi.fn();+ const result = await gateOnDatabase({+ checkHealth: vi.fn(async () => healthy),+ ensureSchema,+ escapeHatch: false,+ onUnbootable+ });+ expect(result).toEqual({ dbReady: true });+ expect(ensureSchema).not.toHaveBeenCalled();+ expect(onUnbootable).not.toHaveBeenCalled();+ });++ it('upgrades and re-probes an install that merely lags the current schema', async () => {+ const { calls, step } = createRecorder();+ // First probe reports the catalog schema missing (the shape an install that+ // pulled new code but hasn't re-run ensureSchema is in); the second, after+ // the upgrade, reports healthy.+ const probes = [{ connected: true, hasSchema: true, hasCatalogSchema: false }, healthy];+ const onUnbootable = vi.fn();+ const result = await gateOnDatabase({+ checkHealth: step('checkHealth', () => Promise.resolve(probes.shift())),+ ensureSchema: step('ensureSchema', () => Promise.resolve()),+ escapeHatch: false,+ onUnbootable+ });+ expect(calls).toEqual(['checkHealth', 'ensureSchema', 'checkHealth']);+ expect(result).toEqual({ dbReady: true });+ expect(onUnbootable).not.toHaveBeenCalled();+ });++ it('refuses to start when the DB is unreachable and no escape hatch is set', async () => {+ const onUnbootable = vi.fn();+ const result = await gateOnDatabase({+ checkHealth: vi.fn(async () => ({ connected: false, error: 'ECONNREFUSED' })),+ ensureSchema: vi.fn(),+ escapeHatch: false,+ onUnbootable+ });+ expect(result).toEqual({ dbReady: false });+ expect(onUnbootable).toHaveBeenCalledTimes(1);+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('PostgreSQL is required but unreachable'));+ });++ it('falls through the failed upgrade of an uninitialized DB to the fail-fast', async () => {+ const onUnbootable = vi.fn();+ await gateOnDatabase({+ checkHealth: vi.fn(async () => ({ connected: true, hasSchema: false, hasCatalogSchema: false })),+ ensureSchema: vi.fn(async () => {+ throw new Error('relation "memories" does not exist');+ }),+ escapeHatch: false,+ onUnbootable+ });+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Schema upgrade on boot failed'));+ expect(onUnbootable).toHaveBeenCalledTimes(1);+ });++ it('warns instead of exiting under the dev/test escape hatch', async () => {+ const onUnbootable = vi.fn();+ const result = await gateOnDatabase({+ checkHealth: vi.fn(async () => ({ connected: false, error: 'no server' })),+ ensureSchema: vi.fn(),+ escapeHatch: true,+ onUnbootable+ });+ expect(result).toEqual({ dbReady: false });+ expect(onUnbootable).not.toHaveBeenCalled();+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('booting via escape hatch'));+ });+});++describe('runDbAndCatalogMigrations', () => {+ const buildDeps = (recorder, overrides = {}) => {+ const { step } = recorder;+ return {+ dbReady: true,+ ensureSchema: step('ensureSchema', () => Promise.resolve()),+ runDbMigrations: step('runDbMigrations', () => Promise.resolve()),+ migrateBibleToCatalog: step('migrateBibleToCatalog', () => Promise.resolve()),+ repairUniverseTags: step('repairUniverseTags', () => Promise.resolve()),+ migrateCatalogPayload: step('migrateCatalogPayload', () => Promise.resolve()),+ reconcileCanonCatalog: step('reconcileCanonCatalog', () => Promise.resolve()),+ initMediaAssetIndex: step('initMediaAssetIndex', () => Promise.resolve()),+ onMigrationFailure: vi.fn(),+ ...overrides+ };+ };++ it('walks the migrations in dependency order', async () => {+ const recorder = createRecorder();+ await runDbAndCatalogMigrations(buildDeps(recorder));+ expect(recorder.calls).toEqual([+ 'ensureSchema',+ 'runDbMigrations',+ 'migrateBibleToCatalog',+ 'repairUniverseTags',+ 'migrateCatalogPayload',+ 'reconcileCanonCatalog',+ 'initMediaAssetIndex'+ ]);+ });++ it('runs nothing at all on the file escape hatch', async () => {+ const recorder = createRecorder();+ await runDbAndCatalogMigrations(buildDeps(recorder, { dbReady: false }));+ expect(recorder.calls).toEqual([]);+ });++ it('treats a failed schema-delta migration as fatal and skips the rest', async () => {+ const recorder = createRecorder();+ const deps = buildDeps(recorder, {+ runDbMigrations: recorder.step('runDbMigrations', () => Promise.reject(new Error('delta 42 failed')))+ });+ await runDbAndCatalogMigrations(deps);+ expect(recorder.calls).toEqual(['ensureSchema', 'runDbMigrations']);+ expect(deps.onMigrationFailure).toHaveBeenCalledTimes(1);+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('DB migration failed at boot'));+ });++ it('keeps booting when a best-effort catalog migration fails', async () => {+ const recorder = createRecorder();+ const deps = buildDeps(recorder, {+ repairUniverseTags: recorder.step('repairUniverseTags', () => Promise.reject(new Error('tag repair hiccup')))+ });+ await runDbAndCatalogMigrations(deps);+ expect(deps.onMigrationFailure).not.toHaveBeenCalled();+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('catalog migrations failed at boot'));+ // Later steps are skipped (they share one try block) but boot continues.+ expect(recorder.calls).toEqual(['ensureSchema', 'runDbMigrations', 'migrateBibleToCatalog', 'repairUniverseTags']);+ });+});++describe('warmMandatoryStores', () => {+ const buildDeps = (recorder, overrides = {}) => {+ const { step } = recorder;+ return {+ warmUniverses: step('warmUniverses', () => Promise.resolve([])),+ warmSeries: step('warmSeries', () => Promise.resolve([])),+ warmIssues: step('warmIssues', () => Promise.resolve([])),+ warmStoryBuilder: step('warmStoryBuilder', () => Promise.resolve([])),+ warmWritersRoom: step('warmWritersRoom', () => Promise.resolve([])),+ warmCatalogUserTypes: step('warmCatalogUserTypes', () => Promise.resolve()),+ warmCreativeDirector: step('warmCreativeDirector', () => Promise.resolve([])),+ pruneLegacyFiles: step('pruneLegacyFiles', () => Promise.resolve()),+ onWarmFailure: vi.fn(),+ ...overrides+ };+ };++ it('warms every store in soft-reference order, pruning last', async () => {+ const recorder = createRecorder();+ await warmMandatoryStores(buildDeps(recorder));+ expect(recorder.calls).toEqual([+ 'warmUniverses',+ 'warmSeries',+ 'warmIssues',+ 'warmStoryBuilder',+ 'warmWritersRoom',+ 'warmCatalogUserTypes',+ 'warmCreativeDirector',+ 'pruneLegacyFiles'+ ]);+ });++ it('refuses to start when a store cannot select its backend', async () => {+ const recorder = createRecorder();+ const deps = buildDeps(recorder, {+ warmWritersRoom: recorder.step('warmWritersRoom', () => Promise.reject(new Error('import failed')))+ });+ await warmMandatoryStores(deps);+ expect(deps.onWarmFailure).toHaveBeenCalledTimes(1);+ // The prune must NOT run: it would drop the .imported recovery copies while+ // a domain's import is still unfinished.+ expect(recorder.calls).not.toContain('pruneLegacyFiles');+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Mandatory store warmup failed at boot'));+ });+});++describe('runDatabasePhase', () => {+ const buildDeps = (recorder, gateResult = { dbReady: true }) => {+ const { step } = recorder;+ return {+ gate: step('gate', () => Promise.resolve(gateResult)),+ migrate: step('migrate', () => Promise.resolve()),+ warmStores: step('warmStores', () => Promise.resolve()),+ reconcileStackerNews: step('reconcileStackerNews', () => Promise.resolve())+ };+ };++ it('gates, migrates, warms, then arms the opt-in schedulers', async () => {+ const recorder = createRecorder();+ await runDatabasePhase(buildDeps(recorder));+ expect(recorder.calls).toEqual(['gate', 'migrate', 'warmStores', 'reconcileStackerNews']);+ });++ it('passes the gate result (dbReady + ensureSchema) straight to the migrations', async () => {+ const recorder = createRecorder();+ const gateResult = { dbReady: true, ensureSchema: () => {} };+ const deps = buildDeps(recorder, gateResult);+ const returned = await runDatabasePhase(deps);+ expect(deps.migrate).toHaveBeenCalledWith(gateResult);+ expect(returned).toBe(gateResult);+ });++ it('skips the warm + scheduler arm when there is no usable DB', async () => {+ const recorder = createRecorder();+ await runDatabasePhase(buildDeps(recorder, { dbReady: false }));+ expect(recorder.calls).toEqual(['gate', 'migrate']);+ });+});++describe('runPostRouteSequence — post-route boot order', () => {+ const buildDeps = (recorder, overrides = {}) => {+ const { step } = recorder;+ return {+ startBackgroundServices: step('startBackgroundServices'),+ ensureSelf: step('ensureSelf', () => Promise.resolve()),+ initSyncLog: step('initSyncLog', () => Promise.resolve()),+ recoverStuckClassifications: step('recoverStuckClassifications', () => Promise.resolve()),+ initMediaJobQueue: step('initMediaJobQueue', () => Promise.resolve()),+ initMediaJobDependentHooks: step('initMediaJobDependentHooks'),+ initSharing: step('initSharing', () => Promise.resolve()),+ recoverCreativeDirectorProjects: step('recoverCreativeDirectorProjects', () => Promise.resolve()),+ runDatabasePhase: step('runDatabasePhase', () => Promise.resolve({ dbReady: true })),+ backfillSeriesCoverImages: step('backfillSeriesCoverImages', () => Promise.resolve()),+ startListening: step('startListening'),+ onFatal: vi.fn(),+ ...overrides+ };+ };++ it('walks the whole chain in the documented order, ending in listen()', async () => {+ const recorder = createRecorder();+ const deps = buildDeps(recorder);+ await runPostRouteSequence(deps);+ expect(recorder.calls).toEqual([+ 'startBackgroundServices',+ 'ensureSelf',+ 'initSyncLog',+ 'recoverStuckClassifications',+ 'initMediaJobQueue',+ 'initMediaJobDependentHooks',+ 'initSharing',+ 'recoverCreativeDirectorProjects',+ 'runDatabasePhase',+ 'backfillSeriesCoverImages',+ 'startListening'+ ]);+ expect(deps.onFatal).not.toHaveBeenCalled();+ });++ it('arms the background services synchronously, before the chain awaits anything', () => {+ const recorder = createRecorder();+ const promise = runPostRouteSequence(buildDeps(recorder));+ expect(recorder.calls).toEqual(['startBackgroundServices']);+ return promise;+ });++ it('awaits the sync log before brain recovery can append to it', async () => {+ const recorder = createRecorder();+ const gate = deferred();+ const deps = buildDeps(recorder, {+ initSyncLog: recorder.step('initSyncLog', () => gate.promise)+ });+ const done = runPostRouteSequence(deps);+ await flush();+ // Recovering earlier would mint colliding sync sequence numbers and corrupt+ // every peer's cursor.+ expect(recorder.calls).not.toContain('recoverStuckClassifications');+ gate.resolve();+ await done;+ expect(recorder.calls).toContain('recoverStuckClassifications');+ });++ it('awaits the media job queue before wiring its completion hooks', async () => {+ const recorder = createRecorder();+ const gate = deferred();+ const deps = buildDeps(recorder, {+ initMediaJobQueue: recorder.step('initMediaJobQueue', () => gate.promise)+ });+ const done = runPostRouteSequence(deps);+ await flush();+ // The hooks must be listening before the queue replays `completed` for+ // reloaded jobs, and no route may enqueue against a half-init queue.+ expect(recorder.calls).toEqual(['startBackgroundServices', 'ensureSelf', 'initSyncLog', 'recoverStuckClassifications', 'initMediaJobQueue']);+ gate.resolve();+ await done;+ expect(recorder.calls).toContain('initMediaJobDependentHooks');+ expect(recorder.calls).toContain('startListening');+ });++ it('does NOT await brain recovery, sharing, CD recovery, or the cover backfill', async () => {+ const recorder = createRecorder();+ const stuck = deferred();+ const deps = buildDeps(recorder, {+ recoverStuckClassifications: recorder.step('recoverStuckClassifications', () => stuck.promise),+ initSharing: recorder.step('initSharing', () => deferred().promise),+ recoverCreativeDirectorProjects: recorder.step('recoverCreativeDirectorProjects', () => deferred().promise),+ backfillSeriesCoverImages: recorder.step('backfillSeriesCoverImages', () => deferred().promise)+ });+ // None of these ever settle; the server must still start listening.+ await runPostRouteSequence(deps);+ expect(recorder.calls).toContain('startListening');+ stuck.resolve();+ });++ it('finishes the database phase before the listener opens', async () => {+ const recorder = createRecorder();+ const gate = deferred();+ const deps = buildDeps(recorder, {+ runDatabasePhase: recorder.step('runDatabasePhase', () => gate.promise)+ });+ const done = runPostRouteSequence(deps);+ await flush();+ // A request landing on a partially-migrated install is the failure mode.+ expect(recorder.calls).not.toContain('startListening');+ gate.resolve({ dbReady: true });+ await done;+ expect(recorder.calls).toContain('startListening');+ });++ it('is fatal when an awaited step rejects, and never opens the listener', async () => {+ const recorder = createRecorder();+ const deps = buildDeps(recorder, {+ initMediaJobQueue: recorder.step('initMediaJobQueue', () => Promise.reject(new Error('queue half-init')))+ });+ await runPostRouteSequence(deps);+ expect(deps.onFatal).toHaveBeenCalledTimes(1);+ expect(recorder.calls).not.toContain('startListening');+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Instance init failed'));+ });++ it('is NOT fatal when a fire-and-forget step rejects', async () => {+ const recorder = createRecorder();+ const deps = buildDeps(recorder, {+ recoverStuckClassifications: recorder.step('recoverStuckClassifications', () => Promise.reject(new Error('brain boom'))),+ initSharing: recorder.step('initSharing', () => Promise.reject(new Error('bucket gone'))),+ backfillSeriesCoverImages: recorder.step('backfillSeriesCoverImages', () => Promise.reject(new Error('no covers')))+ });+ await runPostRouteSequence(deps);+ await flush();+ expect(deps.onFatal).not.toHaveBeenCalled();+ expect(recorder.calls).toContain('startListening');+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Brain recovery failed'));+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Sharing init failed'));+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('series cover backfill failed at boot'));+ });+});++describe('runPostListenSequence — inside the listen callback', () => {+ const buildDeps = (recorder, overrides = {}) => {+ const { step } = recorder;+ return {+ announceListening: step('announceListening'),+ setupProcessErrorHandlers: step('setupProcessErrorHandlers'),+ backfillOriginInstanceId: step('backfillOriginInstanceId', () => Promise.resolve()),+ startPolling: step('startPolling'),+ initSyncOrchestrator: step('initSyncOrchestrator'),+ ...overrides+ };+ };++ it('announces, arms the safety net, then backfills before peer sync starts', async () => {+ const recorder = createRecorder();+ await runPostListenSequence(buildDeps(recorder));+ expect(recorder.calls).toEqual([+ 'announceListening',+ 'setupProcessErrorHandlers',+ 'backfillOriginInstanceId',+ 'startPolling',+ 'initSyncOrchestrator'+ ]);+ });++ it('does not start peer polling until origin tags are backfilled', async () => {+ const recorder = createRecorder();+ const gate = deferred();+ const done = runPostListenSequence(buildDeps(recorder, {+ backfillOriginInstanceId: recorder.step('backfillOriginInstanceId', () => gate.promise)+ }));+ await flush();+ // Polling a peer first would ship records with no originInstanceId.+ expect(recorder.calls).not.toContain('startPolling');+ gate.resolve();+ await done;+ expect(recorder.calls).toContain('startPolling');+ });++ it('logs and continues when the backfill fails', async () => {+ const recorder = createRecorder();+ await runPostListenSequence(buildDeps(recorder, {+ backfillOriginInstanceId: recorder.step('backfillOriginInstanceId', () => Promise.reject(new Error('tag boom')))+ }));+ expect(recorder.calls).not.toContain('startPolling');+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Post-startup init failed'));+ });+});++/**+ * Source contract. The behavioural tests above run the sequence with doubles;+ * these assert the properties that only the real files can carry — that boot is+ * silent on the LLM front, and that the tested ordering is the one that actually+ * runs on a real install.+ */+describe('boot source contract', () => {+ const read = (rel) => stripCommentsAndNormalize(readFileSync(join(__dirname, rel), 'utf-8').replace(/\r\n/g, '\n'));+ const BOOTSTRAP = read('bootstrap.js');+ const SEQUENCE = read('bootstrapSequence.js');++ // Every entry point that dispatches work to an AI provider. CLAUDE.md's+ // "No cold-bootstrap LLM calls": a fresh install coming online must be silent+ // until the user asks for AI-backed work. Boot may ARM a scheduler (which+ // gates on user config before it ever fires) but must never call these.+ const PROVIDER_CALLS = [+ 'runStagedLLM',+ 'runInlineLLM',+ 'runStageScopedInlineLLM',+ 'runPromptThroughProvider',+ 'executeCliRun',+ 'executeTuiRun',+ 'executeApiRun',+ 'createRun'+ ];++ for (const [label, src] of [['bootstrap.js', BOOTSTRAP], ['bootstrapSequence.js', SEQUENCE]]) {+ it(`${label} queues no AI provider call at boot`, () => {+ for (const name of PROVIDER_CALLS) {+ // A bare reference (e.g. handing executeCliRun to setCliRunner) is fine —+ // registering a runner is not invoking one. Only an invocation fails.+ expect(src, `${label} invokes ${name}() during boot`).not.toMatch(new RegExp(`\\b${name}\\s*\\(`));+ }+ });+ }++ it('bootstrapSequence.js imports nothing — every dependency is injected', () => {+ // An import here would both defeat the "runs without a real install"+ // property these tests rely on and let a service sneak into the boot path+ // untested.+ expect(SEQUENCE).not.toMatch(/\bimport\s/);+ });++ it('bootstrap.js delegates its ordering to the tested sequence module', () => {+ expect(BOOTSTRAP).toMatch(/from '\.\/bootstrapSequence\.js'/);+ for (const fn of ['runPreRouteSequence', 'runPostRouteSequence', 'runPostListenSequence', 'runDatabasePhase']) {+ expect(BOOTSTRAP, `bootstrap.js never calls ${fn}() — the tested ordering would be dead code`)+ .toMatch(new RegExp(`\\b${fn}\\s*\\(`));+ }+ });+});