# AI Coaching Panel — Design Spec

## Goal

Replace the current AI chat panel with a proactive coaching surface that shows structured patient summaries, rule-driven upsell/cross-sell/retention suggestions with clickable scripts, and a contextual chat — all in the existing 400px right-hand panel.

## Architecture

Single scrollable panel, three zones. No tabs or toggles. Caller context pre-fetched and cached in Redis (CallerContextService). Rules engine produces suggestion triggers. AI renders triggers into natural language scripts. Every AI response includes updated suggestions (progressive).

## Panel Layout

### Zone 1 — Summary Card (pinned top, ~120px)

- Patient name, age, gender, patient type badge (NEW / RETURNING)
- 2-line AI summary (from `aiSummary` field on lead record)
- Campaign badge + source tag (e.g., "Cervical Cancer Screening Drive" / "Google")
- Compact appointment pills: next upcoming appointment (date + doctor), last completed (date + outcome)
- Renders from CallerContextService data — no AI call needed for this zone

For new callers (no lead/patient): shows phone number, "New Caller" badge, and a prompt to collect name.

### Zone 2 — Suggestions (collapsible, below summary)

- 2-4 suggestion pills as compact cards
- Each pill: type icon (tag/arrow-up/rotate-cw), one-line title, priority dot (high/medium/low)
- Click expands inline with a 2-3 sentence ready-to-read script
- Expanded state has a "Tell me more" link that sends the suggestion as a chat message
- Suggestions refresh with every AI response (progressive)
- Collapse/expand toggle for the entire section ("Suggestions (3)")

Suggestion types:
- **upsell** — premium packages, add-on services
- **crosssell** — related services in other departments
- **retention** — reschedule missed appointments, follow up on lapsed visits
- **operational** — fasting reminders, insurance docs, directions

### Zone 3 — Chat (fills remaining space)

- Streaming chat, same UX as today
- Agent types questions or clicks "Tell me more" from a suggestion
- Each AI response may include updated suggestions (Zone 2 refreshes)
- Quick action pills at bottom, contextual to conversation state
- Auto-fires patient summary on call connect (existing behavior, kept)

## Structured AI Response Format

Every AI response is structured JSON (not free-form text):

```json
{
  "message": "Priya Sharma is a returning patient...",
  "suggestions": [
    {
      "id": "s1",
      "type": "upsell",
      "title": "Cardiac Wellness Package",
      "script": "Since you're already seeing Dr. Lakshmi for cardiology, we have a comprehensive cardiac wellness package...",
      "priority": "high"
    },
    {
      "id": "s2",
      "type": "retention",
      "title": "Reschedule missed appointment",
      "script": "I see your last appointment on April 10th was rescheduled. Would you like me to book a new slot?",
      "priority": "medium"
    }
  ]
}
```

The `message` field renders as a chat bubble in Zone 3. The `suggestions` array replaces the current set in Zone 2. If `suggestions` is empty or absent, Zone 2 retains the previous set.

The initial auto-fired response includes the summary message + first set of suggestions. Subsequent responses update suggestions based on conversation context.

## Rules Engine to AI Prompt Pipeline

### Step 1: Rules evaluation

CallerContextService already builds the caller facts (appointments, campaigns, call history, lead status, interested service). The rules engine evaluates these facts against configured suggestion rules.

Each rule produces a raw trigger:
```json
{
  "type": "upsell",
  "product": "cardiac-wellness-package",
  "reason": "Patient has cardiology appointment, no wellness package booked",
  "priority": "high"
}
```

### Step 2: Prompt injection

Raw triggers are appended to the system prompt as a `SUGGESTION RULES` section:

```
SUGGESTION RULES (from business configuration):
Based on this caller's profile, the following suggestions should be offered.
Generate a natural, conversational script for each that the agent can read aloud.
Return them in the `suggestions` array of your JSON response.

1. [upsell/high] Cardiac Wellness Package — patient has cardiology appointment, no wellness package booked
2. [retention/medium] Reschedule missed appointment — last appointment was rescheduled, no new booking
```

### Step 3: AI generates scripts

The AI turns the raw triggers into conversational scripts using the caller's context (name, history, doctor, department). Scripts are personalized, not templated.

### Step 4: Seeded rules

Default suggestion rules seeded in the rules engine config:
- Package upsell by department (cardiology → cardiac wellness, ortho → physio package)
- Reschedule missed/cancelled appointments
- Cross-sell related departments (ortho → physio, cardio → dietician)
- First-visit patient: suggest health checkup package
- Returning patient with no recent visit: re-engagement prompt

These rules are displayed read-only in Settings > Automations tab (same card pattern as existing automation rules — visible but not editable in v1).

## Data Flow

```
Call arrives
  -> CallerResolutionController.resolve()
    -> CallerContextService.prewarm() (parallel fetch + Redis cache)
  -> Frontend auto-fires AI chat
    -> POST /api/ai/stream
      -> buildCallerContext() — Redis cache hit
      -> rulesEngine.evaluate(callerFacts) — produces suggestion triggers
      -> buildSystemPrompt(KB + callerContext + suggestionRules + structuredOutputInstructions)
      -> streamText() — AI returns structured JSON { message, suggestions }
    -> Frontend parses response
      -> Zone 1: summary card from CallerContextService (no AI needed)
      -> Zone 2: suggestions from AI response
      -> Zone 3: message as chat bubble

Agent clicks "Tell me more" on a suggestion
  -> Sent as chat message: "Tell me more about the Cardiac Wellness Package"
  -> AI responds with detailed info + updated suggestions
  -> Zone 2 refreshes with new suggestions

Agent books appointment (via disposition/form)
  -> System message injected into chat: "Agent booked appointment with Dr. Lakshmi on Apr 24"
  -> Next AI response reflects the action + updates suggestions
    (e.g., removes "reschedule" suggestion, adds "send appointment reminder via WhatsApp")
```

## Surface Area

### Sidecar (helix-engage-server)

| File | Change |
|------|--------|
| `ai-chat.controller.ts` | Add structured output instructions to system prompt. Add suggestion rules injection from rules engine. Parse/pass suggestion triggers. |
| `caller-context.service.ts` | Add rules evaluation method that runs caller facts against suggestion rules. Return triggers alongside context. |
| `rules-engine/` | Seed default suggestion rules (JSON config in Redis or file). |
| `config/ai.defaults.ts` | Update `ccAgentHelper` prompt template with structured output format instructions and suggestion generation rules. |

### Frontend (helix-engage)

| File | Change |
|------|--------|
| NEW: `ai-summary-card.tsx` | Zone 1 — patient profile card rendered from CallerContextService data |
| NEW: `ai-suggestions.tsx` | Zone 2 — suggestion pills with expand/collapse, script display, "Tell me more" |
| REWRITE: `ai-chat-panel.tsx` | Orchestrates all 3 zones. Parses structured JSON responses. Manages suggestion state. Passes "Tell me more" clicks as chat messages. |
| `context-panel.tsx` | Remove P360 tab toggle. Single surface — AI coaching panel is the only mode. |

### No changes needed

- `call-desk.tsx` — panel wrapper stays the same
- `app-shell.tsx` — no changes
- `CallerContextService` — already built, just add rules evaluation call
- Frontend build pipeline — no new dependencies

## What this replaces

- P360 context tab (appointments, call history, follow-ups tables) — replaced by AI summary card
- AI chat toggle — removed (single surface)
- Tool-based patient lookups during chat — replaced by pre-fetched context in KB
- Static quick action pills — replaced by rule-driven contextual suggestions

## Out of scope for v1

- Editable suggestion rules UI (shown read-only in Settings)
- Supervisor AI coaching (different tool set, different panel)
- Real-time transcript-driven suggestions (requires live call transcription)
- Suggestion analytics (which suggestions agents click, conversion tracking)
