Spaces:
Sleeping
fix(privacy v3/v4): two-fact recall gate + extended same-turn extractors (closes ADR-042 follow-ups)
Browse filesCloses the two open follow-ups in ADR-042 (commits 2acdc9e + 10e6843).
(v3) Extended same-turn match-before-merge in apply_pending_recall
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
v2 covered only age. Now extracts age / dependents / location_tier /
income_band from user_text via four small helpers:
_extract_age_from_text β tight regex, range [18, 99]
_extract_dependents_from_text β delegates to brain_tools._normalize_dependents_inline
(honors canonical bucket set)
_extract_location_tier_from_text β Indian-city β metro/tier1/tier2/tier3
lookup (longest-key-first so "navi mumbai"
beats "mumbai")
_extract_income_band_from_text β delegates to needs_finder._parse_income_band
_parse_user_text_facts(text) runs all four and returns a dict of the
fields that successfully parsed. apply_pending_recall now iterates that
dict and discards the staged recall on any contradicting field
(string-compare for the buckets, int-compare for age).
(v4) Two-fact recall gate in rehydrate_by_name
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Even with v1/v2/v3 redacting the prompt + match-before-merge on
confirm, a bare-name "Hi I'm Rohit" would still SURFACE a Welcome Back
prompt β the very *existence* of which telegraphs that someone under
this name has used the bot. Two-fact gate blocks the staging entirely
unless at least ONE identity fact MATCHES between stored and either
the prior-turn live capture OR the same-turn user_text parse:
- matched fact β stage as before
- contradicting fact β fail-closed; no stage, mark probe done
(stored profile is for a different person)
- no fact available β DEFER; set session.recall_match_deferred=True;
single_brain caller does NOT mark
recall_probe_done so probe retries next turn
handle_turn now reads recall_match_deferred after try_recall_by_name
and only flips recall_probe_done when the probe was conclusive.
Verification
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
43/43 extractor cases pass (covers original screenshot phrasings +
edge cases) + 7/7 end-to-end gate scenarios:
1. bare name, no facts β DEFER
2. name + matching age β STAGE
3. name + matching location β STAGE
4. name + contradicting age β FAIL-CLOSED
5. deferred β next turn live β STAGE
6. no stored profile for name β no-op, no defer
7. stage then same-turn loc-contradict β discard, no merge
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- backend/profile_persistence.py +12 -5
- backend/session_state.py +279 -28
- backend/single_brain.py +20 -6
|
@@ -230,7 +230,7 @@ def extract_potential_name(text: str) -> Optional[str]:
|
|
| 230 |
return raw
|
| 231 |
|
| 232 |
|
| 233 |
-
def try_recall_by_name(session, name: str) -> bool:
|
| 234 |
"""Look up a stored profile by name and STAGE it for confirmation.
|
| 235 |
|
| 236 |
PRIVACY FIX (2026-05-16). Wraps session_state.rehydrate_by_name, which
|
|
@@ -238,21 +238,28 @@ def try_recall_by_name(session, name: str) -> bool:
|
|
| 238 |
auto-merging it into `session.profile`. Nothing is applied to the live
|
| 239 |
session here.
|
| 240 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
Returns:
|
| 242 |
Always False β the stored profile is NEVER auto-applied. The
|
| 243 |
single_brain caller therefore never stamps `is_returning_user` /
|
| 244 |
a "Welcome back" greeting off a bare name on a fresh session.
|
| 245 |
Whether a match was *staged* is observable on
|
| 246 |
-
`session.pending_profile_recall`; the
|
| 247 |
-
|
| 248 |
-
|
|
|
|
| 249 |
"""
|
| 250 |
if not name or not name.strip():
|
| 251 |
return False
|
| 252 |
try:
|
| 253 |
from backend.session_state import rehydrate_by_name
|
| 254 |
|
| 255 |
-
return bool(rehydrate_by_name(session, name))
|
| 256 |
except Exception as e: # noqa: BLE001
|
| 257 |
_log.warning(
|
| 258 |
"try_recall_by_name failed (name=%r): %s: %s",
|
|
|
|
| 230 |
return raw
|
| 231 |
|
| 232 |
|
| 233 |
+
def try_recall_by_name(session, name: str, *, user_text: str = "") -> bool:
|
| 234 |
"""Look up a stored profile by name and STAGE it for confirmation.
|
| 235 |
|
| 236 |
PRIVACY FIX (2026-05-16). Wraps session_state.rehydrate_by_name, which
|
|
|
|
| 238 |
auto-merging it into `session.profile`. Nothing is applied to the live
|
| 239 |
session here.
|
| 240 |
|
| 241 |
+
PRIVACY HARDENING v4 (2026-05-27, ADR-042 follow-up #1) β `user_text`
|
| 242 |
+
is threaded through so the two-fact gate inside rehydrate_by_name can
|
| 243 |
+
parse same-turn identity facts (age/dependents/location/income) to
|
| 244 |
+
decide whether to stage / defer / fail-closed. Callers that don't have
|
| 245 |
+
user_text on hand (rare) still get the prior-turn live-profile path.
|
| 246 |
+
|
| 247 |
Returns:
|
| 248 |
Always False β the stored profile is NEVER auto-applied. The
|
| 249 |
single_brain caller therefore never stamps `is_returning_user` /
|
| 250 |
a "Welcome back" greeting off a bare name on a fresh session.
|
| 251 |
Whether a match was *staged* is observable on
|
| 252 |
+
`session.pending_profile_recall`; whether the probe was *deferred*
|
| 253 |
+
(no facts to disambiguate yet) is on `session.recall_match_deferred`.
|
| 254 |
+
The brain surfaces an "are you <name>?" confirm and calls
|
| 255 |
+
session_state.apply_pending_recall on the user's explicit answer.
|
| 256 |
"""
|
| 257 |
if not name or not name.strip():
|
| 258 |
return False
|
| 259 |
try:
|
| 260 |
from backend.session_state import rehydrate_by_name
|
| 261 |
|
| 262 |
+
return bool(rehydrate_by_name(session, name, user_text=user_text))
|
| 263 |
except Exception as e: # noqa: BLE001
|
| 264 |
_log.warning(
|
| 265 |
"try_recall_by_name failed (name=%r): %s: %s",
|
|
@@ -41,13 +41,25 @@ from typing import Any, Dict
|
|
| 41 |
from backend.needs_finder import Profile, record_answer
|
| 42 |
|
| 43 |
|
| 44 |
-
# 2026-05-27 β best-effort
|
| 45 |
-
# guard inside `apply_pending_recall`
|
| 46 |
-
#
|
| 47 |
-
#
|
| 48 |
-
#
|
| 49 |
-
#
|
| 50 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
_AGE_HINT_RE = re.compile(
|
| 52 |
r"\b(?:age\s*[:=]?\s*|i'?m\s+|i\s+am\s+|aged\s+|aged\s*[:=]?\s*)?(\d{2})"
|
| 53 |
r"\s*(?:years?\s*old|yrs?|y/?o)?\b",
|
|
@@ -71,6 +83,122 @@ def _extract_age_from_text(text: str) -> Optional[int]:
|
|
| 71 |
continue
|
| 72 |
return None
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
_log = logging.getLogger(__name__)
|
| 75 |
|
| 76 |
|
|
@@ -127,6 +255,16 @@ class SessionState:
|
|
| 127 |
# known (any turn); this flag stops it re-staging every subsequent
|
| 128 |
# turn and stops a declined recall from being re-offered.
|
| 129 |
recall_probe_done: bool = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
def _flush(self) -> None:
|
| 132 |
"""No-op. Session state lives only in the in-memory dict; the
|
|
@@ -185,7 +323,12 @@ _RECALL_SUMMARY_FIELDS: tuple[str, ...] = (
|
|
| 185 |
)
|
| 186 |
|
| 187 |
|
| 188 |
-
def rehydrate_by_name(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
"""Cross-session re-entry point β STAGE a name match for confirmation.
|
| 190 |
|
| 191 |
PRIVACY FIX (2026-05-16, audit). Previously this AUTO-MERGED the stored
|
|
@@ -196,6 +339,21 @@ def rehydrate_by_name(session: SessionState, name: str) -> bool:
|
|
| 196 |
and greeted "Welcome back, <name>!". A fresh, no-cookie session must
|
| 197 |
NEVER inherit another session's profile from a weak/shared key.
|
| 198 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
Safe design (KI-196 / ADR-041, specced via `pending_profile_recall` but
|
| 200 |
previously never wired): a name match is STAGED on
|
| 201 |
`session.pending_profile_recall`, NOT merged. `session.profile` is left
|
|
@@ -209,7 +367,8 @@ def rehydrate_by_name(session: SessionState, name: str) -> bool:
|
|
| 209 |
False β always. The stored profile is NEVER auto-applied here, so
|
| 210 |
callers must treat False as "do not flag a returning user
|
| 211 |
/ do not greet Welcome back". Whether a match was *staged*
|
| 212 |
-
is observable via `session.pending_profile_recall`
|
|
|
|
| 213 |
|
| 214 |
Failures are logged but never raise β a fresh chat must always proceed.
|
| 215 |
"""
|
|
@@ -229,8 +388,81 @@ def rehydrate_by_name(session: SessionState, name: str) -> bool:
|
|
| 229 |
if _first and _first.lower() != _stripped.lower():
|
| 230 |
stored = load_profile(_first)
|
| 231 |
if stored is None:
|
|
|
|
|
|
|
|
|
|
| 232 |
return False
|
| 233 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
# Build a non-PII-leaking identity summary so the brain can ask
|
| 235 |
# "are you <name>?" without putting anything on the live profile.
|
| 236 |
summary: Dict[str, Any] = {}
|
|
@@ -254,6 +486,7 @@ def rehydrate_by_name(session: SessionState, name: str) -> bool:
|
|
| 254 |
"stored_fields": staged_fields,
|
| 255 |
"staged_at": time.time(),
|
| 256 |
}
|
|
|
|
| 257 |
session.last_touched = time.time()
|
| 258 |
# Deliberately False: nothing merged, no Welcome-back greeting.
|
| 259 |
return False
|
|
@@ -332,29 +565,47 @@ def apply_pending_recall(
|
|
| 332 |
fld, live_v, staged_v,
|
| 333 |
)
|
| 334 |
return False
|
| 335 |
-
# PRIVACY HARDENING v2 (2026-05-27) β same-turn
|
| 336 |
# _affirm_or_deny + apply_pending_recall fire BEFORE the LLM iteration
|
| 337 |
# that runs save_profile_field, so a user reply like "Yes I'm 35"
|
| 338 |
# against a staged Rohit at age=29 would otherwise slip through the
|
| 339 |
-
# prior-turn guard (live.
|
| 340 |
-
# profile.
|
| 341 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
if user_text:
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
for fld, new in stored_fields.items():
|
| 359 |
try:
|
| 360 |
if fld not in Profile.__dataclass_fields__:
|
|
|
|
| 41 |
from backend.needs_finder import Profile, record_answer
|
| 42 |
|
| 43 |
|
| 44 |
+
# 2026-05-27 β best-effort identity-fact extractors for the same-turn
|
| 45 |
+
# match-before-merge guard inside `apply_pending_recall` AND for the
|
| 46 |
+
# two-fact gate inside `rehydrate_by_name`. The LLM is the canonical
|
| 47 |
+
# extractor (save_profile_field), but it runs AFTER both call sites in
|
| 48 |
+
# the turn pipeline β so a "Yes I'm 35" / "Hi I'm Rohit, I'm in
|
| 49 |
+
# Mumbai" reply would otherwise either merge the wrong profile or fail
|
| 50 |
+
# to stage a legitimate same-turn recall. Mis-parses return None and
|
| 51 |
+
# cost nothing.
|
| 52 |
+
#
|
| 53 |
+
# Coverage:
|
| 54 |
+
# age β _extract_age_from_text
|
| 55 |
+
# dependents β _extract_dependents_from_text (delegates to
|
| 56 |
+
# brain_tools._normalize_dependents_inline so the
|
| 57 |
+
# canonical bucket set is honored)
|
| 58 |
+
# location_tier β _extract_location_tier_from_text (Indian-city
|
| 59 |
+
# name β metro / tier1 / tier2 / tier3 lookup)
|
| 60 |
+
# income_band β _extract_income_band_from_text (delegates to
|
| 61 |
+
# needs_finder._parse_income_band)
|
| 62 |
+
|
| 63 |
_AGE_HINT_RE = re.compile(
|
| 64 |
r"\b(?:age\s*[:=]?\s*|i'?m\s+|i\s+am\s+|aged\s+|aged\s*[:=]?\s*)?(\d{2})"
|
| 65 |
r"\s*(?:years?\s*old|yrs?|y/?o)?\b",
|
|
|
|
| 83 |
continue
|
| 84 |
return None
|
| 85 |
|
| 86 |
+
|
| 87 |
+
def _extract_dependents_from_text(text: str) -> Optional[str]:
|
| 88 |
+
"""Best-effort dependents bucket from free-form text.
|
| 89 |
+
Delegates to brain_tools._normalize_dependents_inline so the
|
| 90 |
+
canonical bucket set ("self", "self+spouse", "self+spouse+kids",
|
| 91 |
+
"self+parents", "self+spouse+parents", "self+spouse+kids+parents",
|
| 92 |
+
"self+kids") is honored. Returns None on no match.
|
| 93 |
+
"""
|
| 94 |
+
if not text:
|
| 95 |
+
return None
|
| 96 |
+
try:
|
| 97 |
+
# Lazy import to avoid load-order issues at module init.
|
| 98 |
+
from backend.brain_tools import _normalize_dependents_inline
|
| 99 |
+
except Exception:
|
| 100 |
+
return None
|
| 101 |
+
try:
|
| 102 |
+
return _normalize_dependents_inline(text)
|
| 103 |
+
except Exception:
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# Indian-city β tier lookup. Tier-1 list per the IRDAI / RBI city
|
| 108 |
+
# classification (Mumbai/Delhi/Bangalore/Chennai/Kolkata/Hyderabad =
|
| 109 |
+
# Tier-1 "metro" in insurance vernacular). Bot's pricing uses "metro"
|
| 110 |
+
# as the high-tier loading bucket β keep that as the alias here so a
|
| 111 |
+
# user typing "Mumbai" maps to the same bucket the LLM would store.
|
| 112 |
+
_LOCATION_TIER_MAP: dict[str, str] = {
|
| 113 |
+
# Metro / Tier-1
|
| 114 |
+
"mumbai": "metro", "bombay": "metro",
|
| 115 |
+
"delhi": "metro", "new delhi": "metro",
|
| 116 |
+
"bangalore": "metro", "bengaluru": "metro",
|
| 117 |
+
"kolkata": "metro", "calcutta": "metro",
|
| 118 |
+
"chennai": "metro", "madras": "metro",
|
| 119 |
+
"hyderabad": "metro",
|
| 120 |
+
"metro": "metro", "tier 1": "tier1", "tier1": "tier1", "tier-1": "tier1",
|
| 121 |
+
# Tier-2
|
| 122 |
+
"pune": "tier2", "ahmedabad": "tier2", "jaipur": "tier2",
|
| 123 |
+
"lucknow": "tier2", "kanpur": "tier2", "nagpur": "tier2",
|
| 124 |
+
"indore": "tier2", "thane": "tier2", "bhopal": "tier2",
|
| 125 |
+
"visakhapatnam": "tier2", "vizag": "tier2",
|
| 126 |
+
"patna": "tier2", "vadodara": "tier2", "baroda": "tier2",
|
| 127 |
+
"ghaziabad": "tier2", "ludhiana": "tier2", "agra": "tier2",
|
| 128 |
+
"nashik": "tier2", "faridabad": "tier2", "meerut": "tier2",
|
| 129 |
+
"rajkot": "tier2", "varanasi": "tier2", "srinagar": "tier2",
|
| 130 |
+
"aurangabad": "tier2", "amritsar": "tier2", "navi mumbai": "tier2",
|
| 131 |
+
"allahabad": "tier2", "prayagraj": "tier2", "ranchi": "tier2",
|
| 132 |
+
"howrah": "tier2", "coimbatore": "tier2", "jabalpur": "tier2",
|
| 133 |
+
"gwalior": "tier2", "vijayawada": "tier2", "jodhpur": "tier2",
|
| 134 |
+
"raipur": "tier2", "kota": "tier2", "chandigarh": "tier2",
|
| 135 |
+
"guwahati": "tier2", "solapur": "tier2", "hubli": "tier2",
|
| 136 |
+
"mysore": "tier2", "mysuru": "tier2",
|
| 137 |
+
"tier 2": "tier2", "tier2": "tier2", "tier-2": "tier2",
|
| 138 |
+
# Tier-3 buckets (rest)
|
| 139 |
+
"tier 3": "tier3", "tier3": "tier3", "tier-3": "tier3",
|
| 140 |
+
"small town": "tier3", "village": "tier3", "rural": "tier3",
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _extract_location_tier_from_text(text: str) -> Optional[str]:
|
| 145 |
+
"""Best-effort location_tier from a free-form user reply.
|
| 146 |
+
Returns "metro" / "tier1" / "tier2" / "tier3" or None.
|
| 147 |
+
Matches whole tokens / phrases against _LOCATION_TIER_MAP.
|
| 148 |
+
"""
|
| 149 |
+
if not text:
|
| 150 |
+
return None
|
| 151 |
+
s = text.lower()
|
| 152 |
+
# Longest-key-first so "navi mumbai" beats "mumbai".
|
| 153 |
+
for key in sorted(_LOCATION_TIER_MAP.keys(), key=len, reverse=True):
|
| 154 |
+
# Word-boundary match for single-word keys; substring for
|
| 155 |
+
# multi-word keys (which already have natural boundaries).
|
| 156 |
+
if " " in key:
|
| 157 |
+
if key in s:
|
| 158 |
+
return _LOCATION_TIER_MAP[key]
|
| 159 |
+
else:
|
| 160 |
+
if re.search(rf"\b{re.escape(key)}\b", s):
|
| 161 |
+
return _LOCATION_TIER_MAP[key]
|
| 162 |
+
return None
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _extract_income_band_from_text(text: str) -> Optional[str]:
|
| 166 |
+
"""Best-effort income_band from free-form text.
|
| 167 |
+
Delegates to needs_finder._parse_income_band so the canonical
|
| 168 |
+
bucket set (under_5L / 5L-10L / 10L-25L / 25L+) is honored.
|
| 169 |
+
"""
|
| 170 |
+
if not text:
|
| 171 |
+
return None
|
| 172 |
+
try:
|
| 173 |
+
from backend.needs_finder import _parse_income_band
|
| 174 |
+
except Exception:
|
| 175 |
+
return None
|
| 176 |
+
try:
|
| 177 |
+
return _parse_income_band(text)
|
| 178 |
+
except Exception:
|
| 179 |
+
return None
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _parse_user_text_facts(user_text: str) -> Dict[str, Any]:
|
| 183 |
+
"""Run all four identity-fact extractors against user_text. Returns
|
| 184 |
+
a dict of only the fields that successfully parsed. Used by both
|
| 185 |
+
the two-fact recall gate (rehydrate_by_name) and the same-turn
|
| 186 |
+
match-before-merge guard (apply_pending_recall).
|
| 187 |
+
"""
|
| 188 |
+
if not user_text:
|
| 189 |
+
return {}
|
| 190 |
+
out: Dict[str, Any] = {}
|
| 191 |
+
for fld, fn in (
|
| 192 |
+
("age", _extract_age_from_text),
|
| 193 |
+
("dependents", _extract_dependents_from_text),
|
| 194 |
+
("location_tier", _extract_location_tier_from_text),
|
| 195 |
+
("income_band", _extract_income_band_from_text),
|
| 196 |
+
):
|
| 197 |
+
v = fn(user_text)
|
| 198 |
+
if v not in (None, "", []):
|
| 199 |
+
out[fld] = v
|
| 200 |
+
return out
|
| 201 |
+
|
| 202 |
_log = logging.getLogger(__name__)
|
| 203 |
|
| 204 |
|
|
|
|
| 255 |
# known (any turn); this flag stops it re-staging every subsequent
|
| 256 |
# turn and stops a declined recall from being re-offered.
|
| 257 |
recall_probe_done: bool = False
|
| 258 |
+
# ADR-042 follow-up #1 (2026-05-27) β two-fact recall gate. When
|
| 259 |
+
# rehydrate_by_name finds a stored profile under the captured name
|
| 260 |
+
# but the live session has NO identity-fact match (and user_text
|
| 261 |
+
# carried no parseable fact either), it sets this flag instead of
|
| 262 |
+
# staging. The caller (single_brain.py) sees this and DOES NOT set
|
| 263 |
+
# recall_probe_done=True, so the probe retries on subsequent turns
|
| 264 |
+
# as more facts come in via save_profile_field. Reset to False by
|
| 265 |
+
# the caller every retry. Prevents the slug-collision Welcome-Back
|
| 266 |
+
# leak from ever firing on a bare-name intro.
|
| 267 |
+
recall_match_deferred: bool = False
|
| 268 |
|
| 269 |
def _flush(self) -> None:
|
| 270 |
"""No-op. Session state lives only in the in-memory dict; the
|
|
|
|
| 323 |
)
|
| 324 |
|
| 325 |
|
| 326 |
+
def rehydrate_by_name(
|
| 327 |
+
session: SessionState,
|
| 328 |
+
name: str,
|
| 329 |
+
*,
|
| 330 |
+
user_text: str = "",
|
| 331 |
+
) -> bool:
|
| 332 |
"""Cross-session re-entry point β STAGE a name match for confirmation.
|
| 333 |
|
| 334 |
PRIVACY FIX (2026-05-16, audit). Previously this AUTO-MERGED the stored
|
|
|
|
| 339 |
and greeted "Welcome back, <name>!". A fresh, no-cookie session must
|
| 340 |
NEVER inherit another session's profile from a weak/shared key.
|
| 341 |
|
| 342 |
+
PRIVACY HARDENING v4 (2026-05-27, ADR-042 follow-up #1) β TWO-FACT
|
| 343 |
+
GATE. Even with the explicit confirm gate in apply_pending_recall, a
|
| 344 |
+
bare-name "Hi I'm Rohit" would still LEAK staged attrs in the
|
| 345 |
+
Welcome Back prompt (the brain's recall_block was redacted in v1/v2,
|
| 346 |
+
but the very *existence* of a Welcome Back prompt telegraphs that
|
| 347 |
+
SOMEONE under this name has used the bot before). The two-fact gate
|
| 348 |
+
blocks the staging entirely unless at least ONE identity fact β
|
| 349 |
+
drawn from live `session.profile` (prior-turn captures) OR parsed
|
| 350 |
+
from `user_text` (same-turn, via _parse_user_text_facts) β MATCHES
|
| 351 |
+
the stored profile. If a parsed fact CONTRADICTS, staging is also
|
| 352 |
+
refused (no leak to a different person sharing the name slug). If
|
| 353 |
+
no identity facts are available yet (bare name), staging is
|
| 354 |
+
DEFERRED β `session.recall_match_deferred=True` signals the caller
|
| 355 |
+
to retry on a later turn as more facts come in.
|
| 356 |
+
|
| 357 |
Safe design (KI-196 / ADR-041, specced via `pending_profile_recall` but
|
| 358 |
previously never wired): a name match is STAGED on
|
| 359 |
`session.pending_profile_recall`, NOT merged. `session.profile` is left
|
|
|
|
| 367 |
False β always. The stored profile is NEVER auto-applied here, so
|
| 368 |
callers must treat False as "do not flag a returning user
|
| 369 |
/ do not greet Welcome back". Whether a match was *staged*
|
| 370 |
+
is observable via `session.pending_profile_recall`; the
|
| 371 |
+
deferred-retry signal is `session.recall_match_deferred`.
|
| 372 |
|
| 373 |
Failures are logged but never raise β a fresh chat must always proceed.
|
| 374 |
"""
|
|
|
|
| 388 |
if _first and _first.lower() != _stripped.lower():
|
| 389 |
stored = load_profile(_first)
|
| 390 |
if stored is None:
|
| 391 |
+
# No stored profile under this name. Done β no recall
|
| 392 |
+
# opportunity, no deferral needed.
|
| 393 |
+
session.recall_match_deferred = False
|
| 394 |
return False
|
| 395 |
|
| 396 |
+
# βββ TWO-FACT GATE (v4, 2026-05-27) βββββββββββββββββββββββββββ
|
| 397 |
+
# Require at least ONE non-name identity fact to match the
|
| 398 |
+
# stored profile before staging. Sources for the fact:
|
| 399 |
+
# (1) session.profile β already-captured live facts (any
|
| 400 |
+
# prior turn of this same session)
|
| 401 |
+
# (2) user_text β same-turn parse via _parse_user_text_facts
|
| 402 |
+
# Any CONTRADICTION fails closed (no stage). No fact available
|
| 403 |
+
# β defer (set session.recall_match_deferred=True so the
|
| 404 |
+
# single_brain caller does NOT mark recall_probe_done, and the
|
| 405 |
+
# probe retries next turn as more facts come in).
|
| 406 |
+
same_turn_facts = _parse_user_text_facts(user_text)
|
| 407 |
+
matched_fact = False
|
| 408 |
+
contradicted_fact = False
|
| 409 |
+
for fld in ("age", "dependents", "location_tier", "income_band"):
|
| 410 |
+
stored_v = getattr(stored, fld, None)
|
| 411 |
+
if stored_v in (None, "", []):
|
| 412 |
+
continue
|
| 413 |
+
# Source 1: prior-turn live capture
|
| 414 |
+
live_v = getattr(session.profile, fld, None)
|
| 415 |
+
if live_v not in (None, "", []):
|
| 416 |
+
if fld == "age":
|
| 417 |
+
try:
|
| 418 |
+
if int(live_v) == int(stored_v):
|
| 419 |
+
matched_fact = True
|
| 420 |
+
else:
|
| 421 |
+
contradicted_fact = True
|
| 422 |
+
except Exception:
|
| 423 |
+
pass
|
| 424 |
+
else:
|
| 425 |
+
if str(live_v).strip().lower() == str(stored_v).strip().lower():
|
| 426 |
+
matched_fact = True
|
| 427 |
+
else:
|
| 428 |
+
contradicted_fact = True
|
| 429 |
+
continue
|
| 430 |
+
# Source 2: same-turn parse from user_text
|
| 431 |
+
user_v = same_turn_facts.get(fld)
|
| 432 |
+
if user_v not in (None, "", []):
|
| 433 |
+
if fld == "age":
|
| 434 |
+
try:
|
| 435 |
+
if int(user_v) == int(stored_v):
|
| 436 |
+
matched_fact = True
|
| 437 |
+
else:
|
| 438 |
+
contradicted_fact = True
|
| 439 |
+
except Exception:
|
| 440 |
+
pass
|
| 441 |
+
else:
|
| 442 |
+
if str(user_v).strip().lower() == str(stored_v).strip().lower():
|
| 443 |
+
matched_fact = True
|
| 444 |
+
else:
|
| 445 |
+
contradicted_fact = True
|
| 446 |
+
|
| 447 |
+
if contradicted_fact:
|
| 448 |
+
# Any contradicting identity fact β fail-closed. No stage.
|
| 449 |
+
# Mark probe done so we don't try again β the stored
|
| 450 |
+
# profile is for a DIFFERENT person sharing this name slug.
|
| 451 |
+
session.recall_match_deferred = False
|
| 452 |
+
_log.info(
|
| 453 |
+
"rehydrate_by_name: identity-fact contradiction for "
|
| 454 |
+
"name=%r β fail-closed, no stage", name,
|
| 455 |
+
)
|
| 456 |
+
return False
|
| 457 |
+
if not matched_fact:
|
| 458 |
+
# No fact to confirm a match yet. Defer staging until a
|
| 459 |
+
# later turn has captured a fact via save_profile_field.
|
| 460 |
+
session.recall_match_deferred = True
|
| 461 |
+
session.last_touched = time.time()
|
| 462 |
+
return False
|
| 463 |
+
|
| 464 |
+
# βββ At this point: stored exists AND β₯1 fact matches. Stage. β
|
| 465 |
+
|
| 466 |
# Build a non-PII-leaking identity summary so the brain can ask
|
| 467 |
# "are you <name>?" without putting anything on the live profile.
|
| 468 |
summary: Dict[str, Any] = {}
|
|
|
|
| 486 |
"stored_fields": staged_fields,
|
| 487 |
"staged_at": time.time(),
|
| 488 |
}
|
| 489 |
+
session.recall_match_deferred = False
|
| 490 |
session.last_touched = time.time()
|
| 491 |
# Deliberately False: nothing merged, no Welcome-back greeting.
|
| 492 |
return False
|
|
|
|
| 565 |
fld, live_v, staged_v,
|
| 566 |
)
|
| 567 |
return False
|
| 568 |
+
# PRIVACY HARDENING v2 (2026-05-27) β same-turn contradiction guard.
|
| 569 |
# _affirm_or_deny + apply_pending_recall fire BEFORE the LLM iteration
|
| 570 |
# that runs save_profile_field, so a user reply like "Yes I'm 35"
|
| 571 |
# against a staged Rohit at age=29 would otherwise slip through the
|
| 572 |
+
# prior-turn guard (live.<fld>=None at this point) and merge the
|
| 573 |
+
# wrong profile.
|
| 574 |
+
#
|
| 575 |
+
# PRIVACY HARDENING v3 (2026-05-27, ADR-042 follow-up #2): extended
|
| 576 |
+
# from age-only to all four decision-critical identity facts
|
| 577 |
+
# (age / dependents / location_tier / income_band) via
|
| 578 |
+
# _parse_user_text_facts. Mis-parses return None and cost nothing.
|
| 579 |
if user_text:
|
| 580 |
+
same_turn_facts = _parse_user_text_facts(user_text)
|
| 581 |
+
for fld, user_v in same_turn_facts.items():
|
| 582 |
+
staged_v = stored_fields.get(fld)
|
| 583 |
+
if staged_v in (None, "", []):
|
| 584 |
+
continue
|
| 585 |
+
# Normalise. Age is the only numeric; the rest are strings.
|
| 586 |
+
if fld == "age":
|
| 587 |
+
try:
|
| 588 |
+
staged_norm = int(staged_v)
|
| 589 |
+
user_norm = int(user_v)
|
| 590 |
+
except Exception:
|
| 591 |
+
continue
|
| 592 |
+
if staged_norm != user_norm:
|
| 593 |
+
_log.info(
|
| 594 |
+
"apply_pending_recall: same-turn age contradiction "
|
| 595 |
+
"(user_text age=%d, staged.age=%s) β discarding "
|
| 596 |
+
"staged recall, no merge",
|
| 597 |
+
user_norm, staged_v,
|
| 598 |
+
)
|
| 599 |
+
return False
|
| 600 |
+
else:
|
| 601 |
+
if str(user_v).strip().lower() != str(staged_v).strip().lower():
|
| 602 |
+
_log.info(
|
| 603 |
+
"apply_pending_recall: same-turn %s contradiction "
|
| 604 |
+
"(user_text=%r, staged=%r) β discarding staged "
|
| 605 |
+
"recall, no merge",
|
| 606 |
+
fld, user_v, staged_v,
|
| 607 |
+
)
|
| 608 |
+
return False
|
| 609 |
for fld, new in stored_fields.items():
|
| 610 |
try:
|
| 611 |
if fld not in Profile.__dataclass_fields__:
|
|
@@ -1997,14 +1997,28 @@ async def handle_turn(
|
|
| 1997 |
or (extract_potential_name(user_text or "") or "")
|
| 1998 |
)
|
| 1999 |
if _nm:
|
| 2000 |
-
# One-shot: never re-probe (the captured name won't
|
| 2001 |
-
# change) and never re-stage every subsequent turn.
|
| 2002 |
-
session.recall_probe_done = True
|
| 2003 |
# Stages session.pending_profile_recall iff a stored
|
| 2004 |
-
# profile for this name exists
|
| 2005 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2006 |
# Still privacy-safe: STAGE only; explicit confirm merges.
|
| 2007 |
-
try_recall_by_name(session, _nm)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2008 |
_pending_recall = getattr(
|
| 2009 |
session, "pending_profile_recall", None
|
| 2010 |
)
|
|
|
|
| 1997 |
or (extract_potential_name(user_text or "") or "")
|
| 1998 |
)
|
| 1999 |
if _nm:
|
|
|
|
|
|
|
|
|
|
| 2000 |
# Stages session.pending_profile_recall iff a stored
|
| 2001 |
+
# profile for this name exists AND the two-fact gate
|
| 2002 |
+
# (ADR-042 follow-up #1) is satisfied β i.e., at least
|
| 2003 |
+
# one identity fact (age / dependents / location /
|
| 2004 |
+
# income) MATCHES between stored and the live/parsed
|
| 2005 |
+
# user state. No match yet β session.recall_match_
|
| 2006 |
+
# deferred=True and we DON'T flip recall_probe_done so
|
| 2007 |
+
# the probe retries next turn when more facts come in.
|
| 2008 |
# Still privacy-safe: STAGE only; explicit confirm merges.
|
| 2009 |
+
try_recall_by_name(session, _nm, user_text=user_text)
|
| 2010 |
+
_deferred = bool(
|
| 2011 |
+
getattr(session, "recall_match_deferred", False)
|
| 2012 |
+
)
|
| 2013 |
+
if not _deferred:
|
| 2014 |
+
# Probe was conclusive (staged / contradicted / no
|
| 2015 |
+
# stored profile under this name). Mark done β name
|
| 2016 |
+
# won't change, no point re-probing.
|
| 2017 |
+
session.recall_probe_done = True
|
| 2018 |
+
# Else: leave recall_probe_done as-is (False) so the
|
| 2019 |
+
# next turn's gate re-enters this branch after the LLM
|
| 2020 |
+
# has captured another identity fact via
|
| 2021 |
+
# save_profile_field.
|
| 2022 |
_pending_recall = getattr(
|
| 2023 |
session, "pending_profile_recall", None
|
| 2024 |
)
|