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:
Bernd (Hermes)
2026-08-23 17:41:39 +02:00
parent e8852fc2be
commit cb9fd1c032
2 changed files with 411 additions and 51 deletions
+115 -4
View File
@@ -1352,6 +1352,9 @@ class RocketChatAdapter(BasePlatformAdapter):
# The router's _check_never_route_topic handles per-topic blocking now. # The router's _check_never_route_topic handles per-topic blocking now.
# Clarify state: maps clarify_id → session_key for gateway resolution # Clarify state: maps clarify_id → session_key for gateway resolution
self._clarify_state: Dict[str, str] = {} 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 # FIX 2 (P0): ISSUE 3 — Pending Clarify Dispatch Slot
# {room_id: {text, username, msg_id, msg_obj, is_button_response}} # {room_id: {text, username, msg_id, msg_obj, is_button_response}}
self._pending_clarify_dispatch: Dict[str, dict] = {} self._pending_clarify_dispatch: Dict[str, dict] = {}
@@ -2423,6 +2426,40 @@ class RocketChatAdapter(BasePlatformAdapter):
reason = "sm_completed" if sm_completed else "not_completed" reason = "sm_completed" if sm_completed else "not_completed"
return (sm_completed, operator_room_id, reason) 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: async def _reconnect_ddp(self) -> bool:
"""Bug 7: DDP-Reconnect mit M13 GC. """Bug 7: DDP-Reconnect mit M13 GC.
@@ -2811,26 +2848,75 @@ class RocketChatAdapter(BasePlatformAdapter):
return return
# ── Ende Thema B Onboarding-Guard ──────────────────────────────────── # ── 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 ─────────────────────────────────── # ── CLARIFY Response Handling ───────────────────────────────────
# Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other # Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other
# V8.2.1 A2: Handle ARCHIVAR_CLARIFY (Nachklärung) responses # 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:"): if is_clarify_response and text.startswith("CLARIFY:"):
routing_counter.increment('clarify_answer_bypass') routing_counter.increment('clarify_answer_bypass')
logger.info("ROUTING BYPASS: reason=clarify_answer_bypass, origin_room=%s", room_id) logger.info("ROUTING BYPASS: reason=clarify_answer_bypass, origin_room=%s", room_id)
try: try:
# ── Format-Extraktion (gemeinsam für alt und neu, Feature 55) ──
if "::" in text: if "::" in text:
# Neues Format: CLARIFY:<id>::<choice> (via _build_custom_buttons) # Neues Format: CLARIFY:<id>::<choice> (via _build_custom_buttons)
prefix_part, choice = text.split("::", 1) prefix_part, choice = text.split("::", 1)
clarify_id = prefix_part.split(":", 1)[1] clarify_id = prefix_part.split(":", 1)[1]
else: else:
# Altes Format: CLARIFY:<id>:other (Other-Button) # Altes Format: CLARIFY:<id>:<token>
parts = text.split(":", 2) parts = text.split(":", 2)
if len(parts) != 3: if len(parts) != 3:
logger.debug("[rocketchat] Unrecognized CLARIFY format: %s", text) logger.debug("[rocketchat] Unrecognized CLARIFY format: %s", text)
logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY unrecognized format — skipping") logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY unrecognized format — skipping")
return return
_, clarify_id, choice = parts _, clarify_id, choice = parts
# ── Gemeinsame Verarbeitung (beide Formate) ──
if choice == "other": if choice == "other":
# For "Other" button, enable text capture mode # For "Other" button, enable text capture mode
from tools.clarify_gateway import mark_awaiting_text from tools.clarify_gateway import mark_awaiting_text
@@ -2844,7 +2930,9 @@ class RocketChatAdapter(BasePlatformAdapter):
return return
elif choice.isdigit(): elif choice.isdigit():
# Numeric choice → resolve the clarify immediately # Numeric choice → resolve the clarify immediately
idx = int(choice) # 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 resolved_text: Optional[str] = None
try: try:
from tools.clarify_gateway import _entries as _clarify_entries from tools.clarify_gateway import _entries as _clarify_entries
@@ -2858,6 +2946,11 @@ class RocketChatAdapter(BasePlatformAdapter):
resolved_text = f"choice {idx + 1}" resolved_text = f"choice {idx + 1}"
# Resolve via gateway and clean up # Resolve via gateway and clean up
self._clarify_state.pop(clarify_id, None) 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: try:
from tools.clarify_gateway import resolve_gateway_clarify from tools.clarify_gateway import resolve_gateway_clarify
resolved = resolve_gateway_clarify(clarify_id, resolved_text) resolved = resolve_gateway_clarify(clarify_id, resolved_text)
@@ -3563,7 +3656,20 @@ class RocketChatAdapter(BasePlatformAdapter):
try: try:
if _MULTIROOM() and self.archivar is not None: 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: if not is_button_response:
logger.debug("[rocketchat] Room %s had pending question — Archivar bypassed", room_id) logger.debug("[rocketchat] Room %s had pending question — Archivar bypassed", room_id)
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — pending_questions") logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — pending_questions")
@@ -4568,6 +4674,7 @@ class RocketChatAdapter(BasePlatformAdapter):
self._explicit_switch_sticky.clear() self._explicit_switch_sticky.clear()
self._pending_move_requests.clear() self._pending_move_requests.clear()
self._rooms_with_pending_questions.clear() self._rooms_with_pending_questions.clear()
self._room_clarify.clear()
# Onboarding-State zurücksetzen falls aktiv # Onboarding-State zurücksetzen falls aktiv
if self._onboarding_state: if self._onboarding_state:
@@ -8106,6 +8213,10 @@ class RocketChatAdapter(BasePlatformAdapter):
self._clarify_state = getattr(self, '_clarify_state', {}) self._clarify_state = getattr(self, '_clarify_state', {})
self._clarify_state[clarify_id] = session_key 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 # For "Other" button, we need to enable text capture mode
# This is done by calling mark_awaiting_text when the user clicks "Other" # This is done by calling mark_awaiting_text when the user clicks "Other"
# The actual implementation will be in the message handling logic # The actual implementation will be in the message handling logic
@@ -0,0 +1,249 @@
"""
P-102: Clarify-Button-Parsing + Defense-in-Depth (Bug 2 + Bug 1).
Root Cause (Rainer):
- Bug 2: CLARIFY:ad37e4528a:1 kam als roher Text durch, wurde nicht als
Auswahl "1" = erste Choice erkannt. Zwei Ursachen:
(a) Off-by-one: Button-Payload ist 1-basiert (send_clarify: idx = i+1),
aber der Handler nutzte `idx = int(choice)` (0-basiert erwartet).
"1" → idx=1 → zweite Choice statt erste.
(b) Feature 53 (Plain-Digit-Intercept) war entfernt worden — `_room_clarify`
existierte nicht mehr, Plain-Digit "1" wurde nie als Clarify-Antwort
erkannt.
- Bug 1: Archivar griff Clarify-Responses ab und routete sie thematisch.
Defense-in-Depth: is_pending_clarify_answer als Bypass-Trigger VOR dem
Archivar-Routing.
Tests:
1. is_pending_clarify_answer erkennt CLARIFY:-Payload (beide Formate)
2. is_pending_clarify_answer erkennt Plain-Digit in Raum mit offener Frage
3. is_pending_clarify_answer lehnt normale Nachrichten ab
4. Off-by-one: CLARIFY:<id>:1 mappt auf choices[0] (erste Choice)
"""
from __future__ import annotations
import asyncio
import json
import os
import sys
import tempfile
import threading
import unittest
from pathlib import Path
from unittest.mock import MagicMock, AsyncMock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
def _make_room_map_json(tmpdir: str) -> str:
rooms = {
"room_a": {
"name": "#Raum-A",
"theme": "Raum A",
"keywords_100": ["thema-a"],
"keywords_context": [],
"catch_all": False,
},
"room_b": {
"name": "#Raum-B",
"theme": "Raum B",
"keywords_100": ["thema-b"],
"keywords_context": [],
"catch_all": False,
},
}
data = {
"version": 5,
"rooms": rooms,
"excluded_rooms": [],
"butler_mode": "cognitive",
"fact_store_path": str(Path(tmpdir) / "docs"),
}
map_path = Path(tmpdir) / "room-map.json"
with open(map_path, "w") as f:
json.dump(data, f)
return str(map_path)
def _build_mock_adapter(room_map_path: str):
os.environ["MULTIROOM_AGENT"] = "true"
os.environ["ARCHIVAR_ROOM_MAP_PATH"] = room_map_path
os.environ["ARCHIVAR_STATE_PATH"] = "/tmp/archivar_test_p102_state.json"
os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com"
os.environ["ROCKETCHAT_USER"] = "testbot"
os.environ["ROCKETCHAT_PASSWORD"] = "testpass"
try:
os.remove("/tmp/archivar_test_p102_state.json")
except FileNotFoundError:
pass
from plugin.adapter import RocketChatAdapter, RocketChatREST
from archivar.conversation_history import ConversationHistory
from archivar.multiroom_context import MultiRoomContextRing
from archivar.adapter_integration import ArchivarMessageHandler
from archivar.room_map import RoomMap
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
adapter.config = MagicMock()
adapter.config.extra = {}
adapter.platform = "rocketchat"
adapter.base_url = os.getenv("ROCKETCHAT_BASE_URL", "")
adapter.user = os.getenv("ROCKETCHAT_USER", "")
adapter.password = os.getenv("ROCKETCHAT_PASSWORD", "")
adapter.rest = RocketChatREST(adapter.base_url)
adapter.ddp = None
adapter._auth_token = None
adapter._user_id = None
adapter._rooms = []
adapter._subscribed_rooms = set()
adapter._listen_task = None
adapter._status_timer = None
adapter._last_activity = 0.0
adapter._shutdown_event = threading.Event()
adapter._room_info = {
"room_a": {"name": "Raum-A", "type": "c"},
"room_b": {"name": "Raum-B", "type": "c"},
}
adapter._pending_clarifies = {}
adapter._user_rooms = {}
adapter._rooms_with_pending_questions = set()
adapter._excluded_room_ids = set()
adapter._last_server_activity = 0.0
adapter._health_check_timer = None
adapter._last_ddp_ping_ok = False
adapter._running = False
adapter._conversation_history = ConversationHistory(max_size=10)
adapter._multiroom_context = MultiRoomContextRing(max_entries=20)
adapter.archivar = ArchivarMessageHandler.__new__(ArchivarMessageHandler)
adapter.archivar._room_map = RoomMap.load(Path(room_map_path))
adapter.archivar._stats = {"onboarding_active": False}
adapter.archivar._state = MagicMock()
adapter.archivar._state.should_stay_in_room = MagicMock(return_value=None)
adapter.archivar._state.update_stay_tracker = MagicMock(return_value=0)
adapter.archivar._state.set_never_route = MagicMock()
adapter.archivar._state.set_ring_state = MagicMock()
adapter.archivar._state.get_onboarding_state = MagicMock(return_value={})
adapter.archivar._state.clear_onboarding_state = MagicMock(return_value=True)
adapter.archivar._should_trigger_nachklaerung = MagicMock(return_value=True)
adapter.archivar._get_nachklaerung_buttons = MagicMock(return_value={
"text": "Warum bleibst du hier?",
"actions": [],
})
adapter.archivar.handle_feedback_response = AsyncMock()
adapter.archivar.classify_and_route = AsyncMock(return_value=(None, None, None))
adapter._onboarding_sm = MagicMock()
adapter._onboarding_sm.state = MagicMock()
adapter._onboarding_sm.state.value = "ACTIVE"
adapter._onboarding_sm._data = MagicMock()
adapter._onboarding_sm._data.operator_room_id = ""
adapter._onboarding_state = {}
adapter._pending_clarify_dispatch = {}
adapter._pending_move_requests = {}
adapter._session_room_preferences = {}
adapter._recent_auto_routes = {}
adapter._clarify_state = {}
adapter._room_clarify = {}
adapter._presence_engine = None
adapter._post_message_with_retry = AsyncMock(return_value="msg_sent_001")
adapter._send_archivar_buttons = AsyncMock()
adapter._dispatch_agent = AsyncMock()
adapter._process_onboarding_response = AsyncMock()
return adapter
class TestP102ClarifyParsing(unittest.TestCase):
"""P-102: Clarify-Button-Parsing + Defense-in-Depth."""
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self.room_map_path = _make_room_map_json(self.tmpdir)
self.adapter = _build_mock_adapter(self.room_map_path)
def tearDown(self):
import shutil
shutil.rmtree(self.tmpdir, ignore_errors=True)
try:
os.remove("/tmp/archivar_test_p102_state.json")
except FileNotFoundError:
pass
# ── is_pending_clarify_answer ──────────────────────────────────────
def test_pending_clarify_detects_button_payload_single_colon(self):
"""CLARIFY:<id>:<idx> (altes Format) wird als Clarify-Antwort erkannt."""
self.assertTrue(
self.adapter.is_pending_clarify_answer("CLARIFY:ad37e4528a:1", "room_a")
)
def test_pending_clarify_detects_button_payload_double_colon(self):
"""CLARIFY:<id>::<idx> (neues Format) wird als Clarify-Antwort erkannt."""
self.assertTrue(
self.adapter.is_pending_clarify_answer("CLARIFY:ad37e4528a::1", "room_a")
)
def test_pending_clarify_detects_plain_digit_in_pending_room(self):
"""Plain-Digit '1' in Raum mit offener Frage wird erkannt (Feature 53)."""
self.adapter._room_clarify["room_a"] = "clarify_xyz"
self.assertTrue(
self.adapter.is_pending_clarify_answer("1", "room_a")
)
def test_pending_clarify_rejects_plain_digit_without_pending(self):
"""Plain-Digit '1' OHNE offene Frage wird NICHT erkannt."""
self.assertFalse(
self.adapter.is_pending_clarify_answer("1", "room_a")
)
def test_pending_clarify_rejects_normal_text(self):
"""Normale Nachricht wird NICHT als Clarify-Antwort erkannt."""
self.assertFalse(
self.adapter.is_pending_clarify_answer(
"Kannst du mir die Doku zeigen?", "room_a"
)
)
def test_pending_clarify_rejects_empty(self):
"""Leere Nachricht wird NICHT erkannt."""
self.assertFalse(self.adapter.is_pending_clarify_answer("", "room_a"))
self.assertFalse(self.adapter.is_pending_clarify_answer(None, "room_a"))
# ── Off-by-one: Button-Payload mappt auf erste Choice ──────────────
def test_button_payload_1_maps_to_first_choice(self):
"""CLARIFY:<id>:1 muss auf choices[0] mappen (nicht choices[1]).
Der Button-Payload ist 1-basiert (send_clarify: idx = i + 1).
Der Handler muss `idx = int(choice) - 1` rechnen, sonst wird
"1" fälschlich als zweite Choice interpretiert.
"""
clarify_id = "ad37e4528a"
choices = ["Option A", "Option B", "Option C"]
# Simuliere die Handler-Logik (idx = int(choice) - 1)
choice = "1"
idx = int(choice) - 1
self.assertEqual(idx, 0)
self.assertEqual(choices[idx], "Option A")
# Regression: der alte Bug (idx = int(choice)) hätte idx=1 geliefert
self.assertNotEqual(int(choice), 0)
def test_button_payload_2_maps_to_second_choice(self):
"""CLARIFY:<id>:2 mappt auf choices[1]."""
choices = ["Option A", "Option B", "Option C"]
idx = int("2") - 1
self.assertEqual(idx, 1)
self.assertEqual(choices[idx], "Option B")
if __name__ == "__main__":
unittest.main()