Files
romm/DEVELOPER_SETUP.md
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

10 KiB

Setting up RomM for development

On Windows, develop inside WSL. The frontend dev dependencies include @posthog/coherence, which installs only on Linux and macOS, so npm install fails on native Windows.

Option 1: Using Docker

If you prefer to use Docker for development, you can set up RomM using the provided Docker Compose configuration. This method simplifies the setup process by encapsulating all dependencies within Docker containers.

Environment setup

Create the mock structure with at least one rom and empty config for manual testing

mkdir -p romm_mock/library/roms/switch
touch romm_mock/library/roms/switch/metroid.xci
mkdir -p romm_mock/resources
mkdir -p romm_mock/assets
mkdir -p romm_mock/config
touch romm_mock/config/config.yml

Copy env.template to .env and fill the variables

cp env.template .env
ROMM_BASE_PATH=/app/romm
DEV_MODE=true

Build the image

docker compose build  # or `docker compose build --no-cache` to rebuild from scratch

The image builds on the same Alpine base as the production image. frontend/node_modules lives in an anonymous volume that outlives the container, so after a rebuild that changes dependencies or the base image, recreate it with docker compose up -d --renew-anon-volumes.

Spin up the Docker containers

docker compose up -d

And you're done! You can access the app at http://localhost:3000. Any changes made to the code will be automatically reflected in the app thanks to the volume mounts.

Optional stacks

Two extra stacks sit in their own files, since most work needs neither. Both join the dev stack's network, so bring docker compose up -d up first.

docker compose -f docker-compose.oidc.yml up -d       # Authentik, for OIDC work
docker compose -f docker-compose.streaming.yml up -d  # webstation, for streaming work

Authentik listens on http://localhost:9001; point RomM at it with the OIDC_* variables in .env. The webstation image is amd64-only and several GB; it reads romm_mock/webstation for emulator configs and BIOS, and its BROKER_SECRET follows STREAMING_BROKER_SECRET from .env.

Option 2: Manual setup

Environment setup

- Create the mock structure with at least one rom and empty config for manual testing

mkdir -p romm_mock/library/roms/switch
touch romm_mock/library/roms/switch/metroid.xci
mkdir -p romm_mock/resources
mkdir -p romm_mock/assets
mkdir -p romm_mock/config
touch romm_mock/config/config.yml

- Copy env.template to .env and fill the variables

cp env.template .env

- Install system dependencies

# https://mariadb.com/docs/skysql-previous-release/connect/programming-languages/c/install/#Installation_via_Package_Repository_(Linux):
sudo apt install libmariadb3 libmariadb-dev libpq-dev

# Build and configure RAHasher (optional)
# This is only required to calculate RA hashes
# Users on macOS can skip this step as RAHasher is not supported
git clone --recursive https://github.com/RetroAchievements/RALibretro.git
cd ./RALibretro
git checkout 1.8.3
git submodule update --init --recursive
make HAVE_CHD=1 -f ./Makefile.RAHasher
cp ./bin64/RAHasher /usr/bin/RAHasher

- Install python dependencies

scripts/dev-setup.sh installs the pinned uv, Python, and Node versions plus the backend and frontend dependencies in one step, and is safe to rerun. On systems without apt-get, install the MariaDB and PostgreSQL client headers yourself first. To do it by hand instead, follow the steps below.

You'll need uv installed

https://docs.astral.sh/uv/getting-started/installation/

curl -LsSf https://astral.sh/uv/install.sh | sh

Then create the virtual environment and install the dependencies using uv:

uv venv
source .venv/bin/activate
uv sync --all-extras --dev

- Spin up the database and other services

docker compose up -d

- Run the backend

Migrations will be run automatically when running the backend.

cd backend
uv run python3 main.py

- Run the task workers

A manual task run is refused, and a scheduled job stays queued, until an RQ worker listens on its queue; scans and streaming teardowns each have a worker of their own. Each command is a foreground process, so run them in separate terminals. -c config reads the Redis connection from the same REDIS_* settings in .env the backend uses.

cd backend
uv run rq worker -c config --worker-class handler.rq_worker.RomMWorker --with-scheduler high default low
cd backend
uv run rq worker -c config --worker-class handler.rq_worker.RomMWorker --with-scheduler scans
cd backend
uv run rq worker -c config --worker-class handler.rq_worker.PreloadingWorker --with-scheduler streaming

--with-scheduler releases delayed jobs, such as the rescans the filesystem watcher waits out, so each worker needs it. The recurring schedule is registered by the RQ cron process, which the workers then execute:

cd backend
uv run rq cron -c config tasks.cron_config

Setting up the frontend

- Install node.js dependencies

cd frontend
# npm version >= 9 needed
npm install

Vite serves cover art, screenshots and manuals from assets/romm/resources. The link target resolves from the link's own folder, hence the three levels up:

mkdir -p assets/romm
ln -s ../../../romm_mock/resources assets/romm/resources

- Run the frontend

npm run dev

- Storybook (v2 components)

Component docs and visual QA for frontend/src/ (port 6006):

npm run storybook
npm run storybook:test   # play() + axe on every v2 story, in headless Chromium

storybook:test (and npm run test, which includes it) needs Playwright's Chromium: run npx playwright install chromium once.

For responsive layouts, use the viewport toolbar presets from .storybook/rommViewports.ts.

- Optional: local frontend against a remote RomM

To run npm run dev or npm run preview against another RomM instance (for example a home server with a full library), set DEV_PROXY_TARGET in the repo-root .env to its origin, such as https://romm.example.com. Vite then proxies /api, /ws and /assets/romm there instead of the local backend. Leave it empty to keep the default http://127.0.0.1:${DEV_PORT}. The remote's TLS certificate must be valid. Sign in with a username and password: OIDC login does not work through the proxy, because the identity provider redirects to the remote's OIDC_REDIRECT_URI, so the session never reaches localhost.

Seeding a test library

backend/tools/generate_test_data.py fills a database with a prod-like library (platforms, users, roms, files, saves, collections...) and draws cover art on disk. It writes to the database and RESOURCES_BASE_PATH from your .env, so point both at a throwaway database and folder, not a library you care about.

cd backend
uv run tools/generate_test_data.py --roms 2000 --image-fidelity 2 --wipe

That seeds 2,000 roms in under a minute. It prints the seed it used and a login (every seeded user's password is password). Useful flags, all listed in --help:

  • --wipe deletes the rows the script populates before seeding.
  • --seed N reproduces the same rows and images (default 1337).
  • --image-fidelity sets how real the covers are:
    • 1 (default) draws one-size mosaics.
    • 2 uses the real mix of cover sizes and shapes, drawn as debug art showing each rom's id, size and path.
    • 3 also matches real file weights, and some big.png files hold JPEG data.
  • --image-limit N draws covers for the first N roms only, and --no-images skips them.
  • --image-media adds ScreenScraper media (box3d, fanart...).
  • --dry-run builds everything but writes nothing, image files included.

The seeded roms have no files under library/, so a scan would mark them missing. The frontend's assets/romm/resources symlink should point at the same resources folder, so the UI shows the seeded covers.

Setting up the linter

We use Trunk for linting, which combines multiple linters and formatters with sensible defaults and a single configuration file. You'll need to install the Trunk CLI to use it.

- Install the Trunk CLI

curl https://get.trunk.io -fsSL | bash

Alternative installation methods can be found in their docs. On commit, the linter will run automatically. To run it manually, use the following commands:

trunk fmt
trunk check

Type checking runs separately from Trunk, against the project's own environment. CI type-checks the whole backend on every backend change; to run it locally:

cd backend
uv run mypy --config-file ../.trunk/configs/mypy.ini .

Failing to install and run the linter will result in a failed CI check, which won't allow us to merge your PR.

Test setup

- Create the test user and database with root user

docker exec -i romm-db-dev mariadb -uroot -p<root password> < backend/romm_test/setup.sql

- Run tests

Migrations will be run automatically when running the tests.

cd backend
# path or test file can be passed as argument to test only a subset
uv run pytest [path/file]
# or run the following command to run all tests, one worker per CPU core
uv run pytest -n auto

Each -n worker gets its own database (romm_test_gw0, romm_test_gw1, ...), created on demand; setup.sql grants the test user the rights to create them. On MariaDB, a new worker database is copied from romm_test_template_<digest>, which the run migrates once and keeps for later runs. The digest covers alembic/, models/ and utils/, so editing any of them builds a new template. To migrate from scratch, drop both the worker databases and the template. On a machine with many cores, cap the workers with --maxprocesses 4 (CI's count) to keep the load on the database down. A serial run of the whole suite takes 20+ minutes. Drop -n auto when debugging with --pdb or -s, which don't work under parallel workers.