Spaces:
Sleeping
Sleeping
Commit History
-
fix(voice+chat+llm+docs): KI-155 + KI-156 + KI-157 + KI-158 + KI-159 + KI-160 bundleβ
Six conversation-pipeline + LLM-chain fixes addressing every live-test defect surfaced today, plus the documentation cascade. KI-155 β enforce <FF> trailer emission. Strengthened fact_find_brain system prompt with absolute final-instruction block + edge-case few-shots ('Hi' β still emit trailer, 'ok' β still emit trailer) so Groq Llama-3.3 (was elected as cross-provider fallback, was silently dropping the trailer) now complies. Smoke: My name is Rohit / I am 29 years old / to buy a health insurance policy β all three return fact_find_brain:: continue, no more ::fallback:no_trailer. KI-156 β fix bot non-response + 'not having any policy' uncaptured. Three sub-fixes: Fix A: extend negation regex in fact_find_normalizer._parse_existing_cover to cover 'not having', 'not got', 'not have', 'without (any|a)'. Fix B: stop-list in fact_find_brain._validate_capture for name field β reject hallucinated names that start with 'currently', 'not', 'no', 'looking', etc. (live bug: LLβ¦1c5baae -
feat(deploy): KI-152 β upload_to_hf.py syncs deletions, not just addsβ
After upload_folder, walk local tree + list_repo_files, then issue a second commit that deletes orphan remote files. Prevents ghost brochures lingering on the Space after KI-126/143/144-style renames. Adds --dry-run + --no-upload flags. HF_PROTECTED guards .gitattributes / .gitignore / README.md. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>38c937d -
fix(routing): KI-154 β empty-profile QA must route to fact_findβ
Live bug: user said 'to buy a health insurance policy' (clear intent to buy) and got a generic policy-fact dump citing Health Protector Plus + ACKO + IRDAI 2024 regulations on an EMPTY profile session. Bot quoted 'Any One Illness' definitions to someone who hasn't even given their name. Two failures combined: 1. FACT_FIND_TRIGGERS only had 'buy health insurance' (no article). 'to buy a health insurance policy' has 'buy A health insurance' β the substring match failed, classify_intent fell through to 'qa'. 2. should_route_to_fact_find force-routed only recommendation/comparison intents to fact_find on empty profile. QA was let through, which is correct for specific-policy questions ('Does Star Comprehensive cover IVF?') but wrong for generic intent statements ('to buy a policy'). Fix: 1. Extend FACT_FIND_TRIGGERS with more buying phrasings: 'to buy', 'want to buy', 'looking to buy', 'buy a ', 'buy an ', 'purchase', 'shopping for a', 'get a policy', 'need a plan', β¦a42771b -
fix(routing): KI-153 β profile-update utterances now route to fact_findβ
Live bug: user said 'My name is Rohit' and 'I am 29 years old' on the deployed bot. Both were classified as intent=qa and routed to the QA brain, which had no idea what to do with them and produced defensive 'not enough evidence in the policy documents' replies. The fact-find flow never even started. Root cause: classify_intent in backend/orchestrator.py uses a keyword trigger list (FACT_FIND_TRIGGERS) and falls through to 'qa' on no match. The list covered advice-seeking openers ('looking for', 'i want', 'should i') and greetings ('hi', 'hello') but NOT profile-answer phrasings β the exact text users produce when answering fact-find questions. Result: any name/age/city/family answer was misrouted. Fix: extend FACT_FIND_TRIGGERS with profile-answer patterns β 'my name is', 'call me', 'i am ', 'i'm ', 'years old', 'live in', 'married', 'single', 'with spouse', 'have kids', 'have parents', 'my income', 'first policy', etc. These match the natural answers users give to fact-find questioβ¦5b3fa14 -
fix(chat+marketplace+voice): KI-145 + KI-148 + KI-149 + KI-150 bundleβ
Five fixes from the live-test feedback cycle, all converged into one rebuild. KI-145 final (166 marketplace cards) β replaced strict-UIN merge with field-comparison rule. Same UIN + <2 decision-critical diffs (copay, PED waiting, maternity coverage+waiting, room rent, restoration, NCB, post-hospitalization) -> merge as alias. Same UIN + 2+ material diffs -> keep as separate card (true sub-variants). Result: ProHealth Prime + Protect, Reassure 3, ICICI Elevate, Activ Assure Diamond and 18 others correctly emit as standalone cards. 166 cards = 137 extracted-dedup + 29 curated standalone (variants + non-UIN-match). KI-148 (TTS pronunciation) β voice_format.py tts_preprocess now expands '15k' -> '15 thousand rupees', '1L' -> '1 lakh rupees', '1cr' -> '1 crore rupees', '15-30k' -> '15 to 30 thousand rupees', '60k+' -> 'above 60 thousand rupees'. Context-gated so '10K marathon' stays untouched. Stops the bot from reading 'βΉ15k' as 'fifteen k'. KI-149 (budget + income parser) β needs_findeβ¦48db939 -
fix(api): KI-145 β RENAME-vs-VARIANT smart dedup (final 164 cards)β
Replace strict-UIN merge with field-comparison rule. Same UIN + same decision-critical terms = merge as alias (rename). Same UIN + 2+ diffs = keep as separate marketplace card (true sub-variants). Decision-critical fields compared: copayment_pct, PED waiting, maternity coverage + waiting months, room rent capping, restoration benefit, NCB%, post-hospitalization days. Result: ProHealth Prime + Protect stay separate (PED 24mo vs 48mo, maternity Y vs N, post-hosp 180 vs 90). Activ One + Activ Health Individual merge as alias (only NULL incompleteness differences). Total marketplace = 164 cards. Bumps DATASET_CACHE_BUST so HF Space rebuild pulls fresh state.261abb2 -
fix(marketplace+voice+routing): KI-136 + KI-141 + KI-142 + KI-143 + KI-144 β full bundleβ
Five distinct fixes shipped together for a single rebuild cycle: KI-141 β hybrid alias dedup. /api/coverage + /api/policies/all now collapse curated marketing-rename entries (Activ One, Optima Secure, etc.) under their PDF-backed parent card, with aliases surfaced as 'Also marketed as:' on the marketplace cards. Frontend page.tsx + api.ts add aliases[] field on MarketplacePolicy. Card count went 158 -> ~137. KI-142 β UIN-primary merge rule. /api/coverage and /api/policies/all now build uin_to_parent maps from extracted JSONs and merge curated entries based on UIN equality. Falls back to source_pdf gate when UIN matches fail. 1 UIN = 1 marketplace card invariant. KI-136 β named-SKU comparison routing. orchestrator.py should_route_to_fact_find now accepts query and exempts intent=comparison when the question mentions >=2 named insurers/SKUs. Empty profile no longer traps SKU-specific compare questions in fact_find_brain. Verified: 'Compare HDFC ERGO Optima Secure and Niva Bupa Aspire β¦63290a7 -
fix(deploy): bump DATASET_CACHE_BUST -> ki138-v2 β force rebuild to pull post-KI-138 Chroma + extractedβ
The previous rebuild (24382536) was triggered by KI-140 commit 9c01288 with DATASET_CACHE_BUST=ki137-v1. That rebuild's snapshot_download layer ran in a race against two in-flight HF Dataset pushes: 1. Chroma binary re-upload (capturing KI-138's 27 in-place metadata updates) 2. Extracted JSONs re-upload (with KI-138 canonicalized names + slug renames for the 2 irda->irdai cases) Both pushes completed AFTER the rebuild started. To eliminate any ambiguity about which snapshot the current container holds, bump cache_bust again so the next rebuild is GUARANTEED to pull the now-final dataset state: β’ rag/corpus/ 206 PDFs β’ rag/extracted/ 201 canonicalized JSONs β’ rag/vectors/ 7,317-chunk Chroma (KI-137 ingest + KI-138 metadata)7b92d5d -
fix(rag+voice): KI-137 + KI-138 + KI-139 β ingest 21 curated policies into Chroma, canonicalize 84 policy names, fix voice VAD thresholds
9c01288 -
fix(api): KI-135 β /api/coverage counts from disk same as /api/policies/allβ
Refactor /api/coverage so total_policies counts unique product_keys from extracted/*.json (KI-133 dedup) + curated_facts pass-2, matching the marketplace card count exactly. Result: badge = cards = 158 / 19. The chunks count still comes from Chroma. NOTE: this is a SURFACE fix only. The underlying issue β that ~15 of those 158 policies have NO Chroma chunks and therefore the bot cannot retrieve or cite them in chat β is tracked separately as KI-137.737571a -
fix(voice): KI-134 β 5 blind fixes for silent-fail mic captureβ
Diagnosis agent (run after KI-131's green-pill-on-broken-worklet patch) ranked 5 high-probability additional silent-failure modes. All five patched in one commit since they're all in the same path. 1. AudioContext.resume() β Chrome/Safari autoplay policy starts new AudioContexts in state='suspended' when the click that toggled Voice on has already been consumed by React state propagation. Without resume(), worklet.process() never runs, no PCM frames arrive, green pill renders forever. Patch: explicit ctx.resume() before VAD start; on failure, flip setMicPermissionDenied(true) + setLive(false). (useLiveConversation.ts) 2. PTT silent-recording UX β pre-fix, blob.size < 1000 returned silently with zero user feedback. Now surfaces 'Didn't catch any audio β try holding the mic button while speaking.' (page.tsx) 3. PTT teardown race β 120ms wait between setLive(false) and getUserMedia isn't enough on HF Space's cpu-basic hardware to let AudioContext.close() (β¦e5b5e6c -
fix(api): KI-133 β dedup /api/policies/all to one card per policy productβ
Marketplace was showing 209 cards (one per PDF) while the badge said 138 policies. Confusing. Now sorts extracted JSONs by doctype rank (wordings > prospectus > cis > brochure), strips trailing __<doctype> from policy_id to make a product_key, and keeps only the first occurrence. Wordings (the canonical legal doc, with most complete data) wins for products that have multiple PDFs; brochure-only or cis-only products still get their card. Verified localhost: 209 -> 158 cards across 19 insurers. The remaining 158 vs 138 (badge) gap is under investigation in a parallel agent β likely 138 uses unique policy_NAME while 158 uses unique product slug, and ~20 products have slightly different filename slugs from their policy_name field (e.g., the arogya-sanjeevani two-name split flagged in the harmonization audit).804917b -
fix(api): KI-132 β drop regulatory from /api/policies/all + complete insurer_metaβ
After KI-130 fixed /api/coverage, the marketplace pane STILL showed: β’ '224 policies from 20 leading Indian health insurers' β’ Dropdown listing 'regulatory (13)' as a fake 20th insurer β’ 9 of 19 insurer cards rendering raw slugs (cholamandalam, national-insurance, sbi-general, royal-sundaram, oriental-insurance, iffco-tokio, go-digit, reliance-general, acko) instead of proper display names Root cause: I patched /api/coverage in KI-130 but missed /api/policies/all, which is a SEPARATE endpoint that backs the marketplace pane copy + filter dropdown + card list. The two endpoints had independent insurer_meta dicts, both with only 10 of 19 real insurers populated. Fix: β’ Add 'if slug == "regulatory": continue' in the /api/policies/all iteration loop (backend/main.py L1192) so regulatory JSONs (13 of 224) don't generate marketplace cards. β’ Expand insurer_meta in /api/policies/all to all 19 real insurers with curated display names + home URLs. β’ Apply the sβ¦e1e28dd -
fix(voice): KI-131 β voice OFF by default + surface AudioWorklet failureβ
Two bugs reported on live HF Space after KI-130 deploy: Issue A β voice mode shows green 'Voice on β just speak' pill at page load even for users who never opted in. Root cause: the useEffect in page.tsx rehydrated insurance_live_pref from localStorage and flipped userPrefersLive to true if a prior session had set it 'on'. Combined with ADR-028's 'Default ON' decision, anyone who'd ever visited had a sticky-green pill. Fix: remove the rehydration entirely + wipe the stale key on every load. Voice is now strictly opt-in per visit until the user clicks the pill. The persist-on-toggle effect at L210 still writes the user's *current* choice, but no one starts green. NOTE: this amends ADR-028; an ADR-033 should be written to record the new default β flagging as a follow-up. Issue B β voice was on but the mic captured nothing. Root cause (most likely per voice-diagnosis agent): AudioWorklet.addModule() can fail silently on some browsers/devices; the previous catch block at useLiveConversaβ¦a6115b2 -
fix(api): KI-130 β drop 'regulatory' from /api/coverage marketplace talliesβ
Pre-fix: marketplace badge showed '20 INSURERS / 156 POLICIES'. The 20th 'insurer' was actually the 'regulatory' slug β 18 IRDAI / NHA documents that are not insurance companies. They were leaking into the headline counts because the ingest pipeline stamps insurer_slug=<parent dir name> and rag/corpus/regulatory/ is a sibling of the 19 real-insurer dirs. Post-fix: marketplace badge shows '19 INSURERS / 138 POLICIES' (real insurance products only). The 'regulatory' bucket is excluded from total_insurers, total_policies, and the insurers[] response array. CRITICAL: this is a UI-tally change only. Retrieval / RAG / chat answers are unaffected β rag/retrieve.py::retrieve() pulls chunks from the Chroma 'policies' collection by vector similarity with no insurer_slug filter, so IRDAI / NHA chunks are still surfaced and cited when relevant. Verified in earlier E2E test: 'What does the IRDAI master circular say about moratorium?' returned a citation to regulatory__irdai-master-circular-stanβ¦47e7eeb -
fix(api): KI-129 β /api/coverage must not surface 'profile' as an insurerβ
The marketplace badge was showing '157 POLICIES / 21 INSURERS' on the live HF Space when real corpus is 156/20. The +1 in each came from a 'profile' slug surfacing in /api/coverage's by-insurer aggregation. Background β per KI-118 design (backend/profile_rag.py:24), profile chunks INTENTIONALLY live in the same Chroma 'policies' collection as policy chunks. The orchestrator boosts them at retrieval time so the LLM sees a 'USER CONTEXT' block alongside policy/regulatory text β this is correct and stays. But they were leaking into user-facing aggregations. Fix is a 4-line filter in main.py at the /api/coverage by-insurer loop: skip any chunk where insurer_slug=='profile' OR doc_type=='profile'. The chunks remain queryable for retrieval boosting; they just don't count. Verified on localhost (port 8000) after restart: total_chunks=7296, total_policies=156, total_insurers=20, no 'profile' slug. This is the user-visible piece. The companion endpoint /api/policies/all reads from rag/extβ¦33b4a96 -
fix(deploy): KI-128 β exclude _hf_dataset_backup + LFS pointers from Space pushβ
Two prior pushes (KI-126, KI-127) silently failed with: 403 Forbidden: Repository storage limit reached (Max: 1 GB) on POST /InsuranceBot.git/info/lfs/objects/batch. Root cause: tools/upload_to_hf.py walks the entire ROOT directory and respects ignore_patterns relative to walked paths. The previous IGNORE list excluded rag/corpus/**, rag/vectors/**, rag/extracted/**, but NOT: β’ rag/_hf_dataset_backup/** β which the new rag/corpus and rag/extracted symlinks (created in the 2026-05-15 session) resolve into. The walker followed those symlinks and re-enumerated 206 PDF blobs at paths the rag/corpus/** rule no longer matched. β’ rag/policies.duckdb β an LFS pointer file at project root that tries to push its LFS object on every upload. The HF Space's 1 GB LFS quota is reserved for ACTUAL Space-only artefacts; all corpus / vectors / extracted data lives in the companion HF Dataset (D-019). Adding rag/_hf_dataset_backup/**, **/_hf_dataset_backup/**, rag/policies.duckdb,β¦c20e471 -
fix(docs): KI-127 β correct cascade arithmetic, 224 -> 206 corpus PDFsβ
The KI-126 cascade-agent miscounted by treating regulatory PDFs as a separate category added on top of the 206. Reality: 206 PDFs total, comprising 188 product PDFs across 19 insurers + 18 regulatory IRDAI/NHA docs. Ground truth (verified against disk + HF dataset): rag/corpus/ -> 206 PDFs in 20 dirs (19 real insurer dirs + 1 regulatory dir) rag/extracted/ -> 206 JSONs rag/vectors/chroma.sqlite3 -> 7,295 chunks across 206 policy_ids kb/policies/*.md -> 222 markdown sheets (was 224 pre-deletion; -2 brochures) Files corrected (11 hits): β’ CLAUDE.md L7 β corpus 224 -> 206 + 20-insurer -> 19-insurer (regulatory is a slug but not an insurer) β’ rag/README.md L30 β 224 PDFs -> 206 PDFs β’ README.md L15 β 224-document -> 206-document β’ README.md L44 β 224 docs / 206 product / 20 insurers -> 206 / 188 / 19 β’ README.md L522-523 β 224 source PDFs / 206 across 20 -> 206 / 188 / 19 β’ README.md L547 β 224 markdown -> 222 markdown β’ README.md L595 β section heading (224) -β¦0a86a7c -
fix(corpus): KI-126 β drop 2 image-only PDFs + cascade docs across 3 reposβ
The 2 deleted PDFs are scanned-image PDFs that pdfplumber extracts as 0 chars, so they were never queryable through the RAG pipeline. OCR is explicitly out of scope. Removing them brings every surface back into agreement: β’ royal-sundaram/family-plus__brochure.pdf β Family Plus product is still covered via royal-sundaram__family-plus__wordings (text-extractable). β’ aditya-birla/activ-one__brochure.pdf β Activ One coverage is provided via aditya-birla__activ-health-individual__wordings (already in Chroma, 120 chunks). The separate aditya-birla__activ-one KB entry was independent and remains intact. Cascade across all surfaces (per the no-stale-content prime directive): β’ Deleted: 2 PDFs (HF dataset + local symlink target) β’ Deleted: 2 kb/policies/__brochure.md files β’ Deleted: 2 40-data/policy_facts/__brochure.json files β’ Deleted: 2 _hf_dataset_backup/rag/extracted/__brochure.json + 1 _raw.txt β’ kb/INDEX.md: rows removed; "Policies (255)" -> "Policies (2β¦f9adc25 -
perf(ingest): KI-125 β bump MPS embedding batch 64β128 for bulk re-ingestβ
Doubles batch size on Mac M-series MPS device. ~100 MB per batch (was ~50 MB), still well within unified-memory budget. Halves GPU kernel launches when ingesting all 206 policies + 18 regulatory docs from scratch (motivated by the 2026-05-15 re-ingest). CPU path unchanged at batch_size=32 to keep peak RSS bounded on machines without a GPU.9519893 -
fix(admin): KI-122 β clear LLM availability + in-use indicatorsβ
The admin LLM Chain panel showed a contradictory state β a chain's elected primary marked HEALTHY 100% while a red banner declared "all candidates credit-exhausted". The KI-116 reset-window fix mirrored `is_credit_eligible` but still left a hole: when one chain member had credits_reset_at=None (e.g. OpenRouter's prepaid wallet always stamps None) AND credits_remaining<=low_water, while peer NIM candidates had no credit signal yet (cold start), the banner loop registered any_signal=True on the gated member and never broke out via the permissive NIM peer. Banner fired despite the elected NIM primary being perfectly callable. Backend (`backend/admin.py::_chain_summary`): - New helpers `_candidate_available_for_calls` + `_candidate_credit_ exhausted_strict` produce per-member booleans the wire payload surfaces directly. - New strict banner rule: `chain_credit_exhausted` is true ONLY when ZERO members are available_for_calls AND at least one is strictly credit-exhausted (credits<=lβ¦86105c9
-
fix(ui): KI-120 β unify policy/insurer counts from /api/coverageβ
Top nav badge showed "223 POLICIES Β· 20 INSURERS" (hardcoded/stale). Subtext line below correctly showed "166 policies across 20 insurers indexed" from /api/coverage. Wired the badge to the same live source. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>d59cfe2 -
fix(deploy): KI-119 β DATASET_CACHE_BUST arg forces HF dataset re-pullβ
Docker layer cache reused the snapshot_download layer across HF Space rebuilds because the command string was unchanged. Symptom: even after uploading a cleaned Chroma to the HF Dataset, the Space served the prior cached layer's stale 7356-chunk DB. Bump DATASET_CACHE_BUST any time the dataset content changes; the value just needs to differ from the previous build's value to invalidate the cache. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>0693bf9 -
chore: trigger HF rebuild β pull cleaned Chroma (1 UUID, 3799 chunks)
a9718b3 -
fix(deploy): KI-119 β disable persistent /data/vectors symlinkβ
ROOT CAUSE of HF Space empty-retrieval bug found. Pre-fix entrypoint.sh: rm -rf /app/rag/vectors # delete fresh snapshot ln -sf /data/vectors /app/rag/vectors # symlink to persistent disk The Dockerfile snapshot_downloads a fresh Chroma from the HF Dataset at build time. The entrypoint then DELETED that fresh copy and pointed to /data/vectors, which on second+ builds held STALE Chroma from a prior run β including the corrupted profile_anonymous row that broke every collection.query() call. Our dataset upload couldn't help because the symlink overrode it. /api/coverage reported 7356 chunks (from the stale persistent copy) but collection.query() returned 0 on every QA turn β KI-111's wrap caught the exception and degraded to empty. Post-fix: - /data/vectors symlink REMOVED. Vectors stay at /app/rag/vectors, sourced fresh from the dataset on every build. - Stale /app/rag/vectors symlink unlinked at boot if found, so the fresh snapshot_download directory underβ¦0690bd6 -
chore: trigger HF Space rebuild to pull clean Chroma from datasetβ
KI-119 β uploaded cleaned local Chroma (rag/vectors/) to HF Dataset rohitsar567/insurance-bot-data via tools/upload_vectors_to_dataset.py. HF Space's Dockerfile snapshot_downloads this dataset at build time, so an empty commit on the Space repo forces a rebuild that pulls the fresh 84.8MB DB. Pre-fix, HF Space was running with the dangling profile_anonymous row still in the index; post-rebuild, retrieval will match local behavior (5 chunks per QA query). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>251f011 -
refactor(session): KI-118 β rip out session_id concept, name-based profiles onlyβ
- drop disk persistence in session_state.py (40-data/sessions/<id>.json no longer written) - profile_rag chunks keyed by name_slug instead of session_id - retrieve() takes profile_name_slug not session_id - frontend uses sessionStorage not localStorage so token clears on tab close - anonymous sessions never write to Chroma β corruption surface eliminated - KI-102/107/112/117 isolation scaffolding still in place but its threat model is now moot - added rehydrate_by_name() for cross-session re-entry via name lookup - tests flipped: profile-isolation now pins anonymous-no-write + name-A-vs-name-B - added tests/test_session_no_disk_persistence.py to lock the no-disk contract Rationale: insurance shoppers don't multi-session; cross-session memory is name-based (returning user provides name β pull saved profile). The session_id machinery was the root of the Chroma corruption fought today (profile_anonymous dangling row). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>f6249a7 -
fix(rag): KI-117 β boot-time cleanup of dangling profile chunksβ
The HF Space carries its own Chroma DB which still contains the legacy `profile_anonymous` row from KI-102's earliest deploy β a chunk written without a `session_id` metadata field. That row poisons every retrieval whose `where` clause references session_id, because Chroma raises when a filtered row is missing the filtered key. KI-111's wrap catches the raise so the bot doesn't crash, but retrieval returns empty on HF until the bad row is purged. KI-112 already prevents future bad writes (input guards on upsert_profile_chunk), and the local DB was cleaned manually. This patch adds a one-shot startup task in backend/main.py that, on app boot, scans the Chroma collection for any `doc_type='profile'` chunks lacking a non-empty `session_id` metadata field and deletes them. Runs idempotently β if there are no bad rows, it's a no-op. After HF rebuilds with this code, the boot task self-heals HF's DB on first request. - New helper `_startup_purge_dangling_profile_chunks()` registered via a β¦380491c -
fix(rag+admin): KI-112 hardening + KI-116 banner + admin copyβ
KI-112 β profile_rag.upsert_profile_chunk now refuses to write when: - session_id is missing / empty / not a non-empty str (the actual root cause: initial KI-102 deploy wrote `profile_anonymous` WITHOUT a session_id metadata field, and that dangling row poisoned every subsequent query via Chroma's plan executor β "Error finding id") - embedding shape is not a 384-dim list of finite floats (defence against future shape-mismatch corruption of the HNSW index) Local Chroma DB at rag/vectors/chroma.sqlite3 already cleaned by the KI-112 agent; corrupted copy backed up at rag/_hf_dataset_backup/rag/vectors.corrupted.1778799730/. KI-116 β admin /api/admin/health chain_credit_exhausted banner now mirrors llm_health.is_credit_eligible's reset-window logic. Pre-fix, NIM's 40-RPM rate signal (credits_remaining=0 after a spike) stayed stale long after the 60s window cycled, so the banner contradicted the per-model HEALTHY 100%-success status. Now: if credits_reset_at has elapseβ¦119579e -
fix(voice): KI-113 + KI-114 + KI-115 β reject background noise, distant speech, mid-thought pausesβ
User reported Live mode triggering on background noise + cutting off mid-thought when pausing to think. Tightened all four VAD knobs: KI-113 (background noise rejection): - rmsThreshold 18 β 26 (~44% higher floor) - speechStartFrames 3 β 5 (~80ms sustained, no single-spike opens) - voiceBandMinProp 0.35 β 0.50 (FFT energy must be clearly voiced; HVAC/traffic scores 0.20-0.30, speech scores 0.40-0.70) KI-114 (proximity gate / distant speech rejection): - adaptive multiplier 2.0+4 β 2.5+6 - Distant speech rides just above ambient (high frequencies attenuate with distance). Close-in speech is 10-20Γ ambient so it still clears the wider gap; distant conversation gets rejected. KI-115 (pause tolerance / don't submit mid-thought): - silenceEndFrames 120 β 180 (~2s β ~3s) - Tradeoff: +1s tail latency before bot responds. Accepted to kill the "submit when I pause to think" UX bug. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>cdf5ea5 -
fix(indic): KI-110 β repair Hindi pipeline raising on every turnβ
Live re-smoke verification (2026-05-15) caught every Hindi/Devanagari turn in Scenario S2 surfacing `brain_used=error_fallback` from KI-106's catch-all exception handler. Root cause: post-KI-099 the translator's try/except only catches `asyncio.TimeoutError` β but the KI-099 split httpx.Timeout(connect=2, read=20, write=2, pool=2) means httpx can raise other exception types that are NOT subclasses of asyncio.TimeoutError: - httpx.ReadTimeout (inner 20s read budget; races the outer wait_for(20s)) - httpx.ConnectError / ConnectTimeout (network / DNS / TLS failures) - httpx.HTTPStatusError (Sarvam 429 rate-limit on Indic-heavy load, or 5xx server hiccups, surfaced by resp.raise_for_status()) - KeyError ("choices") on malformed Sarvam payload - ValueError on malformed JSON / dataclass construction Any of these would propagate up through translate_to_english / translate_to_indic. While orchestrator's wrapping `except Exception` catches the inbound call, translation_check.cheβ¦64f55e3 -
fix(safety+closer): KI-108 + KI-109 β apply CoT strip to all reply paths + broaden closer regexβ
KI-108 β chain-of-thought leakage on fact-find replies. Live re-smoke (Scenario S4 T3+T4) caught raw model reasoning leaking into reply_text on the fact-find brain path: "We need to respond naturally..." "We need to process user message..." KI-104 had wired strip_cot_preamble into tts_preprocess (audio path) and persona.strip_think_tags (qa/recommendation paths) but the fact_find brain branch returned outcome.reply_text directly to ChatResponse without any strip. Two additional verbs ('process', 'parse', 'figure out', ...) also fell outside strip_cot_preamble's whitelist. Fixes: 1. orchestrator: call strip_think_tags() on every user-facing reply path: - fact_find brain TurnResult construction (was raw) - after Sarvam indic translation (Hindi/Hinglish CoT preamble too) - defensive final strip on QA/recommendation TurnResult boundary 2. persona.strip_think_tags: add a local pre-pass that strips a single leading "We (need to|must|should) <any-verb> ..." sentenβ¦21ffc50 -
fix(rag): KI-111 β wrap collection.query() to survive corrupted Chroma indexβ
User screenshot showed 'Hmm, something went wrong on my end' on every English chat turn. Local repro of 'Can you help me purchase or find a health insurance policy?' confirmed rag/retrieve.py:267 raises ChromaDB InternalError 'Error executing plan: Internal error: Error finding id' β HNSW index entry pointing to a missing doc, likely from a partial KI-102 profile-chunk write that corrupted collection state. KI-107 wrapped only collection.get(); query() had the same failure mode. Wrap it too β on exception log WARNING + degrade to empty retrieval so the brain still answers (acknowledging no catalog access) instead of every turn returning KI-106's generic exception fallback. Underlying corruption (the index repair / re-ingest) tracked separately. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>7d5e189 -
docs: KI-101..KI-107 β audit + CLAUDE.md + ADR syncβ
Document the seven KIs landed today across the production-readiness register, project memory, and affected ADRs: - KI-101 (66eb4ed) β drop 6 function-local `import logging` lines from orchestrator.py; module-level import is the sole binding so the asyncio wait_for TimeoutError branch no longer raises UnboundLocalError. - KI-102 (4bb8da0) β profile RAG cross-session isolation. session_id stamped on every chunk; main retrieve() excludes doc_type=profile; per-session lookup triple-checks meta.session_id == session_id in Python; legacy chunks without session_id fail-closed. ADR-022 extended with a session-isolation subsection. - KI-103 (8ef5c43) β _canonical_fallback no_trailer loop-breaker. New session._ff_failed_attempts + _ff_skipped_slots; after 2 failed attempts on the same slot, mark skipped and advance. - KI-104 (407f2a1) β voice_format.tts_preprocess strips chain-of-thought leakage: <think> blocks, **Reasoning:** labels, [INTERNAL] blocks, sentence-anchored CoTβ¦1d10432 -
feat(closer): KI-105 β wire ranked recommendation handoff on closer intentβ
Root cause (live 15-persona smoke test): when fact-find was complete and the user asked for a recommendation ("show me policies", "what would you recommend", "compare top 3"), the bot didn't produce a ranked shortlist. It either re-asked a filled slot, refused with "I'd rather not speculate", or leaked CoT β even though middle-conversation turns had already surfaced 15+ named policies. Two intertwined bugs: HYPOTHESIS A (PRIMARY): classify_intent misrouted closer phrases. - "show me the top 3 policies", "show me policies", "give me the top 3", "rank the best", "pitch me the top 3", "your top picks" β qa - "what would you recommend" β fact_find (matched FACT_FIND_TRIGGERS entry "what do you recommend" first) Because intent never landed on recommendation/comparison, pick_brain routed to the fast brain (DeepSeek-V4-Flash) with the default advisor prompt β designed for short conservative single-clause answers, not for multi-policy synthesis. HYPOTβ¦8a58fa1 -
fix(rag): KI-107 β graceful handling of Chroma get(ids=...) for missing idsβ
C5 port-in persona saw 3Γ HTTP 500 'Error executing plan: Internal error: Error finding id'. After KI-102 added per-session profile-chunk lookup, the collection.get(ids=[f"profile_{sid}"]) call could raise on certain Chroma sqlite states (transient HNSW compaction locks, legacy rows). The pre-fix bare `except: pass` masked the failure into the orchestrator's plan executor, surfacing as the cryptic 500. Fix: - New rag/retrieve.py::_safe_collection_get(collection, ids, where, include) wrapper. Returns None on exception (with WARNING log so the failure is observable in HF Space logs), returns raw dict on success. - Profile-boost block in retrieve() routes through the helper; caller treats None as miss and falls through to normal cosine results. - backend/profile_rag.py::upsert_profile_chunk() wraps coll.add() in try/except + WARNING log so profile-write failures no longer crash the chat reply (next profile change retries). Regression tests in tests/test_profile_rag_isolation.pβ¦3a9a14f -
fix(safety): KI-106 β graceful timeout/exception handling on /api/chatβ
C4 NRI persona saw 5x HTTP 500 with 'Orchestrator failed: TimeoutError'. The inner asyncio.wait_for handlers caught their local timeouts but the outer non-fact-find brain call let TimeoutError propagate. FastAPI then converted it to 500. Wrap handle_turn() in try/except for TimeoutError + Exception in /api/chat. Return 200 with a graceful 'try again' message instead of surfacing 500 to the user. Also add an outer asyncio.wait_for(45s) total-budget guard so pathological hangs return a graceful reply, not a connection-reset. Regression test in tests/test_routing_regression.py monkeypatches handle_turn to raise asyncio.TimeoutError and RuntimeError; asserts 200 + graceful reply phrasing both times. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>565bf31 -
fix(safety): KI-104 β strip chain-of-thought / instruction-echo leakage from repliesβ
Live smoke test caught NIM reasoning models (Qwen3-Next 80B) and the faithfulness judge leaking internal reasoning into user-visible reply_text. Examples seen verbatim in production: - "We need to respond to user question..." - "We must ground every factual claim..." - "We need to follow instructions. The user asks... According to conversation rules..." The existing persona.strip_think_tags only handled balanced <think>...</think> tags. Bare instruction-echo and stray scratchpad labels (**Reasoning:**, [INTERNAL]) slipped past every gate. Adds backend/voice_format.strip_cot_preamble β a conservative sentence-level stripper that: 1. Removes labelled reasoning lines (**Reasoning:**, **Thought:**, **Plan:**, [INTERNAL]...[/INTERNAL]) β same-line only, never consumes the next line (which is typically the answer). 2. Drops everything before a stray </think> tag (defense-in-depth for unbalanced cases that strip_think_tags lets through). 3. Sentence-walks thβ¦407f2a1 -
fix(fact-find): KI-103 β break no_trailer fallback loop after 2 failed attemptsβ
Live 15-persona smoke test on 2026-05-15 caught the brain repeating the same slot question 4-8 times in a row even after the user explicitly answered: A3 (Priya): age 42 stated T2, bot asked "First, your age?" 7 times A5 (Sanjay): employer-cover answered T4, bot asked same Q 4 times B3 (Mehul): age 45 stated T2, bot asked age 8 times despite the answer Root cause: when the LLM brain returns a reply WITHOUT the <FF>{...}</FF> trailer (KI-090 lenient parser still fails), _canonical_fallback runs. Its greedy multi-slot capture only appends to profile.asked when a value is successfully captured. When greedy fails to match anything in the user_text, profile.asked stays unchanged and next_question(profile) returns the SAME slot every turn β infinite re-ask loop. Fix β per-session canonical-fallback failure counters with loop breaker: β’ _ff_failed_attempts (dict[slot_id, int]) on the session counts consecutive surfaces of an unfilled slot via canonical fallback without a caβ¦8ef5c43 -
fix(privacy): KI-102 β scope profile-RAG retrieval to session_id onlyβ
P0 privacy leak caught by live 15-persona smoke test (2026-05-15): user B4 (session smokeB_B4_<ts>) retrieved profile chunks from sessions smokeA_1, ki100_ve, and smokeB_B2, and the LLM cited them as B4's "User profile" β leaking three other users' age / health-conditions / dependents into B4's reply. Root cause was a two-layer miss: 1. backend/profile_rag.py::upsert_profile_chunk wrote chunks with metadata {policy_id, doc_type='profile'} but NO session_id field, so any future where={"session_id": X} filter would be a no-op. 2. rag/retrieve.py::retrieve()'s main cosine pass at line 196-209 built where={} when no policy_ids / insurer_slugs were passed, then ran collection.query(..., where=None). With no doc_type filter, ALL profile chunks (every session's) were eligible for cosine match. Profile-shaped queries ("plan for my age", "my dependents") put foreign profile chunks in the top-k. The explicit per-session collection.get(ids=[f"profileβ¦4bb8da0 -
fix(orchestrator): KI-101 β drop function-local 'import logging' to fix UnboundLocalErrorβ
KI-099a added module-level `import logging`, but several legacy function- local `import logging` lines (from KI-005/006/091 handlers) caused Python to treat 'logging' as a local in handle_turn. When the wait_for TimeoutError branch fired BEFORE the function-local import statement, 'logging' was unbound and the orchestrator raised HTTP 500. Caught live by the 15-persona smoke test (B5 T8 'Mild asthma, controlled'). Delete every function-local import; rely on the single module-level one. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>66eb4ed -
fix(latency): KI-100 β outer wait_for(25s) around drive_fact_findβ
Live smoke-test post-KI-099 caught T6 at 41.83s with brain_tag `fact_find_brain::fallback:timeout_after_escalation`. The fact-find brain at orchestrator.py:401 was outside KI-099's scope (which targeted lines 549 / 639 / 684). Its internal KI-079 escalation (FAST 25s + BRAIN 15s) sequentially compounded to 40s on doubly-saturated chains. Wrap drive_fact_find in asyncio.wait_for(timeout=25.0). On outer timeout, fall through to _canonical_fallback with reason="outer_timeout_25s" so the user still gets a coherent next-question prompt while the chain recovers. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>55c83b9 -
fix(latency): KI-099 β bound every per-turn LLM callβ
KI-098 audit surfaced 5 holes where a per-turn LLM call could hang the user-facing chat for 60-120s. This commit installs explicit budgets: backend/orchestrator.py: - extract_profile_updates β asyncio.wait_for(12s) + TimeoutError handler - main brain pick.provider.chat β asyncio.wait_for(30s) - faithfulness cross-check retry β asyncio.wait_for(20s) + skip-retry on timeout (rare-path fallback; safer to skip than hang) backend/providers/sarvam_llm.py: - Monolithic timeout=60.0 β httpx.Timeout(connect=2, read=20, write=2, pool=2) mirroring KI-084 on NIM. Constructor kept backward compatible. backend/translator.py: - asyncio.wait_for(20s) around both Sarvam .chat() calls. On timeout, passthrough original text (callers already tolerate via KI-004). Third callsite (back-translate) routes through translate_to_english so it inherits the wrap. backend/providers/nvidia_nim_llm.py: - Budget guard before the synchronous probe_all() refresh inside chat(). If β¦0e3c560 -
fix(admin): KI-096 + KI-097 β public /api/version + password-only adminβ
KI-096: add unauthenticated GET /api/version (git SHA + uptime). Lets any caller verify which commit HF Space is serving without admin auth. KI-097: rip out admin IP allowlist. ADMIN_IP_ALLOWLIST env, _ip_allowed(), and the dual-gate 404-to-hide-existence behavior are gone. _check_admin now only verifies the X-Admin-Password header; bad/missing password β 401 Unauthorized. Operational rationale: changing networks locked the operator out without adding meaningful security beyond a strong password. ADR-023 superseded; ADR-010 secret count 8 β 7. Also includes test_name_persistence.py (4 deterministic regression cases pinning KI-091/094/095) and the KI-094 mistakes-log entry. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>d37a6cf -
fix(safety): KI-095 β 5 defensive guards against profile-field clearingβ
Closes audit holes found post-KI-094: 1. main.py /api/profile β reject empty-string / empty-list overwrites 2. needs_finder.py record_answer β defer asked.append until setattr succeeds 3. fact_find_brain.py greedy fallback β comment direct-setattr scope reason 4. session_state.py disk rehydrate β log dropped schema-drift keys 5. main.py /reset β require explicit confirm=true to wipe session Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>afe6172 -
docs: KI-091 + KI-094 β extractor gates + None-guard added to audit + CLAUDE + ADR-032β
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>d547d5a -
fix(orchestrator): KI-094 β extractor cannot clear a filled profile fieldβ
LLM profile_extractor periodically returned {"name": null, "age": null, ...} for turns where the user didn't restate fields. The orchestrator was passing those nulls through to session.update_profile_field, OVERWRITING captured values mid-session. next_question(profile) then returned the cleared slot and the bot re-asked it, breaking fact-find progression. KI-091 already skips the extractor on fact-find turns; KI-094 closes the same hole for QA-mode turns where the extractor still runs. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>f068094 -
fix(fact-find): KI-092 β lenient name parser when slot explicitly awaiting nameβ
User screenshot: bot asked "First β what should I call you?", user replied "rohit sar" (plain lowercase name, no intro phrase). Bot RE-ASKED the same question because `_normalize_for_slot("name", "rohit sar")` returned None β KI-074's strict regex required an explicit intro phrase ("I'm X" / "my name is X" / "this is X") which a direct reply doesn't have. Root cause: KI-074 conflated TWO different name-extraction modes: Mode A (lenient) β bot explicitly asked for name; the reply IS the name by construction. Should accept any plain alphabetic input. Mode B (strict) β greedy multi-slot capture; the user's message could be about anything. Need intro phrase to avoid false positives like "this is correct" (KI-069) or "29 years old". Fix: split into two paths via a synthetic slot_id="name__awaiting" tag. `_canonical_fallback` checks `session.awaiting_question_id == "name"` and calls the lenient path first. Greedy multi-slot capture continues to use the strict path. Both paths sβ¦531dfbd -
fix(orchestrator): KI-091 β skip profile_extractor + faithfulness judge on fact-find turns (drop dependent LLM calls on saturated chains)β
Live admin /api/admin/llm-health showed BRAIN_CHAIN + JUDGE_CHAIN credit_exhausted=TRUE while FAST_BRAIN_CHAIN credit_exhausted=FALSE. The fact_find_brain runs on FAST_BRAIN_CHAIN and was succeeding, but the orchestrator's same-turn profile_extractor (BRAIN_CHAIN) and faithfulness judge (JUDGE_CHAIN) calls were hanging on the saturated chains β profile_extractor telemetry showed 10822ms / 15728ms / 16139ms / 20393ms on consecutive turns; a single judge call ran for 733760ms (12 minutes!) before completing. Turn-1 in the user screenshot succeeded because both dependent calls happened to come in under budget; turns 2-3 fell back to the canonical GRAPH[k] prompt because the 25s outer wait_for tripped on the dependent calls β fact_find_brain itself was never the killer. Two gates added in backend/orchestrator.py: Gate 1 β extract_profile_updates: _in_fact_find_now = bool(in_fact_find_continuation) or intent == "fact_find" _run_extractor = ( not _skip_extract anβ¦9813994 -
docs: backend/README β fix stale ADR-027 link on needs_finder + add fact_find_brain row + mark paraphraser deletedβ
Final completeness sweep caught backend/README.md still pointing the `needs_finder.py` row at ADR-027 (the paraphraser ADR) and listing the now-deleted `question_paraphraser.py` as if it's a live module. Fixes: - `needs_finder.py` row reframed as "safeguard fallback only" post- KI-070; link routed to ADR-030 (the current fact-find architecture). - New `fact_find_brain.py` row added between needs_finder and fact_find_normalizer β calls out KI-070's single-LLM-call driver and KI-090's lenient tail parser. Links ADR-030 + ADR-032. - `question_paraphraser.py` row struck through and labelled "deleted in KI-070"; kept in the table so future contributors searching for the historical module name find the supersession note. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>f287dc6