AI Quality and Evaluation
How the WhatsApp AI agent's quality is measured, monitored nightly, reviewed by managers, corrected by staff replies and tested offline.
10 min read
Overview
Kagami measures the AI chat agent (the WhatsApp/DM assistant, see ai-whatsapp-agent.md and ai.md) in five places:

| Layer | What it answers | Where |
|---|---|---|
| Weekly quality view | Is the bot converting, handing off, costing too much? | Settings > AI quality |
| Live transaction and service logs | What did the bot actually book, propose, quote? | Settings > AI quality (other tabs) |
| Chats to review | Which chats failed and need a human look? | Settings > AI quality > Chats to review |
| Nightly anomaly monitor | Did anything odd happen in the last 24h? | WhatsApp message + bell to owners |
| Reply lessons | What did staff answer when the bot was unsure? Feeds the prompt | Automatic, no screen |
| Eval harness | Does a gateway/prompt/model change break a guard? | npm run ai:eval, part of npm test |
There are no numeric pass/fail thresholds in the quality view: it shows rates and the manager judges them. The only hard thresholds are in the anomaly monitor (any single anomaly alerts) and the paging ladder for held replies.
Sources: web/src/lib/ai/quality-metrics.ts, anomaly-monitor.ts, reply-lessons.ts, reply-alerts.ts, chat-transaction-logger.ts, chat-transaction-metrics.ts, and web/src/app/(tenant)/dashboard/settings/ai-quality/page.tsx.
Settings > AI quality page
Route /dashboard/settings/ai-quality, nav entry "AI quality" (web/src/lib/nav/sections.ts), feature flag ai_agent. Visible to MANAGER_ROLES only; other roles get a permission-denied state (see roles-permissions.md). Multi-brand orgs switch brand with chips at the top; the page defaults to the first brand by name. Query params: brand, view, week.
Weekly numbers
Read from the Postgres view ai_quality_weekly (migration 0238_ai_quality_and_reminder_confirm.sql, security_invoker, grant to service_role only, so the page reads it with the admin client after the role check). Weeks are IST, Monday start. The page lists up to 8 weeks as chips and shows nine cards for the selected week:
| Card | Formula (deriveWeekly) |
Meaning |
|---|---|---|
| Chats | conversations |
ai_conversations started that week |
| Bot bookings | bot_bookings |
distinct conversations with a successful create_booking in ai_action_logs.tool_calls that week |
| Conversion | bot_bookings / conversations |
|
| Handoff rate | handoffs / conversations |
chats with status = 'handed_off', any reason |
| Unsure price | ungrounded_price_handoffs / conversations |
handoff_reason = 'ungrounded_price' |
| Bot failures | failure_handoffs (a count) |
handoff_reason IN ('internal_error','ai_agent_failed','empty_reply') |
| AI cost | cost_usd |
sum of ai_action_logs.cost_usd |
| Cost / booking | cost_usd / bot_bookings |
|
| Follow-up replies | cold_followups_replied / cold_followups_sent |
cold follow-up (ai_messages.tool_name LIKE 'cold_followup_%') answered by the client within 24h |
The view also carries turns, upsells_offered and upsells_accepted (ai_upsell_events, channel whatsapp_booking); the page does not display them yet (see ai-upsell-offers.md). Ratios show "-" when the denominator is 0. There is no latency column: per-turn latency and prompt version are not logged in production (web/src/lib/ai/eval/README.md, "Known gaps").
Recent chat transactions (default tab)
ai_chat_transactions (migration 0255), latest 25 rows for the brand. Written after every agent turn by logTurnTransactionsAndServices (called from gateway.ts; never throws, errors go to Sentry tags ai_chat_transactions.*, ai_chat_logger.unhandled).
transaction_type |
Written when | Status values |
|---|---|---|
booking_create, booking_propose |
create_booking / propose_booking tool |
success, failed (+ error_code) |
reschedule, cancel |
write or propose variants | success, failed |
wallet_check |
check_wallet_balance |
success, failed |
switch_store |
switch_store |
success, failed |
handoff |
handoff_to_human or a handoff/held turn |
success, held (jury held the reply) |
rejected is allowed by the table CHECK but the logger never writes it. Tool input is deliberately not stored (PII); only metadata.tool and the handoff reason are kept. Amounts are amount_minor (paise) in INR.
Service demand (last 14 days)
ai_chat_service_logs, aggregated in getServiceInteractionStats: per service, counts of inquired, quoted, proposed, booked; conversion = booked / total interactions; top 20 by volume. The table also accepts availability_checked and recommended (widened in migration 0258), but those are not shown as columns and they inflate "total interactions" and so lower the conversion. A single list_services result logs one inquired per service listed (SALO-2317); per turn at most 20 extra service rows are written.
Chats to review
getFailureReviewList: ai_conversations of the last 14 days (max 100, newest first) whose handoff_reason is in FAILURE_REASONS = ungrounded_price, internal_error, ai_agent_failed, empty_reply. Columns: when (IST), client name, number (channel_ref), reason. Each links to /dashboard/inbox; staff open the chat by number. This list is how real failures become new eval cases (see below).
Nightly anomaly monitor
runAiChatAnomalyMonitor in anomaly-monitor.ts, exposed as GET/POST /api/cron/ai-chat-anomalies (web/src/app/api/cron/ai-chat-anomalies/route.ts, SALO-2189).
Scheduling
It runs from the VM crontab, not pg_cron: scripts-vm/crontab line 30 3 * * * (03:30 UTC, 09:00 IST) calling scripts-vm/cron-endpoint.sh api/cron/ai-chat-anomalies, which POSTs to localhost:3000 with header x-cron-secret read from CRON_SECRET in web/.env.local. The same file says the other recurring jobs moved to pg_cron (SALO-794); this one has no pg_cron migration. Auth is cronSecretMatches (fail closed when CRON_SECRET is unset). Output goes to logs/cron.log on the VM. The route returns counts only, never client text or phones. To confirm it is installed on a server, run crontab -l there.
What it scans
All ai_messages created in the last 24h (lookbackHours default 24, not overridable via the route), paged 1000 rows at a time, max 50 pages (50,000 messages, then it logs ai_anomaly_monitor.truncated and continues with what it has). Messages are grouped by conversation, then by brand, and each brand is scanned and alerted separately.
| Anomaly | Rule | Dedupe |
|---|---|---|
| Non-UUID option ids | A menu option (from tool_input.options, tool_result.options, or the [Options shown: ...] marker in content) whose id is not a UUID and whose title/description contains a price (₹, rs, inr). Date/slot menus legitimately use non-UUID ids, so unpriced options are ignored (SALO-2180) |
one per option id per conversation |
| Client price disputes | An inbound message matching PRICE_DISPUTE_RE ("too expensive", "wrong price", "overcharging", "why Rs 500", etc.) |
none: every matching message counts |
| Drop-off after AI correction | The conversation's last message is an inbound rejection (REJECTION_RE: "no thanks", "never mind", "not interested", "cancel", "skip", ...) and the AI's previous message matches AI_CORRECTION_RE ("sorry", "unfortunately", "not available", "fixed price", "no discount", ...) or a tool result in between contains unauthorized_price, no_slots, unavailable, error, rejected |
one per conversation |
Threshold: any brand with at least 1 anomaly is alerted. There is no count threshold and no stored state between nights, so nothing is deduped across runs (the 24h window is the only guard; a chat active across the boundary can be counted twice).
Who is alerted
Per affected brand (alertBrandOwners):
- Recipients are every
membershipsrow withrole = 'org_owner'in the brand's org. The phone comes fromprofiles.phone, normalized bynormalizeOwnerPhoneto91XXXXXXXXXX(10-digit numbers get91; junk gives null). Duplicate numbers are sent once. - Owners with no usable phone are counted in
ownersSkippedNoPhoneand logged to Sentry (ai_anomaly_monitor.owner_no_phone); they still get the in-app notification below but no WhatsApp. - The brand must have WhatsApp enabled in
messaging_settings(is_whatsapp_enabled,wa_phone_number_id,wa_access_token). If not, Sentry getsai_anomaly_monitor.no_wabaand no WhatsApp is sent. The message goes out over the brand's own WhatsApp Business number. - If the owner messaged the brand in the last 24h (
inbound_messages.from_phone), they get free text (formatAnomalyReport: counts, up to 3 examples per kind as conversation id prefix and last 4 digits of the phone, plus an Inbox link). Otherwise they get the UTILITY templateai_chat_anomaly_alert(web/src/lib/messaging/templates.ts) with three variables: date (IST), total count, top issue label. The template must be approved in Meta (Settings > WhatsApp templates > sync) before it delivers. - Independently,
sendAlertraises the in-app alertai_chat_anomalies_detected("AI chat anomalies", group customers_ai, link/dashboard/inbox, severity warning); who sees it and by which channel is configurable in Settings > Alerts (web/src/lib/alerts/registry.ts). - If no owner at all was reached, Sentry gets
ai_anomaly_monitor.alert_undelivered, so a mute monitor is not silent. Response fields:scannedConversations,scannedMessages,alertDispatched,alertsSent,ownersSkippedNoPhone, and anomaly counts.
Alerts and responses never contain client names or message text; owners open the Inbox for detail.
Held replies and handoff paging
Related quality safety net, in reply-alerts.ts (SALO-2185, SALO-2510). When the reply jury holds a draft, or the AI hands a chat to staff, a row is opened in ai_reply_holds and staff are paged:
| Level | Recipients | Next page after this one |
|---|---|---|
| 1 | front_desk, location_manager of that store |
5 min, then the level 2 page |
| 2 | location_manager, brand_manager |
5 min for a held reply, 25 min for a handoff, then the level 3 page (so the owner page lands about 30 min after a handoff, HANDOFF_OWNER_AFTER_MIN) |
| 3 | org_owner |
10 min, repeated until MAX_PAGES = 8 pages |
Escalation runs from pg_cron job salonos-ai-reply-escalation calling /api/cron/ai-reply-escalation (created every minute in migration 0240, slowed to every 2 minutes in 0290). Alert keys: ai_reply_held, ai_handoff_unanswered (Settings > Alerts). Staff stop paging with Acknowledge, or close it with "mark handled" for chats answered outside the inbox. Handoffs also email owners at level 3. A chat with no recipients logs ai_reply_alerts.no_recipients.
Reply lessons
How a correction becomes training for the prompt (SALO-2185; reply-lessons.ts, reply-alerts.ts):
- Staff reply to a customer from the Inbox (
web/src/lib/inbox/actions.ts, WhatsApp and Meta DM paths) andresolveHoldsForStaffReplyruns. - Open or acknowledged holds for that customer at that store (matched on the last 10 digits of the phone) are marked
resolved. - For each held-reply hold (not handoffs: the AI never tried to answer and the answer is about one customer), a row is upserted into
ai_reply_lessons(migration0240):question= customer message (max 500 chars),answer= the staff reply (max 1000),source = 'staff',source_ref= hold id. Unique on(source, source_ref), so retries do not duplicate. Org members can read the table (RLS); only the service role writes. - On each AI turn,
loadLessonsBlock(brandId)loads the newest 15 lessons for the brand.formatLessonscollapses whitespace (question cut to 200, answer to 400 chars) so stored text cannot add prompt lines, and renders- Customer asked: "..." -> Our team answered: "...". - The block is inserted into the system prompt after the owner's instructions as "Approved answers from our team (SALO-2185)... they override your own guesses", passed to the reply jury, and counted as a trusted price source in the grounding check (
gateway.ts).
There is no screen to list, edit or delete lessons, and no approval step: every staff reply to a held chat becomes a lesson. If a bad lesson is saved, it can only be removed in the database. A lesson load failure returns an empty block and logs ai_reply_lessons.load (the turn continues without lessons).
Eval harness
A golden set of WhatsApp conversations is replayed through the real runAgentTurn with Supabase and tools mocked, then scored by code checks (grounded prices and slot times, discount cap, no write without an explicit yes, no other client's PII, expected handoffs and tools) and an optional LLM judge. It has an offline mode (scripted model, deterministic, runs inside npm test, tests the gateway and guards, not the model) and a live mode (AI_EVAL_LIVE=1, real providers, compare reports on the same set version), plus a model bake-off script. Full file list, modes, the process (baseline, target, one regression case per incident) and known gaps are in web/src/lib/ai/eval/README.md; do not duplicate it here.
cd web
npm run ai:eval # offline
AI_EVAL_LIVE=1 npm run ai:eval # live, needs provider keys in .env
npm run ai:bakeoff -- --dry-run # plan only
Reports go to web/eval-reports/ (gitignored). The harness is not scheduled: it runs on demand and in CI-style npm test; nothing evaluates production nightly. The weekly loop (README "Process" step 5) is manual: read the quality page and Chats to review, then add real failures as golden cases.
Troubleshooting / where to look
| Symptom | Check |
|---|---|
| Quality page empty | No ai_conversations yet, or migration 0238 not applied (error banner shows the Postgres message) |
| Owner got no anomaly WhatsApp | Response ownersSkippedNoPhone, Sentry ai_anomaly_monitor.owner_no_phone / no_waba / whatsapp / alert_undelivered; confirm ai_chat_anomaly_alert is Meta-approved; owner profile phone set; brand WhatsApp connected |
| Monitor never fires | crontab -l on the VM, logs/cron.log, CRON_SECRET in web/.env.local; there is no pg_cron job for it |
| Held reply never escalates | cron.job row salonos-ai-reply-escalation, Vault secrets cron_secret / cron_base_url (run_cron_endpoint) |
| A lesson is not influencing replies | Only the newest 15 per brand load; handoffs never create lessons; check ai_reply_lessons rows for the brand |
| Transactions tab empty | Check Sentry ai_chat_transactions.insert; table is RLS-read by org members, written by service role |
See also analytics.md, communications.md, settings.md.