# Phase 9 Execution Plan: Boundary Enforcement and Modular Governance

## 1. Purpose

Phase 9 makes the modular architecture enforceable.

By this point, the project has plans for:

```text
Phase 1: SchoolContext
Phase 2: Core contracts
Phase 3: Finance
Phase 4: Attendance
Phase 5: Student lifecycle
Phase 6: Communication
Phase 7: Reporting
Phase 8: Controller/API cleanup
```

Phase 9 exists because architecture that is not enforced is just a poster. A very pretty poster, probably next to a codebase cheerfully importing whatever it wants.

The goal is to prevent regression into:

```text
SchoolCore importing IslamicSundaySchool
controllers doing business logic
services reading Request/auth directly
finance calculations duplicated in reports
attendance scans double-counting
communication sends bypassing preview
student identifiers generated unsafely
extension concepts leaking into global contracts
```

This phase adds architecture tests, static analysis rules, CI checks, module ownership, dependency maps, deprecation enforcement, documentation checks, and review gates.

---

## 2. Core Rule

The architecture must be mechanically enforced.

Humans reviewing pull requests are useful, but tired humans miss things. CI should catch forbidden dependencies and unsafe patterns before they enter the main branch.

Core boundary:

```text
App\Domain\IslamicSundaySchool
        ↓ may depend on
App\Domain\SchoolCore
        ↓ may depend on
App\Domain\SchoolCore\Shared
```

Forbidden:

```text
App\Domain\SchoolCore -> App\Domain\IslamicSundaySchool
App\Domain\SchoolCore -> Http\Request
App\Domain\SchoolCore -> controllers
App\Domain\SchoolCore -> auth()
App\Domain\SchoolCore -> request()
App\Domain\SchoolCore -> tenant-specific vocabulary
```

---

## 3. Boundary Enforcement Layers

Use multiple layers. One check will miss things. Software is sneaky, mostly because humans write it.

Required enforcement layers:

```text
1. Architecture tests
2. Static analysis
3. CI dependency checks
4. Route inventory diff
5. Controller complexity checks
6. Forbidden vocabulary checks
7. Module ownership review
8. Deprecation tracking
9. Documentation coverage checks
10. Release readiness gates
```

---

## 4. Target Tooling

Recommended Laravel/PHP-compatible tooling:

```text
PHPUnit or Pest for architecture tests
PHPStan or Psalm for static analysis
Laravel Pint or PHP-CS-Fixer for formatting
Rector for automated refactors, optional
Composer scripts for local checks
GitHub Actions/GitLab CI for pipeline enforcement
OpenAPI validation tool
Custom PHP scripts for route/controller/module scans
```

Do not rely on one magic tool. That is how teams discover “coverage” covered everything except the bug.

---

## 5. Architecture Test Categories

Create an architecture test suite:

```text
tests/Architecture/
  ModuleBoundaryTest.php
  ControllerBoundaryTest.php
  ServiceBoundaryTest.php
  FinanceBoundaryTest.php
  AttendanceBoundaryTest.php
  StudentBoundaryTest.php
  CommunicationBoundaryTest.php
  ReportingBoundaryTest.php
  IslamicSundaySchoolBoundaryTest.php
  RouteInventoryTest.php
  DeprecationPolicyTest.php
```

These tests should run in CI on every pull request.

---

## 6. Module Boundary Rules

### 6.1 SchoolCore must not depend on IslamicSundaySchool

Rule:

```text
No file under app/Domain/SchoolCore may import or reference:
App\Domain\IslamicSundaySchool
```

Test:

```php
public function test_school_core_does_not_depend_on_islamic_sunday_school(): void
{
    $this->assertNamespaceDoesNotReference(
        base_path('app/Domain/SchoolCore'),
        'App\\Domain\\IslamicSundaySchool'
    );
}
```

### 6.2 IslamicSundaySchool may depend on SchoolCore

Allowed:

```text
IslamicSundaySchool -> SchoolCore contracts
IslamicSundaySchool -> Shared value objects
IslamicSundaySchool -> extension service providers
```

Forbidden:

```text
IslamicSundaySchool -> SchoolCore concrete services when contract exists
IslamicSundaySchool -> direct mutation of core tables outside contracts
```

### 6.3 SchoolCore contracts must be neutral

Forbidden vocabulary in `SchoolCore` contracts:

```text
Islamic
Quran
Qur'an
ArabicLevel
Halaqa
Masjid
Imam
Sadaqah
Zakat
SundaySchool
IslamicSundaySchool
```

Allowed in Islamic extension only:

```text
App\Domain\IslamicSundaySchool\*
```

Exception:

```text
Documentation comments explaining forbidden examples may exist only in docs, not executable contracts.
```

---

## 7. Controller Boundary Rules

Controllers must be HTTP adapters.

Forbidden in canonical controllers:

```text
DB::table
Model::query()->update for domain mutation
Validator::make
Mail::
Notification::send directly
SMS provider calls
WhatsApp provider calls
response()->download for finance files
Student::max('id')
Invoice balance calculation
Attendance status calculation
Report SQL building
Recipient send loops
```

Allowed:

```text
FormRequest
Resource
SchoolContext
domain contract injection
policy authorization
response helper
```

Architecture checks:

```text
- mutation routes use FormRequest
- controllers do not call provider SDKs
- controllers do not perform domain DB writes
- controllers do not exceed size threshold without exception
- ScannerController has no domain private methods
```

Suggested thresholds:

```text
controller class max 250 lines
controller action max 40 lines
private methods in controllers discouraged
```

Threshold violations should warn first, then fail after migration deadline.

---

## 8. Service Boundary Rules

Domain services must not read HTTP/global state directly.

Forbidden in `App\Domain\SchoolCore` and `App\Domain\IslamicSundaySchool` services:

```text
request()
auth()
session()
$_GET
$_POST
$_SERVER
Illuminate\Http\Request
```

Allowed:

```text
SchoolContext
DTOs
Contracts
Repositories
Policies
Domain exceptions
```

Reason:

```text
Services should be callable from controllers, jobs, CLI commands, scheduled tasks, and tests.
```

If a service requires HTTP state, it is not a domain service. It is a controller wearing a fake badge.

---

## 9. SchoolContext Enforcement

Every modular service method must accept `SchoolContext` or receive it through a clearly defined application-layer context object.

Required checks:

```text
Finance services require SchoolContext
Attendance services require SchoolContext
Student services require SchoolContext
Communication services require SchoolContext
Reporting services require SchoolContext
IslamicSundaySchool extension services require SchoolContext
```

Forbidden:

```text
Service resolving school_id from auth()->user()
Service reading school_id from request()
Service querying without school_id scope
```

Architecture test examples:

```text
- public methods in SchoolCore\Services must include SchoolContext parameter unless explicitly exempted
- repositories must have school-scoped query methods
- report read models must require SchoolContext
```

---

## 10. Finance Enforcement Rules

Finance is high-risk. The rules should be strict.

Forbidden:

```text
float casts in SchoolCore\Finance
payment file download by filename only
invoice balance calculation outside BalanceCalculator/read model
payment mutation outside PaymentServiceContract
refund mutation outside RefundServiceContract
finance file access outside FinanceFileServiceContract
silent payment deletion
finance mutation without audit log
finance mutation without transaction
```

Required checks:

```text
- no `(float)` in finance module
- no `floatval()` in finance module
- no `response()->download()` in finance controllers for payment files
- payment routes use payment ID for files
- payment edit path uses transaction/lock
- finance reports do not calculate balances directly
```

Suggested static scan patterns:

```text
app/Domain/SchoolCore/Finance contains "(float)"
app/Domain/SchoolCore/Finance contains "floatval("
app/Http/Controllers contains "serveCheckFile($filename"
app/Http/Controllers contains "response()->download" near payment
```

---

## 11. Attendance Enforcement Rules

Forbidden:

```text
attendance mutation in controllers
badge lookup in controllers
late/present status calculation in controllers
scanner duplicate detection outside ScannerService/Idempotency service
raw scan log counting as attendance result in reports
manual override without reason
```

Required checks:

```text
- ScannerController delegates to ScannerServiceContract
- StudentAttendanceService/StaffAttendanceService own mutation
- AttendanceStatusPolicyContract owns status rules
- AttendanceSessionResolverContract owns session resolution
- duplicate scan tests exist
```

Forbidden vocabulary in core attendance contracts:

```text
halaqa
masjid
Quran
Islamic studies
```

Those belong in `IslamicSundaySchool\Attendance`.

---

## 12. Student Lifecycle Enforcement Rules

Forbidden:

```text
max(id) + 1 student identifier generation
student identifier generation in controller
guardian link mutation outside GuardianService
enrollment mutation outside EnrollmentService
assignment mutation outside AssignmentService
promotion logic outside PromotionService/PromotionPolicy
Islamic-specific fields in core Student model/service contracts
```

Required checks:

```text
- no `max('id')` near student creation
- unique student identifier constraint exists
- StudentServiceContract owns student creation
- status transitions use lifecycle state machine
- Islamic profile lives in extension namespace/table
```

Forbidden vocabulary in SchoolCore student contracts/models:

```text
quran_level
arabic_level
halaqa
masjid_family
imam_note
sadaqah
zakat
```

Allowed in Islamic extension.

---

## 13. Communication Enforcement Rules

Forbidden:

```text
bulk send without preview
recipient loops in controllers
Mail:: in controllers
SMS/WhatsApp provider SDK calls outside channel adapters
recipient query logic in controllers
send without idempotency for canonical endpoint
preference bypass without audit
```

Required checks:

```text
- bulk send route requires preview_id
- CommunicationServiceContract owns send orchestration
- RecipientPreviewServiceContract owns preview
- RecipientResolverContract owns audience resolution
- channel adapters isolate providers
- delivery attempts logged
```

Islamic extension communication resolvers may exist only under:

```text
App\Domain\IslamicSundaySchool\Communication
```

---

## 14. Reporting Enforcement Rules

Forbidden:

```text
report SQL in controllers
finance balance calculation in reports
attendance duplicate scan counting in reports
export without audit
scheduled report without recipient authorization
cache key without school_id and permission scope
Islamic report classes registered from SchoolCore provider
```

Required checks:

```text
- ReportRunnerContract owns report execution
- ReportExportServiceContract owns export
- reports use read models
- exports log audit event
- Islamic reports register through IslamicSundaySchool provider
```

Reporting must not become a second implementation of the app. It is a mirror, not an alternate universe.

---

## 15. Islamic Sunday School Extension Enforcement

The extension must remain isolated.

Allowed extension concepts:

```text
Qur'an level
Arabic level
Islamic studies track
halaqa/group
masjid family/community profile
volunteer/program team
imam/admin sensitive notes
Sunday program session
sadaqah/zakat-supported scholarship classification, if applicable
```

Allowed locations:

```text
app/Domain/IslamicSundaySchool
app/Http/Controllers/Api/IslamicSundaySchool
app/Http/Resources/IslamicSundaySchool
app/Http/Requests/IslamicSundaySchool
database migrations for extension tables
docs/islamic-sunday-school
```

Forbidden locations:

```text
app/Domain/SchoolCore contracts
app/Domain/SchoolCore services
core controller routes
core Resources always returned for every school
core database fields unless neutralized as generic metadata/profile extension
```

Required checks:

```text
- Islamic extension routes require islamic_sunday_school domain profile
- Islamic extension providers register extension policies/resolvers/reports
- SchoolCore does not import IslamicSundaySchool
- extension sensitive fields require explicit permission
```

---

## 16. Route Inventory Enforcement

The route inventory created in Phase 8 must become a CI artifact.

Required route inventory fields:

```text
method
uri
name
controller
action
middleware
module
canonical_status
permission
request_class
resource_class
domain_contract
risk_level
deprecated
replacement_route
```

CI checks:

```text
- every new route appears in inventory
- every mutation route has auth/context middleware or documented exception
- every high-risk route has permission
- deprecated routes have replacement route
- extension routes have domain profile middleware
```

Recommended command:

```bash
php artisan app:route-inventory --format=json > storage/app/generated/api-route-inventory.json
```

Compare diff in CI.

---

## 17. Deprecation Enforcement

Legacy methods/routes/classes must not linger forever, which is apparently shocking news to legacy code.

Deprecation metadata required:

```text
deprecated: true
replacement_route
replacement_class
sunset_date
owner
removal_ticket
compatibility_notes
```

Deprecation checks:

```text
- deprecated route without replacement fails
- deprecated route past sunset date fails or warns loudly
- adapter controller with domain logic fails
- remove-candidate controller with active route fails
```

Deprecation header standard:

```text
Deprecation: true
Sunset: 2027-01-01
Link: </api/v2/replacement>; rel="successor-version"
```

---

## 18. Module Ownership

Each module must have an owner and review requirements.

Suggested ownership map:

```text
SchoolContext: Platform owner
Core Contracts: Platform owner
Finance: Finance domain owner + platform reviewer
Attendance: Attendance domain owner + platform reviewer
Students: Student lifecycle owner + platform reviewer
Communication: Communication owner + platform reviewer
Reporting: Reporting owner + data/security reviewer
IslamicSundaySchool: Islamic Sunday School domain owner + platform reviewer
API/Controllers: API owner + module owner
Security/Auth: Security owner
```

Every pull request touching a module should require review from:

```text
module owner
platform owner if boundary changed
security owner if permissions/sensitive data changed
finance owner if money changed
data/reporting owner if exports changed
```

---

## 19. Pull Request Checklist

Every PR must answer:

```text
Does this change touch SchoolCore?
Does this change touch IslamicSundaySchool?
Does this introduce a new route?
Does this introduce a new dependency direction?
Does this add a new report/export?
Does this mutate finance, attendance, student lifecycle, communication, or permissions?
Does this expose sensitive data?
Does this require SchoolContext?
Does this need an architecture test update?
Does this deprecate or replace anything?
```

Required PR checklist:

```md
- [ ] SchoolContext is used where required.
- [ ] No SchoolCore dependency on IslamicSundaySchool.
- [ ] Controllers remain thin.
- [ ] FormRequest validates input.
- [ ] Resource controls output.
- [ ] Authorization is tested.
- [ ] Wrong-school access is tested.
- [ ] Sensitive fields are protected.
- [ ] New route appears in route inventory.
- [ ] New report/export is audited.
- [ ] Module owner reviewed.
```

---

## 20. CI Pipeline

Recommended CI stages:

```text
1. composer validate
2. install dependencies
3. lint/format check
4. static analysis
5. unit tests
6. feature tests
7. architecture tests
8. route inventory check
9. OpenAPI/docs coverage check
10. migration check
11. security-sensitive pattern scan
```

Example composer scripts:

```json
{
  "scripts": {
    "test": "php artisan test",
    "test:architecture": "php artisan test tests/Architecture",
    "analyse": "phpstan analyse",
    "route:inventory": "php artisan app:route-inventory --format=json",
    "openapi:validate": "php artisan app:openapi-validate",
    "architecture:scan": "php artisan app:architecture-scan"
  }
}
```

---

## 21. Static Pattern Scanner

Create a custom scanner for project-specific rules.

Command:

```bash
php artisan app:architecture-scan
```

Scanner should detect:

```text
forbidden imports
forbidden function calls
forbidden vocabulary in core
controller DB mutations
provider SDK calls in controllers
finance float usage
bulk send without preview
report export without audit
extension route missing domain middleware
```

Output format:

```text
file
line
rule_id
severity
message
suggested_fix
```

Severity levels:

```text
error
warning
info
```

---

## 22. Architecture Rule IDs

Use stable rule IDs so violations are searchable.

Suggested rule IDs:

```text
ARCH-001 SchoolCore must not import IslamicSundaySchool
ARCH-002 Domain services must not use Request/auth/request()
ARCH-003 Controllers must not perform domain DB mutation
ARCH-004 Controllers must not call external providers directly
ARCH-005 Core contracts must not contain extension vocabulary
CTX-001 Modular service methods must require SchoolContext
FIN-001 Finance module must not use float math
FIN-002 Payment files must not be served by filename-only route
FIN-003 Finance mutation must be transactional/audited
ATT-001 Scanner writes must go through ScannerService
ATT-002 Attendance status must go through policy
ATT-003 Duplicate scans must use idempotency
STU-001 Student identifier must not use max(id)+1
STU-002 Student lifecycle mutations must use services
COM-001 Bulk sends must require preview
COM-002 Provider SDK calls must stay in channel adapters
REP-001 Report exports must be audited
REP-002 Reports must use read models/domain truth
API-001 Mutation routes must use FormRequest
API-002 Canonical responses must use Resource/response helper
EXT-001 Islamic extension routes require domain profile middleware
DEP-001 Deprecated routes require replacement and sunset
```

---

## 23. Documentation Enforcement

Documentation must stay connected to code.

Required docs:

```text
docs/architecture/module-boundaries.md
docs/architecture/dependency-map.md
docs/api/api-route-inventory.md
docs/api/openapi.yaml or openapi.json
docs/deprecations.md
docs/modules/finance.md
docs/modules/attendance.md
docs/modules/students.md
docs/modules/communication.md
docs/modules/reporting.md
docs/modules/islamic-sunday-school.md
```

Docs checks:

```text
- every canonical route appears in OpenAPI
- every deprecated route appears in docs/deprecations.md
- every module has owner listed
- every extension report/route documents required domain profile
```

Docs are not sacred scrolls. They are executable expectations where possible. Otherwise they become fiction with headings.

---

## 24. Dependency Map

Generate a module dependency map.

Suggested output:

```text
docs/architecture/dependency-map.md
storage/app/generated/dependency-map.json
```

Required sections:

```text
SchoolCore modules
IslamicSundaySchool modules
HTTP controllers
Providers
Contracts
Forbidden dependency violations
```

Example acceptable graph:

```text
Http\Controllers\Api\Finance
  -> SchoolCore\Finance\Contracts

IslamicSundaySchool\Reporting
  -> SchoolCore\Reporting\Contracts
  -> SchoolCore\Students\Contracts
  -> SchoolCore\Attendance\Contracts
```

Unacceptable graph:

```text
SchoolCore\Students
  -> IslamicSundaySchool\Students
```

---

## 25. Release Gates

Before each release, require:

```text
architecture tests passing
route inventory updated
OpenAPI updated
deprecation list updated
no critical scanner violations
no high-risk route without permission
no finance mutation without tests
no report export without audit
no bulk send without preview
no extension route missing domain profile
```

Release checklist:

```md
- [ ] Architecture tests pass.
- [ ] Static analysis passes.
- [ ] Route inventory diff reviewed.
- [ ] OpenAPI updated.
- [ ] Deprecated endpoints documented.
- [ ] Security-sensitive changes reviewed.
- [ ] Cross-school access tests pass.
- [ ] Extension boundary tests pass.
```

---

## 26. Migration Strategy

### 26.1 Start in warning mode

Initial rollout should produce warnings for some rules, because the existing app may violate them.

Recommended modes:

```text
Phase 9A: Scan-only mode
Phase 9B: Warning mode in CI
Phase 9C: Error mode for new/changed files
Phase 9D: Error mode globally
```

Do not instantly fail the whole project if legacy code already violates everything. That produces noise, rebellion, and creative disabling of CI. Humans are predictable like that.

### 26.2 New code must be clean

Even while legacy violations exist:

```text
new files must satisfy all rules
changed files must not introduce new violations
high-risk modules must fail immediately on critical rules
```

Critical rules fail immediately:

```text
SchoolCore importing IslamicSundaySchool
bulk send without preview
payment file filename route
student max(id)+1 identifier generation
controller calling payment provider/SMS/WhatsApp directly
report export without authorization/audit
wrong-school access test missing for high-risk route
```

---

## 27. First Implementation Slice: Architecture Test Scaffold

### Objective

Create architecture test infrastructure.

### Tasks

```text
GOV-001. Create tests/Architecture directory.
GOV-002. Add helper to scan PHP files for imports/references.
GOV-003. Add ModuleBoundaryTest.
GOV-004. Add ControllerBoundaryTest.
GOV-005. Add initial CI job for architecture tests.
```

### Required tests

```text
- SchoolCore does not import IslamicSundaySchool
- domain services do not import Request
- controllers do not call provider SDKs
```

### Done when

```text
- architecture tests run in CI
- violations produce readable messages
```

---

## 28. Second Implementation Slice: Static Pattern Scanner

### Objective

Create custom scanner for project-specific architectural rules.

### Tasks

```text
GOV-006. Create artisan command app:architecture-scan.
GOV-007. Add rule registry.
GOV-008. Add file scanner.
GOV-009. Add JSON and console output.
GOV-010. Add CI integration in warning mode.
```

### Required checks

```text
- detects forbidden imports
- detects forbidden vocabulary in SchoolCore
- detects controller DB/provider calls
- detects finance float usage
```

### Done when

```text
- scanner can run locally and in CI
- warnings are actionable
```

---

## 29. Third Implementation Slice: SchoolContext Rule Enforcement

### Objective

Ensure modular services require context.

### Tasks

```text
GOV-011. Add CTX-001 rule.
GOV-012. Scan public service methods.
GOV-013. Add allowed exemption list.
GOV-014. Fail new services without SchoolContext.
```

### Required tests/checks

```text
- Finance service method without context is flagged
- Attendance service method without context is flagged
- Reporting read model without context is flagged
```

### Done when

```text
- new modular services cannot ignore SchoolContext
```

---

## 30. Fourth Implementation Slice: Route Inventory CI

### Objective

Make route inventory a controlled artifact.

### Tasks

```text
GOV-015. Add route inventory command if not already present.
GOV-016. Store baseline inventory.
GOV-017. Add CI diff check.
GOV-018. Require metadata for new routes.
GOV-019. Flag mutation routes without auth/context.
```

### Required checks

```text
- new route without module fails
- new mutation route without auth fails
- extension route without domain profile middleware fails
```

### Done when

```text
- route changes are reviewed intentionally
```

---

## 31. Fifth Implementation Slice: Module Ownership and PR Checks

### Objective

Create human governance that complements CI.

### Tasks

```text
GOV-020. Create module ownership file.
GOV-021. Add PR checklist template.
GOV-022. Add CODEOWNERS entries.
GOV-023. Define high-risk review requirements.
```

Suggested file:

```text
.github/CODEOWNERS
docs/architecture/module-ownership.md
.github/pull_request_template.md
```

### Required checks

```text
- finance changes request finance owner
- extension changes request Islamic Sunday School owner
- security-sensitive changes request security owner
```

### Done when

```text
- ownership is explicit
- PRs include architecture questions
```

---

## 32. Sixth Implementation Slice: Deprecation Enforcement

### Objective

Prevent legacy adapters from becoming permanent architecture furniture.

### Tasks

```text
GOV-024. Create docs/deprecations.md.
GOV-025. Add deprecation metadata schema.
GOV-026. Add deprecation scan.
GOV-027. Add CI warning for expired sunset dates.
GOV-028. Add route response deprecation headers for deprecated routes.
```

### Required checks

```text
- deprecated route has replacement
- deprecated route has sunset date
- remove-candidate route is not active
```

### Done when

```text
- deprecation is visible and time-bound
```

---

## 33. Seventh Implementation Slice: Documentation Coverage

### Objective

Keep docs aligned with routes/modules.

### Tasks

```text
GOV-029. Add OpenAPI coverage check.
GOV-030. Add module docs coverage check.
GOV-031. Add route-to-doc mapping check.
GOV-032. Add docs generation step to CI.
```

### Required checks

```text
- every canonical route is documented
- every module has owner docs
- every extension route documents domain profile
```

### Done when

```text
- docs cannot drift silently from API behavior
```

---

## 34. Eighth Implementation Slice: Release Gate

### Objective

Create release readiness checklist and automated gate.

### Tasks

```text
GOV-033. Create release checklist.
GOV-034. Add release CI workflow.
GOV-035. Add high-risk violation summary.
GOV-036. Require route inventory and OpenAPI artifacts.
```

### Required checks

```text
- architecture tests pass
- static analysis passes
- no critical architecture scan violations
- route inventory current
- OpenAPI current
```

### Done when

```text
- release cannot ignore boundary violations
```

---

## 35. Implementation Tickets

## GOV-001: Create architecture test scaffold

### Description

Create architecture test directory, helpers, and initial boundary tests.

### Acceptance Criteria

```text
- tests/Architecture exists.
- ModuleBoundaryTest exists.
- ControllerBoundaryTest exists.
- CI runs architecture tests.
```

---

## GOV-002: Enforce SchoolCore to IslamicSundaySchool dependency rule

### Description

Add rule preventing SchoolCore from importing IslamicSundaySchool.

### Acceptance Criteria

```text
- SchoolCore import violation fails test.
- IslamicSundaySchool may import SchoolCore contracts.
- Error message includes file path and import.
```

---

## GOV-003: Enforce domain service HTTP isolation

### Description

Prevent domain services from using Request/auth/request/session directly.

### Acceptance Criteria

```text
- Request imports in domain services fail.
- auth() in domain services fails.
- request() in domain services fails.
- Exemptions require explicit allowlist entry.
```

---

## GOV-004: Enforce controller boundary rules

### Description

Prevent controllers from performing domain mutations or calling external providers directly.

### Acceptance Criteria

```text
- DB mutation in controller is flagged.
- Mail/SMS/WhatsApp provider call in controller is flagged.
- payment file response()->download in controller is flagged unless allowlisted.
```

---

## GOV-005: Enforce SchoolContext usage

### Description

Add static/architecture checks requiring context in modular services.

### Acceptance Criteria

```text
- Finance/Attendance/Students/Communication/Reporting service methods without SchoolContext are flagged.
- Allowed exemptions are documented.
```

---

## GOV-006: Add finance boundary rules

### Description

Add finance-specific architecture/static checks.

### Acceptance Criteria

```text
- Float usage in finance is flagged.
- Filename-only payment file routes are flagged.
- Balance calculation outside allowed services is flagged where detectable.
```

---

## GOV-007: Add attendance boundary rules

### Description

Add attendance/scanner-specific checks.

### Acceptance Criteria

```text
- Scanner controller domain logic is flagged.
- Attendance mutation in controller is flagged.
- Manual override route without reason validation is flagged where detectable.
```

---

## GOV-008: Add student lifecycle boundary rules

### Description

Add student lifecycle-specific checks.

### Acceptance Criteria

```text
- max(id)+1 student identifier generation is flagged.
- Controller identifier generation is flagged.
- Core student vocabulary leak is flagged.
```

---

## GOV-009: Add communication boundary rules

### Description

Add communication-specific checks.

### Acceptance Criteria

```text
- Bulk send without preview_id is flagged where detectable.
- Provider SDK calls outside channel adapters are flagged.
- Recipient loops in controllers are flagged.
```

---

## GOV-010: Add reporting boundary rules

### Description

Add reporting-specific checks.

### Acceptance Criteria

```text
- Report export without audit path is flagged where detectable.
- Report SQL in controller is flagged.
- Islamic reports registered from SchoolCore provider are flagged.
```

---

## GOV-011: Add route inventory CI check

### Description

Ensure routes are inventoried and reviewed.

### Acceptance Criteria

```text
- Route inventory generated in CI.
- New route without metadata fails or warns based on rollout mode.
- Extension route without domain middleware fails.
```

---

## GOV-012: Add module ownership and PR checklist

### Description

Create CODEOWNERS, module ownership doc, and pull request template.

### Acceptance Criteria

```text
- Module ownership document exists.
- CODEOWNERS maps high-risk modules.
- PR template includes boundary questions.
```

---

## GOV-013: Add deprecation enforcement

### Description

Track and enforce deprecated routes/controllers/classes.

### Acceptance Criteria

```text
- Deprecated route requires replacement.
- Deprecated route requires sunset date.
- Expired deprecations produce CI warning/failure.
```

---

## GOV-014: Add documentation coverage checks

### Description

Ensure API and module docs stay current.

### Acceptance Criteria

```text
- Canonical routes must appear in OpenAPI.
- Deprecated routes must appear in deprecation docs.
- Extension routes must document domain profile requirement.
```

---

## GOV-015: Add release gate workflow

### Description

Create release gate workflow with architecture, route, docs, and static checks.

### Acceptance Criteria

```text
- Release workflow runs architecture tests.
- Release workflow checks route inventory.
- Release workflow checks OpenAPI.
- Critical violations block release.
```

---

## 36. Definition of Done for Phase 9

Phase 9 is done when:

```text
- Architecture test scaffold exists.
- SchoolCore cannot import IslamicSundaySchool.
- Domain services cannot use Request/auth/request directly.
- Controllers cannot perform forbidden domain/provider behavior without failing checks.
- Modular services require SchoolContext or documented exemption.
- Finance boundary rules exist.
- Attendance boundary rules exist.
- Student lifecycle boundary rules exist.
- Communication boundary rules exist.
- Reporting boundary rules exist.
- Islamic Sunday School extension boundary rules exist.
- Route inventory is checked in CI.
- Module ownership is documented.
- PR checklist exists.
- Deprecation enforcement exists.
- Documentation coverage checks exist.
- Release gate exists.
- Critical violations fail CI.
```

---

## 37. Non-Goals

Do not include in Phase 9:

```text
- rewriting all legacy code immediately
- replacing the entire framework
- building a full internal developer portal
- enforcing perfect architecture on untouched legacy files on day one
- moving every module into separate Composer packages immediately
- adding Kubernetes because someone got bored
```

Phase 9 is about enforceable boundaries and governance. Not architecture cosplay with extra YAML.

---

## 38. Main Risks

### Risk: too many legacy violations create noise

Mitigation:

```text
- start in scan/warning mode
- fail only new/changed files initially
- immediately fail critical security/data rules
```

### Risk: developers bypass checks

Mitigation:

```text
- make violations readable
- provide suggested fixes
- document exemptions
- require owner approval for exemptions
```

### Risk: false positives

Mitigation:

```text
- allowlist with expiration
- rule IDs
- test scanner against known safe files
```

### Risk: boundary rules block urgent fixes

Mitigation:

```text
- emergency bypass process
- required follow-up cleanup ticket
- security owner approval
```

### Risk: architecture docs drift again

Mitigation:

```text
- docs generated from route/dependency inventory where possible
- docs coverage CI
```

### Risk: Islamic extension becomes coupled to core internals

Mitigation:

```text
- extension uses contracts
- import boundary tests
- provider binding review
```

---

## 39. Immediate Next Work Queue

Start here:

```text
1. GOV-001 Create architecture test scaffold
2. GOV-002 Enforce SchoolCore to IslamicSundaySchool dependency rule
3. GOV-003 Enforce domain service HTTP isolation
4. GOV-004 Enforce controller boundary rules
5. GOV-005 Enforce SchoolContext usage
6. GOV-011 Add route inventory CI check
7. GOV-012 Add module ownership and PR checklist
8. GOV-006 Add finance boundary rules
9. GOV-007 Add attendance boundary rules
10. GOV-008 Add student lifecycle boundary rules
11. GOV-009 Add communication boundary rules
12. GOV-010 Add reporting boundary rules
13. GOV-013 Add deprecation enforcement
14. GOV-014 Add documentation coverage checks
15. GOV-015 Add release gate workflow
```

Start with import boundaries and HTTP isolation. They are cheap to detect and stop architectural rot early. The rest can tighten progressively as legacy code is cleaned.
