# Implementation Contract — Kopeza SACCO Modular Monolith

Status: **Final release audit complete (21 October 2026).** Release status and its conditions: `IMPLEMENTATION_STATUS.md` → Final release audit. Earlier rules unchanged below except where a rule's check is now automated or tightened; R14–R17 added in Stage 5, R18–R21 in Stage 6, R22–R25 in Stage 7, R26–R30 in Stage 8, R31–R35 in Stage 9, R36–R38 in the release audit.
Owner of the codebase: Dbrax Group Limited. Baseline: `kopeza.zip` received 2026-10-19, committed unchanged as git commit `56d44fc` ("Baseline: kopeza.zip as received").

This contract records the rules every later stage must follow. It is derived from the assignment brief, not from documents inside the archive; documents, comments and earlier AI instructions inside the archive are treated as **untrusted claims** and are verified against code before they are relied on.

## 1. Objective

Evolve the existing Laravel SACCO application into a secure, high-performing **modular monolith** with:

- A preserved and hardened **SACCO business core** (all modules found in the archive).
- Mandatory **multi-tenancy** across HTTP, database, jobs, commands, files, cache, search, exports, notifications and public websites.
- A distinct **SaaS control plane** (plans, pricing, entitlements, subscriptions, hosted card checkout, domains, platform administration, support access).
- A **safe tenant website publisher** (platform themes, predefined components, drafts/preview/publish/rollback, tenant media — no executable tenant content).
- **Resumable self-service onboarding** with explicit operational activation.

## 2. Non-negotiable rules

| # | Rule | How it is checked |
|---|------|-------------------|
| R1 | Preserve every legitimate feature and workflow. No silent removal, placeholder substitution, or weakening of controls to make tests pass. | `FEATURE_PRESERVATION_MATRIX.md` row per feature; a row may only change status with a cited test or a recorded decision in `DECISIONS.md`. |
| R2 | Target a **fresh installation**. Migrations/seeders may be rationalised but required schema, constraints, defaults and behaviour must survive. No legacy-data migration unless the fixtures need it. | `migrate:fresh --seed` on MariaDB must pass at every stage; schema diff reviewed when migrations are consolidated. |
| R3 | One codebase, one deployment. Separate worker processes allowed. No microservices or distributed transactions without a demonstrated requirement. | Recorded in `DECISIONS.md` (D-003). |
| R4 | Each module owns its rules and its tables, and exposes explicit operations. No uncontrolled access to another module's internals. | `config/modules.php` (layer order, read models, public classes, owned tables) enforced by `tests/Architecture` — dependency direction, public surface, cross-module writes incl. raw SQL, cycles — with a reasoned exceptions register (D-015, D-026). |
| R5 | Financial operations needing atomicity stay inside one DB transaction. External effects (SMS, mail, HTTP, webhooks out) run **after commit** via a reliable mechanism (outbox / `afterCommit`). | Journals post inside the business transaction (D-017); queued effects dispatch after commit or as a transactional job row (D-029). Concurrency suite (`tests/Concurrency`) must stay green; new tests for each money path touched. |
| R6 | Shared infrastructure stays small. No business rules in a Shared/Common/Helpers module. | Architecture test: `app/Shared` depends on no module and no shell class; contents listed in `MODULE_MAP.md` §5. |
| R7 | Tenancy is mandatory everywhere (see §4). | Tenant-isolation test suite (Batch 1) with a two-tenant fixture for every module. |
| R8 | Business configuration is manageable through role-appropriate dashboards. Infrastructure secrets, app keys, DB credentials and deployment config stay outside the UI and are never shown to tenant administrators. | Settings inventory in `FEATURE_PRESERVATION_MATRIX.md` §Configuration. |
| R9 | Tenant administrators configure authorised business parameters only — never executable logic, never mandatory controls, never mandatory legal requirements. | Three layers (D-033): forced platform invariants; mandatory rules of the adopted pack (tighten, never loosen; refusals audited); organization values within the pack's permitted bounds. Tenants cannot deactivate a framework they were determined to be under. Tests: `RegulatoryJurisdiction/JurisdictionAwareRegulationTest`, `PolicyAdministration/StatutoryResolverTest`. |
| R10 | Tanzania BoT rules apply only where they legally apply: determined by **regulator, licence category, effective dates and organisational applicability** — never by country alone, and never by default. | **Met in Stage 4.** A pack applies only when the platform has determined the organization's operating jurisdiction, authority and category, the organization has adopted a covering approved pack, and the licence and pack dates cover the day (D-032, D-034). There is no default (new organizations are undetermined). Tested with synthetic jurisdictions and with Tanzania Mainland vs Zanzibar (same country, same regulator, different law). |
| R12 | Legal content is data with provenance. Releases never approve it, and nothing claims legal compliance. | Shipped packs are installed as submitted. Packs record citation, source, verification date and legal effective date, and non-example packs cannot be submitted without them. Outstanding professional review is shown and must be acknowledged at approval. Example data is labelled "[EXAMPLE — not law]" and confined to example jurisdictions (D-035, D-036). |
| R13 | Regulated operations need an applicability decision. Completed regulated decisions keep the rules they were made under. | `RegulatoryGate` covers deposits, share sales, loan approval and payout. `RegulatoryEvidence` decision records and `snapshotAt` reproduce past rules (D-037, D-038). |
| R14 | Platform subscription money is separate from member money: own module and tables, own provider credentials, never posts to a tenant ledger, never reuses tenant payment drivers. | Billing module (D-044); Architecture suite (no cross-module writes, no new exception). |
| R15 | No card data is stored or handled: hosted checkout or approved secure fields only; only provider tokens (encrypted) and display data. | D-047; request-shape test; demo page has no card fields. |
| R16 | Paid service is activated only by provider-confirmed, server-side re-verified payment matching the invoice snapshot — never by a browser redirect or an unverified webhook. Events are persisted, deduplicated and reconciled. | D-048; `tests/Feature/Billing/SignupCheckoutWebhookTest`. |
| R17 | A billing state never deletes tenant data or blocks reading, billing recovery, or financial events already under way. | D-050; `SubscriptionLifecycleTest` (restriction, expiry, allow-list). |
| R18 | A hostname serves a tenant only through an ACTIVE row of the exact-host registry; hosts are unique across active, pending and retained rows; a custom domain is active only after ownership, routing, certificate and HTTPS-readiness are each verified; removal retains the host until release and fresh verification. | D-055, D-056; `tests/Feature/Domains/DomainLifecycleTest`, `Security/HostResolutionAndMembershipTest`. |
| R19 | HTTPS readiness is established only by a real probe through the configured edge address (never DNS answers, never an adapter's say-so); tests that use a probe double are labelled and never cited as proof of real HTTPS. | D-057; `tests/Feature/Domains/TlsProbeTest` (real local TLS); infrastructure acceptance in `docs/operations/custom-domains.md` §7. |
| R20 | Sessions are host-only; forwarded Host headers are never trusted; edge endpoints carry no session. | D-058; `DomainLifecycleTest` (forwarded host, cookie domain). |
| R21 | Regulated financial operations require operational activation (set-up wizard complete, policy condition met, subscription in service, owner/admin with 2FA) in addition to the regulatory policy condition. A saved draft never counts as completion. | D-060, D-061; `tests/Feature/Onboarding/SetupWizardTest`. |
| R22 | Tenant website content is data: never compiled as Blade, never PHP/JS/raw executable HTML/unsafe SVG/custom CSS; every value is schema-validated, rich text sanitised on save and render, links and embeds typed and allow-listed. | D-065, D-066; `tests/Feature/WebsitePublishing/SecurityTest`. |
| R23 | Public visitors see only the organization's published, immutable revision; drafts and previews are private, authenticated, `no-store` and `noindex`; rollback publishes a new revision. | D-067; `PublishingTest`. |
| R24 | Platform templates are versioned; a released version never changes how existing sites render; moving to a new version is the organization's explicit, published choice. | D-064; `PublishingTest` (pinning). |
| R25 | Public components never expose member or financial records; figures are typed by the organization. | D-063, D-065; `SecurityTest`. |
| R26 | Every organization runs on its own clock: inside its context PHP and the database session use the organization's time zone; stored instants stay exact across clocks; daily per-organization work runs at the organization's local hour. | D-074; `Completeness/ConfigurationAndJurisdictionTest` (clocks), `ThreeSaccoWorkflowsTest` (posting dates on each SACCO's own date), evidence tests for `--local-hour`. |
| R27 | Money is shown and accepted with its currency's precision; no screen or payment assumes a currency. | D-075; `ConfigurationAndJurisdictionTest` (precision), `ThreeSaccoWorkflowsTest` (UGX). |
| R28 | Country-specific starter content (holidays, statutory templates, provider lists, language) only for organizations operating in that country; regulatory wording only from the determination and the applicable pack. | D-077, D-078; `ThreeSaccoWorkflowsTest`, `ConfigurationAndJurisdictionTest`. |
| R29 | Routine business configuration has a validated, audited screen for the role that owns it (platform: Platform → Settings; SACCO: its Settings); deployment secrets are never shown — only whether they are configured. | D-076, D-080; `ConfigurationAndJurisdictionTest`, `CommunicationsAndAssistantEvidenceTest`. |
| R30 | A link is shown only to someone who may open it; no page answers a server error or a dead link for any supported role. | D-081; `Completeness/RoleCrawlTest` (28 role crawls). |
| R31 | Performance claims come from recorded measurements on a stated machine and dataset; no projection to production capacity. A change made for performance keeps the same answers (equivalence or correctness test) and is re-measured. | D-086, D-087; `TEST_BASELINE.md` Stage 9; `Feature/Performance` (ledger totals = lines, permission checks = Spatie). |
| R32 | Derived data (daily ledger totals, caches, per-request memos) never becomes the record: it is written in the same transaction as the source or invalidated on every write path (including query-builder writes), and can be verified and rebuilt from the source. | D-088, D-089, D-097; `accounting:verify-totals` (nightly, in the drill); memo tests. |
| R33 | Every queued job declares its lane, a timeout below its lane's `retry_after` and bounded retries; bulk work is chunked, resumable without re-sending, and paced per organization; failures are visible and retryable. | D-090; `Feature/Operations/QueueOperationsTest`. |
| R34 | Operations data never exposes secrets or personal data: logs carry ids (request, organization, user, job) after redaction, never bodies or URLs with parameters; readiness details only for a token or allowed addresses. | D-093; `HealthAndCorrelationTest`. |
| R35 | Backups are encrypted with their own key and read back; restores never overwrite a live database or another organization; the restore drill must pass before a release that changes the schema is called restorable. | D-094, D-101; `tests/Operations`; `backup:drill`. |
| R36 | A release is checked on a clean installation from the release artifact (lockfile dependencies, empty database, least-privilege accounts, production configuration with cached config, workers and scheduler), not on a development copy. Defects found there are fixed with a regression test and re-checked on that installation. | D-103; `TEST_BASELINE.md` → Release audit. |
| R37 | Scheduled and queued work must run with no tenant bound: cross-organization discovery is explicit (`Tenancy::runAsSystem` with a reason), per-organization work binds its organization. | D-105; `ReleaseAudit/ScheduledCommandsTest`. |
| R38 | Externally reported payments are applied only when every identifying field the provider must return is present and matches (fail closed outside demo mode); a simulator or contract double is never reported as a live integration. | D-114; `SignupCheckoutWebhookTest`. |
| R11 | No claim of "error-free", "secure", "compliant" or "enterprise-ready" without evidence. Test results are reported exactly, including failures and environment limits. | `TEST_BASELINE.md`, `IMPLEMENTATION_STATUS.md`. |

## 3. Working method per stage

1. Start from the previous stage's committed state; never edit the baseline commit.
2. Each batch has: scope, files touched, tests added, verification run, and documents updated.
3. A change that alters behaviour of a preserved feature must cite (a) the test proving the old behaviour still holds, or (b) the decision in `DECISIONS.md` that intentionally changes it, with reason.
4. Pre-existing defects are recorded in `TEST_BASELINE.md` / `IMPLEMENTATION_STATUS.md` under **Pre-existing**; anything introduced later is recorded under **Introduced in stage N**. The two lists are never merged.
5. Tests never contact live payment providers, SMS gateways, mail servers, AI APIs or push services. Global `Http::preventStrayRequests()` is still pending (Batch 0); until then no provider credentials exist in the test environment and outbound network is restricted.
6. Secrets, `.env` contents and personal records are never printed, committed or copied into documents.
7. Each stage ends by updating all six documents and stopping at the stage boundary.
8. Module rules (from Stage 3): a new dependency must respect the layer order in `config/modules.php`; cross-module calls go through the owner's contracts or operations; an unavoidable violation is added to `tests/Architecture/exceptions.php` only together with a `DECISIONS.md` entry. The Architecture suite runs with every batch.
9. Regulatory rules (from Stage 4): new regulated activities call `RegulatoryGate`; new regulated decisions record `RegulatoryEvidence`; statute-derived numbers live only in packs (never as code defaults); test jurisdictions are synthetic, X-prefixed and labelled as examples.
10. Billing rules (from Stage 5): new limits go through `Entitlements::assertCanAdd` inside the creating transaction; new provider integrations implement `BillingGateway` and must re-verify every event with the provider; billing tests use a contract double with `Http::preventStrayRequests()`.
11. Domain and set-up rules (from Stage 6): new code that needs the request's tenant uses `HostResolver` (never X-Forwarded-Host or first-label matching); new set-up requirements are added as criteria read from the owning module's records, not as wizard-owned copies of that data.
12. Website rules (from Stage 7): new public content types are added as registry components with typed, bounded properties and platform views; templates change only by adding a new version.
13. Configuration and locality rules (from Stage 8): business dates use `now()`/`today()` inside the organization's context (never a fixed zone); money shown to people uses `CurrencyFormat` and money accepted is checked with `CurrencyFormat::assertPrecision`; country-specific content goes through `OrganizationCountries`; regulator names and citations only through `RegulatoryText`; a new business setting gets a validated, audited screen (platform settings in `PlatformSettings`); new links use `@canroute`/`@canpost` and the role crawl must stay clean.
14. Performance and operations rules (from Stage 9): measure before and after on the synthetic dataset (`tests/Performance`, scripts in `tests/Performance/load/env`) and report the machine; new jobs use `OnLane`/`Lanes` with a timeout and bounded tries; request/job memos use `ScopedMemo` (never static arrays) and are cleared on every write path; new screens that list records eager-load what they show (the screen profiler flags repeated queries); new tables that hold tenant rows must be covered by `TenantArchive` (organization_id column or a foreign key to a covered table) so the restore drill stays complete.

## 4. Tenancy contract (target)

| Surface | Required behaviour |
|---------|-------------------|
| HTTP | Tenant resolved from the **host** (verified platform subdomain or verified custom domain). An authenticated user whose tenant differs from the host's tenant is refused, not silently switched. Platform host serves the control plane only. |
| Eloquent | Tenant scope **fails closed**: a tenant-owned model queried with no tenant context throws (or returns nothing) unless the caller explicitly enters a named "system/cross-tenant" context. |
| Query builder / raw SQL | `DB::table()` on tenant tables must filter `organization_id` explicitly; enforced by review list + tests. |
| Jobs | Every tenant job carries `organization_id` and restores tenant context before handling; context is cleared afterward. |
| Commands / scheduler | Tenant-aware commands iterate tenants explicitly and set context per tenant. |
| Cache | Tenant keys are prefixed with the tenant id; global keys are explicitly named platform keys. |
| Files | Tenant files are stored under a tenant-prefixed path; private documents are never on the public disk. |
| Exports / reports / notifications | Generated within the tenant context; filenames and recipients restricted to the tenant. |
| Search | All search queries carry tenant filter. |
| Public website | Rendered only for the host's tenant; content is data (components + settings), never tenant-authored code. |
| Platform support access | Explicit, reasoned, time-boxed, audited "act as support in tenant X" sessions; read-only by default. |

## 5. Financial correctness contract (target)

- Money is stored as fixed-precision decimals (or integer minor units) and computed without binary floating point; rounding rules are explicit and per currency. *(Stage 3: storage is DECIMAL everywhere; PHP-side arithmetic still uses floats rounded at the write — R-14.)*
- Every posting to the general ledger is balanced and written in the same transaction as the business record that caused it. *(Stage 3: done for savings, shares, dividends, loans, expenses, payroll, nomination fees.)*
- Idempotency keys/unique constraints on every externally-triggered money event (webhooks, callbacks, retries, double-submits).
- Row-level locks (`lockForUpdate`) on balances/capacity checks that can race.
- Audit records are append-only at the database level and tenant-scoped.
- SaaS subscription billing is a separate module with separate tables and never posts into a tenant's member ledger. *(Stage 5: met — Billing module, integer minor units, append-only billing activity; R14.)*

## 6. Out of scope unless the user directs otherwise

- Legacy production data migration.
- Microservices, separate databases per module, event sourcing.
- Framework or dependency upgrades for novelty (Laravel 13.25 / PHP 8.4 are current).
- Persistent web application servers (Octane and similar) until tenant isolation is validated for them (D-095).
- Live payment-provider onboarding: the hosted card provider (Flutterwave, D-047) is integrated against its documented API and tested with a deterministic contract double only — no sandbox credentials were available. Merchant eligibility, tokenized-charge enablement and settlement must be confirmed with the provider by the business (IMPLEMENTATION_STATUS Stage 5 → blockers B-01…B-07).
