Files
CatoandClaude Opus 5 095ece7a79 refactor: collapse to a modular monolith, with an identifier-first data model (#63)
* refactor: collapse four services and a workspace into one Next app

Four services, two of them stubs, is a distributed system for a product with
no users. The whole backend is deleted and the frontend moves to the
repository root, so there is one application, one package.json, one lockfile
and no pnpm workspace. Module boundaries are directories, not deployment
units.

Deleted:

  services/api-gateway     stub — routed to two other stubs
  services/matching        stub — scored candidates against found_items,
                           a table nothing has ever inserted into
  services/notification    stub — Redis subscriber
  services/reporting       the one real service (~1,650 LOC). Its Express
                           routes, controller and repository become route
                           handlers later in this branch; nothing it did is
                           being lost, but nothing it did was deployed either
  shared/types             a package that existed to share types across
                           process boundaries that no longer exist
  smoke-*.sh, dev.sh, generate-jwt.js, ws-client.js, test-connection.js

Redis goes with them. It carried pub/sub between the four services; with one
process there is nothing to publish between, and a broker whose job is
talking to yourself is a dependency with no job. Staff push becomes a
same-origin SSE stream later in this branch — REBUILD.md's "if it turns out
to be sufficient", and for one host and one process it is.

.env.development now sets both public URLs EMPTY rather than pointing at
localhost:3001 and :3003, which were the two deleted services. Empty means no
backend is configured, which turns on demo mode and makes the app run on
declared fixtures — the honest state until the route handlers land.

pnpm-workspace.yaml stays, with `packages: ['.']`, for two reasons worth
writing down. pnpm walks UP the tree looking for a workspace root, so without
this file an install run from a git worktree under .claude/worktrees/ silently
resolves against the PARENT checkout's workspace ("Scope: all 6 workspace
projects") and the install you verified is not the install CI performs. And
pnpm 11 reads allowBuilds from there, not from package.json.

CI drops to one install and one lockfile, and still calls `pnpm run verify`
verbatim.

check-tenant-ssot.sh is repointed at app/ components/ lib/ — and re-proved by
mutation rather than assumed, since a path-based grep gate passes vacuously
when its paths are wrong: dropping a file containing an operator name into
components/ makes it exit 1 naming that file.

Verified: `pnpm run verify` green, and `pnpm run build` produces all six
routes. Test count drops from 86 to 59 because the deleted service took its
27 validation tests with it. That is a real loss of coverage, and repaying it
with tests over pure domain logic is the next commit but one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NfPenJdSXVtN8SQ9wHG4Hp

* chore(deps): Next 16.3.4 and React 19, pinned to the fleet's major

REBUILD.md: "upgrade to the Next major used by the rest of the stack, and pin
it." fleetcrown and the other self-hosted apps are on 16.3.4; this was on 14
while already carrying eslint-config-next@16, which is a mismatched pair.

The v15/v16 breaking change is that request APIs are async-only: cookies,
headers, draftMode, `params` in layout/page/route/metadata files, and
`searchParams` in page files. This app uses none of them — checked, not
assumed — so no codemod was needed and nothing had to be awaited. The only
other change is the React major pin in eslint.config.mjs, which exists because
eslint-plugin-react's `version: 'detect'` calls an API ESLint 10 removed.

Verified on the new major: `pnpm run verify` green and `pnpm run build`
produces all six routes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NfPenJdSXVtN8SQ9wHG4Hp

* feat(domain): pure matching, lifecycles, retention and tokenisation

The domain rules move into lib/domain/ as pure functions over plain data — no
database, no HTTP, no clock, no framework. Everything here is unit-testable
without standing anything up, which is why there are 82 new tests.

MATCHING is identifier-first, then spacetime, then description — and the order
is enforced by the TYPE of the result rather than by the size of a weight. A
match has a tier, and only certain signals can raise it:

  identifier   exact agreement on a strong identifier. Nothing else, ever.
  strong       a weaker identifier, or same journey plus same category.
  plausible    same journey, or same line and day plus same category.
  weak         anything else that agrees at all.

Description, colour and brand contribute POINTS, which order results inside a
tier, and carry no tier floor whatsoever. That is the enforceable form of
"description must never outrank an identifier or a trip match": not a
coefficient someone can retune, but unreachable by construction — and
`matching.test.ts` asserts it directly, including a property test that adding
description signal to any pair leaves the tier exactly where it was.

Proved by mutation on a copy: giving the description branch `tierFloor:
'strong'` turns three tests red, including that property test.

Why be this severe about description: agreement weight follows the RARITY of
the agreeing value and "black" is not rare (Fellegi & Sunter 1969); two random
words already sit at near-perfect cosine similarity (Ethayarajh 2019); generic
vocabulary collapses into a dense blob (Li et al. 2020); and in high dimensions
a few points become everyone's nearest neighbour (Radovanović et al. 2010), so
"a generic report matches everything" is geometry rather than bad data. There
is no embedding here and no model output anywhere in the matching path — every
number is arithmetic a person can re-do, and all of it is reported in a
breakdown, because staff and passengers have to see WHY two records were
linked. Conflicts (disagreeing journeys, a find predating the loss) are
surfaced separately and never silently lower a tier: people mistype train
numbers, and a matching IMEI should still win while a human sees the problem.

IDENTIFIERS distinguishes strong kinds (imei, serial, registration) from weak
ones. An engraving is deliberately NOT strong: it is visible to whoever is
holding the object, so it cannot distinguish an owner from a finder, which is
the only job that matters when someone is claiming property. Four IBAN digits
are one in ten thousand — a strong hint beside a matching journey, nothing like
proof alone. IMEI is the one kind that verifies itself, via Luhn, so it can be
marked verified without asking anybody; the test works the checksum by hand
rather than trusting a value this implementation produced.

LIFECYCLES are transition tables, not status strings. Two deliberate edges:
`submitted -> matched` and `not_found_onboard -> matched`, because a report
filed after the trip must still be matchable and "the crew looked and it wasn't
there" is not the end — someone may hand it in at the terminus. There is NO
path from a claim being `opened` to `upheld`; every claim passes through a
challenge, which is the whole point of keeping found-item details private.
`canRelease` reports preconditions and always demands a named human, because
handing over property is a decision with legal effect and Art. 21 revDSG gives
a person the right not to be subject to one taken solely automatically.

RETENTION keeps two dates apart that are easy to conflate. `disposalEligibleAt`
is statute — VPB Art. 77 Abs. 4 (SR 745.11), three months, one month at CHF 50
or less. `deleteAfter` is OUR POLICY and says so in the constant itself, because
revDSG requires purpose-limited retention and names no period. Writing them as
one field would quietly assert that Swiss law tells us when to delete a phone
number. A deadline can only ever move earlier, so closing and reopening a case
cannot keep personal data alive indefinitely.

TOKENISATION avoids two traps. `\w` and `\b` are ASCII in JavaScript, so
splitting on `\W+` cuts "Schlüssel" into "schl" and "ssel" — every split here
uses Unicode property escapes. And the stopword list is applied for all four
languages at once regardless of the text's language, because a list with a hole
makes correct text look foreign: if German function words are dropped and
Italian ones are not, an Italian description scores higher for reasons that
have nothing to do with the object.

One test here failed for the right reason and was rewritten rather than
adjusted: it asserted the same sentence yields equal token counts in all four
languages. It does not, and no stopword list can make it — German says
"Rucksack" where French says "sac à dos". The property that actually matters is
coverage, so that is what it now asserts.

Verified: `pnpm run verify` green, 141 tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NfPenJdSXVtN8SQ9wHG4Hp

* feat(db): identifier-first schema, Drizzle migrations, deny-by-default grants

Replaces database/init/*.sql — raw SQL applied by the Postgres container's
entrypoint, which runs ONCE on an empty volume and never again. That is a
bootstrap, not a migration system: there was no way to evolve the schema of a
database that already had data in it.

THE MODEL

`identifiers` is the point of the rebuild. One table for both halves, with two
nullable foreign keys and `CHECK (num_nonnulls(report_id, found_item_id) = 1)`
— which keeps referential integrity real, since a polymorphic item_id cannot
be a foreign key to anything, while leaving ONE index on (kind, value). That
index is what makes an identifier lookup the first and cheapest thing the
matcher does. `value` is the normalised form; the text the user typed is kept
separately in value_display and never compared, because comparing a raw value
against a normalised one would silently disable the strongest signal in the
system.

`matches` persists a jsonb `breakdown` and `conflicts`. The breakdown is not
decoration, it is the score — deterministic arithmetic, one entry per
contributing signal, kept so staff and passengers can see why two records were
linked months later.

Claims are an assertion plus a challenge plus a resolution, in three tables.
`claim_resolutions.resolver_name` is NOT NULL: Art. 21 revDSG gives a person
the right not to be subject to a decision with legal effect taken solely by
automated processing, and handing over property is exactly that — so there is
no way to record a resolution without recording the human who made it.

`reward_offered` is gone and a test keeps it gone. VPB Art. 77 Abs. 2 bars a
transport operator from claiming a finder's reward at all.

The rail-native model is kept and sharpened: journeys carry BOTH the SJYID
(the national join key, shared by GTFS, Ist-Daten and the formation API) and
the train number a passenger can actually read off a board. `formations`
exists because the upstream API has no history — it answers only for today
through today+3, with no archive — so a formation not captured on the day is
unreconstructable, and a table plus a daily harvester is the only shape that
can work.

DENY BY DEFAULT

REBUILD.md asks for RLS plus `REVOKE ALL` from `anon` and `authenticated`.
Those are Supabase roles; this is plain Postgres on one host with no PostgREST,
so creating them would have proved nothing. The intent is implemented instead:
REVOKE ALL from PUBLIC, ENABLE *and FORCE* row-level security on all 14 tables
(an owner bypasses RLS unless it is forced), an application role that owns
nothing, and grants enumerated one table at a time — never `ON ALL TABLES`,
which would silently cover whatever is added next.

Verified live against the container, not asserted:

  fundbuero_app SELECT reports          -> 1 row
  fundbuero_app UPDATE claim_resolutions -> permission denied
  fundbuero_app DELETE audit_events      -> permission denied
  fundbuero_app INSERT INTO stops        -> permission denied
  a role with only schema USAGE          -> permission denied on reports

Reference data imported from open data is read-only to the app;
claim_resolutions and audit_events have no UPDATE and no DELETE, because a log
the application can rewrite is not a log.

db/__tests__/rls.test.ts catches the drift that actually happens — a table
added to the schema and forgotten in rls.sql — since CI has no database to
catch it by running anything. Proved by mutation, twice: adding a table makes
it fail, and reintroducing a reward column makes it fail. It also had to be
made comment-blind, because on its first run it failed on its own prose: the
files EXPLAIN their rules, so rls.sql contains the words "GRANT ... ON ALL
TABLES" in the comment forbidding it, and schema.ts contains "reward" in the
comment saying there is no reward column.

TRIP SUGGESTION

lib/domain/trip-suggestion.ts ranks candidate journeys from a place and a time
so a passenger never types a train number. Pure, so the rule deciding what
they see first is a readable function rather than an ORDER BY nobody reviews.
A journey slightly BEFORE the stated time outranks one equally after it,
because people notice a loss after boarding and report the time they noticed.
`isUsableSuggestion` refuses to show a list the passenger cannot tell apart —
two unnumbered suburban services on the same line are two rows and one choice,
and showing them is a quiz, not a suggestion.

ONE COMMAND EACH, VERIFIED ON A CLEAN VOLUME

  docker compose up -d
  pnpm run db:setup    # migrations, then rls.sql, in that order and for a reason
  pnpm run db:seed

The seed writes fixtures and says so: every reference is prefixed DEMO- and
every stop and journey demo:, so a fixture can never be mistaken for imported
data or counted in a real number. DEMO-F-0001 shares an IMEI with DEMO-R-0001
and must outrank DEMO-F-0002, which agrees only on words — the matching rule,
visible in the data.

The README is explicit that this does NOT yet mean the app reads the database:
there are no route handlers, so the UI still renders fixtures whether or not
Postgres is running. Seeing data in the browser is not evidence.

Verified: `pnpm run verify` green, 163 tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NfPenJdSXVtN8SQ9wHG4Hp

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 12:11:58 -07:00

56 lines
1.9 KiB
TypeScript

/**
* Apply migrations, then lock the database down.
*
* Order matters and is the whole reason this is one script rather than two
* commands in a README: db/rls.sql grants on tables by name, so it has to run
* AFTER the migration that creates them. Run the other way round it fails
* loudly, which is fine — but run only halfway, it leaves a database whose
* tables exist and whose application role cannot read them, and that failure
* surfaces as a `permission denied` at the first request rather than here.
*/
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { drizzle } from 'drizzle-orm/postgres-js';
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import postgres from 'postgres';
async function main() {
const url = process.env.DATABASE_URL;
if (!url) {
console.error(
'DATABASE_URL is not set.\n\n' +
' docker compose up -d\n' +
' export DATABASE_URL=postgresql://postgres:postgres@localhost:5433/sbb_fundbuero\n' +
' pnpm run db:setup\n',
);
process.exit(1);
}
// max: 1 — a migration runner that opens a pool can interleave statements
// across connections and deadlock against its own locks.
const sql = postgres(url, { max: 1 });
try {
console.log('→ applying migrations from db/migrations');
await migrate(drizzle(sql), { migrationsFolder: join(process.cwd(), 'db', 'migrations') });
console.log('→ applying db/rls.sql (deny by default, then explicit grants)');
const rls = readFileSync(join(process.cwd(), 'db', 'rls.sql'), 'utf8');
// The file is one BEGIN/COMMIT block and contains DO $$ ... $$ bodies, so
// it must go to the server whole. Splitting on ';' would cut the function
// bodies in half.
await sql.unsafe(rls);
console.log('✓ schema and grants applied');
} finally {
await sql.end();
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});