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
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)
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
Problem: _room_context speichert nur EINEN origin_room pro chat_id.
Wenn ein User gleichzeitig in 2 Räumen aktiv ist, überschreibt der
letzte Dispatch den anderen. Antwort landet im falschen Raum.
Stufe 1 — Task-Token:
- _room_context[chat_id] bekommt task_token (UUID4) + timestamp (ISO)
- _set_room_context_origin() generiert Token, setzt _CURRENT_TASK_TOKEN
- _get_room_context_origin() validiert: Token-Match → verwenden;
Token-Mismatch → Cross-Contamination → ignorieren
- _dispatch_agent() ruft _set_room_context_origin() vor copy_context()
auf, damit der Drain-Task das korrekte Token eingefroren bekommt
Stufe 2 — TTL-Sweep:
- Einträge älter als 30 Min werden von _get_room_context_origin()
ignoriert (log Warning "stale room_context entry")
- Backward-Kompatibilität: alte Einträge ohne timestamp/task_token
werden trotzdem verwendet
Tests (10 neue, 20 total in test_v8_1_p1_contextvar.py):
- Token-Match / Token-Mismatch / Cross-Contamination
- Stream-Retry mit Token / ohne Token (TTL gültig)
- TTL abgelaufen → Fallback auf nächste Priorität
- Backward-Kompatibilität für alte Einträge
- _set_room_context_origin generiert UUID4 + ISO-Timestamp
Baseline: 1335 passed, 3 pre-existing failures, 2 skipped
After: 1345 passed, 3 pre-existing failures, 2 skipped
Root Cause: Der else-Zweig (Button 2/3: stay_here/stay_once) in
_process_incoming loggte nur "skipping" und returnte, ohne die
Originalnachricht aus move_req["text"] an den Agenten weiterzuleiten.
Da der move_request_pending_guard den initialen Dispatch blockiert,
war die Nachricht NUR in move_req["text"] verfügbar — nach dem
pop() war sie komplett verloren.
Fix:
- else-Zweig holt origin_text aus move_req.get("text", "")
- Bei leerem Text: logger.warning + return (kein Dispatch)
- Setzt _CURRENT_ORIGIN_ROOM auf room_id (User bleibt im Ursprungsraum)
- _THEMATIC_TARGET_ROOM wird NICHT gesetzt (kein Themenwechsel)
- Dispatch via _dispatch_agent mit room_id=Ursprungsraum, category="work_order"
- Telemetrie-Counter "stay_here_dispatched" wird incrementiert
Tests: 3 neue Tests in test_p0_stay_here_dispatch.py
- test_stay_here_dispatches_original_message
- test_stay_once_dispatches_original_message
- test_stay_here_empty_text_skips_dispatch
Ergebnis: 1330 passed, 3 pre-existing failures, 2 skipped
E1: Lock-Scope in increment_background_tasks und decrement_background_tasks
erweitert — _persist_plugin_state wird jetzt unter _background_tasks_lock
aufgerufen. Verhindert dass bei zwei konkurrierenden Threads ein veralteter
Count persistiert wird.
E2: Concurrency-Test für _write_plugin_state — zwei Threads schreiben
parallel, danach wird verifiziert dass die Datei gültiges JSON enthält
(keine halbe Datei, kein korruptes JSON, keine .tmp-Leichen).
FIX A — Save-Robustheit (room_map.py):
- TOCTOU-Schutz: fcntl.flock(LOCK_EX) wird VOR dem Lesen erworben,
nicht erst beim Schreiben. Eliminiert Race zwischen parallelen
save()-Aufrufen.
- ID-Set-Differenz statt Count-Vergleich: Disk-IDs müssen Teilmenge
von In-Memory-IDs sein (disk_room_ids.issubset(mem_room_ids)).
Verhindert dass Maps mit gleicher Raum-Anzahl aber anderen IDs
die Disk überschreiben.
- Backup-Mechanismus: Vor jedem Schreiben wird die existierende
Datei nach '<path>.bak' kopiert (atomic via os.replace).
- force=True Parameter für administrative Aufrufe (Onboarding-Reset),
die den Guard bewusst umgehen.
- Modul-Level-Helfer: _acquire_flock() (Retry-Loop, thread-safe)
und _create_backup() (atomic copy2 + os.replace).
FIX B — Single-Room-Pfad-Härtung (onboarding.py):
- Pre-Mutation-Snapshot: Vor add_or_update_room() wird die
Disk-Datei nach '<path>.onboarding_bak' gesichert.
- Post-Mutation-Integritätsprüfung nach save()+reload():
1. Raum-Anzahl >= pre_mutation_count + 1?
2. Existiert der ursprüngliche catch_all-Raum noch?
Bei Fehler → automatisches Rollback aus Backup + Critical-Log.
- Telemetrie-Counter: single_room_catch_all_overwrite_attempted
und single_room_catch_all_rolled_back.
Tests (test_single_room_refuse_guard.py, 10 Tests):
(a) Refuse-Guard triggert bei ID-Differenz + Backup wird geschrieben
(b) Konkurrierende save()-Aufrufe via threading → nur einer schreibt
(c) Rollback aus .bak-Datei nach Korruption
(d) Single-Room-Pfad Integritätsprüfung + Rollback
Baseline: 1297 passed, 3 pre-existing failures (unverändert)
Nach Fix: 1307 passed, 3 pre-existing failures (10 neue Tests grün)