Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

docs: formalize Postgres-required / file-backend test-only policy (#1030)

Adam Eivyca09ce4ac077
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 32ccb52184..10754dba82 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,6 +24,7 @@
- **Songs: play any combination of sheet-music parts together** — the read/perform view's Sheet music card now has a layered MIDI player. When a song carries harmony parts beyond the melody, a checkbox per part (**Layers: Melody, Bass, Mid Harmony I/II, High Harmony I/II…**) lets you pick any combination — melody + bass, the whole stack, two inner harmonies on their own — and a single **Play parts** transport synthesizes them all together, sample-aligned on one audio clock (Web Audio oscillators, no MIDI.js / Tone.js), with the master level backing off as voices stack so the blend doesn't clip. All parts are checked by default, so Play gives the full harmony stack out of the box. A **Tempo** field controls playback for the whole stack, and the pill row still picks which staff is *shown* independently of what plays — the moving playhead lights up on the shown staff whenever it's one of the sounding parts. A single-part song keeps the simple per-staff reference-tone player.
- **Songs: recording "take types" now match the harmony stack you generate** — the voice-layer vocabulary used for vocal takes (the "Next take is for layer" picker, the per-take layer dropdown, the "Add layer from ladder" presets, and the Learning Guide ladder) was the old folk set (Lead melody, Bass / root, Harmony third/fifth, Drone, Counter-melody, Vocal percussion) — out of step with the **Melody, Bass, Mid Harmony I/II, High Harmony I/II** stack the AI derive tool actually writes. The two vocabularies are now unified: a recorded take's layer lines up by id and label with the notated part of the same name, so you can record yourself singing each generated part and stack them. A test guards the two lists against drifting apart again. Existing songs keep their stored layers; "Refresh from template" pulls the new set onto built-in songs.
- **Songs: the built-in "500 Miles" ships the full song, not just verse 1** — the bundled sheet-music melody now spans every verse and the closing coda (46 bars) instead of only the first verse, so the Sheet music view shows the whole song. Existing installs that still hold the earlier single-verse (or the original C-major placeholder) melody can pull it via the song's "Refresh from template" button; the per-section harmony parts can be regenerated to match with "Derive with AI" (it now reads the full melody).
+- **Storage backend policy is now formally documented (#1030)** — the decision that **PostgreSQL is mandatory** and `MEMORY_BACKEND=file` is a **development/test-only escape hatch (never a supported deployment mode)** is now written down where contributors and AI agents will find it: a new "PostgreSQL is required — `MEMORY_BACKEND=file` is test-only" section in [`docs/STORAGE.md`](../docs/STORAGE.md) (explaining *why* — the creative catalog/pgvector, federation, and backup have no file-backed equivalent — and documenting the exact `npm run setup:db` happy path), plus a matching policy line in [`CLAUDE.md`](../CLAUDE.md) so the no-silent-fallback behavior isn't mistakenly "fixed." This is documentation + setup-path hardening only — no runtime behavior change (the backend selector already enforced the policy). The DB setup script (`scripts/setup-db.js`) now reports the **configured** Docker port in its success log instead of a hardcoded `5561` (a `PGPORT_DOCKER` override no longer produces a misleading "ready on port 5561" message), and `.env.example` reframes the `PGMODE` comment to mark file storage as the unsupported escape hatch rather than merely "deprecated."
- **Songs: the practice tools now lead the View tab** — the sheet music, metronome, and vocal recorder are grouped at the top of a song's performance view (just under the meta line and round-stack toggle), instead of the recorder sitting at the very bottom below the lyrics and references. So when you open a song to play it, you read the chart, set the tempo, and record against it without scrolling — the lyrics and reference videos follow underneath.
- **Universe Builder now stores universes in PostgreSQL** — your universes (canon bibles, categories, composite sheets, locks, influences, and the per-universe render-run history) moved out of the per-record `data/universes/{id}/index.json` files into dedicated `universes` and `universe_runs` tables, one row per universe. Existing installs are migrated automatically and losslessly on first boot — the legacy `data/universes/` directory is renamed aside (`data/universes.imported`) as a one-release recovery source. Nothing changes in how you create, edit, delete, render, or sync universes: the Universe Builder UI and the cross-machine federation wire format are unchanged (no schema-version bump — the sync payload is storage-independent, so a machine on this version syncs universes cleanly with a peer still on the old file storage). This is the first implementation slice (#1014) of the Create relational-schema migration designed in #999. Universes still persist to the per-record file store under the `MEMORY_BACKEND=file` dev/test escape hatch.
- **Pipeline series & issues now store in PostgreSQL** — your comic/TV series and their issues (the 8-stage production pipeline state: idea, prose, comic script, teleplay, comic pages, storyboards, episode video, audio) moved out of the per-record `data/pipeline-series/{id}/index.json` and `data/pipeline-issues/{id}/index.json` files into dedicated `pipeline_series` and `pipeline_issues` tables, one row per record. The hot relationships are promoted to indexed columns — `pipeline_issues (series_id, number)` directly serves the issue-renumber pass (the most common cross-record pipeline query), and `pipeline_series (universe_id)` serves the universe delete-guard and "series in this universe" lists. Existing installs are migrated automatically and losslessly on first boot. Each issue's full stage map (including its `lastRunId` transcript pointers) stays in the row's `data` payload, and the "Finish the draft" manuscript-review sibling document stays a file alongside the series — only the series/issue records themselves moved. Nothing changes in how you create, edit, delete, renumber, run, or sync the pipeline: the UI and the cross-machine federation wire format are unchanged (no schema-version bump — the sync payload is storage-independent, so a machine on this version syncs the pipeline cleanly with a peer still on the old file storage). This is the second implementation slice (#1015) of the Create relational-schema migration designed in #999, building on the Universes slice (#1014). The pipeline still persists to the per-record file store under the `MEMORY_BACKEND=file` dev/test escape hatch.
diff --git a/.env.example b/.env.example
index 6173114c1d..90c60018fc 100644
--- a/.env.example
+++ b/.env.example
@@ -1,7 +1,9 @@
# PortOS Environment Variables
# Copy to .env and customize for your deployment.
-# Database mode: "docker" (containerized pg, port 5561), "native" (system pg, port 5432), "file" (deprecated JSON storage)
+# Database mode: "docker" (containerized pg, port 5561) or "native" (system pg, port 5432).
+# PostgreSQL is REQUIRED — run `npm run setup:db` to provision it. ("file" = JSON storage
+# is a development/test-only escape hatch, unsupported for production/federation; see docs/STORAGE.md.)
# PGMODE=docker
# PostgreSQL password (must match docker-compose.yml POSTGRES_PASSWORD in Docker mode)
diff --git a/CLAUDE.md b/CLAUDE.md
index 67437eba08..62f176384d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -39,6 +39,8 @@ pm2 logs
The default database password `portos` (in `ecosystem.config.cjs`, `docker-compose.yml`, and `.env.example`) is an intentional backward-compatible fallback for local development. Do not remove it or flag it as a security concern. Production deployments override it via the `PGPASSWORD` environment variable.
+**Storage backend policy.** PostgreSQL (system `:5432` or Docker `:5561`) is a **mandatory** dependency for every install and every federated peer — provisioned by `npm run setup:db` (see the ADR `docs/decisions/2026-06-07-postgres-as-primary-datastore.md` and `docs/STORAGE.md`). **`MEMORY_BACKEND=file` is a development/test-only escape hatch, NOT a supported deployment mode** (the creative catalog/pgvector, federation, and backup all assume Postgres and have no file-backed equivalent). When `MEMORY_BACKEND` is unset, `server/services/memoryBackend.js` requires a healthy DB and fails fast with no silent fallback — this is **intentional**; do not "fix" the no-fallback behavior, re-add a file menu choice in `scripts/setup-db.js`, or treat the file backend as a fallback for real installs. The file path stays runnable only because `NODE_ENV=test` selects it (it is guarded from bitrot by the suite, not promoted to a deployment option).
+
## Architecture
PortOS is a monorepo with Express.js server (always user-facing on `:5555`, HTTP or HTTPS) and React/Vite client (Vite dev server on `:5554` in `npm run dev`; in `npm start` the built client is served from `:5555` directly). PM2 manages app lifecycles. Data persists to JSON files in `./data/`.
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 0a1908b47c..146a605ab0 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -100,6 +100,43 @@ Defaulting a new Create feature to a fresh `data/*.json` file is the anti-patter
---
+## PostgreSQL is required — `MEMORY_BACKEND=file` is test-only
+
+PortOS treats **PostgreSQL as a mandatory install/runtime dependency** for every install and every federated peer machine (decision: [ADR — PostgreSQL as the Primary Datastore](./decisions/2026-06-07-postgres-as-primary-datastore.md)). Run it as either:
+
+- **System (native) PostgreSQL on `:5432`** — `PGMODE=native`, or
+- **Docker PostgreSQL on `:5561`** — `PGMODE=docker` (the default).
+
+Provision either path with **`npm run setup:db`** (also run automatically by `npm run setup` and `npm start`). It auto-detects an already-healthy local PostgreSQL and uses native mode; otherwise it starts/initializes the Docker container, or — when Docker is unavailable — offers to bootstrap native PostgreSQL. See [Setup path](#setup-path-npm-run-setupdb) below.
+
+### `MEMORY_BACKEND=file` is a development/test-only escape hatch — NOT a deployment mode
+
+The file backend (`server/services/memory.js`, JSON under `./data/`) is **unsupported for production and for federated peers.** It exists only so the test suite (and ad-hoc local development) can boot without a database. It is **not** a fallback, a "lite" mode, or a way to run PortOS without Postgres:
+
+- It is reached **only** via the explicit `MEMORY_BACKEND=file` env var (set from `PGMODE=file` in `.env`, mapped by the launcher) **or** automatically under `NODE_ENV=test`. There is no menu choice for it (`scripts/setup-db.js` offers only Docker and Native), and `npm run setup:db` with `PGMODE=file` prints an "unsupported" notice and refuses to provision it.
+- When `MEMORY_BACKEND` is unset, PortOS **requires** a healthy database and **does NOT silently fall back to file storage** — an unreachable/unmigrated DB is an error condition. `server/services/memoryBackend.js` fails fast with an actionable message (`run npm run setup:db`) rather than serving a half-broken install. This no-silent-fallback behavior is intentional; do not "fix" it.
+
+**Why file storage cannot be a supported mode:**
+
+- **No creative-catalog / vector equivalent.** The catalog graph, memory similarity, and hybrid search depend on PostgreSQL + pgvector (HNSW vector search fused with `tsvector` full-text). There is no file-backed implementation of these — a file-backed install would serve a half-broken app the moment a user touched the catalog, memory search, or any `db-primary` Create domain. As each Create domain migrates to Postgres (universes #1014, pipeline #1015, Story Builder #1016, Writers Room #1017, catalog refs #1018), its file path survives **only** under this dev/test escape hatch.
+- **Federation assumes Postgres.** Cross-machine sync (snapshot/push + last-writer-wins) and the `db-primary` sequence cursors/tombstones are designed around the database. A file-backed peer is not a supported member of a federation.
+- **Backup assumes Postgres.** The backup/restore contract treats the `pg_dump` logical dump as **required system state** (see [Backup & Restore](./BACKUP.md)) — a file-backed install has no dump to capture or verify.
+
+The escape hatch is **guarded from bitrot by the test suite** (tests boot with `NODE_ENV=test` and exercise the file backend), so the path stays runnable — but "the tests use it" is **not** an argument that it is a deployment option. It isn't.
+
+### Setup path (`npm run setup:db`)
+
+`npm run setup:db` → `scripts/setup-db.js` is the single command that makes PostgreSQL ready, and is wired into `npm run setup` and `npm start` so a normal install never has to think about it. Its happy path:
+
+1. **Already healthy?** If the configured role can authenticate to the configured database **and** the `memories` table from `server/scripts/init-db.sql` exists, it reports ready and exits (fast path — no re-provisioning on every `npm start`).
+2. **`PGMODE=docker` (default):** starts the `pgvector/pgvector:pg17` container (`docker-compose.yml`), waits for it to accept connections **and** finish applying the init schema, then reports ready on `:5561`. If Docker is missing or not running, it prints platform-specific install/start hints and — if a healthy native PostgreSQL is already present — switches to native automatically.
+3. **`PGMODE=native`:** runs `scripts/db.sh setup-native` (idempotent: brew install, role, db, extensions, schema) and verifies at the domain level (role can auth + schema present) before reporting ready on `:5432`.
+4. **Failure is non-zero exit.** A started-but-unresponsive container, a failed native bootstrap, or a non-interactive context with no usable DB exits non-zero with an actionable message — so the `&&`-chained `npm start` halts here instead of crash-looping under PM2 against an unready database.
+
+`PGPASSWORD`/`PGUSER`/`PGDATABASE`/`PGPORT` are resolved from `process.env` first, then `.env`, then the backward-compatible defaults (`portos`/`portos`/`portos`/`5432`). The default `portos` password is an **intentional** local-development fallback (see the Distribution model note in [`CLAUDE.md`](../CLAUDE.md)); production deployments override it via `PGPASSWORD`.
+
+---
+
## 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.
diff --git a/scripts/setup-db.js b/scripts/setup-db.js
index 6c660264c6..ea71ea2709 100644
--- a/scripts/setup-db.js
+++ b/scripts/setup-db.js
@@ -35,6 +35,15 @@ const PG_USER = envVar('PGUSER', 'portos');
const PG_DATABASE = envVar('PGDATABASE', 'portos');
const PG_PASSWORD = envVar('PGPASSWORD', 'portos');
const PG_PORT_NATIVE = parsePgPort(envVar('PGPORT', 5432));
+// Docker host-port mapping (docker-compose.yml maps `${PGPORT_DOCKER:-5561}:5432`).
+// Resolve it the same tolerant way so the "ready on port N" log can't lie when a
+// user overrides PGPORT_DOCKER — a misleading success port is exactly the kind of
+// "looks fine but points at the wrong place" footgun this script exists to avoid.
+const parseDockerPort = (value) => {
+ const parsed = Number.parseInt(String(value).trim(), 10);
+ return Number.isFinite(parsed) ? parsed : 5561;
+};
+const PG_PORT_DOCKER = parseDockerPort(envVar('PGPORT_DOCKER', 5561));
// Environment to pass to `db.sh` and other psql-wrapping subprocesses, so
// values configured in .env (but not exported into the shell) reach the
@@ -388,7 +397,7 @@ try {
// Wait for health
console.log('⏳ Waiting for PostgreSQL to be ready...');
if (waitForHealth()) {
- console.log('✅ PostgreSQL ready on port 5561');
+ console.log(`✅ PostgreSQL ready on port ${PG_PORT_DOCKER}`);
} else {
// PG is mandatory and boot fail-fasts — a started-but-unresponsive container
// must fail setup, not warn-and-continue, so the &&-chained `npm start` halts
diff --git a/scripts/setup-db.test.js b/scripts/setup-db.test.js
index 08f5e17495..a9da4aa829 100644
--- a/scripts/setup-db.test.js
+++ b/scripts/setup-db.test.js
@@ -16,6 +16,14 @@ function resolveMenuChoice(answer) {
return 'exit'; // 1 or default = they want docker, so exit to install it
}
+// Keep in sync with parseDockerPort() in setup-db.js. The "ready on port N" log
+// must reflect the configured PGPORT_DOCKER, not a hardcoded 5561, and tolerate
+// whitespace / junk by falling back to the canonical docker port.
+function parseDockerPort(value) {
+ const parsed = Number.parseInt(String(value).trim(), 10);
+ return Number.isFinite(parsed) ? parsed : 5561;
+}
+
describe('setup-db menu choice resolver (Phase 1: Postgres mandatory)', () => {
it('maps "2" to native', () => {
expect(resolveMenuChoice('2')).toBe('native');
@@ -47,3 +55,24 @@ describe('setup-db menu choice resolver (Phase 1: Postgres mandatory)', () => {
expect(src).not.toMatch(/resolve\('file'\)/);
});
});
+
+describe('setup-db docker-port resolver (success log accuracy)', () => {
+ it('defaults to 5561 when unset / non-numeric', () => {
+ expect(parseDockerPort(undefined)).toBe(5561);
+ expect(parseDockerPort('')).toBe(5561);
+ expect(parseDockerPort('not-a-port')).toBe(5561);
+ });
+
+ it('honors a configured PGPORT_DOCKER, tolerating whitespace', () => {
+ expect(parseDockerPort('5599')).toBe(5599);
+ expect(parseDockerPort(' 6000 ')).toBe(6000);
+ });
+
+ it('real setup-db.js no longer hardcodes 5561 in the docker success log', () => {
+ const here = dirname(fileURLToPath(import.meta.url));
+ const src = readFileSync(join(here, 'setup-db.js'), 'utf8');
+ // The success log must interpolate the resolved port, not a literal.
+ expect(src).toContain('PostgreSQL ready on port ${PG_PORT_DOCKER}');
+ expect(src).not.toContain("'✅ PostgreSQL ready on port 5561'");
+ });
+});