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
Make PostgreSQL mandatory + add storage-classification contract
Adam Eivye1750b49a901
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 592b73c5ed..2b962fa9dc 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,6 +10,7 @@## Changed+- **PostgreSQL is now a required dependency** — file-based JSON storage is no longer offered as a normal setup choice. `npm run setup:db` presents only Docker and Native PostgreSQL hosting modes (and auto-selects native when a healthy local PostgreSQL is already reachable). On boot, PortOS now verifies the database is reachable with the required schema and refuses to start with an actionable message if it isn't — instead of silently falling back to file-backed memory and serving a half-broken install (the creative catalog has no file-backed equivalent). `MEMORY_BACKEND=file` survives only as an explicit, unsupported development/test escape hatch. New docs: [`docs/STORAGE.md`](../docs/STORAGE.md) (the storage-classification contract — `db-primary` / `file-primary` / `asset-file-db-indexed` / `ephemeral-file` — plus a "new data store?" review checklist) and [`docs/BACKUP.md`](../docs/BACKUP.md) (backup/restore now that the Postgres dump is required system state).- **Local model pickers now show what's actually installed** — the Fallback Model dropdown in the AI Provider editor and the provider/model selector in the manuscript editorial review previously only listed the models stored on the provider record, so models you'd pulled in Ollama later (e.g. Command R+, Gemma) never appeared. Both pickers now fold in the live list of installed Ollama / LM Studio models. Embedding-only models (e.g. `nomic-embed-text`) are filtered out of these generation pickers since they can't run a prompt.- **Editorial model recommendation** — the manuscript editorial review now suggests the best installed local model for editing/feedback (a one-tap "Recommended for editing" chip), ranking models that follow instructions tightly (Qwen/Llama/Gemma) ahead of chatty/RAG-tuned ones (Command R+) and skipping embedding/code/vision models. The pick is always among your *installed* models, so it auto-adapts as you pull newer versions.- **Model context windows are now visible** — each model card on Settings → Local LLM shows its native context length (e.g. "32K ctx"), and the provider/model selector dropdowns (AI Provider editor, manuscript editorial review) annotate each local model with its window as a parenthetical.diff --git a/CLAUDE.md b/CLAUDE.mdindex af2541e535..67437eba08 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -163,6 +163,7 @@ PortOS has reached the size where re-implementing a helper is now cheaper to *st- **HTTP / Socket / browser clients** → `client/src/services/`. API wrappers start with `api*`.- **Express handlers** → `server/routes/`. Use `validateRequest` + `lib/validation.js` schemas.- **Domain orchestration (multi-step business logic over models + services)** → `server/services/`.+- **Persisted data (where a record lives — PostgreSQL vs a `data/` file)** → decide via the storage-classification contract in `docs/STORAGE.md` *before* defaulting to a new `data/*.json`. App-native relational records are `db-primary` (PostgreSQL); the doc's "Adding a new data store?" checklist is required in PR review.One concern per file. Tests live next to their source as `<name>.test.js`. Naming is camelCase with a domain prefix (`brainValidation.js`, `creativeDirectorPrompts.js`).diff --git a/README.md b/README.mdindex 193b350f64..2ccf12c821 100644--- a/README.md+++ b/README.md@@ -324,6 +324,8 @@ Configure AI providers for the runner and Chief of Staff:### Architecture & Operations- [Architecture Overview](./docs/ARCHITECTURE.md) — System design, data flow, and service diagram- [API Reference](./docs/API.md) — 50+ REST endpoints and WebSocket events+- [Storage Classification Contract](./docs/STORAGE.md) — when data belongs in PostgreSQL vs the filesystem, plus the new-data-store checklist+- [Backup & Restore](./docs/BACKUP.md) — filesystem snapshots + mandatory PostgreSQL dumps and how to restore them- [Port Allocation](./docs/PORTS.md) — Port conventions (5553-5561) and allocation guide- [PM2 Configuration](./docs/PM2.md) — PM2 patterns and best practicesdiff --git a/docs/BACKUP.md b/docs/BACKUP.mdnew file mode 100644index 0000000000..64e8907a03--- /dev/null+++ b/docs/BACKUP.md@@ -0,0 +1,85 @@+# Backup & Restore++PortOS backs up two things together, into a single timestamped snapshot:++1. **Filesystem data** — an rsync mirror of `./data/` (with SHA-256 manifest).+2. **PostgreSQL** — a `pg_dump` logical dump (`portos-db.sql`) written alongside the snapshot.++Now that PostgreSQL is a **required** dependency (it owns the creative catalog, memory, and a growing set of app-native records — see [Storage Classification Contract](./STORAGE.md)), **the database dump is part of required system state, not an optional extra.** A snapshot that captured `data/` but failed to capture the DB is incomplete, and PortOS surfaces that explicitly.++Implementation: `server/services/backup.js` (snapshot/dump/restore), `server/services/backupScheduler.js` (cron), `server/routes/backup.js` (API), and `server/routes/database.js` (DB export/sync).++## What gets backed up++A backup run (`runBackup` in `server/services/backup.js`) writes to:++```+<destPath>/snapshots/<hostname>/<snapshotId>/+├── data/ # rsync mirror of ./data/ (minus excludes)+├── portos-db.sql # pg_dump logical dump+└── manifest.json # SHA-256 of every data/ file AND ../portos-db.sql+```++- Snapshots are namespaced by `<hostname>` so one shared destination (e.g. an iCloud folder) can host backups from several federated machines without `snapshotId` collisions.+- The `manifest.json` hashes the SQL dump too (keyed as `../portos-db.sql`, since the dump lives one level above the `data/` tree), so a truncated or corrupt dump is detectable rather than silently trusted.++### What is excluded by default++`DEFAULT_EXCLUDES` (in `backup.js`) skips ephemeral/cache data and large re-downloadable assets — all anchored with a leading `/` (rsync filter syntax). Two tiers:++- **Non-overridable** (`overridable: false`): browser CDP profile, agent worktrees — caches with no irreplaceable user data; never backed up.+- **Overridable** (`overridable: true`): LoRA weight files, cloned repos, reference repos, browser downloads — re-downloadable; the user can opt back in from the Backup settings UI via `disabledDefaultExcludes`.++The effective exclude list is computed by the pure `computeEffectiveExcludes()` helper (unit-tested in `backup.test.js`). The scheduled cron handler in `backupScheduler.js` re-reads settings on every run, so `destPath`, `excludePaths`, `disabledDefaultExcludes`, and `enabled` all take effect on the next run without a restart.++## The Postgres dump is mandatory, not optional++`dumpPostgres()` runs `pg_dump --no-owner --no-acl --clean --if-exists` and returns an explicit status (no silent failure):++| Result | Meaning | Effect on backup |+|---|---|---|+| `{ status: 'ok', sizeBytes, tableCount }` | Dump succeeded and is non-empty | Backup `ok` |+| `{ status: 'failed', reason: 'pg_unreachable' \| 'pg_dump_missing' \| 'dump_error' \| 'empty_dump' }` | Postgres is the active backend but the dump failed | Backup **`degraded`** + warning toast |+| `{ status: 'skipped', reason: 'not_configured' }` | Postgres is not the active backend (legacy `MEMORY_BACKEND=file` dev/test mode) | Backup stays `ok` (benign) |++Key behaviors, accurate to the code:++- **A failed dump degrades the whole backup.** `backupStatusForPg()` maps `failed → 'degraded'`; the run persists `pgBackup` into `data/backup/state.json` and emits a `BACKUP_DB_DUMP_FAILED` warning through the error pipeline — **even on unattended scheduled runs** (which pass `io = null`; the service falls back to the module-level `getIo()`).+- **A skipped dump is still benign** only for the temporary `MEMORY_BACKEND=file` escape hatch (documented as unsupported for production installs). On a normal install where Postgres is active or auto-detected, an unreachable DB returns `failed/pg_unreachable`, not a green "not configured" run.+- **`--clean --if-exists`** makes the dump replay cleanly into a live, already-initialized PortOS database — the common restore target — instead of erroring on `relation already exists`.+- A `pg_dump` that exits 0 but produces a 0-byte file is treated as `failed/empty_dump`; a non-zero exit deletes the partial file so a later restore can't trust a truncated dump.++## How restore works++Restore is two independent operations — restoring files and restoring the DB are separate decisions. Both are **dry-run by default** and validate `snapshotId` against path traversal before touching anything.++### Files — `restoreSnapshot()`++rsyncs `<snapshot>/data/` back to `./data/`. `dryRun: true` (the default) reports what would change without writing; an optional `subdirFilter` limits the restore to one subdirectory.++### Database — `restorePostgres()`++Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ERROR_STOP=1 --single-transaction`, so the restore is **atomic**: it either fully applies or rolls back, never leaving a mixed snapshot/current state.++| Result | Meaning |+|---|---|+| `{ status: 'ok', dryRun, sizeBytes, tableCount }` | Dry-run report, or a successful real restore |+| `{ status: 'skipped', reason: 'no_dump' }` | No `portos-db.sql` in the snapshot (or 0 bytes) |+| `{ status: 'skipped', reason: 'not_configured' }` | Real restore requested but Postgres is unreachable — refuses to half-restore |+| `{ status: 'failed', reason: 'restore_error', error }` | `psql` replay failed (stderr captured) |++A non-dry-run restore requires a reachable DB first (`checkHealth()`), so a restore never half-applies against a down database.++### Backend export / sync — `POST /api/database/sync`++Separate from snapshot restore: `server/routes/database.js` can copy data **between** the native (port 5432) and Docker (port 5561) Postgres backends. It exports the active backend with `pg_dump`, ensures the target backend has the `portos` role/database/extensions, then imports under `ON_ERROR_STOP=1 --single-transaction`. `POST /api/database/export` produces an on-demand dump under `data/db-dumps/`. These power the Database settings tab's mode-switch/sync flows; they are independent of the rsync snapshot backups above.++## Scheduling & status++- Daily backups are driven by `backupScheduler.js` via the `backup-daily` cron event; `getNextRunTime()` reports the next run.+- `GET /api/backup/status` surfaces the persisted state including the last `pgBackup` outcome, so the Backup settings tab shows whether the last DB dump succeeded, its size, and table count.++## See also++- [Storage Classification Contract](./STORAGE.md) — which data lives in Postgres vs files (and therefore which half of a snapshot captures it).+- [`docs/superpowers/specs/2026-06-05-verified-pg-backup-design.md`](./superpowers/specs/2026-06-05-verified-pg-backup-design.md) — design rationale for verified, restorable DB backups.diff --git a/docs/STORAGE.md b/docs/STORAGE.mdnew file mode 100644index 0000000000..25e185ade5--- /dev/null+++ b/docs/STORAGE.md@@ -0,0 +1,117 @@+# Storage Classification Contract++PortOS stores data in two places: **PostgreSQL** (app-native relational records, search/vector indexes, sync cursors, lineage) and the **filesystem** under `./data/` (large binary assets, externally-editable prose, model weights, transient queues, and explicitly file-sync-oriented domains).++PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](./BACKUP.md) and `scripts/setup-db.js`). Files remain first-class for the things a relational DB is bad at. This document is the contract for deciding **which home a given domain belongs in** — and the checklist a reviewer should apply before any new feature defaults to "just write another `data/*.json`."++> For the full domain-by-domain inventory (every current table and `data/` store, with Postgres-fit notes), see the plan doc: [`docs/plans/2026-06-06-create-postgres-storage-inventory.md`](./plans/2026-06-06-create-postgres-storage-inventory.md). This page covers the **contract and decision rules**, not the exhaustive list.++## The Four Storage Classes++| Class | Bytes live | Searchable metadata | Use when | PortOS examples |+|---|---|---|---|---|+| `db-primary` | PostgreSQL | PostgreSQL | App-native relational records: relationships, indexes, status, lineage, sync cursors, tombstones | `catalog_ingredients`, `catalog_ingredient_relations`, `memories`; **target:** universes, series, issues, Creative Director, media metadata |+| `file-primary` | Filesystem | Filesystem (DB may index) | The record IS an external file, or it must survive in a file-sync workflow (iCloud, Git, hand-editing) | Writers Room draft `.md` bodies, MortalLoom / Health / Meatspace iCloud stores |+| `asset-file-db-indexed` | Filesystem | PostgreSQL | Large binary payloads whose **metadata** must be queryable/searchable | Generated images/videos/audio + DB asset rows referencing them via `asset_key` / `media_key` |+| `ephemeral-file` | Filesystem | None (or DB job ref only) | Transient/regenerable runtime state — queues, uploads, caches | `data/uploads/*`, runtime media job queue, browser profile/cache |++**The one rule that ties them together: the DB points to files; it does not absorb the bytes.** Any file asset referenced from the DB gets a stable `asset_key` / `media_key` row plus integrity metadata. Bytes never go into a column.++---++## `db-primary` — app-native relational records++**Definition.** Records that PortOS itself authors and relates: they have foreign keys, statuses, audit trails, search/vector indexes, and federated sync cursors/tombstones. The DB is the source of truth; there is no meaningful file representation of the record.++**When to use.** The record participates in relationships (`series.universeId`, `issue.seriesId`, catalog refs), needs cross-record queries ("everything related to this universe"), needs full-text or vector search, or needs per-table sequence cursors for peer sync.++**Where it lives.** PostgreSQL via `server/lib/db.js` + `server/scripts/init-db.sql`. Service modules own the storage adapter (e.g. `server/services/catalogDB.js`, `server/services/memoryDB.js`).++**Examples.**+- `catalog_ingredients` — typed creative records with JSONB payload, tags, embeddings, generated `search_tsv`, soft delete, sync sequence.+- `catalog_ingredient_relations` — directed ingredient→ingredient graph edges (the strongest argument for Postgres as the catalog graph store).+- `memories` / `memory_links` — long-term memory + pgvector similarity.++**Postgres-First target.** Universes, pipeline series/issues, Story Builder sessions, Creative Director project/scene/run state, and searchable media metadata are all `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. Catalog user-defined types should also move from `settings.json` into catalog DB tables.++---++## `file-primary` — external-file or sync-sensitive records++**Definition.** The record either **is** an external file (long prose, a model, a repo) or must remain a file to preserve a sync/editing workflow PortOS does not own (iCloud, external editors, Git). A DB row may index it, but the file is authoritative for the body.++**When to use.** The payload is long externally-editable prose; the domain syncs through iCloud/file-sync outside PortOS; or forcing the record through the app DB would break an existing sync boundary.++**Where it lives.** Filesystem under `./data/` (or an OS-managed sync container). DB may hold metadata/index rows (hashes, word counts, segment indexes) but **not** the body.++**Examples.**+- Writers Room draft bodies — `data/writers-room/works/{workId}/drafts/{draftId}.md`. Keep `.md` file-backed; store metadata/index rows in DB.+- MortalLoom / Health / Meatspace health data — `data/health`, `data/meatspace`, MortalLoom iCloud store. Kept file-backed to preserve iCloud/file sync and avoid routing sensitive health records through the app DB before that boundary is designed.+- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.++---++## `asset-file-db-indexed` — bytes on disk, metadata in DB++**Definition.** Large binary payloads (images, video, audio, model weights) stay on disk as bytes, while their **searchable metadata** — provenance, gen params, favorites, notes, lineage, collection membership — lives in PostgreSQL as asset rows that reference the file by a stable key.++**When to use.** You have generated or imported binary assets that the user needs to search, filter, favorite, or relate to other records, but the bytes themselves are large and have no business in a column.++**Where it lives.** Bytes under `./data/` (`data/images/*`, `data/videos/*`, `data/audio/*`, `data/music/*`, thumbnails). Metadata in DB asset rows keyed by `asset_key` / `media_key`, with integrity metadata (SHA-256 — see `server/lib/assetHash.js`). The DB row references the file; it never embeds the bytes.++**Examples.**+- Generated images — `data/images/*` bytes + `.metadata.json` sidecars today; **target:** searchable metadata, provenance, favorites, notes move to DB asset rows; bytes stay on disk.+- Generated videos — `data/videos/*`, `data/video-thumbnails/*` bytes; metadata/history/lineage move to DB.+- Media collections — many-to-many links over assets/universes/series/catalog media pointers (`db-primary` link tables) pointing at `asset-file-db-indexed` bytes.++**Postgres-First target.** Image/video history (`data/history.jsonl`, `data/video-history.json`) is strong for metadata-in-DB; the bytes remain files. Do **not** move generated image/video/audio bytes into PostgreSQL.++---++## `ephemeral-file` — queues / uploads / transient state++**Definition.** Regenerable, short-lived runtime state. Losing it costs at most an in-flight job or a cache rebuild — never durable user data. It should never be the only home for anything the user expects to persist.++**When to use.** Upload staging, in-flight job queues, caches, and scratch state. If a record must survive a reinstall or be queryable across records, it is **not** `ephemeral-file` — promote it.++**Where it lives.** Filesystem under `./data/`, frequently excluded from backups (see `DEFAULT_EXCLUDES` in `server/services/backup.js`). The DB may hold a durable **job reference** even when the staging bytes are ephemeral.++**Examples.**+- Upload staging — `data/uploads/*`. Ephemeral; do not put in DB except as job references.+- Media job queue — runtime queue state can stay file-backed short term, but **job history and artifact lineage are `db-primary`** and should move to the DB.+- Browser CDP profile / downloads — `data/browser-profile/`, `data/browser-downloads/` — cache, non-overridable backup excludes.++---++## Postgres-First Target Boundaries++The contract draws a single line:++- **PostgreSQL owns** app-native records, relationships, indexes, sync cursors, tombstones, lineage, status, and searchable metadata.+- **Files own** large binary payloads, long externally-editable prose bodies, model weights, temporary uploads, and iCloud-backed health/life stores.+- **File assets referenced from the DB** get a stable `asset_key` / `media_key` row plus integrity metadata. The DB points to files; it does not absorb the bytes.++Defaulting a new Create feature to a fresh `data/*.json` file is the anti-pattern this contract exists to stop. Monolithic JSON in hot paths (`creative-director-projects.json`, `media-jobs.json`, `video-history.json`) already causes write contention and growth risk; string-id cross-references across separate JSON stores drift with no integrity check. New relational surfaces should be `db-primary` from the start.++---++## Adding a new data store? Answer these++Apply this checklist to **every new feature that persists data**, and require it in PR review. A new `data/*.json` store must *justify* itself against these questions — the default for app-native records is PostgreSQL.++- [ ] **Which class is it?** Tag the domain `db-primary`, `file-primary`, `asset-file-db-indexed`, or `ephemeral-file`. If you cannot pick one cleanly, the design is probably mixing concerns.+- [ ] **Does it relate to other records?** FKs, cross-record queries, "show everything related to X", graph edges → `db-primary`. Do not encode relationships as string ids across separate JSON files (they drift with no integrity check).+- [ ] **Does it need search?** Full-text or vector search → PostgreSQL (`search_tsv` / pgvector), not an app-level scan over JSON files.+- [ ] **If you chose a new `data/*.json`, why not the DB?** Acceptable reasons: large binary bytes (`asset-file-db-indexed` — index the metadata, keep bytes on disk), long externally-editable prose, an iCloud/file-sync workflow PortOS does not own, or genuinely transient runtime state (`ephemeral-file`). "It was faster to write a JSON file" is **not** acceptable for app-native relational records.+- [ ] **Bytes vs. pointer.** If binary assets are involved, confirm bytes stay on disk and the DB holds only an `asset_key` / `media_key` row + integrity metadata. Never store bytes in a column.+- [ ] **Federation.** If the record syncs to peers, does it have a per-table/per-record sequence cursor and tombstone strategy? (See `server/lib/schemaVersions.js`, `server/lib/syncWire.js`.) Cross-machine sync is first-class — see the Distribution model in [`CLAUDE.md`](../CLAUDE.md).+- [ ] **Migration.** On-disk/DB format changes need a migration in `scripts/migrations/` (applied-list tracked per install in `data/migrations.applied.json`) and seed files in `data.reference/`. Other installs and other federated machines upgrade independently.+- [ ] **Backup coverage.** Will the new store be captured by backup? `db-primary` is covered by the Postgres dump; `file-primary` / `asset-file-db-indexed` by the rsync snapshot; `ephemeral-file` is correctly excluded (`DEFAULT_EXCLUDES`). Confirm the store lands in the right bucket. See [Backup & Restore](./BACKUP.md).++---++## See also++- [Backup & Restore](./BACKUP.md) — what gets backed up (data/ files + mandatory Postgres dump) and how restore works.+- [`docs/plans/2026-06-06-create-postgres-storage-inventory.md`](./plans/2026-06-06-create-postgres-storage-inventory.md) — full inventory + migration phases.+- [`server/lib/README.md`](../server/lib/README.md) — storage helpers (`collectionStore`, `fileUtils`, `db.js`, `assetHash`).diff --git a/scripts/setup-db.js b/scripts/setup-db.jsindex 2f9e760a69..fe5f836d3e 100644--- a/scripts/setup-db.js+++ b/scripts/setup-db.js@@ -186,19 +186,21 @@ function promptStorageChoice(message, hint) {console.log(`⚠️ ${message}`);console.log(` ${hint}`);console.log('');- console.log(' Choose a storage backend:');+ console.log(' Choose a PostgreSQL hosting mode:');console.log('');console.log(' 1) Docker PostgreSQL (recommended — containerized, no system install)');console.log(' 2) Native PostgreSQL (use system-installed PostgreSQL on port 5432)');- console.log(' 3) File-based JSON storage (deprecated — no vector search)');console.log('');+ // NOTE: File-based JSON storage is intentionally NOT offered here. PostgreSQL+ // is a mandatory dependency (the creative catalog has no file-backed+ // equivalent). `PGMODE=file` survives only as an advanced/unsupported dev+ // escape hatch honored when already present in .env — never a menu choice.const rl = createInterface({ input: process.stdin, output: process.stdout });- rl.question(' Enter choice [1/2/3]: ', (answer) => {+ rl.question(' Enter choice [1/2]: ', (answer) => {rl.close();const trimmed = answer.trim();if (trimmed === '2') resolve('native');- else if (trimmed === '3') resolve('file');else resolve('exit'); // 1 or default = they want docker, so exit to install it});});@@ -243,6 +245,17 @@ function exitNativeSetupFailed() {}async function handleDockerUnavailable(message, issue) {+ // Default to native when a healthy local PortOS PostgreSQL is already+ // reachable — no need to prompt or fall back to Docker. The schema-ready+ // probe (role can auth + memories table present) is the proof that a usable+ // native PostgreSQL 17 + pgvector install is in place.+ if (isPortOSDbReady()) {+ console.log(' Healthy native PostgreSQL detected — using native mode.');+ setPgMode('native');+ console.log(`✅ PortOS database ready on port ${PG_PORT_NATIVE}`);+ process.exit(0);+ }+const hint = getDockerHints(issue);const choice = await promptStorageChoice(message, hint);@@ -264,12 +277,6 @@ async function handleDockerUnavailable(message, issue) {exitNativeSetupFailed();}- if (choice === 'file') {- setPgMode('file');- console.log(' Memory system will use file-based JSON storage (deprecated)');- process.exit(0);- }-// choice === 'exit' — user wants Docker, tell them to install/start itconsole.log(` ${hint}`);console.log(' Install/start Docker and re-run setup');@@ -279,8 +286,13 @@ async function handleDockerUnavailable(message, issue) {const mode = getMode();if (mode === 'file') {- console.log('🗄️ Storage mode: file-based JSON (deprecated)');- console.log(' Tip: switch to PostgreSQL with: scripts/db.sh set-mode docker');+ // Advanced/unsupported escape hatch: PGMODE=file is honored ONLY when a user+ // has explicitly set it in .env. It is not a normal setup choice — PostgreSQL+ // is a mandatory dependency for production installs and the creative catalog+ // has no file-backed equivalent. Kept for development/tests.+ console.error('🚫 PGMODE=file is UNSUPPORTED for production — PostgreSQL is required.');+ console.error(' File-based storage has no creative-catalog or vector-search support.');+ console.log(' Switch to a supported mode with: scripts/db.sh set-mode native (or docker)');process.exit(0);}@@ -329,9 +341,10 @@ try {cwd: rootDir});} catch (err) {- console.error(`⚠️ Failed to start PostgreSQL: ${err.message}`);- console.log(' Memory system will use file-based JSON storage');- process.exit(0);+ console.error(`❌ Failed to start PostgreSQL container: ${err.message}`);+ console.error(' PostgreSQL is required — try native mode instead:');+ console.error(' scripts/db.sh set-mode native && npm run setup');+ process.exit(1);}// Wait for healthdiff --git a/scripts/setup-db.test.js b/scripts/setup-db.test.jsnew file mode 100644index 0000000000..e1ebec2962--- /dev/null+++ b/scripts/setup-db.test.js@@ -0,0 +1,33 @@+import { describe, it, expect } from 'vitest';++// setup-db.js executes top-level setup logic on import (it's a CLI entrypoint),+// so we can't import it without running the whole flow. Following the repo+// convention for pure-logic coverage, we copy the menu-choice resolver inline+// and assert its post-Phase-1 contract: only Docker (1) and Native (2) are+// offered — file (the deprecated "3") is no longer a normal menu choice.+//+// Keep this in sync with promptStorageChoice() in setup-db.js.+function resolveMenuChoice(answer) {+ const trimmed = String(answer).trim();+ if (trimmed === '2') return 'native';+ return 'exit'; // 1 or default = they want docker, so exit to install it+}++describe('setup-db menu choice resolver (Phase 1: Postgres mandatory)', () => {+ it('maps "2" to native', () => {+ expect(resolveMenuChoice('2')).toBe('native');+ });++ it('maps "1" (and default/empty) to docker exit', () => {+ expect(resolveMenuChoice('1')).toBe('exit');+ expect(resolveMenuChoice('')).toBe('exit');+ expect(resolveMenuChoice(' ')).toBe('exit');+ });++ it('no longer offers file storage as a numbered choice — "3" is not "file"', () => {+ expect(resolveMenuChoice('3')).not.toBe('file');+ // Any out-of-range answer falls through to the docker-install path.+ expect(resolveMenuChoice('3')).toBe('exit');+ expect(resolveMenuChoice('file')).toBe('exit');+ });+});diff --git a/server/index.js b/server/index.jsindex cabb870c9f..76db95d008 100644--- a/server/index.js+++ b/server/index.js@@ -753,11 +753,43 @@ ensureSelf()// Catalog backfill: promote universe canon (characters/places/objects)// into the Postgres ingredients catalog. Idempotent — marker in// data/catalog-backfill.applied.json gates the walk after the first run.- // Fire-and-forget so a DB hiccup doesn't block server boot — the route- // surface tolerates an empty catalog and the user can re-trigger via- // the admin endpoint.+ // Individual migration steps stay inside a try/catch so a transient hiccup+ // mid-walk doesn't crash an otherwise-healthy boot; the route surface+ // tolerates an empty catalog and the user can re-trigger via the admin+ // endpoint.+ //+ // PostgreSQL is a mandatory dependency. Before running any DB-dependent+ // boot work, verify the database is reachable and the required schema is+ // present. If not — 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 instead.+ //+ // Escape hatches (dev/tests only, UNSUPPORTED for production):+ // - MEMORY_BACKEND=file (explicit file backend)+ // - NODE_ENV=test (test suites boot without a database)+ const dbEscapeHatch =+ process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test';+ const { checkHealth, ensureSchema } = await import('./lib/db.js');+ const health = await checkHealth();+ const dbReady = health.connected && health.hasSchema;+ 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 MEMORY_BACKEND=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.`);+ }+try {- const { ensureSchema } = await import('./lib/db.js');+ // Skip DB-dependent boot work entirely when running on the escape hatch+ // without a healthy database — ensureSchema/migrations would throw.+ if (!dbReady) {+ return;+ }await ensureSchema();const { migrateBibleToCatalog } = await import('./scripts/migrateBibleToCatalog.js');await migrateBibleToCatalog();diff --git a/server/services/memoryBackend.js b/server/services/memoryBackend.jsindex 9e9e0aaa51..e1f136b565 100644--- a/server/services/memoryBackend.js+++ b/server/services/memoryBackend.js@@ -26,10 +26,14 @@ async function getBackend() {const envBackend = process.env.MEMORY_BACKEND;+ // `MEMORY_BACKEND=file` is an explicit, UNSUPPORTED-for-production escape+ // hatch — honored for development/tests only. PostgreSQL is the mandatory+ // backend for normal installs (the creative catalog has no file-backed+ // equivalent). See docs/plans/2026-06-06-create-postgres-storage-inventory.md.if (envBackend === 'file') {backend = await import('./memory.js');backendName = 'file';- console.log('🧠 Memory backend: file-based (JSON)');+ console.log('🧠 Memory backend: file-based (JSON) — explicit MEMORY_BACKEND=file (unsupported for production)');return backend;}@@ -41,20 +45,36 @@ async function getBackend() {return backend;}- // Auto-detect: try PostgreSQL first, fall back to file+ // MEMORY_BACKEND unset: require PostgreSQL. We do NOT silently fall back to+ // file storage when Postgres is unavailable — that masks a broken install.const health = await checkHealth();if (health.connected && health.hasSchema) {await ensureSchema();backend = await import('./memoryDB.js');backendName = 'postgres';console.log('🧠 Memory backend: PostgreSQL + pgvector (auto-detected)');- } else {+ return backend;+ }++ // Postgres is required but unavailable/unhealthy. The only sanctioned+ // file-backed path here is the test/dev escape hatch — and that requires+ // NODE_ENV=test (explicit MEMORY_BACKEND=file is handled above). Tests boot+ // without a database; gate the file backend on test mode so a real install+ // never silently serves file-backed memory.+ if (process.env.NODE_ENV === 'test') {backend = await import('./memory.js');backendName = 'file';- console.log(`🧠 Memory backend: file-based (PostgreSQL unavailable: ${health.error || 'no schema'})`);+ console.log(`🧠 Memory backend: file-based (test mode — PostgreSQL unavailable: ${health.error || 'no schema'})`);+ return backend;}- return backend;+ // Production / normal install with no DB and no escape hatch: this is an+ // error condition, not a fallback. Log loudly and point at setup. Startup+ // (server/index.js) fails fast on the same condition.+ console.error(`❌ Memory backend unavailable: PostgreSQL is required but ${health.connected ? 'the schema is missing' : `unreachable (${health.error || 'connection failed'})`}`);+ console.error(' PostgreSQL is a mandatory dependency for PortOS. Set it up with: npm run setup:db');+ console.error(' Dev/test only: set MEMORY_BACKEND=file in .env to use the (unsupported) file backend.');+ throw new Error('PostgreSQL is required for the memory backend — run `npm run setup:db`');}/**diff --git a/server/services/memoryBackend.test.js b/server/services/memoryBackend.test.jsnew file mode 100644index 0000000000..0487091f5e--- /dev/null+++ b/server/services/memoryBackend.test.js@@ -0,0 +1,93 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// memoryBackend caches the selected backend in module scope, so each scenario+// re-imports the module fresh via vi.resetModules() + dynamic import. The four+// dependencies are mocked at the top; the db health result is driven per-test+// through the mocked checkHealth().++const checkHealth = vi.fn();+const ensureSchema = vi.fn();++vi.mock('../lib/db.js', () => ({+ checkHealth: (...args) => checkHealth(...args),+ ensureSchema: (...args) => ensureSchema(...args),+}));++// Sentinel modules so we can assert which backend was selected without+// pulling in the real (DB/file) implementations.+vi.mock('./memory.js', () => ({ __backend: 'file', invalidateCaches: vi.fn() }));+vi.mock('./memoryDB.js', () => ({ __backend: 'postgres', invalidateCaches: vi.fn() }));+vi.mock('./memoryConfig.js', () => ({ DEFAULT_MEMORY_CONFIG: {} }));++const ORIGINAL_ENV = { ...process.env };++async function loadFresh() {+ vi.resetModules();+ return import('./memoryBackend.js');+}++describe('memoryBackend backend selection', () => {+ beforeEach(() => {+ checkHealth.mockReset();+ ensureSchema.mockReset();+ ensureSchema.mockResolvedValue(undefined);+ // Start each test from a clean env; individual tests opt in to flags.+ delete process.env.MEMORY_BACKEND;+ delete process.env.NODE_ENV;+ });++ afterEach(() => {+ process.env = { ...ORIGINAL_ENV };+ });++ it('selects PostgreSQL when MEMORY_BACKEND=postgres', async () => {+ process.env.MEMORY_BACKEND = 'postgres';+ const mod = await loadFresh();+ const name = await mod.ensureBackend();+ expect(name).toBe('postgres');+ expect(ensureSchema).toHaveBeenCalled();+ expect(checkHealth).not.toHaveBeenCalled();+ });++ it('honors the explicit MEMORY_BACKEND=file escape hatch even when Postgres is healthy', async () => {+ process.env.MEMORY_BACKEND = 'file';+ // Postgres is fully available — the explicit escape hatch must still win.+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });+ const mod = await loadFresh();+ const name = await mod.ensureBackend();+ expect(name).toBe('file');+ // Escape hatch short-circuits before any health probe.+ expect(checkHealth).not.toHaveBeenCalled();+ });++ it('auto-detects PostgreSQL when unset and the DB is healthy', async () => {+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });+ const mod = await loadFresh();+ const name = await mod.ensureBackend();+ expect(name).toBe('postgres');+ expect(ensureSchema).toHaveBeenCalled();+ });++ it('does NOT silently fall back to file when unset and Postgres is unavailable (non-test mode)', async () => {+ process.env.NODE_ENV = 'production';+ checkHealth.mockResolvedValue({ connected: false, hasSchema: false, error: 'ECONNREFUSED' });+ const mod = await loadFresh();+ await expect(mod.ensureBackend()).rejects.toThrow(/PostgreSQL is required/);+ expect(mod.getBackendName()).toBeNull();+ });++ it('throws when unset and Postgres is connected but schema is missing (non-test mode)', async () => {+ process.env.NODE_ENV = 'production';+ checkHealth.mockResolvedValue({ connected: true, hasSchema: false });+ const mod = await loadFresh();+ await expect(mod.ensureBackend()).rejects.toThrow(/PostgreSQL is required/);+ });++ it('allows the file fallback in test mode when unset and Postgres is unavailable', async () => {+ process.env.NODE_ENV = 'test';+ checkHealth.mockResolvedValue({ connected: false, hasSchema: false, error: 'no db' });+ const mod = await loadFresh();+ const name = await mod.ensureBackend();+ expect(name).toBe('file');+ });+});