> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pcm.game/llms.txt
> Use this file to discover all available pages before exploring further.

# Sprint 20

# Sprint 21 Housekeeping - Implementation Plan

This implementation plan covers the Sprint 21 housekeeping goals to resolve documentation debt and desynchronization within our Mintlify setup. **No execution will take place until this plan is explicitly approved.**

***

## User Review Required

> \[!NOTE]
> All actions outlined below are safe, low-risk housekeeping operations focused on cleaning up historical files and synchronizing the Mintlify documentation structure. No source code or database functionality will be affected.

***

## Proposed Changes

### Component: Documentation Structure & Retrospectives

We will move, create, and modify various files in the `docs` and root directories.

#### \[NEW] [sprint-19.mdx](file:///home/andrew/pcmtg-core/docs/sprint-19.mdx)

* Draft the Sprint 19 (Identity Hydration & Precision Math) retrospective, capturing key achievements such as the transition to double-precision float Euclidean tie-breaker math and identity hydration across Firestore lobbies.

#### \[NEW] [sprint-20.mdx](file:///home/andrew/pcmtg-core/docs/sprint-20.mdx)

* Draft the Sprint 20 (The Shadow Logger & Diagnostic Observability) retrospective, summarizing key developments such as centralized Prisma client query hooking, HTTP shadow middleware logging, asynchronous BigQuery telemetry sinks, and the conditional glassmorphic "God Mode" overlay.

#### \[MODIFY] [mint.json](file:///home/andrew/pcmtg-core/docs/mint.json)

* Update Mintlify navigation configuration to register newly created sprint retrospectives and correctly mapped implementation plans.
* Add `sprint-18`, `sprint-19`, and `sprint-20` to the `"III. Roadmaps"` group.
* Update `"VI. Sprint Artifacts"` to include:
  * `"implementation/implementation_plan_18.1"`
  * `"implementation/implementation_plan_18.2"`
  * `"implementation/sprint-20"`
  * Keep `"walkthrough"` and `"implementation/sprint-15"` intact.

***

### Component: Relocated Implementation Plans

We will move existing misplaced implementation plans to their correct subdirectories.

#### \[NEW] [implementation\_plan\_18.1.md](file:///home/andrew/pcmtg-core/docs/implementation/implementation_plan_18.1.md)

* Relocated copy of `docs/implementation_plan_18.1.md`.

#### \[NEW] [implementation\_plan\_18.2.md](file:///home/andrew/pcmtg-core/docs/implementation/implementation_plan_18.2.md)

* Relocated copy of `docs/implementation_plan_18.2.md`.

#### \[NEW] [sprint-20.md](file:///home/andrew/pcmtg-core/docs/implementation/sprint-20.md)

* Relocated copy of root `implementation_plan.md` representing the Sprint 20 plan.

#### \[DELETE] [implementation\_plan\_18.1.md](file:///home/andrew/pcmtg-core/docs/implementation_plan_18.1.md) (from source `docs/implementation_plan_18.1.md`)

* Clean up original file after relocation.

#### \[DELETE] [implementation\_plan\_18.2.md](file:///home/andrew/pcmtg-core/docs/docs/implementation_plan_18.2.md) (from source `docs/implementation_plan_18.2.md`)

* Clean up original file after relocation.

#### \[DELETE] [implementation\_plan.md](file:///home/andrew/pcmtg-core/implementation_plan.md) (from source `implementation_plan.md`)

* Clean up original file after relocation.

***

## Draft Contents

Below are the drafted contents for the two new retrospective files to be reviewed.

### `docs/sprint-19.mdx`

```markdown theme={null}
---
title: "Sprint 19: Identity Hydration & Precision Math"
description: "Implementation of double-precision float Euclidean math for tournament tie-breakers and correct contender identity hydration across game states."
---

# Sprint 19: Identity Hydration & Precision Math

Following Sprint 18's intense focus on E2E testing, security audits, and system validation, Sprint 19 targets key game-theoretic calculation accuracy and UI identity precision. This sprint eliminates edge-case math issues in tie-breakers and removes frustrating "Anonymous" fallbacks on the leaderboard and active table interfaces.

## 🛠 Context & Required Skills for AI Agents
When operating within Sprint 19 context:
1. **Mathematical Rigor**: All calculations regarding ELO or Euclidean space must maintain absolute precision to prevent rounding errors from determining tournament winners.
2. **Deterministic Identity Syncing**: Player names and bot identifiers must be hydrated on state transitions rather than on demand. The client-side must never guess player usernames; they must be hydrated directly in the Firestore transaction payload.

---

## 🗺 Sprint 19 Roadmap

### [x] Phase 1: Euclidean Distance Precision Calculations
- **Objective**: Re-architect combat resolution math to support double-precision float calculations for tie-breaker logic.
- **Tasks**:
  - Replaced low-precision rounded coordinate distance calculation with high-precision double-precision float Euclidean math for tournament tie-breakers.
  - Ensured display values show full precision in the logs and terminal to allow visual verification of tie-breaking results while maintaining transactional safety limits at the DB layer.

### [x] Phase 2: Identity Hydration on Game State
- **Objective**: Clean up generic "Anonymous Contender" and "Anonymous Voter" fallbacks on leaderboards and ActiveTable sessions.
- **Tasks**:
  - Refactored Ghost Bot instantiation scripts to inject structured `botNames` directly during active lobby creation.
  - Implemented automatic user profile database fetches to map real players' Firebase accounts, hydrating verified usernames directly onto Firestore collection table records.

---

## 🏁 Retrospective & Conclusion

Sprint 19 successfully resolved core calculation inaccuracies and fixed lingering player identification bugs. By integrating double-precision float calculations, we eliminate mathematical ambiguity in close matches and tournament tie-breakers. Furthermore, robust player and bot identity hydration across Firestore collections guarantees professional, polished UI states, elevating the competitive user experience to production-ready standards.
```

### `docs/sprint-20.mdx`

```markdown theme={null}
---
title: "Sprint 20: The Shadow Logger & Diagnostic Observability"
description: "Comprehensive backend HTTP boundary logging, full Prisma database query hooking, a robust asynchronous BigQuery diagnostic sink, and an admin-only God Mode interactive overlay."
---

# Sprint 20: The Shadow Logger & Diagnostic Observability

With our core game loop and economic mechanics locked down, Sprint 20 establishes a robust, enterprise-grade telemetry, audit, and diagnostic observability layer. This ensures absolute visibility into our high-velocity, serverless-deployed digital economy without introducing runtime latency.

## 🛠 Context & Required Skills for AI Agents
When working inside this context:
1. **Zero-Trust Administrative Claims**: Administrative actions, such as fetching unredacted solution vectors, must never expose client-side Firestore rules bypasses. Rely on secure Express APIs that verify session-based administrative claims.
2. **Non-Blocking Observability**: Diagnostic operations must execute asynchronously in the background. Never let telemetry operations delay or block the HTTP boundary handshake.

---

## 🗺 Sprint 20 Roadmap

### [x] Phase 0: Database & Schema Provisioning
- **Objective**: Set up necessary database schema modifications to support admin flags and verbose log collection.
- **Tasks**:
  - Added the `is_admin` boolean column to the `PlayerAccount` Postgres model.
  - Programmatically provisioned the `VerboseDebugLogs` table inside the Google Cloud BigQuery data warehouse.

### [x] Phase 1: The HTTP Boundary (Shadow Middleware)
- **Objective**: Establish global route request and response payload capturing.
- **Tasks**:
  - Created global Express middleware `shadowLogger` to intercept `req.body` and hook `res.json` payloads.
  - Calculated exact route execution latencies using `process.hrtime()` and emitted flat Newline Delimited JSON (NDJSON) with appropriate GCP severities.

### [x] Phase 2: The Database Boundary (Prisma Hooking)
- **Objective**: Globally trace database query execution timings and queries.
- **Tasks**:
  - Enforced a central Prisma client configuration with strict connection pool limits (`max: 1`) suitable for serverless scale.
  - Built a global `$extends` query hook to audit query timings and emit structured logs to `stdout`.

### [x] Phase 3: The BigQuery Debug Sink
- **Objective**: Construct an asynchronous, non-blocking telemetry log pipeline.
- **Tasks**:
  - Built background-scheduled `TelemetryQueue` utilizing the BigQuery Storage Write API.
  - Added coordinate clamping breach checks that trigger `severity: "WARNING"` anomaly logs.
  - Hooked unhandled route exceptions to stream error call-stacks with `severity: "ERROR"` to BigQuery.

### [x] Phase 4: Client-Side "God Mode" Overlay
- **Objective**: Provide administrative visual tools in the Arena while preserving zero-trust security.
- **Tasks**:
  - Refactored `bouncer.js` session resolution to inject `req.isAdmin` claims on authenticated request sessions.
  - Implemented secure API endpoint `GET /debate/admin-vectors` to fetch active News Stub solution coordinate shifts.
  - Developed and conditionally rendered the glassmorphic `<AdminDebugPanel />` diagnostics overlay for authenticated administrators.

---

## 🏁 Retrospective & Conclusion

Sprint 20 successfully delivered absolute system-wide observability to the PCMTG monorepo. Through global HTTP shadow logging and Prisma client query extensions, we capture all boundary actions and database transaction speeds with minimal overhead. Our asynchronous BigQuery telemetry queue guarantees background shipping of diagnostic data, while our glassmorphic God Mode UI gives administrators precise interactive vector diagnostics safely wrapped inside a Zero-Trust claims architecture.
```

***

## Verification Plan

### Automated Verification

Since this sprint consists of non-executable doc files and a configuration adjustment (`mint.json`), we will verify that Mintlify compiles and has correct syntax:

* Verify JSON formatting of modified `docs/mint.json`:
  ```bash theme={null}
  python3 -m json.tool docs/mint.json
  ```

### Manual Verification

* Verify that no compilation or structural issues are present in the documentation sidebar when viewed locally.
* Confirm all relocated files exist in `docs/implementation/...`.
