"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(grounding): only the engine's own output grounds a backtest report
cgycorey381063dea8c7
diff --git a/agent/src/agent/grounding/evidence.py b/agent/src/agent/grounding/evidence.pyindex cd1012f9c..49e87a1e2 100644--- a/agent/src/agent/grounding/evidence.py+++ b/agent/src/agent/grounding/evidence.py@@ -363,21 +363,6 @@ _CLAIM_DATE_RE = re.compile()-def _claim_date_tuple(date_value: str) -> tuple[int, int] | None:- """Extract the (month, day) a report-style date cell names.-- Args:- date_value: Date cell as written in the answer, e.g. ``08-10(周一)``.-- Returns:- The (month, day) tuple, or None when no date prefix is present.- """- match = _CLAIM_DATE_RE.match((date_value or "").strip())- if match is None:- return None- return (int(match.group(2)), int(match.group(3)))--def _timestamp_matches_claim_date(timestamp: str, date_value: str) -> bool:"""Match an evidence timestamp against the date cell of a claim.@@ -398,15 +383,17 @@ def _timestamp_matches_claim_date(timestamp: str, date_value: str) -> bool:return Falseif stamp.startswith(claim):return True- claim_tuple = _claim_date_tuple(claim)+ match = _CLAIM_DATE_RE.match(claim)parts = stamp[:10].split("-")- if claim_tuple is None or len(parts) != 3:+ if match is None or len(parts) != 3:return Falsetry:- stamp_tuple = (int(parts[1]), int(parts[2]))+ stamp_year, stamp_month, stamp_day = map(int, parts)except ValueError:return False- return stamp_tuple == claim_tuple+ if match.group(1) is not None and stamp_year != int(match.group(1)):+ return False+ return (stamp_month, stamp_day) == (int(match.group(2)), int(match.group(3)))def _leaf_name(path: str) -> str:@@ -716,11 +703,12 @@ class _EvidenceMixin:root = self.run_dir.resolve()candidates: list[Path] = []own_dir: Path | None = None+ declared_name: str | None = Noneraw_dir = arguments.get("run_dir") or payload.get("run_dir")if raw_dir:- candidate = Path(str(raw_dir))- if not candidate.is_absolute():- candidate = self.run_dir / candidate+ declared = Path(str(raw_dir))+ declared_name = declared.name+ candidate = declared if declared.is_absolute() else self.run_dir / declaredtry:resolved = candidate.resolve()if resolved == root or resolved.is_relative_to(root):@@ -729,8 +717,22 @@ class _EvidenceMixin:except OSError:pass# The loop archives a detached backtest's artifacts into the active run- # dir right after it succeeds, so that copy is the second candidate.+ # dir right after it succeeds, so that copy is the second candidate — but+ # only once the archive names the directory this call declared. A+ # detached backtest's own dir sits outside the active run, so there the+ # declared *name* is the only thing tying the archived copy to this call.candidates.append(root)+ archived = (+ declared_name is not None+ and own_dir != root+ and _archive_source(root) == declared_name+ )+ if declared_name is not None and own_dir != root and not archived:+ candidates = [+ item+ for item in candidates+ if own_dir is not None and item.is_relative_to(own_dir)+ ]artifacts = payload.get("artifacts")if isinstance(artifacts, dict):for path_value in artifacts.values():@@ -759,7 +761,7 @@ class _EvidenceMixin:recorded = 0seen_files: set[Path] = set()for file_path in files:- if file_path in seen_files:+ if file_path in seen_files or self._is_model_written(file_path):continueseen_files.add(file_path)recorded += self._record_metrics_file(file_path, call_id)@@ -771,7 +773,7 @@ class _EvidenceMixin:self._record_backtest_outputs(own_dir, call_id, scope)# The active run holds this backtest's copy only when the loop's# archive names it as the source; otherwise it is an earlier run's.- if own_dir != root and _archive_source(root) == own_dir.name:+ if archived:self._record_backtest_outputs(root, call_id, scope)return recordeddiff --git a/agent/src/agent/grounding/identity.py b/agent/src/agent/grounding/identity.pyindex 26857f90e..57e5932fb 100644--- a/agent/src/agent/grounding/identity.py+++ b/agent/src/agent/grounding/identity.py@@ -647,10 +647,32 @@ class _IdentityMixin:self._identity_required = Trueself._buffer_output = True+ def _hold_locked(self, existing: IdentityRecord | None) -> bool:+ """Whether a settled record must survive a non-conclusive resolver step.++ A repeat resolution that fails, is refused or comes back empty carries+ no evidence about the entity, and replacing the record would erase the+ contradiction anchor an earlier successful resolution established. A+ ``conflicting`` record is settled in the same sense: the anchor is the+ only record of which symbols disagreed.++ Args:+ existing: The record for this query key, if any.++ Returns:+ True when the caller must leave the record untouched.+ """+ if existing is not None and existing.status in {"locked", "conflicting"}:+ self.persist()+ return True+ return False+def _begin_resolution(self, query: str, call_id: str) -> None:"""Enter unresolved state before the resolver executes."""key = _query_key(query) or f"call:{call_id}"existing = self._identities.get(key)+ if self._hold_locked(existing):+ returnself._identities[key] = IdentityRecord(query=query,status="unresolved",@@ -668,6 +690,8 @@ class _IdentityMixin:query = str(arguments.get("query") or "")key = _query_key(query) or f"call:{call_id}"existing = self._identities.get(key)+ if self._hold_locked(existing):+ returnself._identities[key] = IdentityRecord(query=query,status="invalidated",@@ -690,6 +714,8 @@ class _IdentityMixin:version = (existing.version + 1) if existing else 1if not isinstance(payload, dict) or payload.get("ok") is False:+ if self._hold_locked(existing):+ returnself._identities[key] = IdentityRecord(query=query,status="invalidated",@@ -705,6 +731,8 @@ class _IdentityMixin:constraint_audit = [item.audit_record() for item in relevant_constraints]sources = data.get("sources") if isinstance(data.get("sources"), dict) else {}if not candidates:+ if self._hold_locked(existing):+ return# "This entity does not exist" may only be concluded when every# source that could answer did answer. Counting two clean sources# instead was unreachable for a Chinese query — Yahoo cannot serve@@ -817,6 +845,27 @@ class _IdentityMixin:)return+ if existing and existing.status == "conflicting":+ # Re-answering one side of a contradiction is not evidence that+ # settles it: the same query through the same resolver returns the+ # same opinion it did a moment ago, so promoting it to ``locked``+ # would drop the anchor and authorize a symbol the run had already+ # found contradicted. Only a different query (a new key, e.g. a+ # disambiguated name) can answer this.+ conflicting = list(candidates)+ for item in existing.candidates:+ if item not in conflicting:+ conflicting.append(item)+ self._identities[key] = IdentityRecord(+ query=query,+ status="conflicting",+ source_tool_call_id=call_id,+ candidates=conflicting,+ resolution_constraints=constraint_audit,+ version=version,+ )+ return+source_names = []for value in [chosen.get("source"), *(chosen.get("also_from") or [])]:name = str(value or "").strip()diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.pyindex 65e5d6b8c..9dfb80e6c 100644--- a/agent/tests/test_agent_grounding.py+++ b/agent/tests/test_agent_grounding.py@@ -197,6 +197,170 @@ def test_ok_false_tool_envelope_is_failure() -> None:assert _is_tool_success('{"ok": true, "data": {}}') is True+def test_re_resolving_same_query_cannot_overwrite_a_locked_symbol(+ tmp_path: Path,+) -> None:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="Analyze Acme")+ first = {+ "ok": True,+ "data": {+ "query": "Acme",+ "candidates": [{"symbol": "AAA.US", "name": "Acme", "market": "us", "source": "yahoo"}],+ },+ }+ second = {+ "ok": True,+ "data": {+ "query": "Acme",+ "candidates": [{"symbol": "BBB.US", "name": "Acme", "market": "us", "source": "yahoo"}],+ },+ }++ ledger.ingest_tool_result(+ tool_name="search_symbol", arguments={"query": "Acme"},+ result=json.dumps(first), call_id="resolve-a", success=True,+ )+ assert ledger.authorized_symbols == {"AAA.US"}+ ledger.authorize_tool_call(+ "search_symbol", {"query": "Acme"},+ batch_authorized_symbols=ledger.authorized_symbols, call_id="resolve-b",+ )+ ledger.ingest_tool_result(+ tool_name="search_symbol", arguments={"query": "Acme"},+ result=json.dumps(second), call_id="resolve-b", success=True,+ )++ assert ledger.identity_status == "conflicting"+ assert ledger.authorized_symbols == set()+++def _resolve_candidate(+ ledger: GroundingLedger, symbol: str, query: str, call_id: str+) -> None:+ """Drive one ``search_symbol`` resolution for ``query`` through the ledger."""+ ledger.authorize_tool_call(+ "search_symbol",+ {"query": query},+ batch_authorized_symbols=ledger.authorized_symbols,+ call_id=call_id,+ )+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": query},+ result=json.dumps(+ {+ "ok": True,+ "data": {+ "query": query,+ "candidates": [+ {+ "symbol": symbol,+ "name": query,+ "market": "us",+ "source": "yahoo",+ }+ ],+ },+ }+ ),+ call_id=call_id,+ success=True,+ )+++def test_a_repeat_resolution_cannot_clear_a_conflict(tmp_path: Path) -> None:+ """Re-answering one side of a contradiction is not evidence that settles it."""+ ledger = GroundingLedger(run_dir=tmp_path, user_message="Analyze Acme")+ _resolve_candidate(ledger, "AAA.US", "Acme", "resolve-a")+ _resolve_candidate(ledger, "BBB.US", "Acme", "resolve-b")+ assert ledger.identity_status == "conflicting"++ _resolve_candidate(ledger, "BBB.US", "Acme", "resolve-c")++ assert ledger.identity_status == "conflicting"+ assert ledger.authorized_symbols == set()+++def test_a_non_conclusive_step_cannot_clear_a_conflict(tmp_path: Path) -> None:+ """A timeout after a contradiction leaves the contradiction standing."""+ ledger = GroundingLedger(run_dir=tmp_path, user_message="Analyze Acme")+ _resolve_candidate(ledger, "AAA.US", "Acme", "resolve-a")+ _resolve_candidate(ledger, "BBB.US", "Acme", "resolve-b")+ assert ledger.identity_status == "conflicting"+ ledger.authorize_tool_call(+ "search_symbol",+ {"query": "Acme"},+ batch_authorized_symbols=ledger.authorized_symbols,+ call_id="resolve-timeout",+ )+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "Acme"},+ result=json.dumps({"ok": False, "error": "timeout"}),+ call_id="resolve-timeout",+ success=False,+ )++ assert ledger.identity_status == "conflicting"+++ ("payload", "success", "call_id"),+ [+ ({"ok": False, "error": "timeout"}, False, "resolve-flaky"),+ ({"ok": False, "error": "rate limited"}, True, "resolve-refused"),+ (+ {+ "ok": True,+ "source": "symbol_search",+ "data": {"query": "Acme", "count": 0, "candidates": []},+ },+ True,+ "resolve-empty",+ ),+ ],+)+def test_a_non_conclusive_re_resolution_cannot_retract_a_locked_symbol(+ tmp_path: Path, payload: dict[str, Any], success: bool, call_id: str+) -> None:+ """A timeout, a refusal or an empty list is not evidence against the lock."""+ ledger = GroundingLedger(run_dir=tmp_path, user_message="Analyze Acme")+ resolved = {+ "ok": True,+ "data": {+ "query": "Acme",+ "candidates": [+ {"symbol": "AAA.US", "name": "Acme", "market": "us", "source": "yahoo"}+ ],+ },+ }+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "Acme"},+ result=json.dumps(resolved),+ call_id="resolve-locked",+ success=True,+ )+ assert ledger.authorized_symbols == {"AAA.US"}++ ledger.authorize_tool_call(+ "search_symbol",+ {"query": "Acme"},+ batch_authorized_symbols=ledger.authorized_symbols,+ call_id=call_id,+ )+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "Acme"},+ result=json.dumps(payload),+ call_id=call_id,+ success=success,+ )++ assert ledger.identity_status == "locked"+ assert ledger.authorized_symbols == {"AAA.US"}++def test_resolver_and_consumer_in_same_batch_cannot_race(tmp_path: Path,) -> None:@@ -980,6 +1144,8 @@ def test_weekday_suffixed_claim_dates_match_evidence() -> None:assert _timestamp_matches_claim_date("2026-08-10T00:00:00", "08-10") is Trueassert _timestamp_matches_claim_date("2026-08-10T00:00:00", "2026-08-10") is Trueassert _timestamp_matches_claim_date("2026-08-10T00:00:00", "2026-08-10(一)") is True+ assert _timestamp_matches_claim_date("2026-08-10T00:00:00", "2025-08-10") is False+ assert _timestamp_matches_claim_date("2026-08-10T00:00:00", "2025-08-10(一)") is Falseassert _timestamp_matches_claim_date("2026-08-10T00:00:00", "08-11") is Falseassert _timestamp_matches_claim_date("2026-08-10T00:00:00", "no-date") is Falsediff --git a/agent/tests/test_grounding_backtest_outputs.py b/agent/tests/test_grounding_backtest_outputs.pyindex ff7a68564..7da1effb9 100644--- a/agent/tests/test_grounding_backtest_outputs.py+++ b/agent/tests/test_grounding_backtest_outputs.py@@ -297,6 +297,28 @@ def test_a_table_grounds_only_the_rows_the_model_was_shown(two_runs: GroundingLeassert not two_runs.validate_final_answer(unseen).valid+def test_model_written_metrics_are_not_backtest_evidence(tmp_path: Path) -> None:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="回测风险平价")+ run_dir = tmp_path / "rp"+ _write_backtest(run_dir, RP)+ _backtest(ledger, run_dir, "bt-rp")+ metrics = run_dir / "artifacts" / "metrics.csv"+ metrics.write_text("sharpe\n0.693563\n", encoding="utf-8")+ ledger.ingest_tool_result(+ tool_name="write_file",+ arguments={"path": str(metrics)},+ result=json.dumps({"status": "ok", "path": str(metrics)}),+ call_id="model-write-metrics",+ success=True,+ )+ _backtest(ledger, run_dir, "bt-after-write")++ assert not any(+ row.get("metric") == "sharpe" and row.get("call_id") == "bt-after-write"+ for row in ledger._analysis_metrics+ )++def test_a_file_the_model_wrote_is_never_engine_output(tmp_path: Path) -> None:"""Neither a table written before the backtest nor one edited after it."""ledger = GroundingLedger(run_dir=tmp_path, user_message="回测风险平价")@@ -342,6 +364,75 @@ def test_a_summary_file_the_run_card_does_not_vouch_for_is_ignored(tmp_path: Patassert vouched.valid, vouched.issues+def test_stale_active_metrics_are_not_attributed_to_a_detached_backtest(tmp_path: Path) -> None:+ """The active run's metrics file is an earlier run's until the archive names this one."""+ ledger = GroundingLedger(run_dir=tmp_path, user_message="回测")+ _write_backtest(tmp_path, EW)+ _write_backtest(tmp_path / "rp", RP)++ _backtest(ledger, tmp_path / "rp", "bt-rp")++ recorded = [+ item["value"] for item in ledger._analysis_metrics if item.get("call_id") == "bt-rp"+ ]+ assert RP["sharpe"] in recorded+ assert EW["sharpe"] not in recorded+++def test_a_detached_backtest_cannot_inherit_the_active_runs_copy(tmp_path: Path) -> None:+ """A run dir outside the active run has no claim on what that dir holds.++ The tool declares a run_dir elsewhere on disk while the active run dir+ happens to hold an earlier run's metrics; the manifest names that earlier+ run, so none of its figures were produced by this call.+ """+ active = tmp_path / "active"+ active.mkdir(parents=True)+ _write_backtest(active, EW)+ (active / ARCHIVE_MANIFEST).write_text(+ json.dumps({"source_run": "an-earlier-run"}), encoding="utf-8"+ )+ detached = tmp_path / "detached-bt"+ _write_backtest(detached, RP)+ ledger = GroundingLedger(run_dir=active, user_message="回测")++ _backtest(ledger, detached, "bt-detached")++ recorded = [+ item["value"]+ for item in ledger._analysis_metrics+ if item.get("call_id") == "bt-detached"+ ]+ assert EW["sharpe"] not in recorded+ assert EW["total_return"] not in recorded+++def test_a_detached_backtests_archived_copy_counts_once_vouched_for(tmp_path: Path) -> None:+ """The loop's archive into the active run counts once the manifest names the source."""+ active = tmp_path / "active"+ active.mkdir(parents=True)+ detached = tmp_path / "detached-bt"+ _write_backtest(detached, RP)+ for name in ("metrics.csv", "risk_xray.json", "validation.json"):+ target = active / "artifacts" / name+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes((detached / "artifacts" / name).read_bytes())+ (active / "run_card.json").write_bytes((detached / "run_card.json").read_bytes())+ (active / ARCHIVE_MANIFEST).write_text(+ json.dumps({"source_run": detached.name}), encoding="utf-8"+ )+ ledger = GroundingLedger(run_dir=active, user_message="回测")++ _backtest(ledger, detached, "bt-detached")++ recorded = [+ item["value"]+ for item in ledger._analysis_metrics+ if item.get("call_id") == "bt-detached"+ ]+ assert RP["sharpe"] in recorded++def test_the_active_runs_copy_belongs_to_the_backtest_the_archive_names(tmp_path: Path) -> None:"""The loop copies each finished backtest into the active run; a ref to thatcopy names the backtest it came from, and only once it has come."""