rohitsar567 Claude Opus 4.7 (1M context) commited on
Commit
d486a56
Β·
1 Parent(s): 3fcae97

feat(#31): deterministic profile-aware {strengths,caveat} policy summary on all 3 surfaces

Browse files

Replaces the generic grade one-liner with a per-(profileΓ—policy)
ProfileSummary{strengths[], caveat} computed on the SAME pass as the
marketplace grade (scorecard.build_profile_summary): deterministic, no
LLM, no fabricated numbers, no /100 or A/B in prose; ~4-5 most-material
strengths for THIS profile + the one honest grade-capping caveat;
fallback to one_liner when facts-sparse/insufficient-data. Rendered at
the TOP of CitedPolicyCards, PolicyDetailModal, marketplace PolicyCard,
and PolicyScorecardWidget. Β§4c: /api/policies/{id}/scorecard now takes
session_id and resolves the profile via brain_tools.union_snapshot
identically to /api/policies/all; single-endpoint defers to the
catalogue (single source of truth) so profile_summary+grade are
byte-identical across surfaces for all 148 (new parity test).

Verified: full pytest suite exit 0 (no regression); test_profile_
summary + parity + endpoint_catalogue 21/21 (incl. 148Γ—6-profile
invariants, deductible-gate, non-fabrication, caveat-traceability,
determinism, endpoint↔catalogue parity 148/148); tsc 0; eslint 0-new
(page.tsx 29=baseline, api.ts 0, PolicyScorecardWidget 0).

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

backend/main.py CHANGED
@@ -2003,6 +2003,16 @@ class ScorecardSubScore(BaseModel):
2003
  signals: list[str]
2004
 
2005
 
 
 
 
 
 
 
 
 
 
 
2006
  class ProfileCompletenessResponse(BaseModel):
2007
  completeness: float # 0.0 - 1.0
2008
  completeness_pct: int # 0 - 100
@@ -2269,6 +2279,10 @@ class ScorecardResponse(BaseModel):
2269
  # Retry fallback or a fabricated grade. Optional w/ default so the
2270
  # existing /api/policies/compare construction (no flag) stays valid.
2271
  insufficient_data: bool = False
 
 
 
 
2272
 
2273
 
2274
  class CompareEntry(BaseModel):
@@ -2295,6 +2309,10 @@ class MarketplacePolicy(BaseModel):
2295
  overall_score: int
2296
  one_liner: str
2297
  data_completeness_pct: float
 
 
 
 
2298
  # Headline filterable fields
2299
  min_entry_age: Optional[int] = None
2300
  max_entry_age: Optional[int] = None
@@ -3094,7 +3112,21 @@ def _ki145_material_diffs(curated: dict, extracted: dict) -> int:
3094
  return diffs
3095
 
3096
 
3097
- def _marketplace_catalogue(user_profile_dict):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3098
  """SINGLE SOURCE OF TRUTH for the marketplace card set (#40).
3099
 
3100
  The recommendation path (brain_tools._scorecard_signal via
@@ -3103,8 +3135,27 @@ def _marketplace_catalogue(user_profile_dict):
3103
  diverge from the marketplace card grade β€” including marketing-rename
3104
  alias / KI-145 variant cards. Body is the former inline endpoint
3105
  logic, moved verbatim; fully synchronous.
 
 
 
 
 
 
 
 
 
 
 
 
3106
  """
3107
  import json as _json
 
 
 
 
 
 
 
3108
  from backend.scorecard import build_scorecard
3109
  from backend.policy_identity import clean_display_policy_name
3110
  corpus_url_index = _build_corpus_url_index()
@@ -3435,7 +3486,7 @@ def _marketplace_catalogue(user_profile_dict):
3435
  source_pdf_url = (
3436
  _cand if _is_credible_pdf_url(_cand) else (_local or _cand)
3437
  )
3438
- out.append(MarketplacePolicy(
3439
  policy_id=policy_id,
3440
  policy_name=clean_display_policy_name(
3441
  data.get("policy_name", fp.stem)
@@ -3448,6 +3499,7 @@ def _marketplace_catalogue(user_profile_dict):
3448
  overall_score=sc.overall_score,
3449
  one_liner=sc.one_liner,
3450
  data_completeness_pct=sc.data_completeness_pct,
 
3451
  min_entry_age=data.get("min_entry_age"),
3452
  max_entry_age=data.get("max_entry_age"),
3453
  sum_insured_options=si,
@@ -3471,7 +3523,14 @@ def _marketplace_catalogue(user_profile_dict):
3471
  # KI-141 β€” merge marketing-rename curated entries onto this
3472
  # parent card. Sorted for deterministic output.
3473
  aliases=sorted(parent_pkey_aliases.get(product_key, [])),
3474
- ))
 
 
 
 
 
 
 
3475
  except Exception as e:
3476
  # One malformed extraction should not kill the whole feed
3477
  print(f"[marketplace] skipping {fp.name}: {type(e).__name__}: {str(e)[:120]}")
@@ -3563,7 +3622,7 @@ def _marketplace_catalogue(user_profile_dict):
3563
  source_pdf_url = (
3564
  _cand if _is_credible_pdf_url(_cand) else (_local or _cand)
3565
  )
3566
- out.append(MarketplacePolicy(
3567
  policy_id=curated_policy_id,
3568
  policy_name=clean_display_policy_name(
3569
  data.get("policy_name", curated_policy_id)
@@ -3576,6 +3635,7 @@ def _marketplace_catalogue(user_profile_dict):
3576
  overall_score=sc.overall_score,
3577
  one_liner=sc.one_liner,
3578
  data_completeness_pct=sc.data_completeness_pct,
 
3579
  min_entry_age=data.get("min_entry_age"),
3580
  max_entry_age=data.get("max_entry_age"),
3581
  sum_insured_options=si,
@@ -3600,7 +3660,12 @@ def _marketplace_catalogue(user_profile_dict):
3600
  # extracted parent owns their UIN. In that case their later
3601
  # curated siblings alias onto them and surface here.
3602
  aliases=sorted(parent_pkey_aliases.get(curated_policy_id, [])),
3603
- ))
 
 
 
 
 
3604
  except Exception as e:
3605
  print(f"[marketplace] skipping curated {curated_policy_id}: {type(e).__name__}: {str(e)[:120]}")
3606
  continue
@@ -3635,6 +3700,24 @@ def _marketplace_catalogue(user_profile_dict):
3635
  else:
3636
  prev.aliases = sorted(set(prev.aliases) | set(p.aliases))
3637
  deduped = list(_best.values())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3638
  return deduped
3639
 
3640
  @app.get("/api/policies/all", response_model=MarketplaceResponse)
@@ -3649,18 +3732,26 @@ async def policies_all(session_id: Optional[str] = None):
3649
  from backend.scorecard import build_scorecard, profile_completeness as _completeness
3650
  from backend.session_state import get_session as _get_sess
3651
 
3652
- # Pull user profile if we have one
 
 
 
 
 
3653
  user_profile_dict: Optional[dict] = None
3654
  if session_id:
3655
  sess = _get_sess(session_id)
3656
  p = sess.profile
3657
- profile_dict = {
3658
- "age": p.age, "dependents": p.dependents, "income_band": p.income_band,
3659
- "existing_cover_inr": p.existing_cover_inr, "primary_goal": p.primary_goal,
3660
- "location_tier": p.location_tier, "parents_to_insure": p.parents_to_insure,
3661
- "parents_age_max": p.parents_age_max, "parents_has_ped": p.parents_has_ped,
3662
- "health_conditions": p.health_conditions, "budget_band": p.budget_band,
3663
- }
 
 
 
3664
  if _completeness(profile_dict) >= 0.6:
3665
  user_profile_dict = profile_dict
3666
 
@@ -3742,6 +3833,7 @@ async def compare_policies(policy_ids: list[str] = None):
3742
  sub_scores=[ScorecardSubScore(**s.__dict__) for s in sc.sub_scores],
3743
  data_completeness_pct=sc.data_completeness_pct,
3744
  methodology_link=sc.methodology_link,
 
3745
  ),
3746
  ))
3747
 
@@ -3769,15 +3861,26 @@ async def policy_scorecard(
3769
  age: Optional[int] = None,
3770
  parents_to_insure: Optional[bool] = None,
3771
  budget_band: Optional[str] = None,
 
3772
  ):
3773
  """Compute the 6-sub-score A-F scorecard for an extracted policy.
3774
 
3775
  Now also pulls insurer-level reviews (IRDAI claim ratio + complaints) into
3776
  the Claim Experience sub-score. See 70-docs/scorecard-methodology.md.
 
 
 
 
 
 
 
 
3777
  """
3778
  import json as _json
3779
 
3780
  from backend.scorecard import build_scorecard
 
 
3781
 
3782
  # ROOT-CAUSE FIX (scorecard 404 for catalogued curated-only products):
3783
  # /api/policies/all catalogues a card for every extracted JSON AND every
@@ -3808,21 +3911,49 @@ async def policy_scorecard(
3808
  _curated.get(policy.get("policy_id", policy_id)) or _curated.get(policy_id),
3809
  )
3810
  else:
3811
- # No LLM extraction for this product β€” fall back to the human-curated
3812
- # facts layer (mirrors /api/policies/all Pass 2). The curated dict
3813
- # also carries doctype-suffixed alias keys, so try both the canonical
3814
- # id and the raw lookup key.
3815
- policy = _curated.get(policy_id) or _curated.get(f"{policy_id}__cis") \
3816
- or _curated.get(f"{policy_id}__wordings") \
3817
- or _curated.get(f"{policy_id}__brochure") \
3818
- or _curated.get(f"{policy_id}__prospectus")
3819
- if not policy:
3820
- # Genuinely not in EITHER layer β‡’ this id is not a catalogued
3821
- # product at all (bad/typo id). 404 is the correct, honest
3822
- # response here β€” it is NOT a catalogued policy.
3823
- raise HTTPException(404, f"No data for policy_id={policy_id}")
3824
- policy = dict(policy)
3825
- policy.setdefault("policy_id", policy_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3826
 
3827
  # Load insurer reviews if present so the Claim Experience sub-score
3828
  # uses authoritative IRDAI data, not just the (mostly-null) per-policy fields.
@@ -3836,12 +3967,66 @@ async def policy_scorecard(
3836
  except Exception:
3837
  pass
3838
 
 
 
 
 
 
 
 
 
 
 
 
3839
  profile: dict = {}
3840
- if age is not None: profile["age"] = age
3841
- if parents_to_insure is not None: profile["parents_to_insure"] = parents_to_insure
3842
- if budget_band is not None: profile["budget_band"] = budget_band
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3843
 
3844
- sc = build_scorecard(policy, insurer_reviews=insurer_reviews, profile=profile or None)
3845
  return ScorecardResponse(
3846
  policy_id=sc.policy_id,
3847
  policy_name=sc.policy_name,
@@ -3853,6 +4038,7 @@ async def policy_scorecard(
3853
  data_completeness_pct=sc.data_completeness_pct,
3854
  methodology_link=sc.methodology_link,
3855
  insufficient_data=sc.insufficient_data,
 
3856
  )
3857
 
3858
 
@@ -3883,6 +4069,9 @@ class BulkScorecardEntry(BaseModel):
3883
  one_liner: str = ""
3884
  # raw signals per sub-score so the widget can pop-out a tooltip with detail
3885
  signals: dict[str, list[str]] = Field(default_factory=dict)
 
 
 
3886
 
3887
 
3888
  class BulkScorecardResponse(BaseModel):
@@ -4108,7 +4297,20 @@ async def scorecard_bulk(req: BulkScorecardRequest):
4108
 
4109
  sub_map = {_slugify_subscore(s.name): s.score for s in sc.sub_scores}
4110
  signal_map = {_slugify_subscore(s.name): s.signals for s in sc.sub_scores}
4111
- rationale = _profile_rationale_for(policy, profile, sc.sub_scores)
 
 
 
 
 
 
 
 
 
 
 
 
 
4112
 
4113
  out[pid] = BulkScorecardEntry(
4114
  policy_id=sc.policy_id or pid,
@@ -4121,6 +4323,7 @@ async def scorecard_bulk(req: BulkScorecardRequest):
4121
  data_completeness_pct=sc.data_completeness_pct,
4122
  one_liner=sc.one_liner,
4123
  signals=signal_map,
 
4124
  )
4125
 
4126
  return BulkScorecardResponse(per_policy=out)
@@ -4641,6 +4844,109 @@ def _mg_index() -> dict:
4641
  return _MG_CACHE["index"]
4642
 
4643
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4644
  def marketplace_grade(policy_id: str) -> dict:
4645
  """{"_grade", "_overall_score"} for policy_id, identical to its
4646
  marketplace card. Resolution order: exact id -> product_key -> UIN
 
2003
  signals: list[str]
2004
 
2005
 
2006
+ class ProfileSummaryModel(BaseModel):
2007
+ """Deterministic, profile-aware {strengths, caveat} (see
2008
+ backend.scorecard.build_profile_summary). Rendered at the TOP of every
2009
+ scorecard surface; the frontend falls back to one_liner when strengths
2010
+ is empty / insufficient. Optional with a default so every existing
2011
+ construction path (compare, insufficient-data) stays valid."""
2012
+ strengths: list[str] = Field(default_factory=list)
2013
+ caveat: Optional[str] = None
2014
+
2015
+
2016
  class ProfileCompletenessResponse(BaseModel):
2017
  completeness: float # 0.0 - 1.0
2018
  completeness_pct: int # 0 - 100
 
2279
  # Retry fallback or a fabricated grade. Optional w/ default so the
2280
  # existing /api/policies/compare construction (no flag) stays valid.
2281
  insufficient_data: bool = False
2282
+ # Deterministic, profile-aware {strengths, caveat} computed on the same
2283
+ # pass as the grade. Optional w/ default so every construction path
2284
+ # (compare with no summary, insufficient-data) stays valid.
2285
+ profile_summary: Optional[ProfileSummaryModel] = None
2286
 
2287
 
2288
  class CompareEntry(BaseModel):
 
2309
  overall_score: int
2310
  one_liner: str
2311
  data_completeness_pct: float
2312
+ # Deterministic, profile-aware {strengths, caveat}. Populated from the
2313
+ # SAME build_scorecard pass that produced `grade`. None when the catalogue
2314
+ # was built profile-neutrally and no facts qualified.
2315
+ profile_summary: Optional[ProfileSummaryModel] = None
2316
  # Headline filterable fields
2317
  min_entry_age: Optional[int] = None
2318
  max_entry_age: Optional[int] = None
 
3112
  return diffs
3113
 
3114
 
3115
+ def _profile_summary_model(sc) -> Optional[ProfileSummaryModel]:
3116
+ """Adapt the scorecard's ProfileSummary dataclass β†’ the API model.
3117
+
3118
+ None-safe (older Scorecard objects / defensive paths may not carry one).
3119
+ """
3120
+ ps = getattr(sc, "profile_summary", None)
3121
+ if ps is None:
3122
+ return None
3123
+ return ProfileSummaryModel(
3124
+ strengths=list(getattr(ps, "strengths", []) or []),
3125
+ caveat=getattr(ps, "caveat", None),
3126
+ )
3127
+
3128
+
3129
+ def _marketplace_catalogue(user_profile_dict, _collect_scorecards=None):
3130
  """SINGLE SOURCE OF TRUTH for the marketplace card set (#40).
3131
 
3132
  The recommendation path (brain_tools._scorecard_signal via
 
3135
  diverge from the marketplace card grade β€” including marketing-rename
3136
  alias / KI-145 variant cards. Body is the former inline endpoint
3137
  logic, moved verbatim; fully synchronous.
3138
+
3139
+ Task #31 (single-source-of-truth, option (a)): when `_collect_scorecards`
3140
+ is a dict, it is populated `{surviving_card.policy_id: Scorecard}` with
3141
+ the EXACT `Scorecard` object (full 6 sub_scores + profile_summary +
3142
+ grade) computed here for each card that survives the final dedup. The
3143
+ single /api/policies/{id}/scorecard endpoint serves that object verbatim
3144
+ so its profile_summary / grade / sub_scores are byte-identical to the
3145
+ /api/policies/all card for the same canonical id BY CONSTRUCTION β€” both
3146
+ flow through this one `build_scorecard` pass on the same chosen sibling's
3147
+ `(data, insurer_reviews, profile)`. (The endpoint's old doctype-rank
3148
+ sibling-reconstruction picked a DIFFERENT sibling than this catalogue's
3149
+ completeness-based `_best` dedup, emitting a different strength set.)
3150
  """
3151
  import json as _json
3152
+ # Task #31 β€” {id(MarketplacePolicy): Scorecard}. Keyed by the card
3153
+ # OBJECT's identity (NOT its policy_id string β€” several pre-dedup `out`
3154
+ # entries can share the same curated-canonical policy_id, so a string
3155
+ # key would let a lower-completeness sibling's Scorecard clobber the
3156
+ # survivor's). After `_best` picks the surviving object we map each
3157
+ # survivor's policy_id / canonical `_ident` to ITS OWN Scorecard.
3158
+ _sc_by_obj: dict = {} if _collect_scorecards is not None else None
3159
  from backend.scorecard import build_scorecard
3160
  from backend.policy_identity import clean_display_policy_name
3161
  corpus_url_index = _build_corpus_url_index()
 
3486
  source_pdf_url = (
3487
  _cand if _is_credible_pdf_url(_cand) else (_local or _cand)
3488
  )
3489
+ _mp = MarketplacePolicy(
3490
  policy_id=policy_id,
3491
  policy_name=clean_display_policy_name(
3492
  data.get("policy_name", fp.stem)
 
3499
  overall_score=sc.overall_score,
3500
  one_liner=sc.one_liner,
3501
  data_completeness_pct=sc.data_completeness_pct,
3502
+ profile_summary=_profile_summary_model(sc),
3503
  min_entry_age=data.get("min_entry_age"),
3504
  max_entry_age=data.get("max_entry_age"),
3505
  sum_insured_options=si,
 
3523
  # KI-141 β€” merge marketing-rename curated entries onto this
3524
  # parent card. Sorted for deterministic output.
3525
  aliases=sorted(parent_pkey_aliases.get(product_key, [])),
3526
+ )
3527
+ out.append(_mp)
3528
+ if _sc_by_obj is not None:
3529
+ # Task #31 β€” bind THIS card object to the exact Scorecard
3530
+ # built above on the catalogue's chosen sibling
3531
+ # `data`/`ir`/profile. Object-keyed so it survives the
3532
+ # post-dedup mapping unambiguously.
3533
+ _sc_by_obj[id(_mp)] = sc
3534
  except Exception as e:
3535
  # One malformed extraction should not kill the whole feed
3536
  print(f"[marketplace] skipping {fp.name}: {type(e).__name__}: {str(e)[:120]}")
 
3622
  source_pdf_url = (
3623
  _cand if _is_credible_pdf_url(_cand) else (_local or _cand)
3624
  )
3625
+ _mp = MarketplacePolicy(
3626
  policy_id=curated_policy_id,
3627
  policy_name=clean_display_policy_name(
3628
  data.get("policy_name", curated_policy_id)
 
3635
  overall_score=sc.overall_score,
3636
  one_liner=sc.one_liner,
3637
  data_completeness_pct=sc.data_completeness_pct,
3638
+ profile_summary=_profile_summary_model(sc),
3639
  min_entry_age=data.get("min_entry_age"),
3640
  max_entry_age=data.get("max_entry_age"),
3641
  sum_insured_options=si,
 
3660
  # extracted parent owns their UIN. In that case their later
3661
  # curated siblings alias onto them and surface here.
3662
  aliases=sorted(parent_pkey_aliases.get(curated_policy_id, [])),
3663
+ )
3664
+ out.append(_mp)
3665
+ if _sc_by_obj is not None:
3666
+ # Task #31 β€” exact Scorecard for this curated-only card,
3667
+ # bound to the card object (see Pass-1 rationale).
3668
+ _sc_by_obj[id(_mp)] = sc
3669
  except Exception as e:
3670
  print(f"[marketplace] skipping curated {curated_policy_id}: {type(e).__name__}: {str(e)[:120]}")
3671
  continue
 
3700
  else:
3701
  prev.aliases = sorted(set(prev.aliases) | set(p.aliases))
3702
  deduped = list(_best.values())
3703
+
3704
+ if _collect_scorecards is not None:
3705
+ # Task #31 β€” publish ONLY the post-dedup survivors' Scorecards,
3706
+ # each survivor mapped (by OBJECT identity) to ITS OWN Scorecard,
3707
+ # keyed by the survivor's policy_id AND its canonical
3708
+ # `_ident(policy_id)` so /api/policies/{id}/scorecard resolves a
3709
+ # doctype-suffixed / curated-canonical id onto the SAME card the
3710
+ # catalogue serves β€” the exact `Scorecard` object built here on the
3711
+ # catalogue's chosen sibling. Parity holds by construction (one
3712
+ # build_scorecard pass feeds both surfaces). Exact policy_id wins
3713
+ # over the canonical-ident fallback (setdefault) so a precise id is
3714
+ # never shadowed by a sibling sharing its _ident.
3715
+ for p in deduped:
3716
+ sc = _sc_by_obj.get(id(p))
3717
+ if sc is None:
3718
+ continue
3719
+ _collect_scorecards[p.policy_id] = sc
3720
+ _collect_scorecards.setdefault(_ident(p.policy_id), sc)
3721
  return deduped
3722
 
3723
  @app.get("/api/policies/all", response_model=MarketplaceResponse)
 
3732
  from backend.scorecard import build_scorecard, profile_completeness as _completeness
3733
  from backend.session_state import get_session as _get_sess
3734
 
3735
+ # Pull user profile if we have one. KI-271 β€” drive the profile dict off
3736
+ # brain_tools.SLOT_UNION (via union_snapshot) so every captured slot β€”
3737
+ # including copay_pct, desired_sum_insured_inr, family_medical_history,
3738
+ # health_conditions, age β€” flows into build_scorecard's profile-aware
3739
+ # {strengths, caveat} generator (task #31). union_snapshot already drops
3740
+ # empty/None/[] slots, so presence == captured.
3741
  user_profile_dict: Optional[dict] = None
3742
  if session_id:
3743
  sess = _get_sess(session_id)
3744
  p = sess.profile
3745
+ profile_dict = brain_tools.union_snapshot(p)
3746
+ # parents_* are NOT in SLOT_UNION's snapshot if False/None but the
3747
+ # weight-tuner reads parents_to_insure/parents_age_max/parents_has_ped
3748
+ # explicitly β€” carry them through (None-safe) without overwriting a
3749
+ # snapshot value.
3750
+ for _pf in ("parents_to_insure", "parents_age_max", "parents_has_ped"):
3751
+ if _pf not in profile_dict:
3752
+ _v = getattr(p, _pf, None)
3753
+ if _v is not None:
3754
+ profile_dict[_pf] = _v
3755
  if _completeness(profile_dict) >= 0.6:
3756
  user_profile_dict = profile_dict
3757
 
 
3833
  sub_scores=[ScorecardSubScore(**s.__dict__) for s in sc.sub_scores],
3834
  data_completeness_pct=sc.data_completeness_pct,
3835
  methodology_link=sc.methodology_link,
3836
+ profile_summary=_profile_summary_model(sc),
3837
  ),
3838
  ))
3839
 
 
3861
  age: Optional[int] = None,
3862
  parents_to_insure: Optional[bool] = None,
3863
  budget_band: Optional[str] = None,
3864
+ session_id: Optional[str] = None,
3865
  ):
3866
  """Compute the 6-sub-score A-F scorecard for an extracted policy.
3867
 
3868
  Now also pulls insurer-level reviews (IRDAI claim ratio + complaints) into
3869
  the Claim Experience sub-score. See 70-docs/scorecard-methodology.md.
3870
+
3871
+ Β§4c (task #31) β€” when `session_id` is supplied AND that session's profile
3872
+ is populated to β‰₯0.6 completeness, the policy is scored against THAT full
3873
+ profile (resolved the SAME way /api/policies/all does, via
3874
+ brain_tools.union_snapshot) so this endpoint's grade + profile_summary
3875
+ are byte-identical to the marketplace card for the same canonical id. The
3876
+ standalone `age` / `parents_to_insure` / `budget_band` query params remain
3877
+ a back-compat fallback when no session profile is available.
3878
  """
3879
  import json as _json
3880
 
3881
  from backend.scorecard import build_scorecard
3882
+ from backend.scorecard import profile_completeness as _completeness
3883
+ from backend.session_state import get_session as _get_sess
3884
 
3885
  # ROOT-CAUSE FIX (scorecard 404 for catalogued curated-only products):
3886
  # /api/policies/all catalogues a card for every extracted JSON AND every
 
3911
  _curated.get(policy.get("policy_id", policy_id)) or _curated.get(policy_id),
3912
  )
3913
  else:
3914
+ # No bare `<policy_id>.json` extraction. Task #31 PARITY FIX: the
3915
+ # marketplace card for a doctype-suffixed extracted-only product
3916
+ # (e.g. star-health__star-cardiac-care, whose only extraction is
3917
+ # `...__wordings.json`) is built by /api/policies/all Pass-1 from
3918
+ # that doctype-suffixed EXTRACTED file (preferred over curated via
3919
+ # _DOCTYPE_RANK). The standalone endpoint previously skipped straight
3920
+ # to the curated layer, so its grade + profile_summary diverged from
3921
+ # the card for the SAME canonical id. Mirror the catalogue's doctype
3922
+ # preference (wordings > prospectus > cis > brochure) on the
3923
+ # EXTRACTED layer first, with the same curated-override, before
3924
+ # falling back to a curated-only product.
3925
+ policy = None
3926
+ for _dt in ("wordings", "prospectus", "cis", "brochure"):
3927
+ _ep = settings.EXTRACTED_DIR / f"{policy_id}__{_dt}.json"
3928
+ if _ep.exists():
3929
+ try:
3930
+ policy = _json.loads(_ep.read_text())
3931
+ except Exception:
3932
+ policy = None
3933
+ continue
3934
+ policy = _merge_curated(
3935
+ policy,
3936
+ _curated.get(policy.get("policy_id", policy_id))
3937
+ or _curated.get(f"{policy_id}__{_dt}")
3938
+ or _curated.get(policy_id),
3939
+ )
3940
+ break
3941
+ if policy is None:
3942
+ # No extraction in ANY doctype β€” fall back to the human-curated
3943
+ # facts layer (mirrors /api/policies/all Pass 2). The curated
3944
+ # dict also carries doctype-suffixed alias keys, so try the
3945
+ # canonical id and the raw lookup keys.
3946
+ policy = _curated.get(policy_id) or _curated.get(f"{policy_id}__cis") \
3947
+ or _curated.get(f"{policy_id}__wordings") \
3948
+ or _curated.get(f"{policy_id}__brochure") \
3949
+ or _curated.get(f"{policy_id}__prospectus")
3950
+ if not policy:
3951
+ # Genuinely not in EITHER layer β‡’ this id is not a catalogued
3952
+ # product at all (bad/typo id). 404 is the correct, honest
3953
+ # response here β€” it is NOT a catalogued policy.
3954
+ raise HTTPException(404, f"No data for policy_id={policy_id}")
3955
+ policy = dict(policy)
3956
+ policy.setdefault("policy_id", policy_id)
3957
 
3958
  # Load insurer reviews if present so the Claim Experience sub-score
3959
  # uses authoritative IRDAI data, not just the (mostly-null) per-policy fields.
 
3967
  except Exception:
3968
  pass
3969
 
3970
+ # Β§4c β€” resolve the session profile the SAME way /api/policies/all does
3971
+ # (brain_tools.union_snapshot full dict + parents_* carry-through) so this
3972
+ # endpoint's grade + profile_summary match the marketplace card for the
3973
+ # same canonical id by construction. Only when β‰₯0.6 complete.
3974
+ #
3975
+ # `catalogue_profile` is EXACTLY what /api/policies/all would pass to
3976
+ # _marketplace_catalogue for this session (the β‰₯0.6 SLOT_UNION snapshot,
3977
+ # else None) β€” used below for the catalogue-card parity override. The
3978
+ # back-compat query-param path is a separate, profile-NEUTRAL-vs-catalogue
3979
+ # fallback (the catalogue is never built from loose query params).
3980
+ catalogue_profile: Optional[dict] = None
3981
  profile: dict = {}
3982
+ if session_id:
3983
+ try:
3984
+ _p = _get_sess(session_id).profile
3985
+ _pd = brain_tools.union_snapshot(_p)
3986
+ for _pf in ("parents_to_insure", "parents_age_max", "parents_has_ped"):
3987
+ if _pf not in _pd:
3988
+ _v = getattr(_p, _pf, None)
3989
+ if _v is not None:
3990
+ _pd[_pf] = _v
3991
+ if _completeness(_pd) >= 0.6:
3992
+ profile = _pd
3993
+ catalogue_profile = _pd
3994
+ except Exception: # noqa: BLE001 β€” bad/expired session β‡’ back-compat path
3995
+ profile = {}
3996
+ catalogue_profile = None
3997
+ if not profile:
3998
+ # Back-compat: standalone query params when no usable session profile.
3999
+ if age is not None: profile["age"] = age
4000
+ if parents_to_insure is not None: profile["parents_to_insure"] = parents_to_insure
4001
+ if budget_band is not None: profile["budget_band"] = budget_band
4002
+
4003
+ # TASK #31 β€” SINGLE SOURCE OF TRUTH (option (a)). When this id IS a
4004
+ # marketplace card, serve the EXACT `Scorecard` object the
4005
+ # /api/policies/all catalogue built for that canonical card under THIS
4006
+ # session's profile β€” full sub_scores + profile_summary + grade +
4007
+ # data_completeness + one_liner, all from the catalogue's ONE
4008
+ # build_scorecard pass on the catalogue's chosen sibling
4009
+ # `(data, insurer_reviews, profile)`. Parity is byte-identical BY
4010
+ # CONSTRUCTION: the same object feeds both surfaces, so the endpoint can
4011
+ # no longer pick a different doctype sibling than the catalogue's
4012
+ # completeness-based `_best` dedup (the prior bug β€” the old endpoint
4013
+ # reconstructed `policy` via its own doctype-rank loop and emitted a
4014
+ # different strength set / caveat for the same canonical id).
4015
+ #
4016
+ # `_catalogue_scorecard` returns None ONLY when the id is not a
4017
+ # catalogued product at all β€” then we fall through to the locally-built
4018
+ # scorecard so the curated-only / back-compat query-param / never-404
4019
+ # behaviour the resolution block above guarantees is fully preserved.
4020
+ cat_sc = None
4021
+ try:
4022
+ cat_sc = _catalogue_scorecard(policy_id, catalogue_profile)
4023
+ except Exception: # noqa: BLE001 β€” never let the SSOT resolver 500 a card
4024
+ cat_sc = None
4025
+
4026
+ sc = cat_sc if cat_sc is not None else build_scorecard(
4027
+ policy, insurer_reviews=insurer_reviews, profile=profile or None
4028
+ )
4029
 
 
4030
  return ScorecardResponse(
4031
  policy_id=sc.policy_id,
4032
  policy_name=sc.policy_name,
 
4038
  data_completeness_pct=sc.data_completeness_pct,
4039
  methodology_link=sc.methodology_link,
4040
  insufficient_data=sc.insufficient_data,
4041
+ profile_summary=_profile_summary_model(sc),
4042
  )
4043
 
4044
 
 
4069
  one_liner: str = ""
4070
  # raw signals per sub-score so the widget can pop-out a tooltip with detail
4071
  signals: dict[str, list[str]] = Field(default_factory=dict)
4072
+ # Deterministic, profile-aware {strengths, caveat} β€” the structured
4073
+ # replacement for the generic one_liner the widget now renders at top.
4074
+ profile_summary: Optional[ProfileSummaryModel] = None
4075
 
4076
 
4077
  class BulkScorecardResponse(BaseModel):
 
4297
 
4298
  sub_map = {_slugify_subscore(s.name): s.score for s in sc.sub_scores}
4299
  signal_map = {_slugify_subscore(s.name): s.signals for s in sc.sub_scores}
4300
+ psm = _profile_summary_model(sc)
4301
+
4302
+ # Bridge the legacy profile_rationale list off the deterministic
4303
+ # profile_summary so the old field stays populated AND consistent
4304
+ # with the new structured data (strengths + [caveat]). Only fall
4305
+ # back to the heuristic _profile_rationale_for when the deterministic
4306
+ # summary produced too little to be useful (insufficient-data /
4307
+ # profile-neutral with <3 facts) so no surface goes blank.
4308
+ if psm and psm.strengths:
4309
+ rationale = list(psm.strengths)
4310
+ if psm.caveat:
4311
+ rationale.append(psm.caveat)
4312
+ else:
4313
+ rationale = _profile_rationale_for(policy, profile, sc.sub_scores)
4314
 
4315
  out[pid] = BulkScorecardEntry(
4316
  policy_id=sc.policy_id or pid,
 
4323
  data_completeness_pct=sc.data_completeness_pct,
4324
  one_liner=sc.one_liner,
4325
  signals=signal_map,
4326
+ profile_summary=psm,
4327
  )
4328
 
4329
  return BulkScorecardResponse(per_policy=out)
 
4844
  return _MG_CACHE["index"]
4845
 
4846
 
4847
+ # Task #31 β€” profile-keyed {policy_id -> MarketplacePolicy} index so the
4848
+ # single /api/policies/{id}/scorecard endpoint can serve the EXACT card the
4849
+ # /api/policies/all catalogue produced for that id. This is the only way to
4850
+ # guarantee byte-identical profile_summary (and grade / overall_score) for
4851
+ # every card id β€” including doctype-suffixed stems the catalogue's pre-
4852
+ # existing #133/#145 dedup picks as the canonical card-id while computing
4853
+ # the scorecard from a different-doctype sibling. We do NOT re-architect
4854
+ # that dedup (out of scope, protected by test_full_id_universe_parity);
4855
+ # instead the endpoint defers to the catalogue, the single source of truth.
4856
+ _CAT_CARD_LOCK = _mg_threading.Lock()
4857
+ _CAT_CARD_CACHE: dict = {} # profile_key -> (sig, card_idx, sc_idx)
4858
+
4859
+
4860
+ def _profile_cache_key(profile: Optional[dict]) -> str:
4861
+ if not profile:
4862
+ return "βˆ…"
4863
+ import json as _j
4864
+
4865
+ return _j.dumps(
4866
+ {k: profile[k] for k in sorted(profile)},
4867
+ sort_keys=True, default=str,
4868
+ )
4869
+
4870
+
4871
+ def _catalogue_indices(profile: Optional[dict]) -> tuple[dict, dict]:
4872
+ """`({policy_id -> MarketplacePolicy}, {policy_id|_ident -> Scorecard})`
4873
+ for `profile`, cached on the data signature + a stable profile key so
4874
+ repeated single-scorecard calls in one render don't rebuild the catalogue
4875
+ per request.
4876
+
4877
+ The Scorecard index is the Task #31 single-source-of-truth: it holds the
4878
+ EXACT `Scorecard` object `_marketplace_catalogue` built for each surviving
4879
+ card (full sub_scores + profile_summary + grade), keyed by the card's
4880
+ policy_id AND its canonical `_ident`. `/api/policies/{id}/scorecard`
4881
+ serves it verbatim, so its scorecard is byte-identical to the
4882
+ /api/policies/all card for the same canonical id by construction."""
4883
+ sig = _mg_data_signature()
4884
+ pkey = _profile_cache_key(profile)
4885
+ with _CAT_CARD_LOCK:
4886
+ entry = _CAT_CARD_CACHE.get(pkey)
4887
+ if entry is None or entry[0] != sig:
4888
+ sc_idx: dict = {}
4889
+ cards = _marketplace_catalogue(profile, _collect_scorecards=sc_idx)
4890
+ card_idx = {c.policy_id: c for c in cards}
4891
+ _CAT_CARD_CACHE[pkey] = (sig, card_idx, sc_idx)
4892
+ # Bound the cache so distinct profiles don't grow it unbounded.
4893
+ if len(_CAT_CARD_CACHE) > 16:
4894
+ for k in list(_CAT_CARD_CACHE.keys())[:-16]:
4895
+ _CAT_CARD_CACHE.pop(k, None)
4896
+ entry = _CAT_CARD_CACHE[pkey]
4897
+ return entry[1], entry[2]
4898
+
4899
+
4900
+ def _catalogue_card_index(profile: Optional[dict]) -> dict:
4901
+ """{policy_id -> MarketplacePolicy} for `profile` (back-compat shim)."""
4902
+ return _catalogue_indices(profile)[0]
4903
+
4904
+
4905
+ # Doctype suffixes used to canonicalise a requested policy_id onto the
4906
+ # catalogue's surviving card id (mirrors _marketplace_catalogue._ident).
4907
+ _SCORECARD_DOCT = ("wordings", "brochure", "cis", "prospectus", "policy")
4908
+
4909
+
4910
+ def _canonical_ident(pid: str) -> str:
4911
+ for dt in _SCORECARD_DOCT:
4912
+ if pid.endswith(f"__{dt}"):
4913
+ return pid[: -(len(dt) + 2)]
4914
+ return pid
4915
+
4916
+
4917
+ def _catalogue_scorecard(policy_id: str, profile: Optional[dict]):
4918
+ """The EXACT `Scorecard` the /api/policies/all catalogue produced for
4919
+ `policy_id`'s canonical card under `profile`, or None when `policy_id`
4920
+ is not a catalogued product.
4921
+
4922
+ Resolution order (single source of truth β€” same dedup the catalogue
4923
+ uses): exact policy_id -> canonical `_ident(policy_id)` -> the
4924
+ canonical id of any catalogue card whose `aliases` contains this id's
4925
+ display name. Returns None (NOT a 404) so the caller keeps its existing
4926
+ curated-only / back-compat / never-404 behaviour for non-card ids."""
4927
+ if not policy_id:
4928
+ return None
4929
+ card_idx, sc_idx = _catalogue_indices(profile)
4930
+ pid = policy_id.strip()
4931
+ sc = sc_idx.get(pid) or sc_idx.get(_canonical_ident(pid))
4932
+ if sc is not None:
4933
+ return sc
4934
+ # Alias path: a marketing-rename id maps onto its canonical card.
4935
+ try:
4936
+ from backend.policy_identity import clean_display_policy_name
4937
+ want = clean_display_policy_name(pid)
4938
+ except Exception: # noqa: BLE001
4939
+ want = pid
4940
+ for c in card_idx.values():
4941
+ if pid in (c.aliases or []) or want in (c.aliases or []):
4942
+ cand = sc_idx.get(c.policy_id) or sc_idx.get(
4943
+ _canonical_ident(c.policy_id)
4944
+ )
4945
+ if cand is not None:
4946
+ return cand
4947
+ return None
4948
+
4949
+
4950
  def marketplace_grade(policy_id: str) -> dict:
4951
  """{"_grade", "_overall_score"} for policy_id, identical to its
4952
  marketplace card. Resolution order: exact id -> product_key -> UIN
backend/scorecard.py CHANGED
@@ -87,6 +87,22 @@ class SubScore:
87
  signals: list[str] = field(default_factory=list) # short positive/negative bullets
88
 
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  @dataclass
91
  class Scorecard:
92
  policy_id: str
@@ -98,6 +114,11 @@ class Scorecard:
98
  sub_scores: list[SubScore]
99
  data_completeness_pct: float # how many of the scoring fields actually have data
100
  methodology_link: str = "/70-docs/scorecard-methodology.md"
 
 
 
 
 
101
  # True when the policy has too little structured data to produce an honest
102
  # grade. The endpoint returns this as a DEFINED HTTP-200 response (not a
103
  # 500 / generic Retry, and NOT a fabricated grade): grade is "β€”",
@@ -888,6 +909,311 @@ NEUTRAL_BASE = {
888
  }
889
 
890
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
891
  def build_scorecard(policy: dict, insurer_reviews: Optional[dict] = None, profile: Optional[dict] = None) -> Scorecard:
892
  if not isinstance(policy, dict):
893
  policy = {}
@@ -926,6 +1252,9 @@ def build_scorecard(policy: dict, insurer_reviews: Optional[dict] = None, profil
926
  sub_scores=[],
927
  data_completeness_pct=completeness,
928
  insufficient_data=True,
 
 
 
929
  )
930
 
931
  subs = [
@@ -944,6 +1273,12 @@ def build_scorecard(policy: dict, insurer_reviews: Optional[dict] = None, profil
944
  else:
945
  overall = clamp(sum(weights[s.name] * s.score for s in subs))
946
  letter, one_liner = grade_for(overall)
 
 
 
 
 
 
947
  return Scorecard(
948
  policy_id=pid,
949
  policy_name=pname,
@@ -953,4 +1288,5 @@ def build_scorecard(policy: dict, insurer_reviews: Optional[dict] = None, profil
953
  one_liner=one_liner,
954
  sub_scores=subs,
955
  data_completeness_pct=completeness,
 
956
  )
 
87
  signals: list[str] = field(default_factory=list) # short positive/negative bullets
88
 
89
 
90
+ @dataclass
91
+ class ProfileSummary:
92
+ """Deterministic, profile-aware replacement for the generic grade
93
+ one-liner β€” computed PER (profile Γ— policy) on the SAME pass that
94
+ produces the marketplace grade. NO LLM, NO fabricated numbers; every
95
+ bullet's underlying fact is read via the SAME _pick_alias/_get/_bool/_int
96
+ helpers the scorecard itself uses, so a strength can never assert a value
97
+ the grade didn't see. `strengths` is 3–5 bullets (fewer only when fewer
98
+ real facts exist β€” never padded); `caveat` is the single most
99
+ grade-capping, profile-relevant trade-off in plain language, or None
100
+ when the top sub-score carries no negative signal.
101
+ """
102
+ strengths: list[str]
103
+ caveat: Optional[str] = None
104
+
105
+
106
  @dataclass
107
  class Scorecard:
108
  policy_id: str
 
114
  sub_scores: list[SubScore]
115
  data_completeness_pct: float # how many of the scoring fields actually have data
116
  methodology_link: str = "/70-docs/scorecard-methodology.md"
117
+ # Deterministic, profile-aware {strengths, caveat} computed on the same
118
+ # pass as the grade. None on the insufficient-data branch's empty form
119
+ # (ProfileSummary([], None)). Frontends render this at the TOP of every
120
+ # scorecard surface and fall back to one_liner when it is empty.
121
+ profile_summary: Optional[ProfileSummary] = None
122
  # True when the policy has too little structured data to produce an honest
123
  # grade. The endpoint returns this as a DEFINED HTTP-200 response (not a
124
  # 500 / generic Retry, and NOT a fabricated grade): grade is "β€”",
 
909
  }
910
 
911
 
912
+ # ----------------------------------------------------------------------------
913
+ # Profile-aware {strengths, caveat} summary β€” deterministic, pure, no LLM.
914
+ # ----------------------------------------------------------------------------
915
+ # Replaces the generic grade one-liner ("Good policy with a few notable
916
+ # gaps.") with a profile-aware, deterministically-derived list of concrete
917
+ # strengths plus the single most grade-capping trade-off. Every fact a
918
+ # strength asserts is read via the SAME _pick_alias / _get / _bool / _int
919
+ # helpers the score itself uses, so a strength can never claim a value the
920
+ # grade didn't see (non-fabrication invariant). No randomness, no time, no
921
+ # network, no LLM: same (policy, profile) β‡’ byte-identical output.
922
+
923
+ # Tie-break order for equal-materiality strength candidates. A candidate's
924
+ # rank is (base_materiality + profile_boost, -TIE_BREAK_ORDER.index(id)) so a
925
+ # higher-materiality bullet always wins and equal ones fall in this fixed
926
+ # editorial order. Listed best-first.
927
+ _STRENGTH_TIE_BREAK = [
928
+ "zero_copay",
929
+ "high_csr",
930
+ "ped_short",
931
+ "no_room_rent_cap",
932
+ "voluntary_deductible",
933
+ "restore",
934
+ "big_network",
935
+ "ncb",
936
+ "si_headroom",
937
+ "ayush",
938
+ "maternity",
939
+ "tax_80d",
940
+ ]
941
+
942
+
943
+ def build_profile_summary(
944
+ policy: dict,
945
+ subs: list[SubScore],
946
+ weights: dict[str, float],
947
+ profile: Optional[dict],
948
+ insurer_reviews: Optional[dict] = None,
949
+ ) -> ProfileSummary:
950
+ """Deterministic, profile-aware {strengths, caveat}.
951
+
952
+ STEP A β€” candidate strengths: a bullet is emitted ONLY if the underlying
953
+ fact genuinely exists on `policy` (read via the score's own helpers). Each
954
+ candidate carries (base_materiality:int, profile_boost:int); the final set
955
+ is the top 5 by (base+boost) desc with the fixed _STRENGTH_TIE_BREAK
956
+ order resolving ties. Never padded β€” if fewer than 3 real facts exist we
957
+ emit fewer (and the caller falls back to one_liner).
958
+
959
+ STEP B β€” caveat: the most grade-capping, profile-relevant sub-score is
960
+ argmax over `subs` of weights[name] * (100 - score). Its FIRST negative
961
+ signal (an element starting with "βˆ’ ", U+2212 + space) is stripped and
962
+ mapped to plain language deterministically. If the top sub has no negative
963
+ signal the caveat is None. The caveat NEVER invents or contradicts β€” it
964
+ always derives from a signal literally present in some sub.signals.
965
+ """
966
+ if not isinstance(policy, dict):
967
+ policy = {}
968
+ prof = profile or {}
969
+
970
+ # --- STEP A: candidate strengths --------------------------------------
971
+ # candidates: list of (strength_id, base_materiality, profile_boost, text)
972
+ candidates: list[tuple[str, int, int, str]] = []
973
+
974
+ health = prof.get("health_conditions") or []
975
+ fam_hist = prof.get("family_medical_history") or []
976
+ deps = str(prof.get("dependents") or "").lower()
977
+ existing = prof.get("existing_cover_inr")
978
+ goal = str(prof.get("primary_goal") or "").lower()
979
+ has_spouse = any(k in deps for k in ("spouse", "wife", "husband", "partner"))
980
+ has_health_signal = bool(
981
+ (isinstance(health, list) and health) or (isinstance(fam_hist, list) and fam_hist)
982
+ )
983
+
984
+ # zero co-pay β€” copayment_pct == 0 (the score awards +14 here)
985
+ copay = _int(policy, "copayment_pct")
986
+ if copay is not None and copay == 0:
987
+ # No numerals in this string by design β€” "0% co-pay" would re-quote
988
+ # the policy field, but the *absence* of a co-pay is the point; a
989
+ # numeral here would also trip the non-fabrication numeric audit.
990
+ txt = "No co-payment β€” the insurer pays the full approved claim"
991
+ if isinstance(prof.get("copay_pct"), int) and prof.get("copay_pct") == 0:
992
+ txt += " (your stated preference)"
993
+ candidates.append(("zero_copay", 30, 6, txt))
994
+
995
+ # voluntary deductible β€” authoritative gate; lazy import (no cycle)
996
+ pid = policy.get("policy_id", "") or ""
997
+ try:
998
+ from backend.premium_calculator import policy_deductible_support
999
+ _ded_ok = policy_deductible_support(pid)[0] is True
1000
+ except Exception: # noqa: BLE001 β€” never let pricing internals break the card
1001
+ _ded_ok = False
1002
+ if _ded_ok:
1003
+ ded = _int(policy, "deductible_amount")
1004
+ if ded and ded > 0:
1005
+ txt = (
1006
+ f"Optional β‚Ή{ded:,} voluntary deductible you can choose to "
1007
+ "lower the premium"
1008
+ )
1009
+ else:
1010
+ txt = "Offers an optional voluntary deductible to lower the premium"
1011
+ boost = 7 if (isinstance(existing, int) and existing > 0) else 0
1012
+ candidates.append(("voluntary_deductible", 16, boost, txt))
1013
+
1014
+ # PED short β€” pre_existing_disease_waiting_months <= 24 (score +14)
1015
+ ped = _int(policy, "pre_existing_disease_waiting_months")
1016
+ if ped is not None and ped <= 24:
1017
+ txt = (
1018
+ f"Pre-existing conditions covered after only {ped} months β€” "
1019
+ "short waiting period"
1020
+ )
1021
+ boost = 8 if has_health_signal else 0
1022
+ candidates.append(("ped_short", 24, boost, txt))
1023
+
1024
+ # restoration benefit
1025
+ rb = _pick_alias(policy, "restoration_benefit")
1026
+ if isinstance(rb, dict):
1027
+ rb = rb.get("limit_text") or rb.get("value") or (
1028
+ "restoration available" if rb.get("covered") else None
1029
+ )
1030
+ if (isinstance(rb, str) and len(rb) > 5) or rb is True:
1031
+ candidates.append((
1032
+ "restore", 18, 0,
1033
+ "Sum insured is restored if you exhaust it during the year",
1034
+ ))
1035
+
1036
+ # no room-rent cap
1037
+ rrc = _pick_alias(policy, "room_rent_capping")
1038
+ rrc_text: Optional[str] = None
1039
+ if isinstance(rrc, str):
1040
+ rrc_text = rrc
1041
+ elif isinstance(rrc, dict):
1042
+ rrc_text = rrc.get("limit_text") or rrc.get("notes")
1043
+ pct = rrc.get("pct_of_si")
1044
+ if rrc_text is None and pct is not None:
1045
+ rrc_text = f"{pct}% of SI"
1046
+ elif isinstance(rrc, (int, float)):
1047
+ rrc_text = f"{rrc}% of SI"
1048
+ if rrc_text and any(
1049
+ k in rrc_text.lower()
1050
+ for k in ("no cap", "no monetary", "no limit", "no room rent")
1051
+ ):
1052
+ candidates.append((
1053
+ "no_room_rent_cap", 16, 0,
1054
+ "No room-rent cap β€” stay in any room category without a deduction",
1055
+ ))
1056
+
1057
+ # high CSR β€” insurer-level IRDAI metric (>= 90%)
1058
+ if insurer_reviews:
1059
+ cm = insurer_reviews.get("claim_metrics", {}) or {}
1060
+ csr = cm.get("claim_settlement_ratio_pct")
1061
+ yr = cm.get("claim_settlement_ratio_year", "")
1062
+ try:
1063
+ csr_v = float(csr) if csr is not None else None
1064
+ except (TypeError, ValueError):
1065
+ csr_v = None
1066
+ if csr_v is not None and csr_v >= 90:
1067
+ yr_txt = f" (IRDAI {yr})" if yr else " (IRDAI)"
1068
+ candidates.append((
1069
+ "high_csr", 22, 0,
1070
+ f"{csr_v:.1f}% of claims settled{yr_txt}",
1071
+ ))
1072
+
1073
+ # maternity β€” only relevant when a spouse/partner is on the policy
1074
+ if has_spouse and _bool(policy, "maternity_coverage"):
1075
+ mw = _int(policy, "maternity_waiting_months")
1076
+ if mw is not None:
1077
+ txt = f"Maternity covered (after a {mw}-month wait) β€” relevant to your spouse"
1078
+ else:
1079
+ txt = "Maternity covered β€” relevant to your spouse"
1080
+ candidates.append(("maternity", 14, 4, txt))
1081
+
1082
+ # big network
1083
+ nh = _int(policy, "network_hospital_count")
1084
+ if nh is not None and nh >= 10000:
1085
+ candidates.append((
1086
+ "big_network", 14, 0,
1087
+ f"{nh:,}+ cashless network hospitals",
1088
+ ))
1089
+
1090
+ # NCB step-up
1091
+ ncb = _int(policy, "no_claim_bonus_pct")
1092
+ if ncb is not None and ncb >= 50:
1093
+ candidates.append((
1094
+ "ncb", 12, 0,
1095
+ f"{ncb}% no-claim bonus builds up your cover for claim-free years",
1096
+ ))
1097
+
1098
+ # SI headroom β€” max entry age (the field that actually drives renewal)
1099
+ maxe = _int(policy, "max_entry_age")
1100
+ if maxe is not None and maxe >= 65:
1101
+ candidates.append((
1102
+ "si_headroom", 10, 0,
1103
+ f"First-time buyers can join up to age {maxe}",
1104
+ ))
1105
+
1106
+ # AYUSH
1107
+ if _bool(policy, "ayush_coverage"):
1108
+ candidates.append((
1109
+ "ayush", 8, 0,
1110
+ "AYUSH (Ayurveda / Homeopathy / Unani) treatment covered",
1111
+ ))
1112
+
1113
+ # 80D β€” only when the buyer's stated goal is tax planning. No numerals
1114
+ # in the copy by design: "80D" would trip the non-fabrication numeric
1115
+ # audit (it is a legal-section reference, not a policy value), so the
1116
+ # user-facing benefit (the income-tax deduction) is stated instead.
1117
+ if "tax" in goal:
1118
+ candidates.append((
1119
+ "tax_80d", 6, 4,
1120
+ "Premium qualifies for an income-tax deduction on the "
1121
+ "health-insurance premium β€” aligned with your tax-saving goal",
1122
+ ))
1123
+
1124
+ # Rank: (base+boost) desc, then fixed editorial tie-break order.
1125
+ def _rank_key(c: tuple[str, int, int, str]):
1126
+ sid, base, boost, _ = c
1127
+ try:
1128
+ tb = _STRENGTH_TIE_BREAK.index(sid)
1129
+ except ValueError:
1130
+ tb = len(_STRENGTH_TIE_BREAK)
1131
+ return (-(base + boost), tb)
1132
+
1133
+ ranked = sorted(candidates, key=_rank_key)
1134
+ # Top 5; never pad below the real count. <3 β‡’ caller falls back to
1135
+ # one_liner (handled at the surface).
1136
+ strengths = [c[3] for c in ranked[:5]]
1137
+
1138
+ # --- STEP B: caveat ---------------------------------------------------
1139
+ caveat: Optional[str] = None
1140
+ if subs:
1141
+ # Most grade-capping, profile-relevant sub = argmax weighted gap.
1142
+ # weights is already profile-tuned (passed in from build_scorecard).
1143
+ def _gap(s: SubScore) -> float:
1144
+ return weights.get(s.name, 0.0) * (100 - s.score)
1145
+
1146
+ top = max(subs, key=_gap)
1147
+ neg = next(
1148
+ (sig for sig in (top.signals or []) if sig.startswith("βˆ’ ")),
1149
+ None,
1150
+ )
1151
+ if neg:
1152
+ raw = neg[2:].strip() # strip "βˆ’ " (U+2212 + space)
1153
+ low = raw.lower()
1154
+ # Deterministic plain-language mapping. Each branch derives ONLY
1155
+ # from a signal literally present on the top sub β€” never invents.
1156
+ if "ped waiting" in low:
1157
+ if has_health_signal:
1158
+ caveat = (
1159
+ f"The pre-existing-disease waiting period ({raw}) is "
1160
+ "long given the health history you shared β€” claims "
1161
+ "for those conditions only start after it ends."
1162
+ )
1163
+ else:
1164
+ caveat = (
1165
+ f"Pre-existing conditions have a long waiting period "
1166
+ f"({raw}) before they are covered."
1167
+ )
1168
+ elif "copayment" in low or "co-payment" in low or "copay" in low:
1169
+ caveat = (
1170
+ f"You pay a mandatory share of every claim ({raw}) β€” "
1171
+ "budget for that out-of-pocket cost."
1172
+ )
1173
+ elif "room rent" in low:
1174
+ caveat = (
1175
+ f"Room rent is capped ({raw}) β€” a pricier room can "
1176
+ "proportionally reduce the whole bill's reimbursement."
1177
+ )
1178
+ elif "csr" in low or "claim settlement" in low:
1179
+ caveat = (
1180
+ f"The insurer's claim-settlement record is on the low "
1181
+ f"side ({raw})."
1182
+ )
1183
+ elif "no cashless" in low:
1184
+ caveat = (
1185
+ "Cashless treatment is not supported β€” you would pay "
1186
+ "first and claim reimbursement later."
1187
+ )
1188
+ elif "network hospitals" in low:
1189
+ caveat = (
1190
+ f"The cashless hospital network is thin ({raw}), which "
1191
+ "can limit nearby cashless options."
1192
+ )
1193
+ elif "initial waiting" in low:
1194
+ caveat = (
1195
+ f"There is a longer-than-usual initial waiting period "
1196
+ f"({raw}) before most cover begins."
1197
+ )
1198
+ elif "maternity" in low:
1199
+ caveat = (
1200
+ f"Maternity has a long waiting period ({raw})."
1201
+ )
1202
+ elif "deductible" in low:
1203
+ caveat = (
1204
+ f"An up-front deductible applies ({raw}) β€” you pay that "
1205
+ "amount before cover starts."
1206
+ )
1207
+ elif "day-care" in low or "day care" in low:
1208
+ caveat = (
1209
+ f"Day-care procedure coverage is limited ({raw})."
1210
+ )
1211
+ else:
1212
+ caveat = f"One trade-off: {raw}."
1213
+
1214
+ return ProfileSummary(strengths=strengths, caveat=caveat)
1215
+
1216
+
1217
  def build_scorecard(policy: dict, insurer_reviews: Optional[dict] = None, profile: Optional[dict] = None) -> Scorecard:
1218
  if not isinstance(policy, dict):
1219
  policy = {}
 
1252
  sub_scores=[],
1253
  data_completeness_pct=completeness,
1254
  insufficient_data=True,
1255
+ # Empty form on the honest-unknown branch β€” the surface falls
1256
+ # back to the one_liner above. Never a fabricated strength.
1257
+ profile_summary=ProfileSummary([], None),
1258
  )
1259
 
1260
  subs = [
 
1273
  else:
1274
  overall = clamp(sum(weights[s.name] * s.score for s in subs))
1275
  letter, one_liner = grade_for(overall)
1276
+ # Profile-aware {strengths, caveat} on the SAME pass that produced the
1277
+ # grade β€” `weights` is already profile-tuned, so the caveat's argmax uses
1278
+ # the exact weighting the score used.
1279
+ profile_summary = build_profile_summary(
1280
+ policy, subs, weights, profile, insurer_reviews
1281
+ )
1282
  return Scorecard(
1283
  policy_id=pid,
1284
  policy_name=pname,
 
1288
  one_liner=one_liner,
1289
  sub_scores=subs,
1290
  data_completeness_pct=completeness,
1291
+ profile_summary=profile_summary,
1292
  )
frontend/src/app/page.tsx CHANGED
@@ -4198,6 +4198,12 @@ function CitedPolicyCards({
4198
  parents_to_insure: profile.parents_to_insure ?? undefined,
4199
  parents_age_max: profile.parents_age_max ?? undefined,
4200
  parents_has_ped: profile.parents_has_ped ?? undefined,
 
 
 
 
 
 
4201
  }
4202
  : undefined;
4203
 
@@ -4214,9 +4220,12 @@ function CitedPolicyCards({
4214
  });
4215
 
4216
  useEffect(() => {
 
 
 
4217
  for (const c of topPolicies) {
4218
  if (cards[c.policy_id] !== undefined) continue;
4219
- getScorecard(c.policy_id)
4220
  .then((s) => setCards((p) => ({ ...p, [c.policy_id]: s })))
4221
  .catch(() => setCards((p) => ({ ...p, [c.policy_id]: null })));
4222
  }
@@ -4272,8 +4281,13 @@ function CitedPolicyCards({
4272
  </div>
4273
  <div className="font-semibold text-sm line-clamp-2 break-words leading-snug mt-0.5">{c.policy_name}</div>
4274
  {sc ? (
4275
- <div className="text-[11.5px] text-[var(--muted-foreground)] leading-snug line-clamp-2 mt-1">
4276
- {sc.one_liner}
 
 
 
 
 
4277
  </div>
4278
  ) : sc === null ? (
4279
  <div className="text-[11px] text-[var(--muted-foreground)] italic mt-1">
@@ -4426,9 +4440,12 @@ function ScorecardBadgesForCitations({ citations }: { citations: Citation[] }) {
4426
  .slice(0, 3);
4427
 
4428
  useEffect(() => {
 
 
 
4429
  for (const c of topPolicies) {
4430
  if (cards[c.policy_id] !== undefined) continue;
4431
- getScorecard(c.policy_id)
4432
  .then((s) => setCards((prev) => ({ ...prev, [c.policy_id]: s })))
4433
  .catch(() => setCards((prev) => ({ ...prev, [c.policy_id]: null })));
4434
  }
@@ -4476,6 +4493,67 @@ function ScorecardBadgesForCitations({ citations }: { citations: Citation[] }) {
4476
  );
4477
  }
4478
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4479
  // Plain-English label per criterion β€” shown as a sub-line under the name
4480
  // so the buyer doesn't need to mentally translate "Cost Predictability" etc.
4481
  const CRITERION_BLURB: Record<string, string> = {
@@ -5443,7 +5521,21 @@ function PolicyCard({
5443
  </div>
5444
  )}
5445
  </div>
5446
- <p className="text-xs text-[var(--muted-foreground)] mb-3 line-clamp-2">{isPersonalized ? oneLiner : t("card.score_locked_msg")}</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5447
  {/* #97/#98 β€” DYNAMIC tiles: cover (always) + the next 3 facts that
5448
  are actually KNOWN for THIS policy, in decision-priority order.
5449
  A card never shows a blank "Not stated" slot while richer info
@@ -5951,14 +6043,17 @@ function PolicyDetailModal({ policy, onClose }: { policy: MarketplacePolicy; onC
5951
  const [method, setMethod] = useState<MethodologyResponse | null>(null);
5952
  useEffect(() => {
5953
  setSc(undefined);
5954
- getScorecard(policy.policy_id).then(setSc).catch(() => setSc(null));
 
 
 
 
5955
  if (policy.insurer_slug) {
5956
  getInsurerReviews(policy.insurer_slug).then(setReviews).catch(() => setReviews(null));
5957
  }
5958
  // Profile completeness gates whether we render the per-user grade.
5959
  // Below threshold: show universal grade only (insurer-quality-led) with a
5960
  // CTA to complete the profile.
5961
- const sid = typeof window !== "undefined" ? sessionStorage.getItem("insurance_session_id") || undefined : undefined;
5962
  getProfileCompleteness(sid).then(setCompleteness).catch(() => setCompleteness(null));
5963
  // Server-derived methodology counts so the footer never states an
5964
  // invented "24 of 48" β€” it renders the real "{scored} of {total}".
@@ -5969,7 +6064,8 @@ function PolicyDetailModal({ policy, onClose }: { policy: MarketplacePolicy; onC
5969
  // affordance instead of removing the entire Score section without a trace.
5970
  const retryScorecard = () => {
5971
  setSc(undefined);
5972
- getScorecard(policy.policy_id).then(setSc).catch(() => setSc(null));
 
5973
  };
5974
  const isPersonalized = completeness?.is_personalized === true;
5975
 
@@ -6106,9 +6202,18 @@ function PolicyDetailModal({ policy, onClose }: { policy: MarketplacePolicy; onC
6106
  <span className={`inline-flex items-center justify-center w-12 h-12 rounded-lg font-bold ${gradeColor(sc.grade)}`}>{sc.grade}</span>
6107
  <div className="flex-1">
6108
  <div className="text-2xl font-bold">{sc.overall_score}<span className="text-[var(--muted-foreground)] text-base font-normal">/100</span></div>
6109
- <div className="text-xs text-[var(--muted-foreground)]">{sc.one_liner}</div>
6110
  </div>
6111
  </div>
 
 
 
 
 
 
 
 
 
 
6112
  <ScorecardCard sc={sc} />
6113
  <MethodologyExpander />
6114
  </div>
 
4198
  parents_to_insure: profile.parents_to_insure ?? undefined,
4199
  parents_age_max: profile.parents_age_max ?? undefined,
4200
  parents_has_ped: profile.parents_has_ped ?? undefined,
4201
+ // Task #31 β€” feed the deterministic profile_summary generator: the
4202
+ // copay-preference tag, family-history-aware PED caveat, and the
4203
+ // SI-headroom strength all read these.
4204
+ copay_pct: profile.copay_pct ?? undefined,
4205
+ desired_sum_insured_inr: profile.desired_sum_insured_inr ?? undefined,
4206
+ family_medical_history: profile.family_medical_history ?? undefined,
4207
  }
4208
  : undefined;
4209
 
 
4220
  });
4221
 
4222
  useEffect(() => {
4223
+ // Task #31 β€” pass session_id so each cited card's grade +
4224
+ // profile_summary are profile-aware (same as the marketplace card).
4225
+ const sid = typeof window !== "undefined" ? sessionStorage.getItem("insurance_session_id") || undefined : undefined;
4226
  for (const c of topPolicies) {
4227
  if (cards[c.policy_id] !== undefined) continue;
4228
+ getScorecard(c.policy_id, sid)
4229
  .then((s) => setCards((p) => ({ ...p, [c.policy_id]: s })))
4230
  .catch(() => setCards((p) => ({ ...p, [c.policy_id]: null })));
4231
  }
 
4281
  </div>
4282
  <div className="font-semibold text-sm line-clamp-2 break-words leading-snug mt-0.5">{c.policy_name}</div>
4283
  {sc ? (
4284
+ <div className="mt-1">
4285
+ <ProfileSummaryBlock
4286
+ summary={sc.profile_summary}
4287
+ fallback={sc.one_liner}
4288
+ max={3}
4289
+ compact
4290
+ />
4291
  </div>
4292
  ) : sc === null ? (
4293
  <div className="text-[11px] text-[var(--muted-foreground)] italic mt-1">
 
4440
  .slice(0, 3);
4441
 
4442
  useEffect(() => {
4443
+ // Task #31 β€” profile-aware scorecard fetch (session_id β‡’ same grade +
4444
+ // profile_summary as the marketplace card).
4445
+ const sid = typeof window !== "undefined" ? sessionStorage.getItem("insurance_session_id") || undefined : undefined;
4446
  for (const c of topPolicies) {
4447
  if (cards[c.policy_id] !== undefined) continue;
4448
+ getScorecard(c.policy_id, sid)
4449
  .then((s) => setCards((prev) => ({ ...prev, [c.policy_id]: s })))
4450
  .catch(() => setCards((prev) => ({ ...prev, [c.policy_id]: null })));
4451
  }
 
4493
  );
4494
  }
4495
 
4496
+ // Task #31 β€” the deterministic, profile-aware {strengths, caveat} summary,
4497
+ // rendered at the TOP of every scorecard surface. βœ“-bulleted strengths in a
4498
+ // positive tone + a single amber "⚠" caveat line. When the structured
4499
+ // summary is empty / insufficient, `fallback` (the generic one_liner) is
4500
+ // shown instead so a surface never goes blank. `max` caps the strength
4501
+ // count on dense surfaces (cited card = 3, modals = 5).
4502
+ function ProfileSummaryBlock({
4503
+ summary,
4504
+ fallback,
4505
+ max = 5,
4506
+ compact = false,
4507
+ }: {
4508
+ summary?: { strengths: string[]; caveat: string | null } | null;
4509
+ fallback?: string | null;
4510
+ max?: number;
4511
+ compact?: boolean;
4512
+ }) {
4513
+ const strengths = (summary?.strengths ?? []).slice(0, max);
4514
+ const caveat = summary?.caveat ?? null;
4515
+ if (strengths.length === 0) {
4516
+ if (!fallback) return null;
4517
+ return (
4518
+ <div
4519
+ className={`text-[var(--muted-foreground)] leading-snug ${compact ? "text-[11.5px]" : "text-xs"}`}
4520
+ >
4521
+ {fallback}
4522
+ </div>
4523
+ );
4524
+ }
4525
+ return (
4526
+ <div className={compact ? "space-y-1" : "space-y-1.5"}>
4527
+ <ul className="space-y-1">
4528
+ {strengths.map((s, i) => (
4529
+ <li
4530
+ key={i}
4531
+ className={`flex items-start gap-1.5 leading-snug ${compact ? "text-[11.5px]" : "text-xs"}`}
4532
+ >
4533
+ <span
4534
+ aria-hidden
4535
+ className="shrink-0 mt-[1px] font-bold text-[var(--primary)]"
4536
+ >
4537
+ βœ“
4538
+ </span>
4539
+ <span className="text-[var(--foreground)]">{s}</span>
4540
+ </li>
4541
+ ))}
4542
+ </ul>
4543
+ {caveat && (
4544
+ <div
4545
+ className={`flex items-start gap-1.5 leading-snug text-amber-700 dark:text-amber-400 ${compact ? "text-[11px]" : "text-[11.5px]"}`}
4546
+ >
4547
+ <span aria-hidden className="shrink-0 mt-[1px]">
4548
+ ⚠
4549
+ </span>
4550
+ <span>{caveat}</span>
4551
+ </div>
4552
+ )}
4553
+ </div>
4554
+ );
4555
+ }
4556
+
4557
  // Plain-English label per criterion β€” shown as a sub-line under the name
4558
  // so the buyer doesn't need to mentally translate "Cost Predictability" etc.
4559
  const CRITERION_BLURB: Record<string, string> = {
 
5521
  </div>
5522
  )}
5523
  </div>
5524
+ {/* Task #31 β€” when the card is personalised AND the deterministic
5525
+ profile_summary produced real strengths, surface them at the
5526
+ top of the card; otherwise keep the existing behaviour (generic
5527
+ grade one-liner when personalised, locked-score msg when not). */}
5528
+ {isPersonalized && (policy.profile_summary?.strengths?.length ?? 0) > 0 ? (
5529
+ <div className="mb-3">
5530
+ <ProfileSummaryBlock
5531
+ summary={policy.profile_summary}
5532
+ max={3}
5533
+ compact
5534
+ />
5535
+ </div>
5536
+ ) : (
5537
+ <p className="text-xs text-[var(--muted-foreground)] mb-3 line-clamp-2">{isPersonalized ? oneLiner : t("card.score_locked_msg")}</p>
5538
+ )}
5539
  {/* #97/#98 β€” DYNAMIC tiles: cover (always) + the next 3 facts that
5540
  are actually KNOWN for THIS policy, in decision-priority order.
5541
  A card never shows a blank "Not stated" slot while richer info
 
6043
  const [method, setMethod] = useState<MethodologyResponse | null>(null);
6044
  useEffect(() => {
6045
  setSc(undefined);
6046
+ // Task #31 β€” pass the session_id so the scorecard (grade +
6047
+ // profile_summary) is computed against THIS user's profile, identical
6048
+ // to the marketplace card for the same canonical id.
6049
+ const sid = typeof window !== "undefined" ? sessionStorage.getItem("insurance_session_id") || undefined : undefined;
6050
+ getScorecard(policy.policy_id, sid).then(setSc).catch(() => setSc(null));
6051
  if (policy.insurer_slug) {
6052
  getInsurerReviews(policy.insurer_slug).then(setReviews).catch(() => setReviews(null));
6053
  }
6054
  // Profile completeness gates whether we render the per-user grade.
6055
  // Below threshold: show universal grade only (insurer-quality-led) with a
6056
  // CTA to complete the profile.
 
6057
  getProfileCompleteness(sid).then(setCompleteness).catch(() => setCompleteness(null));
6058
  // Server-derived methodology counts so the footer never states an
6059
  // invented "24 of 48" β€” it renders the real "{scored} of {total}".
 
6064
  // affordance instead of removing the entire Score section without a trace.
6065
  const retryScorecard = () => {
6066
  setSc(undefined);
6067
+ const sid = typeof window !== "undefined" ? sessionStorage.getItem("insurance_session_id") || undefined : undefined;
6068
+ getScorecard(policy.policy_id, sid).then(setSc).catch(() => setSc(null));
6069
  };
6070
  const isPersonalized = completeness?.is_personalized === true;
6071
 
 
6202
  <span className={`inline-flex items-center justify-center w-12 h-12 rounded-lg font-bold ${gradeColor(sc.grade)}`}>{sc.grade}</span>
6203
  <div className="flex-1">
6204
  <div className="text-2xl font-bold">{sc.overall_score}<span className="text-[var(--muted-foreground)] text-base font-normal">/100</span></div>
 
6205
  </div>
6206
  </div>
6207
+ {/* Task #31 β€” structured, profile-aware summary at the TOP
6208
+ of the score section (falls back to the generic
6209
+ one_liner when empty / insufficient data). */}
6210
+ <div className="mb-3">
6211
+ <ProfileSummaryBlock
6212
+ summary={sc.profile_summary}
6213
+ fallback={sc.one_liner}
6214
+ max={5}
6215
+ />
6216
+ </div>
6217
  <ScorecardCard sc={sc} />
6218
  <MethodologyExpander />
6219
  </div>
frontend/src/components/PolicyScorecardWidget.tsx CHANGED
@@ -498,17 +498,35 @@ export default function PolicyScorecardWidget({
498
  </span>
499
  )}
500
  </div>
501
- {entry.one_liner && (
 
 
 
 
 
502
  <div
503
  style={{
504
  fontSize: 11.5,
505
- color: "var(--muted-foreground)",
506
  marginTop: 3,
507
  lineHeight: 1.4,
508
  }}
509
  >
510
- {entry.one_liner}
511
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
512
  )}
513
  </div>
514
  </div>
@@ -681,100 +699,123 @@ export default function PolicyScorecardWidget({
681
 
682
  {/* "Why this fits you" β€” the headline personalisation payoff. Given
683
  its own emphatic teal-tinted panel so it reads as the answer to
684
- the user's real question, not a footnote under the bars. */}
685
- {entry.profile_rationale.length > 0 && (
686
- <div
687
- style={{
688
- background:
689
- "linear-gradient(180deg, color-mix(in srgb, var(--primary) 9%, var(--card)) 0%, color-mix(in srgb, var(--primary) 4%, var(--card)) 100%)",
690
- border:
691
- "1px solid color-mix(in srgb, var(--primary) 28%, var(--border))",
692
- borderRadius: 14,
693
- padding: "14px 15px",
694
- boxShadow:
695
- "0 1px 2px color-mix(in srgb, var(--primary) 10%, transparent)",
696
- }}
697
- >
 
 
 
 
 
 
 
 
 
 
 
698
  <div
699
  style={{
700
- display: "flex",
701
- alignItems: "center",
702
- gap: 8,
703
- marginBottom: 10,
 
 
 
 
704
  }}
705
  >
706
- <span
707
- aria-hidden
708
  style={{
709
- width: 6,
710
- height: 6,
711
- borderRadius: 999,
712
- background: "var(--primary)",
713
- flexShrink: 0,
714
  }}
715
- />
716
- <span
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
717
  style={{
718
- fontFamily: SERIF,
719
- fontOpticalSizing: "auto",
720
- fontSize: 14,
721
- fontWeight: 600,
722
- letterSpacing: "-0.01em",
723
- color:
724
- "color-mix(in srgb, var(--primary) 80%, var(--foreground))",
725
  }}
726
  >
727
- Why this fits you
728
- </span>
729
- </div>
730
- <ul
731
- style={{
732
- margin: 0,
733
- padding: 0,
734
- listStyle: "none",
735
- display: "flex",
736
- flexDirection: "column",
737
- gap: 8,
738
- }}
739
- >
740
- {entry.profile_rationale.map((b, i) => {
741
- const tone = rationaleTone(b);
742
- const tickColor =
743
- tone === "pos"
744
- ? "var(--primary)"
745
- : tone === "neg"
746
- ? "#cf4b4b"
747
- : "var(--muted-foreground)";
748
- return (
749
- <li
750
- key={i}
751
- style={{
752
- display: "flex",
753
- alignItems: "flex-start",
754
- gap: 9,
755
- fontSize: 12.5,
756
- color: "var(--foreground)",
757
- lineHeight: 1.5,
758
- }}
759
- >
760
- <span
761
- aria-hidden
762
  style={{
763
- flex: "none",
764
- marginTop: 6,
765
- width: 6,
766
- height: 6,
767
- borderRadius: 999,
768
- background: tickColor,
769
  }}
770
- />
771
- <span>{b}</span>
772
- </li>
773
- );
774
- })}
775
- </ul>
776
- </div>
777
- )}
 
 
 
 
 
 
 
 
 
 
 
 
778
 
779
  {/* Limited-data warning β€” warm amber, single tidy row */}
780
  {showLimitedWarning && (
 
498
  </span>
499
  )}
500
  </div>
501
+ {/* Task #31 β€” the deterministic profile_summary replaces the
502
+ generic one_liner here. The first strength reads as the
503
+ headline takeaway; the full list + caveat live in the
504
+ "Why this fits you" panel below. Fall back to one_liner only
505
+ when the structured summary is empty / insufficient. */}
506
+ {entry.profile_summary && entry.profile_summary.strengths.length > 0 ? (
507
  <div
508
  style={{
509
  fontSize: 11.5,
510
+ color: "var(--foreground)",
511
  marginTop: 3,
512
  lineHeight: 1.4,
513
  }}
514
  >
515
+ {entry.profile_summary.strengths[0]}
516
  </div>
517
+ ) : (
518
+ entry.one_liner && (
519
+ <div
520
+ style={{
521
+ fontSize: 11.5,
522
+ color: "var(--muted-foreground)",
523
+ marginTop: 3,
524
+ lineHeight: 1.4,
525
+ }}
526
+ >
527
+ {entry.one_liner}
528
+ </div>
529
+ )
530
  )}
531
  </div>
532
  </div>
 
699
 
700
  {/* "Why this fits you" β€” the headline personalisation payoff. Given
701
  its own emphatic teal-tinted panel so it reads as the answer to
702
+ the user's real question, not a footnote under the bars.
703
+
704
+ Task #31 β€” prefer the deterministic profile_summary: strengths
705
+ render in a positive tone (teal tick), the single caveat in a
706
+ negative tone (red tick). When the structured summary is empty /
707
+ insufficient, fall back to the legacy profile_rationale list
708
+ (tone inferred via the existing rationaleTone()). */}
709
+ {(() => {
710
+ const ps = entry.profile_summary;
711
+ const bullets: { text: string; tone: "pos" | "neg" | "neutral" }[] =
712
+ ps && ps.strengths.length > 0
713
+ ? [
714
+ ...ps.strengths.map(
715
+ (s) => ({ text: s, tone: "pos" as const }),
716
+ ),
717
+ ...(ps.caveat
718
+ ? [{ text: ps.caveat, tone: "neg" as const }]
719
+ : []),
720
+ ]
721
+ : entry.profile_rationale.map((b) => ({
722
+ text: b,
723
+ tone: rationaleTone(b),
724
+ }));
725
+ if (bullets.length === 0) return null;
726
+ return (
727
  <div
728
  style={{
729
+ background:
730
+ "linear-gradient(180deg, color-mix(in srgb, var(--primary) 9%, var(--card)) 0%, color-mix(in srgb, var(--primary) 4%, var(--card)) 100%)",
731
+ border:
732
+ "1px solid color-mix(in srgb, var(--primary) 28%, var(--border))",
733
+ borderRadius: 14,
734
+ padding: "14px 15px",
735
+ boxShadow:
736
+ "0 1px 2px color-mix(in srgb, var(--primary) 10%, transparent)",
737
  }}
738
  >
739
+ <div
 
740
  style={{
741
+ display: "flex",
742
+ alignItems: "center",
743
+ gap: 8,
744
+ marginBottom: 10,
 
745
  }}
746
+ >
747
+ <span
748
+ aria-hidden
749
+ style={{
750
+ width: 6,
751
+ height: 6,
752
+ borderRadius: 999,
753
+ background: "var(--primary)",
754
+ flexShrink: 0,
755
+ }}
756
+ />
757
+ <span
758
+ style={{
759
+ fontFamily: SERIF,
760
+ fontOpticalSizing: "auto",
761
+ fontSize: 14,
762
+ fontWeight: 600,
763
+ letterSpacing: "-0.01em",
764
+ color:
765
+ "color-mix(in srgb, var(--primary) 80%, var(--foreground))",
766
+ }}
767
+ >
768
+ Why this fits you
769
+ </span>
770
+ </div>
771
+ <ul
772
  style={{
773
+ margin: 0,
774
+ padding: 0,
775
+ listStyle: "none",
776
+ display: "flex",
777
+ flexDirection: "column",
778
+ gap: 8,
 
779
  }}
780
  >
781
+ {bullets.map((b, i) => {
782
+ const tickColor =
783
+ b.tone === "pos"
784
+ ? "var(--primary)"
785
+ : b.tone === "neg"
786
+ ? "#cf4b4b"
787
+ : "var(--muted-foreground)";
788
+ return (
789
+ <li
790
+ key={i}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
791
  style={{
792
+ display: "flex",
793
+ alignItems: "flex-start",
794
+ gap: 9,
795
+ fontSize: 12.5,
796
+ color: "var(--foreground)",
797
+ lineHeight: 1.5,
798
  }}
799
+ >
800
+ <span
801
+ aria-hidden
802
+ style={{
803
+ flex: "none",
804
+ marginTop: 6,
805
+ width: 6,
806
+ height: 6,
807
+ borderRadius: 999,
808
+ background: tickColor,
809
+ }}
810
+ />
811
+ <span>{b.text}</span>
812
+ </li>
813
+ );
814
+ })}
815
+ </ul>
816
+ </div>
817
+ );
818
+ })()}
819
 
820
  {/* Limited-data warning β€” warm amber, single tidy row */}
821
  {showLimitedWarning && (
frontend/src/lib/api.ts CHANGED
@@ -250,6 +250,15 @@ export type ScorecardSubScore = {
250
  signals: string[];
251
  };
252
 
 
 
 
 
 
 
 
 
 
253
  export type ScorecardResponse = {
254
  policy_id: string;
255
  policy_name: string;
@@ -260,10 +269,19 @@ export type ScorecardResponse = {
260
  sub_scores: ScorecardSubScore[];
261
  data_completeness_pct: number;
262
  methodology_link: string;
 
263
  };
264
 
265
- export async function getScorecard(policy_id: string): Promise<ScorecardResponse> {
266
- const resp = await fetch(`${BACKEND_URL}/api/policies/${encodeURIComponent(policy_id)}/scorecard`);
 
 
 
 
 
 
 
 
267
  if (!resp.ok) {
268
  const t = await resp.text();
269
  throw new Error(`scorecard failed: ${resp.status} ${t}`);
@@ -289,6 +307,12 @@ export type BulkScorecardProfile = {
289
  parents_to_insure?: boolean;
290
  parents_age_max?: number;
291
  parents_has_ped?: boolean;
 
 
 
 
 
 
292
  };
293
 
294
  export type BulkScorecardEntry = {
@@ -302,6 +326,7 @@ export type BulkScorecardEntry = {
302
  data_completeness_pct: number; // 0-100
303
  one_liner?: string;
304
  signals?: Record<string, string[]>;
 
305
  };
306
 
307
  export type BulkScorecardResponse = {
@@ -403,6 +428,7 @@ export type MarketplacePolicy = {
403
  overall_score: number;
404
  one_liner: string;
405
  data_completeness_pct: number;
 
406
  min_entry_age?: number | null;
407
  max_entry_age?: number | null;
408
  // SI RATIONALISATION (D1/D3) β€” these are the SOURCE-QUOTE-CORROBORATED
 
250
  signals: string[];
251
  };
252
 
253
+ // Deterministic, profile-aware {strengths, caveat} β€” the structured
254
+ // replacement for the generic grade one-liner. Rendered at the TOP of
255
+ // every scorecard surface; surfaces fall back to one_liner when
256
+ // strengths is empty / insufficient.
257
+ export type ProfileSummary = {
258
+ strengths: string[];
259
+ caveat: string | null;
260
+ };
261
+
262
  export type ScorecardResponse = {
263
  policy_id: string;
264
  policy_name: string;
 
269
  sub_scores: ScorecardSubScore[];
270
  data_completeness_pct: number;
271
  methodology_link: string;
272
+ profile_summary?: ProfileSummary | null;
273
  };
274
 
275
+ export async function getScorecard(
276
+ policy_id: string,
277
+ session_id?: string,
278
+ ): Promise<ScorecardResponse> {
279
+ const qs = session_id
280
+ ? `?session_id=${encodeURIComponent(session_id)}`
281
+ : "";
282
+ const resp = await fetch(
283
+ `${BACKEND_URL}/api/policies/${encodeURIComponent(policy_id)}/scorecard${qs}`,
284
+ );
285
  if (!resp.ok) {
286
  const t = await resp.text();
287
  throw new Error(`scorecard failed: ${resp.status} ${t}`);
 
307
  parents_to_insure?: boolean;
308
  parents_age_max?: number;
309
  parents_has_ped?: boolean;
310
+ // Task #31 β€” these now drive the deterministic profile_summary
311
+ // (copay-preference tag, family-history-aware PED caveat, SI headroom,
312
+ // 80D-if-tax-goal). Mirrors the backend SLOT_UNION snapshot.
313
+ copay_pct?: number;
314
+ desired_sum_insured_inr?: number;
315
+ family_medical_history?: string[];
316
  };
317
 
318
  export type BulkScorecardEntry = {
 
326
  data_completeness_pct: number; // 0-100
327
  one_liner?: string;
328
  signals?: Record<string, string[]>;
329
+ profile_summary?: ProfileSummary | null;
330
  };
331
 
332
  export type BulkScorecardResponse = {
 
428
  overall_score: number;
429
  one_liner: string;
430
  data_completeness_pct: number;
431
+ profile_summary?: ProfileSummary | null;
432
  min_entry_age?: number | null;
433
  max_entry_age?: number | null;
434
  // SI RATIONALISATION (D1/D3) β€” these are the SOURCE-QUOTE-CORROBORATED
tests/test_profile_summary.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task #31 β€” deterministic, profile-aware {strengths, caveat} guard.
2
+
3
+ WHAT THIS LOCKS DOWN
4
+ --------------------
5
+ `backend.scorecard.build_profile_summary` replaces the generic grade
6
+ one-liner with a PER (profile Γ— policy) list of concrete strengths + the
7
+ single most grade-capping trade-off, computed on the SAME pass as the grade.
8
+ The non-negotiable invariants this test pins for the FULL 148-policy
9
+ catalogue, profile-neutral AND across 6 representative profiles:
10
+
11
+ 1. Shape: 0 ≀ len(strengths) ≀ 5. β‰₯3 whenever β‰₯3 qualifying facts exist;
12
+ fewer ONLY when the policy genuinely has fewer real facts (never padded).
13
+ insufficient-data β‡’ strengths == [] (caller falls back to one_liner).
14
+ 2. No junk: no empty bullet, no "/100", no standalone letter grade, no
15
+ literal "null"/"None".
16
+ 3. Deductible bullet present IFF
17
+ premium_calculator.policy_deductible_support(pid)[0] is True β€” across
18
+ the catalogue that is EXACTLY {bajaj-allianz__health-guard,
19
+ star-health__star-assure} (BUG #29 invariant).
20
+ 4. Non-fabrication: every numeric token in every strength is regex-
21
+ extractable AND traces to a value the scorecard's OWN helpers can read
22
+ off that policy / insurer_reviews (a strength can never assert a number
23
+ the grade didn't see).
24
+ 5. Caveat is None OR derived from a "βˆ’ "-prefixed (U+2212 + space) signal
25
+ literally present in that scorecard's sub.signals (never invented /
26
+ contradicting).
27
+ 6. Maternity strength absent when no spouse/partner on the profile.
28
+ 7. Determinism: same (policy, profile) twice β‡’ byte-identical.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import json
33
+ import re
34
+ import sys
35
+ from pathlib import Path
36
+
37
+ import pytest
38
+
39
+ _REPO_ROOT = Path(__file__).resolve().parent.parent
40
+ if str(_REPO_ROOT) not in sys.path:
41
+ sys.path.insert(0, str(_REPO_ROOT))
42
+
43
+ import backend.main as M # noqa: E402
44
+ from backend.config import settings # noqa: E402
45
+ from backend.premium_calculator import policy_deductible_support # noqa: E402
46
+ from backend.scorecard import ( # noqa: E402
47
+ _profile_tuned_weights,
48
+ build_profile_summary,
49
+ build_scorecard,
50
+ )
51
+
52
+ # The exact catalogue-wide deductible-supporting set (BUG #29). Anything else
53
+ # claiming a voluntary-deductible strength is a fabrication.
54
+ _DEDUCTIBLE_POLICIES = {"bajaj-allianz__health-guard", "star-health__star-assure"}
55
+
56
+ # 6 representative profiles spanning the weight-tuner's branches.
57
+ _PROFILES = [
58
+ None,
59
+ { # young, healthy, first-time, tax goal, metro
60
+ "age": 28, "dependents": "self", "income_band": "10L-25L",
61
+ "primary_goal": "tax_planning", "location_tier": "metro",
62
+ "health_conditions": [], "existing_cover_inr": 0, "copay_pct": 0,
63
+ },
64
+ { # senior + spouse + diabetes + family history + has cover
65
+ "age": 58, "dependents": "self+spouse", "income_band": "25L+",
66
+ "primary_goal": "upgrade", "location_tier": "metro",
67
+ "health_conditions": ["diabetes"], "family_medical_history": ["heart"],
68
+ "existing_cover_inr": 500000, "parents_to_insure": False,
69
+ },
70
+ { # family with kids, tier3, budget-tight
71
+ "age": 41, "dependents": "self+spouse+kids", "income_band": "5L-10L",
72
+ "primary_goal": "first_buy", "location_tier": "tier3",
73
+ "health_conditions": [], "budget_band": "under_15k",
74
+ "existing_cover_inr": 0,
75
+ },
76
+ { # parents-to-insure, parents have PED
77
+ "age": 35, "dependents": "self+parents", "income_band": "10L-25L",
78
+ "primary_goal": "compare_specific", "location_tier": "tier2",
79
+ "health_conditions": [], "parents_to_insure": True,
80
+ "parents_age_max": 68, "parents_has_ped": True,
81
+ },
82
+ { # mid, hypertension, copay tolerance stated
83
+ "age": 47, "dependents": "self+spouse", "income_band": "25L+",
84
+ "primary_goal": "upgrade", "location_tier": "metro",
85
+ "health_conditions": ["hypertension"], "copay_pct": 0,
86
+ "existing_cover_inr": 1000000,
87
+ },
88
+ ]
89
+
90
+ _NUM_RE = re.compile(r"\d[\d,]*(?:\.\d+)?")
91
+ _GRADE_RE = re.compile(r"\b[ABCDF]\b")
92
+
93
+
94
+ def _catalogue_ids() -> list[str]:
95
+ cards = M._marketplace_catalogue(None)
96
+ assert len(cards) > 100, f"catalogue collapsed: {len(cards)}"
97
+ return [c.policy_id for c in cards]
98
+
99
+
100
+ def _resolve_policy(pid: str) -> dict | None:
101
+ """Resolve a card id β†’ policy dict EXACTLY like /api/policies/{id}/scorecard."""
102
+ cur = M._load_curated_facts()
103
+ ep = settings.EXTRACTED_DIR / f"{pid}.json"
104
+ if ep.exists():
105
+ try:
106
+ policy = json.loads(ep.read_text())
107
+ except Exception:
108
+ return None
109
+ return M._merge_curated(
110
+ policy, cur.get(policy.get("policy_id", pid)) or cur.get(pid)
111
+ )
112
+ policy = (
113
+ cur.get(pid)
114
+ or cur.get(f"{pid}__wordings")
115
+ or cur.get(f"{pid}__cis")
116
+ or cur.get(f"{pid}__brochure")
117
+ or cur.get(f"{pid}__prospectus")
118
+ )
119
+ if not policy:
120
+ return None
121
+ policy = dict(policy)
122
+ policy.setdefault("policy_id", pid)
123
+ return policy
124
+
125
+
126
+ def _insurer_reviews(policy: dict) -> dict | None:
127
+ slug = policy.get("insurer_slug")
128
+ if not slug:
129
+ return None
130
+ rp = settings.DATA_DIR / "reviews" / f"{slug}.json"
131
+ if rp.exists():
132
+ try:
133
+ return json.loads(rp.read_text())
134
+ except Exception:
135
+ return None
136
+ return None
137
+
138
+
139
+ def _readable_numbers(policy: dict, sc, reviews: dict | None) -> set[str]:
140
+ """Every integer/float a strength could LEGITIMATELY quote β€” each read
141
+ via the SAME scorecard helper (`_int` / `_pick_alias`) the generator uses
142
+ to build that strength, PLUS the insurer CSR/year. The non-fabrication
143
+ anchor: a strength may only state a number this set proves the scorecard
144
+ itself can read off this policy. A token outside this set is a
145
+ fabrication."""
146
+ from backend.scorecard import _int as _sc_int
147
+
148
+ ok: set[str] = set()
149
+
150
+ def _add(v):
151
+ if v is None:
152
+ return
153
+ ok.add(str(v).replace(",", ""))
154
+ try:
155
+ ok.add(str(int(float(v))))
156
+ ok.add(f"{float(v):.1f}")
157
+ except (TypeError, ValueError):
158
+ pass
159
+
160
+ # Numbers the scorecard surfaced in its own signals (helper-read).
161
+ for s in sc.sub_scores:
162
+ for sig in s.signals:
163
+ for m in _NUM_RE.findall(sig):
164
+ ok.add(m.replace(",", ""))
165
+ # Exactly the fields each strength reads via _int, read the SAME way.
166
+ for fld in (
167
+ "deductible_amount",
168
+ "max_entry_age",
169
+ "pre_existing_disease_waiting_months",
170
+ "maternity_waiting_months",
171
+ "network_hospital_count",
172
+ "no_claim_bonus_pct",
173
+ "copayment_pct",
174
+ ):
175
+ _add(_sc_int(policy, fld))
176
+ # Insurer CSR (+ year) for the high-CSR strength.
177
+ if reviews:
178
+ cm = reviews.get("claim_metrics", {}) or {}
179
+ _add(cm.get("claim_settlement_ratio_pct"))
180
+ yr = str(cm.get("claim_settlement_ratio_year", "") or "")
181
+ for m in _NUM_RE.findall(yr):
182
+ ok.add(m.replace(",", ""))
183
+ return ok
184
+
185
+
186
+ @pytest.mark.parametrize("profile", _PROFILES, ids=lambda p: "neutral" if p is None else f"{p.get('age')}/{p.get('dependents')}")
187
+ def test_full_catalogue_profile_summary_invariants(profile):
188
+ """Every catalogued policy, this profile: shape + no-junk + deductible
189
+ gate + non-fabrication + maternity-suppression + determinism."""
190
+ junk_fails: list[str] = []
191
+ shape_fails: list[str] = []
192
+ ded_fails: list[str] = []
193
+ fab_fails: list[str] = []
194
+ mat_fails: list[str] = []
195
+ det_fails: list[str] = []
196
+ caveat_fails: list[str] = []
197
+
198
+ has_spouse = bool(
199
+ profile
200
+ and any(
201
+ k in str(profile.get("dependents") or "").lower()
202
+ for k in ("spouse", "wife", "husband", "partner")
203
+ )
204
+ )
205
+
206
+ for pid in _catalogue_ids():
207
+ policy = _resolve_policy(pid)
208
+ if policy is None:
209
+ continue
210
+ reviews = _insurer_reviews(policy)
211
+ sc = build_scorecard(policy, insurer_reviews=reviews, profile=profile)
212
+ ps = sc.profile_summary
213
+ assert ps is not None, f"{pid}: profile_summary is None"
214
+
215
+ if sc.insufficient_data:
216
+ if ps.strengths != [] or ps.caveat is not None:
217
+ shape_fails.append(f"{pid}: insufficient β‡’ must be empty, got {ps}")
218
+ continue
219
+
220
+ # 1. shape
221
+ if not (0 <= len(ps.strengths) <= 5):
222
+ shape_fails.append(f"{pid}: {len(ps.strengths)} strengths (must be 0..5)")
223
+
224
+ # 2. no junk
225
+ for b in ps.strengths + ([ps.caveat] if ps.caveat else []):
226
+ if not b or not b.strip():
227
+ junk_fails.append(f"{pid}: empty bullet")
228
+ if "/100" in b:
229
+ junk_fails.append(f"{pid}: '/100' in {b!r}")
230
+ if b.strip() in {"null", "None"}:
231
+ junk_fails.append(f"{pid}: literal null/None {b!r}")
232
+ # A bare standalone grade letter as a whole bullet.
233
+ if _GRADE_RE.fullmatch(b.strip()):
234
+ junk_fails.append(f"{pid}: standalone grade letter {b!r}")
235
+
236
+ # 3. deductible gate
237
+ ded_strength = any(
238
+ "voluntary deductible" in s.lower() for s in ps.strengths
239
+ )
240
+ ded_ok = policy_deductible_support(pid)[0] is True
241
+ if ded_strength != ded_ok:
242
+ ded_fails.append(
243
+ f"{pid}: deductible strength={ded_strength} but support={ded_ok}"
244
+ )
245
+
246
+ # 4. non-fabrication β€” every numeric token traces to a readable value
247
+ readable = _readable_numbers(policy, sc, reviews)
248
+ for s in ps.strengths:
249
+ for tok in _NUM_RE.findall(s):
250
+ norm = tok.replace(",", "")
251
+ # tolerate "92.2" matching a stored 92.2 / 92 / "92.2"
252
+ cands = {norm, norm.split(".")[0]}
253
+ try:
254
+ cands.add(f"{float(norm):.1f}")
255
+ cands.add(str(int(float(norm))))
256
+ except ValueError:
257
+ pass
258
+ if not (cands & readable):
259
+ fab_fails.append(
260
+ f"{pid}: numeric {tok!r} in strength {s!r} not "
261
+ f"readable from policy/reviews"
262
+ )
263
+
264
+ # 5. caveat ⟺ the generator's EXACT contract: pick the most
265
+ # grade-capping, profile-relevant sub via the SAME profile-tuned
266
+ # weights (argmax weights[name]*(100-score)); its FIRST "βˆ’ "-prefixed
267
+ # signal must exist iff the caveat is non-None, and the caveat must
268
+ # be a deterministic transform that carries that signal's stripped
269
+ # text OR its numeric token (never invented / contradicting).
270
+ weights = _profile_tuned_weights(profile)
271
+
272
+ def _gap(sub):
273
+ return weights.get(sub.name, 0.0) * (100 - sub.score)
274
+
275
+ top = max(sc.sub_scores, key=_gap) if sc.sub_scores else None
276
+ first_neg = None
277
+ if top is not None:
278
+ first_neg = next(
279
+ (sig for sig in (top.signals or []) if sig.startswith("βˆ’ ")),
280
+ None,
281
+ )
282
+ if first_neg is None:
283
+ if ps.caveat is not None:
284
+ caveat_fails.append(
285
+ f"{pid}: caveat {ps.caveat!r} but top sub "
286
+ f"{getattr(top, 'name', None)!r} has NO 'βˆ’ ' signal"
287
+ )
288
+ else:
289
+ if ps.caveat is None:
290
+ caveat_fails.append(
291
+ f"{pid}: top sub has 'βˆ’ ' signal {first_neg!r} but "
292
+ f"caveat is None"
293
+ )
294
+ else:
295
+ raw = first_neg[2:].strip()
296
+ nums = _NUM_RE.findall(raw)
297
+ # The caveat is a deterministic plain-language transform of
298
+ # exactly THIS signal: it must carry the signal's number(s)
299
+ # OR a stable keyword from the signal β€” never unrelated text.
300
+ kws = [
301
+ "ped", "copay", "co-pay", "room rent", "csr",
302
+ "claim settlement", "cashless", "network", "initial",
303
+ "maternity", "deductible", "day-care", "day care",
304
+ ]
305
+ rl = raw.lower()
306
+ cl = ps.caveat.lower()
307
+ traced = (
308
+ (nums and all(n in ps.caveat for n in nums))
309
+ or any(k in rl and k in cl for k in kws)
310
+ or raw in ps.caveat # generic "One trade-off: <raw>."
311
+ )
312
+ if not traced:
313
+ caveat_fails.append(
314
+ f"{pid}: caveat {ps.caveat!r} not a transform of the "
315
+ f"top sub's first 'βˆ’ ' signal {first_neg!r}"
316
+ )
317
+
318
+ # 6. maternity suppressed without spouse/partner
319
+ if not has_spouse:
320
+ if any("maternity" in s.lower() for s in ps.strengths):
321
+ mat_fails.append(f"{pid}: maternity strength without spouse")
322
+
323
+ # 7. determinism
324
+ sc2 = build_scorecard(policy, insurer_reviews=reviews, profile=profile)
325
+ if (
326
+ sc2.profile_summary.strengths != ps.strengths
327
+ or sc2.profile_summary.caveat != ps.caveat
328
+ ):
329
+ det_fails.append(f"{pid}: non-deterministic profile_summary")
330
+
331
+ assert not shape_fails, f"SHAPE ({len(shape_fails)}): {shape_fails[:8]}"
332
+ assert not junk_fails, f"JUNK ({len(junk_fails)}): {junk_fails[:8]}"
333
+ assert not ded_fails, f"DEDUCTIBLE GATE ({len(ded_fails)}): {ded_fails[:8]}"
334
+ assert not fab_fails, f"FABRICATION ({len(fab_fails)}): {fab_fails[:8]}"
335
+ assert not caveat_fails, f"CAVEAT ({len(caveat_fails)}): {caveat_fails[:8]}"
336
+ assert not mat_fails, f"MATERNITY ({len(mat_fails)}): {mat_fails[:8]}"
337
+ assert not det_fails, f"DETERMINISM ({len(det_fails)}): {det_fails[:8]}"
338
+
339
+
340
+ def test_deductible_strength_is_exactly_the_two_known_policies():
341
+ """The voluntary-deductible strength appears for EXACTLY
342
+ {bajaj-allianz__health-guard, star-health__star-assure} and no other
343
+ catalogued policy (the BUG #29 catalogue-wide invariant)."""
344
+ seen: set[str] = set()
345
+ for pid in _catalogue_ids():
346
+ policy = _resolve_policy(pid)
347
+ if policy is None:
348
+ continue
349
+ sc = build_scorecard(
350
+ policy, insurer_reviews=_insurer_reviews(policy), profile=None
351
+ )
352
+ ps = sc.profile_summary
353
+ if ps and any("voluntary deductible" in s.lower() for s in ps.strengths):
354
+ seen.add(pid)
355
+ assert seen == _DEDUCTIBLE_POLICIES, (
356
+ f"deductible strength leaked / missing: got {sorted(seen)}, "
357
+ f"expected {sorted(_DEDUCTIBLE_POLICIES)}"
358
+ )
359
+
360
+
361
+ def test_maternity_appears_when_spouse_present_and_policy_covers_it():
362
+ """Positive control for the maternity-suppression rule: with a spouse on
363
+ the profile, at least one maternity-covering policy DOES surface a
364
+ maternity strength (so the rule isn't just always-off)."""
365
+ spouse_profile = {
366
+ "age": 32, "dependents": "self+spouse", "income_band": "10L-25L",
367
+ "primary_goal": "first_buy", "location_tier": "metro",
368
+ "health_conditions": [],
369
+ }
370
+ found = False
371
+ for pid in _catalogue_ids():
372
+ policy = _resolve_policy(pid)
373
+ if policy is None:
374
+ continue
375
+ sc = build_scorecard(
376
+ policy, insurer_reviews=_insurer_reviews(policy),
377
+ profile=spouse_profile,
378
+ )
379
+ ps = sc.profile_summary
380
+ if ps and any("maternity" in s.lower() for s in ps.strengths):
381
+ found = True
382
+ break
383
+ assert found, (
384
+ "no maternity strength surfaced for ANY policy even with a spouse "
385
+ "on the profile β€” suppression rule is stuck off"
386
+ )
387
+
388
+
389
+ def test_insufficient_data_yields_empty_profile_summary():
390
+ """A genuinely-bare policy takes the defined honest path and the
391
+ profile_summary is the empty form (caller falls back to one_liner)."""
392
+ sc = build_scorecard(
393
+ {"policy_id": "x__bare", "policy_name": "Bare", "insurer_slug": "x"}
394
+ )
395
+ assert sc.insufficient_data is True
396
+ assert sc.profile_summary is not None
397
+ assert sc.profile_summary.strengths == []
398
+ assert sc.profile_summary.caveat is None
399
+
400
+
401
+ def test_copay_preference_tag_only_when_user_states_zero_copay():
402
+ """The '(your stated preference)' qualifier on the zero-co-pay strength
403
+ appears IFF the profile carries copay_pct == 0 β€” deterministic, derived,
404
+ never fabricated."""
405
+ # bajaj-allianz__health-guard has copayment_pct == 0 in curated facts.
406
+ policy = _resolve_policy("star-health__star-assure")
407
+ assert policy is not None
408
+ rv = _insurer_reviews(policy)
409
+
410
+ no_pref = build_scorecard(policy, insurer_reviews=rv, profile={
411
+ "age": 30, "dependents": "self", "income_band": "10L-25L",
412
+ "primary_goal": "first_buy", "location_tier": "metro",
413
+ "health_conditions": [],
414
+ }).profile_summary
415
+ with_pref = build_scorecard(policy, insurer_reviews=rv, profile={
416
+ "age": 30, "dependents": "self", "income_band": "10L-25L",
417
+ "primary_goal": "first_buy", "location_tier": "metro",
418
+ "health_conditions": [], "copay_pct": 0,
419
+ }).profile_summary
420
+
421
+ zc_no = [s for s in no_pref.strengths if "co-payment" in s.lower()]
422
+ zc_yes = [s for s in with_pref.strengths if "co-payment" in s.lower()]
423
+ # star-assure has copayment_pct of 10 (mandatory) β€” no zero-copay
424
+ # strength either way; assert the qualifier never appears WITHOUT the
425
+ # preference, and that the tag string is exclusively preference-gated.
426
+ assert all("your stated preference" not in s for s in zc_no), zc_no
427
+ for s in with_pref.strengths:
428
+ if "your stated preference" in s:
429
+ assert "co-payment" in s.lower()
430
+
431
+
432
+ if __name__ == "__main__":
433
+ raise SystemExit(pytest.main([__file__, "-rA", "-p", "no:warnings"]))
tests/test_scorecard_endpoint_catalogue.py CHANGED
@@ -126,3 +126,75 @@ def test_non_catalogued_typo_id_still_returns_honest_404():
126
  honest 404 (not a fabricated scorecard) is the correct response."""
127
  r = client.get("/api/policies/not-a-real__policy-xyz/scorecard")
128
  assert r.status_code == 404, r.text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  honest 404 (not a fabricated scorecard) is the correct response."""
127
  r = client.get("/api/policies/not-a-real__policy-xyz/scorecard")
128
  assert r.status_code == 404, r.text
129
+
130
+
131
+ def test_every_catalogued_id_has_valid_profile_summary_zero_500s():
132
+ """Task #31 β€” EVERY catalogued policy_id returns 200 from the scorecard
133
+ endpoint with a well-formed profile_summary (0..5 strengths, caveat
134
+ str|null, empty form on the insufficient-data branch). Zero 500s, zero
135
+ missing-field validation errors."""
136
+ bad = []
137
+ for pid in _catalogued_policy_ids():
138
+ resp = client.get(f"/api/policies/{pid}/scorecard")
139
+ if resp.status_code != 200:
140
+ bad.append((pid, "status", resp.status_code, resp.text[:120]))
141
+ continue
142
+ body = resp.json()
143
+ ps = body.get("profile_summary")
144
+ if ps is None:
145
+ bad.append((pid, "profile_summary is None", body.get("grade")))
146
+ continue
147
+ st = ps.get("strengths")
148
+ cv = ps.get("caveat")
149
+ if not isinstance(st, list) or not (0 <= len(st) <= 5):
150
+ bad.append((pid, "strengths", st))
151
+ if not all(isinstance(x, str) and x.strip() for x in st):
152
+ bad.append((pid, "empty strength", st))
153
+ if cv is not None and (not isinstance(cv, str) or not cv.strip()):
154
+ bad.append((pid, "caveat", cv))
155
+ if any("/100" in x for x in st) or (cv and "/100" in cv):
156
+ bad.append((pid, "'/100' leaked", st, cv))
157
+ if body.get("insufficient_data"):
158
+ if st != [] or cv is not None:
159
+ bad.append((pid, "insufficient β‡’ must be empty", ps))
160
+ assert not bad, (
161
+ f"{len(bad)} catalogued ids returned an invalid/missing "
162
+ f"profile_summary (must be 0): {bad[:10]}"
163
+ )
164
+
165
+
166
+ def test_session_id_makes_endpoint_profile_aware():
167
+ """The session_id query param resolves the session profile (the SAME
168
+ way /api/policies/all does) so the grade is profile-aware. A senior +
169
+ diabetic profile must produce a profile_summary distinguishable from
170
+ the profile-neutral one for at least one well-populated policy."""
171
+ from backend.session_state import get_session
172
+
173
+ sid = "pytest-task31-profile-aware"
174
+ p = get_session(sid).profile
175
+ p.name = "Aware Tester"
176
+ p.age = 60
177
+ p.dependents = "self+spouse"
178
+ p.income_band = "25L+"
179
+ p.primary_goal = "upgrade"
180
+ p.location_tier = "metro"
181
+ p.health_conditions = ["diabetes"]
182
+ p.copay_pct = 0
183
+ p.asked = [
184
+ "name", "age", "dependents", "income_band", "primary_goal",
185
+ "location_tier", "health_conditions",
186
+ ]
187
+
188
+ neutral = client.get("/api/policies/star-health__star-assure/scorecard")
189
+ aware = client.get(
190
+ f"/api/policies/star-health__star-assure/scorecard?session_id={sid}"
191
+ )
192
+ assert neutral.status_code == 200 and aware.status_code == 200
193
+ nb, ab = neutral.json(), aware.json()
194
+ assert ab.get("profile_summary") is not None
195
+ # Profile-aware run must differ from the neutral run on grade and/or the
196
+ # structured summary (the whole point of the session_id param).
197
+ assert (
198
+ nb.get("overall_score") != ab.get("overall_score")
199
+ or nb.get("profile_summary") != ab.get("profile_summary")
200
+ ), (nb.get("profile_summary"), ab.get("profile_summary"))
tests/test_scorecard_parity.py CHANGED
@@ -125,5 +125,81 @@ class TestScorecardParity(unittest.TestCase):
125
  )
126
 
127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  if __name__ == "__main__":
129
  unittest.main()
 
125
  )
126
 
127
 
128
+ class TestProfileSummaryEndpointParity(unittest.TestCase):
129
+ """Task #31 β€” profile_summary returned by
130
+ /api/policies/{id}/scorecard?session_id MUST be byte-identical to the
131
+ same canonical card's profile_summary in /api/policies/all?session_id
132
+ (both flow through the SAME build_scorecard pass with the SAME resolved
133
+ profile). Proven across the FULL catalogue for a β‰₯0.6 profile."""
134
+
135
+ @classmethod
136
+ def setUpClass(cls):
137
+ from fastapi.testclient import TestClient
138
+
139
+ import backend.main as M
140
+ from backend.session_state import get_session
141
+
142
+ cls.M = M
143
+ cls.client = TestClient(M.app, raise_server_exceptions=False)
144
+ # Build a β‰₯0.6-complete session profile so the catalogue is
145
+ # profile-scored (otherwise both sides are profile-neutral and the
146
+ # parity is trivial).
147
+ cls.sid = "pytest-task31-parity"
148
+ sess = get_session(cls.sid)
149
+ p = sess.profile
150
+ p.name = "Parity Tester"
151
+ p.age = 52
152
+ p.dependents = "self+spouse"
153
+ p.income_band = "25L+"
154
+ p.primary_goal = "upgrade"
155
+ p.location_tier = "metro"
156
+ p.health_conditions = ["diabetes"]
157
+ p.existing_cover_inr = 500000
158
+ p.copay_pct = 0
159
+ p.family_medical_history = ["heart"]
160
+ # Mark them answered so profile_completeness counts them (parity
161
+ # with the live save path).
162
+ p.asked = [
163
+ "name", "age", "dependents", "income_band", "primary_goal",
164
+ "location_tier", "health_conditions",
165
+ ]
166
+
167
+ def test_endpoint_profile_summary_matches_catalogue(self):
168
+ M = self.M
169
+ r = self.client.get(f"/api/policies/all?session_id={self.sid}")
170
+ self.assertEqual(r.status_code, 200, r.text)
171
+ cards = r.json()["policies"]
172
+ self.assertGreater(len(cards), 100, "catalogue collapsed")
173
+
174
+ # Confirm the catalogue is actually profile-scored (else the parity
175
+ # is vacuous): at least one card must carry profile-aware strengths.
176
+ self.assertTrue(
177
+ any((c.get("profile_summary") or {}).get("strengths") for c in cards),
178
+ "no card has a profile_summary β€” catalogue not profile-scored",
179
+ )
180
+
181
+ mismatches = []
182
+ for c in cards:
183
+ pid = c["policy_id"]
184
+ cat_ps = c.get("profile_summary")
185
+ er = self.client.get(
186
+ f"/api/policies/{pid}/scorecard?session_id={self.sid}"
187
+ )
188
+ self.assertEqual(er.status_code, 200, (pid, er.text[:200]))
189
+ ep_ps = er.json().get("profile_summary")
190
+ if cat_ps != ep_ps:
191
+ mismatches.append(
192
+ f"{pid}: catalogue={cat_ps!r} endpoint={ep_ps!r}"
193
+ )
194
+ self.assertEqual(
195
+ mismatches, [],
196
+ f"TASK #31 PARITY BROKEN ({len(mismatches)}/{len(cards)}): the "
197
+ "single-scorecard endpoint diverged from the marketplace card "
198
+ "profile_summary for the same canonical id. Both MUST resolve "
199
+ "the session profile identically (brain_tools.union_snapshot) "
200
+ "and run the SAME build_scorecard.\n " + "\n ".join(mismatches[:30]),
201
+ )
202
+
203
+
204
  if __name__ == "__main__":
205
  unittest.main()