Spaces:
Sleeping
Sleeping
Commit History
-
fix(upload): show heuristic-floor card on LLM-fail path + extend poll to 150s (KI-331)β
User caught live on Test Policy.pdf 8MB upload (2026-05-27): after Gemini 3/3 retries failed and the 120s poll timed out, the frontend pushed only a prose "I couldn't pull a full analysis" message and never surfaced the heuristic-baseline card β even though `record.json` already had 47.8% completeness / grade C / 6 sub-scores from the heuristic pass that runs BEFORE the LLM ever fires. Two changes: 1. KI-331 β fail/timeout branch now pushes the card-bearing assistant message FIRST (same citations as the success path β inline PolicyScorecardWidget renders with whatever record.json has), then the soft caveat ("I couldn't pull a full analysis"), then the choice prompt. setActiveUploadPid still fires so the brain's DIVE-IN block activates for follow-up questions about the policy. 2. MAX_TRIES bumped 40 β 50 (120s β 150s polling budget). Live audit showed Gemini retry #3 sometimes lands at ~130s on large/complex PDFs; 15s extra buffer eliminates the borderline-miss cβ¦993bcd5 -
feat(single_brain): wire view_context β ACTIVE POLICY DIVE-IN block (KI-330)β
Root cause caught in 2026-05-27 multi-PDF e2e audit. On 3 of 5 uploads, asking "What are the waiting periods on this policy?" got back "Before I pull your recommendations, just a couple more (you can skip any):" β single_brain pivoted to profile-building / recommendation flow instead of answering about the just-uploaded policy. Triple root cause: 1. ChatRequest.view_context declared since launch but NEVER CONSUMED anywhere on the backend (truly dead code). 2. single_brain.handle_turn signature didn't accept it. 3. Frontend set view_context.active_policy_id only when a marketplace card was clicked (openPolicy modal); never on a just-uploaded PDF. Fix: - backend/single_brain.py: handle_turn(..., view_context=None); _system_instruction(..., view_context=None); new _build_active_policy_block() that appends an ACTIVE POLICY DIVE-IN block to the system instruction when view_context. active_policy_id is set. Block tells the model: answer the question viβ¦2a58c28
-
feat(upload-ux): lock canonical sequence β ack β wait (everything gated) β card β choiceβ
Per user directive (2026-05-27): 1. User uploads PDF. 2. Bot acknowledges "reading it now, ~30-60s". NO card, NO choice prompt at this point. 3. EVERYTHING is gated during the wait β Send button, textarea, PDF button, voice paths, and the send() function itself all check `uploadStatus || extractionInFlight` and refuse to fire. This eliminates the race where a typed/voice message during the wait drops an unprompted reply into the chat and breaks the staged flow. 4. LLM extraction completes (Gemini 2.5-flash with JSON-mode, ~30s for a 73-page PDF; falls back to NIM if Gemini missing). 5. Bot pushes the card-bearing message + inline scorecard card with the fully-extracted, catalogued-grade data. 6. THEN bot pushes the choice prompt ("finish profile / dive into PDF"). Order matters β the user sees the full picture before being asked what to do next. Defense-in-depth at the send() function entry (last-line guard), so even a progβ¦3dcbe9b -
fix(voice): gate the PTT/Sarvam send-paths on uploadStatus + extractionInFlight tooβ
The voiceSubmitRef path (browser SpeechRecognition end-of-speech auto-fire) was guarded in dfaa4d6 β but two OTHER voice send-paths in the PTT recorder.onstop callback (L1289 srFallback + L1311 Sarvam authoritative text) had no guard. If the user accidentally pressed PTT during the upload + extraction window, or if a stray TTS playback bled into the mic and the recorder picked it up, the Sarvam transcription would still drop the resulting chat turn into the middle of the wait β producing the "I can help with that! Please tell me what you'd like to know" unprompted message reported in screenshot #53. Single early-return at the top of the PTT post-transcribe callback now blocks ALL voice send-paths while uploadStatus || extractionInFlight. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>24349be -
feat(upload): wait-for-extraction flow + status endpoint + extended voice guardβ
User directives integrated: 1. "generate the card inline ONLY after full data extraction" β card no longer renders on the partial heuristic record; we wait for the LLM pass to complete first. 2. "ensure re-grading actually happens" β new /api/upload/extraction-status/{policy_id} exposes real-time in-memory state of the background LLM extraction. 3. "kill the unprompted 'Could you please upload' message" β voice auto-submit now blocked for the ENTIRE extraction window (extractionInFlight state), not just the 8s upload-status window. 4. "same level of usability as the 148 catalogued, no less" β no user-upload__ branches in PolicyPremiumWidget / PerPolicyPremiumEstimator β parity by construction once LLM extraction lands and HealthPolicy fields populate. BACKEND βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ - _UPLOAD_EXTRACTION_STATUS dict (in-process) tracks per-upload extraction lifecycle: pending β running β¦dfaa4d6 -
feat: uploaded-PDF parity with catalogued 148 (ADR-044)β
User-uploaded PDFs now go through the IDENTICAL pipeline as the 148 catalogued policies β same LLM extractor, same scorecard, same review data flow, same card UI. No "user-upload" carve-outs. CHANGES βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ A. Insurer detection (backend/uploaded_docs.py) detect_insurer_slug() scans the first ~6000 chars of PDF text for the legal name of any of the 21 insurers we have reviews data for (Acko, Bajaj Allianz, HDFC ERGO, ICICI Lombard, ManipalCigna, Niva Bupa, Star Health, Tata AIG, β¦). On a match, the persisted record + chunk metadata + Chroma metadata are stamped with the REAL insurer_slug β the scorecard's Claim Experience sub-score reads 40-data/reviews/<slug>.json and gets real claim-ratio + complaint-volume + NPS data, same as a catalogued card. Fail-closed: no match β insurer_slug stays "user-upload". B. LLM-assisted extraction on upload (backend/uploaded_docs.py + backend/main.py) New β¦4bb66dd -
fix(frontend): PDF upload β in-chat ack + inline scorecard card + proceed-choice promptβ
Reported symptom: user uploaded a PDF and saw no acknowledgment in chat β only a transient 8-second banner above the composer, which is easy to miss. The chat transcript itself showed no trace of the upload, so the user had no signal the indexing succeeded or that they could now ask the bot about the document. CHANGES βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ handleFile (frontend/src/app/page.tsx): 1. pushUser("π Uploaded: <filename>") β breadcrumb so the chat transcript records the action AND so the next /api/chat turn's chat_history includes it (helps the brain disambiguate "this policy" references). 2. On success: pushAssistant with the upload-ack text AND a `citations` array carrying the uploaded policy_id. The existing chat renderer reads citations from an assistant message and fires getScorecard(policy_id, session_id) per cited policy, so the scorecard card now appears INLINE under the bubble β same treatβ¦de473cb -
feat!: remove cross-session profile recall (ADR-043) β net β3700 LOCβ
Sessions are now in-memory only. ADR-041's name-slug + persona_id two-tier on-disk store and ADR-042 v3+v4's two-fact gate + extended extractors are removed entirely. Closing the tab discards the profile. CONTEXT βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ Two-week arc of recall hardening (ADR-041 β KI-196 β Bug #25 β Bug #26 β ADR-042 v1 β v2 β v3 β v4) kept exposing new failure modes. Each pass was a real bug class, but after v4 the live audit still showed seeded-test failures because the name-slug pointer was being overwritten between tests β the structural truth a name-only key cannot safely disambiguate two visitors who share a name. The workarounds were accumulating without converging. Cost/benefit was wrong for an insurance-shopping product (rare- purchase, return sessions uncommon): ~1500 LOC + 100+ profile JSONs + 2 ADRs + 5 test files + ongoing audit-time state drift, for a feature whose value is "the bot remembers you next visit." Minimum-data- reβ¦6d5684e
-
#33: add "?" help affordance to every policy-calculation controlβ
Shared HelpTip component (createPortal body-root popover, desktop hover/focus + touch tap-toggle, Esc/outside/scroll dismiss, a11y labelled) driven by one CALC_HELP_COPY map. Wired next to every calc control across all 3 surfaces: - ProfileBuilder sliders (sum insured / existing cover / co-pay / budget) - PerPolicyPremiumEstimator (sum insured / co-pay) - PolicyPremiumWidget (sum insured / tenure / deductible) Deductible tip auto-absent where unsupported (sits inside the #29 supportsDeductible gate). Copy is purely qualitative β zero digits/%/βΉ (no-invented-numbers). Verified: tsc 0, eslint 0-new vs baseline, static build OK, copy-map digit scan clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>deefe3a -
feat(#31): deterministic profile-aware {strengths,caveat} policy summary on all 3 surfacesβ
Replaces the generic grade one-liner with a per-(profileΓpolicy) ProfileSummary{strengths[], caveat} computed on the SAME pass as the marketplace grade (scorecard.build_profile_summary): deterministic, no LLM, no fabricated numbers, no /100 or A/B in prose; ~4-5 most-material strengths for THIS profile + the one honest grade-capping caveat; fallback to one_liner when facts-sparse/insufficient-data. Rendered at the TOP of CitedPolicyCards, PolicyDetailModal, marketplace PolicyCard, and PolicyScorecardWidget. Β§4c: /api/policies/{id}/scorecard now takes session_id and resolves the profile via brain_tools.union_snapshot identically to /api/policies/all; single-endpoint defers to the catalogue (single source of truth) so profile_summary+grade are byte-identical across surfaces for all 148 (new parity test). Verified: full pytest suite exit 0 (no regression); test_profile_ summary + parity + endpoint_catalogue 21/21 (incl. 148Γ6-profile invariants, deductible-gate, non-fabrication, caveat-tβ¦d486a56 -
fix: deductible gating (#29), existing-cover steering + dangling-turn guard (#30), compare-modal full reviews (#32)β
#29 β deductible selector/discount was applied to all 148 though only 2 truly offer a voluntary deductible. New premium_calculator.policy_ deductible_support() (deductible_amount>0 AND not top-up β exactly bajaj-allianz__health-guard, star-health__star-assure); estimate + bulk gate the discount (defense-in-depth); PremiumEstimateResponse echoes supports_voluntary_deductible/allowed_deductibles; widget renders the deductible row only when supported. tests/test_deductible_ eligibility.py sweeps all 148. #30 β existing_cover_inr drove neither ranking, retrieval phrasing, nor framing; bot promised 're-evaluate' then stopped; re-eval recycled 2/3. Decisive fix B1-c: +22 existing-cover term in _fit_score for top-ups + seed out-of-window top-ups in _quality_seed_candidates. B1-a: RULE 2 mandatory existing-cover phrasing + Worked example C + RULE 2.6 framing mandate. B2: RULE 3.7 never-promise + _is_promissory_ no_action + one-shot loop guard that forces the promised tool call. B3: RULE 3 matβ¦3fcae97
-
fix(chat): thread AbortController signal into postChat() so barge-in cancels the in-flight requestβ
Resolves the 2 pre-existing page.tsx TODOs. The AbortController, currentSendAbortRef, the barge-in-abort window listener, the AbortError catch ('stay silent') and the finally cleanup were all already in place, and api.ts/postChat() already accepts + forwards signal to fetch via _fetchWithRetry β the ONLY missing link was the send() call site not passing controller.signal. Added that one arg; corrected the now-stale TODO/comment blocks (they claimed the signal was 'not yet plumbed' / 'has no effect'). Frontend-only, additive. Verified: tsc clean; eslint 29/13/16 == baseline (0 new). The 8 prior live-verified fixes are unaffected (no shared code path). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>8831b7b -
fix(batch): voice interim, TTS truncation, RULE2.5 re-ask, faithfulness regression, markdown, compare-reviews, policy-nameβ
Eight user-reported defects fixed together (all root-caused, all verified): #17 page.tsx PTT live transcript: separate inline SpeechRecognition had continuous=false + no-op onend (died after first pause, never restarted) + replace-not-accumulate. Added cross-session final accumulator, want-gated onend restart + 3s heartbeat, trailing flush. #19 sarvam_tts.py: bulbul:v2 silently voices only the first sentence of an over-real-limit single request; hard-coded 1500 ceiling meant the chunker never engaged for 370-720-char replies. Ceiling 1500->500, dropped undocumented enable_preprocessing, added a WAV-duration truncation guard (fail-loud). RED->GREEN proven. #18 single_brain.py: _profile_to_snapshot never exported smoker/ copay_pct/family_medical_history/parents_age_max, so the model couldn't know they were captured -> RULE 2.5 re-asked them. Snapshot widened + RULE 2.5 'omit captured items' directive. #23 single_brain.py: get_policy_facts policies now regisβ¦8828a2e -
fix(voice/brain): remove hold-space, fix silent TTS + policy-Q&A refusalβ
Bug 1: remove the hold-SPACE-to-talk path entirely (listeners, state, delegated fns, all SPACE UI strings, the welcome 'Hold SPACE' tile + ModeIcon). Push-to-talk button is the only voice-capture control. Deleted the now-invalid test_space_hold_ptt_delegation.py; corrected the stale test_ptt_preroll_warm_stream.py docstring. Bug 2: single_brain.py overwrote accumulated prose with '' when a tool-only Gemini iteration returned no text (two sites: CASE A end-of-loop, CASE B tool-iteration). Guarded both with 'if text:' so the spoken reply survives -> TTS no longer skipped after profile/recommendation. Bug 3: in-chat CitedPolicyCards never fetched insurer reviews; added a getInsurerReviews fetch + a 'Reviews:' line (claim ratio / grade / headline) mirroring the #65 claim-experience pattern + the #76 'never silently vanish' rule. Bug 4/5: the brain had NO tool for claim-settlement / denial / complaint / review data (retrieve_policies returns wording only) and was never shown its own shorβ¦abbb3a5 -
fix(#63): header premium pill is the TYPICAL cohort range, labelled as suchβ
The header pill showed a bare 'βΉXββΉY/yr' while the LIVE PREMIUM panel showed a different (often higher) per-plan number β read as 'random different numbers'. Per estimate_premium_band's KI-278 contract this is DELIBERATE: the pill is the p25-p75 typical-cohort band; the panel is ONE specific plan's estimate (may sit outside the typical band β expected, not a contradiction). NO pricing math changed (so #44's 0-violation engine is untouched β gate rc=0). Fix is purely clarity: - PredictedPremiumBandResponse now surfaces sum_insured_used (the model was silently dropping the value the contract already returns) - api.ts type + page.tsx: pill reads 'Typically βΉXββΉY/yr'; tooltip explains it's the typical range similar buyers pay (at βΉN cover) and that a specific plan's live premium can sit above/below it β expected. Backend import OK; full pytest rc=0; tsc/build green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>e21c985 -
fix(#65): surface claim-experience on inline chat compare cardsβ
The inline CitedPolicyCards strip showed grade + one-liner but omitted the claim-experience (insurer claim-settlement) signal that the full compare modal carries β user flagged the reviews/claim section missing from the inline comparison. Now, when a card's scorecard is loaded, the claim sub-score (matched case-insensitively) renders as a compact 'Claim experience: N/100 Β· <signal>' line. Guarded: nothing shown until the scorecard loads or if no claim sub-score exists. tsc clean; frontend build green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>45a9a70 -
fix(#66): enrich the sparse POLICY DETAILS expanderβ
The expander showed only policy name + insurer + PDF link (user: 'what is the point of this'). PolicyDetails now takes the resolved marketplacePolicy and renders the key decision facts when present: Cover, Grade, No-claim bonus, Pre-existing wait, Initial wait, Room rent, Co-pay, Network hospitals, Max entry age β each row only shown when the value exists (no fabricated/empty rows). citation-only fallback unchanged when no marketplace row resolves. tsc clean; frontend build green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>bb734ab -
fix(#76): show the customer's chosen cover, not 'As per policy schedule'β
When a plan publishes no fixed SI tiers the premium IS already priced at the customer's desired_sum_insured_inr, but the Cover-amount row still rendered the dismissive 'As per policy schedule' placeholder β looking like the customer's stated cover was ignored. SnapProfile now carries desired_sum_insured_inr (the live profile already provides it; build green) and buildSnapshot overrides the placeholder with 'βΉX (your chosen cover)' ONLY when the plan has no published SI AND the customer gave one β otherwise unchanged. fmtSumInsured signature untouched (used elsewhere). tsc clean; frontend build Compiled successfully. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>1e171b7 -
fix(#64): preserve EXACT budget βΉ β slider shows what the user saidβ
The annual-budget slider is continuous, but budget round-tripped through a lossy 4-band enum: budgetBandToInr() could only ever return 12k/22k/45k/75k, so 'I don't want to spend more than 15000 a year' showed as βΉ12k. Added a lossless exact field end-to-end: - needs_finder.Profile.budget_inr; brain_tools SLOT_UNION + _ACCEPTED_FIELDS - save_profile_field: when budget_band is captured, also parse + store the EXACT βΉ (numeric, or strip per-annum qualifiers then _parse_inr_amount β same KI-161 guard _coerce_budget_band uses; verified '15000'/'βΉ15,000/yr'/ '15000 a year'/'more than 15000 a year'/'around 25k per year' β 15000/25000) - main.py ProfileUpdateRequest + apply tuple accept budget_inr - api.ts UserProfile (+nullable) gains budget_inr - page.tsx: slider seeds from budget_inr ?? band-fallback; reseed effect same; handleSave sends budget_inr (exact) alongside the derived budget_band (pricing contract unchanged). Band stays the pricing contract; budget_inr is the display trβ¦06c7cbc -
fix(#53+#54): page.tsx SPACE-hold PTT delegates to warm-stream hookβ
Final wiring of the warm-stream/pre-roll engine (#53/#54). The SPACE-hold push-to-talk path no longer cold-starts its own getUserMedia + MediaRecorder per press; it delegates to streamingVoice.beginPushToTalk() / endPushToTalk(). The hook keeps the OS mic warm and prepends an 800ms pre-roll, so the first word ('Sir.') is always at the head of one valid webm blob (head-clip #53 eliminated) and capture begins instantly (no multi-second start delay #54). All prior semantics preserved: e.repeat/ modifier/shouldSuppressSpace guards, recording/busy gate (+ new spaceHoldPttInFlightRef re-entrancy guard), spaceHoldOwnsRec / setSpaceHoldActive, bot-TTS interrupt, voicePhase UX, busy ownership left to send() (avoids silent turn-drop), maybeResumeLive/userPrefersLive, mic_permission_denied banner, sub-threshold tap = clean no-op, no double-submit. On-screen PTT button left on legacy path (separate handler, out of reported scope β tracked for follow-up). tsc clean; build green; pytest 233 passed β¦2bb7b0f -
fix(#55+#56+#53/#54-engine): TTS full natural readout + voice warm-stream/pre-rollβ
#55 TTS 10s truncation: voice_format._truncate_for_voice(max_words=55) chopped every advisor reply to ~55 words (~10s) before it reached Sarvam. Cap removed (max_words now ignored unless >=100000). Latent Sarvam Bulbul v2 1500-char cap covered: sarvam_tts now char-ceiling chunks at item/sentence/comma seams, synthesizes sequentially, gapless WAV concat, propagates any chunk error (no silent partial) β STT-style. #56 TTS normalization: _normalize_abbreviations + _normalize_ranges β e.g./i.e./etc. spoken as words; '/' β 'or'; βΉ/L/Cr/K/% and en-dash ranges expanded; markdown/list numbering stripped. Verified on the exact 6-question pricing message (all 6 questions present, artifacts gone). #53/#54 ENGINE: useStreamingVoice warm pre-armed mic + 800ms PreRollRing + 200ms deliberate-hold gate + beginPushToTalk/endPushToTalk/ consumePreRollChunks API. Keeps the OS mic hot so page.tsx getUserMedia is ~10-50ms not 200-700ms (latency #54) and the first word is captured (head-clip #53). page.tsβ¦7d87d62 -
fix(#57+#58+#59): canonical-resolve compare-card marketplace lookupβ
One root cause, three symptoms on the HDFC ERGO Optima Restore compare card. page.tsx policyById was keyed ONLY by exact marketplace policy_id; the compare modal resolves the marketplace row by the CITED policy_id. A recommendation can cite a doctype/variant/alias id that is not byte-equal to the marketplace card's id (same canonical-identity class #40 solved for grades) β policyById[id] undefined β the card silently degraded: - #58 no network_list_url β 'Hospitals list' link missing - #57 no rationalised SI β Cover amount fell back to 'As per policy schedule' - #59 fewer populated fields β shorter/asymmetric vs Niva Bupa & Star Fix: build a canonical-resolving index (exact policy_id wins, plus doctype-stripped product_key + normalised policy_name + aliases, never overwriting a real id hit) and a _resolvePolicy(id,name) fallback chain; PolicyCompareModal now passes c.policy_name as the canonical fallback. Niva Bupa & Star already matched exactly so they were unaffected; HDFC now resolβ¦e525764
-
fix(#40+voice+upload): SSOT scorecard parity + Sarvam 30s-truncation + uploaded-PDF retrieval gateβ
#40 SINGLE SOURCE OF TRUTH: extract the marketplace catalogue into backend.main._marketplace_catalogue + marketplace_grade(); brain_tools ._scorecard_signal now delegates (deleted the parallel doctype-rank/_merge re-implementation). Rec-card grade == marketplace grade for all 148 by construction β deterministic oracle 790 ids / 0 mismatches; parity test rewritten to assert the full id universe + alias/doctype edges. VOICE: Sarvam saarika REST has a hard ~30s limit and silently returns only the first 30s (HTTP 200). sarvam_stt now decodes to 16k mono and splits >25s audio on silence, transcribes sequentially, concatenates, raises on error (no silent failure). Frontend POST timeout scales with blob size. Regression test: 92s utterance -> all 92 words. UPLOAD: brain_tools profile-gate silently returned 0 chunks for a freshly uploaded PDF asked about before fact-find (contradicted the 'searchable now' UI promise). Added session-scoped quarantine bypass + single_brain UPLOADED-DOC prompt β¦a5d9bfd -
fix(pricing+scoring): rebuild premium engine to 0 logical violations + classification, faithfulness, links, writingβ
Claude Code +1: Claude Opus 4.7 (1M context)Pricing: rebuilt sampleβpremium as median-of-normalized-bases (monotone by construction) + real-fact product-type classifier + age-bucket-key fix + type-aware abs/low caps + P7 capped vs cheapest real comprehensive + Sanjeevani rel-cap. Exhaustive harness 3,316β0 (P1-P8=0, 104,760 checks); 5 monotonicity + 4 strict all-148 seeds clean. Deep-research harvest (6 agents, integrity-gated): 93/148 now real-quote-anchored, rest typeΓprofile-modelled w/ honest provenance labels. Classification: fixed Health Guard/Star Assure (voluntary-deductible comprehensive mislabelled topup β dedβ₯βΉ2L threshold), Criti Care/Medicareβdisease, Energyβcomprehensive, Health Protector Plusβtopup. Scoring: parity-by-construction (_scorecard_signal mirrors marketplace doctype-rank + merge); harness S3=0, test_scorecard_parity green. Reviews source-map + 148 confirm. Weighted-avg math audited PASS. Faithfulness: _verify_prose_grounding β UINs in reply prose must be retrieved-grounded (faithfulness_passed now coβ¦f266901 -
fix(reco): cap 3, exclude non-extracted policies, unify premium, ask PEDβ
Claude Code +1: Claude Opus 4.7 (1M context)Five live recommendation-card defects, fixed at source: - #28 hard β€3 cap in _build_recommendation_citations + prompt 2-3 + compare modal β€3 (>3 collapsed the layout to 1 char/line) - #29 _has_extraction renderability gate: non-extracted policies excluded from _quality_seed_candidates AND the citation gate (was rendering raw slug / N/A / 'No extraction available' / 'Data not indexed') - #30 'Your share & the limits' always renders both rows with 'Not specified' fallback (was omitting nulls -> different field per card) - #31 removed Path C NonCuratedPricingNotice (dead component+styles deleted); estimate_premium_band now p25-p75 interquartile not raw min-max (was identical 30x-wide band on every non-curated card) - #32 SYSTEM_PROMPT now mandates the explicit pre-existing-conditions question before retrieve_policies Tests: rewrote no-cap + band-superset guards to the new contracts, added tests/test_extraction_gate.py + tests/conftest.py renderable-stub; full pytest gate green; frontendβ¦61980e6 -
chore(cleanup): frontend β drop stale narrative comments (current-standard)β
Comment-only: removed a dated KI mistake-narrative on the tts_error_code type and trimmed a few "old hack / used to" history parentheticals in page.tsx / globals.css to clean current-behaviour wording. No TS/JSX/CSS behaviour change. Completes the codebase-wide stale-content purge (history of record stays in ADR/KI/README only). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>3a0fde4
-
fix(ui): insurer logos β transparent on card, aspect-correct (not distorted)β
User-reported live bug. Two causes fixed: - 10 logos had a baked-in white background (acko, bajaj-allianz, go-digit, icici-lombard, iffco-tokio, indusind-general, niva-bupa, sbi-general, star-health, tata-aig) β edge-seeded flood-fill whiteβtransparent + tight-crop (interior white preserved). They now sit directly on the card. - InsurerLogo forced a square box β wide logos (1:1 β¦ 4.9:1) collapsed to slivers. Switched to fixed-height / auto-width, aspect-preserving, capped. Originals kept in local _logo_originals_backup/ (gitignored). tsc clean; verified locally via Playwright marketplace screenshot. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>74e87b6 -
recovery: integrate stalled-session work + de-stale/cleanup (pytest 215 green) [build-fix]β
Resumes the session whose 3 background agents stalled on the 600s watchdog; captures the prior session's uncommitted #42β#110 work + data exercise plus this session's verified recovery changes. (Rebuilt from the first attempt to store frontend/public/insurer-logos/*.png via Git LFS β HF Spaces' pre-receive hook requires it; .gitattributes updated, tools/.pdf_text_cache gitignored.) Prior-session work captured (was uncommitted, behaviourally live-tested): - single_brain rewrite, full frontend rebuild, compare/scorecard/premium UI, ~77 40-data/policy_facts sourced-data edits, new tests/tools, render.yaml drop. This session's recovery (surgical, verified, behaviour-preserving): - Fix app-wide HTTP 500: a `*/` inside a CSS comment killed the stylesheet. - Remove dead get_judge_llm everywhere (judge retired in single-brain rewrite). - eval/run.py: repair imports + hard-guard against stale results.json. - Centralize ~13 hardcoded "40-data" literals to one settings.DATA_DIR (resolves idβ¦b87bd2d -
deploy#2: unified reco-fit gate + session-privacy fix + profile-completeness + full UI rebuildβ
- Reco-fit gate (absorbs #10/#26): product-type + hard-eligibility(entry-age) + required-feature(maternity) + fit-rank + UIN dedup; new policy_identity.py; fixes overall_score rank-inversion. 7-persona audit failures resolved. - Profile session-persistence privacy leak closed (name-keyed directory scan removed; recall now staged + confirmation-gated, fails closed) + single_brain "Are you <name>? yes/no" confirm-prompt. - Profile-form completeness: + desired_sum_insured_inr/smoker/copay_pct/ family_medical_history; ProfileUpdateRequest silent-drop closed. - Full premium UI rebuild (front-page design system): profile panel, chat/AI replies, cited cards, marketplace, compare modal, scorecard/premium widgets; Live(BETA) real warning modal; front-page proseβbullets. - 117 backend tests pass; frontend production build clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>b134f5b -
data+scoring: verbatim-source all policy_facts, recalibrate scorecard, fix recommendationβ
- Re-sourced ~2900 cells to verbatim PDF clauses (v1/v2/v3 fleets); 0 fabrication, 0 legacy-provenance, ~250 wrong values corrected; image-only Acko cells dropped. - Removed max_renewal_age from scoring (IRDAI lifelong is universal); root-caused 999. - Recalibrated 6 sub-scores + thresholds: real A/B/C/D/F spread (was ~90% B); fixed-benefit N/A reweight. - #9 citations = exactly the prose-named policies (no slice cap). - #10 eligibility gates (no top-up for first-timers, zero-copay, SI floor) + profile-fit rank. - Voice TTS silent-failure surfaced + codec fix; 14 dead source URLs replaced. - scorecard/compare/bulk now merge corrected policy_facts (divergence fix). - 62/62 tests; two-part verify: 4113 verbatim-verified, 66 documented residual, 0 fabrication. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>7081aaa
-
fix(pricing): KI-277 β F6 Option B+ curated vs non-curated premium UIβ
User clarified: per-policy pricing is only real for the 26 curated policies in illustrative_premiums.json. For the other ~124 policies in the corpus we have NO quote data β the flat heuristic just reuses the same buyer math across them, giving false per-policy precision. Implementation of Option B+: - Curated policy (base_sample_used=true): existing slider widget renders unchanged β real quote-anchored estimate with SI/tenure/deductible sliders + Β±15% range + methodology footnote. (Removed the now-redundant "Estimate" badge since this branch is curated-only.) - Non-curated policy (base_sample_used=false): NEW NonCuratedPricingNotice sub-component renders instead. Blue-accented info card. Reads: "We don't have a verified quote for [Policy Name] yet, so we can't show a plan-specific estimate. Based on your profile, plans in this category typically cost: βΉX-Y/year." + median sub-line + sample size + footnote pointing to PolicyBazaar / InsuranceDekho for an exactβ¦fc6581d -
fix(landing): KI-276 β remove redundant subtitle/no-commissions/source-link tripletβ
User asked to delete the welcome.subtitle text. It said: "I'll ask a few short questions, then show you 3 policies that match β with the exact reasons each ranked well. No broker commissions in my ranking. Every fact you see has a source link." Removed because Section 1 ("How this works") immediately below already explains the same flow in a cleaner numbered-step format. Keeping the hero heading + Section 1 below it; removed the paragraph between them. i18n keys (welcome.subtitle / welcome.no_commissions / welcome.source_link) left in i18n.ts as dead β could be cleaned up in a follow-up sweep, but the renderer no longer references them. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>a16d228 -
feat(profile+pricing+voice): KI-275 β F-bundle: smoker + recap-verify + premium scope + price consolidationβ
F2 β Smoker slot end-to-end (KI-275): - needs_finder.Profile: smoker: Optional[bool] field - brain_tools._ACCEPTED_FIELDS + SLOT_UNION extended (now 16 slots). _coerce_smoker accepts yes/true/smoker/tobaccoβTrue, no/non-smokerβFalse, empty/unclearβNone. - single_brain SYSTEM_PROMPT RULE 2.5 item 7: ask "Do you smoke or use tobacco?" Save smoker: save_profile_field(field="smoker", value="yes"/"no"). - premium_calculator bulk_estimate threads smoker_mult (1.4Γ when True) through both curated-anchor + flat-base paths. Surfaces smoker_loading_x + smoker_loading_reason in breakdown when !=1.0. - Premium delta: 35yo metro 10L SI no-PED β βΉ11,500 β βΉ14,300 (+24% via curated 1.35Γ) / βΉ9,000 β βΉ12,600 (+40% flat fallback). F3 β Recap-vs-reality fix: - single_brain RULE 4 new "RECAP VERIFY" sub-section: forbids recapping slots not actually saved via save_profile_field. Worked example for the diabetes/family_medical_history split (don't conflate them). - main.py post-turn confirmβ¦a7d8209 -
fix(ux+voice): KI-274 β landing page enterprise redesign + Sarvam 429 friendly errorβ
Two parallel bundles committed together: A β Landing page enterprise 3-section redesign (frontend/src/app/page.tsx): - Removed: 4 example suggestion chips ("nonsense"), yellow standalone callout "Tell me the truth", "You can type below" narrative, "166 policies" standalone line, header EN/HI lang toggle (already removed in KI-257). - Section 1 "How this works": 3-step grid with numbered teal circles β (1) ask Qs β profile, (2) match 150+ policies, (3) customised premium estimate. Lightbulb icon header. - Section 2 "Using the bot": 4-mode card grid β Type / Push-to-talk / Hold SPACE / Live (BETA). Mic icon header. Note about Sarvam TTS + Hindi. - Section 3 "Two things before we start": 2 callouts side-by-side β Left (amber/teal): "Tell me the truth, even on hard things" (absorbed yellow callout). Right (muted): "Speaking to the bot" β speak slowly, English OR Hindi, the bot mirrors. Shield icon header. - Visual: rounded cards with subtle borders + shadows, hero gradientβ¦ce7f6d0 -
fix(ui): KI-273 β EST. PREMIUM chip always visible (was hidden at <50% profile)β
User feedback: after KI-269 merged the two premium chips into one, the chip-CTA disappears at 0% profile completeness. Lost the entry point to the premium calculator for users exploring before any conversation. Fix: remove the `completeness_pct >= 50` gate on the chip. Now ALWAYS renders, with two display states: - Profile <50% complete (or no sample): label reads "Tap to estimate" (Hindi: "Tap ΰ€ΰ€°ΰ₯ΰ€"). Clicking still opens the panel β sliders default to standard fallbacks (35yo, 10L SI, metro, no PED, 0 copay) which the user can move manually. - Profile β₯50% complete with sample: label reads the actual band "βΉXββΉY/yr" derived from estimate_premium_band. Tooltip updated to "Tap to estimate / refine premium with sliders" so it reads sensibly in both states. Behavior preserved: - Same onClick (toggles showPremium, closes sibling panels) - Same amber/orange gradient + RupeeIcon + edit-pencil affordance - Active ring when panel is open - KI-270 + KI-272 panel pre-fill from profilβ¦e04b308 -
fix(panel): KI-272 β PremiumCalculatorPanel copay pre-fill + re-sync on profile loadβ
E1 Playwright run found three pre-fill bugs in PremiumCalculatorPanel that D1 either missed or that occurred via timing race: 1. **Copay always 0** β D1's derivation helpers covered age/SI/family/PED/ city but copay was hardcoded `useState(0)`. Profile's `copay_pct=20` never propagated. Fix: `useState<number>(initialProfile?.copay_pct ?? 0)`. 2. **Age stuck at 35, family stuck at "Self only"** β useState initializers run ONCE on first mount. If profile data loads AFTER the panel mounts (race: user clicks the chip the moment profile finishes fetching), the sliders never update. Fix: new useEffect watches `initialProfile` changes and updates each slider IFF the slider still holds its initial-default value. Once user moves a slider, future profile updates no longer override their choice (snapshot-comparison ref prevents redundant runs). 3. **SI now correctly prefers desired_sum_insured_inr over existing_cover_inr** β already shipped in KI-270 / D1; this commiβ¦7a8965b -
fix(types): KI-270 β Frontend UserProfile schema add 3 missing slotsβ
Closes the typing gap D1 flagged after KI-269: backend added desired_sum_insured_inr (B5), copay_pct (D2), family_medical_history (D2) to the Profile dataclass, but the frontend TS type was lagging. frontend/src/lib/api.ts: - UserProfile.desired_sum_insured_inr?: number (B5/KI-258) - UserProfile.copay_pct?: number (D2/KI-269) - UserProfile.family_medical_history?: string[](D2/KI-269) frontend/src/app/page.tsx::PremiumCalculatorPanel: - SI prefill now prefers desired_sum_insured_inr (the canonical target) over existing_cover_inr (D1's typed-proxy fallback), with 1_000_000 ultimate fallback. Closes the typed-proxy workaround. Verification: - npx tsc --noEmit: clean - npx next build: Compiled successfully, 4/4 static pages generated - desired_sum_insured_inr now referenced in both api.ts type + page.tsx prefill Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>dab7341 -
feat(profile+pricing): KI-269 β D1+D2 bundle: chip merge + panel pre-fill + copay + family historyβ
D1 (frontend, page.tsx) β chip merge + panel pre-fill: - Deleted the redundant "ESTIMATE Annual premium" CTA button. - Made the "EST. PREMIUM βΉX-Y/yr" band chip itself clickable: same onClick as the old CTA (toggles PremiumCalculatorPanel + closes sibling panels). Added hover state (ring + brightness + cursor-pointer), chevron-edit SVG, tooltip "Tap to refine premium with sliders" (en + hi). - PremiumCalculatorPanel now reads `initialProfile` prop (passed from page as `profileCompleteness?.profile`). Three pure derivation helpers pre-populate the 5 sliders from the live profile: Age β profile.age (fallback 35) Sum insured β existing_cover_inr (fallback 10L; will widen to desired_sum_insured_inr once UserProfile schema is regen'd) Family covered β derived from profile.dependents string Pre-existing conditions β mapped from profile.health_conditions City tier β profile.location_tier (default metro) - Users can still override via sliders post-open. Dβ¦dea6883 -
refactor: KI-268 β Path B cleanup: -5,219 LOC legacy + nim_fallback + chain collapse + modal wiringβ
CLEAN1 β nim_fallback replaces legacy orchestrator fallback (+190 LOC, NEW): - backend/nim_fallback.py: handle_turn_fallback(session, user_text, chat_history) picks NIM via llm_health.get_primary("brain") with BRAIN_CHAIN[0] last-resort. One NvidiaNimLLM.chat call with 15s timeout. Never raises β graceful TurnResult on timeout/exception. - main.py: removed `from backend.orchestrator import handle_turn`. Both fallback branches (SingleBrainError non-sticky + USE_SINGLE_BRAIN=False) now call nim_fallback.handle_turn_fallback. Sticky-graceful-retry preserved. CLEAN2 β Port _normalize_dependents into brain_tools, delete 9 legacy modules: - brain_tools._coerce_dependents now uses ported _normalize_dependents_inline + _CANONICAL_VALUES tuple. Zero imports from sales_brain_normalizer. - DELETED (5,219 LOC total): * orchestrator.py (1,832) * sales_brain_normalizer.py (855) * sales_brain.py (819) * faithfulness.py (616) * providers/tiered_brain_llm.py (257) * persona.py β¦55fb938 -
feat(profile+pricing): KI-259..KI-266 β B-bundle (compare modal + per-policy + scorecard + premium band + budget/SI + union + persistence + recall)β
B1 β Structured recommendation cards + Compare modal - NEW frontend/src/components/PolicyCompareModal.tsx: side-by-side compare for up to 3 cited policies. Each column = insurer logo + policy name + premium-calc slot + scorecard slot + policy details expandable + PDF. - page.tsx Message renderer now uses CitedPolicyCards (replaces flat PolicyChipsFromCitations). "Compare all" pill opens the modal when >=2 cited policies present. Removed dead PolicyChipsFromCitations (-67 LOC). B2 β Per-policy premium widget with sliders + profile defaults - NEW frontend/src/components/PolicyPremiumWidget.tsx: SI/tenure/deductible sliders, 300ms debounced fetch, AbortController cleanup, profile-summary line, "Estimate" badge when assumed=true, breakdown bullets. - backend/premium_calculator.py + main.py /api/premium/bulk: multiplicative model (base x SI x age-band x location x family x tenure x deductible). Anchors to illustrative_premiums.json when available (assumed=false); flat heuβ¦f6901d8 -
fix(voice): KI-258 β SPACE-hold-to-talk now actually worksβ
Two bugs from the KI-257 first ship: (a) isInputFocused() returned true whenever the chat textarea had focus β which is almost always β so SPACE-hold was DOA. Fix: only suppress SPACE when the focused input/textarea has user-typed CONTENT. An empty textarea (the fresh-chat default) now passes through, and the handler's e.preventDefault() blocks the stray space from typing. (b) `recording` and `spaceHoldActive` were in the effect's deps array, so every state change re-bound the keydown/keyup handlers with fresh closures. A keydownβkeyup pair often spanned two effect lifecycles with stale `recording` values. Fix: read all state via refs (recordingRef, busyRef, spaceHoldOwnsRecRef); deps reduced to [voiceMasterOn] so handlers bind once per Voice-toggle change. Also added spaceHoldOwnsRecRef so keyup only fires when THIS keydown started the recording β protects against the textarea being a legitimate target for a stray space-up event. Co-Authored-By:β¦96d766d -
fix(ui): KI-257 β restructure chat input: master Voice toggle + 3-button row + hold-SPACEβ
Per user redesign: simplify the chat input to just textarea + Send by default, with voice controls hidden behind a single "Enable voice" toggle. When voice is enabled, two equal options appear: Live (BETA) and Push-to-talk. Push-to-talk works in TWO modes: (a) click mic to start, click Stop to submit (classic) (b) hold SPACE to start, release SPACE to submit (like command line) Both PTT modes share the same startRecording() entrypoint which already calls interruptBotAudio("ptt-start") β so barge-in (interrupting the bot's TTS mid-sentence) works cleanly on both click AND SPACE-hold paths. This is the reliable barge-in path; Live voice barge-in remains in BETA. Removed from the UI per user request (functionality preserved as defaults behind the scenes): - Paperclip / PDF upload icon (textarea only; drag-drop still works via the existing fileInputRef handler if needed in future) - Voice reply checkbox (returnAudio state now const, default true) - Lang dropdown EN/ΰ€Ήΰ€Ώΰ€¨ΰ₯ΰ€¦ΰ₯ (ttsLang statβ¦ef90cd6 -
fix(voice): KI-256 β PTT primary + live voice BETA confirm gateβ
Per user decision: keep BOTH PTT (default + reliable) and live voice (BETA), but make the trade-off explicit so users don't enable always-on voice expecting production reliability. Architecture (no change to STT/TTS layer β Sarvam preserved everywhere): - PTT (default): MediaRecorder β Sarvam STT (authoritative, Indic-aware) + Web Speech runs in parallel ONLY for live interim transcript display in the gray-italic strip. Sarvam transcript wins on release. - Live voice (BETA, off by default, requires one-time accept): existing useStreamingVoice with Web Speech driving utterance commit + Sarvam blob as cleanup. Same path as before, just gated behind a warning. - Sarvam TTS for ALL bot replies regardless of input mode. Indic preserved: when user types in Hindi/Tamil/Marathi (via PTT or live), Sarvam STT transcribes the blob. Web Speech may garble the interim display on Indic but its result is discarded β the Sarvam text submitted to /api/chat is correct. Frontend changes (page.tβ¦438d1fa -
fix(closure+voice+latency): KI-253 β P-bundle from U1 fails (P2 watchdog + P3 mark_rec gate + P4 instrumentation)β
U1 Playwright re-test surfaced 4 remaining bugs after V-bundle landed. P-agents diagnosed + fixed: P1 β React #418 hydration: NO CODE CHANGE. V3 fix at page.tsx:229-232 + 357-363 (mounted flag gating micPermissionDenied) is correct + committed (52e5881). P1 local rebuild + serve produces zero #418 errors. U1's failure was a stale Next.js cache on HF Space β KI-252 redeploy will refresh. P2 β Voice "green pill, zero audio" silent failure (V4 incomplete): V4's catch worked for hard rejections (NotAllowedError), but TWO silent paths bypassed it: (a) Fake / silent stream β getUserMedia resolves but recorder.state never reaches "recording" (Playwright fake-mic, Android WebView, codec rejection). No error thrown, pill flipped to "Voice on" over dead stream. (b) OS-stalled getUserMedia β locked-down Chromium / mic-busy / WebViews leave getUserMedia pending forever instead of rejecting. V4's catch never fires; user sits in limbo. (c) PTT path bypassed the banner entirely β stβ¦8a7350c -
fix(ux+voice): KI-252 β align profile bar with Path B 7-slot ready gate + RULE 4 implicit confirmation + ZCR scalingβ
Root-cause of "70% DONE despite all data" + "Let me pause for a second": 1. Profile completeness bar mismatch (Q2 from user screenshot 59): - scorecard.py:profile_completeness checked 9 weighted fields: age 20% + dependents 15% + budget_band 15% + existing_cover_inr 10% + primary_goal 10% + location_tier 10% + health_conditions 10% + income_band 5% + parents_age_max 5% = 100%. - Path B's _REQUIRED_FOR_READY = (name, age, dependents, location_tier, income_band, primary_goal, health_conditions) β 7 slots. - So a fully captured Path B profile (Priya) shows only 70%: age (20) + dependents (15) + primary_goal (10) + location_tier (10) + health_conditions (10) + income_band (5) = 70%. The 30% gap is budget_band/existing_cover_inr/parents_age_max that Path B doesn't gather (intentionally β budget can be inferred from income). - FIX: re-weighted scorecard.profile_completeness to the 7 Path B slots: age 20% + dependents 17% + income_bandβ¦bcf9753 -
fix(closure+hydration+voice+admin): KI-248..KI-251 β V1-V4 bundle from Playwright smokeβ
V1 β recommendation closure ("I lost my train of thought"): ROOT CAUSE was a coercer/null-guard collision, NOT MAX_ITERATIONS or prompt length. Z6 prompt told Gemini β save_profile_field(health_conditions, "none"), _coerce_health_conditions stripped "none" β [], save_profile_field's KI-091 null-overwrite guard rejected [] as normalized_empty, profile stayed incomplete forever, retrieve looped, MAX_ITERATIONS=5 exhausted, defensive "lost my train of thought" fired. Three-angle fix: - (D primary) brain_tools._coerce_health_conditions: pure-negation tokens ("none", "no", "healthy", "n/a") now collapse to sentinel ["none"] (non-empty list) instead of []. Mixed input ("diabetes, none") still drops the negation noise. Downstream consumers verified safe. - (C) brain_tools.retrieve_policies profile_incomplete return now includes action_required="ask_user_for" + field=<first_missing> + exact_question so Gemini relays the question verbatim instead of looping. - (A) single_brain MAX_ITEβ¦52e5881 -
fix(arch+wiring): KI-237..KI-241 β Phase Y bundle (Y1+Y2+Y3+Y4 + profile-gate)β
Y1 β BrainProviderError + soft_hints consumer: - tiered_brain_llm catches BrainProviderError specifically: retryable=False fails fast (auth/safety), retryable=True falls through to NIM. - orchestrator soft-hint retry block (max 1 per turn): missing_citation re-prompts with [Source:N] addendum; hallucinated_policy constrains brain to cited_policies from X5's faithfulness verdict. Y2 β turn_idx stamping on policy events: - session_state.SessionState.turn_idx int field, incremented at handle_turn start in both orchestrator and single_brain. - All shown_policies / selected_policies / rejected_policies events stamped with turn_idx so admin /api/admin/recommendation-history can show conversation_turn instead of "β". - brain_tools.mark_recommendation records a shown_policies event via profile_store. Y3 β Backend honors X-Preferred-Codec for Safari/Webkit: - main.py chat() now accepts FastAPI Request; reads X-Preferred-Codec header (whitelisted: audio/wav, audio/mp4, audio/webm; else wav). -β¦2524073 -
fix(arch+robustness): KI-225..KI-235 β Path B single-LLM rewrite + audit bundleβ
Architectural simplification (KI-225, Path B) β replaces the two-brain sales_brain/qa_brain handoff with a single Gemini Flash call per turn using native function-calling. Kills 40+ scaffolding failure modes at once: - No fact_find vs QA routing boundary (every confirmation/knowledge edge case in should_route_to_fact_find disappears). - No faithfulness gate rejecting natural phrasing ("yes, that sounds correct"). - No separate profile_extractor pass overwriting captured slots with null (KI-091/094 root cause permanently fixed via save_profile_field tool guard). - No rigid normalizer enum β accepts what Gemini emits, light coerce only. - No 700-token JSON contract β Gemini function-calling separates tool calls from prose, no truncation trade-off. Feature-flagged: USE_SINGLE_BRAIN=true activates the new path; default off, legacy orchestrator preserved as fallback. SingleBrainError falls back to orchestrator transparently. New files: - backend/single_brain.py β Gemini function-calβ¦f15911b -
fix(voice+recall): KI-214 + KI-217 + KI-218 bundleβ
KI-214 β Block recognition for ENTIRE request-in-flight window. Previously dropResultsRef only blocked during <audio> playback (KI-203), leaving a 1-3s gap between send() firing and bot audio rendering+playing where mic captured bot voice from speakers. Now onresult also early- returns when isTextRequestPendingRef is true. Eliminates the entire echo-leak window from user submit until bot finishes speaking. KI-217 β Fix first-phrase cutoff in utterance batching. User showed "My name is Rohit Sarma" reduced to "last name" β start of utterance dropped. Root cause: rec.onend reset finalsRef.current=[] on every restart cycle. Chrome occasionally delivers buffered isFinal=true events for the early speech AFTER onend (same dirty- window quirk that motivated KI-203). Eager wipe meant late finals landed in a freshly emptied ref, then got wiped again before submit. Fix: introduced finalsConsumedRef monotonic cursor. onend reads finalsRef.current.slice(consumed), appenβ¦7fdaa57 -
fix(voice+slots+routing): KI-212 + KI-213 + KI-215 + KI-216 bundleβ
KI-212 β Aggressive barge-in thresholds for reliable trigger. BARGE_IN_RMS_THRESHOLD 0.025 β 0.008. BASE 0.005 β 0.002. MULTIPLIER 2.0 β 1.5. SUSTAINED_FRAMES 18 β 6 (~100ms vs ~300ms). Barge-in fires on much softer speech without requiring calibration. KI-213 β Push-to-talk shows live interim transcript. Added SpeechRecognition in parallel with MediaRecorder during PTT. Interim words stream into chat input as user speaks. On release, Sarvam transcript replaces interim text. Falls back to browser final if Sarvam fails. Self-contained in page.tsx. KI-215 β Don't prematurely flip free_form_session. Bug: once all 6 required slots captured + ready_for_recommendations =true, orchestrator immediately flipped free_form_session=True. User's confirmation reply ("Yes, that sounds correct") then routed to QA β faithfulness rejected with "I'd rather not answer that without stronger evidence." Now require the user's text to explicitly contain a recommendation keyword (shβ¦9a617cc