"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(cli): add institutional research slash commands
Haozhe Wu382fadc0ca71
diff --git a/agent/cli/commands/institutional/__init__.py b/agent/cli/commands/institutional/__init__.pynew file mode 100644index 000000000..5e631f95e--- /dev/null+++ b/agent/cli/commands/institutional/__init__.py@@ -0,0 +1,29 @@+"""Institutional research workflow slash commands.++This package turns five recurring sell-side / buy-side workflows into explicit,+discoverable slash commands instead of prose buried in a swarm preset:++``/comps`` comparable company analysis+``/dcf`` discounted cash flow+``/attrib`` Brinson-Fachler performance attribution+``/memo`` investment memo+``/earnings`` earnings surprise bridge+``/screen`` systematic idea screen++Layout — deliberately import-cycle free:++``playbooks.py``+ Pure data. Imports nothing from :mod:`cli`, so+ :mod:`cli.commands.slash_router` can read the command specs at its own+ import time without a circular import.+``runner.py``+ Rendering + prompt construction + the shared ``run_playbook`` entry.+``comps.py`` / ``dcf.py`` / ``attrib.py`` / ``memo.py`` / ``earnings.py`` /+``screen.py``+ One thin ``run(ctx, *args)`` module per command. The REPL dispatcher+ (``cli.main._dispatch_slash``) passes the command keyword only for the+ modules listed in ``_MULTI_COMMAND_MODULES``; every other handler module+ owns exactly one command, so each command gets its own module here.++This ``__init__`` intentionally stays import-free.+"""diff --git a/agent/cli/commands/institutional/attrib.py b/agent/cli/commands/institutional/attrib.pynew file mode 100644index 000000000..5c4011b40--- /dev/null+++ b/agent/cli/commands/institutional/attrib.py@@ -0,0 +1,29 @@+"""``/attrib`` — Brinson-Fachler performance attribution.++Thin handler: the execution skeleton, the worked numeric example and the+missing-data policy all live in :mod:`.playbooks`, and the render/dispatch+logic in :mod:`.runner`. Running it produces allocation / selection /+interaction per sector, reconciled to the total active return.+"""++from __future__ import annotations++from typing import Any++from .runner import run_playbook+++def run(ctx: Any = None, *args: str) -> int:+ """Render or dispatch the ``/attrib`` playbook.++ Args:+ ctx: Interactive context supplying ``pending_prompt``.+ *args: Raw slash-command arguments.++ Returns:+ Process-style exit code; ``0`` on every user-facing path.+ """+ return run_playbook("attrib", ctx, *args)+++__all__ = ["run"]diff --git a/agent/cli/commands/institutional/comps.py b/agent/cli/commands/institutional/comps.pynew file mode 100644index 000000000..3609dcc12--- /dev/null+++ b/agent/cli/commands/institutional/comps.py@@ -0,0 +1,30 @@+"""``/comps`` — Comparable company analysis.++Thin handler: the execution skeleton, the worked numeric example and the+missing-data policy all live in :mod:`.playbooks`, and the render/dispatch+logic in :mod:`.runner`. Running it produces peer multiple table, the+subject's premium or discount versus the peer median, and an implied value+range.+"""++from __future__ import annotations++from typing import Any++from .runner import run_playbook+++def run(ctx: Any = None, *args: str) -> int:+ """Render or dispatch the ``/comps`` playbook.++ Args:+ ctx: Interactive context supplying ``pending_prompt``.+ *args: Raw slash-command arguments.++ Returns:+ Process-style exit code; ``0`` on every user-facing path.+ """+ return run_playbook("comps", ctx, *args)+++__all__ = ["run"]diff --git a/agent/cli/commands/institutional/dcf.py b/agent/cli/commands/institutional/dcf.pynew file mode 100644index 000000000..bc7e18764--- /dev/null+++ b/agent/cli/commands/institutional/dcf.py@@ -0,0 +1,30 @@+"""``/dcf`` — Discounted cash flow valuation.++Thin handler: the execution skeleton, the worked numeric example and the+missing-data policy all live in :mod:`.playbooks`, and the render/dispatch+logic in :mod:`.runner`. Running it produces value per share, the terminal-+value share of enterprise value, an exit-multiple cross-check and a WACC x g+sensitivity grid.+"""++from __future__ import annotations++from typing import Any++from .runner import run_playbook+++def run(ctx: Any = None, *args: str) -> int:+ """Render or dispatch the ``/dcf`` playbook.++ Args:+ ctx: Interactive context supplying ``pending_prompt``.+ *args: Raw slash-command arguments.++ Returns:+ Process-style exit code; ``0`` on every user-facing path.+ """+ return run_playbook("dcf", ctx, *args)+++__all__ = ["run"]diff --git a/agent/cli/commands/institutional/earnings.py b/agent/cli/commands/institutional/earnings.pynew file mode 100644index 000000000..426cf3d1c--- /dev/null+++ b/agent/cli/commands/institutional/earnings.py@@ -0,0 +1,29 @@+"""``/earnings`` — Earnings review.++Thin handler: the execution skeleton, the worked numeric example and the+missing-data policy all live in :mod:`.playbooks`, and the render/dispatch+logic in :mod:`.runner`. Running it produces a line-by-line surprise bridge+from revenue to EPS, splitting the recurring beat from the non-recurring one.+"""++from __future__ import annotations++from typing import Any++from .runner import run_playbook+++def run(ctx: Any = None, *args: str) -> int:+ """Render or dispatch the ``/earnings`` playbook.++ Args:+ ctx: Interactive context supplying ``pending_prompt``.+ *args: Raw slash-command arguments.++ Returns:+ Process-style exit code; ``0`` on every user-facing path.+ """+ return run_playbook("earnings", ctx, *args)+++__all__ = ["run"]diff --git a/agent/cli/commands/institutional/memo.py b/agent/cli/commands/institutional/memo.pynew file mode 100644index 000000000..04d31f7fa--- /dev/null+++ b/agent/cli/commands/institutional/memo.py@@ -0,0 +1,30 @@+"""``/memo`` — Investment memo.++Thin handler: the execution skeleton, the worked numeric example and the+missing-data policy all live in :mod:`.playbooks`, and the render/dispatch+logic in :mod:`.runner`. Running it produces thesis, variant view,+probability-weighted scenarios, falsifiable kill criteria and a monitoring+set.+"""++from __future__ import annotations++from typing import Any++from .runner import run_playbook+++def run(ctx: Any = None, *args: str) -> int:+ """Render or dispatch the ``/memo`` playbook.++ Args:+ ctx: Interactive context supplying ``pending_prompt``.+ *args: Raw slash-command arguments.++ Returns:+ Process-style exit code; ``0`` on every user-facing path.+ """+ return run_playbook("memo", ctx, *args)+++__all__ = ["run"]diff --git a/agent/cli/commands/institutional/playbooks.py b/agent/cli/commands/institutional/playbooks.pynew file mode 100644index 000000000..16f56370d--- /dev/null+++ b/agent/cli/commands/institutional/playbooks.py@@ -0,0 +1,654 @@+"""Playbook definitions for the institutional research slash commands.++Pure data — this module imports nothing from :mod:`cli`, so+:mod:`cli.commands.slash_router` can pull the command specs at its own import+time without a circular import.++Each :class:`Playbook` carries four things that make the command more than a+prompt forwarder:++1. ``steps`` — an ordered execution skeleton where every step names its+ inputs, the computation, and the artifact it must produce.+2. ``worked_example`` — a fully arithmetic-consistent numeric walkthrough.+ Every number below was computed and reconciled by hand; the totals tie out+ (the Brinson decomposition sums exactly to the active return, the earnings+ bridge sums exactly to the EPS delta). Both the user and the agent can+ reproduce them, which is what makes the skeleton checkable.+3. ``tools`` — the real registered tool names the agent should reach for.+ Verified against ``src/tools/*`` (``get_financial_statements``,+ ``get_stock_profile``, ``get_market_data``, ``get_sec_filings``,+ ``get_macro_series``, ``screen_market``, ``get_stock_news``,+ ``get_research_reports``, ``portfolio_risk_xray``).+4. ``gap_policy`` — what to do when a number cannot be fetched. The shared+ default forbids filling gaps from model memory.++Numbers in the worked examples are illustrative teaching figures, not+quotes for any real security.+"""++from __future__ import annotations++from dataclasses import dataclass+++@dataclass(frozen=True)+class Step:+ """One step of a playbook's execution skeleton.++ Attributes:+ title: Short imperative label, e.g. ``"Fix the peer set"``.+ inputs: What the step consumes (data, prior-step artifacts).+ compute: The transformation to perform.+ output: The artifact the step must produce before moving on.+ """++ title: str+ inputs: str+ compute: str+ output: str+++@dataclass(frozen=True)+class Playbook:+ """A single institutional workflow exposed as a slash command.++ Attributes:+ slug: Slash command keyword, without the leading ``/``.+ summary: One-line description shown in ``/help`` and the typeahead.+ usage: Usage line, e.g. ``"/dcf <ticker> [horizon=5y] [wacc=9%]"``.+ examples: Concrete invocations to show when arguments are missing.+ ask: Friendly follow-up question printed when arguments are missing.+ objective: One sentence stating what a finished run delivers.+ steps: Ordered execution skeleton.+ worked_example: Pre-rendered lines of the numeric walkthrough.+ tools: Registered tool names the agent should prefer.+ aliases: Extra keywords resolving to this command.+ """++ slug: str+ summary: str+ usage: str+ examples: tuple[str, ...]+ ask: str+ objective: str+ steps: tuple[Step, ...]+ worked_example: tuple[str, ...]+ tools: tuple[str, ...]+ aliases: tuple[str, ...] = ()++ @property+ def handler_module(self) -> str:+ """Dotted path of the module exposing ``run(ctx, *args)``."""+ return f"cli.commands.institutional.{self.slug}"+++# Shared policy text. Every playbook ships both blocks so the rule travels with+# the prompt rather than living only in a system prompt the user cannot see.+GAP_POLICY: tuple[str, ...] = (+ "Every figure must carry its source: the tool call and the fiscal period it",+ "came from. If a figure cannot be fetched, do NOT substitute a remembered or",+ "typical value. Instead: (a) name the missing item explicitly, (b) mark it",+ "MISSING in the table, (c) continue the analysis with the evidence actually",+ "retrieved, and (d) state which conclusions are now unsupported. A partial",+ "analysis with named holes is the correct deliverable; a complete-looking",+ "analysis with invented inputs is not.",+)++NOT_ADVICE: str = (+ "This is research tooling, not investment advice, and not a recommendation "+ "to buy or sell any security. Outputs are analytical artifacts to be "+ "reviewed by the user."+)+++_COMPS = Playbook(+ slug="comps",+ summary="Comparable company analysis (peer multiples -> implied range)",+ usage="/comps <ticker> [peer ...] [--asof YYYY-MM-DD]",+ examples=("/comps AAPL", "/comps 0700.HK 9988.HK BABA", "/comps NVDA AMD AVGO TSM"),+ ask="Which company should I run comps on? Peers are optional — I will build the peer set if you omit them.",+ objective=(+ "Produce a peer multiple table, the subject's premium/discount versus the "+ "peer median, and an implied value RANGE with the operating reason for the gap."+ ),+ steps=(+ Step(+ title="Fix the peer set",+ inputs="Subject ticker; user-supplied peers, or screen_market by sector and size when none are given.",+ compute=(+ "Keep names that share the subject's revenue driver and sit inside a "+ "0.25x-4x market-cap band. Reject everything else."+ ),+ output="Peer table listing each INCLUDED name with its inclusion reason, and each REJECTED name with its rejection reason.",+ ),+ Step(+ title="Pull the raw inputs",+ inputs="get_stock_profile + get_financial_statements (latest annual and quarterly) for the subject and every peer.",+ compute=(+ "Enterprise value = market cap + total debt - cash. Then EV/Sales, "+ "EV/EBITDA and P/E on trailing-twelve-month figures."+ ),+ output="One row per name, every cell tagged with the fiscal period it was taken from.",+ ),+ Step(+ title="Normalize",+ inputs="The raw multiple table from step 2.",+ compute=(+ "Mark negative or non-meaningful EBITDA / earnings as 'nm' — never as "+ "zero, and never dropped silently. Then compute the median and the "+ "25th/75th percentile per multiple."+ ),+ output="Peer median + interquartile range, plus the COUNT of names actually used in each column.",+ ),+ Step(+ title="Position the subject",+ inputs="Subject multiples versus the peer median.",+ compute="Premium/discount in percent for each multiple.",+ output=(+ "One verdict line per multiple, plus the two operating metrics "+ "(revenue growth, margin) that explain the largest gap. A discount is "+ "not a conclusion until it is explained."+ ),+ ),+ Step(+ title="Implied value range",+ inputs="Peer 25th / median / 75th percentile multiple x the subject's own metric.",+ compute="Implied EV -> minus net debt -> implied equity -> divide by diluted shares.",+ output="A RANGE with the spot price marked inside or outside it. Never a single point estimate.",+ ),+ ),+ worked_example=(+ "Subject: TTM revenue 4,000 | TTM EBITDA 800 (20.0% margin) | debt 900 |",+ "cash 400 (net debt 500) | 250m diluted shares | price 22.00",+ "",+ " market cap = 250 x 22.00 = 5,500",+ " EV = 5,500 + 900 - 400 = 6,000",+ " EV/EBITDA = 6,000 / 800 = 7.50x",+ "",+ "Peer EV/EBITDA sorted: 8.00, 9.20, 10.40, 11.60 (n=4, 0 marked nm)",+ " P25 = 8.00 + 0.75 x (9.20 - 8.00) = 8.90x",+ " median = 9.20 + 0.50 x (10.40 - 9.20) = 9.80x",+ " P75 = 10.40 + 0.25 x (11.60 - 10.40) = 10.70x",+ "",+ "Position: 7.50 / 9.80 - 1 = -23.5% (discount)",+ "",+ "Implied equity value per share (EV - net debt 500, / 250 shares):",+ " at P25 8.90 x 800 = 7,120 -> 6,620 = 26.48",+ " at median 9.80 x 800 = 7,840 -> 7,340 = 29.36",+ " at P75 10.70 x 800 = 8,560 -> 8,060 = 32.24",+ " spot 22.00 sits BELOW the P25 case; median implies +33.5%",+ "",+ "Step 4 verdict (the part that is actually analysis):",+ " subject revenue growth 4% vs peer median 11%. A -23.5% EV/EBITDA",+ " discount on 7pp less growth is roughly the fair penalty, so the",+ " gap is EXPLAINED, not an opportunity. The comp set only becomes a",+ " buy case if the growth gap is closing — check the last 4 quarters",+ " of year-over-year revenue before concluding anything.",+ ),+ tools=("get_stock_profile", "get_financial_statements", "screen_market", "get_market_data"),+ aliases=("peers",),+)+++_DCF = Playbook(+ slug="dcf",+ summary="Discounted cash flow valuation with sensitivity grid",+ usage="/dcf <ticker> [horizon=5] [wacc=9%] [g=2.5%]",+ examples=("/dcf MSFT", "/dcf 600519.SH horizon=10 g=3%", "/dcf TSLA wacc=11%"),+ ask="Which company should I value? Optionally pass horizon, wacc and terminal growth, e.g. /dcf MSFT horizon=5 wacc=9% g=2.5%.",+ objective=(+ "Produce an unlevered DCF: value per share, the terminal-value share of "+ "enterprise value, an exit-multiple cross-check, and a WACC x g sensitivity grid."+ ),+ steps=(+ Step(+ title="Anchor the base year",+ inputs="get_financial_statements — last 3 fiscal years plus trailing twelve months. get_sec_filings for the 10-K when a line item is ambiguous.",+ compute="Revenue, EBIT, effective tax rate, D&A, capex, change in net working capital. Then unlevered FCF = EBIT x (1 - tax) + D&A - capex - dNWC.",+ output="Base-year FCF with every line traced to a specific filing period.",+ ),+ Step(+ title="Set the drivers",+ inputs="History from step 1, plus management guidance if get_stock_news or get_sec_filings surfaces it.",+ compute="Revenue growth path, EBIT margin path, capex and D&A as a percent of revenue converging by the final year, dNWC as a percent of the revenue increment.",+ output="A driver table where every cell is labelled FILED, GUIDED, or ASSUMPTION. No unlabelled numbers.",+ ),+ Step(+ title="Discount rate",+ inputs="get_macro_series for the risk-free rate (e.g. DGS10); beta, equity risk premium, cost of debt, target debt weight.",+ compute="WACC = E/V x (rf + beta x ERP) + D/V x kd x (1 - tax).",+ output="WACC with each input tagged sourced or assumed. The equity risk premium is ALWAYS an assumption — say so.",+ ),+ Step(+ title="Terminal value, computed two ways",+ inputs="Final-year FCF and final-year EBITDA.",+ compute="Gordon growth TV = FCF_N x (1+g) / (WACC - g), with g capped at long-run nominal GDP. Separately, exit-multiple TV = EV/EBITDA x EBITDA_N.",+ output="Both terminal values, the implied exit multiple from the Gordon method, and whether it falls inside the peer range from /comps.",+ ),+ Step(+ title="Bridge to value per share",+ inputs="Discounted explicit-horizon FCF plus discounted terminal value.",+ compute="Enterprise value - net debt + non-operating assets - minority interest = equity value; divide by diluted shares.",+ output="Value per share, percent versus spot, and the terminal-value share of EV.",+ ),+ Step(+ title="Sensitivity, then the honest read",+ inputs="Base case from step 5.",+ compute="3x3 grid: WACC +/-100bp and terminal g +/-50bp.",+ output="The grid, the single driver that moves value most, and the WACC/g pair the CURRENT market price implies. That last number is the useful one.",+ ),+ ),+ worked_example=(+ "Base year: revenue 1,000 | EBIT margin 15% | tax 25% | D&A 60 | capex 80 | dNWC 10",+ " FCF0 = 150 x 0.75 + 60 - 80 - 10 = 82.5",+ "Drivers: revenue +8%/yr for 5y | margin flat 15% | D&A 6% of revenue",+ " capex 8% of revenue | dNWC 10% of the revenue increment",+ "",+ " yr revenue EBIT NOPAT D&A capex dNWC FCF DF@9% PV",+ " 1 1,080 162.0 121.5 64.8 86.4 8.0 91.9 0.9174 84.31",+ " 2 1,166 175.0 131.2 70.0 93.3 8.6 99.3 0.8417 83.54",+ " 3 1,260 189.0 141.7 75.6 100.8 9.3 107.2 0.7722 82.77",+ " 4 1,360 204.1 153.1 81.6 108.8 10.1 115.8 0.7084 82.02",+ " 5 1,469 220.4 165.3 88.2 117.6 10.9 125.0 0.6499 81.26",+ " sum PV(FCF) = 413.9",+ "",+ "Terminal value, g = 2.5%: (carry the unrounded FCF5 = 125.03, not the",+ "displayed 125.0 — rounding the terminal driver moves EV by ~0.4)",+ " TV = 125.03 x 1.025 / (0.09 - 0.025) = 1,971.6",+ " PV(TV) = 1,971.6 x 0.6499 = 1,281.4",+ " EV = 413.9 + 1,281.4 = 1,695.3",+ " equity = 1,695.3 - net debt 200 = 1,495.3",+ " per share, 100m shares = 14.95 (spot 12.50, +19.6%)",+ "",+ "Two mandatory cross-checks:",+ " TV share of EV = 1,281.4 / 1,695.3 = 75.6%",+ " -> above ~75% the answer IS the terminal assumption, so the exit",+ " multiple check below carries the conclusion, not the 5y forecast.",+ " implied exit EV/EBITDA = 1,971.6 / (220.4 + 88.2 = 308.6) = 6.39x",+ " -> inside a 6-9x peer range, so the Gordon g is not smuggling in",+ " a re-rating. If it landed at 14x, the model would be broken.",+ "",+ "Sensitivity corners (value per share):",+ " WACC 8.0%, g 2.5%: PV(FCF) 425.5 + PV(TV) 1,586.0 -> equity 1,811.5 = 18.12",+ " WACC 9.0%, g 2.5%: base case = 14.95",+ " WACC 10.0%, g 2.0%: PV(FCF) 402.8 + PV(TV) 989.8 -> equity 1,192.6 = 11.93",+ "",+ "The deliverable is NOT 'worth 14.95'. It is: the market's 12.50 sits",+ "just above the WACC 10% / g 2.0% corner, so the price is already",+ "discounting a ~10% cost of capital and near-zero real terminal growth.",+ "The question to research next is whether that is too harsh.",+ ),+ tools=("get_financial_statements", "get_sec_filings", "get_macro_series", "get_stock_profile"),+)+++_ATTRIB = Playbook(+ slug="attrib",+ summary="Brinson-Fachler attribution (allocation vs selection)",+ usage="/attrib <portfolio-or-holdings> [--benchmark SPY] [--from YYYY-MM-DD] [--to YYYY-MM-DD]",+ examples=(+ "/attrib my portfolio --benchmark SPY --from 2026-01-01",+ "/attrib AAPL:0.3 MSFT:0.4 XOM:0.3 --benchmark SPY",+ "/attrib holdings.csv --benchmark 000300.SH",+ ),+ ask="Which portfolio should I attribute, and against which benchmark? e.g. /attrib holdings.csv --benchmark SPY --from 2026-01-01",+ objective=(+ "Decompose active return into allocation, selection and interaction per "+ "sector, reconcile the decomposition to the total active return, and state "+ "whether the alpha came from the source the mandate promised."+ ),+ steps=(+ Step(+ title="Fix the weights",+ inputs="Portfolio holdings and weights at the START of the window; benchmark weights; a sector map for both.",+ compute="Normalize both weight vectors to 100%. Assign every name a sector.",+ output="Two weight vectors that each sum to 100%, plus the unclassified residual named explicitly rather than dumped into 'Other'.",+ ),+ Step(+ title="Get returns",+ inputs="get_market_data over the window for every holding, every benchmark constituent (or the benchmark's own sector series), and the benchmark itself.",+ compute="Sector return = weight-averaged constituent return, computed separately for the portfolio (Rp_i) and the benchmark (Rb_i).",+ output="Rp_i and Rb_i per sector, plus total Rp and Rb.",+ ),+ Step(+ title="Decompose",+ inputs="Weights from step 1 and returns from step 2.",+ compute=(+ "Per sector i: allocation = (wp_i - wb_i) x (Rb_i - Rb); "+ "selection = wb_i x (Rp_i - Rb_i); "+ "interaction = (wp_i - wb_i) x (Rp_i - Rb_i)."+ ),+ output="A per-sector table with the three effects and their column totals.",+ ),+ Step(+ title="Reconcile — this step is a gate",+ inputs="Column totals from step 3 and the total active return Rp - Rb.",+ compute="sum(allocation + selection + interaction) versus (Rp - Rb).",+ output=(+ "The residual. If it exceeds 1bp, STOP and report the gap and its "+ "likely cause (intra-period trades, cash, corporate actions, FX). Do "+ "not present an attribution table that does not tie out."+ ),+ ),+ Step(+ title="Attribute the residual",+ inputs="The gap from step 4 plus the trade log if available.",+ compute="Split into trading/timing, cash drag, and FX translation.",+ output="Each named with a number. Whatever remains is reported as unexplained — never absorbed into selection.",+ ),+ Step(+ title="Mandate verdict",+ inputs="The allocation-versus-selection split.",+ compute="Share of active return from each source.",+ output="A one-line verdict on whether the return came from the skill the mandate is paid for, and whether the top contributor is repeatable or a single lucky tilt.",+ ),+ ),+ worked_example=(+ "Benchmark: Tech wb 50%, Rb 10.0% | Health wb 30%, Rb 4.0% | Energy wb 20%, Rb -2.0%",+ "Portfolio: Tech wp 60%, Rp 12.0% | Health wp 30%, Rp 3.0% | Energy wp 10%, Rp -1.0%",+ "",+ " Rb = 0.50x10.0 + 0.30x4.0 + 0.20x(-2.0) = 5.80%",+ " Rp = 0.60x12.0 + 0.30x3.0 + 0.10x(-1.0) = 8.00%",+ " active return = +2.20%",+ "",+ " sector alloc (wp-wb)(Rb_i-Rb) selection wb(Rp_i-Rb_i) interaction",+ " Tech (0.10)(10.0-5.80)=+0.420 (0.50)(12.0-10.0)=+1.000 +0.200",+ " Health (0.00)(4.0-5.80) = 0.000 (0.30)(3.0- 4.0)=-0.300 0.000",+ " Energy (-0.10)(-2.0-5.80)=+0.780 (0.20)(-1.0-(-2.0))=+0.200 -0.100",+ " total +1.200 +0.900 +0.100",+ "",+ " reconciliation: 1.200 + 0.900 + 0.100 = 2.200 = active PASS",+ "",+ "Step 6 verdict (the part that is actually analysis):",+ " 55% of the +220bp is ALLOCATION, and +78bp of that is a single",+ " Energy underweight in a sector that fell 2%. Selection contributed",+ " +90bp, of which +100bp is Tech stock picking partly given back by",+ " -30bp in Health. For a stock-selection mandate this is an OFF-MANDATE",+ " quarter: the headline beat is mostly one sector tilt, which is one",+ " decision, not a repeatable process. Report it that way.",+ ),+ tools=("get_market_data", "portfolio_risk_xray", "get_sector_info", "get_stock_profile"),+ aliases=("attribution",),+)+++_MEMO = Playbook(+ slug="memo",+ summary="Investment memo — thesis, variant view, scenarios, kill criteria",+ usage="/memo <ticker> [long|short] [horizon=12m]",+ examples=("/memo NVDA long", "/memo BABA short horizon=6m", "/memo 005930.KS"),+ ask="Which company should the memo cover? Optionally say long or short and a horizon, e.g. /memo NVDA long horizon=12m.",+ objective=(+ "Produce a decision-ready memo: a one-sentence thesis, the variant view, "+ "probability-weighted scenarios, falsifiable kill criteria, and the "+ "quarterly monitoring set."+ ),+ steps=(+ Step(+ title="Thesis and variant view",+ inputs="get_research_reports and get_stock_news for what consensus currently believes.",+ compute="State consensus in one sentence, your view in one sentence, and the specific fact or mechanism that separates them.",+ output="If you cannot name what you believe that consensus does not, there is no memo — say so and stop.",+ ),+ Step(+ title="Business and unit economics",+ inputs="get_stock_profile, get_financial_statements, get_sec_filings (segment disclosure).",+ compute="Revenue drivers (volume x price x mix), contribution margin, what one marginal unit earns and how that trends.",+ output="A driver tree where the top line decomposes into things that can be independently observed.",+ ),+ Step(+ title="The numbers",+ inputs="Three years of history plus your forecast.",+ compute="Growth, margins, returns on capital, cash conversion, leverage.",+ output="A table where each historical cell cites a filing period and each forecast cell cites the step-2 driver it comes from.",+ ),+ Step(+ title="Valuation with two independent anchors",+ inputs="A /dcf run and a /comps run.",+ compute="Bear / base / bull value per share, with an explicit probability on each. Expected value = sum(probability x value).",+ output="The three cases, the expected value, the upside/downside skew, and the break-even probability of the base case.",+ ),+ Step(+ title="What kills it",+ inputs="The driver tree from step 2.",+ compute="Three risks, each expressed as an observable metric with a numeric threshold.",+ output="'Thesis is wrong if X falls below Y for two consecutive quarters' — falsifiable. 'Competition may intensify' is not a risk, it is filler.",+ ),+ Step(+ title="Monitoring set",+ inputs="Step 5 thresholds.",+ compute="Pick the three datapoints that move first when the thesis breaks.",+ output="Three metrics, their release cadence, their current value, and the exit trigger.",+ ),+ ),+ worked_example=(+ "Step 4 scenario math, spot 12.50:",+ "",+ " case prob value/share source",+ " bear 25% 9.00 comps at peer P25 on trough EBITDA",+ " base 50% 15.00 DCF, WACC 9.0%, g 2.5%",+ " bull 25% 22.00 DCF, margin path to 19% by year 5",+ "",+ " expected value = 0.25x9.00 + 0.50x15.00 + 0.25x22.00",+ " = 2.25 + 7.50 + 5.50 = 15.25 (+22.0% vs spot)",+ " downside = 9.00/12.50 - 1 = -28.0%",+ " upside = 22.00/12.50 - 1 = +76.0%",+ " skew = 76.0 / 28.0 = 2.7 : 1",+ "",+ " break-even test — hold bear at 25% and solve for the bull weight p",+ " that makes expected value equal the 12.50 spot:",+ " 2.25 + (0.75 - p)x15.00 + p x 22.00 = 12.50",+ " 13.50 + 7.00p = 12.50 -> p = -0.14",+ "",+ " A NEGATIVE break-even weight means even with zero probability on the",+ " bull case the expected value (2.25 + 0.75x15.00 = 13.50) still clears",+ " the spot price. So the position does not depend on the bull case at",+ " all — it depends entirely on the base case being right. That redirects",+ " the remaining work: stop arguing the upside, stress-test the 15.00.",+ " Concretely, the base case fails if the 15% EBIT margin is not held;",+ " at 12% margin the same DCF gives roughly 11.60, below spot.",+ ),+ tools=(+ "get_financial_statements",+ "get_sec_filings",+ "get_stock_profile",+ "get_research_reports",+ "get_stock_news",+ ),+)+++_EARNINGS = Playbook(+ slug="earnings",+ summary="Earnings review — surprise bridge from revenue to EPS",+ usage="/earnings <ticker> [quarter=Q3-2026]",+ examples=("/earnings AAPL", "/earnings MSFT quarter=Q2-2026", "/earnings 0700.HK"),+ ask="Whose earnings should I review? e.g. /earnings AAPL quarter=Q3-2026 (quarter defaults to the most recent report).",+ objective=(+ "Turn a headline beat or miss into a line-by-line bridge, separate the "+ "recurring operating surprise from the non-recurring one, and state what "+ "actually changed in the model."+ ),+ steps=(+ Step(+ title="Pull the print",+ inputs="get_financial_statements for the latest quarter; get_sec_filings for the 8-K / 10-Q; get_stock_news or get_research_reports for the consensus figure.",+ compute="Line up actual versus consensus for revenue, gross margin, opex, tax rate, share count, EPS.",+ output="A two-column table. The consensus column is tagged SOURCED or ASSUMPTION — a remembered consensus number is an ASSUMPTION and must be labelled one.",+ ),+ Step(+ title="Build the bridge",+ inputs="The step-1 table.",+ compute=(+ "Walk from consensus EPS to actual EPS ONE variable at a time, holding "+ "the others at consensus, then re-baselining after each step. Order: "+ "revenue, gross margin, opex, below-the-line, tax rate, share count."+ ),+ output="A bridge whose steps sum EXACTLY to actual EPS minus consensus EPS. If it does not sum, a variable is missing — find it before writing anything.",+ ),+ Step(+ title="Grade the quality",+ inputs="The bridge.",+ compute="Split each step into recurring operating (volume, price, mix, structural cost) and non-recurring (one-off tax items, buybacks, FX, asset sales, legal reversals).",+ output="Operating-only surprise versus headline surprise, as a number and as a percentage of the headline.",+ ),+ Step(+ title="Guidance delta",+ inputs="New guidance versus prior guidance versus consensus for the year.",+ compute="Implied remainder of the year = full-year guide minus reported year-to-date.",+ output="Whether the implied remainder is an acceleration or a quiet cut hidden by a strong quarter already banked.",+ ),+ Step(+ title="What changed in the model",+ inputs="Steps 3 and 4.",+ compute="The three inputs whose forward path you now revise, and the resulting change in fair value.",+ output="Old fair value, new fair value, and the single line item responsible for most of the change.",+ ),+ ),+ worked_example=(+ "Consensus: revenue 1,000 | GM 60.0% | opex 400 | interest -20 | tax 25%",+ " | 100.0m shares -> EPS 1.35",+ "Actual: revenue 1,050 | GM 58.5% | opex 405 | interest -20 | tax 22%",+ " | 99.0m shares -> EPS 1.49",+ "",+ "Bridge, one variable at a time, re-baselining after each step:",+ " start (consensus) EPS 1.3500",+ " + revenue 1,000 -> 1,050 at 60% GM GP 630, NI 157.50 EPS 1.5750 +0.2250",+ " + GM 60.0% -> 58.5% GP 614.25, NI 145.69 EPS 1.4569 -0.1181",+ " + opex 400 -> 405 NI 141.94 EPS 1.4194 -0.0375",+ " + tax 25% -> 22% NI 147.62 EPS 1.4762 +0.0568",+ " + shares 100.0m -> 99.0m NI 147.62 EPS 1.4911 +0.0149",+ " sum of steps = 0.2250-0.1181-0.0375+0.0568+0.0149 = +0.1411",+ " check: 1.4911 - 1.3500 = +0.1411 PASS",+ "",+ "Step 3 quality grade (the part that is actually analysis):",+ " recurring operating = +0.2250 - 0.1181 - 0.0375 = +0.0694",+ " non-recurring = +0.0568 (one-off R&D tax credit)",+ " + 0.0149 (buyback) = +0.0717",+ " non-recurring share of the headline beat = 0.0717/0.1411 = 50.8%",+ "",+ " So 'beat by 14 cents on a 5% revenue beat' is really a 7-cent",+ " operating beat. The 5% volume upside was half given back by a 150bp",+ " mix-driven gross margin decline — that mix shift is the datapoint",+ " that changes the model, not the EPS headline. Check whether the",+ " lower-margin revenue is a one-quarter mix accident or the new run rate.",+ ),+ tools=(+ "get_financial_statements",+ "get_sec_filings",+ "get_stock_news",+ "get_research_reports",+ "get_market_data",+ ),+)+++_SCREEN = Playbook(+ slug="screen",+ summary="Systematic idea screen — hypothesis, funnel, survivor queue",+ usage="/screen <hypothesis or criteria> [--universe sp500|csi300|...]",+ examples=(+ "/screen quality compounders trading below 15x FCF --universe sp500",+ "/screen ROIC > 12% and net debt/EBITDA < 2 --universe csi300",+ "/screen oversold industrials with rising order books",+ ),+ ask="What should I screen for? Give me the economic hypothesis or the hard criteria, e.g. /screen quality compounders below 15x FCF --universe sp500",+ objective=(+ "Turn a hypothesis into hard thresholds, run the screen, publish the funnel "+ "count at every filter, and hand back a de-duplicated research queue with an "+ "honest false-positive caveat."+ ),+ steps=(+ Step(+ title="State the hypothesis first",+ inputs="The user's words.",+ compute="Write the economic mechanism in one sentence BEFORE choosing any threshold, so the filters are derived from the idea rather than reverse-engineered from a pretty result.",+ output="One sentence. If the hypothesis cannot be stated without referring to the metrics, it is a data-mining exercise — label it as one.",+ ),+ Step(+ title="Translate to hard criteria",+ inputs="The hypothesis.",+ compute="Each clause becomes a metric with a numeric threshold and a direction. Every threshold gets a one-line justification.",+ output="A criteria table: metric, operator, threshold, why this number.",+ ),+ Step(+ title="Run the funnel",+ inputs="screen_market over the stated universe, then get_financial_statements for any criterion the screener cannot express.",+ compute="Apply filters in order, from cheapest and most eliminating to most expensive.",+ output="The FUNNEL: the surviving count after every single filter. A screen that only reports the final list is unreviewable.",+ ),+ Step(+ title="Data-completeness pass",+ inputs="The survivor list.",+ compute="Drop names missing an input for a binding criterion.",+ output="Names dropped for missing data are listed SEPARATELY from names dropped for failing a test. Conflating the two silently biases the result toward well-covered large caps.",+ ),+ Step(+ title="De-duplicate by driver",+ inputs="Survivors.",+ compute="Group names sharing one underlying driver (same commodity, same customer, same rate sensitivity).",+ output="One representative per cluster plus the cluster members, so the queue is not five bets on one macro variable.",+ ),+ Step(+ title="Hand back a queue, not a portfolio",+ inputs="The de-duplicated survivors.",+ compute="For each name: the single metric it is weakest on, and the one question to answer first.",+ output=(+ "A ranked research queue plus a threshold-sensitivity caveat stated in "+ "numbers: re-run the funnel with each threshold loosened one notch and "+ "report how much of the survivor set is an artifact of where the lines "+ "were drawn. Never quote a per-name false-positive rate — a deterministic "+ "screen is not a hypothesis test and has none."+ ),+ ),+ ),+ worked_example=(+ "Hypothesis: 'Businesses that earn well above their cost of capital and",+ "are not levered can reinvest through a downturn; the market underpays",+ "for that when the free cash flow yield is already high.'",+ "",+ "Criteria and funnel (universe: 3,200 listed names):",+ " filter surviving removed",+ " start 3,200",+ " market cap >= 2.0bn (liquidity) 812 -2,388",+ " ROIC >= 12% (above cost of capital) 245 -567",+ " net debt/EBITDA <= 2.0 (survives a downturn) 96 -149",+ " FCF yield >= 5% (the underpayment) 31 -65",+ " data-completeness pass (step 4) 19 -12 MISSING DATA",+ " de-duplicate by driver (step 5) 6 -13 same driver",+ "",+ " the 12 dropped for missing data are listed by name and by which",+ " field was absent; they are NOT counted as failures.",+ " the 13 collapsed names are 6 semis-cycle, 4 US housing, 3 freight.",+ "",+ "Step 6 caveat, stated in numbers rather than hedged in prose:",+ " A screen is a deterministic filter on observed data, so there is no",+ " per-name 'false positive rate' to quote — the selection risk lives in",+ " the CHOICE of the 4 thresholds, not in the 3,200 rows. Size it that way:",+ " the funnel keeps 31/3,200 = 0.97% of the universe, so moving any one",+ " threshold by a notch (ROIC 12% -> 10%, FCF yield 5% -> 4%) is what to",+ " report. Here that widens 31 -> 74, i.e. 58% of the survivor set is an",+ " artifact of where the lines were drawn rather than a stable property.",+ " So the screen cannot establish that these 6 names are good; it can only",+ " establish that they are worth the next 6 hours. Treat the output as a",+ " research queue and require an out-of-sample or fundamental confirmation",+ " before any of it becomes a position.",+ ),+ tools=("screen_market", "get_financial_statements", "get_stock_profile", "iwencai_search"),+ aliases=("screener",),+)+++PLAYBOOKS: tuple[Playbook, ...] = (_COMPS, _DCF, _ATTRIB, _MEMO, _EARNINGS, _SCREEN)++PLAYBOOKS_BY_SLUG: dict[str, Playbook] = {pb.slug: pb for pb in PLAYBOOKS}+++__all__ = [+ "GAP_POLICY",+ "NOT_ADVICE",+ "PLAYBOOKS",+ "PLAYBOOKS_BY_SLUG",+ "Playbook",+ "Step",+]diff --git a/agent/cli/commands/institutional/runner.py b/agent/cli/commands/institutional/runner.pynew file mode 100644index 000000000..d53c3e909--- /dev/null+++ b/agent/cli/commands/institutional/runner.py@@ -0,0 +1,211 @@+"""Shared rendering and dispatch for the institutional workflow commands.++Every ``/comps``-style command funnels through :func:`run_playbook`:++* no arguments (or ``help`` / ``-h`` / ``--help`` / ``?``) renders the full+ playbook card — objective, numbered execution skeleton, the worked numeric+ example, the data-gap policy and the not-advice notice — followed by a+ friendly follow-up question. This is a normal, successful outcome, so it+ returns ``0``; missing arguments are not an error here.+* with arguments the same skeleton is rendered into a prompt and queued on+ ``ctx.pending_prompt``, which ``cli.main._interactive_loop`` drains into a+ real agent turn (the mechanism ``/journal`` and ``/shadow`` already use).+ When the context cannot hold a queued prompt — a bare test stub, or a+ non-interactive caller — the prompt is printed instead so it can be pasted.+"""++from __future__ import annotations++import os+from typing import Any++from rich.console import Console, Group+from rich.panel import Panel+from rich.table import Table+from rich.text import Text++from .playbooks import GAP_POLICY, NOT_ADVICE, PLAYBOOKS_BY_SLUG, Playbook++# Defensive ceiling on the free-text argument so a paste bomb cannot blow up+# the queued prompt (and, downstream, the model context).+#+# A malformed override must not be fatal: this module is imported by+# ``cli.main._dispatch_slash``, whose import guard only catches ``ImportError``,+# so a ``ValueError`` raised here would escape the dispatcher and take down the+# whole REPL. Fall back to the default instead.+def _arg_max_chars() -> int:+ """Resolve the argument length cap, ignoring a malformed override."""+ raw = os.getenv("VIBE_TRADING_SLASH_ARG_MAX", "")+ try:+ return max(32, int(raw))+ except ValueError:+ return 600+++_ARG_MAX_CHARS = _arg_max_chars()++_HELP_TOKENS = frozenset({"help", "-h", "--help", "?"})+++def _console() -> Console:+ """Return the shared CLI console."""+ from cli.theme import get_console++ return get_console()+++def _render_card(playbook: Playbook) -> None:+ """Print the full playbook card for ``playbook``.++ Steps go into a two-column ``Table.grid`` rather than a flat ``Text`` so+ the ``in`` / ``compute`` / ``out`` labels keep a hanging indent when the+ body wraps on a narrow terminal.+ """+ header = Text()+ header.append(playbook.objective + "\n\n")+ header.append("Usage ", style="dim")+ header.append(playbook.usage + "\n", style="bold")+ for example in playbook.examples:+ header.append(" ")+ header.append(example + "\n", style="cyan")+ header.append("\nExecution skeleton", style="bold")++ steps = Table.grid(padding=(0, 1))+ steps.add_column(style="dim", no_wrap=True, justify="right", width=9)+ steps.add_column(ratio=1, overflow="fold")+ for index, step in enumerate(playbook.steps, start=1):+ steps.add_row(f"{index}.", Text(step.title, style="bold"))+ steps.add_row("in", Text(step.inputs, style="dim"))+ steps.add_row("compute", Text(step.compute, style="dim"))+ steps.add_row("out", Text(step.output, style="dim"))+ steps.add_row("", "")++ example_block = Text()+ example_block.append("Worked example\n", style="bold")+ for line in playbook.worked_example:+ example_block.append(f" {line}\n", style="dim")+ example_block.append("\nTools ", style="dim")+ example_block.append(", ".join(playbook.tools) + "\n\n", style="cyan")+ example_block.append("Missing data\n", style="bold")+ for line in GAP_POLICY:+ example_block.append(f" {line}\n", style="dim")+ example_block.append("\n")+ example_block.append(NOT_ADVICE + "\n\n", style="yellow")+ example_block.append(playbook.ask, style="bold")++ _console().print(+ Panel(+ Group(header, steps, example_block),+ title=f"/{playbook.slug}",+ border_style="cyan",+ padding=(1, 2),+ )+ )+++def build_prompt(playbook: Playbook, subject: str) -> str:+ """Render ``playbook`` plus the user's arguments into an agent prompt.++ The full skeleton, the worked example, the gap policy and the not-advice+ notice all travel with the prompt so the behaviour does not depend on any+ particular system prompt being loaded.++ Args:+ playbook: The workflow to run.+ subject: The user's raw arguments, already trimmed and length-capped.++ Returns:+ The prompt text to hand to the agent loop.+ """+ lines = [+ f"Run the {playbook.slug.upper()} research playbook.",+ "",+ f"Request: {subject}",+ "",+ f"Deliverable: {playbook.objective}",+ "",+ "Work through these steps in order. Do not skip a step, do not reorder them,",+ "and show the intermediate artifact each step is required to produce.",+ "",+ ]+ for index, step in enumerate(playbook.steps, start=1):+ lines.append(f"Step {index} — {step.title}")+ lines.append(f" Inputs: {step.inputs}")+ lines.append(f" Compute: {step.compute}")+ lines.append(f" Output: {step.output}")+ lines.append("")++ lines.append("Worked example — reproduce this level of arithmetic explicitness with")+ lines.append("the real retrieved data. The figures below are illustrative teaching")+ lines.append("numbers, not data about any real security, and must not be reused as facts.")+ lines.extend(f" {line}" for line in playbook.worked_example)+ lines.append("")++ lines.append(f"Preferred tools: {', '.join(playbook.tools)}.")+ # Some of these are key-gated (``get_macro_series`` needs FRED_API_KEY,+ # ``iwencai_search`` needs VIBE_TRADING_IWENCAI_KEY) and are absent from the+ # registry unless configured. Say so explicitly: an unavailable tool must+ # become a declared gap, never a remembered number.+ lines.append(+ "Any preferred tool that is not registered in this session is simply "+ "unavailable — skip it, record what it would have supplied as a gap under "+ "the missing-data policy below, and never fill that gap from memory."+ )+ lines.append("")+ lines.append("Missing data:")+ lines.extend(f" {line}" for line in GAP_POLICY)+ lines.append("")+ lines.append(NOT_ADVICE)+ return "\n".join(lines)+++def run_playbook(slug: str, ctx: Any = None, *args: str) -> int:+ """Render or dispatch the playbook registered under ``slug``.++ Args:+ slug: Playbook key, matching the slash command keyword.+ ctx: The interactive context. Needs a writable ``pending_prompt``+ attribute for the queued-turn path; anything else falls back to+ printing the prompt.+ *args: Raw slash-command arguments.++ Returns:+ ``0`` in every user-facing path — a missing argument is answered with+ the playbook card and a follow-up question, not an error. ``1`` only+ when ``slug`` is not a registered playbook, which is a programming+ error rather than a user mistake.+ """+ playbook = PLAYBOOKS_BY_SLUG.get(slug)+ if playbook is None:+ _console().print(Text(f"Unknown research playbook: {slug}", style="bold red"))+ return 1++ if args and args[0].lower() in _HELP_TOKENS:+ _render_card(playbook)+ return 0++ subject = " ".join(args).strip()+ if not subject:+ _render_card(playbook)+ return 0+ if len(subject) > _ARG_MAX_CHARS:+ subject = subject[:_ARG_MAX_CHARS].rstrip() + " …(truncated)"++ prompt = build_prompt(playbook, subject)+ console = _console()+ if ctx is not None and hasattr(ctx, "pending_prompt"):+ try:+ ctx.pending_prompt = prompt+ console.print(+ Text(f"→ Running the /{playbook.slug} playbook on: {subject}", style="dim")+ )+ return 0+ except Exception: # noqa: BLE001 — never let a slash handler kill the REPL+ pass++ console.print(Text(f"/{playbook.slug} — paste this prompt to run it:", style="bold"))+ console.print(Text(prompt, style="dim"))+ return 0+++__all__ = ["build_prompt", "run_playbook"]diff --git a/agent/cli/commands/institutional/screen.py b/agent/cli/commands/institutional/screen.pynew file mode 100644index 000000000..78f6e6358--- /dev/null+++ b/agent/cli/commands/institutional/screen.py@@ -0,0 +1,29 @@+"""``/screen`` — Systematic idea screen.++Thin handler: the execution skeleton, the worked numeric example and the+missing-data policy all live in :mod:`.playbooks`, and the render/dispatch+logic in :mod:`.runner`. Running it produces hypothesis, hard thresholds, the+full funnel count and a de-duplicated research queue.+"""++from __future__ import annotations++from typing import Any++from .runner import run_playbook+++def run(ctx: Any = None, *args: str) -> int:+ """Render or dispatch the ``/screen`` playbook.++ Args:+ ctx: Interactive context supplying ``pending_prompt``.+ *args: Raw slash-command arguments.++ Returns:+ Process-style exit code; ``0`` on every user-facing path.+ """+ return run_playbook("screen", ctx, *args)+++__all__ = ["run"]diff --git a/agent/cli/commands/slash_router.py b/agent/cli/commands/slash_router.pyindex af9250668..195cf437d 100644--- a/agent/cli/commands/slash_router.py+++ b/agent/cli/commands/slash_router.py@@ -1,7 +1,11 @@"""Slash command registry + fuzzy matcher.-Source of truth for the 15 user-facing slash commands defined in-``docs/2026-05-19_session02_uiux_design_proposal.md`` §3.4.+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.Each :class:`Command` is a frozen dataclass — registry entries areimmutable so callers can cache filtered slices without worrying about@@ -61,6 +65,61 @@ _ALIASES: dict[str, str] = {}+def _register_institutional_slash_commands() -> None:+ """Append the institutional research workflow commands to the registry.++ ``/comps``, ``/dcf``, ``/attrib``, ``/memo``, ``/earnings`` and ``/screen``+ each own a handler module under :mod:`cli.commands.institutional`, and each+ carries its own execution skeleton and worked numeric example. They are+ registered here rather than inlined into :data:`SLASH_COMMANDS` so the same+ guarantees the connector group gets in :func:`cli.main._register_live_slash_commands`+ apply: a name already in the registry is never overwritten, and a repeated+ call never duplicates a row.++ Running at this module's import time — the earliest possible moment — means+ ``cli.commands.help`` (which binds :data:`SLASH_COMMANDS` at ITS import) and+ ``cli.completer`` (which snapshots the tuple as a default argument) both see+ the commands regardless of import order.++ The specs come from :mod:`cli.commands.institutional.playbooks`, a data-only+ module that imports nothing from :mod:`cli`, so there is no import cycle.+ """+ from .institutional.playbooks import PLAYBOOKS++ global SLASH_COMMANDS, _ALIASES++ existing = {cmd.name for cmd in SLASH_COMMANDS}+ additions = tuple(+ Command(pb.slug, pb.summary, pb.handler_module)+ for pb in PLAYBOOKS+ if pb.slug not in existing+ )+ if additions:+ commands = list(SLASH_COMMANDS)+ # Sit just above ``quit`` so the exit row stays last.+ quit_idx = next(+ (i for i, c in enumerate(commands) if c.name == "quit"), len(commands)+ )+ commands[quit_idx:quit_idx] = list(additions)+ SLASH_COMMANDS = tuple(commands)++ # Aliases only ever ADD keys. A key that is already a command name, or is+ # already claimed by another alias, is left untouched — an alias must never+ # shadow an existing command.+ registered = {cmd.name for cmd in SLASH_COMMANDS}+ new_aliases = {+ alias: pb.slug+ for pb in PLAYBOOKS+ for alias in pb.aliases+ if alias not in registered and alias not in _ALIASES+ }+ if new_aliases:+ _ALIASES = {**_ALIASES, **new_aliases}+++_register_institutional_slash_commands()++def _parse_token(input_text: str) -> str:"""Strip the leading ``/`` and isolate the command token.diff --git a/agent/tests/test_institutional_commands.py b/agent/tests/test_institutional_commands.pynew file mode 100644index 000000000..c155bbd33--- /dev/null+++ b/agent/tests/test_institutional_commands.py@@ -0,0 +1,552 @@+"""Tests for the institutional research workflow slash commands.++Covers the four things that can silently break:++1. Registration — all six commands reach ``SLASH_COMMANDS``, without+ duplicating or displacing anything already there, and idempotently.+2. Aliases — never shadow an existing command, never steal a key another+ alias already owns.+3. Argument handling — a missing argument produces the playbook card and a+ follow-up question (exit code 0, nothing queued), while a supplied+ argument queues a prompt carrying the skeleton, the worked example, the+ missing-data policy and the not-advice notice.+4. Playbook data integrity — every tool name referenced by a playbook is a+ real registered tool (checked against the ``src/tools`` sources rather+ than against any document), and the two worked examples that claim to+ reconcile actually do when recomputed from first principles.++No network is touched anywhere in this module.+"""++from __future__ import annotations++import importlib+import re+from pathlib import Path+from typing import Any++import pytest++from cli.commands import slash_router+from cli.commands.institutional import runner+from cli.commands.institutional.playbooks import (+ GAP_POLICY,+ NOT_ADVICE,+ PLAYBOOKS,+ PLAYBOOKS_BY_SLUG,+)++_SLUGS = ("comps", "dcf", "attrib", "memo", "earnings", "screen")++_AGENT_DIR = Path(__file__).resolve().parent.parent+++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 (legacy / stub caller)."""+++# ---------------------------------------------------------------------------+# Registration+# ---------------------------------------------------------------------------+++class TestRegistration:+ def test_all_six_commands_are_registered(self) -> None:+ names = {cmd.name for cmd in slash_router.SLASH_COMMANDS}+ assert set(_SLUGS) <= names++ def test_registry_has_no_duplicate_names(self) -> None:+ names = [cmd.name for cmd in slash_router.SLASH_COMMANDS]+ assert len(names) == len(set(names))++ def test_pre_existing_commands_survive(self) -> None:+ """Appending must not displace or rewrite the base registry."""+ names = {cmd.name for cmd in slash_router.SLASH_COMMANDS}+ assert {"help", "model", "memory", "history", "goal", "quit"} <= names++ def test_quit_stays_last(self) -> None:+ assert slash_router.SLASH_COMMANDS[-1].name == "quit"++ def test_registration_is_idempotent(self) -> None:+ before = list(slash_router.SLASH_COMMANDS)+ before_aliases = dict(slash_router._ALIASES)+ slash_router._register_institutional_slash_commands()+ assert list(slash_router.SLASH_COMMANDS) == before+ assert dict(slash_router._ALIASES) == before_aliases++ def test_registration_skips_names_already_taken(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """A pre-existing ``/memo`` must win; we never overwrite it."""+ squatter = slash_router.Command("memo", "someone else's memo", "cli.commands.help")+ base = tuple(+ cmd for cmd in slash_router.SLASH_COMMANDS if cmd.name not in _SLUGS+ )+ monkeypatch.setattr(slash_router, "SLASH_COMMANDS", base + (squatter,))+ slash_router._register_institutional_slash_commands()+ memo_rows = [c for c in slash_router.SLASH_COMMANDS if c.name == "memo"]+ assert len(memo_rows) == 1+ assert memo_rows[0].handler_module == "cli.commands.help"++ def test_descriptions_are_one_line_and_non_empty(self) -> None:+ for cmd in slash_router.SLASH_COMMANDS:+ if cmd.name in _SLUGS:+ assert cmd.description.strip()+ assert "\n" not in cmd.description+ assert len(cmd.description) <= 70+++# ---------------------------------------------------------------------------+# Aliases+# ---------------------------------------------------------------------------+++class TestAliases:+ def test_declared_aliases_resolve(self) -> None:+ for alias, expected in (("peers", "comps"), ("attribution", "attrib"), ("screener", "screen")):+ cmd = slash_router.find_exact(alias)+ assert cmd is not None, alias+ assert cmd.name == expected++ def test_no_alias_shadows_a_command_name(self) -> None:+ names = {cmd.name for cmd in slash_router.SLASH_COMMANDS}+ assert not (set(slash_router._ALIASES) & names)++ def test_alias_targets_all_exist(self) -> None:+ names = {cmd.name for cmd in slash_router.SLASH_COMMANDS}+ for alias, target in slash_router._ALIASES.items():+ assert target in names, f"{alias} -> {target}"++ def test_pre_existing_aliases_untouched(self) -> None:+ for alias, target in (("q", "quit"), ("exit", "quit"), (":q", "quit"), ("?", "help")):+ assert slash_router._ALIASES[alias] == target++ def test_registration_does_not_steal_a_claimed_alias(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(+ slash_router, "_ALIASES", {**slash_router._ALIASES, "peers": "help"}+ )+ slash_router._register_institutional_slash_commands()+ assert slash_router._ALIASES["peers"] == "help"+++# ---------------------------------------------------------------------------+# Discoverability: /help + typeahead+# ---------------------------------------------------------------------------+++class TestDiscoverability:+ def test_help_module_sees_the_commands(self) -> None:+ from cli.commands import help as help_cmd++ assert set(_SLUGS) <= {c.name for c in help_cmd.SLASH_COMMANDS}++ def test_help_renders_them(self, capsys: pytest.CaptureFixture[str]) -> None:+ from cli.commands import help as help_cmd++ help_cmd.run(None)+ out = capsys.readouterr().out+ for slug in _SLUGS:+ assert f"/{slug}" in out++ def test_match_commands_surfaces_them(self) -> None:+ assert "comps" in {c.name for c in slash_router.match_commands("/comp")}+ assert "dcf" in {c.name for c in slash_router.match_commands("/dc")}+ assert "earnings" in {c.name for c in slash_router.match_commands("/earn")}++ def test_bare_slash_lists_them(self) -> None:+ names = {c.name for c in slash_router.match_commands("/")}+ assert set(_SLUGS) <= names++ def test_completer_yields_them(self) -> None:+ from prompt_toolkit.document import Document++ from cli.completer import SlashCompleter++ completions = list(+ SlashCompleter().get_completions(+ Document("/", cursor_position=1), complete_event=None+ )+ )+ assert set(_SLUGS) <= {c.text for c in completions}+++# ---------------------------------------------------------------------------+# Handler modules+# ---------------------------------------------------------------------------+++class TestHandlerModules:+ def test_handler_modules_import_and_expose_run(self) -> None:+ for slug in _SLUGS:+ module = importlib.import_module(f"cli.commands.institutional.{slug}")+ assert callable(module.run)++ def test_registry_points_at_the_right_modules(self) -> None:+ for cmd in slash_router.SLASH_COMMANDS:+ if cmd.name in _SLUGS:+ assert cmd.handler_module == f"cli.commands.institutional.{cmd.name}"++ def test_handlers_are_single_command_modules(self) -> None:+ """``cli.main`` only passes the keyword to modules it lists as multi-command.++ These are not listed, so ``run`` must take ``(ctx, *args)`` — if that+ ever changed the dispatcher would silently feed the keyword in as the+ first argument.+ """+ main = importlib.import_module("cli.main")++ for slug in _SLUGS:+ assert f"cli.commands.institutional.{slug}" not in main._MULTI_COMMAND_MODULES+++# ---------------------------------------------------------------------------+# Argument handling+# ---------------------------------------------------------------------------+++class TestArgumentHandling:+ @pytest.mark.parametrize("slug", _SLUGS)+ def test_missing_args_prints_the_card_and_asks(+ self, slug: str, capsys: pytest.CaptureFixture[str]+ ) -> None:+ ctx = _Ctx()+ module = importlib.import_module(f"cli.commands.institutional.{slug}")+ assert module.run(ctx) == 0+ assert ctx.pending_prompt is None # nothing dispatched to the model+ out = capsys.readouterr().out+ assert "Execution skeleton" in out+ assert "Worked example" in out+ # The friendly follow-up question, not a usage error.+ assert "?" in out+ assert "Error" not in out+ assert "Usage:" not in out++ @pytest.mark.parametrize("token", ["help", "--help", "-h", "?"])+ def test_help_token_prints_the_card_without_queueing(+ self, token: str, capsys: pytest.CaptureFixture[str]+ ) -> None:+ ctx = _Ctx()+ from cli.commands.institutional import dcf++ assert dcf.run(ctx, token, "AAPL") == 0+ assert ctx.pending_prompt is None+ assert "Execution skeleton" in capsys.readouterr().out++ @pytest.mark.parametrize("slug", _SLUGS)+ def test_args_queue_a_prompt(self, slug: str) -> None:+ ctx = _Ctx()+ module = importlib.import_module(f"cli.commands.institutional.{slug}")+ assert module.run(ctx, "AAPL", "MSFT") == 0+ prompt = ctx.pending_prompt+ assert prompt is not None+ assert "AAPL MSFT" in prompt+ assert slug.upper() in prompt+ # Skeleton, worked example, gap policy and disclaimer all travel along.+ playbook = PLAYBOOKS_BY_SLUG[slug]+ for index, step in enumerate(playbook.steps, start=1):+ assert f"Step {index} — {step.title}" in prompt+ assert GAP_POLICY[0] in prompt+ assert NOT_ADVICE in prompt+ assert playbook.worked_example[0] in prompt++ def test_long_argument_is_truncated(self) -> None:+ ctx = _Ctx()+ from cli.commands.institutional import screen++ assert screen.run(ctx, "x" * 5000) == 0+ assert ctx.pending_prompt is not None+ assert "…(truncated)" in ctx.pending_prompt+ # The cap bounds the user's argument, not the (fixed-size) skeleton.+ request = next(+ line for line in ctx.pending_prompt.splitlines() if line.startswith("Request: ")+ )+ assert len(request) < runner._ARG_MAX_CHARS + 40+ assert request.count("x") == runner._ARG_MAX_CHARS++ def test_falls_back_to_printing_when_context_cannot_queue(+ self, capsys: pytest.CaptureFixture[str]+ ) -> None:+ from cli.commands.institutional import comps++ assert comps.run(_NoQueueCtx(), "AAPL") == 0+ out = capsys.readouterr().out+ assert "paste this prompt" in out+ assert "Step 1" in out++ def test_none_context_does_not_raise(self, capsys: pytest.CaptureFixture[str]) -> None:+ from cli.commands.institutional import memo++ assert memo.run(None, "NVDA") == 0+ assert "paste this prompt" in capsys.readouterr().out++ def test_unknown_slug_is_reported_not_raised(+ self, capsys: pytest.CaptureFixture[str]+ ) -> None:+ assert runner.run_playbook("not-a-playbook", _Ctx()) == 1+ assert "Unknown research playbook" in capsys.readouterr().out+++# ---------------------------------------------------------------------------+# End-to-end through the real REPL dispatcher+# ---------------------------------------------------------------------------+++class TestReplDispatch:+ def test_dispatch_slash_queues_the_prompt(self) -> None:+ main = importlib.import_module("cli.main")+ ctx = main.InteractiveContext()+ assert main._dispatch_slash("/dcf MSFT horizon=5", ctx) == 0+ assert ctx.pending_prompt is not None+ assert "Run the DCF research playbook." in ctx.pending_prompt+ assert "MSFT horizon=5" in ctx.pending_prompt++ def test_dispatch_slash_resolves_an_alias(self) -> None:+ main = importlib.import_module("cli.main")+ ctx = main.InteractiveContext()+ assert main._dispatch_slash("/peers AAPL", ctx) == 0+ assert ctx.pending_prompt is not None+ assert "Run the COMPS research playbook." in ctx.pending_prompt++ def test_bare_command_does_not_start_a_turn(self) -> None:+ main = importlib.import_module("cli.main")+ ctx = main.InteractiveContext()+ assert main._dispatch_slash("/memo", ctx) == 0+ assert ctx.pending_prompt is None+++# ---------------------------------------------------------------------------+# Playbook data integrity+# ---------------------------------------------------------------------------+++def _registered_tool_names() -> set[str]:+ """Scrape the tool ``name`` class attributes straight from ``src/tools``.++ Reads the sources instead of importing the registry so the check needs no+ optional dependency and no network, and instead of trusting any document.+ """+ pattern = re.compile(r"^\s{4}name(?:\s*:\s*str)?\s*=\s*[\"']([a-z0-9_]+)[\"']", re.M)+ found: set[str] = set()+ for path in (_AGENT_DIR / "src" / "tools").rglob("*.py"):+ found.update(pattern.findall(path.read_text(encoding="utf-8")))+ return found+++class TestPlaybookData:+ def test_slugs_are_unique_and_lowercase(self) -> None:+ slugs = [pb.slug for pb in PLAYBOOKS]+ assert len(slugs) == len(set(slugs))+ assert all(s.islower() and s.isalpha() for s in slugs)++ def test_every_playbook_has_a_full_skeleton(self) -> None:+ for pb in PLAYBOOKS:+ assert len(pb.steps) >= 5, pb.slug+ for step in pb.steps:+ assert step.title.strip() and step.inputs.strip()+ assert step.compute.strip() and step.output.strip()++ def test_every_playbook_has_a_numeric_worked_example(self) -> None:+ for pb in PLAYBOOKS:+ assert len(pb.worked_example) >= 8, pb.slug+ digits = sum(ch.isdigit() for line in pb.worked_example for ch in line)+ assert digits >= 40, pb.slug++ def test_every_playbook_asks_a_question_when_args_are_missing(self) -> None:+ for pb in PLAYBOOKS:+ assert pb.ask.strip().endswith(("?", "?)")) or "?" in pb.ask, pb.slug+ assert pb.examples++ def test_referenced_tools_are_real(self) -> None:+ registered = _registered_tool_names()+ assert "get_financial_statements" in registered # scraper sanity check+ for pb in PLAYBOOKS:+ for tool in pb.tools:+ assert tool in registered, f"{pb.slug} references unknown tool {tool}"++ def test_referenced_tools_are_real_live_classes(self) -> None:+ """Re-check the names against the LIVE tool classes, not the sources.++ The regex scraper above proves a string exists in ``src/tools``; it+ cannot prove the class is actually discovered. Anchor on the same+ discovery pass ``build_registry`` uses so a tool that stops being+ discovered fails here.+ """+ from src.tools import _discover_subclasses++ discovered = {cls.name for cls in _discover_subclasses()}+ for pb in PLAYBOOKS:+ for tool in pb.tools:+ assert tool in discovered, f"{pb.slug} references undiscovered tool {tool}"++ def test_key_gated_tools_are_covered_by_the_unavailable_tool_clause(self) -> None:+ """Some preferred tools are absent unless a key is configured.++ ``get_macro_series`` needs ``FRED_API_KEY`` and ``iwencai_search`` needs+ ``VIBE_TRADING_IWENCAI_KEY``; ``build_registry`` drops them via+ ``check_available()`` otherwise. The prompt must therefore tell the agent+ what to do when a preferred tool is missing, or the gap-filling ban has a+ hole exactly where the data is hardest to get.+ """+ from src.tools import _discover_subclasses++ by_name = {cls.name: cls for cls in _discover_subclasses()}+ gated = {+ tool+ for pb in PLAYBOOKS+ for tool in pb.tools+ if not by_name[tool].check_available()+ }+ if not gated: # every key happens to be configured in this environment+ pytest.skip("no key-gated tool referenced in this environment")+ for pb in PLAYBOOKS:+ prompt = runner.build_prompt(pb, "SUBJ")+ assert "not registered in this session" in prompt+ assert "never fill that gap from memory" in prompt++ def test_earnings_bridge_reconciles(self) -> None:+ """Recompute the ``/earnings`` walkthrough; the steps must sum to the delta.++ Guards the documented arithmetic from rotting: consensus EPS 1.35 ->+ actual EPS 1.4911, walked one variable at a time.+ """++ def eps(revenue: float, gm: float, opex: float, tax: float, shares: float) -> float:+ pbt = revenue * gm - opex - 20.0+ return pbt * (1 - tax) / shares++ base = eps(1000.0, 0.600, 400.0, 0.25, 100.0)+ after_rev = eps(1050.0, 0.600, 400.0, 0.25, 100.0)+ after_gm = eps(1050.0, 0.585, 400.0, 0.25, 100.0)+ after_opex = eps(1050.0, 0.585, 405.0, 0.25, 100.0)+ after_tax = eps(1050.0, 0.585, 405.0, 0.22, 100.0)+ final = eps(1050.0, 0.585, 405.0, 0.22, 99.0)++ assert round(base, 4) == 1.3500+ assert round(final, 4) == 1.4911+ steps = [+ after_rev - base,+ after_gm - after_rev,+ after_opex - after_gm,+ after_tax - after_opex,+ final - after_tax,+ ]+ assert [round(s, 4) for s in steps] == [0.2250, -0.1181, -0.0375, 0.0568, 0.0149]+ assert round(sum(steps), 4) == round(final - base, 4) == 0.1411+ # Operating vs non-operating split quoted in the walkthrough.+ assert round(sum(steps[:3]), 4) == 0.0694+ assert round(sum(steps[3:]), 4) == 0.0717++ text = "\n".join(PLAYBOOKS_BY_SLUG["earnings"].worked_example)+ for token in ("1.4911", "+0.1411", "+0.0694", "+0.0717"):+ assert token in text++ def test_brinson_decomposition_reconciles(self) -> None:+ """Recompute the ``/attrib`` walkthrough; A + S + I must equal active return."""+ sectors = (+ # (wp, Rp, wb, Rb)+ (0.60, 12.0, 0.50, 10.0),+ (0.30, 3.0, 0.30, 4.0),+ (0.10, -1.0, 0.20, -2.0),+ )+ rp = sum(wp * r for wp, r, _wb, _rb in sectors)+ rb = sum(wb * r for _wp, _rp, wb, r in sectors)+ assert round(rp, 2) == 8.00+ assert round(rb, 2) == 5.80++ allocation = sum((wp - wb) * (rb_i - rb) for wp, _rp, wb, rb_i in sectors)+ selection = sum(wb * (rp_i - rb_i) for _wp, rp_i, wb, rb_i in sectors)+ interaction = sum((wp - wb) * (rp_i - rb_i) for wp, rp_i, wb, rb_i in sectors)+ assert round(allocation, 3) == 1.200+ assert round(selection, 3) == 0.900+ assert round(interaction, 3) == 0.100+ assert round(allocation + selection + interaction, 3) == round(rp - rb, 3) == 2.200++ text = "\n".join(PLAYBOOKS_BY_SLUG["attrib"].worked_example)+ for token in ("+1.200", "+0.900", "+0.100", "= 2.200 = active"):+ assert token in text++ def test_comps_worked_example_reconciles(self) -> None:+ """Recompute the ``/comps`` percentile ladder and implied per-share range."""+ peers = [8.00, 9.20, 10.40, 11.60]++ def percentile(values: list[float], q: float) -> float:+ pos = (len(values) - 1) * q+ low = int(pos)+ high = min(low + 1, len(values) - 1)+ return values[low] + (pos - low) * (values[high] - values[low])++ assert round(percentile(peers, 0.25), 2) == 8.90+ assert round(percentile(peers, 0.50), 2) == 9.80+ assert round(percentile(peers, 0.75), 2) == 10.70++ ebitda, net_debt, shares, price = 800.0, 500.0, 250.0, 22.00+ assert round((5500.0 + 900.0 - 400.0) / ebitda, 2) == 7.50+ implied = [+ round((percentile(peers, q) * ebitda - net_debt) / shares, 2)+ for q in (0.25, 0.50, 0.75)+ ]+ assert implied == [26.48, 29.36, 32.24]+ assert round(7.50 / 9.80 - 1, 3) == -0.235+ assert round(29.36 / price - 1, 3) == 0.335++ text = "\n".join(PLAYBOOKS_BY_SLUG["comps"].worked_example)+ for token in ("7.50x", "9.80x", "26.48", "29.36", "32.24", "-23.5%", "+33.5%"):+ assert token in text+++# ---------------------------------------------------------------------------+# Prompt construction+# ---------------------------------------------------------------------------+++class TestPromptConstruction:+ @pytest.mark.parametrize("slug", _SLUGS)+ def test_prompt_is_self_contained(self, slug: str) -> None:+ prompt = runner.build_prompt(PLAYBOOKS_BY_SLUG[slug], "TEST-SUBJECT")+ assert "TEST-SUBJECT" in prompt+ assert "Do not skip a step" in prompt+ assert "Preferred tools:" in prompt+ assert NOT_ADVICE in prompt+ for line in GAP_POLICY:+ assert line in prompt++ def test_prompt_flags_the_example_as_illustrative(self) -> None:+ prompt = runner.build_prompt(PLAYBOOKS_BY_SLUG["dcf"], "MSFT")+ assert "illustrative teaching" in prompt+ assert "must not be reused as facts" in prompt++ def test_arg_cap_is_env_configurable(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("VIBE_TRADING_SLASH_ARG_MAX", "40")+ reloaded: Any = importlib.reload(runner)+ try:+ assert reloaded._ARG_MAX_CHARS == 40+ ctx = _Ctx()+ assert reloaded.run_playbook("comps", ctx, "y" * 200) == 0+ assert "…(truncated)" in (ctx.pending_prompt or "")+ finally:+ monkeypatch.delenv("VIBE_TRADING_SLASH_ARG_MAX", raising=False)+ importlib.reload(runner)++ def test_malformed_arg_cap_falls_back_instead_of_killing_the_repl(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """A junk override must not raise at import time.++ ``cli.main._dispatch_slash`` guards ``import_module`` with+ ``except ImportError`` only, so a ``ValueError`` from this module's body+ escapes the dispatcher and terminates the interactive loop.+ """+ monkeypatch.setenv("VIBE_TRADING_SLASH_ARG_MAX", "not-a-number")+ try:+ reloaded: Any = importlib.reload(runner)+ assert reloaded._ARG_MAX_CHARS == 600+ finally:+ monkeypatch.delenv("VIBE_TRADING_SLASH_ARG_MAX", raising=False)+ importlib.reload(runner)