Skip to content

"Vibe-Trading: Your Personal Trading Agent"

refactor(agent): extract loop tuning/config helpers into tuning module

Jackzigen3788d8877ead
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 0a2dc1ea5..331c460bc 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -19,13 +19,27 @@ import copy
import json
import logging
import queue
-import sys
import threading
import time as _time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Dict, List, Mapping, Optional
+from src.agent.tuning import (
+ TOKEN_THRESHOLD as TOKEN_THRESHOLD,
+ _override as _override,
+ _token_threshold as _token_threshold,
+ _heartbeat_interval_s as _heartbeat_interval_s,
+ _reasoning_delta_min_interval_s as _reasoning_delta_min_interval_s,
+ _stream_retry_delay_s as _stream_retry_delay_s,
+ _stream_retry_max_delay_s as _stream_retry_max_delay_s,
+ _stream_retry_backoff_s as _stream_retry_backoff_s,
+ _tool_timeout_seconds as _tool_timeout_seconds,
+ _llm_timeout_seconds as _llm_timeout_seconds,
+ _goal_max_continuations as _goal_max_continuations,
+ _stall_timeout_seconds as _stall_timeout_seconds,
+)
+
from src.agent.context import ContextBuilder
from src.agent.grounding import GroundingLedger
from src.agent.grounding.release import MAX_GROUNDING_REVISIONS
@@ -93,132 +107,6 @@ MAX_CONSECUTIVE_EMPTY_RESPONSE_SKIPS = 1
MAX_READONLY_REPLAY_RECOVERIES = 6
-#: Test hook only: set it (monkeypatch) to run the three compaction layers on
-#: the pre-2026-09-29 estimated-token thresholds. A real attribute on purpose:
-#: while it was resolved lazily by the module ``__getattr__``, monkeypatch read
-#: the lazy 40000 before patching and wrote it back as a real attribute on
-#: undo, silently switching every later test in the process to the old path.
-TOKEN_THRESHOLD: Optional[int] = None
-
-
-def _override(name: str):
- """Return a monkeypatched module-level override if present."""
- mod = sys.modules.get(__name__)
- if mod is not None and name in mod.__dict__:
- return mod.__dict__[name]
- return None
-
-
-def _token_threshold() -> int:
- ov = _override("TOKEN_THRESHOLD")
- if ov is not None:
- return ov
- from src.config.accessor import get_env_config
- return get_env_config().agent_tuning.token_threshold
-
-
-def _heartbeat_interval_s() -> float:
- ov = _override("HEARTBEAT_INTERVAL_S")
- if ov is not None:
- return ov
- from src.config.accessor import get_env_config
- return get_env_config().agent_tuning.vt_heartbeat_interval_s
-
-
-def _reasoning_delta_min_interval_s() -> float:
- ov = _override("REASONING_DELTA_MIN_INTERVAL_S")
- if ov is not None:
- return ov
- from src.config.accessor import get_env_config
- return get_env_config().agent_tuning.vt_reasoning_delta_min_interval_s
-
-
-def _stream_retry_delay_s() -> float:
- ov = _override("STREAM_RETRY_DELAY_S")
- if ov is not None:
- return ov
- from src.config.accessor import get_env_config
- return get_env_config().agent_tuning.vt_stream_retry_delay_s
-
-
-def _stream_retry_max_delay_s() -> float:
- ov = _override("STREAM_RETRY_MAX_DELAY_S")
- if ov is not None:
- return ov
- from src.config.accessor import get_env_config
- return get_env_config().agent_tuning.vt_stream_retry_max_delay_s
-
-
-def _stream_retry_backoff_s(streak: int) -> float:
- """Return the capped exponential delay for the one-based failure streak.
-
- Doubles per consecutive retryable stream failure (1.0s, 2.0s, 4.0s, ...)
- so a sustained provider outage backs off instead of burning the retry
- budget at a constant cadence. The exponent is clamped at 62 (mirroring
- ``src/swarm/runtime.py``'s worker-level backoff) and the result is capped
- at ``_stream_retry_max_delay_s()``.
-
- Args:
- streak: Number of consecutive retryable stream failures including the
- current one; values below 1 are treated as 1.
-
- Returns:
- Seconds to sleep before the stream retry, never negative.
- """
- ceiling = min(
- _stream_retry_delay_s() * (2 ** min(max(streak, 1) - 1, 62)),
- _stream_retry_max_delay_s(),
- )
- return max(ceiling, 0.0)
-
-
-def _tool_timeout_seconds() -> float:
- ov = _override("TOOL_TIMEOUT_SECONDS")
- if ov is not None:
- return ov
- from src.config.accessor import get_env_config
- return get_env_config().agent_tuning.vibe_trading_tool_timeout_seconds
-
-
-def _llm_timeout_seconds() -> float:
- """Return the per-call LLM timeout in seconds (0/negative disables).
-
- A silent provider stall otherwise hangs the ReAct loop or the
- auto-compact summary call indefinitely - no chunk arrives, so the
- per-chunk cancel check never runs. Bounding the call lets the run fail
- (or degrade compaction) instead of freezing mid-task.
- """
- ov = _override("LLM_TIMEOUT_SECONDS")
- if ov is not None:
- return ov
- from src.config.accessor import get_env_config
- return get_env_config().agent_tuning.vibe_trading_llm_timeout_seconds
-
-
-def _goal_max_continuations() -> int:
- ov = _override("GOAL_MAX_CONTINUATIONS")
- if ov is not None:
- return ov
- from src.config.accessor import get_env_config
- return get_env_config().agent_tuning.vibe_trading_goal_max_continuations
-
-
-def _stall_timeout_seconds() -> float:
- """Return the run-stall watchdog timeout in seconds (0/negative disables).
-
- A run that makes no forward progress (no LLM completion, no tool result)
- for this long is treated as a zombie and failed explicitly with a clear
- reason instead of staying "running" forever with no state.json
- (recurring 2026-08 zombie runs). Heartbeats do NOT count as progress: a
- hung tool keeps emitting heartbeats, which is exactly the case the
- watchdog must catch.
- """
- ov = _override("STALL_TIMEOUT_SECONDS")
- if ov is not None:
- return ov
- from src.config.accessor import get_env_config
- return get_env_config().agent_tuning.vibe_trading_run_stall_timeout_seconds
-
logger = logging.getLogger(__name__)
diff --git a/agent/src/agent/tuning.py b/agent/src/agent/tuning.py
new file mode 100644
index 000000000..8f0c8d306
--- /dev/null
+++ b/agent/src/agent/tuning.py
@@ -0,0 +1,131 @@
+"""Tuning and configuration helpers for the agent loop."""
+
+import sys
+from typing import Optional
+
+
+#: Test hook only: set it (monkeypatch) to run the three compaction layers on
+#: the pre-2026-09-29 estimated-token thresholds. A real attribute on purpose:
+#: while it was resolved lazily by the module ``__getattr__``, monkeypatch read
+#: the lazy 40000 before patching and wrote it back as a real attribute on
+#: undo, silently switching every later test in the process to the old path.
+TOKEN_THRESHOLD: Optional[int] = None
+
+
+def _override(name: str):
+ """Return a monkeypatched module-level override if present."""
+ mod = sys.modules.get(__name__)
+ if mod is not None and name in mod.__dict__:
+ return mod.__dict__[name]
+ return None
+
+
+def _token_threshold() -> int:
+ ov = _override("TOKEN_THRESHOLD")
+ if ov is not None:
+ return ov
+ from src.config.accessor import get_env_config
+ return get_env_config().agent_tuning.token_threshold
+
+
+def _heartbeat_interval_s() -> float:
+ ov = _override("HEARTBEAT_INTERVAL_S")
+ if ov is not None:
+ return ov
+ from src.config.accessor import get_env_config
+ return get_env_config().agent_tuning.vt_heartbeat_interval_s
+
+
+def _reasoning_delta_min_interval_s() -> float:
+ ov = _override("REASONING_DELTA_MIN_INTERVAL_S")
+ if ov is not None:
+ return ov
+ from src.config.accessor import get_env_config
+ return get_env_config().agent_tuning.vt_reasoning_delta_min_interval_s
+
+
+def _stream_retry_delay_s() -> float:
+ ov = _override("STREAM_RETRY_DELAY_S")
+ if ov is not None:
+ return ov
+ from src.config.accessor import get_env_config
+ return get_env_config().agent_tuning.vt_stream_retry_delay_s
+
+
+def _stream_retry_max_delay_s() -> float:
+ ov = _override("STREAM_RETRY_MAX_DELAY_S")
+ if ov is not None:
+ return ov
+ from src.config.accessor import get_env_config
+ return get_env_config().agent_tuning.vt_stream_retry_max_delay_s
+
+
+def _stream_retry_backoff_s(streak: int) -> float:
+ """Return the capped exponential delay for the one-based failure streak.
+
+ Doubles per consecutive retryable stream failure (1.0s, 2.0s, 4.0s, ...)
+ so a sustained provider outage backs off instead of burning the retry
+ budget at a constant cadence. The exponent is clamped at 62 (mirroring
+ ``src/swarm/runtime.py``'s worker-level backoff) and the result is capped
+ at ``_stream_retry_max_delay_s()``.
+
+ Args:
+ streak: Number of consecutive retryable stream failures including the
+ current one; values below 1 are treated as 1.
+
+ Returns:
+ Seconds to sleep before the stream retry, never negative.
+ """
+ ceiling = min(
+ _stream_retry_delay_s() * (2 ** min(max(streak, 1) - 1, 62)),
+ _stream_retry_max_delay_s(),
+ )
+ return max(ceiling, 0.0)
+
+
+def _tool_timeout_seconds() -> float:
+ ov = _override("TOOL_TIMEOUT_SECONDS")
+ if ov is not None:
+ return ov
+ from src.config.accessor import get_env_config
+ return get_env_config().agent_tuning.vibe_trading_tool_timeout_seconds
+
+
+def _llm_timeout_seconds() -> float:
+ """Return the per-call LLM timeout in seconds (0/negative disables).
+
+ A silent provider stall otherwise hangs the ReAct loop or the
+ auto-compact summary call indefinitely - no chunk arrives, so the
+ per-chunk cancel check never runs. Bounding the call lets the run fail
+ (or degrade compaction) instead of freezing mid-task.
+ """
+ ov = _override("LLM_TIMEOUT_SECONDS")
+ if ov is not None:
+ return ov
+ from src.config.accessor import get_env_config
+ return get_env_config().agent_tuning.vibe_trading_llm_timeout_seconds
+
+
+def _goal_max_continuations() -> int:
+ ov = _override("GOAL_MAX_CONTINUATIONS")
+ if ov is not None:
+ return ov
+ from src.config.accessor import get_env_config
+ return get_env_config().agent_tuning.vibe_trading_goal_max_continuations
+
+
+def _stall_timeout_seconds() -> float:
+ """Return the run-stall watchdog timeout in seconds (0/negative disables).
+
+ A run that makes no forward progress (no LLM completion, no tool result)
+ for this long is treated as a zombie and failed explicitly with a clear
+ reason instead of staying "running" forever with no state.json
+ (recurring 2026-08 zombie runs). Heartbeats do NOT count as progress: a
+ hung tool keeps emitting heartbeats, which is exactly the case the
+ watchdog must catch.
+ """
+ ov = _override("STALL_TIMEOUT_SECONDS")
+ if ov is not None:
+ return ov
+ from src.config.accessor import get_env_config
+ return get_env_config().agent_tuning.vibe_trading_run_stall_timeout_seconds
diff --git a/agent/tests/test_agent_goal_context.py b/agent/tests/test_agent_goal_context.py
index 84b663156..e8111bcc0 100644
--- a/agent/tests/test_agent_goal_context.py
+++ b/agent/tests/test_agent_goal_context.py
@@ -61,7 +61,7 @@ def _agent(llm: _CapturingLLM, run_dir: Path) -> AgentLoop:
def test_agent_loop_injects_active_goal_context(tmp_path: Path, monkeypatch) -> None:
- monkeypatch.setattr("src.agent.loop.GOAL_MAX_CONTINUATIONS", 0)
+ monkeypatch.setattr("src.agent.tuning.GOAL_MAX_CONTINUATIONS", 0, raising=False)
monkeypatch.setenv("VIBE_TRADING_GOAL_DB_PATH", str(tmp_path / "goals.db"))
store = GoalStore()
goal = store.replace_goal(
@@ -86,7 +86,7 @@ def test_agent_loop_injects_active_goal_context(tmp_path: Path, monkeypatch) ->
def test_agent_loop_accounts_goal_token_and_turn_usage(tmp_path: Path, monkeypatch) -> None:
- monkeypatch.setattr("src.agent.loop.GOAL_MAX_CONTINUATIONS", 0)
+ monkeypatch.setattr("src.agent.tuning.GOAL_MAX_CONTINUATIONS", 0, raising=False)
monkeypatch.setenv("VIBE_TRADING_GOAL_DB_PATH", str(tmp_path / "goals.db"))
store = GoalStore()
goal = store.replace_goal(
@@ -110,7 +110,7 @@ def test_agent_loop_accounts_goal_token_and_turn_usage(tmp_path: Path, monkeypat
def test_agent_loop_continues_active_incomplete_goal(tmp_path: Path, monkeypatch) -> None:
- monkeypatch.setattr("src.agent.loop.GOAL_MAX_CONTINUATIONS", 1)
+ monkeypatch.setattr("src.agent.tuning.GOAL_MAX_CONTINUATIONS", 1, raising=False)
monkeypatch.setenv("VIBE_TRADING_GOAL_DB_PATH", str(tmp_path / "goals.db"))
store = GoalStore()
store.replace_goal(
@@ -137,7 +137,7 @@ def test_agent_loop_continues_active_covered_goal_to_force_audit(tmp_path: Path,
"""Covered criteria still need a terminal status audit before the loop stops."""
from src.goal import EvidenceInput
- monkeypatch.setattr("src.agent.loop.GOAL_MAX_CONTINUATIONS", 1)
+ monkeypatch.setattr("src.agent.tuning.GOAL_MAX_CONTINUATIONS", 1, raising=False)
monkeypatch.setenv("VIBE_TRADING_GOAL_DB_PATH", str(tmp_path / "goals.db"))
store = GoalStore()
goal = store.replace_goal(
diff --git a/agent/tests/test_agent_loop_content_filter.py b/agent/tests/test_agent_loop_content_filter.py
index 3c9db5144..26eee1341 100644
--- a/agent/tests/test_agent_loop_content_filter.py
+++ b/agent/tests/test_agent_loop_content_filter.py
@@ -251,7 +251,7 @@ def test_auto_compact_summary_hard_deadline(
"""
import time
- import src.agent.loop as loop_module
+ import src.agent.tuning as tuning_module
from src.agent.loop import AgentLoop
from src.agent.tools import ToolRegistry
from src.agent.trace import TraceWriter
@@ -270,7 +270,7 @@ def test_auto_compact_summary_hard_deadline(
llm = _HangingSummaryLLM()
agent = AgentLoop(registry=ToolRegistry(), llm=llm)
- monkeypatch.setattr(loop_module, "LLM_TIMEOUT_SECONDS", 0.3, raising=False)
+ monkeypatch.setattr(tuning_module, "LLM_TIMEOUT_SECONDS", 0.3, raising=False)
messages: list[dict[str, Any]] = [
{"role": "system", "content": "sys"},
diff --git a/agent/tests/test_agent_loop_stream_retry.py b/agent/tests/test_agent_loop_stream_retry.py
index df742cbb9..79318a95c 100644
--- a/agent/tests/test_agent_loop_stream_retry.py
+++ b/agent/tests/test_agent_loop_stream_retry.py
@@ -14,7 +14,7 @@ from typing import Any, Callable
import pytest
-import src.agent.loop as loop_mod
+import src.agent.tuning as tuning_mod
from src.providers.chat import LLMResponse, ProviderStreamError
@@ -127,7 +127,7 @@ def _run(
from src.memory.persistent import PersistentMemory
from src.tools import build_registry
- monkeypatch.setattr(loop_mod, "STREAM_RETRY_DELAY_S", 0.0)
+ monkeypatch.setattr(tuning_mod, "STREAM_RETRY_DELAY_S", 0.0, raising=False)
pm = PersistentMemory()
agent = AgentLoop(
registry=build_registry(persistent_memory=pm, include_shell_tools=False),
diff --git a/agent/tests/test_context_budget.py b/agent/tests/test_context_budget.py
index 297fc4e4a..85dc2e5e0 100644
--- a/agent/tests/test_context_budget.py
+++ b/agent/tests/test_context_budget.py
@@ -29,6 +29,7 @@ from src.agent.context_budget import (
resolve_window,
)
from src.agent.loop import AgentLoop
+import src.agent.tuning as tuning_mod
from src.agent.tools import BaseTool, ToolRegistry
from src.agent.trace import TraceWriter
from src.config.accessor import reset_env_config
@@ -269,9 +270,8 @@ def test_twelve_company_comparison_keeps_every_filing(tmp_path, monkeypatch, pro
def test_the_old_fixed_threshold_evicts_the_same_run(tmp_path, monkeypatch) -> None:
"""Mutation side: the pre-fix 40K estimate clears filings mid-comparison."""
- import src.agent.loop as loop_mod
- monkeypatch.setattr(loop_mod, "TOKEN_THRESHOLD", 40_000, raising=False)
+ monkeypatch.setattr(tuning_mod, "TOKEN_THRESHOLD", 40_000, raising=False)
_, _, _, _, trace = _run(tmp_path, monkeypatch, provider="openai-codex", model="openai-codex/gpt-6-sol")
assert [e for e in trace if e.get("type") == "microcompact_cleared"]
diff --git a/agent/tests/test_loop_helpers.py b/agent/tests/test_loop_helpers.py
index 69c64da6a..fa6988dde 100644
--- a/agent/tests/test_loop_helpers.py
+++ b/agent/tests/test_loop_helpers.py
@@ -560,12 +560,12 @@ class TestArchiveBacktestResult:
def test_llm_timeout_seconds_default_and_override(monkeypatch) -> None:
"""The LLM call timeout reads config and honors a module-level override."""
- import src.agent.loop as loop_module
+ import src.agent.tuning as tuning_module
assert _llm_timeout_seconds() > 0
- monkeypatch.setattr(loop_module, "LLM_TIMEOUT_SECONDS", 42.0, raising=False)
+ monkeypatch.setattr(tuning_module, "LLM_TIMEOUT_SECONDS", 42.0, raising=False)
assert _llm_timeout_seconds() == 42.0
- monkeypatch.delattr(loop_module, "LLM_TIMEOUT_SECONDS", raising=False)
+ monkeypatch.delattr(tuning_module, "LLM_TIMEOUT_SECONDS", raising=False)
assert _llm_timeout_seconds() > 0
def test_pending_write_directive_tracks_written_targets(tmp_path: Path) -> None:
@@ -672,12 +672,12 @@ def test_verification_ledger_deduplicates_and_caps() -> None:
def test_stall_timeout_seconds_default_and_override(monkeypatch) -> None:
"""The stall watchdog timeout reads config and honors a module override."""
- import src.agent.loop as loop_module
+ import src.agent.tuning as tuning_module
assert _stall_timeout_seconds() > 0
- monkeypatch.setattr(loop_module, "STALL_TIMEOUT_SECONDS", 42.0, raising=False)
+ monkeypatch.setattr(tuning_module, "STALL_TIMEOUT_SECONDS", 42.0, raising=False)
assert _stall_timeout_seconds() == 42.0
- monkeypatch.delattr(loop_module, "STALL_TIMEOUT_SECONDS", raising=False)
+ monkeypatch.delattr(tuning_module, "STALL_TIMEOUT_SECONDS", raising=False)
assert _stall_timeout_seconds() > 0
diff --git a/agent/tests/test_stream_retry_escalation.py b/agent/tests/test_stream_retry_escalation.py
index efd922b27..52ba33293 100644
--- a/agent/tests/test_stream_retry_escalation.py
+++ b/agent/tests/test_stream_retry_escalation.py
@@ -19,6 +19,7 @@ import pytest
from pydantic import ValidationError
import src.agent.loop as loop_mod
+import src.agent.tuning as tuning_mod
import src.swarm.worker as worker_mod
from src.config.env_schema import AgentTuningConfig, SwarmConfig
from src.providers.chat import LLMResponse, ProviderStreamError, ToolCallRequest
@@ -359,8 +360,8 @@ def _run_loop(
sleeps: list[float] = []
monkeypatch.setattr(loop_mod._time, "sleep", lambda s: sleeps.append(s))
- monkeypatch.setattr(loop_mod, "STREAM_RETRY_DELAY_S", 1.0)
- monkeypatch.setattr(loop_mod, "STREAM_RETRY_MAX_DELAY_S", 8.0)
+ monkeypatch.setattr(tuning_mod, "STREAM_RETRY_DELAY_S", 1.0, raising=False)
+ monkeypatch.setattr(tuning_mod, "STREAM_RETRY_MAX_DELAY_S", 8.0, raising=False)
pm = PersistentMemory()
agent = AgentLoop(
registry=build_registry(persistent_memory=pm, include_shell_tools=False),
@@ -428,8 +429,8 @@ def test_loop_non_retryable_error_no_sleep(monkeypatch, tmp_path: Path) -> None:
def test_loop_backoff_helper_escalates_and_caps(monkeypatch) -> None:
"""The loop's capped-exponential helper escalates 1→2→4 and caps at max."""
- monkeypatch.setattr(loop_mod, "STREAM_RETRY_DELAY_S", 1.0)
- monkeypatch.setattr(loop_mod, "STREAM_RETRY_MAX_DELAY_S", 8.0)
+ monkeypatch.setattr(tuning_mod, "STREAM_RETRY_DELAY_S", 1.0, raising=False)
+ monkeypatch.setattr(tuning_mod, "STREAM_RETRY_MAX_DELAY_S", 8.0, raising=False)
assert loop_mod._stream_retry_backoff_s(1) == 1.0
assert loop_mod._stream_retry_backoff_s(2) == 2.0
@@ -495,8 +496,8 @@ def test_loop_cancel_during_retry_delay_returns_without_waiting_it_out(
from src.memory.persistent import PersistentMemory
from src.tools import build_registry
- monkeypatch.setattr(loop_mod, "STREAM_RETRY_DELAY_S", 30.0)
- monkeypatch.setattr(loop_mod, "STREAM_RETRY_MAX_DELAY_S", 30.0)
+ monkeypatch.setattr(tuning_mod, "STREAM_RETRY_DELAY_S", 30.0, raising=False)
+ monkeypatch.setattr(tuning_mod, "STREAM_RETRY_MAX_DELAY_S", 30.0, raising=False)
pm = PersistentMemory()
agent = AgentLoop(
registry=build_registry(persistent_memory=pm, include_shell_tools=False),
diff --git a/agent/tests/test_tool_timeout.py b/agent/tests/test_tool_timeout.py
index 9bf60f74e..59535d239 100644
--- a/agent/tests/test_tool_timeout.py
+++ b/agent/tests/test_tool_timeout.py
@@ -7,7 +7,7 @@ import time
from types import SimpleNamespace
from typing import Any
-from src.agent import loop as loop_mod
+from src.agent import tuning as tuning_mod
from src.agent.loop import AgentLoop
@@ -41,8 +41,8 @@ class _SlowWriteRegistry:
def test_tool_timeout_returns_error_and_stops_heartbeats(monkeypatch) -> None:
"""A hung tool should become a bounded diagnostic instead of heartbeating forever."""
- monkeypatch.setattr(loop_mod, "TOOL_TIMEOUT_SECONDS", 0.05)
- monkeypatch.setattr(loop_mod, "HEARTBEAT_INTERVAL_S", 0.01)
+ monkeypatch.setattr(tuning_mod, "TOOL_TIMEOUT_SECONDS", 0.05, raising=False)
+ monkeypatch.setattr(tuning_mod, "HEARTBEAT_INTERVAL_S", 0.01, raising=False)
events: list[tuple[str, dict[str, Any]]] = []
agent = AgentLoop(
registry=_SlowRegistry(), # type: ignore[arg-type]
@@ -73,8 +73,8 @@ def test_tool_timeout_returns_error_and_stops_heartbeats(monkeypatch) -> None:
def test_write_tool_timeout_warns_but_does_not_return_before_completion(monkeypatch) -> None:
"""Write tools must not report failure while their side effect continues."""
- monkeypatch.setattr(loop_mod, "TOOL_TIMEOUT_SECONDS", 0.02)
- monkeypatch.setattr(loop_mod, "HEARTBEAT_INTERVAL_S", 0.01)
+ monkeypatch.setattr(tuning_mod, "TOOL_TIMEOUT_SECONDS", 0.02, raising=False)
+ monkeypatch.setattr(tuning_mod, "HEARTBEAT_INTERVAL_S", 0.01, raising=False)
events: list[tuple[str, dict[str, Any]]] = []
registry = _SlowWriteRegistry()
agent = AgentLoop(
diff --git a/agent/tests/test_tuning_reexport.py b/agent/tests/test_tuning_reexport.py
new file mode 100644
index 000000000..620e8a09f
--- /dev/null
+++ b/agent/tests/test_tuning_reexport.py
@@ -0,0 +1,34 @@
+"""Contract tests for the tuning helpers extracted from the agent loop."""
+
+import pytest
+
+import src.agent.loop as loop_module
+import src.agent.tuning as tuning_module
+
+MOVED_NAMES = (
+ "TOKEN_THRESHOLD",
+ "_override",
+ "_token_threshold",
+ "_heartbeat_interval_s",
+ "_reasoning_delta_min_interval_s",
+ "_stream_retry_delay_s",
+ "_stream_retry_max_delay_s",
+ "_stream_retry_backoff_s",
+ "_tool_timeout_seconds",
+ "_llm_timeout_seconds",
+ "_goal_max_continuations",
+ "_stall_timeout_seconds",
+)
+
+
[email protected]("name", MOVED_NAMES)
+def test_tuning_helpers_are_reexported_by_loop(name: str) -> None:
+ assert getattr(loop_module, name) is getattr(tuning_module, name)
+
+
+def test_token_threshold_override_must_target_tuning_module(monkeypatch) -> None:
+ default = tuning_module._token_threshold()
+ monkeypatch.setattr(loop_module, "TOKEN_THRESHOLD", 123)
+ assert tuning_module._token_threshold() == default
+ monkeypatch.setattr(tuning_module, "TOKEN_THRESHOLD", 321)
+ assert tuning_module._token_threshold() == 321