Spaces:
Sleeping
Sleeping
Commit History
-
test(#44): add SSOT regression test for canonical_decision_factsβ
The fix for Bug #44 landed in commit 2c51f98 (scorecard path and get_policy_facts path resolve different values for the same policy's decision-critical fields β live audit: ICICI Health AdvantEdge PED showed 24mo in the comparison table and 0mo in the #31 scorecard card). The fix introduced brain_tools.canonical_decision_facts and wired it into key_coverage_facts as the single canonical resolver. This test (written 2026-05-19) is the CI guard for that contract. It was sitting untracked in the working tree for 9 days. Without it, any future regression of the SSOT invariant β e.g. someone adds a field to brain_tools._FACT_KEYS without also threading it through canonical_decision_facts, or _load_curated_facts changes its precedence β would ship to the live Space silently. What the test asserts: - For every id in the full catalogue (every marketplace card + every key in _load_curated_facts), every decision-critical field where get_policy_facts surfaces a value MUST equal the scβ¦1cc997b
-
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
-
#41 + #43: fix family-history re-ask + unverifiable-UIN warningβ
#41 β the post-recap pricing bundle re-asked family medical history even after the user answered "no family history". Root cause: an explicit negative coerces to [] and save_profile_field dropped it as "normalized_empty", so the slot stayed unset and _unresolved_pricing_bundle re-asked it. Fix: save_profile_field records an explicit-none family-history answer on profile.asked (value stays []); the bundle gate now treats an answered (asked) slot as resolved even when its value is empty. #43 β a comparison reply citing a genuine catalogue UIN not echoed in this turn's retrieved chunks was wrongly flagged "could not be verified against our records". _verify_prose_grounding now treats a real catalogue UIN (from _catalogue_uin_index) as verified-by-definition; only a truly fabricated UIN is still flagged. #42 needs no code β boot warmup() + 503-retry already exist and are wired; the residual cold-start is transient infra. Regression tests tests/test_bug4143_fixes.py; full suite green. Cβ¦ba47227 -
#47: UIN-based net-new dedup for user-uploaded policy PDFsβ
When a user uploads a policy PDF whose IRDAI UIN already belongs to a catalogue policy, it is NOT net-new β the route now short-circuits and returns the existing card (UploadResponse.already_in_catalogue=True + existing_policy_id/name) instead of indexing a duplicate. Adds _catalogue_uin_index() (cached, modern-format UINs only) and _match_catalogue_uin() (case-insensitive extraction). Hash-dedup (Gate 8) still handles identical re-uploads; this adds same-policy-different-PDF. Other gaps from the #47 spec were already covered by the existing #52 work (persisted JSON, global graded marketplace card, dynamic insurer logo) β not rebuilt; durable cross-restart persistence intentionally left session-scoped (HF FS is ephemeral; durability would leak unvetted uploads into the shared catalogue). Also fixes a pre-existing test-hygiene leak: the #45 auto-persist wrote the recall test's throwaway name to disk; fixture teardown now cleans it. Regression test tests/test_upload_uin_dedup.py; fullβ¦1a7161d
-
#44: reconcile PED waiting across policy-facts doctype files (data integrity)β
14 policies had conflicting pre_existing_disease_waiting_months across base/__wordings/__cis/__brochure files, causing the scorecard surface and get_policy_facts to contradict each other in one reply (e.g. ICICI Health AdvantEdge card said "0 months β short waiting" while the table said 24mo; the bogus 0 also inflated its grade). Each set to the source-faithful canonical value (wordings/Code-Excl01 legal clause preferred; garbled OCR resolved to the real number in the quote; no invented numbers β every value keeps its real supporting quote). Guard test tests/test_policy_facts_ped_consistency.py pins "no policy's doctype files disagree on PED" (redβgreen verified). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>2c51f98 -
#45: persist chat-only profiles so returning-user recall actually worksβ
Real cause of the recurring "returning user not recognised": the #25 recall LOOKUP fix was correct but its verification used a pre-existing rohit.json, masking that the WRITE side never ran. profile_persistence. auto_persist_session() (saves named profile to disk + Chroma) was ORPHANED by the orchestratorβsingle-LLM rewrite β single_brain.handle_turn never called it; save_profile() only ran from POST /api/profile (builder UI). So a user who completed fact-find purely by chat was never saved and recall had nothing to find (live audit: brand-new "Auditkumar Verma" β fresh same-name session β NO recall; no auditkumar*.json written). Fix: handle_turn now awaits auto_persist_session(session) at end-of-turn (after all save_profile_field + recall handling). No-ops without profile.name; swallows all errors so persistence can never block a reply. Regression tests (red-green verified): chat turn persists <name>.json; anonymous turn does not; persist-then-fresh-session β recall fires (the real β¦a025a43 -
#25/#26: returning-user recall any-turn + mid-conversation state recoveryβ
#25 β returning user never recognised. Recall probe was gated to _current_turn==1, but fact-find asks the name in the bot's FIRST reply so the name lands on turn >=2; compounded by extract_potential_name needing an "I'm X" preamble and a two-token name slugging past the stored first-name file. Fix: probe whenever the LLM-captured session.profile.name is first known (any turn) + first-name slug fallback in rehydrate_by_name; one-shot guarded (recall_probe_done), declined recall never re-offered. Privacy design (stage + explicit confirm, no auto-merge) preserved. #26 β profile lost mid-conversation. In-memory sessions (1h TTL, KI-118 removed disk persistence) evict on HF container restart/idle -> get_session returns blank -> bot says "I seem to have lost ... What's your name?". Fix (chosen design): when the live profile is blank but the client still carries chat_history, inject STATE-RECOVERY MODE so the model silently re-captures facts from history and continues β never re-asking the nβ¦2368504 -
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(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(brain): don't re-ask recalled slots after returning-user confirmβ
Live audit of the recall fix surfaced a real secondary bug: after the user confirms 'yes' to 'are you the same <name>?', apply_pending_recall correctly merged the stored profile (returning_user_recalled=True; a recall probe proved income/city were present) β but the model still RE-ASKED income band + pre-existing conditions, defeating 'pick up where we left off'. The generic 'do not re-ask' snapshot was too weak on the confirm turn. Fix: _system_instruction now takes recall_applied (= _did_recall_this_turn) and, on the apply turn, injects a high-priority 'RETURNING USER CONFIRMED β PROFILE RESTORED' block listing the restored slots and forbidding any re-ask/re-confirm of them ('Re-asking a RESTORED slot is a hard error'), instructing a one-line welcome-back then resume at RULE 2.5 pricing / recommendation. Verified locally with a PRECISE interrogative-only detector (not the naive substring checks that produced false alarms): turn-2 recaps the full restored profile and asks only the oβ¦6e0462a -
fix(brain): wire returning-user-by-name recall into single_brain (ADR-041/KI-196)β
Root cause: the confirmation-gated profile recall was ORPHANED by the orchestrator->single-LLM rewrite. extract_potential_name / try_recall_by_name / apply_pending_recall existed and were unit-tested, but NOTHING on the live path (single_brain.handle_turn) called them, and TurnResult.returning_user_recalled was hard-coded False. A same-name revisit ('Hi, I'm Rohit') therefore never triggered 'are you the same Rohit?' and never reused the stored profile. Fix (single_brain.py, fits current architecture; no orchestrator revival): - turn-1: extract_potential_name -> try_recall_by_name STAGES the match on session.pending_profile_recall (privacy-safe; never auto-merged). - _system_instruction injects a RETURNING-USER CHECK block so the LLM's entire turn is just the 'Welcome back - are you the same <name>?' confirm (no tools / no fact-find that turn). - next turn: _affirm_or_deny (new, conservative WORD-BOUNDARY yes/no; deny wins ties = privacy fail-closed) -> explicit yes calls apβ¦3591985 -
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 -
feat(#77 / #52-residual-5): admin prune for persisted uploaded docsβ
Persisted uploaded marketplace docs have NO TTL by design (public catalogue cards). Added the sanctioned operator removal path: - backend/uploaded_docs.prune_persisted_upload(policy_id | prefix=...) β HARD path-safety guard: only ever rmtrees a DIRECT child of UPLOADED_DOCS_DIR (can never touch rag/corpus, 40-data, curated/ extracted); traversal attempt is skipped (resolves inside root) / empty prefix RAISES (no silent no-op). - POST /api/admin/uploaded-docs/prune (password-gated, reuses _check_admin): prunes dir(s) + deletes the doc's chunks from the GLOBAL policies Chroma collection + busts _MG_CACHE/_CORPUS_PDF_IDX so /api/policies/all drops the card immediately; collects (never swallows) Chroma errors. - tests/test_uploaded_docs_prune.py β exact+prefix removal, non-matching docs preserved, traversal-safe, empty-prefix rejected (3/3). Needed because my own live #52 verification created disposable 'Zzz E2E Verify' (user-upload__e2e-verify-*) cards on prod; this is hoβ¦e6eb838 -
Revert "Revert "feat(#52): PDF upload β persistent JSON + marketplace card + restart-survival""β
This reverts commit a6bda5e29589a6a1990c025a892d761b0cb40709.afdb7c7 -
Revert "feat(#52): PDF upload β persistent JSON + marketplace card + restart-survival"β
This reverts commit 60f835880951c32c879f7068c912658980e2dae4.a6bda5e -
feat(#52): PDF upload β persistent JSON + marketplace card + restart-survivalβ
Full end-to-end uploaded-PDF ingestion (graded server-assignment feature): - backend/uploaded_docs.py (new): deterministic source-quoted field extractor (no fabrication β only evidenced cells), crash-atomic persistent store (source.pdf + record.json curated-facts schema + chunks.json + meta.json) under settings.UPLOADED_DOCS_DIR; load + startup re-ingest helpers. Raises on any failure (no silent failure). - config.py: UPLOADED_DOCS_DIR (/data/uploaded_docs on HF β the PERSISTENT disk; rag/vectors stays ephemeral per KI-119; 40-data locally). entrypoint.sh exports + mkdir in the writable-/data block. - main.py: upload_policy persists + adds chunks to the GLOBAL policies collection + busts _MG_CACHE/_CORPUS_PDF_IDX (HTTP 500 on failure); _load_curated_facts merges persisted records so they flow through the EXISTING _marketplace_catalogue Pass-2 + build_scorecard (zero grading re-impl β #40 SSOT preserved, parity test 0 mismatches); _mg_data_ signature walks uploadedβ¦60f8358 -
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(#60+#62): bulk-scorecard curated fallback + stop internal scoring jargon leakingβ
#60 REGRESSION: /api/scorecard/bulk hard-required rag/extracted/<pid>.json and emitted the N/A 'No extraction available' / 'Data not indexed' sentinel for curated-only catalogued products (star-health__star- comprehensive, UIN SHAHLIP26044V092526) β the broken-card defect the user re-reported. Mirrored the curated fallback the marketplace + single /api/scorecard endpoint already use (policies_all Pass-2). Star Comprehensive now grades A 76 instead of N/A. #62: scorecard.py hardcoded the user-facing signal as 'lifelong renewable (IRDAI norm β not scored)' β internal scoring scaffolding leaking into the card UI. Now 'Lifelong renewability guaranteed'. Test updated to assert clean copy + no jargon leak. Full pytest gate green (rc=0). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>208c839
-
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 -
fix(scorecard): rec-path scorecard == marketplace (KI-FULLFACTS) β restores recommendation cardsβ
ROOT CAUSE of empty CitedPolicyCards: brain_tools._scorecard_signal fed build_scorecard the 7-key eligibility subset (_load_policy_facts), which is below build_scorecard's data-completeness floor β every recommended policy returned grade "β" / overall 0 β the Bug #71 >=70 fitness gate dropped 100% of them β recommendation citations always empty β no cards. The marketplace (/api/policies/all) scored the SAME policies correctly (HDFC ERGO Optima Restore = A/78) because it feeds the FULL curated layer (main._load_curated_facts, KI-219/251 canonical precedence). Fix: _scorecard_signal now reuses main._load_curated_facts (lazy import β main is loaded at request time; dodges the cycle) + the same 40-data/reviews/<slug>.json insurer reviews + profile that the marketplace passes to build_scorecard. A policy's recommendation grade is now identical to its marketplace grade by construction. The 7-key _load_policy_facts is unchanged β it remains the correct input for the eligibility/dedup gate, Nβ¦4a63fa6 -
fix(single_brain): restore broken core flow β model revert + thinkingConfig + rip deterministic scaffoldingβ
Root causes of the live "new user never gets a recommendation" regression: - KI-183 (132a829) silently set the brain to the weak gemini-2.5-flash-lite while migrating off retired gemini-2.0-flash. Reverted DEFAULT_MODEL + _FALLBACK_MODEL to gemini-2.5-flash. - gemini-2.5-flash is a THINKING model; with no thinkingConfig it returns EMPTY completions (zero output tokens, no parts) β proven via raw A/B payload test. Added generationConfig.thinkingConfig.thinkingBudget=0. - b87bd2d's RULE-0 "ASK FOR THE NAME FIRST" overlay contradicted RULE 1 ("save the name the user gave"); removed (restores pre-b87bd2d prompt). - Ripped out leftover pre-Path-B deterministic fact-find scaffolding (the old rule/3-brain/judge defect): _synthesise_fallback + _FALLBACK_SLOT_QUESTIONS (the canned "What's your name?" mask) and the entire in-conversation recall-confirm/sniff (_classify_recall_answer, extract_name_in_context, _recall_sniff_done, STEP1/STEP2). Empty-LLM now surfaces an honest eβ¦5a4b5e8 -
feat(audit): selftest in pytest gate (static-scoped, no recursion) + opt-in git hooks + README
22a03fc
-
feat(audit): core contract + runner + CLI
a519e2c -
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
-
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 -
fix(voice+llm+admin): KI-200/201/202/203/204/205/206/207/208/210/211 bundleβ
THE LAST OPERATIONAL FIX BUNDLE β voice + recommendation routing + LLM election + admin clarity. Docs cascade held for post-test confirmation. KI-200 β Admin LLM Chain redesigned to 2 clean tables. Table 1 "Currently In Use" (per use case + provider + tier). Table 2 "All Eligible Models" with explicit Primary / 1st backup / Last resort labels. Provider column color-coded (Google blue / NVIDIA green / OpenRouter orange). KI-201 β Election by chain order (not latency score). backend/llm_health.py get_primary + get_backup now walk the chain definition in priority order. Returns first eligible model. nemotron only serves as last resort. Resolves "maverick elected over qwen when all healthy" bug. KI-202 β Utterance batching with 1.5s grace. Mid-sentence pauses < 1.5s accumulate into one submission. pendingUtteranceRef + pendingChunksRef + grace timer per onend. KI-203 β Block recognition transcripts during TTS. dropResultsRef gates onresult while audio plays + 300mβ¦e9cfc9f -
refactor(brain): KI-167 β rip out fact_find_brain, replace with sales_brainβ
Replaces scripted slot-walker (fact_find_brain + canonical_fallback + scripted Question.prompt_en + "Got that β" prefix + <FF> trailer) with a single LLM-driven sales agent using NIM response_format=json_object. WHY: 8 patches (KI-150/155/156/158/161) all worked around <FF> trailer fragility + canonical_fallback firing as the dominant path. Symptom: "zero natural LLM chat β always defaults to script." Architectural rot from reactive accretion. NEW: + backend/sales_brain.py β single LLM call, response_format=json_object, SalesBrainResult{reply_text, captured_updates, ready_for_recommendations, brain_used}. NO scripted fallback. Fail-loud on errors. + backend/sales_brain_normalizer.py β deterministic post-processor: cityβtier, "5 lakhs"β"5L-10L", bad-name rejection, schema validation. DELETED: - backend/fact_find_brain.py (986 lines) - backend/fact_find_normalizer.py (452 lines β cherry-picked into normalizer) - tests/test_fact_find_loop_break.py (architeβ¦f7df227 -
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
-
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+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(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 -
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(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 -
test(llm-chain): KI-089 β update credits-election test for KI-087 NIM-first preferenceβ
The pre-KI-087 `test_groq_above_water_picked_in_election` asserted that Groq wins election when both candidates are healthy and Groq has more credits + faster latency. KI-087 (`d90f8c0`) inverted this: NIM is always preferred when eligible, regardless of latency. The test has been failing on main since KI-087 landed. Replaced with two paired tests that lock in both halves of the new contract: 1. `test_nim_preferred_over_faster_groq_when_eligible` β asserts NIM is elected as PRIMARY even when Groq is 3x faster AND has credits. The strategic point: NIM is the free, $0, no-daily-cap provider; Groq + OpenRouter are emergency fallback only. 2. `test_groq_picked_when_nim_pool_empty` β fallthrough invariant. When NO eligible NIM candidate exists (chain has only non-NIM models, or all NIM models down/quota-exhausted), election picks the highest-scored non-NIM candidate as PRIMARY. Locks in the safety net so a full NIM regional outage still produces a working brain caβ¦8a87526 -
feat(llm-chain): KI-085 β proactive credit tracking; election gates by quota not just livenessβ
WHY: KI-084 (commit 119e0fd) demotes a candidate for 1h AFTER the first HTTP 429 β that's REACTIVE. Cost: one user-facing failure per dead quota before the elector knows to skip it. KI-085 is PROACTIVE: every probe + every real call updates our view of remaining quota from response headers + provider endpoints; election filters by `is_alive AND has_credits` BEFORE suggesting a primary, so a quota-exhausted Groq is sidelined the moment headers say `remaining_tokens_day < 5000`, not after a 429 hits. SIGNAL SOURCES (priority order): 1) GROQ β response headers on every successful call. Parse `x-ratelimit-remaining-tokens-day` (the one that bit us today; free-tier daily TPD cap) + `x-ratelimit-reset-tokens-day` (duration string `"1h2m"` / bare seconds / unix epoch β all three shapes handled). Low-water 5000 tokens (β₯ one fact-find ~2K-input + ~400- output round-trip with margin). 2) OPENROUTER β dedicated GET /api/v1/credits endpoint, polled every ~10 minβ¦8fc7979 -
docs: KI-080 β sync CLAUDE.md + ENTERPRISE_AUDIT + new ADR-031 + 11 stale KI-025/50-50 surface sweepβ
Documents the KI-080 architectural shift from "iterate every chain candidate per call" (ADR-026 / KI-025 50/50 NIM β Groq rotation) to "probe-elected sticky primary with cross-provider backup" (ADR-031). Files updated: - CLAUDE.md β "LLM stack" section rewritten for KI-080 election; KI-025 rotation marked deprecated. - 80-audit/ENTERPRISE_AUDIT.md β KI-078/KI-079/KI-080 rows added to "Fixes shipped today" table; executive-scorecard UX-latency + test- coverage rows updated to cite KI-080 (supersedes KI-025). - 70-docs/60-decisions/ADR-031-sticky-primary-election.md β NEW. Full ADR following ADR-030 shape: Context, Decision, Alternatives, Consequences, Files touched, Revisit at scale. - 70-docs/60-decisions/ADR-026-provider-load-balancing.md β header updated to "Superseded by ADR-031"; body retained as historical record per ADR convention. - 70-docs/60-decisions/ADR-030-llm-driven-fact-find.md β pointer to ADR-026 swapped for ADR-031. - READMEβ¦c592055 -
refactor: KI-047 β bucket reorg (Option A safe subset)β
User picked numbered-bucket layout. Executing the SAFE subset that does NOT touch Python imports or string path refs: β’ docs/ β 70-docs/ β’ audit_results/ β 80-audit/ Kept as-is (renaming would need ~25 Python files of string-path updates β deferred to follow-up): β’ data/ β code-referenced (backend/{premium_calculator, session_state, profile_store, scorecard, admin, llm_health, main}, rag/build_kb, tools/{check_link_rot, info_source_map, curate_*, refresh_premiums, generate_policy_facts}). β’ backend/, frontend/, rag/, tools/, eval/, tests/, kb/ β Python directly forbids leading-digit / hyphen package names. All references to the moved folders updated in one sed pass across *.md, *.py, *.sh, *.ts, *.tsx, *.json, Dockerfile. Verified by: β’ tests/test_routing_regression.py β 15/15 still pass. β’ No residual (docs/ or [docs/ or /docs/ or ^docs/ refs. β’ Same for audit_results/. Docβ¦e2d09f9 -
feat: KI-044 PCM pre-roll via AudioWorklet + 11 folder READMEsβ
KI-044 β Proper first-word capture in Live mode. Previous MediaRecorder approach started recording only AFTER VAD declared speech-start, missing the first 50-100 ms of the opening word. User report: "ensure that the first word uttered is also captured, especially in live." New approach (frontend/src/lib/useLiveConversation.ts): β’ Inline AudioWorkletProcessor (Blob-URL registered, no static asset routing) taps the raw PCM from the mic source. Every render quantum (128 samples) is posted to the main thread as Float32. β’ Main thread maintains a circular preroll buffer (~300 ms at the AudioContext sample rate) while no utterance is in progress. β’ When VAD fires speech-start: snapshot the preroll into the active utterance buffer; continue accumulating subsequent samples. β’ When VAD fires silence-end: encode utterance as 16-bit PCM WAV (Sarvam Saarika native format) and post to onUtterance. β’ Worklet stays running via source β workletNode β silentSink (zeroβ¦86fcc31