refactor: remove redundant comments and docstrings (#6527)

* refactor: remove redundant comments and docstrings

* fix(signal): annotate async context manager as a generator
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-30 13:07:03 +08:00
1 parent cb3ba45317
commit a4d2430140
922 files changed
+406 -7738

No files matched your search

-2
View File
@@ -1,5 +1,3 @@
"""Tests for sustained goal tools (``create_goal``, ``update_goal``)."""
from __future__ import annotations
import asyncio
-10
View File
@@ -1,5 +1,3 @@
"""Contract and security regressions for the MyTool runtime boundary."""
from __future__ import annotations
import asyncio
@@ -73,7 +71,6 @@ def wire_request(request):
max_tokens=100, temperature=0.7, reasoning_effort=None,
tool_choice=call.get("tool_choice"),
)
# Keep the protocol's real item shape, but use one name for prefix comparisons.
if "input" in body:
body["messages"] = body.pop("input")
return body
@@ -302,7 +299,6 @@ async def test_workspace_inspection_matches_registered_file_tool(
definitions = json.dumps(loop.tools.get_definitions(), sort_keys=True)
token = bind_workspace_scope(build_workspace_scope(project, mode))
try:
# Legacy display writes must not spoof the effective directory or permission.
await tool.execute(action="set", key="workspace", value=str(outside.parent))
status = tool._runtime_control.snapshot().workspace_sandbox
assert status["workspace_root"] == str(project.resolve())
@@ -320,7 +316,6 @@ async def test_workspace_inspection_matches_registered_file_tool(
assert "project marker" in await loop.tools.execute("read_file", {"path": "marker.txt"})
result = await loop.tools.execute("read_file", {"path": str(outside)})
assert ("outside allowed directory" if restricted else "outside marker") in result
# The directory and permission enter tool results, not the reusable tool schemas.
assert json.dumps(loop.tools.get_definitions(), sort_keys=True) == definitions
status["workspace_root"] = "changed snapshot"
assert tool._runtime_control.snapshot().workspace_sandbox["workspace_root"] == str(project.resolve())
@@ -429,7 +424,6 @@ async def test_workspace_context_uses_request_scope_not_active_tool_scope(
loop = _make_loop(tmp_path / "agent", sandbox=sandbox)
control = _my_tool(loop)._runtime_control
scope = build_workspace_scope(tmp_path / "new-project", mode)
# Pending user inputs are prepared while the earlier turn is still bound.
token = bind_workspace_scope(build_workspace_scope(tmp_path / "old-project", "restricted"))
try:
block = await control.workspace_context(RequestContext("websocket", "chat", workspace_scope=scope))
@@ -486,7 +480,6 @@ async def test_access_changes_refresh_only_new_message_and_preserve_prefix(tmp_p
)
calls = provider.chat_stream_with_retry.await_args_list
first, second, third = [LLMProvider._sanitize_empty_content(call.kwargs["messages"]) for call in calls]
# Access changes belong to the new request, not a rewrite of the cached history.
assert json.dumps(second[:len(first)]) == json.dumps(first)
assert "File access: project and tool-specific allowed paths only." in first[-1]["content"]
assert "File access: no workspace restriction." in second[-1]["content"]
@@ -586,7 +579,6 @@ async def test_workspace_context_compaction_reuses_serialized_prefix(
assert compact_wire[:len(first_wire)] == first_wire
assert compact["tools"] == first["tools"]
before, after = wire_request(first), wire_request(compact)
# JSON object field order is not model input; preserve every value and array order.
assert json.dumps(
after["messages"][:len(before["messages"])], sort_keys=True,
) == json.dumps(before["messages"], sort_keys=True)
@@ -616,7 +608,6 @@ async def test_workspace_context_transient_retry_keeps_exact_wire_request(
)
return LLMResponse(content="done")
# Keep the production retry policy; replace only transport and backoff waiting.
monkeypatch.setattr(provider, "chat_stream_with_context", respond)
monkeypatch.setattr(provider, "_sleep_with_heartbeat", AsyncMock())
loop.provider.chat_stream_with_retry = provider.chat_stream_with_retry
@@ -653,7 +644,6 @@ async def test_subagent_rejects_missing_action_inputs(tmp_path, runtime, params)
async def test_subagent_check_is_session_scoped(tmp_path, single_task, runtime):
loop = _make_loop(tmp_path)
manager = loop.subagents
# Queued tasks must be scoped before their runner starts.
for _ in range(manager.max_concurrent_subagents):
await manager._run_slots.acquire()
await manager.spawn("ALPHA_PRIVATE_TASK", label="ALPHA_LABEL", session_key="owner:a", runtime=runtime)
-115
View File
@@ -1,5 +1,3 @@
"""Tests for MyTool — runtime state inspection and configuration."""
from __future__ import annotations
import time
@@ -17,9 +15,6 @@ from nanobot.agent.tools.web import WebSearchConfig, WebToolsConfig
from nanobot.config.schema import ModelPresetConfig
from nanobot.providers.base import LLMUsage
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_mock_loop(**overrides):
"""Build a lightweight mock AgentLoop with the attributes MyTool reads."""
@@ -47,18 +42,15 @@ def _make_mock_loop(**overrides):
value,
)
# web_config mock — needed for check tests
loop.web_config = WebToolsConfig()
loop.web_config.search.api_key = "sk-secret-key-12345"
# Tools registry mock
loop.tools = MagicMock()
loop.tools.tool_names = ["read_file", "write_file", "exec", "web_search", "self"]
loop.tools.has.side_effect = lambda n: n in loop.tools.tool_names
loop.tools.get.return_value = None
loop.tool_names = loop.tools.tool_names
# SubagentManager mock
loop.subagents = MagicMock()
for k, v in overrides.items():
@@ -73,10 +65,6 @@ def _make_tool(loop=None):
return MyTool(runtime_control=AgentRuntimeControl(loop))
# ---------------------------------------------------------------------------
# check — no key (summary)
# ---------------------------------------------------------------------------
class TestInspectSummary:
@pytest.mark.asyncio
@@ -99,10 +87,6 @@ class TestInspectSummary:
assert "task" in result
# ---------------------------------------------------------------------------
# check — single key (direct)
# ---------------------------------------------------------------------------
class TestInspectSingleKey:
@pytest.mark.asyncio
@@ -131,15 +115,10 @@ class TestInspectSingleKey:
assert "not found" in result
# ---------------------------------------------------------------------------
# check — dot-path navigation
# ---------------------------------------------------------------------------
class TestInspectPathNavigation:
@pytest.mark.asyncio
async def test_inspect_config_subfield(self):
"""Positive control for sensitive-field blocking: ordinary config stays inspectable."""
loop = _make_mock_loop()
tool = _make_tool(loop=loop)
result = await tool.execute(action="check", key="web_config.enable")
@@ -153,7 +132,6 @@ class TestInspectPathNavigation:
@pytest.mark.asyncio
async def test_inspect_tools_returns_blocked(self):
"""tools is BLOCKED — check should return access error."""
tool = _make_tool()
result = await tool.execute(action="check", key="tools")
assert "not accessible" in result
@@ -174,11 +152,6 @@ class TestInspectPathNavigation:
assert "api_key" not in result.lower()
# ---------------------------------------------------------------------------
# set — restricted (with validation)
# ---------------------------------------------------------------------------
class TestModifyRestricted:
@pytest.mark.asyncio
@@ -236,10 +209,6 @@ class TestModifyRestricted:
assert "Error" in result
# ---------------------------------------------------------------------------
# set — blocked (minimal set)
# ---------------------------------------------------------------------------
class TestModifyBlocked:
@pytest.mark.asyncio
@@ -268,7 +237,6 @@ class TestModifyBlocked:
@pytest.mark.asyncio
async def test_modify_dotpath_leaf_dunder_blocked(self):
"""Fix 3.1: leaf segment of dot-path must also be validated."""
tool = _make_tool()
result = await tool.execute(
action="set",
@@ -279,7 +247,6 @@ class TestModifyBlocked:
@pytest.mark.asyncio
async def test_modify_dotpath_leaf_denied_attr_blocked(self):
"""Fix 3.1: leaf segment matching _DENIED_ATTRS must be rejected."""
tool = _make_tool()
result = await tool.execute(
action="set",
@@ -289,15 +256,10 @@ class TestModifyBlocked:
assert "not accessible" in result
# ---------------------------------------------------------------------------
# set — free tier (setattr priority)
# ---------------------------------------------------------------------------
class TestRuntimeSettingsAndScratchpad:
@pytest.mark.asyncio
async def test_set_updates_runtime_setting(self):
"""Set a runtime setting through the runtime-control capability."""
tool = _make_tool()
result = await tool.execute(action="set", key="provider_retry_mode", value="persistent")
assert "Set provider_retry_mode" in result
@@ -305,7 +267,6 @@ class TestRuntimeSettingsAndScratchpad:
@pytest.mark.asyncio
async def test_modify_new_key_stores_in_scratchpad(self):
"""Modifying an unknown key should store it in the scratchpad."""
tool = _make_tool()
result = await tool.execute(action="set", key="my_custom_var", value="hello")
assert "my_custom_var" in result
@@ -368,7 +329,6 @@ class TestRuntimeSettingsAndScratchpad:
@pytest.mark.asyncio
async def test_modify_existing_attr_type_mismatch_rejected(self):
"""Setting a string attr to int should be rejected."""
tool = _make_tool()
result = await tool.execute(action="set", key="provider_retry_mode", value=42)
assert "Error" in result
@@ -377,22 +337,16 @@ class TestRuntimeSettingsAndScratchpad:
@pytest.mark.asyncio
async def test_modify_existing_int_attr_wrong_type_rejected(self):
"""Setting an int attr to string should be rejected."""
tool = _make_tool()
result = await tool.execute(action="set", key="max_tool_result_chars", value="big")
assert "Error" in result
assert tool._runtime_control.snapshot().max_tool_result_chars == 16000
# ---------------------------------------------------------------------------
# set — previously BLOCKED/READONLY now open
# ---------------------------------------------------------------------------
class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_tools_blocked(self):
"""tools is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_registry = MagicMock()
result = await tool.execute(action="set", key="tools", value=new_registry)
@@ -400,7 +354,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_subagents_blocked(self):
"""Subagent control is outside the self-inspection capability."""
tool = _make_tool()
new_subagents = MagicMock()
result = await tool.execute(action="set", key="subagents", value=new_subagents)
@@ -408,7 +361,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_runner_blocked(self):
"""runner is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_runner = MagicMock()
result = await tool.execute(action="set", key="runner", value=new_runner)
@@ -416,7 +368,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_sessions_blocked(self):
"""sessions is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_sessions = MagicMock()
result = await tool.execute(action="set", key="sessions", value=new_sessions)
@@ -424,7 +375,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_consolidator_blocked(self):
"""consolidator is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_consolidator = MagicMock()
result = await tool.execute(action="set", key="consolidator", value=new_consolidator)
@@ -432,7 +382,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_dream_blocked(self):
"""dream is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_dream = MagicMock()
result = await tool.execute(action="set", key="dream", value=new_dream)
@@ -440,7 +389,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_auto_compact_blocked(self):
"""auto_compact is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_auto_compact = MagicMock()
result = await tool.execute(action="set", key="auto_compact", value=new_auto_compact)
@@ -448,7 +396,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_context_blocked(self):
"""context is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_context = MagicMock()
result = await tool.execute(action="set", key="context", value=new_context)
@@ -456,7 +403,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_commands_blocked(self):
"""commands is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_commands = MagicMock()
result = await tool.execute(action="set", key="commands", value=new_commands)
@@ -464,7 +410,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_workspace_preserves_display_compatibility(self):
"""The compatibility value is isolated from filesystem security boundaries."""
tool = _make_tool()
result = await tool.execute(action="set", key="workspace", value="/new/path")
assert "Set workspace" in result
@@ -486,30 +431,23 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_background_tasks_blocked(self):
"""_background_tasks tracks background tasks — must be blocked."""
tool = _make_tool()
result = await tool.execute(action="set", key="_background_tasks", value=[])
assert "protected" in result
@pytest.mark.asyncio
async def test_modify_wrapped_denied(self):
"""__wrapped__ allows decorator bypass — must be denied."""
tool = _make_tool()
result = await tool.execute(action="set", key="__wrapped__", value="evil")
assert "protected" in result
@pytest.mark.asyncio
async def test_modify_closure_denied(self):
"""__closure__ exposes function internals — must be denied."""
tool = _make_tool()
result = await tool.execute(action="set", key="__closure__", value="evil")
assert "protected" in result
# ---------------------------------------------------------------------------
# validate_json_safe — element counting
# ---------------------------------------------------------------------------
class TestValidateJsonSafe:
def test_single_list_passes(self):
@@ -520,10 +458,6 @@ class TestValidateJsonSafe:
assert MyTool._validate_json_safe(value) is None
# ---------------------------------------------------------------------------
# unknown action
# ---------------------------------------------------------------------------
class TestUnknownAction:
@pytest.mark.asyncio
@@ -533,10 +467,6 @@ class TestUnknownAction:
assert "Unknown action" in result
# ---------------------------------------------------------------------------
# scratchpad limits
# ---------------------------------------------------------------------------
class TestScratchpadLimits:
@pytest.mark.asyncio
@@ -558,10 +488,6 @@ class TestScratchpadLimits:
assert tool._runtime_control.snapshot().scratchpad["key_0"] == "updated"
# ---------------------------------------------------------------------------
# denied attrs (non-dunder)
# ---------------------------------------------------------------------------
class TestDeniedAttrs:
@pytest.mark.asyncio
@@ -572,15 +498,10 @@ class TestDeniedAttrs:
assert "protected" in result, f"{attr} should be blocked"
# ---------------------------------------------------------------------------
# _SubagentHook after_iteration updates status
# ---------------------------------------------------------------------------
class TestSubagentHookStatus:
@pytest.mark.asyncio
async def test_after_iteration_updates_status(self):
"""after_iteration should copy iteration, tool_events, usage to status."""
from nanobot.agent.hook import AgentHookContext
from nanobot.agent.subagent import SubagentStatus, _SubagentHook
@@ -607,7 +528,6 @@ class TestSubagentHookStatus:
@pytest.mark.asyncio
async def test_after_iteration_with_error(self):
"""after_iteration should set status.error when context has an error."""
from nanobot.agent.hook import AgentHookContext
from nanobot.agent.subagent import SubagentStatus, _SubagentHook
@@ -629,10 +549,6 @@ class TestSubagentHookStatus:
assert status.error == "something went wrong"
# ---------------------------------------------------------------------------
# read-only mode (tools.my.allow_set=False)
# ---------------------------------------------------------------------------
class TestReadOnlyMode:
def _make_readonly_tool(self):
@@ -659,15 +575,10 @@ class TestReadOnlyMode:
assert "READ-ONLY MODE" in tool.description
# ---------------------------------------------------------------------------
# scratchpad inspection
# ---------------------------------------------------------------------------
class TestScratchpadInspection:
@pytest.mark.asyncio
async def test_inspect_scratchpad_value_after_modify(self):
"""Design doc scenario: set then check should return the value."""
tool = _make_tool()
await tool.execute(action="set", key="user_prefers_concise", value=True)
result = await tool.execute(action="check", key="user_prefers_concise")
@@ -688,22 +599,17 @@ class TestScratchpadInspection:
assert "step" in result
assert "2" in result
# ---------------------------------------------------------------------------
# sensitive sub-field blocking (Fix #3: API key leak prevention)
# ---------------------------------------------------------------------------
class TestSensitiveSubFieldBlocking:
@pytest.mark.asyncio
async def test_inspect_api_key_blocked(self):
"""web_config.search.api_key must not be accessible."""
tool = _make_tool()
result = await tool.execute(action="check", key="web_config.search.api_key")
assert "not accessible" in result
@pytest.mark.asyncio
async def test_inspect_password_blocked(self):
"""Any field named 'password' must be blocked."""
loop = _make_mock_loop()
loop.some_config = MagicMock()
loop.some_config.password = "hunter2"
@@ -731,10 +637,8 @@ class TestSensitiveSubFieldBlocking:
@pytest.mark.asyncio
async def test_modify_api_key_blocked(self):
"""web_config is READ_ONLY, so any set under it is blocked."""
tool = _make_tool()
result = await tool.execute(action="set", key="web_config.search.api_key", value="evil")
# Blocked either by READ_ONLY (web_config) or sensitive name (api_key)
assert "read-only" in result or "not accessible" in result
@pytest.mark.asyncio
@@ -747,84 +651,69 @@ class TestSensitiveSubFieldBlocking:
@pytest.mark.asyncio
async def test_modify_sensitive_top_level_blocked(self):
"""Top-level key matching sensitive name must be blocked for set."""
tool = _make_tool()
result = await tool.execute(action="set", key="api_key", value="evil")
assert "protected" in result
# ---------------------------------------------------------------------------
# security-sensitive attribute protection (Fix #4)
# ---------------------------------------------------------------------------
class TestSecurityAttributeProtection:
@pytest.mark.asyncio
async def test_modify_restrict_to_workspace_blocked(self):
"""restrict_to_workspace is BLOCKED — cannot be toggled."""
tool = _make_tool()
result = await tool.execute(action="set", key="restrict_to_workspace", value=True)
assert "protected" in result
@pytest.mark.asyncio
async def test_modify_exec_config_blocked(self):
"""exec_config is READ_ONLY — cannot be modified."""
tool = _make_tool()
result = await tool.execute(action="set", key="exec_config", value=MagicMock())
assert "read-only" in result
@pytest.mark.asyncio
async def test_modify_web_config_blocked(self):
"""web_config is READ_ONLY — cannot be modified."""
tool = _make_tool()
result = await tool.execute(action="set", key="web_config", value=MagicMock())
assert "read-only" in result
@pytest.mark.asyncio
async def test_modify_channels_config_blocked(self):
"""channels_config is BLOCKED — cannot be modified."""
tool = _make_tool()
result = await tool.execute(action="set", key="channels_config", value={})
assert "protected" in result
@pytest.mark.asyncio
async def test_inspect_restrict_to_workspace_blocked(self):
"""restrict_to_workspace is BLOCKED — cannot be inspected."""
tool = _make_tool()
result = await tool.execute(action="check", key="restrict_to_workspace")
assert "not accessible" in result
@pytest.mark.asyncio
async def test_inspect_exec_config_allowed(self):
"""exec_config is READ_ONLY — check should work."""
tool = _make_tool()
result = await tool.execute(action="check", key="exec_config")
assert "Error" not in result
@pytest.mark.asyncio
async def test_inspect_web_config_allowed(self):
"""web_config is READ_ONLY — check should work."""
tool = _make_tool()
result = await tool.execute(action="check", key="web_config")
assert "Error" not in result
@pytest.mark.asyncio
async def test_modify_exec_config_dotpath_blocked(self):
"""exec_config.enable = False should be blocked because exec_config is READ_ONLY."""
tool = _make_tool()
result = await tool.execute(action="set", key="exec_config.enable", value=False)
assert "read-only" in result
@pytest.mark.asyncio
async def test_modify_web_config_dotpath_blocked(self):
"""web_config.enable = False should be blocked because web_config is READ_ONLY."""
tool = _make_tool()
result = await tool.execute(action="set", key="web_config.enable", value=False)
assert "read-only" in result
@pytest.mark.asyncio
async def test_modify_model_presets_dotpath_blocked(self):
"""The config-derived model preset catalog is inspectable but not mutable."""
presets = {"fast": ModelPresetConfig(model="fast-model")}
tool = _make_tool(loop=_make_mock_loop(model_presets=presets))
@@ -849,10 +738,6 @@ class TestSecurityAttributeProtection:
assert result == "model_presets.fast.model: 'fast-model'"
# ---------------------------------------------------------------------------
# request context (audit session tracking)
# ---------------------------------------------------------------------------
class TestRequestContext:
@pytest.mark.asyncio
@@ -1,5 +1,3 @@
"""Focused tests for MyTool runtime sync side effects."""
from unittest.mock import MagicMock
import pytest
@@ -1,5 +1,3 @@
"""Session tools read full canonical history independently of WebUI replay."""
from __future__ import annotations
import json
-3
View File
@@ -1,5 +1,3 @@
"""Tests for read-only persisted session tools."""
from __future__ import annotations
import json
@@ -90,7 +88,6 @@ def test_session_tools_do_not_own_runtime_context(tmp_path) -> None:
@pytest.mark.asyncio
async def test_search_sessions_has_no_hidden_content_scan_cutoff(manager):
# Seed offline on this thread; nested saves share the existing store transaction.
with manager._store.transaction():
for index in range(200):
_save_session(
-19
View File
@@ -1,5 +1,3 @@
"""Tests for subagent tool registration and wiring."""
import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -25,7 +23,6 @@ def _runtime(provider: MagicMock, model: str = "test-model") -> LLMRuntime:
@pytest.mark.asyncio
async def test_run_inline_returns_result_without_announcement(tmp_path):
"""Inline subagents return directly instead of injecting a follow-up."""
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
@@ -59,7 +56,6 @@ async def test_run_inline_returns_result_without_announcement(tmp_path):
@pytest.mark.asyncio
async def test_run_inline_returns_structured_error(tmp_path):
"""Inline subagent failures remain tool errors for the parent runner."""
from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.registry import is_tool_error_result
from nanobot.bus.queue import MessageBus
@@ -92,7 +88,6 @@ async def test_run_inline_returns_structured_error(tmp_path):
@pytest.mark.asyncio
async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
"""allowed_env_keys from ExecToolConfig must be forwarded to the subagent's ExecTool."""
from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.shell import ExecToolConfig
from nanobot.bus.queue import MessageBus
@@ -137,7 +132,6 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
@pytest.mark.asyncio
async def test_subagent_uses_configured_max_iterations(tmp_path):
"""Subagents should honor the configured tool-iteration limit."""
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
@@ -178,7 +172,6 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
@pytest.mark.asyncio
async def test_subagent_checkpoint_updates_status_and_preserves_omitted_fields(tmp_path):
"""Runner checkpoints update detached task snapshots without resetting omitted fields."""
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
@@ -224,7 +217,6 @@ async def test_subagent_checkpoint_updates_status_and_preserves_omitted_fields(t
@pytest.mark.asyncio
async def test_spawn_forwards_temperature_to_run_spec(tmp_path):
"""A temperature passed to spawn() should reach the AgentRunSpec."""
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
@@ -262,7 +254,6 @@ async def test_spawn_forwards_temperature_to_run_spec(tmp_path):
@pytest.mark.asyncio
async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
"""Background tasks should be accepted and start when capacity becomes available."""
from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.subagent import SubagentTool
from nanobot.bus.queue import MessageBus
@@ -429,7 +420,6 @@ async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
@pytest.mark.asyncio
async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
"""Adjacent blocking consultations should share one concurrent tool batch."""
from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.context import RequestContext, request_context
@@ -539,7 +529,6 @@ async def test_cancel_by_session_cancels_inline_subagent(tmp_path):
def test_subagent_default_max_concurrent_matches_agent_defaults(tmp_path):
"""Direct SubagentManager construction should use the agent default concurrency limit."""
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
@@ -556,7 +545,6 @@ def test_subagent_default_max_concurrent_matches_agent_defaults(tmp_path):
def test_subagent_default_max_iterations_matches_agent_defaults(tmp_path):
"""Direct SubagentManager construction should use the agent default limit."""
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
@@ -572,7 +560,6 @@ def test_subagent_default_max_iterations_matches_agent_defaults(tmp_path):
def test_agent_loop_passes_max_iterations_to_subagents(tmp_path):
"""AgentLoop's configured limit should be shared with spawned subagents."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
@@ -593,7 +580,6 @@ def test_agent_loop_passes_max_iterations_to_subagents(tmp_path):
@pytest.mark.asyncio
async def test_agent_loop_syncs_updated_max_iterations_before_run(tmp_path):
"""Runtime max_iterations changes should be reflected before tool execution."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
@@ -636,7 +622,6 @@ async def test_agent_loop_syncs_updated_max_iterations_before_run(tmp_path):
@pytest.mark.asyncio
async def test_drain_pending_no_block_when_no_subagents(tmp_path):
"""_drain_pending should not block when no sub-agents are running."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
@@ -679,14 +664,12 @@ async def test_drain_pending_no_block_when_no_subagents(tmp_path):
assert injection_callback is not None
assert terminal_injection_callback is not None
# With no sub-agents and an empty queue, both paths return immediately.
assert await asyncio.wait_for(injection_callback(), timeout=1.0) == []
assert await asyncio.wait_for(terminal_injection_callback(), timeout=1.0) == []
@pytest.mark.asyncio
async def test_terminal_drain_timeout(tmp_path):
"""The terminal drain should return empty after its shared timeout expires."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
from nanobot.session.manager import Session
@@ -739,7 +722,6 @@ async def test_terminal_drain_timeout(tmp_path):
assert terminal_injection_callback is not None
# Patch the timeout path without leaking the queue.get() coroutine.
async def _timeout(awaitable, timeout):
awaitable.close()
raise asyncio.TimeoutError
@@ -753,7 +735,6 @@ async def test_terminal_drain_timeout(tmp_path):
@pytest.mark.asyncio
async def test_terminal_drain_reuses_one_timeout_budget(tmp_path):
"""Repeated terminal rendezvous calls share one 300-second deadline."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus