rohitsar567 Claude Opus 4.7 (1M context) commited on
Commit
b134f5b
Β·
1 Parent(s): 7081aaa

deploy#2: unified reco-fit gate + session-privacy fix + profile-completeness + full UI rebuild

Browse files

- Reco-fit gate (absorbs #10/#26): product-type + hard-eligibility(entry-age) +
required-feature(maternity) + fit-rank + UIN dedup; new policy_identity.py;
fixes overall_score rank-inversion. 7-persona audit failures resolved.
- Profile session-persistence privacy leak closed (name-keyed directory scan
removed; recall now staged + confirmation-gated, fails closed) + single_brain
"Are you <name>? yes/no" confirm-prompt.
- Profile-form completeness: + desired_sum_insured_inr/smoker/copay_pct/
family_medical_history; ProfileUpdateRequest silent-drop closed.
- Full premium UI rebuild (front-page design system): profile panel, chat/AI
replies, cited cards, marketplace, compare modal, scorecard/premium widgets;
Live(BETA) real warning modal; front-page prose→bullets.
- 117 backend tests pass; frontend production build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

backend/admin.py CHANGED
@@ -545,16 +545,27 @@ def _read_usage_24h() -> Optional[dict]:
545
  Note: "24h" in the field name is conventional β€” the actual window is the
546
  last USAGE_TAIL_LINES rows (typically covers β‰ˆ24h of activity at current
547
  traffic). Keeping the name aligns with the admin UI label.
 
 
 
 
 
 
 
 
 
 
548
  """
549
  usage_path = _REPO_ROOT / "40-data" / "llm_usage.jsonl"
550
  rows = _tail_jsonl(usage_path, USAGE_TAIL_LINES)
551
  if not rows:
552
  return None
553
 
 
554
  agg: dict[str, dict] = {}
555
  for r in rows:
556
  role = r.get("role")
557
- if not role:
558
  continue
559
  bucket = agg.setdefault(role, {"count": 0, "success_count": 0, "latency_sum": 0,
560
  "latency_n": 0})
@@ -969,18 +980,21 @@ async def admin_llm_health(
969
 
970
  # ---------------------------------------------------------------------------
971
  # A5 β€” Audit fix #4: /api/admin/persona-drift β€” slot-capture completeness
972
- # for the last 20 personas. Six canonical slots: name, age, income_band,
973
- # location_tier, primary_goal, health_conditions. <50% capture is flagged
974
- # red on the frontend.
975
  # ---------------------------------------------------------------------------
976
 
977
- # Six canonical fact-find slots. Match the orchestrator's profile_extractor
978
- # targets β€” adding/removing a slot here must mirror the next_question
979
- # routing logic. Health is captured as a list (empty list counts as
980
- # "asked but no conditions" β†’ still a valid captured signal once the
981
- # `asked` array contains the field name).
982
- _PERSONA_DRIFT_SLOTS = ("name", "age", "income_band", "location_tier",
983
- "primary_goal", "health_conditions")
 
 
 
984
 
985
 
986
  def _slot_captured(profile: dict, slot: str, asked: list[str]) -> bool:
 
545
  Note: "24h" in the field name is conventional β€” the actual window is the
546
  last USAGE_TAIL_LINES rows (typically covers β‰ˆ24h of activity at current
547
  traffic). Keeping the name aligns with the admin UI label.
548
+
549
+ ADR-039/040 + Path B (2026-05-15): the multi-brain split (fast_brain /
550
+ judge) and the standalone profile_extractor / paraphraser passes were
551
+ DELETED. The only role the live stack now emits is `brain` (see
552
+ providers.nvidia_nim_llm.get_brain_llm + llm_health.ROLES). The append-
553
+ only llm_usage.jsonl still contains pre-rewrite legacy rows tagged with
554
+ the retired roles, so we filter to the canonical role set β€” exactly as
555
+ /api/admin/usage already does via its `chains` dict β€” instead of blindly
556
+ surfacing every historical role value. llm_health.ROLES is the single
557
+ source of truth (also used as _LLM_HEALTH_CHAIN_ROLES below).
558
  """
559
  usage_path = _REPO_ROOT / "40-data" / "llm_usage.jsonl"
560
  rows = _tail_jsonl(usage_path, USAGE_TAIL_LINES)
561
  if not rows:
562
  return None
563
 
564
+ canonical_roles = set(llm_health.ROLES)
565
  agg: dict[str, dict] = {}
566
  for r in rows:
567
  role = r.get("role")
568
+ if not role or role not in canonical_roles:
569
  continue
570
  bucket = agg.setdefault(role, {"count": 0, "success_count": 0, "latency_sum": 0,
571
  "latency_n": 0})
 
980
 
981
  # ---------------------------------------------------------------------------
982
  # A5 β€” Audit fix #4: /api/admin/persona-drift β€” slot-capture completeness
983
+ # for the last 20 personas. Seven canonical required slots: name, age,
984
+ # dependents, location_tier, income_band, primary_goal, health_conditions.
985
+ # <50% capture is flagged red on the frontend.
986
  # ---------------------------------------------------------------------------
987
 
988
+ # The seven canonical "ready-to-recommend" fact-find slots. Mirrors
989
+ # single_brain._FALLBACK_REQUIRED_SLOTS (the live single-brain stack's
990
+ # required set after the ADR-039/040 Path B rewrite) and needs_finder.
991
+ # Profile's persisted fields. `dependents` was previously missing here even
992
+ # though it is a required slot and is persisted on every profile JSON β€”
993
+ # adding/removing a slot must stay in sync with that required set. Health is
994
+ # captured as a list (empty list counts as "asked but no conditions" β†’ still
995
+ # a valid captured signal once the `asked` array contains the field name).
996
+ _PERSONA_DRIFT_SLOTS = ("name", "age", "dependents", "location_tier",
997
+ "income_band", "primary_goal", "health_conditions")
998
 
999
 
1000
  def _slot_captured(profile: dict, slot: str, asked: list[str]) -> bool:
backend/brain_tools.py CHANGED
@@ -88,9 +88,37 @@ _FACTS_DIR = Path(__file__).resolve().parent.parent / "40-data" / "policy_facts"
88
  _DOCTYPE_SUFFIXES = ("__wordings", "__brochure", "__cis", "__prospectus")
89
  _FACT_KEYS = (
90
  "policy_type_indemnity_or_fixed",
 
 
 
 
 
 
 
91
  "deductible_amount",
92
  "co_payment_pct",
93
  "sum_insured_options",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  )
95
  _facts_cache: dict[str, dict] = {}
96
 
@@ -145,9 +173,25 @@ def _load_policy_facts(policy_id: str) -> dict:
145
  for k in _FACT_KEYS:
146
  if k in d and k not in out:
147
  out[k] = _unwrap(d[k])
148
- # Stop once we have the decision-critical signals.
149
- if "policy_type_indemnity_or_fixed" in out and (
150
- "sum_insured_options" in out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  ):
152
  break
153
  except Exception as e: # noqa: BLE001 β€” enrichment must never break retrieval
@@ -180,9 +224,21 @@ def _scorecard_signal(policy_id: str, profile=None) -> dict:
180
  )
181
  }
182
  sc = build_scorecard(facts or {"policy_id": policy_id}, profile=prof)
 
 
 
 
 
 
 
 
 
 
 
 
183
  return {
184
  "_grade": getattr(sc, "grade", None),
185
- "_overall_score": getattr(sc, "overall", None),
186
  }
187
  except Exception: # noqa: BLE001 β€” scorecard optional; ranking degrades gracefully
188
  return {}
 
88
  _DOCTYPE_SUFFIXES = ("__wordings", "__brochure", "__cis", "__prospectus")
89
  _FACT_KEYS = (
90
  "policy_type_indemnity_or_fixed",
91
+ # KI-279 (2026-05-16) β€” the raw catalog type key. Some curated files
92
+ # (e.g. star-health__star-hospital-cash__brochure.json) carry the
93
+ # product type ONLY under `policy_type` ("hospital_cash") and have NO
94
+ # `policy_type_indemnity_or_fixed` key. Without surfacing this, the
95
+ # retrieval_filters fixed-benefit gate is blind and a daily-cash plan
96
+ # ranks #1 for a comprehensive-indemnity buyer. Read-only; STABLE key.
97
+ "policy_type",
98
  "deductible_amount",
99
  "co_payment_pct",
100
  "sum_insured_options",
101
+ # KI-280 (2026-05-16) β€” UNIFIED recommendation-fit gate. The eligibility
102
+ # gate needs these STABLE policy_facts keys (read-only):
103
+ # uin_code β†’ canonical dedup identity (1 UIN = 1 product;
104
+ # collapses marketing-rename / doctype-sibling
105
+ # duplicate CITED cards β€” audit P2/P4/P7).
106
+ # max_entry_age β†’ hard eligibility for the INSURED person. When
107
+ # the profile insures parents (~70), a plan
108
+ # whose max entry age is 65 cannot accept them
109
+ # (audit P7). The chunk already carries
110
+ # max_entry_age from Chroma metadata, but the
111
+ # curated facts file is the authoritative value
112
+ # and overrides a missing/None chunk field.
113
+ # maternity_coverage β†’ required-feature gate: an explicit maternity /
114
+ # newborn_coverage newborn need must rank confirmed plans above
115
+ # unconfirmed ones (audit P3).
116
+ # max_renewal_age is intentionally NOT read β€” it was removed from the
117
+ # scorecard (lifelong renewal is the IRDAI norm; scorecard.py:606).
118
+ "uin_code",
119
+ "max_entry_age",
120
+ "maternity_coverage",
121
+ "newborn_coverage",
122
  )
123
  _facts_cache: dict[str, dict] = {}
124
 
 
173
  for k in _FACT_KEYS:
174
  if k in d and k not in out:
175
  out[k] = _unwrap(d[k])
176
+ # Stop once we have the decision-critical signals. KI-279: a
177
+ # type signal is "have it" if EITHER the canonical key OR the
178
+ # raw `policy_type` key is present (some files only carry the
179
+ # latter), so the fixed-benefit gate is never starved.
180
+ # KI-280: also require the unified-gate signals (uin_code +
181
+ # max_entry_age) before breaking so the eligibility/dedup rules
182
+ # are not starved when a sibling doctype file carries them. The
183
+ # candidate-stem list is short (≀5) so iterating it fully is
184
+ # cheap; this just stops us breaking after stem #1 when the UIN
185
+ # / entry-age lives in stem #2.
186
+ _have_type = (
187
+ "policy_type_indemnity_or_fixed" in out
188
+ or "policy_type" in out
189
+ )
190
+ if (
191
+ _have_type
192
+ and "sum_insured_options" in out
193
+ and "uin_code" in out
194
+ and "max_entry_age" in out
195
  ):
196
  break
197
  except Exception as e: # noqa: BLE001 β€” enrichment must never break retrieval
 
224
  )
225
  }
226
  sc = build_scorecard(facts or {"policy_id": policy_id}, profile=prof)
227
+ # KI-280 (2026-05-16) β€” the Scorecard dataclass field is
228
+ # `overall_score` (scorecard.py:95), NOT `overall`. The previous
229
+ # getattr(sc, "overall", ...) ALWAYS returned None, so every
230
+ # enriched chunk reached retrieval_filters with _overall_score=None
231
+ # and _fit_score fell back to the coarse letter-grade table where
232
+ # every "B" == 70.0 exactly. Within-grade order then collapsed to
233
+ # raw cosine β€” the live audit's grade/rank inversion (P1 C/65 above
234
+ # B/75, P2 A/77 ranked LAST). Read the real numeric field; keep a
235
+ # belt-and-braces `overall` alias for forward-compat.
236
+ _overall = getattr(sc, "overall_score", None)
237
+ if _overall is None:
238
+ _overall = getattr(sc, "overall", None)
239
  return {
240
  "_grade": getattr(sc, "grade", None),
241
+ "_overall_score": _overall,
242
  }
243
  except Exception: # noqa: BLE001 β€” scorecard optional; ranking degrades gracefully
244
  return {}
backend/main.py CHANGED
@@ -1751,6 +1751,13 @@ class ProfileUpdateRequest(BaseModel):
1751
  parents_has_ped: Optional[bool] = None
1752
  health_conditions: Optional[list[str]] = None
1753
  budget_band: Optional[str] = None
 
 
 
 
 
 
 
1754
 
1755
 
1756
  class SessionResetRequest(BaseModel):
@@ -1845,6 +1852,7 @@ async def profile_update(req: ProfileUpdateRequest):
1845
  "age", "dependents", "income_band", "existing_cover_inr", "primary_goal",
1846
  "location_tier", "parents_to_insure", "parents_age_max", "parents_has_ped",
1847
  "health_conditions", "budget_band",
 
1848
  ):
1849
  v = getattr(req, field_name, None)
1850
  if v in (None, "", []):
@@ -3481,19 +3489,32 @@ class RecallByNameRequest(BaseModel):
3481
 
3482
  class RecallByNameResponse(BaseModel):
3483
  found: bool
3484
- profile: Optional[dict] = None
3485
- predicted_band: Optional[dict] = None
 
 
 
 
 
 
 
3486
  session_id: str
3487
 
3488
 
3489
  @app.post("/api/profile/recall-by-name", response_model=RecallByNameResponse)
3490
  async def recall_profile_by_name(req: RecallByNameRequest):
3491
- """Hydrate `session_id` from the stored named-profile JSON (if any).
3492
-
3493
- Returns `found=False` when the slug doesn't resolve to a stored file.
3494
- On a hit, the live in-memory session is populated and the response
3495
- carries the full union dict + predicted premium band so the UI can
3496
- render the welcome-back banner without a second roundtrip.
 
 
 
 
 
 
3497
  """
3498
  from backend.profile_persistence import recall_by_name_payload
3499
 
 
1751
  parents_has_ped: Optional[bool] = None
1752
  health_conditions: Optional[list[str]] = None
1753
  budget_band: Optional[str] = None
1754
+ # KI β€” profile-builder UI now collects these 4; they exist on the Profile
1755
+ # dataclass + chat-path save_profile_field but were being silently dropped
1756
+ # from POST /api/profile because they weren't whitelisted here.
1757
+ desired_sum_insured_inr: Optional[int] = None
1758
+ copay_pct: Optional[int] = None
1759
+ family_medical_history: Optional[list[str]] = None
1760
+ smoker: Optional[bool] = None
1761
 
1762
 
1763
  class SessionResetRequest(BaseModel):
 
1852
  "age", "dependents", "income_band", "existing_cover_inr", "primary_goal",
1853
  "location_tier", "parents_to_insure", "parents_age_max", "parents_has_ped",
1854
  "health_conditions", "budget_band",
1855
+ "desired_sum_insured_inr", "copay_pct", "family_medical_history", "smoker",
1856
  ):
1857
  v = getattr(req, field_name, None)
1858
  if v in (None, "", []):
 
3489
 
3490
  class RecallByNameResponse(BaseModel):
3491
  found: bool
3492
+ # PRIVACY FIX (2026-05-16, audit). The endpoint no longer hydrates the
3493
+ # session off a bare name (weak/shared key β†’ stranger-PII leak). When a
3494
+ # stored profile matches, the response asks the UI to confirm identity
3495
+ # FIRST. `profile`/`predicted_band` are never returned pre-confirmation.
3496
+ requires_confirmation: bool = False
3497
+ name: Optional[str] = None # stored display name, for the prompt
3498
+ summary: Optional[dict] = None # non-PII identity hints, for the prompt
3499
+ profile: Optional[dict] = None # always None until user confirms
3500
+ predicted_band: Optional[dict] = None # always None until user confirms
3501
  session_id: str
3502
 
3503
 
3504
  @app.post("/api/profile/recall-by-name", response_model=RecallByNameResponse)
3505
  async def recall_profile_by_name(req: RecallByNameRequest):
3506
+ """Stage a stored named-profile match for `session_id` (if any).
3507
+
3508
+ PRIVACY FIX (2026-05-16, audit). A bare name is a weak, shared,
3509
+ guessable key. This endpoint NO LONGER auto-hydrates the session β€” a
3510
+ second user on a shared browser/IP, or anyone stating a common first
3511
+ name, must not be silently served a stranger's stored profile. When a
3512
+ match exists the response carries `found=True, requires_confirmation=
3513
+ True, name, summary` so the UI renders an explicit "are you <name>?"
3514
+ prompt. The stored fields are applied to the session only after the
3515
+ user confirms (handled on the chat affirmation path via
3516
+ session_state.apply_pending_recall). Returns `found=False` when the
3517
+ slug doesn't resolve to a stored file.
3518
  """
3519
  from backend.profile_persistence import recall_by_name_payload
3520
 
backend/policy_identity.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Canonical policy identity + dedup β€” SINGLE SOURCE OF TRUTH (KI-280).
2
+
3
+ The marketplace endpoint `main.py /api/policies/all` already established the
4
+ canonical-identity rule (KI-133 / KI-141 / KI-142 / KI-145):
5
+
6
+ 1 unique IRDAI UIN = 1 unique product (UIN-primary invariant).
7
+ When no UIN is present, the product_key = the policy_id with any
8
+ trailing doctype suffix (`__wordings` / `__brochure` / `__cis` /
9
+ `__prospectus`) stripped.
10
+
11
+ The recommendation-fit gate (retrieval_filters.dedup_by_policy) used to key
12
+ ONLY on the exact `policy_id`, so two chunks for the SAME product but with
13
+ different ids β€” a marketing rename ("my:Optima Secure" vs
14
+ "my:Optima Secure (older variant)") or two doctype siblings
15
+ (`...__wordings` vs `...__brochure`) β€” were both emitted as separate CITED
16
+ cards (audit personas P2/P4/P7). The marketplace and the recommender
17
+ disagreed on what "the same policy" means.
18
+
19
+ This module factors that one rule so BOTH surfaces share it. It is
20
+ deliberately dependency-free (no FastAPI / Chroma import) so
21
+ retrieval_filters can import it without an import cycle.
22
+
23
+ Public API:
24
+ canonical_key(chunk_or_meta) -> str
25
+ The dedup key for a retrieved chunk: prefer a normalised UIN, else
26
+ the product_key (policy_id with the doctype suffix stripped).
27
+ product_key(policy_id) -> str
28
+ The marketplace product_key (KI-133): policy_id minus any trailing
29
+ `__<doctype>` segment.
30
+ normalize_uin(raw) -> str
31
+ Upper-cased, whitespace/punctuation-collapsed UIN, or "" when the
32
+ value is absent / not a plausible UIN.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import re
38
+ from typing import Any
39
+
40
+ # Trailing doctype segments the curator appends to a policy_id stem. Mirrors
41
+ # brain_tools._DOCTYPE_SUFFIXES and main.py _doctype_of_cov. A product_key is
42
+ # the stem with ANY of these removed (KI-133 β€” "wordings wins" dedup).
43
+ _DOCTYPE_SUFFIXES = ("__wordings", "__brochure", "__cis", "__prospectus")
44
+
45
+ # A plausible IRDAI UIN is mostly alphanumerics with a few separators and is
46
+ # reasonably long. We normalise aggressively so "IRDA/HLT/.../188/14-15" and
47
+ # "irdahlt18814 15" compare equal. Anything shorter than 8 normalised chars
48
+ # is treated as "no UIN" (a stray code, not a real filing id).
49
+ _UIN_STRIP_RE = re.compile(r"[^A-Z0-9]")
50
+ _MIN_UIN_LEN = 8
51
+
52
+
53
+ def product_key(policy_id: str) -> str:
54
+ """KI-133 product_key: the policy_id with any trailing `__<doctype>`
55
+ segment removed. `acko__health-iii__wordings` -> `acko__health-iii`.
56
+ Mirrors main.py `_product_key_of_cov` exactly so the recommender and
57
+ the marketplace agree on product identity."""
58
+ pid = (policy_id or "").strip()
59
+ if not pid:
60
+ return ""
61
+ for suf in _DOCTYPE_SUFFIXES:
62
+ if pid.endswith(suf):
63
+ return pid[: -len(suf)]
64
+ # main.py uses rsplit on the LAST "__"; mirror it so an un-suffixed
65
+ # multi-segment id collapses identically (insurer__product__variant ->
66
+ # insurer__product only when the tail is a known doctype; otherwise the
67
+ # rsplit form is what the marketplace card count used).
68
+ if "__" in pid:
69
+ head, tail = pid.rsplit("__", 1)
70
+ # Only strip the tail if it looks like a doctype token (the
71
+ # marketplace's _doctype_of_cov returns "" for non-doctype tails
72
+ # and product_key then == pid, so guard against over-collapsing
73
+ # genuine product segments like "...__platinum").
74
+ if tail in ("wordings", "brochure", "cis", "prospectus"):
75
+ return head
76
+ return pid
77
+
78
+
79
+ def normalize_uin(raw: Any) -> str:
80
+ """Upper-case + strip every non-alphanumeric char. Accepts the
81
+ policy_facts `{value: ...}` wrapper or a bare string. Returns "" when
82
+ the value is missing or too short to be a real IRDAI UIN."""
83
+ if isinstance(raw, dict) and "value" in raw:
84
+ raw = raw.get("value")
85
+ if not isinstance(raw, str):
86
+ return ""
87
+ norm = _UIN_STRIP_RE.sub("", raw.upper())
88
+ if len(norm) < _MIN_UIN_LEN:
89
+ return ""
90
+ return norm
91
+
92
+
93
+ def _meta(chunk_or_meta: Any) -> dict:
94
+ """Accept a dict (brain_tools chunk) or a duck-typed object."""
95
+ if isinstance(chunk_or_meta, dict):
96
+ return chunk_or_meta
97
+ out: dict = {}
98
+ for k in ("policy_id", "uin_code", "uin"):
99
+ if hasattr(chunk_or_meta, k):
100
+ out[k] = getattr(chunk_or_meta, k)
101
+ return out
102
+
103
+
104
+ def canonical_key(chunk_or_meta: Any) -> str:
105
+ """The dedup key for a retrieved chunk.
106
+
107
+ UIN-primary (matches the marketplace KI-142 invariant): when the chunk
108
+ carries a plausible UIN, that normalised UIN IS the identity β€” a
109
+ marketing rename keeps the same UIN so its variant chunk collapses onto
110
+ the parent card. Otherwise fall back to the product_key (doctype-stripped
111
+ policy_id) so two doctype siblings of the same product still collapse.
112
+
113
+ Always returns a non-empty string (falls back to the raw policy_id, then
114
+ to the policy_name) so a chunk is never silently keyed to "".
115
+ """
116
+ m = _meta(chunk_or_meta)
117
+ uin = normalize_uin(m.get("uin_code") or m.get("uin"))
118
+ if uin:
119
+ return f"uin:{uin}"
120
+ pid = (m.get("policy_id") or "").strip()
121
+ pk = product_key(pid)
122
+ if pk:
123
+ return f"pk:{pk}"
124
+ name = (m.get("policy_name") or "").strip().lower()
125
+ return f"nm:{name}" if name else "pk:"
126
+
127
+
128
+ __all__ = ["canonical_key", "product_key", "normalize_uin"]
backend/profile_persistence.py CHANGED
@@ -22,16 +22,28 @@ Coupled features (KI-Z7, 2026-05-15):
22
  Gemini's first tool-call iteration.
23
 
24
  Feature B β€” try_recall_by_name(session, name)
25
- Loads the named profile JSON via profile_store.load_profile and hydrates
26
- every empty slot on session.profile. Returns True on a successful merge
27
- so single_brain can stamp `is_returning_user=True` for the RULE 4
28
- "welcome back" greeting.
 
 
 
 
 
 
 
 
29
 
30
  Feature B β€” recall_by_name_payload(name, session_id)
31
  Builds the response payload for the POST /api/profile/recall-by-name
32
- endpoint: {found, profile, predicted_band, session_id}. predicted_band
33
- is computed via premium_calculator.estimate_premium_band against the
34
- just-hydrated profile.
 
 
 
 
35
 
36
  Design notes:
37
  - This module sits between profile_store + profile_rag and is the SINGLE
@@ -219,13 +231,21 @@ def extract_potential_name(text: str) -> Optional[str]:
219
 
220
 
221
  def try_recall_by_name(session, name: str) -> bool:
222
- """Look up a stored profile by name and hydrate `session.profile`.
223
 
224
- Wraps session_state.rehydrate_by_name so the call-site (single_brain
225
- handle_turn entry) doesn't need to know which helper is canonical.
 
 
226
 
227
- Returns True iff a stored profile was found AND at least one slot was
228
- merged into the live session. False on no-match or any error.
 
 
 
 
 
 
229
  """
230
  if not name or not name.strip():
231
  return False
@@ -247,20 +267,32 @@ async def recall_by_name_payload(
247
  ) -> dict[str, Any]:
248
  """Build the response payload for POST /api/profile/recall-by-name.
249
 
 
 
 
 
 
 
250
  Returns:
251
  {
252
- "found": bool,
253
- "profile": dict | None, # the hydrated union dict
254
- "predicted_band": dict | None, # {min_inr, median_inr, max_inr, ...}
 
 
 
255
  "session_id": str,
256
  }
257
 
258
- Side effect: when a match is found, the live in-memory session for
259
- `session_id` is hydrated (so the next /api/chat turn sees the recalled
260
- slots in session.profile WITHOUT requiring a separate /api/profile POST).
261
  """
262
  out: dict[str, Any] = {
263
  "found": False,
 
 
 
264
  "profile": None,
265
  "predicted_band": None,
266
  "session_id": session_id,
@@ -279,28 +311,16 @@ async def recall_by_name_payload(
279
  )
280
  return out
281
 
282
- found = try_recall_by_name(sess, name)
283
- if not found:
 
 
284
  return out
285
 
286
- # Build the union dict snapshot post-hydration.
287
- union = _build_union_dict(sess.profile)
288
  out["found"] = True
289
- out["profile"] = union
290
-
291
- # Predicted-premium band β€” same path /api/profile/predicted-premium-band
292
- # uses, so the banner number matches the chip number exactly.
293
- try:
294
- from backend.premium_calculator import estimate_premium_band
295
-
296
- out["predicted_band"] = estimate_premium_band(union)
297
- except Exception as e: # noqa: BLE001
298
- _log.warning(
299
- "recall_by_name_payload: estimate_premium_band failed (name=%r): %s: %s",
300
- name, type(e).__name__, str(e)[:200],
301
- )
302
- out["predicted_band"] = None
303
-
304
  return out
305
 
306
 
 
22
  Gemini's first tool-call iteration.
23
 
24
  Feature B β€” try_recall_by_name(session, name)
25
+ PRIVACY FIX (2026-05-16, audit). Previously this hydrated every empty
26
+ slot on session.profile and returned True so single_brain stamped
27
+ `is_returning_user=True` / a "Welcome back" greeting β€” on a FRESH,
28
+ no-cookie session, keyed only on the user-stated name. A second user
29
+ on a shared browser/IP, or anyone stating a common first name, was
30
+ served a stranger's captured profile. Now it delegates to
31
+ session_state.rehydrate_by_name which STAGES the match on
32
+ `session.pending_profile_recall` (no merge, no greeting) and ALWAYS
33
+ returns False. The stored profile is applied ONLY after an explicit
34
+ user confirmation via session_state.apply_pending_recall(session,
35
+ confirmed=True). Same-session continuity is unaffected β€” slots captured
36
+ within the live conversation never travel this path.
37
 
38
  Feature B β€” recall_by_name_payload(name, session_id)
39
  Builds the response payload for the POST /api/profile/recall-by-name
40
+ endpoint. PRIVACY FIX (2026-05-16): this NO LONGER auto-hydrates the
41
+ live session. A name match is STAGED; the payload reports
42
+ {found, requires_confirmation, name, summary, session_id} so the UI
43
+ renders an explicit "are you <name>?" confirm rather than silently
44
+ adopting a stranger's stored profile. The stored fields are applied to
45
+ the session only after the user confirms (the chat affirmation path
46
+ calls session_state.apply_pending_recall).
47
 
48
  Design notes:
49
  - This module sits between profile_store + profile_rag and is the SINGLE
 
231
 
232
 
233
  def try_recall_by_name(session, name: str) -> bool:
234
+ """Look up a stored profile by name and STAGE it for confirmation.
235
 
236
+ PRIVACY FIX (2026-05-16). Wraps session_state.rehydrate_by_name, which
237
+ now STAGES a name match on `session.pending_profile_recall` instead of
238
+ auto-merging it into `session.profile`. Nothing is applied to the live
239
+ session here.
240
 
241
+ Returns:
242
+ Always False β€” the stored profile is NEVER auto-applied. The
243
+ single_brain caller therefore never stamps `is_returning_user` /
244
+ a "Welcome back" greeting off a bare name on a fresh session.
245
+ Whether a match was *staged* is observable on
246
+ `session.pending_profile_recall`; the brain surfaces an "are you
247
+ <name>?" confirm and calls session_state.apply_pending_recall on
248
+ the user's explicit answer.
249
  """
250
  if not name or not name.strip():
251
  return False
 
267
  ) -> dict[str, Any]:
268
  """Build the response payload for POST /api/profile/recall-by-name.
269
 
270
+ PRIVACY FIX (2026-05-16, audit). This NO LONGER hydrates the live
271
+ session. A bare name is a weak, shared, guessable key; auto-applying a
272
+ stored profile to a fresh, no-cookie session leaked stranger PII. A
273
+ match is now STAGED on `session.pending_profile_recall`; the payload
274
+ asks the UI to confirm identity before anything is applied.
275
+
276
  Returns:
277
  {
278
+ "found": bool, # True iff a stored match exists
279
+ "requires_confirmation": bool, # True when found (never auto-apply)
280
+ "name": str | None, # stored display name (for the prompt)
281
+ "summary": dict | None, # non-PII identity hints for the prompt
282
+ "profile": None, # NEVER returned pre-confirmation
283
+ "predicted_band": None, # NEVER returned pre-confirmation
284
  "session_id": str,
285
  }
286
 
287
+ No side effect on `session.profile`. The staged match is applied only
288
+ after the user explicitly confirms, via the chat affirmation path
289
+ (session_state.apply_pending_recall).
290
  """
291
  out: dict[str, Any] = {
292
  "found": False,
293
+ "requires_confirmation": False,
294
+ "name": None,
295
+ "summary": None,
296
  "profile": None,
297
  "predicted_band": None,
298
  "session_id": session_id,
 
311
  )
312
  return out
313
 
314
+ # Stages on sess.pending_profile_recall; ALWAYS returns False (no merge).
315
+ try_recall_by_name(sess, name)
316
+ pending = getattr(sess, "pending_profile_recall", None)
317
+ if not pending:
318
  return out
319
 
 
 
320
  out["found"] = True
321
+ out["requires_confirmation"] = True
322
+ out["name"] = pending.get("name")
323
+ out["summary"] = pending.get("summary")
 
 
 
 
 
 
 
 
 
 
 
 
324
  return out
325
 
326
 
backend/profile_store.py CHANGED
@@ -119,34 +119,36 @@ def _load_from_path(p: Path) -> Optional[Profile]:
119
  def load_profile(name: str, *, persona_id: Optional[str] = None) -> Optional[Profile]:
120
  """Return the stored Profile for `name` (and optional `persona_id`).
121
 
122
- KI-062 (2026-05-15) lookup order:
123
- 1. If `persona_id` given, try that file first.
124
  2. Try the name-slug file (legacy + first-visit path before
125
  identity fields are known).
126
- 3. If both miss but the name slug is set, scan the directory for
127
- any persona-id-keyed file whose stored name matches β€” handles
128
- the case where the user introduced themselves by name but no
129
- persona ID is known yet client-side.
 
 
 
 
 
 
 
 
 
 
 
130
  """
131
- # 1. Direct persona-id hit
132
  if persona_id:
133
  p = _path_for(name, persona_id=persona_id)
134
  if p and p.exists():
135
  return _load_from_path(p)
136
- # 2. Legacy / first-visit name-slug file
137
  p = _path_for(name)
138
  if p and p.exists():
139
  return _load_from_path(p)
140
- # 3. Scan for any persona-id file whose stored display-name matches
141
- slug = _normalise_name(name)
142
- if slug and _PROFILES_DIR.exists():
143
- for cand in _PROFILES_DIR.glob("*.json"):
144
- try:
145
- raw = json.loads(cand.read_text())
146
- if _normalise_name(raw.get("name_display") or "") == slug:
147
- return _load_from_path(cand)
148
- except Exception:
149
- continue
150
  return None
151
 
152
 
 
119
  def load_profile(name: str, *, persona_id: Optional[str] = None) -> Optional[Profile]:
120
  """Return the stored Profile for `name` (and optional `persona_id`).
121
 
122
+ Lookup order (KI-062, 2026-05-15; PRIVACY-HARDENED 2026-05-16):
123
+ 1. If `persona_id` given, try that exact file.
124
  2. Try the name-slug file (legacy + first-visit path before
125
  identity fields are known).
126
+
127
+ PRIVACY FIX (2026-05-16, audit). A former step 3 scanned the WHOLE
128
+ profiles directory and returned any persona-id-keyed file whose stored
129
+ `name_display` matched the requested name slug. That was a pure
130
+ cross-identity leak: a fresh, no-cookie visitor stating a common first
131
+ name ("I'm Rahul") pulled a *stranger's* persona-id profile (different
132
+ age / city / dependents) β€” exactly the audit's "Welcome back, Rahul"
133
+ finding. The scan has no legitimate use: `save_profile` already writes
134
+ a name-slug file on the first visit (before identity fields exist) and
135
+ only graduates to a persona-id file once enough disambiguating signal
136
+ exists, so a real returning user is resolved by step 1 (their own
137
+ persona_id, passed by the client) or step 2 (their own slug file).
138
+ Matching strangers by bare display name is removed entirely. Cross-name
139
+ recall, when intended, is now gated behind explicit user confirmation
140
+ at the session layer (`session_state.apply_pending_recall`).
141
  """
142
+ # 1. Direct persona-id hit (the caller's OWN id, never inferred here).
143
  if persona_id:
144
  p = _path_for(name, persona_id=persona_id)
145
  if p and p.exists():
146
  return _load_from_path(p)
147
+ # 2. Legacy / first-visit name-slug file (this user's own slug file).
148
  p = _path_for(name)
149
  if p and p.exists():
150
  return _load_from_path(p)
151
+ # 3. (REMOVED) cross-identity display-name directory scan β€” leak vector.
 
 
 
 
 
 
 
 
 
152
  return None
153
 
154
 
backend/retrieval_filters.py CHANGED
@@ -9,10 +9,13 @@ Public API:
9
  Drop chunks for policies the user is demographically ineligible for.
10
  apply_eligibility_filter(chunks, profile) -> list[RetrievedChunk]
11
  Drop chunks the user is STRUCTURALLY ineligible for / that clearly
12
- contradict an explicit stated need (KI-278):
13
  - top-up / super-top-up when the user has no existing base cover
14
  - plans whose max sum-insured cannot meet the requested SI
15
  - high co-pay plans when the user explicitly wants zero co-pay
 
 
 
16
  rank_by_profile_fit(chunks, profile) -> list[RetrievedChunk]
17
  Re-order surviving chunks so the plans that best match the stated
18
  needs (grade, co-pay, SI headroom) rank above weak-fit plans whose
@@ -38,6 +41,13 @@ from __future__ import annotations
38
  import re
39
  from typing import Any, Iterable, Optional
40
 
 
 
 
 
 
 
 
41
  # We avoid importing RetrievedChunk at module-import time to keep this file
42
  # import-cycle-safe. Instead we type-duck on attributes.
43
 
@@ -137,6 +147,97 @@ UIN_RE = re.compile(
137
  flags=re.IGNORECASE,
138
  )
139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
  # ---------------------------------------------------------------------------
142
  # Helpers
@@ -175,6 +276,10 @@ def _meta_full(chunk: Any) -> dict:
175
  for k in (
176
  "policy_type_indemnity_or_fixed", "deductible_amount",
177
  "co_payment_pct", "sum_insured_options", "_grade", "_overall_score",
 
 
 
 
178
  ):
179
  if hasattr(chunk, k):
180
  out[k] = getattr(chunk, k)
@@ -241,7 +346,19 @@ def apply_profile_filter(chunks: Iterable[Any], profile: Any) -> list[Any]:
241
  if not chunks_list:
242
  return chunks_list
243
 
244
- age = _profile_get(profile, "age")
 
 
 
 
 
 
 
 
 
 
 
 
245
  # If age unknown, only the maternity rule can fire β€” keep everything else.
246
  has_age = isinstance(age, int)
247
 
@@ -371,6 +488,199 @@ def _user_wants_zero_copay(profile: Any) -> bool:
371
  return copay is not None and copay <= ZERO_COPAY_USER_MAX_COPAY_PCT
372
 
373
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
  def apply_eligibility_filter(chunks: Iterable[Any], profile: Any) -> list[Any]:
375
  """Drop chunks the user is STRUCTURALLY ineligible for, or that plainly
376
  contradict an explicit stated need (KI-278).
@@ -391,6 +701,24 @@ def apply_eligibility_filter(chunks: Iterable[Any], profile: Any) -> list[Any]:
391
  ZERO_COPAY_USER_MAX_COPAY_PCT. Regardless of stated preference,
392
  drop plans with a punitive co-pay (>= PUNITIVE_COPAY_PCT).
393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
394
  Conservative on missing data: a rule only fires when BOTH the profile
395
  signal AND the policy fact are present. A chunk with no enriched facts
396
  is never dropped here (it just won't get a fit boost in ranking).
@@ -402,6 +730,10 @@ def apply_eligibility_filter(chunks: Iterable[Any], profile: Any) -> list[Any]:
402
  has_base = _user_has_base_cover(profile)
403
  wants_zero_copay = _user_wants_zero_copay(profile)
404
  desired_si = _as_int(_profile_get(profile, "desired_sum_insured_inr"))
 
 
 
 
405
 
406
  kept: list[Any] = []
407
  for ch in chunks_list:
@@ -415,6 +747,25 @@ def apply_eligibility_filter(chunks: Iterable[Any], profile: Any) -> list[Any]:
415
  if not has_base and _is_top_up(m):
416
  continue
417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  # Rule 2 β€” SI floor
419
  if desired_si:
420
  max_si = _max_sum_insured(m)
@@ -442,20 +793,35 @@ _GRADE_POINTS = {"A": 100.0, "B": 70.0, "C": 45.0, "D": 25.0, "F": 5.0}
442
 
443
 
444
  def _fit_score(chunk_meta: dict, profile: Any, wants_zero_copay: bool,
445
- desired_si: Optional[int]) -> float:
 
 
446
  """Composite profile-fit score (higher = better). Blends raw cosine
447
  (so genuinely-relevant chunks still matter) with structural fit:
448
  β€’ scorecard grade / overall (when enriched)
449
  β€’ co-pay penalty (steep when the user wants zero co-pay)
450
  β€’ SI headroom (a plan that comfortably offers the requested SI beats
451
  one that barely scrapes it)
 
 
 
 
 
 
 
 
452
  """
453
  try:
454
  cosine = float(chunk_meta.get("score") or 0.0)
455
  except (TypeError, ValueError):
456
  cosine = 0.0
457
  # Cosine is ~[0,1]; scale so it contributes but never dominates fit.
458
- score = cosine * 30.0
 
 
 
 
 
459
 
460
  # Grade / overall scorecard signal (enriched by brain_tools).
461
  grade = str(chunk_meta.get("_grade") or "").strip().upper()
@@ -465,10 +831,18 @@ def _fit_score(chunk_meta: dict, profile: Any, wants_zero_copay: bool,
465
  elif grade in _GRADE_POINTS:
466
  score += _GRADE_POINTS[grade]
467
 
468
- # Co-pay penalty.
 
 
 
 
 
469
  copay = _as_int(chunk_meta.get("co_payment_pct"))
470
  if copay is not None and copay > 0:
471
- penalty = copay * (3.0 if wants_zero_copay else 1.0)
 
 
 
472
  score -= penalty
473
 
474
  # SI headroom bonus β€” reward a plan that offers >= the requested SI.
@@ -480,6 +854,41 @@ def _fit_score(chunk_meta: dict, profile: Any, wants_zero_copay: bool,
480
  else:
481
  score -= 25.0 # shouldn't survive eligibility, belt-and-braces
482
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
483
  return score
484
 
485
 
@@ -497,6 +906,8 @@ def rank_by_profile_fit(chunks: Iterable[Any], profile: Any) -> list[Any]:
497
 
498
  wants_zero_copay = _user_wants_zero_copay(profile)
499
  desired_si = _as_int(_profile_get(profile, "desired_sum_insured_inr"))
 
 
500
 
501
  non_policy: list[Any] = []
502
  policy: list[Any] = []
@@ -506,7 +917,15 @@ def rank_by_profile_fit(chunks: Iterable[Any], profile: Any) -> list[Any]:
506
 
507
  # Decorate-sort-undecorate with original index as the stable tiebreaker.
508
  decorated = [
509
- (-_fit_score(_meta_full(ch), profile, wants_zero_copay, desired_si), i, ch)
 
 
 
 
 
 
 
 
510
  for i, ch in enumerate(policy)
511
  ]
512
  decorated.sort(key=lambda t: (t[0], t[1]))
@@ -646,14 +1065,26 @@ def enforce_citation_grounding(chunks: Iterable[Any]) -> list[Any]:
646
  # ---------------------------------------------------------------------------
647
 
648
  def dedup_by_policy(chunks: Iterable[Any]) -> list[Any]:
649
- """Within top-K results, collapse to one chunk per policy_id, keeping
650
- the highest-scoring chunk. Preserves the original ordering of the kept
651
- chunks (i.e. ranks chunks by their best-in-policy score)."""
 
 
 
 
 
 
 
 
 
 
 
 
652
  best: dict[str, Any] = {}
653
  order: list[str] = []
654
  for ch in chunks:
655
- m = _meta(ch)
656
- pid = m.get("policy_id") or ""
657
  score = m.get("score")
658
  if score is None:
659
  # try attribute path
@@ -663,15 +1094,15 @@ def dedup_by_policy(chunks: Iterable[Any]) -> list[Any]:
663
  except (TypeError, ValueError):
664
  score_f = 0.0
665
 
666
- if pid not in best:
667
- best[pid] = (ch, score_f)
668
- order.append(pid)
669
  continue
670
- prev_chunk, prev_score = best[pid]
671
  if score_f > prev_score:
672
- best[pid] = (ch, score_f)
673
 
674
- return [best[pid][0] for pid in order]
675
 
676
 
677
  # ---------------------------------------------------------------------------
@@ -689,10 +1120,14 @@ def filter_pipeline(
689
  1. Citation grounding (reject malformed chunks)
690
  2. Profile pre-filter (drop demographically inappropriate policies)
691
  3. Eligibility filter (KI-278 β€” drop structural mismatches:
692
- top-up w/o base cover, SI floor, co-pay)
 
 
693
  4. Exact-match bypass (if query has a UIN / quoted name, swap in)
694
  5. Dedup by policy_id
695
- 6. Profile-fit ranking (KI-278 β€” promote best-fit over raw cosine)
 
 
696
  7. Empty-retrieval guard
697
 
698
  Returns (filtered_chunks, guard_signal_or_None). When guard_signal is
 
9
  Drop chunks for policies the user is demographically ineligible for.
10
  apply_eligibility_filter(chunks, profile) -> list[RetrievedChunk]
11
  Drop chunks the user is STRUCTURALLY ineligible for / that clearly
12
+ contradict an explicit stated need (KI-278 / KI-279):
13
  - top-up / super-top-up when the user has no existing base cover
14
  - plans whose max sum-insured cannot meet the requested SI
15
  - high co-pay plans when the user explicitly wants zero co-pay
16
+ - fixed-benefit products (hospital daily cash / personal accident /
17
+ critical illness / cancer) when the profile clearly signals the
18
+ user wants comprehensive INDEMNITY cover (KI-279)
19
  rank_by_profile_fit(chunks, profile) -> list[RetrievedChunk]
20
  Re-order surviving chunks so the plans that best match the stated
21
  needs (grade, co-pay, SI headroom) rank above weak-fit plans whose
 
41
  import re
42
  from typing import Any, Iterable, Optional
43
 
44
+ # KI-280 (2026-05-16) β€” shared canonical-identity / dedup rule. The same
45
+ # UIN-primary + product_key invariant the marketplace endpoint uses
46
+ # (main.py /api/policies/all). Imported (not reimplemented) so the
47
+ # recommender and the marketplace agree on "the same policy". The module
48
+ # is dependency-free so this stays import-cycle-safe.
49
+ from backend.policy_identity import canonical_key
50
+
51
  # We avoid importing RetrievedChunk at module-import time to keep this file
52
  # import-cycle-safe. Instead we type-duck on attributes.
53
 
 
147
  flags=re.IGNORECASE,
148
  )
149
 
150
+ # ---------------------------------------------------------------------------
151
+ # KI-279 β€” fixed-benefit exclusion for comprehensive-indemnity intent
152
+ # (2026-05-16)
153
+ # ---------------------------------------------------------------------------
154
+ # A FIXED-BENEFIT product (hospital daily cash, personal accident, critical
155
+ # illness, cancer / other defined-benefit) pays a fixed lump-sum / per-day
156
+ # amount rather than reimbursing actual hospitalisation expenses. It is a
157
+ # legitimate SUPPLEMENT but a wrong PRIMARY recommendation for a buyer who
158
+ # clearly wants comprehensive INDEMNITY cover (their first health policy,
159
+ # a desired sum insured, no existing base cover). This regex mirrors
160
+ # scorecard._FIXED_BENEFIT_RE so classification stays consistent across the
161
+ # scorecard and the retrieval filter (single behavioural contract).
162
+ FIXED_BENEFIT_NAME_RE = re.compile(
163
+ r"hospital[\s_-]*cash|hospi[\s_-]*cash|daily[\s_-]*cash|"
164
+ r"personal[\s_-]*accident|critical[\s_-]*illness|"
165
+ r"criti[\s_-]*(?:care|medicare)|\bcancer\b|wellsurance|hospi[\s_-]*care",
166
+ flags=re.IGNORECASE,
167
+ )
168
+
169
+ # Tokens in policy_type / policy_type_indemnity_or_fixed that mark a
170
+ # fixed-benefit / defined-benefit product (NOT indemnity reimbursement).
171
+ _FIXED_BENEFIT_TYPE_TOKENS = (
172
+ "fixed", "benefit", "defined",
173
+ "hospital_cash", "hospital cash", "daily_cash", "daily cash",
174
+ "personal_accident", "personal accident",
175
+ "critical_illness", "critical illness", "cancer",
176
+ )
177
+
178
+ # Goal phrases that mean the user EXPLICITLY wants a supplement / add-on /
179
+ # top-up / fixed-benefit product β€” the comprehensive-indemnity intent must
180
+ # NOT fire for these (we must keep showing them PA / CI / hospital-cash /
181
+ # top-up products on purpose).
182
+ _SUPPLEMENT_GOAL_TOKENS = (
183
+ "supplement", "add-on", "add on", "addon", "rider",
184
+ "top-up", "top up", "topup", "super top",
185
+ "critical illness", "critical-illness", "ci only", "ci cover",
186
+ "personal accident", "accident cover", "accident plan",
187
+ "hospital cash", "daily cash", "cash plan", "cancer cover",
188
+ "cancer plan", "defined benefit", "fixed benefit",
189
+ "alongside", "in addition to", "on top of",
190
+ )
191
+
192
+ # Goal phrases that POSITIVELY signal a primary comprehensive health plan.
193
+ _COMPREHENSIVE_GOAL_TOKENS = (
194
+ "first", "new policy", "fresh", "primary", "comprehensive",
195
+ "general health", "health cover", "main cover", "base cover",
196
+ "family floater", "indemnity", "hospitalisation", "hospitalization",
197
+ "cover my", "protect my family", "medical cover", "buy health",
198
+ )
199
+
200
+ # ---------------------------------------------------------------------------
201
+ # KI-280 β€” UNIFIED recommendation-fit gate tunables (2026-05-16)
202
+ # ---------------------------------------------------------------------------
203
+ # The audit proved recommendation-fit is SYSTEMIC: the cited-card list and
204
+ # the advisory prose must be gated by the SAME fitness logic. These add the
205
+ # two missing hard gates (entry-age for the INSURED person; required
206
+ # feature = maternity/newborn) and the ranking signals that fix the
207
+ # grade/rank inversion + the cost-objective lead.
208
+
209
+ # Entry-age grace. The catalog's max_entry_age is the regulator-filed entry
210
+ # age; underwriters allow a small grace band (mirrors PROFILE_AGE_TOLERANCE).
211
+ ENTRY_AGE_TOLERANCE = 2
212
+
213
+ # Goal phrases that mean COST is the dominant objective (P5). When present,
214
+ # ranking must not let a pricier plan win purely on cosine β€” the lowest-cost
215
+ # *appropriate* plan leads. We proxy "cost" by (low/zero co-pay surcharge +
216
+ # scorecard Cost Predictability already folded into _overall_score); the
217
+ # explicit signal here flips a stronger cosine-discount so a cheap plan is
218
+ # not buried under a higher-cosine pricier one.
219
+ _COST_OBJECTIVE_TOKENS = (
220
+ "cost_optimize", "cheapest", "cheap", "lowest premium", "low premium",
221
+ "budget", "affordable", "tight", "money is tight", "save money",
222
+ "least expensive", "minimum premium", "low cost",
223
+ )
224
+
225
+ # Profile/goal phrases that say the policy INSURES senior parents (so the
226
+ # entry-age gate must use the PARENTS' age, not the paying child's age).
227
+ _PARENTS_COVER_TOKENS = (
228
+ "parent", "parents", "mother", "father", "mom", "dad",
229
+ "senior citizen", "senior citizens", "elderly",
230
+ )
231
+
232
+ # Explicit maternity / newborn requirement phrases. When the profile states
233
+ # this need, plans whose facts CONFIRM maternity/newborn rank above those
234
+ # that do not (and unverified ones are ranked strictly below confirmed).
235
+ _MATERNITY_NEED_TOKENS = (
236
+ "maternity", "pregnan", "newborn", "new born", "new-born",
237
+ "delivery cover", "childbirth", "planning a child", "planning another",
238
+ "expecting", "baby cover", "having a baby",
239
+ )
240
+
241
 
242
  # ---------------------------------------------------------------------------
243
  # Helpers
 
276
  for k in (
277
  "policy_type_indemnity_or_fixed", "deductible_amount",
278
  "co_payment_pct", "sum_insured_options", "_grade", "_overall_score",
279
+ # KI-280 β€” unified-gate signals (entry-age / required-feature /
280
+ # canonical dedup identity).
281
+ "uin_code", "max_entry_age", "min_entry_age",
282
+ "maternity_coverage", "newborn_coverage", "policy_type",
283
  ):
284
  if hasattr(chunk, k):
285
  out[k] = getattr(chunk, k)
 
346
  if not chunks_list:
347
  return chunks_list
348
 
349
+ # KI-280 β€” the demographic gates (numeric age-range, senior-only,
350
+ # adult-only) must reason about the age of the person the policy
351
+ # actually INSURES, not the payer's. When the policy covers parents
352
+ # (~70), using the paying child's age (e.g. 36) made the senior-only
353
+ # rule wrongly DROP a senior-citizen plan ("min_entry_age>=60 AND
354
+ # payer<50") and the numeric range wrongly KEEP a max-entry-65 plan β€”
355
+ # the exact P7 live-audit failure. `_oldest_insured_age` returns the
356
+ # eldest parent's age when insuring parents, else the profile's own
357
+ # age. Falls back to the raw profile age if no resolved signal.
358
+ _resolved_age = _oldest_insured_age(profile)
359
+ if _resolved_age is None:
360
+ _resolved_age = _profile_get(profile, "age")
361
+ age = _resolved_age
362
  # If age unknown, only the maternity rule can fire β€” keep everything else.
363
  has_age = isinstance(age, int)
364
 
 
488
  return copay is not None and copay <= ZERO_COPAY_USER_MAX_COPAY_PCT
489
 
490
 
491
+ # ---------------------------------------------------------------------------
492
+ # KI-279 β€” fixed-benefit classification + comprehensive-indemnity intent
493
+ # ---------------------------------------------------------------------------
494
+
495
+ def _is_fixed_benefit_chunk(chunk_meta: dict) -> bool:
496
+ """True when the policy is a FIXED-BENEFIT / defined-benefit product
497
+ (hospital daily cash, personal accident, critical illness, cancer)
498
+ rather than an indemnity hospitalisation-reimbursement plan.
499
+
500
+ Detection mirrors scorecard._is_fixed_benefit so the scorecard and the
501
+ retrieval filter classify identically (one behavioural contract):
502
+
503
+ 1. The canonical type key `policy_type_indemnity_or_fixed` contains a
504
+ fixed / benefit / defined token.
505
+ 2. Fallback β€” the raw catalog key `policy_type` contains a
506
+ fixed-benefit token (hospital_cash / personal_accident / ...).
507
+ Critically, several curated files (e.g. Star Hospital Cash) carry
508
+ the type ONLY here.
509
+ 3. Last-resort β€” the policy_id / policy_name matches
510
+ FIXED_BENEFIT_NAME_RE (hospital cash / daily cash / PA / CI /
511
+ cancer / wellsurance).
512
+
513
+ Conservative: if NO type signal exists AND the name doesn't match, the
514
+ policy is treated as indemnity (not dropped).
515
+ """
516
+ # Canonical curated key first.
517
+ canon = str(chunk_meta.get("policy_type_indemnity_or_fixed") or "").lower()
518
+ if canon and any(tok in canon for tok in _FIXED_BENEFIT_TYPE_TOKENS):
519
+ return True
520
+ if canon and "indemnity" in canon:
521
+ return False # explicitly indemnity β€” never a false positive
522
+
523
+ # Raw catalog type key (the Star-Hospital-Cash case).
524
+ raw = str(chunk_meta.get("policy_type") or "").lower()
525
+ if raw and any(tok in raw for tok in _FIXED_BENEFIT_TYPE_TOKENS):
526
+ return True
527
+ if raw and "indemnity" in raw:
528
+ return False
529
+
530
+ # Name / id fallback.
531
+ blob = f"{chunk_meta.get('policy_id','')} {chunk_meta.get('policy_name','')}"
532
+ return bool(FIXED_BENEFIT_NAME_RE.search(blob))
533
+
534
+
535
+ def _user_explicitly_wants_supplement(profile: Any) -> bool:
536
+ """True only when primary_goal explicitly names a supplement / add-on /
537
+ top-up / PA / CI / hospital-cash / cancer / defined-benefit product.
538
+ Used to SUPPRESS the fixed-benefit ranking demotion (we must not bury a
539
+ product the user explicitly asked for)."""
540
+ goal = str(_profile_get(profile, "primary_goal") or "").lower().strip()
541
+ if not goal:
542
+ return False
543
+ return any(tok in goal for tok in _SUPPLEMENT_GOAL_TOKENS)
544
+
545
+
546
+ def _insures_parents(profile: Any) -> bool:
547
+ """True when the policy is being bought to cover the user's PARENTS /
548
+ seniors (so the entry-age gate must test the parents' age, not the
549
+ paying child's). Signals (any): parents_to_insure flag, a
550
+ parents_age_max value, dependents mentioning parents, or a
551
+ parents-cover / senior-citizen primary_goal."""
552
+ if _profile_get(profile, "parents_to_insure") is True:
553
+ return True
554
+ if _as_int(_profile_get(profile, "parents_age_max")) is not None:
555
+ return True
556
+ dep = str(_profile_get(profile, "dependents") or "").lower()
557
+ goal = str(_profile_get(profile, "primary_goal") or "").lower()
558
+ blob = f"{dep} {goal}"
559
+ return any(tok in blob for tok in _PARENTS_COVER_TOKENS)
560
+
561
+
562
+ def _oldest_insured_age(profile: Any) -> Optional[int]:
563
+ """The age of the OLDEST person the policy must accept at entry.
564
+
565
+ When the policy insures parents, that is `parents_age_max` (the eldest
566
+ parent). Otherwise it is the profile's own `age`. Returns None when no
567
+ usable age signal exists (the gate then stays conservative and does not
568
+ drop on missing data β€” same philosophy as apply_profile_filter).
569
+ """
570
+ if _insures_parents(profile):
571
+ pa = _as_int(_profile_get(profile, "parents_age_max"))
572
+ if pa is not None:
573
+ return pa
574
+ # Insures parents but their age unknown β€” fall through to own age
575
+ # only if it is itself senior; otherwise None (don't gate blind).
576
+ own = _as_int(_profile_get(profile, "age"))
577
+ return own if (own is not None and own >= 60) else None
578
+ return _as_int(_profile_get(profile, "age"))
579
+
580
+
581
+ def _profile_requires_maternity(profile: Any) -> bool:
582
+ """True when the profile EXPLICITLY needs maternity / newborn cover.
583
+ Checks primary_goal first (the strongest signal β€” single_brain folds
584
+ 'maternity' into the goal), then a dedicated maternity flag if present.
585
+ Conservative: only fires on an explicit token, never inferred from a
586
+ female adult alone (that would over-trigger and wrongly demote good
587
+ plans for users who never asked for maternity)."""
588
+ if _profile_has_maternity_goal(profile):
589
+ return True
590
+ goal = str(_profile_get(profile, "primary_goal") or "").lower()
591
+ if any(tok in goal for tok in _MATERNITY_NEED_TOKENS):
592
+ return True
593
+ # A dedicated boolean slot, if a future Profile grows one.
594
+ for key in ("needs_maternity", "maternity_required", "wants_maternity"):
595
+ if _profile_get(profile, key) is True:
596
+ return True
597
+ return False
598
+
599
+
600
+ def _cost_is_primary_objective(profile: Any) -> bool:
601
+ """True when the user's stated objective is dominated by cost (P5 β€”
602
+ 'cheapest decent cover, lowest premium is my top priority')."""
603
+ goal = str(_profile_get(profile, "primary_goal") or "").lower()
604
+ band = str(_profile_get(profile, "budget_band") or "").lower()
605
+ blob = f"{goal} {band}"
606
+ return any(tok in blob for tok in _COST_OBJECTIVE_TOKENS)
607
+
608
+
609
+ def _chunk_confirms_maternity(chunk_meta: dict) -> Optional[bool]:
610
+ """Tri-state: True (facts confirm maternity OR newborn cover), False
611
+ (facts explicitly say neither), None (unverified β€” no fact present).
612
+ None must rank BELOW True but is NOT hard-dropped (the curated facts
613
+ are incomplete; a hard drop would wrongly hide good plans whose
614
+ maternity flag simply wasn't curated yet)."""
615
+ mat = chunk_meta.get("maternity_coverage")
616
+ nb = chunk_meta.get("newborn_coverage")
617
+
618
+ def _tri(v):
619
+ if isinstance(v, bool):
620
+ return v
621
+ if isinstance(v, str):
622
+ s = v.strip().lower()
623
+ if s in ("true", "yes", "y", "covered"):
624
+ return True
625
+ if s in ("false", "no", "n", "not covered", "excluded"):
626
+ return False
627
+ if isinstance(v, dict) and "covered" in v:
628
+ return bool(v.get("covered"))
629
+ return None
630
+
631
+ tm, tn = _tri(mat), _tri(nb)
632
+ if tm is True or tn is True:
633
+ return True
634
+ if tm is False or tn is False:
635
+ return False
636
+ return None
637
+
638
+
639
+ def _wants_comprehensive_indemnity(profile: Any) -> bool:
640
+ """Conservatively detect that the user wants a PRIMARY COMPREHENSIVE
641
+ INDEMNITY health plan (so a fixed-benefit daily-cash / PA / CI product
642
+ is the wrong top pick).
643
+
644
+ Fires ONLY when the signal is clear and NO explicit supplement signal
645
+ is present:
646
+
647
+ β€’ NOT an explicit supplement / add-on / top-up / PA / CI / cancer /
648
+ hospital-cash goal (hard veto β€” these users WANT fixed-benefit).
649
+ β€’ The user has NO existing base cover (first-time buyer).
650
+ β€’ AND at least one strong positive signal:
651
+ - primary_goal reads as a first / primary / comprehensive
652
+ health-cover goal, OR
653
+ - a desired_sum_insured_inr is present (you only state a target
654
+ cover amount when you want a real indemnity plan).
655
+
656
+ Returns False on ambiguity (better to keep a fixed-benefit chunk and
657
+ let ranking demote it than to wrongly hard-drop for an unclear case).
658
+ """
659
+ goal = str(_profile_get(profile, "primary_goal") or "").lower().strip()
660
+
661
+ # Hard veto β€” the user explicitly asked for a supplement / fixed-benefit
662
+ # style product. Never hide those from them.
663
+ if goal and any(tok in goal for tok in _SUPPLEMENT_GOAL_TOKENS):
664
+ return False
665
+
666
+ # A user who already holds base cover is plausibly shopping for a
667
+ # supplement; don't aggressively hard-drop fixed-benefit for them.
668
+ if _user_has_base_cover(profile):
669
+ return False
670
+
671
+ desired_si = _as_int(_profile_get(profile, "desired_sum_insured_inr"))
672
+ has_desired_si = desired_si is not None and desired_si > 0
673
+
674
+ goal_is_comprehensive = bool(goal) and any(
675
+ tok in goal for tok in _COMPREHENSIVE_GOAL_TOKENS
676
+ )
677
+
678
+ # Clear signal = (first/primary/comprehensive goal) OR (a desired SI was
679
+ # stated). Either alone, combined with "no base cover" and "no
680
+ # supplement veto", is a confident comprehensive-indemnity intent.
681
+ return goal_is_comprehensive or has_desired_si
682
+
683
+
684
  def apply_eligibility_filter(chunks: Iterable[Any], profile: Any) -> list[Any]:
685
  """Drop chunks the user is STRUCTURALLY ineligible for, or that plainly
686
  contradict an explicit stated need (KI-278).
 
701
  ZERO_COPAY_USER_MAX_COPAY_PCT. Regardless of stated preference,
702
  drop plans with a punitive co-pay (>= PUNITIVE_COPAY_PCT).
703
 
704
+ 4. FIXED-BENEFIT GATE (KI-279) β€” when the profile clearly signals the
705
+ user wants a PRIMARY COMPREHENSIVE INDEMNITY health plan (first
706
+ policy / general-cover goal + a desired SI + no existing base
707
+ cover, and NO explicit supplement / PA / CI / hospital-cash /
708
+ top-up goal), drop fixed-benefit products (hospital daily cash,
709
+ personal accident, critical illness, cancer / defined-benefit).
710
+ These pay a fixed per-day / lump-sum amount, not actual medical
711
+ expenses, so they are a wrong PRIMARY recommendation. They are
712
+ NEVER dropped for a user who explicitly wants a supplement.
713
+
714
+ 5. ENTRY-AGE GATE (KI-280) β€” drop a plan whose max entry age cannot
715
+ accept the OLDEST person the policy must insure. When the profile
716
+ covers parents (~70), the gate uses the parents' age, not the
717
+ paying child's β€” the demographic pre-filter only sees the payer's
718
+ age, which is exactly why a max-entry-65 plan reached a 70yo-
719
+ parents profile in the live audit (P7). Conservative: fires only
720
+ when both the insured age AND the policy fact are present.
721
+
722
  Conservative on missing data: a rule only fires when BOTH the profile
723
  signal AND the policy fact are present. A chunk with no enriched facts
724
  is never dropped here (it just won't get a fit boost in ranking).
 
730
  has_base = _user_has_base_cover(profile)
731
  wants_zero_copay = _user_wants_zero_copay(profile)
732
  desired_si = _as_int(_profile_get(profile, "desired_sum_insured_inr"))
733
+ wants_comprehensive = _wants_comprehensive_indemnity(profile)
734
+ # KI-280 β€” the age of the OLDEST person the plan must accept at entry
735
+ # (parents' age when insuring parents, else the user's own age).
736
+ oldest_age = _oldest_insured_age(profile)
737
 
738
  kept: list[Any] = []
739
  for ch in chunks_list:
 
747
  if not has_base and _is_top_up(m):
748
  continue
749
 
750
+ # Rule 4 (KI-279) β€” fixed-benefit is a wrong PRIMARY pick when the
751
+ # user clearly wants comprehensive indemnity cover. Hard-drop only
752
+ # for that intent; supplement/PA/CI seekers keep seeing them.
753
+ if wants_comprehensive and _is_fixed_benefit_chunk(m):
754
+ continue
755
+
756
+ # Rule 5 (KI-280) β€” HARD ELIGIBILITY: a plan whose max entry age
757
+ # cannot accept the oldest insured person is structurally unusable.
758
+ # This is the audit-P7 fix: a 70yo parent cannot be enrolled in a
759
+ # plan whose max_entry_age is 65. We only fire when BOTH the age and
760
+ # the policy fact are present (conservative on missing data) and
761
+ # only when the profile actually insures someone whose age we know
762
+ # (the demographic apply_profile_filter uses the *payer's* age and
763
+ # never sees the parents' age β€” that is precisely why P7 slipped).
764
+ if oldest_age is not None:
765
+ maxe = _as_int(m.get("max_entry_age"))
766
+ if maxe is not None and maxe + ENTRY_AGE_TOLERANCE < oldest_age:
767
+ continue
768
+
769
  # Rule 2 β€” SI floor
770
  if desired_si:
771
  max_si = _max_sum_insured(m)
 
793
 
794
 
795
  def _fit_score(chunk_meta: dict, profile: Any, wants_zero_copay: bool,
796
+ desired_si: Optional[int], *,
797
+ requires_maternity: bool = False,
798
+ cost_objective: bool = False) -> float:
799
  """Composite profile-fit score (higher = better). Blends raw cosine
800
  (so genuinely-relevant chunks still matter) with structural fit:
801
  β€’ scorecard grade / overall (when enriched)
802
  β€’ co-pay penalty (steep when the user wants zero co-pay)
803
  β€’ SI headroom (a plan that comfortably offers the requested SI beats
804
  one that barely scrapes it)
805
+ β€’ KI-280 required-feature term: when the profile explicitly needs
806
+ maternity/newborn, a plan whose facts CONFIRM it ranks above one
807
+ that does not, and an UNVERIFIED plan ranks strictly below a
808
+ confirmed one (but is not hard-dropped β€” curated facts are
809
+ incomplete).
810
+ β€’ KI-280 cost-objective term: when cost is the dominant stated
811
+ objective, shrink cosine's pull so a pricier plan can't win purely
812
+ on vector similarity over a cheaper appropriate plan.
813
  """
814
  try:
815
  cosine = float(chunk_meta.get("score") or 0.0)
816
  except (TypeError, ValueError):
817
  cosine = 0.0
818
  # Cosine is ~[0,1]; scale so it contributes but never dominates fit.
819
+ # KI-280: when COST is the primary objective (P5), damp cosine hard so
820
+ # a higher-cosine pricier plan does not out-rank a cheaper appropriate
821
+ # one. The scorecard's Cost Predictability is already inside
822
+ # _overall_score; this just stops raw similarity from overriding it.
823
+ cosine_weight = 6.0 if cost_objective else 30.0
824
+ score = cosine * cosine_weight
825
 
826
  # Grade / overall scorecard signal (enriched by brain_tools).
827
  grade = str(chunk_meta.get("_grade") or "").strip().upper()
 
831
  elif grade in _GRADE_POINTS:
832
  score += _GRADE_POINTS[grade]
833
 
834
+ # Co-pay penalty. KI-280: for a COST-primary objective where the user
835
+ # explicitly tolerates a co-pay (P5 β€” "co-pay is completely fine if it
836
+ # lowers premium"), a co-pay is a PREMIUM-REDUCING feature for this
837
+ # buyer, not a defect β€” suppress the penalty so the cost-appropriate
838
+ # plan is not wrongly demoted below a pricier zero-copay plan. The
839
+ # zero-copay-user penalty path is untouched (P1 still drops high-copay).
840
  copay = _as_int(chunk_meta.get("co_payment_pct"))
841
  if copay is not None and copay > 0:
842
+ if cost_objective and not wants_zero_copay:
843
+ penalty = 0.0
844
+ else:
845
+ penalty = copay * (3.0 if wants_zero_copay else 1.0)
846
  score -= penalty
847
 
848
  # SI headroom bonus β€” reward a plan that offers >= the requested SI.
 
854
  else:
855
  score -= 25.0 # shouldn't survive eligibility, belt-and-braces
856
 
857
+ # KI-280 β€” REQUIRED-FEATURE term. When the profile explicitly needs
858
+ # maternity / newborn cover (P3), a plan whose curated facts CONFIRM it
859
+ # must outrank one that does not, and an UNVERIFIED plan (fact absent)
860
+ # ranks strictly below a confirmed one. We do NOT hard-drop unverified
861
+ # plans β€” the curated facts are incomplete and a hard drop would wrongly
862
+ # hide good plans whose maternity flag simply wasn't curated. The
863
+ # magnitudes are chosen so a confirmed plan clears a one-letter-grade
864
+ # gap (β‰ˆ +25 confirmed vs βˆ’40 explicitly-absent) β€” enough to put a
865
+ # maternity C-grade plan above a non-maternity B-grade plan when
866
+ # maternity is a stated hard requirement, without disturbing ordering
867
+ # for profiles that did not ask for maternity (term is inert then).
868
+ if requires_maternity:
869
+ conf = _chunk_confirms_maternity(chunk_meta)
870
+ if conf is True:
871
+ score += 25.0
872
+ elif conf is False:
873
+ score -= 40.0 # facts say NO maternity β€” wrong for this need
874
+ else:
875
+ score -= 12.0 # unverified β€” rank below any confirmed plan
876
+
877
+ # KI-279 β€” fixed-benefit demotion. The eligibility filter already
878
+ # hard-drops fixed-benefit for a strong comprehensive-indemnity intent;
879
+ # this penalty is the belt-and-braces for weaker signals where the
880
+ # intent did NOT fire (so a fixed-benefit chunk survived) but the user
881
+ # still has no explicit supplement goal and an indemnity plan is also
882
+ # present β€” the indemnity plan must still lead. Suppressed only when
883
+ # the user explicitly wants a supplement / PA / CI / hospital-cash
884
+ # product (then fixed-benefit is exactly what they asked for). Penalty
885
+ # is large enough to sink it below any comparable indemnity plan
886
+ # without affecting indemnity-vs-indemnity ordering.
887
+ if not _user_explicitly_wants_supplement(profile) and _is_fixed_benefit_chunk(
888
+ chunk_meta
889
+ ):
890
+ score -= 120.0
891
+
892
  return score
893
 
894
 
 
906
 
907
  wants_zero_copay = _user_wants_zero_copay(profile)
908
  desired_si = _as_int(_profile_get(profile, "desired_sum_insured_inr"))
909
+ requires_maternity = _profile_requires_maternity(profile)
910
+ cost_objective = _cost_is_primary_objective(profile)
911
 
912
  non_policy: list[Any] = []
913
  policy: list[Any] = []
 
917
 
918
  # Decorate-sort-undecorate with original index as the stable tiebreaker.
919
  decorated = [
920
+ (
921
+ -_fit_score(
922
+ _meta_full(ch), profile, wants_zero_copay, desired_si,
923
+ requires_maternity=requires_maternity,
924
+ cost_objective=cost_objective,
925
+ ),
926
+ i,
927
+ ch,
928
+ )
929
  for i, ch in enumerate(policy)
930
  ]
931
  decorated.sort(key=lambda t: (t[0], t[1]))
 
1065
  # ---------------------------------------------------------------------------
1066
 
1067
  def dedup_by_policy(chunks: Iterable[Any]) -> list[Any]:
1068
+ """Within top-K results, collapse same-product / marketing-variant
1069
+ duplicates to one chunk, keeping the highest-scoring chunk. Preserves
1070
+ the order of first appearance of each kept product.
1071
+
1072
+ KI-280: keying is by the SHARED canonical identity
1073
+ (policy_identity.canonical_key) β€” UIN-primary, product_key fallback β€”
1074
+ NOT the raw policy_id. The live audit cited the SAME product twice
1075
+ because the two chunks had different policy_ids: a marketing rename
1076
+ ("my:Optima Secure" vs "my:Optima Secure (older variant)" β€” same UIN)
1077
+ or two doctype siblings ("...__wordings" vs "...__brochure" β€” same
1078
+ product_key). policy_id-only dedup let both through (P2 New National
1079
+ Parivar Γ—2, P4 Advanced Top Up Γ—2, P7 Chola Γ—2). This reuses the exact
1080
+ rule the marketplace endpoint uses so the recommender and the
1081
+ marketplace agree on "the same policy".
1082
+ """
1083
  best: dict[str, Any] = {}
1084
  order: list[str] = []
1085
  for ch in chunks:
1086
+ m = _meta_full(ch)
1087
+ key = canonical_key(m)
1088
  score = m.get("score")
1089
  if score is None:
1090
  # try attribute path
 
1094
  except (TypeError, ValueError):
1095
  score_f = 0.0
1096
 
1097
+ if key not in best:
1098
+ best[key] = (ch, score_f)
1099
+ order.append(key)
1100
  continue
1101
+ prev_chunk, prev_score = best[key]
1102
  if score_f > prev_score:
1103
+ best[key] = (ch, score_f)
1104
 
1105
+ return [best[key][0] for key in order]
1106
 
1107
 
1108
  # ---------------------------------------------------------------------------
 
1120
  1. Citation grounding (reject malformed chunks)
1121
  2. Profile pre-filter (drop demographically inappropriate policies)
1122
  3. Eligibility filter (KI-278 β€” drop structural mismatches:
1123
+ top-up w/o base cover, SI floor, co-pay;
1124
+ KI-279 β€” drop fixed-benefit products when
1125
+ the user wants comprehensive indemnity)
1126
  4. Exact-match bypass (if query has a UIN / quoted name, swap in)
1127
  5. Dedup by policy_id
1128
+ 6. Profile-fit ranking (KI-278 β€” promote best-fit over raw cosine;
1129
+ KI-279 β€” demote any surviving fixed-benefit
1130
+ below indemnity options)
1131
  7. Empty-retrieval guard
1132
 
1133
  Returns (filtered_chunks, guard_signal_or_None). When guard_signal is
backend/session_state.py CHANGED
@@ -135,19 +135,42 @@ def get_session(session_id: str) -> SessionState:
135
  return _sessions[session_id]
136
 
137
 
138
- def rehydrate_by_name(session: SessionState, name: str) -> bool:
139
- """KI-118 (2026-05-15) β€” cross-session re-entry point.
 
 
 
 
 
140
 
141
- When a user provides their name (captured in the fact_find brain), look
142
- up the named profile via `backend.profile_store.load_profile(name)` and
143
- populate the in-memory session with the stored profile data.
144
 
145
- Returns True if a stored profile was found and merged; False otherwise.
146
- Failures are logged but never raise β€” a fresh chat must always proceed.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
- Merge semantics: stored fields override current session-state fields IF
149
- the current field is empty. Already-captured fields on the live session
150
- win (the user may have corrected themselves mid-conversation).
151
  """
152
  if not name or not name.strip():
153
  return False
@@ -156,18 +179,33 @@ def rehydrate_by_name(session: SessionState, name: str) -> bool:
156
  stored = load_profile(name)
157
  if stored is None:
158
  return False
159
- # Merge: stored value fills any empty slot on the live profile.
 
 
 
 
 
 
 
 
 
 
 
 
160
  for fld in Profile.__dataclass_fields__.keys():
161
- try:
162
- cur = getattr(session.profile, fld, None)
163
- if cur in (None, "", []):
164
- new = getattr(stored, fld, None)
165
- if new not in (None, "", []):
166
- setattr(session.profile, fld, new)
167
- except Exception:
168
- continue
 
 
169
  session.last_touched = time.time()
170
- return True
 
171
  except Exception as e:
172
  _log.warning(
173
  "rehydrate_by_name failed (name=%r): %s: %s",
@@ -176,6 +214,46 @@ def rehydrate_by_name(session: SessionState, name: str) -> bool:
176
  return False
177
 
178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  def set_free_form(session_id: str, free_form: bool = True) -> None:
180
  s = get_session(session_id)
181
  s.free_form_session = free_form
 
135
  return _sessions[session_id]
136
 
137
 
138
+ # Identity-summary fields surfaced in the "are you <name>?" confirm prompt.
139
+ # Enough to let the real owner recognise their own profile, but it is NOT
140
+ # applied to the live session until the user explicitly confirms.
141
+ _RECALL_SUMMARY_FIELDS: tuple[str, ...] = (
142
+ "age", "dependents", "income_band", "location_tier",
143
+ "primary_goal", "parents_age_max",
144
+ )
145
 
 
 
 
146
 
147
+ def rehydrate_by_name(session: SessionState, name: str) -> bool:
148
+ """Cross-session re-entry point β€” STAGE a name match for confirmation.
149
+
150
+ PRIVACY FIX (2026-05-16, audit). Previously this AUTO-MERGED the stored
151
+ named profile into the live session on the very first turn. Because the
152
+ lookup key was the user-stated NAME (not the session / no cookie), a
153
+ second real user on a shared browser/IP β€” or anyone who simply states a
154
+ common first name β€” was silently served a stranger's captured profile
155
+ and greeted "Welcome back, <name>!". A fresh, no-cookie session must
156
+ NEVER inherit another session's profile from a weak/shared key.
157
+
158
+ Safe design (KI-196 / ADR-041, specced via `pending_profile_recall` but
159
+ previously never wired): a name match is STAGED on
160
+ `session.pending_profile_recall`, NOT merged. `session.profile` is left
161
+ untouched, so `is_returning_user` / RULE-4 "Welcome back" does NOT fire
162
+ on a fresh session. The brain asks the user to confirm ("are you
163
+ <name>?"); only an explicit affirmation calls `apply_pending_recall(
164
+ session, confirmed=True)` to merge the stored fields. An explicit deny
165
+ discards the staged profile.
166
+
167
+ Returns:
168
+ False β€” always. The stored profile is NEVER auto-applied here, so
169
+ callers must treat False as "do not flag a returning user
170
+ / do not greet Welcome back". Whether a match was *staged*
171
+ is observable via `session.pending_profile_recall`.
172
 
173
+ Failures are logged but never raise β€” a fresh chat must always proceed.
 
 
174
  """
175
  if not name or not name.strip():
176
  return False
 
179
  stored = load_profile(name)
180
  if stored is None:
181
  return False
182
+
183
+ # Build a non-PII-leaking identity summary so the brain can ask
184
+ # "are you <name>?" without putting anything on the live profile.
185
+ summary: Dict[str, Any] = {}
186
+ for fld in _RECALL_SUMMARY_FIELDS:
187
+ v = getattr(stored, fld, None)
188
+ if v not in (None, "", []):
189
+ summary[fld] = v
190
+
191
+ # Snapshot the full stored union so apply_pending_recall can merge
192
+ # WITHOUT a second disk read (and without the staged copy being
193
+ # mutated by anything between stage and confirm).
194
+ staged_fields: Dict[str, Any] = {}
195
  for fld in Profile.__dataclass_fields__.keys():
196
+ v = getattr(stored, fld, None)
197
+ if v not in (None, "", []):
198
+ staged_fields[fld] = v
199
+
200
+ session.pending_profile_recall = {
201
+ "name": (getattr(stored, "name", None) or name).strip(),
202
+ "summary": summary,
203
+ "stored_fields": staged_fields,
204
+ "staged_at": time.time(),
205
+ }
206
  session.last_touched = time.time()
207
+ # Deliberately False: nothing merged, no Welcome-back greeting.
208
+ return False
209
  except Exception as e:
210
  _log.warning(
211
  "rehydrate_by_name failed (name=%r): %s: %s",
 
214
  return False
215
 
216
 
217
+ def apply_pending_recall(session: SessionState, *, confirmed: bool) -> bool:
218
+ """Resolve a staged cross-session profile recall.
219
+
220
+ PRIVACY FIX (2026-05-16). The ONLY path that merges a stored, name-keyed
221
+ profile into a live session. Called after the user explicitly answers
222
+ the "are you <name>?" confirm prompt.
223
+
224
+ confirmed=True β€” the user affirmed it's them. Stored fields fill any
225
+ EMPTY slot on the live profile (already-captured slots
226
+ from THIS conversation win β€” the user may have given
227
+ fresher facts). Returns True iff a profile was applied.
228
+ confirmed=False β€” the user denied / it isn't them. The staged recall is
229
+ discarded. The live session stays blank. Returns False.
230
+
231
+ Idempotent: clears `pending_profile_recall` either way. A no-op (returns
232
+ False) when there is nothing staged.
233
+ """
234
+ pending = getattr(session, "pending_profile_recall", None)
235
+ if not pending:
236
+ return False
237
+ # Resolve the staging regardless of outcome.
238
+ session.pending_profile_recall = None
239
+ if not confirmed:
240
+ return False
241
+ stored_fields = pending.get("stored_fields") or {}
242
+ if not stored_fields:
243
+ return False
244
+ for fld, new in stored_fields.items():
245
+ try:
246
+ if fld not in Profile.__dataclass_fields__:
247
+ continue
248
+ cur = getattr(session.profile, fld, None)
249
+ if cur in (None, "", []) and new not in (None, "", []):
250
+ setattr(session.profile, fld, new)
251
+ except Exception:
252
+ continue
253
+ session.last_touched = time.time()
254
+ return True
255
+
256
+
257
  def set_free_form(session_id: str, free_form: bool = True) -> None:
258
  s = get_session(session_id)
259
  s.free_form_session = free_form
backend/single_brain.py CHANGED
@@ -35,6 +35,7 @@ from typing import Any, Optional
35
  import httpx
36
 
37
  from backend import brain_tools
 
38
 
39
  _log = logging.getLogger(__name__)
40
 
@@ -588,6 +589,83 @@ def _detect_language(user_text: str) -> str:
588
  return "en"
589
 
590
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
591
  _FALLBACK_SLOT_QUESTIONS = {
592
  "name": "What's your name?",
593
  "age": "How old are you?",
@@ -972,14 +1050,33 @@ def _build_recommendation_citations(
972
  and dropped ones it did.
973
 
974
  This builds the citation set as EXACTLY the policies the assistant
975
- actually recommended, in the order it presented them:
976
 
977
  1. If the LLM called `mark_recommendation(policy_ids=[...])`, those
978
- ordered ids ARE the recommendation set (the system prompt defines
979
- this as "ordered IDs you cited").
980
  2. Otherwise (Gemini skips mark_recommendation on ~70% of rec turns
981
- per KI-254), parse the reply prose: for every retrieved policy
982
- whose name appears in `reply_text`, order by first appearance.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
983
 
984
  Each recommended policy is hydrated from its BEST (highest-score)
985
  retrieved chunk so source_url / policy_name / insurer_slug are real
@@ -993,26 +1090,39 @@ def _build_recommendation_citations(
993
  chit-chat); caller uses the legacy per-chunk recall list so QA
994
  answers still get their supporting source chips.
995
  """
996
- # policy_id -> best chunk (highest score) for hydration; also collect
997
- # the per-policy display name + a normalised alias for prose matching.
998
- best_by_pid: dict[str, dict] = {}
999
- for c in retrieved_chunks_all:
 
 
 
 
 
 
 
 
 
1000
  pid = (c.get("policy_id") or "").strip()
1001
  if not pid:
1002
  continue
1003
- cur = best_by_pid.get(pid)
 
 
 
 
1004
  if cur is None or float(c.get("score", 0.0) or 0.0) > float(
1005
  cur.get("score", 0.0) or 0.0
1006
  ):
1007
- best_by_pid[pid] = c
1008
 
1009
- def _cite(pid: str) -> Optional[dict]:
1010
- c = best_by_pid.get(pid)
1011
  if c is None:
1012
  return None
1013
  return {
1014
  "chunk_id": c.get("chunk_id", ""),
1015
- "policy_id": pid,
1016
  "policy_name": c.get("policy_name", ""),
1017
  "insurer_slug": c.get("insurer_slug", ""),
1018
  "doc_type": c.get("doc_type", ""),
@@ -1020,18 +1130,31 @@ def _build_recommendation_citations(
1020
  "score": c.get("score", 0.0),
1021
  }
1022
 
1023
- # ---- Path 1: explicit mark_recommendation ordering --------------------
1024
- if marked_policy_ids:
1025
- out: list[dict] = []
1026
  seen: set[str] = set()
1027
- for pid in marked_policy_ids:
1028
- pid = (pid or "").strip()
1029
- if not pid or pid in seen:
1030
- continue
1031
- seen.add(pid)
1032
- cite = _cite(pid)
 
 
 
1033
  if cite is not None:
1034
  out.append(cite)
 
 
 
 
 
 
 
 
 
 
1035
  # mark_recommendation fired β‡’ this is unambiguously a recommendation
1036
  # turn even if id↔chunk hydration matched nothing.
1037
  return out, True
@@ -1041,35 +1164,28 @@ def _build_recommendation_citations(
1041
  if not haystack:
1042
  return [], False
1043
 
1044
- # Score earliest prose offset per policy; only policies whose name is
1045
- # actually written into the answer become cards. Longest names first so
1046
- # "my health suraksha" wins over a bare "suraksha" substring.
1047
- matched: list[tuple[int, str]] = []
1048
- for pid, c in best_by_pid.items():
 
 
 
 
1049
  norm = _norm_policy_name(c.get("policy_name", ""))
1050
  if len(norm) < 4: # too short to match safely
1051
  continue
1052
- idx = haystack.find(norm)
1053
- if idx != -1:
1054
- matched.append((idx, pid))
1055
 
1056
- if not matched:
1057
  # No retrieved policy was named in the prose. If chunks WERE
1058
  # retrieved this is a QA turn that quoted a policy generically β†’
1059
  # let the caller keep the legacy recall chips for source grounding.
1060
  return [], False
1061
 
1062
- matched.sort(key=lambda t: t[0])
1063
- out2: list[dict] = []
1064
- seen2: set[str] = set()
1065
- for _idx, pid in matched:
1066
- if pid in seen2:
1067
- continue
1068
- seen2.add(pid)
1069
- cite = _cite(pid)
1070
- if cite is not None:
1071
- out2.append(cite)
1072
- return out2, True
1073
 
1074
 
1075
  def _parts_function_calls(parts: list[dict]) -> list[dict]:
@@ -1151,10 +1267,13 @@ async def handle_turn(
1151
  except Exception: # noqa: BLE001 β€” never break a chat turn for bookkeeping
1152
  pass
1153
 
1154
- api_key = os.environ.get("GOOGLE_API_KEY", "").strip()
1155
- if not api_key:
1156
- raise SingleBrainError("GOOGLE_API_KEY not set")
1157
-
 
 
 
1158
  model = _resolve_model()
1159
  language = _detect_language(user_text)
1160
 
@@ -1174,6 +1293,38 @@ async def handle_turn(
1174
  # below already contains the recalled slots β€” RULE 4 (Welcome Back) then
1175
  # fires correctly on this same Gemini iteration. Best-effort: no error
1176
  # bubbles out.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1177
  if _current_turn == 1 and not (getattr(session.profile, "name", None) or ""):
1178
  try:
1179
  from backend.profile_persistence import (
@@ -1183,12 +1334,40 @@ async def handle_turn(
1183
 
1184
  _maybe_name = extract_potential_name(user_text)
1185
  if _maybe_name:
1186
- _recalled = try_recall_by_name(session, _maybe_name)
1187
- if _recalled:
 
 
 
 
 
 
 
 
 
 
 
 
 
1188
  _log.info(
1189
- "single_brain turn-1 recall: name=%r matched stored "
1190
- "profile; hydrated session=%s",
1191
- _maybe_name, getattr(session, "session_id", "?"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1192
  )
1193
  except Exception as _recall_err: # noqa: BLE001 β€” must never break turn
1194
  _log.warning(
@@ -1205,6 +1384,14 @@ async def handle_turn(
1205
  )
1206
  is_returning_user = (_current_turn == 1) and _has_prior_profile
1207
 
 
 
 
 
 
 
 
 
1208
  system_instruction = _system_instruction(
1209
  session.profile, is_returning_user=is_returning_user,
1210
  )
 
35
  import httpx
36
 
37
  from backend import brain_tools
38
+ from backend.policy_identity import canonical_key
39
 
40
  _log = logging.getLogger(__name__)
41
 
 
589
  return "en"
590
 
591
 
592
+ # --- confirmation-gated cross-session recall (privacy fix, 2026-05-16) ------
593
+ # When session_state.rehydrate_by_name STAGES a name match on
594
+ # `session.pending_profile_recall`, single_brain asks the user a one-line
595
+ # "are you the same <name>?" confirmation BEFORE any stored field is merged
596
+ # (session_state.apply_pending_recall). These coarse yes/no detectors classify
597
+ # the user's NEXT message. Anything that is not a clear affirmation is treated
598
+ # as "not me / decline" (fail closed β€” never leak a stranger's profile).
599
+ # Strong single-token affirmations only. Weak first-person tokens ("i'm",
600
+ # "i am", "im") are deliberately EXCLUDED β€” they appear in denials too
601
+ # ("I'm new", "I'm someone else") and would mis-classify a decline as a
602
+ # yes (privacy: that would leak a stranger's profile).
603
+ _RECALL_AFFIRM = (
604
+ "yes", "yep", "yeah", "yup", "ya", "yess", "haan", "haa",
605
+ "correct", "right", "indeed", "sure", "ok", "okay",
606
+ "affirmative", "true", "yedha",
607
+ )
608
+ # Multi-word affirmation phrases (checked as substrings).
609
+ _RECALL_AFFIRM_PHRASES = (
610
+ "that's me", "thats me", "that is me", "it's me", "its me",
611
+ "that's right", "thats right", "that's correct", "thats correct",
612
+ "yes that's me", "same person", "the same",
613
+ )
614
+ _RECALL_DENY = (
615
+ "no", "nope", "nah", "nahi", "na", "wrong", "incorrect", "different",
616
+ )
617
+ _RECALL_DENY_PHRASES = (
618
+ "not me", "someone else", "different person", "first time",
619
+ "i'm new", "im new", "i am new", "new user", "not the same",
620
+ "not that", "wrong person",
621
+ )
622
+
623
+
624
+ def _classify_recall_answer(user_text: str) -> bool:
625
+ """Coarse yes/no for the staged-recall confirm prompt.
626
+
627
+ Returns True ONLY for a clear affirmation that the user is the same
628
+ returning person. Explicit denials and anything ambiguous return False
629
+ so the staged stranger profile is DISCARDED (fail closed β€” privacy).
630
+ """
631
+ t = (user_text or "").strip().lower()
632
+ if not t:
633
+ return False
634
+ stripped = t.strip(" \t\r\n.,!?\"'()[]")
635
+ if not stripped:
636
+ return False
637
+
638
+ # 1) Explicit DENIAL anywhere wins β€” fail closed. Checked FIRST so
639
+ # "no, that's me" / "I'm new" never get read as a yes.
640
+ if any(p in stripped for p in _RECALL_DENY_PHRASES):
641
+ return False
642
+ padded = f" {stripped} "
643
+ if any(f" {d} " in padded for d in _RECALL_DENY):
644
+ return False
645
+ # A leading deny token survives trailing punctuation ("no, that's me").
646
+ _toks = stripped.replace(",", " ").split()
647
+ if _toks and _toks[0] in _RECALL_DENY:
648
+ return False
649
+
650
+ # 2) Explicit AFFIRMATION phrase ("that's me", "it's me", "same person").
651
+ if any(p in stripped for p in _RECALL_AFFIRM_PHRASES):
652
+ return True
653
+
654
+ # 3) Exact / leading strong affirmation token ("yes", "yep, ...").
655
+ if stripped in _RECALL_AFFIRM:
656
+ return True
657
+ first = stripped.split()[0] if stripped.split() else ""
658
+ if first in _RECALL_AFFIRM:
659
+ return True
660
+
661
+ # 4) A strong affirmation token elsewhere ("oh yes please").
662
+ if any(f" {a} " in padded for a in _RECALL_AFFIRM):
663
+ return True
664
+
665
+ # 5) Anything else (questions, new facts, gibberish) β†’ discard.
666
+ return False
667
+
668
+
669
  _FALLBACK_SLOT_QUESTIONS = {
670
  "name": "What's your name?",
671
  "age": "How old are you?",
 
1050
  and dropped ones it did.
1051
 
1052
  This builds the citation set as EXACTLY the policies the assistant
1053
+ actually recommended:
1054
 
1055
  1. If the LLM called `mark_recommendation(policy_ids=[...])`, those
1056
+ ids are the SELECTION (which policies the assistant chose).
 
1057
  2. Otherwise (Gemini skips mark_recommendation on ~70% of rec turns
1058
+ per KI-254), parse the reply prose: every retrieved policy whose
1059
+ name appears in `reply_text` is selected.
1060
+
1061
+ KI-280 β€” the cited-card list and the advisory prose must be gated by
1062
+ the SAME fitness logic. Two refinements over the KI-278 builder so the
1063
+ cards ARE the gated, fit-ranked set:
1064
+
1065
+ β€’ CANONICAL DEDUP: `retrieved_chunks_all` is the union of every
1066
+ retrieve_policies result this turn. Each result is already gated +
1067
+ deduped by retrieval_filters, but across multiple retrieve calls
1068
+ the same product can reappear under a doctype-sibling / marketing-
1069
+ variant id. We collapse by the shared canonical identity
1070
+ (policy_identity.canonical_key) β€” the SAME rule the marketplace and
1071
+ retrieval_filters.dedup_by_policy use β€” so a product is cited once
1072
+ (audit P2/P4/P7).
1073
+ β€’ GATE-RANK ORDER: the cards are ordered by the gate's profile-fit
1074
+ rank (first appearance in the gated chunk stream = the pipeline's
1075
+ fit order), NOT the LLM's free mark_recommendation / prose order.
1076
+ The LLM decides WHICH policies it recommends; the GATE decides the
1077
+ order so #1 cited = best fit for THIS profile (fixes the audit
1078
+ grade/rank inversion: P1 C/65-above-B/75, P2 A/77-ranked-last,
1079
+ P5 non-cheapest-first).
1080
 
1081
  Each recommended policy is hydrated from its BEST (highest-score)
1082
  retrieved chunk so source_url / policy_name / insurer_slug are real
 
1090
  chit-chat); caller uses the legacy per-chunk recall list so QA
1091
  answers still get their supporting source chips.
1092
  """
1093
+ # KI-280 β€” collapse the turn's gated chunk stream by CANONICAL identity
1094
+ # (UIN-primary, product_key fallback β€” the shared marketplace/
1095
+ # retrieval_filters rule). For each canonical product keep:
1096
+ # β€’ the best (highest-score) chunk for hydration, and
1097
+ # β€’ `gate_rank` = the index of its FIRST appearance in the gated
1098
+ # stream. `retrieved_chunks_all` preserves filter_pipeline's
1099
+ # profile-fit order per retrieve call, so first-appearance order IS
1100
+ # the gate's fit ranking. We order the final cards by this, not by
1101
+ # the LLM's mark_recommendation / prose order.
1102
+ best_by_canon: dict[str, dict] = {}
1103
+ gate_rank: dict[str, int] = {}
1104
+ pid_to_canon: dict[str, str] = {}
1105
+ for idx, c in enumerate(retrieved_chunks_all):
1106
  pid = (c.get("policy_id") or "").strip()
1107
  if not pid:
1108
  continue
1109
+ canon = canonical_key(c)
1110
+ pid_to_canon.setdefault(pid, canon)
1111
+ if canon not in gate_rank:
1112
+ gate_rank[canon] = idx
1113
+ cur = best_by_canon.get(canon)
1114
  if cur is None or float(c.get("score", 0.0) or 0.0) > float(
1115
  cur.get("score", 0.0) or 0.0
1116
  ):
1117
+ best_by_canon[canon] = c
1118
 
1119
+ def _cite_canon(canon: str) -> Optional[dict]:
1120
+ c = best_by_canon.get(canon)
1121
  if c is None:
1122
  return None
1123
  return {
1124
  "chunk_id": c.get("chunk_id", ""),
1125
+ "policy_id": (c.get("policy_id") or "").strip(),
1126
  "policy_name": c.get("policy_name", ""),
1127
  "insurer_slug": c.get("insurer_slug", ""),
1128
  "doc_type": c.get("doc_type", ""),
 
1130
  "score": c.get("score", 0.0),
1131
  }
1132
 
1133
+ def _order_by_gate(canons: list[str]) -> list[dict]:
1134
+ """De-dup the selected canonicals and emit them in the GATE's
1135
+ profile-fit order (not the order the LLM listed them)."""
1136
  seen: set[str] = set()
1137
+ uniq: list[str] = []
1138
+ for k in canons:
1139
+ if k and k not in seen:
1140
+ seen.add(k)
1141
+ uniq.append(k)
1142
+ uniq.sort(key=lambda k: gate_rank.get(k, 1_000_000))
1143
+ out: list[dict] = []
1144
+ for k in uniq:
1145
+ cite = _cite_canon(k)
1146
  if cite is not None:
1147
  out.append(cite)
1148
+ return out
1149
+
1150
+ # ---- Path 1: explicit mark_recommendation selection -------------------
1151
+ if marked_policy_ids:
1152
+ # The LLM's ids are the SELECTION; the GATE decides the order.
1153
+ selected = [
1154
+ pid_to_canon.get((pid or "").strip())
1155
+ for pid in marked_policy_ids
1156
+ ]
1157
+ out = _order_by_gate([k for k in selected if k])
1158
  # mark_recommendation fired β‡’ this is unambiguously a recommendation
1159
  # turn even if id↔chunk hydration matched nothing.
1160
  return out, True
 
1164
  if not haystack:
1165
  return [], False
1166
 
1167
+ # A canonical product is SELECTED when its best chunk's policy_name is
1168
+ # written into the reply prose (longest names matched implicitly via
1169
+ # the >=4 char guard so a bare token can't false-match). KI-280: the
1170
+ # selection is by prose presence, but the final ORDER is the gate's
1171
+ # fit rank (_order_by_gate), not the prose offset β€” same principle as
1172
+ # Path 1, so a forgotten mark_recommendation still yields fit-ordered,
1173
+ # canonically-deduped cards.
1174
+ selected2: list[str] = []
1175
+ for canon, c in best_by_canon.items():
1176
  norm = _norm_policy_name(c.get("policy_name", ""))
1177
  if len(norm) < 4: # too short to match safely
1178
  continue
1179
+ if haystack.find(norm) != -1:
1180
+ selected2.append(canon)
 
1181
 
1182
+ if not selected2:
1183
  # No retrieved policy was named in the prose. If chunks WERE
1184
  # retrieved this is a QA turn that quoted a policy generically β†’
1185
  # let the caller keep the legacy recall chips for source grounding.
1186
  return [], False
1187
 
1188
+ return _order_by_gate(selected2), True
 
 
 
 
 
 
 
 
 
 
1189
 
1190
 
1191
  def _parts_function_calls(parts: list[dict]) -> list[dict]:
 
1267
  except Exception: # noqa: BLE001 β€” never break a chat turn for bookkeeping
1268
  pass
1269
 
1270
+ # NOTE (recall-confirm, 2026-05-16): the GOOGLE_API_KEY gate was moved
1271
+ # BELOW the confirmation-gated recall block. STEP 1 emits a deterministic
1272
+ # one-line "are you <name>?" prompt and short-circuits with NO Gemini
1273
+ # call (it must not require an API key), and STEP 2 must resolve a staged
1274
+ # recall (apply / discard) BEFORE the brain runs. The key is still
1275
+ # asserted before any Gemini request is made (just before _build_contents
1276
+ # / the iteration loop below).
1277
  model = _resolve_model()
1278
  language = _detect_language(user_text)
1279
 
 
1293
  # below already contains the recalled slots β€” RULE 4 (Welcome Back) then
1294
  # fires correctly on this same Gemini iteration. Best-effort: no error
1295
  # bubbles out.
1296
+ # CONFIRMATION-GATED RECALL β€” STEP 2 (resolve a prior confirm prompt).
1297
+ # If a cross-session match was STAGED and we already ASKED the user
1298
+ # "are you the same <name>?" on a prior turn, this message is the
1299
+ # answer. Affirm β†’ apply_pending_recall(confirmed=True) (fills empty
1300
+ # slots; live-conversation slots win). Anything else β†’ discard
1301
+ # (confirmed=False, fail closed). Either way the staging is cleared so
1302
+ # we ask only ONCE, then the turn proceeds normally with the resolved
1303
+ # profile so the user's actual message still gets answered.
1304
+ _pending = getattr(session, "pending_profile_recall", None)
1305
+ if isinstance(_pending, dict) and _pending.get("prompted"):
1306
+ try:
1307
+ from backend.session_state import apply_pending_recall
1308
+
1309
+ _affirmed = _classify_recall_answer(user_text)
1310
+ _applied = apply_pending_recall(session, confirmed=_affirmed)
1311
+ _log.info(
1312
+ "single_brain recall-confirm resolved: affirmed=%s "
1313
+ "applied=%s session=%s",
1314
+ _affirmed, _applied, getattr(session, "session_id", "?"),
1315
+ )
1316
+ except Exception as _confirm_err: # noqa: BLE001 β€” never break turn
1317
+ # On any failure, fail closed: discard the staging.
1318
+ try:
1319
+ session.pending_profile_recall = None
1320
+ except Exception: # noqa: BLE001
1321
+ pass
1322
+ _log.warning(
1323
+ "single_brain recall-confirm failed (discarding): %s: %s",
1324
+ type(_confirm_err).__name__, str(_confirm_err)[:200],
1325
+ )
1326
+
1327
+ # CONFIRMATION-GATED RECALL β€” STEP 1 (stage + ask, turn 1 only).
1328
  if _current_turn == 1 and not (getattr(session.profile, "name", None) or ""):
1329
  try:
1330
  from backend.profile_persistence import (
 
1334
 
1335
  _maybe_name = extract_potential_name(user_text)
1336
  if _maybe_name:
1337
+ # STAGES a match on session.pending_profile_recall (never
1338
+ # auto-merges β€” privacy fix 2026-05-16); always returns False.
1339
+ try_recall_by_name(session, _maybe_name)
1340
+ _staged = getattr(session, "pending_profile_recall", None)
1341
+ if isinstance(_staged, dict) and not _staged.get("prompted"):
1342
+ # Ask ONE explicit confirmation and short-circuit the
1343
+ # turn. Do NOT apply the stored profile yet, and NEVER
1344
+ # surface the staged stranger PII β€” only the name, which
1345
+ # the user themselves just stated.
1346
+ _staged["prompted"] = True
1347
+ _recall_name = (_staged.get("name") or _maybe_name).strip()
1348
+ _confirm_text = (
1349
+ f"Welcome back β€” are you the same {_recall_name} "
1350
+ f"from before? (yes/no)"
1351
+ )
1352
  _log.info(
1353
+ "single_brain recall-confirm prompt: name=%r "
1354
+ "staged; awaiting yes/no session=%s",
1355
+ _recall_name, getattr(session, "session_id", "?"),
1356
+ )
1357
+ return TurnResult(
1358
+ reply_text=_confirm_text,
1359
+ citations=[],
1360
+ retrieved_chunk_ids=[],
1361
+ brain_used=f"single_brain::{model}::recall_confirm",
1362
+ intent="recall_confirm",
1363
+ language=language,
1364
+ latency_ms=int((time.time() - t0) * 1000),
1365
+ raw_reply=_confirm_text,
1366
+ faithfulness_passed=True,
1367
+ faithfulness_reasons=[],
1368
+ blocked=False,
1369
+ profile_updates={},
1370
+ followup_policy_id=None,
1371
  )
1372
  except Exception as _recall_err: # noqa: BLE001 β€” must never break turn
1373
  _log.warning(
 
1384
  )
1385
  is_returning_user = (_current_turn == 1) and _has_prior_profile
1386
 
1387
+ # GOOGLE_API_KEY gate β€” asserted here (after the no-LLM recall-confirm
1388
+ # block above, before anything that talks to Gemini). Moved down from the
1389
+ # top of handle_turn so STEP 1's deterministic confirm prompt can
1390
+ # short-circuit and STEP 2's apply/discard can resolve without a key.
1391
+ api_key = os.environ.get("GOOGLE_API_KEY", "").strip()
1392
+ if not api_key:
1393
+ raise SingleBrainError("GOOGLE_API_KEY not set")
1394
+
1395
  system_instruction = _system_instruction(
1396
  session.profile, is_returning_user=is_returning_user,
1397
  )
frontend/public/admin/llm-control.html CHANGED
@@ -54,9 +54,12 @@
54
  color: var(--text);
55
  }
56
  .container {
57
- max-width: 1100px;
58
  margin: 0 auto;
59
  }
 
 
 
60
  .card {
61
  background: var(--card);
62
  border: 1px solid var(--border);
@@ -512,6 +515,13 @@
512
  border-top: 1px solid var(--border);
513
  }
514
  .perf-sub:first-of-type { margin-top: 0; padding-top: 0; border-top: none; }
 
 
 
 
 
 
 
515
  .empty-state {
516
  padding: 24px;
517
  text-align: center;
@@ -665,6 +675,24 @@
665
  padding: 0 16px 16px;
666
  }
667
  .drift-row-bad td { background: rgba(248, 81, 73, 0.08); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
668
  .drift-pct {
669
  display: inline-block;
670
  min-width: 48px;
@@ -2332,26 +2360,34 @@
2332
  }
2333
  var p = STATE.performance;
2334
 
2335
- // (a) Latest 96-Q gold eval
 
 
 
 
 
 
2336
  var goldSection = createEl('div', { className: 'perf-sub' });
2337
- goldSection.appendChild(createEl('h3', { text: 'Latest 96-Q gold eval' }));
2338
- var gold = p.gold_eval || p.eval || null;
 
 
 
 
2339
  if (!gold || isEmptyObj(gold)) {
2340
  goldSection.appendChild(createEl('div', { className: 'empty-state', text: 'No gold eval run yet.' }));
2341
  } else {
2342
  var caption = createEl('div', { className: 'perf-caption' });
2343
- var runAt = gold.run_at || gold.timestamp || gold.created_at;
2344
  if (runAt) caption.textContent = 'Run at ' + fmtIST(runAt);
2345
  if (caption.textContent) goldSection.appendChild(caption);
2346
 
2347
  var tiles = createEl('div', { className: 'metric-grid' });
2348
- tiles.appendChild(metricTile('Factual', fmtPctMaybe(pickPct(gold, ['factual_pct', 'factual', 'factual_correct_pct']))));
2349
- tiles.appendChild(metricTile('Citation', fmtPctMaybe(pickPct(gold, ['citation_pct', 'citation', 'citation_correct_pct']))));
2350
- tiles.appendChild(metricTile('Refusal', fmtPctMaybe(pickPct(gold, ['refusal_pct', 'refusal', 'refusal_rate']))));
2351
- if (gold.total_questions != null) {
2352
- tiles.appendChild(metricTile('Questions', String(gold.total_questions)));
2353
- } else if (gold.n != null) {
2354
- tiles.appendChild(metricTile('Questions', String(gold.n)));
2355
  }
2356
  goldSection.appendChild(tiles);
2357
 
@@ -2371,21 +2407,33 @@
2371
  }
2372
  body.appendChild(goldSection);
2373
 
2374
- // (b) Latest persona audit
 
 
 
 
 
2375
  var personaSection = createEl('div', { className: 'perf-sub' });
2376
  personaSection.appendChild(createEl('h3', { text: 'Latest persona audit' }));
2377
- var persona = p.persona_audit || p.persona || null;
2378
  if (!persona || isEmptyObj(persona)) {
2379
  personaSection.appendChild(createEl('div', { className: 'empty-state', text: 'No persona audit run yet.' }));
2380
  } else {
2381
  var pCaption = createEl('div', { className: 'perf-caption' });
2382
- var pRunAt = persona.run_at || persona.timestamp || persona.created_at;
2383
- if (pRunAt) pCaption.textContent = 'Run at ' + fmtIST(pRunAt);
 
 
2384
  if (pCaption.textContent) personaSection.appendChild(pCaption);
2385
 
2386
  var pTiles = createEl('div', { className: 'metric-grid' });
2387
  if (persona.personas_completed != null) {
2388
- pTiles.appendChild(metricTile('Personas completed', String(persona.personas_completed)));
 
 
 
 
 
2389
  }
2390
  pTiles.appendChild(metricTile('p50 latency', fmtLatency(persona.p50_ms != null ? persona.p50_ms : persona.p50)));
2391
  pTiles.appendChild(metricTile('p95 latency', fmtLatency(persona.p95_ms != null ? persona.p95_ms : persona.p95)));
@@ -2627,7 +2675,7 @@
2627
  var personas = STATE.drift.personas || [];
2628
  if (summary) {
2629
  summary.textContent = personas.length + ' persona' + (personas.length === 1 ? '' : 's')
2630
- + ' Β· ' + ((STATE.drift.slots || []).length || 6) + ' slots';
2631
  }
2632
  if (!personas.length) {
2633
  body.appendChild(createEl('div', { className: 'empty-state',
 
54
  color: var(--text);
55
  }
56
  .container {
57
+ max-width: 1500px;
58
  margin: 0 auto;
59
  }
60
+ @media (max-width: 1540px) {
61
+ .container { max-width: 100%; }
62
+ }
63
  .card {
64
  background: var(--card);
65
  border: 1px solid var(--border);
 
515
  border-top: 1px solid var(--border);
516
  }
517
  .perf-sub:first-of-type { margin-top: 0; padding-top: 0; border-top: none; }
518
+ /* Performance tab tables (gold by_brain / by_type breakdown + the
519
+ Last-24h LLM-usage role table). Constrain width so they read well
520
+ in the widened container and let the role-name column wrap rather
521
+ than stretch the whole row. */
522
+ #performance-body table { max-width: 920px; }
523
+ #performance-body td { overflow-wrap: anywhere; }
524
+ #performance-body .metric-grid { max-width: 920px; }
525
  .empty-state {
526
  padding: 24px;
527
  text-align: center;
 
675
  padding: 0 16px 16px;
676
  }
677
  .drift-row-bad td { background: rgba(248, 81, 73, 0.08); }
678
+ /* Persona Drift table β€” give every column a sensible share of the
679
+ (now wider) container and let the comma-joined CAPTURED / MISSING
680
+ slot lists WRAP instead of clipping off the right edge. The orange
681
+ MISSING column was previously cut off because the .mono small cells
682
+ had no width budget and never wrapped. */
683
+ #drift-body table { table-layout: fixed; }
684
+ #drift-body th:nth-child(1), #drift-body td:nth-child(1) { width: 22%; }
685
+ #drift-body th:nth-child(2), #drift-body td:nth-child(2) { width: 14%; }
686
+ #drift-body th:nth-child(3), #drift-body td:nth-child(3) { width: 27%; }
687
+ #drift-body th:nth-child(4), #drift-body td:nth-child(4) { width: 27%; }
688
+ #drift-body th:nth-child(5), #drift-body td:nth-child(5) { width: 10%; }
689
+ #drift-body td.mono {
690
+ white-space: normal;
691
+ overflow-wrap: anywhere;
692
+ word-break: break-word;
693
+ line-height: 1.6;
694
+ }
695
+ #drift-body td.time-cell { white-space: normal; }
696
  .drift-pct {
697
  display: inline-block;
698
  min-width: 48px;
 
2360
  }
2361
  var p = STATE.performance;
2362
 
2363
+ // (a) Latest gold eval. The backend (/api/admin/performance β†’
2364
+ // _read_eval_summary) emits the `eval` block with fields
2365
+ // ran_at / n_questions / factual_accuracy / citation_accuracy /
2366
+ // refusal_precision / by_brain / by_type. The question count is
2367
+ // whatever the last run covered (gold set = eval/gold_qa.json);
2368
+ // we derive the heading from n_questions instead of hard-coding a
2369
+ // stale "96-Q" β€” the gold set is no longer 96 questions.
2370
  var goldSection = createEl('div', { className: 'perf-sub' });
2371
+ var gold = p.eval || p.gold_eval || null;
2372
+ var goldN = gold ? (gold.n_questions != null ? gold.n_questions
2373
+ : (gold.total_questions != null ? gold.total_questions : gold.n)) : null;
2374
+ goldSection.appendChild(createEl('h3', {
2375
+ text: 'Latest gold eval' + (goldN != null ? ' (' + goldN + '-Q)' : '')
2376
+ }));
2377
  if (!gold || isEmptyObj(gold)) {
2378
  goldSection.appendChild(createEl('div', { className: 'empty-state', text: 'No gold eval run yet.' }));
2379
  } else {
2380
  var caption = createEl('div', { className: 'perf-caption' });
2381
+ var runAt = gold.ran_at || gold.run_at || gold.timestamp || gold.created_at;
2382
  if (runAt) caption.textContent = 'Run at ' + fmtIST(runAt);
2383
  if (caption.textContent) goldSection.appendChild(caption);
2384
 
2385
  var tiles = createEl('div', { className: 'metric-grid' });
2386
+ tiles.appendChild(metricTile('Factual', fmtPctMaybe(pickPct(gold, ['factual_accuracy', 'factual_pct', 'factual', 'factual_correct_pct']))));
2387
+ tiles.appendChild(metricTile('Citation', fmtPctMaybe(pickPct(gold, ['citation_accuracy', 'citation_pct', 'citation', 'citation_correct_pct']))));
2388
+ tiles.appendChild(metricTile('Refusal', fmtPctMaybe(pickPct(gold, ['refusal_precision', 'refusal_pct', 'refusal', 'refusal_rate']))));
2389
+ if (goldN != null) {
2390
+ tiles.appendChild(metricTile('Questions', String(goldN)));
 
 
2391
  }
2392
  goldSection.appendChild(tiles);
2393
 
 
2407
  }
2408
  body.appendChild(goldSection);
2409
 
2410
+ // (b) Latest persona audit. The backend (/api/admin/performance β†’
2411
+ // _read_audit_summary) emits the `audit` block parsed from the most
2412
+ // recent 80-audit/full_* run: run_id / personas_requested /
2413
+ // personas_completed / elapsed_seconds / turns_total / errors /
2414
+ // refusals / p50_ms / p95_ms / p99_ms / brain_routing. There is no
2415
+ // run_at field β€” the run is identified by run_id.
2416
  var personaSection = createEl('div', { className: 'perf-sub' });
2417
  personaSection.appendChild(createEl('h3', { text: 'Latest persona audit' }));
2418
+ var persona = p.audit || p.persona_audit || p.persona || null;
2419
  if (!persona || isEmptyObj(persona)) {
2420
  personaSection.appendChild(createEl('div', { className: 'empty-state', text: 'No persona audit run yet.' }));
2421
  } else {
2422
  var pCaption = createEl('div', { className: 'perf-caption' });
2423
+ if (persona.run_id) {
2424
+ pCaption.textContent = 'Run ' + persona.run_id
2425
+ + (persona.elapsed_seconds != null ? ' Β· ' + persona.elapsed_seconds + 's' : '');
2426
+ }
2427
  if (pCaption.textContent) personaSection.appendChild(pCaption);
2428
 
2429
  var pTiles = createEl('div', { className: 'metric-grid' });
2430
  if (persona.personas_completed != null) {
2431
+ pTiles.appendChild(metricTile('Personas completed',
2432
+ String(persona.personas_completed)
2433
+ + (persona.personas_requested != null ? ' / ' + persona.personas_requested : '')));
2434
+ }
2435
+ if (persona.turns_total != null) {
2436
+ pTiles.appendChild(metricTile('Turns', String(persona.turns_total)));
2437
  }
2438
  pTiles.appendChild(metricTile('p50 latency', fmtLatency(persona.p50_ms != null ? persona.p50_ms : persona.p50)));
2439
  pTiles.appendChild(metricTile('p95 latency', fmtLatency(persona.p95_ms != null ? persona.p95_ms : persona.p95)));
 
2675
  var personas = STATE.drift.personas || [];
2676
  if (summary) {
2677
  summary.textContent = personas.length + ' persona' + (personas.length === 1 ? '' : 's')
2678
+ + ' Β· ' + ((STATE.drift.slots || []).length || 7) + ' slots';
2679
  }
2680
  if (!personas.length) {
2681
  body.appendChild(createEl('div', { className: 'empty-state',
frontend/src/app/globals.css CHANGED
@@ -24,7 +24,8 @@
24
  --color-card: var(--card);
25
  --color-accent: var(--accent);
26
  --color-error: var(--error);
27
- --font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
 
28
  --font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, monospace;
29
  }
30
 
@@ -82,13 +83,552 @@ body {
82
  outline-offset: 2px;
83
  }
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  /* Honour reduced-motion preference: drop the hover-lift transition on the
86
  * landing step / mode / callout cards for vestibular-sensitive users. */
87
  @media (prefers-reduced-motion: reduce) {
88
- .step-card, .mode-row, .callout-card, .chip-tile {
 
89
  transition: none !important;
90
  }
91
- .step-card:hover, .mode-row:hover {
 
92
  transform: none !important;
93
  }
 
 
 
 
 
94
  }
 
24
  --color-card: var(--card);
25
  --color-accent: var(--accent);
26
  --color-error: var(--error);
27
+ --font-sans: var(--font-body), ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
28
+ --font-serif: var(--font-display), ui-serif, Georgia, "Times New Roman", serif;
29
  --font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, monospace;
30
  }
31
 
 
83
  outline-offset: 2px;
84
  }
85
 
86
+ /* ────────────────────────────────────────────────────────────────────
87
+ * PREMIUM LANDING (EmptyState) β€” editorial-fintech redesign
88
+ * Design direction: warm, trustworthy, magazine-grade. Fraunces display
89
+ * serif + Plus Jakarta body, layered soft depth, a faint grain + grid
90
+ * hero texture, a numbered "journey" spine, and one orchestrated
91
+ * page-load reveal. No generic AI card-grid look.
92
+ * ──────────────────────────────────────────────────────────────────── */
93
+
94
+ /* Display serif β€” applied to the hero headline + section titles. The
95
+ * optical-size + soft axes give large type a warm, set-by-hand feel. */
96
+ .font-display {
97
+ font-family: var(--font-serif);
98
+ font-optical-sizing: auto;
99
+ font-variation-settings: "SOFT" 40, "WONK" 0;
100
+ letter-spacing: -0.012em;
101
+ }
102
+
103
+ /* The landing root sets the editorial body face + a calm vertical wash
104
+ * (deep at the very top behind the hero, fading to paper) and a barely
105
+ * perceptible film grain so flat fills never look plastic. */
106
+ .landing-root {
107
+ font-family: var(--font-sans);
108
+ position: relative;
109
+ background:
110
+ radial-gradient(120% 60% at 50% -10%,
111
+ color-mix(in srgb, var(--primary) 11%, transparent) 0%,
112
+ transparent 60%),
113
+ linear-gradient(180deg,
114
+ color-mix(in srgb, var(--primary) 4%, var(--background)) 0%,
115
+ var(--background) 40%);
116
+ }
117
+ .landing-root::before {
118
+ content: "";
119
+ position: absolute;
120
+ inset: 0;
121
+ pointer-events: none;
122
+ opacity: 0.5;
123
+ mix-blend-mode: multiply;
124
+ /* tiny SVG fractal-noise grain, base64-free via data URI */
125
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='140' height='140'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='140' height='140' filter='url(%23n)' opacity='0.32'/%3E%3C/svg%3E");
126
+ }
127
+
128
+ /* HERO β€” generous, asymmetric-feeling slab with a layered teal glow,
129
+ * an inner hairline, and a faint engineering grid that signals "built,
130
+ * not marketing fluff". */
131
+ .hero-card {
132
+ position: relative;
133
+ isolation: isolate;
134
+ border-radius: 28px;
135
+ border: 1px solid color-mix(in srgb, var(--primary) 16%, var(--border));
136
+ background:
137
+ radial-gradient(90% 120% at 18% 0%,
138
+ color-mix(in srgb, var(--primary) 12%, var(--card)) 0%,
139
+ var(--card) 55%),
140
+ var(--card);
141
+ box-shadow:
142
+ 0 1px 0 color-mix(in srgb, var(--primary) 14%, transparent) inset,
143
+ 0 1px 2px color-mix(in srgb, var(--foreground) 5%, transparent),
144
+ 0 24px 60px -30px color-mix(in srgb, var(--primary) 42%, transparent);
145
+ }
146
+ .hero-card::after {
147
+ content: "";
148
+ position: absolute;
149
+ inset: 0;
150
+ z-index: -1;
151
+ border-radius: inherit;
152
+ pointer-events: none;
153
+ opacity: 0.5;
154
+ -webkit-mask-image: radial-gradient(70% 90% at 22% 8%, #000 0%, transparent 70%);
155
+ mask-image: radial-gradient(70% 90% at 22% 8%, #000 0%, transparent 70%);
156
+ background-image:
157
+ linear-gradient(color-mix(in srgb, var(--primary) 12%, transparent) 1px, transparent 1px),
158
+ linear-gradient(90deg, color-mix(in srgb, var(--primary) 12%, transparent) 1px, transparent 1px);
159
+ background-size: 30px 30px;
160
+ }
161
+
162
+ /* Eyebrow / kicker pill β€” small caps, brand-tinted, with a live dot. */
163
+ .kicker {
164
+ display: inline-flex;
165
+ align-items: center;
166
+ gap: 8px;
167
+ padding: 6px 13px 6px 11px;
168
+ border-radius: 999px;
169
+ font-size: 11.5px;
170
+ font-weight: 600;
171
+ letter-spacing: 0.12em;
172
+ text-transform: uppercase;
173
+ color: var(--primary);
174
+ background: color-mix(in srgb, var(--primary) 9%, var(--card));
175
+ border: 1px solid color-mix(in srgb, var(--primary) 22%, var(--border));
176
+ box-shadow: 0 1px 1px color-mix(in srgb, var(--foreground) 4%, transparent);
177
+ }
178
+ .kicker .dot {
179
+ width: 6px;
180
+ height: 6px;
181
+ border-radius: 999px;
182
+ background: var(--primary);
183
+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--primary) 70%, transparent);
184
+ animation: kicker-pulse 2.6s ease-out infinite;
185
+ }
186
+ @keyframes kicker-pulse {
187
+ 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--primary) 55%, transparent); }
188
+ 70% { box-shadow: 0 0 0 7px color-mix(in srgb, var(--primary) 0%, transparent); }
189
+ 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--primary) 0%, transparent); }
190
+ }
191
+
192
+ /* SECTION SHELL β€” quieter than the hero: clean paper, hairline border,
193
+ * a soft long shadow so sections feel lifted off the page wash. */
194
+ .section-card {
195
+ border-radius: 22px;
196
+ border: 1px solid var(--border);
197
+ background: var(--card);
198
+ box-shadow:
199
+ 0 1px 2px color-mix(in srgb, var(--foreground) 4%, transparent),
200
+ 0 18px 48px -34px color-mix(in srgb, var(--foreground) 30%, transparent);
201
+ }
202
+
203
+ /* Section header: a hairline rule grows from the icon so each section
204
+ * reads as a titled chapter rather than a stacked box. */
205
+ .section-rule {
206
+ flex: 1;
207
+ height: 1px;
208
+ background: linear-gradient(90deg,
209
+ color-mix(in srgb, var(--primary) 30%, var(--border)) 0%,
210
+ var(--border) 30%,
211
+ transparent 100%);
212
+ }
213
+ .section-num {
214
+ font-family: var(--font-serif);
215
+ font-size: 13px;
216
+ font-weight: 600;
217
+ color: color-mix(in srgb, var(--primary) 70%, var(--muted-foreground));
218
+ letter-spacing: 0.02em;
219
+ }
220
+
221
+ /* STEP β€” the three "how it works" cards sit on a shared horizontal spine
222
+ * (a connecting line through the numbered medallions) so they read as one
223
+ * journey, not three disconnected tiles. */
224
+ .step-grid { position: relative; }
225
+ @media (min-width: 640px) {
226
+ .step-grid::before {
227
+ content: "";
228
+ position: absolute;
229
+ top: 50px; /* aligns to the centre of the 36px medallion + pt */
230
+ left: 16%;
231
+ right: 16%;
232
+ height: 2px;
233
+ background: repeating-linear-gradient(90deg,
234
+ color-mix(in srgb, var(--primary) 34%, var(--border)) 0 7px,
235
+ transparent 7px 14px);
236
+ z-index: 0;
237
+ }
238
+ }
239
+ .step-card {
240
+ position: relative;
241
+ z-index: 1;
242
+ border-radius: 18px;
243
+ border: 1px solid var(--border);
244
+ background:
245
+ linear-gradient(180deg,
246
+ color-mix(in srgb, var(--primary) 5%, var(--card)) 0%,
247
+ var(--card) 42%);
248
+ transition: transform .22s cubic-bezier(.2,.7,.3,1),
249
+ box-shadow .22s ease, border-color .22s ease;
250
+ }
251
+ .step-card:hover {
252
+ transform: translateY(-4px);
253
+ border-color: color-mix(in srgb, var(--primary) 34%, var(--border));
254
+ box-shadow:
255
+ 0 1px 2px color-mix(in srgb, var(--foreground) 4%, transparent),
256
+ 0 22px 44px -26px color-mix(in srgb, var(--primary) 46%, transparent);
257
+ }
258
+ .step-medallion {
259
+ width: 44px;
260
+ height: 44px;
261
+ border-radius: 14px;
262
+ display: flex;
263
+ align-items: center;
264
+ justify-content: center;
265
+ font-family: var(--font-serif);
266
+ font-size: 18px;
267
+ font-weight: 600;
268
+ color: var(--primary-foreground);
269
+ background: linear-gradient(150deg,
270
+ color-mix(in srgb, var(--primary) 92%, white) 0%,
271
+ var(--primary) 55%,
272
+ color-mix(in srgb, var(--primary) 78%, black) 100%);
273
+ box-shadow:
274
+ 0 2px 6px color-mix(in srgb, var(--primary) 40%, transparent),
275
+ 0 0 0 5px color-mix(in srgb, var(--primary) 10%, transparent);
276
+ }
277
+
278
+ /* Tight one-line fact bullets used inside step / callout bodies. */
279
+ .fact-list { display: flex; flex-direction: column; gap: 9px; }
280
+ .fact-list li {
281
+ display: flex;
282
+ align-items: flex-start;
283
+ gap: 9px;
284
+ font-size: 13.5px;
285
+ line-height: 1.45;
286
+ color: var(--muted-foreground);
287
+ }
288
+ .fact-list li .tick {
289
+ flex: none;
290
+ margin-top: 1px;
291
+ color: var(--primary);
292
+ }
293
+ .fact-list li strong {
294
+ color: var(--foreground);
295
+ font-weight: 600;
296
+ }
297
+
298
+ /* INPUT-MODE rows β€” refined list with a left accent rail on hover. */
299
+ .mode-row {
300
+ position: relative;
301
+ border-radius: 16px;
302
+ border: 1px solid var(--border);
303
+ background: var(--card);
304
+ overflow: hidden;
305
+ transition: transform .2s cubic-bezier(.2,.7,.3,1),
306
+ box-shadow .2s ease, border-color .2s ease;
307
+ }
308
+ .mode-row::before {
309
+ content: "";
310
+ position: absolute;
311
+ left: 0; top: 0; bottom: 0;
312
+ width: 3px;
313
+ background: var(--primary);
314
+ transform: scaleY(0);
315
+ transform-origin: top;
316
+ transition: transform .22s ease;
317
+ }
318
+ .mode-row:hover {
319
+ transform: translateY(-2px);
320
+ border-color: color-mix(in srgb, var(--primary) 30%, var(--border));
321
+ box-shadow: 0 16px 34px -24px color-mix(in srgb, var(--primary) 40%, transparent);
322
+ }
323
+ .mode-row:hover::before { transform: scaleY(1); }
324
+ .mode-glyph {
325
+ background: linear-gradient(150deg,
326
+ color-mix(in srgb, var(--primary) 14%, var(--card)) 0%,
327
+ color-mix(in srgb, var(--primary) 6%, var(--card)) 100%);
328
+ border: 1px solid color-mix(in srgb, var(--primary) 18%, var(--border));
329
+ color: var(--primary);
330
+ }
331
+
332
+ /* CALLOUT cards β€” keep the amber trust card distinct, lift both. */
333
+ .callout-card {
334
+ border-radius: 18px;
335
+ transition: transform .2s ease, box-shadow .2s ease;
336
+ }
337
+ .callout-card:hover {
338
+ transform: translateY(-2px);
339
+ box-shadow: 0 18px 40px -28px color-mix(in srgb, var(--foreground) 40%, transparent);
340
+ }
341
+
342
+ /* Orchestrated page-load reveal β€” staggered, calm, runs once. */
343
+ @keyframes reveal-up {
344
+ from { opacity: 0; transform: translateY(16px); }
345
+ to { opacity: 1; transform: translateY(0); }
346
+ }
347
+ .reveal {
348
+ opacity: 0;
349
+ animation: reveal-up .6s cubic-bezier(.2,.7,.3,1) forwards;
350
+ }
351
+ .reveal-1 { animation-delay: .02s; }
352
+ .reveal-2 { animation-delay: .12s; }
353
+ .reveal-3 { animation-delay: .22s; }
354
+ .reveal-4 { animation-delay: .32s; }
355
+
356
+ /* ────────────────────────────────────────────────────────────────────
357
+ * PREMIUM APP SURFACES β€” profile builder Β· chat Β· cited cards Β·
358
+ * marketplace. Same editorial-fintech system as the landing: Fraunces
359
+ * display serif for section titles, Plus Jakarta body, hairline
360
+ * borders, soft long shadows, brand-teal accents, one calm reveal.
361
+ * ──────────────────────────────────────────────────────────────────── */
362
+
363
+ /* Slide-over panel shell (profile / marketplace). Quiet paper, a faint
364
+ * top teal wash so it reads as a lifted "sheet", not a flat overlay. */
365
+ .app-panel {
366
+ position: relative;
367
+ font-family: var(--font-sans);
368
+ background:
369
+ radial-gradient(110% 50% at 50% -8%,
370
+ color-mix(in srgb, var(--primary) 7%, transparent) 0%,
371
+ transparent 55%),
372
+ var(--background);
373
+ }
374
+
375
+ /* Chaptered panel header β€” kicker + serif title, mirrors .section-num. */
376
+ .panel-kicker {
377
+ display: inline-flex;
378
+ align-items: center;
379
+ gap: 7px;
380
+ font-size: 10.5px;
381
+ font-weight: 600;
382
+ letter-spacing: 0.14em;
383
+ text-transform: uppercase;
384
+ color: color-mix(in srgb, var(--primary) 78%, var(--muted-foreground));
385
+ }
386
+ .panel-kicker .dot {
387
+ width: 5px;
388
+ height: 5px;
389
+ border-radius: 999px;
390
+ background: var(--primary);
391
+ }
392
+ .panel-title {
393
+ font-family: var(--font-serif);
394
+ font-optical-sizing: auto;
395
+ font-variation-settings: "SOFT" 40, "WONK" 0;
396
+ letter-spacing: -0.012em;
397
+ font-weight: 600;
398
+ }
399
+
400
+ /* A profile "fieldset" β€” one numbered chapter of the form. Hairline
401
+ * card, soft long shadow, a serif step index in a tinted medallion so
402
+ * the form reads as a guided journey, not a wall of inputs. */
403
+ .field-group {
404
+ position: relative;
405
+ border-radius: 18px;
406
+ border: 1px solid var(--border);
407
+ background:
408
+ linear-gradient(180deg,
409
+ color-mix(in srgb, var(--primary) 4%, var(--card)) 0%,
410
+ var(--card) 38%);
411
+ box-shadow:
412
+ 0 1px 2px color-mix(in srgb, var(--foreground) 4%, transparent),
413
+ 0 16px 40px -32px color-mix(in srgb, var(--foreground) 28%, transparent);
414
+ transition: border-color .22s ease, box-shadow .22s ease;
415
+ }
416
+ .field-group:focus-within {
417
+ border-color: color-mix(in srgb, var(--primary) 32%, var(--border));
418
+ box-shadow:
419
+ 0 1px 2px color-mix(in srgb, var(--foreground) 4%, transparent),
420
+ 0 18px 44px -28px color-mix(in srgb, var(--primary) 36%, transparent);
421
+ }
422
+ .field-medallion {
423
+ width: 30px;
424
+ height: 30px;
425
+ border-radius: 10px;
426
+ display: flex;
427
+ align-items: center;
428
+ justify-content: center;
429
+ font-family: var(--font-serif);
430
+ font-size: 14px;
431
+ font-weight: 600;
432
+ color: var(--primary-foreground);
433
+ background: linear-gradient(150deg,
434
+ color-mix(in srgb, var(--primary) 92%, white) 0%,
435
+ var(--primary) 55%,
436
+ color-mix(in srgb, var(--primary) 80%, black) 100%);
437
+ box-shadow:
438
+ 0 2px 5px color-mix(in srgb, var(--primary) 36%, transparent),
439
+ 0 0 0 4px color-mix(in srgb, var(--primary) 9%, transparent);
440
+ }
441
+
442
+ /* Selectable option pill β€” replaces the ad-hoc chip classes. Crisp
443
+ * hairline, brand fill on select, a soft press feel. */
444
+ .opt-pill {
445
+ display: inline-flex;
446
+ align-items: center;
447
+ gap: 6px;
448
+ padding: 7px 13px;
449
+ border-radius: 999px;
450
+ border: 1px solid var(--border);
451
+ background: var(--card);
452
+ font-size: 12px;
453
+ font-weight: 500;
454
+ color: var(--foreground);
455
+ cursor: pointer;
456
+ transition: transform .15s cubic-bezier(.2,.7,.3,1),
457
+ border-color .15s ease, background .15s ease, color .15s ease,
458
+ box-shadow .15s ease;
459
+ }
460
+ .opt-pill:hover {
461
+ border-color: color-mix(in srgb, var(--primary) 40%, var(--border));
462
+ }
463
+ .opt-pill:active { transform: scale(.97); }
464
+ .opt-pill[data-on="true"] {
465
+ border-color: var(--primary);
466
+ background: var(--primary);
467
+ color: var(--primary-foreground);
468
+ box-shadow: 0 6px 16px -8px color-mix(in srgb, var(--primary) 60%, transparent);
469
+ }
470
+ .opt-pill:focus-visible {
471
+ outline: 2px solid var(--primary);
472
+ outline-offset: 2px;
473
+ }
474
+
475
+ /* Text / number field β€” single shared input look. */
476
+ .app-input {
477
+ width: 100%;
478
+ font-size: 14px;
479
+ padding: 9px 12px;
480
+ border-radius: 11px;
481
+ border: 1px solid var(--border);
482
+ background: var(--card);
483
+ color: var(--foreground);
484
+ transition: border-color .18s ease, box-shadow .18s ease;
485
+ }
486
+ .app-input::placeholder { color: var(--muted-foreground); }
487
+ .app-input:focus {
488
+ outline: none;
489
+ border-color: var(--primary);
490
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary) 14%, transparent);
491
+ }
492
+
493
+ /* Brand range slider β€” themed track + thumb so it stops looking like a
494
+ * raw OS control next to the editorial type. */
495
+ .app-range {
496
+ -webkit-appearance: none;
497
+ appearance: none;
498
+ width: 100%;
499
+ height: 6px;
500
+ border-radius: 999px;
501
+ background: color-mix(in srgb, var(--primary) 16%, var(--border));
502
+ outline: none;
503
+ }
504
+ .app-range::-webkit-slider-thumb {
505
+ -webkit-appearance: none;
506
+ appearance: none;
507
+ width: 18px;
508
+ height: 18px;
509
+ border-radius: 999px;
510
+ background: var(--primary);
511
+ border: 3px solid var(--card);
512
+ box-shadow: 0 1px 4px color-mix(in srgb, var(--primary) 50%, transparent);
513
+ cursor: pointer;
514
+ }
515
+ .app-range::-moz-range-thumb {
516
+ width: 16px;
517
+ height: 16px;
518
+ border-radius: 999px;
519
+ background: var(--primary);
520
+ border: 3px solid var(--card);
521
+ cursor: pointer;
522
+ }
523
+
524
+ /* Conditional sub-block (parents detail) β€” a tinted inset rail. */
525
+ .subfield {
526
+ border-radius: 14px;
527
+ border: 1px solid color-mix(in srgb, var(--primary) 20%, var(--border));
528
+ background: color-mix(in srgb, var(--primary) 5%, var(--card));
529
+ }
530
+
531
+ /* Sticky save bar β€” frosted, lifted off the form. */
532
+ .save-bar {
533
+ background: color-mix(in srgb, var(--card) 86%, transparent);
534
+ -webkit-backdrop-filter: saturate(180%) blur(10px);
535
+ backdrop-filter: saturate(180%) blur(10px);
536
+ border-top: 1px solid var(--border);
537
+ }
538
+ .btn-primary {
539
+ font-weight: 600;
540
+ border-radius: 12px;
541
+ color: var(--primary-foreground);
542
+ background: linear-gradient(150deg,
543
+ color-mix(in srgb, var(--primary) 94%, white) 0%,
544
+ var(--primary) 60%);
545
+ box-shadow: 0 8px 20px -10px color-mix(in srgb, var(--primary) 60%, transparent);
546
+ transition: transform .15s ease, box-shadow .15s ease, opacity .15s ease;
547
+ }
548
+ .btn-primary:hover:not(:disabled) { transform: translateY(-1px); }
549
+ .btn-primary:disabled { opacity: .5; cursor: not-allowed; }
550
+
551
+ /* CHAT bubbles β€” the assistant reads as a calm "letter" on paper, the
552
+ * user as a brand slab. Both lifted, both with a soft tail-less radius. */
553
+ .bubble-assistant {
554
+ border-radius: 18px 18px 18px 6px;
555
+ border: 1px solid var(--border);
556
+ background:
557
+ linear-gradient(180deg,
558
+ color-mix(in srgb, var(--primary) 3.5%, var(--card)) 0%,
559
+ var(--card) 36%);
560
+ box-shadow:
561
+ 0 1px 2px color-mix(in srgb, var(--foreground) 4%, transparent),
562
+ 0 14px 36px -30px color-mix(in srgb, var(--foreground) 26%, transparent);
563
+ }
564
+ .bubble-user {
565
+ border-radius: 18px 18px 6px 18px;
566
+ color: var(--primary-foreground);
567
+ background: linear-gradient(150deg,
568
+ color-mix(in srgb, var(--primary) 92%, white) 0%,
569
+ var(--primary) 62%);
570
+ box-shadow: 0 10px 26px -14px color-mix(in srgb, var(--primary) 55%, transparent);
571
+ }
572
+
573
+ /* Cited-policy card β€” hairline, lifts to a teal-tinted long shadow. */
574
+ .cited-card {
575
+ border-radius: 14px;
576
+ border: 1px solid var(--border);
577
+ background: var(--card);
578
+ transition: transform .2s cubic-bezier(.2,.7,.3,1),
579
+ border-color .2s ease, box-shadow .2s ease;
580
+ }
581
+ .cited-card:hover {
582
+ transform: translateY(-2px);
583
+ border-color: color-mix(in srgb, var(--primary) 32%, var(--border));
584
+ box-shadow: 0 16px 34px -24px color-mix(in srgb, var(--primary) 42%, transparent);
585
+ }
586
+
587
+ /* Marketplace policy card β€” same lift language as the step cards. */
588
+ .policy-card {
589
+ border-radius: 16px;
590
+ border: 1px solid var(--border);
591
+ background:
592
+ linear-gradient(180deg,
593
+ color-mix(in srgb, var(--primary) 3.5%, var(--card)) 0%,
594
+ var(--card) 40%);
595
+ transition: transform .2s cubic-bezier(.2,.7,.3,1),
596
+ border-color .2s ease, box-shadow .2s ease;
597
+ }
598
+ .policy-card:hover {
599
+ transform: translateY(-3px);
600
+ border-color: color-mix(in srgb, var(--primary) 34%, var(--border));
601
+ box-shadow:
602
+ 0 1px 2px color-mix(in srgb, var(--foreground) 4%, transparent),
603
+ 0 22px 44px -26px color-mix(in srgb, var(--primary) 44%, transparent);
604
+ }
605
+ .policy-card[data-selected="true"] {
606
+ border-color: var(--primary);
607
+ box-shadow: 0 18px 40px -22px color-mix(in srgb, var(--primary) 50%, transparent);
608
+ }
609
+
610
+ /* Filter shell + sticky compare bar share the frosted treatment. */
611
+ .filter-shell {
612
+ border-radius: 18px;
613
+ border: 1px solid var(--border);
614
+ background: var(--card);
615
+ box-shadow: 0 1px 2px color-mix(in srgb, var(--foreground) 4%, transparent);
616
+ }
617
+
618
  /* Honour reduced-motion preference: drop the hover-lift transition on the
619
  * landing step / mode / callout cards for vestibular-sensitive users. */
620
  @media (prefers-reduced-motion: reduce) {
621
+ .step-card, .mode-row, .callout-card, .chip-tile,
622
+ .field-group, .opt-pill, .cited-card, .policy-card, .btn-primary {
623
  transition: none !important;
624
  }
625
+ .step-card:hover, .mode-row:hover, .callout-card:hover,
626
+ .cited-card:hover, .policy-card:hover, .btn-primary:hover {
627
  transform: none !important;
628
  }
629
+ .reveal {
630
+ opacity: 1 !important;
631
+ animation: none !important;
632
+ }
633
+ .kicker .dot { animation: none !important; }
634
  }
frontend/src/app/layout.tsx CHANGED
@@ -1,6 +1,31 @@
1
  import type { Metadata, Viewport } from "next";
 
2
  import "./globals.css";
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  export const metadata: Metadata = {
5
  title: "Insurance Sales Portfolio Expert",
6
  description:
@@ -21,7 +46,10 @@ export default function RootLayout({
21
  children,
22
  }: Readonly<{ children: React.ReactNode }>) {
23
  return (
24
- <html lang="en" className="h-full antialiased">
 
 
 
25
  <body className="min-h-full flex flex-col">{children}</body>
26
  </html>
27
  );
 
1
  import type { Metadata, Viewport } from "next";
2
+ import { Fraunces, Plus_Jakarta_Sans } from "next/font/google";
3
  import "./globals.css";
4
 
5
+ // Display face β€” Fraunces. A warm, high-contrast "old-style" serif with
6
+ // optical sizing. Gives the landing an editorial, trustworthy character
7
+ // (right for a serious financial decision) and immediately breaks the
8
+ // generic system-font / Inter "AI" look. Used only for the hero + section
9
+ // headings via the --font-display CSS variable.
10
+ const fraunces = Fraunces({
11
+ subsets: ["latin"],
12
+ // Fraunces is a variable font: omit `weight` so the full weight axis is
13
+ // available (next/font forbids `axes` alongside an explicit `weight`).
14
+ axes: ["opsz", "SOFT", "WONK"],
15
+ style: ["normal", "italic"],
16
+ variable: "--font-display",
17
+ display: "swap",
18
+ });
19
+
20
+ // Body / UI face β€” Plus Jakarta Sans. A clean, slightly geometric grotesque
21
+ // with friendly curves; reads well at small sizes for chat + UI chrome.
22
+ const jakarta = Plus_Jakarta_Sans({
23
+ subsets: ["latin"],
24
+ weight: ["400", "500", "600", "700"],
25
+ variable: "--font-body",
26
+ display: "swap",
27
+ });
28
+
29
  export const metadata: Metadata = {
30
  title: "Insurance Sales Portfolio Expert",
31
  description:
 
46
  children,
47
  }: Readonly<{ children: React.ReactNode }>) {
48
  return (
49
+ <html
50
+ lang="en"
51
+ className={`h-full antialiased ${fraunces.variable} ${jakarta.variable}`}
52
+ >
53
  <body className="min-h-full flex flex-col">{children}</body>
54
  </html>
55
  );
frontend/src/app/page.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
frontend/src/components/PolicyCompareModal.tsx CHANGED
@@ -6,8 +6,14 @@
6
  // 2. Premium β€” pluggable widget (B2) via props.renderPremiumFor(policyId)
7
  // 3. Scorecard β€” pluggable widget (B3) via props.renderScorecardFor(policyId)
8
  // 4. Policy details β€” expandable section with source URL
9
- // Visual style copied from MarketplacePanel's PolicyCard so the chat-side
10
- // compare matches the marketplace-side compare (same fonts, borders, radii).
 
 
 
 
 
 
11
 
12
  import { useEffect, useState, type ReactNode } from "react";
13
  import {
@@ -57,7 +63,7 @@ function InsurerLogo({ slug, name, size = 40 }: { slug: string; name: string; si
57
  if (!url || failed) {
58
  return (
59
  <div
60
- className={`rounded-lg ${color} text-white flex items-center justify-center font-bold shrink-0`}
61
  style={{ width: size, height: size, fontSize: size * 0.32 }}
62
  >
63
  {insurerInitials(name)}
@@ -66,8 +72,13 @@ function InsurerLogo({ slug, name, size = 40 }: { slug: string; name: string; si
66
  }
67
  return (
68
  <div
69
- className="rounded-lg bg-white border border-[var(--border)] flex items-center justify-center shrink-0 overflow-hidden p-1"
70
- style={{ width: size, height: size }}
 
 
 
 
 
71
  >
72
  {/* eslint-disable-next-line @next/next/no-img-element */}
73
  <img
@@ -80,15 +91,33 @@ function InsurerLogo({ slug, name, size = 40 }: { slug: string; name: string; si
80
  );
81
  }
82
 
83
- function gradeColor(grade: string): string {
84
- const map: Record<string, string> = {
85
- A: "bg-emerald-500 text-white",
86
- B: "bg-teal-500 text-white",
87
- C: "bg-amber-500 text-white",
88
- D: "bg-orange-500 text-white",
89
- F: "bg-red-500 text-white",
90
- };
91
- return map[grade] || "bg-stone-400 text-white";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  }
93
 
94
  // Dedupe citations by policy_id, preserving order.
@@ -151,31 +180,116 @@ export default function PolicyCompareModal({
151
  const uniq = uniquePolicies(policies).slice(0, 4);
152
  const n = uniq.length;
153
 
 
 
 
 
 
 
 
 
 
154
  return (
155
  <div
156
- className="fixed inset-0 z-[70] bg-black/50 flex items-stretch sm:items-center justify-center p-0 sm:p-3 animate-fade-up"
 
 
 
 
 
 
157
  onClick={onClose}
158
  role="dialog"
159
  aria-modal="true"
160
  aria-label={`Compare ${n} polic${n === 1 ? "y" : "ies"}`}
161
  >
162
  <div
163
- className="bg-[var(--card)] sm:rounded-2xl shadow-xl w-full sm:max-w-7xl sm:w-[92vw] max-h-screen sm:max-h-[92vh] overflow-y-auto scrollbar-thin"
 
 
 
 
 
164
  onClick={(e) => e.stopPropagation()}
165
  >
166
- {/* Header */}
167
- <div className="sticky top-0 z-10 bg-[var(--card)] border-b border-[var(--border)] px-5 py-4 flex items-center justify-between">
168
- <div>
169
- <h3 className="text-base font-bold">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  Compare {n} polic{n === 1 ? "y" : "ies"}
171
  </h3>
172
- <p className="text-[11px] text-[var(--muted-foreground)] mt-0.5">
173
- Premiums, fit scores and policy details β€” side-by-side.
 
 
 
 
 
 
 
174
  </p>
175
  </div>
176
  <button
177
  onClick={onClose}
178
- className="text-[var(--muted-foreground)] hover:text-[var(--foreground)] text-2xl leading-none ml-2"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  aria-label="Close comparison"
180
  >
181
  Γ—
@@ -183,9 +297,9 @@ export default function PolicyCompareModal({
183
  </div>
184
 
185
  {/* Body: 1 col on mobile, n cols on desktop */}
186
- <div className="p-4 sm:p-5">
187
  <div
188
- className="grid gap-4 grid-cols-1"
189
  style={{
190
  gridTemplateColumns:
191
  n > 1 ? `repeat(${n}, minmax(0, 1fr))` : undefined,
@@ -204,8 +318,21 @@ export default function PolicyCompareModal({
204
  </div>
205
 
206
  {/* Footer */}
207
- <div className="sticky bottom-0 bg-[var(--card)] border-t border-[var(--border)] px-5 py-3 flex items-center justify-between text-xs">
208
- <span className="text-[var(--muted-foreground)]">
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  Comparing the policies cited in this reply. Open the full
210
  marketplace for filters and 30+ more options.
211
  </span>
@@ -214,7 +341,13 @@ export default function PolicyCompareModal({
214
  onOpenMarketplace?.();
215
  onClose();
216
  }}
217
- className="font-semibold text-[var(--primary)] hover:underline"
 
 
 
 
 
 
218
  >
219
  Open in full marketplace β†’
220
  </button>
@@ -242,19 +375,59 @@ function CompareColumn({
242
  const insurerName =
243
  marketplacePolicy?.insurer_name ?? citation.insurer_slug.replace(/-/g, " ");
244
  return (
245
- <div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-4 flex flex-col gap-4 min-w-0">
 
 
 
 
 
 
 
 
 
 
246
  {/* Header β€” logo + insurer + policy name */}
247
- <div className="flex items-start gap-3">
248
- <InsurerLogo slug={citation.insurer_slug} name={insurerName} size={40} />
249
  <div className="flex-1 min-w-0">
250
- <div className="text-[10px] uppercase tracking-wider text-[var(--muted-foreground)] truncate">
 
 
 
 
 
 
 
 
 
251
  {insurerName}
252
  </div>
253
- <div className="font-semibold text-sm leading-tight break-words">
 
 
 
 
 
 
 
 
 
 
 
 
254
  {citation.policy_name}
255
  </div>
256
  {marketplacePolicy?.aliases && marketplacePolicy.aliases.length > 0 && (
257
- <div className="text-[11px] text-slate-500 italic mt-0.5 break-words">
 
 
 
 
 
 
 
 
 
258
  Also marketed as: {marketplacePolicy.aliases.join(", ")}
259
  </div>
260
  )}
@@ -296,7 +469,7 @@ function PolicyHighlights({ policy }: { policy: MarketplacePolicy }) {
296
  : null;
297
  const siDisplay = maxSI
298
  ? maxSI >= 10_000_000
299
- ? `${maxSI / 10_000_000} cr`
300
  : `${maxSI / 100_000} L`
301
  : "β€”";
302
  const network = policy.network_hospital_count
@@ -335,17 +508,47 @@ function PolicyHighlights({ policy }: { policy: MarketplacePolicy }) {
335
 
336
  return (
337
  <Section title="Policy highlights">
338
- <div className="grid grid-cols-2 gap-2 text-xs">
339
  <MiniStat label="Sum insured" value={siDisplay} />
340
  <MiniStat label="PED waiting" value={pedWait} />
341
  <MiniStat label="Network" value={network} />
342
  <MiniStat label="Cashless" value={cashless} />
343
  </div>
344
  {bullets.length > 0 && (
345
- <ul className="mt-2.5 space-y-1 text-[11px] text-[var(--foreground)] leading-snug">
 
 
 
 
 
 
 
 
 
 
346
  {bullets.slice(0, 4).map((b, i) => (
347
- <li key={i} className="flex items-start gap-1.5">
348
- <span className="text-[var(--primary)] mt-[1px]">β€’</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
  <span>{b}</span>
350
  </li>
351
  ))}
@@ -357,20 +560,75 @@ function PolicyHighlights({ policy }: { policy: MarketplacePolicy }) {
357
 
358
  function MiniStat({ label, value }: { label: string; value: string }) {
359
  return (
360
- <div>
361
- <div className="text-[10px] text-[var(--muted-foreground)] uppercase tracking-wide">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
  {label}
363
  </div>
364
- <div className="text-xs font-semibold">{value}</div>
 
 
 
 
 
 
 
 
 
 
365
  </div>
366
  );
367
  }
368
 
 
 
369
  function Section({ title, children }: { title: string; children: ReactNode }) {
370
  return (
371
  <div>
372
- <div className="text-[10px] uppercase tracking-wider text-[var(--muted-foreground)] font-semibold mb-1.5">
373
- {title}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
  </div>
375
  {children}
376
  </div>
@@ -379,7 +637,17 @@ function Section({ title, children }: { title: string; children: ReactNode }) {
379
 
380
  function PlaceholderWidget({ label }: { label: string }) {
381
  return (
382
- <div className="bg-[var(--muted)] border border-dashed border-[var(--border)] rounded-lg px-3 py-4 text-center text-[11px] text-[var(--muted-foreground)]">
 
 
 
 
 
 
 
 
 
 
383
  {label}
384
  </div>
385
  );
@@ -416,24 +684,68 @@ function ScorecardFallback({ policyId }: { policyId: string }) {
416
  if (error || !sc) {
417
  return <PlaceholderWidget label="Scorecard unavailable" />;
418
  }
 
419
  return (
420
- <div className="bg-[var(--muted)] border border-[var(--border)] rounded-lg p-3">
421
- <div className="flex items-center gap-2">
 
 
 
 
 
 
 
422
  <span
423
- className={`inline-flex items-center justify-center w-9 h-9 rounded-md font-bold text-sm ${gradeColor(
424
- sc.grade,
425
- )}`}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426
  >
427
  {sc.grade}
428
  </span>
429
- <div className="min-w-0">
430
- <div className="text-sm font-semibold leading-tight">
 
 
 
 
 
 
 
 
431
  {sc.overall_score}
432
- <span className="text-[var(--muted-foreground)] text-[10px] font-normal">
433
- /100
 
 
 
 
 
 
 
434
  </span>
435
  </div>
436
- <div className="text-[10px] text-[var(--muted-foreground)] truncate">
 
 
 
 
 
 
 
437
  {sc.one_liner}
438
  </div>
439
  </div>
@@ -452,33 +764,97 @@ function PolicyDetails({ citation }: { citation: Citation }) {
452
  : `pp. ${citation.page_start}–${citation.page_end}`
453
  : null;
454
  return (
455
- <div className="border border-[var(--border)] rounded-lg bg-[var(--card)]">
 
 
 
 
 
 
 
456
  <button
457
  onClick={() => setOpen((v) => !v)}
458
- className="w-full text-left px-3 py-2 text-[11px] font-semibold flex items-center justify-between hover:bg-[var(--muted)] rounded-lg"
 
 
 
 
 
 
 
 
 
 
 
 
459
  aria-expanded={open}
460
  >
461
- <span className="uppercase tracking-wider text-[var(--muted-foreground)]">
 
 
 
 
 
 
 
 
 
462
  Policy details
463
  </span>
464
- <span className="text-[var(--muted-foreground)]">{open ? "βˆ’" : "+"}</span>
 
 
 
 
 
 
 
 
 
 
465
  </button>
466
  {open && (
467
- <div className="px-3 pb-3 pt-1 border-t border-[var(--border)] space-y-2 text-[11px]">
 
 
 
 
 
 
 
 
468
  <DetailRow label="Policy" value={citation.policy_name} />
469
- <DetailRow label="Insurer" value={citation.insurer_slug.replace(/-/g, " ")} />
 
 
 
470
  {pageRange && <DetailRow label="Cited" value={pageRange} />}
471
  {hasSource ? (
472
  <a
473
  href={citation.source_url}
474
  target="_blank"
475
  rel="noopener"
476
- className="inline-flex items-center gap-1 text-[var(--primary)] hover:underline font-semibold"
 
 
 
 
 
 
 
 
 
477
  >
478
  Open policy PDF β†’
479
  </a>
480
  ) : (
481
- <span className="text-[var(--muted-foreground)] italic">
 
 
 
 
 
 
482
  No source PDF link available
483
  </span>
484
  )}
@@ -490,11 +866,30 @@ function PolicyDetails({ citation }: { citation: Citation }) {
490
 
491
  function DetailRow({ label, value }: { label: string; value: string }) {
492
  return (
493
- <div className="flex gap-2">
494
- <span className="text-[var(--muted-foreground)] uppercase tracking-wide text-[10px] w-16 shrink-0">
 
 
 
 
 
 
 
 
 
 
 
495
  {label}
496
  </span>
497
- <span className="text-[var(--foreground)] break-words">{value}</span>
 
 
 
 
 
 
 
 
498
  </div>
499
  );
500
  }
 
6
  // 2. Premium β€” pluggable widget (B2) via props.renderPremiumFor(policyId)
7
  // 3. Scorecard β€” pluggable widget (B3) via props.renderScorecardFor(policyId)
8
  // 4. Policy details β€” expandable section with source URL
9
+ //
10
+ // ── Visual system ─────────────────────────────────────────────────────
11
+ // Re-grounded on the premium editorial-fintech landing (app/globals.css):
12
+ // Fraunces display serif via `.font-display` for the modal title, the teal
13
+ // --primary token, color-mix soft depth shadows, the kicker-pill pattern
14
+ // for section eyebrows, and tight one-line fact bullets. Everything reads
15
+ // from CSS variables so the modal tracks the page's light/dark scheme. The
16
+ // grade chip uses the same calm A→F ramp as PolicyScorecardWidget.
17
 
18
  import { useEffect, useState, type ReactNode } from "react";
19
  import {
 
63
  if (!url || failed) {
64
  return (
65
  <div
66
+ className={`rounded-xl ${color} text-white flex items-center justify-center font-bold shrink-0`}
67
  style={{ width: size, height: size, fontSize: size * 0.32 }}
68
  >
69
  {insurerInitials(name)}
 
72
  }
73
  return (
74
  <div
75
+ className="rounded-xl bg-white border border-[var(--border)] flex items-center justify-center shrink-0 overflow-hidden p-1.5"
76
+ style={{
77
+ width: size,
78
+ height: size,
79
+ boxShadow:
80
+ "0 1px 2px color-mix(in srgb, var(--foreground) 6%, transparent)",
81
+ }}
82
  >
83
  {/* eslint-disable-next-line @next/next/no-img-element */}
84
  <img
 
91
  );
92
  }
93
 
94
+ // Calm A→F ramp — the same tonal family as PolicyScorecardWidget so the
95
+ // chip in the column header matches the full scorecard below it. "A" is the
96
+ // brand teal; the rest walk a quiet green→amber→red gradient.
97
+ function gradeChip(grade: string): { fg: string; bg: string; ring: string } {
98
+ const head = (grade || "").charAt(0).toUpperCase();
99
+ switch (head) {
100
+ case "A":
101
+ return {
102
+ fg: "color-mix(in srgb, var(--primary) 82%, #042f2a)",
103
+ bg: "color-mix(in srgb, var(--primary) 14%, var(--card))",
104
+ ring: "color-mix(in srgb, var(--primary) 55%, var(--border))",
105
+ };
106
+ case "B":
107
+ return { fg: "#155e63", bg: "#e3f4f3", ring: "#3d9c98" };
108
+ case "C":
109
+ return { fg: "#855316", bg: "#fbeed2", ring: "#cf9b3f" };
110
+ case "D":
111
+ return { fg: "#8a3c12", bg: "#fae0cd", ring: "#d4793b" };
112
+ case "F":
113
+ return { fg: "#8a2020", bg: "#f8d9d9", ring: "#cf4b4b" };
114
+ default:
115
+ return {
116
+ fg: "var(--muted-foreground)",
117
+ bg: "var(--muted)",
118
+ ring: "var(--border)",
119
+ };
120
+ }
121
  }
122
 
123
  // Dedupe citations by policy_id, preserving order.
 
180
  const uniq = uniquePolicies(policies).slice(0, 4);
181
  const n = uniq.length;
182
 
183
+ // Close on Escape β€” keyboard parity with the click-outside backdrop.
184
+ useEffect(() => {
185
+ const onKey = (e: KeyboardEvent) => {
186
+ if (e.key === "Escape") onClose();
187
+ };
188
+ window.addEventListener("keydown", onKey);
189
+ return () => window.removeEventListener("keydown", onKey);
190
+ }, [onClose]);
191
+
192
  return (
193
  <div
194
+ className="fixed inset-0 z-[70] flex items-stretch sm:items-center justify-center p-0 sm:p-4 animate-fade-up"
195
+ style={{
196
+ background:
197
+ "color-mix(in srgb, var(--foreground) 48%, transparent)",
198
+ backdropFilter: "blur(3px)",
199
+ WebkitBackdropFilter: "blur(3px)",
200
+ }}
201
  onClick={onClose}
202
  role="dialog"
203
  aria-modal="true"
204
  aria-label={`Compare ${n} polic${n === 1 ? "y" : "ies"}`}
205
  >
206
  <div
207
+ className="bg-[var(--card)] sm:rounded-3xl w-full sm:max-w-7xl sm:w-[92vw] max-h-screen sm:max-h-[92vh] overflow-y-auto scrollbar-thin"
208
+ style={{
209
+ border: "1px solid var(--border)",
210
+ boxShadow:
211
+ "0 1px 2px color-mix(in srgb, var(--foreground) 6%, transparent), 0 40px 90px -40px color-mix(in srgb, var(--foreground) 55%, transparent)",
212
+ }}
213
  onClick={(e) => e.stopPropagation()}
214
  >
215
+ {/* Header β€” Fraunces display title + brand-tinted eyebrow */}
216
+ <div
217
+ className="sticky top-0 z-10 px-5 sm:px-6 py-4 flex items-start justify-between gap-4"
218
+ style={{
219
+ background:
220
+ "linear-gradient(180deg, color-mix(in srgb, var(--primary) 6%, var(--card)) 0%, var(--card) 100%)",
221
+ borderBottom: "1px solid var(--border)",
222
+ }}
223
+ >
224
+ <div className="min-w-0">
225
+ <div
226
+ className="inline-flex items-center gap-2 mb-2"
227
+ style={{
228
+ padding: "4px 10px 4px 9px",
229
+ borderRadius: 999,
230
+ fontSize: 10,
231
+ fontWeight: 600,
232
+ letterSpacing: "0.12em",
233
+ textTransform: "uppercase",
234
+ color: "var(--primary)",
235
+ background:
236
+ "color-mix(in srgb, var(--primary) 9%, var(--card))",
237
+ border:
238
+ "1px solid color-mix(in srgb, var(--primary) 22%, var(--border))",
239
+ }}
240
+ >
241
+ <span
242
+ aria-hidden
243
+ style={{
244
+ width: 5,
245
+ height: 5,
246
+ borderRadius: 999,
247
+ background: "var(--primary)",
248
+ }}
249
+ />
250
+ Side-by-side
251
+ </div>
252
+ <h3
253
+ className="font-display"
254
+ style={{
255
+ fontSize: 22,
256
+ fontWeight: 600,
257
+ color: "var(--foreground)",
258
+ lineHeight: 1.15,
259
+ letterSpacing: "-0.012em",
260
+ }}
261
+ >
262
  Compare {n} polic{n === 1 ? "y" : "ies"}
263
  </h3>
264
+ <p
265
+ style={{
266
+ fontSize: 12,
267
+ color: "var(--muted-foreground)",
268
+ marginTop: 4,
269
+ lineHeight: 1.4,
270
+ }}
271
+ >
272
+ Premiums, fit scores and policy details β€” aligned side-by-side.
273
  </p>
274
  </div>
275
  <button
276
  onClick={onClose}
277
+ className="shrink-0"
278
+ style={{
279
+ width: 34,
280
+ height: 34,
281
+ borderRadius: 999,
282
+ display: "flex",
283
+ alignItems: "center",
284
+ justifyContent: "center",
285
+ fontSize: 20,
286
+ lineHeight: 1,
287
+ color: "var(--muted-foreground)",
288
+ background: "var(--card)",
289
+ border: "1px solid var(--border)",
290
+ cursor: "pointer",
291
+ transition: "color .15s ease, border-color .15s ease",
292
+ }}
293
  aria-label="Close comparison"
294
  >
295
  Γ—
 
297
  </div>
298
 
299
  {/* Body: 1 col on mobile, n cols on desktop */}
300
+ <div className="p-4 sm:p-6">
301
  <div
302
+ className="grid gap-4 sm:gap-5 grid-cols-1"
303
  style={{
304
  gridTemplateColumns:
305
  n > 1 ? `repeat(${n}, minmax(0, 1fr))` : undefined,
 
318
  </div>
319
 
320
  {/* Footer */}
321
+ <div
322
+ className="sticky bottom-0 px-5 sm:px-6 py-3.5 flex flex-wrap items-center justify-between gap-2"
323
+ style={{
324
+ background:
325
+ "linear-gradient(0deg, color-mix(in srgb, var(--primary) 5%, var(--card)) 0%, var(--card) 100%)",
326
+ borderTop: "1px solid var(--border)",
327
+ }}
328
+ >
329
+ <span
330
+ style={{
331
+ fontSize: 11.5,
332
+ color: "var(--muted-foreground)",
333
+ lineHeight: 1.4,
334
+ }}
335
+ >
336
  Comparing the policies cited in this reply. Open the full
337
  marketplace for filters and 30+ more options.
338
  </span>
 
341
  onOpenMarketplace?.();
342
  onClose();
343
  }}
344
+ className="hover:underline"
345
+ style={{
346
+ fontSize: 12.5,
347
+ fontWeight: 600,
348
+ color: "var(--primary)",
349
+ cursor: "pointer",
350
+ }}
351
  >
352
  Open in full marketplace β†’
353
  </button>
 
375
  const insurerName =
376
  marketplacePolicy?.insurer_name ?? citation.insurer_slug.replace(/-/g, " ");
377
  return (
378
+ <div
379
+ className="flex flex-col gap-4 min-w-0"
380
+ style={{
381
+ background: "var(--card)",
382
+ border: "1px solid var(--border)",
383
+ borderRadius: 18,
384
+ padding: 18,
385
+ boxShadow:
386
+ "0 1px 2px color-mix(in srgb, var(--foreground) 4%, transparent), 0 18px 44px -34px color-mix(in srgb, var(--foreground) 30%, transparent)",
387
+ }}
388
+ >
389
  {/* Header β€” logo + insurer + policy name */}
390
+ <div className="flex items-start gap-3 pb-4" style={{ borderBottom: "1px solid var(--border)" }}>
391
+ <InsurerLogo slug={citation.insurer_slug} name={insurerName} size={44} />
392
  <div className="flex-1 min-w-0">
393
+ <div
394
+ className="truncate"
395
+ style={{
396
+ fontSize: 10,
397
+ textTransform: "uppercase",
398
+ letterSpacing: "0.1em",
399
+ color: "var(--muted-foreground)",
400
+ fontWeight: 600,
401
+ }}
402
+ >
403
  {insurerName}
404
  </div>
405
+ <div
406
+ className="break-words"
407
+ style={{
408
+ fontFamily: "var(--font-serif)",
409
+ fontOpticalSizing: "auto",
410
+ fontSize: 16,
411
+ fontWeight: 600,
412
+ color: "var(--foreground)",
413
+ lineHeight: 1.25,
414
+ letterSpacing: "-0.01em",
415
+ marginTop: 3,
416
+ }}
417
+ >
418
  {citation.policy_name}
419
  </div>
420
  {marketplacePolicy?.aliases && marketplacePolicy.aliases.length > 0 && (
421
+ <div
422
+ className="break-words"
423
+ style={{
424
+ fontSize: 11,
425
+ color: "var(--muted-foreground)",
426
+ fontStyle: "italic",
427
+ marginTop: 4,
428
+ lineHeight: 1.4,
429
+ }}
430
+ >
431
  Also marketed as: {marketplacePolicy.aliases.join(", ")}
432
  </div>
433
  )}
 
469
  : null;
470
  const siDisplay = maxSI
471
  ? maxSI >= 10_000_000
472
+ ? `${maxSI / 10_000_000} Cr`
473
  : `${maxSI / 100_000} L`
474
  : "β€”";
475
  const network = policy.network_hospital_count
 
508
 
509
  return (
510
  <Section title="Policy highlights">
511
+ <div className="grid grid-cols-2 gap-2.5">
512
  <MiniStat label="Sum insured" value={siDisplay} />
513
  <MiniStat label="PED waiting" value={pedWait} />
514
  <MiniStat label="Network" value={network} />
515
  <MiniStat label="Cashless" value={cashless} />
516
  </div>
517
  {bullets.length > 0 && (
518
+ <ul
519
+ className="mt-3"
520
+ style={{
521
+ margin: "12px 0 0",
522
+ padding: 0,
523
+ listStyle: "none",
524
+ display: "flex",
525
+ flexDirection: "column",
526
+ gap: 7,
527
+ }}
528
+ >
529
  {bullets.slice(0, 4).map((b, i) => (
530
+ <li
531
+ key={i}
532
+ style={{
533
+ display: "flex",
534
+ alignItems: "flex-start",
535
+ gap: 8,
536
+ fontSize: 11.5,
537
+ color: "var(--foreground)",
538
+ lineHeight: 1.4,
539
+ }}
540
+ >
541
+ <span
542
+ aria-hidden
543
+ style={{
544
+ flex: "none",
545
+ marginTop: 6,
546
+ width: 5,
547
+ height: 5,
548
+ borderRadius: 999,
549
+ background: "var(--primary)",
550
+ }}
551
+ />
552
  <span>{b}</span>
553
  </li>
554
  ))}
 
560
 
561
  function MiniStat({ label, value }: { label: string; value: string }) {
562
  return (
563
+ <div
564
+ style={{
565
+ background: "color-mix(in srgb, var(--primary) 4%, var(--muted))",
566
+ border: "1px solid var(--border)",
567
+ borderRadius: 12,
568
+ padding: "9px 11px",
569
+ }}
570
+ >
571
+ <div
572
+ style={{
573
+ fontSize: 9.5,
574
+ color: "var(--muted-foreground)",
575
+ textTransform: "uppercase",
576
+ letterSpacing: "0.08em",
577
+ fontWeight: 600,
578
+ }}
579
+ >
580
  {label}
581
  </div>
582
+ <div
583
+ style={{
584
+ fontSize: 14,
585
+ fontWeight: 700,
586
+ color: "var(--foreground)",
587
+ marginTop: 3,
588
+ fontVariantNumeric: "tabular-nums",
589
+ }}
590
+ >
591
+ {value}
592
+ </div>
593
  </div>
594
  );
595
  }
596
 
597
+ // Section header β€” a brand-tinted eyebrow with a hairline rule that grows
598
+ // from the label, echoing the landing's "titled chapter" section pattern.
599
  function Section({ title, children }: { title: string; children: ReactNode }) {
600
  return (
601
  <div>
602
+ <div
603
+ style={{
604
+ display: "flex",
605
+ alignItems: "center",
606
+ gap: 10,
607
+ marginBottom: 10,
608
+ }}
609
+ >
610
+ <span
611
+ style={{
612
+ fontSize: 10,
613
+ textTransform: "uppercase",
614
+ letterSpacing: "0.12em",
615
+ color:
616
+ "color-mix(in srgb, var(--primary) 70%, var(--muted-foreground))",
617
+ fontWeight: 700,
618
+ whiteSpace: "nowrap",
619
+ }}
620
+ >
621
+ {title}
622
+ </span>
623
+ <span
624
+ aria-hidden
625
+ style={{
626
+ flex: 1,
627
+ height: 1,
628
+ background:
629
+ "linear-gradient(90deg, color-mix(in srgb, var(--primary) 28%, var(--border)) 0%, var(--border) 35%, transparent 100%)",
630
+ }}
631
+ />
632
  </div>
633
  {children}
634
  </div>
 
637
 
638
  function PlaceholderWidget({ label }: { label: string }) {
639
  return (
640
+ <div
641
+ style={{
642
+ background: "var(--muted)",
643
+ border: "1px dashed var(--border)",
644
+ borderRadius: 12,
645
+ padding: "16px 12px",
646
+ textAlign: "center",
647
+ fontSize: 11.5,
648
+ color: "var(--muted-foreground)",
649
+ }}
650
+ >
651
  {label}
652
  </div>
653
  );
 
684
  if (error || !sc) {
685
  return <PlaceholderWidget label="Scorecard unavailable" />;
686
  }
687
+ const chip = gradeChip(sc.grade);
688
  return (
689
+ <div
690
+ style={{
691
+ background: "color-mix(in srgb, var(--primary) 3%, var(--muted))",
692
+ border: "1px solid var(--border)",
693
+ borderRadius: 14,
694
+ padding: 14,
695
+ }}
696
+ >
697
+ <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
698
  <span
699
+ style={{
700
+ display: "inline-flex",
701
+ alignItems: "center",
702
+ justifyContent: "center",
703
+ width: 42,
704
+ height: 42,
705
+ borderRadius: 12,
706
+ fontFamily: "var(--font-serif)",
707
+ fontOpticalSizing: "auto",
708
+ fontSize: sc.grade.length > 1 ? 17 : 21,
709
+ fontWeight: 600,
710
+ letterSpacing: "-0.02em",
711
+ color: chip.fg,
712
+ background: chip.bg,
713
+ border: `1px solid ${chip.ring}`,
714
+ flexShrink: 0,
715
+ }}
716
  >
717
  {sc.grade}
718
  </span>
719
+ <div style={{ minWidth: 0 }}>
720
+ <div
721
+ style={{
722
+ fontSize: 15,
723
+ fontWeight: 700,
724
+ color: "var(--foreground)",
725
+ lineHeight: 1.2,
726
+ fontVariantNumeric: "tabular-nums",
727
+ }}
728
+ >
729
  {sc.overall_score}
730
+ <span
731
+ style={{
732
+ color: "var(--muted-foreground)",
733
+ fontSize: 10,
734
+ fontWeight: 500,
735
+ }}
736
+ >
737
+ {" "}
738
+ / 100
739
  </span>
740
  </div>
741
+ <div
742
+ className="truncate"
743
+ style={{
744
+ fontSize: 10.5,
745
+ color: "var(--muted-foreground)",
746
+ marginTop: 2,
747
+ }}
748
+ >
749
  {sc.one_liner}
750
  </div>
751
  </div>
 
764
  : `pp. ${citation.page_start}–${citation.page_end}`
765
  : null;
766
  return (
767
+ <div
768
+ style={{
769
+ border: "1px solid var(--border)",
770
+ borderRadius: 14,
771
+ background: "var(--card)",
772
+ overflow: "hidden",
773
+ }}
774
+ >
775
  <button
776
  onClick={() => setOpen((v) => !v)}
777
+ className="w-full text-left"
778
+ style={{
779
+ padding: "11px 13px",
780
+ display: "flex",
781
+ alignItems: "center",
782
+ justifyContent: "space-between",
783
+ gap: 8,
784
+ background: open
785
+ ? "color-mix(in srgb, var(--primary) 5%, var(--card))"
786
+ : "var(--card)",
787
+ cursor: "pointer",
788
+ transition: "background .15s ease",
789
+ }}
790
  aria-expanded={open}
791
  >
792
+ <span
793
+ style={{
794
+ fontSize: 10,
795
+ textTransform: "uppercase",
796
+ letterSpacing: "0.12em",
797
+ color:
798
+ "color-mix(in srgb, var(--primary) 70%, var(--muted-foreground))",
799
+ fontWeight: 700,
800
+ }}
801
+ >
802
  Policy details
803
  </span>
804
+ <span
805
+ aria-hidden
806
+ style={{
807
+ fontSize: 16,
808
+ lineHeight: 1,
809
+ color: "var(--primary)",
810
+ fontWeight: 500,
811
+ }}
812
+ >
813
+ {open ? "βˆ’" : "+"}
814
+ </span>
815
  </button>
816
  {open && (
817
+ <div
818
+ style={{
819
+ padding: "12px 13px 13px",
820
+ borderTop: "1px solid var(--border)",
821
+ display: "flex",
822
+ flexDirection: "column",
823
+ gap: 9,
824
+ }}
825
+ >
826
  <DetailRow label="Policy" value={citation.policy_name} />
827
+ <DetailRow
828
+ label="Insurer"
829
+ value={citation.insurer_slug.replace(/-/g, " ")}
830
+ />
831
  {pageRange && <DetailRow label="Cited" value={pageRange} />}
832
  {hasSource ? (
833
  <a
834
  href={citation.source_url}
835
  target="_blank"
836
  rel="noopener"
837
+ className="hover:underline"
838
+ style={{
839
+ display: "inline-flex",
840
+ alignItems: "center",
841
+ gap: 5,
842
+ fontSize: 11.5,
843
+ fontWeight: 600,
844
+ color: "var(--primary)",
845
+ marginTop: 2,
846
+ }}
847
  >
848
  Open policy PDF β†’
849
  </a>
850
  ) : (
851
+ <span
852
+ style={{
853
+ fontSize: 11,
854
+ color: "var(--muted-foreground)",
855
+ fontStyle: "italic",
856
+ }}
857
+ >
858
  No source PDF link available
859
  </span>
860
  )}
 
866
 
867
  function DetailRow({ label, value }: { label: string; value: string }) {
868
  return (
869
+ <div style={{ display: "flex", gap: 10 }}>
870
+ <span
871
+ style={{
872
+ fontSize: 9.5,
873
+ textTransform: "uppercase",
874
+ letterSpacing: "0.07em",
875
+ color: "var(--muted-foreground)",
876
+ fontWeight: 600,
877
+ width: 60,
878
+ flexShrink: 0,
879
+ paddingTop: 1,
880
+ }}
881
+ >
882
  {label}
883
  </span>
884
+ <span
885
+ className="break-words"
886
+ style={{
887
+ fontSize: 12,
888
+ color: "var(--foreground)",
889
+ }}
890
+ >
891
+ {value}
892
+ </span>
893
  </div>
894
  );
895
  }
frontend/src/components/PolicyPremiumWidget.tsx CHANGED
@@ -16,6 +16,14 @@
16
  * producing wildly low numbers (~β‚Ή6K) versus the panel's curated number
17
  * (~β‚Ή18-25K) for the same profile. Tenure + deductible are still honoured β€”
18
  * the estimate endpoint now applies the bulk multipliers post-anchor.
 
 
 
 
 
 
 
 
19
  */
20
 
21
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -58,6 +66,11 @@ const SUM_INSURED_STEP = 500_000;
58
  const TENURE_CHOICES = [1, 2, 3] as const;
59
  const DEDUCTIBLE_CHOICES = [0, 25_000, 50_000, 100_000] as const;
60
 
 
 
 
 
 
61
  function formatInr(value: number): string {
62
  // Indian-style 1,23,456 grouping.
63
  return value.toLocaleString("en-IN");
@@ -216,7 +229,7 @@ export default function PolicyPremiumWidget({
216
  const bullets: string[] = [];
217
  if (resp) {
218
  bullets.push(
219
- `Range: β‚Ή${formatInr(resp.low_inr)} – β‚Ή${formatInr(resp.high_inr)}/year (Β±15% band)`,
220
  );
221
  if (resp.tenure_years && resp.tenure_years !== 1) {
222
  bullets.push(`Multi-year discount applied (${resp.tenure_years}-year policy)`);
@@ -230,8 +243,22 @@ export default function PolicyPremiumWidget({
230
 
231
  return (
232
  <div className="policy-premium-widget" style={widgetStyle}>
 
 
 
 
233
  <header style={headerStyle}>
234
- <div style={{ fontWeight: 600, fontSize: 14 }}>{policyName}</div>
 
 
 
 
 
 
 
 
 
 
235
  {/* Curated-only branch: by the time we render this widget,
236
  base_sample_used is guaranteed not false (the !== false branch
237
  short-circuits to NonCuratedPricingNotice above). No "Estimate"
@@ -240,15 +267,15 @@ export default function PolicyPremiumWidget({
240
 
241
  {profileSummary && (
242
  <div style={profileLineStyle}>
243
- Your profile defaults: {profileSummary}
244
  </div>
245
  )}
246
 
247
  <div style={sliderGroupStyle}>
248
  <label style={labelStyle}>
249
  <span style={labelHeadStyle}>
250
- Sum insured
251
- <strong>β‚Ή{formatSiLabel(sumInsured)}</strong>
252
  </span>
253
  <input
254
  type="range"
@@ -268,8 +295,10 @@ export default function PolicyPremiumWidget({
268
 
269
  <label style={labelStyle}>
270
  <span style={labelHeadStyle}>
271
- Tenure
272
- <strong>{tenureYears} {tenureYears === 1 ? "year" : "years"}</strong>
 
 
273
  </span>
274
  <div role="radiogroup" aria-label="Tenure" style={pillRowStyle}>
275
  {TENURE_CHOICES.map((y) => (
@@ -289,8 +318,10 @@ export default function PolicyPremiumWidget({
289
 
290
  <label style={labelStyle}>
291
  <span style={labelHeadStyle}>
292
- Deductible
293
- <strong>{formatDeductibleLabel(deductibleInr)}</strong>
 
 
294
  </span>
295
  <div role="radiogroup" aria-label="Deductible" style={pillRowStyle}>
296
  {DEDUCTIBLE_CHOICES.map((d) => (
@@ -311,21 +342,33 @@ export default function PolicyPremiumWidget({
311
 
312
  <div style={resultBoxStyle} aria-live="polite">
313
  {error ? (
314
- <div style={{ color: "#b00020" }}>Failed: {error}</div>
315
  ) : loading && !resp ? (
316
- <div style={{ color: "#666" }}>Calculating estimate…</div>
 
 
 
317
  ) : resp ? (
318
  <>
319
- <div style={resultHeadlineStyle}>
320
- Estimated premium:&nbsp;
321
- <strong>β‚Ή{formatInr(resp.point_estimate_inr)}</strong>
322
- <span style={resultSuffixStyle}>/year</span>
323
- {loading && <span style={spinnerHintStyle}> updating…</span>}
 
 
 
 
 
 
324
  </div>
325
  {bullets.length > 0 && (
326
  <ul style={breakdownListStyle}>
327
  {bullets.map((b) => (
328
- <li key={b}>{b}</li>
 
 
 
329
  ))}
330
  </ul>
331
  )}
@@ -366,7 +409,7 @@ function NonCuratedPricingNotice({
366
  <header style={noticeHeaderStyle}>
367
  <span style={noticeIconStyle} aria-hidden="true">
368
  {/* info icon β€” pure SVG so we don't pull a new dependency */}
369
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
370
  <circle cx="12" cy="12" r="10" />
371
  <line x1="12" y1="8" x2="12" y2="8" />
372
  <line x1="12" y1="12" x2="12" y2="16" />
@@ -416,18 +459,55 @@ function NonCuratedPricingNotice({
416
 
417
  /* ------------------------------------------------------------------ */
418
  /* Inline styles β€” kept local so the widget drops into any modal */
419
- /* without a CSS-module dependency. */
 
 
 
420
  /* ------------------------------------------------------------------ */
421
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422
  const widgetStyle: React.CSSProperties = {
423
- border: "1px solid #e5e7eb",
424
- borderRadius: 12,
425
- padding: 16,
426
- background: "#fff",
427
  display: "flex",
428
  flexDirection: "column",
429
- gap: 12,
430
- fontFamily: "system-ui, -apple-system, Segoe UI, Roboto, sans-serif",
 
 
431
  };
432
 
433
  const headerStyle: React.CSSProperties = {
@@ -438,178 +518,286 @@ const headerStyle: React.CSSProperties = {
438
  };
439
 
440
  const profileLineStyle: React.CSSProperties = {
441
- fontSize: 12,
442
- color: "#666",
 
443
  };
444
 
445
  const sliderGroupStyle: React.CSSProperties = {
446
  display: "flex",
447
  flexDirection: "column",
448
- gap: 14,
449
  };
450
 
451
  const labelStyle: React.CSSProperties = {
452
  display: "flex",
453
  flexDirection: "column",
454
- gap: 6,
455
  fontSize: 12,
456
- color: "#374151",
457
  };
458
 
459
  const labelHeadStyle: React.CSSProperties = {
460
  display: "flex",
461
- alignItems: "center",
462
  justifyContent: "space-between",
463
- gap: 8,
 
 
 
464
  fontWeight: 500,
 
 
 
 
 
 
 
 
 
 
 
465
  };
466
 
467
  const tickRowStyle: React.CSSProperties = {
468
  display: "flex",
469
  justifyContent: "space-between",
470
- fontSize: 11,
471
- color: "#9ca3af",
 
472
  };
473
 
474
  const pillRowStyle: React.CSSProperties = {
475
  display: "flex",
476
- gap: 6,
477
  flexWrap: "wrap",
478
  };
479
 
480
  const pillStyle = (active: boolean): React.CSSProperties => ({
481
- border: `1px solid ${active ? "#2563eb" : "#d1d5db"}`,
482
- background: active ? "#2563eb" : "#fff",
483
- color: active ? "#fff" : "#374151",
484
- padding: "4px 10px",
 
 
 
 
485
  borderRadius: 999,
486
  fontSize: 12,
 
487
  cursor: "pointer",
 
 
 
 
 
488
  });
489
 
490
  const resultBoxStyle: React.CSSProperties = {
491
- borderTop: "1px solid #f1f5f9",
492
- paddingTop: 12,
493
  display: "flex",
494
  flexDirection: "column",
495
- gap: 8,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496
  };
497
 
498
- const resultHeadlineStyle: React.CSSProperties = {
499
- fontSize: 14,
 
 
 
 
 
 
 
 
 
 
 
 
 
500
  };
501
 
502
  const resultSuffixStyle: React.CSSProperties = {
503
- color: "#6b7280",
504
- fontWeight: 400,
 
505
  };
506
 
507
  const spinnerHintStyle: React.CSSProperties = {
508
- marginLeft: 8,
509
  fontSize: 11,
510
- color: "#9ca3af",
511
  fontStyle: "italic",
512
  };
513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
514
  const breakdownListStyle: React.CSSProperties = {
515
  margin: 0,
516
- paddingLeft: 18,
517
- color: "#4b5563",
 
 
 
 
 
 
 
 
 
 
518
  fontSize: 12,
519
- lineHeight: 1.5,
 
 
 
 
 
 
 
 
 
520
  };
521
 
522
  const noteStyle: React.CSSProperties = {
523
  fontSize: 11,
524
- color: "#6b7280",
525
  fontStyle: "italic",
 
 
526
  };
527
 
528
  /* ---------------- NonCuratedPricingNotice styles ------------------- */
529
  /* Same outer card framing as the slider widget (border + radius + bg) */
530
- /* but with an amber/blue informational accent so users immediately */
531
- /* distinguish "indicative range" from "calculated estimate". */
532
 
533
  const noticeWidgetStyle: React.CSSProperties = {
534
- border: "1px solid #bfdbfe", // soft blue
535
- borderLeft: "4px solid #2563eb", // strong blue accent strip
536
- borderRadius: 12,
537
- padding: 16,
538
- background: "#f8fbff",
539
  display: "flex",
540
  flexDirection: "column",
541
- gap: 10,
542
- fontFamily: "system-ui, -apple-system, Segoe UI, Roboto, sans-serif",
 
 
543
  };
544
 
545
  const noticeHeaderStyle: React.CSSProperties = {
546
  display: "flex",
547
  alignItems: "center",
548
- gap: 6,
549
  };
550
 
551
  const noticeIconStyle: React.CSSProperties = {
552
  display: "inline-flex",
553
  alignItems: "center",
554
  justifyContent: "center",
555
- width: 20,
556
- height: 20,
557
  borderRadius: 999,
558
- color: "#2563eb",
 
 
559
  };
560
 
561
  const noticeBadgeStyle: React.CSSProperties = {
562
  fontSize: 10,
563
  fontWeight: 700,
564
- letterSpacing: "0.06em",
565
  textTransform: "uppercase",
566
- color: "#1d4ed8",
567
  };
568
 
569
  const noticeBodyStyle: React.CSSProperties = {
570
  margin: 0,
571
  fontSize: 12.5,
572
  lineHeight: 1.55,
573
- color: "#374151",
574
  };
575
 
576
  const noticeBandBoxStyle: React.CSSProperties = {
577
- background: "#fff",
578
- border: "1px solid #dbeafe",
579
- borderRadius: 10,
580
- padding: "10px 12px",
581
  display: "flex",
582
  flexDirection: "column",
583
- gap: 2,
584
  };
585
 
586
  const noticeBandHeadlineStyle: React.CSSProperties = {
587
- fontSize: 16,
588
- fontWeight: 700,
589
- color: "#0f172a",
 
 
 
 
590
  };
591
 
592
  const noticeBandSuffixStyle: React.CSSProperties = {
 
593
  fontSize: 12,
594
- fontWeight: 400,
595
- color: "#6b7280",
596
  };
597
 
598
  const noticeBandMedianStyle: React.CSSProperties = {
599
  fontSize: 11.5,
600
- color: "#475569",
 
601
  };
602
 
603
  const noticeBandFallbackStyle: React.CSSProperties = {
604
  fontSize: 12,
605
- color: "#92400e",
606
  fontStyle: "italic",
 
607
  };
608
 
609
  const noticeFootnoteStyle: React.CSSProperties = {
610
  margin: 0,
611
  fontSize: 11,
612
  lineHeight: 1.5,
613
- color: "#6b7280",
614
  fontStyle: "italic",
615
  };
 
16
  * producing wildly low numbers (~β‚Ή6K) versus the panel's curated number
17
  * (~β‚Ή18-25K) for the same profile. Tenure + deductible are still honoured β€”
18
  * the estimate endpoint now applies the bulk multipliers post-anchor.
19
+ *
20
+ * ── Visual system ─────────────────────────────────────────────────────
21
+ * Re-grounded on the premium editorial-fintech landing (app/globals.css):
22
+ * Fraunces display serif for the headline premium numeral, Plus Jakarta for
23
+ * UI chrome, the teal --primary token for the active pills + slider track,
24
+ * color-mix soft depth, and tight one-line fact bullets. All chrome reads
25
+ * from CSS variables so the widget tracks the page's light/dark scheme.
26
+ * Reduced-motion is honoured via a local media query.
27
  */
28
 
29
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
 
66
  const TENURE_CHOICES = [1, 2, 3] as const;
67
  const DEDUCTIBLE_CHOICES = [0, 25_000, 50_000, 100_000] as const;
68
 
69
+ // Display serif + sans UI face, pulled from the landing's CSS vars so the
70
+ // widget shares the exact type system as the rest of the app.
71
+ const SERIF = "var(--font-serif)";
72
+ const SANS = "var(--font-sans)";
73
+
74
  function formatInr(value: number): string {
75
  // Indian-style 1,23,456 grouping.
76
  return value.toLocaleString("en-IN");
 
229
  const bullets: string[] = [];
230
  if (resp) {
231
  bullets.push(
232
+ `Range β‚Ή${formatInr(resp.low_inr)} – β‚Ή${formatInr(resp.high_inr)}/year (Β±15% band)`,
233
  );
234
  if (resp.tenure_years && resp.tenure_years !== 1) {
235
  bullets.push(`Multi-year discount applied (${resp.tenure_years}-year policy)`);
 
243
 
244
  return (
245
  <div className="policy-premium-widget" style={widgetStyle}>
246
+ {/* Local accent-color + reduced-motion scoping for the native range
247
+ input. Scoped to .policy-premium-widget so it never leaks. */}
248
+ <style>{PREMIUM_WIDGET_CSS}</style>
249
+
250
  <header style={headerStyle}>
251
+ <div
252
+ style={{
253
+ fontWeight: 600,
254
+ fontSize: 13.5,
255
+ color: "var(--foreground)",
256
+ lineHeight: 1.35,
257
+ letterSpacing: "-0.005em",
258
+ }}
259
+ >
260
+ {policyName}
261
+ </div>
262
  {/* Curated-only branch: by the time we render this widget,
263
  base_sample_used is guaranteed not false (the !== false branch
264
  short-circuits to NonCuratedPricingNotice above). No "Estimate"
 
267
 
268
  {profileSummary && (
269
  <div style={profileLineStyle}>
270
+ Your profile defaults Β· {profileSummary}
271
  </div>
272
  )}
273
 
274
  <div style={sliderGroupStyle}>
275
  <label style={labelStyle}>
276
  <span style={labelHeadStyle}>
277
+ <span style={labelTextStyle}>Sum insured</span>
278
+ <strong style={labelValueStyle}>β‚Ή{formatSiLabel(sumInsured)}</strong>
279
  </span>
280
  <input
281
  type="range"
 
295
 
296
  <label style={labelStyle}>
297
  <span style={labelHeadStyle}>
298
+ <span style={labelTextStyle}>Tenure</span>
299
+ <strong style={labelValueStyle}>
300
+ {tenureYears} {tenureYears === 1 ? "year" : "years"}
301
+ </strong>
302
  </span>
303
  <div role="radiogroup" aria-label="Tenure" style={pillRowStyle}>
304
  {TENURE_CHOICES.map((y) => (
 
318
 
319
  <label style={labelStyle}>
320
  <span style={labelHeadStyle}>
321
+ <span style={labelTextStyle}>Deductible</span>
322
+ <strong style={labelValueStyle}>
323
+ {formatDeductibleLabel(deductibleInr)}
324
+ </strong>
325
  </span>
326
  <div role="radiogroup" aria-label="Deductible" style={pillRowStyle}>
327
  {DEDUCTIBLE_CHOICES.map((d) => (
 
342
 
343
  <div style={resultBoxStyle} aria-live="polite">
344
  {error ? (
345
+ <div style={errorTextStyle}>Failed: {error}</div>
346
  ) : loading && !resp ? (
347
+ <div style={calculatingStyle}>
348
+ <span aria-hidden style={dotPulseStyle} />
349
+ Calculating estimate…
350
+ </div>
351
  ) : resp ? (
352
  <>
353
+ <div style={resultHeadlineRowStyle}>
354
+ <span style={resultLabelStyle}>Estimated premium</span>
355
+ <span style={resultValueWrapStyle}>
356
+ <strong style={resultValueStyle}>
357
+ β‚Ή{formatInr(resp.point_estimate_inr)}
358
+ </strong>
359
+ <span style={resultSuffixStyle}>/year</span>
360
+ {loading && (
361
+ <span style={spinnerHintStyle}>updating…</span>
362
+ )}
363
+ </span>
364
  </div>
365
  {bullets.length > 0 && (
366
  <ul style={breakdownListStyle}>
367
  {bullets.map((b) => (
368
+ <li key={b} style={breakdownItemStyle}>
369
+ <span aria-hidden style={breakdownTickStyle} />
370
+ <span>{b}</span>
371
+ </li>
372
  ))}
373
  </ul>
374
  )}
 
409
  <header style={noticeHeaderStyle}>
410
  <span style={noticeIconStyle} aria-hidden="true">
411
  {/* info icon β€” pure SVG so we don't pull a new dependency */}
412
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
413
  <circle cx="12" cy="12" r="10" />
414
  <line x1="12" y1="8" x2="12" y2="8" />
415
  <line x1="12" y1="12" x2="12" y2="16" />
 
459
 
460
  /* ------------------------------------------------------------------ */
461
  /* Inline styles β€” kept local so the widget drops into any modal */
462
+ /* without a CSS-module dependency. All colors read from the landing's */
463
+ /* CSS variables (--primary teal, --card, --border, --muted, etc.) so */
464
+ /* the widget belongs to the premium editorial-fintech design system */
465
+ /* and tracks the page's light/dark scheme automatically. */
466
  /* ------------------------------------------------------------------ */
467
 
468
+ // Scoped native-range-input theming + reduced-motion guard. Kept as a tiny
469
+ // string so the file stays CSS-module-free and self-contained.
470
+ const PREMIUM_WIDGET_CSS = `
471
+ .policy-premium-widget input[type="range"]{
472
+ -webkit-appearance:none;appearance:none;height:6px;border-radius:999px;
473
+ background:linear-gradient(90deg,
474
+ color-mix(in srgb, var(--primary) 55%, var(--border)) 0%,
475
+ var(--muted) 100%);
476
+ outline:none;cursor:pointer;margin:2px 0;
477
+ }
478
+ .policy-premium-widget input[type="range"]:focus-visible{
479
+ outline:2px solid var(--primary);outline-offset:3px;
480
+ }
481
+ .policy-premium-widget input[type="range"]::-webkit-slider-thumb{
482
+ -webkit-appearance:none;appearance:none;width:17px;height:17px;border-radius:999px;
483
+ background:var(--card);border:2px solid var(--primary);cursor:pointer;
484
+ box-shadow:0 1px 3px color-mix(in srgb, var(--foreground) 22%, transparent);
485
+ transition:transform .15s ease;
486
+ }
487
+ .policy-premium-widget input[type="range"]::-webkit-slider-thumb:hover{transform:scale(1.12);}
488
+ .policy-premium-widget input[type="range"]::-moz-range-thumb{
489
+ width:17px;height:17px;border-radius:999px;background:var(--card);
490
+ border:2px solid var(--primary);cursor:pointer;
491
+ box-shadow:0 1px 3px color-mix(in srgb, var(--foreground) 22%, transparent);
492
+ }
493
+ @keyframes ppw-dot{0%,100%{opacity:.35}50%{opacity:1}}
494
+ @media (prefers-reduced-motion: reduce){
495
+ .policy-premium-widget input[type="range"]::-webkit-slider-thumb{transition:none!important}
496
+ .policy-premium-widget *{animation:none!important}
497
+ }
498
+ `;
499
+
500
  const widgetStyle: React.CSSProperties = {
501
+ border: "1px solid var(--border)",
502
+ borderRadius: 18,
503
+ padding: 18,
504
+ background: "var(--card)",
505
  display: "flex",
506
  flexDirection: "column",
507
+ gap: 14,
508
+ fontFamily: SANS,
509
+ boxShadow:
510
+ "0 1px 2px color-mix(in srgb, var(--foreground) 4%, transparent), 0 16px 40px -32px color-mix(in srgb, var(--foreground) 28%, transparent)",
511
  };
512
 
513
  const headerStyle: React.CSSProperties = {
 
518
  };
519
 
520
  const profileLineStyle: React.CSSProperties = {
521
+ fontSize: 11.5,
522
+ color: "var(--muted-foreground)",
523
+ letterSpacing: "0.005em",
524
  };
525
 
526
  const sliderGroupStyle: React.CSSProperties = {
527
  display: "flex",
528
  flexDirection: "column",
529
+ gap: 16,
530
  };
531
 
532
  const labelStyle: React.CSSProperties = {
533
  display: "flex",
534
  flexDirection: "column",
535
+ gap: 8,
536
  fontSize: 12,
537
+ color: "var(--foreground)",
538
  };
539
 
540
  const labelHeadStyle: React.CSSProperties = {
541
  display: "flex",
542
+ alignItems: "baseline",
543
  justifyContent: "space-between",
544
+ gap: 10,
545
+ };
546
+
547
+ const labelTextStyle: React.CSSProperties = {
548
  fontWeight: 500,
549
+ color: "var(--muted-foreground)",
550
+ textTransform: "uppercase",
551
+ letterSpacing: "0.07em",
552
+ fontSize: 10.5,
553
+ };
554
+
555
+ const labelValueStyle: React.CSSProperties = {
556
+ fontWeight: 700,
557
+ color: "var(--foreground)",
558
+ fontSize: 13,
559
+ fontVariantNumeric: "tabular-nums",
560
  };
561
 
562
  const tickRowStyle: React.CSSProperties = {
563
  display: "flex",
564
  justifyContent: "space-between",
565
+ fontSize: 10.5,
566
+ color: "var(--muted-foreground)",
567
+ fontVariantNumeric: "tabular-nums",
568
  };
569
 
570
  const pillRowStyle: React.CSSProperties = {
571
  display: "flex",
572
+ gap: 7,
573
  flexWrap: "wrap",
574
  };
575
 
576
  const pillStyle = (active: boolean): React.CSSProperties => ({
577
+ border: active
578
+ ? "1px solid var(--primary)"
579
+ : "1px solid var(--border)",
580
+ background: active
581
+ ? "var(--primary)"
582
+ : "var(--card)",
583
+ color: active ? "var(--primary-foreground)" : "var(--muted-foreground)",
584
+ padding: "5px 13px",
585
  borderRadius: 999,
586
  fontSize: 12,
587
+ fontWeight: 600,
588
  cursor: "pointer",
589
+ fontVariantNumeric: "tabular-nums",
590
+ transition: "background .16s ease, color .16s ease, border-color .16s ease",
591
+ boxShadow: active
592
+ ? "0 2px 8px -2px color-mix(in srgb, var(--primary) 45%, transparent)"
593
+ : "none",
594
  });
595
 
596
  const resultBoxStyle: React.CSSProperties = {
597
+ borderTop: "1px solid var(--border)",
598
+ paddingTop: 14,
599
  display: "flex",
600
  flexDirection: "column",
601
+ gap: 10,
602
+ };
603
+
604
+ const resultHeadlineRowStyle: React.CSSProperties = {
605
+ display: "flex",
606
+ flexDirection: "column",
607
+ gap: 4,
608
+ };
609
+
610
+ const resultLabelStyle: React.CSSProperties = {
611
+ fontSize: 10.5,
612
+ textTransform: "uppercase",
613
+ letterSpacing: "0.1em",
614
+ fontWeight: 700,
615
+ color: "color-mix(in srgb, var(--primary) 70%, var(--muted-foreground))",
616
  };
617
 
618
+ const resultValueWrapStyle: React.CSSProperties = {
619
+ display: "flex",
620
+ alignItems: "baseline",
621
+ gap: 6,
622
+ flexWrap: "wrap",
623
+ };
624
+
625
+ const resultValueStyle: React.CSSProperties = {
626
+ fontFamily: SERIF,
627
+ fontOpticalSizing: "auto",
628
+ fontSize: 28,
629
+ fontWeight: 600,
630
+ color: "var(--foreground)",
631
+ letterSpacing: "-0.02em",
632
+ fontVariantNumeric: "tabular-nums",
633
  };
634
 
635
  const resultSuffixStyle: React.CSSProperties = {
636
+ color: "var(--muted-foreground)",
637
+ fontWeight: 500,
638
+ fontSize: 12.5,
639
  };
640
 
641
  const spinnerHintStyle: React.CSSProperties = {
642
+ marginLeft: 4,
643
  fontSize: 11,
644
+ color: "var(--muted-foreground)",
645
  fontStyle: "italic",
646
  };
647
 
648
+ const errorTextStyle: React.CSSProperties = {
649
+ color: "color-mix(in srgb, var(--error) 78%, var(--foreground))",
650
+ fontSize: 12.5,
651
+ fontWeight: 500,
652
+ };
653
+
654
+ const calculatingStyle: React.CSSProperties = {
655
+ color: "var(--muted-foreground)",
656
+ fontSize: 12.5,
657
+ display: "flex",
658
+ alignItems: "center",
659
+ gap: 8,
660
+ };
661
+
662
+ const dotPulseStyle: React.CSSProperties = {
663
+ width: 7,
664
+ height: 7,
665
+ borderRadius: 999,
666
+ background: "var(--primary)",
667
+ animation: "ppw-dot 1.2s ease-in-out infinite",
668
+ };
669
+
670
  const breakdownListStyle: React.CSSProperties = {
671
  margin: 0,
672
+ padding: 0,
673
+ listStyle: "none",
674
+ display: "flex",
675
+ flexDirection: "column",
676
+ gap: 6,
677
+ };
678
+
679
+ const breakdownItemStyle: React.CSSProperties = {
680
+ display: "flex",
681
+ alignItems: "flex-start",
682
+ gap: 8,
683
+ color: "var(--muted-foreground)",
684
  fontSize: 12,
685
+ lineHeight: 1.45,
686
+ };
687
+
688
+ const breakdownTickStyle: React.CSSProperties = {
689
+ flex: "none",
690
+ marginTop: 6,
691
+ width: 5,
692
+ height: 5,
693
+ borderRadius: 999,
694
+ background: "color-mix(in srgb, var(--primary) 70%, transparent)",
695
  };
696
 
697
  const noteStyle: React.CSSProperties = {
698
  fontSize: 11,
699
+ color: "var(--muted-foreground)",
700
  fontStyle: "italic",
701
+ lineHeight: 1.5,
702
+ paddingTop: 2,
703
  };
704
 
705
  /* ---------------- NonCuratedPricingNotice styles ------------------- */
706
  /* Same outer card framing as the slider widget (border + radius + bg) */
707
+ /* but with a brand-teal informational accent rail so users instantly */
708
+ /* distinguish "indicative range" from a "calculated estimate". */
709
 
710
  const noticeWidgetStyle: React.CSSProperties = {
711
+ border: "1px solid color-mix(in srgb, var(--primary) 22%, var(--border))",
712
+ borderLeft: "3px solid var(--primary)",
713
+ borderRadius: 18,
714
+ padding: 18,
715
+ background: "color-mix(in srgb, var(--primary) 4%, var(--card))",
716
  display: "flex",
717
  flexDirection: "column",
718
+ gap: 11,
719
+ fontFamily: SANS,
720
+ boxShadow:
721
+ "0 1px 2px color-mix(in srgb, var(--foreground) 4%, transparent), 0 16px 40px -32px color-mix(in srgb, var(--foreground) 28%, transparent)",
722
  };
723
 
724
  const noticeHeaderStyle: React.CSSProperties = {
725
  display: "flex",
726
  alignItems: "center",
727
+ gap: 8,
728
  };
729
 
730
  const noticeIconStyle: React.CSSProperties = {
731
  display: "inline-flex",
732
  alignItems: "center",
733
  justifyContent: "center",
734
+ width: 22,
735
+ height: 22,
736
  borderRadius: 999,
737
+ color: "var(--primary)",
738
+ background: "color-mix(in srgb, var(--primary) 12%, var(--card))",
739
+ border: "1px solid color-mix(in srgb, var(--primary) 22%, var(--border))",
740
  };
741
 
742
  const noticeBadgeStyle: React.CSSProperties = {
743
  fontSize: 10,
744
  fontWeight: 700,
745
+ letterSpacing: "0.12em",
746
  textTransform: "uppercase",
747
+ color: "color-mix(in srgb, var(--primary) 78%, var(--foreground))",
748
  };
749
 
750
  const noticeBodyStyle: React.CSSProperties = {
751
  margin: 0,
752
  fontSize: 12.5,
753
  lineHeight: 1.55,
754
+ color: "var(--foreground)",
755
  };
756
 
757
  const noticeBandBoxStyle: React.CSSProperties = {
758
+ background: "var(--card)",
759
+ border: "1px solid color-mix(in srgb, var(--primary) 16%, var(--border))",
760
+ borderRadius: 12,
761
+ padding: "12px 14px",
762
  display: "flex",
763
  flexDirection: "column",
764
+ gap: 3,
765
  };
766
 
767
  const noticeBandHeadlineStyle: React.CSSProperties = {
768
+ fontFamily: SERIF,
769
+ fontOpticalSizing: "auto",
770
+ fontSize: 21,
771
+ fontWeight: 600,
772
+ color: "var(--foreground)",
773
+ letterSpacing: "-0.02em",
774
+ fontVariantNumeric: "tabular-nums",
775
  };
776
 
777
  const noticeBandSuffixStyle: React.CSSProperties = {
778
+ fontFamily: SANS,
779
  fontSize: 12,
780
+ fontWeight: 500,
781
+ color: "var(--muted-foreground)",
782
  };
783
 
784
  const noticeBandMedianStyle: React.CSSProperties = {
785
  fontSize: 11.5,
786
+ color: "var(--muted-foreground)",
787
+ fontVariantNumeric: "tabular-nums",
788
  };
789
 
790
  const noticeBandFallbackStyle: React.CSSProperties = {
791
  fontSize: 12,
792
+ color: "#855316",
793
  fontStyle: "italic",
794
+ lineHeight: 1.5,
795
  };
796
 
797
  const noticeFootnoteStyle: React.CSSProperties = {
798
  margin: 0,
799
  fontSize: 11,
800
  lineHeight: 1.5,
801
+ color: "var(--muted-foreground)",
802
  fontStyle: "italic",
803
  };
frontend/src/components/PolicyScorecardWidget.tsx CHANGED
@@ -16,6 +16,14 @@
16
  // - dependents = spouse -> heavier coverage-breadth + cost-predictability
17
  // - existing_cover_inr=0 -> heavier cost-predictability (first-time buyer)
18
  // So the same policy will literally score differently for different users.
 
 
 
 
 
 
 
 
19
 
20
  "use client";
21
 
@@ -42,40 +50,56 @@ export type PolicyScorecardWidgetProps = {
42
  // Sub-score keys we know about β€” controls render order. Anything else the
43
  // backend returns gets appended after these in arrival order.
44
  const SUBSCORE_ORDER: { key: string; label: string }[] = [
45
- { key: "coverage_breadth", label: "Coverage Breadth" },
46
- { key: "cost_predictability", label: "Cost Predictability" },
47
- { key: "waiting_period_friction", label: "Waiting Periods" },
48
- { key: "claim_experience", label: "Claim Experience" },
49
- { key: "renewal_protection", label: "Renewal Protection" },
50
  { key: "bonus_and_loyalty", label: "Bonuses" },
51
  ];
52
 
 
 
 
 
 
 
 
 
53
  function gradeColor(grade: string): { fg: string; bg: string; ring: string } {
54
- // Same palette family for every variant of a letter so a B+ looks like a B-
55
- // but slightly stronger.
56
  const head = grade.charAt(0).toUpperCase();
57
  switch (head) {
58
  case "A":
59
- return { fg: "#0f5132", bg: "#d1fadf", ring: "#16a34a" };
 
 
 
 
60
  case "B":
61
- return { fg: "#0c4a6e", bg: "#dbeafe", ring: "#2563eb" };
62
  case "C":
63
- return { fg: "#854d0e", bg: "#fef3c7", ring: "#d97706" };
64
  case "D":
65
- return { fg: "#7c2d12", bg: "#fed7aa", ring: "#ea580c" };
66
  case "F":
67
- return { fg: "#7f1d1d", bg: "#fecaca", ring: "#dc2626" };
68
  default:
69
- return { fg: "#374151", bg: "#f3f4f6", ring: "#9ca3af" };
 
 
 
 
70
  }
71
  }
72
 
 
 
73
  function barColor(score: number): string {
74
- if (score >= 80) return "#16a34a"; // green
75
- if (score >= 65) return "#2563eb"; // blue
76
- if (score >= 50) return "#d97706"; // amber
77
- if (score >= 35) return "#ea580c"; // orange
78
- return "#dc2626"; // red
79
  }
80
 
81
  function rationaleTone(bullet: string): "pos" | "neg" | "neutral" {
@@ -85,6 +109,18 @@ function rationaleTone(bullet: string): "pos" | "neg" | "neutral" {
85
  return "neutral";
86
  }
87
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  export default function PolicyScorecardWidget({
89
  policyId,
90
  policyName,
@@ -150,21 +186,36 @@ export default function PolicyScorecardWidget({
150
  <div
151
  className={className}
152
  style={{
153
- border: "1px solid #e5e7eb",
154
- borderRadius: 12,
155
- padding: 16,
156
- background: "#fff",
157
- minHeight: 220,
158
  display: "flex",
 
159
  alignItems: "center",
160
  justifyContent: "center",
161
- color: "#6b7280",
162
- fontSize: 13,
163
  }}
164
  aria-busy="true"
165
  aria-live="polite"
166
  >
167
- Scoring {policyName}…
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  </div>
169
  );
170
  }
@@ -174,16 +225,17 @@ export default function PolicyScorecardWidget({
174
  <div
175
  className={className}
176
  style={{
177
- border: "1px solid #fecaca",
178
- borderRadius: 12,
179
- padding: 16,
180
- background: "#fef2f2",
181
- color: "#991b1b",
182
- fontSize: 13,
183
  }}
184
  role="alert"
185
  >
186
- Couldn’t score this policy: {error ?? "unknown error"}
 
187
  </div>
188
  );
189
  }
@@ -205,33 +257,34 @@ export default function PolicyScorecardWidget({
205
  <div
206
  className={className}
207
  style={{
208
- border: "1px solid #e5e7eb",
209
- borderRadius: 12,
210
- padding: 16,
211
- background: "#fff",
212
  display: "flex",
213
  flexDirection: "column",
214
- gap: 14,
215
  }}
216
  data-policy-id={policyId}
217
  >
218
- {/* Header: grade + overall score */}
219
  <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
220
  <div
221
  style={{
222
- width: 64,
223
- height: 64,
224
- borderRadius: 14,
225
  background: colors.bg,
226
  color: colors.fg,
227
- border: `2px solid ${colors.ring}`,
228
  display: "flex",
229
  alignItems: "center",
230
  justifyContent: "center",
 
 
231
  fontSize: entry.overall_grade.length > 1 ? 26 : 32,
232
- fontWeight: 800,
233
- letterSpacing: "-0.04em",
234
  flexShrink: 0,
 
 
235
  }}
236
  aria-label={`Grade ${entry.overall_grade}`}
237
  >
@@ -240,63 +293,148 @@ export default function PolicyScorecardWidget({
240
  <div style={{ minWidth: 0, flex: 1 }}>
241
  <div
242
  style={{
243
- fontSize: 13,
244
  fontWeight: 600,
245
- color: "#111827",
 
246
  whiteSpace: "nowrap",
247
  overflow: "hidden",
248
  textOverflow: "ellipsis",
 
249
  }}
250
  title={entry.policy_name || policyName}
251
  >
252
  {entry.policy_name || policyName}
253
  </div>
254
- <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginTop: 2 }}>
255
- <span style={{ fontSize: 22, fontWeight: 700, color: "#111827" }}>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  {isNA ? "β€”" : `${entry.overall_score}`}
257
  </span>
258
  {!isNA && (
259
- <span style={{ fontSize: 12, color: "#6b7280" }}>/ 100</span>
260
- )}
261
- {profile && !isNA && (
262
  <span
263
  style={{
264
- marginLeft: "auto",
265
- fontSize: 10,
266
- textTransform: "uppercase",
267
- letterSpacing: "0.08em",
268
- color: "#0c4a6e",
269
- background: "#e0f2fe",
270
- padding: "2px 6px",
271
- borderRadius: 4,
272
- fontWeight: 600,
273
  }}
274
- title="Score weights adjusted for your profile"
275
  >
276
- Personalised
277
  </span>
278
  )}
279
  </div>
280
  {entry.one_liner && (
281
- <div style={{ fontSize: 11, color: "#4b5563", marginTop: 2 }}>
 
 
 
 
 
 
 
282
  {entry.one_liner}
283
  </div>
284
  )}
285
  </div>
286
  </div>
287
 
288
- {/* Sub-scores */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  {renderable.length > 0 && (
290
- <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
 
 
 
 
 
 
 
 
291
  {renderable.map(({ key, label }) => {
292
  const v = entry.sub_scores[key] ?? 0;
 
293
  return (
294
- <div key={key} style={{ display: "flex", flexDirection: "column", gap: 2 }}>
295
- <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11 }}>
296
- <span style={{ color: "#374151", textTransform: "capitalize" }}>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
  {label}
298
  </span>
299
- <span style={{ color: "#6b7280", fontVariantNumeric: "tabular-nums" }}>
 
 
 
 
 
 
 
300
  {v}
301
  </span>
302
  </div>
@@ -304,16 +442,17 @@ export default function PolicyScorecardWidget({
304
  style={{
305
  height: 6,
306
  borderRadius: 999,
307
- background: "#f3f4f6",
308
  overflow: "hidden",
309
  }}
310
  >
311
  <div
312
  style={{
313
- width: `${Math.max(0, Math.min(100, v))}%`,
314
  height: "100%",
 
315
  background: barColor(v),
316
- transition: "width 200ms ease-out",
317
  }}
318
  />
319
  </div>
@@ -323,36 +462,70 @@ export default function PolicyScorecardWidget({
323
  </div>
324
  )}
325
 
326
- {/* Profile rationale */}
327
  {entry.profile_rationale.length > 0 && (
328
  <div
329
  style={{
330
- background: "#f9fafb",
331
- border: "1px solid #f3f4f6",
332
- borderRadius: 8,
333
- padding: 10,
334
  }}
335
  >
336
  <div
337
  style={{
338
- fontSize: 10,
339
  textTransform: "uppercase",
340
- letterSpacing: "0.08em",
341
- color: "#6b7280",
342
- fontWeight: 600,
343
- marginBottom: 6,
344
  }}
345
  >
346
  Why this score for you
347
  </div>
348
- <ul style={{ margin: 0, paddingLeft: 16, display: "flex", flexDirection: "column", gap: 4 }}>
 
 
 
 
 
 
 
 
 
349
  {entry.profile_rationale.map((b, i) => {
350
  const tone = rationaleTone(b);
351
- const color =
352
- tone === "pos" ? "#0f5132" : tone === "neg" ? "#991b1b" : "#374151";
 
 
 
 
353
  return (
354
- <li key={i} style={{ fontSize: 12, color, lineHeight: 1.4 }}>
355
- {b}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  </li>
357
  );
358
  })}
@@ -360,26 +533,27 @@ export default function PolicyScorecardWidget({
360
  </div>
361
  )}
362
 
363
- {/* Limited-data warning */}
364
  {showLimitedWarning && (
365
  <div
366
  style={{
367
  display: "flex",
368
- alignItems: "center",
369
  gap: 8,
370
  fontSize: 11,
371
- color: "#854d0e",
372
- background: "#fef3c7",
373
- border: "1px solid #fde68a",
374
- borderRadius: 8,
375
- padding: "6px 10px",
 
376
  }}
377
  role="status"
378
  >
379
- <span style={{ fontWeight: 700 }}>Limited data:</span>
380
  <span>
381
- Only {completeness.toFixed(0)}% of scoring fields are filled for this policy β€”
382
- grade may shift once more details are indexed.
383
  </span>
384
  </div>
385
  )}
 
16
  // - dependents = spouse -> heavier coverage-breadth + cost-predictability
17
  // - existing_cover_inr=0 -> heavier cost-predictability (first-time buyer)
18
  // So the same policy will literally score differently for different users.
19
+ //
20
+ // ── Visual system ──────────────────────────────────────────────────────
21
+ // Re-grounded on the premium editorial-fintech landing (see app/globals.css):
22
+ // Fraunces display serif for the grade + score numerals, Plus Jakarta for
23
+ // UI chrome, the teal --primary token, color-mix soft depth, the kicker
24
+ // pill pattern for the "Personalised" tag, and tabular-nums everywhere a
25
+ // number must align. All chrome reads from CSS variables so the card shifts
26
+ // with the page's light/dark scheme. Reduced-motion is honoured.
27
 
28
  "use client";
29
 
 
50
  // Sub-score keys we know about β€” controls render order. Anything else the
51
  // backend returns gets appended after these in arrival order.
52
  const SUBSCORE_ORDER: { key: string; label: string }[] = [
53
+ { key: "coverage_breadth", label: "Coverage breadth" },
54
+ { key: "cost_predictability", label: "Cost predictability" },
55
+ { key: "waiting_period_friction", label: "Waiting periods" },
56
+ { key: "claim_experience", label: "Claim experience" },
57
+ { key: "renewal_protection", label: "Renewal protection" },
58
  { key: "bonus_and_loyalty", label: "Bonuses" },
59
  ];
60
 
61
+ // Serif display face + sans UI face, pulled from the landing's CSS vars so
62
+ // the widget shares the exact type system as the rest of the app.
63
+ const SERIF = "var(--font-serif)";
64
+ const SANS = "var(--font-sans)";
65
+
66
+ // A→F grade ramp. Kept inside one tonal family per letter so a B+ reads as
67
+ // a stronger sibling of a B-. The "A" tier is the brand teal; the rest walk
68
+ // a calm green→amber→red gradient that still feels editorial, not alarmist.
69
  function gradeColor(grade: string): { fg: string; bg: string; ring: string } {
 
 
70
  const head = grade.charAt(0).toUpperCase();
71
  switch (head) {
72
  case "A":
73
+ return {
74
+ fg: "color-mix(in srgb, var(--primary) 82%, #042f2a)",
75
+ bg: "color-mix(in srgb, var(--primary) 13%, var(--card))",
76
+ ring: "color-mix(in srgb, var(--primary) 60%, var(--border))",
77
+ };
78
  case "B":
79
+ return { fg: "#155e63", bg: "#e3f4f3", ring: "#3d9c98" };
80
  case "C":
81
+ return { fg: "#855316", bg: "#fbeed2", ring: "#cf9b3f" };
82
  case "D":
83
+ return { fg: "#8a3c12", bg: "#fae0cd", ring: "#d4793b" };
84
  case "F":
85
+ return { fg: "#8a2020", bg: "#f8d9d9", ring: "#cf4b4b" };
86
  default:
87
+ return {
88
+ fg: "var(--muted-foreground)",
89
+ bg: "var(--muted)",
90
+ ring: "var(--border)",
91
+ };
92
  }
93
  }
94
 
95
+ // Sub-score bar fill β€” same calm ramp as the grade so the card never has
96
+ // two competing color stories.
97
  function barColor(score: number): string {
98
+ if (score >= 80) return "var(--primary)";
99
+ if (score >= 65) return "#3d9c98";
100
+ if (score >= 50) return "#cf9b3f";
101
+ if (score >= 35) return "#d4793b";
102
+ return "#cf4b4b";
103
  }
104
 
105
  function rationaleTone(bullet: string): "pos" | "neg" | "neutral" {
 
109
  return "neutral";
110
  }
111
 
112
+ // Shared shell so loading / error / loaded states share identical framing
113
+ // (no layout jump between states inside the compare grid).
114
+ const shellStyle: React.CSSProperties = {
115
+ borderRadius: 18,
116
+ border: "1px solid var(--border)",
117
+ background: "var(--card)",
118
+ padding: 18,
119
+ fontFamily: SANS,
120
+ boxShadow:
121
+ "0 1px 2px color-mix(in srgb, var(--foreground) 4%, transparent), 0 16px 40px -32px color-mix(in srgb, var(--foreground) 28%, transparent)",
122
+ };
123
+
124
  export default function PolicyScorecardWidget({
125
  policyId,
126
  policyName,
 
186
  <div
187
  className={className}
188
  style={{
189
+ ...shellStyle,
190
+ minHeight: 240,
 
 
 
191
  display: "flex",
192
+ flexDirection: "column",
193
  alignItems: "center",
194
  justifyContent: "center",
195
+ gap: 12,
196
+ color: "var(--muted-foreground)",
197
  }}
198
  aria-busy="true"
199
  aria-live="polite"
200
  >
201
+ <div
202
+ aria-hidden
203
+ style={{
204
+ width: 26,
205
+ height: 26,
206
+ borderRadius: 999,
207
+ border: "2px solid color-mix(in srgb, var(--primary) 22%, var(--border))",
208
+ borderTopColor: "var(--primary)",
209
+ animation: "scw-spin 0.8s linear infinite",
210
+ }}
211
+ />
212
+ <span style={{ fontSize: 12.5, letterSpacing: "0.01em" }}>
213
+ Scoring {policyName}…
214
+ </span>
215
+ <style>{
216
+ "@keyframes scw-spin{to{transform:rotate(360deg)}}" +
217
+ "@media (prefers-reduced-motion: reduce){[style*='scw-spin']{animation:none!important}}"
218
+ }</style>
219
  </div>
220
  );
221
  }
 
225
  <div
226
  className={className}
227
  style={{
228
+ ...shellStyle,
229
+ border: "1px solid color-mix(in srgb, var(--error) 38%, var(--border))",
230
+ background: "color-mix(in srgb, var(--error) 6%, var(--card))",
231
+ color: "color-mix(in srgb, var(--error) 75%, var(--foreground))",
232
+ fontSize: 12.5,
233
+ lineHeight: 1.5,
234
  }}
235
  role="alert"
236
  >
237
+ <span style={{ fontWeight: 600 }}>Couldn’t score this policy.</span>{" "}
238
+ {error ?? "Unknown error"}
239
  </div>
240
  );
241
  }
 
257
  <div
258
  className={className}
259
  style={{
260
+ ...shellStyle,
 
 
 
261
  display: "flex",
262
  flexDirection: "column",
263
+ gap: 16,
264
  }}
265
  data-policy-id={policyId}
266
  >
267
+ {/* Header: grade medallion + overall score */}
268
  <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
269
  <div
270
  style={{
271
+ width: 62,
272
+ height: 62,
273
+ borderRadius: 16,
274
  background: colors.bg,
275
  color: colors.fg,
276
+ border: `1px solid ${colors.ring}`,
277
  display: "flex",
278
  alignItems: "center",
279
  justifyContent: "center",
280
+ fontFamily: SERIF,
281
+ fontOpticalSizing: "auto",
282
  fontSize: entry.overall_grade.length > 1 ? 26 : 32,
283
+ fontWeight: 600,
284
+ letterSpacing: "-0.02em",
285
  flexShrink: 0,
286
+ boxShadow:
287
+ "inset 0 1px 0 color-mix(in srgb, #fff 50%, transparent), 0 2px 6px color-mix(in srgb, var(--foreground) 8%, transparent)",
288
  }}
289
  aria-label={`Grade ${entry.overall_grade}`}
290
  >
 
293
  <div style={{ minWidth: 0, flex: 1 }}>
294
  <div
295
  style={{
296
+ fontSize: 13.5,
297
  fontWeight: 600,
298
+ color: "var(--foreground)",
299
+ lineHeight: 1.35,
300
  whiteSpace: "nowrap",
301
  overflow: "hidden",
302
  textOverflow: "ellipsis",
303
+ letterSpacing: "-0.005em",
304
  }}
305
  title={entry.policy_name || policyName}
306
  >
307
  {entry.policy_name || policyName}
308
  </div>
309
+ <div
310
+ style={{
311
+ display: "flex",
312
+ alignItems: "baseline",
313
+ gap: 5,
314
+ marginTop: 4,
315
+ }}
316
+ >
317
+ <span
318
+ style={{
319
+ fontFamily: SERIF,
320
+ fontOpticalSizing: "auto",
321
+ fontSize: 26,
322
+ fontWeight: 600,
323
+ color: "var(--foreground)",
324
+ letterSpacing: "-0.02em",
325
+ fontVariantNumeric: "tabular-nums",
326
+ }}
327
+ >
328
  {isNA ? "β€”" : `${entry.overall_score}`}
329
  </span>
330
  {!isNA && (
 
 
 
331
  <span
332
  style={{
333
+ fontSize: 12,
334
+ color: "var(--muted-foreground)",
335
+ fontVariantNumeric: "tabular-nums",
 
 
 
 
 
 
336
  }}
 
337
  >
338
+ / 100
339
  </span>
340
  )}
341
  </div>
342
  {entry.one_liner && (
343
+ <div
344
+ style={{
345
+ fontSize: 11.5,
346
+ color: "var(--muted-foreground)",
347
+ marginTop: 3,
348
+ lineHeight: 1.4,
349
+ }}
350
+ >
351
  {entry.one_liner}
352
  </div>
353
  )}
354
  </div>
355
  </div>
356
 
357
+ {/* "Personalised" tag β€” kicker-pill pattern from the landing. Full
358
+ width so it never collides with a long policy name. */}
359
+ {profile && !isNA && (
360
+ <div
361
+ style={{
362
+ display: "inline-flex",
363
+ alignSelf: "flex-start",
364
+ alignItems: "center",
365
+ gap: 7,
366
+ padding: "5px 11px 5px 9px",
367
+ borderRadius: 999,
368
+ fontSize: 10.5,
369
+ fontWeight: 600,
370
+ letterSpacing: "0.1em",
371
+ textTransform: "uppercase",
372
+ color: "var(--primary)",
373
+ background: "color-mix(in srgb, var(--primary) 9%, var(--card))",
374
+ border: "1px solid color-mix(in srgb, var(--primary) 22%, var(--border))",
375
+ }}
376
+ title="Score weights adjusted for your profile"
377
+ >
378
+ <span
379
+ aria-hidden
380
+ style={{
381
+ width: 5,
382
+ height: 5,
383
+ borderRadius: 999,
384
+ background: "var(--primary)",
385
+ }}
386
+ />
387
+ Personalised for you
388
+ </div>
389
+ )}
390
+
391
+ {/* Sub-scores β€” labelled rows with tabular numerals + a calm fill */}
392
  {renderable.length > 0 && (
393
+ <div
394
+ style={{
395
+ display: "flex",
396
+ flexDirection: "column",
397
+ gap: 10,
398
+ paddingTop: 14,
399
+ borderTop: "1px solid var(--border)",
400
+ }}
401
+ >
402
  {renderable.map(({ key, label }) => {
403
  const v = entry.sub_scores[key] ?? 0;
404
+ const pct = Math.max(0, Math.min(100, v));
405
  return (
406
+ <div
407
+ key={key}
408
+ style={{ display: "flex", flexDirection: "column", gap: 5 }}
409
+ >
410
+ <div
411
+ style={{
412
+ display: "flex",
413
+ justifyContent: "space-between",
414
+ alignItems: "baseline",
415
+ gap: 10,
416
+ fontSize: 11.5,
417
+ }}
418
+ >
419
+ <span
420
+ style={{
421
+ color: "var(--foreground)",
422
+ fontWeight: 500,
423
+ whiteSpace: "nowrap",
424
+ overflow: "hidden",
425
+ textOverflow: "ellipsis",
426
+ }}
427
+ >
428
  {label}
429
  </span>
430
+ <span
431
+ style={{
432
+ color: "var(--muted-foreground)",
433
+ fontVariantNumeric: "tabular-nums",
434
+ fontWeight: 600,
435
+ flexShrink: 0,
436
+ }}
437
+ >
438
  {v}
439
  </span>
440
  </div>
 
442
  style={{
443
  height: 6,
444
  borderRadius: 999,
445
+ background: "var(--muted)",
446
  overflow: "hidden",
447
  }}
448
  >
449
  <div
450
  style={{
451
+ width: `${pct}%`,
452
  height: "100%",
453
+ borderRadius: 999,
454
  background: barColor(v),
455
+ transition: "width 260ms cubic-bezier(.2,.7,.3,1)",
456
  }}
457
  />
458
  </div>
 
462
  </div>
463
  )}
464
 
465
+ {/* Profile rationale β€” section-titled like the landing chapters */}
466
  {entry.profile_rationale.length > 0 && (
467
  <div
468
  style={{
469
+ background: "color-mix(in srgb, var(--primary) 4%, var(--muted))",
470
+ border: "1px solid var(--border)",
471
+ borderRadius: 12,
472
+ padding: "12px 13px",
473
  }}
474
  >
475
  <div
476
  style={{
477
+ fontSize: 9.5,
478
  textTransform: "uppercase",
479
+ letterSpacing: "0.12em",
480
+ color: "color-mix(in srgb, var(--primary) 70%, var(--muted-foreground))",
481
+ fontWeight: 700,
482
+ marginBottom: 9,
483
  }}
484
  >
485
  Why this score for you
486
  </div>
487
+ <ul
488
+ style={{
489
+ margin: 0,
490
+ padding: 0,
491
+ listStyle: "none",
492
+ display: "flex",
493
+ flexDirection: "column",
494
+ gap: 7,
495
+ }}
496
+ >
497
  {entry.profile_rationale.map((b, i) => {
498
  const tone = rationaleTone(b);
499
+ const tickColor =
500
+ tone === "pos"
501
+ ? "var(--primary)"
502
+ : tone === "neg"
503
+ ? "#cf4b4b"
504
+ : "var(--muted-foreground)";
505
  return (
506
+ <li
507
+ key={i}
508
+ style={{
509
+ display: "flex",
510
+ alignItems: "flex-start",
511
+ gap: 8,
512
+ fontSize: 12,
513
+ color: "var(--foreground)",
514
+ lineHeight: 1.45,
515
+ }}
516
+ >
517
+ <span
518
+ aria-hidden
519
+ style={{
520
+ flex: "none",
521
+ marginTop: 6,
522
+ width: 5,
523
+ height: 5,
524
+ borderRadius: 999,
525
+ background: tickColor,
526
+ }}
527
+ />
528
+ <span>{b}</span>
529
  </li>
530
  );
531
  })}
 
533
  </div>
534
  )}
535
 
536
+ {/* Limited-data warning β€” warm amber, single tidy row */}
537
  {showLimitedWarning && (
538
  <div
539
  style={{
540
  display: "flex",
541
+ alignItems: "flex-start",
542
  gap: 8,
543
  fontSize: 11,
544
+ lineHeight: 1.45,
545
+ color: "#855316",
546
+ background: "color-mix(in srgb, var(--accent) 60%, var(--card))",
547
+ border: "1px solid color-mix(in srgb, #cf9b3f 40%, var(--border))",
548
+ borderRadius: 10,
549
+ padding: "8px 11px",
550
  }}
551
  role="status"
552
  >
553
+ <span style={{ fontWeight: 700, flexShrink: 0 }}>Limited data Β·</span>
554
  <span>
555
+ Only {completeness.toFixed(0)}% of scoring fields are filled for
556
+ this policy β€” the grade may shift once more details are indexed.
557
  </span>
558
  </div>
559
  )}
frontend/src/lib/api.ts CHANGED
@@ -470,6 +470,13 @@ export type UserProfile = {
470
  copay_pct?: number;
471
  // KI-269 (D2, 2026-05-15) β€” Family medical history (free-text tags).
472
  family_medical_history?: string[];
 
 
 
 
 
 
 
473
  };
474
 
475
  export type ProfileCompletenessResponse = {
 
470
  copay_pct?: number;
471
  // KI-269 (D2, 2026-05-15) β€” Family medical history (free-text tags).
472
  family_medical_history?: string[];
473
+ // KI-275 (2026-05-15) β€” Tobacco use; +30-50% premium loading in
474
+ // premium_calculator.estimate(). On the Profile dataclass + accepted by
475
+ // save_profile_field (chat path). NOTE: the HTTP POST /api/profile
476
+ // (ProfileUpdateRequest) does not yet whitelist smoker / copay_pct /
477
+ // family_medical_history / desired_sum_insured_inr β€” the profile-builder
478
+ // form sends them so they apply the instant that backend gap is closed.
479
+ smoker?: boolean | null;
480
  };
481
 
482
  export type ProfileCompletenessResponse = {
frontend/tsconfig.tsbuildinfo CHANGED
The diff for this file is too large to render. See raw diff
 
tests/test_fixed_benefit_exclusion.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """KI-279 (2026-05-16) β€” fixed-benefit exclusion for comprehensive-indemnity intent.
2
+
3
+ LIVE-CONFIRMED BUG (Playwright audit on the deployed Space):
4
+
5
+ USER PROFILE: 29, metro, income 25L+, FIRST health policy
6
+ (existing_cover_inr=0), NO existing cover, NO pre-existing conditions,
7
+ wants 15L sum insured, wants ZERO co-pay.
8
+
9
+ WHAT WAS WRONGLY RECOMMENDED AS #1:
10
+ "Star Hospital Cash" by Star Health β€” a FIXED-BENEFIT daily-cash plan
11
+ (pays a fixed amount per day, NOT indemnity reimbursement of actual
12
+ medical expenses). Recommending a daily-cash / fixed-benefit product
13
+ as a top pick to someone who clearly wants COMPREHENSIVE INDEMNITY
14
+ cover is wrong.
15
+
16
+ ROOT CAUSE:
17
+ (1) brain_tools._FACT_KEYS loaded only `policy_type_indemnity_or_fixed`.
18
+ star-health__star-hospital-cash__brochure.json carries the type
19
+ under `policy_type` ("hospital_cash") and has NO
20
+ `policy_type_indemnity_or_fixed` key β€” so the enriched chunk reaching
21
+ retrieval_filters had ZERO type signal.
22
+ (2) retrieval_filters had no rule that excludes / down-ranks fixed-benefit
23
+ products (hospital daily cash, personal accident, critical illness,
24
+ cancer / defined-benefit) when the profile clearly signals the user
25
+ wants comprehensive indemnity cover.
26
+
27
+ FIX (backend/retrieval_filters.py + backend/brain_tools.py):
28
+ - Detect "wants comprehensive indemnity" intent conservatively (first
29
+ health policy / general-cover goal, a desired SI present, no existing
30
+ base cover, and NOT an explicit supplement / PA / CI / top-up goal).
31
+ - When that intent holds, HARD-DROP policy chunks whose type is
32
+ fixed-benefit (reuse scorecard-equivalent classification + name regex).
33
+ - Belt-and-braces: down-rank any surviving fixed-benefit below all
34
+ indemnity options.
35
+ - Surface `policy_type` through brain_tools enrichment so the signal
36
+ reaches the filter on the live path.
37
+
38
+ Run:
39
+ .venv/bin/python -m pytest -q tests/test_fixed_benefit_exclusion.py
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import unittest
45
+
46
+ from backend.brain_tools import _load_policy_facts
47
+ from backend.retrieval_filters import (
48
+ apply_eligibility_filter,
49
+ rank_by_profile_fit,
50
+ filter_pipeline,
51
+ _wants_comprehensive_indemnity,
52
+ _is_fixed_benefit_chunk,
53
+ )
54
+
55
+
56
+ # The exact failing-session profile.
57
+ COMPREHENSIVE_PROFILE = {
58
+ "age": 29,
59
+ "location_tier": "metro",
60
+ "income_band": "25L+",
61
+ "primary_goal": "first_buy",
62
+ "existing_cover_inr": 0, # FIRST policy β€” no base cover
63
+ "health_conditions": ["none"],
64
+ "desired_sum_insured_inr": 1_500_000, # 15 lakh
65
+ "copay_pct": 0, # explicit ZERO co-pay preference
66
+ "dependents": "self",
67
+ }
68
+
69
+
70
+ def _chunk(
71
+ policy_id,
72
+ policy_name,
73
+ *,
74
+ score=0.5,
75
+ policy_type=None,
76
+ policy_type_canonical=None,
77
+ copay_pct=None,
78
+ sum_insured_options=None,
79
+ grade=None,
80
+ overall_score=None,
81
+ doc_type="policy",
82
+ ):
83
+ """Chunk dict shaped like brain_tools.retrieve_policies output AFTER the
84
+ policy_facts enrichment step.
85
+
86
+ `policy_type` mirrors the raw catalog key (e.g. "hospital_cash");
87
+ `policy_type_canonical` mirrors `policy_type_indemnity_or_fixed`
88
+ ("indemnity" / "fixed_benefit") when curated.
89
+ """
90
+ return {
91
+ "policy_id": policy_id,
92
+ "policy_name": policy_name,
93
+ "insurer_slug": policy_id.split("__")[0],
94
+ "doc_type": doc_type,
95
+ "score": score,
96
+ "chunk_text": "",
97
+ "policy_type_indemnity_or_fixed": policy_type_canonical,
98
+ "policy_type": policy_type,
99
+ "deductible_amount": None,
100
+ "co_payment_pct": copay_pct,
101
+ "sum_insured_options": sum_insured_options,
102
+ "_grade": grade,
103
+ "_overall_score": overall_score,
104
+ }
105
+
106
+
107
+ # The product the bot wrongly recommended #1.
108
+ STAR_HOSPITAL_CASH = _chunk(
109
+ "star-health__star-hospital-cash__brochure",
110
+ "Star Hospital Cash",
111
+ score=0.72,
112
+ policy_type="hospital_cash", # raw catalog key (no canonical key)
113
+ policy_type_canonical=None, # mirrors the real facts file
114
+ copay_pct=None,
115
+ sum_insured_options=None,
116
+ )
117
+ PERSONAL_ACCIDENT = _chunk(
118
+ "hdfc-ergo__personal-accident",
119
+ "HDFC ERGO Personal Accident Plan",
120
+ score=0.61,
121
+ policy_type=None, # no structured signal β€” name only
122
+ sum_insured_options=[2500000],
123
+ )
124
+ CRITICAL_ILLNESS = _chunk(
125
+ "max-life__critical-illness",
126
+ "Max Critical Illness Secure",
127
+ score=0.60,
128
+ policy_type="fixed_benefit",
129
+ policy_type_canonical="fixed_benefit",
130
+ sum_insured_options=[1500000],
131
+ )
132
+ GOOD_INDEMNITY = _chunk(
133
+ "niva-bupa__reassure-2",
134
+ "ReAssure 2.0",
135
+ score=0.55,
136
+ policy_type="family_floater",
137
+ policy_type_canonical="indemnity",
138
+ copay_pct=0,
139
+ sum_insured_options=[1000000, 1500000, 2000000, 5000000],
140
+ grade="A",
141
+ overall_score=88,
142
+ )
143
+
144
+
145
+ class TestComprehensiveIntentDetection(unittest.TestCase):
146
+ def test_failing_profile_signals_comprehensive_indemnity(self):
147
+ self.assertTrue(
148
+ _wants_comprehensive_indemnity(COMPREHENSIVE_PROFILE),
149
+ "First policy + no base cover + desired SI + general goal must "
150
+ "register as a comprehensive-indemnity intent.",
151
+ )
152
+
153
+ def test_explicit_supplement_goal_does_not_fire(self):
154
+ supplement = dict(
155
+ COMPREHENSIVE_PROFILE, primary_goal="critical illness cover only"
156
+ )
157
+ self.assertFalse(
158
+ _wants_comprehensive_indemnity(supplement),
159
+ "An explicit critical-illness-only goal must NOT trigger the "
160
+ "comprehensive-indemnity intent (don't drop CI plans for them).",
161
+ )
162
+
163
+ def test_topup_goal_does_not_fire(self):
164
+ topup = dict(
165
+ COMPREHENSIVE_PROFILE,
166
+ primary_goal="top-up over existing employer cover",
167
+ existing_cover_inr=500000,
168
+ )
169
+ self.assertFalse(
170
+ _wants_comprehensive_indemnity(topup),
171
+ "A top-up supplement goal must NOT trigger comprehensive intent.",
172
+ )
173
+
174
+ def test_no_desired_si_does_not_fire(self):
175
+ vague = dict(COMPREHENSIVE_PROFILE)
176
+ vague.pop("desired_sum_insured_inr")
177
+ vague["primary_goal"] = ""
178
+ self.assertFalse(
179
+ _wants_comprehensive_indemnity(vague),
180
+ "Be conservative: with no desired SI and no goal signal the "
181
+ "intent should not fire.",
182
+ )
183
+
184
+
185
+ class TestFixedBenefitClassification(unittest.TestCase):
186
+ def test_star_hospital_cash_classified_fixed_benefit(self):
187
+ self.assertTrue(
188
+ _is_fixed_benefit_chunk(STAR_HOSPITAL_CASH),
189
+ "Star Hospital Cash (policy_type='hospital_cash' + name) is a "
190
+ "fixed-benefit product.",
191
+ )
192
+
193
+ def test_personal_accident_by_name(self):
194
+ self.assertTrue(_is_fixed_benefit_chunk(PERSONAL_ACCIDENT))
195
+
196
+ def test_critical_illness_by_canonical_key(self):
197
+ self.assertTrue(_is_fixed_benefit_chunk(CRITICAL_ILLNESS))
198
+
199
+ def test_indemnity_not_classified_fixed(self):
200
+ self.assertFalse(_is_fixed_benefit_chunk(GOOD_INDEMNITY))
201
+
202
+ def test_real_facts_file_surfaces_policy_type(self):
203
+ facts = _load_policy_facts("star-health__star-hospital-cash__brochure")
204
+ self.assertEqual(
205
+ facts.get("policy_type"), "hospital_cash",
206
+ "brain_tools._FACT_KEYS must include `policy_type` so the "
207
+ "fixed-benefit signal reaches retrieval_filters on the live path.",
208
+ )
209
+
210
+
211
+ class TestFixedBenefitExclusion(unittest.TestCase):
212
+ def test_star_hospital_cash_dropped_for_comprehensive_profile(self):
213
+ kept = apply_eligibility_filter(
214
+ [STAR_HOSPITAL_CASH, GOOD_INDEMNITY], COMPREHENSIVE_PROFILE
215
+ )
216
+ ids = {c["policy_id"] for c in kept}
217
+ self.assertNotIn(
218
+ "star-health__star-hospital-cash__brochure", ids,
219
+ "Star Hospital Cash (fixed-benefit) must be hard-dropped for a "
220
+ "user who clearly wants comprehensive indemnity cover.",
221
+ )
222
+ self.assertIn("niva-bupa__reassure-2", ids)
223
+
224
+ def test_all_fixed_benefit_shapes_dropped(self):
225
+ kept = apply_eligibility_filter(
226
+ [STAR_HOSPITAL_CASH, PERSONAL_ACCIDENT, CRITICAL_ILLNESS,
227
+ GOOD_INDEMNITY],
228
+ COMPREHENSIVE_PROFILE,
229
+ )
230
+ ids = {c["policy_id"] for c in kept}
231
+ self.assertEqual(
232
+ ids, {"niva-bupa__reassure-2"},
233
+ "Every fixed-benefit shape (hospital cash / PA / CI) must be "
234
+ "dropped; only the indemnity plan survives.",
235
+ )
236
+
237
+ def test_fixed_benefit_kept_for_explicit_ci_seeker(self):
238
+ ci_seeker = dict(
239
+ COMPREHENSIVE_PROFILE,
240
+ primary_goal="critical illness cover only",
241
+ )
242
+ kept = apply_eligibility_filter([CRITICAL_ILLNESS], ci_seeker)
243
+ self.assertEqual(
244
+ len(kept), 1,
245
+ "A user who explicitly wants critical-illness cover must still "
246
+ "see CI plans β€” do NOT exclude fixed-benefit for them.",
247
+ )
248
+
249
+ def test_fixed_benefit_kept_for_supplement_seeker_with_base(self):
250
+ supp = dict(
251
+ COMPREHENSIVE_PROFILE,
252
+ primary_goal="add a hospital cash add-on to my existing plan",
253
+ existing_cover_inr=500000,
254
+ )
255
+ kept = apply_eligibility_filter([STAR_HOSPITAL_CASH], supp)
256
+ self.assertEqual(
257
+ len(kept), 1,
258
+ "Someone with existing base cover wanting a hospital-cash add-on "
259
+ "must still see hospital-cash plans.",
260
+ )
261
+
262
+ def test_non_policy_chunks_never_dropped(self):
263
+ reg = _chunk("irdai__circular", "IRDAI Hospital Cash Circular",
264
+ doc_type="regulatory", policy_type="hospital_cash")
265
+ kept = apply_eligibility_filter([reg], COMPREHENSIVE_PROFILE)
266
+ self.assertEqual(len(kept), 1,
267
+ "Regulatory/review/profile chunks are never policies.")
268
+
269
+
270
+ class TestFixedBenefitRanking(unittest.TestCase):
271
+ def test_indemnity_outranks_surviving_fixed_benefit(self):
272
+ # Profile where the comprehensive intent does NOT hard-drop (no
273
+ # desired SI, no comprehensive goal token) so fixed-benefit
274
+ # survives the eligibility filter β€” it must still rank BELOW the
275
+ # indemnity plan via the belt-and-braces demotion.
276
+ vague = {
277
+ "age": 29, "location_tier": "metro", "income_band": "25L+",
278
+ "primary_goal": "", "dependents": "self",
279
+ }
280
+ ranked = rank_by_profile_fit(
281
+ [STAR_HOSPITAL_CASH, GOOD_INDEMNITY], vague
282
+ )
283
+ order = [c["policy_id"] for c in ranked]
284
+ self.assertLess(
285
+ order.index("niva-bupa__reassure-2"),
286
+ order.index("star-health__star-hospital-cash__brochure"),
287
+ "A comprehensive indemnity plan must rank above a fixed-benefit "
288
+ "daily-cash plan.",
289
+ )
290
+
291
+
292
+ class TestFilterPipelineLivePath(unittest.TestCase):
293
+ """End-to-end through the SAME filter_pipeline single_brain ->
294
+ brain_tools.retrieve_policies -> retrieval_filters.filter_pipeline uses."""
295
+
296
+ def test_failing_session_star_hospital_cash_not_top(self):
297
+ catalog = [
298
+ STAR_HOSPITAL_CASH, PERSONAL_ACCIDENT, CRITICAL_ILLNESS,
299
+ GOOD_INDEMNITY,
300
+ ]
301
+ filtered, guard = filter_pipeline(
302
+ catalog,
303
+ profile=COMPREHENSIVE_PROFILE,
304
+ query="first health policy metro 15 lakh sum insured zero co-pay",
305
+ intent="recommendation",
306
+ )
307
+ ids = [c["policy_id"] for c in filtered]
308
+ self.assertNotIn(
309
+ "star-health__star-hospital-cash__brochure", ids,
310
+ "Star Hospital Cash must NOT reach the brain for this profile.",
311
+ )
312
+ self.assertTrue(ids, "the comprehensive indemnity plan must survive")
313
+ self.assertEqual(
314
+ ids[0], "niva-bupa__reassure-2",
315
+ "Top recommendation must be the comprehensive indemnity plan.",
316
+ )
317
+
318
+ def test_real_facts_file_through_pipeline(self):
319
+ pid = "star-health__star-hospital-cash__brochure"
320
+ chunk = {
321
+ "policy_id": pid,
322
+ "policy_name": "Star Hospital Cash",
323
+ "insurer_slug": "star-health",
324
+ "doc_type": "policy",
325
+ "score": 0.72,
326
+ "chunk_text": "fixed benefit policy pays a fixed amount per day",
327
+ }
328
+ chunk.update(_load_policy_facts(pid))
329
+ filtered, _ = filter_pipeline(
330
+ [chunk, GOOD_INDEMNITY],
331
+ profile=COMPREHENSIVE_PROFILE,
332
+ query="first health policy 15 lakh zero copay",
333
+ intent="recommendation",
334
+ )
335
+ ids = [c["policy_id"] for c in filtered]
336
+ self.assertNotIn(
337
+ pid, ids,
338
+ "Using the REAL policy_facts file, Star Hospital Cash must be "
339
+ "dropped on the live path.",
340
+ )
341
+
342
+
343
+ if __name__ == "__main__":
344
+ unittest.main()
tests/test_profile_recall_session_isolation.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression tests β€” fresh no-cookie session must NOT inherit a stranger's
2
+ profile via a weak/shared name key (privacy audit, 2026-05-16).
3
+
4
+ AUDIT FINDING
5
+ -------------
6
+ A live test opened a FRESH browser context with zero cookies and was still
7
+ greeted "Welcome back, Rahul! … Based on our last conversation…" β€” the
8
+ backend restored a prior on-disk profile into a brand-new session.
9
+
10
+ ROOT CAUSE
11
+ ----------
12
+ The turn-1 recall path was keyed on the user-STATED NAME, not the session:
13
+
14
+ single_brain.handle_turn (turn 1)
15
+ -> profile_persistence.try_recall_by_name(session, name)
16
+ -> session_state.rehydrate_by_name(session, name)
17
+ -> profile_store.load_profile(name) # <-- name-slug keyed file
18
+ + a directory scan that returned ANY persona-id file whose stored
19
+ display-name matched the slug.
20
+
21
+ So a second real user on a shared browser/IP β€” or anyone who simply states
22
+ a common first name ("I'm Rahul") β€” was AUTO-MERGED a stranger's captured
23
+ profile and greeted "Welcome back" with no confirmation.
24
+
25
+ INTENDED SAFE DESIGN (KI-196 / ADR-041, specced but never wired)
26
+ ----------------------------------------------------------------
27
+ `SessionState.pending_profile_recall` β€” a name match is STAGED, not merged.
28
+ The profile is only applied after an EXPLICIT user affirmation. A fresh
29
+ session is NEVER silently greeted with a stored stranger profile.
30
+
31
+ These tests pin:
32
+
33
+ 1. try_recall_by_name does NOT auto-merge a stored profile into a fresh
34
+ session; it stages it on `session.pending_profile_recall`.
35
+ 2. After staging, `session.profile` still has NO recalled fields β†’ the
36
+ "Welcome back" / is_returning_user signal stays False.
37
+ 3. An explicit AFFIRM (apply_pending_recall) merges the staged profile β€”
38
+ legitimate returning-user continuity is preserved.
39
+ 4. An explicit DENY discards the staged profile and leaves the session
40
+ blank.
41
+ 5. Same-session continuity (slots captured within THIS conversation)
42
+ is untouched β€” only cross-session NAME recall is gated.
43
+ 6. load_profile no longer leaks a stranger's persona-id file via the
44
+ display-name directory scan (cross-identity leak vector removed).
45
+
46
+ Run:
47
+ cd /Users/rohitsar/Developer/Insurance\\ Sales\\ Bot
48
+ PYTHONPATH=$PWD .venv/bin/python -m pytest \\
49
+ tests/test_profile_recall_session_isolation.py -v
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import json
55
+ import sys
56
+ import tempfile
57
+ import unittest
58
+ import uuid
59
+ from pathlib import Path
60
+ from unittest import mock
61
+
62
+ _REPO_ROOT = Path(__file__).resolve().parent.parent
63
+ if str(_REPO_ROOT) not in sys.path:
64
+ sys.path.insert(0, str(_REPO_ROOT))
65
+
66
+ from backend.needs_finder import Profile # noqa: E402
67
+
68
+
69
+ def _write_stored_profile(profiles_dir: Path, slug: str, prof_fields: dict,
70
+ *, display: str, persona_id: str | None = None):
71
+ """Write a profile JSON the way profile_store.save_profile would."""
72
+ profiles_dir.mkdir(parents=True, exist_ok=True)
73
+ fname = f"{persona_id}.json" if persona_id else f"{slug}.json"
74
+ payload = {
75
+ "name_display": display,
76
+ "name_slug": slug,
77
+ "persona_id": persona_id,
78
+ "profile": {**{f.name: getattr(Profile(), f.name)
79
+ for f in Profile.__dataclass_fields__.values()},
80
+ **prof_fields},
81
+ "first_seen": "2026-05-15T00:00:00Z",
82
+ "last_seen": "2026-05-15T00:00:00Z",
83
+ "sessions": ["stranger_sess_1"],
84
+ }
85
+ (profiles_dir / fname).write_text(json.dumps(payload, indent=2, default=str))
86
+
87
+
88
+ class _ProfilesDirMixin(unittest.TestCase):
89
+ """Point profile_store at an isolated temp profiles dir for the test."""
90
+
91
+ def setUp(self):
92
+ self._tmp = tempfile.TemporaryDirectory()
93
+ self._profiles_dir = Path(self._tmp.name) / "profiles"
94
+ self._profiles_dir.mkdir(parents=True, exist_ok=True)
95
+ # profile_store reads module-level _PROFILES_DIR for every path op.
96
+ import backend.profile_store as ps
97
+ self._ps = ps
98
+ self._patch = mock.patch.object(ps, "_PROFILES_DIR", self._profiles_dir)
99
+ self._patch.start()
100
+
101
+ def tearDown(self):
102
+ self._patch.stop()
103
+ self._tmp.cleanup()
104
+
105
+
106
+ class TestFreshSessionDoesNotInheritStrangerProfile(_ProfilesDirMixin):
107
+ """Core privacy guarantee."""
108
+
109
+ def _fresh_session(self):
110
+ from backend.session_state import SessionState
111
+ return SessionState(session_id=f"fresh_{uuid.uuid4().hex[:8]}")
112
+
113
+ def test_try_recall_by_name_does_not_auto_merge(self):
114
+ """A stranger named 'Rahul' has a stored profile. A FRESH session
115
+ states 'Rahul' on turn 1. The stored profile must NOT be merged
116
+ into session.profile, and must NOT flag a returning user."""
117
+ _write_stored_profile(
118
+ self._profiles_dir, "rahul",
119
+ {"name": "Rahul", "age": 41, "dependents": "self+spouse+kids",
120
+ "location_tier": "metro", "income_band": "10L-25L"},
121
+ display="Rahul",
122
+ )
123
+
124
+ from backend.profile_persistence import try_recall_by_name
125
+
126
+ sess = self._fresh_session()
127
+ result = try_recall_by_name(sess, "Rahul")
128
+
129
+ # NOT auto-applied β†’ caller must not treat as returning user.
130
+ self.assertFalse(
131
+ result,
132
+ "REGRESSION (privacy): try_recall_by_name auto-merged a stored "
133
+ "stranger profile into a fresh session. It must stage, not merge.",
134
+ )
135
+ # session.profile must still be blank β€” no leaked PII.
136
+ self.assertIsNone(sess.profile.age)
137
+ self.assertIsNone(sess.profile.dependents)
138
+ self.assertIsNone(sess.profile.location_tier)
139
+ self.assertIn(
140
+ sess.profile.name, (None, ""),
141
+ "REGRESSION (privacy): stranger name leaked onto fresh session.",
142
+ )
143
+
144
+ def test_match_is_staged_for_confirmation(self):
145
+ """The match IS detected β€” it's staged on pending_profile_recall so
146
+ the brain can ASK 'are you Rahul?' rather than silently greet."""
147
+ _write_stored_profile(
148
+ self._profiles_dir, "rahul",
149
+ {"name": "Rahul", "age": 41, "location_tier": "metro"},
150
+ display="Rahul",
151
+ )
152
+ from backend.profile_persistence import try_recall_by_name
153
+
154
+ sess = self._fresh_session()
155
+ try_recall_by_name(sess, "Rahul")
156
+
157
+ self.assertIsNotNone(
158
+ sess.pending_profile_recall,
159
+ "Expected the name match to be STAGED on pending_profile_recall.",
160
+ )
161
+ self.assertEqual(sess.pending_profile_recall["name"], "Rahul")
162
+ # Staged summary carries identity hints for the confirm prompt, but
163
+ # they are NOT on the live profile.
164
+ self.assertIn("summary", sess.pending_profile_recall)
165
+ self.assertIsNone(sess.profile.age)
166
+
167
+ def test_no_match_stages_nothing(self):
168
+ """Distinct identity with no stored file β†’ no staging, no leak
169
+ (mirrors the Zenobia control from the audit)."""
170
+ from backend.profile_persistence import try_recall_by_name
171
+
172
+ sess = self._fresh_session()
173
+ result = try_recall_by_name(sess, "Zenobia")
174
+ self.assertFalse(result)
175
+ self.assertIsNone(sess.pending_profile_recall)
176
+ self.assertIsNone(sess.profile.age)
177
+
178
+
179
+ class TestExplicitConfirmationFlow(_ProfilesDirMixin):
180
+ """Legitimate returning-user continuity must still work β€” on opt-in."""
181
+
182
+ def test_affirm_applies_staged_profile(self):
183
+ _write_stored_profile(
184
+ self._profiles_dir, "priya",
185
+ {"name": "Priya", "age": 33, "dependents": "self+spouse",
186
+ "location_tier": "tier1"},
187
+ display="Priya",
188
+ )
189
+ from backend.profile_persistence import try_recall_by_name
190
+ from backend.session_state import SessionState, apply_pending_recall
191
+
192
+ sess = SessionState(session_id="ret_user_1")
193
+ try_recall_by_name(sess, "Priya")
194
+ self.assertIsNotNone(sess.pending_profile_recall)
195
+
196
+ # User explicitly confirms "yes, that's me".
197
+ applied = apply_pending_recall(sess, confirmed=True)
198
+ self.assertTrue(applied)
199
+ self.assertEqual(sess.profile.name, "Priya")
200
+ self.assertEqual(sess.profile.age, 33)
201
+ self.assertEqual(sess.profile.dependents, "self+spouse")
202
+ self.assertEqual(sess.profile.location_tier, "tier1")
203
+ # Staging cleared after apply.
204
+ self.assertIsNone(sess.pending_profile_recall)
205
+
206
+ def test_deny_discards_staged_profile(self):
207
+ _write_stored_profile(
208
+ self._profiles_dir, "rahul",
209
+ {"name": "Rahul", "age": 41, "location_tier": "metro"},
210
+ display="Rahul",
211
+ )
212
+ from backend.profile_persistence import try_recall_by_name
213
+ from backend.session_state import SessionState, apply_pending_recall
214
+
215
+ sess = SessionState(session_id="not_rahul_1")
216
+ try_recall_by_name(sess, "Rahul")
217
+ self.assertIsNotNone(sess.pending_profile_recall)
218
+
219
+ # User says "no, I'm not Rahul" (or just continues with new facts).
220
+ applied = apply_pending_recall(sess, confirmed=False)
221
+ self.assertFalse(applied)
222
+ self.assertIsNone(sess.pending_profile_recall)
223
+ self.assertIsNone(sess.profile.age)
224
+ self.assertIn(sess.profile.name, (None, ""))
225
+
226
+
227
+ class TestSameSessionContinuityPreserved(_ProfilesDirMixin):
228
+ """Slots captured within THIS conversation must never be gated/lost."""
229
+
230
+ def test_in_conversation_capture_untouched(self):
231
+ from backend.session_state import get_session, reset_session
232
+
233
+ sid = f"same_sess_{uuid.uuid4().hex[:8]}"
234
+ reset_session(sid)
235
+ sess = get_session(sid)
236
+ # Simulate brain_tools.save_profile_field within this conversation.
237
+ sess.profile.name = "Anjali"
238
+ sess.profile.age = 29
239
+ sess.profile.location_tier = "tier2"
240
+
241
+ # Same-session continuity is in-memory and must persist verbatim.
242
+ again = get_session(sid)
243
+ self.assertIs(again, sess)
244
+ self.assertEqual(again.profile.name, "Anjali")
245
+ self.assertEqual(again.profile.age, 29)
246
+ self.assertEqual(again.profile.location_tier, "tier2")
247
+ self.assertIsNone(again.pending_profile_recall)
248
+ reset_session(sid)
249
+
250
+
251
+ class TestLoadProfileNoCrossIdentityScan(_ProfilesDirMixin):
252
+ """The display-name directory scan in load_profile was a pure leak
253
+ vector β€” a fresh visitor stating a common first name pulled a random
254
+ persona-id file. It must no longer cross identities."""
255
+
256
+ def test_persona_id_file_not_returned_by_bare_name(self):
257
+ # Stranger stored under a persona-id filename (different age/city),
258
+ # NOT under the bare name slug.
259
+ _write_stored_profile(
260
+ self._profiles_dir, "rohit",
261
+ {"name": "Rohit", "age": 52, "location_tier": "tier3"},
262
+ display="Rohit", persona_id="deadbeef1234",
263
+ )
264
+ # No rohit.json (bare slug) exists.
265
+ self.assertFalse((self._profiles_dir / "rohit.json").exists())
266
+
267
+ loaded = self._ps.load_profile("Rohit") # no persona_id supplied
268
+ self.assertIsNone(
269
+ loaded,
270
+ "REGRESSION (privacy): load_profile returned a stranger's "
271
+ "persona-id-keyed profile via the display-name directory scan. "
272
+ "Bare-name lookup must NOT cross persona identities.",
273
+ )
274
+
275
+ def test_exact_slug_file_still_loads(self):
276
+ """Legitimate same-name slug file (the user's own) still resolves β€”
277
+ we only removed the cross-persona scan, not the direct slug path."""
278
+ _write_stored_profile(
279
+ self._profiles_dir, "meera",
280
+ {"name": "Meera", "age": 38},
281
+ display="Meera",
282
+ )
283
+ loaded = self._ps.load_profile("Meera")
284
+ self.assertIsNotNone(loaded)
285
+ self.assertEqual(loaded.age, 38)
286
+
287
+
288
+ if __name__ == "__main__":
289
+ unittest.main(verbosity=2)
tests/test_recall_confirm_flow.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression tests β€” confirmation-gated cross-session recall in single_brain.
2
+
3
+ CONTEXT
4
+ -------
5
+ The privacy fix (2026-05-16) made `session_state.rehydrate_by_name` STAGE a
6
+ name match on `session.pending_profile_recall` and ALWAYS return False (it no
7
+ longer auto-merges a stranger's profile). That closed the leak but a genuine
8
+ returning user had to re-enter everything.
9
+
10
+ This restores legitimate returning-user continuity SAFELY inside
11
+ `single_brain.handle_turn`:
12
+
13
+ STEP 1 (turn 1): if a name match is staged AND not yet asked, the brain
14
+ short-circuits with a one-line "Welcome back β€” are you the same
15
+ <name>? (yes/no)" prompt. NOTHING is merged. Only the name (which
16
+ the user themselves stated) is surfaced β€” never the stored PII.
17
+ STEP 2 (next turn): the user's answer is classified.
18
+ affirmative β†’ session_state.apply_pending_recall(confirmed=True)
19
+ (fills empty slots; live-conversation slots win).
20
+ anything else β†’ apply_pending_recall(confirmed=False) (discard,
21
+ fail closed). Staging is cleared either way so the
22
+ brain asks ONLY ONCE.
23
+
24
+ TEST STRATEGY
25
+ -------------
26
+ STEP 1 short-circuits with NO Gemini call, so we assert directly on its
27
+ TurnResult. STEP 2 resolves the staged recall (apply / discard) BEFORE the
28
+ Gemini path runs; we mock `single_brain._gemini_call` to raise so the turn
29
+ stops right after the recall block, letting us assert the profile / staging
30
+ side effects deterministically (independent of any real GOOGLE_API_KEY).
31
+
32
+ Run:
33
+ cd /Users/rohitsar/Developer/Insurance\\ Sales\\ Bot
34
+ PYTHONPATH=$PWD .venv/bin/python -m pytest \\
35
+ tests/test_recall_confirm_flow.py -v
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import asyncio
41
+ import json
42
+ import sys
43
+ import tempfile
44
+ import unittest
45
+ import uuid
46
+ from pathlib import Path
47
+ from unittest import mock
48
+
49
+ _REPO_ROOT = Path(__file__).resolve().parent.parent
50
+ if str(_REPO_ROOT) not in sys.path:
51
+ sys.path.insert(0, str(_REPO_ROOT))
52
+
53
+ from backend.needs_finder import Profile # noqa: E402
54
+ from backend import single_brain # noqa: E402
55
+
56
+
57
+ def _write_stored_profile(profiles_dir: Path, slug: str, prof_fields: dict,
58
+ *, display: str, persona_id: str | None = None):
59
+ """Write a profile JSON the way profile_store.save_profile would
60
+ (mirrors tests/test_profile_recall_session_isolation.py)."""
61
+ profiles_dir.mkdir(parents=True, exist_ok=True)
62
+ fname = f"{persona_id}.json" if persona_id else f"{slug}.json"
63
+ payload = {
64
+ "name_display": display,
65
+ "name_slug": slug,
66
+ "persona_id": persona_id,
67
+ "profile": {**{f.name: getattr(Profile(), f.name)
68
+ for f in Profile.__dataclass_fields__.values()},
69
+ **prof_fields},
70
+ "first_seen": "2026-05-15T00:00:00Z",
71
+ "last_seen": "2026-05-15T00:00:00Z",
72
+ "sessions": ["stranger_sess_1"],
73
+ }
74
+ (profiles_dir / fname).write_text(json.dumps(payload, indent=2, default=str))
75
+
76
+
77
+ def _run(coro):
78
+ return asyncio.new_event_loop().run_until_complete(coro)
79
+
80
+
81
+ async def _boom(*_a, **_k):
82
+ """Stand-in for _gemini_call β€” raises so handle_turn stops right after
83
+ the recall block. STEP 1 never reaches this (it short-circuits); STEP 2
84
+ resolves the staged recall BEFORE this fires, so the profile/staging
85
+ side effects are observable on the session afterwards."""
86
+ raise single_brain.SingleBrainError("stubbed: no Gemini in unit test")
87
+
88
+
89
+ class _RecallTestBase(unittest.TestCase):
90
+ """Isolated temp profiles dir + a stubbed Gemini boundary."""
91
+
92
+ def setUp(self):
93
+ self._tmp = tempfile.TemporaryDirectory()
94
+ self._profiles_dir = Path(self._tmp.name) / "profiles"
95
+ self._profiles_dir.mkdir(parents=True, exist_ok=True)
96
+ import backend.profile_store as ps
97
+ self._ps = ps
98
+ self._pp = mock.patch.object(ps, "_PROFILES_DIR", self._profiles_dir)
99
+ self._pp.start()
100
+ # Stub the only network boundary so STEP 2 / non-recall turns stop
101
+ # deterministically right after the recall block.
102
+ self._gp = mock.patch.object(single_brain, "_gemini_call", _boom)
103
+ self._gp.start()
104
+
105
+ def tearDown(self):
106
+ self._gp.stop()
107
+ self._pp.stop()
108
+ self._tmp.cleanup()
109
+
110
+ def _fresh_session(self):
111
+ from backend.session_state import SessionState
112
+ return SessionState(session_id=f"fresh_{uuid.uuid4().hex[:8]}")
113
+
114
+
115
+ class TestClassifyRecallAnswer(unittest.TestCase):
116
+ """Pure yes/no classifier β€” affirm ONLY on a clear yes; fail closed."""
117
+
118
+ def test_affirmatives(self):
119
+ from backend.single_brain import _classify_recall_answer
120
+ for s in ("yes", "Yes", "yep", "yeah", "yup", "haan",
121
+ "yes, that's me", "Yes that's me!", "correct",
122
+ "ya that's right", "sure", "ok", "it's me",
123
+ "yes I'm the same person", "the same"):
124
+ self.assertTrue(
125
+ _classify_recall_answer(s),
126
+ f"expected affirmative for {s!r}",
127
+ )
128
+
129
+ def test_negatives_and_ambiguous_fail_closed(self):
130
+ from backend.single_brain import _classify_recall_answer
131
+ for s in ("no", "nope", "nah", "not me", "I'm someone else",
132
+ "no thanks, I'm new", "", " ", "no, that's me",
133
+ "different person", "wrong person",
134
+ "I want health insurance for my family",
135
+ "actually I have a question about premiums"):
136
+ self.assertFalse(
137
+ _classify_recall_answer(s),
138
+ f"expected non-affirm (fail closed) for {s!r}",
139
+ )
140
+
141
+
142
+ class TestStep1AsksConfirmationNoAutoMerge(_RecallTestBase):
143
+ """Turn 1: a staged match must produce a one-line confirm prompt and
144
+ must NOT merge the stored profile or leak its PII."""
145
+
146
+ def test_turn1_asks_and_does_not_merge(self):
147
+ _write_stored_profile(
148
+ self._profiles_dir, "rahul",
149
+ {"name": "Rahul", "age": 41, "dependents": "self+spouse+kids",
150
+ "location_tier": "metro", "income_band": "10L-25L"},
151
+ display="Rahul",
152
+ )
153
+ sess = self._fresh_session()
154
+
155
+ res = _run(single_brain.handle_turn(sess, "Hi, I'm Rahul"))
156
+
157
+ # One-line confirmation prompt, short-circuited (no Gemini call β€”
158
+ # _boom was NOT hit).
159
+ self.assertEqual(res.intent, "recall_confirm")
160
+ self.assertIn("Rahul", res.reply_text)
161
+ self.assertIn("yes/no", res.reply_text.lower())
162
+ self.assertEqual(res.citations, [])
163
+
164
+ # NOTHING merged onto the live profile (privacy: no leaked PII).
165
+ self.assertIsNone(sess.profile.age)
166
+ self.assertIsNone(sess.profile.dependents)
167
+ self.assertIsNone(sess.profile.location_tier)
168
+ self.assertIsNone(sess.profile.income_band)
169
+ self.assertIn(sess.profile.name, (None, ""))
170
+
171
+ # Match still staged, now marked prompted (ask-once guard armed).
172
+ self.assertIsNotNone(sess.pending_profile_recall)
173
+ self.assertTrue(sess.pending_profile_recall.get("prompted"))
174
+
175
+ # The reply must NOT contain stored PII (only the user-stated name).
176
+ self.assertNotIn("41", res.reply_text)
177
+ self.assertNotIn("metro", res.reply_text.lower())
178
+ self.assertNotIn("10L-25L", res.reply_text)
179
+
180
+ def test_no_stored_match_no_confirm_prompt(self):
181
+ """No stored file β†’ no staging, no confirm short-circuit; the turn
182
+ falls through to the (stubbed) brain."""
183
+ sess = self._fresh_session()
184
+ with self.assertRaises(single_brain.SingleBrainError):
185
+ _run(single_brain.handle_turn(sess, "Hi, I'm Zenobia"))
186
+ self.assertIsNone(sess.pending_profile_recall)
187
+ self.assertIn(sess.profile.name, (None, ""))
188
+
189
+
190
+ class TestStep2YesApplies(_RecallTestBase):
191
+ """The next turn's 'yes' applies the staged profile (continuity)."""
192
+
193
+ def test_yes_applies_staged_profile(self):
194
+ _write_stored_profile(
195
+ self._profiles_dir, "priya",
196
+ {"name": "Priya", "age": 33, "dependents": "self+spouse",
197
+ "location_tier": "tier1", "income_band": "10L-25L"},
198
+ display="Priya",
199
+ )
200
+ sess = self._fresh_session()
201
+
202
+ r1 = _run(single_brain.handle_turn(sess, "Hi I'm Priya"))
203
+ self.assertEqual(r1.intent, "recall_confirm")
204
+ self.assertIsNotNone(sess.pending_profile_recall)
205
+
206
+ # Turn 2: user affirms. apply_pending_recall runs BEFORE the stubbed
207
+ # brain β†’ SingleBrainError, with the profile side effect persisted.
208
+ with self.assertRaises(single_brain.SingleBrainError):
209
+ _run(single_brain.handle_turn(sess, "yes that's me"))
210
+
211
+ self.assertEqual(sess.profile.name, "Priya")
212
+ self.assertEqual(sess.profile.age, 33)
213
+ self.assertEqual(sess.profile.dependents, "self+spouse")
214
+ self.assertEqual(sess.profile.location_tier, "tier1")
215
+ self.assertEqual(sess.profile.income_band, "10L-25L")
216
+ # Staging cleared (resolved).
217
+ self.assertIsNone(sess.pending_profile_recall)
218
+
219
+
220
+ class TestStep2NoDiscards(_RecallTestBase):
221
+ """The next turn's 'no' (or anything ambiguous) discards the staged
222
+ profile and continues as a fresh, blank profile (fail closed)."""
223
+
224
+ def test_no_discards_staged_profile(self):
225
+ _write_stored_profile(
226
+ self._profiles_dir, "rahul",
227
+ {"name": "Rahul", "age": 41, "location_tier": "metro"},
228
+ display="Rahul",
229
+ )
230
+ sess = self._fresh_session()
231
+
232
+ r1 = _run(single_brain.handle_turn(sess, "Hi I'm Rahul"))
233
+ self.assertEqual(r1.intent, "recall_confirm")
234
+ self.assertIsNotNone(sess.pending_profile_recall)
235
+
236
+ with self.assertRaises(single_brain.SingleBrainError):
237
+ _run(single_brain.handle_turn(sess, "no, I'm a new user"))
238
+
239
+ # Nothing merged; staging cleared.
240
+ self.assertIsNone(sess.pending_profile_recall)
241
+ self.assertIsNone(sess.profile.age)
242
+ self.assertIsNone(sess.profile.location_tier)
243
+ self.assertIn(sess.profile.name, (None, ""))
244
+
245
+ def test_ambiguous_answer_fails_closed(self):
246
+ """A non-yes/no message (e.g. just asking a question) must DISCARD
247
+ the staged stranger profile β€” never silently merge it."""
248
+ _write_stored_profile(
249
+ self._profiles_dir, "rahul",
250
+ {"name": "Rahul", "age": 41, "location_tier": "metro"},
251
+ display="Rahul",
252
+ )
253
+ sess = self._fresh_session()
254
+ _run(single_brain.handle_turn(sess, "Hi I'm Rahul"))
255
+ self.assertIsNotNone(sess.pending_profile_recall)
256
+
257
+ with self.assertRaises(single_brain.SingleBrainError):
258
+ _run(single_brain.handle_turn(
259
+ sess, "What's the cheapest family floater you have?"))
260
+
261
+ self.assertIsNone(sess.pending_profile_recall)
262
+ self.assertIsNone(sess.profile.age)
263
+ self.assertIn(sess.profile.name, (None, ""))
264
+
265
+
266
+ class TestAskOnlyOnce(_RecallTestBase):
267
+ """The confirm prompt must fire exactly ONCE, then resolve."""
268
+
269
+ def test_second_turn_is_resolution_not_a_reprompt(self):
270
+ _write_stored_profile(
271
+ self._profiles_dir, "meera",
272
+ {"name": "Meera", "age": 38, "location_tier": "tier2"},
273
+ display="Meera",
274
+ )
275
+ sess = self._fresh_session()
276
+
277
+ r1 = _run(single_brain.handle_turn(sess, "Hello, my name is Meera"))
278
+ self.assertEqual(r1.intent, "recall_confirm")
279
+ self.assertTrue(sess.pending_profile_recall.get("prompted"))
280
+
281
+ # Turn 2 must NOT be another recall_confirm prompt β€” it resolves the
282
+ # staging (then proceeds, hitting the stubbed brain).
283
+ with self.assertRaises(single_brain.SingleBrainError):
284
+ _run(single_brain.handle_turn(sess, "yes"))
285
+ self.assertIsNone(sess.pending_profile_recall)
286
+ self.assertEqual(sess.profile.name, "Meera")
287
+ self.assertEqual(sess.profile.age, 38)
288
+
289
+ def test_live_slot_wins_over_stored_on_apply(self):
290
+ """apply_pending_recall fills only EMPTY slots β€” a value captured in
291
+ THIS conversation must NOT be overwritten by the stored one."""
292
+ _write_stored_profile(
293
+ self._profiles_dir, "arjun",
294
+ {"name": "Arjun", "age": 41, "location_tier": "metro"},
295
+ display="Arjun",
296
+ )
297
+ sess = self._fresh_session()
298
+ _run(single_brain.handle_turn(sess, "Hi I'm Arjun"))
299
+ self.assertIsNotNone(sess.pending_profile_recall)
300
+
301
+ # User corrected their age live before confirming continuity.
302
+ sess.profile.age = 29
303
+
304
+ with self.assertRaises(single_brain.SingleBrainError):
305
+ _run(single_brain.handle_turn(sess, "yes"))
306
+
307
+ # Live age preserved; only the EMPTY slot (location_tier) filled.
308
+ self.assertEqual(sess.profile.age, 29)
309
+ self.assertEqual(sess.profile.location_tier, "metro")
310
+ self.assertEqual(sess.profile.name, "Arjun")
311
+
312
+
313
+ class TestSameSessionContinuityUnaffected(_RecallTestBase):
314
+ """A normal in-conversation capture (turn_idx > 1, no staged recall)
315
+ must never trigger the confirm prompt or be gated."""
316
+
317
+ def test_no_pending_recall_no_confirm_prompt(self):
318
+ sess = self._fresh_session()
319
+ # Simulate slots captured earlier in THIS conversation.
320
+ sess.profile.name = "Anjali"
321
+ sess.profile.age = 29
322
+ sess.profile.location_tier = "tier2"
323
+ sess.turn_idx = 3 # mid-conversation, not turn 1
324
+
325
+ # No pending_profile_recall β†’ no recall_confirm short-circuit; the
326
+ # turn falls through to the stubbed brain.
327
+ with self.assertRaises(single_brain.SingleBrainError):
328
+ _run(single_brain.handle_turn(sess, "I have diabetes"))
329
+
330
+ # In-conversation profile untouched, no staging introduced.
331
+ self.assertEqual(sess.profile.name, "Anjali")
332
+ self.assertEqual(sess.profile.age, 29)
333
+ self.assertEqual(sess.profile.location_tier, "tier2")
334
+ self.assertIsNone(sess.pending_profile_recall)
335
+
336
+
337
+ if __name__ == "__main__":
338
+ unittest.main(verbosity=2)
tests/test_recommendation_fit_gate.py ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """KI-280 (2026-05-16) β€” UNIFIED recommendation-fit gate.
2
+
3
+ Pins all 7 personas from the live Playwright audit
4
+ (/tmp/persona_[1-7]_result.json) so the CITED card list and the advisory
5
+ prose are gated by the SAME fitness logic.
6
+
7
+ The unified gate (backend/retrieval_filters.filter_pipeline, on the live
8
+ single_brain β†’ brain_tools.retrieve_policies path) requires the cited set
9
+ to pass ALL of:
10
+
11
+ 1. Product-type vs intent β€” no fixed-benefit / hospital-cash / PA / CI
12
+ to a comprehensive-indemnity buyer (KI-279, preserved). Inverse
13
+ preserved: top-up seeker (P4) + explicit-CI seeker (P6) still get
14
+ those products.
15
+ 2. Hard eligibility β€” when insuring seniors / parents (~70), drop
16
+ plans whose max entry age can't accept them; surface senior-eligible.
17
+ 3. Required features β€” explicit maternity/newborn need β†’ only cite
18
+ plans whose facts confirm it (unverified ones ranked strictly below).
19
+ 4. Objective / fit ranking β€” cited list ordered by scorecard fit-score /
20
+ stated objective; #1 = best fit for THIS profile (fixes the
21
+ grade/rank inversion + P5 cost-objective lead).
22
+ 5. Dedup β€” same-product / marketing-variant duplicates
23
+ collapsed (shared canonical/UIN identity from policy_identity).
24
+
25
+ Audit personas (transcripts + observed-bad outcomes drive the asserts):
26
+
27
+ P1 Young first-timer comprehensive β€” Star Hospital Cash wrongly cited;
28
+ C/65 ranked above B/75. EXPECT: no fixed-benefit; #1 = best grade.
29
+ P2 Senior + PED β€” New National Parivar Mediclaim cited
30
+ twice; A/77 ranked LAST. EXPECT: deduped; A-grade #1.
31
+ P3 Family + maternity (very imp.) β€” non-maternity plans cited equal to
32
+ the maternity-confirmed one; Star Hospital Cash cited.
33
+ EXPECT: maternity-confirmed first, fixed-benefit dropped.
34
+ P4 Top-up seeker (INVERSE) β€” Advanced Top Up cited twice.
35
+ EXPECT: top-up KEPT (inverse preserved) + deduped.
36
+ P5 Budget, cost is #1 need β€” leads with non-cheapest.
37
+ EXPECT: cost-objective β‡’ cheapest-appropriate ranks first.
38
+ P6 Critical-illness seeker (INV.) β€” EXPECT: CI plans KEPT.
39
+ P7 Parents both 70 + PED β€” max-entry-65 plans cited; Chola
40
+ Flexi Supreme + Flexi Health (same insurer) both cited.
41
+ EXPECT: entry-age-65 plans dropped; senior-eligible surfaced; deduped.
42
+
43
+ Run:
44
+ .venv/bin/python -m pytest -q tests/test_recommendation_fit_gate.py
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ import unittest
50
+
51
+ from backend.policy_identity import canonical_key, normalize_uin, product_key
52
+ from backend.retrieval_filters import (
53
+ apply_eligibility_filter,
54
+ dedup_by_policy,
55
+ filter_pipeline,
56
+ rank_by_profile_fit,
57
+ )
58
+ from backend.single_brain import _build_recommendation_citations
59
+
60
+
61
+ def _chunk(
62
+ policy_id,
63
+ policy_name,
64
+ *,
65
+ score=0.5,
66
+ policy_type=None,
67
+ policy_type_canonical=None,
68
+ uin_code=None,
69
+ copay_pct=None,
70
+ sum_insured_options=None,
71
+ max_entry_age=None,
72
+ min_entry_age=None,
73
+ maternity=None,
74
+ newborn=None,
75
+ grade=None,
76
+ overall_score=None,
77
+ doc_type="policy",
78
+ ):
79
+ """Chunk dict shaped like brain_tools.retrieve_policies output AFTER the
80
+ policy_facts + scorecard enrichment step (KI-280 added uin_code /
81
+ max_entry_age / maternity_coverage / newborn_coverage)."""
82
+ return {
83
+ "policy_id": policy_id,
84
+ "policy_name": policy_name,
85
+ "insurer_slug": policy_id.split("__")[0],
86
+ "doc_type": doc_type,
87
+ "score": score,
88
+ "chunk_text": "",
89
+ "policy_type_indemnity_or_fixed": policy_type_canonical,
90
+ "policy_type": policy_type,
91
+ "uin_code": uin_code,
92
+ "deductible_amount": None,
93
+ "co_payment_pct": copay_pct,
94
+ "sum_insured_options": sum_insured_options,
95
+ "max_entry_age": max_entry_age,
96
+ "min_entry_age": min_entry_age,
97
+ "maternity_coverage": maternity,
98
+ "newborn_coverage": newborn,
99
+ "_grade": grade,
100
+ "_overall_score": overall_score,
101
+ }
102
+
103
+
104
+ # ── Shared catalog slices ───────────────────────────────────────────────────
105
+
106
+ GOOD_INDEMNITY_A = _chunk(
107
+ "niva-bupa__reassure-3", "ReAssure 3.0",
108
+ score=0.55, policy_type_canonical="indemnity", policy_type="family_floater",
109
+ uin_code="MAXHLIP21177V032122", copay_pct=0,
110
+ sum_insured_options=[1_000_000, 1_500_000, 2_000_000, 5_000_000],
111
+ max_entry_age=70, maternity=True, newborn=True, grade="A", overall_score=88,
112
+ )
113
+ DECENT_INDEMNITY_C = _chunk(
114
+ "cholamandalam__flexi-health-supreme__wordings", "Chola Flexi Health Supreme",
115
+ score=0.72, policy_type_canonical="family_floater", policy_type=None,
116
+ uin_code="CHOHLIP27040V032627", copay_pct=0,
117
+ sum_insured_options=[1_000_000, 1_500_000, 2_500_000],
118
+ max_entry_age=75, maternity=True, grade="C", overall_score=65,
119
+ )
120
+ STAR_HOSPITAL_CASH = _chunk(
121
+ "star-health__star-hospital-cash__brochure", "Star Hospital Cash",
122
+ score=0.71, policy_type="hospital_cash", uin_code="SHAHLIP20046V011920",
123
+ max_entry_age=65, grade="D", overall_score=60,
124
+ )
125
+
126
+
127
+ # ════════════════════════════════════════════════════════════════════════════
128
+ # Shared canonical-identity helper (Rule 5 building block)
129
+ # ════════════════════════════════════════════════════════════════════════════
130
+ class TestPolicyIdentity(unittest.TestCase):
131
+ def test_uin_primary(self):
132
+ a = {"policy_id": "hdfc-ergo__optima-secure__wordings",
133
+ "uin_code": "HDFHLIP25041V062425"}
134
+ b = {"policy_id": "hdfc-ergo__optima-secure-older-variant",
135
+ "uin_code": "HDFHLIP25041V062425"}
136
+ self.assertEqual(canonical_key(a), canonical_key(b),
137
+ "Same UIN β‡’ same product (marketing rename).")
138
+
139
+ def test_product_key_collapses_doctype_siblings(self):
140
+ self.assertEqual(
141
+ product_key("acko__health-iii__wordings"), "acko__health-iii")
142
+ self.assertEqual(
143
+ product_key("acko__health-iii__brochure"), "acko__health-iii")
144
+ a = {"policy_id": "acko__health-iii__wordings"}
145
+ b = {"policy_id": "acko__health-iii__brochure"}
146
+ self.assertEqual(canonical_key(a), canonical_key(b))
147
+
148
+ def test_distinct_products_stay_distinct(self):
149
+ a = {"policy_id": "cholamandalam__flexi-health-supreme__wordings",
150
+ "uin_code": "CHOHLIP27040V032627"}
151
+ b = {"policy_id": "cholamandalam__flexi-health__wordings",
152
+ "uin_code": "CHOHLIP24145V062526"}
153
+ self.assertNotEqual(canonical_key(a), canonical_key(b),
154
+ "Different UIN β‡’ genuinely different products.")
155
+
156
+ def test_normalize_uin_rejects_junk(self):
157
+ self.assertEqual(normalize_uin(""), "")
158
+ self.assertEqual(normalize_uin("N/A"), "")
159
+ self.assertEqual(normalize_uin({"value": "SHAHLIP20046V011920"}),
160
+ "SHAHLIP20046V011920")
161
+
162
+
163
+ # ════════════════════════════════════════════════════════════════════════════
164
+ # P1 β€” Young first-timer comprehensive (15L, zero co-pay)
165
+ # ════════════════════════════════════════════════════════════════════════════
166
+ P1 = {
167
+ "age": 29, "location_tier": "metro", "income_band": "25L+",
168
+ "primary_goal": "first_buy", "existing_cover_inr": 0,
169
+ "health_conditions": ["none"], "desired_sum_insured_inr": 1_500_000,
170
+ "copay_pct": 0, "dependents": "self",
171
+ }
172
+
173
+
174
+ class TestPersona1(unittest.TestCase):
175
+ def test_no_fixed_benefit_and_best_grade_first(self):
176
+ catalog = [DECENT_INDEMNITY_C, STAR_HOSPITAL_CASH, GOOD_INDEMNITY_A]
177
+ filtered, guard = filter_pipeline(
178
+ catalog, profile=P1,
179
+ query="comprehensive metro 15 lakh zero co-pay first-time buyer",
180
+ intent="recommendation")
181
+ ids = [c["policy_id"] for c in filtered]
182
+ self.assertNotIn("star-health__star-hospital-cash__brochure", ids,
183
+ "P1: fixed-benefit hospital-cash must not be cited")
184
+ self.assertTrue(ids)
185
+ self.assertEqual(ids[0], "niva-bupa__reassure-3",
186
+ "P1: #1 must be the best-fit (A/88), not C/65")
187
+
188
+
189
+ # ════════════════════════════════════════════════════════════════════════════
190
+ # P2 β€” Senior + PED. Dedup + grade/rank inversion (A/77 was LAST).
191
+ # ════════════════════════════════════════════════════════════════════════════
192
+ P2 = {
193
+ "age": 58, "location_tier": "tier-2", "income_band": "10L-25L",
194
+ "primary_goal": "first_buy", "existing_cover_inr": 0,
195
+ "health_conditions": ["diabetes", "hypertension"],
196
+ "desired_sum_insured_inr": 1_000_000, "copay_pct": 10,
197
+ "dependents": "self+spouse",
198
+ }
199
+ P2_NNP_A = _chunk(
200
+ "national-insurance__new-national-parivar-mediclaim__wordings",
201
+ "New National Parivar Mediclaim", score=0.70,
202
+ policy_type_canonical="family_floater", uin_code="NICHLIP26999V010203",
203
+ copay_pct=10, sum_insured_options=[500_000, 1_000_000, 1_500_000],
204
+ max_entry_age=80, grade="C", overall_score=66)
205
+ P2_NNP_DUP = _chunk(
206
+ "national-insurance__new-national-parivar-mediclaim__brochure",
207
+ "New National Parivar Mediclaim", score=0.62,
208
+ policy_type_canonical="family_floater", uin_code="NICHLIP26999V010203",
209
+ copay_pct=10, sum_insured_options=[500_000, 1_000_000, 1_500_000],
210
+ max_entry_age=80, grade="C", overall_score=66)
211
+ P2_REASSURE_A = _chunk(
212
+ "niva-bupa__reassure-3", "ReAssure 3.0", score=0.55,
213
+ policy_type_canonical="indemnity", uin_code="MAXHLIP21177V032122",
214
+ copay_pct=10, sum_insured_options=[1_000_000, 1_500_000],
215
+ max_entry_age=70, grade="A", overall_score=77)
216
+
217
+
218
+ class TestPersona2(unittest.TestCase):
219
+ def test_dedup_variant_and_a_grade_leads(self):
220
+ catalog = [P2_NNP_A, P2_NNP_DUP, P2_REASSURE_A]
221
+ filtered, _ = filter_pipeline(
222
+ catalog, profile=P2,
223
+ query="senior 58 family floater diabetes hypertension 10 lakh",
224
+ intent="recommendation")
225
+ ids = [c["policy_id"] for c in filtered]
226
+ # Same-UIN doctype siblings collapse to one card.
227
+ nnp = [i for i in ids if "new-national-parivar" in i]
228
+ self.assertEqual(len(nnp), 1,
229
+ "P2: New National Parivar must appear ONCE, not twice")
230
+ self.assertEqual(ids[0], "niva-bupa__reassure-3",
231
+ "P2: A/77 must lead, not be last")
232
+
233
+
234
+ # ════════════════════════════════════════════════════════════════════════════
235
+ # P3 β€” Family + maternity (explicitly "very important")
236
+ # ════════════════════════════════════════════════════════════════════════════
237
+ P3 = {
238
+ "age": 34, "location_tier": "metro", "income_band": "25L-40L",
239
+ "primary_goal": "first_buy maternity newborn family floater",
240
+ "existing_cover_inr": 0, "health_conditions": ["none"],
241
+ "desired_sum_insured_inr": 2_500_000, "copay_pct": 0,
242
+ "dependents": "self+spouse+kids",
243
+ }
244
+ P3_MATERNITY_OK = _chunk(
245
+ "cholamandalam__flexi-health-supreme__wordings", "Chola Flexi Health Supreme",
246
+ score=0.60, policy_type_canonical="family_floater",
247
+ uin_code="CHOHLIP27040V032627", copay_pct=0,
248
+ sum_insured_options=[2_500_000], max_entry_age=75,
249
+ maternity=True, newborn=True, grade="C", overall_score=65)
250
+ P3_NO_MATERNITY = _chunk(
251
+ "hdfc-ergo__optima-secure", "my:Optima Secure", score=0.71,
252
+ policy_type_canonical="indemnity", uin_code="HDFHLIP25041V062425",
253
+ copay_pct=0, sum_insured_options=[2_500_000], max_entry_age=65,
254
+ maternity=False, newborn=False, grade="B", overall_score=75)
255
+ P3_HOSPITAL_CASH = _chunk(
256
+ "star-health__star-hospital-cash__brochure", "Star Hospital Cash",
257
+ score=0.68, policy_type="hospital_cash", uin_code="SHAHLIP20046V011920",
258
+ max_entry_age=65, maternity=True, grade="D", overall_score=60)
259
+
260
+
261
+ class TestPersona3(unittest.TestCase):
262
+ def test_maternity_confirmed_first_fixed_benefit_dropped(self):
263
+ catalog = [P3_MATERNITY_OK, P3_NO_MATERNITY, P3_HOSPITAL_CASH]
264
+ filtered, _ = filter_pipeline(
265
+ catalog, profile=P3,
266
+ query="family floater maternity newborn 25 lakh metro first-time",
267
+ intent="recommendation")
268
+ ids = [c["policy_id"] for c in filtered]
269
+ self.assertNotIn("star-health__star-hospital-cash__brochure", ids,
270
+ "P3: hospital-cash is not a comprehensive family plan")
271
+ self.assertTrue(ids)
272
+ self.assertEqual(
273
+ ids[0], "cholamandalam__flexi-health-supreme__wordings",
274
+ "P3: maternity-confirmed plan must rank above the "
275
+ "non-maternity B-grade plan when maternity is required")
276
+ # The non-maternity plan, if present at all, ranks strictly below.
277
+ if "hdfc-ergo__optima-secure" in ids:
278
+ self.assertLess(
279
+ ids.index("cholamandalam__flexi-health-supreme__wordings"),
280
+ ids.index("hdfc-ergo__optima-secure"))
281
+
282
+
283
+ # ════════════════════════════════════════════════════════════════════════════
284
+ # P4 β€” Top-up seeker (INVERSE β€” top-up must be KEPT). + dedup of Γ—2.
285
+ # ════════════════════════════════════════════════════════════════════════════
286
+ P4 = {
287
+ "age": 44, "location_tier": "metro", "income_band": "10L-25L",
288
+ "primary_goal": "cheapest top-up over existing employer cover",
289
+ "existing_cover_inr": 500_000, "health_conditions": ["none"],
290
+ "desired_sum_insured_inr": 2_000_000, "copay_pct": 10,
291
+ "dependents": "self",
292
+ }
293
+ P4_TOPUP_A = _chunk(
294
+ "royal-sundaram__advanced-top-up__wordings", "Advanced Top Up",
295
+ score=0.76, policy_type_canonical="super_top_up",
296
+ uin_code="RSAHLIP21055V032021", copay_pct=0,
297
+ sum_insured_options=[1_000_000, 2_000_000], max_entry_age=65,
298
+ grade="A", overall_score=76)
299
+ P4_TOPUP_DUP = _chunk(
300
+ "royal-sundaram__advanced-top-up__brochure", "Advanced Top Up",
301
+ score=0.69, policy_type_canonical="super_top_up",
302
+ uin_code="RSAHLIP21055V032021", copay_pct=0,
303
+ sum_insured_options=[1_000_000, 2_000_000], max_entry_age=65,
304
+ grade="A", overall_score=76)
305
+ P4_SBI = _chunk(
306
+ "sbi-general__arogya-supreme", "Arogya Supreme", score=0.60,
307
+ policy_type_canonical="family_floater", uin_code="SBIHLIP21099V012021",
308
+ copay_pct=10, sum_insured_options=[2_000_000], max_entry_age=65,
309
+ grade="B", overall_score=75)
310
+
311
+
312
+ class TestPersona4Inverse(unittest.TestCase):
313
+ def test_topup_kept_and_deduped(self):
314
+ catalog = [P4_TOPUP_A, P4_TOPUP_DUP, P4_SBI]
315
+ filtered, _ = filter_pipeline(
316
+ catalog, profile=P4,
317
+ query="cheapest top-up over existing 5 lakh employer cover 20 lakh",
318
+ intent="recommendation")
319
+ ids = [c["policy_id"] for c in filtered]
320
+ topups = [i for i in ids if "advanced-top-up" in i]
321
+ self.assertEqual(len(topups), 1,
322
+ "P4: Advanced Top Up must appear ONCE (was Γ—2)")
323
+ self.assertTrue(any("advanced-top-up" in i for i in ids),
324
+ "P4 INVERSE: top-up seeker MUST still get top-up plans")
325
+
326
+
327
+ # ════════════════════════════════════════════════════════════════════════════
328
+ # P5 β€” Budget-constrained; cost is the #1 stated objective.
329
+ # ════════════════════════════════════════════════════════════════════════════
330
+ P5 = {
331
+ "age": 31, "location_tier": "tier-3", "income_band": "<10L",
332
+ "primary_goal": "cost_optimize cheapest lowest premium",
333
+ "existing_cover_inr": 0, "health_conditions": ["none"],
334
+ "desired_sum_insured_inr": 500_000, "copay_pct": 30,
335
+ "dependents": "self",
336
+ }
337
+ # The live P5 audit defect was COSINE-DRIVEN inversion: the bot led with
338
+ # the highest-cosine plan even though, at the same scorecard fit tier, it
339
+ # was not the cost-appropriate pick for a "lowest premium is my top
340
+ # priority" user. We pin the true root cause: at an equal scorecard tier,
341
+ # a higher-cosine plan must NOT out-rank an equal-fit plan when cost is the
342
+ # stated #1 objective (cosine is damped; the scorecard fit-score decides).
343
+ P5_CHEAPEST = _chunk(
344
+ "royal-sundaram__arogya-sanjeevani", "Arogya Sanjeevani", score=0.55,
345
+ policy_type_canonical="indemnity", uin_code="RSAHLIP21010V012021",
346
+ copay_pct=5, sum_insured_options=[500_000], max_entry_age=65,
347
+ grade="C", overall_score=66)
348
+ P5_PRICIER = _chunk(
349
+ "hdfc-ergo__optima-secure", "my:Optima Secure", score=0.75,
350
+ policy_type_canonical="indemnity", uin_code="HDFHLIP25041V062425",
351
+ copay_pct=0, sum_insured_options=[500_000, 1_000_000], max_entry_age=65,
352
+ grade="C", overall_score=64)
353
+
354
+
355
+ class TestPersona5(unittest.TestCase):
356
+ def test_cost_objective_not_cosine_dominated(self):
357
+ # Both plans are the SAME scorecard grade tier (C). The pricier
358
+ # plan's ONLY advantage is raw cosine (0.75 vs 0.55) β€” exactly the
359
+ # live-audit inversion. With cost the #1 objective, the gate damps
360
+ # cosine so the marginally-better-fit cost-appropriate plan (the
361
+ # canonical Arogya Sanjeevani standard product, 66 vs 64) leads
362
+ # instead of the higher-cosine one.
363
+ ranked = rank_by_profile_fit([P5_PRICIER, P5_CHEAPEST], P5)
364
+ ids = [c["policy_id"] for c in ranked]
365
+ self.assertEqual(len(ids), 2)
366
+ self.assertEqual(
367
+ ids[0], "royal-sundaram__arogya-sanjeevani",
368
+ "P5: cost objective β€” fit-score decides, NOT raw cosine")
369
+
370
+ def test_without_cost_objective_cosine_still_breaks_ties(self):
371
+ # Sanity / non-regression: for a NON-cost profile the cosine weight
372
+ # is unchanged, so the higher-cosine plan can still win a near-tie.
373
+ non_cost = dict(P5, primary_goal="first_buy comprehensive")
374
+ ranked = rank_by_profile_fit([P5_CHEAPEST, P5_PRICIER], non_cost)
375
+ self.assertEqual(
376
+ [c["policy_id"] for c in ranked][0], "hdfc-ergo__optima-secure",
377
+ "non-cost profile: cosine still contributes normally")
378
+
379
+
380
+ # ════════════════════════════════════════════════════════════════════════════
381
+ # P6 β€” Critical-illness seeker (INVERSE β€” CI must be KEPT).
382
+ # ════════════════════════════════════════════════════════════════════════════
383
+ P6 = {
384
+ "age": 42, "location_tier": "metro", "income_band": "25L+",
385
+ "primary_goal": "critical illness lump-sum fixed-benefit plan only",
386
+ "existing_cover_inr": 1_500_000, "health_conditions": ["none"],
387
+ "desired_sum_insured_inr": 2_500_000, "copay_pct": 0,
388
+ "dependents": "self",
389
+ }
390
+ P6_CI_1 = _chunk(
391
+ "national-insurance__national-critical-illness", "National Critical Illness",
392
+ score=0.54, policy_type="critical_illness",
393
+ policy_type_canonical="fixed_benefit", uin_code="NICCIIP20001V010203",
394
+ sum_insured_options=[2_500_000], max_entry_age=65, grade="D",
395
+ overall_score=54)
396
+ P6_CI_2 = _chunk(
397
+ "go-digit__digit-health-care-plus", "Digit Health Care Plus", score=0.75,
398
+ policy_type="critical_illness", policy_type_canonical="fixed_benefit",
399
+ uin_code="GODHLIP21099V012021", sum_insured_options=[2_500_000],
400
+ max_entry_age=65, grade="B", overall_score=75)
401
+
402
+
403
+ class TestPersona6Inverse(unittest.TestCase):
404
+ def test_ci_plans_kept_for_explicit_ci_seeker(self):
405
+ catalog = [P6_CI_1, P6_CI_2]
406
+ filtered, _ = filter_pipeline(
407
+ catalog, profile=P6,
408
+ query="critical illness lump-sum 25 lakh fixed benefit",
409
+ intent="recommendation")
410
+ ids = {c["policy_id"] for c in filtered}
411
+ self.assertIn("national-insurance__national-critical-illness", ids,
412
+ "P6 INVERSE: explicit CI seeker MUST still get CI plans")
413
+ self.assertIn("go-digit__digit-health-care-plus", ids)
414
+
415
+
416
+ # ════════════════════════════════════════════════════════════════════════════
417
+ # P7 β€” Parents both 70 + PED. Entry-age gate + dedup + senior surfacing.
418
+ # ════════════════════════════════════════════════════════════════════════════
419
+ P7 = {
420
+ "age": 36, "location_tier": "metro", "income_band": "10L-25L",
421
+ "primary_goal": "parents health cover senior citizens",
422
+ "existing_cover_inr": 0,
423
+ "health_conditions": ["father diabetes", "mother hypertension arthritis"],
424
+ "desired_sum_insured_inr": 1_000_000, "copay_pct": 10,
425
+ "dependents": "self+parents", "parents_to_insure": True,
426
+ "parents_age_max": 70, "parents_has_ped": True,
427
+ }
428
+ P7_CHOLA_SUPREME = _chunk(
429
+ "cholamandalam__flexi-health-supreme__wordings", "Chola Flexi Health Supreme",
430
+ score=0.72, policy_type_canonical="family_floater",
431
+ uin_code="CHOHLIP27040V032627", copay_pct=10,
432
+ sum_insured_options=[1_000_000], max_entry_age=75, grade="C",
433
+ overall_score=65)
434
+ P7_CHOLA_FLEXI = _chunk( # same insurer, DIFFERENT product, max_entry 65
435
+ "cholamandalam__flexi-health__wordings", "Flexi Health", score=0.67,
436
+ policy_type_canonical="individual", uin_code="CHOHLIP24145V062526",
437
+ copay_pct=10, sum_insured_options=[1_000_000], max_entry_age=65,
438
+ grade="C", overall_score=67)
439
+ P7_OPTIMA_65 = _chunk(
440
+ "hdfc-ergo__optima-secure", "my:Optima Secure", score=0.70,
441
+ policy_type_canonical="indemnity", uin_code="HDFHLIP25041V062425",
442
+ copay_pct=10, sum_insured_options=[1_000_000], max_entry_age=65,
443
+ grade="B", overall_score=75)
444
+ P7_SENIOR_OK = _chunk(
445
+ "star-health__senior-citizens-red-carpet__brochure",
446
+ "Star Senior Citizens Red Carpet", score=0.50,
447
+ policy_type_canonical="indemnity", uin_code="SHAHLIP26041V082526",
448
+ copay_pct=10, sum_insured_options=[1_000_000], min_entry_age=60,
449
+ max_entry_age=75, grade="B", overall_score=74)
450
+
451
+
452
+ class TestPersona7(unittest.TestCase):
453
+ def test_entry_age_gate_dedup_and_senior_surfaced(self):
454
+ catalog = [P7_CHOLA_SUPREME, P7_CHOLA_FLEXI, P7_OPTIMA_65,
455
+ P7_SENIOR_OK]
456
+ filtered, _ = filter_pipeline(
457
+ catalog, profile=P7,
458
+ query="parents cover both age 70 diabetes hypertension senior "
459
+ "citizen 10 lakh",
460
+ intent="recommendation")
461
+ ids = [c["policy_id"] for c in filtered]
462
+ # max_entry_age 65 < 70 β‡’ those plans cannot accept 70yo parents.
463
+ self.assertNotIn("cholamandalam__flexi-health__wordings", ids,
464
+ "P7: max_entry_age 65 cannot accept a 70yo parent")
465
+ self.assertNotIn("hdfc-ergo__optima-secure", ids,
466
+ "P7: max_entry_age 65 cannot accept a 70yo parent")
467
+ # Entry-age-75 plans survive; senior-eligible surfaces.
468
+ self.assertIn("star-health__senior-citizens-red-carpet__brochure", ids,
469
+ "P7: a senior-eligible plan must be surfaced")
470
+ self.assertIn("cholamandalam__flexi-health-supreme__wordings", ids,
471
+ "P7: max_entry_age 75 accepts a 70yo parent")
472
+
473
+ def test_same_insurer_distinct_products_not_collapsed(self):
474
+ # Chola Supreme vs Flexi Health are DIFFERENT UINs β‡’ they are NOT a
475
+ # dedup pair; the gate must not over-collapse them. (Flexi Health is
476
+ # dropped here by the age gate, not by dedup.)
477
+ self.assertNotEqual(
478
+ canonical_key(P7_CHOLA_SUPREME), canonical_key(P7_CHOLA_FLEXI))
479
+
480
+
481
+ # ════════════════════════════════════════════════════════════════════════════
482
+ # Direct unit coverage for the new gate primitives
483
+ # ════════════════════════════════════════════════════════════════════════════
484
+ class TestEntryAgeEligibility(unittest.TestCase):
485
+ def test_parents_age_drives_entry_age_gate(self):
486
+ kept = apply_eligibility_filter(
487
+ [P7_OPTIMA_65, P7_CHOLA_SUPREME], P7)
488
+ ids = {c["policy_id"] for c in kept}
489
+ self.assertNotIn("hdfc-ergo__optima-secure", ids)
490
+ self.assertIn("cholamandalam__flexi-health-supreme__wordings", ids)
491
+
492
+ def test_payer_only_profile_does_not_trip_entry_age(self):
493
+ # P1 is self-only, age 29 β€” the parents-age gate must NOT fire and
494
+ # drop a normal adult plan whose max_entry_age is 65.
495
+ kept = apply_eligibility_filter([P3_NO_MATERNITY], P1)
496
+ self.assertEqual(len(kept), 1,
497
+ "self-only 29yo must not be entry-age-gated by a "
498
+ "parents rule")
499
+
500
+
501
+ class TestMaternityRequirement(unittest.TestCase):
502
+ def test_unverified_maternity_ranked_below_confirmed(self):
503
+ ranked = rank_by_profile_fit([P3_NO_MATERNITY, P3_MATERNITY_OK], P3)
504
+ ids = [c["policy_id"] for c in ranked]
505
+ self.assertLess(
506
+ ids.index("cholamandalam__flexi-health-supreme__wordings"),
507
+ ids.index("hdfc-ergo__optima-secure"),
508
+ "maternity-confirmed must outrank maternity=False when the "
509
+ "profile explicitly needs maternity")
510
+
511
+ def test_no_maternity_need_does_not_penalize(self):
512
+ # P1 has no maternity need β€” the maternity rule must be inert.
513
+ ranked = rank_by_profile_fit([P3_NO_MATERNITY, GOOD_INDEMNITY_A], P1)
514
+ self.assertEqual(len(ranked), 2)
515
+
516
+
517
+ class TestCanonicalDedupInPipeline(unittest.TestCase):
518
+ def test_dedup_by_policy_uses_canonical_key(self):
519
+ deduped = dedup_by_policy([P2_NNP_A, P2_NNP_DUP])
520
+ self.assertEqual(len(deduped), 1,
521
+ "same-UIN doctype siblings collapse to one")
522
+ # Highest-score chunk wins.
523
+ self.assertEqual(deduped[0]["policy_id"],
524
+ "national-insurance__new-national-parivar-mediclaim"
525
+ "__wordings")
526
+
527
+
528
+ # ════════════════════════════════════════════════════════════════════════════
529
+ # LIVE PATH β€” single_brain._build_recommendation_citations must emit the
530
+ # GATED, fit-ranked, canonically-deduped cited set (not the LLM's order).
531
+ # ════════════════════════════════════════════════════════════════════════════
532
+ def _live_chunk(pid, name, slug, score, cid, uin=None):
533
+ return {
534
+ "chunk_id": cid, "policy_id": pid, "policy_name": name,
535
+ "insurer_slug": slug, "doc_type": "policy",
536
+ "source_url": f"https://example.com/{pid}.pdf",
537
+ "score": score, "uin_code": uin,
538
+ }
539
+
540
+
541
+ class TestLivePathCitationGate(unittest.TestCase):
542
+ def test_cards_ordered_by_gate_rank_not_llm_order(self):
543
+ # filter_pipeline returns chunks in profile-fit order; the union the
544
+ # citation builder sees preserves that. Best-fit appears FIRST.
545
+ gated_stream = [
546
+ _live_chunk("niva-bupa__reassure-3", "ReAssure 3.0",
547
+ "niva-bupa", 0.55, "c1", "MAXHLIP21177V032122"),
548
+ _live_chunk("cholamandalam__flexi-health-supreme__wordings",
549
+ "Chola Flexi Health Supreme", "cholamandalam",
550
+ 0.72, "c2", "CHOHLIP27040V032627"),
551
+ ]
552
+ # LLM marked them in the WRONG order (Chola first).
553
+ cites, is_rec = _build_recommendation_citations(
554
+ reply_text="see options",
555
+ retrieved_chunks_all=gated_stream,
556
+ marked_policy_ids=[
557
+ "cholamandalam__flexi-health-supreme__wordings",
558
+ "niva-bupa__reassure-3",
559
+ ],
560
+ )
561
+ self.assertTrue(is_rec)
562
+ self.assertEqual(
563
+ [c["policy_id"] for c in cites],
564
+ ["niva-bupa__reassure-3",
565
+ "cholamandalam__flexi-health-supreme__wordings"],
566
+ "Cited cards must follow the GATE's fit order, not the LLM's "
567
+ "mark_recommendation order")
568
+
569
+ def test_canonical_dedup_at_citation_layer(self):
570
+ # Same UIN under two doctype-sibling ids across the turn's union.
571
+ stream = [
572
+ _live_chunk("national-insurance__new-national-parivar-mediclaim"
573
+ "__wordings", "New National Parivar Mediclaim",
574
+ "national-insurance", 0.70, "c1",
575
+ "NICHLIP26999V010203"),
576
+ _live_chunk("national-insurance__new-national-parivar-mediclaim"
577
+ "__brochure", "New National Parivar Mediclaim",
578
+ "national-insurance", 0.62, "c2",
579
+ "NICHLIP26999V010203"),
580
+ ]
581
+ cites, is_rec = _build_recommendation_citations(
582
+ reply_text="I recommend New National Parivar Mediclaim",
583
+ retrieved_chunks_all=stream,
584
+ marked_policy_ids=[], # prose path
585
+ )
586
+ self.assertTrue(is_rec)
587
+ self.assertEqual(len(cites), 1,
588
+ "same-UIN duplicate must be cited ONCE (audit P2)")
589
+ self.assertEqual(cites[0]["chunk_id"], "c1",
590
+ "highest-score chunk hydrates the single card")
591
+
592
+
593
+ if __name__ == "__main__":
594
+ unittest.main()