"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: add IRR-AGL artifact store and trace refs
Mirandadcb42d2e5daf
diff --git a/agent/backtest/run_card.py b/agent/backtest/run_card.pyindex 9acb90011..ddbc38a06 100644--- a/agent/backtest/run_card.py+++ b/agent/backtest/run_card.py@@ -30,6 +30,7 @@ def write_run_card(data_sources: Sequence[str] | None = None,strategy_path: Path | None = None,warnings: Sequence[str] | None = None,+ artifact_refs: Sequence[Mapping[str, Any]] | None = None,) -> dict[str, Any]:"""Write JSON and Markdown run cards for a backtest run.@@ -41,6 +42,7 @@ def write_run_card(data_sources: Data sources used by the run.strategy_path: Optional strategy source file to hash for reproducibility.warnings: Optional warnings to include in the card.+ artifact_refs: Optional IRR-AGL artifact references.Returns:The run card payload written to ``run_card.json``.@@ -68,6 +70,9 @@ def write_run_card("warnings": list(warnings or []),"artifacts": _list_artifacts(run_dir),}+ normalized_refs = _normalize_artifact_refs(artifact_refs)+ if normalized_refs:+ card["artifact_refs"] = normalized_refsif "validation" in metrics:card["validation"] = metrics["validation"]@@ -162,6 +167,17 @@ def _list_artifacts(run_dir: Path) -> list[dict[str, Any]]:return artifacts+def _normalize_artifact_refs(artifact_refs: Sequence[Mapping[str, Any]] | None) -> list[dict[str, Any]]:+ refs: list[dict[str, Any]] = []+ for ref in artifact_refs or []:+ if hasattr(ref, "model_dump"):+ value = ref.model_dump(mode="json") # type: ignore[attr-defined]+ else:+ value = dict(ref)+ refs.append(_json_safe(value))+ return refs++def _render_markdown(card: Mapping[str, Any]) -> str:lines = ["# Backtest Run Card",@@ -217,4 +233,17 @@ def _render_markdown(card: Mapping[str, Any]) -> str:else:lines.append("- None found.")+ artifact_refs = card.get("artifact_refs", [])+ if artifact_refs:+ lines.extend(["", "## IRR Artifact Refs"])+ for ref in artifact_refs:+ if isinstance(ref, Mapping):+ label = ref.get("artifact_id", "")+ artifact_type = ref.get("artifact_type", "")+ digest = ref.get("sha256", "")+ uri = ref.get("uri", "")+ lines.append(f"- `{label}` ({artifact_type}, sha256 `{digest}`, uri `{uri}`)")+ else:+ lines.append(f"- {ref}")+return "\n".join(lines) + "\n"diff --git a/agent/src/agent/trace.py b/agent/src/agent/trace.pyindex 661c2d837..23f73bcc0 100644--- a/agent/src/agent/trace.py+++ b/agent/src/agent/trace.py@@ -45,6 +45,15 @@ TRACE_TEXT_OFFLOAD_THRESHOLD = _env_int()OFFLOAD_PREVIEW_CHARS = _env_int("VIBE_TRADING_TRACE_PREVIEW_CHARS", 500)+OPTIONAL_IRR_TRACE_FIELDS = frozenset({+ "artifact_refs",+ "data_audit_id",+ "policy_decision_id",+ "governance_overhead_ms",+ "warning_codes",+ "hard_failure_codes",+})+class TraceWriter:"""JSONL trace writer, one record per line, crash-safe.diff --git a/agent/src/reliability/__init__.py b/agent/src/reliability/__init__.pynew file mode 100644index 000000000..b21a30771--- /dev/null+++ b/agent/src/reliability/__init__.py@@ -0,0 +1,6 @@+"""IRR-AGL reliability foundation modules."""++from __future__ import annotations++__all__ = []+diff --git a/agent/src/reliability/artifacts/__init__.py b/agent/src/reliability/artifacts/__init__.pynew file mode 100644index 000000000..e939030ea--- /dev/null+++ b/agent/src/reliability/artifacts/__init__.py@@ -0,0 +1,17 @@+"""Artifact models, hashing, and local store."""++from __future__ import annotations++from src.reliability.artifacts.hashing import sha256_bytes, sha256_file, sha256_json+from src.reliability.artifacts.model import ArtifactRecord, ArtifactRef+from src.reliability.artifacts.store import ArtifactStore++__all__ = [+ "ArtifactRecord",+ "ArtifactRef",+ "ArtifactStore",+ "sha256_bytes",+ "sha256_file",+ "sha256_json",+]+diff --git a/agent/src/reliability/artifacts/hashing.py b/agent/src/reliability/artifacts/hashing.pynew file mode 100644index 000000000..6c63ee519--- /dev/null+++ b/agent/src/reliability/artifacts/hashing.py@@ -0,0 +1,83 @@+"""Canonical hash helpers for IRR-AGL artifacts."""++from __future__ import annotations++import hashlib+import json+import math+from collections.abc import Mapping+from datetime import date, datetime, time+from pathlib import Path+from typing import Any+from uuid import UUID++from pydantic import BaseModel++from src.reliability.errors import CanonicalJsonError+++def sha256_bytes(data: bytes) -> str:+ """Return the SHA-256 hex digest for bytes."""+ return hashlib.sha256(data).hexdigest()+++def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str:+ """Return a streaming SHA-256 hex digest for a file."""+ digest = hashlib.sha256()+ with Path(path).open("rb") as handle:+ for chunk in iter(lambda: handle.read(chunk_size), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def sha256_json(value: Mapping[str, Any]) -> str:+ """Return a canonical SHA-256 digest for a JSON object."""+ if not isinstance(value, dict):+ raise CanonicalJsonError("sha256_json requires a JSON-serializable dict")+ _validate_json_value(value, path="$")+ try:+ payload = json.dumps(+ value,+ sort_keys=True,+ ensure_ascii=False,+ allow_nan=False,+ separators=(",", ":"),+ )+ except (TypeError, ValueError) as exc:+ raise CanonicalJsonError(str(exc)) from exc+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()+++def _validate_json_value(value: Any, *, path: str) -> None:+ if isinstance(value, BaseModel):+ raise CanonicalJsonError(f"{path}: Pydantic models must use model_dump(mode='json') before hashing")+ if isinstance(value, (datetime, date, time)):+ raise CanonicalJsonError(f"{path}: datetime/date/time values must be converted before hashing")+ if isinstance(value, UUID):+ raise CanonicalJsonError(f"{path}: UUID values must be converted before hashing")+ if _looks_like_pandas(value):+ raise CanonicalJsonError(f"{path}: pandas objects cannot be canonically JSON hashed")+ if value is None or isinstance(value, (str, bool, int)):+ return+ if isinstance(value, float):+ if not math.isfinite(value):+ raise CanonicalJsonError(f"{path}: NaN/Inf values are not allowed")+ return+ if isinstance(value, list):+ for idx, item in enumerate(value):+ _validate_json_value(item, path=f"{path}[{idx}]")+ return+ if isinstance(value, dict):+ for key, item in value.items():+ if not isinstance(key, str):+ raise CanonicalJsonError(f"{path}: JSON object keys must be strings")+ _validate_json_value(item, path=f"{path}.{key}")+ return+ raise CanonicalJsonError(f"{path}: unsupported JSON value type {type(value).__name__}")+++def _looks_like_pandas(value: Any) -> bool:+ module = type(value).__module__+ name = type(value).__name__+ return module.startswith("pandas.") and name in {"DataFrame", "Series"}+diff --git a/agent/src/reliability/artifacts/lineage.py b/agent/src/reliability/artifacts/lineage.pynew file mode 100644index 000000000..0263994f7--- /dev/null+++ b/agent/src/reliability/artifacts/lineage.py@@ -0,0 +1,29 @@+"""Small helpers for artifact lineage graphs."""++from __future__ import annotations++from dataclasses import dataclass++from src.reliability.artifacts.model import ArtifactRecord, ArtifactRef+++@dataclass(frozen=True)+class ArtifactLineageEdge:+ """Parent-child edge in the local artifact graph."""++ parent_artifact_id: str+ child_artifact_id: str+++def refs_for_records(records: list[ArtifactRecord]) -> list[ArtifactRef]:+ """Return lightweight refs for a list of records."""+ return [record.to_ref() for record in records]+++def lineage_edges(record: ArtifactRecord) -> list[ArtifactLineageEdge]:+ """Return parent-child edges implied by one artifact record."""+ return [+ ArtifactLineageEdge(parent_artifact_id=parent, child_artifact_id=record.artifact_id)+ for parent in record.parent_artifacts+ ]+diff --git a/agent/src/reliability/artifacts/model.py b/agent/src/reliability/artifacts/model.pynew file mode 100644index 000000000..1a630c4f0--- /dev/null+++ b/agent/src/reliability/artifacts/model.py@@ -0,0 +1,67 @@+"""Pydantic models for IRR-AGL artifact records."""++from __future__ import annotations++from datetime import datetime, timezone+from typing import Any++from pydantic import BaseModel, Field, field_validator++from src.reliability.redaction import redact_secrets+from src.reliability.schema import ArtifactType+++def _utc_now() -> datetime:+ return datetime.now(timezone.utc)+++class ArtifactRef(BaseModel):+ """Lightweight reference to a persisted IRR-AGL artifact."""++ artifact_id: str+ artifact_type: ArtifactType+ sha256: str | None = None+ uri: str | None = None+++class ArtifactRecord(BaseModel):+ """Metadata record for a persisted IRR-AGL artifact."""++ artifact_id: str+ artifact_type: ArtifactType+ schema_version: str+ sha256: str+ uri: str+ path: str | None = None+ inline_ref: str | None = None+ parent_artifacts: list[str] = Field(default_factory=list)+ created_at: datetime = Field(default_factory=_utc_now)+ generated_by: str+ metadata: dict[str, Any] = Field(default_factory=dict)++ @field_validator("created_at")+ @classmethod+ def _created_at_must_be_aware_utc(cls, value: datetime) -> datetime:+ if value.tzinfo is None or value.utcoffset() is None:+ raise ValueError("created_at must be timezone-aware")+ return value.astimezone(timezone.utc)++ @field_validator("metadata", mode="before")+ @classmethod+ def _redact_metadata(cls, value: Any) -> dict[str, Any]:+ if value is None:+ return {}+ redacted = redact_secrets(value)+ if not isinstance(redacted, dict):+ raise ValueError("metadata must be a JSON object")+ return redacted++ def to_ref(self) -> ArtifactRef:+ """Return a lightweight reference to this artifact."""+ return ArtifactRef(+ artifact_id=self.artifact_id,+ artifact_type=self.artifact_type,+ sha256=self.sha256,+ uri=self.uri,+ )+diff --git a/agent/src/reliability/artifacts/store.py b/agent/src/reliability/artifacts/store.pynew file mode 100644index 000000000..4629463c2--- /dev/null+++ b/agent/src/reliability/artifacts/store.py@@ -0,0 +1,210 @@+"""SQLite-backed local artifact store for IRR-AGL Phase 1."""++from __future__ import annotations++import json+import os+import sqlite3+import time+import uuid+from pathlib import Path+from threading import Lock+from typing import Any++from src.reliability.artifacts.hashing import sha256_bytes+from src.reliability.artifacts.model import ArtifactRecord+from src.reliability.config import artifact_root, reliability_enabled+from src.reliability.errors import ArtifactPathError, ArtifactStoreError+from src.reliability.schema import ARTIFACT_SCHEMA_VERSION, ArtifactType++_INDEX_FILENAME = "artifact_index.sqlite"+_MAX_INSERT_ATTEMPTS = 6+++def resolve_under_root(root: Path, relative_path: Path | str) -> Path:+ """Resolve a relative path and ensure it stays inside root."""+ relative = Path(relative_path)+ if relative.is_absolute():+ raise ArtifactPathError(f"absolute paths are not allowed: {relative}")+ resolved_root = Path(root).resolve(strict=False)+ candidate = (resolved_root / relative).resolve(strict=False)+ try:+ candidate.relative_to(resolved_root)+ except ValueError as exc:+ raise ArtifactPathError(f"path escapes artifact root: {relative}") from exc+ return candidate+++class ArtifactStore:+ """Content-addressed local artifact store with a SQLite metadata index."""++ def __init__(self, root: Path | None = None) -> None:+ self.root = Path(root) if root is not None else artifact_root()+ self._init_lock = Lock()+ self._initialized = False++ @property+ def index_path(self) -> Path:+ """Return the SQLite metadata index path."""+ return self.root / _INDEX_FILENAME++ def write_bytes(+ self,+ data: bytes,+ *,+ artifact_type: ArtifactType,+ generated_by: str,+ metadata: dict[str, Any] | None = None,+ parent_artifacts: list[str] | None = None,+ schema_version: str = ARTIFACT_SCHEMA_VERSION,+ artifact_id: str | None = None,+ ) -> ArtifactRecord | None:+ """Persist bytes and index their artifact metadata."""+ if not reliability_enabled():+ return None++ self._ensure_initialized()+ digest = sha256_bytes(data)+ payload_path = resolve_under_root(self.root, Path("objects") / digest[:2] / f"{digest}.bin")+ _atomic_write_bytes(payload_path, data)++ record = ArtifactRecord(+ artifact_id=artifact_id or f"art_{uuid.uuid4().hex}",+ artifact_type=artifact_type,+ schema_version=schema_version,+ sha256=digest,+ uri=f"artifact://sha256/{digest}",+ path=str(payload_path),+ parent_artifacts=list(parent_artifacts or []),+ generated_by=generated_by,+ metadata=dict(metadata or {}),+ )+ self._insert_record(record)+ return record++ def write_json(+ self,+ payload: dict[str, Any],+ *,+ artifact_type: ArtifactType,+ generated_by: str,+ metadata: dict[str, Any] | None = None,+ parent_artifacts: list[str] | None = None,+ schema_version: str = ARTIFACT_SCHEMA_VERSION,+ ) -> ArtifactRecord | None:+ """Persist a JSON payload using strict, deterministic serialization."""+ data = json.dumps(+ payload,+ ensure_ascii=False,+ sort_keys=True,+ allow_nan=False,+ separators=(",", ":"),+ ).encode("utf-8")+ return self.write_bytes(+ data,+ artifact_type=artifact_type,+ generated_by=generated_by,+ metadata=metadata,+ parent_artifacts=parent_artifacts,+ schema_version=schema_version,+ )++ def _ensure_initialized(self) -> None:+ if self._initialized:+ return+ with self._init_lock:+ if self._initialized:+ return+ self.root.mkdir(parents=True, exist_ok=True)+ with self._connect() as conn:+ conn.execute("PRAGMA journal_mode=WAL")+ conn.execute("PRAGMA synchronous=NORMAL")+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS artifacts (+ artifact_id TEXT PRIMARY KEY,+ artifact_type TEXT NOT NULL,+ schema_version TEXT NOT NULL,+ sha256 TEXT NOT NULL,+ uri TEXT NOT NULL,+ path TEXT,+ inline_ref TEXT,+ parent_artifacts_json TEXT NOT NULL,+ created_at TEXT NOT NULL,+ generated_by TEXT NOT NULL,+ metadata_json TEXT NOT NULL+ )+ """+ )+ self._initialized = True++ def _connect(self) -> sqlite3.Connection:+ conn = sqlite3.connect(str(self.index_path), timeout=30.0)+ conn.execute("PRAGMA busy_timeout=30000")+ return conn++ def _insert_record(self, record: ArtifactRecord) -> None:+ dumped = record.model_dump(mode="json")+ parent_artifacts_json = json.dumps(dumped["parent_artifacts"], ensure_ascii=False, sort_keys=True)+ metadata_json = json.dumps(dumped["metadata"], ensure_ascii=False, sort_keys=True)+ params = (+ dumped["artifact_id"],+ dumped["artifact_type"],+ dumped["schema_version"],+ dumped["sha256"],+ dumped["uri"],+ dumped.get("path"),+ dumped.get("inline_ref"),+ parent_artifacts_json,+ dumped["created_at"],+ dumped["generated_by"],+ metadata_json,+ )+ for attempt in range(_MAX_INSERT_ATTEMPTS):+ try:+ with self._connect() as conn:+ conn.execute("BEGIN IMMEDIATE")+ conn.execute(+ """+ INSERT INTO artifacts (+ artifact_id,+ artifact_type,+ schema_version,+ sha256,+ uri,+ path,+ inline_ref,+ parent_artifacts_json,+ created_at,+ generated_by,+ metadata_json+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ params,+ )+ conn.commit()+ return+ except sqlite3.OperationalError as exc:+ if "locked" not in str(exc).lower() or attempt == _MAX_INSERT_ATTEMPTS - 1:+ raise ArtifactStoreError(str(exc)) from exc+ time.sleep(0.02 * (2**attempt))+++def _atomic_write_bytes(path: Path, data: bytes) -> None:+ """Write bytes atomically with a same-directory temp file."""+ if path.exists():+ return+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")+ try:+ with tmp.open("wb") as handle:+ handle.write(data)+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(tmp, path)+ finally:+ try:+ tmp.unlink()+ except FileNotFoundError:+ pass+diff --git a/agent/src/reliability/config.py b/agent/src/reliability/config.pynew file mode 100644index 000000000..89577c432--- /dev/null+++ b/agent/src/reliability/config.py@@ -0,0 +1,39 @@+"""Configuration helpers for IRR-AGL reliability features."""++from __future__ import annotations++import os+from pathlib import Path+from typing import Literal++ReliabilityMode = Literal["off", "observe", "warn", "enforce"]++VALID_RELIABILITY_MODES: frozenset[str] = frozenset({"off", "observe", "warn", "enforce"})+_DEFAULT_MODE: ReliabilityMode = "observe"+++def parse_reliability_mode(raw: str | None, *, default: ReliabilityMode = _DEFAULT_MODE) -> ReliabilityMode:+ """Parse an IRR-AGL reliability mode."""+ value = (raw or default).strip().lower()+ if value not in VALID_RELIABILITY_MODES:+ raise ValueError(f"unsupported reliability mode: {raw!r}")+ return value # type: ignore[return-value]+++def reliability_mode() -> ReliabilityMode:+ """Return the current reliability feature mode."""+ return parse_reliability_mode(os.getenv("VIBE_TRADING_RELIABILITY_MODE"))+++def reliability_enabled() -> bool:+ """Return whether reliability writes should produce artifacts."""+ return reliability_mode() != "off"+++def artifact_root() -> Path:+ """Return the local artifact root, honoring the environment override."""+ raw = os.getenv("VIBE_TRADING_ARTIFACT_ROOT")+ if raw:+ return Path(os.path.expandvars(os.path.expanduser(raw))).resolve(strict=False)+ return (Path.home() / ".vibe-trading" / "artifacts").resolve(strict=False)+diff --git a/agent/src/reliability/errors.py b/agent/src/reliability/errors.pynew file mode 100644index 000000000..a4293ebe5--- /dev/null+++ b/agent/src/reliability/errors.py@@ -0,0 +1,20 @@+"""Exceptions raised by IRR-AGL reliability components."""++from __future__ import annotations+++class ReliabilityError(Exception):+ """Base class for reliability-layer failures."""+++class CanonicalJsonError(ReliabilityError, ValueError):+ """Raised when a value cannot be canonically hashed as JSON."""+++class ArtifactStoreError(ReliabilityError):+ """Raised when artifact persistence fails."""+++class ArtifactPathError(ArtifactStoreError, ValueError):+ """Raised when an artifact path escapes the configured root."""+diff --git a/agent/src/reliability/redaction.py b/agent/src/reliability/redaction.pynew file mode 100644index 000000000..fc71f8414--- /dev/null+++ b/agent/src/reliability/redaction.py@@ -0,0 +1,59 @@+"""Secret redaction helpers for IRR-AGL records."""++from __future__ import annotations++import re+from collections.abc import Mapping+from typing import Any++REDACTED = "[REDACTED]"++_SECRET_KEY_FRAGMENTS = (+ "secret",+ "token",+ "api_key",+ "apikey",+ "password",+ "credential",+ "broker",+ "authorization",+ "cookie",+ "session",+ "private_key",+ "refresh_token",+ "access_token",+)++_BEARER_RE = re.compile(r"^\s*bearer\s+[A-Za-z0-9._~+/=-]{16,}\s*$", re.IGNORECASE)+_KEY_PREFIX_RE = re.compile(r"^\s*(sk|rk|pk|ghp|gho|ghu|github_pat)-[A-Za-z0-9_\-]{20,}\s*$", re.IGNORECASE)+_LONG_RANDOM_RE = re.compile(r"^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[A-Za-z0-9_\-+/=]{40,}$")+++def redact_secrets(value: Any) -> Any:+ """Recursively redact secret-like keys and values."""+ if isinstance(value, Mapping):+ redacted: dict[str, Any] = {}+ for key, item in value.items():+ key_text = str(key)+ if _key_is_secret_like(key_text):+ redacted[key_text] = REDACTED+ else:+ redacted[key_text] = redact_secrets(item)+ return redacted+ if isinstance(value, list):+ return [redact_secrets(item) for item in value]+ if isinstance(value, tuple):+ return [redact_secrets(item) for item in value]+ if isinstance(value, str) and _value_is_secret_like(value):+ return REDACTED+ return value+++def _key_is_secret_like(key: str) -> bool:+ lowered = key.lower()+ return any(fragment in lowered for fragment in _SECRET_KEY_FRAGMENTS)+++def _value_is_secret_like(value: str) -> bool:+ return bool(_BEARER_RE.match(value) or _KEY_PREFIX_RE.match(value) or _LONG_RANDOM_RE.match(value))+diff --git a/agent/src/reliability/schema.py b/agent/src/reliability/schema.pynew file mode 100644index 000000000..36d401ed7--- /dev/null+++ b/agent/src/reliability/schema.py@@ -0,0 +1,34 @@+"""Shared schema constants for IRR-AGL reliability artifacts."""++from __future__ import annotations++from typing import Literal++ARTIFACT_SCHEMA_VERSION = "1.0.0"++ArtifactType = Literal[+ "data_audit",+ "tool_trace",+ "policy_decision",+ "research_protocol",+ "trial_event",+ "backtest_result",+ "alpha_bench_result",+ "scorecard",+ "research_card",+]++ARTIFACT_TYPES: frozenset[str] = frozenset(+ {+ "data_audit",+ "tool_trace",+ "policy_decision",+ "research_protocol",+ "trial_event",+ "backtest_result",+ "alpha_bench_result",+ "scorecard",+ "research_card",+ }+)+diff --git a/agent/tests/reliability/test_artifact_concurrency.py b/agent/tests/reliability/test_artifact_concurrency.pynew file mode 100644index 000000000..18864a6ec--- /dev/null+++ b/agent/tests/reliability/test_artifact_concurrency.py@@ -0,0 +1,35 @@+"""Concurrency tests for Phase 1 artifact metadata writes."""++from __future__ import annotations++import sqlite3+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import pytest++from src.reliability.artifacts.store import ArtifactStore+++def test_artifact_store_concurrent_writes_no_metadata_loss(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")+ store = ArtifactStore(tmp_path)+ payloads = [f"payload-{idx}".encode("utf-8") for idx in range(40)]++ def write_payload(payload: bytes) -> str:+ record = store.write_bytes(payload, artifact_type="tool_trace", generated_by="pytest")+ assert record is not None+ return record.artifact_id++ with ThreadPoolExecutor(max_workers=8) as pool:+ artifact_ids = list(pool.map(write_payload, payloads))++ with sqlite3.connect(tmp_path / "artifact_index.sqlite") as conn:+ count = conn.execute("SELECT COUNT(*) FROM artifacts").fetchone()[0]++ assert count == len(payloads)+ assert len(set(artifact_ids)) == len(payloads)+diff --git a/agent/tests/reliability/test_artifact_hashing.py b/agent/tests/reliability/test_artifact_hashing.pynew file mode 100644index 000000000..09dd18789--- /dev/null+++ b/agent/tests/reliability/test_artifact_hashing.py@@ -0,0 +1,73 @@+"""Tests for Phase 1 canonical artifact hashing."""++from __future__ import annotations++import math+from datetime import datetime, timezone+from pathlib import Path+from uuid import uuid4++import pytest+from pydantic import BaseModel++from src.reliability.artifacts.hashing import sha256_bytes, sha256_file, sha256_json+from src.reliability.errors import CanonicalJsonError+++class ExampleModel(BaseModel):+ value: str+ created_at: datetime+++def test_sha256_bytes_matches_sha256_file(tmp_path: Path) -> None:+ payload = b"stable artifact payload"+ path = tmp_path / "payload.bin"+ path.write_bytes(payload)++ assert sha256_file(path) == sha256_bytes(payload)+++def test_sha256_json_requires_json_serializable_dict() -> None:+ with pytest.raises(CanonicalJsonError):+ sha256_json(["not", "a", "dict"]) # type: ignore[arg-type]+++def test_sha256_json_is_stable_for_key_order() -> None:+ left = {"z": 1, "a": {"b": [True, None, "x"]}}+ right = {"a": {"b": [True, None, "x"]}, "z": 1}++ assert sha256_json(left) == sha256_json(right)+++def test_sha256_json_rejects_datetime() -> None:+ with pytest.raises(CanonicalJsonError):+ sha256_json({"created_at": datetime.now(timezone.utc)})+++def test_sha256_json_rejects_uuid() -> None:+ with pytest.raises(CanonicalJsonError):+ sha256_json({"id": uuid4()})+++def test_sha256_json_rejects_nan() -> None:+ with pytest.raises(CanonicalJsonError):+ sha256_json({"score": math.nan})+++def test_sha256_json_rejects_inf() -> None:+ with pytest.raises(CanonicalJsonError):+ sha256_json({"score": math.inf})+++def test_pydantic_model_hash_requires_model_dump_json() -> None:+ artifact = ExampleModel(value="ok", created_at=datetime(2026, 7, 6, tzinfo=timezone.utc))++ with pytest.raises(CanonicalJsonError):+ sha256_json(artifact) # type: ignore[arg-type]++ hashable = artifact.model_dump(mode="json")+ digest = sha256_json(hashable)++ assert isinstance(digest, str)+ assert len(digest) == 64+diff --git a/agent/tests/reliability/test_artifact_models.py b/agent/tests/reliability/test_artifact_models.pynew file mode 100644index 000000000..86bce04ae--- /dev/null+++ b/agent/tests/reliability/test_artifact_models.py@@ -0,0 +1,74 @@+"""Tests for Phase 1 artifact Pydantic models."""++from __future__ import annotations++from datetime import datetime, timezone++from src.reliability.artifacts.model import ArtifactRecord, ArtifactRef+++def test_artifact_record_defaults_to_timezone_aware_utc() -> None:+ record = ArtifactRecord(+ artifact_id="art_test",+ artifact_type="tool_trace",+ schema_version="1.0.0",+ sha256="a" * 64,+ uri="artifact://sha256/" + "a" * 64,+ generated_by="pytest",+ )++ assert record.created_at.tzinfo is not None+ assert record.created_at.utcoffset().total_seconds() == 0+++def test_artifact_record_normalizes_aware_datetime_to_utc() -> None:+ created = datetime(2026, 7, 6, 9, 30, tzinfo=timezone.utc)++ record = ArtifactRecord(+ artifact_id="art_test",+ artifact_type="scorecard",+ schema_version="1.0.0",+ sha256="b" * 64,+ uri="artifact://sha256/" + "b" * 64,+ created_at=created,+ generated_by="pytest",+ )++ assert record.created_at == created+++def test_artifact_record_redacts_secret_like_metadata() -> None:+ record = ArtifactRecord(+ artifact_id="art_test",+ artifact_type="policy_decision",+ schema_version="1.0.0",+ sha256="c" * 64,+ uri="artifact://sha256/" + "c" * 64,+ generated_by="pytest",+ metadata={+ "api_key": "plain-secret",+ "nested": {"authorization": "Bearer abcdefghijklmnopqrstuvwxyz012345"},+ "safe": "visible",+ },+ )++ assert record.metadata["api_key"] == "[REDACTED]"+ assert record.metadata["nested"]["authorization"] == "[REDACTED]"+ assert record.metadata["safe"] == "visible"+++def test_artifact_ref_is_lightweight() -> None:+ ref = ArtifactRef(+ artifact_id="art_test",+ artifact_type="research_card",+ sha256="d" * 64,+ uri="artifact://sha256/" + "d" * 64,+ )++ assert ref.model_dump(mode="json") == {+ "artifact_id": "art_test",+ "artifact_type": "research_card",+ "sha256": "d" * 64,+ "uri": "artifact://sha256/" + "d" * 64,+ }+diff --git a/agent/tests/reliability/test_artifact_store.py b/agent/tests/reliability/test_artifact_store.pynew file mode 100644index 000000000..6f970d646--- /dev/null+++ b/agent/tests/reliability/test_artifact_store.py@@ -0,0 +1,107 @@+"""Tests for Phase 1 SQLite-backed artifact store."""++from __future__ import annotations++import json+import sqlite3+from pathlib import Path++import pytest++from src.reliability.artifacts.hashing import sha256_bytes+from src.reliability.artifacts.store import ArtifactStore, resolve_under_root+from src.reliability.errors import ArtifactPathError+++def test_artifact_store_atomic_write(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")+ store = ArtifactStore(tmp_path)+ payload = b"atomic payload"++ record = store.write_bytes(+ payload,+ artifact_type="backtest_result",+ generated_by="pytest",+ metadata={"label": "atomic"},+ )++ assert record is not None+ assert record.sha256 == sha256_bytes(payload)+ assert record.path is not None+ payload_path = Path(record.path)+ assert payload_path.read_bytes() == payload+ assert not list(payload_path.parent.glob("*.tmp"))+++def test_artifact_store_sqlite_wal_enabled(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")+ store = ArtifactStore(tmp_path)+ store.write_bytes(b"wal", artifact_type="tool_trace", generated_by="pytest")++ with sqlite3.connect(tmp_path / "artifact_index.sqlite") as conn:+ mode = conn.execute("PRAGMA journal_mode").fetchone()[0]++ assert mode.lower() == "wal"+++def test_artifact_store_path_containment_rejects_escape(tmp_path: Path) -> None:+ with pytest.raises(ArtifactPathError):+ resolve_under_root(tmp_path, Path("..") / "escape.bin")+++def test_artifact_store_rejects_symlink_escape(tmp_path: Path) -> None:+ outside = tmp_path.parent / "outside"+ outside.mkdir(exist_ok=True)+ link = tmp_path / "link"+ try:+ link.symlink_to(outside, target_is_directory=True)+ except OSError:+ pytest.skip("symlinks are unavailable on this platform")++ with pytest.raises(ArtifactPathError):+ resolve_under_root(tmp_path, link / "payload.bin")+++def test_artifact_store_redacts_secret_like_metadata(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")+ store = ArtifactStore(tmp_path)++ record = store.write_bytes(+ b"secret metadata",+ artifact_type="policy_decision",+ generated_by="pytest",+ metadata={+ "token": "plain-token",+ "note": "visible",+ "nested": {"cookie": "session=abcdef"},+ },+ )++ assert record is not None+ with sqlite3.connect(tmp_path / "artifact_index.sqlite") as conn:+ metadata_json = conn.execute(+ "SELECT metadata_json FROM artifacts WHERE artifact_id = ?",+ (record.artifact_id,),+ ).fetchone()[0]++ metadata = json.loads(metadata_json)+ assert metadata["token"] == "[REDACTED]"+ assert metadata["nested"]["cookie"] == "[REDACTED]"+ assert metadata["note"] == "visible"+ assert "plain-token" not in metadata_json+ assert "session=abcdef" not in metadata_json+++def test_reliability_mode_off_does_not_require_artifact_write(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "off")+ store = ArtifactStore(tmp_path)++ record = store.write_bytes(b"disabled", artifact_type="tool_trace", generated_by="pytest")++ assert record is None+ assert not (tmp_path / "artifact_index.sqlite").exists()+ assert not (tmp_path / "objects").exists()+diff --git a/agent/tests/reliability/test_artifact_trace_compat.py b/agent/tests/reliability/test_artifact_trace_compat.pynew file mode 100644index 000000000..25b66e8fb--- /dev/null+++ b/agent/tests/reliability/test_artifact_trace_compat.py@@ -0,0 +1,88 @@+"""Trace and run-card compatibility tests for Phase 1 artifact refs."""++from __future__ import annotations++import json+from pathlib import Path++from backtest.run_card import write_run_card+from src.agent.trace import TraceWriter+++def test_trace_reader_accepts_old_trace_without_new_fields(tmp_path: Path) -> None:+ (tmp_path / "trace.jsonl").write_text(+ json.dumps({"type": "tool_result", "tool": "get_market_data", "status": "ok"}) + "\n",+ encoding="utf-8",+ )++ [entry] = TraceWriter.read(tmp_path)++ assert entry["tool"] == "get_market_data"+ assert "artifact_refs" not in entry+ assert "policy_decision_id" not in entry+++def test_trace_writer_preserves_optional_artifact_refs(tmp_path: Path) -> None:+ trace = TraceWriter(tmp_path)+ trace.write(+ {+ "type": "tool_result",+ "tool": "backtest",+ "status": "ok",+ "artifact_refs": [{"artifact_id": "art_1", "artifact_type": "backtest_result"}],+ "data_audit_id": "audit_1",+ "policy_decision_id": "pd_1",+ "governance_overhead_ms": 1.5,+ "warning_codes": ["W_TEST"],+ "hard_failure_codes": ["H_TEST"],+ }+ )+ trace.close()++ [entry] = TraceWriter.read(tmp_path)++ assert entry["artifact_refs"] == [{"artifact_id": "art_1", "artifact_type": "backtest_result"}]+ assert entry["data_audit_id"] == "audit_1"+ assert entry["policy_decision_id"] == "pd_1"+ assert entry["governance_overhead_ms"] == 1.5+ assert entry["warning_codes"] == ["W_TEST"]+ assert entry["hard_failure_codes"] == ["H_TEST"]+++def test_run_card_old_shape_still_valid(tmp_path: Path) -> None:+ card = write_run_card(+ tmp_path,+ {"codes": ["AAPL"], "source": "yfinance"},+ {"sharpe": 1.0},+ )++ loaded = json.loads((tmp_path / "run_card.json").read_text(encoding="utf-8"))++ assert loaded == card+ assert isinstance(loaded["artifacts"], list)+ assert "artifact_refs" not in loaded+++def test_run_card_can_include_optional_irr_artifact_refs(tmp_path: Path) -> None:+ artifact_refs = [+ {+ "artifact_id": "art_scorecard",+ "artifact_type": "scorecard",+ "sha256": "e" * 64,+ "uri": "artifact://sha256/" + "e" * 64,+ }+ ]++ card = write_run_card(+ tmp_path,+ {"codes": ["AAPL"], "source": "yfinance"},+ {"sharpe": 1.0},+ artifact_refs=artifact_refs,+ )++ loaded = json.loads((tmp_path / "run_card.json").read_text(encoding="utf-8"))++ assert loaded["artifacts"] == card["artifacts"]+ assert loaded["artifact_refs"] == artifact_refs+ assert "art_scorecard" in (tmp_path / "run_card.md").read_text(encoding="utf-8")+