22 Commits

Author SHA1 Message Date
Georges-Antoine Assi
e813e4d666 chore(coherence): adopt Coherence with specs, invariants and a PR report (#5584)
* chore(coherence): adopt Coherence with specs, invariants and a PR report

Install @posthog/coherence as a frontend dev dependency and wire its
Claude Code hooks into the committed .claude/settings.json, so every
agent session in the repo gets the vocabulary, specs, journal and checks.
The hooks call the binary under frontend/ through $CLAUDE_PROJECT_DIR.

Declare 23 components and the entrances that carry outside trust, and
six invariants, each refuted with a deliberate break before it counted:

- every /api route requires auth and its scopes, except a named public
  list (new route sweep in tests/endpoints/test_route_guards.py)
- a hidden rom, platform or firmware answers every id route exactly as
  a missing id would (new sweep over every method of every id route)
- the unscoped save, state and screenshot fetches by id are reached only
  from their own routers (chokepoints)
- validate_path never resolves outside its base folder

The PR workflow runs in comment mode: one report comment, failing only
when Coherence itself breaks. Trunk skips Prettier and markdownlint on
*.spec.md and *.practice.md, since Prettier escapes their globs.

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

* test(routes): satisfy mypy in the route guard sweep

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

* chore(coherence): record the worktree test database enactment

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

* fix(roms): answer a hidden rom like a missing one on file routes; tighten route sweeps

Addresses Greptile's review on #5584.

The rom file delete and reading-progress routes answered "File not found"
for a hidden rom but "Rom with id N not found" for a missing one, so a
caller could tell them apart. They now raise the same not-found.

The route sweeps now reach the checks they claim to test: a protected
route with no scopes counts as public (its guard admits anyone), write
requests carry a body and upload name so validation can't answer first,
RomFile-keyed routes get a real file id, error bodies are compared with
the id normalized, and the rom routes are swept with the rom hidden
directly, through its platform, and by the unrated filter.

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

* fix(coherence): tighten route guard sweeps and isolate oracle test databases (code-review)

- Count a route as protected only when its endpoint is the scope-checking
  wrapper with non-empty scopes, not just when it declares the bearer scopes.
- Treat 401 and 403 like 422 as never reaching the visibility check, and
  sweep /api/streaming/states/{rom_id}.
- Run pytest oracles with a per-run ROMM_TEST_DB_TAG unless one is set.
- Use the shared setup-frontend action and ubuntu-24.04 in the workflow.

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

* refactor(tests): simplify route guard sweeps and path tests (simplify)

- Mark scope-guard wrappers with required_scopes so the auth sweep reads a
  public attribute instead of the private closure.
- Derive the entity regex from one segment list, ask each missing id once,
  and run the three hide scenarios through one sweep helper.
- Fold the new validate_path inputs into the existing valid, traversal and
  absolute path tests.

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

* chore(coherence): trim workflow comments (review-polish)

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

* test(filesystem): restore the validate_path property test the paths invariant cites

Filesystem.spec.md names test_validate_path_never_escapes_its_base as the
invariant's evidence, and Coherence selects it by name.

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

* chore(coherence): run hooks from the local binary instead of npx

Each hook calls frontend/node_modules/.bin/coherence directly and exits 0
when it isn't installed, so sessions without frontend deps (fresh
worktrees, backend-only setups, cloud setup still installing) don't report
a hook error on every tool call, and no hook pays npx's startup.

Also commits the journal and run records left by earlier sessions, which
.coherence/.gitignore keeps as durable records.

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

* refactor(tests): share the bearer, user token and hide helpers

Tests built the same Authorization headers and HiddenEntity rows in about
40 local copies, and two modules imported private helpers from other test
files. They now use bearer, user_headers and hide from tests/auth_helpers.py.

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

* refactor(endpoints): one 404 for a missing or hidden rom, platform or firmware

Each route wrote the missing-row 404 and the hidden-row 404 separately and
had to keep them identical by hand. visible_rom_or_404,
visible_platform_or_404 and visible_firmware_or_404 take the lookup result
and raise one answer for both, either the standard not-found or a bespoke
detail. Re-reads after a write keep a plain not-found check, so an edit that
hides the row doesn't turn into a 404 after it succeeded.

The RomFile-keyed routes (/roms/{file_id}/files, .../files/content/{name},
/roms/{file_id}/patch) name their path parameter file_id instead of id, so
the route sweep reads which id a route takes from its path and drops its
hand-kept list. URLs are unchanged.

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

* docs(setup): develop inside WSL on Windows

@posthog/coherence installs only on Linux and macOS, so npm install in
frontend/ fails on native Windows.

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

* chore(coherence): record the whole-repo chokepoint run

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

* chore(types): regenerate API types for the file_id patch route

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:53:46 -05:00
Georges-Antoine Assi
a688676de7 fix: enforce ROM visibility on assets, sync, collections, stats and scan events (#5498)
* fix(sync): cap play sessions on sync completion and require roms.user.write

The completion endpoint fed an unbounded play_sessions list to the same
ingest as POST /api/play-sessions, which allows 100 per batch and requires
roms.user.write. Apply both rules before the session is completed.

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

* fix(config): reject empty platform binding and version values

config.yml exits on load when a platforms or versions value is empty, so
the API must not write one.

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

* fix(collections): require smart collection criteria to be a JSON object

Any other JSON value was stored, then failed the response schema and broke
the smart collection list for every user who could see the collection.

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

* fix(stats): require roms.read on /api/stats

Anonymous callers were served counts over the whole library, including
platforms and ROMs hidden from users. The UI only calls it after login.

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

* fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal

/api/roms/filters aggregated facet values over the whole library, GET
/api/saves/{id} and GET /api/play-sessions returned the caller's own rows on
hidden ROMs, and removing ROMs from a collection could drop members hidden
from its owner. The facet visibility clauses move onto RomVisibilityFilter so
stats and filters share them.

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

* fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins

The SSRF exception for a self-hosted Playmatch or Hasheous applied to every
request, so a user's webhook could reach any path on that private origin.
Non-admin webhooks now validate and connect with an empty allowlist.

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

* fix(saves): bound total decompressed size when hashing zip archives

Zip content hashing capped each entry but not the archive, so many
entries each under the cap could still decompress and hash far more
than any real save or memory card holds. Budget the decompressed bytes
across the whole archive and cap the entry count; callers keep treating
an over-budget archive as an unknown hash.

The chunked, budgeted entry reader is shared with the memory card
archive check, and the RetroArch store path now hashes off the event
loop like its siblings.

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

* fix(psp): clamp LZ4 literal and match copies to the ZISO block size

The ZISO block decoder appended literals and copied matches for their
full encoded length before checking the output size, and an LZ4 length
can be extended without bound by 0xFF bytes. A small crafted block
could therefore expand far past the block size before being truncated.

Clamp each copy to the room left in the block, stop once it is full,
end the block on a truncated match offset, and copy matches with slices
instead of a per-byte loop (overlapping matches repeat their pattern).
Output for valid blocks is unchanged.

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

* fix(auth): revoke OAuth tokens when a user's credentials change

A password change, admin reset, reset-link reset or rename cleared the
account's web sessions, but its OAuth access tokens kept working until they
expired and its refresh tokens could still be exchanged at /api/token.

Revoking a user's credentials now also records a per-username revocation
time in Redis, kept for the longest token lifetime. Bearer validation and
refresh consumption reject any token whose iat is at or before it. OAuth
tokens now carry a sub-second iat, so a login right after the change still
works; a token without iat counts as older than any revocation.

The revocation is keyed by the token's sub, the same username sessions are
keyed by, so a rename revokes tokens issued under the old name even if
another account later takes it. Client (API) tokens are left alone.

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

* fix(api): reject local file URLs for user-supplied covers and manuals

file:// and launchbox-file:// URLs are meant for covers and manuals that
a scan records from gamelist.xml or LaunchBox metadata. The collection
create/update endpoints and the ROM update endpoint passed a user-supplied
url_cover (and url_manual) straight to the resource handler, which copied
whatever library file it named into the entity's resources. That let any
user with collections.write or roms.write pull files they cannot otherwise
read, including those of hidden platforms and ROMs.

These endpoints now answer 400 for a local file URL, unless it is the value
already stored, which the edit forms echo back on every save.

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

* fix(resources): bound cover downloads and decodes

Remote covers, screenshots, manuals, badges and media files were streamed
to disk with no size limit, and a gzip-encoded body was read whole and
inflated in memory. Downloads now go through one helper that counts bytes
against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the
same cap, and aborts past it, so the partial file is removed and any
earlier copy kept.

Covers are also bounded once on disk: a still image whose header declares
more than MAX_COVER_PIXELS is discarded before it is decoded (and an
uploaded one is refused with a 400), and a DecompressionBombError while
deriving the small cover now discards the download instead of failing the
request and leaving the file behind.

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

* test: fix mypy errors in the new tests

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

* fix: address Greptile review on permission and input hardening

- Date OAuth tokens to before the credential check, so a password change
  that lands during the check revokes the tokens it issues.
- Apply ROM visibility to play sessions in SQL, before the page slice.
- Reject truncated gzip bodies and inflate every gzip member.
- Shorten the zip budget comment; stream real httpx2 responses in tests.

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

* fix: apply code-review findings on permission hardening

Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to
GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off
the event loop, and reuse the shared httpx client factory for webhooks.

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

* refactor: apply simplify pass on permission hardening

Read the OAuth revocation stamp through the async cache, share the
play-session batch-size check, raise a plain OSError for oversized downloads,
and drop a dead slice in the LZ4 decoder.

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

* style: apply review-polish pass on permission hardening

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

* docs: state that ROM visibility is enforced as access control

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

* fix(assets): hide saves, states, screenshots and memory cards on hidden ROMs

Visibility is access control, so per-id save/state/screenshot routes now 404
when the save's ROM is hidden from the caller (hidden ROM, hidden platform or
age limit), and the save/state lists and identifier lists leave those rows
out in SQL. GET /api/saves/summary 404s on a hidden ROM. Memory cards on a
hidden platform 404 on every per-id route, drop out of both lists, and can't
be created against a hidden platform.

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

* fix(saves): answer a hidden ROM's save summary like a missing one

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

* fix(permissions): enforce ROM visibility in sync, installs and feeds

Hidden ROMs/platforms and age-limited ROMs are access control, so the
paths that skipped the caller's visibility now apply it:

- sync negotiate: saves on hidden ROMs are neither offered, paired nor
  reported as conflicts; a client save on one negotiates like an unknown ROM
- push-pull SSH sync: resolves the device owner's visibility and skips
  saves on hidden ROMs in both directions
- device installs: list and claim leave out requests whose ROM became
  hidden (they stay pending), and outcome notifications don't name it
- recommendations: a hidden seed ROM is no longer named
- music playlists: track_count counts only tracks on visible ROMs
- audit events: firmware targets on hidden platforms are filtered
- setup library: supported platforms honour the caller's visibility
- feeds: a hidden platform found by slug reads as missing

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

* fix(visibility): hide ROMs from virtual collections, stats and scan events

Virtual collections apply the caller's visibility in SQL: a collection with
no visible member is left out (404 by id), member ids and covers skip hidden
ROMs, and the limit counts only visible collections.

Stats save, state and screenshot totals skip assets of hidden ROMs.

Scan events no longer broadcast to every socket. Progress and end events go
to a scan room that sockets of users holding platforms.write or tasks.run
join on connect. scanning_rom and scanning_platform go to the user rooms of
those followers who can see that ROM or platform, resolved once per scan
and grouped by visibility. get_rom_audience now builds on a shared
get_user_visibilities.

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

* fix: apply code-review findings on ROM visibility enforcement

Match virtual collection members by ROM id, build the cover visibility clauses
once, filter feed platforms by visibility in SQL, resolve every id before a
batch save or state delete, filter push-pull saves in the query, and narrow the
hides query to the requested users.

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

* refactor: apply simplify pass on ROM visibility enforcement

Require an explicit visibility filter on the saves, states and memory card
queries, share one roms_facets visibility join and one owned-asset helper,
filter virtual collection members by hidden ids, batch the scan audience's
scope lookup, and move the empty-room emit guard into socket_handler.

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

* test: start the scan audience before emitting from scan_rom

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

* docs: apply humanizer pass on the visibility rule

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

* fix(streaming): don't mount a memory card on a hidden platform

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

* fix: address Greptile review on ROM visibility enforcement

Refresh a running scan's audience after a permission change, fix the precedence
of the scan-room join assertion, and narrow mock await_args before reading them.

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

* revert: drop per-visibility scan event audience

Scan events go back to every socket. Removes handler/scan/audience.py,
the scan room join on connect, the permissions generation bump and the
batched OAuth scope resolution that only the audience used.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 14:33:11 -05:00
Jeremy
aae48728e5 fix(metadata): read names from {id, name} facet entries in recommendations and ROM responses (#5249)
* fix(recommendations): handle named metadata objects in facet tokens

* fix(recommendations): pr-ready step 2 (code-review): skip non-list columns, base role fallback on usable names

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

* refactor(recommendations): pr-ready step 3 (simplify): type facet params as object, trim redundant test cases

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

* test(recommendations): pr-ready step 4 (review-polish): keep the extract_tokens test prefix

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

* fix(roms): read names from metadata objects in filter values and ROM responses

Share the facet name cleaner as utils.facets.facet_names, and run it in the
filter-values reader, RomMetadataSchema, and over every list[str] key of the
provider metadata blobs, so an {id, name} entry no longer fails /api/roms.

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

* fix(roms): clean name lists in raw metadata edits, reject non-object JSON

parse_raw_metadata now runs the provider blob's list-of-names keys through
facet_names before storing it, so {id, name} objects stop landing in the
database, and answers 422 when the JSON is not an object. Manual metadata
keeps its strict adapter.

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

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:03:36 -04:00
Sam Dornan
b3ad84c296 Route ROM visibility through a single RomVisibilityFilter (#5064)
Replace the hidden_platform_ids/hidden_rom_ids parameter pairs with one
RomVisibilityFilter that builds the WHERE clauses and checks loaded ROMs,
so a new visibility rule (the age-rating cap for #2013) lands in one place.
No behaviour change; the visibility-filtered queries send the same SQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Wc3NzFkv97CXavLyZg5kJE
2026-10-03 10:46:47 -04:00
Georges-Antoine Assi
656c85bc46 refactor(tasks): simplify pass on the task catalog split
Loads every model where the engine is built rather than per job, so only
processes that touch the ORM pay for it. Resolves task paths with RQ's
import_attribute, references the scan failure callback by path, hoists
the recommendations builder's registry import now that the registry
loads no task modules, and gates push-pull on its spec.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 11:06:27 -04:00
Sam Dornan
4ffc7c5ce1 style: apply the formatting requires-python already implies (#4638) 2026-09-19 12:33:45 -04:00
Georges-Antoine Assi
0b1f6f7c80 feat(recommendations): index a scanned rom before the nightly build
A game added today had no edges until the 5:30 AM rebuild, so its "Similar
games" section was empty and nothing could reach it from a feed.

`build_for` scores a handful of ROMs against the current library instead of
sweeping every pair, and folds them into the stored neighbour lists of the
games they matched so the new game is reachable from both directions. The
full build is the same sweep with every ROM as a target, so the two paths
share one implementation rather than drifting.

The scan hands over the ids it wrote. Past MAX_TOP_UP_ROMS the incremental
path saves nothing, so that case queues a rebuild rather than blocking the
scan on work a rebuild would redo.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 18:38:32 -04:00
Georges-Antoine Assi
714c99693b fix(recommendations): weight a co-occurrence by the evidence behind it
Co-play and co-collection were a bare cosine, which saturates at 1.0 the
moment two games are always seen together. On a single-user server, the
common case, that is every pair of games the owner has played: the signal
became a flat +0.15 on all of them rather than something that discriminates
between them, and a genuinely similar unplayed game needed a content score of
0.273 just to draw level. Tetris and Madden were neighbours.

The cosine is now damped by the number of sightings behind it, the way
`get_fallback_rom_ids` shrinks a rating toward the mean by its vote count. A
lone sighting keeps a quarter of its weight, which leaves it under
MIN_EDGE_SCORE on its own, while a pair a whole server agrees on is untouched.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 17:04:32 -04:00
Georges-Antoine Assi
e78a4aa1b9 chore(recommendations): cut the comments back to what the code cannot say
The engine carried its tuning history in its comments: measurement logs for
PIVOT_B, the weight a facet held before the company split, the shape of the
cold-start feed before the Bayesian average. None of that describes what the
code does now, and it belongs in the history rather than beside the values.

Also folds serving's ROM loader into feed's, which differed only by the
visibility filter applied afterwards.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 14:35:15 -04:00
Georges-Antoine Assi
5bce1215ce refactor(recommendations): deepen four fixes to their root cause
Merge 0123/0124/0125 into one migration. Each added STORED generated
columns to `roms`, and 0125 already dropped and re-added several, so
upgrading rewrote the widest table three times and restated the
`roms_metadata` view three times. One ALTER TABLE now carries the Steam
rebuild, the three IGDB tag columns and the rating count, and the view is
recreated once. Verified upgrade/downgrade/upgrade on MariaDB and Postgres.

Score each unordered pair once. Candidate generation is symmetric, so
every pair had its dot product computed twice. The sweep now runs in
ascending id order and scores only from the lower id, which also makes a
ROM's edges final the moment the sweep passes it, so the incremental
flush survives. Only the target's quality bonus differs by direction, so
one content score is blended twice. The per-ROM candidate ceiling moves
into `candidate_ids`, taking the rarest posting lists first, where it
bounds work instead of being applied after the cost was already paid.

Read identity off one list. `sibling_roms` decides "same title" from
seven provider ids; the suppression here used two, so a pair matched only
by MobyGames was a sibling everywhere else in RomM and a recommendation
for itself here. `IDENTITY_ID_FIELDS` on the model is now the one home,
consumed unscoped by the builder since a reissue on other hardware is no
more a suggestion than a second copy on the same platform.

Make the facet vocabulary a StrEnum. It was spelled out in five places,
two of them already stale, and `facet: str` kept it out of the API
contract, so an unmapped facet silently rendered a raw value. It reaches
OpenAPI as a closed union and the frontend maps are keyed by it, so
adding a facet now fails the typecheck until the UI handles it.

Give each surface one serving entry point. `similar_roms` and
`recommended_roms` own the over-fetch, hydration, visibility filter,
series cap and cache that the two endpoints and the inspection tool each
re-implemented with three different over-fetch constants; the cache moves
in with them so no caller can rank a feed without populating it.
Endpoints now do ORM-to-schema only.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 12:12:52 -04:00
Georges-Antoine Assi
1ff9944224 refactor(recommendations): reuse, simplification and efficiency pass
Backend, wasted work:
- `_score_one` computed `content_similarity` twice per candidate on the
  trim path and built `shared_reasons` for every candidate clearing the
  score floor, discarding almost all of them. Compute content once and
  build reasons only for the edges actually stored.
- `get_feature_rows` outer-joined `RomMetadata`, a view over the wide
  `roms` table, defeating the point of reading the narrow facet mirror.
  Read the generated columns off the `Rom` join already present.
- Feed cache invalidation ran a keyspace SCAN on every `rom_user` write.
  Put graph and per-user version counters in the key so it is one INCR,
  matching `invalidate_filter_values_cache`.

Backend, reuse:
- Route the five name comprehensions beside `_expanded_names` through it.
- `_recency_factor` reimplemented `to_utc`.
- `replace_similarity_edges` hand-rolled `itertools.batched`.
- Derive `TASTE_FACETS` from `FACET_WEIGHTS` instead of restating its keys.

Backend, dead code:
- `ScoredNeighbour`, `BuildStats.to_dict`, `delete_all_similarity_edges`,
  the unread `difficulty`/`completion`/`backlogged` affinity fields,
  `FACET_ORDER` and `RomInfo.rom_id`, and a no-op `column_type` ternary.

Frontend:
- Extract `RecommendationReason` from the two byte-identical copies in
  `Home.vue` and `SimilarGamesGrid.vue`, dropping the repeated
  `primaryReason` calls and their non-null assertions.
- Cap the caption with `--r-card-art-w` rather than a `158px` literal that
  does not track the per-breakpoint card width.
- Key the similar-games fetch on the ROM id: `watchEffect` refetched on
  every optimistic mutation of `currentRom`.
- One home for the similar-games limit.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 11:44:00 -04:00
Sam Dornan
08480d02ed feat(backend): treat any shared identity id as a duplicate in the build
The duplicate check keyed on igdb_id alone, so two copies of one Steam
game with no IGDB match (a bundle and a standalone, an installer and a
portable) could recommend each other and take two slots. Each ROM now
carries a set of provider:id tokens from every identity provider that
matched it, and two ROMs sharing any token are one game.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-03 09:39:14 -05:00
Sam Dornan
3543447469 fix(backend): drop cached feeds when the graph is rebuilt
Every cached ranking is computed against the edges that existed when it was
built, so the nightly rebuild left users reading the previous graph until
their cache expired. The same argument that moved per-user invalidation into
`update_rom_user` applies to the largest input of all.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-10 19:50:22 -05:00
Sam Dornan
946963ef2e refactor(backend): share one diversity pass between both surfaces
The feed reimplemented franchise counting inline, keyed on a single
representative series where the similar-games surface counts every name a
game's series goes under. On a 14,952-game library 415 series keys are
shared by games whose representative differs, so the two surfaces disagreed
about what counts as the same series.

`cap_by_series` gains an optional platform ceiling, which the feed needs and
a single game's shelf does not, and the feed now calls it. The feed also
picks up the backfill in the process, so a row the caps leave short fills
rather than arriving with fewer entries than asked for.

`primary_series` has no callers left and goes with it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-10 10:09:12 -05:00
Sam Dornan
17ba75b64d chore(backend): tidy recommendation comments
Drop a comment that narrated the per-series cap changing rather than
describing what the cap does, merge two adjacent comments in the builder
that both explained candidates colliding with each other, and refresh the
library statistics quoted in the migrations and the backfill tool so they
match the shelf the numbers were last taken from.

The two measurements in `scoring.py` still cite the 12.7k library they were
run on, since that is where they were run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-10 09:56:56 -05:00
Sam Dornan
022002c4f5 fix(backend): allow three from a series rather than two
Measured on a 14,952-game library, 400 random games at six results each:
a cap of two fired on 52% of lists, and each time it swapped a 0.48 match
for a 0.10 one, roughly five times less related. It bought 0.41 more
distinct series than a cap of three.

Three still keeps the tail of a deep franchise off the list, which is what
the cap is for, without discarding a strong match so eagerly. Applied when
serving, so this needs no rebuild.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-10 09:34:28 -05:00
Sam Dornan
73bb8cce8e fix(backend): let two ports of one game share a single slot
The second pass deduped candidates against each other by igdb_id but
compared titles only against the source, and IGDB gives every port its
own id. A shelf holding Monopoly on both the GB and the NES spent two of
six slots naming the same game.

Found by sampling the index at random rather than by reading the code:
it was the first entry of a 40-game sample.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-10 08:46:40 -05:00
Sam Dornan
08f550245e feat(backend): separate developer from publisher when scoring similarity
`companies` flattens every IGDB involvement role into one list, so the studio
that made a game is indistinguishable from the label that shipped it or the
regional distributor that boxed it. Those carry very different weight: a
studio's games genuinely resemble each other, while a publisher spans
everything it ever released.

It is not a marginal distinction. On a 12.7k-game library the second most
common "company" is Tec Toy, Sega's Brazilian distributor, on 768 games, with
Playtronic (Nintendo's) on 350 -- dense enough that IDF does not suppress
them, so matches were coming out as "same distributor". Super Metroid's
cross-franchise suggestions were all justified by Playtronic.

IGDB returns developer/publisher booleans on involved_companies and the
scanner never requested them. Requesting them turns that noise into signal:
Super Metroid now matches on Nintendo R&D1, the studio behind it, Super Mario
Land and Wario Land. Gunstar Heroes returns Alien Soldier and Dynamite Headdy
-- the rest of Treasure's catalogue.

Developer keeps the 0.7 the merged facet already carried, so splitting the
roles redistributes that weight rather than adding new influence, and
publisher drops to 0.25. Sweeping developer from 1.0 to 0.4 barely moved
anything: a tight studio's games also share genre and theme, so the developer
token is not what carries them. The one place it shows is a wide-ranging
studio -- Tony Hawk's Pro Skater now surfaces Neversoft's unrelated titles
where it used to find other skateboarding games through a keyword.

`companies` is untouched for display, and the scorer falls back to it when a
game was matched by a provider that reports no roles, so emitting both never
double-counts one studio. Coverage is 72% developers and 78% publishers,
ahead of every facet already in use.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-08 09:14:49 -05:00
Sam Dornan
038059b571 fix(backend): cap a series by every name it goes under
The per-series cap keyed on a game's first franchise. IGDB lists franchises
in no stable order and a game often carries several, so one series split
across several counters and each spelling got its own allowance.

Sports libraries show it worst, since they hold every yearly release. Madden
titles carry both "Madden" and "NFL": some resolved to one, some to the other,
and a cap of two returned four Madden games. Tony Hawk's Pro Skater 2 returned
four Tony Hawks, and Mario Kart 64 filled its remaining slots with Mario Golf
and Mario Tennis via the broader "Mario" franchise.

A candidate is now measured against every franchise and collection it lists,
and is held back if any one of them is already at the cap. The same fix
applies to the build-time reservation, which picked its slots the same way.

The three now return two same-series entries followed by something else:
NCAA Football and Tiger Woods for Madden, Skate It and Grind Session for Tony
Hawk (matched on the skateboarding keyword), F-Zero X and Wave Race for Mario
Kart.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-08 08:48:18 -05:00
Sam Dornan
da896efab5 feat(backend): score recommendations on IGDB keywords, themes and perspectives
IGDB carries three descriptors the scanner never requested: community
keywords ("metroidvania", "shmup"), curated themes (Horror, Survival, Open
world) and player perspectives (Side view, First person). They describe how a
game plays, which genre and franchise cannot: on a 12.7k library only these
three connect Castlevania to Symphony of the Night rather than to the
platformers, Ocarina of Time to Super Mario 64 via Open world, EarthBound to
Chrono Trigger via Fantasy, and GoldenEye to Perfect Dark via Stealth plus
First person.

Coverage beats the existing facets: 66% of matched games carry keywords
against 59% for franchises.

They reach the index the same way every other facet does -- a STORED
generated column, the roms_metadata view, then the trigger-maintained
roms_facets -- so the builder still never reads the wide roms table.

Weight a facet by the values it holds. A game's franchise weight is now split
across however many franchises it carries, so one counts for more than one of
six. Compilations and crossovers previously matched strongly on every
franchise they touched: the SNES Mario compilation pulled in Mario Tennis and
Mario Party ahead of the 2D platformers, and Project X Zone surfaced against
Resident Evil at 0.305 rather than 0.197. Splitting by sqrt rather than the
count keeps three genres worth more in total than one.

Rank keywords last when explaining a match. They are the rarest tokens and so
carry the highest IDF, which had them explaining a Castlevania pairing with
"frankenstein's monster" instead of the shared series.

Existing libraries carry none of this until it is fetched, so
tools/backfill_igdb_tags.py asks IGDB for only the three missing fields in
batches of 500 -- 12,118 games in 36 seconds, against the twelve thousand
requests a rescan would make.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 21:47:07 -05:00
Sam Dornan
4f59480ae5 fix(backend): correct ranking defects found on a real library
Validating the index against a 12.7k-game library surfaced four problems a
synthetic fixture could not, because each depends on the shape of real
metadata.

Stop penalising well-documented games. Vectors were L2-normalised, on the
assumption that facet counts behave like document length in text retrieval.
They do not: a long document repeating a word is not more relevant, but a game
tagged with three genres and two franchises genuinely has more in common than
one carrying a single tag. Normalising by a vector's own length made every top
match a sparsely-tagged entry -- a Mario compilation matched Golf, F-1 Race and
Pinball (6-8 tokens each) while the actual Mario platformers (12-16 tokens)
were nowhere in the list. Scaling by the library average instead returns
Yoshi's Island, Super Mario 64 and Donkey Kong.

Two hypotheses were measured and rejected on the way: franchise coherence via
genre entropy (Metroid scored higher than Mario, so no signal) and the
franchise/genre weight ratio (five configurations, none of which moved the
result).

Suppress duplicates against each other, not just against the source. Two discs
of one release share an igdb_id and platform, so both took a slot in the same
list. The same game ported to another platform gets its own igdb_id, so it
needs a title comparison rather than an id one.

Diversify across series. Similarity ranking alone made the section a franchise
filter -- five Metroid games for Super Metroid. Slots are reserved at build
time so the stored graph always carries cross-series options, and the per-
series cap is applied when serving so the policy can change without a rebuild.
Capped-out entries backfill a short list in score order.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 21:17:00 -05:00
Sam Dornan
399aec5c8b feat(backend): add a library-aware recommendations engine
Recommendations came straight from IGDB's `similar_games`, which mostly
names titles the server does not hold and is absent entirely for anything
IGDB never matched.

`rom_similarity` holds a precomputed item-item graph blending four signals:
IDF-weighted metadata overlap, the IGDB prior resolved against the library,
collection co-membership and co-play. Scores are library-relative, so a
shelf full of arcade games learns on its own that "Action" says nothing
while "Metroidvania" says a great deal, with no tuning.

Each edge stores the facets that produced it, so the UI can explain a
recommendation rather than showing an unattributed row of covers.

Candidate generation runs off an inverted index with a document-frequency
cap, avoiding the all-pairs comparison. The graph is rebuilt wholesale by a
scheduled task because the IDF weighting shifts as the library grows, and
writes commit in batches so a task that dies leaves stale edges rather than
an empty table.

The personalised feed is ranked on demand from those edges plus live play
history, since a nightly feed would ignore the game played an hour ago.
Ratings below the scale midpoint act as negative seeds, results are
diversified per franchise and platform, and owned-but-unplayed games are
boosted.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 20:12:19 -05:00