# AI-Driven Development Compatibility Report

**Project:** qslaravel (Laravel 13 / PHP 8.3+)
**Generated:** 2026-03-09
**Last Updated:** 2026-07-18
**Assessed by:** Claude Code (claude-opus-4-8)

---

## Executive Summary

| Metric | Value |
|--------|-------|
| **Overall AI Compatibility Score** | **70 / 100** |
| **Letter Grade** | **C+** |
| **Previous Score** | **68 / 100 (C)** — assessed 2026-07-10 (post admin-wide Form Requests) |
| **Risk Level for AI-Assisted Development** | **Medium** |
| **Verdict** | Static analysis was raised from **PHPStan level 1 to level 5** — the larastan extension is wired in and a 3,064-line `phpstan-baseline.neon` grandfathers existing errors so **new code is now checked at level 5** (undefined methods, wrong argument/return types, calls on nullables). This delivers the report's Recommendation **2.4** and is the single change that pushed the codebase over the **C → C+** boundary: AI-generated code is now validated by a real static-analysis gate instead of the near-no-op level 1, and the type hints added in earlier phases are finally *enforced* rather than advisory. Everything else held flat since 2026-07-10: both remaining god classes are untouched (`BaseAuthService` still **1,459 lines**, `UserQuery` still **1,180**), and model factories (1), `declare(strict_types=1)` (1 file), interfaces (0), and CI/CD (none) are all unchanged — these are now the clear top-of-backlog items. |

---

## Category Scores

| # | Category | Previous | Current | Weight | Weighted | Status |
|---|----------|----------|---------|--------|----------|--------|
| 1 | Code Structure & Organization | 76 | 76/100 | 15% | 11.40 | Unchanged |
| 2 | Consistency & Patterns | 70 | 70/100 | 15% | 10.50 | Unchanged |
| 3 | Type Safety & Contracts | 57 | 61/100 | 20% | 12.20 | PHPStan L5 now enforces the type hints (+4) |
| 4 | Documentation & PHPDoc | 80 | 80/100 | 15% | 12.00 | Unchanged |
| 5 | Testing Infrastructure | 66 | 73/100 | 15% | 10.95 | Static analysis PHPStan level 1 → 5; +3 tests (+7) |
| 6 | Method Complexity | 46 | 46/100 | 10% | 4.60 | Untouched; BaseAuthService still 1,459 (0) |
| 7 | Navigability & Discoverability | 80 | 80/100 | 10% | 8.00 | Unchanged |
| | **TOTAL** | **68** | | **100%** | **69.65** | **+1.85** |

### Score Visualization

```
Structure & Org     ██████████████████████████████████████░░░░░░░░░░░░  76%  (unchanged)
Consistency         ███████████████████████████████████░░░░░░░░░░░░░░░  70%  (unchanged)
Type Safety         ██████████████████████████████░░░░░░░░░░░░░░░░░░░░  61%  (was 57%) ↑
Documentation       ████████████████████████████████████████░░░░░░░░░  80%  ← Strongest
Testing             ████████████████████████████████████░░░░░░░░░░░░░  73%  (was 66%) ↑
Method Complexity   ███████████████████████░░░░░░░░░░░░░░░░░░░░░░░░░░░  46%  ← Biggest gap (unchanged)
Navigability        ████████████████████████████████████████░░░░░░░░░  80%  (unchanged)
```

### Refactoring Impact (2026-07-18)

The period since 2026-07-10 was dominated by a single, focused push: **raising static analysis from PHPStan level 1 to level 5.**

- **PHPStan level 1 → 5**, with the **larastan** extension wired in (`phpstan.neon` includes `larastan/extension.neon`) and scanning both `app/` and `routes/`. Level 1 caught almost nothing; level 5 flags calls to undefined methods, wrong argument/return types, and method calls on possibly-null values — the class of mistakes AI most commonly makes.
- **A 3,064-line `phpstan-baseline.neon`** grandfathers the existing violations, so the gate is enforced on **new and changed code** without requiring the whole legacy surface to be fixed first. This is the pragmatic adoption pattern: AI-authored code is now validated at level 5 immediately.
- This delivers Recommendation **2.4** and, combined with the already-typed service/query layer, turns the earlier type-hint work from *advisory* into *enforced* — the main reason both Type Safety and Testing moved up this period.

**Not touched this period (unchanged or regressed):** `BaseAuthService` still **1,459 lines**, `UserQuery` still **1,180**, `declare(strict_types=1)` now **1 file**, 0 interfaces, **1 model factory**, no CI/CD, and Form Requests hold at 58 (55 admin + 3 outreach/deeplink). These are the unambiguous next targets.

### Refactoring Impact (2026-07-10)

The period since 2026-06-30 was dominated by a single, focused push: **admin-wide Form Request validation.**

- **Form Requests scaled 3 → 55 concrete classes** (56 incl. the shared `BaseAdminFormRequest`), organized by resource under `app/Http/Requests/Admin/` (Coupon, Voucher, Program, Chapter, Day, Article, Exercise, User, UserProgram, Auth, Synonym, TrackerContent, Language, Notification, Instruction, Image, Url, PostQuitHealth, PostQuitStage, Action, SubModule, Email, …).
- **Wired into 24 controllers** — this is real adoption replacing inline `$request->validate()` blocks, not dormant scaffolding. It delivers Recommendation **2.1** for the admin write surface.
- Each request is a discoverable, declarative input contract (typed rules + `authorize()`), which is exactly the shape AI needs to safely add or modify an admin endpoint.

**Not touched this period (unchanged or regressed):** `BaseAuthService` grew again 1,426 → **1,459 lines**, `UserQuery` still 1,180, `declare(strict_types=1)` still 2 files, 0 interfaces, **1 model factory**, PHPStan still level 1, no CI/CD. These are now the unambiguous next targets.

### Refactoring Impact (2026-06-30)

A sustained decomposition effort attacked the two headline god classes and the flat service directory:

- **FirebaseBusinessService decomposed** — the 2,619-line class with 45+ near-identical methods is now a **228-line facade** delegating to 8 domain campaign services under `app/Services/Firebase/Campaigns/`, plus dedicated notification infrastructure (`FirebaseMessenger`, `FirebaseMessageFactory`, `FirebaseInvalidTokenHandler`, `SendResult`) and processors. All 36 public `run*` signatures are preserved for backwards compatibility.
- **Marketing layer split** — `MarketingEmailService` reduced to **125 lines**; logic moved into `app/Services/Marketing/` (Campaigns, Coupon, Sendgrid, Mail, DTOs, Registry, Support).
- **Cron layer split** — `CronService` reduced to **194 lines**; domain cron services and processors now live under `app/Services/Cron/`.
- **Test suite nearly doubled** — 83 → 154 files, with `tests/Unit/Services/` mirroring the new service tree (68 service unit tests).
- **Form Requests introduced** — `StoreDeepLinkRequest`, `DispatchOutreachEmailRequest`, `ComputeOutreachSegmentRequest` (used by `DeepLinkAdminController` and `OutreachController`).
- **Registry pattern** — `FirebaseCampaignRegistry`, `MarketingCampaignRegistry`, `CronJobRegistry` replace large switch/dispatch blocks.

**Not yet done (regressed or unchanged):** `BaseAuthService` grew 1,117 → 1,426 lines, `UserQuery` grew 794 → 1,180, `declare(strict_types=1)` still in 2 files, 0 interfaces, 1 model factory, PHPStan still level 1, no CI/CD.

---

## Codebase Overview

| Metric | Previous (2026-07-10) | Current (2026-07-18) |
|--------|----------|---------|
| Total PHP Files (app/) | ~489 | **~493** (+4) |
| Models | 94 | **94** |
| Controllers | 77 (15 API + 62 Web) | **77** (15 API + 62 Web) |
| Services | 104 | **105** (+1) |
| Query Classes | 93 | **93** |
| Test Files | 157 | **160** (+3) |
| Form Requests | 58 | **58** (55 admin + 3 outreach/deeplink) |
| **PHPStan Level** | **1 / 9** | **5 / 9** (+4, larastan + baseline) |
| Middleware | 8 | **9** (+1) |
| Enums | 4 | **4** |
| Traits | 6 | **6** |
| Helpers | 6 | 6 |
| Console Commands | 14 | **14** |
| Model Factories | 1 (User only) | **1** (User only) |
| `declare(strict_types=1)` files | 2 | **1** |
| Third-Party Integrations | 10 | 10 |
| Database Connections | 4 | 4 |

### Service Decomposition Summary (2026-06-30)

The flat root-level service directory was supplemented (not replaced) with deep domain sub-namespaces:

```
app/Services/
├── Auth/           (4 files: Base, Email, Social, SSO)
├── User/           (User management/profile/activity/etc.)
├── Subscription/   (iOS, Android)
├── Firebase/       (Campaigns ×8, Notifications, Processors, Support, Registry)
├── Marketing/      (Campaigns ×7, Coupon, Sendgrid, Mail, Dto, Registry, Support)
├── Cron/           (domain cron services + Processors)
├── Apple/          (AppStoreConnectJwt)
├── Google/         (GooglePlayService)
└── 38 root-level service files (still flat)
```

---

## Category 1: Code Structure & Organization (76/100, was 75)

### What Works Well

**Clear service-oriented architecture with new domain decomposition.** Beyond the existing `Auth/`, `User/`, `Subscription/` groupings, the biggest god classes were broken into cohesive domain sub-namespaces. An AI looking for "Firebase day-unlock campaign logic" now finds `Firebase/Campaigns/DayUnlockCampaignService.php` instead of scrolling a 2,619-line file.

**God classes decomposed behind facades.** `FirebaseBusinessService` is now a 228-line facade documenting that "new code should depend on the specific campaign service rather than this facade." This preserves backwards compatibility while giving AI small, single-purpose targets.

**Registry pattern for dispatch.** `FirebaseCampaignRegistry`, `MarketingCampaignRegistry`, and `CronJobRegistry` centralize campaign/job lookup, replacing scattered conditionals.

**Form Requests now pervasive.** 55 Form Request classes (up from 3) organized by resource under `app/Http/Requests/Admin/` give AI a dense, copyable pattern for any admin endpoint — one of the strongest "find the pattern and follow it" signals in the codebase.

**Route organization remains clean.** `routes/api.php` uses consistent prefixing and middleware grouping.

### What Hurts AI Comprehension

**Query classes still live in the wrong directory.** 93 query classes sit under `app/Http/Queries/` despite having nothing to do with HTTP. An AI looking for database logic will search `app/Models/` or `app/Repositories/` first.

**38 services still flat at the root of `app/Services/`.** The decomposition added domain folders but left 38 root-level services ungrouped (notification, commerce, integration, search, core all mixed).

**No interfaces or contracts exist.** Still zero interface files. AI cannot discover method signatures through contracts — it must read concrete classes.

---

## Category 2: Consistency & Patterns (70/100, was 66)

### Resolved Since Last Assessment

**Significant code duplication eliminated.** The headline issue — `FirebaseBusinessService` with 40+ near-identical methods — is gone. Each campaign is now its own service; the long-lived-worker timestamp bug (stale `microtime` reused across queue jobs) was fixed as part of the split. **DONE** (2026-06-30).

**Registry + facade patterns standardized** across Firebase, Marketing, and Cron. **DONE** (2026-06-30).

**Form Request validation adopted admin-wide** (3 → 55 classes, 24 controllers). What was a 3-class pilot is now the standard for the admin write surface: every major resource has typed `Store`/`Update` requests behind a shared `BaseAdminFormRequest`, replacing inline controller validation. This is the largest single consistency win since the god-class decomposition and substantially closes the long-standing "validation is inline in controllers" gap for admin routes. **DONE for admin** (2026-07-10); API auth/subscription endpoints still validate inline.

### Previously Resolved (retained)

- `userJournyLog()` → `userJourneyLog()` typo fixed (2026-03-13)
- `Platform::fromString()` replaces magic strings (2026-03-13)
- `validateUserIdMatch()` consolidates ~50 copy-pasted blocks (2026-03-13)
- `SourceDataService` constructor DI in `BaseAuthService` (2026-03-26)
- `CalculatesUtcOffset` trait extracts shared UTC logic (2026-03-26)

### Remaining Naming Inconsistencies

| Pattern | Example | Location |
|---------|---------|----------|
| PascalCase method | `LanguageList()` (should be camelCase) | `ProgramService.php` |
| Numeric suffix | `getUsersList3()` (legacy remnant) | `UserQuery.php` |
| Mixed route naming | `SocialLogin` vs `getSubDetails` | `routes/api.php` |

### Error Handling Patterns

| Layer | Pattern | Consistency |
|-------|---------|-------------|
| **Services** | 5 competing patterns (try-catch, inline, early return, rollback, none) | **Inconsistent** |
| **Controllers** | Mixed delegation and inline handling | **Inconsistent** |

Still no single standardized response/error trait across the API surface.

---

## Category 3: Type Safety & Contracts (61/100, was 57)

### Key Metrics

| Metric | Previous | Current | Impact |
|--------|----------|---------|--------|
| **PHPStan level** | **1 / 9** | **5 / 9** | **Type hints now statically enforced** |
| Files with `declare(strict_types=1)` | 2 of ~489 (0.4%) | 1 of ~493 (0.2%) | Runtime coercion still not enforced |
| Interface/contract files | 0 | 0 | Still none |
| Loose comparisons (`==` / `!=`) | ~742 | ~742 | Flat |
| Typed DTO / value objects | several (`EmailResult`, `SendResult`, `CouponDecision`, `MarketingCampaignConfig`, `HourlyDateRange`) | same | Unchanged |
| Enum files | 4 | 4 | Unchanged |
| Form Request classes | 58 | 58 | Admin-wide typed, validated input |

### What Improved

- **PHPStan raised level 1 → 5** across `app/` and `routes/` (larastan extension + `phpstan-baseline.neon`). The type hints added in earlier phases are now *checked* — passing the wrong type, calling an undefined method, or dereferencing a possible-null is flagged on new code. This is the main driver of the +4 and the biggest single lift to "AI code is validated" since the type hints themselves were added.
- **Typed DTOs and value objects** from the Firebase/Marketing decomposition remain in place, giving AI concrete data shapes.
- **Loose comparisons held flat** (~742) — no regression.

### What Still Needs Work

- `declare(strict_types=1)` still only in 1 file — level-5 static analysis checks types, but PHP's runtime still silently coerces at call boundaries.
- No interfaces/contracts — signatures only discoverable by reading implementations.
- Hungarian notation still obscures intent in DB columns (`iUserID`, `vEmail`, `bActive`).
- **API** controller/auth/subscription methods still mostly untyped and validate inline — the Form Request coverage is admin-only so far.

---

## Category 4: Documentation & PHPDoc (80/100, was 82)

### Coverage by Layer

| Layer | Coverage | Notes |
|-------|----------|-------|
| Models | **91/94 class-level docblocks (~97%)** | `@property` annotations maintained |
| API Controllers | 100% | Method-level PHPDoc |
| Original Services (pre-decomposition) | ~100% | `@param array{...}` shapes + `@return` |
| **New decomposed services** | **partial class-level coverage (~38/102 class docblocks)** | Small, typed, single-purpose — often self-documenting but lack class headers |
| Query Classes | 100% | Method-level `@param`/`@return` |
| Admin Controllers | 100% | ~196 methods documented |

### Why the Slight Dip

The codebase grew by ~80 files of newly extracted small services (campaigns, DTOs, processors). Many are typed and single-purpose, but only ~38% carry a class-level docblock, so documentation breadth lagged behind the structural growth. The original layers remain fully documented.

### What's Still Missing

- Class-level docblocks on the ~64 newly extracted services.
- Only 3 Form Request classes to serve as living input documentation.

### CLAUDE.md Provides Strong Project Context

`CLAUDE.md` remains a major asset — it documents architecture, patterns, commands, and integrations, giving AI a strong starting point. (Note: it documents Laravel 13 / PHP 8.3+, matching `composer.json`.)

---

## Category 5: Testing Infrastructure (73/100, was 66)

### Test Distribution

| Category | Previous | Current | Notes |
|----------|----------|---------|-------|
| Total test files | 157 | **160** | +3 |
| Feature Tests | 70 | **73** | API endpoints |
| Unit Tests | 82 | **85** | Mirror `app/Services/` tree |
| Service unit tests | 68 | **71** | Mirror `app/Services/` tree |
| Model Factories | 1 (User) | **1 (User)** | Unchanged — still the biggest test-data gap |
| Static Analysis Level | PHPStan Level 1/9 | **PHPStan Level 5/9** | **Raised — main driver of +7** |
| CI/CD Pipeline | None | None | No automated checks |

### What Works

- **PHPStan raised to Level 5/9** (larastan + `phpstan-baseline.neon`). The static-analysis gate now catches real type and null-safety errors on new code — the single biggest change this period and the reason AI-authored code is now validated before it runs.
- **`tests/Unit/Services/` mirrors the service tree** — `Firebase/Campaigns/`, `Marketing/Coupon/`, `Cron/Processors/`, etc. AI can locate the test for any service by path.
- **Modern Pest PHP** with BDD-style `describe()`/`it()` blocks and AAA structure.
- **Decomposed services are individually testable** — the Firebase split makes each campaign unit-testable in isolation, which was impossible with the 2,619-line monolith.

### What's Missing for AI

**Still only 1 model factory** — AI cannot easily generate test data for `Program`, `Chapter`, `Day`, `UserProgram`, etc., and must hand-build fixtures. **This is now the single biggest testing gap.**

**No CI/CD pipeline** — the level-5 PHPStan gate and the 160-file suite exist but nothing runs them automatically on push; enforcement depends on developers remembering to run them locally.

> Note: the full suite currently hits a Mockery class-redeclaration error under randomized ordering (`Cannot redeclare Mockery_..._UserConfig::mockery_init()`) — a test-harness isolation issue worth fixing so CI can run green.

---

## Category 6: Method Complexity (46/100, was 37)

### God Classes — Status

| Class | Previous | Current | Status |
|-------|----------|---------|--------|
| `FirebaseBusinessService` | 2,619 lines, 45+ methods | **228-line facade** | **Decomposed** ✅ |
| `MarketingEmailService` | large monolith | **125 lines** | **Decomposed** ✅ |
| `CronService` | monolith | **194 lines** | **Decomposed** ✅ |
| `BaseAuthService` | 1,426 lines | **1,459 lines** | **Grew again** ⚠️ |
| `UserQuery` | 1,180 lines | **1,180 lines** | **Unchanged** ⚠️ |

### God Methods (>100 lines) — still present

| Method | File | Notes |
|--------|------|-------|
| `getProgramSubscriptionDetails()` | `ProgramService.php` | 5+ queries in loops |
| `updateExistingUser()` | `BaseAuthService.php` | 10+ services |
| `getUsersList3()` | `UserQuery.php` | Complex nested whereHas |

### What Improved

- The three highest-impact monoliths (Firebase, Marketing, Cron) were broken into small, single-responsibility classes — directly reducing the "read 1,000+ lines to make one change" failure mode for the most-touched notification/marketing code.

### What Regressed

- **`BaseAuthService` grew again to 1,459 lines** (1,117 → 1,426 → 1,459) and **`UserQuery` holds at 1,180**. These remain the two worst complexity hotspots; the Form Request work did not touch them, so they are still the next decomposition targets — and BaseAuthService is trending the wrong way.

### AI Impact

Modifying a Firebase campaign is now low-risk (isolated, testable class). Modifying `BaseAuthService` remains high-risk: ~33 constructor dependencies, 1,400+ lines, no interfaces.

**Failure probability for non-trivial `BaseAuthService` modifications: still ~50-60%.**

---

## Category 7: Navigability & Discoverability (80/100, was 77)

### Strengths

| Asset | Value to AI |
|-------|------------|
| `CLAUDE.md` / `CLAUDE.local.md` | Excellent project + container context |
| `data-dictionary/` | Auto-generated table/column docs for all 3 databases |
| **Domain-organized services** | **Firebase/Marketing/Cron logic discoverable by path** |
| **Test tree mirrors service tree** | **Find any service's test by path** |
| Facade + Registry patterns | Clear entry points into decomposed domains |
| Single API layer | No ambiguity about which layer to modify |

### Weaknesses

| Issue | Impact |
|-------|--------|
| No interface files | Cannot discover contracts without reading implementations |
| Query classes in `Http/` | Counter-intuitive location (93 classes) |
| 38 flat root-level services | Notification/commerce/integration still ungrouped |
| 4 database connections | Cross-database relationships unclear |
| `BaseAuthService` / `UserQuery` size | Hard to navigate within-file |

---

## AI Success/Failure Scenarios

### Scenario 1: "Add a new Firebase notification campaign"

| Factor | Assessment |
|--------|-----------|
| Finding the pattern | HIGH — 8 isolated campaign services to copy |
| Implementation | HIGH — small, single-purpose, registry-driven |
| Testing | HIGH — mirrored unit test per campaign exists |
| **Overall likelihood** | **80% correct on first attempt** (was 50% with the monolith) |

### Scenario 2: "Add a new API endpoint for user preferences"

| Factor | Assessment |
|--------|-----------|
| Route registration | HIGH — clear pattern in `api.php` |
| Controller + Form Request | MEDIUM-HIGH — 3 Form Request examples now exist |
| Service method | HIGH — typed, PHPDoc documented |
| Test creation | MEDIUM — 70 feature tests to copy |
| **Overall likelihood** | **75% correct on first attempt** |

### Scenario 3: "Fix a bug in the auth / login flow"

| Factor | Assessment |
|--------|-----------|
| Finding relevant code | MEDIUM — `BaseAuthService` is 1,426 lines |
| Understanding the flow | LOW-MEDIUM — 33 deps, no interfaces |
| Making the fix | MEDIUM — typed params help |
| Verifying the fix | LOW — limited auth test coverage |
| **Overall likelihood** | **40% correct on first attempt** |

---

## Actionable Recommendations

### Priority 1: High Impact, Low Effort — COMPLETED

#### 1.1 ~~Add return type hints to all service methods~~ DONE (2026-03-12)
#### 1.2 ~~Add parameter type hints to all public methods~~ DONE (2026-03-12)
#### 1.3 ~~Create a `Platform` enum and replace magic strings~~ DONE (2026-03-13)
#### 1.4 ~~Extract controller validation to base method~~ DONE (2026-03-13)
#### 1.5 ~~Fix `userJournyLog` typo~~ DONE (2026-03-13)
#### 1.6 ~~Build V3 API layer with standardized patterns~~ DONE (2026-03-18), **REMOVED** (2026-03-24)
#### 1.7 ~~Add PHPDoc to all service methods~~ DONE (2026-03-24)
#### 1.8 ~~Fix service layer architectural violations~~ DONE (2026-03-26)
#### 1.9 ~~Decompose `FirebaseBusinessService` god class~~ DONE (2026-06-30)
#### 1.10 ~~Split Marketing & Cron services into domain sub-namespaces~~ DONE (2026-06-30)
#### 1.11 ~~Expand service unit test coverage (mirror service tree)~~ DONE (2026-06-30)

### Priority 2: High Impact, Medium Effort (Score impact: +8-12 points)

#### 2.1 Expand Form Request validation across endpoints — DONE for admin (2026-07-10), remaining for API

**Current state:** 55 Form Request classes across 24 controllers | **Target:** extend to API auth & subscription endpoints | **Effort:** 1-2 days remaining
The admin write surface is now fully covered (`app/Http/Requests/Admin/**` behind `BaseAdminFormRequest`). What's left: apply the same pattern to the **API** auth/subscription endpoints (`BaseAuthService`-backed routes) that still validate inline.

#### 2.2 Standardize error handling with a response trait

**Current state:** 5 competing patterns | **Target:** Single `FormatsApiResponse` trait | **Effort:** 2-3 days

#### 2.3 Add model factories for core models

**Current state:** 1 factory (User) | **Target:** 10-15 factories | **Effort:** 2-3 days
Priority models: `Program`, `Chapter`, `Day`, `UserProgram`, `UserInfo`, `UserProfile`, `Coupon`, `Voucher`, `UserSubscription`. **This is now the single biggest testing gap** — the test suite is large but data setup is manual.

#### 2.4 ~~Raise PHPStan level from 1 to 5~~ DONE (2026-07-18)

**Current state:** Level **5/9** via larastan + a 3,064-line `phpstan-baseline.neon` that enforces the gate on new/changed code. Next lever here is wiring it into CI (2.5 / 4) so it runs automatically, then working the baseline down.

#### 2.5 Fix the suite's Mockery redeclaration error

**Effort:** <1 day. Required before CI can run the full suite green.

### Priority 3: Medium Impact, Higher Effort (Score impact: +5-8 points)

#### 3.1 Decompose `BaseAuthService` (now 1,426 lines, 33 deps) — NOW THE TOP TARGET

```
BaseAuthService (~1,426 lines)
    -> AuthenticationService     - login/OTP logic
    -> UserRegistrationService   - signup/update flows
    -> AuthResponseService       - response formatting
    -> AuthTrackingService       - journey logging, analytics
```

#### 3.2 Decompose `UserQuery` (now 1,180 lines)

Split by domain (user lookup, program joins, smoke/activity aggregates) following the Firebase decomposition model.

#### 3.3 Add `declare(strict_types=1)` to all files

**Current state:** 2 of ~434 files | **Effort:** Automated via script + fix type errors

#### 3.4 Group the 38 flat root-level services by domain

```
app/Services/
├── Notification/   (Firebase facade, Postmark, SendGrid, Transactional)
├── Commerce/       (Coupon, Voucher, Billing)
├── Integration/    (Meta, Gympass, Bajaj, Discourse)
├── Search/         (Search, Typesense*, SynonymSync)
└── Core/           (remaining)
```

### Priority 4: Advanced (Score impact: +3-5 points)

| Task | Effort | Score Impact |
|------|--------|-------------|
| Create interfaces for all service dependencies | 3 days | +3 |
| Replace remaining loose comparisons (`==` -> `===`) | 1-2 days | +2 |
| Set up CI/CD pipeline (GitHub Actions) | 1 day | +2 |
| Add class-level docblocks to decomposed services | 1 day | +1 |
| Move Query classes from `Http/` to `app/Queries/` | 1 day | +1 |

---

## Implementation Roadmap

### Phase 1: Quick Wins — COMPLETED (2026-03-12 → 03-13)

| Task | Status | Score Impact |
|------|--------|-------------|
| ~~Add return/parameter types to all service files~~ | **DONE** | +8 |
| ~~Create `Platform` enum~~ | **DONE** | +1 |
| ~~Extract controller validation to base method~~ | **DONE** | +2 |
| ~~Fix `userJournyLog` typo~~ | **DONE** | +1 |

### Phase 1.5: PHPDoc Coverage — COMPLETED (2026-03-24 → 03-25)

| Task | Status |
|------|--------|
| ~~PHPDoc array shapes for V1 services (52/52)~~ | **DONE** |
| ~~Model `@property` annotations (87/87)~~ | **DONE** |
| ~~Query class method PHPDoc (86/86)~~ | **DONE** |
| ~~Admin controller PHPDoc (57/57)~~ | **DONE** |

### Phase 1.75: Architecture Cleanup — COMPLETED (2026-03-26)

| Task | Status | Score Impact |
|------|--------|-------------|
| ~~Extract CalculatesUtcOffset trait~~ | **DONE** | +1 |
| ~~Remove controller inheritance from services~~ | **DONE** | +1 |
| ~~Replace service locator with constructor DI~~ | **DONE** | +0.5 |
| ~~Optimize auth queries with column selection~~ | **DONE** | +0.5 |

### Phase 2: God-Class Decomposition & Testing — COMPLETED (2026-06-30)

| Task | Status | Score Impact |
|------|--------|-------------|
| ~~Decompose FirebaseBusinessService (2,619 → 228 facade)~~ | **DONE** | +3 |
| ~~Split Marketing into domain sub-namespace~~ | **DONE** | +1 |
| ~~Split Cron into domain services/processors~~ | **DONE** | +1 |
| ~~Expand tests 83 → 154 (mirror service tree)~~ | **DONE** | +2 |
| ~~Introduce Form Request validation (3 classes)~~ | **DONE (started)** | +1 |

### Phase 3: Remaining Standardization — Target Score: 73 (68 → 70 delivered)

| Task | Effort | Score Impact |
|------|--------|-------------|
| ~~Raise PHPStan to level 5~~ | **DONE (2026-07-18)** | **+2** |
| Add 10+ model factories | 2-3 days | +3 |
| Standardize error handling with response trait | 2-3 days | +2 |
| Expand Form Requests to auth/subscription endpoints | 2 days | +2 |
| Fix Mockery suite isolation + add CI | 1-2 days | +2 |

### Phase 4: Structural Depth — Target Score: 80

| Task | Effort | Score Impact |
|------|--------|-------------|
| Decompose BaseAuthService (1,426 lines) | 3 days | +3 |
| Decompose UserQuery (1,180 lines) | 2 days | +2 |
| Add `declare(strict_types=1)` to all files | 1 day | +2 |
| Group 38 flat root-level services by domain | 1 day | +1 |
| Create interfaces for core service dependencies | 3 days | +3 |

### Projected Score Progression

```
Mar 9:   ███████████████████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░  45 (D)   <- Initial assessment
Mar 13:  ███████████████████████████░░░░░░░░░░░░░░░░░░░░░░░░  53 (C-)  <- Phase 1 done
Mar 18:  ████████████████████████████████░░░░░░░░░░░░░░░░░░░  63 (C)   <- V3 API done
Mar 24:  ██████████████████████████████░░░░░░░░░░░░░░░░░░░░░  60 (C)   <- V3 removed, V1 PHPDoc
Mar 25:  ██████████████████████████████░░░░░░░░░░░░░░░░░░░░░  61 (C)   <- Full PHPDoc all layers
Mar 26:  ███████████████████████████████░░░░░░░░░░░░░░░░░░░░  62 (C)   <- Architecture cleanup
Jun 30:  █████████████████████████████████░░░░░░░░░░░░░░░░░░  66 (C)   <- God-class decomposition + testing
Jul 10:  ██████████████████████████████████░░░░░░░░░░░░░░░░░  68 (C)   <- Admin-wide Form Request validation (3 → 55)
Jul 18:  ███████████████████████████████████░░░░░░░░░░░░░░░░  70 (C+)  <- PHPStan level 1 → 5 (static-analysis gate)
Phase 3: ████████████████████████████████████░░░░░░░░░░░░░░░  73 (C+)  <- factories + error trait + API Form Requests + CI
Phase 4: ████████████████████████████████████████░░░░░░░░░░  80 (B)
```

---

## Appendix A: Files Most Critical to Improve

The decomposition shifted the top targets — Firebase is no longer the worst offender; auth and the user query now are.

| File | Lines | Why Critical | AI Difficulty |
|------|-------|-------------|---------------|
| `Services/Auth/BaseAuthService.php` | 1,459 | Core auth, 33 deps, grew again | HARD |
| `Http/Queries/UserQuery.php` | 1,180 | Most-used query class, grew | HARD |
| `Services/ProgramService.php` | ~290 | Core business logic, god methods | MEDIUM |
| `Services/FirebaseBusinessService.php` | 228 | Facade — now safe; depend on campaign services directly | LOW |

## Appendix B: Grading Scale

| Score | Grade | Meaning |
|-------|-------|---------|
| 90-100 | A | AI can work autonomously with high accuracy |
| 80-89 | B | AI produces correct code most of the time |
| 70-79 | C+ | AI needs moderate human review |
| 60-69 | C | AI frequently needs correction |
| 50-59 | C- | AI requires significant guidance |
| 40-49 | D | AI struggles without heavy supervision |
| 0-39 | F | AI cannot reliably work with this codebase |

---

*Report generated by Claude Code. Last updated 2026-07-18 after static analysis was raised from PHPStan level 1 to level 5 (larastan extension + a 3,064-line baseline enforcing the gate on new/changed code), which delivered Recommendation 2.4 and lifted the score 68 → 70, crossing the C → C+ boundary. Next-highest-leverage work is now clearly isolated: add model factories (still 1), wire the level-5 PHPStan gate into CI/CD (none), decompose BaseAuthService (still 1,459) / UserQuery (still 1,180), and extend Form Requests to the API auth/subscription endpoints.*