> ## 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.

# Agent Design

> Low-level contracts, prompts, and control flow for each agent in the CaseSim loop.

## Shared Infrastructure

* **State primitives** -- `CourtroomSession`, `Scenario`, `CourtEvent`, `AgentConfig`, and related Zod schemas live in `lib/courtroom/types.ts`.
* **Turn entry point** -- `handleTurn` in `lib/courtroom/orchestrator.ts` accepts `{ session, scenario, userUtterance }` and returns `{ events, updatedSession }`.
* **Gateway** -- `callAgentThroughGateway` (`lib/courtroom/gateway.ts`) streams completions from the Vercel AI Gateway.
* **Prompt builders** -- `lib/courtroom/prompts.ts` holds helper functions for OCA, Judge, and Witness prompts.
* **Scoring** -- `computeScoreDeltaFromAnswer` increments score metrics based on unlocked witness elicits.

## Orchestrator / Director

**Location:** `lib/courtroom/orchestrator.ts`

### Responsibilities

* Accepts the player question and appends it to the transcript as a `CourtEvent`.
* Computes OCA mode (`objection_mode` vs. `examination_mode`) by examining session phase, player side, and selected witness.
* Runs the objection / judge / witness pipeline sequentially while updating session metrics and score state.
* Emits system-level fallback events when downstream agents fail.

### Turn Sequence

1. **OCA Gate** -- Only runs when `determineOCAMode` returns `objection_mode`. Calls `buildOCSystemPrompt` and parses the response through `ocaObjectionResponseSchema`.
2. **Judge Ruling (conditional)** -- Triggered when OCA returns `response_type === "objection"`. Parses JSON into `{ ruling: sustain | overrule, reason }`. Sustained objections skip the witness call.
3. **Witness Answer** -- Runs when no objection or the objection was overruled. Records the raw answer as a `CourtEvent` and invokes scoring.
4. **Session Persistence** -- Caller (`/api/courtroom/turn`) persists the resulting session via `saveSession`.

### Error Handling

* Each agent call is wrapped in `try/catch` with graceful degradation.
* JSON parsing uses `safeParseJSON` to tolerate LLMs that wrap JSON with commentary.
* `shouldCallWitness` flag prevents accidentally querying the witness when a sustained objection or error occurs.

## Opposing Counsel Agent (OCA)

**Location:** `lib/courtroom/prompts.ts` and `lib/courtroom/types.ts`. Config stored in Payload collection `agentConfigs` with `agentId = "oca"`.

### Modes

* **Objection mode** (player examining their own witness): Returns `response_type: "objection" | "no_objection"` with `objection_type`, optional `rule_refs`, and `is_intentionally_incorrect`.
* **Examination mode** (player objecting while OCA examines): Returns `response_type: "question"` with `question_text`, `is_intentionally_defective`, and optional linkages.

### Configuration Parameters

* `intentionalErrorRate` -- % of turns that produce intentionally incorrect objections/questions.
* `objectionTypes` -- whitelist of admissible objection enums.
* `modelOverride` and `temperature` -- switch models per agent without redeploying.

## Judge Agent

**Location:** Default prompt + builder in `lib/courtroom/prompts.ts`.

### Output Contract

```json theme={null}
{
  "ruling": "sustain | overrule",
  "reason": "Brief explanation citing FRE rule"
}
```

If parsing fails, the orchestrator defaults to `overrule` to avoid blocking witness examination.

## Witness Agents

**Location:** `lib/courtroom/prompts.ts`; witness data originates from each scenario's `forAgents.witnesses[]`.

### Responsibilities

* Role-play a specific witness using their affidavit, tendencies, and elicits.
* Answer questions in natural prose (no JSON) while respecting the current phase and side alignment.

### Output & Post-processing

* Raw text answer captured verbatim in the transcript.
* Scoring uses keyword heuristics (`computeScoreDeltaFromAnswer`) to award points and unlock elicits.

## Future / Auxiliary Agents

* **Director or Coach overlays** -- Additional agents that subscribe to `CourtEvent`s for real-time coaching.
* **Evidence Clerk** -- Manages exhibit foundations and ties into `ocaExaminationResponseSchema.uses_exhibit_id`.
* **Scenario-specific agents** -- New agent IDs can be introduced in Payload and referenced from the orchestrator without modifying UI layers.
