Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(swarm): discover user presets from ~/.vibe-trading/swarm/presets

Ali Emadie04c98ca5b66
diff --git a/CHANGELOG.md b/CHANGELOG.md
index adb2a87a8..66fa5a704 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,14 @@ This project adheres to [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
+- **User swarm-presets directory**: preset YAMLs dropped into
+ `~/.vibe-trading/swarm/presets/` are discovered alongside the bundled
+ roster (same-name files override it — the same rule as user skills) and
+ survive `pip install -U`. `list_presets()` entries now carry a
+ `source: "user" | "bundled"` field; explicitly named user presets run
+ through `run_swarm(preset_name=...)`, while keyword auto-routing stays
+ limited to the curated table. Preset names are validated to a single path
+ segment before any filesystem lookup.
- **Security hardening**: all 10 findings from the 2026-07-10 external audit
closed (#476, tracking discussion #468) — Docker multi-stage rebuild with
digest-pinned base images, AST-hardened backtest sandbox (blocks
diff --git a/README.md b/README.md
index 59e98a8e0..4d5145871 100644
--- a/README.md
+++ b/README.md
@@ -435,6 +435,8 @@ run from a clone (`pip install -e .`).
| `global_allocation_committee` | A-shares + crypto + HK/US → cross-market allocation |
<sub>Plus 20+ additional specialist presets — run vibe-trading --swarm-presets to explore all.
+Bring your own: drop preset YAMLs into <code>~/.vibe-trading/swarm/presets/</code> — they are listed
+alongside the bundled roster (same-name files override it, like user skills) and survive upgrades.
</sub>
diff --git a/agent/src/swarm/presets.py b/agent/src/swarm/presets.py
index e5ae7135d..5468c9123 100644
--- a/agent/src/swarm/presets.py
+++ b/agent/src/swarm/presets.py
@@ -4,6 +4,14 @@ Reads YAML preset files from the bundled ``presets/`` directory next to this
module and parses them into SwarmRun / SwarmAgentSpec / SwarmTask data models.
Keeping the YAMLs inside the ``src.swarm`` package guarantees identical
behavior under editable installs and built wheels.
+
+User-supplied presets are also discovered from ``~/.vibe-trading/swarm/
+presets/`` — the same pattern as user skills (``src/agent/skills.py``):
+the user directory is searched first, so a user preset can both add to and
+override the bundled roster by name, and nothing needs to be copied into
+site-packages (where it would be wiped by the next ``pip install -U``).
+Preset names are validated to a single path segment before any filesystem
+lookup, so a name can never escape either presets directory.
"""
from __future__ import annotations
@@ -20,11 +28,49 @@ from src.swarm.models import RunStatus, SwarmAgentSpec, SwarmRun, SwarmTask, Tas
from src.swarm.task_store import topological_layers, validate_dag
PRESETS_DIR = Path(__file__).resolve().parent / "presets"
+#: User-created presets; searched before the bundled directory so user files
+#: can add to and override the roster by name (mirrors USER_SKILLS_DIR in
+#: ``src/agent/skills.py``). Survives package upgrades.
+USER_PRESETS_DIR = Path.home() / ".vibe-trading" / "swarm" / "presets"
_INTERNAL_TEMPLATE_VARS = {"upstream_context"}
+def _validate_preset_name(name: str) -> str:
+ """Reject names that are empty or could escape a presets directory.
+
+ Preset names map directly to ``<dir>/<name>.yaml``; a name carrying a
+ path separator or ``..`` would resolve outside the directory. The bundled
+ path had the same latent exposure — validating here covers both.
+
+ Returns:
+ The stripped name.
+
+ Raises:
+ ValueError: Empty name, path separators, or parent references.
+ """
+ cleaned = (name or "").strip()
+ if not cleaned or cleaned in {".", ".."} or "/" in cleaned or "\\" in cleaned:
+ raise ValueError(f"invalid preset name: {name!r}")
+ return cleaned
+
+
+def _preset_search_dirs() -> tuple[Path, ...]:
+ """Directories searched for presets, highest priority first."""
+ return (USER_PRESETS_DIR, PRESETS_DIR)
+
+
+def resolve_preset_path(name: str) -> Path | None:
+ """Return the YAML path for *name* (user dir first), or ``None``."""
+ cleaned = _validate_preset_name(name)
+ for directory in _preset_search_dirs():
+ path = directory / f"{cleaned}.yaml"
+ if path.is_file():
+ return path
+ return None
+
+
def load_preset(name: str) -> dict:
- """Load a YAML preset by name.
+ """Load a YAML preset by name (user directory first, then bundled).
Args:
name: Preset name (without .yaml extension).
@@ -33,42 +79,59 @@ def load_preset(name: str) -> dict:
Parsed YAML dict.
Raises:
- FileNotFoundError: If the preset file does not exist.
+ ValueError: If the name is empty or contains path separators.
+ FileNotFoundError: If the preset file does not exist in either the
+ user directory (``~/.vibe-trading/swarm/presets/``) or the
+ bundled package directory.
"""
- path = PRESETS_DIR / f"{name}.yaml"
- if not path.exists():
- available = [p.stem for p in PRESETS_DIR.glob("*.yaml")] if PRESETS_DIR.exists() else []
+ path = resolve_preset_path(name)
+ if path is None:
+ available = sorted({
+ p.stem
+ for directory in _preset_search_dirs()
+ if directory.exists()
+ for p in directory.glob("*.yaml")
+ })
raise FileNotFoundError(
- f"Preset {name!r} not found. Available: {available}"
+ f"Preset {name!r} not found in {USER_PRESETS_DIR} or the bundled "
+ f"presets. Available: {available}"
)
return yaml.safe_load(path.read_text(encoding="utf-8"))
def list_presets() -> list[dict]:
- """Return summary info for all available presets.
+ """Return summary info for all available presets, sorted by name.
+
+ User presets (``~/.vibe-trading/swarm/presets/``) are listed alongside the
+ bundled roster; when both directories carry the same file stem, the user
+ preset wins — the same override rule as user skills.
Returns:
- List of dicts with keys: name, title, description, agent_count, variables.
+ List of dicts with keys: name, title, description, agent_count,
+ variables, source (``"user"`` or ``"bundled"``).
"""
- if not PRESETS_DIR.exists():
- return []
-
- results: list[dict] = []
- for path in sorted(PRESETS_DIR.glob("*.yaml")):
- try:
- data = yaml.safe_load(path.read_text(encoding="utf-8"))
- except Exception:
+ by_stem: dict[str, dict] = {}
+ for directory, source in ((PRESETS_DIR, "bundled"), (USER_PRESETS_DIR, "user")):
+ if not directory.exists():
continue
+ for path in sorted(directory.glob("*.yaml")):
+ try:
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
+ except Exception:
+ continue
+ if not isinstance(data, dict):
+ continue
+ # Later iteration (user) intentionally replaces bundled stems.
+ by_stem[path.stem] = {
+ "name": data.get("name", path.stem),
+ "title": data.get("title", ""),
+ "description": data.get("description", ""),
+ "agent_count": len(data.get("agents", [])),
+ "variables": data.get("variables", []),
+ "source": source,
+ }
- results.append({
- "name": data.get("name", path.stem),
- "title": data.get("title", ""),
- "description": data.get("description", ""),
- "agent_count": len(data.get("agents", [])),
- "variables": data.get("variables", []),
- })
-
- return results
+ return sorted(by_stem.values(), key=lambda entry: entry["name"])
def _declared_variable_names(raw_variables: list) -> set[str]:
diff --git a/agent/src/tools/swarm_tool.py b/agent/src/tools/swarm_tool.py
index aad4d7b27..112c0a3fb 100644
--- a/agent/src/tools/swarm_tool.py
+++ b/agent/src/tools/swarm_tool.py
@@ -434,9 +434,25 @@ _CONTINUATION_PATTERNS = (
def _normalize_preset_name(value: str) -> str | None:
- """Normalize an explicit preset name and validate it against bundled presets."""
+ """Normalize an explicit preset name and validate it resolves to a preset.
+
+ Names in the static routing table are accepted as before. Names outside it
+ are accepted only when they resolve to an actual preset file — which lets
+ explicitly named user presets (``~/.vibe-trading/swarm/presets/``) run
+ through this tool. Keyword ROUTING stays limited to the curated table: a
+ user preset is reachable only by naming it, never by keyword match.
+ """
normalized = re.sub(r"[\s-]+", "_", value.strip().lower())
- return normalized if normalized in _PRESET_NAMES else None
+ if normalized in _PRESET_NAMES:
+ return normalized
+ from src.swarm.presets import resolve_preset_path
+
+ try:
+ if resolve_preset_path(normalized) is not None:
+ return normalized
+ except ValueError:
+ return None
+ return None
def _has_preset_signal(prompt: str) -> bool:
@@ -463,7 +479,10 @@ def _resolve_preset(prompt: str, explicit_preset: str | None = None) -> tuple[st
preset = _normalize_preset_name(explicit_preset)
if preset is None:
available = ", ".join(sorted(_PRESET_NAMES))
- return None, f"Unknown preset_name '{explicit_preset}'. Available presets: {available}"
+ return None, (
+ f"Unknown preset_name '{explicit_preset}'. Available presets: {available}. "
+ "User presets in ~/.vibe-trading/swarm/presets/ are also accepted by name."
+ )
return preset, None
if _looks_like_continuation_prompt(prompt) and not _has_preset_signal(prompt):
diff --git a/agent/tests/test_swarm_presets_packaging.py b/agent/tests/test_swarm_presets_packaging.py
index 96b5e98d5..0d3329be1 100644
--- a/agent/tests/test_swarm_presets_packaging.py
+++ b/agent/tests/test_swarm_presets_packaging.py
@@ -32,7 +32,9 @@ def test_presets_dir_lives_inside_swarm_package() -> None:
def test_list_presets_returns_full_roster() -> None:
- presets = list_presets()
+ # Filter to bundled entries so a developer's own ~/.vibe-trading user
+ # presets can never make the packaging regression flap.
+ presets = [p for p in list_presets() if p["source"] == "bundled"]
assert len(presets) == EXPECTED_PRESET_COUNT, (
f"expected {EXPECTED_PRESET_COUNT} presets, got {len(presets)} — "
"check pyproject package-data and that YAMLs were not dropped"
@@ -65,3 +67,95 @@ def test_known_presets_load(preset_name: str) -> None:
"""Spot-check a few headline presets advertised in docs/UI."""
data = load_preset(preset_name)
assert data["agents"], f"{preset_name} has no agents"
+
+
+# ── User presets directory (~/.vibe-trading/swarm/presets/) ──────────────────
+
+
+_USER_PRESET_YAML = """\
+name: my_custom_desk
+title: "My Custom Desk"
+description: "User-supplied preset."
+agents:
+ - id: analyst
+ role: Analyst
+ system_prompt: "Analyze {topic}."
+ tools: [read_file]
+tasks:
+ - id: task-analyze
+ agent_id: analyst
+ prompt_template: "Analyze {topic}."
+ depends_on: []
+variables:
+ - name: topic
+ description: "Subject"
+ required: true
+"""
+
+
+def user_presets_dir(tmp_path, monkeypatch):
+ import src.swarm.presets as presets_module
+
+ user_dir = tmp_path / "user-presets"
+ user_dir.mkdir()
+ monkeypatch.setattr(presets_module, "USER_PRESETS_DIR", user_dir)
+ return user_dir
+
+
+def test_user_preset_is_discovered(user_presets_dir) -> None:
+ (user_presets_dir / "my_custom_desk.yaml").write_text(
+ _USER_PRESET_YAML, encoding="utf-8"
+ )
+ data = load_preset("my_custom_desk")
+ assert data["agents"][0]["id"] == "analyst"
+
+ entries = {p["name"]: p for p in list_presets()}
+ assert entries["my_custom_desk"]["source"] == "user"
+ assert entries["investment_committee"]["source"] == "bundled"
+
+
+def test_user_preset_overrides_bundled_stem(user_presets_dir) -> None:
+ override = _USER_PRESET_YAML.replace("my_custom_desk", "risk_committee")
+ (user_presets_dir / "risk_committee.yaml").write_text(override, encoding="utf-8")
+
+ data = load_preset("risk_committee")
+ assert len(data["agents"]) == 1 # the user file won
+ entries = {p["name"]: p for p in list_presets()}
+ assert entries["risk_committee"]["source"] == "user"
+ # Override replaces, never duplicates.
+ assert sum(p["name"] == "risk_committee" for p in list_presets()) == 1
+
+
+def test_missing_user_dir_changes_nothing(tmp_path, monkeypatch) -> None:
+ import src.swarm.presets as presets_module
+
+ monkeypatch.setattr(presets_module, "USER_PRESETS_DIR", tmp_path / "absent")
+ assert load_preset("risk_committee")["agents"]
+ assert all(p["source"] == "bundled" for p in list_presets())
+
+
[email protected]("bad_name", ["../escape", "a/b", "..", "", "a\\b"])
+def test_path_escaping_names_rejected(bad_name: str) -> None:
+ with pytest.raises(ValueError):
+ load_preset(bad_name)
+
+
+def test_missing_preset_error_names_both_locations(user_presets_dir) -> None:
+ with pytest.raises(FileNotFoundError) as excinfo:
+ load_preset("does_not_exist")
+ message = str(excinfo.value)
+ assert "bundled" in message and str(user_presets_dir) in message
+
+
+def test_explicit_user_preset_accepted_by_swarm_tool(user_presets_dir) -> None:
+ """run_swarm(preset_name=...) reaches user presets; keyword routing does not."""
+ from src.tools.swarm_tool import _match_preset, _normalize_preset_name
+
+ (user_presets_dir / "my_custom_desk.yaml").write_text(
+ _USER_PRESET_YAML, encoding="utf-8"
+ )
+ assert _normalize_preset_name("My Custom Desk") == "my_custom_desk"
+ assert _normalize_preset_name("no_such_preset_anywhere") is None
+ # A user preset must never be reachable via keyword auto-routing.
+ assert _match_preset("please analyze my custom desk topic") != "my_custom_desk"