# CLAUDE.md

Loyalty platform: API-first loyalty engine embedded into the company's products and sold as SaaS.
Plan: `docs/roadmap.md` (work stage by stage, update statuses there). Decisions: `docs/adr/`.
Research behind the product: `docs/research/report.md`. The team reads Russian: docs and UI texts are in
Russian, code and identifiers in English.

## Environment (Windows + Laragon)

Every PowerShell session starts with `. .\scripts\dev\env.ps1` (PHP 8.5, Composer, Node 22, PostgreSQL 17
first in PATH). Never switch Laragon's global PHP version: other projects depend on it.

- `composer check` — Pint, Larastan (level 8, plus the PHP SDK at PHP 8.2), Deptrac, Pest, the TypeScript SDK tests
  (Node 22.18+), the web till's app (`composer till:test`: build and its tests; the build needs
  `npm ci --ignore-scripts --prefix sdk/typescript` once), the customer portal's app (`composer portal:test`: build and
  its tests), the member widgets (`composer widgets:test`: the committed build is the build of the sources, then their
  tests). Must be green before a stage item is done.
- `composer test`, `composer lint`, `composer fix`, `composer analyse`, `composer deptrac`.
- `composer migrate` — migrations run as the schema owner (`--database=pgsql_owner`), never as the app role.
- `.\scripts\dev\postgres.ps1 start|stop|status|psql`; roles and databases: `php artisan db:bootstrap`.
- Horizon/Octane need `pcntl` (Linux only); they are verified in CI/Docker, not locally.
- A local staff account: `php artisan staff:create <email> --name=...`, then `php artisan staff:grant <email> --platform
  --role=admin` (or `--merchant=<id>` / `--partner=<id>`); sign in at `/console` or `/merchant` by the password (an
  authenticator app is a choice in the profile). Or `php artisan db:seed --class=LocalCabinetSeeder` (local only, idempotent): an operator and a
  demo merchant's owner with the password in that file. Local `.env` has `SESSION_SECURE_COOKIE=false` (http) and no
  `CONSOLE_DOMAIN` (required outside development). Filament's assets are published by `php artisan filament:assets`
  (composer post-autoload-dump) and are not in git.

## Architecture rules

- Modules live in `app-modules/<name>` (`Modules\<Name>`). Other modules may use only
  `Modules\<Name>\Contracts\*` and `Modules\<Name>\Events\*`; the kernel is usable everywhere. New module:
  `php artisan make:module <name>`, `composer update modules/<name>`, add it to `deptrac.php`.
- No Eloquent relations across modules; reference by id and go through a contract.
- Tenant-owned table: `TenantSchema::tenantKey($table)`, `TenantSchema::foreignWithinTenant(...)` for
  references, `Rls::enable('<table>')` after `Schema::create`; unique indexes start with `tenant_id`.
  A key public across the platform (a portal's slug) is the table's primary key instead, allowed by name in
  `tests/Architecture/DatabaseSchemaTest.php`. Model extends `Modules\Kernel\Database\TenantModel`. Append-only tables: `Immutability::appendOnly()`,
  immutable columns: `Immutability::columns()`. Never edit a committed migration; add a new one.
- Points change only through `Modules\Ledger\Contracts\Ledger` (ADR-0003); the cabinets adjust them by hand only
  through `Modules\Support\Contracts\ManualAdjustments` (limits per role, the note kept apart from the audit log).
  A member merged by `Ledger::transferMember` (ADR-0019) takes nothing new in the ledger — `Accounts::lockMember` throws
  `MemberMerged` with the survivor, though the repeat of what it was given returns it (`replayOfMerged`) — while what
  returns or expires of what it had follows its survivor (`LedgerService::lockHolder`; the repeat of such a follow-up is
  known by its reserve or accrual, `replayFollowUp`, a new operation's by the member exactly, `replay`); a lot changes
  its owner only to the owner's recorded successor (database triggers). Look a member's accounts up through the point
  types (the index begins with the point type). Members are merged only by `Modules\Support\Contracts\MemberMerges`
  (overdue reservations cancelled first; then an outermost transaction: both members, the bonus awards, the ledger, the
  modules); a module that keeps something per member adds a `mergeMembers` method called there, or, where its rows
  cannot move, counts the rows of `Members::aliasesOf` as the member's. A merged member (`MemberStatus::Merged`) is
  final: `Members` refuses it with `MemberMerged`. Whatever locks a member's points locks the member first
  (`lockPresent`): processing holds the member of a receipt it registers, and does what a receipt of a merged member
  needs to its holder (`CheckoutService::holderOf`, which waits for a merge under way). An API operation that names a
  member of its program by id answers a merged one with 409 `member_merged` and its `survivor_id` (the Runtime API
  through `MemberResolver::notMerged`, after the program check; the Management API reads it still; an offline receipt
  naming it is taken, for its survivor), the member plane with 401; a Management operation outside the scopes that
  read members (`members`, `widgets`) answers it as a member it does not know (a personal promo code).
  Query-builder rows are read with `Modules\Kernel\Database\Row`; timestamps are written with `Modules\Kernel\Time\SqlTime`.
- Text staff type about a member that a module keeps (an adjustment's note, the reason of a fixed tier) is written
  inside a transaction that holds the member (`Members::lockPresent`) and erased by a `MemberAnonymized` listener. The
  audit log keeps what actions declare for its keeping (three years, ADR-0030): a note goes there only as whether there
  was one, and a reason an action logs says so in its form (`cabinet::members.actions.reason_hint`).
- Points for actions (ADR-0017, module `activities`) live in their own table, not in the rules snapshot, and change at
  once; a reward keeps its points, the ledger's lot its lifecycle. A reward holds the member (`Members::lockPresent`),
  then the action's row (`FOR UPDATE`: a member's limit — reversed rewards count too —, the budget and the event are
  counted under it); a reversal takes the action's row, then the reward's, and gives the budget back only what the ledger
  took; the ledger comes last in both. The runtime scope `activities`, like `presentation_codes`, belongs only to keys of
  `ApiScope::SERVER_TERMINALS`. In the cabinet whatever makes an action pay, or pay otherwise (making it, its terms,
  activating it), is a publication (`campaigns.publish`); terms are saved only over the ones the form opened with
  (`Activities::update(…, basedOn)`); pausing is the protective `activities.pause`.
- Money and points are integers in minor units (`Money`, `IntMath`, `Allocator`); floats are forbidden.
- Rules reach receipts only through published snapshots (`RuleSets::effective`); every change that affects
  receipts (base rules, campaign publication or status) goes through `SnapshotPublisher` under the program lock.
  The engine (`Modules\Rules\Contracts\Calculator`) is pure: no database, clock or randomness. A change of
  its behaviour updates the golden vectors in `app-modules/rules/tests/golden` (expected values computed by
  hand, see the README there) and the CHANGELOG.
- Current time only via `Modules\Kernel\Time\Clock`; timestamps are `timestamptz` (precision 6).
- API errors: throw a subclass of `ProblemException` with a stable `code`; never return ad-hoc error JSON. A new code
  goes into `x-problem-codes` of the spec of every API that can answer with it (checked against every answer in tests
  and against the sources by `tests/Architecture/ProblemCodeCatalogTest.php`). A code no API answers with yet goes
  into `Tests\Support\ProblemCodes::INTERNAL` with the reason.
- The API specifications are the source of truth: `Tests\TestCase` validates every `/api/v1` response against
  `docs/api/runtime-v1.yaml`, every `/api/management/v1` response against `docs/api/management-v1.yaml` and every
  `/api/member/v1` response against `docs/api/member-v1.yaml` (and successful JSON request bodies), and an
  architecture test compares the routes of each API with its operations.
  Change the spec together with any endpoint; test-only routes live under `<api prefix>test/`. In YAML flow
  mappings (`{ ... }`) quote descriptions that contain commas.
- Every Management API route group runs `management.audit` (`:reads` where responses carry personal data or codes),
  `management.auth`, `throttle:management`, `management.scope:<scope>` (several where an operation reaches more: a
  till key reaches members, so issuing one takes `organization,members`) and, for a merchant's data,
  `management.merchant`, in this order; a new route name goes into `AuditAction` of the spec
  (`tests/Architecture/ManagementAuditTest.php`). Cabinets write to the same log through
  `Modules\Audit\Contracts\AuditLog` (ADR-0010).
- The merchant's channels through the Management API (ADR-0025, scope `communications`): a login, password, key or
  token is read from the body as sent (`Requests\Concerns\ReadsCredentialsAsSent`: TrimStrings spares `password` only;
  Livewire skips it, so the cabinet hands them over as typed too), goes to the communications contract alone, which
  checks it with the provider before keeping it, and is never answered (`login_hint` only); `login` is a sensitive key
  of `SensitiveDataRedactor`, which also masks the login and password of an address (`smtp://user:pass@host`), so the
  audit log keeps none of them. Putting an account in place (connecting one, replacing its credentials) takes
  `communications,members`: members' numbers, addresses and codes go through it. A DELETE answers its repeat with 204
  (the SDKs repeat DELETEs); problems name the body's fields (`password`, `daily_limit`); the path of the mail, the bot
  and the community names no channel, so their controllers name it with `RecordAudit::SUBJECT`. No test SMS or letter
  goes through the API (a message to an address a server names), nor the lifting of a stop of codes (a person's, in the
  cabinet). The automatic messages, the rules of messages (stage 7k-2, `communications`) and the portal (`programs`;
  opening it and letting people join, which send codes at the merchant's cost, `programs,communications`): a template
  is published over whatever is current (`PublishTemplate::$basedOnVersion` null; only the cabinet's form gets
  `message_template_outdated`), the standard text back by its own `:restore` (a blank text is refused, never read as
  none); a template's text and a colour are read as sent (`Requests\Concerns\ReadsTextAsSent`: a GET's query, a JSON
  or a form's body), and a text reaches no audit entry, refused ones' neither (`RecordAudit::WITHHELD` keeps only
  whether it was sent, as the cabinet's). Every API entry keeps fields of names an operation could have only
  (`RecordAudit::FIELD`): a JSON sent as a form makes a password part of a field's name. A topic switched as it is
  changes nothing (`AutoMessages::switch`). What only stops messages or a portal goes into
  `RequireMerchant::WRITES_WHILE_SUSPENDED`; an operation the cabinet has as one action with a choice of which only one
  protects is two routes there (`portals.allow-joining`, `portals.stop-joining`). The log and the queue of messages
  (stage 7k-3: `GET /messages`, `/member-messages`, `/members/{member}/messages`) take `communications,members` and
  `:reads`; a recipient is searched by `phone` or `email`, whole (names the audit log redacts), and searches that find
  nothing count per credential in a merchant before they run (`MessageJournalController::MISSES`, the kernel's
  `TooManyLookups`, the cabinet's too). A member's consents are read only (`members`); `ConsentService::record` is the
  only writer of `consent_events` and dispatches `Consents\Events\ConsentChanged` in its transaction, of which the
  outbox records the consents to advertising as `member.consent_changed`.
- Sandbox (ADR-0012, `LOYAL_SANDBOX=true`, a separate deployment): a contract that reaches real people or money
  (messages, payments, documents) extends `Modules\Kernel\Sandbox\RealWorldEffect` and its module registers a double
  with `Sandbox::double()`; code that accepts a member's phone or e-mail calls `Sandbox::assertTestPhone()` /
  `assertTestEmail()` (staff e-mails are real in the sandbox too, ADR-0013). Credential formats (with the `test_` marker) live in `Modules\Access\Internal\CredentialFormat`.
- Communications (ADR-0020, module `communications`): messages to members go only through the merchants' own provider
  accounts (`Contracts\Channels`); every request to a provider goes through the internal `Gateway` (a RealWorldEffect
  with a sandbox double). Credentials are checked with the provider before they are kept, sealed by `CredentialBox`
  (PiiCipher, context of tenant and channel) and leave the module only as a masked login; every request with a login
  stops for a while once a provider refused so many logins, whoever sent them (it would block the platform's address).
  Codes go through `OtpSender` (the `CodeSender` binding): channels turned on in order, Telegram first where a channel
  says so, a repeated code by SMS, within a time budget below the SDK's timeout, to Russian mobile numbers only
  (`mobile_phone_required`); no channel to use → 409 `code_delivery_unavailable` before anything counts, every channel
  refusing → 409 `code_delivery_failed` (never a 5xx: clients repeat those and take them for a lost connection); the log
  instead only in local/testing. A member's own address is confirmed only through `Contracts\MemberEmails` (stage 7e-3b):
  a letter with a code through the merchant's mail account while the member waits (`email_codes.budget_seconds`,
  `Gateway::sendEmail(…, withinSeconds)`), a code of topic `MemberEmails::TOPIC` in the log (`communications.codes`
  leaves it out), the server's breaker read before the letter's transaction; its letters are counted in
  `member_email_confirmations` — failed ones too, committed with the refusal — per member, per mailbox (`+tags` and
  Gmail's dots as one) and per merchant, under advisory locks of the member then the mailbox taken without waiting (429
  when held) with the member held; the same address again within `resend_seconds` is the letter on its way (200), and
  the address stays sealed only while its code may confirm it (`messages:prune`, hourly, erases what expired).
  `members.email_confirmed_at` is written only by `Members::confirmEmail` and goes with the address. A merchant's codes count against its limits of the day and the month before they go,
  in a session of their own (`pgsql_counters`, the app role under RLS, the tenant set per statement: what must count at
  once, outside the request's transaction, goes there); a stop of a low share of confirmed codes lives in
  `verification_limits` and is told to the owners (`TeamNotices`). `messages` keeps no text, no number and no address
  (blind indexes `communications.phone` and `communications.email`, masked); providers'
  amounts are read as text (`ProviderAnswer`), never as floats. Any other message to a member is queued with
  `Contracts\MemberMessages` (in the caller's transaction, the member held; one per key of ids, its text sealed until it
  goes) and sent by `messages:send` (`MessageDelivery`, one sender at a time): the rules of its purpose — the merchant's
  and the member's state, the merchant's pause, the consent, quiet hours and advertising per day of the program's zone —
  are checked when it goes, never when it is queued; what a provider took is never sent again. The merchant's settings
  (`Contracts\MessageSettings`, stage 7d-2: a pause of advertising and service messages, what comes due meanwhile is
  skipped; longer quiet hours, rarer advertising, the first route of service messages) never loosen the platform's
  rules, read at every message (`MessageSettingsService::rules`). The platform's stops (`Contracts\PlatformMessageControls`,
  stage 7d-3, console): of a merchant, as its pause, which only the platform lifts; of every message, a switch
  (`communication_switches`) `messages:send` reads before every message — the queue waits, nothing is skipped, codes go
  on. A merchant's own maxima of codes are `Modules\Verification\Contracts\CodeMaxima`. A message goes by the routes of its purpose
  (`MessageDelivery::routesOf`: a warning by SMS first, a service message and advertising by the merchant's mail first
  unless it set an SMS first), the next route taking over what one did not take, a row of the log per route tried; a
  letter of advertising (stage 7e-4) goes only to an address the member confirmed, with their consent to letters of
  advertising, and carries the link «Отписаться» of `Contracts\Unsubscribes` (a token of the tenant and the message
  signed with the app key, never stored; `/u/<token>` on the portal's host, `Contracts\UnsubscribeAddress` bound by
  the portal — none, no such letter), in its text and its `List-Unsubscribe` headers; the page only asks when opened (mail
  scanners open links) and withdraws by its button or a mail service's one-click POST, outside the web group. A route
  refused for good goes into `member_messages.closed_routes`, which later tries leave out.
  A letter opens the mail account (`ChannelStore::usableMail`) and reads the member's address (`Members::revealEmail`)
  only when it goes; it goes to no server whose refused logins stop the merchant (`RequestLimits`, which counts its
  refusals too), nor again in a run to one that did not answer or was slow (`slow_mail_seconds`), and whether it
  arrived is never asked. The cabinet reads the log only through `Contracts\MessageJournal` (stage 7d-1): a recipient is
  searched by its blind index, never stored, a person's searches that find nothing are limited, and every search is its
  own audit entry (`CabinetAuditor::recordLookup`). It reads the messages to members only through `Contracts\MessageQueue`
  (stage 7g-3, «Очередь» and a member's «Сообщения»): what a waiting message waits for is `member_messages.waits_for`
  (`MessageWait`: quiet hours or the next try when the sender puts it off, `sending` while a sender has it), which
  whatever finishes a queued message clears and readers read of waiting messages only; the database checks its values,
  never against the status: a sender of the version before leaves it behind and must still finish what it sent. A
  migration of a table receipts write to takes its lock for a moment only: checks `not valid`, then validated, indexes
  `concurrently`, outside a transaction (as `2026_12_04_000100_add_waiting_to_member_messages`). The merchant's mail
  account
  (`Contracts\EmailChannel`, stage 7c-4a) is one `communication_channels` row of provider `smtp` (`settings` jsonb):
  `ChannelStore::rows/row/anyUsable` and `Channels` know the SMS channels only. A mail server is reached only through the
  Gateway's `SmtpMailer`: at the public addresses of its name (`Modules\Kernel\Security\PublicAddresses`, shared with
  webhooks), on a port of `EmailSecurity::takenOn` with its encryption, encrypted (TLS 1.2+, the certificate by the name)
  and with the login taken at the first try (`LoginOnce`), within a deadline every read and write of `MailServerStream`
  waits within; a refusal names its step and code only (Symfony's messages name the login), and only what the merchant
  must mend is a refusal that stops (a server not reached, a timeout or a silent name server is `provider_unavailable`).
  Its server, port or login change only with the password typed again, and what a server says of the account is written
  only over the credentials it was asked with. Checks and tests of SMS and mail count in `RequestLimits` together;
  refused logins stop the merchant at a provider or mail server first, the merchants of its partner next
  (`refused_logins.per_partner`: a partner reaches all its merchants by its API), everybody past more. An automatic message's text comes from
  `Contracts\MessageTemplates::render` (a template per `MessageTopic` and program: the merchant's versions, never
  changed, or the platform's standard text; only the topic's variables, each cut to `MessageTopic::VARIABLE_LENGTHS`).
  Whether a message to a member reached the phone is asked of its provider by `messages:check-delivery`
  (`DeliveryChecker`, on a schedule after it went, the tenants taking turns; by the provider's id, and for SMSC the
  member's number while its blind index is the message's; an account failing for what only the merchant mends is not
  asked); codes and test messages are not followed. What a provider says of an account is written only over the sealed
  credentials it was asked with (`ChannelStore::recordHealthLater(…, $credentials)`): news of replaced ones is none.
- Automatic messages (ADR-0022, module `triggers`, stage 7g): listeners of other modules' events queue a topic's message
  (`MessageTemplates::render`, `MemberMessages::queue`) in the event's transaction, inside a savepoint of their own (a
  message that cannot be queued is reported, never fails a receipt — but a deadlock, a serialization failure, a lost
  connection or a transaction an earlier error left dead is rethrown: there is no savepoint to roll back to), only for a
  topic the merchant switched on for the
  program (`Contracts\AutoMessages`, `auto_messages`: off by default; on is `campaigns.publish`, off the protective
  `messages.pause`; a topic outside `AutoMessages::TOPICS` stays off). A topic switched off goes no more from the queue
  either: the sender asks `Communications\Contracts\AutoMessageSwitches` (bound by `triggers`, every topic goes
  without it; it governs `TOPICS` only) and skips with `switched_off` — a test of communications that delivers such a
  topic binds `EveryAutoMessageGoes`. A greeting goes to a member who joined, never through `import`; thanks for the
  first purchase, for the first receipt that earned points (`ReceiptStats::isFirstEarning`: the merged members'
  receipts count), to whoever holds its points, never through `import` nor within `JUST_JOINED_MINUTES` of joining
  while the greeting is on; congratulations, for a higher rank of the rules' tiers, by purchases or by staff, a message
  per change (`Tiers::mergeMembers` tells one net change; `review` holds the member before the tier, an anonymized one's
  unheld); a birthday greeting (stage 7h-1), with the program's birthday points only, on their `BonusGranted` of kind
  `birthday` (key `birthday:<award>`), naming them — the grant holds the member first (`lockPresent`), as whatever
  changes a member's points. «Давно не были» (stage 7h-2) is a message of a day: `auto-messages:queue` (hourly) scans
  each program once its local day from `AutoMessages::DAILY_HOUR` (`DailyAutoMessages`) for members whose last purchase
  that stands, theirs or their aliases' (`ReceiptStats::lastPurchase`; candidates `lastPurchasedWithin`), was the days
  picked before (`AutoMessages::DAYS`, kept in `auto_messages.days`), holds each (a merged one's survivor, merges of the
  moment too), reads it again and keys the message by member, days and that purchase's moment (`Uu`);
  `auto_messages.scanned_on` marks the day scanned only over the days and mark the scan read — a member who failed
  leaves it unmarked for the next run, a missed day is made up `CATCH_UP_DAYS` back at most, switching on or new days
  mark yesterday. «Баллы скоро сгорят» (stage 7h-3, a service message) goes on the same scan to the holders of points
  of the program's rules expiring before the end of the day so many days on (one of `AutoMessages::DAYS`,
  `ONE_OF_DAYS`; candidates `LedgerStats::expiringWithin`, each member once at their nearest moment, keyset by moment
  and member; through `Internal\Expirations`, at one moment of the clock, the local day of
  `LedgerStats::nextExpiration` and all that expires by its end, `expiringOf`), none to a frozen or blocked card, none
  within `WEEK_DAYS` before the scan's day nor on it (`MemberMessages::queuedSince`, asked first: the member's and their
  aliases' messages waiting, or sent, skipped or failed for good — not `QueuedMessage::PASSING`, nor a failure but
  `LASTING_FAILURES`), keyed by member, that day, the scan's day and the points (a warning that reached nobody goes
  again the next day; a sent one counts from `finished_at`); while no route of its purpose is open
  (`MemberMessages::openRoutes`: the merchant's pause or the platform's stop of the merchant, no channel at work — an
  SMS channel refused for want of money is none until something goes through it) its scan waits, the day open, and a
  member no open route reaches (no number for an SMS, no address for a letter) is not warned. Scans count only the
  messages they add, a member reached through two candidates once. The sender asks `AutoMessageSwitches::stillDue` too: a message whose member bought since
  the purchase of its key, or whose days were dropped, or whose day or points of expiry are no longer the key's, or
  whose card was frozen, is skipped `no_longer_due`.
  Values lose invisible format characters (`StandardTemplates::value`, letters' subjects too); `{balance}` is
  the available points, figures are written as the codes' SMS write them (`Internal\Figures`). The notice of a
  redemption (stage 7g-2), a warning per confirmed receipt that spent points, must hold `{link}` (`MessageTopic::hasLink`:
  a text without it is refused, an older version gives way to the standard text in `MessageTemplates::current`; a
  warning goes in the standard text while the platform stops the merchant's messages): the link «Не вы?»
  `/r/<16 letters and digits>` on the portal's host (`Contracts\RedemptionNoticeAddress`, bound by the portal; none, or
  longer than `VARIABLE_LENGTHS['link']`, and the topic is unavailable — nothing queued goes either; the cabinet's
  previews put in `RedemptionNotices::sampleLink`), whose SHA-256 alone `redemption_notices` keeps — written in the
  message's savepoint, the primary key (found before the tenant by `redemption_notice_tenant()`), 30 days, pruned daily
  (a disowned one 13 months after). `Contracts\RedemptionNotices` serves the page: GET only asks; `disown` holds the
  notice's row, then freezes only an active member (`Members::freezeIfActive`, the reason shown on the member's card),
  ends their portal and member sessions and mails the owners (`TeamNotices::redemptionDisowned(DisownedRedemption)`,
  the card's link by `PanelGate::memberUrl`), once.
- The merchant's MAX bot (ADR-0023, stage 7i, `Communications\Contracts\MaxBot`): one `communication_channels` row of
  provider `max` (`settings`: the bot's id and names, the program whose portal it opens, the SHA-256 of its updates'
  secret; the token sealed by `CredentialBox`). MAX is asked whose bot a token is (`Gateway::maxBot`) before anything
  is kept (refused tokens count in `RequestLimits` as server `max`), then told to post the bot's updates (`subscribeMax`)
  with a new secret at every connection and check, one at a time a merchant (a session's advisory lock); the new
  secret becomes the one updates are taken with only once MAX took it (`webhook_pending_sha256`, both taken meanwhile),
  what MAX said is written only over the token and the secret it was given, and another bot or program in the place of
  one forgets its links.
  Updates come to `POST /hooks/max/<channel>` outside the web group (the tenant by the SECURITY DEFINER
  `max_channel_tenant()`, the header's secret compared by its hash), and the bot replies before the update is
  answered, within `MaxUpdates::REPLY_BUDGET_SECONDS` — never in terminating callbacks, which pile up across the
  requests of one process. A member's MAX account (`Contracts\MaxMembers`, `max_links`: the MAX id sealed, found by a
  blind index; one account a member and one member an account of a bot, placed anew holding the member; a merge passes
  it on as unproven, an anonymization erases it; every new one is told to the number's holder — stage 7i-3:
  `Events\MaxLinked` in the link's transaction, whose `triggers` listener queues «К карте подключён MAX. Не вы? <link>»
  with no savepoint, so a notice not written fails the link (`MaxLinkUnavailable`); `max_link_notices`, `/m/<token>` on
  the portal's host as a redemption notice's; disowning holds the member's links as `place()` does, unlinks, ends the
  member's sessions and takes back a `marketing_max` consent given through the bot since; the topic
  `MaxMembers::LINK_NOTICE_TOPIC` goes by SMS alone, whatever the merchant switched; a link without a code needs a
  funded SMS channel and goes `UNPROVEN_LINKS_PER_DAY` a day, and a code links launch data of `LINKING_LAUNCH_SECONDS`
  only; an account named by launch data — at a code's sign-in, a joining or `max/link` — is linked only by the code the
  bot sends it, typed in the page of the portal's session that asked, stage 7i-4: `MaxMembers::offerLink` /
  `confirmLink` / `resendCode`, `max_link_codes`, `POST max/confirm` and `max/code`, a minute between codes of a session
  and account, the tries carried over; the bot's row is taken `for key share` before rows of links, tokens and codes)
  is linked through the portal opened in MAX — the launch data of the address's
  fragment `WebAppData`, which the page reads and drops from the address and the server checks against the bot's token
  (`MaxLaunchData`, Telegram's scheme, an hour) — at a code's sign-in, a joining or `max/link`, or by a one-time link to
  the bot (`link-<token>`, its SHA-256 kept, 15 minutes) from the portal in a browser; `POST /p/<slug>/max/session`
  signs a linked member in without a code, so whatever ends a member's sessions for protection (a block, a new phone,
  «Выйти везде», `Portals::endSessionsOf`, both «Не вы?») calls `MaxMembers::unlink` too, then `VkMembers::unlink` (stage
  7j: a VK account is linked from a session) — before it ends the sessions:
  the order of locks is the member's row, then their links (`unlink`, `place()` and `claim()` take one advisory lock of
  the member), then the links' tokens and the sessions, and a codeless sign-in issues its session holding its link —,
  and a session the page had never links. The bot offers «Моя карта» only while the program's portal works (`Contracts\MiniAppAddress`, bound by the
  portal). Never link by a contact a person shares: MAX does not say its number is verified. MAX is the first route of
  service messages and advertising (stage 7i-2, `MessageDelivery::routesOf`) for a member whose account is linked at the
  working bot and who did not stop it (`MaxMemberService::recipientOf`; scans ask `MaxMembers::reachable`), advertising
  only with `ConsentKind::MarketingMax`, with the button «Не присылать рекламу» and while MAX posts the bot's updates (the
  refusals come by them); a warning goes by SMS first and to MAX last (a MAX someone else linked must not take the news
  of points spent from the number's holder). Only `bot_stopped` marks a link stopped: MAX refusing a message closes the
  route for that message only. A code goes to MAX only when it names its member (a till's, `StartVerification::$memberId`)
  and their account was linked where they confirmed a code of the number (`MaxMembers::link(…, proven)`: a sign-in or a
  joining in the portal opened in MAX; a link from a browser's portal session proves no phone), and is not public
  (`CodeMessage::$public`: where the portal's code went would tell a stranger the phone is a member's), of a new number,
  of registration, nor asked for again while an SMS channel is there — `CodeSender::assertAvailable` takes all of that.
  A new link made in the portal (not at joining, whose form offered the consent) queues `Jobs\AskAboutMaxAdvertising`
  after commit (ids only); the bot asks of advertising only a member with no state of that consent (`Consents::states`),
  a text a message carries and a bot whose updates come; its buttons carry the version and `MaxMemberService::mark` of
  the member asked, and a press goes through `Members::changeConsent` (channel `bot`), «Нет», the ad's button and the
  word «стоп» as a refusal (`ChangeConsent::$refusal`) recorded even where nothing was given — and taken from a bot
  turned off too. While MAX or VK is the only route open, «Баллы скоро сгорят» warns once and keeps its day open for the
  others until an SMS or a letter may go.
- The merchant's VK community (ADR-0024, stage 7j, `Communications\Contracts\VkCommunity`): one `communication_channels`
  row of provider `vk` (`settings`: the community's id and names, the program, the code VK confirms the platform's
  server of its events with, the server's id, the SHA-256 of the events' secret; the access key sealed by
  `CredentialBox`). VK is asked whose community a key is and whether it may write messages and manage the community
  (`Gateway::vkCommunity`) before anything is kept; the confirmation code is kept before VK is told of the server (it
  asks for the code at once); the server is found by its address's path among the community's (others' servers stay),
  its secret taken once VK's server has it (`vkServer`), its events set apart (`vkEvents`); a secret on its way stays
  taken while a newer one is (`webhook_stale_sha256`), one at a time a merchant. Events come to `POST /hooks/vk/<channel>`
  outside the web group (the tenant by the SECURITY DEFINER `vk_channel_tenant()`, the body's `secret` compared by its
  hash and its `group_id` checked; a `confirmation` is answered with the code, any other event `ok`), a repeat of an
  event does nothing twice (`vk_events`, its id kept a day in the work's transaction), and a failure that would come at
  every repeat is reported and answered (VK stops posting to a server that keeps failing) — one of the moment is left
  for VK's repeat. The community's admins and keys with the right to manage it can read that secret: whoever the merchant
  gives them is trusted with members' data (the cabinet says so). A member's VK account (`Contracts\VkMembers`,
  `vk_links`, the VK id sealed, found by a blind index) is linked only from the portal's profile, by a one-time link to
  the community's chat (`vk.me/<name>?ref=link-<the channel's tag>-<token>`, `vk_link_tokens`, 15 minutes, used up by a
  refusal too) the person writes by — never by a phone or VK ID —, and opens nothing (no sign-in, no tills' codes); a
  card blocked links nothing. The community answers only messages by its links and by the till's invitation
  (`VkCommunityData::invitation`, `ref=card-<tag>`: the portal's address, once a day a person), nothing to a person linked
  already, and no `ref` of another channel or of the merchant's own (its messages are the merchant's to read). Every new
  account is told to the number's holder as MAX's (`Events\VkLinked` → `QueueAutoMessages::vkLinked`, no savepoint;
  `max_link_notices.messenger` `vk`, SMS only, «ВК» to take one SMS); either messenger's «Не вы?» forgets both accounts
  and ends the member's sessions. Every link of MAX and VK counts against the day's three (`Internal\UnprovenLinks`,
  under one lock of the member, the last a link takes). The order of locks is MAX's (the member's row, their MAX links,
  their VK links, the community's row `for key share`, the tokens); whatever ends a member's sessions for protection
  forgets the VK account too, a merge passes it on. Messages (stage 7j-2): VK comes after MAX in the routes of service
  messages and advertising and last of a warning (`MessageDelivery::routesOf`), never a link's notice nor a till's code;
  a message's `random_id` is its own (`randomId`, 31 bits), its buttons an inline keyboard (`VkButton`: «Моя карта»,
  under advertising «Не присылать рекламу» marked by `VkMemberService::mark`; a callback's payload carries the channel's
  tag `ch`, and presses of others' buttons are left), which VK takes only with the community's bot capabilities on — its
  refusal (912, `VkKeyboardRefused`) marks the community (`settings.keyboards_refused`, the cabinet says so, a check
  clears it), and a reply or a message that is no advertising goes again at once without them; advertising goes to VK
  only while it takes them. Advertising needs `ConsentKind::MarketingVk` and a community whose events come; the
  community asks a member it links of that consent while the portal works (`VkUpdates::linked`; the news of the link is
  never limited). VK's answer to a press (`Gateway::answerVk`) binds no payload: a «Да» counts only of the question asked
  — the `conversation_message_id` of the message VK took (`messages.send` to `peer_ids`) and its version, kept with the
  link (`vk_links.question_message`, `question_version`; a merge or a link anew drops it) and taken once —, of a press
  seen the first time (`vk_events` keeps every press under `VkUpdates::PRESS`: a press posted again may refuse, never
  consent), once VK took the answer to it, holding the member and only where the account and the consent's state are
  as the press found them. A refusal — «Нет», the ad's button, «стоп» (also in a message with a `ref`) — counts at once
  for the member the account is linked to now, whatever the button's mark (a merged one's survivor), by a community
  turned off too. Either messenger's «Не вы?» takes back the consents to advertising given online — the bot's, the
  community's, the portal's — since the first account the member's live notices warn of was linked.
- An API request runs in its idempotency transaction, which a refusal rolls back: a write that must outlast it (a
  refused code that counts against limits, a log line, a limiter's hit, a channel's health learnt meanwhile) goes
  through `Modules\Kernel\Database\AfterTransaction` — `keep()` writes now and again after a rollback, `run()` once
  the transaction ends either way (a limiter kept in the database must not hold its row while a provider answers).
  Never put such work in Laravel's own `afterRollBack` callbacks: they run while its manager still holds the dead
  transaction (a job queued after commit is lost, a transaction opened commits the dead one's callbacks);
  AfterTransaction runs it on the connection's TransactionRolledBack event, once.
- МойСклад's tills (ADR-0027, module `moy-sklad`, stage 9.2): the platform's one solution in МойСклад's catalog
  (`config/moysklad.php`; without its id, appUid and secret key — or without https outside local and testing — its
  routes answer 404). Its lifecycle (Vendor API) comes to `<APP_URL>/moysklad/api/moysklad/vendor/1.0/apps/{appId}/
  {accountId}` outside the web group: limited per address, then signed by МойСклад's JWT (`VendorJwt`: HS256 only,
  `jti` once, at most `iat` + 300 s; one key both ways, so our own tokens are refused), then limited per account with
  503 and `Retry-After` (МойСклад takes a 4xx for a failure for good and repeats a 5xx, which gives its token back); each
  request idempotent, held on the account's row with its audit entry (channel `moysklad`); a cause МойСклад may add is
  taken, not refused; its error JSON is МойСклад's protocol, not our problems. `moysklad_accounts` is the platform's own
  table (no tenant); a link is the tenant table `moysklad_connections` keyed by the account (one program on the
  platform), found before the tenant by `moysklad_account_tenant()`. The window `/moysklad/window` is outside the web
  group (no cookie reaches a frame of another site) and works only framed (`Sec-Fetch-Dest: iframe`; its POST also
  `Sec-Fetch-Site: same-origin`; `security.headers:framed-form` with `SecurityHeaders::FRAMED_BY`, МойСклад's origin
  only): its form carries the employee's context sealed (`WindowContext`) for 30 minutes from the window's opening,
  never renewed; only an administrator of the account links it to an active merchant, by a code of the cabinet
  (`moysklad_link_codes`, its SHA-256 the primary key, one a merchant, used up first, wrong ones counted per account).
  The till key is kept as SHA-256 and goes to МойСклад only (`PUT /loyalty`); a link is told to the audit log and the
  owners (`TeamNotices::moySkladLinked`) once МойСклад took it, and МойСклад refusing undoes a new link but keeps the new
  key of a renewed one. A point of sale is a terminal `moysklad-<id>` of kind `pos` (`StoreTerminals`, 500 an account at
  most); whatever changes points of sale holds the link first (for update), then the point of sale, then terminals.
  The tills' requests (Loyalty API 1.0, stage 9.2-2) are `processing`'s: `<APP_URL>/moysklad/loyalty/<account>/…`
  outside the web group, `AuthenticateMoySkladTill` (a flood limit per network and account, the key of
  `Lognex-Discount-API-Auth-Token` by its SHA-256, then the account's limit; a wrong key and an account linked to nobody
  answered alike; the merchant `isOpen()` and the account not `stopped`); every answer is МойСклад's JSON, refusals and
  unknown paths too (`MoySkladRefusal`, texts `processing::moysklad.errors`, code 28001 where the protocol names it, the
  status otherwise), a body read only valid and up to 2 MB, numbers read as text (`MoySkladJson`, never floats). A point
  of sale becomes a terminal only where МойСклад lists it for the account (`TillService::listed`, cached). Positions of
  one product at one price are one line (`TillPositions`: a position the calculation split comes back as the line it
  was). A buyer is named by our id afterwards (`discountCardNumber` too); a request's buyer is known by our id, by
  `moysklad_counterparties`, by that number or a card, by the phone, a merged one followed to its survivor; one the
  program does not know is nobody to a calculation and a sale, and pays with no points. A sale is
  `Checkout::open(…, confirm: true)` once by its keys (МойСклад's ids, and point of sale, number and moment) under
  advisory locks (`moysklad_sales`), refused (`TillSpendChanged`) where the program would spend other points than the
  till took off; a return by its key (`moysklad_returns`, the receipt held; one that took back nothing counted for the
  page «МойСклад», `MoySkladReturns`). Codes the till checks itself are `Verification::startForTill` (status and flag
  `delegated`, confirmed only by `consume` with their context whole, a while past their time; never in the stop of a
  low share of confirmed codes): a registration's found by terminal and phone, a redemption's by terminal and member,
  for the points of the member's last calculation at the terminal (`moysklad_quotes`), sent to the member's own phone;
  a code used forgets the others of its purpose there.
- Sites on Tilda (ADR-0028, module `tilda`, stage 9.3-1): a site is a `tilda_sites` row and a terminal of kind `ecommerce`
  (`tilda-<site id>`) in a location; its key (40 letters and digits, `X-Loyal-Key` in a header or the body) is shown once
  and kept as SHA-256. Tilda posts forms to `/hooks/tilda/<site>` outside the web group. The site is looked for before
  the body is read (`tilda_site_tenant()`): requests for no site are limited per network alone and answered only
  `test=test`. A key in the header is checked before the body is read and only refused ones count against the limit of
  an address at the site (a right key passes it full); without one the body is read first and every request counts. A
  site of nobody and a wrong key are answered alike (a wrong one marks `refused_key_at` once a minute); then the site's
  limit and the merchant `isOpen()`. The body is read by `Internal\FormBody` (not `$_POST`: PHP drops fields past
  `max_input_vars`), which tells names given twice: an order whose `payment` fields a page gave again (a visitor's beside
  Tilda's) is left, and `payment` as text is no order; a JSON body's numbers are text (`Kernel\Json\TextNumbers`,
  shared with МойСклад's JSON). Nothing of the body is logged or kept but the order's number and outcome
  (`tilda_orders`). An order is taken once by its number under an advisory lock, one taken unpaid again when it comes
  paid; paid is a `systranid` not of zeros of a `sys` other than `none`/`cash` (`OrderReader::UNPAID_SYSTEMS`); a paid
  order is `Checkout::upload` (earning only, no discount campaigns) of the member found by the form's phone field, else
  anonymous; Tilda's discounts are shared by the lines, the delivery earns nothing. Answers are text: 200 for whatever
  was taken or left, 503 for what failed for the moment. The merchant attaches the webhook to the cart's form only.
  Tilda tells no returns: `Contracts\TildaOrders::giveBack` (stage 9.3-2, the page's «Вернуть заказ»,
  `members.adjust_points` of a role without `cabinet.adjustment_limits`, which a return is not bound by) returns what
  is left of an order's receipt by its number through the site's terminal (a disconnected one too), numbered `R-<order>`
  (a till's return of that number is answered as itself: the rest goes under a marked one), under the order's lock
  (`OrderIntake::lockKey`), and marks `tilda_orders.returned_at`.
- SDKs (ADR-0011): after any spec change run `composer sdk:generate` and commit the result; never edit
  `sdk/php/src/Generated` or `sdk/typescript/src/generated`. The generator is a closed world: a new schema construct
  needs the generator extended first (`sdk/generator/README.md`). Both SDKs implement the contract of `sdk/README.md`,
  pinned by `sdk/conformance` vectors: a behaviour change updates the contract, a vector and both SDKs. The PHP SDK
  targets PHP 8.2 (no `mb_trim`, typed constants, `#[\Override]`; its own Pint config) and uses no platform code; a
  request's body is sensitive there (`#[\SensitiveParameter]` on every body parameter, generated ones too, a sealed
  `SensitiveParameterValue` in `HttpRequest` and in closures a dump follows: `Tests\Support\Dump`); the
  TypeScript SDK uses erasable syntax only and no runtime dependencies.
- The web till's app (ADR-0016, `frontend/till`): TypeScript with erasable syntax only and no dependencies, compiled by
  the SDK's TypeScript into a build folder `public/till-app/<version>` named in `build.json` (not in git,
  `composer till:build`); the shell puts that folder into the page and the manifest. It speaks the Runtime API only
  through the SDK, with its own `fetch` that sends the device cookie (the SDK omits cookies); the shift key stays in
  memory. Elements are made with `dom.ts` `h()` (texts are text nodes, never markup); the page's CSP allows nothing
  inline. A receipt without an answer is repeated as it was (same body and idempotency key) across locks and new keys,
  and `receipt_exists` under a new key is settled by `findReceipts`; its number stays pinned after refusals (the next
  request, of any purchase, goes under it with a new key) until that receipt is found or the number registers another.
  Paying with points by a scanned app code names the member by the code where it spares the SMS, otherwise by id.
  A new member's phone is confirmed by a code unless the program says otherwise (`ProgramData::confirmsPhone`, switched
  with `till.manage`, given to the till as `program.confirms_phone` and read again for every registration); without a
  code the cashier is named and only the required consents go, without an inviting code — the API holds to the same.
  A return is found among the member's purchases (`listMemberReceipts`; the till prints no receipt numbers) and follows
  the receipt's rules: repeated as it was until answered, its number pinned to the receipt for the receipt's next return.
  Receipts (online and in offline batches) and returns taken with a shift key keep its device (`device_id`); a
  shift's summary is its device's between the shift's opening and closing (`ReceiptStats::ofDevice`), none of a locked
  shift. Without a connection the till records accrual-only purchases of a member into its outbox (`outbox.ts`, kept by
  `storage.ts` in localStorage under the device's id, 72 h at most) and sends them in `receipts:batch` batches; what a
  reload brings back waits for a cashier's «Отправить проверенные». An `exists` result is its own receipt only when
  number, purchase time, total and member match (under an inherited number the same purchase at full price counts
  too, another one goes again under a number of its own, and what the till cannot tell is a conflict for the cashier).
  Pins and a receipt or return on its way are saved before the request goes; a batch request is not saved. The shell
  answers `till_device_revoked` (with `Clear-Site-Data`) only to a device gone for good; `till_device_required` leaves
  the browser's storage (a new pairing asks first), and a key the till dropped sends nothing. A batch is finished by
  the first to finish it; given up on, it names only the receipts registered (`receipts:finish-batches` hands batches
  no job finished to a job again). The camera (`camera.ts`, `Camera` in TillOptions; `browserCamera()` only where
  `BarcodeDetector` and a camera API exist) reads scans, never typed text; it stops its stream at the abort itself, and
  a request, a screen change or a hidden page aborts it. A refusal `member_merged` puts the member its `survivor_id`
  names (looked up by id) in place of the member found, and drops what was calculated or listed for the merged one.
- The member plane (ADR-0018, `/api/member/v1`, `docs/api/member-v1.yaml`, routes in `processing`): a session `lms_…`
  (`Modules\Access\Contracts\MemberSessions`) is one member of one program on one site, and works while the merchant key,
  partner's client or portal session that opened it does; `member.session:<scopes>` takes only a request whose `Origin`
  equals the session's site (as `SiteOrigin` writes it) — or, without one, a same-origin request (`Sec-Fetch-Site`) on the
  site's own host — and sets the tenant, and the controller checks the member itself on every
  request (`MemberResolver::ofSession`: blocked, anonymized, merged or of another program: 401, but for ending the
  session). Limits count per member, not per session. Sessions are opened by `POST /api/management/v1/member-sessions`
  (scope `widgets`, which reads members' data: a partner's developer grants it not; `presentation_code`, `consents` and
  `details` need the credential's `members` too) and by the customer portal for its own page; a session knows its opener
  (`MemberSessionOpener`). What a member changes of themselves (stage 7e-3) goes through `Members::changeDetails` and
  `changeConsent` (consents to advertising only, to the version shown, recorded with the channel `portal` or `website` by
  the opener, and the session, the opener's credential, site and address as evidence; the member's row held `for no key
  update`); a birthday kept later is known from then (`birth_date_known_at`): the birthday points wait for it as for a
  membership, a receipt's birthday campaigns count it — as one given joining in the portal — after
  `CheckoutService::OWN_BIRTHDAY_DAYS`, and staff correct a known one in the card (`Members::correctBirthDate`). An
  operation names what it reached beyond its path in the audit entry with `RecordAudit::SUBJECT`. CORS
  (`config/cors.php`) covers the Runtime API and the member plane, never the Management API.
- The customer portal (ADR-0021, module `portal`): a program's portal is `/p/<slug>` on `PORTAL_DOMAIN` (none of the
  cabinets', console's or till's hosts; without it on any host in local and testing, nowhere elsewhere); the slug is the
  primary key of `program_portals` (public, unique across the platform) and is found before the tenant by the SECURITY
  DEFINER `portal_address()`. Its own requests are in the web group (`Sec-Fetch-Site: same-origin` or the XSRF token),
  answer problems as JSON, and their codes are in `Tests\Support\ProblemCodes::INTERNAL`. A code goes only after the
  check that a person asks (`Internal\HumanCheck`: SmartCaptcha with both keys — passing when the service errs —, always
  passing without them in local, testing and the sandbox, unavailable elsewhere), bound to the program, and is public
  (`StartVerification::$public`): it keeps to limits of its own — per recipient and address, half of the merchant's day
  and month, a stateless stop of its own — and the merchant's stop counts the tills' codes only. A member gets a code of
  sign-in, a phone of nobody a code of registration with the same answer where people may join there
  (`Portals::joins`: the portal's `joining`, the merchant's choice, and the program's rules and consent to process
  personal data published), a 404 elsewhere; whatever depends on whether the phone is a member's is asked for every
  phone and told only to whoever confirmed the code of that phone and portal (`Verification::usable` checks a code
  without using it up; a public code's pause and repeat follow all public codes of the phone, whatever their purpose,
  and only whoever names its context whole takes it). Signing in holds the portal open (`Portals::hold`), looks the member up, uses the code up before
  telling anything of the member and issues the session in one transaction; joining (`POST members`) checks the code of
  registration before anything else it is sent, then enrolls through the channel `portal` (`EnrollMember::
  $verificationContext` binds the code to the program, `$consentVersions` records the consent to the version the page
  showed or refuses a newer one). A portal session (`Access\Contracts\PortalSessions`, `lps_`, a year,
  never extended) lives in a `__Host-` HttpOnly SameSite=Strict cookie named by its portal's slug (`PortalCookie`: no
  other host of the domain plants one); the member is
  checked at every request, and a block, a new phone, an anonymization or a merge ends the member's portal sessions in
  its transaction (`MemberStatusChanged`, `MemberPhoneChanged`, `MemberAnonymized`, `MembersMerged`). `Portals::open`
  opens a program's portal only (a program that has one: `PortalExists`), `move` moves an open one only (one closed
  meanwhile stays closed); what changes a portal of a program without one is `PortalNotFound`. Closing a portal
  only protects (`portal.close`, a suspended merchant's too), as do stopping people joining (`portal.close`; letting them
  join is `programs.manage`) and signing a member out everywhere from the card (`members.block_cards`, as a lost card). The page
  reads the member through the member plane with sessions its portal session opens (the third opener of
  `member_sessions`), and the member plane takes a same-origin request of its own host by `Sec-Fetch-Site`.
- The customer portal's app (stage 7f, ADR-0021, `frontend/portal`): TypeScript with erasable syntax only and no
  dependencies over the SDK's member client and the member widgets' sources (relative paths), compiled by the SDK's
  TypeScript into `public/portal-app/<version>` named in `build.json` (not in git, `composer portal:build`), which the
  page `/p/<slug>` loads with nothing inline (`dom.ts` `h()`: texts are text nodes). The card is the member widgets
  with the page's sessions of the member plane (`POST session/tokens`, one provider for the page's life). The page is
  `/p/<slug>/` with its slash (the app's scope, matched as a prefix: without it one portal's would take in another's;
  `/p/<slug>` redirects, `public/.htaccess` keeps the slash; the tests' requests cut it — use `PortalPage::get`). The page
  keeps its strict policy: the box «Я не робот» (SmartCaptcha, another site's script that writes inline styles) lives in
  a frame of its page `/box` on a host of its own, PORTAL_CAPTCHA_DOMAIN (required with the keys outside local and
  testing; `PortalHost::servesCaptcha`), with its own policy (`security.headers:portal-box`: the box's hosts in
  `SecurityHeaders::SOURCES`, `FRAMED_BY` the portals' origin), and talks to the page by messages of each other's
  origin only (`captcha.ts`, `smartcaptcha.ts`); signing in or out reloads the page. The manifest, the service worker
  (served from the portal's path, scope `/p/<slug>/`, registered once the page opened), the card's icons (`CardIcon`, a
  PNG drawn once per colour, its address naming the drawing and the colour) and the box's frame are outside the web
  group; the worker keeps the build's files only, each checked against the digest the build wrote into it before it is
  served, and serves the build's page «Нет соединения» without a network — never a page of a portal or an API's answer.
  A phone of nobody joins there (stage 7f-2): the form shows the documents with their texts and the line «Мне есть N
  лет» of the portal's age (`program_portals.min_age`: 14, or 18 the merchant sets with `programs.manage`; a rule of the
  portal only, staff at a till see the person), and `POST members` takes `age_confirmed`, refusing — after the code
  check — any but the portal's age now (409 `portal_age_outdated`, with `min_age`) and a birthday under it by the day
  of the program's zone (422 `portal_age_not_reached`); the confirmed age goes into the consents' evidence. The age is
  a rule of joining: a birthday told later is kept as told. The profile (stage 7f-3, `profile.ts`, the tab `#profile`)
  changes what the member may of themselves through the member plane with the page's sessions, asked when its tab first
  opens: names only as changed, a birthday once after the page asks, an address by its letter's code («Отправить письмо
  ещё раз» asks nothing within the letter's minute unless its code is gone), the consents to advertising to the version
  shown; a refusal is said in its section's line (always on the page), a section's controls wait while its request goes
  and give back the focus, the boxes change in place (a read older than a box's change leaves it), a consent's change
  without an answer shows what the member plane has, and a session gone signs in again. The unsubscribe page leads to
  `/p/<slug>/#profile` where the program's portal works and the member takes part (`Unsubscription::$takesPart`); a
  failure to read the portal leaves the link out, never the page. The card's colour (stage 7f-4, `Portals::setColour`,
  `programs.manage`) is `program_portals.colour` (none: the platform's): the icon and the browser's bar take it as it
  is, the app's accent a shade of it every member can read in the light and the dark look (`CardColours`, a contrast of
  4.5), from `/p/<slug>/theme.css` after the build's stylesheet (outside the web group); the addresses of that sheet and
  of the icons name the colour and are kept for good, and one of a colour the portal no longer has is answered with the
  colour it has, kept by nobody.
- The member widgets (ADR-0018, `frontend/widgets`, `docs/api/widgets.md`): TypeScript with erasable syntax only and no
  dependencies over the SDK's member client (its sources by relative path), bundled by `frontend/widgets/build.mjs`
  into one module per version, `public/embed/v1/<version>/loyal-widgets.js` (named by its hash; `build.json` names the
  current one and its integrity). The builds are kept in git and a published one never changes or goes: after any change
  of the widgets or of the SDK modules they import, run `composer widgets:build` and commit the new build
  (`widgets:test` fails while public/embed/v1 does not hold the sources' build); a new build removes the builds git does
  not hold, and no commit changes, moves or removes a committed one (`tests/Architecture/WidgetBuildsTest.php` reads the
  history). The bundler takes relative named imports, exports of functions, classes, constants or names of unchanging
  bindings, no cycles, no `import()`, no top-level `await` and `import.meta` in the entry only. Elements are
  made with `dom.ts` `h()` (texts are text nodes, never markup), the styles are one constructed sheet (no inline style
  a page's policy would refuse), the QR is an `<img>` of a checked SVG data address. Widgets of one `tokenProvider` and
  API share one member client (`access.ts`); `endSession()` starts a new generation, and nothing of the ended session
  serves a widget again. The API is the script's site or the `api` property, never an attribute (the widget gives it the
  member's session). A new text, `--loyal-*` variable or part goes into the tables of
  `docs/api/widgets.md` (`test/docs.test.mjs` compares them). The demo `/widgets-demo` (`WidgetsDemoController`,
  `LocalWidgetsSeeder`) is registered in the local environment only.
- Staff (ADR-0013, module `identity`): accounts and e-mails only through `Modules\Identity\Contracts\StaffUsers` (the
  e-mail is encrypted with a `platform`-scope blind index and leaves the module masked); access is decided per request
  by `StaffAccess`, which never touches the tenant context; team rules (last owner, own membership,
  `team.manage_owners`) live in the membership services, not in the UI; platform operators hold no team memberships.
  A partner's people manage no merchant's team: they only hand a merchant without a working owner over to its first
  owner (`Invitations::inviteMerchantOwner`, accepted through `TenantMemberships::addFirstOwner`) and revoke such an
  invitation (protective `invitations.revoke`).
  Mail to staff is a queued notification, encrypted (`ShouldBeEncrypted`), after commit, in Russian (`locale('ru')`);
  a link in a mail is built from APP_URL (`Modules\Cabinet\Kit\PanelHosts::forMail`), never from the request's host;
  text someone else typed goes into a mail through `MailText::literal()`. People join teams by `Invitations` (accepted
  through the team's own service on behalf of the inviter); tests read the link from
  `Notification::assertSentOnDemand(InvitationMail::class, …)`.
- Cabinets (ADR-0014, module `cabinet`): Filament pages, schemas and custom-data tables over module contracts; no
  Filament resources over other modules' models. The merchant comes from the URL as `MerchantWorkspace` (never queried);
  `ApplyMerchantContext` sets the tenant context on every page and Livewire request. The partner cabinet
  (`/partner/{partner}`, `PartnerWorkspace`, `ApplyPartnerContext`) has no tenant context: what it reads of a merchant
  it reads in that merchant's (`TenantContext::run`), and it reaches credentials only through contracts that take the
  partner (never `ManagementCredentials`, architecture test). Every cabinet capability is a
  contract method that validates its input (parity with the APIs). Merchant and staff texts are rendered escaped only.
  Middleware that must also guard Livewire updates is registered persistent (Livewire matches it by class). Livewire
  polling (`wire:poll`) counts as staff-session activity: the update replays the page's `identity.session` check.
  Every change of data or of someone else's access made from a cabinet is a `Kit\Actions\GuardedAction` with a
  permission, a `CabinetAction` (new names go into `AuditAction` of the Management spec, then `composer sdk:generate`)
  and its declared audit input; every cabinet page uses `GuardsCabinetPage` (it also refuses crafted mounts of any
  method but a public argument-free action factory, and of record actions without a proper record key). Name the page's
  factory methods so they do not end in `Action` (Filament would resolve `{name}Action()` itself). A secret shown once
  (a key's token, a webhook's signing secret) goes through `Kit\Pages\Concerns\RevealsSecretOnce` — a protected
  property, never a public one, a notification or the session. Own-account pages
  (profile, sessions) write to the security log instead; the invitation page, whose person is not signed in yet, writes
  its entry through `CabinetAuditor::recordInvitationAccepted`. Problem titles shown in cabinets live in
  `cabinet::problems` (equal to the API catalogs, plus internal codes). A page of an audit log extends
  `Kit\Pages\AuditLogPage`: the merchant's log hides operators, the platform's (`AuditLog::ofPlatform`) names them.
  A page that shows what an audited look-up found keeps its id in a `#[Locked]` property only the look-up action sets,
  so its record actions reach that record only (`Platform\Pages\Accounts`). A page that shows members' personal data
  writes the look when it shows (`CabinetAuditor::recordRead`, as `management.audit:reads`; the same look within a minute
  once): a member's page at mount after checking its access itself (Filament checks it after `mount()`), the list per
  page of names. A Select's key made of digits comes back from Filament as an int (`OptionStateCast`): read form
  choices as text again (`MemberActions::option`).
- Merchant statuses (ADR-0015): `suspended` only reads — Management API changes answer 403 `merchant_suspended`
  (`RequireMerchant`; the only exceptions, with a reason, in `RequireMerchant::WRITES_WHILE_SUSPENDED`), the cabinet is
  read-only but for what only protects (permissions `MerchantPermission::isWrite()` excludes: revoking keys, disabling
  promo codes, pausing actions and messages, blocking lost cards, revoking invitations — a suspended partner keeps revoking its own
  credentials and invitations too; not through support access, which only reads there), tills keep working; `closed`
  is refused everywhere, its keys too. A till key also needs an active terminal (`api_key_candidates` returns both
  statuses); a status is checked by `MerchantData::isOpen()`, never as "not
  closed". Every cabinet table with filters cleans what a request changes with `Kit\Tables\FilterState` (in
  `handleTableFilterUpdates` and `updatedTableDeferredFilters`; filters from the address, `#[Url]`, pass the filters'
  form at mount); `GuardsCabinetPage` keeps every table's `tableSearch` a text (Filament renders its chip even where a
  table cannot be searched, and fails on a list); a filter of days is `Kit\Tables\DayPeriod`. Keyset cursors over
  `(time, id)` are read with `Cursor::timeAndId` (a crafted cursor is a 400, not a database error). The console sees and
  revokes credentials but issues none (architecture test); the partner cabinet caps a new client's scopes by the
  issuer's role, and `PartnerCredentials` holds to the cap (a developer grants none of `members`, `audit`, `widgets`
  and `communications`); mail to a team's owners about what the platform did goes through
  `Modules\Identity\Contracts\TeamNotices`. An operator works
  in a merchant's cabinet only through a grant of `Modules\Identity\Contracts\SupportAccess`: StaffAccess asks it last,
  with the explicit permissions of its mode
  (`SupportMode::permissions`, never a sensitive one; a new merchant permission is classified in `SupportAccessTest`);
  it ends with the operator's role, account, an administrator's reset of the second factor and the merchant, and works
  only in a session where the
  operator confirmed who they are since it began (`ApplyMerchantContext` signs older ones out). The second factor is a
  choice (ADR-0013, 2026-10-22): a session is confirmed (`StaffSessions::confirm`) by the strongest factor its person
  has — the code, or the password without one (`PasswordConfirmations`, never for a person with a code), and
  `GuardedAction`'s step-up asks the one or the other. A link from the console to
  a cabinet is built as mail links are, on APP_URL (`MerchantWorkspace::cabinetUrl`), not with Filament's `getUrl()`.
- The system connection (`pgsql_system`) is used only in the files listed in
  `tests/Architecture/SystemConnectionTest.php`; add a new one there with its purpose.
- Public traffic (ADR-0029, stage 11.4-1: the APIs, the portal, the hooks, МойСклад, the web till on its own host —
  on the cabinets' it goes with them, its pairing ends the cabinet's session there; the paths of
  `Modules\Kernel\Traffic\PublicTraffic`, where a new route takes its side, `tests/Architecture/PublicTrafficTest.php`)
  runs in production with a login of `loyal_rls_tenant` alone; the cabinets, the console and the workers with
  `loyal_rls_staff` too. A pod names its side (`LOYAL_TRAFFIC` public|staff|all, `TrafficSide`) and keeps to it: it
  answers the other side's paths 404 (`KeepTrafficToItsSide`); a pod of public traffic has no usable system, owner or
  superuser login, checks the login of every session it opens and keeps cache, queue (no `sync`) and sessions out of the
  database (`PublicTrafficLogin`); every side shares one Redis for cache and queue. What only staff need — identity's
  tables, `report_subscriptions`, the platform's operation (`health_reports`, `scheduled_runs`, `platform_heartbeats`),
  the framework's cache, queue and migrations tables, the definer functions of memberships and invitations — is
  `loyal_rls_staff`'s, with exactly the rights the tenant role had (`Rls::moveRights()`): its migration calls
  `Rls::staffOnly()` / `Rls::staffFunction()` (or `Rls::staffWrites()` for what public traffic only reads,
  `communication_switches`) and lists it with the reason in `tests/Architecture/StaffDataTest.php`. Public traffic
  reaches staff only through the queue (`TeamNotices` of codes, «Не вы?» and МойСклад queue `TellMerchantOwners`, tried
  again when the look-up fails); a partner's audit entries without a tenant are read through the view
  `partner_audit_entries` (operators unnamed), not the system connection. The tests run every request of public traffic
  with `set role loyal_rls_tenant` and fail one that uses the system or owner connection; a job it queues runs after it,
  as a worker's, with the tenant its payload carries (`PublicTrafficRole`, `PublicTrafficQueue`). A database made before
  this stage takes `php artisan db:bootstrap` before `composer migrate`.
- Retention (ADR-0030, stage 11.5-1): every table is classified in `tests/Architecture/PersonalDataTest.php` (personal
  data and how long it stays, or none), and one with personal data is named in ADR-0030's table of terms. What outlived
  its keeping goes by a scheduled prune of its module, on the system connection where it crosses tenants, in batches.
  An append-only table whose old rows go keeps its guard through `Immutability::keptFor(table, column, floorDays)`: no
  update for anyone, a delete only of a row older than the floor and only by whoever is of the system role (checked by
  the trigger: a view deletes as its invoker); the policy is the prune's configuration, which must exceed the floor (the
  command refuses otherwise; a test compares its `FLOOR_DAYS` with the trigger's arguments). An anonymization is final
  in the database (`members_anonymization_final()`): `anonymized_recorded_at` is the database's own time, set with the
  status, and neither changes after; `proofs_erased_at` is written once, by the system role. Consents and the codes
  that confirmed phones at joining (`verification_requests.member_id`, `Verification::keepAsProof`) go only to the
  system role, of members anonymized 180 days ago at least by that time, through `ConsentProofs` and `CodeProofs` from
  `members:prune` (`members.keep_proofs_after_anonymization_days`, `PROOFS_FLOOR_DAYS`); other confirmed codes go after
  13 months. A module that keeps something of a member that names the person erases it on `MemberAnonymized` and writes
  it holding the member. The runtime roles make no temporary tables; every function of the schema names its search path
  `pg_catalog, public, pg_temp` (`tests/Architecture/FunctionSearchPathTest.php`; the policies' two helpers excepted);
  views are read only to the runtime roles. The emergency logger redacts too (`RedactingLogManager`, not final: tests
  spy on the log). A merchant's closing is kept (`tenants.closed_at`, set by `Merchants::close`, forgotten by
  `reopen`; only staff change `tenants`, public traffic reads and adds); `members.erase_after_merchant_closed_days` (30,
  7 at least) after it, `members:erase-closed-merchants` (hourly, minutes a run, merchants paged by closing)
  anonymizes every member it still has (`Members::presentIds`, `anonymize` each in its own transaction holding the
  merchant closed since that moment, `Merchants::holdClosed`; a member that fails is reported and passed over), and
  once none is left and none failed marks it done of that closing only (`Merchants::markMembersErased`) and writes
  `merchants.erase-members` to its audit log. A closed merchant is told no webhooks (`FanOut`). Before closing, its
  owners take the base out (stage 11.5-4, `Reports\Contracts\MemberBaseExports`, «Участники» → «Выгрузить базу»): a CSV
  of every member present, newest first, contacts whole (a phone as its digits), the points as a member's card tells
  them and the tier as the program counts it (`RuleSet::tierOf`), of one snapshot (a `repeatable read, read only`
  transaction, unless the caller's), written BATCH members at a time into a stream and whole before it goes, each
  batch's points, tiers and consents in one call of each module (`Members::withContacts`, a CursorPage over the index of
  registration; `LedgerStats::accountBalances`, `Tiers::currentOf`, `Consents::statesOf`). `members.export_all` is the
  merchant's owners' alone (no admin, no partner), sensitive, reads only; the action gives a link of a minute
  (`Merchant\Members\BaseDownloads`) and `Merchant\Http\DownloadMemberBase` sends the file as a plain download — never
  a big file through Livewire, which holds it in memory inside its JSON — once every owner was mailed
  (`TeamNotices::membersExported`; told to nobody, no file).
- A member's data on request (ADR-0031, stage 11.5-2): a module that keeps something of a member tells it through a
  source (`Modules\Kernel\Privacy\MemberDataSource`, registered with `MemberDataSources::register()` in its provider):
  its own tables of every id of the request (the member and the records merged into them), sheets keyed
  `<module>.<what>` in `MemberDataExportService::ORDER`, texts in `<module>::member_data`, and never what names other
  people (a cashier, staff, another member, a messenger's account id, the address a code was asked from, a code to a
  number before it was the member's, the address of a till or a server). Every table with `member_id`, and those that
  name a member otherwise (`MEMBER_TABLES_OF_OTHER_KEYS`), is read by a source (`tables()`) — of its own module only —
  or excused in `tests/Architecture/MemberDataTest.php`. A sheet's title holds none of `[]:*?/\`. The file is
  `Reports\Contracts\MemberDataExports` (XLSX, made whole), downloaded from the member's card with
  `members.export_data` (sensitive, reads only, `perHour` and `perDay`). Cells and sheets of files are the kernel's
  (`Modules\Kernel\Files`).
- «Состояние системы» (ADR-0015): a module's health check implements `Modules\Kernel\Health\HealthCheck` (a key
  `<module>.<what>`, every code it may answer with, read-only facts without personal data, counts bounded with
  `Counted`) and is registered with `HealthChecks::register()` in the module's provider; its title and a text per code
  go into `cabinet::health.checks` (`TextsTest` compares them). Only `platform:health` runs the checks (every minute);
  the console reads the results it keeps (`HealthReports`), never the system connection. Scheduled tasks are recorded
  in `scheduled_runs` by the kernel (`ScheduledRuns`); the scheduler and the queues beat through `platform:heartbeat`;
  a queue the workers serve goes into `queue.heartbeat_queues`.
- No personal data or secrets in logs, events or exception messages. Domain events (`Modules\<Name>\Events`) carry
  ids and amounts only and are dispatched inside the transaction of the change, so listeners succeed or roll back
  with it. A new integration event: dispatch a domain event, map it in `Modules\Outbox\Internal\OutboxRecorder`
  (and `OutboxServiceProvider::RECORDED`), add its type to `EventTypes` and describe it in `docs/api/webhooks.md`.

## Testing gotchas

- Feature tests run as the app role inside a rolled-back transaction, so RLS applies. Use
  `actingAsTenant()` / `tenantContext()` from `tests/Pest.php`.
- `systemConnection()` is a separate session and does not see the test transaction: commit fixtures through
  it and delete them in `finally` (see `app-modules/tenancy/tests/Feature/SystemRoleTest.php`).
- `Tests\TestCase` closes every database connection when a test ends (the refresh trait closes only the one it rolls
  back): a test base class extends it, or a whole run uses up the server's 100 connections.
- Tests that need several sessions or system processes (concurrency, `ledger:*` commands) live in
  `app-modules/*/tests/Integration`: data is committed, every test creates its own tenant.
- A seeded random test draws from a generator of its own (`new Randomizer(new Mt19937($seed))`), never from
  `mt_srand()`/`mt_rand()`: the global generator is reseeded at random whenever the garbage collector frees a Faker
  generator (`Faker\Generator::__destruct()` calls `mt_srand()`), which can happen in the middle of any test that runs
  after one that used `fake()` or a factory.
- Ledger tests run `set constraints all immediate` so the balance trigger fires before the rollback.
  `Modules\Ledger\Tests\Support\LedgerScenario` sets up a tenant, point type and member.
- `Modules\Members\Tests\Support\MembersScenario` sets up a tenant, a program with published consent
  documents and a `FakeCodeSender` (captures codes; `unavailable`, `failing` and `channel` play the merchant's
  channels). Install fakes before resolving the services that use them.
- `Modules\Communications\Tests\Support\FakeGateway::install()` plays the providers (refusals scripted per login,
  `summary()` of the calls, `beforeSms` / `beforeStatus` for what happens meanwhile, `report()` for what a provider says
  of a message it took) and rebuilds `Channels`, `CodeSender` and
  `Verification`; the providers' HTTP APIs are tested with `Http::fake` on `SmscApi` / `SmsAeroApi` themselves. Messages
  to members are delivered in a Feature test's tenant (`MessageDelivery::deliver`); `messages:send` across tenants is
  tested in `tests/Integration`, and such a test deletes what it leaves waiting (through the system role), or a later
  run sends it.
- PII keys for tests are fixed in `phpunit.xml`; never log or return decrypted phone/e-mail (use masked values).
- `json_encode` writes `/` as `\/`: to look for a base64 secret in a Livewire snapshot, encode it with
  `JSON_UNESCAPED_SLASHES` (or `serialize()`), and read a secret from where it is kept rather than by a regex over HTML.
- `Modules\Processing\Tests\Support\CheckoutScenario` sets up a program with published rules, a till and a
  member with 1000 points; checkout tests run `set constraints all immediate` like ledger tests. HTTP tests
  that send whole-second times travel the clock a minute past the rules publication.
- `Modules\Rules\Tests\Support\TestRules::make([...dotted overrides])` builds a rule set for engine tests,
  `TestRules::campaign($id, [...])` a campaign definition; `RulesScenario` sets up a program with published
  base rules and runs campaigns through the real services (`runningCampaign([...])`).
  `TestRules::tiers([...])` is the standard tier set (base 3 %, silver 5 %, gold 7 %) and `TestRules::bonuses([...])`
  the standard welcome, birthday and referral bonuses; pass them as `tiers:` / `bonuses:` to
  `RulesScenario::start()` / `CheckoutScenario::start()`. `TestRules::stampCard($pointTypeId)` is a coffee stamp
  card (LATTE, ESPRESSO, every sixth free); its point type is a separate `PointType` with precision 0. `Modules\Tiers\Tests\Support\TiersScenario` records
  purchases and returns directly; tier tests freeze the clock with `travelTo()` and move it with `travel()`.
  Pest resolves closures in datasets after `beforeEach` with `$this` bound, unless the test parameter is typed `Closure`,
  `callable` or `mixed` (then the closure itself arrives, without `$this`).
- Audit entries of a partner outside its merchants have no tenant and are read through the system role, so a
  Feature test cannot see them: test them in `tests/Integration`.
- Integration tests commit partners and merchants that stay until the next test process migrates afresh, so a test
  run after them in the same process (a run of a few modules) sees them: a test that searches the directory looks for a
  word of its own (`tenancy/tests/Feature/DirectoryTest.php`).
- The web till's flows are tested in `frontend/till/test/flows.test.mjs` over a stand-in DOM (`test/support/dom.mjs`),
  a scripted shell and a scripted Runtime API, with `t.mock.timers` for `setTimeout`: the SDK's pause before a repeat
  (a network error, 502–504) sleeps on it too, so such a test ticks the clock or it hangs.
- Member plane requests send `Origin` too: `CheckoutScenario::memberSession()` opens a session for
  `https://shop.example.com`; a browser's preflight (`OPTIONS`) is no operation of a specification.
- The portal's tests: `FakeHumanCheck::install()` plays the check; the tests' JSON requests send cookies only
  `withCredentials()`; the framework skips the CSRF check while tests run (`$this->app['env'] = 'local'` tests it); the
  portal on its own host is tested in `tests/ConsoleHost` (`ConsoleHostTestCase::PORTAL_HOST`, https: a portal session
  opens member sessions for an https site only).
- The portal's app is tested in `frontend/portal/test`: flows over the widgets' stand-in DOM with fields and forms
  (`test/support/dom.mjs`), a scripted portal (`support/portal.mjs`) and the widgets' scripted member API, with the real
  widgets of the card. `php artisan db:seed --class=LocalPortalSeeder` makes a merchant without channels, whose portal
  (`/p/kofe-u-doma`) writes its codes to the application's log: try the portal there, never on the demo merchant of the
  till, whose channels reach real providers.
- The widgets' tests run over a stand-in DOM (`frontend/widgets/test/support/dom.mjs`: install it, then import the widget
  modules dynamically, as their classes extend `HTMLElement`) and a scripted member API (`test/support/api.mjs`,
  `serve()` answers by operation and installs the fetch for the clients made from then on). `php artisan serve
  --host=localhost` may answer on `[::1]` only: the local demo starts at `http://localhost:<port>/widgets-demo`.
- `Tests\Support\Sdk\KernelTransport` sends the PHP SDK's requests through the HTTP kernel of the test (see
  `tests/Feature/Sdk`); `sdk/php/examples/quickstart.php` (`loyalQuickstart()`) sets up a merchant end to end.
- Sandbox-mode tests live in `tests/Sandbox` (`Tests\SandboxTestCase` boots the app with `LOYAL_SANDBOX=true`); they use
  test phones `+7900000NNNN`, e.g. `CheckoutScenario::start(memberPhone: '+79000000001')`.
- `Modules\Identity\Tests\Support\StaffScenario` sets up a partner with a merchant, a direct merchant and another
  partner's merchant, and makes staff with roles (`merchantMember()`, `partnerMember()`, `operator()`) through the
  command-line actor. Staff passwords hash with cheap Argon2id settings in tests (`phpunit.xml`). Statements expected
  to fail in the database (RLS, triggers) run inside `DB::transaction()`, so the failure only rolls back a savepoint.
- `Modules\Cabinet\Tests\Support\CabinetScenario` wraps StaffScenario for the cabinets: `withMfa()`, `code()`,
  `signIn()` (a staff session in a fresh Laravel session) and `livewireUpdate()` / `refreshLivewire()`, which send
  Livewire updates through HTTP with all middleware and a browser's headers: `Livewire::test` skips middleware and its
  request has no session (what `withSession` stored is still read by `session()`), so tenant, session and password-hash
  checks of the cabinets are tested over HTTP. Filament page tests
  call `Filament::setCurrentPanel()` and, for pages inside a merchant, `setTenant()`; the profile has no tenant. Panel
  hosts (`CONSOLE_DOMAIN`, and the till's `TILL_DOMAIN`) are tested in `tests/ConsoleHost` (`Tests\ConsoleHostTestCase`). `RecordingAuditLog::install()`
  keeps the audit records a test wrote (console entries have no tenant, so RLS hides them from feature tests);
  `GuardedActionProbe` and `MerchantActionProbe` are pages with guarded actions; `CabinetScenario::wrongCode()` is a
  code the authenticator surely refuses. Filament renders an open action's modal as a partial of the update, outside
  `html()`: assert it with `assertMountedActionModalSee()` / `…DontSee()` / `…DontSeeHtml()`; while it stays mounted (a halted action), `html()`
  is the last full render, so unmount (`->call('unmountAction')`) before asserting the page or calling another action
  (it would be looked up inside the open one). Livewire's Testable passes
  assertions it has not (`assertSeeInOrder`, `assertForbidden`) to the update's JSON response. `CabinetPrincipal`
  remembers a user's platform access for
  the request: a `Livewire::test` that changes the role of the same user mid-test sees the old one until
  `app()->forgetScopedInstances()`.
- The tenant context cannot change inside a nested DB transaction (by design).
- A report reads whole days of a `Modules\Kernel\Time\ReportWindow` (a named zone, at most 92 days; `lastDays`, or
  `between` days of the calendar and its `previous()` to compare with, stage 8a): it bounds the plain column (`>= from`,
  `< to`) so the bounds reach an index, and groups by `(column at time zone ?)::date` with the window's zone; never an
  offset for a zone (PostgreSQL reads `+03:00` the POSIX way, west). A report by months reads a `ReportMonths` (at most
  12, stage 8b) and names the month of a moment by where PHP's months end (`width_bucket` over `ends()`), never by the
  database's tz data. What members held at a moment is what they hold now less what took effect since, in one
  statement (`LedgerStats::movement`); the end of a range is its start and what moved. Liabilities by legal entity count
  lots: a lot is of the entity its source operation kept (`ledger_transactions.legal_entity_id`, which the database
  writes from the operation's location before the insert — pass a location, never an entity); what reserves not
  finished hold and what members owe is of no lot (`PointsLiabilities::beyondLots`). Reports (ADR-0026) are put
  together by the module
  `reports` (`Contracts\ProgramReports`) from the contracts of the modules that keep the data, for the cabinet and the
  Management API (scope `reports`) alike, keeps one it put together `KEEP_SECONDS` for both and puts a merchant's
  together `PER_MINUTE` times a minute at most (`ReportsThrottled`, counted before); a module of data tells its figures
  by what other modules named them (the ledger's `accruedBy`/`reversedBy` by reference type) and never classifies them
  itself. A report's SQL multiplies amounts in `numeric` (an amount and a quantity the till takes are past bigint).
- Under RLS a condition reaches an index only if it is leakproof: `=`, `<`, `>=`, `^@` on a plain column are, `lower()`,
  `LIKE` and most functions are not. Search on a stored key (a generated column) with `^@` over a `text_pattern_ops`
  index (`members.last_name_key`); check plans with `EXPLAIN` as the app role, inside the tenant context.
- `Model::shouldBeStrict()` is on outside production: eager-load relations (`->load()`), no lazy loading.
- The cache unserializes no classes (`cache.serializable_classes = false`): cache plain values only (arrays of scalars,
  times as strings). Tests serialize the array store (`CACHE_ARRAY_SERIALIZE` in phpunit.xml), so an object put in the
  cache fails there as it would with the database or Redis store.

## Windows PowerShell 5.1 gotchas

- `Set-Content -Encoding utf8` / `Out-File` write a BOM, which breaks `declare(strict_types=1)` in PHP files.
  Write files with the editor tools or `[IO.File]::WriteAllText($path, $text, [Text.UTF8Encoding]::new($false))`.
- `Get-Content` without `-Encoding UTF8` reads a UTF-8 file without a BOM as Windows-1251: written back, every
  Cyrillic letter of it is garbage. Read with `-Encoding UTF8` (or `[IO.File]::ReadAllText`), or edit with the tools.
- `Start-Process -Wait` also waits for child processes (a started server never returns).
- Commands that pipe `Remove-Item` or pass it a path in a variable are blocked by the harness; use literal paths.
- In the Bash tool a heredoc with non-ASCII text (Russian, ₽, arrows) fails with "unexpected EOF", and `\\`
  in a heredoc may collapse to `\` (breaks composer.json); write such files with the Write/Edit tools.

## Database gotchas

- `migrate:fresh` drops tables but not functions: migrations `drop function if exists` before `create function`
  (`create or replace` cannot change a function's result type).
- The immutable columns of a table are the arguments of its `{table}_immutable_columns` trigger, which ignores names it
  does not know: to add one, drop the trigger and make it again with the whole list, and test every column.
- Runtime API tests: the request resets the tenant context, so count rows afterwards inside
  `tenantContext()->run($tenantId, ...)` (without it RLS returns zero rows and the assertion passes vacuously).

## Git

Do not commit or push unless asked. Commit messages end with the attribution lines from the system reminder.
