Files
TREK/server/src/nest/README.md
T
jubnl de8caa81a2 Feat/orm : mikroorm (#2416)
* base entities

* update deps

* fix date as string

* rename entities

* migrations + seeders

* feat(db): DbTimestampType keeps DATETIME columns as the CURRENT_TIMESTAMP text

* feat(db): discover entities from an explicit list instead of a glob

* test(db): createTestOrm binds an ORM to a suite's own SQLite handle

* feat(db): dialect helper is the one place SQL functions are spelled

* test(db): dialect helper refuses malformed column references and day counts

* feat(db): snake_case entity shape and the first three repositories (Days, DayNotes, Trips)

* fix(db): repositories mirror the statement's column set and guard their row types

* feat(db): request-context and unit-of-work helpers for the ORM, with concurrency tests

* test(server): integration suites boot on the migrated schema snapshot

* test(server): snapshot harness keeps the legacy id semantics

* fix(test): route MikroORM's dynamic imports through vitest from the setup file, not the ORM config

* test(db): coverage ratchet entries for the ORM foundation

* test(server): websocket suites boot on the migrated schema snapshot

* test(server): coverage's uncovered-file pass goes through the SWC transform

* fix(db): dialect helpers dispatch on the platform; lint gate for the repository layer

* test(server): ORM suites open the schema snapshot; RESET_TABLES derived from the schema

* chore(server): promise safety net and sweep tooling for the async migration

* refactor(realtime, systemNotices, addons, airports, audit, categories, permissions, query-helpers, tags, transit, trip-membership): async DB-touching methods; transactions through UnitOfWork

* fix(server): observe every promise the async sweep left unobserved (timer, handshake, plugin-runtime test)

* test(doc-sync): unit suites await the methods the async sweep made async

* refactor(atlas, school-holidays, settings): async DB-touching methods; transactions through UnitOfWork

* chore(server): lint rule refusing a Promise used as a plain value, and the misses it found

* test(server): suites await the methods Task 1's forced edits made async

* refactor(budget, common, day-notes, days): async DB-touching methods; transactions through UnitOfWork

* test(oauth): controller suite awaits the async service

* chore(server): db-call-graph --unawaited lists calls to async methods whose result is used without await

* refactor(llm-parse, mcp-shared, oauth, place-shadow, route-usage, storage, todo, trip-invite): async DB-touching methods; transactions through UnitOfWork

* refactor(plugins): async DB-touching methods; transactions through UnitOfWork

* chore(server): db-call-graph --sync stops its transitive walk at an async callee

* chore(plugins): drop gate-only asyncs; observe the scheduler's rejection; async event-sink stub

* refactor(notifications, place-photos, backup): async DB-touching methods; transactions through UnitOfWork

* refactor(auth, files): async DB-touching methods; transactions through UnitOfWork

* test(server): suites await the methods earlier sweep groups made async

* refactor(tokens): async DB-touching methods; the auth token handlers await them

* test(files): upload filters fail closed on an excluded or unresolvable type

* refactor(collab, collections, maps): async DB-touching methods; transactions through UnitOfWork

* refactor(memories, photos, packing, share): async DB-touching methods; transactions through UnitOfWork

* chore(server): lint rule also refuses a Promise handed to expect() without resolves/rejects

* refactor(vacay, admin, doc-sync): async DB-touching methods; transactions through UnitOfWork

* fix(vacay): type the loop accumulators the async sweep introduced

* refactor(journey, oidc, place-enrichment, tokens, trip-members): async DB-touching methods; transactions through UnitOfWork

* fix(server): the journey hooks are awaited by their callers, not detached

* refactor(assignments, public-api, accommodations, places): async DB-touching methods; transactions through UnitOfWork

* refactor(trips): rewrite AccommodationsService.createAccommodation .bind alias

Recipe R4 trap named in the Task 12 brief: a .bind alias of an
AssignmentsService/AccommodationsService method is typed any and hides a
missing await from tsc and the promise lint rules. createAccommodation
belongs to this task's group, so rewritten as an arrow forwarding to the
method instead of a bound reference.

* refactor(assignments): drop the unused Trip type alias

* refactor(reservations, booking-import, calendar, integrations, roadtrip): async DB-touching methods; transactions through UnitOfWork

* refactor(roadtrip, reservations): return await on transactional; document the single-flight promises

* refactor(trip-read-model, trips, feeds): async DB-touching methods; transactions through UnitOfWork

* refactor(server): remove DatabaseService.transaction — every transaction runs through UnitOfWork

* refactor(trips, feeds): drop added return annotations; no double await on the feed guard

* fix(server): phase 1 review follow-ups — awaited returns, logged upload-filter rejections, covered handshake/notice branches, call-graph gate in CI, dead test imports

* fix(server): upload filters answer multer once on a throwing callback; positive call-graph gate test

* test(db): entity metadata must match the migrated schema; fix the four drifts it found

* feat(db): primary-relation entities proven (BudgetCategoryOrder, VacayUserSettings)

* test(db): parity gate also holds declared pivot entities; per-field column types; missing-set ratchets both ways

* test(db): numeric ids for the primary-relation spike

* feat(db): re-runnable entity generator encoding the snake_case/DbTimestampType rules

* fix(db): generator guard rails — validation cannot mask hidden()/index loss; typed JSON; loud failures

* fix(db): generator keeps NOT NULL boolean defaults; fails if a JSON interface import survives

* refactor(db): every entity in the snake_case shape; document-sync entities added; one repository per entity

* fix(db): no NaN class-field initialisers; entity generator --check gate in CI; parity normaliser keeps literal case

* chore(db): entity --check reports stray files; class-field census is a ratchet; migrate-encryption typechecked

* feat(db): AppSettings and Users repositories; forFeature wiring pattern

* refactor(permissions): permission flags through AppSettingsRepository

* fix(server): boot-time settings read runs inside an explicit ORM request context

* refactor(audit): audit log writes through AuditLogRepository

* fix(db): PK reads refresh past the identity map; typed owned-lookup generics; e2e ORM module mirrors production config

* docs(db): owned-lookup call-site convention; refresh side effect; e2e ORM module spread notes

* fix(audit): audit rows are native inserts, not a unit-of-work flush; closed test ORMs

* fix(server): non-HTTP entrypoints run inside an ORM request context; permission loads fail closed on context errors

* refactor(categories, tags): repositories replace raw SQL

* refactor(addons): addon catalog and photo providers through repositories

* fix(db): generator captures inline UNIQUE constraints

SqliteSchemaHelper.getIndexes() drops every unnamed sqlite_autoindex_
entry before entity-generator ever sees it, so a table-level
UNIQUE(...) constraint with no separate named CREATE UNIQUE INDEX
(settings' UNIQUE(user_id, key) among ~40 others) never reached the
generated entity's uniques: metadata. Adds a general
RULE9_addImplicitUniqueConstraints (skips a column set identical to
the table's own primary key — AppSettings.key/Addons.id noise) fed by
a PRAGMA index_list/index_info scan, and regenerates every entity.

* chore(addons): well-known gate wraps only the addon read in a request context; drop unused test factories

* fix(platform): well-known gate tolerates a synchronous addon read from the context helper

* fix(db): PK lookups inside patch refresh past the identity map; corrected identity-map notes

* refactor(settings): user and instance settings through repositories

SettingsRepository (getForUser/upsertForUser/getOne/deleteForUser) replaces
the per-user settings table's raw SQL; SettingsService drops DatabaseService
entirely. instance-api-keys.ts's readInstanceApiKey/writeInstanceApiKey/
resolveApiKey take an explicit AppSettingsRepository/UsersRepository instead
of a raw connection.

An earlier version resolved those two repositories itself from the active
MikroORM request context, so none of its six callers needed to change. That
worked in production and e2e (always inside a real request) but broke
service construction in plain unit tests across every calling domain
(addons, auth x2, maps, transit, unsplash - 185 failures on a full run),
since none of them wrap a request context. Each of those six services now
injects its own AppSettingsRepository/UsersRepository and passes them
through explicitly, matching how every other converted repository in this
migration is consumed; their own SQL is untouched (outside Plan 3a).

* test(server): harness constructors follow the Task 5 repository signatures; one test ORM per handle in the plugin host

* fix(db): generator names relation properties in captured UNIQUE constraints

* fix(settings): drop dead wiring and the speculative deleteForUser; strict row assertions

* fix(server): plan 3a review follow-ups — fail closed without an ORM at every choke point; seam and D5 ratchet tests; dead method and DDL copies removed

* fix(server): plan 3a re-review follow-ups — plugin boot activation and the airports backfill inside a request context; the supervisor answers the child before failing closed; BOOT-SWEEP-001 drives the real boot hooks; ws adapter seam pinned

* feat(db): generated entities declare their repository type; test casts dropped

* fix(server): plan 3a re-review 2 follow-ups — absent-ORM boot branch pinned; airports boot hook never rejects; BOOT-SWEEP-001 asserts the seven routes; duplicate comment removed

* feat(server): pre-init photo route and WS handshake run in a request context; InviteTokensRepository

* refactor(auth): users table through UsersRepository; JWT and MFA lookups repository-backed

* refactor(tokens): MCP and API tokens through McpTokensRepository

* refactor(auth): passkeys and registration invites through repositories

* fix(db): row-out repository reads bypass the identity map — stale write-back over nativeUpdate at flush; insertUser via em.insert; settings round-trip pinned

* fix(server): non-numeric route ids answer the legacy not-found, never NaN (tokens, categories, tags); mint path back to two statements; identity-map regression pinned

* refactor(oauth): OAuth server tables through repositories

OauthClientsRepository/OauthTokensRepository/OauthConsentsRepository
replace OauthService's raw SQL (OA1-OA33). revokeChain's recursive CTE
and the oauth_clients join (its FK actually targets client_id, not the
row id the generated relation assumes) go through em.getKysely();
OA19's chain revoke is one nativeUpdate($in); OA12's consent grant is
em.upsert on the (client, user) unique key. revokeAllForUser built now
for Task 5. Every row-out read is disableIdentityMap: true; inserts go
through em.insert.

* fix(auth): non-numeric passkey and invite ids answer the legacy 404, never NaN; invite join type pinned

* fix(db): generator emits the referenced column for non-PK foreign keys; OAuth client joins through the relation; FK parity un-skipped

* refactor(db): TrekRepository base — every repository path validates the request context and reads bypass the identity map by default

* refactor(auth): AuthService and account cleanup through repositories

* refactor(oidc): OIDC identities and settings through repositories

* fix(auth): invite validation keeps expires_at null on the wire; password transaction scopes and reset-token burn pinned

* fix(server): plan 3b close-out — case folding on both sides for identifier lookups (non-ASCII login regression); coverage ratchet restored; repository scaffold and instanceof ratchet on TrekRepository; D-shape tests load-bearing

* refactor(server): trip-access primitives async at every caller

* refactor(trips): trip access through TripsRepository; demo seed in a request context; dialect helpers for the trips cluster

* refactor(days): days and day notes through repositories

* refactor(assignments): day assignments through repositories

* refactor(server): trip-membership, place-shadow, place-enrichment, place-photos and query helpers through repositories

* refactor(trip-members): membership, guests and the trip read model through repositories

* refactor(places): places, tags, ratings and place images through repositories

* fix(server): place-shadow source counts ordered in SQL; identity-map ratchets load-bearing; photo-cache race pinned

* refactor(places): import paths through repositories

* refactor(trips): trips through repositories

* fix(server): trip ids parsed once at the gate for places and assignments; NUL-safe value quoting on the SQLite platform; places parity tests completed

* refactor(trips): trip copy through repositories for the owned tables

* fix(server): plan 3c close-out — non-finite ids bound as NULL, trip id parsed once at every places/days/ws gate

Platform: NulSafeSqlitePlatform now renders a bound NaN as NULL and
+/-Infinity as 9e999/-9e999, matching better-sqlite3's own legacy binding
(rule 22 extension) — the program-wide fail-safe for any caller that still
passes an unguarded Number(untrusted) into a converted statement.

PlacesService.verifyTripAccess and RealtimeGateway.handleJoin stop doing
that: verifyTripAccess parses once with toRowId and threads the parsed id
through create/import/bulk/rating/export.gpx (deleting the seven
toRowId(tripId) ?? -1 sites), and handleJoin gets a Number.isFinite guard.
DaysService gets the same treatment across list/create/getDay/reorder/
insert/resyncAccommodationDays, closing the gap where a hex-spelled trip id
could renumber a real trip's days while the raw-bind inverted-accommodation
guard silently matched nothing.

DatabaseService.getTripTitle is deleted; PlacesService injects
TripsRepository directly and calls getTitle itself.

Template/cheap-item cleanup: DayAssignmentsRepository.listForTimeSort uses
$castTo instead of an unknown bridge; the duplicated TagRow interface in
Places.repository.ts is now imported from Tags.repository.ts;
AssignmentWithPlaceRow extends the guarded DayAssignmentRow instead of
restating its columns; PlaceShadowPicksRepository.totals drops its
unreachable ??-fallback branch; Places.repository.ts's updatePlace types
the NOT NULL name column as string; trip-members.service.ts's
transferOwnership threads one parsed trip id through all three writes and
corrects two stale "raw-bind seam" docstrings that were actually Number()
seams; a dead canAccessTrip mock is removed from reservations.e2e.test.ts.

Tests: the 23 new no-explicit-any warnings in TRIP-SVC-069 are typed
(lint back to 2416); HTTP and WS regression coverage for the non-finite
and non-canonical id shapes across places/days routes, mutation-proved;
TRIP-JOIN-005 asserts the exact concurrent-join settlement instead of
>= 1; a new tests/unit/db/transaction-yield.test.ts pins rule 24's
measured transaction-yield/dirty-read/nested-BEGIN behaviour.

* test(server): plan 3c close-out — copy-source full-row parity, Kysely rollback proofs, identity-map relabels, trips e2e on the snapshot DB

* fix(server): plan 3c close-out — days create/insert answer the guard 404 for non-canonical trip ids instead of 500; exact settlement and cross-request yield ratchets

* feat(server): plan 3d groundwork — dialect helpers, visibility predicate, feed and cron context ratchets

* refactor(roadtrip): roadtrip tables through repositories

* refactor(reservations): reservations, endpoints and travelers through repositories

* refactor(feeds): ICS feed tokens and anonymous feeds through repositories

* refactor(accommodations): stays through repositories inside the existing transactions

* test(server): plan 3d — MCP test helper constructors follow the accommodations and days services

* refactor(trips): trip copy through repositories for the roadtrip, accommodation and reservation tables

* refactor(calendar): calendar reads and reservation visibility through one predicate

* feat(server): plan 3e groundwork — packing visibility predicate, memories access-gate audit

* fix(server): plan 3d close-out — legacy text shape for stored accommodation ids restores the date-change restamp; reservation ids parsed once at the gate; parity tests for the reservation repositories

* refactor(photos): trek photos, memories access and cache sweeps through repositories

* refactor(files): trip files and file links through repositories, with transactions added

* test(server): plan 3e — hand-built FilesService, FilesRpc and AllowedFileTypesService calls follow the repository constructors

* refactor(memories): unified, immich and synology photo sync through repositories

* refactor(collab): notes, polls, messages and links through repositories

* refactor(budget): budget items, members, payers and settlements through repositories

* refactor(todo): todo items through repositories

* refactor(packing): packing items, bags and templates through repositories

* feat(server): plan 3f groundwork — systemNotices DI shape, TRAVELER_OWNS predicate, ntfy/storage-health specs, composite-PK pins

* refactor(school-holidays): country and region catalog through repositories

* refactor(notifications): in-app notifications and channel preferences through repositories

* refactor(notifications): reminder crons, mailer, ntfy and webhook transports through repositories

* fix(server): plan 3e close-out — repository registrations restore the boot; packing assignee and bag updates parse and no-op as legacy; coverage and scoping ratchets for the budget, packing and collab repositories

* refactor(vacay): vacation plans, entries, shares and holiday calendars through repositories

* refactor(system-notices): notice dismissals through a Nest provider and repository

* refactor(atlas): visited countries, regions and bucket list through repositories

* feat(server): plan 3g groundwork — GALLERY_CHRONOLOGICAL_ORDER Kysely ordering, unixEpochToIsoKysely helper, composite-PK DDL pins, JB5/R7 confirmations

* refactor(journey): journey and trip access control, CRUD and the trip-sync engine through repositories

* feat(server): plan 3h groundwork — date-offset dialect helpers, entity/repository fitness confirmations, pre-init and encryption pattern confirmations, survivor re-grep

* fix(server): plan 3f close-out — ntfy operator-scope test on the live send path; vacay date-offset and shift-order parity; todo reminder window; coverage and parity ratchets for the atlas and vacay repositories

* refactor(journey): journey stats, entries, photos, contributors and suggestions through repositories

* refactor(journey): public share links, TREK Studio books and the journal facades through repositories

* refactor(collections): access model, hydration, export/import and list CRUD through repositories

* refactor(server): journey-table survivors in trips, photos, memories, auth-cleanup and plugin-contributions through repositories

* refactor(integrations): dawarich connection, sync, tracks and review-flow through repositories

* refactor(collections): saved places, copy-to-trip, labels and invitations through repositories

* refactor(integrations,booking-import,airports,maps,route-usage): airtrail, booking import, airport backfill, maps cache and route-usage counters through repositories

* refactor(doc-sync): connections, reconciler and controller-SQL relocation through repositories

* test(integrations): add AirTrail saveSettings tx-asymmetry ratchet (Plan 3h Task 4 addendum)

* fix(server): plan 3g close-out — transactional book first-save, skeleton reconcile and share-link create; unknown-key entry patches are no-ops again; parity and authorization pins for the journey repositories

* feat(server): plan 3i groundwork — AuditLogRepository's reserved methods, the demo connection-swap spike, repository-fitness confirmations

* feat(server): plan 3j groundwork — scheduler onto CronRegistrarService, SDK-contract confirmation, repository fitness

* refactor(storage): backend/category config and usage stats through AppSettingsRepository; fix the seed-file test race and the shared-replica migration-flip gap

* refactor(share): public share links, the pre-init photo fallback, and collection-places survivors through repositories

* feat(server): plan 3j — the withCamelCase utility, unwired, pending a contract decision

* refactor(admin): user CRUD, stats, audit log, version check and addon config through repositories

* test(admin): pin createUser's pre-existing non-transactional uniqueness-check race (AD2-4)

* refactor(plugins): the trip-write role gate through a repository, in isolation

* refactor(demo,backup): seed and reset through DemoRepository, live-connection backup statements through MaintenanceRepository, isDemoUserId through an injected DemoService

* fix(server): plan 3h close-out — new-value-wins COALESCE restores stay/reservation propagation; doc-sync state filter truthiness; request-context and parity ratchets for share, doc-sync and the integrations

* refactor(plugins): runtime lifecycle, config CRUD and the uninstall cascade through repositories

* fix(server): plan 3i close-out — DemoModule imported where its service is consumed (e2e restored); admin addons list selects the provider relation; saveDemoBaseline awaited; backup tests on the maintenance repository

* refactor(plugins): outbound OAuth tokens and per-user plugin settings through repositories

* refactor(plugins): install-time gates, the capability-audit hash chain and the registry through repositories

* refactor(plugins): contribution-hook controllers, the small plugin controllers and the plugins-table survivors through repositories

* test(server): plan 4 — collapse mcp tool test harnesses onto the ORM snapshot

* test(server): plan 4 — collapse nest service test harnesses onto the ORM snapshot

* fix(server): plan 3j close-out — serialized audit-chain appends, atomic metadata and scheduler limits, rollback and race proofs for the plugin repositories

* refactor(server): plan 4 — convert the program's orphaned raw-SQL callers

* fix(server): plan 4 — un-skip PARITY-009 (FK deleteRule and index-name parity)

* refactor(server): plan 4 — inline canAccessTrip/isOwner off DatabaseService (trip-domain services)

* refactor(server): plan 4 — inline canAccessTrip/isOwner off DatabaseService (plugins + MCP surfaces)

* fix(server): plan 4 — RULE12 paren-count scanner ignores string literals

The entity generator's RULE12_fixGarbledCheckExpressions CHECK-expression
paren-balance scanner counted every `(`/`)` character regardless of
whether it fell inside a single-quoted SQL string literal. A CHECK
expression like `status IN ('confirmed)', 'tentative')` has a literal `)`
inside its first string value; the scanner would hit depth 0 at that
in-string character and truncate the expression, losing its own real
closing paren. The scanner now tracks single-quote string state (handling
the doubled `''` SQLite escape) and skips parens while inside one.

Latent-bug fix — no shipped entity's CHECK expression has hit this shape
yet (3d's ledger: "nothing affected today").

* refactor(server): plan 4 — unify the trip-access predicate's Kysely copies

TripsRepository.findForViewer/listForUser/activeTrip each hand-wrote the
identical trip-access boolean (t.user_id = ? OR m.user_id IS NOT NULL)
through the Kysely expression builder. Task 7's security review (M1)
evaluated a shared helper and set it aside for time, falling back to the
TRIPREPO-041 cross-method parity test as a regression guard instead.

Extracted the boolean into one generic helper, tripAccessExpr
(_shared/trip-access.ts), following the reservation-visibility.ts
publicReservationExpr precedent: fully generic over <DB, TB> since the
predicate has no correlated subquery, so it composes across
TripSelectKyselyDB and ActiveTripKyselyDB without needing a narrower
fixed-alias shape. The LEFT JOIN itself stays hand-written at each call
site — tripSelectQuery's own docstring already explains why a shared join
helper can't be typed across these differently-joined outer queries.

feeds.service.ts and memories-access.service.ts no longer duplicate this
predicate at all (Task 2's facade-inline sweep already converted both onto
TripsRepository.findAccessible/getFeedTokenIfReachable/
listReachableActiveTrips, which read through the canonical MikroORM
QueryBuilder form, accessibleTripsQuery) — the remaining duplication this
task closes is the three Kysely copies inside this file.

TRIPREPO-041 (64/64 in the file) stays green as the unification's own
regression guard.

* fix(server): plan 4 — trek_photo_cache_meta.cache_key NOT NULL

The column was a bare TEXT PRIMARY KEY, which SQLite does not implicitly
make NOT NULL (unlike an INTEGER PRIMARY KEY rowid alias). Every writer
(TrekPhotoCacheMetaRepository.upsertMeta, the table's only INSERT path)
has always bound a real string — 3e's R5 confirmed this. Appends a new
migration rebuilding the table with cache_key NOT NULL (SQLite has no
ALTER COLUMN, so this follows the same rebuild recipe
Migration20200101020000 uses in the opposite direction) and updates the
entity/generated metadata to match. Schema tightening, not a behaviour
change.

* refactor(server): plan 4 — retire the safely-convertible string-form where conditions (rule 23)

Places.repository.ts's existsInTrip/findInTrip/findRaw/reclaimInputs/
listByTripAndIds and Trips.repository.ts's findPublicForShare all took a
raw `.where('col = ?', [v])` string condition even though their id/trip_id
parameters were already plain `number` (or, for findPublicForShare,
narrowed to `number` here after confirming its one caller,
share.service.ts#getSharedTripData, only ever passes a number sourced
from a Kysely-typed share_tokens row, never an unconverted URL param) —
converted all six to MikroORM's typed `.where({...})` filter object.

The remaining raw string-form conditions in src/db/repositories/** are
NOT converted here: they are the `number | string` raw-bind seam
findAccessible/isOwner's own docstrings describe (trip_id/id threaded
through unconverted from req.params), which structurally requires the
deferred guard-level single toRowId parse to land first — narrowing any
of those methods' signatures now would either break the '0x10'/'007' id
parity those docstrings warn about, or duplicate the deferred item's own
work ahead of it landing.

* refactor(server): plan 4 — trek-photos.repository.ts finishes its rename

3e Task 6 renamed the CLASS (TrekPhotosRepository -> TrekPhotoRegistrationService,
since the name collided with the generated ORM TrekPhotos.repository.ts) but
left the FILE and its test file's names unchanged. Renames both to
trek-photo-registration.service.ts / .test.ts.

The old path is kept as a thin re-export stub (the src/websocket.ts shape)
rather than repointed at every one of its ~20 importers in this pass: several
of those files sit in two sibling tasks' exclusively-owned windows on this
shared branch (Task 3's budget/packing/todo/accommodations/places ripple,
reached through tests/helpers/plugin-host.ts and mcp-test-controllers.ts;
Task 5c's held-back tests/unit/services/{trekPhotoMedia,conflictUpdate}.test.ts)
and are off limits here. Flagged for a follow-up once those tasks land: delete
the stub and repoint every remaining importer at ./trek-photo-registration.service.

* fix(server): plan 4 — plugin discovery's delete+reinsert pairs are atomic

install/discovery.ts#upsert refreshed a plugin's actions and settings-field
descriptors as two independent delete-then-reinsert pairs (DI5-DI8) with no
transaction spanning either pair, let alone both: a crash between a delete
and its own reinsert left that plugin with an EMPTY actions or
settings-field set until the next discovery run, instead of its previous
still-valid rows. Wraps both pairs in one uow.transactional, so a discovery
refresh for a plugin's descriptors is now all-or-nothing.

Deliberate behaviour change, named for the user per the task brief.

DiscoveryRepos grows a UnitOfWork; PluginRegistryService (the other
production caller, registry.service.ts) picks it up the same @Optional()
way PluginRuntimeService already does, with the same guard-throw. Updates
the two hand-constructed test call sites that actually exercise discovery
(discovery.test.ts, registry.test.ts) to pass a real UnitOfWork.

* refactor(server): plan 4 — facade inline sweep part B (rosterUserIds/getPlaceWithTags)

Inline DatabaseService.rosterUserIds onto TripMembersRepository.rosterUserIds
directly in budget.service.ts, budget.mcp.ts and todo.service.ts, and
DatabaseService.getPlaceWithTags onto PlacesRepository.findWithTagsAndRatings
in accommodations.service.ts (placesRepo was already injected there).

BudgetService/BudgetMcp/TodoService collapse their constructors, dropping
the now-fully-unused DatabaseService param (budget.module.ts/todo.module.ts
register TripMembers on forFeature). PackingService keeps DatabaseService as
a vestigial param behind an optional TripMembersRepository with a fallback
in tripRosterIds: an in-flight Task 5c file
(tests/unit/services/conflictUpdate.test.ts) hand-constructs PackingService
positionally without the new repository, so its arity cannot change this
task; the fallback keeps that file's DatabaseService.rosterUserIds spy
working until Task 4 drops the param with the class itself.

* test(server): plan 4 — constructor ripple for the rosterUserIds/getPlaceWithTags inline

Hand-built BudgetService/BudgetMcp/TodoService call sites drop the removed
DatabaseService constructor arg (budgetRepoArgs() now appends a
TripMembersRepository so most spread call sites need no other change);
budget.service.test.ts's rosterHas() helper and svc() factory move from a
spied DatabaseService to a stubbed TripMembersRepository. The
AccommodationsService helper (tests/helpers/accommodations-service.ts) and
its two direct callers drop the same arg. PackingService call sites are
untouched (its new param is optional, so every existing hand-built instance
still resolves rosterUserIds through the DatabaseService fallback).

* fix(server): plan 4 — thread the discovery UnitOfWork through PluginRuntimeService too

Complements the just-landed discovery atomicity fix (DiscoveryRepos.uow):
PluginRuntimeService's own discoveryRepos getter still built the bundle
without a uow field. Threads its already-injected, @Optional() uow through
so its own onApplicationBootstrap/reload/dev-link discovery calls also get
the transactional DI5-DI8 refresh, not just PluginRegistryService's.

No throwing guard here, unlike PluginRegistryService's: several hand-built
partial-DI-graph test instances of this class (boot-registry-order.test.ts,
in a sibling task's held file window) construct it with uow omitted and
exercise onApplicationBootstrap's discovery call directly. Discovery must
never refuse outright just because a test built a partial graph, so it
degrades to the pre-existing untransacted sequence when uow is absent
(DiscoveryRepos.uow's own docstring covers this), the same "boot must
never block app init" defensiveness this file already applies elsewhere.

* fix(server): plan 4 — guard-level single parse: verify + correct the overclaiming verifyTripAccess docstring (L-2)

TripAccessGuard/TripOwnerGuard already parse :tripId exactly once
(Number(), guarded by Number.isFinite) and hand the resolved TripAccess
row to the handler via request[TRIP_REQUEST_KEY], TripOwnerGuard reusing
TripAccessGuard's own lookup when both are on the same route rather than
re-querying — verified by reading both guards directly, no change needed
there.

PlacesService.verifyTripAccess's own docstring separately claimed its
returned `tid` gets "returned... for every downstream call to reuse
(never re-parsing)" (3c's Task 9 review, L-2, carried to Plan 4). Reading
every call site (not assumed) shows this is false: `.tid` has exactly one
reader (PlacesController.requireTrip itself), which discards it — none of
requireTrip's 13 callers read `.tid` off the trip it returns; each passes
the original raw tripId string on to the write/read method it calls next,
which toRowId-parses it again itself. That second parse cannot be
eliminated by this gate alone: the same service methods are called
directly by places.mcp.ts too, an entry point with no requireTrip gate at
all (its own numeric tripId is re-stringified, String(tripId), to call
them), so each method owns its own id validation regardless of entry
point. Threading `tid` all the way through would mean giving every one of
~15 methods a second, number-only call shape for the REST path alone to
use — a real refactor, out of this docstring fix's own scope. Corrected
the docstring to say so plainly instead of repeating the false claim.

* refactor(server): plan 4 — relocate JS7/10/13/14 off the journey-share fallback stub

JourneyShareTokensRepository's own JS7/JS10/JS13/JS14 Kysely reads were a
3g Task 3 fallback (Task 2's JourneyPhotosRepository/JourneyEntriesRepository/
JourneyEntryPhotosRepository were still mid-flight). Now that those
repositories are stable, relocate: JS7/JS10 (photo/asset validation joins)
onto JourneyPhotosRepository (already injected into JourneyShareService as
photosRepo, no constructor change); JS13 (public entry list) onto
JourneyEntriesRepository.listPublicEntries; JS14 (public per-entry photo
read) onto JourneyEntryPhotosRepository.listForPublicJourney, deduped
against that repository's own JP_COLUMNS select list instead of a
hand-duplicated copy. JourneyShareService gains two new @InjectRepository
params (both already registered in journey-domain.module.ts's forFeature),
rippled through mcp-test-controllers.ts and journey-share.service.test.ts
(P04/P05 parity tests now pin the new homes).

* refactor(server): plan 4 — document unreachable ?? default arms after single-row aggregates

3f Task 7's fix wave flagged a cluster of `row?.x ?? default` arms after
unqualified, ungrouped aggregate reads (MAX/COUNT/COALESCE(SUM,0)) as
"same class as OauthClients:147" but left them unexamined per-site. Decided
per site: document, don't delete — TypeScript still types
executeTakeFirst()'s result as `| undefined` even though SQL guarantees
exactly one row for these unqualified aggregates, so the optional chain
can't be removed without a non-null assertion (worse, not safer). Six
sites: JourneyEntries.repository.ts (maxSortOrderForDate JG42,
countStatsPlaces JG67), JourneyEntryPhotos.repository.ts
(maxSortOrderForEntry JG91), JourneyPhotos.repository.ts (maxSortOrder
JG88/JG99), VacayEntries.repository.ts (sumFraction VC1, sumCompFraction
VC2). No behavior change — comments only.

* refactor(server): plan 4 — unify the two user-data-erasure enqueue paths

UserCleanupService.erasePluginUserData (the account-deletion transaction's
own UC2/UC3 enqueue) and PluginRuntimeService.enqueueUserErasure (the
emitUserDeleted sink's post-commit enqueue) independently walked the
identical SELECT id, permissions FROM plugins + JSON.parse + hook:user-data
filter + INSERT OR IGNORE — and both genuinely run for every account
deletion, since every emitUserDeleted call site (auth.service.ts,
admin.service.ts, trip-members.service.ts's guest removal) fires
immediately after deleteUserCompletely.

Extracted the shared filter into enqueueHookUserDataErasures
(nest/plugins/user-erasure-enqueue.ts) and pointed both call sites at it.
UC2/UC3 also come off DatabaseService onto PluginsRepository/
PluginUserErasureQueueRepository in the same change (they were the last
raw statements standing in the way of sharing one implementation) — this
narrows the Plan 3b Task 5 "stays raw, owned by Plan 3j" ruling to UC1
only (plugin_user_config/plugin_oauth_tokens/plugin_oauth_state), which
still stays raw, unaffected. UserCleanupService's orphan-data-directory
scan (a plugin uninstalled with data retained) has no equivalent on the
enqueueUserErasure side and stays there, now via the same repository.

Both enqueue calls still run per deletion (INSERT OR IGNORE keeps this
idempotent) — this unifies the IMPLEMENTATION, not the call count; not
touching the emitUserDeleted event-sink wiring itself was a deliberate,
smaller-blast-radius choice for this task.

* refactor(server): plan 4 — narrow TripMembersRepository.remove/TripsRepository.setOwner to number

Both accepted trip_id: number | string per 3c's carry note (their "stays
loose for other callers" reasoning), pending the guard-level single parse
landing first. Re-checked every caller directly: setOwner's one production
caller (trip-members.service.ts#transferOwnership) already passes trip.id,
a real number resolved earlier in the same transaction; remove's callers
are trips.rpc.ts (num(), already a validated number), trips.mcp.ts (Zod-
typed tool input, already a number) and TripMembersController.removeMember
(the one genuine raw-string caller, :id off the route with no class-level
TripAccessGuard on this controller by design).

TripMembersController.removeMember now parses :id once (toRowId, not
Number() — rule 15's NaN-into-SQL trap) and threads the parsed number to
both its own access check and removeMember, instead of passing the raw
string through twice. TripMembersService.removeMember and both repository
methods narrow to number accordingly; setOwner's WHERE also moves off its
raw-bind escape hatch onto nativeUpdate now that trip_id is typed, and
remove's trip_id half moves onto a typed .where({ trip: trip_id }) filter
(user_id keeps its own raw bind — a different, still-live NaN-safety seam,
unrelated to this narrowing).

TRIPREPO-018 and TMEMREPO-023, which pinned the retired string-bind seam
on setOwner/remove, no longer typecheck against the narrowed signatures
and are removed with an explanatory comment in their place.

* refactor(server): plan 4 — U6 gate-level id parsing for todo item ids

Rule 21's carry from 3e Task 8's review: TodoController.update/.remove
passed the raw :id route string all the way to TodoItemsRepository,
relying on SQLite's column-affinity CAST to match it instead of a typed
filter. Parse :id ONCE at the controller (toRowId, matching Task 8a's
TripAccessGuard/removeMember shape), 404 on a non-canonical id, and thread
the number down through TodoService.updateItem/deleteItem into
TodoItemsRepository.findInTrip/existsInTrip/update/deleteById, all
narrowed from number | string to number. todo.rpc.ts's num()-derived
todoId no longer needs its String() wrapper. tripId stays string | number
— a separate, already-accepted carry (23c292f2f). Two new e2e tests pin
the non-numeric-id 404 at the gate.

* test(server): plan 4 — full-key parity tests for ShareTokensRepository (3h L4)

3h L4's carry: ShareTokensRepository (SH1-SH6/SH17/UC6) had zero tests.
17 cases pinning every read against the legacy statement run raw on the
same connection — findRawByTrip/findTokenByTrip with every nullable
column both null and set, findValidByToken/findTripAndShareMapByToken/
findTripIdByToken's shared token+expiry predicate (valid, future-expiry,
past-expiry, unknown token), plus insertNew/updateFlagsByTrip/deleteByTrip/
deleteByCreator's write correctness (deleteByCreator's cross-trip erasure
kept distinct from deleteByTrip's single-trip scope, per the repository's
own docstring). The listPublicForShare family (the other half of 3h L4)
is a separate, larger carry — not in this file.

* test(server): plan 4 — full-key parity for Reservations share/public-api reads (3d carry)

Task 8b-2 item 1 (partial): the 8 share.service.ts/public-api.service.ts
reads on ReservationsRepository flagged by the 3d Task 7 review as having
no repository-level toEqual(<legacy raw>) coverage (listEndpointsForShare,
listDayPositionsForShare, listPublicForShare, listPublicAccommodationsForShare,
listScheduledForPublicApi, listUnscheduledForPublicApi,
listAccommodationsForPublicApi, listUnplannedPlacesForPublicApi). 12 new
cases against the legacy statement run raw on the same connection.

* test(server): plan 4 — concurrency pins for boundaries-upsert and token-mint races (3d carry)

Task 8b-2 item 2: R7's two remaining un-transacted-statement races flagged
by the 3d Task 7 review (L4) but never pinned — RoadtripDayBoundariesService
.save's belongs-check-then-upsert, and FeedsService.generateTripToken's
read-then-write. Both tests pin today's actual outcome (an atomic ON
CONFLICT upsert survives cleanly; the token mint has a last-write-wins
loser) with the same concurrent-request-shape Promise.all/allSettled
pattern roadtrip.service.test.ts's existing R7 vias pin uses. Not a fix.

* test(server): plan 4 — full-key parity for Days/DayAssignments/Places roadtrip reads (3d carry)

Task 8b-2 item 1 (remainder): the 3 non-share/public-api reads from the 3d
Task 7 review's missing-parity list — DaysRepository.listPlanDays (RPL1),
DayAssignmentsRepository.listRoadtripVisits (RPL2, the correlated-subquery
LEFT JOIN), and PlacesRepository.isTrackInTrip (RT13, the review's
"findTrackInTrip" — the actual method name). Completes the 11-file carry
together with 434113937's 8 share/public-api reads.

* test(server): plan 4 — dedupe overlapping listPlanDays/isTrackInTrip parity blocks

235f03665 landed two versions of the same DaysRepository.listPlanDays and
PlacesRepository.isTrackInTrip parity coverage side by side (a merge
artifact from concurrent work on the same carry item). Keeps one block per
method, drops the duplicate describe/it blocks and their colliding test ids.

* test(server): plan 4 — budget calc suite onto real repositories (3e carry)

* test(server): plan 4 — at-rest encryption pins for AirTrail/doc-sync/webhook secrets (3h L3)

Task 8b-2 item 4: the three credential columns the 3h Task 7 review flagged
as having no at-rest pin — users.airtrail_api_key (AirtrailService#saveSettings),
document_connections.secrets (DocSyncConfigService's whole-secret-map
column), and trip_document_links.webhook_secret (createLink's per-binding
mint). Each test saves through the real service, reads the raw column via
better-sqlite3, asserts it is enc:v1:-prefixed ciphertext that never
contains the plaintext, and asserts the service's own decrypt path rounds
it back to the original value.

* test(server): plan 4 — at-rest encryption pins for AirTrail/doc-sync secrets (3h L3 carry)

Task 8b-2 item 4: the 3h Task 7 review's L3 finding ("users.airtrail_api_key
has no at-rest pin", "document_connections.secrets ... has no enc:v1: check",
"trip_document_links.webhook_secret - no at-rest pin"). Three targets, each
proven by reading the raw column and asserting the stored value is
enc:v1:-prefixed ciphertext that round-trips, never the plaintext:
UsersRepository.setAirtrailSettingsWithKey/getAirtrailConnRow at the
repository layer, AirtrailService.saveSettings/getAirtrailCredentials at the
service layer, and DocSyncConfigService's connection secrets map plus
createLink's webhook secret.

* test(server): plan 4 — drop duplicate AirTrail encryption repository test

Task 8b-2 item 4 follow-up: 6965869dd already covers
UsersRepository.setAirtrailSettingsWithKey/getAirtrailConnRow's at-rest
ciphertext at the service layer (airtrail.service.test.ts's
AIRTRAIL-SVC-ENC-001/002) plus the doc-sync secrets/webhook pins
(DOCSYNC-ENC-001/002); this repository-level file duplicated the same
AirTrail assertion a second time.

* test(server): plan 4 — atlas read-model parity remainder (3f L6 carry)

Task 8b-2 item 3 (atlas half): full-key toEqual(<legacy raw>) coverage for
the atlas read models the 3f Task 7 review's L6 finding listed as missing
(minus AT1/TRAVELER_OWNS-consumer, already landed) — AT2 (Places.
listForTripIds), AT3/AT28 (PlaceRegions.listCountryCodesForPlaceIds/
listForPlaceIds), AT5/AT10/AT43 (VisitedCountries.listCodesForUser/
listForUser), AT21/AT24/AT25 (VisitedRegions.listForUser/
listRegionCodesForCountry/findCountryCode), AT22 (HiddenRegions.listForUser),
AT23/AT40/AT44 (PlaceRegions.listDistinctRegionCodesForCountryAndPlaces/
countPlacesByCountryForTrip/listVisitedCountryCodesForUser), AT30/33/34
(BucketList.listForUser/findById/findForUser), AT41 (Places.
listAddressesForUser), AT42 (Trips.countTripsAndDaysForUser). New standalone
files for HiddenRegions/VisitedCountries/VisitedRegions/PlaceRegions, which
had none. AT6/45/46 (the TRAVELER_OWNS endpoint reads) are proven on ids
only by the existing consumer test — full-row parity for those three is
NOT done here (carried forward, same as the review's own open item).

* test(server): plan 4 — vacay read-model parity remainder (3f L6 carry)

Task 8b-2 item 3 (vacay half): full-key toEqual(<legacy raw>) coverage for
the vacay read models the 3f Task 7 review's L6 finding listed as missing
(minus VC81/82, already landed) — VacayPlans.findByOwner/findById (the
getPlanData/getStats composite's own plan read), VacayYears.listForPlan
(listYears), VacayCompanyHolidays.listForPlan (the company-holidays list),
VacayHolidayCalendars.listForPlan/findById (holiday-calendar reads),
VacayUserSettings.findForUser (user year settings), VacayUserYears.
findForYear (getStats rows, including the NULL vacation_days case the
review named explicitly), and VacayPlanMembers.listAvailableForFusion/
listPendingForPlan/listPendingForUser (the fusion and share pickers). Seven
new standalone files — only VacayShares had a repository-level test before
this. getSharedCalendars itself is a service-level composite over these
same reads plus VacayCompanyHolidays.listDatesForRange (already exercised
elsewhere); its own dedicated test is NOT added here.

* test(server): plan 4 — full-key parity for PackingItemsRepository.listPublicForShare (3h L4)

Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the share.service.ts SH13 read. Seeds Common items with every nullable
column both null and set, plus Personal and Shared-with-people items on
both sides of the is_private/owner/recipient predicate, and proves only
the Common tier surfaces.

* test(server): plan 4 — full-key parity for BudgetItemsRepository.listPublicForShare (3h L4)

Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the share.service.ts SH14 read. Seeds two items — every nullable column
set and every nullable column null — plus a foreign-trip item, and proves
the ORDER BY category ASC shape (unlike BG72's listAllForTrip, which has
none).

* test(server): plan 4 — full-key parity for CollabMessagesRepository.listPublicForShare (3h L4)

Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the share.service.ts SH16 read. Seeds a root message, a reply (reply_to
set), a deleted message (must be excluded) and a foreign-trip message, and
proves the narrower username/avatar-only join shape (no reply_text/
reply_username, unlike joinedQuery).

* test(server): plan 4 — full-key parity for PlacesRepository.listPublicForShare (3h L4)

Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the share.service.ts SH12 read. Seeds a categorised place with every
nullable column set and an uncategorised place with every nullable column
null, plus a foreign-trip place, and proves the named 20-column allow-list
never leaks an owner-only column (reservation_status, google_place_id,
…).

* test(server): plan 4 — full-key parity for DayAssignmentsRepository.listPublicForShare (3h L4)

Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the SH9 read. Seeds assignments across multiple days (one excluded day_id
never leaks in), every nullable place/assignment column both null and
set, and proves the six owner-only columns SharePublicAssignmentRow omits
(google_place_id, google_ftid, osm_id, amap_poi_id, stop_type,
fill_percent) never appear on the row at all.

* test(server): plan 4 — collapse remaining test harnesses; triage legacy migration tests

* test(server): plan 4 — todo controller test expects the gate-parsed item id (U6 follow-up)

* fix(server): add the missing numbered migration for the booked-night reseat step (#242)

reseatBookedNights (legacy step 242) was never invoked from any shipped
MikroORM migration -- only from the retired db/migrations.ts array --
so an install upgrading through the numbered chain never got the
one-time reorder. Adds Migration20200101040300, which calls the frozen
function through the native better-sqlite3 handle so it runs inside
the migration's own transaction.

orm-driver.ts's BoundSqliteConnection now also captures that handle
onto the field SqliteConnection.getNativeClient() reads, which its
createKyselyDialect() override previously left unset -- needed for
this migration (and any future one) to reach it in production, not
just under the bare test driver.

RESEAT-009 moves off the legacy createTables+runMigrations builder
onto the real Migrator via tests/helpers/migration-step.ts, plus a
new fresh-install guard (RESEAT-011).

* test(server): plan 4 — swap 4 of 5 straggler nest test harnesses off legacy schema builder

day-notes.service.test.ts, public-api-scopes.test.ts,
registration-invites.service.test.ts, trip-invite.service.test.ts onto
createSnapshotTestDb() via the async vi.mock idiom (5a/5b/5c precedent),
dropping their own hand-rolled createTables()+runMigrations() harness.
trip-invite.service.test.ts and registration-invites.service.test.ts
also drop their now-redundant DatabaseService wrapper (its .connection
was always just the same test db handle). expect( assertions unchanged.

user-cleanup.service.test.ts held back: its constructor call was
updated to match UserCleanupService's new EntityManager-based shape,
but deleteUserCompletely() now deadlocks against a real UnitOfWork
(reproduced in isolation, independent of this test file -- see the
report), which looks like a genuine bug in erasePluginUserData's new
MaintenanceRepository(em) call versus UnitOfWork.transactional(), not
a test-harness problem.

* test(server): plan 4 — move auto-backup.test.ts and demo-reset-path.test.ts off createTestDb()

Both build a schema db while 'fs'/'node:fs' are mocked (wholesale in
auto-backup.test.ts, selectively spied in demo-reset-path.test.ts) for
their own archiver/filesystem assertions, which broke
createSnapshotTestDb()'s read of the schema snapshot through
schema-snapshot.ts's own fs import.

auto-backup.test.ts: fs is mocked wholesale, so the snapshot db is now
built via a small helper that points fsMock's three calls at the real
filesystem (fetched through vi.importActual, bypassing the mock) just
long enough to build the db, before the test installs its own
existsSync stub -- never touching schema-snapshot.ts itself.

demo-reset-path.test.ts: fs.existsSync is selectively spied to answer
only for the baseline path, so the db is now built before that spy is
installed instead of after.

* test(server): plan 4 — retire the legacy-runner-only migration hygiene checks

migration-hygiene.test.ts deleted outright: every block in it (the
destructive-op allowlist, the empty-catch guard, the full-chain smoke)
scans or runs the legacy db/migrations.ts array being deleted this
plan, never the numbered src/db/migrations/*.ts chain, so there is
nothing in it to carry forward.

leg-mode-incoming.test.ts: deleted its first describe block (the
legacy-runner column-add + replay-safety smoke, also against
db/migrations.ts); the read-path parity block, already on the modern
createSnapshotTestDb() harness, is untouched.

* chore(server): delete the legacy schema/migration/seed builders

MikroORM's migrations are the only schema source now, including for
tests: src/db/schema.ts, src/db/migrations.ts and src/db/seeds.ts are
gone, along with tests/unit/db/schema-parity.test.ts (the parity gate
that guarded them, already red on 8a's cache_key NOT NULL) and
createTestDb() + its now-dead imports out of tests/helpers/test-db.ts
(its last two callers moved onto createSnapshotTestDb() this plan).
Their three entries drop from eslint.config.mjs's better-sqlite3
allow-list -- the files they exempted no longer exist.

Ruling 7's frozen files (migration-utils.ts, reseat-booked-nights.ts,
document-provider-seed.ts) and every numbered migration in
src/db/migrations/ are untouched.

Precondition grep (server/tests + server/src, from the task brief) is
now empty:

  grep -rlE "from ['\"].*db/schema['\"]|from ['\"].*db/migrations['\"]|from ['\"].*db/seeds['\"]" server/tests server/src --include="*.ts"

* docs: plan 4 — the repository layer is the only data access path

DatabaseService/DatabaseModule are gone; queries go through repositories
(server/src/db/repositories/) and UnitOfWork (server/src/nest/database/
unit-of-work.ts) for transactions. MikroORM's migrations are the only
schema source, including for tests — the hand-kept schema.ts/migrations.ts/
seeds.ts test builders and their parity test are deleted. Documents the
db/database.ts (connection only) / db/orm-driver.ts (bound driver) /
UnitOfWork / repository shape, withRequestContext for non-HTTP entrypoints,
the better-sqlite3 ESLint restriction, and the entity generator (gen:entities/
check:entities) as the schema-parity guard. Corrects two stale nest/README.md
mentions (realtime.gateway.ts's now-repository constructor, the BE-Phase 1
trip-access bullet) and marks the legacy src/services/ migration recipe as a
historical changelog rather than current guidance.

* refactor(server): plan 4 — drop the 13 vestigial DatabaseService params/getters

Removes the now-dead DatabaseService injection (or private get db() getter)
from addons.service.ts, trips.service.ts, trip-invite.mcp.ts,
place-photo-cache.service.ts, trek-photo-registration.service.ts,
categories.mcp.ts, journey-domain.service.ts, plugins.service.ts,
plugin-runtime.service.ts, plugin-mcp-tools.service.ts, places.service.ts
and packing.service.ts — every one of them was fully repository-backed
already (Task 2/3's facade inline sweep), just still carrying the param.

PackingService's TripMembersRepository is required now (the
this.db.rosterUserIds fallback is gone with it) and PluginRuntimeService's
uow is no longer @Optional() — both moved ahead of the optional
registry?/hostFactory? params, since TypeScript refuses a required
parameter after an optional one; install/discovery.ts's DiscoveryRepos.uow
is required to match, and its upsert() always runs the descriptor
refresh inside one transaction instead of falling back to an
un-transacted sequence.

user-cleanup.service.ts's UC1 (the one genuinely live raw site, Plan 3b's
"stays raw" plugin-table trio) moves off DatabaseService onto a new
MaintenanceRepository.deletePluginUserData method — the rule-4-permitted
connection.execute() home, built from a directly-injected EntityManager.
Threads the active UnitOfWork.transactional's transaction context through
execute()'s ctx param: without it, a raw connection.execute() call issued
from inside deleteUserCompletely's open transaction contends for the same
single-connection checkout the transaction already holds and deadlocks
(never released, since the transaction is itself awaiting the call).
tests/unit/db/transaction-yield.test.ts's probe B already pinned this
exact hazard class for a raw better-sqlite3 statement; this is the same
mechanism reached through the ORM's connection pool instead.

nest/photos/trek-photos.repository.ts (the Plan 4 Task 8a re-export shim)
is deleted, with every importer repointed to trek-photo-registration.service
directly. The ~7 files that only imported the TripAccess/PlaceWithTags
type re-export from database.service.ts now import them from
Trips.repository.ts/Places.repository.ts directly, the actual single source.

* refactor(server): plan 4 — delete DatabaseService, DatabaseModule and database.tokens.ts

Grep gate confirmed zero src/ importers of DatabaseService left outside
these three files (Task 1/2/3's earlier conversions + this task's own
vestigial-param sweep). Deletes database.service.ts, database.module.ts
and database.tokens.ts, drops DatabaseModule from app.module.ts's imports
and the five other modules that still listed it
(accommodations/calendar/doc-sync/feeds/trip-members) — none of them had
a live DatabaseService injection left, so the import was already dead.
OrmModule is the module that survives DatabaseModule's deletion, per the
Phase 0 ledger's own ruling; untouched.

db/database.ts's `db` Proxy export itself stays, deliberately: ~190 test
files' vi.mock('…/db/database', …) factories return a { db: <mock
handle>, … } shape, and their own `import { db as testDb } from
'…/db/database'` is typed against this file's real exports regardless of
the runtime mock — vi.mock swaps the module at runtime, but tsc resolves
the import statically. Deleting the export would fail typecheck:tests
across the whole suite for a test-harness idiom this task's file set
doesn't own (Track B's territory). src/ has zero remaining importers, so
the ESLint no-restricted-imports gate this task also shrinks still holds
this file to its permanent allow-list entry either way.

* test(server): plan 4 — repoint the test suite off the deleted DatabaseService/DatabaseModule

Mechanical follow-through of the previous two commits across ~110 test
files:

- The 41 tests/e2e/*.e2e.test.ts suites composed DatabaseModule into their
  partial Test.createTestingModule graphs; the import and the array entry
  are dropped (nothing in any composed domain module injected
  DatabaseService any more, so the entry was already dead weight).
- The shared test helpers (mcp-test-controllers.ts, plugin-host.ts,
  accommodations-service.ts, notifications.ts, test-addons.ts,
  test-uow.ts) each held a DatabaseService/DatabaseService-shaped param
  used only for its raw better-sqlite3 handle; every one now takes that
  handle directly, and every constructor call site the helpers make
  (PackingService, PlacesService, JourneyDomainService,
  PlacePhotoCacheService, TrekPhotoRegistrationService, TripsService,
  UserCleanupService, AddonsService, PluginsService, PluginRuntimeService)
  drops the removed param and, where PluginRuntimeService's uow is
  involved, reorders it ahead of the optional registry?/hostFactory?
  params to match the real constructor.
- ~60 further unit/integration test files hand-constructed one or more of
  those same services directly; same fix, file by file. Four of them
  (memories-access.service.test.ts, places.directions.test.ts,
  places.service.test.ts, unified-memories.service.test.ts) also drop a
  vi.spyOn(DatabaseService.prototype | instance, 'canAccessTrip' | 'isOwner'
  | 'rosterUserIds' | 'getPlaceWithTags') spy left over from when those
  methods delegated through DatabaseService — dead now that the services
  read the owning repository directly.
- database-service.test.ts and database-service.delegation.test.ts tested
  DatabaseService directly and are deleted with it.
- tests/unit/db/transaction-yield.test.ts's probe B, which pinned a raw
  DatabaseService statement's dirty-read behaviour inside an open
  transaction (rule 24), now issues the same raw better-sqlite3
  statement directly against the shared test handle — the exact shape
  DatabaseService.get/run used to wrap (this.conn.prepare(sql).get/run(),
  bypassing MikroORM/Kysely entirely) — so the hazard it documents is
  unchanged. Verified still green.

No expect(...) assertion changed in any file; only construction/import
plumbing. typecheck, typecheck:tests and the full touched-file run
(101 files / 2668 tests) are green, plus the compiled boot
(bootstrap.test.ts + boot-sweeps-request-context.test.ts) and one real
e2e boot file (trips.e2e.test.ts).

tests/unit/nest/user-cleanup.service.test.ts is deliberately NOT in this
commit — see the next one.

* test(server): plan 4 — finish user-cleanup.service.test.ts's harness swap; regression-test the UC1 transactional deadlock fix

This file arrived already modified and unstaged in the shared tree —
Task 6 (the parallel legacy-schema-deletion task) had swapped its DB
harness onto createSnapshotTestDb() and updated the UserCleanupService
construction to this task's new EntityManager-first shape while landing
its own commits. Finished here: USER-CLEANUP-005 ("survives a slim
schema without the plugin tables") passed a fake `{} as unknown as
EntityManager`, which doesn't reach the real UC1 path any more (the
previous raw DatabaseService.run swallowed everything in a try/catch
regardless); it now builds a real EntityManager bound to the slim
handle via sharedTestOrm(slim), so the per-statement query against the
missing plugin_user_config/plugin_oauth_tokens/plugin_oauth_state
tables is what's actually being proven caught, not a construction-time
throw.

USER-CLEANUP-006 through -010 (deleteUserCompletely, all of them
exercising UC1 inside the real uow.transactional wrap) are the
regression test for the previous commit's deadlock fix in
user-cleanup.service.ts/MaintenanceRepository.ts: before that fix, every
one of these hung and timed out. Green now, verified directly.

* chore(server): plan 4 — shrink the better-sqlite3 ESLint allow-list

Per ruling 6: database.service.ts's entry comes off (the file is
deleted). The five plugin entries (plugin-route-normalize.ts,
plugin-host-state.ts, install/discovery.ts, settings-defaults.ts,
signature-status.ts) come off too — re-verified none of the five import
better-sqlite3 or DatabaseService any more (3j's own conversion). The
src/demo/** blanket entry was already gone (3i's own task landed it).

reseat-booked-nights.ts and document-provider-seed.ts stay, with the
`// TODO(plan 4)` comment corrected: they're frozen forever (ruling 7),
invoked from inside numbered, already-shipped MikroORM migrations, never
Plan 4's or any future plan's to touch.

Permanent allow-list after this commit: src/db/database.ts,
src/db/orm-driver.ts, src/db/durability.ts (the driver homes),
src/nest/plugins/host/plugin-data.service.ts (3j's R-out-of-scope — a
plugin's own sqlite file is never TREK's schema), src/nest/backup/backup.impl.ts
(3i's R1, exactly the untrusted-upload-file probe), src/db/reseat-booked-nights.ts
and src/db/document-provider-seed.ts (frozen forever). src/db/{schema,migrations,seeds}.ts
entries were already removed by Task 6 when it deleted those files.

0 new lint errors; warning count unchanged at 2123 (well under the 2247
lean-gate ceiling) — every file the shrink touches was already fully
converted.

* refactor(server): plan 4 — U6 gate-level id parsing for budget item/settlement ids

Rule 21's 3e carry, same discipline 218f75d0f applied to todo: every
:id/:settlementId/:userId route param in BudgetController is parsed ONCE at
the gate with toRowId, matching the legacy affinity-seam "not found" outcome
for a malformed id on each route (404 'Budget item not found'/'Settlement
not found', except toggleMemberPaid — the one legacy handler that never
404'd an unknown item/member either, so a malformed id there skips the write
and keeps the same 200 { member } + Number(id)/Number(userId) broadcast
shape it always had).

The parsed numbers thread down through BudgetService's update/updateMembers/
setPayers/toggleMemberPaid/remove/updateSettlement/deleteSettlement (and
their updateBudgetItem/deleteBudgetItem/setItemPayers/getBudgetItem/
applySettlementUpdate/getSettlement internals) into BudgetItemsRepository's
getCurrency/findInTrip/existsInTrip/findForDelete/findById/update/deleteById
and BudgetSettlementsRepository's findWithUsers/findGuard/update/deleteById,
all narrowed from number | string to number; trip_id stays loose, a
separate, already-accepted carry. costs.rpc.ts's num()-derived itemId no
longer needs its String() wrapper on the update/delete calls; budget.mcp.ts
was already Zod-typed to number throughout. Two new e2e tests pin the
non-numeric-id 404 at the gate; controller/service unit tests cover the
narrowed call args and the toggleMemberPaid malformed-id parity case.

* refactor(server): plan 4 — U6 gate-level id parsing for packing item/bag/template ids

Rule 21's 3e carry, same discipline 218f75d0f applied to todo: every
:id/:bagId/:templateId/:userId route param in PackingController is parsed
ONCE at the gate with toRowId, matching the legacy affinity-seam "not found"
outcome for a malformed id on the routes with a pre-ORM Express precedent
(update/remove -> 'Item not found', updateBag/deleteBag/setBagMembers ->
'Bag not found', applyTemplate -> 'Template not found or empty').

#858's sharing/contributors routes (setSharing/clone/addContributor/
removeContributor) are native Nest code with no pre-ORM precedent (landed in
7eabf6066, after the migration) — a malformed id there just 404s the same
way an unknown one already does. removeContributor's :userId used to reach
contributorsRepo.deleteOne through a bare Number.parseInt(), the exact
NaN-into-SQL trap row-id.ts documents; it now parses through toRowId too.

The parsed numbers thread down through PackingService's updateItem/
setItemSharing/addContributor/removeContributor/cloneItem/deleteItem/
getItemPrivacy/updateBag/deleteBag/setBagMembers/applyTemplate, all narrowed
from number | string to number; tripId stays loose, a separate,
already-accepted carry. PackingItemsRepository's getPrivacy/findVisibleInTrip/
update/updateSharing/delete/findById, PackingBagsRepository's findInTrip/
update/findWithAssignee/delete and PackingTemplateItemsRepository.listForApply
narrow the same way. packing.rpc.ts's num()-derived itemId/bagId no longer
need their String() wrappers on the update/delete/updateBag/deleteBag/
setBagMembers calls; packing.mcp.ts was already Zod-typed to number
throughout. Two new e2e tests pin the non-numeric-id 404 at the gate;
controller/rpc unit tests cover the narrowed call args and the
removeContributor malformed-userId parity case.

AdminPackingTemplatesController (/api/admin/packing-templates) is out of
scope — a separate admin-gated surface with its own string-typed template
CRUD, not part of this trip-scoped controller's :id chain.

* test(server): plan 4 review — three pins catch up with the gate-parsed ids and the cache_key NOT NULL (M1–M3)

* fix(server): boot baselines legacy-runner installs before running MikroORM migrations (B1)

An install the retired positional runner migrated has a schema_version row
and no mikro_orm_migrations rows, so its first boot on this branch replayed
all 244 migrations over an already-migrated schema: eight refuse the boot,
and the replay-safe ones overwrite user data (step 26 rewrites every
day_assignments.assignment_time).

runSchemaBootstrap now records the baseline plus every migration whose
"Legacy migration step N" docstring is <= schema_version as executed, in one
transaction through the migrator's own storage, before the ordinary run
applies the rest. The step map is derived from the discovered migrations'
source, never hand-kept, and anything unmappable (a newer or malformed
schema_version, a duplicated, missing or out-of-order step) refuses the boot.

* test(server): boot the app on three legacy-runner fixtures to pin the B1 baseline

SQL dumps of databases the retired runner itself built: schema_version 205
(main at fa406b708), 242 (417d0445b, the runner's last commit) and 82
(v2.9.14, so seven of the eight non-replay-safe migrations still lie ahead
and run for the first time). Each gets canary rows: user-set assignment
times and a booked night.

buildApp() on each asserts the baseline and the applied rest in order, the
assignment times untouched, the booked-night reseat run exactly once on 205
and 82 and not at all on 242, schema_version kept, no half-built *_new
table, a schema identical to a fresh install's, and an idempotent re-run.

* refactor(server): demo-reset reads the live path off getRawConnection, not the db Proxy (m1)

demo-reset.ts was the one src/ consumer of the db Proxy left, reached
through a runtime require that a grep on `from` misses. It now imports
closeDb/getRawConnection/reinitialize statically, the way backup.impl.ts
does, so the Proxy genuinely has no src/ importer (the claim in database.ts
and server/CLAUDE.md now holds). The path test mocks the module with vi.mock
instead of teaching Node's require loader to answer for a .ts file.

* test(server): renumber the duplicate ASSIGNREPO/PLACEREPO test ids Plan 4 introduced (m3)

ASSIGNREPO-031/032 (the legacy-statement parity pair) become 034/035, and
the later PLACEREPO-030..038 block becomes 053..061, the next free ids, so
each id names one test again. No test body changes.

* refactor(server): derive the two restated public row types instead of copying their columns (m4)

JourneyPublicEntryPhotoRow restated JourneyPublicGalleryRow's nineteen
columns with only the parent key changed; it is now that row with
journey_id swapped for entry_id. PublicApiAssignedPlaceRow and its Kysely
table shape restated PlaceRow's columns; both now Pick them off PlaceRow.
Types only. The review's CPD method over Plan 4's new src lines drops from
about 3.4% to 0.64%.

* test(server): full-key parity for TripsRepository.findPublicForShare and VacaySharesRepository.listAvailableForShare (m5)

Neither read had any test reference. Each is now pinned with
toEqual(<legacy statement run raw on the same connection>), the
listPublicForShare family shape: SH7 on a filled and a NULL-heavy trip plus
a missing id (TRIPREPO-067/068), and VC90 over one world exercising every
exclusion (caller, guest, existing share, plan owner, accepted member) and
a missing plan.

* fix(server): the legacy baseline runs createTables() instead of marking it, atomically with the run (N1)

The legacy runner ran the running release's createTables() on every boot
before its pending steps, and about 30 tables exist only there. Marking the
baseline migration as executed left installs older than those tables (below
legacy step 68) failing with "no such table: photo_provider_fields" and, since
the rows were committed before the run, stuck half-baselined for every later
boot.

Only steps 1..N are recorded now, so the baseline's IF NOT EXISTS DDL runs
first, as the legacy boot did. The rows are logged inside the same
transaction as migrator.up({ transaction }), so a failed first boot records
nothing and the next boot baselines again.

A v66 fixture (the runner at 5be2e9b26) boots: 66 recorded, 178 applied,
canaries kept. Its two schema differences from a fresh install
(users.immich_access_token, reservations.accommodation_id INTEGER) come
from the legacy chain itself and are pinned as carried.

* fix(deps): sync the lockfiles with the bumped manifests and follow lucide's icon renames

feat/orm raised react to ^19.3.0 and several plugin-sdk dependencies without
regenerating the lockfiles, so npm ci failed on every CI job. The root
overrides now pin react 19.3.0, both lockfiles are regenerated with npm 11,
and the tests that select lucide icons by their old class names use the
current ones. Two tests cover the Immich prefs reads and the boot restore
branch that the coverage thresholds were missing.

* ci: give the server lint step an 8 GB heap for the type-aware rules

* test(server): keep the no-promise-as-value rule tester out of single-run mode on CI

With CI=true typescript-eslint infers single-run mode, builds the program
from the fixture file on disk and ignores the code each case passes in, so
all 24 invalid cases reported nothing on the runner. Both testers now set
disallowAutomaticSingleRunInference.

* refactor(server): name the new migrations after the first seven words of their purpose, like the rest

* fix(server): keep tsx a production dependency so image key rotation can load it

* test(server): re-pin the repositories branch floor at the measured 89.83%

* test(planner): keep the sidebar fixtures on past dates so the jump to today never fires in jsdom

* test(server): keep console output for failing tests only and teach Nest's logger LOG_LEVEL

* test(client): keep console output for failing tests only and answer the health probe

* test(client): drop the health handler, it races the admin page's first load

* chore(sonar): assert explicitly in two e2e cases, Number.NaN, and ignore S2187 on the legacy-upgrade fixtures

---------

Co-authored-by: Maurice <mauriceboe@icloud.com>
2026-10-06 19:27:30 +02:00

65 KiB
Raw Blame History

NestJS migration layer — module & test guide

This folder holds the co-hosted NestJS app that incrementally strangles the legacy Express API (see the "Brownfield Rewrite" board). Until a prefix is migrated, the top-level dispatcher in src/index.ts routes it to the legacy app; migrated prefixes go to Nest. Weather (weather/) is the reference implementation — copy its shape when migrating a new domain.

Module layout (per domain)

shared/src/<domain>/<domain>.schema.ts(.spec.ts)   # Zod contract — single source of truth
server/src/nest/<domain>/<domain>.service.ts        # business logic (ported 1:1 from the Express service)
server/src/nest/<domain>/<domain>.controller.ts     # same routes/verbs/params/status codes as Express
server/src/nest/<domain>/<domain>.module.ts         # registered in app.module.ts

Register the module in app.module.ts and it is live. There is no routing gate to flip any more: every request goes through Nest. The strangler.ts matcher and its DEFAULT_NEST_PREFIXES / NEST_PREFIXES escape hatch are gone — Express only remains as the platform underneath @nestjs/platform-express.

Migrated so far

  • Phase 1 (leaf): weather, airports, config (public), system-notices, maps, categories, tags, notifications, atlas.

  • Phase 2 (trip sub-domains): vacay (addon), packing, todo.

  • DI-native services (legacy src/services/* deleted): tags, categories, todo, packing, day-notes, trip-invite, assignments, share, settings, files, collab, vacay, reservations, day, permissions, audit, budget, trip, maps, transit, place, transit-itinerary, collections, atlas, auth, oidc, passkey, notifications, admin, webauthn-config, user-cleanup, oauth, wiki, mailer, notification transports, notification preferences, memories (immich, synology, unified, photo-resolver, thumbnails, trek-photo cache), journey, journeyShare — see the migration recipe below.

  • Foundation (BE-Phase 1, complete): the eight stateless helpers moved to common/; every trip-access check routes through a repository (services/tripAccess.ts and the dead middleware/tripAccess.ts are gone; DatabaseService, the facade BE-Phase 1 originally routed this through, was itself retired by the later ORM migration — see the root/server CLAUDE.md); queryHelpers and tripMembership are providers; every cron is a domain *.job.ts provider on scheduling/CronRegistrarService (src/scheduler.ts is deleted).

  • Plugin RPC surface (BE-7, complete): all 113 wire methods are @PluginMethod / @PluginOpenMethod handlers on @PluginController() providers in their own domains (<domain>/<domain>.rpc.ts; the three that belong to no domain live in plugins/host/rpc/), and all 18 host-to-plugin hook contracts are @PluginHook declarations on PluginHooks. PluginRpcHost no longer holds a handler: it builds the granted subset of the dispatch map from the registry, dispatches, audits and maps errors. PluginHostDepsFactory — the 26-argument wiring sheet named throughout the log below — is now PluginRpcHostFactory and injects two things. See plugins/host/rpc-kit/README.md.

  • Plugin module split (complete): PluginsModule was 21 controllers, 24 domain imports and 10 providers in one class, so AdminModule importing it for one cascade-disable call inherited the whole graph. It is now PluginsRuntimeModule (supervisor, capability router, hook contracts — the half with the domain imports), PluginContributionsModule (the 14 read-only hook controllers, in plugins/contributions/), PluginOAuthModule (plugins/oauth/) and a composition root holding the install and delivery controllers. AdminModule imports the runtime alone. Note the invariant the boot-time coverage check now depends on: importing PluginsRuntimeModule must pull in EVERY domain that owns part of the wire surface, which is why WeatherModule sits in its import list.

  • Guards (BE-Phase 2, done): the JWT verify lives in auth/, and middleware/auth.ts, validate.ts, idempotency.ts and mfaPolicy.ts are deleted; the three addon guards are one AddonGuard + @RequireAddon; the demo-mode block is one condition. TripAccessGuard and TripOwnerGuard cover the trip-scoped and owner-only routes.

    Authentication is default-deny. GlobalAuthGuard is an APP_GUARD: a route is authenticated unless it carries @Public(reason) or @OptionalAuth(reason), or declares its own @UseGuards chain. A controller that declares a chain keeps it — global guards run before route guards, so an addon-gated controller has to stay in charge of answering 404 before anything answers 401, or the response leaks which addons are installed. The global guard still resolves the user in that case, without refusing, because MfaPolicyGuard runs behind it and reads req.user.

    Adding a @Public() route is not a local decision: validateRouteGuards runs in buildApp() and refuses to boot unless the route is also in PUBLIC_ROUTE_ALLOW_LIST in common/validate-route-guards.ts. That list is the whole anonymous surface of the server, in one reviewable place. Stale entries fail too.

src/services/ is gone. It was the legacy layer this whole migration existed to empty, and the last of it — airtrail/, 1305 lines of plain functions over the better-sqlite3 singleton — folded into integrations/. An ESLint no-restricted-imports rule now refuses any import of a services/ path, because the directory disappearing is not what keeps it gone: it grew one reasonable file at a time. Backup made the same trip earlier: services/backupService.ts is nest/backup/backup.impl.ts, imported only by its own domain, and it stays a module of free functions rather than becoming methods because the restore path closes and reinitializes the core DB handle — rewriting that shape in the same step as the move would make a regression there impossible to bisect.

Note that the trip-access and canEdit methods on the domain services are not dead weight waiting for a guard: their callers are overwhelmingly the *.mcp.ts tools, which never pass through an HTTP guard. In the five domains piloted for TripAccessGuard, 40 of the 46 callers are MCP; only 6 sit in controllers.

Cross-cutting Foundation pieces

  • common/idempotency.interceptor.ts — global APP_INTERCEPTOR replaying the client's X-Idempotency-Key on mutations. It replaced the applyIdempotency middleware, which is deleted; this is the only implementation.

  • common/ — the stateless helpers (avatarUrl, conflictResult, demo, passwordPolicy, timezoneService, cookie, rowShape, geo, crypto/). Free functions, not providers: the numbered migrations in db/migrations/ (e.g. the plaintext-secret encryption steps) and demo/demo-seed.ts import them from outside the container and could not inject one. geo.ts holds the two haversines; there were three implementations of the metre variant, differing by one clamp, and the clamped form is the one kept — asin of a value a hair over 1 is NaN, and a NaN distance silently fails every comparison it feeds instead of throwing. maps.helpers.ts re-exports haversineMetres rather than defining it, because callers and a test import it from there.

  • auth/jwt-verify.ts — extractToken + verifyJwtAndLoadUser, the canonical session check behind the four guards, the MCP bearer path and the file-download query token. Free functions for the same reason. JWT_SECRET stays a live binding from src/config and must NOT move to app-config: the admin panel rotates it at runtime, and a registerAs token would freeze the boot value.

  • query-helpers/ — the batch loaders that keep list endpoints off N+1 queries.

  • trip-membership/ — joinTripAsMember. Its own module rather than folded into auth or trip-invite, because both call it (as do oidc and the plugin host) and either home would put AuthModule and TripInviteModule in a cycle.

  • addons/addon.guard.ts + @RequireAddon(addonId, label) — the addon route gate. Declare AddonGuard before JwtAuthGuard: a disabled addon has to answer 404 to anonymous callers, so the addon check must beat the 401.

  • common/demo-write.ts — isDemoWriteBlocked, the demo-mode upload block. A function and not a guard on purpose; see the gotcha below.

  • storage/ — the storage abstraction and its admin surface. storage.types.ts defines the driver contract (opaque keys, no rename/append — S3 constraints baked in) plus the ServedCategory seam: STORAGE_CATEGORIES (shared, 8, configurable) + the legacy photos directory that is served and backed up but not configurable. drivers/ (local, s3, mirror) all pass one contract suite (tests/unit/nest/storage/storage-driver.contract.ts). storage-registry.service.ts merges built-ins ← env (place-photos-local) ← app_settings rows, validates semantics (references, no mirror nesting), falls back to last-good/defaults at boot but NEVER on admin writes (preview() runs the real build first), seeds once from data/storage-config.json, and hot-swaps on reload(). storage.service.ts is the facade every byte-path uses. storage-admin.{controller,service}.ts (+ storage-secrets.ts, storage-probe.ts) carry api/admin/storage: masked GET of the effective world, full-document PUT (unmask → preview → encrypt → one transaction → reload → audit), and per-target test probes with ephemeral drivers. Secrets live enc:v1:-encrypted inside the storage.backends JSON (the implicit key covers installs without an explicit ENCRYPTION_KEY). The client presents mirrors as replicas-on-primary; the wire keeps explicit mirror backends. storage-jobs.service.ts runs backfill and category-migration jobs (one at a time, TTL'd statuses).

  • memories/photo-provider.ts + providers/ — the PhotoProvider seam (#584). Dispatch to a photo backend was a switch (photo.provider) in three places (photo-resolver.service.ts twice, journey-public.controller.ts once, where anything that was not Immich got handed to Synology). It is PhotoProviderRegistry.get(id) now, over adapters registered under the PHOTO_PROVIDERS multi-provider token in memories.module.ts — adding a backend is one registration.

    • Adapters, not implements on the services: ImmichService and SynologyService are also the album/browse surfaces, with their own argument orders and return shapes. The mapping lives in the adapter.
    • PhotoAssetRef exists because the two services took the same three values in different orders — (userId, assetId, ownerId) against (userId, targetUserId, photoId). A transposition compiled cleanly and served another user's photo.
    • local is deliberately NOT a provider. It is storage on this disk, it has no row in photo_providers, and its "asset info" comes from the DB row rather than from a backend. Both dispatch sites branch on it explicitly.
    • The rename memories/ → media/ was considered and dropped: it is 275 files of import churn, and scripts/coverage-thresholds.mjs buckets on one path segment, so merging photos/ into it would collapse two ratchet entries into one and drop the stricter of the two.
  • realtime/ — the /ws transport, as a Nest gateway.

    • realtime.gateway.ts owns the connection lifecycle and the handshake, with TripsRepository/UsersRepository/AppSettingsRepository and EphemeralTokenService injected instead of imported (Plan 4 converted it off the deleted DatabaseService). It replaced setupWebSocket(server), which index.ts kicked off with a dynamic import after listen().
    • ws-state.ts holds the socket registry, and that is module state on purpose. The no-Nest test harnesses build new RealtimeService() outside the container and 115 test files vi.mock the src/websocket stub; rooms on a provider instance would leave their broadcasts going to an empty map, with no error and no log. Same reasoning as the geo throttle cursor.
    • trek-ws.adapter.ts exists because the stock WsAdapter dispatches on { event, data } and every deployed client sends { type, tripId }. It also builds the ws server itself rather than delegating: the base's port-0 branch uses noServer: true and performs the upgrade from its own registry, which never consults verifyClient, so delegating would silently drop the origin check. The per-socket error listener is attached FIRST, because an unhandled one kills the process (#1576), and the flood guard counts every inbound frame before parsing, because malformed frames are the ones worth limiting.
    • The socket id stays a monotonic integer. The client echoes it as X-Socket-Id and broadcast excludes the originator with Number(excludeSid); a uuid is NaN, NaN === NaN is false, and every client would receive its own writes back. It shows up as drag-and-drop that jumps, not as an error.
    • RealtimeGatewayModule is imported by AppModule alone. RealtimeModule is @Global, so a gateway there follows into every hand-assembled TestingModule, and Nest's SocketModule then loads an adapter none of them set: it reaches for @nestjs/platform-socket.io and calls process.exit(1) when it is absent.
    • buildApp() creates the http server and binds the adapter to it BEFORE app.init(), and callers take it from getHttpServer(). Nest binds gateways during init, so an adapter registered later binds nothing, and one given the app instead of the server binds to Nest's internal server, which this process never listens on. Either way the boot is green and no browser can connect.
    • src/websocket.ts survives as a re-export. 115 test files vi.mock that path to assert on broadcasts; repointing them all would be a large diff that proves nothing.
  • geo/ — the ONE Nominatim client (#576). There used to be two: atlas throttled to the published 1.1s and cached its answers, maps did neither, so five interactive routes fired straight at the service while the atlas loops politely waited and OSM saw a single instance ignoring its rate limit. Both domains now go through nominatimFetch.

    • The throttle cursor and the cache are module state, not provider state, for the permissions-cache reason: the no-Nest test harnesses build their collaborators with new, outside the container, and a second copy of the cursor is the very bug the fold removes. GeoModule is registered straight in AppModule and neither MapsModule nor AtlasModule imports it — an import would claim an injection edge that does not exist.
    • GeocodingService owns exactly one thing: the cache-cleanup timer's lifecycle, via OnModuleInit/OnModuleDestroy. Atlas used to start that interval as an import-time side effect, documented as a parity exception. It is not one any more.
    • Two lanes over one cursor. Interactive calls (/api/maps/search, /autocomplete, /details, /reverse, /resolve-url) take the next slot; background calls (the atlas enrichment loops, which walk every uncached place) yield to anything queued on a request path.
    • The cache key carries the query shape, not coordinates alone. Atlas asks at zoom 3 and zoom 8, maps at zoom 18; a coordinate-only key answered a street lookup with a country.
    • AbortSignal.timeout is built after the throttle wait. Built up front, the 1.1s spent queueing would eat nearly half of the identity lookup's 2.5s budget before the socket opens.
    • setGeoThrottleInterval(ms) is a test seam, and tests/setup.ts zeroes it. Nineteen maps cases drive these paths back to back with real timers; at the real interval they slept nineteen seconds and covered nothing extra. A function rather than a NODE_ENV check, for the reason app-config exists.

Reaching the container from outside it

Two shapes, and the choice is settled:

Prefer handing the dependency in. bootstrap.ts hands the /mcp handler its registry via setMcpRegistry(app.get(...)) after buildApp() — the outside code names the capability it needs, structurally, never the provider class, so no module cycle can close through it. (The retired src/scheduler.ts was the fullest example — a structural SchedulerDeps interface filled by index.ts — until every cron became an in-container *.job.ts provider and the seam disappeared entirely, which is the real endgame for this shape.)

<domain>.bridge.ts is a retired shape — zero bridge files remain since the MCP/OAuth mount moved behind the container (2026-08-11). It served code that ran before app.init() and so could not inject; its cost was real: a bridge rebuilt its services with new, so adding one constructor parameter to a service meant hand-editing every bridge that constructed it — five of them in one PR, at the worst. If a pre-init consumer ever reappears, prefer the bootstrap.ts pattern instead: resolve the container singleton with app.get(...) before init (the httpConfig.KEY / discovery-metadata precedent) rather than minting a second instance.

Express middleware with DI has two honest mounts (first used by the mount migration): consumer.apply(...).forRoutes('<concrete path>') in a module's configure() — an Express prefix mount, exactly the legacy app.use('/path') semantics, which is how OauthModule mounts the MCP SDK's authorize/register routers and PlatformModule the consent-COOP override — and, for middleware that must see the ORIGINAL req.url (a wildcard forRoutes() is a pattern mount that strips the matched prefix), a pathless app.use in bootstrap.ts over a container-resolved factory provider (MCP_METADATA_MIDDLEWARE). nest/mcp-transport/ (the /mcp controller + service over injected services) and nest/mcp-shared/ (McpToolGuardsService for the *.mcp.ts classes) are the module shapes that replaced the last bridges.

A bridge imported from INSIDE the container hides an edge from the module graph, which is a different problem from serving a genuine outside consumer. Nine *.mcp.ts files did that with addons.bridge for one boolean each, and not by preference: a decorator's options object is built while the class is being defined, so the when: closure had no this to reach an injected service through. src/nest-mcp/ hands the gate its declaring instance now, and addons/addon-gate.ts turns that into addonGate(ADDON_IDS.X) over an injected AddonsService. reservations.mcp.ts (assignments) and atlas.mcp.ts / journey.mcp.ts (auth) went the same way.

No in-container bridge uses are left. The last four folded 2026-08-11, and their folds are the playbook for any edge that reappears — plain injection would have closed a real cycle in every case, so each cut the knot with a finer-grained module instead:

  • budget.mcp.ts / packing.mcp.ts / costs.rpc.ts → trips.bridge: everything that owns the hydrated trip reads (TripsService, TripReadModelService, TripMembersService) lives in modules importing the budget/packing domains, so the consumers moved instead — the id-level membership reads went to the dependency-free TripMembershipModule (getOwnerId / listMemberUserIds / listAccessibleTripIds) and the two cross-domain prompts moved above the read model onto trips/trip-prompts.mcp.ts. trips.bridge (102 lines, ~25 hand-built services) is deleted.
  • places.mcp.ts → assignments.bridge: the cycle DaysModule → PlacesModule → AssignmentsModule → DaysModule is real, but only AssignmentsMcp needs DaysService — the service itself does not, so it moved to a leaf AssignmentsDomainModule (the journey-domain split) that PlacesModule imports. assignments.bridge is deleted.
  • reservations.controller.ts → airtrail.bridge: the pull genuinely needs ReservationsService, so AirtrailModule keeps it — but the write-back push only needs the hydrated reservation READ. That read became ReservationsReadService (leaf, the trek_photos pattern), the link lifecycle + push became AirtrailLinkService in AirtrailCoreModule, and the controller injects it. airtrail.bridge is deleted, and notifications.instance.ts — whose last consumer it was — died with it.

Two more were on this list and folded 2026-08-11:

  • auth/user-cleanup.service.ts → budget.bridge died when BudgetModule dropped its AuthModule import (BudgetMcp's demo guard reads RuntimeEnvService + the users table via isDemoUserId, not AuthService), which let AuthModule import BudgetModule and UserCleanupService inject BudgetService. budget.bridge is deleted.
  • backup/backup.impl.ts → permissions.bridge: the restore path is free functions, not a provider, so there is nothing for an injected service to hang off — but the thing it needs is the cache, not the service. The cache moved to permissions/permissions-cache.ts (the oauth.pending-codes.ts precedent) and backup.impl imports the plain invalidatePermissionsCache from there.

files.bridge used to be on the list and is gone, resolved 2026-08-10 exactly as predicted: MulterModule.registerAsync over an AllowedFileTypesService leaf, and files.controller.ts / journey.controller.ts build their multer options from that. systemNotices/conditions.ts similarly stopped importing addons.bridge: the enablement check is threaded in through ConditionContext.addonEnabled by the DI-native SystemNoticesService.

days, packing, photos and reservations had no production consumer left and are deleted. Each still built a service outside the container at module load for nobody, and three domain docblocks were still sending readers to them. The cases that exercised them kept their assertions and point at the service. journey.bridge died 2026-08-11 with src/mcp/resources.ts, when the last four legacy resources became @Resource/@ResourceTemplate methods on journey.mcp.ts.

Five bridges remain, all pinned by the one pre-app.init() MCP/OAuth mount (addons, audit, auth, oauth, permissions — shrunk to the exports that seam consumes) and all dying together if that mount ever moves behind the container. When one loses its last outside-container consumer, delete it in the same change rather than leaving it as a courtesy: an unused bridge reads as a supported entry point.

The nine fire-and-forget notification senders inject too. They were lazy import('../notifications/notifications.bridge').then(({ send }) => …) calls working around a cycle that no longer exists, and the laziness hid the edge while handing each send a NotificationsService built outside the container.

That sweep needed a method, because tests/ sits outside tsconfig's include: a missed constructor argument does not fail to compile, it arrives as undefined. Adding tests to a throwaway tsconfig and diffing the errors before and after named all 46 hand-wired new sites exactly; a grep would have been a guess. Worth repeating for any change that widens a service constructor — and worth knowing that such a config reports 288 pre-existing errors in the suites, almost all deliberate partial constructions in the harnesses (new AuthService(db, permissions, atlas) where the class takes six). That is why tests/ is not in the build's include, and cleaning it up is its own piece of work.

notifications.instance.ts held the out-of-container NotificationsService for the cycle-dodge bridges and died 2026-08-11 with the last of them (airtrail.bridge) — every production consumer injects the container singleton now. The module-scoped channel registry it leaned on stays (the no-Nest test harnesses still construct instances; CHOVR-015 pins the sharing).

  • app-config/ — the @nestjs/config binding (AppConfigModule, global). Never read process.env in a module (ESLint enforces this): inject a boot-stable namespace via its registerAs token (@Inject(mcpConfig.KEY) … ConfigType<…>) or read runtime-toggled values live through RuntimeEnvService / readEnv() from src/app-config. The classification and invariants live in src/app-config/README.md.

Parity gotchas worth remembering

  • A POST that answers with res.json in Express stays 200; add @HttpCode(200) (Nest defaults POST to 201). Creates that Express sends as 201 need nothing.
  • Static sub-routes that collide with a :id param (e.g. /in-app/all vs /in-app/:id, /reorder vs /:id) must be declared before the param route.
  • Reproduce bespoke admin/error wording exactly — e.g. notifications' test-smtp returns { error: 'Admin only' }, not the AdminGuard's Admin access required.
  • Trip-scoped routes verify trip access (404) and the relevant permission (403) per handler and forward X-Socket-Id to the WebSocket broadcast.
  • Never gate a multipart upload with a guard. Guards run before the parser, so throwing from one leaves the request body unread and Node resets the connection — the client sees ECONNRESET, not your 403. Check inside the handler, after the interceptor has drained the upload. PROFILE-015 is the regression test.
  • @Global() only applies to modules that are in the graph. An e2e TestingModule built around one domain module does not get AppConfigModule for free just because it is global: a provider injecting RuntimeEnvService fails to resolve and takes every suite importing that module down with it. Import it explicitly, the way PermissionsModule is handled.
  • A module-scoped registry that outside code writes into must stay a module, not a provider. The notification channel registry is the live example: PluginRuntimeService pushes its channel getter in at onModuleInit, and notifications.instance.ts builds its own NotificationsService for the surviving cycle-dodge bridges. As a provider that instance would get a second, empty registry and every plugin channel would go quiet — with no error anywhere. CHOVR-015 is the regression test. Same reasoning as oauth/oauth.pending-codes.ts.
  • Self-registration by side-effect import is a trap. The built-in channels used to register because notificationPreferencesService happened to import './notifications/builtins'. Dropping that one line would have silenced email, webhook and ntfy without a failure. They are built from injected transports and registered in NotificationsService's constructor now, so every path that can dispatch has them.
  • The coverage gate reads src/nest/** and nothing else. Moving code in from src/mcp/ or src/services/ does not just relocate it — it starts being measured. PR #1844 landed airports.mcp.ts at 0% branches because search_airports/get_airport had never had a test in either world, and the aggregate fell to 79.86% with every suite green. Before pushing anything that moves files into this tree, run npm run test:coverage, not just npm test.
  • A guard with a constructor dependency has to be a registered provider everywhere it is used. The three auth guards are dependency-free on purpose — 38 directories apply them and 21 do not import AuthModule, so giving them a dependency is its own migration, not a side effect of another change.

Parity is law

A migrated route must be byte-identical for the client: same URL, method, query/body, HTTP status, Set-Cookie, and JSON body — including bespoke error strings. Where the legacy route returns a hand-written error (e.g. weather's { error: 'Latitude and longitude are required' }), reproduce that exact body in the controller rather than relying on the generic ZodValidationPipe envelope.

TripAccessGuard and TripOwnerGuard, and where they do not fit

permissions/trip-access.guard.ts resolves :tripId once per request, answers 404 "Trip not found" for anything the user cannot reach (never 403 — that would confirm the id exists), and hands the row to the handler through @Trip(). @RequirePermission carries the same action string the domain services pass to checkPermission.

Two limits are worth knowing before rolling it onto another controller, because both were found the expensive way:

  • A guard runs before the body pipe. Any route whose DTO validation is expected to answer 400 ahead of the trip 404 cannot use it. places is exactly that case — its e2e suite documents the pipe-first ordering as a deliberate parity shift — so its create/update/import routes keep their in-handler requireTrip, and that is not an oversight. Its five body-free routes (list, get, unrate, image, delete) do carry the guard; the split runs along "does this handler take a DTO-typed body", not along the domain.
  • A guard also runs before interceptors. On a multipart upload route, a 404 sent while the client is still streaming destroys the socket, so the caller sees ECONNRESET instead of the 404. The three upload routes (files, collab note files, places) keep their own check for that reason; their controllers apply the guard per handler instead of on the class.

permissions/trip-owner.guard.ts is the stricter sibling: @RequireTripOwner(message) demands that the caller owns the trip, not merely that they may edit it. Handing a trip over and creating or deleting guests are the two things a collaborator must never do however generous the trip's permission settings are.

It deliberately does not inject PermissionsService. checkPermission returns true for every admin, and the trip actions are admin-lowerable, so routing ownership through it would quietly hand any admin the ability to transfer other people's trips. The check is the literal one the routes did by hand: trip.user_id === user.id. The message travels in the metadata because the two call sites answer with different strings and both are asserted.

The services keep verifyTripAccess/canEdit regardless: most of their callers are *.mcp.ts tools, which never pass through an HTTP guard.

Coverage is gated per domain, as a ratchet

server/vitest.config.ts carries one threshold entry per src/nest/<domain>/, set at that domain's measured coverage minus one point. The single repo-wide 80% it replaced let a well-covered domain subsidise a thin one — booking-import sits at 50% and integrations at 20%, and the aggregate still cleared the bar, so either could have lost another ten points with the build staying green.

Regenerate the block with node scripts/coverage-thresholds.mjs after a run that RAISED coverage. Raise an entry when you improve a domain; never lower one to make a build pass. The script reads coverage/coverage-summary.json rather than the text reporter on purpose: the text reporter prints one row per DIRECTORY, so a domain with subdirectories reads several points higher there than it actually is.

How to write the tests

Every module ships two kinds of tests. The coverage gate (vitest.config.ts) requires ≥80% over src/nest/** — note that it is an average across the whole tree, not a per-file floor, so a large untested module can hide behind the well-covered small ones.

  1. Service / controller unit spec — tests/unit/nest/<domain>.controller.test.ts. Instantiate the controller with a mocked service; assert status codes, the exact { error } bodies, and that inputs are forwarded correctly (defaults, coercion). See weather.controller.test.ts.

    Parity against the behaviour being replaced belongs here too — assert the exact status codes and bodies the old path produced. There is no separate tests/parity/ directory; it was removed along with the routing toggle.

  2. e2e — tests/e2e/<domain>.e2e.test.ts. Boot the Nest module against a temp in-memory SQLite db via the shared harness (tests/e2e/harness.ts: createTempDb/seedUser/sessionCookie), exercising the real JwtAuthGuard end-to-end (401 without cookie, 200 with a signed session). Mock external I/O (HTTP/etc.). See weather.e2e.test.ts.

Definition of Done (per module)

Contract in @trek/shared → service ported 1:1 → controller with identical routes → validation/error parity → unit + e2e tests, with the old behaviour asserted in the unit test → module registered in app.module.ts → then decommission the legacy service (separate step) → frontend points at the typed contract (Frontend Track).

Migrating a legacy src/services/* service into its Nest module (recipe)

Historical record. src/services/ finished emptying in 2026-08 (see above); the numbered steps below describe how each fold was actually done at the time, including its DatabaseService construction — a deliberate changelog, not a recipe to follow for new code. DatabaseService itself is gone (ORM migration Plan 4): a service now takes the repositories it needs plus UnitOfWork for transactions, per the root and server CLAUDE.md's DB sections.

Pilot: tags (services/tagService.ts → nest/tags/tags.service.ts + nest/tags/tags.bridge.ts); categories followed the same shape (and piloted the first @Resource in categories.mcp.ts); todo followed too (and piloted the first @ResourceTemplate plus the when addon gate in todo.mcp.ts, and the first in-container consumer wiring: TripsService injects TodoService via exports: [TodoService] instead of using the bridge); packing followed (the largest port so far: a 17-tool + 2-resource packing.mcp.ts with inline admin gates, and the first PluginHostDepsFactory swap done as part of a service migration — no bridge entry for the plugin host); day-notes followed (the first migration needing no bridge at all: after its three tools + resource moved to day-notes.mcp.ts and the plugin host injection, nothing outside the container consumed it); trip-invite followed (the smallest port: no MCP surface, no plugin-host import and no bridge — the SQL folded straight into trip-invite.service.ts); assignments followed (a 7-tool assignments.mcp.ts, the plugin-host swap, and a bridge kept only for the two legacy registrars — places and reservations — that borrow its existence checks; the batch loaders stay in services/queryHelpers.ts, shared with the unmigrated place service); share followed (never imported by the plugin host, and its three MCP tools stay in the legacy trips registrar — their trips:share scope gate has no declarative access: { group, mode } equivalent — so the port is the SQL fold plus a 3-export share.bridge.ts for mcp/tools/trips.ts); settings followed (no MCP surface, no bridge, and the first migration that converted an in-container plain-function consumer into a provider instead of bridging it: llm-parse/llm-config.resolver.ts became the injectable LlmConfigResolver, injected by LlmParseService and PluginHostDepsFactory); files followed (no MCP surface and no addon gate; the load-time constants + pure helpers consumed by three controllers' module-scope multer configs moved to files.constants.ts, and files.bridge.ts survives with a single export — the request-time getAllowedExtensions app_settings read those configs need outside DI — while every function consumer, including the plugin host and TripsService, injects FilesService); collab followed (a 12-tool + 3-resource collab.mcp.ts that piloted composite when gates — the collab addon AND the per-sub-feature getCollabFeatures() flags (notes/polls/chat) that the legacy registrar and resources checked at registration time — plus the plugin-host swap and a 3-export collab.bridge.ts for the two remaining legacy consumers, tripService's trip summary and mcp/tools/trips.ts); vacay followed (the largest MCP port yet — a 26-tool + 3-resource vacay.mcp.ts, including the first fixed-URI @Resource behind a when addon gate — plus the plugin-host swap and a 1-export vacay.bridge.ts for tripService's trip-window entry shift; the DTO ratchet for its 13 grandfathered body contracts landed as a sibling commit); reservations followed (the residue fold: the wrapper ReservationsService was already DI-native at the edge, so the 626-line legacy module folded into it — a 5-tool

  • 1-resource reservations.mcp.ts, the plugin host's last plain-function reservation import (notifyBookingChange) swapped for the injected service, TripsService and BookingImportService converted from function imports to injection, and a 9-export + 3-type reservations.bridge.ts for the legacy tripService, the airtrail import/sync pair and the still-legacy transports registrar (the transit registrar has since migrated to transit.mcp.ts); the DTO ratchet for its 4 grandfathered body contracts landed as a sibling commit, which also loosened the shared positions schema to the real wire contract — day_plan_position optional, pinned by RESV-006); day followed (the 592-line legacy dayService folded into the existing wrapper DaysService — including the accommodation SQL that nest/reservations/accommodations.service.ts now reaches via an injected DaysService — with the hand-rolled BEGIN/COMMIT blocks in reorder/insert converted to db.transaction(); a 7-tool + 2-resource days.mcp.ts, the plugin host's 11-symbol import swapped for the injected service, TripsService + the assignments/reservations MCP controllers converted to injection, and a 6-export days.bridge.ts for the legacy tripService and the still-legacy transports registrar (transit has since migrated); the DTO ratchet for its 4 day + 2 accommodation grandfathered body contracts landed as a sibling commit); permissions followed (the first Wave-2 cross-cutting migration and the first greenfield module in the series — no prior wrapper, controller, MCP surface or DTO of its own: a new nest/permissions/ whose PermissionsService is injected by 16 domain services, the airtrail-import controller and PluginHostDepsFactory (its 16th constructor dep) in one move, plus a 5-function permissions.bridge.ts for mcp/tools/_shared.ts — one repoint covering every hasTripPermission call site — and the four legacy consumers adminService/authService/backupService/collectionsService; the permissions cache stays module-scoped in permissions.service.ts on purpose, so the bridge instance and the container singleton share one cache and backup-restore's bridge-side invalidatePermissionsCache() flushes what request handlers serve; the domain e2e suites swapped their path mocks for a vi.spyOn(app.get(PermissionsService), 'checkPermission') instance spy); auditLog followed (the other Wave-2 half, split into five files: the injectable AuditService (writeAudit over DatabaseService), the pure client-ip.ts (files.constants precedent — the four getClientIp-only controllers stay plain imports), the deliberately side-effectful plain audit-log.logger.ts — frozen-at-import LOG_LEVEL and the import-time data/logs mkdir are a documented parity exception to the no-side-effects rule because index.ts lazy-requires it pre-container and tests/setup.ts sets the level pre-import — plus audit.module.ts and a full-surface audit.bridge.ts for mcp/index.ts, mcp/oauthProvider.ts and the legacy airtrail/immich/oauth services, while log*-only consumers (index.ts's lazy require strings, scheduler, globalMiddleware, notifications) point at the logger directly; 8 controllers + PluginRuntimeService inject AuditService, and the domain e2e suites dropped the audit mock entirely — writeAudit runs for real against an audit_log table in their temp DBs). The exchangeRateService fold followed (the pure-infra FX helper — Frankfurter fetch + module-scoped 6h cache, no SQL, no controller, no MCP registrar of its own — folded into nest/budget/ as a dep-free ExchangeRatesService, injected by BudgetService and PluginHostDepsFactory (its 17th constructor dep); the rate cache stays module-scoped like the permissions cache, so any out-of-container instance and the container singleton share one cached upstream feed). budgetService followed (the 755-line Wave-4 money core folded into the wrapper BudgetService: items/members/payers CRUD, the FX freeze + rebase paths and the settlement maths with splitEqualShares gone private; the freeze-then-write composites kept their wrapper names while the raw settlement writes became insertSettlement/applySettlementUpdate so the MCP paths keep skipping the freeze; the 11-tool mcp/tools/budget.ts registrar + 3 resources.ts budget resources moved to budget.mcp.ts; TripsService, ReservationsService (+ its MCP class) and BookingImportService inject BudgetService; a 4-export budget.bridge.ts served the legacy tripService/userCleanupService and the trips/transports registrars (deleted 2026-08-11: BudgetMcp's demo guard moved off AuthService onto isDemoUserId, BudgetModule dropped AuthModule, and UserCleanupService injects BudgetService now); exchange-rates.bridge.ts was deleted with its last consumers, and the controller adopted budget.dto.ts — all nine allow-list entries removed). tripService followed (the 1121-line Wave-4 hub — the biggest fold — moved into the wrapper TripsService: TRIP_SELECT + list/create/get, the generateDays two-phase renumber engine, the updateTrip date-shift transaction, the member/guest lifecycle (#973/#1362), the ICS export with its module-scoped tz-validity cache, copyTripById and getTripSummary; its six bridge imports became injected services (CollabService + VacayService joined the constructor); the 10-tool trips registrar + 3 resources.ts trip resources + the trip-summary prompt moved to trips.mcp.ts — the first @Prompt use, with the fire-once static-token deprecation notice now riding the registry.attach ctx — and the 3 share-link tools it carried moved to share.mcp.ts on the canShareTrips predicate (delete_trip and the canReadTrips reads are predicates too — the broadened legacy gates have no declarative equivalent); FeedsService and the plugin host inject TripsService (its 20th constructor dep); a 4-export trips.bridge.ts serves budget.mcp.ts / packing.mcp.ts / costs.rpc.ts (verified-permanent 2026-08-11: the trip read-model/members modules import the budget and packing domains, so injecting any backing service there closes a real cycle; the prompts registrar it also served is long migrated); todo.bridge.ts, share.bridge.ts, collab.bridge.ts and vacay.bridge.ts were deleted with their last consumers and the unused days/budget bridge exports pruned; the controller adopted trips.dto.ts — all seven allow-list entries removed). mapsService followed (the 1429-line geo core — Google Places, Nominatim, Overpass mirror racing, Wikimedia photos, Maps-URL resolution — folded into the wrapper MapsService; the pure parser/UA/POI-category helpers moved to maps.helpers.ts as plain exports (files.constants/client-ip precedent — the DI-native TransitService's User-Agent imports from there, not a bridge), the module-scoped POI cache / photo-fetch semaphore / frozen Overpass mirrors stayed module-scoped on purpose (permissions-cache precedent: any out-of-container instance and the DI singleton share them); the 3 geo tools left the mixed mcp/tools/mapsWeather.ts registrar for the decorator-driven maps.mcp.ts (the registrar file survives — its weather + airport tools await their own migrations); BookingImportService injects MapsService for its Nominatim geocoding, and a 3-export maps.bridge.ts served the legacy placeEnrichment helper and the places registrar — both absorbed by the 2026-07 place fold, which deleted the bridge). transitService followed (the first fully SQL-free domain fold — the 333-line Transitous/MOTIS proxy became a dep-free TransitService (no DatabaseService; the ExchangeRatesService precedent), its response cache, frozen-at-import TRANSIT_API_BASE and lazy User-Agent memo staying module-scoped on purpose; the pure deriveTransitStats + mode whitelist + itinerary types moved to transit.helpers.ts (maps.helpers precedent) so the downstream legacy transitItineraryService needed no bridge (since relocated into the domain as transit-itinerary.helpers.ts); the whole 3-tool mcp/tools/transit.ts registrar moved to transit.mcp.ts — the two geo search tools on access: { group: 'geo', mode: 'read' } and create_transit_journey on reservations:write, with its days/reservations bridge imports becoming injected DaysService/ReservationsService (+ DatabaseService for canAccessTrip) — leaving zero bridge files and the transports registrar as days.bridge.ts's last consumer). placeService followed (the step-4 tail: the 1029-line place core — the CRUD + ratings SQL, the GPX/KML/KMZ importers and the Google/Naver list importers — folded into the wrapper PlacesService, with the pure pieces (frozen XML parsers, the KMZ unpacker, the dedup predicates, the Google hex-id parsers, reclaimPhotoCache) moving to places.helpers.ts on the maps.helpers precedent; the 10-tool mcp/tools/places.ts registrar + the trek://trips/{tripId}/places resource moved to places.mcp.ts — search_place came along because its gate is places:read, not the geo group, and now injects MapsService; TripsService, DaysMcp, BookingImportService and the plugin host (its 21st constructor dep) inject PlacesService, leaving zero bridge files for the domain; the two assignments.bridge imports stay in places.mcp.ts on purpose — AssignmentsModule imports DaysModule and DaysModule now imports PlacesModule, so injecting would close a DaysModule → PlacesModule → AssignmentsModule → DaysModule cycle (reservations.mcp.ts uses the same seam for the same reason). The sibling placeEnrichment fold went further than the recipe's minimum: the 168-line helper's DB/websocket/Maps half became PlacesService methods over the injected DatabaseService/RealtimeService/MapsService and its pure match selector joined places.helpers.ts, which retired maps.bridge.ts with its last consumer. The DTO ratchet for its 7 grandfathered body contracts landed as a third commit, which also loosened placeBulkUpdateRequestSchema.ids (.min(1) dropped) so the endpoint's empty-list short-circuit stays reachable, and retired three bespoke 400 strings — 'Place name is required', 'ids must be an array of numbers' and 'URL is required' — in favour of the pipe envelope, accepting that a malformed body now 400s ahead of the trip-access 404 (the todo/trips trade). transitItineraryService followed (the first pure-helpers relocation with no service fold at all — the 287-line module is 100% pure, so the recipe's SQL / bridge / DTO / plugin-host steps were all no-ops: the Zod itinerary schemas + endpoint/metadata builders moved byte-identical to transit-itinerary.helpers.ts, next to transit.helpers.ts; the schemas must stay module-level plain exports because transit.mcp.ts consumes them inside @Tool({ inputSchema }) decorators, which evaluate at module load before any container exists; the sole consumer — the in-container transit.mcp.ts — was a one-import repoint, closing step 4 of the dependency-honest order; the legacy module had no direct suite, so a new 21-case TRANSIT-ITIN-* characterization suite now pins all 12 superRefine error strings, the ?? time fallbacks, the coordinate tolerances and the reservation endpoint/metadata builder). collectionsService followed (the biggest single fold yet — 1024 lines / 28 exports into CollectionsService over DatabaseService + PermissionsService + RealtimeService, with the deleteOldCollectionCover path re-anchored one directory deeper and the sendInvite lazy notificationService import() kept, collab precedent; the 25-tool legacy registrar mcp/tools/collections.ts moved to collections.mcp.ts — at relocation time deliberately with NO when: addon gate, since the legacy registrar registered unconditionally while REST/plugin-host gate on the addon; the trailing fix(server) quirk commit then gated all 25 tools (the addon ships disabled by default, so the ungated surface was live on fresh installs) alongside wrapping every multi-statement write in db.transaction(), making the bulk ops all-or-nothing, and forwarding X-Socket-Id on the from-trip saves — each pinned by a new 23-case tools-collections characterization suite plus the COLLECTIONS-SVC-090…092 band (the legacy registrar had no tool-level tests at all); the plugin host swapped its 7 collections imports for the injected service — its 22nd constructor dep — and NO bridge was needed anywhere; the dead buildDedupSet module helper was dropped in the move, the only line that didn't relocate verbatim). atlasService followed (1612 lines split two ways, places precedent: the DB half — stats aggregation, visited countries/regions with the #1490 tombstone/cascade logic, bucket-list CRUD — folded into AtlasService over DatabaseService alone, while the ~750-line pure-geo half — the bundled admin0/admin1 stores and their #1576 OOM-shaped streaming builders, the point-in-polygon indexes, Nominatim geocoding with its shared ≥1.1s throttle, the 50k geocode cache with its import-time unref'd cleanup interval, and the geocodingInFlight dedup set — moved to the plain module atlas-geo.ts so those caches stay process-global across the container instance, the bridge instance and test helpers; assetPath re-anchored one directory deeper, the only non-verbatim line. The 10-tool legacy registrar mcp/tools/atlas.ts plus all four atlas resources in mcp/resources.ts (trek://bucket-list, trek://visited-countries, trek://atlas/stats, trek://atlas/regions) moved to atlas.mcp.ts — here the when: atlas-addon gate IS parity, since the legacy registrar and resources both gated on the addon while the REST controller deliberately does not; the mark_region_visited / get_country_atlas_places no-uppercase divergence from REST relocated untouched. The plugin host swapped its 9 atlas imports for the injected service — its 23rd constructor dep — and a minimal 2-export atlas.bridge.ts existed solely for the legacy authService.getTravelStats edge (getCountryFromCoords re-exported straight from atlas-geo, getHiddenCountries over the bridge instance); it died with the auth fold, as predicted. resources.test.ts retired with its last two cases — every resource it covered now lives in the domain suites. The trailing fix(server) quirk commit then wrapped the four multi-statement mark/unmark writes in db.transaction() (the region cascade nests as a savepoint), made the trip-less countryPlaces early return honour manually_marked, fixed the || null bindings that dropped lat: 0/lng: 0/notes: '' on bucket update, user-scoped the mutating bucket SQL, and uppercased the MCP region/country-places codes to match REST — each pinned by ATLAS-SVC-031…036 plus two MCP casing cases; see migration-graph.md's "Quirks fixed after the atlas fold".) authService followed (1497 lines, the biggest fold and the head of the auth → admin → oauth chain: the pure crypto half — backup-code hash/match/generate, stripUserForClient, key masking, the import-time DUMMY_PASSWORD_HASH timing equaliser and the avatarDir mkdir (both documented parity exceptions) — moved to the plain module auth.helpers.ts, while the DB half — toggles/app-config, register/login with the CWE-208 dummy-hash path, MFA setup/enable/disable/verify, the password-reset throttle+token flows with their two db.transaction() revocation blocks, API keys/settings, travel stats, MCP/ws/resource tokens, isDemoUser and the two token verifiers — folded into AuthService over DatabaseService + injected PermissionsService (ex permissions.bridge) and AtlasService (ex atlas.bridge, which died on schedule). The mfaSetupPending and per-email reset-throttle maps stay module-scoped (with the unref'd cleanup interval) so the bridge instance and the container singleton share them; the otplib window: 1 mutation runs at module top; require('../../../package.json') and avatarDir re-anchored one directory deeper — the only non-verbatim lines besides the two injection swaps. No MCP registrar existed and the plugin host never imported authService, so neither surface changed; the 15 in-container *.mcp.ts demo guards now inject AuthService (their modules import AuthModule) — except atlas.mcp.ts, which keeps a bridge import because AuthService injects AtlasService and the reverse module edge would close a cycle (places.mcp precedent). The 8-export auth.bridge.ts serves mcp/index.ts token verification, the three legacy tool registrars' isDemoUser, and the un-migrated adminService. Tests moved with IDs preserved: authService.test.ts → auth.helpers.test.ts, authServiceDb.test.ts → auth.service.test.ts (+ AUTH-BR-001…007 bridge delegation); auth.e2e converted DI-native — the 30-method whole-module mock died, login now runs real bcrypt and real audit rows; oidc.e2e switched its dead path-mock for a vi.spyOn(app.get(AuthService), …) instance stub.) oidcService followed (the frontier cash-in the auth fold predicted: a pure fold of the 508-line module into the existing wrapper OidcService over DatabaseService + injected AuthService — the resolveAuthToggles auth.bridge import became the injection, the first repoint-consumer of that bridge to migrate. No MCP registrar, no plugin-host import, and no bridge at all: nothing outside the container consumes the domain (day-notes/ trip-invite class), so the pendingStates/authCodes maps, their two sweep setIntervals, the single-slot discovery cache and the JWKS cache became instance state — the module-scope precedent (permissions/atlas-geo/auth maps) applies only where a bridge instance must share state, and none exists here; the sweepers start in the constructor and are cleared in onModuleDestroy, the one wire-invisible deviation. The uuid/bcryptjs lazy requires, the invite_exhausted reference-sentinel transaction (reshaped one line for DatabaseService.transaction) and every SQL string relocated verbatim; controller and its unit suite needed zero edits. Tests moved with IDs preserved: oidcService.test.ts → oidc.service.test.ts (OIDC-SVC-001…045, superseding the 18-case delegation-shim suite; 046–048 carry its wrapper cases); oidc.e2e swapped its whole-module path mock for vi.spyOn(app.get(OidcService), …) instance spies; the integration suite spies the four HTTP methods on the container instance while driving the real state maps on that same instance.) passkeyService followed (the last frontier member of the auth stack: the 364-line WebAuthn module folded into a new nest/auth/passkey.service.ts PasskeyService over DatabaseService + injected AuthService — its three auth.bridge imports resolved to this.auth.generateToken plus plain stripUserForClient/avatarUrl helper imports, and resolveWebauthnConfig stayed a plain services/webauthnConfig import at the time (it has since become the injected WebauthnConfigService, which also feeds auth.service's passkey_configured). No MCP registrar, no plugin-host import, and no bridge at all — both consumers were already in-container: PasskeyController swapped its import * shim for the injection, and AdminService swapped its adminResetPasskeys function import for the injected service (AuthModule now exports PasskeyService and AdminModule imports AuthModule — the todo→TripsService in-container precedent). No module-level mutable state existed to preserve: the challenge store is DB-backed (webauthn_challenges, single-use DELETE … RETURNING claim, 5-min TTL), so the fold is a plain stateless injectable — every SQL string, error string and the counter/login-bookkeeping transaction relocated verbatim. Tests: the legacy module had no service-level suite, so PASSKEY-SVC-001…030 were written fresh with the fold (characterization over a real :memory: DB, @simplewebauthn/server mocked at the ceremony-verdict boundary — the repo's first such mock); auth-guard.test.ts's PasskeyController block swapped its path mock for a constructor stub.) notificationService followed (the notifications fan-in, step 3 of the dependency-honest order: the send() dispatcher and the inAppNotifications.ts store folded together into the existing NotificationsService over DatabaseService + RealtimeService — the wrapper's in-app delegation became the real SQL, while the prefs matrix, the smtp/ webhook/ntfy transports, the channel registry and inAppNotificationActions stay plain-module imports (graph-classified infra helpers, complete with their registry⇄prefs cycle). A one-export notifications.bridge.ts (send) covered the outside-container consumers — scheduler's two cron requires, legacy adminService and memories/{unified,synology} (that bridge died 2026-08-10 with the scheduler migration; notifications.instance.ts carries the surviving cycle-dodge bridges) — and the six deliberately-lazy fire-and-forget import().then(({ send }) => …) sends in migrated Nest services (collab/collections/packing/reservations/trips/vacay, path-only repoints; kept lazy so a send can never block or cycle a domain module). In-container static consumers inject instead: AdminController's dev test send (AdminModule → NotificationsModule) and the plugin host (NotificationsService = PluginHostDepsFactory's 24th dep). The 5-tool legacy registrar + the notifications-in-app resource moved 1:1 to notifications.mcp.ts (no when: — the domain is core, not addon-gated). Tests moved with IDs preserved: notificationService.test.ts → notifications.service.test.ts (NSVC-001…019/NTFY-SVCB-/NSVC-PLUG-001…007, plus the NSVC-020 bridge pin), inAppNotificationPrefs.test.ts → notifications.inapp-prefs.test.ts (INOTIF-); ~18 suites repointed their path mocks/warm-ups to the bridge; admin.controller.test and the plugin-host suite converted theirs to constructor stubs; the module e2e went DI-native (real notifications DDL, prefs/transports still path-mocked).) adminService followed (the last Wave-5 god file and the first fold where recipe steps 2-4 were all no-ops or near-no-ops: no src/mcp/tools/admin.ts has ever existed — the "11 MCP consumers" figure carried in migrate.md / migration-graph.md predated the Phase-0 addons extraction, so no registrar moved, mcp/tools.ts / mcp/resources.ts / mcp-test-controllers.ts were untouched — and plugin-host-deps.factory.ts never imported the domain either (its addon reads already went through the DI-native AddonsService). The 851-line module folded into the wrapper AdminService over DatabaseService plus injected Settings/Addons/Passkey/Packing/Auth/Permissions/Notifications services: the auth.bridge (resolveAuthToggles), notifications.bridge (send) and permissions.bridge (getAllPermissions/savePermissions) imports all became injections, while PERMISSION_ACTIONS stayed a plain const import and the mcp/sessionManager deep import kept its anti-cycle comment. The pure + module-scoped half moved to admin.helpers.ts — compareVersions, utcSuffix, BCRYPT_COST, the import-time isDocker probe (a documented parity exception, auth.helpers precedent) and the 5-minute version cache, which stays module-scoped so the bridge instance and the container singleton share it. Ahead of the fold the 11 packing-template functions relocated to PackingService, which already owned all three template tables (saveAsTemplate writes every one of them) — that also resolved the admin-2 residual without a bridge, since packing.mcp.ts already injects the service; AdminModule gained PackingModule and PermissionsModule, both cycle-free. A 1-export admin.bridge.ts (checkAndNotifyVersion) served the only out-of-container consumer, scheduler.ts's daily cron (both died 2026-08-10 with the scheduler migration — VersionCheckJob injects AdminService). Four lines are non-verbatim, all path re-anchoring one directory deeper for nest/admin/ (rotateJwtSecret's data dir, the package.json version require, the websocket/demo-reset lazy requires) — both resolved paths verified against the emitted dist/ layout. Tests moved with IDs preserved (adminService.test.ts → nest/admin.service.test.ts, ADMIN-SVC-001…069 incl. the pre-existing 029/030 gap and duplicated 069, + ADMIN-BR-001 pinning the bridge and the shared version cache; versionNotification.test.ts → nest/admin.version-notification.test.ts, VNOTIF-001…007; the template cases rode along to packing.service.test.ts), and the module e2e went DI-native — its 3-method whole-module mock died, 6 cases became 15 over real SQL. A sibling DTO ratchet cleared all twenty AdminController allow-list entries — the largest single block — trading the three 'enabled must be a boolean' checks plus 'permissions object required' and 'Object body required' for the pipe envelope; the schemas are deliberately permissive wherever the service owns a bespoke 400 of its own.) Repeat these steps per service (next up: backupService / airtrail — per the dependency-honest order in migration-graph.md). This is a pure relocation — byte-identical SQL, statuses, bodies, and error strings. The plugin RPC host is no longer a bridge consumer: since Option A of src/nest/plugins/DI-MIGRATION.md it injects domain services via PluginHostDepsFactory, so a migrated domain adds exports: [XService] + a PluginsModule import instead of a bridge entry. Only the pre-app.init() MCP/OAuth mount still needs bridges — the module- cycle seams are folded, nothing on the websocket path imports one, and the crons all inject now (*.job.ts providers on scheduling/CronRegistrarService).
  1. Move the SQL into <domain>.service.ts as methods over an injected DatabaseService (this.db.all<T>/get<T>/run/prepare; multi-statement writes go through await this.uow.transactional(...) instead — see the root CLAUDE.md; strict constructor injection, no @Optional()). Preserve every quirk: falsy-coercion defaults (x || fallback, never ??), post-insert/post-update re-selects (no RETURNING), COALESCE semantics. If a controller already wraps the legacy functions, do not change the service's method surface. The module needs no imports: [DatabaseModule] — it's @Global.
  2. Add <domain>.bridge.ts next to the service only if non-Nest consumers exist (legacy MCP tool registrars, websocket — the plugin RPC host and the crons now inject instead, see above). It builds a module-level instance over the shared connection Proxy — new XService(new DatabaseService(db)), reinitialize-proof, same pattern as nest/todo/todo.bridge.ts — and exports the legacy function names 1:1. Container code injects the service; only outside-container code imports the bridge. When porting an MCP registrar, note the access: { group, mode } markers are typed against the scope-derived ScopeGroup union and boot-validated by trekMcpValidateAccess (src/mcp/nest-mcp-policy.ts) — an unknown group, or mode: 'write' on a read-only group (geo, weather), fails app boot. mode is typed the same way: it is the mode half of Scope (read | write | delete | share), fed into src/nest-mcp/types.ts through McpAccessModeRegistry exactly like the group registry. A scope that is neither read nor write — journey:share is the one today — gets a real marker, not a (ctx) => canX(ctx.scopes) predicate: predicates bypass the policy entirely and are invisible to the boot gate, so a scope typo in one would ship as a silent full-access tool. Reach for a predicate only when the gate genuinely is not a scope. (Design decision, settled with the tags pilot: MCP tools stay outside the container and use the bridge. The alternative — handing the Nest app to the MCP layer via app.get(XService) — was rejected: it would thread the container through mcpHandler + every tool registrar and force a Nest bootstrap into the container-less tests/helpers/mcp-harness.ts used by ~25 MCP suites.)
  3. Repoint non-Nest consumers — import-path-only diffs from services/<x>Service to nest/<domain>/<domain>.bridge; call sites unchanged.
  4. Delete the legacy service once grep -rn "services/<x>Service" src tests only hits the tests you're rewriting.
  5. Tests:
    • Move tests/unit/services/<x>Service.test.ts → tests/unit/nest/<domain>.service.test.ts, preserving case IDs. Construct the service directly — new XService(new DatabaseService(testDb)) — no TestingModule, no overrideProvider (repo convention). Add one delegation case per bridge export: the bridge sits under src/nest/**, inside the ≥80% coverage gate, and these cases pin it deterministically.
    • Convert the module e2e to the DI-native pattern (exemplar tests/e2e/trips.e2e.test.ts): temp-db DDL for the domain's tables, imports: [DatabaseModule, <Domain>Module], real SQL assertions. Keep only the vi.mock('../../src/db/database', …) — the auth guard still reads users through the singleton, and DatabaseModule's factory picks up the same mocked db. Drop the legacy-service mock entirely.
    • Suites that mocked the legacy module mock the bridge path instead — same factory shape, path-only change. (For the plugin host suite, plugin-host-deps.factory.test.ts, the domain becomes a constructor stub instead of a path mock.)
  6. Verify (from server/): npm run typecheck, test:unit, test:integration, test:e2e, lint:check, test:coverage.