# Decisions Log

Each entry: context → decision → consequences. Entries are never deleted; superseded entries are marked.

---

## D-001 — Baseline is the archive as received, frozen in git
**Date:** 2026-10-19 · **Stage:** 1
**Context:** The archive arrived without a VCS history. Pre-existing defects must be separable from changes made during implementation.
**Decision:** `git init` in the working copy and commit the archive unchanged (commit `56d44fc`). `.env`, `vendor/`, `node_modules/` stay untracked per the project's own `.gitignore`. All later work happens in subsequent commits.
**Consequences:** `git diff 56d44fc` is the authoritative list of changes introduced by this programme.

## D-002 — Test runtime is PHP 8.4 + MariaDB 10.11
**Date:** 2026-10-19 · **Stage:** 1
**Context:** `composer.json` declares `php: ^8.3`, but `composer.lock` resolves packages that require PHP ≥ 8.4 (`spatie/laravel-activitylog` `^8.4`, `brianium/paratest` `~8.4||~8.5`). Under PHP 8.3 the app does not boot (Composer platform check fatal). `phpunit.xml` requires MySQL/MariaDB because migrations use MySQL-specific SQL.
**Decision:** Run the baseline on PHP 8.4.26 (prebuilt `shivammathur/php-builder` package, minimal extension set) and MariaDB 10.11.14 (Ubuntu package). Keep the shipped `vendor/` for the baseline run.
**Consequences:** The `composer.json` PHP constraint is a pre-existing defect (F-01) to correct to `^8.4` in Batch 0. The user's stated production database version differs from 10.11; MariaDB-version-specific behaviour is a residual risk until tested on the production version.

## D-003 — Modular monolith inside the existing Laravel app, no microservices
**Date:** 2026-10-19 · **Stage:** 1
**Context:** Requirement R3; current app is one Laravel application with ~150 models and one 1 790-line `routes/web.php`.
**Decision:** Introduce modules as namespaces under `app/Modules/<Module>/` (Domain, Application, Infrastructure, Http, Providers, routes, tests) in the same deployment. Separate queue workers allowed. Cross-module calls go through each module's `Contracts/` (public operations) or published domain events. Moves happen incrementally, module by module, with the existing tests as the safety net.
**Consequences:** No distributed transactions; financial atomicity stays in single DB transactions inside the owning module.

## D-004 — Tenant isolation is hardened before any module extraction
**Date:** 2026-10-19 · **Stage:** 1
**Context:** Confirmed fail-open tenant scope (F-03) and host/user precedence issues in `IdentifyTenant` (F-04). Extracting modules first would multiply the surface that relies on these.
**Decision:** Batch 1 = tenancy kernel (fail-closed scope, host-based resolution, job/command/cache/file context) with a two-tenant isolation test suite. Module extraction starts only after Batch 1 is green.
**Consequences:** Some currently-passing tests that rely on implicit cross-tenant reads may fail and must be fixed by giving the code an explicit context, never by re-opening the scope.

## D-005 — Vite pipeline treated as non-runtime for the baseline
**Date:** 2026-10-19 · **Stage:** 1
**Context:** No Blade view uses `@vite`; layouts load hand-maintained `public/css/*.css` and `public/js/*.js`. The shipped `node_modules` contains only the macOS ARM native binding, and the Vite font plugin fetches from `fonts.bunny.net` at build time (blocked in this environment).
**Decision:** Record the build as an environment-blocked check, not a runtime failure. Decide in the website-publishing batch whether to adopt Vite properly (self-hosted fonts, Linux-reproducible lockfile) or remove the unused pipeline.
**Consequences:** No front-end build artefact is required to run the baseline.

## D-006 — Regulatory applicability must not default to Tanzania / Category B
**Date:** 2026-10-19 · **Stage:** 1 (decision recorded; implementation in the regulatory batch)
**Context:** `OrganizationRegulatoryProfile` defaults every organisation to `jurisdiction=TZ, licence_category=B`; provisioning also installs the Tanzania bank list based on timezone. Requirement R10 forbids country-only or default application.
**Decision:** New organisations start with **no regulatory framework applied** (status "not yet determined"). A framework applies only after the organisation's regulator, licence category and effective date are recorded and confirmed by a platform regulatory administrator; packs carry their own effective-date ranges.
**Consequences:** Features currently gated on the TZ/B default (lending controls, security rules) need an explicit "no framework" behaviour that keeps the tenant's own policies working.

## D-007 — Proposed hosted-card provider is undecided
**Date:** 2026-10-19 · **Stage:** 1
**Context:** The control plane needs hosted Visa/Mastercard checkout with recurring payments for a Tanzania-based platform. The archive contains member-payment gateways (Paystack and Tanzanian mobile-money providers among them) but no SaaS subscription billing. Merchant eligibility and recurring-card support must be verified with the provider, which cannot be done from code.
**Decision:** Build subscription billing behind a `SubscriptionPaymentProvider` contract with a sandbox/fake implementation for tests. Choice of live provider is an open dependency for the business (see `IMPLEMENTATION_STATUS.md`).
**Consequences:** No live provider is contacted in any stage.

---

## D-008 — Fail-closed tenancy is enforced in the data layer, with three explicit contexts
**Date:** 2026-10-20 · **Stage:** 2
**Context:** F-03. ~1 360 `withoutGlobalScopes()` calls; tenant filtering silently disappeared outside requests.
**Decision:** `App\Tenancy\TenantContext` holds one of TENANT(org) / SYSTEM(reason) / NONE. `TenantScope` filters in TENANT, does nothing in SYSTEM and **throws** in NONE. Tenant models use `TenantBuilder`, whose `withoutGlobalScopes()` removes every scope except the tenant scope, so the existing bypass calls keep their original purpose (soft-delete, "current" scopes, re-locking) without dropping isolation. Cross-tenant work requires an explicit, reasoned system context (`Tenancy::runAsSystem($reason, …)` or a role-checked platform/console entry point); the full list is in IMPLEMENTATION_STATUS.md, Stage 2. Writes: forged/changed `organization_id`, rows of another organization, and declared cross-tenant foreign keys throw `TenantMismatch`; writes with no context throw `MissingTenantContext`.
**Consequences:** Raw `DB::table()` is not covered (not a model) and still needs explicit filters (reviewed list unchanged from Stage 1: 17 calls, all keyed by already-scoped ids or intentionally global). 14 models that carry `organization_id` without the trait remain outside the scope (see residual risks).

## D-009 — Host decides the tenant site; membership is a separate check
**Date:** 2026-10-20 · **Stage:** 2
**Context:** F-04, F-20.
**Decision:** `organization_domains` stores exact normalized hosts; only verified rows resolve. Platform subdomains (`<label>.<base>` for `TENANCY_SUBDOMAIN_BASES`) are verified on creation; customer domains need a DNS TXT proof (`tenancy:verify-domain`) or an operator mapping (`tenancy:map-domain --verified`). Reserved labels and platform hosts can't be claimed. Unknown hosts → 404. The "only one organization" fallback is removed. On a tenant host the signed-in user is never used to choose another tenant: `EnsureOrganizationMembership` signs out a user whose organization differs, and the login form refuses such accounts. On the platform host (shared back office) an authenticated user works in the organization stored on their account; guests get no tenant.
**Consequences:** A fresh single-tenant install must map its domain after provisioning (deployment prerequisite). Public pages on the platform host return 404 until platform marketing pages exist (control-plane stage).

## D-010 — Platform support access is a reasoned, expiring, read-only-by-default grant
**Date:** 2026-10-20 · **Stage:** 2
**Decision:** "Work in this organization" now creates a `support_access_grants` row (reason ≥ 10 chars, scope read|write, expiry `TENANCY_SUPPORT_ACCESS_MINUTES`, default 120) and audits it in the tenant's trail. There is no implicit home-organization access for super admins. Read-only grants refuse every state-changing request. Ending support revokes the grant.

## D-011 — Mandatory MFA for administrators; re-authentication for sensitive routes
**Date:** 2026-10-20 · **Stage:** 2
**Decision:** Super admins, regulatory admins and SACCO admins (global `admin` role or `is_admin`) must enrol TOTP before any admin/platform page and cannot disable it. Any user with 2FA enrolled must pass it per session (closes sign-in paths that skipped the challenge). TOTP time-steps can be used once; recovery codes are stored as HMAC digests and consumed under a row lock; pending 2FA sign-ins expire after 10 minutes; sessions rotate on login, 2FA completion and enrolment. Routes listed in `config/security.php` need password (+TOTP) re-entry within 15 minutes.
**Test harness:** `actingAs()` in `tests/TestCase.php` simulates a completed sign-in (enrolled admin, verified session, recent confirmation) unless a test sets `$actAsEnrolledAdministrator = false`; the MFA tests do.

## D-012 — Tenant rich text is allow-list sanitized with PHP 8.4's HTML5 parser; tenant custom code removed
**Date:** 2026-10-20 · **Stage:** 2
**Context:** F-05, F-06. Packagist is unreachable from the build environment, so `symfony/html-sanitizer` could not be added.
**Decision:** `App\Services\Website\RichTextSanitizer` uses `Dom\HTMLDocument` (spec-compliant HTML5 parsing, same tree as browsers) with an element/attribute allow-list and scheme allow-list. Applied on save and on render. `site_settings.custom_head_snippet` dropped. Revisit replacing it with `symfony/html-sanitizer` when dependencies can be installed (D-002 environment), keeping the same tests.

## D-013 — Append-only audit and posted-journal immutability via database triggers + hash chain
**Date:** 2026-10-20 · **Stage:** 2
**Decision:** Triggers refuse UPDATE/DELETE on `audit_logs` (except one-time sealing) and any change/delete of posted journal lines and posted/reversed journal content; reversals remain new journals. `audit:seal` (scheduled every minute) chains rows per organization with SHA-256; `audit:verify` recomputes. `Auditable` and `AuditTrail::record` no longer swallow failures; secrets/identity numbers are redacted from audit change sets. `DeferredAudit` still reports (not rethrows) failures because it runs after commit.
**Consequences:** Requires TRIGGER privilege (and SUPER or `log_bin_trust_function_creators=1` with binary logging). A DBA with DDL rights can still drop triggers; the chain makes that detectable, not impossible — true WORM storage/off-site log shipping is an infrastructure requirement.

## D-014 — Test DB isolation: parallel Feature runs, serial Concurrency suite
**Date:** 2026-10-20 · **Stage:** 2
**Decision:** Unit+Feature run with `--parallel --processes=8` (Laravel creates one test database per process); the Concurrency suite runs serially because it uses a fixed `_concurrency` database.

---

## D-015 — Modules are namespaces in layer order, enforced by a manifest and an architecture suite
**Date:** 2026-10-20 · **Stage:** 3
**Context:** R3/R4/R6. Stage 1 found one strongly connected dependency component across ~22 domains and proposed layered modules reached only through contracts.
**Decision:** Code lives in `app/Modules/<Module>/` (22 modules with code; Billing listed as planned), `app/Shared/` (infrastructure only, depends on nothing) and the **application shell** (`app/Http`, `app/Exceptions`, `app/View`, `app/Providers`: request pipeline and error rendering, may use every module, used by none). `config/modules.php` lists the modules **in layer order** — Shared, Tenancy, Identity, Assistant, Reference, Billing, Notifications, Approvals, Regulatory, Accounting, Payments, Members, Savings, Shares, Lending, Workforce, Governance, Events, SupportDesk, Website, Imports, Reporting, Platform — with each module's observed `depends_on` (only lower layers), `read_models` (models others may read, never write), `public` classes (besides `Contracts\*`/`Events\*`) and owned tables without a model. `tests/Architecture` (php-parser static graph over `app/`) fails on: a dependency on a higher layer, a non-public class, a cross-module write (Eloquent statics, typed variables/properties, `DB::table`/raw SQL on another module's table), a cycle, any Shared→module or module→shell reference, providers out of layer order, an empty `catch`. Remaining violations must be listed one by one in `tests/Architecture/exceptions.php` with a reason; a new violation or a stale entry fails the suite.
**Consequences:** A lower module reaches a higher one only through a contract it defines and the higher module implements (binding or registry), or a domain event. Writes go through the owning module's operations. Run with `php vendor/bin/pest --testsuite=Architecture` (no database needed).

## D-016 — Module boundaries adjusted from the Stage 1 proposal
**Date:** 2026-10-20 · **Stage:** 3
**Context:** The brief allows boundary changes where actual dependencies support them, with the reason recorded.
**Decision (each with its reason):**
- **Kernel** split into **Tenancy** (tenant context kernel + organizations, domains, branches, operational settings — the kernel and the tenant record change together) and **Shared** (money, audit trail/chain, logging, mail-failure logging, uploads, validation, phone numbers, redaction).
- **Elections merged into Governance** — elections create and end leadership tenures and discipline records; one module owns offices end to end.
- **Treasury inside Payments** — liquidity is a property of payouts; it reads ledger balances through the Ledger contract and collects commitments from Lending/Workforce (`LiquidityCommitments`).
- **Compliance (AML, thresholds) and Policy Administration inside Regulatory** — both apply the statutory resolver; splitting them created a cycle.
- **Organization settings** split: operational settings and branches → Tenancy; currencies, countries, banks, languages, translations → Reference.
- **Approvals** is its own lower-layer module (used by Accounting, Savings, Lending, Workforce, Governance); owning modules register subject handlers.
- **AI Assist = Assistant** (client, settings, usage log, daily cap); drafting services stay with the module that publishes the text.
- **Credit scoring → Lending** (inputs are loan history); **member dashboard, AI insights, audit-log viewer → Reporting** (cross-module reads); **referral reward payout → Savings** (it credits savings); **OrganizationIdentity → Regulatory** (used for returns); **member look-up → Members** (`MemberDirectory`).
- **Profile completion** engine stays in Members with a subjects registry; the employee subject (requirements, policy, report columns) moved to **Workforce**.
- **Platform** = control-plane screens and provisioning orchestration; organization operations live in Tenancy. **Billing** has no code yet (SaaS billing is a later stage).
- **Events** and **SupportDesk** are small separate modules.

## D-017 — Ledger inversion with synchronous posting inside the business transaction (F-15)
**Date:** 2026-10-20 · **Stage:** 3
**Decision:** Accounting exposes `Contracts\Ledger` (post, reverse, accounts by mapping key, failure records) and never imports source models. Each owning module builds its own journals (`SavingsJournals`, `ShareJournals`, `LoanJournals`, `NominationFeeJournal`, `ExpenseJournals`, `PayrollPostingService`) with idempotency key `event:source`. The post runs **inside the business transaction**; a posting failure (`PostingException`, a validation error) rolls the business change back and is shown to the user. Organizations that have not chosen a functional currency (`Ledger::isActive()` false) keep operating on the subledger alone, as before; no journal is attempted. The accounting exceptions screen keeps retrying legacy failures through the `PostingHandlers` registry.
**Consequences:** Intentional behaviour change: a missing mapping now blocks the money operation with a message instead of committing a subledger record without its journal (test `SaccoPostingTest` updated to the new rule). A late review in this stage found `LoanService::recordPayment` still posting after commit; fixed (D-030).

## D-018 — `accounting:prepare-ledger` is a deployment step
**Date:** 2026-10-20 · **Stage:** 3
**Decision:** Because postings now fail closed, every organization with a functional currency must have the chart and default mappings. `php artisan accounting:prepare-ledger [--organization=]` adds the standard chart and mappings where missing (never overwrites) and lists organizations without a functional currency. Run once after deploying Stage 3.

## D-019 — Funding source on savings credits; funded credits are reversed by their funding event only
**Date:** 2026-10-20 · **Stage:** 3
**Decision:** `saving_activities.funding_source` (migration `2027_08_01_000001`, backfilled from `dividend_payouts`) marks credits funded by another module through `SavingsAccounts::creditInternal` (today: dividend payouts; referral rewards remain ordinary deposits through the chosen payment method). Savings no longer reads Shares tables. `SavingsService::reverseDeposit` refuses to reverse a funded credit directly; the funding module reverses it through the `SavingsAccounts` contract (`reverseInternalCredit`).
**Consequences:** Intentional tightening: staff can no longer reverse a dividend-funded deposit from the deposit screen (which previously left the dividend payout marked paid).

## D-020 — Payments owns providers; owning modules apply outcomes (payables, payout trackers, liquidity commitments)
**Date:** 2026-10-20 · **Stage:** 3
**Decision:** `Payments\Contracts\Payables` (settlement handler per payable type: savings deposit, share purchase, loan repayment) and `PayoutTrackers` (loan disbursements → Lending, payroll/HR payments → Workforce). Payments keeps provider drivers, polling, webhooks and the monitor; the owner decides what a provider answer means for its record and writes its own tables. `LiquidityCommitments` collects money already committed (awaiting loan payouts, staff payables). Monitor actions moved to the owning modules' controllers with unchanged route names and URIs.

## D-021 — Contracts, registries and owner-declared relations
**Date:** 2026-10-20 · **Stage:** 3
**Decision:** (1) A lower module defines a contract; the higher module binds it in its provider (`OfficeRoles`, `GoverningBodies`, `LegalDocuments`, `DeliveryReceipts`, `InsiderLendingPolicy`, `CampaignTopics`, `PaymentChannels`, `SignInMethods` …) or registers handlers in a registry (`PostingHandlers`, `AccountingExtensions`, `ApprovalSubjects`, `Payables`, `PayoutTrackers`, `LiquidityCommitments`, `RegulatoryExtensions`, `CompletionSubjects`). (2) Registry handlers resolve their collaborators at call time (`app()`), so test doubles and re-bindings apply. (3) Inverse relations on hub models (`User`, `Organization`, `MemberGroup`, `Expense`, `AuditLog`) are declared by the module that owns the related records (`resolveRelationUsing`), not by the hub. (4) A tenant-ownership guard on a lower module's foreign key is declared by the owner of the referenced records (`BelongsToTenant::guardTenantForeignKey`, e.g. Payments for `expenses.payment_method_id`).

## D-022 — Identity asks other modules through its own contracts; request pipeline moves to the shell
**Date:** 2026-10-20 · **Stage:** 3
**Decision:** Identity defines `SignInMethods` (Members), `SignInCodeSender` (Notifications), `LandingGate` (Members' profile-completion gate) and `LocalePreference` (Reference). The staff-created welcome link (`password.welcome`) moved to Members with the same URL, name and middleware. The KYC guard on `users.is_kyc_verified` is registered by Members. Support access (`SupportAccessGrant`, `SuperAdminContext`) moved to Identity. The tenant-identification, membership, platform-context and super-admin logging middleware moved to `app/Http/Middleware` (shell) because they compose Tenancy, Identity, Reference and Website.

## D-023 — Provisioning orchestrated by Platform through owner operations
**Date:** 2026-10-20 · **Stage:** 3
**Decision:** `OrganizationProvisioningService` (Platform) keeps the single transaction but calls: `Tenancy\Services\OrganizationLifecycle` (create with unique slug, update, suspend), `Identity\Services\RoleProvisioning` (staff role; also used by Workforce for HR role templates and permission carry-over), `Accounting\Services\AccountingProvisioning`, `Payments\Services\PaymentMethodProvisioning`, `Reference\Services\LanguageProvisioning`, `Website\Support\WebsiteDefaults`, Workforce `HrProvisioningService` and the Regulatory profile/package operations.
**Consequences:** Behaviour unchanged, including the Tanzania / Category B default and the timezone-based bank list (F-12, still open; D-006 assigns it to the regulatory batch).

## D-024 — Importers belong to the owning modules; Imports orchestrates
**Date:** 2026-10-20 · **Stage:** 3
**Decision:** `MemberImportService` → Members, `SavingsBalanceImportService` → Savings, `ShareHoldingImportService` → Shares, `LoanImportService` → Lending, go-live import context → Accounting. Imports keeps the upload, token and batch records and the screens.

## D-025 — Small owner operations replace the remaining cross-module writes
**Date:** 2026-10-20 · **Stage:** 3
**Decision:** Approvals `cancelOpenFor` / `restartOpenFor` (Lending, Governance); Regulatory `PolicyExceptionService::recordDecidedElsewhere` (guarantor-recovery arrangement exceptions); Assistant `AiUsageLog::record` (all AI drafting/insights); `GoverningBodies::officesOf` (policy approvers); `PayoutTracker::inFlight` (retiring a payment method); profile-completion report columns per subject; `User::rememberLocale` and `Organization::recordDefaultLanguage` (columns written by Reference); branch management moved to Tenancy (same URLs and names).

## D-026 — Two documented architecture exceptions remain
**Date:** 2026-10-20 · **Stage:** 3
**EX-1 Tenancy → Reference:** the `Organization` aggregate keeps its currency/country helpers (`enabledCurrencies`, `setDefaultCurrency`, `setOperatingCountries`, `availableCountriesQuery` …), which read Reference's global catalogue and write the `organization_currencies` / `organization_countries` pivots Reference owns. About 100 call sites use them; moving them belongs with the organization-settings work.
**EX-2 writes to `users` from Members, Workforce and Platform:** `users` is the shared person record — member profile columns and member logins (Members), employee columns and staff logins (Workforce), platform administrators and tenant owners (Platform). Identity owns credentials, MFA, roles and permissions; role and permission writes already go through Identity. Splitting person data from the login record is a later-stage change.
Both are listed entry by entry in `tests/Architecture/exceptions.php`.

## D-027 — Behaviour tightenings made in Stage 3
**Date:** 2026-10-20 · **Stage:** 3
1. Postings fail closed (D-017) and funded credits cannot be reversed directly (D-019).
2. AI campaign drafts: `event_id` must be an event of the organization (previously any existing id passed validation and another organization's event was silently ignored).
3. Cancelling an election locks and cancels the open approval chain under a row lock and stamps `updated_at`.
4. Share redemption and manual loan repayment compute their checks from locked rows (D-030); a concurrent duplicate is refused instead of applied twice.

## D-028 — Money columns stored as DECIMAL (F-13)
**Date:** 2026-10-20 · **Stage:** 3
**Decision:** Migration `2027_08_02_000001` converts the 22 remaining `DOUBLE` columns to `DECIMAL` — amounts `(18,2)` like the rest of the schema, account-type interest `(9,4)`, exchange rates `(20,10)` — keeping nullability and defaults. Rows whose value changes by the rounding are counted per column in the application log (no personal data). Models keep `float` casts so PHP behaviour is unchanged.
**Consequences:** Storage and SQL arithmetic (`account_balance = account_balance - x`) are exact. PHP-side arithmetic still uses floats rounded to 2 decimals at the write (residual risk R-14).

## D-029 — External effects only after commit (F-21)
**Date:** 2026-10-20 · **Stage:** 3
**Decision:** `config/queue.php`: `sync`, `redis`, `sqs`, `beanstalkd` dispatch **after commit** (dropped on rollback). The default `database` queue on the application's own connection keeps `after_commit=false` on purpose: the job row is written inside the business transaction, invisible to workers until commit and removed by a rollback — a durable transactional outbox. With a separate queue connection (`DB_QUEUE_CONNECTION`) it switches to after-commit (`DB_QUEUE_AFTER_COMMIT` overrides).
**Consequences:** Notifications sent from money transactions are never delivered for a rolled-back operation (`TransactionalDispatchTest`). `DeferredAudit` is unchanged (R-11).

## D-030 — Row locks on the last two money paths; repayment posting moved inside its transaction; treasury lock deadlock fixed
**Date:** 2026-10-20 · **Stage:** 3
**Decision:** `ShareService::redeemShares` locks the holding and re-validates from it. `LoanService::recordPayment` locks the loan, reads the paid total and pending schedule rows with locking reads, and posts its journal inside the same transaction (it previously posted after commit — a partial-commit defect left over from the inversion). `LiquidityService::lock` now locks the existing treasury row first and creates it only when missing; the previous `insertOrIgnore` → `FOR UPDATE` sequence deadlocked under parallel payouts (pre-existing, found by the new concurrency test; recorded as F-28). The liquidity hold transaction retries up to 3 times on deadlock.

## D-031 — Route registration order follows the manifest; verified harmless
**Date:** 2026-10-20 · **Stage:** 3
**Decision:** Route chunks load in manifest order (Workforce before Governance; branches now registered by Tenancy). Verified against the end of Stage 2 (`32cf97f`): the same 1 173 routes (method, URI, name), the same middleware classes in the same order on every route, 7 routes served by a moved controller (members' loans tab, three loan-payout monitor actions, HR payout re-check, referral reward show/pay). A sample-URL check resolves every route to itself (no route shadows another), so order changes cannot change which route answers.

---

# Stage 4 — Jurisdiction-aware regulatory policy

## D-032 — Jurisdiction, authority, licence category, pack version and dates are separate; country decides nothing
**Date:** 2026-10-20 · **Stage:** 4
**Context:** Applicability used to be `profile.jurisdiction === 'TZ'` plus a licence category letter, with TZ/B as the default for every organization (F-12, R10). The Tanzanian situation itself shows why a country is not a law. Checked on 2026-10-20 against published sources: Tanzania Mainland SACCOS fall under the Microfinance Act No. 10 of 2018 and GN 675 of 2019, with Tier 3 powers delegated to TCDC by GN 887 of 2019. Zanzibar SACCOS fall under the Zanzibar Microfinance Service Act No. 9 of 2023 and L.N. 58 of 2025. The regulator is the same (Bank of Tanzania), but the thresholds differ: core capital Category A is TZS 100 m in Zanzibar against 10 m on the Mainland, and Category B is 5 m against 200 m.
**Decision:** The platform reference data is split into four tables:
- `regulatory_jurisdictions`: a sub-national legal territory with a country code, support status and example flag.
- `regulatory_authorities`: primary licensing authority or delegated supervisor, with its statutory basis.
- `regulatory_licence_categories`: categories belong to the authority that issues them.
- `regulatory_catalogue_events`: an append-only change log.

Each pack is tied to ONE jurisdiction and ONE authority (`jurisdiction_id`, `regulatory_authority_id`) and lists its categories. Its legal effective date and its platform `effective_from` are recorded separately. The organization profile records:
- operating jurisdiction;
- licensing authority;
- supervising (delegated) authority;
- licence category;
- licence number;
- licence effective date;
- a `determination_status` with basis, source, who decided and when.

`RegulatoryPack::covers(jurisdiction, authority, category)` is the only applicability test. The legacy `jurisdiction` / `licence_category` columns are informative mirrors, and writing them changes nothing (tested).
**Consequences:** The seeded reference data is:
- TZ-MAINLAND: supported. Authorities are BOT (primary) and TCDC (delegated). Categories are A and B.
- TZ-ZANZIBAR: unsupported, because no reviewed pack exists. Authorities are BOT (primary) and DCD (possible delegated authority; whether a delegation is in force is not confirmed). Categories are A and B, with the Zanzibar figures in their descriptions.

Platform screens manage this catalogue (Platform → Jurisdictions). Example jurisdictions must use an X-prefixed code and cannot be mixed with real data.

## D-033 — Three policy layers; invariants are forced
**Date:** 2026-10-20 · **Stage:** 4
**Decision:** Policy is split into three layers.
1. **Platform invariants** (`PlatformInvariants`) hold for every organization:
   - balanced journals;
   - tenant isolation;
   - append-only audit;
   - maker–checker;
   - loans need an authorised approver other than the applicant;
   - period control;
   - idempotent money events;
   - effects after commit;
   - no tenant code;
   - statutory floors cannot be weakened.

   Where an invariant is also a rule key (`governance.segregation_of_duties`), the resolver forces its value. The source is `platform_invariant`, the rule is locked, and `check()` refuses any weaker value, with or without a pack.
2. **Mandatory jurisdictional rules** come only from the adopted, covering pack.
3. **Organization policies, settings and products** sit inside the pack's optional `permitted_bounds` (`{min,max}` on numeric rules, enforced by `check()`/`assertWithin`).

The accounting "segregation of duties" toggle is removed. `JournalService` always enforces maker–checker. The settings screen shows the safeguard as always on, and a stored `false` is ignored (tested).
**Not made an invariant:** credit-committee approval (`lending.credit_committee_approval`). *Who* approves is jurisdictional or organizational. *That* an authorised approver other than the applicant approves is the invariant, and it is enforced in `LoanService`.

## D-034 — No default framework; the platform determines applicability; organizations request it
**Date:** 2026-10-20 · **Stage:** 4
**Decision:** A new organization is `undetermined`:
- no country, category, pack or framework is assumed;
- the column defaults are now NULL / `not_applied`;
- provisioning no longer records a default framework.

An organization asks through Policy Administration → Regulatory applicability (`ApplicabilityService::request`). There are four request kinds:
- `determination`: a supported jurisdiction, the licensing authority and the category;
- `not_regulated`;
- `exception`: an unsupported jurisdiction;
- `pack_adoption`: for packs whose adoption policy is `platform_approval`.

Every request needs a statement of evidence. A Platform Regulatory Administrator decides it with a recorded basis. The requester cannot decide their own request. Platform screens can also record a determination directly; the screens are Determinations, and an optional section on organization creation. A determination that the adopted pack no longer covers stops that pack and records the change in the organization's package history.

**Upgraded installations:** profiles that applied the Mainland pack are carried over as `determined` with source `carried_over`. The platform screen flags them for confirmation. This keeps existing operations running, but the carried-over determination is itself the old TZ/B assumption until someone confirms it. All other profiles become `undetermined`.

## D-035 — Releases never approve packs; legal review is explicit
**Date:** 2026-10-20 · **Stage:** 4
**Decision:** `RegulatoryBaselineInstaller::install()` / `installSecurityRelease()` now install the shipped Mainland packs as **submitted**:
- no approver;
- `legal_review_status = required`;
- provenance recorded (D-036).

Approval needs two different Platform Regulatory Administrators, as before. While professional legal review is outstanding, approval also needs an explicit acknowledgement, which is recorded in the approval event and shown to organizations as a warning. Recording a legal review (reviewer, date, scope) is a separate action, and example packs can never be marked reviewed.

On an **upgraded** database, the earlier releases had already marked the packs approved with no approver. Those versions stay in force for continuity, and an `approval_unattributed` event now says plainly that no administrator approved them.

**Consequence for a fresh installation:** no organization can operate regulated activities under the Mainland pack until two administrators approve it. This is intended.

## D-036 — Legal content: what was verified, and what still needs professional review
**Date:** 2026-10-20 · **Stage:** 4
**Verified (2026-10-20, secondary copy of GN 675/2019 — the Bank of Tanzania PDF could not be retrieved from the build environment):** the pack's thresholds match the published text:
- core capital 10 m / 200 m;
- capital ratios 8 / 6 / 6 %;
- maximum maturity 5 years;
- single-loan limits 10 % / 5 % of core capital;
- delinquency at 30 days;
- provisioning 10 / 30 / 50 / 100 %;
- non-accrual at 90 days;
- one restructure and 4 instalments;
- liquidity 15 %;
- single bank 25 %;
- external borrowing 25 %;
- investments 10 % / 5 %;
- audit within 4 months;
- auditor rotation after 3 years;
- disclosure in Kiswahili, or Kiswahili and English;
- 14 days' notice.

**Not changed, flagged for professional review:**
1. The board minimum is Reg. 24(2) in the published text; the pack cites 24(1).
2. Write-off under Reg. 43(1)(a) is permissive ("may"); the pack treats it as a requirement after 365 days.
3. The legal commencement date is not confirmed. The platform `effective_from` (2020-01-01 for v1) is an application choice, recorded as such in `legal_effective_note`.
4. Whether TCDC's delegation (GN 887/2019) is still in force.
5. Whether a Zanzibar delegation to DCD exists.

No threshold, tax rate or approval was invented. Changing a cited figure belongs in a reviewed new pack version.
**Submission rule:** a non-example pack can be submitted only with:
- an official citation;
- a source link or attached text;
- a verification date and note;
- a legal effective date, or a note explaining why it is not confirmed.

Every new version must be re-verified.

## D-037 — Regulated operations wait for a determination; adoption follows an explicit policy; tenants cannot switch law off
**Date:** 2026-10-20 · **Stage:** 4
**Decision:** `RegulatoryGate` blocks three regulated activities: taking deposits (`SavingsService::recordDeposit`, excluding internally funded credits such as dividends), selling share capital (`ShareService::purchaseShares` / `recordPendingPurchase`), and lending (`LoanService::approve`, `LoanDisbursementService::disburse`).

These activities run only in one of three situations:
- `determined`, and an applicable approved pack is adopted and in scope on the date (licence effective date respected);
- `not_regulated`;
- `exception_approved`.

Blocked attempts are refused with a plain message and audited (`regulatory.activity_blocked`). Set-up (products, policies, members, settings) is never blocked. The screens say that "not regulated" and "exception" do not establish compliance.

Each pack carries an `adoption_policy`. `self_service` means a determined organization in scope adopts it itself with a Board-resolution reason. `platform_approval` is the column default for new packs and means adoption is a request. The shipped Mainland pack is `self_service`: the platform's control is the determination, and adopting the law that covers you only tightens rules.

`RegulatoryPackageService::deactivate` refuses a tenant when the organization is determined (audited `regulatory.deactivation_refused`). Only a platform determination takes an organization out of scope.

## D-038 — Historical reproducibility without recalculation
**Date:** 2026-10-20 · **Stage:** 4
**Decision:** Four mechanisms keep the past reproducible.
- Organizations stay pinned to the pack version they adopted (unchanged since the package release).
- `StatutoryPolicyResolver::snapshotAt(org, date)` rebuilds the rules in force at the end of a past date from the activation current then and the organization policy versions in force then.
- `RegulatoryEvidence::record()` writes an append-only `regulatory_decision_records` row when a loan is approved, a loan payout settles, or a restructure is approved. The row holds:
  - pack id, version and content hash;
  - policy generation;
  - the determination scope;
  - the organization policy version ids;
  - each relied-on rule's value, source, statutory value, reference and lock.
- Nothing recalculates completed records when a pack or policy changes; the new rules apply to the next action, as before.

A test shows a decision under v1 (24 months) still reads 24 after v2 (12) takes effect, and that `snapshotAt` returns v1 for that date.

## D-039 — Pack lifecycle states
**Date:** 2026-10-20 · **Stage:** 4
**Decision:** The pack states are:
- `draft`;
- `submitted`;
- `approved` (approved, effective date in the future);
- `effective`;
- `superseded` (replaced by a newer version that has taken effect);
- `retired` (withdrawn by the platform, with a reason; never adoptable again).

The migration maps the old states:
- old `retired` → `superseded`;
- old `approved` in force → `effective`;
- old `approved` ended → `superseded`.

`advanceLifecycle()` replaces `retireSuperseded()`. It runs on approval and nightly in `policies:daily`, moving approved → effective and effective → superseded, with events (`took_effect`, `superseded`). Superseded and withdrawn versions stay the law for their own dates. A withdrawn version still applies, with a warning, to organizations pinned to it until they adopt a replacement.

## D-040 — Neutral behaviour when no pack applies (F-12 / inventory A1, A3, B1)
**Date:** 2026-10-20 · **Stage:** 4
**Decision:** Without an adopted covering pack, the resolver uses `RuleCatalogue`: the built-in rule keys with every statutory value, statute-derived default, BoT reference, TZS unit and BoT note stripped. Controls keep working on the organization's own policies and settings only, and no BoT number becomes a "default". The country-based built-in fallback is removed.

`RegulatoryText` cites neutrally ("the organization's policy") and strips "(Reg. N)" from built-in sentences. `frameworkTitle()` no longer falls back to the BoT title. The pack citation prefix falls back to "Regulation", not "BoT Regulation".
**Consequence:** with no pack installed, a determined organization fails closed: no statutory values and regulated operations blocked. The old behaviour (built-in BoT values for a "Tanzanian" organization) is gone on purpose.

## D-041 — Typed pack content only: reports, bounds and named calculation strategies
**Date:** 2026-10-20 · **Stage:** 4
**Decision:** Packs gain two typed additions:
- **Rule type `report`:** value `{report, frequency, due_days}`. Report kinds are features the application can produce (`RegulatoryReports`); unknown kinds are refused.
- **`permitted_bounds`** on rules.

Extension rules may only name a documented strategy in `CalculationStrategies`, such as capital ratios, liquidity ratio, term in months, DPD classification or single-loan limit. Each strategy lists its inputs, output, pack parameters and implementing class. Tenant input is never evaluated.

The Platform → Safeguards page lists invariants, strategies and report kinds.
**Known limitation:** the DPD classification day bands (30/90/180/365) are fixed in code. Only the provision percentages come from the pack, and the strategy description says so (inventory A7).

## D-042 — Existing tests changed in Stage 4
**Date:** 2026-10-20 · **Stage:** 4
**Decision:** Each change follows from D-032…D-041. No assertion was removed to obtain a pass; refused-behaviour assertions were added where the old path no longer exists. The full list is in TEST_BASELINE Stage 4.

The fixture `pinLegacyBaseline` now does three things:
- records an explicit TEST determination (Mainland, BOT, B);
- moves the shipped packs to approved/effective/superseded as two administrators would (labelled TEST FIXTURE ONLY; the real approval path is tested separately);
- pins v1.

## D-043 — Tanzanian assumptions deliberately left for later stages
**Date:** 2026-10-20 · **Stage:** 4
**Decision:** The inventory (IMPLEMENTATION_STATUS Stage 4) lists 79 findings. Fixed in this stage:
- A1–A6, B1–B5, B7;
- A3 and A30 citations;
- the A13-related bank list now follows the operating/default country, not timezone (B5).

Not fixed, with reasons:
- **A7** DPD bands (needs a reviewed classification strategy per jurisdiction).
- **A8** separate restructured receivable (kept: a stricter accounting presentation, not a legal leak).
- **A9** restructure setting defaults (stored organization settings; editable).
- **A10–A11** application timezone (cross-cutting date semantics; separate change with its own tests).
- **A12–A14** bank country default, sort-code wording, member import (reference data).
- **A15–A21** HR calendar, payroll levy vocabulary, due dates, GL routing (Workforce redesign; payroll rates are already per-organization DRAFT data that apply only once approved).
- **A22–A25** governance approving bodies and declarations.
- **A26–A28** disclosure wording.
- **A29** prudential return currency.
- **A31–A35** phone / mobile-money / import parsing.
- **B6** network catalogue.

These items cannot apply a statute to anyone. They are local defaults, wording or data formats that are wrong for other countries, and they remain recorded risks (R-20…R-24).

---

# Stage 5 — SaaS control plane

## D-044 — Billing is its own module; platform money never touches tenant ledgers
**Date:** 2026-10-20 · **Stage:** 5
**Decision:** A new `Billing` module (layer 5, after Reference; depends only on Tenancy and Identity) owns every `billing_*` table: settings, plans, plan versions, prices, customers, signups, signup steps, subscriptions, invoices, checkout sessions, provider events, usage counters, activity and exceptions.
- No Billing class writes to `journal_*`, `savings_*`, `payment_*` or any other tenant financial table. The Architecture suite enforces this (cross-module writes) with **no new exception**.
- Billing amounts are integers in minor units (`Currencies::toMinor` parses strings exactly; no floats).
- `billing_activity` is append-only at the database level (update/delete triggers), like the Stage 2 audit log.
- The existing tenant payment drivers in `Payments` (including `FlutterwaveV4Driver`, used for member deposits and loan repayments with each SACCO's own credentials) are **not** reused for subscriptions: they have no subscription/token-charge capability and use tenant credentials. The billing gateway is a separate class with the platform's own merchant credentials (`BILLING_FLUTTERWAVE_*`, environment only).
- Platform creates tenants for Billing through the `Billing\Contracts\TenantProvisioner` contract (implemented in Platform), so Billing stays below Platform in the layer order.

## D-045 — Plans, immutable price versions and the annual charge
**Date:** 2026-10-20 · **Stage:** 5
**Decision:**
- A **plan** (code, name, public/active flags) has **versions**: draft → published → retired. A published version and its prices are immutable (model guards throw; the service refuses). Changing a price means publishing a new version, which retires the previous one. Subscriptions keep the price row they bought (`price_id`), so existing customers are never silently repriced.
- A version holds: trial days (0–90), annual discount percent (0–50, two decimals), entitlements (members, staff, storage MB, SMS per month, modules) and an overage policy per metric (`block` or `allow_and_record`).
- Prices: one row per (version, currency, interval). The administrator enters the **monthly** price per currency; the yearly price is computed once, at draft save: `intdiv(12 × monthly × (10000 − discount_bp) + 5000, 10000)` (half-up in minor units). `list_amount_minor` keeps 12 × monthly, so the pricing page can state the real saving. The yearly price is **the amount charged once a year**, and the page says so.
- Invoices carry a **snapshot** (plan code, version, price id, currency, interval, list amount, discount, tax rate and label, subtotal, tax, total). `Invoicing::expectedTotal(snapshot)` recomputes the total from the snapshot and the webhook processor refuses any payment for an invoice whose stored total does not match it.
- Tax: platform setting `tax_rate_percent` (default **none**) and label. No tax rate is invented; see D-054.
- Plans and settings are managed on Platform → Billing by the super-admin only (`BillingAuthorization::isBillingAdmin`).

## D-046 — Purchase modes: disabled, demo, test, live; secrets stay in the environment
**Date:** 2026-10-20 · **Stage:** 5
**Decision:** `BILLING_MODE` (environment only, default `disabled`) selects the mode. The platform dashboard shows it and shows **only booleans** about credentials (configured / not configured); it cannot switch real charging on and never displays a key.
- **disabled:** pricing is shown; buying says "Online purchase is not open yet".
- **demo:** a simulated provider page with **no card fields** (choose successful / failed / authentication). Events are HMAC-signed with an app-derived secret and go through the same ingestion and processing pipeline. Every public page carries a "DEMONSTRATION — no real payment" banner, buttons say "Try the demo purchase", subscriptions are stored with `mode = demo`, and demo routes and the demo webhook return 404 in any other mode.
- **test:** provider sandbox; "TEST MODE" banner; a key without `_TEST` is refused.
- **live:** a `_TEST` key is refused (purchases disabled with a visible reason).
Business settings (retry days, grace days, restricted retention, checkout and signup expiry, verification resend limit, tax rate/label, enabled currencies, upgrade proration) are browser-configurable by the platform billing administrator, validated and logged.

## D-047 — Provider: Flutterwave (v3 API) with app-owned schedule; Paddle as the documented alternative
**Date:** 2026-10-20 · **Stage:** 5
**Evidence gathered (official provider documentation and announcements, read 2026-10-20 with the web tools):**
| Provider | Tanzania merchant | Recurring | TZS | Webhook auth | Result |
|---|---|---|---|---|---|
| Stripe | Not in supported countries | Native | — | HMAC + timestamp | Excluded |
| Paystack | Merchant countries do not include Tanzania | — | — | — | Excluded |
| Pesapal | Tanzanian merchants | Recurring offered | Yes | IPN **unsigned** (pull status) | Excluded for subscription webhooks |
| Paddle (Billing) | Sellers in any non-sanctioned country; merchant of record | Native subscriptions | **No** (USD etc.) | HMAC over `ts:rawBody` | Alternative |
| **Flutterwave** | Bank of Tanzania payment-service authorization announced | Tokenized charges, payment plans | **Yes** | v3: `verif-hash` = shared secret; v4: base64 HMAC-SHA256 of the raw body | **Chosen** |

**Decision:** implement `FlutterwaveGateway` against the v3 API:
- hosted checkout (`POST /payments` → `data.link`; `payment_options = card`), so no card data ever reaches Kopeza;
- verification (`GET /transactions/verify_by_reference?tx_ref=`);
- saved-card renewals (`POST /tokenized-charges`) — the **application owns the schedule** (D-050) instead of provider payment plans, so period, retries, proration and grace are under our tested policy;
- refunds (`POST /transactions/{id}/refund`).
Why v3 here although tenant payments were moved to v4 only (Stage 3 payments work): Flutterwave's v4 API documents no hosted card checkout, while the current tokenization guide documents the first card payment returning `data.card.token` and `POST /v3/tokenized-charges` for merchant-initiated charges, with the merchant owning the subscription lifecycle. Tokens are bound to the customer e-mail used in the first charge, so Billing keeps that e-mail on the billing customer and charges with it. Tenant payments remain v4-only; the code-scan test now names the billing gateway as the single permitted v3 user (D-053).
Because v3 webhook authentication is a shared secret (not a signature), **every webhook is only a hint**: the processor re-fetches the transaction from the API with the secret key and validates that (D-048). If v4 signatures are enabled on the account, the gateway verifies the HMAC over the raw body instead.
**Not verified / live blockers (recorded, not assumed):** the platform's own merchant account approval for card acceptance from a Tanzanian entity; whether tokenized (merchant-initiated) charges are enabled on that account and how 3-D Secure is applied to them; settlement currency (TZS vs USD) and FX; chargeback/dispute webhooks on the account; TRA EFD/VAT obligations for SaaS invoices. No credentials exist in this environment, so **no sandbox call was made**; the gateway is exercised against a deterministic contract double built from the documented request/response shapes (`tests/Support/FakeFlutterwave.php`). There is no claim of live certification.
**Alternative:** Paddle (merchant of record, USD) if the business accepts USD-only pricing and Paddle's onboarding; it would be a second `BillingGateway` implementation.

## D-048 — Webhooks: raw-body verification, inbox, deduplication, re-verification, reconciliation
**Date:** 2026-10-20 · **Stage:** 5
**Decision:**
1. `POST /webhooks/billing/{provider}` (CSRF-exempt, no session) passes the **raw body** and headers to the gateway. A missing or wrong `verif-hash`, or a v4 signature that does not match the exact raw bytes, returns 401, stores nothing and raises a platform exception.
2. Replay safeguards: authentic events are stored in `billing_events` with a unique (provider, mode, event_key); a repeat returns 200 `duplicate` and is not processed again. An authentic event older than `max_event_age_days` (30) is acknowledged as `stale` and not applied. Because v3 has no signed timestamp, the decisive safeguard is (3).
3. Processing (`EventProcessor`, queued after commit; claimed by a conditional update; retried with exponential back-off up to 8 attempts, then an exception) **re-reads the transaction from the provider** and validates against the invoice: provider reference belongs to that invoice; mode; merchant account id; currency; amount equals the invoice total; invoice total equals the server-side snapshot total; customer e-mail. Any mismatch leaves the invoice unpaid and raises `payment_mismatch`.
4. Every payment attempt has its own provider reference (`<invoice reference>-<n>`), so a late failure of attempt 1 cannot undo a confirmed attempt 2, and a failure reported twice (charge response + webhook) counts once (`failed_references`). Periods only move forward.
5. Unknown `kpz_` references are **deferred** and retried (an event can arrive before our transaction commits); other references (e.g. tenants' member payments on a shared account) are ignored.
6. `billing:reconcile` (every 10 minutes) asks the provider for the state of open checkouts and charges, so a payment whose webhook never arrives is still applied — through the same validation.
7. The browser return page **never** applies anything from its query string; it asks the provider server-side and shows "confirming" until the provider says paid.

## D-049 — Entitlements: counting, reset, overage, downgrade, concurrency
**Date:** 2026-10-20 · **Stage:** 5
| Metric | Counted as | Reset | Enforcement |
|---|---|---|---|
| Members | users with `is_admin = 0` and type ≠ employee | never (stock) | `assertCanAdd` inside the creating transaction, under a lock on the organization row (admin form, self-registration) |
| Staff | `is_admin = 1` or type employee | never | same (admin accounts, HR onboarding, recruitment hire) |
| Storage MB | bytes under the organization's storage prefix, measured daily (`billing:measure-storage`) | re-measured | uploads refused when the measured value is at the limit (approximate between measurements) |
| SMS / month | messages counted by the SMS dispatcher and campaign job | UTC calendar month | atomic conditional increment (`used <= limit − n`) |
| Modules | optional modules (HR/payroll, governance, website, events, support desk, marketing, AI insights, groups, referrals) | — | writes refused when not in the plan; reads allowed |
- Overage policy per metric: `block` (refuse, with the readable reason) or `allow_and_record` (allow and log `overage_recorded` / `overage` counter for invoicing by the platform).
- **Downgrade:** nothing is removed. Usage above the new limit is kept; only additions are refused. Modules leaving the plan become read-only.
- Organizations without a subscription (created by the platform, or before Stage 5) keep their existing `max_members`/`max_staff` columns, all modules and unmetered SMS.
- Concurrency: tested with forked processes (last member slot → exactly one winner).

## D-050 — Subscription states, access restriction and policies
**Date:** 2026-10-20 · **Stage:** 5
**States:** incomplete → trialing / active → past_due → grace → restricted → expired; canceled. Service (normal use) in trialing, active, past_due and grace. `billing:advance` (hourly, idempotent) moves time-driven transitions:
- Renewal at period end: invoice issued once per period (idempotent), charged with the saved provider token; result applied only after the provider confirms (D-048).
- Failure → past_due; retries on days 1, 3 and 5 after the due date (setting); when retries are used up → grace (7 days) → restricted; restricted for 60 days (setting) → expired. **Data is never deleted** by any state.
- Authentication required (3-D Secure on a merchant-initiated charge): invoice `requires_action` with the provider's URL shown on the billing page; status reason `authentication_required`.
- Trial: no card needed. At the end, a saved card is charged; without one the subscription is restricted (`trial_ended`).
**Restricted / canceled / expired access** (`billing.access` middleware on admin and member shells): every GET still works (records, reports, exports); writes are refused **except** an allow-list: billing pages and payment, profile/security/notifications, and financial events already under way (deposit confirmation/reversal, withdrawal approval/rejection, loan repayments and disbursement of approved loans, guarantor recovery payments, payroll payment confirmation, dividend payouts; member loan repayment and withdrawal requests). Webhooks, queued jobs and scheduled commands are not affected. The same allow-list also applies when a module is outside the plan. Super-admins are not restricted.
**Policies:**
- Cancel: at period end (resume possible until then); a trial or an unpaid subscription cancels immediately; open invoices are voided.
- Upgrade (same interval, higher monthly price): prorated invoice for the remaining period (seconds-based, half-up); the plan switches only when the provider confirms payment; the period end does not change.
- Downgrade or interval change: scheduled for the period end and applied at renewal.
- Currency cannot change on a subscription.
- Refund: super-admin only, through the provider, at most the unrefunded amount, with a reason; optional immediate cancellation; recorded once.
- Disputes: `open` → platform exception only (no service change); `lost` → recovery invoice and past_due (its payment restores standing **without** extending the paid period); `won` → exception closed. Repeated notices change nothing.
Customer-visible status: Settings → Subscription (plan, usage vs limits, invoices, pay, change plan, cancel/resume, the reason for any restriction). Platform: subscriptions, invoices, events, exceptions queue with retry and resolve actions.

## D-051 — Self-service signup: pending signup, provisional billing identity, verification separate from payment
**Date:** 2026-10-20 · **Stage:** 5
**Decision:** The public pages (`/pricing`, `/signup`, platform host only) create a **pending signup**, not a tenant: organization name, requested subdomain (validated against existing organizations and open signups), owner details, country, timezone, chosen price and trial flag.
- A provisional `billing_customers` row (no organization yet) is the billing identity for checkout.
- Owner e-mail verification is a separate, hashed, single-use token with expiry. Payment never verifies the e-mail and verification never activates paid service. Failed verification e-mails are recorded and visible; resend is throttled and limited (setting); three failures raise a platform exception.
- Paid path: verified → checkout (hosted) → provider-confirmed payment → ready → provisioning → active. Trial path: verified → trialing subscription → ready.
- Unverified signups expire (setting, default 72 h) and release the subdomain.

## D-052 — Provisioning as durable, retryable steps with a unique signup→tenant constraint
**Date:** 2026-10-20 · **Stage:** 5
**Decision:** `SignupProvisioning` runs three recorded steps — `create_tenant`, `attach_subscription`, `activation_email` — each with status, attempts, last error and next attempt (back-off 5·2^(n−1) minutes, 6 attempts, then a platform exception; platform retry button).
- `OrganizationProvisioningService::provision()` was refactored into an explicit operation that accepts a signup reference; `organizations.signup_reference` is **UNIQUE**. A re-run finds the existing tenant; a concurrent duplicate insert is caught as a unique violation and resolved to the existing tenant. Tested with four forked workers → one tenant, one owner.
- Payment is never lost or undone by a provisioning failure: the invoice stays paid, the signup shows "Anything you paid is safe; we retry automatically", and the subscription period is extended by any provisioning delay over an hour.
- The activation e-mail (set-password link) is a separate step; its failure leaves the tenant active and can be resent by the owner from the signup page or by the platform — never creating a second tenant.
- The owner's `email_verified_at` is copied from the signup's verification time, not set by payment.

## D-053 — Existing tests changed in Stage 5
**Date:** 2026-10-20 · **Stage:** 5
**Decision:** Two existing tests changed; no assertion was removed:
- `Payments/FlutterwaveV4Test` "no Flutterwave v3 runtime endpoint": the scan now expects exactly one file, the platform billing gateway (D-047). Any v3 use in tenant payment code still fails the test.
- `Security/StoredScriptAndHeadersTest` CSRF exemptions: `webhooks/billing/*` added to the exact expected list (D-048); the list is still compared exactly.
Test support: `BillingFixtures` added to the Feature and Concurrency test bases; `FakeFlutterwave` is a contract double with `Http::preventStrayRequests()`.

## D-054 — Things deliberately not decided by code
**Date:** 2026-10-20 · **Stage:** 5
- **Tax:** no VAT/withholding rate is configured or assumed. The platform may set a rate and label; invoices then show it and the snapshot includes it. Whether Kopeza's SaaS invoices need TRA EFD receipts is a business/legal question (blocker in IMPLEMENTATION_STATUS).
- **Provider selection is provisional** until the merchant-account checks in D-047 are confirmed in writing by the provider.
- **Storage** is measured daily and is approximate in between.

---

# Stage 6 — Tenant domains and the organization set-up wizard

## D-055 — One exact-hostname registry for every tenant alias, unique across all states
**Date:** 2026-10-20 · **Stage:** 6
**Decision:** `organization_domains` (Tenancy) is the only source of truth for which host serves which organization.
- Every alias is a row: each free sub-domain under each platform base, and each custom domain. Hosts are normalised (lower case, no port, no trailing dot, IDN to punycode).
- `host` is UNIQUE across **all** rows: active, pending, failed and retained. A host can therefore never belong to two organizations at once, and the database refuses it even if application checks are bypassed.
- Only rows with `status = active` and `activated_at` set resolve a request (`HostResolver`). Unknown, pending, failed and removed hosts get 404; there is no guessing and no fallback organization.
- Reserved names: the configured labels (www, app, api, admin, billing, mail, …, plus `TENANCY_RESERVED_LABELS`), platform hosts, anything under a platform base domain (those must be free sub-domains), IP literals, and private suffixes (local, internal, lan, corp, …).
- A changed free sub-domain is **retained**, not freed. The organization can take it back; others cannot until the retention period ends.
- The self-service signup subdomain check now uses the same registry (`DomainRegistry::subdomainProblem`), so a retained name cannot be signed up for.

## D-056 — Custom domains: four separate conditions before activation
**Date:** 2026-10-20 · **Stage:** 6
**Decision:** reserve → issue an expiring random TXT challenge → verify ownership → verify routing → provision at the edge → certificate valid → HTTPS answered by this application → active.
- Each condition is a separate column with its own time: `ownership_verified_at`, `routing_verified_at` (with the records observed), `certificate_status` / `certificate_expires_at` / `certificate_issuer`, `https_ready_at`, and finally `activated_at`.
- **Ownership** is DNS TXT `_kopeza-verify.<host>` = `kopeza-verify=<40 random characters>`. The code expires after 72 h (setting) and can be renewed; a renewed code invalidates the old one.
- **Routing:** a CNAME to the edge target, or A/AAAA records that are *all* edge addresses.
- **Certificate validity and HTTPS readiness are distinct facts.** A valid certificate with a wrong answer is not ready.
- DNS pointing at the server never activates anything, and neither does an ownership proof alone (both are tested).
- **Retries and propagation:** exponential back-off from 2 minutes up to 6 hours, with the observed DNS shown. After 12 attempts the domain is `failed` (visible to the tenant and the platform); a manual "Check now" resumes from the right step.
- **Active domains are re-checked daily:** routing, certificate validity, expiry within 14 days (`expiring`), and failure (`failed`). Renewal is observed, never assumed.
- **Removal** stops serving at once and keeps the row `retained` for 30 days. Anyone claiming it again, including the same organization, starts with a fresh code and all four conditions. The platform may release a held host early, with a recorded reason.
- History of every step is kept in `organization_domain_events`.
- Free sub-domains are active at creation, because the platform owns the base zone and its wildcard certificate (infrastructure, guide §3).
- **Changed behaviour:** before Stage 6 a TXT proof (or `tenancy:map-domain --verified`) made a custom host serve immediately. Now `--verified` only records ownership; routing, certificate and HTTPS still apply. Existing verified rows were carried over as active by the migration.

## D-057 — Edge adapter: Caddy on-demand TLS (supported), operator-managed, none; a real HTTPS probe
**Date:** 2026-10-20 · **Stage:** 6
**Decision:** a `Tenancy\Contracts\EdgeAdapter` with three implementations, chosen by `TENANCY_EDGE` (environment only):
- **`caddy` — Caddy on-demand TLS.**
  - Caddy obtains a certificate on the first handshake only if the application's ask endpoint approves the host.
  - The endpoint approves only platform hosts, active hosts, and custom hosts whose ownership and routing are verified.
  - It requires a secret path segment, and the TCP peer address must be in an allow-list (never a forwarded header).
  - Pointing DNS at the edge therefore cannot obtain a certificate, which guards against hostname takeover and ACME abuse.
- **`operator`** — the operator installs certificates by hand (nginx/certbot); readiness is still probed.
- **`none`** — custom domains can be reserved and proven but never activated.

**HTTPS readiness is never taken from the adapter.** `TlsHttpsProbe`:
1. connects only to `TENANCY_EDGE_PROBE_ADDRESS`, never to a DNS answer, which is the SSRF guard;
2. performs TLS with SNI = host and full chain and hostname verification;
3. reads the certificate expiry;
4. requests `/.well-known/kopeza-domain-check/<nonce>` and compares the response to an HMAC under the application key.

That route answers only for hosts in provisioning or active state; it uses no session or cookies.

**Why Caddy:** it is a single-binary edge that fits a single deployment. Its on-demand mode is designed for SaaS custom domains, and the approval hook keeps the decision in our registry.

**Evidence and limits:** the probe was tested against a real local TLS server with a generated CA (valid host, wrong host, untrusted issuer, wrong answer). Caddy, ACME and public DNS were **not** exercised (see IMPLEMENTATION_STATUS blockers). Setup guide: `docs/operations/custom-domains.md`.

## D-058 — Host-only sessions; forwarded host never trusted
**Date:** 2026-10-20 · **Stage:** 6
**Decision:**
- **Sessions:** `config/session.php` fixes `domain` to null, so session cookies are host-only and `SESSION_DOMAIN` is ignored. A parent-domain cookie would reach every tenant sub-domain, and cookies cannot span unrelated custom domains anyway. Users sign in per address.
- **Secure cookies:** `secure` defaults to true in production.
- **Proxies:** `TRUSTED_PROXIES` enables trust only for `X-Forwarded-For/Proto/Port` from listed proxies. `X-Forwarded-Host` is never trusted (tested). The tenant is always chosen from `Host`.
- **Edge endpoints:** they run without session, CSRF or cookie middleware.

## D-059 — Domain management screens and permissions
**Date:** 2026-10-20 · **Stage:** 6
**Decision:**
- **Tenant screen:** Settings → Web addresses (`admin.settings.domains.*`, permission `manage-domains`, given to the admin role by migration). It offers:
  - change the free name;
  - add a custom domain;
  - Check now, new code, make main address, remove.
- **What the tenant sees:** the exact TXT, CNAME or A/AAAA records (and the ALIAS / CNAME-flattening alternative for a root domain without static edge addresses), what DNS currently shows, each condition, the last error, the next check and the history.
- **Isolation:** another organization's row answers 404.
- **Branding form:** the address fields were removed from it; it now links to this page.
- **Platform screen:** Platform → Domains (super-admin) lists hosts needing attention and offers Check now and release with a reason.
- **Rate limits:** each limiter has its own budget. `domain-actions` allows 20 per minute per user; `edge-checks` limits by IP.

## D-060 — Organization set-up wizard: saved drafts, completion from real records
**Date:** 2026-10-20 · **Stage:** 6
**Decision:** a new **Onboarding** module (layer just below Platform), with table `onboarding_steps` holding one row per organization and step: draft JSON, version, issues, `completed_at`/`by`. It has ten steps:
1. Owner identity, confirmed e-mail and two-factor sign-in.
2. Profile and contacts. New Tenancy columns: legal name, registration number, contact e-mail and phone, addresses, contact person.
3. Jurisdiction, regulation, language, timezone and currency. The regulatory part is the platform's determination (Stage 4); the wizard links to the applicability request page and never decides the law.
4. Accounting: functional currency, chart, mappings and an open financial year (from the Accounting checklist); opening balances when migrating.
5. At least one branch, at least two active staff accounts (money approvals need a second person under the maker–checker invariant), and roles and approval workflows reviewed.
6. Products: an active savings product, plus loan and share products if offered.
7. At least one active payment method; gateway integrations optional.
8. Website: publish (look, headline, contact) or "not now".
9. An active free address. **Custom-domain propagation never blocks this step.**
10. Final validation and activation.

**Rules:**
- **A saved draft is never completion.** Drafts accept partial input (format checks only) and change no records.
- **"Complete this step"** validates fully, applies the wizard-owned values through the owning module's operation (`OrganizationLifecycle::updateProfile` / `updateLocale`), then evaluates the criteria from the real records. Only if all hold is the step complete; otherwise the draft is kept and the missing items are listed.
- **Everything else** is configured on the owning module's own screen, linked from the step. The wizard never bypasses those screens' rules.
- **Return visits:** the overview resumes at the first unfinished step; progress counts complete steps.
- **Safe editing:**
  - Status is recomputed on every visit; a completed step whose records no longer meet its criteria shows "needs attention".
  - "Edit this step" re-opens it.
  - A version number refuses a stale save ("someone else saved this step").

## D-061 — Operational activation gates regulated financial operations
**Date:** 2026-10-20 · **Stage:** 6
**Decision:**
- **New columns:** `organizations.operational_status` (setup | active), `operational_activated_at` / `by` / `source`. New organizations start in set-up.
- **Who activates:** activation is recorded by the wizard only when every step 1–9 is complete, the regulatory policy condition holds, and any subscription is in service. It is done by the organization's owner or an administrator with confirmed two-factor sign-in, with an explicit confirmation. It is audited.
- **The gate now has two conditions:** `RegulatoryGate::status()` requires operational activation **and** the policy condition (`policyStatus()`). Deposits, share sales, loan approval and payout (every existing gate call) are refused with a readable message until both hold, and the refusal is audited with the operational flag. Set-up work itself is never blocked.
- **No automatic deactivation:** activation is not undone automatically when a step later needs attention, because that would block financial events already under way. The regulatory policy condition is still enforced independently on every operation.
- **Upgraded installations:** the migration marks every existing organization `active`, source `carried_over`, because they were already operating. The test fixture does the same (TEST FIXTURE ONLY); the wizard tests use organizations created by the real provisioning service.
- **Other screens:** the platform organization page shows operational status, and the tenant dashboard shows a set-up banner.

## D-062 — Existing tests changed in Stage 6
**Date:** 2026-10-20 · **Stage:** 6
**Decision:** see TEST_BASELINE Stage 6. No assertion was removed to obtain a pass; the changed tests assert the stricter behaviour.

---

# Stage 7 — Website publishing

## D-063 — Website publishing inside the Website module; existing public features kept
**Date:** 2026-10-20 · **Stage:** 7
**Decision:** publishing is built in `Website\Publishing`. It owns `website_sites`, `website_revisions` and the media columns `width`, `height` and `alt_text`. Website already owned the public site and depends on the modules whose public data it shows.

**Before the first publish** nothing changes: every existing public page renders as before.

**After the first publish:**
- **Home, About, Contact** and custom pages are composed from the published revision.
- **The existing system pages** — loans, savings, shares, calculator, branches, events, blog, FAQs and content pages (`/pages/{slug}`) — keep their content and routes and are shown inside the published template's header, navigation and footer (`layouts.public` delegates to `site.shell`).
- **The contact form, legal pages and blog** keep their existing endpoints.
- **`SiteSetting`:** it stays the source for legacy consumers (contact-form recipient, structured data). It is synchronised from the published revision on every publish, and the old settings screen says so.

**Not carried over:** the previous homepage showed live aggregate figures (total savings balance, total loans disbursed, member count). The new `stats` component shows only figures the organization types itself. This change is deliberate and recorded in FEATURE_PRESERVATION_MATRIX §12.

## D-064 — Three platform templates, versioned and pinned
**Date:** 2026-10-20 · **Stage:** 7
**Decision:** `Publishing\Templates` defines three templates. Each has its own page shell (Blade), stylesheet, default header, footer and hero, fonts, and default home composition:

| Template | Header | Hero | Arrangement | Type |
|---|---|---|---|---|
| **Harbor** | horizontal | split text and picture | sections in white cards on a soft background | serif headings |
| **Savanna** | logo centred, menu below | full-width photo | alternating full-width colour bands, centred headings, zig-zag features, masonry gallery | rounded |
| **Summit** | vertical side navigation | oversized typographic | sticky "On this page" index beside numbered blocks | monospace accents |

Measured structural overlap of the rendered home pages (Jaccard similarity of element/class paths) is 0.02–0.07; the test requires below 0.5.

**Versioning:**
- A site document pins `{template, version}`.
- A released version is frozen. New versions are added (`config('website.template_versions')`); existing ones are never edited.
- The public site keeps rendering its pinned version until the organization moves its draft to a newer version and publishes (tested).

Organizations may mix any header and footer variant and choose from 8 approved fonts. There is no custom CSS.

## D-065 — A registry of safe components
**Date:** 2026-10-20 · **Stage:** 7
**Decision:** `Publishing\Components` holds 17 components:
- **Composed content:** hero, text, features, figures, call to action, picture, gallery, video, columns (container).
- **Live content:** products (savings, loans or shares), testimonials, FAQs, branches, team, latest news, upcoming events.
- **Contact:** contact details, contact form.

**Every property is typed:**
- text with a maximum length;
- rich text;
- enum;
- int with a range;
- media from the organization's own library;
- typed link;
- YouTube or Vimeo video ID;
- list with item schema and a maximum count.

**Live components** read only public columns of public records of the host organization: product names, rates and limits as on the existing product pages; branch contacts; published FAQs, testimonials, team, posts and events. **No component reads members, accounts, balances or transactions.**

## D-066 — Structured, versioned page data; never compiled
**Date:** 2026-10-20 · **Stage:** 7
**Decision:** a site is a JSON document (`schema: 1`) validated by `Publishing\SiteDocument`. It is rendered only as data, through platform Blade views, with automatic escaping.

**Never accepted:**
- tenant Blade, PHP or JavaScript;
- raw HTML outside the rich-text component;
- custom CSS;
- SVG;
- arbitrary iframes.

**Rich text** is sanitised by the existing DOM allow-list sanitiser on save **and** on render.

**Links** are typed:
- `page` (must exist when publishing);
- `system` (allow-listed site sections);
- `url` (http/https only, no credentials, ≤ 500 characters);
- `email`;
- `phone`.

Social links must be on the network's own domain. Colours are `#rrggbb`; fonts come from the platform list. The only CSS values written into the page are those colours and the platform's font stacks, and characters are filtered again.

**Embeds:** only YouTube (through youtube-nocookie) and Vimeo, by ID, in sandboxed iframes. Composed pages carry a CSP allowing those two frame sources only; elsewhere `frame-src 'none'` stays.

**Limits:**
- 200 KB per document;
- 20 pages;
- 30 sections and 60 blocks per page;
- nesting depth 2 (columns cannot contain columns);
- 8 menu items with 8 children, two levels;
- lists up to 24 items.

**Strictness:** unknown keys and component types are errors. Draft mode accepts unfinished content; publish mode is strict (required fields, internal links, picture descriptions).

## D-067 — Draft, autosave, preview, publish, rollback
**Date:** 2026-10-20 · **Stage:** 7
**Decision:**
- **Draft:** one per organization (revision number 0, unique `draft_slot`). It is created from the published site or from a starter built from the existing content (site settings, hero, mission, story, contacts, social links, SEO).
- **Autosave:** debounced, with optimistic locking (`lock_version`). A stale save returns 409 and the editor is told to reload; another editor's work is never silently overwritten.
- **Preview:** authenticated (`edit-website` or `publish-website`), own organization only. Phone, tablet and desktop widths in the editor. `Cache-Control: no-store, private`, `X-Robots-Tag: noindex`, a visible "PREVIEW" bar, the contact form inert.
- **Publish:** explicit (`publish-website`) and strictly validated. It creates a new immutable revision (a database trigger refuses changes to published documents), marks the previous one superseded, moves the public pointer and the cache generation in one transaction, and is audited.
- **Rollback:** publishes an earlier revision's content again as a new revision (history is never rewritten), re-validated (for example, a picture since deleted is reported). "Edit from here" loads a revision into the draft without publishing.
- **Public traffic** sees only the published revision.

## D-068 — Tenant-aware page cache with correct invalidation
**Date:** 2026-10-20 · **Stage:** 7
**Decision:** `PageCache` caches rendered composed pages.

**The key covers:** organization, a per-organization generation, the published revision, locale and path.

**What is cached:** only anonymous GET requests without a query string or flashed session data. Previews are never cached.

**Invalidation:**
- publish and rollback bump the generation;
- so does saving or deleting any record a component shows (savings, loan and share products, branches, FAQs, testimonials, team, blog, events, organization branding, media), through model listeners scoped to that organization.

Another organization's cache is never touched (tested).

**Form tokens:** forms on cached pages (contact form, language switch) carry a placeholder replaced with the visitor's own CSRF token on every response; no page leaves a placeholder (tested).

## D-069 — Tenant media: re-encoded, owned, within quota
**Date:** 2026-10-20 · **Stage:** 7
**Decision:** library uploads accept JPG, PNG and WEBP only (existing MIME and size rules).

**Processing:**
- each upload is decoded with GD and **re-encoded**, which strips metadata and anything appended — a PHP payload after the PNG data is gone (tested);
- dimensions are capped;
- files are stored under `website/media/{organization}/` with a random 40-character name.

**Quota:** a per-organization limit (`WEBSITE_MEDIA_QUOTA_MB`, default 200 MB, and 500 files) is checked under an organization-row lock.

**Ownership:**
- a document may reference only pictures in its own organization's library;
- deleting a picture still used by the website draft or the published site is refused;
- a library picture is served only on its own organization's host.

That last check is defence in depth: web servers that serve `/storage` directly bypass it, and library paths are random.

## D-070 — Separate website permissions
**Date:** 2026-10-20 · **Stage:** 7
**Decision:** two new permissions, `edit-website` (draft, preview, media, website content screens) and `publish-website` (publish, rollback). Both are given to the admin role.
- An editor without financial permissions can build the site but cannot open loans or members (tested).
- An editor without `publish-website` cannot publish.
- The existing website content screens accept either `manage-organization-settings` or `edit-website`.

## D-071 — Member sign-in, activation and recovery branding
**Date:** 2026-10-20 · **Stage:** 7
**Decision:** the published document's `auth` section and palette apply to the authentication pages:
- **sign-in and registration:** welcome headline, message, picture, colours and heading font;
- **password recovery, reset and e-mail/SMS activation:** picture and colours, with their security wording kept.

Nothing changes before the first publish, and other organizations' pages are unaffected (tested).

## D-072 — Existing tests changed in Stage 7
**Date:** 2026-10-20 · **Stage:** 7
**Decision:** none. All existing tests pass unchanged; see TEST_BASELINE Stage 7.

## D-073 — Seeders: demo data only outside production; no invented people, quotes or contacts
**Date:** 2026-10-21 · **Stage:** 8
**Finding:** `db:seed` created `admin@example.com` / `superadmin@example.com` with the password "password" in any environment. `PublicSiteContentSeeder` copied invented team members, invented member testimonials ("Member since 2016 …"), an invented founding story and the platform operator's own contact details into **every** organization; `BranchSeeder` copied branches with the operator's phone numbers. Shown on a public site (and by the Stage 7 team and testimonial components) they would be presented as genuine.
**Decision:**
- `DatabaseSeeder::demoDataAllowed()` — demo accounts and sample content only in `local`/`testing`/`development`, or with `SEED_DEMO_DATA=true` set on purpose. A production `db:seed` installs reference data only (roles and permissions, currencies, geography, interest-rate types, periods) and prints how to create the first platform administrator (`kopeza:super-admin`).
- `PublicSiteContentSeeder` now only applies the neutral `WebsiteDefaults` (headline, mission line, legal pages). No team, testimonials, story or contact details are invented.
- `BranchSeeder` (demo only) uses an `example.test` address and no phone number.
**Tests changed (not weakened):** `Branding/KopezaBrandingTest` "seeds the public story with the organization name" asserted the invented story; it is replaced by a stricter test that the seeder writes no story, contact details, team members or testimonials. `Branding/ImageUploadTest` "team photos" relied on the seeded team; the test now creates the organization's own three team members in its set-up and keeps every assertion.

## D-074 — Each organization runs on its own clock
**Date:** 2026-10-21 · **Stage:** 8
**Finding:** `config/app.php` fixed the application time zone to `Africa/Dar_es_Salaam` for everyone, and `organizations.timezone` — collected by the platform form, self-signup and the set-up wizard, and shown as a set-up criterion — was never applied. Every SACCO's "today", due dates, overdue days, posting dates, maturity dates, reminder hours and displayed times were East-African time.
**Decision:** `Tenancy\Kernel\OrganizationClock`.
- Entering an organization's context (`TenantContext::enter/restore`, i.e. every request on its host, every queued job, every per-organization sweep) sets PHP's default time zone **and** the database session's `time_zone` to the organization's zone; leaving restores the application zone (`APP_TIMEZONE`, default **UTC**).
- Stored instants stay exact: timestamp columns are MariaDB TIMESTAMPs, stored in UTC and converted with the session zone, which always changes together with PHP's. Date columns are the organization's calendar dates; the few `dateTime` columns hold local wall-clock times of the organization's own events and are only read inside it. Tested by writing an expiry in one organization's clock and reading it in another's and in the platform's.
- Named zones are used when the server has time-zone tables (`mariadb-tzinfo-to-sql`, recommended for zones with daylight saving); otherwise the zone's current offset. A zone the session cannot take (beyond +13:00 without tables) falls back to the application zone for both PHP and the database, with a log warning — PHP and the database never disagree.
- Daily per-organization work (repayment reminders, overdue recalculation, leave reminders and accrual, event reminders, maturity, HR daily, policy daily) is scheduled hourly with `--local-hour` (and `--local-day` for the monthly accrual): each organization is processed when **its own** clock shows the hour. Recurring journals run hourly and post on each organization's local due date.
- Defaults that named Dar es Salaam (platform organization form, branding form, provisioning fallback) now use Platform → Settings "time zone suggested for new organizations".
**Fresh installs only (R2):** an upgraded installation whose rows were written in Dar es Salaam wall-clock time would need a one-off conversion; none is provided (no legacy data migration).

## D-075 — Currency precision and the organization's currency on screen
**Date:** 2026-10-21 · **Stage:** 8
**Finding:** "TSh"/"TZS" was hard-coded on the teller counter and receipt, the staff dashboard, the member pay-now panel, the member loan application (label and script), the board pack and the prudential return; payroll payments and the Flutterwave connection test assumed TZS when a currency had no code; every amount was shown and accepted with two decimals (UGX and RWF have none).
**Decision:**
- `currencies.decimals` (ISO 4217 minor units; back-filled for known codes; editable in Settings → Currencies, defaulting from the code).
- `Reference\Support\CurrencyFormat`: amount, number and rounding in a given currency (model, id or ISO code) or the organization's default currency; never a guessed currency.
- **Precision is enforced** where money enters: deposits, withdrawals (and charges), loan applications and loan repayments refuse an amount with more decimals than the currency has, with a readable message.
- The hard-coded "TSh"/"TZS" displays use the account's, loan's or organization's currency. Payroll payments with no currency code are refused before anything is sent; the Flutterwave test checks the method's own currency market and never assumes Tanzania.
- Main member- and teller-facing screens (member portal, savings, withdrawals, loans, shares, members, counter, groups, restructures, recoveries, dashboard, workspace) format money amounts with the currency's precision. **Not converted:** about 300 other `number_format(…, 2)` calls in accounting, HR, payroll, governance and report screens still show two decimals (UGX shows ".00"); input precision is enforced regardless.
**Tests changed (not weakened):** four assertions expected the hard-coded "TSh " in front of an amount (`Usability/ArrearsConsistencyTest` ×2, `BoardWorkTest`, `StaffUsabilityTest`); the fixture account's currency is "TZS", which is what is now shown. The amounts asserted are unchanged.

## D-076 — Platform → Settings: business settings separated from deployment configuration
**Date:** 2026-10-21 · **Stage:** 8
**Finding:** platform business values lived only in `.env`/config: support-access duration, custom-domain policy (number per organization, verification window, retention, attempts, certificate warning), website media allowance, and whether self-service sign-up is open (only through `BILLING_MODE`). There was no place for the platform's display name and support contacts; the platform sign-in page linked to a member registration that answers 404 there and to a "Contact support" link with `href="#"`.
**Decision:** `Tenancy\Support\PlatformSettings` (table `platform_settings`) with a Super-Admin-only screen (`platform.settings.*`). Values are validated (types, ranges, IANA time zones, e-mail/https URL), stored only when changed, and every change is written to the audit trail as a platform-level row (no organization; old and new values). Defaults are the existing configuration values, read live, so an installation that never opens the screen behaves as before.
- **Business (screen):** platform name and legal name, support e-mail/phone/web page, accept new sign-ups, time zone and language suggested for new organizations, custom-domain policy, support-session length, website picture allowance (never above the plan's storage allowance).
- **Deployment (never in the application, shown only as configured / not configured):** encryption key, database and mail credentials, mail transport, payment-provider keys, custom-domain edge, billing mode, PDF engine, queue connection. A production server in billing DEMO mode is flagged.
- Sign-up refuses with "New sign-ups are closed" when closed (service and pricing availability); the platform sign-in page offers "See plans and sign up" only while sign-ups are open and links support only when a support contact is set.
- `kopeza:super-admin` stays the only way to grant Super Admin (bootstrap; a compromised Super Admin account cannot mint others). `media:oversized-report` stays an operator command (it scans every organization's legacy files; new uploads are re-encoded since Stage 7).

## D-077 — Country-specific starter content follows where the organization operates
**Date:** 2026-10-21 · **Stage:** 8
**Finding:** every organization was given a "Tanzania Mainland (template)" holiday calendar as its default (driving leave-day counts), Tanzanian leave templates and PAYE/NSSF/PSSSF/WCF/SDL/HESLB payroll templates; members could only choose Tanzanian mobile-money providers (anything else was refused); pension schemes defaulted to NSSF/PSSSF and employee social-security schemes accepted only NSSF/PSSSF; Kiswahili was switched on everywhere; a new bank defaulted to country TZ ("Bank of Tanzania sort code"); bulk import matched cities against Tanzania when no country was set.
**Decision:** `Regulatory\Support\OrganizationCountries` — the countries an organization operates in, from the platform's determination (real jurisdictions only; X-coded examples never count), its operating countries and its default country. Used only for **starter content and option lists, never for deciding which law applies** (that remains the Stage 4 determination).
- Tanzanian calendar, leave and statutory payroll templates only for organizations in Tanzania; others get a "Standard calendar" without holidays and add their own rules (the payroll screen says so; nothing is deducted until a rule is approved).
- Mobile-money providers are an organization catalogue (Settings → Member profile), Tanzanian list by default only in Tanzania; an organization without a list lets members type the provider's name. Pension schemes default to neutral names outside Tanzania; employee schemes come from the organization's own statutory rules (plus NSSF/PSSSF in Tanzania).
- Kiswahili is installed everywhere but switched on only where it is spoken (TZ, KE, UG, RW, BI, CD) or chosen as the default.
- Bank country defaults to the organization's default country, else empty (column no longer defaults to TZ); "domestic sort code (central bank)". Import matches cities only in the organization's default country.

## D-078 — Regulatory wording follows the determination, never a built-in regulator
**Date:** 2026-10-21 · **Stage:** 8
**Finding:** screens and texts named the Bank of Tanzania or its 2019 regulations for every organization: the Policy Administration dashboard ("for Tanzania Category B SACCOS …"), the candidates' fit-and-proper declaration ("I consent to vetting by the Bank of Tanzania"), board-pack headings ("BoT checks", "BoT minimums"), role-template and approval-workflow introductions, help texts citing "BoT Regulation 33/34/41/79", status hints, policy reminder e-mails, prudential-return labels, removal-authority defaults and the restructure-limit message.
**Decision:** `RegulatoryText::authorityName()` / `supervisingAuthorities()` (from the platform's determination) and the existing `@regref` rewriting are used everywhere: with an applicable pack the pack's own citations and title; without one neutral wording ("the organization's policy", "your supervising authority"). Approval workflows installed for an organization without a pack carry no regulation reference in their names; removal authorities default to the determined authority and delegated supervisor (else neutral) until the organization saves its own list. The prudential-return page no longer lists Tanzanian regulation numbers in its introduction; each limit shows its own source.
**Test changed:** `Usability/BoardWorkTest` expected the headings "BoT checks that are failing" and "… against BoT minimums"; they are now "Regulatory checks that are failing" and "… against the regulatory minimums" (the rule rows keep their citations, e.g. "Reg. 67", which the test still asserts).

## D-079 — Loan classification bands are the organization's setting
**Date:** 2026-10-21 · **Stage:** 8
**Finding:** the overdue-day bands (0–30 / 31–90 / 91–180 / 181–365 / over 365) were hard-coded from BoT Reg. 40(2) and applied to every organization, and status hints asserted the BoT provision percentages as facts — statute-derived numbers in code (contract rule 9).
**Decision:** `loan_restructure_settings.band_*_days` (Settings → Loan restructuring & classification; defaults 31/91/181/366, labelled as the common aging buckets; strictly increasing, validated). Classification, labels and hints follow each organization's bands and its own provision rates. Statutory minimum provisions continue to come only from a pack (`provisioning.min_pct.*`).

## D-080 — Sensitive configuration changes are audited
**Date:** 2026-10-21 · **Stage:** 8
**Finding:** validated but unaudited: roles (create/change/delete, staff), staff role assignments, admin accounts (the role grant), custom permissions, SMS gateways, the AI key, currencies, AML thresholds, approval-workflow definitions, loan products, savings products, organization profile/branding (incl. time zone), website site settings, platform administrators (application log only).
**Decision:** the models `LoanProduct`, `AccountType`, `SmsGatewaySetting`, `AiSetting`, `ComplianceThreshold`, `ApprovalWorkflow`, `SiteSetting` use the `Auditable` trait (create/update/delete with before → after; secrets redacted by the existing redactor). Explicit audit records for role, staff-role, admin-role, custom-permission, currency, workflow-definition and organization-profile changes; platform administrator changes are platform-level audit rows. The admin role grant now happens in the same transaction as the account. Member access settings refuse an unknown invitation channel (it was silently turned into e-mail) and SMS invitations without an active SMS gateway.

## D-081 — Navigation shows only what the person may open; warnings and errors always reach the page
**Date:** 2026-10-21 · **Stage:** 8
**Finding (role crawl):** following every link each role is shown, 56 distinct links answered 403 for the role that saw them (accounting set-up steps, member and loan action links, share tabs, dashboard exports and approval queues for Board members, HR queues, report exports, AI settings link, remediation links). The audit-log export answered 500 ("Array to string conversion"); the regulatory pack "Compare with the previous version" link answered 404 on a first version. The admin, member and platform layouts never displayed `warning` or `error` flashes sent by 10 controllers and 2 middlewares.
**Decision:** links use `@canroute`/`@canpost`/`RouteAccess` (a shared `partials.allowed-links`; HR dashboard queues filtered in the controller); the export renders nested change values; compare is offered only when a previous version exists; all layouts show warning and error flashes. `tests/Feature/Completeness/RoleCrawlTest.php` keeps it that way: 28 role crawls (SACCO administrator, Staff, every role template, member, visitor, platform and regulatory administrators) must meet no server error, no dead link and no forbidden link.

## D-082 — Readable failures instead of server errors or false success
**Date:** 2026-10-21 · **Stage:** 8
**Decision:**
- PDF exports need headless Chrome (an external dependency of the server). When it is missing or fails, the person sees a 503 page saying PDF documents cannot be produced right now and to use the Excel/CSV export; the technical error is logged. (With Chrome configured, all 74 PDF exports reached by the crawl rendered.)
- "E-mail this report": a mail failure is a form error, not a 500; with a log/array mail transport the page says the report was **not** sent instead of "Report emailed"; on success it says the report was handed to the mail service (delivery is not confirmed by the application).
- Starter website content no longer contains writing prompts ("Describe your mission.") or an invented "Since <year>" figure: it uses a true neutral sentence and real public counts (branches, savings and loan products), and publishing refuses any remaining starter prompt.

## D-083 — Fix: a loan secured only by liened savings could be approved but never paid out
**Date:** 2026-10-21 · **Stage:** 8
**Found by:** the end-to-end workflow for the Tanzanian SACCO.
**Cause:** the security assessment counted the borrower's available savings as the lien at approval, but at payout it counted only an existing hold — and the hold is placed after the payout check (`activatePledges`), in the same transaction. A loan whose only security was the lien passed approval and was then refused at payout ("no counted security").
**Decision:** at payout and disbursement the balance that will be liened counts, as at approval (the lien is placed under the same loan lock immediately after the check).

## D-084 — Kept as they are (recorded, not changed)
**Date:** 2026-10-21 · **Stage:** 8
- **Group withdrawals** are recorded and debited at once by staff with the permission (baseline behaviour, liquidity-checked and posted). `GroupWithdrawalService::approve/reject` exist but no route has ever reached them (no pending group withdrawal can be created). Adding a maker–checker step for group withdrawals is a product decision, not a regression fix.
- **Phone-number matching** uses the last nine digits (fits East-African numbering; may mis-match longer national numbers within one organization).
- The **HESLB** employee fields stay as optional fields; the import template's example row stays Tanzanian (it is an example).
- **Statutory regime** column of restructure settings keeps its stored value; applicability is decided by the determination (Stage 4).

## D-085 — Existing tests changed in Stage 8
**Date:** 2026-10-21 · **Stage:** 8
Every change keeps or tightens what is asserted:
- `Branding/KopezaBrandingTest`: the seeded-story test is replaced by "seeds only neutral website defaults, never invented people, quotes or contact details" (D-073).
- `Branding/ImageUploadTest` ("team photos"): the organization's own team is created in the set-up instead of relying on invented seeded people (D-073).
- `Usability/ArrearsConsistencyTest`, `BoardWorkTest`, `StaffUsabilityTest`: "TSh " → "TZS " before the same amounts (D-075); `BoardWorkTest` board-pack headings (D-078).

## D-086 — Workload model and how Stage 9 measured
**Date:** 2026-10-21 · **Stage:** 9
**Decision:** a written, reproducible workload model (`tests/Performance/Support/WorkloadModel.php`) with an explicit REFERENCE platform (assumption: 60 SACCOs — 1 × 20 000, 4 × 4 000, 55 × 400 members; peak: 60 staff and 400 members of the large SACCO at once, month-end payroll deposits) and a smaller MEASURED dataset built on the test machine by the application's own services with the clock moved to each business date (member import, account opening, monthly deposits, withdrawals, loans applied → approved → paid out → repaid monthly, monthly verified prudential returns). Nothing is extrapolated from the measured dataset to the reference platform.
**Method:** baseline = Stage 8 code (`71243b8`) in a separate worktree; after = Stage 9; the same dataset dump restored before every run; PHP-FPM + nginx (TLS) in production mode with cached config, MariaDB 10.11 with a 2 GB buffer pool, `innodb_flush_log_at_trx_commit=1`; client-side latency from a Python driver of signed-in virtual users; server-side samples of queue age, row-lock waits, deadlocks and PHP-FPM memory; in-process query profiles of every staff screen and of the money write paths.
**Limits (stated with every number):** one 2-vCPU / 7 GB VM runs the database, PHP-FPM, nginx, queue workers and the load driver together; synthetic data; mail to a local SMTP sink with a fixed delay; no payment provider, SMS gateway, CDN, WAF or second server.

## D-087 — Proposed service targets (set before optimizing)
**Date:** 2026-10-21 · **Stage:** 9
For the large SACCO at its peak, on production hardware sized by the operator (TEST_BASELINE Stage 9 lists them with the measured values):
- staff and member screens: p95 ≤ 800 ms, p99 ≤ 1 500 ms; money operations (deposit, withdrawal, repayment, payout): p95 ≤ 1 000 ms, no error other than a validation refusal, no deadlock;
- interactive reports (trial balance, balance sheet, portfolio, PAR) for one organization: p95 ≤ 3 s; longer work runs in the background (imports, e-mailed reports, campaigns);
- public pages: p95 ≤ 300 ms;
- queues: `critical` oldest wait ≤ 30 s, `notifications` ≤ 2 min at peak; a bulk campaign never delays another organization's notices by more than its pacing share;
- errors: < 0.1 % of requests (excluding validation);
- recovery: RPO ≤ 24 h (≤ 15 min with binary-log shipping), one organization restored into an isolated copy ≤ 1 h.
They are proposals for the business to confirm; they are not an SLA.

## D-088 — Daily ledger totals
**Date:** 2026-10-21 · **Stage:** 9
**Finding (measured):** the liquidity check of every withdrawal and payout summed all posted lines of the cash accounts since the first day; the trial balance, balance sheet and income statement summed all posted lines of the organization — work growing with the age of the ledger.
**Decision:** `ledger_daily_totals` (organization, account, day, closing flag → debit, credit, line count), written by `LedgerTotals::add` in the same transaction as the lines, at the only two places lines become posted (JournalService::writeLines for journals created posted, JournalService::post for drafts). Used by the liquidity check and by the unfiltered statements and account balances; filtered reports (branch, cost centre, transaction currency) still read the lines. Back-filled by migration. `accounting:verify-totals` (nightly, and in the restore drill) recomputes them from the lines; `--repair` rebuilds. Postings of one organization are already serialized by the journal-number row lock and rows are upserted in account order, so no new lock order is introduced (concurrency suite).

## D-089 — Per-request memos; nothing outlives a queued job
**Date:** 2026-10-21 · **Stage:** 9
**Finding:** a deposit read the organization's accounting settings 11 times, its account mappings 4 times and its period 3 times (the mapping service, built anew for every posting, lost its memo); some settings were memoized in static arrays, which in a long-lived queue worker kept serving a value changed elsewhere until the worker restarted.
**Decision:** request/job-scoped memos (`ScopedMemo`, scoped container bindings that Laravel discards for every request and before every job) for accounting settings, accounting periods, the regulatory profile, treasury/governance settings, route-access decisions and heartbeats; the mapping service is request-scoped and loads all of an organization's mappings once. Memos are cleared when the model is saved; callers get their own instance built from the memoized row. Test: a worker processing several jobs sees a setting changed between them, each job in its own organization and clock.

## D-090 — Queue lanes, timeouts below retry_after, bounded retries, fair bulk work
**Date:** 2026-10-21 · **Stage:** 9
**Finding:** every job used one queue; the arrears refresh (timeout 1 800 s) ran on a connection whose retry_after was 90 s (a second worker would pick it up while it still ran); several jobs had no timeout; a campaign was one job for all recipients and a retry re-sent the whole list (and re-charged the SMS allowance).
**Measured (month-end scenario, TEST_BASELINE 9.5):** on Stage 8 two campaign jobs (4 000 and 1 000 recipients) were killed by the 90 s worker timeout after 1 800 messages, taking both workers down; under a supervisor every retry would resend from the first recipient. On Stage 9 the same campaigns sent 5 000 of 5 000 messages, once each, while the tellers' p95 stayed at 1.17 s.
**Decision:** lanes `critical`, `default`, `notifications`, `billing` (connection `database`, retry_after 120 s) and `bulk`, `reports`, `imports` (connection `database-long`, retry_after 3 900 s); every job declares its lane, a timeout below its lane's retry_after and bounded retries (architecture-style test). Campaigns send 100 recipients per job with a cursor saved per recipient and queue the next chunk behind other organizations' work; per-organization pacing (`TenantPace`, shared cache) caps bulk messages per minute. Failed jobs are visible, retryable and deletable (audited) on Platform → Operations.

## D-091 — Long work leaves the request
**Date:** 2026-10-21 · **Stage:** 9
**Decision:** confirmed go-live imports run on the `imports` lane with progress on the batch row (they ran up to 600 s inside the request, beyond the edge timeout, and a retried request could import twice; the upload token is now spent on confirmation); "E-mail this report" builds and mails on the `reports` lane (outcome on `report_exports`); go-live exports stream in chunks instead of building the whole file in memory; public-site figures are cached per organization for 10 minutes (anonymous traffic scanned the whole organization on every hit).
**Kept synchronous (measured, D-086 limits):** direct Excel/PDF downloads of the reports, which completed within the targets for the measured large tenant; website picture processing at upload (Stage 7, bounded by the upload size).

## D-092 — Fix: cross-tenant deadlocks on money paths
**Date:** 2026-10-21 · **Stage:** 9
**Found by:** the synthetic workload (two SACCOs paying out loans at the same moment), reproduced by `tests/Concurrency/ParallelCrossTenantPayoutsTest` (fails 3/3 on Stage 8 with error 1213, passes 3/3 after).
**Causes:** (1) payout activated reserved pledges with a locking UPDATE that matched no row, taking a gap lock at the end of the pledge index, then inserted the lien pledge — two organizations' payouts each held the gap and waited for the other's; (2) the first payout of an organization locked its missing treasury row with SELECT … FOR UPDATE (gap lock) and then inserted it.
**Decision:** (1) a plain read of this loan's reserved pledges (the loan row is already locked), then an update by primary key only when there are any; (2) one upsert that takes the treasury row's exclusive lock whether it exists or not (no shared-lock upgrade, which deadlocked two payouts of one organization in Stage 3).

## D-093 — Observability
**Date:** 2026-10-21 · **Stage:** 9
**Decision:** a correlation id per request (the existing error-page reference, returned as `X-Request-Id`; an upstream id kept only if it is a plain token) carried into queued jobs with the organization and user (Laravel Context); `LOG_FORMAT=json` structured lines with correlation fields lifted, after redaction; an access log (route name, status, duration, queries, database time, memory, organization, user — never URLs, bodies or personal data); slow-request and slow-query warnings; `/health/live` and `/health/ready` (critical checks → 503; queue delay, failed jobs, scheduler and backups → degraded) with details only for a token or allowed addresses; a scheduler heartbeat; Platform → Operations (readiness, production checklist, queues per lane and per organization, failed jobs with retry/delete, backups and drills); `ops:check`.

## D-094 — Backups, tenant export/import, restore drill
**Date:** 2026-10-21 · **Stage:** 9
**Decision:** encrypted backups of the database (`--single-transaction`, binary-log position recorded when logging is on) and stored files with their own key (libsodium secretstream; plaintext never on disk; credentials through a 0600 option file), read back after writing, retention daily/weekly/monthly; restores only into a separate database or an empty directory; one organization exported (schema-driven: rows with its organization_id, children through foreign keys, user role/notification rows, referenced platform rows with platform users' credentials removed, referenced files) and imported into an isolated database keeping every id — the import refuses and rolls back completely if any row already exists, never overwriting another organization; `backup:drill` measures and verifies the whole path. Not in any backup by design: APP_KEY, the backup key, the environment.

## D-095 — No persistent web workers
**Date:** 2026-10-21 · **Stage:** 9
**Decision:** PHP-FPM remains the web runtime. Octane/RoadRunner/FrankenPHP worker mode is not adopted in this stage.
**Evidence both ways:** the final CPU profile shows a per-request framework cost a persistent worker would remove (booting Eloquent model classes ≈ 13 % of sampled web CPU), so there is a potential gain. But tenant-context cleanup was validated only for queue workers (scoped memos, context restore, organization clock — QueueOperationsTest), not for a web process that serves many organizations' requests in a row; static state in the application and its packages (e.g. Spatie's registrar, regulatory text memo keyed by generation) would need the same audit and tests. The brief forbids adding such infrastructure without that validation. Revisit with a dedicated isolation test suite.

## D-096 — Withdrawal liquidity holds are closed when their journal posts
**Date:** 2026-10-21 · **Stage:** 9
**Finding (measured):** a withdrawal on the large synthetic tenant took 419 ms, 334 ms of it summing the cash ledger and 55 ms in a NOT EXISTS over 12 073 withdrawal holds that were never closed (excluded from the figures only by checking for their posted journal).
**Decision:** `LiquidityService::consumeIfPosted()` closes a non-earmark hold once its journal is posted or reversed (after recording and after approving a withdrawal); the Stage 9 migration closes the existing ones under the same condition. A hold whose posting failed stays active and keeps counting. Tests: `LedgerTotalsTest` (hold consumed, pending figure unchanged; unposted hold stays active).

## D-097 — Permission checks: same answers, per-request cost
**Date:** 2026-10-21 · **Stage:** 9
**Finding (measured, CPU profile of the web tier):** about 38 % of web CPU went to permission checks — Spatie loaded and hydrated every organization's roles and permissions from the cache on every request and scanned the permission list for each check (several hundred per staff page); role facts (super admin, administrator, read-only) and route-to-permission patterns were recomputed per check.
**Decision:** (1) `IndexedPermissionRegistrar` — Spatie's registrar with a name|guard index (same collection, same results); (2) `PermissionSet` — a user's (or the Member role's) permission names from one indexed query, kept for the request/job; used by Gate::before and the member-portal check, only while teams and wildcard permissions are off; (3) role facts and Gate::before decisions memoized per request; (4) route-pattern matching compares exact names and trailing-wildcard prefixes directly (checked equal to `Str::is` for all 504 patterns × 1 249 route names). All memos are cleared on every Spatie cache reset and on every change of a user's roles or direct permissions (Spatie signals the latter through `forgetWildcardPermissionIndex`). Tests: `PermissionChecksTest` (every permission × every kind of user equals Spatie; a grant/revoke/role assignment in the same request is seen at once; member portal equals the role). The test caught that an earlier Stage 9 memo missed direct grants — fixed before measuring.

## D-098 — Trusted proxies read through config
**Date:** 2026-10-21 · **Stage:** 9
**Finding:** `TRUSTED_PROXIES` was read with env() in bootstrap code, which returns nothing once `config:cache` is used in production — every client then appeared as the proxy's address (one login throttle for everybody, wrong audit IPs).
**Decision:** `config/trustedproxy.php`; `'*'` is accepted only explicitly and flagged by the production checklist.

## D-099 — Caches with tenant-safe keys and invalidation
**Date:** 2026-10-21 · **Stage:** 9
**Decision:** public-site figures cached per organization for 10 minutes (key contains the organization id; figures are aggregates already public on the site); push settings now cache "no settings row" (a null was never cached, so every page re-queried and re-wrote the cache). Published pages already had a per-organization, per-revision page cache (Stage 7). Reference data (permissions, regulatory snapshots, translations) keep their existing versioned keys. No cache entry is shared between organizations except platform-wide reference data.

## D-100 — Indexes from measured plans
**Date:** 2026-10-21 · **Stage:** 9
**Decision:** six composite indexes, each for a query measured slow on the large synthetic tenant (TEST_BASELINE Stage 9 lists the query, the plan before and after): savings activity by organization and date (and status+date with amount covering), withdrawals by organization and date, journals by organization/date/id (journal list ordering), audit log by organization and action (policy history), journal lines by organization and currency (FX revaluation). No index was added without a measured query.

## D-101 — Restore drill findings fixed
**Date:** 2026-10-21 · **Stage:** 9
**Found by** `backup:drill` on the 714 MB synthetic dataset (the Operations tests used a small fixture): (1) the database restore connected with the read-only backup account; (2) the tenant-archive reader cut its buffer after every line, copying the remainder each time (quadratic: an 18-minute run had not finished importing 738 429 rows); (3) database-generated columns (`languages.default_for_organization_id`, `security_pledges.active_fingerprint`) were inserted and refused.
**Decision:** restores use `BACKUP_RESTORE_DB_USERNAME` (create/write on restore databases only) or the application's connection, and report the client's own error; the reader walks the buffer with an offset; generated columns are left to the database. The Operations suite now includes a generated column. Drill after the fixes: 129.6 s end to end, all checks passed (TEST_BASELINE 9.7).

## D-102 — Tests changed in Stage 9
**Date:** 2026-10-21 · **Stage:** 9
- `Usability/MemberSignInTest`: `Queue::fake()` also faked the import job once imports became queued (D-091); it now fakes only `InviteMembers`, and every assertion (rows imported, invitations queued or not) is unchanged.
- `Completeness/ConfigurationAndJurisdictionTest` (organization clocks) and `Completeness/ThreeSaccoWorkflowsTest`: both used a fixed fake clock of 20 Oct 2026 21:30 UTC while the database's own clock (`NOW()`, column defaults) keeps real time; they failed on the untouched Stage 8 code too as soon as the real date passed (verified in the Stage 8 worktree). The first now compares the database date with the real date in each zone; the second uses the next 21:30 UTC at or after the real time, derives the expected local dates and financial year from it, and asserts that the two clocks really differ. No assertion was removed.
- `Operations/BackupAndTenantRestoreTest` arranges a row with a generated column (D-101).
- No test was weakened; no exception was suppressed.

## D-103 — Release audit: method
**Date:** 2026-10-21 · **Stage:** final release audit
**Decision:** the audit installed the release from the Stage 9 bundle into a new directory and a new, empty MariaDB database with the documented least-privilege accounts, `composer install --no-dev` from the lockfile, a production `.env`, real HTTPS (nginx with a locally issued CA, `kopeza.test` / `*.kopeza.test`), queue workers per lane, a cron scheduler, a mail capture and a local Flutterwave-v3-compatible payment simulator (hosted page, verification, tokenized charges, `verif-hash` webhooks). The customer journey was then driven in Chromium as each role. Every defect found was fixed in the source repository with a regression test (D-113 excepted, see there), committed, and deployed to that installation as an operator would (pull, caches, PHP-FPM reload, `queue:restart`). The simulator is **not** a provider certification and is never described as a live integration.

## D-104 — No default platform password; demo data never in production
**Date:** 2026-10-21 · **Stage:** release audit · **Commit:** `88be172`
**Finding:** `kopeza:super-admin --create` defaulted `--password` to `password`; `AdminSeeder` and `PlatformSuperAdminSeeder` could create known demo accounts on a production database when called directly.
**Decision:** interactive runs ask twice (hidden, ≥ 12 characters); without a terminal a 24-character password is generated and shown once; an existing account keeps its password. Both demo seeders throw unless `DatabaseSeeder::demoDataAllowed()`. `.env.example` lists every key the code reads; `docs/operations/installation.md` written.

## D-105 — Scheduled commands run as the system
**Date:** 2026-10-21 · **Stage:** release audit · **Commit:** `42a9e3b`
**Finding (fresh installation, scheduler log):** `elections:process`, recurring journals (`RecurringJournalService::runDue`) and `reports:prune-exports` read tenant tables with no tenant context; the fail-closed scope (Stage 2) refused them, so they had silently never run on a production-style install. Tests had always run them with an organization bound.
**Decision:** discovery wrapped in `Tenancy::runAsSystem(<reason>, …)`; per-organization work keeps its own context. `ReleaseAudit/ScheduledCommandsTest` runs every scheduled command with no tenant context. The platform root (no organization) redirects to the pricing page instead of a 404.

## D-106 — Values typed on screens and dropped by validation
**Date:** 2026-10-21 · **Stage:** release audit · **Commits:** `fbcbcc0`, `7e9977c`
**Finding:** (1) plan limits and overage policies were not in `PlanController::saveDraft` rules, so `validate()` dropped them and every published plan was unlimited (seen when publishing "growth" v1); (2) the HR employment-change screen dropped every proposed target (position, grade, unit, department …); (3) printed regulatory documents ignored the legal name and addresses captured in Organization set-up.
**Decision:** the missing rules added (limits as nullable short strings, overage `block|allow_and_record`; HR targets nullable integers, still ownership-checked by the service); `OrganizationIdentity::for()` falls back to the set-up values. Tests: `CatalogPricingAccessTest`, `HrScreensTest`, `PackageActivationTest`.

## D-107 — Set-up checklist and assets
**Date:** 2026-10-21 · **Stage:** release audit · **Commits:** `85b5376`, `fa5311d`
**Finding:** the People step counted only administrators as staff (employees never counted); the Website step read only the pre-Stage-7 settings, so a SACCO with a published builder site could not finish set-up; every page requested a missing `Jost-Light.woff2` (404).
**Decision:** active `is_admin` or `type = employee` users count (≥ 2); the Website step also accepts `Website\Support\PublishedSiteFacts` (look, home headline, contacts of the published revision; public class in the module manifest); weight 300 maps to the shipped regular face.

## D-108 — Production reference seed and notices
**Date:** 2026-10-21 · **Stage:** release audit · **Commit:** `b9fe83c`
**Finding:** a production `migrate --seed` installed no notification types or default templates, so no deposit, withdrawal or loan notice was ever sent ("unknown notification type deposit_success" in the log).
**Decision:** `MessageTemplateSeeder` and `NotificationSettingSeeder` (idempotent, no demo content) are part of the production reference seed. Upgraded installations: run `php artisan db:seed --force` once. After the fix the fresh installation sent deposit, withdrawal, loan-received, loan-approved, funds-sent and repayment notices.

## D-109 — Administrators receive their verification link
**Date:** 2026-10-21 · **Stage:** release audit · **Commit:** `0b1c8ff`
**Finding:** an administrator created under Access Control → Admins is subject to the `verified` middleware but no link was sent; the verification page claimed one had been.
**Decision:** the link is sent on creation through `VerificationEmailDelivery` (a mail outage is logged and audited and never breaks the request); the success message says whether it was sent.

## D-110 — Approvals queue: every reason, and 404 for foreign steps
**Date:** 2026-10-21 · **Stage:** release audit · **Commits:** `007d1b4`, `6dde231`
**Finding:** (1) a refused Credit Committee decision showed only "This loan cannot proceed to approval yet:" — the reasons (no counted security; no verified prudential return) were hidden; (2) the cross-tenant route sweep found that posting to another organization's approval step returned 500 (the step has no organization column; its tenant-scoped parent resolved to null). Nothing was changed by the request.
**Decision:** the page lists all messages; the step's parent is checked null-safely and a foreign step is a 404. `ReleaseAudit/ApprovalsPageTest` (fails on the previous code).

## D-111 — Subscription standing is visible in the back office
**Date:** 2026-10-21 · **Stage:** release audit · **Commit:** `c07f75a`
**Finding:** after a failed renewal, administrators were told only by e-mail; past due and grace looked normal until the system became read-only. On a new installation with a running scheduler the dashboard also said "The daily jobs have never run … add the cron entry" until the first 01:00 run.
**Decision:** a banner on every back-office page for administrators while past due, in grace (with the end date) or restricted/cancelled/expired, linking to Settings → Subscription; members never see it. The scheduler notice treats a recent scheduler heartbeat as "first daily update pending"; a silent scheduler is still reported.

## D-112 — Renewal payments return to the platform page
**Date:** 2026-10-21 · **Stage:** release audit · **Commit:** `5f119fd`
**Finding:** a SACCO paying an unpaid renewal from its own host was returned by the provider to `https://<tenant>/billing/checkout/…/return`, a platform-only route: "Page not found" immediately after paying (service was restored correctly by the webhook).
**Decision:** `Billing\Support\PlatformUrl` builds the return URL, the demo checkout pages and the sign-up verification link on `APP_URL`; the return page of a renewal or recovery links back to the SACCO's own Settings → Subscription instead of the sign-up page.

## D-113 — Restore commands under a cached configuration
**Date:** 2026-10-21 · **Stage:** release audit · **Commit:** `6818c22`
**Finding:** the documented `DB_USERNAME=kopeza_restore php artisan backup:drill` is ignored once `config:cache` has run (production), so the drill connected as the least-privilege application account and failed on `CREATE DATABASE`. D-101 had moved only the SQL client to the restore account. This is R-64 ("restore grants not exercised").
**Decision:** scratch-database creation, the restored and isolated connections, and `tenant:import`'s database creation use `BACKUP_RESTORE_DB_*` from the (cached) configuration; the application account still reads the live database. deployment.md corrected. Exercised on the fresh installation with exactly the documented grants: backup with the backup account, drill passed (25.2 s single-SACCO restore). No automated test: the Operations suite connects with a privileged test account, so it cannot show the difference.

## D-114 — Payment validation fails closed (R-35)
**Date:** 2026-10-21 · **Stage:** release audit · **Commit:** `1bf30b8`
**Decision:** outside demo mode a provider transaction is applied only if it reports the configured receiving account and a customer e-mail matching the invoice's customer; omission is now a rejection (billing exception for review), not a skipped check. `ops:check` fails when test or live billing has no provider account id. Tests: two new datasets in `SignupCheckoutWebhookTest`, `OperationsScreenTest`. Verified on the fresh installation: initial checkout, merchant-initiated renewal and recovery payment all applied.

## D-115 — Public site and wording
**Date:** 2026-10-21 · **Stage:** release audit · **Commits:** `ea85ab8`, `3ec3ba4`
**Decision:** (1) the live site leaves out list blocks with nothing to list (testimonials, FAQs, branches, team, news, products) instead of showing editor placeholders such as "Member stories will appear here." to the public; the builder preview still shows them. Rendered pages are cached for up to 30 minutes, so a release that changes rendering reaches already-cached pages within that time (or at the next publish). (2) The stored legacy status `successfull` (reconciliation and close queries depend on it) is shown as "Successful". (3) The settings directory entry labelled "Security policy — passwords, sessions and two-step sign-in" opened the loan security policy; it is now named so.

## D-116 — Development dependencies
**Date:** 2026-10-21 · **Stage:** release audit · **Commit:** `96f7fc2`
**Decision:** `npm audit fix` for four advisories in development-only packages (vite/rolldown, concurrently/shell-quote, source-map-js); lockfile only, patch and minor versions, no production package changed. `npm audit` now reports 0. `composer audit` could not reach Packagist from this environment (HTTP 403) — PHP dependencies were **not** audited here.

## D-117 — Tests changed in the release audit
**Date:** 2026-10-21 · **Stage:** release audit
- `Access/PlatformAndOrganizationSettingsTest`: `--create` now answers the password prompts (`expectsQuestion`) because the command no longer has a default password; a new test refuses a short password and checks that no default is used.
- `Billing/SignupCheckoutWebhookTest`: two datasets added (receiving account or customer not reported).
- `Operations/OperationsScreenTest`: one test added (provider account id).
- `Security/HostResolutionAndMembershipTest`: asserted that the platform root is a 404 (written in Stage 2, before any platform page existed, R-08). D-105 deliberately sends it to the plans; the test now asserts the redirect, that the page shows no SACCO's content, and (new) that an unmapped host is still a 404.
- `Operations/QueueOperationsTest` (long-lived worker): the in-process `queue:work` stopped with exit code 12 (memory limit 128 MB) once, in a 4-process parallel run, because the "worker" is the whole test process; it passes alone. The test now gives the worker `--memory=2048`; every assertion about settings and tenant context is unchanged.
- New files under `tests/Feature/ReleaseAudit/` (one per defect above; `AssetsAndLabelsTest` covers the missing font and the settings label).
- No test was removed or weakened; no exception was suppressed.

## D-118 — rc3 meeting management lives in Governance (one engine, family defaults)

Meeting lifecycle, participants, badges and admission, attendance evidence, quorum, allowances, minutes versions and
resolution actions extend the Governance module (it already owned meetings and resolutions). No new module, no
per-family copy. Family differences are configuration defaults (`MeetingSettings::PROFILE_DEFAULTS`). VICOBA weekly
meetings stay in the Vicoba module untouched, with no link in either direction. Governance now declares `Profiles`
(read through `ProfileAssignment`). See docs/meetings/README.md.

## D-119 — Admission is online and server-validated; shared/exclusive lock on the meeting row

A scan takes a SHARED lock on the meeting row and accepts only while `scheduled|in_progress` and
`check-in ≤ now < effective end`, re-checking participant and badge under EXCLUSIVE locks (meeting → participant → badge).
End, cancel, extend and postpone take the meeting row EXCLUSIVELY. No offline acceptance and no scheduler dependency.
Instants carry microseconds so that "before the end" is decidable in the evidence. Proven by the forked scan/end race
test (0 admissions after the end).

## D-120 — Badge tokens: random 256-bit, hash for look-up, encrypted copy for reprint

The QR payload `KZB1:<base64url token>` is not a URL and holds no id. SHA-256 is stored for look-up, and an APP_KEY-encrypted
copy lets the same badge be re-rendered (printer jams) without reissuing. Reissue and revoke are immediate. The token
alone never admits anyone.

## D-121 — Allowance settlement is manual/cash/bank with evidence in rc3; journal on confirmation

Workforce's HR payment engine is not public and exists only with the HR extension, so allowances keep their own
payment attempts. These are database-guarded (one open attempt per entitlement, idempotency keys per tenant). The
journal is posted through `Ledger` in the confirmation transaction. "Unknown" keeps the attempt open, so it can never be
paid twice. Gateway disbursement (a `PayoutTracker` for allowances) is deferred and recorded as partial in the rc3
acceptance checklist.

## D-122 — Meeting services require an organization context (system context refused)

`MeetingAccess` fails closed both without context and in the platform's system context. Console commands, jobs and
tests reach meeting services through `Tenancy::run($org, …)`. The actor must hold an active membership of that
organization, not merely have it as their home organization.

## D-123 — Pre-existing defects fixed while establishing the baseline

Four duplicate global test helpers prevented the suite from loading; they were renamed in the later files only.
`ListExporter` shortened unlimited CLI/queue time limits to 300 s; it now uses `ExecutionTime::atLeast`.
`config/integrations.php` used null array keys, which PHP 8.5 deprecates; a `(string)` cast keeps the same keys. The
PHP requirement is ≥ 8.4.1, as the lockfile demands.

## Platform Admin redesign (Kopeza Super Admin Designs v1)

* PA-D01 One Platform Admin shell (`platform/layout`) with a role-aware sidebar (`PlatformNavigation`) and its own
  stylesheet `public/css/platform.css`, scoped under `body.pa`; organization screens keep `app.css` untouched.
* PA-D02 `/platform` is the Platform overview and the landing page of the Super Admin, platform staff and the regulatory
  administrator (`HomeRoute`); a remembered intended URL still wins. Its own shell (`platform.overview`) enters no tenant
  context; every section is authorized again from the person's platform permissions, preferences can only hide.
* PA-D03 Figures are computed live with stated periods and definitions (docs/platform-admin/REDESIGN.md §3); no uptime
  figure because none is measured; billing figures in one mode and one currency, never converted.
* PA-D04 Support conversations live in one place: the support workspace (`crm/cases`, deep link `crm/cases/{id}`).
  Added: per-person read markers, contact channel, escalation (priority raise, reasoned, supervisors), saved replies.
* PA-D05 Read-only roles may complete their OWN MFA enrolment, recovery codes, re-authentication, passkeys and overview
  layout (the mandatory MFA set-up was refused to a read-only auditor before).

## Loan penalty engine (docs/loan-penalties)

* LP-D01 Penalties are durable charges derived by a pure, deterministic replay (`Penalties\LoanReplay`) of the loan's
  agreed terms, standing receipts, approved waivers/reversals and the instant; persistence stores only the difference
  (charges unique per loan/instalment/key, append-only movements, superseded allocation rows, idempotent journals).
  Daily, catch-up, repeated and concurrent runs give identical results.
* LP-D02 Terms are a versioned product document approved by a second person and copied (hashed, immutable) onto each
  loan at application; active-loan amendments are blocked (restructure creates a new agreement).
* LP-D03 One method per policy; base = due instalments only (principal or principal + interest); no penalty on
  penalty; grace treatment must be chosen explicitly; caps apply per charge → instalment → loan and are never refilled
  by waivers or reversals; daily charges use cumulative rounding.
* LP-D04 Delinquency (days past due, classification, non-accrual) is measured from the contractual due date and
  cutoff; grace only delays penalties.
* LP-D05 One allocation engine for every receipt channel, in the agreed order; staff receipts above everything owed
  are refused; confirmed gateway/check-off excess is held as `unapplied` (overpayments liability).
* LP-D06 Cash basis by default (income on collection); accrual basis optional (receivable on assessment, cleared on
  collection, released on waiver/reversal, impairment on write-off); non-accrual loans are memo-only.
* LP-D07 No statutory penalty rate or cap is encoded (none found for SACCOS / Tier 2 in the sources reviewed);
  organisation ceilings + recorded review basis + maker–checker instead. See LEGAL-APPLICABILITY.md.
* LP-D08 Fixed alongside: DATE vs timestamp comparisons in the delinquency gate and reports; `Heartbeat::beat`
  duplicate insert when beaten twice in one second; portfolio subledger principal counting penalties/excess.
