"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(tools): reject ambiguous boolean flags before changing state
Haozhe Wu6dafa4cdecd4
diff --git a/agent/src/tools/_arguments.py b/agent/src/tools/_arguments.pynew file mode 100644index 000000000..bcca32d42--- /dev/null+++ b/agent/src/tools/_arguments.py@@ -0,0 +1,34 @@+"""Shared coercion for tool arguments received from JSON callers."""++from __future__ import annotations++from typing import Any+++def boolean_argument(value: Any, *, field: str) -> bool:+ """Parse an optional boolean without treating non-empty strings as true.++ Args:+ value: Boolean, null, zero/one, or an explicit boolean spelling.+ field: Argument name to include in a validation error.++ Returns:+ The parsed boolean; null retains the historical false value.++ Raises:+ ValueError: If the input is ambiguous or malformed. In particular,+ an unknown dry-run string must never silently enable writes.+ """+ if value is None:+ return False+ if isinstance(value, bool):+ return value+ if isinstance(value, str):+ token = value.strip().lower()+ if token in {"true", "1", "yes", "on"}:+ return True+ if token in {"false", "0", "no", "off"}:+ return False+ elif isinstance(value, (int, float)) and value in (0, 1):+ return bool(value)+ raise ValueError(f"{field} must be a boolean (true or false)")diff --git a/agent/src/tools/autopilot_tool.py b/agent/src/tools/autopilot_tool.pyindex 91cecdbbb..e4ecdda79 100644--- a/agent/src/tools/autopilot_tool.py+++ b/agent/src/tools/autopilot_tool.py@@ -16,6 +16,7 @@ from pathlib import Pathfrom typing import Anyfrom src.agent.tools import BaseTool+from src.tools._arguments import boolean_argumentfrom src.config.paths import get_runs_dirfrom src.hypotheses import HypothesisRegistry@@ -492,7 +493,7 @@ class ScaffoldSignalEngineTool(BaseTool):ensure_ascii=False,)- overwrite = bool(kwargs.get("overwrite", False))+ overwrite = boolean_argument(kwargs.get("overwrite", False), field="overwrite")code_dir = run_path / "code"code_dir.mkdir(parents=True, exist_ok=True)signal_path = code_dir / "signal_engine.py"diff --git a/agent/src/tools/cashflow_analytics_tool.py b/agent/src/tools/cashflow_analytics_tool.pyindex c7d397dfd..ce1a5e300 100644--- a/agent/src/tools/cashflow_analytics_tool.py+++ b/agent/src/tools/cashflow_analytics_tool.py@@ -14,6 +14,7 @@ from datetime import datefrom typing import Anyfrom src.agent.tools import BaseTool+from src.tools._arguments import boolean_argumentfrom src.entities.cashflow import CashFlow, CashFlowSeriesfrom src.entities.ingest import load_cashflowsfrom src.quantlib.performance import (@@ -359,13 +360,14 @@ def _resolve_flows(kwargs: dict[str, Any]) -> CashFlowSeries | None:columns = kwargs.get("flows_columns")if columns is not None and not isinstance(columns, dict):raise ValueError("flows_columns must be an object mapping field to column name")+ invert_sign = boolean_argument(kwargs.get("flows_invert_sign", False), field="flows_invert_sign")return load_cashflows(str(path),columns=columns,currency=currency,default_kind=kwargs.get("flows_default_kind"),date_format=kwargs.get("flows_date_format"),- invert_sign=bool(kwargs.get("flows_invert_sign", False)),+ invert_sign=invert_sign,)if not inline:diff --git a/agent/src/tools/institutional_holdings_tool.py b/agent/src/tools/institutional_holdings_tool.pyindex 825798fdd..9f37b1a24 100644--- a/agent/src/tools/institutional_holdings_tool.py+++ b/agent/src/tools/institutional_holdings_tool.py@@ -118,6 +118,7 @@ from backtest.loaders.sec_edgar_client import get_submissions# place to change them. Both are stable module-level helpers.from backtest.loaders.sec_edgar_client import _min_interval, _pad_cik, _user_agentfrom src.agent.tools import BaseTool+from src.tools._arguments import boolean_argumentfrom src.config.accessor import get_env_configfrom src.config.limits import TOOL_RESULT_LIMITfrom src.tools._result_paging import fit_records@@ -1940,7 +1941,7 @@ class InstitutionalHoldingsTool(BaseTool):if candidates:data["other_name_matches"] = candidates- if kwargs.get("include_changes"):+ if boolean_argument(kwargs.get("include_changes"), field="include_changes"):data["changes"] = self._changes_block(cik, filings, target, positions, budget)return _envelope("manager_holdings", data, positions[:top_n], "positions", offset)diff --git a/agent/src/tools/propose_mandate_tool.py b/agent/src/tools/propose_mandate_tool.pyindex fcccb5f75..bc7e0d2ab 100644--- a/agent/src/tools/propose_mandate_tool.py+++ b/agent/src/tools/propose_mandate_tool.py@@ -22,6 +22,7 @@ import uuidfrom typing import Anyfrom src.agent.tools import BaseTool+from src.tools._arguments import boolean_argumentfrom src.live.mandate.commit import _normalize_limits, save_proposal#: Ordered profile templates synthesized when the caller gives no explicit@@ -124,9 +125,8 @@ class ProposeMandateProfilesTool(BaseTool):intent = str(kwargs.get("intent") or "").strip()session_id = kwargs.get("session_id")reauth_for = kwargs.get("reauth_for") if isinstance(kwargs.get("reauth_for"), dict) else None- flatten_on_halt = bool(kwargs.get("flatten_on_halt", False))-try:+ flatten_on_halt = boolean_argument(kwargs.get("flatten_on_halt", False), field="flatten_on_halt")profiles = self._synthesize_profiles(ceilings, reauth_for, flatten_on_halt)except (TypeError, ValueError) as exc:return json.dumps(diff --git a/agent/src/tools/sdm_decay_scan_tool.py b/agent/src/tools/sdm_decay_scan_tool.pyindex 372c7ce6c..8e8ded9ae 100644--- a/agent/src/tools/sdm_decay_scan_tool.py+++ b/agent/src/tools/sdm_decay_scan_tool.py@@ -6,6 +6,7 @@ import jsonfrom typing import Anyfrom src.agent.tools import BaseTool+from src.tools._arguments import boolean_argumentfrom src.strategy_store.decay import DecayEvaluatorfrom src.strategy_store.metrics import (DECAY_BENCH_TYPES,@@ -70,7 +71,7 @@ class SdmDecayScanTool(BaseTool):type_filter = Noneif kwargs.get("artifact_type"):type_filter = ArtifactType(kwargs["artifact_type"])- dry_run = bool(kwargs.get("dry_run", False))+ dry_run = boolean_argument(kwargs.get("dry_run", False), field="dry_run")# Collect ACTIVE and MONITORING artifactsactive = store.list_artifacts(diff --git a/agent/src/tools/taiwan_stock_data_tool.py b/agent/src/tools/taiwan_stock_data_tool.pyindex 298c9e3dc..c06827b37 100644--- a/agent/src/tools/taiwan_stock_data_tool.py+++ b/agent/src/tools/taiwan_stock_data_tool.py@@ -13,6 +13,7 @@ from pathlib import Pathfrom typing import Anyfrom src.agent.tools import BaseTool+from src.tools._arguments import boolean_argumentfrom src.config.accessor import get_env_configDEFAULT_DB_PATH = "/data/tw-stock/latest.db"@@ -1180,12 +1181,7 @@ class TaiwanStockDataTool(BaseTool):else:data = self._universe(connection,- active_only=bool(- kwargs.get(- "active_only",- True,- )- ),+ active_only=boolean_argument(kwargs.get("active_only", True), field="active_only"),market=kwargs.get("market"),industry=kwargs.get("industry"),limit=limit,diff --git a/agent/src/tools/trading_connector_tool.py b/agent/src/tools/trading_connector_tool.pyindex 4c4aa86e0..00b8c4890 100644--- a/agent/src/tools/trading_connector_tool.py+++ b/agent/src/tools/trading_connector_tool.py@@ -11,6 +11,7 @@ import mathfrom typing import Anyfrom src.agent.tools import BaseTool+from src.tools._arguments import boolean_argumentfrom src.trading.profiles import (list_profiles,load_selected_profile_id,@@ -370,7 +371,7 @@ class TradingOrdersTool(BaseTool):return _json_result(get_open_orders(_connection(kwargs.get("connection")),- include_executions=bool(kwargs.get("include_executions", False)),+ include_executions=boolean_argument(kwargs.get("include_executions", False), field="include_executions"),**_overrides(kwargs),))@@ -452,7 +453,7 @@ class TradingHistoryTool(BaseTool):duration=str(kwargs.get("duration") or "30 D"),bar_size=str(kwargs.get("bar_size") or "1 day"),what_to_show=str(kwargs.get("what_to_show") or "TRADES"),- use_rth=bool(kwargs.get("use_rth", True)),+ use_rth=boolean_argument(kwargs.get("use_rth", True), field="use_rth"),period=str(kwargs.get("period") or "1d"),limit=int(kwargs.get("limit") or 90),**_overrides(kwargs),@@ -1026,9 +1027,9 @@ class EtoroEditPositionStopsTool(BaseTool):_connection(kwargs.get("connection")),stop_loss=stop_loss,take_profit=take_profit,- trailing_stop_loss=bool(trailing) if trailing is not None else None,- clear_stop_loss=bool(kwargs.get("clear_stop_loss", False)),- clear_take_profit=bool(kwargs.get("clear_take_profit", False)),+ trailing_stop_loss=boolean_argument(trailing, field="trailing_stop_loss") if trailing is not None else None,+ clear_stop_loss=boolean_argument(kwargs.get("clear_stop_loss"), field="clear_stop_loss"),+ clear_take_profit=boolean_argument(kwargs.get("clear_take_profit"), field="clear_take_profit"),request_id=_connection(kwargs.get("request_id")),**overrides,)diff --git a/agent/src/tools/web_reader_tool.py b/agent/src/tools/web_reader_tool.pyindex 304049be7..28463ef25 100644--- a/agent/src/tools/web_reader_tool.py+++ b/agent/src/tools/web_reader_tool.py@@ -11,6 +11,7 @@ import requestsfrom src.agent.progress import emit_progressfrom src.agent.tools import BaseTool+from src.tools._arguments import boolean_argumentfrom src.security.scanner import with_security_warningslogger = logging.getLogger(__name__)@@ -162,4 +163,8 @@ class WebReaderTool(BaseTool):def execute(self, **kwargs) -> str:"""Fetch web page."""- return read_url(kwargs["url"], no_cache=bool(kwargs.get("no_cache", False)))+ try:+ no_cache = boolean_argument(kwargs.get("no_cache", False), field="no_cache")+ except ValueError as exc:+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)+ return read_url(kwargs["url"], no_cache=no_cache)diff --git a/agent/tests/test_autopilot_phase3.py b/agent/tests/test_autopilot_phase3.pyindex 877d0016e..add741566 100644--- a/agent/tests/test_autopilot_phase3.py+++ b/agent/tests/test_autopilot_phase3.py@@ -165,6 +165,52 @@ def test_scaffold_refuses_overwrite_by_default(isolated_env: Path) -> None:assert "SignalEngine" in signal_path.read_text(encoding="utf-8")+ ("flag", "error"),+ [+ ("false", "already exists"),+ ("False", "already exists"),+ ("0", "already exists"),+ ("no", "already exists"),+ ("", "overwrite must be a boolean"),+ ("maybe", "overwrite must be a boolean"),+ ],+)+def test_scaffold_false_or_invalid_overwrite_keeps_existing_file(+ isolated_env: Path, flag: str, error: str+) -> None:+ hyp_id = _make_hypothesis()+ run_dir = _run_dir(isolated_env)+ tool = ScaffoldSignalEngineTool()+ first = json.loads(tool.execute(hypothesis_id=hyp_id, run_dir=str(run_dir)))+ signal_path = Path(first["signal_engine_path"])+ signal_path.write_text("# user edits\n", encoding="utf-8")++ result = json.loads(+ tool.execute(hypothesis_id=hyp_id, run_dir=str(run_dir), overwrite=flag)+ )++ assert result["status"] == "error"+ assert error in result["error"]+ assert signal_path.read_text(encoding="utf-8") == "# user edits\n"+++def test_scaffold_string_true_overwrite_replaces_file(isolated_env: Path) -> None:+ hyp_id = _make_hypothesis()+ run_dir = _run_dir(isolated_env)+ tool = ScaffoldSignalEngineTool()+ first = json.loads(tool.execute(hypothesis_id=hyp_id, run_dir=str(run_dir)))+ signal_path = Path(first["signal_engine_path"])+ signal_path.write_text("# user edits\n", encoding="utf-8")++ result = json.loads(+ tool.execute(hypothesis_id=hyp_id, run_dir=str(run_dir), overwrite="true")+ )++ assert result["status"] == "ok"+ assert "SignalEngine" in signal_path.read_text(encoding="utf-8")++# --------------------------------------------------------------------------# link_autopilot_backtest# --------------------------------------------------------------------------diff --git a/agent/tests/test_cashflow_analytics_tool.py b/agent/tests/test_cashflow_analytics_tool.pyindex 364d63b50..a894e757d 100644--- a/agent/tests/test_cashflow_analytics_tool.py+++ b/agent/tests/test_cashflow_analytics_tool.py@@ -104,6 +104,23 @@ def test_flows_can_be_loaded_from_a_file_and_internal_kinds_are_ignored(assert payload["summary"]["time_weighted_return"] == pytest.approx(-0.01, abs=1e-9)[email protected]("flag", ["false", "False", "0", "no"])+def test_a_string_false_invert_sign_leaves_file_amounts_alone(+ tmp_path: Path, flag: str+) -> None:+ """A JSON-string "false" must not be read as truthy and negate every row."""+ payload = json.loads(+ CashFlowPerformanceTool().execute(+ valuations=_valuations(),+ flows_path=str(_write_flow_file(tmp_path)),+ flows_invert_sign=flag,+ )+ )++ assert payload["status"] == "ok"+ assert payload["summary"]["net_external_flow"] == pytest.approx(900.0)++def test_a_bad_path_returns_a_clean_error_envelope(tmp_path: Path) -> None:"""A missing file is an explicit error, never a silent null result."""payload = json.loads(diff --git a/agent/tests/test_consent_commit.py b/agent/tests/test_consent_commit.pyindex 092ec3949..95d000bd7 100644--- a/agent/tests/test_consent_commit.py+++ b/agent/tests/test_consent_commit.py@@ -564,6 +564,33 @@ def test_propose_opt_in_flatten_on_halt_stamps_profiles(live_runtime: Path) -> Nassert profile["flatten_on_halt"] is True[email protected]("flag", ["false", "False", "0", "no", ""])+def test_propose_string_false_flatten_on_halt_stays_cancel_only(+ live_runtime: Path, flag: str+) -> None:+ """A JSON-string "false" must not opt every profile into flattening."""+ tool = ProposeMandateProfilesTool()+ payload = json.loads(+ tool.execute(broker="robinhood", ceilings=dict(_CEILINGS), flatten_on_halt=flag)+ )+ if flag == "":+ assert payload["status"] == "error"+ assert "flatten_on_halt" in payload["error"]+ assert "profiles" not in payload+ return+ for profile in payload["profiles"]:+ assert profile["flatten_on_halt"] is False+++def test_propose_string_true_flatten_on_halt_opts_in(live_runtime: Path) -> None:+ tool = ProposeMandateProfilesTool()+ payload = json.loads(+ tool.execute(broker="robinhood", ceilings=dict(_CEILINGS), flatten_on_halt="true")+ )+ for profile in payload["profiles"]:+ assert profile["flatten_on_halt"] is True++def test_commit_persists_flatten_on_halt_from_profile(live_runtime: Path) -> None:"""An opted-in proposal commits a mandate.json carrying flatten_on_halt=True."""tool = ProposeMandateProfilesTool()diff --git a/agent/tests/test_etoro_edit_stops_tool_flags.py b/agent/tests/test_etoro_edit_stops_tool_flags.pynew file mode 100644index 000000000..91956a2c0--- /dev/null+++ b/agent/tests/test_etoro_edit_stops_tool_flags.py@@ -0,0 +1,46 @@+"""etoro_edit_position_stops reads JSON-string stop flags by their value."""++from __future__ import annotations++import json+from typing import Any++import pytest++import src.tools.trading_connector_tool as tool_mod+++def seen(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:+ box: dict[str, Any] = {}++ def fake_edit(position_id: str, _conn: Any, **kw: Any) -> dict:+ box.update(kw, position_id=position_id)+ return {"status": "ok"}++ monkeypatch.setattr(tool_mod, "edit_position_stops", fake_edit)+ return box++[email protected]("flag", ["false", "False", "0", "no"])+def test_string_false_keeps_stops_and_fixed_type(seen: dict[str, Any], flag: str) -> None:+ out = json.loads(+ tool_mod.EtoroEditPositionStopsTool().execute(+ position_id="123",+ take_profit=110.0,+ clear_stop_loss=flag,+ clear_take_profit=flag,+ trailing_stop_loss=flag,+ )+ )+ assert out["status"] == "ok"+ assert seen["clear_stop_loss"] is False+ assert seen["clear_take_profit"] is False+ assert seen["trailing_stop_loss"] is False+++def test_string_true_and_omitted_flags(seen: dict[str, Any]) -> None:+ tool_mod.EtoroEditPositionStopsTool().execute(position_id="123", clear_stop_loss="true")+ assert seen["clear_stop_loss"] is True+ assert seen["clear_take_profit"] is False+ assert seen["trailing_stop_loss"] is Nonediff --git a/agent/tests/test_institutional_holdings_tool.py b/agent/tests/test_institutional_holdings_tool.pyindex cf98cc9bf..bd4de9ea6 100644--- a/agent/tests/test_institutional_holdings_tool.py+++ b/agent/tests/test_institutional_holdings_tool.py@@ -548,6 +548,23 @@ class TestManagerHoldingsMode:assert changes["prior_quarter"] == "2025Q4"assert changes["counts"] == {"reduced": 1, "closed": 1}+ def test_string_false_include_changes_skips_the_prior_quarter_diff(self) -> None:+ for flag in ("false", "False", "0", "no"):+ with patch.object(iht, "_sec_get", side_effect=_router()):+ payload = json.loads(+ InstitutionalHoldingsTool().execute(+ manager="0001067983", quarter="2026Q1", include_changes=flag+ )+ )+ assert "changes" not in payload["data"], flag++ def test_string_true_include_changes_still_diffs(self) -> None:+ with patch.object(iht, "_sec_get", side_effect=_router()):+ payload = json.loads(+ InstitutionalHoldingsTool().execute(manager="0001067983", quarter="2026Q1", include_changes="true")+ )+ assert payload["data"]["changes"]["prior_quarter"] == "2025Q4"+def test_a_busy_diff_stays_inside_the_result_budget(self) -> None:"""The change list rides outside the paged position list, so it needs its own cap.diff --git a/agent/tests/test_sdm_decay_scan_dry_run_flag.py b/agent/tests/test_sdm_decay_scan_dry_run_flag.pynew file mode 100644index 000000000..54cca919f--- /dev/null+++ b/agent/tests/test_sdm_decay_scan_dry_run_flag.py@@ -0,0 +1,69 @@+"""sdm_decay_scan reads a JSON-string dry_run flag by its value."""++import json++import pytest++from src.strategy_store.models import (+ Artifact,+ ArtifactStatus,+ ArtifactType,+ BenchResult,+ DecaySignal,+ DecaySnapshot,+)+from src.strategy_store.store import InMemoryStrategyStore+from src.tools.sdm_decay_scan_tool import SdmDecayScanTool+++def _decaying_store(monkeypatch):+ store = InMemoryStrategyStore()+ monkeypatch.setattr("src.tools.sdm_decay_scan_tool._get_store", lambda: store)+ aid = store.register_artifact(+ Artifact(+ id="",+ name="decay_factor",+ type=ArtifactType.FACTOR,+ universe="CSI300",+ status=ArtifactStatus.ACTIVE,+ )+ )+ for _ in range(5):+ store.record_bench(BenchResult(artifact_id=aid, ic_mean=0.08))+ for _ in range(5):+ store.record_bench(BenchResult(artifact_id=aid, ic_mean=0.04))+ for _ in range(2):+ store.record_decay_snapshot(+ DecaySnapshot(artifact_id=aid, ic_ratio=0.5, decay_signal=DecaySignal.WARNING)+ )+ return store, aid++[email protected]("flag", ["false", "False", "0", "no"])+def test_string_false_dry_run_applies_the_transition(monkeypatch, flag):+ store, aid = _decaying_store(monkeypatch)++ result = json.loads(SdmDecayScanTool().execute(dry_run=flag))++ assert result["dry_run"] is False+ assert result["transitions_applied"] == 1+ assert store.get_artifact(aid).status == ArtifactStatus.MONITORING+++def test_string_true_dry_run_changes_nothing(monkeypatch):+ store, aid = _decaying_store(monkeypatch)++ result = json.loads(SdmDecayScanTool().execute(dry_run="true"))++ assert result["dry_run"] is True+ assert result["transitions_applied"] == 0+ assert store.get_artifact(aid).status == ArtifactStatus.ACTIVE++[email protected]("flag", ["treu", "maybe", "", [], 2])+def test_invalid_dry_run_does_not_write_a_transition(monkeypatch, flag):+ store, aid = _decaying_store(monkeypatch)+ result = json.loads(SdmDecayScanTool().execute(dry_run=flag))+ assert result["status"] == "error"+ assert "dry_run" in result["error"]+ assert store.get_artifact(aid).status == ArtifactStatus.ACTIVEdiff --git a/agent/tests/test_taiwan_stock_data_tool.py b/agent/tests/test_taiwan_stock_data_tool.pyindex 212e192fe..5332c337a 100644--- a/agent/tests/test_taiwan_stock_data_tool.py+++ b/agent/tests/test_taiwan_stock_data_tool.py@@ -557,6 +557,27 @@ def test_universe_defaults_to_active_only(][email protected]("flag", [False, "false", "False", "0", "no"])+def test_universe_active_only_false_includes_inactive_stocks(+ tmp_path: Path,+ flag: object,+) -> None:+ db_path = _create_test_database(tmp_path)+ tool = TaiwanStockDataTool(db_path)++ payload = json.loads(+ tool.execute(+ action="universe",+ active_only=flag,+ limit=20,+ )+ )++ records = payload["data"]["records"]++ assert sorted(row["stock_id"] for row in records) == ["0054", "2330"]++def test_lookup_reports_unknown_stock_ids(tmp_path: Path,) -> None:diff --git a/agent/tests/test_tool_boolean_arguments.py b/agent/tests/test_tool_boolean_arguments.pynew file mode 100644index 000000000..de0512613--- /dev/null+++ b/agent/tests/test_tool_boolean_arguments.py@@ -0,0 +1,35 @@+"""Boolean strings never silently turn ambiguous action flags into writes."""++import json++import pytest++from src.tools._arguments import boolean_argument+from src.tools.trading_connector_tool import EtoroEditPositionStopsTool++[email protected]("value", [False, None, 0, 0.0, "false", " False ", "0", "no", "OFF"])+def test_false_values(value):+ assert boolean_argument(value, field="flag") is False++[email protected]("value", [True, 1, 1.0, "true", " True ", "1", "yes", "ON"])+def test_true_values(value):+ assert boolean_argument(value, field="flag") is True++[email protected]("value", ["", "maybe", "flase", 2, -1, [], {}, float("nan")])+def test_ambiguous_values_are_errors(value):+ with pytest.raises(ValueError, match="dry_run must be a boolean"):+ boolean_argument(value, field="dry_run")++[email protected]("field", ["clear_stop_loss", "clear_take_profit", "trailing_stop_loss"])+def test_invalid_stop_flag_cannot_call_the_broker(monkeypatch, field):+ def forbidden(*args, **kwargs):+ pytest.fail("Invalid flag reached the broker service")++ monkeypatch.setattr("src.tools.trading_connector_tool.edit_position_stops", forbidden)+ result = json.loads(EtoroEditPositionStopsTool().execute(position_id="123", **{field: "maybe"}))+ assert result["status"] == "error"+ assert field in result["error"]diff --git a/agent/tests/test_trading_history_tool_flags.py b/agent/tests/test_trading_history_tool_flags.pynew file mode 100644index 000000000..73bf99219--- /dev/null+++ b/agent/tests/test_trading_history_tool_flags.py@@ -0,0 +1,36 @@+"""trading_history reads a JSON-string use_rth flag by its value."""++from __future__ import annotations++import json+from typing import Any++import pytest++import src.tools.trading_connector_tool as tool_mod+++def seen(monkeypatch: pytest.MonkeyPatch) -> list[bool]:+ calls: list[bool] = []++ def fake_get_history(_symbol: str, _conn: Any, *, use_rth: bool, **_kw: Any) -> dict:+ calls.append(use_rth)+ return {"status": "ok", "bars": []}++ monkeypatch.setattr(tool_mod, "_connection", lambda name: name)+ monkeypatch.setattr(tool_mod, "get_history", fake_get_history)+ return calls++[email protected]("flag", ["false", "False", "0", "no"])+def test_string_false_requests_all_sessions(seen: list[bool], flag: str) -> None:+ out = json.loads(tool_mod.TradingHistoryTool().execute(symbol="AAPL", use_rth=flag))+ assert out["status"] == "ok"+ assert seen == [False]++[email protected]("kwargs", [{}, {"use_rth": "true"}, {"use_rth": True}])+def test_default_and_true_keep_regular_hours(seen: list[bool], kwargs: dict) -> None:+ tool_mod.TradingHistoryTool().execute(symbol="AAPL", **kwargs)+ assert seen == [True]diff --git a/agent/tests/test_trading_orders_tool_flags.py b/agent/tests/test_trading_orders_tool_flags.pynew file mode 100644index 000000000..bf6950122--- /dev/null+++ b/agent/tests/test_trading_orders_tool_flags.py@@ -0,0 +1,40 @@+"""trading_orders reads a JSON-string include_executions flag by its value."""++from __future__ import annotations++import json+from typing import Any++import pytest++import src.tools.trading_connector_tool as tool_mod+++def seen(monkeypatch: pytest.MonkeyPatch) -> list[bool]:+ calls: list[bool] = []++ def fake_get_open_orders(_conn: Any, *, include_executions: bool, **_kw: Any) -> dict:+ calls.append(include_executions)+ return {"status": "ok", "orders": []}++ monkeypatch.setattr(tool_mod, "_connection", lambda name: name)+ monkeypatch.setattr(tool_mod, "get_open_orders", fake_get_open_orders)+ return calls++[email protected]("flag", ["false", "False", "0", "no", ""])+def test_string_false_does_not_request_executions(seen: list[bool], flag: str) -> None:+ out = json.loads(tool_mod.TradingOrdersTool().execute(include_executions=flag))+ if flag == "":+ assert out["status"] == "error"+ assert seen == []+ return+ assert out["status"] == "ok"+ assert seen == [False]++[email protected]("flag", ["true", True])+def test_true_requests_executions(seen: list[bool], flag: Any) -> None:+ tool_mod.TradingOrdersTool().execute(include_executions=flag)+ assert seen == [True]diff --git a/agent/tests/test_web_reader_privacy.py b/agent/tests/test_web_reader_privacy.pyindex 672edb2f1..6303fdd2f 100644--- a/agent/tests/test_web_reader_privacy.py+++ b/agent/tests/test_web_reader_privacy.py@@ -75,3 +75,11 @@ def test_no_cache_header_opt_in_only(captured):assert "x-no-cache" not in {k.lower() for k in captured["headers"]}read_url(URL, no_cache=True)assert captured["headers"].get("x-no-cache") == "true"++[email protected]("flag", ["false", "False", "0", "no"])+def test_string_false_no_cache_does_not_bypass_the_cache(captured, flag):+ """A JSON-string "false" must not be read as truthy and skip the cache."""+ captured["resp"] = _Resp(200, "Title: X\n\nbody")+ wr.WebReaderTool().execute(url=URL, no_cache=flag)+ assert "x-no-cache" not in {k.lower() for k in captured["headers"]}