# STRUCTURE.md — how this API is built

Read it **at the start of every task**, together with `AGENTS.md`. It records the structural choices
of this repository so that every change is written the same way. Update it **in the same commit** as
any code that changes the structure. Keep it short and factual: fix an entry that became wrong
instead of adding a contradicting one.

## 1. Stack

Symfony 8.1, PHP 8.4, API Platform 5 (Doctrine ORM 3), LexikJWT, MySQL 8 (InnoDB forced), symfony/uid
UUID keys, PHPUnit 13 with `api-platform/test`. Everything is written in English (code, comments,
OpenAPI texts, validation messages); clients translate on their side. Set aside: PostgreSQL (named
in the specification), decided with the human: the database server is shared with other projects,
`ClubScopeFilter` relies on MySQL's `UNHEX`, and no gain was identified.

Every table is `utf8mb4` / `utf8mb4_0900_ai_ci` (`default_table_options` in `doctrine.yaml`, key
`collation`: DBAL 4 ignores `collate`), with `charset=utf8mb4` in `DATABASE_URL`: every script and
emoji is stored and compared (Unicode 9; `utf8mb4_unicode_ci`, Unicode 4, takes most emoji for one
another). Comparisons ignore case and accents, as a search does. Human decision (2026-10-29): "all
languages". `InternationalTextTest` checks the tables and a round trip in ten scripts.

## 2. Where things live

```
src/
  Entity/          Doctrine entities. CRUD resources carry their #[ApiResource] here (Club, Membership, Invitation, JoinRequest, Team, Player, TeamMember, User,
                   Exercise, TrainingSession, TrainingRun, Game, SupportAction); AggregatePartInterface marks the parts of a document
  ApiResource/     resources that are not entities (Authentication, Me, ReceivedInvitation, MyJoinRequest, ClubDirectoryEntry,
                   ProfileReview, NotificationSummary, NotificationSettings, CommunityProfile, MyFollow, MyFollower,
                   MyTrainingDraft,
                   CommunityPost, PostMediaUpload, PublicMedia, CommunityComment, ContentReport, ModerationCase,
                   ModerationDecisionRecord, MyModeration, ModerationAppealCase):
                   attribute-only classes
  Enum/            backed enums; PlatformRole is the single place of the platform role rules, ClubSupport of the staff's access to clubs
  Dto/<Domain>/    input / output objects of custom operations (LoginInput, TokenPair…, Training/ExerciseInput…)
  State/<Domain>/  State Providers (read) and Processors (write) of custom operations; `State/AggregateWriter`
                   is shared by the processors of the documents written in one piece
  Auth/            authentication services (tokens, sessions, mailer, rate limits)
  Mail/            DeferredMailer: every e-mail leaves after the response (see §4), laid out by templates/email/
  Notification/    Notifier (the one way to notify: in the app + e-mail as chosen), NotificationDigests (the
                   grouped e-mails), NotificationMailer (their content)
  Community/       the community outside the clubs: CommunityPeople (who can be found, by public name), Follows,
                   PostAccess (who reads a post), PostViews, ExercisePosts, Mentions, LinkPreviewFetcher
  Moderation/      reports and moderation: ModerationDesk (the decisions), AppealDesk (the right of reply), ReportTargets (what a report is about), ModerationScope
                   (the only way to read what is hidden), Moderatable + trait
  Tenant/          multi-tenancy: CurrentClub, ClubPermission, ClubScopedInterface/Trait, SupportLog
  Doctrine/        listeners, SQL filter `club_scope`, query extensions, `Type/` (encrypted column)
  Security/        voters (ClubPermissionVoter, UserManagementVoter, PlayerVoter, AuthorVoter, ModerationVoter), user checker, PiiCipher
  Serializer/      normalizers that change the context record by record (PlayerNormalizer, UserNormalizer, MembershipNormalizer)
  Privacy/         PlayerPrivacy: what a reader sees of a player record
  Media/           private file storage (MediaStorage), image re-encoding (PhotoSanitizer), photo upload and copy (PhotoUploader),
                   signed links of the community's files (SignedMediaUrls), videos (VideoUploader, VideoSanitizer)
  Profile/         PlayerProfileSync: the profile of an account copied to its player records;
                   PlayerRecordLink: a member of a club becomes one of its players (themselves or by the staff)
  Http/            kernel listeners (security headers, Content-Length, constraint violations → 409)
  Logging/         Monolog processors (RedactAddressesProcessor: no e-mail address in any log record)
  OpenApi/         OpenAPI decorators
  Validator/       reusable constraints (StrongPassword, ClubStaff)
  Command/         console commands: invokable `final` classes named `XxxCommand`, `app:<domain>:<verb>`,
                   output through `SymfonyStyle`; a secret is only typed at a hidden prompt, never an argument
  DataFixtures/    development data set (§5): UserFixtures → ClubFixtures → TrainingFixtures, GameFixtures, CommunityFixtures,
                   linked by references
```

`dev/` holds development tooling outside `src/` (namespace `App\Dev\`, `autoload-dev`). `Controller/UmlDiagramController` draws
the entities as a UML diagram at `/uml-diagram`. It is routed (`config/routes/uml_diagram.yaml`) and registered (`when@dev` in
`services.yaml`) in the `dev` environment only: in `prod` the code is not autoloaded (`composer install --no-dev`) and the URL is a plain
404, which `tests/Dev/UmlDiagramRouteTest` guards.

## 3. How an endpoint is written

- **No controllers for the API.** Every endpoint is an API Platform operation. This is the model
  API Platform recommends since v3 and it gives validation, serialization, security, pagination,
  filters, error format and OpenAPI for free. Decided on 2026-10-23 after reviewing it with the
  user: keep it.
- **CRUD on an entity**: declare the operations in the entity's `#[ApiResource]`, with
  `security:` expressions (`is_granted('teams.write', object)`), serialization groups, filters as
  `QueryParameter`s. No PHP code.
- **Custom action** (sign-in, password reset, `/me`…): an operation (on an `ApiResource/` class
  or an entity) with `input:` a DTO from `Dto/`, `output:` a DTO or `false`, `read: false`, and a
  `processor:` (write) or `provider:` (read) from `State/<Domain>/`. The processor stays thin and
  delegates to services (`Auth/…`).
- **A document written in one piece** (an exercise and its frames, a session and its slots, a run and
  its attendance — §4 quater; a game and its score sheet — §4 quinquies): `Post` and `Put` (whole
  replacement) with `input:` a DTO of `Dto/<Domain>/` implementing `ClientIdentifiedInput` and a
  processor of `State/<Domain>/` built on `State/AggregateWriter`. Reads are plain `Get` / `GetCollection` on the entity.
- **A `Post` on a record that already exists** (`/exercises/{id}/archive`, `/game_shares/{id}/link`,
  `/players/{id}/photo`…) sets `throwOnNotFound: true`. API Platform answers a missing record with a 404 for every
  verb but POST (a POST creates), so without it `object` is `null` and the `security` expression runs on nothing:
  `object.getGame()` is a 500, and `is_granted('members.manage', null)` lets any administrator through to a processor
  that gets `null`. On purpose, `POST /exercises/{id}/unpublish` does not: an unknown and a non-public exercise
  both get a 403, so identifiers cannot be probed. `RoleMatrixTest` plays every operation with an identifier that
  designates nothing and fails on a 5xx (audit API-SEC-10: ten operations did).
- **Every operation** has `openapi: new Operation(summary:, description:)` and documents its
  non-2xx responses (a test enforces it). Docblocks go at the top of classes and methods.
- Request validation: `#[Assert\…]` on the DTO / entity properties. Error responses are
  `application/problem+json`; a 422 carries `violations[]` with Symfony constraint `code`s, which
  the clients translate.

## 4. Conventions in place

- **Text sent is data** (human decision of 2026-11-13: "no code injection, no characters we do not handle"):
  `Http/CleanTextListener` (`kernel.request`, after the firewall) reads every JSON write body (POST / PUT / PATCH) and answers
  **422** with `violations[]` (code `NOT_CLEAN_ERROR` of `Validator/CleanText`) when any string, or any key, carries a control
  character (null byte included, tab / LF / CR allowed), a forced text direction (U+202A-202E, U+2066-2069), a zero-width space, a
  BOM, a "tag" character or invalid UTF-8; nested JSON (`style`, `legend`, `drawing`) is covered, secrets (`password`, `code`,
  tokens…) are not. The clients (`cleanText()` of `packages/core/lib/text.ts`) remove them as the person types, so a 422 means an
  old or hostile client. Markup is **not** rewritten: it is stored as text and escaped where it is displayed. The `style` of an
  element is checked key by key by `Validator/ExerciseStyle` (closed set, enums, bounds, 96 KB; mirror of `ElementStyleSchema`),
  the `legend` is an object with keys of 64 characters at most, a video link must belong to its provider and carry its id
  (`VideoProvider::hosts()`), and a blank title is refused (`NotBlank(normalizer: 'trim')`). Set aside: a constraint on each of the
  ~100 text properties (one forgotten is one hole), stripping on the server (the stored text would differ from what was sent).
- UUID primary keys (`AbstractEntity`), client-chosen id allowed on creation through the
  `entity:id` group in the Post `denormalizationContext`.
- `createdAt` / `updatedAt` (UTC, no setter, so no client can write them) are stamped only by
  `Doctrine/TimestampListener` (`prePersist` + `onFlush`). A DQL `UPDATE` bypasses every Doctrine
  event, so it sets `t.updatedAt = :now` itself (token revocations in `RefreshTokenRepository`,
  `UserTokenRepository`). Set aside: `EventListener/EntityUpdateListener` (`setCreatedAt` /
  `setUpdatedAt` through `method_exists`), a duplicate that needs public setters; `ON UPDATE
  CURRENT_TIMESTAMP` in MySQL (second mechanism, session time zone instead of UTC).
- Personal data at rest is encrypted: a column `#[ORM\Column(type: EncryptedStringType::NAME)]`
  (TEXT, `Doctrine/Type/`) is sealed by `Security/PiiCipher` (libsodium XChaCha20-Poly1305, random
  nonce, `v1:` prefix for a future key rotation). The key `PII_KEY` (base64 of 32 bytes,
  `app:pii:generate-key`) lives in `.env.local` / the environment / the secrets vault, never in the
  repository; `.env.test` has a test-only key. `Kernel::boot()` hands the cipher to the type. Such a
  column cannot be searched, sorted or unique: only data read record by record goes there. Set
  aside: a third-party bundle (a dependency for ~80 lines), MySQL encryption functions (the key would
  travel to the shared server). An encrypted value that must be found by equality gets a **blind
  index** next to it: `PiiCipher::blindIndex()` (HMAC-SHA256, key derived from `PII_KEY`), kept by a
  Doctrine listener (`SignInEmailIndexListener` for `Player.signInEmail`), compared by a validator
  for uniqueness (`UniqueSignInEmail`, 422 with its code) and by a unique index.
- Data only some callers may read goes in its own serialization groups, added **record by record**
  by a decorating normalizer (`Serializer/PlayerNormalizer`, deciding through `Privacy/PlayerPrivacy`):
  `players.private` (the staff through `ClubPermission`, the person through `PlayerVoter`) opens
  everything, the audiences chosen open the rest (see « Privacy of player records »). Set aside: a
  group added to the whole request (a list could not show the caller's own record differently), a
  separate sub-resource (two calls per screen). A summary embedded in another resource only ever
  gets the names, never `player:private`.
- Uploaded files (`Media`): received by `Media/PhotoUploader` (one place for every photo: a player's,
  an account's), validated with `Assert\Image` (type detected from the content, size and
  pixel limits before decoding), photos re-encoded by GD as a JPEG of 512 px at most (no EXIF / GPS
  left; the camera orientation is not applied, clients send an upright image), stored encrypted by
  `Media/MediaStorage` under a random key in `MEDIA_STORAGE_DIR` (outside `public/`, back it up with
  the database and `PII_KEY`). Served only by an operation whose provider checks the record and
  returns a `Response` (`no-store`), e.g. `GET /players/{id}/photo`. A file is deleted after the
  flush that removes its `Media` (`Doctrine/MediaFileListener`); a purged club has the files of its
  media deleted before the database cascade (`Tenant/ClubDeletion::purge`).
- A relation written by a client is an IRI only: `#[ApiProperty(writableLink: false)]`, so a nested
  object (which the `entity:id` group would otherwise let through as a new record) is a 400. Reads
  embed a summary of the related record through the reader's group (`team_member:read` on
  `Player::$firstName`…), never its private fields.
- Club-scoped resources are read through the `X-Club-Id` header (400 missing, 403 neither a member nor platform staff, §4 sexies); the `club_scope` SQL filter is always on; the club of a new record is set server-side;
  permissions live in `ClubPermission` (defaults by role, `held()`) + `ClubPermissionVoter`.
- An access token is accepted only while its session (refresh-token family, claim `sid`) is alive:
  `Auth/ActiveSessionListener` (`JWT_DECODED`) asks `RefreshTokenRepository::isSessionActive` on each
  request, so a sign-out, a password change or reset, a reuse or an account deletion takes effect at
  once. Tests open the session row directly (`ApiDatabaseTestCase::openSession`). Set aside: waiting
  for the 15-minute expiry, a revocation list in a cache (one more store for one indexed query).
  The dates of a token are checked with a **10-second tolerance** both ways (`clock_skew: 10`, audit API-SEC-09): at 0
  a clock put back by one second (time synchronisation; a virtual machine under load, which made two full test runs fail
  with `401 Invalid JWT Token`) made a token issued a moment ago look like it came from the future. The tolerance is no
  weakening: the token lives 15 minutes and a revoked session is refused whatever the dates. A gap of two minutes is still
  refused (`AuthenticationSecurityTest`).
- The user's sessions (`ApiResource/MySession`, read model of `RefreshToken`, never a token):
  `GET /me/sessions` (families that can still be renewed, from
  `RefreshTokenRepository::activeSessionsOf`: start = first token's `createdAt`, last use = last
  token's, `deviceLabel` given at sign-in, `current` = the `sid` of the request), `DELETE
  /me/sessions/{id}` (someone else's → 404), `POST /me/sessions/revoke-others`. No column added:
  tokens are kept until the end of their session (`deleteExpired`).
- An operation without identifier in its path (`/me`) reads its provider before a `Patch` only with
  `read: true`; without it the payload is deserialized into an empty object and a merge-patch
  clears every field it does not send.
- **`app:deploy:check`** (audit API-SEC-06, `Command/DeployCheckCommand`): run after every deployment, exits 1 when the
  server kept something of development — `APP_ENV` / debug, an `APP_SECRET` or `PII_KEY` equal to the one committed in
  `.env.dev` / `.env.test`, an unreadable JWT pair, `CORS_ALLOW_ORIGIN` accepting localhost, a front-end URL over HTTP or on
  localhost, `MAILER_DSN=null://`, the placeholder database password, `MEDIA_STORAGE_DIR` under `public/` or not writable,
  `var/` not writable, development dependencies installed, pending migrations. `TRUSTED_PROXIES` empty is only a warning. The
  logic is `problems()`, tested value by value in `DeployCheckCommandTest`; the "dev tools installed" fact is injectable
  because the test suite itself needs them.
- **Security headers** (`Http/SecurityHeadersListener`, audit API-SEC-01): every API response forbids sniffing, referrers,
  framing (`X-Frame-Options: DENY`), loading anything (`Content-Security-Policy: default-src 'none'; frame-ancestors
  'none'`) and the camera, microphone and location; over HTTPS it also says `Strict-Transport-Security: max-age=31536000`
  — without `includeSubDomains`, because other sites of the same domain may not be on HTTPS; behind a proxy `isSecure()`
  needs `TRUSTED_PROXIES`. The signed photos and videos get no content security policy, nor does anything in the `dev` environment, whose tools are pages with their own styles and scripts (Swagger, the profiler and its toolbar, `/uml-diagram`); production has none of them (`when@prod` in `api_platform.yaml`). Any change to these headers is checked in a browser: a unit test does not see a blocked stylesheet. If the web server adds the same
  headers, do not duplicate them.
- **Rate limits of the public endpoints** (`framework.rate_limiter`, applied by `Auth/RateLimitGuard`; audit API-SEC-02 /
  API-SEC-05): they are keyed on the client address, which a gym or a stadium shares, so they are sized for a club and
  count what is abusive, not what is normal. `login_ip` (60 in 5 minutes) counts **failed** guesses only: it is read at
  the start (`assertAvailable`, `consume(0)`, nothing counted) and counted where a guess fails — never `reset()` after a
  success, which would let anyone with one valid account start the count over between two series of guesses.
  `login_account` (5 in 15 minutes, per account and address) is unchanged. `refresh` (600 a minute, shared by renewing a
  session and signing out) is only a ceiling: a stolen refresh token works once (rotation, reuse revokes the session), so a
  limit per session would add nothing. **One exception, decided with the human on 2026-11-09 for the mobile app**: the answer to a
  refresh can be lost on the way (a phone in a gym) after the server made the rotation, and the retry would otherwise end the
  whole session. A replaced token presented again within `RefreshTokenManager::REPLAY_GRACE` (30 s) of its first use gets a new token
  of the same session; the delay is counted from the first use and never extended by retrying, a signed-out or expired session is not
  revived, and after the delay a reuse revokes the session as before (`AuthenticationSecurityTest`). The price accepted: a copy of the
  token used inside those 30 s also gets one. `token_submit` (30 an hour) covers the three single-use token endpoints. Behind a
  reverse proxy `TRUSTED_PROXIES` must be set, or every user shares the proxy's address and its budget.
- Auth answers never reveal whether an address has an account (same status, same timing).
  An SMTP exchange takes about a second and the auth flows only mail existing accounts, so every
  e-mail goes through `Mail/DeferredMailer`, which keeps it until `kernel.terminate`, after the
  response is sent (used by `Auth/AuthMailer` and `Tenant/ClubMailer`), and
  `Http/ContentLengthListener` gives every response a `Content-Length` so that even under mod_php
  the client does not wait for PHP to end. A test fails if an e-mail leaves before the response.
  Set aside: Messenger + worker (needs a supervised process the target host may not offer, see §5);
  synchronous sending with an artificial delay (still leaks on SMTP slowness, slows every caller).
  Left as is: an existing address costs a few dozen ms more (its token is written to the database).
- E-mail links point to `FRONTEND_URL` + `/verify-email?token=`, `/reset-password?token=`,
  `/confirm-email-change?token=`, `/forgot-password` (`Auth/AuthMailer.php`). The web and mobile clients depend on these paths. The
  invitation of an account created by the staff also uses `/reset-password?token=` (purpose
  `invitation`, 7 days), accepted by `POST /auth/password/reset`. A club invitation links to
  `/join?token=` (`ClubMailer::joinUrl`, also the link of a link invitation), a request to join to
  `/membres`; the account deletion e-mail to the home page.
- **The schema changes through migrations only** (audit API-TOOL-01, 2026-11-04). `migrations/` holds a
  baseline, `Version20261104101445` (the whole schema, 47 tables, generated from an empty database on
  MySQL 8.0, every table `ENGINE = InnoDB` / `utf8mb4_0900_ai_ci` written out), never edited again; every
  entity change gets its own migration (`make:migration`, read, then `doctrine:migrations:migrate`).
  `MigrationsTest` plays the migrations on an empty test database and fails if the result differs from the
  mapping (an entity changed without its migration); its `down` / `up` cycle is in the `slow` group
  (`bin/phpunit --group slow`, excluded from the everyday run by `phpunit.dist.xml`). A development
  database that predates the baseline is marked up to date once (Readme), not migrated. The versions
  table of Doctrine Migrations belongs to no entity: tests that scan the whole schema
  (`MappingTest`, `UuidPrimaryKeyTest`) leave it aside. The baseline's `up()` first converts that table to
  InnoDB: Doctrine creates it without an engine and the shared server defaults to MyISAM. Set aside: a
  `doctrine.dbal.schema_filter` hiding that table (Doctrine Migrations then no longer sees it and tries to
  create it again: « table already exists »), `doctrine:schema:update` outside a throwaway database.

- **Code quality is checked by tools** (audit API-TOOL-03, 2026-11-04): `composer qa` = `cs` (PHP-CS-Fixer,
  `@Symfony`, `migrations/` left out as generated) + `stan` (PHPStan level 6 with the Symfony, Doctrine and
  PHPUnit extensions included by hand, not through `extension-installer`, to keep one Composer plugin less) +
  `test`. The 52 errors that existed are frozen in `phpstan-baseline.neon` (21 in `src/`, none a bug: redundant
  checks, missing generics on the decorated processors); a new one fails, a fixed one must leave the
  baseline (`composer stan:baseline`). Goal: level 8, one level at a time. The test helpers' `array<string,
  mixed>` JSON bodies make every key read an `offsetAccess.notFound`: ignored in `tests/` only, never in `src/`.
- **A page costs the same number of SQL statements whatever it shows** (audit API-PERF-01 / API-PERF-02,
  `tests/Api/QueryCountTest.php`). A normalizer runs once per record, so what it needs from the database is read **once
  per request** for the whole list and kept (`MembershipNormalizer`, `TeamNormalizer`, `UserNormalizer`: `??=` on an
  array, cleared by `reset()` — they implement `ResetInterface`), with repository methods that answer for the whole page
  (`PlayerRepository::recordIdsByAccountIn()`, `recordIdsByClubOf()`, `TeamRepository::countsByClubOf()`,
  `rolesByTeamIn()`: plain SQL scoped by the club or account given). Before: a member list of 30 cost 60 statements (3 members:
  13), the memberships of an account in 6 clubs 21 (1 club: 6), 20 teams 24 (2 teams: 6); now 5 to 6 each, whatever the
  size. `Tests\Support\QueryCounter` is a DBAL middleware counting the statements, **static** because the container hands out
  more than one instance; `countStatements()` resets it just before the request, so prepare the headers first
  (`headersFor()` writes). An unmeasured request goes first: at most once a minute the end of a request looks for
  e-mail digests that are due (one more statement), and the first request after that minute pays it.
- **No `@` in front of a call that can fail** (audit API-CLEAN-02): `MediaStorage` looks (`is_file`, `is_readable`) and says
  what is wrong with the key (`missing`, `cannot be read`, `not stored by chunks`), never the path of the server. The only
  `@` left is `@unlink` of a temporary copy in the `finally` of `VideoUploader`, with its reason.
- **A device catches up with `updatedAt[after]`** (audit MOB-01, 2026-11-04): the lists a device keeps a copy of (teams, players,
  team members, games, planned trainings, runs, exercises, sessions, `/memberships`, `/clubs/{id}/memberships`, `/clubs`) take
  `?updatedAt[after|before|strictly_after|strictly_before]=` (`DateFilter`, the description is `Sync\Protocol::UPDATED_AT_DESCRIPTION`,
  declared as a `QueryParameter` on each `GetCollection`). The protocol (read every page, keep the greatest `updatedAt`, ask again
  from a minute before it, the boundary included) is in the Readme. `Doctrine/StableOrderExtension`, tagged by hand in
  `services.yaml` at priority -40 (after the filters and API Platform's own order at -32, before the pagination at -64), ends the
  order of any operation that has the `updatedAt` parameter with the identifier, so that records of the same second do not move between
  pages; `UpdatedSinceTest` checks the SQL (the default order is kept, `id ASC` comes last; at priority -10 it would swallow the default
  order, a mutation that test catches). A new synchronisable list: add the `updatedAt` parameter and a line in that test. Not added
  (measured, 62 000 games, 2 000 in the club): `(club_id, updated_at)`, which saves 1.7 ms (2.6 to 0.9 ms) and removes no scan.
  Set aside: an `order[updatedAt]` parameter (the device reads every page, so the order does not matter, and the one of `Player` is
  reserved to staff).
- **A read the device already has answers 304** (audit MOB-07, 2026-11-04): API Platform tags every successful read with the hash of
  its body (`etag`, on by default; `cache_headers.vary` already names `Authorization` and `X-Club-Id`) but nothing compared the tag with
  the request, so `If-None-Match` was ignored. `Http/NotModifiedListener` (`kernel.response`) calls `Response::isNotModified()` on every
  cacheable 200 that has a tag: 304 without a body when it matches, 200 otherwise. The answers to authenticated requests stay
  `no-store` (SecurityHeadersListener): no browser or proxy sends a tag by itself, an application that keeps its own copy does,
  and a 304 reveals nothing it does not hold (the tag is the hash of a body it has). The server still builds the answer: what is saved is
  the transfer. `ConditionalRequestTest`: 304 and no body, 200 after a change, a tag of one club never validates another's list.
- **Versions of the API and of the apps** (audit MOB-03, 2026-11-04): the policy (added = compatible, removed or renamed = a new major
  version served next to the old one for six months) is in the Readme. `app.api_version` (`services.yaml`) is the single version, also
  the OpenAPI `info.version`. `GET /api/public/meta` (`ApiMeta`, `State/Meta/ApiMetaProvider`; under `/api/public/` because that prefix is
  already the anonymous one in `security.yaml`, where the audit proposed `/api/meta`) gives it with `minSupportedClient` (`MIN_CLIENT_*`
  environment variables, absent or empty = no minimum). `X-Client-Version` is read by `Logging/ClientVersionProcessor` only: it puts a
  short plain value (`[A-Za-z0-9._+/-]{1,40}`, anything else is ignored, a header is the client's to write) in the `extra.client` of
  every log record of the request, so that an error shows which app caused it; it is allowed by CORS and never changes an answer.
  `tests/fixtures/openapi.contract.txt` (2 846 lines: routes, parameters, response codes, fields with their type and `*` when
  required; the JSON-LD copies of the schemas left out) is compared with the live OpenAPI document by `OpenApiContractTest`, which fails
  on any difference and says whether something was removed (a break) or only added (write it down, `UPDATE_OPENAPI_CONTRACT=1`).
  A route added without being registered for the access matrix, a field renamed for a serialisation group: both show up there.
- **`/me/stats` carries 300 games at most** (audit API-PERF-03, 2026-11-04; the cap proposed in the audit, kept): `MyStats::MAX_GAMES`.
  Each club is read for its 301 most recent games (`setMaxResults`, `scheduledAt DESC, id DESC`; the raw counts follow the same ids),
  the clubs are merged, the 300 most recent kept with only their clubs, teams and counts, and `truncated` says there were more (a
  narrower `from` / `to` reaches them). Exactly 300 is not truncated. Before: no bound (a career of 100 games is ~30 000 events in one
  answer). The games' sheets are still read game by game (sets, events), which the cap bounds without removing.
- **Deletions are told to the devices** (audit MOB-02, 2026-11-04; the recommendation of the audit, tombstones rather than a
  generalised soft delete, which would change every query and every test): `DeletedRecord` (`deleted_record`: `type` = `SyncType`,
  `record_id`, `club_id` or `user_id`, `audience` = `DeletionAudience`, `deleted_at`; no foreign key, no `ClubScopedInterface`: it is only
  read by `DeletedRecordRepository::since()`, where the rule of who may read what is written). `GET /api/sync/deletions?since=`
  (`Deletion`, `State/Sync/DeletionsProvider`, `X-Club-Id` optional) gives what the caller could read: the lines of their club for the
  audiences they hold (`club`; `games.write` for the games only the staff reads; `trainings.write` for runs) plus their own (`owner`: the
  authors of an exercise, a session or a private game), never another club's; 90 days kept (`DeletedRecordRepository::RETENTION`, purged by
  `app:tokens:purge`), older `since` = 410. **Written in the transaction of the deletion, by two means**: `Doctrine/DeletionListener`
  (`onFlush`: every entity of those types scheduled for deletion, and, before the database deletes them, the children it cascades: the places
  of a team or a player, the runs of a planned training) and `Sync/DeletionLog` for what is deleted behind the entity manager (the places of
  an archived team or player or of a membership that ends, the trainings to come of a deleted session, the coach places of an erased account),
  called before the deletion. A new deletion of one of those records outside the entity manager must call `DeletionLog`;
  `DeletionsTest` plays each path. Archiving a team or a player is told as a deletion (it leaves the lists); archiving an exercise or a
  session is not (it moves to another `scope`). Not told: what a person can no longer read without a deletion. Over-reporting inside a
  club is accepted (a `team` game is told to the whole club), across clubs never; `ClubDeletion` (the club itself) is not told.
  **A deletion also changes a parent the entity manager never sees** (the database applies the foreign key rule): deleting an exercise
  removes its slots from every session that placed it (`ON DELETE CASCADE`), deleting a session empties `session` of the trainings
  already held with it (`ON DELETE SET NULL`). `Doctrine/CascadeTouchListener` (`onFlush`, plain SQL, before the deletion, same
  transaction) gives those sessions and trainings a new `updatedAt`, so a device that catches up with `updatedAt[after]` reads them
  again (`UpdatedSinceTest`). A new foreign key that cascades or nulls on a synchronised record needs the same.
- **Words of the code and words of the screens** (audit VOCAB-01 to VOCAB-05, decided 2026-11-04): the API keeps its names (`Game`,
  `Exercise`, `StatOutcome::Error`/`Kill`, `StatSkill::Set`, `TrainingSession`, `PlannedTraining`, `TrainingRun`, `trainingSchedule`) and the
  apps show: *match* for a game, *exercise* (a *drill* or a *lesson*), *error* and *kill*, *setting* for the pass (a *set* is the period of a match),
  *session*, *planned training*, *run* and *slot*. The table is in the web `STRUCTURE.md` (§5 bis, "Vocabulaire figé"), a test there keeps the
  labels to it; nothing to rename here, and an OpenAPI description may keep saying "game".
- **The suite is fast because the schema is only rebuilt when it changed** (audit API-TEST-07, 2026-11-04). Measured with
  `--log-junit`: 602 tests took 5 min 16 s, of which two rebuilds of the schema (drop + create of every table, ~22 s each on
  the shared server, one per base class `DatabaseTestCase` / `ApiDatabaseTestCase`) and `MigrationsTest` (80 s, it rebuilt
  the schema once more before dropping it). `Support\ResetsDatabase` now compares the database with the mapping
  (`SchemaTool::getUpdateSchemaSql`, the versions table of Doctrine Migrations left aside) and only rebuilds when they differ,
  i.e. after an entity changed; otherwise it empties the tables, as before. Now 3 min 25 s for the same 602 tests and 5 169
  assertions; a run right after a mapping change still pays the rebuild. What is left is ~0.25 s per HTTP test (a kernel
  booted for each request) and four tests of 7 to 23 s (`MigrationsTest`, two in `RoleMatrixTest`, `GameTest` ~2 s). Going
  below two minutes takes parallel runs (paratest, one database per process): set aside with the test infrastructure.
- **An index is added when a measure shows it removes a scan** (audit API-PERF-04, 2026-11-04): EXPLAIN and timing of the
  real SQL (captured from the logs of a real request) on a volume 100 times the demo data (80 000 exercises, 60 800 games,
  30 300 planned trainings), before and after. Kept: `planned_training (club_id, scheduled_at)` (the agenda: 6.1 ms and
  15 150 rows read, then 0.8 ms and 209), as a real migration and `tests/Entity/IndexesTest.php`. Measured and **not**
  added: `game (team_id, scheduled_at)` (3.2 ms either way: the team already narrows to a few hundred rows) and
  `exercise (visibility, archived_at, updated_at)` (258 ms, 265 ms: the public list is a `DISTINCT` over joins with an
  `OR` of `EXISTS` for who may read, so no index can serve the filter and the sort). The public exercise list is the one
  query to watch (about 250 ms for 20 000 public exercises, growing with them): the fix is the shape of the query, not an
  index, and belongs with the library search. New indexes go through `doctrine:migrations:diff`, never by hand.
- **Access is tested by construction, not resource by resource** (audit API-TEST-01, `tests/Api/RoleMatrix*.php`).
  `RoleMatrix::OPERATIONS` states, from the rules of the product, who may use each operation of the club-scoped
  resources (`member`, `staff`, `admin`); `RoleMatrixTest` fails if a club-scoped operation has no line (or a line has no
  operation), if an operation of any other resource has no `security` expression and is not listed with the reason
  (`DECIDED_ELSEWHERE`, `LISTED_THROUGH_AN_EXTENSION`), and plays every operation against real records with a player, a
  coach, an administrator, somebody who is in another club only and sends this club's header (403), and the
  administrator of another club asking for a record by its identifier (404). Adding an operation means deciding
  its audience in that file. The records are inserted in plain SQL with fixed identifiers and made again before every
  operation that changes something (an entity made before a request belongs to a kernel that is gone by the next one).
  Mutations checked: opening a `PATCH` to every member, or removing the rule of a `DELETE`, are both caught.
- **Logs** (audit API-TOOL-04, 2026-11-04; Monolog): `var/log/dev.log` in dev; in production `var/log/prod.log`,
  kept 14 days (`rotating_file`, written only when a request ends in an error: `fingers_crossed` at `error`, 404/405
  left out) and `deprecation.log` 7 days — not `php://stderr`, which on a shared host ends up in a log nobody reads.
  `Logging/RedactAddressesProcessor` runs on every record: any e-mail address in the message, the context or the
  extra becomes `[address]`, and an exception of the context is replaced by a description of it (class, code, redacted
  message, redacted trace, previous), because an SMTP answer to a refused recipient quotes the address. Text that is not valid UTF-8 (the binary ids of the
  SQL parameters in dev) is read byte by byte, never replaced whole. What the client
  got wrong is information, not an error: `framework.exceptions` logs `HttpExceptionInterface`,
  `NotNormalizableValueException` and the serializer's `UnexpectedValueException` (malformed JSON, an IRI pointing to
  nothing) at `info`; a 5xx stays `critical`. Set aside: a JSON formatter in production (stack traces unreadable in a
  cPanel file viewer), mapping only the subclasses of `UnexpectedValueException` (the 400s come from the base class).
  In tests every record stays in memory in the public `test.logs` service (`TestHandler`).
- **Git hooks and CI** (audit TOOL-05 / TOOL-02, 2026-11-04): `lefthook.yml` at the repository root — pre-commit: secrets
  (`scripts/gitleaks.sh`, the official image pinned to `zricethezav/gitleaks:v8.30.1`; no binary downloaded) and
  `composer cs`; pre-push: `composer stan`; commit-msg: `scripts/check-commit-message.mjs` (`type: 🐛 message`, no
  assistant credit). The PHP steps go through `scripts/php-qa.sh`, which runs them in the dev container and lets a
  container that is down pass with a warning (a failing check always fails). The hooks need the lefthook binary and one
  `lefthook install`. `.gitleaks.toml` lets through only `app/.env.dev` and `app/.env.test`, whose values are meant for
  development and tests. The CI is a model, `docs/ci/github-actions.yml.example`, kept out of `.github/workflows/` on
  purpose (human decision: no CI before the production deployment on o2switch); it has never run.
- **Coverage is measured and has floors** (audit API-TEST-05): PCOV is installed in the dev image but off
  (`pcov.enabled=0`, so requests are not slowed down); `composer test:coverage` turns it on and
  `bin/check-coverage` fails under the floors it holds (2026-11-04, after the audit's tests: 95.2 % of the lines overall,
  7467 of 7844; it was 93.4 % at the first measure; `State` 95.1, `Security` 95.4, `Doctrine` 95.5, `Entity` 96.0, `Auth` 97.0,
  `Tenant` 98.7, `Serializer` and `Http` 100). A floor is the measured value rounded down: raised when the coverage rises,
  never lowered to let a change through. The weakest areas are `Notification` (74 %), `Command` (80 %) and `Media` (86 %).

## 4 ter. Clubs, members, invitations, players and teams

- **Club roles** (`Enum/ClubRole`, decided with the user): `club_admin`, `coach`,
  `community_manager`, `player`, and a member holds **one or several** at once (`Membership.roles`,
  `Invitation.roles`, `roles` of a join request: JSON lists, one at least, stored once each in the
  order of the enum by `ClubRole::normalize()`). The rights add up (`ClubPermission::isGrantedToAny`).
  `Membership.admin` repeats « `club_admin` is held » in its own column so that SQL and DQL find the
  administrators (`countAdmins`, `MyClubsExtension`, join requests) without reading JSON; it is set
  by `setRoles()` only. The stored property is `roleValues` (column `roles`): named apart, so that
  the serializer reads `list<ClubRole>` from the setter. The last administrator cannot lose
  `club_admin` (409), adding roles to them is fine. E-mails and notifications name the roles in a
  sentence (`ClubRole::describe`, data `roles` = values joined by commas).
- **Community manager** (decided with the user): speaks for the club (`community.publish`), moderates
  under its posts (`community.moderate`: deletes its posts and the comments under them), keeps its
  public page (`club.profile`: name, address, website, `listedInDirectory`, logo; the other fields of
  `PATCH /clubs/{id}` — `defaultTrackingMode`, `nameDisplay`, the audiences — need `club.manage`,
  403 otherwise, `UpdateClubProcessor::MANAGED_FIELDS`), and reads the club like any member. A coach
  does not publish in the club's name. Set aside: a fixed role ladder, one role per member.
- **Permissions managed by the club** (decided with the user: by role and per person, the
  administrators keep everything): `ClubPermission::roles()` are the defaults; the club replaces
  what a role holds (`Club.rolePermissions`, column `role_permissions`: only the roles it changed,
  `PATCH /clubs/{id}`, `club.manage` only) and gives or takes one permission from a member
  (`Membership.grantedPermissions` / `revokedPermissions`, `PATCH /memberships/{id}`,
  `members.manage`). `ClubPermission::held()` adds it up (taken > given > roles) and is the only
  place that does: `Membership::getPermissions()` (sent to the client as `permissions`),
  `CurrentClub::permissions()` (filled by `ClubContextListener`), the voter, `PostAccess`,
  `VisibleGamesExtension`. Never configurable (`isConfigurable()`): `club.view`, `club.history`,
  `club.manage`, `members.manage` — whoever got the last two would give themselves the rest —, and
  `media.upload`, which guards no operation yet. Set
  aside: free permission groups, a permission per team.

- A membership exists only once someone is in the club: created with the club for its creator
  (`CreateClubProcessor`) or by accepting an invitation. There is no pending membership (the former
  `status` column was removed): what is pending is an `Invitation`.
- `Invitation` (club-scoped, `/invitations` with `X-Club-Id`, `members.manage`; decided with the
  user, 2026-10-29: by e-mail or by link, for one person): roles and optionally the player record to
  link, valid 7 days, limited to 30 per hour per administrator. `kind` is written (`email` default,
  `link`) and read from the address (null = link). E-mail: one per address and club (inviting again
  renews it and mails again); the answer never tells whether the address has an account or is a
  member. Link: no e-mail, never `club_admin` (422 code `LinkInvitationAdmin`), one per record (a new
  link for the record replaces it). Each send or `POST /invitations/{id}/link` (link only, 409
  otherwise) makes a new token (`OpaqueToken`, only `tokenHash` stored): `link` is returned that once,
  the previous link dies.
- The invited person answers through `ReceivedInvitation` (`/me/invitations`, accept, decline:
  **bound to the confirmed address** of the signed-in user), or from the link (`ApiResource/InvitationLink`):
  `GET /public/invitations/{token}` (anonymous, `InvitationPreview`: club, roles, inviter, first name
  of the record, masked address; `invitation_view` 100/h per IP), `POST /me/invitation_links/{token}/accept
  {code}` → `{clubId, playerId}`. A link lets in the first account (single use); an e-mailed invitation
  lets in the account of its address, or another account once it typed the six-digit code mailed to
  the address by `POST /me/invitation_links/{token}/code` (`Tenant/InvitationCode`: HMAC with the app
  secret, 10 minutes, the asking account only, void after 5 wrong tries, `invitation_code` 5/h per
  account, 409 when no code is needed; 422 codes `InvitationCodeRequired`, `InvitationCodeInvalid`).
  So a forwarded e-mail still lets nobody else in. Token and address lookups are the lookups across
  clubs (`InvitationRepository::findReceived` / `findOneByToken`, club filter suspended for them
  alone, refused while a club is selected). Accepting creates the membership (an existing member keeps
  their roles), links the player record if it has no account and the user none in the club, then
  deletes the invitation; the administrators are told how when it was not at the user's own address
  (`membership.joined` `data.via` = `link` | `code`, `data.player`). Every way into an existing club
  goes through `Tenant/ClubJoin::join()`.
- **Club search** (`ApiResource/ClubDirectoryEntry`, `Tenant/ClubDirectory`, decided with the user):
  `/directory/clubs?search=&city=&page=&itemsPerPage=` (`search` = in the name, `city` = in the city,
  each optional: human decision, 2026-10-30, "by name, a city may be added") and
  `/directory/clubs/{id}` show every active club
  unless its administrators turned `Club.listedInDirectory` off, and a member's own club: address,
  website, `hasLogo`, team names (not archived), `teamsCount`, `membersCount`, `myStatus` (`member` |
  `invited` | `requested` | null), never a person. Counts and team names are plain SQL (outside the
  club filter, the reader is not in the club). Logo: `POST` / `DELETE /clubs/{id}/logo`
  (`club.profile`, `PhotoUploader`), served by `/directory/clubs/{id}/logo` to whoever may find the club.
- **Request to join** (`Entity/JoinRequest`, club-scoped like `Invitation`, one per user and club,
  encrypted `message`): the person through `ApiResource/MyJoinRequest` (`POST /me/join_requests`
  `{clubId, message}` — an id, the club IRI only resolves for members —, list, `DELETE`; 404 outside
  the search, 409 already a member or invited, asking again replaces the message without a new
  e-mail, `join_request` limiter 10/h); the administrators through `/join_requests` (names and
  confirmed address of the person) and `POST /join_requests/{id}/accept` `{roles, player IRI | null,
  createPlayer}` → `ClubJoin` (a record without account, or a new record named after the account;
  422 otherwise), `DELETE` = decline, the person is not told. The administrators are mailed with a
  link to `FRONTEND_URL/membres` (`ClubMailer::sendJoinRequest`). Joining any other way deletes the
  request.
- A record may give the address its player signs in with (`Player.signInEmail`, staff only,
  encrypted, one per address in a club, cleared once an account is linked). The account that
  confirmed that address finds it in `/me/invitations` with `source: record` (id = the record, no
  expiry, only the club's name), unless an invitation already names the record
  (`State/Invitation/OfferedRecords`, `PlayerRepository::findOfferedTo` with the blind index, same
  cross-club rule as `findReceived`). Accepting joins as a player linked to the record; declining
  clears the address from the record. No e-mail is sent: "Invite" stays the way to mail someone
  (decided with the user). Expired invitations are purged by `app:tokens:purge`. Set aside: a link
  for the whole club used by many (a club holds data about minors: a link stays one person's), a link
  that makes an administrator, accepting an e-mail from another account without proving the address,
  memberships with a pending status (an invitation to an address without account could not be one).
- `Player` is the club record of a player, with or without an account; `TeamMember` places a player
  record (jersey number unique in the team) or a coach account (`ClubStaff`: admin or coach of the
  club) in a team. A player in two teams has one record. Coaches always have an account: the app is
  for coaches. Set aside: one record per team (names typed twice, stats split), records for staff
  without account.
- **Deletion with a grace period** (decided with the user: leave room for mistakes, make recovery
  easy). Nothing is erased on request: `Auth/AccountDeletion` and `Tenant/ClubDeletion` schedule it in
  30 days (`DELAY`), and `app:deletions:purge` erases what is due.
  - Account (`DELETE /users/{id}` by the staff, `POST /me/deletion` + password by the owner): asleep
    (sessions revoked, `UserChecker` refuses its tokens, left out of member lists, `findFor` and
    rosters' coaches, not counted as administrator). Signing in cancels an owner's request
    (`accountRestored` in the token pair, e-mail); a staff decision only by `POST /users/{id}/restore`
    (sign-in answers 423 "disabled", distinct from the 403 of an unconfirmed address). The last administrator of a club still gets a 409. Erasure
    keeps what the clubs own: player records (unlinked), their team places and stats.
  - Club (`DELETE /clubs/{id}`, any administrator, every administrator is e-mailed): hidden from its
    members, read-only for its administrators (`ClubContextListener`: 403 for the others, 409 on a
    write; `UpdateClubProcessor`, membership processors), `POST /clubs/{id}/restore`. When the grace
    period ends the club is **closed** (`closedAt`, `ClubDeletion::close`), not erased: history for
    every member (see « History »). `ClubDeletion::purge` erases a closed club once no account is
    linked to it (no membership, active or ended, and no record of an account), in plain SQL since
    the club filter hides records from a console command.
  - 30 days for accounts because the GDPR gives one month to act on an erasure request (art. 12.3);
    the user had asked for 60 days unless the law set a limit. Set aside: immediate deletion,
    restoration by the club creator only (no creator is recorded; any administrator restores).
- **Preferences** stay on the account, never copied to the clubs (`PATCH /me`): `locale`, any BCP 47
  tag without extensions (`User::LOCALE_PATTERN`: `fr`, `pt-BR`, `zh-Hant`; the apps offer the
  languages they are translated into, null = the device's language), `theme` (`Enum/AppTheme`: `dark`, `light`,
  `system`, `contrast`; null = dark, decided by the apps), `palette` (`Enum/AppPalette`: `myvolleyball`,
  `blue-yellow`, `red-green`, `beach`, `purple-orange`; a second axis next to the theme, null = automatic: the
  colours of the club when it applies them to the interface, else `myvolleyball`, decided by the apps; the
  colours themselves live in the apps), `contentLanguages` for the community feed
  (null in the database = every language; the shape of an ISO 639-1 code is checked by a regex,
  `Assert\Language` would need `symfony/intl`, a new dependency for a preference), `privateAccount`
  (§4 novies).
- **Personal profile** (decided with the user): `Entity/PersonalProfileTrait` holds the fields that
  describe a person whatever the club (nickname, `NameDisplay` choices, gender, height, hand, reaches,
  and encrypted birth date, licence, `contactEmail`, phone, guardian), used by both `User` and
  `Player`, so the rules exist once. The account owns its profile (`/me`, `/me/photo`); each club
  where it is a member keeps a copy on its player record (`Profile/PlayerProfileSync`: on every
  change, and when an accepted invitation links a record, which first fills what the account leaves
  empty). A club the user left keeps its last copy. The photo is copied as one file per club, so each
  owner deletes its own. While the record is managed by its player, the staff cannot change those
  fields (`Validator/ProfileOwnedByPlayer`, 422 with its code) nor the photo (409); the positions stay
  the club's. A single record says so in `managedByPlayer` (set by `PlayerNormalizer`, null in lists:
  one query per record). Set aside: a record edited club by club (the person retypes everything, clubs drift
  apart), a record read through from the account (a club would lose the data with the account).
- **Playing in one's own club** (decided with the user, 2026-10-29: whoever creates a club had no way
  to add themselves as a player). A member of the staff (`players.write`, an active member: never the
  platform staff visiting) links a record to **their own account** (`Profile/PlayerRecordLink`):
  `POST /me/player_record` (no body, `X-Club-Id`) creates it named after the profile (422 code
  `ProfileNameMissing` without a name), `POST /players/{id}/claim` takes a record without an account
  (409 one with an account, 404 another club's or archived). Either way: 409 if the user already has a
  record in the club (archived included), the sign-in address goes, `PlayerProfileSync::claim` (so
  the comparison below applies), and the membership gains `player`. `/memberships` carries
  `myPlayerId`. The staff does the same for **another active member** (decided with the user,
  2026-10-29: told, not asked): `POST /memberships/{id}/player_record {player: IRI | null}` (404 not a
  member of the current club or archived record, 409, 422 `MemberNameMissing` at `player`),
  notification `player_record.linked` → `/ma-fiche`; `/clubs/{id}/memberships` carries `playerId`.
  Set aside: the detour of a record giving one's own sign-in address then accepted as an invitation
  (nobody guesses it), a link to any account written by the client (only a member of the club),
  asking the member first.
- **Two records, one person** (decided with the user: compare after joining, never before). When an
  account takes over a record (`PlayerProfileSync::claim`), a field only one side fills is taken at
  once; a field both fill differently (`REVIEWED_FIELDS`: names, profile, `photo` when both have one)
  is not overwritten: the record gets `profileReviewSince` and `push()` skips it. The person reads
  `GET /me/profile_reviews` (`ApiResource/ProfileReview`: `fields[]` `{field, mine, theirs}`,
  computed at read time) and answers `POST /me/profile_reviews/{id}/resolve` `{take: [fields]}`:
  taken values go to the profile, then the profile goes to every record. Records are never merged
  nor deleted, so each club keeps its statistics. Set aside: showing the differences before joining
  (a mistyped address would show a minor's record to a stranger), the account always winning (the
  former behaviour: a club's data silently replaced).
- `contactEmail` is the address a person gives to the clubs, never the sign-in `email` of an account
  (whose change will get its own confirmed flow).
- `displayName` (Player) is the name in the record's `NameDisplay` format (`full`, `nickname`,
  `full_with_nickname`, `first_name_initial`, `last_name_initial`); a format without nickname falls
  back to the full name. `publicNameDisplay` names the account in the community (§4 novies).
- **Contact details, banner and background of a club** (decided with the user, 2026-11-15): `Club.phone`
  (digits, spaces and `+ ( ) . -`), `email` (`Assert\Email`), `description` (2000 characters, refused with
  invisible characters by `CleanTextListener` like any text), `publicContact` (JSON, values of
  `Enum/ClubContact`: `address`, `phone`, `email`, `website`; null = `address` + `website`, the behaviour
  from before, read through `getPublicContact()`), `backgroundColor` (`#rrggbb`, lower case) and `banner`
  (`Media`, same relation as `logo`). Written by `PATCH /clubs/{id}` under `club.profile`, like the rest of
  the public page. `POST|DELETE /clubs/{id}/banner` (multipart `file`, `club.profile`, 409 on a club being
  deleted or closed) go through the same `PhotoUploader` as the logo (JPEG or PNG, 5 MB, pixel and size
  checks, GD re-encode, metadata dropped) at `PhotoSanitizer::POST_MAX_SIDE` (1600 px); served by
  `GET /directory/clubs/{id}/banner` (`ClubBannerProvider`, same readers as the logo, `Cache-Control:
  private, no-store`). `/directory/clubs[/{id}]` shows `phone`, `email`, the address and the website
  **only if the club put them in `publicContact`, or if the reader is a member** (`Club::showsContact`),
  plus `description`, `hasBanner` and `backgroundColor` (the latter only when the club shows its colours on
  its page). Migration `Version20261115120000`.
- **Look of a club and of its records** (decided with the user, 2026-11-05): `Club.primaryColor` and
  `secondaryColor` (`#rrggbb`, kept in lower case, `Assert\Regex`) and `appearanceSurfaces` (JSON,
  values of `Enum/ClubAppearanceSurface`: `page`, `player_records`, `documents`, `interface`; null in the
  database = everything but `interface`, read through `getAppearanceSurfaces()`). Written by `PATCH
  /clubs/{id}` under `club.profile` (administrators and community managers), so not in `MANAGED_FIELDS`
  of `UpdateClubProcessor`; read with `/clubs/{id}` and `/memberships` (the app colours its interface
  from the latter). `Club::colorsFor(surface)` gives the colours of one place or null (no colour, or the
  club did not choose that place). `/directory/clubs[/{id}]` carries `appearance` = `colorsFor(page)`.
  A player with an account chooses the look of their own records (`PATCH /me`): `recordAppearance`
  (`Enum/RecordAppearance`: `club`, `default`, `chosen`; null = `club`) and `recordAppearanceClubId`,
  checked by `UpdateMeProcessor` only when the choice changes (a club the user belongs to, else 422 code
  `RecordAppearanceClub`; any other look keeps no club; `User.recordAppearanceClub` is `SET NULL` with the
  club). `Tenant/RecordAppearanceResolver` gives the colours a record is read in: no account = its
  club's; `default` = none; `chosen` = that club's, while the user is a member and the club shows its
  colours on records; else its club's. A single record carries them as `appearance` (set by
  `PlayerNormalizer`, null in lists), colours only, never the name of the club they come from. Set
  aside: a background image (a file to store and moderate), a per-user look for the whole app (it
  is the club's `interface` place), the record look read from the reader's club.
- **Privacy of player records** (decided with the user): `Privacy/PlayerPrivacy` decides, record by
  record, what the reader sees. The staff of the club and the player see everything; the other
  members see `displayName` (never the names) and, per `ProfileDetail` (photo, age — never the birth
  date —, sporting profile, contact address), what the `Audience` chosen allows: by the player on
  their account (copied to the record), else by the coaches of their teams (`Team`, the most
  restrictive of several), else by the club (`Club`), else the defaults (the behaviour before the
  settings: sporting profile to the club, the rest to the staff). `PrivacySettingsTrait` holds the
  club and team choices, `PersonalProfileTrait` the person's. `PlayerNormalizer` turns the decision
  into groups (`player:name`, `player:photo`, `player:age`, `player:sport`, `player:contact`,
  `player:private`) for every record, summaries included (roster, score sheet), and
  `PlayerPhotoProvider` applies it to the photo. Accounts shown to members (member list, team
  coaches) follow the same name rule (`UserNormalizer`; `MembershipNormalizer` gives it the club of a
  member list read without a current club; in `/memberships` it adds `teamsCount` and `myTeamsCount`,
  read across clubs by `TeamRepository::countsFor()`, for the menu of the apps, and `myPlayerId`). `public` acts as `club` until public pages exist, except
  for the photo of an account, then shown in the community.
  `?search=` and `order[]` on players match the real names, so they are reserved to
  `players.private` (`security` on the parameter, 403 otherwise). Set aside: one setting per field
  (too many choices), the least restrictive team (a coach of minors must be able to close).
- Reading records of several clubs for server work (the profile copies) goes through
  `ClubScopeActivator::acrossClubs()`, which points the filter back at the current club afterwards.
  Never to build a response.
- **Jersey colours of a team** (decided with the user, 2026-11-12): `Team.homeJerseyColor`, `awayJerseyColor` and
  `liberoJerseyColor` (one libero colour per team), `#rrggbb` or null, written by `PATCH /teams/{id}`
  (`teams.write`, merge-patch) and read by every member. Same rule as `Club.primaryColor`
  (`Assert\Regex`, stored in lower case, 422 on the field). The apps copy them into a new game.
- **Training slots of a team** (decided with the user, 2026-10-30): `Team.trainingSchedule`, a JSON
  column written whole by `PATCH /teams/{id}` (`teams.write`), read by every member: `weekly`
  (`id`, `weekday` 1–7, `start` / `end` "HH:MM" in the club's wall-clock time, `location`,
  `validFrom` / `validUntil`), `extra` (a day) and `cancelled` (a day of a weekly slot), 50 entries
  at most. `Team::validateTrainingSchedule` checks the shape (422 on `trainingSchedule`); the getter
  gives back fixed keys in a fixed order (MySQL JSON reorders them). The app unfolds the days and
  merges them with the planned trainings. Set aside: a slot entity with its endpoints (the days are
  never queried by the server).
- **What the caller is in a team**: `myRoles` (`coach` through a place of their account, `player`
  through their record), added by `Serializer/TeamNormalizer` to a team read on its own or in the
  list (not to the team embedded in a game or a place), `TeamRepository::rolesOf`. The planning
  shows by default the teams one coaches or plays in.
- **Nothing a player is linked to is lost** (decided with the user: the stats survive while someone
  linked can read them). Deleting a team that games or attendance lists refer to archives it
  (`archivedAt`, `State/Team/DeleteTeamProcessor`), deleting a record linked to an account, called
  up or in an attendance archives it (`State/Player/DeletePlayerProcessor`); otherwise they are
  deleted. Archived: out of the lists (`Doctrine/HistoryAndArchiveExtension`) and of the teams,
  readable one by one, never written (`and not object.isArchived()` in `security`). A game deleted
  by its coach is really deleted (decided with the user).
- **History.** Leaving a club (or being removed) ends the membership (`endedAt`,
  `RemoveMembershipProcessor`) instead of deleting it; coach places go, the record stays linked but no
  longer receives the profile. An invitation accepted again reactivates it (one membership per user
  and club). A former member, or any member of a closed club, sending `X-Club-Id` gets a club that is
  history (`CurrentClub::isHistory()`, `historyUntil()` = when they left or the club closed): every
  write → 409, `ClubPermissionVoter` only grants `club.history` (the read operations of games and
  records ask for it instead of `club.view`), they read their own record and the games they recorded
  or were called up for (not private ones they did not record) up to that day, others' details stay
  hidden. `/memberships` lists these memberships with `historyUntil`; member lists only show active
  members. Set aside: the whole club frozen for former members (decided with the user: their own
  history only), purging a closed club after a fixed delay.
- Who reads what, field by field, and how long it is kept: `docs/personal-data.md` (repository root).
  A new field, group or access rule updates it in the same commit.

## 4 octies. Notifications

- **Model** (decided with the user: a notification centre plus counts, a choice per type): an
  `Entity/Notification` per recipient (type `Enum/NotificationType`, club, `subjectId`, `data` = names
  to show, never contact details, `readAt`), only the user's own (`Doctrine/MyNotificationsExtension`),
  kept 90 days (`app:tokens:purge`). Clients build the text from `type` + `data` and the link from
  `type` + `clubId` + `subjectId`.
- **Writing one**: `Notification/Notifier::notify($recipients, $type, $club, $subjectId, $data,
  $actor)` from the processor or service that makes the change, before its flush (nothing flushed
  there). The actor and accounts being deleted are skipped; `notifyMembers()` keeps the active members
  of the club only (records and team places may name someone who left). Never notify from a Doctrine
  listener.
- **Choices**: `User.notificationSettings` (JSON, only what differs from the defaults of
  `NotificationType::inAppByDefault()` / `emailByDefault()`), `GET` / `PUT /me/notification_settings`.
  `hasOwnEmail()` types (invitation, deletion of a club) keep their own e-mail, always sent
  (`Tenant/ClubMailer`); every other e-mail is a notification digest.
- **E-mail digests** (decided with the user: grouped, at most one an hour, nothing already read): a
  notification wanted by e-mail is stored with `emailPending` (and `inApp` false when the person wants
  it by e-mail only: hidden from every read, deleted once mailed). `Notification/NotificationDigests`
  sends what is due: a notification waits `HOLD` (15 minutes) to be read in the app, then everything
  still unread leaves in one e-mail, and nothing more for `INTERVAL` (1 hour, `User.notificationsEmailedAt`,
  booked by one conditional UPDATE so that two runs never both send). Runs at the end of any request
  (after the response, at most once a minute, DQL writes only: nothing the request left unflushed is
  flushed) and by `app:notifications:mail` from the scheduler (§5). Content: `NotificationMailer`
  (per type: title, sentence, action, path of the front end), templates `email/notifications.*.twig`.
  Set aside: Messenger + worker (no other process in production), a daily digest (an answer such as
  a join request would wait too long).
- **E-mail layout**: every e-mail has a text body and an HTML one, `templates/email/layout.html.twig`
  (inline styles and tables only). A plain-text message (`DeferredMailer::send`) is shown by
  `email/message.html.twig` (paragraphs, a line holding only a link becomes a link); a richer one goes
  through `DeferredMailer::sendTemplated` with its `.html.twig` / `.txt.twig` pair. English only, like
  every message of the API.
- **Reading**: `GET /me/notifications` (latest first, paginated), `POST /me/notifications/{id}/read`,
  `POST /me/notifications/read_all`, and `GET /me/notification_summary`, read again by the clients
  every minute (no push: production runs no other process): `unread`, the 5 latest unread (`recent`,
  toasts), and what waits (`invitations`, `profileReviews`, `joinRequests` per club administered).
- **Events**: join request received (admins) / accepted / declined (the person); invitation and
  record giving the address (the account of that confirmed address); record to compare; member joined
  (admins but the one who let them in; how, for a link or a code); made a player by the staff (the
  member); role changed; removed by someone else; put in a team; called up
  for a game still to come that they can read (team / club / public; the live saves notify only a
  change of the call-up); training of their team planned, still to come, `club` or `public`; club
  deletion scheduled / restored (admins); exercise unpublished by the moderation (authors); new
  follower, request to follow, request accepted, reaction, comment, reply, mention (§4 novies).

## 4 novies. Community

Decided with the user (2026-10-27): a classic community. Follows, then posts and the feed, likes,
comments and mentions, links, reports and videos, lot by lot.

- **Contacts** (human decision, 2026-10-28; `Contact`, `ApiResource/MyContact`): asked by one person
  (`POST /me/contact_requests {userId, message}`, message encrypted, 20 a day), accepted by the other
  (`…/{id}/accept`), distinct from following; asking back accepts. `GET /me/contacts`,
  `GET /me/contact_requests?direction=received|sent`, `DELETE /me/contact_requests/{id}` (decline or
  withdraw, nobody told), `DELETE /me/contacts/{id}` (either person). 422 `ContactSelf`, 409 already,
  404 outside the community. `/community/people/{id}` carries `myContact` `{id, status, direction}`;
  the notification summary `contactRequests`. Notifications `contact.requested`, `contact.accepted`.
- **Groups** (human decision, 2026-10-28; `UserGroup` + `GroupMember`, shortName `MyGroup`): invited by
  their admins, joined by those who accept (`GroupMember.joinedAt`), roles admin | member; name,
  description, 200 people. `/me/groups` = groups I joined (`MyGroupsExtension`), members read
  `[{id, name, role, status}]`; `POST|PUT /me/groups {name, description, members, admins}` (new people
  invited and told `group.invited`; left out = out; one admin at least, 422), `PUT`/`DELETE` by its
  admins (`GroupVoter`, `group.manage`); `GET /me/group_invitations`, `POST …/{id}/accept`, `DELETE`
  (decline); `DELETE /me/groups/{id}/membership` (leave; 409 for the last admin while others remain,
  the last member deletes the group). Summary `groupInvitations`. They replace the private share lists
  of before (set aside: two notions).
- **Posts of a group**: visibility `group` with `group` (an id, at creation only, a group the author
  joined, else 422 `PostGroupMissing`; a post never leaves or enters a group); `PostAccess` reads them
  for the members (`:readerGroups`), puts them in the following feed, lets the group's admins delete
  them and their comments. `GET /groups/{groupId}/posts`. Members are told (`group.posted`, no e-mail by
  default). Reports go to the platform moderation like any other.

- **People** (`Community/CommunityPeople`, `ApiResource/CommunityProfile`): any signed-in user finds a
  confirmed, awake account by its **public name** (`User::publicName()`: `publicNameDisplay`, else
  `nameDisplay`, else the full name), `/community/people?search=` (2 characters at least, a name only
  matched where the format shows it, in DQL), `/community/people/{id}`. The photo only when
  `photoAudience` is `public` (`User::showsPhotoToPublic()`, `/community/people/{id}/photo`). Never
  the names a format hides, an address, the clubs, the profile. Club pages stay those of the club
  search (`/directory/clubs/{id}`, with `followersCount` and `myFollow`).
- **Follows** (`Entity/Follow`: follower → a user **or** a club, `acceptedAt`, encrypted `note`, not
  club-scoped), written only by `Community/Follows` (follow, accept, accept every request; notifies,
  never flushes). A club or a public account is followed at once; a **private account**
  (`User.privateAccount`, null = private for a minor by the birth date) receives a request; making it
  public (`PATCH /me {privateAccount}`) accepts the requests. A club is followable when the club
  search finds it, and its administrators are not told of each follower.
- The follower: `ApiResource/MyFollow` (`GET /me/follows?kind=user|club`, `POST {userId | clubId,
  note}` — identifiers, an IRI would only resolve for members —, `PATCH /me/follows/{id} {note}`,
  `DELETE`). The person followed: `ApiResource/MyFollower` (`/me/followers`, `/me/follow_requests`,
  `POST /me/follow_requests/{id}/accept`, `DELETE /me/followers/{id}` removes or declines, nobody is
  told). Someone else's follow → 404. The note is read by the follower only (`FollowState` on a
  profile or a club page is the reader's own). `follow` limiter: 100/h.
- Accounts being deleted and clubs being deleted or closed are left out of lists and counts
  (`FollowRepository`), as if they had left; their follows come back with them.
- Notifications `follow.new`, `follow.requested` (e-mailed: it waits for an answer), `follow.accepted`,
  named by the public name of the actor (`data.name`), never the full name; the summary counts
  `followRequests`. Front-end paths: `/communaute/personnes/{id}`, `/communaute/activite?tab=requests`.
- Set aside: approval for every follow (the user chose public by default), clubs that approve their
  followers, notifying a club of each follower (noise for its administrators).
- **Posts** (`Entity/Post`, not club-scoped, `PostMedia` → `Media`; `ApiResource/CommunityPost`, a
  read model): a text (plain, ≤ 5000) and up to 10 photos, by a person, in the name of a club
  (`asClub`: `community.publish`, administrators and community managers), or the publication of a public
  exercise (`Community/ExercisePosts::sync`, called by the exercise save and unpublish processors;
  deleted with the exercise). `PostVisibility`: `public`, `followers`, `club`. **Language**: every
  post has one (input, else `User::getContentLanguage()`, else 422 `PostLanguageMissing`), so that the
  explore feed filters it; the post of an exercise takes the exercise's language at every save (null
  only for an exercise of no particular language, shown in every language). **Every** query of
  posts goes through `Community/PostAccess::restrict()` (DQL; the reader's clubs read in plain SQL,
  membership being club-scoped); a minor's default privacy is stored by `User::settlePrivateAccount()`
  (`PreFlush`) since the birth date is encrypted.
- A post may act in a club: `CommunityPost` implements `Tenant/OptionalClubContextInterface`, so
  `ClubContextListener` checks an optional `X-Club-Id` (needed for `asClub` and `club`, 400 without).
  `asClub` and the club are fixed at creation; `PUT /posts/{id}` replaces text, visibility, language and
  photos (author only, `editedAt`); `DELETE` by the author or whoever holds `community.moderate` in the club spoken for.
  Exercise posts are neither changed nor deleted there.
- **Feeds** (`PostRepository`, pages of 20, latest first): identifiers are UUID v7 made by the server,
  so `before=<last id>` is the cursor (no page numbers: new posts would shift them). `GET
  /feed?scope=following` (own, followed people and clubs, own clubs) or `explore` (public, in the
  reader's `contentLanguages`, posts without language too), `/community/people/{id}/posts`,
  `/directory/clubs/{id}/posts`, `/posts/{id}`.
- **Photos**: sent first (`POST /post_media`, `PhotoUploader` at 1600 px, `post_media` limiter 100/h),
  named in the post's `media`; only the sender's, free or already in that post (422 `PostMediaUnknown`).
  A photo takes the club of its post (erased with the club). Unused after a day: deleted by
  `app:tokens:purge`; an erased account's posts are removed through Doctrine first (files).
- **Signed links** (`Media/SignedMediaUrls`): a reader gets `url` = `/api/public/media/{id}?expires=&
  signature=` (HMAC of id and expiry, key derived from `APP_SECRET`, expiry rounded to the hour so the
  link stays the same and the browser caches it, 1–2 h), served anonymously under `^/api/public/` by
  `PublicMediaProvider` (`private` cache). An `<img>` or `<video>` cannot send a token. Set aside:
  blobs fetched with the token (no streaming for videos, no browser cache). **Revocable** (2026-11-15, security
  campaign): the signature also covers `Media::$linkVersion`, which `Media::revokeLinks()` raises; a post shown to other
  readers (`visibility` changed in `SavePostProcessor`) revokes the links of its files (`Post::revokeMediaLinks()`: photos,
  videos, their first images, the link preview's image), so a link a former reader holds stops working at once instead of
  after its 1–2 h. The provider reads the file before checking the signature (the version is part of it); an expired,
  forged, cut-short or revoked link, or an identifier that is not one, is a 404. Moderation (hiding a content) will use
  the same call.
- Set aside: offsets for the feed, a Doctrine extension (the feeds are custom providers), posts
  scoped to a club (they cross clubs by nature), stored counts.
- **Reactions and comments** (human decision, 2026-10-28; `Entity/Reaction` on a post or a comment,
  one per person, `Enum/ReactionType` like | love | clap | laugh | wow | sad; `Entity/Comment`, ≤ 2000,
  `parent` one level deep: a reply to a reply joins the root, `Comment::replyTo`): only on a post the
  user may read (404 otherwise). `PUT|DELETE /posts/{id}/reaction` and `/comments/{id}/reaction`
  (`ReactProcessor`, `{type}`, an unknown type is a 400; changing it tells nobody again);
  `GET|POST /posts/{postId}/comments` (oldest first, 200 at most, `?after=` for what came since,
  `parentId` to reply; `comment` limiter 60/h), `PUT|DELETE /comments/{id}`. A comment is changed by
  its author, deleted by its author, the author of the post, an administrator of the club it speaks
  for, or an admin of its group (`PostAccess`). Reads carry `reactions` `{type: n}`,
  `reactionsCount`, `myReaction`, and `commentsCount` for a post (`PostViews`: two grouped queries
  per page for the reactions). Activity: `GET /me/liked_posts` (posts I reacted to), `GET /me/comments`.
- **Refresh** (no push, human decision): the apps read `GET /post_activity?ids[]=` (50 at most, the
  readable ones: reactions, mine, comment count) and `GET /feed?after=<newest shown>` every 30 s while
  the screen is visible. `/post_activity` is not under `/posts/`, whose `{id}` route would take it.
- **Mentions** (`Community/Mentions`): the text stores `@{user:<id>}` / `@{club:<id>}` (names change,
  some are hidden); reads add `mentions[]` `{kind, id, name}` named at read time (null when gone).
  Checked on save: a person the community finds, a private account only if it follows the author
  (422 `MentionPrivate`), a club the search finds (`MentionUnknown`), 20 at most. Those newly mentioned
  who may read the post are told (`post.mentioned`; a club's administrators).
- Notifications `post.reacted`, `comment.reacted`, `post.commented`, `comment.replied` (the author of
  the conversation and those who answered; in the app by default except replies; a post in the name of
  a club tells nobody), `post.mentioned` (e-mailed by default), link `/communaute/publications/{id}`.
- **Share links of exercises** (decided with the user: a public lesson has a link, an unlisted one is
  shared by link only, both open to whoever has it): `Visibility::Unlisted` (exercises only: read in
  the club like `club`, never listed outside it, nor in the feed or the moderation). A shared exercise
  gets `Exercise.shareToken` (24 random characters, kept when it stops being shared so the same link
  comes back), exposed as `shareToken` while shared; `POST /exercises/{id}/share_link` renews it
  (`exercises.write`, 409 when not shared). `GET /public/shared/exercises/{token}` is anonymous
  (`^/api/public/`, `shared_view` limiter 300/h per address, `SharedExerciseProvider`) and serializes
  the group `exercise:shared`: title, text, frames, club name, never the authors.
- **Links of the app in a text** are resolved by the clients through the usual endpoints (a person,
  a club, a post, a shared exercise; a club's record with `?club=` in the link and `X-Club-Id`), so
  every access rule applies as it is. Set aside: a server resolver of paths (a second copy of the
  access rules of every resource).
- **Link previews** (`Entity/LinkPreview`, one per post, owned by it; `Community/LinkPreviewFetcher`):
  the first link of the text leading out of the app (`FRONTEND_URL` excluded) is read once when the post
  is written, or when that link changes: Open Graph, else the page's title and description; the image is
  re-encoded (800 px) and stored like a photo (signed link, takes the club of the post). The server
  calls a site chosen by a user, so the call is fenced (SSRF): http(s) on ports 80/443, no credentials,
  `NoPrivateNetworkHttpClient` (no private, loopback, link-local or reserved address, checked again at
  each redirect), 3 redirects, 3–5 s, the HTML up to `</head>` (2 MB at most: YouTube's head ends near
  800 KB), 5 MB of image, `link_preview` limiter 60/h; any
  failure gives no preview, never an error. Synchronous: production runs no worker.
- **Reports and moderation** (decided with the user, 2026-11-13: post-moderation only, everything is online at once for its
  public; a report puts a target in the queue of the moderators). **What can be reported** (`Enum/ReportTarget`): a post, a
  comment, an exercise, a session, a person, a group, a club. `Entity/Report` (one per person and target, reporting again
  replaces it; `targetType` + `targetId`; `ReportReason`; encrypted message): `POST /reports {target, targetId, reason,
  message}` (and the older `POST /posts/{id}/reports`, `POST /comments/{id}/reports`), handled by `State/Community/ReportProcessor`:
  the target must be readable by the reporter (`Moderation/ReportTargets::readableBy`, exercises and sessions through the
  item provider of API Platform so the rule is the one of `GET /exercises/{id}`; a target that does not exist and one that
  cannot be read answer the same 404), never oneself or what one wrote (422 `ReportOwn`), `report` limiter 20/h.
  **Hiding** (`Moderation/Moderatable`, `ModeratableTrait`: `hiddenAt`, `hiddenReason`, on `Post`, `Comment`, `Exercise`,
  `TrainingSession`): a hidden content is left out of **every** query, its author included, by the Doctrine SQL filter
  `Doctrine/ModerationHiddenFilter` (`moderation_hidden`, enabled in `doctrine.yaml`, an exact `hidden_at IS NULL` on the
  table alias, so lists, feeds, search, counts, shared links and signed media all lose it at once); only the moderation reads
  it again, inside `Moderation/ModerationScope::seeingHidden()` (nothing else may call it). Hiding a post also revokes the
  links of its files (`Post::revokeMediaLinks()`). A person, a group and a club cannot be hidden: the moderation dismisses
  their reports (or suspends an account). **The desk** (`Moderation/ModerationDesk`, the only place decisions are taken):
  `GET /admin/moderation/cases?status=open|hidden&target=&reason=&page=` (`ApiResource/ModerationCase` → `Dto/Moderation/CaseView`:
  reports gathered by target, reasons counted, messages, never who reported; 20 a page; the safety of minors first, then the
  most reported, then the oldest; `hidden` lists what is offline), `POST /admin/moderation/decisions {target, targetId, action:
  hidden|restored|dismissed, reason?, note?}` (`ApiResource/ModerationDecisionRecord`, `State/Moderation/DecideProcessor`; 422
  `ModerationNotHideable` / `ModerationAlreadyHidden` / `ModerationNotHidden` / `ModerationNothingReported`; the moderation acts
  on what was reported, what it hid, or a public post or exercise), `GET /admin/moderation/decisions?target=&targetId=` (the
  history of a target). Every decision is kept (`Entity/ModerationDecision`, never deleted with its reports) and written to the
  support log (that of the club for a post in its name, else the platform's: `SupportAction` without club,
  `GET /admin/platform_actions`). **Who is told** (`Notifier`): the author gets `content.hidden` (kind, title, the reason) or
  `content.restored`; the reporters get `report.resolved` with only `outcome` = `actioned` | `dismissed` (never about whom, nor
  why); dismissing tells the author nothing. Hiding or dismissing answers (deletes) the reports of the target; restoring
  leaves new ones open. The usual `DELETE` of a post or a comment by a moderator (`ModerationVoter`: `posts.moderate`,
  `comments.moderate`, allowed on a reported content or a public post) still exists and sends `content.removed`. Exercise posts
  are moderated through their exercise. **Suspending an account** (decided with the user, 2026-11-13): the same desk,
  `action` = `suspended` (`until` = end in UTC, none = for good; 422 `SuspensionEndPast`, `ModerationAlreadySuspended`,
  `ModerationNotSuspended`, `ModerationNotSuspendable`) or `reinstated`, on a `person` target; the moderator must manage the
  role of the person (`PlatformRole::manages`: a moderator plain users only, never oneself, else 403). `User.suspendedAt` /
  `suspendedUntil` / `suspensionReason` are written by `User::suspend()` / `reinstate()` only; `isSuspended($now)` is computed, so
  a timed suspension ends by itself. Suspending closes every session (`RefreshTokenManager::revokeAllSessions`),
  `Security/UserChecker` refuses the access tokens of a suspended account (401), and **sign-in answers 423 with a body**
  (`Auth/AccountSuspendedException` + `Http/AccountSuspendedListener`: `code` `AccountSuspended`, `until`, `reason`) only once
  the password is right. The person gets `account.suspended` (`until`, `reason`; subject = the decision) and
  `account.reinstated`. A suspended person stays in the community (their contents are hidden one by one if needed): set aside.
  **Appeals** (`Moderation/AppealDesk`, `Entity/ModerationAppeal`: one per decision, within 14 days, only while the decision
  still applies): `GET /me/moderation` (`ApiResource/MyModeration`: the decisions that concern the person, where `subject` is
  them, or the exercises and sessions they co-author; reason, note, `inForce`, `canAppeal`, `appealUntil`, their appeal),
  `POST /me/moderation/{decisionId}/appeal {text}` (404 not theirs, 409 already, 422 `AppealNotNeeded` / `AppealWindowClosed`;
  `appeal` limiter 10/day); a suspended person cannot hold a session, so `POST /auth/suspension_appeal {email, password, text}`
  (public, same limits and answers as the sign-in; 404 when the account is not suspended). Moderators read
  `GET /admin/moderation/appeals?status=open|decided` and answer with `POST /admin/moderation/appeals/{id}/decide {outcome:
  upheld|overturned, note}`: **a moderator other than the one who decided** whenever there is another one
  (`UserRepository::countOtherModerators`; 422 `AppealSameModerator`, `canDecide` tells the screen), overturning runs the desk's
  `restored` / `reinstated` on the target, and the person gets `appeal.decided` (`outcome`, `kind`, `title`). This is also the
  basis of the notice-and-action, statement of reasons and internal complaint mechanisms of the EU Digital Services Act.
  Set aside: hiding automatically after N reports (a few reports would silence anyone), showing who reported (retaliation),
  pre-moderation.
- **Videos** (decided with the user: sent directly, no transcoding since production runs no other
  process): `POST /post_media` takes an MP4, QuickTime or WebM in `file` (100 MB, the only limit: no
  ffmpeg to measure a duration) and its first image in `poster` (made by the client), through
  `Media/VideoUploader`. `Media/VideoSanitizer` turns the `udta` / `meta` boxes of an MP4 or MOV (place,
  device) into zeroed `free` boxes, without re-encoding, on a copy. **A file whose structure cannot be followed is
  refused** (422), not stored as it is: a box that does not fit in its parent used to end the walk in silence and leave
  the place of the boxes behind it (no `moov` found, an unreadable box inside it, nesting beyond the depth limit, a 64-bit
  size cut short are all refused; padding after the last box or four zeros at the end of a box are not errors).
  `sanitizeWebm` blanks the `Tags` and `Attachments` elements that come before the first cluster into `Void` elements
  (same size, a title, a comment or a cover picture is not kept) and refuses a file with no EBML header and segment.
  Kept as guard rails (security campaign, 2026-11-15): `PostTest` uploads files that are not what they claim (scripts, PHP, SVG with a
  script, HTML, empty, GIF, executables, a video without a movie box) and a polyglot JPEG, and plays crafted `Range` headers;
  `TenancyTest` checks that a taken client-chosen identifier gets the same 409 whether it belongs to the caller's club or another one.
  `MediaStorage::storeFile` seals it by 1 MiB chunks (`PiiCipher::encryptChunk`, the chunk's index as
  associated data), and the signed link answers `Range` (206, `readRange` decrypts only the chunks of
  the part, streamed). Set aside: unencrypted videos (the photos of minors are encrypted, videos too),
  whole-file encryption (a player could not seek), transcoding (a worker).

## 4 quater. Trainings, exercises and runs

- `Exercise` (drill or lesson, `kind`; `courtType` `full` / `half` / `blank` — blank is a plain
  surface for circuits / strength / plyometric work) → `ExerciseStep` (a frame, complete on its own,
  `notes`) → `ExerciseElement` (position 0–1 of the visible court, display options in the `style`
  JSON, read as is by the editors; `type` includes `icon` — emoji / drawn figure / numbered marker,
  detail in `style.icon` — and `drawing` — a free pen stroke, points in `style.stroke`).
  `Exercise.courtRotation` (0 / 90 / 180 / 270 clockwise degrees, 422 otherwise, null from an older client = 0,
  kept by a copy): the editors turn the court, positions stay in the original frame; a frame count is capped
  at `Exercise::MAX_STEPS` = 500 (a safety cap, the apps show no limit); `style.order` / `delayMs` / `moveMs` of
  an element (when it moves to the next frame) are read as is by the editors (decision of 2026-11-13).
  `Exercise.legend` (JSON, `{<symbol key>: caption}`, sparse overrides the editors compute the lines
  from) and `Exercise.videos` (JSON, up to 8 `{provider, videoId, url, title}`, `provider` on the
  `VideoProvider` whitelist — YouTube, Vimeo, Dailymotion, Bilibili —, validated 422, embedded by the
  clients only on a click) are read/written with the exercise and kept by a copy; `TrainingSession`
  (slots `TrainingSessionExercise`, the blocks below); `PlannedTraining` (a session planned for teams
  of a club at a date); `TrainingRun` (`RunClock` stopwatches, `TrainingRunEntry` per slot,
  `TrainingAttendance`, log in a JSON column).
- **Videos sent for an exercise or a session** (human decision, 2026-11-13: files **and** links; Android 9+ and the web play them):
  `POST /training_media` (`ApiResource/TrainingMediaUpload`, `State/Training/UploadTrainingMediaProcessor`) takes the video of
  `Media/VideoUploader` (MP4, QuickTime or WebM, 100 MB, place and device metadata removed, encrypted by chunks) and its first
  image in `poster`, and answers `TrainingMediaView` (`id`, `size`, signed `url` / `posterUrl`, what is `remaining` of the quota). The
  file is a `TrainingMedia` (Entity, `attachedAt` null while it waits). A document then names it as `{kind: "upload", mediaId, title}`
  in the `videos` of an exercise or in the `video` of a block: the entry is stored as written in the same JSON as the embedded links
  (an entry without `kind` is a link), `ExerciseVideoInput` (`kind` `embed` | `upload`, `validateShape`: a link carries provider,
  `videoId` and `url` and nothing of a file, a file only its `mediaId`; the 8-entry limit counts both). **Who may name a file**
  (`Training/TrainingVideos::attach`): the person who sent it, or any author saving a document that already names it (a co-author, a
  copy); anything else → 422 `TrainingVideoUnknown`. **Reading**: `TrainingNormalizer` adds to each sent video `url`, `posterUrl`
  (signed links of `Media/SignedMediaUrls`, one to two hours, made when a reader that may read the document reads it) and `size`;
  `GET /public/media/{id}` serves by `Range` like any media. **Links end** when the content is hidden by the moderation
  (`ModerationDesk`), and when an exercise or a session changes visibility (`Media::revokeLinks`). **Copy**: a copy names the
  same file (nothing is duplicated), so the original may be deleted. **Quota**: `TRAINING_MEDIA_QUOTA_BYTES` (2 GB), the sum of the
  videos a person sent (`TrainingMediaRepository::bytesSentBy`), refused before the file is stored (422 `MediaQuotaExceeded`).
  **Cleaning**: `app:tokens:purge` deletes a video no document named after three days (a draft may keep it a while) and a named
  one that no exercise (`videos`), no block (`video`) names any more (`TrainingMediaRepository::isNamed`, one day after it was
  named). Moderation: a sent video is moderated through its exercise or session (hidden with it, links dead at once). Set aside: a
  second array next to `videos` (the order of the editor would be lost), duplicating the file in a copy, a table linking each
  document to its files (the JSON stays the only record of what a document names).
- **Blocks of a session** (human decision, 2026-11-03: texts, videos, drawings and breaks between the
  exercises): a slot has a `kind` (`SessionBlockKind`: `exercise | text | video | drawing | break`).
  `exercise` (IRI) only for `exercise`, `video` (`{provider, videoId, url, title}`, `VideoProvider`
  whitelist, `ExerciseVideoInput`) only for `video`, `drawing` (`{courtType, elements}`, the elements
  of one frame, `SessionDrawingInput` → `ExerciseElementInput`, 200 at most, JSON column) only for
  `drawing`; `title` (heading, null = the clients' default) for every block but an exercise; `notes`
  = the session's notes on an exercise, the body of a text, the instructions of a break or a video,
  the caption of a drawing. Anything else → 422 on the field (`SessionExerciseInput::validateContent`).
  The other blocks are read by whoever reads the session and always go with a copy. Set aside: a
  resource per block kind, and promoting a drawing to a library exercise (a drawing belongs to its
  session). The collection keeps its name `sessionExercises` (contract). A run entry carries the
  same `kind`; `exerciseId` and `kindSnapshot` only for an exercise (`RunEntryInput`, 422 otherwise),
  `titleSnapshot` = the heading ('' = default).
- **Written in one piece**: the client sends the whole document, the processor replaces the parts
  (`AggregateWriter`: old parts deleted and flushed first, then the new ones, in one transaction,
  since Doctrine inserts before it deletes; the collections are cleared so they serialize as lists).
  The order of the arrays is the order (`position`). Part identifiers come from the client; a run
  entry has none (keyed by its slot). A change to a part refreshes the root's `updatedAt`
  (`TimestampListener`). Set aside: one resource per part (dozens of calls per save, no atomicity),
  a single JSON column of frames (the relational model was already there).
- **Relations in an input are IRI strings** resolved by `AggregateWriter::relation()` through
  `IriConverter` (club filter + visibility apply, unknown → 400). Typed as entities, a nested object
  in their place was read as a new record or as changes to an existing one (a public exercise of
  another club could be renamed through a session), and saved with the rest.
- Root `id` of an input: API Platform reads an `id` in plain JSON as an update of an existing record;
  `ClientIdentifierDenormalizer` takes it out and sets it on the `ClientIdentifiedInput`. Ignored on
  a `Put`.
- **Owner** (human decision, 2026-10-28): every exercise and session belongs to its **authors**, a
  player as well as a coach, whatever their clubs; there is no club owner (set aside: club or
  personal library, which confused people). `authors` is written with the document (`authors: [uuid]`,
  null = unchanged, one at least, 20 max, any person of the community, `Training/TrainingAuthors`;
  the people added get `training.shared`), read as IRIs plus `authorDetails` `[{id, name}]`. Only
  the authors write and delete (`PersonalLibraryVoter`, `AuthorVoter`); `ClubPermissionVoter` never
  votes on these records. Anyone signed in creates (`library.create`). `X-Club-Id` is optional
  (`OptionalClubContextInterface`): it only says which club `scope=club` lists and lets the staff in
  support read what the club uses. An account's purge removes the records nobody else wrote.
- **Library state** (`TrainingLibraryTrait`): `archivedAt` (`POST …/archive`, `…/restore`, authors;
  out of `mine`, still read by those it is shared with and in the trainings that ran it), `saved` (a
  copy of someone else's record) and `copiedFromLabel` ("title · authors", frozen at the copy, so it
  survives the original).
- **Players of a session**: `minPlayers` / `maxPlayers` (1–99, each optional, the most never fewer
  than the fewest), written with the document and kept by a copy: the range of players it is made for.
- **Visibility** (`Doctrine/VisibleTrainingsExtension`): `private` (default) = its authors and those
  it is shared with; `unlisted` (exercise only) = the same, and anyone with its share link (§4
  novies); `public` = every signed-in user, read-only. `club`, `team` and `group` are refused (422).
  On top of that, a session planned by the current club (`PlannedTraining`) is read by its members
  (and the staff in support), and an exercise is read by whoever reads a session that runs it by a
  share or a planning. Through a **public** session, only the exercises one of its authors also wrote
  are opened (human decision, 2026-10-30: publishing a session shows its exercises, the authors' own
  and their downloaded copies); an exercise of someone else they only read keeps its own visibility.
- **Planned trainings** (`PlannedTraining`, club-scoped, `/planned_trainings?team=&session=&scheduledAt[after|before]=`):
  teams of the club (1–10), a start (`scheduledAt`) and an optional end (`endsAt`, after the start,
  422 otherwise), a place, notes, and the session they run, **linked, not copied**
  (human decision): changing the session changes the trainings that run it. `title` keeps the
  session's title for the day it is gone. Written by `trainings.write` (the session must be readable
  by the caller, through `AggregateWriter::relation()`), deleted by `trainings.delete` or whoever
  planned it; read by every member (`club.view`). A new training still to come tells the players and
  coaches of its teams (`training.scheduled`, subject = the planned training). A session tells its
  authors `usage {upcoming, past}` (plain SQL across clubs, `TrainingNormalizer`): the clients warn
  before an edit or a deletion that changes the history of teams and offer to duplicate (a copy) or
  archive. **Deleting a session** deletes the trainings still to come (plain SQL across clubs) and
  leaves the past ones without it (`session_id` SET NULL), with their runs and attendance.
- **Search** (query parameters of `GET /exercises` and `/training_sessions`): `scope` (`mine` = I
  wrote it, neither saved nor archived | `saved` | `archived` | `shared` | `club` = shared with the
  club of the header, nothing without it | `public`, declared with an enum schema, applied by
  `VisibleTrainingsExtension` after the visibility, so it only narrows), `search` (title + description / notes, `FreeTextQueryFilter`), `kind`, `courtType`,
  `theme[]` / `keyword[]` (every one given, `Doctrine/Filter/TrainingTagFilter`: one `EXISTS` each),
  `language[]` (`Doctrine/Filter/ContentLanguageFilter`: `IS NULL OR IN`, like the explore feed),
  `id[]` (`UuidBinaryFilter`, to resolve the exercises of a session), `order[...]` (`SortFilter`).
  Filters taking constructor arguments live in `src/Doctrine/Filter/`, excluded from the services
  (built inline in the attributes).
- **Shares** (`TrainingShare`, `TrainingSharesTrait`, `Training/TrainingShares`): on top of the
  visibility, a record is read (read-only) by the people it is shared with, by the members of the
  groups it is shared with, and by the active members of the clubs it is shared with (whose staff
  plans it), whatever the header (`scope=shared` lists them). Written with the document as
  `shares: [{user} | {group} | {club}]` (null = unchanged, so an editor who did not read them keeps
  them; 50 max): a new person must be of the community (`UserRepository::findInCommunity`: confirmed
  address, no deletion under way), a new group one of the caller's, a new club one the caller is an
  active member of (422 otherwise); existing ones are kept as they are. Read as `shares: [{kind, id, name}]` by those who may write the record only
  (`Serializer/TrainingNormalizer`, group `training:shares`). The people who gain access (persons and
  members of groups added) get `training.shared` (`data.kind`, `title`, `name`), sent after the save;
  a club is not told. A copy keeps none. A share with a group is read by those who joined it (§4
  novies, groups).
- **Labels** (`TrainingLabelsTrait`, `Training/TrainingLabels`): `language` (ISO 639-1 regex like a
  post, null = unknown, listed in every language; on creation null = the language of the author's `locale`, `User::getContentLanguage()`: `pt` for
  `pt-BR`, null without a two-letter code), `themes`
  (closed `Enum/TrainingTheme`, translated by the clients) and `keywords` (free, 10 max, 30 chars,
  one spelling: trimmed, single spaces, lower case). Themes and keywords are rows of `TrainingTag`
  (kind + value, FK to the exercise or the session), written with the document and read through it,
  so the search filters by `EXISTS` (set aside: a JSON column, which needs JSON functions in DQL).
  `GET /training_keywords?search=` (`TrainingKeywordProvider`, 2 chars, 10 max, most used first):
  counted on what the caller reads (the extension applied to a query on the roots), `X-Club-Id`
  optional (`OptionalClubContextInterface`). A copy keeps language and tags.
- **Copies** (`Training/TrainingCopier`, `POST /exercises/{id}/copy`, `/training_sessions/{id}/copy`,
  no body): into the caller's library, from what they read (`throwOnNotFound`: 404 otherwise), when
  `allowCopy` (authors' choice, default true) or the caller is an author (`library.copy`; that is how
  an author duplicates a session). A copy is private, by the caller, new part ids, `copiedFrom` = IRI
  of the original (SET NULL on delete), `saved` when the original is someone else's.
  **Downloaded exercises** (human decision, 2026-10-30: an exercise added to a session is downloaded
  into the account): `POST /exercises/{id}/copy?reuse=true` returns the copy the caller already keeps
  of it outside the archives (`ExerciseRepository::findCopyOf`, still 201) instead of a new one; the
  clients use it when an exercise of someone else is added to a session. In a session copy, each
  exercise stays when already the caller's, is downloaded (reused or copied once) when the caller may
  copy it, public ones included, stays linked when public but not copyable, and is left out
  otherwise (the client compares the slot counts).
  **Updating a copy** (human decision, 2026-10-30: a downloaded exercise keeps its link with the
  original and is offered its new versions): `Exercise.contentVersion` grows by one at each save
  (`SaveExerciseProcessor`) — a number, not a moment, so two saves within a second differ; a copy
  keeps `originalVersion` (the original's version it holds), `copyVersion` (its own version then) and
  `dismissedVersion`. Its authors read `originalUpdate {available, changedSinceCopy}` (null when not a
  copy or the original is gone; `Serializer/TrainingNormalizer`, `Training/OriginalUpdates`):
  `available` = a newer version, not dismissed, of an original the caller still reads (same rules as a
  GET) and may copy (`library.copy`). `POST /exercises/{id}/update_from_original` (authors of the
  copy) replaces title, description, kind, court, language, tags, frames and elements
  (`TrainingCopier::updateFromOriginal`), keeping identifier, authors, visibility, shares, `allowCopy`
  and archiving, so sessions follow; 403 original unread or not copyable, 409 not a copy, gone or
  nothing new. `POST /exercises/{id}/dismiss_original_update` stores the version ignored (409 when not
  a copy). Sessions are not updated. Readability of the
  exercises is the extension applied to a query on the slots (a list of binary ids bound with the
  extension's parameters matched nothing; a scalar `id` column comes back raw binary).
- **Deleting**: an exercise or a session by its authors only; a public exercise also by the platform
  moderation (§4 sexies; written to the platform log, unpublished to `private`). A run or a planned
  training: administrators (`trainings.delete`), or the coach who started or planned it while they
  may still write trainings (`AuthorVoter`). A public exercise is published in the feed (§4 novies), its post going when it stops being public. Deleting an exercise removes its slots from every session; a run keeps copies (title, kind,
  identifiers) and survives the edit of its session.
- **Runs** belong to a planned training of the club (`plannedTraining`, `?plannedTraining=`; one of
  another club is not found, 400), staff-only (`trainings.write` on every operation): the attendance
  holds absence reasons, encrypted (`docs/personal-data.md`). The client drives the run and saves it
  whole after each action: last write wins (V1). Cancelling the training deletes its runs.
- **Drafts** (human decision, 2026-10-29): `TrainingDraft` = what an author is writing of an
  exercise or a session (`kind`), one per author and item (`itemId`, no foreign key: the item may not
  exist yet), saved by the client every few seconds, apart from the published version which it never
  changes. `ApiResource/MyTrainingDraft`: `GET /me/training_drafts?kind=` (no payload, `published` =
  the item exists), `GET|PUT|DELETE /me/training_drafts/{id}` (the item's id; someone else's → 404;
  a published item drafted by a non-author → 403; another kind than the item's → 422). The payload
  is the client's editing state, kept as is (JSON, 512 KB at most, code `TrainingDraftTooLarge`): it
  is only validated when published by the usual POST / PUT, which deletes the caller's draft
  (`Training/TrainingDrafts::published`); deleting an item deletes all its drafts
  (`Doctrine/TrainingDraftCleanupListener`). Set aside: a draft status on the item itself (would
  leak into lists, shares and plans), a draft per item shared by its co-authors (they would overwrite
  each other).
- Read shapes: authors (and `startedBy`, `plannedTraining` of a run, `session` and `createdBy` of a
  planned training) as IRIs; the teams of a planned training embedded with their name; a slot embeds `{id}` of its exercise only (a title
  could be hidden from the reader), null fields left out (`exercise`, `video`, `drawing`, `title`); an attendance line embeds the player's names (never `player:private`).

## 4 quinquies. Games and score sheets

- `Game` (team, opponent, format: `setsToWin`, `setPoints`, `tieBreakPoints`; `status`, `visibility`,
  authors) → `GamePlayer` (a player called up: club record, jersey number worn, `playingPosition`
  (`PlayerPosition` played in that game, informative), `libero` at the start (two at most, 422 on
  `players`), `captain`) and `GameSet` (score, `status`, `teamSide`, `servingFirst`) → `GameSetLineup`
  (zone 1–6, player) and `GameSetEvent` (`point`, `substitution`, `libero` (the libero comes on for
  `player` or leaves, `player` and `substitute` of the club's team, not counted as a substitution),
  `libero_redesignation` (`player` = libero declared unable for the rest of the game, `substitute` =
  new libero or null), `exceptional_substitution` (injured `player` leaves for `substitute`, not
  counted, does not come back), `timeout`, `sanction` + `SanctionKind`, `rotation`, `stat` + `skill` /
  `outcome`; `side` own / opponent; `player`, `substitute`). Only the club's players are known: the
  opponent's events have none.
- `GET /games?team=&scheduledAt[after|before]=`: a team, a period (the planning reads a week).
- **Written in one piece** like a run (§4 quater): the client records the game live and sends the
  whole game after each action (`SaveGameProcessor`). Each save bumps `Game.revision`
  (`Game/GameRevision`: check and bump in one SQL `UPDATE … WHERE revision = :expected`, inside the
  transaction); a `PUT` with the `revision` it read is refused once another save came in between (409,
  `GameRevisionConflict` in `detail`), so a shared live input never loses an action (the client reads
  again and replays). Without `revision`, last write wins (V1, kept for the mobile sync). The order of `players`,
  `sets` and `events` is the order; parts have no client identifier (nothing refers to them).
  `GameInput::validateSheet` checks that lineups and events only name players called up, so the
  processor reads each player record once (a full game is ~300 events). The team is fixed at creation.
- **Jersey colours of a game** (decided with the user, 2026-11-12): `Game.jerseyColor` and `liberoJerseyColor` (the
  club's team and its libero), `opponentJerseyColor` and `opponentLiberoJerseyColor`, `#rrggbb` or null (same rule as the
  team's, 422 on the field). Part of the details written with the sheet (`GameInput`, `GameSheetWriter`), read in the list,
  the sheet and the shared live input (`game:live`: they make the court clearer for a spectator). The server never
  copies the colours of the team: the client does, at creation (home or away jersey by `home`, then editable). A shared live
  input never changes them (`SaveSharedGameProcessor` puts the stored ones back, like `home`). Like every detail, a
  `PUT` replaces them: an app that does not send them sets them to null.
- **The log is the source of truth**: score, server, rotation and counters follow from it, computed by
  the client (rules of the game in one place, offline-ready for mobile). Each set also stores its
  score, sent by the client: for the lists, and for a result typed after the game (a set without
  log). The server checks the shape (sets ≤ 2 × `setsToWin` − 1, one player per zone, a sanction
  says which one), not the rules of volleyball.
- **Statistics** (`trackingMode` `detailed`, default of a new game = `Club.defaultTrackingMode`): a
  `stat` event names a player of the club's team, a `StatSkill` and one of its `outcomes()` (list
  validated with the user: serve ace / error / in_play, reception perfect / good / average / poor /
  error, set assist / error, attack kill / error / blocked / in_play, block kill / touch / error,
  defense dig / error). A statistic that ends the rally (`StatSkill::scoringSide()`) is followed by
  its `point` event, written by the client: the score stays a count of `point` events. A `basic` game
  refuses `stat` events (422 on `trackingMode`). Indicators are computed by the client from raw
  counts, never stored.
- **Typed statistics** (decided with the user, 2026-10-30): a set also holds `statCounts` (player,
  skill, outcome, signed `count`, `GameSetStatCount`), typed after the game or to correct the log, in
  either mode. They add to the `stat` events of the same line; the sum never goes below zero
  (`GameSetInput::validateLineup`, 422 on `statCounts[i].count`), one count per line (422 on
  `statCounts[i]`), players called up only. They give no point: the score stays the points.
- **`GET /stats?team=&player=&from=&to=`** (`ApiResource/StatSummary`, read model, club-scoped,
  `club.history`): `StatSummaryProvider` selects the games of the team like the game list
  (`VisibleGamesExtension` applied by hand, `detailed` or with typed counts, dates by UTC day), then
  groups their `stat` events and their typed counts in SQL (the game selection reused as a subquery,
  its parameters copied) and adds both up (lines at zero dropped). Answers
  `games` (`id`, `opponentName`, `scheduledAt`, `pointsWon`), `players` (`id`, `displayName` by
  `PlayerPrivacy`) and `lines` (`gameId`, `playerId`, `skill`, `outcome`, `count`). Query parameters
  are validated by their `constraints` (`required` alone adds none: `NotBlank` is listed).
  The counting itself lives in `Game/StatLines` (`of(games, players)`), shared with the two below.
- **My statistics** (decided with the user, 2026-11-03: a player reads their statistics without going
  through a club): **`GET /me/stats?from=&to=`** (`ApiResource/MyStats`, no club header,
  `MyStatsProvider`) goes through every membership of the user (`MembershipRepository::findAllOf`:
  active and history, not a club being deleted), selects each club as a request would
  (`ClubScopeActivator::activate` / `activateHistory`, `deactivate()` at the end) and keeps the games
  one of their records (`Player.user`) is called up for, through `VisibleGamesExtension`: one rule for
  what a player reads of their games, a former member up to the day they left. Answers `clubs`
  (`id`, `name`, `historyUntil`), `teams` (`id`, `clubId`, `name`, `level`), `games` (most recent
  first: `clubId`, `teamId`, `status`, `trackingMode`, `setsToWin`, `myPlayerId`, `playingPosition`,
  `libero`, `captain`, `players` [`playerId`, `libero`] and `sets` with `lineup`, `events` and their
  own `statCounts`, never a name) and `lines` (their own counts only). Basic games and results typed without a log count too:
  the client tells sets and points played by replaying the log (rules of the game in one place).
  Set aside: sets and points played computed here (a second copy of the rotation rules).
- **Comparison** (decided with the user, 2026-11-03): **`GET /stats/benchmark?scope=platform|club
  &position=&level=&from=&to=`** (`ApiResource/StatBenchmark`, `OptionalClubContextInterface`;
  `club` = the club of `X-Club-Id`, 400 without, 403 in a club of history): one entry per **person**
  (their account, or a record without account: two clubs never count them twice), shuffled, with no
  identifier: `games`, `sets` played (started, came in, or a statistic in the set: the client's rule)
  and `counts` (`skill`, `outcome`, `count`). Games with statistics (`detailed` or typed), never
  `private`; `position` = the position of the day (`GamePlayer.playingPosition`, else the first of
  the record); `level` = `Team.level` **now** (not kept per game). Below `StatBenchmark::MIN_PLAYERS`
  (10): `tooFew` and no entry. `platform` reads every club through `ClubScopeActivator::acrossClubs`
  (anonymous counts only). The client computes each indicator per person, then the average without
  the lowest and highest 5 %, weighted by attempts (`stats/benchmark.ts`). Set aside: an average
  computed here (a second copy of the indicators), names or identifiers in the entries.
- **Team level** (`Team.level`, `Enum/TeamLevel`: `leisure`, `departmental`, `regional`,
  `prenational`, `national`, `elite`, or null), written by `PATCH /teams/{id}` (`teams.write`).
- **Players are club records**, not team places: leaving the team keeps the sheets, and a player of
  another team of the club can be called up. Deleting a record removes its call-up line, and leaves
  lineups and events without player (`SET NULL`).
- **Visibility** (`Doctrine/VisibleGamesExtension`), chosen by the person who records the game, each
  level including the previous one: `private` = authors, `staff` = administrators and coaches,
  `team` = the staff + the players and coaches of the team + the players called up (linked to their
  account), `club` = members, `public` = members too until the community feed exists (like a public
  session). Authors always read their games. `group` is refused until groups exist. `staff` and
  `team` exist for games only (the training inputs refuse them). Decided with the user: every level
  possible.
- **Writing**: `games.write` on a game the caller can read (404 otherwise). **Deleting**:
  administrators, or an author who may still write games (`AuthorVoter`), as for trainings.
- Read shapes: the list (`game:list`) carries the details and the score of each set, never the sheet;
  a game (`game:read`) embeds its team's name and the names of the players called up (never
  `player:private`); lineups and events give `playerId` / `substituteId` (a non-resource part ignores
  `readableLink`, so an embedded record would repeat the names in every event). Set aside: one event
  resource appended per rally (a second writing model next to the runs', ordering and duplicates to
  handle), a fixed FIVB format (youth and leisure play best of three or to 21).

## 4 quinquies bis. Shared live input of a game

Decided with the user (2026-10-30): the live input of a game can be given to someone outside the staff
(a scorer, a parent in the stands who records the statistics).

- `GameShare` (club-scoped, `games.write` on the game for every management operation):
  `kind` `account` (a community account, `CommunityPeople::find`, told by `game.shared` →
  `FRONTEND_URL/saisie/compte/{shareId}`) or `link` (OpaqueToken hash, the secret `link` returned once
  by `POST /game_shares` and `POST /game_shares/{id}/link`, and a code of 4 to 8 digits chosen by the
  coach, stored as an HMAC by `Game/GameShareCode`: 5 wrong in a row lock the link 15 min, plus the
  `live_access` limiter per IP). `scope` `stats` (needs `detailed`) or `sheet`. `expiresAt` 24 h by
  default, 7 days at most (`Game/GameShareRules`). `PATCH` changes scope / expiry / code (a new code,
  like a new link, deletes the devices, orphan removal). `GET /game_shares?game=` lists them with their
  devices (`GameShareAccess`: device label, last use written at most once a minute);
  `DELETE /game_share_accesses/{id}` closes one.
- Without account: `GET /public/live/{token}` (`LiveShare`: teams, date, scope, `shareId`, never a
  name; `live_view` limiter), `POST /public/live/{token}/access {code, deviceLabel}` → `accessToken`
  (422 `LiveCodeInvalid`, 429 locked). `GET /public/game_shares/{shareId}` (`LiveShare` by id, same
  access as the game below) tells an account or a device the scope.
- The game itself: `GET|PUT /public/game_shares/{shareId}/game`, operations `live_game_get` /
  `live_game_put` on `Game` (group `game:live`: the sheet without notes, authors, visibility).
  `Game/LiveShareAccess` opens the share: the account signed in (anyone else: 404), or a device token
  in `X-Live-Access` (none or stale: 403); then `ClubScopeActivator::activateLiveShare` selects the
  game's club without roles, so the aggregate reads and writes as usual. `ClubContextListener` skips
  these operations (no `X-Club-Id`).
- `SaveSharedGameProcessor`: `revision` required (409), details of the game always taken from the
  stored one, scope checked by `Game/GameSheetComparator` (`sheet`: same players called up, positions
  free; `stats`: nothing but `stat` events added or removed), 403 otherwise; written by
  `Game/GameSheetWriter`, the write shared with `SaveGameProcessor` (it also removes the parts already
  loaded, or the flush would find them pointing at a deleted set).
- Tests use one client per test: a second client's first request keeps the club filter of the
  previous one (same kernel), which a cross-club lookup refuses.

## 4 quinquies ter. Coach's boards and notes of a game

Decided with the user (2026-11-12): during a game the coach draws a tactical board (the court, the players' tokens, arrows,
free drawing) or writes a free note (text and/or handwriting). Each one is tied to the **moment** of the game it was made at
(before the game, during a set, in a timeout, between two sets, after the game), can be **kept** in the history of the game
(a board is born not kept; a note is born kept), and a board can be **shared**, read-only, with the devices the live input is
shared with. Several per game.

- `GameNote` (club-scoped, `Entity/GameNote.php`): `game` (IRI, never changes), `kind` `board | note` (`Enum/GameNoteKind`),
  `title` (120), `body` (5000), `drawing` JSON `{courtType, elements}` (`Dto/Game/GameNoteDrawingInput`: the elements of the
  exercise editor, 300 at most, `style` stored as sent, so `style.ref` — who a token stands for, `player:<id>` or `opp:<n>` —
  passes through), the moment as `phase` (`Enum/GameNotePhase`) + `setNumber` / `teamScore` / `opponentScore` (read as
  one `moment` object; a phase inside the game names its set), `capturedAt`, `kept`, `shared`, `revision`, `createdBy`
  (read as `{id, name}`, public name). 100 per game at most (422).
- **A resource of its own, not a field of `Game`, on purpose**: each stroke saves the note again; on the game it would bump
  `Game.revision` and make the live input of the score fail with 409. Written in one piece: `POST` / `PUT` (`GameNoteInput`,
  `State/Game/SaveGameNoteProcessor`), `GET` list (`?game=&kind=&kept=&shared=&updatedAt[after]=`) and item, `DELETE`; all
  `games.write` (RoleMatrix `STAFF`). Read through `Doctrine/VisibleGameNotesExtension`: whoever may open the game (a private
  game keeps its notes to its authors).
- **Revision** (`Game/GameNoteRevision`, the mechanism of `GameRevision` on the note alone): each save bumps it; a `PUT` that
  sends the revision it read is refused (409, code `GameNoteRevisionConflict`) once another device saved in between; without a
  revision the last version wins (a device that was offline). The clients merge element by element (`@myvb/core`
  `matches/notes/boardOps.ts`): they read again, replay their changes on the new version, send again.
- **Boards shared with the live input**, read-only, both scopes: `GET /public/game_shares/{shareId}/boards` and
  `/boards/{id}` (operations `live_game_note_list` / `live_game_note_get`, added to `LiveShareAccess::OPERATIONS`, providers
  `State/Game/LiveBoardsProvider` / `LiveBoardProvider`): the boards of the shared game with `shared = true`, never a note; a
  board that stops being shared is 404 at once. Nothing is ever written through a share. No real-time channel (none exists):
  the clients read again every 2 s (the open board) and 5 s (the list).
- Synchronised like the other lists: `updatedAt[after]` (`UpdatedSinceTest`), tombstones (`SyncType::GameNote`, audience
  `GameStaff`, also for the notes that go with a deleted game).

## 4 bis. Platform roles and account administration

- Four platform roles, stored in `User::$roles` (JSON, at most one) and exposed as a single `role`
  field (`getPlatformRole()` / `setPlatformRole()`): `ROLE_PLATFORM_ADMIN` (super administrator) >
  `ROLE_ADMIN` > `ROLE_MODERATOR` > `ROLE_USER`, chained in `role_hierarchy`. Inside a club a platform
  role only gives the support access of §4 sexies. The first platform administrator comes from
  `app:platform-admin:create`.
- Who manages whom lives in `Enum/PlatformRole::managed()` only: platform admin → everyone, admin →
  moderators and users, moderator → users. Managing = create, change, delete, and give one of these
  roles.
- `/api/users` (moderators and above): writes are guarded by `users.manage` (`UserManagementVoter`)
  in `security` (current role) **and** `securityPostDenormalize` (requested role). The caller is never
  their own target (their profile goes through `/me`).
- Escalation attempts (tampered or role-claiming token, forbidden fields such as `roles`, an `id` /
  `@id` in the body, writes through an embedding resource, other methods and formats) are tested in
  `tests/Api/PrivilegeEscalationTest.php`. A new writable field or resource gets a case there.
- The list searches with `?search=` in the e-mail address, given name and family name at once
  (`FreeTextQueryFilter` + `OrFilter` + `PartialSearchFilter`).
- Decisions, with what was set aside:
  - Single `role` field — not an editable `roles` list (inconsistent states, several roles at once).
  - Nobody manages their own account, which keeps a platform administrator forever — not a 409
    "last platform administrator" rule, which the voter makes unnecessary.
  - E-mail set at creation only — not editable by the staff: a moderator could point an account to
    their own address and reset its password. The owner changes it (decided with the user):
    `POST /me/email` with the password stores `pendingEmail` and sends a `ChangeEmail` token (24 h)
    to the new address, the current one is told; `POST /auth/email/change` with the token switches
    the address and tells the former one. An address of another account gets the same 202 and its
    owner is told (no address probing); one taken meanwhile → 409. Sessions stay open (the password
    did not change). Set aside: switching at once (a typo would lock the owner out), a link to the
    former address (a lost mailbox is often why one changes).
  - New accounts get an invitation link to choose their password — not a password typed by the staff.
  - Deleting a user is refused (409) while they are the last administrator of a club.
  - Search term in the query string, though it may hold (part of) an e-mail address — not a
    name-only search nor a POST search: a broad search was asked for, on a staff-only screen. The
    clients never copy the term into the page URL.

## 4 sexies. Platform support access and administration of the clubs

Decided with the user: the platform staff must be able to manage everything, moderators less than
administrators.

- **Support access** (`Enum/ClubSupport`, given by `PlatformRole::clubSupport()`): in any club it
  does not administer, the staff acts with `X-Club-Id` without a membership. `Read` (moderators):
  every read permission (`ClubPermission::isRead()`), private games and sessions included
  (`VisibleGamesExtension`, `VisibleTrainingsExtension` skip their rules when
  `CurrentClub::isSupport()`). `Manage` (administrators and above): every permission, as a club
  administrator. A member of the staff keeps its own roles in its clubs on top of it. A closed club
  is read only, a club being deleted too until restored (`ClubContextListener::selectSupport`).
- `ClubContextListener` selects the club in support, `ClubPermissionVoter` grants
  `roles ∪ support` (for the club of the request, or the club / membership being written:
  `PATCH /clubs/{id}`, `DELETE`, restore, member roles). `MyClubsExtension` lets the staff read any
  club and member list; `/clubs` and `/memberships` stay the user's own.
- **Support log** (`Entity/SupportAction`, `Tenant/SupportLog`): the voters hand over each write
  granted by the support access or the moderation alone; one line per club and request (actor,
  method, path, operation name, never the body or the query string) is persisted then, so it goes
  out in the same flush as the change: a request failing before its flush leaves none. Set aside:
  writing it on `kernel.response` (a second flush over a unit of work a delete left inconsistent).
  Read by the staff: `GET /admin/clubs/{id}/support_actions`, most recent first.
- **Moderation** (`Security/ModerationVoter`, `exercises.moderate`): what a club shows outside
  itself, today the public exercises. `GET /admin/exercises` (moderators and above, `?title=`) lists
  them across clubs; `POST /exercises/{id}/unpublish` (visibility back to `club`,
  `UnpublishExerciseProcessor`) and `DELETE` are open to the staff on a public exercise, logged in
  its club. A non-public or unknown exercise gets the same answer (403 on the POST, 404 on the
  DELETE).
- `GET /admin/clubs` (moderators and above): every club, any state, `?search=` on name and city;
  the details of a club and its members come from the usual `/clubs/{id}` and
  `/clubs/{id}/memberships`; `GET /users/{id}/memberships` gives the clubs of an account, past ones
  included. Naming an administrator = changing a member's role or inviting someone in support: no
  endpoint of its own.
- Set aside: an `/admin/*` copy of every resource (two implementations of each rule), a support
  access without log, a moderator acting as a coach, hiding private records from the staff (the
  user wants everything readable), a computed member count in the club list (one query per club).

## 4 decies. Platform file: announcements, features, versions (human decision of 2026-11-15)

The owner of the platform tells the users about an incident or a maintenance, closes a feature (« coming soon », maintenance) and
says which version of an app is the latest, **by editing one file on the host**, with no deployment.

- **The file** : `PLATFORM_CONFIG_FILE` of the `.env.local` of the host (`shared/platform.yaml`, next to the `.env.local`); without
  it, `config/platform.yaml` of the repository, which keeps the **community `coming_soon`**. Format: comments of
  `config/platform.yaml`; read by `Platform/PlatformConfigParser` (strict: unknown key, state, role, language tag, non-https
  link, version without quotes, announcement without a message… are refused with their place in the file).
  `php bin/console app:platform:check [file]` validates a file and shows its effect now: **run it after each change**.
- **A file that is missing or refused is never used** : the API logs it as `critical` and applies the file of the repository (the
  community stays closed: a typo never opens a feature). Nothing is cached across requests but the number of accounts.
- **`Platform/PlatformConfig`** : `settings()`, `feature($key)` (state now: `unlockAt` reached or `unlockAtUsers` confirmed accounts
  reached, the first wins; the count is kept 10 minutes in `cache.app` and is 0 if the database does not answer), `announcements()`
  (dates). `FeatureGate` lists the keys the file may use (`community`) and the resources of each one.
- **`GET /public/meta`** (`ApiMeta`, anonymous, no database unless `unlockAtUsers` is set) gives `maintenance`, `announcements`,
  `features` (`state`, `message`, `unlockAt`, `staffRole`; **never** `unlockAtUsers`) and `clients` (`minimum`, `latest`, `updateUrl`);
  `minSupportedClient` is kept for the installed apps: `clients.<kind>.minimum` of the file, else `MIN_CLIENT_*`. Texts are objects
  language tag → text (`*` = every language).
- **`Http/FeatureGateListener`** (`kernel.request`, priority 6: after the firewall, before the club): a closed feature answers
  **503** `{code: 'FeatureUnavailable', feature, state, message, unlockAt}` to everyone below its `staffRole`; the general
  maintenance answers **503** `{code: 'PlatformMaintenance', until, message}` to every `/api/` request except `/api/public/`,
  `/api/auth/`, `/api/me` and `/api/docs`, to everyone below `maintenance.staffRole`. The community covers `CommunityPost`,
  `CommunityComment`, `CommunityProfile` (**except** the search `community_people` and the photo `community_person_photo`: people
  are looked up to share an exercise or a live input with an account), `MyFollow`, `MyFollower`, `MyContact`, `UserGroup`,
  `MyGroupInvitation`, `PostMediaUpload`, `PostActivity`; reports stay open (they cover exercises, sessions, clubs). While the
  community is closed to a person, `/me/notification_summary` counts no follow request, contact request or group invitation.
- **Add a closable feature** : the key in `FeatureGate::KEYS` and its classes in `FeatureGate::RESOURCES`, the same key in `FeatureKey` of
  the shared core, `feature` on the menu entry, `RequireFeature` on the routes of the web and of the mobile app (app repository
  `STRUCTURE.md`).
- **Tests** : `PlatformConfigParserTest`, `PlatformGateTest`; the suite runs with `tests/fixtures/platform.open.yaml` (`.env.test`:
  nothing closed), the tests of the file write their own.
- **Written off** : variables of the environment for each flag (a restart of the cache for each change), an administration screen
  (a second way to change what the owner does by hand), a notification per account for an announcement (a row per user and per
  message; the banner is enough), a file committed with the code only (a deployment to announce an outage).

## 5. Runtime

- **Uploads**: a video is 100 MB at most, so the host allows `upload_max_filesize` ≥ 100M and
  `post_max_size` ≥ 110M (the Docker image of dev reads them from `PHP_UPLOAD_MAX_FILESIZE` /
  `PHP_POST_MAX_SIZE`).
- **The API runs on its own on a plain PHP host**: Docker is the dev environment only, the
  production server is not dockerized. Nothing may require a container, a worker or another
  long-running process next to PHP.
- Docker image `image/` (php:8.4-apache, mod_php). The vhost must pass the `Authorization` header
  to PHP (`SetEnvIf Authorization "(.+)" HTTP_AUTHORIZATION=$1` in
  `image/config/apache-symfony.conf`), otherwise every authenticated call answers 401
  "JWT Token not found". PHPUnit does not go through Apache, so the test suite cannot catch it.
- Mail: `.env` keeps `MAILER_DSN=null://null` (no delivery, tests included). Dev sends for real
  through the SMTP account set in the git-ignored `.env.local` (`MAILER_DSN=smtps://…:465`,
  user and password URL-encoded; `MAILER_FROM` must be that account's address, the server refuses
  any other sender). Check SMTP with `bin/console mailer:test <address> --from=<MAILER_FROM
  address>`: without `--from` it sends as `from@example.org`, whose DMARC makes the recipient
  reject it silently (the bounce goes to example.org). E-mails leave on
  `kernel.terminate`, after the profiler's mailer collector ran: they are **not** in the profiler,
  read them in the mailbox. A delivery failure only shows in the logs.
- Reset the rate limiters with `bin/console cache:pool:clear cache.rate_limiter`.
- **Development data**: `doctrine/doctrine-fixtures-bundle` (dev and test only), loaded by
  `bin/console doctrine:fixtures:load`, which empties the whole dev database first (stored media files
  stay). Accounts and their password are listed in the readme. Rules of the data set:
  - addresses at `example.com` only, phone numbers in the range kept for fiction (06 39 98 xx xx): dev
    sends real e-mails;
  - entities built in PHP, flushed through Doctrine (timestamps, encryption and the club checks of the
    listeners apply), each with its club set explicitly (no current club in a console command);
  - dates relative to the day of the load (Paris time, stored in UTC), so there are always past and
    upcoming sessions;
  - only what the API would accept: `tests/Api/DevelopmentFixturesTest.php` validates every record and
    browses the set as a coach. A new entity or rule gets its data and keeps that test green.
  - Set aside: Foundry / Faker (a dependency for a hand-written set, random data differs from one load to the
    next), a custom command (the bundle is the Symfony standard).
- Scheduled tasks (host cron, daily): `bin/console app:tokens:purge` and `bin/console
  app:deletions:purge`. Missing a run only delays the erasure: a due record stays asleep. Every 10
  minutes: `bin/console app:notifications:mail` (the requests already send the due digests; this
  covers the hours nobody uses the app). Missing it only delays a digest.

### Environments and deployment (human decision of 2026-11-13)

- **Three environments**: `localdev` (Docker on the dev machine), `dev` (online, o2switch, branch `develop`) and `prod` (online,
  o2switch, branch `main`). Both online environments run Symfony with `APP_ENV=prod`: "dev" is a test instance, never debug mode
  (`app:deploy:check` demands `prod`). Each has its own database, `PII_KEY`, JWT key pair and `FRONTEND_URL` / `CORS_ALLOW_ORIGIN`
  (one origin each, no wildcard). Hosts: dev `dapi1457.myvolleyball.org` (web `dapp9714.myvolleyball.org`), prod
  `papi1457.myvolleyball.org` (web `app.myvolleyball.org`).
- **Branches**: `main` = prod, `develop` = dev, `feature/*` and `fix/*` from `develop`, `hotfix/*` from `main` (merged into both).
  No other long-lived branch (a `staging` branch would duplicate `develop`). Table and rules: `Readme.md`.
- **Pipeline**: `.github/workflows/ci.yml` (pull requests, and called by the deploy) then `deploy.yml` (push on `develop` / `main`,
  GitHub environments `dev` / `prod`, `prod` with a required reviewer). `composer install --no-dev` runs in the CI (the host needs no
  Composer); `scripts/deploy/deploy.sh` rsyncs a release, runs migrations, cache, `app:deploy:check`, and only then switches the
  `current` symlink (rollback = point it back). `scripts/deploy/server-init.sh` prepares `shared/` once (`.env.local`, JWT keys,
  media, logs). `scripts/deploy/api.htaccess` is copied to the release's `public/` (Authorization header, HTTPS, front controller).
  Procedure: `docs/deploy-o2switch.md`.
- **CORS**: `X-Live-Access` is an allowed request header (the web app's shared live input calls the API cross-origin).
- Set aside: cPanel "Git Version Control" (pulls on the host, needs Composer there and a manual deploy), FTP (no atomic switch).

### Environment firewall (human decision of 2026-11-16)

- Outside production the API refuses every request that lacks a key: `Http/EnvironmentGateListener` (`kernel.request`, priority 200: after
  the CORS listener, before the router, the firewall and the rate limiters). Active **only when `ENV_GATE_KEY_HASH` is set** (the SHA-256 of
  the key in hexadecimal, from `bin/console app:gate:key`): production and the tests do not define it, so nothing is checked there. It cannot
  rest on `kernel.environment`: dev and prod both run `APP_ENV=prod`. The apps send the key in `X-Env-Key` (allowed by `nelmio_cors.yaml`).
- Answer: 403 `{title, detail, status, code: 'EnvironmentKeyRequired'}`, the same whether the key is missing or wrong. Compared with
  `hash_equals` on the hash. A hash set but malformed refuses everything (never opens the API by mistake); `app:deploy:check` fails on it
  and says whether the firewall is on.
- Left open: `OPTIONS` (the preflight carries no custom header), what is not under `/api/`, and `/api/public/media/` (signed URLs loaded by
  `<img>` / `<video>`, which cannot send a header; the HMAC signature protects them). `GET /api/public/meta` stays behind the key.
- **A filter, not a secret**: the key ships in the web bundle / APK of the same environment (anyone who loads the dev site reads it). It
  keeps scanners and direct calls out of a test instance; closing the dev web site itself would take an Apache authentication.
- Where the values live: the hash in `.env.local` of the API (`shared/.env.local` on o2switch, `app/.env.local` in localdev; **not** passed by
  `docker-compose.yml`: an empty container variable would beat `.env.local`); the key in the apps' build (`API_GATE_KEY`, see the app
  repository's `STRUCTURE.md` §8 bis). Rotation: `app:gate:key`, new hash on the server, rebuild the apps.
