Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(agent): sync data-source count and gate microcompact

MarkfuGoddf731256f4da
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.py
index 54f3f3f34..a016ba052 100644
--- a/agent/src/agent/context.py
+++ b/agent/src/agent/context.py
@@ -19,7 +19,7 @@ logger = logging.getLogger(__name__)
# Post-backtest attribution thresholds (Sharpe/MaxDD bands, ≥60-day OLS window,
# holding-period buckets, p≤0.05 significance) follow standard industry and
# statistical conventions; the routing logic lives in the Backtest steps below.
-_SYSTEM_PROMPT = """You are a finance research agent with {skill_count} specialist skills, {tool_count} tools, 7 data sources (with auto-fallback), and 29 multi-agent swarm teams.
+_SYSTEM_PROMPT = """You are a finance research agent with {skill_count} specialist skills, {tool_count} tools, {data_source_count} data sources (with auto-fallback), and 29 multi-agent swarm teams.
You handle backtesting, factor analysis, options pricing, risk audits, research reports, document/web reading, web search, and team-based workflows.
## Tools
@@ -187,6 +187,7 @@ class ContextBuilder:
return _SYSTEM_PROMPT.format(
tool_count=len(self.registry._tools),
skill_count=len(self.skills_loader.skills),
+ data_source_count=self._count_data_sources(),
tool_descriptions=self._format_tool_descriptions(),
skill_descriptions=self.skills_loader.get_descriptions(),
memory_summary=self.memory.to_summary(),
@@ -194,6 +195,22 @@ class ContextBuilder:
current_datetime=now.strftime("%A, %B %d, %Y %H:%M (local)"),
)
+ @staticmethod
+ def _count_data_sources() -> int:
+ """Count registered backtest data sources for the system prompt.
+
+ Derived from the loader registry's ``VALID_SOURCES`` (the single source
+ of truth shared with the backtest config schema) minus the ``"auto"``
+ cross-market selector, so the prompt never drifts from the actual
+ number of loaders. Falls back to a static count if the import fails.
+ """
+ try:
+ from backtest.loaders.registry import VALID_SOURCES
+
+ return len(VALID_SOURCES - {"auto"})
+ except Exception: # noqa: BLE001 - prompt count must never break startup
+ return 18
+
def build_messages(self, user_message: str, history: Optional[List[Dict[str, Any]]] = None) -> List[Dict[str, Any]]:
"""Build full message list.
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index a7a3ebb40..3730ec033 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -1,7 +1,7 @@
"""AgentLoop: ReAct core loop.
Five-layer context management:
- Layer 1 (microcompact) — silently prunes old tool results each iteration
+ Layer 1 (microcompact) — prunes old tool results once under memory pressure
Layer 2 (context_collapse) — folds long text blocks without LLM call (zero cost)
Layer 3 (auto_compact) — LLM structured summary with token-budget tail protection
Layer 4 (compact tool) — model explicitly calls the compact tool to trigger L3
@@ -52,6 +52,12 @@ TOOL_TIMEOUT_SECONDS = float(os.getenv("VIBE_TRADING_TOOL_TIMEOUT_SECONDS", "180
GOAL_MAX_CONTINUATIONS = int(os.getenv("VIBE_TRADING_GOAL_MAX_CONTINUATIONS", "3"))
LLM_USAGE_ARTIFACT = "llm_usage.json"
+# Layer 1: microcompact only prunes old tool results once the transcript is
+# under real memory pressure. Below this it would clear tool history on every
+# iteration even on short runs, discarding results the model may still need to
+# reference (metrics, file contents, search hits).
+MICROCOMPACT_THRESHOLD = int(TOKEN_THRESHOLD * 0.5)
+
# Layer 2: Context collapse thresholds
COLLAPSE_THRESHOLD = int(TOKEN_THRESHOLD * 0.7)
COLLAPSE_PRESERVE_RECENT = 6
@@ -555,11 +561,19 @@ class AgentLoop:
notif_text = "\n".join(f"[bg:{n['task_id']}] {n['status']}: {n['result']}" for n in notifs)
messages.append({"role": "user", "content": f"<background-results>\n{notif_text}\n</background-results>\n\n<system>Continue processing with the background results above.</system>"})
- # Layer 1: microcompact (every iteration)
- _microcompact(messages)
+ # Estimate transcript size once; each compaction layer below
+ # escalates only when its own token threshold is crossed.
+ tokens = estimate_tokens(messages)
+
+ # Layer 1: microcompact — prune old tool results only under
+ # memory pressure, so short, low-pressure runs keep their full
+ # tool history available for the model to reference instead of
+ # having every result past the most recent few cleared.
+ if tokens > MICROCOMPACT_THRESHOLD:
+ _microcompact(messages)
+ tokens = estimate_tokens(messages)
# Layer 2: context collapse (fold long text, zero API cost)
- tokens = estimate_tokens(messages)
if tokens > COLLAPSE_THRESHOLD:
_context_collapse(messages)
tokens = estimate_tokens(messages)
diff --git a/agent/tests/test_context_attribution_layers.py b/agent/tests/test_context_attribution_layers.py
index c056f0a43..7bb23ef23 100644
--- a/agent/tests/test_context_attribution_layers.py
+++ b/agent/tests/test_context_attribution_layers.py
@@ -2,8 +2,13 @@
from __future__ import annotations
+import builtins
+
import pytest
+from backtest.loaders.registry import VALID_SOURCES
+from src.agent.context import ContextBuilder
+
@pytest.mark.unit
class TestAttributionLayersPresence:
@@ -68,6 +73,7 @@ class TestAttributionPromptIntegrity:
result = _SYSTEM_PROMPT.format(
tool_count=10,
skill_count=5,
+ data_source_count=18,
tool_descriptions="[test tools]",
skill_descriptions="[test skills]",
memory_summary="[test memory]",
@@ -79,6 +85,7 @@ class TestAttributionPromptIntegrity:
# (JSON braces are OK, but single { } with names are not)
assert "{tool_count}" not in result
assert "{skill_count}" not in result
+ assert "{data_source_count}" not in result
def test_strategy_routing_thresholds_present(self):
"""Verify strategy routing classification is defined."""
@@ -104,3 +111,24 @@ class TestAttributionPromptIntegrity:
# The internal docs/ tree is gitignored and never published; the module
# must not point at a file that won't exist in the distributed repo.
assert "docs/" not in source
+
+
+class TestCountDataSources:
+ """Regression tests for dynamic data-source count in the system prompt."""
+
+ def test_count_data_sources_matches_registry(self) -> None:
+ """Live count derives from VALID_SOURCES minus the auto selector."""
+ assert ContextBuilder._count_data_sources() == len(VALID_SOURCES - {"auto"})
+
+ def test_count_data_sources_import_failure_returns_18(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Import failures fall back to 18 without propagating."""
+ real_import = builtins.__import__
+
+ def failing_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: ANN001
+ if name == "backtest.loaders.registry":
+ raise ImportError("simulated registry import failure")
+ return real_import(name, globals, locals, fromlist, level)
+
+ monkeypatch.setattr(builtins, "__import__", failing_import)
+ assert ContextBuilder._count_data_sources() == 18
diff --git a/agent/tests/test_loop_helpers.py b/agent/tests/test_loop_helpers.py
index 93e61d35c..4a6c8c622 100644
--- a/agent/tests/test_loop_helpers.py
+++ b/agent/tests/test_loop_helpers.py
@@ -12,6 +12,7 @@ from src.agent.loop import (
KEEP_RECENT,
COLLAPSE_PRESERVE_RECENT,
COLLAPSE_TEXT_MIN,
+ MICROCOMPACT_THRESHOLD,
estimate_tokens,
_microcompact,
_context_collapse,
@@ -21,6 +22,12 @@ from src.agent.loop import (
)
+def _apply_microcompact_gate(messages: list) -> None:
+ """Mirror AgentLoop layer-1 gate (``loop.py`` ~572-573)."""
+ if estimate_tokens(messages) > MICROCOMPACT_THRESHOLD:
+ _microcompact(messages)
+
+
# ---------------------------------------------------------------------------
# estimate_tokens
# ---------------------------------------------------------------------------
@@ -103,6 +110,41 @@ class TestMicrocompact:
assert messages[1]["content"] == "x" * 500
+class TestMicrocompactThresholdGate:
+ """Layer 1 only runs once transcript size crosses MICROCOMPACT_THRESHOLD."""
+
+ def test_no_op_at_or_below_threshold(self) -> None:
+ messages = [{"role": "system", "content": "sys"}]
+ for i in range(KEEP_RECENT + 5):
+ messages.append(
+ {"role": "tool", "content": f"{'x' * 200} result_{i}", "tool_call_id": f"tc_{i}"}
+ )
+
+ assert estimate_tokens(messages) <= MICROCOMPACT_THRESHOLD
+
+ originals = [m["content"] for m in messages]
+ _apply_microcompact_gate(messages)
+ assert [m["content"] for m in messages] == originals
+
+ def test_prunes_above_threshold(self) -> None:
+ messages = [{"role": "system", "content": "sys"}]
+ messages.append({"role": "user", "content": "x" * (MICROCOMPACT_THRESHOLD * 4 + 1000)})
+ for i in range(KEEP_RECENT + 5):
+ messages.append(
+ {"role": "tool", "content": f"{'y' * 200} result_{i}", "tool_call_id": f"tc_{i}"}
+ )
+
+ assert estimate_tokens(messages) > MICROCOMPACT_THRESHOLD
+
+ _apply_microcompact_gate(messages)
+
+ tool_msgs = [m for m in messages if m.get("role") == "tool"]
+ cleared = [m for m in tool_msgs if m["content"] == "[cleared]"]
+ preserved = [m for m in tool_msgs if m["content"] != "[cleared]"]
+ assert len(cleared) == 5
+ assert len(preserved) == KEEP_RECENT
+
+
# ---------------------------------------------------------------------------
# _context_collapse
# ---------------------------------------------------------------------------