Spaces:
Sleeping
docs: KI-101..KI-107 — audit + CLAUDE.md + ADR sync
Browse filesDocument the seven KIs landed today across the production-readiness register,
project memory, and affected ADRs:
- KI-101 (66eb4ed) — drop 6 function-local `import logging` lines from
orchestrator.py; module-level import is the sole binding so the asyncio
wait_for TimeoutError branch no longer raises UnboundLocalError.
- KI-102 (4bb8da0) — profile RAG cross-session isolation. session_id stamped
on every chunk; main retrieve() excludes doc_type=profile; per-session
lookup triple-checks meta.session_id == session_id in Python; legacy
chunks without session_id fail-closed. ADR-022 extended with a
session-isolation subsection.
- KI-103 (8ef5c43) — _canonical_fallback no_trailer loop-breaker. New
session._ff_failed_attempts + _ff_skipped_slots; after 2 failed attempts
on the same slot, mark skipped and advance.
- KI-104 (407f2a1) — voice_format.tts_preprocess strips chain-of-thought
leakage: <think> blocks, **Reasoning:** labels, [INTERNAL] blocks,
sentence-anchored CoT starters; emergency fallback acknowledger if the
whole reply is CoT.
- KI-105 (8a58fa1) — recommendation closer wired. Explicit closer phrases
("show me the top 3", "rank", "pitch me", "compare X vs Y") classified
as recommendation/comparison BEFORE FACT_FIND_TRIGGERS check; persona
prompt gets RECOMMENDATION_CLOSER_ADDENDUM with a strict 3-policy
ranked-shortlist contract. ADR-008 extended with closer-mode subsection.
- KI-106 (565bf31) — graceful TimeoutError + Exception on /api/chat.
handle_turn wrapped in asyncio.wait_for(45s); both return HTTP 200 with
source="graceful_timeout"/"graceful_exception" and an in-character
recovery sentence instead of HTTP 500.
- KI-107 (3a9a14f) — _safe_collection_get helper for Chroma. Wraps every
collection.get(ids=...) and collection.get(where=...) call in
profile_rag.py; returns None on miss with WARNING log instead of
raising. Closes the KI-102 per-session lookup raising on never-existed
sessions on HF Space.
Files touched: 80-audit/ENTERPRISE_AUDIT.md (7 new rows), CLAUDE.md
(7 new bullets in LLM-stack section), ADR-008 (closer-mode subsection),
ADR-022 (session-isolation subsection), backend/README.md (voice_format
+ profile_rag row refreshes).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
@@ -51,3 +51,20 @@ The choice has direct legal, ethical, and commercial consequences.
|
|
| 51 |
## Revisit at scale
|
| 52 |
|
| 53 |
Same. Add A/B mode for deploying partners with strict guard-rails (no mis-selling phrases, persona transparency to the user).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
## Revisit at scale
|
| 52 |
|
| 53 |
Same. Add A/B mode for deploying partners with strict guard-rails (no mis-selling phrases, persona transparency to the user).
|
| 54 |
+
|
| 55 |
+
## Closer-mode subsection (KI-105, `8a58fa1`, 2026-05-15)
|
| 56 |
+
|
| 57 |
+
The consultative persona above is the steady-state default. When the user issues an **explicit closer phrase** the persona is augmented (not replaced) with a strict ranked-shortlist contract.
|
| 58 |
+
|
| 59 |
+
**Trigger.** `classify_intent()` in `backend/orchestrator.py` matches the user message against `RECOMMENDATION_CLOSER_PHRASES` (frozenset, word-boundary regex). Matched phrases include `"show me the top 3"`, `"rank"`, `"pitch me"`, `"which is best for me"`, `"compare X vs Y"`. The closer-phrase check fires BEFORE the `FACT_FIND_TRIGGERS` check, so a fully-fact-found user can never get bounced back into fact-find by a closer phrase that contains words like `"me"`.
|
| 60 |
+
|
| 61 |
+
**Persona augmentation.** The base `ADVISOR_SYSTEM_PROMPT_V1` is concatenated with `RECOMMENDATION_CLOSER_ADDENDUM` for the closer turn only:
|
| 62 |
+
|
| 63 |
+
1. Output **exactly 3 ranked policies** — no more, no less.
|
| 64 |
+
2. One-line rationale per pick **tied to the user's profile** (age / dependents / income_band / city_tier / pre-existing conditions).
|
| 65 |
+
3. End with the **3-policy sum + IRDAI disclaimer** ("confirm policy details with the insurer before purchase; premium quoted is illustrative").
|
| 66 |
+
4. **No hedging language.** "You might want to consider..." / "It depends on..." / "Personal preference matters..." are explicitly forbidden in the addendum. The user asked for a ranked shortlist; deliver a ranked shortlist.
|
| 67 |
+
|
| 68 |
+
The core persona rules from the section above (grounded answers, citation grammar, no medical advice, no scare tactics, no final transactional advice — confirm with insurer) all still apply. The closer addendum is additive, not a replacement.
|
| 69 |
+
|
| 70 |
+
**Rationale.** Without KI-105, a user who has completed fact-find and then says "OK, now pitch me the top 3" got either (a) re-routed into fact-find (because "me" sat inside `FACT_FIND_TRIGGERS` before KI-023's word-boundary fix), or (b) a hedge-heavy 6-bullet exploration of options without a clear ranked recommendation. Both UX failures — the bot needs to be able to close the conversation when the user explicitly asks it to, while staying inside the consultative guard-rails (still cites, still discloses, still refuses transactional advice).
|
|
@@ -90,3 +90,17 @@ backend/profile_extractor.py
|
|
| 90 |
|
| 91 |
- Add a confidence score to the extractor output; only auto-apply at high confidence, flag medium-confidence updates for user confirmation.
|
| 92 |
- Run the extractor in parallel with retrieval+brain to hide the latency.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
- Add a confidence score to the extractor output; only auto-apply at high confidence, flag medium-confidence updates for user confirmation.
|
| 92 |
- Run the extractor in parallel with retrieval+brain to hide the latency.
|
| 93 |
+
|
| 94 |
+
## Session isolation for profile RAG (KI-102, `4bb8da0`, 2026-05-15)
|
| 95 |
+
|
| 96 |
+
The extractor above writes profile updates into `session.profile`. The profile is then embedded as a Chroma chunk via `backend/profile_rag.py::upsert_profile_chunk(profile, session_id)` so the brain sees the user's profile alongside policy chunks during retrieval. Pre-KI-102 the chunk was stored without a `session_id` tag, which meant Chroma's nearest-neighbour retrieval could return User A's profile chunk when User B's session ran retrieval — a cross-session PII leak (age / dependents / health conditions).
|
| 97 |
+
|
| 98 |
+
**Three-layer fix in `backend/profile_rag.py`:**
|
| 99 |
+
|
| 100 |
+
1. **Metadata stamp.** `upsert_profile_chunk(profile, session_id)` writes `metadata={"doc_type": "profile", "session_id": session_id, ...}` on every chunk. Sessions written before KI-102 lack `session_id` and are treated as legacy (see layer 3).
|
| 101 |
+
2. **Exclude from main retrieval.** The general `retrieve()` pass adds `where={"doc_type": {"$ne": "profile"}}` so profile docs never enter the general policy / regulatory retrieval pool. Profile chunks are read ONLY by the dedicated per-session lookup.
|
| 102 |
+
3. **Per-session lookup triple-checks `session_id`.** `_get_profile_chunk_for_session(session_id)` pulls with `where={"$and": [{"doc_type": "profile"}, {"session_id": session_id}]}` AND re-verifies `result.metadata["session_id"] == session_id` in Python after Chroma returns. Defence-in-depth against a Chroma where-clause bug. Legacy chunks (no `session_id` in metadata) fail the Python check and are silently refused (fail-closed, not fail-open).
|
| 103 |
+
|
| 104 |
+
**Companion: KI-107 `_safe_collection_get`.** The per-session lookup `collection.get(where=...)` raised on never-existed sessions on the HF Space build (Chroma version-dependent behaviour). KI-107 wraps every `.get()` call in `_safe_collection_get` which catches `Exception`, logs a WARNING, and returns `None`. A `None` return is treated identically to "session_id mismatch" — both fail-closed, brain runs without profile context that turn.
|
| 105 |
+
|
| 106 |
+
**Privacy invariant.** Session B can NEVER read Session A's profile chunk, regardless of embedding similarity, where-clause behaviour, or never-existed-session edge cases.
|
|
@@ -279,6 +279,13 @@ The full eval was sending **every** QA question to `needs_finder`. Sample bot an
|
|
| 279 |
| **KI-091** | **`9813994`** | **Skip `profile_extractor` + `faithfulness` judge on fact-find turns (saturated-chain hang + mid-session field-clear).** Pre-KI-091 every fact-find turn ran two dependent post-brain LLM chains: (a) `extract_profile_updates` (LLM re-reads the user message to pull profile fields), and (b) `check_faithfulness` (judge LLM grades the bot's reply against retrieved context). Both chains were credit-exhausted on the steady-state primary, hung the turn for 20+ seconds on `asyncio.wait_for`, and — critically — the extractor periodically returned `{"name": null}` for utterances that had nothing to do with name, causing `session.update_profile_field("name", None)` to wipe the captured value mid-session. `next_question(profile)` then re-asked the name slot the user had already answered. KI-091 gates both chains behind an `intent == "fact_find"` short-circuit in `backend/orchestrator.py` so fact-find turns skip them entirely — the fact-find brain (KI-070) already extracts fields natively from its `<FF>` JSON tail, and faithfulness scoring is meaningless on a turn whose reply is "what's your annual income?". QA-mode turns (recommendation / comparison / clarification) still run both chains as before. Live verify: name re-ask loop eliminated; fact-find turn latency drops from p95 28s → p95 6-8s. |
|
| 280 |
| **KI-094** | **`f068094`** | **Defensive `None`-guard in extractor merge — extractor cannot clear a filled profile field even when it runs.** Belt-and-braces companion to KI-091. On QA-mode turns the `extract_profile_updates` chain still runs (it's the right behaviour: a user can mention "I'm now 35" mid-recommendation and the profile should update). But the extractor under load periodically returns `{"name": null, "age": null, "dependents": null}` — semantically "nothing to extract" but the merge loop was writing every key including nulls back into the session, wiping filled fields. Added `if new_value in (None, "", []): continue` guard at the top of the extracted-fields loop in `backend/orchestrator.py` so the merge step ONLY overwrites a profile field when the extractor returns a real value. Null / empty-string / empty-list returns are now no-ops, regardless of which fields they target. Closes the same root-cause hole as KI-091 (LLM returning nulls clears state) at a second layer — extractor running and returning nulls is now safe even when KI-091's intent gate doesn't fire. Together: KI-091 prevents the extractor from running on fact-find turns at all; KI-094 ensures that if it DOES run (QA-mode turn), null returns can't wipe filled fields like `name`. |
|
| 281 |
| **KI-097** | (pending) | **Remove IP allowlist from admin — password-only gate.** Removed `ADMIN_IP_ALLOWLIST` env, deleted `_ip_allowed()`, simplified `_check_admin` to password-only, 404→401, ADR-023 superseded. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
| D-001 | (multi) | ChromaDB HNSW bloat 3-layer prevention (ADR-029) |
|
| 283 |
| D-002 | (LaunchAgent edit) | Three silently-failing LaunchAgent scripts fixed |
|
| 284 |
| D-009 | `bcb7079` | Removed `tmp_*.py` debug files from repo root |
|
|
@@ -329,4 +336,4 @@ This audit so far covers items 1-3, 5 (in progress), and 6. Items 7-10 require a
|
|
| 329 |
|
| 330 |
---
|
| 331 |
|
| 332 |
-
*This file regenerates as new evidence lands. Last updated: 2026-05-
|
|
|
|
| 279 |
| **KI-091** | **`9813994`** | **Skip `profile_extractor` + `faithfulness` judge on fact-find turns (saturated-chain hang + mid-session field-clear).** Pre-KI-091 every fact-find turn ran two dependent post-brain LLM chains: (a) `extract_profile_updates` (LLM re-reads the user message to pull profile fields), and (b) `check_faithfulness` (judge LLM grades the bot's reply against retrieved context). Both chains were credit-exhausted on the steady-state primary, hung the turn for 20+ seconds on `asyncio.wait_for`, and — critically — the extractor periodically returned `{"name": null}` for utterances that had nothing to do with name, causing `session.update_profile_field("name", None)` to wipe the captured value mid-session. `next_question(profile)` then re-asked the name slot the user had already answered. KI-091 gates both chains behind an `intent == "fact_find"` short-circuit in `backend/orchestrator.py` so fact-find turns skip them entirely — the fact-find brain (KI-070) already extracts fields natively from its `<FF>` JSON tail, and faithfulness scoring is meaningless on a turn whose reply is "what's your annual income?". QA-mode turns (recommendation / comparison / clarification) still run both chains as before. Live verify: name re-ask loop eliminated; fact-find turn latency drops from p95 28s → p95 6-8s. |
|
| 280 |
| **KI-094** | **`f068094`** | **Defensive `None`-guard in extractor merge — extractor cannot clear a filled profile field even when it runs.** Belt-and-braces companion to KI-091. On QA-mode turns the `extract_profile_updates` chain still runs (it's the right behaviour: a user can mention "I'm now 35" mid-recommendation and the profile should update). But the extractor under load periodically returns `{"name": null, "age": null, "dependents": null}` — semantically "nothing to extract" but the merge loop was writing every key including nulls back into the session, wiping filled fields. Added `if new_value in (None, "", []): continue` guard at the top of the extracted-fields loop in `backend/orchestrator.py` so the merge step ONLY overwrites a profile field when the extractor returns a real value. Null / empty-string / empty-list returns are now no-ops, regardless of which fields they target. Closes the same root-cause hole as KI-091 (LLM returning nulls clears state) at a second layer — extractor running and returning nulls is now safe even when KI-091's intent gate doesn't fire. Together: KI-091 prevents the extractor from running on fact-find turns at all; KI-094 ensures that if it DOES run (QA-mode turn), null returns can't wipe filled fields like `name`. |
|
| 281 |
| **KI-097** | (pending) | **Remove IP allowlist from admin — password-only gate.** Removed `ADMIN_IP_ALLOWLIST` env, deleted `_ip_allowed()`, simplified `_check_admin` to password-only, 404→401, ADR-023 superseded. |
|
| 282 |
+
| **KI-101** | **`66eb4ed`** | **Drop 6 function-local `import logging` lines from `backend/orchestrator.py` — fixes `UnboundLocalError` when the `asyncio.wait_for` `TimeoutError` branch fires before reaching the inline `import`.** Pre-KI-101 the orchestrator had a module-level `import logging` at the top of the file AND six redundant `import logging` lines inside individual `try` / `except` branches deeper in `handle_turn()`. Python's scoping rule promotes any name assigned (including `import name`) anywhere in a function to a function-local — so the moment the parser saw any of the inline `import logging` lines, `logging` became local to the enclosing function. If a `TimeoutError` from `asyncio.wait_for(...)` fired BEFORE control reached the inline import, the `logger = logging.getLogger(__name__)` line in the `except` handler raised `UnboundLocalError: local variable 'logging' referenced before assignment` — masking the actual TimeoutError and surfacing a confusing trace to the user. Removed all 6 inline imports; module-level import is the sole binding and is unambiguously a free variable in every nested scope. No behavioural change beyond eliminating the spurious traceback. |
|
| 283 |
+
| **KI-102** | **`4bb8da0`** | **Profile RAG cross-session leak — `upsert_profile_chunk` stamps `session_id` metadata, `retrieve` excludes profile docs from the main pass + per-session lookup triple-checks `meta.session_id == session_id`; legacy chunks without `session_id` silently refused (fail-closed).** Pre-KI-102 the profile RAG layer wrote one Chroma chunk per session-profile but didn't tag it with `session_id`, so when User B's session ran retrieval Chroma could return User A's profile chunk if its embedding was a near neighbour — leaking PII (age / dependents / health conditions) across sessions. Three changes in `backend/profile_rag.py`. (1) `upsert_profile_chunk(profile, session_id)` now stamps `metadata={"doc_type": "profile", "session_id": session_id, ...}` on every chunk. (2) Main `retrieve()` pass excludes `doc_type == "profile"` via `where={"doc_type": {"$ne": "profile"}}` so profile docs never enter the general retrieval pool. (3) Separate `_get_profile_chunk_for_session(session_id)` lookup pulls only the current session's profile by `where={"$and": [{"doc_type": "profile"}, {"session_id": session_id}]}` AND triple-checks `result.metadata["session_id"] == session_id` in Python before returning — defence-in-depth against a Chroma where-clause bug. Legacy chunks written pre-KI-102 (no `session_id` metadata) are silently refused by the lookup (fail-closed, not fail-open). Privacy invariant: a session can NEVER read another session's profile chunk, regardless of embedding similarity. ADR-022 extended with a session-isolation subsection. |
|
| 284 |
+
| **KI-103** | **`8ef5c43`** | **`_canonical_fallback` no_trailer loop-breaker — after 2 failed attempts on the same slot, mark skipped + advance via `session._ff_failed_attempts` + `_ff_skipped_slots`.** Pre-KI-103 if the brain returned `fallback:no_trailer` (KI-090 parser also failed) on the same slot 3+ turns in a row, the canonical fallback would re-ask the same canonical question forever — the slot was unfilled, so `next_question(slot_id)` kept selecting it, brain kept failing, user got an infinite identical-question loop. Added two session-level counters: `session._ff_failed_attempts[slot_id]` increments every time the brain bails on a given slot; `session._ff_skipped_slots: set[str]` records slots the canonical fallback has given up on. After 2 consecutive failed attempts on the same slot, `_canonical_fallback` marks the slot skipped and `next_question()` excludes it from selection, advancing to the next unfilled slot. The skipped slot is still flagged in the final profile completeness check so the user can fill it via the admin panel later. Caps the worst-case wedge at 2 turns × `MAX_SLOTS = 9` ≈ 18 turns to escape fact-find, instead of unbounded. |
|
| 285 |
+
| **KI-104** | **`407f2a1`** | **CoT / instruction-echo strip in `backend/voice_format.py::tts_preprocess` — kills `<think>` blocks, `**Reasoning:**` labels, `[INTERNAL]` blocks, sentence-anchored CoT starters; emergency fallback when the whole reply is CoT.** Real LLMs (Qwen 3-Next under load, Nemotron Nano with low temperature) occasionally leak chain-of-thought into the prose: `<think>The user is asking about PED waiting periods. I should check...</think>` or `**Reasoning:** First I need to figure out... **Answer:** The waiting period is 24 months.` Pre-KI-104 those leaks went straight to TTS and the user heard Sarvam read out the bot's internal monologue. New strip pipeline: (1) regex-strip `<think>...</think>` (multi-line, non-greedy); (2) regex-strip `**Reasoning:** ... **Answer:**` and `**Thought:** ... **Final:**` patterns; (3) regex-strip `[INTERNAL] ... [/INTERNAL]`; (4) sentence-level scrub of starters like `"Let me think about that."`, `"First, I'll consider..."`, `"Step 1: ..."`, `"To answer this, I need to..."` (anchored at sentence boundary so they don't kill legitimate prose mid-paragraph); (5) **emergency fallback** — if after all strips the cleaned reply is empty / < 10 chars / still entirely CoT-shaped, return a generic acknowledger ("Let me check that and get back to you.") instead of TTS-ing an empty string or a fragment. Inline tests: 12/12 pass across the 5 strip patterns + emergency-fallback case. |
|
| 286 |
+
| **KI-105** | **`8a58fa1`** | **Recommendation closer wired — explicit closer phrases classified as recommendation/comparison BEFORE `FACT_FIND_TRIGGERS` check; persona prompt gets `RECOMMENDATION_CLOSER_ADDENDUM` with a strict 3-policy ranked-shortlist contract.** Pre-KI-105 a fully-fact-found user saying "Now show me the top 3 policies for me" could still get bounced back into fact-find because the literal word "me" sat inside `FACT_FIND_TRIGGERS` (substring match was fixed by KI-023 word-boundary regex, but the closer-phrase intent classification was missing). New `RECOMMENDATION_CLOSER_PHRASES` frozenset in `backend/orchestrator.py` covers `"show me the top 3"`, `"rank"`, `"pitch me"`, `"compare X vs Y"`, `"which is best for me"`, etc. `classify_intent()` checks closer phrases FIRST — if matched, intent is forced to `"recommendation"` (or `"comparison"` for explicit X-vs-Y patterns) and the `FACT_FIND_TRIGGERS` check is skipped. Persona prompt for these turns is augmented with `RECOMMENDATION_CLOSER_ADDENDUM` — a strict contract requiring: (a) exactly 3 ranked policies, (b) one-line rationale per pick tied to the user's profile, (c) the 3-policy sum / IRDAI disclaimer at the end, (d) no hedging like "you might consider...". ADR-008 extended with a closer-mode subsection (the consultative persona retains its core rules; the closer addendum only kicks in when the user explicitly asks for a ranked shortlist). |
|
| 287 |
+
| **KI-106** | **`565bf31`** | **Graceful `TimeoutError` + `Exception` handling on `/api/chat` — wrapped in `asyncio.wait_for(45s)` + explicit catch; both return HTTP 200 with graceful phrasing instead of 500.** Pre-KI-106 if `handle_turn()` raised any unhandled exception OR exceeded an implicit wall-clock budget, FastAPI's default handler emitted HTTP 500 with a generic JSON error body. The frontend treated 500 as a hard error and surfaced "Something went wrong" to the user — a much worse UX than a graceful in-character bot response that admits the bot is overloaded. New wrap in `backend/main.py::chat()` puts `handle_turn(...)` inside `asyncio.wait_for(coro, timeout=45.0)` with explicit `except asyncio.TimeoutError` and a broad `except Exception` after that. Both return HTTP 200 with `ChatResponse(reply="I'm having trouble responding right now — could you try that again in a moment?", source="graceful_timeout"|"graceful_exception", ...)` so the frontend renders a normal bot bubble and TTS plays the recovery sentence. The 45s budget is the explicit ceiling that bounds the orchestrator's internal nested budgets (brain 25s + escalation 15s + extractor 5s headroom). Internal `logger.exception(...)` still captures the full traceback for the admin tab so silent failures don't hide bugs. |
|
| 288 |
+
| **KI-107** | **`3a9a14f`** | **`_safe_collection_get` helper for Chroma — catches exceptions on `collection.get(ids=[...])` (especially the KI-102 per-session profile lookup for never-existed sessions); returns `None` on miss with a WARNING log.** Pre-KI-107 the new KI-102 `_get_profile_chunk_for_session(session_id)` lookup called `collection.get(where={"$and": [...]})` directly and could raise on a never-existed session (Chroma's behaviour varies by version — some raise `ValueError`, some return `{"ids": []}`, the HF Space build was raising). The raise propagated up through `retrieve()` into `handle_turn()` and KI-106 caught it as a graceful exception, but the user got the recovery sentence instead of a normal reply when really there was just no profile chunk yet. New `_safe_collection_get(collection, **kwargs)` helper in `backend/profile_rag.py` wraps the `.get()` call in a `try / except Exception`, logs `logger.warning("profile_rag: collection.get miss for session=%s: %s", session_id, e)` on failure, and returns `None` so callers can short-circuit ("no profile chunk for this session yet — proceed without profile context") instead of raising. Applied at every `collection.get(ids=[...])` and `collection.get(where=...)` call site in `profile_rag.py` (3 sites total). The KI-102 triple-check semantics are preserved: a `None` return means "no chunk found" which is treated the same as "chunk found but `session_id` doesn't match" — both fail-closed. |
|
| 289 |
| D-001 | (multi) | ChromaDB HNSW bloat 3-layer prevention (ADR-029) |
|
| 290 |
| D-002 | (LaunchAgent edit) | Three silently-failing LaunchAgent scripts fixed |
|
| 291 |
| D-009 | `bcb7079` | Removed `tmp_*.py` debug files from repo root |
|
|
|
|
| 336 |
|
| 337 |
---
|
| 338 |
|
| 339 |
+
*This file regenerates as new evidence lands. Last updated: 2026-05-15 (KI-101..KI-107 landed).*
|
|
@@ -37,6 +37,13 @@ Every LLM role is a `NimChainLLM` candidate pool, NOT a hardcoded single model.
|
|
| 37 |
- **Skip `profile_extractor` + faithfulness judge on fact-find turns (KI-091, `9813994`).** Both chains were credit-exhausted on the steady-state primary, hung fact-find turns for 20+s, and the extractor periodically returned `{"name": null}` which wrote into `session.update_profile_field` and wiped the captured name mid-session — causing `next_question` to re-ask the name slot the user had already answered. Orchestrator now short-circuits both chains behind `intent == "fact_find"`; the fact-find brain (KI-070) extracts fields natively from its `<FF>` JSON tail, and faithfulness scoring is meaningless on "what's your annual income?". QA-mode turns still run both chains. Live: name re-ask loop gone; fact-find p95 28s → 6-8s.
|
| 38 |
- **Defensive `None`-guard in extractor merge (KI-094, `f068094`).** Belt-and-braces companion to KI-091. On QA-mode turns the extractor still runs (correct: "I'm now 35" mid-recommendation should update the profile), but under load it periodically returns `{"name": null, "age": null, ...}` and the merge loop was writing every key including nulls back into the session. Added `if new_value in (None, "", []): continue` at the top of the extracted-fields loop in `backend/orchestrator.py` — null / empty-string / empty-list returns are now no-ops. Closes the same root cause (LLM-returned nulls wiping state) at a second layer; KI-091 prevents the extractor from running on fact-find turns at all, KI-094 makes it safe even when it does run.
|
| 39 |
- **Remove IP allowlist from admin — password-only gate (KI-097, pending).** Dropped `ADMIN_IP_ALLOWLIST` env + `_ip_allowed()` from `backend/admin.py`; `_check_admin` is now password-only against `X-Admin-Password` → `ADMIN_PASSWORD` env. Backend returns 401 Unauthorized (previously 404-to-hide). Frontend admin panel is always visible; password unlocks the live data. ADR-023 superseded — IP gating added zero security beyond a strong password and locked the operator out whenever the home IP changed.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
- **Chain budgets:** brain 20s × 35s total, fast-brain 12s × 22s total, judge 30s × 75s total. With KI-080 only PRIMARY + BACKUP consume budget in the common case — leaves headroom for KI-079 escalation. KI-084 per-phase httpx timeouts are nested inside these budgets.
|
| 41 |
- **STT/TTS/Translator** = Sarvam (Saarika v2.5 / Bulbul v2 / Sarvam-M). **Embeddings** = local BGE-small-en-v1.5.
|
| 42 |
- **Provider keys.** `NVIDIA_NIM_API_KEY` + `GROQ_API_KEY` + `OPENROUTER_API_KEY` required in `.env` (local) and HF Space environment (production — KI-081).
|
|
@@ -122,4 +129,4 @@ Three independent safety layers against ChromaDB HNSW bloat:
|
|
| 122 |
|
| 123 |
---
|
| 124 |
|
| 125 |
-
*Last reviewed 2026-05-
|
|
|
|
| 37 |
- **Skip `profile_extractor` + faithfulness judge on fact-find turns (KI-091, `9813994`).** Both chains were credit-exhausted on the steady-state primary, hung fact-find turns for 20+s, and the extractor periodically returned `{"name": null}` which wrote into `session.update_profile_field` and wiped the captured name mid-session — causing `next_question` to re-ask the name slot the user had already answered. Orchestrator now short-circuits both chains behind `intent == "fact_find"`; the fact-find brain (KI-070) extracts fields natively from its `<FF>` JSON tail, and faithfulness scoring is meaningless on "what's your annual income?". QA-mode turns still run both chains. Live: name re-ask loop gone; fact-find p95 28s → 6-8s.
|
| 38 |
- **Defensive `None`-guard in extractor merge (KI-094, `f068094`).** Belt-and-braces companion to KI-091. On QA-mode turns the extractor still runs (correct: "I'm now 35" mid-recommendation should update the profile), but under load it periodically returns `{"name": null, "age": null, ...}` and the merge loop was writing every key including nulls back into the session. Added `if new_value in (None, "", []): continue` at the top of the extracted-fields loop in `backend/orchestrator.py` — null / empty-string / empty-list returns are now no-ops. Closes the same root cause (LLM-returned nulls wiping state) at a second layer; KI-091 prevents the extractor from running on fact-find turns at all, KI-094 makes it safe even when it does run.
|
| 39 |
- **Remove IP allowlist from admin — password-only gate (KI-097, pending).** Dropped `ADMIN_IP_ALLOWLIST` env + `_ip_allowed()` from `backend/admin.py`; `_check_admin` is now password-only against `X-Admin-Password` → `ADMIN_PASSWORD` env. Backend returns 401 Unauthorized (previously 404-to-hide). Frontend admin panel is always visible; password unlocks the live data. ADR-023 superseded — IP gating added zero security beyond a strong password and locked the operator out whenever the home IP changed.
|
| 40 |
+
- **Drop function-local `import logging` in orchestrator (KI-101, `66eb4ed`).** Removed 6 inline `import logging` lines from `backend/orchestrator.py`; Python's scoping rule was promoting `logging` to function-local, causing `UnboundLocalError` when the `asyncio.wait_for` `TimeoutError` branch fired before reaching the inline import. Module-level import is the sole binding now.
|
| 41 |
+
- **Profile RAG session isolation (KI-102, `4bb8da0`).** `upsert_profile_chunk` stamps `session_id` metadata on every chunk; `retrieve()` excludes `doc_type == "profile"` from the main pass; per-session profile lookup triple-checks `meta.session_id == session_id` in Python after the Chroma where-clause. Legacy chunks without `session_id` are silently refused (fail-closed). Cross-session PII leak (age / dependents / health conditions) closed. ADR-022 extended with session-isolation subsection.
|
| 42 |
+
- **`_canonical_fallback` no_trailer loop-breaker (KI-103, `8ef5c43`).** Added `session._ff_failed_attempts[slot_id]` + `session._ff_skipped_slots: set[str]`. After 2 failed attempts on the same slot, mark skipped and advance to the next unfilled slot. Caps the worst-case wedge at ~18 turns to escape fact-find instead of unbounded.
|
| 43 |
+
- **CoT / instruction-echo strip in voice_format (KI-104, `407f2a1`).** `tts_preprocess` now kills `<think>...</think>` blocks, `**Reasoning:**` / `**Thought:**` labels, `[INTERNAL]` blocks, sentence-anchored CoT starters ("Let me think...", "Step 1:..."). Emergency fallback to a generic acknowledger if the whole reply is CoT-shaped. Stops Sarvam from TTS-ing the bot's internal monologue.
|
| 44 |
+
- **Recommendation closer wired (KI-105, `8a58fa1`).** `RECOMMENDATION_CLOSER_PHRASES` frozenset ("show me the top 3", "rank", "pitch me", "compare X vs Y") classified as `recommendation` / `comparison` BEFORE the `FACT_FIND_TRIGGERS` check, so a fully-fact-found user can never get bounced back into fact-find. Persona prompt gets `RECOMMENDATION_CLOSER_ADDENDUM` with a strict 3-policy ranked-shortlist contract (3 policies, one-line rationale each, IRDAI disclaimer, no hedging). ADR-008 extended with closer-mode subsection.
|
| 45 |
+
- **Graceful TimeoutError + Exception on `/api/chat` (KI-106, `565bf31`).** `handle_turn(...)` wrapped in `asyncio.wait_for(45s)` with explicit `except asyncio.TimeoutError` + broad `except Exception`. Both return HTTP 200 with `source="graceful_timeout"` / `graceful_exception"` and an in-character recovery sentence instead of HTTP 500. Internal `logger.exception` still captures the full traceback for admin observability.
|
| 46 |
+
- **`_safe_collection_get` helper for Chroma (KI-107, `3a9a14f`).** Wraps every `collection.get(ids=[...])` and `collection.get(where=...)` call in `backend/profile_rag.py` in `try / except Exception`, returns `None` on miss with `logger.warning(...)`. Closes the KI-102 per-session profile lookup raising on never-existed sessions on HF Space (Chroma version-dependent behaviour). `None` return is treated identically to a `session_id` mismatch — fail-closed.
|
| 47 |
- **Chain budgets:** brain 20s × 35s total, fast-brain 12s × 22s total, judge 30s × 75s total. With KI-080 only PRIMARY + BACKUP consume budget in the common case — leaves headroom for KI-079 escalation. KI-084 per-phase httpx timeouts are nested inside these budgets.
|
| 48 |
- **STT/TTS/Translator** = Sarvam (Saarika v2.5 / Bulbul v2 / Sarvam-M). **Embeddings** = local BGE-small-en-v1.5.
|
| 49 |
- **Provider keys.** `NVIDIA_NIM_API_KEY` + `GROQ_API_KEY` + `OPENROUTER_API_KEY` required in `.env` (local) and HF Space environment (production — KI-081).
|
|
|
|
| 129 |
|
| 130 |
---
|
| 131 |
|
| 132 |
+
*Last reviewed 2026-05-15 — KI-101..KI-107 landed (orchestrator stability + profile-RAG session isolation + recommendation closer + graceful chat error handling).*
|
|
@@ -20,14 +20,14 @@ FastAPI + Pydantic service that fronts every chat turn. The HTTP entry point is
|
|
| 20 |
| `fact_find_normalizer.py` | LLM-driven free-text → slot-value coercion (e.g. "32 lakh" → `3200000`). Goes through `NimChainLLM`, not a single client (KI-033). | — |
|
| 21 |
| `profile_extractor.py` | LLM extractor that pulls profile updates out of conversational asides ("by the way, my dad has diabetes"). Chain-pattern, never a hardcoded model. | [ADR-022](../70-docs/60-decisions/ADR-022-conversational-profile-updates.md) |
|
| 22 |
| `profile_store.py` | **NEW (KI-040).** Persistent named-profile JSON store under `40-data/profiles/`. O(1) name-keyed lookup; mirrors into `profile_rag` on every save. | — |
|
| 23 |
-
| `profile_rag.py` | Embeds the user's profile as a Chroma chunk so the brain sees it alongside policy chunks for "what's best for me?" turns. |
|
| 24 |
| `session_state.py` | In-memory session map; tracks fact-find progress + chat history per `session_id`. |
|
| 25 |
| `faithfulness.py` | 4-gate hallucination guard (retrieval floor → citation integrity → regex numeric grounding → LLM judge). Blocks land in `logs/hallucinations.jsonl`. | — |
|
| 26 |
| `scorecard.py` | Pure-function 6-sub-score scorer over the 62-field extracted JSON. No LLM. | — |
|
| 27 |
| `translator.py` | Sarvam-M Indic ↔ English translator wrapper. | [ADR-006](../70-docs/60-decisions/ADR-006-sarvam-first-stack.md) |
|
| 28 |
| `translation_check.py` | Post-hoc detector for mixed-script replies; flags Hinglish leakage. | — |
|
| 29 |
| `persona.py` | The consultative-advisor system prompt + view-aware prompt overlays. | [ADR-008](../70-docs/60-decisions/ADR-008-consultative-advisor-persona.md), [ADR-021](../70-docs/60-decisions/ADR-021-view-aware-system-prompt.md) |
|
| 30 |
-
| `voice_format.py` | Strips markdown / lists / bullet glyphs so TTS sounds natural. | — |
|
| 31 |
| `premium_calculator.py` | Looks up `40-data/premiums/illustrative_premiums.json` + applies the documented scaling factors. Never claims a real quote. | [ADR-007](../70-docs/60-decisions/ADR-007-illustrative-pricing.md) |
|
| 32 |
| `security.py` | Request rate-limiting, input sanitisation. | — |
|
| 33 |
| `admin.py` | Admin-only routes (live LLM-health, usage rollups, hallucination tail). | ADR-023 |
|
|
|
|
| 20 |
| `fact_find_normalizer.py` | LLM-driven free-text → slot-value coercion (e.g. "32 lakh" → `3200000`). Goes through `NimChainLLM`, not a single client (KI-033). | — |
|
| 21 |
| `profile_extractor.py` | LLM extractor that pulls profile updates out of conversational asides ("by the way, my dad has diabetes"). Chain-pattern, never a hardcoded model. | [ADR-022](../70-docs/60-decisions/ADR-022-conversational-profile-updates.md) |
|
| 22 |
| `profile_store.py` | **NEW (KI-040).** Persistent named-profile JSON store under `40-data/profiles/`. O(1) name-keyed lookup; mirrors into `profile_rag` on every save. | — |
|
| 23 |
+
| `profile_rag.py` | Embeds the user's profile as a Chroma chunk so the brain sees it alongside policy chunks for "what's best for me?" turns. Per-chunk `session_id` metadata + `doc_type=profile` exclusion from main retrieval + Python-side triple-check on per-session lookup (KI-102). All `collection.get(...)` calls wrapped in `_safe_collection_get` so never-existed sessions return `None` instead of raising (KI-107). | [ADR-022](../70-docs/60-decisions/ADR-022-conversational-profile-updates.md) |
|
| 24 |
| `session_state.py` | In-memory session map; tracks fact-find progress + chat history per `session_id`. |
|
| 25 |
| `faithfulness.py` | 4-gate hallucination guard (retrieval floor → citation integrity → regex numeric grounding → LLM judge). Blocks land in `logs/hallucinations.jsonl`. | — |
|
| 26 |
| `scorecard.py` | Pure-function 6-sub-score scorer over the 62-field extracted JSON. No LLM. | — |
|
| 27 |
| `translator.py` | Sarvam-M Indic ↔ English translator wrapper. | [ADR-006](../70-docs/60-decisions/ADR-006-sarvam-first-stack.md) |
|
| 28 |
| `translation_check.py` | Post-hoc detector for mixed-script replies; flags Hinglish leakage. | — |
|
| 29 |
| `persona.py` | The consultative-advisor system prompt + view-aware prompt overlays. | [ADR-008](../70-docs/60-decisions/ADR-008-consultative-advisor-persona.md), [ADR-021](../70-docs/60-decisions/ADR-021-view-aware-system-prompt.md) |
|
| 30 |
+
| `voice_format.py` | Strips markdown / lists / bullet glyphs so TTS sounds natural. `tts_preprocess` also kills CoT leakage: `<think>...</think>` blocks, `**Reasoning:**` / `**Thought:**` labels, `[INTERNAL]` blocks, sentence-anchored CoT starters; emergency-fallback acknowledger if the whole reply is CoT-shaped (KI-104). | — |
|
| 31 |
| `premium_calculator.py` | Looks up `40-data/premiums/illustrative_premiums.json` + applies the documented scaling factors. Never claims a real quote. | [ADR-007](../70-docs/60-decisions/ADR-007-illustrative-pricing.md) |
|
| 32 |
| `security.py` | Request rate-limiting, input sanitisation. | — |
|
| 33 |
| `admin.py` | Admin-only routes (live LLM-health, usage rollups, hallucination tail). | ADR-023 |
|