Spaces:
Sleeping
Sleeping
Commit History
-
fix(link-rot): validate PDF candidates + untrack llm_health.json
THE INCIDENT Overnight 2026-05-27/28 the nightly link-rot LaunchAgent (com.rohit.insurancebot.linkrot → tools/check_link_rot.py) applied seven bad auto-patches to 40-data/corpus_urls.md and one to tools/.pdf_etag_state.json: - HDFC ERGO ×3 + Bajaj Allianz ×2 + New India ×1: rewrote https→http via try_canonicalise — both work but the downgrade is gratuitous. - Niva Bupa Health Companion (a core indemnity product): rewrote the live URL to a 2-year-old Wayback wrapper that serves HTML, not PDF. Would have silently broken corpus rebuild for that policy. ROOT CAUSE head_check() did HEAD only; the affected origins (HDFC ERGO, Bajaj, New India, Niva Bupa) return text/html interstitials or transient errors for HEAD while serving the real PDF on GET. When HEAD failed transiently, the tool fell into auto_fix and both strategies (try_ canonicalise + try_wayback) accepted any candidate whose HEAD returned status 2xx — without verifying it ACTUALLY served a PDF. The Wayback 'avail…f9437bb -
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
-
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 -
docs(README): fix mermaid sequenceDiagram parse error in §3.7
GitHub-side mermaid renderer choked on curly braces inside sequence arrow message text — '{source.pdf, meta.json}', '{policy_id, ...}', 'Scorecard{grade, ...}', '/{pid}', '[{pid}]' all triggered "Expecting SOLID_ARROW…, got NEWLINE" because '{' is a reserved control token in sequenceDiagram message-text position. Rephrased all 5 instances without braces while preserving identical meaning: 'source.pdf + meta.json', 'HTTP 200 with policy_id', 'Scorecard (grade, data_completeness_pct, sub_scores)', '/pid', 'citations include pid'. No behavioural drift, just renderer-safe wording. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>baf5a60 -
docs: stale-references sweep — align legacy docs with ADR-044 + 8-gate state
11 files fixed per 2026-05-27 docs-audit (P0 / P1 / P2 / one P3): P0 — Upload pipeline most-likely-to-mislead: - 70-docs/20-data-pipeline/ingestion-policy.md: wholesale §"Exception — user uploads" rewrite; dual-write table row; date bumped + ADR-044 cross-ref - kb/security/INDEX.md: "5 gates" → "8 gates" with full table extension P1 — Status inversions: - 70-docs/60-decisions/ADR-003-curated-corpus.md: "Locked" banner now says "partially superseded by ADR-044"; counts 190/19 → 148/21; quarantine-only framing flipped to dual-write - 70-docs/60-decisions/README.md: ADR-003 status row updated - 70-docs/10-architecture/safety-architecture.md: F-13 "Not applicable — D-003" → "LIVE per ADR-044, mitigated by 8 gates" (resolved internal contradiction) - 70-docs/00-overview/problem-statement.md: §5.4 qualified as v1 intent + ADR-044 update; §7 non-goal bullet replaced with cross-session-retrieval caveat P2 — Architecture summaries omitted dual-write: - ARCHITECTURE.md: explicit…21e4b2a -
docs(README+CLAUDE): wire in KI-332 multi-pass + heuristic-floor expansion
- README §2.8 mermaid: hash-cache → multi-pass (≥25K chars) → single-pass branch - README §6 repo map: extract_fields_from_text 28+ patterns enumerated; _multipass_extract_with_gemini call shape; new resolution order - CLAUDE.md upload-pipeline section: floor 47.8% → 65-70% with Test Policy.pdf live verification; multi-pass details including asyncio.gather + max_tokens=4096 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>e7f799a -
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 -
fix(upload): show heuristic-floor card on LLM-fail path + extend poll to 150s (KI-331)
User caught live on Test Policy.pdf 8MB upload (2026-05-27): after Gemini 3/3 retries failed and the 120s poll timed out, the frontend pushed only a prose "I couldn't pull a full analysis" message and never surfaced the heuristic-baseline card — even though `record.json` already had 47.8% completeness / grade C / 6 sub-scores from the heuristic pass that runs BEFORE the LLM ever fires. Two changes: 1. KI-331 — fail/timeout branch now pushes the card-bearing assistant message FIRST (same citations as the success path → inline PolicyScorecardWidget renders with whatever record.json has), then the soft caveat ("I couldn't pull a full analysis"), then the choice prompt. setActiveUploadPid still fires so the brain's DIVE-IN block activates for follow-up questions about the policy. 2. MAX_TRIES bumped 40 → 50 (120s → 150s polling budget). Live audit showed Gemini retry #3 sometimes lands at ~130s on large/complex PDFs; 15s extra buffer eliminates the borderline-miss c…993bcd5 -
feat(single_brain): wire view_context → ACTIVE POLICY DIVE-IN block (KI-330)
Root cause caught in 2026-05-27 multi-PDF e2e audit. On 3 of 5 uploads, asking "What are the waiting periods on this policy?" got back "Before I pull your recommendations, just a couple more (you can skip any):" — single_brain pivoted to profile-building / recommendation flow instead of answering about the just-uploaded policy. Triple root cause: 1. ChatRequest.view_context declared since launch but NEVER CONSUMED anywhere on the backend (truly dead code). 2. single_brain.handle_turn signature didn't accept it. 3. Frontend set view_context.active_policy_id only when a marketplace card was clicked (openPolicy modal); never on a just-uploaded PDF. Fix: - backend/single_brain.py: handle_turn(..., view_context=None); _system_instruction(..., view_context=None); new _build_active_policy_block() that appends an ACTIVE POLICY DIVE-IN block to the system instruction when view_context. active_policy_id is set. Block tells the model: answer the question vi…2a58c28 -
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-ux): lock canonical sequence — ack → wait (everything gated) → card → choice
Per user directive (2026-05-27): 1. User uploads PDF. 2. Bot acknowledges "reading it now, ~30-60s". NO card, NO choice prompt at this point. 3. EVERYTHING is gated during the wait — Send button, textarea, PDF button, voice paths, and the send() function itself all check `uploadStatus || extractionInFlight` and refuse to fire. This eliminates the race where a typed/voice message during the wait drops an unprompted reply into the chat and breaks the staged flow. 4. LLM extraction completes (Gemini 2.5-flash with JSON-mode, ~30s for a 73-page PDF; falls back to NIM if Gemini missing). 5. Bot pushes the card-bearing message + inline scorecard card with the fully-extracted, catalogued-grade data. 6. THEN bot pushes the choice prompt ("finish profile / dive into PDF"). Order matters — the user sees the full picture before being asked what to do next. Defense-in-depth at the send() function entry (last-line guard), so even a prog…3dcbe9b -
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 -
fix(voice): gate the PTT/Sarvam send-paths on uploadStatus + extractionInFlight too
The voiceSubmitRef path (browser SpeechRecognition end-of-speech auto-fire) was guarded in dfaa4d6 — but two OTHER voice send-paths in the PTT recorder.onstop callback (L1289 srFallback + L1311 Sarvam authoritative text) had no guard. If the user accidentally pressed PTT during the upload + extraction window, or if a stray TTS playback bled into the mic and the recorder picked it up, the Sarvam transcription would still drop the resulting chat turn into the middle of the wait — producing the "I can help with that! Please tell me what you'd like to know" unprompted message reported in screenshot #53. Single early-return at the top of the PTT post-transcribe callback now blocks ALL voice send-paths while uploadStatus || extractionInFlight. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>24349be -
feat(upload): 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 -
fix(frontend): PDF upload — in-chat ack + inline scorecard card + proceed-choice prompt
Reported symptom: user uploaded a PDF and saw no acknowledgment in chat — only a transient 8-second banner above the composer, which is easy to miss. The chat transcript itself showed no trace of the upload, so the user had no signal the indexing succeeded or that they could now ask the bot about the document. CHANGES ───────────────────────────────────────────────────────────────────── handleFile (frontend/src/app/page.tsx): 1. pushUser("📎 Uploaded: <filename>") — breadcrumb so the chat transcript records the action AND so the next /api/chat turn's chat_history includes it (helps the brain disambiguate "this policy" references). 2. On success: pushAssistant with the upload-ack text AND a `citations` array carrying the uploaded policy_id. The existing chat renderer reads citations from an assistant message and fires getScorecard(policy_id, session_id) per cited policy, so the scorecard card now appears INLINE under the bubble — same treat…de473cb -
feat!: remove cross-session profile recall (ADR-043) — net −3700 LOC
Sessions are now in-memory only. ADR-041's name-slug + persona_id two-tier on-disk store and ADR-042 v3+v4's two-fact gate + extended extractors are removed entirely. Closing the tab discards the profile. CONTEXT ───────────────────────────────────────────────────────────────────── Two-week arc of recall hardening (ADR-041 → KI-196 → Bug #25 → Bug #26 → ADR-042 v1 → v2 → v3 → v4) kept exposing new failure modes. Each pass was a real bug class, but after v4 the live audit still showed seeded-test failures because the name-slug pointer was being overwritten between tests — the structural truth a name-only key cannot safely disambiguate two visitors who share a name. The workarounds were accumulating without converging. Cost/benefit was wrong for an insurance-shopping product (rare- purchase, return sessions uncommon): ~1500 LOC + 100+ profile JSONs + 2 ADRs + 5 test files + ongoing audit-time state drift, for a feature whose value is "the bot remembers you next visit." Minimum-data- re…6d5684e -
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 -
docs: ADR-042 + README + CLAUDE.md updates for the 4-fix bundle
- new: 70-docs/60-decisions/ADR-042-privacy-hardening-and-sticky-retry.md (full record of v1 + v2 with the live 8/8 audit results) - README §2.4 (LLM brain): new "Sticky-session retry policy" paragraph documenting non-sticky vs sticky retry budgets + the honest canned copy - README §2.6 (Profile / recall): redacted-prompt + match-before-merge flow on the diagram + supporting prose - README §4 (Safety): admin LLM Chain refresh wiring note (KI-296) - CLAUDE.md "Session & profile lifecycle" updated for ADR-042 + KI-296 - CLAUDE.md "Admin panel" updated for the LLM Chain refresh wiring fix Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>128fac1 -
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
-
fix(README): unbreak §3.5 / §3.6 mermaid (HTML entities in participant labels)
GitHub's mermaid parser failed on the §3.5 and §3.6 sequence-diagram participant labels because the literal '<' / '>' entities inside `participant ... as 4. .../<id>.json` look like arrow tokens to the sequence-diagram tokeniser, so it expected SOLID_OPEN_ARROW / DOTTED_ARROW / etc. and got NEWLINE instead — "Parse error on line 5: ...licy_facts/ <id>.json". Both labels were carrying placeholder-style file paths whose only purpose was to name the source file. Replaced: - §3.5 `participant F as 4. 40-data/policy_facts/<id>.json` → `participant F as 4. policy_facts JSON file` - §3.6 `participant D as 4. 40-data/profiles/<name>.json` → `participant D as 4. saved profile JSON file` The file-path detail is already given in §2.7's data-architecture table and in §3.7's stored-vs-live table, so the participant labels can stay plain-English without losing information. The other four sequence diagrams in §3 (which already used plain participants) pa…1786697 -
docs(README): §2 four-level abstraction + §3 sequence diagrams + dedup §4
Reconciled around a single canonical bucket schema (locked in §2.2) and restructured §2 into four ascending levels of abstraction per the product/fintech call follow-up. Every diagram now follows the same prose template: a ≤50-word Summary + a hierarchical "How it flows" breakdown that traces the diagram in visual order. §2 (rebuilt): - §2.1 user journey (unchanged structure; prose normalised to template) - §2.2 building blocks at the highest level (4 canonical buckets; Backend has four sub-blocks 3a..3d); explicit Summary + How-it-flows added, shared diagram legend retained - §2.3 NEW — functional abstraction: the named functions inside each bucket (replaces the unreadable cross-layer mega-diagram). Two-colour edges (blue solid = forward; orange dashed = return). - §2.4 brain + fallback · §2.5 voice · §2.6 profile lifecycle · §2.7 data architecture · §2.8 upload safety · §2.9 deployment — all use the §2.2 bucket vocabulary, all carry the new prose template. §2.7 (rebuilt…4302289 -
docs(README): major rewrite per product+fintech expert review (May 25)
- Merge old §1+§2+§3 into a single §1 with a lead-by-answer structure (the answer first, then the problem, then concretely what it does). - Restructure §4 (now §2) into: - 2.1 user-flow (kept) - 2.2 NEW system-at-a-glance: plain-English frontend / backend primer, a high-level block diagram of the big buckets and how they talk, and a shared LEGEND for every diagram in the section (arrows, dotted arrows, subgraphs, edge labels). - 2.3 Single-turn flow — diagram CORRECTED: Chroma→brain return, 40-data JSON → scorecard.py and premium_calculator.py, profile_store bidirectional restore on returning user. - 2.4 LLM brain + fallback (with old §4.4/§4.5 prose folded in). - 2.5 Voice (with old §4.6 prose folded in). - 2.6 Profile (with old §4.7 prose folded in). - 2.7 Data architecture & ingest — REDRAWN: split into "where it lives" (laptop / GitHub / HF Space / HF Dataset) vs "what kind of data each piece is" (code / curated JSON / heavy binaries / ru…fb32268
-
docs(README): plain-language explanation under every Mermaid diagram
Adds a 'What this diagram traces' aggregate + per-key-block bulleted explanations after every Mermaid in §4.1 (user journey) and §4.3 A-G (request flow, fail-loud fallback, voice, profile+recall, data+ingest, 8 upload gates, deployment). Diagrams themselves are unchanged; the text complements them so a non-Mermaid reader (or a reader skimming) gets the objective + meaning of every block and edge. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>e428554
-
docs: README/ARCHITECTURE — list get_policy_facts tool + note #47 UIN dedup
The brain has 4 function-calling tools; the §4.2 ASCII fallback and ARCHITECTURE.md's one-screen summary listed only 3 (get_policy_facts was missing — the §4.3 Mermaid diagram already had it). Also documents the #47 UIN net-new dedup in §6.1 Uploaded-PDF defence. Architecture itself unchanged this session — the bug fixes (#41/#43/#44/#45/#47) were internal logic/data corrections, not architecture changes. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>7f3a266 -
#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
-
docs: add §4.1 plain-English user-journey diagram; renumber 4.x
New §4.1 'The user's journey' — a Mermaid flowchart of the end-user path (open → fact-find → personalised shortlist → explore/compare/ask/ upload → live premium → decide), placed before any technical content. Existing subsections demoted: shape→4.2, architecture diagrams→4.3, …, profile→4.7. No code touched. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>545bd83 -
docs: expert README polish — rich Mermaid architecture diagrams, clearer data-split table, collapsible repo map
Per expert review (no file moves): (1) §4.2 now has a 7-diagram Mermaid suite covering every layer + interlinkage (request flow, brain+fallback, voice, profile/recall, data+ingest, 8 upload gates, deploy); ASCII kept as plain-text fallback. (2) Rewrote the first table (data split) to be scannable with a lazy-reader reassurance. (3) §8 repo map: concise at-a-glance top-level + full tree behind a <details> so the landing view isn't overwhelming. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>4e11540 -
#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 -
#33: add "?" help affordance to every policy-calculation control
Shared HelpTip component (createPortal body-root popover, desktop hover/focus + touch tap-toggle, Esc/outside/scroll dismiss, a11y labelled) driven by one CALC_HELP_COPY map. Wired next to every calc control across all 3 surfaces: - ProfileBuilder sliders (sum insured / existing cover / co-pay / budget) - PerPolicyPremiumEstimator (sum insured / co-pay) - PolicyPremiumWidget (sum insured / tenure / deductible) Deductible tip auto-absent where unsupported (sits inside the #29 supportsDeductible gate). Copy is purely qualitative — zero digits/%/₹ (no-invented-numbers). Verified: tsc 0, eslint 0-new vs baseline, static build OK, copy-map digit scan clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>deefe3a -
feat(#31): deterministic profile-aware {strengths,caveat} policy summary on all 3 surfaces
Replaces the generic grade one-liner with a per-(profile×policy) ProfileSummary{strengths[], caveat} computed on the SAME pass as the marketplace grade (scorecard.build_profile_summary): deterministic, no LLM, no fabricated numbers, no /100 or A/B in prose; ~4-5 most-material strengths for THIS profile + the one honest grade-capping caveat; fallback to one_liner when facts-sparse/insufficient-data. Rendered at the TOP of CitedPolicyCards, PolicyDetailModal, marketplace PolicyCard, and PolicyScorecardWidget. §4c: /api/policies/{id}/scorecard now takes session_id and resolves the profile via brain_tools.union_snapshot identically to /api/policies/all; single-endpoint defers to the catalogue (single source of truth) so profile_summary+grade are byte-identical across surfaces for all 148 (new parity test). Verified: full pytest suite exit 0 (no regression); test_profile_ summary + parity + endpoint_catalogue 21/21 (incl. 148×6-profile invariants, deductible-gate, non-fabrication, caveat-t…d486a56 -
fix: deductible gating (#29), existing-cover steering + dangling-turn guard (#30), compare-modal full reviews (#32)
#29 — deductible selector/discount was applied to all 148 though only 2 truly offer a voluntary deductible. New premium_calculator.policy_ deductible_support() (deductible_amount>0 AND not top-up → exactly bajaj-allianz__health-guard, star-health__star-assure); estimate + bulk gate the discount (defense-in-depth); PremiumEstimateResponse echoes supports_voluntary_deductible/allowed_deductibles; widget renders the deductible row only when supported. tests/test_deductible_ eligibility.py sweeps all 148. #30 — existing_cover_inr drove neither ranking, retrieval phrasing, nor framing; bot promised 're-evaluate' then stopped; re-eval recycled 2/3. Decisive fix B1-c: +22 existing-cover term in _fit_score for top-ups + seed out-of-window top-ups in _quality_seed_candidates. B1-a: RULE 2 mandatory existing-cover phrasing + Worked example C + RULE 2.6 framing mandate. B2: RULE 3.7 never-promise + _is_promissory_ no_action + one-shot loop guard that forces the promised tool call. B3: RULE 3 mat…3fcae97