Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

docs(db): describe the final Postgres, plugin data and deployment behaviour

Mauricecdc31967b2db
diff --git a/charts/trek/values.yaml b/charts/trek/values.yaml
index 8e20fb6d4..cb95d2833 100644
--- a/charts/trek/values.yaml
+++ b/charts/trek/values.yaml
@@ -188,8 +188,8 @@ env:
# under existingSecretKey and the chart writes nothing. existingSecret wins over url. The
# variable is required when either is set: a missing Secret key stops the pod instead of
# starting it on SQLite. The role in the URL owns TREK's database and must not be a superuser
-# (nor hold pg_execute_server_program or pg_write_server_files): a restore runs the backup's
-# SQL as that role and refuses one that could reach the database host. The wiki page shows the
+# (nor a member of one, nor hold a right that reaches the server's files or programs): a
+# restore runs the backup's SQL as that role and refuses one that could reach the database host. The wiki page shows the
# SQL that creates such a role. PostgreSQL 14 to 18 is supported.
# url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
database:
diff --git a/plugin-sdk/CLAUDE.md b/plugin-sdk/CLAUDE.md
index 6b23fae48..ef0a8abb3 100644
--- a/plugin-sdk/CLAUDE.md
+++ b/plugin-sdk/CLAUDE.md
@@ -32,6 +32,7 @@ Because the package ships standalone it cannot import server code, so several fi
|---|---|---|
| `src/generated/host-facts.ts` (permissions, RPC methods, hooks, event catalog, `KNOWN_ADDONS`, the output contract `PLUGIN_ENTITY_FIELDS` / `PLUGIN_ENTITY_NESTED` / `PLUGIN_METHOD_RESULT`) | `server/src/nest/plugins/protocol/envelope.ts`, `protocol/output-contract.ts` and `server/src/addons.ts` via `server/scripts/gen-plugin-facts.ts` (**machine-written, never hand-edit**) | server `check:plugin-facts` CI gate; the entity interfaces in `src/index.ts` are type-checked against `PLUGIN_ENTITY_FIELDS` |
| `src/egress-policy.ts` (pure helpers, kept **byte-identical**) | `server/src/nest/plugins/runtime/egress-policy.ts` | `test/permissions-parity.test.ts` |
+| `src/plugin-data-contract.ts` (the `ctx.db` contract `dev` and the mock host apply: the caps, the refusal texts, the NUL refusal and the transaction-control refusal, the whole file **byte-identical**) | `server/src/db/engine/plugin-data-contract.ts` | `test/permissions-parity.test.ts` |
| `src/manifest.ts` (validation rules incl. the `trek` version range; its patterns, sets, caps and `PLUGIN_API_VERSION` come from `generated/host-facts.ts`, written from `server/src/nest/plugins/protocol/manifest-rules.ts`) | `server/src/nest/plugins/install/manifest.ts` | the verdicts: `test/fixtures/manifest-corpus.ts`, run here by `test/manifest-corpus.test.ts` and through both validators by `server/tests/unit/plugins/manifest-parity.test.ts` (the SDK may only be stricter, case by case) |
| `src/index.ts` (the plugin API types) | `server/src/nest/plugins/runtime/plugin-sdk.ts` (the child's copy) | `test/host-types.test-d.ts` (vitest typecheck mode, on inside the monorepo): plain shapes equal, ctx-carrying shapes and every ctx namespace with the same members; `test/host-types-names.test.ts` makes it list every shared name |
| `src/cli/checks/*` (registry gates) | TREK-Plugins registry repo (`scripts/validate-entry.mjs`, `check-readme.mjs`) | `test/checks-parity.test.ts` (runs the registry's real script; `TREK_PLUGINS_REPO` points at a checkout) |
diff --git a/plugin-sdk/README.md b/plugin-sdk/README.md
index e7c7ce130..a085f37c7 100644
--- a/plugin-sdk/README.md
+++ b/plugin-sdk/README.md
@@ -217,8 +217,12 @@ What changes on Postgres:
`varchar(20)`, `int8`, ...), JSON and JSONB (`jsonb_build_object`, `jsonb_set`,
`jsonb_path_query`, ...), arrays (`unnest`, `array_agg`, `generate_series`, ...),
aggregates and window functions (`count`, `sum`, `string_agg`, `row_number`, `lag`, ...),
- UUIDs (`gen_random_uuid`), ranges, geometry, network addresses and full text search
- (`to_tsvector`, `ts_rank`, ...). Any other function of Postgres's catalog is refused
+ UUIDs (`gen_random_uuid`), ranges, geometry, network addresses, and full text search over
+ vectors you build yourself (`array_to_tsvector`, `'a & b'::tsquery`, `ts_rank`, `@@`). The
+ text search functions that take a configuration (`to_tsvector`, `to_tsquery`,
+ `plainto_tsquery`, `websearch_to_tsquery`, `ts_headline`, ...) are refused: Postgres looks
+ the configuration up by its name, which would tell you what else the database holds. Any
+ other function of Postgres's catalog is refused
however you spell the call (`f(...)`, `"f"(...)`, the column notation `(x).f`, `t.f`,
`$1.f`): the ones that read the catalogs or the server rather than their arguments
(`obj_description`, `col_description`, `format_type`, `version`, `current_database`,
@@ -232,8 +236,33 @@ What changes on Postgres:
call (`INSERT INTO version (...)`, `CREATE TABLE version (...)`, `REFERENCES version (id)`);
as the table of `CREATE INDEX ... ON` it cannot, so name it differently. Postgres reads
`t.f` as the call `f(t)` when `t` has no column `f`, so a column named like a refused
- function cannot follow a table's name and a dot either (`name`, `version`, `money`, `oid`,
- `xid` and `xml` can); write it without the table's name, or name it differently.
+ function cannot follow a table's name and a dot either (`name`, `version`, `money`, `oid`
+ and `xml` can); write it without the table's name, or name it differently.
+- **No system columns.** Reading `xmin`, `xmax`, `cmin`, `cmax`, `ctid` or `tableoid` is
+ refused, quoted or not, after a table's name or alone: they show the server's transaction
+ ids or where a row is stored, and SQLite has none of them. For optimistic locking keep a
+ version or `updated_at` column of your own. A value of yours may still carry such a name
+ where you give it, after `AS` or in a `WITH` query's or an alias's column list
+ (`SELECT min(lng) AS xmin, max(lng) AS xmax FROM places`), and you read it from the
+ result; the SQL itself cannot refer to it by that name (`ORDER BY xmin` is refused).
+- **No transaction ids.** The types `xid` and `xid8` (and their arrays) are refused where the
+ word stands for the type: `'3'::xid`, `CAST(x AS xid)`, `xid '3'`, `xid(x)`, a column
+ declared `xid`, and `x.xid`, which Postgres reads as the cast `xid(x)` when `x` has no
+ column `xid`. `age()` of one is how many transactions the server ran. A column of yours
+ may be called `xid` (`CREATE TABLE payments (id bigserial PRIMARY KEY, xid text)`, `SELECT
+ xid FROM payments WHERE xid = $1`); name it without its table, and rename it where you
+ need `t.xid` or `excluded.xid` in an upsert.
+- **Collations and access methods every server has.** After `COLLATE` only `"C"`,
+ `"POSIX"`, `"default"` and `ucs_basic` are accepted, and after `USING` (or `SET ACCESS
+ METHOD`) only `btree`, `hash`, `gist`, `gin`, `spgist`, `brin` and, for a table, `heap`:
+ which others exist depends on the server's locales, ICU and extensions. Text sorts by the
+ database's collation; `ORDER BY name COLLATE "C"` sorts by code point, as SQLite does.
+- **Values print the same on every server.** Each call runs with the time zone UTC and with
+ Postgres's built-in defaults for the date style, the interval style, the money, number and
+ month name formats (`lc_monetary`, `lc_numeric`, `lc_time` are `C`), float, bytea and xml
+ output and the text search configuration (`simple`), whatever the server is set to:
+ `now()::text` ends in `+00`, `date_trunc('day', now())` cuts at UTC midnight, and
+ `12.5::money` prints `$12.50`.
- **You change your own objects only.** Right before an `ALTER`, `DROP`, `REFRESH`,
`TRUNCATE` or `CREATE INDEX ... ON` runs, Postgres resolves the object it names (and the
tables a `CREATE`/`ALTER TABLE` ties to with `REFERENCES`, `INHERITS`, `PARTITION OF`,
@@ -260,13 +289,17 @@ What changes on Postgres:
- **One statement at a time.** Each statement goes to Postgres on its own, over the protocol
that runs exactly one: `query` and each `tx` entry take one statement, and an `exec`
script is split at its semicolons and sent statement by statement.
-- **No NUL in text.** Postgres text cannot hold the character U+0000. A bound argument
- holding one (a string, or a string in an array) and a `migrate` id holding one are refused
- with an error that names it, and so is SQL text with one anywhere, a string literal
- included; TREK never drops or changes the character, since `'a\0b'` and `'ab'` are
- different keys. Bind binary data as a `Buffer` into a `bytea` column, and use another
- separator for composite keys. On SQLite your arguments are bound exactly as you send
- them, NUL included, as they always were.
+- **No NUL in text, on either engine.** Postgres text cannot hold the character U+0000, so
+ TREK refuses it on SQLite as well, and `trek-plugin dev` and the mock host refuse it the
+ same way. A bound argument holding one (a string, or a string in an array or an object)
+ and a `migrate` id holding one are refused with an error that names it, and so is SQL text
+ with one anywhere, a string literal included; TREK never drops or changes the character,
+ since `'a\0b'` and `'ab'` are different keys. Bind binary data as a `Buffer` (a `BLOB` on
+ SQLite, `bytea` on Postgres), and use another separator for composite keys. TREK does not
+ see a NUL your SQL builds itself: on SQLite `char(0)` or a BLOB cast to text still stores
+ one, while Postgres refuses `chr(0)`, and moving such an install to Postgres refuses the
+ row. Keep binary data in a `BLOB`. Rows an older TREK stored in your SQLite file with a
+ NUL are still read as they are.
- **Limits**: the same row cap and quota as on SQLite. The 2 s budget is a
`statement_timeout` here, so it also stops a single long statement, and an `exec` with
bound args is held to it too; `migrate` stays untimed. The quota counts every relation of
@@ -360,7 +393,7 @@ for a legitimate plugin and only bite a runaway or abusive one — build against
| `ctx.ai` | 200 calls/day per plugin (UTC midnight rollover); past it throws `"daily AI budget exhausted (resets at UTC midnight)"` |
| `ctx.notify` | 100 calls/day per plugin (UTC midnight rollover); past it throws `"daily notification budget exhausted (resets at UTC midnight)"` |
| RPC (every `ctx.*` call) | burst 60, sustained 20/s, 16 in-flight per plugin; a throttled call is refused with `HOST_ERROR: rate limit exceeded — slow down ctx.* calls` |
-| `ctx.db` (your own database) | 256 MB per plugin; a `query` or `tx` returns at most 100,000 rows (a whole `tx` batch shares one count). A `query`, a whole `tx` batch and an `exec` script without bound args each have 2 s of wall-clock time, checked between the rows a statement reads and between the statements of a batch or script; past either limit the call throws (`query exceeded its 2000 ms time budget`), a `tx` rolls back, and an `exec` script stops before its next statement once the time is up (the statements that ran stay applied, as they always did, and a transaction the script opened itself is rolled back; a script whose last statement has run counts as done, however long it took). Split a longer script over several calls, or batch it with `tx`. `migrate` has no time budget, since a migration stopped part of the way would fail again on every start. `ATTACH`, `DETACH`, `VACUUM`, `PRAGMA`, `WITH RECURSIVE` and `load_extension` are refused. The budget cannot stop a single statement, because SQLite runs it on TREK's main thread in one step: a write runs to its end (an `INSERT ... SELECT` over a cross join of large tables), and a read runs until its first row (an aggregate over one). Keep your statements indexed and bounded. On a TREK running on Postgres the same caps hold, and the budget also stops a single statement (see [Your own database on Postgres](#your-own-database-on-postgres)) |
+| `ctx.db` (your own database) | 256 MB per plugin; a `query` or `tx` returns at most 100,000 rows (a whole `tx` batch shares one count). A `query`, a whole `tx` batch and an `exec` script without bound args each have 2 s of wall-clock time, checked between the rows a statement reads and between the statements of a batch or script; past either limit the call throws (`query exceeded its 2000 ms time budget`), a `tx` rolls back, and an `exec` script stops before its next statement once the time is up (the statements that ran stay applied, as they always did; a script whose last statement has run counts as done, however long it took). Split a longer script over several calls, or batch it with `tx`. `migrate` has no time budget, since a migration stopped part of the way would fail again on every start. `ATTACH`, `DETACH`, `VACUUM`, `PRAGMA`, `WITH RECURSIVE` and `load_extension` are refused. Transaction control (`BEGIN`, `START`, `COMMIT`, `END`, `ROLLBACK`, `ABORT`, `SAVEPOINT`, `RELEASE`) is refused in every statement of every call, on both engines and in `dev`, with the error `PLUGIN_DATA_ERRORS.txControl`: each call runs in a transaction of its own, and `tx` makes a batch atomic. A named parameter written directly before a parenthesis (`$a(1)`) is refused too (`PLUGIN_DATA_ERRORS.parameterBeforeParenthesis`): the SQLite under `dev` reads it as one token up to the closing parenthesis, and TREK's engines refuse it anyway. The budget cannot stop a single statement, because SQLite runs it on TREK's main thread in one step: a write runs to its end (an `INSERT ... SELECT` over a cross join of large tables), and a read runs until its first row (an aggregate over one). Keep your statements indexed and bounded. On a TREK running on Postgres the same caps hold, and the budget also stops a single statement (see [Your own database on Postgres](#your-own-database-on-postgres)) |
| `ctx.meta` | 64 KB per value, 256 chars per key, 100 keys per (plugin, entity) |
| Plugin process | 300 MB RSS ceiling; auto-disabled after 5 crashes in 5 minutes |
| Event redelivery buffer | 200 events held per plugin, dropped unreplayed after 15 minutes |
diff --git a/scripts/ci/doc-paths-baseline.json b/scripts/ci/doc-paths-baseline.json
index 98ba3324b..69458ea17 100644
--- a/scripts/ci/doc-paths-baseline.json
+++ b/scripts/ci/doc-paths-baseline.json
@@ -3,7 +3,6 @@
"plugin-sdk/CLAUDE.md :: protocol/output-contract.ts",
"plugin-sdk/CLAUDE.md :: scripts/validate-entry.mjs",
"server/CLAUDE.md :: db/migrations.ts",
- "server/CLAUDE.md :: host/plugin-data.service.ts",
"server/CLAUDE.md :: host/rpc-host.ts",
"server/CLAUDE.md :: pg-probe/arg-samples.ts",
"server/CLAUDE.md :: pg-probe/recorder.ts",
diff --git a/server/.env.example b/server/.env.example
index be19be9c2..1264bf13f 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -53,7 +53,7 @@ DEMO_MODE=false # Demo mode: resets data hourly
# BACKUP_UPLOAD_LIMIT_MB=500 # Max size (MB) of a backup archive you can upload when restoring. Raise it if your backup exceeds 500 MB. If you sit behind a reverse proxy, raise its upload limit too (e.g. nginx client_max_body_size).
# TREK_DB_URL=postgres://trek:password@db:5432/trek # Run on a Postgres database instead of the SQLite file in data/. TREK creates its schema in an empty database and refuses one holding tables it did not create. sslmode=disable, require, verify-ca or verify-full (the last three always verify the certificate; sslrootcert= names the CA file). Cannot be combined with TREK_DB_FILE, TREK_DB_JOURNAL_MODE or TREK_DB_SYNCHRONOUS.
-# TREK_DB_PG_BIN_DIR=/usr/lib/postgresql/17/bin # The directory holding pg_dump, pg_restore and psql, which back up and restore a Postgres database. Unset, TREK looks in /usr/lib/postgresql/<17..14>/bin, /usr/local/bin and /usr/bin (the Docker image installs the version 17 tools, which cannot dump a newer server). Unused on SQLite.
+# TREK_DB_PG_BIN_DIR=/usr/lib/postgresql/18/bin # The directory holding pg_dump, pg_restore and psql, which back up and restore a Postgres database. Unset, TREK looks in /usr/lib/postgresql/<18..14>/bin, newest first, then /usr/local/bin and /usr/bin (the Docker image installs the version 18 tools, which work with every supported server; tools older than the server are refused). Unused on SQLite.
# TREK_DB_POOL_MAX=10 # Most connections TREK opens to the Postgres database (1 to 100). Unused on SQLite. (default: 10)
# TREK_DB_JOURNAL_MODE=WAL # SQLite journal mode (DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF). WAL is fastest and the right choice on local disk. Set DELETE if the data directory lives on network storage (Azure App Service, an SMB/NFS volume on a NAS) — WAL coordinates writers through a shared-memory file that those filesystems do not implement reliably. The mode is stored inside the database file, so it survives a restart; changing this applies on the next boot.
# TREK_DB_PRE_MIGRATE_SNAPSHOT=true # Copy the database to data/pre-migrate-<schema>-<time>.db (a .pgdump made with pg_dump on Postgres) before a startup migrates it, so the previous image can run on the copy again. A copy that cannot be written stops the startup; false migrates without one.
diff --git a/server/CLAUDE.md b/server/CLAUDE.md
index 72b483652..51167e56f 100644
--- a/server/CLAUDE.md
+++ b/server/CLAUDE.md
@@ -79,10 +79,10 @@ Nest owns everything. Every domain is a DI module under `src/nest/<domain>/` (`c
- **Realtime**: `/ws` is a Nest gateway in `src/nest/realtime/`. Inject `RealtimeService`; tests hand in a `FakeRealtimeService` (`tests/helpers/fake-realtime.ts`) or spy on the container's instance instead of mocking the transport module. Trip mutations forward `X-Socket-Id` so the originating client doesn't echo its own change.
- **MCP**: `src/nest-mcp/` is the decorator/registry layer (`@McpController`/`@Tool`/`@Resource`/`@Prompt`; see its `README.md`); tools live in `<domain>.mcp.ts` files beside each module; the HTTP transport is `src/nest/mcp-transport/`; `src/mcp/` holds process-wide state only (scopes, session manager, boot policy). Every tool invocation writes an audit row through the registry's `onInvoke` seam. The demo-mode write block is the registry's `toolGate` (`trekDemoToolGate`): every tool not annotated read-only refuses a demo account there (except the write tools in `DEMO_UNGATED_WRITE_TOOLS`, which never had a demo check), so a tool never checks demo mode itself (ESLint refuses it in `*.mcp.ts`). MCP tools are adapters over the same services and permission checks as REST — a change on one side lands on the other in the same change.
- **Scheduling**: `src/nest/scheduling/` (`CronRegistrarService`) is the one way to schedule a cron. Jobs are `*.job.ts` providers in their owning domain. The registrar refuses to schedule under `NODE_ENV=test` (an integration test pins it). **Never use a `@Cron` decorator**: it bypasses that gate. Every tick first takes the job's row in `scheduler_leases` (`SchedulerLeasesRepository.acquire`, one conditional upsert that decides the race), renews it while it runs and keeps it for a short settle window afterwards, so two processes on one database never run the same tick; a job needs nothing of its own for this. Claims on individual rows (the reminder jobs' `claimReminder`) stay where they are: the lease decides who runs a tick, the claim what a tick may send.
-- **Plugins** (`src/nest/plugins/`): the child-process runtime (`supervisor/`, `runtime/plugin-host-entry.ts`, `protocol/envelope.ts`) is **intentionally not Nest**; it is the security boundary. `host/rpc-host.ts` registers an RPC method at spawn only if the plugin holds the unlocking permission (registration = authorization). Install-time gates live in `install/`; the manifest's `trek` version range fails closed, and `TREK_PLUGINS_IGNORE_TREK_RANGE` downgrades that to a warning. The protocol tables in `protocol/envelope.ts` (+ `src/plugin-event-sink.ts`) are **generated** into `plugin-sdk/` and `shared/`: run `gen:plugin-facts` after touching them and commit the output. What a plugin gets back is `protocol/output-contract.ts`: every wire method has an entry, and an entity result (`trips.getById`, `todos.list`, `vacay.mine`, ...) is cut down to its published fields in `rpc-host.ts` on the way out, together with every child row it carries whose field is listed in `PLUGIN_ENTITY_NESTED` (a day's `notes_items`, a reservation's `endpoints`). A new column on any whole-row table behind those entities, child tables included, fails `tests/unit/plugins/output-contract.schema.test.ts` until it is listed as published or withheld (the SDK's `PLUGIN_ENTITY_FIELDS` and `PLUGIN_ENTITY_NESTED` are generated from it); a method left as `readModel` must return a value built field by field from named columns. A plugin's own SQL (`host/plugin-data.service.ts`) is held to a row cap, and `query`, `tx` and an `exec` script to a time budget checked between rows and statements (`migrate` is deliberately not timed). Where that data lives is the engine's: `PLUGIN_DATA` (`src/nest/plugins/host/plugin-data.backend.ts`) binds the SQLite file per plugin, or on Postgres a schema per plugin (`trek_plugin_<id>`, `src/db/engine/postgres/plugin-data-store.ts`) whose SQL is kept inside that schema in layers that `src/db/engine/postgres/plugin-sql-guard.ts`'s header names, the ones after the guard enforced by the database: no plugin SQL at all while TREK's role is privileged in the sense of `PRIVILEGED_ROLE_SQL` (`src/db/engine/postgres/plugin-data-checks.ts`, read once per pool connection, and the boot log says why); the guard, which refuses what it would read differently from the Postgres lexer, other schemas, the catalogs, temporary objects, `SELECT ... INTO`, the `reg*` types, the functions that look an object up by name, and every function of `pg_catalog` outside the allowlist `assets/postgres/plugin-functions.txt`, read by `src/db/engine/postgres/plugin-sql-functions.ts` (its catalog list, `assets/postgres/catalog-functions.txt`, is held to `pg_proc` by PGPLUG-021); the objects an ALTER, DROP, REFRESH, TRUNCATE or CREATE INDEX changes, resolved by Postgres (`to_regclass`/`to_regtype`) right before the statement and refused outside the plugin's schema, so an unqualified `int4` is `pg_catalog`'s and refused even on a superuser connection; one statement per round trip over the extended query protocol, which the store sends on a pool client it checks out for each call and runs its transaction on directly; `pg_temp` last on the plugin's and on every pool connection's `search_path`, `session-search-path.ts`, with the store dropping its client's temporary tables and other session state before the client goes back to the pool; and a quota over every relation of the schema with its TOAST table plus a cap on its catalog objects (`PLUGIN_SCHEMA_MAX_OBJECTS`). A plugin argument holding NUL is refused there, since Postgres text cannot hold it, while the plugin's SQLite file binds it exactly; the plugin's SQL is never translated, and `db.engine` tells the plugin which dialect to write. Backups and restores carry the plugin schemas the role owns (`pg-tools.ts`). `runtime/egress-policy.ts` is a hand-kept mirror guarded by a parity test in `plugin-sdk/`; change both sides together.
+- **Plugins** (`src/nest/plugins/`): the child-process runtime (`supervisor/`, `runtime/plugin-host-entry.ts`, `protocol/envelope.ts`) is **intentionally not Nest**; it is the security boundary. `host/rpc-host.ts` registers an RPC method at spawn only if the plugin holds the unlocking permission (registration = authorization). Install-time gates live in `install/`; the manifest's `trek` version range fails closed, and `TREK_PLUGINS_IGNORE_TREK_RANGE` downgrades that to a warning. The protocol tables in `protocol/envelope.ts` (+ `src/plugin-event-sink.ts`) are **generated** into `plugin-sdk/` and `shared/`: run `gen:plugin-facts` after touching them and commit the output. What a plugin gets back is `protocol/output-contract.ts`: every wire method has an entry, and an entity result (`trips.getById`, `todos.list`, `vacay.mine`, ...) is cut down to its published fields in `rpc-host.ts` on the way out, together with every child row it carries whose field is listed in `PLUGIN_ENTITY_NESTED` (a day's `notes_items`, a reservation's `endpoints`). A new column on any whole-row table behind those entities, child tables included, fails `tests/unit/plugins/output-contract.schema.test.ts` until it is listed as published or withheld (the SDK's `PLUGIN_ENTITY_FIELDS` and `PLUGIN_ENTITY_NESTED` are generated from it); a method left as `readModel` must return a value built field by field from named columns. A plugin's own SQL runs in one store per engine behind the `PluginDataStore` port (`src/db/engine/plugin-data.ts`), each in its engine's folder: `SqlitePluginDataStore` (`src/db/engine/sqlite/plugin-data-store.ts`) and `PostgresPluginDataStore` (`src/db/engine/postgres/plugin-data-store.ts`). Both hold it to a row cap, and `query`, `tx` and an `exec` script to a time budget checked between rows and statements (`migrate` is deliberately not timed), and refuse a call that breaks the contract with the same words, taken from `PLUGIN_DATA_ERRORS` beside the caps in `src/db/engine/plugin-data-contract.ts` (`tests/unit/db/engine/plugin-data-contract.test.ts` runs every such call on both stores and fails on one answered differently; a closed store refuses every call). Transaction control is refused in every statement of every call on both engines with one text, `PLUGIN_DATA_ERRORS.txControl` (`refuseTransactionControl` on SQLite and in the SDK, the guard on Postgres). The SDK's dev harness and mock host throw the same texts and hold the same caps from a byte-identical copy of that file, held by a parity test in `plugin-sdk/`. Where that data lives is the engine's: `PLUGIN_DATA` (`src/nest/plugins/host/plugin-data.backend.ts`) binds the SQLite file per plugin, or on Postgres a schema per plugin (`trek_plugin_<id>`) whose SQL is kept inside that schema in layers that `src/db/engine/postgres/plugin-sql-guard.ts`'s header names, the ones after the guard enforced by the database: no plugin SQL at all while TREK's role is privileged in the sense of `PRIVILEGED_ROLE_SQL` (`src/db/engine/postgres/plugin-data-checks.ts`, read once per pool connection, and the boot log says why); the guard, which refuses what it would read differently from the Postgres lexer, other schemas, the catalogs, temporary objects, `SELECT ... INTO`, the `reg*` types, the functions that look an object up by name, a read of a system column (`xmin`, `ctid`, ...; the name may still be given with AS), the `xid` types where the word stands for the type, a collation or access method beyond the ones every server has, and every function of `pg_catalog` outside the allowlist `assets/postgres/plugin-functions.txt`, read by `src/db/engine/postgres/plugin-sql-functions.ts` (its catalog list, `assets/postgres/catalog-functions.txt`, is held to `pg_proc` by PGPLUG-021, and PGPLUG-022 fails on an allowed function with an overload that takes or returns a `reg*` type or `aclitem`, which would turn a text argument into a catalog lookup, and on one that makes a transaction id out of other values); the settings that decide how values print and parse (time zone UTC, the locales `C`, the date style, ...), pinned with `SET LOCAL` in every plugin transaction (`src/db/engine/postgres/plugin-session.ts`; PGPLUG-023 fails on a client setting of those categories a new Postgres adds until it is pinned or named as harmless); the objects an ALTER, DROP, REFRESH, TRUNCATE or CREATE INDEX changes, resolved by Postgres (`to_regclass`/`to_regtype`) right before the statement and refused outside the plugin's schema, so an unqualified `int4` is `pg_catalog`'s and refused even on a superuser connection; one statement per round trip over the extended query protocol, which the store sends on a pool client it checks out for each call and runs its transaction on directly; `pg_temp` last on the plugin's and on every pool connection's `search_path`, `session-search-path.ts`, with the store dropping its client's temporary tables and other session state before the client goes back to the pool; and a quota over every relation of the schema with its TOAST table plus a cap on its catalog objects (`PLUGIN_SCHEMA_MAX_OBJECTS`). Plugin SQL, an argument or a migration id holding NUL is refused on both engines with one error (`refuseNulSql`/`refuseNulValues` in the same contract file, so the SDK refuses it too), since Postgres text cannot hold it and a plugin must answer the same on either; a NUL the plugin's SQLite SQL builds itself (`char(0)`) is not caught, and the move to Postgres refuses such a row; the plugin's SQL is never translated, and `db.engine` tells the plugin which dialect to write. Backups and restores carry the plugin schemas the role owns (`pg-tools.ts`). `runtime/egress-policy.ts` is a hand-kept mirror guarded by a parity test in `plugin-sdk/`; change both sides together.
- **Storage**: `src/nest/storage/` is the upload driver abstraction (local / S3 / mirror behind one interface, with an admin surface and a usage job). Domain services never touch the filesystem or the S3 SDK directly. Where the data lives (`data/`, `uploads/`, backups, logs, key files, the DB file) is resolved in one place, `src/app-config/data-paths.ts`; a provider that reads one injects `DataPathsService`, plain helper modules shared with code outside the container call `resolveDataPaths()` (the list is in `src/app-config/README.md`), and nothing anchors a data path on its own `__dirname` or on `process.cwd()`.
- **DB** (`src/db/`): `better-sqlite3`, WAL, FK on. `database.ts` only holds the connection and applies pragmas. It does not build a schema, and importing it opens nothing (the first reader does). The connection's lifecycle belongs to the `DatabaseLifecycle` provider (`nest/database/database-lifecycle.service.ts`): `buildApp()` opens it through `open()` (which binds the ORM to later swaps and runs the schema bootstrap below), the shutdown closes it through `close()`, and a restore or the demo reset swaps the file only through the database backup port, `DATABASE_BACKUP` (`nest/database/database-backup.interface.ts`; the SQLite implementation is `nest/backup/sqlite-database-backup.ts`: `VACUUM INTO` snapshot, close, atomic file swap, `reopen()`). The port works on `DatabaseLifecycle.file`, the one resolved path (`TREK_DB_FILE` or `data/travel.db`), and a snapshot that fails fails the backup rather than archiving the live file. `MaintenanceRepository` is provided only by `MaintenanceModule`'s factory and injected everywhere else; no consumer constructs it. A provider that has to follow every reopen (the demo reset job saves the first demo baseline after a restore's re-bootstrap seeded the example trips) registers with `DatabaseLifecycle.onReopened()`, which runs after the reopen's schema bootstrap; a listener contains its own failures, since one that throws fails the reopen. MikroORM's migrations (`db/migrations/`) are the only schema source, **including for tests**: the hand-kept `schema.ts`/`migrations.ts`/`seeds.ts` builders and the parity test that guarded them are gone. Seeding is the MikroORM seeders in `db/seeders/`, applied by `db/orm.ts` from `buildApp()` before anything reads. An install the retired positional runner migrated (a `schema_version` row, no `mikro_orm_migrations` rows) is baselined by `db/legacy-baseline.ts`: the migrations whose `Legacy migration step N` docstring is ≤ its version are recorded as executed (never replayed) in the same transaction as the migrator run, while the baseline migration itself still runs first, as the legacy runner's `createTables()` did on every boot. It refuses the boot when `schema_version` is not exactly one row holding an integer ≥ 1, or is above the last mapped step (258); a value from 1 to 258 is read as dev's steps of those numbers, so a pre-ORM feature-branch database whose steps differ is not detected (the Tours branch is the one case it cuts back). Recorded `mikro_orm_migrations` names this build does not ship refuse it too (`refuseNewerDatabase`), whether a newer release or a development build wrote them. 4.3.x and earlier have no such check and start on a database 5.x migrated. Before a boot applies pending migrations to a file database that holds anything, `db/pre-migrate-snapshot.ts` writes a `VACUUM INTO` copy next to it (`pre-migrate-<schema>-<time>.db`, `<schema>` being `legacy-<schema_version>` or the last recorded migration's timestamp; the newest `TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP` stay) and the newer-database refusal names the matching copy; a copy that cannot be written refuses the boot unless `TREK_DB_PRE_MIGRATE_SNAPSHOT=false`. It is off under `NODE_ENV=test` unless a suite sets that variable to true, and a restore's re-bootstrap skips it (the archive is the copy). After the migrator, `db/email-case-index.ts` creates the case-insensitive unique index on `users.email` that its migration had to defer on an install holding two accounts whose emails differ only in case (flag `email_case_index_pending`). `db/orm-driver.ts` binds the ORM to that same connection instead of opening a second one — with `:memory:` under test, a second connection is a second, empty database. Kysely statements (`this.kysely<...>()`) type against `DB` from `db/kysely/db.ts`, narrowed with `Pick<DB, 'trips' | 'days'>`; those files are generated from the migrated schema by `scripts/generate-db-types.ts`, so a migration that adds or changes a column is followed by `npm run gen:db-types`, never by a hand-written table interface. Every read and write goes through a repository in `db/repositories/` (each extends the shared `TrekRepository` base in `db/repositories/_shared/`, which validates the request context before delegating to MikroORM) and, for multi-statement writes, `UnitOfWork.transactional(...)` (`nest/database/unit-of-work.ts`, provided by the global `OrmModule`) — there is no `DatabaseService`/`DatabaseModule` to inject any more. Entrypoints outside an HTTP request — an MCP tool call, a plugin RPC dispatch, a WebSocket message, a cron job, boot-time seeding, a backup restore — open one explicitly with `withRequestContext()` (`nest/database/request-context.ts`), since only the pathless `mikroOrmRequestContext` middleware `buildApp()` mounts (with `@mikro-orm/nestjs`'s own `registerRequestContext` turned off in `app.module.ts`, UPLOADS-P16) forks an `EntityManager` per HTTP request. `NODE_ENV=test` ⇒ isolated `:memory:` DB per vitest worker, opened from a snapshot `tests/global-setup.ts` migrates once per run; `TREK_DB_FILE` ⇒ explicit file DB (Playwright harness).
-- **Engines** (`src/db/engine/`): `TREK_DB_URL` (a `postgres://` URL) runs TREK on Postgres instead of the SQLite file; without it nothing changes. `resolveEngine()` picks the engine, and what differs by engine (the ORM options, opening and closing, how a database reaches the schema) is the engine's, behind the `DatabaseEngine` contract that `DatabaseLifecycle` calls; code elsewhere never checks which engine it runs on (`lint:engine-dispatch`). The Postgres driver (`src/db/engine/postgres/postgres-driver.ts`) reads `bigint` as a number. A Postgres database never replays the SQLite migrations: an empty one gets `assets/postgres/baseline.sql` (generated from the entities by `gen:pg-baseline`, with the triggers ported by hand in `POSTGRES_TRIGGERS`) and every migration up to its cut recorded as executed, in one transaction (`src/db/engine/postgres/schema-bootstrap.ts`); one holding tables without TREK's migration history is refused; an empty one (or one TREK migrated that holds no account) is refused too while the data directory's `travel.db` holds accounts, unless `TREK_DB_IGNORE_SQLITE_FILE=true` (`sqliteLeftBehind` in the bootstrap deps), so a forgotten move never boots an empty instance; one TREK migrated runs the newer-database refusal and the pending migrations. The migrations after the cut run on Postgres through the migrator, each with its schema change written once per engine through `engineDdl` (SQL dialect, Migrations, has the routine), and the baseline stays frozen for them. Before pending migrations the boot takes a `pg_dump` copy to `data/pre-migrate-<last migration>-<time>.pgdump` under the same `TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP)` policy as the SQLite file. The backup port's Postgres side (`src/nest/backup/postgres-database-backup.ts`) dumps with `pg_dump`; a restore turns the dump into a script with `pg_restore` and has `psql` clear the current schema and run it in one transaction (a dump only recreates what it holds, so `pg_restore --clean` would leave a later migration's tables behind); the restore refuses a pg_restore or psql older than 18.0/17.6/16.10/15.14/14.19, whose script would lack the `\restrict` line that keeps a psql meta-command smuggled into a dump from running (CVE-2025-8714), streams the script to its work file and stops it past `BACKUP_MAX_DECOMPRESSED_MB`, and refuses a role that could reach the database host from SQL (`PRIVILEGED_ROLE_SQL` in `server-checks.ts`: a member of any superuser role, its own included, a holder of `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, a role granted EXECUTE on a server file function (`lo_export`, `pg_read_file`, ...), from PostgreSQL 15 on a role granted ALTER SYSTEM or SET on a superuser-only setting, and before PostgreSQL 16 a member of a role with CREATEROLE, its own included, which may grant itself those; the archive's SQL runs as that role, and the boot warns about one). The tools run by absolute path (`src/db/engine/postgres/pg-tools.ts`, `TREK_DB_PG_BIN_DIR`, else `/usr/lib/postgresql/<major>/bin` newest first) with the password in their environment, never on the command line, and their stderr reaches an error only summarized, without the lines that quote rows. Supported servers are PostgreSQL 14 to 18 (`src/db/engine/postgres/server-checks.ts`): the boot refuses any other before it writes anything. The image ships the version 18 client from the PGDG apt repository (pinned major, key kept in `scripts/pgdg-apt-key.asc`), because a client handles every server up to its own major and refuses a newer one; a dump or a restore refuses a client older than the server, and `sslrootcert=system` (the default when the URL names an `sslmode` but no CA) only with a client from 16 on. The migration history lives in the current schema beside the tables (the bootstrap qualifies MikroORM's `migrations.tableName` with `current_schema()`), so the backups, which hold that schema, include it. A restore refuses a SQLite archive or a newer TREK's dump before anything is replaced, and replaces everything in the schema, so TREK wants a database of its own and a role that is not a superuser. `RESTORE_FROM_BACKUP` loads the archive's dump the same way into a database that holds no table yet, and is ignored once it holds one. The Postgres lane (`vitest.pg.config.ts`, `npm run test:pg`, CI job `server-postgres`, once on Postgres 14 and once on 18, each in three slices) runs every suite that boots the app on the real database module, each file on its own copy of one template database migrated by the engine's bootstrap (`tests/postgres/global-setup.ts`), plus `tests/postgres/` (PARITY-PG: the comparator finds nothing between the bootstrapped database and the entities but the differences it lists with their reason; the write lock; case-insensitive search). `TREK_TEST_DB_URL` names a database it may create and drop databases from; without it the lane fails, and with `TREK_TEST_PG_MAJOR` set it refuses a server of another major. Nobody keeps the list: `tests/postgres/lane.ts` takes every test file that reaches `src/bootstrap.ts` or `src/nest/app.module.ts` through its imports (directly or through a helper under `tests/`, so `buildApp()`, `bootTestApp()` and the broadcast-parity harness all count) and does not `vi.mock` `src/db/database`. Its `SQLITE_ONLY` map names the suites that stay on SQLite by design, each with its reason (the two whose faked clock needs SQLite to answer synchronously, the two about the better-sqlite3 handle, and the legacy upgrade suites, which mock `src/db/database` onto a SQLite file the retired positional runner built and so never name the snapshot). A suite that boots the app over the SQLite snapshot mock can never run on Postgres; the ones that still do are listed in `tests/postgres/snapshot-suites-baseline.json`, which only shrinks. `tests/unit/postgres-lane.test.ts` (PGLANE, in the SQLite lane) fails on a new such suite (drop the mock and seed through `tests/helpers/factories` with `app.get(MikroORM)`, as `tests/e2e/packing-mcp.e2e.test.ts` does), on a baseline entry or exclusion that went stale, and on a suite that names `buildApp`/`bootTestApp`/`AppModule` without the discovery seeing it boot. The suites that build a partial module over `createTestOrm(db)`/`createTestMikroOrmModule(db)` bind the ORM to a better-sqlite3 handle and stay on SQLite; the probe is what checks their repositories' SQL on Postgres. An existing SQLite install moves with `npm run db:move-to-postgres` (`src/move-to-postgres.ts`, the move itself in `src/db/engine/postgres/sqlite-move/`): it refuses a file at another migration level, orphaned rows and a target holding any table or plugin schema, creates the schema with the engine's own bootstrap (no seeders), then in one transaction empties the bootstrap's rows, copies every table in foreign key order (a self-reference is set after its rows), converts each value to its Postgres column type and refuses one it cannot hold exactly (a NUL character in TREK's own text too, unless `--drop-nul` lets it drop each one and list it in the summary), copies each plugin's `plugin.db` into its schema after checking, before anything is written, that every plugin value comes back from the Postgres store with its type and bytes, moves the sequences past the copied ids (and past `sqlite_sequence`), and compares every table's row count and an order-free checksum over all rows, built from the SQLite values rather than the converted ones, before it commits; a failure drops the schema again. It never writes the SQLite file and never touches uploads. Two processes starting on one Postgres database at once are not coordinated yet: the second fails its boot (the first one's schema transaction wins), so start one instance for a first boot or an upgrade before scaling out.
+- **Engines** (`src/db/engine/`): `TREK_DB_URL` (a `postgres://` URL) runs TREK on Postgres instead of the SQLite file; without it nothing changes. `resolveEngine()` picks the engine, and what differs by engine (the ORM options, opening and closing, how a database reaches the schema) is the engine's, behind the `DatabaseEngine` contract that `DatabaseLifecycle` calls; code elsewhere never checks which engine it runs on (`lint:engine-dispatch`). The Postgres driver (`src/db/engine/postgres/postgres-driver.ts`) reads `bigint` as a number. A Postgres database never replays the SQLite migrations: an empty one gets `assets/postgres/baseline.sql` (generated from the entities by `gen:pg-baseline`, with the triggers ported by hand in `POSTGRES_TRIGGERS`) and every migration up to its cut recorded as executed, in one transaction (`src/db/engine/postgres/schema-bootstrap.ts`); one holding tables without TREK's migration history is refused; an empty one (or one TREK migrated that holds no account) is refused too while the data directory's `travel.db` holds accounts, unless `TREK_DB_IGNORE_SQLITE_FILE=true` (`sqliteLeftBehind` in the bootstrap deps), so a forgotten move never boots an empty instance; one TREK migrated runs the newer-database refusal and the pending migrations. The migrations after the cut run on Postgres through the migrator, each with its schema change written once per engine through `engineDdl` (SQL dialect, Migrations, has the routine), and the baseline stays frozen for them. Before pending migrations the boot takes a `pg_dump` copy to `data/pre-migrate-<last migration>-<time>.pgdump` under the same `TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP)` policy as the SQLite file. The backup port's Postgres side (`src/nest/backup/postgres-database-backup.ts`) dumps with `pg_dump`; a restore turns the dump into a script with `pg_restore` and has `psql` clear the current schema and run it in one transaction (a dump only recreates what it holds, so `pg_restore --clean` would leave a later migration's tables behind); the restore refuses a pg_restore or psql older than 18.0/17.6/16.10/15.14/14.19, whose script would lack the `\restrict` line that keeps a psql meta-command smuggled into a dump from running (CVE-2025-8714), streams the script to its work file and stops it past `BACKUP_MAX_DECOMPRESSED_MB`, and refuses a role that could reach the database host from SQL (`PRIVILEGED_ROLE_SQL` in `server-checks.ts`: a member of any superuser role, its own included, a holder of `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, a role granted EXECUTE on a server file function (`lo_export`, `pg_read_file`, ...), from PostgreSQL 15 on a role granted ALTER SYSTEM or SET on a superuser-only setting, and before PostgreSQL 16 a member of a role with CREATEROLE, its own included, which may grant itself those; the archive's SQL runs as that role, and the boot warns about one). The tools run by absolute path (`src/db/engine/postgres/pg-tools.ts`, `TREK_DB_PG_BIN_DIR`, else `/usr/lib/postgresql/<major>/bin` newest first) with the password in their environment, never on the command line, and their stderr reaches an error only summarized, without the lines that quote rows. Supported servers are PostgreSQL 14 to 18 (`src/db/engine/postgres/server-checks.ts`): the boot refuses any other before it writes anything. The image ships the version 18 client from the PGDG apt repository (pinned major, key kept in `scripts/pgdg-apt-key.asc`), because a client handles every server up to its own major and refuses a newer one; a dump or a restore refuses a client older than the server, and `sslrootcert=system` (the default when the URL names an `sslmode` but no CA) only with a client from 16 on. The migration history lives in the current schema beside the tables (the bootstrap qualifies MikroORM's `migrations.tableName` with `current_schema()`), so the backups, which hold that schema, include it. A restore refuses a SQLite archive or a newer TREK's dump before anything is replaced, and replaces everything in the schema, so TREK wants a database of its own and a role that is not a superuser. `RESTORE_FROM_BACKUP` loads the archive's dump the same way into a database that holds no table yet, and is ignored once it holds one. The Postgres lane (`vitest.pg.config.ts`, `npm run test:pg`, CI job `server-postgres`, once on Postgres 14 and once on 18, each in two slices) runs every suite that boots the app on the real database module, each file on its own copy of one template database migrated by the engine's bootstrap (`tests/postgres/global-setup.ts`), plus `tests/postgres/` (PARITY-PG: the comparator finds nothing between the bootstrapped database and the entities but the differences it lists with their reason; the write lock; case-insensitive search). `TREK_TEST_DB_URL` names a database it may create and drop databases from; without it the lane fails, and with `TREK_TEST_PG_MAJOR` set it refuses a server of another major. Nobody keeps the list: `tests/postgres/lane.ts` takes every test file that reaches `src/bootstrap.ts` or `src/nest/app.module.ts` through its imports (directly or through a helper under `tests/`, so `buildApp()`, `bootTestApp()` and the broadcast-parity harness all count) and does not `vi.mock` `src/db/database`. Its `SQLITE_ONLY` map names the suites that stay on SQLite by design, each with its reason (the two whose faked clock needs SQLite to answer synchronously, the two about the better-sqlite3 handle, and the legacy upgrade suites, which mock `src/db/database` onto a SQLite file the retired positional runner built and so never name the snapshot). A suite that boots the app over the SQLite snapshot mock can never run on Postgres; the ones that still do are listed in `tests/postgres/snapshot-suites-baseline.json`, which only shrinks. `tests/unit/postgres-lane.test.ts` (PGLANE, in the SQLite lane) fails on a new such suite (drop the mock and seed through `tests/helpers/factories` with `app.get(MikroORM)`, as `tests/e2e/packing-mcp.e2e.test.ts` does), on a baseline entry or exclusion that went stale, and on a suite that names `buildApp`/`bootTestApp`/`AppModule` without the discovery seeing it boot. The suites that build a partial module over `createTestOrm(db)`/`createTestMikroOrmModule(db)` bind the ORM to a better-sqlite3 handle and stay on SQLite; the probe is what checks their repositories' SQL on Postgres. An existing SQLite install moves with `npm run db:move-to-postgres` (`src/move-to-postgres.ts`, the move itself in `src/db/engine/postgres/sqlite-move/`): it refuses a file at another migration level, orphaned rows and a target holding any table or plugin schema, creates the schema with the engine's own bootstrap (no seeders), then in one transaction empties the bootstrap's rows, copies every table in foreign key order (a self-reference is set after its rows), converts each value to its Postgres column type and refuses one it cannot hold exactly (a NUL character in TREK's own text too, unless `--drop-nul` lets it drop each one and list it in the summary), copies each plugin's `plugin.db` into its schema after checking, before anything is written, that every plugin value comes back from the Postgres store with its type and bytes, moves the sequences past the copied ids (and past `sqlite_sequence`), and compares every table's row count and an order-free checksum over all rows, built from the SQLite values rather than the converted ones, before it commits; a failure drops the schema again. It never writes the SQLite file and never touches uploads. Two processes starting on one Postgres database at once are not coordinated yet: the second fails its boot (the first one's schema transaction wins), so start one instance for a first boot or an upgrade, and keep one: TREK holds rate limits, pending codes, the permission cache and the WebSocket connections in memory, so it runs as a single replica on either engine.
## Rules for new code
@@ -91,6 +91,7 @@ Nest owns everything. Every domain is a DI module under `src/nest/<domain>/` (`c
- **Transactions are not optional.** Multi-statement writes go in `await this.uow.transactional(async () => …)` (`UnitOfWork` from `nest/database`, provided by the global `OrmModule`); never hand-roll `BEGIN`/`COMMIT` and never call `db.transaction()` (the Phase 1 async sweep removes it). The sequence lives in the service, never in a controller, MCP tool or RPC handler, so every surface calls the one method that holds the transaction (`ReservationsService.createWithCost` is the shape: side effects such as broadcasts come back to the caller and go out after the commit). A position or id taken as `MAX(...) + 1` is read inside the same transaction as the insert that uses it: the transaction holds the connection, so two requests at once cannot read the same MAX. On Postgres, where a pool runs transactions side by side, `UnitOfWork` first takes one advisory lock for the database (`DatabaseEngine.serializeWrites`), so the same holds; a transaction opened any other way does not get it. So no other transaction is opened under `src/`: ESLint (`trek/transactions-through-unit-of-work`, `eslint-rules/transactions-through-unit-of-work.mjs`, held by `lint:warnings`) refuses `em.transactional`, a repository's own `getEntityManager().transactional`, `em.begin()`, a connection's `transactional` and Kysely's `transaction()` everywhere but `src/db/engine/` and the boot-time `src/db/email-case-index.ts` and `src/db/legacy-baseline.ts`. Code outside the Nest container (the demo seed and reset) opens the same transaction with `writeTransaction` (`src/db/engine/write-transaction.ts`), which `UnitOfWork` wraps. Every check a write relies on (a count under a cap, a name or a row that must not exist yet, the last admin, a one-time token) is read inside the transaction that writes, and a repository method that holds such a check (`upsertValueCapped`, `upsertTaskCapped`) runs inside its caller's unit of work instead of opening one; a claim that has to be single (`markConsumed`, `claimReminder`) is one conditional statement. `lint:tx` holds the rest. Every DB-touching method is `async`; `@typescript-eslint/no-floating-promises` and `no-misused-promises` are errors, so an unawaited call or a `Promise` in a condition fails lint. Bind values with `?`; identifiers only via a literal allow-list. Everywhere under `src/`, ESLint refuses raw SQL in any spelling: `raw()`, the `sql` tag, and SQL text handed to `execute`/`run`/`all`/`get`, so SQL lives in a repository, where the Postgres probe runs it, and a service, job, guard or tool never sends its own. Build the statement with the query builder. Raw SQL has three homes, `src/db/dialect/`, `src/db/engine/` and `src/db/migrations/`; besides them the boot-time lifecycle files `email-case-index.ts`, `legacy-baseline.ts`, `migration-utils.ts` and `pre-migrate-snapshot.ts` in `src/db/`, and `MaintenanceRepository`, `AdminSeeder` and `CategorySeeder` for SQL text, are the named exceptions in `eslint.config.mjs`, and `tests/unit/eslint-rules/restricted-syntax-selectors.test.ts` pins how many SQL strings each still holds, so they can only lose SQL, never gain it. An insert that needs the new id reads it with `.returning('id')`: `InsertResult.insertId` is SQLite's `last_insert_rowid` and undefined on Postgres, and ESLint refuses it in `src/db/repositories/` and `src/db/seeders/`.
- **Migrations are append-only.** A migration is identified by its class name in `mikro_orm_migrations`, and files sort by the timestamp in that name. Never rename or delete one that has shipped, and never edit its body; add a new one. No env interpolation in SQL. (The old positional `schema_version` array and the hand-kept `db/migrations.ts` test builder are both gone; the numbered migrations are the only schema history, for tests too.) A new foreign key comes with an index that leads with its column(s), or deleting the parent scans the child table (a partial index counts only when its WHERE clause is `IS NOT NULL` on those columns); `tests/unit/db/foreign-key-indexes.test.ts` fails on one without.
- **Every write endpoint validates** through the Zod pipe with a schema from `@trek/shared` — no `Record<string, unknown>` + ad-hoc checks. Also verify every referenced id exists and belongs to the same trip. A number bound for an integer column (`p.integer()`, `bigint` on Postgres) takes `.int()`: SQLite would store a fraction as a REAL where Postgres rounds or refuses it. INTCOL (`tests/unit/contracts/integer-columns.test.ts`) reads the integer columns from the entities and fails on a DTO field or an inline MCP tool field of that name without it; a field that only shares the name goes into its `NOT_A_COLUMN` with the reason. A value that really is fractional (a half day) gets a REAL/`double precision` column instead.
+- **A row id from a request is read through `toRowId`** (`src/db/row-id.ts`): only the decimal spelling is an id, and anything else (`'0x5'`, `'5e0'`, `'5.0'`, `'+5'`, `' 5'`, `'5_0'`, a number past 2^53) names no row. Bound raw, such a string matches nothing on SQLite, is refused by Postgres 14 and 15 (a 500) and read as a number from 16 on; `Number()`, `parseInt()` and Nest's `ParseIntPipe` read it as row 5 on every engine. A path id is declared `@Param('id', rowId('<the route's not-found error>'[, status])) id: number` (`src/nest/common/row-id.pipe.ts`; `ParseRowIdPipe` in place of `ParseIntPipe`, `intParam` for a year or a day number), or read with `toRowId`/`withRowId` in the guard, service or repository lookup that answers for an unknown id. A body or query id is declared in its `@trek/shared` schema as `rowIdInputSchema` (a number or its digits, kept as sent), `rowIdStringSchema` (a multipart field) or `idParamSchema` (read as a number), a list of ids as `z.array(z.number().int())`, so one `toRowId` refuses is a 400 `<field>: Invalid id`; a field the schema leaves open is read with `toRowId` where it is used. An MCP resource URI id goes through `uriRowId`, a plugin RPC id through `rowIdParam` or `optionalRowIdParam` (`src/nest-rpc/rpc-params.ts`). Four gates hold this. ROUTEID (`tests/e2e/route-row-ids.e2e.test.ts`, in the SQLite suite and the Postgres lane) sends those spellings to every registered route with a path id, with a body its DTO accepts, fails on a 5xx or on any answer that differs from the one `'abc'` gets, and records what the drivers are handed (`tests/helpers/sql-capture.ts`), failing when a spelling of an id no row has, or the number `Number()` makes of it, reaches SQL; a param named like an id that is not an integer row id goes into its `NOT_ROW_IDS` with the reason. ROUTEID-002 fails on a field named like a row id in any request schema or route DTO that accepts such a spelling (`NOT_ROW_ID_FIELDS` names the string ids, `READ_BY_HANDLER` the open fields a handler parses). MCPROWID (`tests/e2e/mcp-resource-row-ids.e2e.test.ts`) does the same for every MCP resource URI, RPCROWID (`tests/unit/nest-rpc/rpc-row-id-params.test.ts`) refuses a plugin RPC id param read past `rowIdParam`.
- **Every outbound `fetch`** gets a timeout, a response-size cap and boundary validation: no `as`-casting provider responses, no silent `catch → null`. User-influenced URLs go through the SSRF guard. Never fall back to another user's API key. ESLint requires an init with a `signal` on `fetch`, `safeFetch`, `safeFetchFollow` and `safeFetchAdminConfigured` alike, or a literal `timeoutMs` in the options object of `safeFetch`/`safeFetchFollow`; an init spelled `undefined`, `null` or `void 0` counts as none (`safeFetchLlm` takes `LLM_TIMEOUT_MS` inside). Behind that, the guarded wrappers (`utils/ssrfGuard.ts`) cap every body at `DEFAULT_MAX_RESPONSE_BYTES` (64 MB) and, for a call without a signal, wait `DEFAULT_RESPONSE_TIMEOUT_MS` (30 s) for the headers. Pass a tighter `maxBytes` when you buffer a small answer, `timeoutMs` for a deadline over the whole exchange, and `maxBytes: null` only where the body is streamed on or counted by the caller (`pipeAsset`, the doc-sync transfers, the Ollama pull).
- **Fail closed.** Unrecognized flag values mean OFF; sandbox/permission opt-outs refuse in production; never pick a less-safe path based on the *absence* of a file. GET handlers must not write.
- **Don't fork canonical paths.** Auth verification is `verifyJwtAndLoadUser` (with the `password_version` gate and the session gate); reuse it. A session token is minted only by `SessionsService.issue` (`nest/sessions/`, reached through `AuthService.generateToken`), which writes the `user_sessions` row its `jti` names; a token signed anywhere else carries no session and cannot be listed or revoked. An action that should sign a user out everywhere calls `SessionsService.revokeAll` inside the same transaction as the write that warrants it.
@@ -109,7 +110,7 @@ SQLite is the default engine and Postgres the second (`TREK_DB_URL`, see Engines
- **The new id**: `.returning('id').executeTakeFirstOrThrow()`. Never `InsertResult.insertId` or `last_insert_rowid()`; both are SQLite's rowid and undefined on Postgres.
- **Time**: `currentTimestamp`/`currentTimestampKysely`, `nowMinusDays`, `nowMinusHours`, `nowPlusSeconds`/`nowPlusSecondsKysely`, `nowDateOffset`, `dateOf`, `dateAdd`, `unixEpochToIsoKysely` from `src/db/dialect/sql-functions.ts` (the MikroORM `raw()` helpers) and `src/db/dialect/kysely-functions.ts` (their Kysely-expression twins). Never `datetime('now')`, `strftime` or `julianday`.
- **Search that ignores case**: `ilike(platform, refs)` builds the `(a LIKE ? ESCAPE '\' OR …)` condition, `ILIKE` on Postgres, where `LIKE` is exact. A bare `LIKE` is for a prefix that is exact on both engines (a settings key, a storage path), and says so in a `// like-exact: <reason>` comment (`lint:dialect`).
-- **No NUL in text**: Postgres text cannot hold U+0000, so TREK stores it on neither engine. `src/db/nul-free.ts` drops it where every value leaves for the database (both MikroORM platforms, both Kysely dialects; the move from SQLite only with `--drop-nul`, and it lists each value), filters included, so the same request leaves the same row on either engine. A client's input loses it before any logic runs (`src/nest/common/nul-free-input.ts`: the `nulFreeRequest` middleware for the path, query, body and cookies, the first global pipe for a multipart body, the websocket adapter for every frame, `trekMcpInputMapper` for MCP arguments), so a throttle key, a pre-check or a comparison sees the value the database stores; a password TREK only ever hashes (the keys in `HASHED_PASSWORD_KEYS`, matched exactly; `password_login` is a flag and is cleaned) is left as sent, and `tests/unit/db/nul-free.test.ts` fails on a new field of the shared schemas or the settings named like a secret until it is decided either way. New code never strips NUL itself. A plugin's own data is the plugin's: its SQLite file binds a NUL exactly, and its Postgres schema refuses one with an error (`plugin-data-checks.ts`), so its keys never change meaning.
+- **No NUL in text**: Postgres text cannot hold U+0000, so TREK stores it on neither engine. `src/db/nul-free.ts` drops it where every value leaves for the database (both MikroORM platforms, both Kysely dialects; the move from SQLite only with `--drop-nul`, and it lists each value), filters included, so the same request leaves the same row on either engine. A client's input loses it before any logic runs (`src/nest/common/nul-free-input.ts`: the `nulFreeRequest` middleware for the path, query, body and cookies, the first global pipe for a multipart body, the websocket adapter for every frame, `trekMcpInputMapper` for MCP arguments), so a throttle key, a pre-check or a comparison sees the value the database stores; a password TREK only ever hashes (the keys in `HASHED_PASSWORD_KEYS`, matched exactly; `password_login` is a flag and is cleaned) is left as sent, and `tests/unit/db/nul-free.test.ts` fails on a new field of the shared schemas or the settings named like a secret until it is decided either way. New code never strips NUL itself. A plugin's own data is the plugin's: both engines refuse a NUL in its SQL, arguments and migration ids with the same error (`src/db/engine/plugin-data-contract.ts`) instead of dropping it, so its keys never change meaning and it answers alike on either engine.
- **Dates bound as dates**: SQLite rolls an impossible day (`2024-02-30`) over into the next month where Postgres refuses to cast it; a helper that binds a value either engine reads as a date (`dayDistance`) refuses anything `isCalendarDate` does not accept, on both engines, and its caller checks first.
- **Strings and casts**: `concat`/`concatKysely` instead of `||`, `substring`/`substringKysely`, `lower`/`lowerTrim`, `collateNoCase`, `castInteger`/`castIntegerKysely`, and `startsWithIsoDate`/`startsWithIsoDateKysely` instead of `GLOB`.
- **JSON columns** are read whole and parsed in the service; no `json_extract` in SQL. Each one is declared once in `src/db/json-columns.ts` (its Zod shape and the fallback a reader gets for an empty or broken row) and read with `decodeJson`/`decodeJsonResult`, written from a server-built value with `encodeJson` (`src/utils/json-column.ts`), never with a bare `JSON.parse` at the call site: one column, one answer to a broken row, logged.
diff --git a/wiki/Database-Postgres.md b/wiki/Database-Postgres.md
index 2d3e133ce..49dcc0828 100644
--- a/wiki/Database-Postgres.md
+++ b/wiki/Database-Postgres.md
@@ -2,7 +2,7 @@
By default TREK keeps all data in one SQLite file, `travel.db`, in the data directory. Setting `TREK_DB_URL` runs TREK on a PostgreSQL database instead. Without that variable nothing changes, and every page of this wiki that describes `travel.db` still applies to an install on SQLite.
-> **Status:** Postgres support is new. It has been checked end to end against PostgreSQL 17 in Docker (first boot, sign-in, trips, backup and restore, the copy before a migration, `RESTORE_FROM_BACKUP`). The same checks have been run against a Supabase project over its direct connection; see [Supabase](#supabase) and the [Manual verification checklist](#manual-verification-checklist) below.
+> **Status:** Postgres support is new. On every pull request, CI runs the server test suites that start the app against PostgreSQL 14 and 18, the oldest and newest supported versions. It has also been checked by hand end to end against PostgreSQL 17 in Docker (first boot, sign-in, trips, backup and restore, the copy before a migration, `RESTORE_FROM_BACKUP`). The same checks have been run against a Supabase project over its direct connection; see [Supabase](#supabase) and the [Manual verification checklist](#manual-verification-checklist) below.
## When to use it
@@ -128,7 +128,9 @@ TREK ships a command that copies a SQLite install into an empty Postgres databas
It prints a summary: the tables and rows it copied, the plugin schemas it filled, every value it changed with `--drop-nul`, and anything it could not carry over.
-**NUL characters in TREK's data.** Postgres text cannot hold the character U+0000 (NUL). TREK no longer stores it on either engine and drops it on its next write, but a `travel.db` from an older version may still hold one. The command changes nothing silently, so by default it refuses such a value and lists it by table, row and column. To drop the character during the move, the way TREK would on its next write, run the command again with `--drop-nul`. The summary then lists every value it changed. If two values in a unique column differed only by a NUL, dropping it makes them equal. The command then stops, names the key and lists the values it changed in that column. Change or remove one of the two rows in the SQLite file, with TREK stopped, and run the command again. In JSON, `--drop-nul` removes only the escaped character (`\u0000`); everything else in the value stays as it was written.
+**NUL characters in TREK's data.** Postgres text cannot hold the character U+0000 (NUL). TREK no longer stores it on either engine and drops it on its next write, but a `travel.db` from an older version may still hold one. The command changes nothing silently, so by default it refuses such a value and lists it by table, row and column. To drop the character during the move, the way TREK would on its next write, run the command again with `--drop-nul`. The summary then lists every value it changed. If two values in a unique column differed only by a NUL, dropping it makes them equal. The command then stops and names the key and the value the two rows share. It lists the values it changed in the columns that key reads (for a key over an expression such as `lower(email)`, the columns the expression reads) whose text that value holds, so you can check those rows first; a key can also break for a reason that has nothing to do with a NUL (see below). Change or remove one of the two rows in the SQLite file, with TREK stopped, and run the command again. JSON holds a NUL either escaped (`\u0000`) or, in a value written by hand, as the raw character; the command refuses both as a NUL, and `--drop-nul` removes both, the way TREK drops it on its next write. Everything else in the value stays as it was written. A JSON value that is not valid even without its NUL characters is refused as invalid JSON.
+
+**Values the SQLite file accepted and Postgres does not.** A few values pass SQLite's checks but not Postgres's: two rows that a unique key on Postgres holds equal while the SQLite file kept them apart (an install whose case-insensitive email index is still pending holds two accounts whose addresses differ only in case; SQLite's `lower()` changes only the letters A to Z), a value outside a column's allowed set, or JSON holding an escape of half a UTF-16 surrogate pair (`\ud800` alone). The command refuses the move, names the table and the key or value Postgres reports, and says what to do: correct or remove the row in the SQLite file, with TREK stopped, and run the command again. For a plugin's table, that row is in the plugin's `plugin.db`. A value Postgres refuses by its type once the command has let it through is a gap in the command, not in your data: the command stops, writes nothing, and asks you to report it.
**Text that is not UTF-8.** SQLite stores the bytes of a text value as it is given them, so a value written by hand with the `sqlite3` tool can hold bytes that are not valid UTF-8. Postgres text cannot hold such bytes, and reading them as text would replace them. The command refuses such a value, in TREK's data and in plugin data, with or without `--drop-nul`, and lists it by table, row and column with its bytes in hex. Correct the value in the SQLite file, with TREK stopped, and run the command again.
@@ -202,14 +204,16 @@ A plugin with the `db:own` permission keeps its own database. On SQLite that is
- **TREK's role creates the schemas**, so it needs the `CREATE` privilege on the database, which the role that owns the database has.
- **No plugin SQL on a privileged role.** While `TREK_DB_URL` connects as a role TREK refuses restores for (a superuser or a member of one, or a role that may reach the server's files or programs; see [A role that is not a superuser](#a-role-that-is-not-a-superuser)), every plugin database call fails with "Plugin databases (db:own) are refused on Postgres ...", and the boot log says so. A plugin's SQL runs as TREK's role, and such a role could change the system catalogs for the whole server. Connect TREK as a role that owns its database and is not a superuser, and restart; TREK reads the role once per pool connection.
- **A plugin's SQL stays in its schema**, in layers the database enforces as well as TREK's own check:
- - TREK refuses a statement before it runs when it names another schema, the system catalogs, a function that could reach past the schema, or a type that looks an object up by name (`regclass`, `regtype`, `regconfig` and the other `reg*` types, `aclitem`, `has_table_privilege` and its siblings). Of PostgreSQL's own functions a plugin may call only those on an allowlist, the ones that work on their arguments alone (string, number, date and time, JSON, array, aggregate, window, UUID, range, geometry, network address and full text search functions). Every other one is refused, so a function that reads the catalogs or the server (`obj_description`, `format_type`, `version()`, `current_database()`, `inet_server_addr()`, ...) cannot reveal the names or comments of TREK's objects, and neither can a function a later PostgreSQL adds; the keywords `current_user`, `session_user` and their siblings are refused too. It also refuses temporary objects (`CREATE TEMP`/`TEMPORARY` and `SELECT ... INTO TEMP`; a column named `temp` is fine), `INTO` anywhere but after the `INSERT` or `MERGE` that is the statement's verb, hexadecimal, octal and binary numbers, and control characters or non-ASCII whitespace outside strings, which Postgres reads differently from the check.
+ - TREK refuses a statement before it runs when it names another schema, the system catalogs, a function that could reach past the schema, or a type that looks an object up by name (`regclass`, `regtype`, `regconfig` and the other `reg*` types, `aclitem`, `has_table_privilege` and its siblings). Of PostgreSQL's own functions a plugin may call only those on an allowlist, the ones that work on their arguments alone (string, number, date and time, JSON, array, aggregate, window, UUID, range, geometry, network address functions, and full text search over vectors the plugin builds itself). The text search functions that take a configuration name (`to_tsvector`, `to_tsquery`, `ts_headline`, ...) are refused, since the name is looked up in the catalogs. Every other one is refused, so a function that reads the catalogs or the server (`obj_description`, `format_type`, `version()`, `current_database()`, `inet_server_addr()`, ...) cannot reveal the names or comments of TREK's objects, and neither can a function a later PostgreSQL adds; the keywords `current_user`, `session_user` and their siblings are refused too. A read of a system column (`xmin`, `xmax`, `cmin`, `cmax`, `ctid`, `tableoid`) is refused, since they show the server's transaction ids and where rows are stored and SQLite does not have them; a value of the plugin's own may still carry such a name where it is given (`min(lng) AS xmin`). The transaction id types `xid` and `xid8` are refused where the word stands for the type (`'3'::xid`, `xid(x)`, `x.xid`, a column of that type), since `age()` of one shows the server's transaction counter; a column of the plugin's own may be called `xid` and is then named without its table. A collation other than `"C"`, `"POSIX"`, `"default"` and `ucs_basic`, and an access method other than the built-in ones (`btree`, `hash`, `gist`, `gin`, `spgist`, `brin`, `heap`), are refused, since which others exist depends on the server's locales and extensions. It also refuses temporary objects (`CREATE TEMP`/`TEMPORARY` and `SELECT ... INTO TEMP`; a column named `temp` is fine), `INTO` anywhere but after the `INSERT` or `MERGE` that is the statement's verb, hexadecimal, octal and binary numbers, and control characters or non-ASCII whitespace outside strings, which Postgres reads differently from the check.
- Right before an `ALTER`, `DROP`, `REFRESH`, `TRUNCATE` or `CREATE INDEX ... ON`, Postgres itself resolves the objects the statement changes, and TREK refuses it unless each one lies in the plugin's schema. An unqualified `int4` or `text` is the built-in type and is refused, whatever the role may do.
- Each statement is sent on its own over the extended query protocol, which runs one statement and no more.
- Every connection of TREK's pool searches the temporary schema last, and a plugin call drops the temporary tables and other session state of the connection it used before handing it back, so a temporary table can never stand in for one of TREK's.
- A call that writes is held to the quota (256 MB, counted over every table, index, sequence and materialized view of the schema with their TOAST storage) and to 5,000 catalog objects (relations, types, constraints, enum labels), so objects that take no disk space are bounded too.
The rules are in the [plugin-sdk README](https://github.com/liketrek/TREK/blob/main/plugin-sdk/README.md#your-own-database-on-postgres).
-- **No NUL character in plugin text.** Postgres text cannot hold U+0000. A plugin argument holding one is refused with an error that names the reason, instead of being changed. On SQLite a plugin's own file keeps storing and finding it as before. TREK's own data holds no NUL on either engine.
+- **Values print the same on every server.** Every plugin transaction sets the time zone to UTC and the date style, the locale for money, numbers and dates, the float, bytea and xml output and the text search configuration to PostgreSQL's built-in defaults, so what a plugin reads does not depend on how the server is configured. The settings end with the transaction. The order of text follows the database's collation; a plugin that wants SQLite's order (by code point) writes `ORDER BY name COLLATE "C"`.
+- **No NUL character in plugin text, on either engine.** Postgres text cannot hold U+0000. SQL, a plugin argument or a migration id holding one is refused with an error that names the reason, instead of being changed, on SQLite as on Postgres, and `trek-plugin dev` refuses it the same way. SQL that builds a NUL itself (`char(0)`, a BLOB cast to text) still stores one on SQLite, while Postgres refuses to build it, and the move to Postgres refuses such a row; a plugin keeps binary data as a BLOB instead. Rows an older TREK stored in a plugin's SQLite file with a NUL are still read as they are. TREK's own data holds no NUL on either engine.
+- **No transaction control in plugin SQL, on either engine.** Every plugin call runs in a transaction of its own and `tx()` makes a batch atomic, so `BEGIN`, `START`, `COMMIT`, `END`, `ROLLBACK`, `ABORT`, `SAVEPOINT` and `RELEASE` are refused in every statement of a query, an exec script, a tx batch or a migration, with the same error on SQLite and Postgres and in `trek-plugin dev`.
- **A plugin writes Postgres SQL** on a Postgres install, not SQLite SQL. TREK does not translate it. A plugin written for SQLite only fails its `db:own` calls with the database's error; ask its author for Postgres support (`ctx.db.engine()` tells a plugin which engine it runs on).
- **Plugin calls share TREK's pool**, at most half of `TREK_DB_POOL_MAX` at once, one at a time per plugin. Each call takes a connection of its own from the pool for its transaction and gives it back when it ends.
- **Uninstalling a plugin with "delete data"** drops its schema.
diff --git a/wiki/Troubleshooting.md b/wiki/Troubleshooting.md
index 18e4b36b2..c97e97109 100644
--- a/wiki/Troubleshooting.md
+++ b/wiki/Troubleshooting.md
@@ -696,7 +696,7 @@ See [Notifications](Notifications#web-push) for the details.
## Postgres: a restore is refused because of the database role
-**Cause:** `TREK_DB_URL` connects as a superuser, or as a role that holds `pg_execute_server_program` or `pg_write_server_files`. A backup is a SQL script that runs as this role, so TREK refuses to restore it with a role that could run commands or write files on the database server. TREK also logs a warning about such a role at startup.
+**Cause:** `TREK_DB_URL` connects as a role that could reach the database server from SQL: a superuser or a member of one, a role that holds `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files` or may run a server file function such as `lo_export`, from PostgreSQL 15 on a role granted ALTER SYSTEM or a superuser-only setting, or on PostgreSQL 14 and 15 a role with CREATEROLE or a member of one. A backup is a SQL script that runs as this role, so TREK refuses to restore it with a role that could run commands or read or write files on the database server. Plugin databases (`db:own`) are refused for the same roles. TREK also logs a warning about such a role at startup.
**Fix:** Connect TREK as a role that owns its database and is not a superuser. See [Database-Postgres](Database-Postgres#a-role-that-is-not-a-superuser), which also shows how to move an install made with an older `docker-compose.postgres.yml`.