Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(portfolio): read a stored snapshot by id and return read_identity

zeus2298b3a448fa1d7
diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.py
index 0ea354127..668bdc822 100644
--- a/agent/src/portfolio/service.py
+++ b/agent/src/portfolio/service.py
@@ -495,6 +495,24 @@ class PortfolioService:
]
return snapshot
+ def snapshot_by_id(self, snapshot_id: str) -> dict[str, Any] | None:
+ """Return one stored snapshot exactly as persisted, never recomputed.
+
+ Args:
+ snapshot_id: Exact persisted snapshot identifier.
+
+ Returns:
+ The stored envelope, or ``None`` when the id is unknown, was valued
+ under another contract version, or includes a source that is no
+ longer enabled (a removed or revoked connector's data stays hidden).
+ """
+ snapshot = self.store.get(snapshot_id)
+ if snapshot is None or snapshot.get("valuation_version") != PORTFOLIO_VALUATION_VERSION:
+ return None
+ enabled = {source.id for source in self.settings_store.load().sources if source.enabled}
+ observed = {str(account.get("source_id") or account.get("broker")) for account in snapshot.get("accounts", [])}
+ return snapshot if observed <= enabled else None
+
def reconnect_source(self, source_id: str) -> dict[str, Any]:
"""Run a source's interactive OAuth flow on explicit user request.
@@ -618,9 +636,13 @@ class PortfolioService:
writer.writerows(snapshot["positions"])
return output.getvalue()
- def analysis_context(self) -> dict[str, Any] | None:
+ def analysis_context(self, snapshot_id: str | None = None) -> dict[str, Any] | None:
"""Return a credential/account-id-free snapshot suitable for an LLM.
+ With ``snapshot_id`` the read is pinned to that stored snapshot (no
+ fallback to the latest one when it is unavailable); without it the
+ latest semantics are unchanged.
+
The context also carries ``risk_xray_args`` — the ``symbols`` and
``weights`` arguments for the existing ``portfolio_risk_xray`` tool.
The portfolio supplies that tool's arguments; it does not reimplement
@@ -629,7 +651,7 @@ class PortfolioService:
Returns:
The sanitized context, or ``None`` when no usable snapshot exists.
"""
- snapshot = self.latest()
+ snapshot = self.latest() if snapshot_id is None else self.snapshot_by_id(snapshot_id)
if snapshot is None:
return None
total = _decimal(snapshot["totals"]["usd"])
@@ -648,7 +670,14 @@ class PortfolioService:
}
)
return {
+ "snapshot_id": snapshot.get("snapshot_id"),
"as_of": snapshot["created_at"],
+ "read_identity": {
+ "mode": "latest" if snapshot_id is None else "pinned",
+ "snapshot_id": snapshot.get("snapshot_id"),
+ "as_of": snapshot["created_at"],
+ "valuation_version": snapshot.get("valuation_version"),
+ },
"complete": snapshot["complete"],
"totals": snapshot["totals"],
"account_allocation": [
diff --git a/agent/src/portfolio/store.py b/agent/src/portfolio/store.py
index 7b7549f36..3b199f16a 100644
--- a/agent/src/portfolio/store.py
+++ b/agent/src/portfolio/store.py
@@ -120,6 +120,22 @@ class PortfolioStore:
return payload
return None
+ def get(self, snapshot_id: str) -> dict[str, Any] | None:
+ """Return one immutable snapshot by id.
+
+ Args:
+ snapshot_id: Exact persisted snapshot identifier.
+
+ Returns:
+ The stored snapshot envelope, or None when the id is absent.
+ """
+ with self._connect() as db:
+ row = db.execute(
+ "SELECT payload FROM portfolio_snapshots WHERE id = ? LIMIT 1",
+ (str(snapshot_id),),
+ ).fetchone()
+ return json.loads(row["payload"]) if row else None
+
def history(
self,
limit: int = 180,
diff --git a/agent/src/tools/portfolio_tool.py b/agent/src/tools/portfolio_tool.py
index 09c1a74d4..4a0772792 100644
--- a/agent/src/tools/portfolio_tool.py
+++ b/agent/src/tools/portfolio_tool.py
@@ -22,22 +22,49 @@ class PortfolioSummaryTool(BaseTool):
"refresh is reported as an error and excluded from the totals, so a "
"snapshot with complete=false is missing accounts. It never returns "
"credentials, account numbers, order IDs, personal names, or local "
- "paths. Use the Web Portfolio refresh button before requesting current "
- "data."
+ "paths. The result carries snapshot_id and read_identity; pass that "
+ "snapshot_id back to keep a multi-step analysis on the same stored "
+ "observation after a later refresh. Use the Web Portfolio refresh button "
+ "before requesting current data."
)
- parameters = {"type": "object", "properties": {}, "required": []}
+ parameters = {
+ "type": "object",
+ "properties": {
+ "snapshot_id": {
+ "type": "string",
+ "description": (
+ "Optional id of a stored snapshot. When given, read exactly that "
+ "immutable observation instead of the latest one."
+ ),
+ },
+ },
+ "required": [],
+ }
repeatable = True
is_readonly = True
- def execute(self, **_: Any) -> str:
+ def execute(self, **kwargs: Any) -> str:
"""Return the sanitized portfolio context as a JSON envelope.
Returns:
- A JSON string with ``status`` ``ok`` and the context, or ``empty``
- with a hint when no usable snapshot exists.
+ A JSON string with ``status`` ``ok`` and the context, ``empty``
+ with a hint when no usable snapshot exists, or ``error`` when a
+ requested ``snapshot_id`` is unavailable.
"""
- context = PortfolioService().analysis_context()
+ raw_id = kwargs.get("snapshot_id")
+ snapshot_id = None if raw_id is None else str(raw_id).strip()
+ context = PortfolioService().analysis_context(snapshot_id=snapshot_id)
if context is None:
+ if snapshot_id is not None:
+ return json.dumps(
+ {
+ "status": "error",
+ "error_code": "snapshot_not_found",
+ "snapshot_id": snapshot_id,
+ "message": "The requested portfolio snapshot is unavailable or incompatible.",
+ },
+ ensure_ascii=False,
+ )
return json.dumps(
{
"status": "empty",
diff --git a/agent/tests/test_portfolio_service.py b/agent/tests/test_portfolio_service.py
index 718a6a760..078e8af87 100644
--- a/agent/tests/test_portfolio_service.py
+++ b/agent/tests/test_portfolio_service.py
@@ -837,3 +837,86 @@ def test_reconnect_contains_callback_server_system_exit(monkeypatch, tmp_path):
with pytest.raises(RuntimeError, match="stopped safely"):
_reconnect_service(tmp_path).reconnect_source("ibkr")
+
+
+def _pinned_service(tmp_path, nav):
+ accounts = {
+ "ibkr-live-local-readonly": {"summary": [{"tag": "NetLiquidation", "value": nav, "currency": "USD"}]},
+ "longbridge-live-sdk-readonly": {"balances": []},
+ "binance-live-sdk-readonly": {"balances": []},
+ }
+ positions = {
+ "ibkr-live-local-readonly": {
+ "positions": [
+ {"symbol": "AAPL", "sec_type": "STK", "exchange": "SMART", "currency": "USD", "position": 2, "avg_cost": 100}
+ ]
+ },
+ "longbridge-live-sdk-readonly": {"positions": []},
+ "binance-live-sdk-readonly": {"positions": []},
+ }
+ return PortfolioService(
+ PortfolioStore(tmp_path / "portfolio.sqlite3"),
+ settings_store=_settings_store(tmp_path),
+ get_account=lambda profile_id: accounts[profile_id],
+ get_positions=lambda profile_id: positions[profile_id],
+ get_quote=lambda symbol, profile_id, **kwargs: {"quote": {"last": 150}},
+ fx_fetcher=lambda: (Decimal("7.2"), Decimal("7.8"), "2026-08-09T00:00:00+00:00"),
+ ), accounts
+
+
+def test_analysis_context_can_be_pinned_to_a_stored_snapshot(tmp_path):
+ """A later refresh must not move a read that names its snapshot."""
+ service, accounts = _pinned_service(tmp_path, "300")
+ first = service.refresh()
+ accounts["ibkr-live-local-readonly"]["summary"][0]["value"] = "450"
+ second = service.refresh()
+ assert second["snapshot_id"] != first["snapshot_id"]
+
+ latest = service.analysis_context()
+ pinned = service.analysis_context(snapshot_id=first["snapshot_id"])
+
+ assert latest["snapshot_id"] == second["snapshot_id"]
+ assert latest["read_identity"]["mode"] == "latest"
+ assert pinned["snapshot_id"] == first["snapshot_id"]
+ assert pinned["read_identity"] == {
+ "mode": "pinned",
+ "snapshot_id": first["snapshot_id"],
+ "as_of": first["created_at"],
+ "valuation_version": first["valuation_version"],
+ }
+ assert pinned["totals"] == first["totals"]
+ assert pinned["totals"] != latest["totals"]
+ assert service.analysis_context(snapshot_id="missing") is None
+ assert service.analysis_context(snapshot_id="") is None
+
+
+def test_a_pinned_read_hides_a_snapshot_that_includes_a_disabled_source(tmp_path):
+ service, _ = _pinned_service(tmp_path, "300")
+ snapshot = service.refresh()
+ assert service.analysis_context(snapshot_id=snapshot["snapshot_id"]) is not None
+
+ settings = service.settings_store.load()
+ service.settings_store.save(
+ {
+ "display_currency": "USD",
+ "sources": [
+ {
+ "connection_id": source.connection_id,
+ "label": source.label,
+ "order": index,
+ "enabled": source.id != "ibkr",
+ }
+ for index, source in enumerate(settings.sources)
+ ],
+ }
+ )
+
+ assert service.analysis_context(snapshot_id=snapshot["snapshot_id"]) is None
+
+
+def test_a_pinned_read_refuses_a_snapshot_valued_under_another_contract(tmp_path):
+ service, _ = _pinned_service(tmp_path, "300")
+ snapshot = service.refresh()
+ service.store.save_snapshot({**snapshot, "snapshot_id": "old-contract", "valuation_version": 1})
+
+ assert service.analysis_context(snapshot_id="old-contract") is None
diff --git a/agent/tests/test_portfolio_summary_tool_snapshot.py b/agent/tests/test_portfolio_summary_tool_snapshot.py
new file mode 100644
index 000000000..8a06e97b2
--- /dev/null
+++ b/agent/tests/test_portfolio_summary_tool_snapshot.py
@@ -0,0 +1,29 @@
+"""portfolio_summary can read a stored snapshot by id."""
+
+from __future__ import annotations
+
+import json
+
+from src.tools.portfolio_tool import PortfolioSummaryTool
+
+
+def test_snapshot_id_reaches_the_service_and_an_unknown_id_fails_closed(monkeypatch):
+ seen = []
+
+ def fake_context(self, snapshot_id=None):
+ seen.append(snapshot_id)
+ return None if snapshot_id in {"gone", ""} else {"snapshot_id": snapshot_id or "latest-id"}
+
+ monkeypatch.setattr("src.portfolio.service.PortfolioService.analysis_context", fake_context)
+ tool = PortfolioSummaryTool()
+
+ assert json.loads(tool.execute())["context"]["snapshot_id"] == "latest-id"
+ assert json.loads(tool.execute(snapshot_id=" abc "))["context"]["snapshot_id"] == "abc"
+ missing = json.loads(tool.execute(snapshot_id="gone"))
+ blank = json.loads(tool.execute(snapshot_id=" "))
+
+ assert seen == [None, "abc", "gone", ""]
+ assert missing["status"] == "error"
+ assert missing["error_code"] == "snapshot_not_found"
+ assert blank["error_code"] == "snapshot_not_found"
+ assert "snapshot_id" in PortfolioSummaryTool.parameters["properties"]