Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix: store session and run history under the user runtime root, not the code (#925)

Xiaotian Jinc7d2ebaab8fa
diff --git a/README.md b/README.md
index cd00e56f6..bbb2f2699 100644
--- a/README.md
+++ b/README.md
@@ -1002,7 +1002,7 @@ Interactive docs: `http://localhost:8899/docs`
For localhost development, `vibe-trading serve` keeps the browser workflow simple. For any non-local client, sensitive API endpoints require `API_AUTH_KEY`; use `Authorization: Bearer <key>` for JSON/upload requests. Browser EventSource streams are handled by the Web UI after you enter the same key once in Settings.
-Shell-capable process tools (`bash` / `background_run` / `cancel_background`) are enabled only for the interactive local CLI. Every other surface — the HTTP/SSE API and the MCP server on **all** transports (stdio included) — keeps them off unless you explicitly opt in with `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` (or pass `--enable-shell-tools` to `vibe-trading-mcp`). Transport type never implicitly grants shell access. `cancel_background` stops only the tracked task ID returned by `background_run`; broad Python process-name termination is refused because it could terminate Vibe-Trading itself. Document and journal readers are limited to upload/import roots by default; place files under `agent/uploads`, `agent/runs`, `./uploads`, `./data`, `~/.vibe-trading/uploads`, or add a dedicated directory through `VIBE_TRADING_ALLOWED_FILE_ROOTS`.
+Shell-capable process tools (`bash` / `background_run` / `cancel_background`) are enabled only for the interactive local CLI. Every other surface — the HTTP/SSE API and the MCP server on **all** transports (stdio included) — keeps them off unless you explicitly opt in with `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` (or pass `--enable-shell-tools` to `vibe-trading-mcp`). Transport type never implicitly grants shell access. `cancel_background` stops only the tracked task ID returned by `background_run`; broad Python process-name termination is refused because it could terminate Vibe-Trading itself. Document and journal readers are limited to upload/import roots by default; place files under `~/.vibe-trading/uploads`, `~/.vibe-trading/runs`, `./uploads`, `./data` (or the legacy `agent/uploads` / `agent/runs`), or add a dedicated directory through `VIBE_TRADING_ALLOWED_FILE_ROOTS`. Sessions, runs, swarm runs, uploads, and the `sessions.db` index live under `~/.vibe-trading` (relocatable via the `VIBE_TRADING_HOME` shell environment variable); pre-existing history is moved there automatically on first run.
Generated backtest code runs as a local Python subprocess and can make network requests through the configured market-data loaders. Its environment is intentionally narrow: the runner keeps OS/Python basics, proxy/certificate settings, `VIBE_TRADING_ALLOWED_RUN_ROOTS`, and read-only market-data keys such as `TUSHARE_TOKEN`, `FMP_API_KEY`, `FRED_API_KEY`, and `VIBE_TRADING_IWENCAI_KEY`. It does not pass LLM provider keys, API auth tokens, shell-tool switches, broker trading secrets, or live/advisory toggles to generated strategy code by default.
diff --git a/README_ar.md b/README_ar.md
index d018386be..43e356e36 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -943,7 +943,7 @@ vibe-trading serve --port 8899
للتطوير على localhost، يبقي `vibe-trading serve` سير المتصفح بسيطاً. لأي عميل غير محلي، تتطلب نقاط API الحساسة `API_AUTH_KEY`؛ استخدم `Authorization: Bearer <key>` لطلبات JSON/الرفع. تتعامل Web UI مع تدفقات Browser EventSource بعد إدخال المفتاح نفسه مرة واحدة في Settings.
-الأدوات القادرة على shell (`bash` / `background_run` / `cancel_background`) مفعّلة فقط لواجهة CLI المحلية التفاعلية. أما بقية الأسطح — واجهة HTTP/SSE و MCP server على **جميع** وسائط النقل (بما في ذلك stdio) — فتبقى معطّلة ما لم تفعّلها صراحة عبر `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` (أو تمرير `--enable-shell-tools` إلى `vibe-trading-mcp`). نوع وسيط النقل لا يمنح صلاحية shell ضمنيًا أبدًا. قارئات المستندات والسجلات محدودة افتراضياً بجذور الرفع/الاستيراد؛ ضع الملفات تحت `agent/uploads` أو `agent/runs` أو `./uploads` أو `./data` أو `~/.vibe-trading/uploads` أو `~/.vibe-trading/imports`، أو أضف دليلاً مخصصاً عبر `VIBE_TRADING_ALLOWED_FILE_ROOTS`.
+الأدوات القادرة على shell (`bash` / `background_run` / `cancel_background`) مفعّلة فقط لواجهة CLI المحلية التفاعلية. أما بقية الأسطح — واجهة HTTP/SSE و MCP server على **جميع** وسائط النقل (بما في ذلك stdio) — فتبقى معطّلة ما لم تفعّلها صراحة عبر `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` (أو تمرير `--enable-shell-tools` إلى `vibe-trading-mcp`). نوع وسيط النقل لا يمنح صلاحية shell ضمنيًا أبدًا. قارئات المستندات والسجلات محدودة افتراضياً بجذور الرفع/الاستيراد؛ ضع الملفات تحت `~/.vibe-trading/uploads` أو `~/.vibe-trading/runs` أو `./uploads` أو `./data` (أو المسارين القديمين `agent/uploads` / `agent/runs`)، أو أضف دليلاً مخصصاً عبر `VIBE_TRADING_ALLOWED_FILE_ROOTS`. تُخزَّن الجلسات ونتائج التشغيل وتشغيلات swarm والمرفوعات وفهرس `sessions.db` كلها تحت `~/.vibe-trading` (يمكن نقلها بالكامل عبر متغير البيئة `VIBE_TRADING_HOME`)، ويُنقَل السجل القديم تلقائياً عند أول تشغيل.
### إعدادات Web UI
diff --git a/README_ja.md b/README_ja.md
index 3bc4fd779..9851e5693 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -940,7 +940,7 @@ Interactive docs: `http://localhost:8899/docs`
localhost 開発では、`vibe-trading serve` は browser workflow を簡単に保ちます。非ローカル client では、sensitive API endpoints に `API_AUTH_KEY` が必要です。JSON/upload requests には `Authorization: Bearer <key>` を使ってください。Browser EventSource streams は、Settings で同じ key を一度入力した後、Web UI が処理します。
-Shell-capable process tools(`bash` / `background_run` / `cancel_background`)はインタラクティブな local CLI でのみ有効です。それ以外のすべての面 — HTTP/SSE API と MCP server の**すべての** transport(stdio を含む)— は、`VIBE_TRADING_ENABLE_SHELL_TOOLS=1` を明示的に設定する(または `vibe-trading-mcp` に `--enable-shell-tools` を渡す)まで無効のままです。transport の種類が暗黙に shell アクセスを許可することはありません。Document と journal readers は既定で upload/import roots に制限されます。ファイルは `agent/uploads`、`agent/runs`、`./uploads`、`./data`、`~/.vibe-trading/uploads`、`~/.vibe-trading/imports` の下に置くか、`VIBE_TRADING_ALLOWED_FILE_ROOTS` で専用 directory を追加してください。
+Shell-capable process tools(`bash` / `background_run` / `cancel_background`)はインタラクティブな local CLI でのみ有効です。それ以外のすべての面 — HTTP/SSE API と MCP server の**すべての** transport(stdio を含む)— は、`VIBE_TRADING_ENABLE_SHELL_TOOLS=1` を明示的に設定する(または `vibe-trading-mcp` に `--enable-shell-tools` を渡す)まで無効のままです。transport の種類が暗黙に shell アクセスを許可することはありません。Document と journal readers は既定で upload/import roots に制限されます。ファイルは `~/.vibe-trading/uploads`、`~/.vibe-trading/runs`、`./uploads`、`./data`(または旧来の `agent/uploads` / `agent/runs`)の下に置くか、`VIBE_TRADING_ALLOWED_FILE_ROOTS` で専用 directory を追加してください。セッション、実行成果物、swarm 実行、アップロード、`sessions.db` インデックスは `~/.vibe-trading` 配下に統一されています(shell 環境変数 `VIBE_TRADING_HOME` で丸ごと移動可能)。旧位置の履歴は初回起動時に自動で移行されます。
### Web UI Settings
diff --git a/README_ko.md b/README_ko.md
index 400960ccc..a333e0828 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -943,7 +943,7 @@ Interactive docs: `http://localhost:8899/docs`
localhost 개발에서 `vibe-trading serve`는 browser workflow를 단순하게 유지합니다. non-local client에서는 민감한 API endpoint에 `API_AUTH_KEY`가 필요합니다. JSON/upload request에는 `Authorization: Bearer <key>`를 사용하세요. Browser EventSource stream은 Web UI Settings에 같은 key를 한 번 입력하면 Web UI가 처리합니다.
-Shell-capable process tools(`bash` / `background_run` / `cancel_background`)는 대화형 local CLI에서만 활성화됩니다. 그 외 모든 표면 — HTTP/SSE API와 MCP server의 **모든** transport(stdio 포함) — 는 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1`을 명시적으로 설정하지 않는 한(또는 `vibe-trading-mcp`에 `--enable-shell-tools`를 전달하지 않는 한) 비활성 상태로 유지됩니다. transport 종류가 암묵적으로 shell 접근을 부여하는 일은 없습니다. Document와 journal reader는 기본적으로 upload/import roots로 제한됩니다. 파일은 `agent/uploads`, `agent/runs`, `./uploads`, `./data`, `~/.vibe-trading/uploads`, `~/.vibe-trading/imports` 아래에 두거나, `VIBE_TRADING_ALLOWED_FILE_ROOTS`로 전용 directory를 추가하세요.
+Shell-capable process tools(`bash` / `background_run` / `cancel_background`)는 대화형 local CLI에서만 활성화됩니다. 그 외 모든 표면 — HTTP/SSE API와 MCP server의 **모든** transport(stdio 포함) — 는 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1`을 명시적으로 설정하지 않는 한(또는 `vibe-trading-mcp`에 `--enable-shell-tools`를 전달하지 않는 한) 비활성 상태로 유지됩니다. transport 종류가 암묵적으로 shell 접근을 부여하는 일은 없습니다. Document와 journal reader는 기본적으로 upload/import roots로 제한됩니다. 파일은 `~/.vibe-trading/uploads`, `~/.vibe-trading/runs`, `./uploads`, `./data`(또는 레거시 `agent/uploads` / `agent/runs`) 아래에 두거나, `VIBE_TRADING_ALLOWED_FILE_ROOTS`로 전용 directory를 추가하세요. 세션, 실행 산출물, swarm 실행, 업로드, `sessions.db` 인덱스는 `~/.vibe-trading` 아래로 통합되며(shell 환경 변수 `VIBE_TRADING_HOME`으로 전체 이동 가능), 기존 위치의 이력은 첫 실행 시 자동으로 이전됩니다.
### Web UI Settings
diff --git a/README_zh.md b/README_zh.md
index 481dcda4e..b5616615f 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -967,7 +967,7 @@ vibe-trading serve --port 8899
对于 localhost 开发,`vibe-trading serve` 会保持浏览器工作流简单。对任何非本地客户端,敏感 API endpoints 都要求 `API_AUTH_KEY`;JSON/upload 请求请使用 `Authorization: Bearer <key>`。浏览器 EventSource streams 会在你于 Settings 中输入同一个 key 后由 Web UI 处理。
-Shell-capable process tools(`bash` / `background_run` / `cancel_background`)仅对交互式本地 CLI 启用。其他所有入口 —— HTTP/SSE API 以及 MCP server 的**所有** transport(含 stdio)—— 默认关闭,除非你显式设置 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1`(或给 `vibe-trading-mcp` 传 `--enable-shell-tools`)。transport 类型永远不会隐式授予 shell 访问权限。`cancel_background` 只终止 `background_run` 返回的已跟踪 task ID;系统会拒绝按进程名广泛终止 Python,避免把 Vibe-Trading 自身一起终止。文档和日志读取器默认限制在 upload/import roots 内;请将文件放在 `agent/uploads`、`agent/runs`、`./uploads`、`./data`、`~/.vibe-trading/uploads` 或 `~/.vibe-trading/imports` 下,或通过 `VIBE_TRADING_ALLOWED_FILE_ROOTS` 添加专用目录。
+Shell-capable process tools(`bash` / `background_run` / `cancel_background`)仅对交互式本地 CLI 启用。其他所有入口 —— HTTP/SSE API 以及 MCP server 的**所有** transport(含 stdio)—— 默认关闭,除非你显式设置 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1`(或给 `vibe-trading-mcp` 传 `--enable-shell-tools`)。transport 类型永远不会隐式授予 shell 访问权限。`cancel_background` 只终止 `background_run` 返回的已跟踪 task ID;系统会拒绝按进程名广泛终止 Python,避免把 Vibe-Trading 自身一起终止。文档和日志读取器默认限制在 upload/import roots 内;请将文件放在 `~/.vibe-trading/uploads`、`~/.vibe-trading/runs`、`./uploads`、`./data`(或旧版的 `agent/uploads` / `agent/runs`)下,或通过 `VIBE_TRADING_ALLOWED_FILE_ROOTS` 添加专用目录。会话、运行产物、swarm 运行、上传文件与 `sessions.db` 索引统一存放在 `~/.vibe-trading` 下(可通过 shell 环境变量 `VIBE_TRADING_HOME` 整体迁移);旧位置的历史数据会在首次运行时自动迁入。
### Web UI Settings
diff --git a/agent/.env.example b/agent/.env.example
index fd2b16ba8..bd5d6c390 100644
--- a/agent/.env.example
+++ b/agent/.env.example
@@ -182,6 +182,19 @@ TUSHARE_TOKEN=your-tushare-token
# Example: qwen3.7-plus, gpt-5.5, gemini-3.5-flash, claude-sonnet-4.6
# VIBE_TRADING_OCR_LLM_MODEL=
+# ============================================================================
+# Storage root
+# ============================================================================
+# Chat sessions, run artifacts, swarm runs, uploads, and the sessions.db
+# search/goal index live under ~/.vibe-trading by default. Set
+# VIBE_TRADING_HOME to relocate them, e.g. to keep deliberately separate
+# stores per project. (Other state — memory, reports, caches, live configs —
+# is still anchored to ~/.vibe-trading regardless.) Set it in your shell
+# environment (export VIBE_TRADING_HOME=...), NOT in this file: path
+# constants are resolved when the process starts, before this file is read,
+# so an override here would apply to some code paths and not others.
+# VIBE_TRADING_HOME=~/.vibe-trading
+
# Opt-in local market-data cache for backtest loaders (off by default).
# When enabled, every data source caches settled historical bars under
# ~/.vibe-trading/cache/loaders/ so repeated/long-horizon backtests skip the
diff --git a/agent/api_server.py b/agent/api_server.py
index ffa5672fd..84bb0cb1f 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -159,6 +159,12 @@ async def _run_startup_preflight() -> None:
"""Run preflight checks on server startup."""
from src.preflight import run_preflight
+ from src.config import migrate as _migrate
+
+ try:
+ _migrate.migrate_legacy_state() # one-time pre-#904 state move; must never block startup
+ except Exception: # pragma: no cover — best-effort
+ logging.getLogger(__name__).warning("Legacy state migration failed", exc_info=True)
run_preflight(console)
_start_scheduled_research_executor()
from src.config.accessor import get_env_config
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 24957b8c8..9409f96f1 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -51,13 +51,22 @@ from rich.text import Text
from cli.theme import get_console
from src.config.accessor import get_env_config, reset_env_config
+from src.config.paths import (
+ get_runs_dir,
+ get_runtime_root,
+ get_sessions_dir,
+ get_swarm_runs_dir,
+ get_uploads_dir,
+)
console = get_console()
+# AGENT_DIR is a code location (frontend defaults, dev-server cwd). State
+# lives under the user-level runtime root, never relative to the code (#904).
AGENT_DIR = Path(__file__).resolve().parents[1]
-RUNS_DIR = AGENT_DIR / "runs"
-SWARM_DIR = AGENT_DIR / ".swarm" / "runs"
-SESSIONS_DIR = AGENT_DIR / "sessions"
-UPLOADS_DIR = AGENT_DIR / "uploads"
+RUNS_DIR = get_runs_dir()
+SWARM_DIR = get_swarm_runs_dir()
+SESSIONS_DIR = get_sessions_dir()
+UPLOADS_DIR = get_uploads_dir()
EXIT_SUCCESS = 0
EXIT_RUN_FAILED = 1
@@ -1660,7 +1669,7 @@ def _build_welcome_panel(term_width: Optional[int] = None) -> Panel:
("Credential", key_state, "bold green" if credential_ready else "bold yellow"),
("Runs", str(recent_runs), "cyan"),
("Swarms", str(recent_swarms), "cyan"),
- ("Workspace", str(AGENT_DIR), "dim"),
+ ("Workspace", str(get_runtime_root()), "dim"),
]
for label, value, value_style in rows:
config_lines.append(
@@ -1677,7 +1686,7 @@ def _build_welcome_panel(term_width: Optional[int] = None) -> Panel:
rows = [
("Provider", str(provider), "bold cyan", "Credential", key_state, "bold green" if credential_ready else "bold yellow"),
("Model", str(model), "white", "Runs", str(recent_runs), "cyan"),
- ("Workspace", str(AGENT_DIR), "dim", "Swarms", str(recent_swarms), "cyan"),
+ ("Workspace", str(get_runtime_root()), "dim", "Swarms", str(recent_swarms), "cyan"),
]
for left_label, left_value, left_style, right_label, right_value, right_style in rows:
config_lines.append(
diff --git a/agent/cli/main.py b/agent/cli/main.py
index e6378c470..8694b5e17 100644
--- a/agent/cli/main.py
+++ b/agent/cli/main.py
@@ -20,6 +20,7 @@ hits :func:`main`.
from __future__ import annotations
import importlib
+import logging
import os
import sys
import threading
@@ -169,7 +170,9 @@ def _probe_skill_count() -> int:
def _probe_session_count() -> int:
"""Count recorded sessions from the SQLite store."""
- db_path = Path.home() / ".vibe-trading" / "sessions.db"
+ from src.config.paths import get_runtime_root
+
+ db_path = get_runtime_root() / "sessions.db"
if not db_path.exists():
return 0
try:
@@ -363,7 +366,7 @@ class InteractiveContext:
def _session_store() -> Any:
- """Return a process-wide :class:`SessionStore` rooted at ``agent/sessions``.
+ """Return a process-wide :class:`SessionStore` rooted at the user-level sessions dir.
Cached on the module so repeat ``_append_message`` / ``_new_session``
calls don't re-import ``src.session.store`` every turn.
@@ -399,8 +402,8 @@ def _new_session(prompt_preview: str) -> Optional[str]:
"""Create a fresh session record. Returns the id, or None on failure.
Dual-writes to the filesystem :class:`SessionStore` (canonical JSONL
- log under ``agent/sessions/``) *and* to the SQLite FTS5 search index
- (``~/.vibe-trading/sessions.db``) so cross-session search via
+ log in the user-level sessions dir) *and* to the SQLite FTS5 search
+ index (``sessions.db`` beside it) so cross-session search via
:class:`SessionSearchIndex` finds turns recorded from the interactive
loop. Matches the pattern in :class:`SessionService`.
"""
@@ -1309,6 +1312,18 @@ def main(argv: Optional[list[str]] = None) -> int:
Process exit code.
"""
raw_argv = list(sys.argv[1:] if argv is None else argv)
+
+ # One-time move of pre-#904 code-relative state into the runtime root.
+ # A failed migration must never block the CLI.
+ try:
+ from src.config import migrate as _migrate
+
+ _migrate.migrate_legacy_state()
+ except Exception: # pragma: no cover — best-effort
+ logging.getLogger(__name__).warning(
+ "Legacy state migration failed", exc_info=True
+ )
+
interactive = _is_interactive_invocation(raw_argv)
if interactive:
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index 6b29a5545..990f3d69d 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -2166,6 +2166,18 @@ def main():
"to setting VIBE_TRADING_ENABLE_SHELL_TOOLS=1.",
)
args = parser.parse_args()
+
+ # One-time move of pre-#904 code-relative state into the runtime root.
+ # A failed migration must never block the server.
+ try:
+ from src.config import migrate as _migrate
+
+ _migrate.migrate_legacy_state()
+ except Exception: # pragma: no cover — best-effort
+ logging.getLogger(__name__).warning(
+ "Legacy state migration failed", exc_info=True
+ )
+
_include_shell_tools = _resolve_include_shell_tools(args.enable_shell_tools)
_registry = None
_get_registry() # pre-warm: avoids deadlock when first tools/call lazy-inits inside FastMCP worker thread
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 5597e12bc..667d99a91 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -44,11 +44,12 @@ from src.providers.content_filter import (
compute_content_filter_warnings,
)
from src.config.accessor import get_env_config
+from src.config.paths import get_runs_dir, get_sessions_dir
from src.tools.background_tools import get_background_manager
from src.tools.redaction import redact_payload, redact_tool_result
-RUNS_DIR = Path(__file__).resolve().parents[2] / "runs"
-SESSIONS_DIR = Path(__file__).resolve().parents[2] / "sessions"
+RUNS_DIR = get_runs_dir()
+SESSIONS_DIR = get_sessions_dir()
KEEP_RECENT = 3
TOOL_RESULT_LIMIT = 10_000
LLM_USAGE_ARTIFACT = "llm_usage.json"
diff --git a/agent/src/agent/trace.py b/agent/src/agent/trace.py
index 7b73e8c05..1f04ad54f 100644
--- a/agent/src/agent/trace.py
+++ b/agent/src/agent/trace.py
@@ -379,17 +379,22 @@ class TraceWriter:
Args:
run_id: Run or session ID.
- runs_dir: Base runs directory. Defaults to ``agent/runs``.
- sessions_dir: Base sessions directory. Defaults to
- ``agent/sessions``.
+ runs_dir: Base runs directory. Defaults to the user-level
+ runs dir under the runtime root.
+ sessions_dir: Base sessions directory. Defaults to the
+ user-level sessions dir under the runtime root.
Returns:
Directory containing ``trace.jsonl``, or ``None`` when absent.
"""
if sessions_dir is None:
- sessions_dir = Path(__file__).resolve().parents[2] / "sessions"
+ from src.config.paths import get_sessions_dir
+
+ sessions_dir = get_sessions_dir()
if runs_dir is None:
- runs_dir = Path(__file__).resolve().parents[2] / "runs"
+ from src.config.paths import get_runs_dir
+
+ runs_dir = get_runs_dir()
session_dir = sessions_dir / run_id
if (session_dir / "trace.jsonl").exists():
diff --git a/agent/src/api/helpers.py b/agent/src/api/helpers.py
index b146e6f8e..c21b3434d 100644
--- a/agent/src/api/helpers.py
+++ b/agent/src/api/helpers.py
@@ -12,6 +12,7 @@ from fastapi import HTTPException, Request, status
from fastapi.responses import FileResponse
from src.api._compat import host_attr as _host_attr
+from src.config.paths import get_runs_dir, get_sessions_dir, get_uploads_dir
# ============================================================================
@@ -19,11 +20,13 @@ from src.api._compat import host_attr as _host_attr
# ============================================================================
# helpers.py lives at agent/src/api/helpers.py — 4 levels up to Vibe-Trading/.
+# AGENT_DIR stays a code location; state dirs resolve under the user-level
+# runtime root (#904).
_AGENT_DIR = Path(__file__).resolve().parent.parent.parent # agent/
-RUNS_DIR = _AGENT_DIR / "runs"
-SESSIONS_DIR = _AGENT_DIR / "sessions"
-UPLOADS_DIR = _AGENT_DIR / "uploads"
+RUNS_DIR = get_runs_dir()
+SESSIONS_DIR = get_sessions_dir()
+UPLOADS_DIR = get_uploads_dir()
AGENT_DIR = _AGENT_DIR
ENV_PATH = Path.home() / ".vibe-trading" / ".env"
LEGACY_ENV_PATH = AGENT_DIR / ".env"
diff --git a/agent/src/api/swarm_routes.py b/agent/src/api/swarm_routes.py
index 6faecbd78..3990effd3 100644
--- a/agent/src/api/swarm_routes.py
+++ b/agent/src/api/swarm_routes.py
@@ -6,7 +6,6 @@ Mounted by ``agent/api_server.py`` via ``register_swarm_routes(app, ...)``.
from __future__ import annotations
import json
-from pathlib import Path
from typing import Any, Awaitable, Callable
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request
@@ -25,12 +24,10 @@ def _get_swarm_runtime():
if _swarm_runtime is not None:
return _swarm_runtime
from src.config import load_swarm_agent_config
- from src.swarm.store import SwarmStore
+ from src.swarm.store import SwarmStore, swarm_runs_root
from src.swarm.runtime import SwarmRuntime
- # Adjust path: this file is at agent/src/api/, so parent.parent.parent = agent/
- swarm_dir = Path(__file__).resolve().parent.parent.parent / ".swarm" / "runs"
- store = SwarmStore(base_dir=swarm_dir)
+ store = SwarmStore(base_dir=swarm_runs_root())
# Boot-time / operator-trusted: REST API callers cannot influence the
# config path. See docs/2026-05-25_swarm_mcp_tools_roadmap.md.
agent_config = load_swarm_agent_config()
diff --git a/agent/src/api/uploads_routes.py b/agent/src/api/uploads_routes.py
index 4b8b36fb6..c78777f11 100644
--- a/agent/src/api/uploads_routes.py
+++ b/agent/src/api/uploads_routes.py
@@ -13,11 +13,13 @@ from typing import Any, Awaitable, Callable
from fastapi import Depends, FastAPI, HTTPException, UploadFile
from fastapi.responses import FileResponse
+from src.config.paths import get_uploads_dir
+
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
-UPLOADS_DIR = Path(__file__).resolve().parent.parent.parent / "uploads"
+UPLOADS_DIR = get_uploads_dir()
MAX_UPLOAD_SIZE = 50 * 1024 * 1024 # 50 MB
_UPLOAD_CHUNK_SIZE = 1024 * 1024 # 1 MB
diff --git a/agent/src/config/migrate.py b/agent/src/config/migrate.py
new file mode 100644
index 000000000..a527a3f16
--- /dev/null
+++ b/agent/src/config/migrate.py
@@ -0,0 +1,152 @@
+"""One-time migration of code-relative state into the runtime root.
+
+Before issue #904 was fixed, ``sessions/``, ``runs/``, ``.swarm/runs/`` and
+``uploads/`` were resolved relative to the installed code (``site-packages``
+on a pip install, the checkout on an editable install). They now live under
+:func:`src.config.paths.get_runtime_root`. This module moves data from the
+old location on first run so history survives upgrades and reinstalls.
+
+Merge semantics are child-level: each session/run/upload entry moves
+individually, and only a same-named entry already present at the destination
+is skipped (session and run ids are timestamped/random, so real collisions
+mean the entry was already migrated). This keeps destinations that other
+features already populate — autopilot runs, channel media uploads — from
+blocking migration of the rest. Each child lands via a hidden
+``.migrating-*`` staging name plus an atomic rename, so an interrupted move
+can never surface a half-copied entry; staging leftovers are recovered on
+the next run (redone while the source still exists, promoted once it is
+gone).
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import shutil
+from pathlib import Path
+
+from src.config.paths import get_runtime_root
+
+logger = logging.getLogger(__name__)
+
+# (legacy subpath, runtime-root subpath). ``.swarm`` loses its dot: hiding a
+# directory inside the already-hidden runtime root serves no purpose.
+_LEGACY_DIRS: tuple[tuple[str, str], ...] = (
+ ("sessions", "sessions"),
+ ("runs", "runs"),
+ (".swarm/runs", "swarm/runs"),
+ ("uploads", "uploads"),
+)
+
+_STAGING_PREFIX = ".migrating-"
+
+
+def default_legacy_root() -> Path:
+ """Return the pre-#904 state root: the directory containing the packages.
+
+ In the repo layout this is ``agent/``; in an installed distribution it is
+ ``site-packages`` itself (the bug this migration cleans up after).
+ """
+ return Path(__file__).resolve().parents[2]
+
+
+def _has_content(path: Path) -> bool:
+ return path.is_dir() and any(path.iterdir())
+
+
+def _recover_staging(source: Path, destination: Path) -> None:
+ """Resolve ``.migrating-*`` leftovers from an interrupted earlier run.
+
+ A leftover whose final name already exists, or whose source entry is
+ still present (the copy was cut short; the move can simply be redone),
+ is discarded. One whose source entry is gone is a completed move that
+ missed its rename — promote it instead of losing the data.
+ """
+ if not destination.is_dir():
+ return
+ for staged in destination.glob(f"{_STAGING_PREFIX}*"):
+ name = staged.name.removeprefix(_STAGING_PREFIX).split("-", 1)[-1]
+ final = destination / name
+ if final.exists() or (source / name).exists():
+ shutil.rmtree(staged, ignore_errors=True)
+ else:
+ staged.rename(final)
+ logger.info("Recovered interrupted migration of %s", final)
+
+
+def _merge_children(source: Path, destination: Path) -> int:
+ """Move ``source``'s children into ``destination``; skip name collisions."""
+ destination.mkdir(parents=True, exist_ok=True)
+ moved = 0
+ for child in sorted(source.iterdir()):
+ final = destination / child.name
+ if final.exists():
+ logger.warning(
+ "Not migrating %s: %s already exists. Reconcile or delete the old copy manually.",
+ child,
+ final,
+ )
+ continue
+ staged = destination / f"{_STAGING_PREFIX}{os.getpid()}-{child.name}"
+ try:
+ shutil.move(str(child), str(staged))
+ staged.rename(final)
+ except OSError:
+ logger.warning("Failed to migrate %s; leaving it in place.", child, exc_info=True)
+ # A fully-staged copy whose source is gone must survive for
+ # _recover_staging; a partial one (source intact) is discarded.
+ if child.exists():
+ shutil.rmtree(staged, ignore_errors=True)
+ continue
+ moved += 1
+ return moved
+
+
+def _remove_empty_source(source: Path) -> None:
+ try:
+ source.rmdir()
+ if source.parent.name == ".swarm":
+ source.parent.rmdir() # drop the legacy shell once its last child is gone
+ except OSError:
+ pass # non-empty (collision children remain) or already gone
+
+
+def migrate_legacy_state(
+ legacy_root: Path | None = None, runtime_root: Path | None = None
+) -> list[tuple[Path, Path]]:
+ """Move legacy code-relative state directories under the runtime root.
+
+ Idempotent: once a legacy entry has been moved (or was never there),
+ later calls do nothing. A directory that looks like an unrelated Python
+ package (``site-packages/runs`` may be someone else's distribution) is
+ never touched, and a failure in one directory never blocks the others.
+
+ Returns:
+ The ``(source, destination)`` pairs where at least one child moved.
+ """
+ legacy_root = legacy_root if legacy_root is not None else default_legacy_root()
+ runtime_root = runtime_root if runtime_root is not None else get_runtime_root()
+ if legacy_root.resolve() == runtime_root.resolve():
+ return []
+
+ moved: list[tuple[Path, Path]] = []
+ for legacy_sub, new_sub in _LEGACY_DIRS:
+ source = legacy_root / legacy_sub
+ destination = runtime_root / new_sub
+ try:
+ _recover_staging(source, destination)
+ if not _has_content(source):
+ continue
+ if (source / "__init__.py").exists():
+ logger.warning(
+ "Skipping %s: it looks like a Python package, not Vibe-Trading state.",
+ source,
+ )
+ continue
+ if _merge_children(source, destination):
+ moved.append((source, destination))
+ logger.info("Migrated %s -> %s", source, destination)
+ _remove_empty_source(source)
+ except OSError:
+ logger.warning("Migrating %s failed; continuing.", source, exc_info=True)
+ return moved
diff --git a/agent/src/config/paths.py b/agent/src/config/paths.py
index d260b090f..43244790b 100644
--- a/agent/src/config/paths.py
+++ b/agent/src/config/paths.py
@@ -2,10 +2,13 @@
from __future__ import annotations
+import os
from pathlib import Path
_DEFAULT_FILENAMES = ("agent.json", "agent.yaml", "agent.yml")
+_HOME_ENV_VAR = "VIBE_TRADING_HOME"
+
def get_runtime_root(config_path: Path | None = None) -> Path:
"""Return the runtime root directory for user-level agent state.
@@ -16,13 +19,41 @@ def get_runtime_root(config_path: Path | None = None) -> Path:
Returns:
The directory containing the explicit structured config file when one
- is provided, otherwise the default ``~/.vibe-trading`` runtime root.
+ is provided, otherwise the ``VIBE_TRADING_HOME`` environment override,
+ otherwise the default ``~/.vibe-trading`` runtime root.
"""
if config_path is not None:
return config_path.expanduser().parent
+ env_root = os.environ.get(_HOME_ENV_VAR, "").strip()
+ if env_root:
+ if env_root.startswith(("//", "\\\\")):
+ raise ValueError(
+ f"{_HOME_ENV_VAR} must not be a UNC path: {env_root!r}"
+ )
+ return Path(env_root).expanduser()
return Path.home() / ".vibe-trading"
+def get_sessions_dir() -> Path:
+ """Return the user-level directory holding chat session records."""
+ return get_runtime_root() / "sessions"
+
+
+def get_runs_dir() -> Path:
+ """Return the user-level directory holding run artifacts."""
+ return get_runtime_root() / "runs"
+
+
+def get_swarm_runs_dir() -> Path:
+ """Return the user-level directory holding swarm run records."""
+ return get_runtime_root() / "swarm" / "runs"
+
+
+def get_uploads_dir() -> Path:
+ """Return the user-level directory holding uploaded files."""
+ return get_runtime_root() / "uploads"
+
+
def get_config_candidates(config_path: Path | None = None) -> list[Path]:
"""Return supported config path candidates in lookup order.
diff --git a/agent/src/goal/store.py b/agent/src/goal/store.py
index 3173126e1..4067d804c 100644
--- a/agent/src/goal/store.py
+++ b/agent/src/goal/store.py
@@ -28,10 +28,11 @@ from src.goal.models import (
RiskTier,
StaleGoalError,
)
+from src.config.paths import get_runtime_root
from src.goal.policy import normalize_required_text, reject_live_execution_objective
from src.tools.path_utils import safe_document_path, safe_run_id
-_DEFAULT_DB_PATH = Path.home() / ".vibe-trading" / "sessions.db"
+_DEFAULT_DB_PATH = get_runtime_root() / "sessions.db"
_DB_PATH_ENV = "VIBE_TRADING_GOAL_DB_PATH"
_CURRENT_STATUSES = {
diff --git a/agent/src/session/search.py b/agent/src/session/search.py
index 3bb2ca835..bf68ee2d4 100644
--- a/agent/src/session/search.py
+++ b/agent/src/session/search.py
@@ -4,7 +4,8 @@ Stores an inverted index of all conversation messages. The primary data
remains in the file-based SessionStore; this module provides a fast search
layer on top.
-Database location: ~/.vibe-trading/sessions.db (WAL mode for concurrent reads).
+Database location: ``sessions.db`` under the runtime root (default
+``~/.vibe-trading``; WAL mode for concurrent reads).
"""
from __future__ import annotations
@@ -18,9 +19,11 @@ from datetime import datetime
from pathlib import Path
from typing import List, Optional
+from src.config.paths import get_runtime_root
+
logger = logging.getLogger(__name__)
-_DB_PATH = Path.home() / ".vibe-trading" / "sessions.db"
+_DB_PATH = get_runtime_root() / "sessions.db"
@dataclass(frozen=True)
diff --git a/agent/src/swarm/store.py b/agent/src/swarm/store.py
index a90606209..20e7a429c 100644
--- a/agent/src/swarm/store.py
+++ b/agent/src/swarm/store.py
@@ -71,7 +71,9 @@ def swarm_runs_root() -> Path:
run_dir outside the allow-list (P03-A). Deriving it here once keeps
the store location and the allow-list from drifting again.
"""
- return Path(__file__).resolve().parents[2] / ".swarm" / "runs"
+ from src.config.paths import get_swarm_runs_dir
+
+ return get_swarm_runs_dir()
_TRANSIENT_WINERRORS = (5, 32) # ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION
diff --git a/agent/src/tools/path_utils.py b/agent/src/tools/path_utils.py
index 2c36caa62..01843242d 100644
--- a/agent/src/tools/path_utils.py
+++ b/agent/src/tools/path_utils.py
@@ -83,9 +83,12 @@ def _configured_file_roots() -> list[Path]:
def _default_file_roots() -> list[Path]:
"""Return default roots for uploaded/imported user files."""
+ from src.config.paths import get_runtime_root
+
cwd = Path.cwd().resolve()
home = Path.home().resolve()
agent_root = _agent_root()
+ runtime_root = get_runtime_root()
return [
agent_root / "uploads",
agent_root / "runs",
@@ -93,22 +96,30 @@ def _default_file_roots() -> list[Path]:
cwd / "data",
home / ".vibe-trading" / "uploads",
home / ".vibe-trading" / "imports",
+ runtime_root / "uploads",
+ runtime_root / "runs",
+ runtime_root / "imports",
]
def _default_run_roots() -> list[Path]:
"""Return default roots for generated backtest/tool run directories."""
+ from src.config.paths import get_runtime_root
from src.swarm.store import swarm_runs_root
cwd = Path.cwd().resolve()
home = Path.home().resolve()
agent_root = _agent_root()
+ runtime_root = get_runtime_root()
return [
agent_root / "runs",
+ agent_root / ".swarm" / "runs", # un-migrated legacy swarm runs
swarm_runs_root(),
cwd / "runs",
home / ".vibe-trading" / "shadow_runs",
home / ".vibe-trading" / "runs",
+ runtime_root / "shadow_runs",
+ runtime_root / "runs",
]
@@ -136,15 +147,20 @@ def allowed_write_roots() -> list[Path]:
_rejects_unc(item)
configured.append(Path(item).expanduser().resolve())
+ from src.config.paths import get_runtime_root
+
cwd = Path.cwd().resolve()
home = Path.home().resolve()
agent_root = _agent_root()
+ runtime_root = get_runtime_root()
defaults = [
agent_root / "uploads",
agent_root / "runs",
cwd / "uploads",
home / ".vibe-trading" / "uploads",
home / ".vibe-trading" / "runs",
+ runtime_root / "uploads",
+ runtime_root / "runs",
]
roots: list[Path] = []
@@ -236,18 +252,20 @@ def _import_candidate(p: str) -> Path:
"""Return the filesystem candidate for an import path.
Browser uploads are exposed as ``uploads/<name>`` so the UI never needs
- a local absolute path. Resolve that handle back to the agent upload root
- before enforcing the allowlist.
+ a local absolute path. Resolve that handle back to the user-level upload
+ root before enforcing the allowlist.
"""
+ from src.config.paths import get_uploads_dir
+
candidate = Path(p).expanduser()
if candidate.is_absolute():
return candidate.resolve()
parts = candidate.parts
if parts and parts[0] == "uploads":
- return (_agent_root() / candidate).resolve()
+ return (get_uploads_dir() / Path(*parts[1:])).resolve()
if len(parts) >= 2 and parts[0] == "agent" and parts[1] == "uploads":
- return (_agent_root() / Path(*parts[1:])).resolve()
+ return (get_uploads_dir() / Path(*parts[2:])).resolve()
return (Path.cwd() / candidate).resolve()
diff --git a/agent/src/tools/swarm_tool.py b/agent/src/tools/swarm_tool.py
index 112c0a3fb..966563935 100644
--- a/agent/src/tools/swarm_tool.py
+++ b/agent/src/tools/swarm_tool.py
@@ -11,7 +11,6 @@ import logging
import os
import re
import time
-from pathlib import Path
from typing import Any
from src.agent.tools import BaseTool
@@ -757,9 +756,9 @@ class SwarmTool(BaseTool):
from src.config import load_swarm_agent_config
from src.swarm.runtime import SwarmRuntime
- from src.swarm.store import SwarmStore
+ from src.swarm.store import SwarmStore, swarm_runs_root
- swarm_base_dir = Path(__file__).resolve().parents[2] / ".swarm" / "runs"
+ swarm_base_dir = swarm_runs_root()
swarm_base_dir.mkdir(parents=True, exist_ok=True)
store = SwarmStore(base_dir=swarm_base_dir)
# Boot-time / operator-trusted: even when reached via the in-process
diff --git a/agent/tests/test_path_safety.py b/agent/tests/test_path_safety.py
index 01bc4f4c4..2e5c75bdc 100644
--- a/agent/tests/test_path_safety.py
+++ b/agent/tests/test_path_safety.py
@@ -105,10 +105,12 @@ class TestSafeUserPath:
class TestSafeDocumentPath:
- def test_upload_handle_resolves_to_agent_uploads(self) -> None:
+ def test_upload_handle_resolves_to_runtime_uploads(self) -> None:
+ from src.config.paths import get_uploads_dir
+
result = safe_document_path("uploads/local.csv")
- assert result == (Path(__file__).resolve().parents[1] / "uploads" / "local.csv").resolve()
+ assert result == (get_uploads_dir() / "local.csv").resolve()
def test_upload_handle_traversal_is_rejected(self) -> None:
with pytest.raises(ValueError, match="outside allowed document roots"):
diff --git a/agent/tests/test_state_migration.py b/agent/tests/test_state_migration.py
new file mode 100644
index 000000000..64ffbb140
--- /dev/null
+++ b/agent/tests/test_state_migration.py
@@ -0,0 +1,218 @@
+"""One-time migration of code-relative state into the runtime root (issue #904)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from src.config.migrate import migrate_legacy_state
+
+
+def _seed(directory: Path, filename: str = "record.json") -> Path:
+ directory.mkdir(parents=True)
+ marker = directory / filename
+ marker.write_text("{}", encoding="utf-8")
+ return marker
+
+
+def test_moves_all_legacy_dirs_into_runtime_root(tmp_path: Path) -> None:
+ legacy = tmp_path / "install"
+ root = tmp_path / "runtime"
+ _seed(legacy / "sessions")
+ _seed(legacy / "runs")
+ _seed(legacy / ".swarm" / "runs")
+ _seed(legacy / "uploads")
+
+ moved = migrate_legacy_state(legacy_root=legacy, runtime_root=root)
+
+ assert (root / "sessions" / "record.json").is_file()
+ assert (root / "runs" / "record.json").is_file()
+ assert (root / "swarm" / "runs" / "record.json").is_file()
+ assert (root / "uploads" / "record.json").is_file()
+ assert not (legacy / "sessions").exists()
+ assert not (legacy / "runs").exists()
+ assert not (legacy / ".swarm" / "runs").exists()
+ assert not (legacy / "uploads").exists()
+ assert len(moved) == 4
+
+
+def test_noop_when_legacy_dirs_missing_or_empty(tmp_path: Path) -> None:
+ legacy = tmp_path / "install"
+ root = tmp_path / "runtime"
+ (legacy / "sessions").mkdir(parents=True) # empty dir: nothing to migrate
+
+ moved = migrate_legacy_state(legacy_root=legacy, runtime_root=root)
+
+ assert moved == []
+ assert not root.exists()
+
+
+def test_merges_non_colliding_children_when_both_locations_have_data(
+ tmp_path: Path,
+) -> None:
+ """Destination data (e.g. autopilot runs) must not block migrating the rest."""
+ legacy = tmp_path / "install"
+ root = tmp_path / "runtime"
+ (legacy / "sessions" / "sess-old").mkdir(parents=True)
+ (legacy / "sessions" / "sess-old" / "messages.jsonl").write_text("{}")
+ (root / "sessions" / "sess-new").mkdir(parents=True)
+ (root / "sessions" / "sess-new" / "messages.jsonl").write_text("{}")
+
+ moved = migrate_legacy_state(legacy_root=legacy, runtime_root=root)
+
+ assert (root / "sessions" / "sess-old" / "messages.jsonl").is_file()
+ assert (root / "sessions" / "sess-new" / "messages.jsonl").is_file()
+ assert not (legacy / "sessions").exists()
+ assert len(moved) == 1
+
+
+def test_colliding_children_are_left_in_place(tmp_path: Path) -> None:
+ """A same-named child on both sides is never overwritten or merged."""
+ legacy = tmp_path / "install"
+ root = tmp_path / "runtime"
+ (legacy / "runs" / "run-a").mkdir(parents=True)
+ (legacy / "runs" / "run-a" / "metrics.json").write_text("old")
+ (legacy / "runs" / "run-b").mkdir(parents=True)
+ (legacy / "runs" / "run-b" / "metrics.json").write_text("{}")
+ (root / "runs" / "run-a").mkdir(parents=True)
+ (root / "runs" / "run-a" / "metrics.json").write_text("new")
+
+ migrate_legacy_state(legacy_root=legacy, runtime_root=root)
+
+ assert (root / "runs" / "run-a" / "metrics.json").read_text() == "new"
+ assert (legacy / "runs" / "run-a" / "metrics.json").read_text() == "old"
+ assert (root / "runs" / "run-b" / "metrics.json").is_file()
+ assert (legacy / "runs").exists() # collision child keeps the dir alive
+
+
+def test_skips_directories_that_are_python_packages(tmp_path: Path) -> None:
+ """site-packages/runs may be an unrelated installed distribution."""
+ legacy = tmp_path / "site-packages"
+ root = tmp_path / "runtime"
+ _seed(legacy / "runs", "__init__.py")
+ _seed(legacy / "sessions")
+
+ moved = migrate_legacy_state(legacy_root=legacy, runtime_root=root)
+
+ assert (legacy / "runs" / "__init__.py").is_file()
+ assert not (root / "runs").exists()
+ assert (root / "sessions" / "record.json").is_file()
+ assert len(moved) == 1
+
+
+def test_one_failing_directory_does_not_block_the_rest(tmp_path: Path) -> None:
+ legacy = tmp_path / "install"
+ root = tmp_path / "runtime"
+ _seed(legacy / "sessions")
+ _seed(legacy / "uploads")
+ root.mkdir()
+ (root / "sessions").write_text("a file where a directory belongs")
+
+ moved = migrate_legacy_state(legacy_root=legacy, runtime_root=root)
+
+ assert (root / "uploads" / "record.json").is_file()
+ assert (legacy / "sessions" / "record.json").is_file() # failed entry untouched
+ assert len(moved) == 1
+
+
+def test_symlinked_destination_receives_children(tmp_path: Path) -> None:
+ legacy = tmp_path / "install"
+ root = tmp_path / "runtime"
+ target = tmp_path / "bigdisk-runs"
+ target.mkdir()
+ root.mkdir()
+ (root / "runs").symlink_to(target)
+ _seed(legacy / "runs")
+ _seed(legacy / "uploads")
+
+ moved = migrate_legacy_state(legacy_root=legacy, runtime_root=root)
+
+ assert (target / "record.json").is_file()
+ assert (root / "uploads" / "record.json").is_file() # later entries unaffected
+ assert len(moved) == 2
+
+
+def test_stale_partial_tmp_is_discarded_and_move_redone(tmp_path: Path) -> None:
+ """A crash mid-copy leaves .migrating-*; source intact means redo cleanly."""
+ legacy = tmp_path / "install"
+ root = tmp_path / "runtime"
+ (legacy / "sessions" / "sess-1").mkdir(parents=True)
+ (legacy / "sessions" / "sess-1" / "messages.jsonl").write_text("full")
+ partial = root / "sessions" / ".migrating-99999-sess-1"
+ partial.mkdir(parents=True)
+ (partial / "messages.jsonl").write_text("par")
+
+ migrate_legacy_state(legacy_root=legacy, runtime_root=root)
+
+ assert (root / "sessions" / "sess-1" / "messages.jsonl").read_text() == "full"
+ assert not partial.exists()
+
+
+def test_stale_complete_tmp_is_promoted_when_source_is_gone(tmp_path: Path) -> None:
+ """A crash after the copy but before the rename must not lose the data."""
+ legacy = tmp_path / "install"
+ root = tmp_path / "runtime"
+ _seed(legacy / "uploads") # unrelated entry so migration has work to do
+ (legacy / "sessions").mkdir()
+ orphan = root / "sessions" / ".migrating-99999-sess-1"
+ orphan.mkdir(parents=True)
+ (orphan / "messages.jsonl").write_text("full")
+
+ migrate_legacy_state(legacy_root=legacy, runtime_root=root)
+
+ assert (root / "sessions" / "sess-1" / "messages.jsonl").read_text() == "full"
+ assert not orphan.exists()
+
+
+def test_empty_swarm_shell_is_removed_after_migration(tmp_path: Path) -> None:
+ legacy = tmp_path / "install"
+ root = tmp_path / "runtime"
+ _seed(legacy / ".swarm" / "runs")
+
+ migrate_legacy_state(legacy_root=legacy, runtime_root=root)
+
+ assert (root / "swarm" / "runs" / "record.json").is_file()
+ assert not (legacy / ".swarm").exists()
+
+
+def test_replaces_empty_destination_directory(tmp_path: Path) -> None:
+ legacy = tmp_path / "install"
+ root = tmp_path / "runtime"
+ _seed(legacy / "runs")
+ (root / "runs").mkdir(parents=True) # pre-created but empty
+
+ moved = migrate_legacy_state(legacy_root=legacy, runtime_root=root)
+
+ assert (root / "runs" / "record.json").is_file()
+ assert not (legacy / "runs").exists()
+ assert len(moved) == 1
+
+
+def test_second_run_is_a_noop(tmp_path: Path) -> None:
+ legacy = tmp_path / "install"
+ root = tmp_path / "runtime"
+ _seed(legacy / "sessions")
+
+ first = migrate_legacy_state(legacy_root=legacy, runtime_root=root)
+ second = migrate_legacy_state(legacy_root=legacy, runtime_root=root)
+
+ assert len(first) == 1
+ assert second == []
+
+
+def test_default_legacy_root_matches_pre_904_agent_dir() -> None:
+ """The default legacy root must equal the old AGENT_DIR expression."""
+ import cli._legacy as legacy
+
+ from src.config.migrate import default_legacy_root
+
+ assert default_legacy_root() == Path(legacy.__file__).resolve().parents[1]
+
+
+def test_skips_when_legacy_root_equals_runtime_root(tmp_path: Path) -> None:
+ root = tmp_path / "runtime"
+ _seed(root / "sessions")
+
+ moved = migrate_legacy_state(legacy_root=root, runtime_root=root)
+
+ assert moved == []
+ assert (root / "sessions" / "record.json").is_file()
diff --git a/agent/tests/test_state_migration_wiring.py b/agent/tests/test_state_migration_wiring.py
new file mode 100644
index 000000000..d1be6623f
--- /dev/null
+++ b/agent/tests/test_state_migration_wiring.py
@@ -0,0 +1,72 @@
+"""Entry points run the one-time legacy-state migration (issue #904)."""
+
+from __future__ import annotations
+
+import pytest
+
+from src.config import migrate
+
+
+def record_migration(monkeypatch: pytest.MonkeyPatch) -> list[int]:
+ calls: list[int] = []
+ monkeypatch.setattr(
+ migrate, "migrate_legacy_state", lambda *a, **k: calls.append(1) or []
+ )
+ return calls
+
+
+def test_cli_main_runs_migration(
+ monkeypatch: pytest.MonkeyPatch, record_migration: list[int]
+) -> None:
+ import importlib
+
+ import cli._legacy as legacy
+
+ cli_main = importlib.import_module("cli.main")
+
+ monkeypatch.setattr(cli_main, "_is_interactive_invocation", lambda argv: False)
+ monkeypatch.setattr(legacy, "main", lambda argv: 0)
+
+ assert cli_main.main(["list"]) == 0
+ assert record_migration
+
+
+def test_mcp_server_main_runs_migration(
+ monkeypatch: pytest.MonkeyPatch, record_migration: list[int]
+) -> None:
+ import mcp_server
+
+ monkeypatch.setattr(
+ "sys.argv", ["vibe-trading-mcp", "--transport", "stdio"]
+ )
+ monkeypatch.setattr(mcp_server.mcp, "run", lambda **kwargs: None)
+
+ mcp_server.main()
+ assert record_migration
+
+
+def test_api_startup_runs_migration(
+ monkeypatch: pytest.MonkeyPatch, record_migration: list[int]
+) -> None:
+ import asyncio
+
+ import api_server
+
+ monkeypatch.setattr("src.preflight.run_preflight", lambda console: None)
+ monkeypatch.setattr(api_server, "_start_scheduled_research_executor", lambda: None)
+ monkeypatch.setattr(
+ "src.config.accessor.get_env_config",
+ lambda: type(
+ "Cfg",
+ (),
+ {
+ "agent_tuning": type(
+ "Tuning", (), {"vibe_trading_channels_auto_start": False}
+ )()
+ },
+ )(),
+ )
+
+ asyncio.run(api_server._run_startup_preflight())
+ assert record_migration
diff --git a/agent/tests/test_swarm_runs_root_and_shell_tools.py b/agent/tests/test_swarm_runs_root_and_shell_tools.py
index 89a06095a..8c020dbfa 100644
--- a/agent/tests/test_swarm_runs_root_and_shell_tools.py
+++ b/agent/tests/test_swarm_runs_root_and_shell_tools.py
@@ -38,7 +38,7 @@ def test_default_run_roots_uses_single_source():
def test_swarm_runs_root_stable_and_swarm_scoped():
root = swarm_runs_root()
assert root == swarm_runs_root() # deterministic
- assert root.name == "runs" and root.parent.name == ".swarm"
+ assert root.name == "runs" and root.parent.name == "swarm"
# ---- P03-B: filtered registry must keep / not silently drop tools ----------
diff --git a/agent/tests/test_user_state_paths.py b/agent/tests/test_user_state_paths.py
new file mode 100644
index 000000000..037076390
--- /dev/null
+++ b/agent/tests/test_user_state_paths.py
@@ -0,0 +1,248 @@
+"""User-level state directory resolution (issue #904).
+
+Session/run/upload history must live under the runtime root
+(``~/.vibe-trading`` by default), never relative to the installed code.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from src.config.paths import get_runtime_root
+
+
+def test_runtime_root_defaults_to_home(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)
+
+ assert get_runtime_root() == Path.home() / ".vibe-trading"
+
+
+def test_runtime_root_honors_env_override(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path / "custom-root"))
+
+ assert get_runtime_root() == tmp_path / "custom-root"
+
+
+def test_runtime_root_expands_user_in_env_override(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("VIBE_TRADING_HOME", "~/elsewhere")
+
+ assert get_runtime_root() == Path.home() / "elsewhere"
+
+
+def test_explicit_config_path_beats_env_override(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path / "custom-root"))
+ config_path = tmp_path / "explicit" / "agent.json"
+
+ assert get_runtime_root(config_path) == config_path.parent
+
+
+def test_home_override_rejects_unc_paths(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Match the UNC hardening every other root-widening env var enforces."""
+ for unc in ("//server/share", r"\\server\share"):
+ monkeypatch.setenv("VIBE_TRADING_HOME", unc)
+ with pytest.raises(ValueError, match="UNC"):
+ get_runtime_root()
+
+
+def test_legacy_swarm_runs_kept_in_run_root_allowlist() -> None:
+ """Un-migrated legacy swarm runs must stay reachable, like legacy runs/uploads."""
+ from src.tools.path_utils import _agent_root, _default_run_roots
+
+ roots = [p.resolve() for p in _default_run_roots()]
+
+ assert (_agent_root() / ".swarm" / "runs").resolve() in roots
+
+
+def test_state_dir_helpers_live_under_runtime_root(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ from src.config.paths import (
+ get_runs_dir,
+ get_sessions_dir,
+ get_swarm_runs_dir,
+ get_uploads_dir,
+ )
+
+ root = tmp_path / "state-root"
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(root))
+
+ assert get_sessions_dir() == root / "sessions"
+ assert get_runs_dir() == root / "runs"
+ assert get_swarm_runs_dir() == root / "swarm" / "runs"
+ assert get_uploads_dir() == root / "uploads"
+
+
+def test_legacy_cli_constants_derive_from_runtime_root() -> None:
+ from cli import _legacy
+ from src.config import paths
+
+ assert _legacy.SESSIONS_DIR == paths.get_sessions_dir()
+ assert _legacy.RUNS_DIR == paths.get_runs_dir()
+ assert _legacy.SWARM_DIR == paths.get_swarm_runs_dir()
+ assert _legacy.UPLOADS_DIR == paths.get_uploads_dir()
+
+
+def test_agent_loop_constants_derive_from_runtime_root() -> None:
+ from src.agent import loop
+ from src.config import paths
+
+ assert loop.RUNS_DIR == paths.get_runs_dir()
+ assert loop.SESSIONS_DIR == paths.get_sessions_dir()
+
+
+def test_api_constants_derive_from_runtime_root() -> None:
+ from src.api import helpers, uploads_routes
+ from src.config import paths
+
+ assert helpers.RUNS_DIR == paths.get_runs_dir()
+ assert helpers.SESSIONS_DIR == paths.get_sessions_dir()
+ assert helpers.UPLOADS_DIR == paths.get_uploads_dir()
+ assert uploads_routes.UPLOADS_DIR == paths.get_uploads_dir()
+
+
+def test_api_swarm_runtime_uses_swarm_runs_root(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The HTTP API swarm store must share swarm_runs_root() with CLI/MCP."""
+ from src.api import swarm_routes
+ from src.swarm.store import swarm_runs_root
+
+ monkeypatch.setattr(swarm_routes, "_swarm_runtime", None)
+ monkeypatch.setattr(
+ "src.config.load_swarm_agent_config", lambda *a, **k: object()
+ )
+
+ runtime = swarm_routes._get_swarm_runtime()
+
+ assert runtime._store.base_dir == swarm_runs_root()
+
+
+def test_swarm_runs_root_derives_from_runtime_root() -> None:
+ from src.config import paths
+ from src.swarm.store import swarm_runs_root
+
+ assert swarm_runs_root() == paths.get_swarm_runs_dir()
+
+
+def test_trace_lookup_searches_runtime_root(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ from src.agent.trace import TraceWriter
+
+ root = tmp_path / "state-root"
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(root))
+ trace_dir = root / "sessions" / "sess-1"
+ trace_dir.mkdir(parents=True)
+ (trace_dir / "trace.jsonl").write_text("", encoding="utf-8")
+
+ assert TraceWriter.find_trace_dir("sess-1") == trace_dir
+
+
+def test_upload_handle_resolves_to_runtime_uploads_dir(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ from src.tools.path_utils import _import_candidate
+
+ root = tmp_path / "state-root"
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(root))
+
+ assert _import_candidate("uploads/report.pdf") == root / "uploads" / "report.pdf"
+ assert (
+ _import_candidate("agent/uploads/report.pdf")
+ == root / "uploads" / "report.pdf"
+ )
+
+
+def test_sandbox_roots_follow_home_override(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ from src.tools.path_utils import allowed_file_roots, allowed_write_roots
+
+ root = tmp_path / "state-root"
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(root))
+
+ file_roots = allowed_file_roots()
+ write_roots = allowed_write_roots()
+
+ assert (root / "uploads").resolve() in file_roots
+ assert (root / "runs").resolve() in file_roots
+ assert (root / "uploads").resolve() in write_roots
+ assert (root / "runs").resolve() in write_roots
+
+
+def test_sessions_db_and_goal_db_follow_home_override(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """The FTS index and goal store must live beside the sessions they index."""
+ import importlib
+
+ from src.goal import store as goal_store
+ from src.session import search
+
+ root = tmp_path / "state-root"
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(root))
+ try:
+ assert importlib.reload(search)._DB_PATH == root / "sessions.db"
+ assert (
+ importlib.reload(goal_store)._DEFAULT_DB_PATH == root / "sessions.db"
+ )
+ finally:
+ monkeypatch.delenv("VIBE_TRADING_HOME")
+ importlib.reload(search)
+ importlib.reload(goal_store)
+
+
+def test_banner_session_probe_follows_home_override(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ import sqlite3
+
+ import importlib
+
+ cli_main = importlib.import_module("cli.main")
+
+ root = tmp_path / "state-root"
+ root.mkdir()
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(root))
+ with sqlite3.connect(str(root / "sessions.db")) as conn:
+ conn.execute("CREATE TABLE sessions (id TEXT)")
+ conn.execute("INSERT INTO sessions VALUES ('a'), ('b')")
+
+ assert cli_main._probe_session_count() == 2
+
+
+def test_welcome_panel_reports_runtime_root_as_workspace(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from rich.console import Console
+
+ from cli import _legacy
+
+ monkeypatch.setattr(_legacy, "get_runtime_root", lambda: Path("/RTROOT"))
+
+ console = Console(width=200, record=True)
+ console.print(_legacy._build_welcome_panel(term_width=120))
+
+ assert "/RTROOT" in console.export_text()
+
+
+def test_state_dir_helpers_do_not_create_directories(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ from src.config.paths import get_runs_dir, get_sessions_dir
+
+ root = tmp_path / "state-root"
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(root))
+
+ get_sessions_dir()
+ get_runs_dir()
+
+ assert not root.exists()