Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
chore: auto-save WIP via Claude stop-hook safety net (2026-07-11 11:57)
Ruben Lütkee047391db021
diff --git a/codex-realtime-duplicate-response-event.md b/codex-realtime-duplicate-response-event.mdnew file mode 100644index 0000000000..bc5d419f73--- /dev/null+++ b/codex-realtime-duplicate-response-event.md@@ -0,0 +1,70 @@+# Codex Handoff — Fix: duplicate `ResponseGenerated` per delegated realtime turn++Repo: `C:\Users\Administrator\Desktop\Personal Jarvis` (Personal Jarvis). Read `CLAUDE.md`/`AGENTS.md` first — its rules are binding (English-only artifacts, shared working tree, no push).++<task>+In realtime voice mode with the default delegate tool mode (`voice.realtime_tool_mode = "delegate"`), ONE user turn publishes the `ResponseGenerated` bus event TWICE:++1. The realtime session's `jarvis_action` tool call spawns a background delegate (`jarvis/realtime/session.py:825-910`) that runs a full router-brain turn via `BrainManager.generate(...)`. `generate` publishes `ResponseGenerated` itself when the turn completes (`jarvis/brain/manager.py:5834` and `:7620` — two generate paths; there is also a canned-phrase publish at `:2669`).+2. When the provider signals `turn_complete`, the realtime session publishes `ResponseGenerated` AGAIN in `_publish_turn_completed` (`jarvis/realtime/session.py:719-726`) — this time with the realtime model's spoken paraphrase, which may DIFFER textually from the brain's reply.++Downstream consumers therefore see two assistant replies for one turn: `jarvis/memory/message_recorder.py` (recall log — duplicate rows), `jarvis/awareness/story.py::StoryTracker._on_response_generated` (~`:287`, duplicate L2 episode markers), `jarvis/sessions/recorder.py:246` (benign — `VoiceTurnCompleted` values win), `jarvis/memory/wiki/voice_bridge.py:233` (currently no-ops in realtime because no user-text event pairs, but a realtime→wiki feed is being built in a parallel session — double-fire must not survive into that world).++Goal: **exactly ONE `ResponseGenerated` per user turn**, in every mode:+- Realtime + delegate, turn WITH a completed `jarvis_action` call → one event (decide which of the two is canonical — see design notes).+- Realtime + delegate, pure conversational turn (no tool call) → the session's publish stays (it is the only one).+- Realtime + direct tool mode → unchanged (session publish is the only one).+- Classic pipeline mode → completely unchanged (`generate`'s publish drives existing hooks: `MessageRecorder`, `VoiceFactBridge` pairing, `StoryTracker`).++Design notes (recommendation, verify before adopting): suppressing the SESSION's publish for turns whose answer came from a completed delegate is the least invasive option — the brain's publish must survive because pipeline-mode hooks key on it, and threading a `publish_response=False` flag through `generate` risks touching the shared brain path. But you own the final call; whichever side you silence, `VoiceTurnCompleted` (`session.py:727-741`) must still carry the ACTUALLY SPOKEN text in `jarvis_text`.++Edge cases that must be handled and tested:+- Delegate TIMEOUT (`_DELEGATE_TIMEOUT_S`, `session.py:849-874`): if the awaited `generate` task keeps running past the timeout and publishes late, do not end up with zero OR two events for the turn — check whether the timed-out task is cancelled and define the behavior.+- Multiple `jarvis_action` calls inside one turn.+- Delegate failure path (`:877-887`) — the model speaks an error; the session publish must then still fire (the brain never published).+- Turn where the delegate completed but the realtime model spoke an EMPTY answer (`answer` falsy at `session.py:719`) — today that publishes nothing from the session; make sure the invariant "exactly one" still holds.+</task>++<key_files>+- `jarvis/realtime/session.py` — `_start_delegate`, `_run_delegate`, `_dispatch_brain_turn` (`:825-910`), `_publish_turn_completed` (`:709-747`), turn state fields+- `jarvis/brain/manager.py` — `ResponseGenerated` publishes (`:2669`, `:5834`, `:7620`) and `_record_response_side_effects`+- Consumers: `jarvis/memory/message_recorder.py`, `jarvis/awareness/story.py`, `jarvis/sessions/recorder.py`, `jarvis/memory/wiki/voice_bridge.py`+- Existing tests: `tests/unit/realtime/` (delegate-mode tests), `tests/unit/memory/` for the recorder+</key_files>++<constraints>+- CLAUDE.md is binding: everything you commit is English; Conventional Commit messages; NEVER push; the working tree is SHARED with other live agent sessions — stage only your own files by explicit path (never `git add -A`/`git add .`), commit after each completed logical step.+- Do NOT change the `VoiceTurnCompleted` event shape or the meaning of its `user_text`/`jarvis_text` fields — a parallel session is building the realtime→wiki memory feed on exactly that event. A separate Codex session hardens transcript persistence (`SessionRecorder`); stay out of its scope.+- Classic pipeline behavior must be bit-for-bit unchanged; guard tests in `tests/unit/brain/` must stay green.+- EventBus rules: frozen event dataclasses, subscriber errors never propagate (AP-18); nothing heavy on the voice hot path (AP-9).+- Cross-platform: tests must run on headless Linux; use fakes from `tests/fakes/`, not `unittest.mock`.+</constraints>++<default_follow_through_policy>+Default to the most reasonable low-risk interpretation and keep going. Only stop when a missing detail changes correctness or an irreversible action.+</default_follow_through_policy>++<completeness_contract>+Resolve the task fully before stopping: cover all listed modes and edge cases with tests asserting the exactly-one invariant. Do not stop at the first plausible fix.+</completeness_contract>++<verification_loop>+Before finalizing: run `tests/unit/realtime/`, `tests/unit/brain/` and the touched consumer test modules; run `ruff check` on changed files. If a check fails, fix it instead of reporting the first draft.+</verification_loop>++<grounding_rules>+Ground every claim in file:line evidence or test output. If a behavior (e.g. the timeout/late-publish path) turns out different from described above, say so and adapt — do not force the described fix onto contrary evidence.+</grounding_rules>++<action_safety>+Keep changes tightly scoped to the duplicate-event invariant. No unrelated refactors.+</action_safety>++<structured_output_contract>+Return, in order:+1. Chosen design (which publish is canonical per mode) + why, with evidence.+2. Fixes applied (files + one-line rationale each).+3. Tests added (names + which invariant/edge case each locks).+4. Test/lint run output summary.+5. Commits made.+</structured_output_contract>diff --git a/codex-realtime-transcript-guarantee.md b/codex-realtime-transcript-guarantee.mdnew file mode 100644index 0000000000..cbca8f4576--- /dev/null+++ b/codex-realtime-transcript-guarantee.md@@ -0,0 +1,67 @@+# Codex Handoff — Guarantee: Realtime voice mode ALWAYS keeps a transcript++Repo: `C:\Users\Administrator\Desktop\Personal Jarvis` (Personal Jarvis). Read `CLAUDE.md`/`AGENTS.md` first — its rules are binding (English-only artifacts, shared working tree, no push).++<task>+Personal Jarvis has two voice engines: the classic pipeline (STT→Brain→TTS) and the realtime engine (duplex sessions, `jarvis/realtime/`). The maintainer is making realtime the primary engine and needs a hard guarantee: **every realtime conversation turn — on BOTH surfaces (desktop and browser), with EVERY realtime provider (gemini-live, openai-realtime), in BOTH tool modes (`voice.realtime_tool_mode` = "delegate" default, "direct") — lands as a complete row (user_text + jarvis_text) in the sessions.db transcript store** (`jarvis/sessions/store.py`, consumed by the Transcription/Run-Inspector UI).++Current wiring (verified 2026-07-11, treat as starting evidence, re-verify yourself):+- The transcript store is fed by `SessionRecorder` (`jarvis/sessions/recorder.py`), a wildcard bus subscriber. Hard gate: `recorder.py:220` drops ALL events while `self._state is None`; state is only created by a `VoiceSessionStarted` event (`recorder.py:204`).+- The realtime session (`jarvis/realtime/session.py`) publishes `VoiceSessionStarted`/`VoiceSessionEnded` ONLY on the browser surface (guard at `session.py:302-303`, end guard ~`:1042`). It publishes `VoiceTurnStarted` (`:692`) and `VoiceTurnCompleted` with `user_text`/`jarvis_text`/`tier="realtime"` (`:709-747`) unconditionally.+- On desktop, the pipeline session loop wraps the realtime session: it publishes `VoiceSessionStarted` itself (`jarvis/speech/pipeline.py:4919-4926`), then enters `_active_realtime_session()` (`pipeline.py:5098`, impl `:5248`) and passes the SAME `session_id` into the realtime session (`pipeline.py:5316`). So the happy path appears covered by design.++Your job: prove or break that guarantee end-to-end, fix every REAL gap you find, and lock the guarantee with regression tests so it cannot silently regress. Candidate gaps to probe (non-exhaustive — probe beyond this list):+1. Turns where the provider never delivers a final user transcript (`_last_user_text` empty) or never delivers `turn_complete` — is a row still written / finalized? What happens on hangup mid-turn, provider error, provider-family failover mid-session (`session._open` retry chain)?+2. `recorder._on_turn_completed` (`recorder.py:364`) ignores the event when `current_turn.turn_id != event.turn_id` — can realtime turn-id sequencing (turn started on first FINAL input transcript, `session.py:441-444`; reset at `:744`) ever desync from the recorder's `_ensure_turn_open`/auto-close logic?+3. Browser surface: `jarvis/browser_voice/route.py` — same guarantee holds there (session start/end published, turns finalized on socket drop)?+4. Session end: desktop publishes `VoiceSessionEnded` in the pipeline's `finally` (`pipeline.py:4990`) — verify open turns are finalized, not orphaned.+5. Raw event visibility: check `_RAW_EVENT_KINDS` (`recorder.py:70-108`) records enough realtime events (`RealtimeSessionReady`, `TranscriptionUpdate`?) for the Run-Inspector to be useful.+If a probed gap turns out NOT to exist, say so with evidence instead of inventing a fix.+</task>++<key_files>+- `jarvis/realtime/session.py` — session lifecycle, `_pump`, `_publish_turn_started/_publish_turn_completed`, browser-gated session events+- `jarvis/speech/pipeline.py:4895-5010` (session loop + VoiceSessionStarted/Ended), `:5248-5400` (`_active_realtime_session`)+- `jarvis/sessions/recorder.py` + `jarvis/sessions/store.py` + `jarvis/sessions/init.py`+- `jarvis/browser_voice/route.py` (browser surface)+- `jarvis/core/events.py` (`VoiceSessionStarted`, `VoiceTurnStarted`, `VoiceTurnCompleted`, `TranscriptionUpdate`)+- Existing tests: `tests/unit/sessions/`, anything matching `test_*recorder*`, `tests/unit/realtime/`+</key_files>++<constraints>+- CLAUDE.md is binding: everything you commit is English; Conventional Commit messages; NEVER push; the working tree is SHARED with other live agent sessions — stage only your own files by explicit path (never `git add -A`/`git add .`), commit after each completed logical step.+- Do NOT change the `VoiceTurnCompleted` event shape or the meaning of its `user_text`/`jarvis_text`/`tier` fields — a parallel session is building the realtime→wiki memory feed on exactly that event.+- A separate Codex session is fixing the duplicate `ResponseGenerated` publish in delegate mode — do not touch that; your scope is transcript persistence only.+- EventBus rules: subscribers must never propagate exceptions (AP-18); events are frozen dataclasses carrying `trace_id`+`timestamp_ns`.+- Nothing heavy on the voice hot path (AP-9) and nothing on the boot critical path (AP-26).+- Cross-platform: fixes and tests must run on Windows, macOS, and headless Linux (`python:3.11-slim`, no audio) — tests use fakes from `tests/fakes/`, never real audio devices, never `unittest.mock` per repo convention.+</constraints>++<default_follow_through_policy>+Default to the most reasonable low-risk interpretation and keep going. Only stop when a missing detail changes correctness or an irreversible action.+</default_follow_through_policy>++<completeness_contract>+Resolve the task fully before stopping: verify all four surface/provider/tool-mode combinations conceptually, fix every confirmed gap, and add the regression tests. Do not stop at the first plausible answer.+</completeness_contract>++<verification_loop>+Before finalizing: run the touched test modules plus `tests/unit/sessions/` and `tests/unit/realtime/` (`pytest -m "not slow"` subset is acceptable), and `ruff check` on changed files. If a check fails, fix it instead of reporting the first draft.+</verification_loop>++<grounding_rules>+Ground every claim in file:line evidence or test output. If a gap is a hypothesis you could not reproduce, label it clearly instead of "fixing" it.+</grounding_rules>++<action_safety>+Keep changes tightly scoped to transcript persistence. No unrelated refactors or renames.+</action_safety>++<structured_output_contract>+Return, in order:+1. Verdict per candidate gap (real / not real) with file:line evidence.+2. Fixes applied (files + one-line rationale each).+3. Regression tests added (test names + what each locks).+4. Test/lint run output summary.+5. Commits made.+</structured_output_contract>diff --git a/tests/unit/memory/wiki/test_voice_bridge_realtime.py b/tests/unit/memory/wiki/test_voice_bridge_realtime.pynew file mode 100644index 0000000000..56a597d885--- /dev/null+++ b/tests/unit/memory/wiki/test_voice_bridge_realtime.py@@ -0,0 +1,254 @@+"""Realtime turns feed the wiki journal via ``VoiceTurnCompleted``.++The realtime engine never emits ``TranscriptFinal``/``MessageSent`` — the+pairing path in :class:`VoiceFactBridge` stays silent for it. The one event+that carries BOTH final texts of a realtime turn is ``VoiceTurnCompleted``+(``jarvis/realtime/session.py::_publish_turn_completed``). These tests pin+the bridge's realtime ingest contract:++1. A realtime turn (tier="realtime") flows extractor -> journal via the+ aggressive path (salience filter downstream, AP-9 fire-and-forget).+2. An ack-keyword reply uses the ack path even below the aggressive+ min-chars threshold.+3. Pipeline-tier ``VoiceTurnCompleted`` events are IGNORED here — those+ turns are already ingested via the TranscriptFinal/ResponseGenerated+ pairing; reacting twice would double-extract every pipeline turn.+4. The same realtime turn delivered twice is journaled once (hash gate).+5. Empty user transcript -> no ingest; empty reply does NOT block the+ aggressive path (the fact lives in the user text).+6. Aggressive ingests stay rate-limited across realtime turns.+"""+from __future__ import annotations++import asyncio+import json+import time+from collections.abc import AsyncIterator+from pathlib import Path+from typing import Any++import pytest++from jarvis.core.bus import EventBus+from jarvis.core.config import (+ BrainConfig,+ BrainProviderConfig,+ JarvisConfig,+ MemoryConfig,+ WikiMemoryConfig,+)+from jarvis.core.events import VoiceTurnCompleted+from jarvis.core.protocols import BrainDelta, BrainRequest+from jarvis.memory.wiki.extractor import ConversationFactExtractor+from jarvis.memory.wiki.journal import CandidateJournal+from jarvis.memory.wiki.voice_bridge import VoiceFactBridge++FACT_SENTENCE = "Remember that my friend Lena moved to Hamburg last month."+SHORT_FACT = "Lena lives in Hamburg." # >= 12 ack chars, < 30 aggressive chars+++class FakeBrain:+ def __init__(self) -> None:+ self.call_count = 0++ name = "fake-brain"+ context_window = 100_000+ supports_tools = False+ supports_vision = False++ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:+ self.call_count += 1+ yield BrainDelta(+ content=json.dumps(+ [{"fact": "Lena moved to Hamburg.", "kind": "person", "subjects": ["lena"]}]+ )+ )+ yield BrainDelta(finish_reason="stop")++ def estimate_cost(self, req: BrainRequest) -> float: # pragma: no cover+ return 0.0+++class FakeRegistry:+ def __init__(self, brain: Any) -> None:+ self._brain = brain++ def available(self) -> set[str]:+ return {"gemini"}++ def instantiate(self, name: str, **kwargs: Any) -> Any:+ return self._brain+++class FakeCurator:+ def __init__(self) -> None:+ self.ingested: list[str] = []++ async def ingest(self, source_content: str, source_label: str) -> Any:+ self.ingested.append(source_content)++ class _R:+ applied: list = []+ skipped_due_to_recent_edit: list = []+ failed_validation: list = []++ return _R()+++def _config() -> JarvisConfig:+ return JarvisConfig(+ brain=BrainConfig(+ primary="gemini",+ providers={"gemini": BrainProviderConfig(model="gemini-3.1-pro-preview")},+ ),+ memory=MemoryConfig(wiki=WikiMemoryConfig()),+ )+++def _stack(tmp_path: Path):+ bus = EventBus()+ journal = CandidateJournal(tmp_path / "jarvis.db")+ brain = FakeBrain()+ extractor = ConversationFactExtractor(+ config=_config(), journal=journal, registry=FakeRegistry(brain),+ )+ curator = FakeCurator()+ bridge = VoiceFactBridge(bus=bus, curator=curator, config=None, extractor=extractor)+ bridge.start()+ return bus, journal, curator, bridge, brain+++def _realtime_turn(+ user_text: str,+ jarvis_text: str,+ *,+ tier: str = "realtime",+) -> VoiceTurnCompleted:+ return VoiceTurnCompleted(+ session_id="rt-session",+ turn_id="rt-turn-1",+ user_text=user_text,+ jarvis_text=jarvis_text,+ tier=tier,+ provider="gemini-live",+ model="gemini-3.1-flash-live-preview",+ )+++async def _drain(journal: CandidateJournal, *, timeout_s: float = 2.0) -> None:+ deadline = time.monotonic() + timeout_s+ while time.monotonic() < deadline:+ if journal.backlog_count() > 0:+ return+ await asyncio.sleep(0.02)+++async def test_realtime_turn_feeds_journal_via_aggressive_path(tmp_path: Path) -> None:+ bus, journal, curator, bridge, _brain = _stack(tmp_path)+ try:+ await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay, will do!"))+ await _drain(journal)+ finally:+ bridge.stop()++ rows = journal.pending()+ assert rows and rows[0].fact == "Lena moved to Hamburg."+ assert rows[0].source_label.startswith("realtime-aggressive:")+ assert curator.ingested == [], "extractor mode must not call curator.ingest directly"+++async def test_realtime_ack_reply_uses_ack_path(tmp_path: Path) -> None:+ """An acked short fact bypasses the aggressive min-chars threshold."""+ bus, journal, _curator, bridge, _brain = _stack(tmp_path)+ try:+ await bus.publish(_realtime_turn(SHORT_FACT, "Noted."))+ await _drain(journal)+ finally:+ bridge.stop()++ rows = journal.pending()+ assert rows, "acked realtime turn must be journaled"+ assert rows[0].source_label.startswith("realtime-fact:")+++async def test_pipeline_tier_turn_is_ignored(tmp_path: Path) -> None:+ """Pipeline turns already ingest via TranscriptFinal pairing — no double feed."""+ bus, journal, _curator, bridge, brain = _stack(tmp_path)+ try:+ await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted.", tier="flash"))+ await asyncio.sleep(0.3)+ finally:+ bridge.stop()++ assert journal.backlog_count() == 0+ assert brain.call_count == 0+++async def test_same_realtime_turn_delivered_twice_journaled_once(tmp_path: Path) -> None:+ bus, journal, _curator, bridge, brain = _stack(tmp_path)+ try:+ # Ack path both times — the ack path has no rate limit, so the+ # second delivery is stopped by the turn-hash gate alone.+ await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted."))+ await _drain(journal)+ await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted."))+ await asyncio.sleep(0.2)+ finally:+ bridge.stop()++ assert journal.backlog_count() == 1, "duplicate realtime turn must be deduped by hash"+ assert brain.call_count == 1+++async def test_empty_user_text_is_ignored(tmp_path: Path) -> None:+ bus, journal, _curator, bridge, brain = _stack(tmp_path)+ try:+ await bus.publish(_realtime_turn("", "Noted."))+ await asyncio.sleep(0.2)+ finally:+ bridge.stop()++ assert journal.backlog_count() == 0+ assert brain.call_count == 0+++async def test_empty_reply_does_not_block_aggressive_path(tmp_path: Path) -> None:+ """A realtime turn can end with an empty output transcript (e.g. barge-in+ right after the fact was spoken) — the user fact must still be captured."""+ bus, journal, _curator, bridge, _brain = _stack(tmp_path)+ try:+ await bus.publish(_realtime_turn(FACT_SENTENCE, ""))+ await _drain(journal)+ finally:+ bridge.stop()++ rows = journal.pending()+ assert rows, "fact-shaped user text must be journaled even without a reply"+ assert rows[0].source_label.startswith("realtime-aggressive:")+++async def test_aggressive_path_is_rate_limited_across_realtime_turns(tmp_path: Path) -> None:+ """Chatty realtime sessions must not burn one LLM call per turn."""+ bus, journal, _curator, bridge, brain = _stack(tmp_path)+ try:+ await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay!"))+ await _drain(journal)+ await bus.publish(+ _realtime_turn(+ "My favourite restaurant is the little place at the harbour.",+ "Sounds lovely!",+ )+ )+ await asyncio.sleep(0.2)+ finally:+ bridge.stop()++ assert journal.backlog_count() == 1, "second aggressive ingest within 60s must be skipped"+ assert brain.call_count == 1