Adds native file upload support via Rocket.Chat REST API using the
rooms.media → chat.postMessage 2-step flow, replacing the base-class
fallback that showed '⚠️ Couldn't deliver the file attachment'.
Changes:
- RocketChatREST.upload_file(): multipart/form-data upload to
/api/v1/rooms.media/{room_id}, then chat.postMessage with
title_link + type=file attachment
- RocketChatAdapter.send_document(): resolves real room_id from
virtual chat_id (same logic as send()), delegates to
self.rest.upload_file(), falls back to super().send_document()
on any failure (auth, room resolution, upload error, exception)
Fixes: MEDIA:-prefix file delivery attempts that previously hit
the base-class fallback.
TEIL 1 — booster.py:
- Split _keyword_to_rooms into _kw100_to_rooms + _kwctx_to_rooms
- keywords_100 matched via match_keyword_exact (no fuzzy/stemming, hyphen-insensitive)
- keywords_context matched via match_keyword (fuzzy/stemming preserved)
- _build_mapping() builds both mappings separately
- boost() uses separate matchers per keyword type
- _count_unique_matches() checks both mappings with respective matchers
- _record_matches() now takes only matched_kw100 (context keywords never tracked)
- cleanup_orphaned_rooms() rebuilds both mappings
TEIL 2 — room-map.json (data, not in git):
- Removed 39 space-variant dual keywords (e.g. 'presence engine' removed,
'presence-engine' kept). No longer needed since match_keyword_exact
is hyphen-insensitive.
- Backup: .bak-pre-curation-20260805
Tests: 35/35 passed (pytest -k booster)
Replace naive 'kw in text_lower' substring matching (lines 104-106)
with match_keyword() from keyword_matcher, which provides:
- Strategy 1: Exact substring match (case-insensitive, normalized)
- Strategy 1b: Hyphen-insensitive match ('presence-engine' matches
'Presence Engine' in text)
- Strategy 2: Stemming match (snowballstemmer German)
- Strategy 3: Fuzzy match (Levenshtein)
Changes:
- Import match_keyword from .keyword_matcher
- matched_keywords now uses match_keyword(kw, text) instead of kw in text_lower
- _count_unique_matches: same replacement
- _record_matches: parameter renamed text_lower -> text (no logic change)
- Removed now-unused text_lower = text.lower() line
All 35 booster tests pass.
Root Cause: _apply_counter_delta prüfte subagent_active über alle drei
Counter (delegate_subagent, chat_profile, background_term). on_session_start
feuert bei JEDEM Turn und inkrementiert chat_profile → Puls startete ohne
echten Subagenten.
Fix:
- Puls-Trigger (pulse_counters) prüft NUR delegate_subagent
- chat_profile und background_term zeigen weiterhin AWAY (statisch, ohne Puls)
- _on_pulse_tick und _on_circuit_breaker_expired ebenfalls auf delegate_subagent-only umgestellt
Tests (5 neue):
- test_no_pulse_on_session_start: on_session_start → kein Puls
- test_no_pulse_on_background_term: terminal(bg=true) → kein Puls
- test_pulse_only_on_delegate_subagent: nur delegate_subagent triggert Puls
- test_pulse_stops_when_delegate_done_others_stay: delegate→0 stoppt Puls trotz chat_profile>0
- test_chat_profile_away_no_pulse: chat_profile → AWAY statisch, kein Puls
Alle 77 V9-Tests PASSED, keine Regression.
Root Cause: invoke_hook() im Core ruft Callbacks synchron auf
(ret = cb(**kwargs)). Async-Callbacks wurden als Coroutine-Objekt
zurückgegeben aber nie awaited → Hook-Code wurde NIE ausgeführt.
Symptom: Andreas sah immer nur GRÜN (Hooks registriert, feuerten nie).
Änderungen:
- presence_engine.py: Alle Hook-Callbacks synchron (kein async/await)
- Counter-Mutation unter threading.Lock (statt asyncio.Lock)
- REST-Calls via fire-and-forget Daemon-Threads (statt asyncio.create_task)
- away-grace via threading.Timer (statt asyncio.Task)
- _rest_set_status() synchron (urllib ist von Natur aus sync)
- __init__.py: Wrapper-Funktionen synchron (kein async def)
- adapter.py: bind_loop() für PresenceEngine entfernt (nicht mehr nötig)
- Tests: Alle 39 V9-Tests auf sync umgestellt (kein asyncio, kein await)
Tests: 39 passed, 82 skipped in 3.24s
Tool-Calls die länger als 3s dauern (z.B. große Datei-Operationen,
Web-Scraping) würden den Timer feuern lassen und den Status vorzeitig
auf Grün setzen. 10s sind sicherer: lieber die Antwort schon gepostet
bekommen, als zu früh glauben der Agent sei fertig.
Schachuhr-Prinzip-Analyse: Hermes Core hat tool_start_callback,
stream_delta_callback etc. auf AIAgent-Ebene, aber Plugins haben
keinen Zugriff darauf. send() bleibt das einzige Aktivitätssignal.
10s Debounce ist die beste Lösung ohne Core-Änderung.
PROBLEM:
mark_busy_done im finally-Block von _process_incoming feuert 25ms nach
mark_busy_started — der Status geht auf Grün, während der Agent noch
30-90s arbeitet. Ursache: handle_message() dispatched den Agent
asynchron und kehrt sofort zurück, aber der finally-Block wartet nicht
auf die tatsächliche Agent-Fertigstellung.
LÖSUNG:
Busy-Done-Debounce: Statt sofort mark_busy_done zu rufen, startet der
finally-Block einen 3s-Timer. Jeder send()-Call resettet den Timer.
Erst wenn 3s lang keine Nachricht mehr gesendet wurde, ist der Agent
wirklich fertig und mark_busy_done wird aufgerufen.
ÄNDERUNGEN (adapter.py):
- __init__: _agent_dispatched_this_turn, _busy_done_debounce_task,
_busy_done_debounce_lock
- _process_incoming: Flag-Reset vor mark_busy_started; finally-Block
startet _start_busy_done_debounce() statt sofort mark_busy_done
- _dispatch_agent + main dispatch path: Flag auf True setzen
- send(): _reset_busy_done_debounce() nach erfolgreichem Post
- _send_split(): _reset_busy_done_debounce() pro Chunk
- disconnect(): _cancel_busy_done_debounce()
- Neue Methoden: _start_busy_done_debounce, _busy_done_debounce_timer,
_reset_busy_done_debounce, _cancel_busy_done_debounce
EDGE CASES:
- Kein Agent dispatched (Inline-Command, Onboarding-Guard):
mark_busy_done sofort
- Agent sendet mehrere Nachrichten: Timer wird jedes Mal reset
- Agent sendet Split-Nachrichten: Timer wird pro Chunk reset
- disconnect(): Timer wird gecancelled
ZUSÄTZLICH (presence_engine.py):
pgrep-Block von pid_used/gateway_used/plugin_used entkoppelt —
pgrep läuft jetzt immer (bereits deployed von Bernd).
Bug: _pgrep_hermes_subagents() verlangte arg.endswith('.py') fuer
Python-gestartete hermes-Prozesse. Das schlug fehl bei argv wie
['python3', '/home/bernd/.local/bin/hermes', 'chat', '--profile', 'rainer']
weil 'hermes' ein Binary/Script ohne .py-Endung ist.
Fix: os.path.basename(arg) == 'hermes' statt
'hermes' in basename AND endswith('.py').
Tests: 5 neue Tests in TestPgrepArgvParsing:
- hermes-Binary in argv (Rainers realer Fall)
- generischer Pfad /pfad/zu/hermes
- direktes argv0='hermes'
- -m hermes_cli.main (bestehender Pfad intakt)
- non-hermes Python wird nicht gematcht
Mock _check_gateway_pid_alive=False in 7 tests that test secondary/
tertiary/quaternary detection paths, since the PID-Sentinel (PRIMARY)
now always returns True under pytest (parent process exists).
Production-Impact: none (test-only change)
connect() Z.1936: self._gate_sweep_task durch getattr(self, '_gate_sweep_task', None)
ersetzt. Beim ersten connect()-Aufruf nach Adapter-Instanziierung existiert
_gate_sweep_task noch nicht als Attribut — direkter Zugriff warf AttributeError
und connect() brach ab. disconnect() Z.6519 hatte den hasattr-Check bereits.
Konsistenz mit disconnect(): gleiches getattr-Pattern (Option 1 nach Rainer).
Test: test_connect_fresh_adapter_no_attribute_error
- Marker: @pytest.mark.outbound_gate
- Verifiziert: connect() auf frischem Adapter (ohne _gate_sweep_task) wirft
kein AttributeError und erzeugt _gate_sweep_task korrekt.
- Coverage-Lücke geschlossen (Rainer-Review).
P1a: try/finally in send() und send_clarify() für symmetrisches Gate-Release
- _gate_acquired Flag trackt ob try_acquire den Eintrag erstellt hat
- finally-Block released nur wenn _gate_acquired=True und task_token gesetzt
- Verhindert hängende Gate-Einträge bei Exceptions in send()/send_clarify()
P1b: _gate_sweep_task.cancel() in disconnect()
- Sweep-Loop wird vor _mark_disconnected() gecancelled
- self._running = False gesetzt (Sweep-Loop prüft _running Flag)
- Verhindert dass Sweep-Task nach disconnect() weiterläuft
P1c: Sweep-Task-Check vor Re-create in connect()
- Prüft ob _gate_sweep_task existiert und nicht done() ist
- Cancelled alten Task vor create_task() des neuen
- Verhindert doppelte Sweep-Tasks bei Reconnect
Strategy 3 (Fuzzy/Levenshtein) previously returned True if ANY single
keyword word matched ANY text word. For multi-word keywords like
'hermes-gateway', this caused false 100% matches when only 'hermes'
appeared in text like 'hermes deployment pipeline'.
Fix: ALL keyword words must find a fuzzy match in the text. Single-word
keywords still work (one word must match). Words shorter than
MIN_FUZZY_LEN that reach Strategy 3 cause the keyword to NOT match
(they were already checked by Strategy 1/2).
Added 5 unit tests:
- test_strategy3_multiword_all_words_match
- test_strategy3_multiword_only_one_word_matches (the B-1 scenario)
- test_strategy3_multiword_no_words_match
- test_strategy3_single_word_still_works (regression)
- test_strategy3_multiword_fuzzy_typo
Applied to both match_keyword() and match_keyword_with_stems().
Ref: Rainer's review .hermes/reviews/rainer/test-anpassung-2026-07-29.md
Fix 1 (adapter.py): Bug-C-Logik prüft jetzt OnboardingStateMachine.state
vor clear_onboarding_state(). Wenn SM ACTIVE ist, bleibt archivar_state
leer (produktiver Pfad) statt als Zombie-State verworfen zu werden.
Fix 2 (onboarding_state.py): advance_test() und complete() speichern
jetzt einen 'completed'-Event mit completed_at-Timestamp in step_history
für Audit/Debug.
Fix 3 (onboarding_state.py): load() mappt Legacy-State 'COMPLETED' auf
ACTIVE (Backwards-Kompatibilität für alte YAMLs) statt auf ERROR.
Neue Tests:
- test_restart_preserves_active_state: ACTIVE überlebt simulierten Restart
- test_restart_completed_legacy_migration: COMPLETED → ACTIVE Migration
1347 tests passed, 0 failures.
- Add pytest.importorskip('gateway') to test_message_type_has_command
and test_message_type_no_button_click
- Add import pytest
- Tests now skip gracefully when gateway module is unavailable
instead of failing with ModuleNotFoundError
- Add _sanitize_file_path_component() — strips all chars except [a-zA-Z0-9._-]
- download_file() now sanitizes file_id and filename before URL construction
- URL-encode path components with urllib.parse.quote()
- Response size cap: read in 64KB chunks, stop at max_size (default 10MB)
- Reject downloads when sanitized file_id or filename is empty
- Add 10 new tests in test_p1_fb08_file_security.py (all green)
- No regressions: 578 archivar tests pass, 82 top-level tests pass
Bug: Nach Auto-Route + Widerspruch ging die 2. send()-Antwort in den
falschen Raum (Auto-Route-Ziel statt Ursprungsraum).
Root Cause: _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen
stale Wert vom Parent-Task erben (Auto-Route-copy_context). send()
Priority 0 verwendete diesen Wert blind, ohne den Task-Token gegen
_room_context zu validieren.
Fix:
- send() Priority 0: Pre-Read-Validierung — _CURRENT_TASK_TOKEN
gegen _room_context[chat_id]['task_token'] prüfen. Bei Mismatch
Priority 0 skippen, normale ContextVar-Logik weiterlaufen lassen.
- send_clarify() Priority 0: analoge Validierung.
- Telemetrie: routing_counter.increment('priority0_token_mismatch_skip')
bei jedem Mismatch.
- Backward-Compat: _room_context-Einträge ohne task_token werden wie
'kein Token' behandelt (Priority 0 greift normal).
Tests (6 neu, alle grün):
- test_send_priority0_token_match
- test_send_priority0_token_mismatch
- test_send_priority0_no_stored_token
- test_send_clarify_token_mismatch
- test_auto_route_then_widerspruch_answer_in_origin (E2E)
- test_priority0_mismatch_telemetry
Keine Änderungen an _set_room_context_origin / _get_room_context_origin
oder den 10 _CURRENT_ORIGIN_ROOM.set-Stellen.