JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(progressive_tool_rail): 修复 invoke_tool 报"无法获取工具的实例"
xiaowenzihwlbaaa25357bc0
diff --git a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.pyindex 037c9a889d..778be40b6d 100644--- a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py@@ -31,6 +31,7 @@ from jiuwenswarm.agents.harness.common.tools.invoke_tool_tool import (InvokeToolInput,InvokeToolTool,)+from jiuwenswarm.common.mcp_config import resolve_active_office_claw_tool_idlogger = logging.getLogger(__name__)@@ -660,6 +661,21 @@ class ProgressiveToolRail(DeepAgentRail):if str(getattr(tool, "name", "") or "")}+ @staticmethod+ def _tool_id_set(tools: list[Any]) -> set[str]:+ """Return registered tool ids from ability_manager entries.++ Same-named cards can swap ids when a request-scoped MCP rebinds+ (e.g. OfficeClaw MCP re-registers per request with a fresh hash).+ Comparing ids in addition to names lets the staleness check catch+ such rebinds that name-only comparison misses.+ """+ return {+ str(getattr(tool, "id", "") or "")+ for tool in tools+ if str(getattr(tool, "id", "") or "")+ }+async def _refresh_deferred_tool_cache_if_stale(self) -> None:"""Refresh cache when ability_manager has tools not in cache."""agent = self._resolve_runtime_agent()@@ -672,6 +688,11 @@ class ProgressiveToolRail(DeepAgentRail):):await self._refresh_deferred_tool_cache(agent)return+ if self._tool_id_set(live_tools) != self._tool_id_set(+ self._cached_all_tool_infos+ ):+ await self._refresh_deferred_tool_cache(agent)+ returnlive_deferred = [toolfor tool in live_tools@@ -734,6 +755,15 @@ class ProgressiveToolRail(DeepAgentRail):name = str(getattr(tool, "name", "") or "")description = str(getattr(tool, "description", "") or "")input_params = getattr(tool, "input_params", {}) or {}+ tool_id = str(getattr(tool, "id", "") or "")+ if not self._tool_instance_available(name, tool_id):+ logger.warning(+ "%s search skip dead instance: tool_name=%s tool_id=%s",+ _LOG_PREFIX,+ name,+ tool_id,+ )+ continueresult_matches.append({"name": name,@@ -748,6 +778,17 @@ class ProgressiveToolRail(DeepAgentRail):len(result_matches),)+ if matches and not result_matches:+ return {+ "success": False,+ "matches": [],+ "count": 0,+ "message": (+ f"工具 '{tool_name}' 的 schema 可见但实例不可用"+ "(可能被并发请求清理),请稍后重试。"+ ),+ }+return {"success": bool(result_matches),"matches": result_matches,@@ -759,6 +800,89 @@ class ProgressiveToolRail(DeepAgentRail):),}+ @staticmethod+ def _lookup_tool_instance(tool_id: str) -> Any | None:+ """Best-effort resource_mgr lookup; never raises to callers."""+ normalized = str(tool_id or "").strip()+ if not normalized:+ return None+ try:+ return Runner.resource_mgr.get_tool(normalized)+ except Exception as exc:+ logger.warning(+ "%s failed to get tool instance: tool_id=%s error=%s",+ _LOG_PREFIX,+ normalized,+ exc,+ )+ return None++ def _tool_instance_available(self, tool_name: str, tool_id: str) -> bool:+ """True when cache id or this request's active OfficeClaw id still resolves."""+ if self._lookup_tool_instance(tool_id) is not None:+ return True+ active_id = resolve_active_office_claw_tool_id(tool_name)+ if not active_id:+ return False+ if active_id == tool_id:+ return False+ return self._lookup_tool_instance(active_id) is not None++ async def _resolve_tool_instance_with_recovery(+ self,+ tool_name: str,+ preferred_id: str,+ ) -> tuple[Any | None, str, str]:+ """Resolve a live tool instance, recovering from stale card ids.++ Order:+ 1. preferred_id from deferred cache / AbilityManager card+ 2. refresh AbilityManager cache and retry if the live card id changed+ 3. this request's ``bind_active_office_claw_mcp_tools`` allowlist+ (authoritative for OfficeClaw MCP even when short-name AM was+ overwritten or cleaned by a concurrent request)++ Returns ``(tool, resolved_id, refreshed_id_for_diagnostics)``.+ """+ target_tool = self._lookup_tool_instance(preferred_id)+ if target_tool is not None:+ return target_tool, preferred_id, ""++ logger.info(+ "%s stale tool_id retry: tool_name=%s old_id=%s",+ _LOG_PREFIX,+ tool_name,+ preferred_id,+ )+ await self._refresh_deferred_tool_cache()+ refreshed_card = None+ for tool in self._cached_deferred_tool_infos:+ if str(getattr(tool, "name", "") or "") == tool_name:+ refreshed_card = tool+ break+ refreshed_id = (+ str(getattr(refreshed_card, "id", "") or "") if refreshed_card is not None else ""+ )+ if refreshed_id and refreshed_id != preferred_id:+ target_tool = self._lookup_tool_instance(refreshed_id)+ if target_tool is not None:+ return target_tool, refreshed_id, refreshed_id++ active_id = resolve_active_office_claw_tool_id(tool_name)+ if active_id:+ if active_id not in {preferred_id, refreshed_id}:+ logger.info(+ "%s active OfficeClaw tool_id fallback: tool_name=%s active_id=%s",+ _LOG_PREFIX,+ tool_name,+ active_id,+ )+ target_tool = self._lookup_tool_instance(active_id)+ if target_tool is not None:+ return target_tool, active_id, refreshed_id or active_id++ return None, preferred_id, refreshed_id+async def _invoke_target_tool(self,session: Any,@@ -826,14 +950,22 @@ class ProgressiveToolRail(DeepAgentRail):"tool_name": tool_name,}- target_tool_id = str(getattr(target_tool_card, "id", "") or "")- target_tool = None- try:- target_tool = Runner.resource_mgr.get_tool(target_tool_id)- except Exception as e:- logger.warning("%s failed to get tool instance: tool_id=%s error=%s", _LOG_PREFIX, target_tool_id, e)+ preferred_id = str(getattr(target_tool_card, "id", "") or "")+ target_tool, target_tool_id, refreshed_id = await self._resolve_tool_instance_with_recovery(+ tool_name,+ preferred_id,+ )if target_tool is None:+ logger.warning(+ "%s invoke tool=%s failed: instance not found, "+ "tool_id=%s, refresh_attempted=True, refreshed_id=%s, active_id=%s",+ _LOG_PREFIX,+ tool_name,+ target_tool_id,+ refreshed_id,+ resolve_active_office_claw_tool_id(tool_name) or "",+ )return {"success": False,"error": f"无法获取工具 '{tool_name}' 的实例。",diff --git a/jiuwenswarm/common/mcp_config.py b/jiuwenswarm/common/mcp_config.pyindex dc6e66dca8..8b1c30a6c6 100644--- a/jiuwenswarm/common/mcp_config.py+++ b/jiuwenswarm/common/mcp_config.py@@ -855,6 +855,47 @@ def ensure_request_scoped_office_claw_tool_allowed(tool_id: str) -> None:)+def get_active_office_claw_mcp_tool_ids() -> frozenset[str] | None:+ """Return the request-local OfficeClaw tool id allowlist, if bound."""++ return _active_office_claw_tool_ids.get()+++def resolve_active_office_claw_tool_id(tool_name: str) -> str | None:+ """Map a short tool name to this request's OfficeClaw tool id.++ Request-scoped ids look like+ ``office-claw-request-<hash>.office-claw.<tool_name>``. ProgressiveToolRail+ may hold a stale AbilityManager card whose id points at another request's+ (already cleaned-up) registration; the active allowlist is the authority+ for *this* chat.send.+ """++ name = str(tool_name or "").strip()+ if not name:+ return None+ allowed = _active_office_claw_tool_ids.get()+ if not allowed:+ return None+ suffix = f".{name}"+ matches = [+ tool_id+ for tool_id in allowed+ if tool_id.endswith(suffix) or tool_id.rsplit(".", 1)[-1] == name+ ]+ if not matches:+ return None+ if len(matches) == 1:+ return matches[0]+ # Prefer the canonical request-scoped shape when multiple ids match.+ preferred = [+ tool_id+ for tool_id in matches+ if tool_id.startswith(OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX) and tool_id.endswith(suffix)+ ]+ return preferred[0] if preferred else matches[0]++def extract_office_claw_mcp(params: Any) -> dict[str, Any] | None:"""Return only the legacy ``office_claw_mcp`` request field."""@@ -1130,9 +1171,11 @@ __all__ = ["ensure_request_scoped_office_claw_tool_allowed","extract_enabled_mcp_server_entries","extract_office_claw_mcp",+ "get_active_office_claw_mcp_tool_ids","invalidate_office_claw_mcp_schema_cache","list_office_claw_mcp_tools","preflight_mcp_server_reachable",+ "resolve_active_office_claw_tool_id","validate_office_claw_mcp_config","_check_dangerous_args","_is_blocked_host",diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex ea7086db72..045918b41d 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -3803,10 +3803,7 @@ class JiuWenSwarmDeepAdapter:)ability_result = ability_manager.add(card)- if ability_result is None:- # Legacy AbilityManager.add returned None and may overwrite by name.- return- added = getattr(ability_result, "added", None)+ added = getattr(ability_result, "added", None) if ability_result is not None else Noneif added is False:# Conflict-aware AbilityManager kept the existing card. Retry once if# we own it; otherwise fail closed.@@ -3815,12 +3812,23 @@ class JiuWenSwarmDeepAdapter:if existing_id and existing_id in self._owned_office_claw_tool_ids():ability_manager.remove(tool_name)ability_result = ability_manager.add(card)- added = getattr(ability_result, "added", None)+ added = getattr(ability_result, "added", None) if ability_result is not None else Noneif added is False:raise RuntimeError(f"OfficeClaw MCP tool name conflicts with an existing tool: {tool_name}")+ # Legacy AbilityManager.add() returns None and may overwrite by name.+ # Always verify the short-name mapping lands on *this* card id so a+ # conflict-aware or raced manager cannot leave a foreign bind in place.+ installed = getter(tool_name) if callable(getter) else None+ installed_id = str(getattr(installed, "id", "") or "") if installed is not None else ""+ if installed_id != tool_id:+ raise RuntimeError(+ f"OfficeClaw MCP tool name conflicts with an existing tool: {tool_name} "+ f"(existing_id={installed_id or '-'}, new_id={tool_id})"+ )+async def cleanup_request_scoped_office_claw_mcp(self,registration: OfficeClawMcpRegistration | None,diff --git a/tests/unit_tests/agentserver/test_progressive_tool_rail_stale_id.py b/tests/unit_tests/agentserver/test_progressive_tool_rail_stale_id.pynew file mode 100644index 0000000000..aadc5f4842--- /dev/null+++ b/tests/unit_tests/agentserver/test_progressive_tool_rail_stale_id.py@@ -0,0 +1,334 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Regression tests for stale deferred-tool-id handling in ProgressiveToolRail.++Covers the failure where a request-scoped MCP (e.g. OfficeClaw MCP) rebinds+the same tool name to a new id while ``_cached_deferred_tool_infos`` still+holds the previous card. Without the fixes, ``invoke_tool`` would look up+``Runner.resource_mgr`` with the stale id and fail with+``无法获取工具 '<name>' 的实例。``.+"""++# pylint: disable=protected-access++from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++import pytest+from openjiuwen.core.runner import Runner++from jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import (+ ProgressiveToolRail,+)+from jiuwenswarm.agents.harness.common.tools.invoke_tool_tool import (+ InvokeToolInput,+)+++async def test_invoke_retries_with_refreshed_id_when_cached_id_is_stale():+ """When get_tool(stale_id) returns None, the rail refreshes the cache+ and retries with the new id from the refreshed card."""++ old_card = SimpleNamespace(+ name="office_claw_register_scheduled_task",+ id="office-claw-request-stale-hash.office-claw.office_claw_register_scheduled_task",+ description="d",+ input_params={},+ properties={},+ )+ new_card = SimpleNamespace(+ name="office_claw_register_scheduled_task",+ id="office-claw-request-fresh-hash.office-claw.office_claw_register_scheduled_task",+ description="d",+ input_params={},+ properties={"resilience": {"timeout_s": None}},+ )++ target = SimpleNamespace(invoke=AsyncMock(return_value={"ok": True}))+ rail = ProgressiveToolRail(eager_tools=["tools_search", "invoke_tool"])+ rail._cached_deferred_tool_infos = [old_card]++ async def _fake_refresh(_agent=None):+ rail._cached_deferred_tool_infos = [new_card]++ def _get_tool_side_effect(tool_id, session=None):+ if tool_id == old_card.id:+ return None+ if tool_id == new_card.id:+ return target+ return None++ with patch.object(+ Runner.resource_mgr, "get_tool", side_effect=_get_tool_side_effect+ ), patch.object(+ rail, "_refresh_deferred_tool_cache", new=_fake_refresh+ ):+ result = await rail._invoke_target_tool(+ None,+ InvokeToolInput(+ tool_name="office_claw_register_scheduled_task",+ arguments={"templateId": "reminder"},+ ),+ )++ assert result == {+ "success": True,+ "tool_name": "office_claw_register_scheduled_task",+ "result": {"ok": True},+ }+ target.invoke.assert_awaited_once()+++async def test_invoke_returns_failure_when_refreshed_id_also_missing():+ """If both the stale id and the refreshed id fail to resolve in+ resource_mgr, the rail still returns the documented error (now with+ diagnostic logging). The refresh must be attempted exactly once."""++ stale_card = SimpleNamespace(+ name="ghost_tool",+ id="ghost-stale-id",+ description="d",+ input_params={},+ properties={},+ )+ rail = ProgressiveToolRail(eager_tools=["tools_search", "invoke_tool"])+ rail._cached_deferred_tool_infos = [stale_card]++ refresh_calls = 0++ async def _fake_refresh(_agent=None):+ nonlocal refresh_calls+ refresh_calls += 1+ # Cache stays the same — no fresh id available.+ rail._cached_deferred_tool_infos = [stale_card]++ with patch.object(+ Runner.resource_mgr, "get_tool", return_value=None+ ), patch.object(+ rail, "_refresh_deferred_tool_cache", new=_fake_refresh+ ):+ result = await rail._invoke_target_tool(+ None,+ InvokeToolInput(tool_name="ghost_tool", arguments={}),+ )++ assert result == {+ "success": False,+ "error": "无法获取工具 'ghost_tool' 的实例。",+ "tool_name": "ghost_tool",+ }+ # The retry must trigger exactly one cache refresh — no infinite loop.+ assert refresh_calls == 1+++async def test_invoke_does_not_retry_when_get_tool_succeeds_first_time():+ """The retry path must be skipped entirely when the cached id still+ resolves in resource_mgr — no spurious cache refresh."""++ card = SimpleNamespace(+ name="healthy_tool",+ id="healthy-id",+ description="d",+ input_params={},+ properties={"resilience": {"timeout_s": None}},+ )+ target = SimpleNamespace(invoke=AsyncMock(return_value="ok"))+ rail = ProgressiveToolRail(eager_tools=["tools_search", "invoke_tool"])+ rail._cached_deferred_tool_infos = [card]++ refresh_calls = 0++ async def _counting_refresh(_agent=None):+ nonlocal refresh_calls+ refresh_calls += 1++ with patch.object(Runner.resource_mgr, "get_tool", return_value=target), patch.object(+ rail, "_refresh_deferred_tool_cache", new=_counting_refresh+ ):+ result = await rail._invoke_target_tool(+ None,+ InvokeToolInput(tool_name="healthy_tool", arguments={}),+ )++ assert result == {"success": True, "tool_name": "healthy_tool", "result": "ok"}+ assert refresh_calls == 0+++async def test_staleness_check_detects_same_name_different_id_rebind():+ """_refresh_deferred_tool_cache_if_stale must trigger a refresh when+ ability_manager returns cards with the same names but different ids+ (e.g. after a request-scoped MCP rebind)."""++ rail = ProgressiveToolRail(eager_tools=["tools_search", "invoke_tool"])+ agent = SimpleNamespace(ability_manager=SimpleNamespace())+ # Bind both _runtime_agent and _deep_agent to the same object so that+ # _resolve_runtime_agent() does not invalidate the cache mid-check.+ rail._runtime_agent = agent+ rail._deep_agent = agent++ old_card = SimpleNamespace(+ name="office_claw_register_scheduled_task",+ id="office-claw-request-old-hash.office-claw.office_claw_register_scheduled_task",+ )+ new_card = SimpleNamespace(+ name="office_claw_register_scheduled_task",+ id="office-claw-request-new-hash.office-claw.office_claw_register_scheduled_task",+ )+ rail._cached_all_tool_infos = [old_card]+ rail._cached_deferred_tool_infos = [old_card]++ refresh_calls = 0++ async def _counting_refresh(agent=None):+ nonlocal refresh_calls+ refresh_calls += 1+ rail._cached_all_tool_infos = [new_card]+ rail._cached_deferred_tool_infos = [new_card]++ with patch.object(+ rail, "_get_all_tool_infos", new=AsyncMock(return_value=[new_card])+ ), patch.object(+ rail, "_refresh_deferred_tool_cache", new=_counting_refresh+ ):+ await rail._refresh_deferred_tool_cache_if_stale()++ assert refresh_calls == 1+ assert rail._cached_all_tool_infos == [new_card]+++async def test_staleness_check_skips_refresh_when_ids_unchanged():+ """If the live tools have the same ids as the cached tools, no refresh+ should be triggered — the id-set comparison must not produce false+ positives on every iteration."""++ rail = ProgressiveToolRail(eager_tools=["tools_search", "invoke_tool"])+ agent = SimpleNamespace(ability_manager=SimpleNamespace())+ # Bind both agents to the same object so _resolve_runtime_agent() does+ # not invalidate the cache before the staleness comparison runs.+ rail._runtime_agent = agent+ rail._deep_agent = agent++ card = SimpleNamespace(+ name="stable_tool",+ id="stable-id",+ )+ rail._cached_all_tool_infos = [card]+ rail._cached_deferred_tool_infos = [card]++ refresh_calls = 0++ async def _counting_refresh(agent=None):+ nonlocal refresh_calls+ refresh_calls += 1++ with patch.object(+ rail, "_get_all_tool_infos", new=AsyncMock(return_value=[card])+ ), patch.object(+ rail, "_refresh_deferred_tool_cache", new=_counting_refresh+ ):+ await rail._refresh_deferred_tool_cache_if_stale()++ assert refresh_calls == 0+++async def test_invoke_falls_back_to_active_office_claw_tool_id():+ """Problem 172: cache/AM still points at a concurrent request's cleaned-up+ id, but this request's owned tool id remains in resource_mgr and is bound+ via ``bind_active_office_claw_mcp_tools``."""++ from jiuwenswarm.common.mcp_config import bind_active_office_claw_mcp_tools++ foreign_dead = (+ "office-claw-request-other.office-claw.office_claw_register_scheduled_task"+ )+ owned_live = (+ "office-claw-request-mine.office-claw.office_claw_register_scheduled_task"+ )+ stale_card = SimpleNamespace(+ name="office_claw_register_scheduled_task",+ id=foreign_dead,+ description="d",+ input_params={},+ properties={"resilience": {"timeout_s": None}},+ )+ target = SimpleNamespace(invoke=AsyncMock(return_value={"ok": True}))+ rail = ProgressiveToolRail(eager_tools=["tools_search", "invoke_tool"])+ rail._cached_deferred_tool_infos = [stale_card]++ async def _fake_refresh(_agent=None):+ # AbilityManager still polluted with the foreign id after refresh.+ rail._cached_deferred_tool_infos = [stale_card]++ def _get_tool_side_effect(tool_id, session=None):+ if tool_id == foreign_dead:+ return None+ if tool_id == owned_live:+ return target+ return None++ with bind_active_office_claw_mcp_tools([owned_live]), patch.object(+ Runner.resource_mgr, "get_tool", side_effect=_get_tool_side_effect+ ), patch.object(rail, "_refresh_deferred_tool_cache", new=_fake_refresh):+ result = await rail._invoke_target_tool(+ None,+ InvokeToolInput(+ tool_name="office_claw_register_scheduled_task",+ arguments={"templateId": "reminder"},+ ),+ )++ assert result["success"] is True+ assert result["tool_name"] == "office_claw_register_scheduled_task"+ target.invoke.assert_awaited_once()+++async def test_search_skips_dead_instance_without_active_fallback():+ """tools_search must not advertise a tool whose instance is gone and+ which has no active OfficeClaw binding for this request."""++ from jiuwenswarm.agents.harness.common.tools.tools_search_tool import (+ ToolsSearchInput,+ )++ dead_card = SimpleNamespace(+ name="office_claw_preview_scheduled_task",+ id="office-claw-request-dead.office-claw.office_claw_preview_scheduled_task",+ description="preview",+ input_params={"type": "object"},+ )+ rail = ProgressiveToolRail(eager_tools=["tools_search", "invoke_tool"])+ rail._cached_deferred_tool_infos = [dead_card]++ with patch.object(Runner.resource_mgr, "get_tool", return_value=None):+ result = await rail._search_tools(+ None,+ ToolsSearchInput(tool_name="office_claw_preview_scheduled_task"),+ )++ assert result["success"] is False+ assert result["matches"] == []+ assert "实例不可用" in result["message"]+++def test_resolve_active_office_claw_tool_id_maps_short_name():+ from jiuwenswarm.common.mcp_config import (+ bind_active_office_claw_mcp_tools,+ resolve_active_office_claw_tool_id,+ )++ owned = "office-claw-request-abc.office-claw.office_claw_preview_scheduled_task"+ with bind_active_office_claw_mcp_tools([owned]):+ assert (+ resolve_active_office_claw_tool_id("office_claw_preview_scheduled_task")+ == owned+ )+ assert resolve_active_office_claw_tool_id("missing_tool") is None++ assert resolve_active_office_claw_tool_id("office_claw_preview_scheduled_task") is Nonediff --git a/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.py b/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.pyindex 89101bdb18..3786781594 100644--- a/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.py+++ b/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.py@@ -299,6 +299,58 @@ async def test_foreign_short_name_conflict_fails_closed(assert adapter._instance.ability_manager.get("office_claw_multi_mention") is foreign+async def test_legacy_ability_manager_post_add_mismatch_fails_closed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Legacy AbilityManager.add() returns None. If the short-name mapping+ does not land on our card id afterwards, registration must fail closed+ instead of treating ``None`` as success."""++ class _StickyForeignAbilityManager(_AbilityManager):+ def add(self, card: object) -> None:+ # Pretend to accept the card (legacy return) but keep the foreign bind.+ return None++ for key, value in _startup_env().items():+ monkeypatch.setenv(key, value)+ resource_manager = _ResourceManager()+ monkeypatch.setattr(interface_deep.Runner, "resource_mgr", resource_manager)+ monkeypatch.setattr(+ interface_deep,+ "list_office_claw_mcp_tools",+ AsyncMock(+ return_value=[+ {+ "name": "office_claw_preview_scheduled_task",+ "description": "preview",+ "input_params": {"type": "object"},+ }+ ]+ ),+ )+ adapter = _bare_session_adapter()+ sticky = _StickyForeignAbilityManager()+ sticky.cards["office_claw_preview_scheduled_task"] = ToolCard(+ id="office-claw-request-foreign.office-claw.office_claw_preview_scheduled_task",+ name="office_claw_preview_scheduled_task",+ description="foreign",+ input_params={},+ )+ # Pre-check sees foreign id and fails before add — exercise post-add path+ # by clearing the foreign card only for the pre-check window is hard;+ # instead start empty and make add() a no-op so post-verify sees missing id.+ sticky.cards.clear()+ adapter._instance = SimpleNamespace(ability_manager=sticky)++ registration = await adapter.register_request_scoped_office_claw_mcp(+ _request(_valid_config())+ )++ assert registration is None+ assert sticky.cards == {}++@pytest.mark.asyncioasync def test_registration_failure_is_non_blocking(monkeypatch: pytest.MonkeyPatch,