# SPRINT 2.2 — Product Usability Pass

**Status:** built and tested locally; awaiting acceptance.
**Predecessor:** Sprint 2.1.1 (accepted, sandbox live end-to-end)
**Worker version:** `0.2.2`
**Widget version:** `0.2.2`
**Tests:** 48/48 passing (35 carried forward + 13 new smart-mock tests)
**Bolt-on contract:** unchanged. Hosts that worked in 2.1.1 work in 2.2 with no code changes.

---

## Goal

Move the sandbox from "technical proof the wires work" to "usable product demo." Two host pages (Comp Intelligence synthetic, public website FAQ) should render Lexi as a polished bolt-on assistant that answers from deployment-specific context, not from a generic echo.

No production blockers introduced. No real provider compensation data. No PHI. No Foundry credentials. Governance gates (Tabor for production infra, Chapman for real PHI/audit storage, Microsoft for Foundry activation) remain unchanged and unblocked by this work.

---

## What changed

### 1. Smart mock adapter (server-side answer logic)

`worker/src/adapters/mock.js` is no longer an echo. It now:

- **Parses the `systemPrompt`** for deployment-specific structured data:
  - Comp Intel: extracts `PERIOD`, `TOTALS`, `FMV exceptions`, and per-specialty rows of the form `SPECIALTY <id>: <n> providers, median wRVU <num>, MGMA <pct>th pct`
  - Public FAQ: extracts `FAQ-Q: <question>` / `FAQ-A: <answer>` pairs

- **Pattern-matches the user question** against deployment-specific intents:
  - Comp Intel: total wRVU, FMV exceptions, top specialty by median, compare two specialties, single-specialty lookup, list specialties, provider count, total comp paid
  - Public FAQ: token-overlap scoring against each FAQ entry with light stemming (located/location, scheduled/schedule)

- **Falls back gracefully** to a capabilities summary specific to the deployment when no pattern matches

- **Surfaces context source** via `meta.contextSource` (`comp-intelligence-context.stub`, `public-faq-context`, or `sandbox-echo`), which the route handler propagates to the response JSON

The architecture matches the eventual production path: the browser ships context, the Worker's adapter does the answering. When Foundry replaces the mock, the browser code is unchanged.

### 2. Worker route handler

`worker/src/index.js` (and the dashboard bundle):

- Passes `deploymentId: policyResult.deployment.id` into the adapter call so the mock can dispatch by deployment without re-parsing the systemPrompt
- Surfaces `adapterResult.meta.contextSource` in the success response (new field)
- `WORKER_VERSION` bumped to `0.2.2` in both modular source and dist bundle

### 3. Context builders updated for parser format

**`lexi/context-builders/public-faq-context.js`** — rewritten with a structured Q/A corpus (10 entries) emitted as `FAQ-Q:` / `FAQ-A:` lines. Old version was a flat list of statements that the smart mock couldn't reliably parse. Also exposes `window.LexiPublicFaqCorpus` so host pages can render the FAQ cards from the same source the assistant grounds on.

**`lexi/context-builders/comp-intelligence-context.stub.js`** — output format updated to emit specialty rows as `SPECIALTY <id>: <n> providers, median wRVU <num>, MGMA <pct>th pct` (the format the smart mock's regex expects). Added explicit `FMV exceptions: <n>` line. No data changes; same synthetic specialties, same numbers.

### 4. Widget UX overhaul

`embed/lexi-widget.js` rewritten (521 lines vs 250 in 2.1.1). Additions:

- **Copy response button** on every assistant message. Uses `navigator.clipboard.writeText` with `execCommand` fallback. Visual confirmation: "Copy" → "Copied!" → reverts after 1.4s.
- **Clear chat button** in the widget header. Removes all messages, resets history, re-renders the suggested-prompts row.
- **Keyboard shortcut Cmd/Ctrl+K** to clear chat from inside the widget.
- **Loading state**: animated rotating SVG spinner with "Thinking…" label, replaces previous static "…thinking" string.
- **Friendly error state**: distinct red-bordered bubble with friendly message keyed off `err.code` (eleven known codes covered), plus a Try-again button that retries the same question. Falls back to `err.message` for unknown codes.
- **Source/context indicator chip**: every assistant message has a `from: <contextSource>` green chip in its header showing which context builder shaped the answer. Lets reviewers see at a glance that grounding is working.
- **Suggested-prompts row**: dashed-border row shown when the conversation log is empty, with deployment-appropriate prompt chips. Hidden after the first send; re-appears after Clear.
- **Inline markdown rendering**: `**bold**`, `_italic_`, `code`, and `-` bulleted lists. Smart-mock responses use these; rendering them properly makes responses look like a real product.
- **Per-message Retry**: when an error occurs, the error bubble has a Retry button that re-sends the original question.

`embed/lexi.css` adds styles for all of the above: `.lexi-msg-source`, `.lexi-spinner` with `@keyframes lexi-spin`, `.lexi-msg-error`, `.lexi-suggested-row` / `.lexi-suggested-chip`, `.lexi-header-action`, `.lexi-msg-action`, `.lexi-msg-list`. All scoped under `.lexi-widget`.

### 5. Host pages

Both `hosts/comp-intelligence-test.html` and `hosts/public-website-test.html` updated to pass `suggestedPrompts` matching the stated test prompts in the sprint brief. No other structural changes; banners and synthetic-data labels preserved.

### 6. INTEGRATION.md

New top-level doc with three host integration patterns:

- **Inline panel** (Comp Intelligence-style sidebar)
- **Floating widget** (public website-style bottom-right)
- **Custom UI** (engine-only, no widget, for apps that have their own chrome)

Each with exact copy-paste snippets. Documents the response shape (including the new `contextSource` field), the eleven stable error codes the widget handles, and what's preserved across future changes (Foundry adapter swap, real Supabase auth, Supabase-managed FAQ corpus).

### 7. One-page acceptance checklist

`proof/sprint-2.2-acceptance.html` — printable HTML with 31 click-to-check rows across Comp Intel host (12), Public host (10), cross-cutting UX (6), and Worker/regression (3). Maps directly to the Sprint 2.2 acceptance language: "I should be able to open the two host pages, ask the suggested prompts, and see useful test answers."

### 8. Test suite extended

`worker/test/policy.test.js` now has 48 tests:

- **35 carried forward unchanged** (auth, policy, CORS, sandbox bypass, etc.)
- **Test 11 assertion updated** — old assertion checked for the literal echo string `"mock-adapter-response"`; new assertion checks for non-empty text and confirms `contextSource: 'comp-intelligence-context.stub'` is surfaced
- **13 new smart-mock tests** (M-CI-1 through M-CI-7 + M-FAQ-1 through M-FAQ-5 + M-X-1):
  - M-CI-1: total wRVU pattern returns the right number
  - M-CI-2: highest-median pattern picks the right specialty
  - M-CI-3: FMV exceptions pattern returns "no FMV exceptions" on zero
  - M-CI-4: compare-two-specialties returns side-by-side and declares a winner
  - M-CI-5: list-specialties returns all 5 specialty IDs
  - M-CI-6: off-topic question returns capabilities fallback labeled TEST MODE
  - M-CI-7: no systemPrompt data returns graceful fallback
  - M-FAQ-1: direct FAQ-question hit returns the answer with `From FAQ:` attribution
  - M-FAQ-2: paraphrased question ("Do you take Medicare?") finds the insurance FAQ
  - M-FAQ-3: stemmed question ("Where are locations listed?") finds the locations FAQ
  - M-FAQ-4: off-topic FAQ question returns capability fallback labeled TEST MODE
  - M-FAQ-5: empty FAQ corpus returns graceful fallback
  - M-X-1: sandbox deployment surfaces `contextSource: 'sandbox-echo'`

---

## Acceptance criteria mapping

Sprint brief said: "I should be able to open the two host pages, ask the suggested prompts, and see useful test answers rendered in the widget."

| Brief requirement | How met | Verifiable |
|---|---|---|
| Improved default Lexi widget UX | Copy/Clear/loading/error/source-chip/suggested prompts/markdown | `proof/sprint-2.2-acceptance.html` rows |
| Clear TEST MODE / synthetic-data labels preserved | Banners on both host pages unchanged; TEST MODE badge in widget header | inspect host pages |
| Conversation history visible and resettable | history rendered in log; Clear button + Cmd/Ctrl+K | widget |
| Copy response button | Copy/Copied!/reverts on each assistant message | widget |
| Clear chat button | header button + keyboard shortcut | widget |
| Loading state | spinner SVG + "Thinking…" + env label | widget |
| Friendly error state | red-bordered bubble keyed off err.code, with Retry button | widget |
| Source/context indicator | `from: <contextSource>` green chip per message | widget |
| Public FAQ grounding behavior | smart mock parses FAQ-Q/A pairs; matches with stemming | M-FAQ-1 through M-FAQ-5 |
| Comp Intelligence synthetic summary behavior | smart mock parses systemPrompt; answers from extracted data | M-CI-1 through M-CI-7 |
| Host integration docs with exact script snippets | `INTEGRATION.md` with 3 patterns | top-level doc |
| One-page acceptance checklist | `proof/sprint-2.2-acceptance.html` (printable) | checklist itself |
| Suggested Comp Intel prompts work | total wRVU / highest median / FMV / compare | M-CI-1, M-CI-2, M-CI-3, M-CI-4 |
| Suggested FAQ prompts work | schedule / insurance / contact / locations | M-FAQ-1, M-FAQ-2, plus stemming for contact and locations |

All 8 stated test prompts (4 per deployment) produce useful, grounded answers verified in tests.

---

## What's still ahead (not blocked by 2.2)

Future gates unchanged from prior sprints:

- **Tabor review** before any Cloudflare production infra (custom domain, prod Worker secrets, prod Pages project)
- **Chapman review** before real provider comp data, PHI, persistent audit storage, or production user-facing release
- **Microsoft review** before real Foundry credential activation and BAA-covered LLM traffic

What can move in parallel without those gates:

- More widget polish (avatars, threading, message history persistence in browser storage)
- Sprint 2.3 real-LLM mode behind a separate env flag (e.g. `LLM_BACKEND=anthropic-direct`) for richer demos
- Stub builder for Comp Intel that reads from an internal LC data source (still synthetic until Chapman OKs real data)
- Supabase-managed FAQ corpus (Sprint 3)

---

## Files changed vs Sprint 2.1.1

```
NEW:
  INTEGRATION.md
  proof/sprint-2.2-acceptance.html

MODIFIED:
  worker/src/index.js                              (deploymentId passthrough, contextSource surfacing, WORKER_VERSION → 0.2.2)
  worker/src/adapters/mock.js                      (smart mock with pattern matchers; 343 lines)
  worker/dist/worker-bundle.js                     (smart mock inlined, route handler updates, WORKER_VERSION → 0.2.2)
  worker/test/policy.test.js                       (test 11 updated; 13 new smart-mock tests)
  worker/test/policy.test.output.txt               (regenerated; 48/48 passing)
  lexi/context-builders/public-faq-context.js      (10-entry Q/A corpus in FAQ-Q/FAQ-A format)
  lexi/context-builders/comp-intelligence-context.stub.js  (specialty row format aligned with parser; FMV line)
  embed/lexi-widget.js                             (UX overhaul; 521 lines)
  embed/lexi.css                                   (new styles for source chip, spinner, error state, suggested prompts; 330 lines)
  hosts/comp-intelligence-test.html                (suggestedPrompts in mountWidget options)
  hosts/public-website-test.html                   (suggestedPrompts in mountWidget options)

UNCHANGED (byte-identical to Sprint 2.1.1):
  SPRINT-2.0.1.md, SPRINT-2.1.md, SPRINT-2.1.1.md
  proof/worker-roundtrip.html, proof/sprint-2.1-checklist.html
  worker/src/auth.js, policy.js, audit.js, bootCheck.js, adapters/foundry.js
  worker/wrangler.toml.example, package.json
  worker/test/fixtures/jwt.js
  lexi/*.js (except the two builders above)
  embed/lexi-embed.js (engine unchanged; widget UI only)
```

---

## Deployment

For sandbox-only deployment (no Tabor required):

1. Open Cloudflare dashboard → Workers → `lexi-api-sandbox` → Edit Code
2. Paste contents of `worker/dist/worker-bundle.js`
3. Save and deploy
4. Hit `GET /api/lexi/health` → confirm `workerVersion: "0.2.2"`
5. Open `/proof/worker-roundtrip.html` on the sandbox Pages site → confirm all 5 checks still pass
6. Open `/hosts/comp-intelligence-test.html?worker=https://lexi-api-sandbox.<account>.workers.dev`
7. Work through `/proof/sprint-2.2-acceptance.html`

If anything fails, the test suite (`node worker/test/policy.test.js`) and the bundle smoke-test in this dossier give a fast rollback signal.


---

## Les Sidebottom handoff addendum

This repackaged handoff adds:

- `/index.html` — landing page for the demo package
- `/LES_SIDEBOTTOM_HANDOFF.md` — concise technical/product handoff for the Comp Intelligence owner

No runtime code changed in this repackaging step. The goal is to make the package easy to hand to Data & Analytics and demonstrate the bolt-on path clearly.
