fix(clarify): P-102 Button-Parsing Off-by-one + Feature 53 Plain-Digit + Defense-in-Depth
Bug 2 (Button-Parsing): - Off-by-one: Button-Payload ist 1-basiert (send_clarify: idx=i+1), Handler nutzte idx=int(choice) → '1' mappte auf zweite Choice. Fix: idx = int(choice) - 1. - Feature 53 (Plain-Digit-Intercept) war entfernt worden: _room_clarify (room_id→clarify_id) wiederhergestellt, Plain-Digit '1' wird wieder als Clarify-Antwort erkannt (P-047 Mobile-Workaround). - Feature 55 (::-Fix): Format-Extraktion (:: vs :) von Verarbeitung getrennt — beide Formate münden in gemeinsame if/elif/else-Logik. Bug 1 (Raumwechsel): - Defense-in-Depth: is_pending_clarify_answer() als Bypass-Trigger VOR dem Archivar-Routing. Clarify-Antworten (Button-Payload ODER Plain-Digit) werden IMMER am Routing vorbeigeleitet, nie thematisch in andere Räume geroutet. Tests: 8 neue Unit-Tests (test_p102_clarify_parsing.py). 1607 archivar-Tests passed, keine Regression.
This commit is contained in:
+162
-51
@@ -1352,6 +1352,9 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# The router's _check_never_route_topic handles per-topic blocking now.
|
||||
# Clarify state: maps clarify_id → session_key for gateway resolution
|
||||
self._clarify_state: Dict[str, str] = {}
|
||||
# Feature 53: Clarify room mapping — room_id → clarify_id for
|
||||
# plain-digit text intercept (P-047 Mobile-Workaround).
|
||||
self._room_clarify: Dict[str, str] = {}
|
||||
# FIX 2 (P0): ISSUE 3 — Pending Clarify Dispatch Slot
|
||||
# {room_id: {text, username, msg_id, msg_obj, is_button_response}}
|
||||
self._pending_clarify_dispatch: Dict[str, dict] = {}
|
||||
@@ -2423,6 +2426,40 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
reason = "sm_completed" if sm_completed else "not_completed"
|
||||
return (sm_completed, operator_room_id, reason)
|
||||
|
||||
def is_pending_clarify_answer(self, text: str, room_id: str) -> bool:
|
||||
"""Defense-in-Depth (Bug 1): Ist diese Nachricht eine Clarify-Antwort?
|
||||
|
||||
Liefert True, wenn die Nachricht als Antwort auf eine offene
|
||||
Clarify-Frage zu werten ist — unabhängig vom Format-Pfad:
|
||||
|
||||
1. CLARIFY:-Button-Payload (CLARIFY:<id>:<idx> / CLARIFY:<id>::<idx>)
|
||||
2. Plain-Digit-Text (Feature 53, P-047 Mobile-Workaround) in einem
|
||||
Raum mit offener Clarify-Frage (_room_clarify)
|
||||
|
||||
Der Archivar-Routing-Block prüft diesen Trigger VOR der
|
||||
Klassifikation und leitet Clarify-Antworten IMMER am Routing
|
||||
vorbei — sie dürfen nie thematisch in einen anderen Raum geroutet
|
||||
werden, sondern müssen im Ursprungsraum als Clarify-Response
|
||||
verarbeitet werden.
|
||||
|
||||
Args:
|
||||
text: Die (bereits quote-gestrippte) Nachricht.
|
||||
room_id: Der Ursprungsraum der Nachricht.
|
||||
|
||||
Returns:
|
||||
True, wenn die Nachricht eine Clarify-Antwort ist.
|
||||
"""
|
||||
if not text:
|
||||
return False
|
||||
stripped = text.strip()
|
||||
# 1. CLARIFY:-Button-Payload (beide Formate)
|
||||
if stripped.startswith("CLARIFY:"):
|
||||
return True
|
||||
# 2. Plain-Digit-Text in einem Raum mit offener Clarify-Frage
|
||||
if stripped.isdigit() and room_id in getattr(self, "_room_clarify", {}):
|
||||
return True
|
||||
return False
|
||||
|
||||
async def _reconnect_ddp(self) -> bool:
|
||||
"""Bug 7: DDP-Reconnect mit M13 GC.
|
||||
|
||||
@@ -2811,74 +2848,130 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
return
|
||||
# ── Ende Thema B Onboarding-Guard ────────────────────────────────────
|
||||
|
||||
# ── CLARIFY Plain-Digit Text Intercept (Feature 53) ─────────────
|
||||
# Wenn der User eine einfache Zahl (1, 2, 3) tippt statt auf einen
|
||||
# Button zu klicken, als CLARIFY-Antwort verarbeiten (P-047 Mobile).
|
||||
# P-013: is_clarify_response (CLARIFY:-Prefix) wird zuerst geprüft;
|
||||
# dieser Block fängt NUR plain-digit Texte ab.
|
||||
is_archivar_clarify = text.startswith("ARCHIVAR_CLARIFY:") if text else False
|
||||
if not is_clarify_response and not is_archivar_clarify:
|
||||
stripped = text.strip()
|
||||
_room_clarify = getattr(self, "_room_clarify", {})
|
||||
if stripped.isdigit() and room_id in _room_clarify:
|
||||
clarify_id = _room_clarify[room_id]
|
||||
idx = int(stripped) - 1 # 1-basierte Eingabe → 0-basierter Index
|
||||
resolved_text: Optional[str] = None
|
||||
try:
|
||||
from tools.clarify_gateway import _entries as _clarify_entries
|
||||
entry = _clarify_entries.get(clarify_id)
|
||||
if entry and entry.choices and 0 <= idx < len(entry.choices):
|
||||
resolved_text = entry.choices[idx]
|
||||
except Exception:
|
||||
resolved_text = None
|
||||
if resolved_text is None:
|
||||
resolved_text = f"choice {idx + 1}"
|
||||
# Resolve via gateway and clean up
|
||||
self._clarify_state.pop(clarify_id, None)
|
||||
self._room_clarify.pop(room_id, None)
|
||||
self._rooms_with_pending_questions.discard(room_id)
|
||||
try:
|
||||
from tools.clarify_gateway import resolve_gateway_clarify
|
||||
resolved = resolve_gateway_clarify(clarify_id, resolved_text)
|
||||
if resolved:
|
||||
logger.info(
|
||||
"[rocketchat] Clarify %s resolved via plain-digit: %s (session=%s)",
|
||||
clarify_id, resolved_text[:60],
|
||||
self._clarify_state.get(clarify_id, "?"),
|
||||
)
|
||||
else:
|
||||
logger.warning("[rocketchat] Clarify %s resolve returned False", clarify_id)
|
||||
except Exception as exc:
|
||||
logger.error("[rocketchat] resolve_gateway_clarify failed: %s", exc)
|
||||
# P-067: Clear Clarify-Modal pulse
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None and self._presence_engine.is_enabled():
|
||||
self._presence_engine.clear_clarify_modal()
|
||||
routing_counter.increment('clarify_plain_digit_bypass')
|
||||
logger.info("ROUTING BYPASS: reason=clarify_plain_digit_bypass, origin_room=%s", room_id)
|
||||
return
|
||||
# ── Ende CLARIFY Plain-Digit Text Intercept ─────────────────────
|
||||
|
||||
# ── CLARIFY Response Handling ───────────────────────────────────
|
||||
# Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other
|
||||
# V8.2.1 A2: Handle ARCHIVAR_CLARIFY (Nachklärung) responses
|
||||
is_archivar_clarify = text.startswith("ARCHIVAR_CLARIFY:") if text else False
|
||||
if is_clarify_response and text.startswith("CLARIFY:"):
|
||||
routing_counter.increment('clarify_answer_bypass')
|
||||
logger.info("ROUTING BYPASS: reason=clarify_answer_bypass, origin_room=%s", room_id)
|
||||
try:
|
||||
# ── Format-Extraktion (gemeinsam für alt und neu, Feature 55) ──
|
||||
if "::" in text:
|
||||
# Neues Format: CLARIFY:<id>::<choice> (via _build_custom_buttons)
|
||||
prefix_part, choice = text.split("::", 1)
|
||||
clarify_id = prefix_part.split(":", 1)[1]
|
||||
else:
|
||||
# Altes Format: CLARIFY:<id>:other (Other-Button)
|
||||
# Altes Format: CLARIFY:<id>:<token>
|
||||
parts = text.split(":", 2)
|
||||
if len(parts) != 3:
|
||||
logger.debug("[rocketchat] Unrecognized CLARIFY format: %s", text)
|
||||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY unrecognized format — skipping")
|
||||
return
|
||||
_, clarify_id, choice = parts
|
||||
if choice == "other":
|
||||
# For "Other" button, enable text capture mode
|
||||
from tools.clarify_gateway import mark_awaiting_text
|
||||
mark_awaiting_text(clarify_id)
|
||||
logger.debug("[rocketchat] Clarify %s: awaiting text response from %s", clarify_id, username)
|
||||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY other — awaiting text")
|
||||
# P-067: Clear Clarify-Modal pulse (user responded)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None and self._presence_engine.is_enabled():
|
||||
self._presence_engine.clear_clarify_modal()
|
||||
# Don't process further - wait for the next text message
|
||||
return
|
||||
elif choice.isdigit():
|
||||
# Numeric choice → resolve the clarify immediately
|
||||
idx = int(choice)
|
||||
resolved_text: Optional[str] = None
|
||||
try:
|
||||
from tools.clarify_gateway import _entries as _clarify_entries
|
||||
entry = _clarify_entries.get(clarify_id)
|
||||
if entry and entry.choices and 0 <= idx < len(entry.choices):
|
||||
resolved_text = entry.choices[idx]
|
||||
except Exception:
|
||||
resolved_text = None
|
||||
if resolved_text is None:
|
||||
# Race: entry vanished. Echo the index.
|
||||
resolved_text = f"choice {idx + 1}"
|
||||
# Resolve via gateway and clean up
|
||||
self._clarify_state.pop(clarify_id, None)
|
||||
try:
|
||||
from tools.clarify_gateway import resolve_gateway_clarify
|
||||
resolved = resolve_gateway_clarify(clarify_id, resolved_text)
|
||||
if resolved:
|
||||
logger.info(
|
||||
"[rocketchat] Clarify %s resolved: %s (session=%s)",
|
||||
clarify_id, resolved_text[:60], self._clarify_state.get(clarify_id, "?"),
|
||||
)
|
||||
else:
|
||||
logger.warning("[rocketchat] Clarify %s resolve returned False", clarify_id)
|
||||
except Exception as exc:
|
||||
logger.error("[rocketchat] resolve_gateway_clarify failed: %s", exc)
|
||||
# P-067: Clear Clarify-Modal pulse (user responded with choice)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None and self._presence_engine.is_enabled():
|
||||
self._presence_engine.clear_clarify_modal()
|
||||
# Don't route to agent — this was a button click
|
||||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY resolved — skipping")
|
||||
return
|
||||
else:
|
||||
# Unknown token — let it fall through as regular text
|
||||
logger.warning("[rocketchat] Unknown clarify token: %s", choice)
|
||||
|
||||
# ── Gemeinsame Verarbeitung (beide Formate) ──
|
||||
if choice == "other":
|
||||
# For "Other" button, enable text capture mode
|
||||
from tools.clarify_gateway import mark_awaiting_text
|
||||
mark_awaiting_text(clarify_id)
|
||||
logger.debug("[rocketchat] Clarify %s: awaiting text response from %s", clarify_id, username)
|
||||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY other — awaiting text")
|
||||
# P-067: Clear Clarify-Modal pulse (user responded)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None and self._presence_engine.is_enabled():
|
||||
self._presence_engine.clear_clarify_modal()
|
||||
# Don't process further - wait for the next text message
|
||||
return
|
||||
elif choice.isdigit():
|
||||
# Numeric choice → resolve the clarify immediately
|
||||
# P-102: Off-by-one — Button-Payload ist 1-basiert
|
||||
# (send_clarify: idx = i + 1), also -1 für 0-basierten Index.
|
||||
idx = int(choice) - 1
|
||||
resolved_text: Optional[str] = None
|
||||
try:
|
||||
from tools.clarify_gateway import _entries as _clarify_entries
|
||||
entry = _clarify_entries.get(clarify_id)
|
||||
if entry and entry.choices and 0 <= idx < len(entry.choices):
|
||||
resolved_text = entry.choices[idx]
|
||||
except Exception:
|
||||
resolved_text = None
|
||||
if resolved_text is None:
|
||||
# Race: entry vanished. Echo the index.
|
||||
resolved_text = f"choice {idx + 1}"
|
||||
# Resolve via gateway and clean up
|
||||
self._clarify_state.pop(clarify_id, None)
|
||||
# Clean up room→clarify mapping (button click resolved it)
|
||||
for rid, cid in list(self._room_clarify.items()):
|
||||
if cid == clarify_id:
|
||||
self._room_clarify.pop(rid, None)
|
||||
self._rooms_with_pending_questions.discard(room_id)
|
||||
try:
|
||||
from tools.clarify_gateway import resolve_gateway_clarify
|
||||
resolved = resolve_gateway_clarify(clarify_id, resolved_text)
|
||||
if resolved:
|
||||
logger.info(
|
||||
"[rocketchat] Clarify %s resolved: %s (session=%s)",
|
||||
clarify_id, resolved_text[:60], self._clarify_state.get(clarify_id, "?"),
|
||||
)
|
||||
else:
|
||||
logger.warning("[rocketchat] Clarify %s resolve returned False", clarify_id)
|
||||
except Exception as exc:
|
||||
logger.error("[rocketchat] resolve_gateway_clarify failed: %s", exc)
|
||||
# P-067: Clear Clarify-Modal pulse (user responded with choice)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None and self._presence_engine.is_enabled():
|
||||
self._presence_engine.clear_clarify_modal()
|
||||
# Don't route to agent — this was a button click
|
||||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY resolved — skipping")
|
||||
return
|
||||
else:
|
||||
# Unknown token — let it fall through as regular text
|
||||
logger.warning("[rocketchat] Unknown clarify token: %s", choice)
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] Error processing CLARIFY response: %s", e)
|
||||
|
||||
@@ -3563,7 +3656,20 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
try:
|
||||
if _MULTIROOM() and self.archivar is not None:
|
||||
if is_button_response or room_id in self._rooms_with_pending_questions:
|
||||
# ── Bug 1: Defense-in-Depth — Clarify-Antworten IMMER am
|
||||
# Archivar-Routing vorbeileiten. Wenn eine Clarify-Frage
|
||||
# offen ist, ist die Antwort eine Clarify-Response und darf
|
||||
# NICHT thematisch in einen anderen Raum geroutet werden.
|
||||
# Greift unabhängig vom Format-Pfad (Button-Payload ODER
|
||||
# Plain-Digit-Text) — P-102 asymmetrische Format-Pfade.
|
||||
if self.is_pending_clarify_answer(routing_text, room_id):
|
||||
routing_counter.increment('clarify_answer_bypass')
|
||||
logger.info(
|
||||
"ROUTING BYPASS: reason=clarify_answer_bypass (defense-in-depth), "
|
||||
"origin_room=%s", room_id,
|
||||
)
|
||||
_should_classify = False
|
||||
elif is_button_response or room_id in self._rooms_with_pending_questions:
|
||||
if not is_button_response:
|
||||
logger.debug("[rocketchat] Room %s had pending question — Archivar bypassed", room_id)
|
||||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — pending_questions")
|
||||
@@ -4568,6 +4674,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._explicit_switch_sticky.clear()
|
||||
self._pending_move_requests.clear()
|
||||
self._rooms_with_pending_questions.clear()
|
||||
self._room_clarify.clear()
|
||||
|
||||
# Onboarding-State zurücksetzen falls aktiv
|
||||
if self._onboarding_state:
|
||||
@@ -8105,6 +8212,10 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# Store clarify state for gateway identification
|
||||
self._clarify_state = getattr(self, '_clarify_state', {})
|
||||
self._clarify_state[clarify_id] = session_key
|
||||
|
||||
# Feature 53: Store room→clarify mapping for plain-digit text intercept
|
||||
self._room_clarify = getattr(self, '_room_clarify', {})
|
||||
self._room_clarify[real_room_id] = clarify_id
|
||||
|
||||
# For "Other" button, we need to enable text capture mode
|
||||
# This is done by calling mark_awaiting_text when the user clicks "Other"
|
||||
|
||||
Reference in New Issue
Block a user