Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(cli): add vibe-trading update self-upgrade command

zwrong061b86f0e9d9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index faeecb8b3..e6e69b16c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
+- **`vibe-trading update`** — new CLI subcommand that checks PyPI for a newer `vibe-trading-ai` release and upgrades in place via pip when one exists (no confirmation prompt). Editable/development installs and uninstalled checkouts are detected and answered with the right manual instruction (`git pull` + reinstall) instead of a pip upgrade that would silently replace the dev install with a released wheel.
- **Memory Tier 2: Structural Organization** — four independently-gated modules for memory lifecycle enhancement:
- H-MEM hierarchical directory routing (`VT_MEMORY_HIERARCHY`)
- A-MEM semantic linking via BM25 (`VT_MEMORY_LINKS`)
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 3ad12c04d..fca8ef24a 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -4714,6 +4714,10 @@ def _build_parser() -> argparse.ArgumentParser:
chat_parser = subparsers.add_parser("chat", help="Interactive chat mode")
chat_parser.add_argument("--max-iter", dest="chat_max_iter", type=int, default=50, help="Maximum agent iterations")
+ subparsers.add_parser(
+ "update", help="Check for and install the latest vibe-trading-ai release from PyPI"
+ )
+
subparsers.add_parser("init", help="Interactive setup: create ~/.vibe-trading/.env")
# Cross-platform frontend setup. See cmd_setup() for details.
@@ -5739,6 +5743,10 @@ def main(argv: list[str] | None = None) -> int:
return _coerce_exit_code(cmd_show(args.show))
if args.command == "chat":
return _coerce_exit_code(cmd_interactive(args.chat_max_iter))
+ if args.command == "update":
+ from cli.commands.update import cmd_update
+
+ return _coerce_exit_code(cmd_update())
if args.command == "alpha":
from src.factors.cli_handlers import dispatch as _alpha_dispatch
return _coerce_exit_code(_alpha_dispatch(args))
diff --git a/agent/cli/commands/update.py b/agent/cli/commands/update.py
new file mode 100644
index 000000000..4f9552286
--- /dev/null
+++ b/agent/cli/commands/update.py
@@ -0,0 +1,219 @@
+"""Self-update support: ``vibe-trading update``.
+
+Checks PyPI for a newer ``vibe-trading-ai`` release than the currently
+installed one and, when one exists, upgrades in place through ``pip`` using the
+same interpreter that is running the CLI (``sys.executable -m pip``, never a
+bare ``pip`` — the upgrade must target the interpreter that owns this CLI).
+
+Scope decision (see ``.trellis/tasks/08-07-add-update/prd.md``): v1 handles the
+PyPI-wheel install path only. Editable / git-checkout / Docker installs are
+detected and answered with the right manual instruction instead of a pip
+upgrade that would silently change the install type — ``pip install -U`` over
+an ``pip install -e .`` install replaces the editable dev install with a
+released wheel, which is a surprise nobody wants.
+
+Design rules:
+- Invoking ``vibe-trading update`` means "upgrade me": there is deliberately no
+ confirmation prompt (user decision, 2026-08-07).
+- Never downgrade: only upgrade when the latest PyPI version is strictly
+ greater than the installed one (PEP 440).
+- The upgrade runs in a subprocess; the current process has already imported
+ the old code, so success is verified by re-reading installed metadata from a
+ *fresh* subprocess.
+- On any check failure the local install is left untouched.
+- Docker is deliberately out of scope (user decision, 2026-08-07): inside a
+ container the answer would be `git pull && docker compose up --build`, but
+ detection is deferred.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+from importlib.metadata import PackageNotFoundError, distribution
+
+import requests
+from packaging.version import InvalidVersion, Version
+from rich.markup import escape as rich_escape
+
+from cli._version import __version__ as CURRENT_VERSION
+from cli.theme import get_console
+
+console = get_console()
+
+PACKAGE_NAME = "vibe-trading-ai"
+PYPI_JSON_URL = "https://pypi.org/pypi/vibe-trading-ai/json"
+PYPI_TIMEOUT_SECONDS = 15
+VERIFY_TIMEOUT_SECONDS = 60
+
+EXIT_OK = 0
+EXIT_FAILED = 1
+
+# Install-kind labels returned by :func:`detect_install_kind`.
+KIND_WHEEL = "wheel"
+KIND_EDITABLE = "editable"
+KIND_CHECKOUT = "checkout"
+
+
+def fetch_latest_version() -> str:
+ """Return the newest published version of ``vibe-trading-ai`` on PyPI.
+
+ Raises:
+ requests.RequestException: network / HTTP failures — the caller turns
+ this into a user-facing error and never touches the local install.
+ (KeyError, ValueError): malformed PyPI payload.
+ """
+ resp = requests.get(PYPI_JSON_URL, timeout=PYPI_TIMEOUT_SECONDS)
+ resp.raise_for_status()
+ return str(resp.json()["info"]["version"])
+
+
+def detect_install_kind() -> str:
+ """Classify how ``vibe-trading-ai`` is installed, cheapest signals first.
+
+ Returns one of the ``KIND_*`` constants:
+
+ - ``KIND_CHECKOUT``: not installed as a distribution at all — running from
+ a clone with ``PYTHONPATH=agent`` (``importlib.metadata`` raises).
+ - ``KIND_EDITABLE``: ``pip install -e .`` — either the modern marker
+ (``direct_url.json`` in the metadata dir with ``dir_info.editable``) or
+ the legacy marker (a source-tree ``*.egg-info`` dir on ``sys.path``).
+ - ``KIND_WHEEL``: anything else that resolves through importlib.metadata.
+
+ Why both markers? The metadata dir that ``distribution()`` resolves can be
+ the venv ``dist-info`` OR a source-tree ``*.egg-info`` depending on the
+ working directory (running ``python -m cli`` from ``agent/`` resolves to
+ ``agent/vibe_trading_ai.egg-info``, which carries no ``direct_url.json``).
+ ``read_text`` reads from whatever metadata dir was resolved, and the
+ egg-info check catches the legacy editable style on top of it.
+ """
+ try:
+ dist = distribution(PACKAGE_NAME)
+ except PackageNotFoundError:
+ return KIND_CHECKOUT
+
+ # Modern editable marker: direct_url.json with dir_info.editable, read
+ # straight from the resolved metadata dir (more reliable than dist.files,
+ # which is a RECORD listing that some egg-info dirs omit entirely).
+ direct_url = dist.read_text("direct_url.json")
+ if direct_url:
+ try:
+ parsed = json.loads(direct_url)
+ if isinstance(parsed, dict) and parsed.get("dir_info", {}).get("editable"):
+ return KIND_EDITABLE
+ except (ValueError, AttributeError):
+ return KIND_WHEEL # corrupt metadata; default to the pip path
+ return KIND_WHEEL
+
+ # Legacy editable marker: ``pip install -e .`` / ``python setup.py develop``
+ # leave ``<name>.egg-info`` in the project tree; wheel installs never do.
+ if _has_source_tree_egg_info():
+ return KIND_EDITABLE
+ return KIND_WHEEL
+
+
+def _has_source_tree_egg_info() -> bool:
+ """True if an egg-info dir for this package sits in a source tree on sys.path.
+
+ Returns:
+ Whether ``sys.path`` contains a directory holding ``<name>.egg-info``
+ for :data:`PACKAGE_NAME`.
+ """
+ normalized = PACKAGE_NAME.replace("-", "_")
+ for entry in sys.path:
+ base = entry if entry else os.getcwd()
+ if os.path.isdir(os.path.join(base, f"{normalized}.egg-info")):
+ return True
+ return False
+
+
+def cmd_update() -> int:
+ """Check PyPI and upgrade when a newer release exists. Returns exit code."""
+ try:
+ latest = fetch_latest_version()
+ except (requests.RequestException, KeyError, ValueError) as exc:
+ console.print(f"[red]Could not check for updates on PyPI:[/red] {rich_escape(str(exc))}")
+ return EXIT_FAILED
+
+ try:
+ newer = Version(latest) > Version(CURRENT_VERSION)
+ except InvalidVersion:
+ console.print(
+ f"[red]Could not compare versions[/red] (installed: {CURRENT_VERSION}, latest: {latest})."
+ )
+ return EXIT_FAILED
+
+ if not newer:
+ console.print(f"Already up to date ({CURRENT_VERSION}).")
+ return EXIT_OK
+
+ kind = detect_install_kind()
+ if kind == KIND_EDITABLE:
+ console.print(
+ f"[yellow]Editable/development install detected[/yellow] "
+ f"({CURRENT_VERSION} -> {latest} is available on PyPI).\n"
+ "This checkout is installed with `pip install -e .`, so a pip "
+ "upgrade would replace your dev install with the released wheel.\n"
+ "Update the checkout instead: run `git pull` in the repo and reinstall "
+ "(`pip install -e .`)."
+ )
+ return EXIT_OK
+ if kind == KIND_CHECKOUT:
+ console.print(
+ f"[yellow]Running from an uninstalled checkout[/yellow] "
+ f"({CURRENT_VERSION} -> {latest} is available on PyPI).\n"
+ "No pip-managed install found — update the checkout with `git pull`."
+ )
+ return EXIT_OK
+
+ return _pip_upgrade(latest)
+
+
+def _pip_upgrade(latest: str) -> int:
+ """Upgrade the wheel install in place via pip, then verify. Returns exit code."""
+ console.print(f"Upgrading {PACKAGE_NAME} {CURRENT_VERSION} -> {latest} ...")
+ proc = subprocess.run(
+ [sys.executable, "-m", "pip", "install", "--upgrade", PACKAGE_NAME],
+ text=True,
+ )
+ if proc.returncode != 0:
+ console.print(
+ "[red]Upgrade failed.[/red] Re-run `vibe-trading update` or inspect the pip output above."
+ )
+ return EXIT_FAILED
+ return _verify_upgrade(latest)
+
+
+def _verify_upgrade(expected: str) -> int:
+ """Re-read the installed version from a fresh process to confirm the upgrade."""
+ try:
+ proc = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ "from importlib.metadata import version; print(version('vibe-trading-ai'))",
+ ],
+ capture_output=True,
+ text=True,
+ timeout=VERIFY_TIMEOUT_SECONDS,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ console.print(f"[yellow]Upgrade ran but verification failed:[/yellow] {exc}")
+ return EXIT_FAILED
+
+ installed = proc.stdout.strip()
+ try:
+ confirmed = installed and Version(installed) >= Version(expected)
+ except InvalidVersion:
+ confirmed = False
+ if not confirmed:
+ console.print(
+ f"[yellow]Upgrade verification mismatch[/yellow] — expected {expected}, "
+ f"reported {rich_escape(installed or 'unknown')}. Check `vibe-trading --version`."
+ )
+ return EXIT_FAILED
+
+ console.print(f"Updated to {installed}. Run `vibe-trading --version` to confirm.")
+ return EXIT_OK
diff --git a/agent/tests/test_cli_update.py b/agent/tests/test_cli_update.py
new file mode 100644
index 000000000..6473406f5
--- /dev/null
+++ b/agent/tests/test_cli_update.py
@@ -0,0 +1,284 @@
+"""Tests for the ``vibe-trading update`` self-upgrade command."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+import requests
+
+from cli import _legacy
+from cli.commands import update as update_mod
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+class _FakePyPIResponse:
+ """Minimal stand-in for ``requests.Response`` carrying a PyPI payload."""
+
+ def __init__(self, latest: str, *, status_error: str | None = None):
+ self._latest = latest
+ self._status_error = status_error
+
+ def raise_for_status(self) -> None:
+ if self._status_error:
+ raise requests.HTTPError(self._status_error)
+
+ def json(self) -> dict:
+ return {"info": {"version": self._latest}}
+
+
+class _FakeProc:
+ def __init__(self, returncode: int = 0, stdout: str = ""):
+ self.returncode = returncode
+ self.stdout = stdout
+
+
+def _fake_subprocess(pip_rc: int = 0, verify_stdout: str = "99.0.0") -> tuple[list[list[str]], object]:
+ """Install a fake ``subprocess.run`` and return (calls, original_run).
+
+ The pip call is identified by the ``-m pip`` marker, the verification call
+ by the ``-c`` marker.
+ """
+ calls: list[list[str]] = []
+
+ def fake_run(cmd, *args, **kwargs): # noqa: ANN001, ANN002
+ calls.append(cmd)
+ if "-c" in cmd:
+ return _FakeProc(0, verify_stdout)
+ return _FakeProc(pip_rc)
+
+ return calls, fake_run
+
+
+def _monkeypatch_upgrade_env(monkeypatch, *, latest: str = "99.0.0", kind: str = update_mod.KIND_WHEEL):
+ """Point PyPI + install-kind detection at deterministic fakes."""
+ monkeypatch.setattr(update_mod.requests, "get", lambda *a, **k: _FakePyPIResponse(latest))
+ monkeypatch.setattr(update_mod, "detect_install_kind", lambda: kind)
+
+
+# ---------------------------------------------------------------------------
+# CLI registration
+# ---------------------------------------------------------------------------
+
+
+def test_parser_accepts_update_subcommand() -> None:
+ parser = _legacy._build_parser()
+
+ args = parser.parse_args(["update"])
+ assert args.command == "update"
+
+
+def test_help_lists_update(capsys: pytest.CaptureFixture[str]) -> None:
+ parser = _legacy._build_parser()
+
+ with pytest.raises(SystemExit) as excinfo:
+ parser.parse_args(["--help"])
+ assert excinfo.value.code == 0
+ assert "update" in capsys.readouterr().out
+
+
+# ---------------------------------------------------------------------------
+# Install-kind detection
+# ---------------------------------------------------------------------------
+
+
+class _FakeDist:
+ """Stand-in for importlib.metadata.Distribution."""
+
+ def __init__(self, direct_url: dict | None = None, files=None):
+ self._direct_url = direct_url
+ self.files = files or []
+
+ def read_text(self, filename: str) -> str | None:
+ if filename == "direct_url.json" and self._direct_url is not None:
+ return json.dumps(self._direct_url)
+ return None
+
+
+def test_detect_install_kind_checkout(monkeypatch) -> None:
+ def _raise(*a, **k): # noqa: ANN001, ANN002
+ raise update_mod.PackageNotFoundError
+
+ monkeypatch.setattr(update_mod, "distribution", _raise)
+ assert update_mod.detect_install_kind() == update_mod.KIND_CHECKOUT
+
+
+def test_detect_install_kind_editable_modern_marker(monkeypatch) -> None:
+ """direct_url.json with dir_info.editable => editable (modern pip style)."""
+ dist = _FakeDist(direct_url={"url": "file:///repo", "dir_info": {"editable": True}})
+ monkeypatch.setattr(update_mod, "distribution", lambda *a, **k: dist)
+ assert update_mod.detect_install_kind() == update_mod.KIND_EDITABLE
+
+
+def test_detect_install_kind_wheel(monkeypatch) -> None:
+ """direct_url.json WITHOUT editable (a wheel's index URL) => wheel."""
+ dist = _FakeDist(direct_url={"url": "https://pypi.org/simple/...", "dir_info": {}})
+ monkeypatch.setattr(update_mod, "distribution", lambda *a, **k: dist)
+ assert update_mod.detect_install_kind() == update_mod.KIND_WHEEL
+
+
+def test_detect_install_kind_wheel_without_any_marker(monkeypatch) -> None:
+ """No direct_url.json and no egg-info on sys.path => wheel."""
+ dist = _FakeDist(direct_url=None)
+ monkeypatch.setattr(update_mod, "distribution", lambda *a, **k: dist)
+ monkeypatch.setattr(update_mod, "_has_source_tree_egg_info", lambda: False)
+ assert update_mod.detect_install_kind() == update_mod.KIND_WHEEL
+
+
+def test_detect_install_kind_legacy_editable_egg_info(monkeypatch) -> None:
+ """Metadata without direct_url.json but an egg-info in the source tree.
+
+ Covers the case that bit us live: running ``python -m cli`` from ``agent/``
+ resolves the distribution to ``agent/vibe_trading_ai.egg-info`` (left by
+ ``pip install -e .``), which has no ``direct_url.json``.
+ """
+ dist = _FakeDist(direct_url=None)
+ monkeypatch.setattr(update_mod, "distribution", lambda *a, **k: dist)
+ monkeypatch.setattr(update_mod, "_has_source_tree_egg_info", lambda: True)
+ assert update_mod.detect_install_kind() == update_mod.KIND_EDITABLE
+
+
+def test_detect_install_kind_corrupt_direct_url_is_wheel(monkeypatch) -> None:
+ """Unparseable direct_url.json defaults to the pip path, never crashes."""
+ class _CorruptDist:
+ def read_text(self, filename: str) -> str:
+ return "not-json{"
+
+ monkeypatch.setattr(update_mod, "distribution", lambda *a, **k: _CorruptDist())
+ assert update_mod.detect_install_kind() == update_mod.KIND_WHEEL
+
+
+def test_detect_install_kind_non_dict_direct_url_is_wheel(monkeypatch) -> None:
+ """Valid JSON that is not a dict must not crash (AttributeError guard)."""
+ class _WeirdDist:
+ def read_text(self, filename: str) -> str:
+ return "[1, 2, 3]"
+
+ monkeypatch.setattr(update_mod, "distribution", lambda *a, **k: _WeirdDist())
+ assert update_mod.detect_install_kind() == update_mod.KIND_WHEEL
+
+
+def test_has_source_tree_egg_info_finds_egg_info_on_sys_path(monkeypatch, tmp_path) -> None:
+ egg_dir = tmp_path / f"{update_mod.PACKAGE_NAME.replace('-', '_')}.egg-info"
+ egg_dir.mkdir()
+ monkeypatch.setattr(update_mod.sys, "path", [str(tmp_path), "/nonexistent"])
+ assert update_mod._has_source_tree_egg_info() is True
+
+
+def test_has_source_tree_egg_info_absent(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(update_mod.sys, "path", [str(tmp_path)])
+ assert update_mod._has_source_tree_egg_info() is False
+
+
+# ---------------------------------------------------------------------------
+# Update flow
+# ---------------------------------------------------------------------------
+
+
+def test_already_up_to_date_no_pip(monkeypatch, capsys: pytest.CaptureFixture[str]) -> None:
+ """Latest PyPI version <= installed version: exit 0, no pip call at all."""
+ calls, fake_run = _fake_subprocess()
+ monkeypatch.setattr(update_mod.subprocess, "run", fake_run)
+ # "0.0.1" is below the repo's dev version (0.1.13), and also below any real release.
+ _monkeypatch_upgrade_env(monkeypatch, latest="0.0.1")
+
+ assert update_mod.cmd_update() == update_mod.EXIT_OK
+ assert calls == []
+ assert "Already up to date" in capsys.readouterr().out
+
+
+def test_downgrade_protection_no_pip(monkeypatch) -> None:
+ """A lower PyPI version must never trigger an install (covers downgrade guard)."""
+ calls, fake_run = _fake_subprocess()
+ monkeypatch.setattr(update_mod.subprocess, "run", fake_run)
+ _monkeypatch_upgrade_env(monkeypatch, latest="0.0.1")
+
+ update_mod.cmd_update()
+ assert calls == []
+
+
+def test_newer_wheel_upgrades(monkeypatch, capsys: pytest.CaptureFixture[str]) -> None:
+ """Newer version + wheel install: exactly one pip upgrade call, exit 0."""
+ calls, fake_run = _fake_subprocess(pip_rc=0, verify_stdout="99.0.0")
+ monkeypatch.setattr(update_mod.subprocess, "run", fake_run)
+ _monkeypatch_upgrade_env(monkeypatch, latest="99.0.0")
+
+ assert update_mod.cmd_update() == update_mod.EXIT_OK
+ assert len(calls) == 2
+ pip_cmd = calls[0]
+ assert pip_cmd[:3] == [update_mod.sys.executable, "-m", "pip"]
+ assert "install" in pip_cmd and "--upgrade" in pip_cmd
+ assert update_mod.PACKAGE_NAME in pip_cmd
+ assert "Updated to 99.0.0" in capsys.readouterr().out
+
+
+def test_pip_failure_surfaces(monkeypatch, capsys: pytest.CaptureFixture[str]) -> None:
+ """pip exits non-zero: report failure, exit 1, no verification run."""
+ calls, fake_run = _fake_subprocess(pip_rc=1, verify_stdout="99.0.0")
+ monkeypatch.setattr(update_mod.subprocess, "run", fake_run)
+ _monkeypatch_upgrade_env(monkeypatch, latest="99.0.0")
+
+ assert update_mod.cmd_update() == update_mod.EXIT_FAILED
+ assert len(calls) == 1 # pip call only; verification must not run
+ assert "Upgrade failed" in capsys.readouterr().out
+
+
+def test_verification_mismatch(monkeypatch, capsys: pytest.CaptureFixture[str]) -> None:
+ """pip succeeded but the fresh process reports an older version: exit 1."""
+ calls, fake_run = _fake_subprocess(pip_rc=0, verify_stdout="0.0.1")
+ monkeypatch.setattr(update_mod.subprocess, "run", fake_run)
+ _monkeypatch_upgrade_env(monkeypatch, latest="99.0.0")
+
+ assert update_mod.cmd_update() == update_mod.EXIT_FAILED
+ assert len(calls) == 2
+ assert "verification mismatch" in capsys.readouterr().out
+
+
+def test_editable_install_prints_hint_no_pip(monkeypatch, capsys: pytest.CaptureFixture[str]) -> None:
+ calls, fake_run = _fake_subprocess()
+ monkeypatch.setattr(update_mod.subprocess, "run", fake_run)
+ _monkeypatch_upgrade_env(monkeypatch, latest="99.0.0", kind=update_mod.KIND_EDITABLE)
+
+ assert update_mod.cmd_update() == update_mod.EXIT_OK
+ assert calls == []
+ assert "git pull" in capsys.readouterr().out
+
+
+def test_checkout_install_prints_hint_no_pip(monkeypatch, capsys: pytest.CaptureFixture[str]) -> None:
+ calls, fake_run = _fake_subprocess()
+ monkeypatch.setattr(update_mod.subprocess, "run", fake_run)
+ _monkeypatch_upgrade_env(monkeypatch, latest="99.0.0", kind=update_mod.KIND_CHECKOUT)
+
+ assert update_mod.cmd_update() == update_mod.EXIT_OK
+ assert calls == []
+ assert "git pull" in capsys.readouterr().out
+
+
+def test_pypi_fetch_failure_no_pip(monkeypatch, capsys: pytest.CaptureFixture[str]) -> None:
+ """Network/HTTP failure on the version check: clear error, install untouched."""
+ def _boom(*a, **k): # noqa: ANN001, ANN002
+ raise requests.ConnectionError("offline")
+
+ monkeypatch.setattr(update_mod.requests, "get", _boom)
+ calls, fake_run = _fake_subprocess()
+ monkeypatch.setattr(update_mod.subprocess, "run", fake_run)
+
+ assert update_mod.cmd_update() == update_mod.EXIT_FAILED
+ assert calls == []
+ assert "Could not check for updates" in capsys.readouterr().out
+
+
+def test_unparseable_installed_version_errors(monkeypatch, capsys: pytest.CaptureFixture[str]) -> None:
+ """A garbage installed version cannot be compared: exit 1, nothing touched."""
+ calls, fake_run = _fake_subprocess()
+ monkeypatch.setattr(update_mod.subprocess, "run", fake_run)
+ monkeypatch.setattr(update_mod, "CURRENT_VERSION", "not-a-version")
+ _monkeypatch_upgrade_env(monkeypatch, latest="99.0.0")
+
+ assert update_mod.cmd_update() == update_mod.EXIT_FAILED
+ assert calls == []
+ assert "Could not compare versions" in capsys.readouterr().out