# TORAZ Backend — Implementation Decisions Ledger

This is the single decisions ledger for the TORAZ backend recovery.

- **Part 1** is the recovery package's `02_IMPLEMENTATION_DECISIONS.md`, copied without change.
- **Part 2** lists decisions approved by the project owner during the recovery, in the order they were given.
- **Part 3** lists technical choices made while reconstructing each batch. They are awaiting review and become approved only when the batch is approved.

When two entries disagree, the later approved entry in Part 2 wins, then Part 1, then Part 3.

All backend code written during this recovery is RECONSTRUCTED. None of it is recovered source.

---

## Part 1 — Recovery package decisions (verbatim copy)

Source: `02_IMPLEMENTATION_DECISIONS.md` from `TORAZ_BACKEND_RECOVERY_PACKAGE.zip`. The text between the two markers is byte-for-byte the supplied file.

<!-- BEGIN VERBATIM 02_IMPLEMENTATION_DECISIONS.md -->
# TORAZ BACKEND — RECOVERED IMPLEMENTATION DECISIONS

This document is the recovery ledger of decisions already reviewed during the previous TORAZ backend implementation.

## Status labels

- CONFIRMED: explicitly established during prior implementation/review.
- PRESERVE: do not casually change during recovery.
- VERIFY: check against reconstructed code before finalizing.
- GAP: do not invent; stop for review if required.

## Confirmed architecture

- Node.js
- JavaScript
- Express.js
- MongoDB
- Mongoose
- REST
- Socket.IO
- JWT
- dotenv
- secure upload handling
- VPS-compatible architecture

## Phase history to preserve

### Foundation
Central configuration, security middleware, error handling, response envelopes, health endpoint, database architecture.

### Authentication
User, OtpRequest, Session; secure OTP hashing/verification; attempts; resend throttling; JWT access tokens; refresh-session rotation and revocation; authenticated middleware.

OTP timing decision:
- frontend resend cooldown: 30 seconds
- server OTP validity: 5 minutes

Do not confuse these values.

### Profile
Profile is separate from User.
Photo records are separate from Profile.
No arbitrary profile photo URL writes.
No placeholder Profile.status.
Profile completion is derived.

### Photos
Secure image validation, magic bytes, JPEG/PNG/WEBP, dimensions, Sharp re-encoding, UUID filenames, ownership checks, primary-photo behavior, secure image serving.

### Discovery
Backend-authoritative eligibility.
Self exclusion.
Active-account requirement.
Compatibility based on stored product fields.
Bidirectional block exclusion.
Privacy enforcement.
No exact GPS exposure.
Safe unknown distance representation.
Actual frontend card fields previously verified: firstName, city, profession.
User-controlled regex must be escaped.

### Matching
Like uniqueness.
Canonical pair utility.
Reciprocal likes create one Match.
Transactions/race protection where multi-document consistency requires it.
Blocking enforced.
Super Like ledger and authoritative balance.

### Messaging
Conversation and Message persistence.
Only matched/authorized users can access.
JWT identity determines sender.
REST persistence before broadcast.
Socket.IO authentication and room authorization.
Fresh blocking check when sending.
Cursor pagination.
Idempotent mark-read.
Premium state is derived server-side.

### Safety
Centralized block service.
Report model/service.
Moderation events.
Report rate limiting.
Admin report management.
Block enforcement across discovery, matching, messaging and sockets.

### Verification
Corrected after security review.

Modes:
- real
- dev_simulation
- unavailable

Disabled provider must not auto-verify.
Simulation requires explicit non-production flag.
Production hard-block.
Real provider response must be authoritative/validated.
Do not retain unnecessary raw identity/biometric payloads.

### Premium
Entitlements are server-authoritative.
No client-side entitlement bypass.
Payment disabled until configured.
Payment simulation, if supported, must be explicitly enabled and impossible in production.
Super Likes remain ledger-based.
Boost expiration is server-side.
Messaging premium status derives from the correct participant.

### Settings / deletion
Privacy controls are distinct from profile privacy.
Sessions are server-authoritative.
Pause/visibility uses stored privacy state.
Deletion uses a 30-day scheduled purge.
Purge is idempotent.
Photos hard deleted from DB/disk.
Verification document removed.
Messages anonymized/tombstoned.
Other records are retained unless product contract requires deletion.
Purge uses external scheduling rather than an in-process timer.

### Admin
Admin authorization on every admin route.
Suspend/reinstate.
Verification management.
Reports.
Audit logs.

Admin dashboard:
12 KPI concepts.
Unsupported metrics must not be fabricated.

Real/derivable:
verification_backlog
open_safety_reports
moderation_alerts
total_members
new_today
active_users
online_now
messages_sent
super_likes

Not tracked:
gateway_retries
boost_triggers
mod_queue_sla

Recent activity must come from actual available data, not fabricated payment/boost history.

## Route count correction

Historical report said 57; later mechanical verification established 56 actual routes.

Final route count must always be generated mechanically from code.

## Postman

Previously specified:
- 56 positive requests
- 17 negative/security requests
- 73 total
- v2.1
- bearer access token
- OTP token extraction
- ID variables
- upload requests
- admin authorization negatives

The final collection must be generated/verified against actual reconstructed routes.

## Important testing history

Previous environment limitations included package-install/network problems and lack of live MongoDB/HTTP/Socket runtime validation.

Do not turn those historical limitations into false "passed" claims.

If tests are rerun successfully now, report the new actual results.

## Security correction history

A verification disabled-provider auto-success bug was identified and corrected through an explicit provider-gate design and pure tests.

Do not regress this behavior.

<!-- END VERBATIM 02_IMPLEMENTATION_DECISIONS.md -->

---

## Part 2 — Decisions approved during the recovery

### 2026-10-07 — Recovery 0 approved

Recovery 0 (`RECOVERY_BASELINE.md`, `RECOVERY_GAPS.md`, `IMPLEMENTATION_PLAN.md`) was reviewed and approved with these decisions.

| ID | Decision | Closes |
|---|---|---|
| AD-01 | CommonJS throughout. Module systems are never mixed. | Gap D23 (module system) |
| AD-02 | `docs/IMPLEMENTATION_DECISIONS.md` is created at the start of Recovery 1 and is the single decisions ledger. It holds a copy of the recovery package's decisions and every later approved decision. | Gap C10; plan item P2 |
| AD-03 | Product-rule ASK gaps are not invented or resolved ahead of time. Only gaps required by the current batch are resolved. | — |
| AD-04 | The frontend stays completely untouched. Its 178-file checksum manifest is re-verified after every batch. | — |
| AD-05 | All new backend code is treated and described as RECONSTRUCTED, never recovered. | — |
| AD-06 | One final search for the lost Postman collection, route inventory, backend ZIP or Git repository is made before Recovery 1 coding. Recovery 1 is not delayed if nothing is found. | — |
| AD-07 | Git is the primary persistent backup if available. After every completed batch a ZIP of the entire `backend/` directory is created as a secondary backup. | Gap E4; plan item P4 |
| AD-08 | A runtime or database test is never reported as passed unless it actually ran. While npm or MongoDB access is blocked, those tests are reported as "not executed". | — |
| AD-09 | No real credentials, API keys, phone numbers or secrets appear anywhere. | — |
| AD-10 | After these setup decisions, Recovery 1 only. Recovery 2 does not begin. | — |
| AD-11 | At the end of Recovery 1: run every test that is actually possible, verify the frontend checksum, create the backend ZIP, give the complete report, and stop for review. | — |

**Outcome of AD-06 (search made 2026-10-07).** Nothing was found. Places searched: the whole workspace filesystem by file name; the upload folders; archives nested inside the frontend ZIP; the owner's published artifacts (none exist); GitHub (no account is linked to the session); the linked computer (not connected on four attempts across the day). Gaps B1 and B9 therefore stay open and are handled as `RECOVERY_GAPS.md` describes.

**Plan items not yet explicitly confirmed.** The plan's P1 (design documents grow one module section per batch, written before that batch's models), P3 (the `Block` model and read-only blocking policy are built in Recovery 4) and P5 (provisional numbers are named configuration values listed in each batch report) were proposed in `IMPLEMENTATION_PLAN.md` §4. P5 is being followed from Recovery 1 because it only adds reporting. P1 needs a yes or no before Recovery 2; P3 before Recovery 4.

---

## Part 3 — Technical choices made during reconstruction (awaiting review)

These are choices the surviving record does not dictate. They are RECONSTRUCTED, not recovered. Each stays provisional until the batch that introduced it is approved; an approved one is then referenced from Part 2.

### Recovery 1 — Foundation (written 2026-10-07, awaiting review)

| ID | Choice | Reason |
|---|---|---|
| R1-01 | `package.json` declares Express `^5.1.0`. The code avoids everything that differs between Express 4 and 5: `req.query` is never modified, the query parser is set to `simple`, and no wildcard route patterns are used. | The original Express version is unknown. Version 5 is the current line. |
| R1-02 | `NODE_ENV` has no default. Startup fails if it is missing or not one of `development`, `test`, `production`. | A server that silently starts in development mode could expose development-only behaviour in production. |
| R1-03 | Configuration is validated by a plain JavaScript function (`src/config/buildConfig.js`), not by Zod. Request validation uses Zod from Recovery 2 through `src/middlewares/validate.js`, which depends only on the `safeParse` contract. Zod is added to `package.json` with the first validator. | Configuration must be checked before any package is trusted, and this keeps it testable with Node alone. One validation library is still used for all external input (master prompt §28). |
| R1-04 | A validation failure answers HTTP 400. | The historical status code is unknown. |
| R1-05 | `GET /api/health` is the only health route. It answers 200 when the database is connected and 503 when it is not. The data fields are `status`, `database`, `timestamp` and nothing else. | Master prompt §3; one route distinguishes "alive" from "ready" without adding to the route count. |
| R1-06 | A request from an origin not listed in `FRONTEND_URL` is refused with 403 before routing. A request with no `Origin` header is served and receives no CORS headers. | Master prompt §27. Postman and health probes send no `Origin`. |
| R1-07 | Input guards reject, with 400, any body, query or route parameter containing a key that starts with `$`, contains `.`, or is `__proto__`, `constructor` or `prototype`; and any repeated or nested query parameter. Mongoose's `sanitizeFilter` is not enabled. | Rejecting is safer than cleaning, and the frontend never sends such keys. `sanitizeFilter` would also rewrite operators written in our own queries. |
| R1-08 | The request ID is always generated on the server. A client-sent `X-Request-Id` is ignored. | Prevents log injection. |
| R1-09 | HTTP tests use Node's built-in `http` and `fetch`, so `supertest` is not a dependency. `mongodb-memory-server` is not added yet; the database test harness arrives with the first model in Recovery 2. | Fewer packages (master prompt §26). This departs from `IMPLEMENTATION_PLAN.md` §2, which listed `supertest`. |
| R1-10 | Logging is a small in-house JSON-lines logger. Every field passes through key-name redaction covering secrets, tokens, passwords, authorization and cookie headers, OTP values, API keys, credentials, signatures, phone numbers, and the exact keys `key`, `code`, `text`, `body`, `uri`, `jwt`. Connection strings are stripped from error text. | Master prompt §8, §18, §26. |
| R1-11 | The server listens on `HOST`, default `127.0.0.1`. | The deployment target is a VPS behind Nginx; binding to loopback keeps the app off the public interface by default. |
| R1-12 | Any error that is not an application error answers `Internal server error`. Mongoose cast and validation errors answer 400 without field names; a duplicate-key error answers 409 without naming the key. | Master prompt §29. |
| R1-13 | `autoIndex` is on outside production. An explicit index-build step is added with the first models in Recovery 2. | Unique indexes must exist in development and tests; building them at every production start is avoided. |
| R1-14 | The ESLint configuration imports no plugin. It forbids reading the process environment anywhere except `src/config/index.js`. A unit test enforces the same rule without ESLint. | Master prompt §1; no extra dependency. |
| R1-15 | The upload variables from master prompt §30 (`UPLOAD_DIR`, `MAX_FILE_SIZE_MB`, `MAX_IMAGE_WIDTH`, `MAX_IMAGE_HEIGHT`) are not yet in `.env.example` or the configuration. | Their values depend on gap C2, which belongs to Recovery 3 (AD-03). |
| R1-16 | Six variables were added that master prompt §30 does not list: `HOST`, `TRUST_PROXY`, `BODY_LIMIT`, `REQUEST_TIMEOUT_MS`, `RATE_LIMIT_WINDOW_MS`, `RATE_LIMIT_MAX`. | Needed for the reverse-proxy, body-size, timeout and rate-limit requirements in master prompt §26. |
| R1-17 | When a provider's `*_ENABLED` flag is `false`, its URL and credentials are ignored even if present. | A half-filled `.env` cannot switch a provider on (master prompt §31, §35). |

#### Provisional values introduced in Recovery 1 (plan item P5)

None of these is a product rule. Each is a named setting or constant and can be changed without touching logic.

| Value | Setting | Where |
|---|---|---|
| Minimum JWT secret length in production: 32 characters | constant `MIN_SECRET_LENGTH_PRODUCTION` | `src/config/buildConfig.js` |
| JSON and form body limit: 100 kb | `BODY_LIMIT` | `.env` |
| Request timeout: 30 s | `REQUEST_TIMEOUT_MS` | `.env` |
| Global rate limit: 300 requests per 15 minutes per IP | `RATE_LIMIT_MAX`, `RATE_LIMIT_WINDOW_MS` | `.env` |
| Database server-selection timeout: 10 s | constant | `src/config/database.js` |
| Shutdown grace period: 10 s | constant | `src/server.js` |
| CORS preflight cache: 600 s | option | `src/middlewares/corsOptions.js` |
| Dependency version ranges | `dependencies` | `package.json` |

The dependency ranges were written without access to the npm registry. They have never been resolved by an install, and there is no lockfile. The first successful `npm install` will pin them; until then they are unverified.

---

## Part 2 (continued) — Decisions approved during the recovery

### 2026-10-07 — Recovery 1 approved; Recovery 2 decisions

| ID | Decision | Closes |
|---|---|---|
| AD-12 | Recovery 1 is approved as reconstructed foundation code. R1-01 to R1-17 are accepted **provisionally**, subject to later runtime validation. They remain reconstruction decisions, not recovered historical behaviour. | — |
| AD-13 | No fake lockfile is created while npm installation is unavailable. | — |
| AD-14 | Plan item P1 is approved. Before a batch creates its models, the matching sections of `FRONTEND_BACKEND_FIELD_MAPPING.md`, `API_CONTRACT.md` and `DATABASE_DESIGN.md` are written, reviewed against the actual frontend contract, and only then implemented. | Plan item P1 |
| AD-15 | Gap D13 is settled as an **approved reconstruction**: the first administrator is created by a secure one-time command-line mechanism. No public admin creation exists, and no client-supplied role can create an administrator. This is a reconstructed decision, not recovered behaviour. The exact command and safeguards are designed before implementation. | Gap D13 |
| AD-16 | All other product ASK gaps stay unresolved unless Recovery 2 genuinely requires them. Recovery 3 is not started. | — |

Reconfirmed with this approval: CommonJS throughout (AD-01); the frontend stays untouched and its 178 checksums must keep matching (AD-04); Git and ZIP backup after every completed batch (AD-07); no runtime or database test is described as passed unless it ran (AD-08); no secrets or real credentials (AD-09); product ASK gaps are not invented (AD-03).

**Outcome of AD-15.** The command and its safeguards are specified in `API_CONTRACT.md` §4.1 and were written before the code. Summary: it promotes an account that already exists and has verified its number through the normal OTP flow; it refuses if any administrator exists; it changes nothing without `--confirm`; it reverses itself if two runs collide; it revokes the account's sessions; it never prints the full number. The service behind it is not part of the HTTP object graph.

---

## Part 3 (continued) — Technical choices made during reconstruction (awaiting review)

### Recovery 2 — Authentication (written 2026-10-07, awaiting review)

Gaps handled in this batch, each with the default recorded for it in `RECOVERY_GAPS.md`: C3, C4, C5, C6, D7, D20, and D13 by decision AD-15.

| ID | Choice | Reason |
|---|---|---|
| R2-01 | Services never call Mongoose. They call stores (`src/repositories/`) with a small set of methods. There is one MongoDB implementation and one in-memory implementation for tests, and one shared contract test suite written to run against both. | Keeps business rules testable without a database, and gives a way to prove later that the in-memory stores and the real ones agree. |
| R2-02 | The frontend's `requestId` is a random 32-character hexadecimal string, not a database ID. | An unguessable handle that reveals nothing about the database. |
| R2-03 | An OTP is stored as HMAC-SHA-256 of `requestId:code`, under a key derived with HKDF from `JWT_REFRESH_SECRET`. | Master prompt §8 ("hashed before storage"). A six-digit code has too little entropy for a plain hash; a keyed hash bound to the request cannot be brute-forced from a database copy or replayed on another request. No extra secret needs configuring. |
| R2-04 | The OTP policy values are constants, not environment variables: validity 300 s and cooldown 30 s (both confirmed by the recovery record), 5 verification attempts and 5 resends (from the frontend mock; gap D7). | These are decisions, not deployment settings. An environment variable would invite confusing the two confirmed values. |
| R2-05 | A resend issues a new code, restarts the five minutes and resets the attempt count. | Master prompt §8. The frontend mock keeps the same code, which a real system should not. |
| R2-06 | A new request for a number invalidates that number's earlier request. The database allows at most one active request per number (partial unique index on an `active` flag). | Master prompt §8 ("invalidation of previous active OTP"). The index is what makes two simultaneous requests send one SMS. |
| R2-07 | Per number: at most 5 codes an hour and 10 a day. Per IP: 30 requests per 15 minutes across request-otp, verify-otp, resend-otp and refresh. All four numbers are provisional and configurable. | Master prompt §8 requires both kinds of limit and gives no numbers. |
| R2-08 | A code is delivered by SMS when `SMS_ENABLED=true`. `channel: "whatsapp"` is accepted and delivered by SMS (gap D20). With no delivery method, request-otp and resend-otp answer 503. `OTP_DEV_FIXED_CODE` gives a fixed code for local development; configuration is refused if it is set in production, and the code is never returned by the API (gap D7). | Master prompt §8 allows a development-only bypass behind explicit configuration, never in production. |
| R2-09 | Only country code `+91` is accepted. | The frontend offers no other. |
| R2-10 | `expiresInSeconds` in the request-otp and resend-otp responses is the 30-second resend cooldown (gap C6). | That is what the frontend uses the field for. |
| R2-11 | verify-otp failures: 400 `invalid_code`, 410 `expired`, 429 `too_many_attempts`, in `errors.reason` (gap C5). `isNewUser` means registration has not been completed. The account carries `registrationCompletedAt`; profile registration in Recovery 3 will set it. | The three reasons are the frontend's own. Master prompt §6 puts the registration state on the account. This refines gap D4, which had proposed the marker on the profile. |
| R2-12 | Account status values are `active`, `suspended`, `deleted`; roles are `USER`, `ADMIN` (gap C3). An account that is not active cannot sign in (403 at verify-otp). On an authenticated request a suspended account gets 403 and any other non-active account 401. | Master prompt §5. Whether a deleted account's number may register again is not decided here (gaps B8, D16). |
| R2-13 | Tokens are HS256 JWTs made with `jsonwebtoken`. Access and refresh tokens use different secrets and a different `typ` claim. A token carries the account ID, the session ID and nothing else. Role and status are read from the database on every request. | Master prompt §9: "contains only necessary claims". Reading the session and account each time makes logout, revocation, suspension and role changes immediate. |
| R2-14 | The refresh token is a JWT in an HttpOnly cookie named `toraz_refresh`, limited to the path `/api/auth`. Only its SHA-256 is stored. Each refresh rotates it by compare-and-swap. Presenting a token that is not the session's current one revokes the session. | Master prompt §9; R06. Revoking on reuse is what ends a session whose token was stolen. Consequence: two refresh calls made at the same instant with the same token leave the session revoked, so a client must not refresh in parallel. |
| R2-15 | Logout always answers 200. It revokes the session named by a valid access token or, failing that, a valid refresh cookie. | A sign-out that can fail is worse than one that is a no-op. |
| R2-16 | An account may have several sessions. A session's expiry moves forward on each rotation. Expired sessions and old OTP requests are removed by TTL indexes. | Master prompt §9 ("multiple sessions/devices"). |
| R2-17 | The refresh cookie is read by a small in-house function. `cookie-parser` is not a dependency. | One cookie is read. This departs from `IMPLEMENTATION_PLAN.md` §2, which listed `cookie-parser`. |
| R2-18 | The SMS adapter's request body and headers are a **placeholder**. No provider has been named and no provider documentation exists. The adapter has a timeout (10 s, provisional), makes one attempt with no automatic retry, and never logs the key, the number or the code. | Master prompt §10. A retry of a request that had in fact been accepted would text the user twice; the user's own resend, with its cooldown and caps, is the retry. |
| R2-19 | First administrator: `npm run admin:create-first -- --country-code +91 --phone <10 digits> [--confirm]`. Safeguards as in `API_CONTRACT.md` §4.1. The service behind it is built only by the script and is absent from the HTTP container; tests enforce that. | Decision AD-15. |
| R2-20 | `npm run db:indexes` creates the indexes the models declare and never drops one. | Completes R1-13. |
| R2-21 | `jsonwebtoken` is injected into the token service. Unit tests use an HS256 stand-in built on Node's crypto; HTTP and database tests use the real package. | The package cannot be installed here. Passing unit tests show the token service's logic is right, not that it works with the real package. |
| R2-22 | No IP address or location is stored. Per-IP limits are held in memory. | Less personal data; gap D12 has no approved location source. |
| R2-23 | A masked phone number shows the first five digits and bullets for the rest. | The frontend's own masking rule. |

#### Provisional values introduced in Recovery 2 (plan item P5)

| Value | Setting | Where |
|---|---|---|
| Codes per number: 5 per hour, 10 per day | `OTP_MAX_SENDS_PER_PHONE_PER_HOUR`, `OTP_MAX_SENDS_PER_PHONE_PER_DAY` | `.env` |
| Auth routes per IP: 30 per 15 minutes | `AUTH_RATE_LIMIT_MAX`, `AUTH_RATE_LIMIT_WINDOW_MS` | `.env` |
| SMS provider timeout: 10 s | `SMS_TIMEOUT_MS` | `.env` |
| OTP request record kept 25 hours after its last send | constant | `src/services/auth.service.js` |
| Stored user agent: at most 256 characters | constant | `src/services/auth.service.js` |
| Longest token accepted: 2,048 characters | constant | `src/services/token.service.js` |
| Refresh cookie name `toraz_refresh`, path `/api/auth` | constants | `src/config/buildConfig.js` |
| Version ranges for `jsonwebtoken`, `zod`, `mongodb-memory-server` | `dependencies`, `devDependencies` | `package.json` |

The version ranges were written without access to the npm registry and have never been resolved by an install. There is still no lockfile.

#### Questions Recovery 2 raises but does not answer

| Question | Where it bites |
|---|---|
| How is a second administrator created, and how is one removed? | No surviving source defines either. Nothing is built. |
| Can a deleted account's number register again? | Gaps B8 and D16, Recovery 9. Today a non-active account is refused at sign-in. |
| What is the SMS provider and its API? | The adapter is a placeholder until this is known. |
| Should the first-administrator command write an audit record? | `AdminAuditLog` arrives in Recovery 9. Today the command writes one log line. |

---

## Part 2 (continued) — Decisions approved during the recovery

### 2026-10-08 — Recovery 2 approved; Recovery 3 decisions

| ID | Decision | Closes |
|---|---|---|
| AD-17 | Recovery 2 is approved as **implementation-complete but runtime-unverified**. No claim may be made that MongoDB, the real `jsonwebtoken`, Express, Zod 4, HTTP or server-start tests passed. Every NOT EXECUTED label is preserved until a real dependency and runtime environment is available. Recovery 2 is not redone, and the historical 14 phases are not restarted. | — |
| AD-18 | **Gap C2:** the maximum original photo upload size is **10 MB**, held as a named configuration value, not a magic number. This does not change the frontend. Magic-byte validation, decodeability, dimension checks and secure re-encoding are still enforced. | Gap C2 |
| AD-19 | **Gap C8:** when a profile-level and a settings-level privacy control conflict, **the more restrictive one wins**. The effective restriction is enforced on the server and documented before implementation. | Gap C8 |
| AD-20 | The OTP and authentication limits are **provisionally approved**: 5 sends per number per hour, 10 per day, 30 authentication requests per IP per 15 minutes. They stay named configuration values and are labelled as reconstructed provisional policy, not recovered historical requirements. | Recovery 2 provisional values |
| AD-21 | Recovery 3 scope is Profile and Photos only. Design sections first, checked against the frontend; no unrelated ASK gap is resolved silently; the frontend is not modified; Recovery 4 is not started. | — |

---

## Part 3 (continued) — Technical choices made during reconstruction (awaiting review)

### Recovery 3 — Profile and Photos (written 2026-10-08, awaiting review)

Gaps handled in this batch: C2 and C8 by decisions AD-18 and AD-19; C9 (settled); D1, D4, D5 and D6 with the defaults recorded for them in `RECOVERY_GAPS.md`. No other ASK gap was used.

| ID | Choice | Reason |
|---|---|---|
| R3-01 | The 46 profile fields are declared once, in `src/config/profileFields.js`. The request rules, the Mongoose schema and the serializer are all generated from that list. A test compares it mechanically with the frontend's `registration.ts`: the same names in the same order, every length and count limit, every message. | A field cannot be accepted by one layer and forgotten by another, and a difference from the frontend fails a test. |
| R3-02 | The option lists are copied from the frontend's `registration-options.ts` by `scripts/generate-profile-options.js`, which runs the file's array literals in an empty sandbox. The generated file records the source's SHA-256; a test fails if the frontend file changes. | Gap D5. Not copied by hand. |
| R3-03 | The field rules are plain functions (`src/validators/profileRules.js`). The Zod schemas wrap them with one transform per field. | Every rule can be tested with Node alone; Zod remains the validation layer of the routes. The schemas gave identical results under the Zod 3 API and the Zod 4.0 API (see the report). |
| R3-04 | Routes: `GET`, `POST` (register), `PUT` (update) on `/api/profile/me`, and `PUT /api/profile/me/draft`. Photos on `/api/profile/me/photos` (MP §11) and images on `GET /api/photos/:photoId`. | MP §40 names the capabilities but no profile paths; `/me` follows MP §11's photo paths. No path carries an account or profile ID, so no route can address another account. |
| R3-05 | `""` means "not set" for optional text and choice fields and is stored as absent. Update is a full replacement: an optional field left out is cleared. A draft changes only the fields it sends. | How the frontend's selects, chips and Edit Profile actually send data. |
| R3-06 | A draft applies shape rules only (types, options, maximums), but a date of birth in a draft must still be a real date of someone 18 to 99. Consents are never recorded from a draft. | Gap D4. A draft should not be able to store data that could never be registered. |
| R3-07 | Age is calculated on the server's date in UTC, with the frontend's rule (a year counts once the birthday is reached; 29 February birthdays count from 1 March). The date of birth is stored as UTC midnight. | One answer regardless of server time zone. Consequence: for a user in India the eighteenth birthday is recognised at 05:30 local time. |
| R3-08 | `country`, `state` and `city` have no maximum in the frontend; the backend caps them at 60, 80 and 80 characters. Multi-choice lists without a frontend maximum are capped at the size of their option list (which the no-duplicates rule implies anyway). | MP §6 requires length validation. |
| R3-09 | Two registration markers: `Profile.registeredAt` guards registration (one conditional write), `User.registrationCompletedAt` is the account state reported as `isNewUser`. Registration writes the profile, then the account; a later attempt repairs an unmarked account. | Refines gap D4 and ledger R2-11. Two simultaneous registrations cannot both succeed, and no inconsistent state can persist. |
| R3-10 | Drafts and registration both use one conditional upsert on `{ userId, registeredAt: null }`. On a duplicate key the write is retried once without upsert. | Without the retry, two simultaneous first saves would make one of them look like "already registered". |
| R3-11 | Consents are stored as the time of first acceptance (`consents.*At`), set at registration and kept unchanged by updates. The API returns them as `true`. | The frontend sends booleans; a date is the useful record of consent. |
| R3-12 | `GET /api/profile/me` returns the full phone number to its owner. | The frontend's edit form requires all ten digits to save. Everywhere else the number stays masked or absent. |
| R3-13 | `profileCompletion` (0–100) is added to `GET /api/profile/me`, computed from the registration screen's own 15 progress checks. | MP §7 requires profile completion; the frontend's progress bar defines what "complete" means. Extra fields are harmless to the frontend type. |
| R3-14 | Five photos per account are enforced by five slots and a unique index on `(userId, slot)`; one primary by a partial unique index. The service retries on a collision with fresh state (at most 10 attempts). A new photo is primary whenever the account has no primary at that moment. | Limits that hold under simultaneous requests, without transactions. |
| R3-15 | Deleting the primary promotes the oldest remaining photo. A registered profile cannot delete its last photo (409 `last_photo`); a draft can. Two simultaneous deletions of a registered profile's last two photos can both succeed; this is a known, recoverable limitation. | The frontend's `remove()` promotes `next[0]`; Edit Profile refuses to save without a photo. |
| R3-16 | Photo IDs are 12 random bytes, not ObjectIds made from a timestamp and a counter. | Photo URLs must not be guessable or enumerable. |
| R3-17 | Upload pipeline: per-account rate limit, then multer (memory storage, one file in field `photo`, no other parts, size counted while streaming), then the photo count, then sharp. The signature decides the format; the declared type and the extension must agree with it; the header is read with no pixel limit, the dimensions checked, then the image decoded with a pixel limit of `MAX_IMAGE_WIDTH × MAX_IMAGE_HEIGHT`, rotated upright, scaled to fit 2048, flattened onto white and written as JPEG quality 85 with no metadata. | R01 §5 and MP §11. The original upload never touches the disk. Reading the header without a pixel limit lets the dimension check answer with a clear message, while the decode still refuses decompression bombs. |
| R3-18 | Files live at `UPLOAD_DIR/profiles/<userId>/<uuid>.jpg`, written to a temporary name and renamed, folders 0750 and files 0640. Every key is checked against that exact pattern and must resolve inside `UPLOAD_DIR`. Upload writes the file then the record (removing the file if the record fails); delete removes the record then the file (a failure to remove is logged). | R01 §5 path safety. A record never points to a missing file because of our own ordering. |
| R3-19 | Images are served only by `GET /api/photos/:photoId`, with `Cache-Control: private, max-age=3600`, `nosniff` and `Content-Disposition: inline`. Every refusal is the same 404. | R01 §5 "secure serving". A tested rule forbids static serving anywhere. |
| R3-20 | Who may see another member's photo is decided by one function, `canViewProfileOf`, in `src/services/visibility.service.js`: the owner always; anyone else only if the owner is active, registered and visible in discovery. Recovery 4 adds blocks and matches there, Recovery 9 pause. | One policy function, so later batches extend it rather than duplicate it. |
| R3-21 | Effective privacy is one function, `effectivePrivacy()`. An absent setting imposes no restriction. The public view of a profile is built only by `toPublicProfile()`, from that function: first name, age (if allowed), city, profession, dating intention (unless hidden from non-matches), bio, interests, vibe tags, photos. | Decision AD-19 and `API_CONTRACT.md` §7. |
| R3-22 | `sharp` and `multer` are loaded only in `src/server.js` and injected through the container, like `jsonwebtoken`. Tests replace them with stand-ins; the real sharp is tested separately; the real multer only in HTTP tests. | The container stays free of npm imports, so the whole application graph can be built in a test. |
| R3-23 | `createRateLimiter` accepts a `keyGenerator`; the upload limit counts per account (`accountKey`). | MP §26 requires rate limiting and upload validation but gives no upload limit. Per account, because uploads are authenticated. |
| R3-24 | `sharp.cache(false)` at start-up. | Every uploaded image is different; the libvips cache would only keep members' pixels in memory. |

#### Provisional values introduced in Recovery 3 (plan item P5)

| Value | Setting | Status |
|---|---|---|
| Maximum upload: 10 MB | `MAX_FILE_SIZE_MB` | **Approved** (AD-18) |
| Maximum width and height: 8000 px each | `MAX_IMAGE_WIDTH`, `MAX_IMAGE_HEIGHT` | Provisional; names from MP §30 |
| Minimum width and height: 320 px | `MIN_IMAGE_DIMENSION` | Provisional |
| Longest side after re-encoding: 2048 px | `PHOTO_OUTPUT_MAX_DIMENSION` | Provisional |
| Uploads per account: 20 per hour | `PHOTO_UPLOAD_RATE_LIMIT_MAX`, `PHOTO_UPLOAD_RATE_LIMIT_WINDOW_MS` | Provisional |
| Upload folder: `uploads` | `UPLOAD_DIR` | Provisional |
| JPEG quality 85; output type `image/jpeg` | constants (`PHOTO_POLICY`) | Provisional |
| Photos per account: 5 | constant (`PHOTO_POLICY`) | From the frontend (`maxPhotos`) |
| Photo cache lifetime in the browser: 1 hour, private | constant | Provisional, `src/controllers/photo.controller.js` |
| Length caps for `country`, `state`, `city`: 60, 80, 80 | constants | Provisional, `src/config/profileFields.js` |
| Version ranges for `multer` (^2.0.2) and `sharp` (^0.35.4) | `dependencies` | `package.json` |

The `sharp` range matches the version found on this machine and used for the image tests. The `multer` range has never been resolved by an install. There is still no lockfile.

#### Questions Recovery 3 raises but does not answer

| Question | Where it bites |
|---|---|
| How will a browser fetch photos? An `<img>` element cannot send a bearer token, and Helmet's `Cross-Origin-Resource-Policy: same-origin` blocks cross-site images. | Frontend integration (gap D6). Nothing is changed until it is decided. |
| What are the default values of the Settings privacy switches? The frontend mock starts "Intent & Dietary Privacy" on, which under AD-19 would hide every intention from non-matches by default. | Recovery 9. |
| Should a profile ever be deleted or reset to draft? | Recovery 9 (gaps B8, D16). Nothing deletes a profile today. |
| Is the profile's first name always the first word of the full name? | Recovery 4 (`MemberCard.firstName`). The public view uses the first word for now, as the frontend's preview does. |

---

## Part 2 (continued) — Decisions approved during the recovery

### 2026-10-09 — Recovery 3 approved; Recovery 4 product decisions

Recovery 1–3 are approved as reconstructed work, subject to their documented runtime-validation limits. The decisions below answer `docs/reports/RECOVERY_4_DECISION_REQUEST.md`. They are **new product decisions for the reconstructed backend**, not recovered historical rules.

| ID | Decision | Closes |
|---|---|---|
| AD-22 | **Gap B3 (Q1):** a member receives **3 Super Likes when profile registration completes successfully**, not at account creation. The grant is a unique ledger event, so retries and simultaneous requests cannot grant it twice. A Super Like with an insufficient balance fails with **409 `no_super_likes`** and is never turned into a normal like. Withdrawing a Super Like refunds nothing. The ledger is authoritative; clients cannot supply or change a balance. Inspired by the frontend mock's starting value; not a recovered rule. | Gap B3 |
| AD-23 | **Gap B7 (Q2), strict:** `interestedIn: women` admits `gender: woman`; `men` admits `man`; `everyone` admits every gender value. Eligibility is mutual: each member's `interestedIn` must admit the other's `gender`. No new gender categories or preferences. Consequence, documented on purpose: a member whose gender is `non_binary`, `self_describe` or `prefer_not_to_say` is shown only to members who chose `everyone`. | Gap B7 |
| AD-24 | **Gap B6 (Q3):** unknown distance is the sentinel **`-1`**. A distance filter **includes** members whose distance is unknown, as the surviving mock does. Distances are never fabricated or inferred from city names. The frontend currently renders "-1 km away"; the frontend is not changed in this batch. | Gap B6 |
| AD-25 | **Q4:** until Recovery 5 provides real presence, `onlineOnly` is **ignored** for filtering and every card has `isOnline: false`. Recovery 5 must switch the filter on. | Gap D24 |
| AD-26 | **Q5:** a member who hides their exact age appears with **`age: null`**, as in the Recovery 3 privacy contract (AD-19). No `-1`, no estimated age. The mismatch with the frontend's numeric `MemberCard.age` is left for frontend integration. | Gap D25 |
| AD-27 | **Gap B2 (Q6):** all eight details approved. (1) A pass hides the member from the caller's discovery and Liked-you list, and does not delete the other member's like. (2) Passing someone the caller liked withdraws that like when no Match exists. (3) A pass or like withdrawal after a Match is refused with 409 `already_matched` and changes nothing. (4) A like or Super Like on a passed member removes the pass. (5) Repeating an operation is idempotent: it returns the current state and creates nothing. (6) Pass revocation and like withdrawal are backend-only routes. (7) No refund for a withdrawn Super Like. (8) `pending` is never returned. The transitions must be atomic under concurrency. No unmatching or conversation deletion is invented. | Gap B2 |
| AD-28 | Recovery 4 scope: discovery, pass and like operations, mutual matching, Super Like ledger operations, and the read-only Block policy (plan item P3). Recovery 5 is not started. | — |

---

## Part 3 (continued) — Technical choices made during reconstruction (awaiting review)

### Recovery 4 — Discovery and Matching (written 2026-10-09, awaiting review)

Product decisions applied: AD-22 to AD-27. Defaults applied: D1, D2, D19; plan item P3 (read-only Block policy).

| ID | Choice | Reason |
|---|---|---|
| R4-01 | A pass is stored in the `Like` model, as `type: "pass"`: one record per member and direction, holding a like, a Super Like or a pass. No `Pass` model. | R04 lists the models and says to add only those the recovered design justifies. AD-27 makes a like and a pass to the same person mutually exclusive, so one record per direction enforces it with a unique index instead of coordination. |
| R4-02 | A Match is made by **sealing** both like records with the pair's Match ID, each by one conditional update, then inserting the Match. A failed second seal undoes the first. Sealed records can no longer be passed or withdrawn. No multi-document transaction is used. | R01 asks for transaction-safe matching "where supported". This design is atomic on a standalone MongoDB and on a replica set alike, and every interleaving is tested on the in-memory stores. |
| R4-03 | The Match ID is derived from the pair (first 24 hex characters of SHA-256 of `toraz:match:<userA>:<userB>`). It is never returned to a client. | Concurrent attempts to make the same Match must agree on its ID for the seals to be idempotent. |
| R4-04 | Ledger entries carry `seq` and `balanceAfter`; unique indexes on `(userId, seq)` and `(userId, reason, referenceId)`; at most 10 retries on a collision. | No overspending and no double events without transactions (section 5.5 of the database design). |
| R4-05 | Each Super Like attempt debits under its own key (`<record ID>:v<version>:<random>`) and writes the record only if it has not changed since it was read. An attempt that loses that race writes a **reversal** entry (reason `super_like_reversal`) for its own debit. | Net exactly one debit per Super Like, with an auditable trail. The reversal reason is a technical code, not a product rule; it never refunds a Super Like that was made. |
| R4-06 | The registration grant is appended after the account is marked complete. The 409 repeat-registration path and the repair path call it again, harmlessly. | AD-22; a failure between the two writes is repaired by the next attempt. |
| R4-07 | **Turning an existing like into a Super Like costs one Super Like.** A repeat Super Like, or a Super Like on a match, costs nothing. | The member asked for a Super Like on that person; it is shown as one. **Flagged for review:** AD-22 does not say whether upgrading a like is chargeable. |
| R4-08 | Discovery and every matching route require the caller's own profile to be registered: 409 `profile_not_registered` otherwise. | The frontend reaches these screens only after registration; an unregistered account has no gender or preference to apply. |
| R4-09 | Who may be liked, Super Liked or passed: active, registered, no block either way, mutually compatible, and visible in discovery **or** someone who has liked the caller. Otherwise 404, the same as a missing member. | Discovery eligibility (AD-23) applies to actions, so a profile URL cannot be used to like someone discovery would never show. Someone who chose to like the caller may be answered even if hidden. |
| R4-10 | One member's card (`GET /api/discovery/members/:memberId`) and photos use one policy: active, registered, no block, and visible or has liked the viewer. Compatibility does not apply. | A match must be able to open their match's profile; Liked-you entries must open. |
| R4-11 | Liked-you lists members who liked the caller, unanswered, not passed or liked by the caller, active, registered and unblocked. Compatibility and visibility do not filter it. | Those members chose to reach the caller. |
| R4-12 | **While an age filter is active, members who hide their exact age are left out of discovery.** | Filtering on a hidden age would let repeated searches reveal it (AD-26). The frontend does not send age filters today. |
| R4-13 | Search: trimmed, at most 60 characters, every regular-expression character escaped, case-insensitive literal substring over the first word of `fullName`, `city` and `profession`, as the mock does. Star sign and interests (mentioned by the input's placeholder) are not searched. | MP §6 and R02: user-controlled regex must be escaped. Searching only public fields means search cannot reveal private ones. |
| R4-14 | Pagination: `page` 1–1000 and `limit` 1–50 (default 20); `{ page, limit, hasMore }`; no total. Order: most recent sign-in first, then account ID. | MP §12 requires pagination; a total count would reveal the size of the eligible pool. |
| R4-15 | Cards: a member without a photo is not shown; `profession` is `""` when unset; `datingIntentionLabel` is `""` when withheld; `sharedInterests` is the overlap; `compatibilityPercent` and `lastActiveLabel` are omitted; `isVerified` is `false` until Recovery 7. | No fabricated data (gap D19, AD-24 to AD-26). |
| R4-16 | The path parameter is `:memberId`, the frontend's own name (`like(memberId)`), rather than MP §14's `:userId`. | The Recovery 2 rule "no validator reads an account ID from a request" stays strict; `memberId` always names the other member, never the caller. |
| R4-17 | `GET /api/matching/super-likes/balance` (backend only) and `superLikesRemaining` in the Super Like response. | MP §15 asks for balance checking; `PremiumEntitlement` is Recovery 8. |
| R4-18 | Matching writes share a per-account rate limit of 120 per 15 minutes. | MP §26 requires rate limiting; no number is recorded. |
| R4-19 | The `Block` store has a `create` method used only by tests until Recovery 6; no route reaches it. | P3: Recovery 4 reads blocks; the block routes are Recovery 6. |
| R4-20 | Exclusion lists (own decisions, matches, blocks) are read first and passed to the query as `$nin`; Matches and Liked-you are filtered in memory, then paginated. | Simple and correct at launch scale. **Known limit:** a member with tens of thousands of decisions needs a different query plan. |
| R4-21 | Acting on oneself is 400 `{ reason: "self" }`; an ineligible or missing member is 404 with one message. | A caller cannot tell "hidden" from "does not exist". |
| R4-22 | `featured` is the first recommended member, or 404 when nobody is eligible. | The mock returns the first member. |

#### Provisional values introduced in Recovery 4

| Value | Setting | Status |
|---|---|---|
| 3 Super Likes at registration completion | `MATCHING_POLICY.initialSuperLikeGrant` | **Approved** (AD-22) |
| Unknown distance `-1` | `MATCHING_POLICY.unknownDistanceKm` | **Approved** (AD-24) |
| Matching writes: 120 per 15 minutes per account | `MATCHING_RATE_LIMIT_MAX`, `MATCHING_RATE_LIMIT_WINDOW_MS` | Provisional |
| Page size 20, at most 50; at most page 1000 | `DISCOVERY_LIMITS` | Provisional |
| Search text at most 60 characters | `DISCOVERY_LIMITS.queryMaxLength` | Provisional |
| Distance filter 1–1000 km (accepted; excludes nobody) | `DISCOVERY_LIMITS.maxDistanceKm` | Provisional |
| Write retries on collision: 10 | `MATCHING_POLICY.maxWriteAttempts` | Provisional |

#### Questions Recovery 4 raises but does not answer

| Question | Where it bites |
|---|---|
| Should upgrading an existing like to a Super Like cost a Super Like? (R4-07) | Today it does. |
| How does the public profile page authenticate? `profile/[id]/page.tsx` calls `getById` from a Next.js server component, which has no browser token | Frontend integration (with gap D6) |
| The cards render "-1 km away" and "Asha, " for hidden ages; `MemberCard.age` is typed `number` | Frontend integration (AD-24, AD-26) |
| `onlineOnly` and `isOnline` must be switched on with presence | Recovery 5 (AD-25) |
| Should an unmatch exist? Should Super Likes be visible to their recipient as such (the "Super Likes" tab)? | Not in the frontend's services; nothing is built (AD-27) |

---

## Part 2 (continued) — Decisions approved during the recovery

### 2026-10-09 — Recovery 4 review

| ID | Decision | Closes |
|---|---|---|
| AD-29 | **Super Like upgrade:** turning an existing outgoing like into a Super Like consumes **exactly one** Super Like. Repeated or concurrent requests must not charge twice, and a failed upgrade must not leave a debit without the corresponding change to the like. Withdrawal still refunds nothing (AD-22). A new product decision for the reconstructed backend, not recovered behaviour. Confirms ledger R4-07. | R4-07 question |

**Status of AD-29 in the code (2026-10-09):** the "exactly one" and "no double charge under concurrency" parts are met and tested. The "failed upgrade leaves no debit" part is **not** met when the record write fails or the process stops after the debit (tests DEFECT 5 and DEFECT 6 in `tests/unit/matching.faults.test.js`). The fix is part of the correction awaiting approval.

## Part 3 (continued) — Correction to Recovery 4 technical choices (2026-10-09 review)

| ID | Correction |
|---|---|
| R4-02 (corrected) | The original entry said the sealing design "is atomic on a standalone MongoDB and on a replica set alike". **That is wrong.** Each write is atomic and the design is safe against concurrent requests, but the sequence of writes is not atomic: a crash or a failed write between two of them leaves an inconsistent state, in some cases permanently. Evidence and the proposed correction: `docs/reports/RECOVERY_4_CONSISTENCY_ANALYSIS.md`. |
| R4-05 (corrected) | The reversal of a Super Like debit covers a lost race, not a crash or a failed record write after the debit. |
| R4-06 (corrected) | The registration grant is written after the account marker. If that write fails or the process stops in between, the member is registered without the grant, and the repair path never runs, because a registered member is never sent back to registration. |

---

## Part 2 (continued) — Decisions approved during the recovery

### 2026-10-09 — Recovery 4 consistency correction

| ID | Decision | Closes |
|---|---|---|
| AD-30 | **Option T — MongoDB transactions.** Every operation whose consistency depends on more than one write runs as one multi-document transaction: a like and the Match it completes; a Super Like's debit, its record change (new, from a pass, or an upgrade) and the Match it completes; registration completion with the account marker and the initial three-Super-Like grant. There is no non-transactional fallback. | DEFECT 1–7 of `docs/reports/RECOVERY_4_CONSISTENCY_ANALYSIS.md`; the unmet part of AD-29 |
| AD-31 | **Fail fast without transactions.** The server refuses to start unless the connected MongoDB deployment is a replica set or a sharded cluster able to run the required transactions, with a clear, actionable error. It never silently falls back to non-transactional behaviour. | — |

**Status of AD-29 after the correction:** all three parts are met in the code and tested on the in-memory stores: exactly one debit per upgrade; no double charge under repeated or concurrent requests; a failed upgrade leaves no debit (the debit and the record change commit or abort together). Not yet executed against MongoDB (see the Recovery 4 report).

## Part 3 (continued) — Technical choices of the consistency correction (written 2026-10-09, awaiting review)

| ID | Choice | Reason |
|---|---|---|
| R4-T1 | **Transaction runner.** `stores.transactions.run(work)` (`src/repositories/transactions.js`) runs `work(session)` in `session.withTransaction()` with read concern `snapshot`, write concern `majority`, read preference `primary`. On top of the driver's own retries it retries the **whole unit, in a fresh session, at most 5 times** (`MAX_TRANSACTION_ATTEMPTS`) on: a duplicate key, a `RetryableConflict`, or a `TransientTransactionError`. Every other error (a 409 such as `no_super_likes`, a 404, a programming error) aborts and passes straight through. | Inside a transaction a duplicate key aborts the transaction, so it cannot be absorbed in place as before; the whole unit has to be re-read and re-run. The limit stops a pathological retry loop. |
| R4-T2 | **Stores take an optional `{ session }`.** Every read and write of the three operations passes it. Stores used by them (`like`, `match`, `profile`) **swallow a duplicate key only outside a transaction**; inside one they rethrow it, so the runner retries. A project rule checks this mechanically. | Requirement 2 of the correction: no write required for consistency may happen outside the transaction. |
| R4-T3 | **Pair lock.** The first write of every like or Super Like transaction is `$inc` on `relationshipLock` of the pair's canonical first member (`User.relationshipLock`, a counter never serialized). | Snapshot isolation allows write skew: two simultaneous first likes (A→B and B→A) write different documents, so neither would see the other and no Match would be made. Writing one shared document makes the two transactions conflict; MongoDB aborts one, and the retry sees the other's like. `docs/DATABASE_DESIGN.md` 5.8. |
| R4-T4 | **Super Like debit key: `<record ID>:v<version>`** (the version the record had before the change; `v0` for a new record). Deterministic, so a retried transaction re-derives the same key. | Replaces R4-05's random key and reversal. With the debit inside the transaction, a lost race aborts the debit too; the unique `(userId, reason, referenceId)` index stays as a second guard against paying twice. |
| R4-T5 | **Removed:** the `super_like_reversal` ledger reason and the in-request reversal (R4-05); the `unseal` compensation (R4-02); the registration repair path (R4-06); `MATCHING_POLICY.maxWriteAttempts` (R4-04's 10 retries). | A transaction makes each of them unnecessary; leaving them would leave code paths no test can reach. |
| R4-T6 | **Ledger writes require a session.** `superLikeService.debit` and `grantInitial` throw a `TypeError` when called outside a transaction. | A ledger entry must never exist without the change it pays for or comes with. |
| R4-T7 | **Registration** is one transaction: read the account and profile; a registered profile returns 409 `duplicate_submission`; register the profile; mark the account; grant three Super Likes. A failed attempt leaves a draft exactly as it was. | AD-22, AD-30. |
| R4-T8 | **Start-up check** (`src/config/transactionSupport.js`). After connecting, the server reads `hello`: a replica-set member (`setName`, not an arbiter) or a mongos (`msg: "isdbgrid"`); sessions enabled (`logicalSessionTimeoutMinutes`); wire version ≥ 9 (MongoDB 4.4) for either topology: transactions exist from 4.0 / 4.2, but only 4.4 lets a transaction create a collection, which the first like, Match or ledger entry on a fresh database does. Then it runs one real read-only probe transaction. Any failure: `TransactionSupportError`, the connection closed, the message printed to stderr, exit code 1. The message names no host or credential. | AD-31. The probe catches what `hello` cannot show (permissions, a misconfigured member). |
| R4-T9 | **In-memory transaction model** (`tests/helpers/memoryTransactions.js`): one unit at a time (a queue); every store write in a session records an undo action; a throw replays them in reverse; the same retry policy as R4-T1. | Lets the fault-injection tests prove that the services put every write in the transaction and that no failure leaves partial state. Its limits are listed in the file and in the Recovery 4 report: it does not model MongoDB's isolation, write conflicts or the pair lock's effect. |
| R4-T10 | Database tests use `MongoMemoryReplSet` (a one-member replica set). | Transactions need one; the tests use the production topology. |

**Superseded by this correction:** R4-02 (no transaction), R4-04 (10 retries), R4-05 (random key and reversal), R4-06 (grant after the marker, repair path).

#### Provisional values introduced by the correction

| Value | Setting | Status |
|---|---|---|
| Transaction unit attempts: 5 | `MAX_TRANSACTION_ATTEMPTS` (`src/utils/transactions.js`) | Provisional |
| `MATCHING_POLICY.maxWriteAttempts` (10) | — | **Removed** |

---

## Part 2 (continued) — Decisions approved during the recovery

### 2026-10-09 — Recovery 5 decisions

Answers to `docs/reports/RECOVERY_5_DECISION_REQUEST.md`. New decisions for the reconstructed backend, not recovered behaviour.

| ID | Decision | Closes |
|---|---|---|
| AD-32 | **(Q1) Socket authentication, option A.** The access token travels in the Socket.IO handshake `auth` payload. The existing authentication implementation is reused; no second authentication system. The session and the account are rechecked on every client event; sockets are disconnected when their access token expires; logout disconnects the sockets of that session. No token in a URL. | D11 (handshake) |
| AD-33 | **(Q2) Moderation, option B.** A server-side moderation adapter interface with a disabled development mode. **Production refuses to start while moderation is disabled.** `AI_MODERATION_ENABLED=true` with the provider configuration or implementation unavailable fails start-up with an actionable error. Messages are never described as moderated when they were not. No provider or credential is invented. | D8 (Recovery 5 part) |
| AD-34 | **(Q3) Presence, option A.** Real presence in Recovery 5: `online` while connected, `recently_active` for 15 minutes after the last disconnect (named configuration, provisional), then `offline`. Visibility and block policies apply. Recovery 9 must integrate the "Online Activity Indicator" setting. | D11 (presence); completes AD-25 |
| AD-35 | **(Q4) Read and delivery, option A.** Mark-read marks the recipient's messages from the other member as read **up to and including** the given message. Delivery is tracked separately, set when the recipient fetches the message or acknowledges its push. Both idempotent; a member can never change another member's read state. | New |
| AD-36 | **(Q5) Event contract approved with documentation first:** client → server `conversation:join`, `conversation:leave`, `message:send`, `message:read`; server → client `message:new`, `message:read`, `presence:update`; every payload, acknowledgement, error code, validation rule, authorization check and delivery semantic written in `API_CONTRACT.md` §11 before handlers. **Also approved:** a random Conversation ID; derived summaries; cursor pagination; optional `clientMessageId` idempotency; existing block and eligibility enforcement; the Conversation created in the same transaction as the Match (with the matching fault-injection coverage updated and the matching invariants re-verified, nothing else in Recovery 4 reopened); Socket.IO single-instance, with the limitation documented; provisional limits as named configuration recorded here. | D11 (events), D10, B5 |

## Part 3 (continued) — Technical choices made during reconstruction (awaiting review)

### Recovery 5 — Messaging and Socket.IO (written 2026-10-09, awaiting review)

Decisions applied: AD-32 to AD-36. Defaults applied: B5, B12, D2, D3, D10, D19; D9's recorded fallback. Applies AD-19's `showOnlineStatus` to presence.

| ID | Choice | Reason |
|---|---|---|
| R5-01 | The Conversation has its own random ID and a unique `matchId`; the Match ID stays internal. | R4-03; a pair-derived ID is computable by anyone who knows two account IDs. |
| R5-02 | The Conversation insert is the last write of the Match-making part of the like and Super Like transactions (after the Match insert), with the same session. | AD-36; both exist or neither. |
| R5-03 | No conversation summary is stored. Last message, unread count and order are derived from `Message`; a send is one insert and needs no transaction. | Avoids a two-document write and counter drift (DATABASE_DESIGN §6.3). |
| R5-04 | History: cursor `before` = ID of a message in the conversation; order `createdAt`, then `_id`, newest page first, items oldest→newest; `limit` 1–100, default 30; `{ nextCursor, hasMore, limit }`. A `before` that is not a message of the conversation is 400. | B5's recorded default; the UI renders oldest→newest. |
| R5-05 | The conversation list is paginated with `page` and `limit` exactly like Matches (default 20, at most 50). | The frontend method has no parameters; an unbounded list would contradict MP §12. Same shape as the Recovery 4 lists. |
| R5-06 | `memberName` is the first name only. | Full names are never shared with other members (Recovery 3 public view). |
| R5-07 | Stored moderation state `unmoderated`; served as `moderation: "clear"` (the frontend's "not held") plus a backend field `moderationChecked: false`. | AD-33: "never claim messages were moderated". The frontend's three values have no "unchecked"; the extra field states it explicitly. **Flagged for review.** |
| R5-08 | The production refusal (AD-33) runs in the server's start-up, before the database connection. `db:indexes` and `admin:create-first` do not run it. `AI_MODERATION_ENABLED=true` is refused where the adapter is built (server start-up) because no provider implementation exists; missing URL or key is the existing configuration error. | The commands do not carry chat; blocking them would block deployment chores without adding safety. |
| R5-09 | An adapter outcome other than an unchecked pass makes the send fail with 503 `moderation_unavailable`, storing nothing. | Holding and `ModerationEvent` are Recovery 6; failing closed is safer than storing a message nobody can act on. |
| R5-10 | `clientMessageId`: 1–64 of `[A-Za-z0-9_-]`, unique per sender. A repeat with the same conversation and text returns the stored message (REST 200; socket `created: false`) and pushes nothing; any difference is 409 `client_message_id_conflict`. | Idempotent retries without a duplicate; a key reused for different content is a client error, not a silent replay. |
| R5-11 | Text: trimmed, 1–2000 Unicode code points, control characters other than `\n`, `\r`, `\t` refused. Stored as given (no HTML escaping on the server; the frontend renders plain text). | MP §26 payload control; escaping is the renderer's job and the bubble never uses HTML. |
| R5-12 | Mark-read's `:messageId` must be addressed to the caller; otherwise 404. | "Read up to" a message the caller sent has no meaning; one answer for every refusal. |
| R5-13 | Delivered is set by fetching a history page (REST or `conversation:join`) and by the first acknowledgement of `message:new` from any of the recipient's sockets; the sender is not notified (no such event in AD-36). Reading also sets delivered. | AD-35; event list fixed by AD-36. |
| R5-14 | `authenticate` is split into one shared function, `authenticateAccessToken(token)` (signature, session, account), used by the REST middleware and the socket handshake, and `recheckSession({ userId, sessionId })` for per-event checks. The token service gains `verifyAccessTokenWithExpiry` (the socket needs the expiry); `verifyAccessToken` is unchanged. Every token failure is `unauthenticated`, as REST's 401 does not say why. | AD-32; one implementation. |
| R5-15 | Every client event must carry an acknowledgement callback; one without is dropped unprocessed. | A send whose result cannot be reported would be a silent write. |
| R5-16 | The server places each socket in a private account room at connection; every push goes to account rooms. Conversation rooms are joined only after the access check, and nothing is pushed to them in Recovery 5. | Members need new messages for every conversation (list, unread counts); a room is never a permission. |
| R5-17 | `message:new` also reaches the sender's other sockets, never the socket that sent it (it has the acknowledgement); a REST send reaches all of them. | Several tabs or devices stay in step without a duplicate on the sending socket. |
| R5-18 | Presence follows effective privacy: with `showOnlineStatus` off, a member is always shown `offline`, never kept by `onlineOnly`, and no `presence:update` is sent about them. Pushes go only to members sharing a usable conversation, checked at that moment. | AD-19 and AD-34 ("respect visibility and block policies"). |
| R5-19 | The `recently_active → offline` transition is not pushed; presence is in memory and resets on restart (everyone `offline` until they connect). | No timers per member; restarts are honest rather than guessed. |
| R5-20 | Logout returns the revoked session ID to the auth controller, which asks the real-time hub to disconnect that session's sockets. The hub lives in the container (no npm import); `server.js` creates the Socket.IO server and attaches it. Without it (tests, commands), pushes are no-ops. | AD-32; keeps the composition root free of npm imports. |
| R5-21 | The REST limits (express-rate-limit, per account) and the socket limits (in-house fixed window, per socket) count separately. | Different transports; a shared counter would need shared state (single instance anyway). |
| R5-22 | Socket.IO's allowed origins are `FRONTEND_URL`'s, as for CORS; `serveClient` off. | One origin policy. |
| R5-23 | The access check also confirms the pair's Match exists. | Defence in depth: by construction a Conversation implies its Match (R5-02). |
| R5-24 | `lastMessagePreview` is the latest text cut to 120 code points. | A list item needs no more; less private text crosses the wire. |
| R5-25 | The messaging service applies the text and `clientMessageId` rules again itself, whatever the transport already did. | No caller of the service (a future transport, a script) can bypass them. |
| R5-26 | Message IDs are laid out like MongoDB ObjectIds (seconds, a per-process random part, a counter), so IDs made by one server increase in creation order and break ties between messages with the same `createdAt`. Conversation IDs stay fully random. | A total, stable order that matches sending order on a single instance (AD-36). |
| R5-27 | An idempotent repeat (same `clientMessageId`) is answered from the stored message without calling moderation again. | A retry must not cost a second provider call or be judged differently. |
| R5-28 | A failure while marking a page delivered fails that fetch (500) and changes nothing; the next fetch marks it. | One write per request, no partial state; a read path that silently skipped delivery would make `delivered` unreliable. |
| R5-29 | Discovery's `onlineOnly` passes the connected accounts to the query (`$in`) and requires `privacy.showOnlineStatus` not `false` there too. Cards set `isOnline` from the same rule. Because the Discover screen sends `onlineOnly=true` by default, it shows only connected members. | AD-25, AD-34; one rule for filter and card. |

#### Provisional values introduced in Recovery 5

| Value | Setting | Status |
|---|---|---|
| `recently_active` window: 15 minutes | `PRESENCE_RECENTLY_ACTIVE_MINUTES` | **Approved value** (AD-34), configurable |
| Message text at most 2000 code points | `MESSAGING_LIMITS.textMaxLength` | Provisional |
| History page 30, at most 100 | `MESSAGING_LIMITS.defaultPageSize`, `.maxPageSize` | Provisional |
| Preview 120 code points | `MESSAGING_LIMITS.previewLength` | Provisional |
| Messaging REST writes: 60 per minute per account | `MESSAGING_RATE_LIMIT_MAX`, `MESSAGING_RATE_LIMIT_WINDOW_MS` | Provisional |
| Socket events: 60 per minute per socket | `SOCKET_EVENT_RATE_LIMIT_MAX`, `SOCKET_EVENT_RATE_LIMIT_WINDOW_MS` | Provisional |
| Sockets per account: 5 | `SOCKET_MAX_CONNECTIONS_PER_ACCOUNT` | Provisional |
| Largest socket packet: 16 KiB | `SOCKET_MAX_PAYLOAD_BYTES` | Provisional |
| Delivery acknowledgement wait: 10 s | `SOCKET_DELIVERY_ACK_TIMEOUT_MS` | Provisional |

## Part 3 (continued) — Recovery 5 review (2026-10-12)

The three entries flagged for review in the Recovery 5 report, reviewed against the code, the surviving frontend and the recovery sources. **No source code changed.** The entries above stay as written; these rows record the outcome.

| ID | Disposition | Rationale and evidence |
|---|---|---|
| R5-07 (reviewed) | **Kept, with its limitation documented and a future migration recorded (gap D28).** Unchecked messages stay `moderation: "clear"` + `moderationChecked: false`; stored state stays `unmoderated`. | A fourth `moderation` value (or `null`) would break the surviving frontend type `ModerationStatus = "clear" \| "pending_review" \| "blocked"` (FE `services/messages/types.ts`), which this recovery must not change. In the frontend, `clear` means "not held" (`MessageBubble` reacts only to `pending_review`; the frontend mock assigns `clear` without moderating). `moderationChecked` and the stored `unmoderated` keep the truth on every message. Unchecked messages cannot occur in production (AD-33). Rule for consumers and the migration: `API_CONTRACT.md` §10.3. No word list or simulated moderation was added. |
| R5-05 (reviewed) | **Kept: the conversation list stays paginated** by page number (`page` 1–1000, default 1; `limit` 1–50, default 20; `{ page, limit, hasMore }`; order `lastMessageAt` desc, then `id`; no cursor; no total). **Documented:** the exact shape, the reordering effect of page numbers over an activity order, and that reads are not bounded even though responses are. **Frontend requirement recorded (gap D27).** | Unbounded lists contradict MP §12 and the recovery's bounded-response rule. The frontend's `getConversations()` takes no arguments, so integration needs a separately approved frontend change. Bounding the reads would need a stored last-activity time and a transactional send: a design change, not made. |
| R5-29 (reviewed) | **Enforcement kept; the default is unresolved and needs your decision (gap D26). Backend unchanged.** | Enforcing `onlineOnly=true` is required (MP filter list: "online state") and approved (AD-25, decided with the default known; AD-34). The online-only default exists only in the frontend's `useState(true)`; no recovered requirement states it. The backend has no online-only default. Internal frontend evidence suggests the default may not be intended (a separate "Online Now" tab forces it; the checkbox is in a closed panel; the mock is 4/5 online). `API_CONTRACT.md` §8.5. |

**Also recorded in this review:**

- `docs/RUNTIME_VERIFICATION.md`: the procedure and commands for the first full run with dependencies and MongoDB.
- `docs/frontend-baseline.sha256`: a byte-identical copy of the 178-entry frontend manifest, so that the manifest travels with the backend repository and its backups. The original (`../.frontend_baseline.sha256`) is unchanged.
- One test assertion was added, in a test file only: the shared matching suite now checks that simultaneous mutual likes leave exactly one Conversation, belonging to the one Match. Without it, the runtime verification of AD-36 on MongoDB would have no test.

---

## Part 2 (continued) — Decisions approved during the recovery

### 2026-10-12 — Discover online-only default (gap D26)

| ID | Decision | Closes |
|---|---|---|
| AD-37 | **Discover defaults to `onlineOnly: false`, in a future, separately approved frontend integration change.** Discover must not silently exclude members because they are offline; the existing "Online Now" tab and "Online members only" checkbox remain the explicit ways to filter by presence. The backend is **unchanged**: it enforces `onlineOnly=true` when a client sends it (AD-25, AD-34) and applies no presence filter when `onlineOnly` is absent or `false`, subject to every other discovery and privacy rule. **The frontend has not been changed:** `DiscoverScreen.tsx` still starts with `useState(true)` until that integration change is approved and made. A new product decision for the reconstructed product, not recovered behaviour. | D26 |

---

## Part 2 (continued) — Decisions approved during the recovery

### 2026-10-12 — Recovery 6 decisions

Answers to `docs/reports/RECOVERY_6_DECISION_REQUEST.md`. Approvals of **reconstructed** design decisions, not claims about recovered original behaviour.

| ID | Decision | Closes |
|---|---|---|
| AD-38 | **(Q1) Block = hide and freeze; restore on unblock.** While a block exists in either direction, the pair is hidden from each other in discovery, profile viewing, Matches, Liked-you and conversation lists, and interactions are refused through the centralized safety policy. Matches, Conversations, sealed likes, messages and ledger entries are never deleted; no Super Like is refunded; the blocked member is never notified and no response reveals the block. Unblocking restores what was hidden. Recovery 4 matching invariants and Recovery 5 messaging behaviour are preserved. | D9 |
| AD-39 | **(Q2) Report rate limit: 10 reports per account per 24 hours, provisional**, as the named settings `REPORT_RATE_LIMIT_MAX` and `REPORT_RATE_LIMIT_WINDOW_MS`. Not the recovered figure (unavailable). Enforced server-side; concurrent submissions and the boundary must be tested. | B4 (provisionally) |
| AD-40 | **(Q3) Report rules.** `POST /api/reports` with `targetType` `user`, `profile` or `message`. User and profile targets use the account ID. Self-reports refused; unknown targets 404. Reporting is allowed after a block. Message reports only by the message's recipient, checked through conversation participation, not current access. At most one open report per reporter, type and target; a duplicate returns the existing report, **safe under concurrency** (enforced by the database, not by a sequential pre-check). A resolved or rejected report allows a new one. New reports are `OPEN`. Users never set status, resolution, moderation decision or internal notes. The reporter's identity and report details are never shown to the reported member. Report reasons, message text and evidence are never logged. Optional `reason`, at most 1000 characters (provisional); no category list. | D18 |
| AD-41 | **(Q4) Message-report evidence: snapshot.** A minimal snapshot of the reported message's text and time is stored in the report, **captured in the same operation that creates the report**. Visible only to authorized administrative workflows; no user-facing endpoint reveals it; never in logs or error responses. **Retention is unresolved and must be decided in Recovery 9 (gap D30)**: no duration is invented and indefinite retention is not implied. | — |
| AD-42 | **(Q5) `ModerationEvent` and held messages.** For a non-clear outcome the message and its moderation event are stored **atomically in one transaction**, with state `pending_review` or `blocked` (a `blocked` outcome is also stored, sender-only, with an event). The sender sees their own held message with its status. The recipient never receives it through Socket.IO, history, previews, unread counts, delivery tracking or any other recipient path. No release, appeal or recipient-decision workflow. The event holds no copy of the text. Tested with a fake adapter; no claim that a provider exists or moderation operates. **AD-33 is preserved unchanged.** | D8 (Recovery 6 part) |
| AD-43 | **(Q6) Admin report management: service-level hooks only.** List by status, fetch one, and the state-machine transitions (`OPEN` → `UNDER_REVIEW`, `RESOLVED` or `REJECTED`; `UNDER_REVIEW` → `RESOLVED` or `REJECTED`), with resolution and internal-note fields. **No admin HTTP route, dashboard metric or `AdminAuditLog`** in Recovery 6. The hooks must be integrated with the mandatory audit workflow before any admin route exposes them (Recovery 9). | — |
| AD-44 | **(Q7) `GET /api/users/blocked`**: paginated; only `memberId`, `firstName`, `blockedAt`; only accounts the caller blocked, never accounts that blocked the caller; no photo and no exception to the visibility policy; the existing pagination conventions. | — |
| AD-45 | **(Q8) Block races: the stronger design.** Block and unblock use the same pair-lock discipline as matching, and matching re-checks the block **inside** its transaction, so a Match and Conversation cannot be created after a conflicting block takes effect. For messaging, re-checking before the push is **rejected** as insufficient. The design must ensure that a message send racing a block cannot deliver a new message or notification to the blocked member after the block takes effect; that messages are persisted before normal delivery; that no failure leaves a partial Match/Conversation or message/event pair; and that idempotency, read-up-to, delivery tracking and socket authorization stay intact. The commit-to-emission boundary must be addressed explicitly; a transaction alone does not make post-commit delivery atomic. Fault-injection and concurrency tests cover the interleavings; the in-memory model's limits stay documented. **The synchronization mechanism at the commit-to-emission boundary is a material choice not covered by this approval: request Q9.** | — |

### 2026-10-12 — Recovery 6, Q9

| ID | Decision | Closes |
|---|---|---|
| AD-46 | **(Q9) Option S1: in-process pair gate.** A per-pair asynchronous mutex in the Node.js process coordinates, for each pair of members: block and unblock transactions; message sending, including its database transaction and the Socket.IO emissions that follow; mark-read and its read-receipt emissions; and presence emissions between the two members. The gate is acquired **before** the database pair-lock write and released in a `finally` path on every outcome (transaction, validation or emission failure). Presence fan-out takes **one pair gate at a time**; no operation ever holds two gates. Inside the gate, the current block state is re-read before deciding to emit; a check made before acquiring the gate is never relied on. Guarantees: (1) no Match or Conversation after a conflicting block commits; (2) no message stored after it; (3) **no new server-side push emitted to or about the blocked member after it**; (4) a message and its moderation event commit together or not at all; (5) idempotency, read up to, delivery tracking, authentication, authorization and persistence-before-delivery unchanged. **Server emission time is not network arrival time**: a packet emitted before the block commits may arrive later. **Hard deployment restriction:** safe only while TORAZ runs as a **single Node.js process**: no cluster mode, no multiple workers, no multiple instances. Multi-instance deployment needs a separately designed distributed synchronization mechanism first. | Q9 (AD-45's open part) |

---

## Part 3 (continued) — Technical choices made during reconstruction (awaiting review)

### Recovery 6 — Safety (written 2026-10-12, awaiting review)

Choices made while implementing AD-38 to AD-46 that those decisions do not dictate. RECONSTRUCTED, not recovered.

| ID | Choice | Reason |
|---|---|---|
| R6-01 | One safety policy (`src/services/safety.service.js`) is the only reader of blocks: eligibility, visibility, discovery, matching and messaging receive it and never touch the block store. The block service is the only writer. Enforced by a project-rules test. | AD-38 ("through the centralized safety policy"); one place to change. |
| R6-02 | The pair gate is a per-pair promise chain (`src/realtime/pairGate.js`), created once in the composition root. Acquiring a second gate while holding one throws `PairGateError` (detected with `AsyncLocalStorage`) instead of waiting. | AD-46 ("never hold multiple pair gates"): a lock-order mistake fails loudly at once rather than deadlocking. |
| R6-03 | Order inside every gated write: gate → transaction → pair-lock write → in-transaction re-checks → writes → commit → (still inside the gate) block re-read → emit → release. AD-30's whole-unit retries run inside the gate. | AD-45, AD-46. |
| R6-04 | Block and unblock answer idempotently: a repeated block answers 200 with the original `blockedAt`, the first answers 201; unblock always answers 200 and removes only the caller's own block. Blocking yourself is 400 (`reason: "self"`); an unknown account is 404. | API contract §12.2–12.3. |
| R6-05 | Block and unblock share one per-account limit: **60 per hour (provisional)**. | Abuse of block/unblock toggling; no recovered figure. |
| R6-06 | After a block commits, still inside the gate, both members' sockets leave the pair's conversation room (`io.in(userRoom).socketsLeave`). A failure of that eviction is logged and ignored. Nothing is sent to either member. | Rooms carry no pushes (R5-16), so eviction is hygiene; the guarantee rests on the gate and re-checks, not on room membership. AD-38: never notify. |
| R6-07 | **Deviation from Recovery 4:** a pass or like on a blocked pair answers 404 even when the pair is matched (previously 409 `already_matched` came first). | AD-38: no response may reveal the block; 409 would reveal the Match while hidden. |
| R6-08 | **Deviation from Recovery 5:** a send is now one transaction (pair lock, access re-check, idempotency re-check, message, moderation event). A fault anywhere, including right after the message insert, leaves nothing stored; Recovery 5 left the message stored on a crash after its insert. The Recovery 5 fault test was rewritten to the new semantics. | AD-42 (message and event atomic), AD-45 (pair lock). |
| R6-09 | Moderation is called **before** the gate and outside the transaction; the idempotent replay is checked before the call (R5-27 kept) and again inside the transaction. | No gate or transaction is held across a provider call. |
| R6-10 | Mark-read takes the gate and re-checks access inside it but writes no pair lock: it is one conditional update, not a transaction. | The gate already orders it against blocks in this process; adding a lock write would add a transaction for no further guarantee. |
| R6-11 | Presence fan-out computes the audience before taking any gate, then for each member takes that pair's gate, re-reads the block and emits. A failure for one member is logged (no payload) and the loop goes on. | AD-46 (one gate at a time); one member's failure must not silence the others. |
| R6-12 | Pushes are synchronous; a push that throws is caught, logged without its payload, and does not fail the request or the stored write. The gate is released in `finally` either way. | Persistence before delivery (AD-45); a socket error must not turn a committed send into an error answer. |
| R6-13 | The post-commit block re-read in send and mark-read is **defence in depth**: in one process a block cannot commit between the commit and the push, because the block waits for the gate. Tests that write a block straight into the store at that point (simulating a writer outside the gate, which AD-46 does not support) show the re-read still stops the push. This does not make several processes safe. | AD-46 ("re-check inside the gate"). |
| R6-14 | Deliverable states are `unmoderated` and `clear`; held states are `pending_review` and `blocked`. Recipient paths filter in the repository: history and latest (`visibleTo`), unread counts, `markDelivered`, `markReadUpTo`. A held message used as a cursor by its recipient is 400 `Invalid cursor`, as for an unknown one; mark-read and report of a held message by its recipient are 404. | AD-42: the message does not exist for the recipient. |
| R6-15 | A malformed moderation verdict is refused with 503 and nothing is stored; a checked `pending_review` or `blocked` verdict is now accepted and held (Recovery 5 refused every non-clear outcome; test R5-09 now covers malformed verdicts only). | AD-42 replaces the Recovery 5 refusal. |
| R6-16 | `ModerationEvent`: one per message (unique `messageId`), `status: OPEN`, the provider reference if any, no text. | AD-42. |
| R6-17 | Report creation is one transaction that first writes the reporter's `User.safetyLock`, so one reporter's reports are serialized: duplicate check, target resolution (with evidence), rolling count and insert are consistent under concurrency. The open-report key is `targetType:targetId`, stored as `openKey` with a partial unique index `{ reporterId, openKey }`; closing a report unsets it. | AD-39, AD-40 ("enforced by the database"). |
| R6-18 | A duplicate open report is returned (200) **before** the limit is checked, so repeating a report never costs a slot nor is refused at the limit. The limit counts reports created strictly after `now − window`. | AD-40 (a duplicate returns the existing report). |
| R6-19 | The report answer is `{ reportId, status, createdAt }` (201 new, 200 duplicate). Nothing else about the report is ever returned to users. | AD-40. |
| R6-20 | Message reports: the reporter must be the recipient, the message must be deliverable, and the reporter must be a member of its conversation (not current access, so reporting works after a block). The reported account is the sender; the evidence is `{ messageText, messageSentAt }`. | AD-40, AD-41. |
| R6-21 | The `reason` is trimmed, empty means absent, counted in code points (at most 1000, provisional), and may not contain control characters other than tab and line breaks. | AD-40; same text rules as messages. |
| R6-22 | Admin hooks: `transition` requires the acting administrator's ID (a `TypeError` otherwise, so Recovery 9's audit record has it), is one conditional update on the expected current status (409 `invalid_transition` or `report_state_changed`), and closing unsets `openKey`. `resolution` and `internalNote` at most 2000 characters each (provisional). | AD-43. |
| R6-23 | The blocked list shows `firstName` as the first word of the blocked member's full name, newest block first (ties by member ID), with the usual page/limit pagination. | AD-44. |
| R6-24 | `User` gains `relationshipLock` usage by block and unblock (same field as matching) and a new `safetyLock` used only by reports. | AD-45 (same pair-lock discipline); reports are per reporter, not per pair. |

#### Provisional values introduced in Recovery 6

| Value | Setting | Status |
|---|---|---|
| Reports: 10 per account per rolling 24 hours | `REPORT_RATE_LIMIT_MAX`, `REPORT_RATE_LIMIT_WINDOW_MS` | **Provisionally approved** (AD-39), configurable |
| Block and unblock: 60 per hour per account | `BLOCK_RATE_LIMIT_MAX`, `BLOCK_RATE_LIMIT_WINDOW_MS` | Provisional |
| Report reason at most 1000 code points | `REPORT_LIMITS.reasonMaxLength` | **Provisionally approved** (AD-40) |
| Resolution and internal note at most 2000 code points | `REPORT_LIMITS.resolutionMaxLength`, `.internalNoteMaxLength` | Provisional |

## Part 3 (continued) — Recovery 6.1 corrective checkpoint (written 2026-10-12, awaiting review)

A defect found in review of the `recovery-6` checkpoint, corrected without changing any approved decision. AD-38 to AD-46 stand as written; this entry records how the code now meets AD-46 for one operation it had missed.

**Defect.** `conversation:join` ran the access check and history read (`getMessages`) outside the pair gate, then called `socket.join`. A block could commit and evict both members' sockets between the check and the join; the join then resumed and put the socket in the room after the block. This defeated R6-06's room eviction and AD-46's rule that everything between the pair is decided under the gate after a fresh check.

| ID | Choice | Reason |
|---|---|---|
| R6-25 | `conversation:join` goes through a new service operation, `messagingService.joinConversation(callerId, conversationId, { enter })`. A check before the gate only finds the other member (and refuses early); inside gate(caller, other) the caller's registration and the full access check (membership, Match, the other member's account and profile, the block both ways) run again, then the newest history page, then `enter()`, which the gateway supplies as `() => socket.join(conversationRoom(conversationId))`. `enter()` is awaited, and the gate is released only after it returns. A block that takes the gate first makes the join answer the ordinary `not_found` with no room and no history; a block requested during the join waits and then evicts the socket. A failure at any step releases the gate (`finally`). | AD-46: no decision between the pair may rest on a check made outside the gate. The service stays free of Socket.IO objects and room names (R5-16); the gateway stays the only place that touches a socket. `GET /api/messages/conversations/:conversationId` is unchanged: it joins no room, so it needs no gate. |

**Known residue, unchanged by the fix:** if `enter()` itself fails after the history page was read, the messages on that page stay marked delivered although the client received an error. This was already the case before the fix (the page was read before the join); delivery is idempotent and the next fetch returns the same messages.

## Part 3 (continued) — Recovery 6.2 corrective checkpoint (written 2026-10-12, awaiting review)

Resolves the "known residue" recorded under R6-25. No approved decision changes: AD-35 (delivered is set when the recipient fetches a message), R5-13 (a `conversation:join` page is such a fetch) and R5-28 (a failed delivery write fails that fetch and changes nothing) already require it; R6-25 stands, with step order refined as below.

**Defect.** `joinConversation` read the history page through the shared `page()` helper, which marks the caller's received messages delivered, and only then awaited `enter()`. If the room join failed, the client received an error but the messages stayed marked delivered, although the page was never returned.

| ID | Choice | Reason |
|---|---|---|
| R6-26 | `page()` is split into `readPage()` (reads only; computes which messages on the page are the caller's undelivered, deliverable ones) and `deliverPage()` (the one `markDelivered` write, then the answer). REST history (`getMessages`) calls them back to back, exactly as before. The join, inside the pair gate, now runs: access re-checks → `readPage()` → `await enter()` → `deliverPage()` → release. If `deliverPage()` fails, the service calls the transport's `leave()` and rethrows; a failure of `leave()` is logged (no payload) and does not replace the original error. The callback contract grows from `{ enter }` to `{ enter, leave }`, and `leave` must undo only what `enter` did: the gateway records whether the socket was already in the room before `enter()` and leaves only if it was not, so a failed **re**join never removes membership a previous successful join gave. | AD-35, R5-13, R5-28: a join that fails changes nothing, neither delivery state nor room membership. Entering the room before marking delivery makes the delivery write the last step, so no later step can fail after it. The service still never touches a socket or a room name (R5-16). |

**Failure outcomes of `conversation:join` after R6-26:**

| Failing step | Answer | Delivery state | Room membership | Gate |
|---|---|---|---|---|
| Access re-check | error (`not_found`, `profile_not_registered`, or `internal_error`) | unchanged | not entered | released |
| History read | `internal_error` | unchanged | not entered | released |
| Room entry (`enter`) | `internal_error` | unchanged | not entered | released |
| Delivery write, not performed | `internal_error` | unchanged | entry undone | released |
| Delivery write performed, then a failure is reported | `internal_error` | delivered (one write, happened whole; as for REST under R5-28) | entry undone | released |
| Delivery write fails and `leave` also fails | `internal_error` (the original), `leave` failure logged | as the two rows above | may remain; it was authorized inside the gate, and a later block evicts it | released |

## Part 3 (continued) — Recovery 6.3 corrective checkpoint (written 2026-10-12, awaiting review)

No approved decision changes (AD-35, AD-46, R5-28 apply). R6-25 and R6-26 stand as written; this entry extends R6-26's cleanup to one more failure.

**Defect.** `joinConversation` (6.2) called `leave()` only when the delivery write failed after a successful `enter()`. If `enter()` itself threw or rejected after the transport had already added the socket to the room (a partially applied adapter join), the error was returned with no cleanup, and the socket could stay in the room although the join failed.

| ID | Choice | Reason |
|---|---|---|
| R6-27 | If `enter()` throws or rejects, the service **attempts** `leave()` before rethrowing the **original** entry error, exactly as R6-26 does after a delivery failure; both paths share one helper (`attemptLeave`). A failure of `leave()` is logged as `room exit after a failed join failed` with only `{ step: "enter" | "deliver", err }` (no message text, history, token or payload) and does not replace the original error. The attempt runs inside the pair gate, so the gate is released only after it finishes. The `{ enter, leave }` contract is unchanged; the gateway's `leave()` already leaves only if the socket was not in the room before this `enter()`, so a failed **re**join never removes earlier membership. | A failed join must leave nothing behind (R5-28); the transport may fail part-way. **This is a best-effort cleanup, not a rollback guarantee:** nothing here can promise that every third-party adapter can undo a partial join. If `leave()` fails, the membership may remain. It was authorized by the access check inside the gate, nothing is pushed to conversation rooms (R5-16), and a later block still evicts it through the block's own eviction. |

**Failure outcomes of `conversation:join` from Recovery 6.3** (supersedes the R6-26 table above for the room-entry rows; the other rows are unchanged):

| Failing step | Answer | Delivery state | Room membership created by this join | Gate |
|---|---|---|---|---|
| Access re-check | error (`not_found`, `profile_not_registered`, or `internal_error`) | unchanged | none (not entered) | released |
| History read | `internal_error` | unchanged | none (not entered) | released |
| Room entry fails, nothing added | `internal_error` (the entry error) | unchanged | none; `leave()` attempted (no effect) | released after the attempt |
| Room entry adds the socket, then fails; `leave()` succeeds | `internal_error` (the entry error) | unchanged | removed | released after the attempt |
| Room entry adds the socket, then fails; `leave()` fails | `internal_error` (the **entry** error); `leave()` failure logged with `step: "enter"` | unchanged | **may remain** (authorized; evicted by a later block) | released after the attempt |
| Delivery write, not performed | `internal_error` | unchanged | removed if `leave()` succeeds | released after the attempt |
| Delivery write performed, then a failure reported | `internal_error` | delivered (one write, as for REST, R5-28) | removed if `leave()` succeeds | released after the attempt |
| Delivery write fails and `leave()` fails | `internal_error` (the original); `leave()` failure logged with `step: "deliver"` | as the two rows above | may remain | released after the attempt |
| Any failure on a **re**join of a socket already in the room | the error | as above | the earlier membership is kept (`leave()` does nothing) | released |

---

## Part 2 (continued) — Decisions approved during the recovery

### 2026-10-13 — Recovery 7 decisions (verification)

Answers to `docs/reports/RECOVERY_7_DESIGN_REQUEST.md`, **approved with amendments**. Approvals of **reconstructed** design decisions, not claims about recovered original behaviour. Where an amendment differs from the design request, the amendment governs.

| ID | Decision | Closes |
|---|---|---|
| AD-47 | **(Q1) Retry** is allowed from `retry_required` and `failed`. No separate lifetime attempt cap in Recovery 7; the provisional per-account action rate limit applies. Provider-specific attempt limits are a future decision. | Q1 |
| AD-48 | **(Q2) No automatic reset** of verification after name or photo changes in Recovery 7. Recorded as **unresolved** for a future real provider. | Q2 (deferred) |
| AD-49 | **(Q3) No placeholder provider callback route.** | Q3, D21 (callback part) |
| AD-50 | **(Amendment A, revised T8) Enabled provider without an implementation.** With `VERIFICATION_PROVIDER_ENABLED=true` and no real-provider implementation: in `NODE_ENV=production` **start-up is refused** with a clear, non-secret configuration error; in development and test start-up may proceed, provider actions answer 503 and write nothing. An enabled provider that is missing or misconfigured **never** falls back to simulation. The existing configuration validation and the production prohibition of simulation are kept. | T8 |
| AD-51 | **(Amendment B, revised T5) Verification provenance.** Production trust is not derived from the source of the last transition alone. An explicit provenance invariant: development simulation never confers production-trusted verification; a development database reused in production never shows simulated members as verified; no later state change can convert simulated verification into production-trusted verification; production-trusted verification originates only from an independently validated real-provider result, or from a separately authorized future admin decision under an explicit approved policy. Recovery 7 implements no admin verification management. The model stays minimal; the fields and invariants are documented; transitions that could launder simulation into trusted verification are tested. No real provider is invented; no client-supplied proof is accepted. | T5 |
| AD-52 | **(Amendment C, revised T3/T12) Versioned compare-and-set.** A monotonic record version; the expected version is read before the provider is invoked; conditional writes compare the expected version, not only the state; concurrent first inserts are protected by the unique `userId` index; stale provider results fail safely without overwriting a newer decision. Duplicate calls, state changes during a provider delay and the A → B → A case are tested. Single-document atomicity; no transaction or pair-gate use. | T3, T12 |
| AD-53 | **(Amendment D) Real-provider boundary.** The provider interface and a disabled-safe real-provider placeholder only. No DigiLocker, e-KYC, face matching, callbacks, consent redirects or credentials. Fake real-provider responses exist only in tests. Real verification is not claimed to operate. No frontend change. | D21 (real mode) |
| AD-54 | **Technical choices T1–T7 and T9–T19** of the design request are approved, as amended by AD-50 to AD-53. Routes: `GET /api/verification/status`, `POST /api/verification/start`, `POST /api/verification/liveness`, `POST /api/verification/retry`. The ten frontend states and the frontend's exact `percentComplete` mapping (C1). Client-supplied verification fields and account IDs are ignored. `isVerified` on member cards and conversation summaries from batched reads, without exposing internal verification data. Provisional shared rate limit for start, liveness and retry: 10 per account per hour, as named configuration. | B10, B13, C1, D21 (as recorded) |

## Part 3 (continued) — Technical choices made during reconstruction (awaiting review)

### Recovery 7 — Verification (written 2026-10-13, awaiting review)

Choices made while implementing AD-47 to AD-54 that those decisions do not dictate. RECONSTRUCTED, not recovered.

| ID | Choice | Reason |
|---|---|---|
| R7-01 | The gate is a dependency-free pure module (`src/services/verificationGate.js`): no `require`, no `process`. A project-rule test enforces this. | B10: testable with nothing installed (tier T1). |
| R7-02 | "Production" for verification means **any** `NODE_ENV` other than exactly `development` or `test`: the gate, the adapter factory, the service and the trust rule all use this one definition (`allowsSimulation`). | Misspelt or missing values must fail safe. |
| R7-03 | Simulation is refused in production at **four** layers: configuration (B13), the gate, the adapter factory, and the service constructor. Simulated records are additionally never trusted there (AD-51). Each layer has its own test and its own mutation check. | AD-50, and "production simulation impossible even if configuration is bypassed". |
| R7-04 | Provenance is stored as `evidence` (`simulation` / `provider`) for the current chain, with a sticky taint (`DATABASE_DESIGN.md` §8.2). A new chain begins only with `start`. In production, a record whose evidence is not `provider` is read as absent, so it can only be restarted, never continued. Unknown evidence values are never trusted anywhere. | AD-51: no laundering through later transitions. |
| R7-05 | `version` starts at 1 and every write is `findOneAndUpdate({ userId, version })` with `$inc`. The expected version is read before the provider call. The first write is an insert guarded by the unique `userId`. A lost race is 409 `invalid_verification_state` and is never retried automatically. | AD-52. |
| R7-06 | Provider calls are wrapped in a timeout (`VERIFICATION_PROVIDER_TIMEOUT_MS`, **15 s, provisional**) using injectable timers. A provider error is logged by **error name only**. | A provider's error text could carry provider data; tests need no real clock. |
| R7-07 | A provider result is accepted only as a plain object with exactly `outcome` and `providerRef`, an outcome allowed for that call, and a reference matching `^[A-Za-z0-9._:-]{1,200}$` (or `null`). | AD-53: nothing but an opaque token is ever stored. |
| R7-08 | `providerName` is stored only for real-mode provider results; simulation stores neither name nor reference. Retry, which makes no provider call, keeps the previous name and reference. | Minimal internal data. |
| R7-09 | `isVerified` is computed by `verificationTrust.verifiedAmong(ids)`: one `$in` read of `state: 'verified'` per list, filtered by the trust rule. It is used by the card builder (discovery, featured, member card, matches, liked-you) and the conversation summaries. | AD-54; one place for the trust rule. |
| R7-10 | The verification store is touched only by the verification service and the trust module; the controller reads only `req.auth`; routes take no parameters and no validator. Each is enforced by a project rule. | AD-54: no client value can reach verification state. |
| R7-11 | The real-provider placeholder (`available: false`) is built only outside production; in production the adapter factory and the start-up check both refuse it, and `server.js` reports the refusal as an operator message, before the database connection. | AD-50. |
| R7-12 | Test seams: `overrides.verificationMode`, `overrides.verificationAdapter` and `overrides.verificationTimers` in the container. The only fake provider is `tests/helpers/fakeVerificationProvider.js`. | AD-53: fake results are test-only. |

#### Provisional values introduced in Recovery 7

| Value | Setting | Status |
|---|---|---|
| Start, liveness and retry: 10 per account per hour | `VERIFICATION_RATE_LIMIT_MAX`, `VERIFICATION_RATE_LIMIT_WINDOW_MS` | **Provisionally approved** (AD-54) |
| Provider call timeout: 15 s | `VERIFICATION_PROVIDER_TIMEOUT_MS` | Provisional |

#### Open items recorded by Recovery 7

- **AD-48 (open):** whether verification resets after name or photo changes, needed before a real provider.
- Provider-specific attempt limits (AD-47): a future decision.
- Retention of the verification record and the frontend's "delete all verification audit logs" promise: Recovery 9 (purge) and gap D30's retention question.
- A real provider (and, with it, a callback and consent-redirect design, and a frontend change for the redirect): not chosen.

---

## Part 3 (continued) — Recovery 8: proposed technical choices (design stage)

*Historical note, kept as written at design time:* Recovery 8 was at the design stage; the proposal is `docs/reports/RECOVERY_8_DESIGN_REQUEST.md` §14. **Superseded by the approvals AD-55 to AD-64 below.**

---

## Part 2 (continued) — Decisions approved during the recovery

### 2026-10-13 — Recovery 8 decisions (premium and payment-disabled architecture)

Answers to `docs/reports/RECOVERY_8_DESIGN_REQUEST.md`, **approved with amendments**. Approvals of **reconstructed** design decisions, not claims about recovered original behaviour. Where an amendment differs from the design request, the amendment governs.

| ID | Decision | Closes |
|---|---|---|
| AD-55 | **(Q1, Q2, Q3) Not implemented, and unresolved:** recurring free Super Likes; subscription expiry and renewal (no expiry or renewal behaviour invented); Boost ranking (Boost status does not change discovery order). | D22 (recorded, not built) |
| AD-56 | **(Q4) `callingEnabled`** is true exactly when the member has a **trusted** premium entitlement. This does not implement calling. No other plan benefit is implemented. | D22 (plan benefits, in part) |
| AD-57 | **(Q5) A new Boost activation replaces the currently active Boost**, as the surviving frontend mock does. | Q5 |
| AD-58 | **(Q6) Subscribing while already subscribed** answers **409 `already_subscribed`**; the plan is not changed. | Q6 |
| AD-59 | **(Q7) Optional backend-only `purchaseKey`** (1–64 characters of `[A-Za-z0-9_-]`). Repeated or concurrent requests with the same key apply the credit at most once. Requests without a key are distinct purchases, each applied exactly once. No frontend change. | Q7 |
| AD-60 | **(Q-A) Enabled provider without implementation:** with `PAYMENT_PROVIDER_ENABLED=true` and no real provider implementation, **production refuses to start**; development and test may start, and payment actions answer 503 `{ reason: "payment_unavailable" }` and write nothing. | Q-A |
| AD-61 | **(Q-L) Option L3 with a runtime contamination safeguard.** Simulated pack credits use a distinct ledger reason (`simulated_pack_purchase`), a unique reference per idempotent purchase, and are written only inside the existing transaction runner (the `(userId, seq)` and `(userId, reason, referenceId)` constraints preserved). Production **refuses to start** if any simulated-credit entry exists. **After start-up**, in production, before returning a Super Like balance or allowing a Super Like debit, the account's ledger is checked for simulated-credit history; if found, that account's Super Like balance and spending **fail closed** with a safe operational log. **A corrected balance is never inferred** by subtracting simulated credits from `balanceAfter`, and ledger entries are never rewritten or deleted. Normal debit semantics for clean accounts, the three-Super-Like registration grant and the matching transactions are unchanged. The safeguard is a narrow defence against untrusted ledger history, not a redesign of ledger accounting. | Q-L |
| AD-62 | **Payment mode gate** `resolvePaymentMode` → `real` / `dev_simulation` / `unavailable`, with the precedence: enabled and configured → `real`; enabled but misconfigured → `unavailable` (never simulation); explicit simulation flag in `development` or `test` → `dev_simulation`; otherwise `unavailable`. `PAYMENT_DEV_SIMULATION` defaults to `false`, is a strict boolean, and simulation is refused in production at the configuration, gate, adapter and service layers. No real gateway; a configured but unimplemented provider never falls back to simulation. Simulation creates no payment, order, receipt or settlement record. | B13 (payment part) |
| AD-63 | **Contract.** Routes `GET /api/premium/entitlement`, `POST /api/premium/super-likes/purchase`, `POST /api/premium/boost/activate`, `POST /api/premium/subscribe`. Server-side catalog mirroring the frontend IDs and counts or durations (`pack_5`/`15`/`25` = 5/15/25; `boost_15`/`30`/`60` = 15/30/60 minutes; `plan_1m`, `plan_3m`, `plan_12m` with no invented duration); no prices; unknown IDs rejected with 400 **before** the payment mode is checked; own-property lookup. Entitlement response exactly `tier`, `superLikesRemaining`, `boostStatus`, `boostExpiresAt`, `callingEnabled`. Super Like balance from the ledger with AD-61's safeguards; Boost expiry by the server clock; `isPro` = the viewing member's own trusted `callingEnabled`; simulated subscription and Boost not trusted in production; no provenance or internal identifiers in member responses; `boost_triggers` stays unsupported (no Boost history). | D22, B12 |
| AD-64 | **Concurrency.** Simulated ledger credits in the existing transaction runner; versioned compare-and-set for Boost and subscription writes (conflicting updates never silently overwrite each other); a disabled operation reads and writes no entitlement or ledger state before answering 503 (apart from validation, authentication and the mode check); no second Super Like balance field. T1–T13 of the design request approved as amended here. | T1–T13 |


## Part 3 (continued) — Technical choices made during reconstruction (awaiting review)

### Recovery 8 — Premium, payment disabled (written 2026-10-13, awaiting review)

Choices made while implementing AD-55 to AD-64 that those decisions do not dictate. RECONSTRUCTED, not recovered. **No real payment provider exists in this build.**

| ID | Choice | Reason |
|---|---|---|
| R8-01 | The payment gate (`src/services/paymentGate.js`) is a pure, dependency-free module with the same shape as the verification gate; "production" means any `NODE_ENV` other than exactly `development` or `test` (`allowsPaymentSimulation`). | AD-62; one definition, fail-safe for misspelt values. |
| R8-02 | Simulation is refused in production at four layers: configuration (`PAYMENT_DEV_SIMULATION must not be true in production`), the gate, the adapter factory and the premium service constructor. The Super Like service refuses simulated credits in production as a fifth, independent check. | AD-62. |
| R8-03 | Exactly three adapters, `{ mode, name, available }`: `none` (unavailable), `simulation`, `not_implemented` (the real placeholder, `available: false`, refused in production). No network code, no credential use beyond the gate's presence check, no payment interface is designed. | AD-60: the real-payment boundary is not specified. |
| R8-04 | Only `dev_simulation` with an available adapter can act. A real-mode adapter cannot act even if it claimed availability, because no real-payment flow (checkout, callback, settlement) exists. | AD-60. |
| R8-05 | Order of every action: catalog ID (400) → purchase-key shape (400) → registered caller (409) → mode (503) → reads and writes. Nothing touches the entitlement or ledger stores before the 503. | AD-63, AD-64. |
| R8-06 | Pack references: `key:<purchaseKey>` with a key, `auto:<24 hex characters>` without. A key reused with a different pack answers 409 `purchase_key_conflict` and writes nothing; a key is per account. | AD-59: the unique `(userId, reason, referenceId)` index does the work. |
| R8-07 | `PremiumEntitlement` is one document per account (unique `userId`) with nullable `subscription { planId, source, startedAt }` and `boost { optionId, source, activatedAt, expiresAt }` and a `version`. The first write is an insert; later writes are `findOneAndUpdate({ userId, version })` with `$inc`. A lost race answers 409 `entitlement_changed` and is never retried automatically. | AD-64. |
| R8-08 | `source` is `simulation` for every write in this build. Trust: production trusts `provider` only; development and test trust both; an unknown source is never trusted. Untrusted components read as absent; nothing is rewritten. | AD-62, AD-63. |
| R8-09 | Boost status is computed from the server clock: `active` iff `expiresAt > now`; the exact instant is `expired`; `boostExpiresAt` is kept after expiry. A Boost never enables calling or premium. | AD-57, AD-63; no client time. |
| R8-10 | The runtime ledger safeguard is one `exists({ userId, reason: 'simulated_pack_purchase' })` read before every balance read and every append in production, inside the caller's session when there is one. A refused account answers 503 `super_likes_unavailable` and logs `{ userId }` only. Without a configuration the Super Like service treats itself as production. | AD-61. |
| R8-11 | The start-up ledger check runs in `server.js` right after the database connection and before the application is built; the payment check runs before the connection. Both are reported as operator messages. A new index `{ reason: 1, createdAt: -1 }` serves the start-up check. | AD-60, AD-61. |
| R8-12 | `isPro` on conversation summaries is the viewer's own `callingEnabled`, one entitlement read per list. | AD-63, B12. |
| R8-13 | Premium actions share one per-account limiter (`PREMIUM_RATE_LIMIT_MAX`, `PREMIUM_RATE_LIMIT_WINDOW_MS`); the entitlement read uses the general limit only. | Abuse control without a provider. |
| R8-14 | Test seams: `overrides.paymentMode` and `overrides.paymentAdapter` in the container. | Tests only. |

#### Provisional values introduced in Recovery 8

| Value | Setting | Status |
|---|---|---|
| Premium actions: 20 per account per hour | `PREMIUM_RATE_LIMIT_MAX`, `PREMIUM_RATE_LIMIT_WINDOW_MS` | Provisional |

#### Open items recorded by Recovery 8

- **AD-55 (open):** recurring free Super Likes, subscription expiry and renewal, Boost ranking. None is implemented.
- A real payment provider: checkout, provider callback with signature verification, settlement, refunds, and a frontend change for the checkout step. Not designed.
- Handling of a contaminated production ledger (AD-61): an approved operator procedure is needed; the code only refuses.
- Calling itself: `callingEnabled` is a flag only (AD-56).

---

## Part 3 (continued) — Recovery 9: proposed (design stage, 2026-10-14; revised after design review)

**Nothing in this section is approved or implemented.** The proposal is `docs/reports/RECOVERY_9_DESIGN_REQUEST.md` (revision 2). Until you approve, the binding decisions in table 1 govern. Every item in tables 2 and 3 is **pending**. This section is the **single canonical record** of the Recovery 9 pending decisions; the design request keeps the reasoning and the trade-offs.

### 1. Binding decisions that Recovery 9 must preserve

| Source | Binding content for Recovery 9 |
|---|---|
| MP §5, §20, §25 | Roles `USER` and `ADMIN`; never trust a client role. Every admin endpoint requires a valid JWT, an active session and the `ADMIN` role. Never rely on frontend route protection. Audit important admin mutations. No new frontend pages for audit logs, moderation, analytics or monetization unless requested |
| MP §21 | Admins manage reports; users never set status, decision, resolution or notes; admin actions affecting reports create audit records |
| MP §24 | No retention policy invented silently |
| R01 §5 (Admin) | Admin authorization on every admin route; suspend and reinstate; verification management; reports; audit logs. 12 KPI concepts: 9 real or derivable; `gateway_retries`, `boost_triggers`, `mod_queue_sla` not tracked. Recent activity only from actual data; no fabricated payment or Boost history |
| AD-15 | First administrator by a secure one-time command; no public admin creation; no client-supplied role |
| AD-19, AD-26 | The more restrictive privacy control wins; a hidden exact age is `null` |
| AD-30, AD-31 | Multi-write consistency through MongoDB transactions; no fallback |
| AD-33 | Production refuses to start without a moderation provider; no fake provider |
| AD-34, AD-46 | Presence is in-process; single Node.js process only. The Online Activity Indicator must be integrated by the batch that builds settings |
| AD-38 to AD-45 | Block = hide and freeze. Report rules, rate limit and duplicate-open handling. The evidence snapshot is admin-only and never logged. Held messages never reach the recipient. The admin report hooks and their graph (`OPEN` → `UNDER_REVIEW` / `RESOLVED` / `REJECTED`; `UNDER_REVIEW` → `RESOLVED` / `REJECTED`; closed final), exposed only with the audit. Blocked-list semantics. Block races |
| AD-41 | Evidence retention undecided (D30); indefinite retention is not implied |
| AD-51 | Production-trusted verification only from a validated real provider, or a separately authorized future admin decision under an explicit approved policy. **Conflicts with R01 §5 "verification management" and MP §25 `PATCH /api/admin/users/:id/verification` until such a policy exists: P-08** |
| AD-55 to AD-64 | No real payment provider; simulation never trusted in production; `boost_triggers` unsupported |
| Gap defaults in use | B14 (every admin write audited; reads not, **extended by P-10** to evidence releases), C1 (admin verification status mapping), C7 (`maskedEmail: null`), D14 (queue derivation). **B11 (`value: null`) is proposed for revision by P-14**: the frontend type requires a string |

### 2. Technical defaults — **approved 2026-10-14 as AD-73** (R9-T1 to R9-T15, as written below)

| ID | Proposal |
|---|---|
| R9-T1 | All admin routes on one router under `/api/admin`, which mounts `authenticate` and `requireAdmin` before any route; enforced by a project rule |
| R9-T2 | (Revised 2.2.) Every admin transaction (mutation or evidence release) first **writes** the acting admin's own `users` document: a new internal `adminLock` counter (`$inc`), the existing `relationshipLock` / `safetyLock` pattern. It then re-reads it (role `ADMIN`, status `active`). The write makes a concurrent demotion or suspension of that admin a write conflict, so one transaction aborts and retries; a plain re-read would not under snapshot isolation (design request §7.2) |
| R9-T3 | Report transitions take a required `expectedStatus`, which the existing conditional update uses. The hook gains a `session` option; graph and error codes are unchanged |
| R9-T4 | `sessionStore.revokeAllForUser` gains a `session` option; suspension revokes with reason `admin` |
| R9-T5 | A new `hub.disconnectUser(userId)` disconnects every socket of an account after the suspension commits (best effort) |
| R9-T6 | `AdminAuditLog` insert-only store. Mongoose middleware refuses updates, replaces and deletes; no route mutates it; a project rule restricts writers to the admin services |
| R9-T7 | Audit fields as design request §11: only enumerated values in `change`. No free text, names, phone numbers, IPs, user agents, tokens or bodies |
| R9-T8 | Idempotent no-op status changes answer 200 and write no audit entry |
| R9-T9 | KPI counts are indexed `countDocuments` (for `active_users`, a distinct-account aggregation over an indexed range) with `maxTimeMS` 5000; a failure answers 503 `dashboard_unavailable`; no cache |
| R9-T10 | New indexes: `User { registrationCompletedAt: 1 }`, `Session { lastUsedAt: 1 }`, `Message { createdAt: 1, moderation: 1 }`, and the `AdminAuditLog` indexes (`DATABASE_DESIGN.md` §10) |
| R9-T11 | `timestampLabel`, `joinedLabel` and `waitLabel` are computed server-side by one pure formatter. Responses carry exactly the frontend types' fields, plus `supported` on KPIs |
| R9-T12 | Pagination: `page` ≥ 1, `limit` default 20, max 50; the audit log by cursor; the users `query` ≤ 60 characters, escaped |
| R9-T13 | The project rule "moderation events only in messaging" is widened to allow read-only counting by the dashboard service |
| R9-T14 | Admin serializers live apart from member serializers; a project rule forbids member routes from importing them |
| R9-T15 | Denied and refused admin requests are logged with the user ID, route template, reason code and request ID only |

### 3. Pending decisions: recommended resolutions (design review, 2026-10-14), awaiting your explicit approval

| ID | Recommended resolution | Status |
|---|---|---|
| P-01 | Split: Recovery 9 = admin and moderation operations; settings, sessions, deletion, purge and data export = **Recovery 9B** | **Approved 2026-10-14 (AD-65)** |
| P-02 | One `ADMIN` role in Recovery 9. No public admin registration and no role-management routes. Emergency demotion = the documented operator procedure (design request §7.1: one multi-document transaction on a replica set; database-level, not audited by the application; not yet executed or rehearsed. §7.2: it cannot stop an overlapping sign-in from creating a session, which carries no administrator authority because the role is re-read on every request. A stricter policy needs the application-stop maintenance gate. **Unresolved until the §7.2 rehearsal passes**). An audited `admin:demote` command is a later, separate proposal | Recommended, pending approval → **2026-10-22: conditional, not cleared for production (AD-90)** |
| P-03 | Refuse self-suspension and any status change against an `ADMIN` account (409 `self_action` / `admin_target`). Limitation and emergency recovery path documented (§7, §7.1) | **Approved 2026-10-14 (AD-79)** |
| P-04 | No new step-up authentication in this batch (the frontend has no such flow). The stolen-session risk is kept explicit | Recommended, pending approval → **2026-10-22: not approved; production blocker (AD-91)** |
| P-05 | Keep the AD-43 graph. `expectedStatus` required; `resolution` required for `RESOLVED` and `REJECTED`; no reopening | **Approved 2026-10-14 (AD-66)** |
| P-06 | Report transitions trigger no sanctions. Suspension and reinstatement are separate audited operations | **Approved 2026-10-14 (AD-67)** |
| P-07 | Account status change, session revocation and audit entry commit atomically; sockets are disconnected after commit; reinstatement does not restore revoked sessions | **Approved 2026-10-14 (AD-68)** |
| P-08 | **V2, subject to AD-51:** a read-only verification queue may be built. Approve and re-upload are **not** built until an explicit admin-trust policy is approved. Queue entries are never manufactured; the read-only endpoint is never presented as an approval workflow | **Approved 2026-10-14 as V2, read-only only (AD-80)**; the **admin-trust policy remains undecided** |
| P-09 | **Least-privilege admin user record:** account ID, name, city, account and verification status, tier, masked phone (`maskedEmail` `null`, C7). `age` only as members would see it (`null` when hidden, AD-26). `primaryPhoto` only where the existing visibility rule already allows this admin, else `null`. **No photo-route bypass.** Any further sensitive field or photo access needs a documented purpose and an explicit authorization decision | **Approved 2026-10-14 (AD-75)** |
| P-10 | Audit every successful admin mutation and every successful evidence release (`report.evidence_released` = the server committed to returning the evidence). Evidence is returned only after its audit entry commits; no entry if retrieval fails. Denied attempts go to sanitized operational logs only | **Approved 2026-10-14 with N-1 (AD-77)** |
| P-11 | Fail closed when the audit store is unavailable: no mutation commits without its audit entry (503 `audit_unavailable`) | **Approved 2026-10-14 (AD-69)** |
| P-12 | Every authorized admin may read all audit entries; entries are append-only. **Retention period undecided: production blocker** | **Approved in part 2026-10-14 (AD-78): access and append-only; retention period undecided** |
| P-13 | Document the redaction and anonymization mechanism and its consequences (design request §12). **Periods N, M and P are not chosen.** No automatic retention deletion or redaction is built until a policy is approved | Mechanism recommended, pending approval; **periods undecided** |
| P-14 | KPI formulas as design request §13: India-calendar-day boundaries; `maxTimeMS` limits; single-process caveat for `online_now` (aggregate only, never per member); `messages_sent` **excludes held messages**. Unsupported KPIs: `value: "—"`, `supported: false` (the frontend `value` is a required `string`; revises B11) | **Approved 2026-10-22 (AD-81)** |
| P-15 | Recent activity: registrations, trusted verifications, suspensions and reinstatements, and **"Safety Report Filed"** (category "Moderation", status "Active" = open) while the report is open, naming the reported member, never the reporter. "High Priority" is never produced. Fallback if "Active" is judged misleading: omit report rows | **Approved 2026-10-22 (AD-82)** |
| P-16 | Settings counters accepted in principle: `blockedCount` = the caller's own blocks; `reportedCount` = the caller's own open reports only. Delivery in Recovery 9B | **Approved 2026-10-14 (AD-70)** |
| P-17 | The Online Activity Indicator is a member privacy toggle, integrated through `effectivePrivacy` in Recovery 9B. No admin per-member presence | **Approved 2026-10-14 (AD-71)** |
| P-18 | Per-admin limits, provisional and configurable: 300 reads per 15 minutes, 60 mutations per hour (`ADMIN_READ_RATE_LIMIT_*`, `ADMIN_WRITE_RATE_LIMIT_*`); implementation tests required | **Approved 2026-10-14 (AD-72)** |
| P-19 | **Settings route surface (Recovery 9B).** Three routes only: `GET /api/settings/summary` (`blockedCount`, `reportedCount`), `GET /api/settings/privacy` and `PATCH /api/settings/privacy` (`onlineActivityIndicator` only). Every route requires an access token, acts on the caller's own account only, and requires a completed registration (409 `profile_not_registered`, as for the blocked list). The frontend's whole `getSettings()` snapshot is not served, and no placeholder value is returned | **Approved 2026-10-22 (AD-84)** (proposed in `docs/reports/RECOVERY_9B_DECISION_REGISTER.md`; implemented in `cc46621`) |
| P-20 | **Unset Online Activity Indicator reads as enabled.** With no stored value, the indicator reads `true` and the settings side imposes no restriction (`effectivePrivacy`: an absent setting never restricts). This preserves presence behaviour from before Recovery 9B. Reading never creates a record. This control only; the other four defaults are C8 | **Approved 2026-10-22 (AD-85)** (proposed in `docs/reports/RECOVERY_9B_DECISION_REGISTER.md`; implemented in `cc46621`) |
| P-21 | **Unapproved privacy switches are refused.** A `PATCH /api/settings/privacy` body carrying `intentAndDietaryPrivacy`, `displayExactAge`, `approximateProximity` or `culturalHeritageAndHometown` answers 400 `"This setting is not available yet"` and stores nothing. Any other unknown field is dropped, as on every route. A switch is accepted only after its own approved decision (C8) | **Approved 2026-10-22 (AD-86)** (proposed in `docs/reports/RECOVERY_9B_DECISION_REGISTER.md`; implemented in `cc46621`) |
| P-22 | **No immediate presence push when the indicator changes.** Switching the indicator off or on sends no `presence:update`. While a member is hidden, their presence audience is empty, so no offline update is sent when they later disconnect either. A viewer who saw them online before the switch keeps that state until the viewer's next refresh. Same as the profile's `showOnlineStatus` since Recovery 5. Documented limitation; a push on switch-off would be a separate decision | **Approved 2026-10-22 (AD-87)** (proposed in `docs/reports/RECOVERY_9B_DECISION_REGISTER.md`; implemented in `cc46621`) |

**Readiness review (2026-10-14):** `docs/reports/RECOVERY_9_READINESS.md` holds:
- the consolidated decision matrix;
- the implementation batches;
- the readiness classification;
- refinements N-1 to N-4 (**pending**, not applied to the text above).

**Still undecided after the review (not to be turned into defaults):**
- the audit retention period (P-12);
- the D30 periods N, M and P and their legal and privacy assumptions (P-13);
- the admin-trust policy for verification (P-08);
- any admin access to sensitive fields or photos beyond P-09;
- creating and removing administrators beyond the bootstrap and the emergency procedure (P-02).

### 4. Explicitly deferred (proposed)

- **Recovery 9B, if P-01 is approved:** `UserSettings`; the settings snapshot and delivery of the counters; the Online Activity Indicator integration; sessions and per-session logout; pause; the deletion request; the purge command; data export; settings-control defaults. Gaps B8, D12, D15, D16, D17.
- **Later batches:**
  - verification approve and re-upload, and an admin-trust policy;
  - an audited `admin:demote` command, and administrator management;
  - automatic retention, redaction or deletion;
  - moderation-event review, release or appeal;
  - report reopening, categories, urgency, sanctions, appeals and notifications;
  - dashboard and CSV exports, and the cluster-health display;
  - payment, Boost-history and monetization administration;
  - step-up authentication;
  - multi-instance presence and synchronization;
  - frontend integration.

---

## Part 2 (continued) — Decisions approved during the recovery

### 2026-10-14 — Recovery 9 decisions (limited technical baseline)

A **limited, group approval**. It covers exactly the items below, with the text recorded in "Recovery 9: proposed" (table 2 and the P-rows of table 3) and in `docs/reports/RECOVERY_9_READINESS.md` (N-4). Approvals of **reconstructed** design decisions, not claims about recovered original behaviour.

**It does not extend to any other decision.** Still pending:
- P-02, P-03, P-04, P-08, P-09, P-10, P-12, P-13, P-14, P-15;
- N-1, N-2, N-3.

**Still unresolved:** the retention periods (audit, and D30 N, M, P), and the admin-trust policy for verification.

| ID | Decision | Closes |
|---|---|---|
| AD-65 | **(P-01)** Recovery 9 = admin and moderation operations. Settings, sessions, pause, deletion, purge and data export form **Recovery 9B** | P-01 |
| AD-66 | **(P-05)** The AD-43 report graph unchanged; `expectedStatus` required; `resolution` required for `RESOLVED` and `REJECTED`; no reopening | P-05 |
| AD-67 | **(P-06)** Report transitions trigger no sanctions; suspension and reinstatement are separate, audited operations | P-06 |
| AD-68 | **(P-07)** Account status change, session revocation and audit entry commit atomically; sockets are disconnected after commit; reinstatement does not restore revoked sessions | P-07 |
| AD-69 | **(P-11)** Fail closed when the audit store is unavailable: no admin mutation commits without its audit entry (503 `audit_unavailable`) | P-11 |
| AD-70 | **(P-16)** Settings counter definitions: `blockedCount` = the caller's own blocks (as the blocked list lists them); `reportedCount` = the caller's own reports in `OPEN` or `UNDER_REVIEW` only. Delivered in Recovery 9B | P-16 |
| AD-71 | **(P-17)** The Online Activity Indicator is a member privacy toggle, integrated through `effectivePrivacy` in Recovery 9B; no admin per-member presence | P-17 |
| AD-72 | **(P-18)** Per-admin rate limits, provisional and configurable: 300 reads per 15 minutes, 60 mutations per hour (`ADMIN_READ_RATE_LIMIT_MAX` / `_WINDOW_MS`, `ADMIN_WRITE_RATE_LIMIT_MAX` / `_WINDOW_MS`), with implementation tests | P-18 |
| AD-73 | **(R9-T1 to R9-T15)** The technical defaults in "Recovery 9: proposed", table 2, as written. This includes R9-T2 as revised in 2.2: every admin transaction writes the actor's internal `adminLock`, then re-reads the actor. **The MongoDB concurrency guarantee of R9-T2 is approved as a design; it is not yet demonstrated** (readiness D-2) | R9-T1 to R9-T15 |
| AD-74 | **(N-4)** `npm run db:indexes` must be run, and its result verified, as part of the Recovery 9 production deployment procedure (production runs with `autoIndex: false`) | N-4 |

### 2026-10-14 — Recovery 9-B decisions (report privacy and audit)

A **limited approval** for Recovery 9-B, covering exactly the items below. Approvals of **reconstructed** design decisions.

**Still pending:**
- P-02, P-03, P-04, P-08, P-13, P-14, P-15;
- N-3;
- every retention period;
- the verification admin-trust policy.

| ID | Decision | Closes |
|---|---|---|
| AD-75 | **(P-09) Least-privilege admin member access.** No bypass of member age or photo-visibility restrictions. No full phone numbers, dates of birth, tokens, provider fields or internal security fields. Admin serializers are kept separate from member-facing serializers | P-09 |
| AD-76 | **(N-2) Report-list privacy.** Report lists omit the reporter's identity and carry only what triage needs: report ID, target identity where permitted, target type, status and timestamps. The reporter's identity appears only in the authorized report-detail response. *Reconstruction note:* the approval mentions a category; **no report category exists** (AD-40: "no category list"), so none is added | N-2 |
| AD-77 | **(P-10 with N-1) Audited report-detail release.** Every successful report-detail response is audited, whether or not it includes message evidence. The canonical action is **`report.details_released`**: it replaces the proposed `report.evidence_released`, which no route ever wrote, so no committed application data uses it. The entry holds no reason, message text, evidence, name, phone number or other prohibited field. The details are released only after the audit entry and its transaction have committed. A failed authorization, a missing report, a failed audit write or a failed transaction discloses nothing | P-10, N-1 |
| AD-78 | **(P-12, limited) Audit access and immutability.** Authorized administrators may list audit entries under the admin guard and the read rate limit. The application stays append-only. **Retention periods remain undecided**; none is invented or implemented. The production requirement for a database role preventing audit updates and deletes is kept | P-12 (in part) |

*Implementation note (Recovery 9-B, not a new decision):* AD-75 to AD-78 are implemented by the four routes of `docs/API_CONTRACT.md` §15.6. Applying AD-77, the status-transition response is itself a report-detail response, so a successful transition writes `report.status_changed` and then `report.details_released`, in the same transaction. Every route, reads included, runs in the admin transaction guard, so the N-3 residual window (still pending) is not relied on.

### 2026-10-14 — Recovery 9-C decisions (protected targets and the read-only verification queue)

A **limited approval** for Recovery 9-C, covering exactly the items below. Approvals of **reconstructed** design decisions.

**Still pending:**
- P-02, P-04, P-13, P-14, P-15;
- the retention part of P-12 (AD-78 approved access and append-only only);
- N-3;
- every retention period;
- the verification admin-trust policy.

| ID | Decision | Closes |
|---|---|---|
| AD-79 | **(P-03) Protected suspension targets.** The admin status routes refuse the caller's own account (409 `self_action`) and any `ADMIN` account (409 `admin_target`): an administrator can neither suspend nor reinstate themselves, nor be suspended or reinstated, through them. No other admin role and no role-management endpoint is introduced. The limitation (a compromised administrator cannot be stopped through the console) and the emergency path (design request §7.1, not yet rehearsed) remain as documented | P-03 |
| AD-80 | **(P-08, V2) Read-only verification queue.** Only the read-only queue is built. **No** approval, rejection, re-upload or any other action that confers verification trust; the queue never creates or changes a `Verification` record and never manufactures an entry. The verification trust and provenance rule (AD-51) is unchanged: what the queue lists is decided by that rule. **The verification admin-trust policy remains undecided**; until it is approved, approve and re-upload routes do not exist | P-08 (V2 only) |

*Implementation notes (Recovery 9-C, not new decisions):* AD-79 and AD-80 are implemented by the four routes of `docs/API_CONTRACT.md` §15.7.
- The admin user set is the one in `FRONTEND_BACKEND_FIELD_MAPPING.md` §10.2 (registered `USER` accounts, `active` or `suspended`). An `ADMIN` target is refused with 409 `admin_target` before the set is checked, so the refusal AD-79 names is what an administrator sees; administrators are not listed and their detail answers 404.
- The R9-T8 no-op rule needed the admin guard to accept `requireAudit` as a function of the result: a status change that changes something still cannot commit without its entry (AD-69); a no-op writes none.
- The verification queue applies the AD-51 trust rule unchanged (in production, provider evidence only).

### 2026-10-22 — Recovery 9-D decisions (dashboard, recent activity, final checkpoint)

The final Recovery 9 approval, covering exactly the items below. Approvals of **reconstructed** design decisions.

**Still pending (unchanged):**
- P-02, P-04, P-13;
- the retention part of P-12;
- N-3;
- every retention period;
- the verification admin-trust policy (no verification approval, rejection or re-upload route exists or will be built).

| ID | Decision | Closes |
|---|---|---|
| AD-81 | **(P-14) Dashboard KPI definitions.** The twelve frontend KPIs (`services/admin/types.ts`), with the frontend's IDs and labels, computed live (no cache) from the nine formulas below, exactly as in design request §13. **"Today" is the calendar day in Asia/Kolkata** (00:00 to 24:00 IST); **"24 h" is a rolling window ending now.** Every KPI query has `maxTimeMS` 5000 (R9-T9); any failure answers 503 `{ reason: "dashboard_unavailable" }` and returns no partial or estimated value. Hints are factual definitions only: no trends, ratios or forecasts. The three untracked KPIs (`gateway_retries`, `boost_triggers`, `mod_queue_sla`) answer `value: "—"`, `hint: "Not tracked"`, `supported: false`, never `null`, zero or an estimate (revises the B11 recorded default); every other KPI carries `supported: true`. The nine formulas: (1) `verification_backlog`: `Verification` records in `manual_review` that the AD-51 trust rule accepts, **the same records the R9-C read-only queue lists** (AD-80); (2) `open_safety_reports`: `Report` with status `OPEN` or `UNDER_REVIEW`; (3) `moderation_alerts`: `ModerationEvent` with status `OPEN`; (4) `total_members`: **the R9-C admin user set** (role `USER`, registration completed, status `active` or `suspended`); (5) `new_today`: the same accounts whose `registrationCompletedAt` falls within today (IST); (6) `active_users`: distinct accounts with a session whose `lastUsedAt` is within the last 24 h, **labelled approximate** (`lastUsedAt` changes at sign-in and refresh only; expired sessions are TTL-deleted); (7) `online_now`: distinct accounts with at least one open socket **in this server process** (the presence service), aggregate only, never cluster-wide or per member; (8) `messages_sent`: `Message` created in the last 24 h whose `moderation` is deliverable (`unmoderated` or `clear`); **held messages (`pending_review`, `blocked`) are excluded**; (9) `super_likes`: Super Like ledger entries (reason `super_like`) created in the last 24 h. *Reconciliation note:* §13 calls the backlog records "trusted"; a record in `manual_review` is never trusted in the AD-51 sense (that needs `verified`), so "trusted" is read, as instructed, as "accepted by the trust rule", i.e. the queue's records | P-14 |
| AD-82 | **(P-15) Recent activity.** At most 10 rows, newest first, merged from the P-15 sources, each an indexed query limited to 10: completed registrations (the R9-C admin user set; "New User Registered", "User Lifecycle", "Success"); trusted verifications reaching `verified` ("Verification Completed", "Trust & Safety", "Verified"); **open safety reports** (`OPEN` or `UNDER_REVIEW`: action **"Safety Report Filed"**, category **"Moderation"**, status **"Active"**, meaning the report is still open; **closed reports leave the feed**); suspensions and reinstatements from the audit log ("Account Suspended", "Trust & Safety", "Suspended"; "Account Reinstated", "Trust & Safety", "Success"). `memberName` is the member's first name and last initial; for a report it is the **reported** member, and the **reporter is never shown**; no reason, evidence, resolution or note is read into a row. "High Priority", "Settled", "Monetization", "Engagement", payment and Boost rows are never produced. Least privilege (AD-75) and the audit rules (AD-69, AD-78) are unchanged; reading the dashboard writes no audit entry. *Reading of the instruction "include open safety reports only":* applied to report rows (only open reports are shown); the other four P-15 sources stay | P-15 |
| AD-83 | **Final Recovery 9 checkpoint.** The annotated `recovery-9` tag is authorized only after the R9-D implementation and closure report are complete and the final diff, checkpoint ZIP and checksums have been verified. The tag message states that the checkpoint is **implementation-complete and runtime-unverified**, and claims no production readiness | — |

*Implementation notes (Recovery 9-D, not new decisions):* AD-81 and AD-82 are implemented by `GET /api/admin/dashboard` (`docs/API_CONTRACT.md` §15.8).
- Every KPI count method refuses to run without a positive integer `maxTimeMS` (5000) and applies it to the MongoDB query.
- `total_members` uses the same filter function as the R9-C member list; `verification_backlog` uses the same state and evidence criteria as the R9-C queue.
- Recent-activity row keys are opaque (an HMAC under a per-process key), so a row carries no account, report or audit ID.
- Three project rules were widened, each to read-only use by the dashboard and pinned to the exact methods: moderation events (`countByStatus` only; R9-T13 approved this), the report hooks (`list` and `countOpen` only, never `get` or `transition`), and the admin user query (`countEligible` and `listIds` only). The Recovery 8 rule that keeps `boost_triggers` out of non-premium code now allows the dashboard policy to name it only as an unsupported KPI.

### 2026-10-22 — Recovery 9B: settings implementation notes (no new decisions)

AD-70 and AD-71 are implemented (`docs/API_CONTRACT.md` §16). Choices made while implementing them, for review; none of them is an approved decision:
- **Route surface.** No settings route shape had been designed. Three narrow routes were added (`GET /api/settings/summary`, `GET` / `PATCH /api/settings/privacy`), using the frontend's own field names, instead of the frontend's whole `getSettings()` snapshot, whose other fields are not approved. No placeholder value is returned.
- **Reading an unset indicator.** API_CONTRACT §7 left "the default value of each settings control" to Recovery 9. For this one control, an unset value reads as `true`: that is the established `effectivePrivacy` rule (an absent setting imposes no restriction), and it is the only reading that preserves existing presence behaviour, as Recovery 9B requires. The defaults of the other four privacy controls remain undecided (note the frontend mock's "Intent & Dietary Privacy" on).
- **Unapproved switches are refused, not dropped.** A patch carrying any of the other four `PrivacySettings` keys answers 400, so a client cannot believe it was saved.
- **No offline push on switch-off.** As with the profile's `showOnlineStatus` today, switching the indicator off sends no `presence:update`; viewers' screens correct at their next refresh. Existing behaviour, preserved; a change would be a separate decision.
- **Registration required**, as for the blocked list (409 `profile_not_registered`).

### 2026-10-22 — Recovery 9B settings decisions (AD-84 to AD-87)

Approval of the four Recovery 9B settings choices, proposed as P-19 to P-22 in `docs/reports/RECOVERY_9B_DECISION_REGISTER.md` (Appendix A), covering exactly the items below. The approval includes the completed-registration requirement in P-19 and the documented stale-presence limitation in P-22. These are approvals of **reconstructed** design decisions; they were already implemented in `cc46621`, and no code changes with this entry. The "Recovery 9B: settings implementation notes (no new decisions)" section above is kept as written.

**Not covered by this approval (still pending):**
- the defaults and acceptance of the other four settings privacy switches (C8-a to C8-d);
- P-02, P-04, N-3;
- the retention part of P-12; P-13 and its periods; every retention period;
- the verification admin-trust policy;
- the data-lifecycle decisions L-01 to L-20.

| ID | Decision | Closes |
|---|---|---|
| AD-84 | **Settings route surface (Recovery 9B).** Three routes only: `GET /api/settings/summary` (`blockedCount`, `reportedCount`), `GET /api/settings/privacy` and `PATCH /api/settings/privacy` (`onlineActivityIndicator` only). Every route requires an access token, acts on the caller's own account only, and requires a completed registration (409 `profile_not_registered`, as for the blocked list). The frontend's whole `getSettings()` snapshot is not served, and no placeholder value is returned | P-19 |
| AD-85 | **Unset Online Activity Indicator reads as enabled.** With no stored value, the indicator reads `true` and the settings side imposes no restriction (`effectivePrivacy`: an absent setting never restricts). This preserves presence behaviour from before Recovery 9B. Reading never creates a record. This control only; the other four defaults are C8 | P-20 |
| AD-86 | **Unapproved privacy switches are refused.** A `PATCH /api/settings/privacy` body carrying `intentAndDietaryPrivacy`, `displayExactAge`, `approximateProximity` or `culturalHeritageAndHometown` answers 400 `"This setting is not available yet"` and stores nothing. Any other unknown field is dropped, as on every route. A switch is accepted only after its own approved decision (C8) | P-21 |
| AD-87 | **No immediate presence push when the indicator changes.** Switching the indicator off or on sends no `presence:update`. While a member is hidden, their presence audience is empty, so no offline update is sent when they later disconnect either. A viewer who saw them online before the switch keeps that state until the viewer's next refresh. Same as the profile's `showOnlineStatus` since Recovery 5. Documented limitation; a push on switch-off would be a separate decision | P-22 |

### 2026-10-22 — Post-9B decision batch (AD-88 to AD-96)

Decisions on the second post-9B batch of `docs/reports/RECOVERY_9B_DECISION_REGISTER.md`, covering exactly the items below, with the outcome stated for each (approved, conditional, not approved, deferred). Approvals of **reconstructed** design decisions. Nothing else is approved by this entry.

**Still pending (unchanged):**
- the retention part of P-12; P-13 and its periods; every retention period;
- the verification admin-trust policy;
- the data-lifecycle decisions L-01 to L-17 and L-20;
- C8-c (deferred, AD-95).

| ID | Outcome | Decision | Closes |
|---|---|---|---|
| AD-88 | **Approved** | **(L-18, D12) Session list and per-session sign-out.** List only the authenticated member's own sessions that are active (not revoked) and unexpired. Mark the session of the current request with `isCurrent`. `deviceLabel` is derived from the stored User-Agent; `location` is left empty; no geolocation is added. Revocation affects only the caller's own selected session and uses reason `user` | L-18 |
| AD-89 | **Approved** | **(L-19, D17) Pause.** `UserSettings.paused`. Discovery allows a member only when not paused **and** `visibleInDiscovery`. A member without a stored pause value is not paused, so existing behaviour is preserved and no existing member is hidden. Resume uses the same route with `{ "paused": false }`. Pausing or resuming changes no other privacy setting. The default and migration behaviour are confirmed against the existing discovery logic before implementation | L-19 |
| AD-90 | **Conditional; not cleared for production** | **(P-02) Admin roles and emergency demotion.** One `ADMIN` role; no role-management routes. The emergency demotion requires the documented maintenance gate (design request §7.2) **and** a successful rehearsal (readiness §5 D-1). The operator identity and the rehearsal date remain **explicitly unresolved**. The procedure is not described as ready until the rehearsal passes | P-02 (conditionally) |
| AD-91 | **Not approved** | **(P-04) Step-up authentication.** The risk of admin actions without step-up authentication is **not accepted**; it remains a **production blocker**. The recent-session alternative (403 `reauth_required` for mutations without a recent sign-in) and its frontend implications are documented; no frontend-incompatible flow is implemented and no existing security is weakened | — (P-04 stays open as a blocker) |
| AD-92 | **Approved with condition** | **(N-3) In-flight admin read after demotion.** The residual risk of **one in-flight read-only** admin response after a demotion commits is accepted, provided every admin route is obligatorily run in the admin guard, every mutation remains audited (AD-69), and the risk stays documented. The exception does not extend to mutations or to any unguarded route | N-3 |
| AD-93 | **Approved** | **(C8-a) `displayExactAge`.** Stored in `UserSettings` and applied through `effectivePrivacy`. An unset value imposes no additional restriction; the profile's `showExactAge` continues to govern visibility; the more restrictive wins (AD-19) | C8-a |
| AD-94 | **Not approved** | **(C8-b) `approximateProximity`.** Continues to be refused (AD-86): no independent effect is defined | — |
| AD-95 | **Deferred** | **(C8-c) `intentAndDietaryPrivacy`.** No default is chosen and the setting is not enabled; it continues to be refused (AD-86) until explicitly decided | — |
| AD-96 | **Not approved** | **(C8-d) `culturalHeritageAndHometown`.** Continues to be refused (AD-86) until its effect is defined | — |

### 2026-10-22 — Recovery 9B sessions, pause and Display Exact Age: implementation notes (no new decisions)

AD-88, AD-89 and AD-93 are implemented (`docs/API_CONTRACT.md` §16.4 to §16.6). Choices made while implementing them, for review; **none of them is an approved decision**:
- **Routes.** `GET /api/settings/sessions`, `DELETE /api/settings/sessions/:sessionId`, `POST /api/settings/pause`. They follow AD-84: access token, the caller's own account only, completed registration required (409 `profile_not_registered`). The one path parameter is a session ID, checked against the caller's own live sessions.
- **Responses.** Sessions answer `{ sessions: DeviceSession[] }` (the frontend's `logOutSession` expects the bare array: integration item). Pause answers `{ paused }`. There is no read route for the pause state; the frontend has none.
- **Session list.** Current session first (the only `isCurrent: true`), then most recently used; at most 50 (provisional bound), the current session always included. Revoked and expired sessions are never listed.
- **Revocation.** One conditional update naming the session **and** the account (`revokeForUser`). Another member's, revoked, expired and unknown IDs all answer the same 404. The caller may revoke their current session through this route (not forbidden by AD-88; the frontend offers it only for other sessions); `POST /api/auth/logout` stays the way to sign out of the current one. After revocation the session's sockets are disconnected (AD-32).
- **Device label.** A fixed list of browser and system names; "Unknown device" otherwise; the raw User-Agent is never returned.
- **Pause reach.** Pause enters `effectivePrivacy().visibleInDiscovery`, as API_CONTRACT §7 already specified. It therefore applies wherever "visible in discovery" decides: discovery (including `onlineOnly`, the query and `featured`), cross-member visibility (`canViewProfileOf`: member detail and photos, and the admin user record's photo, AD-75), and the like/pass target rule (§9.1). Matches, members the paused member liked, conversations, the liked-you list and presence are unchanged.
- **Display Exact Age reach.** Every place that shows another member's age: cards, member detail, the matches and liked-you lists, and the admin user record and verification queue (the age as members see it, AD-75; admin code receives only `{ displayExactAge }`). With an age filter, discovery leaves out members hidden by either switch (AD-26).
- **Store changes.** `userSettingsStore.setOnlineActivityIndicator` is replaced by `setPrivacy(userId, values, now)` (approved switches only) and `setPaused`. `sessionStore` gains `listActiveForUser` and `revokeForUser`. The discovery aggregation looks up `usersettings` on its unique `userId` index. **No new index.**

### 2026-10-23 — Recovery 9B integration hardening: implementation notes (no new decisions)

For review; **none of these is an approved decision**:
- **Session responses.** `GET /api/settings/sessions` and `DELETE /api/settings/sessions/:sessionId` now answer `data` as the `DeviceSession[]` array itself, instead of `{ sessions }` (the 2026-10-22 note above). This is the shape of the frontend's `logOutSession()` and `SettingsSnapshot.sessions`, and of every list in this API (`sendPaginated`). No other consumer existed. Ownership, revocation and errors are unchanged.
- **Reading of AD-84 with AD-88, AD-89 and AD-93.** AD-84 ("three routes only"; the patch carries `onlineActivityIndicator` only) described the surface when it was approved. AD-88 and AD-89 approved the session and pause routes, and AD-93 approved storing and using `displayExactAge`. They are therefore read as **extending** AD-84's routes, patch body and privacy response. AD-84's other rules (own account, access token, registration, no placeholders) and AD-86 (refusal of the switches without an approved decision) apply unchanged. If this reading is not intended, AD-84 needs an explicit amendment.
- **Correction of the 2026-10-22 integration note.** The Settings screen does not send the whole `PrivacySettings` object: `togglePrivacy` calls `updatePrivacy({ [key]: value })`, one switch per toggle. The two approved switches therefore work unchanged. The three refused switches answer 400. The screen updates optimistically and does not roll back on error. This is a **frontend integration blocker**; the backend keeps refusing them (AD-86).
- **Resume.** The frontend has no resume call or control, and no paused state to show. This is a **frontend integration blocker**. No backend substitute (for example, resuming on sign-in) is approved, so none is built.

### 2026-10-23 — Deletion-request decisions (AD-97 to AD-102)

Approval of the non-destructive deletion-request workflow (batch LC-3), covering exactly the items below. Approvals of **reconstructed** design decisions. **Nothing in this entry approves any deletion, purge, scheduler, export, redaction, retention enforcement or legal hold.**

**Still pending (unchanged):** L-04 to L-11, L-14 to L-17, L-20; the retention part of P-12; P-13 and its periods; every retention period; any purge-time hold; purge auditing; C8-c (deferred, AD-95); the verification admin-trust policy; P-04 (not approved, AD-91); P-02 (conditional, AD-90).

| ID | Decision | Closes |
|---|---|---|
| AD-97 | **(L-01) Confirmation.** Requesting deletion and cancelling it each require fresh phone verification: a one-time code sent to the account's own phone number, checked in the same request. Codes are **bound to distinct purposes**, so a sign-in code can authorize neither deletion nor cancellation (and a deletion or cancellation code cannot sign in). The existing five-minute validity and the existing rate limits apply. A phone number supplied in the request body is never accepted | L-01, D16 (confirmation) |
| AD-98 | **(L-02) Window.** 30 days is a **waiting period**: `scheduledPurgeAt` = `requestedAt` + 30 days. It is a scheduled **eligibility** time, not a promise that a purge is implemented or will run at an exact instant. No scheduler and no purge are implemented in this batch | L-02 |
| AD-99 | **(L-03) Cancellation.** Cancellation is explicit and requires fresh purpose-bound verification (AD-97). Signing in alone never cancels a request. While a request is pending, the member may use only: deletion status, the cancellation-code request, cancellation, and logout. Sessions revoked at request time stay revoked after cancellation; old sessions are never restored | L-03, D16 (window) |
| AD-100 | **(L-12) Suspension and moderation records.** A suspended member cannot initiate a deletion request through the app while suspended; no exception and no alternate admin-initiated path is created. Reports, evidence, moderation events and audit records are unchanged by a request. Any purge-time hold remains **undecided** | L-12 (request part) |
| AD-101 | **(L-13) History.** A separate **append-only** deletion-history collection records each state change with fixed event types and identifiers only: no phone numbers, codes or free text. History is written atomically with each state change. No retention period is chosen, and purge auditing is not implemented | L-13 (request part) |
| AD-102 | **(LC-3) Scope.** Registered `USER` accounts only; one pending request per account. In one transaction: create the request and its history event, set `User.deletionPendingAt`, and revoke all existing sessions. Sockets are disconnected only after commit. While pending, the account is unavailable to other members wherever the existing inactive-account rules apply, and authorized admin moderation access is preserved. `deletionPendingAt` is separate from `accountStatus`: suspension behaviour is unchanged. **Nothing is deleted.** Cancellation restores member-facing availability but never restores old sessions | LC-3 |

*Deferred frontend integration issue (not a decision):* the frontend says "purged **within** 30 days" (`app/(app)/settings/SettingsScreen.tsx`: card text, dialog and toast). Under AD-98, 30 days is a waiting period before eligibility, so the copy is inaccurate. Frontend files are off-limits, so this is recorded and deferred.

### 2026-10-23 — Batch LC-3 deletion request: implementation notes (no new decisions)

AD-97 to AD-102 are implemented (`docs/API_CONTRACT.md` §17, `docs/DATABASE_DESIGN.md` §12). Choices made while implementing them, for review; **none of them is an approved decision**:
- **Routes.** `GET /api/settings/deletion`, `POST .../request-code`, `POST /api/settings/deletion`, `POST .../cancel-code`, `POST .../cancel` (route count 57 → 62), mounted before `/api/settings`. Request and cancellation each have their own code route, so the restricted mode admits exactly the routes AD-99 lists.
- **Restricted mode** is enforced in the one authenticator (AD-32): a pending account is refused with 409 `deletion_pending` on every REST check and every socket check, unless the route was built with `allowDeletionPending`. Only the three deletion routes are built that way.
  - Logout needs no authentication.
  - `POST /api/auth/refresh` refuses a pending account, so a restricted session ends with its access token. This is the strict reading of AD-99's list.
  - Sockets reuse the existing `unauthenticated` code.
- **Codes.** `OtpRequest.purpose` was added; an absent value reads as `sign_in`.
  - A code of another purpose, or for another number, answers exactly like an expired code (410) and counts no attempt.
  - Deletion codes are not resent by `/api/auth/resend-otp`.
  - The cooldown, caps and one-active-code-per-number rule are shared across purposes, as they were.
  - The text message uses the existing provider template; a purpose-specific template is not assumed.
  - A phone number or country code in a deletion body is refused (400), not silently dropped.
- **Order.** The code is consumed before the transaction. A failed transaction leaves no change, and the member requests a new code.
- **Availability.** One helper (`isMemberAvailable`) replaces the direct `active` checks in eligibility (like and pass targets, matches, liked-you, presence audiences), messaging (conversations, sends) and visibility (member detail, photos, the admin record photo). The discovery query also matches `deletionPendingAt: null`. A project rule pins the files that may still test `active` directly: authentication, admin, and account code.
- **Admins.** Administrators are refused (403 `admin_account`), and `promoteToAdmin` refuses a pending account. The admin user set, report views and suspension are unchanged; a pending account stays listed.
- **History.** `AccountDeletionEvent` uses the same refused-operation list as the admin audit log, declared in `src/config/deletionPolicy.js` so that member-facing code does not import admin modules. A unit test keeps the two lists equal.
- **Response shapes.** Status `{ status: "none" }` or `{ status, requestedAt, scheduledPurgeAt }`; request 201; cancel `{ status: "cancelled", cancelledAt }`; code routes answer like `request-otp` (`requestId`, `expiresInSeconds`, `maskedPhoneNumber`).

### 2026-10-23 — OTP purpose isolation and SMS templates (AD-103, AD-104)

Approval of the two fixes proposed in the post-LC-3 review of the five implementation choices, covering exactly the items below. Choices 1 to 3 of that review are kept unchanged: separate request-code and cancel-code routes, refresh refused while pending, and the socket `unauthenticated` code. Approvals of **reconstructed** design decisions. Nothing here approves purge, export, retention enforcement, redaction or verification approval.

| ID | Decision | Fixes |
|---|---|---|
| AD-103 | **Purpose-specific SMS templates.**<br>• The code's purpose is passed explicitly through the SMS adapter.<br>• Optional configuration `SMS_TEMPLATE_ID_DELETION_REQUEST` and `SMS_TEMPLATE_ID_DELETION_CANCEL`.<br>• When SMS delivery is enabled and the purpose's template is missing, the code request fails closed with HTTP 503 and **nothing is sent**. There is **no fallback** to the sign-in template.<br>• Sign-in SMS behaviour is unchanged (`SMS_TEMPLATE_ID`).<br>• Provider-side template registration and the actual message wording need staging and provider access; real delivery is **not** claimed as verified | Review item 5: a deletion code was presented with the sign-in template |
| AD-104 | **OTP codes and send limits isolated by purpose.**<br>• One active code per phone number **and purpose**.<br>• A new code invalidates only an earlier code of the same purpose; a public sign-in request never invalidates or exhausts deletion or cancellation codes.<br>• Each deletion-related purpose keeps the existing limits (five sends per hour, ten per day, the 30-second cooldown), **scoped to the account**.<br>• Sign-in keeps its own per-number cooldown and caps.<br>• Purpose binding, account binding, five-minute expiry, attempt limits, cooldowns and fail-closed validation are all preserved.<br>• The index change is deployed by an explicit, reviewable migration run on a disposable database first, **never automatically at application start** | Review item 4: cross-purpose invalidation and shared caps |

### 2026-10-23 — AD-103 and AD-104: implementation notes (no new decisions)

For review; **none of these is an approved decision**:
- **Templates.** `config.sms.templates` maps each purpose to its template, and the deletion templates are read only while SMS is enabled. The adapter's `sendOtp` takes the purpose and sends that purpose's template or nothing; the provider request carries only that template ID. `issueCode` checks the template **before** the cooldown, limits, invalidation and storage, so a missing template leaves nothing behind. Without SMS (the development fixed code), no template is needed. Unchanged: provider failures answer 503 and invalidate the new code.
- **Isolation.**
  - Uniqueness, cooldown and invalidation are per number and purpose.
  - Deletion-related cooldown and limits are read per account (`userId`, stored on those codes only) and reuse the existing configured values.
  - Account binding is checked on the stored `userId` as well as the number.
  - Sign-in limits count sign-in sends only, so deletion codes never use them up.
  - A record without a purpose matches `sign_in` in every query.
- **Migration.** `npm run db:migrate-otp-purpose` (`scripts/migrate-otp-purpose.js`, logic in `src/services/otpPurposeMigration.js`): dry run by default; `--apply` backfills and creates the indexes; `--drop-old-index` drops the old index last. It is never loaded by the application (project rule). Order and treatment of existing records: `DATABASE_DESIGN.md` §12.6.
- **Concurrency test.** `deletionFlow` now includes concurrent pending-request inserts that bypass code verification with a stub, so the requests reach the transaction together. It runs on memory here (serialized: **not** proof) and is registered for MongoDB, where it exercises the partial unique index and transaction retries (NOT EXECUTED here).

### 2026-10-26 — Backend gap closure, batch 1: documentation corrections (no new decisions)

Documentation only; no code, test, schema or contract behaviour changed, and **no decision is approved here**:
- `docs/RUNTIME_VERIFICATION.md`: dated status update (still not executed; the external gate script is syntax-checked only); 9 frontend-parity tests, not 8; in the equipped environment the unit suite expects 1412 passes plus 1 by-design skip (the store-contract audit-model test, which runs only against MongoDB), and the full run 2041 plus that skip; the two allowed skip reasons are stated explicitly.
- `README.md`: `db:migrate-otp-purpose` in the command table, and the deployment order (`db:indexes` first; OTP migration dry run, apply, check, then the explicit drop as a separate step).
- `docs/API_CONTRACT.md` §15 and its index row: dated note that P-02, P-04 and N-3 are AD-90 (conditional), AD-91 (not approved; production blocker) and AD-92.
