# The notification subsystem — implementation plan (point by point, to a working state)

> **Status: PLAN — nothing in this file is implemented.** Every claim about *today's* behaviour was read
> from the source and re-verified on **2026-09-30**; every change is a **step** with a file, a check and a
> done-criterion. When this plan and the code disagree, **the code wins** (`AGENTS.md` §12) and this file
> is corrected.
>
> **What this file is, and is not.** It is the **executable** plan: the definition of done, the complete
> gap register, the ordered steps that close each gap, the tests and the verification. It is **not** a
> second opinion on *what* the catalogue should contain — that is `NOTIFICATION_MATRIX.md` (target) and
> `NOTIFICATION_ENTERPRISE_PLAN.md` (why, and in what order the big moves land). Where those two decide a
> category, a recipient or a name, this file **implements** the decision and does not relitigate it.
>
> **Read order:** `PROJECT_DOCUMENTATION.md` §23 (the audit — 23.1–23.31) → `NOTIFICATION_SYSTEM_WORKFLOW.md`
> (how the engine works, §5 pipeline / §16 traps) → `NOTIFICATION_ENTERPRISE_PLAN.md` (the change plan) →
> `NOTIFICATION_MATRIX.md` (the editable catalogue; the events matrix and `NOTIFIERS_EXPLAINATION.md` /
> `NOTIFICATION_EVENTS_MATRIX_V2.md` are its generated readers) → **this file** (how to build it).
>
> **Authority order** (`AGENTS.md` §12): source code → DB schema → tests → `PROJECT_DOCUMENTATION.md` →
> `NOTIFICATION_SYSTEM_WORKFLOW.md` → `NOTIFICATION_ENTERPRISE_PLAN.md` → `NOTIFICATION_MATRIX.md` →
> this file.

---

## 1. The defined point — Definition of Done

The subsystem is **working** when all of these hold. They are the plan's spine; every step below exists to
close one of them, and §10 maps each back to the gaps it closes.

| # | The defined point | How it is proven |
|---|---|---|
| **D1** | **An administrator can change any notification setting through the UI.** | A test mounts the Notification Settings list, opens the edit modal and **saves**; the row changes. Today this throws `SQLSTATE[42S22]` (G-01). |
| **D2** | **One seeding file is the catalogue's source of truth**, idempotent, non-destructive, runnable on any install in any order. | `notifications:sync-catalogue --dry-run` prints the plan; a test asserts a non-default row is untouched and nothing is deleted. Today running `NotificationSettingSeeder` alone deletes 104 events (G-03). |
| **D3** | **Every event the code dispatches either has an active row or is declared no-notification on purpose** — nothing aborts silently. | `php artisan notifications:doctor --strict` exits **0** and prints the two counts. Today **8+8+2+1+1+2+16+5** names are silent for one reason or another (§3, group B). |
| **D4** | **The seat-increase workflow notifies somebody.** | A test drives `SeatChangeRequestService::request()/approve()` and asserts a `notification_history` row. Today all eight names have no settings row (G-09). |
| **D5** | **Every settings row resolves to a class and every recipient key resolves to people** with the context the dispatcher actually passes. | `notifications:doctor --strict`: `0 rows without a class`, `0 unregistered recipient keys`, and the six repaired keys (§5 W5) resolve in their real dispatch sites. Today 5 rows are classless, `participants` resolves nobody and 3 keys mis-read their context (G-17, G-35–G-39). |
| **D6** | **A queued dispatch actually queues — or the queue decision is removed honestly.** | `queue_connection` points at a real connection and a >threshold dispatch lands a job; a test asserts `Queue::fake()` receives it. Today the push always throws (G-29). |
| **D7** | **Quiet hours either work or do not exist.** | A recipient inside their quiet window is deferred (queue delay honoured) **or** the stage and its preference columns are deleted. Today the value written is never read (G-30). |
| **D8** | **A user can opt out, and a program can silence an event — or both mechanisms are removed.** | The preferences page and the program-override surface save, and the stages pick the change up (cache invalidated). Today both tables have 0 rows and no writer (G-46, G-47). |
| **D9** | **Retries retry only what failed, and run without a human.** | One failing recipient schedules **one** `failed_notifications` row; `notifications:retry-failed` is on the schedule. Today one failure schedules N rows and nothing schedules the command (G-31, G-32). |
| **D10** | **An operator can see and prune delivery records.** | A Filament surface lists `notification_history` + `failed_notifications` (with a retry action); `notifications:prune` respects a retention window. Today neither exists and `notifications` grows unbounded (G-51, G-52, G-53). |
| **D11** | **One delivery log, one renderer, one send path.** | `NotificationService`, its 803-line test, the legacy `notification_logs` writer and the second renderer are gone (or formally deprecated in one place). Today both exist (G-55, G-57, G-58). |
| **D12** | **The catalogue is gated in CI** so D3–D5 cannot regress. | The gate command runs in the suite and **never sends** unless an explicit `--send-sample` flag is passed. Today `notifications:validate` asserts 30 resolvers / 53 events and sends real messages (G-64, G-65, G-66). |
| **D13** | **Every event has a recipient test.** | A data-provider suite proves, per event, who receives it and who does not. Today no such test exists. |
| **D14** | **The three catalogues agree.** | Matrix §24.4's per-category counts equal the events matrix's; the notifier totals equal both; `NOTIFICATION_EVENTS_MATRIX_V2.md` regenerates to the same **21 categories / 327 notifications / 801 audience entries** (`backups/20261009-refresh-events-matrix-v2/generator/generate-v2.php`, 2026-10-09). |

**The minimum "working" release** is **D1 + D3 + D4 + D5 + D12** (a maintainable catalogue that actually
delivers, with a gate). D2, D6–D11, D13–D14 are the rest of the defined point and are ordered after it.

---

## 2. The measured baseline (re-verified 2026-09-30)

| Figure | Value | Source |
|---|---|---|
| Notification classes | **291 files** *(the 248 of this baseline was the 2026-09-28 measurement — corrected in session 11)* — 241 empty `BaseNotification` stubs + 3 support + 1 channel + 46 under `RecipientResolver/` | `find app/Notifications -name '*.php'` → 291; `grep -rl "extends BaseNotification" app/Notifications` → 241; `find app/Notifications/RecipientResolver -name '*.php'` → 46 |
| `notification_settings` rows | **209** (185 active / 24 inactive, 209 distinct names) | live DB |
| Recipient groups | **301** — `database` 298, `mail` 96, `whatsapp` **0** | live DB |
| Recipient resolvers | **34 registered / 22 used / 12 never asked for** | `RecipientResolverServiceProvider` + seeders |
| Pipeline stages | **15**, hard-coded in `NotificationDispatcher::registerStages()` | source |
| Config `pipeline` array | exists, **never read** | `config/notification-engine.php` + dispatcher |
| `notification_settings` columns | `id, event_name, label, category, scope_program_id, is_active, is_default, recipient_groups, timestamps` — **no `channels`, no `placeholders`** | migration `2026_07_07_120133` + `…_132248` |
| `NotificationSetting` casts | include `placeholders` and `channels` — **neither is a column** | `app/Models/NotificationSetting.php` |
| Scheduled notification commands | **15 entries** in `routes/console.php`; **`notifications:retry-failed` is not among them** | `routes/console.php` |
| Delivery tables | `notifications` (bell), `notification_history` (engine), `notification_logs` (legacy, 0 rows), `failed_notifications` (0 rows), `notification_preferences` (0), `program_notification_overrides` (0) | live DB |
| The only end-to-end checker | `notifications:validate` — asserts **30** resolvers (there are 34) and **53** events (there are 209), and **dispatches for real** | `app/Console/Commands/ValidateNotificationSystem.php:20,61,74,532` |

**Two counting bases must not be confused.** `PROJECT_DOCUMENTATION.md` §23.17 counts **event names that
no settings row can serve** → **15** (measured against the live rows). `NOTIFICATION_ENTERPRISE_PLAN.md`
§2.1 counts **every name the code can dispatch and the seeder does not cover**, including the names the two
scheduler commands *compute* for assessment types the seeder skips → **37**. Neither is wrong; they answer
different questions. §3 below lists the **union**, each line naming its basis.

---

## 3. The complete gap register

Severity: **BLOCKER** (the subsystem cannot be maintained), **HIGH** (a workflow notifies nobody, or
delivery is wrong), **MEDIUM** (silent wrong behaviour, or an operator cannot see/act),
**LOW** (hygiene, drift, dead code).

### A — The catalogue itself

| # | Gap | Sev | Evidence |
|---|---|---|---|
| **G-01** | **The settings editor cannot save.** `KeyValue::make('placeholders')` + `placeholders` in `$fillable`/casts, but no such column → every save throws. | **BLOCKER** | `NotificationSettingResource.php:240`; `NotificationSetting.php`; verified rolled-back `update()` + mounted edit action |
| **G-02** | `channels` is cast on the model but is **not a column**; the legacy path's middle term (`$setting->channels`) is always `null`, so a group with no `channels` silently becomes `database`. | MEDIUM | `NotificationSetting.php` casts; `NotificationService::sendToRecipientForGroup()` |
| **G-03** | **`NotificationSettingSeeder` deletes every `is_default` row and re-inserts only its own 105.** Run alone it removes **104 events**. | **HIGH** | `NotificationSettingSeeder.php:2343` |
| **G-04** | Five seeders, order load-bearing, 220 entries → 209 rows; 11 names appear twice and every seeder but the first silently skips an existing name. | HIGH | `DatabaseSeeder`; the five seeders |
| **G-05** | A new event needs **two** places (repo seeder **and** the live DB); no sync command exists, and the UI is broken (G-01), so production drifts. | HIGH | workflow §7.5 |
| **G-06** | No `notifications:sync-catalogue` and no non-destructive checker; `notifications:validate` is the only one and is stale + destructive. | HIGH | §2 above |
| **G-07** | `scope_program_id` exists, is set on **0** rows, is in no `$fillable`, is read by nothing. | LOW | `SHOW COLUMNS`; `grep` |
| **G-08** | Re-seeding **overwrites admin edits** on default rows (delete + insert). | MEDIUM | G-03's mechanism |
| **G-09** | The seeder writes `label`, `category` and `recipient_groups` but **no category metadata** — the admin screen prints the raw category key. | LOW | `NotificationSettingResource` |

### B — Dispatch coverage (events the code fires that cannot deliver)

| # | Gap | Sev | Evidence / basis |
|---|---|---|---|
| **G-10** | **The seat-increase workflow notifies nobody** — `{marathon,competition}.seats_increase_{requested,updated,approved,rejected}` (8 names) have **no row**. It is the only way a teacher asks for seats. | **HIGH** | `SeatChangeRequestService:142,271,353,394`; §23.17.3 |
| **G-11** | `{marathon,competition}.enrollment.mode_changed` (2) — no row. | MEDIUM | `StudentEnrollmentService:306` |
| **G-12** | `subscription.trial.converted` — no row (a conversion moves money). | MEDIUM | `SubscriptionService::endTrial($convertToPaid: true)` |
| **G-13** | `subscription.{upgrade,downgrade}.requested` (2) — no row (the *approval* half is seeded). | MEDIUM | `PlanChangeWorkflow:97` |
| **G-14** | `subscription.rejected` — no row. | MEDIUM | `SubscriptionRequestService`; §23.17.3 |
| **G-15** | `competition.result.paper_entered` — no row (a paper result is recorded and nobody is told). | MEDIUM | `PaperResultService:211` |
| **G-16** | `assessment.deleted` (the **generic** one) — dispatched, no row; the typed `{type}.deleted` exists. `App\Notifications\Assessment\Deleted` is therefore unreachable. | MEDIUM | `Models/Assessment.php`; §23.17.5 |
| **G-17** | **The five `{type}.updated` rows are inactive *and* classless** (`exam`, `training`, `self-training`, `child-training`, `marathon-competition`). Two independent reasons a typed update is silent. | MEDIUM | workflow T10; §23.17.4 |
| **G-18** | `group-{homework,assignment,exam}.{updated,deleted}` (6 names) dispatched, no rows. | MEDIUM | `Models/Assessment.php`; plan §2.1 |
| **G-19** | The typed `{starts,ends}.soon` / `{completed,results.available}` pairs the two schedulers compute for **every** assessment type, while the seeder covers only some → **16** combinations abort. | HIGH | plan §2.1 (§23.17.3's 15-name basis excludes these) |
| **G-20** | 18 **dormant** rows (15 active) — toggles for notifications nothing dispatches: `exam.*` twins, `subscription.initial.*`, `invoice.generated`, `payment.submitted`, `data.*`, `group-homework.submitted`, `plan.*`. | MEDIUM | §23.17.2 |
| **G-21** | 21 **silenced** rows — a live dispatch site, row `is_active = false`: login alert, profile update, account deletion, `marathon/competition.updated`, `message.sent`, the legacy join family. | MEDIUM | §23.17.1 |

### C — Dispatch correctness (the event fires, but with the wrong name or context)

| # | Gap | Sev | Evidence |
|---|---|---|---|
| **G-22** | **`CloseExpiredEvents` / `OpenScheduledEvents` iterate `competition` *and* `marathon-competition` but always dispatch `competition.*`** → a marathon-competition's lock/unlock/complete/results arrive under the wrong subject. | **HIGH** | the two commands; matrix §24.2 |
| **G-23** | The assessment observer dispatches **two** events per action — the typed name **and** the generic `assessment.{action}`. | MEDIUM | `Models/Assessment.php` |
| **G-24** | **`announcement.*` resolves nobody** — the dispatcher passes only `acting_user` + `program_id`, so no subject model is in context. | **HIGH** | `Models/Announcement.php:79–107`; matrix §4 |
| **G-25** | `MentalMathTimer` dispatches the generic `assessment.attempt.{submitted,timed_out}` instead of the typed subject. | MEDIUM | `Filament/Pages/MentalMathTimer.php` |
| **G-26** | `competition.results.available` is dispatched by **both** `CloseExpiredEvents` and `RankingService` — a double (dedup swallows it, but the row is noisy). | LOW | competition C-04 |
| **G-27** | `{scope}` appears in typed assessment templates but is **not a placeholder** → it prints literally. | LOW | workflow T12 |
| **G-28** | Mail/WhatsApp render in the **request/CLI locale**, never the recipient's — a cron sends English to an Arabic-only user. | MEDIUM | workflow §9.3 |
| **G-29** | `MarathonCompetitionResource::canView()` delegates to a non-existent `AssessmentResource::canView()`; `show_result` is forced to 0, which silences `results.available`. | HIGH | competition C-01, C-02 |

### D — Engine honesty

| # | Gap | Sev | Evidence |
|---|---|---|---|
| **G-30** | The `pipeline` array in `config/notification-engine.php` is **never read**; the order is hard-coded. Editing the config changes nothing. | MEDIUM | dispatcher; workflow T2 |
| **G-31** | **`queue_connection` is the literal `default`, which is not a configured connection** → the queued second pass always throws, is swallowed and logged. Nothing is ever queued. | HIGH | config; workflow T8 |
| **G-32** | **Quiet hours are a no-op** — the stage writes `recipients[id].delay_seconds`; `QueueDecisionStage` reads `$event->delaySeconds`. | MEDIUM | the two stages; T6 |
| **G-33** | `RetryStage::hasSendError()` re-reads the **batch-level** `failed_count`, so one failure schedules a retry for **every** recipient. | MEDIUM | `RetryStage.php:23,56`; T7 |
| **G-34** | `notifications:retry-failed` is **not scheduled**; `DispatchNotificationJob` has `$tries = 1`, so `release()` is dead. | MEDIUM | `routes/console.php`; the job |
| **G-35** | The batch cap is **500** and the overflow is dropped silently; no per-program volume control exists. | MEDIUM | `ThrottleStage::MAX_BATCH_SIZE` |
| **G-36** | A missing class **and** a missing channel template are only discovered at dispatch; there is no build-time check. | MEDIUM | `DispatchStage`; `CHANNEL_MAP` |

### E — Recipients

| # | Gap | Sev | Evidence |
|---|---|---|---|
| **G-37** | **`participants` resolves nobody** — it reads the deprecated `joinRequests`; `Marathon` has no such method and nothing writes `AssessmentJoinRequest`. **26 live groups** name it. | **HIGH** | `ParticipantsResolver`; matrix §2.4.1 |
| **G-38** | `teacher` reads `$context['teacher']` as a **User**; `user.student.registered` / `team.created` / `team.updated` pass a bare **`teacher_id`**, and it never reads the event key (`competition`) the participation dispatchers send. | HIGH | `TeacherResolver`; matrix §2.4.1 |
| **G-39** | `team-teacher` / `team-members` read `$context['team']`; **`classroom.*` passes only `team_id`** → all four `classroom.*` rows and `team.deleted` resolve nobody. | HIGH | the resolvers; workflow §5.2 |
| **G-40** | `assessment-owner` `match($scope)` has `default => []`, so **`scope = team` returns nobody**. | MEDIUM | the resolver; matrix §2.1.2 |
| **G-41** | Certificates pass the teacher under the key `user`, so `subscriber`/`certificate-holder` semantics are wrong. | MEDIUM | `Models/Certificate.php` |
| **G-42** | `{e}.eligibility.*` carries its subject as a model (`eligible_teacher` / `eligible_program`) that **no registered key reads** — only the actor can be notified. | MEDIUM | matrix §2.5 |
| **G-43** | **13 registered keys no row requests** *(12 at 2026-09-29; `teacher-students` joined them with W5.4)*: `portal-admin`, `portal-manager`, `portal-teacher`, `portal-teacher-assistant`, `portal-teachers`, `portal-student`, `course-owner`, `lesson-owner`, `join-request-owner`, `approver`, `enroller`, `custom`, `teacher-students`. Two are duplicates (`approver` = `acting-user`; `join-request-owner` = the `student` fallback). | MEDIUM | inventory §4.3; `notifications:doctor` `dead-resolvers` (13 of 41, 2026-09-30) |
| **G-44** | `config/participation.php` names `authorities` and `custom-user-ids`, **neither a registry key**; an unknown name is skipped with a warning. The whole `recipients` block is unwired (`ScopeConfig::getRecipients()` has no caller). | LOW | inventory §4.4; §23.29 |
| **G-45** | The target catalogue needs **19 PROPOSED keys**; **6 of them are registered as of 2026-09-30** (`scope-authority`, `scope-participants`, `teacher-students`, `event-eligible-admins`, `event-eligible-teachers`, `level-students`) and **13 remain** (`program-members`, `assessment-students`, `parent-participants`, `certificate-holder`, `record-owner`, `event-participants`, `event-students`, `eligible-teacher`, `eligible-student`, `eligible-program`, `enrollment-student`, `event-participating-teachers`, `level-owner`). | HIGH | matrix §2.4–§2.7; matrix §2.3 now reads "28 of 41 registered keys named by a row" |
| **G-46** | **One audience per group**: the *first* group to contribute a user fixes their channels, so a later group cannot add a channel to the same person. Six live rows rely on a narrower later group. | MEDIUM | `RecipientResolutionStage`; workflow §1 rule 2 |
| **G-47** | `student-teacher` is registered with **no `notifications.resolvers.dynamic` string** (only the admin label exists). | LOW | matrix §24.4 note |

### F — Preferences, overrides, quiet hours, digests

| # | Gap | Sev | Evidence |
|---|---|---|---|
| **G-48** | `notification_preferences`: **0 rows, no writer, no UI**. A user cannot opt out of anything. | MEDIUM | migration; §23.22 |
| **G-49** | `program_notification_overrides`: **0 rows, no writer, no UI**. A program cannot silence an event, add a channel or rate-limit itself. | MEDIUM | migration; §23.22 |
| **G-50** | Digest columns (`digest_mode`, `digest_frequency`, `last_digest_sent_at`) exist; **no digest code exists anywhere**. | LOW | §23.22 |
| **G-51** | The four resolvers cache for **300 s** and nothing invalidates them, so a UI would need explicit `clearCache()` calls. | MEDIUM | workflow §11 |

### G — Observability, retention, delivery truth

| # | Gap | Sev | Evidence |
|---|---|---|---|
| **G-52** | **No Filament surface** for `notification_history` or `failed_notifications` — the retry command exists, the screen does not. | MEDIUM | §23.23, §23.29 |
| **G-53** | **No retention** for `notifications`, `notification_history` or `failed_notifications`; only `notification_logs` is pruned (and it has 0 rows). | MEDIUM | §23.30 B10 |
| **G-54** | The bell query (`data->format` JSON + `read_at` ordering) is **unindexed**; the only index is `(notifiable_type, notifiable_id)`. | LOW | T18 |
| **G-55** | `channels_sent` / `channels_failed` are **never written**; a row is `sent`, never `delivered` — the history cannot tell "handed to Laravel" from "arrived". | MEDIUM | §23.30 B13 |
| **G-56** | **Two parallel send logs** (`notification_logs` legacy+pruned, `notification_history` engine+unpruned) and two template renderers. | MEDIUM | §23.29 |
| **G-57** | The audit trail is **log-file only**; nothing joins a history row to its audit line. | LOW | §23.30 B11 |

### H — Legacy and dead code

| # | Gap | Sev | Evidence |
|---|---|---|---|
| **G-58** | `app/Services/NotificationService.php` — the legacy shell, reachable **only** by tests (its single `app/` mention is an **unused `use`** at `NotificationEngineServiceProvider:32`), plus an 803-line test. | MEDIUM | inventory §2.4; §23.29 |
| **G-59** | `App\Notifications\SystemNotification` — unused scaffolding, nothing resolves to it. | LOW | §23.29 |
| **G-60** | `App\Notifications\Exam\Attempt\{Submitted,TimedOut}` — dead (the resolver rewrites `attempt` → `AssessmentAttempt`). | LOW | T20 |
| **G-61** | `App\Notifications\Assessment\Deleted` — unreachable (no row for the generic event). | LOW | §23.17.5 |
| **G-62** | Under the target catalogue: **add 7 stubs, delete 29** (matrix §24.3). | LOW | matrix §24.3 |
| **G-63** | `notification_settings` presents **silenced** (G-21) and **dormant** (G-20) rows as ordinary on/off toggles — the UI tells the operator nothing about either. | MEDIUM | §23.30 C2 |

### I — Gates and tests

| # | Gap | Sev | Evidence |
|---|---|---|---|
| **G-64** | **There is no test for the settings screen** — which is exactly why G-01 shipped. | HIGH | workflow §17 |
| **G-65** | `notifications:validate` asserts **30** resolvers (34) and **53** events (209); its `testDispatch()` wraps dispatches in a rolled-back transaction but **the send is not transactional**. | HIGH | the command; §23.30 B9 |
| **G-66** | No one-test-per-event gate exists; nothing fails in CI when an event loses its row or its class. | HIGH | workflow §17 |

### J — Documentation consistency (the living-artifact duty)

| # | Gap | Sev | Evidence |
|---|---|---|---|
| **G-67** | `NOTIFICATION_SYSTEM_WORKFLOW.md`'s header still says **312 events** and **"53 resolver keys (34 registered + 17 proposed)"** — the true figures are **319** and **34 + 19**. | LOW | the file's header vs matrix §2.3 |
| **G-68** | Monitored file counts are stale in `PROJECT_DOCUMENTATION.md` §6/§10/§39/§46/Appendix A (measured values in `SERVICES_ACTIONS_RESOLVERS_INVENTORY.md` §6.2). | LOW | inventory §6.2 |
| **G-69** | Four generated/derived notification files must be regenerated together after any catalogue change (`NOTIFICATION_EVENTS_MATRIX.md` → `NOTIFIERS_EXPLAINATION.md` → `NOTIFICATION_EVENTS_MATRIX_V2.md`, and matrix §24.4). | LOW | matrix §24.4 |

**Register size: 69 gaps.** By severity, counted from the table above: **1 BLOCKER** (G-01 — the one defect
that stops the subsystem being maintained at all), **HIGH 17**, **MEDIUM 35**, **LOW 16** (1 + 17 + 35 +
16 = 69). G-03 and G-04 are the two HIGH rows that make **D2** — the one consolidated, non-destructive
seeder — the first catalogue workstream.

---

## 4. Decisions already taken (do not relitigate)

These were decided with the user and are recorded in the matrix; this plan **implements** them.

| Decision | Where it lives |
|---|---|
| The assessment families are **eight named subjects**; `exam` and `group-assignment` get no notifications. | enterprise plan §3.0; matrix §5 |
| **Rule 0** — the scope is part of the event name: `{base}.{scope}.{action}`. | matrix §1 |
| **Enrolment is a marathon/competition concept**; `training`/`self-training`/`group-*` carry no participation audience. | matrix §2.6.3 |
| The **level dimension** applies to `marathon-competition` + `marathon-competition-training` only (Q19); the §5.4 narrowing drops the parent's teachers (Q20). | matrix §2.7 |
| A student's **joining request** reaches the event's owner **and** the student's own teacher (`student-teacher`). | matrix §16.1 / Q18 |
| The subscription audience is a **three-tier policy** (subscriber → +super-admin (decide) → +super-manager (money/access)). `trial.converted` is tier 3. | matrix §19 (rev 2.8) |
| Recipient answers taken 2026-09-30: `user.teacher.registered` → the new teacher **and** the program admins; `user.teacher.assigned` → the student **and** the assigned teacher; `user.account.{approved,suspended}` → the account holder **and** the subscription holder; `team.{created,updated,deleted}` → **teacher + members on all three**; `classroom.*` → **program admins + the team**; `contact.*` → **dropped**; `student-plan.*`/`teacher-plan.*` → **the affected student/teacher + super admins + program admins**; `§5.4` → `event-participating-teachers` added back. | this session; to be folded into the matrix (open work, §5 W2 step 8) |
| `creator` is **not** added to the participation/payment rows (no dispatcher passes it); `the owner` on §16 rows is `{auth}`, and `scope-authority` is the narrow form. | this session |
| The other no-dispatcher rows (`data.*`, `invoice.generated`, the three `user.*` rows, `message.sent`) are **disabled/OPEN** until a dispatcher exists. | this session |

---

## 5. Workstreams — the steps, point by point

Each step is a single change with a **check**. Steps are ordered by dependency, not by size.

### W0 — Unblock (must be first: nothing else is maintainable while the editor is broken)

| Step | Change | Check |
|---|---|---|
| **W0.1** | `NotificationSetting`: drop `placeholders` from `$fillable` **and** its cast; drop the `channels` cast (it is not a column). | `grep placeholders app/Models/NotificationSetting.php` → nothing |
| **W0.2** | `NotificationSettingResource`: remove the `Section('… placeholders_control')` + `KeyValue::make('placeholders')` block (line ~237–240). Nothing reads it (`grep placeholders app/` proves it). | the modal opens with no unknown field |
| **W0.3** | Add `NotificationSettingsEditorTest`: mount `ListNotificationSettings`, call the table's `edit` action, change `is_active`/`label`, **save**, assert the row changed. | test green (G-64 closed) |
| **W0.4** | Add a `recipient_type` validation rule: the value must exist in the registry (`RecipientResolverRegistry::has()`), so a typo cannot be saved. | saving `recipient_type = 'nope'` fails with a message |

**Exit:** D1.

### W1 — The engine's hard-wired facts

| Step | Change | Check |
|---|---|---|
| **W1.1** | Make the pipeline honest: `NotificationDispatcher` reads `config('notification-engine.pipeline')` (defaulting to the current list, **validated against a whitelist**), **or** delete the config array and say so in the file. Prefer reading it — one place, and the config already lists all 15. | a test asserts the configured order is used; a bogus class in the config throws |
| **W1.2** | `queue_connection`: default it to `database` (a real connection) instead of `default`, and document `NOTIFICATION_ENGINE_QUEUE_CONNECTION` in `.env.example`. | a >threshold dispatch with `Queue::fake()` asserts a job is pushed |
| **W1.3** | Fix quiet hours **or** delete them: read the per-recipient delay in `QueueDecisionStage`/`DispatchStage` (honour it by queueing with a delay), or remove `QuietHoursStage` + the preference columns (see W6). Whichever is chosen, one of the two is deleted. | a recipient inside a quiet window is deferred (or the stage is gone) |
| **W1.4** | Batch cap: make the overflow **visible** (log + a history row with `status = 'over_cap'`) instead of silently dropping; make `MAX_BATCH_SIZE` configurable. | a synthetic 501-recipient dispatch reports the dropped count |
| **W1.5** | A missing class or a channel without a template is a **warning at dispatch and a failure in the gate** (W9), not a per-recipient surprise. | the gate reports both |

**Exit:** D6, D7 (or an explicit "removed" record), G-30–G-36.

### W2 — Catalogue truth (the consolidated seeder)

| Step | Change | Check |
|---|---|---|
| **W2.1** | Create `database/seeders/notifications/Categories.php` — the 19 categories with en/ar labels (matrix §3). | file matches matrix §3's 19 |
| **W2.2** | Create `database/seeders/notifications/Catalogue.php` — the **one** data file, written from `NOTIFICATION_EVENTS_MATRIX.md` (319 entries); each entry: `label`, `category`, `active`, `groups[]` (recipient/value/channels/dedup/actions/messages en+ar). | the file's entry count equals the events matrix's |
| **W2.3** | Create `NotificationCatalogueSeeder` with the upsert semantics: missing → **insert**; `is_default = true` → **update**; `is_default = false` → **skip + report**; unknown row → **report** (disable only under `--force`); **never `delete()`**. | a test proves a non-default row is untouched and nothing is deleted |
| **W2.4** | Create `php artisan notifications:sync-catalogue [--dry-run] [--force]`; `--dry-run` prints insert/update/skip/unknown/missing. | `--dry-run` output diffed against the DB plan |
| **W2.5** | `DatabaseSeeder` stops calling the five seeders; each keeps a `@deprecated` header and **delegates** to the catalogue seeder (so an ops runbook that still runs `--class=NotificationSettingSeeder` becomes non-destructive instead of failing). | running the old command deletes nothing |
| **W2.6** | A **data migration** for live installs, keyed by `event_name`, idempotent, deleting nothing: category moves, the `child-training.* → {competition,marathon-competition}-training.*` renames, and the retired rows set `is_active = false` **with a recorded reason**. | migration applied twice is a no-op |
| **W2.7** | Drop `scope_program_id` (G-07) **or** implement it — one of the two, recorded. | column absent, or read by a stage + written by the UI |
| **W2.8** | Fold the 2026-09-30 recipient answers into the matrix (§17 `student-plan.*`/`teacher-plan.*`, §21 `team.*`, §8 `classroom.*`, §10 `contact.*`→drop, §22 `user.teacher.registered`/`teacher.assigned`/`account.*`, §5.4 `event-participating-teachers`), then regenerate the three derived files. | matrix §24.4 counts still agree; V2 regenerates to 319 / 785+ |
| **W2.9** | Surface truth in the UI: a `dormant` badge (active row, no dispatch site) and a `silenced` badge (inactive row, live dispatch site), driven by the gate's own fixture. | the settings list shows both badges on the known rows |

**Exit:** D2; closes G-03–G-09, G-63, and feeds D3.

### W3 — Dispatch coverage (make every fired event deliverable)

Order inside W3 is the severity order.

| Step | Change | Check |
|---|---|---|
| **W3.1** | **Seat-increase family (8 names)** — add the rows + any missing classes; recipients per the matrix's `participation` rules (`participant` + `{auth}`). | a test drives `SeatChangeRequestService::request()/approve()` → history rows for the asking teacher and the authority |
| **W3.2** | `{marathon,competition}.enrollment.mode_changed` (2) — add rows. | test on `StudentEnrollmentService::changeMode()` |
| **W3.3** | `subscription.{rejected,trial.converted,upgrade.requested,downgrade.requested}` (4) — add rows; `trial.converted` per the tier-3 decision. | tests through `SubscriptionRequestService` / `SubscriptionService::endTrial` / `PlanChangeWorkflow` |
| **W3.4** | `competition.result.paper_entered` — add the row (+ enable the venue defect C-02 so `results.available` can fire). | test through `PaperResultService` |
| **W3.5** | `assessment.deleted` — **decide**: add the generic row, or stop dispatching the generic name (W4.1 recommends the latter). | whichever lands, the name is accounted for in the fixture |
| **W3.6** | The 16 scheduler-computed `{starts,ends}.soon` / `{completed,results.available}` combinations — close by **fixing the schedulers to iterate only the eight subjects** (W4.2) so the 16 names disappear, rather than seeding 16 rows. | the fixture lists no such name after W4.2 |
| **W3.7** | The `{type}.updated` family — **enable + add the class**, or retire the rows (matrix §2.3 prefers enable for four, delete one). | `notifications:doctor` shows zero classless rows |
| **W3.8** | `group-{homework,assignment,exam}.{updated,deleted}` — with W4.1's subject resolver, these become part of the 8-subject set; add the rows + the 7 missing stubs (matrix §24.3). | the fixture covers all eight subjects × seven actions |
| **W3.9** | Retire or wire the 18 dormant + 21 silenced rows (the list is G-20/G-21): each row gets a decision recorded as `keep-active`, `keep-inactive (reason)`, or `retire`. | a test asserts every row carries a decision in the fixture |

**Exit:** the fixture has **zero** dispatched-but-unserved names. D3, D4.

### W4 — Dispatch correctness

| Step | Change | Check |
|---|---|---|
| **W4.1** | Add **one** `Assessment::notificationEvent(string $action): ?string` returning `"{subject}.{$scope}.{$action}"` (subject from the type, **and from the parent's type for `child-training`**; `null` for `exam`/`group-assignment`); use it in all five call sites. Drop the generic `assessment.{action}` dispatch. | the subject resolver test: `exam`/`group-assignment` → `null`; `child-training` → the two training subjects by parent; the other five → their type |
| **W4.2** | `SendAssessmentUpcomingNotifications`: use the resolver, query only the eight types, drop the generic dispatch. `CloseExpiredEvents` / `OpenScheduledEvents`: **dispatch the record's own subject + scope**, not `competition.*`. | a marathon-competition closing test asserts `marathon-competition.*`, not `competition.*` |
| **W4.3** | `Announcement`: pass the announcement (or its teacher) into the context so the audience can resolve. | an announcement dispatch resolves ≥1 recipient |
| **W4.4** | `MentalMathTimer`: dispatch the typed subject (`{subject}.{scope}.attempt.{submitted,timed_out}`) or remove the dispatch — one of the two. | the attempt events carry the subject |
| **W4.5** | `Certificate`: pass the certificate (and the holder) so `certificate-holder` resolves honestly. | the certificate test asserts the holder receives it |
| **W4.6** | Fix the competition-resource defects that gate notifications: `canView()` (C-01), `show_result` forced to 0 (C-02), the double `results.available` (C-04). | the competition workflow's C-01/C-02/C-04 close |
| **W4.7** | Replace `{scope}` in the typed templates with a real placeholder or remove it; add a gate check that every `{…}` in a seeded message is in the replacement set. | the gate reports zero unknown placeholders |
| **W4.8** | Per-recipient locale on mail/WhatsApp: render in the recipient's `pref_language` rather than the request locale. | an Arabic-preferring recipient receives Arabic mail in a CLI dispatch |

**Exit:** G-22–G-29.

### W5 — Recipients

| Step | Change | Check |
|---|---|---|
| **W5.1** | **Repair the six keys** that resolve nobody with the real context: `participants` (read `event_participations` + `student_enrollments`), `teacher` (accept `teacher_id` and read the event key), `team-teacher`/`team-members` (accept `team_id`), `assessment-owner` (handle `team`), `subscriber`/certificate key. | a resolver unit test per key with the real dispatch context |
| **W5.2** | **Retire** the redundant keys: `approver` (= `acting-user`), `join-request-owner` (the dead family), `participants` (after W5.1's replacement lands the rows on `event-participants`/`event-students`), and the four `portal-*` role aliases once W5.4 switches `program.*`. | the registry's 1:1 map still holds; the dropdown loses exactly those keys |
| **W5.3** | **Adopt** `course-owner`, `lesson-owner`, `enroller`; **keep** `custom`, `portal-student`, `portal-manager`. | each is named by ≥1 row |
| **W5.4** | Implement the **19 PROPOSED keys** (G-45) with their context contracts from matrix §2.4–§2.7. **PARTIAL — 6 of 19 shipped:** `scope-authority`, `scope-participants`, `teacher-students` (session 2), `event-eligible-admins`, `event-eligible-teachers` (`2026_09_30_000006`), `level-students` + `marathon-eligible-teachers` (2026-09-30, T31). **The level reader shipped narrower than this step asked:** `level-students` reads the enrolment that covers the event (the **parent marathon**) but resolves **nobody when the level is NULL** — the fallback to "the event's approved enrolments" was **dropped on purpose** (a level-less record has no "same level he joined", and the fallback would tell a student about a record they may not sit; recorded in `NOTIFIERS_EXPLAINATION.md` §3 and `NOTIFICATION_MATRIX.md` §2.7). | one unit test per key — shipped as `MarathonEligibleAndLevelStudentsTest` (13 tests) + `NotificationSettingsAudienceRelevanceTest`; the NULL-level row asserts **nobody**; the `level-owner` case is still open with its key |
| **W5.5** | Add `program-admins` to the `program.*` rows (replacing `portal-admins`) — a behaviour no-op when `program_id` is present, and stricter when it is not. | the program tests still pass |
| **W5.6** | Wire the **dispatching side** for every new/ repaired key: the dispatchers must pass the model (not the id) for the keys their rows name — the matrix's §24.2 list. | `notifications:doctor` resolves every row's keys against a fixture context |
| **W5.7** | Unify the resolver labels: add the `notifications.resolvers.dynamic.student_teacher` + `_desc` strings (en+ar) and a label for every new key in **both** `lang/{en,ar}/notifications.php` and `lang/{en,ar}/settings.php`. | a test asserts every registered key has both labels |
| **W5.8** | Enforce **one audience per group** at save time: refuse a second group that names the same resolver as the first with different channels (G-46). | saving the six known rows warns |

**Exit:** D5; G-37–G-47.

### W6 — Preferences and program overrides

**Decision required first: build or remove.** The plan's recommendation is **build the user page**, and
**build the program surface only if an operator asks** — the tables, models, resolvers and stages are
already written, so a UI is the whole cost.

| Step | Change | Check |
|---|---|---|
| **W6.1** | A user-facing **Notification Preferences** page (per-category and per-event toggles + channel checkboxes + quiet hours), writing `notification_preferences`, calling `UserPreferenceResolver::clearCache($userId, $event)` on save. | a test saves a preference and asserts the stage honours it |
| **W6.2** | A **program override** surface (silence an event, force opt-in, add/remove a channel, hourly limit, quiet hours), writing `program_notification_overrides`, clearing `ProgramOverrideResolver::clearCache()`. | a test silences an event for one program and asserts another program still receives it |
| **W6.3** | If either is **removed** instead: delete the table, model, resolver and stage together, and record it. | `grep` finds no reader of the deleted table |
| **W6.4** | Digests: implement or drop the three columns. | one of the two |
| **W6.5** | Wire the cache invalidation the four resolvers need, in one place (an observer or a service), so no future writer can forget it. | a test writes a preference and the next dispatch sees it |

**Exit:** D8; G-48–G-51.

### W7 — Queue, retry, delivery truth

| Step | Change | Check |
|---|---|---|
| **W7.1** | Per-recipient failure tracking: `DispatchStage` records the failed user ids; `RetryStage` schedules **one** row per failed recipient. | one failing recipient → one `failed_notifications` row |
| **W7.2** | Schedule `notifications:retry-failed` (hourly) in `routes/console.php` with a bounded `--limit`. | the schedule test asserts it |
| **W7.3** | `DispatchNotificationJob`: real `$tries`/`backoff`; remove the dead `release()`. | a retried job stops after the configured tries |
| **W7.4** | Decide the queue design honestly: keep post-send delegation (and dedup the second pass), **or** move the send behind the decide step so the queued pass is the only pass. | a >threshold dispatch delivers exactly once |
| **W7.5** | Write `channels_sent` / `channels_failed` on the history row, and use a `delivered` status where a channel can confirm. | a history row names the channels used and any failure |

**Exit:** D9; G-33, G-34, G-55.

### W8 — Observability and retention

| Step | Change | Check |
|---|---|---|
| **W8.1** | A Filament page for `notification_history` (filter by event/user/date, show channels + status) and `failed_notifications` (with a **retry** action calling the command's service). | the page lists a known row |
| **W8.2** | `notifications:prune [--days=N] [--dry-run]` for `notifications`, `notification_history`, `failed_notifications`; scheduled. | dry-run prints counts; nothing is deleted without the flag |
| **W8.3** | The bell index: a composite index for the JSON `format` filter + `read_at` ordering (or a persisted `format` column). | `EXPLAIN` uses the index |
| **W8.4** | Audit: keep a queryable reference (the batch id) on the history row so a delivery can be traced to its audit lines. | a history row exposes a batch id present in the log |

**Exit:** D10; G-52–G-54, G-57.

### W9 — The gate and the tooling

| Step | Change | Check |
|---|---|---|
| **W9.1** | Rewrite `notifications:validate` → **`notifications:doctor`**: derive the counts from the providers and the DB (**no magic numbers**), **never dispatch** unless `--send-sample`, and **exit 1** on: a dispatched name with no row; a row with no class; an unregistered recipient; a channel with no template; a template with an unknown placeholder; an assessment row outside the eight subjects; an active row with no dispatch site (unless declared). | `--strict` exits 1 on a seeded fault, 0 on the real tree |
| **W9.2** | A **dispatched-name fixture** (one row per event the code can fire, generated from the dispatch sites + the subject resolver) committed to the repo — this is what makes D3 testable. | the gate compares the fixture against the catalogue both ways |
| **W9.3** | Run `notifications:doctor --strict` in the test suite. | CI fails on a removed row/class |
| **W9.4** | **Per-event recipient tests** (data provider, one fixture per event): the expected users receive it on the expected channels, and nobody else does. | the suite covers every event in the fixture |
| **W9.5** | Keep the settings requirements in one place: `notifications:doctor` is the enforcement contract, the way `features:audit-usage` is for entitlements. | recorded in `PROJECT_DOCUMENTATION.md` §23.30 |

**Exit:** D12, D13; G-64–G-66.

### W10 — Retirement

| Step | Change | Check |
|---|---|---|
| **W10.1** | Retire `app/Services/NotificationService.php` (and its 803-line test) — after confirming nothing outside tests names it, which the inventory already proved. | `grep NotificationService app/` → the unused import is gone too |
| **W10.2** | Remove the unused `use App\Services\NotificationService;` at `NotificationEngineServiceProvider:32`. | the class looks test-only or is gone |
| **W10.3** | Delete the dead class files: `SystemNotification`, `Exam/Attempt/{Submitted,TimedOut}`, and the 29 stubs of matrix §24.3; add the 7 missing stubs. | `grep` resolves every remaining class from a name |
| **W10.4** | Unify the two logs: stop writing `notification_logs` and delete the legacy writer (or formally deprecate it in one place and prune both). | one writer exists |
| **W10.5** | Retire one template renderer: the second implementation goes with `NotificationService`. | one renderer exists |

**Exit:** D11; G-56, G-58–G-62.

### W11 — Documentation

| Step | Change | Check |
|---|---|---|
| **W11.1** | Update `NOTIFICATION_SYSTEM_WORKFLOW.md` (§6.2, §7.2, §7.4, §8, §16 T1–T20, §17) as each step lands; fix the header's **312 → 319** and **"34 registered + 17 proposed" → 34 + 19** (G-67). | a stale-figure sweep finds none |
| **W11.2** | Update `PROJECT_DOCUMENTATION.md` §23 (the audit), §6/§14/§39/§40/§46 counts, and add an entry per phase. | Rule 7's count duty satisfied |
| **W11.3** | Regenerate the three derived catalogues and keep matrix §24.4's counts equal (G-69). | D14 |
| **W11.4** | Retire this plan's steps into the workflow doc as they land, and mark this file's rows DONE; archive it at the defined point. | every row of §1 is DONE |

---

## 6. Data migration plan (live installs)

The seeder only writes fresh installs; a running install keeps its rows. Each phase therefore ships **a
migration, not only a seeder**, all keyed by `event_name`, all idempotent, **none deleting**:

| Migration | What it does |
|---|---|
| `…_catalogue_categories` | moves rows to the 19 target categories (announcement 3→9, certificate 2→6, marathon 28→21, assessment, NEW `participation`, NEW `data`, `program_level`→`program`, `team.pathstep/student` from `attendance`). |
| `…_catalogue_rename_training` | `child-training.*` → `{competition,marathon-competition}-training.*` (both subjects), updating `recipient_groups` in place. |
| `…_catalogue_disable_retired` | sets `is_active = false` **with a recorded reason** for `exam.*` (12), the generic `assessment.*` (13) and `group-assignment.*` (4) — reversible with one flag. |
| `…_catalogue_add_dispatch_rows` | inserts the names of W3 (seat-increase 8, mode-changed 2, the subscription four, `paper_entered`) as `is_default = false` so a re-seed never overwrites them. |
| `…_notification_settings_cleanup` | drops `scope_program_id` (or implements it) and records the decision. |
| `…_notifications_index` | the bell index (W8.3). |

**Rule:** a migration may **insert** and may set `is_active = false`; it may **never** `delete()` a row and
may **never** overwrite a non-default row's `recipient_groups`.

---

## 7. The execution order (the point-by-point checklist)

Dependency order. The right-hand column is the point at which the phase is **done**.

| Phase | Steps | Done when |
|---|---|---|
| **P0 — Unblock** | W0.1 → W0.4 | an administrator can save a notification setting, and a test proves it (D1). |
| **P1 — Make it truthful** | W9.1 → W9.2 (the gate first, so the rest is measurable), then W2.1 → W2.9 | one seeding file is the catalogue; `notifications:doctor --strict` runs and reports the real state (D2, partial D12). |
| **P2 — Make it deliver** | W3.1 → W3.9 (seat-increase first), W4.1 → W4.8 | every name the code fires has an active row + a class; the seat-increase workflow notifies; the schedulers dispatch the right subject (D3, D4). |
| **P3 — Make the audience right** | W5.1 → W5.8 | `notifications:doctor` reports 0 unregistered keys, 0 unresolved rows; the per-event recipient suite is green (D5, D13). |
| **P4 — Make the engine honest** | W1.1 → W1.5, W7.1 → W7.5 | queued dispatch queues (or is honestly removed); quiet hours work (or are gone); retries are per-recipient and scheduled (D6, D7, D9). |
| **P5 — Give operators the controls** | W6.1 → W6.5, W8.1 → W8.4 | a user can opt out, a program can silence an event, an operator can see and prune deliveries (D8, D10). |
| **P6 — Clean up and gate** | W10.1 → W10.5, W9.3 → W9.5, W11.1 → W11.4 | one send path, one log, one renderer; the gate runs in CI; the docs describe the finished state (D11, D12, D14). |

**Minimum shippable:** **P0 + P1 + P2 + the gate half of P1** — the catalogue becomes maintainable, every
dispatched event delivers, and CI stops it regressing. P3–P6 are the remainder of the defined point.

---

## 8. Test plan

| Test | Proves | Closes |
|---|---|---|
| `NotificationSettingsEditorTest` | the list + modal **save**; a non-default row is deletable | G-01, G-64 |
| `NotificationCatalogueSeederTest` | idempotency; a non-default row untouched; an unknown row reported; **nothing deleted** | G-03, G-04, G-08 |
| `NotificationCatalogueSyncTest` | `--dry-run` prints the exact plan; applying it is a no-op the second time | G-05, G-06 |
| `AssessmentNotificationSubjectTest` | `exam`/`group-assignment` → `null`; `child-training` → the two training subjects by parent; the other five → their type; **every dispatch site uses it** | G-23, G-25, G-18 |
| `NotificationEventCoverageTest` | the dispatched-name fixture has an active row + an existing class for every name — the E1/D3 gate | G-10…G-21 |
| `NotificationSchedulerSubjectTest` | `Close/OpenScheduledEvents` dispatch the record's **own** subject + scope | G-22 |
| `NotificationResolverContractTest` | every registered key resolves with the context its rows' dispatchers pass; the six repairs; **one test per PROPOSED key** | G-37…G-45 |
| `NotificationLevelAudienceTest` | **shipped 2026-09-30 as `MarathonEligibleAndLevelStudentsTest`** — `level-students` narrows to the event's level and reads the parent marathon's enrolments; **the NULL level resolves nobody** (the planned fallback was dropped); `marathon-eligible-teachers` reads the marathon's eligibility and skips the participation exclusion. `level-owner` remains unbuilt | G-45 (level) |
| `NotificationPreferencesTest` | a saved preference changes the next dispatch (cache invalidated) | G-48, G-51 |
| `NotificationProgramOverrideTest` | a program silences one event without touching another program | G-49 |
| `NotificationRetryTest` | one failing recipient → one `failed_notifications` row; the scheduled command drains it | G-33, G-34 |
| `NotificationQueueDecisionTest` | >threshold queues a real job on a real connection; exactly one delivery | G-31 |
| `NotificationQuietHoursTest` | a recipient inside the window is deferred (or the stage is absent) | G-32 |
| `NotificationsDoctorTest` | the gate exits 1 on each seeded fault and 0 on the tree | G-65, G-66 |
| per-event `NotificationsRecipientsTest` (data provider) | the expected users receive it on the expected channels, and nobody else | D13 |
| `NotificationEnginePipelineTest` (exists) | extended for every stage this plan touches | all engine steps |

---

## 9. Verification commands

```bash
cd /Applications/MAMP/htdocs/platform_latest

# the gate (after P1) — the single command that answers "is the catalogue sound?"
php artisan notifications:doctor --strict          # exit 0 = the defined point for D3/D5

# the catalogue plan, before applying anything
php artisan notifications:sync-catalogue --dry-run

# delivery truth for one event
php artisan tinker --execute="
  dump(App\Models\NotificationSetting::where('event_name','x')->first()?->only('is_active','recipient_groups'));
  dump(App\NotificationEngine\Models\NotificationHistory::where('event_name','x')->latest()->first()?->toArray());
"

# recipients a key resolves, with the real context
php artisan tinker --execute="
  dump(count(app(App\Notifications\RecipientResolver\RecipientResolverRegistry::class)
        ->resolve('program-admins', ['program_id' => 1])));
"

# the registry and the settings are 1:1 (34 today)
grep -c "registry->register(" app/Providers/RecipientResolverServiceProvider.php

# the catalogues agree (21 categories / 327 events / 801 recipient lines, measured 2026-10-09)
grep -c "^- \*\*"  NOTIFICATION_EVENTS_MATRIX.md          # 327
grep -c "^- \*\*"  NOTIFICATION_EVENTS_MATRIX_V2.md       # 327
grep -c "^  - "    NOTIFIERS_EXPLAINATION.md              # 801
php backups/20261009-regenerate-derived-catalogues/generator/check-catalogues.php   # 128 checks, exit 0

# regenerate what has a producer in the tree (the three /tmp scripts of 2026-09-30 are gone)
php backups/20261006-notification-seed-review/generator/generate-review.php   # NOTIFICATION_SEED_REVIEW.md, from the live table
php backups/20261009-refresh-events-matrix-v2/generator/generate-v2.php       # NOTIFICATION_EVENTS_MATRIX_V2.md, from NOTIFIERS_EXPLAINATION.md
# NOTIFICATION_EVENTS_MATRIX.md and NOTIFIERS_EXPLAINATION.md still have NO producer — apply a reviewed delta, then run
# the checker above, which holds every count to NOTIFICATION_MATRIX.md §24.4 and to the live table
# (PROJECT_DOCUMENTATION.md §23.118–§23.119)
```

`notifications:validate` must **not** be run against production until W9.1 lands (it sends for real).

---

## 10. Traceability — every gap to a step and a check

| Gap | Step | Check |
|---|---|---|
| G-01, G-64 | W0.1–W0.3 | `NotificationSettingsEditorTest` |
| G-02 | W0.2 (drop the cast) | `grep` — no `channels` cast |
| G-03, G-04, G-08 | W2.3, W2.5 | `NotificationCatalogueSeederTest` |
| G-05, G-06 | W2.4, W9.1 | `NotificationCatalogueSyncTest`, `NotificationsDoctorTest` |
| G-07 | W2.7 | column absent or read |
| G-09 | W2.1, W2.9 | the list shows category labels + badges |
| G-10 | W3.1 | seat-increase test |
| G-11 | W3.2 | mode-changed test |
| G-12, G-13, G-14 | W3.3 | subscription tests |
| G-15 | W3.4 | `PaperResultService` test |
| G-16 | W3.5 | fixture accounts for the name |
| G-17 | W3.7 | doctor: 0 classless |
| G-18 | W3.8 | 8×7 fixture complete |
| G-19 | W3.6 + W4.2 | the 16 names no longer exist |
| G-20, G-21, G-63 | W3.9, W2.9 | every row carries a decision; badges |
| G-22 | W4.2 | `NotificationSchedulerSubjectTest` |
| G-23 | W4.1 | `AssessmentNotificationSubjectTest` |
| G-24 | W4.3 | announcement resolves ≥1 |
| G-25 | W4.4 | typed attempt events |
| G-26 | W4.6 | single `results.available` |
| G-27 | W4.7 | gate: 0 unknown placeholders |
| G-28 | W4.8 | recipient-locale test |
| G-29 | W4.6 | C-01/C-02 close |
| G-30 | W1.1 | configured order is used |
| G-31 | W1.2 | job pushed |
| G-32 | W1.3 | deferred or removed |
| G-33 | W7.1 | one row per failure |
| G-34 | W7.2, W7.3 | schedule + tries |
| G-35 | W1.4 | dropped count reported |
| G-36 | W1.5, W9.1 | gate reports both |
| G-37, G-38, G-39, G-40, G-41 | W5.1 | `NotificationResolverContractTest` |
| G-42, G-45 | W5.4, W5.6 | resolver + context tests |
| G-43, G-44 | W5.2, W5.3 | registry map; adopted keys named by a row |
| G-46 | W5.8 | save-time warning |
| G-47 | W5.7 | label test |
| G-48, G-49, G-50, G-51 | W6.1–W6.5 | preferences/override/digest tests |
| G-52, G-53, G-54, G-57 | W8.1–W8.4 | page lists a row; prune dry-run; index |
| G-55 | W7.5 | channels written |
| G-56, G-58, G-59, G-60, G-61, G-62 | W10.1–W10.5 | `grep` finds one path; class resolution |
| G-65, G-66 | W9.1–W9.3 | `NotificationsDoctorTest` |
| G-67, G-68, G-69 | W11.1–W11.3 | stale-figure sweep; D14 |

---

## 11. Risks and rollback

| Risk | Mitigation |
|---|---|
| **A rename orphans rows on a stale deployment.** | The migration renames rows **and** the code switches the dispatcher in the same change; a temporary alias is deliberately **not** kept (a silent alias would hide the drift) — the gate reports any dispatch of a non-subject name. |
| **Re-seeding overwrites curated admin wording.** | Upsert touches only `is_default` rows; admin-created rows are skipped and reported; `--force` is the only destructive path and it **disables**, never deletes. |
| **The catalogue file becomes a second source of truth.** | The gate compares the file with `notification_settings` **and** the dispatched-name fixture (§9.2). |
| **Making 8 subjects × 7 actions live creates a notification flood.** | `is_active` per row and the three-tier/`scope` audiences are reviewed row by row before seeding; the per-event tests assert "and nobody else". |
| **Removing quiet hours / preferences deletes work.** | Both are inert today (0 rows). The plan prefers building the UI; removal is the recorded fallback, and the tables are dropped in one migration. |
| **The gate itself sends messages.** | `notifications:doctor` never dispatches without `--send-sample`; the old `validate` is retired, not kept as an alias. |
| **Rollback.** | No migration deletes a row; `is_active = false` is reversible with one flag; each phase's changes are listed in `PROJECT_DOCUMENTATION.md` and a `backups/<date>-<slug>/` snapshot is taken before each task (`AGENTS.md` §14.5). |

---

## 12. What this plan deliberately does not do

- **It does not change the target catalogue.** Names, categories and audiences are the matrix's; this file
  builds them.
- **It does not add a queue-based fan-out redesign.** Making the engine genuinely asynchronous is a separate
  plan; W1.2/W7.4 only make the existing decision **honest**.
- **It does not rename events outside the assessment family** — for the rest, the name is the join key and
  200+ rows depend on it.
- **It does not touch the 283 Filament toasts.** They are UI feedback, not messaging.
- **It does not invent a resolver, a category or a language without an event that needs it.**
- **It does not notify for `exam` or `group-assignment`.** The types stay usable; they get no rows.

---

## 13. Change log for this document

| Version | Date | Change |
|---|---|---|
| **1.13** | 2026-10-01 | **Twelfth session — the dedup key learned the RECORD, and the deletion messages print it (the “delete three competitions one by one” report).** The operator reported that deleting a marathon's competitions one by one notifies the authorities only **once**; the table proved it (the `#506` deletion wrote history rows **140/141** at 00:07, the next deletions of the same event name wrote nothing, and the create of **#508** reached only the two level students because the authorities still had a 32-minute-old `marathon-competition.created` row). Root cause: `DedupStage` keyed on **(user, event name)** inside `recipient_groups[0].dedup_window_minutes` (default 1440) and could not tell “the same news” from “the next competition”. **Fixed**: the key gained the **record** — `DedupStage::RECORD_CONTEXT_KEYS` maps the context key that names it (`assessment`, `marathon`) to the `notification_history.context_summary` key `HistoryStage` already writes, a stored row counts only when it names the same record, and a row/dispatch that names **no** record keeps the old suppress-everything rule (so the `competition.*` participation family and every subscription/plan event are unchanged rather than quietly widened); the stage result records `record_key`/`record_id`. **Second half (the operator's own request):** the six record-lifecycle deletion rows now print `{record_id}` right after the title (`Marathon competition “…” (#510) has been deleted …`) — a new renderer token filled from `assessment ?? competition ?? marathon`, the live rows patched by **`DeletionRecordIdRepair`** + migration **`2026_10_01_000001`** (marker inserted mechanically after the quoted title token, so both languages are handled by one rule and no translated string is retyped; `down()` removes exactly the marker; a human-owned row and a message that names no title are left alone), the two legacy seeders edited for a fresh install. Red/green: two new `NotificationEnginePipelineTest` cases are **red against the old stage**; new `DeletionRecordIdTest` **8 tests**. Live proof on marathon **#31**: creating #509/#510 delivered 6 rows each, then deleting them back-to-back wrote **156/157 (#509)** and **158/159 (#510)** — the second deletion now delivers, with the id in the message; the older #506 rows in the same window suppressed nothing. `notifications:doctor --strict` exit **0** (240 rows / 373 groups / 41 resolvers / 191 dispatched names / 0 without a row); `tests/Feature/Notifications` **147 passed / 1456 assertions**. Evidence: `backups/20261001-dedup-record-aware/`; `PROJECT_DOCUMENTATION.md` §23.40; `NOTIFICATION_SYSTEM_WORKFLOW.md` §9.4 + **T32**. |
| **1.12** | 2026-09-30 | **Eleventh session — the same marathon workflow repeated on a PROGRAM-scoped marathon, and the audience defect it exposed (T31).** The whole lifecycle was driven again in the browser, this time with `scope = program` (marathon #31, program 1, created by a portal-admin/manager/teacher from the program tab). Scope behaviour held: `marathon.created` reached the programme's owner audiences only (#1 + #1246 via `marathon-owner`), the **program's** subscription paid (`program_subscription` #152, `no_of_marathons` **0 → 1**, then a second programme-1 marathon was refused at the plan's cap — real enforcement; the 3-competition cap was hit and one competition released), `marathon.status.changed` used the programme narrowed authorities + the eligible teachers (4 distinct users), and the programme-scope eligibility tab worked for the programme admin. The run also found **T31**: `marathon-competition.created` named only `marathon-authorities` and `child-training.created` only `teacher`, so **nobody who could take part was told** — no eligible teacher and no enrolled student. Fixed by two new registered keys, `marathon-eligible-teachers` (the **marathon's** eligibility rows, deliberately **without** the participation exclusion — a participating teacher is exactly who the news is for; a marathon-competition has no eligibility rows of its own, so `event-eligible-teachers` is a permanent no-op there) and `level-students` (the **approved** enrolments whose **joined** `level_classification_id` equals the record's `level_classification`; locked record / non-`open` marathon / no level → nobody), appended to both rows through the family's two paths — `MarathonCreatedAudienceRepair` (`app/NotificationEngine/Services/`) called by migration **`2026_09_30_000007`** for an installed database, and the two legacy seeders for a fresh install (edited in the same pass, so no companion seeder is needed) — with `{en,ar}/notifications.php` + `settings.php` labels. Proven in the browser twice: a level-11 competition reached authorities + both eligible teachers + both enrolled students at that level; a level-15 competition reached authorities + both teachers and **zero** students. Registry **41 keys**; `notifications:doctor --strict` exit **0**; live counts moved to **373 groups / 370 database / 108 mail / 0 whatsapp** (240 rows, 194 active / 46 inactive, 191 dispatched names); the new/updated tests → **26 tests / 126 assertions** green (`MarathonEligibleAndLevelStudentsTest` **16** — the keys, the gates, the fresh-install wiring and the repair's append/idempotent/reverse behaviour — plus `NotificationSettingsAudienceRelevanceTest` **10**). Evidence: `backups/20260930-program-scope-marathon/`. |
| **1.11** | 2026-09-30 | **Tenth session — the whole marathon workflow driven in the browser; N-14 fixed.** A system marathon was created through the Filament modal and walked through every step: two eligible programs added **while it was still a draft**, status → `open`, a teacher participation request (3 online / 2 paper) → approval → a seat increase (+2/+1) → approval (pool **5/3**), a student request → approval, a manual enrolment of a second student, and a `marathon-competition` plus its `child-training`. Result: **24** history rows = **24** bell rows to **13** recipients, audience-correct throughout, **0** literal tokens, **0** unfilled tokens; five isolated browser sessions agreed exactly (**#1 → 11 · #153 → 6 · #154 → 1 · #157 → 1 · #1223 → 1**). It found **N-14**: `marathon-competition.{created,deleted}` name **`marathon-authorities`**, whose resolver read only `context['marathon']` — a key `Assessment::dispatchAssessmentEvent()` never sends — so both names resolved an **empty** set and `RecipientResolutionStage` aborted: creating or deleting a marathon-competition notified **nobody**. `CompetitionAuthoritiesResolver` reads `assessment ?? competition`, which is exactly why the sibling family looked healthy and nothing static could see it. **Fixed** by following the assessment's **parent marathon** off `marathon_id` (the idiom `ParticipantsResolver`/T25 already uses), with one parent-assessment hop for a child-training that inherited no `marathon_id`; proven in production (the delete emitted **0** rows before the fix, **1** after). Also fixed: `BaseNotification` declared no `$batchId` although `DispatchStage` writes it on every dispatch — a PHP 8.2 dynamic-property deprecation per notification class, now `public ?string $batchId = null`. New tests in `SilentParticipantAudienceTest` (**3**, the parent-follow proven **red** unpatched); notification + participation suites **272 tests / 2022 assertions** green; `notifications:doctor --strict` exit **0**. Evidence: `backups/20260930-marathon-e2e/`; `PROJECT_DOCUMENTATION.md` §23.38. |
| **1.10** | 2026-09-30 | **Ninth session — a clean re-execution of every event, six browser sessions, and N-13.** All 39 users' passwords were reset to `123456`, which made the two accounts earlier sessions could not open (program 52's and program 55's admins) usable. The `notifications`/`notification_history`/`notification_logs` tables were emptied first (pre-state saved) so `DedupStage`'s 1440-minute window could not mask anything: **191** names re-driven, **145** delivered, **30** active rows silent, **629** bell rows to **37** users across **145** events, **0** exceptions. Six isolated browser sessions — one per real user kind — each showed a bell badge equal to that user's unread database count (#1 super-admin **124**, #154 program-admin **26**, #1246 program-manager **45**, #153 teacher **27**, #155 student **48**, #1229 program-admin **21**) with **0** literal tokens in any rendered panel. There is no `super-manager` user and no real `portal-teacher-assistant` user (its one assignment points at a deleted user #18). The pass found **one** leaking event pair — **N-13**: `StudentEnrollmentService::removeStudent()` dispatched `{event_type}.enrollment.removed` without `creator`/`enroller`, while the row's `…-authorities` group reads *"{user_name} has been removed … by {creator_name}."*, so **9** authorities read the token on the competition row and 1 on the marathon row. **Fixed** by passing `'enroller' => $remover` — the key `{e}.enrollment.manual` already uses for the acting administrator. The instrument that caught it is the `TemplateRenderStage` runtime guard, which sees all four message fields and both locales where the sweep's own scan sees only the database preview. Evidence: `backups/20260930-notification-reexec-all-kinds/`. |
| **1.9** | 2026-09-30 | **Eighth session — the settings editor offers an event's OWN audience and its placeholders.** The recipient group's **Notify** dropdown listed every registered resolver: its filter mapped the event's `category` to resolver *categories* and started from `alwaysShow = ['system_roles','program_roles','teacher_roles','student_roles','record_owners']`, i.e. 30 of the 39 keys before any category-specific addition, so a `marathon.*` row offered **38 of 39** and only `scope_context` was ever excluded. The rule is now the event's **own family**: `getNotifyOptions()` scans the rows sharing the event name's leading segment (`marathon.*`, `subscription.*`, …) **or** its `category` (active rows first, all rows when a family has only inactive ones) and offers exactly the `recipient_type`s they name, plus the generic targeting keys **`role`**/`custom` and whatever the row being edited already names; the full registry comes back when nothing is known, and the list is never empty. `getRelevantResolverCategories()` is deleted (no other caller). Measured live: `announcement.created` **4** options, `marathon.status.changed` **9**, `subscription.trial.ending` **7**. The four message sections also gained a **placeholder hint** — *"Available placeholders for this event: …"* — listing the `{tokens}` the family already uses plus `{date}`/`{time}`, intersected with `TemplateRenderer::SUPPORTED_PLACEHOLDERS` so it can never advertise a token the renderer prints literally (`marathon.status.changed` → 11, `announcement.created` → just `{date} {time}`). The scan is memoised on the **container**, not in a `static`: the first implementation used a static and the new test suite caught it immediately (2 passed / 8 failed on stale scans) — a static would also mislead a long-running worker. New test `NotificationSettingsAudienceRelevanceTest` (**10 tests / 70 assertions**); notification suite **124 passed** (was 114); `notifications:doctor --strict` still **exit 0**; verified in the browser. Files: `app/Filament/Resources/NotificationSettingResource.php`, `lang/{en,ar}/settings.php`, the new test, and the docs. Evidence: `backups/20260930-notify-dropdown-relevance/`. |
| **1.8** | 2026-09-30 | **Seventh session — a real system marathon driven end to end; two defects fixed (N-11, N-12).** The eligible-audience keys could not be exercised while **`event_eligibilities` was empty**, so a fixture drove the requirement's three steps through the **production** paths (`Marathon::create()` draft → `EligibilityService::addEligibleProgram()` → `MarathonService::openForParticipation()`), with program 46 (MERA) eligible and program 1 (UC MAS) as the control. It proved the requirement — draft created and eligibility-while-draft reach **#1 only**, opening reaches **#1 + MERA's admin**, and program 1's admin/manager/teacher gets **nothing** — and exposed two defects no synthetic sweep could see: **N-11**, a row worded differently per audience delivered **only its first group's sentence to everyone** (`RecipientResolutionStage` discarded which group a user came from, `TemplateRenderStage` rendered `recipient_groups[0]` for every recipient, `DispatchStage` passed `recipient_groups[0]` as the group) — fixed by recording the resolving group index on the recipient and honouring it in both stages, which affects **every** multi-group row (`marathon.status.changed`, `competition.unlocked`, `{marathon,competition}.eligibility.added`, …); and **N-12**, `MarathonService`'s singleton binding passed **2** of its **3** constructor dependencies, so resolving the class threw `ArgumentCountError` — fixed by passing the missing `NotificationEngineContract`. Browser verdict: MERA's admin reads *“The marathon \"…\" is now open. Your program is eligible — you can submit participation requests.”* (bell 1), the super-admin reads the authorities' wording (bell 3), and the ineligible program shows no badge. New test `RecipientGroupMessageRoutingTest` (5 — proven red without the fix); suite **114 tests / 1244 assertions**. Evidence: `backups/20260930-eligible-audience-fixture/`. |
| **1.7** | 2026-09-30 | **Sixth session — the whole execution pass re-run with a FAITHFUL context, T27 fixed, and the browser verdict recorded.** The first harness (`backups/20260930-notification-sweep/sweep.php`) read each event's context **keys off the literal `'key' =>` text at its dispatch call site**, so it could not see the three families that build the key at runtime — the participation family's **morph key** (`$participation->event_type => $participation->event`), the assessment life-cycle's `assessment`, and `NotificationHandler::dispatchToEngine($name, $ctx)` for all of `subscription.*`. It therefore reported **43** literal-token rows, of which **42 were its own artefacts**. The new harness (`…-browser-verify/sweep2.php`) injects the key each real call site passes and re-drove all **191** names: **145 delivered** (**629** bell rows, **37** users), **0** stored rows contain a literal `{token}` (scanned across `notifications.data` **and** `notification_history.message_preview`), **0** threw, **30** active rows delivered nobody. The N-9 runtime warnings were adjudicated one by one against the real call sites and reduced to **one** genuine gap — **N-10/T27**: `subscription.trial.ending` seeds `{expiry_date}` while `SendTrialEndingNotifications` passed only `trial_ends_at`; **fixed** by passing `expiry_date` alongside it. Four **isolated** browser sessions (super-admin #1 **124**, program-admin #154 **26**, teacher #153 **27**, student #155 **48**) each matched the database badge exactly with **0** tokens in the rendered panel. Live counts are now **240 rows (194/46) / 369 groups / 39 resolvers / 191 dispatched names / 0 without a row**; `notifications:doctor --strict` → **exit 0**; notification suite **109 tests / 1234 assertions** green. Evidence: `backups/20260930-notification-browser-verify/`. |
| **1.1** | 2026-09-30 | **Two summary figures reconciled with the tables they summarise** — a self-audit straight after issue. §3's severity line did not match the register it sits under (it read `2 BLOCKER-class / HIGH 12 / MEDIUM 30 / LOW 15` = 59; the table itself carries **1 BLOCKER / 17 HIGH / 35 MEDIUM / 16 LOW = 69**), and §5's step total was given as "~60" where the workstream tables hold **71** numbered steps (`W0.1` … `W11.4`). No gap, step, decision, test, phase or evidence changed — only the two totals, so the file's arithmetic now holds. |
| **1.6** | 2026-09-30 | **Fifth session — the defects the execution pass found are fixed (N-4 … N-9).** *Rendering:* `TemplateRenderer::buildReplacements()` now reads the Assessment from its **morph key** (`context['assessment'] ?? context['competition']`, N-6) and aliases the shapes the dispatchers actually pass (`{user_name}` ← `user ?? participant ?? student`, `{creator_name}` ← `creator ?? enroller`, `{program_name}` ← `program_name ?? program ?? eligible_program`, N-7/N-5); `TemplateRenderStage` logs any token that survives a render and records it as `unfilled_tokens` (the N-9 runtime guard). *Audiences:* new `SilentParticipantAudienceRepair` (+ migration `2026_09_30_000005` + `SilentParticipantAudienceSeeder`) repoints the **ten** rows whose `participants` audience can never resolve (N-8), and `ParticipantsResolver` follows a marathon-competition's **parent marathon**. *Labels:* all **seven** registered-but-unlabelled keys (`scope-authority`, `scope-participants`, `teacher-students`, `marathon-authorities`, `competition-authorities`, `participant`, `enroller`) now have en + ar `settings.php` labels, guarded by a new test (N-4/T21). *Context:* `EligibilityService` passes `program_name` on all four eligibility dispatches; the old record's claim that it passed neither `program_name` nor the event model was **wrong** and is corrected. `notifications:doctor --strict` still exits **0**; the notification suite is **89 tests / 1154 assertions** green; a 40-row re-probe with the real context delivers **0** literal tokens. Files and evidence: `backups/20260930-notification-fixes/`. |
| **1.5** | 2026-09-30 | **Fourth session — every event executed (191/191) and the bells checked in four separate browser sessions.** 134 of 191 delivered at least one notification (600 rows, 37 users); 41 active rows delivered nobody; the message-correctness check was done with three passes because the first two were polluted (a repo scan cannot see a computed context key; `DedupStage` suppresses a re-dispatch). Findings **N-6** (17 `competition.*` events deliver literal `{assessment_title}` — the renderer reads `context['assessment']`, the dispatcher passes `competition`), **N-7** (three tokens no dispatcher supplies: `{creator_name}`, `{user_name}`, `{program_name}`), **N-8** (15 active rows name `participants` for subjects that cannot have participations) and **N-9** (`--send-sample` cannot see any of it). Harness kept at `backups/20260930-notification-sweep/`. |
| **1.4** | 2026-09-30 | **Third session — an independent verification pass; no application file changed.** The session-2 claims were re-run from the outside (gate `exit 0` at 240 / 194 / 46 / 357 / 37 / 191, **66 tests / 1031 assertions** green, **D1 proven again in the browser** with a real saved edit, the bell rendering the four engine deliveries end-to-end) and two defects were added to §14's register as **N-4** (three registered resolver keys with no label in `lang/*/settings.php`, printed raw by the admin UI) and **N-5** (a delivered message can carry `{program_name}` literally because the gate checks tokens are *fillable*, not *supplied*). `NOTIFICATION_SYSTEM_WORKFLOW.md` was re-measured against the live database in the same pass: its header, §6.2, §7.2, §8, §12, §13 and §16 now carry the post-P0–P2 figures and the closed traps (T1, T9, T11) with the old values kept as the 2026-09-29 baseline. |
| **1.3** | 2026-09-30 | **Second implementation session — P2 essentially complete, plus W9.3.** The catalogue's writers landed (W2.2–W2.4 for the coverage scope: `Catalogue.php`, `CatalogueSynchroniser`, the seeder and `notifications:sync-catalogue`), every name the code dispatches now has a settings row (**22 → 0**), the assessment family got its single subject resolver (W4.1, generic fallback removed) and the two retired subjects were retired on **both** delivery paths, `announcement.*` stopped being a silent no-op (W4.3 + the first three W5.4 keys), the six recipient keys were repaired (W5.1) and the gate now runs **in the suite** (W9.3). Two new findings are recorded in §14: a migration-only retirement is undone by `db:seed` on a fresh install, and the fixture has to be told about a family whose name is built at runtime. §14 carries the gate's output and the exact remaining split. |
| **1.2** | 2026-09-30 | **First implementation session — P0 complete, P1/P2/P4 started.** P0 (W0.1–W0.4) closed D1. P1's gate (W9.1, W9.2) is live as `notifications:doctor` and `notifications:validate` now delegates to it. W1.1/W1.2, W3.7, W4.7 and W7.2 landed. See **§14** for the exact state and the gate's own output. |
| **1.0** | 2026-09-30 | First issue. Consolidates the four sources (`PROJECT_DOCUMENTATION.md` §23.17/§23.29/§23.30, `NOTIFICATION_SYSTEM_WORKFLOW.md` §5/§16, `NOTIFICATION_ENTERPRISE_PLAN.md` §1–§7, `NOTIFICATION_MATRIX.md` §2–§25) and the 2026-09-30 recipient decisions into **69 numbered gaps**, a **14-point Definition of Done**, **12 workstreams / 71 numbered steps**, a 6-phase execution order, a data-migration plan, a 16-test plan, a complete gap→step→check traceability table and a risk/rollback register. Every claim about today's behaviour was re-verified against the source on 2026-09-30. **Nothing was implemented.** |

---

## 14. Progress log

**Status: IN PROGRESS.** Everything below was implemented, verified and is in the working tree.
Nothing here is aspirational — each line names the artefact and the check that proves it.

### Done

**Session 1 (P0, the gate, the engine's hard-wired facts).**

| Step | What landed | Verified by |
|---|---|---|
| **W0.1** | `NotificationSetting`: `placeholders` dropped from `$fillable` and from the casts; the `channels` cast dropped (neither is a column). | `tests/Feature/Notifications/NotificationSettingsEditorTest` — 7 tests green |
| **W0.2** | `NotificationSettingResource`: the `KeyValue::make('placeholders')` field and its section wrapper removed; the two control toggles stay in a `Control` section. | the edit modal's mounted state carries no `placeholders` key |
| **W0.3** | `NotificationSettingsEditorTest` — mounts the real list page, opens the edit action and **saves**. | 7/7 pass; the save test is the regression guard for G-01 |
| **W0.4** | The `recipient_type` select validates against `RecipientResolverRegistry::has()`; a forged key is refused at save. | `an unregistered recipient type is refused` + its positive control |
| **W1.1** | `NotificationDispatcher` reads `config('notification-engine.pipeline')` and validates it against a new `ALLOWED_STAGES` whitelist; an unknown entry throws. `NotificationPipeline::getStages()` added so the order is observable. | `tests/Unit/NotificationPipelineConfigTest` — 4 tests green |
| **W1.2** | `queue_connection` default `default` → **`database`**, documented in `.env.example`. | the config test asserts the shipped pipeline; the default is asserted by `G-29`'s fix being a real connection name |
| **W9.1** | `notifications:doctor` — 10 derived checks (pipeline, classes, recipients, channels, placeholders, duplicates, missing-rows, dormant-rows, silenced-rows, dead-resolvers), `--strict` exits 1, `--send-sample` opt-in only, `--json`. | `tests/Feature/Notifications/NotificationsDoctorTest` — 12 tests green |
| **W9.2** | `App\NotificationEngine\Support\DispatchedEvents` — the dispatched-name fixture: a repository scan for literal dispatch sites **plus** the runtime-built families, both annotated. | the fixture test asserts the family names are found and that noise (`a.b`, `tabChanged`, `test.*`) is not |
| **W9.1 (retire)** | `notifications:validate` reduced to a deprecated alias that delegates to the doctor — the wrong hard-coded figures (30 resolvers / 53 events) and the real sends are gone. | `the deprecated validator delegates and still sends nothing` |

**Session 2 (P1's catalogue writers, P2's coverage and correctness, W9.3).**

| Step | What landed | Verified by |
|---|---|---|
| **W2.2 / W2.3 / W2.4 (coverage scope)** | `database/seeders/notifications/Catalogue.php` (31 dispatch-coverage rows, keyed by `event_name`), `CatalogueSynchroniser`, `NotificationCatalogueSeeder` and `php artisan notifications:sync-catalogue [--dry-run] [--force]`. One rule for all three writers: missing → **insert**; `is_default = true` → **update**; `is_default = false` → **skip + report**; unknown → **report**, disabled only under `--force`; **never delete**. | `tests/Feature/Notifications/NotificationCatalogueSeederTest` — 13 tests, including `it deletes nothing at all` and `it never overwrites a row a human owns` |
| **W2.6 (partial — the retirement half)** | Migration `2026_09_30_000002_add_dispatch_coverage_notification_settings.php` inserts the missing names on a running install (insert-only, keyed by name, `down()` scoped to its own non-default rows). **Corrected 2026-10-20:** the migration is pinned to its own **22 W3 names** (`private const NAMES`); it used to walk the whole `Catalogue`, so a fresh install marked the 18 rows later migrations add `is_default = false` (40 custom against live 22) and `CatalogueSynchroniser` skipped them forever. Later migrations now insert their own rows as platform-owned; both paths hold **218 default / 22 custom** (`PROJECT_DOCUMENTATION.md` §23.159). | applied; the gate's `missing-rows` check went from 22 failures to PASS |
| **W3.1–W3.8** | Every name the code dispatches now has a settings row: the seat-increase family (8), `{marathon,competition}.enrollment.mode_changed` (2), the subscription four, `competition.result.paper_entered`, the `{subject}.{starts.soon,ends.soon}` pairs, `group-*.{updated,deleted}`, `assessment.deleted` — **31 rows** in the catalogue, and ~30 `BaseNotification` stubs so each active row resolves to a class. | the gate: `dispatched names: 191`, `dispatched without a row: 0` |
| **W3.7** | Four missing classes added (`Training/Updated`, `ChildTraining/Updated`, `MarathonCompetition/Updated`, `SelfTraining/Updated`); `exam.updated` **retired** by migration (non-destructive). | the gate's `classes` check went from 5 failures to PASS |
| **W3.9** | `DispatchedEvents::declaredDormant()` — every active row that no dispatch site can reach is **declared with its reason and the decision that owns it** (19 rows). The `dormant-rows` check fails on an undeclared row and reports a declared one. | the gate's `dormant-rows` check is PASS with `dormant-declared 19` as INFO |
| **W4.1** | `Assessment::notificationSubject()` / `notificationEvent()`; `Assessment::dispatchAssessmentEvent()` fires **one** name (the generic `assessment.{action}` fallback is gone) and passes `team_id` + `team`; `SendAssessmentUpcomingNotifications` rewritten around the resolver (`whereIn('type', Assessment::NOTIFIABLE_TYPES)`, no generic, no duplicate `completed`/`results.available`); the two scheduler commands read the same resolver. | `tests/Feature/Notifications/AssessmentNotificationSubjectTest` — 9 tests |
| **W4.1 (retirement)** | Migration `2026_09_30_000003_retire_generic_and_retired_assessment_rows.php` retires the five generic names, every `exam.*` and every `group-assignment.*` (`is_active = false`, reversible, never deletes) — **and** `CleanupLegacyNotificationEventsSeeder` applies the same predicate, because the seeders run after the migrations on a fresh install. | 46 inactive rows; `NotificationCatalogueGateTest` proves the gate exits 0 on a fresh seed |
| **W4.3** | `Announcement` dispatches through one method and passes the record, its `scope`, its `teacher` and `teacher_id`; `AnnouncementAudienceRepair` (a service, so both delivery paths share it) repoints the three rows at `scope-participants` + `scope-authority`, with migration `…_000004` for an existing install and `AnnouncementAudienceSeeder` for a fresh one. | `tests/Feature/Notifications/AnnouncementAudienceTest` — 8 tests (program / teacher / system scopes) |
| **W4.7** | `TemplateRenderer` gained the nine placeholders the seeded templates use but the renderer never filled (`{scope}`, `{status}`, `{reason}`, the three seat counters, the three grace fields) via a new `SUPPORTED_PLACEHOLDERS` constant. | the gate's `placeholders` check is PASS — it was reporting user-visible `{scope}` literals |
| **W5.1** | Six keys repaired: `participants` reads `event_participations` + `student_enrollments` (its team fallback uses the shared reader), `teacher` accepts `teacher_id` and the event key, `team-teacher` / `team-members` accept the model **or** the id **or** the owner model's relation (`Team` has no `users()` — its members are on `students()`), `assessment-owner` handles `scope = team`, and the certificate half is recorded as pending. | `tests/Feature/Notifications/RecipientResolverRepairTest` — 9 tests |
| **W5.4 (3 of 19 keys)** | `scope-authority`, `scope-participants` and `teacher-students` implemented, registered (34 → **37**) and labelled in en + ar; `BaseRecipientResolver` gained `resolveTeacherFromContext()` / `studentsOfTeacher()` so the new keys reuse the repaired lookups instead of re-deriving them. `student-teacher`'s missing label (G-47) is added too. | `AnnouncementAudienceTest`: registration, per-scope mapping, and an unknown scope resolving nobody |
| **W4.6 (the half that is real)** | `RankingService::rankCompetition()` took an `$announceResults` flag and dispatches `{subject}.results.available` through the one subject resolver — it shipped the literal `competition.results.available` (a marathon-competition announced as a competition) and duplicated `CloseExpiredEvents`' dispatch, once even with `show_result` off (workflow C-04/C-03). The close command passes `false`; the paper-result path keeps the default. | `AssessmentNotificationSubjectTest::test_the_ranking_announces_results_under_the_records_own_subject_once` |
| **W4.6 (the C-01/C-02 correction)** | **C-01 is not a defect:** `MarathonCompetitionResource::canView()` does not throw — `Filament\Resources\Resource::canView(Model)` exists at `vendor/filament/filament/src/Resources/Resource.php:303` and late static binding resolves it on `AssessmentResource`. The real issue is the **absent `AssessmentPolicy`** (the check is a no-op), which is **authorization**, not notifications. **C-02 is a product decision:** `BaseResource:1918` hard-codes `show_result = 0` for a standalone competition/exam/marathon-competition — a visibility default, deliberately unchanged; the fix that matters for notifications is C-04's removal of the ungated second dispatch. | source read + an executed call to both methods; recorded in `PROJECT_DOCUMENTATION.md` D-51 |
| **W7.2** | `notifications:retry-failed --limit=50` is now scheduled hourly (it was invoked by nothing). | `routes/console.php` |
| **W9.3** | `tests/Feature/Notifications/NotificationCatalogueGateTest` — seeds a fresh install and requires `notifications:doctor --strict` to exit 0; asserts every dispatched name has a row after seeding and that the figures are derived. | the test is the CI gate for D12 |

**Test totals for session 2: 66 tests, 1031 assertions, all green** (13 catalogue, 12 editor, 12 gate, 9 doctor, 9 resolver repair, 9 subject, 8 announcement, 3 catalogue gate, 4 pipeline — some counts overlap between files).

### Session 3 (2026-09-30) — independent verification pass, **no application file changed**

Everything session 2 claimed was re-tested from the outside, in the browser and on the command line,
against the running app (`http://127.0.0.1:8000`, DB `platform_latest_`, users from the live table,
password `123456`). **Every session-2 claim held**, and the search turned up two live defects the gate
cannot see (N-4, N-5 below).

| Verified | Evidence |
|---|---|
| The gate still exits **0** with the session-2 figures | `php artisan notifications:doctor --strict` → `rows: 240 (194 active / 46 inactive) groups: 357 resolvers registered: 37 pipeline stages: 15 dispatched names: 191 dispatched without a row: 0`, `all checks passed`, exit `0` |
| The test suite is green, at the stated size | `php artisan test tests/Feature/Notifications tests/Unit/NotificationPipelineConfigTest.php` → **66 passed (1031 assertions)** |
| **D1 in a browser, not only in a test** | `/admin/login` → `/admin/notification-settings` → a row's **Edit** → **Save changes**: the modal closes, no `SQLSTATE`, and `announcement.created.updated_at` moved `02:11:04 → 03:28:12` |
| The bell renders real engine output end-to-end | `/program` as `admin@example.com` (user 1): badge **4**, slide-over lists `Marathon Eligibility Removed`, `Account Approved`, `Marathon Status Changed`, `Marathon Eligibility Added`; `notifications` has exactly those 4 rows, `notification_history` the 5 send records behind them (channel `database` on all) |
| The retired rows are visible as retired | the list shows `Assessment Created` / `Assessment Approved` / `Assessment Rejected` **Active = ✗**, `System Default = ✓` — the retirement is a toggle, not a delete |
| The queue fix is live | `config/notification-engine.php:41` → `env('NOTIFICATION_ENGINE_QUEUE_CONNECTION', 'database')` |
| W7.2's schedule entry is live | `php artisan schedule:list` → `0 * * * * php artisan notifications:retry-failed --limit=50` |
| WhatsApp is genuinely unavailable | `WhatsAppService::isLoggedIn()` → `false`; 0 of **373** groups name the channel (re-measured 2026-09-30; it was 357 at this pass) |
| The editor's `placeholders` bug is gone from the form | the edit modal mounts no `placeholders` field (`NotificationSettingsEditorTest` asserts the same) |

**Also verified by reading the tree:** `database/seeders/notifications/Catalogue.php` holds **15 event
rows** (the dispatch-coverage set — `assessment.deleted`, the four `{competition,marathon-competition}.{starts,ends}.soon`,
`marathon-competition.{locked,unlocked,assigned,completed,results.available}`, `subscription.rejected`,
`subscription.trial.converted`, `{marathon,competition}.enrollment.mode_changed`,
`competition.result.paper_entered`) and `DatabaseSeeder` now runs the catalogue seeder plus the cleanup
seeder **after** the five legacy seeders — which is what makes N-1's fix hold on a fresh install.

### Session 4 (2026-09-30) — **every event executed**, and what four user kinds actually received

The user's instruction was to execute all notification events and check, per user kind, what arrives
and whether the message is right. It was done in three passes, and only the third is trustworthy for
message correctness:

| Pass | What it did | Why it is not sufficient alone |
|---|---|---|
| **S1 — sweep** (`backups/20260930-notification-sweep/sweep.php`) | scanned the repository for every event name's dispatch call, read the `'key' =>` entries in that call, filled them from live rows, dispatched all **191** names | the scan cannot see the **computed** context key (`$enrollment->event_type => $event`), so it under-supplied some values |
| **S2 — verify** (`verify.php`) | re-dispatched **81** events with the **exact** context copied out of their dispatch sites | `DedupStage` (1440 min) suppressed every event S1 had already delivered to the same user |
| **S3 — probe** (`probe.php`) | re-dispatched the swallowed families to a recipient with **no history for them**, real context, so dedup cannot interfere | — **this is the pass the findings below come from** |

**Measured outcome of S1 (the only pass that covers all names):** 191 dispatched names → **134 delivered
at least one notification**; **41 active rows delivered nobody**; 16 names are inactive (their rows are
turned off, correctly). 600 rows landed in `notifications` across **37 distinct users**.

**The four browser sessions** (separate browser profiles/incognito partitions, real logins, password
`123456`, bells read live) — every badge matched the database exactly:

| User kind | Account | Bell badge | What the bell showed |
|---|---|---|---|
| super-admin | `admin@example.com` (#1) | 113 | all four `/admin/notification-settings` rows, assessment/marathon/course/lesson/announcement families intact |
| program admin + teacher | `abdelrahim.ahmed8dewde5@gmail.com` (#154) | 23 | `Competition Join Request Submitted` → **`…for competition "{assessment_title}" by student-d.`** |
| teacher | `teacher@domain.com` (#153) | 35 | 13 `competition.*` items with **literal `{assessment_title}`**, plus `{creator_name}`, `{user_name}`, `{program_name}`; `Competition Created … (Scope: program)` renders correctly |
| student | `student-a@domain.com` (#155) | 50 | the same literal tokens on the student-facing half; the marathon twins reasonible where the context key matched |

### The four findings of session 4 (N-6 … N-9)

| # | Finding | Evidence |
|---|---|---|
| **N-6** | **`{assessment_title}` is literal in the entire `competition.*` participation family — 17 events.** `TemplateRenderer::buildReplacements()` fills `{assessment_title}` **only** from `$context['assessment']`, but every participation dispatcher passes the event model under its **morph key** (`'competition' => $event`, or `'marathon' => $event`). The marathon twins render because the renderer also reads `context['marathon']` for `{marathon_title}` — the competition side has no matching branch. Affected: `competition.{enrollment.{submitted,manual,mode_changed,approved,rejected,removed}, participation.{submitted,approved,rejected,cancelled}, payment.{submitted,verified,rejected}, seats_increase_{requested,updated,approved,rejected}, seat.full, eligibility.{added,removed}}`. | S3 probe: every one of those rows delivered with `{assessment_title}` intact; verified in the bell of 3 different user kinds |
| **N-7** | **Three templates ask for a token their dispatcher never supplies** — `{creator_name}` (`enrollment.manual` passes `enroller`), `{user_name}` (`payment.submitted` passes `participant` + `acting_user`), `{program_name}` (`{e}.eligibility.*` passes `eligible_program`). The marathon twins show the same three. | S3 probe + the program-admin bell (`Program "{program_name}" …` on the eligibility rows) |
| **N-8** | **15 active rows name the `participants` audience for a subject that can never have participations.** `config/participation.php` and the morph map define participation for **`marathon` and `competition` only**, so `assessment.completed`, `assessment.results.available`, `team.pathstep.created`, `team.deleted`, `{training,self-training,child-training}.{starts,ends}.soon` and `marathon-competition.{starts,ends}.soon,unlocked,completed,results.available}` resolve **nobody, ever** (a marathon-competition's participation lives on the **parent marathon**). 24 active rows name `participants` in total; 15 are structurally silent. | S1: those 15 are in the 41 `active but nobody` list; the audience table was read with `recipient_groups`; matrix §2.6.3 predicts exactly this |
| **N-9** | **`notifications:doctor --send-sample` cannot detect any of this**: it dispatches every name with `['acting_user' => null]`, so almost every resolver resolves nobody and almost nothing is written — it tests the pipeline, not the catalogue. The W9.1 gate has no way to see N-6/N-7 either (a *fillable* token, not a *supplied* one). | `NotificationsDoctor::sendSamples()` |

The remaining 26 of the 41 `active but nobody` names are **not** catalogued defects: 30 of them are
explained by the sweep's own limits (the `subscription.*` payloads are built into a variable and were
dispatched with no context; no `competition`-type assessment row exists in this database, so
every `competition.*` lifecycle/scheduler row has no participations to resolve; `attendance.*`,
`certificate.created`, `classroom.*`, `user.teacher.assigned` and `file.storage.limit.reached` need
context keys the scan did not see). They are recorded as **unverified for audience**, not as defects,
and the honest next step is the per-event recipient fixture (W9.4) had it existed.

### Session 5 (2026-09-30) — the fix pass: N-4 … N-9

The defects sessions 3 and 4 found are fixed. The counts do **not** move (240 rows / 357 groups / 37
resolvers / 191 dispatched names) because the changes are rendering, audiences and labels — never the
number of rows.

| Finding | Fix | Verified by |
|---|---|---|
| **N-6** | `TemplateRenderer::buildReplacements()` reads the Assessment from `context['assessment'] ?? context['competition']`, so the morph-keyed participation dispatchers render `{assessment_title}`. **One** renderer change covers all 17 events. | `tests/Feature/Notifications/TemplateRenderingTest`; 40-row re-probe → **0** literal tokens |
| **N-7** | The renderer fills `{user_name}` from `user ?? participant ?? student`, `{creator_name}` from `creator ?? enroller`, `{program_name}` from `program_name ?? program ?? eligible_program` — one mapping for every dispatcher instead of a copy per site. | `TemplateRenderingTest` (11 tests) |
| **N-5** | `EligibilityService` passes `program_name` on all four eligibility dispatches (the eligible program, or the eligible teacher's program) **and** the renderer reads `eligible_program`. The old record's context list (`marathon_id, marathon_title, program_id, acting_user_id`) was **wrong** — corrected in §“The four findings” above and in `NOTIFICATION_SYSTEM_WORKFLOW.md` §16/T22. | re-probe + `TemplateRenderingTest` |
| **N-4 / T21** | All **seven** registered-but-unlabelled keys got en + ar labels in `settings.php` `recipient_type_labels`. Writing the guard test is what surfaced the extra four. | `AnnouncementAudienceTest::test_every_registered_key_has_a_label_in_the_settings_file_the_admin_ui_reads()` — red before, green after |
| **N-8** | Ten rows repointed by `SilentParticipantAudienceRepair`: `team.pathstep.created` → `team-members`, `team.deleted` → `teacher`, and `assessment.{completed,results.available}` + `{training,self-training,child-training}.{starts,ends}.soon` → `scope-participants`. The five `marathon-competition.*` rows keep `participants`, and `ParticipantsResolver` now follows `marathon_id` to the parent marathon. Two delivery paths (migration + seeder), like `AnnouncementAudienceRepair`. | `tests/Feature/Notifications/SilentParticipantAudienceTest` (9 tests); live DB re-read |
| **N-9** | A **pre-dispatch** gate over the source is not viable: the runtime-built families (`$assessment->notificationEvent(…)`, `"{$participation->event_type}.…"`, the `subscription.*` variable funnel) have no literal call site, and a measured static scan flags the whole **correct** `subscription.*` family (`backups/20260930-notification-fixes/measure-n9.php`). Added instead: `TemplateRenderer::unfilledPlaceholders()` + a warning in `TemplateRenderStage` (`unfilled_tokens` in the stage result) — zero false positives by construction. `--send-sample` is unchanged. | `TemplateRenderingTest` (2 tests); 40 re-probes → **0** warnings |
| **Recorded deviation** | `team.deleted` names **`teacher`**, not the matrix's `team-members`: `Team` has no soft deletes, so the row and its `team_user` pivot are gone before the event resolves — `teacher_id` is the only surviving link. | `SilentParticipantAudienceTest` + the resolver read (`NOTIFICATION_SYSTEM_WORKFLOW.md` §16/T25) |

**Still pending from this pass:** the three-party `{e}.eligibility.*` audience split of matrix §16.5
(`eligible-teacher` / `eligible-student` / `eligible-program`), which is what would let one row stop
borrowing the program wording for the teacher variant.

**Gate after the fix pass (same counts, exit 0):** `php artisan notifications:doctor --strict` →
`rows: 240 (194 active / 46 inactive) groups: 357 resolvers registered: 37 pipeline stages: 15
dispatched names: 191 dispatched without a row: 0`, all checks passed. **Tests: 89 passed (1154
assertions)** in `tests/Feature/Notifications` + `tests/Unit/NotificationPipelineConfigTest`.

### The gate's own output, after session 2 (**exit 0**)

```
rows: 240 (194 active / 46 inactive)   groups: 357   resolvers registered: 37   pipeline stages: 15   dispatched names: 191   dispatched without a row: 0

PASS  pipeline         15 stages, all known and in the documented order
INFO  classes-retired  1 inactive row has no class (retired — never dispatched)
PASS  classes          every active settings row resolves to an existing notification class
PASS  recipients       every recipient group names a registered resolver
PASS  channels         every recipient group has at least one known channel
PASS  placeholders     every template token is one the renderer can fill
PASS  duplicates       no event name is seeded twice
PASS  missing-rows     every dispatched name has a settings row
INFO  dormant-declared 19 active rows are declared dormant, with a reason (W3.9 register)
PASS  dormant-rows     every active row has a dispatch site or a recorded declaration
INFO  silenced-rows    16 inactive rows are still dispatched by the code (turned off on purpose?)
INFO  dead-resolvers   13 of 39 registered resolver keys are named by no row
```

**The same figures, and the same exit 0, on a freshly seeded database** — which is the point of
`tests/Feature/Notifications/NotificationCatalogueGateTest`, and was not true before this session:
see the finding below.

The two failures session 1 ended on are closed: **W3** (the 22 names without a row → `missing-rows`
PASS) and **W3.9/W4.2** (the 43 undeclared dormant rows → the scheduler's subject is fixed and the
remaining unreachable rows are **declared**, so `dormant-rows` PASSes with 19 declared).

### Two findings of session 2 (added to the register's spirit — each is a way the work can silently undo itself)

| # | Finding | Consequence if ignored |
|---|---|---|
| **N-1** | **A retirement that ships only as a migration is undone by `db:seed` on a fresh install.** Migrations run against an empty table and the seeders run afterwards, so the legacy seeders re-created all 22 retired rows as `is_active = true` — a fresh install (and every CI database) came up with 19 phantom rows and a **failing** strict gate. | `DispatchedEvents::isRetiredName()` is now the single predicate, applied by the migration for an existing install **and** by `CleanupLegacyNotificationEventsSeeder` (which runs last) for a fresh one. |
| **N-2** | **The same trap for a row rewrite.** The `announcement.*` audience fix shipped as a migration would be reverted by the seeders on a fresh install (the gate reported 15 unused resolver keys on a fresh seed against 13 on the live database). | `AnnouncementAudienceRepair` is a service; `…_000004` and `AnnouncementAudienceSeeder` both call it, and both paths now report identical figures. |
| **N-3** | A family's name **built at runtime** is invisible to the fixture's repository scan, so removing a literal dispatch can make a live row look dormant. | The `announcement.*` family is declared in `DispatchedEvents::computed()` with the reason, exactly as the scheduler families were in W4.2. |
| **N-4** *(session 3 — browser)* | **A newly registered resolver key has no label in the file the admin UI reads.** W5.4's three keys (`scope-authority`, `scope-participants`, `teacher-students`) are implemented, registered and covered by tests — but `lang/{en,ar}/settings.php` never gained `notification_settings.recipient_type_labels.{key}`, and `NotificationSettingResource` reads **that** file first (§8). The list and the edit modal therefore print `settings.notification_settings.recipient_type_labels.scope-participants` as the audience name. | The gate checks that a key is **registered**, never that it is **labelled** — so `W5.7`'s "every registered key has both labels" test is the missing guard, and it should assert `settings.php` **and** `notifications.php`. |
| **N-5** *(session 3 — browser)* | **A supported placeholder is not a supplied placeholder.** `marathon.eligibility.added/removed` carries `{program_name}` in its seeded templates while its dispatcher passes no `program_name` and no `program` model, so the **delivered** body renders `Program "{program_name}" has been removed from eligibility…` on the bell. The gate's `placeholders` check passes: it verifies the token is *fillable*, not that the dispatch site *fills* it. | The same class of gap exists for any event whose dispatcher version drifts from its seeded template. The fix belongs in the gate: resolve each row's `{tokens}` against the **dispatch fixture's** context keys, not only against `SUPPORTED_PLACEHOLDERS`. |

### Session 6 (2026-09-30) — faithful re-execution, the browser verdict, and **N-10 / T27**

The fifth session closed the four defects the fourth session found, by making the **renderer** read the
shapes the dispatchers actually pass. This session asked the complementary question: was the fourth
session's *measurement* right? It was not, in one direction: the harness derived each event's context
**keys** from the literal `'key' =>` entries in the source text around the `dispatch(...)` call, so any
family whose key is computed went unseen.

| Family | Real key | Why the first scan missed it |
|---|---|---|
| Participation / enrolment / payment / seat (`{e}.*`) | the **morph key** — `'competition' => $event`, `'marathon' => $event` | the key is the expression `$participation->event_type`, not a literal |
| Assessment life-cycle (`training.created`, `group-exam.deleted`, …) | `assessment` | the name comes from `$assessment->notificationEvent($action)` — a variable |
| Subscription funnel (`subscription.*`) | `subscriber`, `user`, `plan_name`, … | the whole call is `NotificationHandler::dispatchToEngine($eventName, $context)` |

The new harness reproduces each real context and re-drove every name. Result: **145 of 191 delivered
(629 rows, 37 users)**, **0 thrown**, **0** literal tokens in any stored row, **30** active rows silent.
Adjudicating the N-9 runtime warnings against the real call sites left exactly **one** genuine gap —
**N-10**, the `subscription.trial.ending` `{expiry_date}` — now fixed and recorded as trap **T27**.

The **30 silent active rows** split into two structural classes, neither a defect: the scheduler-shaped
names (`{subject}.{starts,ends}.soon`, `*.completed`, `*.results.available`, `attendance.*`,
`classroom.*`, `certificate.created`, `user.password.reset.requested`, `user.teacher.assigned`) whose
audience is the **participants of a record** the representative context gives none, and the new
`event-eligible-*` keys, which resolve nobody while **`event_eligibilities` is empty**.

Browser: four isolated incognito sessions, one per user kind, each logged in through
`/program/login-to-program-email`; every bell badge equalled its database count and every rendered
message was token-free. Per-kind delivery (roles overlap): super-admin **124** · portal-admin **237** /
128 events · portal-manager **45** · portal-teacher **339** / 130 events · portal-student **290** / 56 events.

### Session 7 (2026-09-30) — a real system marathon, the eligible audience in the browser, and **N-11 / N-12**

Session 6 proved *rendering* correctness across every event. This session asked the *audience* question
against live data, because the two new eligible keys had never resolved anybody: **`event_eligibilities`
was empty**. A fixture drove the requirement's three steps through the production code paths with program
**46 (MERA)** eligible and program **1 (UC MAS)** as a negative control:

| Step | Recipients | Requirement |
|---|---|---|
| `marathon.created` (draft) | **#1 only** | 1 — a draft tells only the authorities |
| `marathon.eligibility.added` (still draft) | **#1 only** (the keys are gated on `status === 'open'`) | 2-a |
| `marathon.status.changed` (→ open) | **#1** (authority wording) + **#154** (MERA's admin) | 2-c |
| control: program 1's admin/manager/teacher | **nobody** | eligibility is real, not decorative |

Browser: MERA's admin (bell **1**) reads *“The marathon \"Eligible Audience Fixture Marathon\" is now
open. Your program is eligible — you can submit participation requests.”*; the super-admin (bell **3**)
reads the three authority-side sentences; UC MAS's admin/manager/teacher shows **no badge**.

**Two defects the fixture exposed:**

- **N-11 — a multi-group row delivered the FIRST group's wording to everyone.** The recipient map dropped
the group a user came from, `TemplateRenderStage` rendered `recipient_groups[0]` for every recipient and
`DispatchStage` passed `recipient_groups[0]` as the group. Before the fix, #154 read *“Marathon \"…\" status
has been changed to open …”* — the authorities' sentence — while the sentence written for the eligible
programs was never used. Fixed by carrying the group index on the recipient and honouring it in both
stages. Not confined to the new keys: **every** multi-group row with differing `database_message`s was
affected. `RecipientGroupMessageRoutingTest` (5 tests) is red without the fix.
- **N-12 — `MarathonService` was unresolvable.** Its `AppServiceProvider` singleton passed 2 of 3
  constructor dependencies, so resolving it threw `ArgumentCountError`. Inert (nothing resolved it) but
  broken — `openForParticipation()` is the documented way to open a marathon. Fixed.

### Session 8 (2026-09-30) — the settings editor: an event's own audience, and its placeholders

Requested: *the **Notify** dropdown must contain only the items relevant to that event (not all notifiers),
and the message fields must mention the placeholders available for that event.*

**The defect.** The dropdown DID filter — `$get('../../category')` resolves correctly through Filament's
`generateRelativeStatePath()` (two `../` from `recipient_groups.{i}.recipient_type` land on the form's own
`data` root) — but the filter was the defect: `getRelevantResolverCategories()` began from five resolver
categories for **every** event and then added more per category, so a `marathon.*` row offered 38 of the 39
registered keys. It was a filter that behaved like none.

**The rule now.** `getNotifyOptions($eventName, $category, $currentKeys)` — the options are the
`recipient_type`s named by the rows of the **same event family** (the leading dot-segment, let
`marathon.participation.submitted` and `marathon.status.changed` share `marathon`) **union** the rows of the
same `category`, active rows first and all rows when a family has only inactive ones, **plus** the generic
`role`/`custom` keys and any key the row already names. Unknown family → the whole registry (the previous
behaviour); result empty → the whole registry. Three safety properties, each pinned by a test: the narrowing
can never hide a row's existing audience, can never leave the dropdown empty, and every one of the 39 keys
stays reachable from some family.

| Event (live) | Options | Of 39 |
|---|---|---|
| `announcement.created` | `scope-authority`, `scope-participants`, `role`, `custom` | 4 |
| `marathon.status.changed` | `participants`, `event-eligible-admins`, `event-eligible-teachers`, `marathon-authorities`, `participant`, `student`, `marathon-owner`, `role`, `custom` | 9 |
| `subscription.trial.ending` | `program-admins`, `subscriber`, `super-admin`, `super-admins`, `super-manager`, + generic | 7 |

**The placeholder hint.** Each of the four message sections (`database_message`, `mail_subject`,
`mail_body`, `whatsapp_message`) carries a description listing the `{tokens}` that event's family already
uses, plus `{date}`/`{time}`, intersected with `TemplateRenderer::SUPPORTED_PLACEHOLDERS`. `marathon.*`
renders 11 (`{marathon_title} {creator_name} {date} {user_name} {allocated_seats} {used_seats}
{total_seats} {reason} {status} {program_name} {time}`); an unknown family renders just `{date} {time}`.

**A defect this session's own tests caught.** The family scan was memoised in a `static` property. Two
tests passed and eight failed: a static outlives the request, so the first test's scan answered every later
one. The memo now lives on the **container** (`App::instance()`), rebuilt per request and per test — which
is also what a long-running worker needs.

**Verification.** Browser, `admin` panel: `announcement.created` → **4** choices in the Notify dropdown;
`marathon.status.changed` → **9**; the message sections rendered *"Available placeholders for this event:
{marathon_title} {creator_name} {date} …"*. `notifications:doctor --strict` → **exit 0** (240 rows / 194
active / 369 groups / 39 resolvers / 191 dispatched names / 0 without a row — **superseded by session 11,
which moved the figures to 373 groups / 41 resolvers**). Notification suite **124
passed / 1314 assertions** (was 114 / 1244). `tests/Unit/NotificationServiceTest`'s 25 failures are
pre-existing and unrelated — that test drives the legacy `App\Services\NotificationService` and contains
**zero** references to `NotificationSettingResource`.

### Session 9 (2026-09-30) — every event re-executed, six user kinds, and **N-13**

The user reset **every** user's password to `123456` and asked for the full pass again with a browser
session per user kind.

**Clean-slate method.** `notification_logs` was empty but the 4 rows of the eligible-audience fixture were
still in `notifications`/`notification_history` from earlier the same day, and `DedupStage` suppresses a
user+event pair for **1440 minutes**. All three tables were therefore snapshot-then-emptied
(`db/pre-state.json`), so the pass has no hidden dependencies and every badge is attributable to it.

**Result.** 191 names · **145** delivered · **30** active rows silent · **629** bell rows · **37** recipients ·
**145** events · **0** rows with a literal token · **0** exceptions. Per kind (overlapping): super-admin
124 · portal-admin 237/128 events · portal-manager 45 · portal-teacher 339/130 · portal-student 290/56.

**Browser — one isolated session per kind**, each logged in through `/program/login-to-program-email`:

| Kind | User | Badge | DB |
|---|---|---|---|
| super-admin | #1 | 124 | 124 |
| program-admin (p46) | #154 | 26 | 26 |
| program-manager (p1) | #1246 | 45 | 45 |
| teacher (p1) | #153 | 27 | 27 |
| student (p1) | #155 | 48 | 48 |
| program-admin (p55) | #1229 | 21 | 21 |

Every badge matched, no panel rendered a token, and the messages read correctly (seat counters like
`(10/10)`, `{date}` filled, program and event names interpolated).

**N-13, found and fixed.** `StudentEnrollmentService::removeStudent()` passed no `creator`/`enroller`, so
`{creator_name}` in the `…-authorities` group of `{event_type}.enrollment.removed` printed literally to 9
users on the competition row and 1 on the marathon row. Fixed with `'enroller' => $remover`. After the fix,
#154's panel reads *"Anton has been removed from competition \"Teacher Training\" by Anton."*

**Why this reached a user at all** — three guards, three blind spots: the doctor's `placeholders` check
proves a token is *fillable* (`SUPPORTED_PLACEHOLDERS`), not that the dispatch site *supplies* it (N-5); the
sweep's scan reads `notification_history.message_preview`, the database channel only; and no static scan
can see a key the call site never passes. The runtime guard from N-9 does see it: it logged exactly these
two names. Re-reading that log is the cheapest whole-catalogue audit for this class.

### Session 10 (2026-09-30) — the marathon lifecycle end to end in the browser, and **N-14**

Asked to complete the marathon workflow from the super-admin panel and validate both halves (notifications
and subscriptions), the whole lifecycle was driven through the UI: create (draft) → add two eligible programs
**while still a draft** → `open` → teacher participation request (3 online / 2 paper) → approval → seat
increase (+2/+1) → approval (**pool 5/3**) → student request → approval → manual enrolment of a second
student → `marathon-competition` + its `child-training`.

**Clean-slate note.** The same trap as session 9, in a new place: `DedupStage` keyed on **user + event name**,
not on the record, so the *first* attempt of this pass produced exactly one row — the day's earlier
`marathon.created` had already spent the 1440-minute window. The three tables were emptied (pre-state saved)
and the run repeated. Any pass that wants to see a family's deliveries must do this first. *(Since
**2026-10-01** the key includes the record, so a life-cycle family is no longer spent as a whole — a different
record delivers; emptying the tables is still the only way to re-see **the same record's** rows — plan 1.13,
`NOTIFICATION_SYSTEM_WORKFLOW.md` T32.)*

**Result.** 24 history rows = 24 bell rows to 13 recipients, 0 literal tokens, 0 unfilled tokens, 0
exceptions; the 1.13 draft/eligible audience rules reproduced exactly (draft → #1 only; `open` → #1 with the
authorities' wording plus #154, #1246, #153, #163, #164, #1228 with the eligible-audience sentence). Five
isolated browser sessions matched the database: #1 → **11**, #153 → **6**, #154 → **1**, #157 → **1**,
#1223 → **1**.

**N-14, found and fixed.** `marathon-competition.created` produced **no** notification; the log said
`dispatch aborted … No recipients resolved for the event` — a **stage-4** abort, i.e. a resolver answering
`[]`, not a missing row or class. The three `marathon-competition.*` rows name `marathon-authorities` as their
only group, and `MarathonAuthoritiesResolver` read only `context['marathon']`, which
`Assessment::dispatchAssessmentEvent()` never provides. `CompetitionAuthoritiesResolver` reads
`assessment ?? competition`, so the `competition.*` twins worked — the asymmetry is what hid it. Fixed by
following the assessment's parent marathon off `marathon_id`, plus one parent-assessment hop for a
child-training with no inherited `marathon_id`. Recorded as **T30** in `NOTIFICATION_SYSTEM_WORKFLOW.md` §16 and
as a §8 rule ("two resolvers for one family reading different keys is the dangerous shape").

**Also fixed:** `BaseNotification` had no `$batchId` declaration although `DispatchStage` assigns it on every
dispatch — one PHP 8.2 dynamic-property deprecation per notification class.

**Recorded, not fixed (subscription side).** `no_of_marathons` round-trips on create/delete
(`program_subscription 152`: **6 → 7 → 6** on a controlled probe) but is **unverifiable and unrepairable**: 
`config/subscription-resources.php` resolves a `system`-scoped marathon's subscriber from **`auth()->user()`**
with `scope_resolver = program`, so the acting administrator's program pays, while `features:recalculate-usage`
has no authenticated user and reports the same counter as *stored 6, should be 0* with 15 rows unattributable.
`SubscriptionUsageObserver::created()` also has no super-admin bypass although `creating()` does — a
super-admin's resource is never **blocked** yet is still **charged**. Persisting the subscriber on the record
is a schema decision, so it is an open item, not a correction.

### Session 11 (2026-09-30) — the PROGRAM-scoped marathon run, and **T31** (the audience nobody told)

The mainline was repeated with `scope = program` and confirmed the scope machinery the same way session 10
confirmed the system one. Marathon **#31** was created by **#1246** (portal-admin + portal-manager +
portal-teacher, program 1) from the program tab: `marathon.created` reached **#1 + #1246** (the
`marathon-owner` audience for a programme scope), the **programme's** subscription was charged
(`program_subscription` **152**: `no_of_marathons` **0 → 1** — `config/subscription-resources.php` matches
on `scope`), the next programme-1 marathon was then refused at the plan's cap, eligibility rows for teachers
**#1 / #153 / #1228** were written **while the marathon was still draft**, `status → open` reached **4**
distinct users (`marathon-authorities` #1 + #1246 and `event-eligible-teachers` #153 + #1228, deduped), and
the rest of the lifecycle (teacher request → approval, seat increase → approval, student request → approval,
manual enrolment, competition + child training) completed in the browser. The programme's
**3-competition cap** was reached (3/3) and one competition released with the super-admin session.

**T31, found and fixed.** Neither creation row told anyone who could take part:
`marathon-competition.created` named only `marathon-authorities`, `child-training.created` only `teacher`
(the creating teacher). Two registered keys close it — `marathon-eligible-teachers` (the **marathon's**
eligibility rows: `eligible_teacher_id` plus the Program Teachers / Teacher Assistants of every
`eligible_program_id`, **all levels**, **no** participation exclusion) and `level-students` (approved
`student_enrollments` whose **joined** `level_classification_id` equals the record's
`assessments.level_classification`; locked record, non-`open` marathon or no level → nobody). Both were
appended to the two rows on **both** paths N-1/N-2 require: `MarathonCreatedAudienceRepair` + migration
`2026_09_30_000007` for the rows an installed database already has, and the two legacy seeders for a fresh
install — so the fix is neither a migration-only write (`db:seed` would revert it) nor a seeder-only one.
`event-eligible-teachers` cannot serve these rows: a `marathon-competition`
has no `event_eligibilities` of its own, so it resolves nobody there **forever** — the asymmetry that hid
this is now recorded in `NOTIFICATION_SYSTEM_WORKFLOW.md` §8 (defect 6) and §16/T31.

**Browser verdict.** With the notification tables emptied first (dedup keys on user + event name),
a **level-11** competition reached the authorities + **both** eligible teachers (#153, #1228) + **both**
students enrolled at that level (#157, #1223); a **level-15** competition reached the authorities + both
teachers and **zero** students. Level rule confirmed, teachers reach every level.

**Counts and checks.** Registry **41 keys** (from 39); live **240 rows / 194 active / 46 inactive / 373
groups (370 database, 108 mail, 0 whatsapp) / 191 dispatched names / 0 dispatched without a row**;
`notifications:doctor --strict` exit **0**; `php artisan test --filter='MarathonEligibleAndLevelStudents|NotificationSettingsAudienceRelevance'`
→ **26 passed / 126 assertions**, and the other eleven `tests/Feature/Notifications` files re-run green
(59 + 47 + 7 tests in three batches). The generated readers were re-synchronised with the registry in the same
pass (262 stale `⚠` markers dropped in `NOTIFIERS_EXPLAINATION.md`, six glossary rows flipped to
`registered` in `NOTIFICATION_EVENTS_MATRIX.md`, matrix §2.3 re-bucketed: **28 of 41** keys named by a row,
**13** still proposed).

**Left open by this run (recorded, not defects):** the programme-scoped run pays from the **programme's**
subscription while the system-scoped run pays from the acting administrator's — both are what
`config/subscription-resources.php` says; and the per-record cap behaviour (one competition per level per
marathon, 3 per programme plan) is enforced inline by the quota services, not by the observer map.

### Still open

W2.2/W2.5 (the 319-entry catalogue that folds in the five legacy seeders) and W2.6 (the renames),
W3.9's **silenced** decisions (16 rows), W4.4 (`assessment.attempt.*`), W4.5 (the certificate
context), W4.8 (per-recipient locale), W5.2/W5.3/W5.5/W5.8 and the remaining **13 PROPOSED keys** (see below), W6 (preferences
+ program overrides), W7.1/W7.3–W7.5, W8 (observability + prune), W9.4/W9.5 (the per-event recipient
suite), W10 (retirement) and W11.1–W11.3. **Closed since this list was written:** W5.7's label gap
(**N-4** — *seven* unlabelled keys now labelled, with the guard test), the `marathon.eligibility.*`
context (**N-5** — `program_name` now passed, and the record of what the dispatcher passes corrected),
and the recipient-side half of N-8, plus the six W5.4 keys that shipped (with `marathon-eligible-teachers` beside them) — the remaining **13 PROPOSED keys** are `program-members`, `assessment-students`, `parent-participants`, `certificate-holder`, `record-owner`, `event-participants`, `event-students`, `eligible-teacher`, `eligible-student`, `eligible-program`, `enrollment-student`, `event-participating-teachers`, `level-owner`. **N-9 is partially closed:** the runtime guard is in
(`TemplateRenderer::unfilledPlaceholders()` + the `TemplateRenderStage` warning), but a *pre-dispatch*
gate was measured and rejected as non-viable (it cannot see the runtime-built names and false-positives
the `subscription.*` family) — see session 5 and `measure-n9.php`. The three-party eligibility audience
split (matrix §16.5) and the per-event recipient fixture (W9.4) remain the structural gaps.

The gate is what tells you when each lands: `php artisan notifications:doctor --strict` exits **0**
today, so the measure from here on is not "does it fail" but **"does the count of declared-dormant,
silenced and unused rows go down"** — and D13 (a per-event recipient test, W9.4) is the next
structural gap in the defined point.
