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

# System Architecture

> Runtime architecture, request lifecycles, data ownership, and operational concerns for LitigationLabs.

## Purpose & Scope

LitigationLabs delivers an authenticated Next.js experience that lets trial teams rehearse courtroom strategy inside the CaseSim workspace. The system streams user questions through a multi-agent courtroom simulation, persists transcripts and scores, and exposes admin knobs through Payload CMS.

## Primary User Journeys

* **Advocate rehearsal** -- An authenticated user enters the CaseSim dashboard, selects a scenario, and walks through questioning a witness while reacting to objections and judge rulings.
* **Scenario design** -- Internal staff seed/modify scenarios, witness affidavits, elicits, and agent prompt templates inside Payload CMS collections.
* **Session review** -- Players and instructors revisit transcripts, metrics, and unlocked facts for feedback loops.

## Component Stack Overview

1. **Client Shell (Next.js App Router + React 19)**
   * `app/(site)/dashboard` renders the authenticated dashboard shell and CaseSim tooling.
   * Client-side components (`components/layout/dashboard-shell.tsx`, `components/casesim/*`) manage navigation, optimistic UI, and transcript display.
   * NextAuth session is fetched server-side before rendering CaseSim, keeping auth out of the client bundle.
2. **Experience APIs (Next.js Route Handlers)**
   * `app/(site)/api/courtroom/turn` orchestrates each player utterance.
   * Adjacent routes (e.g., `/api/courtroom/witness`, `/api/sessions`, `/api/site/scenarios`) expose CRUD access to sessions and content for the UI.
   * All handlers are server-side modules that can call lib services directly with no network hop cost inside Vercel.
3. **Domain Services (lib/payload.ts)**
   * Encapsulate Payload CMS (Postgres) reads/writes for scenarios, sessions, and agent configs, with in-memory fallbacks for local dev.
   * Enforce schema validation (Zod) for phases, roles, and objection types before persisting Sessions.
4. **AI Agent Layer (lib/courtroom/\*)**
   * `orchestrator.ts` coordinates the player turn, OCA objections, judge rulings, witness answers, scoring, and metrics.
   * `prompts.ts` renders dynamic system prompts per agent, injecting scenario + transcript context and JSON schemas.
   * `gateway.ts` pipes requests through the Vercel AI Gateway, tagging each agent via `x-vercel-ai-route` for observability.
5. **Persistence & Identity**
   * **NextAuth** stores user identities in the same Postgres instance or Neon, using the schema under `db/nextauth-schema.sql`.
   * **Payload CMS** hosts scenarios, agent configs, and courtroom sessions. When Payload is unreachable, `lib/payload.ts` falls back to an in-memory Map to keep the simulator viable in local environments.
6. **External Integrations**
   * Vercel AI Gateway (model multiplexing, rate limiting, API key gating).
   * SMTP/Google/Apple identity providers via NextAuth.

## Request & Data Lifecycles

### Authenticated Navigation

1. User hits `/dashboard/casesim`.
2. `CaseSimPage` calls `getServerSession(authOptions)`; anonymous users are redirected home.
3. The client renders `DashboardShell`, which loads child panels and begins fetching session/scenario data via `/api` routes.

### Player Turn (`/api/courtroom/turn`)

1. Client posts `{ sessionId, userUtterance }`.
2. Route handler reads the latest `CourtroomSession` via `getSessionById` and pulls the linked `Scenario` from Payload CMS (or the fallback sample cache).
3. `handleTurn` executes:
   * Adds the player question to the transcript.
   * Determines OCA mode (objection vs. examination) from session phase + witness ownership.
   * Optionally calls the Opposing Counsel agent via AI Gateway using the system prompt assembled in `buildOCSystemPrompt`. JSON schema enforcement happens by parsing with `ocaObjectionResponseSchema`.
   * If OCA objects, the Judge agent is invoked with `buildJudgeSystemPrompt`; the ruling controls whether the witness answers.
   * Witness answers go through `buildWitnessSystemPrompt`, pointing each witness at their affidavit, demeanor, and elicits.
   * `computeScoreDeltaFromAnswer` tallies unlocked elicits, produces score deltas, and updates session metrics (lag, questions asked, objection stats).
4. Updated session is persisted via `saveSession` and returned to the client alongside the synthesized `CourtEvent`s for real-time rendering.

### Witness Selection (`/api/courtroom/witness`)

Validates that the witness exists in the chosen scenario before mutating `currentWitnessId` on the session.

### Scenario & Session Discovery

`/api/site/scenarios` and `/api/sessions` wrap the underlying Payload finders to populate CaseSim menus, dashboards, and resume experiences.

## Data Model Highlights

* **Scenario** (`lib/courtroom/types.ts`): top-level metadata plus `forAgents.witnesses[]`, each containing affidavits, tendencies, and per-witness elicits (key facts).
* **CourtroomSession**: tracks player side, current phase (`pretrial -> direct -> cross -> ...`), current witness, transcript (`CourtEvent[]`), score state, and per-turn metrics.
* **AgentConfig**: fetched live (1-minute cache) so instructional staff can hot-edit prompts, intentional error rates, and model overrides without redeploying code.

## Deployment & Environment

* **Runtime**: Next.js 16 (App Router) on Vercel, leveraging the Edge/Node runtimes depending on route needs.
* **CMS**: Payload CMS co-deployed under `/app/(payload)` with an isolated admin UI at `/admin`.
* **Data**: Neon or self-hosted Postgres backing NextAuth + Payload. Local development may skip Payload by using sample data.
* **Configuration**: `.env.local` drives NextAuth providers, Payload, and AI Gateway credentials.

## Operational Considerations

* **Latency budgets**: `handleTurn` records `lagMs` for the objection + witness pipeline; these metrics can later feed telemetry dashboards.
* **Resilience**: Each agent call is wrapped in `try/catch`. Failures degrade gracefully by emitting `system` events while allowing the rest of the turn to proceed.
* **Prompt safety**: All AI responses are forced through JSON schemas when applicable (OCA, Judge). Witness answers are constrained through scenario affidavits.
* **Security**: All CaseSim routes require a NextAuth session. Payload admin routes live under `(payload)` to isolate them from public site traffic.
* **Scalability**: Stateless route handlers keep concurrency high. Long-running operations (LLM calls) happen server-side so browser clients stay responsive.
