"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(strategy-store): add description-driven adaptation substrate
Chandan Kumarbad21e070d91
diff --git a/agent/src/strategy_discovery/adaptation.py b/agent/src/strategy_discovery/adaptation.pynew file mode 100644index 000000000..aa86a1c46--- /dev/null+++ b/agent/src/strategy_discovery/adaptation.py@@ -0,0 +1,49 @@+"""Parent-evidence gate for description-driven adaptation."""++from __future__ import annotations++from datetime import date+from typing import Sequence++from src.strategy_discovery.models import (+ DECAY_STALE,+ QUALITY_ADEQUATE,+ EvidenceRow,+ classify_decay,+)+++def parent_adaptation_blockers(+ rows: Sequence[EvidenceRow], today: date+) -> tuple[str, ...]:+ """Return stable refusal reasons, or empty when adaptation may proceed.++ Allowed when at least one row is adequate and not stale. Reasons use+ ``stale-evidence:`` / ``insufficient-evidence:`` prefixes.+ """+ if not rows:+ return ("insufficient-evidence: parent has no evidence rows",)++ has_usable = False+ saw_stale = False+ saw_weak = False+ for row in rows:+ decay = classify_decay(row.date_ranges, today)+ if row.evidence_quality == QUALITY_ADEQUATE and decay != DECAY_STALE:+ has_usable = True+ if decay == DECAY_STALE:+ saw_stale = True+ if row.evidence_quality != QUALITY_ADEQUATE:+ saw_weak = True++ if has_usable:+ return ()++ reasons: list[str] = []+ if saw_stale:+ reasons.append(+ "stale-evidence: parent has no fresh or aging adequate evidence"+ )+ if saw_weak or not saw_stale:+ reasons.append("insufficient-evidence: parent has no adequate evidence")+ return tuple(reasons)diff --git a/agent/src/strategy_store/adaptation.py b/agent/src/strategy_store/adaptation.pynew file mode 100644index 000000000..ae112f738--- /dev/null+++ b/agent/src/strategy_store/adaptation.py@@ -0,0 +1,78 @@+"""Description-driven adaptation of SDM strategy artifacts."""++from __future__ import annotations++from dataclasses import dataclass, replace+from typing import Protocol++from src.strategy_store.models import (+ Artifact,+ ArtifactStatus,+ ArtifactType,+ ValidationStatus,+)+++class AdaptationError(ValueError):+ """Raised when a parent cannot be adapted under the Phase 3 contract."""+++@dataclass(frozen=True)+class AdaptationPatch:+ """Allowed description-driven changes. Signal fields are not on this type."""++ universe: str | None = None+ name: str | None = None+ position_sizing: str | None = None+++class _ArtifactStore(Protocol):+ def get_artifact(self, artifact_id: str) -> Artifact | None: ...++ def register_artifact(self, artifact: Artifact) -> str: ...+++def adapt_artifact(parent: Artifact, patch: AdaptationPatch) -> Artifact:+ """Return a new strategy artifact derived from *parent*. Does not write."""+ if parent.type is not ArtifactType.STRATEGY:+ raise AdaptationError(+ f"only strategy artifacts can be adapted; got type={parent.type.value!r}"+ )+ if not parent.id:+ raise AdaptationError("parent artifact id is required")++ new_universe = patch.universe if patch.universe is not None else parent.universe+ new_name = patch.name if patch.name is not None else parent.name+ if new_universe == parent.universe and new_name == parent.name:+ raise AdaptationError("adaptation must change universe or name")++ new_sizing = (+ patch.position_sizing if patch.position_sizing is not None else parent.position_sizing+ )+ return replace(+ parent,+ id="",+ name=new_name,+ universe=new_universe,+ position_sizing=new_sizing,+ derived_from=parent.id,+ status=ArtifactStatus.CREATED,+ run_dir=None,+ created_at="",+ updated_at="",+ disabled_at=None,+ disabled_reason=None,+ validation_status=ValidationStatus.UNVALIDATED,+ validation_date=None,+ )+++def register_adaptation(+ store: _ArtifactStore, parent_id: str, patch: AdaptationPatch+) -> str:+ """Persist an adapted child through the strategy store. Returns the new id."""+ parent = store.get_artifact(parent_id)+ if parent is None:+ raise AdaptationError(f"parent artifact {parent_id!r} not found")+ child = adapt_artifact(parent, patch)+ return store.register_artifact(child)diff --git a/agent/src/strategy_store/models.py b/agent/src/strategy_store/models.pyindex 5c71185a2..d35bc0d2f 100644--- a/agent/src/strategy_store/models.py+++ b/agent/src/strategy_store/models.py@@ -101,6 +101,8 @@ class Artifact:signal_engine_path: str | None = Nonerun_dir: str | None = Nonehypothesis_id: str | None = None+ #: Parent artifact id when this record was adapted from another strategy.+ derived_from: str | None = None# Lifecyclestatus: ArtifactStatus = ArtifactStatus.CREATEDcreated_at: str = ""diff --git a/agent/src/strategy_store/sqlite_store.py b/agent/src/strategy_store/sqlite_store.pyindex 35ed2d8c1..26b866914 100644--- a/agent/src/strategy_store/sqlite_store.py+++ b/agent/src/strategy_store/sqlite_store.py@@ -43,7 +43,11 @@ _DEFAULT_DB_PATH = Path.home() / ".vibe-trading" / "strategy_store.db"# the migration itself is idempotent via a column-existence check so it is# safe to run unconditionally on every open regardless of the stamped# version (covers DBs that were hand-edited or partially migrated).-_SCHEMA_VERSION_GOVERNANCE = 2+# Schema version 3 adds ``derived_from`` on ``artifacts``.+_SCHEMA_VERSION_ADAPTATION = 3+_ADAPTATION_COLUMNS: dict[str, str] = {+ "derived_from": "TEXT",+}# column_name -> DDL type/default fragment used by ALTER TABLE ADD COLUMN._GOVERNANCE_COLUMNS: dict[str, str] = {@@ -173,6 +177,7 @@ class SqliteStrategyStore:signal_engine_path TEXT,run_dir TEXT,hypothesis_id TEXT,+ derived_from TEXT,status TEXT NOT NULL DEFAULT 'created'CHECK(status IN ('created','benching','active',@@ -239,24 +244,23 @@ class SqliteStrategyStore:)if self._conn.execute("PRAGMA user_version").fetchone()[0] < 1:self._conn.execute("PRAGMA user_version=1")- self._migrate_governance_columns()- if self._conn.execute("PRAGMA user_version").fetchone()[0] < _SCHEMA_VERSION_GOVERNANCE:- self._conn.execute(f"PRAGMA user_version={_SCHEMA_VERSION_GOVERNANCE}")+ self._migrate_artifact_columns()+ version = self._conn.execute("PRAGMA user_version").fetchone()[0]+ if version < _SCHEMA_VERSION_ADAPTATION:+ self._conn.execute(f"PRAGMA user_version={_SCHEMA_VERSION_ADAPTATION}")self._conn.commit()- def _migrate_governance_columns(self) -> None:- """Add model-governance columns to ``artifacts`` if missing.+ def _migrate_artifact_columns(self) -> None:+ """Add optional ``artifacts`` columns if missing.- Idempotent: checks ``PRAGMA table_info`` for each column before- issuing ``ALTER TABLE ADD COLUMN``, so it is safe to call on every- connection open — including against a pre-governance database that- predates this migration (the primary backward-compatibility path)- and against re-running this exact method twice in the same process.+ Idempotent: checks ``PRAGMA table_info`` before each+ ``ALTER TABLE ADD COLUMN``."""existing_columns = {row["name"] for row in self._conn.execute("PRAGMA table_info(artifacts)")}- for column, ddl in _GOVERNANCE_COLUMNS.items():+ extra = {**_GOVERNANCE_COLUMNS, **_ADAPTATION_COLUMNS}+ for column, ddl in extra.items():if column not in existing_columns:self._conn.execute(f"ALTER TABLE artifacts ADD COLUMN {column} {ddl}")@@ -297,6 +301,7 @@ class SqliteStrategyStore:signal_engine_path=row["signal_engine_path"],run_dir=row["run_dir"],hypothesis_id=row["hypothesis_id"],+ derived_from=row["derived_from"],status=ArtifactStatus(row["status"]),created_at=row["created_at"],updated_at=row["updated_at"],@@ -386,13 +391,13 @@ class SqliteStrategyStore:id, type, name, source_paper, source_url, formula_latex,theme, columns_required, decay_horizon, signal_definition,entry_rules, exit_rules, position_sizing, universe,- signal_engine_path, run_dir, hypothesis_id, status,+ signal_engine_path, run_dir, hypothesis_id, derived_from, status,created_at, updated_at, disabled_at, disabled_reason,developer, owner, validator, approver, model_version,artifact_version, model_tier, intended_use, limitations,validation_status, validation_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,- ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",(artifact_id,@@ -412,6 +417,7 @@ class SqliteStrategyStore:artifact.signal_engine_path,artifact.run_dir,artifact.hypothesis_id,+ artifact.derived_from,artifact.status.value,created_at,now,@@ -548,7 +554,7 @@ class SqliteStrategyStore:decay_horizon = ?, signal_definition = ?,entry_rules = ?, exit_rules = ?, position_sizing = ?,universe = ?, signal_engine_path = ?, run_dir = ?,- hypothesis_id = ?, status = ?, updated_at = ?,+ hypothesis_id = ?, derived_from = ?, status = ?, updated_at = ?,disabled_at = ?, disabled_reason = ?,developer = ?, owner = ?, validator = ?, approver = ?,model_version = ?, artifact_version = ?, model_tier = ?,@@ -573,6 +579,7 @@ class SqliteStrategyStore:artifact.signal_engine_path,artifact.run_dir,artifact.hypothesis_id,+ artifact.derived_from,artifact.status.value,now,artifact.disabled_at,diff --git a/agent/tests/test_strategy_discovery_adaptation.py b/agent/tests/test_strategy_discovery_adaptation.pynew file mode 100644index 000000000..b561ee981--- /dev/null+++ b/agent/tests/test_strategy_discovery_adaptation.py@@ -0,0 +1,73 @@+"""Parent-evidence gate for description-driven adaptation."""++from __future__ import annotations++from datetime import date, timedelta++from src.strategy_discovery.adaptation import parent_adaptation_blockers+from src.strategy_discovery.models import (+ DECAY_STALE,+ MIN_TRADES,+ QUALITY_ADEQUATE,+ QUALITY_INSUFFICIENT,+ EvidenceRow,+ classify_decay,+ classify_quality,+ coverage_days_from_ranges,+)++JAN_2026 = ("2026-01 to 2026-01",)+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 _row(+ *,+ trades: int,+ date_ranges: tuple[str, ...],+ evidence_quality: str | None = None,+) -> EvidenceRow:+ coverage = coverage_days_from_ranges(date_ranges)+ quality = evidence_quality if evidence_quality is not None else classify_quality(trades, coverage)+ return EvidenceRow(+ strategy_id="sdm:parent",+ regime="bull_market",+ trades_in_regime=trades,+ date_ranges=date_ranges,+ evidence_quality=quality,+ evidence_stage="backtest",+ provenance="/tmp/run",+ )+++class TestParentAdaptationBlockers:+ def test_healthy_adequate_fresh_window_is_not_blocked(self) -> None:+ row = _row(trades=20, date_ranges=HEALTHY_RANGES)+ assert row.evidence_quality == QUALITY_ADEQUATE+ assert classify_decay(row.date_ranges, TODAY_FRESH) != DECAY_STALE+ assert classify_decay(JAN_2026, TODAY_FRESH) != DECAY_STALE+ assert parent_adaptation_blockers((row,), TODAY_FRESH) == ()++ def test_stale_window_blocks_with_stale_evidence(self) -> None:+ row = _row(trades=20, date_ranges=HEALTHY_RANGES)+ assert row.evidence_quality == QUALITY_ADEQUATE+ assert classify_decay(row.date_ranges, TODAY_STALE) == DECAY_STALE+ blockers = parent_adaptation_blockers((row,), TODAY_STALE)+ assert blockers+ assert any(reason.startswith("stale-evidence:") for reason in blockers)++ def test_insufficient_trades_blocks_with_insufficient_evidence(self) -> None:+ row = _row(trades=4, date_ranges=HEALTHY_RANGES)+ assert 4 < MIN_TRADES+ assert row.evidence_quality == QUALITY_INSUFFICIENT+ assert classify_decay(row.date_ranges, TODAY_FRESH) != DECAY_STALE+ blockers = parent_adaptation_blockers((row,), TODAY_FRESH)+ assert blockers+ assert any(reason.startswith("insufficient-evidence:") for reason in blockers)+ assert not any(reason.startswith("stale-evidence:") for reason in blockers)++ def test_empty_rows_block(self) -> None:+ blockers = parent_adaptation_blockers((), TODAY_FRESH)+ assert blockers+ assert blockers == ("insufficient-evidence: parent has no evidence rows",)diff --git a/agent/tests/test_strategy_store.py b/agent/tests/test_strategy_store.pyindex 7ba2c97b4..130fda816 100644--- a/agent/tests/test_strategy_store.py+++ b/agent/tests/test_strategy_store.py@@ -1306,6 +1306,7 @@ class TestSchemaMigration:assert fetched.limitations is Noneassert fetched.validation_status == ValidationStatus.UNVALIDATEDassert fetched.validation_date is None+ assert fetched.derived_from is Nonedef test_old_db_still_writable_after_migration(self, tmp_path):"""New writes (including governance fields) work on a migrated DB."""@@ -1363,8 +1364,8 @@ class TestSchemaMigration:store = SqliteStrategyStore(db_path=db_path)# First open already ran the migration once (in __init__ -> _init_db).# Run it again explicitly, twice more, to prove idempotency.- store._migrate_governance_columns()- store._migrate_governance_columns()+ store._migrate_artifact_columns()+ store._migrate_artifact_columns()columns = [row["name"]@@ -1374,6 +1375,7 @@ class TestSchemaMigration:assert len(columns) == len(set(columns))assert columns.count("validation_status") == 1assert columns.count("developer") == 1+ assert columns.count("derived_from") == 1# Store still functions normally after repeated migration calls.fetched = store.get_artifact("art_legacy001")diff --git a/agent/tests/test_strategy_store_adaptation.py b/agent/tests/test_strategy_store_adaptation.pynew file mode 100644index 000000000..e88a723d9--- /dev/null+++ b/agent/tests/test_strategy_store_adaptation.py@@ -0,0 +1,153 @@+"""Adaptation writes a new CREATED strategy through the artifact store."""++from __future__ import annotations++import pytest++from src.strategy_store.adaptation import (+ AdaptationError,+ AdaptationPatch,+ adapt_artifact,+ register_adaptation,+)+from src.strategy_store.models import (+ Artifact,+ ArtifactStatus,+ ArtifactType,+ ValidationStatus,+)+from src.strategy_store.store import InMemoryStrategyStore++[email protected](autouse=True)+def _reset_store(tmp_path):+ import src.strategy_store._shared as shared+ from src.strategy_store.sqlite_store import SqliteStrategyStore++ shared._store = SqliteStrategyStore(db_path=tmp_path / "test.db")+ yield+ shared._store = None+++SIGNAL = "close > sma(20)"+ENTRY = "buy next open"+EXIT = "sell next open"+ENGINE = "engines/momentum.py"+++def _strategy(+ *,+ artifact_id: str = "art_parent",+ name: str = "momentum",+ universe: str = "CSI300",+ artifact_type: ArtifactType = ArtifactType.STRATEGY,+ **overrides,+) -> Artifact:+ fields = dict(+ id=artifact_id,+ type=artifact_type,+ name=name,+ universe=universe,+ signal_definition=SIGNAL,+ entry_rules=ENTRY,+ exit_rules=EXIT,+ position_sizing="monthly rebalance",+ signal_engine_path=ENGINE,+ run_dir="/tmp/parent_run",+ status=ArtifactStatus.ACTIVE,+ created_at="2026-01-01T00:00:00+00:00",+ updated_at="2026-01-02T00:00:00+00:00",+ developer="Ada",+ owner="Bob",+ theme=("momentum",),+ columns_required=("close",),+ decay_horizon=20,+ source_paper="Jegadeesh 1993",+ hypothesis_id="hyp_1",+ validation_status=ValidationStatus.UNVALIDATED,+ )+ fields.update(overrides)+ return Artifact(**fields)+++class TestAdaptArtifact:+ def test_child_keeps_parent_signal_fields(self) -> None:+ parent = _strategy()+ child = adapt_artifact(parent, AdaptationPatch(universe="SP500"))+ assert child.signal_definition == SIGNAL+ assert child.entry_rules == ENTRY+ assert child.exit_rules == EXIT+ assert child.signal_engine_path == ENGINE+ assert child.theme == parent.theme+ assert child.columns_required == parent.columns_required+ assert child.decay_horizon == parent.decay_horizon+ assert child.source_paper == parent.source_paper+ assert child.hypothesis_id == parent.hypothesis_id+ assert child.developer == parent.developer+ assert child.owner == parent.owner++ def test_child_identity_starts_clean(self) -> None:+ parent = _strategy()+ child = adapt_artifact(parent, AdaptationPatch(universe="SP500"))+ assert child.derived_from == parent.id+ assert child.id == ""+ assert child.run_dir is None+ assert child.status is ArtifactStatus.CREATED+ assert child.created_at == ""+ assert child.updated_at == ""+ assert child.disabled_at is None+ assert child.disabled_reason is None+ assert child.validation_status is ValidationStatus.UNVALIDATED+ assert child.validation_date is None++ def test_factor_parent_refused(self) -> None:+ parent = _strategy(artifact_type=ArtifactType.FACTOR)+ with pytest.raises(AdaptationError, match="strategy"):+ adapt_artifact(parent, AdaptationPatch(universe="SP500"))++ def test_noop_same_name_and_universe_refused(self) -> None:+ parent = _strategy()+ with pytest.raises(AdaptationError, match="adaptation must change universe or name"):+ adapt_artifact(parent, AdaptationPatch(position_sizing="weekly rebalance"))+++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 = store.get_artifact(child_id)+ parent = store.get_artifact(parent_id)+ assert child is not None+ assert parent is not None+ assert child.id == child_id+ assert child.id != parent_id+ assert child.derived_from == parent_id+ assert child.run_dir is None+ assert child.status is ArtifactStatus.CREATED+ assert child.name == parent.name+ assert child.universe == "SP500"++ 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"))+ with pytest.raises(ValueError, match="already exists"):+ register_adaptation(store, parent_id, AdaptationPatch(name="momentum_weekly"))+++class TestSqliteDerivedFromRoundtrip:+ def test_derived_from_survives_sqlite_roundtrip(self) -> None:+ from src.strategy_store._shared import get_store++ store = get_store()+ parent_id = store.register_artifact(_strategy(artifact_id=""))+ child_id = register_adaptation(store, parent_id, AdaptationPatch(universe="SP500"))+ fetched = store.get_artifact(child_id)+ assert fetched is not None+ assert fetched.derived_from == parent_id+ assert fetched.id == child_id+ assert fetched.id != parent_id+ assert fetched.run_dir is None+ assert fetched.status is ArtifactStatus.CREATED+ assert fetched.signal_definition == SIGNAL