refactor: isolate runtime contracts and enforce import boundaries (#6166)
* test: enforce Python import ownership boundaries * test: protect client import boundaries and rehome shared UI contracts * refactor: remove gateway and client dependency inversions * fix: detect dynamic imports in conditional expressions * refactor(tools): keep configuration contracts with their owners * docs: keep design guidance focused on ownership and checks * fix: preserve default threaded turn delivery
This commit is contained in:
1 parent
cd2a863710
commit
328e933d36
162 files changed
+3449
-1888
No files matched your search
@@ -11,8 +11,11 @@ from nanobot.agent.turn_delivery import TurnDeliveryFactory
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.recovery import RECOVERY_METADATA_KEY, RecoveryCoordinator
|
||||
from nanobot.session.recovery import (
|
||||
RECOVERY_METADATA_KEY,
|
||||
)
|
||||
from nanobot.session.turn_continuation import INTERNAL_CONTINUATION_META
|
||||
from nanobot.webui.recovery import RecoveryCoordinator
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -124,7 +124,10 @@ def _make_full_loop(tmp_path: Path) -> AgentLoop:
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = SimpleNamespace(max_tokens=4096)
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Test title"))
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||
bus = MessageBus()
|
||||
loop = AgentLoop(
|
||||
bus=bus, provider=provider, workspace=tmp_path, model="test-model",
|
||||
)
|
||||
WebuiTurnCoordinator(
|
||||
bus=loop.bus,
|
||||
sessions=loop.sessions,
|
||||
|
||||
@@ -21,11 +21,11 @@ from nanobot.session.goal_state import GOAL_STATE_KEY
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.recovery import (
|
||||
PENDING_FOLLOWUPS_KEY,
|
||||
RecoveryCoordinator,
|
||||
pending_followups,
|
||||
record_pending_followup,
|
||||
)
|
||||
from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META
|
||||
from nanobot.webui.recovery import RecoveryCoordinator
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -13,6 +13,7 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.memory import Consolidator
|
||||
from nanobot.agent.runner import AgentRunResult
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
@@ -23,8 +24,11 @@ from nanobot.agent.tools.shell import ExecTool
|
||||
from nanobot.agent.tools.subagent import SubagentTool
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import TurnRunStatusChanged
|
||||
from nanobot.config import Config
|
||||
from nanobot.nanobot import Nanobot
|
||||
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.webui_turns import WebuiTurnRoutePolicy
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
@@ -176,6 +180,86 @@ async def test_child_origin_uses_the_channel_turn_identity(loop_factory):
|
||||
await loop.subagents.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_default_loop_keeps_slack_thread_for_late_subagent_result(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.agent.loop._SUBAGENT_TERMINAL_WAIT_SECONDS", 0.01)
|
||||
child_started, release_child, parent_idle = (asyncio.Event() for _ in range(3))
|
||||
|
||||
class Provider(LLMProvider):
|
||||
def __init__(self):
|
||||
super().__init__(provider_name="test")
|
||||
self.parent_calls = 0
|
||||
|
||||
async def chat(self, messages, tools=None, **kwargs):
|
||||
if not any(tool.get("function", {}).get("name") == "subagent" for tool in tools or []):
|
||||
child_started.set()
|
||||
await release_child.wait()
|
||||
return LLMResponse(content="Child findings")
|
||||
self.parent_calls += 1
|
||||
if self.parent_calls == 1:
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="delegate", name="subagent",
|
||||
arguments={"action": "create", "task": "Inspect config", "wait": False},
|
||||
)])
|
||||
return LLMResponse(content="Parent reply" if self.parent_calls == 2 else "Late follow-up")
|
||||
|
||||
def get_default_model(self):
|
||||
return "test-model"
|
||||
|
||||
workspace = tmp_path / "workspace"
|
||||
sessions_root = tmp_path / "sessions"
|
||||
sessions = SessionManager(workspace, sessions_root=sessions_root)
|
||||
config = Config.model_validate({"agents": {"defaults": {
|
||||
"workspace": str(workspace), "model": "test-model", "sessionTtlMinutes": 0,
|
||||
}}})
|
||||
bus = MessageBus()
|
||||
loop = AgentLoop.from_config(
|
||||
config, bus, provider=Provider(), session_manager=sessions, tool_registry=ToolRegistry(),
|
||||
)
|
||||
session_key = "slack:C1:1234.5678"
|
||||
slack_route = {"thread_ts": "1234.5678", "channel_type": "channel"}
|
||||
thread_metadata = {"slack": {"thread_ts": "1234.5678"}}
|
||||
|
||||
def observe_idle(event):
|
||||
if event.context.session_key == session_key and event.status == "idle":
|
||||
parent_idle.set()
|
||||
|
||||
unsubscribe = bus.subscribe(observe_idle, TurnRunStatusChanged)
|
||||
|
||||
async def next_reply(content):
|
||||
async with asyncio.timeout(5):
|
||||
while True:
|
||||
message = await bus.consume_outbound()
|
||||
if message.content == content and message.event is None:
|
||||
return message
|
||||
|
||||
consumer = asyncio.create_task(loop.run())
|
||||
try:
|
||||
await bus.publish_inbound(InboundMessage(
|
||||
channel="slack", sender_id="U1", chat_id="C1", content="Delegate this inspection",
|
||||
metadata={"slack": slack_route}, session_key_override=session_key,
|
||||
))
|
||||
initial_reply = await next_reply("Parent reply")
|
||||
await asyncio.wait_for(child_started.wait(), timeout=5)
|
||||
await asyncio.wait_for(parent_idle.wait(), timeout=5)
|
||||
saved = SessionManager(workspace, sessions_root=sessions_root).get_existing(session_key)
|
||||
assert saved is not None
|
||||
saved_route = saved.metadata["_compaction_route"]
|
||||
release_child.set()
|
||||
late_reply = await next_reply("Late follow-up")
|
||||
|
||||
assert (initial_reply.channel, initial_reply.chat_id) == ("slack", "C1")
|
||||
assert initial_reply.metadata["slack"] == slack_route
|
||||
assert saved_route == {"channel": "slack", "chat_id": "C1", "metadata": thread_metadata}
|
||||
assert (late_reply.channel, late_reply.chat_id) == ("slack", "C1")
|
||||
assert late_reply.metadata == thread_metadata
|
||||
finally:
|
||||
release_child.set()
|
||||
loop.stop()
|
||||
await asyncio.wait_for(consumer, timeout=2)
|
||||
unsubscribe()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_owner_canonical_fallback_and_absent_context(tmp_path):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
"""Regression coverage for the executable Python import boundaries."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from scripts.check_import_boundaries import Violation, find_violations
|
||||
|
||||
|
||||
def test_repository_respects_import_boundaries() -> None:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "scripts.check_import_boundaries"],
|
||||
cwd=Path(__file__).resolve().parents[2],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("source", "target", "line"),
|
||||
[
|
||||
("import nanobot.webui.metadata", "nanobot.webui.metadata", 1),
|
||||
("from nanobot import webui", "nanobot.webui", 1),
|
||||
("from nanobot.webui import metadata", "nanobot.webui.metadata", 1),
|
||||
("from .. import webui", "nanobot.webui", 1),
|
||||
("from ..webui import metadata", "nanobot.webui.metadata", 1),
|
||||
(
|
||||
"def load():\n from nanobot.cli import gateway",
|
||||
"nanobot.cli.gateway", 2,
|
||||
),
|
||||
(
|
||||
"import importlib\nimportlib.import_module('nanobot.webui.metadata')",
|
||||
"nanobot.webui.metadata", 2,
|
||||
),
|
||||
(
|
||||
"import importlib as modules\n"
|
||||
"modules.import_module(name='nanobot.webui.metadata')",
|
||||
"nanobot.webui.metadata", 2,
|
||||
),
|
||||
(
|
||||
"from importlib import import_module as load\n"
|
||||
"load('..webui.metadata', __package__)",
|
||||
"nanobot.webui.metadata", 2,
|
||||
),
|
||||
(
|
||||
"from importlib import import_module\n"
|
||||
"import_module('..webui.metadata', package='nanobot.agent')",
|
||||
"nanobot.webui.metadata", 2,
|
||||
),
|
||||
("__import__('nanobot.webui.metadata')", "nanobot.webui.metadata", 1),
|
||||
(
|
||||
"import builtins as imports\nimports.__import__('nanobot.webui.metadata')",
|
||||
"nanobot.webui.metadata", 2,
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_core_rejects_adapter_imports_in_supported_spellings(
|
||||
source: str, target: str, line: int,
|
||||
) -> None:
|
||||
assert find_violations(source, "nanobot.agent.loop") == [
|
||||
Violation("core-execution", target, line),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"source",
|
||||
[
|
||||
"from typing import TYPE_CHECKING as TC\n"
|
||||
"if TC:\n from nanobot.webui import metadata",
|
||||
"import typing as t\n"
|
||||
"if t.TYPE_CHECKING:\n from nanobot.webui import metadata",
|
||||
],
|
||||
)
|
||||
def test_core_boundary_includes_type_dependencies(source: str) -> None:
|
||||
assert find_violations(source, "nanobot.agent.runner") == [
|
||||
Violation("core-execution", "nanobot.webui.metadata", 3),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("module", "rule"),
|
||||
[
|
||||
("nanobot.session.manager", "session-storage"),
|
||||
("nanobot.session.recovery", "session-storage"),
|
||||
("nanobot.security.workspace_policy", "security-primitives"),
|
||||
("nanobot.agent.turn_delivery", "core-execution"),
|
||||
("nanobot.channels.notification_routes", "channel-routing-contracts"),
|
||||
("nanobot.config.schema", "configuration-contracts"),
|
||||
("nanobot.agent.tools.cli_apps_config", "tool-configuration-contracts"),
|
||||
("nanobot.utils.file_io", "shared-primitives"),
|
||||
],
|
||||
)
|
||||
def test_storage_and_security_do_not_depend_on_adapters(module: str, rule: str) -> None:
|
||||
assert find_violations("from nanobot.cli import gateway", module) == [
|
||||
Violation(rule, "nanobot.cli.gateway", 1),
|
||||
]
|
||||
|
||||
|
||||
def test_websocket_only_permits_progress_event_as_a_type_dependency() -> None:
|
||||
source = (
|
||||
"from typing import TYPE_CHECKING\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from nanobot.bus.outbound_events import ProgressEvent\n"
|
||||
" from nanobot.command import router\n"
|
||||
"else:\n"
|
||||
" from nanobot.bus.outbound_events import ProgressEvent\n"
|
||||
)
|
||||
assert find_violations(source, "nanobot.channels.websocket.runtime") == [
|
||||
Violation("websocket-transport", "nanobot.command.router", 4),
|
||||
Violation("websocket-transport", "nanobot.bus.outbound_events.ProgressEvent", 6),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"source",
|
||||
[
|
||||
"from nanobot.config.schema import Base",
|
||||
"from ...config.schema import Base as ConfigBase",
|
||||
],
|
||||
)
|
||||
def test_tool_configs_import_the_shared_base_directly(source: str) -> None:
|
||||
assert find_violations(source, "nanobot.agent.tools.shell") == [
|
||||
Violation("tool-config-base", "nanobot.config.schema.Base", 1),
|
||||
]
|
||||
assert find_violations(
|
||||
"from nanobot.config_base import Base", "nanobot.agent.tools.shell",
|
||||
) == []
|
||||
|
||||
|
||||
def test_configuration_imports_the_six_tool_owned_config_contracts() -> None:
|
||||
source = (
|
||||
"from nanobot.agent.tools.cli_apps_config import CliAppsToolConfig\n"
|
||||
"from nanobot.agent.tools.filesystem_config import FileToolsConfig\n"
|
||||
"from nanobot.agent.tools.image_generation_config import ImageGenerationToolConfig\n"
|
||||
"from nanobot.agent.tools.self_config import MyToolConfig\n"
|
||||
"from nanobot.agent.tools.shell_config import ExecToolConfig\n"
|
||||
"from nanobot.agent.tools.web_config import WebToolsConfig\n"
|
||||
)
|
||||
assert find_violations(source, "nanobot.config.schema") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("module", "source"),
|
||||
[
|
||||
("nanobot.agent.loop", "from nanobot.session.recovery import RecoveryAdmission"),
|
||||
("nanobot.session.manager", "from nanobot.providers.base import ProviderConversationState"),
|
||||
("nanobot.session.webui_turns", "from nanobot.webui import transcript"),
|
||||
("nanobot.cli.gateway_runtime", "from nanobot.agent.loop import AgentLoop"),
|
||||
("nanobot.channels.websocket.runtime", "from nanobot.webui import inbound_commands"),
|
||||
("nanobot.agent.tools.cli_apps_config", "from nanobot.config_base import Base"),
|
||||
(
|
||||
"nanobot.agent.turn_delivery",
|
||||
"from nanobot.channels.notification_routes import notification_metadata",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_existing_runtime_and_composition_dependencies_remain_allowed(
|
||||
module: str, source: str,
|
||||
) -> None:
|
||||
assert find_violations(source, module) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("relative", "source", "rule", "target", "line"),
|
||||
[
|
||||
(
|
||||
"nanobot/agent/runner.py", "import nanobot.webui.metadata",
|
||||
"core-execution", "nanobot.webui.metadata", 1,
|
||||
),
|
||||
(
|
||||
"nanobot/agent/loop.py",
|
||||
"import importlib\nif importlib.import_module('nanobot.webui.metadata'):\n pass",
|
||||
"core-execution", "nanobot.webui.metadata", 2,
|
||||
),
|
||||
(
|
||||
"nanobot/agent/loop.py", "if __import__('nanobot.webui.metadata'):\n pass",
|
||||
"core-execution", "nanobot.webui.metadata", 1,
|
||||
),
|
||||
(
|
||||
"nanobot/session/manager.py", "from nanobot.cli import gateway",
|
||||
"session-storage", "nanobot.cli.gateway", 1,
|
||||
),
|
||||
(
|
||||
"nanobot/channels/notification_routes.py",
|
||||
"from nanobot.channels.slack.runtime import SlackChannel",
|
||||
"channel-routing-contracts", "nanobot.channels.slack.runtime.SlackChannel", 1,
|
||||
),
|
||||
(
|
||||
"nanobot/channels/notification_routes.py",
|
||||
"from nanobot.agent.turn_delivery import TurnRoute",
|
||||
"channel-routing-contracts", "nanobot.agent.turn_delivery.TurnRoute", 1,
|
||||
),
|
||||
(
|
||||
"nanobot/security/__init__.py", "from ..cli import gateway",
|
||||
"security-primitives", "nanobot.cli.gateway", 1,
|
||||
),
|
||||
(
|
||||
"nanobot/channels/websocket/runtime.py",
|
||||
"import importlib as modules\nmodules.import_module('nanobot.command.router')",
|
||||
"websocket-transport", "nanobot.command.router", 2,
|
||||
),
|
||||
(
|
||||
"nanobot/agent/tools/shell.py", "from ...config.schema import Base as ConfigBase",
|
||||
"tool-config-base", "nanobot.config.schema.Base", 1,
|
||||
),
|
||||
(
|
||||
"nanobot/channels/telegram/runtime.py", "from nanobot.config.schema import Base",
|
||||
"tool-config-base", "nanobot.config.schema.Base", 1,
|
||||
),
|
||||
(
|
||||
"nanobot/config/schema.py", "from nanobot.agent.tools.shell import ExecTool",
|
||||
"configuration-contracts", "nanobot.agent.tools.shell.ExecTool", 1,
|
||||
),
|
||||
(
|
||||
"nanobot/agent/tools/cli_apps_config.py", "from .cli_apps import CliAppsTool",
|
||||
"tool-configuration-contracts", "nanobot.agent.tools.cli_apps.CliAppsTool", 1,
|
||||
),
|
||||
(
|
||||
"nanobot/agent/tools/web_config.py", "from nanobot.config.schema import Config",
|
||||
"tool-configuration-contracts", "nanobot.config.schema.Config", 1,
|
||||
),
|
||||
(
|
||||
"nanobot/providers/oauth_catalog_cache.py",
|
||||
"from nanobot.providers import openai_codex_provider",
|
||||
"oauth-catalog-cache", "nanobot.providers.openai_codex_provider", 1,
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_cli_rejects_a_violation_and_reports_its_source_location(
|
||||
tmp_path: Path, relative: str, source: str, rule: str, target: str, line: int,
|
||||
) -> None:
|
||||
path = tmp_path / relative
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text(source + "\n", encoding="utf-8")
|
||||
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "scripts.check_import_boundaries", "--root", str(tmp_path)],
|
||||
cwd=Path(__file__).resolve().parents[2],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == 1
|
||||
assert result.stderr.strip() == f"{relative}:{line}: [{rule}] must not import {target}"
|
||||
|
||||
|
||||
def test_cli_accepts_a_tool_owned_config_import(tmp_path: Path) -> None:
|
||||
path = tmp_path / "nanobot/config/schema.py"
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text(
|
||||
"from nanobot.agent.tools.cli_apps_config import CliAppsToolConfig\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "scripts.check_import_boundaries", "--root", str(tmp_path)],
|
||||
cwd=Path(__file__).resolve().parents[2],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
@@ -2637,7 +2637,7 @@ def test_optional_dependency_metadata_for_enable():
|
||||
required = data["project"]["dependencies"]
|
||||
|
||||
assert "boto3>=1.43.0" not in data["project"]["dependencies"]
|
||||
assert deps["bedrock"] == ["boto3>=1.43.0"]
|
||||
assert deps["bedrock"] == ["boto3>=1.43.0", "botocore>=1.43.0,<2.0.0"]
|
||||
# The built-in remote WebUI proxy now needs aiohttp even without channels.
|
||||
# Keep the historical API extra installable for existing deployment commands.
|
||||
assert "aiohttp>=3.14.3,<4.0.0" in required
|
||||
@@ -2729,6 +2729,8 @@ def test_optional_dependency_metadata_for_enable():
|
||||
"weixin": ("qrcode[pil]>=8.0", "pycryptodome>=3.20.0"),
|
||||
"whatsapp": (
|
||||
"neonize>=0.4.3.post0,<0.5.0",
|
||||
"python-magic>=0.4.27; sys_platform != 'win32'",
|
||||
"python-magic-bin>=0.4.14; sys_platform == 'win32'",
|
||||
"segno>=1.6.1,<2.0.0",
|
||||
),
|
||||
}
|
||||
|
||||
@@ -10,18 +10,6 @@ from nanobot.channels.websocket import runtime
|
||||
_REPOSITORY_ROOT = Path(__file__).resolve().parents[2]
|
||||
_RUNTIME_PATH = _REPOSITORY_ROOT / "nanobot" / "channels" / "websocket" / "runtime.py"
|
||||
_SESSION_IDENTITY_PATH = _REPOSITORY_ROOT / "nanobot" / "webui" / "session_identity.py"
|
||||
_FORBIDDEN_RUNTIME_IMPORTS = (
|
||||
"nanobot.bus.outbound_events",
|
||||
"nanobot.command",
|
||||
"nanobot.runtime_context",
|
||||
"nanobot.security.workspace_access",
|
||||
"nanobot.session.goal_state",
|
||||
"nanobot.webui.cli_apps_api",
|
||||
"nanobot.webui.forking",
|
||||
"nanobot.webui.mcp_presets_api",
|
||||
"nanobot.webui.sidebar_state",
|
||||
"nanobot.webui.transcription_ws",
|
||||
)
|
||||
|
||||
|
||||
def _channel_method(name: str) -> ast.AsyncFunctionDef:
|
||||
@@ -50,21 +38,6 @@ def _statements_without_docstring(node: ast.AsyncFunctionDef) -> list[ast.stmt]:
|
||||
return body
|
||||
|
||||
|
||||
def test_websocket_runtime_does_not_import_application_command_trees() -> None:
|
||||
tree = ast.parse(_RUNTIME_PATH.read_text(encoding="utf-8"))
|
||||
imported = {
|
||||
node.module
|
||||
for node in tree.body
|
||||
if isinstance(node, ast.ImportFrom) and node.module is not None
|
||||
}
|
||||
violations = sorted(
|
||||
module
|
||||
for module in imported
|
||||
if module.startswith(_FORBIDDEN_RUNTIME_IMPORTS)
|
||||
)
|
||||
assert violations == []
|
||||
|
||||
|
||||
def test_business_entrypoints_are_thin_transport_delegations() -> None:
|
||||
for method_name in ("_dispatch_envelope", "_hydrate_after_subscribe", "send"):
|
||||
statements = _statements_without_docstring(_channel_method(method_name))
|
||||
|
||||
@@ -35,7 +35,6 @@ from nanobot.providers.factory import ProviderSnapshot, make_provider, provider_
|
||||
from nanobot.providers.openai_codex_provider import _strip_model_prefix
|
||||
from nanobot.providers.registry import find_by_name
|
||||
from nanobot.providers.unconfigured_provider import UnconfiguredProvider
|
||||
from nanobot.session.webui_turns import WebuiTurnRoutePolicy
|
||||
from nanobot.webui.dev import WebUIDevError
|
||||
from nanobot.webui.metadata import (
|
||||
WEBUI_MESSAGE_SOURCE_METADATA_KEY,
|
||||
@@ -287,6 +286,9 @@ def test_commit_dream_changes_commits_real_edits(tmp_path) -> None:
|
||||
@pytest.fixture
|
||||
def mock_paths():
|
||||
"""Mock config/workspace paths for test isolation."""
|
||||
from importlib import import_module
|
||||
|
||||
import_module("nanobot.channels.validation")
|
||||
with patch("nanobot.config.loader.get_config_path") as mock_cp, \
|
||||
patch("nanobot.config.loader.save_config") as mock_sc, \
|
||||
patch("nanobot.config.loader.load_config") as mock_lc, \
|
||||
@@ -2041,6 +2043,12 @@ def _patch_cli_command_runtime(
|
||||
cron_service=None,
|
||||
get_cron_dir=None,
|
||||
) -> None:
|
||||
from importlib import import_module
|
||||
|
||||
# Load adapter contracts before replacing runtime factories for this invocation.
|
||||
import_module("nanobot.session.webui_turns")
|
||||
import_module("nanobot.channels.validation")
|
||||
import_module("nanobot.channels.websocket.runtime")
|
||||
provider_factory = make_provider or (lambda _config: _fake_provider())
|
||||
|
||||
monkeypatch.setattr(
|
||||
@@ -3591,8 +3599,27 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
|
||||
assert isinstance(turn_delivery_factory, TurnDeliveryFactory)
|
||||
assert turn_delivery_factory.bus is bus
|
||||
assert seen["cron_reconciliation"] == ["remove:dream", "remove:heartbeat", "status"]
|
||||
assert isinstance(turn_delivery_factory.route_policy, WebuiTurnRoutePolicy)
|
||||
assert turn_delivery_factory.route_policy.sessions is agent.sessions
|
||||
websocket_delivery = turn_delivery_factory.create(
|
||||
InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="chat", content="Hello",
|
||||
metadata={"webui": True, "webui_turn_id": "turn-1"},
|
||||
),
|
||||
"websocket:chat",
|
||||
)
|
||||
assert websocket_delivery.route.turn_id == "turn-1"
|
||||
assert websocket_delivery.route.metadata["_websocket_turn_owner"]
|
||||
slack_delivery = turn_delivery_factory.create(
|
||||
InboundMessage(
|
||||
channel="system", sender_id="subagent", chat_id="slack:C1", content="Done",
|
||||
),
|
||||
"slack:C1:1234.5678",
|
||||
)
|
||||
assert slack_delivery.route.metadata["slack"] == {"thread_ts": "1234.5678"}
|
||||
session_metadata = {}
|
||||
slack_delivery.remember_session_route(session_metadata)
|
||||
assert session_metadata["_compaction_route"] == {
|
||||
"channel": "slack", "chat_id": "C1", "metadata": {"slack": {"thread_ts": "1234.5678"}},
|
||||
}
|
||||
|
||||
|
||||
def test_gateway_workspace_override_does_not_migrate_legacy_cron(
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import ast
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from importlib import import_module
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_config_base_import_does_not_load_config_schema():
|
||||
@@ -20,19 +21,90 @@ print("nanobot.config.schema" in sys.modules)
|
||||
assert result.stdout.strip() == "False"
|
||||
|
||||
|
||||
def test_builtin_tool_configs_do_not_depend_on_config_schema_base():
|
||||
repo = Path(__file__).resolve().parents[2]
|
||||
tool_paths = sorted((repo / "nanobot/agent/tools").glob("*.py"))
|
||||
def test_config_validation_and_schema_generation_do_not_import_runtime_implementations():
|
||||
code = """
|
||||
import importlib.abc
|
||||
import sys
|
||||
|
||||
violations = []
|
||||
for path in tool_paths:
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"))
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, ast.ImportFrom):
|
||||
continue
|
||||
if node.module != "nanobot.config.schema":
|
||||
continue
|
||||
if any(alias.name == "Base" for alias in node.names):
|
||||
violations.append(str(path.relative_to(repo)))
|
||||
class RuntimeImportBlocker(importlib.abc.MetaPathFinder):
|
||||
def find_spec(self, fullname, path, target=None):
|
||||
config_modules = {
|
||||
'nanobot.agent', 'nanobot.agent.tools',
|
||||
'nanobot.agent.tools.cli_apps_config',
|
||||
'nanobot.agent.tools.filesystem_config',
|
||||
'nanobot.agent.tools.image_generation_config',
|
||||
'nanobot.agent.tools.self_config',
|
||||
'nanobot.agent.tools.shell_config',
|
||||
'nanobot.agent.tools.web_config',
|
||||
}
|
||||
if fullname in config_modules:
|
||||
return None
|
||||
forbidden = (
|
||||
'nanobot.agent', 'nanobot.api', 'nanobot.apps', 'nanobot.channels',
|
||||
'nanobot.cli', 'nanobot.session', 'nanobot.webui', 'nanobot.providers.base',
|
||||
)
|
||||
if any(fullname == name or fullname.startswith(name + '.') for name in forbidden):
|
||||
raise AssertionError('configuration imported runtime implementation: ' + fullname)
|
||||
|
||||
assert violations == []
|
||||
sys.meta_path.insert(0, RuntimeImportBlocker())
|
||||
from nanobot.config import Config
|
||||
from nanobot.config.schema import ModelPresetConfig
|
||||
|
||||
config = Config.model_validate({'tools': {
|
||||
'exec': {'timeout': 37},
|
||||
'imageGeneration': {
|
||||
'enabled': True,
|
||||
'extraHeaders': {'X-Image-Mode': 'test'},
|
||||
'extraBody': {'quality': 'high', 'provider': {'order': ['example']}},
|
||||
},
|
||||
}})
|
||||
assert config.tools.exec.timeout == 37
|
||||
restored = Config.model_validate_json(config.model_dump_json(by_alias=True))
|
||||
assert restored.tools.exec.timeout == 37
|
||||
assert restored.tools.image_generation.enabled is True
|
||||
assert restored.tools.image_generation.extra_headers == {'X-Image-Mode': 'test'}
|
||||
assert restored.tools.image_generation.extra_body == {
|
||||
'quality': 'high', 'provider': {'order': ['example']},
|
||||
}
|
||||
assert Config.model_json_schema()['properties']['tools']
|
||||
assert ModelPresetConfig(model='example').to_generation_settings().max_tokens == 8192
|
||||
"""
|
||||
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
def test_public_tool_contracts_can_be_imported_without_agent_execution():
|
||||
code = """
|
||||
import sys
|
||||
from nanobot.agent.tools import Tool, ToolResult, tool_parameters
|
||||
from nanobot.agent.tools.base import Tool as BaseTool
|
||||
|
||||
assert Tool is BaseTool
|
||||
assert callable(tool_parameters)
|
||||
assert ToolResult
|
||||
assert 'nanobot.agent.loop' not in sys.modules
|
||||
assert 'nanobot.agent.runner' not in sys.modules
|
||||
assert 'nanobot.agent.tools.shell' not in sys.modules
|
||||
"""
|
||||
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("module", "names"),
|
||||
[
|
||||
("cli_apps", ("CliAppsToolConfig",)),
|
||||
("filesystem", ("FileToolsConfig",)),
|
||||
("image_generation", ("ImageGenerationToolConfig",)),
|
||||
("self", ("MyToolConfig",)),
|
||||
("shell", ("ExecToolConfig",)),
|
||||
("web", ("WebSearchConfig", "WebFetchConfig", "WebToolsConfig")),
|
||||
],
|
||||
)
|
||||
def test_tool_config_imports_keep_the_same_public_class(module, names):
|
||||
contracts = import_module(f"nanobot.agent.tools.{module}_config")
|
||||
aggregate = import_module("nanobot.config.schema")
|
||||
implementation = import_module(f"nanobot.agent.tools.{module}")
|
||||
for name in names:
|
||||
assert getattr(implementation, name) is getattr(contracts, name)
|
||||
assert getattr(aggregate, name) is getattr(contracts, name)
|
||||
@@ -14,13 +14,12 @@ from nanobot.session.recovery import (
|
||||
PENDING_USER_TURN_KEY,
|
||||
RECOVERY_METADATA_KEY,
|
||||
RUNTIME_CHECKPOINT_KEY,
|
||||
RecoveryActionError,
|
||||
RecoveryCoordinator,
|
||||
acknowledge_pending_followups,
|
||||
pending_followups,
|
||||
record_pending_followup,
|
||||
)
|
||||
from nanobot.webui import session_list_index, transcript
|
||||
from nanobot.webui.recovery import RecoveryActionError, RecoveryCoordinator
|
||||
|
||||
|
||||
def _persist(manager: SessionManager, session: Session) -> None:
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import posixpath
|
||||
import shlex
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
@@ -37,3 +39,10 @@ def test_tui_source_archive_preserves_shared_module_import_path():
|
||||
assert "nanobot-tui-source/packages/client-events/notifications.ts" in names
|
||||
assert "nanobot-tui-source/tui/bun.lock" in names
|
||||
assert "nanobot-tui-source/LICENSE" in names
|
||||
package = archive.extractfile("nanobot-tui-source/tui/package.json")
|
||||
assert package is not None
|
||||
scripts = json.load(package)["scripts"]
|
||||
for command in ("check:imports", "test:imports"):
|
||||
entrypoint = next(arg for arg in shlex.split(scripts[command]) if arg.endswith(".mjs"))
|
||||
archived_path = posixpath.normpath(f"nanobot-tui-source/tui/{entrypoint}")
|
||||
assert archived_path in names
|
||||
Reference in new issue
Block a user