# Implementation Status

## Stage 1 — Baseline (complete)

**Changes to application code:** none. Added the six programme documents and a git repository whose first commit is the archive as received.

### Review leads from the previous static review
| Lead | Verdict | Notes |
|---|---|---|
| TenantScope filtering disappears without context | **Confirmed** (F-03) | Fails open in workers, console, unresolved hosts. Mitigated in practice by explicit `organization_id` filters in most background code, but nothing enforces it. 14 models with `organization_id` don't use the scope at all (User, Role, Permission, LoanRepayment, LoanRepaymentSchedule, JournalEntryLine, AuditLog, Push*, ApprovalRequestStep, *NotificationSetting, Organization). |
| IdentifyTenant: user precedence, first-label matching, single-org fallback | **Confirmed** (F-04) | All three present. Additionally, tenant admins can claim unverified domains (F-20). |
| Page/blog raw HTML with string-only validation | **Confirmed** (F-05) | Stored XSS on public pages; AI-drafted content also rendered raw. |
| `custom_head_snippet` | **Partly confirmed** (F-06) | Accepted and stored, but rendered nowhere today; latent. |
| OrganizationProvisioningService assumptions | **Confirmed** (F-07) | Trusted super-admin, immediate email verification, no idempotency; also defaults to TZ/BoT framework (F-12). |
| AuditLog immutability via disabled updated_at | **Confirmed** (F-08) | No DB-level protection; audit failures swallowed. |
| MFA optional | **Confirmed** (F-09) | Plus no challenge throttling and TOTP replay possible. |
| Large shared routes/web.php and centralized AppServiceProvider | **Confirmed** | 1 790-line route file (1 166 routes); provider mixes infrastructure and business listeners; `Gate::before` grants everything to `admin` (F-10). |

### Proposed implementation batches
| Batch | Scope | Exit criteria |
|---|---|---|
| 0 | Hygiene: PHP constraint `^8.4`, reproducible `vendor` from lock, executable bits, global `Http::preventStrayRequests()`, seeders without default passwords in non-local envs | Suite green; `composer validate` clean |
| 1 | Tenancy & security foundations: fail-closed scope, explicit platform/system context, host mapping, membership check, jobs/commands/cache/files/exports, MFA, throttling, re-auth, RBAC fixes, support access, sanitization, secrets, append-only audit, headers | Two-tenant isolation suite green; full suite green |
| 2 | Ledger posting inversion (`PostingRequest`), money as decimals/minor units, row locks + idempotency on all money paths | New concurrency tests for each F-14 path |
| 3 | Module extraction (Kernel, Identity, Ledger, Savings, Shares, Lending …), per-module routes and providers, `arch()` dependency tests | No cross-module table writes; arch tests green |
| 4 | Regulatory applicability (D-006): regulator/licence/effective-date model, no default framework | Tests for TZ and non-TZ tenants |
| 5 | SaaS control plane: plans/prices/entitlements, subscription lifecycle, hosted card checkout (sandbox), domains, platform admin/support, self-service resumable onboarding | Entitlement limits enforced server-side; lifecycle tests |
| 6 | Website publishing: themes, safe components, drag-and-drop editor, drafts/preview/publish/rollback, SEO, tenant media | No executable tenant content; publish/rollback tests |

### Unresolved dependencies (need the business)
1. Hosted Visa/Mastercard provider for SaaS subscriptions in Tanzania with recurring/tokenised billing — merchant eligibility must be confirmed with the provider (D-007).
2. Platform domain(s) and DNS control for tenant subdomains; TLS approach for customer custom domains (wildcard + per-domain certificates) on the chosen hosting.
3. Production database version (MariaDB 10.11 tested here) and whether the host grants `TRIGGER` (and `SUPER` or `log_bin_trust_function_creators` when binary logging is on) — needed for database-level append-only audit.
4. Regulatory catalogue content for non-Tanzanian jurisdictions, if any are targeted.
5. Queue worker and scheduler availability on the target hosting (cPanel shared hosting typically allows cron but not long-running workers).

---
*Later stages append their own sections.*

## Stage 2 — Security and tenancy foundations (complete, pending your review)

### What was implemented
| Requirement | Implementation | Evidence |
|---|---|---|
| 1. Explicit tenant context + separate authorized platform context | `App\Tenancy\TenantContext` (TENANT / SYSTEM(reason) / NONE) held in the container; `IsolateTenantContext` global middleware resets it per request; `EnterPlatformContext` on platform routes re-checks the platform role before entering SYSTEM | TenantContextIsolationTest |
| 2. Fail closed; background work carries validated tenant | `TenantScope` throws without context; `TenantBuilder` keeps the tenant filter through `withoutGlobalScopes()`; write guards in `BelongsToTenant`; queue payload carries `tenant` and is restored/validated per job and restored after; 12 sweep commands run per organization (`RunsPerOrganization`); schema/seed commands run in a named system context | TenantContextIsolationTest, BackgroundAndStorageIsolationTest |
| 3. Exact host mapping, reserved platform hosts, unknown hosts rejected, no substitution | `organization_domains` + `HostResolver` + `OrganizationDomains`; DNS TXT verification; `tenancy:map-domain`, `tenancy:verify-domain` | HostResolutionAndMembershipTest |
| 4. Membership independent of host | `EnsureOrganizationMembership` on admin/member groups; login refuses other tenants' accounts on a tenant host | HostResolutionAndMembershipTest |
| 5. Ownership for relationships, foreign IDs, binding, raw queries, uploads, downloads, exports, search, cache, notifications | Declared tenant foreign keys on 10 core money/member models; route binding goes through the fail-closed scope; table-alias-aware scope; tenant-prefixed public media/branding paths; report export path per org + random; import tokens bound to org/user/type; notification recipients must belong to the tenant | BackgroundAndStorageIsolationTest |
| 6. Global-scope bypass review | All ~1 360 `withoutGlobalScopes()` calls now keep the tenant filter. Remaining explicit cross-tenant (system-context) entry points, each with a logged reason: host resolution, webhook token lookup, legacy webhook record, platform routes (role-checked), queued jobs dispatched in a system context, schema/seed/audit commands, organization iteration for sweeps, `tenancy:map-domain`, `hr:consolidate --permissions`, regulatory pack retirement, and two settings scans (sign-in page wording, maximum across organizations) | `grep -rn runAsSystem app` |
| 7. Admin MFA, recovery, session rotation, throttling, re-auth | `RequireMfa`, `TwoFactorService` (replay protection, hashed single-use recovery codes), `SecurityGateController` (enrol/verify/confirm), throttles `login`, `two-factor`, `password-reset`, `register`, `public-forms`; `config/security.php` re-auth route list | MfaAndReauthenticationTest |
| 8. RBAC, SoD, logged support access, no platform privileges for tenants | `Gate::before` admin bypass limited to tenant permissions; unmapped admin routes refused; self role changes refused; `support_access_grants` (reason, scope, expiry, audit) with read-only enforcement | HostResolutionAndMembershipTest |
| 9. Sanitized rich text, safe links/uploads, no tenant code | `RichTextSanitizer` (PHP 8.4 HTML5 parser, allow-list) on save + render; `custom_head_snippet` removed; raster-only image uploads unchanged (already restricted) | StoredScriptAndHeadersTest |
| 10. Sensitive data encryption and secret masking | Identity/bank numbers already encrypted at rest (verified); guarantor ID numbers now encrypted with keyed digest; Monolog redaction tap on every channel; audit change sets redacted; provider secrets were already write-only in the UI | AppendOnlyAuditTest, code review |
| 11. Append-only financial audit | DB triggers on `audit_logs`, `journal_entries`, `journal_entry_lines`; SHA-256 chain (`audit:seal` every minute, `audit:verify`); audit failures no longer swallowed | AppendOnlyAuditTest |
| 12. Headers, CSRF, webhook auth | `SecurityHeaders` (CSP, XFO, nosniff, referrer, permissions, COOP, HSTS on https, no-store for signed-in pages); CSRF unchanged with exemptions limited to webhook paths; webhooks processed inside the payment method's tenant after token + signature verification (signature logic unchanged) | StoredScriptAndHeadersTest, existing Payments tests |

### Residual risks (not solved in this stage)
| ID | Risk | Why open / next step |
|---|---|---|
| R-01 | 14 models with `organization_id` are not tenant-scoped (User, Role, Permission, LoanRepayment, LoanRepaymentSchedule, JournalEntryLine, AuditLog, PushSubscription, PushDelivery, ApprovalRequestStep, NotificationSetting, OrganizationNotificationSetting, PushSetting, Organization). Controllers guard User/Role manually (reviewed in Stage 1). | Child tables may hold rows with NULL organization_id; needs a data check + NOT NULL migration before adding the scope. Planned with the module extraction. |
| R-02 | Raw `DB::table()` on tenant tables bypasses the scope by nature (80 calls; 17 without an org filter, all reviewed as keyed by scoped ids or intentionally global). | Add an architecture test forbidding new `DB::table()` on tenant tables outside repositories. |
| R-03 | Declared foreign-key ownership checks cover 10 core models only; other relations rely on validation rules (`Rule::exists(...)->where('organization_id')`) and scoped binding. | Extend per module; long-term composite (organization_id, id) foreign keys in the database. |
| R-04 | Money races and float storage (F-13 … F-16, F-21) untouched. | Next batch (ledger posting inversion, decimals, row locks). |
| R-05 | Regulatory default TZ / Category B (F-12) untouched. | Regulatory applicability batch (D-006). |
| R-06 | Triggers can be dropped by a database administrator; the hash chain only detects it. | Ship audit rows to append-only external storage (WORM bucket / log service). |
| R-07 | CSP still allows `'unsafe-inline'` scripts (63 views with inline scripts). | Move inline scripts to files or nonces, then remove `'unsafe-inline'`. |
| R-08 | Public pages on the platform host return 404 (no platform marketing site yet). | Control-plane stage. |
| R-09 | Selcom `api_base_url` remains tenant-controlled (F-22); SMS HTTP calls have no timeout (F-23). | Payments/notifications hardening batch. |
| R-10 | The HTML sanitizer is in-house (packagist unreachable here). It is tested against common XSS/mXSS payloads but has not had third-party review. | Replace with `symfony/html-sanitizer` when dependencies can be installed; keep the tests. |
| R-11 | `DeferredAudit` (after-commit audit writes) still reports rather than rethrows failures, because the business change has already committed. | Move to the transactional outbox. |
| R-12 | `.env`-only secrets (APP_KEY, DB, mail) are not rotated by the app; encrypted columns depend on APP_KEY. | Document key rotation (`APP_PREVIOUS_KEYS`) in the runbook. |
| R-13 | MFA uses TOTP only; no WebAuthn/passkeys; recovery when an administrator loses both device and codes requires another administrator or the platform. | Add an admin-assisted reset with audit + support grant. |

### Deployment prerequisites introduced by Stage 2
1. **PHP 8.4** (already required by the lock file) — the sanitizer uses `Dom\HTMLDocument`.
2. **Environment:** `APP_URL` = platform host; `TENANCY_PLATFORM_HOSTS` (extra platform hosts), `TENANCY_SUBDOMAIN_BASES` (e.g. `kopeza.co.tz`), optional `TENANCY_APP_URL_IS_PLATFORM=false` for a single-tenant install whose APP_URL is the SACCO's own domain, `TENANCY_SUPPORT_ACCESS_MINUTES`.
3. **Domain mapping after provisioning:** `php artisan tenancy:map-domain <org-id|slug> <host> --verified` (operator controls DNS) or publish TXT `_kopeza-verify.<host>` and run `tenancy:verify-domain`. Without a mapping the tenant's public site and sign-in page are not served on that host.
4. **Database privileges:** TRIGGER; with binary logging also SUPER or `log_bin_trust_function_creators=1`, otherwise migration `2027_07_01_000003` fails (deliberately loud).
5. **Scheduler** must run `audit:seal` (every minute) in addition to existing schedules; run `audit:verify` periodically and alert on failure.
6. **Queue workers** (if used instead of `sync`): restart after deploy so they load the tenancy payload handling.
7. **First sign-in of every administrator** will require 2FA enrolment (authenticator app). Communicate before go-live.
8. **Default seeded passwords** (F-17) still exist; change them or don't run `AdminSeeder`/`PlatformSuperAdminSeeder` in production (Batch 0 item, not yet done).

### Next stage (proposed at the end of Stage 2)
Batch 0 hygiene (PHP constraint, lock-reproducible vendor, global `Http::preventStrayRequests`, seeders without default passwords) and Batch 2 (ledger posting inversion, money as decimals/minor units, row locks + idempotency on every money path, after-commit outbox).

## Stage 3 — Modules and controlled interactions (complete)

### Batches
| Batch | Commit | Scope | Verification at the end of the batch |
|---|---|---|---|
| 3.1 | `ecf6404` | Classes moved into `app/Modules/<Module>` and `app/Shared`; `routes/web.php` keeps the middleware shells and loads per-module route chunks; module service providers; `AppServiceProvider` reduced to infrastructure | full suite green; route list identical |
| 3.2 | `20065dd` | Ledger contract + journals in owning modules, postings inside the business transaction (F-15); Approvals module; payables registry; row locks on 9 money paths (F-14); funding source on savings credits; `accounting:prepare-ledger` | full suite green |
| 3.3 | `edb4b8c` | Payout trackers; bank checks; liens via Savings contract; insider-lending policy contract; delivery receipts; OrganizationIdentity → Regulatory | full suite green |
| 3.4 | `2c42a28` | Accounting extensions registry; payroll via Ledger; liquidity commitments; credit scoring → Lending; dashboard → Reporting; referral payout → Savings | full suite green |
| 3.5 | `cfb507a` | Inverse relations of `User`/`Organization` declared by owning modules | 1 584 passed |
| 3.6 | `c53ac86` | Last backward references removed (shell middleware, Shared purity, Identity contracts, profile-completion subjects, campaign topics, payment channels …) | 1 584 passed |
| 3.7 | `d4a07c0` | Owner operations for the remaining cross-module writes; manifest regenerated; architecture suite + exceptions register | 1 584 passed; Architecture 9 passed |
| 3.8 | `b508b77` | DECIMAL money columns (F-13); after-commit dispatch (F-21); locks on share redemption and loan repayment, repayment journal inside its transaction; treasury deadlock (F-28); new concurrency, dispatch, referral and prepare-ledger tests | 1 591 passed; Concurrency 14 passed; Architecture 9 passed |
| 3.9 | final commit | `pint` on files added in Stage 3; documents | see TEST_BASELINE Stage 3 |

### What was implemented (against the Stage 3 brief)
| Requirement | Implementation | Evidence |
|---|---|---|
| Real modules with ownership | 22 modules + Shared + application shell (MODULE_MAP §5). Each owns its models/tables, services, controllers, route chunk(s), console commands, jobs, provider, contracts and adapters. Every table is assigned (manifest) | `config/modules.php`; Architecture suite |
| Explicit contracts; interfaces only at real boundaries | 30 files under `Contracts` (interfaces, one value object, one marker interface) and 8 registries, each defined for a call across a module boundary (usually: lower module defines, higher module implements); no interface was added for an in-module use | DECISIONS D-020…D-022, D-025 |
| No uncontrolled model access | Cross-module writes go through owner operations; reads only of declared read models; raw SQL on another module's table is detected like model access | Architecture suite: 0 violations outside the register |
| Routing and service registration split, URLs/middleware/authorization/names preserved | per-module `routes/<shell>.php` loaded inside the unchanged shells; per-module providers in layer order | route comparison with Stage 2 end (TEST_BASELINE Stage 3 #6–7); permission registry unchanged (route-name patterns) |
| Automated architecture checks | `tests/Architecture` (9 tests): layering DAG, forbidden dependencies, public surface, cross-module writes, cycles, Shared purity, shell isolation, provider order, empty catches; exceptions register with stale-entry check | suite green; mutation checks fail as expected |
| Minimal Shared, no SACCO rules | 26 infrastructure files; SACCO-specific status texts moved to the shell, media-library rule to Website | Architecture: Shared has no module dependency |
| Atomic financial operations on one connection | Savings, shares, loan, dividend, expense, payroll and nomination-fee journals post inside the business transaction; posting failure rolls the business change back | `SaccoPostingTest`, `ParallelMoneyPathsTest` (rollback on committed data) |
| Precision, rounding, balanced journals, reversals, periods, approvals, idempotency preserved | DECIMAL storage; Ledger keeps balance check, period control, reversal-as-new-journal, idempotency key per event and source; approval chains close inside the business transaction | full suite (accounting, period control, approvals, payments idempotency tests unchanged and green) |
| External effects after commit; no silent failures | queues dispatch after commit or transactionally (D-029); 0 empty catch blocks (tested); posting failures are shown, not swallowed | `TransactionalDispatchTest`; Architecture |
| Duplicate submissions, concurrent operations, rollbacks, reconciliation on MariaDB | 6 new races + 8 existing; GL ↔ subledger reconciliation after each money race | Concurrency 14 passed (MariaDB 10.11.14) |

### Limitations and residual risks (Stage 3)
| ID | Risk | Next step |
|---|---|---|
| R-04 | (updated) Money storage and races addressed (F-13, F-14, F-15, F-21 fixed). Penalties, write-offs, provisioning and savings interest postings (F-16) still not implemented. | Lending/Savings feature work |
| R-14 | PHP-side money arithmetic still uses floats rounded to 2 decimals at each write; storage and SQL arithmetic are exact. | Move calculations to `Money`/bcmath per module, starting with Lending schedules |
| R-15 | EX-1: `Organization` helpers read the Reference catalogue and write its pivots (~100 call sites). | Organization-settings work: move helpers to a Reference service |
| R-16 | EX-2: Members, Workforce and Platform write `users` directly (shared person record). | Split person/profile columns from the login record, or Identity user operations |
| R-17 | Permission definitions stay central in Identity's `PermissionRegistry` (route-name patterns for all modules); modules do not declare their own permissions. Behaviour unchanged. | Let each module register its permission patterns (registry), keeping the "unmapped route is refused" rule |
| R-18 | Tests are organised by feature area under `tests/Feature`, not inside module folders; views remain in `resources/views`. | Move gradually if the team prefers co-location |
| R-19 | The static graph sees class references, not validation-rule strings (`exists:payment_methods`) or relations declared at runtime (`resolveRelationUsing`, owner-declared by design). | Review rule strings when touching each module; keep owner-declared relations |
| R-11 | (unchanged) `DeferredAudit` reports after-commit audit failures instead of failing the committed change. | Write audit rows through the transactional job row / outbox |
| R-05 | (unchanged) F-12: new organizations default to Tanzania / Category B; Tanzania bank list chosen by timezone. Not changed in Stage 3 (D-006 assigns it to the regulatory batch). | Regulatory applicability stage |
| R-01…R-03, R-06…R-10, R-12, R-13 | unchanged from Stage 2 | as listed in Stage 2 |

### Deployment prerequisites introduced by Stage 3
1. **Autoload and caches:** classes moved — run `composer dump-autoload -o`, then `php artisan optimize:clear` (and `route:cache`/`config:cache` if used).
2. **Migrations:** `2027_08_01_000001` (funding source, backfill) and `2027_08_02_000001` (DOUBLE → DECIMAL; rewrites the affected tables — schedule a maintenance window on large databases). After it runs, check the log for `money_columns.decimal_conversion_rounding` entries (rows whose stored value changed by rounding) and reconcile them.
3. **Ledger preparation:** run `php artisan accounting:prepare-ledger` once. Organizations that keep their ledger here must have the chart and mappings, because postings now block a money operation when they cannot be made.
4. **Queue:** with a separate queue database connection set `DB_QUEUE_CONNECTION` (after-commit dispatch is then automatic) or `DB_QUEUE_AFTER_COMMIT=true`; restart queue workers after deploy.
5. Stage 2 prerequisites still apply.

### Stopped at the stage boundary
Not started: Batch 0 hygiene items (PHP constraint, reproducible vendor, global stray-HTTP guard, default seeded passwords), regulatory applicability (F-12), SaaS control plane and self-service onboarding, website publishing.

## Stage 4 — Jurisdiction-aware regulatory policy (complete, pending your review)

### Batches
| Batch | Commit | Scope |
|---|---|---|
| 4.1 | `17440f1` | Jurisdiction / authority / licence-category model, determinations, applicability requests, three policy layers, neutral rule catalogue, lifecycle, provenance and legal-review fields, gate, evidence records, platform and SACCO screens, synthetic-jurisdiction tests, existing tests adapted |
| 4.2 | final commit | documents; pint on files added in this stage |

### What was implemented (against the Stage 4 brief)
| # | Requirement | Implementation | Evidence (tests) |
|---|---|---|---|
| 1 | Jurisdiction, regulator, licence category, pack version, effective dates and applicability modelled separately | Separate tables for jurisdictions (sub-national), authorities (primary or delegated) and licence categories. Packs carry jurisdiction, authority, categories, version, platform `effective_from`/`effective_to` and a separate legal effective date. The profile carries the determination, licence number and licence effective date (D-032) | `JurisdictionAwareRegulationTest`: "models … separately"; Zanzibar test |
| 2 | Inventory of Tanzanian assumptions | 79 findings in 11 areas, classed A–E (below; full table in the Stage 4 working notes summarised here) | — |
| 3 | Separate invariants, mandatory jurisdictional rules and organization-configurable policies | `PlatformInvariants` (forced), the adopted pack, organization policies within `permitted_bounds` (D-033) | invariant, bounds and override tests |
| 4 | No tenant can disable balanced accounting, tenant isolation, required approvals or statutory constraints | Several layers enforce this: <br>• invariants are forced in the resolver; <br>• the accounting maker–checker toggle is removed; <br>• tenant deactivation of a determined framework is refused and audited; <br>• weakening a pack rule is refused and audited; <br>• platform routes and services refuse tenant roles. <br>Ledger balancing and tenant isolation are unchanged and still tested by earlier suites | override, deactivation, isolation and access tests |
| 5 | Versioned pack mechanism, typed configuration, validation, documented strategies, report requirements, no tenant code | Packs are versioned with maker–checker and content hashes. Submission validation covers scope, example consistency, categories, provenance, report values and strategy names. The `report` rule type and `CalculationStrategies` registry are new; extensions are allow-listed (D-041) | lifecycle and provenance tests; existing pack tests |
| 6 | Platform policy administrators manage approved content and applicability in the dashboard | Platform screens: <br>• Regulatory catalogue (packs, provenance, legal review, approve with acknowledgement, withdraw); <br>• Jurisdictions; <br>• Determinations; <br>• Requests; <br>• Safeguards | screen test |
| 7 | SACCO administrators select or request an applicable approved pack, configure permitted settings; approvals follow an explicit policy | A new Regulatory applicability page offers determination, exception, not-regulated and adoption requests. The package page lists only covering packs. `adoption_policy` per pack: self-service or platform approval (D-037) | request, adoption and screen tests |
| 8 | Historical versions preserved; no silent recalculation | Pinned activations, `snapshotAt(date)`, append-only decision records on loan approval, payout settlement and restructure approval (D-038) | historical reproducibility test |
| 9 | Draft, approved, effective, superseded, retired with audit history | Lifecycle states and events; `advanceLifecycle` runs nightly (D-039) | lifecycle test |
| 10 | No applicable pack: draft set-up allowed, regulated activation blocked, no generic pack pretending compliance | Undetermined by default; neutral catalogue (no BoT defaults); `RegulatoryGate` on deposits, share sales, loan approval and payout; example packs labelled "[EXAMPLE — not law]" and unable to cover real jurisdictions (D-034, D-037, D-040) | undetermined, gate and example-scope tests |
| 11 | No fabricated thresholds, tax rates or approvals; sources and dates recorded; professional review flagged | Shipped packs are installed as submitted. Provenance and `legal_review_status` are recorded. Approval with outstanding review needs an explicit acknowledgement. Unattributed historical approvals are flagged. The verified facts and open review points are in D-036 | installer and provenance tests |
| 12 | Automated technical onboarding for supported configurations, exception path for unsupported jurisdictions | Provisioning is unchanged and automatic, with no regulatory assumption. Determination is by request or at creation. Unsupported jurisdictions use the exception path, which approves operation on the organization's own policies without claiming compliance | exception-path test; organization creation test |

### Inventory of Tanzanian assumptions (summary)
Classes:
- **A**: applies to every organization unconditionally.
- **B**: gated by country or timezone alone.
- **C**: read correctly through pack, resolver or settings.
- **D**: wording only.
- **E**: optional reference data.

| Area | A | B | C | D | E | Fixed in Stage 4 |
|---|---|---|---|---|---|---|
| Regulatory engine | 3 | 4 | 3 | – | – | A1 (BoT defaults → neutral catalogue), A2 (default TZ/B profile removed), A3 (neutral citations), B1 (country fallback removed), B2 (TZ/B helper removed), B3/B4 (matching by jurisdiction + authority + category) |
| Provisioning / onboarding | 3 | 2 | – | – | – | A4 (no default framework), A5 (carried-over profiles flagged), A6 (column defaults NULL), B5 (bank list by country, not timezone), B7 (platform screen) |
| Calculation | 2 | – | 2 | – | – | — (A7 DPD bands documented as a fixed strategy; A8 kept) |
| Validation | 4 | – | 2 | – | – | — |
| Reports / returns | 4 | – | 1 | – | – | A30 citations neutral; findings still raised |
| Payroll / tax | 4 | – | 2 | – | 1 | — (rates are per-organization drafts; levy vocabulary and due dates remain Tanzanian) |
| HR / leave | 2 | – | – | – | 2 | — |
| Approval / governance | 4 | – | 2 | – | 2 | accounting maker–checker made an invariant |
| Reference data / defaults | 6 | – | 1 | 1 | 4 | — |
| Phone / payments | 3 | 1 | – | – | 2 | — |
| UI text only | – | – | – | 12 | – | neutral citation helper; literal "BoT Regulation" strings in 8 views remain |

The items left are listed in D-043 with reasons. None of them applies a statute to an organization. They are local defaults, wording or formats that are wrong for non-Tanzanian organizations.

### Limitations and residual risks (Stage 4)
| ID | Risk | Next step |
|---|---|---|
| R-05 | (resolved) F-12: no default framework; applicability by determination | — |
| R-20 | Legal content of the shipped Mainland pack has had no professional review. Two citation differences and a permissive write-off are flagged, not changed. Commencement date is unconfirmed (D-036) | Professional review, then a reviewed new version; record the review on the pack |
| R-21 | On a fresh installation the shipped packs are only *submitted*: regulated operations stay blocked for every organization until two administrators approve a pack and the organization is determined | Platform operating procedure |
| R-22 | Upgraded installations: profiles carried over as `determined` reproduce the old TZ/B assumption until confirmed on the Determinations screen | Confirm or correct each carried-over profile |
| R-23 | Workforce, phone, timezone, prudential-return currency and governance wording assumptions (D-043) | Per-module follow-up; payroll levies need a jurisdiction-bound design |
| R-24 | DPD classification bands are fixed in code (only percentages come from the pack) | Reviewed classification strategy per jurisdiction |
| R-25 | Decision records cover loan approval, loan payout and restructure approval. Write-offs, recoveries and policy exceptions keep their existing snapshots or audit entries but no decision record | Extend `RegulatoryEvidence` to the remaining regulated decisions |
| R-26 | Organization creation records the determination after provisioning. If the determination fails after the basis/scope pre-checks (e.g. a category of another authority), the organization exists undetermined and the error is shown | Acceptable (safe default); could move into the provisioning transaction |
| R-27 | Zanzibar is unsupported. Its 2025 regulations are recorded only as reference notes, not as a pack | Build and review a Zanzibar pack if needed |

### Deployment prerequisites introduced by Stage 4
1. **Migration** `2027_09_01_000001` adds and alters the regulatory tables. It seeds the Tanzania Mainland and Zanzibar reference data, converts pack statuses, links the shipped packs with provenance, and carries over existing profiles as described in D-034. Run `composer dump-autoload -o` and `php artisan optimize:clear`.
2. **Upgraded databases:** review Platform → Determinations. Every profile marked "Carried over by the upgrade — confirm" needs a confirmed determination, and every other organization is undetermined: its deposits, lending and share sales are blocked until a determination is recorded.
3. **Fresh databases:** two Platform Regulatory Administrators must approve the shipped pack(s), acknowledging the outstanding legal review, before any Mainland organization can adopt them.
4. `policies:daily` now also advances pack lifecycle states.

### Stopped at the stage boundary
Not started: Batch 0 hygiene items, SaaS control plane and self-service tenant registration, website publishing, and the Stage 4 follow-ups R-20…R-27.

## Stage 5 — SaaS control plane (complete, pending your review)

### Batches
| Batch | Commit | Scope |
|---|---|---|
| 5.1 | `ec3c73d` | Billing module, migration, provider gateways, signup and provisioning, lifecycle, entitlements, access middleware, screens, tests |
| 5.2 | final commit | documents |

### What was implemented (against the Stage 5 brief)
| # | Requirement | Implementation | Evidence (tests in `tests/Feature/Billing`, `tests/Concurrency/ParallelBillingTest`) |
|---|---|---|---|
| 1 | Plans, immutable price versions, monthly/yearly, annual discount, trials, currencies, entitlements | Plan → versions (draft/published/retired, immutable when published) → prices per currency and interval; yearly computed exactly from the monthly price and discount (D-045) | yearly computation, immutability, retire-on-publish, old subscribers keep their price |
| 2 | Configurable members, staff, storage, modules, SMS; counting, reset, overage, downgrade, concurrency | Per-version entitlements and overage policy; definitions in D-049; downgrades keep data and refuse additions; org-row lock; atomic SMS counter | member limit (form), allow-and-record, SMS block/reset (UTC month), module read-only, downgrade, forked race for the last slot |
| 3 | Pricing shows accurate availability and actual annual charge; demo separate from live | `/pricing`: the yearly price is the amount charged once a year, with the saving; availability per currency and mode with the reason; demo/test banners and button wording (D-046) | pricing in test, demo, live-with-test-key and disabled modes; unsupported currency |
| 4 | Pending signup, provisional billing identity, hosted card checkout | `billing_signups`, provisional `billing_customers`, Flutterwave hosted checkout (D-051) | full paid flow; request contract |
| 5 | Provider chosen on evidence | Flutterwave v3 (TZS, BoT-authorised, tokenized charges); Stripe/Paystack excluded; Pesapal unsigned IPN; Paddle as USD alternative (D-047). Existing tenant drivers not reused | — (documentation evidence; live blockers below) |
| 6 | No card data stored | Hosted checkout only; only the provider token (encrypted), brand, last 4, expiry are stored | request-shape test (no card fields); demo page has no card fields |
| 7 | Raw-body webhook authentication, replay safeguards; validate account, mode, customer, invoice, amount, currency, snapshot | D-048 | forged (wrong/no secret, HMAC over different bytes), stale event, wrong amount/currency/customer/account, tampered invoice total |
| 8 | Never activate from the browser redirect | Return page asks the provider server-side; query string ignored | redirect spoofing test |
| 9 | Persist, deduplicate, process reliably, out-of-order, reconcile | Event inbox with unique key, claimed processing with back-off, per-attempt references, deferral, `billing:reconcile` | duplicate delivery, reordered failure/success, deferred then applied, webhook never arrives |
| 10 | Provisioning as explicit operations, unique signup→tenant, transaction safety, durable retryable steps | `SignupProvisioning` steps; `organizations.signup_reference` UNIQUE; Platform implements `TenantProvisioner` (D-052) | payment then provisioning failure then retry → one tenant; DB-level uniqueness; 4 forked workers → one tenant |
| 11 | E-mail verification separate from payment; activation retries without duplicates | D-051, D-052 | verification e-mail failure and resend; activation e-mail failure and resend; owner verification time = signup verification |
| 12 | Trial, active, past-due, grace, restricted, canceled, expired | D-050 state machine, hourly `billing:advance` | trial without card → restricted; retries → grace → restricted → expired; cancel |
| 13 | Renewal, cancellation, plan changes, authentication-required, refunds, disputes under explicit policies | D-050 | renewal (idempotent), requires-action, cancel/resume, prorated upgrade applied on confirmation, scheduled downgrade, refunds (platform only, bounded), disputes open/lost/won |
| 14 | Restriction preserves data and in-flight financial processing; billing recovery and record access stay available | `billing.access`: reads always; allow-list of billing and in-flight financial routes; nothing deleted | restricted read/refuse/pay/recover test; allow-list test; expiry keeps data |
| 15 | Customer-visible status and platform exception handling | Signup status page (steps, safe-payment message, resend); Settings → Subscription; Platform → Billing exceptions (open exceptions, failed/deferred events, stuck signups, retry and resolve) | screen tests |

### Live-integration blockers (nothing here is claimed as done)
| ID | Blocker | Owner |
|---|---|---|
| B-01 | No Flutterwave credentials in this environment: **no sandbox call was made**. All provider behaviour is tested against a deterministic contract double of the documented v3 shapes | Platform operator: create sandbox keys, set `BILLING_MODE=test`, run a manual end-to-end purchase |
| B-02 | Merchant eligibility of the platform's own legal entity for card acceptance, and settlement currency (TZS vs USD) | Business, with Flutterwave |
| B-03 | Tokenized (merchant-initiated) charges enabled on the account; how 3-D Secure applies to them (handled as `requires_action` if returned) | Business, with Flutterwave |
| B-04 | Dispute/chargeback notifications: the gateway maps them if delivered; otherwise the platform records disputes manually | Confirm with Flutterwave |
| B-05 | Tax: no VAT rate configured; TRA EFD receipt obligations for SaaS invoices unknown | Tax adviser |
| B-06 | Webhook URL registration and secret hash on the provider dashboard; v4 signature if available | Platform operator |
| B-07 | No live certification is claimed | — |

### Limitations and residual risks (Stage 5)
| ID | Risk | Next step |
|---|---|---|
| R-28 | Storage is measured daily from the organization's storage path; between measurements uploads can exceed the limit | Count on upload if exactness is required |
| R-29 | The member bulk import enforces the plan's member limit through the mirrored `organizations.max_members` (its own pre-existing check), not through `assertCanAdd`: it counts every non-admin user (employees included), takes no organization lock, and does not honour `allow_and_record` | Route the import through `assertCanAdd` with a readable per-row message |
| R-30 | v3 webhook authentication is a shared secret header, not a signature; safety rests on API re-verification (D-048) | Enable v4 signatures on the account when available |
| R-31 | Proration uses seconds of the current period and a single prorated invoice; no credit for downgrades (by policy) | Business review of the policy |
| R-32 | Demo-mode subscriptions are real records with `mode = demo`; switching a production environment from demo to live keeps them | Use demo only on demonstration installs |
| R-33 | Overage under `allow_and_record` is recorded but not invoiced automatically | Platform invoices manually or a later stage adds overage invoicing |
| R-34 | Browser rendering of the new screens is tested only through HTTP responses (front-end build still blocked, Stage 1) | — |

### Deployment prerequisites introduced by Stage 5
1. Migration `2027_10_01_000001_create_billing_control_plane` (new `billing_*` tables, `organizations.signup_reference`, `manage-subscription` permission). Run `composer dump-autoload -o` and `php artisan optimize:clear`.
2. Environment (never in the UI): `BILLING_MODE` (default `disabled`), `BILLING_FLUTTERWAVE_SECRET_KEY`, `BILLING_FLUTTERWAVE_WEBHOOK_SECRET_HASH`, `BILLING_FLUTTERWAVE_ACCOUNT_ID`, `BILLING_FLUTTERWAVE_CURRENCIES` (see `.env.example`).
3. Register `https://<platform host>/webhooks/billing/flutterwave` on the provider dashboard.
4. The scheduler must run (`billing:process-events`, `billing:reconcile`, `billing:advance`, `billing:provision-signups`, `billing:measure-storage`) and a queue worker should run.
5. Create and publish plans on Platform → Billing before opening `/pricing`.

### Stopped at the stage boundary
Not started: tenant website publisher, custom domains, Batch 0 hygiene items, the Stage 4 follow-ups R-20…R-27 and the Stage 5 follow-ups above.

## Stage 6 — Tenant domains and organization set-up wizard (complete, pending your review)

### Batches
| Batch | Commit | Scope |
|---|---|---|
| 6.1 | `2e4da45` | Domain registry and lifecycle, edge adapter and probe, edge endpoints, proxy and session hardening, domain screens, scheduler, Onboarding module, operational activation, tests, setup guide |
| 6.2 | final commit | documents |

Before Stage 6 started, untested edits made while re-checking Stage 5 were reverted, so Stage 5 stays exactly as committed (`ec3c73d`, `e41a3b1`). The two gaps found during that re-check are recorded as R-35 and R-36.

### Domains (against the brief)
| Requirement | Implementation | Evidence |
|---|---|---|
| Unique free sub-domains under the platform domain; reserved names | `DomainRegistry::claimSubdomain` / `subdomainProblem`; reserved labels, platform hosts; retained old names | DomainLifecycleTest (free sub-domains) |
| Normalised exact-hostname registry for every alias; uniqueness across active, pending and retained | `organization_domains.host` UNIQUE across all states; every base alias is a row; resolver uses ACTIVE rows only (D-055) | collisions test (incl. DB-level) |
| Reserve → expiring random TXT → ownership → routing → edge → certificate → HTTPS → activate | `DomainRegistry::addCustom/check` (D-056) | lifecycle test |
| Ownership and certificate validation separate | Separate columns and states; a certificate failure after ownership keeps the host inactive | lifecycle, re-check tests |
| Correct CNAME / A / AAAA / apex instructions | `EdgeAdapter::routingRecords` from configured edge target and addresses; apex heuristic shows both forms and the ALIAS/flattening note | apex test, screen test |
| No activation because DNS points to the server | Routing is condition 2 of 4; ask endpoint refuses unverified hosts | lifecycle and ask tests |
| Retries, propagation, token renewal, certificate renewal/failure, removal, fresh verification before reassignment | Back-off, observed records, renew, daily re-check (expiring/failed/renewed), retained rows, release, fresh code | expiry, retries, re-check, transfer tests |
| Dangling domains, takeover, SSRF, proxy headers | Retained hosts plus a fresh code; ask endpoint allow-list; probe connects only to the configured edge; X-Forwarded-Host never trusted | transfer, ask, forwarded-host tests; D-057, D-058 |
| Secure host-only sessions | `session.domain` fixed null; secure by default in production | cookie test |
| Edge adapter with a supported implementation and setup guide | `CaddyOnDemandEdge` (+ operator-managed, none); `docs/operations/custom-domains.md` | TlsProbeTest (real TLS); Caddy itself not run |
| Never claim HTTPS from a mocked adapter | Readiness only from `TlsHttpsProbe`'s keyed answer; adapters cannot activate | design (D-057); TlsProbeTest |

### Onboarding (against the brief)
| # | Step | Completion criteria (from real records) |
|---|---|---|
| 1 | Owner identity, e-mail verification, MFA | owner name, `email_verified_at`, `two_factor_confirmed_at` |
| 2 | Profile and contacts | legal and display names, e-mail, phone, address, contact person (applied via Tenancy) |
| 3 | Jurisdiction, applicability, language, timezone, currency | platform determination and policy condition (`policyStatus`); active language; valid timezone; enabled currency (applied via Tenancy) |
| 4 | Accounting year, chart, mappings, opening | Accounting checklist (functional currency, chart, mappings, open year); opening balances when migrating |
| 5 | Branches, staff, roles, approvals | ≥1 active branch, ≥2 active staff accounts, roles and approvals reviewed |
| 6 | Savings, loans, shares products | active savings product; loan and share products if offered |
| 7 | Payment integrations | ≥1 active payment method |
| 8 | Website template and content | publish (look, headline, contact) or "not now" |
| 9 | Sub-domain / custom domain | active free address; custom-domain propagation never blocks |
| 10 | Final validation and activation | steps 1–9 complete, subscription in service, owner/admin with 2FA, explicit confirmation |

- Drafts, versioned safe editing, re-open, progress and resume work as described in D-060.
- Regulated operations need activation in addition to the policy condition (D-061).

### Infrastructure-dependent checks NOT run (reported honestly)
| ID | Check | Why not | Where |
|---|---|---|---|
| I-01 | Caddy on-demand certificate issuance for a real custom domain | No public DNS, no internet-reachable edge in the build environment | guide §7 steps 1–4 |
| I-02 | ACME rate limits, renewal by Caddy over time | Same | guide §4 |
| I-03 | Wildcard certificate for the platform base (DNS-01) | Needs a DNS-provider module and token | guide §3 |
| I-04 | Real DNS propagation behaviour (resolver caching, split-horizon) | `SystemDnsResolver` sees only this server's resolver | guide §1 |
| I-05 | Caddy refusing certificates for unknown hosts in practice | Needs a running Caddy | guide §7 step 5 |

### Limitations and residual risks (Stage 6)
| ID | Risk | Next step |
|---|---|---|
| R-35 | (Found while re-checking Stage 5.) Billing payment validation skips the merchant-account and customer checks when the provider's verification response omits those fields | Fail closed outside demo mode, with tests |
| R-36 | (Found while re-checking Stage 5.) The member bulk import uses the mirrored `max_members` check instead of `Entitlements::assertCanAdd` | As R-29 |
| R-37 | Apex detection is a heuristic (no public-suffix list); the page shows both forms | Add a public-suffix list if needed |
| R-38 | A certificate already stored at the edge for a removed host stays there until it expires (the application answers 404 for the host) | Caddy storage clean-up job, if wanted |
| R-39 | Activation is not reversed automatically when a step later needs attention (by design, so financial events already under way are not blocked); the policy condition is still enforced per operation | Platform review of "needs attention" organizations |
| R-40 | Steps 4–8 rely on the owning modules' screens; the wizard checks their outcomes but adds no new editing UI for them | — |
| R-41 | Organizations on upgraded installations are carried over as operational without going through the wizard | Optional: ask existing organizations to review their profile and contact details |

### Deployment prerequisites introduced by Stage 6
1. Migration `2027_11_01_000001`:
   - adds the domain lifecycle columns and `organization_domain_events`;
   - adds the organization profile and operational columns (existing organizations become `active`, `carried_over`);
   - adds `onboarding_steps` and the `manage-domains` and `manage-onboarding` permissions.
2. Environment, as in `.env.example`:
   - `TENANCY_EDGE`;
   - `TENANCY_EDGE_CNAME_TARGET`, `TENANCY_EDGE_IPV4`, `TENANCY_EDGE_IPV6`;
   - `TENANCY_EDGE_PROBE_ADDRESS`;
   - `TENANCY_EDGE_ASK_SECRET`, `TENANCY_EDGE_ASK_ALLOWED_IPS`;
   - `TRUSTED_PROXIES`.
   `SESSION_DOMAIN` is now ignored.
3. Edge configuration and DNS as described in `docs/operations/custom-domains.md`, then that guide's acceptance check §7.
4. The scheduler runs `tenancy:domains-check` every 5 minutes.
5. New organizations, whether created by the platform or by self-signup, must complete Organization set-up and be activated before deposits, loans or share sales.

### Stopped at the stage boundary
Not started: the safe website publisher (templates/components beyond the current settings), Batch 0 hygiene, and follow-ups R-20…R-41.

## Stage 7 — Website publishing (complete, pending your review)

### Batches
| Batch | Commit | Scope |
|---|---|---|
| 7.1 | `c905ffd` | Publishing model, templates, components, validation, builder UI, preview/publish/rollback, cache, media hardening, auth branding, tests |
| 7.2 | final commit | documents and guides |

### Against the brief
| # | Requirement | Implementation | Evidence |
|---|---|---|---|
| 1 | Three complete templates with different compositions, typography, navigation, heroes and section arrangements | Harbor, Savanna, Summit (D-064) | TemplatesTest; browser check; similarity 0.02–0.07 |
| 2 | Tenant configuration of name, logo, favicon, colours, approved fonts, template, header/footer variants, hero, navigation, sections and order, pages, contacts, social, SEO, sign-in branding | Builder "Site" tab and blocks. Name, logo and favicon stay on Settings → Branding, the single source used across the application, and are linked from the builder (D-063) | PublishingTest, TemplatesTest |
| 3 | Drag-and-drop with a server-validated registry | `site-builder.js` (mouse drag-and-drop plus keyboard buttons) and `Components` / `SiteDocument` | SecurityTest; browser check |
| 4 | Versioned structured data, schema validation, nesting, size and count limits | `website_revisions` JSON, `SiteDocument` (D-066) | SecurityTest |
| 5 | SACCO components | 17 components incl. products, branches, FAQs, testimonials, gallery, contact form, call to action (D-065) | TemplatesTest, PublishingTest |
| 6 | Autosave, authenticated preview, responsive previews, explicit publish, rollback | D-067 | PublishingTest; browser check |
| 7 | Tenant media, validation, safe formats, authorization, quotas | D-069 | SecurityTest |
| 8 | Tenant-aware cache with invalidation | D-068 | PublishingTest |
| 9 | Accessible, responsive UI; validated navigation and links | Landmarks, skip link, `aria-current`, `aria-expanded` menus, keyboard reordering, required picture descriptions, typed links | EmbedsAndAccessibilityTest; browser check |
| S | Security list | Never compiled; sanitised; restricted URLs and embeds; separate permissions; published-only public; preview no-store; versioned templates; no private data | D-063…D-071 |

### Limitations and residual risks (Stage 7)
| ID | Risk | Next step |
|---|---|---|
| R-42 | The previous homepage's live aggregates (total savings, loans disbursed, member count) are not shown once a site is published (by design, D-063); organizations that relied on them must type figures | Business confirmation |
| R-43 | The editor's rich-text field is an HTML textarea (sanitised server-side), not a WYSIWYG editor | Add a platform WYSIWYG that emits the allowed subset |
| R-44 | `/storage` served directly by the web server bypasses the per-host picture check | Route `/storage` through the application if required (guide) |
| R-45 | No automated accessibility audit (axe) was run; checks are assertion-based plus one real-browser pass | Add axe to a browser test job when the front-end build is unblocked |
| R-46 | Fonts load from Google Fonts (as before), which sends visitor IP addresses to Google | Self-host the approved fonts |
| R-47 | Page cache uses the application cache store; with several web servers it must be a shared store | Deployment configuration |
| R-48 | A draft that references a picture later deleted elsewhere is rejected at publish (with the field); the editor shows the path, not a friendly label | Improve the message |

### Deployment prerequisites introduced by Stage 7
1. **Migration** `2027_12_01_000001_website_publishing`: adds the two tables, the immutability trigger, the media columns and the permissions (`edit-website` and `publish-website` are given to the admin role).
2. **Optional environment:** `WEBSITE_MEDIA_QUOTA_MB`, `WEBSITE_MEDIA_MAX_FILES`, `WEBSITE_PAGE_CACHE_MINUTES`.
3. **Static assets:** `public/css/site/*`, `public/js/site.js`, `public/js/site-builder.js` and `public/css/site-builder.css` must be deployed. They are plain files; no front-end build is needed.
4. **Existing sites** are unchanged until each organization publishes from the builder.

### Stopped at the stage boundary
Not started: WYSIWYG rich text, self-hosted fonts, Batch 0 hygiene, and earlier follow-ups (R-20…R-41).

## Stage 8 — Feature preservation and configuration completeness (complete, pending your review)

### Batches
| Batch | Commit | Scope |
|---|---|---|
| 8.1 | `69d42c2` | Organization clock, Platform → Settings, currency precision, country-aware starter content, regulator-neutral wording, classification bands, audits, permission-aware links, readable failures, seed hygiene, Kiswahili, evidence tests, role crawl, three-SACCO workflows |
| 8.2 | final commit | documents |

### Against the brief
| # | Requirement | Result | Evidence |
|---|---|---|---|
| 1 | Reconcile every feature in the matrix | Every row in §1–§5 has a Stage 8 finding, status and evidence | FEATURE_PRESERVATION_MATRIX §13 |
| 2 | Missing routes, screens, operations, permissions, jobs, reports, exports, integrations | Missing: platform business settings screen (added); 9 features without any test (tests added: documents, referrals, collateral, recurring journals, cost centres, events, contact inbox, SLA, AI, SMS gateways/campaigns, maturity, group accounts). No route had been removed in Stages 2–7 | §13; TEST_BASELINE Stage 8 |
| 3 | Restore/complete; document replacements | Bugs fixed: lien-only payout (D-083), recurring journals crash, event colour crash, audit-log export 500, 56 forbidden links. Kept as baseline: group withdrawal maker-checker (D-084) | D-081…D-084 |
| 4 | Platform configuration to platform admins; SACCO configuration to tenant admins | Platform → Settings (Super Admin only); SACCO settings permission-gated (unchanged); platform settings refused to SACCO admins and regulatory admins | ConfigurationAndJurisdictionTest; RoleCrawlTest |
| 5 | Validated settings screens, no routine DB/CLI configuration | Added: platform settings, currency decimals, mobile-money catalogue, classification bands. Remaining CLI: `kopeza:super-admin` (bootstrap, deliberate), `media:oversized-report` (operator), `tenancy:map-domain` (operator fallback; UI exists) | D-076 |
| 6 | Business settings vs deployment secrets | Deployment values never shown; screen shows configured/not configured only | D-076; test asserts no secret value in page |
| 7 | Validate, dependencies, applicability, audit | Ranges, IANA zones, increasing bands, SMS channel needs a working gateway, website allowance ≤ plan; audited (D-080) | ConfigurationAndJurisdictionTest |
| 8 | Permission-aware navigation, errors, validation, empty states, recovery | 28 role crawls with 0 forbidden/dead links; warning/error flashes on every layout; PDF/mail failures readable | RoleCrawlTest; D-081/D-082 |
| 9 | Dead links, misleading success, placeholders, mock production behaviour | Fake TZS ledger on sign-in, "Report emailed" with a log mailer, starter prompts, invented seeded people/quotes/contacts, demo accounts in production, unrouted controller — removed | D-073, D-082 |
| 10 | All roles | SACCO admin, 22 role templates (incl. credit committee/approver, auditor, supervisory committee), plain staff, member, visitor, platform and regulatory admins | RoleCrawlTest; E2E |
| 11 | Localization, currency precision, dates, time zones | Organization clock; ISO minor units; 521 date formats localised; +1 093 Kiswahili strings | D-074, D-075 |
| 12 | Accidental Tanzanian defaults | Time zone, holiday calendar, leave and payroll templates, mobile money, pension schemes, bank country, import cities, Kiswahili, BoT wording, classification bands, TSh — all now follow determination/organization facts | D-074…D-079 |
| E2E | Three synthetic SACCOs | A: Tanzania, BoT pack, TZS, Dar es Salaam. B: example jurisdiction "XB" with its example pack, UGX, Lagos clock. C: undetermined, KES, Bogotá | ThreeSaccoWorkflowsTest 5/5 |

### External dependencies (not verified live; reported separately)
| Dependency | Used for | How it was tested here |
|---|---|---|
| Headless Chrome + Node + puppeteer | PDF exports | Real Chromium in the crawl (74 PDFs); without it a readable 503 (tested) |
| Mail transport (SMTP etc.) | e-mail, verification, reports | Mail fake/array; "not sent" wording tested |
| Payment providers (9) | collections, payouts | Contract doubles only; no provider contacted |
| SMS gateways (4) | SMS, campaigns | HTTP fakes |
| OpenAI | AI insights/drafting | `Http::fake`; no live call |
| Custom-domain edge, DNS, TLS | custom domains | Stage 6 probes faked; HTTPS not claimed |
| MariaDB time-zone tables | named zones with daylight saving | Offset fallback tested; tables not loaded here |
| Queue worker, scheduler | jobs, hourly `--local-hour` sweeps | Sync queue and direct command runs |
| Google Fonts | public site fonts | Not fetched (Stage 7 R-46) |

### Limitations and residual risks (Stage 8)
| ID | Risk | Next step |
|---|---|---|
| R-49 | About 300 `number_format(…, 2)` remain in accounting, HR, payroll, governance and report screens (UGX shows ".00"); input precision is enforced only for deposits, withdrawals, loan applications and repayments | Convert remaining screens to `CurrencyFormat` |
| R-50 | Time-zone semantics are for fresh installs; existing rows written in Dar es Salaam wall-clock time are not converted | One-off conversion if an upgraded install is ever needed |
| R-51 | Without MariaDB time-zone tables, zones with daylight saving use the current offset | Load `mariadb-tzinfo-to-sql` in deployment |
| R-52 | Group withdrawals have no maker–checker (baseline behaviour, D-084) | Product decision |
| R-53 | Phone matching on last nine digits (D-084) | Country-aware normalisation |
| R-54 | Kiswahili translations were machine-assisted and not reviewed by a native speaker | Language review |
| R-55 | Crawl reaches 317 of 505 named GET routes by links; the rest are covered by the parameterless sweep or by tests, not every parameterised screen was opened | Extend crawl seeds |
| R-56 | Built-in texts are neutralised by pattern (`Reg. n`, `BoT Regulation n`) when no pack applies; citations written differently (e.g. "AML Act", "Cooperative by-laws" on role templates) are shown as written | Review remaining static citations |

### Deployment prerequisites introduced by Stage 8
1. Migration `2028_01_01_000001_stage8_configuration_completeness` (platform_settings, currencies.decimals with back-fill, member_profile_settings.mobile_money_providers, banks.country nullable, classification bands).
2. `APP_TIMEZONE` now defaults to **UTC** (was Africa/Dar_es_Salaam). Load MariaDB time-zone tables (recommended).
3. The scheduler entries changed to hourly with `--local-hour`; deploy the new `routes/console.php`.
4. Production `db:seed` creates no users; run `php artisan kopeza:super-admin` once.

### Stopped at the stage boundary
Not started: converting the remaining two-decimal screens (R-49), group-withdrawal maker–checker, and earlier follow-ups (R-20…R-48).

## Stage 9 — Measured performance and production operations (complete, pending your review)

### Batches
| Batch | Commit | Scope |
|---|---|---|
| 9.1 | `8128526` | Workload model and synthetic generator; load driver, sampler, in-process screen/operation profilers; daily ledger totals; liquidity holds closed; indexes; per-request memos; permission-check fast path; N+1 fixes; caches; queue lanes, timeouts, bounded retries, chunked and paced campaigns, queued imports and e-mailed reports, streamed exports; correlation ids, JSON logs, access log, health/readiness, Platform → Operations, `ops:check`; encrypted backups, tenant export/import, restore drill; cross-tenant deadlock fixes; trusted proxies under config cache; operations documentation |
| 9.2 | final commit | the six documents |

### Against the brief
| Requirement | Result | Evidence |
|---|---|---|
| Reproducible workload model, assumptions stated, synthetic data | Reference platform written down as an assumption; measured dataset of 17 SACCOs / 438 652 journal lines built by the application's own services; dump restored before every run | TEST_BASELINE 9.1; D-086 |
| Service targets before optimizing | Proposed in D-087 before any fix; compared in TEST_BASELINE 9.2 — met at light load, **not met at peak on the 2-vCPU test VM** | D-087 |
| Measure percentiles, query counts, queue delay, throughput, memory, lock contention | All recorded per run (client percentiles; queries per action; queue oldest wait per queue and job class; actions/s; PHP-FPM memory; row-lock waits, deadlocks) | TEST_BASELINE 9.3–9.5 |
| Fix N+1, unbounded reads, pagination, unnecessary queries, inefficient reporting | Statements and liquidity from daily totals; dashboards bounded; mappings, settings, periods, profiles read once; staff list, KYC, HR provisioning N+1 removed; exports streamed | TEST_BASELINE 9.4; D-088, D-089 |
| Indexes from actual plans | 6 indexes, each with EXPLAIN and time before/after | TEST_BASELINE 9.4; D-100 |
| Tenant-safe caching | Public figures per organization (10 min); push-settings null caching; existing versioned keys kept; permission data no longer platform-wide per request | D-097, D-099 |
| Queue long work; separate workloads; per-tenant consumption | Imports, e-mailed reports, campaigns, invitations on long lanes; payments on `critical`; campaigns chunked with cursor and per-organization pacing | D-090, D-091; month-end run TEST_BASELINE 9.5 |
| Financial correctness under concurrency | Concurrency suite incl. new cross-tenant payout test (fails 3/3 on Stage 8, passes on Stage 9); after every load run totals = lines, subledgers = ledger, 0 deadlocks | D-092; TEST_BASELINE 9.3 |
| No persistent workers without validation | Not adopted; evidence recorded both ways | D-095 |
| No invented numbers, no extrapolation | Every number in TEST_BASELINE 9 comes from a recorded run on the stated VM; none is projected to production | TEST_BASELINE 9 preamble |
| Secure production configuration, least privilege, deployment documentation | `ops:check` / Platform → Operations checklist; four database accounts documented; every Stage 9 load run used the data-only account and its migrations the migrate account | docs/operations/deployment.md |
| Health/readiness, structured redacted logs, correlation ids, tenant-aware monitoring | `/health/live`, `/health/ready`; JSON logs with request/organization/user/job ids after redaction; access log per route and organization; queue view per lane and organization | D-093; Feature/Operations tests |
| Failed jobs, bounded retries, dead-letter visibility, webhook reconciliation | Every job has lane, timeout < retry_after, bounded tries; failed jobs listed with retry/delete (audited); existing `payments:reconcile`, `billing:reconcile` in the runbooks | D-090; QueueOperationsTest, OperationsScreenTest |
| Encrypted database and file backups, retention | libsodium secretstream archives, own key, read-back verification, 14/8/12 retention | D-094; Operations suite |
| Restore one tenant into an isolated environment without overwriting others | Drill on the large synthetic SACCO: 738 429 rows, 129.6 s, all checks passed; collision import refused and rolled back | TEST_BASELINE 9.7; D-094, D-101 |
| Actual RTO and RPO limits | RTO measured (above); RPO = daily backup (≤ 24 h) — binary-log point-in-time recovery **not demonstrated** | TEST_BASELINE 9.7 |
| Keys, files, pending jobs, gateway reconciliation, audit history during restore | Keys escrowed outside backups (drill checks decryption); files in the archive; queued jobs reviewed before workers start; reconcile commands; audit chain verified in the drill | backup-and-restore.md, disaster-recovery.md |
| Edge/WAF, certificate monitoring, incident response, DR | Written | edge-and-waf.md, monitoring.md, incident-response.md, disaster-recovery.md |
| Safe deploy, worker restart, rollback | Release procedure with `queue:restart`; rollback to Stage 8 and forward demonstrated (requires `verify-totals --repair`) | deployment.md §4–§6; TEST_BASELINE 9.6 |
| Load and concurrency tests on the intended engine; before/after | MariaDB 10.11 throughout; Stage 8 vs Stage 9 on the same restored dataset | TEST_BASELINE 9.3 |

### Test results (final code)
Unit+Feature 1 816 passed (0 failed, 0 skipped); Architecture 9; Concurrency 17; Operations 5; Performance 4 opt-in (skipped by default). Details: TEST_BASELINE 9.8.

### Application work vs operator steps
**Done in the application (this stage):** everything in the table above.

**Requires operator action (not done here, cannot be done from the code):**
1. Size production hardware against D-087 and repeat the load scenarios there (`tests/Performance/load`); the test VM saturates at about 11 mixed actions/s.
2. Create the four database accounts (deployment.md §3) and run migrations with the migrate account.
3. Supervisor programs per lane (deployment.md §5); cron for `schedule:run` on one server.
4. Set `BACKUP_ENABLED`, `BACKUP_ENCRYPTION_KEY` (escrowed with `APP_KEY`), offsite copies with immutability, `HEALTH_TOKEN`, `TRUSTED_PROXIES`, `LOG_FORMAT=json` and log shipping.
5. Binary logging and a replica for point-in-time recovery and failover; then rehearse PITR (not demonstrated here).
6. Edge/WAF rules, TLS certificate monitoring and alerting (edge-and-waf.md, monitoring.md).
7. Monthly restore drill with the restore account (its grants were documented but not exercised here).

### Limitations and residual risks (Stage 9)
| ID | Risk | Next step |
|---|---|---|
| R-57 | Peak targets not met on the test VM; production capacity unknown | Operator load test on sized hardware |
| R-58 | Member deposit notices were not generated in the synthetic dataset, so their wait behind campaigns was not measured | Enable a notification template in the generator and re-run the month-end scenario |
| R-59 | Point-in-time recovery from binary logs not demonstrated | Operator rehearsal with binlog enabled |
| R-60 | `audit:seal` chains 15 000 rows per organization per run; a backlog (e.g. after an import) takes several scheduler minutes to seal (45 runs for 410 659 rows here) | Acceptable at expected rates; raise the batch if needed |
| R-61 | Rolling code back after the Stage 9 migration leaves daily totals stale until `accounting:verify-totals --repair` | Documented as a mandatory step (deployment.md §6) |
| R-62 | Framework model booting is ≈ 13 % of web CPU per request; only a persistent runtime would remove it, which is not validated for tenant isolation | D-095 |
| R-63 | Status hints (regulation references in badges) cost ≈ 8 % of web CPU on every page | Memoize per organization and locale |
| R-64 | Restore account grants (deployment.md §3) were written but the drill ran with the development account | Run the drill with the documented account in staging |
| R-65 | Load scenarios used one load driver on the same VM; client think time and mixes are assumptions | Replay real access-log mixes once in production |

### Deployment prerequisites introduced by Stage 9
1. Migrations `2028_02_01_000001_stage9_operations` and `2028_02_01_000002_stage9_performance` (new tables `ledger_daily_totals`, `backup_runs`, `report_exports`; campaign progress columns; six indexes; back-fill). Run with the migrate account.
2. Queue workers per lane (`database` and `database-long` connections); `queue:restart` on deploy.
3. New environment keys: `LOG_FORMAT`, `BACKUP_*`, `HEALTH_TOKEN`, `HEALTH_ALLOWED_IPS`, `TRUSTED_PROXIES` (now honoured under `config:cache`), `DB_QUEUE_RETRY_AFTER`, `DB_QUEUE_LONG_RETRY_AFTER`, `QUEUE_TENANT_PACE_PER_MINUTE`.
4. Scheduler: heartbeat, `backup:run`, `reports:prune-exports`, `accounting:verify-totals`.

### Stopped at the stage boundary
Not started: R-57…R-65 follow-ups, and earlier follow-ups (R-20…R-56).

## Final release audit (complete — release status below)

### Release status
**Ready for a controlled pilot, conditionally** (conditions C-1…C-9 below). **Not** supported by the evidence for a broader release. No claim is made of zero defects, regulatory compliance or certification, payment-provider approval or production security certification.

### What was done
| Part of the brief | Result | Evidence |
|---|---|---|
| Fresh install from a clean database and clean application state | Done: release bundle → new directory, `composer install --no-dev` from the lockfile, empty MariaDB, four least-privilege accounts, production `.env`, cached config/routes/views, HTTPS, workers per lane, scheduler | TEST_BASELINE R.1; D-103 |
| Schema, constraints, reference seed, first platform administrator | 215 migrations; production seed = reference data only (now including notification types/templates, D-108); demo seeders refuse; Super Admin created without any default password (D-104) | ProductionSeedTest; PlatformAndOrganizationSettingsTest |
| No default production passwords, customer data, secrets, logs or live credentials | None in the repository or the release archives (checked when packaging); simulator secrets and audit passwords stay outside the repository | packaging check, D-104 |
| Production assets; route/config/view caching | No build step needed (plain `public/` assets; `npm run build` unused and offline-incompatible); all three caches built and used throughout | installation.md |
| Scheduler and worker operation | Ran throughout; three scheduled commands that never worked without a tenant fixed (D-105); readiness shows the heartbeat | ScheduledCommandsTest |
| Installation independent of development state | installation.md followed on the clean directory; two documentation gaps fixed (restore under cached config, D-113; backups must be configured before go-live — `ops:check` warns) | TEST_BASELINE R.5, R.7 |
| Complete customer journey | Every step exercised in Chromium; results per step | RELEASE_REPORT §3; FEATURE_PRESERVATION_MATRIX §15 |
| Defects fixed and checks rerun | 21 application defects fixed, each with a regression test except D-113 (restore account under cached configuration — verified by running the drill on the clean installation; the automated Operations suite connects with a privileged test account), redeployed and the step repeated | D-104…D-116; commits `88be172`…`ae047dc` |
| Automated suites | Architecture, Unit+Feature, Concurrency, Operations on the final code | TEST_BASELINE R.2 |
| Isolation across access surfaces | Suites + cross-tenant sweep of every parameterised admin route (one 500 found and fixed; no data exposure) | TEST_BASELINE R.4; D-110 |
| Performance benchmarks, tenant restore evidence | Latency smoke test on the clean installation; Stage 9 load results remain the capacity evidence; restore drill with the documented accounts passed (25.2 s) | TEST_BASELINE R.5, R.6 |
| Dependency/security checks available | `npm audit` 0 after fixing dev-only advisories (D-116); `composer audit` unavailable (network) | TEST_BASELINE R.7 |
| Deliverables | Source, bundle and installable archive; installation/deployment guides (docs/operations); platform and SACCO administrator guides, configuration and permissions matrix, release report (docs/release); MODULE_MAP; completed matrix | docs/release/ |

### Conditions for the controlled pilot (C) — outside the application or requiring real infrastructure
| ID | Condition |
|---|---|
| C-1 | **Payments.** Either run with `BILLING_MODE=disabled` and create pilot SACCOs manually, or complete the provider's sandbox UAT (docs/payments/sandbox-uat-checklist.md) with real sandbox credentials and obtain the provider's approval (merchant account, card tokenization and recurring charges) before `live`. Set `BILLING_FLUTTERWAVE_ACCOUNT_ID`. Never `demo` in production. Member-side mobile-money/card integrations likewise need each provider's sandbox UAT before use with real money |
| C-2 | **Regulation.** Professional legal review of the pack(s) applied to the pilot SACCOs (R-20) and a recorded determination for each SACCO by the platform's regulatory administrator; the SACCO board adopts it |
| C-3 | **Infrastructure.** TLS edge with publicly trusted certificates, DNS for the platform and subdomains, supervisor-managed workers per lane, one scheduler, opcache with `validate_timestamps=0`, log shipping, monitoring and alerts (docs/operations); `ops:check` all OK |
| C-4 | **Backups.** `BACKUP_*` configured, keys escrowed with `APP_KEY`, offsite immutable copies, a restore drill on the production stack before the first SACCO goes live and monthly after |
| C-5 | **Capacity.** A load test on the production hardware at the pilot's expected volume (Stage 9 peak targets were not met on the test VM) |
| C-6 | **Security review.** At least a review of authentication, tenant isolation and payment flows by someone independent of this implementation before real money moves; a full penetration test before a broader release |
| C-7 | **PHP dependency audit** (`composer audit`) from an environment with access to Packagist, in CI for every release |
| C-8 | **Pilot operating rules.** Each pilot SACCO has at least two administrators or an administrator and an HR officer (maker–checker on HR verification, collateral, prudential returns); all staff who approve, disburse or post enrol two-step verification (it is enforced only for administrators); savings interest, penalties, write-offs and loan-loss provisioning are posted by the accountant as manual journals (not automated, R-04) |
| C-9 | **Custom domains and SMS** are used only after they are verified on the real edge and with the SMS gateway's sandbox |

### Limitations still open after the audit (new or restated)
| ID | Limitation | Next step |
|---|---|---|
| R-66 | Payment integration verified only against a local simulator and the contract double; no sandbox or live provider call was possible here | C-1 |
| R-67 | Custom-domain DNS, certificate issuance and HTTPS on public domains unverified | C-9; staging with the real edge |
| R-68 | `composer audit` not run | C-7 |
| R-69 | Two-step verification is mandatory only for administrators; there is no SACCO setting to require it for other staff | Product decision; until then C-8 |
| R-70 | Subscription time transitions in the browser journey were driven by moving dates in the database; real elapsed-time behaviour relies on the lifecycle tests (`SubscriptionLifecycleTest`, travel in time) | Observe the first real renewals in the pilot |
| R-71 | Rendered public pages may show pre-release rendering for up to 30 minutes after a release (page cache TTL; the key has no release component) | Add the release id to the page-cache key, or flush on deploy |
| R-72 | The teller's own workflow after HR verification was not repeated in the browser (the credit-committee member's was); payroll, elections, meetings, events, campaigns, group savings and dividends were not part of this journey (Stage 8 crawls and workflow tests cover them) | Pilot UAT |
| R-58 | (resolved by D-108: notices are now generated on a production install; their queue wait under campaigns is still unmeasured) | — |
| R-64 | (resolved by D-113: drill run with the documented restore account) | — |
| R-35 | (resolved by D-114) | — |
| R-08 | (resolved by D-105: platform root leads to pricing) | — |
| Earlier | R-01…R-03, R-06, R-07, R-09…R-34 (except R-08), R-36…R-57, R-59…R-63, R-65 remain as recorded in the stage sections above; the most material for a pilot are R-04/R-14 (money arithmetic and unautomated postings), R-07 (CSP `unsafe-inline`), R-10 (in-house HTML sanitizer, no third-party review), R-13 (TOTP only), R-20 (legal review), R-54 (Kiswahili review), R-57 (capacity), R-59 (no point-in-time recovery) | as listed |

### Test results (final code)
Architecture 9/9; Unit+Feature **1 842 passed, 0 failed, 0 skipped** (24 244 assertions, commit `ae047dc`); Concurrency 17/17; Operations 5/5; Performance 4 opt-in (skipped). First run (commit `3ec3ba4`, before the D-117 test corrections): 1 838/1 840; repeat on `0197eb4`: 1 840/1 840; final on `ae047dc` (two more tests): 1 842/1 842. Details: TEST_BASELINE → Release audit.

### Stopped at the release boundary
No further work started. The audit's browser scripts, simulator and installation stay outside the repository (they hold synthetic passwords).
