"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(strategy-store): stop the adapted child inheriting an attestation, and put the evidence gate on the write path
Haozhe Wua7bd2e309080
diff --git a/agent/src/strategy_store/adaptation.py b/agent/src/strategy_store/adaptation.pyindex ae112f738..508649ee5 100644--- a/agent/src/strategy_store/adaptation.py+++ b/agent/src/strategy_store/adaptation.py@@ -3,7 +3,8 @@from __future__ import annotationsfrom dataclasses import dataclass, replace-from typing import Protocol+from datetime import date+from typing import TYPE_CHECKING, Protocol, Sequencefrom src.strategy_store.models import (Artifact,@@ -12,6 +13,9 @@ from src.strategy_store.models import (ValidationStatus,)+if TYPE_CHECKING: # pragma: no cover - import cycle guard, see register_adaptation+ from src.strategy_discovery.models import EvidenceRow+class AdaptationError(ValueError):"""Raised when a parent cannot be adapted under the Phase 3 contract."""@@ -49,6 +53,21 @@ def adapt_artifact(parent: Artifact, patch: AdaptationPatch) -> Artifact:new_sizing = (patch.position_sizing if patch.position_sizing is not None else parent.position_sizing)+ # ``replace`` copies every field not named here, so the governance block+ # (models.py: "who built it, who owns it, who independently validated it,+ # who signed off, at what version") has to be split deliberately.+ #+ # ``developer`` / ``owner`` carry forward: the same team owns the derived+ # strategy. ``model_tier`` / ``intended_use`` / ``limitations`` describe+ # what the signal is for, which adaptation does not change.+ #+ # ``validator`` / ``approver`` do NOT. They name people who attested to+ # *this* artifact, and the child is UNVALIDATED with no run behind it —+ # carrying their names is the parent's attestation worn by something that+ # never earned it, the same inherited-provenance rule that keeps evidence+ # off the child. ``artifact_version`` / ``model_version`` go with them:+ # the child is version 1 of its own lineage, and no model has generated+ # its code yet (``run_dir`` is None until its own backtest runs).return replace(parent,id="",@@ -62,17 +81,56 @@ def adapt_artifact(parent: Artifact, patch: AdaptationPatch) -> Artifact:updated_at="",disabled_at=None,disabled_reason=None,+ validator=None,+ approver=None,+ artifact_version=None,+ model_version=None,validation_status=ValidationStatus.UNVALIDATED,validation_date=None,)def register_adaptation(- store: _ArtifactStore, parent_id: str, patch: AdaptationPatch+ store: _ArtifactStore,+ parent_id: str,+ patch: AdaptationPatch,+ *,+ parent_evidence: "Sequence[EvidenceRow]",+ today: date,) -> str:- """Persist an adapted child through the strategy store. Returns the new id."""+ """Persist an adapted child through the strategy store. Returns the new id.++ ``parent_evidence`` and ``today`` are keyword-only and required so the+ Phase 3 evidence gate cannot be skipped by forgetting to call it: the+ function will not run without the inputs the gate needs. Pass the rows+ the facade's ``get_strategy_evidence`` returned for *parent_id*; an empty+ sequence is a refusal, not a bypass.++ Args:+ store: Artifact store to read the parent from and write the child to.+ parent_id: Identifier of the strategy being adapted.+ patch: Description-driven changes; signal fields are not on this type.+ parent_evidence: Evidence rows computed for *parent_id*.+ today: Reference date the decay verdict is taken against.++ Returns:+ The new child artifact's id.++ Raises:+ AdaptationError: if the parent is missing, is not adaptable, or has+ no adequate, non-stale evidence row.+ """+ from src.strategy_discovery.adaptation import parent_adaptation_blockers+parent = store.get_artifact(parent_id)if parent is None:raise AdaptationError(f"parent artifact {parent_id!r} not found")++ blockers = parent_adaptation_blockers(parent_evidence, today)+ if blockers:+ raise AdaptationError(+ f"parent artifact {parent_id!r} cannot be adapted: " + "; ".join(blockers)+ )+child = adapt_artifact(parent, patch)return store.register_artifact(child)diff --git a/agent/tests/test_strategy_store_adaptation.py b/agent/tests/test_strategy_store_adaptation.pyindex e88a723d9..260e2f63c 100644--- a/agent/tests/test_strategy_store_adaptation.py+++ b/agent/tests/test_strategy_store_adaptation.py@@ -2,6 +2,8 @@from __future__ import annotations+from datetime import date, timedelta+import pytestfrom src.strategy_store.adaptation import (@@ -16,6 +18,11 @@ from src.strategy_store.models import (ArtifactType,ValidationStatus,)+from src.strategy_discovery.models import (+ EvidenceRow,+ classify_quality,+ coverage_days_from_ranges,+)from src.strategy_store.store import InMemoryStrategyStore@@ -29,6 +36,29 @@ def _reset_store(tmp_path):shared._store = None+HEALTHY_RANGES = ("2023-01 to 2025-12", "2026-01 to 2026-01")+TODAY_FRESH = date(2026, 1, 31)+TODAY_STALE = TODAY_FRESH + timedelta(days=180)+++def _evidence(+ *, trades: int = 20, date_ranges: tuple[str, ...] = HEALTHY_RANGES+) -> tuple[EvidenceRow, ...]:+ """One evidence row for the parent, adequate and fresh unless told otherwise."""+ coverage = coverage_days_from_ranges(date_ranges)+ return (+ EvidenceRow(+ strategy_id="sdm:parent",+ regime="bull_market",+ trades_in_regime=trades,+ date_ranges=date_ranges,+ evidence_quality=classify_quality(trades, coverage),+ evidence_stage="backtest",+ provenance="/tmp/run",+ ),+ )++SIGNAL = "close > sma(20)"ENTRY = "buy next open"EXIT = "sell next open"@@ -115,7 +145,13 @@ class TestRegisterAdaptation:def test_new_universe_same_name_succeeds(self) -> None:store = InMemoryStrategyStore()parent_id = store.register_artifact(_strategy(artifact_id=""))- child_id = register_adaptation(store, parent_id, AdaptationPatch(universe="SP500"))+ child_id = register_adaptation(+ store,+ parent_id,+ AdaptationPatch(universe="SP500"),+ parent_evidence=_evidence(),+ today=TODAY_FRESH,+ )child = store.get_artifact(child_id)parent = store.get_artifact(parent_id)assert child is not None@@ -131,9 +167,21 @@ class TestRegisterAdaptation:def test_same_universe_same_name_raises_duplicate(self) -> None:store = InMemoryStrategyStore()parent_id = store.register_artifact(_strategy(artifact_id=""))- register_adaptation(store, parent_id, AdaptationPatch(name="momentum_weekly"))+ register_adaptation(+ store,+ parent_id,+ AdaptationPatch(name="momentum_weekly"),+ parent_evidence=_evidence(),+ today=TODAY_FRESH,+ )with pytest.raises(ValueError, match="already exists"):- register_adaptation(store, parent_id, AdaptationPatch(name="momentum_weekly"))+ register_adaptation(+ store,+ parent_id,+ AdaptationPatch(name="momentum_weekly"),+ parent_evidence=_evidence(),+ today=TODAY_FRESH,+ )class TestSqliteDerivedFromRoundtrip:@@ -142,7 +190,13 @@ class TestSqliteDerivedFromRoundtrip:store = get_store()parent_id = store.register_artifact(_strategy(artifact_id=""))- child_id = register_adaptation(store, parent_id, AdaptationPatch(universe="SP500"))+ child_id = register_adaptation(+ store,+ parent_id,+ AdaptationPatch(universe="SP500"),+ parent_evidence=_evidence(),+ today=TODAY_FRESH,+ )fetched = store.get_artifact(child_id)assert fetched is not Noneassert fetched.derived_from == parent_id@@ -151,3 +205,117 @@ class TestSqliteDerivedFromRoundtrip:assert fetched.run_dir is Noneassert fetched.status is ArtifactStatus.CREATEDassert fetched.signal_definition == SIGNAL+++class TestChildDoesNotInheritAttestation:+ """The child may not wear an attestation it never earned.++ ``adapt_artifact`` copies through ``dataclasses.replace``, so every+ governance field the call does not name survives onto the child. The+ parent's ``validator`` / ``approver`` name people who signed off on a+ *different* artifact, and the child is UNVALIDATED with no run behind+ it — the same inherited-provenance rule that keeps the parent's evidence+ off the child. Asserted per field, and cross-checked against the fields+ that are meant to carry forward, so a future blanket reset is caught too.+ """++ def _signed_parent(self) -> Artifact:+ return _strategy(+ validator="Val",+ approver="Cho",+ artifact_version="3",+ model_version="gpt-x-2025",+ validation_status=ValidationStatus.VALIDATED,+ validation_date="2026-01-05T00:00:00+00:00",+ model_tier=None,+ intended_use="CSI300 momentum sleeve",+ limitations="thin coverage before 2015",+ )++ def test_attestation_fields_are_cleared(self) -> None:+ parent = self._signed_parent()+ child = adapt_artifact(parent, AdaptationPatch(universe="SP500"))++ assert child.validation_status is ValidationStatus.UNVALIDATED+ assert child.validation_date is None+ assert child.validator is None, "child claims an independent validator it never had"+ assert child.approver is None, "child claims a sign-off it never received"+ assert child.artifact_version is None, "child is version 1 of its own lineage"+ assert child.model_version is None, "no model has generated the child's code yet"++ def test_authorship_and_declared_use_still_carry_forward(self) -> None:+ """The reset must be surgical: ownership and scope are not attestations."""+ parent = self._signed_parent()+ child = adapt_artifact(parent, AdaptationPatch(universe="SP500"))++ assert child.developer == parent.developer+ assert child.owner == parent.owner+ assert child.intended_use == parent.intended_use+ assert child.limitations == parent.limitations++ def test_cleared_child_is_not_a_four_eyes_violation(self) -> None:+ """A same-person dev/approve pair must not survive the copy either."""+ from src.strategy_store.models import is_four_eyes_violation++ parent = _strategy(developer="Ada", approver="Ada")+ assert is_four_eyes_violation(parent)+ assert not is_four_eyes_violation(adapt_artifact(parent, AdaptationPatch(universe="SP500")))+++class TestEvidenceGateSitsOnTheWritePath:+ """``parent_adaptation_blockers`` has to be reachable from the write, not+ just from a caller who remembers to ask.++ The gate inputs are keyword-only and required, so a caller cannot skip+ the check by forgetting it — the call does not typecheck or run without+ them. These tests pin the refusal itself rather than the signature, so+ the guarantee survives a refactor of how the inputs arrive.+ """++ def test_stale_parent_evidence_refuses_the_write(self) -> None:+ store = InMemoryStrategyStore()+ parent_id = store.register_artifact(_strategy(artifact_id=""))+ before = len(store.list_artifacts())++ with pytest.raises(AdaptationError, match="stale-evidence"):+ register_adaptation(+ store,+ parent_id,+ AdaptationPatch(universe="SP500"),+ parent_evidence=_evidence(),+ today=TODAY_STALE,+ )++ assert len(store.list_artifacts()) == before, "refused adaptation still wrote a child"++ def test_insufficient_parent_evidence_refuses_the_write(self) -> None:+ store = InMemoryStrategyStore()+ parent_id = store.register_artifact(_strategy(artifact_id=""))++ with pytest.raises(AdaptationError, match="insufficient-evidence"):+ register_adaptation(+ store,+ parent_id,+ AdaptationPatch(universe="SP500"),+ parent_evidence=(),+ today=TODAY_FRESH,+ )++ def test_gate_inputs_are_required(self) -> None:+ """Omitting them is a TypeError, not a silent unguarded write."""+ store = InMemoryStrategyStore()+ parent_id = store.register_artifact(_strategy(artifact_id=""))++ with pytest.raises(TypeError):+ register_adaptation(store, parent_id, AdaptationPatch(universe="SP500"))++ def test_missing_parent_is_reported_before_the_gate(self) -> None:+ store = InMemoryStrategyStore()+ with pytest.raises(AdaptationError, match="not found"):+ register_adaptation(+ store,+ "art_missing",+ AdaptationPatch(universe="SP500"),+ parent_evidence=(),+ today=TODAY_FRESH,+ )