# NUMONIX — FINAL PRODUCTION ENGINEERING MASTER PROMPT
# Version: FINAL-CONSOLIDATED | Date: 2026-10-03
# All facts verified against actual repositories on this date.

> Copy this entire prompt verbatim into your AI code editor at the start of EVERY session.
> Read the checkpoint files first, then resume from next_exact_action.

---

## VERIFIED PROJECT FACTS (confirmed from real code — never assume)

| Item | Confirmed Value |
|------|----------------|
| Backend path | D:\Projects\Herd\lee-backend-work |
| Flutter path | D:\Projects\Herd\lee-flutter-work |
| Production API base URL | https://api.numonix.app/api/ |
| Flutter package name | app.numonix |
| Backend framework | Laravel 12.x |
| Payment provider | Paddle ONLY — laravel/cashier-paddle ^2.8 |
| Firebase backend | kreait/laravel-firebase ^6.2 |
| Social auth backend | laravel/socialite ^5.24 + firebase/php-jwt ^7.0 |
| Flutter HTTP client | dio ^5.9.2 |
| Flutter Firebase | firebase_core ^4.15.0, firebase_auth ^6.7.0, firebase_messaging ^16.7.0 |
| Flutter Google Login | google_sign_in: 6.2.1 |
| Flutter Apple Login | sign_in_with_apple ^8.2.0 |
| Total API routes | 81 confirmed |
| Stripe | REMOVED — confirmed by comment in backend.php |
| RevenueCat | NOT in pubspec or composer — do not add |
| Firebase credentials | FirebaseCredentialResolver service + admin dashboard upload |
| firebase-credentials.json | Must NOT exist anywhere in repo — delete it |
| PDF requirements | No PDF generation in app — client PDFs are requirement documents only |

---

## CRITICAL EXECUTION ORDER — MANDATORY

```
STEP 1: Deeply check, analyze, and fix BACKEND (lee-backend-work) FIRST
         -> All routes, controllers, models, migrations, seeders, services, repositories,
            jobs, notifications, mail, admin dashboard, security, tests
         -> Confirm all 81 APIs are working, all logic is correct, no errors

STEP 2: Deeply check, analyze, and fix FLUTTER (lee-flutter-work) SECOND
         -> All screens, widgets, models, services, network layer, auth, notifications,
            payment, Android config, tests
         -> Confirm all Flutter functionality is fully connected to backend APIs

STEP 3: Integration verification — confirm every Flutter API call hits the correct
         backend route with the correct request/response contract

NEVER start Flutter work until backend is confirmed fully working.
```

---

## ROLE

You are simultaneously:
- Principal/Senior Software Engineer
- Application Security Engineer
- Flutter Engineer
- Laravel/PHP Backend Engineer
- Firebase Engineer
- Payment Integration Engineer
- SQA/QA Automation Engineer (test like a human SQA tester)
- DevOps Engineer
- Production Release Engineer
- Database Engineer
- Mobile Engineer
- API Integration Engineer

This is a REAL production engineering task. Fix code. Run real tests. Produce real evidence.

DO NOT:
- Only analyze or recommend — fix the code
- Assume code works because files exist
- Skip any file, route, feature, test, or security check
- Fabricate test results
- Disable TLS validation
- Trust client-supplied payment/subscription/tier data
- Store secrets in Flutter source code
- Run destructive operations against production data
- Declare complete while anything critical is FAIL / BLOCKED / untested / unknown

---

## CLIENT REQUIREMENT DOCUMENTS (authoritative baseline)

```
D:\Projects\Herd\lee-backend-work\NumoniX_Dev_Roadmap.pdf
D:\Projects\Herd\lee-backend-work\NumoniX_Launch_Roadmap.pdf
D:\Projects\Herd\lee-flutter-work\NumoniX_Dev_Roadmap.pdf
D:\Projects\Herd\lee-flutter-work\NumoniX_Launch_Roadmap.pdf
```

Read BOTH PDFs completely before touching any code.
Extract every requirement per phase. Classify each as:
IMPLEMENTED | PARTIAL | MISSING | BROKEN | BLOCKED | MANUAL/EXTERNAL | NOT-APPLICABLE

Cover ALL roadmap areas:
- Phase 1: Content and Configuration
- Phase 2: Website and Paddle Foundation
- Phase 3: Backend Development
- Phase 4: Decision Point and Founder Recruitment
- Phase 5: Store Testing
- Phase 6: Store Listing and Submission
- Phase 7: Launch
- Phase 8: Post-Launch and Founder Conversion

Do NOT silently omit tasks that are manual or external. Classify them appropriately.

Key requirements confirmed from PDFs:
- Paddle ONLY (Laravel Cashier Paddle, webhook at /paddle/webhook, Ed25519 sig verification, lifecycle events)
- RevenueCat = future contingency ONLY if Apple/CMA forces UK IAP — do not implement now
- Stripe = completely removed from both projects
- Transactional email via SMTP (mail.thewarriors.team:465 SSL): welcome, founder onboarding,
  trial-ending day-25 reminder with GBP 24.99 offer, subscription confirmation, password reset
- Founder programme: CSV import from Tally -> user + founder flag + Tier 2 + 30-day rolling trial ->
  day-25 email regardless of review form completion -> GBP 24.99 unique Paddle checkout ->
  cancellation = Free tier at period end. Review form is OPTIONAL and never gates anything.
- Entitlement/tier: server-side authoritative; Flutter reads tier from backend;
  Flutter links to numonix.app in external browser to upgrade
- Firebase/FCM: backend uses Kreait, Flutter uses firebase_messaging;
  admin dashboard custom notification sender (ALL users / SELECTED users), admin-only
- Google and Apple Login: Flutter -> Firebase Auth -> ID token -> Laravel server-side verification
  -> user lookup/creation -> Sanctum token

---

## PRODUCTION ENVIRONMENT (complete confirmed .env)

```
APP_NAME="Numonix"
APP_ENV=local                  [CHANGE TO: production ON SERVER]
APP_KEY=base64:6nZivR9iX5D7FSZkunPRCKsdc7lErFqkQdXPGF637xo=
APP_DEBUG=true                 [CHANGE TO: false ON SERVER]
APP_URL=https://api.numonix.app
APP_LOCALE=en

APP_MAINTENANCE_DRIVER=file
PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12

LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug                [CHANGE TO: error ON SERVER]

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dbwli6a3xutj7r
DB_USERNAME=uvx8imitzxosf
DB_PASSWORD="rM&1c9@+#c$3"

SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null

BROADCAST_CONNECTION=log
FILESYSTEM_DISK=public
QUEUE_CONNECTION=sync          [CHANGE TO: database OR redis ON SERVER]

CACHE_STORE=database
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mail.thewarriors.team
MAIL_PORT=465
MAIL_USERNAME=dev@thewarriors.team
MAIL_PASSWORD="iR1G9fLI2y^uB&&O"
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS="dev@thewarriors.team"
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

VITE_APP_NAME="${APP_NAME}"
CASHIER_LOGGER=stack

FIREBASE_CREDENTIALS=          [LEAVE EMPTY — use admin dashboard upload]
[OLD VALUE WAS: C:\Users\Imtiaz\Herd\Leemcwest-Backend\storage\app/firebase-credentials.json]
[THIS OLD PATH MUST BE CLEARED — it points to a machine that is not the production server]

STRIPE_KEY=23425789            [REMOVE FROM PRODUCTION .env — Stripe is removed]
STRIPE_SECRET=34448            [REMOVE FROM PRODUCTION .env]
STRIPE_WEBHOOK_SECRET=2666666666665789  [REMOVE FROM PRODUCTION .env]

GOOGLE_CLIENT_ID=412757137282-ho4p96fi3td21pjuaoljssejqif0jve1.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=AIzaSyAd0-oVXFb7Ujwy7wubBa_ucmJ0oUE-18M

APPLE_CLIENT_ID=               [BLOCKED — client must provide]
APPLE_TEAM_ID=                 [BLOCKED — client must provide]
APPLE_KEY_ID=                  [BLOCKED — client must provide]
APPLE_PRIVATE_KEY=             [BLOCKED — client must provide]
APPLE_REDIRECT_URI=            [BLOCKED — client must provide]

MAINTENANCE_TOKEN=38cd99dcaf195df1ece6c1713a6d01e2b516dfb501268dbc
```

Production server deployment checklist (do all before going live):
- APP_ENV=production
- APP_DEBUG=false
- LOG_LEVEL=error
- QUEUE_CONNECTION=database or redis
- STRIPE_KEY, STRIPE_SECRET, STRIPE_WEBHOOK_SECRET REMOVED from .env
- FIREBASE_CREDENTIALS= (empty — use dashboard upload)
- php artisan config:cache
- php artisan route:cache
- php artisan view:cache
- php artisan storage:link
- php artisan migrate --force
- Supervisor/systemd managing queue workers
- Cron running: php artisan schedule:run * * * * *
- nginx/apache configured correctly for Laravel public/ directory
- SSL certificate valid for api.numonix.app

---

## CONFIRMED ARCHITECTURE

```
Flutter App (app.numonix)
  -> Dio HTTP client
  -> Base URL: https://api.numonix.app/api/
  -> Auth: Bearer {sanctum_token} via Authorization header
  -> Guest: HMAC fingerprint via X-Device-ID + X-Device-Fingerprint headers

Laravel Backend (lee-backend-work)
  -> ValidateGuestHeaders middleware (HMAC fingerprinting)
  -> Sanctum token auth for authenticated routes
  -> Controller -> Service -> Repository -> Model -> MySQL
  -> FCMService -> Kreait -> Firebase -> FCM -> Device
  -> PaddleService -> Laravel Cashier Paddle -> Paddle API -> Webhook
  -> SocialLoginService -> Socialite + firebase/php-jwt -> User
  -> FirebaseCredentialResolver -> admin-uploaded JSON -> storage/app/firebase-credentials-dashboard.json

MySQL Database
  -> Users (Billable trait, founder fields, subscription_tier, paddle_id, paddle_customer)
  -> FirebaseTokens, Notifications, FounderReviewSubmissions
  -> Learning, EarTraining, Quiz, CMS, Preferences, etc.

Admin Dashboard (Livewire/Blade)
  -> CustomNotificationController (send to all/selected users)
  -> FounderDashboardController (metrics: count, trial status, review rate, conversion rate)
  -> FirebaseSettingController (upload credentials JSON)
  -> MailSettingController, SystemSettingController
```

---

## FIREBASE CREDENTIALS — CRITICAL PROTOCOL

firebase-credentials.json must NOT exist anywhere in the repository.
Search for it: Get-ChildItem -Recurse -Name "firebase-credentials.json"
If found: delete it immediately.

The FirebaseCredentialResolver is already implemented with this priority:
1. Admin dashboard upload: storage/app/firebase-credentials-dashboard.json
2. FIREBASE_CREDENTIALS env variable (path, raw JSON, or base64-encoded JSON)
3. GOOGLE_APPLICATION_CREDENTIALS env variable

For production: Admin logs into admin dashboard -> Settings -> Firebase Settings
-> Uploads the Firebase service account JSON file
-> File saved to storage/app/firebase-credentials-dashboard.json
-> All FCM operations work immediately

FIREBASE_CREDENTIALS in .env = (empty on production server, use dashboard)

---

## 7 KNOWN ERRORS — FIX IN THIS ORDER

### ERROR 1 — P0: Flutter Release APK Cannot Connect to Internet/API

Root cause candidates (investigate in order):
1. ProGuard/R8 obfuscating Dio interceptors or OkHttp classes
   -> Check android/app/proguard-rules.pro for missing keep rules
2. key.properties missing -> release signing falls back to debug key
   -> Verify android/key.properties exists and is correctly configured
3. firebase_options.dart hardcoded android_client_id vs actual google-services.json SHA
   -> Verify debug and release SHA-1 fingerprints registered in Firebase console
4. Dio connectTimeout/receiveTimeout too short -> requests silently time out
   -> Check DioClient or NetworkClient timeout configuration

Investigation commands:
```
flutter clean && flutter pub get
flutter build apk --release --verbose
adb install build/app/outputs/flutter-apk/app-release.apk
adb logcat -s "flutter" "OkHttp" "Dio"
```

DO NOT: disable TLS, add android:usesCleartextTraffic="true" globally, bypass certificates.
DO NOT mark this fixed until the release APK communicates with https://api.numonix.app/api/

Current confirmed state:
- INTERNET permission: PRESENT in AndroidManifest.xml
- network_security_config.xml: PRESENT and correctly configured (HTTPS only for api.numonix.app)
- Base URL in Flutter Endpoints class: https://api.numonix.app/api/ (CORRECT)
- isMinifyEnabled: true for release (ProGuard/R8 is running)
- proguard-rules.pro: needs verification

Required ProGuard keep rules (add if missing):
```
-keep class io.flutter.** { *; }
-keep class com.google.firebase.** { *; }
-keep class com.google.android.gms.** { *; }
-dontwarn io.flutter.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes *Annotation*
```

### ERROR 2 — P0: Google Login Broken End-to-End

Required architecture:
```
Flutter -> google_sign_in.signIn() -> GoogleSignInAccount
  -> FirebaseAuth.signInWithCredential(GoogleAuthProvider.credential(idToken))
  -> FirebaseUser.getIdToken()
  -> POST /api/social/login {provider: "google", token: "<firebase_id_token>"}
  -> Backend: SocialLoginController -> SocialLoginService
  -> firebase/php-jwt verifies Firebase ID token with Google public keys
  -> User::firstOrCreate by email/google_id
  -> Sanctum token returned
  -> Flutter stores token in secure storage
```

Backend: SocialLoginController@socialLogin must verify Firebase ID token server-side.
NEVER trust raw Google token without server-side Firebase verification.
Test: new user via Google, existing user via Google, cancelled auth, invalid token, logout.

SHA-1 fingerprint: both debug and release SHA-1 MUST be registered in Firebase console.
Get debug SHA: cd android && ./gradlew signingReport
Get release SHA: depends on key.properties keystore — verify both are in google-services.json.

### ERROR 3 — P0: Apple Login Broken End-to-End

Required architecture:
```
Flutter -> SignInWithApple.getAppleIDCredential()
  -> FirebaseAuth.signInWithCredential(OAuthProvider("apple.com").credential(...))
  -> FirebaseUser.getIdToken()
  -> POST /api/social/login {provider: "apple", token: "<firebase_id_token>"}
  -> Backend: SocialLoginController -> SocialLoginService
  -> firebase/php-jwt verifies Apple/Firebase ID token
  -> User::firstOrCreate (handle private relay email)
  -> Sanctum token returned
```

BLOCKED until client provides:
- APPLE_CLIENT_ID
- APPLE_TEAM_ID
- APPLE_KEY_ID
- APPLE_PRIVATE_KEY
- APPLE_REDIRECT_URI

Mark end-to-end test as BLOCKED. Never fabricate success.
Implement the code fully so it works the moment credentials are provided.

### ERROR 4 — P0: Push Notifications, Real-Time Notifications, Admin Custom Sender

Backend (Kreait — kreait/laravel-firebase ^6.2):
Documentation: https://firebase-php.readthedocs.io/8.5.0/
- FCMService::sendMessage() confirmed using Firebase::messaging()->send($message)
- FirebaseCredentialResolver confirmed multi-strategy
- Gap: FIREBASE_CREDENTIALS in .env points to old Windows machine path — must be cleared
- Admin dashboard CustomNotificationController exists at /backend/custom-notifications

Flutter:
- firebase_messaging is in pubspec
- Verify FirebaseMessaging.onMessage, onMessageOpenedApp, onBackgroundMessage handlers
- FCM token registration: POST /api/firebase-token/add called on login AND token refresh
- android/app/google-services.json must be present and valid

Admin Dashboard custom sender requirements:
- Title input (with validation)
- Message/body input (with validation)
- Recipient selector: ALL USERS or SELECTED USERS
- Authorization: admin-only (403 for normal users, 403 for unauthenticated)
- Database: create Notification record for each recipient
- Delivery: send via Kreait FCM with error handling for invalid/expired tokens
- Feedback: success/failure message shown in dashboard

Security tests required:
```
Normal user -> POST /api/notifications/send = 403 FORBIDDEN
Unauthenticated -> /backend/custom-notifications = 302/401
Admin -> all users notification = TEST PASS
Admin -> selected users notification = TEST PASS
Invalid FCM token = handled gracefully (log, cleanup, continue)
```

### ERROR 5 — Full Functional Audit Both Projects

For BACKEND (do first):
Check code-by-code, line-by-line:
- All routes (api.php, backend.php, web.php, settings.php)
- All controllers (29 API controllers + 40+ web/admin controllers)
- All models (36 models) — relationships, fillable, casts, scopes
- All migrations — schema completeness, indexes, foreign keys
- All seeders — data correctness
- All services (36 services) — business logic correctness
- All repositories — query correctness, N+1 issues
- All jobs — queue handling, retry logic
- All notifications and mail — templates, queue dispatch
- All tests — run php artisan test, fix all failures
- No mismatches between migrations and models
- No missing relationships
- No broken logic

For FLUTTER (do second):
Check code-by-code, line-by-line:
- All screens and widgets
- All models (fromJson/toJson completeness)
- All API service methods
- All GetX controllers
- Network layer (Dio interceptors, error handling)
- Auth flow (token storage, refresh, expiry)
- All feature modules (confirm each calls the correct backend endpoint)
- flutter analyze (zero errors)
- flutter test (all pass)

### ERROR 6 — Remove All Unused, Extra, and Vulnerable Files

From BACKEND remove:
- firebase-credentials.json (delete permanently)
- Stripe references in .env, .env.example, config/services.php (STRIPE_* keys)
- Any Stripe controller, service, route, test if remaining
- PHP cache files: php artisan cache:clear, config:clear, route:clear, view:clear
- composer unused packages if any
- Orphaned migration files that reference removed features
- storage/framework/cache/* (safe to clear)
- .env.example Stripe entries

From FLUTTER remove:
- Any Stripe package references in pubspec.yaml
- Any RevenueCat package references in pubspec.yaml
- Any dead Dart import statements
- build/ directory artifacts (flutter clean)
- .dart_tool/package_config.json (regenerated by flutter pub get)
- Any hardcoded credentials or API keys in Dart source files

For BOTH projects:
- Search and remove/resolve: TODO, FIXME, HACK, TEMP in production paths
- Remove: debugPrint, print( calls in production code (keep only logger calls)
- Remove: dd(, dump(, die(, var_dump in PHP (keep only Log:: calls)

### ERROR 7 — Backend and Flutter Full Alignment with PDFs

Backend must be fully updated so NO mismatch exists between:
- Migrations and models (all fields in $fillable must have migration columns)
- Models and controllers (all response fields must exist in model)
- Controllers and services (all method calls must exist)
- Services and repositories (all query methods must exist)
- Routes and controllers (all route handlers must be implemented)
- Seeders and migrations (all seeded columns must exist)
- Tests and current code (tests must reflect current behavior)

Flutter must be fully updated so NO mismatch exists between:
- Endpoints class and backend routes (every Flutter endpoint must map to a real route)
- Model fromJson and backend response schema
- Controller actions and expected API response structure
- Error handling and actual backend error response format
- Auth token storage and token validation logic

Create/update NUMONIX_REQUIREMENTS_MATRIX.md with every PDF requirement classified.

---

## CONFIRMED BACKEND INVENTORY

### API Controllers (29)
Auth\LoginController, Auth\ProfileUpdateController, Auth\RegisterController
Cms\AboutNumoniXApiController, Cms\CompleteGlossaryApiController, Cms\GlossaryApiController
Cms\PrivacyPolicyApiController, Cms\TermsConditionsApiController, Cms\UserGuideApiController
Cookie\CookieSettingsController
DashboardView\DashboardOverviewController
EarTraining\EarTrainingApiController
Faq\FaqController
Founder\FounderController
Guest\GuestDeviceController
HomeController, LearningController
Notification\NotificationController, Notification\NotificationSettingsController
Preferences\PreferencesController
PushNotification\FirebaseTokenController
Quiz\QuizApiController
Review\ReviewController
SocialLogin\SocialLoginController
Subscription\SubscriptionController
Support\SupportController
SystemSetting\SystemSettingController, SystemSetting\UpdateAlertApiController
UserProgress\UserProgressController

### Admin/Web Controllers (40+)
Web\Backend\Settings\FirebaseSettingController  <- admin Firebase credential upload
Web\Backend\Notification\CustomNotificationController  <- admin notification sender
Web\Backend\Founder\FounderDashboardController
Web\Backend\DashboardController
Web\Backend\LearningController, LearningGroupController
Web\Backend\EarTraining\* (5 controllers)
Web\Backend\Cms\* (6 controllers)
Web\Backend\Quiz\* (2 controllers)
Web\Backend\Mail\MailController
Web\Backend\GuestAccess\* (2 controllers)
Web\Backend\Settings\* (5 controllers)
Web\Backend\UserController, ReviewController, FaqController, etc.
Web\Frontend\HomeController, FounderReviewController

### Services (36)
AuthenticationService, EmailVerificationService, PasswordService, ProfileService, RegistrationService
FCMService <- Kreait Firebase messaging (CONFIRMED CODE VERIFIED)
FirebaseCredentialResolver <- Multi-strategy (dashboard -> ENV -> GOOGLE_APPLICATION_CREDENTIALS)
PaddleService <- generateFounderCheckoutLink(), mapStatusToTier() (CONFIRMED CODE VERIFIED)
SocialLoginService <- Google + Apple token verification
SubscriptionService, NotificationService, NotificationSettingsService
LearningService, EarTrainingService, QuizService, HomeService
CmsService, ReviewService, FaqService, SupportService
PreferencesService, UserProgressService, SystemSettingService
GuestDeviceService, GuestAnalyticsService, GuestFingerprintService
DashboardOverviewService, LearningElementFormatter
SentenceVisual\SentenceVisualMapper, SentenceVisualService, SentenceVisualValidator
ContentAccessConfig, CookieSettingsService

### Models (36)
User (Billable, HasApiTokens, LogsActivity — founder fields confirmed in code)
FirebaseToken, FounderReviewSubmission
EarTrainingStage, EarTrainingLevel, EarTrainingQuiz, EarTrainingQuestion
EarTrainingQuizAttempt, EarTrainingUserAnswer, EarTrainingUserProgress
EarTrainingExplanationTemplate
Learning, LearningGroup, LearningPage, LearningPageElement
LearningUserProgress, LearningChecklistProgress
Quiz, QuizAttempt, QuizQuestion
HomeModule, Faq, Review
BugReport, ContactSupport, FeatureSuggestion
SystemSetting, MailSetting, EmailLog, EmailTemplate
GuestDevice, GuestAccessSetting, GuestActivityLog
UserCookieSetting, UserNotificationSetting, UserPreference
ChunkUploadSession

### User Model Confirmed Fields (from actual code)
subscription_tier, paddle_id, paddle_customer
is_founder, founder_trial_ends_at, founder_review_completed
founder_checkout_link, founder_day25_sent_at, founder_day30_sent_at, founder_converted_at
Methods: hasActiveSubscription(), getSubscriptionTier(), isFounderTrialActive(), hasTier()

---

## CONFIRMED API ROUTE INVENTORY (81 routes)

### Public / Guest Routes
POST   /api/register                        Auth\RegisterController@register
POST   /api/login                           Auth\LoginController@login
POST   /api/email/verify                    Auth\RegisterController@verifyEmail
POST   /api/email/verify/resend             Auth\RegisterController@resendEmailVerifyOTP
POST   /api/password/forgot                 Auth\RegisterController@forgotPassword
POST   /api/password/forgot/verify          Auth\RegisterController@verifyForgotPasswordOTP
POST   /api/password/reset                  Auth\RegisterController@resetPassword
POST   /api/social/login                    SocialLogin\SocialLoginController@socialLogin
POST   /api/social/apple/callback           SocialLogin\SocialLoginController@redirectCallbackApple
POST   /api/guest/identify                  Guest\GuestDeviceController@identify
GET    /api/guest/device                    Guest\GuestDeviceController@device
GET    /api/system-setting                  SystemSetting\SystemSettingController@systemSetting
GET    /api/cms/about-update                SystemSetting\UpdateAlertApiController

### Authenticated Routes (Bearer token required)
POST   /api/logout                          Auth\LoginController@logout
POST   /api/logout/all                      Auth\LoginController@logoutAll
GET    /api/profile                         Auth\ProfileUpdateController@profile
POST   /api/profile/details                 Auth\ProfileUpdateController@updateDetails
POST   /api/profile/change-password         Auth\ProfileUpdateController@changePassword
POST   /api/profile/delete-account          Auth\ProfileUpdateController@accountDelete
POST   /api/profile/download-my-data        Auth\ProfileUpdateController@downloadMyData
GET    /api/profile/manage-account          Auth\ProfileUpdateController@manageAccount
GET    /api/home                            API\HomeController@index
GET    /api/learnings                       API\LearningController@index
GET    /api/learnings/lessons               API\LearningController@lessons
GET    /api/learnings/core-theory           API\LearningController@coreTheory
GET    /api/learnings/advanced-insights     API\LearningController@advancedInsights
GET    /api/learnings/fnh-architecture      API\LearningController@fnhArchitecture
GET    /api/learnings/case-studies          API\LearningController@caseStudies
GET    /api/learnings/show/{id}             API\LearningController@show
GET    /api/learnings/summary/{id}          API\LearningController@summary
POST   /api/learnings/completed             API\LearningController@complete
POST   /api/learnings/next                  API\LearningController@nextLearning
POST   /api/learnings/previous              API\LearningController@previousLearning
POST   /api/learnings/checklist/update      API\LearningController@updateChecklist
GET    /api/ear-training/stages             EarTraining\EarTrainingApiController@stages
GET    /api/ear-training/stages/{id}/levels EarTraining\EarTrainingApiController@levels
POST   /api/ear-training/submit/{levelId}   EarTraining\EarTrainingApiController@submit
GET    /api/ear-training/explanation-templates
GET    /api/ear-training/levels/quizzes/{id}
GET    /api/ear-training/quizzes/questions/{quizId}
GET    /api/quiz/questions                  Quiz\QuizApiController@questions
GET    /api/quiz/by-learning/{id}           Quiz\QuizApiController@byLearning
GET    /api/quiz/by-lesson/{id}             Quiz\QuizApiController@byLearning
POST   /api/quiz/submit/{learning_id}       Quiz\QuizApiController@submit
POST   /api/quiz/check-answer               Quiz\QuizApiController@checkAnswer
GET    /api/quiz/review/{attempt_id}        Quiz\QuizApiController@review
GET    /api/quiz/review-by-learning/{id}    Quiz\QuizApiController@reviewByLearning
POST   /api/quiz/retry/{learning_id}        Quiz\QuizApiController@retry
GET    /api/quiz/attempt-details/{id}       Quiz\QuizApiController@attemptDetails
GET    /api/notifications                   Notification\NotificationController@index
POST   /api/notifications/{id}/mark-as-read Notification\NotificationController@markAsRead
POST   /api/notifications/mark-all-as-read  Notification\NotificationController@markAllAsRead
POST   /api/notifications/send              Notification\NotificationController@sendCustom [ADMIN ONLY]
GET    /api/notification-settings-show      Notification\NotificationSettingsController@show
POST   /api/notification-settings-update    Notification\NotificationSettingsController@update
POST   /api/firebase-token/add              PushNotification\FirebaseTokenController@updateFirebaseToken
POST   /api/firebase-token/delete           PushNotification\FirebaseTokenController@deleteFirebaseToken
GET/POST /api/subscription/checkout         Subscription\SubscriptionController@checkout
GET    /api/subscription/status             Subscription\SubscriptionController@status
GET    /api/founder/status                  Founder\FounderController@status
POST   /api/founder/review                  Founder\FounderController@submitReview
GET    /api/user/progress                   UserProgress\UserProgressController
GET    /api/preferences                     Preferences\PreferencesController@index
POST   /api/preferences                     Preferences\PreferencesController@store
GET    /api/faq                             Faq\FaqController@index
GET    /api/cms/about-numonix               Cms\AboutNumoniXApiController
GET    /api/cms/glossary                    Cms\GlossaryApiController
GET    /api/cms/complete-glossary           Cms\CompleteGlossaryApiController
GET    /api/cms/privacy-policy              Cms\PrivacyPolicyApiController
GET    /api/cms/terms-conditions            Cms\TermsConditionsApiController
GET    /api/cms/user-guide                  Cms\UserGuideApiController
GET    /api/cookie-settings-show            Cookie\CookieSettingsController
POST   /api/cookie-settings-update          Cookie\CookieSettingsController
GET    /api/reviews                         Review\ReviewController@index
POST   /api/reviews-store                   Review\ReviewController@store
POST   /api/reviews-update/{id}             Review\ReviewController@update
DELETE /api/reviews-delete/{id}             Review\ReviewController@destroy
POST   /api/support/contact                 Support\SupportController@contact
POST   /api/support/bug-report              Support\SupportController@reportBug
POST   /api/support/feature-suggestion      Support\SupportController@suggestFeature
GET    /api/dashboard/overview              DashboardView\DashboardOverviewController

ALSO VERIFY (may be in web.php or routes/settings.php):
POST   /paddle/webhook                      Paddle webhook with Ed25519 signature verification

---

## CONFIRMED FLUTTER FEATURE MODULES

authentication (login, register, social login, OTP, password reset)
subscription (tier check, checkout link, subscription status)
notification (list, mark read, notification settings)
notification_settings
home
functional_ear_training (v2 API: ear-training/stages)
course / lesson / quiz
advanced_insights, core_theory, fn_architecture, case_study_analysis
faq, help_support
profile, manage_account, rate_numonix
app_update
progress

Flutter data flow:
  Screen/Widget -> GetX Controller -> Repository -> API Service (Dio)
  -> Endpoints class (generates full URL) -> Interceptors (auth header, error handling)
  -> Response -> Model.fromJson() -> GetX reactive state -> UI rebuild

---

## SECURITY REQUIREMENTS

### Non-Negotiable Controls
1. Server-side authorization on EVERY endpoint — never trust client claims
2. IDOR: verify resource ownership before returning data
3. Mass assignment: $fillable must NOT include is_admin, subscription_tier, is_founder
4. Paddle webhook: Ed25519 signature MUST be verified before any processing
5. Firebase ID token: MUST be verified server-side — never trust raw client token
6. Admin notification sender: MUST require admin role — 403 for all others
7. APP_DEBUG=false on production
8. No secrets in Flutter source code — use secure storage for tokens
9. No firebase-credentials.json in git — delete it

### Security Test Matrix (minimum required, record PASS/FAIL/BLOCKED + evidence)

| Test | Target | Expected |
|------|--------|----------|
| SQL injection | All text inputs | 422 / no data leak |
| Mass assignment (is_admin) | POST /api/register | Field ignored |
| Mass assignment (subscription_tier) | POST /api/profile/details | Field ignored |
| IDOR | GET /api/profile with User B token | 403 |
| IDOR notifications | GET /api/notifications as different user | Only own data |
| Auth bypass | Any auth endpoint without token | 401 |
| Privilege escalation horizontal | User A -> User B data | 403 |
| Privilege escalation vertical | Normal user -> admin notification sender | 403 |
| Paddle webhook forge | Invalid Ed25519 signature | 400 or 403 |
| Paddle webhook replay | Duplicate event_id | 200 idempotent, no double process |
| Payment state client manipulation | Send subscription_tier:tier_2 in request body | Ignored |
| Firebase token bypass | Submit fake Google ID token | 401 |
| Brute force login | 10+ rapid failed logins | 429 |
| XSS | Submit script tag in support message | Escaped in response |
| Path traversal | ../../etc/passwd in any parameter | 400 or 403 |
| Stripe env exposure | Check .env for STRIPE_* keys | Should not exist |
| firebase-credentials.json in repo | git ls-files | File not found |

---

## EXECUTION METHODOLOGY — BOUNDED SESSIONS

Work in bounded sessions. At the end of every session:
1. Update all checkpoint files (see below)
2. Provide plain-language summary: what was inspected, what was fixed, what was tested, what remains, exact next action

### SESSION 1 — AUDIT ONLY (no implementation)
Read both PDFs completely
Extract every requirement -> NUMONIX_REQUIREMENTS_MATRIX.md
Inventory backend file-by-file
Inventory Flutter file-by-file
Map Flutter <-> Laravel: every call -> route -> controller -> service -> DB
List endpoints Flutter calls that don't exist in backend
List endpoints in backend that Flutter never calls
Audit auth/authz, Paddle, Firebase, email, founder, admin dashboard
Document every issue (severity, file, line, root cause, exploit, impact, fix)
Create NUMONIX_REMEDIATION_PLAN.md ordered by priority
Create NUMONIX_API_MATRIX.md (all 81 routes verified)
Create all checkpoint files
STOP — deliver audit report. Do NOT implement anything yet.

### SESSION 2 — Fix Error 1: Flutter API Connectivity (P0)
Inspect proguard-rules.pro, add missing keep rules
Verify key.properties for release signing
Verify google-services.json present and correct
Build release APK, install on emulator, run adb logcat to confirm API works
flutter analyze must pass

### SESSION 3 — Fix Error 2: Google Login
Server-side Firebase token verification in SocialLoginController
Flutter sends Firebase ID token (not Google access token)
Test: new user, existing user, cancelled, invalid token, logout

### SESSION 4 — Fix Error 3: Apple Login
Implement backend Apple handling ready for credentials
Implement Flutter sign_in_with_apple -> Firebase -> ID token -> /api/social/login
Mark end-to-end as BLOCKED — document exactly what credentials are needed

### SESSION 5 — Fix Error 4: Notifications
Clear FIREBASE_CREDENTIALS old Windows path from .env
Confirm dashboard upload works (FirebaseCredentialResolver)
FCM token registration on login and refresh
Flutter handlers: onMessage, onMessageOpenedApp, onBackgroundMessage
Admin sender Blade view: verify exists with correct form + authorization
Security test: 403 for normal users on notification send

### SESSION 6 — Paddle Audit and Completion
Confirm POST /paddle/webhook exists with Ed25519 verification
Confirm SubscriptionController@checkout creates Paddle checkout (not Stripe)
Confirm lifecycle events update subscription_tier
Confirm Flutter subscription screen opens numonix.app in external browser
Idempotency test: duplicate webhook must not double-process
Security: modified price, modified user_id, replayed webhook -> all rejected

### SESSION 7 — Founder Programme
Verify all founder fields in migration match User model
Verify CSV import command creates user + founder flag + Tier 2 + trial start
Verify SendFounderDay25Email job scheduled and sends to ALL founders
Verify GBP 24.99 unique Paddle checkout link per-founder
Verify cancellation -> subscription_tier = tier_1 at period end
Test complete founder journey end-to-end

### SESSION 8 — Remove Stripe Completely (Error 6 partial)
Search both repos: Stripe stripe payment_intent stripePayment stripe_webhook STRIPE_
Remove: STRIPE_* from .env and .env.example
Remove: any remaining Stripe config references
Verify nothing Paddle-related breaks

### SESSION 9 — Remove Unused Files and Code (Error 6)
Delete firebase-credentials.json if found anywhere
Remove dead Dart imports, unused Flutter dependencies
php artisan cache:clear, config:clear, route:clear, view:clear
Remove debugPrint/print calls from Flutter production code
Remove dd/dump/die from PHP production code
Remove TODO/FIXME/HACK that represent actual incomplete work

### SESSION 10 — Full Alignment with PDFs (Error 7)
Re-read both PDFs line by line
For every requirement: verify implementation in backend AND Flutter
Document any mismatch or gap
Fix all gaps found
Update NUMONIX_REQUIREMENTS_MATRIX.md with final status

### SESSION 11 — Transactional Email
Verify mail config connects to mail.thewarriors.team:465:ssl
Confirm all email templates: Welcome, Founder Onboarding, Day-25 Reminder, Subscription Confirmation, Password Reset
Confirm emails dispatched via queue (not inline Mail::send)
Test password reset flow end-to-end

### SESSION 12 — Security Pass (Error 5 security portion)
Execute full security test matrix above
Record PASS/FAIL/BLOCKED with evidence for each
Fix all FAIL items

### SESSION 13 — Static Analysis + Automated Tests (Error 5)
Backend:
  php artisan about
  php artisan route:list
  composer validate
  composer audit
  php artisan test --stop-on-failure
Flutter:
  flutter pub get
  flutter analyze (zero errors required)
  flutter test (all pass)
  flutter build apk --release
  flutter build appbundle --release
Fix ALL failures.

### SESSION 14 — Emulator + Release APK Runtime Testing
flutter doctor -v
flutter devices
flutter clean && flutter pub get
flutter run (debug — confirm API works)
flutter build apk --release
adb install build/app/outputs/flutter-apk/app-release.apk
Test on release APK: launch, register, login, Google login, API calls,
FCM notifications, subscription status, upgrade link, logout, restart

### SESSION 15 — Full Regression + Final Audit
Re-read both PDFs
Re-run all tests
Re-run security matrix
Confirm no new vulnerabilities from fixes
Produce final engineering report

---

## RESUMABLE SESSION PROTOCOL

At the start of EVERY session:
1. Read NUMONIX_AUDIT_CHECKPOINT.md
2. Read NUMONIX_REQUIREMENTS_MATRIX.md
3. Read NUMONIX_REMEDIATION_PLAN.md
4. Read NUMONIX_SECURITY_FINDINGS.md
5. Read NUMONIX_TEST_RESULTS.md
6. Verify actual repository state matches checkpoint
7. Resume from next_exact_action field
8. If conflict: actual repository code is SOURCE OF TRUTH

Create and maintain these files (never store secrets in them):
- NUMONIX_AUDIT_CHECKPOINT.md
- NUMONIX_AUDIT_STATE.json
- NUMONIX_REQUIREMENTS_MATRIX.md
- NUMONIX_REMEDIATION_PLAN.md
- NUMONIX_SECURITY_FINDINGS.md
- NUMONIX_TEST_RESULTS.md
- NUMONIX_API_MATRIX.md
- NUMONIX_FINAL_REPORT.md

Store all checkpoint files in both project roots OR in a dedicated audit folder.

Checkpoint must contain:
{
  "current_phase": "",
  "current_subphase": "",
  "phase_status": "",
  "last_completed_step": "",
  "last_completed_file": "",
  "next_exact_action": "",
  "issues_found": [],
  "issues_fixed": [],
  "tests_passed": [],
  "tests_failed": [],
  "blocked_items": [],
  "backend_status": "",
  "flutter_status": "",
  "paddle_status": "",
  "firebase_status": "",
  "notification_status": "",
  "google_login_status": "",
  "apple_login_status": "BLOCKED — needs APPLE_CLIENT_ID, APPLE_TEAM_ID, APPLE_KEY_ID, APPLE_PRIVATE_KEY",
  "release_apk_status": "",
  "stripe_removal_status": "",
  "firebase_credentials_cleanup": "",
  "requirements_implemented": 0,
  "requirements_partial": 0,
  "requirements_missing": 0,
  "requirements_blocked": 0,
  "last_updated": ""
}

Update checkpoint BEFORE stopping each session.

---

## MAXIMUM DEBUGGING BOUNDARY

For a single defect: maximum 3 meaningful remediation attempts without new root-cause evidence:
- Attempt 1 -> Test
- Attempt 2 (new hypothesis) -> Test
- Attempt 3 (different approach) -> Test
- All fail -> STOP -> Document -> BLOCKED/PARTIAL -> Define next investigation

Never repeat the same approach indefinitely. Never enter infinite loops.

---

## PHASE GATE RULES

A phase cannot be approved while any of the following are true:
- Backend app throws 500 on any non-error route
- php artisan test has failures
- flutter analyze has errors
- flutter test has failures
- Any critical API returns wrong status code
- Authentication bypass exists
- Admin notification sender reachable by normal users
- firebase-credentials.json exists anywhere in the repo
- STRIPE_* keys remain in .env

---

## EXTERNAL BLOCKERS (known, confirmed)

| Blocker | What is Needed | Status |
|---------|---------------|--------|
| Apple Login | APPLE_CLIENT_ID, APPLE_TEAM_ID, APPLE_KEY_ID, APPLE_PRIVATE_KEY, APPLE_REDIRECT_URI | BLOCKED |
| Firebase Credentials | Admin uploads service account JSON via admin dashboard | BLOCKED - awaiting upload |
| Paddle Price ID | cashier.founder_price_id config value — client provides GBP 24.99 price ID | BLOCKED |
| Paddle Webhook Secret | Ed25519 public key / webhook secret from Paddle dashboard | BLOCKED |
| Google Sign-In SHA-1 | Debug + release SHA-1 registered in Firebase console for google-services.json | Verify |
| Production server | MySQL at 127.0.0.1:3306 with correct credentials, Nginx, PHP-FPM | Deployment-time |
| SPF/DKIM/DMARC | DNS records for numonix.app and thewarriors.team | MANUAL/EXTERNAL |
| Apple App Store | App Store Connect setup, certificates, provisioning profiles | MANUAL/EXTERNAL |
| Google Play Store | Play Console setup, release track, content rating | MANUAL/EXTERNAL |

---

## FINAL DELIVERABLE STRUCTURE

At true completion (not before), produce NUMONIX_FINAL_REPORT.md containing:

1. Executive Summary (what inspected / fixed / tested / remains)
2. Architecture Map (Flutter -> Laravel -> DB -> Paddle -> Firebase -> FCM -> Flutter)
3. Complete Issues Table (Severity | Component | File | Issue | Fix | Status)
4. Security Test Matrix (Attack | Result | Evidence)
5. Payment Audit (Paddle flow confirmed + Stripe/RevenueCat removal confirmed)
6. Full API Matrix (all 81 endpoints: method, auth, Flutter consumer, validation, tested)
7. PDF Requirements Matrix (every requirement from both client PDFs with status)
8. Founder Programme Audit
9. Notification Audit (push + real-time + admin sender with test evidence)
10. Google Login Audit with evidence
11. Apple Login Audit (mark end-to-end BLOCKED with explanation)
12. Flutter Test Results (flutter analyze + flutter test + build apk + build appbundle output)
13. Backend Test Results (composer audit + php artisan test + route:list output)
14. Emulator + Release APK Test Results
15. Remaining Risks (Resolved / Partial / Blocked / External)
16. Final Status Block (counts by severity, by category — see format below)
17. Exact backend deployment commands for production server
18. Exact Flutter release build commands

### Final Status Block Format

TOTAL REQUIREMENTS: ?
- IMPLEMENTED: ?
- PARTIAL: ?
- MISSING: ?
- BROKEN: ?
- BLOCKED: ?
- MANUAL/EXTERNAL: ?

CRITICAL ISSUES: ? | HIGH: ? | MEDIUM: ? | LOW: ?

BACKEND TESTS: PASSED ? / FAILED ? / BLOCKED ?
FLUTTER TESTS: PASSED ? / FAILED ? / BLOCKED ?
API TESTS: PASSED ? / FAILED ? / BLOCKED ?
SECURITY TESTS: PASSED ? / FAILED ? / BLOCKED ?
INTEGRATION TESTS: PASSED ? / FAILED ? / BLOCKED ?

EMULATOR: PASS / FAIL / BLOCKED
RELEASE APK: PASS / FAIL / BLOCKED
RELEASE AAB: PASS / FAIL / BLOCKED
PADDLE: PASS / FAIL / BLOCKED
FIREBASE: PASS / FAIL / BLOCKED
GOOGLE LOGIN: PASS / FAIL / BLOCKED
APPLE LOGIN: BLOCKED (credentials not provided)
PUSH NOTIFICATIONS: PASS / FAIL / BLOCKED
REAL-TIME NOTIFICATIONS: PASS / FAIL / BLOCKED
CUSTOM ADMIN NOTIFICATION SENDER: PASS / FAIL / BLOCKED
ADMIN DASHBOARD: PASS / FAIL / BLOCKED

Final Verdict — select exactly one:
- APPROVED FOR PRODUCTION
- NOT APPROVED — CRITICAL/HIGH ISSUES REMAIN
- NOT APPROVED — EXTERNAL DEPENDENCIES BLOCK FINAL VALIDATION

---

## PRODUCTION APPROVAL GATE — NEVER APPROVE WHILE ANY OF THESE ARE TRUE

- Flutter release APK cannot reach https://api.numonix.app/api/
- Auth bypass, IDOR, or injection vulnerability exists
- Paddle webhook can be forged or replayed
- RevenueCat runtime code remains anywhere
- Stripe runtime code remains anywhere (env keys also count)
- Admin notification sender reachable by non-admins
- firebase-credentials.json exists in the repository
- Any client PDF requirement unaccounted for
- Critical automated test failing
- Release APK cannot build, install, or connect
- Admin dashboard has broken functionality
- Any model/migration mismatch causing runtime errors

---

## ABSOLUTE WORKING RULES

1. DO NOT merely analyze — fix the code
2. DO NOT assume something works because a file exists
3. DO NOT skip files because the repository is large
4. DO NOT disable TLS or bypass certificate validation
5. DO NOT trust client-supplied payment/subscription/tier/ownership data
6. DO NOT store secrets in Flutter source code
7. DO NOT bypass Laravel authorization for convenience
8. DO NOT mark a test PASS without actually executing it or having objective evidence
9. DO NOT fabricate Paddle transactions, Firebase delivery, or API responses
10. DO NOT run destructive DB operations against anything but local/test database
11. DO NOT expand scope silently — record new findings, continue current task
12. DO NOT repeat the same fix approach more than 3 times without new root-cause evidence
13. DO NOT declare complete while anything critical is FAIL / BLOCKED / untested
14. ALWAYS update checkpoint files before stopping a session
15. ALWAYS test after fixing — then run regression
16. ALWAYS mark BLOCKED with exact list of what is needed to unblock

---

START NOW: Read both PDFs completely, verify both repos, inventory both projects,
build requirements matrix, API map, architecture map, initial security findings.

SESSION 1 IS AUDIT-ONLY — do NOT implement or change code yet.
Produce the Session 1 audit deliverable, then STOP.

Generated from verified repository inspection: 2026-10-03
Backend: D:\Projects\Herd\lee-backend-work | Flutter: D:\Projects\Herd\lee-flutter-work
