17 Commits
Author SHA1 Message Date
CatoandClaude Opus 5 291fec94ac A website with an evidence base, and the app behind /app (#76)
* feat(site): a website with an evidence base, and the app behind /app

The repository was one route: `app/page.tsx` rendered `<ReportFlow />` and
that was the whole product. There was nothing to send anyone — no explanation
of what the thing is, no argument for why it should exist, and no way to look
at the reasoning without reading the source.

This adds the website, and puts the evidence under it rather than beside it.

WHAT THE SITE ARGUES, AND WHY IT CHANGED

The pitch used to be "report within 30 minutes and recovery jumps above 70%".
That number could not be sourced anywhere, and two findings contradict the
story it tells. The incumbent (RUBICON Nova Find, in service since 2004)
re-matches open loss reports against later finds continuously, so a report
filed on day three is not penalised — "report fast or lose it forever" was
never true. And the operator's own figures show roughly 180,000 loss reports
chasing roughly 120,000 handed-in items: the shortfall is not a matching
failure, it is items that never reach the operator at all.

So matching is the part that already works, and speed is not the constraint.

Cohn et al. (Science, 2019) turned in over 17,000 wallets across 355 cities in
40 countries. Return rates ROSE with the money inside — 40% empty, 51% with
money, 72% with a large sum — the opposite of what self-interest predicts. The
detail that is almost always dropped when that study is cited is the one that
matters here: every wallet contained a business card with the owner's email
address. It measures what people do WHEN A CHANNEL TO THE OWNER EXISTS.

A jacket on a seat has no business card. That is the gap — not honesty, not
matching speed — and it is a claim the literature actually supports.

STRUCTURE

- `(site)` and `(app)` route groups. The app keeps its 430px phone frame; the
  website gets a full-width shell. Both draw from the same tokens. The root
  layout no longer imposes `.mobile-container` on everything.
- `/` landing, `/how-it-works`, `/research`; the report flow moves to `/app`,
  the crew board stays at `/staff`.
- 45 message keys across all four catalogues. de/fr/it/en, no exceptions —
  a missing key is a compile error here by design.

THE CLAIMS ARE DATA, NOT COPY

`lib/research.ts` holds every empirical claim as a typed entry that carries
its own source or is typed `assumption`. The pages map over it; no figure is
typed into a paragraph. AGENTS.md rule 1 says never state a number without a
citable source — that rule now fails the build (`research.test.ts`, 20 tests),
including a guard that the 30-minute claim stays OUT of the citable set and
that the wallet study's contact channel stays on the record.

`lib/capabilities.ts` does the same for rule 2. Each capability names the file
that would have to exist for its built/designed label to be true, and the test
checks the filesystem in both directions: relabelling passenger notification
"built" fails, and so does shipping it while the page still says "designed".
Both proven by mutation.

THREE THINGS THE GATES CAUGHT

The contrast test rejected the step numeral at 1.17:1 — doing its job. But it
also revealed that its own premise had expired: it checks every text token
against white and milk, because those were the only surfaces text sat on until
this commit added a charcoal band. A grey chosen there would have been checked
against the wrong background. So the dark surface and its permitted
foregrounds are declared together in globals.css and a third property reads
them back out; a fourth modifier added later is covered automatically.

The tenant guard rejected two operator names in `lib/research.ts` — inside
published article titles. A citation title is a quotation, and paraphrasing it
to satisfy the guard would make the reference not match the article it points
at, which breaks rule 1 to satisfy rule 7. The exemption is scoped to one file
AND one field; a claim, a comment or a publisher naming an operator still
fails, and so does the same title in any other file. Five tests prove both
edges by running the real script against a fixture tree.

Those fixtures then tripped the guard themselves — a directory-scanning check
reading its own test data. They live under `test-fixtures/` now, outside the
scanned tree, rather than exempting `__tests__` and putting a real hole in the
guard to accommodate a test.

`pnpm run verify` green: 274 tests, 19 suites. Production build green.

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

* fix(site): the evidence speaks German, and the logo stops disagreeing with the page

Three defects, all of which only a browser could find. The build was green for
every one of them.

THE EVIDENCE RENDERED IN ENGLISH

`lib/research.ts` stored its claims as English sentences, and the German page
rendered them verbatim: "Share of handed-in items reunited with their owner"
under "Das Problem ist nicht das Zuordnen." Nothing failed, because nothing
was watching — the repository's rule that no string lives outside a catalogue
had never been applied to the evidence module.

`claim` and `limit` are `MessageKey` now. `MessageKey` is derived from the
German catalogue, so an evidence entry whose claim has not been translated
into all four languages does not compile. 72 keys added; the claims render in
de/fr/it/en, checked live.

`value` was carrying English too — "~180,000 reported / ~120,000 found" is a
sentence fragment inside a field the type system treats as language-neutral,
and no catalogue can reach it. Values are digits and units only now, with a
test that rejects any word of two letters or more.

The content guards moved with them. They used to read one English field;
they now resolve every claim through all four catalogues, because the banned
"30 minutes / 70%" number could return through the French copy — the one
nobody rereads — and the old guard would not have looked.

THE LOGO SAID ONE OPERATOR, THE PAGE TITLE SAID ANOTHER

`SiteHeader` is a client component and read `tenant.wordmark` directly. On a
build made without `NEXT_PUBLIC_TENANT` and then RUN with it set, the header
rendered the neutral house wordmark while the title, footer and palette all
named the livery tenant.

`NEXT_PUBLIC_*` has two origins: Next inlines it into the client bundle at
BUILD time, and a server component reads it from the process at REQUEST time.
They agree only when build and runtime were handed the same value — which a
deploy that configures the unit rather than the build step does not
guarantee. No error, no warning, two operators on one screen. And of all the
values to get this wrong on, the tenant is the worst: failing open to someone
else's brand is the one failure mode that carries real cost.

The tenant is resolved on the server and passed down. A component handed a
value cannot disagree with the server about it, whatever the bundler inlined.
`tenant-client-boundary.test.ts` scans for the import rather than the symptom,
because the symptom needs a build/runtime combination that `pnpm run dev`
never produces. Proven by mutation: restoring the import fails the test.

Verified under the exact condition that broke it — built with no tenant set,
served with one. The wordmark now matches the title, and the house wordmark
appears in no client chunk at all.

THE HEADER FELL OFF THE PHONE

At 390px the two nav links shredded into three lines and the action button was
pushed past the right edge. The header wraps now: wordmark and action on the
first row, nav full-width below, one row again from `sm` up. One markup, no
duplicated nav, no JavaScript. No horizontal overflow at 320px on any page.

Also: the back-link out of `/app` was rendering in the gap between the form
and its sticky action bar, reading as a stray link inside the form. It sits at
the top now, where it reads as a way out.

`pnpm run verify` green: 279 tests, 20 suites.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-11 08:42:00 -07:00
CatoandClaude Fable 5.1 5ad6b87984 feat(retention): the purge reaches the box's timer as POST /api/cron/purge (#72)
The purge existed as `pnpm run db:purge` and nothing ran it. It could not:
the production release is a Next standalone build with no `scripts/` and no
`tsx`, so "install a daily cron" had nowhere to stand. The fleet's mechanism
for scheduled jobs is a systemd timer calling a route on localhost with a
bearer secret (fleetcrown `install-app-crons.sh`, appcron-<app>-<job>), with a
Telegram alert on failure — so the purge is now such a route.

- lib/server/purge.ts: the purge, extracted so the script and the route are
  two callers of one function rather than two purges.
- lib/server/auth.ts: authoriseCron — same fail-closed shape as staff access
  (503 unconfigured, 401 wrong, constant-time), bearer form only, and its own
  secret so a leaked crew token cannot trigger deletions.
- app/api/cron/purge/route.ts: POST, counts in the body, references in the
  log, 500 on failure so the timer unit fails and the alert fires.
- .env.example: replaced the stale microservice-era ports with the variables
  the code actually reads.
- Docs describe the mechanism; the TODO item stays OPEN until the timer has
  fired with an HTTP 200 on the box.

Tests: 225 -> 237.


Claude-Session: https://claude.ai/code/session_01NfPenJdSXVtN8SQ9wHG4Hp

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 00:11:10 -07:00
CatoandClaude Opus 5 cf945ec57e feat(retention): the purge job that makes delete_after mean something (#67)
Every table holding personal data has carried a `delete_after` column since the
schema landed. A deadline nobody reads is a paragraph with extra steps, so this
is the job that reads it.

Proved against a real database rather than asserted:

  nothing due          -> "0 reports, 0 found items, 0 contacts", nothing gone
  one report expired   -> deleted BY NAME (DEMO-R-0001), its identifiers
                          cascaded from 2 to 1, found items and contacts
                          untouched

Two things it gets right that a first draft would not:

The orphan clause carries an HOUR'S GRACE. `createReport` inserts the contact
row first and the report a moment later, outside a transaction — a purge
landing in that gap would delete a contact whose report was about to reference
it. An hour is far longer than that window and far shorter than any retention
period.

Audit events are deliberately NOT purged. They record that a decision was made
and by whom, they carry no contact details, and a log that erases itself is not
a log. Changing that should be a decision, not a side effect of this job.

The first version threw on every run: postgres-js rejects a Date inside a raw
sql template ("The 'string' argument must be of type string … Received an
instance of Date"). It is ISO strings with an explicit ::timestamptz cast now.
Worth noting how that would have failed in production — a cron whose script
throws is a cron that never purges anything, and nothing else in the system
would have noticed. It was caught by running it, not by reading it.

TODO.md keeps the remaining half honest: the script exists and works, and
nothing runs it on a schedule yet. Until a cron does, retention is a column and
a good intention.

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


Claude-Session: https://claude.ai/code/session_01NfPenJdSXVtN8SQ9wHG4Hp

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 16:11:57 -07:00
CatoandClaude Opus 5 caffb76522 feat(gtfs): import the real Swiss timetable, and bind a report to a real journey (#65)
* feat(i18n): four typed catalogues, with a ratchet on hardcoded prose

Switzerland is quadrilingual and this app had one language. `lib/labels.ts`
was the SSOT for UI text but held only German — a single-language SSOT, which
is not i18n.

German is the REFERENCE locale: `MessageKey` is derived from it and the other
three are typed `Record<MessageKey, string>`, so a missing French string is a
COMPILE ERROR rather than a key rendered raw to a passenger on a train. That
is the whole argument for TypeScript over JSON here — a JSON catalogue drifts
in silence and the failure surfaces to the person least able to fix it.

The tests cover the three ways a catalogue rots while still typechecking:

  - a key present but EMPTY, which renders as nothing
  - a catalogue COPIED from German and never translated (asserted as: fewer
    than 20% of strings may be byte-identical to the German, since "E-Mail" is
    legitimately "E-Mail" but ninety of them are not)
  - a key that renders as itself

Accept-Language resolution takes region tags, because `de-CH` must select `de`.
Every Swiss browser sends one, so getting that wrong routes all of them to the
default — and the default is German, so it would have looked like it worked.
Romansh resolves to the default and is a documented gap, not a crash.

There is no module-level "current locale". The locale is passed in, because
the server renders for whoever is asking and a global is wrong the moment two
requests overlap.

The last test is a RATCHET, not a wish: 8 components hold literal prose today,
and it fails if a ninth appears, naming the files. Asserting zero now would
mean deleting or skipping the check, and a skipped check is one nobody
un-skips. Proved by mutation — a ninth component makes it fail with the list.

The catalogues are written but not yet wired into any component; that is the
UI rewrite, and the ratchet is what stops the debt growing in the meantime.

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

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

* feat(gtfs): import the real Swiss timetable, and bind a report to a real journey

Task 4. Run against the actual 248 MB feed, not a fixture:

  services active on 2026-09-10: 10125 (+202 / -35242 by exception)
  stations: 10, platforms mapped: 223
  trips: 212313 active of 2174758 total
  ✓ imported 6704 journeys and 9034 calls
    from 35,143,405 stop_time rows, feed version 20260905

Then, end to end: a passenger named a stop and a time, picked a train from the
suggestions, and the report was stored against
ch:1:sjyid:100001:19629-001 — the canonical national journey identifier, on a
real operating day. A found item recorded on that journey matched it at tier
`identifier`, and the persisted breakdown reads:

  imei agrees (both verified)                              100
  same journey ch:1:sjyid:100001:19629-001@2026-09-10       30
  same coach 7                                             15
  both electronics                                          5
  both schwarz                                              2

Description contributed NOTHING — "Handy" and "Mobiltelefon" share no tokens —
so the link is carried entirely by the identifier and the journey. That is the
design working on real data rather than on a fixture built to flatter it.

WHY IT IS BOUNDED

The feed is 3.83 GB open and stop_times.txt alone is 3.07 GB. Importing
everything, for every service day, is hundreds of millions of rows to answer
"which trains called here around then". So the import takes a date and a set of
stations. It is a nightly job, not a request path.

Nothing is extracted to disk — `unzip -p` streams one member at a time.

THINGS THAT WOULD HAVE BEEN WRONG AND LOOKED RIGHT

- **calendar_dates.txt is a LAYER, not a filter.** −35,242 services on this one
  day are removed by exception. Filtering instead of layering would have
  imported tens of thousands of trains that do not run, and every one of them
  would have looked plausible.
- **GTFS times exceed 24:00:00.** A night train at "25:30:00" under the 8th
  departs at 01:30 on the 9th. `new Date('…T25:30:00')` is Invalid Date and a
  naive modulo puts it a day in the past — the difference between finding
  someone's bag and telling them no such train ran.
- **The header carries a UTF-8 BOM.** Without stripping it the first column is
  named "trip_id", every lookup returns undefined, every row parses with an
  undefined id, and nothing errors anywhere.
- **Station names contain commas.** "Zürich, Bahnhofstrasse" is one CSV field.
  Splitting on `,` breaks precisely the tram and bus stops that are most of
  Switzerland.
- **A call is recorded against a PLATFORM, a passenger names a STATION.** Every
  row carries `didok`, the UIC, so grouping by it is exact and needs no string
  surgery on the `Parent…` convention.
- **stop_times.txt being grouped by trip_id is an assumption about someone
  else's file**, so it is CHECKED at runtime: a trip reappearing after its group
  closed aborts the import rather than silently importing half a journey.

All of the above are pure functions in lib/domain/gtfs.ts with 20 tests, so
none of them needs a 248 MB download to exercise.

A BUG ONLY REAL DATA COULD SHOW

/api/trips/suggest returned "no journeys found" at Zürich HB, which has 275
calls in a two-and-a-half hour window. It fetched a WIDER window than it ranked
and ordered ascending with LIMIT 50 — so it got the 50 EARLIEST rows, all far
enough from the stated time that the ranker rejected every one. The seed's
three journeys could never expose this. The query now orders by PROXIMITY to
the stated time, so the limit truncates the least relevant rows instead of the
most relevant ones.

The real data also corrected two of my own comments: 8503016 is Zürich
Flughafen, not Oerlikon, and 8502113 is Aarau, not Olten.

THE ONE IRREVERSIBLE GAP, STATED PLAINLY

scripts/harvest-formations.ts archives coach-level formations, and it has NEVER
RUN. The formation API answers only for today..today+3 and there is no archive
— four candidate endpoints probed, all 404 — so a loss report, always filed
after the trip, can only resolve "I was in coach 7" against a formation
captured on the day. Every day the harvester does not run is a day of coach
data that cannot be reconstructed from any source, ever.

It needs a free self-service key from api-manager.opentransportdata.swiss that
nobody has registered, and it EXITS NON-ZERO without one rather than logging a
shrug: a harvester that silently does nothing is indistinguishable from one
working on a quiet day. TODO.md carries the registration as its own section
because it is the only item whose cost grows while it waits.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 12:11:31 -07:00
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
CatoandClaude Opus 5 c035de6e12 docs: replace three fabricated statistics with sourced ones (#62)
The README asserted, with no source:

  1.2 million items lost annually in Swiss public transport
  ~25% recovery rate
  >70% recovery when reported within 30 minutes

All three are wrong. Two are wrong in the direction that flattered this
project, and the third — the one the entire product rested on — appears to have
been invented; searching for it returns only content-marketing pages that cite
nothing and contradict each other.

What is actually true, now cited inline:

  ~130,000 items handed in at SBB in 2024, ~7,000 more than 2023
  ~60% returned to their owners (2024); 52.3% in 2016
  ~120,000 items found against ~180,000 loss reports filed

So the incumbent is not broken — RUBICON's Nova Find has run SBB's service
since 2004 and already re-matches open reports against later finds, meaning a
report filed on day three is not penalised. But the gap between 180,000 reports
and 120,000 found items is real and is a *different* problem: items that never
reach the operator at all.

The 30-minute claim is replaced with an explicitly labelled unverified
assumption, argued from mechanism rather than from a number nobody can source —
the vehicle reaches its terminus in 10-30 minutes, turnaround cleaning takes
5-15, another passenger can take the item at any moment. The README says in
those words that we know of no published evidence for it, and that
time-to-report is therefore instrumented rather than asserted.

Also in the README: a table stating for every capability whether it is
implemented, a fixture, or an assumption — including that recording a found
item, matching, claiming, photo upload and staff authentication do not exist;
what Swiss open transport data does and does not provide; and the removal of an
MIT badge that pointed at a LICENSE file the repository does not contain.

Docs consolidated per the rebuild brief:

  AGENTS.md      one file, load-bearing decisions plus a must-not-do list;
                 CLAUDE.md is now a symlink to it
  TODO.md        new — launch blockers / security / regulatory / later
  AGENTS_SYNC.md deleted, with PROMPT.md, TASK_QUEUE.md, ralph.sh, the Makefile
                 and the Cursor-era coordination scripts. They coordinate
                 through files that no longer exist, name models that no longer
                 exist, and the Makefile drove npm in a pnpm repo.

Two security findings verified while reading, now tracked in TODO.md:
`services/reporting/src/middleware/auth.ts:44` falls back to a hardcoded
'your-secret-key' when JWT_SECRET is unset, and `/staff` has no authentication
of any kind.

docs/ANALYSE_UND_VORSCHLAG.md is kept, not deleted — its analysis is the most
accurate thing in the repository and its figures match the vendor's. Four
claims in it were wrong and are corrected in place: live train positions are
NOT available (GTFS-RT carries delays and cancellations, not vehicle
positions), formation data exists only for today through today+3 with no
archive, the express search costs CHF 75 since 1 January 2026 rather than
CHF 50, and its international comparisons are unsourced and now say so.

pnpm run verify green — 86 tests, tenant SSOT clean.


Claude-Session: https://claude.ai/code/session_01NfPenJdSXVtN8SQ9wHG4Hp

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 09:11:22 -07:00
CatoandClaude Opus 5 0627dd66d7 chore: rename to sbb-fundbuero, delete k8s and the static mock-ups (#61)
The project is now "SBB Fundbüro" and moves to sbbfundbuero.orangecat.ch.
Renamed mechanically: the pnpm scope (@sbb-lost-found → @sbb-fundbuero), the
Postgres database name, the deploy target, the site URL defaults, and the
product name in the tenant SSOT (both tenants — "Fundbüro" is a common noun,
not anyone's trademark, so the neutral tenant keeps a neutral name).

Deleted in the same pass because they are dead weight the rebuild has no use
for, not because of the rename:

  k8s/          Six manifests for a cluster that does not exist. This runs on
                one host behind Caddy. `k8s:deploy` went with them.
  demo/         Static HTML mock-up, superseded by the real frontend.
  mobile-demo/  Three more of the same.

Checked before deleting: nothing in the repo references demo/ or mobile-demo/
— no import, no route, no workflow, no doc link. `pnpm run verify` is green
(86 tests, tenant SSOT clean).

The historical record is left alone: comments elsewhere in the fleet that
mention sbb-lost-found describe things that happened under that name.


Claude-Session: https://claude.ai/code/session_01NfPenJdSXVtN8SQ9wHG4Hp

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 08:41:50 -07:00
baf9434f1e chore: pnpm — the fleet has one package manager (#46)
* chore: pnpm — the fleet has one package manager

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn

* fix(types): declare @types/cors and @types/pg — pnpm does not hoist phantom deps

---------

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-04 00:40:21 +00:00
GandClaude Opus 5 e20933ad95 chore: add a formatter (#33)
* chore: add a formatter, matching the style this repo already writes

singleQuote=true was chosen by counting this repo's own
imports, not by fleet decree. The fleet is genuinely split and the two repos
that already had a .prettierrc disagreed with each other, so there was no
standard to restore. Quote style does not cross repo boundaries; having a
gate does.

Markdown is ignored for now — prettier rewraps prose, which would bury the
real diff.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* style: format with prettier (86 files)

Mechanical. No behaviour change. This SHA is listed in
.git-blame-ignore-revs so `git blame` skips it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore: teach git blame to skip the reformat

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(demo): close the body tag, and format the rest

The formatter refused to parse demo/index.html, which turned out to be a real
defect rather than a prettier quirk: head closes at line 29, body opens at 30,
and the last tag before </html> was a second </head>. The document never closed
its body. Browsers paper over this; a parser does not.

Also formats two service entrypoints the reformat pass had left alone.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 10:55:26 +00:00
GandClaude Opus 5 f9776b47bc ci: call the central auto-merge sweep instead of carrying a copy (#16)
auto-merge-sweep.sh was copied into 22 repos and drifted into EIGHT distinct
versions, 245 to 404 lines. Three of them independently grew different fixes for
real outages, and each fix reached only the repo that wrote it:

  evig, revampit   infra-failure detection + re-run. An Actions incident left
                   main "failure" with no failed job at all; 11 PRs stranded
                   for roughly 14 hours.
  fleetcrown       DEADLOCK naming — a red base with the repairing PR sitting in
                   the queue was indistinguishable from "nothing to merge".
  the other 19     neither.

Nothing could carry a fix across, so every repo waited to hit each outage
itself. This repo now calls the canonical sweep in maonakamoto/dotfiles, and the
local copy is deleted.

The canonical is the union of the three, built on the variant ten repos were
already running rather than on the longest one — the 404-line variant is missing
the step-summary reporting the 296-line one has, so "take the biggest file"
would have silently deleted working behaviour. The merge was 106 insertions and
zero deletions: nothing can be lost by adopting it.

The triggers stay in this file because they genuinely are per-repo: workflow_run
must name the CI workflow exactly, and that name differs across the fleet.

Two details that are silent when wrong, both found by piloting rather than
reasoning:

  rearm_workflows is SPACE-separated. The sweep word-splits it; a comma makes
  one bogus token, every dispatch fails, and the only symptom is that nothing
  deploys — while the sweep still exits 0 and reports a successful merge.

  permissions are declared on the CALLER as well. A called workflow's token is
  capped by what the caller grants, so relying on the callee's block alone can
  hand it a read-only token; the sweep would then merge nothing while exiting 0,
  which is indistinguishable from having nothing to merge.

Verified before this rollout: the canonical ran end to end in dotfiles' own CI,
and the reusable-workflow path ran end to end in the pilot repo (s-ink).

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 13:18:24 +00:00
GandClaude Opus 5 7bbb018683 feat(tenant): make the operator configuration, not code (#11)
The app was written for one operator and said so in 609 places — token
names (--sbb-red), class names (.header-sbb), copy, metadata, types and
the vehicle-operator union. Re-skinning it meant a find-and-replace
across the codebase, which is not a product.

Branding is now expressed in exactly two files, and switching operator is
one environment variable:

    npm run build                          # Nordbahn (neutral house brand)
    NEXT_PUBLIC_TENANT=sbb npm run build   # SBB livery, same binary

  frontend/lib/tenant.ts      wordmark, legal name, product name, locale,
                              operator code, theme colour
  frontend/app/globals.css    palette + font, one :root[data-tenant=...]
                              block per operator

<html data-tenant> is set once in layout.tsx and every colour token keys
off it, so the palette flips at runtime from a single attribute — verified
in a browser via getComputedStyle: --brand goes #eb0000 -> #0b4f8f and the
header gradient, icon tiles, progress bar, primary button, active nav item
and alert badge all follow. Nothing kept a hardcoded red, which is the
evidence that the token rename is complete.

Token names are now semantic rather than tenant-named: bg-sbb-red became
bg-brand (the brand colour is whatever the tenant's is), and the shared
neutral/functional palette became app-*. That was the actual defect — a
token named after a company cannot be re-themed, only renamed.

Trademark safety, because a pitch build is indistinguishable from the real
product and that is the risk:

  - a tenant with isConcept: true renders "Unabhängiges Konzept — kein
    offizielles Produkt von <name>" on every screen and emits
    robots: noindex, nofollow;
  - the neutral tenant is the default, including when NEXT_PUBLIC_TENANT is
    unset or misspelled. Failing open to someone else's trademark is the one
    failure mode with real cost, so resolveTenantId falls back to neutral.

Enforced, not documented: scripts/check-tenant-ssot.sh fails if an operator
name appears outside those two files, and runs inside npm run verify.
Negative-tested — it was confirmed to fail on an injected reference before
being trusted, and it caught two real leaks while writing this (stale
comments, and a comment in the notice component itself).

Station names such as "Basel SBB" are left alone: those are place names, not
branding, and renaming them would make the demo data wrong.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 12:34:17 +00:00
G fd772205b9 fix(ci): declare the failing-job list before the branch that can skip it (#10) 2026-08-07 09:59:56 +00:00
G 8c0238279c fix(ci): a red base must not trap the PR that repairs it (#9) 2026-08-07 09:38:48 +00:00
G edac68cf81 fix(ci): stop skipping conflicts, and keep branches current (#7) 2026-08-07 07:15:28 +00:00
GandClaude Opus 5 f6cd6503f2 fix(ci): drain the merge queue oldest-first, not newest-first (#6)
`gh pr list` returns newest-first, and the sweep merges the first eligible PR
then stops. So the newest green PR wins every sweep, and an older one can wait
indefinitely.

Observed in maonakamoto/fleetcrown on 2026-08-06: two consecutive sweeps merged
the two newest PRs while three older green ones sat untouched and were never
even evaluated. With several agent sessions opening PRs continuously that is
starvation — and it starves the worst candidate, since the longest-waiting PR
is the one whose checks were proven against the most now-stale base.

PR numbers increase monotonically with creation, so sorting ascending is FIFO.
The ordering was never a decision, just whatever gh happened to return.

Fixed upstream first (fleetcrown #182) and verified in production there: the
sweep immediately after it landed correctly took the oldest open PR rather than
the newest. This is that one-line change, applied to the fleet.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 13:41:56 +00:00
G a05de60b51 ci: green PRs merge and deploy themselves (#5)
* ci: add the auto-merge sweep policy

* ci: green PRs merge and deploy themselves

* ci: allow CI to be dispatched so auto-merge can re-arm it

* ci: allow deploy to be dispatched so an automated merge still ships
2026-08-05 19:17:58 +02:00
g-butandClaude Opus 4.5 761dc4c615 feat: Rename driver interface to staff, prepare for SBB demo
- Rename /driver route to /staff (supports all employees: drivers,
  conductors, controllers, cleaners)
- Update all components from Driver* to Staff*
- Update German labels: "Fahrer" → "Personal/Mitarbeiter"
- Add Vercel deployment configuration
- Add comprehensive README.md for SBB demo
- Add SSOT infrastructure: labels.ts, schemas.ts, design-system.ts
- Add shared UI components: LoadingSpinner, ErrorBoundary, icons
- Add Docker and development scripts
- Add React hooks for API with mock data fallback

Interfaces:
- / - Passenger app (report lost items)
- /staff - Staff app (receive notifications, respond)
- /demo - Concept explanation for stakeholders

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 19:58:39 +01:00