Skip to content

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.

feat(wiki): remove automatic fact collection after every turn and at hangup

rubenluetke10-beep7f0ce2dc9615
diff --git a/docs/LLM-CONTEXT.md b/docs/LLM-CONTEXT.md
index 16113ca6c1..7f21873544 100644
--- a/docs/LLM-CONTEXT.md
+++ b/docs/LLM-CONTEXT.md
@@ -617,8 +617,7 @@ Self-mod writeup: [`docs/self_mod.md`](docs/self_mod.md) — 8 mutable settings
- **Auto-push-EOD:** Task Scheduler 22:00 default. Tags `safety/eod-*` per branch, skips active Jarvis-Agent worktrees (modified within last 30 min).
- **Wiki triggers** (ADR-0014 contract — all classified silent vs loud):
- `WikiContextInjector` (silent) — runs before every brain turn
- - `VoiceFactBridge` ack path (loud) — `ResponseGenerated` with ack keyword, async via `asyncio.create_task`
- - `VoiceFactBridge` aggressive path (loud, rate-limited 60s default, opt-out `aggressive_mode=false`)
+ - `VoiceFactBridge` ack path (loud) — `ResponseGenerated` with ack keyword, async via `asyncio.create_task`; the automatic per-turn review and the end-of-call sweep were removed 2026-09-30
- `SessionRollupWorker` (loud) — `IdleEntered` past `session_idle_threshold_minutes`, writes one Markdown page per session
- **Preflight:** mandatory in every new worktree before any code edit.
diff --git a/docs/adr/0014-memory-trigger-contract.md b/docs/adr/0014-memory-trigger-contract.md
index acc4dba65b..b3bde15424 100644
--- a/docs/adr/0014-memory-trigger-contract.md
+++ b/docs/adr/0014-memory-trigger-contract.md
@@ -1,6 +1,23 @@
# ADR-0014 — Memory-Trigger Contract (silent vs loud failure discipline)
-**Status:** Accepted · **Date:** 2026-05-14 · **Phase:** B8 (Memory Hardening)
+**Status:** Accepted, amended 2026-09-30 · **Date:** 2026-05-14 · **Phase:** B8 (Memory Hardening)
+
+> **Amendment 2026-09-30 — automatic review removed.** The aggressive path
+> (every user turn reviewed without an acknowledgement), the realtime
+> end-of-call sweep with its held-back per-turn extractions, and the
+> six-hourly auto-backfill are removed. They spent paid API keys around the
+> clock: ~300 wiki calls on keys in 30 days, ~5 EUR in three hours while
+> nobody was at the PC. `[memory.wiki.voice_bridge]` is no longer read (old
+> tables still validate). What the user triggers explicitly stays: the
+> acknowledgement path, the `wiki-ingest` tool, the memory-save skill and the
+> manual backfill. Every model call the wiki still makes on its own bills only
+> what background work may bill (`jarvis/brain/background_policy.py`: once a
+> subscription is connected, subscriptions and local models only; a failing
+> subscription makes the work wait) and passes the runaway guard in
+> `jarvis/memory/wiki/background_guard.py` (backoff plus a daily cap on the
+> number of calls, `[wiki_integration] max_background_llm_calls_per_day`,
+> default 200). Section 3 below is superseded; the inventory table is
+> updated.
> Note: this ADR shares the 0014 prefix with
> `0014-flash-brain-suppress-if-fast.md` (Voice UX hardening). The
@@ -75,8 +92,7 @@ removing or renaming a trigger requires amending this ADR.
| Trigger | Subscribes to | Side effect | Failure class |
|---|---|---|---|
| `WikiContextInjector` | direct call before each brain turn | prepends `## Wiki context` to system prompt | **silent fallback** — missing context degrades gracefully to unaltered prompt |
-| `VoiceFactBridge` (ack path) | `ResponseGenerated` with ack keyword | calls `WikiCurator.ingest()` in background | **loud regression** — every ingest failure increments `voice_turns_ingested_ack` discrepancy and is exception-logged |
-| `VoiceFactBridge` (aggressive path) | `ResponseGenerated` without ack, > 30 chars | calls `WikiCurator.ingest()` in background, rate-limited | **loud regression** — same as ack path, plus rate-limit logged at DEBUG |
+| `VoiceFactBridge` (ack path) | `ResponseGenerated` / `VoiceTurnCompleted` with ack keyword | Stage-1 extraction into the candidate journal in background; held and retried while the wiki must wait for a subscription | **loud regression** — every extraction failure is exception-logged; a wait shows on the wiki health strip |
| `SessionRollupWorker` | `IdleEntered` past `session_idle_threshold_minutes` | writes one session Markdown page | **loud regression** — failure increments `session_rollups_failed` and is WARNING-logged |
New triggers (planned in B6: external-source ingest, Jarvis-Agents
@@ -127,7 +143,12 @@ The two classes are mutually exclusive. A trigger cannot be silent
on some failures and loud on others — that ambiguity is what masked
the 2026-05-13 outage.
-### 3. Aggressive-mode safety contract
+### 3. Aggressive-mode safety contract (superseded 2026-09-30)
+
+The aggressive path this section governed was removed; see the amendment at
+the top. Any future trigger that fires without an explicit acknowledgement
+must additionally obey the background billing rule and the wiki runaway
+guard. The original text is kept for history.
Any second-path ingest mode that fires without an explicit
acknowledgement signal (today: `VoiceFactBridge` aggressive path;
diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md
index f8e302e329..8f759fa821 100644
--- a/docs/architecture-overview.md
+++ b/docs/architecture-overview.md
@@ -320,8 +320,14 @@ This project has an auto-memory at `~/.claude/projects/<your-claude-project-dir>
The Knowledge Wiki is the long-term memory tier (B0/B1/B5/B7/B8/B9 live). Three router-tier tools: `wiki-recall` (search), `wiki-page-read` (read by vault path), `wiki-ingest` (deterministic save-fact). Vault root configured in `[wiki_integration].vault_root`; default `wiki/obsidian-vault/`. Telemetry snapshot at `GET /api/wiki/telemetry`. Trigger contract in ADR-0014.
Realtime and chat memory use a durable two-stage path. A recall-biased extractor
-reviews each eligible user turn in the background and performs an overlapping,
-chunked whole-session sweep at session end. Candidates carry an exact user-turn
+reviews a turn only when the user explicitly asked to keep it (the brain
+acknowledged the save) or when the user starts a backfill; the automatic review
+of every turn, the end-of-call sweep and the periodic auto-backfill were removed
+on 2026-09-30 because they billed paid keys around the clock. Every model call
+the wiki makes on its own bills only what background work may bill
+(`jarvis/brain/background_policy.py`) and passes the runaway guard in
+`jarvis/memory/wiki/background_guard.py` (backoff plus a daily cap on the number
+of calls, default 200). Candidates carry an exact user-turn
ID plus a bounded, secret-redacted user-only evidence excerpt in
`data/jarvis.db`; assistant text can resolve a reference but is never evidence.
The body-aware consolidator is the binding cleanliness gate: it compares that
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.py
index 3e69368970..3ad9e1e25e 100644
--- a/jarvis/brain/factory.py
+++ b/jarvis/brain/factory.py
@@ -152,7 +152,7 @@ ROUTER_TOOLS = frozenset({
"wiki-list",
# Phase B5 follow-up: deterministic ingest path. Lets the brain
# explicitly store a fact ("merk dir: …") rather than relying on the
- # aggressive-mode VoiceFactBridge heuristic.
+ # VoiceFactBridge acknowledgement heuristic.
"wiki-ingest",
# CLI-Integration (2026-05-24): virtual loader that expands to one
# ``cli_<name>`` tool per connected & usable CLI (gcloud, gh, docker, …).
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index e8688217f1..0bf2e73ca0 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -1753,39 +1753,6 @@ class SchedulerConfig(BaseModel):
flush_pending_max_age_minutes: int = 10
-class VoiceBridgeConfig(BaseModel):
- """``VoiceFactBridge`` settings (Phase B8 — aggressive-ingest mode).
-
- The bridge has two paths from voice turn -> wiki:
-
- * **Ack path** (always on): ingest when the brain reply contains an
- explicit "notiert" / "vermerkt" / ... keyword. Narrow, false-positive
- free.
- * **Aggressive path** (this section's toggle): every user turn with
- at least ``min_user_chars`` characters is handed to the curator
- regardless of how the brain replied. The curator's prompt is the
- salience filter -- smalltalk returns an empty list, facts produce
- pages.
-
- The aggressive path is the safety net for the case "user states a
- fact, brain replies conversationally without an ack-keyword". B1 §3.8
- planned this but never activated it; this section turns it on by
- default.
-
- ``rate_limit_seconds`` is an opt-in cost control. The default reviews every
- eligible completed turn so a second durable fact in the same realtime
- conversation is not silently discarded.
- """
-
- model_config = ConfigDict(extra="allow")
-
- aggressive_mode: bool = True
- # Keep this aligned with ExtractorConfig.min_user_chars. Stage 2 remains
- # the quality gate; a 12-character ownership statement can be durable.
- min_user_chars: int = 12
- rate_limit_seconds: int = 0
-
-
class ExtractorConfig(BaseModel):
"""Settings for the Stage-1 ``ConversationFactExtractor`` (Wave 2).
@@ -1793,6 +1760,9 @@ class ExtractorConfig(BaseModel):
configured here — both curator stages resolve through the single
``[memory.wiki.curator]`` provider/model pair (the Wiki settings card
drives them together). This section only holds the extraction gates.
+ The extractor reviews only explicitly saved turns (the voice bridge's
+ acknowledgement path) and user-started backfills; ``enabled = false``
+ turns both off.
"""
model_config = ConfigDict(extra="allow")
@@ -1815,19 +1785,23 @@ class ExtractorConfig(BaseModel):
class WikiMemoryConfig(BaseModel):
- """Root of the ``[memory.wiki]`` block (Phase B1+B7+B8 + Wave 2).
+ """Root of the ``[memory.wiki]`` block (Phase B1+B7 + Wave 2).
+
+ Holds the Curator LLM section (B1), the session-rollup section (B7) and
+ the Stage-1 extractor section (Wave 2). Defaults are chosen so a config
+ without the section loads cleanly as ``WikiMemoryConfig()``.
- Holds the Curator LLM section (B1), the session-rollup section (B7),
- the voice-bridge section (B8 aggressive ingest), and the Stage-1
- extractor section (Wave 2). Defaults are chosen so a config without
- the section loads cleanly as ``WikiMemoryConfig()``.
+ The former ``[memory.wiki.voice_bridge]`` table (``aggressive_mode``,
+ ``min_user_chars``, ``rate_limit_seconds``) configured the automatic
+ review of every user turn, removed 2026-09-30. An old ``jarvis.toml``
+ that still carries it keeps validating through ``extra="allow"`` (AP-16)
+ and the values are ignored.
"""
model_config = ConfigDict(extra="allow")
curator: WikiCuratorConfig = Field(default_factory=WikiCuratorConfig)
session_rollup: SessionRollupConfig = Field(default_factory=SessionRollupConfig)
- voice_bridge: VoiceBridgeConfig = Field(default_factory=VoiceBridgeConfig)
extractor: ExtractorConfig = Field(default_factory=ExtractorConfig)
@@ -3011,7 +2985,7 @@ class WikiContextConfig(BaseModel):
and migrate callers off the top-level ``cfg.wiki_context`` field.
``extra="allow"`` is mandatory and matches every sibling wiki sub-table
- (WikiCurator/SessionRollup/Scheduler/VoiceBridge/WikiMemory/
+ (WikiCurator/SessionRollup/Scheduler/Extractor/WikiMemory/
WikiIntegration): a self-mod or drift-guard write of an unknown future
key must survive validation rather than being silently dropped (AP-16).
"""
diff --git a/jarvis/memory/wiki/integration.py b/jarvis/memory/wiki/integration.py
index 315c4ff2d2..5d56f04f5f 100644
--- a/jarvis/memory/wiki/integration.py
+++ b/jarvis/memory/wiki/integration.py
@@ -46,7 +46,7 @@ from jarvis.core.events import IdleEntered, WikiPageChanged
if TYPE_CHECKING:
from jarvis.core.bus import EventBus
- from jarvis.core.config import VoiceBridgeConfig, WikiIntegrationConfig
+ from jarvis.core.config import WikiIntegrationConfig
from jarvis.memory.wiki.protocols import PageRepository
from jarvis.memory.wiki.scheduler import CuratorScheduler
@@ -263,7 +263,6 @@ async def bootstrap_wiki_integration(
config: WikiIntegrationConfig,
brain_caller: Callable[[str, str], Awaitable[str]] | None = None,
scheduler_factory: Callable[..., CuratorScheduler] | None = None,
- voice_bridge_config: VoiceBridgeConfig | None = None,
) -> WikiIntegrationHandle:
"""Wire ``SessionRollupWorker`` → (Scheduler →) ``WikiCurator`` and
subscribe to ``IdleEntered``.
@@ -451,19 +450,13 @@ async def bootstrap_wiki_integration(
handle._unsubscribe_idle = _unsubscribe # noqa: SLF001
- # ------------------------------------------------------------------
- # B5 follow-up (2026-05-13): VoiceFactBridge — listens for voice turns
- # where the brain replies with an acknowledgement keyword and pushes
- # the user-spoken fact straight to the curator. Without this, voice
- # turns never reach the wiki because:
- # - voice_turns live in sessions.db, not in awareness_episodes
- # - SessionRollupWorker reads awareness_episodes only at idle
- # The bridge closes that gap with an explicit "brain said notiert"
- # heuristic.
# ------------------------------------------------------------------
# Wave-2 Stage 1: candidate journal + conversation fact extractor.
- # Guarded: any failure degrades to the legacy direct-ingest bridge
- # (extractor=None) so the conversation->wiki path never goes dark.
+ # Since 2026-09-30 the extractor reviews only turns the user explicitly
+ # asked to keep (the VoiceFactBridge acknowledgement path below) and the
+ # user-started backfill; nothing reviews every turn any more. Guarded:
+ # a failure leaves the explicit wiki-ingest tool as the save path.
+ # ------------------------------------------------------------------
extractor = None
journal = None
try:
@@ -506,19 +499,22 @@ async def bootstrap_wiki_integration(
else:
log.info(
"wiki_integration: [memory.wiki.extractor] disabled — "
- "bridge keeps the legacy direct curator ingest"
+ "acknowledged saves are not reviewed; the wiki-ingest tool "
+ "remains the explicit save path"
)
except Exception as exc: # noqa: BLE001
extractor = None
if journal is not None:
try:
journal.close()
- except Exception: # noqa: BLE001, S110
- pass
+ except Exception: # noqa: BLE001 - the extractor failure is what gets reported
+ log.debug("wiki_integration: journal.close() after a failed build", exc_info=True)
journal = None
log.warning(
- "wiki_integration: Stage-1 extractor unavailable (%s) — "
- "falling back to the legacy direct curator ingest", exc,
+ "wiki_integration: Stage-1 extractor unavailable (%s) — acknowledged "
+ "saves are not reviewed; the wiki-ingest tool remains the explicit "
+ "save path",
+ exc,
)
# Wave-2 Stage 2: body-aware consolidator, drained via the scheduler's
@@ -564,9 +560,18 @@ async def bootstrap_wiki_integration(
# otherwise sit pending forever (not enough NEW conversation
# ever arrives to cross consolidate_after_candidates). Start a
# background age-check loop, same fire-and-forget conventions
- # as the hourly telemetry loop started below (AP-9/AP-26).
+ # as the hourly telemetry loop started below (AP-9/AP-26). It
+ # also retries explicit saves the bridge had to hold, and it
+ # waits out the runaway guard's backoff instead of re-triggering
+ # a failing judge every tick.
handle._journal_age_flush_task = asyncio.create_task( # noqa: SLF001
- _journal_age_flush_loop(journal, scheduler, root_cfg.wiki_scheduler),
+ _journal_age_flush_loop(
+ journal,
+ scheduler,
+ root_cfg.wiki_scheduler,
+ root_config=root_cfg,
+ held_saves=lambda: handle._voice_bridge, # noqa: SLF001
+ ),
name="wiki-journal-age-flush",
)
log.info("wiki_integration: age-based journal flush loop started")
@@ -588,8 +593,9 @@ async def bootstrap_wiki_integration(
_set_running_capture_runtime(None)
if extractor is not None:
log.warning(
- "wiki_integration: Stage-2 unavailable; live bridge uses guarded "
- "direct ingest instead of accumulating undrainable candidates"
+ "wiki_integration: Stage-2 unavailable; acknowledged saves are "
+ "not reviewed rather than piling up candidates nothing can "
+ "consolidate — the wiki-ingest tool remains the explicit save path"
)
# B7: make sure the self-documentation page exists from first boot.
@@ -625,24 +631,23 @@ async def bootstrap_wiki_integration(
except Exception as exc: # noqa: BLE001 — contacts absent ≠ wiki broken
log.warning("wiki_integration: contact mirror not wired — %s", exc)
- try:
- from jarvis.memory.wiki.voice_bridge import VoiceFactBridge
- voice_bridge = VoiceFactBridge(
- bus=bus,
- curator=curator,
- config=voice_bridge_config,
- extractor=extractor if capture_ready else None,
- )
- voice_bridge.start()
- handle._voice_bridge = voice_bridge # noqa: SLF001
- log.info(
- "wiki_integration: VoiceFactBridge attached "
- "(aggressive_mode=%s, extractor=%s)",
- getattr(voice_bridge_config, "aggressive_mode", "default(True)"),
- "stage-1" if extractor is not None else "legacy-direct",
- )
- except Exception as exc: # noqa: BLE001
- log.warning("wiki_integration: VoiceFactBridge failed to start: %s", exc)
+ # ------------------------------------------------------------------
+ # VoiceFactBridge — explicit saves only. When the brain acknowledges a
+ # save ("notiert", "noted", ...) the user's turn goes to the Stage-1
+ # extractor. Nothing reviews ordinary turns or runs at hangup any more
+ # (removed 2026-09-30: it billed paid keys around the clock). Without a
+ # working Stage 1 + Stage 2 the bridge is not started at all.
+ # ------------------------------------------------------------------
+ if extractor is not None and capture_ready:
+ try:
+ from jarvis.memory.wiki.voice_bridge import VoiceFactBridge
+
+ voice_bridge = VoiceFactBridge(bus=bus, extractor=extractor)
+ voice_bridge.start()
+ handle._voice_bridge = voice_bridge # noqa: SLF001
+ log.info("wiki_integration: VoiceFactBridge attached (explicit saves only)")
+ except Exception as exc: # noqa: BLE001
+ log.warning("wiki_integration: VoiceFactBridge failed to start: %s", exc)
# ------------------------------------------------------------------
# B8.7 — telemetry hourly-summary loop. Cheap, in-memory; the only
@@ -927,36 +932,80 @@ def _should_age_flush(oldest_ms: int | None, now_ms: int, max_age_min: int) -> b
return age_min >= max_age_min
-async def _journal_age_flush_loop(journal: Any, scheduler: Any, sched_cfg: Any) -> None:
+async def _journal_age_flush_tick(
+ journal: Any,
+ scheduler: Any,
+ *,
+ max_age_min: int,
+ root_config: Any = None,
+ held_saves: Callable[[], Any] | None = None,
+) -> bool:
+ """One pass of the age flush. Returns whether a JOURNAL trigger fired.
+
+ Nothing happens while the runaway guard says the wiki must not call a
+ model (backoff window after a failed or waiting judge run, or the daily
+ call cap): the candidates simply stay pending. This is what stops the
+ old failure mode — a failing judge re-billed every two minutes.
+ """
+ from jarvis.memory.wiki.background_guard import guard
+ from jarvis.memory.wiki.scheduler import fire_journal_trigger
+
+ if not guard.ready(root_config):
+ return False
+ bridge = held_saves() if held_saves is not None else None
+ if bridge is not None and getattr(bridge, "waiting_count", 0):
+ await bridge.retry_waiting()
+ if max_age_min <= 0:
+ return False
+ oldest = await asyncio.to_thread(journal.oldest_pending_ms)
+ if not _should_age_flush(oldest, int(time.time() * 1000), max_age_min):
+ return False
+ if not guard.ready(root_config):
+ return False
+ fire_journal_trigger(
+ scheduler,
+ name="wiki-journal-age-flush-trigger",
+ log_context="age-based journal flush",
+ )
+ return True
+
+
+async def _journal_age_flush_loop(
+ journal: Any,
+ scheduler: Any,
+ sched_cfg: Any,
+ *,
+ root_config: Any = None,
+ held_saves: Callable[[], Any] | None = None,
+) -> None:
"""Fire a JOURNAL trigger when the oldest pending candidate exceeds the
- configured age (spec A4).
+ configured age (spec A4), and retry explicit saves the bridge held.
Below-threshold backlogs on a quiet install never cross
``consolidate_after_candidates`` on their own — this loop is the
backstop that still gets them written, the below-threshold counterpart
to the extractor's count-gated trigger (both go through the shared
- :func:`~jarvis.memory.wiki.scheduler.fire_journal_trigger`). Runs off
+ :func:`~jarvis.memory.wiki.scheduler.fire_journal_trigger`). Every tick
+ first asks the runaway guard (:mod:`jarvis.memory.wiki.background_guard`)
+ and does nothing inside a backoff window or past the daily cap. Runs off
the voice hot path (AP-9) and was started off the boot critical path
(AP-26); cancelled in :meth:`WikiIntegrationHandle.shutdown` exactly
like the hourly telemetry loop. Never raises — a check failure is
logged and the loop keeps polling.
"""
- from jarvis.memory.wiki.scheduler import fire_journal_trigger
-
max_age_min = int(getattr(sched_cfg, "flush_pending_max_age_minutes", 10))
if max_age_min <= 0:
log.debug("wiki_integration: age-based journal flush disabled (max_age<=0)")
- return
while True:
await asyncio.sleep(120)
try:
- oldest = journal.oldest_pending_ms()
- if _should_age_flush(oldest, int(time.time() * 1000), max_age_min):
- fire_journal_trigger(
- scheduler,
- name="wiki-journal-age-flush-trigger",
- log_context="age-based journal flush",
- )
+ await _journal_age_flush_tick(
+ journal,
+ scheduler,
+ max_age_min=max_age_min,
+ root_config=root_config,
+ held_saves=held_saves,
+ )
except Exception: # noqa: BLE001 — never kill the loop
log.debug("wiki_integration: journal age flush check failed", exc_info=True)
diff --git a/jarvis/memory/wiki/telemetry.py b/jarvis/memory/wiki/telemetry.py
index b5f241c762..3f7c5a10d0 100644
--- a/jarvis/memory/wiki/telemetry.py
+++ b/jarvis/memory/wiki/telemetry.py
@@ -46,7 +46,6 @@ log = logging.getLogger(__name__)
DEFAULT_COUNTERS: tuple[str, ...] = (
"voice_turns_seen",
"voice_turns_ingested_ack",
- "voice_turns_ingested_aggressive",
"wiki_context_hits",
"wiki_context_misses",
"session_rollups_succeeded",
diff --git a/jarvis/memory/wiki/voice_bridge.py b/jarvis/memory/wiki/voice_bridge.py
index 71f6edb979..f2212f5221 100644
--- a/jarvis/memory/wiki/voice_bridge.py
+++ b/jarvis/memory/wiki/voice_bridge.py
@@ -1,54 +1,41 @@
-"""Voice-fact -> Wiki bridge with two parallel ingest paths.
-
-Closes the gap between the voice pipeline and the WikiCurator:
-
-* :class:`StoryTracker` writes ``awareness_episodes`` triggered by
- window-switch / idle, but never sees the spoken user content.
-* :class:`SessionRollupWorker` reads ``awareness_episodes`` at idle and
- rolls them into a session digest, but does not look at ``voice_turns``.
-
-This bridge listens for ``TranscriptFinal`` and ``ResponseGenerated`` on
-the bus, correlates them as one voice turn, and feeds the user text to
-the WikiCurator via two complementary paths:
-
-The realtime engine never emits ``TranscriptFinal``/``MessageSent`` — its
-one signal carrying both final texts of a turn is ``VoiceTurnCompleted``
-(tier="realtime"). The bridge consumes that event directly (no pairing
-state needed) and routes it through the SAME two paths below, so both
-voice engines share one ingest contract.
-
-1. **Ack path (B5, narrow):** when the brain reply contains an
- acknowledgement keyword ("notiert", "vermerkt", ...). Mirrors the
- user-visible contract -- if the brain says it noted the fact, the
- wiki gets the note. False-positive-free, but misses any fact the
- brain replies to conversationally without an ack keyword.
-
-2. **Aggressive path (B8, defence-in-depth):** every user turn with at
- least ``cfg.min_user_chars`` characters is handed to the curator
- anyway, with the curator's prompt acting as the salience filter
- (smalltalk -> empty list, real facts -> pages). An optional
- ``cfg.rate_limit_seconds`` can reduce review calls, but the default is
- zero so consecutive durable facts are never silently skipped.
-
-Both paths are fire-and-forget background tasks. The voice path is
-never blocked, and a failure on one path never crashes the other. When
-both fire on the same turn the bridge deduplicates so the curator sees
-the text only once.
-
-Configuration: :class:`jarvis.core.config.VoiceBridgeConfig`. The
-aggressive path can be disabled by setting ``aggressive_mode = false``;
-the ack path is always on.
+"""Explicit-save bridge: acknowledged voice/chat turns -> Stage-1 extraction.
+
+When the brain confirms that it stored something ("notiert", "noted", ...),
+the user's turn is handed to the Stage-1 fact extractor, which journals
+candidate facts for the Stage-2 consolidator. The acknowledgement is the
+user-visible contract: if Jarvis says it noted the fact, the wiki gets it.
+
+Removed 2026-09-30 by maintainer decision: the automatic review of every user
+turn (the former "aggressive" path), the end-of-call sweep of a realtime
+session, and the per-turn extractions held back until hangup. They reviewed
+turns nobody asked to keep and spent paid API keys around the clock. What
+the user triggers explicitly stays: this acknowledgement path, the
+``wiki-ingest`` tool, the memory-save skill and the manual backfill route.
+
+Both voice engines share this one contract. The pipeline pairs
+``TranscriptFinal``/``MessageSent`` with ``ResponseGenerated``; the realtime
+engine delivers both final texts on ``VoiceTurnCompleted`` (tier
+``realtime``). ``VoiceSessionEnded`` only drops the call's reference-
+resolution context — nothing runs at hangup.
+
+Extraction is a fire-and-forget background task, so the voice path never
+waits on it (AP-9). It bills only what background work may bill
+(:mod:`jarvis.brain.background_policy`). When the wiki has to wait — the
+subscription is not usable, the runaway guard is backing off, or the daily
+call cap is reached — the turn is kept in a small in-memory queue and
+:meth:`VoiceFactBridge.retry_waiting` retries it once a model call is allowed
+again. It is never moved onto an API key.
"""
from __future__ import annotations
import asyncio
import hashlib
import logging
-import time
-from collections import OrderedDict
+from collections import OrderedDict, deque
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
+from jarvis.brain.background_policy import BackgroundDeferred
from jarvis.core.bus import EventBus
from jarvis.core.events import (
MessageSent,
@@ -61,8 +48,6 @@ from jarvis.memory.wiki.extractor import ConversationContextTurn
from jarvis.memory.wiki.telemetry import telemetry
if TYPE_CHECKING:
- from jarvis.core.config import VoiceBridgeConfig
- from jarvis.memory.wiki.curator import WikiCurator
from jarvis.memory.wiki.extractor import ConversationFactExtractor
log = logging.getLogger(__name__)
@@ -72,15 +57,17 @@ log = logging.getLogger(__name__)
# hash gate makes sure only one extraction fires per distinct turn text.
_SEEN_HASHES_MAX = 128
-# Per-turn extractions captured DURING a live realtime call are deferred and
-# run at session end: each extraction is an LLM round (provider call, 429
-# retry storms, Codex CLI subprocess spawns) on the same event loop that
-# paces the call's audio, and freshly journaled candidates additionally
-# trigger in-call consolidator judge rounds (live 2026-07-21 11:31: a
-# 10.9 s judge round mid-call; the loop-stall forensics measured 481 ms).
-# AP-9: awareness work stays off the voice hot path. Bounded so a session
-# that never ends cannot grow the queue without limit.
-_DEFERRED_MAX_PER_SESSION = 200
+# Explicit saves held while the wiki must wait for a usable subscription or
+# the next day's call budget. Small on purpose: these are turns the user
+# asked to keep, not a transcript archive. The oldest is dropped (and logged)
+# when a long outage overflows it.
+_MAX_WAITING_SAVES = 20
+
+# Reference-resolution context kept per live realtime call, and how many
+# calls are tracked at once (a session whose end event never arrives must
+# not grow the map without limit).
+_CONTEXT_TURNS = 5
+_MAX_TRACKED_SESSIONS = 8
def _turn_hash(text: str) -> str:
@@ -91,7 +78,7 @@ def _turn_hash(text: str) -> str:
# Keywords (lowercase, simple substring match) that mark the brain's
# reply as "yes, I stored this". Keep narrow -- false positives mean
-# noise in the wiki; false negatives are caught by the aggressive path.
+# noise in the wiki.
_ACK_KEYWORDS = ( # i18n-allow: multilingual acknowledgement-phrase matching vocabulary
"notiert",
"vermerkt",
@@ -106,10 +93,9 @@ _ACK_KEYWORDS = ( # i18n-allow: multilingual acknowledgement-phrase matching vo
"apuntado", # i18n-allow: Spanish acknowledgement-phrase matching vocabulary
)
-# Minimum length for the ack path to consider the user utterance worth
-# curating. Filters out "ja", "ok", "hallo" -- anything shorter is
-# almost certainly not a fact. The aggressive path uses its own,
-# higher threshold from config.
+# Minimum length for an acknowledged user utterance to be worth a review.
+# Filters out "ja", "ok", "hallo" -- anything shorter is almost certainly
+# not a fact.
_MIN_ACK_USER_CHARS = 12
@@ -120,8 +106,8 @@ class _PendingTurn:
user_text: str = ""
user_language: str = ""
captured_at_ns: int = 0
- # "voice" (TranscriptFinal) or "chat" (MessageSent role=user) — only
- # labels the journal source; the processing pipeline is identical.
+ # "voice" (TranscriptFinal), "chat" (MessageSent role=user) or
+ # "realtime" — only labels the journal source.
origin: str = "voice"
session_id: str = ""
turn_id: str = ""
@@ -129,65 +115,49 @@ class _PendingTurn:
context_turns: tuple[ConversationContextTurn, ...] = ()
-class VoiceFactBridge:
- """Bridge voice-pipeline -> WikiCurator with ack + aggressive paths.
+@dataclass(frozen=True, slots=True)
+class _ExtractionJob:
+ """One acknowledged turn, deduped and ready for Stage-1 extraction."""
+
+ pending: _PendingTurn
+ reply_raw: str
+ source_kind: str
+ turn_hash: str
+ review_key: str
- Construct once at app boot, hand it the bus, a curator and (since
- B8) a :class:`VoiceBridgeConfig`, then call :meth:`start`. The
- bridge subscribes itself and runs until :meth:`stop` is called.
- ``config=None`` falls back to default settings (aggressive_mode=True,
- min_user_chars=12, rate_limit_seconds=0) so legacy callers keep
- working unchanged.
+class VoiceFactBridge:
+ """Bridge acknowledged voice/chat turns into the Stage-1 extractor.
+
+ Construct once at app boot with the bus and the extractor, then call
+ :meth:`start`. The bridge subscribes itself and runs until :meth:`stop`
+ (or :meth:`stop_and_wait`) is called.
"""
def __init__(
self,
*,
bus: EventBus,
- curator: WikiCurator,
- config: VoiceBridgeConfig | None = None,
- extractor: ConversationFactExtractor | None = None,
+ extractor: ConversationFactExtractor,
) -> None:
- # Late import keeps the dataclass-only module import-cheap and
- # avoids a circular-import risk with ``jarvis.core.config`` in
- # very-early bootstrap paths.
- if config is None:
- from jarvis.core.config import VoiceBridgeConfig
- config = VoiceBridgeConfig()
self._bus = bus
- self._curator = curator
- self._cfg = config
- # Wave-2: when an extractor is attached, both paths feed the
- # candidate journal (Stage 1) instead of the legacy blind
- # per-turn curator ingest. ``None`` keeps the legacy behaviour
- # (WikiIntegrationConfig.fallback_to_direct_ingest posture).
self._extractor = extractor
self._pending = _PendingTurn()
# (event type, handler) pairs, because EventBus.subscribe returns None:
- # detaching needs both halves handed back to unsubscribe(). This used to
- # hold the return value of subscribe() and therefore a list of None,
- # whose call raised into a bare except — stop() cleared the list and
- # left every handler attached to the bus.
+ # detaching needs both halves handed back to unsubscribe().
self._subscriptions: list[tuple[type[Any], Any]] = []
self._inflight: set[asyncio.Task[Any]] = set()
- self._session_inflight: dict[str, set[asyncio.Task[Any]]] = {}
- # In-call extraction jobs held back until the session ends (AP-9).
- # Keyed by session id; each entry is the full argument tuple of one
- # already-deduped `_extract_safe` run.
- self._deferred_extractions: dict[
- str, list[tuple[_PendingTurn, str, str, str, str]]
- ] = {}
- self._realtime_sessions: dict[str, list[ConversationContextTurn]] = {}
+ self._realtime_sessions: OrderedDict[str, list[ConversationContextTurn]] = (
+ OrderedDict()
+ )
self._realtime_turn_ids: dict[str, set[str]] = {}
+ # Explicit saves waiting for the wiki to be allowed a model call.
+ self._waiting: deque[_ExtractionJob] = deque()
+ self._retry_lock = asyncio.Lock()
self._started = False
- # Recently dispatched turn hashes (bounded LRU) — dedupes the
+ # Recently dispatched review keys (bounded LRU) — dedupes the
# TranscriptFinal/MessageSent double delivery of the same turn.
self._seen_hashes: OrderedDict[str, None] = OrderedDict()
- # Monotonic ns -- never compared across reboots, so wall-clock
- # drift is irrelevant. Initialised to a value far enough in the
- # past that the first aggressive ingest always passes the gate.
- self._last_aggressive_ns: int = -(10**18)
# ------------------------------------------------------------------
# lifecycle
@@ -197,8 +167,8 @@ class VoiceFactBridge:
"""Subscribe to the turn events of both voice engines."""
if self._started:
return
- # Annotated: the five handlers have five different event parameters, and
- # an unannotated literal makes the checker join them into a union that
+ # Annotated: the handlers take different event types, and an
+ # unannotated literal makes the checker join them into a union that
# no longer matches subscribe()'s Callable[[Event], ...].
wiring: tuple[tuple[type[Any], Any], ...] = (
(TranscriptFinal, self._on_transcript_final),
@@ -211,16 +181,10 @@ class VoiceFactBridge:
self._bus.subscribe(event_type, handler)
self._subscriptions.append((event_type, handler))
self._started = True
- log.info(
- "VoiceFactBridge started "
- "(aggressive_mode=%s, min_user_chars=%d, rate_limit_s=%d)",
- self._cfg.aggressive_mode,
- self._cfg.min_user_chars,
- self._cfg.rate_limit_seconds,
- )
+ log.info("VoiceFactBridge started (explicit saves only)")
def stop(self) -> None:
- """Cancel in-flight ingests and unsubscribe. Idempotent."""
+ """Cancel in-flight reviews and unsubscribe. Idempotent."""
self._cancel_and_unsubscribe()
async def stop_and_wait(self, *, timeout_s: float = 5.0) -> None:
@@ -255,10 +219,15 @@ class VoiceFactBridge:
tasks = tuple(self._inflight)
for task in tasks:
task.cancel()
- self._session_inflight.clear()
self._realtime_sessions.clear()
self._realtime_turn_ids.clear()
- self._deferred_extractions.clear()
+ if self._waiting:
+ log.info(
+ "VoiceFactBridge: %d explicit save(s) still waiting for the "
+ "subscription are dropped at shutdown",
+ len(self._waiting),
+ )
+ self._waiting.clear()
self._started = False
return tasks
@@ -267,7 +236,7 @@ class VoiceFactBridge:
# ------------------------------------------------------------------
async def _on_transcript_final(self, event: TranscriptFinal) -> None:
- """Capture the user text. Don't ingest yet -- wait for the brain reply."""
+ """Capture the user text. Don't review yet -- wait for the brain reply."""
transcript = getattr(event, "transcript", None)
if transcript is None:
return
@@ -287,10 +256,9 @@ class VoiceFactBridge:
async def _on_user_message(self, event: MessageSent) -> None:
"""Capture a CHAT user turn (desktop chat, Discord/Telegram channels).
- Mirrors :meth:`_on_transcript_final` for the text path so chat turns
- feed the same journal. Non-user roles (assistant/preamble/...) are
- ignored. A voice turn that the server mirrors as ``MessageSent`` is
- deduped later by the turn-hash gate, never double-extracted.
+ Mirrors :meth:`_on_transcript_final` for the text path. Non-user roles
+ (assistant/preamble/...) are ignored. A voice turn that the server
+ mirrors as ``MessageSent`` keeps its voice origin and is deduped later.
"""
if (getattr(event, "role", "") or "") != "user":
return
@@ -298,8 +266,6 @@ class VoiceFactBridge:
if not text:
return
ts_ns = getattr(event, "timestamp_ns", 0) or 0
- # A voice turn already sits in pending (TranscriptFinal fired first):
- # do not downgrade its origin to "chat" when the server mirrors it.
if self._pending.user_text and _turn_hash(self._pending.user_text) == _turn_hash(text):
return
self._pending = _PendingTurn(
@@ -311,11 +277,10 @@ class VoiceFactBridge:
)
async def _on_response_generated(self, event: ResponseGenerated) -> None:
- """Pair the pending user text with the brain reply and ingest."""
+ """Pair the pending user text with the brain reply."""
reply_raw = (getattr(event, "text", "") or "").strip()
if not reply_raw:
return
-
pending = self._pending
if not pending.user_text:
return
@@ -323,18 +288,11 @@ class VoiceFactBridge:
self._pending = _PendingTurn()
async def _on_voice_turn_completed(self, event: VoiceTurnCompleted) -> None:
- """Ingest a REALTIME turn — both final texts arrive on this one event.
+ """Handle a REALTIME turn — both final texts arrive on this one event.
- The realtime engine emits ``TranscriptionUpdate`` (never
- ``TranscriptFinal``/``MessageSent``), so the pairing path above stays
- silent for it. Pipeline turns (any other tier) are already ingested
- via that pairing and MUST be ignored here — reacting to both signals
- would double-extract every pipeline turn. The turn-hash gate in
+ Pipeline turns (any other tier) are already handled by the pairing
+ path above and MUST be ignored here; the review-key gate in
:meth:`_dispatch` additionally dedupes any residual overlap.
-
- Unlike the pairing path, an empty reply does not block ingestion:
- a realtime turn can end without an output transcript (barge-in) and
- the fact lives in the user text.
"""
if (getattr(event, "tier", "") or "") != "realtime":
return
@@ -347,9 +305,9 @@ class VoiceFactBridge:
captured_at_ns = getattr(event, "timestamp_ns", 0) or 0
turn_id = raw_turn_id or f"turn-{captured_at_ns}"
review_key = f"live:v2:{session_id or 'unknown-session'}:{turn_id}"
- session_turns = self._realtime_sessions.setdefault(session_id, [])
+ session_turns = self._session_context(session_id)
seen_ids = self._realtime_turn_ids.setdefault(session_id, set())
- context_turns = tuple(session_turns[-5:])
+ context_turns = tuple(session_turns[-_CONTEXT_TURNS:])
reply_raw = (getattr(event, "jarvis_text", "") or "").strip()
if turn_id not in seen_ids:
session_turns.append(
@@ -359,6 +317,7 @@ class VoiceFactBridge:
assistant_text=reply_raw,
)
)
+ del session_turns[:-_CONTEXT_TURNS]
seen_ids.add(turn_id)
pending = _PendingTurn(
user_text=user_text,
@@ -373,350 +332,172 @@ class VoiceFactBridge:
self._decide_and_dispatch(pending, reply_raw)
async def _on_voice_session_ended(self, event: VoiceSessionEnded) -> None:
- """Schedule one full-run Realtime completeness sweep off the hot path."""
+ """Forget the call's reference-resolution context. Nothing else runs."""
session_id = (getattr(event, "session_id", "") or "").strip()
- turns = tuple(self._realtime_sessions.pop(session_id, ()))
+ self._realtime_sessions.pop(session_id, None)
self._realtime_turn_ids.pop(session_id, None)
- deferred = tuple(self._deferred_extractions.pop(session_id, ()))
- if deferred and self._extractor is not None:
- # Registered under the session BEFORE the sweep task is created,
- # so the sweep's inflight snapshot waits for these turn reviews
- # exactly as it waited for their in-call predecessors.
- flush = asyncio.create_task(
- self._run_deferred_extractions(session_id, deferred),
- name=f"wiki-realtime-deferred-extract-{session_id[:12]}",
- )
- self._inflight.add(flush)
- flush.add_done_callback(self._inflight.discard)
- session_tasks = self._session_inflight.setdefault(session_id, set())
- session_tasks.add(flush)
-
- def _discard_flush(done: asyncio.Task[Any]) -> None:
- active = self._session_inflight.get(session_id)
- if active is None:
- return
- active.discard(done)
- if not active:
- self._session_inflight.pop(session_id, None)
-
- flush.add_done_callback(_discard_flush)
- if self._extractor is None or not session_id or not turns:
- return
- task = asyncio.create_task(
- self._sweep_session_safe(session_id, turns),
- name=f"wiki-realtime-session-sweep-{session_id[:12]}",
- )
- self._inflight.add(task)
- task.add_done_callback(self._inflight.discard)
+
+ def _session_context(self, session_id: str) -> list[ConversationContextTurn]:
+ turns = self._realtime_sessions.get(session_id)
+ if turns is None:
+ turns = []
+ self._realtime_sessions[session_id] = turns
+ while len(self._realtime_sessions) > _MAX_TRACKED_SESSIONS:
+ stale, _turns = self._realtime_sessions.popitem(last=False)
+ self._realtime_turn_ids.pop(stale, None)
+ else:
+ self._realtime_sessions.move_to_end(session_id)
+ return turns
def _decide_and_dispatch(self, pending: _PendingTurn, reply_raw: str) -> bool:
- """Run ack-path first, then aggressive-path. At most one dispatch fires.
+ """Dispatch the turn when the brain acknowledged storing it.
- Returns ``True`` when the turn was consumed (dispatched) so callers
- holding pairing state know to clear it.
+ Returns ``True`` when the turn was consumed so callers holding
+ pairing state know to clear it. A reply without an acknowledgement
+ leaves the pending turn in place: a later part of the same reply may
+ still carry it.
"""
- jarvis_text = reply_raw.lower()
-
- # ---- Path 1: ack-keyword match -----------------------------------
- if jarvis_text and any(kw in jarvis_text for kw in _ACK_KEYWORDS):
- if len(pending.user_text) < _MIN_ACK_USER_CHARS:
- log.debug(
- "VoiceFactBridge: ack-keyword matched but user text too "
- "short (len=%d).",
- len(pending.user_text),
- )
- if self._extractor is not None:
- self._dispatch(
- pending,
- reply_raw,
- source_kind=f"{pending.origin}-filtered",
- )
- return True
- return False
- telemetry.inc("voice_turns_ingested_ack")
- log.debug(
- "VoiceFactBridge[ack]: brain acked storage, capturing user text "
- "(%d chars, lang=%s, origin=%s)",
- len(pending.user_text), pending.user_language, pending.origin,
- )
- self._dispatch(pending, reply_raw, source_kind=f"{pending.origin}-fact")
- return True
-
- # ---- Path 2: aggressive ingest -----------------------------------
- if not self._cfg.aggressive_mode:
+ reply = reply_raw.lower()
+ if not reply or not any(kw in reply for kw in _ACK_KEYWORDS):
return False
- min_chars = (
- self._extractor.min_user_chars
- if self._extractor is not None
- else int(self._cfg.min_user_chars)
- )
- if len(pending.user_text) < min_chars:
- if self._extractor is not None:
- self._dispatch(
- pending,
- reply_raw,
- source_kind=f"{pending.origin}-filtered",
- )
- return True
- return False
- if not self._aggressive_rate_limit_ok():
+ if len(pending.user_text) < _MIN_ACK_USER_CHARS:
log.debug(
- "VoiceFactBridge[aggressive]: rate-limited (last ingest "
- "%.1fs ago, limit=%ds).",
- (time.monotonic_ns() - self._last_aggressive_ns) / 1e9,
- self._cfg.rate_limit_seconds,
+ "VoiceFactBridge: acknowledgement matched but the user text is "
+ "too short (len=%d).",
+ len(pending.user_text),
)
return False
-
- self._last_aggressive_ns = time.monotonic_ns()
- telemetry.inc("voice_turns_ingested_aggressive")
+ telemetry.inc("voice_turns_ingested_ack")
log.debug(
- "VoiceFactBridge[aggressive]: brain did not ack but user text "
- "looks fact-shaped, capturing via salience filter "
+ "VoiceFactBridge: brain acknowledged a save, reviewing the user text "
"(%d chars, lang=%s, origin=%s)",
len(pending.user_text), pending.user_language, pending.origin,
)
- self._dispatch(pending, reply_raw, source_kind=f"{pending.origin}-aggressive")
+ self._dispatch(pending, reply_raw, source_kind=f"{pending.origin}-fact")
return True
# ------------------------------------------------------------------
- # ingest plumbing
+ # extraction plumbing
# ------------------------------------------------------------------
def _dispatch(
self, pending: _PendingTurn, reply_raw: str, *, source_kind: str,
) -> None:
- """Route one captured turn to Stage-1 extraction (or legacy ingest).
-
- Extractor mode dedupes by turn hash FIRST (in-memory LRU + the
- journal's durable ``seen_turn``) so the TranscriptFinal/MessageSent
- double delivery of one turn never extracts twice. Always
- fire-and-forget — the voice path is never blocked (AP-9).
- """
- if self._extractor is None:
- self._spawn_ingest(pending, source_kind=source_kind)
- return
-
+ """Start one deduped, fire-and-forget Stage-1 review (AP-9)."""
turn_hash = _turn_hash(pending.user_text)
review_key = pending.review_key or (
f"live:v2:{pending.origin}:{pending.captured_at_ns}:{turn_hash}"
)
if review_key in self._seen_hashes:
log.debug(
- "VoiceFactBridge: duplicate turn (hash=%s) — skipping extraction",
+ "VoiceFactBridge: duplicate turn (key=%s) — skipping",
review_key[-24:],
)
return
-
- if (
- pending.origin == "realtime"
- and pending.session_id
- and pending.session_id in self._realtime_sessions
- ):
- # The call is still live: hold the LLM round back (AP-9). The
- # turn is already deduped, so it is recorded as seen now — the
- # queue append cannot fail the way create_task can.
- queue = self._deferred_extractions.setdefault(
- pending.session_id, []
- )
- if len(queue) >= _DEFERRED_MAX_PER_SESSION:
- log.warning(
- "VoiceFactBridge: deferred-extraction queue full for %s "
- "— dropping turn (hash=%s)",
- pending.session_id[:12],
- review_key[-24:],
- )
- return
- queue.append(
- (pending, reply_raw, source_kind, turn_hash, review_key)
- )
- self._seen_hashes[review_key] = None
- while len(self._seen_hashes) > _SEEN_HASHES_MAX:
- self._seen_hashes.popitem(last=False)
- log.debug(
- "VoiceFactBridge[%s]: extraction deferred until session end "
- "(%d queued)",
- source_kind,
- len(queue),
- )
- return
-
+ job = _ExtractionJob(
+ pending=pending,
+ reply_raw=reply_raw,
+ source_kind=source_kind,
+ turn_hash=turn_hash,
+ review_key=review_key,
+ )
task = asyncio.create_task(
- self._extract_safe(
- pending,
- reply_raw,
- source_kind=source_kind,
- turn_hash=turn_hash,
- review_key=review_key,
- ),
+ self._extract_safe(job),
name=f"voice-fact-bridge-extract-{source_kind}",
)
- # Record the hash only AFTER the task was actually created — a
+ # Record the key only AFTER the task was actually created — a
# create_task failure (loop shutting down) must not permanently
- # block this turn text for the rest of the process lifetime. The
- # dispatch path runs on the event loop, so add-after-create cannot
- # race a concurrent dispatch of the same hash.
+ # block this turn text for the rest of the process lifetime.
self._seen_hashes[review_key] = None
while len(self._seen_hashes) > _SEEN_HASHES_MAX:
self._seen_hashes.popitem(last=False)
self._inflight.add(task)
task.add_done_callback(self._inflight.discard)
- if pending.session_id:
- session_tasks = self._session_inflight.setdefault(pending.session_id, set())
- session_tasks.add(task)
-
- def _discard_session_task(done: asyncio.Task[Any]) -> None:
- active = self._session_inflight.get(pending.session_id)
- if active is None:
- return
- active.discard(done)
- if not active:
- self._session_inflight.pop(pending.session_id, None)
-
- task.add_done_callback(_discard_session_task)
-
- def _spawn_ingest(self, pending: _PendingTurn, *, source_kind: str) -> None:
- """Start a fire-and-forget ingest task. Voice path is never blocked."""
- task = asyncio.create_task(
- self._ingest_safe(pending, source_kind=source_kind),
- name=f"voice-fact-bridge-{source_kind}",
- )
- self._inflight.add(task)
- task.add_done_callback(self._inflight.discard)
- async def _extract_safe(
- self,
- pending: _PendingTurn,
- reply_raw: str,
- *,
- source_kind: str,
- turn_hash: str,
- review_key: str,
- ) -> None:
+ async def _extract_safe(self, job: _ExtractionJob) -> bool:
"""Stage-1 extraction with broad exception handling (background only).
- The conversation must never notice a memory failure — log and move
- on; the worst case is one lost candidate fact.
+ Returns ``False`` when the wiki has to wait and the job was queued for
+ :meth:`retry_waiting`, ``True`` otherwise. The conversation must never
+ notice a memory failure — log and move on.
"""
try:
# ``capture_seen`` performs a locked SQLite lookup. Keep it off the
# latency-critical voice event loop (AP-9).
- if await asyncio.to_thread(self._extractor.capture_seen, review_key):
+ if await asyncio.to_thread(self._extractor.capture_seen, job.review_key):
log.debug(
- "VoiceFactBridge: turn already journaled (hash=%s) — skipping",
- review_key[-24:],
+ "VoiceFactBridge: turn already journaled (key=%s) — skipping",
+ job.review_key[-24:],
)
- return
+ return True
count = await self._extractor.extract_and_journal(
- pending.user_text,
- reply_raw,
- source_label=f"{source_kind}:{pending.captured_at_ns}",
- turn_hash=turn_hash,
- review_key=review_key,
- session_id=pending.session_id,
- turn_id=pending.turn_id,
- source_kind=source_kind,
- context_turns=pending.context_turns,
+ job.pending.user_text,
+ job.reply_raw,
+ source_label=f"{job.source_kind}:{job.pending.captured_at_ns}",
+ turn_hash=job.turn_hash,
+ review_key=job.review_key,
+ session_id=job.pending.session_id,
+ turn_id=job.pending.turn_id,
+ source_kind=job.source_kind,
+ context_turns=job.pending.context_turns,
)
log.info(
- "VoiceFactBridge[%s]: extraction done — %d candidate(s) journaled",
- source_kind, count,
+ "VoiceFactBridge[%s]: review done — %d candidate(s) journaled",
+ job.source_kind, count,
)
+ return True
+ except BackgroundDeferred as exc: # held for retry; _hold logs the wait
+ self._hold(job, reason=str(exc))
+ return False
except Exception: # noqa: BLE001
log.exception(
- "VoiceFactBridge[%s]: extraction failed, candidates lost.",
- source_kind,
+ "VoiceFactBridge[%s]: review failed, candidates lost.",
+ job.source_kind,
)
+ return True
- async def _run_deferred_extractions(
- self,
- session_id: str,
- jobs: tuple[tuple[_PendingTurn, str, str, str, str], ...],
- ) -> None:
- """Run the call's held-back per-turn extractions, one at a time.
-
- Sequential on purpose: firing the whole backlog concurrently at
- hangup would reproduce the in-call 429 retry storms this deferral
- removes, just compressed into one burst.
- """
+ def _hold(self, job: _ExtractionJob, *, reason: str) -> None:
+ if len(self._waiting) >= _MAX_WAITING_SAVES:
+ dropped = self._waiting.popleft()
+ log.warning(
+ "VoiceFactBridge: waiting queue full — dropping the oldest held "
+ "save (key=%s)",
+ dropped.review_key[-24:],
+ )
+ self._waiting.append(job)
log.info(
- "VoiceFactBridge: running %d deferred extraction(s) for %s",
- len(jobs),
- session_id[:12],
+ "VoiceFactBridge[%s]: explicit save held until the wiki may call a "
+ "model again (%d waiting) — %s",
+ job.source_kind,
+ len(self._waiting),
+ reason,
)
- for pending, reply_raw, source_kind, turn_hash, review_key in jobs:
- await self._extract_safe(
- pending,
- reply_raw,
- source_kind=source_kind,
- turn_hash=turn_hash,
- review_key=review_key,
- )
- async def _sweep_session_safe(
- self,
- session_id: str,
- turns: tuple[ConversationContextTurn, ...],
- ) -> None:
- """Wait for turn reviews, then audit the complete Realtime run once."""
- try:
- active = tuple(self._session_inflight.get(session_id, ()))
- if active:
- await asyncio.gather(*active, return_exceptions=True)
- count = await self._extractor.extract_session_and_journal(
- turns,
- session_id=session_id,
- source_label=f"realtime-session-sweep:{session_id}",
- )
- log.info(
- "VoiceFactBridge[session-sweep]: %d candidate(s) journaled for %s",
- count,
- session_id,
- )
- except asyncio.CancelledError:
- raise
- except Exception: # noqa: BLE001
- log.exception(
- "VoiceFactBridge[session-sweep]: extraction failed for %s",
- session_id,
- )
-
- def _aggressive_rate_limit_ok(self) -> bool:
- """True when at least ``rate_limit_seconds`` have passed since the last fire."""
- limit_ns = int(self._cfg.rate_limit_seconds) * 1_000_000_000
- return (time.monotonic_ns() - self._last_aggressive_ns) >= limit_ns
+ @property
+ def waiting_count(self) -> int:
+ """Explicit saves currently held for a later retry."""
+ return len(self._waiting)
- async def _ingest_safe(
- self, pending: _PendingTurn, *, source_kind: str,
- ) -> None:
- """Curator ingest with broad exception handling.
+ async def retry_waiting(self) -> int:
+ """Retry held explicit saves, oldest first; stop at the first new wait.
- Voice path must never crash because the wiki write failed -- log
- and move on. The user already finished their turn, so the worst
- case is a silent fact-loss, which is logged once.
+ Called by the wiki integration's background loop once the runaway
+ guard allows model calls again. Sequential on purpose: a burst of
+ held saves must not turn into a burst of parallel provider calls.
+ Returns how many held saves completed.
"""
- try:
- result = await self._curator.ingest(
- pending.user_text,
- f"{source_kind}:{pending.captured_at_ns}",
- )
- log.info(
- "VoiceFactBridge[%s]: ingest done -- %s",
- source_kind, _format_result(result),
- )
- except Exception: # noqa: BLE001
- log.exception(
- "VoiceFactBridge[%s]: ingest failed, fact lost.", source_kind,
- )
-
-
-def _format_result(result: Any) -> str:
- """Compact human-readable summary of a WriteResult for log lines."""
- applied = getattr(result, "applied", []) or []
- rolled = getattr(result, "failed_validation", []) or []
- skipped = getattr(result, "skipped_due_to_recent_edit", []) or []
- return (
- f"applied={len(applied)} "
- f"rolled_back={len(rolled)} "
- f"skipped={len(skipped)}"
- )
+ if not self._waiting:
+ return 0
+ done = 0
+ async with self._retry_lock:
+ while self._waiting:
+ job = self._waiting.popleft()
+ if not await self._extract_safe(job):
+ # ``_extract_safe`` re-queued it at the back; restore the
+ # original order so the oldest save stays first.
+ self._waiting.rotate(1)
+ break
+ done += 1
+ if done:
+ log.info("VoiceFactBridge: %d held explicit save(s) reviewed", done)
+ return done
diff --git a/jarvis/plugins/tool/wiki_ingest.py b/jarvis/plugins/tool/wiki_ingest.py
index 701cb5b843..9ee7418ff1 100644
--- a/jarvis/plugins/tool/wiki_ingest.py
+++ b/jarvis/plugins/tool/wiki_ingest.py
@@ -5,9 +5,9 @@ B5 follow-up (post-merge). Router-tier tool with write semantics.
Why this tool exists alongside the voice-bridge
-----------------------------------------------
:class:`jarvis.memory.wiki.voice_bridge.VoiceFactBridge` already pushes
-voice-spoken facts to the wiki via two heuristics: the *ack path* (brain
-reply acknowledges a saved fact) and the *aggressive path*
-(every user turn >= ``min_user_chars`` is curator-filtered).
+voice-spoken facts to the wiki via one heuristic: the *ack path* (brain
+reply acknowledges a saved fact). The former *aggressive path* that
+reviewed every user turn was removed on 2026-09-30.
Heuristics drift. When the brain consciously decides "this is worth
storing" (e.g. user typed something into chat, or the brain is
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index b032d8adc9..355a2b7e80 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -166,8 +166,6 @@ class WebServer:
self._task_cancel_token: Any | None = None
# Phase B5 wiki write-wiring handle — shutdown() called in stop().
self._wiki_integration_handle: Any | None = None
- # Periodic evidence-safe realtime wiki backfill — cancelled in stop().
- self._wiki_backfill_task: asyncio.Task[None] | None = None
# Phase B3 wiki live-reload watchdog handle — shutdown() called in stop().
self._wiki_watcher: Any | None = None
self._channel_chat_bridge: Any | None = None
@@ -3217,19 +3215,13 @@ class WebServer:
config=wiki_cfg,
brain_caller=None, # curator uses BrainProviderRegistry internally
scheduler_factory=_wiki_scheduler_factory,
- voice_bridge_config=self.cfg.memory.wiki.voice_bridge,
)
self._wiki_integration_handle = handle
logger.info("wiki_integration: bootstrap_wiki_integration succeeded")
- # Safety net for realtime turns whose live capture was missed (empty
- # provider input transcript, crash, provider outage): sweep persisted
- # sessions periodically. Idempotent via durable review keys, so a
- # session already reviewed live is skipped, never re-journaled. The
- # manual POST /api/wiki/backfill stays the explicit control.
- if self._wiki_backfill_task is None:
- self._wiki_backfill_task = asyncio.create_task(
- self._wiki_auto_backfill_loop(), name="wiki-auto-backfill"
- )
+ # No periodic re-review of voice sessions: the six-hourly auto-backfill
+ # was removed on 2026-09-30 together with the per-turn and end-of-call
+ # extraction (it billed paid keys while nobody was at the PC). The
+ # manual POST /api/wiki/backfill is the explicit control.
try:
from jarvis.memory.wiki.health import health as _wiki_health
@@ -3237,63 +3229,6 @@ class WebServer:
except Exception: # noqa: BLE001 — health recording must never break boot
logger.debug("wiki health.record_bootstrap(True) failed", exc_info=True)
- async def _wiki_auto_backfill_loop(
- self,
- *,
- initial_delay_s: float = 300.0,
- interval_s: float = 6 * 3600.0,
- ) -> None:
- """Periodically sweep persisted realtime sessions into the wiki.
-
- The live per-turn capture silently loses a turn whenever the realtime
- provider delivers no input transcript, and the session-end sweep dies
- with whichever layer misses its teardown. ``backfill_realtime_sessions``
- re-reads the persisted voice turns and runs the same evidence-bound
- pipeline, idempotent across retries via durable review keys — so this
- loop only ever pays for sessions live capture actually missed. First
- run is delayed well past boot readiness (AP-26); every pass is bounded
- (2 days, 20 sessions).
- """
- from jarvis.memory.wiki.backfill import backfill_realtime_sessions
- from jarvis.memory.wiki.integration import get_running_capture_runtime
-
- await asyncio.sleep(initial_delay_s)
- while True:
- try:
- runtime = get_running_capture_runtime()
- store = getattr(self.app.state, "session_store", None)
- if runtime is None or store is None or runtime.scheduler is None:
- logger.debug(
- "wiki auto-backfill: capture runtime or session store "
- "not ready — skipping this pass"
- )
- else:
- result = await backfill_realtime_sessions(
- store=store,
- extractor=runtime.extractor,
- days=2,
- max_sessions=20,
- dry_run=False,
- )
- if result.sessions_reviewed or result.candidates_journaled:
- logger.info(
- "wiki auto-backfill: reviewed {} session(s), journaled {} candidate(s)",
- result.sessions_reviewed,
- result.candidates_journaled,
- )
- else:
- logger.debug(
- "wiki auto-backfill: nothing eligible "
- "(scanned={}, already_reviewed={})",
- result.sessions_scanned,
- result.sessions_already_reviewed,
- )
- except asyncio.CancelledError:
- raise
- except Exception: # noqa: BLE001 — the safety net must never crash the app
- logger.opt(exception=True).warning("wiki auto-backfill pass failed")
- await asyncio.sleep(interval_s)
-
def _init_wiki_boot_index(self, *, background: bool = False) -> None:
"""Rebuild the derived FTS view against the active vault.
@@ -3971,12 +3906,6 @@ class WebServer:
except Exception as exc: # noqa: BLE001
logger.opt(exception=exc).debug("Board-Aggregator close(): {}", exc)
- # Stop the periodic realtime backfill before the wiki runtime goes away.
- backfill_task = getattr(self, "_wiki_backfill_task", None)
- if backfill_task is not None:
- backfill_task.cancel()
- self._wiki_backfill_task = None
-
# Phase B5 wiki write-wiring: unsubscribe + drain in-flight rollup task.
wiki_handle = getattr(self, "_wiki_integration_handle", None)
if wiki_handle is not None:
diff --git a/scripts/ci/test-baseline-windows.json b/scripts/ci/test-baseline-windows.json
index a0bb8049d3..c92fa16831 100644
--- a/scripts/ci/test-baseline-windows.json
+++ b/scripts/ci/test-baseline-windows.json
@@ -84,9 +84,6 @@
"tests.unit.dictation.test_polish_timeout_ramp::test_a_maximum_at_the_base_switches_the_ramp_off",
"tests.unit.dictation.test_polish_timeout_ramp::test_a_short_dictation_keeps_the_configured_ceiling",
"tests.unit.local_models.test_assistant_tools::test_test_plan_tool_reports_per_role",
- "tests.unit.memory.wiki.test_voice_bridge_realtime::test_aggressive_path_is_rate_limited_across_realtime_turns",
- "tests.unit.memory.wiki.test_voice_bridge_realtime::test_default_reviews_consecutive_realtime_turns",
- "tests.unit.memory.wiki.test_voice_bridge_realtime::test_empty_reply_does_not_block_aggressive_path",
"tests.unit.plugins.brain.test_local_openai::test_client_appends_v1_to_root",
"tests.unit.plugins.brain.test_local_openai::test_client_normalizes_pasted_v1",
"tests.unit.plugins.brain.test_local_openai::test_client_timeout_fast_connect_wide_read",
diff --git a/tests/integration/memory/test_aggressive_ingest.py b/tests/integration/memory/test_aggressive_ingest.py
deleted file mode 100644
index cb4ebd4e93..0000000000
--- a/tests/integration/memory/test_aggressive_ingest.py
+++ /dev/null
@@ -1,426 +0,0 @@
-"""Integration tests for :class:`VoiceFactBridge` aggressive-ingest path (B8.6).
-
-The bridge has two paths from voice turn -> wiki:
-
-1. The B5 *ack path*: trigger when the brain's reply contains "notiert",
- "vermerkt", etc.
-2. The B8 *aggressive path*: trigger on every user turn with at least
- ``min_user_chars`` characters, even when the brain did not ack. The
- curator's prompt is the salience filter -- smalltalk returns [] and
- produces no on-disk artefact.
-
-These tests run the full bridge -> curator -> AtomicWriter -> disk
-pipeline. The only mocked piece is the curator's LLM (``propose_updates``)
--- we drive it with a scripted return so we control whether the
-salience filter says "fact" or "smalltalk".
-
-Acceptance criteria from B8:
-
-* Pad-Thai utterance + non-ack brain reply -> page lands on disk.
-* "hallo, wie geht's" + non-ack brain reply -> no page lands.
-* The legacy ack path (`brain says "Notiert."`) keeps working.
-"""
-from __future__ import annotations
-
-import asyncio
-from pathlib import Path
-from unittest.mock import patch
-
-import pytest
-import pytest_asyncio
-
-from jarvis.core.bus import EventBus
-from jarvis.core.config import VoiceBridgeConfig
-from jarvis.core.events import ResponseGenerated, TranscriptFinal
-from jarvis.core.protocols import Transcript
-from jarvis.memory.wiki.atomic_writer import AtomicWriter
-from jarvis.memory.wiki.curator import WikiCurator
-from jarvis.memory.wiki.curator_llm import WikiCuratorLLM
-from jarvis.memory.wiki.log_writer import LogWriter
-from jarvis.memory.wiki.page import MarkdownPageRepository
-from jarvis.memory.wiki.protocols import PageUpdate
-from jarvis.memory.wiki.vault_index import VaultIndex
-from jarvis.memory.wiki.voice_bridge import VoiceFactBridge
-
-
-# ---------------------------------------------------------------------------
-# Fixtures: real curator + writer + vault, mocked-out CuratorLLM
-# ---------------------------------------------------------------------------
-
-
-def _entity_body(slug: str, summary_line: str) -> str:
- """Minimal schema-compliant entity-page body. Mirrors the canonical
- template used in the curator-ingest E2E test."""
- return (
- "---\n"
- "type: entity\n"
- "entity_kind: person\n"
- f"slug: {slug}\n"
- "aliases: []\n"
- "created: 2026-05-14\n"
- "updated: 2026-05-14\n"
- "---\n"
- "\n"
- f"# {slug.title()}\n"
- "\n"
- "## Summary\n"
- "\n"
- f"{summary_line}\n"
- "\n"
- "## Facts\n"
- "\n"
- "- TODO\n"
- "\n"
- "## Relationships\n"
- "\n"
- "- TODO\n"
- "\n"
- "## Sources\n"
- "\n"
- "- voice-aggressive fixture\n"
- )
-
-
-@pytest_asyncio.fixture
-async def stack(tmp_path: Path):
- """Build the real curator pipeline with an empty on-disk vault."""
- vault_root = tmp_path / "workspace"
- for sub in ("entities", "concepts", "projects", "sessions", "_archive", "attachments"):
- (vault_root / sub).mkdir(parents=True)
- (vault_root / "schema.md").write_text("# stub schema\n", encoding="utf-8")
- (vault_root / "index.md").write_text(
- "# Index\n\n## Entities\n\n(empty)\n", encoding="utf-8"
- )
- (vault_root / "log.md").write_text("# Wiki Log\n", encoding="utf-8")
-
- backup_dir = tmp_path / "backups"
- repo = MarkdownPageRepository()
- vault = VaultIndex(repo=repo)
- await vault.scan(vault_root)
- writer = AtomicWriter(vault_root=vault_root, backup_dir=backup_dir)
- log_writer = LogWriter(log_path=vault_root / "log.md")
-
- # Curator-LLM is bypassed (we only need ``propose_updates`` which the
- # tests patch per-case). Following the E2E-test convention from
- # tests/integration/memory/wiki/test_curator_ingest_e2e.py.
- llm = WikiCuratorLLM.__new__(WikiCuratorLLM)
-
- curator = WikiCurator(
- repo=repo,
- vault=vault,
- writer=writer,
- llm=llm,
- log_writer=log_writer,
- vault_root=vault_root,
- )
-
- bus = EventBus()
- yield curator, vault_root, bus
-
-
-async def _drive_voice_turn(
- bus: EventBus,
- *,
- user_text: str,
- brain_text: str,
-) -> None:
- """Publish a TranscriptFinal + ResponseGenerated pair and let the
- bridge process them. The brief sleep gives the fire-and-forget
- ingest task room to run before we inspect disk."""
- await bus.publish(TranscriptFinal(
- transcript=Transcript(text=user_text, language="de", confidence=0.95),
- timestamp_ns=42,
- ))
- await bus.publish(ResponseGenerated(text=brain_text, language="de"))
- # Give the background ingest a few event-loop ticks to land. The
- # curator + AtomicWriter chain is ~100 ms in this test setup.
- for _ in range(8):
- await asyncio.sleep(0.05)
-
-
-# ---------------------------------------------------------------------------
-# Aggressive path
-# ---------------------------------------------------------------------------
-
-
-async def test_pad_thai_lands_in_wiki_without_brain_ack(stack) -> None:
- """The headline scenario: fact-shaped user text + non-ack brain reply
- must still produce a wiki page via the aggressive path."""
- curator, vault_root, bus = stack
-
- bridge = VoiceFactBridge(
- bus=bus,
- curator=curator,
- config=VoiceBridgeConfig(
- aggressive_mode=True,
- min_user_chars=30,
- rate_limit_seconds=0, # disable rate-limit for the test
- ),
- )
- bridge.start()
-
- # The curator-LLM acts as the salience filter. Here it produces a
- # carlos.md entity page -- the LLM has decided "Pad-Thai with Carlos"
- # is a fact worth persisting.
- carlos_update = PageUpdate(
- target_path=vault_root / "entities" / "carlos.md",
- operation="create",
- new_body=_entity_body(
- "carlos",
- "Carlos went out for Pad Thai with Ruben on 2026-05-14.",
- ),
- reason="new fact about a person",
- )
-
- with patch.object(
- curator._llm, "propose_updates", return_value=[carlos_update],
- ):
- await _drive_voice_turn(
- bus,
- user_text="Ich war heute mit Carlos Pad-Thai essen, er hat mir von seinem Boss erzaehlt.", # i18n-allow
- brain_text="Klingt lecker, war es scharf?",
- )
-
- bridge.stop()
-
- page = vault_root / "entities" / "carlos.md"
- assert page.is_file(), "Pad-Thai fact should have produced entities/carlos.md"
- assert "Pad Thai" in page.read_text(encoding="utf-8")
-
-
-async def test_smalltalk_produces_no_page(stack) -> None:
- """Salience filter (curator prompt) decides smalltalk -> [].
- Even when the bridge fires the ingest, no page lands on disk."""
- curator, vault_root, bus = stack
-
- bridge = VoiceFactBridge(
- bus=bus,
- curator=curator,
- config=VoiceBridgeConfig(
- aggressive_mode=True,
- min_user_chars=30,
- rate_limit_seconds=0,
- ),
- )
- bridge.start()
-
- # Curator-LLM returns empty -- this is the "smalltalk, drop it"
- # decision. The bridge still calls the curator, but no page lands.
- with patch.object(
- curator._llm, "propose_updates", return_value=[],
- ) as proposer:
- await _drive_voice_turn(
- bus,
- # 38 chars > 30 threshold so the bridge actually fires.
- user_text="Hallo Jarvis, wie geht es dir denn so?",
- brain_text="Mir geht's gut, danke der Nachfrage!",
- )
-
- bridge.stop()
-
- # The curator was offered the chance to act -- and declined.
- assert proposer.called, (
- "aggressive path should have called the curator even for "
- "smalltalk-looking text; the salience filter lives inside the "
- "curator's prompt, not in the bridge"
- )
- # ... and produced no on-disk artefacts.
- assert list((vault_root / "entities").glob("*.md")) == []
-
-
-async def test_short_text_skips_aggressive_path(stack) -> None:
- """Below the min_user_chars cut-off the bridge never calls the curator."""
- curator, _vault_root, bus = stack
-
- bridge = VoiceFactBridge(
- bus=bus,
- curator=curator,
- config=VoiceBridgeConfig(
- aggressive_mode=True,
- min_user_chars=30,
- rate_limit_seconds=0,
- ),
- )
- bridge.start()
-
- with patch.object(
- curator._llm, "propose_updates", return_value=[],
- ) as proposer:
- await _drive_voice_turn(
- bus,
- user_text="hallo", # 5 chars -- way below 30
- brain_text="hi!",
- )
-
- bridge.stop()
- assert not proposer.called, (
- "trivial utterances must be filtered out by the bridge BEFORE "
- "the curator/LLM is consulted -- otherwise wake-word noise burns "
- "LLM calls"
- )
-
-
-# ---------------------------------------------------------------------------
-# Ack path keeps working (regression guard)
-# ---------------------------------------------------------------------------
-
-
-async def test_ack_path_still_fires_when_brain_says_notiert(stack) -> None:
- """The B5 ack path must keep working alongside the aggressive path."""
- curator, vault_root, bus = stack
-
- bridge = VoiceFactBridge(
- bus=bus,
- curator=curator,
- config=VoiceBridgeConfig(
- aggressive_mode=True,
- min_user_chars=30,
- rate_limit_seconds=0,
- ),
- )
- bridge.start()
-
- harald_update = PageUpdate(
- target_path=vault_root / "entities" / "harald.md",
- operation="create",
- new_body=_entity_body("harald", "Harald wurde 1976 geboren."), # i18n-allow
- reason="explicit user note",
- )
-
- with patch.object(
- curator._llm, "propose_updates", return_value=[harald_update],
- ):
- await _drive_voice_turn(
- bus,
- user_text="Harald wurde 1976 geboren.", # 26 chars -- below aggressive min # i18n-allow
- brain_text="Notiert.", # explicit ack keyword
- )
-
- bridge.stop()
-
- page = vault_root / "entities" / "harald.md"
- assert page.is_file(), (
- "ack path must still fire for fact-shaped texts even when they "
- "are below the aggressive-path min_user_chars threshold"
- )
-
-
-async def test_ack_path_and_aggressive_path_do_not_double_ingest(stack) -> None:
- """When the brain acks AND the text is long enough for the aggressive
- path, exactly one ingest fires -- ack-path wins, _pending is cleared."""
- curator, vault_root, bus = stack
-
- bridge = VoiceFactBridge(
- bus=bus,
- curator=curator,
- config=VoiceBridgeConfig(
- aggressive_mode=True,
- min_user_chars=30,
- rate_limit_seconds=0,
- ),
- )
- bridge.start()
-
- update = PageUpdate(
- target_path=vault_root / "entities" / "ruben.md",
- operation="create",
- new_body=_entity_body("ruben", "Ruben rebuilt the wiki system."),
- reason="ack path fact",
- )
-
- with patch.object(
- curator._llm, "propose_updates", return_value=[update],
- ) as proposer:
- await _drive_voice_turn(
- bus,
- user_text="Ich habe heute das gesamte Wiki-System neu aufgebaut.",
- brain_text="Notiert.",
- )
-
- bridge.stop()
-
- # Exactly one ingest call -- not two. The ack path fires first and
- # clears self._pending so the aggressive branch finds nothing.
- assert proposer.call_count == 1
-
-
-# ---------------------------------------------------------------------------
-# Rate-limit on the aggressive path
-# ---------------------------------------------------------------------------
-
-
-async def test_rate_limit_drops_second_aggressive_ingest_within_window(stack) -> None:
- """With rate_limit_seconds=60 the second voice turn within a minute
- must not trigger a second aggressive ingest."""
- curator, _vault_root, bus = stack
-
- bridge = VoiceFactBridge(
- bus=bus,
- curator=curator,
- config=VoiceBridgeConfig(
- aggressive_mode=True,
- min_user_chars=30,
- rate_limit_seconds=60, # the real-world default
- ),
- )
- bridge.start()
-
- with patch.object(
- curator._llm, "propose_updates", return_value=[],
- ) as proposer:
- await _drive_voice_turn(
- bus,
- user_text="Mein Lieblingsfilm ist Inception und ich liebe Nolan-Filme.", # i18n-allow
- brain_text="Cool, was hat dich daran beruehrt?",
- )
- # Same window -- second aggressive ingest must NOT fire.
- await _drive_voice_turn(
- bus,
- user_text="Mein Lieblingsessen ist Pizza und am liebsten mit Salami.", # i18n-allow
- brain_text="Klassiker. Italienisch oder amerikanisch?",
- )
-
- bridge.stop()
- assert proposer.call_count == 1, (
- "second aggressive ingest within the rate-limit window must be "
- "dropped to avoid burning LLM calls on consecutive turns"
- )
-
-
-async def test_aggressive_mode_off_disables_path_entirely(stack) -> None:
- """``aggressive_mode=False`` keeps the ack path on but never fires
- the aggressive path."""
- curator, _vault_root, bus = stack
-
- bridge = VoiceFactBridge(
- bus=bus,
- curator=curator,
- config=VoiceBridgeConfig(
- aggressive_mode=False,
- min_user_chars=30,
- rate_limit_seconds=0,
- ),
- )
- bridge.start()
-
- with patch.object(
- curator._llm, "propose_updates", return_value=[],
- ) as proposer:
- await _drive_voice_turn(
- bus,
- user_text="Mein Lieblingsfilm ist Inception und das ist die volle Wahrheit.", # i18n-allow
- brain_text="Klingt nach einem guten Film!", # i18n-allow
- )
-
- bridge.stop()
- assert not proposer.called, (
- "with aggressive_mode=False, a non-ack reply must NOT trigger "
- "a curator call"
- )
diff --git a/tests/integration/memory/test_three_triggers.py b/tests/integration/memory/test_three_triggers.py
index e3e9b8e3c0..b47cd67056 100644
--- a/tests/integration/memory/test_three_triggers.py
+++ b/tests/integration/memory/test_three_triggers.py
@@ -1,35 +1,22 @@
-"""Three-trigger regression suite -- the whole memory pipeline at once (B8.10).
-
-The wiki memory has three independent triggers that must all stay green
-for the system to be considered intact:
-
-1. :class:`WikiContextInjector` -- runs on every brain turn and
- prepends matching vault snippets to the system prompt.
-2. :class:`VoiceFactBridge` -- listens for ``TranscriptFinal`` +
- ``ResponseGenerated`` and feeds the user text to the curator on
- either the ack path (B5) or the aggressive path (B8).
-3. :class:`SessionRollupWorker` -- listens for ``IdleEntered`` and
- rolls awareness episodes into a session markdown page.
-
-Each trigger already has its own focused suite. This file is the
-*cross-trigger* one: ten cases that exercise the three together
-against a single shared tmp-vault. A green run is the strongest
-single signal that the wiki memory subsystem is intact.
-
-Design notes
-------------
-* AP-5 from B5: no SQLite mocking. :class:`RecallStore` runs against a
- real on-disk SQLite file.
-* AP-6 from B5: every test uses a single shared :class:`EventBus`.
-* The curator's LLM is the only stubbed-out component (we do not want
- a live brain call in CI). Stubbed via ``patch.object(curator._llm,
- "propose_updates", ...)``.
-* The rollup worker's brain is bypassed via a small private
- :class:`_FakeStreamBrain` -- it satisfies the
- ``BrainRequest -> AsyncIterator[BrainDelta]`` contract that
- :func:`session_rollup._call_brain` consumes.
-* Telemetry is reset before each test so counters reflect the
- individual case.
+"""Memory triggers regression suite -- context injection plus session rollup.
+
+Two wiki triggers must stay green together against one shared tmp-vault:
+
+1. :class:`WikiContextInjector` -- runs on every brain turn and prepends
+ matching vault snippets to the system prompt (LLM-free).
+2. :class:`SessionRollupWorker` -- listens for ``IdleEntered`` and rolls
+ awareness episodes into a session markdown page. Retired by default
+ (``wiki_write_enabled`` off, no built-in ``IdleEntered`` publisher); this
+ suite opts back in to keep the code path honest.
+
+The former third trigger, the voice bridge's automatic review of every user
+turn, was removed on 2026-09-30; explicit saves are pinned in
+``tests/unit/memory/wiki/test_conversation_observer.py``.
+
+* AP-5 from B5: no SQLite mocking. :class:`RecallStore` runs against a real
+ on-disk SQLite file.
+* The rollup worker's brain is a small private :class:`_FakeStreamBrain`.
+* Telemetry is reset before each test so counters reflect the case.
"""
from __future__ import annotations
@@ -39,34 +26,24 @@ import time
from collections.abc import AsyncIterator
from pathlib import Path
from typing import Any
-from unittest.mock import MagicMock, patch
import pytest
import pytest_asyncio
from jarvis.brain.wiki_context import WikiContextInjector
from jarvis.core.bus import EventBus
-from jarvis.core.config import (
- JarvisConfig,
- SessionRollupConfig,
- VoiceBridgeConfig,
-)
-from jarvis.core.events import IdleEntered, ResponseGenerated, TranscriptFinal
-from jarvis.core.protocols import BrainDelta, BrainRequest, Transcript
+from jarvis.core.config import JarvisConfig, SessionRollupConfig
+from jarvis.core.events import IdleEntered
+from jarvis.core.protocols import BrainDelta, BrainRequest
from jarvis.memory.recall import RecallStore
from jarvis.memory.wiki.atomic_writer import AtomicWriter
-from jarvis.memory.wiki.curator import WikiCurator
-from jarvis.memory.wiki.curator_llm import WikiCuratorLLM
+from jarvis.memory.wiki.fts_index import rebuild_index
from jarvis.memory.wiki.log_writer import LogWriter
from jarvis.memory.wiki.page import MarkdownPageRepository
-from jarvis.memory.wiki.protocols import PageUpdate
-from jarvis.memory.wiki.fts_index import rebuild_index
from jarvis.memory.wiki.search import VaultSearch
from jarvis.memory.wiki.session_rollup import SessionRollupWorker
from jarvis.memory.wiki.telemetry import telemetry
from jarvis.memory.wiki.vault_index import VaultIndex
-from jarvis.memory.wiki.voice_bridge import VoiceFactBridge
-
NS_PER_MIN = 60 * 1_000_000_000
@@ -126,59 +103,6 @@ class _SpyRegistry:
return self._brain
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _entity_body(slug: str, summary: str, facts: list[str] | None = None) -> str:
- """Schema-compliant entity page body."""
- fact_lines = "\n".join(f"- {f}" for f in (facts or ["TODO"]))
- return (
- "---\n"
- "type: entity\n"
- "entity_kind: person\n"
- f"slug: {slug}\n"
- "aliases: []\n"
- "created: 2026-05-14\n"
- "updated: 2026-05-14\n"
- "---\n"
- "\n"
- f"# {slug.title()}\n"
- "\n"
- "## Summary\n"
- "\n"
- f"{summary}\n"
- "\n"
- "## Facts\n"
- "\n"
- f"{fact_lines}\n"
- "\n"
- "## Relationships\n"
- "\n"
- "- TODO\n"
- "\n"
- "## Sources\n"
- "\n"
- "- three-trigger test\n"
- )
-
-
-async def _drive_voice_turn(
- bus: EventBus, *, user_text: str, brain_text: str,
-) -> None:
- """Publish one voice-turn pair and let the bridge react."""
- await bus.publish(TranscriptFinal(
- transcript=Transcript(text=user_text, language="de", confidence=0.95),
- timestamp_ns=int(time.time_ns()),
- ))
- await bus.publish(ResponseGenerated(text=brain_text, language="de"))
- # The bridge spawns fire-and-forget ingest tasks; give them a few
- # event-loop ticks to land in this single-process test setup.
- for _ in range(8):
- await asyncio.sleep(0.05)
-
-
async def _seed_episode(
recall: RecallStore, *, started_at_ns: int, summary: str, app: str = "code.exe",
) -> int:
@@ -192,12 +116,6 @@ async def _seed_episode(
)
-# ---------------------------------------------------------------------------
-# Big shared fixture: real curator + writer + recall + bridge + rollup +
-# injector. All three triggers wired against one tmp-vault on disk.
-# ---------------------------------------------------------------------------
-
-
@pytest_asyncio.fixture
async def stack(tmp_path: Path):
vault_root = tmp_path / "workspace"
@@ -209,32 +127,13 @@ async def stack(tmp_path: Path):
)
(vault_root / "log.md").write_text("# Wiki Log\n", encoding="utf-8")
- backup_dir = tmp_path / "backups"
bus = EventBus()
repo = MarkdownPageRepository()
vault = VaultIndex(repo=repo)
await vault.scan(vault_root)
- writer = AtomicWriter(vault_root=vault_root, backup_dir=backup_dir)
+ writer = AtomicWriter(vault_root=vault_root, backup_dir=tmp_path / "backups")
log_writer = LogWriter(log_path=vault_root / "log.md")
- # Curator-LLM is bypassed -- tests patch ``propose_updates`` per case.
- llm = WikiCuratorLLM.__new__(WikiCuratorLLM)
- curator = WikiCurator(
- repo=repo, vault=vault, writer=writer, llm=llm,
- log_writer=log_writer, vault_root=vault_root,
- )
-
- # Voice bridge.
- bridge = VoiceFactBridge(
- bus=bus, curator=curator,
- config=VoiceBridgeConfig(
- aggressive_mode=True, min_user_chars=30, rate_limit_seconds=0,
- ),
- )
- bridge.start()
-
- # Rollup worker. We craft a small ``JarvisConfig``-like surface for
- # the worker -- only the bits the worker actually reads are populated.
full_config = JarvisConfig()
full_config.memory.wiki.session_rollup = SessionRollupConfig(
enabled=True,
@@ -266,11 +165,9 @@ async def stack(tmp_path: Path):
rollup._cfg = rollup._cfg.model_copy(update={"wiki_write_enabled": True}) # noqa: SLF001
await rollup.start()
- # Context injector consumes the same on-disk vault. VaultSearch reads
- # the FTS index, which in production is fed by the boot reconcile
- # (wiki_boot_index -> rebuild_index) and the live vault watcher; neither
- # runs in this fixture, so tests re-run rebuild_index (the boot step)
- # before every injector expectation.
+ # The injector reads the FTS index, fed in production by the boot
+ # reconcile and the vault watcher; neither runs here, so tests re-run
+ # rebuild_index (the boot step) before every injector expectation.
fts_conn = sqlite3.connect(":memory:", check_same_thread=False)
rebuild_index(vault_root, fts_conn)
search = VaultSearch(vault_root, conn=fts_conn)
@@ -280,75 +177,26 @@ async def stack(tmp_path: Path):
min_keyword_length=4,
)
- # Reset telemetry so counters reflect just this test.
telemetry.reset()
yield {
"vault_root": vault_root,
"bus": bus,
- "curator": curator,
- "bridge": bridge,
"rollup": rollup,
+ "registry": registry,
"fake_rollup_brain": fake_rollup_brain,
"recall": recall,
"clock_holder": clock_holder,
"injector": injector,
- "search": search,
"fts_conn": fts_conn,
}
- bridge.stop()
await rollup.stop()
await recall.close()
# ===========================================================================
-# Case 1 -- Happy-Path: voice fact lands AND becomes context next turn
-# ===========================================================================
-
-
-async def test_voice_fact_becomes_context_on_next_turn(stack) -> None:
- """One spoken fact must (a) land in the wiki via the bridge and
- (b) be retrievable by the injector on the next brain turn."""
- s = stack
- vault_root = s["vault_root"]
-
- update = PageUpdate(
- target_path=vault_root / "entities" / "ruben.md",
- operation="create",
- new_body=_entity_body(
- "ruben",
- "Ruben's favourite movie is Inception by Christopher Nolan.",
- facts=["Lieblingsfilm: Inception", "Nolan-Fan since 2010"],
- ),
- reason="user identity fact",
- )
-
- with patch.object(s["curator"]._llm, "propose_updates", return_value=[update]):
- await _drive_voice_turn(
- s["bus"],
- user_text="Mein Lieblingsfilm ist Inception und Nolan ist der beste Regisseur.", # i18n-allow
- brain_text="Cool, Nolan ist wirklich stark.", # no ack -> aggressive path
- )
-
- page = vault_root / "entities" / "ruben.md"
- assert page.is_file(), "voice fact should have produced a wiki page"
-
- # Next turn: the injector finds the freshly-written page and
- # prepends it to the system prompt.
- base_prompt = "You are Personal Jarvis."
- rebuild_index(s["vault_root"], s["fts_conn"]) # the boot/watcher index step
- augmented = await s["injector"].maybe_inject(
- user_text="Was war nochmal mein Lieblingsfilm?",
- system_prompt=base_prompt,
- )
- assert "Wiki context" in augmented, "injector should have prepended a context block"
- assert "Inception" in augmented, "the just-ingested fact must be in the context"
-
-
-# ===========================================================================
-# Case 2 -- Rollup-Path: episodes -> idle -> session page -> visible to injector
+# Case 1 -- Rollup-Path: episodes -> idle -> session page -> visible to injector
# ===========================================================================
@@ -393,221 +241,20 @@ async def test_rollup_produces_session_page_visible_to_injector(stack) -> None:
# ===========================================================================
-# Case 3 -- Smalltalk: 5 hallo-turns produce no wiki pages
-# ===========================================================================
-
-
-async def test_smalltalk_burst_produces_no_pages(stack) -> None:
- """Five short greeting turns must NOT leak into the wiki."""
- s = stack
- vault_root = s["vault_root"]
-
- # The curator's LLM is patched but we expect it never to be called
- # on these too-short inputs.
- with patch.object(
- s["curator"]._llm, "propose_updates", return_value=[],
- ) as proposer:
- for _ in range(5):
- await _drive_voice_turn(
- s["bus"],
- user_text="hallo", # 5 chars -- below 30
- brain_text="hi!",
- )
-
- assert list((vault_root / "entities").glob("*.md")) == []
- assert not proposer.called, (
- "trivial greetings must never reach the curator (LLM-call protection)"
- )
-
-
-# ===========================================================================
-# Case 4 -- Ack path isolated
-# ===========================================================================
-
-
-async def test_ack_path_alone_creates_page(stack) -> None:
- """Brain explicitly acks -> ack path fires regardless of utterance length."""
- s = stack
- vault_root = s["vault_root"]
-
- harald_update = PageUpdate(
- target_path=vault_root / "entities" / "harald.md",
- operation="create",
- new_body=_entity_body("harald", "Harald wurde 1976 geboren."), # i18n-allow
- reason="ack-path fact",
- )
-
- with patch.object(
- s["curator"]._llm, "propose_updates", return_value=[harald_update],
- ):
- await _drive_voice_turn(
- s["bus"],
- user_text="Harald wurde 1976 geboren.", # 26 chars -- below aggressive min # i18n-allow
- brain_text="Notiert.", # explicit ack keyword
- )
-
- assert (vault_root / "entities" / "harald.md").is_file()
- assert telemetry.get("voice_turns_ingested_ack") == 1
- assert telemetry.get("voice_turns_ingested_aggressive") == 0
-
-
-# ===========================================================================
-# Case 5 -- Aggressive path isolated
-# ===========================================================================
-
-
-async def test_aggressive_path_alone_creates_page(stack) -> None:
- """Brain replies conversationally -> aggressive path fires on long-enough text."""
- s = stack
- vault_root = s["vault_root"]
-
- carlos_update = PageUpdate(
- target_path=vault_root / "entities" / "carlos.md",
- operation="create",
- new_body=_entity_body(
- "carlos",
- "Carlos went out for Pad Thai with Ruben on 2026-05-14.",
- ),
- reason="aggressive-path fact",
- )
-
- with patch.object(
- s["curator"]._llm, "propose_updates", return_value=[carlos_update],
- ):
- await _drive_voice_turn(
- s["bus"],
- user_text="Ich war heute mit Carlos Pad-Thai essen, war richtig lecker.",
- brain_text="Klingt gut, wo wart ihr?",
- )
-
- assert (vault_root / "entities" / "carlos.md").is_file()
- assert telemetry.get("voice_turns_ingested_aggressive") == 1
- assert telemetry.get("voice_turns_ingested_ack") == 0
-
-
-# ===========================================================================
-# Case 6 -- Voice-path latency: bridge handlers must return promptly
-# ===========================================================================
-
-
-async def test_voice_path_handlers_do_not_block_voice(stack) -> None:
- """``_on_transcript_final`` + ``_on_response_generated`` together must
- return well within the voice-path budget. Ingest itself can take
- seconds; the handlers must just spawn a background task and exit."""
- s = stack
- vault_root = s["vault_root"]
-
- update = PageUpdate(
- target_path=vault_root / "entities" / "ruben.md",
- operation="create",
- new_body=_entity_body("ruben", "Test latency fact."),
- reason="latency test",
- )
-
- async def _slow_propose(*_args, **_kwargs):
- # Pretend the curator-LLM takes 300 ms. This must NOT show up
- # in the bridge handler latency budget.
- await asyncio.sleep(0.3)
- return [update]
-
- with patch.object(
- s["curator"]._llm, "propose_updates", side_effect=_slow_propose,
- ):
- t0 = time.monotonic_ns()
- await s["bus"].publish(TranscriptFinal(
- transcript=Transcript(
- text="Mein Lieblings-Test ist dieser hier mit ausreichend Zeichen.", # i18n-allow
- language="de",
- confidence=0.95,
- ),
- timestamp_ns=int(time.time_ns()),
- ))
- await s["bus"].publish(ResponseGenerated(
- text="Klingt spannend, erzaehl mehr.", language="de",
- ))
- elapsed_ms = (time.monotonic_ns() - t0) / 1_000_000
-
- assert elapsed_ms < 50, (
- f"voice-bridge bus handlers blocked for {elapsed_ms:.1f}ms "
- f"(budget 50ms) -- this is the contract for the voice path"
- )
-
- # And to prove the ingest still runs eventually:
- for _ in range(20):
- if (vault_root / "entities" / "ruben.md").exists():
- break
- await asyncio.sleep(0.05)
- assert (vault_root / "entities" / "ruben.md").exists(), (
- "the slow ingest must still complete in the background"
- )
-
-
-# ===========================================================================
-# Case 7 -- Curator failure path
-# ===========================================================================
-
-
-async def test_curator_failure_does_not_break_voice_path(stack) -> None:
- """A raising curator-LLM must NOT propagate to the voice handlers."""
- s = stack
- vault_root = s["vault_root"]
-
- with patch.object(
- s["curator"]._llm, "propose_updates",
- side_effect=RuntimeError("synthetic curator failure"),
- ):
- # The voice turn must complete without raising.
- await _drive_voice_turn(
- s["bus"],
- user_text="Mein Lieblingsfilm ist Inception und das ist ein langer Satz.", # i18n-allow
- brain_text="Klingt cool, mag ich auch.",
- )
-
- # No page landed (the failure was real)...
- assert list((vault_root / "entities").glob("*.md")) == []
- # ...but the bridge handlers returned cleanly. We prove that by
- # firing another turn and asserting the bridge still works.
- rescue_update = PageUpdate(
- target_path=vault_root / "entities" / "ruben.md",
- operation="create",
- new_body=_entity_body("ruben", "Recovery turn after curator crash."),
- reason="recovery",
- )
- with patch.object(
- s["curator"]._llm, "propose_updates", return_value=[rescue_update],
- ):
- await _drive_voice_turn(
- s["bus"],
- user_text="Test ob das System nach dem Crash noch funktioniert.", # i18n-allow
- brain_text="Klar, alles laeuft.", # i18n-allow
- )
- assert (vault_root / "entities" / "ruben.md").is_file()
-
-
-# ===========================================================================
-# Case 8 -- Rollup failure path
+# Case 2 -- A failing rollup brain is contained
# ===========================================================================
@pytest.mark.asyncio
-async def test_rollup_failure_does_not_break_voice_path(stack) -> None:
- """A raising rollup brain must NOT prevent the voice bridge from working."""
+async def test_rollup_failure_reports_llm_failure_and_writes_nothing(stack) -> None:
s = stack
vault_root = s["vault_root"]
base = s["clock_holder"][0]
- # Swap the rollup's brain for one that always raises.
s["rollup"]._brain = None # noqa: SLF001 -- force re-instantiate
s["rollup"]._registry = _SpyRegistry( # noqa: SLF001
_FakeStreamBrain(raise_exc=RuntimeError("rollup brain down")),
)
-
- # Seed two episodes so the rollup tries to run.
s["rollup"]._session_start_ns = base - 60 * NS_PER_MIN # noqa: SLF001
for i in range(2):
await _seed_episode(
@@ -615,135 +262,37 @@ async def test_rollup_failure_does_not_break_voice_path(stack) -> None:
started_at_ns=base - (30 - i * 10) * NS_PER_MIN,
summary=f"episode {i}",
)
- # Trigger the rollup. Expect status=llm_failure, no session md.
+
result = await s["rollup"].flush_session()
assert result.status == "llm_failure"
assert list((vault_root / "sessions").glob("*.md")) == []
- # Voice path still works:
- fact_update = PageUpdate(
- target_path=vault_root / "entities" / "ruben.md",
- operation="create",
- new_body=_entity_body("ruben", "Voice path survives rollup crash."),
- reason="resilience proof",
- )
- with patch.object(
- s["curator"]._llm, "propose_updates", return_value=[fact_update],
- ):
- await _drive_voice_turn(
- s["bus"],
- user_text="Test ob die Voice-Pipeline trotz Rollup-Crash noch laeuft.", # i18n-allow
- brain_text="Klar, antworte ich.",
- )
- assert (vault_root / "entities" / "ruben.md").is_file()
-
# ===========================================================================
-# Case 9 -- Race: voice turn while rollup is running
+# Case 3 -- The retired rollup can never bill a key in subscription mode
# ===========================================================================
@pytest.mark.asyncio
-async def test_voice_turn_during_rollup_both_finish(stack) -> None:
- """Driving a voice turn concurrently with a rollup must let both finish."""
+async def test_rollup_skips_a_keyed_provider_in_subscription_mode(
+ stack, background_billing, # noqa: ANN001 - fixture from conftest
+) -> None:
s = stack
- vault_root = s["vault_root"]
base = s["clock_holder"][0]
+ background_billing.remember_subscription("claude-cli")
+ background_billing.sign_out("claude-cli")
- # Seed rollup episodes.
+ s["rollup"]._brain = None # noqa: SLF001 -- force re-instantiate
s["rollup"]._session_start_ns = base - 60 * NS_PER_MIN # noqa: SLF001
for i in range(2):
await _seed_episode(
s["recall"],
started_at_ns=base - (30 - i * 10) * NS_PER_MIN,
- summary=f"episode {i} about rebuild work",
- )
-
- voice_update = PageUpdate(
- target_path=vault_root / "entities" / "ruben.md",
- operation="create",
- new_body=_entity_body("ruben", "Concurrent voice fact during rollup."),
- reason="race test",
- )
-
- with patch.object(
- s["curator"]._llm, "propose_updates", return_value=[voice_update],
- ):
- # Run both at the same time. Each AtomicWriter call is async-locked
- # internally so they serialise -- the assertion is that BOTH
- # complete cleanly without raising.
- rollup_task = asyncio.create_task(s["rollup"].flush_session())
- voice_task = asyncio.create_task(_drive_voice_turn(
- s["bus"],
- user_text="Ein Fakt mitten im Rollup, gleichzeitig ausgeloest.",
- brain_text="Verstanden, bemerkt.",
- ))
- rollup_result, _ = await asyncio.gather(rollup_task, voice_task)
-
- assert rollup_result.status == "ok", (
- f"rollup must finish cleanly under concurrent voice load, "
- f"got status={rollup_result.status}"
- )
- # Both pages on disk:
- assert (vault_root / "entities" / "ruben.md").is_file(), (
- "voice fact must land even when a rollup is running"
- )
- assert list((vault_root / "sessions").glob("*.md")), (
- "rollup must produce its session page despite concurrent voice ingest"
- )
-
-
-# ===========================================================================
-# Case 10 -- Recovery: fresh triggers see persisted state on restart
-# ===========================================================================
-
-
-async def test_fresh_triggers_recover_existing_vault_state(stack) -> None:
- """After tearing down + reconstructing the triggers, the vault state
- persists -- the injector finds pages a previous run wrote."""
- s = stack
- vault_root = s["vault_root"]
-
- # 1) First "run" writes a page through the bridge.
- update = PageUpdate(
- target_path=vault_root / "entities" / "ruben.md",
- operation="create",
- new_body=_entity_body(
- "ruben",
- "Ruben built the three-trigger regression suite. Coffee with milk.",
- facts=["Lieblingsgetraenk: Cafe Latte"],
- ),
- reason="pre-restart fact",
- )
- with patch.object(s["curator"]._llm, "propose_updates", return_value=[update]):
- await _drive_voice_turn(
- s["bus"],
- user_text="Mein Lieblingsgetraenk ist Cafe Latte mit Hafermilch.", # i18n-allow
- brain_text="Schoen zu wissen.",
+ summary=f"episode {i}",
)
- assert (vault_root / "entities" / "ruben.md").is_file()
-
- # 2) "Restart": stop the bridge / rollup, build fresh equivalents
- # against the SAME tmp vault.
- s["bridge"].stop()
- await s["rollup"].stop()
-
- fresh_conn = sqlite3.connect(":memory:", check_same_thread=False)
- rebuild_index(vault_root, fresh_conn) # the boot's wiki_boot_index step
- fresh_search = VaultSearch(vault_root, conn=fresh_conn)
- fresh_injector = WikiContextInjector(
- search=fresh_search, max_chars=1500,
- latency_budget_ms=500, min_keyword_length=4,
- )
- # 3) Fresh injector must surface the pre-restart fact -- that is the
- # operational contract of "restart-safe memory".
- augmented = await fresh_injector.maybe_inject(
- user_text="Was war nochmal mein Lieblingsgetraenk?",
- system_prompt="You are Personal Jarvis.",
- )
- assert "Wiki context" in augmented, "fresh injector must see persisted pages"
- assert "Cafe Latte" in augmented or "Latte" in augmented, (
- "the pre-restart fact must round-trip through disk"
- )
+ result = await s["rollup"].flush_session()
+ assert result.status == "llm_failure"
+ assert s["registry"].instantiate_calls == [], "no keyed provider may be built"
+ assert s["fake_rollup_brain"].call_count == 0
+ assert background_billing.calls_today == 0
diff --git a/tests/integration/memory/wiki/test_realtime_to_vault_e2e.py b/tests/integration/memory/wiki/test_realtime_to_vault_e2e.py
index 6bf5373e56..f59e3a2864 100644
--- a/tests/integration/memory/wiki/test_realtime_to_vault_e2e.py
+++ b/tests/integration/memory/wiki/test_realtime_to_vault_e2e.py
@@ -1,4 +1,8 @@
-"""Realtime transcript review reaches real Markdown pages without manual flush."""
+"""Explicitly saved realtime turns reach real Markdown pages without a manual flush.
+
+Since 2026-09-30 only turns the brain acknowledged saving ("Noted.") are
+reviewed; there is no automatic per-turn review and no end-of-call sweep.
+"""
from __future__ import annotations
import asyncio
@@ -38,12 +42,10 @@ from jarvis.memory.wiki.voice_bridge import VoiceFactBridge
class _ReviewBrain:
"""Script both review stages while keeping the production pipeline real.
- Responses are routed by REQUEST KIND, not by call order: per-turn
- extraction is deferred to the session-end boundary (AP-9, 2026-07-21),
- where the completeness sweep runs concurrently with the judge rounds
- that freshly journaled candidates trigger — a strict call-order script
- would race those two. Sweeps re-read already-reviewed turns and answer
- with an empty candidate array.
+ Responses are routed by REQUEST KIND, not by call order: a turn's
+ extraction and the judge round its candidates trigger run as
+ background tasks, and the write-time alias lookups interleave with
+ them, so a strict call-order script would race.
"""
name = "review-brain"
@@ -74,8 +76,6 @@ class _ReviewBrain:
if "You generate SEARCH ALIASES" in text:
self.alias_requests.append(request)
payload = "[]"
- elif "completeness sweep" in text:
- payload = "[]"
elif "Evidence user turn [" in text:
self.judge_requests.append(request)
payload = self._judgements.pop(0)
@@ -143,7 +143,7 @@ def _turn(
turn_id: str,
provider: str,
text: str,
- assistant_text: str = "Thanks for telling me.",
+ assistant_text: str = "Noted, thanks for telling me.",
session_id: str = "realtime-session",
) -> VoiceTurnCompleted:
return VoiceTurnCompleted(
@@ -208,7 +208,6 @@ async def test_consecutive_realtime_reviews_write_to_selected_vault(
# 2026-07-28 cost audit).
wiki_scheduler=SchedulerConfig(consolidate_after_candidates=1),
)
- assert config.memory.wiki.voice_bridge.rate_limit_seconds == 0
assert config.wiki_scheduler.consolidate_after_candidates == 1
facts = [
@@ -365,18 +364,11 @@ async def test_consecutive_realtime_reviews_write_to_selected_vault(
consolidate_after=config.wiki_scheduler.consolidate_after_candidates,
)
bus = EventBus()
- bridge = VoiceFactBridge(
- bus=bus,
- curator=curator,
- config=config.memory.wiki.voice_bridge,
- extractor=extractor,
- )
+ bridge = VoiceFactBridge(bus=bus, extractor=extractor)
bridge.start()
async def _speak_and_hang_up(turn: VoiceTurnCompleted) -> None:
- """One short call per fact: extraction is deferred to session end
- (AP-9, 2026-07-21), so the turn only reaches the extractor once its
- session closes."""
+ """One short call per fact; hanging up runs nothing extra."""
await bus.publish(turn)
await bus.publish(
VoiceSessionEnded(
@@ -426,17 +418,17 @@ async def test_consecutive_realtime_reviews_write_to_selected_vault(
session_id="call-4",
)
)
- await _wait_for_idle(brain, journal, calls=15)
+ await _wait_for_idle(brain, journal, calls=11)
await _speak_and_hang_up(
_turn(
turn_id="assistant-guess-turn",
provider="openai-realtime",
text="What do you think I own?",
- assistant_text="Perhaps you own a demo glider.",
+ assistant_text="Perhaps you own a demo glider. Noted.",
session_id="call-5",
)
)
- await _wait_for_idle(brain, journal, calls=18)
+ await _wait_for_idle(brain, journal, calls=13)
finally:
bridge.stop()
journal.close()
@@ -468,8 +460,8 @@ async def test_consecutive_realtime_reviews_write_to_selected_vault(
assert "Evidence user turn [assistant-guess-turn]" in final_judge_prompt
assert "What do you think I own?" in final_judge_prompt
assert "Perhaps you own a demo glider." not in final_judge_prompt
- # 5 deferred turn extractions + 5 judge rounds + 5 session sweeps,
- # plus one separate alias lookup for each page that was written.
+ # 5 turn extractions + 5 judge rounds, no session sweeps, plus one
+ # separate alias lookup for each page that was written.
assert len(brain.alias_requests) == 3
- assert brain.calls == 15 + len(brain.alias_requests)
+ assert brain.calls == 10 + len(brain.alias_requests)
assert journal.backlog_count() == 0
diff --git a/tests/integration/memory/wiki/test_two_stage_e2e.py b/tests/integration/memory/wiki/test_two_stage_e2e.py
index 8183287c5b..00a8cabaf3 100644
--- a/tests/integration/memory/wiki/test_two_stage_e2e.py
+++ b/tests/integration/memory/wiki/test_two_stage_e2e.py
@@ -227,7 +227,7 @@ async def stack(tmp_path: Path):
)
bus = EventBus()
- bridge = VoiceFactBridge(bus=bus, curator=curator, config=None, extractor=extractor)
+ bridge = VoiceFactBridge(bus=bus, extractor=extractor)
bridge.start()
# D4 skeleton, as bootstrap would do it — then age again so the first
diff --git a/tests/unit/memory/wiki/test_conversation_observer.py b/tests/unit/memory/wiki/test_conversation_observer.py
index d5009a394c..10c5e2d76c 100644
--- a/tests/unit/memory/wiki/test_conversation_observer.py
+++ b/tests/unit/memory/wiki/test_conversation_observer.py
@@ -1,9 +1,8 @@
-"""Conversation observer (Wave-2 B3): voice + chat turns feed the journal.
+"""Conversation observer: explicitly saved voice + chat turns feed the journal.
-Pins four contracts:
+Pins five contracts:
-1. A completed voice turn flows extractor -> journal; the legacy direct
- ``curator.ingest`` path is NOT called when an extractor is attached.
+1. A voice turn the brain acknowledged ("Noted.") flows extractor -> journal.
2. A chat turn (``MessageSent(role="user")`` + ``ResponseGenerated``)
feeds the same journal.
3. The same turn text delivered via BOTH event paths is journaled once
@@ -11,9 +10,8 @@ Pins four contracts:
server's MessageSent mirror).
4. AP-9: the bus handlers return immediately; extraction happens in a
fire-and-forget background task, never awaited on the voice path.
-
-Plus: without an extractor the bridge falls back to the legacy direct
-``curator.ingest`` path unchanged.
+5. A turn the brain did NOT acknowledge is never reviewed: the automatic
+ per-turn review was removed on 2026-09-30.
"""
from __future__ import annotations
@@ -96,21 +94,6 @@ class FakeRegistry:
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(
@@ -128,10 +111,9 @@ def _stack(tmp_path: Path, *, brain_sleep_s: float = 0.0):
extractor = ConversationFactExtractor(
config=_config(), journal=journal, registry=FakeRegistry(brain),
)
- curator = FakeCurator()
- bridge = VoiceFactBridge(bus=bus, curator=curator, config=None, extractor=extractor)
+ bridge = VoiceFactBridge(bus=bus, extractor=extractor)
bridge.start()
- return bus, journal, curator, bridge, brain
+ return bus, journal, None, bridge, brain
async def _drain(
@@ -149,7 +131,7 @@ async def _drain(
@pytest.mark.asyncio
async def test_voice_turn_feeds_journal_not_direct_ingest(tmp_path: Path) -> None:
- bus, journal, curator, bridge, _brain = _stack(tmp_path)
+ bus, journal, _unused, bridge, _brain = _stack(tmp_path)
try:
await bus.publish(TranscriptFinal(
transcript=Transcript(text=FACT_SENTENCE, language="en", confidence=0.95),
@@ -162,12 +144,11 @@ async def test_voice_turn_feeds_journal_not_direct_ingest(tmp_path: Path) -> Non
rows = journal.pending()
assert rows and rows[0].fact == "Lena moved to Hamburg."
assert rows[0].source_label.startswith("voice-fact:")
- assert curator.ingested == [], "extractor mode must not call curator.ingest directly"
@pytest.mark.asyncio
async def test_chat_turn_feeds_same_journal(tmp_path: Path) -> None:
- bus, journal, curator, bridge, _brain = _stack(tmp_path)
+ bus, journal, _unused, bridge, _brain = _stack(tmp_path)
try:
await bus.publish(MessageSent(thread_id="t1", role="user", text=FACT_SENTENCE))
await bus.publish(ResponseGenerated(text="Noted.", language="en"))
@@ -178,7 +159,6 @@ async def test_chat_turn_feeds_same_journal(tmp_path: Path) -> None:
rows = journal.pending()
assert rows and rows[0].fact == "Lena moved to Hamburg."
assert rows[0].source_label.startswith("chat-fact:")
- assert curator.ingested == []
@pytest.mark.asyncio
@@ -245,21 +225,19 @@ async def test_ap9_handlers_return_before_extraction_completes(tmp_path: Path) -
@pytest.mark.asyncio
-async def test_without_extractor_legacy_direct_ingest_still_fires(tmp_path: Path) -> None:
- bus = EventBus()
- curator = FakeCurator()
- bridge = VoiceFactBridge(bus=bus, curator=curator, config=None, extractor=None)
- bridge.start()
+async def test_unacknowledged_turns_are_never_reviewed(tmp_path: Path) -> None:
+ """No automatic per-turn review: without an acknowledgement nothing bills."""
+ bus, journal, _unused, bridge, brain = _stack(tmp_path)
try:
await bus.publish(TranscriptFinal(
transcript=Transcript(text=FACT_SENTENCE, language="en", confidence=0.95),
))
- await bus.publish(ResponseGenerated(text="Noted.", language="en"))
- for _ in range(100): # up to ~2 s
- if curator.ingested:
- break
- await asyncio.sleep(0.02)
+ await bus.publish(ResponseGenerated(text="Hamburg is lovely.", language="en"))
+ await bus.publish(MessageSent(thread_id="t1", role="user", text=FACT_SENTENCE * 2))
+ await bus.publish(ResponseGenerated(text="Tell me more!", language="en"))
+ await asyncio.sleep(0.3)
finally:
bridge.stop()
- assert curator.ingested, "fallback path must keep the legacy direct ingest alive"
+ assert brain.call_count == 0
+ assert journal.backlog_count() == 0
diff --git a/tests/unit/memory/wiki/test_d2_no_session_page_feed.py b/tests/unit/memory/wiki/test_d2_no_session_page_feed.py
index 5689264fa0..18d6136a6e 100644
--- a/tests/unit/memory/wiki/test_d2_no_session_page_feed.py
+++ b/tests/unit/memory/wiki/test_d2_no_session_page_feed.py
@@ -6,16 +6,15 @@ Two invariants:
that would previously have triggered a session-page write produces NO
page on disk and reports ``disabled_wiki_write`` — while the awareness
episodes themselves are untouched (read, not deleted).
-2. The conversation path (``VoiceFactBridge`` -> curator) still reaches the
- curator, so retiring the session feed does not silence the wiki.
+2. Re-enabling the flag restores the page write.
+
+Explicit conversation saves are pinned in ``test_conversation_observer``.
"""
from __future__ import annotations
-import asyncio
import time
from collections.abc import AsyncIterator
from pathlib import Path
-from typing import Any
from unittest.mock import MagicMock
import pytest
@@ -23,14 +22,13 @@ import pytest_asyncio
from jarvis.core.bus import EventBus
from jarvis.core.config import load_config
-from jarvis.core.events import IdleEntered, ResponseGenerated, TranscriptFinal
-from jarvis.core.protocols import BrainDelta, BrainRequest, Transcript
+from jarvis.core.events import IdleEntered
+from jarvis.core.protocols import BrainDelta, BrainRequest
from jarvis.memory.recall import RecallStore
from jarvis.memory.wiki.atomic_writer import AtomicWriter
from jarvis.memory.wiki.log_writer import LogWriter
from jarvis.memory.wiki.page import MarkdownPageRepository
from jarvis.memory.wiki.session_rollup import SessionRollupWorker
-from jarvis.memory.wiki.voice_bridge import VoiceFactBridge
NS_PER_MIN = 60 * 1_000_000_000
@@ -153,35 +151,3 @@ async def test_reenabling_flag_restores_the_page_write(worker_stack):
assert result.status == "ok"
assert brain.call_count == 1
assert list((vault_root / "sessions").glob("*.md"))
-
-
-async def test_voice_bridge_conversation_path_still_reaches_curator(tmp_path: Path):
- """Retiring the session feed must NOT silence the conversation -> curator path."""
- bus = EventBus()
- ingested: list[str] = []
-
- class _FakeCurator:
- async def ingest(self, source_content: str, source_label: str) -> Any:
- ingested.append(source_content)
- # Minimal WriteResult-shaped object the bridge tolerates.
- return MagicMock(applied=[], skipped_due_to_recent_edit=[], failed_validation=[])
-
- bridge = VoiceFactBridge(bus=bus, curator=_FakeCurator(), config=None)
- bridge.start()
- try:
- user_text = "Remember that my dentist appointment is on Friday at 3pm in Munich."
- await bus.publish(TranscriptFinal(
- transcript=Transcript(text=user_text, language="en", confidence=0.95),
- ))
- await bus.publish(ResponseGenerated(text="Noted.", language="en"))
- # The bridge fires fire-and-forget tasks; let them run.
- for _ in range(20):
- await asyncio.sleep(0.02)
- if ingested:
- break
- finally:
- bridge.stop()
-
- assert ingested, "VoiceFactBridge must still forward conversation turns to the curator"
- assert any("dentist" in text for text in ingested)
diff --git a/tests/unit/memory/wiki/test_voice_bridge_detach.py b/tests/unit/memory/wiki/test_voice_bridge_detach.py
index a1ace75b5d..a30d389d4a 100644
--- a/tests/unit/memory/wiki/test_voice_bridge_detach.py
+++ b/tests/unit/memory/wiki/test_voice_bridge_detach.py
@@ -15,7 +15,6 @@ from __future__ import annotations
import asyncio
from jarvis.core.bus import EventBus
-from jarvis.core.config import VoiceBridgeConfig
from jarvis.core.events import (
MessageSent,
ResponseGenerated,
@@ -35,9 +34,8 @@ SUBSCRIBED_EVENTS = (
def _bridge(bus: EventBus) -> VoiceFactBridge:
- return VoiceFactBridge(
- bus=bus, curator=None, config=VoiceBridgeConfig(), extractor=None
- )
+ # The detach contract never reaches the extractor; a placeholder suffices.
+ return VoiceFactBridge(bus=bus, extractor=object()) # type: ignore[arg-type]
def _attached(bus: EventBus) -> int:
diff --git a/tests/unit/memory/wiki/test_voice_bridge_realtime.py b/tests/unit/memory/wiki/test_voice_bridge_realtime.py
index 0851107f5a..a2529b2e2a 100644
--- a/tests/unit/memory/wiki/test_voice_bridge_realtime.py
+++ b/tests/unit/memory/wiki/test_voice_bridge_realtime.py
@@ -1,28 +1,20 @@
-"""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.
-7. NOTHING extracts while the call is live (AP-9, 2026-07-21): per-turn
- extraction jobs are deferred and run sequentially at session end,
- before the completeness sweep — an in-call extraction is an LLM round
- (plus 429 retries and Codex CLI spawns) on the loop that paces the
- call's audio, and its journaled candidates trigger in-call
- consolidator judge rounds on top.
+"""Realtime turns reach the wiki journal only when the user asked to keep them.
+
+The realtime engine never emits ``TranscriptFinal``/``MessageSent`` — the one
+event that carries BOTH final texts of a realtime turn is
+``VoiceTurnCompleted``. These tests pin the bridge's realtime contract since
+the automatic review was removed (2026-09-30):
+
+1. A realtime turn whose reply acknowledges a save ("Noted.") is reviewed at
+ once (fire-and-forget, AP-9) and its facts are journaled.
+2. A turn without an acknowledgement is never reviewed — no per-turn review,
+ no end-of-call sweep, no held-back extraction at hangup.
+3. Pipeline-tier ``VoiceTurnCompleted`` events are ignored (they are paired
+ via TranscriptFinal/ResponseGenerated instead).
+4. The same realtime turn delivered twice is reviewed once.
+5. Earlier turns of the same call are bounded reference context.
+6. When the wiki must wait for the subscription, the explicit save is held,
+ never billed to an API key, and retried once a subscription answers.
"""
from __future__ import annotations
@@ -42,17 +34,17 @@ from jarvis.core.config import (
BrainProviderConfig,
JarvisConfig,
MemoryConfig,
- VoiceBridgeConfig,
WikiMemoryConfig,
)
from jarvis.core.events import VoiceSessionEnded, VoiceTurnCompleted
from jarvis.core.protocols import BrainDelta, BrainRequest
+from jarvis.memory.wiki.background_guard import guard
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
+SHORT_FACT = "Lena lives in Hamburg."
class FakeBrain:
@@ -90,31 +82,21 @@ class FakeBrain:
class FakeRegistry:
- def __init__(self, brain: Any) -> None:
+ """Records every provider it is asked to instantiate."""
+
+ def __init__(self, brain: Any, *, providers: set[str] | None = None) -> None:
self._brain = brain
+ self._providers = providers or {"gemini"}
+ self.instantiated: list[str] = []
def available(self) -> set[str]:
- return {"gemini"}
+ return set(self._providers)
def instantiate(self, name: str, **kwargs: Any) -> Any:
+ self.instantiated.append(name)
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(
@@ -125,22 +107,17 @@ def _config() -> JarvisConfig:
)
-def _stack(tmp_path: Path, *, bridge_config: VoiceBridgeConfig | None = None):
+def _stack(tmp_path: Path, *, providers: set[str] | None = None):
bus = EventBus()
journal = CandidateJournal(tmp_path / "jarvis.db")
brain = FakeBrain()
+ registry = FakeRegistry(brain, providers=providers)
extractor = ConversationFactExtractor(
- config=_config(), journal=journal, registry=FakeRegistry(brain),
- )
- curator = FakeCurator()
- bridge = VoiceFactBridge(
- bus=bus,
- curator=curator,
- config=bridge_config,
- extractor=extractor,
+ config=_config(), journal=journal, registry=registry,
)
+ bridge = VoiceFactBridge(bus=bus, extractor=extractor)
bridge.start()
- return bus, journal, curator, bridge, brain
+ return bus, journal, registry, bridge, brain
def _realtime_turn(
@@ -171,21 +148,11 @@ async def _drain(journal: CandidateJournal, *, timeout_s: float = 2.0) -> None:
async def _end_session(bus: EventBus, session_id: str = "rt-session") -> None:
- """Close the live call — extraction is deferred until this boundary."""
await bus.publish(
VoiceSessionEnded(session_id=session_id, hangup_reason="hotkey")
)
-def _turn_rows(journal: CandidateJournal) -> list[Any]:
- """Journal rows from per-turn extraction (the sweep rows filtered out)."""
- return [
- row
- for row in journal.pending()
- if not row.source_label.startswith("realtime-session-sweep")
- ]
-
-
async def _wait_for_calls(brain: FakeBrain, count: int, *, timeout_s: float = 2.0) -> None:
deadline = time.monotonic() + timeout_s
while brain.call_count < count and time.monotonic() < deadline: # noqa: ASYNC110
@@ -193,192 +160,99 @@ async def _wait_for_calls(brain: FakeBrain, count: int, *, timeout_s: float = 2.
@pytest.mark.asyncio
-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!"))
- # AP-9: while the call is live, NO extraction round may run — the
- # job is deferred, not fired.
- await asyncio.sleep(0.2)
- assert brain.call_count == 0
- assert journal.backlog_count() == 0
- await _end_session(bus)
- 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)
+async def test_acknowledged_realtime_turn_is_reviewed_during_the_call(tmp_path: Path) -> None:
+ bus, journal, _registry, bridge, brain = _stack(tmp_path)
try:
await bus.publish(_realtime_turn(SHORT_FACT, "Noted."))
- await _end_session(bus)
await _drain(journal)
finally:
bridge.stop()
rows = journal.pending()
- assert rows, "acked realtime turn must be journaled"
+ assert rows and rows[0].fact == "Lena moved to Hamburg."
assert rows[0].source_label.startswith("realtime-fact:")
+ assert brain.call_count == 1
@pytest.mark.asyncio
-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)
+async def test_unacknowledged_realtime_turns_are_never_reviewed(tmp_path: Path) -> None:
+ """No per-turn review, no end-of-call sweep, nothing held until hangup."""
+ bus, journal, registry, bridge, brain = _stack(tmp_path)
try:
- await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted.", tier="flash"))
+ await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay, will do!"))
+ await bus.publish(_realtime_turn("I own a yacht.", "", turn_id="rt-turn-2"))
+ await _end_session(bus)
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 (recorded
- # at defer time, before any extraction ran).
- await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted."))
- await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted."))
- await _end_session(bus)
- await _wait_for_calls(brain, 2) # one turn extraction + the sweep
- await asyncio.sleep(0.1)
- finally:
- bridge.stop()
-
- assert len(_turn_rows(journal)) == 1, (
- "duplicate realtime turn must be deduped by hash"
- )
- assert brain.call_count == 2
-
-
-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 registry.instantiated == []
assert journal.backlog_count() == 0
- assert brain.call_count == 0
+ assert journal.capture_summary()["sessions_swept"] == 0
@pytest.mark.asyncio
-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)
+async def test_session_end_runs_nothing_after_an_acknowledged_turn(tmp_path: Path) -> None:
+ bus, journal, _registry, bridge, brain = _stack(tmp_path)
try:
- await bus.publish(_realtime_turn(FACT_SENTENCE, ""))
+ await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted.", turn_id="turn-a"))
+ await _wait_for_calls(brain, 1)
await _end_session(bus)
- 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:
- """Operators can opt into rate limiting when call cost matters more."""
- bus, journal, _curator, bridge, brain = _stack(
- tmp_path,
- bridge_config=VoiceBridgeConfig(rate_limit_seconds=60),
- )
- try:
- await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay!"))
- await bus.publish(
- _realtime_turn(
- "My favourite restaurant is the little place at the harbour.",
- "Sounds lovely!",
- turn_id="rt-turn-2",
- )
- )
await _end_session(bus)
- await _wait_for_calls(brain, 2) # one turn extraction + the sweep
- await asyncio.sleep(0.1)
+ await asyncio.sleep(0.3)
finally:
bridge.stop()
- assert len(_turn_rows(journal)) == 1, (
- "second aggressive ingest within 60s must be skipped"
- )
- assert brain.call_count == 2
+ assert brain.call_count == 1, "only the acknowledged turn is reviewed"
+ assert journal.capture_summary()["sessions_swept"] == 0
@pytest.mark.asyncio
-async def test_default_reviews_consecutive_realtime_turns(tmp_path: Path) -> None:
- """The default must not silently discard a second durable fact."""
- bus, journal, _curator, bridge, brain = _stack(tmp_path)
+async def test_pipeline_tier_turn_is_ignored(tmp_path: Path) -> None:
+ """Pipeline turns are paired via TranscriptFinal — no double feed."""
+ bus, journal, _registry, bridge, brain = _stack(tmp_path)
try:
- await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay!"))
- await bus.publish(
- _realtime_turn(
- "My favourite restaurant is the little place at the harbour.",
- "Sounds lovely!",
- turn_id="rt-turn-2",
- )
- )
- await _end_session(bus)
- await _wait_for_calls(brain, 3) # two turn extractions + the sweep
- await asyncio.sleep(0.1)
+ await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted.", tier="flash"))
+ await asyncio.sleep(0.3)
finally:
bridge.stop()
- assert len(_turn_rows(journal)) == 2
- assert brain.call_count == 3
+ assert journal.backlog_count() == 0
+ assert brain.call_count == 0
@pytest.mark.asyncio
-async def test_short_yacht_ownership_reaches_extractor_without_ack(tmp_path: Path) -> None:
- bus, journal, _curator, bridge, brain = _stack(tmp_path)
+async def test_same_realtime_turn_delivered_twice_is_reviewed_once(tmp_path: Path) -> None:
+ bus, journal, _registry, bridge, brain = _stack(tmp_path)
try:
- await bus.publish(_realtime_turn("I own a yacht.", "That sounds exciting."))
- await _end_session(bus)
- await _wait_for_calls(brain, 2) # one turn extraction + the sweep
- await asyncio.sleep(0.1)
+ await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted."))
+ await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted."))
+ await _wait_for_calls(brain, 1)
+ await asyncio.sleep(0.2)
finally:
bridge.stop()
- assert brain.call_count == 2
- assert len(_turn_rows(journal)) == 1
+ assert journal.backlog_count() == 1
+ assert brain.call_count == 1
@pytest.mark.asyncio
-async def test_same_text_in_different_turns_is_reviewed_twice(tmp_path: Path) -> None:
- bus, journal, _curator, bridge, brain = _stack(tmp_path)
+async def test_empty_user_text_is_ignored(tmp_path: Path) -> None:
+ bus, journal, _registry, bridge, brain = _stack(tmp_path)
try:
- await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay.", turn_id="turn-a"))
- await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay.", turn_id="turn-b"))
- await _end_session(bus)
- await _wait_for_calls(brain, 3) # two turn extractions + the sweep
- await asyncio.sleep(0.1)
+ await bus.publish(_realtime_turn("", "Noted."))
+ await asyncio.sleep(0.2)
finally:
bridge.stop()
- assert brain.call_count == 3
- assert len(_turn_rows(journal)) == 2
+ assert journal.backlog_count() == 0
+ assert brain.call_count == 0
@pytest.mark.asyncio
-async def test_second_turn_receives_bounded_same_session_context(tmp_path: Path) -> None:
- bus, _journal, _curator, bridge, brain = _stack(tmp_path)
+async def test_acknowledged_turn_receives_bounded_same_session_context(tmp_path: Path) -> None:
+ bus, _journal, _registry, bridge, brain = _stack(tmp_path)
try:
await bus.publish(
_realtime_turn(
@@ -389,17 +263,17 @@ async def test_second_turn_receives_bounded_same_session_context(tmp_path: Path)
)
await bus.publish(
_realtime_turn(
- "It is currently moored in Kiel.",
- "Understood.",
+ "It is currently moored in Kiel, please remember that.",
+ "Noted.",
turn_id="turn-b",
)
)
- await _end_session(bus)
- await _wait_for_calls(brain, 2)
+ await _wait_for_calls(brain, 1)
finally:
bridge.stop()
- prompt = brain.received_requests[1].messages[0].content
+ assert brain.call_count == 1
+ prompt = brain.received_requests[0].messages[0].content
assert "USER TURN [turn-a]" in prompt
assert "I own a yacht called Aurora." in prompt
assert "FOCUS USER TURN [turn-b]" in prompt
@@ -407,52 +281,35 @@ async def test_second_turn_receives_bounded_same_session_context(tmp_path: Path)
@pytest.mark.asyncio
-async def test_session_end_runs_one_full_realtime_sweep(tmp_path: Path) -> None:
- bus, journal, _curator, bridge, brain = _stack(tmp_path)
+async def test_subscription_wait_holds_the_save_and_never_bills_a_key(
+ tmp_path: Path, background_billing, # noqa: ANN001 - fixture from conftest
+) -> None:
+ """Subscription mode, subscription signed out: wait, never the key."""
+ background_billing.remember_subscription("claude-cli")
+ background_billing.sign_out("claude-cli")
+ bus, journal, registry, bridge, brain = _stack(
+ tmp_path, providers={"gemini", "openrouter", "claude-cli"}
+ )
try:
- await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay.", turn_id="turn-a"))
- await bus.publish(
- VoiceSessionEnded(session_id="rt-session", hangup_reason="hotkey")
- )
- await _wait_for_calls(brain, 2)
+ await bus.publish(_realtime_turn(SHORT_FACT, "Noted."))
deadline = time.monotonic() + 2.0
- while ( # noqa: ASYNC110 - polls a persisted counter with a hard deadline
- journal.capture_summary()["sessions_swept"] < 1
- and time.monotonic() < deadline
- ):
+ while bridge.waiting_count == 0 and time.monotonic() < deadline: # noqa: ASYNC110
await asyncio.sleep(0.02)
- finally:
- bridge.stop()
-
- assert brain.call_count == 2
- assert journal.capture_summary()["sessions_swept"] == 1
+ assert bridge.waiting_count == 1
+ assert registry.instantiated == [], "no keyed provider may be touched"
+ assert brain.call_count == 0
+ # A retry while the subscription is still out keeps waiting.
+ assert await bridge.retry_waiting() == 0
+ assert bridge.waiting_count == 1
-async def test_duplicate_session_end_sweeps_only_once(tmp_path: Path) -> None:
- """On desktop BOTH the realtime session and the speech pipeline publish
- VoiceSessionEnded with the same session_id. The first event pops the
- per-session turn buffer, so the duplicate must be a natural no-op."""
- bus, journal, _curator, bridge, brain = _stack(tmp_path)
- try:
- await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay.", turn_id="turn-a"))
- await bus.publish(
- VoiceSessionEnded(session_id="rt-session", hangup_reason="hotkey")
- )
- await bus.publish(
- VoiceSessionEnded(session_id="rt-session", hangup_reason="client_stop")
- )
- await _wait_for_calls(brain, 2)
- deadline = time.monotonic() + 2.0
- while ( # noqa: ASYNC110 - polls a persisted counter with a hard deadline
- journal.capture_summary()["sessions_swept"] < 1
- and time.monotonic() < deadline
- ):
- await asyncio.sleep(0.02)
- # Give a hypothetical second sweep a moment to (wrongly) start.
- await asyncio.sleep(0.1)
+ # The subscription answers again and the backoff window has passed.
+ background_billing.sign_in("claude-cli")
+ guard.note_progress()
+ assert await bridge.retry_waiting() == 1
+ assert bridge.waiting_count == 0
finally:
bridge.stop()
- assert brain.call_count == 2 # one turn extraction + ONE sweep
- assert journal.capture_summary()["sessions_swept"] == 1
+ assert registry.instantiated == ["claude-cli"]
+ assert journal.backlog_count() == 1
diff --git a/tests/unit/ui/test_wiki_auto_backfill_loop.py b/tests/unit/ui/test_wiki_auto_backfill_loop.py
deleted file mode 100644
index d03ed4fc5c..0000000000
--- a/tests/unit/ui/test_wiki_auto_backfill_loop.py
+++ /dev/null
@@ -1,110 +0,0 @@
-"""The periodic realtime wiki backfill loop (server background task).
-
-Live 2026-07-18: realtime turns whose provider delivered no input transcript
-were silently lost to live capture, and the manual ``POST /api/wiki/backfill``
-was the only recovery. The server now runs the evidence-safe backfill as a
-bounded periodic background task. These tests bind the loop method to a
-minimal fake server so no real WebServer (sockets, config, voice) is built.
-"""
-from __future__ import annotations
-
-import asyncio
-from types import SimpleNamespace
-from typing import Any
-
-import pytest
-
-from jarvis.memory.wiki.backfill import BackfillResult
-
-
-def _fake_server(store: Any) -> SimpleNamespace:
- return SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(session_store=store)))
-
-
-def _result(**overrides: Any) -> BackfillResult:
- defaults: dict[str, Any] = {
- "dry_run": False,
- "days": 2,
- "sessions_scanned": 1,
- "sessions_eligible": 1,
- "sessions_already_reviewed": 0,
- "sessions_in_progress": 0,
- "sessions_reviewed": 1,
- "sessions_failed": 0,
- "turns_considered": 3,
- "candidates_journaled": 2,
- }
- defaults.update(overrides)
- return BackfillResult(**defaults)
-
-
-async def _run_until(task: asyncio.Task, condition, *, timeout_s: float = 2.0) -> None:
- deadline = asyncio.get_event_loop().time() + timeout_s
- while not condition() and asyncio.get_event_loop().time() < deadline: # noqa: ASYNC110
- await asyncio.sleep(0.01)
- task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task
-
-
-async def test_loop_runs_bounded_live_backfill(monkeypatch: pytest.MonkeyPatch) -> None:
- from jarvis.memory.wiki import backfill as backfill_module
- from jarvis.memory.wiki import integration as integration_module
- from jarvis.ui.web.server import WebServer
-
- extractor = object()
- runtime = SimpleNamespace(extractor=extractor, scheduler=object())
- monkeypatch.setattr(
- integration_module, "get_running_capture_runtime", lambda: runtime
- )
- calls: list[dict[str, Any]] = []
-
- async def _fake_backfill(**kwargs: Any) -> BackfillResult:
- calls.append(kwargs)
- return _result()
-
- monkeypatch.setattr(backfill_module, "backfill_realtime_sessions", _fake_backfill)
-
- store = object()
- loop = WebServer._wiki_auto_backfill_loop.__get__(_fake_server(store))
- task = asyncio.get_event_loop().create_task(
- loop(initial_delay_s=0.0, interval_s=3600.0)
- )
- await _run_until(task, lambda: len(calls) >= 1)
-
- assert len(calls) == 1 # one pass, then the long interval sleep
- call = calls[0]
- assert call["store"] is store
- assert call["extractor"] is extractor
- assert call["dry_run"] is False # a safety net that actually writes
- assert call["days"] == 2 and call["max_sessions"] == 20 # bounded pass
-
-
-async def test_loop_skips_pass_when_runtime_not_ready(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jarvis.memory.wiki import backfill as backfill_module
- from jarvis.memory.wiki import integration as integration_module
- from jarvis.ui.web.server import WebServer
-
- probes: list[bool] = []
-
- def _no_runtime() -> None:
- probes.append(True)
- return None
-
- monkeypatch.setattr(integration_module, "get_running_capture_runtime", _no_runtime)
-
- async def _must_not_run(**_kwargs: Any) -> BackfillResult:
- raise AssertionError("backfill must not run without a capture runtime")
-
- monkeypatch.setattr(backfill_module, "backfill_realtime_sessions", _must_not_run)
-
- loop = WebServer._wiki_auto_backfill_loop.__get__(_fake_server(object()))
- task = asyncio.get_event_loop().create_task(
- loop(initial_delay_s=0.0, interval_s=3600.0)
- )
- await _run_until(task, lambda: len(probes) >= 1)
- assert probes # the pass ran, probed the runtime, and skipped gracefully