"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(providers): apply tool policy across providers
Yufeng He0c3bdccfc8fa
diff --git a/README.md b/README.mdindex 96e51d72c..b45e0fb01 100644--- a/README.md+++ b/README.md@@ -1124,12 +1124,14 @@ LANGCHAIN_PROVIDER=claude-cliLANGCHAIN_MODEL_NAME=claude-opus-5-5# LANGCHAIN_REASONING_EFFORT=high # low|medium|high|xhigh|max; passed as --effort# CLAUDE_CLI_PATH=/opt/homebrew/bin/claude # when `claude` is not on PATH or in ~/.local/bin-# CLAUDE_CLI_DENY_TOOL_PREFIXES=trading_,etoro_ # default; set empty to offer every tool-# CLAUDE_CLI_BASH_POLICY=python-only # or `off`+# VIBE_TRADING_DENY_TOOL_PREFIXES=trading_,etoro_ # any provider; empty offers every tool+# VIBE_TRADING_BASH_POLICY=python-only # any provider, or `off`+# CLAUDE_CLI_DENY_TOOL_PREFIXES=trading_,etoro_ # legacy alias when the generic name is unset+# CLAUDE_CLI_BASH_POLICY=python-only # legacy alias when the generic name is unset```-- `CLAUDE_CLI_DENY_TOOL_PREFIXES` hides tools whose names start with these prefixes from the model. The default hides every `trading_*` and `etoro_*` tool, read-only ones included, so the agent cannot quote or list positions through a broker connector under this provider until you change it.-- `CLAUDE_CLI_BASH_POLICY=python-only` lets the `bash` tool run only `python <relative script>.py`, `python -c ...`, and read-only `ls`/`cat`/`head`/`tail`/`wc`/`pwd` on non-hidden relative paths (so not `.env`); refused calls are returned to the model so it can choose again. Any other value stops the provider from starting.+- `VIBE_TRADING_DENY_TOOL_PREFIXES` hides tools whose names start with these prefixes from every provider. The default hides every `trading_*` and `etoro_*` tool, read-only ones included, so the agent cannot quote or list positions through a broker connector until you change it. `CLAUDE_CLI_DENY_TOOL_PREFIXES` remains the fallback alias for existing configurations.+- `VIBE_TRADING_BASH_POLICY=python-only` applies the same rule to every provider: `bash` may run only `python <relative script>.py`, `python -c ...`, and read-only `ls`/`cat`/`head`/`tail`/`wc`/`pwd` on non-hidden relative paths (so not `.env`); refused calls are returned to the model so it can choose again. `CLAUDE_CLI_BASH_POLICY` remains the fallback alias. `vibe-trading provider doctor` reports the active policy and which variable supplied it.> **Warning:** Both settings are convenience filters, not a security boundary. `python -c` can still run arbitrary code, and external MCP tools (`mcp_<server>_<tool>`) are not covered by the default prefixes. Live orders stay bound by the mandate gate and kill switch whatever these settings allow.@@ -1239,8 +1241,10 @@ Copy `agent/.env.example` to `agent/.env` and uncomment the provider block you w| `TUSHARE_TOKEN` | No | Tushare Pro token for A-share data (falls back to AKShare) || `TIMEOUT_SECONDS` | No | LLM call timeout, default 120s || `CLAUDE_CLI_PATH` | No | `claude` executable for the `claude-cli` provider when it is not on PATH or in `~/.local/bin` |-| `CLAUDE_CLI_DENY_TOOL_PREFIXES` | No | Tool-name prefixes hidden from the `claude-cli` model (default `trading_,etoro_`; empty offers every tool) |-| `CLAUDE_CLI_BASH_POLICY` | No | `python-only` (default) or `off` for the `claude-cli` provider's `bash` tool |+| `VIBE_TRADING_DENY_TOOL_PREFIXES` | No | Tool-name prefixes hidden from every provider (default `trading_,etoro_`; empty offers every tool) |+| `VIBE_TRADING_BASH_POLICY` | No | `python-only` (default) or `off` for every provider's `bash` tool |+| `CLAUDE_CLI_DENY_TOOL_PREFIXES` | No | Legacy alias for `VIBE_TRADING_DENY_TOOL_PREFIXES`, used when the generic name is unset |+| `CLAUDE_CLI_BASH_POLICY` | No | Legacy alias for `VIBE_TRADING_BASH_POLICY`, used when the generic name is unset || `API_AUTH_KEY` | Recommended for network deployments | Bearer token required when the API is reachable from non-local clients || `VIBE_TRADING_ENABLE_SHELL_TOOLS` | No | Explicit opt-in for shell-capable tools in remote API/MCP-SSE style deployments || `VIBE_TRADING_ALLOWED_FILE_ROOTS` | No | Extra comma-separated roots for document and broker-journal imports |diff --git a/agent/src/agent/tool_lifecycle.py b/agent/src/agent/tool_lifecycle.pyindex 486e21559..1b9d2442b 100644--- a/agent/src/agent/tool_lifecycle.py+++ b/agent/src/agent/tool_lifecycle.py@@ -23,6 +23,7 @@ from src.agent.tool_results import (_archive_backtest_result, _failure_code, _is_tool_success, _normalize_tool_run_dir,)from src.agent.result_artifacts import deliver_tool_result+from src.providers.tool_policy import _deny_prefixes, screen_callsfrom src.tools.redaction import redact_payload, redact_tool_resultlogger = logging.getLogger("src.agent.loop")@@ -71,6 +72,7 @@ class ToolCallLifecycle:compact_requested = Falsefocus_topic = ""execution_plan: list[tuple[Any, str | None]] = []+ deny_prefixes = _deny_prefixes()batch_authorized_symbols = (set(self._grounding.authorized_symbols)if self._grounding is not None@@ -87,6 +89,33 @@ class ToolCallLifecycle:return compact_requested, focus_topicfor tc in tool_calls:+ if tc.name.startswith(deny_prefixes):+ execution_plan.append((+ tc,+ json.dumps({+ "status": "error",+ "skipped": True,+ "reason": f"{tc.name} is disabled by the active tool policy",+ }),+ ))+ continue+ if tc.name in {"bash", "background_run", "cancel_background"}:+ accepted, notes = screen_calls(+ [{"name": tc.name, "arguments": tc.arguments}],+ {tc.name},+ )+ if notes:+ execution_plan.append((+ tc,+ json.dumps({+ "status": "error",+ "skipped": True,+ "reason": notes[0].removeprefix("- "),+ }),+ ))+ continue+ tc.arguments = accepted[0]["arguments"]+# Layer 4: compact tool — mark then defer executionif tc.name == "compact":self._tool_progress.note("compact", "compact")diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.pyindex c63e85d59..5ff1083c5 100644--- a/agent/src/config/env_schema.py+++ b/agent/src/config/env_schema.py@@ -185,6 +185,12 @@ class LLMConfig(_EnvBase):default="https://chatgpt.com/backend-api/codex/responses",)claude_cli_path: str = Field(alias="CLAUDE_CLI_PATH", default="")+ vibe_trading_deny_tool_prefixes: str | None = Field(+ alias="VIBE_TRADING_DENY_TOOL_PREFIXES", default=None+ )+ vibe_trading_bash_policy: str | None = Field(+ alias="VIBE_TRADING_BASH_POLICY", default=None+ )# A convenience filter, not a security boundary: live orders are still bound# by the mandate gate whatever this list hides.claude_cli_deny_tool_prefixes: str = Field(diff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.pyindex 74a9ee744..0ab55afe1 100644--- a/agent/src/providers/chat.py+++ b/agent/src/providers/chat.py@@ -18,6 +18,7 @@ from typing import Any, Callable, Dict, List, Optionalfrom src.config.accessor import get_env_configfrom src.providers.content_filter import is_content_filter_triggeredfrom src.providers.llm import build_llm+from src.providers.tool_policy import offered_toolslogger = logging.getLogger(__name__)@@ -468,7 +469,7 @@ class ChatLLM:Returns:LLMResponse."""- llm = self._llm.bind_tools(tools) if tools else self._llm+ llm = self._llm.bind_tools(offered_tools(tools)) if tools else self._llmconfig = {"timeout": timeout} if timeout else {}messages, call_kwargs = self._prompt_cache_request(messages)ai_message = llm.invoke(messages, config=config, **call_kwargs)@@ -511,7 +512,7 @@ class ChatLLM:"""accumulated = Nonetry:- llm = self._llm.bind_tools(tools) if tools else self._llm+ llm = self._llm.bind_tools(offered_tools(tools)) if tools else self._llmconfig = {"timeout": timeout} if timeout else {}messages, call_kwargs = self._prompt_cache_request(messages)accumulated = Nonediff --git a/agent/src/providers/claude_cli_policy.py b/agent/src/providers/claude_cli_policy.pyindex d99243c7b..63bb35bc4 100644--- a/agent/src/providers/claude_cli_policy.py+++ b/agent/src/providers/claude_cli_policy.py@@ -1,129 +1,19 @@-"""Tool screening for the claude-cli provider: the deny list and the bash policy.--Both are convenience filters, not a security boundary: ``python -c`` can still-run anything, and live orders stay bound by the mandate gate and kill switch.-"""--from __future__ import annotations--import shlex-import sys-from pathlib import Path-from typing import Any, Optional--from src.config.accessor import get_env_config--_PYTHON_COMMANDS = frozenset({"python", "python3"})-_READONLY_COMMANDS = frozenset({"ls", "cat", "head", "tail", "wc", "pwd"})-_SHELL_PROCESS_TOOLS = frozenset({"background_run", "cancel_background"})-_SHELL_OPERATOR_CHARS = set("();<>|&")---def _deny_prefixes() -> tuple[str, ...]:- """Tool-name prefixes never offered to the model; ``""`` disables the list."""- raw = get_env_config().llm.claude_cli_deny_tool_prefixes- return tuple(p.strip() for p in raw.split(",") if p.strip())---def bash_policy() -> str:- """``python-only`` (default) or ``off``; anything else is a configuration error."""- value = get_env_config().llm.claude_cli_bash_policy.strip().lower()- if value not in {"python-only", "off"}:- raise RuntimeError(- f"CLAUDE_CLI_BASH_POLICY must be python-only or off, got {value!r}"- )- return value---def tool_name(definition: dict[str, Any]) -> str:- return str((definition.get("function") or definition).get("name") or "")---def offered_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:- prefixes = _deny_prefixes()- return (- [t for t in tools if not tool_name(t).startswith(prefixes)]- if prefixes- else list(tools)- )---def _relative_path(token: str) -> bool:- return not token.startswith(("/", "~")) and ".." not in Path(token).parts---def _hidden_path(token: str) -> bool:- # ``.env`` and ``.git`` hold credentials; a read would put them in the trace.- return any(part.startswith(".") and part != "." for part in Path(token).parts)---def check_bash_command(command: str) -> tuple[Optional[str], Optional[str]]:- """Apply the ``python-only`` policy to one shell command.-- Args:- command: The command the model asked ``bash`` to run.-- Returns:- ``(rewritten_command, None)`` when allowed, else ``(None, reason)``.- An allowed ``python``/``python3`` call is rewritten to this process's- interpreter so scripts can import Vibe-Trading's own packages.- """- if "\n" in command or "`" in command or "$(" in command:- return None, "newlines, backticks and $( ) are not allowed"- lexer = shlex.shlex(command, posix=True, punctuation_chars=True)- lexer.whitespace_split = True- try:- tokens = list(lexer)- except ValueError as exc:- return None, f"unparseable command: {exc}"- if not tokens:- return None, "empty command"- if any(tok and set(tok) <= _SHELL_OPERATOR_CHARS for tok in tokens):- return None, "shell operators (; && || | redirection) are not allowed"- program, args = tokens[0], tokens[1:]- if program in _PYTHON_COMMANDS:- if args[:1] == ["-c"] and len(args) >= 2:- return shlex.join([sys.executable, *args]), None- if args and args[0].endswith(".py") and _relative_path(args[0]):- return shlex.join([sys.executable, *args]), None- return (- None,- "python may only run `python <relative script>.py` or `python -c <code>`",- )- if program in _READONLY_COMMANDS:- paths = [a for a in args if not a.startswith("-")]- if all(_relative_path(p) and not _hidden_path(p) for p in paths):- return shlex.join(tokens), None- return (- None,- f"{program} may only read non-hidden relative paths inside the working directory",- )- return None, f"program {program!r} is not allowed (python-only policy)"---def screen_calls(- calls: list[dict[str, Any]], offered: set[str]-) -> tuple[list[dict[str, Any]], list[str]]:- """Return calls the host may execute, plus one rejection note per refused call."""- policy = bash_policy()- accepted: list[dict[str, Any]] = []- notes: list[str] = []- for call in calls:- name = str(call.get("name") or "")- args = dict(call.get("arguments") or {})- if name not in offered:- notes.append(f"- {name}: not an available tool")- continue- if policy == "python-only" and name in _SHELL_PROCESS_TOOLS:- notes.append(- f"- {name}: background processes are not allowed (python-only policy)"- )- continue- if policy == "python-only" and name == "bash":- rewritten, reason = check_bash_command(str(args.get("command") or ""))- if reason:- notes.append(f"- bash `{args.get('command')}`: {reason}")- continue- args["command"] = rewritten- accepted.append({"name": name, "arguments": args})- return accepted, notes+"""Compatibility re-exports for the provider-agnostic tool policy."""++from src.providers.tool_policy import (+ _deny_prefixes,+ bash_policy,+ check_bash_command,+ offered_tools,+ screen_calls,+ tool_name,+)++__all__ = [+ "_deny_prefixes",+ "bash_policy",+ "check_bash_command",+ "offered_tools",+ "screen_calls",+ "tool_name",+]diff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.pyindex d40cecc2b..9564f9a72 100644--- a/agent/src/providers/llm.py+++ b/agent/src/providers/llm.py@@ -1581,6 +1581,8 @@ def provider_diagnostics() -> dict[str, Any]:)else "openai-compatible")+ from src.providers.tool_policy import policy_status+return {"provider": caps.name if provider in {"kimi", "openai_codex"} else provider,"model": model,@@ -1620,6 +1622,7 @@ def provider_diagnostics() -> dict[str, Any]:"packages": {name: _package_version(name) for name in package_names},"timeout_seconds": get_env_config().llm.timeout_seconds,"max_retries": get_env_config().llm.max_retries,+ "tool_policy": policy_status(),"reasoning_effort": get_env_config().llm.langchain_reasoning_effort.strip().lower(),"adapter": {"type": adapter_type,diff --git a/agent/src/providers/tool_policy.py b/agent/src/providers/tool_policy.pynew file mode 100644index 000000000..1f314257c--- /dev/null+++ b/agent/src/providers/tool_policy.py@@ -0,0 +1,160 @@+"""Provider-agnostic tool screening: the deny list and the bash policy.++Both are convenience filters, not a security boundary: ``python -c`` can still+run anything, and live orders stay bound by the mandate gate and kill switch.+"""++from __future__ import annotations++import shlex+import sys+from pathlib import Path+from typing import Any, Optional++from src.config.accessor import get_env_config++_PYTHON_COMMANDS = frozenset({"python", "python3"})+_READONLY_COMMANDS = frozenset({"ls", "cat", "head", "tail", "wc", "pwd"})+_SHELL_PROCESS_TOOLS = frozenset({"background_run", "cancel_background"})+_SHELL_OPERATOR_CHARS = set("();<>|&")+++def _deny_prefixes() -> tuple[str, ...]:+ """Tool-name prefixes never offered to the model; ``""`` disables the list."""+ config = get_env_config().llm+ raw = config.vibe_trading_deny_tool_prefixes+ if raw is None:+ raw = config.claude_cli_deny_tool_prefixes+ return tuple(p.strip() for p in raw.split(",") if p.strip())+++def bash_policy() -> str:+ """``python-only`` (default) or ``off``; anything else is a configuration error."""+ config = get_env_config().llm+ generic = config.vibe_trading_bash_policy+ value = (+ (generic if generic is not None else config.claude_cli_bash_policy)+ .strip()+ .lower()+ )+ if value not in {"python-only", "off"}:+ source = (+ "VIBE_TRADING_BASH_POLICY"+ if generic is not None+ else "CLAUDE_CLI_BASH_POLICY"+ )+ raise RuntimeError(f"{source} must be python-only or off, got {value!r}")+ return value+++def policy_status() -> dict[str, Any]:+ """Return the active, non-secret policy for provider diagnostics."""+ config = get_env_config().llm+ return {+ "deny_tool_prefixes": list(_deny_prefixes()),+ "deny_tool_prefixes_source": (+ "VIBE_TRADING_DENY_TOOL_PREFIXES"+ if config.vibe_trading_deny_tool_prefixes is not None+ else "CLAUDE_CLI_DENY_TOOL_PREFIXES"+ ),+ "bash_policy": bash_policy(),+ "bash_policy_source": (+ "VIBE_TRADING_BASH_POLICY"+ if config.vibe_trading_bash_policy is not None+ else "CLAUDE_CLI_BASH_POLICY"+ ),+ }+++def tool_name(definition: dict[str, Any]) -> str:+ return str((definition.get("function") or definition).get("name") or "")+++def offered_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:+ prefixes = _deny_prefixes()+ return (+ [t for t in tools if not tool_name(t).startswith(prefixes)]+ if prefixes+ else list(tools)+ )+++def _relative_path(token: str) -> bool:+ return not token.startswith(("/", "~")) and ".." not in Path(token).parts+++def _hidden_path(token: str) -> bool:+ # ``.env`` and ``.git`` hold credentials; a read would put them in the trace.+ return any(part.startswith(".") and part != "." for part in Path(token).parts)+++def check_bash_command(command: str) -> tuple[Optional[str], Optional[str]]:+ """Apply the ``python-only`` policy to one shell command.++ Args:+ command: The command the model asked ``bash`` to run.++ Returns:+ ``(rewritten_command, None)`` when allowed, else ``(None, reason)``.+ An allowed ``python``/``python3`` call is rewritten to this process's+ interpreter so scripts can import Vibe-Trading's own packages.+ """+ if "\n" in command or "`" in command or "$(" in command:+ return None, "newlines, backticks and $( ) are not allowed"+ lexer = shlex.shlex(command, posix=True, punctuation_chars=True)+ lexer.whitespace_split = True+ try:+ tokens = list(lexer)+ except ValueError as exc:+ return None, f"unparseable command: {exc}"+ if not tokens:+ return None, "empty command"+ if any(tok and set(tok) <= _SHELL_OPERATOR_CHARS for tok in tokens):+ return None, "shell operators (; && || | redirection) are not allowed"+ program, args = tokens[0], tokens[1:]+ if program in _PYTHON_COMMANDS:+ if args[:1] == ["-c"] and len(args) >= 2:+ return shlex.join([sys.executable, *args]), None+ if args and args[0].endswith(".py") and _relative_path(args[0]):+ return shlex.join([sys.executable, *args]), None+ return (+ None,+ "python may only run `python <relative script>.py` or `python -c <code>`",+ )+ if program in _READONLY_COMMANDS:+ paths = [a for a in args if not a.startswith("-")]+ if all(_relative_path(p) and not _hidden_path(p) for p in paths):+ return shlex.join(tokens), None+ return (+ None,+ f"{program} may only read non-hidden relative paths inside the working directory",+ )+ return None, f"program {program!r} is not allowed (python-only policy)"+++def screen_calls(+ calls: list[dict[str, Any]], offered: set[str]+) -> tuple[list[dict[str, Any]], list[str]]:+ """Return calls the host may execute, plus one rejection note per refused call."""+ policy = bash_policy()+ accepted: list[dict[str, Any]] = []+ notes: list[str] = []+ for call in calls:+ name = str(call.get("name") or "")+ args = dict(call.get("arguments") or {})+ if name not in offered:+ notes.append(f"- {name}: not an available tool")+ continue+ if policy == "python-only" and name in _SHELL_PROCESS_TOOLS:+ notes.append(+ f"- {name}: background processes are not allowed (python-only policy)"+ )+ continue+ if policy == "python-only" and name == "bash":+ rewritten, reason = check_bash_command(str(args.get("command") or ""))+ if reason:+ notes.append(f"- bash `{args.get('command')}`: {reason}")+ continue+ args["command"] = rewritten+ accepted.append({"name": name, "arguments": args})+ return accepted, notesdiff --git a/agent/tests/test_provider_agnostic_tool_policy.py b/agent/tests/test_provider_agnostic_tool_policy.pynew file mode 100644index 000000000..70565dbf6--- /dev/null+++ b/agent/tests/test_provider_agnostic_tool_policy.py@@ -0,0 +1,234 @@+"""Provider-agnostic deny lists and bash screening (#2085)."""++from __future__ import annotations++import json+import sys+from types import SimpleNamespace++import pytest+from langchain_core.messages import AIMessage, AIMessageChunk++from src.agent.context import ContextBuilder+from src.agent.loop import AgentLoop+from src.agent.tools import BaseTool, ToolRegistry+from src.agent.trace import TraceWriter+from src.config.accessor import get_env_config, reset_env_config+from src.providers.chat import ChatLLM+from src.providers.llm import provider_diagnostics+from src.providers.tool_policy import bash_policy, policy_status++_POLICY_ENV = (+ "VIBE_TRADING_DENY_TOOL_PREFIXES",+ "VIBE_TRADING_BASH_POLICY",+ "CLAUDE_CLI_DENY_TOOL_PREFIXES",+ "CLAUDE_CLI_BASH_POLICY",+)++[email protected](autouse=True)+def clean_policy_env(monkeypatch: pytest.MonkeyPatch):+ for name in _POLICY_ENV:+ monkeypatch.delenv(name, raising=False)+ reset_env_config()+ yield+ reset_env_config()+++def _tool(name: str) -> dict:+ return {+ "type": "function",+ "function": {+ "name": name,+ "description": "test tool",+ "parameters": {"type": "object", "properties": {}},+ },+ }+++class _RecordingLLM:+ def __init__(self) -> None:+ self.bound_tools: list[dict] | None = None++ def bind_tools(self, tools: list[dict]) -> _RecordingLLM:+ self.bound_tools = tools+ return self++ def invoke(self, messages: list[dict], **kwargs: object) -> AIMessage:+ return AIMessage(content="ok")++ def stream(self, messages: list[dict], **kwargs: object):+ yield AIMessageChunk(content="ok", response_metadata={"finish_reason": "stop"})+++def _chat(llm: _RecordingLLM) -> ChatLLM:+ chat = ChatLLM.__new__(ChatLLM)+ chat._llm = llm+ chat.model_name = "gpt-test"+ return chat+++def test_chat_filters_denied_tools_before_any_provider_binds() -> None:+ llm = _RecordingLLM()++ _chat(llm).chat(+ [{"role": "user", "content": "x"}],+ tools=[+ _tool("get_market_data"),+ _tool("trading_place_order"),+ _tool("etoro_close_position"),+ ],+ )++ assert llm.bound_tools is not None+ assert [item["function"]["name"] for item in llm.bound_tools] == ["get_market_data"]+++def test_stream_chat_uses_the_same_provider_agnostic_filter() -> None:+ llm = _RecordingLLM()++ response = _chat(llm).stream_chat(+ [{"role": "user", "content": "x"}],+ tools=[_tool("get_market_data"), _tool("trading_place_order")],+ )++ assert response.content == "ok"+ assert llm.bound_tools is not None+ assert [item["function"]["name"] for item in llm.bound_tools] == ["get_market_data"]+++class _FakeBashTool(BaseTool):+ name = "bash"+ description = "recording bash double"+ parameters: dict = {"type": "object", "properties": {}}+ is_readonly = False++ def __init__(self, name: str = "bash") -> None:+ self.name = name+ self.calls: list[dict] = []++ def execute(self, **kwargs: object) -> str:+ self.calls.append(kwargs)+ return json.dumps({"status": "ok", "arguments": kwargs})+++def _agent(tool: BaseTool, tmp_path) -> AgentLoop:+ registry = ToolRegistry()+ registry.register(tool)+ agent = AgentLoop(+ registry=registry,+ llm=SimpleNamespace(),+ max_iterations=2,+ event_callback=lambda name, data: None,+ )+ agent.memory.run_dir = str(tmp_path)+ return agent+++def _call(agent: AgentLoop, name: str, arguments: dict, tmp_path) -> list[dict]:+ messages: list[dict] = []+ trace = TraceWriter(tmp_path)+ agent._process_tool_calls(+ [SimpleNamespace(id="call-1", name=name, arguments=arguments)],+ ContextBuilder,+ messages,+ trace,+ [],+ 1,+ )+ trace.close()+ return messages+++def test_shared_execution_rejects_bash_without_running_it(tmp_path) -> None:+ tool = _FakeBashTool()+ agent = _agent(tool, tmp_path)++ messages = _call(agent, "bash", {"command": "curl https://example.com"}, tmp_path)++ assert tool.calls == []+ assert "not allowed" in messages[0]["content"]+++def test_shared_execution_rewrites_allowed_python(tmp_path) -> None:+ tool = _FakeBashTool()+ agent = _agent(tool, tmp_path)++ _call(agent, "bash", {"command": "python report.py"}, tmp_path)++ assert len(tool.calls) == 1+ assert tool.calls[0]["command"].startswith(sys.executable)+++def test_shared_execution_fail_closed_for_a_directly_denied_tool(tmp_path) -> None:+ tool = _FakeBashTool("trading_place_order")+ agent = _agent(tool, tmp_path)++ messages = _call(agent, "trading_place_order", {}, tmp_path)++ assert tool.calls == []+ assert "disabled by the active tool policy" in messages[0]["content"]+++def test_generic_off_allows_the_shared_bash_path_unchanged(+ monkeypatch, tmp_path+) -> None:+ monkeypatch.setenv("VIBE_TRADING_BASH_POLICY", "off")+ reset_env_config()+ tool = _FakeBashTool()+ agent = _agent(tool, tmp_path)++ _call(agent, "bash", {"command": "curl https://example.com"}, tmp_path)++ assert len(tool.calls) == 1+ assert tool.calls[0]["command"] == "curl https://example.com"+++def test_generic_values_override_legacy_aliases(monkeypatch) -> None:+ monkeypatch.setenv("CLAUDE_CLI_BASH_POLICY", "off")+ monkeypatch.setenv("VIBE_TRADING_BASH_POLICY", "python-only")+ monkeypatch.setenv("VIBE_TRADING_DENY_TOOL_PREFIXES", "custom_")+ reset_env_config()++ assert bash_policy() == "python-only"+ assert policy_status() == {+ "deny_tool_prefixes": ["custom_"],+ "deny_tool_prefixes_source": "VIBE_TRADING_DENY_TOOL_PREFIXES",+ "bash_policy": "python-only",+ "bash_policy_source": "VIBE_TRADING_BASH_POLICY",+ }+++def test_legacy_values_remain_the_fallback(monkeypatch) -> None:+ monkeypatch.setenv("CLAUDE_CLI_BASH_POLICY", "off")+ monkeypatch.setenv("CLAUDE_CLI_DENY_TOOL_PREFIXES", "legacy_")+ reset_env_config()++ assert policy_status()["deny_tool_prefixes"] == ["legacy_"]+ assert policy_status()["bash_policy"] == "off"+++def test_invalid_generic_policy_names_the_generic_variable(monkeypatch) -> None:+ monkeypatch.setenv("VIBE_TRADING_BASH_POLICY", "strict")+ reset_env_config()++ with pytest.raises(RuntimeError, match="VIBE_TRADING_BASH_POLICY"):+ bash_policy()+++def test_provider_doctor_exposes_only_the_active_nonsecret_policy(monkeypatch) -> None:+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "openai")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "gpt-test")+ monkeypatch.setenv("VIBE_TRADING_DENY_TOOL_PREFIXES", "custom_")+ monkeypatch.setenv("VIBE_TRADING_BASH_POLICY", "off")+ reset_env_config()++ diagnostics = provider_diagnostics()++ assert diagnostics["tool_policy"] == {+ "deny_tool_prefixes": ["custom_"],+ "deny_tool_prefixes_source": "VIBE_TRADING_DENY_TOOL_PREFIXES",+ "bash_policy": "off",+ "bash_policy_source": "VIBE_TRADING_BASH_POLICY",+ }+ assert get_env_config().llm.vibe_trading_deny_tool_prefixes == "custom_"diff --git a/agent/tests/test_readonly_replay_after_microcompact.py b/agent/tests/test_readonly_replay_after_microcompact.pyindex 97c10d223..1a182a3c4 100644--- a/agent/tests/test_readonly_replay_after_microcompact.py+++ b/agent/tests/test_readonly_replay_after_microcompact.py@@ -523,7 +523,7 @@ def test_a_write_makes_earlier_readonly_results_unreplayable() -> None:read = {"factor_csv": "factor.csv"}loop._process_tool_calls([SimpleNamespace(name="factor_analysis", arguments=read, id="f1")], _Context(), [], _Trace(), [], 1)loop._process_tool_calls(- [SimpleNamespace(name="bash", arguments={"command": "python make_factor.py > factor.csv"}, id="w1")],+ [SimpleNamespace(name="bash", arguments={"command": "python make_factor.py"}, id="w1")],_Context(), [], _Trace(), [], 2,)assert loop._readonly_replay_visibility_pending == set()