Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(scheduled): surface research playbooks on CLI, REST and slash

Haozhe Wu9eb681f8ff61
diff --git a/agent/api_server.py b/agent/api_server.py
index d080972c9..960ac9769 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -295,16 +295,16 @@ try_register_openbb_routes(app)
# ============================================================================
# Scheduled Research Routes - defined in src/api/scheduled_routes.py
# ============================================================================
-#
-# Lightweight CRUD endpoints backed by ScheduledResearchJobStore. The endpoint
-# handlers only record and expose jobs; the optional executor lifecycle is
-# guarded separately by VIBE_TRADING_ENABLE_SCHEDULER.
+# Job CRUD plus the playbook-template catalogue, all auth-gated. Handlers only
+# record and expose jobs; execution is guarded by VIBE_TRADING_ENABLE_SCHEDULER.
from src.api.scheduled_routes import register_scheduled_routes # noqa: E402
register_scheduled_routes(app)
from src.api.scheduled_routes import ( # noqa: E402, F401
+ CreateRunFromPlaybookRequest,
CreateScheduledRunRequest,
+ PlaybookResponse,
ScheduledRunResponse,
_dispatch_scheduled_research_job,
_get_scheduled_research_executor,
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 9409f96f1..3ad12c04d 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -4866,6 +4866,10 @@ def _build_parser() -> argparse.ArgumentParser:
from src.hypotheses.cli_handlers import add_subparser as _add_hypothesis_subparser
_add_hypothesis_subparser(subparsers)
+ # Scheduled-research playbook templates (list / show / create)
+ from cli.commands.research_playbook import add_subparser as _add_playbook_subparser
+ _add_playbook_subparser(subparsers)
+
return parser
@@ -5741,6 +5745,9 @@ def main(argv: list[str] | None = None) -> int:
if args.command == "hypothesis":
from src.hypotheses.cli_handlers import dispatch as _hyp_dispatch
return _coerce_exit_code(_hyp_dispatch(args))
+ if args.command == "playbook":
+ from cli.commands.research_playbook import dispatch as _playbook_dispatch
+ return _coerce_exit_code(_playbook_dispatch(args))
if args.command == "connector":
return _coerce_exit_code(_dispatch_connector(args))
if args.command == "memory":
diff --git a/agent/cli/commands/research_playbook.py b/agent/cli/commands/research_playbook.py
new file mode 100644
index 000000000..094cb8fb6
--- /dev/null
+++ b/agent/cli/commands/research_playbook.py
@@ -0,0 +1,660 @@
+"""User-facing entry points for the scheduled-research playbook catalogue.
+
+The catalogue itself lives in :mod:`src.scheduled_research.playbooks` (markdown
+templates with a YAML frontmatter header). Until this module existed the only
+way to reach it was a Python import, so a shipped template was effectively
+invisible. This module is the single place both non-interactive and interactive
+users enter through:
+
+* ``vibe-trading playbook list | show <slug> | create <slug>`` — the argparse
+ subcommand, wired in :mod:`cli._legacy` next to ``alpha`` / ``hypothesis``.
+* ``/playbook`` — the REPL slash command, registered in
+ :mod:`cli.commands.slash_router`, dispatched through ``run(ctx, *args)``.
+
+Two properties this layer is built to preserve:
+
+* **The body is never rewritten.** A template states the data it needs in plain
+ language and deliberately names no tool; routing is the agent's job. Both
+ ``/playbook run`` and ``playbook create`` hand over
+ ``ResearchPlaybook.render()`` output verbatim, so the text executed
+ interactively is byte-identical to the ``prompt`` the scheduler later
+ replays. Nothing here appends tool names, hints, or a preamble.
+* **The schedule is validated by the scheduler's own rules.**
+ ``ResearchPlaybook.to_job`` calls
+ :func:`src.scheduled_research.models.validate_schedule` and
+ ``validate_timezone``; this module only catches the resulting ``ValueError``
+ and prints it. There is no second, drifting copy of the grammar here.
+
+``playbook create`` writes straight to
+:class:`src.scheduled_research.store.ScheduledResearchJobStore` — the same file
+the API server and the executor read. It deliberately does not go through HTTP:
+the store is a file under the user's own runtime root, so a local CLI writing it
+carries exactly the trust of the shell that launched it, and requiring a running
+server to schedule a job would be a worse experience with no security gain. The
+HTTP surface for the same operation stays behind ``require_auth``.
+
+Not to be confused with :mod:`cli.commands.institutional.playbooks`, which holds
+the one-shot ``/comps`` / ``/dcf`` workflow cards. These are recurring research
+templates for the scheduler.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+from typing import Any, Dict, List, Optional, Sequence, Tuple
+
+_HELP_TOKENS = frozenset({"help", "-h", "--help", "?"})
+_LIST_TOKENS = frozenset({"list", "ls", "all"})
+_VAR_TOKEN_RE = re.compile(r"^([A-Za-z0-9_]+)=(.*)$")
+
+# Defensive ceilings. ``ResearchPlaybook.render`` already caps a single
+# substituted value at 4000 chars; these bound the *number* of tokens and the
+# raw argument string so a paste accident cannot make the CLI do silly work
+# before that cap is reached.
+_MAX_VARIABLES = 32
+_MAX_ARG_CHARS = 20000
+
+# "Caller did not override the timezone", distinct from an explicit ``None``
+# (which means UTC and is a legitimate override of a template's suggestion).
+_KEEP_TZ = object()
+
+
+def _console() -> Any:
+ """Return the shared CLI console."""
+ from cli.theme import get_console
+
+ return get_console()
+
+
+def _print(message: str) -> None:
+ """Print one line through the shared console."""
+ _console().print(message)
+
+
+# ---------------------------------------------------------------------------
+# Argument parsing helpers
+# ---------------------------------------------------------------------------
+
+
+def parse_variable_tokens(tokens: Sequence[str]) -> Tuple[Dict[str, str], Optional[str]]:
+ """Parse ``key=value`` tokens, allowing unquoted multi-word values.
+
+ A token that does not look like ``key=`` continues the value of the
+ previous key, so ``home_market=US equities`` works without shell quoting in
+ the REPL. The first token must open a key.
+
+ Args:
+ tokens: Raw whitespace-split arguments.
+
+ Returns:
+ A ``(variables, error)`` pair. ``error`` is ``None`` on success and a
+ user-facing message otherwise; ``variables`` is empty when it is set.
+ """
+ variables: Dict[str, str] = {}
+ order: List[str] = []
+ current: Optional[str] = None
+ for token in tokens:
+ match = _VAR_TOKEN_RE.match(token)
+ if match is not None:
+ current = match.group(1)
+ if current not in variables:
+ order.append(current)
+ variables[current] = match.group(2)
+ continue
+ if current is None:
+ return {}, f"expected key=value, got {token!r}"
+ variables[current] = f"{variables[current]} {token}".strip()
+ if len(order) > _MAX_VARIABLES:
+ return {}, f"too many variables ({len(order)}); the cap is {_MAX_VARIABLES}"
+ return variables, None
+
+
+def _parse_var_options(raw: Sequence[str]) -> Tuple[Dict[str, str], Optional[str]]:
+ """Parse repeated ``--var key=value`` options.
+
+ Unlike :func:`parse_variable_tokens` each option carries one whole
+ assignment, because the shell already did the quoting.
+ """
+ variables: Dict[str, str] = {}
+ for item in raw:
+ match = _VAR_TOKEN_RE.match(item)
+ if match is None:
+ return {}, f"--var expects key=value, got {item!r}"
+ variables[match.group(1)] = match.group(2)
+ if len(variables) > _MAX_VARIABLES:
+ return {}, f"too many --var options ({len(variables)}); the cap is {_MAX_VARIABLES}"
+ return variables, None
+
+
+# ---------------------------------------------------------------------------
+# Catalogue access
+# ---------------------------------------------------------------------------
+
+
+def _load_catalogue() -> Tuple[List[Any], Optional[str]]:
+ """Load every playbook, converting a parse failure into a message.
+
+ Returns:
+ A ``(playbooks, error)`` pair. A malformed file is surfaced rather than
+ skipped, matching ``list_playbooks``.
+ """
+ from src.scheduled_research.playbooks import PlaybookError, list_playbooks
+
+ try:
+ return list_playbooks(), None
+ except (PlaybookError, OSError) as exc:
+ return [], str(exc)
+
+
+def _load_one(slug: str) -> Tuple[Optional[Any], Optional[str]]:
+ """Load a single playbook by slug, converting failures into a message."""
+ from src.scheduled_research.playbooks import PlaybookError, get_playbook
+
+ try:
+ return get_playbook(slug), None
+ except (PlaybookError, OSError) as exc:
+ return None, str(exc)
+
+
+def build_job_from_playbook(
+ slug: str,
+ *,
+ schedule: Optional[str] = None,
+ timezone: Any = _KEEP_TZ,
+ variables: Optional[Dict[str, str]] = None,
+ job_id: Optional[str] = None,
+) -> Tuple[Optional[Any], Optional[str]]:
+ """Build (but do not persist) a scheduled job from a template.
+
+ Every validation rule — schedule grammar, timezone resolution, declared
+ variable names, the cron search window — belongs to
+ ``ResearchPlaybook.to_job``; this only translates the exception into a
+ printable message.
+
+ Args:
+ slug: Template slug.
+ schedule: Schedule override, or ``None`` to keep the suggestion.
+ timezone: Timezone override. Leave at the sentinel to keep the
+ template's suggestion; pass ``None`` to force UTC.
+ variables: Placeholder overrides.
+ job_id: Explicit job id, or ``None`` for a generated one.
+
+ Returns:
+ A ``(job, error)`` pair; exactly one side is populated.
+ """
+ from src.scheduled_research.playbooks import build_job
+
+ kwargs: Dict[str, Any] = {"variables": variables or {}}
+ if schedule is not None:
+ kwargs["schedule"] = schedule
+ if timezone is not _KEEP_TZ:
+ kwargs["timezone"] = timezone
+ if job_id:
+ kwargs["job_id"] = job_id
+ try:
+ return build_job(slug, **kwargs), None
+ except (ValueError, OSError) as exc:
+ # PlaybookError and PlaybookNotFoundError both subclass ValueError.
+ return None, str(exc)
+
+
+def _persist(job: Any) -> Optional[str]:
+ """Upsert ``job`` into the shared store. Returns an error message or None."""
+ from src.scheduled_research.store import ScheduledResearchJobStore
+
+ try:
+ ScheduledResearchJobStore().upsert(job)
+ except Exception as exc: # noqa: BLE001 — surfaced as one line, never a traceback
+ return f"{type(exc).__name__}: {exc}"
+ return None
+
+
+def _scheduler_enabled() -> bool:
+ """Return whether the background executor is switched on for this install."""
+ try:
+ from src.config.accessor import get_env_config
+
+ return bool(get_env_config().agent_tuning.vibe_trading_enable_scheduler)
+ except Exception: # noqa: BLE001 — a config problem must not break the print
+ return False
+
+
+def _schedule_note(job: Any) -> str:
+ """Return the one-line caveat printed after a job is stored."""
+ if _scheduler_enabled():
+ return "The scheduler is enabled; the API server will fire this job."
+ return (
+ "The scheduler is OFF — set VIBE_TRADING_ENABLE_SCHEDULER=1 and run "
+ "`vibe-trading serve` for stored jobs to fire."
+ )
+
+
+# ---------------------------------------------------------------------------
+# Rendering
+# ---------------------------------------------------------------------------
+
+
+def _describe_schedule(schedule: str, tz: Optional[str]) -> str:
+ """Return a human-readable form of a stored schedule string."""
+ if schedule.isdigit():
+ seconds = int(schedule) / 1000
+ if seconds >= 3600:
+ return f"every {seconds / 3600:g}h"
+ if seconds >= 60:
+ return f"every {seconds / 60:g}m"
+ return f"every {seconds:g}s"
+ return f"cron {schedule} ({tz or 'UTC'})"
+
+
+def _render_catalogue(playbooks: Sequence[Any]) -> None:
+ """Print the template catalogue as a table."""
+ from rich.table import Table
+
+ console = _console()
+ if not playbooks:
+ console.print("[dim]No research playbooks found.[/dim]")
+ return
+
+ table = Table(title="Scheduled research playbooks", title_style="bold", box=None, pad_edge=False)
+ table.add_column("slug", style="cyan", no_wrap=True)
+ table.add_column("cadence", style="dim", no_wrap=True)
+ table.add_column("markets", style="dim", no_wrap=True)
+ table.add_column("what it produces", overflow="fold")
+ for playbook in playbooks:
+ table.add_row(
+ playbook.slug,
+ _describe_schedule(playbook.suggested_schedule, playbook.suggested_timezone),
+ ",".join(playbook.markets),
+ playbook.description,
+ )
+ console.print(table)
+
+
+def _render_card(playbook: Any, variables: Optional[Dict[str, str]] = None) -> bool:
+ """Print one template: metadata, declared variables and the full body.
+
+ Returns:
+ ``True`` when the card was printed, ``False`` when substitution failed
+ (the error is printed instead). Callers must propagate the failure into
+ their exit code rather than reporting success on an empty card.
+ """
+ from rich.panel import Panel
+ from rich.text import Text
+
+ console = _console()
+ header = Text()
+ header.append(playbook.description + "\n\n")
+ header.append("Cadence ", style="dim")
+ header.append(
+ _describe_schedule(playbook.suggested_schedule, playbook.suggested_timezone) + "\n"
+ )
+ header.append("Markets ", style="dim")
+ header.append(", ".join(playbook.markets) + "\n\n")
+ header.append("Data it needs\n", style="bold")
+ for capability in playbook.data_capabilities:
+ header.append(f" - {capability}\n", style="dim")
+ if playbook.variables:
+ header.append("\nVariables\n", style="bold")
+ for key, default in sorted(playbook.variables.items()):
+ header.append(f" {key}", style="cyan")
+ header.append(f" = {default}\n", style="dim")
+
+ try:
+ body = playbook.render(variables)
+ except ValueError as exc:
+ console.print(f"[bold red]{exc}[/bold red]")
+ return False
+
+ console.print(
+ Panel(
+ header,
+ title=f"{playbook.slug} — {playbook.name}",
+ border_style="cyan",
+ padding=(1, 2),
+ )
+ )
+ console.print(Text(body, style="dim"))
+ return True
+
+
+def _job_summary(job: Any, slug: str) -> str:
+ """Return the confirmation line printed after a job is created."""
+ import datetime as _dt
+
+ when = _dt.datetime.fromtimestamp(job.next_run_at / 1000, _dt.timezone.utc)
+ return (
+ f"Scheduled [cyan]{slug}[/cyan] as [bold]{job.id}[/bold] — "
+ f"{_describe_schedule(job.schedule, job.timezone)}, "
+ f"first run {when.strftime('%Y-%m-%d %H:%M')}Z"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Slash command: /playbook
+# ---------------------------------------------------------------------------
+
+
+def _queue_prompt(ctx: Any, prompt: str) -> bool:
+ """Stash ``prompt`` on ``ctx.pending_prompt`` for the REPL loop to run."""
+ if ctx is None or not hasattr(ctx, "pending_prompt"):
+ return False
+ try:
+ ctx.pending_prompt = prompt
+ return True
+ except Exception: # noqa: BLE001 — a stub context must not kill the REPL
+ return False
+
+
+def _slash_usage() -> None:
+ """Print the ``/playbook`` usage block.
+
+ The ``\\[k=v ...]`` hints are backslash-escaped: rich treats a bare
+ ``[k=v ...]`` as a markup tag and silently drops it, which would hide the
+ variable syntax — the one thing this help text exists to teach.
+ """
+ console = _console()
+ console.print("[bold]/playbook[/bold] — scheduled research templates")
+ console.print(" [cyan]/playbook[/cyan] list the templates")
+ console.print(" [cyan]/playbook <slug>[/cyan] show one in full")
+ console.print(" [cyan]/playbook run <slug> \\[k=v ...][/cyan] run it now in this session")
+ console.print(" [cyan]/playbook schedule <slug> \\[k=v ...][/cyan] store it on its suggested cadence")
+
+
+def run(ctx: Any = None, *args: str) -> int:
+ """Handle a ``/playbook`` slash command line.
+
+ Args:
+ ctx: Interactive context supplying ``pending_prompt``. When it cannot
+ hold a queued prompt (a test stub, a non-interactive caller) the
+ prompt is printed so it can be pasted.
+ *args: Raw slash-command arguments.
+
+ Returns:
+ ``0`` on every user-facing path, including "unknown slug" — a mistyped
+ template is answered with the catalogue, not an error exit code.
+ """
+ console = _console()
+ tokens = [token for token in args if token]
+
+ if tokens and tokens[0].lower() in _HELP_TOKENS:
+ _slash_usage()
+ return 0
+
+ if not tokens or tokens[0].lower() in _LIST_TOKENS:
+ playbooks, error = _load_catalogue()
+ if error:
+ console.print(f"[bold red]{error}[/bold red]")
+ return 0
+ _render_catalogue(playbooks)
+ console.print(
+ "[dim]/playbook run <slug> to run one now, "
+ "/playbook schedule <slug> to put it on a cadence.[/dim]"
+ )
+ return 0
+
+ action = tokens[0].lower()
+ if action in {"run", "schedule", "show"}:
+ slug, rest = (tokens[1] if len(tokens) > 1 else ""), tokens[2:]
+ else:
+ action, slug, rest = "show", tokens[0], tokens[1:]
+
+ if not slug:
+ console.print(f"[bold red]/playbook {action} needs a template slug.[/bold red]")
+ _slash_usage()
+ return 0
+
+ if sum(len(token) + 1 for token in rest) > _MAX_ARG_CHARS:
+ console.print(f"[bold red]Arguments exceed {_MAX_ARG_CHARS} characters.[/bold red]")
+ return 0
+
+ variables, var_error = parse_variable_tokens(rest)
+ if var_error:
+ console.print(f"[bold red]{var_error}[/bold red]")
+ return 0
+
+ playbook, load_error = _load_one(slug)
+ if playbook is None:
+ console.print(f"[bold red]{load_error}[/bold red]")
+ return 0
+
+ if action == "show":
+ _render_card(playbook, variables)
+ return 0
+
+ if action == "run":
+ try:
+ prompt = playbook.render(variables)
+ except ValueError as exc:
+ console.print(f"[bold red]{exc}[/bold red]")
+ return 0
+ if _queue_prompt(ctx, prompt):
+ console.print(f"[dim]→ Running the {playbook.slug} playbook now.[/dim]")
+ return 0
+ console.print(f"[bold]{playbook.slug} — paste this prompt to run it:[/bold]")
+ console.print(prompt)
+ return 0
+
+ job, build_error = build_job_from_playbook(slug, variables=variables)
+ if job is None:
+ console.print(f"[bold red]{build_error}[/bold red]")
+ return 0
+ store_error = _persist(job)
+ if store_error:
+ console.print(f"[bold red]{store_error}[/bold red]")
+ return 0
+ console.print(_job_summary(job, slug))
+ console.print(f"[dim]{_schedule_note(job)}[/dim]")
+ return 0
+
+
+# ---------------------------------------------------------------------------
+# argparse subcommand: vibe-trading playbook ...
+# ---------------------------------------------------------------------------
+
+_PLAYBOOK_PARSER: Optional[argparse.ArgumentParser] = None
+
+
+def add_subparser(subparsers: Any) -> argparse.ArgumentParser:
+ """Register ``playbook`` and its sub-subcommands on the parent subparsers.
+
+ Args:
+ subparsers: The object returned by ``ArgumentParser.add_subparsers``.
+
+ Returns:
+ The ``playbook`` parser, for test introspection.
+ """
+ global _PLAYBOOK_PARSER
+
+ parser = subparsers.add_parser(
+ "playbook",
+ help="Scheduled research templates: list / show / create",
+ )
+ sub = parser.add_subparsers(dest="playbook_command")
+
+ p_list = sub.add_parser("list", help="List the available research templates")
+ p_list.add_argument(
+ "--json", dest="playbook_json", action="store_true", help="Emit JSON instead of a table"
+ )
+
+ p_show = sub.add_parser("show", help="Show one template, including its full body")
+ p_show.add_argument("slug", help="Template slug, e.g. premarket-brief")
+ p_show.add_argument(
+ "--var",
+ dest="playbook_vars",
+ action="append",
+ default=[],
+ metavar="KEY=VALUE",
+ help="Substitute a declared variable in the previewed body (repeatable)",
+ )
+ p_show.add_argument(
+ "--json", dest="playbook_json", action="store_true", help="Emit JSON instead of a card"
+ )
+
+ p_create = sub.add_parser("create", help="Create a scheduled job from a template")
+ p_create.add_argument("slug", help="Template slug, e.g. premarket-brief")
+ p_create.add_argument(
+ "--schedule",
+ dest="playbook_schedule",
+ default=None,
+ help="Override the suggested cadence: interval milliseconds or a 5-field cron string",
+ )
+ p_create.add_argument(
+ "--timezone",
+ dest="playbook_timezone",
+ default=None,
+ help="Override the suggested IANA timezone the cron schedule is read in",
+ )
+ p_create.add_argument(
+ "--utc",
+ dest="playbook_utc",
+ action="store_true",
+ help="Force UTC, dropping the template's suggested timezone",
+ )
+ p_create.add_argument(
+ "--var",
+ dest="playbook_vars",
+ action="append",
+ default=[],
+ metavar="KEY=VALUE",
+ help="Set a declared template variable (repeatable)",
+ )
+ p_create.add_argument("--id", dest="playbook_id", default=None, help="Explicit job id")
+ p_create.add_argument(
+ "--dry-run",
+ dest="playbook_dry_run",
+ action="store_true",
+ help="Print the job that would be stored without persisting it",
+ )
+ p_create.add_argument(
+ "--json", dest="playbook_json", action="store_true", help="Emit JSON instead of a summary"
+ )
+
+ _PLAYBOOK_PARSER = parser
+ return parser
+
+
+def _cmd_list(args: argparse.Namespace) -> int:
+ """Handle ``vibe-trading playbook list``."""
+ playbooks, error = _load_catalogue()
+ if error:
+ _print(f"[bold red]{error}[/bold red]")
+ return 1
+ if getattr(args, "playbook_json", False):
+ print(json.dumps([p.to_dict() for p in playbooks], indent=2, ensure_ascii=False))
+ return 0
+ _render_catalogue(playbooks)
+ _print("[dim]vibe-trading playbook show <slug> for the full text.[/dim]")
+ return 0
+
+
+def _cmd_show(args: argparse.Namespace) -> int:
+ """Handle ``vibe-trading playbook show <slug>``."""
+ variables, var_error = _parse_var_options(getattr(args, "playbook_vars", []) or [])
+ if var_error:
+ _print(f"[bold red]{var_error}[/bold red]")
+ return 2
+ playbook, load_error = _load_one(args.slug)
+ if playbook is None:
+ _print(f"[bold red]{load_error}[/bold red]")
+ return 1
+ if getattr(args, "playbook_json", False):
+ try:
+ body = playbook.render(variables)
+ except ValueError as exc:
+ _print(f"[bold red]{exc}[/bold red]")
+ return 2
+ payload = playbook.to_dict()
+ payload["body"] = body
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
+ return 0
+ # Same failure, same exit code as the --json branch above: a bad --var is a
+ # usage error whichever output format was asked for.
+ return 0 if _render_card(playbook, variables) else 2
+
+
+def _cmd_create(args: argparse.Namespace) -> int:
+ """Handle ``vibe-trading playbook create <slug>``."""
+ variables, var_error = _parse_var_options(getattr(args, "playbook_vars", []) or [])
+ if var_error:
+ _print(f"[bold red]{var_error}[/bold red]")
+ return 2
+
+ timezone: Any = _KEEP_TZ
+ if getattr(args, "playbook_utc", False):
+ if getattr(args, "playbook_timezone", None):
+ _print("[bold red]--utc and --timezone are mutually exclusive.[/bold red]")
+ return 2
+ timezone = None
+ elif getattr(args, "playbook_timezone", None):
+ timezone = args.playbook_timezone
+
+ job, build_error = build_job_from_playbook(
+ args.slug,
+ schedule=getattr(args, "playbook_schedule", None),
+ timezone=timezone,
+ variables=variables,
+ job_id=getattr(args, "playbook_id", None),
+ )
+ if job is None:
+ _print(f"[bold red]{build_error}[/bold red]")
+ return 1
+
+ dry_run = getattr(args, "playbook_dry_run", False)
+ if not dry_run:
+ store_error = _persist(job)
+ if store_error:
+ _print(f"[bold red]{store_error}[/bold red]")
+ return 1
+
+ if getattr(args, "playbook_json", False):
+ payload = job.to_dict()
+ payload["dry_run"] = dry_run
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
+ return 0
+
+ if dry_run:
+ _print(f"[dim]Dry run — nothing stored.[/dim] {_job_summary(job, args.slug)}")
+ _print(f"[dim]{job.prompt}[/dim]")
+ return 0
+ _print(_job_summary(job, args.slug))
+ _print(f"[dim]{_schedule_note(job)}[/dim]")
+ return 0
+
+
+_DISPATCH = {
+ "list": _cmd_list,
+ "show": _cmd_show,
+ "create": _cmd_create,
+}
+
+
+def dispatch(args: argparse.Namespace) -> int:
+ """Dispatch ``playbook <sub>`` to its handler.
+
+ Returns:
+ A process exit code: ``0`` on success, ``1`` on a failed operation,
+ ``2`` on a usage error.
+ """
+ sub = getattr(args, "playbook_command", None)
+ handler = _DISPATCH.get(sub or "")
+ if handler is None:
+ if _PLAYBOOK_PARSER is not None:
+ _PLAYBOOK_PARSER.print_help()
+ else:
+ _print(
+ "[red]playbook requires a subcommand.[/red] "
+ "Try: vibe-trading playbook list"
+ )
+ return 2
+ return int(handler(args))
+
+
+__all__ = [
+ "add_subparser",
+ "build_job_from_playbook",
+ "dispatch",
+ "parse_variable_tokens",
+ "run",
+]
diff --git a/agent/cli/commands/slash_router.py b/agent/cli/commands/slash_router.py
index 195cf437d..5952be26d 100644
--- a/agent/cli/commands/slash_router.py
+++ b/agent/cli/commands/slash_router.py
@@ -3,9 +3,10 @@
Source of truth for the user-facing slash commands. The literal
:data:`SLASH_COMMANDS` tuple below holds the base set; further groups append
themselves through idempotent, name-checked registration functions — the
-institutional research playbooks at the bottom of this module, and the live
-connector / data-routing groups from :mod:`cli.main` at ITS import time. Read
-the registry at runtime rather than assuming a fixed length.
+institutional workflow cards and the scheduled-research ``/playbook``
+catalogue further down this module, and the live connector / data-routing
+groups from :mod:`cli.main` at ITS import time. Read the registry at runtime
+rather than assuming a fixed length.
Each :class:`Command` is a frozen dataclass — registry entries are
immutable so callers can cache filtered slices without worrying about
@@ -120,6 +121,41 @@ def _register_institutional_slash_commands() -> None:
_register_institutional_slash_commands()
+def _register_research_playbook_slash_command() -> None:
+ """Append ``/playbook`` — the scheduled-research template catalogue.
+
+ Registered here for the same reason the institutional group is: this module
+ is imported before ``cli.commands.help`` and ``cli.completer`` read the
+ registry, so one reassignment surfaces the command in the help screen, the
+ typeahead and the fuzzy matcher at once. Idempotent and never overwrites a
+ name that already exists.
+
+ The :class:`Command` is built literally rather than imported from the
+ handler module, so no import cycle (and no scheduler-store import cost) is
+ paid just to draw the completion menu.
+ """
+ global SLASH_COMMANDS
+
+ if any(cmd.name == "playbook" for cmd in SLASH_COMMANDS):
+ return
+ commands = list(SLASH_COMMANDS)
+ quit_idx = next(
+ (i for i, c in enumerate(commands) if c.name == "quit"), len(commands)
+ )
+ commands.insert(
+ quit_idx,
+ Command(
+ "playbook",
+ "Scheduled research templates (list / run / schedule)",
+ "cli.commands.research_playbook",
+ ),
+ )
+ SLASH_COMMANDS = tuple(commands)
+
+
+_register_research_playbook_slash_command()
+
+
def _parse_token(input_text: str) -> str:
"""Strip the leading ``/`` and isolate the command token.
diff --git a/agent/src/api/scheduled_routes.py b/agent/src/api/scheduled_routes.py
index 6d0532bc0..22169802a 100644
--- a/agent/src/api/scheduled_routes.py
+++ b/agent/src/api/scheduled_routes.py
@@ -135,6 +135,65 @@ class CreateScheduledRunRequest(BaseModel):
)
+class PlaybookResponse(BaseModel):
+ """Catalogue record for one research playbook template.
+
+ ``body`` is the raw instruction text with ``{{placeholders}}`` unresolved.
+ It is populated only by the single-template endpoint; the list endpoint
+ leaves it null so a catalogue response stays small.
+ """
+
+ slug: str
+ name: str
+ description: str
+ suggested_schedule: str
+ suggested_timezone: Optional[str] = None
+ markets: List[str] = Field(default_factory=list)
+ data_capabilities: List[str] = Field(default_factory=list)
+ variables: Dict[str, str] = Field(default_factory=dict)
+ body: Optional[str] = None
+
+
+class CreateRunFromPlaybookRequest(BaseModel):
+ """Request body for POST /scheduled-runs/playbooks/{slug}.
+
+ Every field is optional: posting ``{}`` schedules the template on its own
+ suggested cadence with its declared variable defaults.
+ """
+
+ id: Optional[str] = Field(
+ None, description="Job id; defaults to a slug-prefixed generated id"
+ )
+ schedule: Optional[str] = Field(
+ None,
+ min_length=1,
+ description=(
+ "Schedule override (interval-ms or 5-field cron); defaults to the "
+ "template's suggested_schedule"
+ ),
+ )
+ timezone: Optional[str] = Field(
+ None,
+ description=(
+ "IANA timezone override. Omit the field to keep the template's "
+ "suggested_timezone; send null explicitly to force UTC."
+ ),
+ )
+ variables: Dict[str, str] = Field(
+ default_factory=dict,
+ description=(
+ "Overrides for the template's declared variables. An undeclared "
+ "name is rejected rather than silently ignored."
+ ),
+ )
+ config: Dict[str, Any] = Field(
+ default_factory=dict, description="Session config forwarded to the agent run"
+ )
+ next_run_at: Optional[int] = Field(
+ None, description="Explicit first-fire epoch-ms, bypassing the default rule"
+ )
+
+
class ScheduledRunResponse(BaseModel):
"""API response for a single scheduled job."""
@@ -268,3 +327,119 @@ def register_scheduled_routes(
raise HTTPException(
status_code=404, detail=f"scheduled run {job_id} not found"
)
+
+ # --- Playbook templates ---
+ #
+ # Mounted under /scheduled-runs because a template is only useful as the
+ # source of a scheduled run. ``{job_id}`` never matches across a "/", so
+ # these paths cannot collide with the CRUD routes above. Every one carries
+ # the same ``require_auth`` dependency: there is deliberately no unguarded
+ # way to enumerate the catalogue or create a job from it.
+
+ @app.get(
+ "/scheduled-runs/playbooks",
+ response_model=List[PlaybookResponse],
+ dependencies=[Depends(require_auth)],
+ )
+ async def list_research_playbooks() -> List[PlaybookResponse]:
+ """List the available research playbook templates, without bodies."""
+ from src.scheduled_research.playbooks import PlaybookError, list_playbooks
+
+ try:
+ playbooks = list_playbooks()
+ except (PlaybookError, OSError) as exc:
+ # A malformed file is surfaced, not skipped: a user template the
+ # loader refuses must be visible as a broken template rather than
+ # vanish from the catalogue.
+ raise HTTPException(
+ status_code=500, detail=f"playbook catalogue is unreadable: {exc}"
+ ) from exc
+ return [PlaybookResponse(**pb.to_dict()) for pb in playbooks]
+
+ @app.get(
+ "/scheduled-runs/playbooks/{slug}",
+ response_model=PlaybookResponse,
+ dependencies=[Depends(require_auth)],
+ )
+ async def get_research_playbook(slug: str) -> PlaybookResponse:
+ """Read one research playbook template, including its instruction body."""
+ from src.scheduled_research.playbooks import (
+ PlaybookError,
+ PlaybookNotFoundError,
+ get_playbook,
+ )
+
+ _host_validate_path_param(slug, "slug")
+ try:
+ playbook = get_playbook(slug)
+ except PlaybookNotFoundError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except (PlaybookError, OSError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ return PlaybookResponse(**playbook.to_dict(include_body=True))
+
+ @app.post(
+ "/scheduled-runs/playbooks/{slug}",
+ response_model=ScheduledRunResponse,
+ status_code=status.HTTP_201_CREATED,
+ dependencies=[Depends(require_auth)],
+ )
+ async def create_scheduled_run_from_playbook(
+ slug: str,
+ request: CreateRunFromPlaybookRequest,
+ ) -> ScheduledRunResponse:
+ """Create a scheduled research job from a template.
+
+ The template body becomes ``job.prompt`` verbatim — the natural-language
+ data requirements are never rewritten into tool calls here; routing
+ stays the agent's job at run time.
+
+ Schedule and timezone are validated by ``ResearchPlaybook.to_job``,
+ which calls the same ``validate_schedule`` / ``validate_timezone`` the
+ plain ``POST /scheduled-runs`` path uses, so the two entry points can
+ never accept different schedule grammars.
+ """
+ from src.scheduled_research.playbooks import (
+ PlaybookError,
+ PlaybookNotFoundError,
+ get_playbook,
+ )
+
+ _host_validate_path_param(slug, "slug")
+ # Unlike POST /scheduled-runs this checks the caller-supplied id up
+ # front: an id outside the safe pattern would persist fine but could
+ # never be removed through DELETE /scheduled-runs/{job_id}, which
+ # rejects it with 400.
+ if request.id is not None:
+ _host_validate_path_param(request.id, "id")
+
+ try:
+ playbook = get_playbook(slug)
+ except PlaybookNotFoundError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except (PlaybookError, OSError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+ kwargs: Dict[str, Any] = {}
+ # An omitted timezone keeps the template's suggestion; an explicit null
+ # means UTC. Pydantic collapses both to ``None``, so the distinction has
+ # to come from the fields the caller actually sent.
+ if "timezone" in request.model_fields_set:
+ kwargs["timezone"] = request.timezone
+
+ try:
+ job = playbook.to_job(
+ job_id=request.id,
+ schedule=request.schedule,
+ variables=request.variables,
+ config=request.config,
+ next_run_at=request.next_run_at,
+ **kwargs,
+ )
+ except ValueError as exc:
+ # Covers PlaybookError (undeclared/oversized variable) and the
+ # schedule / timezone / cron-window failures, all ValueError.
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+ _get_scheduled_research_store().upsert(job)
+ return ScheduledRunResponse(**job.to_dict())
diff --git a/agent/tests/test_playbooks_surface.py b/agent/tests/test_playbooks_surface.py
new file mode 100644
index 000000000..2ba71a673
--- /dev/null
+++ b/agent/tests/test_playbooks_surface.py
@@ -0,0 +1,770 @@
+"""Entry-point contracts for the scheduled-research playbook catalogue.
+
+The templates themselves are covered by ``tests/test_research_playbooks.py``.
+This module covers the three surfaces a user actually reaches them through, and
+the properties that are easy to break from any of them:
+
+* REST — ``GET /scheduled-runs/playbooks``, ``GET /scheduled-runs/playbooks/{slug}``
+ and ``POST /scheduled-runs/playbooks/{slug}``, including the structural claim
+ that EVERY route under ``/scheduled-runs`` carries ``require_auth``.
+* CLI — ``vibe-trading playbook list | show | create``, driven through
+ ``cli._legacy.main`` so the argparse wiring is exercised, not just the handler.
+* Slash — ``/playbook`` registration plus its list / show / run / schedule paths.
+
+The decoupling assertion runs on all three: a queued or persisted prompt must be
+``ResearchPlaybook.render()`` byte for byte. An entry point that "helpfully"
+appended tool names would fail here.
+
+No network is involved. The job store is redirected to ``tmp_path`` by pointing
+``VIBE_TRADING_HOME`` at it (CLI/slash, which construct their own store) and by
+patching the route module's singleton (REST).
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, List, Tuple
+
+import pytest
+from fastapi.testclient import TestClient
+
+import api_server
+from cli.commands import research_playbook, slash_router
+from src.api import scheduled_routes
+from src.scheduled_research.playbooks import get_playbook, list_playbooks
+from src.scheduled_research.store import ScheduledResearchJobStore
+
+BUNDLED_SLUGS = {
+ "a-share-money-flow",
+ "earnings-season-tracker",
+ "institutional-holdings-diff",
+ "portfolio-checkup",
+ "premarket-brief",
+}
+
+# A template with declared variables and a timezone-carrying cron cadence, so
+# the variable-substitution and first-fire branches both get exercised.
+SAMPLE = "premarket-brief"
+
+
+class _Ctx:
+ """Minimal stand-in for ``cli.main.InteractiveContext``."""
+
+ def __init__(self) -> None:
+ self.pending_prompt: str | None = None
+
+
+class _NoQueueCtx:
+ """A context that cannot hold a queued prompt (stub / non-interactive)."""
+
+
[email protected](autouse=True)
+def _hermetic_catalogue(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Ignore any user playbook directory on the developer's machine."""
+ monkeypatch.delenv("VIBE_TRADING_PLAYBOOK_DIR", raising=False)
+
+
[email protected](autouse=True)
+def _wide_console(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Stop Rich from ellipsizing slugs at the default 80-column test width."""
+ from cli.theme import get_console
+
+ monkeypatch.setattr(get_console(), "width", 200, raising=False)
+
+
+def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Point the runtime root at ``tmp_path`` so the CLI writes a temp store."""
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path))
+ return tmp_path
+
+
+def cli_store(home: Path) -> ScheduledResearchJobStore:
+ """The store the CLI and slash surfaces write to under the temp home."""
+ return ScheduledResearchJobStore()
+
+
+def rest_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> ScheduledResearchJobStore:
+ """Isolate the route module's store singleton onto a temp file."""
+ isolated = ScheduledResearchJobStore(path=tmp_path / "scheduled_jobs.json")
+ monkeypatch.setattr(scheduled_routes, "_scheduled_research_store", isolated)
+ return isolated
+
+
+def client(rest_store: ScheduledResearchJobStore, monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ """Keyless dev-mode client whose peer host counts as loopback."""
+ monkeypatch.delenv("API_AUTH_KEY", raising=False)
+ monkeypatch.setattr(api_server, "_API_KEY", "")
+ return TestClient(api_server.app, client=("127.0.0.1", 50000))
+
+
+def _run_cli(argv: List[str]) -> int:
+ """Drive the real argparse dispatcher, returning its exit code."""
+ from cli import _legacy
+
+ return int(_legacy.main(argv))
+
+
+# ---------------------------------------------------------------------------
+# REST — catalogue
+# ---------------------------------------------------------------------------
+
+
+class TestRestCatalogue:
+ def test_list_returns_every_bundled_template(self, client: TestClient) -> None:
+ response = client.get("/scheduled-runs/playbooks")
+
+ assert response.status_code == 200
+ rows = response.json()
+ assert {row["slug"] for row in rows} >= BUNDLED_SLUGS
+ assert [row["slug"] for row in rows] == sorted(row["slug"] for row in rows)
+
+ def test_list_omits_bodies(self, client: TestClient) -> None:
+ rows = client.get("/scheduled-runs/playbooks").json()
+
+ assert rows
+ assert all(row["body"] is None for row in rows)
+
+ def test_list_carries_catalogue_metadata(self, client: TestClient) -> None:
+ rows = {row["slug"]: row for row in client.get("/scheduled-runs/playbooks").json()}
+
+ row = rows[SAMPLE]
+ playbook = get_playbook(SAMPLE)
+ assert row["suggested_schedule"] == playbook.suggested_schedule
+ assert row["suggested_timezone"] == playbook.suggested_timezone
+ assert row["data_capabilities"] == list(playbook.data_capabilities)
+ assert row["variables"] == playbook.variables
+
+ def test_get_one_includes_the_body_verbatim(self, client: TestClient) -> None:
+ response = client.get(f"/scheduled-runs/playbooks/{SAMPLE}")
+
+ assert response.status_code == 200
+ assert response.json()["body"] == get_playbook(SAMPLE).body
+
+ def test_get_unknown_slug_returns_404(self, client: TestClient) -> None:
+ response = client.get("/scheduled-runs/playbooks/not-a-template")
+
+ assert response.status_code == 404
+ assert "not-a-template" in response.json()["detail"]
+
+ def test_get_unsafe_slug_returns_400(self, client: TestClient) -> None:
+ # Rejected by the shared path-param guard before any filesystem lookup.
+ assert client.get("/scheduled-runs/playbooks/bad.slug").status_code == 400
+
+ def test_user_directory_template_is_listed_and_readable(
+ self, client: TestClient, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ directory = tmp_path / "user-playbooks"
+ directory.mkdir()
+ (directory / "desk-open.md").write_text(
+ "---\n"
+ "name: Desk Open\n"
+ "description: A user-authored template.\n"
+ "suggested_schedule: '900000'\n"
+ "data_capabilities:\n"
+ " - Recent daily bars for the desk's names\n"
+ "---\n\nCheck the desk.\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("VIBE_TRADING_PLAYBOOK_DIR", str(directory))
+
+ listed = {row["slug"] for row in client.get("/scheduled-runs/playbooks").json()}
+ detail = client.get("/scheduled-runs/playbooks/desk-open")
+
+ assert "desk-open" in listed
+ assert detail.status_code == 200
+ assert detail.json()["body"] == "Check the desk."
+
+
+# ---------------------------------------------------------------------------
+# REST — create from template
+# ---------------------------------------------------------------------------
+
+
+class TestRestCreate:
+ def test_create_persists_the_rendered_body_unchanged(
+ self, client: TestClient, rest_store: ScheduledResearchJobStore
+ ) -> None:
+ response = client.post(f"/scheduled-runs/playbooks/{SAMPLE}", json={})
+
+ assert response.status_code == 201
+ body = response.json()
+ playbook = get_playbook(SAMPLE)
+ # The decoupling contract: the natural-language body travels verbatim,
+ # with no tool names spliced in by the entry layer.
+ assert body["prompt"] == playbook.render()
+ assert body["schedule"] == playbook.suggested_schedule
+ assert body["timezone"] == playbook.suggested_timezone
+ assert body["status"] == "pending"
+ assert body["config"]["playbook"] == SAMPLE
+
+ stored = rest_store.get(body["id"])
+ assert stored is not None
+ assert stored.prompt == playbook.render()
+
+ def test_create_substitutes_declared_variables(self, client: TestClient) -> None:
+ response = client.post(
+ f"/scheduled-runs/playbooks/{SAMPLE}",
+ json={"id": "tokyo-brief", "variables": {"home_market": "Japan equities"}},
+ )
+
+ assert response.status_code == 201
+ prompt = response.json()["prompt"]
+ assert "Japan equities" in prompt
+ assert prompt == get_playbook(SAMPLE).render({"home_market": "Japan equities"})
+
+ def test_create_rejects_undeclared_variable(
+ self, client: TestClient, rest_store: ScheduledResearchJobStore
+ ) -> None:
+ response = client.post(
+ f"/scheduled-runs/playbooks/{SAMPLE}",
+ json={"id": "bad-var", "variables": {"not_a_variable": "x"}},
+ )
+
+ assert response.status_code == 422
+ assert "not_a_variable" in response.json()["detail"]
+ assert rest_store.list_jobs() == []
+
+ def test_create_rejects_malformed_schedule(
+ self, client: TestClient, rest_store: ScheduledResearchJobStore
+ ) -> None:
+ response = client.post(
+ f"/scheduled-runs/playbooks/{SAMPLE}",
+ json={"id": "bad-cron", "schedule": "0 99 * * *"},
+ )
+
+ assert response.status_code == 422
+ assert "out of range" in response.json()["detail"]
+ assert rest_store.list_jobs() == []
+
+ def test_create_rejects_unresolvable_timezone(
+ self, client: TestClient, rest_store: ScheduledResearchJobStore
+ ) -> None:
+ response = client.post(
+ f"/scheduled-runs/playbooks/{SAMPLE}",
+ json={"id": "bad-tz", "timezone": "Not/AZone"},
+ )
+
+ assert response.status_code == 422
+ assert "IANA timezone" in response.json()["detail"]
+ assert rest_store.list_jobs() == []
+
+ def test_create_rejects_unsafe_job_id(
+ self, client: TestClient, rest_store: ScheduledResearchJobStore
+ ) -> None:
+ # An id outside the safe pattern would persist but could never be
+ # removed through DELETE /scheduled-runs/{job_id}.
+ response = client.post(
+ f"/scheduled-runs/playbooks/{SAMPLE}", json={"id": "../escape"}
+ )
+
+ assert response.status_code == 400
+ assert rest_store.list_jobs() == []
+
+ def test_create_unknown_slug_returns_404(
+ self, client: TestClient, rest_store: ScheduledResearchJobStore
+ ) -> None:
+ response = client.post("/scheduled-runs/playbooks/not-a-template", json={})
+
+ assert response.status_code == 404
+ assert rest_store.list_jobs() == []
+
+ def test_explicit_null_timezone_forces_utc_and_immediate_first_fire(
+ self, client: TestClient
+ ) -> None:
+ import time
+
+ before = int(time.time() * 1000)
+ response = client.post(
+ f"/scheduled-runs/playbooks/{SAMPLE}",
+ json={"id": "utc-brief", "timezone": None},
+ )
+ after = int(time.time() * 1000)
+
+ assert response.status_code == 201
+ body = response.json()
+ assert body["timezone"] is None
+ assert before <= body["next_run_at"] <= after
+
+ def test_suggested_timezone_defers_first_fire_to_an_authored_occurrence(
+ self, client: TestClient
+ ) -> None:
+ import time
+
+ after = int(time.time() * 1000)
+ response = client.post(
+ f"/scheduled-runs/playbooks/{SAMPLE}", json={"id": "tz-brief"}
+ )
+
+ assert response.status_code == 201
+ body = response.json()
+ assert body["timezone"] == get_playbook(SAMPLE).suggested_timezone
+ # A weekday 08:30 cadence never fires at creation time.
+ assert body["next_run_at"] > after
+
+ def test_created_job_is_visible_through_the_plain_list_endpoint(
+ self, client: TestClient
+ ) -> None:
+ client.post(f"/scheduled-runs/playbooks/{SAMPLE}", json={"id": "listed-brief"})
+
+ rows = client.get("/scheduled-runs").json()
+
+ assert "listed-brief" in {row["id"] for row in rows}
+
+
+# ---------------------------------------------------------------------------
+# REST — authentication
+# ---------------------------------------------------------------------------
+
+
+def _scheduled_routes_under_test() -> List[Any]:
+ """Every mounted route whose path lives under ``/scheduled-runs``."""
+ return [
+ route
+ for route in api_server.app.routes
+ if getattr(route, "path", "").startswith("/scheduled-runs")
+ ]
+
+
+class TestRestAuth:
+ def test_every_scheduled_route_declares_require_auth(self) -> None:
+ """Structural guard: no route in this group may skip the dependency."""
+ routes = _scheduled_routes_under_test()
+ assert len(routes) >= 6 # 3 CRUD + 3 playbook routes
+
+ for route in routes:
+ calls = {dep.call for dep in route.dependant.dependencies}
+ assert api_server.require_auth in calls, route.path
+
+ @pytest.mark.parametrize(
+ ("method", "path"),
+ [
+ ("get", "/scheduled-runs/playbooks"),
+ ("get", f"/scheduled-runs/playbooks/{SAMPLE}"),
+ ("post", f"/scheduled-runs/playbooks/{SAMPLE}"),
+ ],
+ )
+ def test_configured_key_rejects_uncredentialed_requests(
+ self,
+ method: str,
+ path: str,
+ rest_store: ScheduledResearchJobStore,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ monkeypatch.setenv("API_AUTH_KEY", "secret")
+ monkeypatch.setattr(api_server, "_API_KEY", "secret")
+ keyed = TestClient(api_server.app)
+
+ response = keyed.request(method.upper(), path, json={})
+
+ assert response.status_code in {401, 403}
+ assert rest_store.list_jobs() == []
+
+ @pytest.mark.parametrize(
+ ("method", "path", "expected"),
+ [
+ ("get", "/scheduled-runs/playbooks", 200),
+ ("get", f"/scheduled-runs/playbooks/{SAMPLE}", 200),
+ ("post", f"/scheduled-runs/playbooks/{SAMPLE}", 201),
+ ],
+ )
+ def test_valid_bearer_is_accepted(
+ self,
+ method: str,
+ path: str,
+ expected: int,
+ rest_store: ScheduledResearchJobStore,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ monkeypatch.setenv("API_AUTH_KEY", "secret")
+ monkeypatch.setattr(api_server, "_API_KEY", "secret")
+ keyed = TestClient(api_server.app)
+
+ response = keyed.request(
+ method.upper(), path, json={}, headers={"Authorization": "Bearer secret"}
+ )
+
+ assert response.status_code == expected
+
+
+# ---------------------------------------------------------------------------
+# CLI subcommand
+# ---------------------------------------------------------------------------
+
+
+class TestCliSubcommand:
+ def test_list_prints_every_slug(
+ self, home: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = _run_cli(["playbook", "list"])
+
+ out = capsys.readouterr().out
+ assert code == 0
+ for slug in BUNDLED_SLUGS:
+ assert slug in out
+
+ def test_list_json_is_machine_readable(
+ self, home: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ import json
+
+ code = _run_cli(["playbook", "list", "--json"])
+
+ rows = json.loads(capsys.readouterr().out)
+ assert code == 0
+ assert {row["slug"] for row in rows} >= BUNDLED_SLUGS
+
+ def test_show_prints_the_body(
+ self, home: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = _run_cli(["playbook", "show", SAMPLE])
+
+ out = capsys.readouterr().out
+ assert code == 0
+ assert "Pre-market brief" in out
+ assert "Data gaps" in out
+
+ def test_show_json_renders_variable_overrides(
+ self, home: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ import json
+
+ code = _run_cli(
+ ["playbook", "show", SAMPLE, "--json", "--var", "home_market=Korea equities"]
+ )
+
+ payload = json.loads(capsys.readouterr().out)
+ assert code == 0
+ assert payload["body"] == get_playbook(SAMPLE).render(
+ {"home_market": "Korea equities"}
+ )
+
+ def test_show_unknown_slug_fails(
+ self, home: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = _run_cli(["playbook", "show", "not-a-template"])
+
+ assert code == 1
+ assert "not-a-template" in capsys.readouterr().out
+
+ def test_create_persists_a_job_with_the_verbatim_body(
+ self, cli_store: ScheduledResearchJobStore, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = _run_cli(["playbook", "create", SAMPLE, "--id", "desk-brief"])
+ capsys.readouterr()
+
+ assert code == 0
+ job = cli_store.get("desk-brief")
+ assert job is not None
+ assert job.prompt == get_playbook(SAMPLE).render()
+ assert job.schedule == get_playbook(SAMPLE).suggested_schedule
+ assert job.config["playbook"] == SAMPLE
+
+ def test_create_applies_variables_and_schedule_override(
+ self, cli_store: ScheduledResearchJobStore, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = _run_cli(
+ [
+ "playbook",
+ "create",
+ SAMPLE,
+ "--id",
+ "hourly-brief",
+ "--schedule",
+ "3600000",
+ "--var",
+ "watchlist=AAPL, MSFT",
+ ]
+ )
+ capsys.readouterr()
+
+ assert code == 0
+ job = cli_store.get("hourly-brief")
+ assert job is not None
+ assert job.schedule == "3600000"
+ assert "AAPL, MSFT" in job.prompt
+
+ def test_create_utc_flag_drops_the_suggested_timezone(
+ self, cli_store: ScheduledResearchJobStore, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = _run_cli(["playbook", "create", SAMPLE, "--id", "utc-brief", "--utc"])
+ capsys.readouterr()
+
+ assert code == 0
+ job = cli_store.get("utc-brief")
+ assert job is not None
+ assert job.timezone is None
+
+ def test_create_rejects_utc_together_with_timezone(
+ self, cli_store: ScheduledResearchJobStore, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = _run_cli(
+ ["playbook", "create", SAMPLE, "--utc", "--timezone", "Asia/Tokyo"]
+ )
+
+ assert code == 2
+ assert "mutually exclusive" in capsys.readouterr().out
+ assert cli_store.list_jobs() == []
+
+ def test_create_rejects_malformed_schedule(
+ self, cli_store: ScheduledResearchJobStore, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = _run_cli(["playbook", "create", SAMPLE, "--schedule", "0 99 * * *"])
+
+ assert code == 1
+ assert "out of range" in capsys.readouterr().out
+ assert cli_store.list_jobs() == []
+
+ def test_create_rejects_undeclared_variable(
+ self, cli_store: ScheduledResearchJobStore, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = _run_cli(["playbook", "create", SAMPLE, "--var", "not_a_variable=x"])
+
+ assert code == 1
+ assert "not_a_variable" in capsys.readouterr().out
+ assert cli_store.list_jobs() == []
+
+ def test_create_unknown_slug_lists_what_is_available(
+ self, cli_store: ScheduledResearchJobStore, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = _run_cli(["playbook", "create", "not-a-template"])
+
+ out = capsys.readouterr().out
+ assert code == 1
+ assert "premarket-brief" in out
+ assert cli_store.list_jobs() == []
+
+ def test_dry_run_stores_nothing(
+ self, cli_store: ScheduledResearchJobStore, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = _run_cli(["playbook", "create", SAMPLE, "--dry-run"])
+
+ assert code == 0
+ assert "Dry run" in capsys.readouterr().out
+ assert cli_store.list_jobs() == []
+
+ def test_bare_subcommand_prints_help_and_signals_usage_error(
+ self, home: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = _run_cli(["playbook"])
+
+ assert code == 2
+ assert "create" in capsys.readouterr().out
+
+
+# ---------------------------------------------------------------------------
+# Slash command
+# ---------------------------------------------------------------------------
+
+
+class TestSlashCommand:
+ def test_registered_once_and_resolvable(self) -> None:
+ names = [cmd.name for cmd in slash_router.SLASH_COMMANDS]
+
+ assert names.count("playbook") == 1
+ assert len(names) == len(set(names))
+ command = slash_router.find_exact("/playbook")
+ assert command is not None
+ assert command.handler_module == "cli.commands.research_playbook"
+
+ def test_registration_is_idempotent(self) -> None:
+ before = slash_router.SLASH_COMMANDS
+ slash_router._register_research_playbook_slash_command()
+
+ assert slash_router.SLASH_COMMANDS == before
+
+ def test_quit_stays_last(self) -> None:
+ assert slash_router.SLASH_COMMANDS[-1].name == "quit"
+
+ def test_typeahead_surfaces_it(self) -> None:
+ matches = [cmd.name for cmd in slash_router.match_commands("/play")]
+
+ assert "playbook" in matches
+
+ def test_bare_command_lists_the_catalogue(
+ self, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ ctx = _Ctx()
+
+ code = research_playbook.run(ctx)
+
+ out = capsys.readouterr().out
+ assert code == 0
+ assert ctx.pending_prompt is None
+ for slug in BUNDLED_SLUGS:
+ assert slug in out
+
+ def test_slug_alone_shows_the_card(self, capsys: pytest.CaptureFixture[str]) -> None:
+ code = research_playbook.run(_Ctx(), SAMPLE)
+
+ out = capsys.readouterr().out
+ assert code == 0
+ assert "Pre-market Brief" in out
+ assert "Data gaps" in out
+
+ def test_run_queues_the_body_verbatim(
+ self, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ ctx = _Ctx()
+
+ code = research_playbook.run(ctx, "run", SAMPLE)
+ capsys.readouterr()
+
+ assert code == 0
+ # Byte-for-byte identical to what the scheduler would replay.
+ assert ctx.pending_prompt == get_playbook(SAMPLE).render()
+
+ def test_run_accepts_unquoted_multi_word_variables(self) -> None:
+ ctx = _Ctx()
+
+ research_playbook.run(ctx, "run", SAMPLE, "home_market=US", "equities")
+
+ assert ctx.pending_prompt == get_playbook(SAMPLE).render(
+ {"home_market": "US equities"}
+ )
+
+ def test_run_without_a_queueable_context_prints_the_prompt(
+ self, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = research_playbook.run(_NoQueueCtx(), "run", SAMPLE)
+
+ assert code == 0
+ assert "paste this prompt" in capsys.readouterr().out
+
+ def test_schedule_persists_a_job(
+ self, cli_store: ScheduledResearchJobStore, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ ctx = _Ctx()
+
+ code = research_playbook.run(ctx, "schedule", SAMPLE)
+ out = capsys.readouterr().out
+
+ assert code == 0
+ assert ctx.pending_prompt is None
+ jobs = cli_store.list_jobs()
+ assert len(jobs) == 1
+ assert jobs[0].prompt == get_playbook(SAMPLE).render()
+ assert jobs[0].schedule == get_playbook(SAMPLE).suggested_schedule
+ assert jobs[0].id in out
+
+ def test_schedule_reports_a_bad_variable_without_storing(
+ self, cli_store: ScheduledResearchJobStore, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = research_playbook.run(_Ctx(), "schedule", SAMPLE, "not_a_variable=x")
+
+ assert code == 0 # a user mistake is answered, not raised
+ assert "not_a_variable" in capsys.readouterr().out
+ assert cli_store.list_jobs() == []
+
+ def test_unknown_slug_lists_what_is_available(
+ self, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ ctx = _Ctx()
+
+ code = research_playbook.run(ctx, "not-a-template")
+
+ out = capsys.readouterr().out
+ assert code == 0
+ assert ctx.pending_prompt is None
+ assert "premarket-brief" in out
+
+ def test_missing_slug_is_answered_with_usage(
+ self, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = research_playbook.run(_Ctx(), "run")
+
+ out = capsys.readouterr().out
+ assert code == 0
+ assert "needs a template slug" in out
+
+ def test_help_token_prints_usage(self, capsys: pytest.CaptureFixture[str]) -> None:
+ code = research_playbook.run(_Ctx(), "help")
+
+ assert code == 0
+ assert "/playbook run" in capsys.readouterr().out
+
+
+# ---------------------------------------------------------------------------
+# Shared argument parsing
+# ---------------------------------------------------------------------------
+
+
+class TestVariableParsing:
+ @pytest.mark.parametrize(
+ ("tokens", "expected"),
+ [
+ ([], {}),
+ (["a=1"], {"a": "1"}),
+ (["a=1", "b=2"], {"a": "1", "b": "2"}),
+ (["a=two", "words", "b=x"], {"a": "two words", "b": "x"}),
+ (["a="], {"a": ""}),
+ (["a=x", "a=y"], {"a": "y"}),
+ ],
+ )
+ def test_accepted_forms(self, tokens: List[str], expected: dict) -> None:
+ variables, error = research_playbook.parse_variable_tokens(tokens)
+
+ assert error is None
+ assert variables == expected
+
+ def test_leading_bare_token_is_an_error(self) -> None:
+ variables, error = research_playbook.parse_variable_tokens(["oops", "a=1"])
+
+ assert variables == {}
+ assert error is not None and "key=value" in error
+
+ def test_variable_count_is_capped(self) -> None:
+ tokens = [f"v{i}=1" for i in range(research_playbook._MAX_VARIABLES + 1)]
+
+ variables, error = research_playbook.parse_variable_tokens(tokens)
+
+ assert variables == {}
+ assert error is not None and "too many" in error
+
+ def test_option_form_requires_an_assignment(self) -> None:
+ variables, error = research_playbook._parse_var_options(["nope"])
+
+ assert variables == {}
+ assert error is not None and "key=value" in error
+
+
+# ---------------------------------------------------------------------------
+# Cross-surface consistency
+# ---------------------------------------------------------------------------
+
+
+def test_all_three_surfaces_produce_the_same_prompt(
+ client: TestClient,
+ cli_store: ScheduledResearchJobStore,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ """REST, CLI and slash must schedule byte-identical instruction text."""
+ variables = {"home_market": "Hong Kong equities"}
+
+ rest_prompt = client.post(
+ f"/scheduled-runs/playbooks/{SAMPLE}",
+ json={"id": "cross-rest", "variables": variables},
+ ).json()["prompt"]
+
+ _run_cli(
+ ["playbook", "create", SAMPLE, "--id", "cross-cli", "--var", "home_market=Hong Kong equities"]
+ )
+ cli_job = cli_store.get("cross-cli")
+
+ ctx = _Ctx()
+ research_playbook.run(ctx, "run", SAMPLE, "home_market=Hong", "Kong", "equities")
+ capsys.readouterr()
+
+ assert cli_job is not None
+ assert rest_prompt == cli_job.prompt == ctx.pending_prompt
+ assert rest_prompt == get_playbook(SAMPLE).render(variables)
+
+
+def test_catalogue_size_matches_the_loader(client: TestClient) -> None:
+ """The REST catalogue is the loader's output, not a hand-maintained list."""
+ rows = client.get("/scheduled-runs/playbooks").json()
+
+ assert [row["slug"] for row in rows] == [pb.slug for pb in list_playbooks()]