# 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 good: 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).
- 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, 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.
- 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.
- 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; 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`). 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` and
  `widgets`); 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.
- «Состояние системы» (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): 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).
- 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))`.
- `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.
