rohitsar567 Claude Opus 4.7 (1M context) commited on
Commit
d37a6cf
·
1 Parent(s): afe6172

fix(admin): KI-096 + KI-097 — public /api/version + password-only admin

Browse files

KI-096: add unauthenticated GET /api/version (git SHA + uptime). Lets any
caller verify which commit HF Space is serving without admin auth.

KI-097: rip out admin IP allowlist. ADMIN_IP_ALLOWLIST env, _ip_allowed(),
and the dual-gate 404-to-hide-existence behavior are gone. _check_admin
now only verifies the X-Admin-Password header; bad/missing password →
401 Unauthorized. Operational rationale: changing networks locked the
operator out without adding meaningful security beyond a strong password.
ADR-023 superseded; ADR-010 secret count 8 → 7.

Also includes test_name_persistence.py (4 deterministic regression cases
pinning KI-091/094/095) and the KI-094 mistakes-log entry.

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

70-docs/60-decisions/ADR-010-secret-handling.md CHANGED
@@ -5,7 +5,7 @@
5
 
6
  ## Context
7
 
8
- The bot needs 8 API keys / secrets (Sarvam, Voyage, NIM, HuggingFace, Groq, OpenRouter, admin password, admin IP allowlist). Leaking any of them creates real cost or security exposure.
9
 
10
  ## Decision
11
 
 
5
 
6
  ## Context
7
 
8
+ The bot needs 7 API keys / secrets (Sarvam, Voyage, NIM, HuggingFace, Groq, OpenRouter, admin password). [Was 8 — admin IP allowlist removed in KI-097.] Leaking any of them creates real cost or security exposure.
9
 
10
  ## Decision
11
 
70-docs/60-decisions/ADR-023-admin-panel-ip-gated.md CHANGED
@@ -1,5 +1,7 @@
1
  # ADR-023: Admin panel IP-gated; surfaced as in-app tab
2
 
 
 
3
  **Status:** Locked
4
  **Date:** 2026-05-14
5
 
 
1
  # ADR-023: Admin panel IP-gated; surfaced as in-app tab
2
 
3
+ > **SUPERSEDED 2026-05-15 (KI-097).** The IP allowlist gate described below was removed because changing networks locked the operator out without meaningful added security beyond a strong password. The admin endpoints are now password-only (`X-Admin-Password` header → `ADMIN_PASSWORD` env). Backend returns 401 Unauthorized (no longer 404-to-hide). Frontend admin panel is always visible; password unlocks the data.
4
+
5
  **Status:** Locked
6
  **Date:** 2026-05-14
7
 
80-audit/ENTERPRISE_AUDIT.md CHANGED
@@ -278,6 +278,7 @@ The full eval was sending **every** QA question to `needs_finder`. Sample bot an
278
  | **KI-090** | **`11cf4b3`** | **Lenient FF-block parser.** Post-KI-088 live probe showed ~70% of brain calls returned successfully in 4-10s (NIM concurrency fix surfaced the real bottleneck) but `_parse_ff_block` rejected the reply with `fallback:no_trailer` because the brain had dropped the literal `<FF>...</FF>` tags around its JSON tail. Real LLMs under load (Qwen 3-Next 80B, Nemotron Nano 30B, Groq Llama-3.3-70B) regularly drop the wrapper even when the structured payload is otherwise contract-compliant. New `_parse_ff_block` tries three strategies in order: (a) strict `<FF>{...}</FF>` (the original contract); (b) fenced ```` ```json {...} ``` ```` (common LLM habit); (c) bare `{...}` JSON object at the end of the reply. Each candidate must `json.loads` cleanly AND contain at least one contract key (`captured` / `slot_driving` / `complete`) before it counts — prevents false positives from prose that happens to contain `{...}`. `_strip_ff_block` mirrors the three strategies in reverse so prose-only output to the user never leaks the structured metadata block. Inline tests: 7/7 parse tests + 7/7 strip tests pass. Brain success rate climbs from ~30% (post-KI-088 baseline blocked by parser) toward ~95% (NIM concurrency healthy + parser accepts contract-compliant tails regardless of wrapper). |
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
  | D-001 | (multi) | ChromaDB HNSW bloat 3-layer prevention (ADR-029) |
282
  | D-002 | (LaunchAgent edit) | Three silently-failing LaunchAgent scripts fixed |
283
  | D-009 | `bcb7079` | Removed `tmp_*.py` debug files from repo root |
 
278
  | **KI-090** | **`11cf4b3`** | **Lenient FF-block parser.** Post-KI-088 live probe showed ~70% of brain calls returned successfully in 4-10s (NIM concurrency fix surfaced the real bottleneck) but `_parse_ff_block` rejected the reply with `fallback:no_trailer` because the brain had dropped the literal `<FF>...</FF>` tags around its JSON tail. Real LLMs under load (Qwen 3-Next 80B, Nemotron Nano 30B, Groq Llama-3.3-70B) regularly drop the wrapper even when the structured payload is otherwise contract-compliant. New `_parse_ff_block` tries three strategies in order: (a) strict `<FF>{...}</FF>` (the original contract); (b) fenced ```` ```json {...} ``` ```` (common LLM habit); (c) bare `{...}` JSON object at the end of the reply. Each candidate must `json.loads` cleanly AND contain at least one contract key (`captured` / `slot_driving` / `complete`) before it counts — prevents false positives from prose that happens to contain `{...}`. `_strip_ff_block` mirrors the three strategies in reverse so prose-only output to the user never leaks the structured metadata block. Inline tests: 7/7 parse tests + 7/7 strip tests pass. Brain success rate climbs from ~30% (post-KI-088 baseline blocked by parser) toward ~95% (NIM concurrency healthy + parser accepts contract-compliant tails regardless of wrapper). |
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 |
80-audit/KI-094-mistake.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # KI-094 — Mistake log entry
2
+
3
+ **Date:** 2026-05-15
4
+ **Commits:** `9813994` (KI-091), `f068094` (KI-094)
5
+
6
+ ## Symptom
7
+
8
+ Fact-find conversational flow exhibited a "logical failure": bot captured `name` correctly on turn N, advanced to `income` on turn N+1, advanced to `existing_cover` on turn N+2, then on turn N+3 re-asked the user for `name`. The `name` field had clearly been captured and used to ask follow-up questions, then silently disappeared from the profile.
9
+
10
+ ## Root cause
11
+
12
+ The LLM `profile_extractor` chain returns a structured dict (`{"name": ..., "income": ..., "existing_cover": ..., ...}`) on every turn. On turns where the user did not restate their name, the extractor returned `{"name": null, ...}` — the LLM's way of saying "I did not extract a name from this turn." The orchestrator's merge loop iterated those keys and called `session.update_profile_field("name", None)`, which `setattr`'d `None` onto the profile, **overwriting the previously captured value**. Then `next_question(profile)` correctly re-returned the `name` slot because `profile.name` was `None` again.
13
+
14
+ Two distinct semantics — "I didn't extract anything for this field" vs. "this field should now be empty" — were conflated under the same `null` return, and the merge loop trusted the extractor's nulls as authoritative.
15
+
16
+ ## Fix (two layers)
17
+
18
+ 1. **KI-091 (commit `9813994`)** — orchestrator now skips both `extract_profile_updates` and the faithfulness `judge` on fact-find turns. Rationale:
19
+ - BRAIN_CHAIN + JUDGE_CHAIN are credit-exhausted and were hanging the response loop ~20s per turn.
20
+ - The extractor was the field-clearing culprit. Fact-find turns already capture fields deterministically from the slot-filler — running the LLM extractor on top was both redundant and destructive.
21
+
22
+ 2. **KI-094 (commit `f068094`)** — defensive guard inside the extractor merge loop:
23
+ ```python
24
+ for field, new_value in extracted.items():
25
+ if new_value in (None, "", []):
26
+ continue
27
+ session.update_profile_field(field, new_value)
28
+ ```
29
+ This ensures that even in QA-mode (non fact-find) turns where the extractor still runs, a `None` / empty return from the LLM cannot wipe an already-filled field. Belt-and-suspenders alongside KI-091.
30
+
31
+ ## Prevention rule
32
+
33
+ **When an LLM extractor returns a structured dict, NEVER pass `None` / `""` / `[]` values straight to `setattr` on a profile / state / session object.** Always filter Nones before merging.
34
+
35
+ The extractor LLM's `null` for a field means "I didn't extract anything for this field this turn" — it does NOT mean "this field is now empty." Conflating those two semantics silently destroys captured state.
36
+
37
+ ### Checklist for any future extractor pipeline in this codebase
38
+
39
+ - [ ] Merge loop skips `None`, `""`, `[]`, `{}` by default — filter is opt-out, not opt-in.
40
+ - [ ] Unit test: feed the extractor a turn with no relevant info; assert no profile fields are cleared.
41
+ - [ ] Grep audit: any `setattr(profile, field, None)` callsite is a code smell. Add to pre-commit.
42
+ - [ ] If a field legitimately needs to be cleared, expose an explicit `clear_profile_field(field)` API. Never use a `None` return from a generic extractor as the clear-signal channel.
43
+
44
+ ## Cross-references
45
+
46
+ - `MUST_FIX.md` — KI-091, KI-094 entries
47
+ - `backend/orchestrator/orchestrator.py` — fact-find skip path
48
+ - `backend/extractors/profile_extractor.py` (or merge loop callsite) — None filter
CLAUDE.md CHANGED
@@ -36,6 +36,7 @@ Every LLM role is a `NimChainLLM` candidate pool, NOT a hardcoded single model.
36
  - **Lenient FF-block parser (KI-090, `11cf4b3`).** Real LLMs (Qwen, Nemotron under load, Groq Llama-3.3) sometimes drop the literal `<FF>...</FF>` tags around their JSON tail. Pre-KI-090 those replies fell to `fallback:no_trailer` even though the brain had produced a perfectly valid structured response. Now `_parse_ff_block` tries strict → fenced ```` ```json``` ```` → bare-JSON-tail, each candidate validated by presence of a contract key (`captured` / `slot_driving` / `complete`). `_strip_ff_block` mirrors the strategies so prose-only output never leaks structured metadata.
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
  - **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.
40
  - **STT/TTS/Translator** = Sarvam (Saarika v2.5 / Bulbul v2 / Sarvam-M). **Embeddings** = local BGE-small-en-v1.5.
41
  - **Provider keys.** `NVIDIA_NIM_API_KEY` + `GROQ_API_KEY` + `OPENROUTER_API_KEY` required in `.env` (local) and HF Space environment (production — KI-081).
@@ -85,7 +86,7 @@ Numbered top-level buckets for non-code artifacts (sort lexicographically in `ls
85
 
86
  ## Admin panel (KI-048 / KI-052)
87
 
88
- - **Backend:** `GET /api/admin/profiles` + `GET /api/admin/performance`, both behind `_check_admin` (IP allowlist + `X-Admin-Password` header). Auth failure returns 404 (not 401) so unauthenticated probes can't enumerate endpoints.
89
  - **Frontend:** admin HTML has 3 lazy-loaded tabs — **Profile + Visitor Log** (pulls `/api/admin/profiles`), **Performance** (pulls `/api/admin/performance`), **LLM Chain** (unchanged from prior). Auth state preserved across tab switches.
90
 
91
  ## Disk + storage hardening (ADR-029)
 
36
  - **Lenient FF-block parser (KI-090, `11cf4b3`).** Real LLMs (Qwen, Nemotron under load, Groq Llama-3.3) sometimes drop the literal `<FF>...</FF>` tags around their JSON tail. Pre-KI-090 those replies fell to `fallback:no_trailer` even though the brain had produced a perfectly valid structured response. Now `_parse_ff_block` tries strict → fenced ```` ```json``` ```` → bare-JSON-tail, each candidate validated by presence of a contract key (`captured` / `slot_driving` / `complete`). `_strip_ff_block` mirrors the strategies so prose-only output never leaks structured metadata.
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).
 
86
 
87
  ## Admin panel (KI-048 / KI-052)
88
 
89
+ - **Backend:** `GET /api/admin/profiles` + `GET /api/admin/performance`, both behind `_check_admin` (`X-Admin-Password` header only, post-KI-097). Auth failure returns 401 Unauthorized.
90
  - **Frontend:** admin HTML has 3 lazy-loaded tabs — **Profile + Visitor Log** (pulls `/api/admin/profiles`), **Performance** (pulls `/api/admin/performance`), **LLM Chain** (unchanged from prior). Auth state preserved across tab switches.
91
 
92
  ## Disk + storage hardening (ADR-029)
backend/README.md CHANGED
@@ -29,7 +29,7 @@ FastAPI + Pydantic service that fronts every chat turn. The HTTP entry point is
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, admin-IP allowlist. | [ADR-023](../70-docs/60-decisions/ADR-023-admin-panel-ip-gated.md) |
33
  | `admin.py` | Admin-only routes (live LLM-health, usage rollups, hallucination tail). | ADR-023 |
34
  | `llm_health.py` | Lightweight probe that pings each provider and writes `40-data/llm_health.json` for the admin tab. | — |
35
 
 
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 |
34
  | `llm_health.py` | Lightweight probe that pings each provider and writes `40-data/llm_health.json` for the admin tab. | — |
35
 
backend/admin.py CHANGED
@@ -1,4 +1,4 @@
1
- """Admin endpoints — IP+password gated. NEVER exposed to ordinary users.
2
 
3
  The four endpoints:
4
  GET /api/admin/health — full LLM health snapshot (every model)
@@ -6,18 +6,17 @@ The four endpoints:
6
  GET /api/admin/chain — current brain/fast/judge chain order
7
  POST /api/admin/chain — reorder a chain (promote a model to primary)
8
 
9
- Access gates (BOTH must pass):
10
- 1. Client IP must match ADMIN_IP_ALLOWLIST env (comma-separated)
11
- 2. Request must include `X-Admin-Password` header matching ADMIN_PASSWORD env
12
-
13
- If either gate fails, returns 404 (not 401) — the endpoints DO NOT exist
14
- for unauthorized callers. Even the existence of /api/admin/* is hidden.
15
 
16
  Setup:
17
  Add to Space secrets (Settings → Variables and secrets):
18
- ADMIN_PASSWORD = your-strong-password-here
19
- ADMIN_IP_ALLOWLIST = your.public.ip.v4,your.other.ip
20
- Find your IP at https://api.ipify.org/
 
 
 
21
  """
22
  from __future__ import annotations
23
 
@@ -43,14 +42,6 @@ router = APIRouter()
43
  USAGE_TAIL_LINES = 1000
44
 
45
 
46
- def _ip_allowed(client_ip: str) -> bool:
47
- """Allowlist check. Empty/unset allowlist => deny everyone."""
48
- allowed = os.environ.get("ADMIN_IP_ALLOWLIST", "").strip()
49
- if not allowed:
50
- return False
51
- return client_ip in {ip.strip() for ip in allowed.split(",") if ip.strip()}
52
-
53
-
54
  def _password_ok(supplied: Optional[str]) -> bool:
55
  expected = os.environ.get("ADMIN_PASSWORD", "").strip()
56
  if not expected:
@@ -59,13 +50,14 @@ def _password_ok(supplied: Optional[str]) -> bool:
59
 
60
 
61
  def _check_admin(request: Request, password: Optional[str]) -> None:
62
- """Both gates must pass. Returns 404 (not 401) on failure to hide existence."""
63
- # Honor X-Forwarded-For for HF Space proxy headers (HF Spaces sets this)
64
- client_ip = request.headers.get("X-Forwarded-For", "").split(",")[0].strip()
65
- if not client_ip:
66
- client_ip = request.client.host if request.client else ""
67
- if not _ip_allowed(client_ip) or not _password_ok(password):
68
- raise HTTPException(status_code=404, detail="Not Found")
 
69
 
70
 
71
  # --- Endpoints --------------------------------------------------------------
 
1
+ """Admin endpoints — password gated. NEVER exposed to ordinary users.
2
 
3
  The four endpoints:
4
  GET /api/admin/health — full LLM health snapshot (every model)
 
6
  GET /api/admin/chain — current brain/fast/judge chain order
7
  POST /api/admin/chain — reorder a chain (promote a model to primary)
8
 
9
+ Access gate (KI-097 — single check):
10
+ Request must include `X-Admin-Password` header matching ADMIN_PASSWORD env.
 
 
 
 
11
 
12
  Setup:
13
  Add to Space secrets (Settings → Variables and secrets):
14
+ ADMIN_PASSWORD = your-strong-password-here
15
+
16
+ Returns 401 Unauthorized on bad/missing password. The earlier IP allowlist
17
+ gate (ADMIN_IP_ALLOWLIST + 404-to-hide-existence) was removed in KI-097
18
+ because it added operational complexity (changing networks → locked out)
19
+ without meaningful additional security beyond a strong password.
20
  """
21
  from __future__ import annotations
22
 
 
42
  USAGE_TAIL_LINES = 1000
43
 
44
 
 
 
 
 
 
 
 
 
45
  def _password_ok(supplied: Optional[str]) -> bool:
46
  expected = os.environ.get("ADMIN_PASSWORD", "").strip()
47
  if not expected:
 
50
 
51
 
52
  def _check_admin(request: Request, password: Optional[str]) -> None:
53
+ """KI-097 — password-only gate. Raises 401 on bad/missing password.
54
+
55
+ `request` is kept in the signature so callsites don't churn, but the
56
+ function no longer inspects the client IP. Earlier dual-gate behavior
57
+ (IP allowlist + 404-to-hide-existence) was removed in KI-097.
58
+ """
59
+ if not _password_ok(password):
60
+ raise HTTPException(status_code=401, detail="Unauthorized")
61
 
62
 
63
  # --- Endpoints --------------------------------------------------------------
backend/main.py CHANGED
@@ -173,9 +173,11 @@ app.add_middleware(
173
 
174
 
175
  # ---------- Admin panel + LLM health background loop ----------
176
- # Mount the IP+password-gated admin endpoints. Unauthorized callers get 404
177
- # (not 401), so the existence of /api/admin/* is hidden from non-allowlisted
178
- # IPs and unauthenticated requests.
 
 
179
  from backend import admin as _admin_router_module
180
  app.include_router(_admin_router_module.router)
181
 
@@ -224,6 +226,49 @@ async def health():
224
  )
225
 
226
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  @app.post("/api/transcribe", response_model=TranscribeResponse)
228
  async def transcribe(
229
  file: UploadFile = File(...),
 
173
 
174
 
175
  # ---------- Admin panel + LLM health background loop ----------
176
+ # Mount the password-gated admin endpoints (KI-097). Unauthorized callers
177
+ # get 401 Unauthorized. The earlier IP allowlist gate (ADMIN_IP_ALLOWLIST +
178
+ # 404-to-hide-existence) was removed in KI-097 — operationally it locked
179
+ # the operator out when switching networks without adding real security
180
+ # beyond a strong password.
181
  from backend import admin as _admin_router_module
182
  app.include_router(_admin_router_module.router)
183
 
 
226
  )
227
 
228
 
229
+ # KI-096 — public deploy-verification endpoint. No auth (deliberate) so any
230
+ # caller can confirm which commit the HF Space is actually serving without
231
+ # needing the admin password. Cached at module import so we don't spawn
232
+ # `git` per request.
233
+ def _compute_build_sha() -> str:
234
+ import os
235
+ import subprocess
236
+ env_sha = os.environ.get("BUILD_SHA") or os.environ.get("HF_SPACE_GIT_REV")
237
+ if env_sha:
238
+ return env_sha[:12]
239
+ try:
240
+ out = subprocess.check_output(
241
+ ["git", "rev-parse", "HEAD"],
242
+ cwd=Path(__file__).resolve().parent.parent,
243
+ stderr=subprocess.DEVNULL,
244
+ timeout=2,
245
+ ).decode().strip()
246
+ return out[:12] if out else "unknown"
247
+ except Exception:
248
+ return "unknown"
249
+
250
+
251
+ _BUILD_SHA = _compute_build_sha()
252
+ _BUILD_STARTED_AT = time.time()
253
+
254
+
255
+ @app.get("/api/version")
256
+ async def version():
257
+ """Public deploy-verification endpoint — no auth required.
258
+
259
+ Returns the git SHA the running app was built from + the process start
260
+ timestamp. Used by deploy probes (and humans) to confirm which commit
261
+ HF Space is actually serving. The admin /api/admin/* endpoints are
262
+ password-gated (KI-097) and return 401; this endpoint is the auth-free
263
+ escape hatch for deploy verification.
264
+ """
265
+ return {
266
+ "sha": _BUILD_SHA,
267
+ "started_at": _BUILD_STARTED_AT,
268
+ "uptime_s": round(time.time() - _BUILD_STARTED_AT, 1),
269
+ }
270
+
271
+
272
  @app.post("/api/transcribe", response_model=TranscribeResponse)
273
  async def transcribe(
274
  file: UploadFile = File(...),
frontend/src/app/page.tsx CHANGED
@@ -70,9 +70,9 @@ export default function Page() {
70
  const [showPremium, setShowPremium] = useState(false);
71
  const [showMarketplace, setShowMarketplace] = useState(false);
72
  const [showProfile, setShowProfile] = useState(false);
73
- // Admin panel: iframe-embedded LLM control surface. Backend admin API is
74
- // IP-gated (ADMIN_IP_ALLOWLIST), so the panel itself silently renders the
75
- // dashboard's "not authorized" view for non-allowlisted IPs.
76
  const [showAdmin, setShowAdmin] = useState(false);
77
  const [marketplace, setMarketplace] = useState<MarketplaceResponse | null>(null);
78
  const [openPolicy, setOpenPolicy] = useState<MarketplacePolicy | null>(null);
@@ -652,14 +652,14 @@ export default function Page() {
652
  </div>
653
  </button>
654
  {/* Admin access — opens the LLM control panel in an embedded view.
655
- Backend admin API is IP-gated, so the panel works only from the
656
- allowlisted home IP; from other networks it shows "not authorized". */}
657
  <button
658
  onClick={() => { setShowAdmin(!showAdmin); setShowMarketplace(false); setShowPremium(false); setShowProfile(false); setShowCoverage(false); }}
659
  className={`group relative overflow-hidden rounded-xl transition-all shadow-sm hover:shadow-md ${
660
  showAdmin ? "ring-2 ring-[var(--primary)]" : ""
661
  }`}
662
- title="LLM control panel — health, chain order, usage (admin-only, IP-gated)"
663
  >
664
  <div className="absolute inset-0 bg-gradient-to-br from-slate-700 via-slate-600 to-zinc-700" />
665
  <div className="relative flex items-stretch text-white">
 
70
  const [showPremium, setShowPremium] = useState(false);
71
  const [showMarketplace, setShowMarketplace] = useState(false);
72
  const [showProfile, setShowProfile] = useState(false);
73
+ // Admin panel: iframe-embedded LLM control surface. Backend admin API
74
+ // is password-gated (KI-097); the embedded dashboard prompts for the
75
+ // X-Admin-Password header and shows its login view when missing.
76
  const [showAdmin, setShowAdmin] = useState(false);
77
  const [marketplace, setMarketplace] = useState<MarketplaceResponse | null>(null);
78
  const [openPolicy, setOpenPolicy] = useState<MarketplacePolicy | null>(null);
 
652
  </div>
653
  </button>
654
  {/* Admin access — opens the LLM control panel in an embedded view.
655
+ Backend admin API is password-gated (KI-097); enter the admin
656
+ password in the embedded dashboard to unlock the live data. */}
657
  <button
658
  onClick={() => { setShowAdmin(!showAdmin); setShowMarketplace(false); setShowPremium(false); setShowProfile(false); setShowCoverage(false); }}
659
  className={`group relative overflow-hidden rounded-xl transition-all shadow-sm hover:shadow-md ${
660
  showAdmin ? "ring-2 ring-[var(--primary)]" : ""
661
  }`}
662
+ title="LLM control panel — health, chain order, usage (admin-only, password-gated)"
663
  >
664
  <div className="absolute inset-0 bg-gradient-to-br from-slate-700 via-slate-600 to-zinc-700" />
665
  <div className="relative flex items-stretch text-white">
tests/test_name_persistence.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression tests for the fact-find name-loop bug (KI-091 + KI-094 + KI-095).
2
+
3
+ Pre-fix bug:
4
+ 1. User says "Rohit" → bot captures name + advances to next slot.
5
+ 2. Mid-session, on a later turn, the LLM extractor (running in the
6
+ free-form / QA branch) returns {"name": null, ...} for an utterance
7
+ that has nothing to do with the name.
8
+ 3. Orchestrator's merge loop wrote that None back via
9
+ session.update_profile_field("name", None), wiping the captured value.
10
+ 4. next_question(profile) then re-asks the name slot → infinite loop.
11
+
12
+ Three fixes pin the bug shut:
13
+ KI-091 — skip the LLM extractor + faithfulness judge entirely on fact-find
14
+ turns (intent=='fact_find' OR in_fact_find_continuation).
15
+ KI-094 — defensive guard inside the extractor merge: if new_value is in
16
+ (None, "", []), skip the field — never clobber a filled slot.
17
+ KI-095 — the /api/profile REST endpoint applies the same guard: empty
18
+ strings from the client cannot wipe a filled field.
19
+
20
+ These tests run WITHOUT touching any LLM API. retrieve / brain / judge /
21
+ extractor are all monkeypatched. The only thing exercised is the
22
+ orchestrator merge logic + the /api/profile endpoint logic.
23
+
24
+ Run:
25
+ cd /Users/rohitsar/Developer/Insurance\\ Sales\\ Bot
26
+ .venv/bin/python -m pytest tests/test_name_persistence.py -v
27
+ # or:
28
+ .venv/bin/python -m unittest tests.test_name_persistence -v
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import asyncio
34
+ import os
35
+ import unittest
36
+ import uuid
37
+ from dataclasses import dataclass
38
+ from typing import Optional
39
+ from unittest import mock
40
+
41
+ # Bootstrap import path so this file runs from either pytest or unittest.
42
+ import sys
43
+ from pathlib import Path
44
+ _REPO_ROOT = Path(__file__).resolve().parent.parent
45
+ if str(_REPO_ROOT) not in sys.path:
46
+ sys.path.insert(0, str(_REPO_ROOT))
47
+
48
+
49
+ # ---------------------------------------------------------------------------
50
+ # Lightweight stubs that stand in for the heavy I/O dependencies of
51
+ # `handle_turn`. Together they let us drive the orchestrator end-to-end
52
+ # without spinning up Chroma, an LLM provider, or the faithfulness judge.
53
+ # ---------------------------------------------------------------------------
54
+
55
+ @dataclass
56
+ class _StubLLMResult:
57
+ text: str = "Got it."
58
+ model: str = "stub-model"
59
+
60
+
61
+ class _StubProvider:
62
+ """Stands in for whatever `pick_brain(...).provider` returns."""
63
+ name = "stub-provider"
64
+ model = "stub-model"
65
+
66
+ async def chat(self, messages, temperature=0.2, max_tokens=1500):
67
+ return _StubLLMResult(text="Got it.", model="stub-model")
68
+
69
+
70
+ def _stub_brain_pick(intent: str, language: str):
71
+ # Match the BrainPick shape (.provider, .tag) the orchestrator uses.
72
+ from backend.orchestrator import BrainPick
73
+ return BrainPick(_StubProvider(), f"stub::{intent}")
74
+
75
+
76
+ async def _stub_retrieve(query, top_k=5, policy_ids=None, session_id=None):
77
+ return [] # empty context — perfectly valid for these tests
78
+
79
+
80
+ def _stub_format_for_llm_context(chunks):
81
+ return ""
82
+
83
+
84
+ async def _stub_upsert(*args, **kwargs):
85
+ return None
86
+
87
+
88
+ def _fresh_session_id() -> str:
89
+ """Use a unique session id per test so the on-disk JSON cache doesn't
90
+ cross-contaminate. We also clean up the file in tearDown."""
91
+ return f"test_name_persistence_{uuid.uuid4().hex[:10]}"
92
+
93
+
94
+ def _cleanup_session_file(session_id: str) -> None:
95
+ target = _REPO_ROOT / "40-data" / "sessions" / f"{session_id}.json"
96
+ if target.exists():
97
+ try:
98
+ target.unlink()
99
+ except OSError:
100
+ pass
101
+
102
+
103
+ # ---------------------------------------------------------------------------
104
+ # CASE A — extractor returning {"name": null} cannot wipe captured name.
105
+ # ---------------------------------------------------------------------------
106
+
107
+ class TestCaseA_ExtractorNullCannotWipeName(unittest.TestCase):
108
+ """KI-094 regression. The merge loop in orchestrator.handle_turn must
109
+ treat extractor-returned None / "" / [] as a no-op for that field —
110
+ NEVER overwrite a filled slot.
111
+ """
112
+
113
+ def setUp(self) -> None:
114
+ from backend.session_state import _sessions # in-memory cache
115
+ _sessions.clear()
116
+ self.session_id = _fresh_session_id()
117
+
118
+ def tearDown(self) -> None:
119
+ _cleanup_session_file(self.session_id)
120
+
121
+ def test_null_extraction_preserves_filled_name(self) -> None:
122
+ from backend.session_state import get_session
123
+ from backend import orchestrator as orch
124
+
125
+ # Seed: a session that already has name="Rohit" + name slot asked.
126
+ # Mark free_form_session so the extractor branch is reached (and not
127
+ # short-circuited by KI-091's fact-find gate).
128
+ session = get_session(self.session_id)
129
+ session.profile.name = "Rohit"
130
+ session.profile.age = 30
131
+ session.profile.asked = ["name"]
132
+ session.free_form_session = True
133
+ session.awaiting_question_id = None
134
+ session._flush()
135
+
136
+ # Mock extractor: returns null name + a valid new age update.
137
+ # Per KI-094, the null name must be skipped; the valid age update
138
+ # should still be applied.
139
+ async def _mock_extractor(user_text, current_profile):
140
+ return {"name": None, "age": 31, "income_band": "", "health_conditions": []}
141
+
142
+ # Patch all the heavy collaborators. We patch the names AS REFERENCED
143
+ # by orchestrator (which imports them inside the function body, so
144
+ # we patch at their source module).
145
+ with mock.patch("backend.profile_extractor.extract_profile_updates",
146
+ new=_mock_extractor), \
147
+ mock.patch("backend.orchestrator.retrieve", new=_stub_retrieve), \
148
+ mock.patch("backend.orchestrator.format_for_llm_context",
149
+ new=_stub_format_for_llm_context), \
150
+ mock.patch("backend.orchestrator.pick_brain", new=_stub_brain_pick), \
151
+ mock.patch("backend.profile_rag.upsert_profile_chunk",
152
+ new=_stub_upsert), \
153
+ mock.patch("backend.orchestrator.check_faithfulness",
154
+ new=mock.AsyncMock(return_value=mock.Mock(
155
+ passed=True, reasons=[]))):
156
+
157
+ # Drive a QA turn — an explicit policy-fact question.
158
+ # Intent should classify as "qa", profile is not empty (has age),
159
+ # so should_route_to_fact_find returns False → flow falls through
160
+ # to the extractor branch.
161
+ asyncio.run(orch.handle_turn(
162
+ user_text="What is the waiting period for PED under Activ Assure?",
163
+ chat_history=[],
164
+ user_profile=None,
165
+ session_id=self.session_id,
166
+ ))
167
+
168
+ # Re-read the session and assert.
169
+ session_after = get_session(self.session_id)
170
+ self.assertEqual(
171
+ session_after.profile.name, "Rohit",
172
+ "REGRESSION (KI-094): extractor returning {'name': null} wiped "
173
+ "the captured name. The merge guard "
174
+ "`if new_value in (None, '', []): continue` is missing or "
175
+ "broken in backend/orchestrator.py.",
176
+ )
177
+ self.assertEqual(
178
+ session_after.profile.age, 31,
179
+ "Valid non-null extractor updates should still be applied; "
180
+ "guard must skip ONLY null/empty values, not block all updates.",
181
+ )
182
+
183
+
184
+ # ---------------------------------------------------------------------------
185
+ # CASE B — fact-find branch does not invoke extract_profile_updates.
186
+ # ---------------------------------------------------------------------------
187
+
188
+ class TestCaseB_FactFindBranchDoesNotInvokeExtractor(unittest.TestCase):
189
+ """KI-091 regression. On a fact-find turn the orchestrator MUST NOT call
190
+ extract_profile_updates — the fact_find brain extracts slots natively
191
+ from its <FF> JSON tail, and the heavy extractor LLM both (a) duplicates
192
+ work and (b) periodically returns nulls that wipe filled slots.
193
+
194
+ We pin this by patching `extract_profile_updates` to raise. If the
195
+ orchestrator wrongly calls it on a fact-find turn, the call raises and
196
+ the test fails. If KI-091's gate is in place, the call never happens
197
+ and the turn completes cleanly.
198
+ """
199
+
200
+ def setUp(self) -> None:
201
+ from backend.session_state import _sessions
202
+ _sessions.clear()
203
+ self.session_id = _fresh_session_id()
204
+
205
+ def tearDown(self) -> None:
206
+ _cleanup_session_file(self.session_id)
207
+
208
+ def test_fact_find_turn_does_not_call_extractor(self) -> None:
209
+ from backend.session_state import get_session
210
+ from backend import orchestrator as orch
211
+ from backend.fact_find_brain import FactFindOutcome
212
+
213
+ # Seed a session that's in fact-find continuation (awaiting an answer).
214
+ session = get_session(self.session_id)
215
+ session.profile.name = "Rohit"
216
+ session.profile.age = 30
217
+ session.profile.asked = ["name", "age"]
218
+ session.free_form_session = False
219
+ session.awaiting_question_id = "dependents" # mid-fact-find
220
+ session._flush()
221
+
222
+ # Mock extractor: if called, fail loudly.
223
+ async def _explode(user_text, current_profile):
224
+ raise AssertionError(
225
+ "extract_profile_updates was called on a fact-find turn — "
226
+ "KI-091 gate is broken. The fact_find brain already extracts "
227
+ "slots from its <FF> trailer; the heavy extractor LLM here "
228
+ "is both wasteful AND the source of the name-wipe bug."
229
+ )
230
+
231
+ # Mock the fact_find brain to return a benign outcome.
232
+ async def _stub_drive(user_text, session, chat_history, session_id):
233
+ return FactFindOutcome(
234
+ reply_text="And who else do you want covered?",
235
+ captured_updates={},
236
+ slot_driving="dependents",
237
+ fact_find_complete=False,
238
+ ambiguous=False,
239
+ )
240
+
241
+ # The orchestrator wraps the extractor call in try/except, swallows
242
+ # AssertionError, and just logs a warning — meaning a broken KI-091
243
+ # gate would silently regress without our raise propagating. To pin
244
+ # this properly, we monitor the patched extractor with a Mock and
245
+ # assert call_count == 0 instead of relying on the raise reaching us.
246
+ extractor_spy = mock.AsyncMock(side_effect=_explode)
247
+
248
+ with mock.patch("backend.profile_extractor.extract_profile_updates",
249
+ new=extractor_spy), \
250
+ mock.patch("backend.fact_find_brain.drive_fact_find",
251
+ new=_stub_drive), \
252
+ mock.patch("backend.profile_rag.upsert_profile_chunk",
253
+ new=_stub_upsert), \
254
+ mock.patch("backend.profile_store.save_profile", new=mock.Mock()):
255
+
256
+ # Drive a turn — the user's message is a fact-find answer.
257
+ # in_fact_find_continuation is True (awaiting_question_id set,
258
+ # not free-form), so the orchestrator should route to the
259
+ # fact-find brain and return BEFORE reaching the extractor.
260
+ result = asyncio.run(orch.handle_turn(
261
+ user_text="self + spouse",
262
+ chat_history=[],
263
+ user_profile=None,
264
+ session_id=self.session_id,
265
+ ))
266
+
267
+ # The headline assertion: extractor was never invoked.
268
+ self.assertEqual(
269
+ extractor_spy.call_count, 0,
270
+ "REGRESSION (KI-091): extract_profile_updates was called on a "
271
+ "fact-find turn (call_count=%d). The intent='fact_find' / "
272
+ "in_fact_find_continuation gate in backend/orchestrator.py is "
273
+ "broken — fact-find turns must skip the heavy extractor LLM."
274
+ % extractor_spy.call_count,
275
+ )
276
+
277
+ # Sanity: the fact-find branch did run (we got its reply back).
278
+ self.assertEqual(result.intent, "fact_find")
279
+ self.assertEqual(
280
+ result.reply_text, "And who else do you want covered?",
281
+ "Fact-find branch did not run — test setup is wrong.",
282
+ )
283
+
284
+ # And the captured name is still there.
285
+ session_after = get_session(self.session_id)
286
+ self.assertEqual(session_after.profile.name, "Rohit")
287
+
288
+
289
+ # ---------------------------------------------------------------------------
290
+ # CASE C — /api/profile endpoint rejects empty-string overwrite.
291
+ # ---------------------------------------------------------------------------
292
+
293
+ class TestCaseC_ProfileApiRejectsEmptyOverwrite(unittest.TestCase):
294
+ """KI-095 regression. The POST /api/profile endpoint must NOT overwrite
295
+ a filled field with an empty string / empty list from the client.
296
+
297
+ Pre-fix: the loop did `if v is not None: setattr(...)` — an empty
298
+ string passed through and clobbered the existing name.
299
+
300
+ Post-fix (KI-095): `if v in (None, "", []): continue` — empty values
301
+ from the client are now no-ops.
302
+ """
303
+
304
+ def setUp(self) -> None:
305
+ from backend.session_state import _sessions
306
+ _sessions.clear()
307
+ self.session_id = _fresh_session_id()
308
+
309
+ def tearDown(self) -> None:
310
+ _cleanup_session_file(self.session_id)
311
+
312
+ def test_empty_string_name_does_not_clobber_filled_name(self) -> None:
313
+ from backend.session_state import get_session
314
+ from backend.main import profile_update, ProfileUpdateRequest
315
+
316
+ # Seed a session with name="Rohit".
317
+ session = get_session(self.session_id)
318
+ session.profile.name = "Rohit"
319
+ session.profile.age = 30
320
+ session._flush()
321
+
322
+ # Build a request with name="" — the bad payload that used to wipe.
323
+ # Other fields stay None so they're skipped by the existing
324
+ # `if v is not None` guard regardless.
325
+ req = ProfileUpdateRequest(session_id=self.session_id, name="")
326
+
327
+ # Patch the downstream RAG upsert + named-profile store so the
328
+ # endpoint doesn't hit disk/Chroma.
329
+ with mock.patch("backend.profile_rag.upsert_profile_chunk",
330
+ new=_stub_upsert), \
331
+ mock.patch("backend.profile_store.save_profile", new=mock.Mock()):
332
+ asyncio.run(profile_update(req))
333
+
334
+ # Re-read and assert.
335
+ session_after = get_session(self.session_id)
336
+ self.assertEqual(
337
+ session_after.profile.name, "Rohit",
338
+ "REGRESSION (KI-095): /api/profile let an empty string clobber "
339
+ "a filled name. The guard `if v in (None, '', []): continue` "
340
+ "in backend/main.py:profile_update is missing or broken.",
341
+ )
342
+
343
+ def test_empty_list_health_conditions_does_not_clobber_filled_list(self) -> None:
344
+ """KI-095 also protects list fields — an empty health_conditions
345
+ list from the client must not wipe a populated list."""
346
+ from backend.session_state import get_session
347
+ from backend.main import profile_update, ProfileUpdateRequest
348
+
349
+ session = get_session(self.session_id)
350
+ session.profile.name = "Rohit"
351
+ session.profile.health_conditions = ["diabetes", "hypertension"]
352
+ session._flush()
353
+
354
+ req = ProfileUpdateRequest(
355
+ session_id=self.session_id,
356
+ health_conditions=[],
357
+ )
358
+
359
+ with mock.patch("backend.profile_rag.upsert_profile_chunk",
360
+ new=_stub_upsert), \
361
+ mock.patch("backend.profile_store.save_profile", new=mock.Mock()):
362
+ asyncio.run(profile_update(req))
363
+
364
+ session_after = get_session(self.session_id)
365
+ self.assertEqual(
366
+ session_after.profile.health_conditions,
367
+ ["diabetes", "hypertension"],
368
+ "REGRESSION (KI-095): empty list from client clobbered a "
369
+ "filled health_conditions list.",
370
+ )
371
+
372
+
373
+ if __name__ == "__main__":
374
+ unittest.main(verbosity=2)