"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Merge PR #2079: add research revisions with atomic and scoped provenance
Haozhe Wud802e39015e5
diff --cc agent/src/research_artifacts/models.pyindex 000000000,adeb680a5..4aaf927fbmode 000000,100644..100644--- a/agent/src/research_artifacts/models.py+++ b/agent/src/research_artifacts/models.py@@@ -1,0 -1,54 +1,54 @@@+ """Models for persistent, versioned research artifacts."""++ from __future__ import annotations++ from dataclasses import asdict, dataclass, field+ from typing import Any+++ @dataclass(frozen=True)+ class ResearchArtifactRevision:+ """One immutable revision in a research-artifact series."""++ revision_id: str+ artifact_id: str+ revision_number: int+ previous_revision_id: str | None+ subject: str+ universe: str+ content: str+ content_hash: str+ provenance_hash: str+ identity_hash: str+ data_as_of: str+ created_at: str+ evidence: tuple[dict[str, Any], ...] = field(default_factory=tuple)+ verification_status: str = "unverified"+ completeness: str = "complete"+ hypothesis_id: str | None = None+ goal_id: str | None = None+ session_id: str | None = None+ run_id: str | None = None++ @property+ def evidence_missing(self) -> bool:+ """Whether this revision has no attached evidence references."""+ return not self.evidence++ def to_dict(self) -> dict[str, Any]:+ """Return a JSON-compatible representation with explicit evidence gaps."""+ payload = asdict(self)- payload["evidence"] = [dict(item) for item in self.evidence]++ payload["evidence"] = list(payload["evidence"])+ payload["evidence_missing"] = self.evidence_missing+ return payload+++ @dataclass(frozen=True)+ class ResearchArtifactSaveResult:+ """Distinguish a new revision from an idempotent repeated save."""++ revision: ResearchArtifactRevision+ created: bool++ def to_dict(self) -> dict[str, Any]:+ return {"revision": self.revision.to_dict(), "created": self.created}diff --cc agent/src/research_artifacts/store.pyindex 000000000,72b0edcfe..a3574606emode 000000,100644..100644--- a/agent/src/research_artifacts/store.py+++ b/agent/src/research_artifacts/store.py@@@ -1,0 -1,366 +1,394 @@@+ """SQLite index for immutable, versioned research artifacts."""++ from __future__ import annotations++ import hashlib+ import json+ import sqlite3+ import threading+ import uuid+ from collections.abc import Callable+ from datetime import datetime, timezone+ from functools import wraps+ from pathlib import Path+ from typing import Any, TypeVar++ from src.config.accessor import get_env_config+ from src.config.paths import get_runtime_root++ from .models import ResearchArtifactRevision, ResearchArtifactSaveResult+++ def _utc_now() -> str:+ return datetime.now(timezone.utc).isoformat()+++ def _canonical_json(value: object) -> str:- return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))++ return json.dumps(++ value,++ ensure_ascii=False,++ sort_keys=True,++ separators=(",", ":"),++ allow_nan=False,++ )+++ def _default_db_path() -> Path:+ paths = get_env_config().paths+ override = paths.vibe_trading_research_artifact_db_path.strip()+ if override:+ return Path(override).expanduser()+ goal_path = paths.vibe_trading_goal_db_path.strip()+ if goal_path:+ return Path(goal_path).expanduser()+ return get_runtime_root() / "sessions.db"+++ def _required(value: str, name: str) -> str:++ if not isinstance(value, str):++ raise ValueError(f"{name} is required (string)")+ cleaned = value.strip()+ if not cleaned:+ raise ValueError(f"{name} is required")+ return cleaned+++ F = TypeVar("F", bound=Callable)+++ def _synchronized(method: F) -> F:+ @wraps(method)+ def wrapper(self, *args, **kwargs): # type: ignore[no-untyped-def]+ with self._lock:+ return method(self, *args, **kwargs)++ return wrapper # type: ignore[return-value]+++ class ResearchArtifactStore:+ """Persist research revisions without modifying GoalStore or SDM records."""++ def __init__(self, db_path: Path | str | None = None) -> None:+ self.db_path = Path(db_path) if db_path is not None else _default_db_path()+ self.db_path.parent.mkdir(parents=True, exist_ok=True)+ self._conn = sqlite3.connect(str(self.db_path), check_same_thread=False)+ self._conn.row_factory = sqlite3.Row+ self._conn.execute("PRAGMA foreign_keys=ON")+ self._conn.execute("PRAGMA busy_timeout=5000")+ self._conn.execute("PRAGMA journal_mode=WAL")+ self._conn.execute("PRAGMA synchronous=NORMAL")+ self._lock = threading.RLock()+ self._init_db()++ def _init_db(self) -> None:+ with self._lock:- self._conn.executescript(- """++ self._conn.executescript("""+ CREATE TABLE IF NOT EXISTS research_artifact_revisions (+ revision_id TEXT PRIMARY KEY,+ artifact_id TEXT NOT NULL,+ revision_number INTEGER NOT NULL,+ previous_revision_id TEXT,+ subject TEXT NOT NULL,+ universe TEXT NOT NULL,+ content TEXT NOT NULL,+ content_hash TEXT NOT NULL,+ provenance_hash TEXT NOT NULL,+ identity_hash TEXT NOT NULL UNIQUE,+ data_as_of TEXT NOT NULL,+ created_at TEXT NOT NULL,+ evidence_json TEXT NOT NULL,+ verification_status TEXT NOT NULL,+ completeness TEXT NOT NULL,+ hypothesis_id TEXT,+ goal_id TEXT,+ session_id TEXT,+ run_id TEXT,+ UNIQUE(artifact_id, revision_number),+ FOREIGN KEY(previous_revision_id)+ REFERENCES research_artifact_revisions(revision_id)+ );++ CREATE INDEX IF NOT EXISTS idx_research_artifact_series+ ON research_artifact_revisions(artifact_id, revision_number);+ CREATE INDEX IF NOT EXISTS idx_research_artifact_subject+ ON research_artifact_revisions(subject, universe);+ CREATE INDEX IF NOT EXISTS idx_research_artifact_goal+ ON research_artifact_revisions(goal_id);+ CREATE INDEX IF NOT EXISTS idx_research_artifact_hypothesis+ ON research_artifact_revisions(hypothesis_id);+ CREATE INDEX IF NOT EXISTS idx_research_artifact_run+ ON research_artifact_revisions(run_id);- """- )++ """)+ self._conn.commit()++ def close(self) -> None:+ """Close the SQLite connection, primarily for isolated test cleanup."""+ with self._lock:+ self._conn.close()++ @staticmethod+ def _from_row(row: sqlite3.Row) -> ResearchArtifactRevision:+ return ResearchArtifactRevision(+ revision_id=row["revision_id"],+ artifact_id=row["artifact_id"],+ revision_number=row["revision_number"],+ previous_revision_id=row["previous_revision_id"],+ subject=row["subject"],+ universe=row["universe"],+ content=row["content"],+ content_hash=row["content_hash"],+ provenance_hash=row["provenance_hash"],+ identity_hash=row["identity_hash"],+ data_as_of=row["data_as_of"],+ created_at=row["created_at"],+ evidence=tuple(json.loads(row["evidence_json"])),+ verification_status=row["verification_status"],+ completeness=row["completeness"],+ hypothesis_id=row["hypothesis_id"],+ goal_id=row["goal_id"],+ session_id=row["session_id"],+ run_id=row["run_id"],+ )++ def _latest(self, artifact_id: str) -> ResearchArtifactRevision | None:+ row = self._conn.execute(+ """+ SELECT * FROM research_artifact_revisions+ WHERE artifact_id = ?+ ORDER BY revision_number DESC LIMIT 1+ """,+ (artifact_id,),+ ).fetchone()+ return self._from_row(row) if row else None+- def _by_identity(self, identity_hash: str) -> ResearchArtifactRevision | None:++ def _by_fingerprint(++ self, content_hash: str, provenance_hash: str, artifact_id: str | None++ ) -> ResearchArtifactRevision | None:+ row = self._conn.execute(- "SELECT * FROM research_artifact_revisions WHERE identity_hash = ?",- (identity_hash,),++ "SELECT * FROM research_artifact_revisions WHERE content_hash = ? AND provenance_hash = ?"++ + (" AND artifact_id = ?" if artifact_id else "")++ + " ORDER BY created_at DESC LIMIT 1",++ (++ (content_hash, provenance_hash, artifact_id)++ if artifact_id++ else (content_hash, provenance_hash)++ ),+ ).fetchone()+ return self._from_row(row) if row else None++ @_synchronized+ def save(+ self,+ *,+ content: str,+ data_as_of: str,+ artifact_id: str | None = None,+ subject: str | None = None,+ universe: str | None = None,+ evidence: list[dict[str, Any]] | None = None,+ verification_status: str | None = None,+ completeness: str | None = None,+ hypothesis_id: str | None = None,+ goal_id: str | None = None,+ session_id: str | None = None,+ run_id: str | None = None,+ ) -> ResearchArtifactSaveResult:+ """Append a revision, or return the identical existing revision."""- content = _required(content, "content")- data_as_of = _required(data_as_of, "data_as_of")- latest = self._latest(artifact_id) if artifact_id else None- if artifact_id and latest is None:- raise KeyError(f"research artifact not found: {artifact_id}")-- if latest is None:- subject = _required(subject or "", "subject")- universe = (universe or "").strip()- evidence = list(evidence or [])- verification_status = verification_status or "unverified"- completeness = completeness or "complete"- else:- subject = _required(subject if subject is not None else latest.subject, "subject")- universe = latest.universe if universe is None else universe.strip()- if subject != latest.subject or universe != latest.universe:- raise ValueError("a revision must preserve the artifact subject and universe")- evidence = list(latest.evidence) if evidence is None else list(evidence)- verification_status = verification_status or latest.verification_status- completeness = completeness or latest.completeness- hypothesis_id = hypothesis_id or latest.hypothesis_id- goal_id = goal_id or latest.goal_id- session_id = session_id or latest.session_id- run_id = run_id or latest.run_id-- if any(not isinstance(item, dict) for item in evidence):- raise ValueError("evidence must contain JSON objects")- evidence_json = _canonical_json(evidence)- content_hash = hashlib.sha256(content.encode("utf-8")).hexdigest()- provenance_hash = hashlib.sha256(- _canonical_json(- {- "subject": subject,- "universe": universe,- "data_as_of": data_as_of,- "evidence": evidence,- "verification_status": verification_status,- "completeness": completeness,- "hypothesis_id": hypothesis_id,- "goal_id": goal_id,- "session_id": session_id,- "run_id": run_id,- }- ).encode("utf-8")- ).hexdigest()- identity_hash = hashlib.sha256(f"{content_hash}:{provenance_hash}".encode("ascii")).hexdigest()- existing = self._by_identity(identity_hash)- if existing is not None:- return ResearchArtifactSaveResult(existing, created=False)-- if latest is None:- artifact_id = f"ra_{uuid.uuid4().hex[:12]}"- revision_number = 1- previous_revision_id = None- else:- revision_number = latest.revision_number + 1- previous_revision_id = latest.revision_id- revision_id = f"{artifact_id}_r{revision_number}"- created_at = _utc_now()-+ self._conn.execute("BEGIN IMMEDIATE")- try:- existing = self._by_identity(identity_hash)++ with self._conn:++ content = _required(content, "content")++ data_as_of = _required(data_as_of, "data_as_of")++ latest = self._latest(artifact_id) if artifact_id else None++ if artifact_id and latest is None:++ raise KeyError(f"research artifact not found: {artifact_id}")++++ if latest is None:++ subject = _required(subject or "", "subject")++ universe = (universe or "").strip()++ evidence = list(evidence or [])++ verification_status = verification_status or "unverified"++ completeness = completeness or "complete"++ else:++ subject = _required(++ subject if subject is not None else latest.subject, "subject"++ )++ universe = latest.universe if universe is None else universe.strip()++ if subject != latest.subject or universe != latest.universe:++ raise ValueError(++ "a revision must preserve the artifact subject and universe"++ )++ evidence = list(latest.evidence) if evidence is None else list(evidence)++ unchanged = (++ content == latest.content++ and data_as_of == latest.data_as_of++ and evidence == list(latest.evidence)++ and all(++ value is None or value == getattr(latest, key)++ for key, value in (++ ("hypothesis_id", hypothesis_id),++ ("goal_id", goal_id),++ ("session_id", session_id),++ ("run_id", run_id),++ )++ )++ )++ verification_status = verification_status or (++ latest.verification_status if unchanged else "unverified"++ )++ completeness = completeness or latest.completeness++ hypothesis_id = hypothesis_id or latest.hypothesis_id++ goal_id = goal_id or latest.goal_id++ session_id = session_id or latest.session_id++ run_id = run_id or latest.run_id++++ if any(not isinstance(item, dict) for item in evidence):++ raise ValueError("evidence must contain JSON objects")++ evidence_json = _canonical_json(evidence)++ content_hash = hashlib.sha256(content.encode("utf-8")).hexdigest()++ provenance_hash = hashlib.sha256(++ _canonical_json(++ {++ "subject": subject,++ "universe": universe,++ "data_as_of": data_as_of,++ "evidence": evidence,++ "verification_status": verification_status,++ "completeness": completeness,++ "hypothesis_id": hypothesis_id,++ "goal_id": goal_id,++ "session_id": session_id,++ "run_id": run_id,++ }++ ).encode("utf-8")++ ).hexdigest()++ existing = self._by_fingerprint(content_hash, provenance_hash, artifact_id)+ if existing is not None:- self._conn.rollback()+ return ResearchArtifactSaveResult(existing, created=False)++++ if latest is None:++ artifact_id = f"ra_{uuid.uuid4().hex[:12]}"++ revision_number = 1++ previous_revision_id = None++ else:++ revision_number = latest.revision_number + 1++ previous_revision_id = latest.revision_id++ revision_id = f"{artifact_id}_r{revision_number}"++ identity_hash = hashlib.sha256(++ f"{artifact_id}:{content_hash}:{provenance_hash}".encode("ascii")++ ).hexdigest()++ created_at = _utc_now()+++ self._conn.execute(+ """+ INSERT INTO research_artifact_revisions (+ revision_id, artifact_id, revision_number, previous_revision_id,+ subject, universe, content, content_hash, provenance_hash,+ identity_hash, data_as_of, created_at, evidence_json,+ verification_status, completeness, hypothesis_id, goal_id,+ session_id, run_id+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ revision_id,+ artifact_id,+ revision_number,+ previous_revision_id,+ subject,+ universe,+ content,+ content_hash,+ provenance_hash,+ identity_hash,+ data_as_of,+ created_at,+ evidence_json,+ verification_status,+ completeness,+ hypothesis_id,+ goal_id,+ session_id,+ run_id,+ ),+ )+ row = self._conn.execute(+ "SELECT * FROM research_artifact_revisions WHERE revision_id = ?",+ (revision_id,),+ ).fetchone()- except Exception:- self._conn.rollback()- raise- self._conn.commit()- return ResearchArtifactSaveResult(self._from_row(row), created=True)++ return ResearchArtifactSaveResult(self._from_row(row), created=True)++ @_synchronized+ def get_latest(self, artifact_id: str) -> ResearchArtifactRevision | None:+ """Return the newest revision in one series."""+ return self._latest(artifact_id)++ @_synchronized+ def get_revision(self, revision_id: str) -> ResearchArtifactRevision | None:+ """Return one immutable revision by its stable ID."""+ row = self._conn.execute(+ "SELECT * FROM research_artifact_revisions WHERE revision_id = ?",+ (revision_id,),+ ).fetchone()+ return self._from_row(row) if row else None++ @_synchronized+ def list_revisions(self, artifact_id: str) -> list[ResearchArtifactRevision]:+ """Return a series newest first, including every linked revision."""+ rows = self._conn.execute(+ """+ SELECT * FROM research_artifact_revisions+ WHERE artifact_id = ? ORDER BY revision_number DESC+ """,+ (artifact_id,),+ ).fetchall()+ return [self._from_row(row) for row in rows]++ @_synchronized+ def search(+ self,+ *,+ query: str = "",+ subject: str = "",+ universe: str = "",+ hypothesis_id: str = "",+ goal_id: str = "",+ session_id: str = "",+ run_id: str = "",+ limit: int = 50,+ ) -> list[ResearchArtifactRevision]:+ """Search the latest revision of each series with optional provenance filters."""+ limit = max(1, min(int(limit), 200))+ clauses: list[str] = []+ params: list[Any] = []+ if query.strip():+ needle = f"%{query.strip()}%"+ clauses.append("(subject LIKE ? OR universe LIKE ? OR content LIKE ?)")+ params.extend([needle, needle, needle])+ for column, value in (+ ("subject", subject.strip()),+ ("universe", universe.strip()),+ ("hypothesis_id", hypothesis_id.strip()),+ ("goal_id", goal_id.strip()),+ ("session_id", session_id.strip()),+ ("run_id", run_id.strip()),+ ):+ if value:+ clauses.append(f"{column} = ?")+ params.append(value)+ where = f"WHERE {' AND '.join(clauses)}" if clauses else ""+ rows = self._conn.execute(+ f"""+ SELECT r.* FROM research_artifact_revisions AS r+ JOIN (+ SELECT artifact_id, MAX(revision_number) AS latest_revision+ FROM research_artifact_revisions+ GROUP BY artifact_id+ ) AS latest+ ON r.artifact_id = latest.artifact_id+ AND r.revision_number = latest.latest_revision+ {where}+ ORDER BY r.created_at DESC, r.revision_id DESC+ LIMIT ?+ """,+ (*params, limit),+ ).fetchall()+ return [self._from_row(row) for row in rows]diff --cc agent/src/tools/research_artifact_tool.pyindex 000000000,8773331d1..004f293f6mode 000000,100644..100644--- a/agent/src/tools/research_artifact_tool.py+++ b/agent/src/tools/research_artifact_tool.py@@@ -1,0 -1,170 +1,171 @@@+ """Agent tools for saving and reusing versioned research artifacts."""++ from __future__ import annotations++ import json+ from typing import Any++ from src.agent.tools import BaseTool+ from src.research_artifacts import ResearchArtifactStore+++ def _ok(payload: dict[str, Any]) -> str:+ return json.dumps({"status": "ok", **payload}, ensure_ascii=False)+++ def _error(exc: Exception) -> str:+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)+++ class SaveResearchArtifactTool(BaseTool):+ """Save an immutable revision with content and provenance identity."""++ name = "save_research_artifact"+ description = (+ "Save research as an immutable, versioned artifact with evidence and data-as-of provenance. "- "Pass an existing artifact_id to append a linked revision. Identical repeated saves are idempotent."++ "Pass an existing artifact_id to append a linked revision. Identical repeated saves are idempotent. "++ "Changed content or provenance defaults to unverified; storing a revision does not revalidate it."+ )+ is_readonly = False+ repeatable = True+ parameters = {+ "type": "object",+ "properties": {+ "artifact_id": {"type": "string", "description": "Existing series ID to revise; omit for a new series"},+ "subject": {"type": "string", "description": "Research subject; inherited on revision"},+ "universe": {"type": "string", "description": "Optional market or asset universe"},+ "content": {"type": "string", "description": "Complete research conclusions for this revision"},+ "data_as_of": {"type": "string", "description": "Date or timestamp the research data represents"},+ "evidence": {+ "type": "array",+ "items": {"type": "object"},+ "description": "Source/evidence references, including URIs, IDs, and content hashes when available",+ },+ "verification_status": {"type": "string", "description": "Verification state, default unverified"},+ "completeness": {"type": "string", "description": "Completeness state, default complete"},+ "hypothesis_id": {"type": "string"},+ "goal_id": {"type": "string"},+ "session_id": {"type": "string"},+ "run_id": {"type": "string"},+ },+ "required": ["content", "data_as_of"],+ "additionalProperties": False,+ }++ def execute(self, **kwargs: Any) -> str:+ store = ResearchArtifactStore()+ try:+ result = store.save(+ artifact_id=kwargs.get("artifact_id"),+ subject=kwargs.get("subject"),+ universe=kwargs.get("universe"),- content=str(kwargs.get("content", "")),- data_as_of=str(kwargs.get("data_as_of", "")),++ content=kwargs.get("content", ""),++ data_as_of=kwargs.get("data_as_of", ""),+ evidence=kwargs.get("evidence"),+ verification_status=kwargs.get("verification_status"),+ completeness=kwargs.get("completeness"),+ hypothesis_id=kwargs.get("hypothesis_id"),+ goal_id=kwargs.get("goal_id"),+ session_id=kwargs.get("session_id"),+ run_id=kwargs.get("run_id"),+ )+ return _ok(result.to_dict())+ except Exception as exc:+ return _error(exc)+ finally:+ store.close()+++ class SearchResearchArtifactsTool(BaseTool):+ """Search the latest revision of each research-artifact series."""++ name = "search_research_artifacts"+ description = (+ "Search previous research by text, subject, universe, or linked hypothesis/goal/session/run IDs. "+ "Results are the latest revisions only and preserve evidence gaps and data-as-of dates."+ )+ repeatable = True+ parameters = {+ "type": "object",+ "properties": {+ "query": {"type": "string"},+ "subject": {"type": "string"},+ "universe": {"type": "string"},+ "hypothesis_id": {"type": "string"},+ "goal_id": {"type": "string"},+ "session_id": {"type": "string"},+ "run_id": {"type": "string"},+ "limit": {"type": "integer", "minimum": 1, "maximum": 200, "default": 50},+ },+ "required": [],+ "additionalProperties": False,+ }++ def execute(self, **kwargs: Any) -> str:+ store = ResearchArtifactStore()+ try:+ results = store.search(+ query=str(kwargs.get("query", "")),+ subject=str(kwargs.get("subject", "")),+ universe=str(kwargs.get("universe", "")),+ hypothesis_id=str(kwargs.get("hypothesis_id", "")),+ goal_id=str(kwargs.get("goal_id", "")),+ session_id=str(kwargs.get("session_id", "")),+ run_id=str(kwargs.get("run_id", "")),+ limit=int(kwargs.get("limit", 50)),+ )+ return _ok(+ {+ "count": len(results),+ "artifacts": [item.to_dict() for item in results],+ }+ )+ except Exception as exc:+ return _error(exc)+ finally:+ store.close()+++ class GetResearchArtifactTool(BaseTool):+ """Retrieve one series or one immutable revision."""++ name = "get_research_artifact"+ description = (+ "Retrieve a research-artifact series by artifact_id or one immutable revision by revision_id. "+ "Series retrieval can include every linked historical revision."+ )+ repeatable = True+ parameters = {+ "type": "object",+ "properties": {+ "artifact_id": {"type": "string"},+ "revision_id": {"type": "string"},+ "include_history": {"type": "boolean", "default": True},+ },+ "required": [],+ "additionalProperties": False,+ }++ def execute(self, **kwargs: Any) -> str:+ store = ResearchArtifactStore()+ try:+ revision_id = str(kwargs.get("revision_id", "")).strip()+ artifact_id = str(kwargs.get("artifact_id", "")).strip()+ if bool(revision_id) == bool(artifact_id):+ return _error(ValueError("provide exactly one of artifact_id or revision_id"))+ if revision_id:+ revision = store.get_revision(revision_id)+ if revision is None:+ return _error(ValueError(f"research revision not found: {revision_id}"))+ return _ok({"revision": revision.to_dict()})+ latest = store.get_latest(artifact_id)+ if latest is None:+ return _error(ValueError(f"research artifact not found: {artifact_id}"))+ payload: dict[str, Any] = {"artifact": latest.to_dict()}+ if kwargs.get("include_history", True):+ payload["revisions"] = [item.to_dict() for item in store.list_revisions(artifact_id)]+ return _ok(payload)+ except Exception as exc:+ return _error(exc)+ finally:+ store.close()diff --cc agent/tests/test_akshare_loader.pyindex 50c72ded2,270920528..21151bf33--- a/agent/tests/test_akshare_loader.py+++ b/agent/tests/test_akshare_loader.py@@@ -81,36 -75,19 +81,48 @@@ class TestIsForex# "ZZZZZZ" isn't in akshare's symbol_market_mapassert not _is_forex("ZZZZZZ")+ def test_akshare_120_cons_namespace(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setitem(sys.modules, "akshare.forex.cons", None)+ monkeypatch.setitem(+ sys.modules,+ "akshare.fx.cons_forex",+ SimpleNamespace(symbol_market_map={"EURUSD": 119}),+ )+ assert _is_forex("EURUSD")+ assert not _is_forex("ZZZZZZ")++class TestForexSymbolMapLocation:+ """AKShare 1.20.0 deleted ``akshare.forex`` and moved the symbol map to+ ``akshare.fx.cons_forex``. Detection must survive either layout, otherwise+ every FX pair silently routes to the A-share endpoint (CI red on 1.20.x)."""++ @staticmethod+ def _patch_blocked(monkeypatch: pytest.MonkeyPatch, *blocked: str) -> None:+ def fake_import(name: str, *args: object, **kwargs: object) -> object:+ if name in blocked:+ raise ModuleNotFoundError(f"No module named {name!r}")+ return _REAL_IMPORT(name, *args, **kwargs)++ monkeypatch.setattr(akshare_loader.importlib, "import_module", fake_import)++ def test_newer_layout_alone_still_detects_pairs(self, monkeypatch) -> None:+ pytest.importorskip("akshare.fx.cons_forex", reason="akshare >= 1.20 only")+ self._patch_blocked(monkeypatch, "akshare.forex.cons")+ assert _is_forex("EURUSD")++ def test_legacy_layout_alone_still_detects_pairs(self, monkeypatch) -> None:+ pytest.importorskip("akshare.forex.cons", reason="akshare <= 1.19 only")+ self._patch_blocked(monkeypatch, "akshare.fx.cons_forex")+ assert _is_forex("EURUSD")++ def test_missing_symbol_map_degrades_to_false(self, monkeypatch) -> None:+ self._patch_blocked(monkeypatch, "akshare.fx.cons_forex", "akshare.forex.cons")+ assert not _is_forex("EURUSD")++# ---------------------------------------------------------------------------# Routing tests — verify _fetch_one dispatches to the right endpoint without# actually hitting AKShare.diff --cc agent/tests/test_research_artifact_store.pyindex 000000000,d282f1468..b2f1d3491mode 000000,100644..100644--- a/agent/tests/test_research_artifact_store.py+++ b/agent/tests/test_research_artifact_store.py@@@ -1,0 -1,125 +1,209 @@@+ """Persistence and revision contracts for versioned research artifacts."""++ from __future__ import annotations++ import pytest++from concurrent.futures import ThreadPoolExecutor++import threading++import time++ from src.research_artifacts import ResearchArtifactStore+++ def _save(store: ResearchArtifactStore, **overrides):+ payload = {+ "subject": "NVDA fundamental review",+ "universe": "NVDA",+ "content": "Original conclusion with traceable evidence.",+ "data_as_of": "2026-10-20",- "evidence": [{"source_uri": "https://example.com/filing", "content_hash": "abc"}],++ "evidence": [++ {"source_uri": "https://example.com/filing", "content_hash": "abc"}++ ],+ "verification_status": "verified",+ "hypothesis_id": "hyp_nvda",+ "goal_id": "goal_nvda",+ "session_id": "session-a",+ "run_id": "run-a",+ }+ payload.update(overrides)+ return store.save(**payload)+++ def test_save_search_and_reload_across_instances(tmp_path):+ db_path = tmp_path / "research.db"+ store = ResearchArtifactStore(db_path)+ saved = _save(store)+ store.close()++ reloaded = ResearchArtifactStore(db_path)+ found = reloaded.search(subject="NVDA fundamental review", run_id="run-a")++ assert saved.created is True+ assert [item.revision_id for item in found] == [saved.revision.revision_id]+ assert found[0].evidence[0]["source_uri"] == "https://example.com/filing"+ assert found[0].evidence_missing is False- assert reloaded.get_revision(saved.revision.revision_id).content == saved.revision.content++ assert (++ reloaded.get_revision(saved.revision.revision_id).content++ == saved.revision.content++ )+++ def test_identical_content_and_provenance_are_idempotent(tmp_path):+ store = ResearchArtifactStore(tmp_path / "research.db")+ first = _save(store)+ repeated = _save(store)++ assert repeated.created is False+ assert repeated.revision.revision_id == first.revision.revision_id+ assert len(store.list_revisions(first.revision.artifact_id)) == 1+++ def test_changed_data_as_of_and_evidence_create_linked_revisions(tmp_path):+ store = ResearchArtifactStore(tmp_path / "research.db")+ first = _save(store)- second = _save(store, artifact_id=first.revision.artifact_id, data_as_of="2026-10-27")++ second = _save(++ store, artifact_id=first.revision.artifact_id, data_as_of="2026-10-27"++ )+ third = _save(+ store,+ artifact_id=first.revision.artifact_id,+ data_as_of="2026-10-27",+ evidence=[{"source_uri": "https://example.com/new-filing"}],+ )++ assert second.created is True+ assert second.revision.revision_number == 2+ assert second.revision.previous_revision_id == first.revision.revision_id+ assert third.revision.previous_revision_id == second.revision.revision_id+ history = store.list_revisions(first.revision.artifact_id)+ assert [item.revision_id for item in history] == [+ third.revision.revision_id,+ second.revision.revision_id,+ first.revision.revision_id,+ ]+ assert history[-1].content == first.revision.content+ assert history[-1].data_as_of == "2026-10-20"+++ def test_missing_evidence_and_verification_status_remain_visible(tmp_path):+ store = ResearchArtifactStore(tmp_path / "research.db")+ saved = _save(store, evidence=[], verification_status="unverified")++ result = saved.revision.to_dict()+ assert result["evidence_missing"] is True+ assert result["verification_status"] == "unverified"+ assert result["data_as_of"] == "2026-10-20"+++ def test_search_defaults_to_latest_revision_and_supports_link_filters(tmp_path):+ store = ResearchArtifactStore(tmp_path / "research.db")+ first = _save(store)+ latest = _save(+ store,+ artifact_id=first.revision.artifact_id,+ content="Updated conclusion.",+ data_as_of="2026-10-27",+ run_id="run-b",+ )+ _save(+ store,+ subject="MSFT sector review",+ universe="MSFT",+ content="Different sector conclusion.",+ hypothesis_id="hyp_msft",+ goal_id="goal_msft",+ session_id="session-b",+ run_id="run-c",+ )++ assert store.search(query="Original conclusion") == []- assert [item.revision_id for item in store.search(query="Updated conclusion")] == [latest.revision.revision_id]- assert [item.revision_id for item in store.search(goal_id="goal_nvda")] == [latest.revision.revision_id]++ assert [item.revision_id for item in store.search(query="Updated conclusion")] == [++ latest.revision.revision_id++ ]++ assert [item.revision_id for item in store.search(goal_id="goal_nvda")] == [++ latest.revision.revision_id++ ]+ assert len(store.search()) == 2+ assert len(store.list_revisions(first.revision.artifact_id)) == 2+++ def test_revision_requires_existing_series_and_preserves_subject(tmp_path):+ store = ResearchArtifactStore(tmp_path / "research.db")+ with pytest.raises(KeyError):+ _save(store, artifact_id="ra_missing")++ first = _save(store)+ with pytest.raises(ValueError, match="preserve the artifact subject"):- _save(store, artifact_id=first.revision.artifact_id, subject="Different subject")++ _save(++ store, artifact_id=first.revision.artifact_id, subject="Different subject"++ )+ with pytest.raises(ValueError, match="content is required"):+ _save(store, content=" ")++++++def test_changed_revision_does_not_inherit_verification(tmp_path):++ store = ResearchArtifactStore(tmp_path / "research.db")++ first = _save(store)++ changed = store.save(++ artifact_id=first.revision.artifact_id,++ content="New conclusion",++ data_as_of="2026-10-27",++ )++ assert changed.revision.verification_status == "unverified"++ assert (++ store.get_revision(first.revision.revision_id).verification_status == "verified"++ )++++++def test_revision_idempotency_cannot_return_another_series(tmp_path):++ store = ResearchArtifactStore(tmp_path / "research.db")++ first = _save(store, content="A")++ other = _save(store, content="B")++ changed = _save(store, artifact_id=first.revision.artifact_id, content="B")++ assert changed.created++ assert changed.revision.artifact_id == first.revision.artifact_id++ assert changed.revision.revision_id != other.revision.revision_id++++++def test_concurrent_instances_append_a_single_serial_revision_chain(++ tmp_path, monkeypatch++):++ db = tmp_path / "research.db"++ first = _save(ResearchArtifactStore(db))++ stores = [ResearchArtifactStore(db) for _ in range(4)]++ start = threading.Barrier(len(stores))++ for store in stores:++ original = store._latest++++ def slow_latest(artifact_id, original=original):++ result = original(artifact_id)++ time.sleep(0.03)++ return result++++ monkeypatch.setattr(store, "_latest", slow_latest)++++ def revise(index):++ start.wait(timeout=5)++ return _save(++ stores[index],++ artifact_id=first.revision.artifact_id,++ content=f"Concurrent revision {index}",++ )++++ try:++ with ThreadPoolExecutor(max_workers=4) as pool:++ results = list(pool.map(revise, range(4)))++ assert sorted(r.revision.revision_number for r in results) == [2, 3, 4, 5]++ history = stores[0].list_revisions(first.revision.artifact_id)++ assert [r.previous_revision_id for r in history[:-1]] == [++ r.revision_id for r in history[1:]++ ]++ finally:++ for store in stores:++ store.close()++++++def test_nonfinite_evidence_is_rejected_before_persistence(tmp_path):++ store = ResearchArtifactStore(tmp_path / "research.db")++ with pytest.raises(ValueError):++ _save(store, evidence=[{"value": float("nan")}])diff --cc frontend/src/i18n/locales/ar.jsonindex ad6783c54,3fa786560..2bf7648c0--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@@ -67,7 -69,36 +69,41 @@@"about": "حول","sessionsLoadFailed": "تعذر تحميل المحادثات.","pixelOffice": "المكتب البكسلي",- "paperTrading": "التداول التجريبي"+ "paperTrading": "التداول التجريبي",+ "researchArtifacts": "مخرجات البحث"+ },+ "researchArtifacts": {+ "completeness": "الاكتمال",+ "optionalLinks": "معرفات مرتبطة اختيارية",+ "formTitleNew": "حفظ البحث",+ "verification": "التحقق",+ "subject": "موضوع البحث",+ "createdNotice": "تم إنشاء المراجعة {{id}}.",+ "emptyHint": "احفظ تحليلاً لإعادة استخدام استنتاجاته وأدلته في جلسة لاحقة.",+ "newResearch": "بحث جديد",+ "emptyTitle": "لا توجد مخرجات بحث بعد",+ "save": "حفظ البحث",+ "evidenceMissing": "لا توجد مراجع أدلة مرفقة",+ "saveError": "تعذر حفظ مخرج البحث.",+ "additionalEvidence": "روابط أدلة إضافية (رابط واحد في كل سطر)",+ "subtitle": "أعد استخدام التحليلات المدعومة بالأدلة عبر الجلسات دون استبدال المراجعات السابقة.",+ "revise": "المراجعة انطلاقًا من هذه النسخة",+ "history": "سجل المراجعات",+ "searchPlaceholder": "ابحث في الموضوع أو النطاق أو المحتوى",+ "loadError": "تعذر تحميل مخرجات البحث.",+ "close": "إغلاق",+ "universe": "النطاق (اختياري)",+ "title": "مخرجات البحث",+ "dataAsOf": "البيانات اعتبارًا من",+ "content": "محتوى البحث",+ "saving": "جارٍ الحفظ…",+ "idempotentNotice": "المحتوى والمصدر المتطابقان موجودان بالفعل في {{id}}.",- "formTitleRevision": "إنشاء مراجعة مرتبطة"++ "formTitleRevision": "إنشاء مراجعة مرتبطة",++ "evidence": "مراجع الأدلة",++ "hypothesis_id": "معرّف الفرضية",++ "goal_id": "معرّف الهدف",++ "session_id": "معرّف الجلسة",++ "run_id": "معرّف التشغيل"},"runtime": {"monitorBadge": "مراقبة التداول",diff --cc frontend/src/i18n/locales/de.jsonindex f5fdba923,9b8eb46c4..4f00f3995--- a/frontend/src/i18n/locales/de.json+++ b/frontend/src/i18n/locales/de.json@@@ -73,7 -75,36 +75,41 @@@"portfolio": "Kontopositionen","sessionsLoadFailed": "Gespräche können nicht geladen werden.","pixelOffice": "Pixelbüro",- "paperTrading": "Simulierter Handel"+ "paperTrading": "Simulierter Handel",+ "researchArtifacts": "Recherche-Artefakte"+ },+ "researchArtifacts": {+ "subject": "Forschungsthema",+ "dataAsOf": "Datenstand",+ "saving": "Speichern…",+ "saveError": "Recherche-Artefakt konnte nicht gespeichert werden.",+ "evidenceMissing": "Keine Belegreferenzen vorhanden",+ "createdNotice": "Revision {{id}} erstellt.",+ "emptyHint": "Speichere eine Analyse, um ihre Schlussfolgerungen und Belege in späteren Sitzungen wiederzuverwenden.",+ "emptyTitle": "Noch keine Recherche-Artefakte",+ "save": "Recherche speichern",+ "universe": "Universum (optional)",+ "loadError": "Recherche-Artefakte konnten nicht geladen werden.",+ "formTitleNew": "Recherche speichern",+ "verification": "Verifizierung",+ "additionalEvidence": "Zusätzliche Beleg-URIs (eine pro Zeile)",+ "revise": "Ausgehend von dieser Revision überarbeiten",+ "completeness": "Vollständigkeit",+ "searchPlaceholder": "Thema, Universum oder Inhalt suchen",+ "newResearch": "Neue Recherche",+ "formTitleRevision": "Verknüpfte Revision erstellen",+ "content": "Inhalt der Recherche",+ "subtitle": "Beleggestützte Analysen sitzungsübergreifend wiederverwenden, ohne frühere Revisionen zu überschreiben.",+ "history": "Revisionsverlauf",+ "optionalLinks": "Optionale verknüpfte IDs",+ "title": "Recherche-Artefakte",+ "close": "Schließen",- "idempotentNotice": "Identischer Inhalt und identische Provenienz existieren bereits in {{id}}."++ "idempotentNotice": "Identischer Inhalt und identische Provenienz existieren bereits in {{id}}.",++ "evidence": "Belegquellen",++ "hypothesis_id": "Hypothesen-ID",++ "goal_id": "Ziel-ID",++ "session_id": "Sitzungs-ID",++ "run_id": "Lauf-ID"},"runtime": {"monitorBadge": "Runtime-Monitor",diff --cc frontend/src/i18n/locales/en.jsonindex 9dc82dd49,0fc3847dd..6bb5a11ea--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@@ -75,6 -78,34 +78,39 @@@"pixelOffice": "Pixel Office","paperTrading": "Paper trading"},+ "researchArtifacts": {+ "title": "Research artifacts",+ "subtitle": "Save and reuse evidence-backed analyses across sessions without overwriting earlier revisions.",+ "searchPlaceholder": "Search subject, universe, or content",+ "emptyTitle": "No research artifacts yet",+ "emptyHint": "Save an analysis to reuse its conclusions and evidence in a later session.",+ "newResearch": "New research",+ "formTitleNew": "Save research",+ "formTitleRevision": "Create a linked revision",+ "subject": "Research subject",+ "universe": "Universe (optional)",+ "dataAsOf": "Data as of",+ "verification": "Verification",+ "completeness": "Completeness",+ "content": "Research content",+ "additionalEvidence": "Additional evidence URIs (one per line)",+ "optionalLinks": "Optional linked IDs",+ "evidenceMissing": "No evidence references attached",+ "history": "Revision history",+ "revise": "Revise from this revision",+ "save": "Save research",+ "saving": "Saving...",+ "createdNotice": "Created revision {{id}}.",+ "idempotentNotice": "Identical content and provenance already exist in {{id}}.",+ "close": "Close",+ "loadError": "Unable to load research artifacts.",- "saveError": "Unable to save the research artifact."++ "saveError": "Unable to save the research artifact.",++ "evidence": "Evidence references",++ "hypothesis_id": "Hypothesis ID",++ "goal_id": "Goal ID",++ "session_id": "Session ID",++ "run_id": "Run ID"+ },"runtime": {"monitorBadge": "Runtime Monitor","title": "Live / Paper Runtime Status",diff --cc frontend/src/i18n/locales/es.jsonindex 07ea48276,4ebba1f2c..59d83c8c3--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@@ -73,7 -75,36 +75,41 @@@"about": "Acerca de","sessionsLoadFailed": "No se pueden cargar las conversaciones.","pixelOffice": "Oficina de píxeles",- "paperTrading": "Trading simulado"+ "paperTrading": "Trading simulado",+ "researchArtifacts": "Artefactos de investigación"+ },+ "researchArtifacts": {+ "subject": "Tema de investigación",+ "dataAsOf": "Datos a fecha de",+ "saving": "Guardando…",+ "saveError": "No se pudo guardar el artefacto de investigación.",+ "evidenceMissing": "No hay referencias de evidencia",+ "createdNotice": "Revisión {{id}} creada.",+ "emptyHint": "Guarda un análisis para reutilizar sus conclusiones y evidencia en otra sesión.",+ "emptyTitle": "Aún no hay artefactos de investigación",+ "save": "Guardar investigación",+ "universe": "Universo (opcional)",+ "loadError": "No se pudieron cargar los artefactos de investigación.",+ "formTitleNew": "Guardar investigación",+ "verification": "Verificación",+ "additionalEvidence": "URI de evidencia adicionales (una por línea)",+ "revise": "Revisar a partir de esta revisión",+ "completeness": "Integridad",+ "searchPlaceholder": "Buscar tema, universo o contenido",+ "newResearch": "Nueva investigación",+ "formTitleRevision": "Crear revisión vinculada",+ "content": "Contenido de la investigación",+ "subtitle": "Reutiliza análisis respaldados por evidencia entre sesiones sin sobrescribir revisiones anteriores.",+ "history": "Historial de revisiones",+ "optionalLinks": "ID vinculados opcionales",+ "title": "Artefactos de investigación",+ "close": "Cerrar",- "idempotentNotice": "El mismo contenido y procedencia ya existen en {{id}}."++ "idempotentNotice": "El mismo contenido y procedencia ya existen en {{id}}.",++ "evidence": "Referencias de evidencia",++ "hypothesis_id": "ID de hipótesis",++ "goal_id": "ID de objetivo",++ "session_id": "ID de sesión",++ "run_id": "ID de ejecución"},"runtime": {"monitorBadge": "Monitor de Runtime",diff --cc frontend/src/i18n/locales/fa.jsonindex a8086ce2a,4a30d2219..b59fbfe7d--- a/frontend/src/i18n/locales/fa.json+++ b/frontend/src/i18n/locales/fa.json@@@ -73,7 -75,36 +75,41 @@@"about": "درباره","sessionsLoadFailed": "گفتگوها بارگذاری نمیشوند.","pixelOffice": "دفتر پیکسلی",- "paperTrading": "معاملهٔ آزمایشی"+ "paperTrading": "معاملهٔ آزمایشی",+ "researchArtifacts": "خروجیهای پژوهش"+ },+ "researchArtifacts": {+ "completeness": "کمال",+ "optionalLinks": "شناسههای پیوندی اختیاری",+ "formTitleNew": "ذخیره پژوهش",+ "verification": "وضعیت راستیآزمایی",+ "subject": "موضوع پژوهش",+ "createdNotice": "بازبینی {{id}} ایجاد شد.",+ "emptyHint": "یک تحلیل ذخیره کنید تا نتایج و شواهد آن را در نشستهای بعدی دوباره استفاده کنید.",+ "newResearch": "پژوهش جدید",+ "emptyTitle": "هنوز خروجی پژوهشی وجود ندارد",+ "save": "ذخیره پژوهش",+ "evidenceMissing": "هیچ مرجع شاهدی پیوست نشده است",+ "saveError": "خروجی پژوهش ذخیره نشد.",+ "additionalEvidence": "URIهای شواهد بیشتر (در هر خط یکی)",+ "subtitle": "تحلیلهای مبتنی بر شواهد را بدون بازنویسی بازبینیهای قبلی، میان نشستها دوباره استفاده کنید.",+ "revise": "بازبینی بر اساس این بازبینی",+ "history": "تاریخچه بازبینیها",+ "searchPlaceholder": "جستجوی موضوع، حوزه یا محتوا",+ "loadError": "خروجیهای پژوهش بارگیری نشد.",+ "close": "بستن",+ "universe": "حوزه (اختیاری)",+ "title": "خروجیهای پژوهش",+ "dataAsOf": "دادهها تا تاریخ",+ "content": "محتوای پژوهش",+ "saving": "در حال ذخیره…",+ "idempotentNotice": "محتوا و اطلاعات منشأ یکسان از قبل در {{id}} وجود دارد.",- "formTitleRevision": "ایجاد بازبینی پیوندی"++ "formTitleRevision": "ایجاد بازبینی پیوندی",++ "evidence": "ارجاعات شواهد",++ "hypothesis_id": "شناسه فرضیه",++ "goal_id": "شناسه هدف",++ "session_id": "شناسه نشست",++ "run_id": "شناسه اجرا"},"runtime": {"monitorBadge": "مانیتور رانتایم",diff --cc frontend/src/i18n/locales/id.jsonindex 561533fce,81edcdd0f..151276e20--- a/frontend/src/i18n/locales/id.json+++ b/frontend/src/i18n/locales/id.json@@@ -73,7 -75,36 +75,41 @@@"about": "Tentang","sessionsLoadFailed": "Percakapan tidak dapat dimuat.","pixelOffice": "Kantor piksel",- "paperTrading": "Trading simulasi"+ "paperTrading": "Trading simulasi",+ "researchArtifacts": "Artefak riset"+ },+ "researchArtifacts": {+ "completeness": "Kelengkapan",+ "optionalLinks": "ID tertaut opsional",+ "formTitleNew": "Simpan riset",+ "verification": "Verifikasi",+ "subject": "Subjek riset",+ "createdNotice": "Revisi {{id}} dibuat.",+ "emptyHint": "Simpan analisis untuk menggunakan kembali kesimpulan dan buktinya di sesi berikutnya.",+ "newResearch": "Riset baru",+ "emptyTitle": "Belum ada artefak riset",+ "save": "Simpan riset",+ "evidenceMissing": "Tidak ada referensi bukti terlampir",+ "saveError": "Tidak dapat menyimpan artefak riset.",+ "additionalEvidence": "URI bukti tambahan (satu per baris)",+ "subtitle": "Gunakan kembali analisis berbasis bukti antarsesi tanpa menimpa revisi sebelumnya.",+ "revise": "Revisi dari revisi ini",+ "history": "Riwayat revisi",+ "searchPlaceholder": "Cari subjek, universe, atau konten",+ "loadError": "Tidak dapat memuat artefak riset.",+ "close": "Tutup",+ "universe": "Universe (opsional)",+ "title": "Artefak riset",+ "dataAsOf": "Data per",+ "content": "Konten riset",+ "saving": "Menyimpan…",+ "idempotentNotice": "Konten dan asal-usul yang sama sudah ada di {{id}}.",- "formTitleRevision": "Buat revisi tertaut"++ "formTitleRevision": "Buat revisi tertaut",++ "evidence": "Referensi bukti",++ "hypothesis_id": "ID hipotesis",++ "goal_id": "ID tujuan",++ "session_id": "ID sesi",++ "run_id": "ID proses"},"runtime": {"monitorBadge": "Monitor Runtime",diff --cc frontend/src/i18n/locales/ja.jsonindex 8ea25da0f,571da1a93..b2362a0ef--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@@ -67,7 -69,36 +69,41 @@@"about": "概要","sessionsLoadFailed": "会話を読み込めません。","pixelOffice": "ピクセルオフィス",- "paperTrading": "模擬取引"+ "paperTrading": "模擬取引",+ "researchArtifacts": "リサーチ成果物"+ },+ "researchArtifacts": {+ "subject": "研究主題",+ "dataAsOf": "データ基準日",+ "saving": "保存中…",+ "saveError": "リサーチ成果物を保存できません。",+ "evidenceMissing": "証拠参照がありません",+ "createdNotice": "リビジョン {{id}} を作成しました。",+ "emptyHint": "分析を保存すると、後のセッションで結論と証拠を再利用できます。",+ "emptyTitle": "リサーチ成果物はまだありません",+ "save": "リサーチを保存",+ "universe": "ユニバース(任意)",+ "loadError": "リサーチ成果物を読み込めません。",+ "formTitleNew": "リサーチを保存",+ "verification": "検証状態",+ "additionalEvidence": "追加の証拠 URI(1行に1件)",+ "revise": "このリビジョンから新しいリビジョンを作成",+ "completeness": "完全性",+ "searchPlaceholder": "主題・ユニバース・本文を検索",+ "newResearch": "新規リサーチ",+ "formTitleRevision": "関連リビジョンを作成",+ "content": "研究本文",+ "subtitle": "証拠に基づく分析をセッション間で再利用し、過去のリビジョンを上書きしません。",+ "history": "リビジョン履歴",+ "optionalLinks": "任意の関連 ID",+ "title": "リサーチ成果物",+ "close": "閉じる",- "idempotentNotice": "同一の内容と 出典情報 は {{id}} に既に存在します。"++ "idempotentNotice": "同一の内容と 出典情報 は {{id}} に既に存在します。",++ "evidence": "根拠資料",++ "hypothesis_id": "仮説 ID",++ "goal_id": "目標 ID",++ "session_id": "セッション ID",++ "run_id": "実行 ID"},"runtime": {"monitorBadge": "取引モニター",diff --cc frontend/src/i18n/locales/ko.jsonindex 9fba21b21,f7edbbe99..3506f870a--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@@ -67,7 -69,36 +69,41 @@@"about": "소개","sessionsLoadFailed": "대화를 불러올 수 없습니다.","pixelOffice": "픽셀 오피스",- "paperTrading": "모의 거래"+ "paperTrading": "모의 거래",+ "researchArtifacts": "연구 산출물"+ },+ "researchArtifacts": {+ "completeness": "완전성",+ "optionalLinks": "선택적 연결 ID",+ "formTitleNew": "연구 저장",+ "verification": "검증 상태",+ "subject": "연구 주제",+ "createdNotice": "리비전 {{id}}을(를) 만들었습니다.",+ "emptyHint": "분석을 저장하면 이후 세션에서 결론과 근거를 재사용할 수 있습니다.",+ "newResearch": "새 연구",+ "emptyTitle": "아직 연구 산출물이 없습니다",+ "save": "연구 저장",+ "evidenceMissing": "첨부된 증거 참조가 없습니다",+ "saveError": "연구 산출물을 저장하지 못했습니다.",+ "additionalEvidence": "추가 증거 URI(줄당 하나)",+ "subtitle": "이전 리비전을 덮어쓰지 않고 근거 기반 분석을 세션 간에 재사용합니다.",+ "revise": "이 리비전을 바탕으로 수정",+ "history": "리비전 기록",+ "searchPlaceholder": "주제, 유니버스 또는 내용 검색",+ "loadError": "연구 산출물을 불러오지 못했습니다.",+ "close": "닫기",+ "universe": "유니버스(선택 사항)",+ "title": "연구 산출물",+ "dataAsOf": "데이터 기준일",+ "content": "연구 내용",+ "saving": "저장 중…",+ "idempotentNotice": "동일한 내용과 출처 정보가 {{id}}에 이미 있습니다.",- "formTitleRevision": "연결된 리비전 만들기"++ "formTitleRevision": "연결된 리비전 만들기",++ "evidence": "근거 자료",++ "hypothesis_id": "가설 ID",++ "goal_id": "목표 ID",++ "session_id": "세션 ID",++ "run_id": "실행 ID"},"runtime": {"monitorBadge": "거래 모니터",diff --cc frontend/src/i18n/locales/pt-BR.jsonindex e439dcba8,ed036312b..da0f6d60a--- a/frontend/src/i18n/locales/pt-BR.json+++ b/frontend/src/i18n/locales/pt-BR.json@@@ -73,7 -75,36 +75,41 @@@"about": "Sobre","sessionsLoadFailed": "Não foi possível carregar as conversas.","pixelOffice": "Escritório pixel",- "paperTrading": "Negociação simulada"+ "paperTrading": "Negociação simulada",+ "researchArtifacts": "Artefatos de pesquisa"+ },+ "researchArtifacts": {+ "subject": "Assunto da pesquisa",+ "dataAsOf": "Dados em",+ "saving": "Salvando…",+ "saveError": "Não foi possível salvar o artefato de pesquisa.",+ "evidenceMissing": "Nenhuma referência de evidência anexada",+ "createdNotice": "Revisão {{id}} criada.",+ "emptyHint": "Salve uma análise para reutilizar suas conclusões e evidências em outra sessão.",+ "emptyTitle": "Ainda não há artefatos de pesquisa",+ "save": "Salvar pesquisa",+ "universe": "Universo (opcional)",+ "loadError": "Não foi possível carregar os artefatos de pesquisa.",+ "formTitleNew": "Salvar pesquisa",+ "verification": "Verificação",+ "additionalEvidence": "URIs de evidência adicionais (uma por linha)",+ "revise": "Revisar a partir desta revisão",+ "completeness": "Completude",+ "searchPlaceholder": "Pesquisar assunto, universo ou conteúdo",+ "newResearch": "Nova pesquisa",+ "formTitleRevision": "Criar revisão vinculada",+ "content": "Conteúdo da pesquisa",+ "subtitle": "Reutilize análises baseadas em evidências entre sessões sem sobrescrever revisões anteriores.",+ "history": "Histórico de revisões",+ "optionalLinks": "IDs vinculados opcionais",+ "title": "Artefatos de pesquisa",+ "close": "Fechar",- "idempotentNotice": "Conteúdo e proveniência idênticos já existem em {{id}}."++ "idempotentNotice": "Conteúdo e proveniência idênticos já existem em {{id}}.",++ "evidence": "Referências de evidências",++ "hypothesis_id": "ID da hipótese",++ "goal_id": "ID do objetivo",++ "session_id": "ID da sessão",++ "run_id": "ID da execução"},"runtime": {"monitorBadge": "Monitor de Runtime",diff --cc frontend/src/i18n/locales/tr.jsonindex ada3049bb,efe22c9d4..71f1c9a4b--- a/frontend/src/i18n/locales/tr.json+++ b/frontend/src/i18n/locales/tr.json@@@ -37,7 -37,36 +37,41 @@@"about": "Hakkında","sessionsLoadFailed": "Konuşmalar yüklenemiyor.","pixelOffice": "Piksel Ofis",- "paperTrading": "Sanal işlem"+ "paperTrading": "Sanal işlem",+ "researchArtifacts": "Araştırma çıktıları"+ },+ "researchArtifacts": {+ "completeness": "Tamlık",+ "optionalLinks": "İsteğe bağlı bağlantılı kimlikler",+ "formTitleNew": "Araştırmayı kaydet",+ "verification": "Doğrulama",+ "subject": "Araştırma konusu",+ "createdNotice": "{{id}} revizyonu oluşturuldu.",+ "emptyHint": "Sonraki oturumlarda sonuçlarını ve kanıtlarını yeniden kullanmak için bir analiz kaydedin.",+ "newResearch": "Yeni araştırma",+ "emptyTitle": "Henüz araştırma çıktısı yok",+ "save": "Araştırmayı kaydet",+ "evidenceMissing": "Kanıt referansı eklenmemiş",+ "saveError": "Araştırma çıktısı kaydedilemedi.",+ "additionalEvidence": "Ek kanıt URI’leri (satır başına bir)",+ "subtitle": "Önceki revizyonların üzerine yazmadan kanıta dayalı analizleri oturumlar arasında yeniden kullanın.",+ "revise": "Bu revizyondan yola çıkarak düzenle",+ "history": "Revizyon geçmişi",+ "searchPlaceholder": "Konu, evren veya içerik ara",+ "loadError": "Araştırma çıktıları yüklenemedi.",+ "close": "Kapat",+ "universe": "Evren (isteğe bağlı)",+ "title": "Araştırma çıktıları",+ "dataAsOf": "Veri tarihi",+ "content": "Araştırma içeriği",+ "saving": "Kaydediliyor…",+ "idempotentNotice": "Aynı içerik ve kaynak bilgisi {{id}} içinde zaten var.",- "formTitleRevision": "Bağlantılı revizyon oluştur"++ "formTitleRevision": "Bağlantılı revizyon oluştur",++ "evidence": "Kanıt referansları",++ "hypothesis_id": "Hipotez kimliği",++ "goal_id": "Hedef kimliği",++ "session_id": "Oturum kimliği",++ "run_id": "Çalıştırma kimliği"},"runtime": {"monitorBadge": "Çalışma durumu izleyicisi",diff --cc frontend/src/i18n/locales/zh-CN.jsonindex 271e03435,a0d65546f..7db051a97--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@@ -67,7 -69,36 +69,41 @@@"about": "关于","sessionsLoadFailed": "无法加载会话。","pixelOffice": "像素办公室",- "paperTrading": "模拟交易"+ "paperTrading": "模拟交易",+ "researchArtifacts": "研究资料"+ },+ "researchArtifacts": {+ "subject": "研究主题",+ "dataAsOf": "数据截至",+ "saving": "正在保存…",+ "saveError": "无法保存研究资料。",+ "evidenceMissing": "未附证据引用",+ "createdNotice": "已创建修订 {{id}}。",+ "emptyHint": "保存一份分析,在以后的会话中复用其中的结论和证据。",+ "emptyTitle": "还没有研究资料",+ "save": "保存研究",+ "universe": "研究范围(可选)",+ "loadError": "无法加载研究资料。",+ "formTitleNew": "保存研究",+ "verification": "验证状态",+ "additionalEvidence": "新增证据 URI(每行一个)",+ "revise": "基于此修订继续修订",+ "completeness": "完整程度",+ "searchPlaceholder": "搜索主题、范围或正文",+ "newResearch": "新建研究",+ "formTitleRevision": "创建关联修订",+ "content": "研究正文",+ "subtitle": "跨会话保存并复用有证据支持的分析,不覆盖历史修订。",+ "history": "修订历史",+ "optionalLinks": "可选关联 ID",+ "title": "研究资料",+ "close": "关闭",- "idempotentNotice": "相同内容和来源信息已存在于 {{id}}。"++ "idempotentNotice": "相同内容和来源信息已存在于 {{id}}。",++ "evidence": "证据引用",++ "hypothesis_id": "假设 ID",++ "goal_id": "目标 ID",++ "session_id": "会话 ID",++ "run_id": "运行 ID"},"runtime": {"monitorBadge": "交易监控",diff --cc frontend/src/pages/ResearchArtifacts.tsxindex 000000000,127c4b87c..0d206a2eemode 000000,100644..100644--- a/frontend/src/pages/ResearchArtifacts.tsx+++ b/frontend/src/pages/ResearchArtifacts.tsx@@@ -1,0 -1,259 +1,270 @@@+ import { useEffect, useState, type FormEvent } from "react";+ import { useTranslation } from "react-i18next";+ import { AlertTriangle, FilePlus2, Loader2, RefreshCw, Search } from "lucide-react";+ import {+ api,+ type ResearchArtifactRevision,+ type ResearchArtifactSaveResult,+ type SaveResearchArtifactRequest,+ } from "@/lib/api";++ interface ArtifactForm {+ artifact_id?: string;+ subject: string;+ universe: string;+ content: string;+ data_as_of: string;+ verification_status: string;+ completeness: string;+ hypothesis_id: string;+ goal_id: string;+ session_id: string;+ run_id: string;+ newEvidence: string;+ existingEvidence?: ResearchArtifactRevision["evidence"];+ }++ function blankForm(): ArtifactForm {++ const today = new Date();+ return {+ subject: "",+ universe: "",+ content: "",- data_as_of: new Date().toISOString().slice(0, 10),++ data_as_of: [today.getFullYear(), String(today.getMonth() + 1).padStart(2, "0"), String(today.getDate()).padStart(2, "0")].join("-"),+ verification_status: "unverified",+ completeness: "complete",+ hypothesis_id: "",+ goal_id: "",+ session_id: "",+ run_id: "",+ newEvidence: "",+ };+ }++ function revisionForm(revision: ResearchArtifactRevision): ArtifactForm {+ return {+ artifact_id: revision.artifact_id,+ subject: revision.subject,+ universe: revision.universe,+ content: revision.content,+ data_as_of: revision.data_as_of,+ verification_status: revision.verification_status,+ completeness: revision.completeness,+ hypothesis_id: revision.hypothesis_id || "",+ goal_id: revision.goal_id || "",+ session_id: revision.session_id || "",+ run_id: revision.run_id || "",+ newEvidence: "",+ existingEvidence: revision.evidence,+ };+ }++ function evidenceFromText(text: string): Array<Record<string, unknown>> {+ return text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((source_uri) => ({ source_uri }));+ }++ export function ResearchArtifacts() {+ const { t } = useTranslation();+ const [artifacts, setArtifacts] = useState<ResearchArtifactRevision[]>([]);+ const [detail, setDetail] = useState<{ artifact: ResearchArtifactRevision; revisions: ResearchArtifactRevision[] } | null>(null);+ const [form, setForm] = useState<ArtifactForm>(blankForm);+ const [query, setQuery] = useState("");+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [notice, setNotice] = useState<string | null>(null);++ async function loadArtifacts(search = "") {+ setLoading(true);+ setError(null);+ try {+ const result = await api.searchResearchArtifacts(search ? { query: search } : {});+ setArtifacts(result.artifacts);+ } catch (err) {+ setError(err instanceof Error ? err.message : t("researchArtifacts.loadError"));+ } finally {+ setLoading(false);+ }+ }++ useEffect(() => {+ void loadArtifacts();+ }, []);++ async function openArtifact(artifactId: string) {+ setError(null);+ try {+ setDetail(await api.getResearchArtifact(artifactId));+ } catch (err) {+ setError(err instanceof Error ? err.message : t("researchArtifacts.loadError"));+ }+ }++ function update<Key extends keyof ArtifactForm>(key: Key, value: ArtifactForm[Key]) {- setForm((current) => ({ ...current, [key]: value }));++ setForm((current) => ({++ ...current, [key]: value,++ ...(current.artifact_id && ["content", "data_as_of", "newEvidence"].includes(key)++ ? { verification_status: "unverified" } : {}),++ }));+ }++ async function save(event: FormEvent) {+ event.preventDefault();+ setSaving(true);+ setError(null);+ setNotice(null);+ try {+ const newEvidence = evidenceFromText(form.newEvidence);+ const body: SaveResearchArtifactRequest = {+ artifact_id: form.artifact_id,+ subject: form.subject,+ universe: form.universe,+ content: form.content,+ data_as_of: form.data_as_of,+ verification_status: form.verification_status,+ completeness: form.completeness,+ hypothesis_id: form.hypothesis_id || undefined,+ goal_id: form.goal_id || undefined,+ session_id: form.session_id || undefined,+ run_id: form.run_id || undefined,+ };+ if (form.existingEvidence || newEvidence.length) {+ body.evidence = [...(form.existingEvidence || []), ...newEvidence];+ }+ const result: ResearchArtifactSaveResult = await api.saveResearchArtifact(body);+ const id = result.revision.revision_id;+ setNotice(t(result.created ? "researchArtifacts.createdNotice" : "researchArtifacts.idempotentNotice", { id }));+ setForm(revisionForm(result.revision));+ await Promise.all([loadArtifacts(query.trim()), openArtifact(result.revision.artifact_id)]);+ } catch (err) {+ setError(err instanceof Error ? err.message : t("researchArtifacts.saveError"));+ } finally {+ setSaving(false);+ }+ }++ return (+ <div className="min-h-screen p-6 lg:p-8">+ <div className="mx-auto flex w-full max-w-7xl flex-col gap-6">+ <section className="flex flex-wrap items-end justify-between gap-4 border-b pb-6">+ <div>+ <h1 className="text-2xl font-semibold tracking-tight">{t("researchArtifacts.title")}</h1>+ <p className="mt-2 max-w-3xl text-sm text-muted-foreground">{t("researchArtifacts.subtitle")}</p>+ </div>+ <div className="flex gap-2">+ <button type="button" className="rounded-md border px-3 py-2 text-sm" onClick={() => setForm(blankForm())}>+ <FilePlus2 className="me-2 inline h-4 w-4" />{t("researchArtifacts.newResearch")}+ </button>+ <button type="button" className="rounded-md border px-3 py-2 text-sm" disabled={loading} onClick={() => void loadArtifacts(query.trim())}>+ <RefreshCw className={`me-2 inline h-4 w-4 ${loading ? "animate-spin" : ""}`} />{t("reports.refresh")}+ </button>+ </div>+ </section>++ <form className="flex gap-2" onSubmit={(event) => { event.preventDefault(); void loadArtifacts(query.trim()); }}>+ <label className="relative flex-1">+ <Search className="absolute start-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />+ <input className="w-full rounded-md border bg-background py-2 ps-9 pe-3 text-sm" value={query} onChange={(event) => setQuery(event.target.value)} placeholder={t("researchArtifacts.searchPlaceholder")} />+ </label>+ <button type="submit" className="rounded-md border px-4 py-2 text-sm">{t("alphaZoo.search")}</button>+ </form>++ {error && <div role="alert" className="rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">{error}</div>}+ {notice && <div role="status" className="rounded-md border border-emerald-500/40 bg-emerald-500/10 p-3 text-sm">{notice}</div>}++ <div className="grid gap-6 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.7fr)]">+ <div className="space-y-4">+ {loading && <div className="flex justify-center p-8"><Loader2 className="h-5 w-5 animate-spin" /></div>}+ {!loading && artifacts.length === 0 && (+ <section className="rounded-lg border border-dashed p-8 text-center">+ <h2 className="font-medium">{t("researchArtifacts.emptyTitle")}</h2>+ <p className="mt-2 text-sm text-muted-foreground">{t("researchArtifacts.emptyHint")}</p>+ </section>+ )}+ {artifacts.map((item) => (+ <button key={item.artifact_id} type="button" onClick={() => void openArtifact(item.artifact_id)} className="w-full rounded-lg border p-4 text-start transition hover:bg-muted/50">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h2 className="font-medium">{item.subject}</h2>+ <span className="text-xs text-muted-foreground">r{item.revision_number}</span>+ </div>+ <div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">+ {item.universe && <span>{item.universe}</span>}+ <span>{t("researchArtifacts.dataAsOf")}: {item.data_as_of}</span>+ <span>{t("researchArtifacts.verification")}: {item.verification_status}</span>+ </div>+ {item.evidence_missing && <div className="mt-2 flex items-center gap-1 text-xs text-amber-600"><AlertTriangle className="h-3.5 w-3.5" />{t("researchArtifacts.evidenceMissing")}</div>}+ </button>+ ))}++ {detail && (+ <section className="rounded-lg border p-4">+ <div className="flex items-start justify-between gap-3">+ <div>+ <h2 className="font-medium">{detail.artifact.subject}</h2>+ <p className="mt-1 text-xs text-muted-foreground">{detail.artifact.artifact_id}</p>+ </div>+ <button type="button" className="text-sm text-muted-foreground" onClick={() => setDetail(null)}>{t("researchArtifacts.close")}</button>+ </div>+ <pre className="mt-4 max-h-96 overflow-auto whitespace-pre-wrap rounded-md bg-muted/40 p-3 font-sans text-sm">{detail.artifact.content}</pre>++ <details className="mt-3 text-sm">++ <summary className="cursor-pointer">{t("researchArtifacts.evidence")}</summary>++ <pre className="mt-2 overflow-auto whitespace-pre-wrap">{JSON.stringify(detail.artifact.evidence, null, 2)}</pre>++ </details>+ <button type="button" className="mt-3 rounded-md border px-3 py-1.5 text-sm" onClick={() => setForm(revisionForm(detail.artifact))}>{t("researchArtifacts.revise")}</button>+ <h3 className="mt-5 text-sm font-medium">{t("researchArtifacts.history")}</h3>+ <div className="mt-2 space-y-2">+ {detail.revisions.map((revision) => (+ <details key={revision.revision_id} className="rounded-md border p-3 text-sm">+ <summary className="cursor-pointer">r{revision.revision_number} · {revision.data_as_of} · {revision.created_at}</summary>+ <pre className="mt-3 whitespace-pre-wrap font-sans text-muted-foreground">{revision.content}</pre>++ <p className="mt-2 text-xs text-muted-foreground">{t("researchArtifacts.verification")}: {revision.verification_status}</p>++ <pre className="mt-2 overflow-auto whitespace-pre-wrap text-xs">{JSON.stringify(revision.evidence, null, 2)}</pre>+ </details>+ ))}+ </div>+ </section>+ )}+ </div>++ <form className="space-y-3 rounded-lg border p-4" onSubmit={(event) => void save(event)}>+ <h2 className="font-medium">{t(form.artifact_id ? "researchArtifacts.formTitleRevision" : "researchArtifacts.formTitleNew")}</h2>+ <label className="block text-sm">{t("researchArtifacts.subject")}+ <input required className="mt-1 w-full rounded-md border bg-background px-3 py-2" disabled={Boolean(form.artifact_id)} value={form.subject} onChange={(event) => update("subject", event.target.value)} />+ </label>+ <label className="block text-sm">{t("researchArtifacts.universe")}+ <input className="mt-1 w-full rounded-md border bg-background px-3 py-2" disabled={Boolean(form.artifact_id)} value={form.universe} onChange={(event) => update("universe", event.target.value)} />+ </label>+ <label className="block text-sm">{t("researchArtifacts.dataAsOf")}- <input required type="date" className="mt-1 w-full rounded-md border bg-background px-3 py-2" value={form.data_as_of} onChange={(event) => update("data_as_of", event.target.value)} />++ <input required className="mt-1 w-full rounded-md border bg-background px-3 py-2" value={form.data_as_of} onChange={(event) => update("data_as_of", event.target.value)} />+ </label>+ <label className="block text-sm">{t("researchArtifacts.content")}+ <textarea required rows={7} className="mt-1 w-full rounded-md border bg-background px-3 py-2" value={form.content} onChange={(event) => update("content", event.target.value)} />+ </label>+ <div className="grid grid-cols-2 gap-3">+ <label className="block text-sm">{t("researchArtifacts.verification")}+ <input className="mt-1 w-full rounded-md border bg-background px-3 py-2" value={form.verification_status} onChange={(event) => update("verification_status", event.target.value)} />+ </label>+ <label className="block text-sm">{t("researchArtifacts.completeness")}+ <input className="mt-1 w-full rounded-md border bg-background px-3 py-2" value={form.completeness} onChange={(event) => update("completeness", event.target.value)} />+ </label>+ </div>+ <label className="block text-sm">{t("researchArtifacts.additionalEvidence")}+ <textarea rows={3} className="mt-1 w-full rounded-md border bg-background px-3 py-2" value={form.newEvidence} onChange={(event) => update("newEvidence", event.target.value)} />+ </label>+ <details className="text-sm">+ <summary className="cursor-pointer">{t("researchArtifacts.optionalLinks")}</summary>+ <div className="mt-2 grid grid-cols-2 gap-2">+ {(["hypothesis_id", "goal_id", "session_id", "run_id"] as const).map((key) => (- <input key={key} aria-label={key} placeholder={key} className="rounded-md border bg-background px-3 py-2" value={form[key]} onChange={(event) => update(key, event.target.value)} />++ <input key={key} aria-label={t(`researchArtifacts.${key}`)} placeholder={t(`researchArtifacts.${key}`)} className="rounded-md border bg-background px-3 py-2" value={form[key]} onChange={(event) => update(key, event.target.value)} />+ ))}+ </div>+ </details>+ <button type="submit" disabled={saving} className="w-full rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50">+ {saving ? t("researchArtifacts.saving") : t("researchArtifacts.save")}+ </button>+ </form>+ </div>+ </div>+ </div>+ );+ }diff --cc frontend/src/pages/__tests__/ResearchArtifacts.test.tsxindex 000000000,1796479b3..8d10c4c01mode 000000,100644..100644--- a/frontend/src/pages/__tests__/ResearchArtifacts.test.tsx+++ b/frontend/src/pages/__tests__/ResearchArtifacts.test.tsx@@@ -1,0 -1,95 +1,96 @@@+ import { fireEvent, render, screen, waitFor } from "@testing-library/react";+ import { MemoryRouter } from "react-router";+ import { ResearchArtifacts } from "../ResearchArtifacts";++ const apiMock = vi.hoisted(() => ({+ searchResearchArtifacts: vi.fn(),+ getResearchArtifact: vi.fn(),+ saveResearchArtifact: vi.fn(),+ }));++ vi.mock("@/lib/api", () => ({ api: apiMock }));++ const first = {+ revision_id: "ra_1_r1",+ artifact_id: "ra_1",+ revision_number: 1,+ previous_revision_id: null,+ subject: "NVDA fundamental review",+ universe: "NVDA",+ content: "Original conclusion.",+ content_hash: "old",+ provenance_hash: "old",+ identity_hash: "old",+ data_as_of: "2026-10-20",+ created_at: "2026-10-20T10:00:00Z",+ evidence: [{ source_uri: "https://example.com/old", content_hash: "abc" }],+ evidence_missing: false,+ verification_status: "verified",+ completeness: "complete",+ hypothesis_id: "hyp_1",+ goal_id: "goal_1",+ session_id: "session_1",+ run_id: "run_1",+ };+ const second = {+ ...first,+ revision_id: "ra_1_r2",+ revision_number: 2,+ previous_revision_id: "ra_1_r1",+ content: "Updated conclusion.",+ content_hash: "new",+ provenance_hash: "new",+ identity_hash: "new",+ data_as_of: "2026-10-27",+ created_at: "2026-10-27T10:00:00Z",+ };+ const third = {+ ...second,+ revision_id: "ra_1_r3",+ revision_number: 3,+ previous_revision_id: "ra_1_r2",+ };++ describe("ResearchArtifacts page", () => {+ beforeEach(() => {+ Object.values(apiMock).forEach((mock) => mock.mockReset());+ });++ it("shows an actionable empty state", async () => {+ apiMock.searchResearchArtifacts.mockResolvedValue({ count: 0, artifacts: [] });+ render(<ResearchArtifacts />, { wrapper: MemoryRouter });++ expect(await screen.findByText("No research artifacts yet")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "New research" })).toBeInTheDocument();+ });++ it("opens revision history and preserves existing evidence when revising", async () => {+ apiMock.searchResearchArtifacts.mockResolvedValue({ count: 1, artifacts: [second] });+ apiMock.getResearchArtifact.mockResolvedValue({ artifact: second, revisions: [second, first] });+ apiMock.saveResearchArtifact.mockResolvedValue({ revision: third, created: true });+ render(<ResearchArtifacts />, { wrapper: MemoryRouter });++ fireEvent.click(await screen.findByText("NVDA fundamental review"));+ expect(await screen.findByText("Revision history")).toBeInTheDocument();+ expect(screen.getByText("Original conclusion.")).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "Revise from this revision" }));+ fireEvent.change(screen.getByLabelText("Research content"), { target: { value: "Third conclusion." } });+ fireEvent.change(screen.getByLabelText("Additional evidence URIs (one per line)"), {+ target: { value: "https://example.com/new" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Save research" }));++ await waitFor(() => expect(apiMock.saveResearchArtifact).toHaveBeenCalledTimes(1));+ expect(apiMock.saveResearchArtifact).toHaveBeenCalledWith(expect.objectContaining({+ artifact_id: "ra_1",+ content: "Third conclusion.",++ verification_status: "unverified",+ evidence: [+ { source_uri: "https://example.com/old", content_hash: "abc" },+ { source_uri: "https://example.com/new" },+ ],+ }));+ expect(await screen.findByText("Created revision ra_1_r3.")).toBeInTheDocument();+ });+ });