"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: finish numeric boundaries, replay coverage and Trigger inheritance
Haozhe Wud0ef98a60602
diff --git a/agent/src/live/runtime/triggers.py b/agent/src/live/runtime/triggers.pyindex 8582a9fb7..4279870cd 100644--- a/agent/src/live/runtime/triggers.py+++ b/agent/src/live/runtime/triggers.py@@ -229,7 +229,9 @@ class Trigger:# reordering the two names only moves the damage (the field default becomes the# method, or the factory becomes ``None``), and an explicit# ``field(default=None)`` is overwritten the same way.-Trigger.market = Trigger._market # type: ignore[assignment]+# Keep the descriptor, not a method already bound to Trigger: subclasses must+# receive their own ``cls`` just as they do through ``interval`` and ``event``.+Trigger.market = classmethod(Trigger._market.__func__) # type: ignore[assignment]del Trigger._market# Introspection must not leak the private placeholder: ``help()`` and ``repr``# read ``__qualname__``, while ``str()`` and logging read ``__name__``.diff --git a/agent/src/tools/financial_rigor_tool.py b/agent/src/tools/financial_rigor_tool.pyindex a2632cce5..b540308b8 100644--- a/agent/src/tools/financial_rigor_tool.py+++ b/agent/src/tools/financial_rigor_tool.py@@ -296,16 +296,11 @@ def benford_check(values: list[Any]) -> dict[str, Any]:"""digits: list[int] = []for raw in values:- v = abs(float(raw))- if v > 0 and math.isfinite(v):- sig = 10 ** (math.log10(v) - math.floor(math.log10(v)))- # sig is mathematically in [1, 10), but float round-trip through- # log10/pow can land a hair under an integer boundary (e.g. sig- # == 4.999999999999999 for v == 5000), so a bare int() truncates- # to the digit below. Round first, then clamp the 10 -> 9 edge.- d = int(round(sig, 9))- d = min(9, max(1, d))- digits.append(d)+ # Decimal construction preserves the supplied digits without a float+ # round-trip or context rounding at a leading-digit boundary.+ value = Decimal(int(raw)) if isinstance(raw, bool) else Decimal(str(raw))+ if value.is_finite() and not value.is_zero():+ digits.append(value.as_tuple().digits[0])n = len(digits)if n < 50:return {diff --git a/agent/tests/test_dataclass_field_name_collisions.py b/agent/tests/test_dataclass_field_name_collisions.pyindex 3480568df..fb5d6d7ba 100644--- a/agent/tests/test_dataclass_field_name_collisions.py+++ b/agent/tests/test_dataclass_field_name_collisions.py@@ -42,8 +42,8 @@ too (it simply has no ``field(default_factory=...)`` spelling). The gatetherefore covers both class kinds.Remediation note: the worked example binds the factory after the class body.-For a ``slots=True`` dataclass that rebinding is blocked by ``__slots__`` on-Python <= 3.13, so rename the member instead.+For a ``slots=True`` dataclass that rebinding replaces the slot descriptor and+breaks instance assignment, so rename the member instead."""from __future__ import annotations@@ -61,10 +61,10 @@ EXCLUDED_DIRS = (REPO_ROOT / "agent" / "tests",)def _is_dataclass(node: ast.ClassDef) -> bool:"""True when the class carries a ``@dataclass`` decorator (any spelling)."""for decorator in node.decorator_list:- text = ast.unparse(decorator)- if text == "dataclass" or text.startswith("dataclass("):+ target = decorator.func if isinstance(decorator, ast.Call) else decorator+ if isinstance(target, ast.Name) and target.id == "dataclass":return True- if text.endswith(".dataclass") or ".dataclass(" in text:+ if isinstance(target, ast.Attribute) and target.attr == "dataclass":return Truereturn False@@ -78,19 +78,19 @@ def _is_namedtuple(node: ast.ClassDef) -> bool:return False-def _class_body_bindings(node: ast.ClassDef) -> list[tuple[str, int, str]]:+def _class_body_bindings(node: ast.ClassDef) -> list[tuple[str, ast.stmt, str]]:"""Every class-body statement that binds a bare name, in body order."""- bindings: list[tuple[str, int, str]] = []+ bindings: list[tuple[str, ast.stmt, str]] = []for stmt in node.body:if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)):- bindings.append((stmt.name, stmt.lineno, f"def {stmt.name}"))+ bindings.append((stmt.name, stmt, f"def {stmt.name}"))elif isinstance(stmt, ast.AnnAssign):if isinstance(stmt.target, ast.Name) and stmt.value is not None:- bindings.append((stmt.target.id, stmt.lineno, f"{stmt.target.id} = <value>"))+ bindings.append((stmt.target.id, stmt, f"{stmt.target.id} = <value>"))elif isinstance(stmt, ast.Assign):for target in stmt.targets:if isinstance(target, ast.Name):- bindings.append((target.id, stmt.lineno, f"{target.id} = <value>"))+ bindings.append((target.id, stmt, f"{target.id} = <value>"))return bindings@@ -100,6 +100,11 @@ def _is_classvar(annotation: ast.expr) -> bool:Aliased imports (``from typing import ClassVar as CV``) are not resolved;the tree does not use them, and a miss there is merely a false positive."""+ if isinstance(annotation, ast.Constant) and isinstance(annotation.value, str):+ try:+ annotation = ast.parse(annotation.value, mode="eval").body+ except SyntaxError:+ return Falsebase = ast.unparse(annotation).split("[", 1)[0]return base in {"ClassVar", "typing.ClassVar", "typing_extensions.ClassVar"}@@ -111,7 +116,7 @@ def _collisions(tree: ast.Module) -> list[str]:if not isinstance(node, ast.ClassDef) or not (_is_dataclass(node) or _is_namedtuple(node)):continue- annotated: dict[str, int] = {}+ annotated: dict[str, ast.AnnAssign] = {}for stmt in node.body:if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):if _is_classvar(stmt.annotation):@@ -120,25 +125,26 @@ def _collisions(tree: ast.Module) -> list[str]:# same-named binding cannot corrupt anything. Flagging it# would be a false positive on a legitimate pattern.continue- annotated[stmt.target.id] = stmt.lineno+ annotated[stmt.target.id] = stmtbindings = _class_body_bindings(node)- for field_name, field_line in annotated.items():- same_name = [(line, text) for name, line, text in bindings if name == field_name]+ for field_name, field_stmt in annotated.items():+ same_name = [(stmt, text) for name, stmt, text in bindings if name == field_name]if not same_name:- continue # the annotation's own assignment is the only binding- last_line, last_text = same_name[-1]- owns_last_binding = last_line == field_line and last_text.startswith(f"{field_name} = ")- if owns_last_binding:+ continue # the field has no default and no same-named binding+ last_stmt, last_text = same_name[-1]+ # Two assignments can occupy one source line; only the actual+ # annotated statement owns the declared field default.+ if last_stmt is field_stmt:continueshape = ("required field silently becomes optional"- if not any(line == field_line for line, _ in same_name)+ if field_stmt.value is Noneelse "field default silently replaced")found.append(- f"{node.name}.{field_name} (field line {field_line}) is shadowed by "- f"`{last_text}` on line {last_line}: {shape}"+ f"{node.name}.{field_name} (field line {field_stmt.lineno}) is shadowed by "+ f"`{last_text}` on line {last_stmt.lineno}: {shape}")return found@@ -282,6 +288,39 @@ class Fine:assert failures == []+def test_quoted_classvar_shadowing_is_not_flagged() -> None:+ failures = _collisions_in(+ '''+from dataclasses import dataclass+from typing import ClassVar+import typing++@dataclass+class Fine:+ registry: "ClassVar[dict]" = {}+ other: "typing.ClassVar[dict]" = {}++ def registry(self):+ return None++ def other(self):+ return None+'''+ )+ assert failures == []+++def test_same_line_overwrite_is_flagged() -> None:+ for declaration, shape in (+ ("value: int = 1; value = 2", "field default silently replaced"),+ ("value: int; value = 2", "required field silently becomes optional"),+ ):+ failures = _collisions_in(f"@dataclass\nclass Broken:\n {declaration}\n")+ assert len(failures) == 1+ assert "Broken.value" in failures[0]+ assert shape in failures[0]++def test_mirror_image_shape_stays_out_of_scope() -> None:"""Member first, field second: the default wins and the member breaks loudly."""failures = _collisions_in(@@ -316,3 +355,13 @@ class Fine:""")assert failures == []+++def test_unrelated_decorator_argument_is_not_a_dataclass_decorator() -> None:+ assert _collisions_in("""+@identity(dataclasses.dataclass())+class Ordinary:+ field: int = 1+ def field(self):+ return 2+""") == []diff --git a/agent/tests/test_financial_rigor_tool.py b/agent/tests/test_financial_rigor_tool.pyindex a100fdff9..9da19e57e 100644--- a/agent/tests/test_financial_rigor_tool.py+++ b/agent/tests/test_financial_rigor_tool.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport jsonimport math+from decimal import Decimalfrom typing import Anyimport pytest@@ -276,3 +277,26 @@ def test_execute_three_scenario_validates_growth_shape() -> None:growth=[0.1, 0.2], pe=[25, 20, 15], # growth has only 2 entries)assert env["status"] == "error"++[email protected]("value, digit", [+ (4999.9999999, 4), (1999.9999999, 1),+ (math.nextafter(5000.0, 0.0), 4), (math.nextafter(5000.0, math.inf), 5),+ (math.nextafter(1.0, 0.0), 9), (math.nextafter(1.0, math.inf), 1),+ (-5000, 5), (-0.0049999999999, 4), (5e-324, 5),+ ("4.999999999999999999999999999999999999999", 4),+ (Decimal("-9.999999999999999999999999999999999999999"), 9),+ ("5e-1000", 5), (10**400 * 7, 7),+])+def test_benford_preserves_leading_digit_without_rounding(value, digit):+ result = benford_check([value] * 50)+ assert result["sample_size"] == 50+ counts = {row["digit"]: row["observed"] for row in result["distribution"]}+ assert counts[digit] == 1.0+ assert sum(counts.values()) == 1.0+++def test_benford_ignores_zero_and_nonfinite_values():+ result = benford_check([0, -0.0, float("nan"), float("inf"), -float("inf")] + [5] * 50)+ assert result["sample_size"] == 50+ assert result["distribution"][4]["observed"] == 1.0diff --git a/agent/tests/test_grounding_generic_timestamps.py b/agent/tests/test_grounding_generic_timestamps.pyindex 4d0434b2a..397096847 100644--- a/agent/tests/test_grounding_generic_timestamps.py+++ b/agent/tests/test_grounding_generic_timestamps.py@@ -155,3 +155,22 @@ def test_generic_latest_date_beats_as_of_but_local_date_wins(tmp_path: Path) ->assert timestamp_by_field["snapshot.close"] == "2026-08-04"assert timestamp_by_field["rows[0].close"] == "2026-08-03"assert timestamp_by_field["rows[1].close"] == "2026-08-04"++[email protected]("timestamps, expected", [+ ({"latest_date": None, "as_of": "2026-08-05"}, "2026-08-05"),+ ({"latest_date": "2026-08-04", "as_of": "2026-08-05"}, "2026-08-04"),+ ({"date": "2026-08-03", "latest_date": "2026-08-04"}, "2026-08-03"),+ ({"latest_date": None}, None),+ ({}, None),+])+def test_latest_date_preserves_timestamp_priority_and_absence(tmp_path, timestamps, expected):+ ledger = _ledger(tmp_path, {**timestamps, "snapshot": {"close": 212.5}})+ evidence = json.loads((tmp_path / "artifacts" / "grounding_evidence.json").read_text())+ record = next(row for row in evidence["evidence"] if row["field"] == "snapshot.close")+ assert record["timestamp"] == expected+ answer = f"| Date | Close |\n|---|---|\n| {expected or '2026-08-04'} | 212.5 |"+ assert ledger.validate_final_answer(answer).valid is (expected is not None)+ assert not ledger.validate_final_answer(+ "| Date | Close |\n|---|---|\n| 2020-01-01 | 212.5 |"+ ).validdiff --git a/agent/tests/test_runtime_triggers.py b/agent/tests/test_runtime_triggers.pyindex 39d2f6308..067ce7b48 100644--- a/agent/tests/test_runtime_triggers.py+++ b/agent/tests/test_runtime_triggers.py@@ -180,6 +180,26 @@ def test_market_field_default_and_factory_are_both_intact() -> None:assert not hasattr(Trigger, "_market")[email protected]("decorate", [False, True])+def test_market_factory_binds_to_subclass(decorate: bool) -> None:+ """The deferred factory must retain normal classmethod inheritance."""+ class DerivedTrigger(Trigger):+ pass++ if decorate:+ DerivedTrigger = dataclasses.dataclass(frozen=True)(DerivedTrigger)++ trigger = DerivedTrigger.market("crypto")+ assert type(trigger) is DerivedTrigger+ assert DerivedTrigger.market.__self__ is DerivedTrigger+ assert trigger.kind is TriggerKind.MARKET+ assert trigger.market == "crypto"+ assert DerivedTrigger.interval(1).market is None+ assert DerivedTrigger.event(lambda _state: True).market is None+ assert dataclasses.replace(trigger).market == "crypto"+ assert json.loads(json.dumps(dataclasses.asdict(trigger)))["market"] == "crypto"++# --------------------------------------------------------------------------- ## due_now — INTERVAL ## --------------------------------------------------------------------------- #diff --git a/agent/tests/test_technical_indicator_compaction_replay.py b/agent/tests/test_technical_indicator_compaction_replay.pyindex 3d1655cfd..185c98be2 100644--- a/agent/tests/test_technical_indicator_compaction_replay.py+++ b/agent/tests/test_technical_indicator_compaction_replay.py@@ -1,5 +1,13 @@from __future__ import annotations+import json+from types import SimpleNamespace++import pandas as pd+import pytest++from tests.test_readonly_replay_after_microcompact import _Context, _Registry, _Trace, _loop+from src.agent.grounding import GroundingLedgerfrom src.agent.loop import AgentLoopfrom src.tools.technical_indicator_tool import TechnicalIndicatorTool@@ -26,3 +34,56 @@ def test_technical_indicators_opt_into_readonly_compaction_replay() -> None:)is True)++[email protected]("refresh_args", [{"no_cache": True}, {"lookback": 100}])+def test_indicator_replay_preserves_dated_evidence_and_refreshes(monkeypatch, tmp_path, refresh_args):+ calls = []+ frame = pd.DataFrame(+ {"close": [100.0 + i for i in range(60)], "volume": [1000.0] * 60},+ index=pd.date_range("2026-06-01", periods=60),+ )++ def fetch(**kwargs):+ calls.append(kwargs)+ return {"AAPL.US": frame}++ monkeypatch.setattr("src.tools.technical_indicator_tool.fetch_market_data", fetch)+ registry = _Registry()+ registry.tool = TechnicalIndicatorTool()+ registry.execute = lambda name, args: registry.tool.execute(**args)+ loop = _loop(registry)+ args = {"symbol": "AAPL.US", "interval": "1d", "lookback": 200}+ messages, trace = [], _Trace()++ def run(arguments, number):+ call = SimpleNamespace(name="technical_indicators", arguments=arguments, id=f"call-{number}")+ loop._process_tool_calls([call], _Context(), messages, trace, [], number)+ return json.loads(messages[-1]["content"])++ original = run(args, 1)+ assert original["ok"] is True+ assert len(calls) == 1+ key = loop._identical_call_key("technical_indicators", args)+ messages.clear() # Compaction discarded the tool result.+ assert loop._unblock_lost_readonly_results(messages, {key}) == ["technical_indicators"]+ restored = run(args, 2)+ assert len(calls) == 1+ assert restored["_vibe_replay"]["restored"] is True+ assert restored["latest_date"] == original["latest_date"]+ assert restored["indicators"] == original["indicators"]++ ledger = GroundingLedger(run_dir=tmp_path, user_message="Show AAPL.US prices by date")+ ledger.ingest_tool_result(tool_name="technical_indicators", arguments=args,+ result=json.dumps(restored), call_id="call-2", success=True)+ evidence = json.loads((tmp_path / "artifacts" / "grounding_evidence.json").read_text())+ prices = [row for row in evidence["evidence"] if row["field"] == "latest_close"]+ assert len(prices) == 1+ assert prices[0]["timestamp"] == original["latest_date"]+ assert prices[0]["value"] == 159.0+ assert ledger.validate_final_answer("The latest observed price is 159.0.").valid++ fresh = run({**args, **refresh_args}, 3)+ assert fresh["ok"] is True+ assert "_vibe_replay" not in fresh+ assert len(calls) == 2