Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix: restore wiki, realtime, and worker tool execution
Ruben Lütke0f8cdda63ebe
diff --git a/docs/adr/0011-router-pure-dispatcher.md b/docs/adr/0011-router-pure-dispatcher.mdindex b4ac32d53e..b9a29c865a 100644--- a/docs/adr/0011-router-pure-dispatcher.md+++ b/docs/adr/0011-router-pure-dispatcher.md@@ -4,14 +4,14 @@ slug: adr-0011-router-pure-dispatcherdiataxis: adrstatus: activeowner: sam-last_reviewed: 2026-04-29+last_reviewed: 2026-07-12phase: 5audience: developer---# ADR-0011 — Main Jarvis is a Pure Dispatcher with EXACTLY four tools-**Status:** Accepted (2026-04-25)+**Status:** Amended 2026-07-12**Phase:** Persona refactor §3 — routing fix## Context@@ -819,3 +819,41 @@ ASGI execution, and echo-verify readback are unchanged. Guards:`test_factory_wires_registry_command_tools_into_router_set`,`tests/unit/plugins/tool/test_app_command.py` (loader expansion + flatschemas + the provider-test regression).++## Amendment 2026-07-12 - retire `multi-spawn` from the router++### Context++The live harness inventory no longer contains the historical OpenClaw/Codex+vehicles advertised by `multi-spawn`. The tool therefore competed with the+working `spawn-worker` mission path while offering backend names that could not+run. This is the same phantom-capability failure class that previously required+removing `dispatch-to-harness` from the LLM-visible router.++### Decision++`multi-spawn` is removed from `ROUTER_TOOLS` and from the seeded capability+registry. `spawn-worker` is the sole LLM-visible heavy-work delegation path; its+Mission Manager may still decompose a mission into parallel supervised steps.+The legacy implementation and entry point may remain for internal compatibility,+but model-facing schemas and prompts must not advertise it.++### Consequences++- Heavy work has one observable mission id and one critic/review lifecycle.+- The router can no longer select unregistered harness names through the legacy+ fan-out schema.+- Parallelism remains an internal Mission Manager decision rather than a second+ public spawn surface.++### Alternatives considered++- Re-register the historical harness names: rejected because those backends were+ removed after empirical reliability failures.+- Rewrite `multi-spawn` as an alias for `spawn-worker`: rejected because two+ model-visible tools for one operation recreate nondeterministic tool choice.++### Follow-up items++- Keep exact router-set and capability-registry negative tests.+- Keep recursive spawn tools out of every worker capability inventory.diff --git a/docs/commands-reference.md b/docs/commands-reference.mdindex 4a602440a7..37b0a73993 100644--- a/docs/commands-reference.md+++ b/docs/commands-reference.md@@ -151,6 +151,36 @@ List available speaker and microphone devices.- **Desktop UI section:** `settings`- **Voice example (EN):** "list my audio devices"+## `wiki-ingest` — Store a fact in the Wiki++Store one self-contained fact or summary through the guarded Wiki curator. The command succeeds only after a page is written.++- **Endpoint:** `POST /api/wiki/ingest`+- **Arguments:** `text` (string; required); `source` (string; optional)+- **Requires confirmation:** no+- **Desktop UI section:** `memory`+- **Voice example (EN):** "store that in my wiki"++## `session-latest-turn` — Show latest voice turn++Return the latest persisted user transcript and its complete voice turn, optionally restricted to one session.++- **Endpoint:** `GET /api/sessions/latest-turn`+- **Arguments:** `session_id` (string; optional)+- **Requires confirmation:** no+- **Desktop UI section:** `sessions`+- **Voice example (EN):** "read the latest transcript"++## `tools-list` — List effective tools++Return the effective live Brain tool surface, including native, connected CLI, Marketplace, and MCP tools.++- **Endpoint:** `GET /api/tools`+- **Arguments:** none+- **Requires confirmation:** no+- **Desktop UI section:** `settings`+- **Voice example (EN):** "list the connected tools mcps and clis"+## `app-restart` — Restart JarvisRestart the Jarvis desktop app (voice + UI restart too).diff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.mdindex 6936ab7e34..b575a4f84f 100644--- a/docs/jarvis-cli-reference.md+++ b/docs/jarvis-cli-reference.md@@ -132,6 +132,7 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`## sessions- `jarvis sessions delete <session_id> --yes --dry-run` — Delete a text conversation thread.+- `jarvis sessions latest-turn --session-id` — Show the latest persisted user transcript and its complete turn.- `jarvis sessions list --days --limit` — List text + voice sessions, newest first.- `jarvis sessions resume <kind> <session_id> --yes --dry-run` — Seed the brain from a past conversation to continue it in text.- `jarvis sessions show <kind> <session_id>` — Show one conversation with its messages.@@ -183,6 +184,7 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`## wiki- `jarvis wiki health` — Show wiki subsystem health: bootstrap, last write, chain failures, backlog (spec A5).+- `jarvis wiki ingest <text> --source --dry-run` — Store a fact through the guarded Wiki curator.- `jarvis wiki page <slug>` — Read a wiki page by vault path / slug.- `jarvis wiki recall <query>` — Full-text search the wiki.- `jarvis wiki reindex --preview` — Rebuild the wiki search index from the active vault.diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex a60bb5057c..01c693c44f 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -29,7 +29,7 @@ BrainCallback = Callable[[str], Awaitable[str]]# + Wave-4 amendment ``spawn-sub-jarvis`` -> ``spawn-worker``) and# Master-Plan §22 / Persona-Mandate Phase 3.#-# Baseline (Mandate-Phase-3): run-shell, screen-snapshot, multi-spawn,+# Baseline after the 2026-07-12 cleanup: run-shell, screen-snapshot,# spawn-worker. Phase 8.4 (Plan §6.4 Quality-Gate) added dispatch-with-review,# which legitimately extends the set without breaking the pure-dispatcher# spirit.@@ -62,7 +62,6 @@ ROUTER_TOOLS = frozenset({# NB: ``dispatch-to-harness`` deliberately absent (removed 2026-06-28) —# see the header comment above. Heavy work → spawn-worker; desktop →# computer-use. The tool remains for the internal local-action fast path.- "multi-spawn","spawn-worker",# Phase 8.4 (Plan §6.4) — Hauptjarvis calls the quality-gate pipeline# explicitly. NEVER downstream in a recursive spawn (D9 recursion guard).@@ -329,7 +328,7 @@ def _load_tools_for_tier(the heavy worker runs as an external subprocess via the Mission-Manager.Encapsulates entry-point discovery + special cases (dispatch-to-harness,- spawn-worker, multi-spawn, whoami, awareness-snapshot).+ spawn-worker, whoami, awareness-snapshot).Args:tier: currently only ``"router"``.@@ -346,6 +345,46 @@ def _load_tools_for_tier(allow = ROUTER_TOOLStools: dict[str, Any] = {}+ # ``app-command`` and the other virtual loaders can expand to a name that+ # is also provided by a purpose-built native entry point. Entry-point+ # iteration order is not a contract, so plain ``tools[name] = tool`` made+ # the winner environment-dependent (notably Command Registry+ # ``wiki-ingest`` versus the native lazy-curator WikiIngestTool). Track+ # provenance and make the precedence explicit: native > virtual; ties are+ # resolved by stable source name.+ tool_sources: dict[str, tuple[bool, str]] = {}++ def register_tool(tool: Any, *, source: str, virtual: bool) -> None:+ name = str(getattr(tool, "name", "") or "").strip()+ if not name:+ log.warning("Tool from %s has no name and was skipped", source)+ return+ candidate = (not virtual, source)+ existing = tool_sources.get(name)+ if existing is not None:+ candidate_wins = candidate[0] and not existing[0]+ if candidate[0] == existing[0]:+ candidate_wins = candidate[1] < existing[1]+ if not candidate_wins:+ log.info(+ "Tool name collision for %r: keeping %s %r over %s %r",+ name,+ "native" if existing[0] else "virtual",+ existing[1],+ "native" if candidate[0] else "virtual",+ candidate[1],+ )+ return+ log.info(+ "Tool name collision for %r: replacing %s %r with %s %r",+ name,+ "native" if existing[0] else "virtual",+ existing[1],+ "native" if candidate[0] else "virtual",+ candidate[1],+ )+ tools[name] = tool+ tool_sources[name] = candidatefor ep in entry_points(group="jarvis.tool"):if ep.name not in allow:@@ -384,8 +423,6 @@ def _load_tools_for_tier(manager=harness_manager,max_output_chars=config.harness.max_output_chars,)- elif ep.name == "multi-spawn":- inst = cls(bus=bus, manager=harness_manager)elif ep.name in ("verify-via-curl", "verify-localhost"):inst = cls()elif ep.name == "start-preview-server":@@ -466,9 +503,9 @@ def _load_tools_for_tier(log.debug("virtual-loader '%s' expand() failed: %s", ep.name, exc)continuefor tool in expanded:- tools[tool.name] = tool+ register_tool(tool, source=ep.name, virtual=True)else:- tools[inst.name] = inst+ register_tool(inst, source=ep.name, virtual=False)except Exception as exc: # noqa: BLE001log.debug("Tool %s not loadable: %s", ep.name, exc)@@ -711,7 +748,7 @@ def _phase2_full_brain(executor = ToolExecutor(bus, evaluator, approval)# HarnessManager for the internal harness fast path (computer-use /- # local-action) + multi-spawn. NB: dispatch-to-harness is no longer an+ # local-action). NB: dispatch-to-harness is no longer an# LLM-visible router tool (removed 2026-06-28) — see the ROUTER_TOOLS header.from jarvis.harness.manager import HarnessManagerharness_manager = HarnessManager(bus=bus)diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 47f2d2505e..e3d80ea5c2 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -112,6 +112,10 @@ _PUBLISH_RESPONSE_EVENT: ContextVar[bool] = ContextVar("jarvis.brain.manager.publish_response_event",default=True,)+_TURN_HISTORY_OVERRIDE: ContextVar[tuple[BrainMessage, ...] | None] = ContextVar(+ "jarvis.brain.manager.turn_history_override",+ default=None,+)#: Hard bound on the per-turn vision capture (Wave-3 latency fix). ``vision.#: current()`` can stall (mss BitBlt hang, paused-state miss, slow disk); without@@ -5604,7 +5608,7 @@ class BrainManager:usable ingest source text; anything else is skipped, never raises."""try:- items = list(self._history)[-4:]+ items = list(self._active_turn_history())[-4:]except Exception: # noqa: BLE001 — history shape is provider-ownedreturn Noneparts: list[str] = []@@ -5615,6 +5619,56 @@ class BrainManager:parts.append(f"{role}: {text.strip()}")return "\n".join(parts[-2:]) or None+ def _active_turn_history(self) -> list[BrainMessage]:+ """Return the context-local history when a caller supplied one."""+ override = _TURN_HISTORY_OVERRIDE.get()+ return list(override) if override is not None else self._history++ async def _persisted_session_exchange_text(self) -> str | None:+ """Return the latest persisted exchange from the active voice session.++ Realtime deliberately owns a small context-local history instead of+ sharing ``self._history``. On its first delegated turn that history can+ therefore be empty even though the session recorder already contains a+ previous transcript. Resolve the existing live runtime objects lazily+ and require an active session id before reading: an unscoped "latest"+ lookup could copy text from a different conversation into the Wiki.++ The runtime objects are intentionally accessed through+ :mod:`jarvis.core.runtime_refs`; the brain layer neither imports the web+ server nor depends on the concrete ``SessionStore`` type. Any partially+ bootstrapped/headless runtime degrades to ``None``.+ """+ try:+ from jarvis.core import runtime_refs++ pipeline = runtime_refs.get_speech_pipeline()+ status_fn = getattr(pipeline, "voice_engine_status", None)+ status = status_fn() if callable(status_fn) else {}+ session_id = str(status.get("session_id") or "").strip()+ if not session_id:+ return None++ app = runtime_refs.get_web_app()+ store = getattr(getattr(app, "state", None), "session_store", None)+ get_latest = getattr(store, "get_latest_user_turn", None)+ if not callable(get_latest):+ return None++ turn = await asyncio.to_thread(get_latest, session_id=session_id)+ except Exception: # noqa: BLE001 - persisted context is a soft fallback+ log.debug("Persisted session-history lookup failed", exc_info=True)+ return None++ parts: list[str] = []+ for role, value in (+ ("user", getattr(turn, "user_text", None)),+ ("assistant", getattr(turn, "jarvis_text", None)),+ ):+ if isinstance(value, str) and value.strip():+ parts.append(f"{role}: {value.strip()}")+ return "\n".join(parts) or None+async def _run_wiki_ingest_fast_path(self,user_text: str,@@ -5645,6 +5699,8 @@ class BrainManager:content = match.contentif content is None:content = self._last_exchange_text()+ if content is None:+ content = await self._persisted_session_exchange_text()if not content or len(content.strip()) < 12:return await render_readback(getattr(self, "_readback_composer", None),@@ -5992,7 +6048,12 @@ class BrainManager:return self._reply_languagereturn "de" if _looks_german(user_text) else "en"- def _build_history_hints(self, *, max_turns: int = 3, max_chars_per_msg: int = 240) -> list[str]:+ def _build_history_hints(+ self,+ *,+ max_turns: int = 3,+ max_chars_per_msg: int = 240,+ ) -> list[str]:"""Formats the last N turn pairs as compact ``context_hints``.Conversation memory bridge to the OpenClaw worker (bug fix 2026-04-30,@@ -6001,14 +6062,14 @@ class BrainManager:explicitly refers to them ("erklaer mir das genauer","was war der zweite Punkt?").- One hint per turn pair in the format:- ``Frueherer Turn — User: '...' | Du sagtest: '...'``+ One hint is emitted per user/assistant turn pair.Truncated to ``max_chars_per_msg`` to prevent long replies frombloating the worker context."""- if not self._history:+ history = self._active_turn_history()+ if not history:return []- recent = self._history[-(2 * max_turns):]+ recent = history[-(2 * max_turns):]hints: list[str] = []for i in range(0, len(recent) - 1, 2):u = recent[i]@@ -6017,9 +6078,9 @@ class BrainManager:continueu_text = str(u.content)[:max_chars_per_msg]a_text = str(a.content)[:max_chars_per_msg]- hints.append(f"Frueherer Turn — User: {u_text!r} | Du sagtest: {a_text!r}")+ hints.append(f"Earlier turn — User: {u_text!r} | Assistant: {a_text!r}")if hints:- hints.insert(0, "Konversations-Kontext (letzte Turns, juengster zuletzt):")+ hints.insert(0, "Conversation context (recent turns, newest last):")return hintsasync def _force_spawn_worker(@@ -6549,14 +6610,21 @@ class BrainManager:allow_voice_confirm: bool = False,prefer_tool_model: bool = False,publish_response: bool = True,+ history_override: Iterable[BrainMessage] | None = None,) -> str:"""Generate a turn, optionally leaving its public response event to the caller.``publish_response=False`` suppresses only ``ResponseGenerated``. History,curator work, tool execution, and every other turn side effect remain intact.The context-local policy keeps concurrent classic and delegated calls isolated.+ ``history_override`` supplies caller-owned context for this turn without+ mutating the manager's shared conversation buffer; combine it with+ ``use_history=False`` when the caller owns history persistence too."""token = _PUBLISH_RESPONSE_EVENT.set(bool(publish_response))+ history_token = _TURN_HISTORY_OVERRIDE.set(+ tuple(history_override) if history_override is not None else None+ )try:return await self._generate(user_text,@@ -6569,6 +6637,7 @@ class BrainManager:prefer_tool_model=prefer_tool_model,)finally:+ _TURN_HISTORY_OVERRIDE.reset(history_token)_PUBLISH_RESPONSE_EVENT.reset(token)async def _generate(@@ -6770,6 +6839,25 @@ class BrainManager:getattr(self._skill_turn_match, "name", "?"),)self._skill_turn_match = None++ # Wiki-write fast path (spec A1-A3): an explicit wiki target owns the+ # turn before generic local-action, external-integration, or+ # keyword-matched skill routing. The destination is authoritative;+ # nouns inside the content (for example a trip to save as a fact) must+ # never reinterpret the command as booking or dispatching that noun.+ # Deterministic, model-independent, and confirm-after-write.+ wiki_reply = await self._run_wiki_ingest_fast_path(+ user_text, trace_id=turn_trace_id,+ )+ if wiki_reply is not None:+ await self._record_response_side_effects(+ user_text=user_text,+ response_text=wiki_reply,+ use_history=use_history,+ trace_id=turn_trace_id,+ )+ return wiki_reply+# Sibling of AD-S9: a plugin/marketplace skill that merely keyword-# matched an APP NAME ("Discord", "Spotify", "Slack") must NOT capture a# turn the deterministic desktop-control gate owns. Computer-Use is the@@ -6834,25 +6922,6 @@ class BrainManager:)return local_action- # Wiki-write fast path (spec A1-A3): an explicit "write this to the- # wiki" command must not depend on the router LLM choosing the- # wiki-ingest tool (fresh-machine forensics Bug 12/18). Deterministic,- # model-independent, confirm-after-write — same shape as the- # local-action block above. Placed before navigation/capability gates- # so a skill match never shadows an explicit wiki command.- if self._skill_turn_match is None:- wiki_reply = await self._run_wiki_ingest_fast_path(- user_text, trace_id=turn_trace_id,- )- if wiki_reply is not None:- await self._record_response_side_effects(- user_text=user_text,- response_text=wiki_reply,- use_history=use_history,- trace_id=turn_trace_id,- )- return wiki_reply-# Navigation fast-path: a clear "go to section X" command moves the UI# deterministically (a dumb action, AD-OE3). Placed BEFORE the capability# gate — which would refuse "zeig die Socials" because 'social' is an@@ -7087,7 +7156,12 @@ class BrainManager:log.warning("No brain providers available — spoken fallback used.")return await self._provider_down_reply(trace_uuid)- history = self._history if use_history else []+ history_override = _TURN_HISTORY_OVERRIDE.get()+ history = (+ list(history_override)+ if history_override is not None+ else (self._history if use_history else [])+ )_drop_in_hist = sum(1 for m in historyif isinstance(getattr(m, "content", None), str)diff --git a/jarvis/brain/router.py b/jarvis/brain/router.pyindex 95c0a53dc0..31abd10e68 100644--- a/jarvis/brain/router.py+++ b/jarvis/brain/router.py@@ -6,13 +6,14 @@ spawn_worker) IMPLICITLY via tool choice — no separate LLM call.Design (plan §"Router-Design"):- Haiku 4.5 / Gemini Flash as provider (via `BrainManager.from_tier_config("router")`).-- Tool set: only `bash` (run_shell), `screenshot`, `multi_spawn`, `spawn_worker`.+- Delegation tool: ``spawn_worker``; direct actions use the explicitly registered+ router tools such as ``bash`` and ``screenshot``.- Strict rule: the user utterance is NEVER rephrased; for `direct_action` and`spawn_worker` the utterance is passed VERBATIM as the tool argument.Classification via tool choice:- TRIVIAL → brain responds directly (no tool call).-- DIRECT → brain calls `bash` / `screenshot` / `multi_spawn`.+- DIRECT → brain calls an explicitly registered non-spawn router tool.- SPAWN → brain calls `spawn_worker(utterance=...)`.The loop (text stream + tool use) runs in `BrainDispatcher`; `RouterBrain`diff --git a/jarvis/cli_ctl/commands/sessions.py b/jarvis/cli_ctl/commands/sessions.pyindex b1984dbfef..5152fdf769 100644--- a/jarvis/cli_ctl/commands/sessions.py+++ b/jarvis/cli_ctl/commands/sessions.py@@ -21,6 +21,19 @@ def list_sessions(invoke.run("GET", "/api/chats", params={"days": days, "limit": limit})[email protected]("latest-turn")+def latest_turn(+ session_id: str | None = typer.Option(+ None,+ "--session-id",+ help="Restrict the lookup to one voice session.",+ ),+) -> None:+ """Show the latest persisted user transcript and its complete turn."""+ params = {"session_id": session_id} if session_id else None+ invoke.run("GET", "/api/sessions/latest-turn", params=params)++@app.command()def show(kind: str = typer.Argument(..., help="text | voice."),diff --git a/jarvis/cli_ctl/commands/wiki.py b/jarvis/cli_ctl/commands/wiki.pyindex 357557dc54..01d9c83901 100644--- a/jarvis/cli_ctl/commands/wiki.py+++ b/jarvis/cli_ctl/commands/wiki.py@@ -1,14 +1,9 @@-"""wiki: search and read the knowledge wiki (/api/wiki).--Note: deterministic save-fact (wiki-ingest) is a brain-tool, not a REST-endpoint, so it has no curated command here — use the running assistant for-ingestion. Search and read are exposed.-"""+"""wiki: search, read, and explicitly update the knowledge wiki (/api/wiki)."""from __future__ import annotationsimport typer-from jarvis.cli_ctl import invoke+from jarvis.cli_ctl import invoke, optionsapp = typer.Typer(no_args_is_help=True,@@ -46,6 +41,26 @@ def health() -> None:invoke.run("GET", "/api/wiki/health")+def ingest(+ text: str = typer.Argument(..., help="Self-contained fact or summary to store."),+ source: str = typer.Option(+ "cli:wiki-ingest",+ "--source",+ help="Short audit label for the content source.",+ ),+ dry_run: bool = options.dry_opt(),+) -> None:+ """Store a fact through the guarded Wiki curator."""+ invoke.run(+ "POST",+ "/api/wiki/ingest",+ body={"text": text, "source": source},+ dry_run=dry_run,+ dangerous=False,+ )++@app.command()def reindex(preview: bool = typer.Option(diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.pyindex 437c89e001..079c405d3b 100644--- a/jarvis/commands/registry.py+++ b/jarvis/commands/registry.py@@ -401,6 +401,80 @@ def _build_registry() -> tuple[AppCommand, ...]:"es": ("qué dispositivos de audio hay",), # i18n-allow: input vocab},),+ # ------------------------------------------------ knowledge & history+ AppCommand(+ id="wiki-ingest",+ title="Store a fact in the Wiki",+ description=(+ "Store one self-contained fact or summary through the guarded "+ "Wiki curator. The command succeeds only after a page is written."+ ),+ method="POST",+ path="/api/wiki/ingest",+ params={+ "type": "object",+ "properties": {+ "text": _str_param(+ "Self-contained fact or summary to store.",+ min_length=12,+ max_length=32_000,+ ),+ "source": _str_param(+ "Optional short audit label for the content source.",+ min_length=1,+ max_length=128,+ ),+ },+ "required": ["text"],+ },+ ui_section="memory",+ voice_aliases={+ "de": ("trag das in mein wiki ein",), # i18n-allow: input vocab+ "en": ("store that in my wiki",),+ "es": ("guarda eso en mi wiki",), # i18n-allow: input vocab+ },+ ),+ AppCommand(+ id="session-latest-turn",+ title="Show latest voice turn",+ description=(+ "Return the latest persisted user transcript and its complete "+ "voice turn, optionally restricted to one session."+ ),+ method="GET",+ path="/api/sessions/latest-turn",+ params={+ "type": "object",+ "properties": {+ "session_id": _str_param(+ "Optional voice-session id.", min_length=1, max_length=128+ ),+ },+ },+ ui_section="sessions",+ voice_aliases={+ "de": ("lies die letzte transkription",), # i18n-allow: input vocab+ "en": ("read the latest transcript",),+ "es": ("lee la última transcripción",), # i18n-allow: input vocab+ },+ ),+ AppCommand(+ id="tools-list",+ title="List effective tools",+ description=(+ "Return the effective live Brain tool surface, including native, "+ "connected CLI, Marketplace, and MCP tools."+ ),+ method="GET",+ path="/api/tools",+ params={"type": "object", "properties": {}},+ ui_section="settings",+ voice_aliases={+ "de": ("welche tools mcps und clis sind verbunden",), # i18n-allow: input vocab+ "en": ("list the connected tools mcps and clis",),+ "es": ("lista las herramientas mcps y clis conectadas",), # i18n-allow: input vocab+ },+ ),# ----------------------------------------------------------- systemAppCommand(id="app-restart",diff --git a/jarvis/core/capabilities_seed.py b/jarvis/core/capabilities_seed.pyindex 8c297412ea..dd492adc1b 100644--- a/jarvis/core/capabilities_seed.py+++ b/jarvis/core/capabilities_seed.py@@ -61,8 +61,9 @@ _SCREEN_OBJECTS: tuple[str, ...] = ()_WIKI_OBJECTS: tuple[str, ...] = (- "wiki", "notiz", "note", "wissen", "knowledge", "seite", "page",- "eintrag", "entry", "fact", "fakt", # i18n-allow+ "wiki", "wiki-system", "wiki system", "wikisystem",+ "notiz", "note", "wissen", "knowledge", "seite", "page",+ "fact", "fakt", # i18n-allow)_AWARENESS_OBJECTS: tuple[str, ...] = (@@ -101,15 +102,6 @@ _SEED_CAPABILITIES: list[Capability] = [# no longer an LLM-visible router tool (see jarvis/brain/factory.py header).# Desktop-control intent is carried by ``harness.computer-use`` + the shared# _ACTION_VERBS; heavy sub-agent intent by ``tool.spawn-worker``.- Capability(- id="tool.multi-spawn",- source="router_tool",- verbs=("spawn", "spawne", "spawnen", "starte", "start", "launch", "delegier"),- objects=("agent", "agenten", "agents", "worker", "workers", "aufgaben", "tasks"),- description="Spawn multiple parallel worker agents for a complex task.",- risk_tier="ask",- requires_evidence=True,- ),Capability(id="tool.spawn-worker",source="router_tool",@@ -187,7 +179,9 @@ _SEED_CAPABILITIES: list[Capability] = [source="router_tool",verbs=("speicher", "save", "merk", "merke", "notier", "notiere",- "ingest", "store", "schreib", "write",+ "ingest", "store", "schreib", "write", "record", "add", "put",+ "eintrag", "eintrage", "eintragen", # i18n-allow+ "anota", "apunta", "agrega", "guarda", # i18n-allow: input vocabulary),objects=_WIKI_OBJECTS,description="Store a fact / note deterministically into the wiki vault.",diff --git a/jarvis/memory/wiki/consolidator.py b/jarvis/memory/wiki/consolidator.pyindex 38e4ba00f7..3c040e320a 100644--- a/jarvis/memory/wiki/consolidator.py+++ b/jarvis/memory/wiki/consolidator.py@@ -230,6 +230,24 @@ class Consolidator:else available),)+ rejection_reasons: list[str] = []++ def _validate_response(agg: Any) -> str | None:+ if is_length_truncated(agg.finish_reason, agg.text):+ reason = (+ f"truncated structured output ({len(agg.text or '')} chars, "+ f"finish_reason={agg.finish_reason!r})"+ )+ rejection_reasons.append(reason)+ return reason+ try:+ _extract_json_array(agg.text)+ except ValueError as exc:+ reason = f"malformed JSON array: {exc}"+ rejection_reasons.append(reason)+ return reason+ return None+result = await complete_with_fallback(registry=self._registry,chain=chain,@@ -237,8 +255,16 @@ class Consolidator:timeout_s=float(self._curator_cfg.timeout_s),label="Consolidator",aggregate=aggregate,+ validate=_validate_response,)if result is None:+ if any(reason.startswith("truncated") for reason in rejection_reasons):+ log.warning(+ "Consolidator: every provider hit the output-token cap or failed "+ "after a truncated response; the batch will be skipped"+ )+ telemetry.inc("wiki_writes_blocked_truncated")+ return "truncated"return Noneagg, self._resolved_provider = resultdiff --git a/jarvis/memory/wiki/curator_llm.py b/jarvis/memory/wiki/curator_llm.pyindex 2649990c79..b8b54fcaef 100644--- a/jarvis/memory/wiki/curator_llm.py+++ b/jarvis/memory/wiki/curator_llm.py@@ -421,6 +421,24 @@ class WikiCuratorLLM:else available),)+ rejection_reasons: list[str] = []++ def _validate_response(agg: Any) -> str | None:+ if is_length_truncated(agg.finish_reason, agg.text):+ reason = (+ f"truncated structured output ({len(agg.text or '')} chars, "+ f"finish_reason={agg.finish_reason!r})"+ )+ rejection_reasons.append(reason)+ return reason+ try:+ _parse_updates(agg.text)+ except (ValueError, json.JSONDecodeError) as exc:+ reason = f"malformed update JSON: {exc}"+ rejection_reasons.append(reason)+ return reason+ return None+result = await complete_with_fallback(registry=self._registry,chain=chain,@@ -428,8 +446,15 @@ class WikiCuratorLLM:timeout_s=self._cfg.timeout_s,label="WikiCuratorLLM",aggregate=aggregate,+ validate=_validate_response,)if result is None:+ if any(reason.startswith("truncated") for reason in rejection_reasons):+ logger.warning(+ "WikiCuratorLLM: every provider hit the output-token cap "+ "or failed after a truncated response; no updates were persisted"+ )+ telemetry.inc("wiki_writes_blocked_truncated")return []agg, self._resolved_provider = resultdiff --git a/jarvis/memory/wiki/extractor.py b/jarvis/memory/wiki/extractor.pyindex 538536dabb..2a42de8f64 100644--- a/jarvis/memory/wiki/extractor.py+++ b/jarvis/memory/wiki/extractor.py@@ -234,6 +234,24 @@ class ConversationFactExtractor:else available),)+ rejection_reasons: list[str] = []++ def _validate_response(agg: Any) -> str | None:+ if is_length_truncated(agg.finish_reason, agg.text):+ reason = (+ f"truncated structured output ({len(agg.text or '')} chars, "+ f"finish_reason={agg.finish_reason!r})"+ )+ rejection_reasons.append(reason)+ return reason+ try:+ _extract_json_array(agg.text)+ except ValueError as exc:+ reason = f"malformed JSON array: {exc}"+ rejection_reasons.append(reason)+ return reason+ return None+result = await complete_with_fallback(registry=self._registry,chain=chain,@@ -241,8 +259,15 @@ class ConversationFactExtractor:timeout_s=float(self._cfg.timeout_s),label="ConversationFactExtractor",aggregate=aggregate,+ validate=_validate_response,)if result is None:+ if any(reason.startswith("truncated") for reason in rejection_reasons):+ log.warning(+ "ConversationFactExtractor: every provider hit the output-token "+ "cap or failed after a truncated response; no candidates were saved"+ )+ telemetry.inc("wiki_writes_blocked_truncated")return []agg, self._resolved_provider = resultdiff --git a/jarvis/memory/wiki/ingest_service.py b/jarvis/memory/wiki/ingest_service.pynew file mode 100644index 0000000000..709af72785--- /dev/null+++ b/jarvis/memory/wiki/ingest_service.py@@ -0,0 +1,246 @@+"""Shared, audited write service for explicit Wiki ingestion.++The brain tool, REST route, and curated CLI command all terminate here so they+cannot disagree about validation or claim that a no-op updated the vault. The+curator remains the only component that decides page changes, and its+``AtomicWriter`` remains the only component that touches Wiki pages.+"""+from __future__ import annotations++import logging+from dataclasses import dataclass+from pathlib import Path+from typing import Any++log = logging.getLogger(__name__)++MIN_INGEST_CHARS = 12+MAX_INGEST_CHARS = 32_000+MAX_SOURCE_CHARS = 128+++@dataclass(frozen=True, slots=True)+class WikiIngestOutcome:+ """Normalized result shared by tool and HTTP callers."""++ success: bool+ source: str+ applied: tuple[Path, ...] = ()+ skipped_due_to_recent_edit: tuple[Path, ...] = ()+ failed_validation: tuple[Path, ...] = ()+ blocked_pii: tuple[Path, ...] = ()+ error_code: str | None = None+ error: str | None = None++ @property+ def page_names(self) -> list[str]:+ """Return safe display names without exposing an absolute vault path."""+ return [path.name for path in self.applied]++ def render_summary(self) -> str:+ """Render the established ``wiki-ingest`` tool result format."""+ lines = [+ f"Wiki ingest done (source={self.source}):",+ f"- applied: {len(self.applied)}",+ ]+ if self.skipped_due_to_recent_edit:+ lines.append(+ "- skipped (recent user edit): "+ f"{len(self.skipped_due_to_recent_edit)}"+ )+ if self.failed_validation:+ lines.append(+ "- failed validation (rolled back): "+ f"{len(self.failed_validation)}"+ )+ if self.blocked_pii:+ lines.append(f"- blocked sensitive content: {len(self.blocked_pii)}")+ if self.applied:+ lines.append("Pages touched:")+ lines.extend(f" - {path.name}" for path in self.applied[:10])+ return "\n".join(lines)+++def _failure(source: str, code: str, error: str) -> WikiIngestOutcome:+ return WikiIngestOutcome(+ success=False,+ source=source,+ error_code=code,+ error=error,+ )+++def _record_write_health(outcome: WikiIngestOutcome) -> None:+ """Record the explicit write outcome without affecting the write path."""+ try:+ from jarvis.memory.wiki.health import health++ health.record_write(+ outcome.success,+ pages=[str(path) for path in outcome.applied],+ error=outcome.error,+ source=outcome.source,+ )+ except Exception: # noqa: BLE001 - observability must not break ingestion+ log.debug("wiki-ingest: health.record_write failed", exc_info=True)+++async def ingest_wiki_text(+ *,+ curator: Any,+ text: str,+ source: str,+) -> WikiIngestOutcome:+ """Validate and ingest one self-contained fact through the live curator.++ A call succeeds only when at least one page is actually written. Recent+ edit conflicts, validation rollbacks, sensitive-content blocks, and an LLM+ salience no-op are distinct failure codes so HTTP and tool callers can+ report the real outcome.+ """+ clean_text = str(text or "").strip()+ clean_source = str(source or "").strip()++ if not clean_text:+ return _failure(clean_source, "missing-text", "missing 'text' argument")+ if len(clean_text) < MIN_INGEST_CHARS:+ return _failure(+ clean_source,+ "text-too-short",+ f"text too short ({len(clean_text)} chars; min {MIN_INGEST_CHARS}). "+ "Pass a full self-contained statement, not a single word.",+ )+ if len(clean_text) > MAX_INGEST_CHARS:+ return _failure(+ clean_source,+ "text-too-long",+ f"text too long ({len(clean_text)} chars; max {MAX_INGEST_CHARS}). "+ "Split it into multiple ingest calls.",+ )+ if (+ not clean_source+ or len(clean_source) > MAX_SOURCE_CHARS+ or any(char in clean_source for char in ("\r", "\n", "\x00"))+ ):+ return _failure(+ clean_source,+ "invalid-source",+ f"source must be a single non-empty line up to {MAX_SOURCE_CHARS} chars",+ )+ if curator is None:+ outcome = _failure(+ clean_source,+ "not-bootstrapped",+ "wiki integration not bootstrapped",+ )+ _record_write_health(outcome)+ return outcome++ log.debug(+ "wiki-ingest: source=%s len=%d body=%r",+ clean_source,+ len(clean_text),+ clean_text,+ )+ log.info(+ "wiki-ingest: ingesting %d chars (source=%s)",+ len(clean_text),+ clean_source,+ )++ try:+ result = await curator.ingest(clean_text, clean_source)+ except Exception as exc: # noqa: BLE001 - boundary reports a clean outcome+ log.warning("wiki-ingest: curator.ingest raised %s", exc)+ outcome = _failure(+ clean_source,+ "curator-failed",+ f"curator ingest failed: {exc}",+ )+ _record_write_health(outcome)+ return outcome++ applied = tuple(Path(path) for path in (getattr(result, "applied", ()) or ()))+ skipped = tuple(+ Path(path)+ for path in (getattr(result, "skipped_due_to_recent_edit", ()) or ())+ )+ failed = tuple(+ Path(path)+ for path in (getattr(result, "failed_validation", ()) or ())+ )+ blocked = tuple(+ Path(path) for path in (getattr(result, "blocked_pii", ()) or ())+ )++ if applied:+ outcome = WikiIngestOutcome(+ success=True,+ source=clean_source,+ applied=applied,+ skipped_due_to_recent_edit=skipped,+ failed_validation=failed,+ blocked_pii=blocked,+ )+ elif blocked:+ outcome = WikiIngestOutcome(+ success=False,+ source=clean_source,+ skipped_due_to_recent_edit=skipped,+ failed_validation=failed,+ blocked_pii=blocked,+ error_code="sensitive-content-blocked",+ error=(+ "nothing was stored: the write was blocked because sensitive "+ "content was detected"+ ),+ )+ elif failed:+ outcome = WikiIngestOutcome(+ success=False,+ source=clean_source,+ skipped_due_to_recent_edit=skipped,+ failed_validation=failed,+ blocked_pii=blocked,+ error_code="validation-failed",+ error="nothing was stored: every proposed page failed validation",+ )+ elif skipped:+ outcome = WikiIngestOutcome(+ success=False,+ source=clean_source,+ skipped_due_to_recent_edit=skipped,+ failed_validation=failed,+ blocked_pii=blocked,+ error_code="recent-edit-conflict",+ error=(+ "nothing was stored: every proposed page had a recent user edit; "+ "retry after reviewing that edit"+ ),+ )+ else:+ outcome = _failure(+ clean_source,+ "nothing-stored",+ "nothing was stored: the curator judged the content not salient "+ "enough for the wiki",+ )++ _record_write_health(outcome)+ log.info(+ "wiki-ingest: applied=%d skipped=%d failed=%d blocked=%d",+ len(applied),+ len(skipped),+ len(failed),+ len(blocked),+ )+ return outcome+++__all__ = [+ "MAX_INGEST_CHARS",+ "MAX_SOURCE_CHARS",+ "MIN_INGEST_CHARS",+ "WikiIngestOutcome",+ "ingest_wiki_text",+]diff --git a/jarvis/memory/wiki/intent.py b/jarvis/memory/wiki/intent.pyindex e0887edfdc..2fa94a5687 100644--- a/jarvis/memory/wiki/intent.py+++ b/jarvis/memory/wiki/intent.py@@ -1,127 +1,209 @@"""Deterministic wiki-write intent matcher (spec A1).-Explicit "write this to the wiki" commands must never depend on the-router LLM choosing the ``wiki-ingest`` tool — the weak free default-model on fresh installs almost never does (forensics Bug 12/18). This-matcher runs on the final user transcript in the brain's fast-path-pre-pass (same philosophy as ``jarvis/brain/local_action_gate.py``) and-fires the ingest pipeline model-independently.--Pure regex — no LLM, no IO (AP-9/AP-11). The de/en/es tokens are-speech-recognition input vocabulary (closed-list category 3).-Precision over recall: a false positive writes noise to the vault, a-false negative falls back to the (possibly capable) LLM tool path — so-every pattern REQUIRES an explicit wiki object.+Explicit "write this to the wiki" commands must never depend on the router+LLM choosing the ``wiki-ingest`` tool. This matcher runs on the final user+transcript in the brain's fast-path pre-pass and fires the ingest pipeline+model-independently.++Pure regex -- no LLM and no IO (AP-9/AP-11). The de/en/es tokens are speech+recognition input vocabulary (closed-list category 3). Precision remains the+priority: every match requires both a write verb and an explicit wiki target."""from __future__ import annotationsimport refrom dataclasses import dataclass-# German-umlaut transliteration table (input normalization).-_UMLAUTS = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "ß": "ss"}) # i18n-allow+# Input normalization for supported speech languages. # i18n-allow: literal input vocabulary+_TRANSLITERATION = str.maketrans({+ "ä": "ae", "ö": "oe", "ü": "ue", "ß": "ss", # i18n-allow+ "á": "a", "é": "e", "í": "i", "ó": "o", "ú": "u",+})# Write verbs (normalized, de/en/es). # i18n-allow: input vocabulary-_VERBS = (- r"(?:schreib(?:e|st)?|notier(?:e)?|speicher(?:e)?|merk(?:e)?\s+dir|"- r"trag(?:e)?\s+.{0,20}?ein|halte?\s+.{0,30}?fest|"- r"write|save|note|add|store|put|record|"- r"escribe|guarda|anota|apunta|agrega)"+_WRITE_VERB_RE = re.compile(+ r"\b(?:"+ r"schreib\w*|notier\w*|speicher\w*|merk(?:e|st|t)?\s+(?:es\s+)?dir|"+ r"eintrag\w*|trag\w*|vermerk\w*|hinzufueg\w*|fueg\w*|" # i18n-allow+ r"write|save|note(?:\s+down)?|add|store|put|record|enter|update|"+ r"escrib\w*|guard\w*|anot\w*|apunt\w*|agreg\w*|anad\w*|"+ r"registr\w*|actualiz\w*|pon"+ r")\b",+ re.IGNORECASE,+)++_DE_POSSESSIVE = r"(?:mein|dein|unser|euer|ihr)(?:e[msn]?)?"+_WIKI_NOUN = r"wiki(?:[\s-]?system)?"++# A target must be grammatically marked as the destination/object. This keeps+# source/recall clauses such as "what the wiki says" out of the write path.+# The tokens are de/en/es speech-input vocabulary. # i18n-allow+_WIKI_TARGET_RE = re.compile(+ rf"\b(?:"+ rf"(?:ins|im|zum)\s+(?:{_DE_POSSESSIVE}\s+)?{_WIKI_NOUN}|"+ rf"in\s+(?:das|{_DE_POSSESSIVE})\s+{_WIKI_NOUN}|"+ rf"(?:to|in|into)\s+(?:(?:the|my|your)\s+)?{_WIKI_NOUN}|"+ rf"(?:en|al|a)\s+(?:(?:la|el|mi|tu)\s+)?{_WIKI_NOUN}|"+ rf"(?:das|{_DE_POSSESSIVE}|the|my|your|la|el|mi|tu)\s+{_WIKI_NOUN}"+ rf")\b",+ re.IGNORECASE,)-# Explicit wiki object (normalized, de/en/es). # i18n-allow: input vocabulary-_WIKI_OBJ = (- r"(?:(?:ins|in\s+das|im|in\s+mein(?:em)?|zum)\s+wiki" # i18n-allow: input vocabulary- r"|(?:to|in|into)\s+(?:the\s+|my\s+)?wiki"- r"|(?:en|al)\s+(?:la\s+|el\s+|mi\s+)?wiki)"+# Polite question grammar may still express a command.+# The tokens are speech-input vocabulary. # i18n-allow+_POLITE_PREFIX_RE = re.compile(+ r"^[¿¡\s]*(?:(?:hey\s+)?jarvis(?:[,\s]+|$))?"+ r"(?:(?:(?:kannst|koenntest|wuerdest)\s+du(?:\s+mir)?(?:\s+bitte)?|"+ r"(?:can|could|would|will)\s+you(?:\s+please)?|"+ r"(?:puedes|podrias)(?:\s+por\s+favor)?)(?:[,\s]+|$))?"+ r"(?:(?:bitte|please|por\s+favor)(?:[,\s]+|$))?",+ re.IGNORECASE,)-_PREFIX = r"^(?:hey\s+)?(?:jarvis[,\s]+)?"+# Information questions remain reads even if they mention a write verb later,+# for example "What should I write in my wiki?". # i18n-allow: input vocabulary+_INFORMATION_QUESTION_RE = re.compile(+ r"^(?:was|wer|wie|wo|wann|warum|welch\w*|what|who|how|where|when|why|"+ r"which|que|quien|como|donde|cuando|cual)\b",+ re.IGNORECASE,+)-# Question openers that mean recall/general questions, never a write command.-_QUESTION_RE = re.compile(- r"^(?:was|wer|wie|wo|wann|warum|what|who|how|where|when|why|que|qu|quien|" # i18n-allow- r"como|donde|cuando)\b", # i18n-allow+# Explicit references to the immediately preceding spoken turn. These are+# anaphoric even though they contain nouns, so the caller must supply bounded+# current-session history rather than storing the literal words "last+# transcript". # i18n-allow: multilingual speech-input vocabulary+_LATEST_TRANSCRIPT_RE = re.compile(+ r"\b(?:"+ r"(?:die\s+)?letzte\w*\s+(?:transkription|transkript|aussage|nachricht|turn)|" # i18n-allow: German speech-input vocabulary+ r"(?:das\s+)?zuletzt\s+gesagte|"+ r"(?:the\s+)?(?:last|latest|previous)\s+(?:transcript|utterance|message|turn)|"+ r"(?:la\s+)?ultima\w*\s+(?:transcripcion|mensaje|turno)"+ r")\b",+ re.IGNORECASE,)-# Anaphoric objects: the command refers to prior conversation content.+# Anaphoric objects refer to content from the prior conversation exchange. # i18n-allow_ANAPHORA = frozenset({- "das", "es", "dies", "diese", "dieses", "den", "die", # i18n-allow- "that", "this", "it", "them",- "eso", "esto", "lo", "la", # i18n-allow+ "das", "es", "dies", "diese", "dieses", "den", "die", "etwas", # i18n-allow+ "that", "this", "it", "them", "something",+ "eso", "esto", "lo", "la", "algo",})-# Standalone filler particles (single tokens from _FILLER_RE's alternation)-# that carry no content on their own — e.g. "schreib das BITTE ins wiki" is # i18n-allow-# still anaphoric even though "bitte" trails the anaphor instead of leading # i18n-allow-# the fragment, so the prefix-anchored _FILLER_RE strip alone misses it._FILLER_WORDS = frozenset({- "bitte", "mal", "doch", "kurz", "please", "por", "favor", "que", "dass", # i18n-allow+ "bitte", "mal", "doch", "kurz", "please", "por", "favor", "que",+ "dass", "ein", "hinzu", # i18n-allow: input vocabulary})-_COMMAND_RE = re.compile(- _PREFIX- + _VERBS- + r"\s+(?P<pre>.*?)\s*"- + _WIKI_OBJ- + r"\s*[:,]?\s*(?P<post>.*?)\s*[?.!]*$",+_LEADING_FILLER_RE = re.compile(+ r"^(?:(?:bitte|mal|doch|kurz|please|por\s+favor|que|dass)\b|[,;:])+\s*",re.IGNORECASE,)--_FILLER_RE = re.compile(- r"^(?:bitte|mal|doch|kurz|please|por\s+favor|que|dass|,)+\s*" # i18n-allow-)+_WORD_RE = re.compile(r"[a-z0-9]+")@dataclass(frozen=True, slots=True)class WikiIntentMatch:- #: Inline content to ingest; ``None`` = anaphoric — the caller supplies- #: the last conversation exchange as the source.+ #: Inline content to ingest; ``None`` means the caller must supply the+ #: previous conversation exchange.content: str | None- #: The full matched utterance (normalized) for logging.+ #: Full matched utterance after normalization, for diagnostics.matched: strdef _normalize(text: str) -> str:- return text.strip().lower().translate(_UMLAUTS)---def _strip_filler(fragment: str) -> str:- prev = None- frag = fragment.strip()- while prev != frag:- prev = frag- frag = _FILLER_RE.sub("", frag).strip()- return frag+ normalized = text.strip().lower().translate(_TRANSLITERATION)+ return re.sub(r"\s+", " ", normalized)+++def _strip_leading_filler(fragment: str) -> str:+ previous = None+ cleaned = fragment.strip()+ while previous != cleaned:+ previous = cleaned+ cleaned = _LEADING_FILLER_RE.sub("", cleaned).strip()+ return cleaned+++def _words(fragment: str) -> list[str]:+ return _WORD_RE.findall(fragment.lower())+++def _only_control_words(fragment: str) -> bool:+ return all(word in _ANAPHORA or word in _FILLER_WORDS for word in _words(fragment))+++def _content_after_verb(fragment: str, verb: str) -> str | None:+ content = fragment.strip(" \t,;:")+ # German separable verbs put the particle after the target:+ # "trag das ins Wiki ein, dass ...". # i18n-allow: input syntax example+ if verb.startswith("trag"):+ content = re.sub(r"^ein\b\s*[,;:]?\s*", "", content)+ elif verb.startswith("fueg"):+ content = re.sub(r"^hinzu\b\s*[,;:]?\s*", "", content)+ content = _strip_leading_filler(content).rstrip(" \t.?!")+ meaningful = [+ word for word in _words(content)+ if word not in _ANAPHORA and word not in _FILLER_WORDS+ ]+ return content if meaningful else None+++def _match_verb_before_target(+ body: str,+ target: re.Match[str],+) -> tuple[re.Match[str], str | None] | None:+ for verb in _WRITE_VERB_RE.finditer(body, 0, target.start()):+ if not _only_control_words(body[:verb.start()]):+ continue+ if not _only_control_words(body[verb.end():target.start()]):+ continue+ return verb, _content_after_verb(body[target.end():], verb.group(0))+ return None+++def _match_target_before_verb(+ body: str,+ target: re.Match[str],+) -> tuple[re.Match[str], str | None] | None:+ if not _only_control_words(body[:target.start()]):+ return None+ for verb in _WRITE_VERB_RE.finditer(body, target.end()):+ if not _only_control_words(body[target.end():verb.start()]):+ continue+ return verb, _content_after_verb(body[verb.end():], verb.group(0))+ return Nonedef match_wiki_intent(user_text: str) -> WikiIntentMatch | None:- """Return a match for an explicit wiki-WRITE command, else ``None``."""+ """Return a match for an explicit wiki-write command, otherwise ``None``."""norm = _normalize(user_text)if not norm or len(norm) > 600:return None- if _QUESTION_RE.match(norm) or norm.endswith("?"):- return None- m = _COMMAND_RE.match(norm)- if m is None:++ question_probe = norm.lstrip("¿¡ ")+ if _INFORMATION_QUESTION_RE.match(question_probe):return None- # Precision gate: a legitimate command puts the write verb DIRECTLY on- # the wiki-object, so ``pre`` (whatever sits between them) is either- # empty (the content follows the object) or a bare anaphor (the- # "write THAT to the wiki" shape). Any real word in ``pre`` means the- # wiki reference sits in a subordinate/recall clause (a recall question- # that merely opens with a write verb), not a write target — so defer to- # the LLM tool path. A false negative is acceptable; a false positive- # writes noise to the vault.- pre = _strip_filler(m.group("pre") or "")- pre_words = [w for w in re.split(r"\s+", pre) if w]- if any(w not in _ANAPHORA and w not in _FILLER_WORDS for w in pre_words):++ body = _POLITE_PREFIX_RE.sub("", norm, count=1).strip()+ if not body:return None- # Anaphoric-vs-inline is decided on ``post``: real content there is an- # inline write; nothing meaningful means an anaphoric command whose- # source is the prior conversation exchange.- post = _strip_filler(m.group("post") or "")- post_words = [w for w in re.split(r"\s+", post) if w]- if not any(w not in _ANAPHORA and w not in _FILLER_WORDS for w in post_words):++ # A longer wrapper such as "After looking at the last transcript, could you+ # put it in my Wiki?" need not fit the compact command grammar below. The+ # three explicit signals (latest-turn reference + Wiki target + write verb)+ # make this an unambiguous anaphoric write without extracting prose as data.+ if (+ _LATEST_TRANSCRIPT_RE.search(body)+ and _WIKI_TARGET_RE.search(body)+ and _WRITE_VERB_RE.search(body)+ ):return WikiIntentMatch(content=None, matched=norm)- return WikiIntentMatch(content=post, matched=norm)++ for target in _WIKI_TARGET_RE.finditer(body):+ matched = _match_verb_before_target(body, target)+ if matched is None:+ matched = _match_target_before_verb(body, target)+ if matched is not None:+ _verb, content = matched+ return WikiIntentMatch(content=content, matched=norm)+ return Nonediff --git a/jarvis/memory/wiki/provider_chain.py b/jarvis/memory/wiki/provider_chain.pyindex 4eff856c44..0020804612 100644--- a/jarvis/memory/wiki/provider_chain.py+++ b/jarvis/memory/wiki/provider_chain.py@@ -107,14 +107,14 @@ async def complete_with_fallback(timeout_s: float,label: str,aggregate: Callable[[Any], Any],+ validate: Callable[[Any], str | None] | None = None,) -> tuple[Any, str] | None:"""Try each ``(provider, model)`` until one returns an aggregated response.- Returns ``(agg, provider_name)`` on the first success, or ``None`` when the- WHOLE chain failed. A single provider failure is a WARNING (visible, not- fatal); an exhausted chain is an ERROR plus a ``wiki_all_providers_failed``- telemetry bump — the HONEST signal that the wiki could reach NO provider,- instead of the old silent empty return.+ Returns ``(agg, provider_name)`` on the first usable success, or ``None``+ when the whole chain fails. ``validate`` can reject a transport-successful+ response with a short reason; the next provider is then tried before the+ caller gives up on malformed or truncated structured output."""from jarvis.memory.wiki.curator_llm import instantiate_curator_brain@@ -138,6 +138,31 @@ async def complete_with_fallback(continuetry:agg = await asyncio.wait_for(aggregate(brain.complete(request)), timeout=timeout_s)+ if validate is not None:+ try:+ rejection = validate(agg)+ except Exception as exc: # noqa: BLE001 - validator faults mean unusable output+ rejection = f"response validation failed: {exc}"+ if rejection:+ log.warning(+ "%s: provider %s returned unusable output (%s) - "+ "trying next provider",+ label,+ provider,+ rejection,+ )+ failure_summaries.append(+ f"{provider} unusable output: {rejection}"+ )+ try:+ telemetry.inc("wiki_provider_output_rejected")+ except Exception: # noqa: BLE001 - telemetry cannot break fallback+ log.debug(+ "%s: output-rejection telemetry failed",+ label,+ exc_info=True,+ )+ continuereturn agg, providerexcept TimeoutError:log.warning(@@ -154,8 +179,8 @@ async def complete_with_fallback(continuelog.error(- "%s: ALL %d wiki provider(s) failed — no LLM reachable this round; nothing "- "was written. Check API keys / quota in the API-Keys section.",+ "%s: ALL %d wiki provider(s) failed or returned unusable output — "+ "nothing was written. Check provider health and structured-output logs.",label,len(chain),)diff --git a/jarvis/memory/wiki/scheduler.py b/jarvis/memory/wiki/scheduler.pyindex 7b4de8d1a9..a689065521 100644--- a/jarvis/memory/wiki/scheduler.py+++ b/jarvis/memory/wiki/scheduler.py@@ -38,7 +38,7 @@ import asyncioimport loggingimport timefrom dataclasses import dataclass-from enum import Enum+from enum import StrEnumfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -50,7 +50,7 @@ if TYPE_CHECKING:log = logging.getLogger(__name__)-class TriggerSource(str, Enum):+class TriggerSource(StrEnum):"""Source that fired a ``CuratorScheduler.trigger`` call."""SESSION_END = "session_end"@@ -86,7 +86,12 @@ def fire_journal_trigger(``RuntimeError`` guard for "no running event loop". Returns the createdtask so a caller may await or track it."""- task = asyncio.create_task(scheduler.trigger(TriggerSource.JOURNAL), name=name)+ schedule = getattr(scheduler, "schedule_journal_trigger", None)+ task = (+ schedule(name=name)+ if callable(schedule)+ else asyncio.create_task(scheduler.trigger(TriggerSource.JOURNAL), name=name)+ )def _log_outcome(t: asyncio.Task[Any]) -> None:# A lost trigger is retried on the next append/tick, so WARNING@@ -97,7 +102,9 @@ def fire_journal_trigger(if exc is not None:log.warning("wiki journal trigger (%s) failed: %s", log_context, exc)- task.add_done_callback(_log_outcome)+ if not getattr(task, "_jarvis_journal_outcome_callback", False):+ task.add_done_callback(_log_outcome)+ task._jarvis_journal_outcome_callback = True # type: ignore[attr-defined]return task@@ -147,9 +154,9 @@ class CuratorScheduler:def __init__(self,*,- curator: "WikiCurator",- lock: "VaultLock",- config: "SchedulerConfig",+ curator: WikiCurator,+ lock: VaultLock,+ config: SchedulerConfig,consolidator: Any = None,) -> None:self._curator = curator@@ -159,6 +166,13 @@ class CuratorScheduler:# triggers drain the candidate journal through it instead of the# legacy curator.ingest path. Duck-typed: needs ``run_once()``.self._consolidator = consolidator+ # All overlapping JOURNAL requests share one drain task. A request that+ # arrives during a drain marks it dirty, causing exactly one additional+ # pass after the active batch. This preserves newly appended candidates+ # without creating an unbounded convoy of redundant empty runs.+ self._journal_drain_task: asyncio.Task[SchedulerResult] | None = None+ self._journal_fire_task: asyncio.Task[SchedulerResult] | None = None+ self._journal_dirty = False# Monotonic timestamp of the last completed curator run.# ``None`` means "never ran" — the first trigger always passes the# cooldown gate. (A 0.0 sentinel is wrong: when the machine's@@ -202,7 +216,24 @@ class CuratorScheduler:re-raised after the lock is released — callers must handlethem)."""- result = await self._do_trigger(source, episode_paths=episode_paths)+ if source is TriggerSource.JOURNAL:+ active = self._journal_drain_task+ if active is not None and not active.done():+ self._journal_dirty = True+ result = await asyncio.shield(active)+ else:+ self._journal_dirty = False+ active = asyncio.create_task(+ self._drain_journal(), name="wiki-journal-drain"+ )+ self._journal_drain_task = active+ try:+ result = await asyncio.shield(active)+ finally:+ if self._journal_drain_task is active and active.done():+ self._journal_drain_task = None+ else:+ result = await self._do_trigger(source, episode_paths=episode_paths)# Emit a single structured INFO line per call.log.info("CuratorScheduler trigger: source=%s triggered=%s skip_reason=%r label=%r",@@ -213,10 +244,45 @@ class CuratorScheduler:)return result+ def schedule_journal_trigger(+ self, *, name: str = "wiki-journal-trigger"+ ) -> asyncio.Task[SchedulerResult]:+ """Return one shared fire-and-forget task for journal pressure.++ A request made while the task is actively draining marks the drain dirty+ so one follow-up pass observes candidates appended during that run.+ """+ active = self._journal_fire_task+ if active is not None and not active.done():+ drain = self._journal_drain_task+ if drain is not None and not drain.done():+ self._journal_dirty = True+ return active++ active = asyncio.create_task(self.trigger(TriggerSource.JOURNAL), name=name)+ self._journal_fire_task = active++ def _clear(done: asyncio.Task[SchedulerResult]) -> None:+ if self._journal_fire_task is done:+ self._journal_fire_task = None++ active.add_done_callback(_clear)+ return active+# ------------------------------------------------------------------# Internals# ------------------------------------------------------------------+ async def _drain_journal(self) -> SchedulerResult:+ """Drain one batch and at most one coalesced follow-up at a time."""+ result = await self._do_trigger(TriggerSource.JOURNAL, episode_paths=None)+ while self._journal_dirty:+ self._journal_dirty = False+ result = await self._do_trigger(+ TriggerSource.JOURNAL, episode_paths=None+ )+ return result+async def _do_trigger(self,source: TriggerSource,@@ -242,7 +308,10 @@ class CuratorScheduler:)# ----- gate 2: cooldown (MANUAL/JOURNAL bypass; first run always passes)- if source not in {TriggerSource.MANUAL, TriggerSource.JOURNAL} and self._last_run_ts is not None:+ if (+ source not in {TriggerSource.MANUAL, TriggerSource.JOURNAL}+ and self._last_run_ts is not None+ ):elapsed = time.monotonic() - self._last_run_tsif elapsed < self._config.cooldown_seconds:return SchedulerResult(diff --git a/jarvis/missions/critic/prompts.py b/jarvis/missions/critic/prompts.pyindex c7995a24e4..fb17395f99 100644--- a/jarvis/missions/critic/prompts.py+++ b/jarvis/missions/critic/prompts.py@@ -167,6 +167,13 @@ believed the log and approved with confidence=0.9):"(command succeeded; no output captured)" for a silent detached spawn). Judgewhether the launched command satisfies the user's goal. A diff containing atleast one such block is NOT empty — do NOT veto it under the empty-diff rule.+- EXCEPTION — verified MCP/external action: a+ `diff --external-action-evidence` block, marked `# verified-external-action`,+ is ALSO ground truth and is NOT an empty diff. The runtime emits this block+ only after correlating a namespaced MCP `tool_use` with its non-errored+ `tool_result`; a bare call or worker prose cannot create it. Judge the tool and+ returned result against the requested external action. A block containing this+ marker is NOT empty — do not veto it under the empty-diff rule.- A log entry like `toolSummary: write tool was called` is NOT evidencethat any file was actually created — it is the worker's self-report.Evidence strings that only cite `log_line:N` without a correspondingdiff --git a/jarvis/missions/critic/runner.py b/jarvis/missions/critic/runner.pyindex 834c5038a0..a393e0ec45 100644--- a/jarvis/missions/critic/runner.py+++ b/jarvis/missions/critic/runner.py@@ -36,6 +36,7 @@ from pydantic import ValidationErrorfrom ..stream_evidence import (capability_refusal_answer,diff_has_action_evidence,+ extract_verified_external_actions,informational_file_answer,is_informational_request,readonly_answer,@@ -60,6 +61,22 @@ from .verdict import (logger = logging.getLogger(__name__)+def _render_external_action_evidence(worker_log: str) -> str:+ """Render correlated successful MCP results as a critic evidence block."""+ actions = extract_verified_external_actions(worker_log)+ if not actions:+ return ""+ lines = [+ "diff --external-action-evidence",+ "# verified-external-action",+ ]+ for name, result in actions:+ compact = " ".join(result.split())+ lines.append(f"+tool: {name}")+ lines.append(f"+result: {compact}")+ return "\n".join(lines)++# ---------------------------------------------------------------------------# Capability-Honesty Gate (Layer 3c of the Capability Coupling spec)# ---------------------------------------------------------------------------@@ -616,6 +633,15 @@ class CriticRunner:# record — the "claims success without invoking any tool"# hallucination (BUG-LIVE-02, mission_019e2c18): there is nothing on# disk for the LLM to grade, so log text alone cannot earn an approve.+ # Correlated, non-errored MCP results are observable external-action+ # evidence even though they leave no worktree file. Surface them through+ # the same diff-like channel used for verified command/desktop actions.+ # A bare tool call or prose claim never renders this block.+ if not worker_diff.strip():+ external_action_diff = _render_external_action_evidence(worker_log)+ if external_action_diff:+ worker_diff = external_action_diff+_defer_empty_diff_to_llm = bool(_extract_tool_call_evidence(worker_log))if not worker_diff.strip() and is_informational_request(mission_prompt):diff --git a/jarvis/missions/init.py b/jarvis/missions/init.pyindex 41d7ba5569..c28501ad09 100644--- a/jarvis/missions/init.py+++ b/jarvis/missions/init.py@@ -19,6 +19,7 @@ Startup order per plan §"Block D":Each step is optional via a cfg flag. Default values come from jarvis.toml[phase6.*] (see the section defaults there)."""+from __future__ import annotationsimport asyncio@@ -50,6 +51,10 @@ from .worker_runtime.provider_map import (CODEX_SUBAGENT_SLUGS,)from .workers.api_agent_worker import ApiAgentWorker+from .workers.capabilities import (+ WorkerCapabilityInventory,+ restricted_worker_app_commands,+)from .workers.claude_direct_worker import ClaudeDirectWorkerfrom .workers.codex_direct_worker import CodexDirectWorkerfrom .workers.gemini_worker import GeminiWorker@@ -99,9 +104,7 @@ def _default_job_factory() -> Any:return WindowsJobObject()-def _resolve_readback_mode(- *, tts_speak_fn: object | None, speech_bus: object | None-) -> str:+def _resolve_readback_mode(*, tts_speak_fn: object | None, speech_bus: object | None) -> str:"""Decide which mission voice-readback path is active — exactly one.Starting BOTH the MissionVoiceListener (direct-TTS callback) and the@@ -132,9 +135,7 @@ def _worker_mcp_relevance_filter_enabled() -> bool:from jarvis.core.config import load_configcfg = load_config()- return bool(- getattr(cfg.brain.routing, "worker_mcp_relevance_filter", True)- )+ return bool(getattr(cfg.brain.routing, "worker_mcp_relevance_filter", True))except Exception: # noqa: BLE001 — missing/blip config => keep the gate ONreturn True@@ -171,8 +172,9 @@ def _live_server_tools(): # noqa: ANN202if name:tools.append({"name": f"{sid}/{name}", "description": desc})out[sid] = tools- except Exception: # noqa: BLE001 — gate must never break mission dispatch+ except Exception: # noqa: BLE001 - gate must never break mission dispatchlogger.debug("missions: live MCP tool gather failed", exc_info=True)+ return Nonereturn out@@ -212,6 +214,9 @@ def _filter_servers_by_relevance( # noqa: ANN201from jarvis.marketplace.plugin_relevance import plugin_is_relevanttool_lookup = server_tools if server_tools is not None else _live_server_tools()+ if tool_lookup is None:+ logger.warning("missions: MCP relevance evidence unavailable - full export")+ return serverskept: dict[str, dict] = {}dropped: list[str] = []for sid, entry in servers.items():@@ -227,13 +232,12 @@ def _filter_servers_by_relevance( # noqa: ANN201if dropped:logger.info("missions: MCP relevance filter kept %s, dropped %s (off-task)",- sorted(kept), sorted(dropped),+ sorted(kept),+ sorted(dropped),)return keptexcept Exception as exc: # noqa: BLE001 — never break dispatch; full export- logger.debug(- "missions: MCP relevance filter failed (%s) — full export", exc- )+ logger.debug("missions: MCP relevance filter failed (%s) — full export", exc)return servers@@ -289,9 +293,7 @@ def _assemble_worker_mcp_servers( # noqa: ANN201logger.warning("missions: mcp.json -> claude config failed (%s)", exc)extra = {}- servers = assemble_claude_mcp_servers(- load_catalog(), store, extra_servers=extra- )+ servers = assemble_claude_mcp_servers(load_catalog(), store, extra_servers=extra)return _filter_servers_by_relevance(servers,task_text=task_text,@@ -307,9 +309,15 @@ def _assemble_worker_mcp_servers( # noqa: ANN201return {}-def _select_subagent_worker_kind(- sub_jarvis_provider: str | None, step_model: str-) -> str:+def _assemble_worker_capability_inventory(task_text: str) -> WorkerCapabilityInventory:+ """Build the one restricted capability snapshot shared by all backends."""+ return WorkerCapabilityInventory.build(+ mcp_servers=_assemble_worker_mcp_servers(task_text=task_text),+ app_commands=restricted_worker_app_commands(),+ )+++def _select_subagent_worker_kind(sub_jarvis_provider: str | None, step_model: str) -> str:"""Pure routing decision for the Heavy-Task subagent worker.Returns one of ``"claude_direct"`` | ``"codex_direct"`` | ``"antigravity"``@@ -441,8 +449,7 @@ def _live_subagent_provider(boot_snapshot: str | None) -> str | None:return primaryexcept Exception as exc: # noqa: BLE001logger.debug(- "missions: live subagent re-resolve failed (%s) — using boot "- "snapshot %r",+ "missions: live subagent re-resolve failed (%s) — using boot snapshot %r",exc,boot_snapshot,)@@ -478,9 +485,7 @@ def _claude_cli_auth_viable() -> bool:if live_claude_oauth_status() == "valid":token = read_live_claude_oauth_token()- return not claude_auth_dead(- current_fingerprint=credential_fingerprint(token)- )+ return not claude_auth_dead(current_fingerprint=credential_fingerprint(token))try:from jarvis.core.config import get_secret@@ -519,9 +524,7 @@ def _api_key_family_viable(provider: str) -> bool:from jarvis.api_family_quota_state import api_family_in_cooldownfrom jarvis.claude_auth_state import claude_auth_dead, credential_fingerprint- if api_family_in_cooldown(- provider, current_fingerprint=credential_fingerprint(key)- ):+ if api_family_in_cooldown(provider, current_fingerprint=credential_fingerprint(key)):return Falseif provider == "claude-api":if key.startswith("sk-ant-oat"):@@ -549,11 +552,7 @@ def reachable_worker_families() -> list[str]:from jarvis.codex_quota_state import codex_in_quota_cooldownfrom jarvis.missions.workers.codex_direct_worker import _codex_oauth_available- if (- _codex_oauth_available()- and not codex_needs_reauth()- and not codex_in_quota_cooldown()- ):+ if _codex_oauth_available() and not codex_needs_reauth() and not codex_in_quota_cooldown():families.append("codex")from jarvis.missions.workers.api_agent_worker import supports_api_agent_worker@@ -563,7 +562,10 @@ def reachable_worker_families() -> list[str]:return families-def _cross_family_last_resort_worker(task_text: str) -> Any | None:+def _cross_family_last_resort_worker(+ task_text: str,+ capability_inventory: WorkerCapabilityInventory | None = None,+) -> Any | None:"""The key-aware, cross-family LAST-resort heavy worker (open-source AP-22/23).The legacy last resort was always ``ClaudeDirectWorker`` — the Claude Max@@ -594,13 +596,13 @@ def _cross_family_last_resort_worker(task_text: str) -> Any | None:# Auth-aware since 2026-07-06: binary presence alone picked a claude CLI# whose OAuth token had expired in place, and every mission 401'd while# a healthy codex login + OpenRouter key sat unused (AP-22).+ inventory = capability_inventory or _assemble_worker_capability_inventory(task_text)+from jarvis.missions.workers.claude_direct_worker import _resolve_claude_binaryif _resolve_claude_binary() is not None:if _claude_cli_auth_viable():- return ClaudeDirectWorker(- mcp_servers=_assemble_worker_mcp_servers(task_text=task_text)- )+ return ClaudeDirectWorker(capability_inventory=inventory)logger.warning("Mission worker: the `claude` CLI is installed but its auth is ""dead/expired (no live OAuth login, no classic Anthropic key) — "@@ -620,7 +622,7 @@ def _cross_family_last_resort_worker(task_text: str) -> Any | None:if _codex_oauth_available() and not codex_needs_reauth():if not codex_in_quota_cooldown():- return CodexDirectWorker()+ return CodexDirectWorker(capability_inventory=inventory)logger.warning("Mission worker: the codex ChatGPT plan is in quota cooldown ""(usage cap hit this session) — skipping codex and crossing "@@ -640,11 +642,15 @@ def _cross_family_last_resort_worker(task_text: str) -> Any | None:"(open-source AP-22/AP-23, single-key downloader).",prov,)- return ApiAgentWorker(prov)+ return ApiAgentWorker(prov, capability_inventory=inventory)return None-def _resolve_api_agent_worker(provider: str, task_text: str) -> Any:+def _resolve_api_agent_worker(+ provider: str,+ task_text: str,+ capability_inventory: WorkerCapabilityInventory | None = None,+) -> Any:"""Worker for an ``api_agent``-kind subagent provider (openai / openrouter /nvidia run ON their OWN provider via the in-process ApiAgentWorker).@@ -655,6 +661,7 @@ def _resolve_api_agent_worker(provider: str, task_text: str) -> Any:tries the user's other provider families before the honest Claude lastresort — never a guaranteed-fail worker."""+ inventory = capability_inventory or _assemble_worker_capability_inventory(task_text)try:has_key = _api_key_family_viable(provider)except Exception: # noqa: BLE001 — any resolve failure => no usable key@@ -665,20 +672,23 @@ def _resolve_api_agent_worker(provider: str, task_text: str) -> Any:"loop over the provider's own API, writes files in the worktree).",provider,)- return ApiAgentWorker(provider)+ return ApiAgentWorker(provider, capability_inventory=inventory)logger.warning("Mission worker: subagent provider %r has no API key configured, ""so it cannot run — trying the user's other provider families ""before the Claude last resort (open-source AP-22/AP-23).",provider,)- cross = _cross_family_last_resort_worker(task_text)+ cross = _cross_family_last_resort_worker(task_text, inventory)if cross is not None:return cross- return ClaudeDirectWorker(mcp_servers=_assemble_worker_mcp_servers(task_text=task_text))+ return ClaudeDirectWorker(capability_inventory=inventory)-def _resolve_codex_dead_login_worker(task_text: str) -> Any:+def _resolve_codex_dead_login_worker(+ task_text: str,+ capability_inventory: WorkerCapabilityInventory | None = None,+) -> Any:"""Worker to use when the codex ChatGPT login is flagged dead this session(``kind == "codex_direct"`` and ``codex_needs_reauth()`` is True).@@ -688,6 +698,8 @@ def _resolve_codex_dead_login_worker(task_text: str) -> Any:and crosses to another provider family when Claude itself is notreachable either (open-source AP-22/AP-23)."""+ inventory = capability_inventory or _assemble_worker_capability_inventory(task_text)+from jarvis.claude_quota_state import claude_in_quota_cooldownfrom jarvis.missions.workers.claude_direct_worker import _resolve_claude_binary@@ -697,7 +709,7 @@ def _resolve_codex_dead_login_worker(task_text: str) -> Any:"dead and no `claude` CLI binary is present, running in-process ""on the Anthropic API key.")- return ApiAgentWorker("claude-api")+ return ApiAgentWorker("claude-api", capability_inventory=inventory)claude_cli_ready = (_resolve_claude_binary() is not Noneand _claude_cli_auth_viable()@@ -710,17 +722,17 @@ def _resolve_codex_dead_login_worker(task_text: str) -> Any:"`codex login` restores it (avoids the dead-provider double ""fallback).")- return ClaudeDirectWorker(mcp_servers=_assemble_worker_mcp_servers(task_text=task_text))+ return ClaudeDirectWorker(capability_inventory=inventory)logger.warning("Mission worker: codex login is dead and Claude is not reachable ""either (no CLI auth, quota cooldown, or no Anthropic key) — ""crossing provider families instead of a guaranteed-fail worker ""(open-source AP-22/AP-23).")- cross = _cross_family_last_resort_worker(task_text)+ cross = _cross_family_last_resort_worker(task_text, inventory)if cross is not None:return cross- return ClaudeDirectWorker(mcp_servers=_assemble_worker_mcp_servers(task_text=task_text))+ return ClaudeDirectWorker(capability_inventory=inventory)async def bootstrap_missions(@@ -849,10 +861,7 @@ async def bootstrap_missions(sweep_report = await asyncio.to_thread(worktree_mgr.prune_and_sweep_leaked, max_age_hours=6.0)- if (- sweep_report.get("swept_run_dirs", 0) > 0- or sweep_report.get("errors", 0) > 0- ):+ if sweep_report.get("swept_run_dirs", 0) > 0 or sweep_report.get("errors", 0) > 0:logger.info("worktree-sweep at bootstrap: %s", sweep_report)except Exception: # noqa: BLE001logger.warning("worktree-sweep at bootstrap failed", exc_info=True)@@ -900,7 +909,8 @@ async def bootstrap_missions(except Exception as exc: # noqa: BLE001logger.warning("missions: brain config lookup failed (%s) — defaulting to "- "openclaw-backed worker routing", exc,+ "openclaw-backed worker routing",+ exc,)# B6 (open-source AP-22): no explicit sub-agent provider → default to the@@ -931,9 +941,7 @@ async def bootstrap_missions(# persisted choice instead of the frozen boot snapshot).live_provider = _live_subagent_provider(sub_jarvis_provider)- anthropic_key = get_secret(- "anthropic_api_key", env_fallback="ANTHROPIC_API_KEY"- )+ anthropic_key = get_secret("anthropic_api_key", env_fallback="ANTHROPIC_API_KEY")# Codex-as-subagent API-key path: prefer the dedicated Codex key slot# so OPENAI_API_KEY carries it (the OAuth path strips the key anyway —# see CodexDirectWorker._build_codex_env). Other subagents use the@@ -943,9 +951,7 @@ async def bootstrap_missions("codex_openai_api_key", env_fallback="OPENAI_API_KEY") or get_secret("openai_api_key", env_fallback="OPENAI_API_KEY")else:- openai_key = get_secret(- "openai_api_key", env_fallback="OPENAI_API_KEY"- )+ openai_key = get_secret("openai_api_key", env_fallback="OPENAI_API_KEY")# Antigravity (Google subscription) deliberately runs OAuth-only: a# configured Gemini API key must NOT be injected, or the CLI would# bill the key instead of the subscription login. Other subagents@@ -955,26 +961,20 @@ async def bootstrap_missions(else:gemini_key = get_secret("gemini_api_key", env_fallback="GEMINI_API_KEY"- ) or get_secret(- "google_api_key", env_fallback="GOOGLE_API_KEY"- )+ ) or get_secret("google_api_key", env_fallback="GOOGLE_API_KEY")# Grok / xAI: Jarvis stores under ``grok_api_key`` in the# credential manager (ENV fallback ``GROK_API_KEY``); we set# both XAI_API_KEY + GROK_API_KEY on the worker side so# OpenClaw (XAI_API_KEY) and any legacy SDK (GROK_API_KEY)# both find it.- xai_key = get_secret(- "grok_api_key", env_fallback="GROK_API_KEY"- ) or get_secret(+ xai_key = get_secret("grok_api_key", env_fallback="GROK_API_KEY") or get_secret("xai_api_key", env_fallback="XAI_API_KEY")- openrouter_key = get_secret(- "openrouter_api_key", env_fallback="OPENROUTER_API_KEY"- )+ openrouter_key = get_secret("openrouter_api_key", env_fallback="OPENROUTER_API_KEY")except Exception as exc: # noqa: BLE001logger.warning(- "missions: secret lookup failed (%s) — worker will hit "- "authentication_failed", exc,+ "missions: secret lookup failed (%s) — worker will hit authentication_failed",+ exc,)# Subscription-first billing for Claude (mirror of Codex's "OAuth wins,@@ -1011,7 +1011,9 @@ async def bootstrap_missions(openrouter_api_key=openrouter_key,)- def _worker_factory(step): # noqa: ANN001 — Step type local+ def _worker_factory(step): # noqa: ANN001 - Step type local+ task_text = getattr(step, "prompt", "") or ""+ capability_inventory = _assemble_worker_capability_inventory(task_text)# Worker routing post-Welle-4:## 1. If ``[brain.sub_jarvis].provider`` is set in jarvis.toml,@@ -1064,9 +1066,7 @@ async def bootstrap_missions(# kept routing every heavy mission to the ClaudeDirectWorker (Opus)# fallback for hours. Degrades to the boot snapshot on any read failure.live_provider = _live_subagent_provider(sub_jarvis_provider)- kind = _select_subagent_worker_kind(- live_provider, getattr(step, "model", "") or ""- )+ kind = _select_subagent_worker_kind(live_provider, getattr(step, "model", "") or "")if kind == "claude_direct":# B3 (open-source AP-22): an Anthropic-API-key-only user has NO `claude`# CLI binary — run the heavy worker IN-PROCESS via ApiAgentWorker on the@@ -1075,14 +1075,13 @@ async def bootstrap_missions(from jarvis.missions.workers.claude_direct_worker import (_resolve_claude_binary,)- if _resolve_claude_binary() is None and _api_key_family_viable(- "claude-api"- ):++ if _resolve_claude_binary() is None and _api_key_family_viable("claude-api"):logger.info("Mission worker -> ApiAgentWorker('claude-api'): no `claude` CLI ""binary, running in-process on the Anthropic API key.")- return ApiAgentWorker("claude-api")+ return ApiAgentWorker("claude-api", capability_inventory=capability_inventory)# Proactive quota routing (mirror of the codex_needs_reauth branch# below): if a Claude worker already proved the Max window exhausted# this session, route STRAIGHT to codex (a separate ChatGPT@@ -1109,23 +1108,19 @@ async def bootstrap_missions("quota cooldown this session — routing to codex until the ""window resets (avoids a wasted Claude probe per mission).")- return CodexDirectWorker()+ return CodexDirectWorker(capability_inventory=capability_inventory)# Open-source AP-22/AP-23: before the honest Claude last resort, try# the user's ACTUAL provider family. A fresh install whose only key is# gemini/openrouter/openai (and who never moved off the claude-api# default) has neither the `claude` binary nor an Anthropic key, so a# bare ClaudeDirectWorker here would brick the mission. The helper# probes Claude FIRST, so a host WITH Claude is unchanged.- cross = _cross_family_last_resort_worker(getattr(step, "prompt", "") or "")+ cross = _cross_family_last_resort_worker(task_text, capability_inventory)if cross is not None:return cross# Give the delegated worker the connected marketplace plugins as a# claude-cli MCP config so it can issue the plugin tool calls (AD-OE4).- return ClaudeDirectWorker(- mcp_servers=_assemble_worker_mcp_servers(- task_text=getattr(step, "prompt", "") or ""- )- )+ return ClaudeDirectWorker(capability_inventory=capability_inventory)if kind == "codex_direct":# If a codex subprocess already proved the ChatGPT login dead this# session, skip codex entirely and run on Claude Max directly (one@@ -1139,10 +1134,8 @@ async def bootstrap_missions(# AP-22/AP-23): a dead codex login must not hand back an# unconditional ClaudeDirectWorker — see# `_resolve_codex_dead_login_worker`.- return _resolve_codex_dead_login_worker(- getattr(step, "prompt", "") or ""- )- return CodexDirectWorker()+ return _resolve_codex_dead_login_worker(task_text, capability_inventory)+ return CodexDirectWorker(capability_inventory=capability_inventory)if kind == "antigravity":# "antigravity" (Google subscription): drive the official `agy` CLI# over a PTY with --dangerously-skip-permissions so it can write files@@ -1157,14 +1150,14 @@ async def bootstrap_missions("Mission worker -> GoogleCliWorker over the Google subscription ""(agy over PTY, OAuth login, no API key) — billed against Antigravity.")- return GoogleCliWorker()+ return GoogleCliWorker(capability_inventory=capability_inventory)if kind == "api_agent":# grok / openai / openrouter / nvidia: run ON the selected# provider via the in-process ApiAgentWorker — see# `_resolve_api_agent_worker` (viability-gated, cross-family# fallback, honest Claude last resort).provider = live_provider or ""- return _resolve_api_agent_worker(provider, getattr(step, "prompt", "") or "")+ return _resolve_api_agent_worker(provider, task_text, capability_inventory)if kind == "gemini":# B4 (open-source AP-22): no Gemini CLI but a Gemini API key → run the# heavy worker IN-PROCESS via ApiAgentWorker instead of failing on the@@ -1172,14 +1165,15 @@ async def bootstrap_missions(import shutilfrom jarvis.core.config import get_provider_secret- if not (- shutil.which("gemini") or shutil.which("gemini.cmd")- ) and get_provider_secret("gemini"):++ if not (shutil.which("gemini") or shutil.which("gemini.cmd")) and get_provider_secret(+ "gemini"+ ):logger.info("Mission worker -> ApiAgentWorker('gemini'): no Gemini CLI, ""running in-process on the Gemini API key.")- return ApiAgentWorker("gemini")+ return ApiAgentWorker("gemini", capability_inventory=capability_inventory)# Reached when [brain.sub_jarvis].provider == "gemini" was selected# (the user's "selected provider must run" mandate) OR, legacy, when# no provider is configured but the step model is a gemini model.@@ -1191,21 +1185,17 @@ async def bootstrap_missions("Max subscription.",getattr(step, "model", ""),)- return GeminiWorker()+ return GeminiWorker(capability_inventory=capability_inventory)# The legacy ``"subjarvis"`` kind (openclaw-claude / unknown provider /# unset default) routed to the OpenClaw subprocess worker, which was# removed (it caused the ~92% nested-claude hang; see docs/BUGS.md).# Open-source AP-22/AP-23: try the user's ACTUAL provider family before# the Claude last resort, so an openrouter/gemini/openai-only downloader# is not dead-ended on the absent `claude` binary.- cross = _cross_family_last_resort_worker(getattr(step, "prompt", "") or "")+ cross = _cross_family_last_resort_worker(task_text, capability_inventory)if cross is not None:return cross- return ClaudeDirectWorker(- mcp_servers=_assemble_worker_mcp_servers(- task_text=getattr(step, "prompt", "") or ""- )- )+ return ClaudeDirectWorker(capability_inventory=capability_inventory)kontrollierer = Kontrollierer(manager=manager,@@ -1226,9 +1216,7 @@ async def bootstrap_missions(# #6): exactly one readback path runs, else every completion is spoken# twice. The announcer wins when a speech_bus is present (production),# the listener is the direct-TTS fallback.- _readback_mode = _resolve_readback_mode(- tts_speak_fn=tts_speak_fn, speech_bus=speech_bus- )+ _readback_mode = _resolve_readback_mode(tts_speak_fn=tts_speak_fn, speech_bus=speech_bus)# Context-aware readback composer (maintainer mandate: no fixed stock# phrases). One instance shared by whichever readback path is active. Built@@ -1238,6 +1226,7 @@ async def bootstrap_missions(_readback_composer = Nonetry:from jarvis.brain.factory import build_readback_composer+_readback_composer = build_readback_composer()except Exception as exc: # noqa: BLE001logger.warning("Mission readback composer wiring skipped: %s", exc)diff --git a/jarvis/missions/stream_evidence.py b/jarvis/missions/stream_evidence.pyindex f4f788f8c7..32499e5828 100644--- a/jarvis/missions/stream_evidence.py+++ b/jarvis/missions/stream_evidence.py@@ -146,14 +146,21 @@ def _codex_item_to_claude_lines(if itype in ("mcp_tool_call", "web_search"):counter += 1tid = f"codex_{itype}_{counter}"- name = "web_search" if itype == "web_search" else str(- item.get("tool") or item.get("server") or "mcp_tool_call"- )+ if itype == "web_search":+ name = "web_search"+ else:+ server = str(item.get("server") or "mcp").strip()+ tool = str(item.get("tool") or "tool").strip()+ name = f"mcp__{server}__{tool}"excerpt = str(item.get("result") or item.get("query") or item.get("output") or "")[:_CODEX_OUTPUT_CAP]lines.append(_tool_use(name, {}, tid))- lines.append(_tool_result(tid, excerpt or "(tool completed)", is_error=False))+ status = str(item.get("status") or "completed").strip().lower()+ is_error = status in {"failed", "error", "cancelled", "canceled"}+ lines.append(+ _tool_result(tid, excerpt or "(tool completed)", is_error=is_error)+ )return lines, counterreturn lines, counter@@ -499,6 +506,61 @@ def extract_verified_commands(return tuple(credited)+def extract_verified_external_actions(+ stream_text: str, *, max_result_chars: int = 800+) -> tuple[tuple[str, str], ...]:+ """Successful MCP actions with a correlated, non-errored result frame.++ A remote action can legitimately leave no filesystem diff. It is credited+ only when the worker stream contains both a namespaced MCP ``tool_use`` and+ its matching successful ``tool_result``. A bare tool call, prose claim, or+ truncated stream is never evidence. Codex ``mcp_tool_call`` items are first+ normalised into the same paired representation as Claude workers.+ """+ stream_text = _normalize_worker_stream(stream_text)+ pending: dict[str, str] = {}+ credited: list[tuple[str, str]] = []+ seen: set[tuple[str, str]] = set()++ for raw in stream_text.splitlines():+ line = raw.strip()+ if not line:+ continue+ try:+ obj = json.loads(line)+ except (json.JSONDecodeError, ValueError):+ continue+ if not isinstance(obj, dict):+ continue+ otype = obj.get("type")+ if otype == "assistant":+ for blk in (obj.get("message", {}) or {}).get("content", []) or []:+ if not isinstance(blk, dict) or blk.get("type") != "tool_use":+ continue+ name = str(blk.get("name", "")).strip()+ tid = str(blk.get("id", "")).strip()+ is_mcp = name.startswith("mcp__") or "/" in name+ if is_mcp and tid:+ pending[tid] = name+ elif otype == "user":+ for blk in (obj.get("message", {}) or {}).get("content", []) or []:+ if not isinstance(blk, dict) or blk.get("type") != "tool_result":+ continue+ tid = str(blk.get("tool_use_id", "")).strip()+ name = pending.pop(tid, None)+ if name is None or _result_is_error(blk):+ continue+ result = _result_text(blk.get("content", "")).strip()+ if not result:+ result = "(tool completed successfully; no output captured)"+ evidence = (name, result[:max_result_chars])+ if evidence not in seen:+ seen.add(evidence)+ credited.append(evidence)++ return tuple(credited)++# Desktop/process-LAUNCH commands that produce NO file diff: the deliverable is# a running process, not a file change. Cross-platform (Win/mac/Linux). Mirrors# the git/gh command-evidence path so a diff-less "open Explorer / launch Chrome"@@ -639,6 +701,7 @@ _DIFF_ACTION_PREFIXES: tuple[str, ...] = ("diff --external-target","diff --command-evidence","diff --desktop-action-evidence",+ "diff --external-action-evidence",)@@ -1104,6 +1167,7 @@ __all__ = ["extract_stream_evidence","extract_verified_commands","extract_verified_desktop_actions",+ "extract_verified_external_actions","extract_write_targets","informational_file_answer","is_informational_request",diff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.pyindex 5fa31c177d..209200d938 100644--- a/jarvis/missions/workers/api_agent_worker.py+++ b/jarvis/missions/workers/api_agent_worker.py@@ -20,6 +20,7 @@ the only spawned processes are short-lived ``Bash`` tool subprocesses (run offthe loop via ``run_in_executor`` so the voice pipeline never blocks). Cancel ishonored cooperatively at each turn boundary."""+from __future__ import annotationsimport asyncio@@ -35,6 +36,7 @@ from typing import Any, Literalfrom jarvis.core.protocols import BrainMessage, BrainRequestfrom .api_agent_tools import WORKER_TOOL_SPECS, execute_worker_tool+from .capabilities import WorkerCapabilityInventoryfrom .stream_consumer import (ClaudeAssistantMessage,ClaudeResult,@@ -149,6 +151,7 @@ def _resolve_worker_model(provider: str, explicit: str) -> str:passreturn _DEFAULT_MODEL.get(prov, "")+_WORKER_TIMEOUT_S: float = 1200.0 # 20 min hard cap, mirrors the other workers_MAX_TURNS: int = 25_MAX_TOKENS: int = 8192@@ -205,10 +208,16 @@ class ApiAgentWorker:cli: Literal["claude"] = "claude"- def __init__(self, provider: str) -> None:+ def __init__(+ self,+ provider: str,+ *,+ capability_inventory: WorkerCapabilityInventory | None = None,+ ) -> None:self.provider = (provider or "").strip().lower()self.last_pid: int | None = Noneself.last_session_id: str | None = None+ self.capability_inventory = capability_inventory or WorkerCapabilityInventory.build()async def spawn(self,@@ -240,6 +249,7 @@ class ApiAgentWorker:model=f"{self.provider}/{resolved_model}",tools=[t["name"] for t in WORKER_TOOL_SPECS],cwd=str(worktree),+ external_capabilities=self.capability_inventory.report_for(f"api:{self.provider}"),)_emit_line(init)yield init@@ -252,8 +262,11 @@ class ApiAgentWorker:brain = _build_brain(self.provider, resolved_model)except Exception as exc: # noqa: BLE001res = ClaudeResult(- subtype="error_during_execution", is_error=True, session_id=session_id,- duration_ms=0, result=f"ApiAgentWorker init failed: {exc}",+ subtype="error_during_execution",+ is_error=True,+ session_id=session_id,+ duration_ms=0,+ result=f"ApiAgentWorker init failed: {exc}",)_emit_line(res)yield res@@ -270,7 +283,9 @@ class ApiAgentWorker:can_call_tools = Trueif not can_call_tools:res = ClaudeResult(- subtype="error_during_execution", is_error=True, session_id=session_id,+ subtype="error_during_execution",+ is_error=True,+ session_id=session_id,duration_ms=0,result=_tool_incapable_message(resolved_model, self.provider),)@@ -280,7 +295,10 @@ class ApiAgentWorker:logger.info("ApiAgentWorker[%s] spawn in-process: provider=%s model=%s cwd=%s",- worker_id, self.provider, resolved_model, worktree,+ worker_id,+ self.provider,+ resolved_model,+ worktree,)messages: list[BrainMessage] = [BrainMessage(role="user", content=prompt)]@@ -293,8 +311,10 @@ class ApiAgentWorker:for turn in range(max_turns):if time.perf_counter() - t0 > _WORKER_TIMEOUT_S:res = ClaudeResult(- subtype="error_during_execution", is_error=True,- session_id=session_id, timed_out=True,+ subtype="error_during_execution",+ is_error=True,+ session_id=session_id,+ timed_out=True,duration_ms=int((time.perf_counter() - t0) * 1000),result=f"{final_text}\n[timeout after {_WORKER_TIMEOUT_S:.0f}s]".strip(),)@@ -338,7 +358,8 @@ class ApiAgentWorker:)if turn == 0 and no_tool_endpoints:res = ClaudeResult(- subtype="error_during_execution", is_error=True,+ subtype="error_during_execution",+ is_error=True,session_id=session_id,duration_ms=int((time.perf_counter() - t0) * 1000),result=_tool_incapable_message(@@ -358,12 +379,14 @@ class ApiAgentWorker:if assistant_text:content_blocks.append({"type": "text", "text": assistant_text})for tc in tool_calls:- content_blocks.append({- "type": "tool_use",- "id": str(tc.get("id") or uuid.uuid4().hex),- "name": str(tc.get("name") or ""),- "input": tc.get("input") or {},- })+ content_blocks.append(+ {+ "type": "tool_use",+ "id": str(tc.get("id") or uuid.uuid4().hex),+ "name": str(tc.get("name") or ""),+ "input": tc.get("input") or {},+ }+ )assistant_event = ClaudeAssistantMessage(message={"role": "assistant", "content": content_blocks},session_id=session_id,@@ -385,23 +408,28 @@ class ApiAgentWorker:tool_input = block["input"] if isinstance(block["input"], dict) else {}result_text, is_error = await loop.run_in_executor(None,- lambda n=name, i=tool_input: execute_worker_tool(- n, i, worktree=worktree- ),+ lambda n=name, i=tool_input: execute_worker_tool(n, i, worktree=worktree),)if name in ("Write", "Edit") and not is_error:fp = str(tool_input.get("file_path", ""))if fp:written.append(fp)- result_blocks.append({- "type": "tool_result",- "tool_use_id": block["id"],- "content": result_text,- "is_error": is_error,- })- messages.append(BrainMessage(- role="tool", content=result_text, tool_call_id=block["id"], name=name,- ))+ result_blocks.append(+ {+ "type": "tool_result",+ "tool_use_id": block["id"],+ "content": result_text,+ "is_error": is_error,+ }+ )+ messages.append(+ BrainMessage(+ role="tool",+ content=result_text,+ tool_call_id=block["id"],+ name=name,+ )+ )user_event = ClaudeUserMessage(message={"role": "user", "content": result_blocks},@@ -413,11 +441,16 @@ class ApiAgentWorker:wall_ms = int((time.perf_counter() - t0) * 1000)summary = final_text or (f"Completed {len(written)} file change(s): {', '.join(written[:10])}"- if written else "Worker finished with no output."+ if written+ else "Worker finished with no output.")res = ClaudeResult(- subtype="success", is_error=False, session_id=session_id,- num_turns=turns, duration_ms=wall_ms, result=summary[:4000],+ subtype="success",+ is_error=False,+ session_id=session_id,+ num_turns=turns,+ duration_ms=wall_ms,+ result=summary[:4000],)# This family's key works — lift any armed cooldown immediately.from jarvis.api_family_quota_state import clear_api_family_cooldown@@ -450,11 +483,15 @@ class ApiAgentWorker:"ApiAgentWorker[%s]: provider %r key is unusable (quota/auth) ""— arming the family cooldown so the worker factory crosses ""to the next reachable key family on the retry.",- worker_id, self.provider,+ worker_id,+ self.provider,)res = ClaudeResult(- subtype="error_during_execution", is_error=True, session_id=session_id,- num_turns=turns, duration_ms=wall_ms,+ subtype="error_during_execution",+ is_error=True,+ session_id=session_id,+ num_turns=turns,+ duration_ms=wall_ms,result=f"{final_text}\n[worker error: {exc}]".strip(),)_emit_line(res)diff --git a/jarvis/missions/workers/capabilities.py b/jarvis/missions/workers/capabilities.pynew file mode 100644index 0000000000..7819401a18--- /dev/null+++ b/jarvis/missions/workers/capabilities.py@@ -0,0 +1,123 @@+"""Explicit external-capability contract shared by every mission worker.++Mission workers all receive the same restricted inventory. A backend either+consumes that inventory explicitly or reports ``unsupported``; no backend may+silently discover extra app or MCP tools from a machine-global CLI config.++Only the two app commands needed for the durable knowledge workflow are in the+initial allowlist. Spawn, review, and skill-execution commands are deliberately+absent (AP-5/AP-14).+"""++from __future__ import annotations++import json+from dataclasses import dataclass, field+from typing import Any++RESTRICTED_WORKER_APP_COMMANDS: tuple[str, ...] = (+ "session-latest-turn",+ "wiki-ingest",+)++_FORBIDDEN_RECURSIVE_NAMES = frozenset(+ {+ "dispatch-with-review",+ "dispatch_with_review",+ "multi-spawn",+ "multi_spawn",+ "run-skill",+ "run_skill",+ "spawn-worker",+ "spawn_worker",+ }+)+++@dataclass(frozen=True)+class WorkerCapabilityInventory:+ """Immutable, secret-safe-to-report inventory for one mission step.++ The serialized MCP config is excluded from ``repr`` because it can contain+ resolved OAuth tokens. Public reports expose server ids only.+ """++ _mcp_json: str = field(default="{}", repr=False)+ app_commands: tuple[str, ...] = ()++ @classmethod+ def build(+ cls,+ *,+ mcp_servers: dict[str, Any] | None = None,+ app_commands: tuple[str, ...] = (),+ ) -> WorkerCapabilityInventory:+ commands = tuple(dict.fromkeys(str(name) for name in app_commands if name))+ forbidden = _FORBIDDEN_RECURSIVE_NAMES.intersection(commands)+ if forbidden:+ raise ValueError(+ "recursive tools are forbidden in worker capability inventories: "+ + ", ".join(sorted(forbidden))+ )+ payload = json.dumps(mcp_servers or {}, ensure_ascii=False, sort_keys=True)+ return cls(_mcp_json=payload, app_commands=commands)++ @property+ def mcp_servers(self) -> dict[str, Any]:+ """Return a fresh config copy so one backend cannot mutate another's."""+ value = json.loads(self._mcp_json)+ return value if isinstance(value, dict) else {}++ @property+ def mcp_server_ids(self) -> tuple[str, ...]:+ return tuple(sorted(self.mcp_servers))++ def report_for(self, backend: str) -> dict[str, Any]:+ """Public capability report for a concrete worker backend.++ Claude CLI is currently the only backend that can consume the assembled+ Claude-format MCP config without putting resolved secrets on argv.+ App-command execution is intentionally unsupported until the worker+ broker can route it through ToolExecutor and the REST validation chain.+ """+ mcp_requested = bool(self.mcp_server_ids)+ app_requested = bool(self.app_commands)+ mcp_supported = backend == "claude-cli"+ return {+ "backend": backend,+ "mcp": {+ "status": (+ "available"+ if mcp_requested and mcp_supported+ else "unsupported"+ if mcp_requested+ else "not_requested"+ ),+ "servers": list(self.mcp_server_ids),+ },+ "app_commands": {+ "status": "unsupported" if app_requested else "not_requested",+ "commands": list(self.app_commands),+ },+ }+++def restricted_worker_app_commands() -> tuple[str, ...]:+ """Return only allowlisted commands that exist in the live registry."""+ try:+ from jarvis.commands.registry import get_command++ return tuple(+ command_id+ for command_id in RESTRICTED_WORKER_APP_COMMANDS+ if get_command(command_id) is not None+ )+ except Exception: # noqa: BLE001 - registry drift must not break missions+ return ()+++__all__ = [+ "RESTRICTED_WORKER_APP_COMMANDS",+ "WorkerCapabilityInventory",+ "restricted_worker_app_commands",+]diff --git a/jarvis/missions/workers/claude_direct_worker.py b/jarvis/missions/workers/claude_direct_worker.pyindex b4e55e88c2..e78e036577 100644--- a/jarvis/missions/workers/claude_direct_worker.py+++ b/jarvis/missions/workers/claude_direct_worker.py@@ -41,6 +41,7 @@ in the user's profile. The env-builder copies the bearer to both``ANTHROPIC_API_KEY`` and ``ANTHROPIC_OAUTH_TOKEN`` so the binary worksregardless of which env var the CLI happens to check first."""+from __future__ import annotationsimport asyncio@@ -53,7 +54,9 @@ from contextlib import suppressfrom pathlib import Pathfrom typing import Any, AsyncIterator, ClassVar, Literal+from .capabilities import WorkerCapabilityInventoryfrom .process_utils import create_worker_subprocess+from .provider_chain import _resolve_provider_chainfrom .stream_consumer import (ClaudeAssistantMessage,ClaudeResult,@@ -61,7 +64,6 @@ from .stream_consumer import (ClaudeSystemInit,ClaudeUserMessage,)-from .provider_chain import _resolve_provider_chainlogger = logging.getLogger(__name__)@@ -195,10 +197,7 @@ def _resolve_claude_model(primary: Any) -> str:providers = getattr(cfg.brain, "providers", {}) or {}pcfg = providers.get("claude-api")if pcfg is not None:- resolved = (- getattr(pcfg, "deep_model", None)- or getattr(pcfg, "model", None)- )+ resolved = getattr(pcfg, "deep_model", None) or getattr(pcfg, "model", None)if resolved:return str(resolved)return _DEFAULT_CLAUDE_MODEL@@ -250,9 +249,7 @@ def _resolve_claude_argv_prefix() -> list[str]:return [bare] if bare else ["claude"]-def _build_mcp_config_args(- config_dir: Path, mcp_servers: dict[str, Any] | None-) -> list[str]:+def _build_mcp_config_args(config_dir: Path, mcp_servers: dict[str, Any] | None) -> list[str]:"""Write the assembled MCP servers to ``config_dir`` and return claude-cliflags so the worker can call connected marketplace plugins / mcp.jsonservers.@@ -262,18 +259,16 @@ def _build_mcp_config_args(would leak the token into ``_capture_diff`` (``git add -N`` + diff), thesafety scan, and the archived ``diff.patch`` (AP-2 / AP-12).- Returns ``[]`` when there are no servers, so a plain mission is byte-for-byte- unchanged. ``--strict-mcp-config`` ensures only this config is honoured (a- stray project ``.mcp.json`` cannot inject extra servers into the worker).+ An explicit config is written even when there are no servers.+ ``--strict-mcp-config`` ensures only this inventory is honoured, so a stray+ project or machine-global MCP config cannot inject extra worker tools."""- if not mcp_servers:- return []# NOTE: this file inlines resolved plugin secrets — spawn() deletes it the# moment the subprocess exits (see _MCP_CONFIG_FILENAME). Do not move it# into the worktree (AP-2 / AP-12) and do not keep it after the run.cfg_path = Path(config_dir) / _MCP_CONFIG_FILENAMEcfg_path.write_text(- json.dumps({"mcpServers": mcp_servers}, ensure_ascii=False),+ json.dumps({"mcpServers": mcp_servers or {}}, ensure_ascii=False),encoding="utf-8",)return ["--mcp-config", str(cfg_path), "--strict-mcp-config"]@@ -290,12 +285,20 @@ class ClaudeDirectWorker:cli: ClassVar[Literal["claude", "codex", "python", "browser"]] = "claude"- def __init__(self, mcp_servers: dict[str, Any] | None = None) -> None:+ def __init__(+ self,+ mcp_servers: dict[str, Any] | None = None,+ *,+ capability_inventory: WorkerCapabilityInventory | None = None,+ ) -> None:self.last_pid: int | None = Noneself.last_session_id: str | None = None- # Assembled claude-cli ``mcpServers`` map (connected marketplace plugins- # + user mcp.json). Empty -> no MCP wiring. See jarvis.marketplace.mcp_bridge.- self._mcp_servers: dict[str, Any] = dict(mcp_servers or {})+ # The legacy mcp_servers argument is folded into the same explicit+ # inventory every backend receives.+ self.capability_inventory = capability_inventory or WorkerCapabilityInventory.build(+ mcp_servers=mcp_servers+ )+ self._mcp_servers = self.capability_inventory.mcp_serversasync def spawn(self,@@ -362,7 +365,9 @@ class ClaudeDirectWorker:"which has no direct worker (OpenClaw path removed in Welle 4) — ""running heavy work on the Claude Max OAuth backend (model=%s) ""instead of failing the mission.",- worker_id, primary.provider, claude_model,+ worker_id,+ primary.provider,+ claude_model,)session_id = resume_session_id or str(uuid.uuid4())@@ -377,10 +382,13 @@ class ClaudeDirectWorker:cmd: list[str] = [*argv_prefix,"--print",- "--output-format", "stream-json",+ "--output-format",+ "stream-json","--verbose", # required by --print + stream-json- "--permission-mode", permission_mode,- "--add-dir", str(worktree),+ "--permission-mode",+ permission_mode,+ "--add-dir",+ str(worktree),]if not force_default_model:cmd.extend(["--model", claude_model])@@ -397,11 +405,14 @@ class ClaudeDirectWorker:model=f"claude-cli/{claude_model}",tools=[],cwd=str(worktree),+ external_capabilities=self.capability_inventory.report_for("claude-cli"),)logger.info("ClaudeDirectWorker[%s] spawn: cwd=%s model=%s",- worker_id, worktree, claude_model,+ worker_id,+ worktree,+ claude_model,)# 3. Spawn the subprocess with the prompt on stdin. The helper sources@@ -439,7 +450,9 @@ class ClaudeDirectWorker:except Exception: # noqa: BLE001logger.warning("ClaudeDirectWorker[%s]: job.assign(pid=%d) failed",- worker_id, proc.pid, exc_info=True,+ worker_id,+ proc.pid,+ exc_info=True,)# Write the prompt then close stdin to signal EOF.@@ -451,7 +464,8 @@ class ClaudeDirectWorker:except (BrokenPipeError, ConnectionResetError) as exc:logger.warning("ClaudeDirectWorker[%s]: prompt stdin write failed: %s",- worker_id, exc,+ worker_id,+ exc,)# 4. Drain stdout LINE-BY-LINE so progress is observable WHILE the@@ -501,15 +515,9 @@ class ClaudeDirectWorker:f"({timeout_s + _HARDCAP_GRACE_S:.0f}s) exceeded while streaming")break- read_cap = (- remaining- if got_first_line- else min(first_output_timeout_s, remaining)- )+ read_cap = remaining if got_first_line else min(first_output_timeout_s, remaining)try:- raw = await asyncio.wait_for(- proc.stdout.readline(), timeout=read_cap- )+ raw = await asyncio.wait_for(proc.stdout.readline(), timeout=read_cap)except TimeoutError:if got_first_line:# read_cap == remaining here, so the deadline check at the@@ -549,9 +557,7 @@ class ClaudeDirectWorker:with stdout_log.open("ab") as stream_fh:stream_fh.write(raw)except OSError as exc:- logger.warning(- "ClaudeDirectWorker: stream.jsonl append failed: %s", exc- )+ logger.warning("ClaudeDirectWorker: stream.jsonl append failed: %s", exc)line = raw.decode("utf-8", errors="replace").strip()if not line:continue@@ -567,11 +573,8 @@ class ClaudeDirectWorker:cost_usd=obj.get("total_cost_usd") or obj.get("cost_usd"),num_turns=obj.get("num_turns"),session_id=obj.get("session_id") or session_id,- duration_ms=obj.get("duration_ms")- or int((time.perf_counter() - t0) * 1000),- result=obj.get("result")- or obj.get("text")- or "\n".join(text_acc),+ duration_ms=obj.get("duration_ms") or int((time.perf_counter() - t0) * 1000),+ result=obj.get("result") or obj.get("text") or "\n".join(text_acc),)continueif obj_type == "assistant":@@ -586,14 +589,10 @@ class ClaudeDirectWorker:yield ClaudeAssistantMessage(message=msg, session_id=session_id)continueif obj_type == "user":- yield ClaudeUserMessage(- message=obj.get("message", {}), session_id=session_id- )+ yield ClaudeUserMessage(message=obj.get("message", {}), session_id=session_id)continueif obj_type == "stream_event":- yield ClaudeStreamDelta(- event=obj.get("event", {}), session_id=session_id- )+ yield ClaudeStreamDelta(event=obj.get("event", {}), session_id=session_id)continue# ignore "system" events — we already emitted our synthetic init.@@ -662,8 +661,7 @@ class ClaudeDirectWorker:final_result = final_result.model_copy(update={"timed_out": True})logger.info(- "ClaudeDirectWorker[%s] done: exit=%s wall_ms=%s tool_use_seen=%s "- "session=%s",+ "ClaudeDirectWorker[%s] done: exit=%s wall_ms=%s tool_use_seen=%s session=%s",worker_id,proc.returncode,int((time.perf_counter() - t0) * 1000),@@ -693,23 +691,21 @@ class ClaudeDirectWorker:# rejection slips past and the mission fails instead of retrying on the# CLI default. (`not timed_out` above means stderr_bytes here is the# subprocess's real stderr, never the synthetic timeout message.)- stderr_text = (- stderr_bytes.decode("utf-8", errors="replace") if stderr_bytes else ""- )+ stderr_text = stderr_bytes.decode("utf-8", errors="replace") if stderr_bytes else ""if (final_result.is_errorand not timed_outand not any_tool_useand not force_default_model- and _claude_error_is_model_unavailable(- (final_result.result or "") + "\n" + stderr_text- )+ and _claude_error_is_model_unavailable((final_result.result or "") + "\n" + stderr_text)):logger.warning("ClaudeDirectWorker[%s]: model %r rejected by the CLI (%r) — ""retrying without --model so the CLI picks an accessible ""default and the mission completes.",- worker_id, claude_model, (final_result.result or "")[:160],+ worker_id,+ claude_model,+ (final_result.result or "")[:160],)async for ev in self.spawn(prompt,@@ -751,9 +747,7 @@ class ClaudeDirectWorker:final_result.is_errorand not timed_outand not any_tool_use- and _claude_error_is_auth_failure(- (final_result.result or "") + "\n" + stderr_text- )+ and _claude_error_is_auth_failure((final_result.result or "") + "\n" + stderr_text)):from jarvis.claude_auth_state import (credential_fingerprint,@@ -762,8 +756,7 @@ class ClaudeDirectWorker:mark_claude_auth_dead(fingerprint=credential_fingerprint(- env.get("CLAUDE_CODE_OAUTH_TOKEN")- or env.get("ANTHROPIC_API_KEY")+ env.get("CLAUDE_CODE_OAUTH_TOKEN") or env.get("ANTHROPIC_API_KEY")))if allow_backend_fallback:@@ -786,9 +779,12 @@ class ClaudeDirectWorker:"(ChatGPT) worker so the mission completes. Run ""`claude /login` (or save a fresh Anthropic key in the ""API-Keys view) to use Claude again.",- worker_id, (final_result.result or "")[:160],+ worker_id,+ (final_result.result or "")[:160],)- async for ev in CodexDirectWorker().spawn(+ async for ev in CodexDirectWorker(+ capability_inventory=self.capability_inventory+ ).spawn(prompt,worktree=worktree,env=env,@@ -809,7 +805,8 @@ class ClaudeDirectWorker:"login is reachable — surfacing the auth error honestly; the ""worker factory will cross to another provider family on the ""retry. Run `claude /login` to restore Claude.",- worker_id, (final_result.result or "")[:160],+ worker_id,+ (final_result.result or "")[:160],)# Claude Max quota fallback (mirror of the codex->claude direction).@@ -821,12 +818,7 @@ class ClaudeDirectWorker:# discarded, the orchestrator grades it instead), complete the# mission on the codex worker. `allow_backend_fallback=False` on the# nested spawn prevents claude->codex->claude ping-pong.- if (- allow_backend_fallback- and final_result.is_error- and not timed_out- and not any_tool_use- ):+ if allow_backend_fallback and final_result.is_error and not timed_out and not any_tool_use:from jarvis.codex_auth_state import codex_needs_reauthfrom jarvis.codex_quota_state import codex_in_quota_cooldown@@ -856,9 +848,12 @@ class ClaudeDirectWorker:"with no work delivered — falling back to the codex ""(ChatGPT) worker so the mission completes. claude ""resumes automatically once its window resets.",- worker_id, (final_result.result or "")[:160],+ worker_id,+ (final_result.result or "")[:160],)- async for ev in CodexDirectWorker().spawn(+ async for ev in CodexDirectWorker(+ capability_inventory=self.capability_inventory+ ).spawn(prompt,worktree=worktree,env=env,diff --git a/jarvis/missions/workers/codex_direct_worker.py b/jarvis/missions/workers/codex_direct_worker.pyindex 14430fb570..076c423316 100644--- a/jarvis/missions/workers/codex_direct_worker.py+++ b/jarvis/missions/workers/codex_direct_worker.py@@ -31,6 +31,7 @@ once interactively) is the canonical way to populate that file. WeNEVER write API keys here -- the user explicitly chose the ChatGPTsubscription path."""+from __future__ import annotationsimport asyncio@@ -44,6 +45,7 @@ from contextlib import suppressfrom pathlib import Pathfrom typing import Any, ClassVar, Literal+from .capabilities import WorkerCapabilityInventoryfrom .process_utils import create_worker_subprocess, resolve_node_executablefrom .stream_consumer import (ClaudeAssistantMessage,@@ -139,9 +141,7 @@ def _resolve_codex_argv_prefix() -> list[str]:cli_dir = Path(cli).resolve().parent# npm shim layout: ``<npm-root>/codex.cmd`` →# ``<npm-root>/node_modules/@openai/codex/bin/codex.js``.- candidate = (- cli_dir / "node_modules" / "@openai" / "codex" / "bin" / "codex.js"- )+ candidate = cli_dir / "node_modules" / "@openai" / "codex" / "bin" / "codex.js"if candidate.is_file():return [node, str(candidate)]return [_resolve_codex_binary() or "codex"]@@ -187,9 +187,13 @@ def _build_codex_env(env: dict[str, str], *, oauth_available: bool) -> dict[str,# normalisation converts them to empty string so codex falls back to# the user's CLI default (configured under ~/.codex/config.toml or# whatever the ChatGPT subscription exposes today).-_CLAUDE_MODEL_ALIASES: frozenset[str] = frozenset({- "sonnet", "opus", "haiku",-})+_CLAUDE_MODEL_ALIASES: frozenset[str] = frozenset(+ {+ "sonnet",+ "opus",+ "haiku",+ }+)def _normalize_model_for_codex(model: str | None) -> str:@@ -236,20 +240,19 @@ def _build_codex_direct_cmd("exec","--json","--skip-git-repo-check",- # Welle 6 (2026-05-18 live debug): worker keeps the user's- # ~/.codex/config.toml so the default sandbox + tool registry- # apply. The Cloudflare MCP plugin errors loudly in stderr- # when its OAuth token is expired, but the worker still- # completes the turn successfully (file_write + turn.completed).- # The Critic path strips user config because the critic's- # long prompt + plugin-bootstrap race actually does swallow- # the agent_message frame -- worker doesn't.- "--sandbox", sandbox,- "-c", f"approval_policy={approval_policy}",+ # Auth still comes from CODEX_HOME, but mission capabilities must never+ # come from the user's machine-global config. Explicit unsupported MCP+ # inventory is safer than silently inheriting unrelated plugins.+ "--ignore-user-config",+ "--sandbox",+ sandbox,+ "-c",+ f"approval_policy={approval_policy}",# Cap reasoning effort for SPEED, overriding the user's interactive# config (often "xhigh" -> ~7 min/run). A CLI `-c` override wins over# config.toml. See _MISSION_REASONING_EFFORT (live mission 019ec742).- "-c", f"model_reasoning_effort={_MISSION_REASONING_EFFORT}",+ "-c",+ f"model_reasoning_effort={_MISSION_REASONING_EFFORT}",# Enable web search so research / current-events missions can produce# SOURCED work instead of fabricating it. Without it the worker has no# live data, invents current events (GPT-5.5, a 2026 AI Agent Index),@@ -260,7 +263,8 @@ def _build_codex_direct_cmd(# current data inside the workspace-write sandbox WITHOUT opening raw# network access, so this is the targeted capability, not a blast-radius# network grant.- "-c", "tools.web_search=true",+ "-c",+ "tools.web_search=true",# D9 recursion guard at the codex level. A mission worker IS the# sub-agent — it must NEVER use codex's native multi-agent collaboration# tools (spawn_agent / wait) to spawn a NESTED codex agent and block on@@ -272,9 +276,12 @@ def _build_codex_direct_cmd(# off here. `--disable <FEATURE>` == `-c features.<name>=false`;# multi_agent is `stable`/on-by-default, multi_agent_v2 is the# in-development successor (future-proofing).- "--disable", "multi_agent",- "--disable", "multi_agent_v2",- "--add-dir", str(worktree),+ "--disable",+ "multi_agent",+ "--disable",+ "multi_agent_v2",+ "--add-dir",+ str(worktree),]if model:cmd.extend(["--model", model])@@ -384,10 +391,15 @@ class CodexDirectWorker:cli: ClassVar[Literal["claude", "codex", "python", "browser"]] = "codex"- def __init__(self) -> None:+ def __init__(+ self,+ *,+ capability_inventory: WorkerCapabilityInventory | None = None,+ ) -> None:self.last_pid: int | None = Noneself.last_session_id: str | None = Noneself.last_thread_id: str | None = None+ self.capability_inventory = capability_inventory or WorkerCapabilityInventory.build()async def spawn(self,@@ -399,9 +411,9 @@ class CodexDirectWorker:worker_id: str,log_dir: Path,model: str = "",- allowed_tools: str = "", # unused -- codex has its own toolset- permission_mode: str = "", # unused- max_turns: int = 20, # unused -- codex turn cap is internal+ allowed_tools: str = "", # unused -- codex has its own toolset+ permission_mode: str = "", # unused+ max_turns: int = 20, # unused -- codex turn cap is internalresume_session_id: str | None = None,extra_args: tuple[str, ...] = (),timeout_s: float = _DEFAULT_TIMEOUT_S,@@ -445,11 +457,15 @@ class CodexDirectWorker:model=f"codex-cli/{model or 'default'}",tools=[],cwd=str(worktree),+ external_capabilities=self.capability_inventory.report_for("codex-cli"),)logger.info("CodexDirectWorker[%s] spawn: cwd=%s model=%s argv=%s",- worker_id, worktree, model or "<default>", cmd,+ worker_id,+ worktree,+ model or "<default>",+ cmd,)# The helper sources the Windows creation flags itself and degrades@@ -482,7 +498,9 @@ class CodexDirectWorker:except Exception: # noqa: BLE001logger.warning("CodexDirectWorker[%s]: job.assign(pid=%d) failed",- worker_id, proc.pid, exc_info=True,+ worker_id,+ proc.pid,+ exc_info=True,)# Write the prompt to stdin then close to signal EOF.@@ -494,7 +512,8 @@ class CodexDirectWorker:except (BrokenPipeError, ConnectionResetError) as exc:logger.warning("CodexDirectWorker[%s]: prompt stdin write failed: %s",- worker_id, exc,+ worker_id,+ exc,)# Live line-by-line streaming (2026-06-10 root-cause fix, missions@@ -552,15 +571,9 @@ class CodexDirectWorker:f"({timeout_s + _HARDCAP_GRACE_S:.0f}s) exceeded while streaming")break- read_cap = (- remaining- if got_first_line- else min(first_output_timeout_s, remaining)- )+ read_cap = remaining if got_first_line else min(first_output_timeout_s, remaining)try:- raw = await asyncio.wait_for(- proc.stdout.readline(), timeout=read_cap- )+ raw = await asyncio.wait_for(proc.stdout.readline(), timeout=read_cap)except TimeoutError:if got_first_line:# read_cap == remaining here, so the deadline check at the@@ -597,7 +610,8 @@ class CodexDirectWorker:stream_fh.write(raw)except OSError as exc:logger.warning(- "CodexDirectWorker: stream.jsonl append failed: %s", exc,+ "CodexDirectWorker: stream.jsonl append failed: %s",+ exc,)line = raw.decode("utf-8", errors="replace").strip()if not line:@@ -639,18 +653,17 @@ class CodexDirectWorker:yield ClaudeAssistantMessage(message={"role": "assistant",- "content": [{- "type": "tool_use",- "name": (- "Write" if item_type == "file_change"- else "Bash"- ),- "input": (- item.get("changes", [{}])[0]- if item_type == "file_change"- else {"command": item.get("command", "")}- ),- }],+ "content": [+ {+ "type": "tool_use",+ "name": ("Write" if item_type == "file_change" else "Bash"),+ "input": (+ item.get("changes", [{}])[0]+ if item_type == "file_change"+ else {"command": item.get("command", "")}+ ),+ }+ ],},session_id=session_id,)@@ -715,11 +728,11 @@ class CodexDirectWorker:# claude result drive the outcome; the git diff is captured after._err = terminal_message or ""_auth_dead = (- terminal_kind == "error" and not any_tool_use- and _codex_error_is_auth_expired(_err)+ terminal_kind == "error" and not any_tool_use and _codex_error_is_auth_expired(_err))_usage_capped = (- terminal_kind == "error" and not any_tool_use+ terminal_kind == "error"+ and not any_tool_useand not _auth_deadand _codex_error_is_usage_limited(_err))@@ -766,13 +779,15 @@ class CodexDirectWorker:"CodexDirectWorker[%s]: codex %s (%r) — falling back to the ""Claude Max OAuth worker so the mission completes. %s",worker_id,- "ChatGPT login expired" if _auth_dead- else "usage/rate limit hit",+ "ChatGPT login expired" if _auth_dead else "usage/rate limit hit",_err[:160],- "Run `codex login` to use codex again." if _auth_dead+ "Run `codex login` to use codex again."+ if _auth_deadelse "codex resumes automatically once the cap resets.",)- async for ev in ClaudeDirectWorker().spawn(+ async for ev in ClaudeDirectWorker(+ capability_inventory=self.capability_inventory+ ).spawn(prompt,worktree=worktree,env=env,@@ -794,8 +809,7 @@ class CodexDirectWorker:"is not auth-viable — surfacing the error honestly; the worker ""factory will cross to another provider family on the retry.",worker_id,- "ChatGPT login expired" if _auth_dead- else "usage/rate limit hit",+ "ChatGPT login expired" if _auth_dead else "usage/rate limit hit",_err[:160],)@@ -820,10 +834,13 @@ class CodexDirectWorker:)logger.info(- "CodexDirectWorker[%s] done: exit=%s wall_ms=%s tool_use_seen=%s "- "thread=%s tokens=%s",- worker_id, exit_code, wall_ms, any_tool_use,- self.last_thread_id, tokens_used,+ "CodexDirectWorker[%s] done: exit=%s wall_ms=%s tool_use_seen=%s thread=%s tokens=%s",+ worker_id,+ exit_code,+ wall_ms,+ any_tool_use,+ self.last_thread_id,+ tokens_used,)yield finaldiff --git a/jarvis/missions/workers/gemini_worker.py b/jarvis/missions/workers/gemini_worker.pyindex 27922d8903..158b7a78a1 100644--- a/jarvis/missions/workers/gemini_worker.py+++ b/jarvis/missions/workers/gemini_worker.py@@ -1,4 +1,4 @@-"""GeminiWorker — wrapt `gemini -p ... --yolo` als Phase-6-Worker-Subprocess.+"""GeminiWorker - wrap ``gemini -p ... --yolo`` as a Phase-6 worker subprocess.Driven by the Gemini CLI (installed via `npm install -g @google/gemini-cli`,resolved from PATH at runtime). Lets a mission honor the brain provider the@@ -25,24 +25,28 @@ Spawn discipline:helper owns the Win32 creationflags (incl. CREATE_BREAKAWAY_FROM_JOB so theper-mission Job Object can assign the tree) AND sets start_new_session=Trueon POSIX so the worker forms its own killable process group (H3).-- `env=...` strikt aus `build_worker_env` (Whitelist-only); we expect+- ``env=...`` comes strictly from ``build_worker_env`` (allowlist only); we expectGEMINI_API_KEY / GOOGLE_API_KEY to be injected by the caller.- `cwd=worktree` — Gemini CLI writes/reads files relative to cwd, sohello.py-style tasks land inside the git worktree and theKontrollierer's `_capture_diff` picks them up (`git add -N .` + `gitdiff HEAD`)."""+from __future__ import annotationsimport asyncio+import jsonimport loggingimport shutilimport timeimport uuid+from collections.abc import AsyncIteratorfrom contextlib import suppressfrom pathlib import Path-from typing import Any, AsyncIterator, Literal+from typing import Any, Literal+from .capabilities import WorkerCapabilityInventoryfrom .process_utils import create_worker_subprocessfrom .stream_consumer import ClaudeResult, ClaudeSystemInit@@ -64,6 +68,28 @@ _QUOTA_BLOCKED_MARKERS: tuple[str, ...] = (_FALLBACK_MODEL: str = "gemini-3-flash-preview"+def _build_isolated_gemini_env(+ env: dict[str, str], *, log_dir: Path+) -> tuple[dict[str, str], Path, str]:+ """Apply a highest-precedence restricted config without hiding CLI auth."""+ settings_path = log_dir / ".jarvis-gemini-system-settings.json"+ no_mcp_server = f"jarvis-no-mcp-{uuid.uuid4().hex}"+ settings_path.write_text(+ json.dumps(+ {+ "hooksConfig": {"enabled": False},+ "mcp": {"allowed": [no_mcp_server]},+ "security": {"allowedExtensions": ["(?!)"]},+ "skills": {"enabled": False},+ }+ ),+ encoding="utf-8",+ )+ restricted = dict(env)+ restricted["GEMINI_CLI_SYSTEM_SETTINGS_PATH"] = str(settings_path)+ return restricted, settings_path, no_mcp_server++def _stderr_signals_quota_block(stderr_bytes: bytes) -> bool:"""True if the CLI stderr indicates the Frontier model is unavailable(rolling-window 429 quota or 403 access denial). Used to decide whether@@ -83,11 +109,9 @@ def _resolve_gemini_argv_prefix(*, bundle_finder: Any = None) -> list[str]:`asyncio.create_subprocess_exec` makes cmd.exe re-parse the fullargv with batch tokenizer rules, and that tokenizer treats `<`,`>`, `&`, `|`, `^`, `%` as metacharacters. Embedding a JSON- schema (which contains `<`) in `--prompt` then causes- CreateProcess to fail with `Das System kann die angegebene Datei # i18n-allow (quotes the literal OS error string)- nicht finden` (the literal Win32 error text on a German-locale # i18n-allow (quotes the literal OS error string)- machine — English: "The system cannot find the file specified") # i18n-allow (quotes the literal OS error string)- long before the model is ever invoked — verified live 2026-05-13.+ schema (which contains `<`) in `--prompt` then causes CreateProcess+ to fail with the localized Win32 "file not found" error long before+ the model is invoked - verified live 2026-05-13.Skipping the .cmd wrapper entirely by invoking `node ...gemini.js`directly avoids the second-stage parser and lets any payload@@ -105,10 +129,7 @@ def _resolve_gemini_argv_prefix(*, bundle_finder: Any = None) -> list[str]:if not cli:continuecli_dir = Path(cli).resolve().parent- candidate = (- cli_dir / "node_modules" / "@google" / "gemini-cli"- / "bundle" / "gemini.js"- )+ candidate = cli_dir / "node_modules" / "@google" / "gemini-cli" / "bundle" / "gemini.js"if candidate.is_file():return [node, str(candidate)]@@ -247,9 +268,14 @@ class GeminiWorker:cli: Literal["claude"] = "claude"- def __init__(self) -> None:+ def __init__(+ self,+ *,+ capability_inventory: WorkerCapabilityInventory | None = None,+ ) -> None:self.last_pid: int | None = Noneself.last_session_id: str | None = None+ self.capability_inventory = capability_inventory or WorkerCapabilityInventory.build()async def spawn(self,@@ -275,7 +301,7 @@ class GeminiWorker:NOT extracted from stream events — `_capture_diff(worktree)`runs `git diff` after this generator exits."""- log_dir.mkdir(parents=True, exist_ok=True)+ log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240stdout_log = log_dir / "stream.jsonl"stderr_log = log_dir / "stderr.log"@@ -291,7 +317,8 @@ class GeminiWorker:effective_model = _resolve_gemini_model(model)cmd = _build_gemini_cmd(- prompt, model=effective_model,+ prompt,+ model=effective_model,yolo=(permission_mode == "yolo"),extra_args=extra_args,)@@ -308,11 +335,21 @@ class GeminiWorker:model=f"gemini/{effective_model}",tools=[],cwd=str(worktree),+ external_capabilities=self.capability_inventory.report_for("gemini-cli"),)+ (+ env_for_gemini,+ restricted_settings,+ no_mcp_server,+ ) = _build_isolated_gemini_env(env, log_dir=log_dir)+ cmd.extend(["--allowed-mcp-server-names", no_mcp_server])+logger.info("GeminiWorker[%s] spawn: cwd=%s model=%s yolo=%s",- worker_id, worktree, effective_model,+ worker_id,+ worktree,+ effective_model,permission_mode == "yolo",)@@ -329,7 +366,9 @@ class GeminiWorker:# create_subprocess_exec, which would leave the worker in the# orchestrator's process group off Windows (H3).proc_local = await create_worker_subprocess(- spawn_cmd, cwd=str(worktree), env=env,+ spawn_cmd,+ cwd=str(worktree),+ env=env_for_gemini,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,)@@ -339,17 +378,17 @@ class GeminiWorker:except Exception: # noqa: BLE001logger.warning("GeminiWorker[%s]: job.assign(pid=%d) failed",- worker_id, proc_local.pid, exc_info=True,+ worker_id,+ proc_local.pid,+ exc_info=True,)# 1200 s (20 min) hard cap — raised from 600 s so complex tasks can# finish (user mandate 2026-06-09). The "timeout" substring in the# stderr below still flags is_timeout to the orchestrator, which then# grades the on-disk diff instead of discarding it.try:- out, err = await asyncio.wait_for(- proc_local.communicate(), timeout=1200.0- )- except asyncio.TimeoutError:+ out, err = await asyncio.wait_for(proc_local.communicate(), timeout=1200.0)+ except TimeoutError:with suppress(ProcessLookupError):proc_local.kill()# Audit-2 H3 (2026-05-17): always wait() after kill() so the@@ -357,9 +396,7 @@ class GeminiWorker:with suppress(Exception):await asyncio.wait_for(proc_local.wait(), timeout=5.0)out, err = b"", b"GeminiWorker: subprocess wait_for timeout (1200s)"- exit_local = (- proc_local.returncode if proc_local.returncode is not None else -1- )+ exit_local = proc_local.returncode if proc_local.returncode is not None else -1return out, err, exit_localt0 = time.perf_counter()@@ -380,13 +417,17 @@ class GeminiWorker:):logger.warning("GeminiWorker[%s]: %s returned 429/quota — retrying on %s",- worker_id, effective_model, _FALLBACK_MODEL,+ worker_id,+ effective_model,+ _FALLBACK_MODEL,)fallback_cmd = _build_gemini_cmd(- prompt, model=_FALLBACK_MODEL,+ prompt,+ model=_FALLBACK_MODEL,yolo=(permission_mode == "yolo"),extra_args=extra_args,)+ fallback_cmd.extend(["--allowed-mcp-server-names", no_mcp_server])effective_model = _FALLBACK_MODELstdout_bytes, stderr_bytes, exit_code = await _spawn_once(fallback_cmd)@@ -395,6 +436,8 @@ class GeminiWorker:stdout_log.write_bytes(stdout_bytes)with suppress(OSError):stderr_log.write_bytes(stderr_bytes)+ with suppress(OSError):+ restricted_settings.unlink(missing_ok=True)wall_ms = int((time.perf_counter() - t0) * 1000)is_error = exit_code != 0@@ -407,10 +450,7 @@ class GeminiWorker:result_text = stdout_bytes.decode("utf-8", errors="replace")if is_error and stderr_bytes:tail = stderr_bytes.decode("utf-8", errors="replace")[-300:]- result_text = (- (result_text or "")- + f"\n[stderr-tail]\n{tail}"- )+ result_text = (result_text or "") + f"\n[stderr-tail]\n{tail}"yield ClaudeResult(subtype="success" if not is_error else "error_during_execution",diff --git a/jarvis/missions/workers/google_cli_worker.py b/jarvis/missions/workers/google_cli_worker.pyindex 5b1a8b6b07..a2875dbef4 100644--- a/jarvis/missions/workers/google_cli_worker.py+++ b/jarvis/missions/workers/google_cli_worker.py@@ -22,6 +22,7 @@ and the child PID is assigned to the per-mission Job Object via ``on_spawn`` sothe kernel reaps the tree on cancel/timeout/crash (Windows). Google ToS: only theofficial binary is driven; the OAuth token is never read into our own client."""+from __future__ import annotationsimport asyncio@@ -45,6 +46,7 @@ from jarvis.google_cli.isolated_home import (from jarvis.google_cli.pty_runner import repair_agy_path, run_cli_over_ptyfrom jarvis.google_cli.resolver import resolve_google_cli+from .capabilities import WorkerCapabilityInventoryfrom .gemini_worker import GeminiWorkerfrom .stream_consumer import ClaudeResult, ClaudeSystemInit@@ -89,9 +91,12 @@ def _build_agy_worker_argv(exe: str, prompt: str, worktree: Path) -> list[str]:safe_prompt = " ".join(prompt.split())return [exe,- "--print", safe_prompt,- "--add-dir", str(worktree),- "--print-timeout", f"{int(_WORKER_TIMEOUT_S)}s",+ "--print",+ safe_prompt,+ "--add-dir",+ str(worktree),+ "--print-timeout",+ f"{int(_WORKER_TIMEOUT_S)}s","--dangerously-skip-permissions",]@@ -122,10 +127,15 @@ class GoogleCliWorker:cli: Literal["claude"] = "claude"- def __init__(self) -> None:+ def __init__(+ self,+ *,+ capability_inventory: WorkerCapabilityInventory | None = None,+ ) -> None:self.last_pid: int | None = Noneself.last_session_id: str | None = None- self._gemini_fallback = GeminiWorker()+ self.capability_inventory = capability_inventory or WorkerCapabilityInventory.build()+ self._gemini_fallback = GeminiWorker(capability_inventory=self.capability_inventory)async def spawn(self,@@ -150,7 +160,11 @@ class GoogleCliWorker:if cli is None:yield ClaudeSystemInit(- session_id=session_id, model="antigravity/none", tools=[], cwd=str(worktree)+ session_id=session_id,+ model="antigravity/none",+ tools=[],+ cwd=str(worktree),+ external_capabilities=self.capability_inventory.report_for("google-cli"),)yield ClaudeResult(subtype="error_during_execution",@@ -207,11 +221,16 @@ class GoogleCliWorker:agy_env = _build_agy_worker_env(env)yield ClaudeSystemInit(- session_id=session_id, model="antigravity/agy", tools=[], cwd=str(worktree)+ session_id=session_id,+ model="antigravity/agy",+ tools=[],+ cwd=str(worktree),+ external_capabilities=self.capability_inventory.report_for("google-cli"),)logger.info("GoogleCliWorker[%s] spawn agy over PTY: cwd=%s (Google subscription, OAuth)",- worker_id, worktree,+ worker_id,+ worktree,)loop = asyncio.get_running_loop()@@ -222,7 +241,9 @@ class GoogleCliWorker:job.assign(pid)except Exception: # noqa: BLE001logger.warning(- "GoogleCliWorker[%s]: job.assign(pid=%s) failed", worker_id, pid,+ "GoogleCliWorker[%s]: job.assign(pid=%s) failed",+ worker_id,+ pid,exc_info=True,)@@ -250,7 +271,10 @@ class GoogleCliWorker:text = f"{text}\n[timeout after {_WORKER_TIMEOUT_S:.0f}s]".strip()logger.info("GoogleCliWorker[%s] agy done: error=%s %dms text=%d chars",- worker_id, is_error, wall_ms, len(result.text),+ worker_id,+ is_error,+ wall_ms,+ len(result.text),)yield ClaudeResult(subtype="success" if not is_error else "error_during_execution",diff --git a/jarvis/missions/workers/stream_consumer.py b/jarvis/missions/workers/stream_consumer.pyindex 41b74f7148..c01c5fa345 100644--- a/jarvis/missions/workers/stream_consumer.py+++ b/jarvis/missions/workers/stream_consumer.py@@ -21,6 +21,7 @@ Codex `--json` is simpler: a flat `type` discriminatorFrozen + extra='ignore': CLI output may add fields without us crashing —we only remember what we know."""+from __future__ import annotationsimport asyncio@@ -66,6 +67,7 @@ class ClaudeSystemInit(_ClaudeBase):model: str | None = Nonetools: list[str] = Field(default_factory=list)cwd: str | None = None+ external_capabilities: dict[str, Any] = Field(default_factory=dict)class ClaudeApiRetry(_ClaudeBase):@@ -306,8 +308,12 @@ def parse_codex_stream_json(line: str) -> Any | None:if isinstance(type_, str) and type_.startswith("item"):# Collapse all item.* sub-variants under CodexItem.return CodexItem.model_validate(- {"type": type_ if type_ in CodexItem.model_fields["type"].annotation.__args__ else "item", # type: ignore[union-attr]- "payload": {k: v for k, v in data.items() if k != "type"}}+ {+ "type": type_+ if type_ in CodexItem.model_fields["type"].annotation.__args__+ else "item", # type: ignore[union-attr]+ "payload": {k: v for k, v in data.items() if k != "type"},+ })except ValidationError as exc:logger.debug("parse_codex_stream_json: validation fail: %s", exc)@@ -378,5 +384,3 @@ async def read_ndjson_stream(finally:if tee_handle is not None:tee_handle.close()--diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.pyindex 207ff4c9bd..e480a3af01 100644--- a/jarvis/plugins/realtime/gemini_live.py+++ b/jarvis/plugins/realtime/gemini_live.py@@ -43,6 +43,13 @@ class _ProviderEvent:class _GeminiLiveSession:+ supports_tool_updates = False+ creates_responses_automatically = True+ # The ordered Live stream emits old output before ``interrupted`` and the+ # next input transcript. Output observed after that boundary belongs to+ # the new automatic response generation.+ isolates_response_generations = True+def __init__(self,*,@@ -140,14 +147,19 @@ class _GeminiLiveSession:)async def update_session(- self, *, instructions: str | None = None, language: str | None = None+ self,+ *,+ instructions: str | None = None,+ language: str | None = None,+ tools: tuple[dict[str, Any], ...] | None = None,) -> None:# Gemini fixes system instructions at connect time. The orchestrator# reconnects on a substantive language change in a later session.- del instructions, language+ del instructions, language, tools- async def request_response(self) -> None:+ async def request_response(self, *, required_tool: str | None = None) -> None:# Gemini Live creates a response automatically at the VAD turn boundary.+ del required_toolreturn Noneasync def send_text(self, text: str) -> None:diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex 708b50d10c..aca3ceda90 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -114,6 +114,10 @@ def _session_payload(cfg: Any) -> dict[str, Any]:class _OpenAIRealtimeSession:+ supports_tool_updates = True+ creates_responses_automatically = False+ isolates_response_generations = True+def __init__(self,*,@@ -244,16 +248,36 @@ class _OpenAIRealtimeSession:yield _ProviderEvent(type="error", error=_error_message(event))async def update_session(- self, *, instructions: str | None = None, language: str | None = None+ self,+ *,+ instructions: str | None = None,+ language: str | None = None,+ tools: tuple[dict[str, Any], ...] | None = None,) -> None:del language # Input transcription stays provider-inferred and multilingual.+ update: dict[str, Any] = {"type": "realtime"}if instructions is not None:- await self._conn.session.update(- session={"type": "realtime", "instructions": instructions}- )-- async def request_response(self) -> None:- await self._create_response()+ update["instructions"] = instructions+ if tools is not None:+ update["tools"] = [+ {+ "type": "function",+ "name": str(tool.get("name", "")),+ "description": str(tool.get("description", "")),+ "parameters": tool.get("parameters") or {"type": "object"},+ }+ for tool in tools+ if isinstance(tool, dict) and tool.get("name")+ ]+ update["tool_choice"] = "auto" if update["tools"] else "none"+ if len(update) > 1:+ await self._conn.session.update(session=update)++ async def request_response(self, *, required_tool: str | None = None) -> None:+ tool_choice: Any = None+ if required_tool:+ tool_choice = {"type": "function", "name": str(required_tool)}+ await self._create_response(tool_choice=tool_choice)async def send_text(self, text: str) -> None:"""Add one trusted text turn and ask the live model for audio output."""@@ -275,6 +299,16 @@ class _OpenAIRealtimeSession:)async def interrupt(self) -> None:+ # Invalidate the cancelled generation before awaiting the wire. Late+ # audio/transcript/done events keep their old response id and are then+ # suppressed by ``_response_is_accepted`` even if they race the next+ # user turn.+ self._pending_response_markers.clear()+ self._accepted_response_ids.clear()+ self._response_had_tool_calls = False+ self._tool_response_done_seen = False+ self._pending_tool_call_ids.clear()+ self._last_item_id = ""await self._conn.response.cancel()async def send_tool_result(@@ -302,7 +336,7 @@ class _OpenAIRealtimeSession:self._tool_response_done_seen = Falseawait self._create_response()- async def _create_response(self, *, tool_choice: str | None = None) -> None:+ async def _create_response(self, *, tool_choice: Any = None) -> None:marker = uuid4().hexself._pending_response_markers.add(marker)response: dict[str, Any] = {diff --git a/jarvis/plugins/tool/wiki_ingest.py b/jarvis/plugins/tool/wiki_ingest.pyindex 4411499d7e..701cb5b843 100644--- a/jarvis/plugins/tool/wiki_ingest.py+++ b/jarvis/plugins/tool/wiki_ingest.py@@ -6,7 +6,7 @@ Why this tool exists alongside the voice-bridge-----------------------------------------------:class:`jarvis.memory.wiki.voice_bridge.VoiceFactBridge` already pushesvoice-spoken facts to the wiki via two heuristics: the *ack path* (brain-reply contains "notiert"/"vermerkt"/...) and the *aggressive path*+reply acknowledges a saved fact) and the *aggressive path*(every user turn >= ``min_user_chars`` is curator-filtered).Heuristics drift. When the brain consciously decides "this is worth@@ -25,48 +25,18 @@ adds nothing beyond the dispatch.Risk tier and confirmation---------------------------Marked ``safe``. The write surface is protected by ``AtomicWriter``+Marked ``monitor``. The write surface is protected by ``AtomicWriter``(AP-3 pre-validate, AP-4 backup) and the curator's salience filter; thetool itself has no destructive scope. Bypass-confirmation matches``wiki-recall`` so the brain can call both freely."""from __future__ import annotations-import logging-from typing import Any, Callable+from collections.abc import Callable+from typing import Anyfrom jarvis.core.protocols import ToolResult--log = logging.getLogger(__name__)---# Minimum length to even attempt an ingest. Below this the curator's-# salience filter would almost certainly drop the content and we save-# the LLM call. Mirrors the ``_MIN_ACK_USER_CHARS`` constant in-# voice_bridge.py.-_MIN_INGEST_CHARS: int = 12--# Hard cap on accepted content length. Wiki pages are KB-sized; anyone-# trying to push a megabyte through here is either confused or-# malicious. ``WikiCuratorLLM`` truncates internally too, but failing-# fast is cleaner.-_MAX_INGEST_CHARS: int = 32_000---def _record_write_health(- ok: bool, *, pages: list[str], error: str | None, source: str,-) -> None:- """Record a wiki-ingest write outcome on the health singleton (spec A5).-- Recording must never raise into the write path (AP-9) — a health-write- failure here would invert the honest-not-silent design.- """- try:- from jarvis.memory.wiki.health import health-- health.record_write(ok, pages=pages, error=error, source=source)- except Exception: # noqa: BLE001 — health recording must never break ingest- log.debug("wiki-ingest: health.record_write failed", exc_info=True)+from jarvis.memory.wiki.ingest_service import ingest_wiki_textclass WikiIngestTool:@@ -76,7 +46,7 @@ class WikiIngestTool:description: str = ("Store a fact, observation, or summary in the user's long-term Obsidian ""wiki. Use this when the user explicitly asks you to remember something "- "('merk dir', 'speichere', 'remember that …') or when you have finished "+ "('remember that', 'save this') or when you have finished ""a substantial piece of work whose outcome should outlive this session. ""The curator decides which pages to touch — give it the content as one ""self-contained block."@@ -86,7 +56,7 @@ class WikiIngestTool:# markdown pages under the vault; that is the precise definition of# `monitor` per the project's risk-tier taxonomy -- run without a# user prompt (anti-confirmation-fatigue) but log every invocation- # for audit. `ask` would nag the user on every "merk dir das"; `safe`+ # for audit. `ask` would nag the user on every memory request; `safe`# falsely implied no side effects.risk_tier: str = "monitor"schema: dict[str, Any] = {@@ -137,114 +107,12 @@ class WikiIngestTool:async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:text = str(args.get("text", "")).strip()source = str(args.get("source") or "tool:wiki-ingest").strip() or "tool:wiki-ingest"-- if not text:- return ToolResult(success=False, output="", error="missing 'text' argument")-- if len(text) < _MIN_INGEST_CHARS:- return ToolResult(- success=False,- output="",- error=(- f"text too short ({len(text)} chars; min {_MIN_INGEST_CHARS}). "- "Pass a full self-contained statement, not a single word."- ),- )-- if len(text) > _MAX_INGEST_CHARS:- return ToolResult(- success=False,- output="",- error=(- f"text too long ({len(text)} chars; max {_MAX_INGEST_CHARS}). "- "Split into multiple ingest calls."- ),- )-curator = self._resolve_curator()- if curator is None:- log.warning("wiki-ingest: no live WikiCurator registered (bootstrap not run?)")- _record_write_health(- False,- pages=[],- error="wiki integration not bootstrapped",- source="tool:wiki-ingest",- )- return ToolResult(- success=False,- output="",- error="wiki integration not bootstrapped",- )-- # Privacy: text is logged at DEBUG only (full content), source at INFO.- log.debug("wiki-ingest: source=%s len=%d body=%r", source, len(text), text)- log.info("wiki-ingest: ingesting %d chars (source=%s)", len(text), source)-- try:- result = await curator.ingest(text, source)- except Exception as exc: # noqa: BLE001- log.warning("wiki-ingest: curator.ingest raised %s", exc)- _record_write_health(- False,- pages=[],- error=f"curator ingest failed: {exc}",- source="tool:wiki-ingest",- )- return ToolResult(- success=False,- output="",- error=f"curator ingest failed: {exc}",- )-- applied = list(getattr(result, "applied", []) or [])- skipped = list(getattr(result, "skipped_due_to_recent_edit", []) or [])- failed = list(getattr(result, "failed_validation", []) or [])-- _record_write_health(- bool(applied),- pages=[str(p) for p in applied],- error=None if applied else "no pages written",- source="tool:wiki-ingest",+ outcome = await ingest_wiki_text(+ curator=curator,+ text=text,+ source=source,)-- if not applied and not skipped and not failed:- # Curator judged the content not salient. The old success=True here made- # the model tell users "stored" when NOTHING was written (fresh-machine- # forensics Bug 12/18) -- a no-op is a failure from the caller's intent.- log.info("wiki-ingest: curator returned no updates (salience filter)")- return ToolResult(- success=False,- output="",- error=(- "nothing was stored: the curator judged the content not salient "- "enough for the wiki. Tell the user the wiki was NOT updated; if "- "they explicitly asked to store this, apologize and suggest they "- "add it via the Wiki view instead."- ),- )-- summary_lines = [- f"Wiki ingest done (source={source}):",- f"- applied: {len(applied)}",- ]- if skipped:- summary_lines.append(f"- skipped (recent user edit): {len(skipped)}")- if failed:- summary_lines.append(f"- failed validation (rolled back): {len(failed)}")- if applied:- summary_lines.append("Pages touched:")- for page_path in applied[:10]:- # ``applied`` is a list of Path objects per WriteResult contract.- try:- summary_lines.append(f" - {page_path.name}")- except AttributeError:- summary_lines.append(f" - {page_path}")-- log.info(- "wiki-ingest: applied=%d skipped=%d failed=%d",- len(applied),- len(skipped),- len(failed),- )-- return ToolResult(success=True, output="\n".join(summary_lines))+ if not outcome.success:+ return ToolResult(success=False, output="", error=outcome.error)+ return ToolResult(success=True, output=outcome.render_summary())diff --git a/jarvis/realtime/protocol.py b/jarvis/realtime/protocol.pyindex c9a5450c4b..f4edecd285 100644--- a/jarvis/realtime/protocol.py+++ b/jarvis/realtime/protocol.py@@ -66,15 +66,21 @@ class RealtimeSession(Protocol):"""A live duplex handle (one connection)."""session_id: str+ creates_responses_automatically: bool+ isolates_response_generations: boolasync def send_audio(self, chunk: AudioChunk) -> None: ...def receive(self) -> AsyncIterator[RealtimeEvent]: ...async def update_session(- self, *, instructions: str | None = None, language: str | None = None+ self,+ *,+ instructions: str | None = None,+ language: str | None = None,+ tools: tuple[dict[str, Any], ...] | None = None,) -> None: ...- async def request_response(self) -> None: ...+ async def request_response(self, *, required_tool: str | None = None) -> None: ...async def send_text(self, text: str) -> None: ...async def truncate(self, audio_end_ms: int) -> None: ...async def interrupt(self) -> None: ...diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 9725b9bcdf..14f77d6841 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -10,11 +10,13 @@ from __future__ import annotationsimport asyncioimport logging-from dataclasses import dataclass+import re+import unicodedata+from dataclasses import dataclass, fieldfrom typing import Anyfrom uuid import uuid4-from jarvis.core.protocols import AudioChunk+from jarvis.core.protocols import AudioChunk, BrainMessagefrom jarvis.core.redact import safe_previewfrom jarvis.core.turn_language import resolve_output_languagefrom jarvis.realtime.audio import StreamingPcm16Resampler@@ -51,14 +53,19 @@ _END_CALL_DECLARATION: dict[str, Any] = {# the router turn itself offloads heavy work to background missions, so a# turn that exceeds this is stuck, not busy._DELEGATE_TIMEOUT_S = 90.0+_DELEGATE_INPUT_BOUNDARY_WAIT_S = 3.0+_DELEGATE_NATIVE_BOUNDARY_WAIT_S = 1.0+_DELEGATE_HISTORY_MAX_MESSAGES = 8+_DELEGATE_HISTORY_MAX_CHARS = 1_200_DELEGATE_DECLARATION: dict[str, Any] = {"name": "jarvis_action","description": ("Execute an action for the user through the Jarvis action system: ""open apps or views, change settings, control the computer, manage "- "files, start background research or coding missions, and any other "- "operation on the user's system. Also call this to relay the user's "- "answer to a pending confirmation question."+ "files, start background research or coding missions, read or write "+ "the user's private Wiki memory, and inspect the current MCP, CLI, "+ "tool, integration, configuration, or system state. Also call this "+ "to relay the user's answer to a pending confirmation question."),"parameters": {"type": "object",@@ -75,16 +82,107 @@ _DELEGATE_ROLE_DIRECTIVE = ("You have ONE action function: jarvis_action. It hands the user's spoken ""request to the Jarvis action system, which can open apps and views, ""change settings, control the computer, manage files and windows, and "- "start background research or coding missions. Whenever the user asks "- "you to DO something on their computer or in the Jarvis app, call "- "jarvis_action — never claim you cannot act, and never invent an "- "outcome. The function returns spoken_reply: deliver that content to the "- "user in your own voice, in the conversation language, without reading "- "JSON. If spoken_reply asks a confirmation question, ask the user and "- "call jarvis_action again with their answer. Answer pure knowledge and "- "chat questions yourself, without the function. Use end_call only when "- "the user says goodbye."+ "start background research or coding missions. The Jarvis orchestrator "+ "automatically handles every Wiki read or write, every question about the "+ "user's private or personal memory, and every question about current "+ "Jarvis settings, installed tools, MCPs, CLIs, integrations, connections, "+ "capabilities, or system state. Do not answer or call a function for those "+ "turns; wait for the trusted result that the orchestrator injects. For any "+ "other request to act on the computer or Jarvis app, call jarvis_action. "+ "Answer only general world knowledge and ordinary social chat yourself. Never "+ "claim that an action or mission was started, completed, saved, opened, "+ "or changed unless the latest successful jarvis_action result explicitly "+ "supports that claim. A promise or intention is not a result. The function "+ "returns spoken_reply: deliver that content to the user in your own voice, "+ "in the conversation language, without reading JSON. If spoken_reply asks "+ "a confirmation question, ask the user and call jarvis_action again with "+ "their answer. Use end_call only when the user says goodbye.")+_DELEGATE_REQUIRED_DIRECTIVE = (+ "The Jarvis orchestrator is handling this current turn deterministically. "+ "Do not answer, do not call a function, and do not promise an outcome. Wait "+ "for the trusted action result that the orchestrator will inject."+)++# Speech-intent vocabulary only. These expressions decide when the live model+# must cross the local evidence boundary instead of answering from its weights.+_WIKI_REFERENCE_RE = re.compile(r"\bwiki(?:[\s-]?system)?\b")+_PERSONAL_REFERENCE_RE = re.compile(+ r"\b(?:my|mine|about\s+me|remember\s+me|mein\w*|mir|u(?:e)?ber\s+mich|"+ r"mi|mis|sobre\s+mi)\b" # i18n-allow: multilingual speech-input vocabulary+)+_PERSONAL_KNOWLEDGE_RE = re.compile(+ r"\b(?:who|what|when|where|how|remember\w*|know\w*|favorite\w*|"+ r"birthday\w*|friend\w*|address\w*|name\w*|wer|was|wann|wo|wie|"+ r"erinner\w*|weiss\w*|liebling\w*|geburtstag\w*|freund\w*|adresse\w*|"+ r"quien|que|cuando|donde|como|recuerd\w*|sab\w*|favorit\w*|"+ r"cumplean\w*|amig\w*|nombre\w*)\b" # i18n-allow: multilingual speech-input vocabulary+)+_LOCAL_STATE_RE = re.compile(+ r"\b(?:mcp\w*|cli\w*|command[\s-]?line|tool\w*|werkzeug\w*|"+ r"integration\w*|connector\w*|plugin\w*|setting\w*|einstellung\w*|" # i18n-allow: German speech-input vocabulary+ r"configuration\w*|konfiguration\w*|config\w*|api[\s-]?key\w*|"+ r"system[\s-]?status|capabilit\w*|faehigkeit\w*|installed\w*|"+ r"installiert\w*|connected\w*|verbunden\w*|herramient\w*|ajuste\w*|" # i18n-allow: multilingual speech-input vocabulary+ r"configuracion\w*|integracion\w*|conectad\w*|instalad\w*|capacidad\w*|"+ r"clave\w*)\b" # i18n-allow: multilingual speech-input vocabulary+)+_ACTION_VERB_RE = re.compile(+ r"\b(?:open\w*|close\w*|start\w*|spawn\w*|create\w*|write\w*|save\w*|"+ r"add\w*|change\w*|set\w*|restart\w*|install\w*|connect\w*|delete\w*|"+ r"move\w*|send\w*|run\w*|build\w*|research\w*|o(?:e)?ffn\w*|schliess\w*|"+ r"erstell\w*|schreib\w*|speicher\w*|eintrag\w*|a(?:e)?nder\w*|stell\w*|" # i18n-allow: German speech-input vocabulary+ r"installier\w*|verbind\w*|lo(?:e)?sch\w*|verschieb\w*|schick\w*|fu(?:e)?hr\w*|"+ r"bau\w*|recherchier\w*|abre\w*|cierra\w*|inicia\w*|crea\w*|"+ r"escrib\w*|guarda\w*|cambia\w*|instala\w*|conecta\w*|elimina\w*|"+ r"envia\w*|ejecuta\w*)\b" # i18n-allow: multilingual speech-input vocabulary+)+_ACTION_TARGET_RE = re.compile(+ r"\b(?:app\w*|view\w*|window\w*|computer\w*|file\w*|folder\w*|"+ r"agent\w*|mission\w*|background\w*|transcript\w*|message\w*|that|this|it|"+ r"ansicht\w*|fenster\w*|datei\w*|ordner\w*|hintergrund\w*|"+ r"transkription\w*|nachricht\w*|das|dies\w*|es|aplicacion\w*|" # i18n-allow: multilingual speech-input vocabulary+ r"ventana\w*|archivo\w*|carpeta\w*|agente\w*|mision\w*|"+ r"transcripcion\w*|mensaje\w*|eso|esto)\b" # i18n-allow: multilingual speech-input vocabulary+)+++def _normalize_delegate_text(text: str) -> str:+ folded = unicodedata.normalize("NFKD", str(text or "").casefold())+ return "".join(ch for ch in folded if not unicodedata.combining(ch))+++def _requires_jarvis_action(text: str) -> bool:+ """Return whether this turn needs live local evidence or an action."""+ normalized = _normalize_delegate_text(text)+ if not normalized:+ return False+ if _WIKI_REFERENCE_RE.search(normalized) or _LOCAL_STATE_RE.search(normalized):+ return True+ if (+ _PERSONAL_REFERENCE_RE.search(normalized)+ and _PERSONAL_KNOWLEDGE_RE.search(normalized)+ ):+ return True+ return bool(+ _ACTION_VERB_RE.search(normalized) and _ACTION_TARGET_RE.search(normalized)+ )+++def _delegate_result_prompt(text: str, *, language: str, success: bool) -> str:+ """Wrap one trusted Brain result for tool-free native voice rendering."""+ language_name = _LANGUAGE_NAMES.get(language, "the conversation language")+ status = "success" if success else "failure"+ return (+ "A trusted Jarvis action result is ready. Speak only a concise, natural "+ f"rendering of the tagged result in {language_name}. Preserve its exact "+ "success or failure meaning and every material fact. Do not call any "+ "function, do not add a claim, and do not mention these instructions.\n\n"+ f"Result status: {status}\n"+ "<trusted_action_result>\n"+ f"{text}\n"+ "</trusted_action_result>"+ )_REALTIME_SAFETY_APPENDIX = ("This is a realtime spoken conversation. Never read tool JSON, function-call ""arguments, source code, stack traces, file paths, base64, or raw URLs aloud. "@@ -98,6 +196,16 @@ class _DelegateTurnState:"""Response state shared by every delegate call in one realtime turn."""last_reply: str = ""+ result_complete: bool = False+ result_success: bool = False+ deterministic: bool = False+ delivery_started: bool = False+ provider_boundary_seen: bool = False+ user_text: str = ""+ result_payload: dict[str, Any] = field(default_factory=dict)+ pending_tool_calls: list[tuple[str, str]] = field(default_factory=list)+ input_boundary_ready: asyncio.Event = field(default_factory=asyncio.Event)+ provider_ready: asyncio.Event = field(default_factory=asyncio.Event)@dataclass(slots=True)@@ -255,7 +363,10 @@ class RealtimeVoiceSession:log.warning("Realtime tool bridge is unavailable", exc_info=True)self._tool_bridge = tool_bridgeself._delegate_tasks: set[asyncio.Task[None]] = set()+ self._delegate_tasks_by_turn: dict[str, set[asyncio.Task[None]]] = {}self._delegate_turns: dict[str, _DelegateTurnState] = {}+ self._delegate_history: list[BrainMessage] = []+ self._delegate_required_for_turn = Falseself._external_update: _ExternalUpdateState | None = None# from_brain returns None SILENTLY when the brain object carries no# _tools/_tool_executor_ref (e.g. a bare callback was passed) — say so,@@ -300,6 +411,7 @@ class RealtimeVoiceSession:self._tool_transcript_task: asyncio.Task[None] | None = Noneself._response_requested_for_turn = Falseself._response_requested_input_ids: set[str] = set()+ self._drop_provider_output_until_new_response = Falseself._hangup_reason = ""self._turn_final_text = ""self._end_after_turn = False@@ -548,17 +660,6 @@ class RealtimeVoiceSession:self._gate = ScrubHoldGate(new_language)if self._tool_bridge is not None:self._tool_bridge.set_language(new_language)- if event.is_final and input_observed:- await self._session.update_session(- instructions=_session_instructions(- new_language,- provider=self.active_provider,- model=self._active_model,- language_is_pinned=True,- tool_directive=self._tool_directive(),- ),- language=new_language,- )if input_observed:mark_phase(LatencyPhase.REALTIME_INPUT_COMMITTED)if transcript:@@ -569,6 +670,53 @@ class RealtimeVoiceSession:).strip()elif not self._user_transcript_parts:self._last_user_text = transcript+ if event.is_final and input_observed:+ if self._delegate_enabled and self._last_user_text:+ self._delegate_required_for_turn = (+ self._delegate_required_for_turn+ or _requires_jarvis_action(self._last_user_text)+ )+ refresh_tools = getattr(+ self._tool_bridge, "refresh_from_source", None+ )+ tools_changed = bool(+ callable(refresh_tools) and refresh_tools()+ )+ update_kwargs: dict[str, Any] = {+ "instructions": _session_instructions(+ new_language,+ provider=self.active_provider,+ model=self._active_model,+ language_is_pinned=True,+ tool_directive=self._tool_directive(+ delegate_required=self._delegate_required_for_turn,+ ),+ ),+ "language": new_language,+ }+ if tools_changed:+ update_kwargs["tools"] = self._declared_tools()+ if not bool(+ getattr(+ self._session,+ "supports_tool_updates",+ False,+ )+ ):+ log.warning(+ "realtime[%s] direct tools changed, but %s "+ "cannot update declarations until the next "+ "session; removed tools are denied immediately",+ self.session_id,+ self.active_provider,+ )+ try:+ await self._session.update_session(**update_kwargs)+ except TypeError:+ # Compatibility with third-party adapters built+ # against the older update-session protocol.+ update_kwargs.pop("tools", None)+ await self._session.update_session(**update_kwargs)if self._tool_bridge is not None and event.is_final and transcript:await self._tool_bridge.handle_user_transcript(self._last_user_text@@ -626,16 +774,42 @@ class RealtimeVoiceSession:await self._reject_untranscribed_tool_call(pending_event)+ if (+ event.is_final+ and input_observed+ and self._delegate_required_for_turn+ ):+ self._start_deterministic_delegate(self._last_user_text)if (event.is_finaland input_observedand not self._response_requested_for_turn):- await self._session.request_response()+ if not self._delegate_required_for_turn:+ try:+ await self._session.request_response(+ required_tool=None+ )+ except TypeError:+ # Compatibility with third-party realtime adapters+ # built against the older no-argument protocol.+ await self._session.request_response()+ if bool(+ getattr(+ self._session,+ "isolates_response_generations",+ False,+ )+ ):+ self._drop_provider_output_until_new_response = Falseself._response_requested_for_turn = Trueif input_item_id:self._response_requested_input_ids.add(input_item_id)elif event.type == "output_transcript_delta" and event.text:+ if self._must_withhold_provider_output():+ self._cancel_release_task()+ self._gate.drain()+ continueawait self._ensure_turn_started()mark_phase(LatencyPhase.REALTIME_FIRST_TRANSCRIPT)display = await self._gate.feed_transcript(event.text)@@ -660,6 +834,10 @@ class RealtimeVoiceSession:for chunk in self._gate.release_available():await self._emit_audio(chunk)elif event.type == "audio_delta" and event.audio is not None:+ if self._must_withhold_provider_output():+ self._cancel_release_task()+ self._gate.drain()+ continueawait self._ensure_turn_started()mark_phase(LatencyPhase.REALTIME_FIRST_AUDIO)self._output_active = True@@ -697,6 +875,33 @@ class RealtimeVoiceSession:self._pending_tool_events = []for pending_event in pending:await self._reject_untranscribed_tool_call(pending_event)+ delegate_state = self._delegate_turns.get(self._turn_id)+ hold_for_delegate = bool(+ delegate_state is not None+ and (+ self._turn_has_pending_delegate(self._turn_id)+ or (+ delegate_state.deterministic+ and not delegate_state.delivery_started+ )+ )+ )+ if hold_for_delegate and delegate_state is not None:+ self._cancel_release_task()+ self._gate.drain()+ delegate_state.provider_boundary_seen = True+ delegate_state.input_boundary_ready.set()+ delegate_state.provider_ready.set()+ self._output_transcript.clear()+ self._output_active = False+ self._output_samples_sent = 0+ log.debug(+ "realtime[%s] held provider turn_complete for "+ "delegate turn %s",+ self.session_id,+ self._turn_id,+ )+ continueself._cancel_release_task()for chunk in self._gate.release_available():await self._emit_audio(chunk)@@ -745,6 +950,9 @@ class RealtimeVoiceSession:async def _release_after_lookahead(self) -> None:try:await asyncio.sleep(_TRANSCRIPT_LOOKAHEAD_S)+ if self._must_withhold_provider_output():+ self._gate.drain()+ returnfor chunk in self._gate.release_available():await self._emit_audio(chunk)except asyncio.CancelledError:@@ -852,6 +1060,7 @@ class RealtimeVoiceSession:async def _begin_user_speech_turn(self) -> None:"""Close an interrupted reply before the next transcript opens a turn."""+ self._drop_provider_output_until_new_response = Trueif self._turn_id and self._turn_has_activity():await self._publish_turn_completed()# Do not open the next persisted turn on VAD alone. A cancelled provider@@ -883,6 +1092,9 @@ class RealtimeVoiceSession:answer = "".join(self._output_transcript).strip()delegate_state = self._delegate_turns.pop(self._turn_id, None)external_update = self._external_update+ response_text = answer or (+ delegate_state.last_reply if delegate_state is not None else ""+ )if self._bus is not None:try:from jarvis.core.events import (@@ -916,9 +1128,6 @@ class RealtimeVoiceSession:# the one public event for a delegated turn. When the realtime# model emits no transcript, retain the completed delegate reply# as a non-empty record while VoiceTurnCompleted stays literal.- response_text = answer or (- delegate_state.last_reply if delegate_state is not None else ""- )if answer or delegate_state is not None:await self._bus.publish(ResponseGenerated(@@ -944,9 +1153,33 @@ class RealtimeVoiceSession:)except Exception: # noqa: BLE001, S110pass+ if external_update is None:+ self._remember_delegate_turn(self._last_user_text, response_text)self._external_update = Noneself._reset_turn_tracking()+ def _remember_delegate_turn(self, user_text: str, assistant_text: str) -> None:+ """Keep only this live session's bounded context for later delegation."""++ def _bounded(text: str) -> str:+ cleaned = str(text or "").strip()+ if len(cleaned) <= _DELEGATE_HISTORY_MAX_CHARS:+ return cleaned+ half = _DELEGATE_HISTORY_MAX_CHARS // 2+ return f"{cleaned[:half]} … {cleaned[-half:]}"++ user = _bounded(user_text)+ assistant = _bounded(assistant_text)+ if user:+ self._delegate_history.append(BrainMessage(role="user", content=user))+ if assistant:+ self._delegate_history.append(+ BrainMessage(role="assistant", content=assistant)+ )+ self._delegate_history = self._delegate_history[+ -_DELEGATE_HISTORY_MAX_MESSAGES:+ ]+def _reset_turn_tracking(self) -> None:self._turn_id = ""self._last_user_text = ""@@ -955,6 +1188,7 @@ class RealtimeVoiceSession:self._output_transcript.clear()self._executed_tool_names.clear()self._turn_final_text = ""+ self._delegate_required_for_turn = Falsedef _declared_tools(self) -> tuple[dict[str, Any], ...]:if self._delegate_enabled:@@ -963,13 +1197,70 @@ class RealtimeVoiceSession:return (*self._tool_bridge.declarations, _END_CALL_DECLARATION)return (_END_CALL_DECLARATION,)- def _tool_directive(self) -> str:+ def _tool_directive(self, *, delegate_required: bool = False) -> str:if self._delegate_enabled:+ if delegate_required:+ return f"{_DELEGATE_ROLE_DIRECTIVE}\n\n{_DELEGATE_REQUIRED_DIRECTIVE}"return _DELEGATE_ROLE_DIRECTIVEif self._tool_bridge is not None:return _TOOL_ROLE_DIRECTIVEreturn ""+ def _delegate_delivery_started(self) -> bool:+ state = self._delegate_turns.get(self._turn_id)+ return bool(+ state is not None+ and state.result_complete+ and state.delivery_started+ )++ def _must_withhold_delegate_output(self) -> bool:+ return bool(+ self._delegate_required_for_turn+ and not self._delegate_delivery_started()+ )++ def _must_withhold_provider_output(self) -> bool:+ """Drop untrusted output during delegation and after barge-in."""+ return bool(+ self._drop_provider_output_until_new_response+ or self._must_withhold_delegate_output()+ )++ def _track_delegate_task(+ self, turn_id: str, task: asyncio.Task[None]+ ) -> None:+ self._delegate_tasks.add(task)+ turn_tasks = self._delegate_tasks_by_turn.setdefault(turn_id, set())+ turn_tasks.add(task)++ def _discard(done: asyncio.Task[None]) -> None:+ self._delegate_tasks.discard(done)+ tracked = self._delegate_tasks_by_turn.get(turn_id)+ if tracked is None:+ return+ tracked.discard(done)+ if not tracked:+ self._delegate_tasks_by_turn.pop(turn_id, None)++ task.add_done_callback(_discard)++ def _turn_has_pending_delegate(self, turn_id: str) -> bool:+ return any(+ not task.done()+ for task in self._delegate_tasks_by_turn.get(turn_id, ())+ )++ def _delegate_turn_is_active(+ self, turn_id: str, turn_state: _DelegateTurnState+ ) -> bool:+ """Return whether a late delegate result still belongs to this turn."""+ return bool(+ turn_id+ and self._turn_id == turn_id+ and self._delegate_turns.get(turn_id) is turn_state+ )+async def _handle_tool_call(self, event: Any) -> None:if self._session is None:return@@ -995,6 +1286,20 @@ class RealtimeVoiceSession:and call_idand wire_name == str(_DELEGATE_DECLARATION["name"])):+ turn_state = self._delegate_turns.get(self._turn_id)+ if turn_state is not None and turn_state.deterministic:+ if turn_state.result_complete and turn_state.result_payload:+ self._drop_provider_output_until_new_response = False+ await self._session.send_tool_result(+ call_id,+ wire_name,+ turn_state.result_payload,+ )+ else:+ turn_state.pending_tool_calls.append((call_id, wire_name))+ turn_state.input_boundary_ready.set()+ turn_state.provider_ready.set()+ return# Routed HERE (not in the pump branch) so the untranscribed-call# guard and pending flush keep applying to delegate calls too.self._start_delegate(call_id, wire_name, arguments)@@ -1025,6 +1330,7 @@ class RealtimeVoiceSession:}if result.get("success"):self._executed_tool_names.add(original_name)+ self._drop_provider_output_until_new_response = Falseawait self._session.send_tool_result(call_id, wire_name, result)async def _handle_end_call(self, event: Any) -> None:@@ -1044,6 +1350,183 @@ class RealtimeVoiceSession:name=f"rt-end-call-{self.session_id}",)+ def _start_deterministic_delegate(self, user_text: str) -> None:+ """Start one orchestrator-owned Brain turn for local-evidence input."""+ turn_id = self._turn_id+ if not turn_id:+ return+ turn_state = self._delegate_turns.setdefault(+ turn_id,+ _DelegateTurnState(deterministic=True),+ )+ turn_state.deterministic = True+ turn_state.user_text = str(user_text or "").strip()+ if self._turn_has_pending_delegate(turn_id) or turn_state.result_complete:+ return+ log.info(+ "realtime[%s] deterministic delegate: dispatching local-evidence turn",+ self.session_id,+ )+ task = asyncio.create_task(+ self._run_deterministic_delegate(turn_id, turn_state),+ name=f"rt-deterministic-delegate-{self.session_id}",+ )+ self._track_delegate_task(turn_id, task)++ async def _run_deterministic_delegate(+ self,+ turn_id: str,+ turn_state: _DelegateTurnState,+ ) -> None:+ try:+ boundary_ready = True+ if bool(+ getattr(+ self._session,+ "creates_responses_automatically",+ False,+ )+ ):+ try:+ await asyncio.wait_for(+ turn_state.input_boundary_ready.wait(),+ timeout=_DELEGATE_INPUT_BOUNDARY_WAIT_S,+ )+ except TimeoutError:+ boundary_ready = False+ else:+ # A manual-response provider may already have queued a native+ # function call or cancelled output behind the final input+ # event. Let the receive pump classify that evidence before+ # injecting the trusted result response.+ await asyncio.sleep(0)+ if not self._delegate_turn_is_active(turn_id, turn_state):+ return+ user_text = turn_state.user_text+ if boundary_ready:+ reply = (+ await asyncio.wait_for(+ self._dispatch_brain_turn(user_text),+ timeout=_DELEGATE_TIMEOUT_S,+ )+ or ""+ ).strip()+ if reply:+ turn_state.last_reply = reply+ result: dict[str, Any] = {+ "success": True,+ "spoken_reply": reply,+ }+ succeeded = True+ else:+ result = {+ "success": False,+ "error": "The delegated action returned no grounded result.",+ }+ succeeded = False+ else:+ result = {+ "success": False,+ "error": (+ "The complete spoken request could not be determined "+ "safely, so no action was executed."+ ),+ }+ succeeded = False+ except TimeoutError:+ result = {+ "success": False,+ "error": "The delegated action did not finish in time.",+ }+ succeeded = False+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 — deterministic delegation degrades honestly+ log.warning(+ "realtime[%s] deterministic delegate failed",+ self.session_id,+ exc_info=True,+ )+ await self._publish_error(+ "RealtimeDelegateError",+ "Deterministic delegated brain turn failed",+ recoverable=True,+ )+ result = {+ "success": False,+ "error": "The delegated action failed safely.",+ }+ succeeded = False++ if not succeeded:+ from jarvis.voice.action_phrases import action_phrase++ turn_state.last_reply = action_phrase(+ "action_failed_generic", self._language+ )+ result["spoken_reply"] = turn_state.last_reply+ turn_state.result_complete = True+ turn_state.result_success = succeeded+ turn_state.result_payload = result+ if self._delegate_turn_is_active(turn_id, turn_state) and succeeded:+ self._executed_tool_names.add(str(_DELEGATE_DECLARATION["name"]))+ if (+ self._ended+ or self._session is None+ or not self._delegate_turn_is_active(turn_id, turn_state)+ ):+ return++ if (+ bool(getattr(self._session, "creates_responses_automatically", False))+ and not turn_state.pending_tool_calls+ and not turn_state.provider_boundary_seen+ ):+ try:+ await asyncio.wait_for(+ turn_state.provider_ready.wait(),+ timeout=_DELEGATE_NATIVE_BOUNDARY_WAIT_S,+ )+ except TimeoutError:+ try:+ await self._session.interrupt()+ except Exception: # noqa: BLE001, S110 — best-effort boundary+ pass++ if not self._delegate_turn_is_active(turn_id, turn_state):+ return+ turn_state.delivery_started = True+ drop_before_delivery = self._drop_provider_output_until_new_response+ self._drop_provider_output_until_new_response = False+ try:+ if turn_state.pending_tool_calls:+ for call_id, wire_name in tuple(turn_state.pending_tool_calls):+ await self._session.send_tool_result(+ call_id,+ wire_name,+ result,+ )+ turn_state.pending_tool_calls.clear()+ else:+ await self._session.send_text(+ _delegate_result_prompt(+ turn_state.last_reply,+ language=self._language,+ success=succeeded,+ )+ )+ except Exception: # noqa: BLE001 — preserve an honest surface fallback+ turn_state.delivery_started = False+ self._drop_provider_output_until_new_response = drop_before_delivery+ log.warning(+ "realtime[%s] trusted delegate result injection failed",+ self.session_id,+ exc_info=True,+ )+ await self._send_json(+ {"type": "error_spoken", "text": turn_state.last_reply}+ )+def _start_delegate(self, call_id: str, wire_name: str, arguments: dict[str, Any]) -> None:@@ -1065,8 +1548,7 @@ class RealtimeVoiceSession:self._run_delegate(call_id, wire_name, user_text, turn_id, turn_state),name=f"rt-delegate-{self.session_id}",)- self._delegate_tasks.add(task)- task.add_done_callback(self._delegate_tasks.discard)+ self._track_delegate_task(turn_id, task)async def _run_delegate(self,@@ -1076,6 +1558,7 @@ class RealtimeVoiceSession:turn_id: str,turn_state: _DelegateTurnState,) -> None:+ succeeded = Falsetry:reply = (await asyncio.wait_for(@@ -1097,6 +1580,7 @@ class RealtimeVoiceSession:"briefly confirm it to the user."),}+ succeeded = Trueif self._delegate_turns.get(turn_id) is turn_state:self._executed_tool_names.add(str(_DELEGATE_DECLARATION["name"]))except TimeoutError:@@ -1120,11 +1604,23 @@ class RealtimeVoiceSession:"success": False,"error": "The action failed safely and was not completed.",}- if self._ended or self._session is None:+ turn_state.result_complete = True+ turn_state.result_success = succeeded+ turn_state.result_payload = result+ if (+ self._ended+ or self._session is None+ or not self._delegate_turn_is_active(turn_id, turn_state)+ ):returntry:+ turn_state.delivery_started = True+ drop_before_delivery = self._drop_provider_output_until_new_response+ self._drop_provider_output_until_new_response = Falseawait self._session.send_tool_result(call_id, wire_name, result)except Exception: # noqa: BLE001 — late result on a torn-down wire+ turn_state.delivery_started = False+ self._drop_provider_output_until_new_response = drop_before_deliverylog.debug("realtime[%s] delegate result send failed",self.session_id,@@ -1142,14 +1638,37 @@ class RealtimeVoiceSession:# can publish the one response that was actually spoken.generate = getattr(self._brain, "generate", None)if callable(generate):+ isolated_context = {+ "use_history": False,+ "history_override": tuple(self._delegate_history),+ }for kwargs in ({"allow_voice_confirm": True,"prefer_tool_model": True,"publish_response": False,+ **isolated_context,+ },+ {+ "allow_voice_confirm": True,+ "publish_response": False,+ **isolated_context,+ },+ {+ "allow_voice_confirm": True,+ "prefer_tool_model": True,+ "publish_response": False,+ "use_history": False,+ },+ {+ "allow_voice_confirm": True,+ "publish_response": False,+ "use_history": False,+ },+ {+ "allow_voice_confirm": True,+ "prefer_tool_model": True,},- {"allow_voice_confirm": True, "publish_response": False},- {"allow_voice_confirm": True, "prefer_tool_model": True},{"allow_voice_confirm": True},):try:@@ -1224,6 +1743,8 @@ class RealtimeVoiceSession:self._tool_transcript_task = Noneasync def _emit_audio(self, chunk: Any) -> None:+ if self._must_withhold_provider_output():+ returnpcm = bytes(getattr(chunk, "pcm", b"") or b"")if not pcm:return@@ -1238,6 +1759,7 @@ class RealtimeVoiceSession:await self._send_binary(pcm)async def _barge_in(self) -> None:+ self._drop_provider_output_until_new_response = Trueself._response_requested_for_turn = Falseself._cancel_release_task()self._gate.drain()@@ -1279,6 +1801,7 @@ class RealtimeVoiceSession:if not task.done():task.cancel()self._delegate_tasks.clear()+ self._delegate_tasks_by_turn.clear()if self._pump_task is not None and not self._pump_task.done():self._pump_task.cancel()try:diff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.pyindex b08a450da6..b8e921a41e 100644--- a/jarvis/realtime/tools.py+++ b/jarvis/realtime/tools.py@@ -72,8 +72,16 @@ class _PendingConfirmation:class RealtimeToolBridge:"""Expose the live router tools and execute only through ``ToolExecutor``."""- def __init__(self, *, tools: dict[str, Any], executor: Any, language: str) -> None:+ def __init__(+ self,+ *,+ tools: dict[str, Any],+ executor: Any,+ language: str,+ tools_source: Any = None,+ ) -> None:self._tools = dict(tools)+ self._tools_source = tools_sourceself._executor = executorself._language = languageself._wire_to_name: dict[str, str] = {}@@ -88,9 +96,15 @@ class RealtimeToolBridge:executor = getattr(brain, "_tool_executor_ref", None)if not isinstance(tools, dict) or not tools or executor is None:return None- return cls(tools=tools, executor=executor, language=language)+ return cls(+ tools=tools,+ executor=executor,+ language=language,+ tools_source=lambda: getattr(brain, "_tools", None),+ )def _build_declarations(self) -> tuple[dict[str, Any], ...]:+ self._wire_to_name.clear()declarations: list[dict[str, Any]] = []for name, tool in sorted(self._tools.items()):schema = getattr(tool, "schema", None)@@ -118,6 +132,36 @@ class RealtimeToolBridge:def set_language(self, language: str) -> None:self._language = language+ def refresh_from_source(self) -> bool:+ """Refresh a live BrainManager tool replacement safely.++ Returns ``True`` only when the provider-facing declarations changed.+ A tool awaiting voice confirmation is retained until that confirmation+ resolves, so a concurrent registry refresh cannot strand the pending+ ``ToolExecutor`` action.+ """+ source = self._tools_source+ if not callable(source):+ return False+ current = source()+ if not isinstance(current, dict):+ return False+ try:+ refreshed = dict(current)+ except RuntimeError:+ return False+ pending = self._pending+ if (+ pending is not None+ and pending.tool_name not in refreshed+ and pending.tool_name in self._tools+ ):+ refreshed[pending.tool_name] = self._tools[pending.tool_name]+ previous_declarations = self._declarations+ self._tools = refreshed+ self._declarations = self._build_declarations()+ return self._declarations != previous_declarations+async def handle_user_transcript(self, text: str) -> None:self._last_user_text = textself._vetoed_tool = ""diff --git a/jarvis/sessions/store.py b/jarvis/sessions/store.pyindex a7916b1e18..70baf2cebe 100644--- a/jarvis/sessions/store.py+++ b/jarvis/sessions/store.py@@ -22,8 +22,9 @@ import jsonimport loggingimport sqlite3import threading+from collections.abc import Iterablefrom pathlib import Path-from typing import Any, Iterable+from typing import Anyfrom pydantic import ValidationError@@ -373,6 +374,31 @@ class SessionStore:rows = cur.fetchall()return [_row_to_turn(r) for r in rows]+ def get_latest_user_turn(+ self,+ *,+ session_id: str | None = None,+ ) -> VoiceTurnRow | None:+ """Return the newest persisted turn with a non-empty user transcript.++ ``started_ms`` is the durable utterance-order signal. The optional+ session filter lets callers avoid crossing conversation boundaries;+ without it, this is the newest voice transcript in the store.+ """+ with self._lock:+ cur = self._c.execute(+ """+ SELECT * FROM voice_turns+ WHERE TRIM(user_text) != ''+ AND (? IS NULL OR session_id = ?)+ ORDER BY started_ms DESC, idx DESC, id DESC+ LIMIT 1+ """,+ (session_id, session_id),+ )+ row = cur.fetchone()+ return _row_to_turn(row) if row is not None else None+def get_events(self, session_id: str) -> list[VoiceEventRow]:with self._lock:cur = self._c.execute(diff --git a/jarvis/ui/web/sessions_routes.py b/jarvis/ui/web/sessions_routes.pyindex 5340e35bb1..62c2362455 100644--- a/jarvis/ui/web/sessions_routes.py+++ b/jarvis/ui/web/sessions_routes.py@@ -2,6 +2,7 @@Endpoints:GET /api/sessions List (newest first, max 100)+ GET /api/sessions/latest-turn Latest persisted user transcriptGET /api/sessions/{session_id} Detail with turns + raw eventsGET /api/sessions/{session_id}/export Markdown / plain text for copyPOST /api/sessions/{session_id}/save Writes a file to the user's Downloads folder@@ -32,7 +33,12 @@ from fastapi.responses import PlainTextResponse, Responsefrom pydantic import BaseModelfrom jarvis.sessions.formatter import format_session_markdown, format_session_plain-from jarvis.sessions.models import SessionDetail, SessionListItem, VoiceSessionRow+from jarvis.sessions.models import (+ SessionDetail,+ SessionListItem,+ VoiceSessionRow,+ VoiceTurnRow,+)from jarvis.sessions.store import SessionStorelog = logging.getLogger(__name__)@@ -74,6 +80,19 @@ async def list_sessions(return store.list_sessions(limit=limit)[email protected]("/latest-turn", response_model=VoiceTurnRow)+async def get_latest_user_turn(+ request: Request,+ session_id: str | None = Query(default=None),+) -> VoiceTurnRow:+ """Return the newest persisted turn containing a user transcript."""+ store = _require_store(request)+ turn = store.get_latest_user_turn(session_id=session_id)+ if turn is None:+ raise HTTPException(status_code=404, detail="user-turn-not-found")+ return turn++@router.get("/{session_id}", response_model=SessionDetail)async def get_session_detail(session_id: str, request: Request) -> SessionDetail:"""Full session: header + turns + raw events for replay."""diff --git a/jarvis/ui/web/tools_routes.py b/jarvis/ui/web/tools_routes.pyindex f58a7a2dd8..1ee9db19c2 100644--- a/jarvis/ui/web/tools_routes.py+++ b/jarvis/ui/web/tools_routes.py@@ -14,7 +14,9 @@ router = APIRouter(prefix="/api/tools", tags=["tools"])def _tool_to_dict(name: str, tool: Any) -> dict[str, Any]:source = "native"- if "/" in name:+ if name.startswith("cli_"):+ source = "cli"+ elif "/" in name or name.startswith("mcp__"):# MCPToolAdapter.name = "<server>/<tool>"source = "mcp"@@ -35,12 +37,24 @@ def _tool_to_dict(name: str, tool: Any) -> dict[str, Any]:@router.get("")async def list_tools(request: Request) -> dict[str, Any]:- registry = getattr(request.app.state, "tool_registry", None)+ # ``tool_registry`` is only the user-added MCP registry. The effective+ # BrainManager registry also contains native, Marketplace, and connected CLI+ # tools and is replaced atomically on live refresh. Prefer that authoritative+ # per-turn surface so this endpoint can answer "which tools are available?"+ # honestly; retain the MCP registry as an early-boot fallback.+ brain = getattr(request.app.state, "brain", None)+ registry = getattr(brain, "_tools", None)if registry is None or not hasattr(registry, "items"):- return {"tools": [], "total": 0, "by_source": {"mcp": 0, "native": 0}}+ registry = getattr(request.app.state, "tool_registry", None)+ if registry is None or not hasattr(registry, "items"):+ return {+ "tools": [],+ "total": 0,+ "by_source": {"mcp": 0, "cli": 0, "native": 0},+ }tools = [_tool_to_dict(name, tool) for name, tool in registry.items()]- by_source: dict[str, int] = {"mcp": 0, "native": 0}+ by_source: dict[str, int] = {"mcp": 0, "cli": 0, "native": 0}for t in tools:by_source[t["source"]] = by_source.get(t["source"], 0) + 1diff --git a/jarvis/ui/web/wiki_routes.py b/jarvis/ui/web/wiki_routes.pyindex 47c98478b5..8a9689681c 100644--- a/jarvis/ui/web/wiki_routes.py+++ b/jarvis/ui/web/wiki_routes.py@@ -1,6 +1,6 @@"""FastAPI routes that expose the on-disk Obsidian vault as JSON (Phase B3, Agent A).-Five read-only endpoints power the Desktop App's new "Wiki" sidebar tab:+The read endpoints power the Desktop App's "Wiki" sidebar tab:* ``GET /api/wiki/tree`` — folder structure with file metadata.* ``GET /api/wiki/page/{slug}`` — one page (frontmatter + body + wikilinks).@@ -8,19 +8,20 @@ Five read-only endpoints power the Desktop App's new "Wiki" sidebar tab:* ``GET /api/wiki/backlinks/{slug}``— reverse-link list with body snippets.* ``GET /api/wiki/search`` — keyword search via ``VaultSearch`` (B5).-Two later additions follow the same style: ``GET /api/wiki/telemetry`` (B8.7,-in-memory counter snapshot) and ``GET /api/wiki/health`` (spec A5, bootstrap /-write / chain-failure / journal-backlog status).+Later additions expose telemetry, health, index repair, and one explicit write+surface: ``POST /api/wiki/ingest``. The write route delegates to the same+curator service as the native ``wiki-ingest`` brain tool.-All endpoints follow the existing house style: HTTP 200 with the envelope+Read endpoints follow the existing house style: HTTP 200 with the envelope``{"ok": True, ...}`` on success and ``{"ok": False, "error": "..."}`` onlogical errors. HTTP 404 stays reserved for unknown routes; HTTP 500 only-fires on unhandled exceptions.+fires on unhandled exceptions. The write endpoint uses non-2xx responses when+nothing was stored so CLI and agent callers cannot mistake a no-op for success.The module reuses ``PageRepository`` (B1, ``jarvis/memory/wiki/page.py``),``VaultIndex`` (B1, ``jarvis/memory/wiki/vault_index.py``) and-``VaultSearch`` (B5, ``jarvis/memory/wiki/search.py``). It is a pure view-layer — no writes, no brain, no event-bus side effects.+``VaultSearch`` (B5, ``jarvis/memory/wiki/search.py``), and the guarded Wiki+ingest service. It never writes Wiki files directly.The vault root is read from ``app.state.config.wiki_integration.vault_root``.Tests can override the path by setting that attribute directly before the@@ -31,18 +32,29 @@ from __future__ import annotationsimport asyncioimport logging+from datetime import UTCfrom pathlib import Pathfrom typing import Any-from fastapi import APIRouter, Query, Request+from fastapi import APIRouter, HTTPException, Query, Request+from pydantic import BaseModel, Field+from jarvis.memory.wiki.ingest_service import (+ MAX_INGEST_CHARS,+ MAX_SOURCE_CHARS,+ MIN_INGEST_CHARS,+ ingest_wiki_text,+)+from jarvis.memory.wiki.integration import get_running_curatorfrom jarvis.memory.wiki.page import MarkdownPageRepositoryfrom jarvis.memory.wiki.protocols import WikiPagefrom jarvis.memory.wiki.search import VaultSearchfrom jarvis.memory.wiki.telemetry import telemetry as _telemetryfrom jarvis.memory.wiki.vault_index import VaultIndexfrom jarvis.memory.wiki.vault_root import resolve_vault_root-from jarvis.memory.wiki.wikilink import _canonicalise as _canonicalise_link # type: ignore[attr-defined]+from jarvis.memory.wiki.wikilink import (+ _canonicalise as _canonicalise_link, # type: ignore[attr-defined]+)log = logging.getLogger(__name__)@@ -61,6 +73,30 @@ _BACKLINK_SNIPPET_RADIUS = 80_BACKLINK_SNIPPET_MAX = 200+class WikiIngestRequest(BaseModel):+ """One explicit, self-contained fact or summary to store."""++ text: str = Field(min_length=MIN_INGEST_CHARS, max_length=MAX_INGEST_CHARS)+ source: str = Field(+ default="api:wiki-ingest",+ min_length=1,+ max_length=MAX_SOURCE_CHARS,+ pattern=r"^[A-Za-z0-9][A-Za-z0-9:._/-]*$",+ )+++class WikiIngestResponse(BaseModel):+ """Honest result returned only after at least one page was written."""++ ok: bool = True+ source: str+ applied: int+ skipped_due_to_recent_edit: int+ failed_validation: int+ blocked_sensitive_content: int+ pages_touched: list[str]++# ----------------------------------------------------------------------# Vault-root resolution# ----------------------------------------------------------------------@@ -458,6 +494,48 @@ async def get_search(return {"ok": True, "query": sanitised, "hits": rendered}+ "/ingest",+ response_model=WikiIngestResponse,+ openapi_extra={"x-jarvis-risk-tier": "monitor"},+)+async def ingest_wiki(payload: WikiIngestRequest) -> WikiIngestResponse:+ """Store one fact or summary through the guarded live Wiki curator."""+ outcome = await ingest_wiki_text(+ curator=get_running_curator(),+ text=payload.text,+ source=payload.source,+ )+ if not outcome.success:+ status_code = {+ "not-bootstrapped": 503,+ "curator-failed": 503,+ "recent-edit-conflict": 409,+ }.get(outcome.error_code or "", 422)+ raise HTTPException(+ status_code=status_code,+ detail={+ "code": outcome.error_code or "wiki-ingest-failed",+ "message": outcome.error or "nothing was stored",+ "source": outcome.source,+ "skipped_due_to_recent_edit": len(+ outcome.skipped_due_to_recent_edit+ ),+ "failed_validation": len(outcome.failed_validation),+ "blocked_sensitive_content": len(outcome.blocked_pii),+ },+ )++ return WikiIngestResponse(+ source=outcome.source,+ applied=len(outcome.applied),+ skipped_due_to_recent_edit=len(outcome.skipped_due_to_recent_edit),+ failed_validation=len(outcome.failed_validation),+ blocked_sensitive_content=len(outcome.blocked_pii),+ pages_touched=outcome.page_names,+ )++# ----------------------------------------------------------------------# Internals# ----------------------------------------------------------------------@@ -581,11 +659,11 @@ def _format_mtime(mtime: float | None) -> str | None:"""Format a POSIX mtime as ISO-8601 (UTC) or return ``None`` when missing."""if mtime is None:return None- from datetime import datetime, timezone+ from datetime import datetimetry:return (- datetime.fromtimestamp(mtime, tz=timezone.utc)+ datetime.fromtimestamp(mtime, tz=UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")diff --git a/tests/fakes/fake_realtime.py b/tests/fakes/fake_realtime.pyindex 7e7c8fcfbb..4726bfe709 100644--- a/tests/fakes/fake_realtime.py+++ b/tests/fakes/fake_realtime.py@@ -10,6 +10,10 @@ class FakeRealtimeWire:"""Scripted provider session with no network, audio device, or model."""session_id = "fake-realtime-wire"+ creates_responses_automatically = False+ # This fake stands in for the two bundled adapters, both of which isolate+ # cancelled output generations before exposing normalized events.+ isolates_response_generations = Truedef __init__(self, events: list[Any], *, hold_after_events: bool = False) -> None:self._events = list(events)@@ -19,6 +23,7 @@ class FakeRealtimeWire:self.tool_results: list[tuple[str, str, dict[str, Any]]] = []self.session_updates: list[dict[str, Any]] = []self.response_requests = 0+ self.required_tools: list[str | None] = []self.truncated: list[int] = []self.interrupts = 0self.closed = False@@ -35,14 +40,19 @@ class FakeRealtimeWire:await asyncio.Event().wait()async def update_session(- self, *, instructions: str | None = None, language: str | None = None+ self,+ *,+ instructions: str | None = None,+ language: str | None = None,+ tools: tuple[dict[str, Any], ...] | None = None,) -> None:self.session_updates.append(- {"instructions": instructions, "language": language}+ {"instructions": instructions, "language": language, "tools": tools})- async def request_response(self) -> None:+ async def request_response(self, *, required_tool: str | None = None) -> None:self.response_requests += 1+ self.required_tools.append(required_tool)async def truncate(self, audio_end_ms: int) -> None:self.truncated.append(audio_end_ms)diff --git a/tests/missions/critic/test_capability_honesty.py b/tests/missions/critic/test_capability_honesty.pyindex 5b3f35d789..d3f413103b 100644--- a/tests/missions/critic/test_capability_honesty.py+++ b/tests/missions/critic/test_capability_honesty.py@@ -23,6 +23,8 @@ import pytestfrom jarvis.missions.critic.runner import (CriticRunner,_extract_tool_call_evidence,+ _render_external_action_evidence,+ _request_is_messaging_action,enforce_capability_honesty,)from jarvis.missions.critic.verdict import (@@ -30,7 +32,6 @@ from jarvis.missions.critic.verdict import (CriticAxis,CriticVerdict,)-from jarvis.missions.critic.runner import _request_is_messaging_actionfrom jarvis.missions.stream_evidence import diff_has_action_evidencefrom tests.missions.critic.test_runner_claude_direct import (_patch_direct,@@ -94,6 +95,25 @@ def test_codex_mcp_tool_call_counts_as_evidence() -> None:assert _extract_tool_call_evidence(stream)+def test_codex_mcp_success_renders_ground_truth_evidence_block() -> None:+ stream = _codex_item_line(+ {+ "id": "item_9",+ "type": "mcp_tool_call",+ "server": "gmail",+ "tool": "send_message",+ "status": "completed",+ "result": "message id 84",+ }+ )++ evidence = _render_external_action_evidence(stream)+ assert evidence.startswith("diff --external-action-evidence")+ assert "# verified-external-action" in evidence+ assert "+tool: mcp__gmail__send_message" in evidence+ assert "+result: message id 84" in evidence++def test_codex_prose_only_is_not_evidence() -> None:"""agent_message prose alone must keep yielding zero evidence."""stream = "\n".join(diff --git a/tests/missions/critic/test_prompts.py b/tests/missions/critic/test_prompts.pyindex 0bf3e6734d..83d70af259 100644--- a/tests/missions/critic/test_prompts.py+++ b/tests/missions/critic/test_prompts.py@@ -163,6 +163,11 @@ def test_ground_truth_rule_recognizes_verified_external_writes() -> None:assert "verified-external-write" in CRITIC_SYSTEM_PROMPT+def test_ground_truth_rule_recognizes_verified_external_actions() -> None:+ assert "diff --external-action-evidence" in CRITIC_SYSTEM_PROMPT+ assert "verified-external-action" in CRITIC_SYSTEM_PROMPT++# --- Render-Behavior ---diff --git a/tests/missions/test_api_agent_worker_resolution.py b/tests/missions/test_api_agent_worker_resolution.pyindex 54f8ac8c7f..71ec25fd8e 100644--- a/tests/missions/test_api_agent_worker_resolution.py+++ b/tests/missions/test_api_agent_worker_resolution.py@@ -20,6 +20,7 @@ Both branches were extracted into standalone, directly-testable helpersworker-factory closure inside ``bootstrap_missions`` stays a thin dispatcher —same pattern as ``_cross_family_last_resort_worker``."""+from __future__ import annotationsimport pytest@@ -46,8 +47,9 @@ def test_unviable_provider_crosses_family_instead_of_being_reused(`_api_key_family_viable` reports False, so the branch crosses family."""monkeypatch.setattr(mi, "_api_key_family_viable", lambda p: False)monkeypatch.setattr(- mi, "_cross_family_last_resort_worker",- lambda task_text: ApiAgentWorker("gemini"),+ mi,+ "_cross_family_last_resort_worker",+ lambda task_text, *_args: ApiAgentWorker("gemini"),)worker = mi._resolve_api_agent_worker("openrouter", "do the task")assert isinstance(worker, ApiAgentWorker)@@ -58,7 +60,7 @@ def test_no_family_reachable_falls_back_to_claude_honest_fail(monkeypatch: pytest.MonkeyPatch,) -> None:monkeypatch.setattr(mi, "_api_key_family_viable", lambda p: False)- monkeypatch.setattr(mi, "_cross_family_last_resort_worker", lambda task_text: None)+ monkeypatch.setattr(mi, "_cross_family_last_resort_worker", lambda task_text, *_args: None)monkeypatch.setattr(mi, "_assemble_worker_mcp_servers", lambda **_k: {})worker = mi._resolve_api_agent_worker("openrouter", "do the task")assert isinstance(worker, ClaudeDirectWorker)@@ -72,8 +74,9 @@ def test_viability_check_failure_is_treated_as_no_key(monkeypatch.setattr(mi, "_api_key_family_viable", _boom)monkeypatch.setattr(- mi, "_cross_family_last_resort_worker",- lambda task_text: ApiAgentWorker("gemini"),+ mi,+ "_cross_family_last_resort_worker",+ lambda task_text, *_args: ApiAgentWorker("gemini"),)worker = mi._resolve_api_agent_worker("openrouter", "do the task")assert isinstance(worker, ApiAgentWorker)@@ -101,7 +104,8 @@ def _patch_codex_dead_login(lambda: claude_quota_capped,)monkeypatch.setattr(- mi, "_api_key_family_viable",+ mi,+ "_api_key_family_viable",lambda p: claude_api_key_viable if p == "claude-api" else False,)monkeypatch.setattr(mi, "_assemble_worker_mcp_servers", lambda **_k: {})@@ -120,7 +124,9 @@ def test_dead_codex_login_viable_claude_cli_runs_claude_direct(monkeypatch: pytest.MonkeyPatch,) -> None:_patch_codex_dead_login(- monkeypatch, claude_binary="/usr/bin/claude", claude_auth_viable=True,+ monkeypatch,+ claude_binary="/usr/bin/claude",+ claude_auth_viable=True,)worker = mi._resolve_codex_dead_login_worker("do the task")assert isinstance(worker, ClaudeDirectWorker)@@ -139,8 +145,9 @@ def test_dead_codex_login_claude_quota_cooldown_crosses_family(claude_quota_capped=True,)monkeypatch.setattr(- mi, "_cross_family_last_resort_worker",- lambda task_text: ApiAgentWorker("openrouter"),+ mi,+ "_cross_family_last_resort_worker",+ lambda task_text, *_args: ApiAgentWorker("openrouter"),)worker = mi._resolve_codex_dead_login_worker("do the task")assert isinstance(worker, ApiAgentWorker)@@ -151,11 +158,14 @@ def test_dead_codex_login_and_dead_claude_auth_crosses_family(monkeypatch: pytest.MonkeyPatch,) -> None:_patch_codex_dead_login(- monkeypatch, claude_binary="/usr/bin/claude", claude_auth_viable=False,+ monkeypatch,+ claude_binary="/usr/bin/claude",+ claude_auth_viable=False,)monkeypatch.setattr(- mi, "_cross_family_last_resort_worker",- lambda task_text: ApiAgentWorker("gemini"),+ mi,+ "_cross_family_last_resort_worker",+ lambda task_text, *_args: ApiAgentWorker("gemini"),)worker = mi._resolve_codex_dead_login_worker("do the task")assert isinstance(worker, ApiAgentWorker)@@ -166,8 +176,10 @@ def test_dead_codex_login_nothing_reachable_falls_back_to_claude_honest_fail(monkeypatch: pytest.MonkeyPatch,) -> None:_patch_codex_dead_login(- monkeypatch, claude_binary="/usr/bin/claude", claude_auth_viable=False,+ monkeypatch,+ claude_binary="/usr/bin/claude",+ claude_auth_viable=False,)- monkeypatch.setattr(mi, "_cross_family_last_resort_worker", lambda task_text: None)+ monkeypatch.setattr(mi, "_cross_family_last_resort_worker", lambda task_text, *_args: None)worker = mi._resolve_codex_dead_login_worker("do the task")assert isinstance(worker, ClaudeDirectWorker)diff --git a/tests/missions/test_claude_worker_mcp_config.py b/tests/missions/test_claude_worker_mcp_config.pyindex f775325f81..2c8e584420 100644--- a/tests/missions/test_claude_worker_mcp_config.py+++ b/tests/missions/test_claude_worker_mcp_config.py@@ -2,8 +2,10 @@The worker must turn an assembled ``mcpServers`` dict into a claude-cli``--mcp-config <file>`` flag so the delegated worker can call the connected-plugins. No servers -> no flag (zero behavioural change for plain missions).+plugins. An empty explicit config still activates strict mode so project/global+MCP settings cannot inject undeclared worker tools."""+from __future__ import annotationsimport json@@ -12,9 +14,12 @@ from pathlib import Pathfrom jarvis.missions.workers.claude_direct_worker import _build_mcp_config_args-def test_no_servers_produces_no_flag(tmp_path: Path) -> None:- assert _build_mcp_config_args(tmp_path, {}) == []- assert _build_mcp_config_args(tmp_path, None) == []+def test_no_servers_still_produces_a_strict_empty_config(tmp_path: Path) -> None:+ for servers in ({}, None):+ args = _build_mcp_config_args(tmp_path, servers)+ assert "--strict-mcp-config" in args+ cfg_path = Path(args[args.index("--mcp-config") + 1])+ assert json.loads(cfg_path.read_text(encoding="utf-8")) == {"mcpServers": {}}def test_servers_write_config_and_emit_flag(tmp_path: Path) -> None:diff --git a/tests/missions/test_stream_evidence.py b/tests/missions/test_stream_evidence.pyindex 8d0236caca..07abc4b73e 100644--- a/tests/missions/test_stream_evidence.py+++ b/tests/missions/test_stream_evidence.py@@ -12,6 +12,7 @@ import jsonfrom jarvis.missions.stream_evidence import (extract_stream_evidence,extract_verified_commands,+ extract_verified_external_actions,)@@ -209,6 +210,51 @@ def test_no_tools_no_answer_is_empty() -> None:assert not ev.has_tool_evidence+def test_verified_external_action_requires_correlated_success_result() -> None:+ stream = _stream([+ {"type": "assistant", "message": {"content": [+ {"type": "tool_use", "id": "m1", "name": "mcp__gmail__send_message", "input": {}}+ ]}},+ {"type": "user", "message": {"content": [+ {"type": "tool_result", "tool_use_id": "m1", "content": "message id 42"}+ ]}},+ ])++ assert extract_verified_external_actions(stream) == (+ ("mcp__gmail__send_message", "message id 42"),+ )+++def test_verified_external_action_rejects_error_and_missing_result() -> None:+ stream = _stream([+ {"type": "assistant", "message": {"content": [+ {"type": "tool_use", "id": "m1", "name": "mcp__gmail__send_message", "input": {}},+ {"type": "tool_use", "id": "m2", "name": "mcp__linear__create_issue", "input": {}},+ ]}},+ {"type": "user", "message": {"content": [+ {"type": "tool_result", "tool_use_id": "m1", "content": "denied", "is_error": True}+ ]}},+ ])++ assert extract_verified_external_actions(stream) == ()+++def test_codex_mcp_completion_normalizes_to_verified_external_action() -> None:+ stream = _stream([+ {"type": "item.completed", "item": {+ "type": "mcp_tool_call",+ "server": "gmail",+ "tool": "send_message",+ "status": "completed",+ "result": "message id 84",+ }}+ ])++ assert extract_verified_external_actions(stream) == (+ ("mcp__gmail__send_message", "message id 84"),+ )++# --- readonly_answer: the read-only success signal -------------------------from jarvis.missions.stream_evidence import readonly_answer, summarize_answers # noqa: E402diff --git a/tests/missions/test_worker_capability_parity.py b/tests/missions/test_worker_capability_parity.pynew file mode 100644index 0000000000..ff43480e29--- /dev/null+++ b/tests/missions/test_worker_capability_parity.py@@ -0,0 +1,93 @@+"""Provider-parity guards for the restricted mission capability inventory."""++from __future__ import annotations++import json+from pathlib import Path++from jarvis.missions.workers.api_agent_worker import ApiAgentWorker+from jarvis.missions.workers.capabilities import WorkerCapabilityInventory+from jarvis.missions.workers.claude_direct_worker import ClaudeDirectWorker+from jarvis.missions.workers.codex_direct_worker import (+ CodexDirectWorker,+ _build_codex_direct_cmd,+)+from jarvis.missions.workers.gemini_worker import (+ GeminiWorker,+ _build_isolated_gemini_env,+)+from jarvis.missions.workers.google_cli_worker import GoogleCliWorker+++def _inventory() -> WorkerCapabilityInventory:+ return WorkerCapabilityInventory.build(+ mcp_servers={+ "notes": {+ "command": "notes-mcp",+ "env": {"ACCESS_TOKEN": "secret-value"},+ }+ },+ app_commands=("session-latest-turn", "wiki-ingest"),+ )+++def test_every_backend_receives_the_same_restricted_inventory() -> None:+ inventory = _inventory()+ workers = (+ ClaudeDirectWorker(capability_inventory=inventory),+ CodexDirectWorker(capability_inventory=inventory),+ GeminiWorker(capability_inventory=inventory),+ GoogleCliWorker(capability_inventory=inventory),+ ApiAgentWorker("openrouter", capability_inventory=inventory),+ )++ assert all(worker.capability_inventory is inventory for worker in workers)+ assert workers[3]._gemini_fallback.capability_inventory is inventory+ assert "secret-value" not in repr(inventory)+++def test_backend_reports_are_honest_about_unsupported_surfaces() -> None:+ inventory = _inventory()++ assert inventory.report_for("claude-cli")["mcp"]["status"] == "available"+ for backend in ("codex-cli", "gemini-cli", "google-cli", "api:openrouter"):+ report = inventory.report_for(backend)+ assert report["mcp"]["status"] == "unsupported"+ assert report["app_commands"]["status"] == "unsupported"+ assert "secret-value" not in json.dumps(report)+++def test_recursive_tools_are_rejected_from_worker_inventory() -> None:+ try:+ WorkerCapabilityInventory.build(app_commands=("spawn-worker",))+ except ValueError as exc:+ assert "recursive tools" in str(exc)+ else: # pragma: no cover - assertion branch+ raise AssertionError("spawn-worker entered a worker capability inventory")+++def test_codex_worker_ignores_machine_global_config(tmp_path: Path) -> None:+ cmd = _build_codex_direct_cmd(worktree=tmp_path / "worktree", model=None)+ assert "--ignore-user-config" in cmd+++def test_gemini_worker_restricts_tools_without_hiding_auth_home(tmp_path: Path) -> None:+ original = {+ "HOME": "/real/home",+ "GEMINI_CLI_HOME": "/real/gemini-auth",+ "GEMINI_API_KEY": "key",+ }+ restricted, settings_path, no_mcp_server = _build_isolated_gemini_env(+ original, log_dir=tmp_path+ )++ assert original["HOME"] == "/real/home"+ assert restricted["HOME"] == "/real/home"+ assert restricted["GEMINI_CLI_HOME"] == "/real/gemini-auth"+ assert restricted["GEMINI_CLI_SYSTEM_SETTINGS_PATH"] == str(settings_path)+ settings = json.loads(settings_path.read_text(encoding="utf-8"))+ assert "admin" not in settings+ assert settings["mcp"]["allowed"] == [no_mcp_server]+ assert no_mcp_server.startswith("jarvis-no-mcp-")+ assert settings["security"]["allowedExtensions"] == ["(?!)"]+ assert settings["hooksConfig"]["enabled"] is Falsediff --git a/tests/missions/test_worker_mcp_assembly.py b/tests/missions/test_worker_mcp_assembly.pyindex 7dec384c8e..ddda7065da 100644--- a/tests/missions/test_worker_mcp_assembly.py+++ b/tests/missions/test_worker_mcp_assembly.py@@ -13,10 +13,11 @@ wrong-MCP stall. The filter is reversible (``relevance_filter=False`` or the``[brain.routing].worker_mcp_relevance_filter`` kill-switch) and ALWAYS degradesto exporting on a fault (never silently strips a mission's MCPs)."""+from __future__ import annotations-from jarvis.missions.init import _assemble_worker_mcp_serversfrom jarvis.marketplace.token_store import InMemoryBackend, Tokens, TokenStore+from jarvis.missions.init import _assemble_worker_mcp_serversdef test_assembles_connected_plugins() -> None:@@ -151,3 +152,26 @@ def test_relevance_fault_falls_back_to_export(monkeypatch) -> None: # noqa: ANNserver_tools={"weather-mcp": []},)assert "weather-mcp" in servers+++def test_live_registry_inspection_fault_falls_back_to_full_export(+ monkeypatch,+) -> None: # noqa: ANN001+ """A swallowed registry fault must not look like valid empty evidence."""+ import jarvis.core.runtime_refs as runtime_refs++ def _boom():+ raise RuntimeError("live registry unavailable")++ monkeypatch.setattr(runtime_refs, "get_mcp_registry", _boom)+ ts = TokenStore(InMemoryBackend())+ mcp_json = {"weather-mcp": {"command": "npx", "enabled": True}}++ servers = _assemble_worker_mcp_servers(+ token_store=ts,+ mcp_json_servers=mcp_json,+ task_text="refactor the authentication module",+ relevance_filter=True,+ )++ assert "weather-mcp" in serversdiff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.pyindex 42bad29388..62e8a09ebf 100644--- a/tests/unit/brain/test_routing.py+++ b/tests/unit/brain/test_routing.py@@ -913,6 +913,50 @@ def test_factory_wires_registry_command_tools_into_router_set() -> None:assert "provider-test" in tools+def test_factory_native_tool_wins_registry_name_collision_in_any_entrypoint_order(+ monkeypatch,+) -> None:+ """Native tools deterministically outrank same-named virtual commands."""+ import importlib.metadata++ from jarvis.brain.factory import _load_tools_for_tier+ from jarvis.plugins.tool.app_command import AppCommandTool+ from jarvis.plugins.tool.wiki_ingest import WikiIngestTool++ class FakeEntryPoint:+ def __init__(self, name, target):+ self.name = name+ self._target = target++ def load(self):+ return self._target++ app_command = FakeEntryPoint("app-command", AppCommandTool)+ wiki_ingest = FakeEntryPoint("wiki-ingest", WikiIngestTool)++ for ordered in (+ [app_command, wiki_ingest],+ [wiki_ingest, app_command],+ ):+ monkeypatch.setattr(+ importlib.metadata,+ "entry_points",+ lambda *, group, ordered=ordered: list(ordered),+ )+ tools = _load_tools_for_tier(+ "router",+ bus=EventBus(),+ executor=None,+ harness_manager=None,+ user_profile=None,+ people=None,+ config=JarvisConfig(),+ )++ assert type(tools["wiki-ingest"]) is WikiIngestTool+ assert "session-latest-turn" in tools++def test_inspect_pointer_is_not_a_spawn_in_local_action_set() -> None:"""The AI-Pointer tool is a router-tier read, never in the worker fast-path."""from jarvis.brain.factory import _load_local_action_tools@@ -1042,6 +1086,13 @@ def test_spawn_worker_in_router_tools() -> None:assert "spawn-worker" in ROUTER_TOOLS+def test_multi_spawn_not_in_router_tools() -> None:+ """The dead legacy fan-out tool must not compete with spawn-worker."""+ from jarvis.brain.factory import ROUTER_TOOLS++ assert "multi-spawn" not in ROUTER_TOOLS++@pytest.mark.parametrize("utterance",[@@ -1582,7 +1633,7 @@ def test_router_tools_is_pure_dispatcher_set() -> None:Welle-4-OpenClaw-Migration.Mandat-Phase-3 / Master-Plan §22 Z. 1617 (Baseline 2026-04-22):- vier Tools — run-shell, screen-snapshot, multi-spawn, spawn-worker.+ The historical baseline had four tools; multi-spawn is now retired.Welle-4-Migration: ``spawn-worker`` umbenannt auf ``spawn-worker``(siehe docs/openclaw-bridge.md §11). Heavy-Worker laeuft als externer@@ -1631,7 +1682,6 @@ def test_router_tools_is_pure_dispatcher_set() -> None:# Mandat-Phase-3 Baseline (Master-Plan §22)"run-shell","screen-snapshot",- "multi-spawn","spawn-worker",# NB: ``dispatch-to-harness`` was REMOVED from the LLM-visible router# set on 2026-06-28 (ADR-0011 amendment "dispatch-to-harness removal").diff --git a/tests/unit/brain/test_seed_history.py b/tests/unit/brain/test_seed_history.pyindex c635b3ac5a..ff8b4fd6b1 100644--- a/tests/unit/brain/test_seed_history.py+++ b/tests/unit/brain/test_seed_history.py@@ -14,6 +14,8 @@ Invariants:"""from __future__ import annotations+import pytest+from jarvis.brain.manager import BrainManagerfrom jarvis.core.bus import EventBusfrom jarvis.core.config import JarvisConfig@@ -90,3 +92,31 @@ def test_seeded_turns_visible_to_history_hints() -> None:joined = "\n".join(hints)assert "Paris." in joinedassert "capital of France" in joined+++async def test_generate_history_override_is_context_local(monkeypatch) -> None:+ manager = _bare_manager()+ manager.seed_history(+ [("user", "stale unrelated request"), ("assistant", "stale answer")]+ )+ realtime_history = (+ BrainMessage(role="user", content="The launch code name is Aurora."),+ BrainMessage(role="assistant", content="Understood."),+ )++ async def observe_context(_user_text, **_kwargs):+ assert "Aurora" in (manager._last_exchange_text() or "")+ assert "stale" not in "\n".join(manager._build_history_hints())+ return "observed"++ monkeypatch.setattr(manager, "_generate", observe_context)++ result = await manager.generate(+ "Write that to the wiki.",+ use_history=False,+ history_override=realtime_history,+ )++ assert result == "observed"+ assert manager._last_exchange_text() == "user: stale unrelated request\nassistant: stale answer"diff --git a/tests/unit/brain/test_wiki_fast_path.py b/tests/unit/brain/test_wiki_fast_path.pyindex 58c34f52ff..888a959954 100644--- a/tests/unit/brain/test_wiki_fast_path.py+++ b/tests/unit/brain/test_wiki_fast_path.py@@ -13,6 +13,7 @@ only after the write actually happened."""from __future__ import annotationsimport asyncio+from types import SimpleNamespacefrom typing import Anyimport pytest@@ -21,6 +22,7 @@ from jarvis.brain.manager import BrainManagerfrom jarvis.core.bus import EventBusfrom jarvis.core.config import JarvisConfigfrom jarvis.core.protocols import BrainMessage, ToolResult+from jarvis.sessions.store import SessionStoreclass FakeWikiIngestTool:@@ -226,8 +228,174 @@ async def test_anaphoric_command_without_usable_content_asks_what_to_write(manag], "no write happened, so nothing is announced"+async def test_latest_transcript_falls_back_to_active_persisted_session(+ manager_factory,+ monkeypatch,+ tmp_path,+):+ """An empty Realtime-owned history uses only its active persisted session."""+ from jarvis.core import runtime_refs++ store = SessionStore(tmp_path / "sessions.db")+ store.open()+ try:+ for session_id, turn_id, started_ms, user_text, jarvis_text in (+ (+ "active-session",+ "active-turn",+ 1_000,+ "The launch code name is Aurora.",+ "I will remember Aurora.",+ ),+ (+ "other-session",+ "other-turn",+ 2_000,+ "A different conversation contains private text.",+ "This must not cross session boundaries.",+ ),+ ):+ store.upsert_session(+ session_id=session_id,+ started_ms=started_ms,+ language="en",+ )+ store.upsert_turn(+ turn_id=turn_id,+ session_id=session_id,+ idx=0,+ started_ms=started_ms,+ )+ store.finalize_turn(+ turn_id=turn_id,+ ended_ms=started_ms + 100,+ user_text=user_text,+ user_lang="en",+ jarvis_text=jarvis_text,+ jarvis_lang="en",+ tier="realtime",+ provider="fake",+ model="fake-model",+ tokens_in=0,+ tokens_out=0,+ cost_usd=0.0,+ latency_total_ms=100,+ tool_calls=[],+ )++ pipeline = SimpleNamespace(+ voice_engine_status=lambda: {"session_id": "active-session"}+ )+ app = SimpleNamespace(state=SimpleNamespace(session_store=store))+ monkeypatch.setattr(runtime_refs, "get_speech_pipeline", lambda: pipeline)+ monkeypatch.setattr(runtime_refs, "get_web_app", lambda: app)++ tool = FakeWikiIngestTool(ToolResult(success=True, output="stored"))+ mgr, _executor, _bus = manager_factory(tools={"wiki-ingest": tool})+ mgr._history.clear()++ reply = await mgr._run_wiki_ingest_fast_path(+ "Write the latest transcript to the Wiki."+ )++ assert reply is not None+ await asyncio.sleep(0.05)+ assert len(tool.calls) == 1+ saved_text = tool.calls[0]["text"]+ assert "Aurora" in saved_text+ assert "different conversation" not in saved_text+ assert "cross session boundaries" not in saved_text+ finally:+ store.close()+++async def test_latest_transcript_never_uses_unscoped_persisted_history(+ manager_factory,+ monkeypatch,+ tmp_path,+):+ """Without a reliable active session id, persisted fallback stays closed."""+ from jarvis.core import runtime_refs++ store = SessionStore(tmp_path / "sessions.db")+ store.open()+ try:+ store.upsert_session(session_id="unrelated", started_ms=1_000, language="en")+ store.upsert_turn(+ turn_id="unrelated-turn",+ session_id="unrelated",+ idx=0,+ started_ms=1_000,+ )+ store.finalize_turn(+ turn_id="unrelated-turn",+ ended_ms=1_100,+ user_text="Never copy this unrelated transcript.",+ user_lang="en",+ jarvis_text="Unrelated answer.",+ jarvis_lang="en",+ tier="realtime",+ provider="fake",+ model="fake-model",+ tokens_in=0,+ tokens_out=0,+ cost_usd=0.0,+ latency_total_ms=100,+ tool_calls=[],+ )++ pipeline = SimpleNamespace(voice_engine_status=lambda: {"session_id": ""})+ app = SimpleNamespace(state=SimpleNamespace(session_store=store))+ monkeypatch.setattr(runtime_refs, "get_speech_pipeline", lambda: pipeline)+ monkeypatch.setattr(runtime_refs, "get_web_app", lambda: app)++ tool = FakeWikiIngestTool(ToolResult(success=True, output="stored"))+ mgr, _executor, _bus = manager_factory(tools={"wiki-ingest": tool})+ mgr._history.clear()++ reply = await mgr._run_wiki_ingest_fast_path(+ "Write the latest transcript to the Wiki."+ )++ assert reply is not None+ assert "wiki" in reply.lower()+ await asyncio.sleep(0.05)+ assert not tool.calls+ finally:+ store.close()++async def test_non_wiki_turn_returns_none(manager_factory):tool = FakeWikiIngestTool(ToolResult(success=True, output=""))mgr, executor, bus = manager_factory(tools={"wiki-ingest": tool})assert await mgr._run_wiki_ingest_fast_path("wie wird das wetter morgen?") is None # i18n-allowassert not tool.calls+++async def test_live_polite_travel_fact_reaches_wiki_before_local_action(+ manager_factory,+ monkeypatch,+):+ """The production utterance must never be reinterpreted as trip booking."""+ tool = FakeWikiIngestTool(+ ToolResult(success=True, output="Wiki ingest done:\n- applied: 1")+ )+ mgr, executor, bus = manager_factory(tools={"wiki-ingest": tool})++ async def fail_if_local_action_runs(*args, **kwargs):+ raise AssertionError("explicit wiki writes must precede local-action routing")++ monkeypatch.setattr(+ BrainManager,+ "_run_local_action_fast_path",+ fail_if_local_action_runs,+ )+ reply = await mgr.generate(+ "Kannst du bitte mein Wiki-System eintragen, dass ich morgen nach " # i18n-allow+ "San Francisco reisen will?" # i18n-allow: production transcript under test+ )++ assert reply+ await asyncio.sleep(0.05)+ assert len(tool.calls) == 1+ assert "san francisco" in tool.calls[0]["text"].lower()diff --git a/tests/unit/cli_ctl/test_commands_sessions.py b/tests/unit/cli_ctl/test_commands_sessions.pyindex eb67110cb3..9582cb2982 100644--- a/tests/unit/cli_ctl/test_commands_sessions.py+++ b/tests/unit/cli_ctl/test_commands_sessions.py@@ -18,6 +18,24 @@ def test_show(capture_api):assert capture_api["calls"][-1]["path"] == "/api/chats/text/c1"+def test_latest_turn(capture_api):+ result = runner.invoke(app, ["sessions", "latest-turn"])+ assert result.exit_code == 0+ call = capture_api["calls"][-1]+ assert call["method"] == "GET"+ assert call["path"] == "/api/sessions/latest-turn"+ assert call["query"] == {}+++def test_latest_turn_can_be_scoped_to_session(capture_api):+ result = runner.invoke(+ app,+ ["sessions", "latest-turn", "--session-id", "voice-1"],+ )+ assert result.exit_code == 0+ assert capture_api["calls"][-1]["query"] == {"session_id": "voice-1"}++def test_delete_requires_yes(capture_api):assert runner.invoke(app, ["sessions", "delete", "c1"]).exit_code == 1assert capture_api["calls"] == []diff --git a/tests/unit/cli_ctl/test_commands_wiki.py b/tests/unit/cli_ctl/test_commands_wiki.pyindex 668e7f5afb..c7364db9ae 100644--- a/tests/unit/cli_ctl/test_commands_wiki.py+++ b/tests/unit/cli_ctl/test_commands_wiki.py@@ -29,6 +29,37 @@ def test_vaults(capture_api):assert capture_api["calls"][-1]["path"] == "/api/setup/obsidian/vaults"+def test_ingest_sends_guarded_write_request(capture_api):+ result = runner.invoke(+ app,+ [+ "wiki",+ "ingest",+ "The user will travel to San Francisco tomorrow.",+ "--source",+ "test:cli",+ ],+ )+ assert result.exit_code == 0+ call = capture_api["calls"][-1]+ assert call["method"] == "POST"+ assert call["path"] == "/api/wiki/ingest"+ assert call["body"] == {+ "text": "The user will travel to San Francisco tomorrow.",+ "source": "test:cli",+ }+++def test_ingest_dry_run_sends_nothing(capture_api):+ result = runner.invoke(+ app,+ ["wiki", "ingest", "A durable statement for the Wiki.", "--dry-run"],+ )+ assert result.exit_code == 0+ assert capture_api["calls"] == []+ assert '"path": "/api/wiki/ingest"' in result.output++def test_reindex(capture_api):runner.invoke(app, ["wiki", "reindex"])call = capture_api["calls"][-1]diff --git a/tests/unit/core/test_capabilities.py b/tests/unit/core/test_capabilities.pyindex becf01e1c5..ff4549c1f3 100644--- a/tests/unit/core/test_capabilities.py+++ b/tests/unit/core/test_capabilities.py@@ -317,7 +317,6 @@ class TestSeedRegistry:"tool.screen-snapshot",# NB: tool.dispatch-to-harness removed 2026-06-28 (no longer an# LLM-visible router tool — phantom-openclaw routing fix).- "tool.multi-spawn","tool.spawn-worker","tool.dispatch-with-review","tool.awareness-snapshot",@@ -329,11 +328,26 @@ class TestSeedRegistry:):assert tool in ids, f"{tool!r} missing from seed"+ def test_polite_wiki_system_write_resolves_to_ingest(self) -> None:+ """Wiki destination wins even when the fact mentions travel."""+ cap = self.reg.resolve_intent(+ "Kannst du bitte mein Wiki-System eintragen, dass ich morgen nach " # i18n-allow+ "San Francisco reisen will?" # i18n-allow: production transcript under test+ )++ assert cap is not None+ assert cap.id == "tool.wiki-ingest"+def test_dispatch_to_harness_capability_removed(self) -> None:"""The dead dispatch-to-harness capability must not reappear (2026-06-28)."""ids = {c.id for c in self.reg.all()}assert "tool.dispatch-to-harness" not in ids+ def test_multi_spawn_capability_removed(self) -> None:+ """Parallel work is expressed through one supervised mission path."""+ ids = {c.id for c in self.reg.all()}+ assert "tool.multi-spawn" not in ids+def test_local_actions_present(self) -> None:ids = {c.id for c in self.reg.all()}for la in (@@ -379,7 +393,6 @@ class TestSeedRegistry:action_ids = {"tool.run-shell","tool.screen-snapshot",- "tool.multi-spawn","tool.spawn-worker","tool.dispatch-with-review","tool.run-skill",diff --git a/tests/unit/memory/wiki/test_consolidator.py b/tests/unit/memory/wiki/test_consolidator.pyindex 6a6f07e8f8..aec33631ff 100644--- a/tests/unit/memory/wiki/test_consolidator.py+++ b/tests/unit/memory/wiki/test_consolidator.py@@ -96,6 +96,9 @@ class FakeRegistry:def instantiate(self, name: str, **kwargs: Any) -> Any:return self._brain+ def available(self) -> set[str]:+ return {"gemini"}+def _config() -> JarvisConfig:return JarvisConfig(diff --git a/tests/unit/memory/wiki/test_provider_chain.py b/tests/unit/memory/wiki/test_provider_chain.pyindex e320a071cd..b9db4e11ba 100644--- a/tests/unit/memory/wiki/test_provider_chain.py+++ b/tests/unit/memory/wiki/test_provider_chain.py@@ -71,7 +71,8 @@ def test_keyless_primary_is_skipped_for_the_users_available_key() -> None:available={"openrouter", "nvidia"},credential_ready={"nvidia"},)- assert chain == [("nvidia", None)]+ assert [provider for provider, _model in chain] == ["nvidia"]+ assert chain[0][1] # fallback receives its own cheap provider-family modeldef test_credential_probe_uses_core_portable_storage_and_keeps_oauth(@@ -182,3 +183,59 @@ async def test_first_provider_success_does_not_try_others():assert result is not Noneassert result[1] == "gemini"assert reg.tried == ["gemini"] # no needless fallback calls+++class _TextBrain:+ def __init__(self, text: str) -> None:+ self._text = text++ def complete(self, request: Any): # noqa: ARG002+ async def _gen():+ yield self._text++ return _gen()+++class _ScriptedRegistry:+ def __init__(self, responses: dict[str, str]) -> None:+ self._responses = responses+ self.tried: list[str] = []++ def instantiate(self, name: str, **kwargs: Any) -> Any: # noqa: ARG002+ self.tried.append(name)+ return _TextBrain(self._responses[name])+++async def test_semantically_invalid_success_crosses_to_next_provider() -> None:+ reg = _ScriptedRegistry(+ {"openrouter": "not-json", "gemini": '[{"fact":"usable"}]'}+ )+ result = await complete_with_fallback(+ registry=reg,+ chain=[("openrouter", None), ("gemini", None)],+ request=object(),+ timeout_s=5.0,+ label="test",+ aggregate=_aggregate,+ validate=lambda agg: None if agg.text.startswith("[") else "malformed JSON",+ )++ assert result is not None+ assert result[1] == "gemini"+ assert reg.tried == ["openrouter", "gemini"]+++async def test_returns_none_when_every_provider_output_is_invalid() -> None:+ reg = _ScriptedRegistry({"openrouter": "bad", "gemini": "also bad"})+ result = await complete_with_fallback(+ registry=reg,+ chain=[("openrouter", None), ("gemini", None)],+ request=object(),+ timeout_s=5.0,+ label="test",+ aggregate=_aggregate,+ validate=lambda _agg: "malformed JSON",+ )++ assert result is None+ assert reg.tried == ["openrouter", "gemini"]diff --git a/tests/unit/memory/wiki/test_scheduler_journal_trigger.py b/tests/unit/memory/wiki/test_scheduler_journal_trigger.pyindex 890e8fcb53..ca9b21b054 100644--- a/tests/unit/memory/wiki/test_scheduler_journal_trigger.py+++ b/tests/unit/memory/wiki/test_scheduler_journal_trigger.py@@ -4,13 +4,18 @@ reviewed durable turn behind the general scheduler cooldown."""from __future__ import annotations+import asynciofrom pathlib import Pathimport pytestfrom jarvis.core.config import SchedulerConfigfrom jarvis.memory.wiki.lock import VaultLock-from jarvis.memory.wiki.scheduler import CuratorScheduler, TriggerSource+from jarvis.memory.wiki.scheduler import (+ CuratorScheduler,+ TriggerSource,+ fire_journal_trigger,+)class FakeCurator:@@ -65,6 +70,91 @@ async def test_journal_trigger_bypasses_cooldown(tmp_path: Path) -> None:assert consolidator.runs == 2+async def test_overlapping_journal_triggers_are_coalesced_not_lost(+ tmp_path: Path,+) -> None:+ entered = asyncio.Event()+ release = asyncio.Event()++ class _SlowConsolidator(FakeConsolidator):+ async def run_once(self) -> str:+ self.runs += 1+ if self.runs == 1:+ entered.set()+ await release.wait()+ return f"journal-batch:{self.runs}"++ consolidator = _SlowConsolidator()+ scheduler = _scheduler(tmp_path, consolidator=consolidator)+ first = asyncio.create_task(scheduler.trigger(TriggerSource.JOURNAL))+ await entered.wait()+ second = asyncio.create_task(scheduler.trigger(TriggerSource.JOURNAL))+ await asyncio.sleep(0)++ assert not second.done(), "the later trigger must wait instead of returning locked"+ release.set()+ first_result, second_result = await asyncio.gather(first, second)++ assert first_result.triggered is True+ assert second_result.triggered is True+ assert consolidator.runs == 2+++async def test_many_overlapping_journal_triggers_need_only_one_follow_up(+ tmp_path: Path,+) -> None:+ entered = asyncio.Event()+ release = asyncio.Event()++ class _SlowConsolidator(FakeConsolidator):+ async def run_once(self) -> str:+ self.runs += 1+ if self.runs == 1:+ entered.set()+ await release.wait()+ return f"journal-batch:{self.runs}"++ consolidator = _SlowConsolidator()+ scheduler = _scheduler(tmp_path, consolidator=consolidator)+ first = asyncio.create_task(scheduler.trigger(TriggerSource.JOURNAL))+ await entered.wait()+ followers = [+ asyncio.create_task(scheduler.trigger(TriggerSource.JOURNAL))+ for _ in range(25)+ ]+ await asyncio.sleep(0)++ release.set()+ results = await asyncio.gather(first, *followers)++ assert all(result.triggered for result in results)+ assert consolidator.runs == 2+++async def test_fire_and_forget_requests_share_one_task(tmp_path: Path) -> None:+ entered = asyncio.Event()+ release = asyncio.Event()++ class _SlowConsolidator(FakeConsolidator):+ async def run_once(self) -> str:+ self.runs += 1+ entered.set()+ await release.wait()+ return f"journal-batch:{self.runs}"++ scheduler = _scheduler(tmp_path, consolidator=_SlowConsolidator())+ first = fire_journal_trigger(scheduler)+ await entered.wait()+ second = fire_journal_trigger(scheduler)++ assert second is first+ release.set()+ await first++@pytest.mark.asyncioasync def test_journal_trigger_without_consolidator_skips(tmp_path: Path) -> None:scheduler = _scheduler(tmp_path, consolidator=None)diff --git a/tests/unit/memory/wiki/test_wiki_intent.py b/tests/unit/memory/wiki/test_wiki_intent.pyindex 8367726b7f..3a3ec52fea 100644--- a/tests/unit/memory/wiki/test_wiki_intent.py+++ b/tests/unit/memory/wiki/test_wiki_intent.py@@ -40,6 +40,62 @@ def test_inline_content_is_extracted(text, expected_fragment):assert expected_fragment in m.content.lower()[email protected](("text", "expected_fragment"), [+ (+ "Kannst du bitte mein Wiki-System eintragen, dass ich morgen nach " # i18n-allow+ "San Francisco reisen will?", # i18n-allow: production transcript under test+ "san francisco",+ ),+ (+ "Kannst du bitte in mein Wikisystem eintragen, dass mein Zug um acht fährt?", # i18n-allow+ "zug",+ ),+ (+ "Trag bitte ins Wiki ein, dass der Schlüssel heute rotiert wurde?", # i18n-allow+ "schluessel",+ ),+ (+ "Could you please add to my wiki that the deploy key rotated today?",+ "deploy key",+ ),+ (+ "Can you please enter in my wiki that the train leaves at eight?",+ "train",+ ),+ (+ "¿Puedes anotar en mi wiki que el vuelo sale el viernes?", # i18n-allow+ "vuelo",+ ),+])+def test_polite_question_commands_and_object_first_forms_match(+ text: str,+ expected_fragment: str,+) -> None:+ """Polite question grammar and terminal question marks remain writes."""+ match = match_wiki_intent(text)++ assert match is not None+ assert match.content is not None+ assert expected_fragment in match.content++[email protected]("text", [+ "Schreib die letzte Transkription ins Wikisystem.", # i18n-allow+ "Kannst du bitte die letzte Transkription in mein Wiki eintragen?", # i18n-allow+ (+ "Wenn du die letzte Transkription anschaust, kannst du bitte etwas " # i18n-allow+ "in dein Wikisystem eintragen?" # i18n-allow: reported production wording+ ),+ "Please write the previous turn into my wiki.",+ "Anota la ultima transcripcion en mi wiki.", # i18n-allow+])+def test_latest_transcript_reference_is_anaphoric(text: str) -> None:+ match = match_wiki_intent(text)++ assert match is not None+ assert match.content is None++@pytest.mark.parametrize("text", ["Was steht im Wiki über Joy?", # recall, not write # i18n-allow"Wie funktioniert ein Wiki?", # general question # i18n-allow@@ -55,6 +111,10 @@ def test_inline_content_is_extracted(text, expected_fragment):"Save me the trouble and tell me what's in the wiki about the server","Schreib mir, wenn du fertig bist, damit ich es ins Wiki eintragen kann", # i18n-allow"note down what the wiki says about the deploy key",+ "Kannst du mir sagen, was ich in mein Wiki eintragen soll?", # i18n-allow+ "Could you tell me what I should write in my wiki?",+ "¿Puedes decirme qué debo anotar en mi wiki?", # i18n-allow+ "What should I write in my wiki?",])def test_non_write_utterances_do_not_match(text):assert match_wiki_intent(text) is Nonediff --git a/tests/unit/plugins/tool/test_wiki_tools.py b/tests/unit/plugins/tool/test_wiki_tools.pyindex b094552a44..9f1c7b454e 100644--- a/tests/unit/plugins/tool/test_wiki_tools.py+++ b/tests/unit/plugins/tool/test_wiki_tools.py@@ -14,7 +14,6 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom pathlib import Path-from typing import Anyimport pytest@@ -22,7 +21,6 @@ from jarvis.brain.factory import ROUTER_TOOLSfrom jarvis.plugins.tool.wiki_ingest import WikiIngestToolfrom jarvis.plugins.tool.wiki_page_read import WikiPageReadTool-# ---------------------------------------------------------------------------# Shared fixtures# ---------------------------------------------------------------------------@@ -94,7 +92,8 @@ async def test_wiki_page_read_rejects_traversal(vault: Path) -> None:tool = WikiPageReadTool(vault_root=vault)result = await tool.execute({"path": "../etc/passwd"}, ctx=None)assert result.success is False- assert "vault-relative" in (result.error or "").lower() or "outside" in (result.error or "").lower()+ error = (result.error or "").lower()+ assert "vault-relative" in error or "outside" in error@pytest.mark.asyncio@@ -131,6 +130,7 @@ class _FakeWriteResult:applied: list[Path] = field(default_factory=list)skipped_due_to_recent_edit: list[Path] = field(default_factory=list)failed_validation: list[Path] = field(default_factory=list)+ blocked_pii: list[Path] = field(default_factory=list)backup_path: Path = field(default_factory=Path)@@ -248,6 +248,40 @@ async def test_wiki_ingest_reports_not_salient_when_no_updates() -> None:assert "not" in (result.error or "").lower() and "stored" in (result.error or "").lower()+async def test_wiki_ingest_does_not_claim_success_for_recent_edit_only() -> None:+ fake = _FakeCurator(+ result=_FakeWriteResult(+ skipped_due_to_recent_edit=[Path("people/joy.md")],+ )+ )+ tool = WikiIngestTool(curator_resolver=lambda: fake)++ result = await tool.execute(+ {"text": "Joy's birthday is August 14th."}, ctx=None,+ )++ assert result.success is False+ assert "recent user edit" in (result.error or "").lower()+++async def test_wiki_ingest_does_not_claim_success_for_sensitive_content_block() -> None:+ fake = _FakeCurator(+ result=_FakeWriteResult(+ blocked_pii=[Path("people/joy.md")],+ )+ )+ tool = WikiIngestTool(curator_resolver=lambda: fake)++ result = await tool.execute(+ {"text": "A complete statement containing protected data."}, ctx=None,+ )++ assert result.success is False+ assert "sensitive content" in (result.error or "").lower()++@pytest.mark.asyncioasync def test_wiki_ingest_surfaces_curator_exception_cleanly() -> None:fake = _FakeCurator(raise_on_ingest=RuntimeError("curator boom"))diff --git a/tests/unit/realtime/test_gemini_live.py b/tests/unit/realtime/test_gemini_live.pyindex 9b2b94ea0e..a8439a5af9 100644--- a/tests/unit/realtime/test_gemini_live.py+++ b/tests/unit/realtime/test_gemini_live.py@@ -186,7 +186,8 @@ async def test_explicit_reply_language_configures_gemini_speech(_model, config = holder["client"].aio.live.connect_calls[0]assert config.speech_config.language_code == "es"- await session.request_response() # Gemini auto-responds; the method is a no-op.+ # Gemini auto-responds; the required-tool hint remains a compatible no-op.+ await session.request_response(required_tool="jarvis_action")await session.close()@@ -209,6 +210,9 @@ async def test_tools_are_declared_mapped_and_answered(_model, config = holder["client"].aio.live.connect_calls[0]dumped = config.model_dump(exclude_none=True)assert dumped["tools"][0]["function_declarations"][0]["name"] == "open_app"+ # Gemini fixes tool declarations at connection time; accepting a live+ # update remains a safe no-op until the next session reconnects.+ await provider_session.update_session(tools=(declaration,))class FakeLiveSession:def __init__(self):diff --git a/tests/unit/realtime/test_openai_realtime.py b/tests/unit/realtime/test_openai_realtime.pyindex 41117e78ae..d18e9b99cd 100644--- a/tests/unit/realtime/test_openai_realtime.py+++ b/tests/unit/realtime/test_openai_realtime.py@@ -57,8 +57,8 @@ class _FakeConn:self.response_creates += 1self.response_create_payloads.append(kwargs)- async def _cancel_response(self, *, response_id: str) -> None:- self.response_cancels.append(response_id)+ async def _cancel_response(self, *, response_id: str | None = None) -> None:+ self.response_cancels.append(response_id or "<active>")class _FakeConnectCM:@@ -306,6 +306,142 @@ async def test_automatic_response_race_consumes_only_one_manual_allowance(await session.close()+async def test_interrupt_invalidates_late_events_from_cancelled_response(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ holder = _patch_openai_client(monkeypatch)+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(+ RealtimeSessionConfig()+ )+ conn = holder["client"].realtime.last_conn++ await session.request_response()+ old_marker = conn.response_create_payloads[0]["response"]["metadata"][+ "jarvis_request_id"+ ]+ await session._handle_response_created(+ SimpleNamespace(+ type="response.created",+ response=SimpleNamespace(+ id="resp-old",+ metadata={"jarvis_request_id": old_marker},+ ),+ )+ )+ await session.interrupt()+ await session.request_response()+ new_marker = conn.response_create_payloads[1]["response"]["metadata"][+ "jarvis_request_id"+ ]+ conn._events = iter(+ [+ SimpleNamespace(+ type="response.output_audio.delta",+ response_id="resp-old",+ item_id="item-old",+ delta=base64.b64encode(b"\x01\x00").decode("ascii"),+ ),+ SimpleNamespace(+ type="response.done",+ response=SimpleNamespace(id="resp-old"),+ ),+ SimpleNamespace(+ type="response.created",+ response=SimpleNamespace(+ id="resp-new",+ metadata={"jarvis_request_id": new_marker},+ ),+ ),+ SimpleNamespace(+ type="response.output_audio.delta",+ response_id="resp-new",+ item_id="item-new",+ delta=base64.b64encode(b"\x02\x00").decode("ascii"),+ ),+ SimpleNamespace(+ type="response.done",+ response=SimpleNamespace(id="resp-new"),+ ),+ ]+ )+ session._events = conn.__aiter__()++ events = [event async for event in session.receive()]++ assert [event.type for event in events] == ["audio_delta", "turn_complete"]+ assert events[0].audio.pcm == b"\x02\x00"+ assert conn.response_cancels == ["<active>"]+ await session.close()+++async def test_interrupt_invalidates_pending_response_before_created_event(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ holder = _patch_openai_client(monkeypatch)+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(+ RealtimeSessionConfig()+ )+ conn = holder["client"].realtime.last_conn++ await session.request_response()+ old_marker = conn.response_create_payloads[0]["response"]["metadata"][+ "jarvis_request_id"+ ]+ await session.interrupt()+ await session.request_response()+ new_marker = conn.response_create_payloads[1]["response"]["metadata"][+ "jarvis_request_id"+ ]+ conn._events = iter(+ [+ SimpleNamespace(+ type="response.created",+ response=SimpleNamespace(+ id="resp-old",+ metadata={"jarvis_request_id": old_marker},+ ),+ ),+ SimpleNamespace(+ type="response.output_audio.delta",+ response_id="resp-old",+ item_id="item-old",+ delta=base64.b64encode(b"OLD").decode("ascii"),+ ),+ SimpleNamespace(+ type="response.done",+ response=SimpleNamespace(id="resp-old"),+ ),+ SimpleNamespace(+ type="response.created",+ response=SimpleNamespace(+ id="resp-new",+ metadata={"jarvis_request_id": new_marker},+ ),+ ),+ SimpleNamespace(+ type="response.output_audio.delta",+ response_id="resp-new",+ item_id="item-new",+ delta=base64.b64encode(b"NEW").decode("ascii"),+ ),+ SimpleNamespace(+ type="response.done",+ response=SimpleNamespace(id="resp-new"),+ ),+ ]+ )+ session._events = conn.__aiter__()++ events = [event async for event in session.receive()]++ assert [event.type for event in events] == ["audio_delta", "turn_complete"]+ assert events[0].audio.pcm == b"NEW"+ assert conn.response_cancels == ["<active>", "resp-old"]+ await session.close()++@pytest.mark.asyncioasync def test_open_session_falls_back_to_adapter_default(monkeypatch: pytest.MonkeyPatch,@@ -432,7 +568,11 @@ async def test_tools_are_declared_mapped_and_answered(monkeypatch: pytest.Monkeyassert payload["tools"] == [{"type": "function", **declaration}]assert payload["tool_choice"] == "auto"- await session.request_response()+ await session.request_response(required_tool="open_app")+ assert conn.response_create_payloads[0]["response"]["tool_choice"] == {+ "type": "function",+ "name": "open_app",+ }marker = conn.response_create_payloads[0]["response"]["metadata"]["jarvis_request_id"]@@ -489,3 +629,25 @@ async def test_tools_are_declared_mapped_and_answered(monkeypatch: pytest.Monkeyassert conn.response_creates == 2assert conn.response_cancels == []await session.close()+++async def test_live_session_update_replaces_tool_declarations(+ monkeypatch: pytest.MonkeyPatch,+):+ holder = _patch_openai_client(monkeypatch)+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(+ RealtimeSessionConfig()+ )+ declaration = {+ "name": "new_tool",+ "description": "A newly connected tool.",+ "parameters": {"type": "object", "properties": {}},+ }++ await session.update_session(tools=(declaration,))++ update = holder["client"].realtime.last_conn.session_updates[-1]+ assert update["tools"] == [{"type": "function", **declaration}]+ assert update["tool_choice"] == "auto"+ await session.close()diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 1579b34187..9004f93821 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -10,6 +10,9 @@ from jarvis.realtime.session import RealtimeVoiceSessionclass FakeSession:session_id = "fake"+ supports_tool_updates = True+ creates_responses_automatically = False+ isolates_response_generations = Falsedef __init__(self, events):self._events = events@@ -18,6 +21,7 @@ class FakeSession:self.truncated = []self.session_updates = []self.response_requests = 0+ self.required_tools = []self.text_inputs = []self.interrupts = 0self.closed = False@@ -30,13 +34,14 @@ class FakeSession:yield evawait asyncio.sleep(0)- async def update_session(self, *, instructions=None, language=None):+ async def update_session(self, *, instructions=None, language=None, tools=None):self.session_updates.append(- {"instructions": instructions, "language": language}+ {"instructions": instructions, "language": language, "tools": tools})- async def request_response(self):+ async def request_response(self, *, required_tool=None):self.response_requests += 1+ self.required_tools.append(required_tool)async def send_text(self, text):self.text_inputs.append(text)@@ -140,6 +145,46 @@ class ToolResultGatedProvider(FakeProvider):return self.session+class AutomaticDelegateSession(FakeSession):+ """Emit one speculative native turn, then wait for trusted text input."""++ creates_responses_automatically = True++ def __init__(self, before_result, after_result):+ super().__init__([])+ self._before_result = before_result+ self._after_result = after_result+ self._trusted_text_sent = asyncio.Event()++ async def receive(self):+ for event in self._before_result:+ yield event+ await asyncio.sleep(0)+ await self._trusted_text_sent.wait()+ for event in self._after_result:+ yield event+ await asyncio.sleep(0)++ async def send_text(self, text):+ await super().send_text(text)+ self._trusted_text_sent.set()+++class AutomaticDelegateProvider(FakeProvider):+ def __init__(self, before_result, after_result):+ super().__init__([])+ self._before_result = before_result+ self._after_result = after_result++ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = AutomaticDelegateSession(+ self._before_result,+ self._after_result,+ )+ return self.session++class FailingProvider(FakeProvider):name = "failing-family"@@ -1195,11 +1240,16 @@ def _session(tool_bridge=None,tool_mode=None,jsons=None,+ binaries=None,bus=None,):return RealtimeVoiceSession(session_id="delegate-test",- send_binary=lambda _data: asyncio.sleep(0),+ send_binary=(+ (lambda data: binaries.append(data) or asyncio.sleep(0))+ if binaries is not None+ else (lambda _data: asyncio.sleep(0))+ ),send_json=((lambda m: jsons.append(m) or asyncio.sleep(0))if jsons is not None@@ -1224,6 +1274,213 @@ async def test_delegate_mode_declares_single_action_function():assert _tool_names(provider.opened_with) == ["jarvis_action", "end_call"]assert "jarvis_action" in provider.opened_with.instructions+ assert "private or personal memory" in provider.opened_with.instructions+ assert "MCPs" in provider.opened_with.instructions+++ "utterance",+ [+ "Who is my best friend?",+ "Was weißt du über mich?", # i18n-allow: German speech-input fixture+ "Which MCPs and CLIs are installed?",+ "¿Qué herramientas están conectadas?", # i18n-allow: Spanish speech-input fixture+ "Write that to the wiki.",+ "Write the last transcript to the wiki.",+ "Kannst du bitte mein Wiki-System eintragen, dass ich morgen nach " # i18n-allow: German speech-input fixture+ "San Francisco reisen will?", # i18n-allow: German speech-input fixture+ ],+)+async def test_local_evidence_turns_run_deterministic_jarvis_action(utterance):+ brain = FakeBrain()+ provider = FakeProvider(+ [RealtimeEvent(type="input_transcript", text=utterance, is_final=True)]+ )+ sess = _session(provider, brain=brain)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await asyncio.sleep(0.12)++ assert provider.session.required_tools == []+ assert brain.calls[0][0] == utterance+ assert provider.session.text_inputs+ assert "<trusted_action_result>" in provider.session.text_inputs[-1]+ update = provider.session.session_updates[-1]["instructions"]+ assert "orchestrator is handling this current turn" in update+ await sess.end(reason="test")+++async def test_general_knowledge_turn_keeps_native_realtime_answering():+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="What is the capital of France?",+ is_final=True,+ )+ ]+ )+ sess = _session(provider, brain=FakeBrain())++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()++ assert provider.session.required_tools == [None]+ await sess.end(reason="test")+++async def test_automatic_provider_wiki_turn_runs_brain_without_tool_call():+ brain = FakeBrain(replies=("The Wiki entry was saved.",))+ speculative_audio = AudioChunk(+ pcm=b"\x01\x02" * 8,+ sample_rate=24_000,+ timestamp_ns=0,+ )+ provider = AutomaticDelegateProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="Write the travel plan to my wiki.",+ is_final=True,+ ),+ RealtimeEvent(type="audio_delta", audio=speculative_audio),+ RealtimeEvent(+ type="output_transcript_delta",+ text="I do not have access to your Wiki.",+ ),+ RealtimeEvent(type="audio_delta", audio=speculative_audio),+ RealtimeEvent(type="turn_complete"),+ ],+ [+ RealtimeEvent(+ type="output_transcript_delta",+ text="The Wiki entry was saved.",+ ),+ RealtimeEvent(type="turn_complete"),+ ],+ )+ jsons = []+ binaries = []+ sess = _session(+ provider,+ brain=brain,+ jsons=jsons,+ binaries=binaries,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()++ assert [call[0] for call in brain.calls] == [+ "Write the travel plan to my wiki."+ ]+ assistant_text = "".join(+ str(message.get("text", ""))+ for message in jsons+ if message.get("role") == "assistant"+ )+ assert assistant_text == "The Wiki entry was saved."+ assert provider.session.tool_results == []+ assert len(provider.session.text_inputs) == 1+ assert binaries == []+ await sess.end(reason="test")+++async def test_multi_final_transcript_waits_for_provider_turn_boundary():+ brain = FakeBrain(replies=("Stored the complete travel plan.",))++ class _DelayedFinalSession(AutomaticDelegateSession):+ async def receive(self):+ yield RealtimeEvent(+ type="input_transcript",+ text="Write this to my wiki",+ is_final=True,+ )+ await asyncio.sleep(0.12)+ yield RealtimeEvent(+ type="input_transcript",+ text="that I travel to San Francisco tomorrow",+ is_final=True,+ )+ yield RealtimeEvent(type="turn_complete")+ await self._trusted_text_sent.wait()+ yield RealtimeEvent(type="turn_complete")++ class _DelayedFinalProvider(FakeProvider):+ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = _DelayedFinalSession([], [])+ return self.session++ provider = _DelayedFinalProvider([])+ sess = _session(provider, brain=brain)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await asyncio.sleep(0.2)++ assert brain.calls[0][0] == (+ "Write this to my wiki that I travel to San Francisco tomorrow"+ )+ await sess.end(reason="test")+++async def test_barge_in_detaches_late_delegate_result_from_new_turn():+ gate = asyncio.Event()+ brain = FakeBrain(replies=("Old Wiki action completed.",), gate=gate)++ class _BargeSession(FakeSession):+ async def receive(self):+ yield RealtimeEvent(+ type="input_transcript",+ text="Write this to my wiki.",+ is_final=True,+ )+ while not brain.calls:+ await asyncio.sleep(0.005)+ yield RealtimeEvent(type="speech_started")+ yield RealtimeEvent(+ type="input_transcript",+ text="What time is it?",+ is_final=True,+ )+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(+ pcm=b"\x01\x02" * 8,+ sample_rate=24_000,+ timestamp_ns=0,+ ),+ )++ class _BargeProvider(FakeProvider):+ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = _BargeSession([])+ return self.session++ provider = _BargeProvider([])+ binaries = []+ sess = _session(provider, brain=brain, binaries=binaries)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ new_turn_id = sess._turn_id+ gate.set()+ await asyncio.sleep(0.1)++ assert new_turn_id+ assert sess._last_user_text == "What time is it?"+ assert provider.session.text_inputs == []+ assert provider.session.tool_results == []+ assert binaries == []+ await sess.end(reason="test")@pytest.mark.asyncio@@ -1244,6 +1501,32 @@ async def test_direct_mode_builds_bridge_from_brain():assert "jarvis_action" not in names+async def test_direct_mode_pushes_live_brain_tool_replacements_to_provider():+ brain = FakeBrain()+ brain._tools = {"old_tool": _StubTool()}+ brain._tool_executor_ref = _StubExecutor()+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="Which tools are available?",+ is_final=True,+ )+ ]+ )+ sess = _session(provider, brain=brain, tool_mode="direct")++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ brain._tools = {"new_tool": _StubTool()}+ await sess.wait_finished()++ assert _tool_names(provider.opened_with) == ["old_tool", "end_call"]+ updated_tools = provider.session.session_updates[-1]["tools"]+ assert [item["name"] for item in updated_tools] == ["new_tool", "end_call"]+ await sess.end(reason="test")++@pytest.mark.asyncioasync def test_explicit_bridge_wins_over_delegate_mode():provider = FakeProvider([RealtimeEvent(type="turn_complete")])@@ -1290,6 +1573,8 @@ async def test_delegate_call_dispatches_raw_transcript_with_voice_confirm():"allow_voice_confirm": True,"prefer_tool_model": True,"publish_response": False,+ "use_history": False,+ "history_override": (),},)]@@ -1303,6 +1588,82 @@ async def test_delegate_call_dispatches_raw_transcript_with_voice_confirm():await sess.end(reason="test")+async def test_delegate_uses_only_bounded_current_realtime_history():+ brain = FakeBrain(replies=("Saved.",))+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="The launch code name is Aurora.",+ is_final=True,+ ),+ RealtimeEvent(type="output_transcript_delta", text="Understood."),+ RealtimeEvent(type="turn_complete"),+ RealtimeEvent(+ type="input_transcript",+ text="Write that to the wiki.",+ is_final=True,+ ),+ RealtimeEvent(+ type="tool_call",+ call_id="history-1",+ tool_name="jarvis_action",+ tool_args={"request": "Write that to the wiki."},+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ sess = _session(provider, brain=brain)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await asyncio.sleep(0.02)++ text, kwargs = brain.calls[0]+ assert text == "Write that to the wiki."+ assert kwargs["use_history"] is False+ assert [(item.role, item.content) for item in kwargs["history_override"]] == [+ ("user", "The launch code name is Aurora."),+ ("assistant", "Understood."),+ ]+ await sess.end(reason="test")+++async def test_native_mission_claim_is_withheld_for_trusted_brain_result():+ jsons = []+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="Start an agent to create the report.",+ is_final=True,+ ),+ RealtimeEvent(+ type="output_transcript_delta",+ text="I started the mission successfully.",+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ sess = _session(provider, brain=FakeBrain(), jsons=jsons)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()++ assistant_text = "".join(+ str(message.get("text", ""))+ for message in jsons+ if message.get("role") == "assistant"+ )+ assert "started the mission" not in assistant_text+ assert provider.session.tool_results == []+ assert provider.session.text_inputs+ assert "<trusted_action_result>\ndone\n" in provider.session.text_inputs[-1]+ await sess.end(reason="test")++@pytest.mark.asyncioasync def test_delegate_turn_publishes_only_the_spoken_realtime_response():bus = FakeBus()@@ -1558,6 +1919,44 @@ async def test_delegate_does_not_block_pump():await sess.end(reason="test")+async def test_turn_complete_waits_for_slow_delegate_task_on_same_turn():+ gate = asyncio.Event()+ brain = FakeBrain(replies=("Completed on the original turn.",), gate=gate)+ provider = FakeProvider(+ [+ RealtimeEvent(type="input_transcript", text="do it", is_final=True),+ RealtimeEvent(+ type="tool_call",+ call_id="slow-same-turn",+ tool_name="jarvis_action",+ tool_args={"request": "do it"},+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ sess = _session(provider, brain=brain)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ original_turn_id = sess._turn_id++ assert original_turn_id+ assert original_turn_id in sess._delegate_turns+ assert sess._last_user_text == "do it"+ assert sess._turn_has_pending_delegate(original_turn_id) is True++ gate.set()+ await asyncio.sleep(0.02)++ assert sess._turn_id == original_turn_id+ assert sess._delegate_turns[original_turn_id].last_reply == (+ "Completed on the original turn."+ )+ assert provider.session.tool_results[0][0] == "slow-same-turn"+ await sess.end(reason="test")++@pytest.mark.asyncioasync def test_delegate_timeout_sends_honest_failure(monkeypatch):monkeypatch.setattr("jarvis.realtime.session._DELEGATE_TIMEOUT_S", 0.05)diff --git a/tests/unit/realtime/test_tools.py b/tests/unit/realtime/test_tools.pyindex ffd90919c4..a4aa18cebd 100644--- a/tests/unit/realtime/test_tools.py+++ b/tests/unit/realtime/test_tools.py@@ -159,3 +159,60 @@ def test_bridge_declarations_keep_the_full_json_schema() -> None:declaration = bridge.declarations[0]assert declaration["parameters"]["additionalProperties"] is False+++async def test_bridge_refreshes_replaced_brain_tools_and_denies_removed_tool():+ executor = FakeExecutor()+ old_tool = FakeTool("old_tool")+ new_tool = FakeTool("new_tool")+ brain = SimpleNamespace(+ _tools={"old_tool": old_tool},+ _tool_executor_ref=executor,+ )+ bridge = RealtimeToolBridge.from_brain(brain, language="en")+ assert bridge is not None++ brain._tools = {"new_tool": new_tool}++ assert bridge.refresh_from_source() is True+ assert [item["name"] for item in bridge.declarations] == ["new_tool"]+ _name, removed = await bridge.execute(+ wire_name="old_tool", arguments={"app_name": "Calculator"}+ )+ _name, added = await bridge.execute(+ wire_name="new_tool", arguments={"app_name": "Calculator"}+ )+ assert removed["success"] is False+ assert added["success"] is True+++async def test_bridge_refresh_retains_a_tool_awaiting_voice_confirmation():+ executor = FakeExecutor(confirmation_required=True)+ pending_tool = FakeTool("pending_tool")+ brain = SimpleNamespace(+ _tools={"pending_tool": pending_tool},+ _tool_executor_ref=executor,+ )+ bridge = RealtimeToolBridge.from_brain(brain, language="en")+ assert bridge is not None+ await bridge.handle_user_transcript("Open Calculator")+ await bridge.execute(+ wire_name="pending_tool", arguments={"app_name": "Calculator"}+ )++ brain._tools = {"new_tool": FakeTool("new_tool")}+ assert bridge.refresh_from_source() is True+ assert {item["name"] for item in bridge.declarations} == {+ "new_tool",+ "pending_tool",+ }++ await bridge.handle_user_transcript("Yes")+ _name, result = await bridge.execute(+ wire_name="pending_tool", arguments={"app_name": "Calculator"}+ )+ assert result["success"] is True+ assert bridge.refresh_from_source() is True+ assert [item["name"] for item in bridge.declarations] == ["new_tool"]diff --git a/tests/unit/realtime/test_transcript_persistence.py b/tests/unit/realtime/test_transcript_persistence.pyindex 79cb67ada7..d42426a20d 100644--- a/tests/unit/realtime/test_transcript_persistence.py+++ b/tests/unit/realtime/test_transcript_persistence.py@@ -189,6 +189,21 @@ async def test_every_realtime_surface_provider_and_tool_mode_persists_complete_ttool_mode: str,) -> None:events, expected_user, raw_parts = _provider_events(provider_name)+ if tool_mode == "delegate":+ output_index = next(+ index+ for index, event in enumerate(events)+ if event.type == "output_transcript_delta"+ )+ events.insert(+ output_index,+ RealtimeEvent(+ type="tool_call",+ call_id="matrix-delegate",+ tool_name="jarvis_action",+ tool_args={"request": expected_user},+ ),+ )provider = FakeRealtimeProvider(provider_name, events)store = SessionStore(tmp_path / "sessions.db")store.open()diff --git a/tests/unit/ui/web/test_sessions_routes.py b/tests/unit/ui/web/test_sessions_routes.pyindex 779667fabe..d3573b1f43 100644--- a/tests/unit/ui/web/test_sessions_routes.py+++ b/tests/unit/ui/web/test_sessions_routes.py@@ -79,3 +79,66 @@ def test_save_session_to_downloads_uses_events_for_plain_export(tmp_path, monkey)finally:store.close()+++def test_latest_turn_returns_newest_persisted_user_transcript(tmp_path) -> None:+ store = SessionStore(tmp_path / "sessions.db")+ store.open()+ try:+ _seed_session(store)+ store.upsert_session(session_id="s2", started_ms=5_000, language="en")+ store.upsert_turn(+ turn_id="t2",+ session_id="s2",+ idx=0,+ started_ms=5_100,+ )+ store.finalize_turn(+ turn_id="t2",+ ended_ms=5_500,+ user_text="The newest persisted transcript.",+ user_lang="en",+ jarvis_text="Acknowledged.",+ jarvis_lang="en",+ tier="fast",+ provider="fake",+ model="fake-model",+ tokens_in=0,+ tokens_out=0,+ cost_usd=0.0,+ latency_total_ms=400,+ tool_calls=[],+ )++ app = FastAPI()+ app.include_router(sessions_routes.router)+ app.state.session_store = store+ with TestClient(app) as client:+ newest = client.get("/api/sessions/latest-turn")+ scoped = client.get(+ "/api/sessions/latest-turn", params={"session_id": "s1"}+ )++ assert newest.status_code == 200+ assert newest.json()["id"] == "t2"+ assert newest.json()["user_text"] == "The newest persisted transcript."+ assert scoped.status_code == 200+ assert scoped.json()["id"] == "t1"+ finally:+ store.close()+++def test_latest_turn_returns_404_when_no_user_transcript_exists(tmp_path) -> None:+ store = SessionStore(tmp_path / "sessions.db")+ store.open()+ try:+ app = FastAPI()+ app.include_router(sessions_routes.router)+ app.state.session_store = store+ with TestClient(app) as client:+ response = client.get("/api/sessions/latest-turn")++ assert response.status_code == 404+ assert response.json()["detail"] == "user-turn-not-found"+ finally:+ store.close()diff --git a/tests/unit/ui/web/test_tools_routes.py b/tests/unit/ui/web/test_tools_routes.pynew file mode 100644index 0000000000..ba527f74eb--- /dev/null+++ b/tests/unit/ui/web/test_tools_routes.py@@ -0,0 +1,56 @@+"""The tools endpoint reports the BrainManager's effective live surface."""+from __future__ import annotations++from types import SimpleNamespace++from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.ui.web.tools_routes import router+++def _tool(name: str) -> SimpleNamespace:+ return SimpleNamespace(+ name=name,+ description=f"{name} description",+ risk_tier="monitor",+ schema={"type": "object"},+ )+++def test_lists_effective_brain_tools_not_partial_mcp_registry() -> None:+ app = FastAPI()+ app.include_router(router)+ app.state.brain = SimpleNamespace(+ _tools={+ "wiki-recall": _tool("wiki-recall"),+ "cli_gh": _tool("cli_gh"),+ "notebooklm-mcp/search": _tool("notebooklm-mcp/search"),+ }+ )+ app.state.tool_registry = {"partial/only": _tool("partial/only")}++ with TestClient(app) as client:+ body = client.get("/api/tools").json()++ assert body["total"] == 3+ assert {item["name"] for item in body["tools"]} == {+ "wiki-recall",+ "cli_gh",+ "notebooklm-mcp/search",+ }+ assert body["by_source"] == {"mcp": 1, "cli": 1, "native": 1}+++def test_falls_back_to_user_mcp_registry_before_brain_ready() -> None:+ app = FastAPI()+ app.include_router(router)+ app.state.brain = None+ app.state.tool_registry = {"weather/search": _tool("weather/search")}++ with TestClient(app) as client:+ body = client.get("/api/tools").json()++ assert body["total"] == 1+ assert body["tools"][0]["name"] == "weather/search"+ assert body["by_source"]["mcp"] == 1diff --git a/tests/unit/ui/web/test_wiki_routes.py b/tests/unit/ui/web/test_wiki_routes.pyindex 1364f99ebd..60c83cf42f 100644--- a/tests/unit/ui/web/test_wiki_routes.py+++ b/tests/unit/ui/web/test_wiki_routes.py@@ -16,14 +16,22 @@ import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from jarvis.ui.web import wiki_routesfrom jarvis.ui.web.wiki_routes import router as wiki_router-# ----------------------------------------------------------------------# Fixtures# ----------------------------------------------------------------------[email protected](autouse=True)+def _isolate_wiki_health(monkeypatch: pytest.MonkeyPatch) -> None:+ """Keep process-wide Wiki health mutations local to each route test."""+ from jarvis.memory.wiki.health import WikiHealth++ monkeypatch.setattr("jarvis.memory.wiki.health.health", WikiHealth())++def _make_app(vault_root: Path | None) -> FastAPI:"""Build a minimal FastAPI app with the wiki router mounted.@@ -81,7 +89,10 @@ def populated_vault(tmp_path: Path) -> Path:"entities","harald",page_type="entity",- body="# Harald\n\n## Summary\nHarald is a person born in 1976.\n\n## Facts\n- Born in 1976.\n",+ body=(+ "# Harald\n\n## Summary\nHarald is a person born in 1976.\n\n"+ "## Facts\n- Born in 1976.\n"+ ),)_write_page(vault,@@ -113,6 +124,16 @@ def empty_vault(tmp_path: Path) -> Path:return vault+class _FakeCurator:+ def __init__(self, result: object) -> None:+ self.result = result+ self.calls: list[tuple[str, str]] = []++ async def ingest(self, text: str, source: str) -> object:+ self.calls.append((text, source))+ return self.result++# ----------------------------------------------------------------------# /tree# ----------------------------------------------------------------------@@ -373,6 +394,95 @@ def test_search_k_parameter_caps_results(populated_vault: Path) -> None:assert len(body["hits"]) <= 1+# ----------------------------------------------------------------------+# /ingest+# ----------------------------------------------------------------------+++def test_ingest_writes_through_shared_curator_service(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ page = tmp_path / "vault" / "entities" / "traveler.md"+ curator = _FakeCurator(+ SimpleNamespace(+ applied=[page],+ skipped_due_to_recent_edit=[],+ failed_validation=[],+ blocked_pii=[],+ )+ )+ monkeypatch.setattr(wiki_routes, "get_running_curator", lambda: curator)++ with TestClient(_make_app(tmp_path / "vault")) as client:+ response = client.post(+ "/api/wiki/ingest",+ json={+ "text": "The user will travel to San Francisco tomorrow.",+ "source": "test:explicit",+ },+ )++ assert response.status_code == 200+ assert response.json() == {+ "ok": True,+ "source": "test:explicit",+ "applied": 1,+ "skipped_due_to_recent_edit": 0,+ "failed_validation": 0,+ "blocked_sensitive_content": 0,+ "pages_touched": ["traveler.md"],+ }+ assert curator.calls == [+ ("The user will travel to San Francisco tomorrow.", "test:explicit")+ ]+++def test_ingest_returns_non_success_when_curator_writes_nothing(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ curator = _FakeCurator(+ SimpleNamespace(+ applied=[],+ skipped_due_to_recent_edit=[],+ failed_validation=[],+ blocked_pii=[],+ )+ )+ monkeypatch.setattr(wiki_routes, "get_running_curator", lambda: curator)++ with TestClient(_make_app(tmp_path / "vault")) as client:+ response = client.post(+ "/api/wiki/ingest",+ json={"text": "A complete but non-salient statement."},+ )++ assert response.status_code == 422+ assert response.json()["detail"]["code"] == "nothing-stored"+++def test_ingest_returns_503_without_live_curator(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(wiki_routes, "get_running_curator", lambda: None)++ with TestClient(_make_app(tmp_path / "vault")) as client:+ response = client.post(+ "/api/wiki/ingest",+ json={"text": "A complete statement for the knowledge Wiki."},+ )++ assert response.status_code == 503+ assert response.json()["detail"]["code"] == "not-bootstrapped"+++def test_ingest_openapi_declares_monitor_risk() -> None:+ operation = _make_app(None).openapi()["paths"]["/api/wiki/ingest"]["post"]+ assert operation["x-jarvis-risk-tier"] == "monitor"++# ----------------------------------------------------------------------# /reindex# ----------------------------------------------------------------------