Spaces:
Sleeping
Sleeping
Commit History
-
docs: Cluster A (count drift) + Cluster B (deleted-module refs) sweep
Cluster A — Align pre-ADR-044 count snapshots with current 148/21 state: - CLAUDE.md L7: "19 insurers / 166 cards / 4-gate faithfulness" → "21 insurer slugs / 148 catalogued cards / structural grounding" - README.md L61: "~150 plans across 20 insurers" → "~148 plans across 21 insurers" - rag/README.md L30: "19 insurers" → "21 insurer slugs; dedup to 148 marketplace cards" - 70-docs/80-audit/reviews-source-map.md ×4: "20 insurers" → "21" - ADR-002 + ADR-009 + 60-decisions/README.md: kept historical scope numbers as ADR history-of-record; added forward-pointer footnotes to current 21/148 per ADR-044 Cluster B — Replace references to modules deleted in KI-225 single-brain consolidation: - kb/AUDIT_TRAIL.md: faithfulness.py / persona.py / fact_find_brain.py / sales_brain.py / qa_brain.py / translator.py / profile_extractor.py / orchestrator.py → single_brain.py - backend/providers/README.md L13: removed translator.py reference (sarvam_llm.py now used directly by …4c728a9 -
fix(upload-extract): status parity on LLM-fail path + docs updated
KI-333 — when all LLM passes (multi-pass + single-pass + NIM) fail and the card falls back to the heuristic floor, the status endpoint now reports the SAME completeness_pct + overall_grade the card endpoint serves. Previously status said comp=None/grade=None while the card showed C/65% — confusing parity gap caught live on Test Policy.pdf (8 MB). Fix runs the same `_catalogue_scorecard(pid, None)` → fallback `build_scorecard(record.json flat, insurer_reviews)` resolution the success path uses, but on the heuristic record (which exists because build_record() ran synchronously in the upload HTTP call). Flattens cell-shape {value, ...} dicts to scalars before scoring. Plus README §2.8 + §4.4 + CLAUDE.md updated with: - Heuristic floor expansion (KI-332): 32 patterns vs prior 16 - Multi-pass per-section extraction path - Updated resolution order (1 hash-cache → 2 multipass → 3 single → 4 NIM → 5 heuristic) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>2ec48b7 -
feat(upload): multi-pass per-section extraction + heuristic-floor expansion (KI-332)
Two coordinated changes to the upload extraction pipeline, addressing the 2026-05-27 user-caught regression on Test Policy.pdf (8MB) where single-pass Gemini truncated JSON on 3/3 retries. 1. MULTI-PASS PER-SECTION EXTRACTION (ADR-044 §D6) For PDFs ≥25K chars: split the HealthPolicy schema into 7 logical sections (identity, eligibility, financial, waiting_periods, coverage, limits, network_claims). Run each section as its own Gemini call in PARALLEL via asyncio.gather. Each call carries ~15% of the schema → fits comfortably in Gemini 2.5-flash's output budget even for 8 MB PDFs. Failure-isolated: partial section results merge into a partial HealthPolicy that's strictly better than the heuristic floor. Same wall-clock cost as single-pass (parallel). On total failure, falls through to legacy single-pass + NIM chain. New helpers: - _EXTRACT_SECTIONS: 7-entry schema partition (39 fields covered) - _schema_excerpt_for_fields(): filtered schema_excer…d92f07a -
feat(single_brain): wire view_context → ACTIVE POLICY DIVE-IN block (KI-330)
Root cause caught in 2026-05-27 multi-PDF e2e audit. On 3 of 5 uploads, asking "What are the waiting periods on this policy?" got back "Before I pull your recommendations, just a couple more (you can skip any):" — single_brain pivoted to profile-building / recommendation flow instead of answering about the just-uploaded policy. Triple root cause: 1. ChatRequest.view_context declared since launch but NEVER CONSUMED anywhere on the backend (truly dead code). 2. single_brain.handle_turn signature didn't accept it. 3. Frontend set view_context.active_policy_id only when a marketplace card was clicked (openPolicy modal); never on a just-uploaded PDF. Fix: - backend/single_brain.py: handle_turn(..., view_context=None); _system_instruction(..., view_context=None); new _build_active_policy_block() that appends an ACTIVE POLICY DIVE-IN block to the system instruction when view_context. active_policy_id is set. Block tells the model: answer the question vi…2a58c28 -
fix(upload-extract): hash-cache short-circuit now matches scorecard endpoint
The Tier-2 content-hash short-circuit had the SAME three bugs the main extraction path used to have: 1. Called build_scorecard(doc, profile=None) without insurer_reviews → completeness diverged from the card endpoint (17.4 vs 47.8/52.2) 2. Read `.overall_grade` off the Scorecard dataclass (attr is `.grade`) → grade always None on cache-hit 3. Never set llm_used → operator can't see WHY no LLM ran on cache-hit All three caused the multi-insurer audit to show status='complete' llm=None comp=17.4 grade=None for a card the user sees as 47.8% / grade C. Fix applies the same resolution as the main path: - Bust _MG_CACHE FIRST so _catalogue_scorecard rebuilds with new card - PRIMARY: _bm._catalogue_scorecard(pid, None) - FALLBACK: build_scorecard(doc, insurer_reviews=ir, profile=None) - Read sc.grade (not sc.overall_grade) - Set llm_used="hash-cache" so operator sees the cache hit explicitly Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>58e3c82 -
fix(upload-extract): read sc.grade not sc.overall_grade
Scorecard dataclass exposes `.grade` (backend/scorecard.py:112). Only the ScorecardResponse wire model renames it to `.overall_grade` in the /api/policies/{id}/scorecard endpoint. The extraction-status resolver was reading `.overall_grade` off the dataclass, getting None, and silently storing grade=None on every upload — the multi-insurer parity audit caught it. Audit re-run will now show status.completeness_pct AND status.overall_grade both equal to the scorecard endpoint's response. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>2323b26 -
fix(upload-extract): use _catalogue_scorecard primary path for status
Previous fix mirrored only the fallback path of /api/policies/{id}/scorecard (build_scorecard(extracted, insurer_reviews)). The endpoint's PRIMARY path is _catalogue_scorecard(policy_id, profile), which builds off the marketplace catalogue (heuristic record.json + curated overlay + dedup + insurer reviews) — that's what produces the 52.2%/grade-C the user sees. The bare build_scorecard path reads 17.4% because it doesn't see the heuristic merge. Same resolution order as the live scorecard endpoint: 1. _catalogue_scorecard(pid, None) ← primary 2. build_scorecard(extracted, insurer_reviews) ← fallback This makes status.completeness_pct + status.overall_grade equal to the scorecard endpoint's response BY CONSTRUCTION for every upload that becomes a marketplace card (which is every successful upload). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>59cf54e -
fix(upload-extract): status completeness now matches scorecard endpoint
Bug: /api/upload/extraction-status reported data_completeness_pct off build_scorecard(policy.model_dump(), profile=None) — no insurer_reviews arg. /api/policies/{id}/scorecard reads the SAME extracted JSON but ALSO passes insurer_reviews loaded off insurer_slug, so the Claim Experience sub-score (and downstream data_completeness accounting) diverged between the two endpoints. On the 2026-05-27 proof upload (Sarvah Param → manipalcigna) this surfaced as status=17.4% while the card endpoint served 52.2%, looking exactly like a merge regression even though the merge was working correctly. Fix: mirror the scorecard endpoint's exact path inside the status resolver — load EXTRACTED_DIR/<pid>.json (the freshly-written LLM JSON), load insurer_reviews off the resolved insurer_slug, call build_scorecard(policy, insurer_reviews=ir, profile=None). Completeness and grade on the status endpoint now equal what the card renders, by construction. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply…e204c0e
-
chore: surface llm_used + llm_response_chars on extraction-status endpoint
For operator visibility — answers "did Gemini actually run, or did NIM/heuristic land it?" without HF Space stdout access. ExtractionStatusResponse now carries: llm_used: "gemini-2.5-flash#1" / "...#2" / "...#3" / "nim-fallback" / None (None = heuristic-only or hash-cache hit, never reached the LLM call loop) llm_response_chars: int — raw response size Set inside extract_one_for_upload after each successful LLM call. Plus: README §6 repo map extended with the backend/uploaded_docs.py function inventory (persist_upload, detect_insurer_slug, extract_one_for_upload, backfill_extractions, _UPLOAD_EXTRACTION_STATUS). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>2abfd01 -
feat(upload-extract): Tier-2 content-hash cache — same PDF, no re-extraction
When a user re-uploads the same PDF (same sha256 of bytes), look up any prior persisted upload's extracted JSON and reuse it. Saves: - 30-60s of LLM call time - one Gemini API call (rate-limit pressure, cost) - guarantees deterministic same-extraction-for-same-content How it works: - meta.json already records sha256 of pdf_bytes per upload - _find_cached_extraction() iterates UPLOADED_DOCS_DIR/*/meta.json, finds another policy_id with the same sha but different policy_id - if rag/extracted/<other_pid>.json exists for that hash, copy it to this policy's path - marks status=complete + bumps the marketplace grade cache - returns immediately, never enters the LLM retry loop Fail-closed: any lookup error → cache miss → falls through to fresh LLM extraction. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>b0375cd -
feat(upload-extract): Tier-1 Gemini stability + new ADR-044 + README rewrites
UPLOADED_DOCS Gemini retry hardening (extract_one_for_upload): - Gemini retry count 1 → 3 with jittered exp backoffs (2s/4s/8s ±25%), mirroring ADR-042's _TRANSIENT_RETRY_BACKOFFS_STICKY pattern that handles Gemini's 429/5xx tail in single_brain. - NIM moved to FINAL fallback (after Gemini exhausts retries). - Raw LLM responses persisted to UPLOADED_DOCS_DIR/<pid>/llm_raw_<n>_<label>.txt on every attempt (success or failure) — gives the operator visibility into WHY a Gemini call failed (was it 429, truncation mid-emission, markdown fence around the JSON, schema mismatch?). Previously a black box. DOCS: - New 70-docs/60-decisions/ADR-044-uploaded-pdf-parity.md — the architectural record for the entire upload-PDF parity effort (LLM extraction + insurer detection + status endpoint + sequence lock + backfill). Includes verification fingerprints from the live e8ccfa0 audit. - README §2.1 user-journey diagram extended with the new upload …be7234d -
fix(upload-extract): drop responseMimeType=application/json — was producing unparseable payloads
Gemini's native JSON mode (responseMimeType=application/json) was silently emitting JSON that json_from_llm_text / HealthPolicy schema validation rejected — surfacing as "LLM returned no valid HealthPolicy" on every fresh upload. Catalogued 148 extraction worked WITHOUT JSON mode (rag/extract.py never sets it) because the EXTRACT_SYSTEM prompt already mandates JSON-only output ("Single object. No whitespace beyond what's needed.") AND json_from_llm_text already strips code fences + <think> blocks + finds the first balanced { ... } block. Removed the response_format kwarg from the Gemini chat call. Same path as the catalogued 148 now — prompt-driven JSON, not transport- driven JSON mode. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>e8ccfa0 -
fix(upload-extract): LLM output now merges INTO heuristic record (not replace)
Live evidence on commit 52b0b5d showed Gemini extraction completing in ~14s but with data_completeness_pct=17.4% — LOWER than the pure heuristic baseline (47.8%). Cause: the marketplace catalogue prefers the rag/extracted/<pid>.json (LLM payload) over the persisted record.json (heuristic baseline), so a sparse LLM extraction was overwriting the richer heuristic fields. Fix: after Gemini writes rag/extracted/<pid>.json, also merge the LLM scalar values INTO UPLOADED_DOCS_DIR/<pid>/record.json. Heuristic stays as the floor; LLM fields override where non-empty. This is the same "extracted + curated overlay" pattern the catalogued 148 use via 40-data/policy_facts/. Schema-shape preserved: heuristic cells ({value, source_pdf_path, source_quote, _confidence}) get their value lifted; bare-scalar heuristic fields get replaced wholesale. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>835f745 -
fix(upload-extract): Gemini-primary done right — max_tokens 2048→8192 to stop truncation
Previous Gemini swap (7ef3ca3) failed live because max_tokens=2048 truncated the HealthPolicy JSON mid-emission (the schema has 23 nested fields each with a value + source_quote, can easily exceed 2k tokens). json_from_llm_text then couldn't parse the truncated payload and the schema validation raised, surfacing as "LLM returned no valid HealthPolicy after primary + fallback retries". Fix: - max_tokens: 2048 → 8192 (Gemini 2.5-flash supports it; the HealthPolicy + quotes typically lands in ~3-5k tokens). - Gemini-only JSON mode: response_format only sent to the Gemini primary, not the NIM fallback (NIM has different kwargs). - Info log on raw-response length so future debugging shows immediately whether the LLM ran out of output budget. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>52b0b5d -
revert(upload-extract): roll back Gemini-primary switch — surfaced as live failures
7ef3ca3 swapped the extraction LLM from NIM (get_brain_llm) to Gemini 2.5-flash with native JSON-mode. Live probe just now showed BOTH attempts (Gemini primary + NIM fallback) raising on the EXTRACT prompt — error surfaces as "LLM returned no valid HealthPolicy after primary + fallback retries". The Sarvah Param test that worked at 9ec9eae (grade C, score 65) regressed to status=failed on 3dcbe9b. Reverted the primary back to NIM. Both attempts are NIM now, same as the proven path. Gemini will be re-added in a follow-up after: - tracing why response_format={"type":"json_object"} returned something json_from_llm_text() couldn't parse against the HealthPolicy schema - confirming Gemini 2.5-flash's JSON-mode honors the EXTRACT_SYSTEM schema_excerpt() instructions Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>fd30ceb -
feat(upload-extract): switch primary LLM from NIM chain → Gemini 2.5-flash (JSON mode)
User-flagged: NIM was being used for upload extraction inherited from rag/extract.py's offline pipeline, even though Gemini 2.5-flash is the steady-state primary brain (ADR-040). Switching primary to Gemini gives us: - Native JSON mode (response_mime_type=application/json) — the LLM is schema-locked, no prose to clean up before parsing - The same Tier-0 brain every live chat turn already uses, with no cold-start regression - Better extraction quality on non-standard PDFs NIM stays as the Tier-1 fallback for: (a) missing GOOGLE_API_KEY (local dev / test machine), (b) Gemini 5xx / quota path. Same EXTRACT_SYSTEM prompt, same HealthPolicy schema, same downstream writes — only the transport changes. Two-tier attempt: Gemini primary (180s timeout) → NIM fallback (120s timeout). Both surface label in the warning log so the operator can see which path each upload took. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>7ef3ca3 -
hotfix: import Header from fastapi — caused RUNTIME_ERROR on 24349be
backend/main.py uses Header(default=None, alias="X-Admin-Password") in the new POST /api/admin/upload/reextract endpoint I just added, but Header wasn't on the `from fastapi import …` line. Python raised NameError at module-import time, which surfaced as the HF Space stage=RUNTIME_ERROR for 24349be. Added Header to the fastapi imports. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>9ec9eae -
feat(upload): backfill LLM extraction for old uploads + admin re-extract endpoint
Old uploads (persisted before ADR-044's LLM-extraction pipeline was wired, OR persisted between dfaa4d6 and 245310d when the pipeline was crashing on the missing asyncio import) never had a rag/extracted/<policy_id>.json written. Their cards therefore stayed at the ~13-17% heuristic-only completeness baseline forever — looked identical pre- and post- fix because the new pipeline never touched them. CHANGES ───────────────────────────────────────────────────────────────────── backend/uploaded_docs.py - New backfill_extractions(force=False) — iterates every persisted upload (UPLOADED_DOCS_DIR), skips ones that already have a rag/extracted/<id>.json (unless force=True), calls extract_one_for_upload sequentially. Returns {processed, skipped, failed, policies}. backend/main.py - New @app.on_event("startup") _startup_upload_extraction_backfill — fires backfill as a fire-and-forget asyncio task on every container boot. Old uploads upgrade automatically to the new…88e54a8 -
fix(upload): missing asyncio import — module-level Lock() fired NameError on import
backend/uploaded_docs.py used asyncio.Lock() + asyncio.wait_for but never imported asyncio. The module-level _UPLOAD_EXTRACTION_LOCK = asyncio.Lock() raised NameError at import time, which surfaced as "Indexing failed: NameError: name 'asyncio' is not defined" on every POST /api/upload-policy after dfaa4d6. Added `import asyncio` at the top of backend/uploaded_docs.py. Verified live by re-importing the module under the project venv. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>245310d -
feat(upload): wait-for-extraction flow + status endpoint + extended voice guard
User directives integrated: 1. "generate the card inline ONLY after full data extraction" → card no longer renders on the partial heuristic record; we wait for the LLM pass to complete first. 2. "ensure re-grading actually happens" → new /api/upload/extraction-status/{policy_id} exposes real-time in-memory state of the background LLM extraction. 3. "kill the unprompted 'Could you please upload' message" → voice auto-submit now blocked for the ENTIRE extraction window (extractionInFlight state), not just the 8s upload-status window. 4. "same level of usability as the 148 catalogued, no less" → no user-upload__ branches in PolicyPremiumWidget / PerPolicyPremiumEstimator — parity by construction once LLM extraction lands and HealthPolicy fields populate. BACKEND ───────────────────────────────────────────────────────────────────── - _UPLOAD_EXTRACTION_STATUS dict (in-process) tracks per-upload extraction lifecycle: pending → running …dfaa4d6 -
feat: uploaded-PDF parity with catalogued 148 (ADR-044)
User-uploaded PDFs now go through the IDENTICAL pipeline as the 148 catalogued policies — same LLM extractor, same scorecard, same review data flow, same card UI. No "user-upload" carve-outs. CHANGES ───────────────────────────────────────────────────────────────────── A. Insurer detection (backend/uploaded_docs.py) detect_insurer_slug() scans the first ~6000 chars of PDF text for the legal name of any of the 21 insurers we have reviews data for (Acko, Bajaj Allianz, HDFC ERGO, ICICI Lombard, ManipalCigna, Niva Bupa, Star Health, Tata AIG, …). On a match, the persisted record + chunk metadata + Chroma metadata are stamped with the REAL insurer_slug → the scorecard's Claim Experience sub-score reads 40-data/reviews/<slug>.json and gets real claim-ratio + complaint-volume + NPS data, same as a catalogued card. Fail-closed: no match ⇒ insurer_slug stays "user-upload". B. LLM-assisted extraction on upload (backend/uploaded_docs.py + backend/main.py) New …4bb66dd -
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 -
fix(privacy v3/v4): two-fact recall gate + extended same-turn extractors (closes ADR-042 follow-ups)
Closes the two open follow-ups in ADR-042 (commits 2acdc9e + 10e6843). (v3) Extended same-turn match-before-merge in apply_pending_recall ───────────────────────────────────────────────────────────────────── v2 covered only age. Now extracts age / dependents / location_tier / income_band from user_text via four small helpers: _extract_age_from_text — tight regex, range [18, 99] _extract_dependents_from_text — delegates to brain_tools._normalize_dependents_inline (honors canonical bucket set) _extract_location_tier_from_text — Indian-city → metro/tier1/tier2/tier3 lookup (longest-key-first so "navi mumbai" beats "mumbai") _extract_income_band_from_text — delegates to needs_finder._parse_income_band _parse_user_text_facts(text) runs all four and returns a dict of the fields that successfully parsed. apply_pending_recall now iterates that dict and discards the stage…2be56b4 -
fix(privacy v2): same-turn age contradiction in apply_pending_recall
The v1 match-before-merge guard (2acdc9e) only catches contradictions that already exist on session.profile from PRIOR turns — but _affirm_or_deny + apply_pending_recall fire BEFORE the LLM iteration that calls save_profile_field. So a reply like "Yes I'm 35" against a staged Rohit-age-29 slipped through (live.age=None pre-merge → no guard fire → merge → LLM later overrides age to 35, leaving the WRONG Rohit's location/dependents/goal stuck on the live profile). This adds: - _extract_age_from_text(user_text) — best-effort regex parse for common phrasings ("I'm 29", "29 years old", "age: 42", "aged 27"). Range-gated [18, 99] so a stray "2 kids" can't trip it. - apply_pending_recall(session, *, confirmed, user_text="") now also runs the parse against user_text and discards the staged recall if the user-said age contradicts staged.age. Mis-parses return None and skip the extra check, costing nothing. - single_brain.py call sites pass user_text through. 11/11 e…10e6843 -
fix: 4 hardening fixes — sticky-retry, canned-msg copy, admin refresh wiring, recall privacy
1) sticky-retry hardening (single_brain.py / KI-singlebrain-503 extension) _gemini_call: gain `is_sticky` kwarg; non-sticky session keeps the 1-retry + 1.5s schedule (fast-fail → nim_fallback on cold-start 503); STICKY session now gets 2 retries with jittered exp backoffs (1.5s → 3s, ±25%). handle_turn reads session.single_brain_sticky once and threads it. Soaks up ~6-10s Gemini "high demand" 503 storms that previously surfaced as the sticky_graceful_retry canned reply. 2) canned-message copy (main.py) "Sorry, I'm having trouble — could you say that again?" wrongly blamed STT/comprehension when the cause was an upstream Gemini transient. New text: "My model service had a brief blip on that turn — please send the same message again, it should go through now." Plain register per feedback_no_ai_sounding_register, locates blame correctly, tells the user exactly what to do. 3) admin LLM Chain refresh wiring (frontend/public/admin/llm-control.html, KI-29…2acdc9e
-
#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
-
#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 -
fix(#61): named-policy bypass not gated on intent (single_brain hardcodes it)
PROVEN root cause: single_brain._execute_tool (single_brain.py:1529) hardcodes intent='recommendation' for EVERY retrieve_policies tool call. The prior #61 bypass was gated on intent!='recommendation' → dead code on the live path → every named-policy Q&A was blocked by the profile gate → 'I couldn't find that policy' (#26/#28, reproduced live 3x). Removed the intent condition. Safety is the resolver's conservatism, not intent. Verified under the EXACT production call signature (intent='recommendation', cold/no-profile): the exact #28 query → count=5 niva-bupa__health-companion-v2022__brochure (was 0); the V2022 variant → count=5; HDFC Optima Restore PED query → count=6; generic 'recommend me a plan' + incomplete profile → count=0 profile_incomplete (recommendation gate STILL intact). Full pytest rc=0. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>2d0235b -
fix(#61): resolve the version-specific chunk-bearing card, not the empty base
Ground truth: my resolver returned the BASE 'niva-bupa__health-companion' (0 corpus chunks) for 'Niva Bupa Health Companion V2022' because the base name scored more generic tokens than 'Health Companion V2022' — so even with the gate bypass, retrieval found nothing → 'I couldn't find it'. Fix: when the query carries an explicit version token (v2022/2022), the matched card whose name contains that exact version wins. Verified deterministically: the exact #28 query → niva-bupa__health-companion- v2022__brochure (5 chunks), base name w/o version → base, HDFC Optima Restore → its id, generic/recommendation → None (gate intact). Gate rc=0. Residual (flagged, not hidden): a 'V22' abbreviation vs 'V2022' card name still maps to the chunk-less base; primary phrasing works. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>995fecb -
fix(#61): named-policy Q&A bypasses the recommendation profile-gate
REAL root cause (live-reproduced, correct payload): single_brain's prompt tells the LLM to query a named-policy question with policy_filter_ids= None, but brain_tools' profile-complete gate blocks ALL policy_filter_ids=None retrieval until the 7-slot fact-find is done — so 'tell me about Niva Bupa Health Companion V2022' (a policy that IS indexed) returned 0 chunks and the bot said 'I couldn't find that policy' (#26/#28). The prior rag/retrieve.py -expansion fix was DOWNSTREAM of this gate → never reached. The gate exists to not RECOMMEND before fact-find, not to refuse a factual lookup. Fix: _resolve_named_policy(query) — conservative, unambiguous match against the marketplace catalogue policy names (>=2 significant tokens, >=60% coverage, top strictly ahead of runner-up). In retrieve_policies, when intent!=recommendation and no policy_filter_ids, resolve the named policy and set policy_filter_ids=[id] → reuses the EXISTING trusted known-policy gate-bypass + the #61 canonical-family …5056f7a -
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(#63): header premium pill is the TYPICAL cohort range, labelled as such
The header pill showed a bare '₹X–₹Y/yr' while the LIVE PREMIUM panel showed a different (often higher) per-plan number — read as 'random different numbers'. Per estimate_premium_band's KI-278 contract this is DELIBERATE: the pill is the p25-p75 typical-cohort band; the panel is ONE specific plan's estimate (may sit outside the typical band — expected, not a contradiction). NO pricing math changed (so #44's 0-violation engine is untouched — gate rc=0). Fix is purely clarity: - PredictedPremiumBandResponse now surfaces sum_insured_used (the model was silently dropping the value the contract already returns) - api.ts type + page.tsx: pill reads 'Typically ₹X–₹Y/yr'; tooltip explains it's the typical range similar buyers pay (at ₹N cover) and that a specific plan's live premium can sit above/below it — expected. Backend import OK; full pytest rc=0; tsc/build green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>e21c985 -
fix(#64): preserve EXACT budget ₹ — slider shows what the user said
The annual-budget slider is continuous, but budget round-tripped through a lossy 4-band enum: budgetBandToInr() could only ever return 12k/22k/45k/75k, so 'I don't want to spend more than 15000 a year' showed as ₹12k. Added a lossless exact field end-to-end: - needs_finder.Profile.budget_inr; brain_tools SLOT_UNION + _ACCEPTED_FIELDS - save_profile_field: when budget_band is captured, also parse + store the EXACT ₹ (numeric, or strip per-annum qualifiers then _parse_inr_amount — same KI-161 guard _coerce_budget_band uses; verified '15000'/'₹15,000/yr'/ '15000 a year'/'more than 15000 a year'/'around 25k per year' → 15000/25000) - main.py ProfileUpdateRequest + apply tuple accept budget_inr - api.ts UserProfile (+nullable) gains budget_inr - page.tsx: slider seeds from budget_inr ?? band-fallback; reseed effect same; handleSave sends budget_inr (exact) alongside the derived budget_band (pricing contract unchanged). Band stays the pricing contract; budget_inr is the display tr…06c7cbc -
fix(#75): compare_policies curated fallback — no scorecard surface 404s
Generalises #60. compare_policies (/api/policies/compare) was the last scorecard surface that still did 'if not extracted_path.exists(): raise HTTPException(404)'. Curated-only catalogued products (e.g. star-health__star-comprehensive, UIN SHAHLIP26044V092526) have no rag/extracted/<pid>.json, so 'Compare all' 404'd / broke for them while the marketplace, single /api/scorecard and bulk scorecard endpoints all already resolved them from the curated layer. Mirrored the same curated fallback (curated dict also carries __wordings/__cis/__brochure/ __prospectus alias keys). Verified: star-comprehensive now grades A 76 in the compare path (was 404). Every scorecard surface now resolves curated-only + (via #40 SSOT / #61) variant/doctype ids — no catalogued policy can show N/A / 'No extraction available' / 404 on any surface. Full pytest gate green (rc=0). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>5b67f14 -
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