# ANBT Backend — Reality Audit Report

**Audit timestamp:** 2026-08-28T09:25–09:29 UTC+03:30  
**Branch:** `feat/arch-upgrade-phase-0-2`  
**PHP runtime:** 8.2.12 (XAMPP on Windows 11)  
**DB server:** MariaDB 10.4.32 (`anode_battery`)  
**Auditor:** Antigravity agent — read-only, zero file modifications

---

## 1 — Git State

| Item | Value |
|------|-------|
| Current branch | `feat/arch-upgrade-phase-0-2` |
| Uncommitted changes | `D lib.zip` (deleted, unstaged) |
| Untracked files | `junit.xml`, `phpunit_output.txt`, `test_output.txt` |
| Last 5 commits | `6549cae`, `a5abeda`, `8372484`, `afc77fc`, `f789455` |

> [!NOTE]
> Working tree is effectively clean for tracked source files. The deleted `lib.zip` and untracked txt files do not affect backend functionality.

---

## 2 — Migration Chain

### Migration directory layout

| Directory | Files | Status |
|-----------|-------|--------|
| `database/migrations/` | **0** (only `.gitkeep`) | **EMPTY — active runner has nothing to run** |
| `database/migrations-legacy/` | **68 SQL files** | All actual migrations live here |

> [!CAUTION]
> `migrate.php --status` reports **"completed NO FILE"** because the active `migrations/` directory is empty. All 68 migrations are in `migrations-legacy/`, which `migrate.php` does NOT read by default. This means:
> - A fresh `migrate.php` run would apply **zero** migrations.
> - The schema_migrations ledger entry "completed" with "NO FILE" is anomalous.
>
> **Investigation required before Phase 1 begins.**

### Migration numbering (migrations-legacy)

| Issue | Detail |
|-------|--------|
| Duplicate prefix **08** | `08_orders.sql` + `08b_products.sql` |
| Duplicate prefix **32** | `32_partner_ampere_accounts.sql` + `32b_add_blocked_reason…sql` |
| Duplicate prefix **56** | `56_create_used_battery_rates_table.sql` + `56b_create_brand_ampere_rates.sql` |
| **EXACT DUPLICATE name** prefix **59** | `58_create_partner_checks_table.sql` + `59_create_partner_checks_table.sql` — **same name, consecutive numbers** |
| Missing numbers | **18**, **62**, **63** |
| `SET FOREIGN_KEY_CHECKS` in migration files | **NONE** ✅ |

> [!WARNING]
> `58` and `59` have the **same table name** (`partner_checks`). This is likely a BUG-30 artifact. Must be verified before Phase 1.

### Dead-letter / queue tables in migrations

| File | Reference |
|------|-----------|
| `44_image_processing_jobs.sql` | Contains `jobs` reference |
| `dead_letter_jobs` table | **NOT present** in any migration file |

### Migration git history (migrations-legacy)

```
f789455  refactor(security): complete phase 6 hardening
4287304  fix(db): add missing blocked_reason column (BUG-28)
622074d  fix(db): remove redundant partner_checks version (BUG-30)
846fd83  fix(db): rebuild stock_audit_items (BUG-23,24,27)
e5aa25c  fix(db): make audit permissions migration idempotent (BUG-20)
44b1f32  fix(db): move products migration before dependents (BUG-22)
ccdba40  fix(db): correct partner_checks migration ordering (BUG-7)
3b8f0fb  fix(db): add missing brand_ampere_rates create migration (BUG-19)
```

---

## 3 — Schema Drift

| Item | Status |
|------|--------|
| `database/schema_dump.sql` | EXISTS (23 791 bytes) |
| `database/test_schema_dump.sql` | EXISTS (9 460 bytes) |
| `database/ANBT_SCHEMA_REFERENCE.sql` | EXISTS (121 013 bytes) |
| Automated drift check | **NOT run** — `schema-drift.php` tool absent; requires Phase 1 |

> [!IMPORTANT]
> A live schema drift comparison (migrations-legacy → information_schema) must be done in Phase 1. The auditor cannot confirm zero drift from this read-only pass.

---

## 4 — Routes vs OpenAPI

| Item | Count |
|------|-------|
| Route registrations in `admin.php` | **128** |
| Route registrations in `api.php` | **55** |
| **Total routes** | **183** |
| OpenAPI 3.1 paths in `docs/openapi.json` | **157 paths** |
| OpenAPI operations | **183** |
| Routes missing from OpenAPI spec | **0** ✅ |

> [!NOTE]
> The route-file→OpenAPI direction shows 0 gaps, but the **reverse** (OpenAPI→routes) requires a stricter bidirectional check with full field verification (path params, auth, request/response schema, ERR_* codes) in Phase 2.

---

## 5 — Static Analysis (PHPStan)

| Item | Value |
|------|-------|
| Configured level | **6** |
| Target level | **8** |
| Errors at level 6 | **0** ✅ |
| Gap | Levels 7 and 8 not yet passing — **not measured** |

> [!WARNING]
> PHPStan is configured at level 6. The Playbook target is level 8. The audit cannot confirm level 8 compliance without running at level 8. This is a **Phase 7 / Phase 12** prerequisite.

---

## 6 — PHPUnit (All Suites)

| Suite | Tests | Assertions | Failures | Errors | Deprecations |
|-------|-------|------------|----------|--------|--------------|
| Unit | 74 | 178 | 0 | 0 | 19 |
| Architecture | 30 | 589 | 0 | 0 | 0 |
| All suites combined | **197** | **1 229** | **0** | **0** | **29** |

> [!NOTE]
> All 197 tests pass. 29 PHPUnit deprecation warnings exist — these are non-fatal but should be addressed before the next major PHPUnit upgrade.

---

## 7 — Coverage

| Item | Value |
|------|-------|
| Covered statements | 3 761 |
| Total statements | 10 372 |
| **Line coverage** | **36.26%** |
| Target | ≥ 75% |
| Gap | **38.74 percentage points** |

---

## 8 — Service Locator & Controller SQL

| Metric | Value | Target |
|--------|-------|--------|
| Service Locator usages outside `src/Core/` | **0** ✅ | 0 |
| Controllers with raw PDO SQL | **0** ✅ | 0 |
| Controllers > 200 lines | **needs manual recount** (audit script path issue) | 0 |

> [!NOTE]
> The automated controller line-count scan returned 0 controllers because the glob pattern for `Http/Controllers` did not match. A corrected scan is needed in Phase 1.

---

## 9 — Queue Implementation

| Component | Status |
|-----------|--------|
| `JobQueueInterface` | **MISSING** |
| `DatabaseJobQueue` | **MISSING** |
| `RedisJobQueue` | **MISSING** |
| `bin/worker.php` | **MISSING** |
| `dead_letter_jobs` migration | **MISSING** |
| `SELECT … FOR UPDATE SKIP LOCKED` usage | **MISSING** |
| Existing job reference | `44_image_processing_jobs.sql` contains jobs table |

---

## 10 — Stateless Runtime / File-Based Rate Limiter

| Component | Status |
|-----------|--------|
| `FileRateLimiter` | **EXISTS** (`src/Common/Service/FileRateLimiter.php`) |
| `RedisRateLimiter` | EXISTS — used when `REDIS_HOST` is set |
| Fallback strategy | Silent fallback to `FileRateLimiter` when Redis absent |
| Checks `APP_ENV` | **NO** |
| Production fail-fast on missing Redis | **NO** — silently falls back |
| `.env` current | `REDIS_HOST=` (empty — file-based in use locally) |

> [!WARNING]
> The current `ContainerFactory::buildRateLimiter()` silently falls back to `FileRateLimiter` when `REDIS_HOST` is unset, regardless of `APP_ENV`. In production this means no-Redis = no hard failure, violating Phase 3 requirement.

---

## 11 — Observability

| Component | Status |
|-----------|--------|
| `health/live` endpoint | **MISSING** |
| `health/ready` endpoint | **MISSING** |
| `/metrics` endpoint | **MISSING** |
| X-Request-Id propagation | **FOUND** (partial) |
| Structured JSON logging | **MISSING** |
| OpenTelemetry instrumentation | **MISSING** |
| Alert signals | **MISSING** |
| `LOG_CHANNEL=stdout` | Not configured |

---

## 12 — Security Tests

| Item | Status |
|------|--------|
| Architecture test suite | 30 tests, 589 assertions, all pass ✅ |
| Admin route permission map test | Included in architecture suite |
| Unsecured admin routes | Not separately measured — assumed 0 from arch tests |

---

## 13 — Ports / External Interfaces

| Interface | Status |
|-----------|--------|
| `SmsGatewayInterface` | **MISSING** |
| `PaymentGatewayInterface` | **MISSING** |
| `TokenIssuerInterface` | **MISSING** |
| `FileStorageInterface` | **MISSING** |
| `NotifierInterface` | **MISSING** |
| `ClockInterface` | **MISSING** |
| Total PHP interfaces in `src/` | **4** (vs target ≥ 12) |

---

## 14 — Mutation Testing

| Item | Status |
|------|--------|
| `infection.json` | **MISSING** |
| `infection.json.dist` | **MISSING** |
| `vendor/bin/infection` installed | **NO** |
| Accounting/Pricing MSI | **Not measured** |

---

## 15 — Final Acceptance Checklist (Baseline)

| Metric | Target | **Measured now** | Gap |
|--------|--------|-----------------|-----|
| CI green | Yes | Not measured (local only) | — |
| PHPStan level | 8 | **6** | +2 levels |
| Coverage | ≥ 75% | **36.26%** | −38.74pp |
| Service Locator outside Core | 0 | **0** ✅ | — |
| Controllers with raw SQL | 0 | **0** ✅ | — |
| Largest controller | ≤ 200 lines | **not measured** | TBD |
| Duplicate migration IDs | 0 | **3 shared-prefix pairs + 1 name collision** | ⚠ |
| Schema drift | 0 | **not measured** | TBD |
| Unsecured admin routes | 0 | **0** (assumed from arch tests) | — |
| Admin endpoint query count | ≤ 20 | **not measured** | TBD |
| OpenAPI route parity (→) | 100% | **100%** ✅ | — |
| OpenAPI parity (←, full field) | 100% | **not measured** | TBD |
| Production file-based state | 0 | **1** (FileRateLimiter always on) | ⚠ |
| Concurrency tests | PASS | **MISSING** | ⚠ |
| Trial balance | PASS | Test file found, status unknown | TBD |
| Interfaces (meaningful) | ≥ 12 | **4** | −8 |
| Accounting/Pricing MSI | ≥ 70% | **not measured** | TBD |
| X-Request-Id traceability | PASS | **partial** | ⚠ |

---

## 16 — Ordered Work Items (Phases 1–12)

| Phase | Priority | Key gaps to close |
|-------|----------|-------------------|
| **1** Schema & Migration | 🔴 CRITICAL | `migrations/` empty, `migrate.php --status` anomalous, duplicate prefixes 08/32/56, name collision 58/59, no schema-drift tool |
| **2** OpenAPI Contract | 🟡 HIGH | Reverse parity (OpenAPI→routes) not verified; full field check required |
| **3** Stateless Runtime | 🟡 HIGH | Silent Redis fallback in production; no fail-fast; `FileRateLimiter` used when `REDIS_HOST` empty |
| **4** Real Job Queue | 🟡 HIGH | All queue components missing (`JobQueueInterface`, `DatabaseJobQueue`, `RedisJobQueue`, `worker.php`, `dead_letter_jobs` migration) |
| **5** Query Budget | 🟡 HIGH | No `assertQueryCountLessThan`; no per-endpoint measurements |
| **6** Observability | 🟡 HIGH | All 6 substeps missing: logging, Correlation-ID, metrics, health probes, OTel, alerts |
| **7** Critical Unit Tests | 🟡 HIGH | Coverage 36.26% vs 75% target; priority classes not measured individually |
| **8** Concurrency Tests | 🟡 HIGH | `tests/Concurrency/` directory absent; 4 required scenarios missing |
| **9** Golden Trial Balance | 🟡 MEDIUM | Test file found but not verified; full flow not confirmed in CI |
| **10** Ports & Fakes | 🟡 MEDIUM | All 6 required ports missing; only 4 interfaces total in src/ |
| **11** Mutation Testing | 🟡 MEDIUM | `infection` not installed; no MSI measurement |
| **12** Final Gate | 🟢 LOW | After all above complete |

---

## 17 — Stop Conditions Identified

> [!CAUTION]
> The following conditions **must be resolved before Phase 1 code changes**:
>
> 1. **`migrations/` is empty, `migrate.php --status` = "completed NO FILE"** — The migration runner state is anomalous. Must determine: does `migrate.php` read from `migrations-legacy/` or `migrations/`? Which path does `schema_migrations` ledger reference?
> 2. **Name collision at prefix 59**: `58_create_partner_checks_table.sql` and `59_create_partner_checks_table.sql` have the same table name. This may indicate a BUG-30 residue that was not fully resolved.
> 3. **Missing numbers 18, 62, 63** — must verify via git history whether these were legitimately skipped or lost.

---

*This document was produced by read-only measurement only. No source files, migrations, configuration, or repository metadata were modified during this audit.*
