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(tools): stop intermittent "tool not available" from boot races
Ruben Lütkee929d6da17b8
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex e3d80ea5c2..fff9f0e840 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -78,6 +78,7 @@ from jarvis.safety.tool_executor import ToolExecutorfrom jarvis.brain.provider_test import BILLING_LIMIT_MARKERSfrom .dispatcher import BrainDispatcher+from .tool_surface import maybe_reconcile_tool_surface, stamp_tool_surfacefrom .intent_router import RoutingDecision, classifyfrom .local_action_gate import (HARNESS_NAME,@@ -6669,6 +6670,14 @@ class BrainManager:self._active_turn_identity = Noneturn_trace_id = trace_id or uuid4()+ # Tool-surface self-heal (live 2026-07-13): a source that connects+ # AFTER the boot's last BrainToolsChanged — or whose event is lost to a+ # wedged plugin bootstrap — otherwise stays invisible for the WHOLE+ # session and the model refuses with "tool not available". Cheap+ # names-only drift check against the live CLI/plugin/MCP caches; one+ # refresh_tools() when they diverge. Never raises.+ maybe_reconcile_tool_surface(self)+# auto mode: resolve this turn's language so _reply_language_directive()# hard-pins it (a soft "mirror" drifts to German on tool-synthesis# turns — live bug 2026-06-14: an English weather turn answered in@@ -8290,6 +8299,10 @@ class BrainManager:old_count = len(self._tools)self._tools = new_toolsself._local_action_tools = new_local_action_tools+ # Record what the sources looked like at THIS load, so the per-turn+ # reconcile (tool_surface.maybe_reconcile_tool_surface) only fires on+ # genuine drift after a missed BrainToolsChanged.+ stamp_tool_surface(self)log.info("Tool-Registry refreshed: %d -> %d tools",old_count, len(new_tools),diff --git a/jarvis/brain/tool_surface.py b/jarvis/brain/tool_surface.pynew file mode 100644index 0000000000..6f86217348--- /dev/null+++ b/jarvis/brain/tool_surface.py@@ -0,0 +1,125 @@+"""Tool-surface fingerprint + self-heal reconcile for the BrainManager.++The BrainManager's tool snapshot is refreshed event-driven: a CLI, plugin, or+MCP source that connects publishes ``BrainToolsChanged`` and the manager+reloads. Event-driven alone is fragile — a source that becomes ready AFTER the+last refresh of a boot, or whose completion event is lost (a wedged plugin+bootstrap, live 2026-07-13), leaves the snapshot stale for the WHOLE session.+The model then refuses with "tool not available" while the very same request+works after the next restart — the intermittent-availability bug class.++``maybe_reconcile_tool_surface`` runs at the head of every turn: it compares a+cheap names-only fingerprint of the live sources (in-process caches, no IO, no+LLM — AP-11 safe) against the fingerprint stamped at the last tool load, and+triggers one ``refresh_tools()`` on drift. Whatever upstream event went+missing, the tool surface converges at the next turn.+"""+from __future__ import annotations++import logging++log = logging.getLogger(__name__)+++def live_tool_surface_fingerprint() -> frozenset[str] | None:+ """Names-only snapshot of the dynamic tool sources (CLI / plugin / MCP).++ Reads the shared in-process registries' caches synchronously — never+ starts a client, never awaits network IO — so it is cheap enough for the+ per-turn hot path. Each source is guarded on its own: a broken source+ contributes nothing but never blinds the others. Returns ``None`` when no+ source registry is reachable at all (headless test builds), which disables+ the reconcile instead of comparing empty-vs-empty forever.+ """+ readable = False+ names: set[str] = set()++ try:+ from jarvis.clis.shared import get_active_registry++ cli_registry = get_active_registry()+ if cli_registry is not None:+ readable = True+ for tool in cli_registry.active_tools():+ names.add(f"cli:{getattr(tool, 'name', '')}")+ except Exception: # noqa: BLE001 — one source must never blind the rest+ log.debug("tool-surface: CLI source read failed", exc_info=True)++ try:+ from jarvis.marketplace.plugin_shared import get_active_plugin_registry++ plugin_registry = get_active_plugin_registry()+ if plugin_registry is not None:+ readable = True+ for tool in plugin_registry.active_tools():+ names.add(f"plugin:{getattr(tool, 'name', '')}")+ except Exception: # noqa: BLE001+ log.debug("tool-surface: plugin source read failed", exc_info=True)++ try:+ from jarvis.core import runtime_refs++ mcp_registry = runtime_refs.get_mcp_registry()+ if mcp_registry is not None:+ readable = True+ for server_name, client in mcp_registry.active_clients().items():+ for tool_def in getattr(client, "_tools_cache", None) or []:+ tool_name = (+ tool_def.get("name") if isinstance(tool_def, dict) else None+ )+ if tool_name:+ names.add(f"mcp:{server_name}:{tool_name}")+ except Exception: # noqa: BLE001+ log.debug("tool-surface: MCP source read failed", exc_info=True)++ if not readable:+ return None+ return frozenset(names)+++def stamp_tool_surface(manager) -> None:+ """Record the sources' fingerprint on the manager after a tool load."""+ try:+ manager._tool_surface_fp = live_tool_surface_fingerprint()+ except Exception: # noqa: BLE001 — stamping must never break a load+ log.debug("tool-surface: stamp failed", exc_info=True)+++def maybe_reconcile_tool_surface(manager) -> None:+ """Self-heal a stale tool snapshot before the turn touches tools.++ Never raises: any fault degrades to "no reconcile this turn" — the+ event-driven refresh path stays authoritative and untouched.+ """+ try:+ fingerprint = live_tool_surface_fingerprint()+ if fingerprint is None:+ return+ previous = getattr(manager, "_tool_surface_fp", None)+ if previous is None:+ # First observation: adopt without a refresh — at this point the+ # event-driven path has had no chance to be missed yet.+ manager._tool_surface_fp = fingerprint+ return+ if fingerprint == previous:+ return+ log.warning(+ "tool-surface drift: +%d/-%d source tools since the last load — "+ "refreshing the brain tool registry",+ len(fingerprint - previous),+ len(previous - fingerprint),+ )+ # Stamp BEFORE the refresh: refresh_tools() re-stamps on success, and+ # if it early-outs (no tier yet) this still prevents a warning storm —+ # the next genuine drift re-triggers.+ manager._tool_surface_fp = fingerprint+ manager.refresh_tools()+ except Exception: # noqa: BLE001 — reconcile must never break a turn+ log.debug("tool-surface reconcile failed", exc_info=True)+++__all__ = [+ "live_tool_surface_fingerprint",+ "maybe_reconcile_tool_surface",+ "stamp_tool_surface",+]diff --git a/jarvis/marketplace/plugin_registry.py b/jarvis/marketplace/plugin_registry.pyindex 72dec98bf1..0722a47c47 100644--- a/jarvis/marketplace/plugin_registry.py+++ b/jarvis/marketplace/plugin_registry.py@@ -13,8 +13,10 @@ graceful-degradation doctrine).from __future__ import annotationsimport asyncio+import dataclassesimport logging-from typing import Any, Callable+from collections.abc import Callable+from typing import Anyfrom jarvis.marketplace.catalog import PluginCatalog, PluginSpecfrom jarvis.marketplace.catalog_data import load_catalog@@ -53,6 +55,34 @@ def _deregister_plugin_capability(cap_registry, plugin_id) -> None:cap_registry.deregister(f"{PAIRED_CAP_PREFIX}{plugin_id}")+# Upper bound for one plugin's connect (transport handshake + list_tools).+# A wedged remote handshake must degrade to a per-plugin connect error, never+# stall the bootstrap loop: live 2026-07-13, mcp.linear.app answered a stale+# token with 401 and then never completed the stream — bootstrap hung there on+# every boot, so the completion BrainToolsChanged never fired and the github+# plugin's tools only reached the brain when their connect happened to beat+# the last unrelated tool refresh (the intermittent "tool not available" bug).+_CONNECT_TIMEOUT_S_DEFAULT = 15.0+++def _connect_needs_reauth(message: str) -> bool:+ """True iff a connect failure indicates a dead credential, not a flaky host.++ Reuses the refresh scheduler's canonical OAuth marker list and adds the+ connect-time shapes (an HTTP 401/unauthorized on the MCP endpoint itself).+ Conservative on purpose: 'Connection closed', timeouts, and 5xx stay+ retryable so one flaky boot never flags a healthy plugin."""+ try:+ from jarvis.marketplace.refresh_scheduler import _refresh_needs_reauth++ if _refresh_needs_reauth(message):+ return True+ except Exception: # noqa: BLE001 — classifier is best-effort+ log.debug("connect reauth classifier unavailable", exc_info=True)+ m = message.lower()+ return "401" in m or "unauthorized" in m or "invalid_token" in m++class PluginToolRegistry:def __init__(self,@@ -62,12 +92,14 @@ class PluginToolRegistry:client_factory: Callable[..., Any] | None = None,bus: Any = None,default_risk_tier: str = "monitor",+ connect_timeout_s: float = _CONNECT_TIMEOUT_S_DEFAULT,) -> None:self._catalog = catalog or load_catalog()self._store = token_store or TokenStore()self._client_factory = client_factory or _default_client_factoryself._bus = busself._risk_tier = default_risk_tier+ self._connect_timeout_s = float(connect_timeout_s)self._clients: dict[str, Any] = {}self._tools: dict[str, MCPToolAdapter] = {}# Last swallowed connect/list_tools error per plugin (honest liveness@@ -102,18 +134,28 @@ class PluginToolRegistry:# Idempotent: a second bootstrap() would leak the first run's MCP# clients (their AsyncExitStacks) by overwriting self._clients. Callers# use refresh_plugin() for incremental updates after the first boot.+ # (_connect_plugin additionally skips already-connected ids, so a rare+ # concurrent second bootstrap degrades to no-ops, never double-registers.)async with self._lock:if self._bootstrapped:return- for plugin in self._catalog.plugins:+ plugins = list(self._catalog.plugins)+ # Per-plugin lock + per-plugin publish: an early plugin's tools reach+ # the live brain IMMEDIATELY, even while a later plugin is still+ # connecting or timing out. Holding one lock across the whole loop let+ # a single wedged handshake starve every other plugin AND the+ # completion event (live 2026-07-13, see _CONNECT_TIMEOUT_S_DEFAULT).+ for plugin in plugins:+ async with self._lock:await self._connect_plugin(plugin)+ connected = self.live_tool_count(plugin.id) > 0+ # Publish outside the lock — refresh_tools() (the subscriber) must+ # be free to call active_tools() without contending for this lock.+ if connected:+ await self._publish_brain_tools_changed(plugin.id, connected=True)+ async with self._lock:self._bootstrapped = Truelog.info("plugin-registry: %d plugin tools exposed", len(self._tools))- tools_present = bool(self._tools)- # Publish outside the lock — refresh_tools() (the subscriber) must be- # free to call active_tools() without contending for this lock.- if tools_present:- await self._publish_brain_tools_changed("*", connected=True)async def refresh_plugin(self, plugin_id: str) -> None:"""Re-evaluate a single plugin after connect/disconnect."""@@ -157,13 +199,36 @@ class PluginToolRegistry:if resolved is None:returnserver_spec, env_overrides = resolved+ client: Any | None = Nonetry:client = self._client_factory(server_spec, env_overrides=env_overrides)- await client.start()- tool_defs = await client.list_tools()+ # Bounded connect: a handshake that never completes (dead host,+ # 401-that-hangs) must not stall the caller — see+ # _CONNECT_TIMEOUT_S_DEFAULT for the live forensic.+ tool_defs = await asyncio.wait_for(+ self._start_and_list(client), timeout=self._connect_timeout_s+ )except Exception as exc: # noqa: BLE001 — graceful per-plugin degrade- log.warning("plugin-registry: %s connect failed: %s", plugin.id, exc)- self._last_errors[plugin.id] = str(exc)+ if isinstance(exc, asyncio.TimeoutError):+ msg = (+ f"connect timed out after {self._connect_timeout_s:.0f}s "+ "(handshake never completed)"+ )+ else:+ msg = str(exc) or type(exc).__name__+ log.warning("plugin-registry: %s connect failed: %s", plugin.id, msg)+ self._last_errors[plugin.id] = msg+ self._maybe_mark_needs_reauth(plugin.id, tokens, msg)+ if client is not None:+ # Best-effort cleanup; a cancelled/hung transport may not+ # close cleanly, so the stop itself is bounded too.+ try:+ await asyncio.wait_for(client.stop(), timeout=5.0)+ except Exception: # noqa: BLE001 — cleanup must never raise+ log.debug(+ "plugin-registry: %s post-failure stop failed", plugin.id,+ exc_info=True,+ )returnself._clients[plugin.id] = clientself._last_errors.pop(plugin.id, None)@@ -182,6 +247,32 @@ class PluginToolRegistry:except Exception as exc: # noqa: BLE001 — capability is best-effortlog.debug("paired cap register failed for %s: %s", plugin.id, exc)+ @staticmethod+ async def _start_and_list(client: Any) -> list[dict[str, Any]]:+ """Handshake + tool listing as one awaitable so wait_for bounds both."""+ await client.start()+ return await client.list_tools()++ def _maybe_mark_needs_reauth(self, plugin_id: str, tokens: Any, message: str) -> None:+ """Flag the stored token after an auth-shaped connect failure.++ Mirrors the refresh scheduler's marking: later boots then skip the+ doomed connect (no repeated timeout cost) and the plugins view shows+ the Reconnect affordance instead of a silent per-boot failure."""+ try:+ if not _connect_needs_reauth(message):+ return+ self._store.save(plugin_id, dataclasses.replace(tokens, needs_reauth=True))+ log.warning(+ "plugin-registry: %s connect needs re-auth — marked: %s",+ plugin_id, message,+ )+ except Exception as exc: # noqa: BLE001 — marking is best-effort+ log.debug(+ "plugin-registry: needs_reauth save failed for %s: %s",+ plugin_id, exc,+ )+async def _disconnect_plugin(self, plugin_id: str) -> None:for name in [n for n in self._tools if n.startswith(f"{plugin_id}/")]:self._tools.pop(name, None)diff --git a/tests/unit/brain/test_tool_surface_reconcile.py b/tests/unit/brain/test_tool_surface_reconcile.pynew file mode 100644index 0000000000..b15cfd04a8--- /dev/null+++ b/tests/unit/brain/test_tool_surface_reconcile.py@@ -0,0 +1,164 @@+"""Tool-surface self-heal (jarvis/brain/tool_surface.py).++Live 2026-07-13: the plugin bootstrap wedged on one dead plugin, so the github+MCP's 37 tools only reached the brain when their connect happened to beat the+boot's last unrelated BrainToolsChanged refresh — "tool not available" in one+session, working in the next. The fingerprint reconcile makes the manager's+tool snapshot converge at the next turn even when the upstream event is lost.+"""+from __future__ import annotations++import pytest++from jarvis.brain.tool_surface import (+ live_tool_surface_fingerprint,+ maybe_reconcile_tool_surface,+ stamp_tool_surface,+)+++class _NamedTool:+ def __init__(self, name: str) -> None:+ self.name = name+++class _FakeToolRegistry:+ """Stands in for CliToolRegistry / PluginToolRegistry (active_tools())."""++ def __init__(self, names: list[str]) -> None:+ self._names = names++ def active_tools(self) -> list[_NamedTool]:+ return [_NamedTool(n) for n in self._names]+++class _FakeMcpClient:+ def __init__(self, tool_names: list[str]) -> None:+ self._tools_cache = [{"name": n} for n in tool_names]+++class _FakeMcpRegistry:+ def __init__(self, clients: dict[str, _FakeMcpClient]) -> None:+ self._clients = clients++ def active_clients(self) -> dict[str, _FakeMcpClient]:+ return dict(self._clients)+++class _FakeManager:+ """Only what the reconcile touches: _tool_surface_fp + refresh_tools()."""++ def __init__(self) -> None:+ self.refresh_calls = 0++ def refresh_tools(self) -> None:+ self.refresh_calls += 1+++def _wire_sources(+ monkeypatch: pytest.MonkeyPatch,+ *,+ cli: object = None,+ plugin: object = None,+ mcp: object = None,+) -> None:+ monkeypatch.setattr("jarvis.clis.shared.get_active_registry", lambda: cli)+ monkeypatch.setattr(+ "jarvis.marketplace.plugin_shared.get_active_plugin_registry", lambda: plugin+ )+ monkeypatch.setattr("jarvis.core.runtime_refs.get_mcp_registry", lambda: mcp)+++def test_fingerprint_none_when_no_source_registry_reachable(monkeypatch):+ _wire_sources(monkeypatch) # all three absent+ assert live_tool_surface_fingerprint() is None+++def test_fingerprint_collects_all_three_sources_with_prefixes(monkeypatch):+ _wire_sources(+ monkeypatch,+ cli=_FakeToolRegistry(["cli_gh"]),+ plugin=_FakeToolRegistry(["github/search_issues"]),+ mcp=_FakeMcpRegistry({"notebooklm": _FakeMcpClient(["notebook_query"])}),+ )+ fp = live_tool_surface_fingerprint()+ assert fp == frozenset(+ {+ "cli:cli_gh",+ "plugin:github/search_issues",+ "mcp:notebooklm:notebook_query",+ }+ )+++def test_one_broken_source_does_not_blind_the_others(monkeypatch):+ def _boom():+ raise RuntimeError("registry exploded")++ monkeypatch.setattr("jarvis.clis.shared.get_active_registry", _boom)+ monkeypatch.setattr(+ "jarvis.marketplace.plugin_shared.get_active_plugin_registry",+ lambda: _FakeToolRegistry(["github/search_issues"]),+ )+ monkeypatch.setattr("jarvis.core.runtime_refs.get_mcp_registry", lambda: None)+ fp = live_tool_surface_fingerprint()+ assert fp == frozenset({"plugin:github/search_issues"})+++def test_reconcile_adopts_first_fingerprint_without_refresh(monkeypatch):+ _wire_sources(monkeypatch, cli=_FakeToolRegistry(["cli_gh"]))+ mgr = _FakeManager()+ maybe_reconcile_tool_surface(mgr)+ assert mgr.refresh_calls == 0+ assert mgr._tool_surface_fp == frozenset({"cli:cli_gh"})+++def test_reconcile_noop_when_surface_unchanged(monkeypatch):+ _wire_sources(monkeypatch, cli=_FakeToolRegistry(["cli_gh"]))+ mgr = _FakeManager()+ mgr._tool_surface_fp = frozenset({"cli:cli_gh"})+ maybe_reconcile_tool_surface(mgr)+ assert mgr.refresh_calls == 0+++def test_reconcile_refreshes_on_drift_and_stamps(monkeypatch):+ """The github-boot-race shape: a source appears after the last stamp."""+ _wire_sources(+ monkeypatch,+ cli=_FakeToolRegistry(["cli_gh"]),+ plugin=_FakeToolRegistry(["github/search_issues"]),+ )+ mgr = _FakeManager()+ mgr._tool_surface_fp = frozenset({"cli:cli_gh"}) # github missing at load+ maybe_reconcile_tool_surface(mgr)+ assert mgr.refresh_calls == 1+ assert "plugin:github/search_issues" in mgr._tool_surface_fp+++def test_reconcile_skips_when_no_sources_reachable(monkeypatch):+ _wire_sources(monkeypatch)+ mgr = _FakeManager()+ maybe_reconcile_tool_surface(mgr)+ assert mgr.refresh_calls == 0+ assert not hasattr(mgr, "_tool_surface_fp")+++def test_reconcile_survives_refresh_failure(monkeypatch):+ _wire_sources(monkeypatch, cli=_FakeToolRegistry(["cli_gh", "cli_docker"]))++ class _ExplodingManager(_FakeManager):+ def refresh_tools(self) -> None:+ raise RuntimeError("factory rebuild failed")++ mgr = _ExplodingManager()+ mgr._tool_surface_fp = frozenset({"cli:cli_gh"})+ maybe_reconcile_tool_surface(mgr) # must not raise (never break a turn)+ # Stamped before the refresh attempt: no warning storm on later turns.+ assert mgr._tool_surface_fp == frozenset({"cli:cli_gh", "cli:cli_docker"})+++def test_stamp_records_current_surface(monkeypatch):+ _wire_sources(monkeypatch, cli=_FakeToolRegistry(["cli_gh"]))+ mgr = _FakeManager()+ stamp_tool_surface(mgr)+ assert mgr._tool_surface_fp == frozenset({"cli:cli_gh"})diff --git a/tests/unit/marketplace/test_plugin_registry.py b/tests/unit/marketplace/test_plugin_registry.pyindex 6b61e76f06..0fb6efbfb4 100644--- a/tests/unit/marketplace/test_plugin_registry.py+++ b/tests/unit/marketplace/test_plugin_registry.py@@ -158,3 +158,124 @@ async def test_connect_failure_is_recorded_and_tool_count_zero(registry_with_faiawait reg._connect_plugin(plugin)assert reg.live_tool_count(plugin.id) == 0assert "401" in (reg.last_connect_error(plugin.id) or "")+++# ---------------------------------------------------------------------------+# Bootstrap robustness (live 2026-07-13): one wedged plugin connect must never+# stall the whole bootstrap, and every plugin that DOES come up must reach the+# live brain immediately. Root cause of the intermittent "tool not available"+# refusals: the linear plugin's remote MCP answered 401 by hanging the+# handshake, bootstrap never finished, never published BrainToolsChanged — so+# the github plugin's 37 tools only appeared when their connect happened to+# beat the last unrelated tool refresh (mcp_autostart / cli_connected race).+# ---------------------------------------------------------------------------+++def _plugin(pid: str) -> PluginSpec:+ return PluginSpec(+ id=pid, display_name=pid, description="x",+ category="Productivity", logo_slug=pid,+ auth={"mode": "pat_paste", "token_creation_url": "x", "token_prefix": "tok",+ "validation_endpoint": "x", "instruction_md": "x"},+ mcp_server={"transport": "http", "url": f"https://{pid}.example/mcp",+ "auth_header_template": f"Authorization: Bearer $plugin_{pid}_access_token"},+ )+++class _HangingClient:+ """Stands in for a wedged remote MCP handshake (401-that-hangs, dead host)."""+ def __init__(self, spec, env_overrides=None):+ self.spec = spec+ async def start(self) -> None:+ import asyncio+ await asyncio.Event().wait() # never returns+ async def stop(self) -> None: ...+ async def list_tools(self): return []+++def _factory_by_id(mapping):+ """Client factory that picks the fake class by plugin id (spec.name)."""+ def factory(spec, env_overrides=None):+ return mapping[spec.name](spec, env_overrides=env_overrides)+ return factory+++def _store_for(*pids: str) -> TokenStore:+ store = TokenStore(InMemoryBackend())+ for pid in pids:+ store.save(pid, Tokens(access="TOK"))+ return store+++async def test_bootstrap_survives_hanging_plugin_connect():+ """The hanging plugin times out; the healthy one still exposes its tools,+ bootstrap completes, and BrainToolsChanged fires for the healthy plugin."""+ import asyncio++ catalog = PluginCatalog(version=1, schema_version="1",+ plugins=[_plugin("hangs"), _plugin("healthy")])+ bus = _RecordingBus()+ reg = PluginToolRegistry(+ catalog=catalog, token_store=_store_for("hangs", "healthy"),+ client_factory=_factory_by_id({"hangs": _HangingClient, "healthy": _FakeClient}),+ bus=bus, connect_timeout_s=0.05,+ )+ await asyncio.wait_for(reg.bootstrap(), timeout=5.0)+ names = [t.name for t in reg.active_tools()]+ assert "healthy/list_events" in names+ assert reg.live_tool_count("hangs") == 0+ assert "timed out" in (reg.last_connect_error("hangs") or "")+ assert reg.is_bootstrapped()+ reasons = [getattr(e, "reason", "") for e in bus.events]+ assert "plugin_connected:healthy" in reasons+++async def test_bootstrap_publishes_one_event_per_connected_plugin():+ """Each plugin that comes up during bootstrap publishes its own+ BrainToolsChanged, so an early winner reaches the live brain immediately+ instead of waiting behind a slow or wedged later plugin."""+ catalog = PluginCatalog(version=1, schema_version="1",+ plugins=[_plugin("one"), _plugin("two")])+ bus = _RecordingBus()+ reg = PluginToolRegistry(catalog=catalog, token_store=_store_for("one", "two"),+ client_factory=_FakeClient, bus=bus)+ await reg.bootstrap()+ reasons = [getattr(e, "reason", "") for e in bus.events]+ assert "plugin_connected:one" in reasons+ assert "plugin_connected:two" in reasons+++async def test_auth_shaped_connect_failure_marks_needs_reauth():+ """A 401/unauthorized at connect time means the credential is dead — mark+ the token needs_reauth so later boots skip the doomed connect and the UI+ shows the Reconnect affordance."""+ catalog = PluginCatalog(version=1, schema_version="1", plugins=[_plugin("dead-token")])+ store = _store_for("dead-token")+ reg = PluginToolRegistry(catalog=catalog, token_store=store,+ client_factory=_FailingClient, bus=_RecordingBus())+ await reg.bootstrap()+ tokens = store.load("dead-token")+ assert tokens is not None+ assert tokens.needs_reauth is True+++async def test_transient_connect_failure_does_not_mark_needs_reauth():+ """'Connection closed' and friends are retryable — one flaky boot must not+ flag a healthy plugin as needing a reconnect."""+ class _TransientFailClient(_FakeClient):+ async def start(self) -> None:+ raise RuntimeError("Connection closed")++ catalog = PluginCatalog(version=1, schema_version="1", plugins=[_plugin("flaky")])+ store = _store_for("flaky")+ reg = PluginToolRegistry(catalog=catalog, token_store=store,+ client_factory=_TransientFailClient, bus=_RecordingBus())+ await reg.bootstrap()+ tokens = store.load("flaky")+ assert tokens is not None+ assert tokens.needs_reauth is False+ assert "Connection closed" in (reg.last_connect_error("flaky") or "")