Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(live): bounded-autonomy live trading channel (Robinhood Agentic Trading)

Haozhe Wu108bfae96057
diff --git a/README.md b/README.md
index 585a2c025..3c2ce0131 100644
--- a/README.md
+++ b/README.md
@@ -46,12 +46,14 @@
## 📰 News
+- **2026-05-29** 🔐 **Robinhood Agentic Trading support (opt-in, bounded autonomy)**: Adds support for Robinhood Agentic Trading (remote MCP, OAuth). Off and read-only by default; the agent acts only inside a user-committed mandate (symbols / order size / exposure / leverage / daily cap), with a filesystem-level instant kill switch, preemptive flatten, mandate auto-expiry, a full audit ledger, and a persistent autonomous runner. No custody, no venue — the broker holds funds and executes; we only relay intent. Experimental / use at your own risk.
- **2026-05-28** 🧪 **Swarm safety + strict alpha gate + worker MCP**: Swarm DAG blocks downstream tasks when upstream fails ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145)). New `run_bench_strict()` adds a same-universe random control + OOS split to catch factors that just track market beta ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143), thanks @Soli22de). Swarm workers can call operator-configured external MCP servers, with trust boundary pinned ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142), thanks @shadowinlife).
- **2026-05-27** 📊 **mootdx A-share data source + output polish**: New `mootdx` loader speaks the native 通达信 TCP protocol for A-share OHLCV (no auth, no IP rate-limit, daily + intraday with 25-page walk-back pagination), slotting between tushare and akshare in the fallback chain ([#107](https://github.com/HKUDS/Vibe-Trading/issues/107)). CCXT loader now reads `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY` so Binance/OKX public data works from restricted networks ([#126](https://github.com/HKUDS/Vibe-Trading/pull/126), thanks @ruok808). Final-answer rendering also dropped the ugly full-width `---` horizontal separators on CLI and Web: the system prompt now nudges the agent toward markdown tables and `##` headings, the CLI renderer strips standalone HRs as defense-in-depth, and the chat bubble hides any `<hr>` that slips through ([#139](https://github.com/HKUDS/Vibe-Trading/issues/139), thanks @sdwxm188).
-- **2026-05-26** ✅ **Research Goal lifecycle closure**: Goal mode now behaves like a real task runner: Web UI goal creation creates or binds the session and immediately sends the kickoff turn; active goals can be continued, edited, cancelled, and completed across Web/API/CLI/MCP; and the agent advances from the current goal snapshot (criteria, evidence, claims, open items) instead of only the original prompt. Covered-but-still-active goals now enter an audit/status update instead of stopping silently, with regression coverage across backend, CLI, MCP, and frontend events.
<details>
<summary>Earlier news</summary>
+- **2026-05-26** ✅ **Research Goal lifecycle closure**: Goal mode now behaves like a real task runner: Web UI goal creation creates or binds the session and immediately sends the kickoff turn; active goals can be continued, edited, cancelled, and completed across Web/API/CLI/MCP; and the agent advances from the current goal snapshot (criteria, evidence, claims, open items) instead of only the original prompt. Covered-but-still-active goals now enter an audit/status update instead of stopping silently, with regression coverage across backend, CLI, MCP, and frontend events.
+
- **2026-05-25** 🧼 **Cleaner chat UI + composer workflow**: The Web UI keeps chat focused on the next action: upload, swarm, and research-goal modes now live behind the composer `+` menu instead of floating panels. Active context appears above the input as compact chips, and goal details expand inline only when needed. The UI also drops the old custom i18n layer in favor of direct English copy, gates Full Report cards to report-worthy runs, and hardens local dev startup/status reporting for reliable browser smoke tests.
- **2026-05-24** 🎯 **Research Goal runtime**: Added a session-scoped Research Goal layer across backend, CLI, API/MCP, SSE, and Web UI. Goals persist claims, acceptance criteria, evidence rows, budgets, and completion policy; agent tools can create goals and attach evidence; `/goal` gives the CLI a direct entry point; REST/MCP expose goal snapshots and evidence writes; SSE keeps chat clients fresh. Follow-up audit fixes locked down verified evidence, blocked live-trading risk tiers through agent tools, wired CLI-created goals into later turns, cleaned goal ledgers on session deletion, enabled replay-all, and fixed cross-session frontend races.
- **2026-05-23** 🖥️ **Interactive CLI refresh**: The terminal front door now opens with a larger Vibe-Trading banner, a cleaner prompt divider, prior-turn recap, post-run timing, and a Claude Code-style activity rail for live agent work. Tool calls, web/data fetches, shell-style actions, Markdown answers, and pipe tables render in a more readable transcript, while piped or non-TTY runs keep plain-text output for automation. Generated CLI screenshots are now treated as local artifacts instead of committed docs files, keeping the repository lighter.
@@ -151,7 +153,7 @@
Vibe-Trading is an open-source research workspace for turning finance questions into runnable analysis. It connects natural-language prompts to market-data loaders, strategy generation, backtest engines, reports, exports, and persistent research memory.
-It is designed for research, simulation, and backtesting. It does not execute live trades.
+It is designed for research, simulation, and backtesting — and, when you choose, autonomous trading through a broker you authorize yourself (e.g. Robinhood Agentic Trading). It holds no funds and never trades outside the limits you set, and you can halt it instantly.
---
@@ -1008,7 +1010,7 @@ Recent v0.1.8 cycle contributors and credits:
## Disclaimer
-Vibe-Trading is for research, simulation, and backtesting only. It is not investment advice and it does not execute live trades. Past performance does not guarantee future results.
+Vibe-Trading is research and trading software. It is not investment advice, holds no funds, and runs no execution venue. Trading through a broker channel you explicitly authorize (e.g. Robinhood Agentic Trading) happens only within the limits you set and which you can halt at any time. This broker-trading capability is experimental and not verified by us against a real broker account — use it at your own risk. Past performance does not guarantee future results.
## License
diff --git a/README_ar.md b/README_ar.md
index aa73592fe..ccd4b3442 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -46,12 +46,14 @@
## 📰 الأخبار
+- **2026-05-29** 🔐 **دعم Robinhood Agentic Trading (اختياري، استقلالية محدودة)**: أُضيف دعم Robinhood Agentic Trading (MCP عن بُعد، OAuth). مُعطَّل وللقراءة فقط افتراضياً؛ ويتداول الوكيل تلقائياً فقط ضمن mandate يلتزم به المستخدم (الرموز / حجم الأمر / التعرّض / الرافعة / الحد اليومي)، مع kill switch فوري على مستوى الملفات، وتصفية استباقية للمراكز، وانتهاء صلاحية تلقائي لـ mandate، وسجل تدقيق كامل، و runner مستقل دائم. لا حفظ للأموال ولا تشغيل لمنصة تداول — الوسيط يحتفظ بالأموال وينفّذ، ونحن ننقل النية فقط. تجريبي / الاستخدام على مسؤوليتك.
- **2026-05-28** 🧪 **سلامة Swarm + بوّابة alpha صارمة + MCP لعمّال swarm**: يحجب Swarm DAG الآن المهام المتفرعة عندما تفشل المهمة الأعلى ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145)). دالة `run_bench_strict()` الجديدة تضيف فوق بوّابة IC تحكماً عشوائياً بنفس universe + قسمة train/test OOS لاصطياد العوامل التي تتبع beta السوق فقط ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143)، شكراً @Soli22de). يستطيع عمّال Swarm الآن استدعاء أدوات من خوادم MCP خارجية يضبطها المشغل، مع تثبيت حدود الثقة باختبارات مخصصة ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142)، شكراً @shadowinlife).
- **2026-05-27** 📊 **مصدر بيانات A-share عبر mootdx + تحسين الإخراج**: محمّل `mootdx` الجديد يتحدث بروتوكول 通达信 TCP الأصلي لبيانات OHLCV لأسهم A (بدون مصادقة، بدون قيود معدل لكل IP، يومي + intraday مع pagination تراجع بـ 25 صفحة)، ويُدرج بين tushare وakshare في سلسلة fallback ([#107](https://github.com/HKUDS/Vibe-Trading/issues/107)). محمّل CCXT يقرأ الآن `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY` ليعمل جلب بيانات Binance/OKX العامة من الشبكات المقيدة ([#126](https://github.com/HKUDS/Vibe-Trading/pull/126)، شكراً @ruok808). عرض الإجابة النهائية أزال أيضاً فواصل `---` الأفقية القبيحة بعرض كامل على CLI وWeb: يحث system prompt الآن agent على استخدام جداول markdown وعناوين `##`، يجرّد CLI renderer أسطر HR المستقلة كدفاع متعمق، ويخفي chat bubble أي `<hr>` ينفذ عبر ([#139](https://github.com/HKUDS/Vibe-Trading/issues/139)، شكراً @sdwxm188).
-- **2026-05-26** ✅ **إغلاق دورة حياة Research Goal**: أصبح Goal mode يعمل كمنفّذ مهام حقيقي: إنشاء goal من Web UI ينشئ الجلسة أو يربطها ويرسل kickoff turn فوراً؛ يمكن متابعة active goals وتعديلها وإلغاؤها وإكمالها عبر Web/API/CLI/MCP؛ ويتقدم agent loop من لقطة goal الحالية (criteria وevidence وclaims وopen items) بدلاً من الاعتماد على prompt الأصلي فقط. عندما تكون criteria covered لكن goal لا يزال active، ينتقل النظام إلى audit/status update بدلاً من التوقف الصامت، مع تغطية انحدارية عبر backend وCLI وMCP وfrontend events.
<details>
<summary>أخبار سابقة</summary>
+- **2026-05-26** ✅ **إغلاق دورة حياة Research Goal**: أصبح Goal mode يعمل كمنفّذ مهام حقيقي: إنشاء goal من Web UI ينشئ الجلسة أو يربطها ويرسل kickoff turn فوراً؛ يمكن متابعة active goals وتعديلها وإلغاؤها وإكمالها عبر Web/API/CLI/MCP؛ ويتقدم agent loop من لقطة goal الحالية (criteria وevidence وclaims وopen items) بدلاً من الاعتماد على prompt الأصلي فقط. عندما تكون criteria covered لكن goal لا يزال active، ينتقل النظام إلى audit/status update بدلاً من التوقف الصامت، مع تغطية انحدارية عبر backend وCLI وMCP وfrontend events.
+
- **2026-05-25** 🧼 **واجهة Chat أنظف + سير composer**: أصبحت واجهة Web UI تترك التركيز للمدخل التالي: انتقلت أوضاع upload وswarm وresearch-goal إلى قائمة `+` في composer بدلاً من لوحات عائمة تقاطع المحادثة. يظهر السياق النشط فوق حقل الإدخال كشرائح compact، ولا تتوسع تفاصيل goal إلا inline عند النقر على الشريحة. أزيلت طبقة i18n المخصصة القديمة لصالح نصوص إنجليزية مباشرة، وتظهر بطاقة Full Report فقط للتشغيلات ذات تقرير فعلي، كما أصبح تشغيل التطوير المحلي وتقارير الحالة أكثر ثباتاً لاختبارات browser smoke.
- **2026-05-24** 🎯 **Research Goal runtime**: أضيفت طبقة Research Goal مرتبطة بالجلسة عبر backend وCLI وAPI/MCP وSSE وWeb UI. تحفظ الأهداف claims وacceptance criteria وevidence rows وbudgets وcompletion policy؛ تستطيع agent tools إنشاء الأهداف وإضافة evidence؛ أصبح `/goal` مدخل CLI؛ تعرض REST/MCP لقطات goal وكتابات evidence؛ وتحافظ SSE على حداثة حالة chat clients. أغلقت إصلاحات audit اللاحقة مسارات verified evidence، ومنعت live-trading risk tiers عبر agent tools، وربطت goals المنشأة من CLI بالمنعطفات اللاحقة، ونظفت goal ledger عند حذف الجلسة، ووصلت replay-all، وأصلحت race في frontend snapshot بين الجلسات.
- **2026-05-23** 🖥️ **تحديث CLI التفاعلي**: تفتح واجهة الطرفية الآن ببانر Vibe-Trading أكبر، وفاصل prompt أوضح، وملخص للدورة السابقة، وتوقيت بعد التشغيل، ومسار نشاط بأسلوب Claude Code لعمل الوكيل الحي. تُعرض استدعاءات الأدوات، وجلب الويب/البيانات، وأفعال نمط shell، وإجابات Markdown، وجداول pipe كسجل أكثر قابلية للقراءة، بينما تحافظ تشغيلات pipe أو non-TTY على إخراج نصي مناسب للأتمتة. أصبحت لقطات CLI المولدة artifacts محلية بدلاً من ملفات docs ملتزم بها، مما يبقي المستودع أخف.
@@ -152,7 +154,7 @@
Vibe-Trading مساحة عمل بحثية مفتوحة المصدر تحول الأسئلة المالية إلى تحليل قابل للتشغيل. يربط المطالبات باللغة الطبيعية بمحملات بيانات السوق، وتوليد الاستراتيجيات، ومحركات الاختبار الرجعي، والتقارير، والتصدير، وذاكرة البحث الدائمة.
-صُمم للبحث والمحاكاة والاختبار الرجعي. لا ينفذ صفقات حية.
+صُمم للبحث والمحاكاة والاختبار الرجعي — وعند اختيارك، يتيح أيضاً تداولاً مستقلاً عبر وسيط تُصرّح به بنفسك (مثل Robinhood Agentic Trading). لا يحتفظ بأي أموال، ولا يتداول أبداً خارج الحدود التي تضعها، ويمكنك إيقافه فوراً.
---
@@ -917,7 +919,7 @@ Vibe-Trading جزء من نظام وكلاء **[HKUDS](https://github.com/HKUDS)
## إخلاء المسؤولية
-Vibe-Trading مخصص للبحث والمحاكاة والاختبار الرجعي فقط. ليس نصيحة استثمارية ولا ينفذ صفقات حية. الأداء السابق لا يضمن النتائج المستقبلية.
+Vibe-Trading برنامج للبحث والتداول. ليس نصيحة استثمارية، ولا يحتفظ بأي أموال، ولا يشغّل أي منصة تنفيذ. يحدث التداول فقط عبر قناة وسيط تُصرّح بها صراحةً (مثل Robinhood Agentic Trading)، ضمن الحدود التي تضعها، ويمكنك إيقافه في أي وقت. قدرة التداول عبر الوسيط هذه تجريبية ولم نتحقق منها على حساب وسيط حقيقي — استخدمها على مسؤوليتك. الأداء السابق لا يضمن النتائج المستقبلية.
## الرخصة
diff --git a/README_ja.md b/README_ja.md
index 11564f860..47541561e 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -46,12 +46,14 @@
## 📰 ニュース
+- **2026-05-29** 🔐 **Robinhood Agentic Trading 対応(オプトイン・有界自律)**: Robinhood Agentic Trading に対応しました(リモート MCP、OAuth)。デフォルトでは無効かつ読み取り専用。エージェントはユーザーがコミットした mandate(銘柄/注文サイズ/エクスポージャー/レバレッジ/日次上限)の範囲内でのみ自律取引し、ファイルレベルの即時 kill switch、先制的なポジション手仕舞い、mandate の自動失効、完全な監査台帳、永続的な自律 runner を備えます。資金の保管なし・取引所運営なし——資金の保有と執行はブローカーが行い、こちらは意図を中継するだけです。実験的 / 自己責任でご利用ください。
- **2026-05-28** 🧪 **Swarm の安全性 + 厳格 alpha gate + worker 側 MCP**: Swarm DAG は上流タスクが失敗したとき下流タスクをブロックするようになりました ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145))。新規 `run_bench_strict()` は IC gate に同 universe のランダムコントロール + train/test OOS 分割を追加し、市場 beta を追っているだけの偽 factor を捕捉します ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143), @Soli22de さんに感謝)。Swarm worker は operator が設定した外部 MCP server からツールを呼べるようになり、信頼境界は専用テストで固定されています ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142), @shadowinlife さんに感謝)。
- **2026-05-27** 📊 **mootdx A 株データソース + 出力スタイル**: 新規 `mootdx` loader はネイティブ 通达信 TCP プロトコルで A 株 OHLCV を取得します(認証不要、IP 速度制限なし、日足 + 分足の 25 ページ walk-back ページング)。fallback chain では tushare と akshare の間に配置されます ([#107](https://github.com/HKUDS/Vibe-Trading/issues/107))。CCXT loader は `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY` を読み込み、制限されたネットワークから Binance/OKX の公開データを取得できるようになりました ([#126](https://github.com/HKUDS/Vibe-Trading/pull/126), @ruok808 さんに感謝)。最終回答のレンダリングからは CLI と Web の見苦しい全幅 `---` セパレータを削除しました: system prompt は markdown table と `##` heading を促し、CLI renderer は単独 HR を defense-in-depth として除去し、chat bubble はすり抜けた `<hr>` を隠します ([#139](https://github.com/HKUDS/Vibe-Trading/issues/139), @sdwxm188 さんに感謝)。
-- **2026-05-26** ✅ **Research Goal ライフサイクルの閉ループ化**: Goal mode が実際のタスクランナーのように動くようになりました。Web UI で goal を作成すると session を作成または bind し、即座に kickoff turn を送ります。active goal は Web/API/CLI/MCP から continue/edit/cancel/complete でき、agent loop は最初の prompt だけでなく現在の goal snapshot(criteria、evidence、claims、open items)から前進します。criteria が covered でも goal が active のままなら silent stop ではなく audit/status update に入り、backend、CLI、MCP、frontend events の回帰で固定しました。
<details>
<summary>過去のニュース</summary>
+- **2026-05-26** ✅ **Research Goal ライフサイクルの閉ループ化**: Goal mode が実際のタスクランナーのように動くようになりました。Web UI で goal を作成すると session を作成または bind し、即座に kickoff turn を送ります。active goal は Web/API/CLI/MCP から continue/edit/cancel/complete でき、agent loop は最初の prompt だけでなく現在の goal snapshot(criteria、evidence、claims、open items)から前進します。criteria が covered でも goal が active のままなら silent stop ではなく audit/status update に入り、backend、CLI、MCP、frontend events の回帰で固定しました。
+
- **2026-05-25** 🧼 **よりクリーンな Chat UI + composer workflow**: Web UI は次の入力に集中できる形になりました。upload、swarm、research-goal mode は composer の `+` メニューにまとまり、floating panel で会話を邪魔しません。現在の context は input 上の compact chip として表示され、goal details は chip クリック時だけ inline 展開されます。旧 custom i18n layer も削除し、直接 English copy に統一。Full Report card は report-worthy run のみに表示され、local dev startup/status reporting もブラウザ smoke test 向けに安定化しました。
- **2026-05-24** 🎯 **Research Goal runtime**: backend、CLI、API/MCP、SSE、Web UI をまたぐ session-scoped Research Goal layer を追加しました。Goal は claim、acceptance criteria、evidence row、budget、completion policy を永続化します。agent tool は goal 作成と evidence 追加に対応し、`/goal` が CLI 入口になり、REST/MCP は goal snapshot と evidence write を公開し、SSE は chat client の状態を fresh に保ちます。後続 audit fixes では verified evidence をロックダウンし、agent tool からの live-trading risk tier をブロックし、CLI-created goal を後続 turn に接続し、session 削除時の goal ledger cleanup、replay-all 接続、frontend の cross-session snapshot race 修正を行いました。
- **2026-05-23** 🖥️ **インタラクティブ CLI の刷新**: ターミナル入口は大きな Vibe-Trading バナー、より見やすい prompt 区切り、前ターンの recap、実行後の所要時間、Claude Code 風の activity rail で live agent 作業を表示します。tool call、web/data fetch、shell 風 action、Markdown 回答、pipe table は読みやすい transcript として描画され、pipe や非 TTY 実行では自動化向けの plain-text 出力を維持します。生成 CLI スクリーンショットは committed docs ではなく local artifact として扱い、リポジトリを軽く保ちます。
@@ -152,7 +154,7 @@
Vibe-Trading は、金融に関する問いを実行可能な分析へ変換するためのオープンソースのリサーチワークスペースです。自然言語プロンプトを、市場データ loader、戦略生成、バックテストエンジン、レポート、エクスポート、永続リサーチメモリへ接続します。
-研究、シミュレーション、バックテストのために設計されています。ライブ取引は実行しません。
+研究、シミュレーション、バックテストのために設計されています——さらに、お望みであれば、ご自身が認可したブローカー(例: Robinhood Agentic Trading)を通じた自律取引も可能です。資金は一切保管せず、設定した制限を超える取引は決して行わず、いつでも即座に停止できます。
---
@@ -914,7 +916,7 @@ Vibe-Trading に貢献してくださった皆さまに感謝します。
## Disclaimer
-Vibe-Trading は研究、シミュレーション、バックテスト専用です。投資助言ではなく、ライブ取引も実行しません。過去の成績は将来の結果を保証しません。
+Vibe-Trading は研究・取引ソフトウェアです。投資助言ではなく、資金を一切保管せず、取引所も運営しません。取引はご自身が明示的に認可したブローカーチャネル(例: Robinhood Agentic Trading)を通じてのみ行われ、設定した制限の範囲内で、いつでも停止できます。このブローカー取引機能は実験的であり、当方が実際のブローカー口座で検証したものではありません——自己責任でご利用ください。過去の成績は将来の結果を保証しません。
## License
diff --git a/README_ko.md b/README_ko.md
index 644b0c473..5820f6d88 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -46,12 +46,14 @@
## 📰 뉴스
+- **2026-05-29** 🔐 **Robinhood Agentic Trading 지원(옵트인, 제한된 자율성)**: Robinhood Agentic Trading을 지원합니다(원격 MCP, OAuth). 기본적으로 비활성·읽기 전용이며, 에이전트는 사용자가 커밋한 mandate(종목/주문 규모/익스포저/레버리지/일일 한도) 범위 안에서만 자율 거래합니다. 파일 수준의 즉시 kill switch, 선제적 포지션 청산, mandate 자동 만료, 완전한 감사 원장, 영속 자율 runner를 갖췄습니다. 수탁 없음·거래소 없음 — 자금 보유와 체결은 브로커가 하고, 우리는 의도만 중계합니다. 실험적 / 사용에 따른 책임은 본인에게 있습니다.
- **2026-05-28** 🧪 **Swarm 안전성 + 엄격 alpha 게이트 + worker MCP**: Swarm DAG가 상위 태스크 실패 시 하위 태스크를 차단합니다 ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145)). 새 `run_bench_strict()`는 IC 게이트 위에 동일 universe 랜덤 컨트롤 + 학습/테스트 OOS 분할을 추가해 시장 beta만 따라가는 가짜 factor를 잡아냅니다 ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143), @Soli22de 감사). Swarm worker는 이제 operator가 설정한 외부 MCP server를 호출할 수 있으며 신뢰 경계는 전용 테스트로 고정되어 있습니다 ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142), @shadowinlife 감사).
- **2026-05-27** 📊 **mootdx A주 데이터 소스 + 출력 정리**: 새 `mootdx` loader는 네이티브 通达信 TCP 프로토콜로 A주 OHLCV를 가져옵니다(인증 불필요, IP 속도 제한 없음, 일봉 + 분봉의 25 페이지 walk-back 페이지네이션). fallback chain에서 tushare와 akshare 사이에 위치합니다 ([#107](https://github.com/HKUDS/Vibe-Trading/issues/107)). CCXT loader는 이제 `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY`를 읽어 제한된 네트워크에서 Binance/OKX 공개 데이터를 가져올 수 있습니다 ([#126](https://github.com/HKUDS/Vibe-Trading/pull/126), @ruok808 감사). 최종 답변 렌더링에서도 CLI와 Web의 보기 흉한 전체 너비 `---` 구분자를 제거했습니다: system prompt는 markdown 테이블과 `##` 헤딩 사용을 유도하고, CLI 렌더러는 독립 HR을 defense-in-depth로 제거하며, 채팅 버블은 빠져나온 `<hr>`을 숨깁니다 ([#139](https://github.com/HKUDS/Vibe-Trading/issues/139), @sdwxm188 감사).
-- **2026-05-26** ✅ **Research Goal lifecycle 폐쇄 루프**: Goal mode가 실제 task runner처럼 동작합니다. Web UI에서 goal을 만들면 session을 생성하거나 바인딩하고 즉시 kickoff turn을 보냅니다. active goal은 Web/API/CLI/MCP에서 continue/edit/cancel/complete할 수 있으며, agent loop는 최초 prompt만이 아니라 현재 goal snapshot(criteria, evidence, claims, open items)을 기준으로 진행합니다. criteria가 covered였지만 goal이 active로 남아 있으면 조용히 멈추지 않고 audit/status update로 들어가며, backend, CLI, MCP, frontend events 회귀로 고정했습니다.
<details>
<summary>이전 뉴스</summary>
+- **2026-05-26** ✅ **Research Goal lifecycle 폐쇄 루프**: Goal mode가 실제 task runner처럼 동작합니다. Web UI에서 goal을 만들면 session을 생성하거나 바인딩하고 즉시 kickoff turn을 보냅니다. active goal은 Web/API/CLI/MCP에서 continue/edit/cancel/complete할 수 있으며, agent loop는 최초 prompt만이 아니라 현재 goal snapshot(criteria, evidence, claims, open items)을 기준으로 진행합니다. criteria가 covered였지만 goal이 active로 남아 있으면 조용히 멈추지 않고 audit/status update로 들어가며, backend, CLI, MCP, frontend events 회귀로 고정했습니다.
+
- **2026-05-25** 🧼 **더 깔끔한 Chat UI + composer 워크플로**: Web UI는 이제 다음 입력에 집중하도록 정리되었습니다. upload, swarm, research-goal 모드는 composer의 `+` 메뉴 뒤로 모이고, floating panel로 채팅을 방해하지 않습니다. 현재 context는 입력창 위 compact chip으로 표시되며, goal 세부 정보는 chip을 클릭할 때만 inline으로 펼쳐집니다. 기존 custom i18n layer도 제거하고 직접 English copy로 통일했습니다. Full Report card는 report-worthy run에만 표시되며, 로컬 dev startup/status reporting도 브라우저 smoke test에 맞게 안정화했습니다.
- **2026-05-24** 🎯 **Research Goal runtime**: backend, CLI, API/MCP, SSE, Web UI 전반에 session-scoped Research Goal layer를 추가했습니다. Goal은 claim, acceptance criteria, evidence row, budget, completion policy를 영속화합니다. agent tool은 goal 생성과 evidence 추가를 지원하고, `/goal`은 CLI 진입점이 되었으며, REST/MCP는 goal snapshot과 evidence write를 노출하고, SSE는 chat client 상태를 최신으로 유지합니다. 후속 audit fixes에서는 verified evidence 경계를 잠그고, agent tool의 live-trading risk tier 입력을 차단하며, CLI-created goal을 이후 turn에 연결하고, session 삭제 시 goal ledger를 정리하고, replay-all을 연결하고, frontend cross-session snapshot race를 수정했습니다.
- **2026-05-23** 🖥️ **대화형 CLI 새 단장**: 터미널 진입점은 더 큰 Vibe-Trading 배너, 더 깔끔한 prompt 구분선, 이전 턴 요약, 실행 후 소요 시간, Claude Code 스타일 activity rail로 live agent 작업을 보여줍니다. 도구 호출, 웹/데이터 fetch, shell 스타일 동작, Markdown 답변, pipe table은 더 읽기 쉬운 transcript로 렌더링되며, pipe 또는 non-TTY 실행은 자동화에 적합한 plain-text 출력을 유지합니다. 생성된 CLI 스크린샷은 커밋되는 docs 파일이 아니라 local artifact로 처리되어 저장소를 가볍게 유지합니다.
@@ -152,7 +154,7 @@
Vibe-Trading은 금융 질문을 실행 가능한 분석으로 바꾸는 오픈소스 리서치 워크스페이스입니다. 자연어 프롬프트를 시장 데이터 로더, 전략 생성, 백테스트 엔진, 리포트, 내보내기, 영구 리서치 메모리와 연결합니다.
-리서치, 시뮬레이션, 백테스팅을 위해 설계되었습니다. 실거래는 실행하지 않습니다.
+리서치, 시뮬레이션, 백테스팅을 위해 설계되었습니다 — 그리고 원하신다면, 사용자가 직접 인가한 브로커(예: Robinhood Agentic Trading)를 통한 자율 거래도 가능합니다. 자금을 일절 보유하지 않고, 사용자가 설정한 한도를 결코 넘지 않으며, 언제든 즉시 중단할 수 있습니다.
---
@@ -917,7 +919,7 @@ Vibe-Trading에 기여해 주신 모든 분께 감사드립니다!
## 면책조항
-Vibe-Trading은 리서치, 시뮬레이션, 백테스팅 전용입니다. 투자 조언이 아니며 실거래를 실행하지 않습니다. 과거 성과가 미래 수익을 보장하지 않습니다.
+Vibe-Trading은 리서치 및 거래 소프트웨어입니다. 투자 조언이 아니며, 자금을 보유하지 않고, 거래소를 운영하지 않습니다. 거래는 사용자가 명시적으로 인가한 브로커 채널(예: Robinhood Agentic Trading)을 통해서만, 사용자가 설정한 한도 내에서 이루어지며 언제든 중단할 수 있습니다. 이 브로커 거래 기능은 실험적이며 당사가 실제 브로커 계정으로 검증하지 않았습니다 — 사용에 따른 책임은 본인에게 있습니다. 과거 성과가 미래 수익을 보장하지 않습니다.
## 라이선스
diff --git a/README_zh.md b/README_zh.md
index d995b4496..a48d1ad7c 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -46,12 +46,14 @@
## 📰 News
+- **2026-05-29** 🔐 **支持 Robinhood Agentic Trading(可选开启、有界自主)**:新增对 Robinhood Agentic Trading 的支持(远程 MCP,OAuth)。默认关闭且只读;仅在用户提交的 mandate(标的/单量/敞口/杠杆/每日笔数)内自主交易,配文件级即时 kill switch、抢占式平仓、mandate 自动过期、完整审计账本,以及一个持久自主 runner。无托管、无场所——券商持有资金并执行,我们只中继意图。实验性 / 风险自负。
- **2026-05-28** 🧪 **Swarm 安全 + 严格 alpha 门 + worker 端 MCP**:Swarm DAG 在上游任务失败时阻断下游任务([#145](https://github.com/HKUDS/Vibe-Trading/pull/145))。新增 `run_bench_strict()` 在 IC 门之上加入同 universe 随机控制 + 训练/测试 OOS 切分,识别只是跟随市场 beta 的伪因子([#143](https://github.com/HKUDS/Vibe-Trading/pull/143),感谢 @Soli22de)。Swarm worker 现在可以调用 operator 配置的外部 MCP server,信任边界由专项测试固定([#142](https://github.com/HKUDS/Vibe-Trading/pull/142),感谢 @shadowinlife)。
- **2026-05-27** 📊 **mootdx A 股数据源 + 输出排版**:新增 `mootdx` loader,走原生通达信 TCP 协议拉 A 股 OHLCV(无需 token,无 IP 速率限制,日线 + 分钟线 25 页 walk-back 分页),在 fallback chain 中位于 tushare 和 akshare 之间([#107](https://github.com/HKUDS/Vibe-Trading/issues/107))。CCXT loader 现在会读取 `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY`,使 Binance/OKX 公开数据可在受限网络下拉取([#126](https://github.com/HKUDS/Vibe-Trading/pull/126),感谢 @ruok808)。最终回答的渲染也去掉了 CLI 和 Web 上丑陋的全宽 `---` 分隔符:系统提示鼓励 agent 用 markdown 表格和 `##` 标题,CLI 渲染端兜底 strip 孤立 HR,前端 chat 气泡隐藏任何漏过去的 `<hr>`([#139](https://github.com/HKUDS/Vibe-Trading/issues/139),感谢 @sdwxm188)。
-- **2026-05-26** ✅ **Research Goal 生命周期闭环**:Goal 模式现在像真正的任务运行器:Web UI 创建 goal 会创建或绑定 session,并立刻发出 kickoff turn;active goal 可在 Web/API/CLI/MCP 中继续、编辑、取消和完成;agent loop 会按当前 goal snapshot(criteria、evidence、claims、open items)推进,而不是只按最初 prompt。criteria 已 covered 但 goal 仍 active 时,会进入 audit/status 更新,不再静默停住,并用 backend、CLI、MCP 与 frontend events 回归覆盖固定。
<details>
<summary>更早的更新</summary>
+- **2026-05-26** ✅ **Research Goal 生命周期闭环**:Goal 模式现在像真正的任务运行器:Web UI 创建 goal 会创建或绑定 session,并立刻发出 kickoff turn;active goal 可在 Web/API/CLI/MCP 中继续、编辑、取消和完成;agent loop 会按当前 goal snapshot(criteria、evidence、claims、open items)推进,而不是只按最初 prompt。criteria 已 covered 但 goal 仍 active 时,会进入 audit/status 更新,不再静默停住,并用 backend、CLI、MCP 与 frontend events 回归覆盖固定。
+
- **2026-05-25** 🧼 **更干净的 Chat UI + composer 工作流**:Web UI 现在把注意力留给下一步输入:upload、swarm 和 research-goal 模式都收进 composer 的 `+` 菜单,不再用漂浮面板打断聊天。当前上下文会以紧凑 chip 附在输入框上方,goal 详情只在点击 chip 时原地展开。UI 也移除了旧的自定义 i18n 层,改用直接英文文案;Full Report card 只在真正有报告价值的 run 出现;本地 dev 启动与状态报告也加固,方便稳定做浏览器 smoke test。
- **2026-05-24** 🎯 **Research Goal runtime**:新增 session 级 Research Goal 层,贯通 backend、CLI、API/MCP、SSE 和 Web UI。Goal 会持久化 claim、acceptance criteria、evidence row、budget 与 completion policy;agent tools 可以创建 goal 并追加 evidence;`/goal` 成为 CLI 入口;REST/MCP 暴露 goal snapshot 和 evidence 写入;SSE 保持 chat client 状态新鲜。后续审计修复锁紧 verified evidence,阻断 agent tool 写入 live-trading 风险层,串起 CLI 创建的 goal 与后续 turn,删除 session 时清理 goal ledger,接上 replay-all,并修复前端跨 session snapshot race。
- **2026-05-23** 🖥️ **交互式 CLI 刷新**:终端入口现在使用更大的 Vibe-Trading banner、更清晰的 prompt 分隔线、上一轮摘要、运行后耗时,以及 Claude Code 风格的活动轨来展示实时 agent 工作。工具调用、网页/数据抓取、shell 风格动作、Markdown 回答和管道表格都会以更易读的 transcript 渲染;pipe 或非 TTY 运行仍保留适合自动化的纯文本输出。生成的 CLI 截图现在作为本地 artifact 处理,不再提交进 docs,让仓库更轻。
@@ -151,7 +153,7 @@
Vibe-Trading 是一个开源研究工作台,用于把金融问题转化为可运行的分析。它将自然语言提示连接到市场数据加载器、策略生成、回测引擎、报告、导出和持久研究记忆。
-它面向研究、模拟和回测,不执行实盘交易。
+它面向研究、模拟和回测——并且在你选择时,可通过你自己授权的券商(如 Robinhood Agentic Trading)进行自主交易。它不托管任何资金,绝不超出你设定的限额交易,且你可随时一键停止。
---
@@ -913,7 +915,7 @@ Vibe-Trading 是 **[HKUDS](https://github.com/HKUDS)** 智能体生态的一部
## Disclaimer
-Vibe-Trading 仅用于研究、模拟和回测。它不是投资建议,也不会执行实盘交易。历史表现不代表未来结果。
+Vibe-Trading 是研究与交易软件。它不是投资建议,不托管任何资金,也不运营执行场所。仅通过你自己明确授权的券商通道(如 Robinhood Agentic Trading)进行交易,且只在你设定的限额内、你可随时停止。该券商交易能力为实验性,未经我们对接真实券商账户验证——风险自负。历史表现不代表未来结果。
## License
diff --git a/agent/api_server.py b/agent/api_server.py
index 50ba2bb97..eaddfeba5 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -50,6 +50,10 @@ _UPLOAD_CHUNK_SIZE = 1024 * 1024 # 1 MB
# Rich console for colored logs
console = Console()
+import logging
+
+logger = logging.getLogger(__name__)
+
# ============================================================================
# Pydantic Models
@@ -338,6 +342,121 @@ class UpdateGoalResponse(BaseModel):
snapshot: GoalSnapshotResponse
+# ---- Live trading channel: consent commit + kill switch ----
+
+
+class CommitMandateRequest(BaseModel):
+ """Surface-originated mandate commit (Consent §1 / §3).
+
+ This is the ONLY write path that activates a live-trading mandate. It is a
+ privileged HTTP action the user surface sends on an explicit click/keypress
+ — NOT a tool the agent model can call. ``consent_ack`` MUST be ``true``.
+ """
+
+ broker: str = Field(..., min_length=1, max_length=64)
+ proposal_id: str = Field(..., min_length=1, max_length=128)
+ selected_ordinal: int = Field(..., ge=1, le=10)
+ adjustments: Optional[Dict[str, Any]] = None
+ consent_ack: bool = Field(..., description="Explicit affirmative; must be true")
+ session_id: Optional[str] = None
+ account_ref: str = Field("", max_length=128)
+ lifetime_days: int = Field(30, ge=1, le=365)
+
+
+class LiveHaltRequest(BaseModel):
+ """Trip or clear the live kill switch (Consent §4).
+
+ Tripping/clearing is a privileged surface action, never an agent tool. When
+ ``broker`` is omitted the GLOBAL switch is used (halts every broker).
+ """
+
+ broker: Optional[str] = Field(None, max_length=64)
+ reason: str = Field("user requested halt", max_length=500)
+ session_id: Optional[str] = None
+
+
+class LiveAuthorizeRequest(BaseModel):
+ """Kick off (or describe) the OAuth bootstrap for a live broker (C2).
+
+ Vibe-Trading never holds funds and never operates a venue, so the OAuth
+ bootstrap runs through the broker's own user-authorized device flow on the
+ client (CLI / desktop MCP), not a server-side redirect. This endpoint is the
+ web on-ramp: it tells a Web UI user exactly how to discover/start the flow.
+ """
+
+ broker: str = Field(..., min_length=1, max_length=64)
+
+
+class LiveRunnerControlRequest(BaseModel):
+ """Start or stop the persistent live runner for one broker (SPEC §7.5).
+
+ The runner wakes on schedule/market events and trades autonomously inside a
+ committed mandate. Starting it is a privileged surface action, never an
+ agent tool. A committed, unexpired mandate must already exist.
+ """
+
+ broker: str = Field(..., min_length=1, max_length=64)
+ session_id: Optional[str] = None
+
+
+class BrokerAuthState(BaseModel):
+ """Per-broker authorization snapshot for ``GET /live/status``."""
+
+ broker: str
+ oauth_token_present: bool = Field(..., description="Whether an OAuth token cache exists")
+ is_live_broker: bool = Field(..., description="Whether this key is a recognized live broker")
+
+
+class MandateLimits(BaseModel):
+ """Flattened active-mandate limits surfaced to the UI (Mandate layer a/b)."""
+
+ max_order_notional_usd: float
+ max_total_exposure_usd: float
+ max_leverage: float
+ max_trades_per_day: int
+ allowed_instruments: List[str]
+ account_funding_usd: float
+
+
+class ActiveMandateState(BaseModel):
+ """Active-mandate snapshot with the expiry countdown (SPEC §9 dec. 2)."""
+
+ broker: str
+ account_ref: str
+ created_at: str
+ expires_at: str
+ expires_in_seconds: Optional[int] = Field(
+ None, description="Seconds until expiry; negative when already expired"
+ )
+ expired: bool
+ limits: MandateLimits
+
+
+class RunnerLivenessState(BaseModel):
+ """Runner liveness snapshot via the §7.5 liveness contract."""
+
+ broker: str
+ alive: bool
+ last_tick: Optional[float] = Field(None, description="Unix epoch of last heartbeat tick")
+ last_tick_age_seconds: Optional[float] = None
+
+
+class LiveBrokerStatus(BaseModel):
+ """Combined live-channel status for a single broker."""
+
+ auth: BrokerAuthState
+ mandate: Optional[ActiveMandateState] = None
+ runner: RunnerLivenessState
+ halted: bool = Field(..., description="Per-broker OR global kill switch is tripped")
+
+
+class LiveStatusResponse(BaseModel):
+ """Top-level live-channel status (C2)."""
+
+ global_halted: bool = Field(..., description="Whether the GLOBAL kill switch is tripped")
+ brokers: List[LiveBrokerStatus]
+
+
# ============================================================================
# FastAPI Application
@@ -1854,6 +1973,12 @@ async def session_events(
if await request.is_disconnected():
break
yield event.to_sse()
+ relayed = _mandate_proposal_frame_from_tool_result(event)
+ if relayed is not None:
+ yield relayed
+ live_action = _live_action_frame_from_tool_result(event)
+ if live_action is not None:
+ yield live_action
return StreamingResponse(
event_generator(),
@@ -2115,6 +2240,747 @@ async def cancel_swarm_run(run_id: str):
return {"status": "cancelled"}
+# ============================================================================
+# Live trading channel — consent commit + kill switch
+# ============================================================================
+#
+# These are the privileged SURFACE actions of the live-trading channel
+# (docs/live-trading/SPEC.md, Consent §1/§3/§4). None is an agent tool:
+# - POST /mandate/commit -> the single mandate writer (commit_mandate)
+# - POST /live/halt -> trip the kill switch (P5 trip_halt)
+# - POST /live/resume -> clear the kill switch (P5 clear_halt)
+# Each best-effort relays a mandate.committed / live.halted / live.action event
+# through the EXISTING session EventBus, so the frontend's already-wired
+# /sessions/{id}/events SSE stream reflects the state change. No new bus.
+
+
+def _emit_live_event(session_id: Optional[str], event_type: str, data: Dict[str, Any]) -> None:
+ """Best-effort relay of a live-channel event through the existing bus.
+
+ The event flows out the existing ``/sessions/{session_id}/events`` SSE
+ stream. Notifications never gate autonomy (SPEC Consent §5): a relay failure
+ or a missing session is swallowed — the state change already happened on disk.
+
+ Args:
+ session_id: Target session, or ``None`` to skip relay.
+ event_type: SSE event name (``mandate.committed`` / ``live.halted`` /
+ ``live.resumed`` / ``live.action``).
+ data: JSON-serializable event payload.
+ """
+ if not session_id:
+ return
+ try:
+ svc = _get_session_service()
+ if svc and svc.get_session(session_id):
+ svc.event_bus.emit(session_id, event_type, data)
+ except Exception: # pragma: no cover - relay is non-blocking by contract
+ logger.debug("live event relay failed for %s/%s", session_id, event_type, exc_info=True)
+
+
+# ---- C1: propose_mandate_profiles tool_result -> mandate.proposal SSE frame ----
+#
+# The agent surfaces a proposal by calling the read-only ``propose_mandate_profiles``
+# tool whose tool_result JSON body is ``{"type":"mandate.proposal", ...}`` (SPEC
+# Consent §1). The CLI / frontend listen for a TOP-LEVEL ``mandate.proposal`` SSE
+# event. ``src/agent/loop.py`` only emits a truncated ``tool_result`` event
+# (``preview = result[:200]``) and is PROTECTED — we do NOT edit it. Instead this
+# open-file SSE seam (TASKS "Remaining integration items" #1, the recommended
+# wiring) detects the propose tool's tool_result on the stream, recovers the
+# ``proposal_id`` from the preview, reloads the FULL persisted proposal from the
+# proposal store (written by the tool before it returned), and emits the
+# ``mandate.proposal`` frame. No protected touch.
+
+_PROPOSAL_TOOL_NAME = "propose_mandate_profiles"
+_PROPOSAL_ID_RE = re.compile(r'"proposal_id"\s*:\s*"(mp_[0-9a-zA-Z]+)"')
+
+
+def _load_full_proposal(proposal_id: str) -> Optional[Dict[str, Any]]:
+ """Reload a persisted ``mandate.proposal`` payload by id, broker-agnostic.
+
+ The propose tool persists the full proposal under
+ ``<runtime_root>/live/<broker>/proposals/<proposal_id>.json`` before
+ returning. The SSE ``tool_result`` preview is too short to carry the full
+ body, so the relay reloads it from disk. The broker segment is unknown from
+ the preview alone, so every broker's proposals directory is searched.
+
+ Args:
+ proposal_id: The ``mp_...`` id parsed from the tool_result preview.
+
+ Returns:
+ The full proposal dict, or ``None`` when not found / unreadable.
+ """
+ try:
+ from src.live.paths import live_root
+
+ for proposal_path in live_root().glob(f"*/proposals/{proposal_id}.json"):
+ try:
+ data = json.loads(proposal_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ if isinstance(data, dict) and data.get("type") == "mandate.proposal":
+ return data
+ except Exception: # pragma: no cover - relay must never break the stream
+ logger.debug("mandate.proposal reload failed for %s", proposal_id, exc_info=True)
+ return None
+
+
+def _mandate_proposal_frame_from_tool_result(event: Any) -> Optional[str]:
+ """Build a ``mandate.proposal`` SSE frame from a propose-tool tool_result.
+
+ Args:
+ event: An ``SSEEvent`` flowing through the session stream.
+
+ Returns:
+ A ready-to-yield SSE text frame for the ``mandate.proposal`` event, or
+ ``None`` when ``event`` is not a successful propose-tool result or the
+ proposal cannot be recovered.
+ """
+ data = getattr(event, "data", None)
+ if getattr(event, "event_type", None) != "tool_result" or not isinstance(data, dict):
+ return None
+ if data.get("tool") != _PROPOSAL_TOOL_NAME or data.get("status") != "ok":
+ return None
+ match = _PROPOSAL_ID_RE.search(str(data.get("preview") or ""))
+ if not match:
+ return None
+ proposal = _load_full_proposal(match.group(1))
+ if proposal is None:
+ return None
+
+ from src.session.events import SSEEvent
+
+ frame = SSEEvent(
+ event_type="mandate.proposal",
+ data=proposal,
+ session_id=getattr(event, "session_id", "") or "",
+ )
+ return frame.to_sse()
+
+
+_LIVE_ACTION_ID_RE = re.compile(r'"audit_id"\s*:\s*"(la_[0-9a-zA-Z]+)"')
+
+
+def _load_live_action_record(audit_id: str) -> Optional[Dict[str, Any]]:
+ """Reload a redacted live-action record from the ledger by ``audit_id``.
+
+ The order guard embeds its (already-redacted) audit record under the
+ ``live_action`` key of its tool_result, but the SSE ``tool_result`` preview
+ is truncated to ~200 chars, so the full record is reloaded from the
+ append-only ledger at ``<runtime_root>/live/audit.jsonl``.
+
+ Args:
+ audit_id: The ``la_...`` id parsed from the tool_result preview.
+
+ Returns:
+ The full redacted live-action record, or ``None`` when not found.
+ """
+ try:
+ from src.live.paths import live_root
+
+ ledger = live_root() / "audit.jsonl"
+ if not ledger.exists():
+ return None
+ for line in reversed(ledger.read_text(encoding="utf-8").splitlines()):
+ if audit_id not in line:
+ continue
+ try:
+ record = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(record, dict) and record.get("audit_id") == audit_id:
+ return record
+ except Exception: # pragma: no cover - relay must never break the stream
+ logger.debug("live.action reload failed for %s", audit_id, exc_info=True)
+ return None
+
+
+def _live_action_frame_from_tool_result(event: Any) -> Optional[str]:
+ """Build a ``live.action`` SSE frame from an order-guard tool_result.
+
+ The order guard stamps a ``live_action`` audit record onto its tool_result
+ (and the ledger) for every live order placed/rejected. The interactive agent
+ loop only emits a truncated ``tool_result`` event and is PROTECTED, so this
+ open-file relay surfaces the live action as a top-level ``live.action`` event
+ for the timeline — without touching ``src/agent/loop.py``. (Autonomous-runner
+ actions already emit ``live.action`` natively via the runner's event bus.)
+
+ Args:
+ event: An ``SSEEvent`` flowing through the session stream.
+
+ Returns:
+ A ready-to-yield ``live.action`` SSE frame, or ``None`` when the event is
+ not an order-guard result carrying a recoverable live-action record.
+ """
+ data = getattr(event, "data", None)
+ if getattr(event, "event_type", None) != "tool_result" or not isinstance(data, dict):
+ return None
+ preview = str(data.get("preview") or "")
+ if '"live_action"' not in preview:
+ return None
+ match = _LIVE_ACTION_ID_RE.search(preview)
+ if not match:
+ return None
+ record = _load_live_action_record(match.group(1))
+ if record is None:
+ return None
+
+ from src.session.events import SSEEvent
+
+ frame = SSEEvent(
+ event_type="live.action",
+ data=record,
+ session_id=getattr(event, "session_id", "") or "",
+ )
+ return frame.to_sse()
+
+
+def _fetch_broker_ceilings(broker: str) -> Optional[Dict[str, Any]]:
+ """Best-effort fetch of broker-side account ceilings for the commit re-check.
+
+ Reads the broker's ``get_account`` tool and derives an authoritative ceiling
+ snapshot (buying power / funding) so the commit-time fit check binds to the
+ venue's real limits rather than an agent-proposed number. Returns ``None`` on
+ any failure (channel not configured, tool error, fields not recognized) so
+ the caller falls back to the proposal's own snapshot — a commit is never
+ blocked on a broker read. The exact Robinhood field names are finalized
+ post-access (L6); we probe the common ones.
+
+ Args:
+ broker: The live-broker key.
+
+ Returns:
+ A ceilings dict (canonical keys) or ``None`` to fall back.
+ """
+ try:
+ adapter = _live_broker_adapter(broker)
+ except LiveRunnerUnavailable:
+ return None
+ try:
+ result = adapter.call_tool("get_account", {})
+ except Exception: # pragma: no cover - status/commit must never raise here
+ logger.debug("broker ceiling fetch failed for %s", broker, exc_info=True)
+ return None
+ if not isinstance(result, dict) or result.get("status") == "error":
+ return None
+ payload = result.get("result") if isinstance(result.get("result"), dict) else result
+ funding: Optional[float] = None
+ for key in ("account_funding_usd", "buying_power", "cash", "portfolio_value", "equity"):
+ raw = payload.get(key) if isinstance(payload, dict) else None
+ try:
+ if raw is not None:
+ funding = float(raw)
+ break
+ except (TypeError, ValueError):
+ continue
+ if funding is None or funding <= 0:
+ return None
+ # A single order can never exceed available funding; total exposure is capped
+ # at funding for a cash account. Leverage stays at 1.0 unless the broker
+ # reports margin (L6). These canonical keys are normalized by commit_mandate.
+ return {
+ "account_funding_usd": funding,
+ "max_order_notional_usd": funding,
+ "max_total_exposure_usd": funding,
+ }
+
+
[email protected]("/mandate/commit", dependencies=[Depends(require_auth)])
+async def commit_mandate_endpoint(payload: CommitMandateRequest):
+ """Commit a user-selected mandate profile — the only mandate write path.
+
+ Calls :func:`src.live.mandate.commit.commit_mandate`, which re-validates the
+ proposal is live and the resolved profile still fits the ceilings the user
+ saw. Requires ``consent_ack=true`` (rejected otherwise). On success emits a
+ ``mandate.committed`` + ``live.action`` event so all surfaces reflect the
+ newly active mandate.
+ """
+ if payload.consent_ack is not True:
+ raise HTTPException(status_code=400, detail="consent_ack must be true to commit a mandate")
+
+ from src.live.mandate.commit import CommitError, commit_mandate
+
+ # Prefer broker-DERIVED ceilings over the agent-supplied proposal snapshot:
+ # the commit re-check should bind to the venue's real account limits, not a
+ # number the model proposed. Best-effort — falls back to the proposal's own
+ # ceilings (commit_mandate handles ceilings_ref=None) when the broker channel
+ # is unavailable or the read fails (we never block a commit on a broker read).
+ broker_ceilings = _fetch_broker_ceilings(payload.broker)
+
+ try:
+ result = commit_mandate(
+ proposal_id=payload.proposal_id,
+ ordinal=payload.selected_ordinal,
+ adjustments=payload.adjustments,
+ consent_ack=payload.consent_ack,
+ broker=payload.broker,
+ account_ref=payload.account_ref,
+ session_id=payload.session_id,
+ ceilings_ref=broker_ceilings,
+ lifetime_days=payload.lifetime_days,
+ )
+ except CommitError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ _emit_live_event(payload.session_id, "mandate.committed", result)
+ _emit_live_event(
+ payload.session_id,
+ "live.action",
+ {"kind": "mandate_committed", "broker": result["broker"], "mandate_id": result["mandate_id"]},
+ )
+ return result
+
+
[email protected]("/live/halt", dependencies=[Depends(require_auth)])
+async def halt_live_endpoint(payload: LiveHaltRequest):
+ """Trip the live kill switch (privileged surface action, Consent §4).
+
+ Writes the HALT sentinel via :func:`src.live.halt.trip_halt`; the
+ enforcement gate then rejects every order attempt until resumed. Emits a
+ ``live.halted`` event so all surfaces reflect the halted state.
+ """
+ from src.live.halt import trip_halt
+
+ try:
+ path = trip_halt(by="frontend", reason=payload.reason, broker=payload.broker)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ result = {"halted": True, "broker": payload.broker, "reason": payload.reason, "sentinel": str(path)}
+ _emit_live_event(payload.session_id, "live.halted", result)
+ _emit_live_event(
+ payload.session_id,
+ "live.action",
+ {"kind": "halt_tripped", "broker": payload.broker, "reason": payload.reason},
+ )
+ return result
+
+
[email protected]("/live/resume", dependencies=[Depends(require_auth)])
+async def resume_live_endpoint(payload: LiveHaltRequest):
+ """Clear the live kill switch (privileged surface action, Consent §4).
+
+ Deletes the HALT sentinel via :func:`src.live.halt.clear_halt` (an explicit
+ re-enable; never an agent tool). Emits a ``live.resumed`` event.
+ """
+ from src.live.halt import clear_halt
+
+ try:
+ cleared = clear_halt(broker=payload.broker)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ result = {"halted": False, "broker": payload.broker, "cleared": cleared}
+ _emit_live_event(payload.session_id, "live.resumed", result)
+ _emit_live_event(
+ payload.session_id,
+ "live.action",
+ {"kind": "halt_cleared", "broker": payload.broker, "cleared": cleared},
+ )
+ return result
+
+
+# ============================================================================
+# Live trading channel — status, authorize on-ramp, runner control (C2 + §7.5)
+# ============================================================================
+#
+# C2 surfaces the dormant-by-default channel state so a user can SEE what is and
+# is not authorized before trusting it: per-broker OAuth presence, the active
+# mandate with its expiry countdown, runner liveness, and the kill-switch state.
+# The runner-control endpoints start/stop the persistent §7.5 runner that trades
+# autonomously inside a committed mandate. None of these is an agent tool; they
+# are privileged surface actions like /mandate/commit and /live/halt.
+
+
+def _known_live_brokers() -> List[str]:
+ """Return the recognized live-broker keys (SPEC §7.2)."""
+ from src.config.schema import LIVE_BROKER_SERVER_KEYS
+
+ return sorted(LIVE_BROKER_SERVER_KEYS)
+
+
+def _oauth_token_present(broker: str) -> bool:
+ """Return whether an OAuth token cache exists for a broker (C2 auth state).
+
+ The token cache lives at ``<runtime_root>/live/<broker>/oauth/`` (0700) and
+ is created only when the user OAuth-authorizes the channel. A missing or
+ empty directory means the channel is dormant (read-only, no live path).
+ """
+ try:
+ from src.live.paths import broker_dir
+
+ oauth_dir = broker_dir(broker) / "oauth"
+ return oauth_dir.is_dir() and any(oauth_dir.iterdir())
+ except Exception: # pragma: no cover - status must never raise
+ logger.debug("oauth presence check failed for %s", broker, exc_info=True)
+ return False
+
+
+def _active_mandate_state(broker: str) -> Optional[ActiveMandateState]:
+ """Build the active-mandate snapshot for a broker, or ``None`` when absent.
+
+ Reads the committed mandate via the frozen store contract and computes the
+ ``expires_at`` countdown (SPEC §9 dec. 2). A mandate whose ``expires_at`` has
+ passed is still surfaced, flagged ``expired`` so the UI can prompt re-consent.
+ """
+ from src.live.mandate.store import load_mandate
+
+ mandate = load_mandate(broker)
+ if mandate is None:
+ return None
+
+ consent = mandate.consent
+ caps = mandate.hard_caps
+ expires_in: Optional[int] = None
+ expired = False
+ try:
+ expires_dt = datetime.fromisoformat(consent.expires_at.replace("Z", "+00:00"))
+ from datetime import timezone
+
+ now = datetime.now(timezone.utc)
+ if expires_dt.tzinfo is None:
+ expires_dt = expires_dt.replace(tzinfo=timezone.utc)
+ delta = expires_dt - now
+ expires_in = int(delta.total_seconds())
+ expired = expires_in <= 0
+ except (ValueError, AttributeError):
+ logger.debug("could not parse expires_at for %s mandate", broker, exc_info=True)
+
+ return ActiveMandateState(
+ broker=broker,
+ account_ref=consent.account_ref,
+ created_at=consent.created_at,
+ expires_at=consent.expires_at,
+ expires_in_seconds=expires_in,
+ expired=expired,
+ limits=MandateLimits(
+ max_order_notional_usd=caps.max_order_notional_usd,
+ max_total_exposure_usd=caps.max_total_exposure_usd,
+ max_leverage=caps.max_leverage,
+ max_trades_per_day=caps.max_trades_per_day,
+ allowed_instruments=[str(getattr(i, "value", i)) for i in caps.allowed_instruments],
+ account_funding_usd=caps.account_funding_usd,
+ ),
+ )
+
+
+def _runner_liveness_state(broker: str) -> RunnerLivenessState:
+ """Build the runner-liveness snapshot for a broker (SPEC §7.5 contract).
+
+ Uses the §7.5 ``liveness`` module (``is_runner_alive`` / ``last_tick``),
+ keyed by broker as the runner id. The module is built concurrently (R1); a
+ missing module or any error is treated as "not alive" (fail-safe display).
+ """
+ alive = False
+ tick: Optional[float] = None
+ age: Optional[float] = None
+ try:
+ from src.live.runtime import liveness
+
+ alive = bool(liveness.is_runner_alive(broker))
+ raw_tick = liveness.last_tick(broker)
+ if raw_tick is not None:
+ tick = float(raw_tick)
+ age = max(0.0, time.time() - tick)
+ except Exception: # pragma: no cover - liveness module is built concurrently
+ logger.debug("runner liveness lookup failed for %s", broker, exc_info=True)
+
+ return RunnerLivenessState(broker=broker, alive=alive, last_tick=tick, last_tick_age_seconds=age)
+
+
[email protected]("/live/status", response_model=LiveStatusResponse, dependencies=[Depends(require_auth)])
+async def live_status_endpoint(broker: Optional[str] = Query(None, max_length=64)):
+ """Return live-channel status: auth, active mandate, runner liveness, halt (C2).
+
+ Args:
+ broker: Optional single-broker filter. When omitted, every recognized
+ live broker is reported.
+
+ Returns:
+ A :class:`LiveStatusResponse` with the global kill-switch state and a
+ per-broker breakdown so the UI can show exactly what is authorized.
+ """
+ from src.live.halt import halt_flag_set
+
+ if broker is not None:
+ target = broker.strip().lower()
+ if not target:
+ raise HTTPException(status_code=400, detail="broker must not be blank")
+ brokers = [target]
+ else:
+ brokers = _known_live_brokers()
+
+ known = set(_known_live_brokers())
+ statuses: List[LiveBrokerStatus] = []
+ for key in brokers:
+ statuses.append(
+ LiveBrokerStatus(
+ auth=BrokerAuthState(
+ broker=key,
+ oauth_token_present=_oauth_token_present(key),
+ is_live_broker=key in known,
+ ),
+ mandate=_active_mandate_state(key),
+ runner=_runner_liveness_state(key),
+ halted=halt_flag_set(broker=key),
+ )
+ )
+
+ return LiveStatusResponse(global_halted=halt_flag_set(broker=None), brokers=statuses)
+
+
[email protected]("/live/authorize", dependencies=[Depends(require_auth)])
+async def live_authorize_endpoint(payload: LiveAuthorizeRequest):
+ """Describe the OAuth bootstrap on-ramp for a live broker (C2 web on-ramp).
+
+ Vibe-Trading holds no funds and runs no venue: the OAuth flow happens on the
+ broker's own user-authorized device channel (CLI / desktop MCP), never a
+ server-side redirect. A Web UI user reaches this endpoint to DISCOVER how to
+ start the flow. It performs no authorization itself and never returns a token.
+ """
+ broker = payload.broker.strip().lower()
+ if not broker:
+ raise HTTPException(status_code=400, detail="broker must not be blank")
+ if broker not in set(_known_live_brokers()):
+ raise HTTPException(status_code=400, detail=f"unknown live broker: {broker}")
+
+ return {
+ "broker": broker,
+ "oauth_token_present": _oauth_token_present(broker),
+ "instruction": (
+ f"Run `vibe-trading live authorize {broker}` from the device that will "
+ "hold the broker session. This opens the broker's own OAuth consent flow; "
+ "Vibe-Trading never holds funds and only relays intent once you authorize."
+ ),
+ "note": (
+ "The live channel stays read-only until the OAuth token is present AND a "
+ "mandate is committed AND order tools are explicitly enabled."
+ ),
+ }
+
+
+# ---- Runner control (SPEC §7.5): start / stop the persistent live runner ----
+#
+# A LiveRunner (R2 contract: ``LiveRunner(broker)`` with ``run_loop()`` /
+# ``run_once()``) is driven in a background task per broker. The factory is
+# injectable (``_runner_factory``) so tests stub it with no real agent/broker.
+# ``run_loop`` may be sync (long-blocking) or async; both are supported.
+
+_runner_tasks: Dict[str, "asyncio.Task[Any]"] = {}
+_runner_factory: Optional[Any] = None
+
+
+class LiveRunnerUnavailable(RuntimeError):
+ """Raised when a live runner cannot be wired (broker not configured/authorized).
+
+ Distinct from a programming error so the start endpoint can map it to a 503
+ rather than a 500: the runtime is fine, the broker channel just isn't ready.
+ """
+
+
+def _live_broker_adapter(broker: str) -> Any:
+ """Build an ``MCPServerAdapter`` for a live broker from the user-side config.
+
+ Resolves the broker's MCP server entry by config key OR by a live-broker URL
+ host (so an aliased key still resolves), mirroring the registry's detection.
+
+ Args:
+ broker: The live-broker key, e.g. ``"robinhood"``.
+
+ Returns:
+ A constructed :class:`MCPServerAdapter` for the broker's read/write tools.
+
+ Raises:
+ LiveRunnerUnavailable: When no MCP server is configured for the broker.
+ """
+ from src.config.loader import load_agent_config
+ from src.tools.mcp import MCPServerAdapter
+
+ try:
+ from src.config.schema import is_live_broker_entry
+ except Exception: # pragma: no cover - older schema without URL detection
+ is_live_broker_entry = None # type: ignore[assignment]
+
+ cfg = load_agent_config()
+ servers = getattr(cfg, "mcp_servers", {}) or {}
+ for name, server_cfg in servers.items():
+ is_match = name == broker
+ if not is_match and is_live_broker_entry is not None and broker == "robinhood":
+ try:
+ is_match = is_live_broker_entry(name, server_cfg)
+ except Exception: # pragma: no cover
+ is_match = False
+ if is_match:
+ return MCPServerAdapter(name, server_cfg)
+ raise LiveRunnerUnavailable(f"no MCP server configured for live broker {broker!r}")
+
+
+def _build_live_runner(broker: str) -> Any:
+ """Construct a fully-wired ``LiveRunner`` for a broker (SPEC §7.5 R-INT).
+
+ Wires the runner to the real surfaces — the public ``SessionService`` agent
+ caller (never the protected loop internals), the broker's READ/WRITE MCP
+ tools, the R4 reconciler, the R1 scheduler, and R3 market-hours triggers —
+ and injects an audit ``event_callback`` so every autonomous live action is
+ broadcast as a ``live.action`` SSE event on the runner's session bus.
+
+ Args:
+ broker: The live-broker key.
+
+ Returns:
+ A runner object exposing ``run_loop`` / ``run_once`` (R2 contract).
+
+ Raises:
+ LiveRunnerUnavailable: When the broker channel is not configured.
+ """
+ if _runner_factory is not None:
+ return _runner_factory(broker)
+
+ from functools import partial
+
+ from src.live.audit import write_live_action
+ from src.live.runtime.reconcile import reconcile
+ from src.live.runtime.runner import LiveRunner
+ from src.live.runtime.scheduler import Scheduler
+ from src.live.runtime.triggers import Trigger
+
+ adapter = _live_broker_adapter(broker) # raises LiveRunnerUnavailable if absent
+
+ def _read(remote_tool: str):
+ """A zero-arg broker READ callable bound to one remote tool."""
+ return lambda: adapter.call_tool(remote_tool, {})
+
+ def _submit(order: Dict[str, Any]) -> Dict[str, Any]:
+ # Route the flatten sweep's normalized order to the broker's write tools.
+ # Field mapping against the real Robinhood schema is finalized post-access
+ # (L6); the action discriminator is broker-agnostic.
+ if order.get("action") == "cancel":
+ return adapter.call_tool("cancel_order", order)
+ return adapter.call_tool("place_order", order)
+
+ svc = _get_session_service()
+ session = svc.create_session(title=f"live-runner:{broker}")
+ session_id = session.session_id
+
+ async def _agent_caller(sid: str, prompt: str) -> Dict[str, Any]:
+ # Dispatch one autonomous turn through the PUBLIC SessionService entry.
+ # The agent then trades within the mandate via the gated order tools.
+ return await svc.send_message(sid, prompt)
+
+ def _audit_with_bus(event: Any) -> Dict[str, Any]:
+ # Broadcast each live action as a live.action SSE event on the runner's
+ # session bus (no protected-loop touch — the runner owns its session).
+ return write_live_action(
+ event,
+ event_callback=lambda etype, record: svc.event_bus.emit(session_id, etype, record),
+ )
+
+ # Wire the scheduler's fire callback to the runner's tick. The scheduler is
+ # constructed before the runner (it needs on_fire), and the runner needs the
+ # scheduler, so late-bind via a holder to break the cycle.
+ runner_holder: Dict[str, Any] = {}
+
+ async def _on_fire(_job: Any) -> None:
+ runner = runner_holder.get("runner")
+ if runner is not None:
+ await runner.run_once()
+
+ scheduler = Scheduler(_on_fire)
+
+ runner = LiveRunner(
+ broker,
+ agent_caller=_agent_caller,
+ reconcile_fn=reconcile,
+ read_positions=_read("get_positions"),
+ read_balance=_read("get_account"),
+ read_open_orders=_read("list_orders"),
+ submit_fn=_submit,
+ write_audit_fn=_audit_with_bus,
+ scheduler=scheduler,
+ triggers=[Trigger.market("us_equity")],
+ session_id=session_id,
+ )
+ runner_holder["runner"] = runner
+ return runner
+
+
+async def _drive_runner(runner: Any) -> None:
+ """Run a runner's ``run_loop`` to completion, sync or async.
+
+ A synchronous ``run_loop`` is offloaded to a worker thread so it does not
+ block the event loop; an async ``run_loop`` is awaited directly.
+ """
+ result = runner.run_loop()
+ if asyncio.iscoroutine(result):
+ await result
+ else:
+ await asyncio.get_running_loop().run_in_executor(None, lambda: result)
+
+
[email protected]("/live/runner/start", dependencies=[Depends(require_auth)])
+async def start_runner_endpoint(payload: LiveRunnerControlRequest):
+ """Start the persistent live runner for a broker (SPEC §7.5).
+
+ Refuses to start unless a committed, unexpired mandate exists and the kill
+ switch is clear — the runner trades autonomously, so it must not start into a
+ dead/halted channel. Idempotent: a request for an already-running broker
+ returns ``already_running`` without spawning a second task.
+ """
+ from src.live.halt import halt_flag_set
+
+ broker = payload.broker.strip().lower()
+ if not broker:
+ raise HTTPException(status_code=400, detail="broker must not be blank")
+
+ existing = _runner_tasks.get(broker)
+ if existing is not None and not existing.done():
+ return {"broker": broker, "started": False, "already_running": True}
+
+ mandate = _active_mandate_state(broker)
+ if mandate is None:
+ raise HTTPException(status_code=409, detail=f"no committed mandate for {broker}")
+ if mandate.expired:
+ raise HTTPException(status_code=409, detail=f"mandate for {broker} has expired; re-authorize first")
+ if halt_flag_set(broker=broker) or halt_flag_set(broker=None):
+ raise HTTPException(status_code=409, detail="kill switch is tripped; resume before starting the runner")
+
+ try:
+ runner = _build_live_runner(broker)
+ except LiveRunnerUnavailable as exc:
+ raise HTTPException(status_code=503, detail=str(exc)) from exc
+ except Exception as exc:
+ raise HTTPException(status_code=500, detail=f"could not construct runner: {exc}") from exc
+
+ task = asyncio.ensure_future(_drive_runner(runner))
+ _runner_tasks[broker] = task
+ task.add_done_callback(lambda t, b=broker: _runner_tasks.pop(b, None) if _runner_tasks.get(b) is t else None)
+
+ _emit_live_event(payload.session_id, "live.action", {"kind": "runner_started", "broker": broker})
+ return {"broker": broker, "started": True, "already_running": False}
+
+
[email protected]("/live/runner/stop", dependencies=[Depends(require_auth)])
+async def stop_runner_endpoint(payload: LiveRunnerControlRequest):
+ """Stop the persistent live runner for a broker (SPEC §7.5).
+
+ Cancels the background task. This does NOT flatten positions — that is the
+ preemptive kill switch's job (``/live/halt`` -> flatten); stopping the runner
+ simply ceases new autonomous turns. Idempotent for an already-stopped broker.
+ """
+ broker = payload.broker.strip().lower()
+ if not broker:
+ raise HTTPException(status_code=400, detail="broker must not be blank")
+
+ task = _runner_tasks.pop(broker, None)
+ if task is None or task.done():
+ return {"broker": broker, "stopped": False, "was_running": False}
+
+ task.cancel()
+ _emit_live_event(payload.session_id, "live.action", {"kind": "runner_stopped", "broker": broker})
+ return {"broker": broker, "stopped": True, "was_running": True}
+
+
# ============================================================================
# Alpha Zoo routes (Web UI) — defined in src/api/alpha_routes.py
# ============================================================================
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 7b9915193..a21dd9623 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -841,6 +841,82 @@ def _format_tool_result_preview(tool: str, status: str, preview: str) -> str:
return ""
+# ---------------------------------------------------------------------------
+# In-process mandate.proposal relay (CLI mirror of api_server's
+# _mandate_proposal_frame_from_tool_result, SPEC.md Consent §1/§2)
+# ---------------------------------------------------------------------------
+#
+# The agent loop emits the propose tool's output only as a generic
+# ``tool_result`` event (``loop.py`` ``_finalize_tool_result`` → preview =
+# result[:200]); it NEVER emits a top-level ``mandate.proposal`` event. So in
+# the in-process REPL path nothing ever arms ``ctx.pending_proposal`` and the
+# user's numeric pick falls through to the model as chat. The frontend solved
+# the same gap server-side by relaying the propose-tool ``tool_result`` into a
+# top-level ``mandate.proposal`` SSE frame (api_server
+# ``_mandate_proposal_frame_from_tool_result``). The CLI needs the identical
+# relay in its own ``on_event`` handler — done below, WITHOUT touching the
+# protected ``loop.py``.
+
+_PROPOSAL_TOOL_NAME = "propose_mandate_profiles"
+_PROPOSAL_ID_RE = re.compile(r'"proposal_id"\s*:\s*"(mp_[0-9a-zA-Z]+)"')
+
+
+def _load_full_proposal(proposal_id: str) -> Optional[Dict[str, Any]]:
+ """Reload a persisted ``mandate.proposal`` payload by id, broker-agnostic.
+
+ The propose tool persists the full proposal under
+ ``<runtime_root>/live/<broker>/proposals/<proposal_id>.json`` before
+ returning. The ``tool_result`` preview is only the first 200 chars of the
+ JSON body, far too short to carry the full proposal, so the relay reloads it
+ from disk. The broker segment is unknown from the preview alone, so every
+ broker's proposals directory is searched (mirrors api_server).
+
+ Args:
+ proposal_id: The ``mp_...`` id parsed from the tool_result preview.
+
+ Returns:
+ The full proposal dict, or ``None`` when not found / unreadable.
+ """
+ try:
+ from src.live.paths import live_root
+
+ for proposal_path in live_root().glob(f"*/proposals/{proposal_id}.json"):
+ try:
+ data = json.loads(proposal_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ if isinstance(data, dict) and data.get("type") == "mandate.proposal":
+ return data
+ except Exception: # noqa: BLE001 — relay must never break the turn
+ pass
+ return None
+
+
+def _mandate_proposal_from_tool_result(data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+ """Recover a full ``mandate.proposal`` payload from a propose-tool result.
+
+ Detection mirrors api_server's ``_mandate_proposal_frame_from_tool_result``:
+ the event must be a successful ``tool_result`` for ``propose_mandate_profiles``
+ whose preview carries a ``proposal_id``. The full proposal is then reloaded
+ from disk (the preview is truncated).
+
+ Args:
+ data: The ``tool_result`` event payload (``tool`` / ``status`` /
+ ``preview``).
+
+ Returns:
+ The full proposal dict ready to feed ``proposal_sink`` (arming
+ ``ctx.pending_proposal``), or ``None`` when this is not a recoverable
+ propose-tool result.
+ """
+ if data.get("tool") != _PROPOSAL_TOOL_NAME or data.get("status") != "ok":
+ return None
+ match = _PROPOSAL_ID_RE.search(str(data.get("preview") or ""))
+ if not match:
+ return None
+ return _load_full_proposal(match.group(1))
+
+
def _run_agent(
prompt: str,
history: Optional[List[Dict]] = None,
@@ -851,8 +927,18 @@ def _run_agent(
stream_output: bool = True,
dashboard: Optional[_RunDashboard] = None,
session_id: str = "",
+ proposal_sink: Optional[Any] = None,
) -> dict:
- """Build AgentLoop and execute, return result dict."""
+ """Build AgentLoop and execute, return result dict.
+
+ Args:
+ proposal_sink: Optional callable invoked with the payload of every
+ ``mandate.proposal`` event the agent emits. The interactive REPL
+ uses this to capture an outstanding live-trading mandate proposal so
+ it can intercept the user's numeric pick *before* the model — a pick
+ is a privileged surface action (commit), never a tool the model can
+ call (SPEC.md Consent §2).
+ """
from src.tools import build_registry
from src.providers.chat import ChatLLM
from src.agent.loop import AgentLoop
@@ -866,6 +952,30 @@ def _run_agent(
}
def on_event(event_type: str, data: Dict[str, Any]) -> None:
+ # Live mandate proposals are surfaced to the REPL out-of-band so the
+ # user's pick is intercepted before the model (SPEC.md Consent §2).
+ # This fires regardless of stream_output / rich state — capturing the
+ # proposal must not depend on rendering.
+ if event_type == "mandate.proposal" and proposal_sink is not None:
+ try:
+ proposal_sink(data)
+ except Exception: # noqa: BLE001 — capture must never kill the turn
+ pass
+ return
+ # The agent loop never emits a top-level ``mandate.proposal`` — it only
+ # emits the propose tool's output as a generic ``tool_result``. Relay it
+ # here (CLI mirror of api_server's SSE relay) so the REPL arms
+ # ``ctx.pending_proposal`` and intercepts the pick before the model
+ # (SPEC.md Consent §1/§2). Fires regardless of stream_output / rich
+ # state — arming must not depend on rendering — and does NOT return:
+ # the tool_result still flows on to the dashboard / no-rich printers.
+ if event_type == "tool_result" and proposal_sink is not None:
+ proposal = _mandate_proposal_from_tool_result(data)
+ if proposal is not None:
+ try:
+ proposal_sink(proposal)
+ except Exception: # noqa: BLE001 — relay must never kill the turn
+ pass
if not stream_output:
return
if dashboard is not None and not no_rich:
@@ -2585,6 +2695,605 @@ def cmd_provider_login(provider: str) -> int:
return EXIT_RUN_FAILED
+# ---------------------------------------------------------------------------
+# Live trading channel (`vibe-trading live ...`) — SPEC.md §9 Decision 1.
+#
+# Every state-changing verb here is a PRIVILEGED USER-SIDE action: none is
+# reachable from the agent loop / tool registry. There is deliberately NO
+# `live commit` verb — committing a mandate happens only through the consent
+# flow's `POST /mandate/commit`, never the CLI (the CLI cannot create or widen
+# a mandate). The verbs are:
+#
+# live authorize <broker> Desktop OAuth bootstrap (opens browser, writes
+# the token cache). The only way to turn on the channel.
+# live run [<broker>] Run the persistent runner in the FOREGROUND (tails
+# the heartbeat; Ctrl+C stops it). SPEC §7.5.
+# live start [<broker>] Start the persistent runner in the background.
+# live stop [<broker>] Stop the persistent runner.
+# live status Per-broker auth state + active mandate (limits +
+# expires_at countdown) + halt state + runner
+# liveness / last-tick (read-only).
+# live mandate [<broker>] Print the committed mandate (read-only).
+# live halt [<broker>] Trip the kill switch (writes the HALT sentinel).
+# live resume [<broker>] Clear the halt (explicit privileged re-enable).
+# live revoke <broker> Revoke OAuth token + delete the mandate (full off).
+# ---------------------------------------------------------------------------
+
+_DEFAULT_LIVE_BROKER = "robinhood"
+
+
+def _live_api_base() -> str:
+ """Return the base URL of the running API server for runner-control calls.
+
+ Mirrors :func:`cli.main._commit_mandate`: the base is read from
+ ``VIBE_TRADING_API_URL`` (falling back to ``http://127.0.0.1:8000``). The
+ persistent runner (SPEC §7.5) is controlled through the R6 surface endpoints
+ (``POST /live/runner/start|stop`` / ``GET /live/status``), never from the
+ agent loop, so the CLI only ever relays intent.
+
+ Returns:
+ The API base URL with any trailing slash removed.
+ """
+ return os.environ.get("VIBE_TRADING_API_URL", "http://127.0.0.1:8000").rstrip("/")
+
+
+def _live_api_call(method: str, path: str, *, body: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
+ """Call an R6 live-runner endpoint and decode the JSON response.
+
+ Args:
+ method: HTTP verb (``"GET"`` or ``"POST"``).
+ path: Endpoint path beginning with ``/`` (e.g. ``"/live/runner/start"``).
+ body: JSON request body for ``POST`` calls.
+
+ Returns:
+ The decoded response object on success, or an ``{"status": "error",
+ "error": ...}`` envelope when the server is unreachable / returns a
+ non-2xx status — so a caller can surface a clean message instead of a
+ traceback when no server is running.
+ """
+ import httpx
+
+ url = f"{_live_api_base()}{path}"
+ try:
+ if method.upper() == "GET":
+ response = httpx.get(url, timeout=30.0)
+ else:
+ response = httpx.post(url, json=body or {}, timeout=30.0)
+ response.raise_for_status()
+ return response.json()
+ except Exception as exc: # noqa: BLE001 — surface a clean error to the user
+ return {"status": "error", "error": str(exc)}
+
+
+def _live_server_config(broker: str):
+ """Resolve the protected MCP server config for ``broker``.
+
+ The config is read at boot from the user-side protected agent config file
+ (never from caller input / agent tool args / ``variables``), exactly as the
+ #142 swarm-config trust template requires.
+
+ Args:
+ broker: Broker key, e.g. ``"robinhood"``.
+
+ Returns:
+ The :class:`MCPServerConfig` for ``broker``, or ``None`` when the broker
+ has no entry in the protected config.
+ """
+ from src.config.loader import load_agent_config
+
+ agent_config = load_agent_config()
+ servers = getattr(agent_config, "mcp_servers", {}) or {}
+ return servers.get(broker.strip().lower())
+
+
+def cmd_live_authorize(broker: str) -> int:
+ """Bootstrap the OAuth handshake for a live broker channel (desktop only).
+
+ Builds the broker's MCP tool wrappers, which forces a connection and — when
+ no valid token is cached — triggers the native FastMCP OAuth flow: a browser
+ opens to the broker's authorize page and the token is persisted to the
+ protected cache. This is the only way to turn the channel on.
+
+ Args:
+ broker: Broker key, e.g. ``"robinhood"``.
+
+ Returns:
+ Process exit code.
+ """
+ key = broker.strip().lower()
+ server_config = _live_server_config(key)
+ if server_config is None:
+ console.print(
+ f"[red]No live channel configured for '{key}'.[/red] "
+ "Add the broker's mcpServers entry to ~/.vibe-trading/agent.json first."
+ )
+ return EXIT_USAGE_ERROR
+ if getattr(server_config, "auth", None) is None:
+ console.print(
+ f"[red]Live channel '{key}' has no OAuth auth configured[/red] — "
+ "cannot authorize."
+ )
+ return EXIT_USAGE_ERROR
+
+ console.print(f"[cyan]Opening browser to authorize {key}…[/cyan]")
+ console.print(
+ "[dim]Complete the sign-in in your browser; this terminal will continue "
+ "once the broker redirects back.[/dim]"
+ )
+ try:
+ from src.tools.mcp import build_mcp_tool_wrappers
+
+ tools = build_mcp_tool_wrappers(key, server_config)
+ except Exception as exc: # noqa: BLE001 — surface any handshake failure
+ console.print(f"[red]Authorization failed:[/red] {exc}")
+ return EXIT_RUN_FAILED
+
+ console.print(
+ f"[green]Authorized {key}[/green] "
+ f"[dim]({len(tools)} read-only tool(s) available)[/dim]"
+ )
+ console.print(
+ "[dim]The channel is read-only until you commit a mandate and enable "
+ "order tools. Use `vibe-trading live status` to check state.[/dim]"
+ )
+ return EXIT_SUCCESS
+
+
+def _format_expiry_countdown(expires_at: str) -> str:
+ """Return a human-readable countdown to ``expires_at`` (ISO-8601 UTC)."""
+ from datetime import datetime, timezone
+
+ try:
+ parsed = datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
+ except ValueError:
+ return f"{expires_at} (unparseable)"
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ delta = parsed - datetime.now(timezone.utc)
+ secs = int(delta.total_seconds())
+ if secs <= 0:
+ return f"{expires_at} (EXPIRED)"
+ days, rem = divmod(secs, 86400)
+ hours, rem = divmod(rem, 3600)
+ minutes = rem // 60
+ if days:
+ human = f"{days}d {hours}h"
+ elif hours:
+ human = f"{hours}h {minutes}m"
+ else:
+ human = f"{minutes}m"
+ return f"{expires_at} (in {human})"
+
+
+def _runner_id_for(broker: str) -> str:
+ """Return the persistent-runner identity key for ``broker`` (SPEC §7.5)."""
+ return f"live-{broker}"
+
+
+def _add_runner_liveness_rows(table: Table, broker: str) -> None:
+ """Append persistent-runner liveness rows to a ``live status`` table.
+
+ Liveness is reported from the local heartbeat files via the runtime
+ contract (:func:`src.live.runtime.liveness.is_runner_alive` /
+ :func:`~src.live.runtime.liveness.last_tick`), so it works without a running
+ API server. If the liveness module is not yet present (it lands concurrently
+ with this parcel), the rows degrade to ``unknown`` rather than crashing the
+ read-only status command.
+
+ Args:
+ table: The Rich table being built by :func:`cmd_live_status`.
+ broker: Broker key the runner is bound to.
+ """
+ runner_id = _runner_id_for(broker)
+ try:
+ from src.live.runtime.liveness import is_runner_alive, last_tick
+ except Exception: # noqa: BLE001 — liveness lands concurrently; degrade cleanly
+ table.add_row("Runner", "[dim]unknown (runtime not available)[/dim]")
+ return
+
+ try:
+ alive = is_runner_alive(runner_id)
+ except Exception as exc: # noqa: BLE001 — never let a status read raise
+ table.add_row("Runner", f"[dim]unknown ({exc})[/dim]")
+ return
+
+ if alive:
+ table.add_row("Runner", "[green]running[/green]")
+ else:
+ table.add_row("Runner", "[yellow]stopped[/yellow]")
+
+ try:
+ tick = last_tick(runner_id)
+ except Exception: # noqa: BLE001
+ tick = None
+ if tick is not None:
+ table.add_row(" Last tick", _format_last_tick(tick))
+
+
+def _format_last_tick(tick: Any) -> str:
+ """Render a runner's last-tick timestamp as an absolute + relative string.
+
+ Args:
+ tick: A ``datetime`` or ISO-8601 string from the liveness heartbeat.
+
+ Returns:
+ Human-readable ``"<iso> (<n>s ago)"`` (or the raw value if unparseable).
+ """
+ from datetime import datetime, timezone
+
+ if isinstance(tick, datetime):
+ parsed = tick
+ else:
+ try:
+ parsed = datetime.fromisoformat(str(tick).replace("Z", "+00:00"))
+ except ValueError:
+ return str(tick)
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ ago = int((datetime.now(timezone.utc) - parsed).total_seconds())
+ iso = parsed.isoformat()
+ if ago < 0:
+ return iso
+ if ago < 60:
+ return f"{iso} ({ago}s ago)"
+ if ago < 3600:
+ return f"{iso} ({ago // 60}m ago)"
+ return f"{iso} ({ago // 3600}h ago)"
+
+
+def cmd_live_status(broker: Optional[str] = None) -> int:
+ """Show auth state, active mandate, and halt state for live channels.
+
+ Read-only: it loads the mandate via :func:`src.live.mandate.store.load_mandate`
+ and checks the halt sentinel via :func:`src.live.halt.halt_flag_set`; it never
+ writes anything.
+
+ Args:
+ broker: Limit the report to a single broker. ``None`` reports the
+ default broker (``robinhood``).
+
+ Returns:
+ Process exit code.
+ """
+ from src.live.halt import halt_flag_set, read_halt
+ from src.live.mandate.model import MANDATE_SCHEMA_VERSION
+ from src.live.mandate.store import load_mandate
+
+ key = (broker or _DEFAULT_LIVE_BROKER).strip().lower()
+
+ table = Table(title=f"Live channel: {key}", box=box.SIMPLE)
+ table.add_column("Field", style="cyan", no_wrap=True)
+ table.add_column("Value")
+
+ server_config = _live_server_config(key)
+ authorized = server_config is not None and getattr(server_config, "auth", None) is not None
+ table.add_row("Configured", "yes" if server_config is not None else "[red]no[/red]")
+ table.add_row("OAuth auth", "yes" if authorized else "no")
+
+ halted = halt_flag_set(key)
+ if halted:
+ meta = read_halt(key) or read_halt() or {}
+ reason = meta.get("reason", "")
+ by = meta.get("by", "")
+ detail = f" [dim]({by}: {reason})[/dim]" if (by or reason) else ""
+ table.add_row("Halt", f"[bold red]HALTED[/bold red]{detail}")
+ else:
+ table.add_row("Halt", "[green]clear[/green]")
+
+ _add_runner_liveness_rows(table, key)
+
+ mandate = load_mandate(key)
+ if mandate is None:
+ table.add_row("Mandate", "[yellow]none on file[/yellow] (read-only)")
+ elif mandate.schema_version != MANDATE_SCHEMA_VERSION:
+ table.add_row(
+ "Mandate",
+ f"[red]unknown schema v{mandate.schema_version}[/red] (gate fail-closed)",
+ )
+ else:
+ caps = mandate.hard_caps
+ table.add_row("Mandate", "[green]active[/green]")
+ table.add_row(" Max order", f"${caps.max_order_notional_usd:,.0f}")
+ table.add_row(" Max exposure", f"${caps.max_total_exposure_usd:,.0f}")
+ table.add_row(" Max leverage", f"{caps.max_leverage:g}x")
+ table.add_row(" Trades/day", str(caps.max_trades_per_day))
+ table.add_row(
+ " Instruments",
+ ", ".join(i.value for i in caps.allowed_instruments) or "[red]none[/red]",
+ )
+ table.add_row(" Expires", _format_expiry_countdown(mandate.consent.expires_at))
+
+ console.print(table)
+ return EXIT_SUCCESS
+
+
+def cmd_live_mandate(broker: Optional[str] = None) -> int:
+ """Print the committed mandate for a broker (read-only).
+
+ Args:
+ broker: Broker key. ``None`` uses the default broker (``robinhood``).
+
+ Returns:
+ Process exit code. ``EXIT_RUN_FAILED`` when no mandate is on file.
+ """
+ from dataclasses import asdict
+
+ from src.live.mandate.store import load_mandate
+
+ key = (broker or _DEFAULT_LIVE_BROKER).strip().lower()
+ mandate = load_mandate(key)
+ if mandate is None:
+ console.print(
+ f"[yellow]No committed mandate for '{key}'.[/yellow] "
+ "The channel is read-only until a mandate is committed via the consent flow."
+ )
+ return EXIT_RUN_FAILED
+
+ payload = asdict(mandate)
+ # asdict leaves enums as Enum members; render their string values.
+ caps = payload["hard_caps"]
+ caps["allowed_instruments"] = [i.value for i in mandate.hard_caps.allowed_instruments]
+ payload["universe"]["asset_classes"] = [a.value for a in mandate.universe.asset_classes]
+ console.print_json(data=payload)
+ return EXIT_SUCCESS
+
+
+def cmd_live_halt(broker: Optional[str] = None) -> int:
+ """Trip the kill switch — write the HALT sentinel (privileged).
+
+ With no broker, trips the global switch (halts all brokers); with a broker,
+ trips only that broker's sentinel. The gate rejects all order attempts until
+ the switch is cleared with ``live resume``.
+
+ Args:
+ broker: Broker key, or ``None`` for the global switch.
+
+ Returns:
+ Process exit code.
+ """
+ from src.live.halt import trip_halt
+
+ target = broker.strip().lower() if broker else None
+ path = trip_halt(by="cli", reason="cli live halt", broker=target)
+ scope = target or "ALL brokers"
+ console.print(f"[bold red]Live trading halted[/bold red] for {scope}.")
+ console.print(f"[dim]Sentinel: {path}[/dim]")
+ console.print("[dim]Run `vibe-trading live resume` to re-enable.[/dim]")
+ return EXIT_SUCCESS
+
+
+def cmd_live_resume(broker: Optional[str] = None) -> int:
+ """Clear a tripped kill switch (privileged, explicit re-enable).
+
+ Args:
+ broker: Broker key, or ``None`` for the global switch. Each scope is
+ cleared independently.
+
+ Returns:
+ Process exit code.
+ """
+ from src.live.halt import clear_halt
+
+ target = broker.strip().lower() if broker else None
+ cleared = clear_halt(broker=target)
+ scope = target or "ALL brokers"
+ if cleared:
+ console.print(f"[green]Halt cleared[/green] for {scope}.")
+ else:
+ console.print(f"[dim]No active halt for {scope}.[/dim]")
+ return EXIT_SUCCESS
+
+
+def cmd_live_revoke(broker: str) -> int:
+ """Revoke the OAuth token and delete the mandate — full channel off.
+
+ Deletes the broker's OAuth token cache directory and its ``mandate.json``
+ so the channel reverts to fully off. This is a privileged user-side action.
+
+ Args:
+ broker: Broker key, e.g. ``"robinhood"``.
+
+ Returns:
+ Process exit code.
+ """
+ from src.live.paths import broker_dir
+
+ key = broker.strip().lower()
+ try:
+ base = broker_dir(key)
+ except ValueError as exc:
+ console.print(f"[red]{exc}[/red]")
+ return EXIT_USAGE_ERROR
+
+ removed: list[str] = []
+
+ # OAuth token cache. Prefer the configured cache_dir; fall back to the
+ # canonical per-broker oauth/ subtree.
+ server_config = _live_server_config(key)
+ cache_dir: Optional[Path] = None
+ auth = getattr(server_config, "auth", None) if server_config is not None else None
+ if auth is not None and getattr(auth, "cache_dir", None):
+ cache_dir = Path(auth.cache_dir).expanduser()
+ if cache_dir is None or not cache_dir.exists():
+ cache_dir = base / "oauth"
+ if cache_dir.exists():
+ shutil.rmtree(cache_dir, ignore_errors=True)
+ removed.append(f"OAuth token cache ({cache_dir})")
+
+ mandate_path = base / "mandate.json"
+ if mandate_path.exists():
+ try:
+ mandate_path.unlink()
+ removed.append(f"mandate ({mandate_path})")
+ except OSError as exc:
+ console.print(f"[red]Failed to delete mandate: {exc}[/red]")
+ return EXIT_RUN_FAILED
+
+ if removed:
+ console.print(f"[green]Revoked live channel '{key}'.[/green]")
+ for item in removed:
+ console.print(f" [dim]- removed {item}[/dim]")
+ else:
+ console.print(f"[dim]Nothing to revoke for '{key}' (no token or mandate on file).[/dim]")
+ return EXIT_SUCCESS
+
+
+def cmd_live_start(broker: Optional[str] = None) -> int:
+ """Start the persistent live runner in the background (SPEC §7.5).
+
+ Relays a start request to the R6 surface endpoint
+ (``POST /live/runner/start``); the server owns the durable scheduler + job
+ store. This never touches the agent loop. The runner is read-only until a
+ mandate is committed (the consent flow), so starting it is safe even before
+ any mandate exists.
+
+ Args:
+ broker: Broker key, or ``None`` for the default broker (``robinhood``).
+
+ Returns:
+ Process exit code. ``EXIT_RUN_FAILED`` when the server is unreachable.
+ """
+ key = (broker or _DEFAULT_LIVE_BROKER).strip().lower()
+ result = _live_api_call(
+ "POST", "/live/runner/start", body={"broker": key, "foreground": False}
+ )
+ if result.get("status") == "error":
+ console.print(f"[red]Could not start the live runner:[/red] {result.get('error')}")
+ console.print(
+ "[dim]Is the API server running? Start it with `vibe-trading serve`.[/dim]"
+ )
+ return EXIT_RUN_FAILED
+
+ runner_id = result.get("runner_id") or _runner_id_for(key)
+ console.print(f"[green]Live runner started[/green] for {key} [dim]({runner_id})[/dim].")
+ console.print("[dim]Check it with `vibe-trading live status`.[/dim]")
+ return EXIT_SUCCESS
+
+
+def cmd_live_stop(broker: Optional[str] = None) -> int:
+ """Stop the persistent live runner (SPEC §7.5).
+
+ Relays a stop request to ``POST /live/runner/stop``. Stopping the runner
+ halts autonomous activity but does NOT clear a tripped kill switch or revoke
+ the mandate — use ``live resume`` / ``live revoke`` for those.
+
+ Args:
+ broker: Broker key, or ``None`` for the default broker (``robinhood``).
+
+ Returns:
+ Process exit code. ``EXIT_RUN_FAILED`` when the server is unreachable.
+ """
+ key = (broker or _DEFAULT_LIVE_BROKER).strip().lower()
+ result = _live_api_call("POST", "/live/runner/stop", body={"broker": key})
+ if result.get("status") == "error":
+ console.print(f"[red]Could not stop the live runner:[/red] {result.get('error')}")
+ console.print(
+ "[dim]Is the API server running? Start it with `vibe-trading serve`.[/dim]"
+ )
+ return EXIT_RUN_FAILED
+
+ console.print(f"[yellow]Live runner stopped[/yellow] for {key}.")
+ return EXIT_SUCCESS
+
+
+def cmd_live_run(broker: Optional[str] = None) -> int:
+ """Run the persistent live runner in the foreground (SPEC §7.5).
+
+ The foreground variant of ``live start``: it starts the runner via
+ ``POST /live/runner/start`` and then tails its heartbeat in a Rich ``Live``
+ panel until Ctrl+C, at which point it requests a clean stop. This mirrors
+ how ``serve`` runs a long-lived process attached to the terminal. The runner
+ is read-only until a mandate is committed through the consent flow.
+
+ Args:
+ broker: Broker key, or ``None`` for the default broker (``robinhood``).
+
+ Returns:
+ Process exit code.
+ """
+ key = (broker or _DEFAULT_LIVE_BROKER).strip().lower()
+ runner_id = _runner_id_for(key)
+
+ result = _live_api_call(
+ "POST", "/live/runner/start", body={"broker": key, "foreground": True}
+ )
+ if result.get("status") == "error":
+ console.print(f"[red]Could not start the live runner:[/red] {result.get('error')}")
+ console.print(
+ "[dim]Is the API server running? Start it with `vibe-trading serve`.[/dim]"
+ )
+ return EXIT_RUN_FAILED
+
+ console.print(
+ f"[green]Live runner running[/green] for {key} [dim]({runner_id})[/dim] — "
+ "press Ctrl+C to stop."
+ )
+
+ try:
+ from src.live.runtime.liveness import is_runner_alive, last_tick
+ except Exception: # noqa: BLE001 — runtime lands concurrently; fall back to a wait
+ is_runner_alive = None # type: ignore[assignment]
+ last_tick = None # type: ignore[assignment]
+
+ def _panel() -> Panel:
+ alive = bool(is_runner_alive(runner_id)) if is_runner_alive else True
+ state = "[green]running[/green]" if alive else "[yellow]stopped[/yellow]"
+ lines = [f"Runner: {state}", f"Broker: {key}"]
+ if last_tick:
+ try:
+ tick = last_tick(runner_id)
+ except Exception: # noqa: BLE001
+ tick = None
+ if tick is not None:
+ lines.append(f"Last tick: {_format_last_tick(tick)}")
+ return Panel("\n".join(lines), title=f"live run · {key}", box=box.ROUNDED)
+
+ try:
+ with Live(_panel(), console=console, refresh_per_second=2, transient=False) as live:
+ while True:
+ time.sleep(1.0)
+ live.update(_panel())
+ if is_runner_alive and not is_runner_alive(runner_id):
+ break
+ except KeyboardInterrupt:
+ console.print("\n[dim]Stopping live runner…[/dim]")
+ finally:
+ stop = _live_api_call("POST", "/live/runner/stop", body={"broker": key})
+ if stop.get("status") == "error":
+ console.print(f"[red]Failed to stop the runner cleanly:[/red] {stop.get('error')}")
+ else:
+ console.print(f"[yellow]Live runner stopped[/yellow] for {key}.")
+ return EXIT_SUCCESS
+
+
+def _dispatch_live(args: argparse.Namespace) -> int:
+ """Route a parsed ``live`` subcommand to its handler."""
+ sub = getattr(args, "live_command", None)
+ if sub == "authorize":
+ return cmd_live_authorize(args.live_broker)
+ if sub == "run":
+ return cmd_live_run(getattr(args, "live_broker", None))
+ if sub == "start":
+ return cmd_live_start(getattr(args, "live_broker", None))
+ if sub == "stop":
+ return cmd_live_stop(getattr(args, "live_broker", None))
+ if sub == "status":
+ return cmd_live_status(getattr(args, "live_broker", None))
+ if sub == "mandate":
+ return cmd_live_mandate(getattr(args, "live_broker", None))
+ if sub == "halt":
+ return cmd_live_halt(getattr(args, "live_broker", None))
+ if sub == "resume":
+ return cmd_live_resume(getattr(args, "live_broker", None))
+ if sub == "revoke":
+ return cmd_live_revoke(args.live_broker)
+ console.print(
+ "[red]live requires a subcommand.[/red] "
+ "Try: vibe-trading live status"
+ )
+ return EXIT_USAGE_ERROR
+
+
# ---------------------------------------------------------------------------
# CLI entrypoint
# ---------------------------------------------------------------------------
@@ -2672,6 +3381,70 @@ def _build_parser() -> argparse.ArgumentParser:
memory_forget_parser.add_argument("name", help="Memory title or filename stem")
memory_forget_parser.add_argument("-y", "--yes", action="store_true", help="Skip confirmation prompt")
+ # Live trading channel (SPEC.md §9 Decision 1). Every verb is a privileged
+ # user-side action; there is intentionally NO `live commit` verb.
+ live_parser = subparsers.add_parser("live", help="Manage the live trading channel")
+ live_subparsers = live_parser.add_subparsers(dest="live_command")
+
+ live_authorize = live_subparsers.add_parser(
+ "authorize", help="Desktop OAuth bootstrap — opens browser, turns the channel on"
+ )
+ live_authorize.add_argument("live_broker", metavar="broker", help="Broker key, e.g. robinhood")
+
+ live_run = live_subparsers.add_parser(
+ "run", help="Run the persistent runner in the foreground (Ctrl+C to stop)"
+ )
+ live_run.add_argument(
+ "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: robinhood)"
+ )
+
+ live_start = live_subparsers.add_parser(
+ "start", help="Start the persistent runner in the background"
+ )
+ live_start.add_argument(
+ "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: robinhood)"
+ )
+
+ live_stop = live_subparsers.add_parser(
+ "stop", help="Stop the persistent runner"
+ )
+ live_stop.add_argument(
+ "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: robinhood)"
+ )
+
+ live_status = live_subparsers.add_parser(
+ "status", help="Show auth state, active mandate, and halt state (read-only)"
+ )
+ live_status.add_argument(
+ "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: robinhood)"
+ )
+
+ live_mandate = live_subparsers.add_parser(
+ "mandate", help="Print the committed mandate (read-only)"
+ )
+ live_mandate.add_argument(
+ "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: robinhood)"
+ )
+
+ live_halt = live_subparsers.add_parser(
+ "halt", help="Trip the kill switch (writes the HALT sentinel)"
+ )
+ live_halt.add_argument(
+ "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: global)"
+ )
+
+ live_resume = live_subparsers.add_parser(
+ "resume", help="Clear the halt (explicit privileged re-enable)"
+ )
+ live_resume.add_argument(
+ "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: global)"
+ )
+
+ live_revoke = live_subparsers.add_parser(
+ "revoke", help="Revoke OAuth token + delete mandate (full off)"
+ )
+ live_revoke.add_argument("live_broker", metavar="broker", help="Broker key, e.g. robinhood")
+
# Alpha Zoo subcommands (registered via cli_handlers.add_subparser)
from src.factors.cli_handlers import add_subparser as _add_alpha_subparser
_add_alpha_subparser(subparsers)
@@ -3175,6 +3948,8 @@ 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 == "live":
+ return _coerce_exit_code(_dispatch_live(args))
if args.command == "memory":
if args.memory_command == "list":
return _coerce_exit_code(cmd_memory_list(args.memory_type))
diff --git a/agent/cli/main.py b/agent/cli/main.py
index 797c8aa00..4afd452c1 100644
--- a/agent/cli/main.py
+++ b/agent/cli/main.py
@@ -32,6 +32,58 @@ from cli.intro import print_banner
from cli.onboard import run_onboarding
from cli.theme import Theme, get_console
+
+def _register_live_slash_commands() -> None:
+ """Surface the live-trading slash commands in the shared registry.
+
+ Discoverability fix (SPEC.md Consent §4 + §9 audit): ``/live``, ``/halt`` and
+ ``/resume`` are privileged kill-switch / runner surface actions intercepted
+ in the REPL input path (never dispatched to the model), so they were absent
+ from the slash registry — meaning ``/help``, the typeahead completer, and the
+ fuzzy matcher never listed them. We append them here, at this module's import
+ time, which runs on every interactive startup *before* the lazily-imported
+ ``cli.commands.help`` / ``cli.completer`` first read the registry. Both of
+ those read ``slash_router.SLASH_COMMANDS`` (help) / call ``match_commands``
+ (completer) which resolve the live module attribute, so the single
+ reassignment here surfaces the commands in all three places.
+
+ The registry is a tuple of frozen dataclasses, so we build a NEW tuple rather
+ than mutate in place. Registration is idempotent — re-import (e.g. in tests)
+ never duplicates rows.
+ """
+ from cli.commands import slash_router
+
+ existing = {cmd.name for cmd in slash_router.SLASH_COMMANDS}
+ additions = (
+ slash_router.Command(
+ "live", "Live trading channel (status / run / halt)", "cli.main"
+ ),
+ slash_router.Command(
+ "halt", "Kill switch — halt ALL live trading now", "cli.main"
+ ),
+ slash_router.Command(
+ "resume", "Clear the kill switch (re-enable live trading)", "cli.main"
+ ),
+ )
+ new = tuple(cmd for cmd in additions if cmd.name not in existing)
+ if not new:
+ return
+ # Insert the live group just before ``quit`` (the conventional last row) so
+ # the kill switch sits with the other safety-relevant commands.
+ commands = list(slash_router.SLASH_COMMANDS)
+ quit_idx = next(
+ (i for i, c in enumerate(commands) if c.name == "quit"), len(commands)
+ )
+ commands[quit_idx:quit_idx] = list(new)
+ slash_router.SLASH_COMMANDS = tuple(commands)
+ # ``/stop`` is the kill-switch alias of ``/halt`` (SPEC Consent §4) so the
+ # fuzzy matcher / find_exact resolve it.
+ if "stop" not in slash_router._ALIASES:
+ slash_router._ALIASES = {**slash_router._ALIASES, "stop": "halt"}
+
+
+_register_live_slash_commands()
+
_ENV_PATH = Path.home() / ".vibe-trading" / ".env"
# Best-effort fallbacks used only when the probe genuinely fails (missing
# dependency, broken install). The numbers track the actual bundled counts
@@ -217,7 +269,18 @@ def _maybe_run_onboarding() -> bool:
def _show_banner() -> None:
"""Print the welcome banner using best-effort stat probes."""
stats = _collect_banner_stats()
- print_banner(get_console(), **stats)
+ console = get_console()
+ print_banner(console, **stats)
+ # Discoverability one-liner (SPEC.md §9 audit): point users at the
+ # live-trading channel + its CLI surface. Live is opt-in and read-only by
+ # default, so this is a pointer, not an enablement.
+ console.print(
+ " [dim]Live trading (opt-in, read-only by default): "
+ "[/dim][bold]/live[/bold][dim] in chat · "
+ "[/dim][bold]vibe-trading live --help[/bold][dim] · "
+ "[/dim][bold]/halt[/bold][dim] = kill switch.[/dim]"
+ )
+ console.print()
# ---------------------------------------------------------------------------
@@ -241,6 +304,12 @@ class InteractiveContext:
(``/journal``, ``/shadow``) that the loop should execute as
the next user turn. Consumed by :func:`_interactive_loop`
and cleared.
+ pending_proposal: The most recent live-trading ``mandate.proposal``
+ payload emitted by the agent during this session, awaiting the
+ user's pick or adjust reply. A numeric pick is intercepted in the
+ REPL input path and committed directly via the commit endpoint —
+ the model never sees the pick (SPEC.md Consent §2). ``None`` when
+ no proposal is outstanding.
"""
session_id: Optional[str] = None
@@ -249,6 +318,7 @@ class InteractiveContext:
debug: bool = False
last_recap_history_len: int = 0
pending_prompt: Optional[str] = None
+ pending_proposal: Optional[Dict[str, Any]] = None
# ---------------------------------------------------------------------------
@@ -589,6 +659,14 @@ def _run_one_turn(user_input: str, ctx: InteractiveContext) -> None:
start = time.perf_counter()
dashboard = _RunDashboard(user_input, ctx.max_iter)
+ # Capture the latest live-trading mandate proposal emitted this turn so the
+ # REPL can intercept the user's pick before the model (SPEC.md Consent §2).
+ captured_proposal: Dict[str, Any] = {}
+
+ def _capture_proposal(payload: Dict[str, Any]) -> None:
+ captured_proposal.clear()
+ captured_proposal.update(payload)
+
# ``transient=False`` — keep the final timeline visible after the run
# completes. Audit item 4.
try:
@@ -605,6 +683,7 @@ def _run_one_turn(user_input: str, ctx: InteractiveContext) -> None:
max_iter=ctx.max_iter,
dashboard=dashboard,
session_id=ctx.session_id or "",
+ proposal_sink=_capture_proposal,
)
dashboard.finish(result, time.perf_counter() - start)
except (KeyboardInterrupt, BrokenPipeError):
@@ -621,6 +700,13 @@ def _run_one_turn(user_input: str, ctx: InteractiveContext) -> None:
elapsed = time.perf_counter() - start
_print_interactive_result(console, result, elapsed)
+ # Render any mandate proposal AFTER the Live dashboard has closed so the
+ # numbered choice block isn't clobbered by the live region, and arm the
+ # REPL to intercept the next reply (SPEC.md Consent §2).
+ if captured_proposal:
+ ctx.pending_proposal = dict(captured_proposal)
+ _render_mandate_proposal(console, ctx.pending_proposal)
+
ctx.history.append({"role": "user", "content": user_input})
answer = (result.get("content") or "").strip()
if answer:
@@ -667,6 +753,300 @@ def _print_input_hint(console: Any, hint: str) -> None:
console.print(render_hint_bar(left=hint, right="Ctrl+D · /quit to exit"))
+# ---------------------------------------------------------------------------
+# Live trading channel — REPL intercepts (SPEC.md Consent §2, §4)
+#
+# Two privileged surface actions are intercepted in the REPL input path BEFORE
+# the agent loop is ever entered, so neither depends on the model cooperating:
+#
+# 1. Kill switch — a bare "停"/"stop"/"kill" turn, or the /halt /stop slash
+# commands, trip the HALT sentinel directly. The model never sees them.
+# 2. Mandate pick — when a `mandate.proposal` is outstanding, a bare numeric
+# reply ("1"/"2"/"3") is a COMMIT: it calls the commit endpoint directly
+# and the model never sees the pick. An "按 2,但…"-style adjust reply is
+# re-routed to the agent (PROPOSE re-render), not committed.
+# ---------------------------------------------------------------------------
+
+#: Bare turns that trip the kill switch when typed alone (case-insensitive).
+_HALT_WORDS = frozenset({"停", "停止", "stop", "kill", "halt", "停手"})
+
+_DEFAULT_LIVE_BROKER = "robinhood"
+
+
+def _is_halt_turn(text: str) -> bool:
+ """Return True if ``text`` is a bare kill-switch turn.
+
+ Matches a turn whose entire content (trimmed, trailing punctuation removed,
+ lower-cased) is one of :data:`_HALT_WORDS`. A longer sentence that merely
+ *mentions* "stop" is NOT a halt turn — it routes to the agent normally.
+
+ Args:
+ text: The raw user input line (already stripped of surrounding space).
+
+ Returns:
+ ``True`` if the turn should trip the kill switch.
+ """
+ token = text.strip().strip(".!。! ").lower()
+ return token in _HALT_WORDS
+
+
+def _trip_halt_from_repl(console: Any, *, reason: str) -> None:
+ """Trip the global kill switch from the REPL and print a notice.
+
+ This is the surface action behind a bare "停"/"stop" turn and the
+ ``/halt`` / ``/stop`` slash commands. It writes the HALT sentinel via
+ :func:`src.live.halt.trip_halt` — independent of the agent loop, so it works
+ even mid-stream.
+
+ Args:
+ console: Rich console for the confirmation notice.
+ reason: Human-readable reason recorded in the sentinel.
+ """
+ try:
+ from src.live.halt import trip_halt
+
+ path = trip_halt(by="cli", reason=reason)
+ except Exception as exc: # noqa: BLE001 — never let a halt failure kill the loop
+ console.print(f"[bold red]Failed to trip kill switch:[/bold red] {exc}")
+ return
+ console.print(
+ "[bold red]Live trading halted[/bold red] — all live order tools are now "
+ "disabled until you run [bold]/resume[/bold] or [bold]vibe-trading live resume[/bold]."
+ )
+ console.print(f"[dim]HALT sentinel: {path}[/dim]")
+
+
+def _clear_halt_from_repl(console: Any) -> None:
+ """Clear the global kill switch from the REPL (``/resume``).
+
+ Clearing the halt is a privileged surface action — an explicit re-enable,
+ never an agent tool (SPEC.md Consent §4). It is intercepted in the input
+ path so the model never performs it. Mirrors ``vibe-trading live resume``
+ with no broker (the global scope).
+
+ Args:
+ console: Rich console for the confirmation notice.
+ """
+ try:
+ from src.live.halt import clear_halt
+
+ cleared = clear_halt()
+ except Exception as exc: # noqa: BLE001 — never let a resume failure kill the loop
+ console.print(f"[bold red]Failed to clear kill switch:[/bold red] {exc}")
+ return
+ if cleared:
+ console.print(
+ "[green]Live trading re-enabled[/green] — the global kill switch is cleared."
+ )
+ else:
+ console.print("[dim]No active global halt to clear.[/dim]")
+
+
+def _run_live_command_from_repl(console: Any, args: list[str]) -> None:
+ """Run a ``/live ...`` subcommand from the REPL via the legacy dispatcher.
+
+ ``/live`` is a thin in-REPL bridge to the ``vibe-trading live`` subcommand
+ group (SPEC.md §9 Decision 1): ``/live status``, ``/live run``,
+ ``/live start``, ``/live stop``, ``/live mandate``, etc. It parses the
+ arguments through the same argparse surface as the non-interactive CLI and
+ dispatches to the same privileged handlers — none of which is an agent tool.
+ A bare ``/live`` defaults to ``status`` so the most common read is one
+ keystroke away.
+
+ Args:
+ console: Rich console for error messages.
+ args: Tokens following ``/live`` (e.g. ``["status", "robinhood"]``).
+ """
+ from cli._legacy import _build_parser, _dispatch_live
+
+ argv = ["live", *(args or ["status"])]
+ parser = _build_parser()
+ try:
+ parsed = parser.parse_args(argv)
+ except SystemExit:
+ # argparse already printed usage to stderr; keep the REPL alive.
+ console.print("[dim]Usage: /live [status|run|start|stop|mandate|halt|resume|revoke][/dim]")
+ return
+ try:
+ _dispatch_live(parsed)
+ except Exception as exc: # noqa: BLE001 — never let a live command kill the loop
+ console.print(f"[bold red]/live failed:[/bold red] {exc}")
+
+
+def _is_numeric_pick(text: str) -> Optional[int]:
+ """Return the chosen ordinal if ``text`` is a bare numeric pick, else None.
+
+ Only a turn that is *exactly* a positive integer (e.g. ``"2"``) counts as a
+ pick. Anything with extra words ("按 2 但每日笔数提到 10") is an adjust reply,
+ not a pick, and must route back through PROPOSE.
+
+ Args:
+ text: The raw user input line.
+
+ Returns:
+ The 1-based ordinal, or ``None`` when ``text`` is not a bare pick.
+ """
+ token = text.strip().strip(".。 ")
+ if token.isdigit():
+ value = int(token)
+ if value >= 1:
+ return value
+ return None
+
+
+def _render_mandate_proposal(console: Any, proposal: Dict[str, Any]) -> None:
+ """Print the numbered mandate-proposal choice block (SPEC.md Consent §2).
+
+ Renders the agent's candidate mandate profiles as a numbered list with their
+ concrete limits, plus the funding note and the kill-switch note. The user
+ replies with a bare number to commit, or an adjust sentence to re-propose.
+
+ Args:
+ console: Rich console.
+ proposal: The ``mandate.proposal`` event payload.
+ """
+ intent = proposal.get("intent_normalized") or "live trading"
+ account = proposal.get("account") or {}
+ acct_type = account.get("type")
+ acct_suffix = f" ({acct_type} account)" if acct_type else ""
+ profiles = proposal.get("profiles") or []
+
+ console.print()
+ if proposal.get("reauth_for"):
+ console.print(
+ f'[bold]AI proposes widening your mandate for "{intent}"{acct_suffix}:[/bold]'
+ )
+ else:
+ console.print(
+ f'[bold]AI proposes {len(profiles)} mandate(s) for "{intent}"{acct_suffix}:[/bold]'
+ )
+ console.print()
+
+ for profile in profiles:
+ ordinal = profile.get("ordinal", "?")
+ label = profile.get("label", "")
+ universe = profile.get("universe")
+ if isinstance(universe, (list, tuple)):
+ universe = "/".join(str(s) for s in universe)
+ bits = []
+ if universe:
+ bits.append(f"univ: {universe}")
+ if profile.get("max_order_usd") is not None:
+ bits.append(f"≤${profile['max_order_usd']}/order")
+ if profile.get("daily_trade_cap") is not None:
+ bits.append(f"{profile['daily_trade_cap']} trades/day")
+ leverage = profile.get("leverage")
+ if leverage in (None, "none", "None", 1, 1.0):
+ bits.append("no leverage")
+ elif leverage is not None:
+ bits.append(f"leverage {leverage}")
+ line = " · ".join(bits)
+ console.print(f" [bold cyan][{ordinal}][/bold cyan] {label} {line}")
+ notes = profile.get("notes")
+ if notes:
+ console.print(f" [dim]{notes}[/dim]")
+
+ console.print()
+ funding_note = proposal.get("funding_note") or (
+ "Funding is set by YOU in the broker; the agent cannot move money."
+ )
+ halt_note = proposal.get("halt_note") or '随时一句 "停" = kill switch, halts everything.'
+ console.print(f" [dim]{funding_note}[/dim]")
+ console.print(f" [dim]{halt_note}[/dim]")
+ console.print(
+ ' [bold]Pick a number to commit, or say "按 2 但每日笔数提到 10" to adjust.[/bold]'
+ )
+ console.print()
+
+
+def _commit_mandate(proposal: Dict[str, Any], selected_ordinal: int) -> Dict[str, Any]:
+ """Commit a mandate selection via the surface commit endpoint.
+
+ This is the single privileged write that activates a mandate. The pick is a
+ SURFACE action — it goes straight to ``POST /mandate/commit`` (owned by the
+ commit-endpoint parcel) and is NEVER fed to the model. ``consent_ack`` is set
+ here because the user's keypress *is* the affirmative consent.
+
+ The endpoint base URL is read from ``VIBE_TRADING_API_URL`` (falling back to
+ ``http://127.0.0.1:8000``); a per-request override is not accepted from the
+ proposal payload so the model cannot redirect the commit.
+
+ Args:
+ proposal: The outstanding ``mandate.proposal`` payload (binds the commit
+ to the exact rendered options via ``proposal_id``).
+ selected_ordinal: The 1-based profile the user picked.
+
+ Returns:
+ The decoded commit response (``mandate_id`` / ``consent_record_id`` on
+ success), or an ``{"status": "error", ...}`` envelope on failure.
+ """
+ import httpx
+
+ base = os.environ.get("VIBE_TRADING_API_URL", "http://127.0.0.1:8000").rstrip("/")
+ body = {
+ "proposal_id": proposal.get("proposal_id"),
+ "selected_ordinal": selected_ordinal,
+ "adjustments": None,
+ "session_id": proposal.get("session_id"),
+ "consent_ack": True,
+ }
+ try:
+ response = httpx.post(f"{base}/mandate/commit", json=body, timeout=30.0)
+ response.raise_for_status()
+ return response.json()
+ except Exception as exc: # noqa: BLE001 — surface a clean error to the user
+ return {"status": "error", "error": str(exc)}
+
+
+def _handle_proposal_reply(text: str, ctx: InteractiveContext) -> bool:
+ """Intercept a reply while a mandate proposal is outstanding.
+
+ Must be called only when ``ctx.pending_proposal`` is set. A bare numeric pick
+ is a COMMIT (calls the endpoint directly, the model never sees it); any other
+ reply is an ADJUST and is routed back to the agent for a fresh proposal.
+
+ Args:
+ text: The raw user input line.
+ ctx: The interactive context (proposal is cleared on a successful pick).
+
+ Returns:
+ ``True`` if the reply was a numeric pick and was handled here (the caller
+ must NOT route it to the agent). ``False`` for an adjust reply, which the
+ caller routes to the agent normally (keeping the proposal pending until a
+ fresh one replaces it).
+ """
+ console = get_console()
+ ordinal = _is_numeric_pick(text)
+ if ordinal is None:
+ # Adjust path — re-render via PROPOSE. Leave the proposal pending; the
+ # agent will emit a fresh one that overwrites it.
+ return False
+
+ proposal = ctx.pending_proposal or {}
+ profiles = proposal.get("profiles") or []
+ valid_ordinals = {p.get("ordinal") for p in profiles}
+ if valid_ordinals and ordinal not in valid_ordinals:
+ console.print(
+ f"[yellow]No option [{ordinal}] in this proposal.[/yellow] "
+ f"Pick one of: {', '.join(str(o) for o in sorted(o for o in valid_ordinals if o is not None))}, "
+ "or type an adjust sentence."
+ )
+ return True
+
+ console.print(f"[dim]Committing mandate option [{ordinal}]…[/dim]")
+ result = _commit_mandate(proposal, ordinal)
+ if result.get("status") == "error":
+ console.print(f"[red]Commit failed:[/red] {result.get('error')}")
+ console.print("[dim]The proposal is still open — pick again once the issue is resolved.[/dim]")
+ return True
+
+ # Success — clear the proposal so subsequent turns route normally.
+ ctx.pending_proposal = None
+ mandate_id = result.get("mandate_id") or "?"
+ console.print(f"[green]Mandate {mandate_id} active.[/green]")
+ return True
+
+
def _interactive_loop(max_iter: int) -> int:
"""Drive the new interactive REPL.
@@ -733,8 +1113,38 @@ def _interactive_loop(max_iter: int) -> int:
if not text:
continue
+ # Kill switch — intercept a bare "停"/"stop"/"kill" turn BEFORE the
+ # agent loop so it trips even if a turn is mid-stream and never depends
+ # on the model cooperating (SPEC.md Consent §4).
+ if _is_halt_turn(text):
+ _trip_halt_from_repl(console, reason=f"repl turn: {text}")
+ ctx.pending_proposal = None
+ continue
+
+ # Mandate pick — when a proposal is outstanding, a bare numeric reply
+ # is a COMMIT handled here (the model never sees it). An adjust reply
+ # falls through to the agent for a fresh proposal (SPEC.md Consent §2).
+ if ctx.pending_proposal is not None and not text.startswith("/"):
+ if _handle_proposal_reply(text, ctx):
+ continue
+
# Slash command path.
if text.startswith("/"):
+ # /halt /stop /resume /live are privileged live-trading surface
+ # actions handled in the input path, never dispatched to the model
+ # (SPEC.md Consent §4 / §9 Decision 1).
+ slash_tokens = text.lstrip("/").split()
+ slash_name = slash_tokens[0].lower() if slash_tokens else ""
+ if slash_name in {"halt", "stop"}:
+ _trip_halt_from_repl(console, reason=f"/{slash_name}")
+ ctx.pending_proposal = None
+ continue
+ if slash_name == "resume":
+ _clear_halt_from_repl(console)
+ continue
+ if slash_name == "live":
+ _run_live_command_from_repl(console, slash_tokens[1:])
+ continue
rc = _dispatch_slash(text, ctx)
if rc == 2:
break
diff --git a/agent/src/config/schema.py b/agent/src/config/schema.py
index 01d4f9ccd..df4db243d 100644
--- a/agent/src/config/schema.py
+++ b/agent/src/config/schema.py
@@ -3,9 +3,118 @@
from __future__ import annotations
from typing import Literal
+from urllib.parse import urlsplit
from pydantic import BaseModel, ConfigDict, Field, model_validator
+# Live-broker MCP server keys. These channels place real orders, so a wildcard
+# ``enabled_tools`` (which would re-admit every WRITE/UNKNOWN tool) is rejected
+# at config-load time — a live channel must pin an explicit read-only allowlist.
+LIVE_BROKER_SERVER_KEYS: frozenset[str] = frozenset({"robinhood"})
+
+# Live-broker URL host suffixes. Detecting a live broker by config key alone is
+# bypassable: a Robinhood agentic URL placed under any other key (e.g. ``rh``)
+# would otherwise dodge BOTH the wildcard rejection AND the classification gate,
+# exposing ``place_order`` ungated. So a server whose ``url`` host matches one of
+# these suffixes is treated as a live broker regardless of its config key. The
+# name-key path (``LIVE_BROKER_SERVER_KEYS``) stays as a fallback for stdio /
+# non-URL live channels and for keys that intentionally name a known broker.
+LIVE_BROKER_URL_HOST_SUFFIXES: tuple[str, ...] = ("robinhood.com",)
+
+
+def _url_host(url: str) -> str:
+ """Return the lower-cased hostname of an http(s) URL, or ``""``.
+
+ Args:
+ url: A candidate MCP server URL.
+
+ Returns:
+ The lower-cased host with any port stripped, or ``""`` when the URL is
+ empty or has no parseable host.
+ """
+ if not url or not url.strip():
+ return ""
+ try:
+ host = urlsplit(url.strip()).hostname
+ except ValueError:
+ return ""
+ return (host or "").lower()
+
+
+def is_live_broker_url(url: str) -> bool:
+ """Return whether a URL points at a known live-broker host.
+
+ A live broker is detected by host so an aliased config key cannot bypass the
+ wildcard rejection / gate. Match is on the host or any subdomain of a known
+ suffix (``agent.robinhood.com`` and ``robinhood.com`` both match), never a
+ substring (``robinhood.com.evil.test`` does NOT match).
+
+ Args:
+ url: The MCP server ``url`` from config.
+
+ Returns:
+ ``True`` when the URL host equals or is a subdomain of a live-broker
+ host suffix.
+ """
+ host = _url_host(url)
+ if not host:
+ return False
+ return any(
+ host == suffix or host.endswith(f".{suffix}")
+ for suffix in LIVE_BROKER_URL_HOST_SUFFIXES
+ )
+
+
+def is_live_broker_entry(server_key: str, server: "MCPServerConfig | MCPServerConfigOverride") -> bool:
+ """Return whether a configured MCP server is a live broker.
+
+ Detection is by config key (``LIVE_BROKER_SERVER_KEYS``) OR by URL host
+ (``is_live_broker_url``), so a live-broker URL parked under an arbitrary key
+ is still gated and still subject to the wildcard-allowlist rejection.
+
+ Args:
+ server_key: The MCP server key from config.
+ server: The server config (or override) carrying the ``url``.
+
+ Returns:
+ ``True`` when either the key or the URL host identifies a live broker.
+ """
+ if server_key.strip().lower() in LIVE_BROKER_SERVER_KEYS:
+ return True
+ return is_live_broker_url(getattr(server, "url", "") or "")
+
+# Canonical seed for the operator-side ``~/.vibe-trading/agent.json`` mcpServers
+# entry that wires the Robinhood Agentic Trading channel. It ships OFF-by-default
+# read-only: an explicit READ allowlist (never ``["*"]``), OAuth auth, and the
+# streamableHttp transport. Operators copy this block into their protected config
+# file; WRITE/order tools are only ever added by the user editing that file by
+# hand (never via agent tool args), and only take effect once a mandate exists.
+# Documented here (not invented elsewhere) because the operator config file is a
+# runtime artifact, not checked into the repo. See SPEC §7.2 / Transport §1–§6.
+ROBINHOOD_MCP_SERVER_SEED: dict[str, object] = {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "auth": {
+ "type": "oauth",
+ "scopes": ["trading.read"],
+ "client_name": "Vibe-Trading",
+ "cache_dir": "~/.vibe-trading/live/robinhood/oauth",
+ },
+ # Seed the OFF-by-default READ allowlist to EXACTLY the canonical curated
+ # READ tool names (``src.live.robinhood_classification.ROBINHOOD_TOOL_CLASS``).
+ # These MUST match the curated map's READ entries: a name here that the map
+ # does not classify READ would resolve UNKNOWN -> gated -> refused, silently
+ # hiding the real read tool. Canonical READ catalog: get_account,
+ # get_positions, get_quotes, list_orders. WRITE (place_order, cancel_order)
+ # is never seeded — the user adds those by hand once a mandate exists.
+ "enabled_tools": [
+ "get_account",
+ "get_positions",
+ "get_quotes",
+ "list_orders",
+ ],
+}
+
def _to_camel(name: str) -> str:
"""Convert snake_case names to camelCase aliases.
@@ -26,6 +135,42 @@ class ConfigBase(BaseModel):
model_config = ConfigDict(alias_generator=_to_camel, populate_by_name=True, extra="forbid")
+class MCPOAuthConfig(ConfigBase):
+ """OAuth authentication for a remote (HTTP) MCP server.
+
+ The OAuth provider owns the runtime ``Authorization`` header, so a server
+ using OAuth must not also set static ``headers`` (mutually exclusive — see
+ :meth:`MCPServerConfig.validate_transport_config`). OAuth is only valid on an
+ HTTPS HTTP transport: a refresh token must never traverse cleartext.
+
+ Attributes:
+ type: Auth discriminator. Only ``"oauth"`` is supported today.
+ scopes: OAuth scopes requested at authorization time.
+ client_name: Client name presented during dynamic client registration.
+ cache_dir: Directory for the persistent OAuth token cache. ``~`` is
+ expanded and the directory is created ``0700`` at first write by the
+ client. This is the single canonical field name (wire alias
+ ``cacheDir``) — every consumer reads ``auth.cache_dir`` (the OAuth
+ wiring in :func:`src.tools.mcp.MCPServerAdapter._build_client`, the
+ ``live revoke`` CLI cache sweep, and the seed below) so there is no
+ silent default-path fallback from a name mismatch. (``docs/live-
+ trading/SPEC.md`` §2 names this ``token_cache_path``; the shipped
+ field name is ``cache_dir`` to stay consistent with the existing CLI
+ consumer, which is the authoritative wire name.)
+ callback_port: Fixed loopback port for the browser redirect callback.
+ ``None`` (default) lets the OAuth provider pick a free port.
+ client_id: Optional pre-registered OAuth client id (skips dynamic
+ client registration when provided).
+ """
+
+ type: Literal["oauth"] = "oauth"
+ scopes: list[str] = Field(default_factory=list)
+ client_name: str = "Vibe-Trading"
+ cache_dir: str = "~/.vibe-trading/live/robinhood/oauth"
+ callback_port: int | None = Field(default=None, ge=1, le=65535)
+ client_id: str | None = None
+
+
class MCPServerConfig(ConfigBase):
"""Single external MCP server definition."""
@@ -35,6 +180,7 @@ class MCPServerConfig(ConfigBase):
env: dict[str, str] = Field(default_factory=dict)
url: str = ""
headers: dict[str, str] = Field(default_factory=dict)
+ auth: MCPOAuthConfig | None = None
tool_timeout: float = Field(default=30.0, ge=0.1)
enabled_tools: list[str] = Field(default_factory=lambda: ["*"])
@@ -66,12 +212,26 @@ class MCPServerConfig(ConfigBase):
raise ValueError("stdio MCP servers require a command")
if self.url.strip() or self.headers:
raise ValueError("stdio MCP servers do not accept url/headers")
+ if self.auth is not None:
+ raise ValueError("stdio MCP servers do not accept auth (OAuth is HTTP-only)")
return self
if not self.url.strip():
raise ValueError(f"{transport} MCP servers require a url")
if self.command.strip() or self.args or self.env:
raise ValueError(f"{transport} MCP servers do not accept command/args/env")
+
+ if self.auth is not None:
+ # The OAuth provider owns the runtime Authorization header; a
+ # hand-set static header alongside it is always a config error.
+ if self.headers:
+ raise ValueError(
+ "MCP servers using auth must not also set static headers "
+ "(the OAuth provider owns the Authorization header)"
+ )
+ # A refresh token must never traverse cleartext.
+ if not self.url.strip().lower().startswith("https://"):
+ raise ValueError("OAuth MCP servers require an https url")
return self
@@ -84,6 +244,7 @@ class MCPServerConfigOverride(ConfigBase):
env: dict[str, str] | None = None
url: str | None = None
headers: dict[str, str] | None = None
+ auth: MCPOAuthConfig | None = None
tool_timeout: float | None = Field(default=None, ge=0.1)
enabled_tools: list[str] | None = None
@@ -93,6 +254,33 @@ class AgentConfig(ConfigBase):
mcp_servers: dict[str, MCPServerConfig] = Field(default_factory=dict)
+ @model_validator(mode="after")
+ def validate_live_broker_servers(self) -> "AgentConfig":
+ """Reject wildcard allowlists on live-broker MCP server entries.
+
+ A live-broker channel places real orders, so a wildcard
+ ``enabled_tools`` of ``["*"]`` — which would re-admit every WRITE/UNKNOWN
+ tool — is a config error. Live channels must pin an explicit read-only
+ allowlist. A server is a live broker by config key OR by URL host
+ (:func:`is_live_broker_entry`), so a Robinhood URL parked under an
+ aliased key (e.g. ``rh``) cannot dodge this rejection. The server key is
+ only known at this top-level scope, which is why the check lives here
+ rather than on :class:`MCPServerConfig`.
+
+ Returns:
+ The validated agent config instance.
+
+ Raises:
+ ValueError: If a live-broker server entry uses ``["*"]``.
+ """
+ for server_key, server in self.mcp_servers.items():
+ if is_live_broker_entry(server_key, server) and "*" in server.enabled_tools:
+ raise ValueError(
+ f"Live-broker MCP server '{server_key}' may not use a wildcard "
+ "enabledTools allowlist ('*'); pin an explicit read-only tool list"
+ )
+ return self
+
class AgentConfigOverride(ConfigBase):
"""Partial top-level config override used for runtime layering."""
diff --git a/agent/src/live/__init__.py b/agent/src/live/__init__.py
new file mode 100644
index 000000000..fc84975e3
--- /dev/null
+++ b/agent/src/live/__init__.py
@@ -0,0 +1,10 @@
+"""Live trading channel (Robinhood Agentic Trading).
+
+Bounded-autonomy live execution: the agent trades autonomously inside a
+user-committed mandate, on funds ring-fenced in the broker's dedicated
+agentic account, with an out-of-band kill switch and a full audit trail.
+
+All live-channel state lives under ``~/.vibe-trading/live/`` (see
+:mod:`src.live.paths`). The mandate is read-only at the agent loop — there is
+no write path reachable from a tool (see ``docs/live-trading/SPEC.md`` §3).
+"""
diff --git a/agent/src/live/audit.py b/agent/src/live/audit.py
new file mode 100644
index 000000000..8e1c4e9e5
--- /dev/null
+++ b/agent/src/live/audit.py
@@ -0,0 +1,237 @@
+"""Live-action audit ledger (SPEC.md Consent §5).
+
+Every live action — order placed, order rejected by the gate, mandate committed,
+breach raised, kill switch tripped/cleared — appends one immutable record to a
+dedicated, append-only ledger at ``<runtime_root>/live/audit.jsonl``. This ledger
+is segregated from per-run research traces because it is the compliance-grade
+record that must survive run-dir cleanup: the canonical answer to "show me
+everything the agent did with real money."
+
+``mandate_snapshot_ref`` + ``consent_record_ref`` together make every live order
+traceable back to the exact user click that authorized the mandate it ran under —
+the core accountability chain.
+
+**Three sinks (SPEC §5).** Every redacted record fans out to up to three
+append-only destinations: (1) the dedicated compliance ledger above; (2) the
+per-run ``TraceWriter`` (``type="live_action"``, sitting alongside
+``tool_call`` / ``tool_result`` in the run dir) when one is supplied; and (3)
+the surfacing ``event_callback`` (``"live.action"``) so the CLI/frontend can
+render the action inline. Sinks 2 and 3 are optional — when absent they are
+silently skipped — and the dedicated ledger is always written.
+
+**Redaction (SPEC §5 / #142 shared helper).** Broker requests/responses can carry
+OAuth tokens, account numbers, and PII. Every record is scrubbed through
+:func:`src.tools.redaction.redact_payload` BEFORE it is written to ANY sink,
+so sensitive values are ``[redacted]`` before they reach the trace, the live
+ledger, or the SSE bus. The opaque ``account_ref`` provenance carried by the
+authorizing mandate is intentionally NOT a record field here and is preserved
+elsewhere as the mandate→consent accountability chain.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import uuid
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable, Literal, Protocol
+
+from src.live.paths import live_root
+from src.tools.redaction import redact_payload
+
+logger = logging.getLogger(__name__)
+
+#: SSE / surface event name for a live-action record (SPEC §5).
+_LIVE_ACTION_EVENT = "live.action"
+
+#: Trace record type, so live actions sit alongside ``tool_call`` /
+#: ``tool_result`` in the per-run trace (SPEC §5).
+_LIVE_ACTION_TRACE_TYPE = "live_action"
+
+
+class _TraceWriterLike(Protocol):
+ """Structural type for the per-run trace sink.
+
+ Matches :class:`src.agent.trace.TraceWriter` without importing the
+ protected agent core into the live module.
+ """
+
+ def write(self, entry: dict[str, Any]) -> None: ...
+
+
+#: Surface callback shape: ``event_callback(event_name, payload)`` — the same
+#: bus that already carries ``tool_call`` / ``tool_result`` (SPEC §5).
+EventCallback = Callable[[str, dict[str, Any]], Any]
+
+_LEDGER_FILENAME = "audit.jsonl"
+
+#: Canonical live-action kinds (SPEC §5).
+LiveActionKind = Literal[
+ "order_placed",
+ "order_rejected",
+ "mandate_committed",
+ "breach",
+ "halt_tripped",
+ "halt_cleared",
+]
+
+#: Canonical outcomes (SPEC §5).
+LiveActionOutcome = Literal["accepted", "filled", "rejected", "error", "blocked"]
+
+
+def _new_audit_id() -> str:
+ """Return a fresh unique audit id with the ``la_`` prefix (SPEC §5)."""
+ return f"la_{uuid.uuid4().hex}"
+
+
+def _utc_now_iso_ms() -> str:
+ """Return the current UTC time as an ISO-8601 string with ms precision."""
+ now = datetime.now(timezone.utc)
+ return now.isoformat(timespec="milliseconds")
+
+
+def audit_ledger_path() -> Path:
+ """Return the path to the dedicated live-action ledger.
+
+ Returns:
+ ``<runtime_root>/live/audit.jsonl``. The file/parent is NOT created here;
+ :func:`write_live_action` creates the directory on first append.
+ """
+ return live_root() / _LEDGER_FILENAME
+
+
+@dataclass(frozen=True)
+class LiveActionEvent:
+ """One immutable live-action audit record (SPEC.md Consent §5).
+
+ Attributes:
+ kind: The live-action kind (``order_placed`` | ``order_rejected`` |
+ ``mandate_committed`` | ``breach`` | ``halt_tripped`` |
+ ``halt_cleared``).
+ session_id: Originating session id.
+ outcome: Action outcome (``accepted`` | ``filled`` | ``rejected`` |
+ ``error`` | ``blocked``).
+ server: Origin server / broker key, e.g. ``"robinhood"`` (#142 origin
+ metadata, reused).
+ remote_tool: Broker remote tool name invoked, e.g. ``"place_order"``.
+ intent_normalized: Human-readable normalized intent,
+ e.g. ``"buy 3 NVDA @ market"``.
+ mandate_snapshot_ref: Which mandate authorized the action — the first
+ half of the accountability chain.
+ consent_record_ref: Which user consent authorized that mandate — the
+ second half of the accountability chain.
+ broker_request: Raw request sent to the broker. **Redacted** before
+ write/emit.
+ broker_response: Raw broker response. **Redacted** before write/emit.
+ gate_decision: The enforcement gate's verdict, e.g.
+ ``{"allowed": True, "checked_limits": [...]}``.
+ error: Error description when ``outcome == "error"``, else ``None``.
+ audit_id: Unique id (``la_<hex>``); auto-generated when omitted.
+ ts: ISO-8601 UTC timestamp (ms precision); auto-generated when omitted.
+ """
+
+ kind: LiveActionKind
+ session_id: str
+ outcome: LiveActionOutcome
+ server: str
+ remote_tool: str | None = None
+ intent_normalized: str | None = None
+ mandate_snapshot_ref: str | None = None
+ consent_record_ref: str | None = None
+ broker_request: dict[str, Any] | None = None
+ broker_response: dict[str, Any] | None = None
+ gate_decision: dict[str, Any] | None = None
+ error: str | None = None
+ audit_id: str = field(default_factory=_new_audit_id)
+ ts: str = field(default_factory=_utc_now_iso_ms)
+
+ def to_record(self) -> dict[str, Any]:
+ """Return the redacted, JSON-serializable record for this event.
+
+ Sensitive keys anywhere in the structure (notably inside
+ ``broker_request`` / ``broker_response``) are replaced with
+ ``[redacted]`` via :func:`src.tools.redaction.redact_payload`. The
+ field order matches the SPEC §5 schema for readability.
+
+ Returns:
+ A new dict safe to append to the ledger and emit on the SSE bus. The
+ event itself is never mutated.
+ """
+ record: dict[str, Any] = {
+ "audit_id": self.audit_id,
+ "ts": self.ts,
+ "session_id": self.session_id,
+ "kind": self.kind,
+ "intent_normalized": self.intent_normalized,
+ "mandate_snapshot_ref": self.mandate_snapshot_ref,
+ "consent_record_ref": self.consent_record_ref,
+ "broker_request": self.broker_request,
+ "broker_response": self.broker_response,
+ "outcome": self.outcome,
+ "gate_decision": self.gate_decision,
+ "server": self.server,
+ "remote_tool": self.remote_tool,
+ "error": self.error,
+ }
+ return redact_payload(record)
+
+
+def write_live_action(
+ event: LiveActionEvent,
+ *,
+ event_callback: EventCallback | None = None,
+ trace_writer: _TraceWriterLike | None = None,
+) -> dict[str, Any]:
+ """Fan a redacted live-action record out to up to three sinks (SPEC §5).
+
+ The record is redacted via :func:`src.tools.redaction.redact_payload` FIRST,
+ before any write or emit, so OAuth tokens / account numbers / PII never reach
+ the ledger, the trace, or a surface. The SAME redacted dict is then sent to
+ every configured sink:
+
+ 1. **Dedicated ledger** (always) — appended as single-line JSONL with a
+ trailing newline to ``<runtime_root>/live/audit.jsonl``, opened in append
+ mode so concurrent writers cannot truncate it (append-only). The directory
+ tree is created ``0700`` on first write.
+ 2. **Per-run trace** (when ``trace_writer`` is given) — written via
+ ``trace_writer.write({...})`` with ``type="live_action"`` so it sits
+ alongside ``tool_call`` / ``tool_result`` in the run dir.
+ 3. **Surface** (when ``event_callback`` is given) — called as
+ ``event_callback("live.action", record)`` so the CLI / frontend renders
+ the action inline. Notifications never gate autonomy (SPEC §5).
+
+ Optional sinks are silently skipped when not supplied, preserving backward
+ compatibility with ledger-only callers (``write_live_action(event)``).
+
+ Args:
+ event: The live-action event to record.
+ event_callback: Optional surface bus ``(event_name, payload)`` callable;
+ skipped when ``None``.
+ trace_writer: Optional per-run trace sink exposing ``write(dict)``;
+ skipped when ``None``.
+
+ Returns:
+ The redacted record dict — identical to what was written to every sink —
+ for the caller to embed or re-emit.
+ """
+ record = event.to_record()
+
+ # Sink 1: dedicated compliance ledger (always, append-only).
+ path = audit_ledger_path()
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ line = json.dumps(record, ensure_ascii=False)
+ with path.open("a", encoding="utf-8") as handle:
+ handle.write(line + "\n")
+
+ # Sink 2: per-run trace (optional). type="live_action" sits alongside
+ # tool_call / tool_result for this run.
+ if trace_writer is not None:
+ trace_writer.write({"type": _LIVE_ACTION_TRACE_TYPE, **record})
+
+ # Sink 3: surface / SSE bus (optional, non-blocking notification).
+ if event_callback is not None:
+ event_callback(_LIVE_ACTION_EVENT, record)
+
+ return record
diff --git a/agent/src/live/classification.py b/agent/src/live/classification.py
new file mode 100644
index 000000000..5498112ba
--- /dev/null
+++ b/agent/src/live/classification.py
@@ -0,0 +1,89 @@
+"""Read/write classification for live-channel remote MCP tools.
+
+We do not own the broker's tool names or schemas — they are discovered at
+runtime from a server we do not control and are invite-gated, so classification
+must be driven by discovery data plus a maintainer-curated map, never a blind
+hardcoded name match that silently lets an unrecognized tool through. Every
+discovered tool resolves to exactly one of three classes via a strict
+precedence ladder (see ``docs/live-trading/SPEC.md`` §7.2):
+
+Tier 1 — MCP tool ``annotations`` (advisory, server-asserted):
+ * ``readOnlyHint is True`` → READ
+ * ``readOnlyHint is False`` → WRITE (an additive-only order is still a write)
+ * ``readOnlyHint is None`` → fall through (absent != read)
+Tier 2 — curated per-broker map: an explicit name→class map. **The map wins**
+ over annotations whenever it names the tool — a server lying with
+ ``readOnlyHint=True`` on its ``place_order`` cannot demote a curated WRITE.
+ Annotations can only *catch* writes the map missed, never *excuse* one.
+Tier 3 — default-deny: anything neither annotated read-only nor in the map is
+ UNKNOWN, handled exactly like WRITE downstream (gate-wrapped, never a plain
+ read tool).
+
+The honesty caveat (from ``mcp.types.ToolAnnotations``'s own docstring):
+*"Clients should never make tool use decisions based on ToolAnnotations
+received from untrusted servers."* So a Tier-1 READ is necessary-but-not-
+sufficient to relax safety — it only downgrades toward read, and only when the
+curated map has not already pinned the tool WRITE.
+"""
+
+from __future__ import annotations
+
+from enum import Enum
+from typing import TYPE_CHECKING, Mapping
+
+if TYPE_CHECKING:
+ from mcp.types import ToolAnnotations
+
+
+class ToolClass(str, Enum):
+ """Read/write classification of a remote MCP tool.
+
+ Attributes:
+ READ: Observed to be read-only — wrapped as a plain ``MCPRemoteTool``.
+ WRITE: Mutates broker state (order placement/cancel) — gate-wrapped.
+ UNKNOWN: Unrecognized — fail-closed, treated identically to WRITE.
+ """
+
+ READ = "read"
+ WRITE = "write"
+ UNKNOWN = "unknown"
+
+
+def classify_tool(
+ name: str,
+ annotations: "ToolAnnotations | None",
+ curated: Mapping[str, ToolClass] | None = None,
+) -> ToolClass:
+ """Classify one remote tool via the 3-tier precedence ladder.
+
+ The curated map is authoritative: when it names the tool, its class is
+ returned regardless of any annotation (a deceptive ``readOnlyHint`` cannot
+ override a curated WRITE). Otherwise an explicit ``readOnlyHint`` decides;
+ an absent hint is NOT treated as read. Anything left over is UNKNOWN.
+
+ Args:
+ name: Remote tool name (the broker's un-prefixed name).
+ annotations: The tool's ``mcp.types.ToolAnnotations``, or ``None`` when
+ the server provided none.
+ curated: Per-broker name→:class:`ToolClass` map (Tier 2). When omitted,
+ only Tiers 1 and 3 apply (so an annotation-less tool is UNKNOWN).
+
+ Returns:
+ The resolved :class:`ToolClass`.
+ """
+ # Tier 2 wins whenever the map names the tool.
+ if curated is not None:
+ pinned = curated.get(name)
+ if pinned is not None:
+ return pinned
+
+ # Tier 1: explicit annotation. Absent (None) hint falls through.
+ if annotations is not None:
+ hint = getattr(annotations, "readOnlyHint", None)
+ if hint is True:
+ return ToolClass.READ
+ if hint is False:
+ return ToolClass.WRITE
+
+ # Tier 3: default-deny.
+ return ToolClass.UNKNOWN
diff --git a/agent/src/live/enforcement.py b/agent/src/live/enforcement.py
new file mode 100644
index 000000000..ac2d6fec3
--- /dev/null
+++ b/agent/src/live/enforcement.py
@@ -0,0 +1,696 @@
+"""Pre-trade mandate enforcement (SPEC.md Mandate Enforcement §5–§6).
+
+This module owns the broker-agnostic order representation
+(:class:`OrderIntent`), the breach contract the consent layer consumes
+(:class:`BreachEvent`, SPEC §6 verbatim), and the pure decision function
+:func:`check_mandate` that the enforcement gate (``src.live.order_guard``) calls
+on every live order before forwarding it to the broker.
+
+Every check is **fail-closed**: any unparseable input, missing market data, or
+ambiguous field denies the order rather than waving it through. Checks run in a
+fixed order — exclude-list → instrument → asset-class → single-order notional →
+total exposure → leverage → daily count → funding (defense-in-depth). The first
+failing check produces the verdict; the broker-side funding ceiling remains the
+backstop the agent physically cannot breach regardless of any data staleness on
+our side.
+
+The verdict is a :class:`BreachEvent` whose ``kind`` is one of
+``"universe"`` / ``"instrument"`` / ``"quantitative"``:
+
+* ``universe`` / ``instrument`` → structural violation; the gate DENIES outright
+ (no widening short of editing the mandate could permit it, and the agent may
+ never edit the mandate).
+* ``quantitative`` → the gate emits the event and PAUSES for re-authorization.
+
+``check_mandate`` returns ``None`` when the order is fully in-mandate (ALLOW).
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
+
+import pandas as pd
+
+from src.live.mandate.model import (
+ AssetClass,
+ InstrumentType,
+ Mandate,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class UniverseDataUnavailable(Exception):
+ """Raised when no data loader can return a usable universe figure.
+
+ Callers treat this exactly like a ``None`` result — fail-closed DENY — but
+ it lets the market-cap / liquidity helpers distinguish "loader said the
+ figure is missing" from "loader chain is entirely unavailable".
+ """
+
+
+#: AssetClass → the loader market key (``backtest.loaders.registry`` fallback
+#: chains). US equities/ETFs route to the ``us_equity`` chain (yfinance →
+#: akshare); crypto routes to the ``crypto`` chain (okx → ccxt).
+_ASSET_CLASS_MARKET: dict[AssetClass, str] = {
+ AssetClass.US_EQUITY: "us_equity",
+ AssetClass.US_ETF: "us_equity",
+ AssetClass.CRYPTO: "crypto",
+}
+
+#: Breach ``kind`` values. ``universe``/``instrument`` are structural (DENY);
+#: ``quantitative`` pauses for re-authorization (SPEC §6).
+BREACH_KIND_UNIVERSE = "universe"
+BREACH_KIND_INSTRUMENT = "instrument"
+BREACH_KIND_QUANTITATIVE = "quantitative"
+
+#: InstrumentType → the AssetClass bucket it belongs to. OPTION has no
+#: universe-level asset-class bucket (the user permits asset classes, not
+#: option chains), so an option is gated purely by ``allowed_instruments``.
+_INSTRUMENT_ASSET_CLASS: dict[InstrumentType, AssetClass] = {
+ InstrumentType.EQUITY: AssetClass.US_EQUITY,
+ InstrumentType.ETF: AssetClass.US_ETF,
+ InstrumentType.CRYPTO: AssetClass.CRYPTO,
+}
+
+
+def instrument_asset_class(instrument_type: InstrumentType) -> AssetClass | None:
+ """Map an :class:`InstrumentType` to its universe :class:`AssetClass` bucket.
+
+ Returns ``None`` for instruments with no equity-style universe bucket (e.g.
+ ``OPTION``), which the quote/universe paths skip. Exposed so the gate can
+ pick the right loader market chain when deriving a quantity quote.
+
+ Args:
+ instrument_type: The order's instrument type.
+
+ Returns:
+ The mapped :class:`AssetClass`, or ``None`` when the instrument has no
+ bucket.
+ """
+ return _INSTRUMENT_ASSET_CLASS.get(instrument_type)
+
+
+@dataclass(frozen=True)
+class OrderIntent:
+ """Broker-agnostic normalized order, units explicit.
+
+ Attributes:
+ symbol: Normalized upper-case symbol (e.g. ``AAPL``, ``BTC-USDT``).
+ side: ``"buy"`` or ``"sell"``.
+ notional_usd: Order notional in USD when derivable.
+ quantity: Share/contract/coin quantity when notional is not given.
+ instrument_type: Mapped :class:`~src.live.mandate.model.InstrumentType`.
+ """
+
+ symbol: str
+ side: str
+ notional_usd: float | None
+ quantity: float | None
+ instrument_type: InstrumentType
+
+
+@dataclass(frozen=True)
+class BreachEvent:
+ """Emitted by the gate when an order would breach a limit.
+
+ Consumed by the consent/re-authorization section. Structural violations
+ (exclude-list, disallowed instrument/asset-class) carry ``kind`` ==
+ ``"universe"`` / ``"instrument"`` and cause an outright DENY, since no
+ widening short of editing the mandate could permit them and the agent may
+ never edit the mandate. Quantitative breaches carry ``kind`` ==
+ ``"quantitative"`` and pause for re-authorization.
+
+ Attributes:
+ broker: Broker key.
+ limit: Which limit tripped (e.g. ``"max_order_notional_usd"``,
+ ``"max_total_exposure_usd"``, ``"max_leverage"``,
+ ``"max_trades_per_day"``).
+ limit_value: The mandate's configured value for that limit.
+ attempted_value: The post-trade value the order would have produced.
+ overage: ``attempted_value - limit_value`` in the limit's native unit.
+ proposed_action: The normalized :class:`OrderIntent` that triggered the
+ breach.
+ remote_tool: Broker remote tool name the agent invoked.
+ created_at: ISO-8601 UTC timestamp.
+ kind: One of ``"universe"`` / ``"instrument"`` / ``"quantitative"`` —
+ the gate routes structural kinds to DENY and quantitative to
+ PAUSE_FOR_REAUTH.
+ detail: Human-readable explanation, mainly for structural breaches whose
+ ``limit_value`` / ``attempted_value`` numbers are not meaningful.
+ """
+
+ broker: str
+ limit: str
+ limit_value: float
+ attempted_value: float
+ overage: float
+ proposed_action: OrderIntent
+ remote_tool: str
+ created_at: str
+ kind: str
+ detail: str = ""
+
+
+def _utc_now_iso() -> str:
+ """Return the current UTC time as an ISO-8601 string."""
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _breach(
+ *,
+ broker: str,
+ remote_tool: str,
+ intent: OrderIntent,
+ kind: str,
+ limit: str,
+ limit_value: float,
+ attempted_value: float,
+ detail: str = "",
+) -> BreachEvent:
+ """Construct a :class:`BreachEvent` with a computed ``overage``."""
+ return BreachEvent(
+ broker=broker,
+ limit=limit,
+ limit_value=limit_value,
+ attempted_value=attempted_value,
+ overage=attempted_value - limit_value,
+ proposed_action=intent,
+ remote_tool=remote_tool,
+ created_at=_utc_now_iso(),
+ kind=kind,
+ detail=detail,
+ )
+
+
+def _resolve_order_notional(intent: OrderIntent) -> float | None:
+ """Return the order's USD notional from ``intent.notional_usd``, fail-closed.
+
+ The gate is responsible for normalizing the intent BEFORE ``check_mandate``
+ runs: when an order carries ``quantity`` (with or without an explicit
+ ``notional_usd``), the gate derives a quantity-implied notional from a live
+ quote and stamps the LARGER of the two onto ``intent.notional_usd`` (see
+ :func:`src.live.order_guard.LiveOrderGuardTool._normalize_intent_notional`).
+ By the time the intent reaches here it therefore always carries a single,
+ authoritative ``notional_usd``; an intent that still lacks one is
+ unresolvable and denies upstream.
+
+ Args:
+ intent: The normalized order intent (notional already reconciled by the
+ gate against any quantity).
+
+ Returns:
+ The order notional in USD, or ``None`` when it cannot be resolved
+ (→ fail-closed DENY upstream).
+ """
+ notional = intent.notional_usd
+ if notional is None:
+ return None
+ try:
+ value = float(notional)
+ except (TypeError, ValueError):
+ return None
+ if value <= 0 or value != value: # reject non-positive and NaN
+ return None
+ return value
+
+
+def last_price_usd(symbol: str, asset_class: AssetClass) -> float | None:
+ """Last traded price (USD) for ``symbol`` via the data loaders, fail-closed.
+
+ The fallback path the gate uses when the broker's own quote read tool is
+ unavailable: pull the most recent daily close from the first available
+ loader in the asset-class market chain (yfinance/akshare for US equity,
+ okx/ccxt for crypto — the project's standard auto-fallback). Used to convert
+ a quantity-only order into a USD notional so the notional cap stays
+ enforceable (SPEC §4).
+
+ Args:
+ symbol: Normalized upper-case symbol.
+ asset_class: The order's universe asset-class bucket.
+
+ Returns:
+ Last close price in USD, or ``None`` when no loader can return a usable
+ price (→ fail-closed DENY upstream — never a wave-through).
+ """
+ try:
+ loader = _resolve_loader(asset_class)
+ except UniverseDataUnavailable:
+ return None
+ end = datetime.now(timezone.utc).date()
+ start = end - timedelta(days=_QUOTE_WINDOW_DAYS)
+ try:
+ frames = loader.fetch(
+ [symbol],
+ start.isoformat(),
+ end.isoformat(),
+ interval="1D",
+ )
+ except Exception as exc: # loader / network failure → fail-closed
+ logger.warning("quote fetch failed for %s via %s: %s", symbol, loader.name, exc)
+ return None
+ frame = frames.get(symbol) if isinstance(frames, dict) else None
+ if frame is None or not isinstance(frame, pd.DataFrame) or frame.empty:
+ return None
+ if "close" not in frame.columns:
+ return None
+ closes = frame["close"].astype(float).dropna()
+ if closes.empty:
+ return None
+ price = float(closes.iloc[-1])
+ return price if price == price and price > 0 else None
+
+
+def _positions_market_value(positions: object) -> float | None:
+ """Sum the USD market value of all open positions, fail-closed.
+
+ Accepts the broker read tool's positions payload in the two shapes the read
+ path may return: a list of position dicts, or a dict envelope with a
+ ``positions`` / ``data`` list. Each position must expose a numeric market
+ value under one of the common keys.
+
+ Args:
+ positions: Positions payload from the broker's read MCP tool.
+
+ Returns:
+ Total market value in USD, or ``None`` when any position cannot be
+ parsed (→ fail-closed DENY upstream).
+ """
+ rows = _coerce_position_rows(positions)
+ if rows is None:
+ return None
+ total = 0.0
+ for row in rows:
+ value = _position_market_value(row)
+ if value is None:
+ return None
+ total += value
+ return total
+
+
+def _coerce_position_rows(positions: object) -> list[dict] | None:
+ """Normalize a positions payload to a list of position dicts."""
+ if isinstance(positions, list):
+ rows = positions
+ elif isinstance(positions, dict):
+ # TODO(L6): pin the exact Robinhood positions envelope key once the real
+ # read-tool schema is observed (get_positions). Until then accept the
+ # common envelope shapes and fail-closed on anything else.
+ rows = positions.get("positions")
+ if rows is None:
+ rows = positions.get("data")
+ if rows is None:
+ # A bare mapping of symbol -> position dict is also accepted.
+ rows = list(positions.values()) if positions else []
+ else:
+ return None
+ if not isinstance(rows, list):
+ return None
+ if not all(isinstance(row, dict) for row in rows):
+ return None
+ return rows
+
+
+def _position_market_value(row: dict) -> float | None:
+ """Extract one position's USD market value, fail-closed.
+
+ Prefers an explicit ``market_value`` field; otherwise derives it from
+ ``quantity`` × (``price`` | ``last_price`` | ``mark_price``). Returns
+ ``None`` if neither is parseable.
+ """
+ for key in ("market_value", "marketValue", "value_usd", "value"):
+ if key in row:
+ parsed = _as_float(row[key])
+ return parsed # may be None → fail-closed upstream
+ qty = None
+ for key in ("quantity", "qty", "shares"):
+ if key in row:
+ qty = _as_float(row[key])
+ break
+ price = None
+ for key in ("price", "last_price", "mark_price", "market_price"):
+ if key in row:
+ price = _as_float(row[key])
+ break
+ if qty is None or price is None:
+ return None
+ return abs(qty) * price
+
+
+def _account_balance_market_value(balance: object) -> float | None:
+ """Return account funding/equity in USD from the balance payload.
+
+ This is read defensively for completeness; mandate leverage math uses the
+ mandate's ``account_funding_usd`` as the denominator per SPEC §5, so this
+ helper is only used to sanity-parse the read payload. Returns ``None`` when
+ unparseable.
+ """
+ if isinstance(balance, dict):
+ for key in ("equity", "buying_power", "cash", "account_value", "total"):
+ if key in balance:
+ return _as_float(balance[key])
+ return _as_float(balance)
+
+
+def _as_float(value: object) -> float | None:
+ """Coerce ``value`` to a finite positive-or-zero float, else ``None``."""
+ try:
+ out = float(value) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return None
+ if out != out: # NaN
+ return None
+ return out
+
+
+def check_mandate(
+ mandate: Mandate,
+ intent: OrderIntent,
+ positions: object,
+ balance: object,
+ *,
+ broker: str,
+ remote_tool: str,
+ daily_count: int,
+) -> BreachEvent | None:
+ """Evaluate one order intent against the mandate (fail-closed).
+
+ Checks run in a fixed order and the first failure produces the verdict:
+ exclude-list, instrument allowance, asset-class allowance (universe market-
+ cap/liquidity), single-order notional, post-trade total exposure, post-trade
+ gross leverage, daily order count, and funding (defense-in-depth). Any
+ unparseable input (bad intent, unreadable positions, missing market data)
+ denies rather than allows.
+
+ Args:
+ mandate: The active, schema-valid, unexpired mandate (validated by the
+ gate before this is called).
+ intent: The normalized order intent extracted from the tool call.
+ positions: Current positions from the broker's read MCP tool.
+ balance: Current balance from the broker's read MCP tool.
+ broker: Broker key (stamped onto any :class:`BreachEvent`).
+ remote_tool: Broker remote tool name the agent invoked.
+ daily_count: Orders already placed today (from the persisted counter,
+ after UTC rollover).
+
+ Returns:
+ ``None`` when the order is fully in-mandate (ALLOW), otherwise a
+ :class:`BreachEvent` describing the first violated rule.
+ """
+ caps = mandate.hard_caps
+ universe = mandate.universe
+
+ symbol = (intent.symbol or "").strip().upper()
+ if not symbol or intent.side not in ("buy", "sell"):
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_INSTRUMENT, limit="order_intent",
+ limit_value=0.0, attempted_value=0.0,
+ detail="order intent missing symbol or side",
+ )
+
+ # 1. Exclude-list — takes precedence over every other universe rule.
+ if symbol in {s.strip().upper() for s in universe.exclude_symbols}:
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_UNIVERSE, limit="exclude_symbols",
+ limit_value=0.0, attempted_value=0.0,
+ detail=f"{symbol} is on the mandate exclude list",
+ )
+
+ # 2. Instrument-type allowance (empty == deny all, fail-closed).
+ if intent.instrument_type not in caps.allowed_instruments:
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_INSTRUMENT, limit="allowed_instruments",
+ limit_value=0.0, attempted_value=0.0,
+ detail=f"{intent.instrument_type.value} not in allowed_instruments",
+ )
+
+ # 3. Asset-class allowance (universe bucket). OPTION has no bucket and is
+ # governed by allowed_instruments alone.
+ asset_class = _INSTRUMENT_ASSET_CLASS.get(intent.instrument_type)
+ if asset_class is not None and asset_class not in universe.asset_classes:
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_UNIVERSE, limit="asset_classes",
+ limit_value=0.0, attempted_value=0.0,
+ detail=f"{asset_class.value} not in permitted asset_classes",
+ )
+
+ # 4. Single-order notional.
+ notional = _resolve_order_notional(intent)
+ if notional is None:
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_INSTRUMENT, limit="order_intent",
+ limit_value=0.0, attempted_value=0.0,
+ detail="order notional could not be resolved",
+ )
+ if notional > caps.max_order_notional_usd:
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_QUANTITATIVE, limit="max_order_notional_usd",
+ limit_value=caps.max_order_notional_usd, attempted_value=notional,
+ )
+
+ # 5–6. Exposure + leverage need observable positions; fail-closed on any
+ # unparseable position. A sell reduces gross exposure (signed by side).
+ current_exposure = _positions_market_value(positions)
+ if current_exposure is None:
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_QUANTITATIVE, limit="max_total_exposure_usd",
+ limit_value=caps.max_total_exposure_usd, attempted_value=0.0,
+ detail="current positions could not be read (fail-closed)",
+ )
+ signed = notional if intent.side == "buy" else -notional
+ post_exposure = current_exposure + signed
+ if post_exposure > caps.max_total_exposure_usd:
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_QUANTITATIVE, limit="max_total_exposure_usd",
+ limit_value=caps.max_total_exposure_usd, attempted_value=post_exposure,
+ )
+
+ # 6. Gross leverage = post-trade gross exposure / account_funding_usd.
+ if caps.account_funding_usd <= 0:
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_QUANTITATIVE, limit="max_leverage",
+ limit_value=caps.max_leverage, attempted_value=float("inf"),
+ detail="account_funding_usd is non-positive (fail-closed)",
+ )
+ post_leverage = abs(post_exposure) / caps.account_funding_usd
+ if post_leverage > caps.max_leverage:
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_QUANTITATIVE, limit="max_leverage",
+ limit_value=caps.max_leverage, attempted_value=post_leverage,
+ )
+
+ # 7. Daily order count (count over UTC calendar days).
+ attempted_count = daily_count + 1
+ if attempted_count > caps.max_trades_per_day:
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_QUANTITATIVE, limit="max_trades_per_day",
+ limit_value=float(caps.max_trades_per_day),
+ attempted_value=float(attempted_count),
+ )
+
+ # 8. Funding (defense-in-depth; broker is the real ceiling). Only a buy can
+ # push us past funding — never block a sell on this.
+ if intent.side == "buy" and post_exposure > caps.account_funding_usd:
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_QUANTITATIVE, limit="account_funding_usd",
+ limit_value=caps.account_funding_usd, attempted_value=post_exposure,
+ detail="post-trade exposure exceeds mirrored funding ceiling",
+ )
+
+ # 9. Expensive universe rules (market-cap / liquidity floors). Fail-closed
+ # on missing data per SPEC §5. Skipped for instruments with no equity
+ # universe bucket (e.g. options) where these floors do not apply.
+ if asset_class is not None:
+ universe_breach = _check_universe_floors(
+ universe, intent, symbol, asset_class,
+ broker=broker, remote_tool=remote_tool,
+ )
+ if universe_breach is not None:
+ return universe_breach
+
+ return None
+
+
+def _check_universe_floors(
+ universe,
+ intent: OrderIntent,
+ symbol: str,
+ asset_class: AssetClass,
+ *,
+ broker: str,
+ remote_tool: str,
+) -> BreachEvent | None:
+ """Enforce market-cap / liquidity floors via the data loaders (fail-closed).
+
+ Both floors are optional (``None`` == no floor). When a floor is set, the
+ figure is fetched from Vibe-Trading's existing loaders (with auto-fallback);
+ if no loader can return a usable figure, the order is DENIED rather than
+ waved through (SPEC §5 fail-closed contract).
+
+ Returns:
+ A universe-kind :class:`BreachEvent`, or ``None`` when both floors pass
+ (or neither is set).
+ """
+ if universe.min_market_cap_usd is not None:
+ try:
+ cap = market_cap_usd(symbol, asset_class)
+ except UniverseDataUnavailable:
+ cap = None
+ if cap is None or cap < universe.min_market_cap_usd:
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_UNIVERSE, limit="min_market_cap_usd",
+ limit_value=universe.min_market_cap_usd,
+ attempted_value=cap if cap is not None else 0.0,
+ detail=(
+ f"market cap for {symbol} unavailable (fail-closed)"
+ if cap is None
+ else f"{symbol} market cap below floor"
+ ),
+ )
+
+ if universe.min_avg_daily_volume_usd is not None:
+ try:
+ adv = avg_daily_dollar_volume(symbol, asset_class)
+ except UniverseDataUnavailable:
+ adv = None
+ if adv is None or adv < universe.min_avg_daily_volume_usd:
+ return _breach(
+ broker=broker, remote_tool=remote_tool, intent=intent,
+ kind=BREACH_KIND_UNIVERSE, limit="min_avg_daily_volume_usd",
+ limit_value=universe.min_avg_daily_volume_usd,
+ attempted_value=adv if adv is not None else 0.0,
+ detail=(
+ f"liquidity for {symbol} unavailable (fail-closed)"
+ if adv is None
+ else f"{symbol} avg daily $ volume below floor"
+ ),
+ )
+
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Universe market-cap / liquidity via the existing data loaders (auto-fallback).
+# ---------------------------------------------------------------------------
+
+#: Trailing window (calendar days) over which average daily dollar volume is
+#: computed from OHLCV. ~30 trading days of context with weekend slack.
+_ADV_WINDOW_DAYS = 45
+
+#: Trailing window (calendar days) the quote fallback fetches to recover the most
+#: recent daily close. A short window with weekend/holiday slack so a Monday
+#: order still resolves Friday's close.
+_QUOTE_WINDOW_DAYS = 10
+
+
+def _resolve_loader(asset_class: AssetClass):
+ """Return the first available data loader for ``asset_class``.
+
+ Raises:
+ UniverseDataUnavailable: When no loader in the market's fallback chain
+ is available (e.g. no network / no credentials).
+ """
+ from backtest.loaders.base import NoAvailableSourceError
+ from backtest.loaders.registry import resolve_loader
+
+ market = _ASSET_CLASS_MARKET.get(asset_class)
+ if market is None:
+ raise UniverseDataUnavailable(f"no loader market for {asset_class.value}")
+ try:
+ return resolve_loader(market)
+ except NoAvailableSourceError as exc:
+ raise UniverseDataUnavailable(str(exc)) from exc
+
+
+def avg_daily_dollar_volume(symbol: str, asset_class: AssetClass) -> float | None:
+ """Trailing average daily dollar volume (USD) for ``symbol``, fail-closed.
+
+ Computed as ``mean(close * volume)`` over the trailing
+ :data:`_ADV_WINDOW_DAYS` of daily OHLCV from the first available loader.
+ This is exact and derivable from data the loaders already return.
+
+ Args:
+ symbol: Normalized upper-case symbol.
+ asset_class: The order's universe asset-class bucket.
+
+ Returns:
+ Average daily dollar volume in USD, or ``None`` when no loader can
+ return usable OHLCV for the symbol (→ fail-closed DENY upstream).
+ """
+ loader = _resolve_loader(asset_class)
+ end = datetime.now(timezone.utc).date()
+ start = end - timedelta(days=_ADV_WINDOW_DAYS)
+ try:
+ frames = loader.fetch(
+ [symbol],
+ start.isoformat(),
+ end.isoformat(),
+ interval="1D",
+ )
+ except Exception as exc: # loader / network failure → fail-closed
+ logger.warning("ADV fetch failed for %s via %s: %s", symbol, loader.name, exc)
+ return None
+ frame = frames.get(symbol) if isinstance(frames, dict) else None
+ if frame is None or not isinstance(frame, pd.DataFrame) or frame.empty:
+ return None
+ if "close" not in frame.columns or "volume" not in frame.columns:
+ return None
+ dollar = (frame["close"].astype(float) * frame["volume"].astype(float)).dropna()
+ if dollar.empty:
+ return None
+ value = float(dollar.mean())
+ return value if value == value and value >= 0 else None
+
+
+def market_cap_usd(symbol: str, asset_class: AssetClass) -> float | None:
+ """Market capitalization (USD) for ``symbol``, fail-closed.
+
+ The existing OHLCV loaders do not expose a unified market-cap field, so this
+ is best-effort: for US equities/ETFs it reads ``yfinance``'s ``.info``
+ when available; it returns ``None`` (→ fail-closed DENY) whenever the figure
+ cannot be obtained. This keeps the contract honest — an unenforceable floor
+ denies rather than waves the order through.
+
+ TODO(L6): once the real Robinhood read-tool catalog is observed, prefer a
+ broker-reported fundamentals/quote figure (and a dedicated fundamentals
+ loader for non-US assets) over the yfinance ``.info`` best-effort below.
+
+ Args:
+ symbol: Normalized upper-case symbol.
+ asset_class: The order's universe asset-class bucket.
+
+ Returns:
+ Market cap in USD, or ``None`` when unavailable.
+ """
+ if asset_class not in (AssetClass.US_EQUITY, AssetClass.US_ETF):
+ # No unified market-cap source for crypto/other here — fail-closed.
+ return None
+ try:
+ import yfinance # type: ignore
+ except Exception:
+ return None
+ try:
+ info = yfinance.Ticker(symbol).info
+ except Exception as exc:
+ logger.warning("market-cap lookup failed for %s: %s", symbol, exc)
+ return None
+ if not isinstance(info, dict):
+ return None
+ cap = info.get("marketCap")
+ parsed = _as_float(cap)
+ return parsed if parsed and parsed > 0 else None
diff --git a/agent/src/live/extractors/__init__.py b/agent/src/live/extractors/__init__.py
new file mode 100644
index 000000000..f694a3850
--- /dev/null
+++ b/agent/src/live/extractors/__init__.py
@@ -0,0 +1,45 @@
+"""Per-broker order-intent extractors (SPEC.md Mandate Enforcement §4).
+
+Vibe-Trading does not control a broker's tool arg schema, so the enforcement
+gate cannot hard-code arg names. Each broker ships an ``extract_order_intent``
+function that maps the broker's ``place_order``-style kwargs to the normalized
+:class:`~src.live.enforcement.OrderIntent`, returning ``None`` (→ DENY) whenever
+a required field is absent, ambiguous, or fails validation — it never guesses.
+
+Extractors register themselves in :data:`BROKER_EXTRACTORS`, keyed by broker.
+The gate looks up the broker's extractor and applies it to the raw tool kwargs.
+"""
+
+from __future__ import annotations
+
+from typing import Callable
+
+from src.live.enforcement import OrderIntent
+from src.live.extractors.robinhood import (
+ extract_order_intent as _robinhood_extract,
+)
+
+#: Signature every broker extractor satisfies.
+OrderIntentExtractor = Callable[[str, dict], "OrderIntent | None"]
+
+#: Broker key → order-intent extractor. Adding a live broker is additive: drop
+#: in an ``extractors/<broker>.py`` and register it here.
+BROKER_EXTRACTORS: dict[str, OrderIntentExtractor] = {
+ "robinhood": _robinhood_extract,
+}
+
+
+def get_extractor(broker: str) -> OrderIntentExtractor | None:
+ """Return the registered extractor for ``broker``, or ``None``.
+
+ Args:
+ broker: Broker key, e.g. ``"robinhood"``.
+
+ Returns:
+ The broker's :data:`OrderIntentExtractor`, or ``None`` when no extractor
+ is registered (→ the gate fail-closes / DENIES).
+ """
+ return BROKER_EXTRACTORS.get(broker.strip().lower())
+
+
+__all__ = ["BROKER_EXTRACTORS", "OrderIntentExtractor", "get_extractor"]
diff --git a/agent/src/live/extractors/robinhood.py b/agent/src/live/extractors/robinhood.py
new file mode 100644
index 000000000..db585f7bf
--- /dev/null
+++ b/agent/src/live/extractors/robinhood.py
@@ -0,0 +1,164 @@
+"""Robinhood order-intent extractor (SPEC.md Mandate Enforcement §4).
+
+Maps Robinhood's ``place_order`` tool kwargs to the normalized
+:class:`~src.live.enforcement.OrderIntent`. Pinned against the frozen Robinhood
+catalog: the only order-placing WRITE tool is ``place_order`` (``cancel_order``
+is a WRITE but not an *order placement* — it carries no notional/quantity to
+enforce, so it is not an order-intent tool here).
+
+``place_order`` is sized by ``symbol`` + ``side`` plus exactly one (or, defended
+against, both) of ``notional_usd`` / ``quantity`` (``dollar_amount`` accepted as
+a notional alias). The extractor maps these concrete fields and returns ``None``
+(→ DENY) on anything missing or ambiguous — it never guesses, so the gate
+defaults to the safe state. Unknown extra keys are ignored. When both a notional
+and a quantity are present the extractor surfaces BOTH; the gate reconciles them
+to the larger enforced notional (closing the notional+quantity bypass).
+"""
+
+from __future__ import annotations
+
+from src.live.enforcement import OrderIntent
+from src.live.mandate.model import InstrumentType
+
+#: Remote tool names this extractor recognizes as order placements. Frozen to
+#: the canonical catalog: ``place_order`` is the sole order-placing WRITE tool
+#: (``cancel_order`` carries no order intent to size).
+_ORDER_TOOLS = frozenset({"place_order"})
+
+#: Accepted side spellings → normalized ``"buy"`` / ``"sell"``.
+_SIDE_ALIASES = {
+ "buy": "buy",
+ "b": "buy",
+ "long": "buy",
+ "sell": "sell",
+ "s": "sell",
+ "short": "sell",
+}
+
+#: Broker instrument-type spellings → :class:`InstrumentType`.
+_INSTRUMENT_ALIASES = {
+ "equity": InstrumentType.EQUITY,
+ "stock": InstrumentType.EQUITY,
+ "stocks": InstrumentType.EQUITY,
+ "etf": InstrumentType.ETF,
+ "option": InstrumentType.OPTION,
+ "options": InstrumentType.OPTION,
+ "crypto": InstrumentType.CRYPTO,
+ "cryptocurrency": InstrumentType.CRYPTO,
+}
+
+#: Order-size keys for the notional path (``dollar_amount`` is the Robinhood
+#: dollar-based order field; ``notional_usd`` is the normalized name).
+_NOTIONAL_KEYS = ("notional_usd", "notional", "dollar_amount", "amount")
+
+#: Order-size keys for the share/contract/coin quantity path.
+_QUANTITY_KEYS = ("quantity", "qty", "shares", "units")
+
+
+def extract_order_intent(remote_name: str, kwargs: dict) -> OrderIntent | None:
+ """Parse Robinhood ``place_order`` kwargs into a normalized :class:`OrderIntent`.
+
+ Returns ``None`` (→ DENY) whenever the tool is not a recognized order tool,
+ a required field is absent, or a field is ambiguous/invalid. Never guesses;
+ unknown extra keys are ignored.
+
+ Args:
+ remote_name: The broker's un-prefixed remote tool name (e.g.
+ ``"place_order"``).
+ kwargs: Raw tool-call arguments the agent passed to the order tool.
+
+ Returns:
+ A normalized :class:`OrderIntent`, or ``None`` when the order cannot be
+ unambiguously parsed.
+ """
+ if remote_name not in _ORDER_TOOLS:
+ return None
+ if not isinstance(kwargs, dict):
+ return None
+
+ symbol = _extract_symbol(kwargs)
+ if symbol is None:
+ return None
+
+ side = _extract_side(kwargs)
+ if side is None:
+ return None
+
+ instrument = _extract_instrument(kwargs)
+ if instrument is None:
+ return None
+
+ notional, quantity = _extract_size(kwargs)
+ # Need at least one of notional / quantity to size the order. Both present is
+ # allowed and surfaced — the gate reconciles to the larger enforced notional.
+ if notional is None and quantity is None:
+ return None
+
+ return OrderIntent(
+ symbol=symbol,
+ side=side,
+ notional_usd=notional,
+ quantity=quantity,
+ instrument_type=instrument,
+ )
+
+
+def _extract_symbol(kwargs: dict) -> str | None:
+ """Return the normalized upper-case symbol, or ``None`` if absent."""
+ for key in ("symbol", "ticker", "instrument"):
+ value = kwargs.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip().upper()
+ return None
+
+
+def _extract_side(kwargs: dict) -> str | None:
+ """Return normalized ``"buy"`` / ``"sell"``, or ``None`` if ambiguous."""
+ for key in ("side", "action", "direction"):
+ value = kwargs.get(key)
+ if isinstance(value, str):
+ normalized = _SIDE_ALIASES.get(value.strip().lower())
+ if normalized is not None:
+ return normalized
+ return None
+
+
+def _extract_instrument(kwargs: dict) -> InstrumentType | None:
+ """Return the mapped :class:`InstrumentType`, or ``None`` if absent/unknown.
+
+ An absent/unknown instrument is ambiguous → DENY (fail-closed), never a
+ silent default.
+ """
+ for key in ("instrument_type", "asset_class", "type", "instrument_class"):
+ value = kwargs.get(key)
+ if isinstance(value, str):
+ mapped = _INSTRUMENT_ALIASES.get(value.strip().lower())
+ if mapped is not None:
+ return mapped
+ return None
+
+
+def _extract_size(kwargs: dict) -> tuple[float | None, float | None]:
+ """Return ``(notional_usd, quantity)``, each parsed or ``None``.
+
+ Both may be returned non-``None`` (a notional+quantity order); the gate
+ reconciles them. An invalid value for a present key yields ``None`` for that
+ path (→ fail-closed downstream if nothing else sizes the order).
+ """
+ notional = _first_positive_float(kwargs, _NOTIONAL_KEYS)
+ quantity = _first_positive_float(kwargs, _QUANTITY_KEYS)
+ return notional, quantity
+
+
+def _first_positive_float(kwargs: dict, keys: tuple[str, ...]) -> float | None:
+ """Return the first present key's value as a positive float, else ``None``."""
+ for key in keys:
+ if key in kwargs:
+ try:
+ value = float(kwargs[key])
+ except (TypeError, ValueError):
+ return None
+ if value != value or value <= 0: # NaN or non-positive
+ return None
+ return value
+ return None
diff --git a/agent/src/live/halt.py b/agent/src/live/halt.py
new file mode 100644
index 000000000..361f6626b
--- /dev/null
+++ b/agent/src/live/halt.py
@@ -0,0 +1,280 @@
+"""Kill switch for the live trading channel (SPEC.md Consent §4).
+
+The kill switch is a single, instant, global halt of all live activity. It is
+enforced at the filesystem layer — **independent of the LLM cooperating** — via
+an out-of-band sentinel file. The enforcement gate (P3) checks
+:func:`halt_flag_set` at the top of every live order tool invocation, before any
+broker call, so the halt works even if the agent loop is wedged mid-iteration,
+the model is looping, or the SSE bus is down.
+
+Authoritative sentinel (SPEC §2 / Consent §4)::
+
+ <runtime_root>/live/HALT # global kill switch; halts ALL brokers
+
+An optional per-broker sentinel (``<runtime_root>/live/<broker>/HALT``) lets a
+single broker channel be halted without stopping others. The global flag always
+wins: when the global sentinel exists, :func:`halt_flag_set` returns ``True`` for
+every broker regardless of per-broker state.
+
+Sentinel payload is a small JSON object so audit can attribute the trip::
+
+ {"tripped_at": "2026-05-29T14:03:11.482000+00:00", "by": "cli", "reason": "..."}
+
+A user (or an external watchdog) may ``touch`` the file directly; a sentinel with
+unreadable / malformed contents is still treated as tripped (fail-closed: the
+file's *existence* is the halt, the JSON is only attribution metadata).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from src.live.paths import broker_dir, live_root
+
+logger = logging.getLogger(__name__)
+
+_HALT_FILENAME = "HALT"
+
+#: Recognized trip sources written into the sentinel's ``by`` field.
+_VALID_BY = ("cli", "frontend", "file")
+
+
+def halt_path() -> Path:
+ """Return the path to the global kill-switch sentinel.
+
+ Returns:
+ ``<runtime_root>/live/HALT``. The file is NOT created here; use
+ :func:`trip_halt` to write it.
+ """
+ return live_root() / _HALT_FILENAME
+
+
+def broker_halt_path(broker: str) -> Path:
+ """Return the path to a per-broker kill-switch sentinel.
+
+ Args:
+ broker: Broker key, e.g. ``"robinhood"``.
+
+ Returns:
+ ``<runtime_root>/live/<broker>/HALT``. Not created here.
+
+ Raises:
+ ValueError: If ``broker`` is invalid (delegated to
+ :func:`src.live.paths.broker_dir`).
+ """
+ return broker_dir(broker) / _HALT_FILENAME
+
+
+def trip_halt(by: str, reason: str, broker: str | None = None) -> Path:
+ """Trip the kill switch by writing a sentinel file.
+
+ Writing is atomic (same-directory temp file + ``os.replace``) so a partial
+ write can never leave a corrupt sentinel that a concurrent
+ :func:`halt_flag_set` would misread. Tripping is idempotent: a fresh sentinel
+ overwrites any prior one, recording the latest trip metadata.
+
+ Args:
+ by: Trip source — one of ``"cli"``, ``"frontend"``, ``"file"``. An
+ unrecognized value is stored verbatim (the file's existence is what
+ enforces the halt; ``by`` is attribution only).
+ reason: Human-readable reason recorded in the sentinel for the audit
+ trail.
+ broker: When ``None`` (default), trips the **global** switch that halts
+ all brokers. When set, trips only that broker's sentinel.
+
+ Returns:
+ The path to the sentinel that was written.
+ """
+ path = broker_halt_path(broker) if broker is not None else halt_path()
+ payload: dict[str, Any] = {
+ "tripped_at": datetime.now(timezone.utc).isoformat(),
+ "by": by,
+ "reason": reason,
+ }
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ tmp = path.with_name(f".{path.name}.tmp")
+ tmp.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
+ tmp.replace(path)
+ logger.warning(
+ "live kill switch tripped (broker=%s, by=%s): %s",
+ broker or "*",
+ by,
+ reason,
+ )
+ return path
+
+
+def clear_halt(broker: str | None = None) -> bool:
+ """Clear a tripped kill switch by deleting its sentinel.
+
+ Clearing is a privileged surface action (never an agent tool). Clearing the
+ global switch does NOT clear per-broker sentinels and vice versa — each is
+ cleared independently.
+
+ Args:
+ broker: When ``None`` (default), clears the global sentinel. When set,
+ clears only that broker's sentinel.
+
+ Returns:
+ ``True`` if a sentinel existed and was removed, ``False`` if there was
+ nothing to clear.
+ """
+ path = broker_halt_path(broker) if broker is not None else halt_path()
+ try:
+ path.unlink()
+ except FileNotFoundError:
+ return False
+ logger.warning("live kill switch cleared (broker=%s)", broker or "*")
+ return True
+
+
+def halt_flag_set(broker: str | None = None) -> bool:
+ """Return whether live trading is halted — a pure filesystem check.
+
+ This is the authoritative kill-switch check the enforcement gate calls before
+ every live order. It performs NO LLM/agent-state lookup and reads NO
+ in-process flag: it is solely the presence of the sentinel file(s), so it
+ holds even when the agent loop is wedged or the model is non-cooperating.
+
+ The global sentinel always halts: if ``<runtime_root>/live/HALT`` exists,
+ this returns ``True`` for any ``broker``. When ``broker`` is given and the
+ global switch is not set, the broker's own sentinel is also consulted.
+
+ Args:
+ broker: Optional broker key. When provided, the per-broker sentinel is
+ checked in addition to the global one. An invalid broker key is
+ treated as halted (fail-closed) rather than raising.
+
+ Returns:
+ ``True`` if live trading is halted (globally, or for ``broker``).
+ """
+ if halt_path().exists():
+ return True
+ if broker is None:
+ return False
+ try:
+ return broker_halt_path(broker).exists()
+ except ValueError:
+ # An unresolvable broker key can never be safely traded — fail closed.
+ return True
+
+
+def read_halt(broker: str | None = None) -> dict[str, Any] | None:
+ """Read the sentinel metadata for a tripped kill switch.
+
+ Args:
+ broker: When ``None``, reads the global sentinel; otherwise the broker's.
+
+ Returns:
+ The parsed sentinel payload (``tripped_at`` / ``by`` / ``reason``), or
+ ``None`` when no sentinel exists. A sentinel that exists but is empty or
+ holds malformed JSON returns an empty dict ``{}`` — the halt is still in
+ effect (existence is authoritative), only its attribution is unreadable.
+ """
+ path = broker_halt_path(broker) if broker is not None else halt_path()
+ if not path.exists():
+ return None
+ try:
+ raw = path.read_text(encoding="utf-8")
+ except OSError:
+ return {}
+ if not raw.strip():
+ return {}
+ try:
+ parsed = json.loads(raw)
+ except json.JSONDecodeError:
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+
+
+# --- Preemptive halt action hook (SPEC §7.5 component 6) -------------------
+#
+# The functions above are the LLM-independent *trigger* (the filesystem
+# sentinel). The hook below is the *action* plumbing: a runner registers a
+# per-broker callable (in practice a closure over
+# ``src.live.runtime.flatten.flatten_and_cancel`` with broker callables bound)
+# and invokes it via :func:`on_halt_action` the moment it observes a trip —
+# cancelling resting orders and (per mandate) flattening positions, instead of
+# merely refusing the next order.
+#
+# This is deliberately a SEPARATE register/invoke pair, NOT auto-fired inside
+# :func:`trip_halt`: ``trip_halt`` must stay a pure, side-effect-bounded
+# sentinel writer (a user / watchdog may also trip the switch by touching the
+# file directly, bypassing ``trip_halt`` entirely — see SPEC §Consent 4.1). The
+# runner observing the sentinel is the single place that drives the preemptive
+# action, so the broker-call side effect is never coupled to the flag write.
+
+from typing import Callable # noqa: E402 — additive import kept local to the hook section
+
+#: Per-broker preemptive-halt actions, keyed by broker. A ``None`` key is the
+#: global default action used when no broker-specific action is registered.
+_HALT_ACTIONS: dict[str | None, Callable[[str], object]] = {}
+
+
+def register_halt_action(
+ action: Callable[[str], object], broker: str | None = None
+) -> None:
+ """Register the preemptive action a runner runs when a halt is observed.
+
+ The action is invoked by :func:`on_halt_action` with the tripped broker key.
+ Registering is idempotent per key: a later registration replaces the prior
+ one. Registering does NOT trip or check the halt — it only wires the action;
+ the filesystem sentinel remains the sole, LLM-independent trigger.
+
+ Args:
+ action: Callable invoked as ``action(broker)`` on a trip. In production
+ this wraps :func:`src.live.runtime.flatten.flatten_and_cancel` with
+ the broker's READ/submit callables bound.
+ broker: Broker this action applies to, or ``None`` (default) to register
+ the fallback action used for any broker lacking a specific one.
+ """
+ _HALT_ACTIONS[broker] = action
+
+
+def unregister_halt_action(broker: str | None = None) -> bool:
+ """Remove a previously registered preemptive-halt action.
+
+ Args:
+ broker: The broker key whose action to remove, or ``None`` for the
+ global fallback.
+
+ Returns:
+ ``True`` if an action was registered and removed, ``False`` otherwise.
+ """
+ return _HALT_ACTIONS.pop(broker, None) is not None
+
+
+def on_halt_action(broker: str) -> object | None:
+ """Run the registered preemptive-halt action for a tripped ``broker``.
+
+ Called by the runner after it observes the HALT sentinel (via
+ :func:`halt_flag_set`) — it does the cancel-resting-orders + optional
+ flatten sweep. A broker-specific action takes precedence over the global
+ fallback. If neither is registered this is a no-op (the cooperative
+ order-time gate still blocks all future orders regardless).
+
+ The action's own exceptions are NOT swallowed here: a failure to flatten is
+ load-bearing and must propagate to the runner's error handling / audit. (The
+ per-broker-call no-retry handling lives inside the action itself.)
+
+ Args:
+ broker: The broker key whose channel was halted.
+
+ Returns:
+ Whatever the registered action returns (e.g. the flatten report dict),
+ or ``None`` when no action is registered for ``broker``.
+ """
+ action = _HALT_ACTIONS.get(broker) or _HALT_ACTIONS.get(None)
+ if action is None:
+ logger.warning(
+ "halt observed for broker=%s but no preemptive action registered "
+ "(cooperative gate still blocks future orders)",
+ broker,
+ )
+ return None
+ logger.warning("running preemptive halt action for broker=%s", broker)
+ return action(broker)
diff --git a/agent/src/live/mandate/__init__.py b/agent/src/live/mandate/__init__.py
new file mode 100644
index 000000000..200d93347
--- /dev/null
+++ b/agent/src/live/mandate/__init__.py
@@ -0,0 +1,9 @@
+"""Bounded-autonomy mandate for the live trading channel.
+
+The mandate is the user-defined safety boundary: quantitative hard caps
+(:class:`~src.live.mandate.model.HardCaps`) plus a discovery universe
+(:class:`~src.live.mandate.model.UniverseConstraint`) plus consent provenance
+(:class:`~src.live.mandate.model.ConsentMeta`). It is loaded read-only at boot
+by :func:`src.live.mandate.store.load_mandate`; there is no agent-reachable
+write path (see ``docs/live-trading/SPEC.md`` §3 trust invariant).
+"""
diff --git a/agent/src/live/mandate/commit.py b/agent/src/live/mandate/commit.py
new file mode 100644
index 000000000..838eb7127
--- /dev/null
+++ b/agent/src/live/mandate/commit.py
@@ -0,0 +1,480 @@
+"""The single mandate writer — the COMMIT half of the consent state machine.
+
+This module is deliberately **not** a tool and **not** importable/registerable
+through the agent tool registry (``src.tools.__init__`` only discovers
+:class:`~src.agent.tools.BaseTool` subclasses; nothing here subclasses it). It
+is a plain function the API surface (``POST /mandate/commit``) calls when a user
+picks a profile. The agent loop has no reference to :func:`commit_mandate`, so
+even a compromised/hallucinating model cannot self-authorize a mandate — the
+only code path that writes one requires the surface-originated ``consent_ack``
+the model never produces (see ``docs/live-trading/SPEC.md`` §3 trust invariant,
+Consent §1, Mandate §2). This is the 命门 invariant: a structural guarantee,
+not a prompt-level one.
+
+The companion :func:`save_proposal` persists the read-only proposals the
+``propose_mandate_profiles`` tool synthesizes (Consent PROPOSE state). A proposal
+is *not* a mandate — persisting it grants no authority — so the tool may write
+proposals; only :func:`commit_mandate` writes the mandate, and only after
+re-validating that the committed profile still fits the ceilings the user saw.
+
+Storage layout (under :func:`src.live.paths.live_root`)::
+
+ <runtime_root>/live/<broker>/mandate.json # 0600, committed mandate
+ <runtime_root>/live/<broker>/proposals/<id>.json # 0600, pending proposals
+ <runtime_root>/live/<broker>/consent/<id>.json # 0600, consent records
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import os
+import uuid
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any, Mapping
+
+from src.live.mandate.model import MANDATE_SCHEMA_VERSION
+from src.live.paths import broker_dir
+
+logger = logging.getLogger(__name__)
+
+#: Default mandate lifetime when a commit does not override it (SPEC §9 dec. 2).
+DEFAULT_MANDATE_LIFETIME_DAYS = 30
+
+_MANDATE_FILENAME = "mandate.json"
+_PROPOSALS_DIRNAME = "proposals"
+_CONSENT_DIRNAME = "consent"
+
+#: Maps every accepted alias of a clamped limit to its CANONICAL name. The
+#: proposal profile, the ceiling snapshot, and the clamp in
+#: ``propose_mandate_tool`` all use slightly different human-vs-schema spellings
+#: for the same limit (e.g. the profile stores ``max_order_usd`` while a ceiling
+#: snapshot may key it ``max_order_notional_usd``). Comparing raw key names would
+#: silently skip a limit whenever the two sides disagree on spelling — turning
+#: the commit-time ceiling re-check into a NO-OP for that field (audit H9). Both
+#: sides are normalized through this map before comparison so the re-check covers
+#: exactly the four fields ``propose_mandate_profiles`` clamps: order notional,
+#: daily trade cap, leverage, and instruments.
+_CEILING_ALIASES: dict[str, str] = {
+ # order notional
+ "max_order_usd": "max_order_notional_usd",
+ "max_order_notional_usd": "max_order_notional_usd",
+ # daily trade cap
+ "daily_trade_cap": "max_trades_per_day",
+ "max_trades_per_day": "max_trades_per_day",
+ # leverage (single spelling, mapped for completeness)
+ "leverage": "leverage",
+ "max_leverage": "leverage",
+ # instrument whitelist
+ "instruments": "allowed_instruments",
+ "allowed_instruments": "allowed_instruments",
+}
+
+
+def _normalize_limits(source: Mapping[str, Any]) -> dict[str, Any]:
+ """Project ``source`` onto canonical limit names for ceiling comparison.
+
+ Only the keys that name a clamped limit (those in :data:`_CEILING_ALIASES`)
+ are carried through; everything else is dropped because it is not a limit the
+ commit-time re-check bounds. When both an alias and its canonical name are
+ present, the canonical name wins (it is the authoritative spelling), so a
+ profile cannot smuggle a wider value past the check under a second spelling.
+
+ Args:
+ source: A profile or ceiling snapshot keyed by human/schema field names.
+
+ Returns:
+ A dict keyed by canonical limit names (a subset of the four clamped
+ limits present in ``source``).
+ """
+ normalized: dict[str, Any] = {}
+ for raw_key, value in source.items():
+ canonical = _CEILING_ALIASES.get(raw_key)
+ if canonical is None:
+ continue
+ # Canonical spelling is authoritative; do not let an alias overwrite it.
+ if canonical == raw_key or canonical not in normalized:
+ normalized[canonical] = value
+ return normalized
+
+
+class CommitError(ValueError):
+ """Raised when a commit request is invalid or its proposal is not live.
+
+ The API layer maps this to a 4xx response. It is a ``ValueError`` subclass
+ so existing ``except ValueError`` handlers keep working.
+ """
+
+
+def _utcnow() -> datetime:
+ """Return the current UTC time (seam for tests)."""
+ return datetime.now(timezone.utc)
+
+
+def _new_id(prefix: str) -> str:
+ """Return a short, sortable-enough opaque id with a typed prefix."""
+ return f"{prefix}_{uuid.uuid4().hex}"
+
+
+def _proposals_dir(broker: str) -> Path:
+ """Return the per-broker pending-proposals directory."""
+ return broker_dir(broker) / _PROPOSALS_DIRNAME
+
+
+def _consent_dir(broker: str) -> Path:
+ """Return the per-broker consent-records directory."""
+ return broker_dir(broker) / _CONSENT_DIRNAME
+
+
+def _atomic_write_json(path: Path, payload: Mapping[str, Any]) -> None:
+ """Write ``payload`` as JSON to ``path`` atomically with 0600 perms.
+
+ The parent directory is created 0700 and the file is written via a
+ same-directory temp file + ``os.replace`` so a partial write can never leave
+ a corrupt record a concurrent reader would misread.
+
+ Args:
+ path: Destination file path.
+ payload: JSON-serializable mapping to persist.
+ """
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ tmp = path.with_name(f".{path.name}.tmp")
+ tmp.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
+ try:
+ os.chmod(tmp, 0o600)
+ except OSError:
+ # Best-effort on platforms without POSIX perms (e.g. Windows).
+ pass
+ os.replace(tmp, path)
+
+
+# ---------------------------------------------------------------------------
+# PROPOSE state — proposal persistence (read-only; grants no authority)
+# ---------------------------------------------------------------------------
+
+
+def save_proposal(proposal: Mapping[str, Any]) -> None:
+ """Persist a synthesized proposal so a later commit can re-validate it.
+
+ Called by the read-only ``propose_mandate_profiles`` tool. Writing a
+ proposal is NOT a mandate write — it confers no trading authority; the
+ proposal is merely the menu of clamped options the user picks from. The
+ proposal record carries the ``ceilings_ref`` snapshot and the resolved
+ limits of every profile, so :func:`commit_mandate` can verify the selected
+ ordinal still fits the ceilings the user actually saw.
+
+ Args:
+ proposal: The ``mandate.proposal`` payload (must contain
+ ``proposal_id``, ``account.broker``, ``ceilings_ref``, and
+ ``profiles``).
+
+ Raises:
+ ValueError: If required keys are missing or the broker key is invalid.
+ """
+ proposal_id = str(proposal.get("proposal_id") or "").strip()
+ if not proposal_id:
+ raise ValueError("proposal must carry a proposal_id")
+ broker = str((proposal.get("account") or {}).get("broker") or "").strip()
+ if not broker:
+ raise ValueError("proposal must carry account.broker")
+ path = _proposals_dir(broker) / f"{proposal_id}.json"
+ _atomic_write_json(path, dict(proposal))
+
+
+def _load_proposal(broker: str, proposal_id: str) -> dict[str, Any] | None:
+ """Load a persisted proposal, or ``None`` when absent/unreadable."""
+ path = _proposals_dir(broker) / f"{proposal_id}.json"
+ if not path.is_file():
+ return None
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as exc:
+ logger.warning("proposal %s for %s is unreadable: %s", proposal_id, broker, exc)
+ return None
+ return raw if isinstance(raw, dict) else None
+
+
+def _invalidate_proposal(broker: str, proposal_id: str) -> None:
+ """Delete a proposal so it can never be committed twice (idempotency)."""
+ try:
+ (_proposals_dir(broker) / f"{proposal_id}.json").unlink()
+ except FileNotFoundError:
+ pass
+
+
+# ---------------------------------------------------------------------------
+# COMMIT state — the single mandate write
+# ---------------------------------------------------------------------------
+
+
+def _resolve_profile(
+ proposal: Mapping[str, Any],
+ ordinal: int,
+ adjustments: Mapping[str, Any] | None,
+) -> dict[str, Any]:
+ """Return the selected profile, applying any per-commit adjustments.
+
+ Adjustments may only *narrow* limits relative to the rendered profile;
+ anything that would widen a limit is rejected (a commit may never authorize
+ more than the user saw — widening goes back through PROPOSE, Consent §3).
+
+ Args:
+ proposal: The persisted proposal record.
+ ordinal: 1-based ordinal of the selected profile.
+ adjustments: Optional narrowing overrides keyed by profile field.
+
+ Returns:
+ The resolved profile dict.
+
+ Raises:
+ CommitError: If the ordinal is out of range or an adjustment widens a
+ limit.
+ """
+ profiles = proposal.get("profiles") or []
+ match = next((p for p in profiles if int(p.get("ordinal", -1)) == ordinal), None)
+ if match is None:
+ raise CommitError(f"selected_ordinal {ordinal} is not in proposal {proposal.get('proposal_id')!r}")
+
+ resolved = dict(match)
+ if adjustments:
+ for key, value in adjustments.items():
+ if key not in resolved:
+ raise CommitError(f"adjustment {key!r} is not a field of the selected profile")
+ current = resolved[key]
+ if isinstance(current, (int, float)) and isinstance(value, (int, float)):
+ if value > current:
+ raise CommitError(
+ f"adjustment {key!r}={value} widens the rendered limit {current}; "
+ "widening must go through a fresh proposal"
+ )
+ resolved[key] = value
+ return resolved
+
+
+def _profile_fits_ceilings(profile: Mapping[str, Any], ceilings: Mapping[str, Any]) -> bool:
+ """Return whether every clamped limit in ``profile`` is within ``ceilings``.
+
+ Both sides are first normalized to canonical limit names (see
+ :func:`_normalize_limits`) so the comparison is robust to alias spellings.
+ Without this the check only compared keys that happened to share an IDENTICAL
+ name on both sides — so a profile keyed ``max_order_usd`` against a ceiling
+ keyed ``max_order_notional_usd`` was never checked at all, and an over-ceiling
+ order notional committed silently (audit H9). After normalization a ceiling
+ that does not bound a given field still imposes no constraint on it, but every
+ field the propose step clamps IS re-checked here regardless of spelling. A
+ cash-only ceiling (``leverage == "none"``) is enforced structurally: a profile
+ may not request leverage the ceiling forbids.
+
+ Args:
+ profile: The resolved profile.
+ ceilings: The ceiling snapshot recorded at propose time.
+
+ Returns:
+ ``True`` when the profile fits the ceilings.
+ """
+ prof = _normalize_limits(profile)
+ caps = _normalize_limits(ceilings)
+ for key, ceiling_value in caps.items():
+ if key not in prof:
+ continue
+ prof_value = prof[key]
+ if isinstance(ceiling_value, (int, float)) and isinstance(prof_value, (int, float)):
+ if prof_value > ceiling_value:
+ return False
+ elif key == "leverage":
+ # Cash-only ceiling forbids any leverage other than "none".
+ if ceiling_value == "none" and prof_value not in ("none", None, 1, 1.0):
+ return False
+ return True
+
+
+def commit_mandate(
+ proposal_id: str,
+ ordinal: int,
+ adjustments: Mapping[str, Any] | None,
+ consent_ack: bool,
+ *,
+ broker: str,
+ account_ref: str = "",
+ session_id: str | None = None,
+ ceilings_ref: Mapping[str, Any] | None = None,
+ lifetime_days: int = DEFAULT_MANDATE_LIFETIME_DAYS,
+ flatten_on_halt: bool | None = None,
+) -> dict[str, Any]:
+ """Write a mandate — the ONLY code path that activates live-trading authority.
+
+ Re-validates that ``proposal_id`` is live and that the resolved profile
+ still fits the ceiling snapshot the user saw, then writes
+ ``<runtime_root>/live/<broker>/mandate.json`` (0600) plus an immutable
+ consent record. The committed proposal is invalidated so it can never be
+ replayed. ``ConsentMeta.expires_at`` defaults to ``created_at + 30 days``.
+
+ This function MUST stay unreachable from the agent loop / tool registry; it
+ is invoked only by the surface commit endpoint, which supplies the
+ surface-originated ``consent_ack`` (Consent §1 / §3).
+
+ Args:
+ proposal_id: Id of the proposal the user selected from.
+ ordinal: 1-based ordinal of the chosen profile.
+ adjustments: Optional narrowing overrides (Consent §3 adjust path).
+ consent_ack: Explicit affirmative the surface sets on user action.
+ **Must be ``True``** — a falsy value rejects the commit.
+ broker: Broker key, e.g. ``"robinhood"``.
+ account_ref: Opaque broker account identifier (never credentials).
+ session_id: Originating session id, recorded in the consent record.
+ ceilings_ref: Optional ceiling snapshot to validate against. When
+ omitted, the snapshot stored on the proposal record is used (the
+ authoritative one the user saw).
+ lifetime_days: Mandate lifetime in days (default 30).
+ flatten_on_halt: Whether a kill-switch trip flattens open positions
+ (vs. cancel-only). ``None`` (the default — keeps this param
+ backward-compatible for the surface endpoint) defers to the selected
+ profile's ``flatten_on_halt`` field, which itself defaults to
+ ``False`` (cancel-only, the safe default). An explicit bool overrides
+ the profile. Persisted on the mandate and read on a halt trip by
+ ``src.live.runtime.flatten`` (SPEC §7.5 #6).
+
+ Returns:
+ ``{"mandate_id", "consent_record_id", "broker", "expires_at",
+ "resolved_profile"}``.
+
+ Raises:
+ CommitError: If ``consent_ack`` is not ``True``, the proposal is not
+ live, the ordinal is invalid, an adjustment widens a limit, or the
+ resolved profile exceeds the ceilings.
+ """
+ if consent_ack is not True:
+ raise CommitError("commit requires an explicit consent_ack=true")
+
+ proposal = _load_proposal(broker, proposal_id)
+ if proposal is None:
+ raise CommitError(f"proposal {proposal_id!r} is not live (already committed, expired, or unknown)")
+
+ resolved = _resolve_profile(proposal, ordinal, adjustments)
+
+ ceilings = dict(ceilings_ref) if ceilings_ref is not None else dict(proposal.get("ceilings") or {})
+ if ceilings and not _profile_fits_ceilings(resolved, ceilings):
+ raise CommitError("resolved profile exceeds the account ceilings — refusing to commit")
+
+ created = _utcnow()
+ expires = created + timedelta(days=max(1, int(lifetime_days)))
+ created_iso = created.isoformat().replace("+00:00", "Z")
+ expires_iso = expires.isoformat().replace("+00:00", "Z")
+
+ # An explicit param wins; otherwise defer to the profile, which defaults to
+ # cancel-only (the safe default) when it carries no flatten_on_halt field.
+ do_flatten_on_halt = (
+ bool(flatten_on_halt)
+ if flatten_on_halt is not None
+ else bool(resolved.get("flatten_on_halt", False))
+ )
+
+ mandate_id = _new_id("mandate")
+ consent_record_id = _new_id("cr")
+
+ # The consent token binds this mandate file to the exact human approval.
+ token_material = f"{proposal_id}|{ordinal}|{consent_record_id}|{created_iso}"
+ consent_token_sha256 = hashlib.sha256(token_material.encode("utf-8")).hexdigest()
+
+ mandate_doc = {
+ "schema_version": MANDATE_SCHEMA_VERSION,
+ "mandate_id": mandate_id,
+ "hard_caps": _profile_to_hard_caps(resolved),
+ "universe": _profile_to_universe(resolved),
+ # Top-level halt-behavior policy (not a quantitative ceiling): read by
+ # the read-only loader onto Mandate.flatten_on_halt; absent => False.
+ "flatten_on_halt": do_flatten_on_halt,
+ "consent": {
+ "created_at": created_iso,
+ "consent_token_sha256": consent_token_sha256,
+ "broker": broker,
+ "account_ref": account_ref,
+ "expires_at": expires_iso,
+ },
+ }
+ _atomic_write_json(broker_dir(broker) / _MANDATE_FILENAME, mandate_doc)
+
+ consent_record = {
+ "consent_record_id": consent_record_id,
+ "mandate_id": mandate_id,
+ "proposal_id": proposal_id,
+ "selected_ordinal": ordinal,
+ "adjustments": dict(adjustments) if adjustments else None,
+ "consent_ack": True,
+ "session_id": session_id,
+ "broker": broker,
+ "account_ref": account_ref,
+ "resolved_profile": resolved,
+ "flatten_on_halt": do_flatten_on_halt,
+ "ceilings_ref": proposal.get("ceilings_ref"),
+ "created_at": created_iso,
+ "expires_at": expires_iso,
+ }
+ _atomic_write_json(_consent_dir(broker) / f"{consent_record_id}.json", consent_record)
+
+ # One-shot: the proposal can never be committed again.
+ _invalidate_proposal(broker, proposal_id)
+
+ logger.warning(
+ "live mandate committed (broker=%s, mandate_id=%s, consent=%s, ordinal=%s)",
+ broker,
+ mandate_id,
+ consent_record_id,
+ ordinal,
+ )
+ return {
+ "mandate_id": mandate_id,
+ "consent_record_id": consent_record_id,
+ "broker": broker,
+ "expires_at": expires_iso,
+ "resolved_profile": resolved,
+ }
+
+
+def _profile_to_hard_caps(profile: Mapping[str, Any]) -> dict[str, Any]:
+ """Map a clamped proposal profile to the mandate ``hard_caps`` section.
+
+ The proposal profile uses the human-facing field names from the consent
+ payload (``max_order_usd``, ``daily_trade_cap``, ``leverage``,
+ ``instruments``); this normalizes them to the persisted mandate schema the
+ read-only store/gate expect.
+
+ Args:
+ profile: The resolved proposal profile.
+
+ Returns:
+ A ``hard_caps`` dict in the persisted mandate schema.
+ """
+ leverage_raw = profile.get("leverage", "none")
+ max_leverage = 1.0 if leverage_raw in ("none", None) else float(leverage_raw)
+ instruments = list(profile.get("instruments") or ["equity"])
+ funding = float(profile.get("account_funding_usd", profile.get("max_total_exposure_usd", 0.0)) or 0.0)
+ max_order = float(profile.get("max_order_usd", 0.0) or 0.0)
+ max_exposure = float(profile.get("max_total_exposure_usd", funding or max_order) or max_order)
+ return {
+ "account_funding_usd": funding or max_exposure,
+ "max_order_notional_usd": max_order,
+ "max_total_exposure_usd": max_exposure,
+ "max_leverage": max_leverage,
+ "allowed_instruments": instruments,
+ "max_trades_per_day": int(profile.get("daily_trade_cap", 0) or 0),
+ }
+
+
+def _profile_to_universe(profile: Mapping[str, Any]) -> dict[str, Any]:
+ """Map a clamped proposal profile to the mandate ``universe`` section.
+
+ Args:
+ profile: The resolved proposal profile.
+
+ Returns:
+ A ``universe`` dict in the persisted mandate schema.
+ """
+ return {
+ "asset_classes": list(profile.get("asset_classes") or ["us_equity"]),
+ "min_market_cap_usd": profile.get("min_market_cap_usd"),
+ "min_avg_daily_volume_usd": profile.get("min_avg_daily_volume_usd"),
+ "exclude_symbols": list(profile.get("exclude_symbols") or []),
+ }
diff --git a/agent/src/live/mandate/model.py b/agent/src/live/mandate/model.py
new file mode 100644
index 000000000..563e80c7b
--- /dev/null
+++ b/agent/src/live/mandate/model.py
@@ -0,0 +1,136 @@
+"""Mandate data model — the immutable bounded-autonomy contract.
+
+Frozen dataclasses (no Pydantic): the mandate is read once at boot and never
+mutated, so plain frozen dataclasses give the strongest immutability guarantee
+with zero validation surface the agent could exploit. See
+``docs/live-trading/SPEC.md`` Mandate §1.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import Enum
+
+MANDATE_SCHEMA_VERSION = 1
+
+
+class InstrumentType(str, Enum):
+ """Instrument classes the broker may report or accept."""
+
+ EQUITY = "equity"
+ ETF = "etf"
+ OPTION = "option"
+ CRYPTO = "crypto"
+
+
+class AssetClass(str, Enum):
+ """Universe-level asset class buckets the user may permit."""
+
+ US_EQUITY = "us_equity"
+ US_ETF = "us_etf"
+ CRYPTO = "crypto"
+
+
+@dataclass(frozen=True)
+class HardCaps:
+ """Layer (a): user-set quantitative ceilings.
+
+ Funding is enforced BROKER-SIDE (Robinhood dedicated agentic account
+ balance) and is the absolute ceiling the agent physically cannot exceed;
+ it is mirrored here only for defense-in-depth pre-trade math, never as the
+ primary guarantee. Every other field is enforced VIBE-SIDE in the gate.
+
+ Attributes:
+ account_funding_usd: Ring-fenced balance in the dedicated agentic
+ account, USD. BROKER-ENFORCED ceiling; mirrored for local math.
+ max_order_notional_usd: Vibe-enforced max single-order notional, USD.
+ max_total_exposure_usd: Vibe-enforced cap on aggregate post-trade
+ market value of all open positions, USD.
+ max_leverage: Vibe-enforced gross leverage multiple. 1.0 == cash-only.
+ allowed_instruments: Vibe-enforced whitelist of tradable instrument
+ types. Empty == deny all (fail-closed).
+ max_trades_per_day: Vibe-enforced count of order placements allowed
+ per UTC calendar day. Counter persisted alongside the mandate.
+ """
+
+ account_funding_usd: float
+ max_order_notional_usd: float
+ max_total_exposure_usd: float
+ max_leverage: float
+ allowed_instruments: tuple[InstrumentType, ...]
+ max_trades_per_day: int
+
+
+@dataclass(frozen=True)
+class UniverseConstraint:
+ """Layer (b): user-set universe the agent picks symbols WITHIN.
+
+ Not a ticker whitelist — that would kill agent discovery. The agent selects
+ individual symbols freely so long as each clears these structural filters.
+
+ Attributes:
+ asset_classes: Permitted asset-class buckets. Empty == deny all.
+ min_market_cap_usd: Market-cap floor, USD. ``None`` == no floor.
+ min_avg_daily_volume_usd: Liquidity floor as trailing avg daily dollar
+ volume, USD. ``None`` == no floor.
+ exclude_symbols: Hard per-symbol denylist (normalized upper-case,
+ e.g. ``BTC-USDT`` style for crypto). Takes precedence over every
+ other universe rule.
+ """
+
+ asset_classes: tuple[AssetClass, ...]
+ min_market_cap_usd: float | None
+ min_avg_daily_volume_usd: float | None
+ exclude_symbols: tuple[str, ...]
+
+
+@dataclass(frozen=True)
+class ConsentMeta:
+ """Provenance proving the user (not the agent) authored this mandate.
+
+ Attributes:
+ created_at: ISO-8601 UTC timestamp the user committed the mandate.
+ consent_token_sha256: Hash of the consent artifact emitted by the
+ consent UX section, binding this file to an explicit human approval.
+ broker: Broker key, e.g. ``"robinhood"``.
+ account_ref: Opaque broker account identifier (NOT credentials).
+ expires_at: ISO-8601 UTC timestamp after which the mandate is dead and
+ the gate fail-closes until the user re-authorizes. Default lifetime
+ 30 days from ``created_at`` (configurable per commit). A live
+ mandate must not live forever — see §9 decision 2.
+ """
+
+ created_at: str
+ consent_token_sha256: str
+ broker: str
+ account_ref: str
+ expires_at: str
+
+
+@dataclass(frozen=True)
+class Mandate:
+ """Immutable bounded-autonomy mandate for one live broker channel.
+
+ Loaded read-only at session boot from the user-side protected store. The
+ agent loop has no constructor or write path to this object (see §2).
+
+ Attributes:
+ schema_version: ``MANDATE_SCHEMA_VERSION`` at write time; gate refuses
+ to operate on an unknown future version (fail-closed).
+ hard_caps: Layer (a) quantitative ceilings.
+ universe: Layer (b) discovery universe.
+ consent: Provenance/consent metadata.
+ flatten_on_halt: Whether a kill-switch trip should flatten open
+ positions (submit closing orders) in addition to cancelling resting
+ orders. ``False`` (the default, and the value an old ``mandate.json``
+ lacking this field loads as) means cancel-only — the safe default.
+ ``True`` is an explicit per-mandate opt-in the user makes at commit.
+ Read by ``src.live.runtime.flatten`` on a halt trip (SPEC §7.5 #6
+ "optionally, per mandate").
+ """
+
+ schema_version: int
+ hard_caps: HardCaps
+ universe: UniverseConstraint
+ consent: ConsentMeta
+ flatten_on_halt: bool = False
diff --git a/agent/src/live/mandate/store.py b/agent/src/live/mandate/store.py
new file mode 100644
index 000000000..9c354e5be
--- /dev/null
+++ b/agent/src/live/mandate/store.py
@@ -0,0 +1,132 @@
+"""Read-only mandate loader.
+
+This module exposes exactly ONE public function, :func:`load_mandate`. There is
+deliberately NO ``save_mandate`` / ``set_mandate`` here or in any module
+importable by the agent loop or registered as a tool — mandate writes happen
+only in the consent UX commit path (``src.live.mandate.commit``, owned by a
+separate parcel), which is not reachable from ``loop.py`` / ``worker.py`` /
+any ``BaseTool.execute()``. This mirrors the #142 swarm-config trust template:
+the protected file is resolved at boot from a fixed user-side path, never from
+caller input, agent tool args, or session ``variables`` (see
+``docs/live-trading/SPEC.md`` §3 trust invariant, Mandate §2).
+
+Loading is fail-closed: a missing file, malformed JSON, or a structurally
+invalid record yields ``None`` so the enforcement gate (P5) denies all orders
+rather than guessing at an unrecognized contract. ``schema_version`` is parsed
+and returned as-is; the gate compares it against
+:data:`~src.live.mandate.model.MANDATE_SCHEMA_VERSION` and fail-closes on a
+mismatch (so an unknown future version is surfaced at the gate, not silently
+coerced here).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+
+from src.live.mandate.model import (
+ AssetClass,
+ ConsentMeta,
+ HardCaps,
+ InstrumentType,
+ Mandate,
+ UniverseConstraint,
+)
+from src.live.paths import broker_dir
+
+logger = logging.getLogger(__name__)
+
+_MANDATE_FILENAME = "mandate.json"
+
+
+def load_mandate(broker: str) -> Mandate | None:
+ """Load the committed mandate for ``broker`` from the protected store.
+
+ Reads ``<runtime_root>/live/<broker>/mandate.json`` (written 0600 by the
+ consent commit path). Parsing is strict and fail-closed: any absent file,
+ unreadable file, malformed JSON, or structurally invalid record returns
+ ``None`` so the gate denies. ``expires_at`` and ``schema_version`` are
+ carried through verbatim for the gate to evaluate.
+
+ Args:
+ broker: Broker key, e.g. ``"robinhood"``.
+
+ Returns:
+ The committed :class:`~src.live.mandate.model.Mandate`, or ``None`` when
+ no valid mandate is on file.
+ """
+ path = broker_dir(broker) / _MANDATE_FILENAME
+ if not path.is_file():
+ return None
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as exc:
+ logger.warning("live mandate for %s is unreadable/invalid JSON: %s", broker, exc)
+ return None
+ try:
+ return _parse_mandate(raw)
+ except (KeyError, TypeError, ValueError) as exc:
+ logger.warning("live mandate for %s failed structural validation: %s", broker, exc)
+ return None
+
+
+def _parse_mandate(raw: object) -> Mandate:
+ """Build a :class:`Mandate` from a decoded JSON object (strict).
+
+ Raises:
+ KeyError: A required field is missing.
+ TypeError: ``raw`` (or a nested section) is not an object.
+ ValueError: An enum value or numeric field cannot be parsed.
+ """
+ if not isinstance(raw, dict):
+ raise TypeError("mandate root must be a JSON object")
+
+ caps = _require_dict(raw["hard_caps"], "hard_caps")
+ universe = _require_dict(raw["universe"], "universe")
+ consent = _require_dict(raw["consent"], "consent")
+
+ hard_caps = HardCaps(
+ account_funding_usd=float(caps["account_funding_usd"]),
+ max_order_notional_usd=float(caps["max_order_notional_usd"]),
+ max_total_exposure_usd=float(caps["max_total_exposure_usd"]),
+ max_leverage=float(caps["max_leverage"]),
+ allowed_instruments=tuple(
+ InstrumentType(value) for value in caps["allowed_instruments"]
+ ),
+ max_trades_per_day=int(caps["max_trades_per_day"]),
+ )
+ universe_constraint = UniverseConstraint(
+ asset_classes=tuple(AssetClass(value) for value in universe["asset_classes"]),
+ min_market_cap_usd=_opt_float(universe["min_market_cap_usd"]),
+ min_avg_daily_volume_usd=_opt_float(universe["min_avg_daily_volume_usd"]),
+ exclude_symbols=tuple(str(value) for value in universe["exclude_symbols"]),
+ )
+ consent_meta = ConsentMeta(
+ created_at=str(consent["created_at"]),
+ consent_token_sha256=str(consent["consent_token_sha256"]),
+ broker=str(consent["broker"]),
+ account_ref=str(consent["account_ref"]),
+ expires_at=str(consent["expires_at"]),
+ )
+ return Mandate(
+ schema_version=int(raw["schema_version"]),
+ hard_caps=hard_caps,
+ universe=universe_constraint,
+ consent=consent_meta,
+ # Optional per-mandate halt-behavior flag (SPEC §7.5 #6). Absent on an
+ # old mandate.json → False (cancel-only, the safe default), keeping the
+ # read backward-compatible. Read on a halt trip by src.live.runtime.flatten.
+ flatten_on_halt=bool(raw.get("flatten_on_halt", False)),
+ )
+
+
+def _require_dict(value: object, field: str) -> dict:
+ """Return ``value`` as a dict or raise ``TypeError`` naming ``field``."""
+ if not isinstance(value, dict):
+ raise TypeError(f"mandate field {field!r} must be a JSON object")
+ return value
+
+
+def _opt_float(value: object) -> float | None:
+ """Coerce an optional numeric field to ``float | None``."""
+ return None if value is None else float(value)
diff --git a/agent/src/live/order_guard.py b/agent/src/live/order_guard.py
new file mode 100644
index 000000000..6caf092f4
--- /dev/null
+++ b/agent/src/live/order_guard.py
@@ -0,0 +1,731 @@
+"""Pre-trade enforcement gate (SPEC.md Mandate Enforcement §3).
+
+:class:`LiveOrderGuardTool` is the dedicated wrapper that owns the live-order
+gate. It subclasses :class:`~src.tools.mcp.MCPRemoteTool` and is instantiated
+only for a broker's order-placing (WRITE/UNKNOWN) remote tools; every read tool
+keeps the untouched plain ``MCPRemoteTool.execute()`` path with no gate.
+
+On every ``execute()`` it runs, in order and **all fail-closed** before any
+broker call:
+
+1. ``load_mandate`` — no valid mandate / unknown schema version → DENY.
+2. expiry — past ``consent.expires_at`` → DENY (routes to re-auth).
+3. ``halt_flag_set`` — kill switch tripped → DENY, NO remote call.
+4. ``extract_order_intent`` — unparseable order → DENY.
+5. read positions + balance via the broker's READ MCP tools (plain path).
+6. ``check_mandate`` — ALLOW (forward via ``super().execute``) / DENY
+ (structural: universe|instrument) / PAUSE_FOR_REAUTH (quantitative).
+
+The daily ``trade_counter.json`` is incremented only on a confirmed ALLOW whose
+forwarded broker result is **non-error** (``MCPServerAdapter.call_tool`` returns
+an error envelope, it does not raise — a failed forward never placed an order and
+never consumes a count), with UTC-date rollover. Every decision writes one
+live-action audit event via :func:`src.live.audit.write_live_action`, and the
+returned tool_result carries that redacted record under the frozen
+``"live_action"`` key so the api_server SSE relay can emit a ``live.action``
+event without touching the agent loop.
+
+When the order is sized by ``quantity``, the gate derives a live quote (broker
+``get_quotes`` READ tool first, then the data loaders) and enforces the LARGER of
+the explicit notional and ``quantity`` × price — fail-closed DENY when no quote
+is obtainable — so the notional/exposure/leverage caps stay enforceable.
+
+``repeatable = False`` mirrors the no-retry stance in
+``MCPServerAdapter._call_tool`` — a live order must never be silently re-issued.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from datetime import datetime, timezone
+from typing import Any
+
+from src.live.audit import LiveActionEvent, write_live_action
+from src.live.enforcement import (
+ BREACH_KIND_INSTRUMENT,
+ BREACH_KIND_UNIVERSE,
+ BreachEvent,
+ OrderIntent,
+ check_mandate,
+ instrument_asset_class,
+ last_price_usd,
+)
+from src.live.extractors import get_extractor
+from src.live.halt import halt_flag_set
+from src.live.mandate.model import MANDATE_SCHEMA_VERSION, Mandate
+from src.live.mandate.store import load_mandate
+from src.live.paths import broker_dir
+from src.tools.mcp import MCPRemoteTool, MCPRemoteToolSpec, MCPServerAdapter
+
+logger = logging.getLogger(__name__)
+
+_COUNTER_FILENAME = "trade_counter.json"
+
+#: Frozen marker key the api_server SSE relay reads off the returned tool_result
+#: to emit a ``live.action`` event without touching the agent loop.
+LIVE_ACTION_RESULT_KEY = "live_action"
+
+#: Canonical Robinhood READ tools the gate uses to snapshot positions/balance
+#: and (for quantity orders) a live quote. Pinned to the frozen catalog: READ =
+#: {get_account, get_positions, get_quotes, list_orders}.
+_POSITIONS_TOOLS = ("get_positions",)
+_BALANCE_TOOLS = ("get_account",)
+_QUOTE_TOOLS = ("get_quotes",)
+
+_DECISION_ALLOW = "allow"
+_DECISION_DENY = "deny"
+_DECISION_PAUSE = "pause_for_reauth"
+
+
+class LiveOrderGuardTool(MCPRemoteTool):
+ """Mandate-enforcing wrapper for a broker's order-placing remote tool."""
+
+ repeatable = False
+ is_readonly = False
+
+ def __init__(
+ self,
+ adapter: MCPServerAdapter,
+ spec: MCPRemoteToolSpec,
+ *,
+ broker: str | None = None,
+ session_id: str = "",
+ ) -> None:
+ """Initialize the gate wrapper.
+
+ Args:
+ adapter: Adapter used to invoke the remote server (read + write).
+ spec: Resolved local metadata for the order-placing remote tool.
+ broker: Broker key for mandate/counter/halt lookups. Defaults to the
+ spec's ``server_name`` (the channel is keyed by broker, e.g.
+ ``"robinhood"``).
+ session_id: Originating session id, stamped onto audit events.
+ """
+ super().__init__(adapter, spec)
+ self.broker = (broker or spec.server_name or "").strip().lower()
+ self.session_id = session_id
+
+ @property
+ def remote_name(self) -> str:
+ """The broker's un-prefixed remote tool name (e.g. ``place_order``)."""
+ return self._spec.remote_name
+
+ def execute(self, **kwargs: Any) -> str:
+ """Run the pre-trade gate, then ALLOW / DENY / PAUSE the order.
+
+ Args:
+ **kwargs: Order-tool arguments from the agent loop.
+
+ Returns:
+ JSON string: on ALLOW, the forwarded broker result; otherwise a
+ structured refusal envelope (``status: "blocked"``) carrying the
+ decision and, for quantitative breaches, the :class:`BreachEvent`.
+ """
+ mandate = load_mandate(self.broker)
+ if mandate is None or mandate.schema_version != MANDATE_SCHEMA_VERSION:
+ return self._deny(
+ reason="no valid mandate on file",
+ checked=["mandate"],
+ mandate=mandate,
+ )
+
+ if self._is_expired(mandate):
+ return self._deny(
+ reason="mandate expired — re-authorize",
+ checked=["mandate", "expiry"],
+ mandate=mandate,
+ reauth=True,
+ )
+
+ if halt_flag_set(self.broker):
+ return self._deny(
+ reason="live trading halted",
+ checked=["mandate", "expiry", "halt_flag"],
+ mandate=mandate,
+ )
+
+ extractor = get_extractor(self.broker)
+ intent = extractor(self.remote_name, kwargs) if extractor is not None else None
+ if intent is None:
+ return self._deny(
+ reason="order intent could not be parsed",
+ checked=["mandate", "expiry", "halt_flag", "intent"],
+ mandate=mandate,
+ )
+
+ # Reconcile any quantity into a single authoritative notional BEFORE the
+ # mandate checks so a {notional_usd, quantity} pair can't bypass the
+ # notional cap (H3) and a quantity-only order stays cap-enforceable (H4).
+ intent = self._normalize_intent_notional(intent)
+ if intent is None:
+ return self._deny(
+ reason="quantity order notional could not be priced (fail-closed)",
+ checked=["mandate", "expiry", "halt_flag", "intent", "quote"],
+ mandate=mandate,
+ )
+
+ positions = self._read_first(_POSITIONS_TOOLS)
+ balance = self._read_first(_BALANCE_TOOLS)
+ daily_count = self._read_daily_count()
+
+ breach = check_mandate(
+ mandate,
+ intent,
+ positions,
+ balance,
+ broker=self.broker,
+ remote_tool=self.remote_name,
+ daily_count=daily_count,
+ )
+
+ if breach is None:
+ return self._allow(mandate=mandate, intent=intent, kwargs=kwargs)
+
+ if breach.kind in (BREACH_KIND_UNIVERSE, BREACH_KIND_INSTRUMENT):
+ return self._deny_breach(breach, mandate=mandate, intent=intent, reauth=False)
+ return self._deny_breach(breach, mandate=mandate, intent=intent, reauth=True)
+
+ # -- intent normalization (quantity → notional) -------------------------
+
+ def _normalize_intent_notional(self, intent: OrderIntent) -> OrderIntent | None:
+ """Stamp a single authoritative ``notional_usd`` onto the intent.
+
+ Closes two bypasses (SPEC §4):
+
+ * **H3** — an order carrying BOTH ``notional_usd`` and ``quantity`` is
+ enforced on the LARGER of (explicit notional, ``quantity`` × live
+ price), so a small notional can't smuggle a huge quantity past the
+ notional / exposure / leverage math.
+ * **H4** — a quantity-only order derives its notional from a live quote
+ so the notional cap stays enforceable.
+
+ Fail-closed: when ``quantity`` is present but NO quote can be obtained
+ from the broker quote tool or any data loader, the order is DENIED
+ (returns ``None``) rather than waved through. When no ``quantity`` is
+ present the intent passes through unchanged (its explicit notional, if
+ any, is validated downstream).
+
+ Args:
+ intent: The extractor's normalized intent.
+
+ Returns:
+ A new :class:`OrderIntent` with ``notional_usd`` set to the enforced
+ value, or ``None`` when a quantity order cannot be priced.
+ """
+ if intent.quantity is None:
+ return intent
+
+ price = self._quote_price(intent)
+ if price is None:
+ return None
+ implied = intent.quantity * price
+ if implied != implied or implied <= 0: # NaN / non-positive → fail-closed
+ return None
+
+ explicit = intent.notional_usd if intent.notional_usd is not None else 0.0
+ enforced = max(float(explicit), implied)
+ return OrderIntent(
+ symbol=intent.symbol,
+ side=intent.side,
+ notional_usd=enforced,
+ quantity=intent.quantity,
+ instrument_type=intent.instrument_type,
+ )
+
+ def _quote_price(self, intent: OrderIntent) -> float | None:
+ """Return a live USD price for the intent's symbol, fail-closed.
+
+ Prefers the broker's READ quote tool (``get_quotes``) so the price is
+ the broker's own; falls back to Vibe-Trading's data loaders
+ (:func:`src.live.enforcement.last_price_usd`, standard auto-fallback)
+ when the broker quote is unavailable. Returns ``None`` when no source
+ yields a usable price.
+
+ Args:
+ intent: The order intent whose symbol is priced.
+
+ Returns:
+ A positive USD price, or ``None`` (→ fail-closed DENY upstream).
+ """
+ broker_price = self._broker_quote_price(intent.symbol)
+ if broker_price is not None:
+ return broker_price
+ asset_class = instrument_asset_class(intent.instrument_type)
+ if asset_class is None:
+ return None
+ try:
+ return last_price_usd(intent.symbol, asset_class)
+ except Exception as exc: # loader chain failure → fail-closed
+ logger.warning("loader quote failed for %s: %s", intent.symbol, exc)
+ return None
+
+ def _broker_quote_price(self, symbol: str) -> float | None:
+ """Read a USD price for ``symbol`` from the broker's quote tool.
+
+ Calls the ungated read path (never the guard) for ``get_quotes`` with the
+ symbol argument and parses a price from the common envelope shapes.
+ Returns ``None`` on any error envelope, missing field, or unparseable
+ value — the caller then falls back to the data loaders.
+
+ Args:
+ symbol: Normalized upper-case symbol.
+
+ Returns:
+ A positive USD price, or ``None``.
+ """
+ for remote in _QUOTE_TOOLS:
+ try:
+ result = self._adapter.call_tool(
+ remote, {"symbol": symbol}, local_name=remote
+ )
+ except Exception as exc:
+ logger.warning("broker quote tool %s failed: %s", remote, exc)
+ continue
+ if isinstance(result, dict) and result.get("status") == "error":
+ continue
+ price = _parse_quote_price(result, symbol)
+ if price is not None:
+ return price
+ return None
+
+ # -- decision helpers ---------------------------------------------------
+
+ def _allow(self, *, mandate: Mandate, intent: OrderIntent, kwargs: dict) -> str:
+ """Forward the order unchanged; consume a count + audit only on success.
+
+ ``MCPServerAdapter.call_tool`` does NOT raise on broker/network failure —
+ it returns a ``{"status": "error", ...}`` envelope. So the gate inspects
+ the forwarded payload (H2):
+
+ * **non-error** → increment the daily counter and audit
+ ``kind="order_placed"`` / ``outcome="accepted"``.
+ * **error envelope** → audit ``kind="order_rejected"`` /
+ ``outcome="error"`` and do NOT consume a daily count (a failed forward
+ never placed an order).
+
+ Either way the returned tool_result carries the redacted audit record
+ under :data:`LIVE_ACTION_RESULT_KEY` so the api_server SSE relay can emit
+ a ``live.action`` event without touching the agent loop (H5).
+ """
+ forwarded = super().execute(**kwargs)
+ broker_response = self._safe_json(forwarded)
+ is_error = self._is_error_envelope(broker_response)
+
+ checked = [
+ "mandate", "expiry", "halt_flag", "intent",
+ "exclude_symbols", "allowed_instruments", "asset_classes",
+ "max_order_notional_usd", "max_total_exposure_usd",
+ "max_leverage", "max_trades_per_day", "account_funding_usd",
+ "universe_floors",
+ ]
+ if is_error:
+ record = self._audit(
+ kind="order_rejected",
+ outcome="error",
+ mandate=mandate,
+ intent=intent,
+ broker_request=dict(kwargs),
+ broker_response=broker_response,
+ gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked},
+ error=self._error_message(broker_response),
+ )
+ else:
+ # Only a confirmed ALLOW + non-error forward consumes a daily count.
+ self._increment_daily_count()
+ record = self._audit(
+ kind="order_placed",
+ outcome="accepted",
+ mandate=mandate,
+ intent=intent,
+ broker_request=dict(kwargs),
+ broker_response=broker_response,
+ gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked},
+ )
+ return self._embed_live_action(forwarded, record)
+
+ def _deny(
+ self,
+ *,
+ reason: str,
+ checked: list[str],
+ mandate: Mandate | None,
+ reauth: bool = False,
+ ) -> str:
+ """Audit + return a refusal envelope for a pre-intent / structural DENY."""
+ record = self._audit(
+ kind="order_rejected",
+ outcome="blocked",
+ mandate=mandate,
+ intent=None,
+ broker_request=None,
+ broker_response=None,
+ gate_decision={"allowed": False, "decision": _DECISION_DENY, "checked_limits": checked},
+ error=reason,
+ )
+ return self._refusal(
+ decision=_DECISION_DENY, reason=reason, reauth=reauth, record=record
+ )
+
+ def _deny_breach(
+ self,
+ breach: BreachEvent,
+ *,
+ mandate: Mandate,
+ intent: OrderIntent,
+ reauth: bool,
+ ) -> str:
+ """Audit + return a refusal for a ``check_mandate`` breach.
+
+ Structural breaches (``reauth=False``) DENY outright; quantitative
+ breaches (``reauth=True``) PAUSE for re-authorization and surface the
+ full :class:`BreachEvent` so the consent layer can render a widen-prompt.
+ """
+ decision = _DECISION_PAUSE if reauth else _DECISION_DENY
+ record = self._audit(
+ kind="breach",
+ outcome="blocked",
+ mandate=mandate,
+ intent=intent,
+ broker_request=None,
+ broker_response=None,
+ gate_decision={
+ "allowed": False,
+ "decision": decision,
+ "limit": breach.limit,
+ "kind": breach.kind,
+ "limit_value": breach.limit_value,
+ "attempted_value": breach.attempted_value,
+ },
+ error=breach.detail or f"order breaches {breach.limit}",
+ )
+ return self._refusal(
+ decision=decision,
+ reason=breach.detail or f"order breaches {breach.limit}",
+ reauth=reauth,
+ breach=breach,
+ record=record,
+ )
+
+ def _refusal(
+ self,
+ *,
+ decision: str,
+ reason: str,
+ reauth: bool,
+ breach: BreachEvent | None = None,
+ record: dict | None = None,
+ ) -> str:
+ """Build the structured refusal envelope returned to the agent loop."""
+ payload: dict[str, Any] = {
+ "status": "blocked",
+ "decision": decision,
+ "reason": reason,
+ "broker": self.broker,
+ "remote_tool": self.remote_name,
+ "requires_reauthorization": reauth,
+ }
+ if record is not None:
+ payload[LIVE_ACTION_RESULT_KEY] = record
+ if breach is not None:
+ payload["breach"] = {
+ "broker": breach.broker,
+ "limit": breach.limit,
+ "limit_value": breach.limit_value,
+ "attempted_value": breach.attempted_value,
+ "overage": breach.overage,
+ "remote_tool": breach.remote_tool,
+ "created_at": breach.created_at,
+ "kind": breach.kind,
+ "detail": breach.detail,
+ "proposed_action": {
+ "symbol": breach.proposed_action.symbol,
+ "side": breach.proposed_action.side,
+ "notional_usd": breach.proposed_action.notional_usd,
+ "quantity": breach.proposed_action.quantity,
+ "instrument_type": breach.proposed_action.instrument_type.value,
+ },
+ }
+ return json.dumps(payload, ensure_ascii=False)
+
+ # -- read snapshot ------------------------------------------------------
+
+ def _read_first(self, candidates: tuple[str, ...]) -> object:
+ """Read the first responsive broker read tool, fail-closed.
+
+ Routes through the plain ``MCPServerAdapter.call_tool`` path (NOT the
+ guard) so reads are never gated. Returns ``None`` on any error envelope
+ or exception so the downstream check fail-closes.
+
+ Args:
+ candidates: Ordered remote read-tool names to try.
+
+ Returns:
+ The first successful tool result payload, or ``None``.
+ """
+ for remote in candidates:
+ try:
+ result = self._adapter.call_tool(remote, {}, local_name=remote)
+ except Exception as exc:
+ logger.warning("live read tool %s failed: %s", remote, exc)
+ continue
+ if isinstance(result, dict) and result.get("status") == "error":
+ continue
+ return result
+ return None
+
+ # -- daily counter ------------------------------------------------------
+
+ def _counter_path(self):
+ """Return the per-broker ``trade_counter.json`` path."""
+ return broker_dir(self.broker) / _COUNTER_FILENAME
+
+ def _read_daily_count(self) -> int:
+ """Return today's order count from the persisted counter (UTC rollover).
+
+ A missing/unreadable counter, or one stamped with a previous UTC date,
+ reads as ``0``. Parse failure reads as ``0`` (the count is advisory; the
+ broker enforces the hard ceiling).
+ """
+ path = self._counter_path()
+ if not path.is_file():
+ return 0
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return 0
+ if not isinstance(raw, dict) or raw.get("date") != _utc_today():
+ return 0
+ try:
+ return int(raw.get("count", 0))
+ except (TypeError, ValueError):
+ return 0
+
+ def _increment_daily_count(self) -> None:
+ """Persist today's incremented order count (UTC rollover, atomic write)."""
+ today = _utc_today()
+ count = self._read_daily_count() + 1
+ path = self._counter_path()
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ tmp = path.with_name(f".{path.name}.tmp")
+ tmp.write_text(
+ json.dumps({"date": today, "count": count}, ensure_ascii=False),
+ encoding="utf-8",
+ )
+ tmp.replace(path)
+
+ # -- audit + misc -------------------------------------------------------
+
+ def _audit(
+ self,
+ *,
+ kind: str,
+ outcome: str,
+ mandate: Mandate | None,
+ intent: OrderIntent | None,
+ broker_request: dict | None,
+ broker_response: dict | None,
+ gate_decision: dict,
+ error: str | None = None,
+ ) -> dict | None:
+ """Write one live-action audit event and return the redacted record.
+
+ The returned record (identical to what was written to the ledger) is
+ embedded under :data:`LIVE_ACTION_RESULT_KEY` in the tool_result so the
+ SSE relay can emit a ``live.action`` event. Auditing must never block a
+ decision, so a write failure logs and returns ``None``.
+
+ Returns:
+ The redacted audit record, or ``None`` when the write failed.
+ """
+ consent = mandate.consent if mandate is not None else None
+ try:
+ event = LiveActionEvent(
+ kind=kind, # type: ignore[arg-type]
+ session_id=self.session_id,
+ outcome=outcome, # type: ignore[arg-type]
+ server=self.broker,
+ remote_tool=self.remote_name,
+ intent_normalized=_describe_intent(intent),
+ mandate_snapshot_ref=consent.consent_token_sha256 if consent else None,
+ consent_record_ref=consent.account_ref if consent else None,
+ broker_request=broker_request,
+ broker_response=broker_response,
+ gate_decision=gate_decision,
+ error=error,
+ )
+ return _record_live_action(event)
+ except Exception as exc: # auditing must never block a decision
+ logger.warning("live-action audit write failed (%s): %s", kind, exc)
+ return None
+
+ def _is_expired(self, mandate: Mandate) -> bool:
+ """Return whether the mandate is past its ``expires_at`` (fail-closed).
+
+ An unparseable ``expires_at`` is treated as expired (fail-closed): a
+ live mandate with a malformed expiry must not keep trading.
+ """
+ raw = mandate.consent.expires_at
+ try:
+ expires = datetime.fromisoformat(raw)
+ except (TypeError, ValueError):
+ return True
+ if expires.tzinfo is None:
+ expires = expires.replace(tzinfo=timezone.utc)
+ return datetime.now(timezone.utc) >= expires
+
+ @staticmethod
+ def _safe_json(text: str) -> dict | None:
+ """Best-effort parse of the forwarded broker result for the audit record."""
+ try:
+ parsed = json.loads(text)
+ except (TypeError, ValueError):
+ return {"raw": text}
+ return parsed if isinstance(parsed, dict) else {"raw": parsed}
+
+ @staticmethod
+ def _is_error_envelope(broker_response: dict | None) -> bool:
+ """Whether the forwarded result is an error envelope (H2).
+
+ ``MCPServerAdapter.call_tool`` returns ``{"status": "error", ...}`` on
+ broker/network failure without raising. Treats a missing/unparseable
+ response as an error too (fail-closed: no order was confirmed placed).
+ """
+ if not isinstance(broker_response, dict):
+ return True
+ return str(broker_response.get("status", "")).lower() == "error"
+
+ @staticmethod
+ def _error_message(broker_response: dict | None) -> str:
+ """Extract a human-readable error from an error envelope."""
+ if isinstance(broker_response, dict):
+ for key in ("error", "message", "detail"):
+ value = broker_response.get(key)
+ if isinstance(value, str) and value:
+ return value
+ return "broker forward returned an error"
+
+ @staticmethod
+ def _embed_live_action(forwarded: str, record: dict | None) -> str:
+ """Embed the redacted audit record under the frozen live-action key (H5).
+
+ The forwarded broker result is a JSON object string; the record is added
+ as a top-level ``live_action`` key so the api_server SSE relay can emit a
+ ``live.action`` event without touching ``loop.py``. If the result isn't a
+ JSON object or there is no record, the forwarded string is returned
+ unchanged.
+ """
+ if record is None:
+ return forwarded
+ try:
+ payload = json.loads(forwarded)
+ except (TypeError, ValueError):
+ return forwarded
+ if not isinstance(payload, dict):
+ return forwarded
+ payload[LIVE_ACTION_RESULT_KEY] = record
+ return json.dumps(payload, ensure_ascii=False)
+
+
+def _record_live_action(event: LiveActionEvent) -> dict | None:
+ """Call ``write_live_action`` with the keyword contract, fall back positional.
+
+ The frozen contract is
+ ``write_live_action(event, *, event_callback=None, trace_writer=None)`` (G2
+ is updating the signature). If only the positional form exists today, the
+ keyword call raises ``TypeError`` and we retry positionally so this parcel
+ works against either signature.
+ """
+ try:
+ return write_live_action(event, event_callback=None, trace_writer=None)
+ except TypeError:
+ return write_live_action(event)
+
+
+def _parse_quote_price(result: object, symbol: str) -> float | None:
+ """Extract a positive USD price from a broker quote-tool payload, fail-closed.
+
+ Accepts the common envelope shapes a ``get_quotes`` read tool may return:
+
+ * a flat dict with a price field (``price`` / ``last_price`` / ``last`` /
+ ``mark_price`` / ``ask`` / ``bid``);
+ * a dict keyed by symbol → quote dict;
+ * a dict with a ``quotes`` / ``data`` list of quote dicts (matched on
+ ``symbol`` / ``ticker`` when present, else the sole entry).
+
+ Unknown extra keys are ignored, never guessed. Returns ``None`` on anything
+ unparseable so the caller falls back to the data loaders.
+
+ Args:
+ result: The broker quote tool's normalized payload.
+ symbol: The normalized upper-case symbol requested.
+
+ Returns:
+ A positive USD price, or ``None``.
+ """
+ if not isinstance(result, dict):
+ return None
+
+ direct = _price_from_quote_dict(result)
+ if direct is not None:
+ return direct
+
+ keyed = result.get(symbol)
+ if isinstance(keyed, dict):
+ price = _price_from_quote_dict(keyed)
+ if price is not None:
+ return price
+
+ for container_key in ("quotes", "data", "results"):
+ rows = result.get(container_key)
+ if not isinstance(rows, list):
+ continue
+ match = _match_quote_row(rows, symbol)
+ if match is not None:
+ price = _price_from_quote_dict(match)
+ if price is not None:
+ return price
+ return None
+
+
+def _match_quote_row(rows: list, symbol: str) -> dict | None:
+ """Pick the quote row for ``symbol`` from a list, or the sole entry."""
+ dict_rows = [row for row in rows if isinstance(row, dict)]
+ for row in dict_rows:
+ for key in ("symbol", "ticker", "instrument"):
+ value = row.get(key)
+ if isinstance(value, str) and value.strip().upper() == symbol:
+ return row
+ return dict_rows[0] if len(dict_rows) == 1 else None
+
+
+def _price_from_quote_dict(quote: dict) -> float | None:
+ """Return the first parseable positive price from a quote dict, else None."""
+ for key in ("price", "last_price", "last", "mark_price", "close", "ask", "bid"):
+ if key in quote:
+ try:
+ value = float(quote[key])
+ except (TypeError, ValueError):
+ continue
+ if value == value and value > 0: # finite + positive
+ return value
+ return None
+
+
+def _utc_today() -> str:
+ """Return today's UTC calendar date as ``YYYY-MM-DD``."""
+ return datetime.now(timezone.utc).date().isoformat()
+
+
+def _describe_intent(intent: OrderIntent | None) -> str | None:
+ """Render a human-readable normalized intent for the audit record."""
+ if intent is None:
+ return None
+ size = (
+ f"${intent.notional_usd:g}"
+ if intent.notional_usd is not None
+ else f"{intent.quantity:g} units"
+ if intent.quantity is not None
+ else "?"
+ )
+ return f"{intent.side} {size} {intent.symbol} ({intent.instrument_type.value})"
diff --git a/agent/src/live/paths.py b/agent/src/live/paths.py
new file mode 100644
index 000000000..d0ccac189
--- /dev/null
+++ b/agent/src/live/paths.py
@@ -0,0 +1,52 @@
+"""Filesystem layout for the live trading channel.
+
+All live-channel state is rooted at ``<runtime_root>/live`` (where
+``runtime_root`` defaults to ``~/.vibe-trading``, the same root the swarm
+config and persistent memory resolve, via :func:`src.config.paths.get_runtime_root`).
+
+Layout (see ``docs/live-trading/SPEC.md`` §2)::
+
+ <runtime_root>/live/robinhood/oauth/ # OAuth token cache (0700/0600)
+ <runtime_root>/live/robinhood/mandate.json # committed mandate (0600)
+ <runtime_root>/live/robinhood/trade_counter.json
+ <runtime_root>/live/HALT # kill-switch sentinel
+ <runtime_root>/live/audit.jsonl # live-action ledger (append-only)
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from src.config.paths import get_runtime_root
+
+
+def live_root() -> Path:
+ """Return the root directory for all live-channel state.
+
+ Returns:
+ ``<runtime_root>/live``. The directory is NOT created here; callers
+ that write create their own subtree with the correct ``0700`` perms.
+ """
+ return get_runtime_root() / "live"
+
+
+def broker_dir(broker: str) -> Path:
+ """Return the per-broker state directory under the live root.
+
+ Args:
+ broker: Broker key, e.g. ``"robinhood"``. Normalized to lower-case and
+ stripped so a stray ``"Robinhood "`` resolves to the same dir.
+
+ Returns:
+ ``<runtime_root>/live/<broker>``. Not created here.
+
+ Raises:
+ ValueError: If ``broker`` is empty/whitespace or contains a path
+ separator or ``..`` segment (a broker key is never a path).
+ """
+ key = broker.strip().lower()
+ if not key:
+ raise ValueError("broker key must not be empty")
+ if "/" in key or "\\" in key or ".." in key:
+ raise ValueError(f"invalid broker key: {broker!r}")
+ return live_root() / key
diff --git a/agent/src/live/registry.py b/agent/src/live/registry.py
new file mode 100644
index 000000000..63ab71220
--- /dev/null
+++ b/agent/src/live/registry.py
@@ -0,0 +1,207 @@
+"""Live-broker tool wrapping for the registry (SPEC §7.2 + integration seam).
+
+``build_mcp_tool_wrappers`` returns a plain :class:`~src.tools.mcp.MCPRemoteTool`
+for every discovered tool. For a live broker (e.g. Robinhood) that is not safe:
+every order-placing (WRITE or UNKNOWN) tool must be re-wrapped in
+:class:`~src.live.order_guard.LiveOrderGuardTool` so the mandate gate + kill
+switch run before any broker call, while READ tools stay on the plain path but
+are marked read-only for downstream UI/audit. Classification uses the 3-tier
+ladder (annotations -> curated map -> default-deny); UNKNOWN is treated as WRITE
+(fail-closed), so an unrecognized broker tool is never exposed ungated.
+"""
+
+from __future__ import annotations
+
+import logging
+
+from src.config.schema import LIVE_BROKER_SERVER_KEYS, is_live_broker_url
+from src.live.classification import ToolClass, classify_tool
+from src.live.halt import halt_flag_set
+from src.live.order_guard import LiveOrderGuardTool
+from src.live.robinhood_classification import ROBINHOOD_TOOL_CLASS
+from src.tools.mcp import MCPRemoteTool
+
+logger = logging.getLogger(__name__)
+
+#: Per-broker curated classification maps (Tier 2). Keyed by broker name; an
+#: aliased server key resolves to its broker via :func:`_broker_for`.
+_BROKER_CURATED_MAPS = {"robinhood": ROBINHOOD_TOOL_CLASS}
+
+#: URL host suffix -> broker name, so a live-broker URL under an arbitrary key
+#: still resolves to the right curated map / mandate / halt namespace.
+_HOST_SUFFIX_TO_BROKER = {"robinhood.com": "robinhood"}
+
+
+def is_live_broker(server_name: str, url: str = "") -> bool:
+ """Return whether an MCP server denotes a live-trading broker.
+
+ Detection is by config key OR by URL host, so a live-broker URL parked under
+ an arbitrary key (e.g. ``rh``) is still gated and wildcard-rejected. The
+ name-key path stays as a fallback for non-URL / intentionally-named entries.
+
+ Args:
+ server_name: The MCP server key from agent config.
+ url: The server's ``url`` (empty for stdio). When its host matches a
+ known live-broker host, the server is a live broker regardless of
+ ``server_name``.
+
+ Returns:
+ ``True`` when the server is a live broker requiring gated wrapping.
+ """
+ if server_name.strip().lower() in LIVE_BROKER_SERVER_KEYS:
+ return True
+ return is_live_broker_url(url)
+
+
+def _broker_for(server_name: str, url: str = "") -> str:
+ """Resolve the canonical broker namespace for a live-broker server.
+
+ A server keyed by a known broker name uses that key; a server detected only
+ by URL host maps to the broker that owns that host. This keeps the curated
+ map, mandate store, and HALT sentinel all keyed by the real broker even when
+ the config key is an alias.
+
+ Args:
+ server_name: The MCP server key from agent config.
+ url: The server's ``url``.
+
+ Returns:
+ The canonical broker key (e.g. ``"robinhood"``).
+ """
+ key = server_name.strip().lower()
+ if key in LIVE_BROKER_SERVER_KEYS:
+ return key
+ from src.config.schema import _url_host
+
+ host = _url_host(url)
+ for suffix, broker in _HOST_SUFFIX_TO_BROKER.items():
+ if host == suffix or host.endswith(f".{suffix}"):
+ return broker
+ return key
+
+
+#: FastMCP's OAuth token cache collection name (``TokenStorageAdapter``).
+_OAUTH_TOKEN_COLLECTION = "mcp-oauth-token"
+
+
+def has_cached_oauth_token(url: str, cache_dir: str) -> bool:
+ """Return whether a cached OAuth token already exists for a live channel.
+
+ FastMCP's OAuth provider persists tokens through the same
+ :func:`~src.tools.mcp._build_token_store` (``FileTreeStore``) backend, under
+ the ``mcp-oauth-token`` collection. ``FileTreeStore`` lays a collection out
+ as ``<cache_dir>/mcp-oauth-token/`` containing one entry file per cached
+ token. We detect authorization by the PRESENCE of any token entry file in
+ that collection directory rather than by reconstructing FastMCP's exact
+ (server-URL-derived) cache key — the key scheme is an internal detail and is
+ not stable to reconstruct, so a directory-level presence check is the robust
+ signal. The token VALUE is never read, returned, or logged — only presence.
+
+ Args:
+ url: The live channel's MCP server URL (unused for the presence scan,
+ kept for signature symmetry and future per-URL scoping).
+ cache_dir: The configured token cache directory.
+
+ Returns:
+ ``True`` when at least one token entry file is present; ``False`` on an
+ absent/empty cache or any read error (fail-closed: unreadable = not
+ authorized, so a non-interactive run skips rather than blocks).
+ """
+ from pathlib import Path
+
+ try:
+ collection = Path(cache_dir).expanduser() / _OAUTH_TOKEN_COLLECTION
+ if not collection.is_dir():
+ return False
+ # Any persisted token entry (FileTreeStore writes one file per key, plus
+ # a sidecar ``*-info.json`` at the cache root — not inside the dir).
+ return any(p.is_file() for p in collection.iterdir())
+ except OSError as exc:
+ logger.debug("OAuth token presence check failed for %s: %s", url, exc)
+ return False
+
+
+def should_register_live_channel(
+ *, interactive: bool, url: str, cache_dir: str | None
+) -> bool:
+ """Decide whether to register a live channel given session interactivity.
+
+ SPEC Transport §4 (headless / no-token-yet): a non-interactive
+ ``serve``/swarm run with no cached OAuth token must NOT register the channel,
+ because the first authorized call would block on ``webbrowser.open`` against
+ a browser that cannot open. An interactive TTY session always registers so
+ first-run browser authorize works. When a cached token already exists, the
+ channel registers in any context (no browser needed).
+
+ Args:
+ interactive: Whether the session is an interactive TTY.
+ url: The live channel's MCP server URL.
+ cache_dir: The configured OAuth token cache dir (``None`` when the
+ channel has no OAuth config — then there is no token to wait on and
+ registration proceeds).
+
+ Returns:
+ ``True`` when the channel should be registered.
+ """
+ if interactive:
+ return True
+ if cache_dir is None:
+ return True
+ return has_cached_oauth_token(url, cache_dir)
+
+
+def wrap_live_broker_tools(
+ server_name: str,
+ wrappers: list[MCPRemoteTool],
+ *,
+ url: str = "",
+) -> list[MCPRemoteTool]:
+ """Re-wrap a live broker's discovered tools by read/write class.
+
+ READ tools are returned as-is with ``is_readonly = True``; WRITE and UNKNOWN
+ tools are replaced by a :class:`LiveOrderGuardTool` over the same adapter and
+ spec, so order placement passes the mandate gate + kill switch.
+
+ Registration-time halt (SPEC §Consent 4, defense-in-depth): when the kill
+ switch is tripped for this broker, the WRITE/UNKNOWN (order) tools are
+ OMITTED from the assembled list entirely — a halted session's tool list does
+ not even contain them. READ tools stay. The call-time gate
+ (:class:`LiveOrderGuardTool`) is the un-bypassable check that also covers the
+ race where the flag is set after the list was built mid-turn; this is the
+ belt-and-suspenders registration-time half.
+
+ Args:
+ server_name: The live-broker MCP server key (e.g. ``"robinhood"`` or an
+ alias like ``"rh"``).
+ wrappers: The plain ``MCPRemoteTool`` wrappers from
+ :func:`~src.tools.mcp.build_mcp_tool_wrappers`.
+ url: The server's ``url``, used to resolve the canonical broker when the
+ config key is an alias (so curated map / mandate / halt all key off
+ the real broker).
+
+ Returns:
+ The wrappers with order-placing tools gated, and (when halted) with the
+ order tools omitted. Order is preserved.
+ """
+ broker = _broker_for(server_name, url)
+ curated = _BROKER_CURATED_MAPS.get(broker)
+ halted = halt_flag_set(broker)
+ result: list[MCPRemoteTool] = []
+ for tool in wrappers:
+ spec = tool._spec # internal seam: the gate is constructed from the same spec/adapter
+ tool_class = classify_tool(spec.remote_name, spec.annotations, curated)
+ if tool_class is ToolClass.READ:
+ tool.is_readonly = True
+ result.append(tool)
+ elif halted:
+ # WRITE/UNKNOWN + halt tripped -> do not even hand it to the model.
+ logger.warning(
+ "live kill switch tripped for broker '%s' — omitting order tool "
+ "'%s' from the registry",
+ broker,
+ spec.remote_name,
+ )
+ else:
+ # WRITE or UNKNOWN -> mandate-gated (fail-closed for UNKNOWN).
+ result.append(LiveOrderGuardTool(tool._adapter, spec, broker=broker))
+ return result
diff --git a/agent/src/live/robinhood_classification.py b/agent/src/live/robinhood_classification.py
new file mode 100644
index 000000000..2a2baa654
--- /dev/null
+++ b/agent/src/live/robinhood_classification.py
@@ -0,0 +1,33 @@
+"""Curated read/write classification map for Robinhood Agentic Trading.
+
+Tier 2 of the classification ladder (:mod:`src.live.classification`): an
+explicit, version-controlled map keyed by the broker's remote tool name. Map
+entries are authoritative and override Tier-1 ``annotations`` when they
+disagree (a deceptive ``readOnlyHint=True`` on ``place_order`` cannot demote a
+curated WRITE). A tool absent from this map and not annotated read-only is
+UNKNOWN and treated as WRITE (fail-closed).
+
+This map is the FROZEN canonical Robinhood catalog (SPEC §7.5):
+``READ = {get_account, get_positions, get_quotes, list_orders}`` and
+``WRITE = {place_order, cancel_order}``. Any tool the broker reports that is not
+in this map and not annotated read-only resolves to UNKNOWN → treated as WRITE
+(fail-closed), so an unrecognized new broker tool can never slip through as a
+plain read. Adding a tool here is a localized edit to this one dict plus the
+classification test parametrize list.
+"""
+
+from __future__ import annotations
+
+from src.live.classification import ToolClass
+
+#: Frozen canonical Robinhood read/write catalog.
+ROBINHOOD_TOOL_CLASS: dict[str, ToolClass] = {
+ # READ
+ "get_account": ToolClass.READ,
+ "get_positions": ToolClass.READ,
+ "get_quotes": ToolClass.READ,
+ "list_orders": ToolClass.READ,
+ # WRITE
+ "place_order": ToolClass.WRITE,
+ "cancel_order": ToolClass.WRITE,
+}
diff --git a/agent/src/live/runtime/__init__.py b/agent/src/live/runtime/__init__.py
new file mode 100644
index 000000000..6807fa0e9
--- /dev/null
+++ b/agent/src/live/runtime/__init__.py
@@ -0,0 +1,13 @@
+"""Persistent live-trading runtime (SPEC.md §7.5).
+
+The runtime makes the "agentic" framing honest: a persistent process that
+wakes on a schedule, decides + trades inside the committed mandate, sleeps,
+and survives restarts. This package holds the *shell* (scheduler, durable
+crash-safe job store, runner liveness); the trading-truth layer (reconcile,
+preemptive halt, triggers) is built on top in sibling modules.
+
+Submodules are intentionally NOT re-exported here: parcels land sibling
+modules (runner, triggers, reconcile, flatten) concurrently, so importing
+``src.live.runtime`` must never pull a half-written sibling. Import the exact
+module you need (e.g. ``from src.live.runtime.scheduler import Scheduler``).
+"""
diff --git a/agent/src/live/runtime/flatten.py b/agent/src/live/runtime/flatten.py
new file mode 100644
index 000000000..fe0680058
--- /dev/null
+++ b/agent/src/live/runtime/flatten.py
@@ -0,0 +1,277 @@
+"""Preemptive kill-switch action: cancel resting orders, then flatten positions.
+
+SPEC.md §7.5 component 6. The filesystem ``HALT`` sentinel (``src.live.halt``)
+is the LLM-independent *trigger*; this module is the *action* the runner executes
+once a trip is observed. It upgrades the cooperative order-time halt (which only
+refuses the next order) to **preemptive**: on trip the runner
+
+1. cancels every resting/open order, then
+2. — only if the active mandate permits flattening — submits closing orders for
+ every open position.
+
+Cancel-before-flatten ordering is deliberate: a resting order left live while we
+flatten could fill against our closing trade and re-open exposure. Cancelling
+first quiesces the book, then the position sweep closes what is actually held.
+
+**Per-mandate flatten flag (SPEC §7.5 #6 "optionally, per mandate").** The frozen
+:class:`~src.live.mandate.model.Mandate` has no flatten field today (its
+``HardCaps`` carry only ceilings). Until the mandate schema grows one, flattening
+defaults to **OFF** (cancel-only) — the safe default, since auto-submitting market
+exits is itself a trading action the user may not have authorized. Callers can
+opt in explicitly via ``allow_flatten=True``; and if a future mandate schema adds
+a truthy ``flatten_on_halt`` attribute, it is honored automatically (read
+defensively via ``getattr`` so this module needs no edit when the field lands).
+TODO(live-runtime): once ``Mandate``/``HardCaps`` gains a first-class
+``flatten_on_halt`` flag, drop the ``getattr`` probe and read it directly.
+
+**No-retry (SPEC §8.5).** Trading is not idempotent. A broker call that errors is
+recorded and we move on — it is NEVER retried, exactly like ``mcp._call_tool``.
+A failed cancel/flatten must surface as an error in the returned report, not be
+silently re-sent (which could double-trade).
+
+Every broker call — each cancel, each flatten submit, and each error — is written
+to the live-action audit ledger via :func:`src.live.audit.write_live_action`
+BEFORE the report is returned, so the preemptive sweep is fully reconstructable.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Callable
+
+from src.live.audit import LiveActionEvent, write_live_action
+from src.live.mandate.store import load_mandate
+
+logger = logging.getLogger(__name__)
+
+#: Session id stamped on audit records emitted by the preemptive sweep. The
+#: sweep is runner-initiated (not a chat turn), so it has no user session.
+_RUNTIME_SESSION_ID = "live-runtime"
+
+#: Broker remote-tool names recorded in the audit ledger for sweep actions.
+_CANCEL_TOOL = "cancel_order"
+_FLATTEN_TOOL = "place_order"
+
+#: Type aliases for the injected broker callables (stubbed in tests).
+SubmitFn = Callable[[dict[str, Any]], dict[str, Any]]
+ReadPositionsFn = Callable[[], list[dict[str, Any]]]
+ReadOpenOrdersFn = Callable[[], list[dict[str, Any]]]
+
+
+def flatten_and_cancel(
+ broker: str,
+ submit: SubmitFn,
+ read_positions: ReadPositionsFn,
+ read_open_orders: ReadOpenOrdersFn,
+ *,
+ allow_flatten: bool | None = None,
+) -> dict[str, Any]:
+ """Cancel all resting orders, then (if permitted) flatten open positions.
+
+ Executed by the runner the moment a halt trip is observed. Cancels run first
+ to quiesce the order book; the position sweep runs only when the mandate
+ permits flattening (see module docstring for the per-mandate flag policy).
+ Every broker call and every error is audited before this returns; no errored
+ call is ever retried (SPEC §8.5).
+
+ Args:
+ broker: Broker key, e.g. ``"robinhood"``. Used to load the active mandate
+ and to stamp audit records.
+ submit: Injected broker callable that places one order. Receives a
+ normalized order dict; returns the broker's raw response dict. Used
+ for both cancel (``{"action": "cancel", "order_id": ...}``) and
+ flatten (a closing order) submissions.
+ read_positions: Injected broker callable returning the list of open
+ position dicts (each with at least ``symbol`` and a signed ``qty``).
+ read_open_orders: Injected broker callable returning the list of
+ resting/open order dicts (each with at least ``order_id``).
+ allow_flatten: Explicit override for whether to flatten positions. When
+ ``None`` (default) the decision is taken from the active mandate's
+ ``flatten_on_halt`` attribute if present, else ``False`` (cancel-only).
+
+ Returns:
+ A structured report dict::
+
+ {
+ "broker": "robinhood",
+ "cancelled_order_ids": ["o1", ...], # successfully cancelled
+ "flatten_orders_submitted": [ # closing orders accepted
+ {"symbol": "NVDA", "qty": 3, "side": "sell", "response": {...}},
+ ],
+ "flatten_skipped_reason": "mandate forbids flatten" | None,
+ "errors": [ # one per failed broker call
+ {"phase": "cancel", "order_id": "o2", "error": "..."},
+ ],
+ }
+ """
+ report: dict[str, Any] = {
+ "broker": broker,
+ "cancelled_order_ids": [],
+ "flatten_orders_submitted": [],
+ "flatten_skipped_reason": None,
+ "errors": [],
+ }
+
+ _cancel_resting_orders(broker, submit, read_open_orders, report)
+
+ do_flatten = _resolve_allow_flatten(broker, allow_flatten)
+ if not do_flatten:
+ report["flatten_skipped_reason"] = "mandate forbids flatten (cancel-only)"
+ logger.warning(
+ "live preemptive sweep (broker=%s): cancel-only, flatten not permitted",
+ broker,
+ )
+ return report
+
+ _flatten_open_positions(broker, submit, read_positions, report)
+ return report
+
+
+def _resolve_allow_flatten(broker: str, allow_flatten: bool | None) -> bool:
+ """Decide whether positions may be flattened on this trip.
+
+ An explicit ``allow_flatten`` argument always wins. Otherwise the active
+ mandate is consulted for a (future) ``flatten_on_halt`` attribute, defaulting
+ to ``False`` (cancel-only) — the safe default and the current behavior, since
+ the frozen mandate schema has no such field yet (see module docstring).
+
+ Args:
+ broker: Broker key used to load the mandate.
+ allow_flatten: Caller override, or ``None`` to defer to the mandate.
+
+ Returns:
+ ``True`` if positions should be flattened, else ``False``.
+ """
+ if allow_flatten is not None:
+ return allow_flatten
+ mandate = load_mandate(broker)
+ if mandate is None:
+ # No valid mandate on file → fail-closed to cancel-only.
+ return False
+ return bool(getattr(mandate, "flatten_on_halt", False))
+
+
+def _cancel_resting_orders(
+ broker: str,
+ submit: SubmitFn,
+ read_open_orders: ReadOpenOrdersFn,
+ report: dict[str, Any],
+) -> None:
+ """Cancel every resting/open order, auditing each call (no retry on error).
+
+ Args:
+ broker: Broker key for audit stamping.
+ submit: Injected broker callable (receives a cancel request dict).
+ read_open_orders: Injected broker callable returning open-order dicts.
+ report: Mutated in place — successful ids appended to
+ ``cancelled_order_ids``, failures to ``errors``.
+ """
+ try:
+ open_orders = read_open_orders()
+ except Exception as exc: # noqa: BLE001 — broker read must not abort the sweep
+ report["errors"].append({"phase": "read_open_orders", "error": str(exc)})
+ return
+
+ for order in open_orders:
+ order_id = order.get("order_id")
+ request = {"action": "cancel", "order_id": order_id}
+ try:
+ response = submit(request)
+ except Exception as exc: # noqa: BLE001 — record + move on, never retry
+ report["errors"].append(
+ {"phase": "cancel", "order_id": order_id, "error": str(exc)}
+ )
+ _audit(broker, _CANCEL_TOOL, f"cancel order {order_id}", request,
+ None, "error", str(exc))
+ continue
+ report["cancelled_order_ids"].append(order_id)
+ _audit(broker, _CANCEL_TOOL, f"cancel order {order_id}", request,
+ response, "accepted", None)
+
+
+def _flatten_open_positions(
+ broker: str,
+ submit: SubmitFn,
+ read_positions: ReadPositionsFn,
+ report: dict[str, Any],
+) -> None:
+ """Submit a closing order for each open position, auditing each (no retry).
+
+ A long position (``qty > 0``) is closed by a sell of ``abs(qty)``; a short
+ (``qty < 0``) by a buy. A zero-qty position is skipped.
+
+ Args:
+ broker: Broker key for audit stamping.
+ submit: Injected broker callable (receives a closing order dict).
+ read_positions: Injected broker callable returning position dicts.
+ report: Mutated in place — accepted closes appended to
+ ``flatten_orders_submitted``, failures to ``errors``.
+ """
+ try:
+ positions = read_positions()
+ except Exception as exc: # noqa: BLE001 — broker read must not abort the sweep
+ report["errors"].append({"phase": "read_positions", "error": str(exc)})
+ return
+
+ for position in positions:
+ symbol = position.get("symbol")
+ qty = float(position.get("qty", 0) or 0)
+ if qty == 0:
+ continue
+ side = "sell" if qty > 0 else "buy"
+ close_qty = abs(qty)
+ request = {
+ "action": "close",
+ "symbol": symbol,
+ "side": side,
+ "qty": close_qty,
+ "type": "market",
+ }
+ intent = f"flatten {symbol}: {side} {close_qty} @ market"
+ try:
+ response = submit(request)
+ except Exception as exc: # noqa: BLE001 — record + move on, never retry
+ report["errors"].append(
+ {"phase": "flatten", "symbol": symbol, "error": str(exc)}
+ )
+ _audit(broker, _FLATTEN_TOOL, intent, request, None, "error", str(exc))
+ continue
+ report["flatten_orders_submitted"].append(
+ {"symbol": symbol, "qty": close_qty, "side": side, "response": response}
+ )
+ _audit(broker, _FLATTEN_TOOL, intent, request, response, "accepted", None)
+
+
+def _audit(
+ broker: str,
+ remote_tool: str,
+ intent: str,
+ request: dict[str, Any],
+ response: dict[str, Any] | None,
+ outcome: str,
+ error: str | None,
+) -> None:
+ """Append one redacted live-action record for a sweep broker call.
+
+ Args:
+ broker: Broker key (stamped as ``server``).
+ remote_tool: Broker remote tool invoked (``cancel_order`` | ``place_order``).
+ intent: Human-readable normalized intent for the ledger.
+ request: Raw broker request (redacted before write by the ledger).
+ response: Raw broker response, or ``None`` on error.
+ outcome: ``"accepted"`` on success, ``"error"`` on failure.
+ error: Error string when ``outcome == "error"``, else ``None``.
+ """
+ write_live_action(
+ LiveActionEvent(
+ kind="order_placed" if outcome == "accepted" else "order_rejected",
+ session_id=_RUNTIME_SESSION_ID,
+ outcome=outcome, # type: ignore[arg-type]
+ server=broker,
+ remote_tool=remote_tool,
+ intent_normalized=intent,
+ broker_request=request,
+ broker_response=response,
+ error=error,
+ )
+ )
diff --git a/agent/src/live/runtime/jobstore.py b/agent/src/live/runtime/jobstore.py
new file mode 100644
index 000000000..88f625ef1
--- /dev/null
+++ b/agent/src/live/runtime/jobstore.py
@@ -0,0 +1,288 @@
+"""Durable, crash-safe job store for the live runtime (SPEC.md §7.5 #1).
+
+The scheduler's set of jobs must survive a SIGKILL mid-write: a persistent
+trading runner that loses or truncates its job store on a crash would silently
+stop watching the mandate's cadence. This store guarantees:
+
+* **Atomic save** — write a temp file in the *same* directory, ``fsync`` it,
+ ``os.replace`` over the target (atomic on POSIX/NTFS), then ``fsync`` the
+ parent directory so the rename itself is durable. A crash at any instant
+ leaves either the old complete store or the new complete store, never a
+ truncated one.
+* **Corruption quarantine** — a store whose JSON no longer parses is renamed
+ ``<name>.corrupt-<ts>`` and the load **refuses to start empty**: it raises
+ :class:`CorruptJobStoreError` rather than silently booting with zero jobs
+ (which on a trading runner would look like "mandate has no work" and stop
+ all activity). A genuinely-missing store (first boot) loads as empty — that
+ is the only blank-start path.
+
+State lives under ``live_root()/runtime/`` (see :mod:`src.live.paths`).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+from datetime import datetime, timezone
+from pathlib import Path
+
+from src.live.paths import live_root
+from src.live.runtime.scheduler import Job
+
+logger = logging.getLogger(__name__)
+
+_STORE_FILENAME = "jobs.json"
+_RUNTIME_SUBDIR = "runtime"
+#: Schema version of the persisted store envelope. Bump on breaking changes so
+#: a future loader can branch instead of mis-parsing an old layout.
+_SCHEMA_VERSION = 1
+
+
+class CorruptJobStoreError(RuntimeError):
+ """Raised when the on-disk store exists but cannot be parsed.
+
+ Carries the path the corrupt file was quarantined to so an operator can
+ inspect it. The runner must surface this rather than boot with no jobs.
+ """
+
+ def __init__(self, original: Path, quarantined: Path, cause: str) -> None:
+ """Initialize the error.
+
+ Args:
+ original: Path of the store that failed to parse.
+ quarantined: Path the corrupt file was renamed to.
+ cause: Short description of why parsing failed.
+ """
+ super().__init__(
+ f"job store {original} is corrupt ({cause}); "
+ f"quarantined to {quarantined} — refusing empty start"
+ )
+ self.original = original
+ self.quarantined = quarantined
+ self.cause = cause
+
+
+def runtime_dir() -> Path:
+ """Return the runtime state directory (``live_root()/runtime``).
+
+ Returns:
+ The directory path. Not created here; :meth:`JobStore.save` creates it
+ with ``0700`` perms before the first write.
+ """
+ return live_root() / _RUNTIME_SUBDIR
+
+
+class JobStore:
+ """Crash-safe, on-disk persistence for the scheduler's job set.
+
+ The store is a thin durable envelope around a list of :class:`Job`. It owns
+ only serialization + atomic IO; scheduling decisions live in
+ :class:`src.live.runtime.scheduler.Scheduler`.
+
+ Attributes:
+ path: Absolute path of the JSON store file.
+ """
+
+ def __init__(self, path: Path | None = None) -> None:
+ """Initialize the store.
+
+ Args:
+ path: Explicit store path. When ``None`` (default), resolves to
+ ``runtime_dir()/jobs.json``. Resolved lazily-but-once here so a
+ test that monkeypatches ``get_runtime_root`` before construction
+ gets the isolated path.
+ """
+ self.path = path if path is not None else runtime_dir() / _STORE_FILENAME
+
+ def load(self) -> list[Job]:
+ """Load the persisted jobs.
+
+ A missing store (never written) is the *only* clean empty result. A
+ store that exists but fails to parse is quarantined and the load raises,
+ so the runner never silently starts with no work.
+
+ Returns:
+ The persisted jobs, or an empty list when the store has never been
+ written.
+
+ Raises:
+ CorruptJobStoreError: If the store exists but its JSON / schema
+ cannot be parsed. The corrupt file is renamed first.
+ """
+ if not self.path.exists():
+ return []
+ try:
+ raw = self.path.read_text(encoding="utf-8")
+ envelope = json.loads(raw)
+ jobs_raw = self._extract_jobs(envelope)
+ return [self._job_from_dict(item) for item in jobs_raw]
+ except (OSError, ValueError, KeyError, TypeError) as exc:
+ quarantined = self._quarantine(str(exc))
+ raise CorruptJobStoreError(self.path, quarantined, str(exc)) from exc
+
+ def save(self, jobs: list[Job]) -> None:
+ """Atomically persist the job set.
+
+ Write sequence (durable even under SIGKILL): temp file in the same dir
+ → ``os.fsync`` the temp fd → ``os.replace`` onto the target →
+ ``fsync`` the parent directory fd so the rename is itself durable.
+
+ Args:
+ jobs: The full job set to persist (the store holds the complete
+ set, not a delta).
+
+ Raises:
+ OSError: If the directory cannot be created or the write fails.
+ """
+ target = self.path
+ target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ payload = json.dumps(self._envelope(jobs), ensure_ascii=False, indent=2)
+
+ tmp = target.with_name(f".{target.name}.{os.getpid()}.tmp")
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ try:
+ os.write(fd, payload.encode("utf-8"))
+ os.fsync(fd)
+ finally:
+ os.close(fd)
+
+ os.replace(tmp, target)
+ self._fsync_dir(target.parent)
+
+ def _quarantine(self, cause: str) -> Path:
+ """Rename the corrupt store aside as ``<name>.corrupt-<ts>``.
+
+ Args:
+ cause: Reason string (logged only).
+
+ Returns:
+ The path the corrupt store was moved to. If the rename itself fails
+ the original path is returned (best-effort quarantine).
+ """
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
+ quarantined = self.path.with_name(f"{self.path.name}.corrupt-{ts}")
+ try:
+ os.replace(self.path, quarantined)
+ logger.error(
+ "job store %s corrupt (%s) — quarantined to %s",
+ self.path,
+ cause,
+ quarantined,
+ )
+ return quarantined
+ except OSError:
+ logger.error(
+ "job store %s corrupt (%s) — quarantine rename failed",
+ self.path,
+ cause,
+ exc_info=True,
+ )
+ return self.path
+
+ @staticmethod
+ def _fsync_dir(directory: Path) -> None:
+ """Fsync a directory fd so a contained ``os.replace`` is durable.
+
+ On platforms where opening a directory for fsync is unsupported (some
+ Windows builds), this is a best-effort no-op: ``os.replace`` is already
+ atomic there, only the rename's durability window differs.
+
+ Args:
+ directory: The directory whose entry was just renamed.
+ """
+ try:
+ dir_fd = os.open(directory, os.O_RDONLY)
+ except OSError:
+ return
+ try:
+ os.fsync(dir_fd)
+ except OSError:
+ logger.debug("parent-dir fsync unsupported on %s", directory, exc_info=True)
+ finally:
+ os.close(dir_fd)
+
+ @staticmethod
+ def _envelope(jobs: list[Job]) -> dict[str, object]:
+ """Wrap jobs in the versioned on-disk envelope.
+
+ Args:
+ jobs: Jobs to serialize.
+
+ Returns:
+ A JSON-serializable dict carrying schema version + job list.
+ """
+ return {
+ "schema_version": _SCHEMA_VERSION,
+ "jobs": [JobStore._job_to_dict(job) for job in jobs],
+ }
+
+ @staticmethod
+ def _extract_jobs(envelope: object) -> list[dict]:
+ """Validate the envelope shape and return its raw job dicts.
+
+ Args:
+ envelope: The parsed top-level JSON value.
+
+ Returns:
+ The list of raw job dicts.
+
+ Raises:
+ ValueError: If the envelope shape is unrecognized.
+ """
+ if not isinstance(envelope, dict):
+ raise ValueError("store root is not a JSON object")
+ jobs = envelope.get("jobs")
+ if not isinstance(jobs, list):
+ raise ValueError("store 'jobs' is missing or not a list")
+ if not all(isinstance(item, dict) for item in jobs):
+ raise ValueError("store 'jobs' contains a non-object entry")
+ return jobs
+
+ @staticmethod
+ def _job_to_dict(job: Job) -> dict[str, object]:
+ """Serialize a :class:`Job` to a plain dict.
+
+ Args:
+ job: The job to serialize.
+
+ Returns:
+ A JSON-serializable dict.
+ """
+ return {
+ "id": job.id,
+ "next_run_at": job.next_run_at,
+ "schedule": job.schedule,
+ "payload": job.payload,
+ }
+
+ @staticmethod
+ def _job_from_dict(item: dict) -> Job:
+ """Reconstruct a :class:`Job` from a persisted dict.
+
+ Args:
+ item: A raw job dict from the store.
+
+ Returns:
+ The reconstructed Job.
+
+ Raises:
+ KeyError: If a required field is absent.
+ TypeError: If a field has the wrong type.
+ """
+ job_id = item["id"]
+ next_run_at = item["next_run_at"]
+ schedule = item["schedule"]
+ if not isinstance(job_id, str) or not isinstance(schedule, str):
+ raise TypeError("job 'id' and 'schedule' must be strings")
+ if not isinstance(next_run_at, int):
+ raise TypeError("job 'next_run_at' must be an int (epoch ms)")
+ payload = item.get("payload")
+ if payload is not None and not isinstance(payload, dict):
+ raise TypeError("job 'payload' must be an object or null")
+ return Job(
+ id=job_id,
+ next_run_at=next_run_at,
+ schedule=schedule,
+ payload=payload,
+ )
diff --git a/agent/src/live/runtime/liveness.py b/agent/src/live/runtime/liveness.py
new file mode 100644
index 000000000..4b1abb166
--- /dev/null
+++ b/agent/src/live/runtime/liveness.py
@@ -0,0 +1,190 @@
+"""Runner liveness for the live runtime (SPEC.md §7.5 #3).
+
+A persistent trading runner must be *detectably* alive. Each runner writes a
+heartbeat file (its last-tick epoch-ms timestamp) under ``live_root()/runtime/``
+every tick; a stale heartbeat means the process died without cleanup (zombie /
+SIGKILL / host crash). The reaper borrows :mod:`src.swarm.runtime`'s shape: a
+read-only staleness check (``last_tick`` older than a threshold) drives a
+separate purge, so the same predicate serves both "is this runner alive?" reads
+and the destructive reap.
+
+A live runner that looks dead must never be re-spawned blindly — reconciliation
+(SPEC #5) runs first — so this module only *reports* and *purges sentinels*; it
+never starts or kills processes.
+
+Heartbeat writes are atomic (same-dir temp + ``os.replace``) so a concurrent
+:func:`last_tick` read can never see a torn timestamp.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import time
+from pathlib import Path
+
+from src.live.runtime.jobstore import runtime_dir
+
+logger = logging.getLogger(__name__)
+
+_HEARTBEAT_SUFFIX = ".heartbeat"
+_HEARTBEAT_DIR = "heartbeats"
+
+#: A runner is considered dead if its last tick is older than this. Generous
+#: relative to a tick (the runner heartbeats once per scheduler wake, well
+#: under a minute) so a momentarily slow tick is never false-reaped.
+DEFAULT_STALENESS_MS = 90 * 1000
+
+
+def _now_ms() -> int:
+ """Return the current wall-clock time in epoch milliseconds.
+
+ Returns:
+ Milliseconds since the Unix epoch.
+ """
+ return int(time.time() * 1000)
+
+
+def heartbeats_dir() -> Path:
+ """Return the directory holding per-runner heartbeat files.
+
+ Returns:
+ ``live_root()/runtime/heartbeats``. Not created here; written lazily by
+ :func:`write_heartbeat`.
+ """
+ return runtime_dir() / _HEARTBEAT_DIR
+
+
+def heartbeat_path(runner_id: str) -> Path:
+ """Return the heartbeat file path for a runner.
+
+ Args:
+ runner_id: Stable runner identifier.
+
+ Returns:
+ ``live_root()/runtime/heartbeats/<runner_id>.heartbeat``.
+
+ Raises:
+ ValueError: If ``runner_id`` is empty/whitespace or contains a path
+ separator or ``..`` segment (a runner id is never a path).
+ """
+ key = runner_id.strip()
+ if not key:
+ raise ValueError("runner_id must not be empty")
+ if "/" in key or "\\" in key or ".." in key:
+ raise ValueError(f"invalid runner_id: {runner_id!r}")
+ return heartbeats_dir() / f"{key}{_HEARTBEAT_SUFFIX}"
+
+
+def write_heartbeat(runner_id: str, *, now_ms: int | None = None) -> int:
+ """Atomically record a runner's last-tick timestamp.
+
+ Args:
+ runner_id: The runner writing its heartbeat.
+ now_ms: Timestamp to record, in epoch ms. Defaults to the current
+ wall-clock; injectable for deterministic tests.
+
+ Returns:
+ The timestamp that was written, in epoch ms.
+
+ Raises:
+ ValueError: If ``runner_id`` is invalid.
+ OSError: If the directory cannot be created or the write fails.
+ """
+ tick = now_ms if now_ms is not None else _now_ms()
+ path = heartbeat_path(runner_id)
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
+ tmp.write_text(str(tick), encoding="utf-8")
+ os.replace(tmp, path)
+ return tick
+
+
+def last_tick(runner_id: str) -> int | None:
+ """Return a runner's last recorded heartbeat timestamp.
+
+ Args:
+ runner_id: The runner to read.
+
+ Returns:
+ The last-tick timestamp in epoch ms, or ``None`` when no heartbeat
+ exists or the file is unreadable / malformed (treated as "no signal",
+ which :func:`is_runner_alive` reads as not-alive — fail-closed).
+ """
+ try:
+ path = heartbeat_path(runner_id)
+ except ValueError:
+ return None
+ if not path.exists():
+ return None
+ try:
+ raw = path.read_text(encoding="utf-8").strip()
+ return int(raw)
+ except (OSError, ValueError):
+ return None
+
+
+def is_runner_alive(
+ runner_id: str,
+ *,
+ now_ms: int | None = None,
+ staleness_ms: int = DEFAULT_STALENESS_MS,
+) -> bool:
+ """Report whether a runner's heartbeat is fresh enough to call it alive.
+
+ Args:
+ runner_id: The runner to check.
+ now_ms: Reference time in epoch ms. Defaults to current wall-clock.
+ staleness_ms: Maximum age of the last tick before the runner is
+ considered dead.
+
+ Returns:
+ ``True`` if a heartbeat exists and its last tick is within
+ ``staleness_ms`` of ``now_ms``; ``False`` otherwise (missing, stale, or
+ unreadable heartbeat).
+ """
+ tick = last_tick(runner_id)
+ if tick is None:
+ return False
+ now = now_ms if now_ms is not None else _now_ms()
+ return (now - tick) <= staleness_ms
+
+
+def reap_stale(
+ *,
+ now_ms: int | None = None,
+ staleness_ms: int = DEFAULT_STALENESS_MS,
+) -> list[str]:
+ """Purge heartbeat sentinels of runners that have gone stale.
+
+ Mirrors the swarm reaper shape: scan every heartbeat, keep the live ones,
+ delete the stale ones, and return the ids reaped so the caller can log /
+ trigger reconciliation. Reaping only removes the *sentinel* — it never
+ touches a process or any trading state.
+
+ Args:
+ now_ms: Reference time in epoch ms. Defaults to current wall-clock.
+ staleness_ms: Age threshold; a heartbeat older than this is reaped.
+
+ Returns:
+ The runner ids whose stale heartbeats were removed (empty list when
+ none were stale or the heartbeat dir does not exist).
+ """
+ directory = heartbeats_dir()
+ if not directory.is_dir():
+ return []
+ now = now_ms if now_ms is not None else _now_ms()
+ reaped: list[str] = []
+ for entry in directory.glob(f"*{_HEARTBEAT_SUFFIX}"):
+ runner_id = entry.name[: -len(_HEARTBEAT_SUFFIX)]
+ if is_runner_alive(runner_id, now_ms=now, staleness_ms=staleness_ms):
+ continue
+ try:
+ entry.unlink()
+ reaped.append(runner_id)
+ logger.warning("reaped stale live runner heartbeat: %s", runner_id)
+ except FileNotFoundError:
+ continue
+ except OSError:
+ logger.warning("failed to reap stale heartbeat %s", entry, exc_info=True)
+ return reaped
diff --git a/agent/src/live/runtime/reconcile.py b/agent/src/live/runtime/reconcile.py
new file mode 100644
index 000000000..2c197288c
--- /dev/null
+++ b/agent/src/live/runtime/reconcile.py
@@ -0,0 +1,588 @@
+"""Crash recovery + position reconciliation (SPEC.md §7.5 component 5).
+
+This is the hardest piece of the persistent runtime and has **no nanobot
+analog**. On startup and before every trading tick the runner must answer one
+question before it is allowed to trade again: *does broker truth match the
+durable last-known state we persisted before the crash?* Trading is not
+idempotent, so a naive "resume + re-send" closes one hole (lost work) by opening
+a far worse one (double-trade real money).
+
+The dangerous case is a **mid-order crash**: we asked the broker to place an
+order, the process died, and we never learned whether it filled. The order may
+be open, may have filled, or may never have reached the broker. The no-retry
+rule (SPEC §8.5 — ``_call_tool`` deliberately never retries mutating calls and
+``LiveOrderGuardTool.repeatable = False``) means we MUST NOT auto-resend such an
+order. Reconciliation's job is therefore to *classify and SURFACE* the
+ambiguity, never to auto-correct or auto-resend it.
+
+Design contract (frozen — R2's runner imports these blind):
+
+* :func:`reconcile` takes the broker key plus three **injected READ callables**
+ (``read_positions`` / ``read_balance`` / ``read_open_orders``). These are the
+ broker's read-only MCP tools at runtime and stubs in tests. Reconciliation
+ NEVER receives, holds, or calls a broker *write* tool — that is structurally
+ how we guarantee it cannot resend an order.
+* It diffs broker truth against the durable last-known state at
+ ``<runtime_root>/<broker>/runtime_state.json`` (via
+ :func:`src.live.paths.broker_dir`).
+* Every delta is classified into one of :class:`DeltaKind`:
+ ``matched`` / ``unknown_fill`` / ``orphan_order`` / ``mid_order_ambiguous``.
+* The returned :class:`ReconcileReport` carries the classified deltas plus an
+ overall ``is_safe`` / ``requires_halt`` flag the runner consults. Any
+ ``mid_order_ambiguous`` (or ``unknown_fill``) delta flips ``requires_halt``:
+ the runner halts and surfaces — it never silently retries.
+* After a *clean* reconcile (broker truth fully reconciled, nothing ambiguous)
+ the new last-known state is persisted atomically (temp + ``os.replace``).
+
+Idempotency / client-order-id: where a client-order-id is derivable from the
+recorded state we carry it on the delta and in
+:attr:`ReconcileReport.recorded_client_order_ids` so the runner / broker layer
+can dedupe instead of resend. The exact broker field that maps to a
+client-order-id is broker-specific; see ``_client_order_id`` for the mapping
+TODO that needs the real broker catalog.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable, Mapping, Sequence
+
+from src.live.mandate.store import load_mandate
+from src.live.paths import broker_dir
+
+logger = logging.getLogger(__name__)
+
+#: Filename of the durable last-known runtime state under the broker dir.
+_STATE_FILENAME = "runtime_state.json"
+
+#: Schema version of the persisted runtime state document.
+RUNTIME_STATE_SCHEMA_VERSION = 1
+
+#: A broker READ callable: takes no args, returns the broker truth payload.
+#: ``read_positions`` / ``read_open_orders`` return a sequence of dicts;
+#: ``read_balance`` returns a single dict. They are the broker's read-only MCP
+#: tools at runtime and fabricated stubs in tests. None of them mutate state.
+ReadList = Callable[[], Sequence[Mapping[str, Any]]]
+ReadDict = Callable[[], Mapping[str, Any]]
+
+
+class DeltaKind:
+ """Classification labels for a single reconciliation delta.
+
+ Not an :class:`enum.Enum` so callers can compare against bare strings in
+ audit records without an import; the set is closed and documented here.
+
+ Attributes:
+ MATCHED: Broker truth and our recorded state agree — no action needed.
+ UNKNOWN_FILL: The broker shows a fill (a position or a filled order) we
+ have no record of. Dangerous: real money moved without our audit
+ trail. Forces a halt.
+ ORPHAN_ORDER: We recorded a resting/open order the broker does NOT show.
+ It was cancelled, rejected, or filled-and-cleared out of band. Not
+ auto-resent; surfaced for the runner to investigate.
+ MID_ORDER_AMBIGUOUS: We recorded an order as *submitted-but-unconfirmed*
+ (placed before the crash, never audited as accepted/filled) and the
+ broker neither shows it open nor confirms a matching fill. It may
+ have filled before our audit write. The no-retry rule forbids
+ resending it; this is surfaced and forces a halt.
+ """
+
+ MATCHED = "matched"
+ UNKNOWN_FILL = "unknown_fill"
+ ORPHAN_ORDER = "orphan_order"
+ MID_ORDER_AMBIGUOUS = "mid_order_ambiguous"
+
+
+#: Delta kinds that mean real money may have moved without a clean audit trail,
+#: so the runner MUST halt and surface rather than trade on the next tick.
+_HALTING_KINDS = frozenset({DeltaKind.UNKNOWN_FILL, DeltaKind.MID_ORDER_AMBIGUOUS})
+
+
+@dataclass(frozen=True)
+class ReconcileDelta:
+ """One classified difference between broker truth and recorded state.
+
+ Attributes:
+ kind: One of :class:`DeltaKind`'s labels.
+ subject: ``"order"`` or ``"position"`` — which kind of broker fact this
+ delta concerns.
+ identity: Stable identity of the subject (a broker order id or a symbol)
+ used to correlate the two sides of the diff. Never credentials.
+ client_order_id: The client-order-id derived from recorded state when
+ available, so the runner can dedupe instead of resend. ``None`` when
+ not derivable (e.g. an unknown broker-side fill).
+ detail: Human-readable explanation of why this delta was raised.
+ recorded: The recorded-state view of the subject (redaction-safe; ids
+ and quantities only), or ``None`` when we had no record.
+ broker: The broker-truth view of the subject, or ``None`` when the
+ broker did not report it.
+ """
+
+ kind: str
+ subject: str
+ identity: str
+ client_order_id: str | None
+ detail: str
+ recorded: Mapping[str, Any] | None
+ broker: Mapping[str, Any] | None
+
+
+@dataclass(frozen=True)
+class ReconcileReport:
+ """Outcome of one reconciliation pass (SPEC §7.5 component 5).
+
+ The runner (R2) consults :attr:`is_safe` / :attr:`requires_halt` BEFORE
+ constructing a trading turn. Reconciliation never auto-resends or
+ auto-corrects: a ``requires_halt`` report means the runner halts and
+ surfaces the deltas, in keeping with the no-retry rule (SPEC §8.5).
+
+ Attributes:
+ broker: Broker key this report was produced for.
+ ts: ISO-8601 UTC timestamp (ms precision) of the reconcile pass.
+ deltas: Every classified difference; empty == fully reconciled.
+ recorded_client_order_ids: Client-order-ids we had on file for resting
+ orders, surfaced so the broker layer can dedupe rather than resend.
+ state_persisted: ``True`` when a clean reconcile persisted fresh
+ last-known state; ``False`` when persistence was withheld because
+ the pass was not safe (we never overwrite the durable record of an
+ unresolved ambiguity).
+ had_prior_state: ``False`` on a cold/first start (no prior state file),
+ ``True`` when a prior durable state was loaded and diffed.
+ """
+
+ broker: str
+ ts: str
+ deltas: tuple[ReconcileDelta, ...]
+ recorded_client_order_ids: tuple[str, ...]
+ state_persisted: bool
+ had_prior_state: bool
+
+ @property
+ def is_safe(self) -> bool:
+ """Return ``True`` when no delta requires a halt.
+
+ Safe means the runner may proceed to construct a trading turn. A safe
+ report may still carry benign ``matched`` / ``orphan_order`` deltas; it
+ only excludes the money-moved-without-audit kinds.
+ """
+ return not self.requires_halt
+
+ @property
+ def requires_halt(self) -> bool:
+ """Return ``True`` when any delta means the runner must halt + surface.
+
+ Trips on ``unknown_fill`` or ``mid_order_ambiguous`` — the cases where
+ real money may have moved without a clean audit trail. The no-retry rule
+ forbids resolving these by resending; they must be surfaced to a human.
+ """
+ return any(delta.kind in _HALTING_KINDS for delta in self.deltas)
+
+
+def _utc_now_iso_ms() -> str:
+ """Return the current UTC time as an ISO-8601 string with ms precision."""
+ return datetime.now(timezone.utc).isoformat(timespec="milliseconds")
+
+
+def _client_order_id(recorded_order: Mapping[str, Any]) -> str | None:
+ """Derive a client-order-id from a recorded order for dedupe.
+
+ A client-order-id is the idempotency key the broker echoes back so a caller
+ can recognize its own prior submission instead of resending. We store it on
+ the order when we place it; here we read it back.
+
+ TODO(broker-catalog): the canonical field name is broker-specific. Robinhood
+ Agentic MCP's order schema is not yet frozen (SPEC §9 "still open"), so we
+ look up the well-known aliases below. When the real catalog lands, pin the
+ exact field for each broker in a per-broker map rather than this alias scan.
+
+ Args:
+ recorded_order: One recorded order dict from the durable state.
+
+ Returns:
+ The client-order-id string, or ``None`` when none is recorded.
+ """
+ for key in ("client_order_id", "client_oid", "clientOrderId", "clord_id"):
+ value = recorded_order.get(key)
+ if value:
+ return str(value)
+ return None
+
+
+def _order_identity(order: Mapping[str, Any]) -> str | None:
+ """Return the broker-side identity used to correlate an order across sides.
+
+ Prefers the broker order id; falls back to the client-order-id so a
+ submitted-but-unconfirmed order (which has no broker id yet) still has a
+ stable identity for diffing.
+
+ Args:
+ order: An order dict from either broker truth or recorded state.
+
+ Returns:
+ A stable identity string, or ``None`` when the order carries neither id.
+ """
+ for key in ("order_id", "id", "broker_order_id"):
+ value = order.get(key)
+ if value:
+ return str(value)
+ return _client_order_id(order)
+
+
+def _is_confirmed(recorded_order: Mapping[str, Any]) -> bool:
+ """Return whether a recorded order was durably confirmed before any crash.
+
+ A recorded order is "confirmed" once we audited the broker's acceptance and
+ learned its broker order id. An unconfirmed order is one we submitted but
+ whose fate we never persisted — the mid-order-crash candidate.
+
+ Args:
+ recorded_order: One recorded order dict from the durable state.
+
+ Returns:
+ ``True`` when the order has a broker order id AND a non-pending status.
+ """
+ has_broker_id = any(recorded_order.get(k) for k in ("order_id", "id", "broker_order_id"))
+ status = str(recorded_order.get("status", "")).lower()
+ return has_broker_id and status not in ("", "pending", "submitted", "unconfirmed")
+
+
+def _position_symbol(position: Mapping[str, Any]) -> str | None:
+ """Return the symbol of a position dict, or ``None`` if absent/flat."""
+ symbol = position.get("symbol") or position.get("ticker")
+ return str(symbol) if symbol else None
+
+
+def _position_qty(position: Mapping[str, Any]) -> float:
+ """Return the signed quantity of a position dict (0.0 when absent)."""
+ for key in ("qty", "quantity", "position"):
+ if key in position and position[key] is not None:
+ try:
+ return float(position[key])
+ except (TypeError, ValueError):
+ return 0.0
+ return 0.0
+
+
+def reconcile(
+ broker: str,
+ read_positions: ReadList,
+ read_balance: ReadDict,
+ read_open_orders: ReadList,
+) -> ReconcileReport:
+ """Reconcile broker truth against the durable last-known state.
+
+ Pulls the broker's positions, balance, and open orders through the injected
+ READ callables, diffs them against the state persisted before the last
+ shutdown/crash at ``<runtime_root>/<broker>/runtime_state.json``, classifies
+ every difference, and returns a :class:`ReconcileReport`. The mandate is
+ loaded for provenance/logging context but reconciliation is mandate-shape
+ agnostic. On a clean (safe) reconcile the new last-known state is persisted
+ atomically; on an unsafe one the durable record of the unresolved ambiguity
+ is preserved untouched.
+
+ This function NEVER mutates broker state: it is handed only READ callables
+ and has no write path. The no-retry rule (SPEC §8.5) is enforced by design —
+ an ambiguous order is classified ``mid_order_ambiguous`` and surfaced via
+ :attr:`ReconcileReport.requires_halt`, never resent.
+
+ Args:
+ broker: Broker key, e.g. ``"robinhood"``.
+ read_positions: Injected READ callable returning current broker
+ positions as a sequence of dicts.
+ read_balance: Injected READ callable returning the broker balance dict.
+ read_open_orders: Injected READ callable returning resting/open orders
+ as a sequence of dicts.
+
+ Returns:
+ The classified :class:`ReconcileReport`. The runner consults
+ :attr:`ReconcileReport.is_safe` / :attr:`~ReconcileReport.requires_halt`
+ before deciding whether it may trade this tick.
+ """
+ # Loaded for provenance context only; reconcile does not depend on its shape.
+ mandate = load_mandate(broker)
+ if mandate is None:
+ logger.info("reconcile(%s): no committed mandate on file (provenance only)", broker)
+
+ prior = _load_state(broker)
+ had_prior_state = prior is not None
+ recorded_orders = list(prior.get("open_orders", [])) if prior else []
+ recorded_positions = list(prior.get("positions", [])) if prior else []
+
+ broker_orders = list(read_open_orders())
+ broker_positions = list(read_positions())
+ balance = dict(read_balance()) # pulled for the persisted snapshot + caller context
+
+ # On a cold/first start there is no durable baseline to diff against, so
+ # broker truth simply BECOMES the baseline and there are zero deltas — a
+ # position we never recorded is not an "unknown fill" when we never recorded
+ # anything. Diffing only runs once a prior durable state exists.
+ deltas: list[ReconcileDelta] = []
+ if had_prior_state:
+ deltas.extend(_diff_orders(recorded_orders, broker_orders))
+ deltas.extend(_diff_positions(recorded_positions, broker_positions))
+
+ recorded_client_order_ids = tuple(
+ coid for coid in (_client_order_id(o) for o in recorded_orders) if coid
+ )
+
+ report = ReconcileReport(
+ broker=broker,
+ ts=_utc_now_iso_ms(),
+ deltas=tuple(deltas),
+ recorded_client_order_ids=recorded_client_order_ids,
+ state_persisted=False,
+ had_prior_state=had_prior_state,
+ )
+
+ # Persist fresh last-known state ONLY on a clean reconcile. We never
+ # overwrite the durable record of an unresolved ambiguity — the runner needs
+ # the original recorded order to surface it to a human.
+ if report.is_safe:
+ _persist_state(broker, broker_orders, broker_positions, balance, report.ts)
+ report = ReconcileReport(
+ broker=report.broker,
+ ts=report.ts,
+ deltas=report.deltas,
+ recorded_client_order_ids=report.recorded_client_order_ids,
+ state_persisted=True,
+ had_prior_state=report.had_prior_state,
+ )
+ else:
+ logger.warning(
+ "reconcile(%s): UNSAFE — %d halting delta(s); state NOT advanced",
+ broker,
+ sum(1 for d in report.deltas if d.kind in _HALTING_KINDS),
+ )
+
+ return report
+
+
+def _diff_orders(
+ recorded_orders: Sequence[Mapping[str, Any]],
+ broker_orders: Sequence[Mapping[str, Any]],
+) -> list[ReconcileDelta]:
+ """Classify the order side of the diff.
+
+ Args:
+ recorded_orders: Orders we persisted as open/submitted before shutdown.
+ broker_orders: Orders the broker currently reports as open/resting.
+
+ Returns:
+ One :class:`ReconcileDelta` per order that is matched, orphaned, or
+ mid-order ambiguous. (Unknown broker-side fills surface on the position
+ side via :func:`_diff_positions`; a broker order the recorded side lacks
+ but is still *open* is benign and not raised.)
+ """
+ broker_by_id = {
+ ident: order
+ for order in broker_orders
+ if (ident := _order_identity(order)) is not None
+ }
+
+ deltas: list[ReconcileDelta] = []
+ for recorded in recorded_orders:
+ identity = _order_identity(recorded)
+ coid = _client_order_id(recorded)
+ if identity is not None and identity in broker_by_id:
+ deltas.append(
+ ReconcileDelta(
+ kind=DeltaKind.MATCHED,
+ subject="order",
+ identity=identity,
+ client_order_id=coid,
+ detail="recorded order still open on broker",
+ recorded=dict(recorded),
+ broker=dict(broker_by_id[identity]),
+ )
+ )
+ continue
+
+ # Recorded order the broker does NOT show open. The split hinges on
+ # whether we durably confirmed it before the crash.
+ if _is_confirmed(recorded):
+ deltas.append(
+ ReconcileDelta(
+ kind=DeltaKind.ORPHAN_ORDER,
+ subject="order",
+ identity=identity or (coid or "<unknown>"),
+ client_order_id=coid,
+ detail=(
+ "confirmed order absent from broker open-orders "
+ "(cancelled / rejected / filled-and-cleared); not resent"
+ ),
+ recorded=dict(recorded),
+ broker=None,
+ )
+ )
+ else:
+ deltas.append(
+ ReconcileDelta(
+ kind=DeltaKind.MID_ORDER_AMBIGUOUS,
+ subject="order",
+ identity=identity or (coid or "<unknown>"),
+ client_order_id=coid,
+ detail=(
+ "submitted-but-unconfirmed order: may have filled before "
+ "the audit write; no-retry rule forbids resend — surfaced "
+ "for halt"
+ ),
+ recorded=dict(recorded),
+ broker=None,
+ )
+ )
+ return deltas
+
+
+def _diff_positions(
+ recorded_positions: Sequence[Mapping[str, Any]],
+ broker_positions: Sequence[Mapping[str, Any]],
+) -> list[ReconcileDelta]:
+ """Classify the position side of the diff.
+
+ A broker position (or quantity) we have no record of is an ``unknown_fill``:
+ real money moved without a matching audit record. A recorded position that
+ still matches broker truth is ``matched``.
+
+ Args:
+ recorded_positions: Positions we persisted before shutdown.
+ broker_positions: Positions the broker currently reports.
+
+ Returns:
+ One :class:`ReconcileDelta` per symbol where broker truth diverges from
+ (or matches) the recorded snapshot.
+ """
+ recorded_by_symbol = {
+ sym: _position_qty(p)
+ for p in recorded_positions
+ if (sym := _position_symbol(p)) is not None
+ }
+
+ deltas: list[ReconcileDelta] = []
+ for position in broker_positions:
+ symbol = _position_symbol(position)
+ if symbol is None:
+ continue
+ broker_qty = _position_qty(position)
+ recorded_qty = recorded_by_symbol.get(symbol)
+ if recorded_qty is not None and recorded_qty == broker_qty:
+ deltas.append(
+ ReconcileDelta(
+ kind=DeltaKind.MATCHED,
+ subject="position",
+ identity=symbol,
+ client_order_id=None,
+ detail="recorded position matches broker truth",
+ recorded={"symbol": symbol, "qty": recorded_qty},
+ broker=dict(position),
+ )
+ )
+ else:
+ deltas.append(
+ ReconcileDelta(
+ kind=DeltaKind.UNKNOWN_FILL,
+ subject="position",
+ identity=symbol,
+ client_order_id=None,
+ detail=(
+ "broker reports a position/quantity we have no record of "
+ f"(recorded={recorded_qty}, broker={broker_qty}); "
+ "real money moved without a matching audit record"
+ ),
+ recorded=(
+ None
+ if recorded_qty is None
+ else {"symbol": symbol, "qty": recorded_qty}
+ ),
+ broker=dict(position),
+ )
+ )
+ return deltas
+
+
+def _state_path(broker: str) -> Path:
+ """Return the durable runtime-state path for ``broker``."""
+ return broker_dir(broker) / _STATE_FILENAME
+
+
+def _load_state(broker: str) -> dict[str, Any] | None:
+ """Load the durable last-known runtime state for ``broker``.
+
+ Loading is fail-open-to-cold-start: a missing file means a first/cold start
+ (``None``). A *corrupt* file is NOT silently treated as cold start — that
+ would hide a partial write — it is renamed aside and surfaced as a fresh
+ start so the diff can never run against a half-truth.
+
+ Args:
+ broker: Broker key.
+
+ Returns:
+ The decoded state dict, or ``None`` on cold start / unreadable state.
+ """
+ path = _state_path(broker)
+ if not path.is_file():
+ return None
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as exc:
+ corrupt = path.with_name(f"{path.name}.corrupt-{int(datetime.now().timestamp())}")
+ try:
+ os.replace(path, corrupt)
+ except OSError:
+ pass
+ logger.warning(
+ "reconcile(%s): runtime_state.json unreadable (%s); renamed to %s, cold start",
+ broker,
+ exc,
+ corrupt.name,
+ )
+ return None
+ if not isinstance(raw, dict):
+ logger.warning("reconcile(%s): runtime_state.json is not an object; cold start", broker)
+ return None
+ return raw
+
+
+def _persist_state(
+ broker: str,
+ open_orders: Sequence[Mapping[str, Any]],
+ positions: Sequence[Mapping[str, Any]],
+ balance: Mapping[str, Any],
+ ts: str,
+) -> None:
+ """Persist the new last-known state atomically (temp + ``os.replace``).
+
+ A same-directory temp file is written then atomically renamed over the
+ target, so a SIGKILL mid-write can never leave a truncated state file a later
+ reconcile would misread (mirrors the mandate commit + scheduler store
+ pattern, SPEC §7.5 component 1).
+
+ Args:
+ broker: Broker key.
+ open_orders: Broker-truth open orders to record as the new baseline.
+ positions: Broker-truth positions to record as the new baseline.
+ balance: Broker-truth balance snapshot.
+ ts: ISO-8601 UTC timestamp to stamp the state with.
+ """
+ payload = {
+ "schema_version": RUNTIME_STATE_SCHEMA_VERSION,
+ "broker": broker,
+ "reconciled_at": ts,
+ "open_orders": [dict(o) for o in open_orders],
+ "positions": [dict(p) for p in positions],
+ "balance": dict(balance),
+ }
+ path = _state_path(broker)
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ tmp = path.with_name(f".{path.name}.tmp")
+ tmp.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
+ try:
+ os.chmod(tmp, 0o600)
+ except OSError:
+ # Best-effort on platforms without POSIX perms (e.g. Windows).
+ pass
+ os.replace(tmp, path)
diff --git a/agent/src/live/runtime/runner.py b/agent/src/live/runtime/runner.py
new file mode 100644
index 000000000..c558178aa
--- /dev/null
+++ b/agent/src/live/runtime/runner.py
@@ -0,0 +1,797 @@
+"""Persistent live-trading runner loop (SPEC.md §7.5 components 2 + 7).
+
+The runner is the persistent process that turns the interactive consent channel
+into an *autonomous* one: it wakes on a schedule / market trigger, decides and
+trades inside the committed mandate, sleeps, and survives restarts. This module
+implements two of the eight §7.5 components:
+
+* **Component 2 — Runner loop.** Per tick, in a fixed fail-closed order:
+ ``halt → proactive expiry → reconciliation → autonomous turn → audit``. The
+ mandate is **pinned inline** into the turn prompt this runner constructs so it
+ survives ``loop.py`` 5-layer compaction — done in the runner-owned prompt
+ string, never by editing the protected ``src/agent/context.py``.
+* **Component 7 — Proactive expiry.** ``ConsentMeta.expires_at`` is checked every
+ tick (not only at order time): an expired mandate trips a stop and clears
+ authority *before* any agent invocation, so a dead mandate never reaches the
+ order path.
+
+Trust + safety invariants honored here:
+
+* **Caller-only agent invocation.** The agent is reached solely through the
+ existing public entry (an injected async caller bound to
+ ``SessionService.send_message`` by default). This module never imports or edits
+ ``src/agent/`` or ``src/session/`` internals — it is a *caller*.
+* **No-retry on mutating calls (§8 finding 5).** When reconciliation surfaces an
+ unsafe / ambiguous broker state (e.g. a mid-order crash where a fill may have
+ landed before the audit write), the tick **aborts** — it never auto-resends.
+ Reconciliation, not re-send, closes the cross-restart double-trade hole.
+* **Resume-via-recompute.** :meth:`LiveRunner.run_loop` reloads the mandate and
+ recomputes the schedule on (re)start; there is no mid-task checkpoint.
+
+Every external dependency — scheduler, triggers, reconcile, the agent caller and
+the clock — is injectable, so the runner is unit-testable with no live agent or
+broker. See ``docs/live-trading/SPEC.md`` §7.5.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Any, Awaitable, Callable, Mapping, Protocol
+
+from src.live.audit import LiveActionEvent, write_live_action
+from src.live.halt import halt_flag_set, trip_halt
+from src.live.mandate.model import Mandate
+from src.live.mandate.store import load_mandate
+from src.live.runtime.flatten import flatten_and_cancel
+from src.live.runtime.jobstore import JobStore
+from src.live.runtime.liveness import write_heartbeat
+from src.live.runtime.scheduler import Job, Scheduler
+from src.live.runtime.triggers import Trigger, due_now
+
+logger = logging.getLogger(__name__)
+
+#: Tick outcome codes (the ``outcome`` key of :meth:`LiveRunner.run_once`).
+TICK_HALTED = "halted"
+TICK_NO_MANDATE = "no_mandate"
+TICK_EXPIRED = "expired"
+TICK_RECONCILE_UNSAFE = "reconcile_unsafe"
+TICK_RECONCILE_ERROR = "reconcile_error"
+TICK_INVOKED = "invoked"
+TICK_ERROR = "error"
+
+#: Stop-source attribution recorded on the HALT sentinel when the runner trips it.
+_RUNNER_TRIP_SOURCE = "file"
+
+#: Default watch cadence (ms) for a MARKET trigger — the runner wakes on this
+#: interval and the tick itself re-checks market state + mandate. 60s keeps the
+#: runner responsive without hammering the broker. Operator-configurable per
+#: runner via ``LiveRunner(market_watch_ms=...)``; it is an operational polling
+#: knob, NOT a user-authorized safety limit, so it lives on the runner (not the
+#: mandate, which carries only trading limits).
+_DEFAULT_MARKET_WATCH_MS = 60_000
+
+# ---- Injected dependency contracts (duck-typed; coded blind against R1/R3/R4) -
+
+
+class _Job(Protocol):
+ """Minimal :class:`src.live.runtime.scheduler.Job` view the runner relies on."""
+
+ id: str
+ next_run_at: int
+ schedule: Any
+
+
+class _Scheduler(Protocol):
+ """Minimal :class:`src.live.runtime.scheduler.Scheduler` view (R1 contract)."""
+
+ def start(self) -> Any: ...
+
+ def stop(self) -> Any: ...
+
+ def add_job(self, job: _Job) -> Any: ...
+
+ def remove_job(self, job_id: str) -> Any: ...
+
+
+#: Async agent caller: ``(session_id, prompt) -> result dict``. Bound by default
+#: to the public ``SessionService.send_message`` entry (never the loop internals).
+AgentCaller = Callable[[str, str], Awaitable[Mapping[str, Any]]]
+
+#: Reconcile callable matching R4: ``reconcile(broker, read_positions,
+#: read_balance, read_open_orders) -> ReconcileReport``.
+ReconcileFn = Callable[..., Any]
+
+#: Broker READ callables injected into reconciliation (no write surface).
+ReadCallable = Callable[[], Any]
+
+#: Broker WRITE callable (place/cancel) injected for the preemptive halt sweep.
+#: Receives a normalized order/cancel dict, returns the broker's raw response.
+SubmitCallable = Callable[[dict[str, Any]], Mapping[str, Any]]
+
+#: Preemptive flatten action signature (mirrors
+#: :func:`src.live.runtime.flatten.flatten_and_cancel`). Injectable so a test can
+#: assert it fires exactly once on a halt trip without a real broker.
+FlattenFn = Callable[..., Mapping[str, Any]]
+
+#: Heartbeat writer signature (mirrors
+#: :func:`src.live.runtime.liveness.write_heartbeat`). Injectable so a test can
+#: observe the per-tick liveness write without touching the filesystem.
+HeartbeatFn = Callable[..., int]
+
+#: Clock returning a timezone-aware UTC ``datetime`` (injected for determinism).
+ClockFn = Callable[[], datetime]
+
+
+def _default_clock() -> datetime:
+ """Return the current time as a timezone-aware UTC ``datetime``."""
+ return datetime.now(timezone.utc)
+
+
+def _report_is_unsafe(report: Any) -> bool:
+ """Return whether a reconcile report flags an unsafe / ambiguous state.
+
+ R4 owns :class:`~src.live.runtime.reconcile.ReconcileReport`; its concrete
+ field name is not frozen in this parcel's contract, so this reads the report
+ defensively across the plausible shapes and **fail-closes** (treats an
+ unrecognized report as unsafe) so an ambiguous broker state can never slip
+ into the trading path.
+
+ Args:
+ report: The object returned by the injected reconcile callable.
+
+ Returns:
+ ``True`` if the report is unsafe / ambiguous (abort the tick).
+ """
+ if report is None:
+ return True
+ # Positive-safety attributes: present + truthy means safe.
+ for safe_attr in ("safe_to_trade", "is_safe", "safe", "ok", "clean"):
+ if hasattr(report, safe_attr):
+ return not bool(getattr(report, safe_attr))
+ # Negative attributes: present + truthy means unsafe.
+ for unsafe_attr in ("unsafe", "ambiguous", "has_discrepancies", "discrepancies"):
+ if hasattr(report, unsafe_attr):
+ return bool(getattr(report, unsafe_attr))
+ # An unrecognized report shape cannot be proven safe.
+ return True
+
+
+def _parse_expiry(raw: str) -> datetime | None:
+ """Parse an ISO-8601 UTC ``expires_at`` string into an aware ``datetime``.
+
+ The mandate commit path writes the expiry with a trailing ``Z`` (e.g.
+ ``2026-06-28T00:00:00Z``); :func:`datetime.fromisoformat` does not accept
+ ``Z`` before Python 3.11, so it is normalized to ``+00:00`` first. A naive
+ result is assumed UTC. Returns ``None`` when the value cannot be parsed so
+ the caller can fail-closed.
+
+ Args:
+ raw: The ``ConsentMeta.expires_at`` value.
+
+ Returns:
+ A timezone-aware UTC ``datetime``, or ``None`` if unparseable.
+ """
+ if not isinstance(raw, str) or not raw.strip():
+ return None
+ normalized = raw.strip()
+ if normalized.endswith(("Z", "z")):
+ normalized = normalized[:-1] + "+00:00"
+ try:
+ parsed = datetime.fromisoformat(normalized)
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed.astimezone(timezone.utc)
+
+
+def _mandate_is_expired(mandate: Mandate, now: datetime) -> bool:
+ """Return whether ``mandate`` is at/past its expiry as of ``now`` (fail-closed).
+
+ An unparseable ``expires_at`` is treated as expired: a live mandate with a
+ malformed expiry must not keep trading (mirrors
+ ``order_guard._is_expired``).
+
+ Args:
+ mandate: The loaded mandate.
+ now: The injected current UTC time.
+
+ Returns:
+ ``True`` if the mandate is dead.
+ """
+ expires = _parse_expiry(mandate.consent.expires_at)
+ if expires is None:
+ return True
+ return now >= expires
+
+
+def _pin_mandate_prompt(broker: str, mandate: Mandate, now: datetime) -> str:
+ """Build the autonomous-turn prompt with the full mandate pinned inline.
+
+ The mandate text is embedded directly in the prompt this runner owns so it
+ survives ``loop.py`` context compaction — the protected ``context.py`` is
+ NOT touched. The prompt states the bounded-autonomy contract explicitly: the
+ agent trades freely *inside* these limits and must defer (never breach) on
+ any action that would exceed them; the enforcement gate is the hard backstop.
+
+ Args:
+ broker: Broker key the runner drives.
+ mandate: The active, unexpired mandate.
+ now: The injected current UTC time (stamped into the prompt for the LLM).
+
+ Returns:
+ The full autonomous-turn user prompt.
+ """
+ caps = mandate.hard_caps
+ universe = mandate.universe
+ instruments = ", ".join(i.value for i in caps.allowed_instruments) or "(none)"
+ asset_classes = ", ".join(a.value for a in universe.asset_classes) or "(none)"
+ excluded = ", ".join(universe.exclude_symbols) or "(none)"
+ return (
+ "You are running an AUTONOMOUS live-trading tick under a bounded "
+ "mandate. Trade freely INSIDE the limits below; you must NEVER place an "
+ "order that would breach any limit — defer instead. The enforcement "
+ "gate and kill switch are hard backstops outside your control.\n\n"
+ f"Broker: {broker}\n"
+ f"Tick time (UTC): {now.isoformat(timespec='seconds')}\n"
+ f"Mandate expires (UTC): {mandate.consent.expires_at}\n\n"
+ "=== HARD CAPS (vibe-enforced; broker funding is the absolute ceiling) ===\n"
+ f"- Account funding (USD): {caps.account_funding_usd}\n"
+ f"- Max single-order notional (USD): {caps.max_order_notional_usd}\n"
+ f"- Max total exposure (USD): {caps.max_total_exposure_usd}\n"
+ f"- Max gross leverage: {caps.max_leverage}\n"
+ f"- Allowed instruments: {instruments}\n"
+ f"- Max trades per UTC day: {caps.max_trades_per_day}\n\n"
+ "=== DISCOVERY UNIVERSE (pick symbols within these structural filters) ===\n"
+ f"- Asset classes: {asset_classes}\n"
+ f"- Min market cap (USD): {universe.min_market_cap_usd}\n"
+ f"- Min avg daily volume (USD): {universe.min_avg_daily_volume_usd}\n"
+ f"- Excluded symbols (hard denylist): {excluded}\n\n"
+ "Assess the current opportunity set, then act within the mandate. If no "
+ "action is warranted this tick, hold and explain why."
+ )
+
+
+@dataclass(frozen=True)
+class TickResult:
+ """Immutable outcome of one :meth:`LiveRunner.run_once` tick.
+
+ Attributes:
+ outcome: One of the ``TICK_*`` codes.
+ broker: Broker the tick ran for.
+ reason: Human-readable detail (empty when not applicable).
+ agent_result: The raw result dict from the agent caller when the tick
+ reached the invocation step, else ``None``.
+ audit_id: The audit record id written for this tick, when one was
+ written, else ``None``.
+ """
+
+ outcome: str
+ broker: str
+ reason: str = ""
+ agent_result: Mapping[str, Any] | None = None
+ audit_id: str | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ """Return a plain JSON-serializable view of this tick result."""
+ return {
+ "outcome": self.outcome,
+ "broker": self.broker,
+ "reason": self.reason,
+ "agent_result": dict(self.agent_result) if self.agent_result else None,
+ "audit_id": self.audit_id,
+ }
+
+
+class LiveRunner:
+ """Persistent autonomous runner for one live broker channel (§7.5 #2, #7).
+
+ The runner owns the per-tick ordering and the scheduling loop. Every external
+ dependency is injected, so the class is fully unit-testable without a live
+ agent or broker.
+
+ Attributes:
+ broker: Broker key this runner drives (e.g. ``"robinhood"``).
+ """
+
+ def __init__(
+ self,
+ broker: str,
+ *,
+ agent_caller: AgentCaller,
+ reconcile_fn: ReconcileFn,
+ read_positions: ReadCallable,
+ read_balance: ReadCallable,
+ read_open_orders: ReadCallable,
+ scheduler: _Scheduler | None = None,
+ clock: ClockFn = _default_clock,
+ load_mandate_fn: Callable[[str], Mandate | None] = load_mandate,
+ write_audit_fn: Callable[[LiveActionEvent], Mapping[str, Any]] = write_live_action,
+ halt_flag_fn: Callable[[str | None], bool] = halt_flag_set,
+ trip_halt_fn: Callable[..., Any] = trip_halt,
+ report_unsafe_fn: Callable[[Any], bool] = _report_is_unsafe,
+ submit_fn: SubmitCallable | None = None,
+ flatten_fn: FlattenFn = flatten_and_cancel,
+ heartbeat_fn: HeartbeatFn = write_heartbeat,
+ job_store: JobStore | None = None,
+ triggers: list[Trigger] | None = None,
+ market_watch_ms: int = _DEFAULT_MARKET_WATCH_MS,
+ session_id: str = "",
+ ) -> None:
+ """Initialize the runner.
+
+ Args:
+ broker: Broker key this runner drives.
+ agent_caller: Async ``(session_id, prompt) -> result`` caller bound to
+ the public ``SessionService`` entry. The runner never touches the
+ agent loop internals.
+ reconcile_fn: R4 ``reconcile(broker, read_positions, read_balance,
+ read_open_orders) -> ReconcileReport``.
+ read_positions: Broker READ callable for current positions.
+ read_balance: Broker READ callable for the account balance.
+ read_open_orders: Broker READ callable for resting open orders.
+ scheduler: R1 scheduler used by :meth:`run_loop`. May be ``None`` when
+ only :meth:`run_once` is exercised.
+ clock: Injectable UTC clock for deterministic expiry tests.
+ load_mandate_fn: Injectable mandate loader (defaults to the protected
+ read-only store loader).
+ write_audit_fn: Injectable audit writer.
+ halt_flag_fn: Injectable halt check.
+ trip_halt_fn: Injectable halt tripper (used on proactive expiry).
+ report_unsafe_fn: Predicate deciding whether a reconcile report is
+ unsafe/ambiguous (defaults to the defensive duck-typed check).
+ submit_fn: Broker WRITE callable (place/cancel) used ONLY by the
+ preemptive halt sweep. ``None`` (default) means no write surface
+ is wired, so a halt trip cancels/flattens nothing it cannot reach
+ — the cooperative gate still blocks future orders. The real
+ factory binds the broker's ``place_order`` / ``cancel_order``
+ tools here.
+ flatten_fn: Preemptive sweep action (defaults to
+ :func:`src.live.runtime.flatten.flatten_and_cancel`). Injectable
+ so a test can assert it fires exactly once on a trip.
+ heartbeat_fn: Liveness writer (defaults to
+ :func:`src.live.runtime.liveness.write_heartbeat`). Called every
+ tick and every loop iteration, keyed by :attr:`runner_id`.
+ job_store: Durable job store (R1) loaded on :meth:`run_loop` start for
+ resume-via-recompute. ``None`` (default) constructs the default
+ store lazily inside :meth:`run_loop`.
+ triggers: Watch triggers (R3) the runner schedules ticks from when no
+ explicit ``jobs`` are passed to :meth:`run_loop`. ``None`` means
+ no trigger-derived jobs (a caller may pass jobs directly).
+ market_watch_ms: Polling cadence (ms) a MARKET trigger wakes the
+ runner on; the tick re-checks market state + mandate each wake.
+ An operational knob (default 60s), NOT a safety limit — non-positive
+ values fall back to the default.
+ session_id: Session id passed to the agent caller + audit records.
+ """
+ self.broker = broker
+ self._agent_caller = agent_caller
+ self._reconcile_fn = reconcile_fn
+ self._read_positions = read_positions
+ self._read_balance = read_balance
+ self._read_open_orders = read_open_orders
+ self._scheduler = scheduler
+ self._clock = clock
+ self._load_mandate = load_mandate_fn
+ self._write_audit = write_audit_fn
+ self._halt_flag = halt_flag_fn
+ self._trip_halt = trip_halt_fn
+ self._report_unsafe = report_unsafe_fn
+ self._submit_fn = submit_fn
+ self._flatten_fn = flatten_fn
+ self._heartbeat = heartbeat_fn
+ self._job_store = job_store
+ self._triggers = list(triggers or [])
+ self._market_watch_ms = market_watch_ms if market_watch_ms > 0 else _DEFAULT_MARKET_WATCH_MS
+ self._session_id = session_id or f"live-{broker}"
+ #: Set once the preemptive sweep has fired so a tripped channel never
+ #: flattens twice across consecutive ticks (no-retry, SPEC §8.5).
+ self._flatten_fired = False
+
+ @property
+ def runner_id(self) -> str:
+ """Return the liveness / heartbeat key for this runner.
+
+ Aligned with the API server's ``_runner_liveness_state`` and the CLI
+ ``live status`` path, both of which read liveness keyed by the bare
+ broker key. Keeping the heartbeat key identical is what makes a running
+ runner show as *alive* rather than perpetually dead.
+
+ Returns:
+ The broker key (the runner id the status path expects).
+ """
+ return self.broker
+
+ async def run_once(self) -> dict[str, Any]:
+ """Run ONE fail-closed tick in fixed order; return the outcome dict.
+
+ Ordering (each step short-circuits the tick on failure):
+
+ 1. **Halt** — if the kill switch is tripped, abort, audit, return.
+ 2. **Mandate + proactive expiry** — load the mandate; if absent or past
+ ``expires_at``, trip a stop + clear authority + audit, and return
+ BEFORE any agent invocation. A dead mandate never reaches step 5.
+ 3. **Reconcile** — pull broker truth via the injected READ callables; an
+ unsafe/ambiguous report aborts the tick (no auto-resend, §8 finding 5).
+ 4. **Pin + invoke** — build the autonomous-turn prompt with the full
+ mandate inline and invoke the agent through the public caller.
+ 5. **Audit** — record the tick outcome.
+
+ Returns:
+ A JSON-serializable tick result (see :meth:`TickResult.to_dict`).
+ """
+ now = self._clock()
+ self._write_heartbeat(now)
+
+ if self._halt_flag(self.broker):
+ return self._halted_result()
+
+ mandate = self._load_mandate(self.broker)
+ if mandate is None:
+ return self._no_mandate_result()
+ if _mandate_is_expired(mandate, now):
+ return self._expired_result()
+
+ reconcile_outcome = self._run_reconcile()
+ if reconcile_outcome is not None:
+ return reconcile_outcome
+
+ return await self._invoke_and_audit(mandate, now)
+
+ def _run_reconcile(self) -> dict[str, Any] | None:
+ """Reconcile broker truth before trading; abort on unsafe/error.
+
+ Returns:
+ A tick result dict when the tick must abort (unsafe state or a
+ reconcile failure — fail-closed), or ``None`` when it is safe to
+ proceed to the agent invocation.
+ """
+ try:
+ report = self._reconcile_fn(
+ self.broker,
+ self._read_positions,
+ self._read_balance,
+ self._read_open_orders,
+ )
+ except Exception as exc: # Reconcile failure is fail-closed: do not trade.
+ logger.warning("live reconcile failed for %s: %s", self.broker, exc)
+ audit_id = self._audit(
+ kind="breach",
+ outcome="blocked",
+ intent="reconcile failed — tick aborted (fail-closed)",
+ error=str(exc),
+ )
+ return TickResult(
+ outcome=TICK_RECONCILE_ERROR,
+ broker=self.broker,
+ reason="reconcile raised; tick aborted",
+ audit_id=audit_id,
+ ).to_dict()
+
+ if self._report_unsafe(report):
+ logger.warning("live reconcile unsafe for %s — aborting tick", self.broker)
+ audit_id = self._audit(
+ kind="breach",
+ outcome="blocked",
+ intent="reconcile flagged unsafe/ambiguous — no auto-resend",
+ )
+ return TickResult(
+ outcome=TICK_RECONCILE_UNSAFE,
+ broker=self.broker,
+ reason="reconcile flagged unsafe/ambiguous broker state",
+ audit_id=audit_id,
+ ).to_dict()
+ return None
+
+ async def _invoke_and_audit(self, mandate: Mandate, now: datetime) -> dict[str, Any]:
+ """Invoke the agent with the pinned mandate, then audit the outcome.
+
+ Args:
+ mandate: The active, unexpired mandate to pin inline.
+ now: The injected tick time.
+
+ Returns:
+ The tick result dict.
+ """
+ prompt = _pin_mandate_prompt(self.broker, mandate, now)
+ try:
+ result = await self._agent_caller(self._session_id, prompt)
+ except Exception as exc:
+ logger.exception("live agent invocation failed for %s", self.broker)
+ audit_id = self._audit(
+ kind="breach",
+ outcome="error",
+ intent="autonomous tick — agent invocation error",
+ error=str(exc),
+ )
+ return TickResult(
+ outcome=TICK_ERROR,
+ broker=self.broker,
+ reason=str(exc),
+ audit_id=audit_id,
+ ).to_dict()
+
+ audit_id = self._audit(
+ kind="order_placed",
+ outcome="accepted",
+ intent="autonomous tick completed",
+ )
+ return TickResult(
+ outcome=TICK_INVOKED,
+ broker=self.broker,
+ agent_result=result,
+ audit_id=audit_id,
+ ).to_dict()
+
+ def _write_heartbeat(self, now: datetime) -> None:
+ """Record a liveness heartbeat for this tick (best-effort).
+
+ A failed heartbeat write must never abort a tick (the trading decision is
+ far more important than the liveness signal), so the error is logged and
+ swallowed — a missed heartbeat only makes the runner *look* stale, which
+ the reaper handles safely.
+
+ Args:
+ now: The tick's UTC time, converted to epoch ms for the heartbeat.
+ """
+ try:
+ self._heartbeat(self.runner_id, now_ms=int(now.timestamp() * 1000))
+ except Exception: # noqa: BLE001 — liveness must not break trading
+ logger.warning("failed to write heartbeat for %s", self.runner_id, exc_info=True)
+
+ def _halted_result(self) -> dict[str, Any]:
+ """Fire the preemptive sweep ONCE, audit, and return for a halted tick.
+
+ This closes Hole #1 (SPEC §7.5 #6): a tripped halt is no longer merely
+ cooperative (refuse the next order). The runner cancels every resting
+ order and — per the mandate's flatten flag — flattens open positions, via
+ the injected broker submit callable. The sweep runs at most once per
+ runner lifetime (``_flatten_fired`` latch): a halted channel that keeps
+ ticking must not re-submit closes (no-retry, SPEC §8.5). With no broker
+ write surface wired (``submit_fn is None``) the sweep is skipped and the
+ cooperative gate alone blocks future orders.
+ """
+ self._run_preemptive_sweep()
+ audit_id = self._audit(
+ kind="halt_tripped",
+ outcome="blocked",
+ intent="tick aborted — kill switch tripped",
+ )
+ return TickResult(
+ outcome=TICK_HALTED,
+ broker=self.broker,
+ reason="kill switch tripped",
+ audit_id=audit_id,
+ ).to_dict()
+
+ def _run_preemptive_sweep(self) -> None:
+ """Cancel resting orders + (per mandate) flatten positions, exactly once.
+
+ Invoked the moment the runner observes a tripped HALT. Idempotent across
+ ticks via the ``_flatten_fired`` latch so the no-retry rule (SPEC §8.5)
+ holds even if the halted runner keeps waking. A sweep failure is audited
+ but not retried — flatten/cancel side effects are not idempotent.
+ """
+ if self._flatten_fired or self._submit_fn is None:
+ return
+ self._flatten_fired = True
+ try:
+ self._flatten_fn(
+ self.broker,
+ self._submit_fn,
+ self._read_positions,
+ self._read_open_orders,
+ )
+ except Exception as exc: # noqa: BLE001 — surfaced via audit, never retried
+ logger.exception("preemptive flatten failed for %s", self.broker)
+ self._audit(
+ kind="breach",
+ outcome="error",
+ intent="preemptive halt sweep failed — not retried (no-retry §8.5)",
+ error=str(exc),
+ )
+
+ def _no_mandate_result(self) -> dict[str, Any]:
+ """Audit + return the result when no valid mandate is on file."""
+ audit_id = self._audit(
+ kind="order_rejected",
+ outcome="blocked",
+ intent="tick aborted — no valid mandate on file",
+ )
+ return TickResult(
+ outcome=TICK_NO_MANDATE,
+ broker=self.broker,
+ reason="no valid mandate",
+ audit_id=audit_id,
+ ).to_dict()
+
+ def _expired_result(self) -> dict[str, Any]:
+ """Trip a stop, clear authority, audit, and return on proactive expiry.
+
+ This is the §7.5 component-7 proactive path: expiry is acted on in the
+ tick, not deferred to the next order attempt, so a dead mandate never
+ reaches the agent invocation. The kill switch is tripped (per-broker) so
+ all in-flight live authority for this channel is cut immediately.
+ """
+ try:
+ self._trip_halt(
+ _RUNNER_TRIP_SOURCE,
+ "mandate expired — proactive runner stop",
+ broker=self.broker,
+ )
+ except Exception: # A trip failure must not swallow the expiry outcome.
+ logger.exception("failed to trip halt on expiry for %s", self.broker)
+ audit_id = self._audit(
+ kind="halt_tripped",
+ outcome="blocked",
+ intent="mandate expired — proactive stop, authority revoked",
+ )
+ return TickResult(
+ outcome=TICK_EXPIRED,
+ broker=self.broker,
+ reason="mandate expired — proactive stop",
+ audit_id=audit_id,
+ ).to_dict()
+
+ def _audit(
+ self,
+ *,
+ kind: str,
+ outcome: str,
+ intent: str,
+ error: str | None = None,
+ ) -> str | None:
+ """Write one live-action audit record for a tick outcome.
+
+ Audit failures are swallowed (logged) so a ledger problem can never make
+ a *blocking* tick outcome look like it proceeded.
+
+ Args:
+ kind: The :class:`~src.live.audit.LiveActionKind`.
+ outcome: The :class:`~src.live.audit.LiveActionOutcome`.
+ intent: Normalized human-readable intent string.
+ error: Optional error description.
+
+ Returns:
+ The written record's ``audit_id``, or ``None`` if the write failed.
+ """
+ event = LiveActionEvent(
+ kind=kind, # type: ignore[arg-type]
+ session_id=self._session_id,
+ outcome=outcome, # type: ignore[arg-type]
+ server=self.broker,
+ intent_normalized=intent,
+ error=error,
+ )
+ try:
+ record = self._write_audit(event)
+ except Exception:
+ logger.exception("failed to write live-action audit for %s", self.broker)
+ return None
+ return record.get("audit_id") if isinstance(record, Mapping) else event.audit_id
+
+ def run_loop(self, jobs: list[_Job] | None = None) -> None:
+ """Start the scheduler and register tick jobs (resume-via-recompute).
+
+ On every (re)start this recomputes from durable inputs — it reloads the
+ mandate and registers the watch-cadence jobs — rather than restoring a
+ mid-task checkpoint (§7.5: "Resume-via-recompute on restart … not mid-task
+ checkpoint"). When the mandate is absent or already expired, the loop is
+ NOT started: there is nothing to schedule and a dead mandate must not
+ wake the runner.
+
+ The scheduler (R1) and triggers (R3) own the wall-clock firing; this
+ method only wires the jobs and starts the scheduler. The scheduler is
+ expected to invoke :meth:`run_once` per fired job.
+
+ Args:
+ jobs: Watch-cadence jobs to register (R1 :class:`Job` instances). When
+ ``None``, the runner recomputes its jobs from durable inputs:
+ first any jobs persisted in the durable job store (resume), else
+ jobs synthesized from the injected triggers (R3). Only when there
+ are neither does the scheduler start empty.
+
+ Raises:
+ RuntimeError: If no scheduler was injected.
+ """
+ if self._scheduler is None:
+ raise RuntimeError("run_loop requires an injected scheduler")
+
+ now = self._clock()
+ mandate = self._load_mandate(self.broker)
+ if mandate is None:
+ logger.warning("live runner not starting for %s: no mandate", self.broker)
+ return
+ if _mandate_is_expired(mandate, now):
+ logger.warning("live runner not starting for %s: mandate expired", self.broker)
+ self._expired_result()
+ return
+
+ resolved_jobs = self._resolve_jobs(jobs, now)
+ for job in resolved_jobs:
+ self._scheduler.add_job(job)
+ self._scheduler.start()
+ logger.info(
+ "live runner started for %s with %d job(s)", self.broker, len(resolved_jobs)
+ )
+
+ def _resolve_jobs(self, jobs: list[_Job] | None, now: datetime) -> list[Job]:
+ """Recompute the watch-cadence jobs on (re)start (resume-via-recompute).
+
+ Precedence: an explicit ``jobs`` arg wins (test / caller injection); else
+ durable jobs reloaded from the job store (a restart resumes the same
+ cadence); else jobs synthesized from the injected triggers (R3) and
+ persisted so the next restart resumes them. Never a mid-task checkpoint —
+ just the schedule, recomputed from durable inputs.
+
+ Args:
+ jobs: Explicit jobs to use, or ``None`` to recompute.
+ now: Current UTC time (anchors the first fire of synthesized jobs).
+
+ Returns:
+ The list of :class:`Job` to register with the scheduler.
+ """
+ if jobs is not None:
+ return list(jobs)
+
+ store = self._job_store or JobStore()
+ try:
+ persisted = store.load()
+ except Exception: # noqa: BLE001 — a corrupt store must not wedge start
+ logger.exception("job store load failed for %s; recomputing", self.broker)
+ persisted = []
+ if persisted:
+ return persisted
+
+ synthesized = self._jobs_from_triggers(now)
+ if synthesized:
+ try:
+ store.save(synthesized)
+ except Exception: # noqa: BLE001 — persistence is best-effort at start
+ logger.exception("job store save failed for %s", self.broker)
+ return synthesized
+
+ def _jobs_from_triggers(self, now: datetime) -> list[Job]:
+ """Convert the injected triggers (R3) into schedulable watch jobs (R1).
+
+ INTERVAL triggers map to an ``interval:<ms>`` job on their own cadence;
+ MARKET triggers map to a default watch-cadence interval job (the tick
+ itself re-checks market state + mandate); EVENT triggers are skipped here
+ because they fire from an out-of-band event source, not the wall clock.
+
+ Args:
+ now: Current UTC time, used to anchor the first fire.
+
+ Returns:
+ One :class:`Job` per schedulable trigger.
+ """
+ now_ms = int(now.timestamp() * 1000)
+ built: list[Job] = []
+ for index, trigger in enumerate(self._triggers):
+ kind = getattr(trigger, "kind", None)
+ kind_value = getattr(kind, "value", kind)
+ if kind_value == "interval":
+ interval_ms = int(trigger.interval_ms)
+ elif kind_value == "market":
+ interval_ms = self._market_watch_ms
+ else: # event triggers fire out-of-band, not via the wall clock
+ logger.info(
+ "skipping non-wall-clock trigger %s for %s", kind_value, self.broker
+ )
+ continue
+ built.append(
+ Job(
+ id=f"{self.broker}-{kind_value}-{index}",
+ next_run_at=now_ms + interval_ms,
+ schedule=f"interval:{interval_ms}",
+ payload={"broker": self.broker, "trigger": kind_value},
+ )
+ )
+ return built
+
+ def stop_loop(self) -> None:
+ """Stop the scheduler if one was injected (idempotent)."""
+ if self._scheduler is not None:
+ self._scheduler.stop()
diff --git a/agent/src/live/runtime/scheduler.py b/agent/src/live/runtime/scheduler.py
new file mode 100644
index 000000000..6f5876ba2
--- /dev/null
+++ b/agent/src/live/runtime/scheduler.py
@@ -0,0 +1,328 @@
+"""Wall-clock scheduler for the live runtime (SPEC.md §7.5 #1).
+
+Follows nanobot's ``cron/service.py`` shape: an asyncio timer that sleeps until
+the earliest ``next_run_at`` across all jobs, fires the due jobs, advances each
+fired job's ``next_run_at``, then re-sleeps. The sleep is **capped** at a
+re-check interval (default 5 min) so a far-future job still wakes the loop
+periodically — defending against wall-clock jumps, a job added while asleep, and
+host suspend/resume drift.
+
+Time is epoch-milliseconds throughout. Every pure decision helper takes
+``now_ms`` explicitly (no wall-clock read inside) so scheduling logic is unit
+testable without sleeping or freezing the clock. Only the async run loop reads
+the real clock, via an injectable ``now_fn``.
+
+The scheduler holds the live job set in memory and invokes an async
+``on_fire(job)`` callback per due job; durability of the set is the
+:class:`src.live.runtime.jobstore.JobStore`'s job, kept orthogonal here.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+from dataclasses import dataclass, field
+from typing import Awaitable, Callable
+
+logger = logging.getLogger(__name__)
+
+#: Hard cap on how long the loop sleeps before re-checking, even when the next
+#: job is far in the future. Bounds clock-drift / suspend-resume blind spots.
+DEFAULT_MAX_RECHECK_MS = 5 * 60 * 1000
+
+#: Default cadence applied when a job's ``schedule`` is a bare/empty/unknown
+#: spec — the watch still fires on a sane interval rather than never.
+DEFAULT_INTERVAL_MS = 60 * 1000
+
+NowFn = Callable[[], int]
+FireCallback = Callable[["Job"], Awaitable[None]]
+
+
+def _now_ms() -> int:
+ """Return the current wall-clock time in epoch milliseconds.
+
+ Returns:
+ Milliseconds since the Unix epoch.
+ """
+ return int(time.time() * 1000)
+
+
+@dataclass
+class Job:
+ """A scheduled live-runtime job.
+
+ ``next_run_at`` is mutable by design: the scheduler advances it in place
+ after each fire (a frozen DTO would force a copy-and-reinsert per tick for
+ no benefit, and the job's identity is its ``id``, not its run time). All
+ other fields are treated as immutable after construction.
+
+ Attributes:
+ id: Stable unique identifier (also the key in the scheduler's set).
+ next_run_at: Epoch-ms timestamp of the next scheduled fire. Mutated by
+ the scheduler as the job recurs.
+ schedule: Schedule spec. ``"interval:<ms>"`` recurs every ``<ms>``;
+ ``"once"`` (or any unrecognized spec) fires a single time and is
+ then removed. Higher-level market-hours / event triggers (SPEC #4)
+ layer over this and are out of scope for this module.
+ payload: Opaque, JSON-serializable application data carried with the
+ job (e.g. mandate id / watch target). The scheduler never inspects
+ it; it is round-tripped by the job store.
+ """
+
+ id: str
+ next_run_at: int
+ schedule: str
+ payload: dict | None = field(default=None)
+
+ def interval_ms(self) -> int | None:
+ """Return the recurrence interval in ms, or ``None`` for one-shot jobs.
+
+ Returns:
+ The interval for an ``"interval:<ms>"`` schedule, ``None`` for a
+ ``"once"`` schedule, and :data:`DEFAULT_INTERVAL_MS` for any other
+ (non-empty) recognized-but-bare spec so a misconfigured job still
+ watches on a sane cadence rather than silently never recurring.
+ """
+ spec = (self.schedule or "").strip().lower()
+ if spec == "once":
+ return None
+ if spec.startswith("interval:"):
+ raw = spec.split(":", 1)[1].strip()
+ try:
+ ms = int(raw)
+ except ValueError:
+ return DEFAULT_INTERVAL_MS
+ return ms if ms > 0 else DEFAULT_INTERVAL_MS
+ return DEFAULT_INTERVAL_MS
+
+
+def earliest_next_run(jobs: list[Job]) -> int | None:
+ """Return the smallest ``next_run_at`` across ``jobs``.
+
+ Args:
+ jobs: The current job set.
+
+ Returns:
+ The earliest scheduled fire time in epoch ms, or ``None`` when there
+ are no jobs.
+ """
+ if not jobs:
+ return None
+ return min(job.next_run_at for job in jobs)
+
+
+def due_jobs(jobs: list[Job], now_ms: int) -> list[Job]:
+ """Return jobs whose ``next_run_at`` is at or before ``now_ms``.
+
+ Args:
+ jobs: The current job set.
+ now_ms: The reference time in epoch ms.
+
+ Returns:
+ The due jobs, in ascending ``next_run_at`` order so the earliest-due
+ fires first.
+ """
+ return sorted(
+ (job for job in jobs if job.next_run_at <= now_ms),
+ key=lambda job: job.next_run_at,
+ )
+
+
+def compute_sleep_ms(jobs: list[Job], now_ms: int, max_recheck_ms: int) -> int:
+ """Compute how long the loop should sleep before its next check.
+
+ Args:
+ jobs: The current job set.
+ now_ms: The reference time in epoch ms.
+ max_recheck_ms: Hard upper bound on the returned sleep so a far-future
+ job still wakes the loop periodically.
+
+ Returns:
+ A non-negative sleep duration in ms, clamped to ``[0, max_recheck_ms]``.
+ Returns ``max_recheck_ms`` when there are no jobs (idle poll). Returns
+ ``0`` when a job is already due so the loop fires it immediately.
+ """
+ earliest = earliest_next_run(jobs)
+ if earliest is None:
+ return max_recheck_ms
+ delta = earliest - now_ms
+ if delta <= 0:
+ return 0
+ return min(delta, max_recheck_ms)
+
+
+def advance_after_fire(job: Job, now_ms: int) -> bool:
+ """Advance a fired job's ``next_run_at``; report whether it should remain.
+
+ Recurring jobs are re-scheduled one interval past ``now_ms`` (not past the
+ old ``next_run_at``), so a job that fired late — because the host was
+ suspended or the loop was busy — does not immediately re-fire a backlog of
+ missed slots. One-shot jobs are not advanced.
+
+ Args:
+ job: The job that just fired. Mutated in place when recurring.
+ now_ms: The time the job fired, in epoch ms.
+
+ Returns:
+ ``True`` if the job recurs and should stay in the set, ``False`` if it
+ was one-shot and should be removed.
+ """
+ interval = job.interval_ms()
+ if interval is None:
+ return False
+ job.next_run_at = now_ms + interval
+ return True
+
+
+class Scheduler:
+ """Async wall-clock scheduler over an in-memory job set.
+
+ Lifecycle: :meth:`start` spawns the loop task on the running event loop;
+ :meth:`stop` cancels and awaits it. :meth:`add_job` / :meth:`remove_job`
+ mutate the live set and wake the loop so a newly-added near-term job is not
+ blocked behind a long sleep.
+
+ The scheduler does not persist anything itself — pair it with a
+ :class:`src.live.runtime.jobstore.JobStore` at the runner layer.
+
+ Attributes:
+ on_fire: Async callback invoked once per due job each tick.
+ """
+
+ def __init__(
+ self,
+ on_fire: FireCallback,
+ *,
+ max_recheck_ms: int = DEFAULT_MAX_RECHECK_MS,
+ now_fn: NowFn = _now_ms,
+ ) -> None:
+ """Initialize the scheduler.
+
+ Args:
+ on_fire: Async callback invoked with each due :class:`Job`. An
+ exception it raises is logged and swallowed so one bad job
+ cannot kill the loop or starve its peers.
+ max_recheck_ms: Cap on the loop's sleep (see
+ :func:`compute_sleep_ms`).
+ now_fn: Injectable wall-clock source returning epoch ms. Overridden
+ in tests to make the loop deterministic.
+ """
+ self._on_fire = on_fire
+ self._max_recheck_ms = max_recheck_ms
+ self._now_fn = now_fn
+ self._jobs: dict[str, Job] = {}
+ self._task: asyncio.Task | None = None
+ self._wakeup: asyncio.Event = asyncio.Event()
+ self._stopping = False
+
+ def jobs(self) -> list[Job]:
+ """Return a snapshot list of the current jobs.
+
+ Returns:
+ A new list of the live :class:`Job` objects (the list is a copy;
+ the jobs themselves are the live instances).
+ """
+ return list(self._jobs.values())
+
+ def add_job(self, job: Job) -> None:
+ """Add or replace a job and wake the loop.
+
+ Args:
+ job: The job to schedule. An existing job with the same ``id`` is
+ replaced (idempotent re-registration on restart).
+ """
+ self._jobs[job.id] = job
+ self._wakeup.set()
+
+ def remove_job(self, job_id: str) -> bool:
+ """Remove a job by id and wake the loop.
+
+ Args:
+ job_id: The id of the job to remove.
+
+ Returns:
+ ``True`` if a job was removed, ``False`` if no such job existed.
+ """
+ existed = self._jobs.pop(job_id, None) is not None
+ if existed:
+ self._wakeup.set()
+ return existed
+
+ def start(self) -> None:
+ """Start the scheduler loop on the running event loop.
+
+ Idempotent: calling :meth:`start` while already running is a no-op.
+
+ Raises:
+ RuntimeError: If there is no running event loop.
+ """
+ if self._task is not None and not self._task.done():
+ return
+ self._stopping = False
+ loop = asyncio.get_running_loop()
+ self._task = loop.create_task(self._run(), name="live-scheduler")
+
+ async def stop(self) -> None:
+ """Stop the scheduler loop and await its teardown.
+
+ Idempotent: calling :meth:`stop` when not running is a no-op. Safe to
+ call from within the same event loop the loop runs on.
+ """
+ self._stopping = True
+ self._wakeup.set()
+ task = self._task
+ self._task = None
+ if task is None:
+ return
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+
+ async def _run(self) -> None:
+ """Core loop: sleep until the earliest due job, fire it, repeat.
+
+ Sleeps are interruptible by :attr:`_wakeup`, so ``add_job`` /
+ ``remove_job`` / ``stop`` take effect immediately rather than after the
+ current sleep expires.
+ """
+ while not self._stopping:
+ now = self._now_fn()
+ sleep_ms = compute_sleep_ms(self.jobs(), now, self._max_recheck_ms)
+ if sleep_ms > 0:
+ await self._sleep_or_wake(sleep_ms)
+ if self._stopping:
+ break
+ continue
+ await self._fire_due(now)
+
+ async def _sleep_or_wake(self, sleep_ms: int) -> None:
+ """Sleep for ``sleep_ms`` or until woken by a set mutation / stop.
+
+ Args:
+ sleep_ms: Duration to sleep, in milliseconds.
+ """
+ self._wakeup.clear()
+ try:
+ await asyncio.wait_for(self._wakeup.wait(), timeout=sleep_ms / 1000.0)
+ except asyncio.TimeoutError:
+ pass
+
+ async def _fire_due(self, now_ms: int) -> None:
+ """Fire every job due at ``now_ms`` and reschedule/remove each.
+
+ Args:
+ now_ms: The reference time for due-ness, in epoch ms.
+ """
+ for job in due_jobs(self.jobs(), now_ms):
+ try:
+ await self._on_fire(job)
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.error("live scheduler on_fire failed for job %s", job.id, exc_info=True)
+ keep = advance_after_fire(job, now_ms)
+ if not keep:
+ self._jobs.pop(job.id, None)
diff --git a/agent/src/live/runtime/triggers.py b/agent/src/live/runtime/triggers.py
new file mode 100644
index 000000000..6aaa9e174
--- /dev/null
+++ b/agent/src/live/runtime/triggers.py
@@ -0,0 +1,347 @@
+"""Live-runtime triggers — when an autonomous tick is due (SPEC §7.5 component 4).
+
+This layers market-session, interval, and event triggers over R1's wall-clock
+scheduler. nanobot is time-only; trading additionally needs market-session
+awareness ("is the US equity market open right now?") and event-driven
+predicates (price crossings, fill notifications). This module owns that layer.
+
+Purity contract (CRITICAL): the testable core takes ``now_ms`` (epoch
+milliseconds, UTC) and any market/event state as *arguments* — it never reads
+the wall clock. This keeps :func:`due_now` and :func:`market_is_open`
+deterministic under test. The only clock read lives in the thin
+:func:`due_now_at` convenience wrapper, which delegates straight into the pure
+core.
+
+Frozen public contract (imported blind by R2):
+
+* :class:`Trigger` — the immutable trigger descriptor.
+* :func:`market_is_open` ``(market) -> bool`` — is the given market open *now*.
+* :func:`due_now` ``(trigger, now_ms) -> bool`` — is the trigger due at ``now_ms``.
+
+Imports are stdlib only (``datetime`` / ``zoneinfo``); no other parcel.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from datetime import date, datetime, time, timezone
+from enum import Enum
+from typing import Callable, Mapping
+from zoneinfo import ZoneInfo
+
+# --------------------------------------------------------------------------- #
+# Market specifications (module-level config — no hardcoding inline). #
+# --------------------------------------------------------------------------- #
+
+
+@dataclass(frozen=True)
+class _MarketSpec:
+ """Regular-trading-hours spec for one market.
+
+ Attributes:
+ tz: IANA timezone the session times are expressed in.
+ open_time: Local session open (inclusive).
+ close_time: Local session close (exclusive — a tick exactly at the
+ close bell counts as *closed*, matching exchange convention).
+ weekdays: Permitted weekdays as ``date.weekday()`` values (Mon==0).
+ Empty == every day (24/7 markets such as crypto).
+ always_open: Short-circuit for 24/7 markets; when ``True`` the time /
+ weekday / holiday checks are skipped entirely.
+ holidays: Full-day market closures (no half-days modelled). This is a
+ deliberately small, static set — see module docstring limitation.
+ """
+
+ tz: str
+ open_time: time
+ close_time: time
+ weekdays: frozenset[int] = frozenset()
+ always_open: bool = False
+ holidays: frozenset[date] = field(default_factory=frozenset)
+
+
+# US market holidays. LIMITATION: this is a hand-maintained static set (no
+# half-day early closes, no rolling computation). It covers the current and
+# next calendar year; extend as needed. A production deploy that needs decades
+# of coverage should swap in `pandas_market_calendars` behind this same spec.
+_US_EQUITY_HOLIDAYS: frozenset[date] = frozenset(
+ {
+ # 2026
+ date(2026, 1, 1), # New Year's Day
+ date(2026, 1, 19), # MLK Jr. Day
+ date(2026, 2, 16), # Washington's Birthday
+ date(2026, 4, 3), # Good Friday
+ date(2026, 5, 25), # Memorial Day
+ date(2026, 6, 19), # Juneteenth
+ date(2026, 7, 3), # Independence Day (observed)
+ date(2026, 9, 7), # Labor Day
+ date(2026, 11, 26), # Thanksgiving
+ date(2026, 12, 25), # Christmas
+ # 2027
+ date(2027, 1, 1), # New Year's Day
+ date(2027, 1, 18), # MLK Jr. Day
+ date(2027, 2, 15), # Washington's Birthday
+ date(2027, 3, 26), # Good Friday
+ date(2027, 5, 31), # Memorial Day
+ date(2027, 6, 18), # Juneteenth (observed)
+ date(2027, 7, 5), # Independence Day (observed)
+ date(2027, 9, 6), # Labor Day
+ date(2027, 11, 25), # Thanksgiving
+ date(2027, 12, 24), # Christmas (observed)
+ }
+)
+
+_WEEKDAYS_MON_FRI = frozenset({0, 1, 2, 3, 4})
+
+# Market registry. Keys match the AssetClass-style identifiers the runner uses
+# (e.g. "us_equity", "crypto"). Add markets here, never inline in functions.
+MARKET_SPECS: Mapping[str, _MarketSpec] = {
+ "us_equity": _MarketSpec(
+ tz="America/New_York",
+ open_time=time(9, 30),
+ close_time=time(16, 0),
+ weekdays=_WEEKDAYS_MON_FRI,
+ holidays=_US_EQUITY_HOLIDAYS,
+ ),
+ "crypto": _MarketSpec(
+ tz="UTC",
+ open_time=time(0, 0),
+ close_time=time(0, 0),
+ always_open=True,
+ ),
+}
+
+
+# --------------------------------------------------------------------------- #
+# Trigger model #
+# --------------------------------------------------------------------------- #
+
+
+class TriggerKind(str, Enum):
+ """The three trigger families layered over the wall-clock scheduler."""
+
+ INTERVAL = "interval"
+ MARKET = "market"
+ EVENT = "event"
+
+
+@dataclass(frozen=True)
+class Trigger:
+ """Immutable descriptor of when an autonomous tick should fire.
+
+ A single dataclass covers all three families; the active fields depend on
+ ``kind``. It is frozen so a mandate can pin it once and the runner can never
+ mutate it mid-flight.
+
+ Attributes:
+ kind: Which trigger family this is.
+ interval_ms: INTERVAL only — fire every this many milliseconds, counted
+ from ``epoch_ms``. Must be > 0 for an interval trigger.
+ epoch_ms: INTERVAL only — the phase anchor (epoch ms) the cadence is
+ measured from. Defaults to 0 (UNIX epoch) so the schedule is stable
+ across restarts.
+ market: MARKET only — a key into :data:`MARKET_SPECS` (e.g.
+ ``"us_equity"``). The trigger is "due" whenever that market is open.
+ predicate: EVENT only — a pure callable evaluated against an
+ event-state mapping supplied by the runner/event source. It returns
+ ``True`` when the awaited condition (price crossing, fill, etc.) is
+ met. The trigger carries the predicate; the runner carries the data.
+
+ Construct via the classmethod helpers (:meth:`interval`, :meth:`market`,
+ :meth:`event`) rather than the raw constructor where convenient.
+ """
+
+ kind: TriggerKind
+ interval_ms: int = 0
+ epoch_ms: int = 0
+ market: str | None = None
+ predicate: Callable[[Mapping[str, object]], bool] | None = None
+
+ @classmethod
+ def interval(cls, interval_ms: int, *, epoch_ms: int = 0) -> "Trigger":
+ """Build an interval trigger firing every ``interval_ms`` ms.
+
+ Args:
+ interval_ms: Cadence in milliseconds; must be strictly positive.
+ epoch_ms: Phase anchor in epoch ms (default 0 == UNIX epoch).
+
+ Returns:
+ A frozen INTERVAL :class:`Trigger`.
+
+ Raises:
+ ValueError: If ``interval_ms`` is not strictly positive.
+ """
+ if interval_ms <= 0:
+ raise ValueError("interval_ms must be > 0")
+ return cls(kind=TriggerKind.INTERVAL, interval_ms=interval_ms, epoch_ms=epoch_ms)
+
+ @classmethod
+ def market(cls, market: str) -> "Trigger":
+ """Build a market-session trigger for a known market key.
+
+ Args:
+ market: A key into :data:`MARKET_SPECS` (e.g. ``"us_equity"``).
+
+ Returns:
+ A frozen MARKET :class:`Trigger`.
+
+ Raises:
+ ValueError: If ``market`` is not a registered market.
+ """
+ if market not in MARKET_SPECS:
+ raise ValueError(f"unknown market: {market!r}")
+ return cls(kind=TriggerKind.MARKET, market=market)
+
+ @classmethod
+ def event(cls, predicate: Callable[[Mapping[str, object]], bool]) -> "Trigger":
+ """Build an event trigger driven by a pure predicate.
+
+ Args:
+ predicate: A callable taking the runner-supplied event-state mapping
+ and returning ``True`` when the awaited condition is met.
+
+ Returns:
+ A frozen EVENT :class:`Trigger`.
+ """
+ return cls(kind=TriggerKind.EVENT, predicate=predicate)
+
+
+# --------------------------------------------------------------------------- #
+# Pure core #
+# --------------------------------------------------------------------------- #
+
+
+def _ms_to_aware_dt(now_ms: int, tz: str) -> datetime:
+ """Convert epoch milliseconds to a tz-aware datetime in ``tz``.
+
+ Args:
+ now_ms: Epoch milliseconds, UTC.
+ tz: Target IANA timezone name.
+
+ Returns:
+ A timezone-aware :class:`datetime` localized to ``tz``.
+ """
+ utc_dt = datetime.fromtimestamp(now_ms / 1000.0, tz=timezone.utc)
+ return utc_dt.astimezone(ZoneInfo(tz))
+
+
+def market_is_open_at(market: str, now_ms: int) -> bool:
+ """Pure core: is ``market`` open at the instant ``now_ms``.
+
+ Deterministic — reads no clock. 24/7 markets (``always_open``) are always
+ open. Session markets are open only on permitted weekdays, outside the
+ holiday set, and within ``[open_time, close_time)`` local time.
+
+ Args:
+ market: A key into :data:`MARKET_SPECS`.
+ now_ms: Epoch milliseconds, UTC.
+
+ Returns:
+ ``True`` if the market is open at ``now_ms``, else ``False``.
+
+ Raises:
+ ValueError: If ``market`` is not a registered market (fail loud — an
+ unknown market must never be silently treated as open).
+ """
+ spec = MARKET_SPECS.get(market)
+ if spec is None:
+ raise ValueError(f"unknown market: {market!r}")
+ if spec.always_open:
+ return True
+
+ local_dt = _ms_to_aware_dt(now_ms, spec.tz)
+ if spec.weekdays and local_dt.weekday() not in spec.weekdays:
+ return False
+ if local_dt.date() in spec.holidays:
+ return False
+ return spec.open_time <= local_dt.time() < spec.close_time
+
+
+def due_now(trigger: Trigger, now_ms: int, *, event_state: Mapping[str, object] | None = None) -> bool:
+ """Pure core: is ``trigger`` due at ``now_ms``.
+
+ Deterministic — reads no clock; all inputs are arguments.
+
+ * INTERVAL: due when ``(now_ms - epoch_ms)`` lands on an exact multiple of
+ ``interval_ms``. The scheduler quantizes ticks, so callers test exact
+ boundaries; this is the alignment the runner's quantized clock produces.
+ * MARKET: due whenever the trigger's market is open at ``now_ms``.
+ * EVENT: due when the trigger's predicate returns truthy against
+ ``event_state`` (an empty mapping when the runner supplies none).
+
+ Args:
+ trigger: The trigger to evaluate.
+ now_ms: Epoch milliseconds, UTC.
+ event_state: Event-source state for EVENT triggers; ignored otherwise.
+
+ Returns:
+ ``True`` if the trigger is due, else ``False``.
+
+ Raises:
+ ValueError: If the trigger is malformed for its kind (e.g. an EVENT
+ trigger with no predicate, or a MARKET trigger with no market).
+ """
+ if trigger.kind is TriggerKind.INTERVAL:
+ if trigger.interval_ms <= 0:
+ raise ValueError("interval trigger requires interval_ms > 0")
+ elapsed = now_ms - trigger.epoch_ms
+ return elapsed >= 0 and elapsed % trigger.interval_ms == 0
+
+ if trigger.kind is TriggerKind.MARKET:
+ if trigger.market is None:
+ raise ValueError("market trigger requires a market")
+ return market_is_open_at(trigger.market, now_ms)
+
+ if trigger.kind is TriggerKind.EVENT:
+ if trigger.predicate is None:
+ raise ValueError("event trigger requires a predicate")
+ return bool(trigger.predicate(event_state or {}))
+
+ raise ValueError(f"unknown trigger kind: {trigger.kind!r}")
+
+
+# --------------------------------------------------------------------------- #
+# Clock-reading convenience wrappers (delegate to the pure core) #
+# --------------------------------------------------------------------------- #
+
+
+def _now_ms() -> int:
+ """Current wall-clock time in epoch milliseconds, UTC.
+
+ Returns:
+ Epoch milliseconds for the current instant.
+ """
+ return int(datetime.now(tz=timezone.utc).timestamp() * 1000)
+
+
+def market_is_open(market: str) -> bool:
+ """Is ``market`` open right now (wall clock).
+
+ Thin convenience wrapper around the pure :func:`market_is_open_at`; the
+ only clock read happens here and is delegated immediately.
+
+ Args:
+ market: A key into :data:`MARKET_SPECS`.
+
+ Returns:
+ ``True`` if the market is open now, else ``False``.
+
+ Raises:
+ ValueError: If ``market`` is not a registered market.
+ """
+ return market_is_open_at(market, _now_ms())
+
+
+def due_now_at(trigger: Trigger, *, event_state: Mapping[str, object] | None = None) -> bool:
+ """Is ``trigger`` due right now (wall clock).
+
+ Thin convenience wrapper around the pure :func:`due_now`; the only clock
+ read happens here and is delegated immediately.
+
+ Args:
+ trigger: The trigger to evaluate.
+ event_state: Event-source state for EVENT triggers.
+
+ Returns:
+ ``True`` if the trigger is due now, else ``False``.
+ """
+ return due_now(trigger, _now_ms(), event_state=event_state)
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index cf8777091..880d85eb3 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -28,6 +28,7 @@ from src.swarm.models import (
)
from src.tools import build_swarm_registry
from src.tools.mcp import MCPRemoteTool
+from src.tools.redaction import is_sensitive_arg, redact_payload
logger = logging.getLogger(__name__)
@@ -50,17 +51,6 @@ def _heartbeat_interval_s() -> float:
_HEARTBEAT_INTERVAL_S = _heartbeat_interval_s()
_MAX_TOKEN_ESTIMATE = 60_000
-_SENSITIVE_TOOL_ARGUMENT_KEYS = {
- "api_key",
- "authorization",
- "content",
- "env",
- "headers",
- "passphrase",
- "password",
- "secret",
- "token",
-}
def _emit(
@@ -653,10 +643,10 @@ def _preview_tool_arguments(arguments: dict) -> dict[str, str]:
for key, value in arguments.items():
if key == "run_dir":
continue
- if _is_sensitive_tool_argument(key):
+ if is_sensitive_arg(key):
preview[key] = "[redacted]"
continue
- preview[key] = _truncate_preview(_redact_preview_payload(value))
+ preview[key] = _truncate_preview(redact_payload(value))
return preview
@@ -666,19 +656,7 @@ def _preview_tool_result(result: str) -> str:
parsed = json.loads(result)
except (TypeError, ValueError):
return _truncate_preview(result)
- return _truncate_preview(_redact_preview_payload(parsed))
-
-
-def _redact_preview_payload(value: Any) -> Any:
- """Recursively redact sensitive keys before event preview stringification."""
- if isinstance(value, dict):
- return {
- key: "[redacted]" if _is_sensitive_tool_argument(str(key)) else _redact_preview_payload(item)
- for key, item in value.items()
- }
- if isinstance(value, list):
- return [_redact_preview_payload(item) for item in value]
- return value
+ return _truncate_preview(redact_payload(parsed))
def _truncate_preview(value: Any, *, limit: int = 200) -> str:
@@ -690,15 +668,6 @@ def _truncate_preview(value: Any, *, limit: int = 200) -> str:
return text if len(text) <= limit else text[:limit] + "..."
-def _is_sensitive_tool_argument(key: str) -> bool:
- """Return whether a tool argument name should be redacted in events."""
- normalized = key.strip().lower()
- return normalized in _SENSITIVE_TOOL_ARGUMENT_KEYS or any(
- marker in normalized
- for marker in ("api_key", "authorization", "password", "secret", "token")
- )
-
-
# Tools that do not themselves fetch/compute market data. An agent whose
# entire toolset is a subset of these is a synthesis/editor role (e.g. the
# research editor in equity_research_team) and may legitimately produce a
diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.py
index 5d5d8a8ff..6d6acae4f 100644
--- a/agent/src/tools/__init__.py
+++ b/agent/src/tools/__init__.py
@@ -71,6 +71,7 @@ def build_registry(
session_id: str | None = None,
event_callback: Callable[[str, dict], None] | None = None,
warn_callback: Callable[[str], None] | None = None,
+ interactive: bool | None = None,
_mcp_server_tool_name_segments: Mapping[str, str] | None = None,
) -> ToolRegistry:
"""Build the tool registry via auto-discovery, optionally enriched with MCP tools.
@@ -101,6 +102,12 @@ def build_registry(
messages. When provided, server-name collision warnings are passed
to this callback in addition to the standard logger so CLI and
SessionService can surface them to operators.
+ interactive: Whether the session is an interactive TTY. Governs whether
+ a live-broker channel with no cached OAuth token is registered: a
+ non-interactive run (``serve`` / swarm) skips an unauthorized live
+ channel rather than blocking on a browser that cannot open
+ (SPEC Transport §4). ``None`` (default) auto-detects via
+ ``sys.stdin.isatty()``.
Returns:
ToolRegistry containing all available local tools followed by any
@@ -155,13 +162,56 @@ def build_registry(
for server_name in agent_config.mcp_servers
}
+ if interactive is None:
+ import sys
+
+ interactive = sys.stdin.isatty()
+
for server_name, server_config in agent_config.mcp_servers.items():
try:
+ # Live brokers (e.g. Robinhood) gate their order-placing tools
+ # behind the mandate + kill switch; reads stay plain (read-only).
+ # Detection is by config key OR URL host, so a live-broker URL
+ # under an aliased key cannot bypass the gate.
+ from src.live.registry import (
+ is_live_broker,
+ should_register_live_channel,
+ wrap_live_broker_tools,
+ )
+
+ server_url = server_config.url
+ live = is_live_broker(server_name, server_url)
+
+ # Headless / no-token: skip an unauthorized live channel rather
+ # than block on a browser that can't open (SPEC Transport §4).
+ if live:
+ cache_dir = (
+ server_config.auth.cache_dir
+ if server_config.auth is not None
+ else None
+ )
+ if not should_register_live_channel(
+ interactive=interactive, url=server_url, cache_dir=cache_dir
+ ):
+ skip_msg = (
+ f"Robinhood live channel configured but not authorized — "
+ f"run `vibe-trading live authorize {server_name}` on a "
+ f"desktop session"
+ )
+ logger.warning(skip_msg)
+ if warn_callback is not None:
+ warn_callback(skip_msg)
+ continue
+
wrappers = build_mcp_tool_wrappers(
server_name,
server_config,
local_server_name=local_server_names[server_name],
)
+ if live:
+ wrappers = wrap_live_broker_tools(
+ server_name, wrappers, url=server_url
+ )
for tool in wrappers:
registry.register(tool)
logger.info(
diff --git a/agent/src/tools/mcp.py b/agent/src/tools/mcp.py
index 616bfbfde..33d84682d 100644
--- a/agent/src/tools/mcp.py
+++ b/agent/src/tools/mcp.py
@@ -14,11 +14,13 @@ from dataclasses import dataclass
from typing import Any, Awaitable, Callable, Coroutine, Iterable, Protocol, TypeVar
from fastmcp.client import Client
+from fastmcp.client.auth import OAuth
from fastmcp.client.client import CallToolResult
from fastmcp.client.transports.http import StreamableHttpTransport
from fastmcp.client.transports.sse import SSETransport
from fastmcp.client.transports.stdio import StdioTransport
from fastmcp.exceptions import McpError, ToolError
+from key_value.aio.stores.filetree import FileTreeStore
from mcp import types as mcp_types
from src.agent.tools import BaseTool
@@ -82,13 +84,22 @@ ClientFactory = Callable[[], AsyncMCPClient]
@dataclass(frozen=True)
class MCPRemoteToolSpec:
- """Resolved metadata for one remote MCP tool."""
+ """Resolved metadata for one remote MCP tool.
+
+ Attributes:
+ annotations: Server-asserted MCP tool annotations (``readOnlyHint`` /
+ ``destructiveHint`` / etc.), or ``None`` when the server omits them.
+ These are advisory hints from a possibly-untrusted server and must
+ never be the sole basis for relaxing safety — the live classification
+ layer (P1) treats them as one tier behind the curated map.
+ """
server_name: str
remote_name: str
local_name: str
description: str
parameters: dict[str, Any]
+ annotations: mcp_types.ToolAnnotations | None = None
def build_mcp_tool_wrappers(
@@ -243,6 +254,31 @@ def normalize_mcp_tool_schema(schema: dict[str, Any] | None) -> dict[str, Any]:
return normalized
+def _build_token_store(cache_dir: str) -> FileTreeStore:
+ """Build a persistent OAuth token store rooted at ``cache_dir``.
+
+ The directory is created (with parents) and locked down to ``0700`` so only
+ the owning user can read the cached refresh tokens. ``FileTreeStore`` is a
+ pure-stdlib ``AsyncKeyValue`` backend (no ``diskcache`` dependency) and uses
+ atomic same-directory temp-file renames for write safety. The OAuth provider
+ persists refreshed tokens back through this store, giving silent refresh
+ across CLI sessions.
+
+ Args:
+ cache_dir: Token cache directory. A leading ``~`` is expanded.
+
+ Returns:
+ A ``FileTreeStore`` rooted at the resolved cache directory.
+ """
+ from pathlib import Path
+
+ path = Path(cache_dir).expanduser()
+ path.mkdir(parents=True, exist_ok=True)
+ # 0700: owner-only. Tokens are secrets; no group/other access.
+ os.chmod(path, 0o700)
+ return FileTreeStore(data_directory=path)
+
+
class MCPServerAdapter:
"""Synchronous wrapper around the async FastMCP client."""
@@ -297,6 +333,7 @@ class MCPServerAdapter:
local_name=local_name,
description=(tool.description or f"Remote MCP tool {tool.name} from {self.server_name}."),
parameters=normalize_mcp_tool_schema(getattr(tool, "inputSchema", None)),
+ annotations=getattr(tool, "annotations", None),
)
)
@@ -367,9 +404,25 @@ class MCPServerAdapter:
headers=dict(self.server_config.headers) or None,
)
else:
+ auth = None
+ if self.server_config.auth is not None:
+ oauth_config = self.server_config.auth
+ # `mcp_url` is intentionally omitted — StreamableHttpTransport
+ # calls `auth._bind(self.url)` so the URL fills in from the
+ # transport. Token cache is persistent (FileTreeStore), so the
+ # channel stays authorized across CLI invocations and refresh is
+ # handled inside the MCP lib's OAuthClientProvider.
+ auth = OAuth(
+ scopes=list(oauth_config.scopes) or None,
+ client_name=oauth_config.client_name,
+ token_storage=_build_token_store(oauth_config.cache_dir),
+ callback_port=oauth_config.callback_port,
+ client_id=oauth_config.client_id,
+ )
transport = StreamableHttpTransport(
url=self.server_config.url,
headers=dict(self.server_config.headers) or None,
+ auth=auth,
)
# Use a minimum of 30 s for init_timeout so cold-start servers (pip
diff --git a/agent/src/tools/propose_mandate_tool.py b/agent/src/tools/propose_mandate_tool.py
new file mode 100644
index 000000000..f21574caa
--- /dev/null
+++ b/agent/src/tools/propose_mandate_tool.py
@@ -0,0 +1,245 @@
+"""``propose_mandate_profiles`` — the read-only PROPOSE half of consent.
+
+The agent calls this tool when the user expresses a live-trading intent (or when
+a mandate breach needs widening options). It synthesizes 2-4 numbered candidate
+mandate profiles, **every one clamped to the account ceilings** so even the most
+aggressive option can never request more than the broker allows, persists the
+proposal so the surface commit endpoint can re-validate it, and returns the
+``mandate.proposal`` payload (Consent §1 shape).
+
+It is read-only by design: it writes a *proposal* (a menu of clamped options),
+never a mandate. Persisting a proposal grants zero trading authority — only the
+surface-side :func:`src.live.mandate.commit.commit_mandate` (unreachable from the
+agent loop) writes a mandate, and only after re-validating the selected profile
+still fits the ceilings the user saw. This is the structural "agent proposes,
+user disposes" guarantee (``docs/live-trading/SPEC.md`` §3, Consent §1).
+"""
+
+from __future__ import annotations
+
+import json
+import uuid
+from typing import Any
+
+from src.agent.tools import BaseTool
+from src.live.mandate.commit import _normalize_limits, save_proposal
+
+#: Ordered profile templates synthesized when the caller gives no explicit
+#: profiles. Each is a fraction of the funded ceiling so they always clamp down.
+_PROFILE_TEMPLATES: tuple[dict[str, Any], ...] = (
+ {"ordinal": 1, "label": "稳健", "order_fraction": 0.05, "daily_trade_cap": 2,
+ "notes": "Smallest clips, fewest trades — capital-preservation tilt."},
+ {"ordinal": 2, "label": "均衡", "order_fraction": 0.15, "daily_trade_cap": 5,
+ "notes": "Moderate sizing, cash-only."},
+ {"ordinal": 3, "label": "激进", "order_fraction": 0.30, "daily_trade_cap": 10,
+ "notes": "Largest clips this account allows — still cash-only."},
+)
+
+
+class ProposeMandateProfilesTool(BaseTool):
+ """Synthesize clamped bounded-autonomy mandate profiles for the user to pick.
+
+ Read-only: returns a ``mandate.proposal`` payload and persists it for later
+ commit. Never writes a mandate.
+ """
+
+ name = "propose_mandate_profiles"
+ description = (
+ "Propose 2-4 numbered bounded-autonomy live-trading mandate profiles for "
+ "the user to pick from, each clamped to the account's hard ceilings. "
+ "READ-ONLY: it returns options and does NOT activate any mandate — the "
+ "user must explicitly commit one through the surface. Call this when the "
+ "user expresses a live-trading intent, or (with reauth_for set) when an "
+ "order breached the active mandate and the user may want to widen it."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "broker": {
+ "type": "string",
+ "description": "Broker key, e.g. 'robinhood'.",
+ },
+ "intent": {
+ "type": "string",
+ "description": "Normalized user intent, e.g. 'aggressive tech, ~$5000'.",
+ },
+ "ceilings": {
+ "type": "object",
+ "description": (
+ "Account hard-ceiling snapshot the profiles are clamped to "
+ "(e.g. account_funding_usd, max_total_exposure_usd, leverage, "
+ "instruments). Every proposed profile is bounded by these; the "
+ "tool can only clamp DOWN, never up."
+ ),
+ },
+ "session_id": {
+ "type": "string",
+ "description": "Originating session id (echoed into the payload).",
+ },
+ "reauth_for": {
+ "type": "object",
+ "description": (
+ "Optional breach seed: when an order breached a quantitative "
+ "limit, pass {'breach_id', 'limit', 'attempted_value'} to bias "
+ "the proposed widening options. Still clamped to ceilings."
+ ),
+ },
+ "flatten_on_halt": {
+ "type": "boolean",
+ "description": (
+ "Per-mandate opt-in: when true, a kill-switch trip flattens "
+ "open positions (submits closing orders) in addition to "
+ "cancelling resting orders. Defaults to false (cancel-only — "
+ "the safe default). Stamped onto every proposed profile so the "
+ "user's choice is carried through to commit (SPEC §7.5 #6)."
+ ),
+ },
+ },
+ "required": ["broker", "ceilings"],
+ }
+ repeatable = True
+ is_readonly = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Synthesize, persist, and return a ``mandate.proposal`` payload.
+
+ Args:
+ **kwargs: ``broker`` and ``ceilings`` required; optional ``intent``,
+ ``session_id``, ``reauth_for``, ``flatten_on_halt``.
+
+ Returns:
+ JSON string of the ``mandate.proposal`` payload, or an error
+ envelope.
+ """
+ broker = str(kwargs.get("broker") or "").strip().lower()
+ if not broker:
+ return json.dumps({"status": "error", "error": "broker is required"}, ensure_ascii=False)
+ ceilings = kwargs.get("ceilings")
+ if not isinstance(ceilings, dict):
+ return json.dumps(
+ {"status": "error", "error": "ceilings (object) is required"},
+ ensure_ascii=False,
+ )
+
+ intent = str(kwargs.get("intent") or "").strip()
+ session_id = kwargs.get("session_id")
+ reauth_for = kwargs.get("reauth_for") if isinstance(kwargs.get("reauth_for"), dict) else None
+ flatten_on_halt = bool(kwargs.get("flatten_on_halt", False))
+
+ try:
+ profiles = self._synthesize_profiles(ceilings, reauth_for, flatten_on_halt)
+ except (TypeError, ValueError) as exc:
+ return json.dumps(
+ {"status": "error", "error": f"invalid ceilings: {exc}"},
+ ensure_ascii=False,
+ )
+
+ proposal_id = f"mp_{uuid.uuid4().hex}"
+ payload: dict[str, Any] = {
+ "type": "mandate.proposal",
+ "proposal_id": proposal_id,
+ "session_id": session_id,
+ "intent_normalized": intent,
+ "account": {
+ "broker": broker,
+ "type": self._account_type(ceilings),
+ "funded_by": "user",
+ },
+ "ceilings_ref": str(ceilings.get("ceilings_ref") or f"caps_{uuid.uuid4().hex}"),
+ # The full snapshot is stored on the record so commit re-validates
+ # the resolved profile against exactly what the user saw.
+ "ceilings": dict(ceilings),
+ "profiles": profiles,
+ "funding_note": (
+ "Funding is set by YOU inside the broker's dedicated trading "
+ "account; the agent cannot move money."
+ ),
+ "halt_note": "随时一句『停』= kill switch, halts everything instantly.",
+ }
+ if reauth_for is not None:
+ payload["reauth_for"] = reauth_for
+
+ try:
+ save_proposal(payload)
+ except ValueError as exc:
+ return json.dumps(
+ {"status": "error", "error": f"could not persist proposal: {exc}"},
+ ensure_ascii=False,
+ )
+
+ return json.dumps(payload, ensure_ascii=False)
+
+ def _synthesize_profiles(
+ self,
+ ceilings: dict[str, Any],
+ reauth_for: dict[str, Any] | None,
+ flatten_on_halt: bool = False,
+ ) -> list[dict[str, Any]]:
+ """Build 2-4 numbered profiles, every limit clamped to ``ceilings``.
+
+ Args:
+ ceilings: The account hard-ceiling snapshot.
+ reauth_for: Optional breach seed biasing the widening options.
+ flatten_on_halt: Per-mandate flatten opt-in stamped onto every
+ profile (default ``False`` == cancel-only).
+
+ Returns:
+ A list of clamped profile dicts (Consent §1 shape).
+ """
+ # Read the four clamped limits through the SAME canonical-alias map the
+ # commit-time ceiling re-check uses, so propose and commit agree on which
+ # ceiling bounds which field regardless of the snapshot's spelling
+ # (max_order_usd vs max_order_notional_usd, daily_trade_cap vs
+ # max_trades_per_day, instruments vs allowed_instruments). Without this,
+ # propose could clamp against one spelling while commit re-checked a
+ # different one — the audit H9 mismatch.
+ canon = _normalize_limits(ceilings)
+ funding = float(ceilings.get("account_funding_usd", ceilings.get("max_total_exposure_usd", 0.0)) or 0.0)
+ ceil_order = canon.get("max_order_notional_usd")
+ ceil_order = float(ceil_order) if ceil_order is not None else None
+ ceil_exposure = ceilings.get("max_total_exposure_usd")
+ ceil_exposure = float(ceil_exposure) if ceil_exposure is not None else funding
+ ceil_daily = canon.get("max_trades_per_day")
+ ceil_daily = int(ceil_daily) if ceil_daily is not None else None
+ instruments = list(canon.get("allowed_instruments") or ["equity"])
+ universe = ceilings.get("universe") or ["AAPL", "MSFT", "NVDA", "GOOGL"]
+ # Leverage is always clamped to the ceiling; default cash-only.
+ leverage = canon.get("leverage", "none")
+
+ # A reauth seed nudges the top option toward the breached level, still
+ # clamped: we never propose past the ceiling.
+ bias = 1.0
+ if reauth_for is not None:
+ attempted = reauth_for.get("attempted_value")
+ if isinstance(attempted, (int, float)) and ceil_order:
+ bias = min(1.0, max(bias, float(attempted) / ceil_order))
+
+ profiles: list[dict[str, Any]] = []
+ for tpl in _PROFILE_TEMPLATES:
+ raw_order = funding * tpl["order_fraction"] * bias
+ max_order = round(raw_order, 2)
+ if ceil_order is not None:
+ max_order = min(max_order, ceil_order)
+ daily = tpl["daily_trade_cap"]
+ if ceil_daily is not None:
+ daily = min(daily, ceil_daily)
+ profile = {
+ "ordinal": tpl["ordinal"],
+ "label": tpl["label"],
+ "universe": universe,
+ "max_order_usd": max_order,
+ "max_total_exposure_usd": ceil_exposure,
+ "daily_trade_cap": daily,
+ "leverage": leverage,
+ "instruments": instruments,
+ "flatten_on_halt": flatten_on_halt,
+ "notes": tpl["notes"],
+ }
+ profiles.append(profile)
+ return profiles
+
+ @staticmethod
+ def _account_type(ceilings: dict[str, Any]) -> str:
+ """Return the account type label ('cash' unless ceilings allow leverage)."""
+ leverage = ceilings.get("leverage", "none")
+ return "cash" if leverage in ("none", None, 1, 1.0) else "margin"
diff --git a/agent/src/tools/redaction.py b/agent/src/tools/redaction.py
index 24973133c..87a359261 100644
--- a/agent/src/tools/redaction.py
+++ b/agent/src/tools/redaction.py
@@ -1,10 +1,22 @@
-"""Redact internal absolute paths from user-facing strings (CWE-209/497, P10).
+"""Shared redaction helpers (CWE-209/497, P10).
-Redacts ONLY known-internal root prefixes (anchored to the running env) and
-keeps the relative tail — caller-supplied/external absolute paths stay intact
-for diagnosability; only our own topology is hidden. Idempotent: each root is
-replaced by the literal '<redacted>' sentinel, which is not itself a root, so
-a second pass is a no-op. No regex (zero ReDoS surface).
+Two independent concerns live here:
+
+1. ``redact_internal_paths`` — replaces internal root prefixes with a
+ ``'<redacted>'`` sentinel, keeping the relative tail. Caller-supplied or
+ external absolute paths stay intact for diagnosability; only our own
+ topology is hidden. Idempotent and regex-free (zero ReDoS surface).
+2. ``redact_payload`` / ``is_sensitive_arg`` — recursively scrub sensitive
+ keys from structured tool-call payloads before they reach any event
+ stream, trace, or live audit ledger. Two key classes are scrubbed:
+ credential keys (OAuth tokens, ``api_key``, ``authorization``, secrets)
+ matched by exact name or ``*token*``-style marker, and a curated set of
+ exact account/PII field names (``account_number``, ``ssn``,
+ ``routing_number`` …). The opaque ``account_ref`` provenance field is
+ deliberately preserved (SPEC §5 accountability chain).
+ Promoted from the swarm worker's private copies (#142) so
+ the swarm worker, the live-action audit, the main agent loop, and the
+ paper-trading surfaces all consume one shared implementation.
"""
from __future__ import annotations
@@ -13,9 +25,80 @@ import sys
import sysconfig
from functools import cache
from pathlib import Path
+from typing import Any
_SENTINEL = "<redacted>"
+_REDACTED = "[redacted]"
+
+#: Curated EXACT-MATCH PII / account-identifier field names (SPEC Consent §5 /
+#: §8 #2). These are scrubbed in addition to the credential-marker keys below.
+#: Matching is exact (normalized) on purpose: a broad ``"account"`` substring
+#: marker would over-redact benign codebase fields (account balances, account
+#: config, etc.), and — critically — would clobber the audit record's own
+#: ``account_ref`` provenance field, which is an OPAQUE broker reference that
+#: SPEC §5 intentionally keeps as the mandate→consent accountability chain.
+#: ``account_ref`` is deliberately absent from this set so it survives.
+_PII_EXACT_KEYS = {
+ # Generic brokerage account identifiers.
+ "account_number",
+ "account_id",
+ "account_no",
+ "account_num",
+ "brokerage_account_number",
+ "brokerage_account_id",
+ # Robinhood-style account fields (raw broker request/response payloads).
+ "account_url",
+ "rhs_account_number",
+ # Government / tax identifiers.
+ "ssn",
+ "social_security_number",
+ "tax_id",
+ "taxpayer_id",
+ "tin",
+ # Bank routing / account.
+ "routing_number",
+ "bank_account_number",
+}
+
+_SENSITIVE_ARG_KEYS = {
+ "api_key",
+ "authorization",
+ "content",
+ "env",
+ "headers",
+ "passphrase",
+ "password",
+ "secret",
+ "token",
+} | _PII_EXACT_KEYS
+
+_SENSITIVE_ARG_MARKERS = ("api_key", "authorization", "password", "secret", "token")
+
+
+def _fold_key(name: str) -> str:
+ """Fold a key to its alphanumeric core (lower-case, separators stripped).
+
+ Collapses snake_case, camelCase, kebab-case and spaced variants to one form
+ so ``account_number``, ``accountNumber``, ``account-number`` and
+ ``Account Number`` all match the same curated entry — without resorting to a
+ broad ``"account"`` substring that would over-redact benign fields. Regex-free
+ (zero ReDoS surface), consistent with the rest of this module.
+
+ Args:
+ name: Raw key name.
+
+ Returns:
+ The lower-cased, alphanumeric-only fold of ``name``.
+ """
+ return "".join(ch for ch in name.lower() if ch.isalnum())
+
+
+#: Separator-folded forms of the sensitive keys + markers, matched against a
+#: folded candidate key so camelCase/kebab variants are caught too.
+_SENSITIVE_ARG_KEYS_FOLDED = frozenset(_fold_key(k) for k in _SENSITIVE_ARG_KEYS)
+_SENSITIVE_ARG_MARKERS_FOLDED = tuple(_fold_key(m) for m in _SENSITIVE_ARG_MARKERS)
+
@cache
def _internal_roots() -> list[str]:
@@ -54,3 +137,73 @@ def redact_internal_paths(text: object) -> str:
if root in s:
s = s.replace(root, _SENTINEL)
return s
+
+
+def is_sensitive_arg(name: str) -> bool:
+ """Return whether a tool-argument / payload key name should be redacted.
+
+ A key is sensitive when its normalized (stripped, lower-cased) form either
+
+ * is an exact match for a known credential key (``api_key`` …) or a curated
+ account/PII field (``account_number``, ``ssn``, ``routing_number`` … see
+ :data:`_PII_EXACT_KEYS`), or
+ * contains a credential marker substring (so ``api_token``,
+ ``access_token``, ``x-authorization`` all redact).
+
+ Account/PII matching is intentionally exact-only — never a broad
+ ``"account"`` substring — so benign fields are not over-redacted and the
+ audit record's opaque ``account_ref`` provenance field (the
+ mandate→consent accountability chain, SPEC §5) is preserved.
+
+ Args:
+ name: Argument or payload key name to classify.
+
+ Returns:
+ ``True`` when the key holds a credential, account number, or other PII
+ value and its value must be replaced with ``'[redacted]'`` before
+ surfacing.
+ """
+ normalized = name.strip().lower()
+ if normalized in _SENSITIVE_ARG_KEYS or any(
+ marker in normalized for marker in _SENSITIVE_ARG_MARKERS
+ ):
+ return True
+ # Separator-folded match catches camelCase / kebab / spaced variants
+ # (accountNumber, account-number, socialSecurityNumber) that the exact
+ # snake_case set would miss, without a broad substring over-redaction.
+ folded = _fold_key(name)
+ return folded in _SENSITIVE_ARG_KEYS_FOLDED or any(
+ marker in folded for marker in _SENSITIVE_ARG_MARKERS_FOLDED
+ )
+
+
+def redact_payload(obj: Any) -> Any:
+ """Recursively redact sensitive keys in a structured payload.
+
+ Walks dicts and lists; any dict value whose key :func:`is_sensitive_arg`
+ is replaced with the ``'[redacted]'`` sentinel. Non-container values pass
+ through unchanged. Used before event-preview stringification and before
+ writing broker request/response payloads to the live audit ledger.
+
+ Scrubs two key classes (see :func:`is_sensitive_arg`): credential keys
+ (OAuth tokens, ``api_key``, ``authorization``, ``password``/``secret``,
+ and any ``*token*``-style markers) and a curated set of exact account/PII
+ field names (``account_number``, ``ssn``, ``routing_number`` …). It does
+ NOT redact the audit record's opaque ``account_ref`` provenance field,
+ which is kept for the mandate→consent accountability chain (SPEC §5).
+
+ Args:
+ obj: Arbitrary payload (dict / list / scalar) to scrub.
+
+ Returns:
+ A new structure of the same shape with sensitive values replaced. The
+ input is never mutated.
+ """
+ if isinstance(obj, dict):
+ return {
+ key: _REDACTED if is_sensitive_arg(str(key)) else redact_payload(item)
+ for key, item in obj.items()
+ }
+ if isinstance(obj, list):
+ return [redact_payload(item) for item in obj]
+ return obj
diff --git a/agent/tests/test_api_live_runtime.py b/agent/tests/test_api_live_runtime.py
new file mode 100644
index 000000000..5595b9a2a
--- /dev/null
+++ b/agent/tests/test_api_live_runtime.py
@@ -0,0 +1,434 @@
+"""API regressions for the live-trading runtime wiring (R6: C1 + C2 + runner control).
+
+Covers the open-file integration seam the orchestrator and parcel R6 own:
+- C1: a ``propose_mandate_profiles`` tool_result is translated into a top-level
+ ``mandate.proposal`` SSE frame WITHOUT touching the protected ``src/agent/loop.py``.
+- C2: ``GET /live/status`` surfaces the dormant-by-default channel (auth, mandate,
+ runner liveness, halt) and ``POST /live/authorize`` is a discover-only on-ramp.
+- Runner control: ``POST /live/runner/start|stop`` are privileged surface actions
+ gated on a committed, unexpired mandate and a clear kill switch.
+
+All tests run against stubbed runner/liveness state — no real agent or broker.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+from fastapi.testclient import TestClient
+
+import api_server
+
+
+def _client(tmp_path: Path, monkeypatch) -> TestClient:
+ # Redirect the runtime root (``~/.vibe-trading``) at the home boundary so the
+ # live tree, HALT sentinel, mandate store, and proposal store all resolve
+ # under tmp_path. get_runtime_root() == Path.home() / ".vibe-trading".
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)
+ monkeypatch.setattr(api_server, "_runner_tasks", {}, raising=False)
+ monkeypatch.setattr(api_server, "_runner_factory", None, raising=False)
+ return TestClient(api_server.app, client=("127.0.0.1", 50000))
+
+
+def _valid_mandate_state(broker: str = "robinhood") -> api_server.ActiveMandateState:
+ """Build a committed, unexpired active-mandate snapshot for stubbing."""
+ return api_server.ActiveMandateState(
+ broker=broker,
+ account_ref="acct_test",
+ created_at="2026-05-29T00:00:00+00:00",
+ expires_at="2099-01-01T00:00:00+00:00",
+ expires_in_seconds=10_000_000,
+ expired=False,
+ limits=api_server.MandateLimits(
+ max_order_notional_usd=750.0,
+ max_total_exposure_usd=5000.0,
+ max_leverage=1.0,
+ max_trades_per_day=5,
+ allowed_instruments=["equity"],
+ account_funding_usd=5000.0,
+ ),
+ )
+
+
+# --------------------------------------------------------------------------- #
+# C2 — GET /live/status
+# --------------------------------------------------------------------------- #
+
+
+def test_live_status_dormant_by_default(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+
+ response = client.get("/live/status")
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["global_halted"] is False
+ brokers = {b["auth"]["broker"]: b for b in body["brokers"]}
+ assert "robinhood" in brokers
+ rh = brokers["robinhood"]
+ # Channel is OFF until OAuth + mandate: no token, no mandate, runner dead.
+ assert rh["auth"]["oauth_token_present"] is False
+ assert rh["auth"]["is_live_broker"] is True
+ assert rh["mandate"] is None
+ assert rh["runner"]["alive"] is False
+ assert rh["halted"] is False
+
+
+def test_live_status_single_broker_filter(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+
+ response = client.get("/live/status", params={"broker": "Robinhood "})
+
+ assert response.status_code == 200
+ body = response.json()
+ assert [b["auth"]["broker"] for b in body["brokers"]] == ["robinhood"]
+
+
+def test_live_status_blank_broker_rejected(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+
+ response = client.get("/live/status", params={"broker": " "})
+
+ assert response.status_code == 400
+
+
+def test_live_status_reflects_active_mandate(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ monkeypatch.setattr(
+ api_server, "_active_mandate_state", lambda broker: _valid_mandate_state(broker)
+ )
+
+ response = client.get("/live/status", params={"broker": "robinhood"})
+
+ assert response.status_code == 200
+ rh = response.json()["brokers"][0]
+ assert rh["mandate"]["expired"] is False
+ assert rh["mandate"]["limits"]["max_order_notional_usd"] == 750.0
+
+
+# --------------------------------------------------------------------------- #
+# C2 — POST /live/authorize (discover-only on-ramp; never authorizes server-side)
+# --------------------------------------------------------------------------- #
+
+
+def test_authorize_onramp_describes_cli_flow(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+
+ response = client.post("/live/authorize", json={"broker": "robinhood"})
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["broker"] == "robinhood"
+ assert body["oauth_token_present"] is False
+ # On-ramp must point at the desktop CLI flow and never return a token.
+ assert "vibe-trading live authorize robinhood" in body["instruction"]
+ assert "token" not in body
+
+
+def test_authorize_unknown_broker_rejected(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+
+ response = client.post("/live/authorize", json={"broker": "etrade"})
+
+ assert response.status_code == 400
+
+
+# --------------------------------------------------------------------------- #
+# Runner control — POST /live/runner/start|stop
+# --------------------------------------------------------------------------- #
+
+
+def test_runner_start_requires_committed_mandate(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+
+ response = client.post("/live/runner/start", json={"broker": "robinhood"})
+
+ assert response.status_code == 409
+ assert "mandate" in response.json()["detail"].lower()
+
+
+def test_runner_start_blocked_by_kill_switch(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ monkeypatch.setattr(
+ api_server, "_active_mandate_state", lambda broker: _valid_mandate_state(broker)
+ )
+ from src.live.halt import trip_halt
+
+ trip_halt(by="test", reason="safety", broker="robinhood")
+
+ response = client.post("/live/runner/start", json={"broker": "robinhood"})
+
+ assert response.status_code == 409
+ assert "kill switch" in response.json()["detail"].lower()
+
+
+def test_runner_start_success_then_idempotent(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ monkeypatch.setattr(
+ api_server, "_active_mandate_state", lambda broker: _valid_mandate_state(broker)
+ )
+ monkeypatch.setattr(api_server, "_runner_factory", lambda broker: SimpleNamespace(broker=broker))
+
+ async def _noop_drive(runner) -> None: # never spawns a real agent/broker loop
+ return None
+
+ monkeypatch.setattr(api_server, "_drive_runner", _noop_drive)
+
+ first = client.post("/live/runner/start", json={"broker": "robinhood"})
+ assert first.status_code == 200
+ assert first.json() == {"broker": "robinhood", "started": True, "already_running": False}
+
+ # Pre-seed a still-pending task so the idempotency branch is deterministic.
+ class _PendingTask:
+ def done(self) -> bool:
+ return False
+
+ def cancel(self) -> None:
+ self._cancelled = True
+
+ monkeypatch.setattr(api_server, "_runner_tasks", {"robinhood": _PendingTask()})
+
+ second = client.post("/live/runner/start", json={"broker": "robinhood"})
+ assert second.status_code == 200
+ assert second.json()["already_running"] is True
+
+
+def test_runner_stop_idempotent_when_not_running(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+
+ response = client.post("/live/runner/stop", json={"broker": "robinhood"})
+
+ assert response.status_code == 200
+ assert response.json() == {"broker": "robinhood", "stopped": False, "was_running": False}
+
+
+def test_runner_stop_cancels_running_task(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+
+ cancelled = {"value": False}
+
+ class _PendingTask:
+ def done(self) -> bool:
+ return False
+
+ def cancel(self) -> None:
+ cancelled["value"] = True
+
+ monkeypatch.setattr(api_server, "_runner_tasks", {"robinhood": _PendingTask()})
+
+ response = client.post("/live/runner/stop", json={"broker": "robinhood"})
+
+ assert response.status_code == 200
+ assert response.json() == {"broker": "robinhood", "stopped": True, "was_running": True}
+ assert cancelled["value"] is True
+
+
+# --------------------------------------------------------------------------- #
+# C1 — propose_mandate_profiles tool_result -> mandate.proposal SSE frame
+# --------------------------------------------------------------------------- #
+
+
+def _seed_proposal(tmp_path: Path, proposal_id: str, broker: str = "robinhood") -> dict:
+ proposal = {
+ "type": "mandate.proposal",
+ "proposal_id": proposal_id,
+ "session_id": "s1",
+ "profiles": [{"ordinal": 1, "label": "稳健", "max_order_usd": 250}],
+ }
+ proposals_dir = tmp_path / ".vibe-trading" / "live" / broker / "proposals"
+ proposals_dir.mkdir(parents=True, exist_ok=True)
+ (proposals_dir / f"{proposal_id}.json").write_text(
+ json.dumps(proposal), encoding="utf-8"
+ )
+ return proposal
+
+
+def test_c1_relay_builds_mandate_proposal_frame(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)
+ proposal_id = "mp_01ABCdef"
+ _seed_proposal(tmp_path, proposal_id)
+
+ event = SimpleNamespace(
+ event_type="tool_result",
+ session_id="s1",
+ data={
+ "tool": "propose_mandate_profiles",
+ "status": "ok",
+ "preview": json.dumps({"proposal_id": proposal_id})[:200],
+ },
+ )
+
+ frame = api_server._mandate_proposal_frame_from_tool_result(event)
+
+ assert frame is not None
+ assert "mandate.proposal" in frame
+ assert proposal_id in frame
+
+
+def test_c1_relay_ignores_non_propose_events(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)
+
+ # A different tool's result: no relay.
+ other = SimpleNamespace(
+ event_type="tool_result",
+ session_id="s1",
+ data={"tool": "run_backtest", "status": "ok", "preview": "{}"},
+ )
+ assert api_server._mandate_proposal_frame_from_tool_result(other) is None
+
+ # A non-tool_result event: no relay.
+ thinking = SimpleNamespace(event_type="thinking", session_id="s1", data={})
+ assert api_server._mandate_proposal_frame_from_tool_result(thinking) is None
+
+
+def test_c1_relay_returns_none_when_proposal_missing(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)
+ # Preview references an id with no persisted proposal on disk.
+ event = SimpleNamespace(
+ event_type="tool_result",
+ session_id="s1",
+ data={
+ "tool": "propose_mandate_profiles",
+ "status": "ok",
+ "preview": json.dumps({"proposal_id": "mp_missing01"})[:200],
+ },
+ )
+ assert api_server._mandate_proposal_frame_from_tool_result(event) is None
+
+
+# --------------------------------------------------------------------------- #
+# Real runner factory (R-INT): no more TypeError on the default path
+# --------------------------------------------------------------------------- #
+
+
+def test_build_live_runner_no_broker_configured_raises_unavailable(tmp_path, monkeypatch) -> None:
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)
+ monkeypatch.setattr(api_server, "_runner_factory", None, raising=False)
+ # No robinhood MCP server in the default config → clean 503-class error,
+ # NOT a TypeError (the audit's CRITICAL finding).
+ import pytest
+
+ with pytest.raises(api_server.LiveRunnerUnavailable):
+ api_server._build_live_runner("robinhood")
+
+
+def test_build_live_runner_wires_a_real_runner(tmp_path, monkeypatch) -> None:
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)
+ monkeypatch.setattr(api_server, "_runner_factory", None, raising=False)
+
+ # Stub the broker adapter + session service so no real broker/agent is hit.
+ class _StubAdapter:
+ def call_tool(self, name, args):
+ return {"status": "ok", "result": {}}
+
+ class _StubSession:
+ session_id = "live-sess-1"
+
+ class _StubSvc:
+ event_bus = SimpleNamespace(emit=lambda *a, **k: None)
+
+ def create_session(self, title=""):
+ return _StubSession()
+
+ async def send_message(self, sid, content, **kw):
+ return {"message_id": "m1", "attempt_id": "a1"}
+
+ monkeypatch.setattr(api_server, "_live_broker_adapter", lambda broker: _StubAdapter())
+ monkeypatch.setattr(api_server, "_get_session_service", lambda: _StubSvc())
+
+ runner = api_server._build_live_runner("robinhood")
+ # Constructs without TypeError and exposes the R2 contract.
+ assert runner.broker == "robinhood"
+ assert hasattr(runner, "run_once") and hasattr(runner, "run_loop")
+ assert runner.runner_id == "robinhood"
+
+
+def test_runner_start_returns_503_when_broker_unavailable(tmp_path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ monkeypatch.setattr(
+ api_server, "_active_mandate_state", lambda broker: _valid_mandate_state(broker)
+ )
+
+ def _boom(broker):
+ raise api_server.LiveRunnerUnavailable("no MCP server configured for live broker 'robinhood'")
+
+ monkeypatch.setattr(api_server, "_runner_factory", _boom)
+
+ response = client.post("/live/runner/start", json={"broker": "robinhood"})
+ assert response.status_code == 503
+ assert "configured" in response.json()["detail"]
+
+
+# --------------------------------------------------------------------------- #
+# H5 — per-order live.action SSE relay (reload full record from the ledger)
+# --------------------------------------------------------------------------- #
+
+
+def _seed_ledger(tmp_path: Path, record: dict) -> None:
+ ledger = tmp_path / ".vibe-trading" / "live" / "audit.jsonl"
+ ledger.parent.mkdir(parents=True, exist_ok=True)
+ with ledger.open("a", encoding="utf-8") as fh:
+ fh.write(json.dumps(record) + "\n")
+
+
+def test_live_action_relay_builds_frame_from_guard_result(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)
+ audit_id = "la_01abcDEF"
+ _seed_ledger(tmp_path, {"audit_id": audit_id, "kind": "order_placed", "outcome": "accepted",
+ "broker_request": {"symbol": "NVDA"}})
+
+ event = SimpleNamespace(
+ event_type="tool_result",
+ session_id="s1",
+ data={
+ "tool": "mcp_robinhood_place_order",
+ "status": "ok",
+ "preview": json.dumps({"status": "ok", "live_action": {"audit_id": audit_id}})[:200],
+ },
+ )
+
+ frame = api_server._live_action_frame_from_tool_result(event)
+ assert frame is not None
+ assert "live.action" in frame
+ assert audit_id in frame and "order_placed" in frame
+
+
+def test_live_action_relay_ignores_non_live_results(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)
+ # A normal tool_result with no live_action marker → no relay.
+ event = SimpleNamespace(
+ event_type="tool_result", session_id="s1",
+ data={"tool": "run_backtest", "status": "ok", "preview": "{}"},
+ )
+ assert api_server._live_action_frame_from_tool_result(event) is None
+
+
+# --------------------------------------------------------------------------- #
+# H9 — broker-derived ceilings hook
+# --------------------------------------------------------------------------- #
+
+
+def test_fetch_broker_ceilings_derives_from_account(tmp_path, monkeypatch) -> None:
+ class _StubAdapter:
+ def call_tool(self, name, args):
+ assert name == "get_account"
+ return {"status": "ok", "result": {"buying_power": 4200.0}}
+
+ monkeypatch.setattr(api_server, "_live_broker_adapter", lambda broker: _StubAdapter())
+ ceilings = api_server._fetch_broker_ceilings("robinhood")
+ assert ceilings == {
+ "account_funding_usd": 4200.0,
+ "max_order_notional_usd": 4200.0,
+ "max_total_exposure_usd": 4200.0,
+ }
+
+
+def test_fetch_broker_ceilings_falls_back_to_none(tmp_path, monkeypatch) -> None:
+ # Unavailable broker → None (commit falls back to the proposal snapshot).
+ def _unavail(broker):
+ raise api_server.LiveRunnerUnavailable("x")
+
+ monkeypatch.setattr(api_server, "_live_broker_adapter", _unavail)
+ assert api_server._fetch_broker_ceilings("robinhood") is None
diff --git a/agent/tests/test_audit_redact.py b/agent/tests/test_audit_redact.py
new file mode 100644
index 000000000..ea6416ab9
--- /dev/null
+++ b/agent/tests/test_audit_redact.py
@@ -0,0 +1,307 @@
+"""Tests for the live-action audit ledger (src/live/audit.py, SPEC Consent §5).
+
+Focus: every record is redacted BEFORE it touches the ledger or the SSE bus, the
+ledger is append-only, and the accountability refs (mandate/consent) survive
+redaction so the chain back to the authorizing user click stays intact.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from src.live import audit
+from src.live import paths
+from src.live.audit import LiveActionEvent, write_live_action
+
+
+def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Point the live runtime root at an isolated tmp dir."""
+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)
+ return tmp_path
+
+
+def _read_ledger() -> list[dict]:
+ lines = audit.audit_ledger_path().read_text(encoding="utf-8").splitlines()
+ return [json.loads(line) for line in lines if line.strip()]
+
+
+def test_credentials_redacted_before_write(live_runtime: Path) -> None:
+ event = LiveActionEvent(
+ kind="order_placed",
+ session_id="s1",
+ outcome="accepted",
+ server="robinhood",
+ remote_tool="place_order",
+ intent_normalized="buy 3 NVDA @ market",
+ mandate_snapshot_ref="mandate_01",
+ consent_record_ref="cr_01",
+ broker_request={
+ "symbol": "NVDA",
+ "qty": 3,
+ "authorization": "Bearer super-secret-jwt",
+ "access_token": "rh-oauth-token-xyz",
+ "api_key": "ak_live_123",
+ },
+ broker_response={"order_id": "rh_1", "state": "accepted"},
+ )
+ returned = write_live_action(event)
+ written = _read_ledger()
+ assert len(written) == 1
+ rec = written[0]
+
+ # The function returns exactly what it wrote (for the SSE emit).
+ assert returned == rec
+
+ req = rec["broker_request"]
+ # Credential-class keys are scrubbed (authorization / *_token / api_key).
+ assert req["authorization"] == "[redacted]"
+ assert req["access_token"] == "[redacted]"
+ assert req["api_key"] == "[redacted]"
+ # Non-sensitive order fields are preserved.
+ assert req["symbol"] == "NVDA"
+ assert req["qty"] == 3
+
+ # The accountability chain survives redaction.
+ assert rec["mandate_snapshot_ref"] == "mandate_01"
+ assert rec["consent_record_ref"] == "cr_01"
+ assert rec["intent_normalized"] == "buy 3 NVDA @ market"
+ assert rec["server"] == "robinhood"
+ assert rec["remote_tool"] == "place_order"
+
+
+def test_event_not_mutated_by_redaction(live_runtime: Path) -> None:
+ event = LiveActionEvent(
+ kind="order_placed",
+ session_id="s1",
+ outcome="accepted",
+ server="robinhood",
+ broker_request={"token": "leak-me"},
+ )
+ write_live_action(event)
+ # The frozen event's original payload is untouched; only the written record
+ # is redacted.
+ assert event.broker_request == {"token": "leak-me"}
+
+
+def test_ledger_is_append_only(live_runtime: Path) -> None:
+ for i in range(3):
+ write_live_action(
+ LiveActionEvent(
+ kind="order_placed",
+ session_id="s1",
+ outcome="accepted",
+ server="robinhood",
+ intent_normalized=f"order {i}",
+ )
+ )
+ written = _read_ledger()
+ assert len(written) == 3
+ assert [r["intent_normalized"] for r in written] == ["order 0", "order 1", "order 2"]
+
+
+def test_auto_ids_and_timestamp(live_runtime: Path) -> None:
+ write_live_action(
+ LiveActionEvent(
+ kind="halt_tripped",
+ session_id="s1",
+ outcome="blocked",
+ server="robinhood",
+ )
+ )
+ rec = _read_ledger()[0]
+ assert rec["audit_id"].startswith("la_")
+ # ms-precision UTC ISO-8601.
+ assert rec["ts"].endswith("+00:00") or rec["ts"].endswith("Z")
+ assert "." in rec["ts"]
+
+
+def test_directory_created_on_first_write(live_runtime: Path) -> None:
+ assert not audit.audit_ledger_path().exists()
+ write_live_action(
+ LiveActionEvent(
+ kind="mandate_committed",
+ session_id="s1",
+ outcome="accepted",
+ server="robinhood",
+ )
+ )
+ assert audit.audit_ledger_path().exists()
+
+
+def test_account_number_and_pii_redacted_but_provenance_kept(live_runtime: Path) -> None:
+ """H1: account numbers / SSN inside broker payloads are scrubbed, while the
+ opaque ``account_ref`` provenance (mandate→consent chain, SPEC §5) survives.
+
+ Pre-fix this FAILS — ``redact_payload`` only scrubbed credential markers, so
+ ``account_number`` / ``ssn`` / ``routing_number`` passed through RAW.
+ """
+ event = LiveActionEvent(
+ kind="order_placed",
+ session_id="s1",
+ outcome="accepted",
+ server="robinhood",
+ remote_tool="place_order",
+ broker_request={
+ "symbol": "NVDA",
+ "qty": 3,
+ "account_number": "5XX111222",
+ "routing_number": "021000021",
+ },
+ broker_response={
+ "order_id": "rh_1",
+ "state": "accepted",
+ "account_id": "acct-abc-123",
+ "account_url": "https://api.robinhood.com/accounts/5XX111222/",
+ "ssn": "123-45-6789",
+ "tax_id": "98-7654321",
+ # An opaque per-record broker reference kept for traceability.
+ "account_ref": "rh_ref_opaque_keepme",
+ },
+ )
+ rec = write_live_action(event)
+
+ req = rec["broker_request"]
+ assert req["account_number"] == "[redacted]"
+ assert req["routing_number"] == "[redacted]"
+ assert req["symbol"] == "NVDA" # benign field preserved
+ assert req["qty"] == 3
+
+ resp = rec["broker_response"]
+ assert resp["account_id"] == "[redacted]"
+ assert resp["account_url"] == "[redacted]"
+ assert resp["ssn"] == "[redacted]"
+ assert resp["tax_id"] == "[redacted]"
+ # Provenance reference is intentionally NOT redacted.
+ assert resp["account_ref"] == "rh_ref_opaque_keepme"
+ # Benign response fields preserved.
+ assert resp["order_id"] == "rh_1"
+ assert resp["state"] == "accepted"
+
+
+class _RecordingTrace:
+ """Minimal TraceWriter-shaped sink that records the entries it receives."""
+
+ def __init__(self) -> None:
+ self.entries: list[dict] = []
+
+ def write(self, entry: dict) -> None:
+ self.entries.append(entry)
+
+
+def test_trace_writer_sink_receives_live_action_type(live_runtime: Path) -> None:
+ """H5 sink 2: when a trace_writer is passed it gets the redacted record
+ tagged ``type="live_action"``, alongside tool_call/tool_result."""
+ trace = _RecordingTrace()
+ event = LiveActionEvent(
+ kind="order_placed",
+ session_id="s1",
+ outcome="accepted",
+ server="robinhood",
+ broker_request={"symbol": "AAPL", "token": "leak-me", "account_number": "999"},
+ )
+ rec = write_live_action(event, trace_writer=trace)
+
+ assert len(trace.entries) == 1
+ entry = trace.entries[0]
+ assert entry["type"] == "live_action"
+ # Redacted BEFORE the trace sink — no secret/account number leaks.
+ assert entry["broker_request"]["token"] == "[redacted]"
+ assert entry["broker_request"]["account_number"] == "[redacted]"
+ assert entry["broker_request"]["symbol"] == "AAPL"
+ # The trace entry carries the same record fields as the returned dict.
+ assert entry["audit_id"] == rec["audit_id"]
+ assert entry["kind"] == "order_placed"
+
+
+def test_event_callback_sink_called_with_redacted_record(live_runtime: Path) -> None:
+ """H5 sink 3: event_callback fires with ("live.action", redacted_record)."""
+ captured: list[tuple] = []
+
+ def cb(name: str, payload: dict) -> None:
+ captured.append((name, payload))
+
+ event = LiveActionEvent(
+ kind="order_placed",
+ session_id="s1",
+ outcome="accepted",
+ server="robinhood",
+ broker_request={"symbol": "MSFT", "ssn": "111-22-3333"},
+ )
+ rec = write_live_action(event, event_callback=cb)
+
+ assert len(captured) == 1
+ name, payload = captured[0]
+ assert name == "live.action"
+ assert payload == rec
+ # Redacted before the surface sees it.
+ assert payload["broker_request"]["ssn"] == "[redacted]"
+ assert payload["broker_request"]["symbol"] == "MSFT"
+
+
+def test_redaction_happens_before_all_sinks(live_runtime: Path) -> None:
+ """All three sinks (ledger, trace, callback) receive the SAME redacted dict;
+ nothing sees the raw secret/account number."""
+ trace = _RecordingTrace()
+ captured: list[dict] = []
+ event = LiveActionEvent(
+ kind="order_placed",
+ session_id="s1",
+ outcome="accepted",
+ server="robinhood",
+ broker_request={"authorization": "Bearer x", "account_number": "777", "qty": 1},
+ )
+ rec = write_live_action(
+ event,
+ trace_writer=trace,
+ event_callback=lambda _n, p: captured.append(p),
+ )
+
+ ledger_rec = _read_ledger()[0]
+ trace_req = trace.entries[0]["broker_request"]
+ cb_req = captured[0]["broker_request"]
+ for req in (rec["broker_request"], ledger_rec["broker_request"], trace_req, cb_req):
+ assert req["authorization"] == "[redacted]"
+ assert req["account_number"] == "[redacted]"
+ assert req["qty"] == 1
+
+
+def test_optional_sinks_skipped_when_absent_backward_compat(live_runtime: Path) -> None:
+ """Backward compat: write_live_action(event) with no kwargs still works and
+ writes ONLY the ledger (no trace, no callback)."""
+ rec = write_live_action(
+ LiveActionEvent(
+ kind="order_placed",
+ session_id="s1",
+ outcome="accepted",
+ server="robinhood",
+ intent_normalized="ledger only",
+ )
+ )
+ written = _read_ledger()
+ assert len(written) == 1
+ assert written[0]["intent_normalized"] == "ledger only"
+ assert written[0] == rec
+
+
+def test_ledger_still_append_only_with_sinks(live_runtime: Path) -> None:
+ """Trace/callback sinks do not disturb the append-only ledger semantics."""
+ trace = _RecordingTrace()
+ for i in range(3):
+ write_live_action(
+ LiveActionEvent(
+ kind="order_placed",
+ session_id="s1",
+ outcome="accepted",
+ server="robinhood",
+ intent_normalized=f"order {i}",
+ ),
+ trace_writer=trace,
+ event_callback=lambda _n, _p: None,
+ )
+ written = _read_ledger()
+ assert [r["intent_normalized"] for r in written] == ["order 0", "order 1", "order 2"]
+ assert len(trace.entries) == 3
diff --git a/agent/tests/test_classification.py b/agent/tests/test_classification.py
new file mode 100644
index 000000000..99baa3134
--- /dev/null
+++ b/agent/tests/test_classification.py
@@ -0,0 +1,64 @@
+"""Read/write classification ladder: annotations, curated map wins, default-deny."""
+
+from __future__ import annotations
+
+from mcp.types import ToolAnnotations
+
+from src.live.classification import ToolClass, classify_tool
+from src.live.robinhood_classification import ROBINHOOD_TOOL_CLASS
+
+
+def test_tier1_explicit_read_only_hint_true_is_read() -> None:
+ """readOnlyHint=True with no curated entry → READ."""
+ ann = ToolAnnotations(readOnlyHint=True)
+ assert classify_tool("get_quotes", ann) is ToolClass.READ
+
+
+def test_tier1_explicit_read_only_hint_false_is_write() -> None:
+ """readOnlyHint=False → WRITE (additive-only is still a write)."""
+ ann = ToolAnnotations(readOnlyHint=False, destructiveHint=False)
+ assert classify_tool("submit_thing", ann) is ToolClass.WRITE
+
+
+def test_absent_read_only_hint_is_not_read() -> None:
+ """readOnlyHint=None (hint absent) must NOT be treated as read → UNKNOWN."""
+ ann = ToolAnnotations(readOnlyHint=None, title="some tool")
+ assert classify_tool("mystery_tool", ann) is ToolClass.UNKNOWN
+
+
+def test_tier2_curated_map_classifies_known_tools() -> None:
+ """Curated map drives classification for known names."""
+ assert (
+ classify_tool("get_positions", None, ROBINHOOD_TOOL_CLASS) is ToolClass.READ
+ )
+ assert classify_tool("place_order", None, ROBINHOOD_TOOL_CLASS) is ToolClass.WRITE
+
+
+def test_deceptive_read_only_hint_cannot_demote_curated_write() -> None:
+ """A lying readOnlyHint=True on place_order stays WRITE — the map wins."""
+ deceptive = ToolAnnotations(readOnlyHint=True)
+ assert (
+ classify_tool("place_order", deceptive, ROBINHOOD_TOOL_CLASS)
+ is ToolClass.WRITE
+ )
+
+
+def test_annotation_catches_write_map_missed() -> None:
+ """A tool absent from the map but annotated write → WRITE (not excused)."""
+ ann = ToolAnnotations(readOnlyHint=False)
+ assert (
+ classify_tool("place_bracket_order", ann, ROBINHOOD_TOOL_CLASS)
+ is ToolClass.WRITE
+ )
+
+
+def test_tier3_default_deny_unknown_and_unannotated() -> None:
+ """Neither annotated read-only nor in the map → UNKNOWN (fail-closed)."""
+ assert classify_tool("brand_new_tool", None, ROBINHOOD_TOOL_CLASS) is ToolClass.UNKNOWN
+ assert classify_tool("brand_new_tool", None) is ToolClass.UNKNOWN
+
+
+def test_map_read_pin_not_overridden_by_absent_annotation() -> None:
+ """A curated READ wins even when annotations are present but silent."""
+ ann = ToolAnnotations(title="quotes", readOnlyHint=None)
+ assert classify_tool("get_quotes", ann, ROBINHOOD_TOOL_CLASS) is ToolClass.READ
diff --git a/agent/tests/test_cli_live.py b/agent/tests/test_cli_live.py
new file mode 100644
index 000000000..536dbed2f
--- /dev/null
+++ b/agent/tests/test_cli_live.py
@@ -0,0 +1,648 @@
+"""Tests for the `vibe-trading live` CLI surface + REPL intercepts (P6).
+
+Covers SPEC.md §9 Decision 1 (CLI surface table) and Consent §2/§4:
+
+* The ``live`` subcommand group dispatches each verb to the right handler.
+* ``live halt`` / ``live resume`` trip and clear the kill switch on disk.
+* ``live status`` / ``live mandate`` are read-only and reflect disk state.
+* ``live revoke`` deletes the token cache + mandate.
+* The REPL intercepts a bare numeric pick as a COMMIT — it calls the commit
+ endpoint directly and NEVER routes the pick to the agent/model.
+* The REPL intercepts a bare "停"/"stop"/"/halt" turn — it trips the kill
+ switch without entering the agent loop.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any, Dict
+from unittest.mock import patch
+
+import pytest
+
+import importlib
+
+import src.live.paths as live_paths
+
+# ``cli/__init__.py`` re-exports the ``main`` *function* as ``cli.main``, which
+# shadows the submodule for attribute access. Import the module object directly
+# so ``patch.object(main, ...)`` targets the real ``cli/main.py`` namespace.
+main = importlib.import_module("cli.main")
+InteractiveContext = main.InteractiveContext
+_commit_mandate = main._commit_mandate
+_handle_proposal_reply = main._handle_proposal_reply
+_is_halt_turn = main._is_halt_turn
+_is_numeric_pick = main._is_numeric_pick
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def live_root(tmp_path: Path):
+ """Redirect the live-channel runtime root to a tmp dir for the test.
+
+ ``src.live.paths.live_root`` and ``broker_dir`` both resolve through
+ ``get_runtime_root`` at call time, so patching it isolates halt + mandate
+ state for halt.py / store.py without touching the real ~/.vibe-trading.
+ """
+ with patch.object(live_paths, "get_runtime_root", return_value=tmp_path):
+ yield tmp_path
+
+
+def _write_mandate(root: Path, broker: str = "robinhood", *, schema_version: int = 1) -> Path:
+ """Write a structurally valid mandate.json under the patched root."""
+ broker_dir = root / "live" / broker
+ broker_dir.mkdir(parents=True, exist_ok=True)
+ payload = {
+ "schema_version": schema_version,
+ "hard_caps": {
+ "account_funding_usd": 5000.0,
+ "max_order_notional_usd": 750.0,
+ "max_total_exposure_usd": 5000.0,
+ "max_leverage": 1.0,
+ "allowed_instruments": ["equity"],
+ "max_trades_per_day": 5,
+ },
+ "universe": {
+ "asset_classes": ["us_equity"],
+ "min_market_cap_usd": None,
+ "min_avg_daily_volume_usd": None,
+ "exclude_symbols": [],
+ },
+ "consent": {
+ "created_at": "2026-05-29T00:00:00+00:00",
+ "consent_token_sha256": "deadbeef",
+ "broker": broker,
+ "account_ref": "acct_123",
+ "expires_at": "2099-01-01T00:00:00+00:00",
+ },
+ }
+ path = broker_dir / "mandate.json"
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ return path
+
+
+# ---------------------------------------------------------------------------
+# Subcommand dispatch
+# ---------------------------------------------------------------------------
+
+
+class TestLiveDispatch:
+ def _dispatch(self, argv: list[str]) -> int:
+ from cli._legacy import _build_parser, _dispatch_live
+
+ args = _build_parser().parse_args(argv)
+ return _dispatch_live(args)
+
+ def test_authorize_routes_to_handler(self) -> None:
+ with patch("cli._legacy.cmd_live_authorize", return_value=0) as m:
+ assert self._dispatch(["live", "authorize", "robinhood"]) == 0
+ m.assert_called_once_with("robinhood")
+
+ def test_status_routes_with_broker(self) -> None:
+ with patch("cli._legacy.cmd_live_status", return_value=0) as m:
+ self._dispatch(["live", "status", "robinhood"])
+ m.assert_called_once_with("robinhood")
+
+ def test_status_routes_default_broker_none(self) -> None:
+ with patch("cli._legacy.cmd_live_status", return_value=0) as m:
+ self._dispatch(["live", "status"])
+ m.assert_called_once_with(None)
+
+ def test_mandate_routes(self) -> None:
+ with patch("cli._legacy.cmd_live_mandate", return_value=0) as m:
+ self._dispatch(["live", "mandate"])
+ m.assert_called_once_with(None)
+
+ def test_halt_routes(self) -> None:
+ with patch("cli._legacy.cmd_live_halt", return_value=0) as m:
+ self._dispatch(["live", "halt"])
+ m.assert_called_once_with(None)
+
+ def test_resume_routes(self) -> None:
+ with patch("cli._legacy.cmd_live_resume", return_value=0) as m:
+ self._dispatch(["live", "resume", "robinhood"])
+ m.assert_called_once_with("robinhood")
+
+ def test_revoke_routes(self) -> None:
+ with patch("cli._legacy.cmd_live_revoke", return_value=0) as m:
+ self._dispatch(["live", "revoke", "robinhood"])
+ m.assert_called_once_with("robinhood")
+
+ def test_no_subcommand_is_usage_error(self) -> None:
+ from cli._legacy import EXIT_USAGE_ERROR
+
+ assert self._dispatch(["live"]) == EXIT_USAGE_ERROR
+
+ def test_no_live_commit_verb_exists(self) -> None:
+ """SPEC: the CLI live group must not be able to create/widen a mandate."""
+ from cli._legacy import _build_parser
+
+ parser = _build_parser()
+ with pytest.raises(SystemExit):
+ parser.parse_args(["live", "commit", "robinhood"])
+
+
+# ---------------------------------------------------------------------------
+# halt / resume on disk
+# ---------------------------------------------------------------------------
+
+
+class TestLiveHaltResume:
+ def test_halt_trips_global_sentinel(self, live_root: Path) -> None:
+ from cli._legacy import cmd_live_halt
+ from src.live.halt import halt_flag_set
+
+ assert cmd_live_halt(None) == 0
+ assert (live_root / "live" / "HALT").exists()
+ assert halt_flag_set("robinhood") is True
+
+ def test_halt_broker_scoped(self, live_root: Path) -> None:
+ from cli._legacy import cmd_live_halt
+ from src.live.halt import halt_flag_set
+
+ cmd_live_halt("robinhood")
+ assert (live_root / "live" / "robinhood" / "HALT").exists()
+ assert not (live_root / "live" / "HALT").exists()
+ assert halt_flag_set("robinhood") is True
+
+ def test_resume_clears_halt(self, live_root: Path) -> None:
+ from cli._legacy import cmd_live_halt, cmd_live_resume
+ from src.live.halt import halt_flag_set
+
+ cmd_live_halt(None)
+ assert cmd_live_resume(None) == 0
+ assert halt_flag_set("robinhood") is False
+
+ def test_resume_when_not_halted_is_success(self, live_root: Path) -> None:
+ from cli._legacy import cmd_live_resume
+
+ assert cmd_live_resume(None) == 0
+
+
+# ---------------------------------------------------------------------------
+# status / mandate (read-only)
+# ---------------------------------------------------------------------------
+
+
+class TestLiveStatusMandate:
+ def test_status_no_mandate(self, live_root: Path, capsys: pytest.CaptureFixture[str]) -> None:
+ from cli._legacy import cmd_live_status
+
+ assert cmd_live_status("robinhood") == 0
+ out = capsys.readouterr().out
+ assert "none on file" in out
+
+ def test_status_shows_active_mandate_and_countdown(
+ self, live_root: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ from cli._legacy import cmd_live_status
+
+ _write_mandate(live_root)
+ cmd_live_status("robinhood")
+ out = capsys.readouterr().out
+ assert "active" in out
+ assert "750" in out # max order notional
+ assert "2099" in out # expires_at countdown anchor
+
+ def test_status_reflects_halt(self, live_root: Path, capsys: pytest.CaptureFixture[str]) -> None:
+ from cli._legacy import cmd_live_halt, cmd_live_status
+
+ cmd_live_halt(None)
+ cmd_live_status("robinhood")
+ assert "HALTED" in capsys.readouterr().out
+
+ def test_status_flags_unknown_schema_version(
+ self, live_root: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ from cli._legacy import cmd_live_status
+
+ _write_mandate(live_root, schema_version=999)
+ cmd_live_status("robinhood")
+ assert "unknown schema" in capsys.readouterr().out
+
+ def test_mandate_print_no_file(self, live_root: Path) -> None:
+ from cli._legacy import EXIT_RUN_FAILED, cmd_live_mandate
+
+ assert cmd_live_mandate("robinhood") == EXIT_RUN_FAILED
+
+ def test_mandate_print_renders_json(
+ self, live_root: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ from cli._legacy import cmd_live_mandate
+
+ _write_mandate(live_root)
+ assert cmd_live_mandate("robinhood") == 0
+ out = capsys.readouterr().out
+ assert "max_order_notional_usd" in out
+ assert "equity" in out # enum rendered as string value, not InstrumentType.EQUITY
+ assert "InstrumentType" not in out
+
+
+# ---------------------------------------------------------------------------
+# revoke
+# ---------------------------------------------------------------------------
+
+
+class TestLiveRevoke:
+ def test_revoke_deletes_token_and_mandate(self, live_root: Path) -> None:
+ from cli._legacy import cmd_live_revoke
+
+ broker_dir = live_root / "live" / "robinhood"
+ oauth_dir = broker_dir / "oauth"
+ oauth_dir.mkdir(parents=True)
+ (oauth_dir / "token.json").write_text("{}", encoding="utf-8")
+ mandate_path = _write_mandate(live_root)
+
+ # No agent config on disk → _live_server_config returns None → falls back
+ # to the canonical broker oauth/ subtree.
+ with patch("cli._legacy._live_server_config", return_value=None):
+ assert cmd_live_revoke("robinhood") == 0
+
+ assert not oauth_dir.exists()
+ assert not mandate_path.exists()
+
+ def test_revoke_nothing_to_remove(self, live_root: Path) -> None:
+ from cli._legacy import cmd_live_revoke
+
+ with patch("cli._legacy._live_server_config", return_value=None):
+ assert cmd_live_revoke("robinhood") == 0
+
+
+# ---------------------------------------------------------------------------
+# authorize (browser OAuth bootstrap)
+# ---------------------------------------------------------------------------
+
+
+class TestLiveAuthorize:
+ def test_authorize_no_config_is_usage_error(self) -> None:
+ from cli._legacy import EXIT_USAGE_ERROR, cmd_live_authorize
+
+ with patch("cli._legacy._live_server_config", return_value=None):
+ assert cmd_live_authorize("robinhood") == EXIT_USAGE_ERROR
+
+ def test_authorize_triggers_oauth_handshake(self) -> None:
+ """The only on-switch: building wrappers forces the connection/OAuth flow."""
+ from cli._legacy import cmd_live_authorize
+
+ fake_cfg = type("Cfg", (), {"auth": object()})()
+ with patch("cli._legacy._live_server_config", return_value=fake_cfg), patch(
+ "src.tools.mcp.build_mcp_tool_wrappers", return_value=[1, 2]
+ ) as build:
+ assert cmd_live_authorize("robinhood") == 0
+ build.assert_called_once()
+ assert build.call_args.args[0] == "robinhood"
+
+
+# ---------------------------------------------------------------------------
+# REPL intercept helpers
+# ---------------------------------------------------------------------------
+
+
+class TestHaltTurnDetection:
+ @pytest.mark.parametrize("text", ["停", "停。", "stop", "STOP", "kill", "halt", " 停 "])
+ def test_halt_words(self, text: str) -> None:
+ assert _is_halt_turn(text) is True
+
+ @pytest.mark.parametrize(
+ "text",
+ ["stop the AAPL position", "should I stop trading?", "buy NVDA", "停一下再分析这只票"],
+ )
+ def test_non_halt_turns(self, text: str) -> None:
+ assert _is_halt_turn(text) is False
+
+
+class TestNumericPick:
+ @pytest.mark.parametrize("text,expected", [("1", 1), ("2", 2), (" 3 ", 3), ("2.", 2)])
+ def test_bare_pick(self, text: str, expected: int) -> None:
+ assert _is_numeric_pick(text) == expected
+
+ @pytest.mark.parametrize("text", ["按 2 但每日笔数提到 10", "option 2", "0", "-1", "two"])
+ def test_adjust_or_invalid_not_a_pick(self, text: str) -> None:
+ assert _is_numeric_pick(text) is None
+
+
+# ---------------------------------------------------------------------------
+# COMMIT path: pick goes to the endpoint, NEVER the model
+# ---------------------------------------------------------------------------
+
+
+def _proposal() -> Dict[str, Any]:
+ return {
+ "proposal_id": "mp_test",
+ "session_id": "sess_1",
+ "intent_normalized": "aggressive tech, ~$5000",
+ "account": {"broker": "robinhood", "type": "cash"},
+ "profiles": [
+ {"ordinal": 1, "label": "稳健", "max_order_usd": 250, "daily_trade_cap": 2},
+ {"ordinal": 2, "label": "均衡", "max_order_usd": 750, "daily_trade_cap": 5},
+ ],
+ }
+
+
+class TestProposalPickIntercept:
+ def test_numeric_pick_calls_commit_not_model(self) -> None:
+ ctx = InteractiveContext()
+ ctx.pending_proposal = _proposal()
+ commit_result = {"status": "ok", "mandate_id": "mandate_42"}
+
+ with patch.object(main, "_commit_mandate", return_value=commit_result) as commit:
+ handled = _handle_proposal_reply("2", ctx)
+
+ assert handled is True # caller must NOT route to the agent/model
+ commit.assert_called_once()
+ # The commit binds the exact rendered proposal + the picked ordinal.
+ called_proposal, called_ordinal = commit.call_args.args
+ assert called_proposal["proposal_id"] == "mp_test"
+ assert called_ordinal == 2
+ # Successful commit clears the pending proposal.
+ assert ctx.pending_proposal is None
+
+ def test_adjust_reply_is_not_intercepted(self) -> None:
+ ctx = InteractiveContext()
+ ctx.pending_proposal = _proposal()
+
+ with patch.object(main, "_commit_mandate") as commit:
+ handled = _handle_proposal_reply("按 2 但每日笔数提到 10", ctx)
+
+ assert handled is False # caller routes to the agent for a re-render
+ commit.assert_not_called()
+ # Proposal stays pending until a fresh one replaces it.
+ assert ctx.pending_proposal is not None
+
+ def test_out_of_range_pick_does_not_commit(self) -> None:
+ ctx = InteractiveContext()
+ ctx.pending_proposal = _proposal()
+
+ with patch.object(main, "_commit_mandate") as commit:
+ handled = _handle_proposal_reply("9", ctx)
+
+ assert handled is True # consumed (the model still never sees it)
+ commit.assert_not_called()
+ assert ctx.pending_proposal is not None # not cleared on an invalid pick
+
+ def test_commit_failure_keeps_proposal_open(self) -> None:
+ ctx = InteractiveContext()
+ ctx.pending_proposal = _proposal()
+
+ with patch.object(main, "_commit_mandate", return_value={"status": "error", "error": "boom"}):
+ handled = _handle_proposal_reply("1", ctx)
+
+ assert handled is True
+ assert ctx.pending_proposal is not None
+
+ def test_commit_posts_to_endpoint_with_consent_ack(self) -> None:
+ """_commit_mandate POSTs to /mandate/commit — the surface, not the model."""
+ captured: Dict[str, Any] = {}
+
+ class _Resp:
+ def raise_for_status(self) -> None:
+ return None
+
+ def json(self) -> Dict[str, Any]:
+ return {"status": "ok", "mandate_id": "m1"}
+
+ def _fake_post(url: str, json: Dict[str, Any], timeout: float) -> _Resp: # noqa: A002
+ captured["url"] = url
+ captured["body"] = json
+ return _Resp()
+
+ with patch("httpx.post", _fake_post):
+ result = _commit_mandate(_proposal(), 2)
+
+ assert result["mandate_id"] == "m1"
+ assert captured["url"].endswith("/mandate/commit")
+ assert captured["body"]["selected_ordinal"] == 2
+ assert captured["body"]["proposal_id"] == "mp_test"
+ assert captured["body"]["consent_ack"] is True
+
+
+# ---------------------------------------------------------------------------
+# Kill-switch intercept: trips the flag without the agent loop
+# ---------------------------------------------------------------------------
+
+
+# ---------------------------------------------------------------------------
+# ARMING path: a REAL propose-tool tool_result event through on_event arms
+# ctx.pending_proposal (closes the false-confidence gap — prior tests set
+# pending_proposal directly and never exercised the relay). SPEC Consent §1/§2.
+# ---------------------------------------------------------------------------
+
+
+def _write_proposal_to_disk(root: Path, proposal_id: str, broker: str = "robinhood") -> Dict[str, Any]:
+ """Persist a full mandate.proposal exactly as ``propose_mandate_profiles`` does.
+
+ The propose tool writes ``<runtime_root>/live/<broker>/proposals/<id>.json``;
+ the relay reloads from there because the tool_result preview is truncated.
+ """
+ proposals_dir = root / "live" / broker / "proposals"
+ proposals_dir.mkdir(parents=True, exist_ok=True)
+ payload: Dict[str, Any] = {
+ "type": "mandate.proposal",
+ "proposal_id": proposal_id,
+ "session_id": "sess_1",
+ "intent_normalized": "aggressive tech, ~$5000",
+ "account": {"broker": broker, "type": "cash"},
+ "profiles": [
+ {"ordinal": 1, "label": "稳健", "max_order_usd": 250, "daily_trade_cap": 2},
+ {"ordinal": 2, "label": "均衡", "max_order_usd": 750, "daily_trade_cap": 5},
+ ],
+ }
+ (proposals_dir / f"{proposal_id}.json").write_text(json.dumps(payload), encoding="utf-8")
+ return payload
+
+
+def _capture_on_event(captured: Dict[str, Any]):
+ """Run ``_run_agent`` with all heavy deps stubbed, returning its ``on_event``.
+
+ Replaces ``AgentLoop`` with a stub that captures the real ``event_callback``
+ closure (``on_event``) instead of running an LLM, so a test can replay
+ arbitrary events THROUGH the genuine relay logic. ``build_registry`` /
+ ``ChatLLM`` / ``PersistentMemory`` / ``load_agent_config`` are stubbed to
+ no-ops so nothing touches the network or disk beyond the proposal reload.
+ """
+ import types as _types
+
+ from cli import _legacy
+
+ class _StubLoop:
+ def __init__(self, *_, event_callback=None, **__):
+ captured["on_event"] = event_callback
+ self.memory = _types.SimpleNamespace(run_dir=None)
+
+ def run(self, **__):
+ return {"content": "ok"}
+
+ proposal_seen: Dict[str, Any] = {}
+
+ def _sink(payload: Dict[str, Any]) -> None:
+ proposal_seen.clear()
+ proposal_seen.update(payload)
+
+ captured["sink_result"] = proposal_seen
+
+ # ``_run_agent`` does local ``from ... import`` for these, so patch the
+ # SOURCE modules, not the ``cli._legacy`` namespace.
+ with patch("src.agent.loop.AgentLoop", _StubLoop), patch(
+ "src.tools.build_registry", return_value=object()
+ ), patch("src.providers.chat.ChatLLM", lambda *a, **k: object()), patch(
+ "src.memory.persistent.PersistentMemory",
+ lambda *a, **k: _types.SimpleNamespace(run_dir=None),
+ ), patch(
+ "src.config.loader.load_agent_config", return_value=object()
+ ):
+ _legacy._run_agent(
+ "let AI trade tech aggressively with $5000",
+ stream_output=False,
+ proposal_sink=_sink,
+ )
+ return captured["on_event"]
+
+
+class TestProposalArmingRelay:
+ def test_real_tool_result_event_arms_pending_proposal(self, live_root: Path) -> None:
+ """A genuine propose-tool tool_result through on_event arms the proposal.
+
+ This is the path the prior tests skipped (they set pending_proposal
+ directly). Drives the event THROUGH the real ``on_event`` relay and
+ asserts the full proposal is reloaded from disk into the sink.
+ """
+ proposal_id = "mp_armtest01"
+ _write_proposal_to_disk(live_root, proposal_id)
+
+ captured: Dict[str, Any] = {}
+ on_event = _capture_on_event(captured)
+ assert on_event is not None
+
+ # The agent loop emits ONLY a generic tool_result; preview = result[:200]
+ # of the JSON body, which carries the proposal_id near the front.
+ preview = json.dumps(
+ {"type": "mandate.proposal", "proposal_id": proposal_id, "session_id": "sess_1"}
+ )[:200]
+ on_event("tool_result", {"tool": "propose_mandate_profiles", "status": "ok", "preview": preview})
+
+ armed = captured["sink_result"]
+ assert armed.get("proposal_id") == proposal_id
+ assert armed.get("type") == "mandate.proposal"
+ # Full body reloaded from disk — profiles the preview never carried.
+ assert [p["ordinal"] for p in armed["profiles"]] == [1, 2]
+
+ def test_unrelated_tool_result_does_not_arm(self, live_root: Path) -> None:
+ """A non-propose tool_result must never arm a proposal (no false-positive)."""
+ captured: Dict[str, Any] = {}
+ on_event = _capture_on_event(captured)
+ on_event("tool_result", {"tool": "backtest", "status": "ok", "preview": '{"sharpe": 1.2}'})
+ assert captured["sink_result"] == {}
+
+ def test_armed_then_bare_2_is_intercepted_not_sent_to_model(self, live_root: Path) -> None:
+ """End-to-end: arm via the relay, then a bare '2' commits (model never sees it).
+
+ Mirrors ``_interactive_loop``'s interception order: halt → proposal pick
+ → slash → model. With a proposal armed, '2' is consumed by
+ ``_handle_proposal_reply`` and routed to the commit endpoint, NOT the
+ agent.
+ """
+ proposal_id = "mp_e2e01"
+ _write_proposal_to_disk(live_root, proposal_id)
+
+ # 1) Arm through the real relay.
+ captured: Dict[str, Any] = {}
+ on_event = _capture_on_event(captured)
+ preview = json.dumps({"type": "mandate.proposal", "proposal_id": proposal_id})[:200]
+ on_event("tool_result", {"tool": "propose_mandate_profiles", "status": "ok", "preview": preview})
+
+ ctx = InteractiveContext()
+ ctx.pending_proposal = dict(captured["sink_result"])
+ assert ctx.pending_proposal["proposal_id"] == proposal_id
+
+ # 2) A bare "2" is intercepted BEFORE the model: replicate the loop guard.
+ text = "2"
+ routed_to_model = {"called": False}
+
+ def _fake_run_turn(*_a, **_k) -> None:
+ routed_to_model["called"] = True
+
+ with patch.object(main, "_run_one_turn", _fake_run_turn), patch.object(
+ main, "_commit_mandate", return_value={"status": "ok", "mandate_id": "m99"}
+ ) as commit, patch.object(main, "_is_halt_turn", return_value=False):
+ handled = False
+ if main._is_halt_turn(text):
+ pass
+ elif ctx.pending_proposal is not None and not text.startswith("/"):
+ handled = main._handle_proposal_reply(text, ctx)
+ if not handled and not text.startswith("/"):
+ main._run_one_turn(text, ctx)
+
+ assert handled is True
+ assert routed_to_model["called"] is False # the model NEVER saw the pick
+ commit.assert_called_once()
+ assert commit.call_args.args[0]["proposal_id"] == proposal_id
+ assert commit.call_args.args[1] == 2
+ assert ctx.pending_proposal is None # cleared on a successful commit
+
+ def test_bare_2_with_no_pending_proposal_routes_to_model(self, live_root: Path) -> None:
+ """No proposal armed → a bare '2' is normal text and goes to the model.
+
+ Guards against the relay over-reaching: the interception only fires when
+ ``ctx.pending_proposal`` is set; otherwise '2' must reach the agent.
+ """
+ ctx = InteractiveContext()
+ assert ctx.pending_proposal is None
+
+ text = "2"
+ routed_to_model = {"called": False}
+
+ def _fake_run_turn(arg_text: str, _ctx) -> None:
+ routed_to_model["called"] = True
+ assert arg_text == "2"
+
+ with patch.object(main, "_run_one_turn", _fake_run_turn), patch.object(
+ main, "_handle_proposal_reply"
+ ) as handle, patch.object(main, "_is_halt_turn", return_value=False):
+ handled = False
+ if main._is_halt_turn(text):
+ pass
+ elif ctx.pending_proposal is not None and not text.startswith("/"):
+ handled = main._handle_proposal_reply(text, ctx)
+ if not handled and not text.startswith("/"):
+ main._run_one_turn(text, ctx)
+
+ handle.assert_not_called() # no proposal → interception never runs
+ assert routed_to_model["called"] is True # '2' reached the model as chat
+
+
+class TestHaltIntercept:
+ def test_repl_halt_trips_flag(self, live_root: Path) -> None:
+ from src.live.halt import halt_flag_set
+
+ console = main.get_console()
+ main._trip_halt_from_repl(console, reason="repl turn: 停")
+
+ assert halt_flag_set("robinhood") is True
+ assert (live_root / "live" / "HALT").exists()
+
+ def test_halt_turn_bypasses_one_turn_runner(self, live_root: Path) -> None:
+ """A bare halt turn trips the switch via the input path, never the agent.
+
+ Mirrors the ``_interactive_loop`` guard: a halt turn is consumed before
+ ``_run_one_turn`` (the only path into ``_run_agent``) is ever called.
+ """
+ from src.live.halt import halt_flag_set
+
+ text = "停"
+ ctx = InteractiveContext()
+ console = main.get_console()
+
+ with patch.object(main, "_run_one_turn") as run_turn:
+ # Replicate the loop's interception order: halt check comes first.
+ if _is_halt_turn(text):
+ main._trip_halt_from_repl(console, reason=f"repl turn: {text}")
+ else:
+ run_turn(text, ctx)
+
+ run_turn.assert_not_called()
+ assert halt_flag_set("robinhood") is True
diff --git a/agent/tests/test_cli_runtime.py b/agent/tests/test_cli_runtime.py
new file mode 100644
index 000000000..a600a9b92
--- /dev/null
+++ b/agent/tests/test_cli_runtime.py
@@ -0,0 +1,377 @@
+"""Tests for the live-runtime CLI surface + discoverability (parcel R7).
+
+Covers SPEC.md §7.5 (persistent runner control) + §9 Decision 1 (CLI surface
+table) + the §9 audit discoverability fix:
+
+* ``live run`` / ``live start`` / ``live stop`` dispatch to their handlers and
+ relay to the R6 surface endpoints (``POST /live/runner/start|stop``).
+* ``live status`` surfaces runner liveness + last-tick from the liveness
+ contract (``src.live.runtime.liveness``), degrading cleanly when the runtime
+ module is not yet present.
+* The slash registry / ``/help`` / typeahead completer now include
+ ``live`` / ``halt`` / ``resume`` (previously undiscoverable surface actions),
+ and ``/stop`` resolves as the kill-switch alias of ``/halt``.
+* The REPL intercepts ``/resume`` (clear halt) and ``/live ...`` (bridge to the
+ live subcommand group) in the input path — neither is dispatched to the model.
+
+The API client is stubbed (``httpx``) and the liveness module is injected into
+``sys.modules`` so no server / concurrent runtime parcel is needed.
+"""
+
+from __future__ import annotations
+
+import importlib
+import sys
+import types
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any, Dict, List
+from unittest.mock import patch
+
+import pytest
+
+import src.live.paths as live_paths
+
+# ``cli/__init__.py`` re-exports ``main`` as a function, shadowing the submodule
+# for attribute access; import the module object directly (mirrors test_cli_live).
+main = importlib.import_module("cli.main")
+InteractiveContext = main.InteractiveContext
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def live_root(tmp_path: Path):
+ """Redirect the live-channel runtime root to a tmp dir for the test."""
+ with patch.object(live_paths, "get_runtime_root", return_value=tmp_path):
+ yield tmp_path
+
+
+def fake_liveness():
+ """Inject a stub ``src.live.runtime.liveness`` module (R1 lands concurrently).
+
+ Yields a dict the test can mutate to control ``is_runner_alive`` /
+ ``last_tick`` return values. The real module is restored on teardown.
+ """
+ state: Dict[str, Any] = {"alive": True, "tick": datetime.now(timezone.utc)}
+ mod = types.ModuleType("src.live.runtime.liveness")
+ mod.is_runner_alive = lambda runner_id: bool(state["alive"]) # type: ignore[attr-defined]
+ mod.last_tick = lambda runner_id: state["tick"] # type: ignore[attr-defined]
+
+ saved = sys.modules.get("src.live.runtime.liveness")
+ sys.modules["src.live.runtime.liveness"] = mod
+ try:
+ yield state
+ finally:
+ if saved is not None:
+ sys.modules["src.live.runtime.liveness"] = saved
+ else:
+ sys.modules.pop("src.live.runtime.liveness", None)
+
+
+def no_liveness():
+ """Force ``src.live.runtime.liveness`` import to fail (module absent)."""
+ saved = sys.modules.get("src.live.runtime.liveness")
+ sys.modules["src.live.runtime.liveness"] = None # type: ignore[assignment]
+ try:
+ yield
+ finally:
+ if saved is not None:
+ sys.modules["src.live.runtime.liveness"] = saved
+ else:
+ sys.modules.pop("src.live.runtime.liveness", None)
+
+
+class _FakeResp:
+ def __init__(self, payload: Dict[str, Any]) -> None:
+ self._payload = payload
+
+ def raise_for_status(self) -> None:
+ return None
+
+ def json(self) -> Dict[str, Any]:
+ return self._payload
+
+
+# ---------------------------------------------------------------------------
+# Subcommand dispatch (run / start / stop) — argparse + _dispatch_live
+# ---------------------------------------------------------------------------
+
+
+class TestRunnerDispatch:
+ def _dispatch(self, argv: List[str]) -> int:
+ from cli._legacy import _build_parser, _dispatch_live
+
+ args = _build_parser().parse_args(argv)
+ return _dispatch_live(args)
+
+ def test_run_routes_to_handler(self) -> None:
+ with patch("cli._legacy.cmd_live_run", return_value=0) as m:
+ assert self._dispatch(["live", "run", "robinhood"]) == 0
+ m.assert_called_once_with("robinhood")
+
+ def test_run_default_broker_none(self) -> None:
+ with patch("cli._legacy.cmd_live_run", return_value=0) as m:
+ self._dispatch(["live", "run"])
+ m.assert_called_once_with(None)
+
+ def test_start_routes_to_handler(self) -> None:
+ with patch("cli._legacy.cmd_live_start", return_value=0) as m:
+ self._dispatch(["live", "start", "robinhood"])
+ m.assert_called_once_with("robinhood")
+
+ def test_stop_routes_to_handler(self) -> None:
+ with patch("cli._legacy.cmd_live_stop", return_value=0) as m:
+ self._dispatch(["live", "stop"])
+ m.assert_called_once_with(None)
+
+ def test_subparsers_registered(self) -> None:
+ """run/start/stop parse without error (the parser knows them)."""
+ from cli._legacy import _build_parser
+
+ parser = _build_parser()
+ for verb in ("run", "start", "stop"):
+ parsed = parser.parse_args(["live", verb])
+ assert parsed.live_command == verb
+
+
+# ---------------------------------------------------------------------------
+# Runner control relays to the R6 surface endpoints
+# ---------------------------------------------------------------------------
+
+
+class TestRunnerControlEndpoints:
+ def test_start_posts_to_runner_start(self) -> None:
+ from cli._legacy import EXIT_SUCCESS, cmd_live_start
+
+ captured: Dict[str, Any] = {}
+
+ def _post(url: str, json: Dict[str, Any], timeout: float) -> _FakeResp: # noqa: A002
+ captured["url"] = url
+ captured["body"] = json
+ return _FakeResp({"runner_id": "live-robinhood", "status": "started"})
+
+ with patch("httpx.post", _post):
+ assert cmd_live_start("robinhood") == EXIT_SUCCESS
+ assert captured["url"].endswith("/live/runner/start")
+ assert captured["body"]["broker"] == "robinhood"
+ assert captured["body"]["foreground"] is False
+
+ def test_stop_posts_to_runner_stop(self) -> None:
+ from cli._legacy import EXIT_SUCCESS, cmd_live_stop
+
+ captured: Dict[str, Any] = {}
+
+ def _post(url: str, json: Dict[str, Any], timeout: float) -> _FakeResp: # noqa: A002
+ captured["url"] = url
+ captured["body"] = json
+ return _FakeResp({"status": "stopped"})
+
+ with patch("httpx.post", _post):
+ assert cmd_live_stop("robinhood") == EXIT_SUCCESS
+ assert captured["url"].endswith("/live/runner/stop")
+ assert captured["body"]["broker"] == "robinhood"
+
+ def test_start_server_unreachable_is_run_failed(self) -> None:
+ from cli._legacy import EXIT_RUN_FAILED, cmd_live_start
+
+ def _boom(url: str, json: Dict[str, Any], timeout: float) -> _FakeResp: # noqa: A002
+ raise OSError("connection refused")
+
+ with patch("httpx.post", _boom):
+ assert cmd_live_start("robinhood") == EXIT_RUN_FAILED
+
+ def test_run_foreground_starts_then_stops(self, fake_liveness: Dict[str, Any]) -> None:
+ """`live run` relays a foreground start, tails liveness, then stops."""
+ from cli._legacy import EXIT_SUCCESS, cmd_live_run
+
+ calls: List[str] = []
+
+ def _post(url: str, json: Dict[str, Any], timeout: float) -> _FakeResp: # noqa: A002
+ calls.append(url)
+ if url.endswith("/live/runner/start"):
+ assert json["foreground"] is True
+ # Make the tail loop exit immediately: runner reports stopped.
+ fake_liveness["alive"] = False
+ return _FakeResp({"runner_id": "live-robinhood", "status": "ok"})
+
+ import cli._legacy as legacy
+
+ # _legacy uses its own ``time`` import; patch that one so the tail loop
+ # does not actually sleep.
+ with patch("httpx.post", _post), patch.object(legacy.time, "sleep", lambda *_: None):
+ assert cmd_live_run("robinhood") == EXIT_SUCCESS
+
+ assert any(u.endswith("/live/runner/start") for u in calls)
+ assert any(u.endswith("/live/runner/stop") for u in calls)
+
+
+# ---------------------------------------------------------------------------
+# live status surfaces runner liveness
+# ---------------------------------------------------------------------------
+
+
+class TestStatusLiveness:
+ def test_status_shows_running(
+ self, live_root: Path, fake_liveness: Dict[str, Any], capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ from cli._legacy import cmd_live_status
+
+ fake_liveness["alive"] = True
+ fake_liveness["tick"] = datetime.now(timezone.utc) - timedelta(seconds=5)
+ assert cmd_live_status("robinhood") == 0
+ out = capsys.readouterr().out
+ assert "Runner" in out
+ assert "running" in out
+ assert "ago" in out # last-tick relative time rendered
+
+ def test_status_shows_stopped(
+ self, live_root: Path, fake_liveness: Dict[str, Any], capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ from cli._legacy import cmd_live_status
+
+ fake_liveness["alive"] = False
+ cmd_live_status("robinhood")
+ out = capsys.readouterr().out
+ assert "stopped" in out
+
+ def test_status_degrades_when_liveness_absent(
+ self, live_root: Path, no_liveness: None, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ """Status must not crash if the runtime parcel hasn't landed yet."""
+ from cli._legacy import cmd_live_status
+
+ assert cmd_live_status("robinhood") == 0
+ out = capsys.readouterr().out
+ assert "Runner" in out
+ assert "unknown" in out
+
+
+# ---------------------------------------------------------------------------
+# Discoverability: registry + help + completer now include live/halt/resume
+# ---------------------------------------------------------------------------
+
+
+class TestSlashDiscoverability:
+ def test_registry_includes_live_group(self) -> None:
+ from cli.commands.slash_router import SLASH_COMMANDS
+
+ names = {c.name for c in SLASH_COMMANDS}
+ assert {"live", "halt", "resume"} <= names
+
+ def test_find_exact_resolves_new_commands(self) -> None:
+ from cli.commands.slash_router import find_exact
+
+ for name in ("live", "halt", "resume"):
+ assert find_exact(name) is not None
+
+ def test_stop_is_alias_of_halt(self) -> None:
+ from cli.commands.slash_router import find_exact
+
+ cmd = find_exact("stop")
+ assert cmd is not None
+ assert cmd.name == "halt"
+
+ def test_match_commands_surfaces_in_typeahead(self) -> None:
+ """The completer ranks via match_commands — the live group must appear."""
+ from cli.commands.slash_router import match_commands
+
+ names = {c.name for c in match_commands("/ha")}
+ assert "halt" in names
+ names = {c.name for c in match_commands("/li")}
+ assert "live" in names
+
+ def test_completer_yields_live_group(self) -> None:
+ from prompt_toolkit.document import Document
+
+ from cli.completer import SlashCompleter
+
+ comp = SlashCompleter()
+ completions = list(
+ comp.get_completions(Document("/", cursor_position=1), complete_event=None)
+ )
+ texts = {c.text for c in completions}
+ assert {"live", "halt", "resume"} <= texts
+
+ def test_help_lists_live_group(self, capsys: pytest.CaptureFixture[str]) -> None:
+ """``/help`` renders the registry — the live group must be present."""
+ from cli.commands import help as help_cmd
+
+ # help.py binds SLASH_COMMANDS at import; our registration runs at
+ # cli.main import (already done above) so the bound tuple includes them.
+ assert {"live", "halt", "resume"} <= {c.name for c in help_cmd.SLASH_COMMANDS}
+ help_cmd.run(None)
+ out = capsys.readouterr().out
+ assert "/live" in out
+ assert "/halt" in out
+ assert "/resume" in out
+
+ def test_registration_is_idempotent(self) -> None:
+ from cli.commands.slash_router import SLASH_COMMANDS
+
+ before = len(SLASH_COMMANDS)
+ main._register_live_slash_commands()
+ from cli.commands.slash_router import SLASH_COMMANDS as after_tuple
+
+ assert len(after_tuple) == before # no duplicate rows
+
+
+# ---------------------------------------------------------------------------
+# REPL intercepts: /resume clears halt, /live bridges to the subcommand group
+# ---------------------------------------------------------------------------
+
+
+class TestReplResumeIntercept:
+ def test_resume_clears_halt(self, live_root: Path) -> None:
+ from src.live.halt import halt_flag_set, trip_halt
+
+ trip_halt(by="cli", reason="test")
+ assert halt_flag_set("robinhood") is True
+
+ console = main.get_console()
+ main._clear_halt_from_repl(console)
+ assert halt_flag_set("robinhood") is False
+
+ def test_resume_when_not_halted_is_clean(
+ self, live_root: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ console = main.get_console()
+ main._clear_halt_from_repl(console) # must not raise
+ assert "No active global halt" in capsys.readouterr().out
+
+
+class TestReplLiveBridge:
+ def test_live_bridges_to_dispatch_live(self) -> None:
+ console = main.get_console()
+ with patch("cli._legacy._dispatch_live", return_value=0) as disp:
+ main._run_live_command_from_repl(console, ["status", "robinhood"])
+ disp.assert_called_once()
+ parsed = disp.call_args.args[0]
+ assert parsed.live_command == "status"
+ assert parsed.live_broker == "robinhood"
+
+ def test_bare_live_defaults_to_status(self) -> None:
+ console = main.get_console()
+ with patch("cli._legacy._dispatch_live", return_value=0) as disp:
+ main._run_live_command_from_repl(console, [])
+ parsed = disp.call_args.args[0]
+ assert parsed.live_command == "status"
+
+ def test_live_run_bridges_to_run_handler(self) -> None:
+ console = main.get_console()
+ with patch("cli._legacy.cmd_live_run", return_value=0) as run:
+ main._run_live_command_from_repl(console, ["run"])
+ run.assert_called_once_with(None)
+
+ def test_invalid_live_subcommand_keeps_loop_alive(
+ self, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ console = main.get_console()
+ # Unknown subcommand → argparse SystemExit, caught, usage printed.
+ main._run_live_command_from_repl(console, ["frobnicate"])
+ assert "Usage: /live" in capsys.readouterr().out
diff --git a/agent/tests/test_consent_commit.py b/agent/tests/test_consent_commit.py
new file mode 100644
index 000000000..fdebdcdd7
--- /dev/null
+++ b/agent/tests/test_consent_commit.py
@@ -0,0 +1,505 @@
+"""Consent backend: propose -> select -> commit state machine + invariants.
+
+Covers (docs/live-trading/SPEC.md Consent §1/§3, Mandate §2):
+
+* PROPOSE -> SELECT -> COMMIT happy path, then the mandate loads back.
+* commit-is-the-only-write: an AST + registry scan proves no agent tool / tool
+ registry path reaches ``commit_mandate`` (the 命门 invariant).
+* Adjust round-trip (narrowing) and reauth-seeded proposal round-trip.
+* Commit rejected without ``consent_ack=true`` and once a proposal is consumed.
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+import src.live.paths as paths
+from src.live.mandate.commit import (
+ CommitError,
+ DEFAULT_MANDATE_LIFETIME_DAYS,
+ commit_mandate,
+ save_proposal,
+)
+from src.live.mandate.store import load_mandate
+from src.tools.propose_mandate_tool import ProposeMandateProfilesTool
+
+pytestmark = pytest.mark.unit
+
+AGENT_DIR = Path(__file__).resolve().parent.parent
+
+
+def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Point the live root at a tmp dir so tests never touch the real store."""
+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)
+ return tmp_path
+
+
+_CEILINGS = {
+ "account_funding_usd": 5000.0,
+ "max_order_usd": 1500.0,
+ "max_total_exposure_usd": 5000.0,
+ "daily_trade_cap": 10,
+ "leverage": "none",
+ "instruments": ["equity"],
+ "universe": ["AAPL", "MSFT", "NVDA", "GOOGL"],
+}
+
+
+def _propose(broker: str = "robinhood", reauth_for=None) -> dict:
+ """Run the propose tool and return the parsed proposal payload."""
+ tool = ProposeMandateProfilesTool()
+ raw = tool.execute(
+ broker=broker,
+ intent="aggressive tech, ~$5000",
+ ceilings=dict(_CEILINGS),
+ session_id="sess_1",
+ reauth_for=reauth_for,
+ )
+ payload = json.loads(raw)
+ assert payload.get("type") == "mandate.proposal", payload
+ return payload
+
+
+# ---------------------------------------------------------------------------
+# PROPOSE
+# ---------------------------------------------------------------------------
+
+
+def test_propose_is_readonly_and_clamps_to_ceilings(live_runtime: Path) -> None:
+ """The tool is read-only and every profile clamps to the ceiling."""
+ assert ProposeMandateProfilesTool.is_readonly is True
+ proposal = _propose()
+
+ assert 2 <= len(proposal["profiles"]) <= 4
+ for profile in proposal["profiles"]:
+ assert profile["max_order_usd"] <= _CEILINGS["max_order_usd"]
+ assert profile["daily_trade_cap"] <= _CEILINGS["daily_trade_cap"]
+ # Cash-only ceiling => no profile may request leverage.
+ assert profile["leverage"] == "none"
+ assert "funding_note" in proposal and "halt_note" in proposal
+ assert proposal["account"]["type"] == "cash"
+
+
+def test_propose_persists_for_commit(live_runtime: Path) -> None:
+ """A proposal is persisted under the broker's proposals dir (not a mandate)."""
+ proposal = _propose()
+ proposals_dir = paths.broker_dir("robinhood") / "proposals"
+ saved = proposals_dir / f"{proposal['proposal_id']}.json"
+ assert saved.is_file()
+ # Persisting a proposal must NOT have written a mandate.
+ assert load_mandate("robinhood") is None
+
+
+# ---------------------------------------------------------------------------
+# COMMIT happy path
+# ---------------------------------------------------------------------------
+
+
+def test_propose_select_commit_activates_mandate(live_runtime: Path) -> None:
+ """End-to-end: propose -> pick ordinal 2 -> commit -> mandate loads back."""
+ proposal = _propose()
+ result = commit_mandate(
+ proposal_id=proposal["proposal_id"],
+ ordinal=2,
+ adjustments=None,
+ consent_ack=True,
+ broker="robinhood",
+ account_ref="rh_acct_opaque",
+ session_id="sess_1",
+ )
+ assert result["mandate_id"].startswith("mandate_")
+ assert result["consent_record_id"].startswith("cr_")
+ assert result["broker"] == "robinhood"
+
+ mandate = load_mandate("robinhood")
+ assert mandate is not None
+ picked = next(p for p in proposal["profiles"] if p["ordinal"] == 2)
+ assert mandate.hard_caps.max_order_notional_usd == picked["max_order_usd"]
+ assert mandate.hard_caps.max_trades_per_day == picked["daily_trade_cap"]
+ assert mandate.consent.account_ref == "rh_acct_opaque"
+ # 30-day default lifetime.
+ created = datetime.fromisoformat(mandate.consent.created_at.replace("Z", "+00:00"))
+ expires = datetime.fromisoformat(mandate.consent.expires_at.replace("Z", "+00:00"))
+ assert (expires - created).days == DEFAULT_MANDATE_LIFETIME_DAYS
+
+ # A consent record was written before the mandate could be used.
+ consent_dir = paths.broker_dir("robinhood") / "consent"
+ records = list(consent_dir.glob("*.json"))
+ assert len(records) == 1
+ record = json.loads(records[0].read_text(encoding="utf-8"))
+ assert record["proposal_id"] == proposal["proposal_id"]
+ assert record["selected_ordinal"] == 2
+ assert record["consent_ack"] is True
+
+
+def test_commit_consumes_proposal_no_replay(live_runtime: Path) -> None:
+ """A committed proposal is invalidated and cannot be committed again."""
+ proposal = _propose()
+ commit_mandate(
+ proposal_id=proposal["proposal_id"],
+ ordinal=1,
+ adjustments=None,
+ consent_ack=True,
+ broker="robinhood",
+ )
+ with pytest.raises(CommitError, match="not live"):
+ commit_mandate(
+ proposal_id=proposal["proposal_id"],
+ ordinal=1,
+ adjustments=None,
+ consent_ack=True,
+ broker="robinhood",
+ )
+
+
+# ---------------------------------------------------------------------------
+# consent_ack gate
+# ---------------------------------------------------------------------------
+
+
[email protected]("ack", [False, None, 0, "", "true"])
+def test_commit_rejected_without_consent_ack(live_runtime: Path, ack) -> None:
+ """Only a strict boolean True authorizes a commit (no truthy coercion)."""
+ proposal = _propose()
+ with pytest.raises(CommitError, match="consent_ack"):
+ commit_mandate(
+ proposal_id=proposal["proposal_id"],
+ ordinal=1,
+ adjustments=None,
+ consent_ack=ack, # type: ignore[arg-type]
+ broker="robinhood",
+ )
+ # Failed commit wrote no mandate (fail-closed) and left the proposal live.
+ assert load_mandate("robinhood") is None
+ assert (paths.broker_dir("robinhood") / "proposals" / f"{proposal['proposal_id']}.json").is_file()
+
+
+# ---------------------------------------------------------------------------
+# ADJUST + REAUTH
+# ---------------------------------------------------------------------------
+
+
+def test_adjust_narrowing_round_trip(live_runtime: Path) -> None:
+ """Adjust narrows a limit; the narrowed value is what gets committed."""
+ proposal = _propose()
+ picked = next(p for p in proposal["profiles"] if p["ordinal"] == 3)
+ narrower_daily = max(1, picked["daily_trade_cap"] - 1)
+ commit_mandate(
+ proposal_id=proposal["proposal_id"],
+ ordinal=3,
+ adjustments={"daily_trade_cap": narrower_daily},
+ consent_ack=True,
+ broker="robinhood",
+ )
+ mandate = load_mandate("robinhood")
+ assert mandate is not None
+ assert mandate.hard_caps.max_trades_per_day == narrower_daily
+
+
+def test_adjust_widening_rejected(live_runtime: Path) -> None:
+ """An adjustment that widens a rendered limit is rejected (must re-propose)."""
+ proposal = _propose()
+ picked = next(p for p in proposal["profiles"] if p["ordinal"] == 1)
+ with pytest.raises(CommitError, match="widen"):
+ commit_mandate(
+ proposal_id=proposal["proposal_id"],
+ ordinal=1,
+ adjustments={"daily_trade_cap": picked["daily_trade_cap"] + 99},
+ consent_ack=True,
+ broker="robinhood",
+ )
+
+
+def test_reauth_seeded_proposal_round_trip(live_runtime: Path) -> None:
+ """A breach-seeded proposal carries reauth_for and still clamps to ceiling."""
+ proposal = _propose(
+ reauth_for={"breach_id": "be_1", "limit": "max_order_notional_usd", "attempted_value": 1200.0}
+ )
+ assert proposal["reauth_for"]["breach_id"] == "be_1"
+ for profile in proposal["profiles"]:
+ assert profile["max_order_usd"] <= _CEILINGS["max_order_usd"]
+
+ # The widened proposal commits exactly like any other proposal.
+ result = commit_mandate(
+ proposal_id=proposal["proposal_id"],
+ ordinal=3,
+ adjustments=None,
+ consent_ack=True,
+ broker="robinhood",
+ )
+ assert result["mandate_id"]
+ assert load_mandate("robinhood") is not None
+
+
+# ---------------------------------------------------------------------------
+# H9: commit-time ceiling re-check is alias-robust (no silent NO-OP)
+# ---------------------------------------------------------------------------
+
+
+def _save_handcrafted_proposal(
+ broker: str,
+ profile: dict,
+ ceilings: dict,
+) -> str:
+ """Persist a proposal with an arbitrary single profile + ceiling snapshot.
+
+ Lets a test exercise commit-time validation against a profile the clamping
+ proposer would never emit (e.g. one that breaches an alias-keyed ceiling).
+ """
+ proposal_id = "mp_handcrafted_h9"
+ save_proposal(
+ {
+ "type": "mandate.proposal",
+ "proposal_id": proposal_id,
+ "account": {"broker": broker, "type": "cash", "funded_by": "user"},
+ "ceilings_ref": "caps_h9",
+ "ceilings": ceilings,
+ "profiles": [profile],
+ }
+ )
+ return proposal_id
+
+
+def test_commit_rejects_profile_over_alias_keyed_order_ceiling(live_runtime: Path) -> None:
+ """H9: an order notional over an ALIAS-keyed ceiling is rejected at commit.
+
+ The profile stores the limit as ``max_order_usd`` while the ceiling snapshot
+ keys it ``max_order_notional_usd`` (the schema spelling). Before the fix the
+ re-check only compared identically-named keys, so it never saw this field and
+ the over-ceiling profile committed silently. After normalization both sides
+ map to the canonical name and the breach is caught.
+ """
+ profile = {
+ "ordinal": 1,
+ "label": "rogue",
+ "max_order_usd": 999_999.0, # human/profile spelling
+ "max_total_exposure_usd": 5000.0,
+ "daily_trade_cap": 2,
+ "leverage": "none",
+ "instruments": ["equity"],
+ }
+ ceilings = {
+ "account_funding_usd": 5000.0,
+ "max_order_notional_usd": 100.0, # schema/alias spelling, far below profile
+ "max_total_exposure_usd": 5000.0,
+ "max_trades_per_day": 10,
+ "leverage": "none",
+ "allowed_instruments": ["equity"],
+ }
+ proposal_id = _save_handcrafted_proposal("robinhood", profile, ceilings)
+
+ with pytest.raises(CommitError, match="exceeds the account ceilings"):
+ commit_mandate(
+ proposal_id=proposal_id,
+ ordinal=1,
+ adjustments=None,
+ consent_ack=True,
+ broker="robinhood",
+ )
+ # Fail-closed: no mandate written.
+ assert load_mandate("robinhood") is None
+
+
+def test_commit_rejects_profile_over_alias_keyed_daily_cap(live_runtime: Path) -> None:
+ """H9 (daily cap): profile ``daily_trade_cap`` over ceiling ``max_trades_per_day``."""
+ profile = {
+ "ordinal": 1,
+ "label": "rogue",
+ "max_order_usd": 50.0,
+ "max_total_exposure_usd": 5000.0,
+ "daily_trade_cap": 500, # human spelling, way over
+ "leverage": "none",
+ "instruments": ["equity"],
+ }
+ ceilings = {
+ "account_funding_usd": 5000.0,
+ "max_order_notional_usd": 5000.0,
+ "max_total_exposure_usd": 5000.0,
+ "max_trades_per_day": 3, # schema spelling
+ "leverage": "none",
+ "allowed_instruments": ["equity"],
+ }
+ proposal_id = _save_handcrafted_proposal("robinhood", profile, ceilings)
+
+ with pytest.raises(CommitError, match="exceeds the account ceilings"):
+ commit_mandate(
+ proposal_id=proposal_id,
+ ordinal=1,
+ adjustments=None,
+ consent_ack=True,
+ broker="robinhood",
+ )
+ assert load_mandate("robinhood") is None
+
+
+def test_commit_accepts_within_alias_keyed_ceiling(live_runtime: Path) -> None:
+ """A profile that fits an alias-keyed ceiling still commits (no over-rejection)."""
+ profile = {
+ "ordinal": 1,
+ "label": "fits",
+ "max_order_usd": 90.0,
+ "max_total_exposure_usd": 5000.0,
+ "daily_trade_cap": 2,
+ "leverage": "none",
+ "instruments": ["equity"],
+ }
+ ceilings = {
+ "account_funding_usd": 5000.0,
+ "max_order_notional_usd": 100.0,
+ "max_total_exposure_usd": 5000.0,
+ "max_trades_per_day": 10,
+ "leverage": "none",
+ "allowed_instruments": ["equity"],
+ }
+ proposal_id = _save_handcrafted_proposal("robinhood", profile, ceilings)
+ result = commit_mandate(
+ proposal_id=proposal_id,
+ ordinal=1,
+ adjustments=None,
+ consent_ack=True,
+ broker="robinhood",
+ )
+ assert result["mandate_id"]
+ assert load_mandate("robinhood") is not None
+
+
+# ---------------------------------------------------------------------------
+# M3: per-mandate flatten_on_halt flag is proposed + persisted on commit
+# ---------------------------------------------------------------------------
+
+
+def test_propose_defaults_flatten_on_halt_false(live_runtime: Path) -> None:
+ """Every proposed profile carries flatten_on_halt=False by default (cancel-only)."""
+ proposal = _propose()
+ for profile in proposal["profiles"]:
+ assert profile["flatten_on_halt"] is False
+
+
+def test_propose_opt_in_flatten_on_halt_stamps_profiles(live_runtime: Path) -> None:
+ """An explicit opt-in stamps flatten_on_halt=True onto every profile."""
+ tool = ProposeMandateProfilesTool()
+ payload = json.loads(
+ tool.execute(
+ broker="robinhood",
+ ceilings=dict(_CEILINGS),
+ flatten_on_halt=True,
+ )
+ )
+ for profile in payload["profiles"]:
+ assert profile["flatten_on_halt"] is True
+
+
+def test_commit_persists_flatten_on_halt_from_profile(live_runtime: Path) -> None:
+ """An opted-in proposal commits a mandate.json carrying flatten_on_halt=True."""
+ tool = ProposeMandateProfilesTool()
+ payload = json.loads(
+ tool.execute(broker="robinhood", ceilings=dict(_CEILINGS), flatten_on_halt=True)
+ )
+ commit_mandate(
+ proposal_id=payload["proposal_id"],
+ ordinal=2,
+ adjustments=None,
+ consent_ack=True,
+ broker="robinhood",
+ )
+ doc = json.loads((paths.broker_dir("robinhood") / "mandate.json").read_text(encoding="utf-8"))
+ assert doc["flatten_on_halt"] is True
+ # And the consent record records the same decision for audit.
+ record_path = next((paths.broker_dir("robinhood") / "consent").glob("*.json"))
+ record = json.loads(record_path.read_text(encoding="utf-8"))
+ assert record["flatten_on_halt"] is True
+
+
+def test_commit_defaults_flatten_on_halt_false_for_cancel_only(live_runtime: Path) -> None:
+ """A plain proposal (no opt-in) commits flatten_on_halt=False (cancel-only)."""
+ proposal = _propose()
+ commit_mandate(
+ proposal_id=proposal["proposal_id"],
+ ordinal=1,
+ adjustments=None,
+ consent_ack=True,
+ broker="robinhood",
+ )
+ doc = json.loads((paths.broker_dir("robinhood") / "mandate.json").read_text(encoding="utf-8"))
+ assert doc["flatten_on_halt"] is False
+
+
+def test_commit_explicit_flatten_param_overrides_profile(live_runtime: Path) -> None:
+ """An explicit flatten_on_halt param overrides the selected profile's flag."""
+ proposal = _propose() # profiles default flatten_on_halt=False
+ commit_mandate(
+ proposal_id=proposal["proposal_id"],
+ ordinal=1,
+ adjustments=None,
+ consent_ack=True,
+ broker="robinhood",
+ flatten_on_halt=True,
+ )
+ doc = json.loads((paths.broker_dir("robinhood") / "mandate.json").read_text(encoding="utf-8"))
+ assert doc["flatten_on_halt"] is True
+
+
+# ---------------------------------------------------------------------------
+# 命门 INVARIANT: commit is unreachable from the agent loop / tool registry
+# ---------------------------------------------------------------------------
+
+
+def test_propose_tool_is_a_basetool_but_commit_is_not() -> None:
+ """The proposer is a registerable tool; the committer is a plain function."""
+ from src.agent.tools import BaseTool
+ import src.live.mandate.commit as commit_mod
+
+ assert issubclass(ProposeMandateProfilesTool, BaseTool)
+ # No BaseTool subclass lives in the commit module — it can never be
+ # auto-discovered by the registry.
+ for value in vars(commit_mod).values():
+ if isinstance(value, type) and issubclass(value, BaseTool):
+ pytest.fail(f"{value!r} in commit.py is a BaseTool — commit must not be a tool")
+
+
+def test_no_registered_tool_references_commit_mandate() -> None:
+ """Build the real registry; assert no tool module imports commit_mandate.
+
+ The mandate writer must be structurally unreachable from anything the agent
+ loop can call. We AST-scan every tool source file (plus the loop/worker) for
+ an import of or call to ``commit_mandate`` / ``save_proposal``-as-mandate.
+ Importing ``save_proposal`` is allowed (a proposal grants no authority); a
+ reference to ``commit_mandate`` from a tool/loop module is a hard failure.
+ """
+ suspect_files = list((AGENT_DIR / "src" / "tools").glob("*.py"))
+ suspect_files += [
+ AGENT_DIR / "src" / "agent" / "loop.py",
+ AGENT_DIR / "src" / "swarm" / "worker.py",
+ ]
+ offenders: list[str] = []
+ for path in suspect_files:
+ if not path.is_file():
+ continue
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom) and (node.module or "").endswith("mandate.commit"):
+ names = {alias.name for alias in node.names}
+ if "commit_mandate" in names or "CommitError" in names:
+ offenders.append(f"{path.name} imports commit_mandate")
+ if isinstance(node, ast.Name) and node.id == "commit_mandate":
+ offenders.append(f"{path.name} references commit_mandate")
+ if isinstance(node, ast.Attribute) and node.attr == "commit_mandate":
+ offenders.append(f"{path.name} references .commit_mandate")
+ assert not offenders, f"commit_mandate is reachable from the agent surface: {offenders}"
+
+
+def test_registry_has_propose_tool_but_no_mandate_writer() -> None:
+ """The assembled registry exposes propose_mandate_profiles, no commit tool."""
+ from src.tools import build_registry
+
+ registry = build_registry()
+ names = set(registry.tool_names)
+ assert "propose_mandate_profiles" in names
+ for forbidden in ("commit_mandate", "set_mandate", "write_mandate", "authorize_live"):
+ assert forbidden not in names, f"{forbidden} must not be a registered tool"
diff --git a/agent/tests/test_default_deny_unknown_robinhood_tool.py b/agent/tests/test_default_deny_unknown_robinhood_tool.py
new file mode 100644
index 000000000..1cfe1d06d
--- /dev/null
+++ b/agent/tests/test_default_deny_unknown_robinhood_tool.py
@@ -0,0 +1,164 @@
+"""Default-deny / fail-closed classification gate (SPEC §7.3 threat (d), §7.4).
+
+Stands up a MOCK MCP server (reusing the ``client_factory`` seam in
+``src.tools.mcp``) exposing the four classification-critical shapes:
+
+* a genuine READ tool in the curated map,
+* a genuine WRITE tool in the curated map,
+* an UNKNOWN tool — absent from the curated map AND with ``annotations=None``,
+* a DECEPTIVE tool — ``readOnlyHint=True`` but pinned WRITE by the curated map.
+
+Asserts the live-channel wrapping that the registry assembles:
+
+* UNKNOWN+unannotated -> classified WRITE/UNKNOWN, wrapped by LiveOrderGuardTool
+ (default-deny: an unrecognized broker tool is never a plain read tool).
+* DECEPTIVE-read -> stays WRITE (curated map wins over the annotation).
+* genuine READ -> plain ``MCPRemoteTool`` with ``is_readonly=True``.
+* genuine WRITE -> wrapped by LiveOrderGuardTool.
+
+No Robinhood access required — discovery runs entirely against the mock client.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from fastmcp.client.client import CallToolResult
+from mcp import types as mcp_types
+
+from src.live.classification import ToolClass, classify_tool
+from src.live.order_guard import LiveOrderGuardTool
+from src.live.registry import wrap_live_broker_tools
+from src.live.robinhood_classification import ROBINHOOD_TOOL_CLASS
+from src.tools.mcp import MCPRemoteTool, build_mcp_tool_wrappers
+
+pytestmark = pytest.mark.unit
+
+# Tool names exercising every tier of the ladder.
+_READ_TOOL = "get_positions" # curated READ
+_WRITE_TOOL = "place_order" # curated WRITE
+_UNKNOWN_TOOL = "place_bracket_order" # absent from map + annotations=None
+_DECEPTIVE_TOOL = "cancel_order" # curated WRITE but lies readOnlyHint=True
+
+assert _READ_TOOL in ROBINHOOD_TOOL_CLASS and ROBINHOOD_TOOL_CLASS[_READ_TOOL] is ToolClass.READ
+assert _WRITE_TOOL in ROBINHOOD_TOOL_CLASS and ROBINHOOD_TOOL_CLASS[_WRITE_TOOL] is ToolClass.WRITE
+assert _DECEPTIVE_TOOL in ROBINHOOD_TOOL_CLASS and ROBINHOOD_TOOL_CLASS[_DECEPTIVE_TOOL] is ToolClass.WRITE
+assert _UNKNOWN_TOOL not in ROBINHOOD_TOOL_CLASS
+
+
+class _MockMCPServer:
+ """Mock MCP client exposing the four classification shapes."""
+
+ async def __aenter__(self) -> "_MockMCPServer":
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb) -> None:
+ return None
+
+ async def list_tools(self) -> list[mcp_types.Tool]:
+ return [
+ # Genuine read — curated READ; annotation agrees but map decides.
+ mcp_types.Tool(
+ name=_READ_TOOL,
+ description="read positions",
+ inputSchema={"type": "object"},
+ annotations=mcp_types.ToolAnnotations(readOnlyHint=True),
+ ),
+ # Genuine write — curated WRITE; no annotation.
+ mcp_types.Tool(
+ name=_WRITE_TOOL,
+ description="place an order",
+ inputSchema={"type": "object"},
+ ),
+ # Unknown — absent from map AND annotations=None -> default-deny.
+ mcp_types.Tool(
+ name=_UNKNOWN_TOOL,
+ description="brand-new tool",
+ inputSchema={"type": "object"},
+ ),
+ # Deceptive — lies readOnlyHint=True but the map pins WRITE.
+ mcp_types.Tool(
+ name=_DECEPTIVE_TOOL,
+ description="cancel an order (claims read-only)",
+ inputSchema={"type": "object"},
+ annotations=mcp_types.ToolAnnotations(readOnlyHint=True),
+ ),
+ ]
+
+ async def call_tool(
+ self,
+ name: str,
+ arguments: dict[str, Any] | None = None,
+ *,
+ timeout: float | int | None = None,
+ raise_on_error: bool = False,
+ ) -> CallToolResult:
+ raise AssertionError("classification must not invoke remote tools")
+
+
+def _factory() -> _MockMCPServer:
+ return _MockMCPServer()
+
+
+def _make_config():
+ from src.config.schema import MCPServerConfig
+
+ return MCPServerConfig.model_validate(
+ {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "auth": {"type": "oauth", "scopes": ["trading.read"]},
+ "enabled_tools": [_READ_TOOL, _WRITE_TOOL, _UNKNOWN_TOOL, _DECEPTIVE_TOOL],
+ }
+ )
+
+
+def _wrapped_by_name() -> dict[str, MCPRemoteTool]:
+ wrappers = build_mcp_tool_wrappers("robinhood", _make_config(), client_factory=_factory)
+ gated = wrap_live_broker_tools("robinhood", wrappers, url="https://agent.robinhood.com/mcp/trading")
+ return {t._spec.remote_name: t for t in gated}
+
+
+# --- Classification ladder (unit, directly on the mock annotations) ----------
+
+
+def test_unknown_unannotated_classifies_unknown() -> None:
+ cls = classify_tool(_UNKNOWN_TOOL, None, ROBINHOOD_TOOL_CLASS)
+ assert cls is ToolClass.UNKNOWN
+
+
+def test_deceptive_readonly_hint_stays_write_map_wins() -> None:
+ deceptive = mcp_types.ToolAnnotations(readOnlyHint=True)
+ cls = classify_tool(_DECEPTIVE_TOOL, deceptive, ROBINHOOD_TOOL_CLASS)
+ assert cls is ToolClass.WRITE
+
+
+# --- End-to-end via the mock-MCP discovery + live wrapping seam ---------------
+
+
+def test_unknown_tool_is_gate_wrapped() -> None:
+ by_name = _wrapped_by_name()
+ assert isinstance(by_name[_UNKNOWN_TOOL], LiveOrderGuardTool), (
+ "default-deny: an unknown+unannotated tool must be gate-wrapped, never plain read"
+ )
+
+
+def test_deceptive_read_tool_is_gate_wrapped() -> None:
+ by_name = _wrapped_by_name()
+ assert isinstance(by_name[_DECEPTIVE_TOOL], LiveOrderGuardTool), (
+ "deceptive readOnlyHint must not unguard a curated WRITE"
+ )
+
+
+def test_genuine_write_tool_is_gate_wrapped() -> None:
+ by_name = _wrapped_by_name()
+ assert isinstance(by_name[_WRITE_TOOL], LiveOrderGuardTool)
+
+
+def test_genuine_read_tool_is_plain_readonly() -> None:
+ by_name = _wrapped_by_name()
+ read = by_name[_READ_TOOL]
+ assert type(read) is MCPRemoteTool
+ assert read.is_readonly is True
+ assert not isinstance(read, LiveOrderGuardTool)
diff --git a/agent/tests/test_enforcement_l6.py b/agent/tests/test_enforcement_l6.py
new file mode 100644
index 000000000..57ffa84ab
--- /dev/null
+++ b/agent/tests/test_enforcement_l6.py
@@ -0,0 +1,269 @@
+"""L6 — real Robinhood catalog + quantity→quote pricing (SPEC.md §4, §7.5).
+
+Covers:
+
+* The frozen canonical Robinhood read/write catalog.
+* The extractor's finalized ``place_order`` field mapping (symbol/side/size,
+ unknown keys ignored, ambiguity → ``None``).
+* Quantity-only quote derivation: broker ``get_quotes`` preferred, data-loader
+ fallback, fail-closed DENY when no quote is obtainable. Never hits the network
+ (the loader path is stubbed).
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+import src.live.enforcement as enforcement
+import src.live.order_guard as order_guard
+import src.live.paths as paths
+from src.live.classification import ToolClass
+from src.live.extractors.robinhood import extract_order_intent
+from src.live.mandate.model import (
+ MANDATE_SCHEMA_VERSION,
+ AssetClass,
+ InstrumentType,
+)
+from src.live.robinhood_classification import ROBINHOOD_TOOL_CLASS
+from src.tools.mcp import MCPRemoteToolSpec
+
+
+# --------------------------------------------------------------------------- #
+# C1 / L6 — frozen canonical catalog #
+# --------------------------------------------------------------------------- #
+
+_CANONICAL_READ = {"get_account", "get_positions", "get_quotes", "list_orders"}
+_CANONICAL_WRITE = {"place_order", "cancel_order"}
+
+
+def test_catalog_is_exactly_the_canonical_set() -> None:
+ reads = {n for n, c in ROBINHOOD_TOOL_CLASS.items() if c is ToolClass.READ}
+ writes = {n for n, c in ROBINHOOD_TOOL_CLASS.items() if c is ToolClass.WRITE}
+ assert reads == _CANONICAL_READ
+ assert writes == _CANONICAL_WRITE
+ # No stale names beyond the frozen catalog.
+ assert set(ROBINHOOD_TOOL_CLASS) == _CANONICAL_READ | _CANONICAL_WRITE
+
+
+# --------------------------------------------------------------------------- #
+# L6 — extractor field mapping finalized + defensive #
+# --------------------------------------------------------------------------- #
+
+
+def test_extractor_maps_notional_order() -> None:
+ intent = extract_order_intent(
+ "place_order",
+ {"symbol": "aapl", "side": "buy", "instrument_type": "stock", "notional_usd": 250.0},
+ )
+ assert intent is not None
+ assert intent.symbol == "AAPL"
+ assert intent.side == "buy"
+ assert intent.notional_usd == 250.0
+ assert intent.quantity is None
+ assert intent.instrument_type is InstrumentType.EQUITY
+
+
+def test_extractor_maps_quantity_and_dollar_amount_alias() -> None:
+ intent = extract_order_intent(
+ "place_order",
+ {"ticker": "NVDA", "action": "sell", "type": "equity", "quantity": 3, "dollar_amount": 600},
+ )
+ assert intent is not None
+ assert intent.symbol == "NVDA"
+ assert intent.side == "sell"
+ assert intent.quantity == 3.0
+ # dollar_amount is accepted as a notional alias.
+ assert intent.notional_usd == 600.0
+
+
+def test_extractor_ignores_unknown_extra_keys() -> None:
+ intent = extract_order_intent(
+ "place_order",
+ {
+ "symbol": "MSFT", "side": "buy", "instrument_type": "equity",
+ "quantity": 1, "time_in_force": "gtc", "client_tag": "x", "extended_hours": True,
+ },
+ )
+ assert intent is not None
+ assert intent.symbol == "MSFT"
+ assert intent.quantity == 1.0
+
+
+def test_extractor_rejects_non_order_tool() -> None:
+ assert extract_order_intent("cancel_order", {"order_id": "x"}) is None
+ assert extract_order_intent("get_quotes", {"symbol": "AAPL"}) is None
+
+
+def test_extractor_rejects_missing_or_ambiguous_fields() -> None:
+ # Missing side.
+ assert extract_order_intent("place_order", {"symbol": "AAPL", "instrument_type": "equity", "notional_usd": 10}) is None
+ # Unknown instrument.
+ assert extract_order_intent("place_order", {"symbol": "AAPL", "side": "buy", "instrument_type": "warrant", "notional_usd": 10}) is None
+ # No size at all.
+ assert extract_order_intent("place_order", {"symbol": "AAPL", "side": "buy", "instrument_type": "equity"}) is None
+
+
+# --------------------------------------------------------------------------- #
+# L6 — quantity-only quote derivation through the gate #
+# --------------------------------------------------------------------------- #
+
+
+def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)
+ return tmp_path
+
+
+def _spec() -> MCPRemoteToolSpec:
+ return MCPRemoteToolSpec(
+ server_name="robinhood",
+ remote_name="place_order",
+ local_name="mcp_robinhood_place_order",
+ description="Place an order.",
+ parameters={"type": "object", "properties": {}, "additionalProperties": True},
+ )
+
+
+def _write_mandate(live_runtime: Path, *, max_order_notional_usd: float = 750.0) -> None:
+ broker = live_runtime / "live" / "robinhood"
+ broker.mkdir(parents=True, exist_ok=True)
+ created = datetime.now(timezone.utc)
+ payload = {
+ "schema_version": MANDATE_SCHEMA_VERSION,
+ "hard_caps": {
+ "account_funding_usd": 100000.0,
+ "max_order_notional_usd": max_order_notional_usd,
+ "max_total_exposure_usd": 1e9,
+ "max_leverage": 100.0,
+ "allowed_instruments": ["equity", "etf"],
+ "max_trades_per_day": 50,
+ },
+ "universe": {
+ "asset_classes": ["us_equity", "us_etf"],
+ "min_market_cap_usd": None,
+ "min_avg_daily_volume_usd": None,
+ "exclude_symbols": [],
+ },
+ "consent": {
+ "created_at": created.isoformat(),
+ "consent_token_sha256": "deadbeef",
+ "broker": "robinhood",
+ "account_ref": "acct_ref",
+ "expires_at": (created + timedelta(days=30)).isoformat(),
+ },
+ }
+ (broker / "mandate.json").write_text(json.dumps(payload), encoding="utf-8")
+
+
+class _BrokerQuoteAdapter:
+ """Adapter whose ``get_quotes`` returns a price; loader path is never needed."""
+
+ def __init__(self, *, price: float) -> None:
+ self.server_name = "robinhood"
+ self._price = price
+ self.order_calls: list[dict[str, Any]] = []
+ self.quote_calls = 0
+
+ def call_tool(self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:
+ if remote_name == "get_positions":
+ return {"positions": [], "status": "ok"}
+ if remote_name == "get_account":
+ return {"equity": 100000.0, "status": "ok"}
+ if remote_name == "get_quotes":
+ self.quote_calls += 1
+ return {"status": "ok", "results": [{"symbol": arguments.get("symbol"), "last_price": self._price}]}
+ self.order_calls.append({"remote": remote_name, "arguments": arguments})
+ return {"status": "ok", "order_id": "rh_q", "state": "accepted"}
+
+
+class _NoBrokerQuoteAdapter:
+ """Adapter whose ``get_quotes`` errors — forces the data-loader fallback."""
+
+ def __init__(self) -> None:
+ self.server_name = "robinhood"
+ self.order_calls: list[dict[str, Any]] = []
+
+ def call_tool(self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:
+ if remote_name == "get_positions":
+ return {"positions": [], "status": "ok"}
+ if remote_name == "get_account":
+ return {"equity": 100000.0, "status": "ok"}
+ if remote_name == "get_quotes":
+ return {"status": "error", "error": "quotes unavailable"}
+ self.order_calls.append({"remote": remote_name, "arguments": arguments})
+ return {"status": "ok", "order_id": "rh_q", "state": "accepted"}
+
+
+def _guard(adapter):
+ return order_guard.LiveOrderGuardTool(adapter, _spec(), broker="robinhood", session_id="s1")
+
+
+def test_quantity_only_uses_broker_quote_and_enforces_notional(live_runtime: Path) -> None:
+ _write_mandate(live_runtime, max_order_notional_usd=750.0)
+ adapter = _BrokerQuoteAdapter(price=100.0) # 10 * 100 = 1000 > 750
+ guard = _guard(adapter)
+ out = json.loads(
+ guard.execute(symbol="AAPL", side="buy", instrument_type="equity", quantity=10.0)
+ )
+ assert adapter.quote_calls == 1
+ assert out["status"] == "blocked"
+ assert out["breach"]["limit"] == "max_order_notional_usd"
+ assert out["breach"]["attempted_value"] == 1000.0
+ assert adapter.order_calls == []
+
+
+def test_quantity_only_in_mandate_forwards(live_runtime: Path) -> None:
+ _write_mandate(live_runtime, max_order_notional_usd=2000.0)
+ adapter = _BrokerQuoteAdapter(price=100.0) # 10 * 100 = 1000 <= 2000
+ guard = _guard(adapter)
+ out = json.loads(
+ guard.execute(symbol="AAPL", side="buy", instrument_type="equity", quantity=10.0)
+ )
+ assert out.get("status") == "ok"
+ assert len(adapter.order_calls) == 1
+
+
+def test_quantity_falls_back_to_data_loader(live_runtime: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """When the broker quote tool errors, the gate derives price from the data
+ loaders (stubbed — no network)."""
+ _write_mandate(live_runtime, max_order_notional_usd=750.0)
+ monkeypatch.setattr(order_guard, "last_price_usd", lambda sym, ac: 100.0)
+ adapter = _NoBrokerQuoteAdapter()
+ guard = _guard(adapter)
+ out = json.loads(
+ guard.execute(symbol="AAPL", side="buy", instrument_type="equity", quantity=10.0)
+ )
+ assert out["status"] == "blocked"
+ assert out["breach"]["limit"] == "max_order_notional_usd"
+ assert adapter.order_calls == []
+
+
+def test_quantity_no_quote_anywhere_denies_fail_closed(live_runtime: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Quantity order + broker quote errors + loader returns nothing → DENY,
+ never waved through."""
+ _write_mandate(live_runtime)
+ monkeypatch.setattr(order_guard, "last_price_usd", lambda sym, ac: None)
+ adapter = _NoBrokerQuoteAdapter()
+ guard = _guard(adapter)
+ out = json.loads(
+ guard.execute(symbol="AAPL", side="buy", instrument_type="equity", quantity=10.0)
+ )
+ assert out["status"] == "blocked"
+ assert out["decision"] == "deny"
+ assert "priced" in out["reason"].lower()
+ assert adapter.order_calls == []
+
+
+def test_last_price_usd_fail_closed_on_loader_unavailable(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The loader-backed price helper denies (returns None) when no loader is
+ available — never a network call in tests."""
+ def _raise(_ac):
+ raise enforcement.UniverseDataUnavailable("no loader")
+
+ monkeypatch.setattr(enforcement, "_resolve_loader", _raise)
+ assert enforcement.last_price_usd("AAPL", AssetClass.US_EQUITY) is None
diff --git a/agent/tests/test_halt.py b/agent/tests/test_halt.py
new file mode 100644
index 000000000..2f7e10897
--- /dev/null
+++ b/agent/tests/test_halt.py
@@ -0,0 +1,150 @@
+"""Tests for the live-trading kill switch (src/live/halt.py, SPEC Consent §4).
+
+The kill switch is a pure-filesystem sentinel — independent of any LLM/agent
+state — so these tests exercise it purely through the filesystem.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from src.live import halt
+from src.live import paths
+
+
+def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Point the live runtime root at an isolated tmp dir."""
+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)
+ return tmp_path
+
+
+def test_not_halted_when_no_sentinel(live_runtime: Path) -> None:
+ assert halt.halt_flag_set() is False
+ assert halt.halt_flag_set("robinhood") is False
+ assert halt.read_halt() is None
+
+
+def test_global_trip_and_clear(live_runtime: Path) -> None:
+ path = halt.trip_halt(by="cli", reason="user said stop")
+ assert path.exists()
+ assert halt.halt_flag_set() is True
+ # Global sentinel halts every broker regardless of per-broker state.
+ assert halt.halt_flag_set("robinhood") is True
+ assert halt.halt_flag_set("anything") is True
+
+ meta = halt.read_halt()
+ assert meta is not None
+ assert meta["by"] == "cli"
+ assert meta["reason"] == "user said stop"
+ assert "tripped_at" in meta
+
+ assert halt.clear_halt() is True
+ assert halt.halt_flag_set() is False
+ # Clearing an already-clear switch is a no-op returning False.
+ assert halt.clear_halt() is False
+
+
+def test_per_broker_trip_is_scoped(live_runtime: Path) -> None:
+ halt.trip_halt(by="frontend", reason="halt one broker", broker="robinhood")
+ assert halt.halt_flag_set("robinhood") is True
+ # A different broker is unaffected, and the global check stays clear.
+ assert halt.halt_flag_set("alpaca") is False
+ assert halt.halt_flag_set() is False
+ # Clearing the broker sentinel does not require touching the global one.
+ assert halt.clear_halt(broker="robinhood") is True
+ assert halt.halt_flag_set("robinhood") is False
+
+
+def test_global_wins_over_broker(live_runtime: Path) -> None:
+ halt.trip_halt(by="cli", reason="broker only", broker="robinhood")
+ halt.trip_halt(by="cli", reason="global")
+ # Clearing the global still leaves the broker sentinel in effect.
+ halt.clear_halt()
+ assert halt.halt_flag_set("robinhood") is True
+
+
+def test_existence_is_authoritative_even_if_malformed(live_runtime: Path) -> None:
+ # A user/watchdog touching the file with junk still counts as halted;
+ # only the attribution metadata is unreadable.
+ path = halt.halt_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("not json", encoding="utf-8")
+ assert halt.halt_flag_set() is True
+ assert halt.read_halt() == {}
+
+
+def test_bare_touch_trips_without_metadata(live_runtime: Path) -> None:
+ path = halt.halt_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("", encoding="utf-8")
+ assert halt.halt_flag_set() is True
+ assert halt.read_halt() == {}
+
+
+def test_invalid_broker_fails_closed(live_runtime: Path) -> None:
+ # An unresolvable broker key (path traversal) can never be safely traded.
+ assert halt.halt_flag_set("../evil") is True
+
+
+def test_trip_is_idempotent_latest_wins(live_runtime: Path) -> None:
+ halt.trip_halt(by="cli", reason="first")
+ halt.trip_halt(by="frontend", reason="second")
+ meta = halt.read_halt()
+ assert meta is not None
+ assert meta["by"] == "frontend"
+ assert meta["reason"] == "second"
+
+
+# --- Preemptive halt action hook (SPEC §7.5 component 6) ------------------
+
+
[email protected](autouse=True)
+def _clear_halt_actions() -> object:
+ """Isolate the module-level action registry between tests."""
+ halt._HALT_ACTIONS.clear()
+ yield
+ halt._HALT_ACTIONS.clear()
+
+
+def test_on_halt_action_noop_when_unregistered(live_runtime: Path) -> None:
+ # No action registered → no-op returning None (cooperative gate still blocks).
+ assert halt.on_halt_action("robinhood") is None
+
+
+def test_register_and_run_halt_action(live_runtime: Path) -> None:
+ seen: list[str] = []
+ halt.register_halt_action(lambda broker: seen.append(broker) or "swept")
+ assert halt.on_halt_action("robinhood") == "swept"
+ assert seen == ["robinhood"]
+
+
+def test_broker_action_overrides_global(live_runtime: Path) -> None:
+ halt.register_halt_action(lambda broker: "global")
+ halt.register_halt_action(lambda broker: "rh", broker="robinhood")
+ assert halt.on_halt_action("robinhood") == "rh"
+ assert halt.on_halt_action("alpaca") == "global"
+
+
+def test_unregister_halt_action(live_runtime: Path) -> None:
+ halt.register_halt_action(lambda broker: "x", broker="robinhood")
+ assert halt.unregister_halt_action(broker="robinhood") is True
+ assert halt.unregister_halt_action(broker="robinhood") is False
+ assert halt.on_halt_action("robinhood") is None
+
+
+def test_register_is_idempotent_latest_wins(live_runtime: Path) -> None:
+ halt.register_halt_action(lambda broker: "first", broker="robinhood")
+ halt.register_halt_action(lambda broker: "second", broker="robinhood")
+ assert halt.on_halt_action("robinhood") == "second"
+
+
+def test_action_exception_propagates(live_runtime: Path) -> None:
+ def boom(broker: str) -> object:
+ raise RuntimeError("flatten failed")
+
+ halt.register_halt_action(boom, broker="robinhood")
+ with pytest.raises(RuntimeError, match="flatten failed"):
+ halt.on_halt_action("robinhood")
diff --git a/agent/tests/test_killswitch_blocks_orders.py b/agent/tests/test_killswitch_blocks_orders.py
new file mode 100644
index 000000000..be93f6794
--- /dev/null
+++ b/agent/tests/test_killswitch_blocks_orders.py
@@ -0,0 +1,142 @@
+"""Kill switch blocks live orders at the gate (SPEC.md Consent §4, gate-level).
+
+With a committed mandate and the HALT flag set, ``LiveOrderGuardTool.execute``
+must return a refusal and make NO remote call (the mock adapter's order tool is
+never invoked). Read tools are unaffected by HALT — only the gate refuses.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+import src.live.paths as paths
+from src.live.halt import trip_halt
+from src.live.mandate.model import (
+ MANDATE_SCHEMA_VERSION,
+ AssetClass,
+ ConsentMeta,
+ HardCaps,
+ InstrumentType,
+ Mandate,
+ UniverseConstraint,
+)
+from src.live.order_guard import LiveOrderGuardTool
+from src.tools.mcp import MCPRemoteTool, MCPRemoteToolSpec
+
+
+def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)
+ return tmp_path
+
+
+class _MockAdapter:
+ def __init__(self) -> None:
+ self.server_name = "robinhood"
+ self.calls: list[str] = []
+
+ def call_tool(self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:
+ self.calls.append(remote_name)
+ if remote_name in ("get_positions", "list_positions"):
+ return {"positions": [], "status": "ok"}
+ if remote_name in ("get_account", "get_balance", "get_buying_power"):
+ return {"equity": 5000.0, "status": "ok"}
+ return {"status": "ok", "order_id": "rh_x", "state": "accepted"}
+
+
+def _order_spec() -> MCPRemoteToolSpec:
+ return MCPRemoteToolSpec(
+ server_name="robinhood",
+ remote_name="place_order",
+ local_name="mcp_robinhood_place_order",
+ description="Place an order.",
+ parameters={"type": "object", "properties": {}, "additionalProperties": True},
+ )
+
+
+def _read_spec() -> MCPRemoteToolSpec:
+ return MCPRemoteToolSpec(
+ server_name="robinhood",
+ remote_name="get_positions",
+ local_name="mcp_robinhood_get_positions",
+ description="Read positions.",
+ parameters={"type": "object", "properties": {}, "additionalProperties": True},
+ )
+
+
+def _write_mandate(live_runtime: Path) -> None:
+ broker = live_runtime / "live" / "robinhood"
+ broker.mkdir(parents=True, exist_ok=True)
+ created = datetime.now(timezone.utc)
+ payload = {
+ "schema_version": MANDATE_SCHEMA_VERSION,
+ "hard_caps": {
+ "account_funding_usd": 5000.0,
+ "max_order_notional_usd": 750.0,
+ "max_total_exposure_usd": 5000.0,
+ "max_leverage": 1.0,
+ "allowed_instruments": ["equity", "etf"],
+ "max_trades_per_day": 5,
+ },
+ "universe": {
+ "asset_classes": ["us_equity", "us_etf"],
+ "min_market_cap_usd": None,
+ "min_avg_daily_volume_usd": None,
+ "exclude_symbols": [],
+ },
+ "consent": {
+ "created_at": created.isoformat(),
+ "consent_token_sha256": "deadbeef",
+ "broker": "robinhood",
+ "account_ref": "acct_ref",
+ "expires_at": (created + timedelta(days=30)).isoformat(),
+ },
+ }
+ (broker / "mandate.json").write_text(json.dumps(payload), encoding="utf-8")
+
+
+def test_halt_blocks_order_no_remote_call(live_runtime: Path) -> None:
+ _write_mandate(live_runtime)
+ trip_halt(by="file", reason="test halt") # global sentinel
+ adapter = _MockAdapter()
+ guard = LiveOrderGuardTool(adapter, _order_spec(), broker="robinhood", session_id="s1")
+
+ out = json.loads(
+ guard.execute(symbol="AAPL", side="buy", instrument_type="equity", notional_usd=100.0)
+ )
+
+ assert out["status"] == "blocked"
+ assert out["decision"] == "deny"
+ assert "halt" in out["reason"].lower()
+ # No remote call of ANY kind — the gate short-circuits before reading.
+ assert adapter.calls == []
+
+
+def test_per_broker_halt_blocks_order(live_runtime: Path) -> None:
+ _write_mandate(live_runtime)
+ trip_halt(by="cli", reason="broker halt", broker="robinhood")
+ adapter = _MockAdapter()
+ guard = LiveOrderGuardTool(adapter, _order_spec(), broker="robinhood", session_id="s1")
+
+ out = json.loads(
+ guard.execute(symbol="AAPL", side="buy", instrument_type="equity", notional_usd=100.0)
+ )
+ assert out["status"] == "blocked"
+ assert adapter.calls == []
+
+
+def test_read_tools_unaffected_by_halt(live_runtime: Path) -> None:
+ """A plain read tool is NOT a guard — HALT must not block reads."""
+ _write_mandate(live_runtime)
+ trip_halt(by="file", reason="test halt")
+ adapter = _MockAdapter()
+ read_tool = MCPRemoteTool(adapter, _read_spec())
+
+ payload = json.loads(read_tool.execute())
+ assert payload["status"] == "ok"
+ assert adapter.calls == ["get_positions"]
diff --git a/agent/tests/test_mandate_enforcement.py b/agent/tests/test_mandate_enforcement.py
new file mode 100644
index 000000000..b09b78b02
--- /dev/null
+++ b/agent/tests/test_mandate_enforcement.py
@@ -0,0 +1,471 @@
+"""Mandate enforcement gate tests (SPEC.md Mandate Enforcement §3–§6).
+
+Parametrized per limit: each case submits an order breaching exactly one limit
+and asserts a refusal carrying the breach; one in-mandate case asserts the order
+forwards through to the underlying mock MCP tool. Universe market-cap/liquidity
+floors are exercised by monkeypatching the loader-backed helpers (no network).
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+import src.live.enforcement as enforcement
+import src.live.order_guard as order_guard
+import src.live.paths as paths
+from src.live.enforcement import (
+ BREACH_KIND_INSTRUMENT,
+ BREACH_KIND_QUANTITATIVE,
+ BREACH_KIND_UNIVERSE,
+ OrderIntent,
+ check_mandate,
+)
+from src.live.mandate.model import (
+ MANDATE_SCHEMA_VERSION,
+ AssetClass,
+ ConsentMeta,
+ HardCaps,
+ InstrumentType,
+ Mandate,
+ UniverseConstraint,
+)
+from src.tools.mcp import MCPRemoteToolSpec
+
+
+# --------------------------------------------------------------------------- #
+# Fixtures + mock MCP adapter #
+# --------------------------------------------------------------------------- #
+
+
+def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Point the live root at a tmp dir so tests never touch the real store."""
+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)
+ return tmp_path
+
+
+class _MockAdapter:
+ """Minimal MCPServerAdapter stand-in with recording call_tool."""
+
+ def __init__(self, *, positions: Any, balance: Any) -> None:
+ self.server_name = "robinhood"
+ self._positions = positions
+ self._balance = balance
+ self.call_records: list[dict[str, Any]] = []
+ self.order_calls: list[dict[str, Any]] = []
+
+ def call_tool(self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:
+ self.call_records.append({"remote": remote_name, "arguments": arguments})
+ if remote_name in ("get_positions", "list_positions"):
+ return {"positions": self._positions, "status": "ok"}
+ if remote_name in ("get_account", "get_balance", "get_buying_power"):
+ return {"equity": self._balance, "status": "ok"}
+ # The order placement itself (super().execute forwards here).
+ self.order_calls.append({"remote": remote_name, "arguments": arguments})
+ return {"status": "ok", "order_id": "rh_test_1", "state": "accepted"}
+
+
+def _spec() -> MCPRemoteToolSpec:
+ return MCPRemoteToolSpec(
+ server_name="robinhood",
+ remote_name="place_order",
+ local_name="mcp_robinhood_place_order",
+ description="Place an order.",
+ parameters={
+ "type": "object",
+ "properties": {
+ "symbol": {"type": "string"},
+ "side": {"type": "string"},
+ "instrument_type": {"type": "string"},
+ "notional_usd": {"type": "number"},
+ "quantity": {"type": "number"},
+ },
+ "additionalProperties": True,
+ },
+ )
+
+
+def _mandate(expires_in_days: int = 30, **caps_overrides: Any) -> Mandate:
+ created = datetime.now(timezone.utc)
+ caps = {
+ "account_funding_usd": 5000.0,
+ "max_order_notional_usd": 750.0,
+ "max_total_exposure_usd": 5000.0,
+ "max_leverage": 1.0,
+ "allowed_instruments": (InstrumentType.EQUITY, InstrumentType.ETF),
+ "max_trades_per_day": 5,
+ }
+ caps.update(caps_overrides)
+ return Mandate(
+ schema_version=MANDATE_SCHEMA_VERSION,
+ hard_caps=HardCaps(**caps),
+ universe=UniverseConstraint(
+ asset_classes=(AssetClass.US_EQUITY, AssetClass.US_ETF),
+ min_market_cap_usd=None,
+ min_avg_daily_volume_usd=None,
+ exclude_symbols=("GME",),
+ ),
+ consent=ConsentMeta(
+ created_at=created.isoformat(),
+ consent_token_sha256="deadbeef",
+ broker="robinhood",
+ account_ref="acct_ref_xyz",
+ expires_at=(created + timedelta(days=expires_in_days)).isoformat(),
+ ),
+ )
+
+
+def _write_mandate(live_runtime: Path, mandate: Mandate) -> None:
+ broker = live_runtime / "live" / "robinhood"
+ broker.mkdir(parents=True, exist_ok=True)
+ payload = {
+ "schema_version": mandate.schema_version,
+ "hard_caps": {
+ "account_funding_usd": mandate.hard_caps.account_funding_usd,
+ "max_order_notional_usd": mandate.hard_caps.max_order_notional_usd,
+ "max_total_exposure_usd": mandate.hard_caps.max_total_exposure_usd,
+ "max_leverage": mandate.hard_caps.max_leverage,
+ "allowed_instruments": [i.value for i in mandate.hard_caps.allowed_instruments],
+ "max_trades_per_day": mandate.hard_caps.max_trades_per_day,
+ },
+ "universe": {
+ "asset_classes": [a.value for a in mandate.universe.asset_classes],
+ "min_market_cap_usd": mandate.universe.min_market_cap_usd,
+ "min_avg_daily_volume_usd": mandate.universe.min_avg_daily_volume_usd,
+ "exclude_symbols": list(mandate.universe.exclude_symbols),
+ },
+ "consent": {
+ "created_at": mandate.consent.created_at,
+ "consent_token_sha256": mandate.consent.consent_token_sha256,
+ "broker": mandate.consent.broker,
+ "account_ref": mandate.consent.account_ref,
+ "expires_at": mandate.consent.expires_at,
+ },
+ }
+ (broker / "mandate.json").write_text(json.dumps(payload), encoding="utf-8")
+
+
+# --------------------------------------------------------------------------- #
+# check_mandate — pure decision function, parametrized per limit #
+# --------------------------------------------------------------------------- #
+
+
+def _intent(**overrides: Any) -> OrderIntent:
+ base = {
+ "symbol": "AAPL",
+ "side": "buy",
+ "notional_usd": 100.0,
+ "quantity": None,
+ "instrument_type": InstrumentType.EQUITY,
+ }
+ base.update(overrides)
+ return OrderIntent(**base)
+
+
+def _check(intent: OrderIntent, mandate: Mandate, *, positions=None, daily_count=0):
+ return check_mandate(
+ mandate,
+ intent,
+ positions if positions is not None else [],
+ {"equity": 5000.0},
+ broker="robinhood",
+ remote_tool="place_order",
+ daily_count=daily_count,
+ )
+
+
+def test_in_mandate_order_passes() -> None:
+ assert _check(_intent(notional_usd=100.0), _mandate()) is None
+
+
+ "intent_kwargs, mandate_kwargs, positions, daily_count, expect_limit, expect_kind",
+ [
+ # Exclude-list (universe, structural).
+ (dict(symbol="GME"), {}, [], 0, "exclude_symbols", BREACH_KIND_UNIVERSE),
+ # Disallowed instrument (instrument, structural).
+ (dict(instrument_type=InstrumentType.CRYPTO), {}, [], 0, "allowed_instruments", BREACH_KIND_INSTRUMENT),
+ # Per-order notional (quantitative).
+ (dict(notional_usd=1000.0), {}, [], 0, "max_order_notional_usd", BREACH_KIND_QUANTITATIVE),
+ # Total exposure (quantitative): existing $4900 + $200 buy > $5000 cap.
+ (dict(notional_usd=200.0), {}, [{"market_value": 4900.0}], 0, "max_total_exposure_usd", BREACH_KIND_QUANTITATIVE),
+ # Leverage (quantitative): tiny funding makes 1x leverage breach.
+ (dict(notional_usd=600.0), dict(account_funding_usd=500.0, max_total_exposure_usd=1e9), [], 0, "max_leverage", BREACH_KIND_QUANTITATIVE),
+ # Daily count (quantitative): already at the cap.
+ (dict(notional_usd=100.0), {}, [], 5, "max_trades_per_day", BREACH_KIND_QUANTITATIVE),
+ ],
+)
+def test_each_limit_breach(
+ intent_kwargs, mandate_kwargs, positions, daily_count, expect_limit, expect_kind
+) -> None:
+ breach = _check(
+ _intent(**intent_kwargs),
+ _mandate(**mandate_kwargs),
+ positions=positions,
+ daily_count=daily_count,
+ )
+ assert breach is not None
+ assert breach.limit == expect_limit
+ assert breach.kind == expect_kind
+
+
+def test_unreadable_positions_fail_closed() -> None:
+ # A position with no parseable value → total-exposure check denies.
+ breach = _check(_intent(notional_usd=100.0), _mandate(), positions=[{"junk": 1}])
+ assert breach is not None
+ assert breach.limit == "max_total_exposure_usd"
+
+
+def test_universe_market_cap_floor_denies_when_below(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(enforcement, "market_cap_usd", lambda s, ac: 1.0e8)
+ mandate = _mandate()
+ mandate = Mandate(
+ schema_version=mandate.schema_version,
+ hard_caps=mandate.hard_caps,
+ universe=UniverseConstraint(
+ asset_classes=mandate.universe.asset_classes,
+ min_market_cap_usd=1.0e9, # floor above the stubbed cap
+ min_avg_daily_volume_usd=None,
+ exclude_symbols=mandate.universe.exclude_symbols,
+ ),
+ consent=mandate.consent,
+ )
+ breach = _check(_intent(notional_usd=100.0), mandate)
+ assert breach is not None
+ assert breach.limit == "min_market_cap_usd"
+ assert breach.kind == BREACH_KIND_UNIVERSE
+
+
+def test_universe_market_cap_missing_data_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(enforcement, "market_cap_usd", lambda s, ac: None)
+ mandate = _mandate()
+ mandate = Mandate(
+ schema_version=mandate.schema_version,
+ hard_caps=mandate.hard_caps,
+ universe=UniverseConstraint(
+ asset_classes=mandate.universe.asset_classes,
+ min_market_cap_usd=1.0e9,
+ min_avg_daily_volume_usd=None,
+ exclude_symbols=mandate.universe.exclude_symbols,
+ ),
+ consent=mandate.consent,
+ )
+ breach = _check(_intent(notional_usd=100.0), mandate)
+ assert breach is not None
+ assert breach.limit == "min_market_cap_usd" # no data → DENY
+
+
+# --------------------------------------------------------------------------- #
+# LiveOrderGuardTool — end to end through the gate #
+# --------------------------------------------------------------------------- #
+
+
+def _guard(adapter, **kwargs):
+ return order_guard.LiveOrderGuardTool(adapter, _spec(), broker="robinhood", session_id="s1", **kwargs)
+
+
+def test_guard_forwards_in_mandate_order(live_runtime: Path) -> None:
+ _write_mandate(live_runtime, _mandate())
+ adapter = _MockAdapter(positions=[], balance=5000.0)
+ guard = _guard(adapter)
+ out = json.loads(guard.execute(symbol="AAPL", side="buy", instrument_type="equity", notional_usd=100.0))
+ assert out.get("status") == "ok"
+ assert out.get("order_id") == "rh_test_1"
+ assert len(adapter.order_calls) == 1
+ # Daily counter incremented exactly once on confirmed forward.
+ counter = json.loads((live_runtime / "live" / "robinhood" / "trade_counter.json").read_text())
+ assert counter["count"] == 1
+
+
+def test_guard_blocks_over_notional_with_breach(live_runtime: Path) -> None:
+ _write_mandate(live_runtime, _mandate())
+ adapter = _MockAdapter(positions=[], balance=5000.0)
+ guard = _guard(adapter)
+ out = json.loads(guard.execute(symbol="AAPL", side="buy", instrument_type="equity", notional_usd=5000.0))
+ assert out["status"] == "blocked"
+ assert out["decision"] == "pause_for_reauth"
+ assert out["requires_reauthorization"] is True
+ assert out["breach"]["limit"] == "max_order_notional_usd"
+ assert adapter.order_calls == [] # never forwarded
+
+
+def test_guard_structural_breach_denies_no_reauth(live_runtime: Path) -> None:
+ _write_mandate(live_runtime, _mandate())
+ adapter = _MockAdapter(positions=[], balance=5000.0)
+ guard = _guard(adapter)
+ out = json.loads(guard.execute(symbol="GME", side="buy", instrument_type="equity", notional_usd=100.0))
+ assert out["status"] == "blocked"
+ assert out["decision"] == "deny"
+ assert out["requires_reauthorization"] is False
+ assert out["breach"]["kind"] == BREACH_KIND_UNIVERSE
+ assert adapter.order_calls == []
+
+
+def test_guard_no_mandate_denies(live_runtime: Path) -> None:
+ adapter = _MockAdapter(positions=[], balance=5000.0)
+ guard = _guard(adapter)
+ out = json.loads(guard.execute(symbol="AAPL", side="buy", instrument_type="equity", notional_usd=100.0))
+ assert out["status"] == "blocked"
+ assert out["decision"] == "deny"
+ assert adapter.order_calls == []
+
+
+def test_guard_expired_mandate_denies_with_reauth(live_runtime: Path) -> None:
+ _write_mandate(live_runtime, _mandate(expires_in_days=-1))
+ adapter = _MockAdapter(positions=[], balance=5000.0)
+ guard = _guard(adapter)
+ out = json.loads(guard.execute(symbol="AAPL", side="buy", instrument_type="equity", notional_usd=100.0))
+ assert out["status"] == "blocked"
+ assert out["requires_reauthorization"] is True
+ assert adapter.order_calls == []
+
+
+def test_guard_unparseable_intent_denies(live_runtime: Path) -> None:
+ _write_mandate(live_runtime, _mandate())
+ adapter = _MockAdapter(positions=[], balance=5000.0)
+ guard = _guard(adapter)
+ # Missing side → extractor returns None → DENY.
+ out = json.loads(guard.execute(symbol="AAPL", instrument_type="equity", notional_usd=100.0))
+ assert out["status"] == "blocked"
+ assert adapter.order_calls == []
+
+
+def test_guard_repeatable_is_false() -> None:
+ assert order_guard.LiveOrderGuardTool.repeatable is False
+ assert order_guard.LiveOrderGuardTool.is_readonly is False
+
+
+# --------------------------------------------------------------------------- #
+# H2 — failed broker forward must not consume a count or audit "accepted" #
+# --------------------------------------------------------------------------- #
+
+
+class _FailingForwardAdapter:
+ """Adapter whose order placement returns an ERROR envelope (no raise).
+
+ Mirrors ``MCPServerAdapter.call_tool``: broker/network failure is reported as
+ a ``{"status": "error", ...}`` envelope, not an exception.
+ """
+
+ def __init__(self) -> None:
+ self.server_name = "robinhood"
+ self.order_calls: list[dict[str, Any]] = []
+
+ def call_tool(self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:
+ if remote_name == "get_positions":
+ return {"positions": [], "status": "ok"}
+ if remote_name == "get_account":
+ return {"equity": 5000.0, "status": "ok"}
+ # The order placement fails at the broker.
+ self.order_calls.append({"remote": remote_name, "arguments": arguments})
+ return {"status": "error", "error": "broker rejected", "error_type": "BrokerError"}
+
+
+def _read_audit_records(live_runtime: Path) -> list[dict[str, Any]]:
+ ledger = live_runtime / "live" / "audit.jsonl"
+ if not ledger.is_file():
+ return []
+ return [json.loads(line) for line in ledger.read_text().splitlines() if line.strip()]
+
+
+def test_failed_forward_does_not_consume_count_or_audit_accepted(live_runtime: Path) -> None:
+ """H2: an in-mandate order whose forward errors must NOT consume a daily
+ count and must NOT write an ``accepted`` record."""
+ _write_mandate(live_runtime, _mandate())
+ adapter = _FailingForwardAdapter()
+ guard = _guard(adapter)
+
+ out = json.loads(
+ guard.execute(symbol="AAPL", side="buy", instrument_type="equity", notional_usd=100.0)
+ )
+
+ # The order WAS forwarded (it passed the gate) but the broker errored.
+ assert len(adapter.order_calls) == 1
+ assert out.get("status") == "error"
+
+ # No daily count consumed.
+ counter_path = live_runtime / "live" / "robinhood" / "trade_counter.json"
+ assert not counter_path.is_file()
+
+ # No "accepted" record; exactly one error record instead.
+ records = _read_audit_records(live_runtime)
+ assert all(r["outcome"] != "accepted" for r in records)
+ accepted = [r for r in records if r["kind"] == "order_placed"]
+ assert accepted == []
+ errored = [r for r in records if r["outcome"] == "error"]
+ assert len(errored) == 1
+ assert errored[0]["kind"] == "order_rejected"
+
+
+def test_successful_forward_consumes_count_and_audits_accepted(live_runtime: Path) -> None:
+ """Counterpart to H2: a non-error forward consumes exactly one count and
+ writes one ``order_placed``/``accepted`` record carrying ``live_action``."""
+ _write_mandate(live_runtime, _mandate())
+ adapter = _MockAdapter(positions=[], balance=5000.0)
+ guard = _guard(adapter)
+
+ out = json.loads(
+ guard.execute(symbol="AAPL", side="buy", instrument_type="equity", notional_usd=100.0)
+ )
+ assert out.get("status") == "ok"
+ counter = json.loads((live_runtime / "live" / "robinhood" / "trade_counter.json").read_text())
+ assert counter["count"] == 1
+ accepted = [r for r in _read_audit_records(live_runtime) if r["kind"] == "order_placed"]
+ assert len(accepted) == 1
+ # H5: the redacted audit record is embedded under the frozen marker key.
+ assert out[order_guard.LIVE_ACTION_RESULT_KEY]["kind"] == "order_placed"
+
+
+# --------------------------------------------------------------------------- #
+# H3 — notional+quantity ambiguity bypass is closed #
+# --------------------------------------------------------------------------- #
+
+
+class _QuoteAdapter:
+ """Adapter with a working ``get_quotes`` read tool returning a fixed price."""
+
+ def __init__(self, *, price: float, positions: Any = (), balance: Any = 5000.0) -> None:
+ self.server_name = "robinhood"
+ self._price = price
+ self._positions = list(positions)
+ self._balance = balance
+ self.order_calls: list[dict[str, Any]] = []
+ self.quote_calls: list[dict[str, Any]] = []
+
+ def call_tool(self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:
+ if remote_name == "get_positions":
+ return {"positions": self._positions, "status": "ok"}
+ if remote_name == "get_account":
+ return {"equity": self._balance, "status": "ok"}
+ if remote_name == "get_quotes":
+ self.quote_calls.append({"arguments": arguments})
+ return {"status": "ok", "symbol": arguments.get("symbol"), "price": self._price}
+ self.order_calls.append({"remote": remote_name, "arguments": arguments})
+ return {"status": "ok", "order_id": "rh_test_1", "state": "accepted"}
+
+
+def test_notional_quantity_bypass_is_closed(live_runtime: Path) -> None:
+ """H3: an order carrying a tiny notional but a huge quantity is enforced on
+ the quantity-implied notional, so it is NOT waved through."""
+ _write_mandate(live_runtime, _mandate()) # max_order_notional_usd = 750
+ # 100000 shares * $10 = $1,000,000 implied notional, well over the cap; the
+ # explicit $10 notional must not be the value enforced.
+ adapter = _QuoteAdapter(price=10.0)
+ guard = _guard(adapter)
+
+ out = json.loads(
+ guard.execute(
+ symbol="AAPL", side="buy", instrument_type="equity",
+ notional_usd=10.0, quantity=100000.0,
+ )
+ )
+ assert out["status"] == "blocked"
+ assert out["breach"]["limit"] == "max_order_notional_usd"
+ assert out["breach"]["attempted_value"] == 1_000_000.0
+ assert adapter.order_calls == [] # never forwarded
+ assert adapter.quote_calls # broker quote tool was consulted
diff --git a/agent/tests/test_mandate_model.py b/agent/tests/test_mandate_model.py
new file mode 100644
index 000000000..5576d44b0
--- /dev/null
+++ b/agent/tests/test_mandate_model.py
@@ -0,0 +1,193 @@
+"""Mandate model + read-only store: round-trip, absent→None, expiry parse."""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+
+import pytest
+
+import src.live.paths as paths
+from src.live.mandate.model import (
+ MANDATE_SCHEMA_VERSION,
+ AssetClass,
+ ConsentMeta,
+ HardCaps,
+ InstrumentType,
+ Mandate,
+ UniverseConstraint,
+)
+from src.live.mandate.store import load_mandate
+
+
+def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Point the live root at a tmp dir so tests never touch the real store."""
+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)
+ return tmp_path
+
+
+def _sample_mandate(expires_at: str, *, flatten_on_halt: bool = False) -> Mandate:
+ return Mandate(
+ schema_version=MANDATE_SCHEMA_VERSION,
+ flatten_on_halt=flatten_on_halt,
+ hard_caps=HardCaps(
+ account_funding_usd=5000.0,
+ max_order_notional_usd=750.0,
+ max_total_exposure_usd=5000.0,
+ max_leverage=1.0,
+ allowed_instruments=(InstrumentType.EQUITY, InstrumentType.ETF),
+ max_trades_per_day=5,
+ ),
+ universe=UniverseConstraint(
+ asset_classes=(AssetClass.US_EQUITY, AssetClass.US_ETF),
+ min_market_cap_usd=2_000_000_000.0,
+ min_avg_daily_volume_usd=None,
+ exclude_symbols=("TSLA", "GME"),
+ ),
+ consent=ConsentMeta(
+ created_at="2026-05-29T14:00:00Z",
+ consent_token_sha256="a" * 64,
+ broker="robinhood",
+ account_ref="rh_acct_opaque",
+ expires_at=expires_at,
+ ),
+ )
+
+
+def _write_mandate(broker_path: Path, mandate: Mandate) -> None:
+ broker_path.mkdir(parents=True, exist_ok=True)
+ caps = mandate.hard_caps
+ universe = mandate.universe
+ consent = mandate.consent
+ payload = {
+ "schema_version": mandate.schema_version,
+ "flatten_on_halt": mandate.flatten_on_halt,
+ "hard_caps": {
+ "account_funding_usd": caps.account_funding_usd,
+ "max_order_notional_usd": caps.max_order_notional_usd,
+ "max_total_exposure_usd": caps.max_total_exposure_usd,
+ "max_leverage": caps.max_leverage,
+ "allowed_instruments": [i.value for i in caps.allowed_instruments],
+ "max_trades_per_day": caps.max_trades_per_day,
+ },
+ "universe": {
+ "asset_classes": [a.value for a in universe.asset_classes],
+ "min_market_cap_usd": universe.min_market_cap_usd,
+ "min_avg_daily_volume_usd": universe.min_avg_daily_volume_usd,
+ "exclude_symbols": list(universe.exclude_symbols),
+ },
+ "consent": {
+ "created_at": consent.created_at,
+ "consent_token_sha256": consent.consent_token_sha256,
+ "broker": consent.broker,
+ "account_ref": consent.account_ref,
+ "expires_at": consent.expires_at,
+ },
+ }
+ (broker_path / "mandate.json").write_text(json.dumps(payload), encoding="utf-8")
+
+
+def test_load_mandate_round_trip(live_runtime: Path) -> None:
+ """A written mandate loads back into an equal frozen object."""
+ expires = "2026-06-28T14:00:00Z"
+ original = _sample_mandate(expires)
+ from src.live.paths import broker_dir
+
+ _write_mandate(broker_dir("robinhood"), original)
+ loaded = load_mandate("robinhood")
+
+ assert loaded == original
+ # Frozen dataclass — enums survive the round-trip.
+ assert loaded.hard_caps.allowed_instruments == (
+ InstrumentType.EQUITY,
+ InstrumentType.ETF,
+ )
+ assert loaded.universe.asset_classes == (AssetClass.US_EQUITY, AssetClass.US_ETF)
+ assert loaded.universe.min_avg_daily_volume_usd is None
+
+
+def test_flatten_on_halt_round_trips(live_runtime: Path) -> None:
+ """A mandate written with flatten_on_halt=True loads back True (M3)."""
+ from src.live.paths import broker_dir
+
+ _write_mandate(broker_dir("robinhood"), _sample_mandate("2026-06-28T14:00:00Z", flatten_on_halt=True))
+ loaded = load_mandate("robinhood")
+ assert loaded is not None
+ assert loaded.flatten_on_halt is True
+
+
+def test_flatten_on_halt_absent_defaults_false(live_runtime: Path) -> None:
+ """An OLD mandate.json lacking flatten_on_halt loads as False (cancel-only).
+
+ Backward compatibility: the field is optional with a safe default, so a
+ mandate written before the field existed must not break the loader and must
+ default to cancel-only.
+ """
+ from src.live.paths import broker_dir
+
+ bdir = broker_dir("robinhood")
+ _write_mandate(bdir, _sample_mandate("2026-06-28T14:00:00Z"))
+ # Strip the field to simulate a pre-flatten_on_halt mandate.json on disk.
+ doc = json.loads((bdir / "mandate.json").read_text(encoding="utf-8"))
+ doc.pop("flatten_on_halt", None)
+ (bdir / "mandate.json").write_text(json.dumps(doc), encoding="utf-8")
+
+ loaded = load_mandate("robinhood")
+ assert loaded is not None
+ assert loaded.flatten_on_halt is False
+
+
+def test_load_mandate_absent_returns_none(live_runtime: Path) -> None:
+ """No file on disk → None (fail-closed, gate denies)."""
+ assert load_mandate("robinhood") is None
+
+
+def test_load_mandate_malformed_json_returns_none(live_runtime: Path) -> None:
+ """Unparseable JSON → None rather than an exception."""
+ from src.live.paths import broker_dir
+
+ bdir = broker_dir("robinhood")
+ bdir.mkdir(parents=True, exist_ok=True)
+ (bdir / "mandate.json").write_text("{not json", encoding="utf-8")
+ assert load_mandate("robinhood") is None
+
+
+def test_load_mandate_missing_field_returns_none(live_runtime: Path) -> None:
+ """A structurally invalid record (missing section) → None (fail-closed)."""
+ from src.live.paths import broker_dir
+
+ bdir = broker_dir("robinhood")
+ bdir.mkdir(parents=True, exist_ok=True)
+ (bdir / "mandate.json").write_text(
+ json.dumps({"schema_version": MANDATE_SCHEMA_VERSION}), encoding="utf-8"
+ )
+ assert load_mandate("robinhood") is None
+
+
+def test_expires_at_parses_as_utc_datetime(live_runtime: Path) -> None:
+ """expires_at round-trips as an ISO-8601 UTC timestamp the gate can parse."""
+ created = datetime(2026, 5, 29, 14, 0, 0, tzinfo=timezone.utc)
+ expires_dt = created + timedelta(days=30)
+ expires = expires_dt.isoformat().replace("+00:00", "Z")
+ from src.live.paths import broker_dir
+
+ _write_mandate(broker_dir("robinhood"), _sample_mandate(expires))
+ loaded = load_mandate("robinhood")
+
+ assert loaded is not None
+ parsed = datetime.fromisoformat(loaded.consent.expires_at.replace("Z", "+00:00"))
+ assert parsed == expires_dt
+ assert parsed - created == timedelta(days=30)
+
+
+def test_broker_dir_rejects_path_traversal() -> None:
+ """A broker key is never a path — separators / .. are rejected."""
+ from src.live.paths import broker_dir
+
+ for bad in ("../escape", "rob/inhood", "a\\b", ".."):
+ with pytest.raises(ValueError):
+ broker_dir(bad)
+ with pytest.raises(ValueError):
+ broker_dir(" ")
diff --git a/agent/tests/test_mcp_oauth_schema.py b/agent/tests/test_mcp_oauth_schema.py
new file mode 100644
index 000000000..0b1323dbd
--- /dev/null
+++ b/agent/tests/test_mcp_oauth_schema.py
@@ -0,0 +1,199 @@
+"""Unit tests for the MCP OAuth schema + ``_build_client`` OAuth wiring.
+
+Covers:
+
+* ``MCPOAuthConfig`` / ``MCPServerConfig.auth`` pydantic round-trip (camelCase
+ and snake_case keys) and the seeded Robinhood config.
+* Validator rejections: OAuth requires https, auth and static headers are
+ mutually exclusive, stdio rejects auth, and a live-broker entry rejects a
+ wildcard ``["*"]`` allowlist.
+* ``_build_client`` yields a ``StreamableHttpTransport`` whose ``.auth`` is an
+ ``OAuth`` instance carrying the expected scopes / client_name / callback_port.
+* The static-header HTTP path and the stdio path are byte-for-byte unchanged
+ (``.auth is None``; transport types and fields untouched).
+"""
+
+from __future__ import annotations
+
+import pytest
+from fastmcp.client.auth import OAuth
+from fastmcp.client.transports.http import StreamableHttpTransport
+from fastmcp.client.transports.sse import SSETransport
+from fastmcp.client.transports.stdio import StdioTransport
+from pydantic import ValidationError
+
+from src.config.schema import (
+ LIVE_BROKER_SERVER_KEYS,
+ ROBINHOOD_MCP_SERVER_SEED,
+ AgentConfig,
+ MCPOAuthConfig,
+ MCPServerConfig,
+ MCPServerConfigOverride,
+)
+from src.tools.mcp import MCPServerAdapter
+
+pytestmark = pytest.mark.unit
+
+
+# --------------------------------------------------------------------------- #
+# Schema round-trip
+# --------------------------------------------------------------------------- #
+def test_oauth_config_round_trip_snake_and_camel() -> None:
+ snake = MCPOAuthConfig.model_validate(
+ {
+ "type": "oauth",
+ "scopes": ["trading.read"],
+ "client_name": "Vibe-Trading",
+ "cache_dir": "~/.vibe-trading/live/robinhood/oauth",
+ "callback_port": 8765,
+ }
+ )
+ camel = MCPOAuthConfig.model_validate(
+ {
+ "type": "oauth",
+ "scopes": ["trading.read"],
+ "clientName": "Vibe-Trading",
+ "cacheDir": "~/.vibe-trading/live/robinhood/oauth",
+ "callbackPort": 8765,
+ }
+ )
+ assert snake == camel
+ assert snake.client_name == "Vibe-Trading"
+ assert snake.callback_port == 8765
+
+
+def test_server_config_carries_auth() -> None:
+ cfg = MCPServerConfig.model_validate(
+ {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "auth": {"type": "oauth", "scopes": ["trading.read"]},
+ }
+ )
+ assert isinstance(cfg.auth, MCPOAuthConfig)
+ assert cfg.auth.scopes == ["trading.read"]
+ assert cfg.resolved_transport() == "streamableHttp"
+
+
+def test_override_carries_auth() -> None:
+ override = MCPServerConfigOverride.model_validate(
+ {"auth": {"type": "oauth", "scopes": ["trading.read"]}}
+ )
+ assert isinstance(override.auth, MCPOAuthConfig)
+
+
+def test_robinhood_seed_is_readonly_and_oauth() -> None:
+ cfg = AgentConfig.model_validate({"mcpServers": {"robinhood": ROBINHOOD_MCP_SERVER_SEED}})
+ rh = cfg.mcp_servers["robinhood"]
+ assert rh.resolved_transport() == "streamableHttp"
+ assert rh.auth is not None and rh.auth.type == "oauth"
+ assert "*" not in rh.enabled_tools
+ assert rh.enabled_tools # non-empty explicit allowlist
+ assert "robinhood" in LIVE_BROKER_SERVER_KEYS
+
+
+# --------------------------------------------------------------------------- #
+# Validator rejections
+# --------------------------------------------------------------------------- #
+def test_oauth_requires_https() -> None:
+ with pytest.raises(ValidationError, match="https"):
+ MCPServerConfig.model_validate(
+ {"type": "streamableHttp", "url": "http://insecure/mcp", "auth": {"type": "oauth"}}
+ )
+
+
+def test_auth_and_static_headers_are_mutually_exclusive() -> None:
+ with pytest.raises(ValidationError, match="static headers"):
+ MCPServerConfig.model_validate(
+ {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "headers": {"Authorization": "Bearer hand-set"},
+ "auth": {"type": "oauth"},
+ }
+ )
+
+
+def test_stdio_rejects_auth() -> None:
+ with pytest.raises(ValidationError, match="HTTP-only"):
+ MCPServerConfig.model_validate({"command": "uvx", "args": ["demo"], "auth": {"type": "oauth"}})
+
+
+def test_live_broker_rejects_wildcard_allowlist() -> None:
+ with pytest.raises(ValidationError, match="wildcard"):
+ AgentConfig.model_validate(
+ {
+ "mcpServers": {
+ "robinhood": {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "auth": {"type": "oauth"},
+ "enabledTools": ["*"],
+ }
+ }
+ }
+ )
+
+
+def test_non_live_broker_still_allows_wildcard() -> None:
+ # A non-broker HTTP server keeps the default ["*"] semantics.
+ cfg = AgentConfig.model_validate(
+ {"mcpServers": {"internal_kb": {"type": "streamableHttp", "url": "https://kb/mcp"}}}
+ )
+ assert cfg.mcp_servers["internal_kb"].enabled_tools == ["*"]
+
+
+# --------------------------------------------------------------------------- #
+# _build_client OAuth wiring
+# --------------------------------------------------------------------------- #
+def _build_transport(server_config: MCPServerConfig):
+ return MCPServerAdapter("robinhood", server_config)._build_client().transport
+
+
+def test_build_client_yields_oauth_streamable_transport() -> None:
+ cfg = MCPServerConfig.model_validate(
+ {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "auth": {
+ "type": "oauth",
+ "scopes": ["trading.read"],
+ "client_name": "Vibe-Trading",
+ "callback_port": 8765,
+ },
+ }
+ )
+ transport = _build_transport(cfg)
+
+ assert isinstance(transport, StreamableHttpTransport)
+ assert isinstance(transport.auth, OAuth)
+ # Scopes / name / port flow through from config to the OAuth provider.
+ assert transport.auth._scopes == ["trading.read"]
+ assert transport.auth._client_name == "Vibe-Trading"
+ assert transport.auth._callback_port == 8765
+
+
+def test_static_header_http_path_unchanged() -> None:
+ cfg = MCPServerConfig.model_validate(
+ {"type": "streamableHttp", "url": "https://kb/mcp", "headers": {"X-Api-Key": "k"}}
+ )
+ transport = _build_transport(cfg)
+
+ assert isinstance(transport, StreamableHttpTransport)
+ # No auth was constructed; the static-header path is byte-unchanged.
+ assert transport.auth is None
+ assert transport.headers == {"X-Api-Key": "k"}
+
+
+def test_sse_path_unchanged() -> None:
+ cfg = MCPServerConfig.model_validate(
+ {"type": "sse", "url": "https://kb/sse", "headers": {"X-Api-Key": "k"}}
+ )
+ transport = _build_transport(cfg)
+ assert isinstance(transport, SSETransport)
+
+
+def test_stdio_path_unchanged() -> None:
+ cfg = MCPServerConfig.model_validate({"command": "uvx", "args": ["demo"]})
+ transport = _build_transport(cfg)
+ assert isinstance(transport, StdioTransport)
diff --git a/agent/tests/test_no_set_mandate_tool.py b/agent/tests/test_no_set_mandate_tool.py
new file mode 100644
index 000000000..5b2494b9e
--- /dev/null
+++ b/agent/tests/test_no_set_mandate_tool.py
@@ -0,0 +1,114 @@
+"""Structural guarantee: nothing the agent can reach writes the mandate store.
+
+Mirrors the BROKERS.md method-name-regex gate. Two checks:
+
+1. **Name-regex AST scan** over ``src/live/`` (and ``src/tools/``): no function
+ or method matches the forbidden self-authorization regex. The single
+ legitimate writer (the consent commit path, ``src/live/mandate/commit.py``,
+ owned by a different parcel) is named ``commit_mandate`` — deliberately NOT
+ matching ``^(_)?(set|write|update|grant|authorize|enable|widen)_...`` — and
+ is exempted by name + by not being importable as a tool.
+2. **No agent-reachable write path** opens ``mandate.json`` for write. We AST-
+ scan the modules the agent loop *can* import (``src/live/order_guard.py``,
+ ``src/live/enforcement.py``, ``src/live/extractors/``) for any ``open(...)``
+ in a write mode targeting the mandate file, and assert the mandate store
+ module exposes no ``save``/``set`` symbol.
+"""
+
+from __future__ import annotations
+
+import ast
+import re
+from pathlib import Path
+
+import pytest
+
+import src.live.mandate.store as store
+
+AGENT_DIR = Path(__file__).resolve().parent.parent
+LIVE_DIR = AGENT_DIR / "src" / "live"
+
+_FORBIDDEN_NAME = re.compile(
+ r"^(_)?(set|write|update|grant|authorize|enable|widen)_(mandate|limit|live|authorization)([_a-z]*)?$"
+)
+
+#: Known-legitimate functions whose names collide with the broad regex but do
+#: NOT write the mandate store. ``write_live_action`` (P5) appends to the
+#: append-only AUDIT ledger — it has no mandate write path. Exempting by exact
+#: name keeps the security regex strict (it still catches any real
+#: ``write_mandate`` / ``enable_live`` etc.) without a false positive.
+_NAME_ALLOWLIST = {"write_live_action"}
+
+
+def _py_files(root: Path) -> list[Path]:
+ return [p for p in root.rglob("*.py") if "__pycache__" not in p.parts]
+
+
+def test_no_self_authorization_named_function_in_live() -> None:
+ offenders: list[str] = []
+ for path in _py_files(LIVE_DIR):
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ for node in ast.walk(tree):
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ if node.name in _NAME_ALLOWLIST:
+ continue
+ if _FORBIDDEN_NAME.match(node.name):
+ offenders.append(f"{path.name}:{node.name}")
+ assert not offenders, f"forbidden mandate-write function names: {offenders}"
+
+
+def test_store_exposes_no_write_symbol() -> None:
+ public = [name for name in dir(store) if not name.startswith("_")]
+ for forbidden in ("save_mandate", "set_mandate", "write_mandate", "update_mandate"):
+ assert forbidden not in public, f"{forbidden} must not exist in the store module"
+ # The only public callable is the read-only loader.
+ assert "load_mandate" in public
+
+
+def test_agent_reachable_modules_never_open_mandate_for_write() -> None:
+ """No agent-importable live module opens the mandate file in a write mode."""
+ reachable = [
+ LIVE_DIR / "order_guard.py",
+ LIVE_DIR / "enforcement.py",
+ LIVE_DIR / "extractors" / "__init__.py",
+ LIVE_DIR / "extractors" / "robinhood.py",
+ LIVE_DIR / "mandate" / "store.py",
+ ]
+ write_modes = {"w", "wb", "a", "ab", "w+", "r+", "x"}
+ offenders: list[str] = []
+ for path in reachable:
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ func = node.func
+ is_open = (isinstance(func, ast.Name) and func.id == "open") or (
+ isinstance(func, ast.Attribute) and func.attr == "open"
+ )
+ if not is_open:
+ continue
+ # mode may be positional[1] or keyword 'mode'
+ mode = None
+ if len(node.args) >= 2 and isinstance(node.args[1], ast.Constant):
+ mode = node.args[1].value
+ for kw in node.keywords:
+ if kw.arg == "mode" and isinstance(kw.value, ast.Constant):
+ mode = kw.value.value
+ if isinstance(mode, str) and mode in write_modes:
+ # Allowed: trade_counter.json writes in order_guard (NOT the mandate).
+ src_seg = ast.get_source_segment(path.read_text(encoding="utf-8"), node) or ""
+ offenders.append(f"{path.name}: open(..., {mode!r}) [{src_seg[:60]}]")
+ # order_guard writes trade_counter.json via Path.write_text/replace, not open();
+ # the only open() write any reachable module performs would be a violation.
+ assert not offenders, f"agent-reachable write opens found: {offenders}"
+
+
+def test_registry_has_no_mandate_write_tool() -> None:
+ """The assembled tool registry exposes no tool that can write a mandate."""
+ from src.tools import build_registry
+
+ registry = build_registry()
+ names = list(getattr(registry, "_tools", {}).keys())
+ for name in names:
+ assert not _FORBIDDEN_NAME.match(name), f"tool {name!r} matches forbidden write regex"
+ assert "set_mandate" not in name and "commit_mandate" not in name
diff --git a/agent/tests/test_oauth_token_cache.py b/agent/tests/test_oauth_token_cache.py
new file mode 100644
index 000000000..7d58f7f23
--- /dev/null
+++ b/agent/tests/test_oauth_token_cache.py
@@ -0,0 +1,261 @@
+"""Unit tests for the OAuth token cache backend (``_build_token_store``).
+
+These guard the security-critical invariants of the live-channel token cache:
+
+* The cache directory is created ``0700`` and ``~`` is expanded.
+* Tokens survive a fresh store instance (persistence round-trip) and are read
+ back from disk, never from constructor args or process memory alone.
+* A cached token never appears in any log record or in the OAuth transport's
+ request-bound payload.
+* The store rejects path-escape keys (defense-in-depth on the cache root).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import os
+import stat
+from pathlib import Path
+
+import pytest
+
+from src.tools.mcp import _build_token_store
+
+pytestmark = pytest.mark.unit
+
+
+def test_build_token_store_creates_dir_0700(tmp_path: Path) -> None:
+ cache = tmp_path / "oauth"
+ assert not cache.exists()
+
+ _build_token_store(str(cache))
+
+ assert cache.is_dir()
+ mode = stat.S_IMODE(os.stat(cache).st_mode)
+ assert mode == 0o700, f"expected owner-only 0700, got {oct(mode)}"
+
+
+def test_build_token_store_expands_user(monkeypatch, tmp_path: Path) -> None:
+ fake_home = tmp_path / "home"
+ fake_home.mkdir()
+ monkeypatch.setenv("HOME", str(fake_home))
+
+ _build_token_store("~/.vibe-trading/live/robinhood/oauth")
+
+ resolved = fake_home / ".vibe-trading" / "live" / "robinhood" / "oauth"
+ assert resolved.is_dir()
+
+
+def test_build_token_store_idempotent_on_existing_dir(tmp_path: Path) -> None:
+ cache = tmp_path / "oauth"
+ _build_token_store(str(cache))
+ # Second call must not raise on an already-existing directory.
+ _build_token_store(str(cache))
+ assert stat.S_IMODE(os.stat(cache).st_mode) == 0o700
+
+
+def test_token_persists_across_store_instances(tmp_path: Path) -> None:
+ cache = tmp_path / "oauth"
+ token_value = {"access_token": "secret-abc", "refresh_token": "secret-refresh"}
+
+ async def _roundtrip() -> dict | None:
+ writer = _build_token_store(str(cache))
+ await writer.put(collection="robinhood", key="tokens", value=token_value)
+ # A brand-new store instance must read the token back from disk.
+ reader = _build_token_store(str(cache))
+ return await reader.get(collection="robinhood", key="tokens")
+
+ read_back = asyncio.run(_roundtrip())
+ assert read_back == token_value
+
+
+def test_token_value_never_in_args_or_payload(tmp_path: Path) -> None:
+ """The token lives only on disk — it is never passed via constructor args.
+
+ ``_build_token_store`` receives only a directory path; the secret token is
+ written/read through the async store API, so the secret can never leak from
+ the factory's positional/keyword arguments.
+ """
+ cache = tmp_path / "oauth"
+ store = _build_token_store(str(cache))
+
+ # The factory's only input is the directory; no token material is bound to
+ # the returned store object's public surface as plaintext.
+ repr_text = repr(store)
+ assert "secret" not in repr_text.lower()
+
+
+def test_token_never_logged(tmp_path: Path, caplog) -> None:
+ cache = tmp_path / "oauth"
+ secret = "token-must-not-be-logged-xyz"
+
+ async def _write() -> None:
+ store = _build_token_store(str(cache))
+ await store.put(collection="robinhood", key="tokens", value={"access_token": secret})
+
+ with caplog.at_level(logging.DEBUG):
+ # Building the store must not log the cache path's token contents, and
+ # writing a token must not emit it to any logger.
+ asyncio.run(_write())
+
+ for record in caplog.records:
+ assert secret not in record.getMessage()
+
+
+def test_store_rejects_path_escape_key(tmp_path: Path) -> None:
+ """FileTreeStore fails closed when a key would escape the cache root."""
+ from key_value.aio.errors.store import PathSecurityError
+
+ cache = tmp_path / "oauth"
+ store = _build_token_store(str(cache))
+
+ async def _write_escape() -> None:
+ await store.put(collection="robinhood", key="../../escape", value={"x": 1})
+
+ with pytest.raises(PathSecurityError):
+ asyncio.run(_write_escape())
+
+ # Nothing leaked outside the cache root.
+ assert not (tmp_path / "escape").exists()
+ assert not (tmp_path.parent / "escape").exists()
+
+
+# --------------------------------------------------------------------------- #
+# SPEC §7.4: token never in audit / envelopes, not accepted from args,
+# cache-expiry surfaces re-auth (no silent call with a stale token).
+# --------------------------------------------------------------------------- #
+
+_OAUTH_SECRET = "rh-access-token-MUST-NOT-LEAK-123"
+
+
+def test_token_never_in_audit_payload() -> None:
+ """A token in a broker request/response is redacted in the audit record.
+
+ The live-action audit ledger scrubs credential keys via
+ ``redact_payload`` before any sink write (SPEC §5/§7.4), so an OAuth token
+ that rides a raw broker payload never reaches the ledger / trace / SSE bus.
+ """
+ from src.live.audit import LiveActionEvent
+
+ event = LiveActionEvent(
+ kind="order_placed",
+ session_id="s1",
+ outcome="accepted",
+ server="robinhood",
+ remote_tool="place_order",
+ broker_request={"symbol": "AAPL", "access_token": _OAUTH_SECRET},
+ broker_response={"order_id": "rh_x", "authorization": _OAUTH_SECRET},
+ )
+
+ record = event.to_record()
+
+ flat = json.dumps(record)
+ assert _OAUTH_SECRET not in flat, "OAuth token leaked into the audit record"
+ assert record["broker_request"]["access_token"] == "[redacted]"
+ assert record["broker_response"]["authorization"] == "[redacted]"
+ # The non-secret intent survives.
+ assert record["broker_request"]["symbol"] == "AAPL"
+
+
+def test_token_not_accepted_from_tool_args_or_variables() -> None:
+ """A token injected via tool args is stripped before reaching the broker.
+
+ ``MCPRemoteTool._filter_arguments`` projects kwargs down to the remote
+ tool's declared schema. A live channel's order tool declares its real
+ fields; an injected ``access_token`` / ``authorization`` (the
+ caller-injection / prompt-injection vector, SPEC §3 (b)) is not a declared
+ field and is dropped, so it never forwards to Robinhood. The OAuth provider
+ owns the Authorization header at the transport layer — the agent cannot
+ supply a token through the call surface.
+ """
+ from src.tools.mcp import MCPRemoteTool, MCPRemoteToolSpec
+
+ spec = MCPRemoteToolSpec(
+ server_name="robinhood",
+ remote_name="place_order",
+ local_name="mcp_robinhood_place_order",
+ description="place an order",
+ parameters={
+ "type": "object",
+ "properties": {
+ "symbol": {"type": "string"},
+ "side": {"type": "string"},
+ "quantity": {"type": "number"},
+ },
+ "required": ["symbol", "side"],
+ "additionalProperties": False,
+ },
+ )
+ tool = MCPRemoteTool(adapter=object(), spec=spec)
+
+ filtered = tool._filter_arguments(
+ {
+ "symbol": "AAPL",
+ "side": "buy",
+ "quantity": 1,
+ # Injection attempts via tool args / variables:
+ "access_token": _OAUTH_SECRET,
+ "authorization": _OAUTH_SECRET,
+ "token": _OAUTH_SECRET,
+ }
+ )
+
+ assert filtered == {"symbol": "AAPL", "side": "buy", "quantity": 1}
+ assert _OAUTH_SECRET not in json.dumps(filtered)
+
+
+def test_cache_expiry_surfaces_reauth_no_silent_stale_call() -> None:
+ """An expired/revoked refresh token surfaces an error, not a silent call.
+
+ When the OAuth provider cannot refresh (revoked/expired refresh token,
+ headless), the failure propagates through the adapter's normal error
+ envelope (``{"status": "error", ...}``) — there is NO ``status: "ok"``
+ result returned off a stale token (SPEC Transport §5 / §7.4). The mutating
+ path must NOT be retried either (no duplicate side effect).
+ """
+ from fastmcp.exceptions import McpError
+ from mcp import types as mcp_types
+
+ from src.config.schema import MCPServerConfig
+ from src.tools.mcp import MCPServerAdapter
+
+ # 401 Unauthorized → an auth failure the provider could not silently refresh.
+ auth_error = McpError(
+ mcp_types.ErrorData(code=-32001, message="401 Unauthorized: token expired, re-auth required")
+ )
+
+ call_count = {"n": 0}
+
+ class _ExpiredAuthClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb) -> None:
+ return None
+
+ async def list_tools(self):
+ return []
+
+ async def call_tool(self, name, arguments=None, *, timeout=None, raise_on_error=False):
+ call_count["n"] += 1
+ raise auth_error
+
+ cfg = MCPServerConfig.model_validate(
+ {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "auth": {"type": "oauth", "scopes": ["trading.read"]},
+ "enabled_tools": ["place_order"],
+ }
+ )
+ adapter = MCPServerAdapter("robinhood", cfg, client_factory=_ExpiredAuthClient)
+
+ result = adapter.call_tool("place_order", {"symbol": "AAPL", "side": "buy"})
+
+ # Surfaced as an error envelope — never a silent success off a stale token.
+ assert result["status"] == "error"
+ assert "401" in result["error"] or "re-auth" in result["error"].lower() or "expired" in result["error"].lower()
+ # Mutating call must NOT be retried (no duplicate order side effect).
+ assert call_count["n"] == 1
diff --git a/agent/tests/test_readonly_default.py b/agent/tests/test_readonly_default.py
new file mode 100644
index 000000000..cc7b453c9
--- /dev/null
+++ b/agent/tests/test_readonly_default.py
@@ -0,0 +1,313 @@
+"""Live channel OFF-by-default + read-only-default invariants (SPEC §7.4).
+
+This gate encodes the four SPEC invariants end to end:
+
+1. The seeded ``robinhood`` config's ``enabled_tools`` contains EXACTLY the
+ curated READ tool names (and never ``"*"``). This is the structural defense
+ that catches finding #1 (seed/map name mismatch): a name here that the
+ curated map does not classify READ would classify UNKNOWN -> gated -> refused
+ and the real read would be filtered out.
+2. The config-load validator rejects ``enabled_tools=["*"]`` for a live broker.
+3. With the seed (READ-only) allowlist, the order-placing tools are ABSENT from
+ the assembled wrappers — the allowlist filters them at discovery before
+ classification ever runs (OFF-by-default).
+4. After the user allowlists the WRITE tool names AND a mandate is committed, the
+ order tools APPEAR and are gate-wrapped (:class:`LiveOrderGuardTool`).
+
+Reuses the mock-MCP ``client_factory`` seam (``src.tools.mcp``) so no Robinhood
+access is required.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastmcp.client.client import CallToolResult
+from mcp import types as mcp_types
+
+import src.live.paths as paths
+from src.config.schema import (
+ LIVE_BROKER_SERVER_KEYS,
+ AgentConfig,
+ MCPServerConfig,
+ ROBINHOOD_MCP_SERVER_SEED,
+)
+from src.live.mandate.model import MANDATE_SCHEMA_VERSION
+from src.live.order_guard import LiveOrderGuardTool
+from src.live.registry import is_live_broker, wrap_live_broker_tools
+from src.live.robinhood_classification import ROBINHOOD_TOOL_CLASS
+from src.live.classification import ToolClass
+from src.tools.mcp import MCPRemoteTool, build_mcp_tool_wrappers
+
+pytestmark = pytest.mark.unit
+
+# The full Robinhood catalog a mock server would expose (4 READ + 2 WRITE).
+_CATALOG = ("get_account", "get_positions", "get_quotes", "list_orders", "place_order", "cancel_order")
+
+
+class _FakeClient:
+ """Mock MCP client exposing the full Robinhood catalog."""
+
+ async def __aenter__(self) -> "_FakeClient":
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb) -> None:
+ return None
+
+ async def list_tools(self) -> list[mcp_types.Tool]:
+ return [
+ mcp_types.Tool(name=name, description=f"remote {name}", inputSchema={"type": "object"})
+ for name in _CATALOG
+ ]
+
+ async def call_tool(self, name: str, arguments=None, *, timeout=None, raise_on_error=False) -> CallToolResult: # noqa: D401
+ raise AssertionError("registry assembly must not call tools")
+
+
+def _factory() -> _FakeClient:
+ return _FakeClient()
+
+
+def _assemble(enabled_tools: list[str]) -> list[MCPRemoteTool]:
+ """Discover + live-wrap the robinhood channel for a given allowlist."""
+ cfg = MCPServerConfig.model_validate(
+ {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "auth": {"type": "oauth", "scopes": ["trading.read"]},
+ "enabled_tools": enabled_tools,
+ }
+ )
+ wrappers = build_mcp_tool_wrappers("robinhood", cfg, client_factory=_factory)
+ assert is_live_broker("robinhood", cfg.url)
+ return wrap_live_broker_tools("robinhood", wrappers, url=cfg.url)
+
+
+def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)
+ return tmp_path
+
+
+def _commit_mandate(live_runtime: Path) -> None:
+ broker = live_runtime / "live" / "robinhood"
+ broker.mkdir(parents=True, exist_ok=True)
+ created = datetime.now(timezone.utc)
+ payload = {
+ "schema_version": MANDATE_SCHEMA_VERSION,
+ "hard_caps": {
+ "account_funding_usd": 5000.0,
+ "max_order_notional_usd": 750.0,
+ "max_total_exposure_usd": 5000.0,
+ "max_leverage": 1.0,
+ "allowed_instruments": ["equity", "etf"],
+ "max_trades_per_day": 5,
+ },
+ "universe": {
+ "asset_classes": ["us_equity", "us_etf"],
+ "min_market_cap_usd": None,
+ "min_avg_daily_volume_usd": None,
+ "exclude_symbols": [],
+ },
+ "consent": {
+ "created_at": created.isoformat(),
+ "consent_token_sha256": "deadbeef",
+ "broker": "robinhood",
+ "account_ref": "acct_ref",
+ "expires_at": (created + timedelta(days=30)).isoformat(),
+ },
+ }
+ (broker / "mandate.json").write_text(json.dumps(payload), encoding="utf-8")
+
+
+# --- Invariant 1: seed allowlist == curated READ names (catches finding #1) ---
+
+
+def test_seed_enabled_tools_are_exactly_curated_read_names() -> None:
+ curated_reads = {
+ name for name, cls in ROBINHOOD_TOOL_CLASS.items() if cls is ToolClass.READ
+ }
+ seed = set(ROBINHOOD_MCP_SERVER_SEED["enabled_tools"])
+ assert seed == curated_reads, (
+ "seeded enabled_tools must equal the curated READ names exactly; a "
+ "mismatch silently hides real reads / refuses them as UNKNOWN"
+ )
+ # And every seeded name classifies READ in the curated map (no UNKNOWN).
+ for name in seed:
+ assert ROBINHOOD_TOOL_CLASS.get(name) is ToolClass.READ
+
+
+def test_seed_never_uses_wildcard() -> None:
+ assert "*" not in ROBINHOOD_MCP_SERVER_SEED["enabled_tools"]
+ assert ROBINHOOD_MCP_SERVER_SEED["enabled_tools"] # non-empty
+
+
+# --- Invariant 2: validator rejects "*" for a live broker ---
+
+
+def test_validator_rejects_wildcard_for_live_broker() -> None:
+ with pytest.raises(ValueError, match="wildcard"):
+ AgentConfig.model_validate(
+ {
+ "mcpServers": {
+ "robinhood": {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "auth": {"type": "oauth"},
+ "enabledTools": ["*"],
+ }
+ }
+ }
+ )
+ assert "robinhood" in LIVE_BROKER_SERVER_KEYS
+
+
+def test_validator_rejects_wildcard_for_aliased_live_broker_url() -> None:
+ # H8: a Robinhood URL under a non-canonical key must still be rejected.
+ with pytest.raises(ValueError, match="wildcard"):
+ AgentConfig.model_validate(
+ {
+ "mcpServers": {
+ "rh": {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "auth": {"type": "oauth"},
+ "enabledTools": ["*"],
+ }
+ }
+ }
+ )
+
+
+# --- Invariant 3: no mandate / READ-only seed -> order tools absent ---
+
+
+def test_order_tools_absent_with_seed_allowlist() -> None:
+ """The seeded READ-only allowlist keeps WRITE tools out of the registry."""
+ tools = _assemble(list(ROBINHOOD_MCP_SERVER_SEED["enabled_tools"]))
+ names = {t._spec.remote_name for t in tools}
+ assert names == set(ROBINHOOD_MCP_SERVER_SEED["enabled_tools"])
+ assert "place_order" not in names
+ assert "cancel_order" not in names
+ # Every surviving tool is a plain read-only MCPRemoteTool (no gate).
+ assert all(type(t) is MCPRemoteTool and t.is_readonly for t in tools)
+ assert not any(isinstance(t, LiveOrderGuardTool) for t in tools)
+
+
+# --- Invariant 4: write allowlisted + mandate committed -> gated tools appear ---
+
+
+def test_order_tools_appear_gate_wrapped_when_allowlisted(live_runtime: Path) -> None:
+ _commit_mandate(live_runtime)
+ enabled = list(ROBINHOOD_MCP_SERVER_SEED["enabled_tools"]) + ["place_order", "cancel_order"]
+ tools = _assemble(enabled)
+ by_name = {t._spec.remote_name: t for t in tools}
+
+ assert "place_order" in by_name and "cancel_order" in by_name
+ assert isinstance(by_name["place_order"], LiveOrderGuardTool)
+ assert isinstance(by_name["cancel_order"], LiveOrderGuardTool)
+ assert by_name["place_order"].broker == "robinhood"
+ # Reads stay plain read-only.
+ assert type(by_name["get_account"]) is MCPRemoteTool
+ assert by_name["get_account"].is_readonly is True
+
+
+# --- H8: a Robinhood URL under an aliased key is still a live broker ----------
+
+
+def test_aliased_key_with_robinhood_url_is_gated() -> None:
+ """A Robinhood agentic URL parked under key 'rh' is gated + broker-resolved."""
+ from src.config.schema import MCPServerConfig
+
+ assert is_live_broker("rh", "https://agent.robinhood.com/mcp/trading")
+ assert not is_live_broker("rh", "https://example.test/mcp")
+
+ cfg = MCPServerConfig.model_validate(
+ {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "auth": {"type": "oauth"},
+ "enabled_tools": ["get_positions", "place_order"],
+ }
+ )
+ wrappers = build_mcp_tool_wrappers("rh", cfg, client_factory=_factory)
+ gated = wrap_live_broker_tools("rh", wrappers, url=cfg.url)
+ by_name = {t._spec.remote_name: t for t in gated}
+
+ assert isinstance(by_name["place_order"], LiveOrderGuardTool)
+ # Broker namespace resolves to the real broker, not the alias.
+ assert by_name["place_order"].broker == "robinhood"
+ assert type(by_name["get_positions"]) is MCPRemoteTool
+
+
+def test_lookalike_host_is_not_a_live_broker() -> None:
+ """A substring/lookalike host must NOT match (no false positive)."""
+ assert not is_live_broker("rh", "https://robinhood.com.evil.test/mcp")
+
+
+# --- M1: registration-time halt omits order tools (defense-in-depth) ----------
+
+
+def test_halt_omits_order_tools_at_registration(live_runtime: Path) -> None:
+ from src.live.halt import trip_halt
+
+ _commit_mandate(live_runtime)
+ trip_halt(by="test", reason="reg-time halt", broker="robinhood")
+
+ enabled = list(ROBINHOOD_MCP_SERVER_SEED["enabled_tools"]) + ["place_order", "cancel_order"]
+ tools = _assemble(enabled)
+ names = {t._spec.remote_name for t in tools}
+
+ # Order tools are not even present in the assembled list.
+ assert "place_order" not in names
+ assert "cancel_order" not in names
+ assert not any(isinstance(t, LiveOrderGuardTool) for t in tools)
+ # Read tools survive a halt.
+ assert "get_account" in names
+ assert all(t.is_readonly for t in tools)
+
+
+# --- H7: headless / no-token live channel is skipped, TTY registers ----------
+
+
+def test_should_register_live_channel_headless_no_token(live_runtime: Path) -> None:
+ from src.live.registry import should_register_live_channel
+
+ cache = str(live_runtime / "live" / "robinhood" / "oauth")
+ url = "https://agent.robinhood.com/mcp/trading"
+
+ # Non-interactive + no cached token -> skip (do not block on a browser).
+ assert should_register_live_channel(interactive=False, url=url, cache_dir=cache) is False
+ # Interactive TTY -> register so first-run authorize works.
+ assert should_register_live_channel(interactive=True, url=url, cache_dir=cache) is True
+
+
+def test_should_register_live_channel_headless_with_cached_token(live_runtime: Path) -> None:
+ import asyncio
+
+ from src.live.registry import has_cached_oauth_token, should_register_live_channel
+ from src.tools.mcp import _build_token_store
+
+ cache = str(live_runtime / "live" / "robinhood" / "oauth")
+ url = "https://agent.robinhood.com/mcp/trading"
+
+ # Seed a token entry the way FastMCP's FileTreeStore lays one out: a file
+ # under the <cache>/mcp-oauth-token/ collection directory. (A slash-free key
+ # is used because that is how an entry actually materializes on disk.)
+ async def _seed_token() -> None:
+ store = _build_token_store(cache)
+ await store.put(
+ collection="mcp-oauth-token",
+ key="cached_tokens",
+ value={"access_token": "cached"},
+ )
+
+ asyncio.run(_seed_token())
+
+ assert has_cached_oauth_token(url, cache) is True
+ # With a cached token, even a non-interactive run registers the channel.
+ assert should_register_live_channel(interactive=False, url=url, cache_dir=cache) is True
diff --git a/agent/tests/test_redaction_shared.py b/agent/tests/test_redaction_shared.py
new file mode 100644
index 000000000..d62f2adb9
--- /dev/null
+++ b/agent/tests/test_redaction_shared.py
@@ -0,0 +1,141 @@
+"""Shared redaction helpers promoted from the swarm worker (#142 → public).
+
+Covers ``redact_payload`` (recursive sensitive-key scrubbing) and
+``is_sensitive_arg`` (key-name classification), now consumed by the swarm
+worker and the live-action audit ledger from one module.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from src.tools.redaction import is_sensitive_arg, redact_payload
+
+
+ "key",
+ [
+ "api_key",
+ "Authorization",
+ " TOKEN ",
+ "password",
+ "passphrase",
+ "secret",
+ "headers",
+ "content",
+ "env",
+ "api_token", # marker substring
+ "access_token", # marker substring
+ "x-authorization", # marker substring
+ "client_secret", # marker substring
+ ],
+)
+def test_is_sensitive_arg_matches(key: str) -> None:
+ assert is_sensitive_arg(key) is True
+
+
+ "key",
+ [
+ "account_number",
+ "account_id",
+ "account_no",
+ "account_num",
+ "brokerage_account_number",
+ "account_url",
+ "rhs_account_number",
+ "ssn",
+ "social_security_number",
+ "tax_id",
+ "taxpayer_id",
+ "tin",
+ "routing_number",
+ "bank_account_number",
+ " Account_Number ", # normalized (stripped, lower-cased)
+ ],
+)
+def test_is_sensitive_arg_matches_account_pii(key: str) -> None:
+ """H1: curated exact account/PII field names redact."""
+ assert is_sensitive_arg(key) is True
+
+
[email protected]("key", ["symbol", "side", "quantity", "url", "path", "query"])
+def test_is_sensitive_arg_allows_benign_keys(key: str) -> None:
+ assert is_sensitive_arg(key) is False
+
+
+ "key",
+ [
+ "account_ref", # opaque provenance — SPEC §5 accountability chain
+ "account", # broad token must NOT trip exact-match PII set
+ "account_balance",
+ "account_type",
+ "account_status",
+ "accounts",
+ ],
+)
+def test_is_sensitive_arg_preserves_account_ref_and_benign_account_fields(
+ key: str,
+) -> None:
+ """Exact-match (not substring) PII keys keep ``account_ref`` and other
+ benign ``account*`` fields readable, preventing over-redaction."""
+ assert is_sensitive_arg(key) is False
+
+
+def test_redact_payload_keeps_account_ref_provenance() -> None:
+ """``account_ref`` provenance survives while sibling account numbers/SSN are
+ scrubbed (SPEC §5 mandate→consent chain)."""
+ out = redact_payload(
+ {
+ "account_ref": "rh_ref_opaque",
+ "account_number": "5XX111",
+ "ssn": "123-45-6789",
+ "symbol": "NVDA",
+ }
+ )
+ assert out == {
+ "account_ref": "rh_ref_opaque",
+ "account_number": "[redacted]",
+ "ssn": "[redacted]",
+ "symbol": "NVDA",
+ }
+
+
+def test_redact_payload_scrubs_top_level_sensitive_keys() -> None:
+ out = redact_payload(
+ {"symbol": "NVDA", "authorization": "Bearer rh-oauth-token", "qty": 3}
+ )
+ assert out == {"symbol": "NVDA", "authorization": "[redacted]", "qty": 3}
+
+
+def test_redact_payload_recurses_into_nested_structures() -> None:
+ payload = {
+ "broker_request": {"symbol": "AAPL", "headers": {"Authorization": "secret"}},
+ "orders": [
+ {"id": 1, "access_token": "leak"},
+ {"id": 2, "note": "ok"},
+ ],
+ }
+ out = redact_payload(payload)
+ assert out == {
+ "broker_request": {"symbol": "AAPL", "headers": "[redacted]"},
+ "orders": [
+ {"id": 1, "access_token": "[redacted]"},
+ {"id": 2, "note": "ok"},
+ ],
+ }
+
+
+def test_redact_payload_does_not_mutate_input() -> None:
+ payload = {"token": "abc", "nested": [{"secret": "x"}]}
+ out = redact_payload(payload)
+ assert payload == {"token": "abc", "nested": [{"secret": "x"}]}
+ assert out["token"] == "[redacted]"
+ assert out["nested"][0]["secret"] == "[redacted]"
+
+
+def test_redact_payload_passes_through_scalars() -> None:
+ assert redact_payload("plain string") == "plain string"
+ assert redact_payload(42) == 42
+ assert redact_payload(None) is None
diff --git a/agent/tests/test_runtime_flatten.py b/agent/tests/test_runtime_flatten.py
new file mode 100644
index 000000000..114008087
--- /dev/null
+++ b/agent/tests/test_runtime_flatten.py
@@ -0,0 +1,208 @@
+"""Tests for the preemptive kill-switch sweep (src/live/runtime/flatten.py).
+
+SPEC §7.5 component 6. Verifies cancel-then-flatten ordering, the cancel-only
+default when the mandate forbids flatten, the no-retry-on-error contract
+(SPEC §8.5), and that every broker call is audited.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from src.live import audit, paths
+from src.live.runtime import flatten
+
+
+class _Broker:
+ """In-memory broker stub recording the order of injected calls."""
+
+ def __init__(
+ self,
+ open_orders: list[dict[str, Any]],
+ positions: list[dict[str, Any]],
+ fail_on: set[str] | None = None,
+ ) -> None:
+ self._open_orders = open_orders
+ self._positions = positions
+ self._fail_on = fail_on or set()
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+
+ def read_open_orders(self) -> list[dict[str, Any]]:
+ return list(self._open_orders)
+
+ def read_positions(self) -> list[dict[str, Any]]:
+ return list(self._positions)
+
+ def submit(self, request: dict[str, Any]) -> dict[str, Any]:
+ action = request.get("action", "")
+ key = request.get("order_id") or request.get("symbol") or action
+ self.calls.append((action, request))
+ if key in self._fail_on:
+ raise RuntimeError(f"broker rejected {key}")
+ return {"state": "accepted", "echo": key}
+
+
+def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Point the live runtime root at an isolated tmp dir."""
+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)
+ return tmp_path
+
+
+def _read_ledger() -> list[dict[str, Any]]:
+ path = audit.audit_ledger_path()
+ if not path.exists():
+ return []
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()]
+
+
+def test_cancel_only_default_when_mandate_absent(live_runtime: Path) -> None:
+ # No mandate on file → fail-closed to cancel-only; positions untouched.
+ broker = _Broker(
+ open_orders=[{"order_id": "o1"}, {"order_id": "o2"}],
+ positions=[{"symbol": "NVDA", "qty": 3}],
+ )
+ report = flatten.flatten_and_cancel(
+ "robinhood", broker.submit, broker.read_positions, broker.read_open_orders
+ )
+ assert report["cancelled_order_ids"] == ["o1", "o2"]
+ assert report["flatten_orders_submitted"] == []
+ assert report["flatten_skipped_reason"] is not None
+ # Only cancels were submitted — no flatten/close calls.
+ assert all(action == "cancel" for action, _ in broker.calls)
+
+
+def test_cancel_then_flatten_order(live_runtime: Path) -> None:
+ broker = _Broker(
+ open_orders=[{"order_id": "o1"}],
+ positions=[{"symbol": "NVDA", "qty": 3}, {"symbol": "AAPL", "qty": -2}],
+ )
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ broker.read_open_orders,
+ allow_flatten=True,
+ )
+ # Cancels MUST precede flattens.
+ actions = [action for action, _ in broker.calls]
+ assert actions == ["cancel", "close", "close"]
+ assert report["cancelled_order_ids"] == ["o1"]
+ submitted = report["flatten_orders_submitted"]
+ # Long closed by sell, short closed by buy.
+ by_symbol = {s["symbol"]: s for s in submitted}
+ assert by_symbol["NVDA"]["side"] == "sell" and by_symbol["NVDA"]["qty"] == 3
+ assert by_symbol["AAPL"]["side"] == "buy" and by_symbol["AAPL"]["qty"] == 2
+ assert report["flatten_skipped_reason"] is None
+
+
+def test_zero_qty_position_skipped(live_runtime: Path) -> None:
+ broker = _Broker(open_orders=[], positions=[{"symbol": "GME", "qty": 0}])
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ broker.read_open_orders,
+ allow_flatten=True,
+ )
+ assert report["flatten_orders_submitted"] == []
+ assert broker.calls == []
+
+
+def test_errored_cancel_is_not_retried(live_runtime: Path) -> None:
+ broker = _Broker(
+ open_orders=[{"order_id": "o1"}, {"order_id": "o2"}],
+ positions=[],
+ fail_on={"o1"},
+ )
+ report = flatten.flatten_and_cancel(
+ "robinhood", broker.submit, broker.read_positions, broker.read_open_orders
+ )
+ # o1 failed once and was NOT retried; o2 still cancelled.
+ assert [r for r in broker.calls if r[1].get("order_id") == "o1"] == [
+ ("cancel", {"action": "cancel", "order_id": "o1"})
+ ]
+ assert report["cancelled_order_ids"] == ["o2"]
+ assert report["errors"] == [
+ {"phase": "cancel", "order_id": "o1", "error": "broker rejected o1"}
+ ]
+
+
+def test_errored_flatten_is_not_retried(live_runtime: Path) -> None:
+ broker = _Broker(
+ open_orders=[],
+ positions=[{"symbol": "NVDA", "qty": 3}, {"symbol": "AAPL", "qty": 1}],
+ fail_on={"NVDA"},
+ )
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ broker.read_open_orders,
+ allow_flatten=True,
+ )
+ nvda_calls = [r for r in broker.calls if r[1].get("symbol") == "NVDA"]
+ assert len(nvda_calls) == 1 # errored once, not retried
+ assert [s["symbol"] for s in report["flatten_orders_submitted"]] == ["AAPL"]
+ assert report["errors"] == [
+ {"phase": "flatten", "symbol": "NVDA", "error": "broker rejected NVDA"}
+ ]
+
+
+def test_every_action_is_audited(live_runtime: Path) -> None:
+ broker = _Broker(
+ open_orders=[{"order_id": "o1"}],
+ positions=[{"symbol": "NVDA", "qty": 2}],
+ fail_on={"o1"},
+ )
+ flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ broker.read_open_orders,
+ allow_flatten=True,
+ )
+ records = _read_ledger()
+ # One audit per broker call: failed cancel (rejected) + accepted flatten.
+ kinds = sorted(r["kind"] for r in records)
+ assert kinds == ["order_placed", "order_rejected"]
+ rejected = next(r for r in records if r["kind"] == "order_rejected")
+ assert rejected["remote_tool"] == "cancel_order"
+ assert rejected["outcome"] == "error"
+ assert rejected["error"] == "broker rejected o1"
+ placed = next(r for r in records if r["kind"] == "order_placed")
+ assert placed["remote_tool"] == "place_order"
+ assert placed["outcome"] == "accepted"
+ assert placed["server"] == "robinhood"
+
+
+def test_read_failure_recorded_not_raised(live_runtime: Path) -> None:
+ def boom_orders() -> list[dict[str, Any]]:
+ raise RuntimeError("read failed")
+
+ broker = _Broker(open_orders=[], positions=[])
+ report = flatten.flatten_and_cancel(
+ "robinhood", broker.submit, broker.read_positions, boom_orders
+ )
+ assert {"phase": "read_open_orders", "error": "read failed"} in report["errors"]
+
+
+def test_mandate_flatten_flag_honored(
+ live_runtime: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # When a (future) mandate exposes a truthy flatten_on_halt, flatten runs
+ # without an explicit allow_flatten override.
+ class _Mandate:
+ flatten_on_halt = True
+
+ monkeypatch.setattr(flatten, "load_mandate", lambda broker: _Mandate())
+ broker = _Broker(open_orders=[], positions=[{"symbol": "NVDA", "qty": 1}])
+ report = flatten.flatten_and_cancel(
+ "robinhood", broker.submit, broker.read_positions, broker.read_open_orders
+ )
+ assert [s["symbol"] for s in report["flatten_orders_submitted"]] == ["NVDA"]
+ assert report["flatten_skipped_reason"] is None
diff --git a/agent/tests/test_runtime_jobstore.py b/agent/tests/test_runtime_jobstore.py
new file mode 100644
index 000000000..2618929ae
--- /dev/null
+++ b/agent/tests/test_runtime_jobstore.py
@@ -0,0 +1,148 @@
+"""Tests for the durable live-runtime job store (src/live/runtime/jobstore.py,
+SPEC.md §7.5 #1).
+
+The store is exercised purely through its public API + the filesystem (the
+runtime root is redirected to a tmp dir). Focus: atomic save round-trips, a
+SIGKILL mid-write can never truncate the real store, a corrupt store is
+quarantined and refuses an empty start, and a genuinely-missing store is the
+only blank-start path.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+from src.live import paths
+from src.live.runtime.jobstore import (
+ CorruptJobStoreError,
+ JobStore,
+ runtime_dir,
+)
+from src.live.runtime.scheduler import Job
+
+
+def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Point the live runtime root at an isolated tmp dir."""
+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)
+ return tmp_path
+
+
+def _job(jid: str = "j1", next_run_at: int = 1000, schedule: str = "interval:60000") -> Job:
+ return Job(id=jid, next_run_at=next_run_at, schedule=schedule, payload={"watch": jid})
+
+
+def test_missing_store_loads_empty(live_runtime: Path) -> None:
+ store = JobStore()
+ assert not store.path.exists()
+ assert store.load() == []
+
+
+def test_save_then_load_roundtrips(live_runtime: Path) -> None:
+ store = JobStore()
+ jobs = [_job("a", 1000), _job("b", 2000, "once")]
+ store.save(jobs)
+
+ loaded = store.load()
+ assert [j.id for j in loaded] == ["a", "b"]
+ assert loaded[0].next_run_at == 1000
+ assert loaded[1].schedule == "once"
+ assert loaded[0].payload == {"watch": "a"}
+
+
+def test_save_creates_runtime_dir_private(live_runtime: Path) -> None:
+ store = JobStore()
+ store.save([_job()])
+ assert runtime_dir().is_dir()
+ # The store file itself was written 0600 (best-effort; POSIX only).
+ if os.name == "posix":
+ assert (os.stat(store.path).st_mode & 0o777) == 0o600
+
+
+def test_save_is_atomic_no_temp_left_behind(live_runtime: Path) -> None:
+ store = JobStore()
+ store.save([_job()])
+ leftovers = list(runtime_dir().glob(".*tmp"))
+ assert leftovers == [], f"temp files leaked: {leftovers}"
+
+
+def test_save_overwrites_in_place(live_runtime: Path) -> None:
+ store = JobStore()
+ store.save([_job("a", 1000)])
+ store.save([_job("a", 9999), _job("c", 1)])
+ loaded = {j.id: j for j in store.load()}
+ assert set(loaded) == {"a", "c"}
+ assert loaded["a"].next_run_at == 9999
+
+
+def test_sigkill_mid_write_leaves_old_store_intact(
+ live_runtime: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A crash during the write (modeled as os.replace raising) must leave the
+ previously-committed store fully readable, never a truncated file."""
+ store = JobStore()
+ store.save([_job("a", 1000)])
+
+ real_replace = os.replace
+
+ def boom(src, dst, *a, **k):
+ # Simulate SIGKILL after the temp is written + fsync'd but before the
+ # atomic rename lands.
+ raise OSError("simulated crash before rename")
+
+ monkeypatch.setattr("src.live.runtime.jobstore.os.replace", boom)
+ with pytest.raises(OSError):
+ store.save([_job("a", 7777), _job("b", 2)])
+ monkeypatch.setattr("src.live.runtime.jobstore.os.replace", real_replace)
+
+ # Old store survives untouched — the half-written attempt never replaced it.
+ loaded = {j.id: j for j in store.load()}
+ assert set(loaded) == {"a"}
+ assert loaded["a"].next_run_at == 1000
+
+
+def test_corrupt_store_quarantined_and_refuses_empty_start(live_runtime: Path) -> None:
+ store = JobStore()
+ store.save([_job("a", 1000)])
+ store.path.write_text("{ this is not valid json", encoding="utf-8")
+
+ with pytest.raises(CorruptJobStoreError) as exc_info:
+ store.load()
+
+ err = exc_info.value
+ # Quarantine file exists and the original is gone (renamed aside).
+ assert err.quarantined.exists()
+ assert err.quarantined.name.startswith("jobs.json.corrupt-")
+ assert not store.path.exists()
+
+
+def test_corrupt_wrong_shape_also_refuses(live_runtime: Path) -> None:
+ store = JobStore()
+ store.path.parent.mkdir(parents=True, exist_ok=True)
+ # Valid JSON but not the expected envelope.
+ store.path.write_text(json.dumps({"nope": []}), encoding="utf-8")
+ with pytest.raises(CorruptJobStoreError):
+ store.load()
+
+
+def test_corrupt_bad_job_field_refuses(live_runtime: Path) -> None:
+ store = JobStore()
+ store.path.parent.mkdir(parents=True, exist_ok=True)
+ store.path.write_text(
+ json.dumps({"jobs": [{"id": "a", "next_run_at": "not-an-int", "schedule": "once"}]}),
+ encoding="utf-8",
+ )
+ with pytest.raises(CorruptJobStoreError):
+ store.load()
+
+
+def test_explicit_path_is_honored(tmp_path: Path) -> None:
+ custom = tmp_path / "nested" / "store.json"
+ store = JobStore(path=custom)
+ store.save([_job("a", 5)])
+ assert custom.is_file()
+ assert JobStore(path=custom).load()[0].id == "a"
diff --git a/agent/tests/test_runtime_liveness.py b/agent/tests/test_runtime_liveness.py
new file mode 100644
index 000000000..9734f76b5
--- /dev/null
+++ b/agent/tests/test_runtime_liveness.py
@@ -0,0 +1,109 @@
+"""Tests for live-runtime runner liveness (src/live/runtime/liveness.py,
+SPEC.md §7.5 #3).
+
+Heartbeat write/read, the alive predicate against a staleness threshold, and
+the stale-runner reaper (borrowed from the swarm reaper shape). All time is
+injected via ``now_ms`` so the tests are deterministic and never sleep; the
+runtime root is redirected to a tmp dir.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from src.live import paths
+from src.live.runtime import liveness
+from src.live.runtime.liveness import (
+ DEFAULT_STALENESS_MS,
+ heartbeats_dir,
+ is_runner_alive,
+ last_tick,
+ reap_stale,
+ write_heartbeat,
+)
+
+
+def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Point the live runtime root at an isolated tmp dir."""
+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)
+ return tmp_path
+
+
+def test_write_then_read_roundtrips(live_runtime: Path) -> None:
+ written = write_heartbeat("runner-1", now_ms=123_456)
+ assert written == 123_456
+ assert last_tick("runner-1") == 123_456
+
+
+def test_last_tick_missing_is_none(live_runtime: Path) -> None:
+ assert last_tick("never-ran") is None
+
+
+def test_write_is_atomic_no_temp_left(live_runtime: Path) -> None:
+ write_heartbeat("r", now_ms=1)
+ leftovers = list(heartbeats_dir().glob(".*tmp"))
+ assert leftovers == []
+
+
+def test_is_runner_alive_fresh(live_runtime: Path) -> None:
+ write_heartbeat("r", now_ms=1_000_000)
+ assert is_runner_alive("r", now_ms=1_000_000 + DEFAULT_STALENESS_MS) is True
+
+
+def test_is_runner_alive_stale(live_runtime: Path) -> None:
+ write_heartbeat("r", now_ms=1_000_000)
+ assert is_runner_alive("r", now_ms=1_000_000 + DEFAULT_STALENESS_MS + 1) is False
+
+
+def test_is_runner_alive_missing_is_false(live_runtime: Path) -> None:
+ assert is_runner_alive("ghost", now_ms=0) is False
+
+
+def test_unreadable_heartbeat_is_not_alive(live_runtime: Path) -> None:
+ write_heartbeat("r", now_ms=1000)
+ # Corrupt the file: a non-integer body reads as no-signal (fail-closed).
+ liveness.heartbeat_path("r").write_text("not-a-number", encoding="utf-8")
+ assert last_tick("r") is None
+ assert is_runner_alive("r", now_ms=1000) is False
+
+
+def test_invalid_runner_id_rejected_on_write(live_runtime: Path) -> None:
+ with pytest.raises(ValueError):
+ write_heartbeat("../escape", now_ms=0)
+ with pytest.raises(ValueError):
+ write_heartbeat("a/b", now_ms=0)
+ with pytest.raises(ValueError):
+ write_heartbeat(" ", now_ms=0)
+
+
+def test_invalid_runner_id_reads_as_none(live_runtime: Path) -> None:
+ # last_tick swallows the ValueError -> no signal.
+ assert last_tick("../escape") is None
+
+
+def test_reap_stale_removes_only_stale(live_runtime: Path) -> None:
+ now = 10_000_000
+ write_heartbeat("fresh", now_ms=now)
+ write_heartbeat("stale", now_ms=now - DEFAULT_STALENESS_MS - 1)
+
+ reaped = reap_stale(now_ms=now)
+ assert reaped == ["stale"]
+ # Fresh heartbeat survives; stale sentinel is gone.
+ assert last_tick("fresh") == now
+ assert last_tick("stale") is None
+
+
+def test_reap_stale_empty_when_no_dir(live_runtime: Path) -> None:
+ assert reap_stale(now_ms=0) == []
+
+
+def test_reap_stale_nothing_when_all_fresh(live_runtime: Path) -> None:
+ now = 5_000
+ write_heartbeat("a", now_ms=now)
+ write_heartbeat("b", now_ms=now)
+ assert reap_stale(now_ms=now) == []
+ assert last_tick("a") == now
+ assert last_tick("b") == now
diff --git a/agent/tests/test_runtime_reconcile.py b/agent/tests/test_runtime_reconcile.py
new file mode 100644
index 000000000..b402fbb63
--- /dev/null
+++ b/agent/tests/test_runtime_reconcile.py
@@ -0,0 +1,313 @@
+"""Tests for crash recovery + position reconciliation (SPEC §7.5 component 5).
+
+Drives each delta class with fabricated broker snapshots (no live broker), and
+asserts the load-bearing invariants:
+
+* classification (matched / unknown_fill / orphan_order / mid_order_ambiguous),
+* ``is_safe`` / ``requires_halt`` derive correctly from the deltas,
+* NO write callable is ever invoked (reconcile only receives READ callables),
+* atomic last-known-state persistence round-trips,
+* an unsafe reconcile does NOT advance (overwrite) the durable state.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any, Mapping, Sequence
+
+import pytest
+
+import src.live.paths as paths
+from src.live.runtime.reconcile import (
+ DeltaKind,
+ ReconcileReport,
+ reconcile,
+)
+
+
+def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Point the live runtime root at an isolated tmp dir (no real ~/.vibe-trading)."""
+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)
+ return tmp_path
+
+
+def _readers(
+ *,
+ positions: Sequence[Mapping[str, Any]] = (),
+ balance: Mapping[str, Any] | None = None,
+ open_orders: Sequence[Mapping[str, Any]] = (),
+):
+ """Build the three injected READ callables from fabricated snapshots."""
+ bal = dict(balance or {"cash_usd": 10_000.0})
+ return (
+ lambda: [dict(p) for p in positions],
+ lambda: dict(bal),
+ lambda: [dict(o) for o in open_orders],
+ )
+
+
+def _seed_state(
+ broker: str,
+ *,
+ open_orders: Sequence[Mapping[str, Any]] = (),
+ positions: Sequence[Mapping[str, Any]] = (),
+ balance: Mapping[str, Any] | None = None,
+) -> Path:
+ """Write a durable last-known runtime_state.json for ``broker`` directly."""
+ path = paths.broker_dir(broker) / "runtime_state.json"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ payload = {
+ "schema_version": 1,
+ "broker": broker,
+ "reconciled_at": "2026-05-29T00:00:00.000+00:00",
+ "open_orders": [dict(o) for o in open_orders],
+ "positions": [dict(p) for p in positions],
+ "balance": dict(balance or {"cash_usd": 10_000.0}),
+ }
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ return path
+
+
+def _kinds(report: ReconcileReport) -> set[str]:
+ return {d.kind for d in report.deltas}
+
+
+# ---------------------------------------------------------------------------
+# Cold start
+# ---------------------------------------------------------------------------
+
+
+def test_cold_start_is_safe_and_persists(live_runtime: Path) -> None:
+ """First run (no prior state) is safe and writes a baseline."""
+ rp, rb, ro = _readers(
+ positions=[{"symbol": "NVDA", "qty": 3}],
+ open_orders=[{"order_id": "o1", "status": "open"}],
+ )
+ report = reconcile("robinhood", rp, rb, ro)
+
+ assert report.had_prior_state is False
+ assert report.is_safe is True
+ assert report.requires_halt is False
+ assert report.state_persisted is True
+ assert (paths.broker_dir("robinhood") / "runtime_state.json").is_file()
+
+
+# ---------------------------------------------------------------------------
+# matched
+# ---------------------------------------------------------------------------
+
+
+def test_matched_order_and_position(live_runtime: Path) -> None:
+ """Recorded order still open + recorded position unchanged == all matched."""
+ _seed_state(
+ "robinhood",
+ open_orders=[{"order_id": "o1", "status": "open", "client_order_id": "c-1"}],
+ positions=[{"symbol": "NVDA", "qty": 3}],
+ )
+ rp, rb, ro = _readers(
+ positions=[{"symbol": "NVDA", "qty": 3}],
+ open_orders=[{"order_id": "o1", "status": "open"}],
+ )
+ report = reconcile("robinhood", rp, rb, ro)
+
+ assert _kinds(report) == {DeltaKind.MATCHED}
+ assert report.is_safe is True
+ assert report.requires_halt is False
+ assert report.had_prior_state is True
+ assert "c-1" in report.recorded_client_order_ids
+
+
+# ---------------------------------------------------------------------------
+# unknown_fill (broker shows a position we never recorded)
+# ---------------------------------------------------------------------------
+
+
+def test_unknown_fill_forces_halt(live_runtime: Path) -> None:
+ """A broker position with no recorded counterpart is an unknown_fill -> halt."""
+ _seed_state("robinhood", positions=[])
+ rp, rb, ro = _readers(positions=[{"symbol": "TSLA", "qty": 10}])
+ report = reconcile("robinhood", rp, rb, ro)
+
+ assert DeltaKind.UNKNOWN_FILL in _kinds(report)
+ assert report.requires_halt is True
+ assert report.is_safe is False
+
+
+def test_unknown_fill_on_quantity_drift(live_runtime: Path) -> None:
+ """A recorded position whose broker qty changed is an unknown_fill."""
+ _seed_state("robinhood", positions=[{"symbol": "NVDA", "qty": 3}])
+ rp, rb, ro = _readers(positions=[{"symbol": "NVDA", "qty": 8}])
+ report = reconcile("robinhood", rp, rb, ro)
+
+ assert DeltaKind.UNKNOWN_FILL in _kinds(report)
+ assert report.requires_halt is True
+
+
+# ---------------------------------------------------------------------------
+# orphan_order (we recorded a CONFIRMED order the broker no longer shows)
+# ---------------------------------------------------------------------------
+
+
+def test_orphan_order_is_safe(live_runtime: Path) -> None:
+ """A confirmed order the broker no longer lists is orphan_order, not a halt."""
+ _seed_state(
+ "robinhood",
+ open_orders=[
+ {"order_id": "o9", "status": "accepted", "client_order_id": "c-9"}
+ ],
+ )
+ rp, rb, ro = _readers(open_orders=[]) # broker shows nothing
+ report = reconcile("robinhood", rp, rb, ro)
+
+ kinds = _kinds(report)
+ assert DeltaKind.ORPHAN_ORDER in kinds
+ assert DeltaKind.MID_ORDER_AMBIGUOUS not in kinds
+ assert report.requires_halt is False
+ assert report.is_safe is True
+ orphan = next(d for d in report.deltas if d.kind == DeltaKind.ORPHAN_ORDER)
+ assert orphan.client_order_id == "c-9"
+ assert orphan.broker is None
+
+
+# ---------------------------------------------------------------------------
+# mid_order_ambiguous (submitted-but-unconfirmed order, broker silent)
+# ---------------------------------------------------------------------------
+
+
+def test_mid_order_ambiguous_forces_halt(live_runtime: Path) -> None:
+ """An unconfirmed (pending, no broker id) recorded order absent from the
+ broker is the dangerous crash case: classified ambiguous -> halt, never resent.
+ """
+ _seed_state(
+ "robinhood",
+ open_orders=[
+ {"client_order_id": "c-pending", "status": "submitted", "symbol": "AAPL"}
+ ],
+ )
+ rp, rb, ro = _readers(open_orders=[]) # broker neither shows it open nor confirms
+ report = reconcile("robinhood", rp, rb, ro)
+
+ kinds = _kinds(report)
+ assert DeltaKind.MID_ORDER_AMBIGUOUS in kinds
+ assert report.requires_halt is True
+ assert report.is_safe is False
+ amb = next(d for d in report.deltas if d.kind == DeltaKind.MID_ORDER_AMBIGUOUS)
+ assert amb.client_order_id == "c-pending"
+ assert "no-retry" in amb.detail
+ # The recorded order is carried so the runner can surface it to a human.
+ assert amb.recorded is not None and amb.recorded.get("client_order_id") == "c-pending"
+
+
+# ---------------------------------------------------------------------------
+# NO write callable is ever invoked
+# ---------------------------------------------------------------------------
+
+
+def test_reconcile_never_invokes_a_write_callable(live_runtime: Path) -> None:
+ """reconcile receives only READ callables; it must never call a writer.
+
+ We pass extra trap callables (place/cancel) and assert they were untouched,
+ proving the no-resend / no-correct invariant structurally.
+ """
+ _seed_state("robinhood", positions=[{"symbol": "NVDA", "qty": 3}])
+
+ calls: list[str] = []
+
+ def trap_write(*_: Any, **__: Any) -> None:
+ calls.append("WRITE")
+ raise AssertionError("reconcile invoked a broker write callable")
+
+ def counting_positions() -> list[dict[str, Any]]:
+ calls.append("read_positions")
+ return [{"symbol": "NVDA", "qty": 3}]
+
+ def counting_balance() -> dict[str, Any]:
+ calls.append("read_balance")
+ return {"cash_usd": 10_000.0}
+
+ def counting_open_orders() -> list[dict[str, Any]]:
+ calls.append("read_open_orders")
+ return []
+
+ # reconcile's signature only accepts the three readers — the trap is never
+ # reachable, which is the point; we still keep a reference to prove intent.
+ _ = trap_write
+ report = reconcile(
+ "robinhood", counting_positions, counting_balance, counting_open_orders
+ )
+
+ assert "WRITE" not in calls
+ assert calls.count("read_positions") == 1
+ assert calls.count("read_balance") == 1
+ assert calls.count("read_open_orders") == 1
+ assert report.is_safe is True
+
+
+# ---------------------------------------------------------------------------
+# atomic persistence round-trips on clean reconcile
+# ---------------------------------------------------------------------------
+
+
+def test_clean_reconcile_persists_broker_truth_roundtrip(live_runtime: Path) -> None:
+ """A clean reconcile writes broker truth as the new baseline, round-trippable."""
+ rp, rb, ro = _readers(
+ positions=[{"symbol": "NVDA", "qty": 5}],
+ balance={"cash_usd": 4242.0},
+ open_orders=[{"order_id": "o2", "status": "open"}],
+ )
+ report = reconcile("robinhood", rp, rb, ro)
+ assert report.state_persisted is True
+
+ path = paths.broker_dir("robinhood") / "runtime_state.json"
+ loaded = json.loads(path.read_text(encoding="utf-8"))
+ assert loaded["positions"] == [{"symbol": "NVDA", "qty": 5}]
+ assert loaded["open_orders"] == [{"order_id": "o2", "status": "open"}]
+ assert loaded["balance"] == {"cash_usd": 4242.0}
+ assert loaded["broker"] == "robinhood"
+ assert loaded["schema_version"] == 1
+ # No stray temp file left behind by the atomic replace.
+ assert not (path.parent / ".runtime_state.json.tmp").exists()
+
+
+def test_unsafe_reconcile_does_not_advance_state(live_runtime: Path) -> None:
+ """An unsafe reconcile must NOT overwrite the durable record of the ambiguity."""
+ _seed_state(
+ "robinhood",
+ open_orders=[{"client_order_id": "c-pending", "status": "submitted"}],
+ positions=[{"symbol": "NVDA", "qty": 3}],
+ )
+ before = (paths.broker_dir("robinhood") / "runtime_state.json").read_text(
+ encoding="utf-8"
+ )
+ rp, rb, ro = _readers(positions=[{"symbol": "NVDA", "qty": 3}], open_orders=[])
+ report = reconcile("robinhood", rp, rb, ro)
+
+ assert report.requires_halt is True
+ assert report.state_persisted is False
+ after = (paths.broker_dir("robinhood") / "runtime_state.json").read_text(
+ encoding="utf-8"
+ )
+ assert before == after # durable state preserved untouched
+
+
+# ---------------------------------------------------------------------------
+# corrupt state is renamed aside, treated as cold start
+# ---------------------------------------------------------------------------
+
+
+def test_corrupt_state_renamed_and_cold_starts(live_runtime: Path) -> None:
+ """A truncated/corrupt state file is renamed .corrupt-* and treated as cold."""
+ path = paths.broker_dir("robinhood") / "runtime_state.json"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("{not json", encoding="utf-8")
+
+ rp, rb, ro = _readers(positions=[{"symbol": "NVDA", "qty": 1}])
+ report = reconcile("robinhood", rp, rb, ro)
+
+ assert report.had_prior_state is False # corrupt -> cold start
+ assert report.is_safe is True
+ corrupt = list(path.parent.glob("runtime_state.json.corrupt-*"))
+ assert corrupt, "corrupt state file should be renamed aside"
+ assert path.is_file() # a fresh clean state was written
diff --git a/agent/tests/test_runtime_runner.py b/agent/tests/test_runtime_runner.py
new file mode 100644
index 000000000..036094026
--- /dev/null
+++ b/agent/tests/test_runtime_runner.py
@@ -0,0 +1,568 @@
+"""Unit tests for the persistent live-trading runner (SPEC.md §7.5 #2, #7).
+
+The runner is exercised with all external dependencies stubbed — no live agent,
+no broker, no real audit ledger — so these tests assert pure control flow:
+
+* tick ordering (halt → expiry → reconcile → invoke → audit),
+* halt aborts before anything else,
+* proactive expiry trips a stop AND never reaches the agent invocation,
+* a reconcile-unsafe / reconcile-error report aborts (no auto-resend, §8 #5),
+* the mandate is pinned inline in the prompt the runner constructs.
+
+pytest-asyncio is not a dependency here, so the single async entry
+(:meth:`LiveRunner.run_once`) is driven via :func:`asyncio.run`.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from datetime import datetime, timedelta, timezone
+from typing import Any, Mapping
+
+import pytest
+
+from src.live.mandate.model import (
+ AssetClass,
+ ConsentMeta,
+ HardCaps,
+ InstrumentType,
+ Mandate,
+ UniverseConstraint,
+ MANDATE_SCHEMA_VERSION,
+)
+from src.live.runtime.runner import (
+ LiveRunner,
+ TICK_ERROR,
+ TICK_EXPIRED,
+ TICK_HALTED,
+ TICK_INVOKED,
+ TICK_NO_MANDATE,
+ TICK_RECONCILE_ERROR,
+ TICK_RECONCILE_UNSAFE,
+ _mandate_is_expired,
+ _parse_expiry,
+ _pin_mandate_prompt,
+ _report_is_unsafe,
+)
+
+BROKER = "robinhood"
+_FIXED_NOW = datetime(2026, 6, 1, 12, 0, 0, tzinfo=timezone.utc)
+
+
+# --------------------------------------------------------------------------- #
+# Fixtures / stubs
+# --------------------------------------------------------------------------- #
+
+
+def _make_mandate(*, expires_at: str) -> Mandate:
+ """Build a minimal valid mandate with a caller-chosen ``expires_at``."""
+ return Mandate(
+ schema_version=MANDATE_SCHEMA_VERSION,
+ hard_caps=HardCaps(
+ account_funding_usd=10_000.0,
+ max_order_notional_usd=750.0,
+ max_total_exposure_usd=5_000.0,
+ max_leverage=1.0,
+ allowed_instruments=(InstrumentType.EQUITY, InstrumentType.ETF),
+ max_trades_per_day=5,
+ ),
+ universe=UniverseConstraint(
+ asset_classes=(AssetClass.US_EQUITY,),
+ min_market_cap_usd=1_000_000_000.0,
+ min_avg_daily_volume_usd=5_000_000.0,
+ exclude_symbols=("GME", "AMC"),
+ ),
+ consent=ConsentMeta(
+ created_at="2026-06-01T00:00:00Z",
+ consent_token_sha256="deadbeef",
+ broker=BROKER,
+ account_ref="acct-xyz",
+ expires_at=expires_at,
+ ),
+ )
+
+
+def _future_expiry() -> str:
+ return (_FIXED_NOW + timedelta(days=30)).isoformat().replace("+00:00", "Z")
+
+
+def _past_expiry() -> str:
+ return (_FIXED_NOW - timedelta(seconds=1)).isoformat().replace("+00:00", "Z")
+
+
+class _SafeReport:
+ """A reconcile report that reports a clean, safe-to-trade state."""
+
+ safe_to_trade = True
+
+
+class _UnsafeReport:
+ """A reconcile report that flags an unsafe / ambiguous state."""
+
+ safe_to_trade = False
+
+
+class _OrderTracker:
+ """Records the order in which the runner reaches each tick stage."""
+
+ def __init__(self) -> None:
+ self.calls: list[str] = []
+ self.audits: list[dict[str, Any]] = []
+ self.agent_prompts: list[str] = []
+ self.tripped: list[dict[str, Any]] = []
+
+ def halt_flag(self, broker: str | None) -> bool:
+ self.calls.append("halt")
+ return False
+
+ def load_mandate(self, broker: str) -> Mandate | None:
+ self.calls.append("mandate")
+ return _make_mandate(expires_at=_future_expiry())
+
+ def reconcile(self, broker, read_positions, read_balance, read_open_orders):
+ self.calls.append("reconcile")
+ return _SafeReport()
+
+ async def agent_caller(self, session_id: str, prompt: str) -> Mapping[str, Any]:
+ self.calls.append("invoke")
+ self.agent_prompts.append(prompt)
+ return {"status": "success", "content": "held"}
+
+ def write_audit(self, event) -> Mapping[str, Any]:
+ self.calls.append("audit")
+ record = {"audit_id": event.audit_id, "kind": event.kind, "outcome": event.outcome}
+ self.audits.append(record)
+ return record
+
+ def trip_halt(self, by: str, reason: str, broker: str | None = None):
+ self.tripped.append({"by": by, "reason": reason, "broker": broker})
+
+
+def _read_stub() -> list:
+ return []
+
+
+def _build_runner(tracker: _OrderTracker, **overrides) -> LiveRunner:
+ """Build a runner wired entirely to the tracker stubs, with overrides."""
+ kwargs: dict[str, Any] = dict(
+ agent_caller=tracker.agent_caller,
+ reconcile_fn=tracker.reconcile,
+ read_positions=_read_stub,
+ read_balance=_read_stub,
+ read_open_orders=_read_stub,
+ clock=lambda: _FIXED_NOW,
+ load_mandate_fn=tracker.load_mandate,
+ write_audit_fn=tracker.write_audit,
+ halt_flag_fn=tracker.halt_flag,
+ trip_halt_fn=tracker.trip_halt,
+ session_id="live-test",
+ )
+ kwargs.update(overrides)
+ return LiveRunner(BROKER, **kwargs)
+
+
+# --------------------------------------------------------------------------- #
+# Pure-helper tests
+# --------------------------------------------------------------------------- #
+
+
+def test_parse_expiry_handles_z_suffix() -> None:
+ parsed = _parse_expiry("2026-06-28T00:00:00Z")
+ assert parsed == datetime(2026, 6, 28, tzinfo=timezone.utc)
+
+
+def test_parse_expiry_handles_offset() -> None:
+ parsed = _parse_expiry("2026-06-28T00:00:00+00:00")
+ assert parsed == datetime(2026, 6, 28, tzinfo=timezone.utc)
+
+
+def test_parse_expiry_unparseable_is_none() -> None:
+ assert _parse_expiry("not-a-date") is None
+ assert _parse_expiry("") is None
+
+
+def test_mandate_expired_failclosed_on_bad_expiry() -> None:
+ mandate = _make_mandate(expires_at="garbage")
+ assert _mandate_is_expired(mandate, _FIXED_NOW) is True
+
+
+def test_mandate_not_expired_in_future() -> None:
+ mandate = _make_mandate(expires_at=_future_expiry())
+ assert _mandate_is_expired(mandate, _FIXED_NOW) is False
+
+
+def test_report_is_unsafe_defensive() -> None:
+ assert _report_is_unsafe(None) is True
+ assert _report_is_unsafe(_SafeReport()) is False
+ assert _report_is_unsafe(_UnsafeReport()) is True
+
+ class _Ambiguous:
+ ambiguous = True
+
+ assert _report_is_unsafe(_Ambiguous()) is True
+
+ class _Unknown:
+ pass
+
+ assert _report_is_unsafe(_Unknown()) is True # fail-closed on unknown shape
+
+
+def test_pin_mandate_prompt_includes_full_mandate() -> None:
+ mandate = _make_mandate(expires_at=_future_expiry())
+ prompt = _pin_mandate_prompt(BROKER, mandate, _FIXED_NOW)
+ # Hard caps and universe pinned inline (survives loop.py compaction).
+ assert "750.0" in prompt # max order notional
+ assert "5000.0" in prompt # max total exposure
+ assert "Max trades per UTC day: 5" in prompt
+ assert "equity, etf" in prompt
+ assert "us_equity" in prompt
+ assert "GME, AMC" in prompt # exclude list
+ assert BROKER in prompt
+
+
+# --------------------------------------------------------------------------- #
+# run_once control-flow tests
+# --------------------------------------------------------------------------- #
+
+
+def test_happy_path_tick_ordering() -> None:
+ tracker = _OrderTracker()
+ runner = _build_runner(tracker)
+ result = asyncio.run(runner.run_once())
+
+ assert result["outcome"] == TICK_INVOKED
+ assert result["agent_result"] == {"status": "success", "content": "held"}
+ # Order: halt → mandate → reconcile → invoke → audit.
+ assert tracker.calls == ["halt", "mandate", "reconcile", "invoke", "audit"]
+ # Mandate was pinned into the prompt actually sent to the agent.
+ assert tracker.agent_prompts and "Max trades per UTC day: 5" in tracker.agent_prompts[0]
+
+
+def test_halt_aborts_before_anything_else() -> None:
+ tracker = _OrderTracker()
+ runner = _build_runner(tracker, halt_flag_fn=lambda broker: True)
+ result = asyncio.run(runner.run_once())
+
+ assert result["outcome"] == TICK_HALTED
+ # No mandate load, no reconcile, no invoke — only the halt audit.
+ assert tracker.calls == ["audit"]
+ assert tracker.audits[0]["kind"] == "halt_tripped"
+ assert not tracker.agent_prompts
+
+
+def test_no_mandate_aborts_with_block() -> None:
+ tracker = _OrderTracker()
+ runner = _build_runner(tracker, load_mandate_fn=lambda broker: None)
+ result = asyncio.run(runner.run_once())
+
+ assert result["outcome"] == TICK_NO_MANDATE
+ assert tracker.calls == ["halt", "audit"]
+ assert not tracker.agent_prompts
+
+
+def test_proactive_expiry_trips_stop_and_never_invokes() -> None:
+ tracker = _OrderTracker()
+ runner = _build_runner(
+ tracker,
+ load_mandate_fn=lambda broker: _make_mandate(expires_at=_past_expiry()),
+ )
+ result = asyncio.run(runner.run_once())
+
+ assert result["outcome"] == TICK_EXPIRED
+ # Authority was cut: a per-broker halt was tripped.
+ assert tracker.tripped == [
+ {
+ "by": "file",
+ "reason": "mandate expired — proactive runner stop",
+ "broker": BROKER,
+ }
+ ]
+ # Expiry acted on BEFORE reconcile/invoke; the agent is never reached.
+ assert "reconcile" not in tracker.calls
+ assert "invoke" not in tracker.calls
+ assert not tracker.agent_prompts
+ assert tracker.audits[-1]["kind"] == "halt_tripped"
+
+
+def test_reconcile_unsafe_aborts_no_resend() -> None:
+ tracker = _OrderTracker()
+ runner = _build_runner(tracker, reconcile_fn=lambda *a: _UnsafeReport())
+ result = asyncio.run(runner.run_once())
+
+ assert result["outcome"] == TICK_RECONCILE_UNSAFE
+ # Reached reconcile but NOT invoke — no auto-resend on ambiguous state.
+ assert "invoke" not in tracker.calls
+ assert not tracker.agent_prompts
+ assert tracker.audits[-1]["kind"] == "breach"
+
+
+def test_reconcile_error_is_failclosed() -> None:
+ tracker = _OrderTracker()
+
+ def _boom(*_a):
+ raise RuntimeError("broker read timeout")
+
+ runner = _build_runner(tracker, reconcile_fn=_boom)
+ result = asyncio.run(runner.run_once())
+
+ assert result["outcome"] == TICK_RECONCILE_ERROR
+ assert "invoke" not in tracker.calls
+ assert not tracker.agent_prompts
+
+
+def test_agent_invocation_error_is_audited() -> None:
+ tracker = _OrderTracker()
+
+ async def _boom(session_id: str, prompt: str):
+ raise RuntimeError("agent crashed")
+
+ runner = _build_runner(tracker, agent_caller=_boom)
+ result = asyncio.run(runner.run_once())
+
+ assert result["outcome"] == TICK_ERROR
+ assert result["reason"] == "agent crashed"
+ assert tracker.audits[-1]["kind"] == "breach"
+ assert tracker.audits[-1]["outcome"] == "error"
+
+
+def test_expired_mandate_never_reaches_invoke_even_if_reconcile_safe() -> None:
+ # Regression guard for the §7.5 #7 invariant: expiry precedes reconcile.
+ tracker = _OrderTracker()
+ runner = _build_runner(
+ tracker,
+ load_mandate_fn=lambda broker: _make_mandate(expires_at=_past_expiry()),
+ reconcile_fn=lambda *a: _SafeReport(),
+ )
+ result = asyncio.run(runner.run_once())
+ assert result["outcome"] == TICK_EXPIRED
+ # load_mandate_fn is overridden with a lambda that does not record the
+ # "mandate" marker, so calls reflect: halt check -> (lambda load) -> expiry
+ # -> audit. The invariant under test is that reconcile/invoke never run.
+ assert tracker.calls == ["halt", "audit"]
+ assert "reconcile" not in tracker.calls
+ assert "invoke" not in tracker.calls
+
+
+# --------------------------------------------------------------------------- #
+# run_loop (resume-via-recompute) tests
+# --------------------------------------------------------------------------- #
+
+
+class _FakeJob:
+ def __init__(self, job_id: str) -> None:
+ self.id = job_id
+ self.next_run_at = 0
+ self.schedule = None
+
+
+class _FakeScheduler:
+ def __init__(self) -> None:
+ self.started = False
+ self.stopped = False
+ self.jobs: list[Any] = []
+
+ def start(self) -> None:
+ self.started = True
+
+ def stop(self) -> None:
+ self.stopped = True
+
+ def add_job(self, job) -> None:
+ self.jobs.append(job)
+
+ def remove_job(self, job_id: str) -> None:
+ self.jobs = [j for j in self.jobs if j.id != job_id]
+
+
+def test_run_loop_recomputes_and_starts() -> None:
+ tracker = _OrderTracker()
+ sched = _FakeScheduler()
+ runner = _build_runner(tracker, scheduler=sched)
+ runner.run_loop(jobs=[_FakeJob("watch-1")])
+
+ assert sched.started is True
+ assert [j.id for j in sched.jobs] == ["watch-1"]
+
+
+def test_run_loop_refuses_without_mandate() -> None:
+ tracker = _OrderTracker()
+ sched = _FakeScheduler()
+ runner = _build_runner(tracker, scheduler=sched, load_mandate_fn=lambda b: None)
+ runner.run_loop(jobs=[_FakeJob("watch-1")])
+
+ assert sched.started is False
+ assert sched.jobs == []
+
+
+def test_run_loop_refuses_when_expired_and_trips() -> None:
+ tracker = _OrderTracker()
+ sched = _FakeScheduler()
+ runner = _build_runner(
+ tracker,
+ scheduler=sched,
+ load_mandate_fn=lambda b: _make_mandate(expires_at=_past_expiry()),
+ )
+ runner.run_loop()
+
+ assert sched.started is False
+ assert tracker.tripped # proactive stop tripped on a dead mandate at boot
+
+
+def test_run_loop_requires_scheduler() -> None:
+ tracker = _OrderTracker()
+ runner = _build_runner(tracker) # no scheduler injected
+ with pytest.raises(RuntimeError):
+ runner.run_loop()
+
+
+def test_run_loop_synthesizes_jobs_from_triggers() -> None:
+ # No explicit jobs, no durable store entries -> the runner must recompute its
+ # watch cadence from the injected triggers (R3) so it actually wakes, instead
+ # of starting an empty scheduler that never fires (the C3 integration gap).
+ from src.live.runtime.triggers import Trigger
+
+ tracker = _OrderTracker()
+ sched = _FakeScheduler()
+
+ class _EmptyStore:
+ def load(self):
+ return []
+
+ def save(self, jobs):
+ self.saved = list(jobs)
+
+ store = _EmptyStore()
+ runner = _build_runner(
+ tracker,
+ scheduler=sched,
+ triggers=[Trigger.market("us_equity"), Trigger.interval(30_000)],
+ job_store=store,
+ )
+ runner.run_loop() # no explicit jobs
+
+ assert sched.started is True
+ assert len(sched.jobs) == 2 # market watch-job + interval job
+ assert all(j.schedule.startswith("interval:") for j in sched.jobs)
+ assert getattr(store, "saved", None) is not None # synthesized jobs persisted
+
+
+def test_market_watch_cadence_is_operator_configurable() -> None:
+ # The MARKET watch cadence is no longer a hardcoded constant — it is an
+ # injectable operational knob (default 60s). A custom value flows into the
+ # synthesized job's interval schedule.
+ from src.live.runtime.triggers import Trigger
+
+ tracker = _OrderTracker()
+ sched = _FakeScheduler()
+
+ class _EmptyStore:
+ def load(self):
+ return []
+
+ def save(self, jobs):
+ pass
+
+ runner = _build_runner(
+ tracker,
+ scheduler=sched,
+ triggers=[Trigger.market("us_equity")],
+ job_store=_EmptyStore(),
+ market_watch_ms=15_000,
+ )
+ runner.run_loop()
+
+ assert [j.schedule for j in sched.jobs] == ["interval:15000"]
+
+
+def test_market_watch_cadence_defaults_when_nonpositive() -> None:
+ from src.live.runtime.triggers import Trigger
+
+ tracker = _OrderTracker()
+ sched = _FakeScheduler()
+
+ class _EmptyStore:
+ def load(self):
+ return []
+
+ def save(self, jobs):
+ pass
+
+ runner = _build_runner(
+ tracker,
+ scheduler=sched,
+ triggers=[Trigger.market("us_equity")],
+ job_store=_EmptyStore(),
+ market_watch_ms=0, # invalid → falls back to the 60s default
+ )
+ runner.run_loop()
+
+ assert [j.schedule for j in sched.jobs] == ["interval:60000"]
+
+
+def test_run_loop_resumes_persisted_jobs_over_triggers() -> None:
+ # A restart with durable jobs must resume THEM (resume-via-recompute), not
+ # re-synthesize from triggers.
+ from src.live.runtime.scheduler import Job
+ from src.live.runtime.triggers import Trigger
+
+ tracker = _OrderTracker()
+ sched = _FakeScheduler()
+ persisted = [Job(id="resumed-1", next_run_at=1, schedule="interval:5000")]
+
+ class _Store:
+ def load(self):
+ return persisted
+
+ def save(self, jobs): # pragma: no cover - must not be called on resume
+ raise AssertionError("save must not run when durable jobs exist")
+
+ runner = _build_runner(
+ tracker, scheduler=sched, triggers=[Trigger.market("us_equity")], job_store=_Store()
+ )
+ runner.run_loop()
+
+ assert [j.id for j in sched.jobs] == ["resumed-1"]
+
+
+def test_stop_loop_idempotent() -> None:
+ tracker = _OrderTracker()
+ sched = _FakeScheduler()
+ runner = _build_runner(tracker, scheduler=sched)
+ runner.stop_loop()
+ assert sched.stopped is True
+ # No scheduler => no-op, no raise.
+ _build_runner(tracker).stop_loop()
+
+
+# --------------------------------------------------------------------------- #
+# Real audit-ledger integration (one path, isolated home)
+# --------------------------------------------------------------------------- #
+
+
+def test_real_audit_write_on_halt(monkeypatch, tmp_path) -> None:
+ # Isolate the runtime root so the real ledger lands under tmp.
+ monkeypatch.setattr("src.config.paths.Path.home", lambda: tmp_path)
+ from src.live.audit import audit_ledger_path, write_live_action
+ from src.live.halt import halt_flag_set, trip_halt
+
+ tracker = _OrderTracker()
+ runner = LiveRunner(
+ BROKER,
+ agent_caller=tracker.agent_caller,
+ reconcile_fn=tracker.reconcile,
+ read_positions=_read_stub,
+ read_balance=_read_stub,
+ read_open_orders=_read_stub,
+ clock=lambda: _FIXED_NOW,
+ load_mandate_fn=tracker.load_mandate,
+ write_audit_fn=write_live_action,
+ halt_flag_fn=lambda broker: True,
+ trip_halt_fn=trip_halt,
+ session_id="live-test",
+ )
+ result = asyncio.run(runner.run_once())
+ assert result["outcome"] == TICK_HALTED
+ assert result["audit_id"] is not None
+ ledger = audit_ledger_path()
+ assert ledger.exists()
+ assert "halt_tripped" in ledger.read_text(encoding="utf-8")
diff --git a/agent/tests/test_runtime_scheduler.py b/agent/tests/test_runtime_scheduler.py
new file mode 100644
index 000000000..f4adedc25
--- /dev/null
+++ b/agent/tests/test_runtime_scheduler.py
@@ -0,0 +1,198 @@
+"""Tests for the live-runtime scheduler (src/live/runtime/scheduler.py,
+SPEC.md §7.5 #1).
+
+Two layers:
+* pure decision helpers (``earliest_next_run`` / ``due_jobs`` /
+ ``compute_sleep_ms`` / ``advance_after_fire``) — no clock, ``now_ms`` passed
+ in, fully deterministic.
+* the async ``Scheduler`` loop — driven with ``asyncio.run`` (house style; no
+ pytest-asyncio in this repo) and a controllable ``now_fn`` so a job fires
+ without real sleeping.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+from src.live.runtime.scheduler import (
+ DEFAULT_INTERVAL_MS,
+ DEFAULT_MAX_RECHECK_MS,
+ Job,
+ Scheduler,
+ advance_after_fire,
+ compute_sleep_ms,
+ due_jobs,
+ earliest_next_run,
+)
+
+
+def _job(jid: str, next_run_at: int, schedule: str = "interval:1000") -> Job:
+ return Job(id=jid, next_run_at=next_run_at, schedule=schedule)
+
+
+# ---- Job.interval_ms ------------------------------------------------------
+
+
+def test_interval_ms_parses_interval_spec() -> None:
+ assert _job("a", 0, "interval:5000").interval_ms() == 5000
+
+
+def test_interval_ms_once_is_none() -> None:
+ assert _job("a", 0, "once").interval_ms() is None
+
+
+def test_interval_ms_bad_or_bare_spec_defaults() -> None:
+ assert _job("a", 0, "interval:nope").interval_ms() == DEFAULT_INTERVAL_MS
+ assert _job("a", 0, "interval:-5").interval_ms() == DEFAULT_INTERVAL_MS
+ assert _job("a", 0, "weird").interval_ms() == DEFAULT_INTERVAL_MS
+ assert _job("a", 0, "").interval_ms() == DEFAULT_INTERVAL_MS
+
+
+# ---- pure decision helpers ------------------------------------------------
+
+
+def test_earliest_next_run() -> None:
+ assert earliest_next_run([]) is None
+ assert earliest_next_run([_job("a", 30), _job("b", 10), _job("c", 20)]) == 10
+
+
+def test_due_jobs_ordered_ascending() -> None:
+ jobs = [_job("a", 30), _job("b", 10), _job("c", 20), _job("d", 100)]
+ due = due_jobs(jobs, now_ms=25)
+ assert [j.id for j in due] == ["b", "c"]
+
+
+def test_compute_sleep_ms_no_jobs_polls_at_cap() -> None:
+ assert compute_sleep_ms([], now_ms=0, max_recheck_ms=DEFAULT_MAX_RECHECK_MS) == DEFAULT_MAX_RECHECK_MS
+
+
+def test_compute_sleep_ms_far_future_is_capped() -> None:
+ jobs = [_job("a", 10_000_000)]
+ assert compute_sleep_ms(jobs, now_ms=0, max_recheck_ms=5000) == 5000
+
+
+def test_compute_sleep_ms_near_term_returns_delta() -> None:
+ jobs = [_job("a", 800)]
+ assert compute_sleep_ms(jobs, now_ms=300, max_recheck_ms=5000) == 500
+
+
+def test_compute_sleep_ms_due_now_is_zero() -> None:
+ jobs = [_job("a", 100)]
+ assert compute_sleep_ms(jobs, now_ms=200, max_recheck_ms=5000) == 0
+
+
+def test_advance_after_fire_recurring_reschedules_past_now() -> None:
+ job = _job("a", next_run_at=100, schedule="interval:1000")
+ # Fired late at now=5000; next run should be now+interval, not 100+interval,
+ # so a backlog of missed slots does not stampede.
+ keep = advance_after_fire(job, now_ms=5000)
+ assert keep is True
+ assert job.next_run_at == 6000
+
+
+def test_advance_after_fire_once_is_removed() -> None:
+ job = _job("a", next_run_at=100, schedule="once")
+ keep = advance_after_fire(job, now_ms=5000)
+ assert keep is False
+ assert job.next_run_at == 100 # untouched
+
+
+# ---- async Scheduler loop -------------------------------------------------
+
+
+def test_scheduler_fires_due_job_then_removes_oneshot() -> None:
+ fired: list[str] = []
+
+ async def on_fire(job: Job) -> None:
+ fired.append(job.id)
+
+ # now_fn returns a fixed time well past the job's next_run_at so the loop
+ # treats it as due immediately (sleep_ms == 0) — no real waiting.
+ async def scenario() -> None:
+ sched = Scheduler(on_fire, now_fn=lambda: 10_000)
+ sched.add_job(Job(id="x", next_run_at=0, schedule="once"))
+ sched.start()
+ # Yield until the one-shot has fired and self-removed.
+ for _ in range(100):
+ await asyncio.sleep(0)
+ if fired and not sched.jobs():
+ break
+ await sched.stop()
+
+ asyncio.run(scenario())
+ assert fired == ["x"]
+
+
+def test_scheduler_recurring_job_stays_and_advances() -> None:
+ fired: list[str] = []
+
+ async def on_fire(job: Job) -> None:
+ fired.append(job.id)
+
+ async def scenario() -> None:
+ sched = Scheduler(on_fire, now_fn=lambda: 10_000)
+ sched.add_job(Job(id="r", next_run_at=0, schedule="interval:1000"))
+ sched.start()
+ for _ in range(100):
+ await asyncio.sleep(0)
+ if fired:
+ break
+ # Job advanced to now+interval == 11000 and remains scheduled.
+ assert [j.id for j in sched.jobs()] == ["r"]
+ assert sched.jobs()[0].next_run_at == 11_000
+ await sched.stop()
+
+ asyncio.run(scenario())
+ assert fired and fired[0] == "r"
+
+
+def test_scheduler_on_fire_exception_does_not_kill_loop() -> None:
+ calls: list[str] = []
+
+ async def on_fire(job: Job) -> None:
+ calls.append(job.id)
+ raise RuntimeError("boom")
+
+ async def scenario() -> None:
+ sched = Scheduler(on_fire, now_fn=lambda: 10_000)
+ sched.add_job(Job(id="bad", next_run_at=0, schedule="once"))
+ sched.start()
+ for _ in range(100):
+ await asyncio.sleep(0)
+ if calls and not sched.jobs():
+ break
+ # Loop survived the raising callback and still removed the one-shot.
+ assert sched._task is not None and not sched._task.done()
+ await sched.stop()
+
+ asyncio.run(scenario())
+ assert calls == ["bad"]
+
+
+def test_scheduler_remove_job_and_idempotent_add() -> None:
+ async def on_fire(job: Job) -> None: # pragma: no cover - never fires here
+ pass
+
+ async def scenario() -> None:
+ sched = Scheduler(on_fire, now_fn=lambda: 0)
+ sched.add_job(Job(id="a", next_run_at=10**12, schedule="once"))
+ sched.add_job(Job(id="a", next_run_at=10**13, schedule="once")) # replace
+ assert len(sched.jobs()) == 1
+ assert sched.jobs()[0].next_run_at == 10**13
+ assert sched.remove_job("a") is True
+ assert sched.remove_job("a") is False
+ assert sched.jobs() == []
+
+ asyncio.run(scenario())
+
+
+def test_scheduler_stop_is_idempotent_when_not_started() -> None:
+ async def on_fire(job: Job) -> None: # pragma: no cover
+ pass
+
+ async def scenario() -> None:
+ sched = Scheduler(on_fire)
+ await sched.stop() # never started — must be a no-op
+ await sched.stop()
+
+ asyncio.run(scenario())
diff --git a/agent/tests/test_runtime_triggers.py b/agent/tests/test_runtime_triggers.py
new file mode 100644
index 000000000..9fb799593
--- /dev/null
+++ b/agent/tests/test_runtime_triggers.py
@@ -0,0 +1,227 @@
+"""Tests for live-runtime triggers (src/live/runtime/triggers.py, SPEC §7.5 c4).
+
+The decision core is pure — it takes ``now_ms`` as an argument and reads no
+clock — so every market-session / interval / event case is pinned to a fixed
+epoch-millisecond instant and asserted deterministically.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from typing import Mapping
+
+import pytest
+
+from src.live.runtime import triggers
+from src.live.runtime.triggers import (
+ Trigger,
+ TriggerKind,
+ due_now,
+ market_is_open,
+ market_is_open_at,
+)
+
+
+def _ms(year: int, month: int, day: int, hour: int, minute: int, tz_name: str) -> int:
+ """Epoch milliseconds for a wall-clock instant in a named timezone."""
+ from zoneinfo import ZoneInfo
+
+ dt = datetime(year, month, day, hour, minute, tzinfo=ZoneInfo(tz_name))
+ return int(dt.timestamp() * 1000)
+
+
+# --------------------------------------------------------------------------- #
+# Market sessions — us_equity #
+# --------------------------------------------------------------------------- #
+
+# 2026-05-29 is a Friday (regular trading day, not a holiday).
+_FRI = (2026, 5, 29)
+# 2026-05-30 is a Saturday.
+_SAT = (2026, 5, 30)
+# 2026-05-25 is Memorial Day (a holiday that falls on a weekday Monday).
+_MEMORIAL = (2026, 5, 25)
+
+
+ ("now_ms", "expected"),
+ [
+ # Mid-session weekday RTH.
+ (_ms(*_FRI, 12, 0, "America/New_York"), True),
+ # Exactly at the open bell (inclusive).
+ (_ms(*_FRI, 9, 30, "America/New_York"), True),
+ # One minute before open — pre-market, closed.
+ (_ms(*_FRI, 9, 29, "America/New_York"), False),
+ # Exactly at the close bell (exclusive) — closed.
+ (_ms(*_FRI, 16, 0, "America/New_York"), False),
+ # One minute before close — open.
+ (_ms(*_FRI, 15, 59, "America/New_York"), True),
+ # After hours — closed.
+ (_ms(*_FRI, 18, 0, "America/New_York"), False),
+ # Weekend (Saturday) at would-be-session time — closed.
+ (_ms(*_SAT, 12, 0, "America/New_York"), False),
+ # Weekday holiday (Memorial Day) at session time — closed.
+ (_ms(*_MEMORIAL, 12, 0, "America/New_York"), False),
+ ],
+)
+def test_us_equity_open_windows(now_ms: int, expected: bool) -> None:
+ assert market_is_open_at("us_equity", now_ms) is expected
+
+
+def test_us_equity_uses_ny_local_not_utc() -> None:
+ # 14:00 UTC on the Friday is 10:00 ET — inside RTH despite 14:00 looking
+ # like afternoon if (wrongly) read as local.
+ utc_1400 = _ms(*_FRI, 14, 0, "UTC")
+ assert market_is_open_at("us_equity", utc_1400) is True
+ # 21:00 UTC is 17:00 ET — after close.
+ utc_2100 = _ms(*_FRI, 21, 0, "UTC")
+ assert market_is_open_at("us_equity", utc_2100) is False
+
+
+# --------------------------------------------------------------------------- #
+# Market sessions — crypto (24/7) #
+# --------------------------------------------------------------------------- #
+
+
+ "now_ms",
+ [
+ _ms(*_FRI, 12, 0, "UTC"), # weekday noon
+ _ms(*_SAT, 3, 0, "UTC"), # weekend small hours
+ _ms(*_MEMORIAL, 0, 0, "UTC"), # an equity holiday
+ 0, # the UNIX epoch
+ ],
+)
+def test_crypto_always_open(now_ms: int) -> None:
+ assert market_is_open_at("crypto", now_ms) is True
+
+
+def test_unknown_market_fails_loud() -> None:
+ # An unknown market must never be silently treated as open.
+ with pytest.raises(ValueError):
+ market_is_open_at("forex_zzz", 0)
+
+
+# --------------------------------------------------------------------------- #
+# due_now — MARKET #
+# --------------------------------------------------------------------------- #
+
+
+def test_due_now_market_delegates_to_session() -> None:
+ trig = Trigger.market("us_equity")
+ assert due_now(trig, _ms(*_FRI, 12, 0, "America/New_York")) is True
+ assert due_now(trig, _ms(*_SAT, 12, 0, "America/New_York")) is False
+
+
+def test_market_trigger_rejects_unknown_market() -> None:
+ with pytest.raises(ValueError):
+ Trigger.market("nope")
+
+
+def test_market_trigger_without_market_raises() -> None:
+ bad = Trigger(kind=TriggerKind.MARKET, market=None)
+ with pytest.raises(ValueError):
+ due_now(bad, 0)
+
+
+# --------------------------------------------------------------------------- #
+# due_now — INTERVAL #
+# --------------------------------------------------------------------------- #
+
+
+def test_interval_due_on_exact_multiples() -> None:
+ trig = Trigger.interval(60_000) # every 60 s, anchored at epoch 0
+ assert due_now(trig, 0) is True
+ assert due_now(trig, 60_000) is True
+ assert due_now(trig, 120_000) is True
+ # Off-boundary instants are not due.
+ assert due_now(trig, 59_999) is False
+ assert due_now(trig, 60_001) is False
+
+
+def test_interval_respects_phase_anchor() -> None:
+ trig = Trigger.interval(60_000, epoch_ms=10_000)
+ assert due_now(trig, 10_000) is True
+ assert due_now(trig, 70_000) is True
+ assert due_now(trig, 10_001) is False
+ # Before the anchor it is never due.
+ assert due_now(trig, 0) is False
+
+
+def test_interval_must_be_positive() -> None:
+ with pytest.raises(ValueError):
+ Trigger.interval(0)
+ with pytest.raises(ValueError):
+ Trigger.interval(-1000)
+ # A hand-built malformed interval trigger also raises at evaluation.
+ bad = Trigger(kind=TriggerKind.INTERVAL, interval_ms=0)
+ with pytest.raises(ValueError):
+ due_now(bad, 0)
+
+
+# --------------------------------------------------------------------------- #
+# due_now — EVENT #
+# --------------------------------------------------------------------------- #
+
+
+def test_event_predicate_drives_due() -> None:
+ # Fire when last price crosses above a threshold supplied by the runner.
+ def crossed_above(state: Mapping[str, object]) -> bool:
+ return float(state.get("last_price", 0.0)) >= 150.0
+
+ trig = Trigger.event(crossed_above)
+ assert due_now(trig, 0, event_state={"last_price": 151.0}) is True
+ assert due_now(trig, 0, event_state={"last_price": 149.0}) is False
+ # No state supplied -> predicate sees empty mapping -> not due.
+ assert due_now(trig, 0) is False
+
+
+def test_event_fill_predicate() -> None:
+ def has_fill(state: Mapping[str, object]) -> bool:
+ return bool(state.get("filled"))
+
+ trig = Trigger.event(has_fill)
+ assert due_now(trig, 12345, event_state={"filled": True}) is True
+ assert due_now(trig, 12345, event_state={"filled": False}) is False
+
+
+def test_event_trigger_without_predicate_raises() -> None:
+ bad = Trigger(kind=TriggerKind.EVENT, predicate=None)
+ with pytest.raises(ValueError):
+ due_now(bad, 0)
+
+
+# --------------------------------------------------------------------------- #
+# Immutability + clock wrappers #
+# --------------------------------------------------------------------------- #
+
+
+def test_trigger_is_frozen() -> None:
+ trig = Trigger.interval(1000)
+ with pytest.raises(Exception):
+ trig.interval_ms = 2000 # type: ignore[misc]
+
+
+def test_market_is_open_wrapper_delegates_to_pure_core(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Pin the wall clock to a known weekend instant; the wrapper must agree
+ # with the pure core fed the same now_ms.
+ fixed = _ms(*_SAT, 12, 0, "America/New_York")
+ monkeypatch.setattr(triggers, "_now_ms", lambda: fixed)
+ assert market_is_open("us_equity") is False
+ assert market_is_open("us_equity") == market_is_open_at("us_equity", fixed)
+ assert market_is_open("crypto") is True
+
+
+def test_due_now_at_wrapper_delegates(monkeypatch: pytest.MonkeyPatch) -> None:
+ fixed = _ms(*_FRI, 12, 0, "America/New_York")
+ monkeypatch.setattr(triggers, "_now_ms", lambda: fixed)
+ trig = Trigger.market("us_equity")
+ assert triggers.due_now_at(trig) is True
+ assert triggers.due_now_at(trig) == due_now(trig, fixed)
+
+
+def test_now_ms_is_utc_epoch_ms() -> None:
+ # Sanity: the real clock reader returns a plausible epoch-ms value.
+ before = int(datetime.now(tz=timezone.utc).timestamp() * 1000)
+ val = triggers._now_ms()
+ after = int(datetime.now(tz=timezone.utc).timestamp() * 1000)
+ assert before <= val <= after + 1000
diff --git a/frontend/src/components/chat/MandateProposalCard.tsx b/frontend/src/components/chat/MandateProposalCard.tsx
new file mode 100644
index 000000000..723d1361f
--- /dev/null
+++ b/frontend/src/components/chat/MandateProposalCard.tsx
@@ -0,0 +1,309 @@
+import { memo, useCallback, useState } from "react";
+import { ShieldCheck, ShieldAlert, Wallet, OctagonX, SlidersHorizontal, Check, X, Loader2 } from "lucide-react";
+import { toast } from "sonner";
+import { api, type MandateProfile, type MandateProposal } from "@/lib/api";
+import { AgentAvatar } from "./AgentAvatar";
+
+interface Props {
+ proposal: MandateProposal;
+ /** True once a mandate.committed event for this proposal has arrived; the card collapses to a badge. */
+ committed?: {
+ selected_ordinal?: number;
+ max_order_usd?: number;
+ daily_trade_cap?: number;
+ expires_at?: string;
+ } | null;
+ /**
+ * Submit a free-text adjust request as a normal chat message back to the agent,
+ * which re-invokes propose_mandate_profiles and returns a fresh proposal.
+ */
+ onAdjust: (message: string) => void;
+}
+
+function formatUsd(value: number): string {
+ if (!Number.isFinite(value)) return "—";
+ return `$${value.toLocaleString("en-US", { maximumFractionDigits: 0 })}`;
+}
+
+function formatLeverage(leverage: MandateProfile["leverage"]): string {
+ if (typeof leverage === "number") {
+ return leverage <= 1 ? "no leverage" : `${leverage}× leverage`;
+ }
+ const lowered = leverage.toLowerCase();
+ return lowered === "none" || lowered === "" ? "no leverage" : leverage;
+}
+
+function formatUniverse(universe: MandateProfile["universe"]): string {
+ if (Array.isArray(universe)) return universe.join(" / ");
+ return universe.replace(/_/g, " ");
+}
+
+function ProfileTile({
+ profile,
+ active,
+ busy,
+ disabled,
+ adjusting,
+ onCommit,
+ onAdjustToggle,
+ onAdjustSubmit,
+ onAdjustCancel,
+}: {
+ profile: MandateProfile;
+ active: boolean;
+ busy: boolean;
+ disabled: boolean;
+ adjusting: boolean;
+ onCommit: () => void;
+ onAdjustToggle: () => void;
+ onAdjustSubmit: (text: string) => void;
+ onAdjustCancel: () => void;
+}) {
+ const [adjustText, setAdjustText] = useState("");
+
+ const submit = () => {
+ const text = adjustText.trim();
+ if (!text) return;
+ onAdjustSubmit(text);
+ setAdjustText("");
+ };
+
+ return (
+ <div
+ className={[
+ "rounded-xl border p-3 transition-colors",
+ active
+ ? "border-primary/60 bg-primary/5"
+ : "border-border/60 bg-muted/20 hover:border-primary/40",
+ ].join(" ")}
+ >
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex items-center gap-1.5">
+ <span className="flex h-5 w-5 items-center justify-center rounded-full bg-primary/10 font-mono text-[11px] font-semibold text-primary">
+ {profile.ordinal}
+ </span>
+ <span className="text-sm font-semibold text-foreground">{profile.label}</span>
+ </div>
+ <button
+ type="button"
+ onClick={onAdjustToggle}
+ disabled={disabled}
+ className="inline-flex items-center gap-1 rounded-lg border px-2 py-0.5 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40"
+ title="Adjust this mandate"
+ >
+ <SlidersHorizontal className="h-3 w-3" />
+ Adjust
+ </button>
+ </div>
+
+ <dl className="mt-2 grid grid-cols-2 gap-x-3 gap-y-1.5 text-[11px]">
+ <div className="col-span-2">
+ <dt className="text-muted-foreground">Universe</dt>
+ <dd className="font-medium text-foreground">{formatUniverse(profile.universe)}</dd>
+ </div>
+ <div>
+ <dt className="text-muted-foreground">Max order</dt>
+ <dd className="font-mono font-medium text-foreground">{formatUsd(profile.max_order_usd)}</dd>
+ </div>
+ <div>
+ <dt className="text-muted-foreground">Daily cap</dt>
+ <dd className="font-mono font-medium text-foreground">{profile.daily_trade_cap} trades/day</dd>
+ </div>
+ <div>
+ <dt className="text-muted-foreground">Leverage</dt>
+ <dd className="font-medium text-foreground">{formatLeverage(profile.leverage)}</dd>
+ </div>
+ <div>
+ <dt className="text-muted-foreground">Instruments</dt>
+ <dd className="font-medium text-foreground">{profile.instruments.join(", ") || "—"}</dd>
+ </div>
+ </dl>
+
+ {profile.notes && (
+ <p className="mt-2 text-[11px] leading-relaxed text-muted-foreground">{profile.notes}</p>
+ )}
+
+ {adjusting ? (
+ <div className="mt-3 grid gap-2">
+ <input
+ type="text"
+ value={adjustText}
+ autoFocus
+ onChange={(e) => setAdjustText(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ submit();
+ } else if (e.key === "Escape") {
+ onAdjustCancel();
+ }
+ }}
+ placeholder="e.g. keep this but raise the daily cap to 10"
+ className="w-full rounded-lg border bg-background px-3 py-1.5 text-xs text-foreground outline-none focus:ring-2 focus:ring-primary/30"
+ />
+ <div className="flex justify-end gap-2">
+ <button
+ type="button"
+ onClick={onAdjustCancel}
+ className="inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <X className="h-3 w-3" />
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={submit}
+ disabled={!adjustText.trim()}
+ className="inline-flex items-center gap-1 rounded-lg bg-primary px-2 py-1 text-[11px] font-medium text-primary-foreground transition-opacity disabled:opacity-40"
+ >
+ <Check className="h-3 w-3" />
+ Send adjustment
+ </button>
+ </div>
+ </div>
+ ) : (
+ <button
+ type="button"
+ onClick={onCommit}
+ disabled={disabled}
+ className="mt-3 inline-flex w-full items-center justify-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground transition-opacity hover:opacity-90 disabled:opacity-40"
+ >
+ {busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <ShieldCheck className="h-3.5 w-3.5" />}
+ {busy ? "Committing…" : `Commit “${profile.label}”`}
+ </button>
+ )}
+ </div>
+ );
+}
+
+/**
+ * Renders a live-trading mandate proposal (SPEC Consent §1/§2).
+ *
+ * Each profile tile shows concrete numbers (universe, max order, daily cap, leverage,
+ * instruments). Committing calls `api.commitMandate` — a privileged surface action,
+ * never `api.sendMessage`. "Adjust" sends a natural-language message back to the agent
+ * to re-render a fresh proposal. Once committed, the card collapses to a compact badge.
+ */
+export const MandateProposalCard = memo(function MandateProposalCard({ proposal, committed, onAdjust }: Props) {
+ const [busyOrdinal, setBusyOrdinal] = useState<number | null>(null);
+ const [adjustingOrdinal, setAdjustingOrdinal] = useState<number | null>(null);
+
+ const handleCommit = useCallback(
+ async (ordinal: number) => {
+ if (busyOrdinal != null) return;
+ setBusyOrdinal(ordinal);
+ try {
+ await api.commitMandate({
+ proposal_id: proposal.proposal_id,
+ selected_ordinal: ordinal,
+ adjustments: null,
+ consent_ack: true,
+ session_id: proposal.session_id,
+ });
+ // Card collapses to the active-mandate badge when the mandate.committed
+ // SSE event arrives; no optimistic state-write here.
+ } catch (error) {
+ setBusyOrdinal(null);
+ toast.error(error instanceof Error ? error.message : "Failed to commit mandate.");
+ }
+ },
+ [busyOrdinal, proposal.proposal_id, proposal.session_id],
+ );
+
+ // Collapsed state: a compact active-mandate badge (same visual family as the goal badge).
+ if (committed) {
+ const profile = proposal.profiles.find((p) => p.ordinal === committed.selected_ordinal);
+ const maxOrder = committed.max_order_usd ?? profile?.max_order_usd;
+ const dailyCap = committed.daily_trade_cap ?? profile?.daily_trade_cap;
+ const expires = committed.expires_at ? new Date(committed.expires_at) : null;
+ return (
+ <div className="flex gap-3">
+ <AgentAvatar />
+ <div className="flex-1 min-w-0">
+ <span className="inline-flex max-w-full flex-wrap items-center gap-1.5 rounded-lg bg-emerald-500/10 px-2.5 py-1 text-xs font-medium text-emerald-600 dark:text-emerald-400">
+ <ShieldCheck className="h-3 w-3 shrink-0" />
+ <span className="shrink-0">
+ Mandate {committed.selected_ordinal != null ? `#${committed.selected_ordinal} ` : ""}active
+ </span>
+ {maxOrder != null && (
+ <span className="shrink-0 font-mono text-[11px]">· ≤{formatUsd(maxOrder)}/order</span>
+ )}
+ {dailyCap != null && <span className="shrink-0 font-mono text-[11px]">· {dailyCap}/day</span>}
+ {expires && (
+ <span className="shrink-0 text-[10px] text-muted-foreground">
+ · expires {expires.toLocaleDateString()}
+ </span>
+ )}
+ </span>
+ </div>
+ </div>
+ );
+ }
+
+ const isReauth = Boolean(proposal.reauth_for);
+
+ return (
+ <div className="flex gap-3">
+ <AgentAvatar />
+ <div className="flex-1 min-w-0 space-y-3 rounded-2xl border border-primary/20 bg-background/95 p-4 shadow-sm">
+ <div className="flex items-start gap-2">
+ {isReauth ? (
+ <ShieldAlert className="h-4 w-4 shrink-0 text-amber-500" />
+ ) : (
+ <ShieldCheck className="h-4 w-4 shrink-0 text-primary" />
+ )}
+ <div className="min-w-0">
+ <p className="text-sm font-semibold text-foreground">
+ {isReauth ? "Re-authorize live mandate" : "Live trading mandate"}
+ </p>
+ {proposal.intent_normalized && (
+ <p className="text-xs text-muted-foreground">{proposal.intent_normalized}</p>
+ )}
+ {proposal.account && (
+ <p className="mt-0.5 text-[11px] text-muted-foreground">
+ {proposal.account.broker} · {proposal.account.type} account · funded by {proposal.account.funded_by}
+ </p>
+ )}
+ </div>
+ </div>
+
+ <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
+ {proposal.profiles.map((profile) => (
+ <ProfileTile
+ key={profile.ordinal}
+ profile={profile}
+ active={adjustingOrdinal === profile.ordinal}
+ busy={busyOrdinal === profile.ordinal}
+ disabled={busyOrdinal != null}
+ adjusting={adjustingOrdinal === profile.ordinal}
+ onCommit={() => handleCommit(profile.ordinal)}
+ onAdjustToggle={() =>
+ setAdjustingOrdinal((cur) => (cur === profile.ordinal ? null : profile.ordinal))
+ }
+ onAdjustCancel={() => setAdjustingOrdinal(null)}
+ onAdjustSubmit={(text) => {
+ setAdjustingOrdinal(null);
+ onAdjust(`For mandate proposal "${profile.label}" (option ${profile.ordinal}): ${text}`);
+ }}
+ />
+ ))}
+ </div>
+
+ <div className="grid gap-1.5 border-t border-border/60 pt-2 text-[11px] text-muted-foreground">
+ {proposal.funding_note && (
+ <p className="flex items-start gap-1.5">
+ <Wallet className="mt-0.5 h-3 w-3 shrink-0" />
+ <span>{proposal.funding_note}</span>
+ </p>
+ )}
+ {proposal.halt_note && (
+ <p className="flex items-start gap-1.5">
+ <OctagonX className="mt-0.5 h-3 w-3 shrink-0 text-destructive" />
+ <span>{proposal.halt_note}</span>
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+});
diff --git a/frontend/src/components/chat/RunnerStatus.tsx b/frontend/src/components/chat/RunnerStatus.tsx
new file mode 100644
index 000000000..ea32c0c30
--- /dev/null
+++ b/frontend/src/components/chat/RunnerStatus.tsx
@@ -0,0 +1,298 @@
+import { memo, useCallback, useState } from "react";
+import {
+ Activity,
+ Power,
+ PlugZap,
+ ShieldCheck,
+ Clock,
+ Loader2,
+ ChevronDown,
+ CircleDot,
+ CircleSlash,
+ OctagonX,
+} from "lucide-react";
+import { toast } from "sonner";
+import {
+ api,
+ type LiveStatus,
+ type LiveBrokerStatus,
+ type LiveMandateLimits,
+} from "@/lib/api";
+
+interface Props {
+ /** Shared `GET /live/status` snapshot, polled once by the parent (Agent.tsx).
+ * `null` until the first poll resolves. */
+ status: LiveStatus | null;
+ /** True when the status endpoint is not wired on this backend (404/501) — hide. */
+ unavailable?: boolean;
+ /** When true, every broker's halted banner reflects the global kill switch. */
+ halted?: boolean;
+ /** Forces the parent to re-poll immediately (e.g. after a runner start/stop). */
+ onRefresh: () => void;
+}
+
+function formatUsd(value: number | undefined): string {
+ if (value == null || !Number.isFinite(value)) return "—";
+ return `$${value.toLocaleString("en-US", { maximumFractionDigits: 0 })}`;
+}
+
+function formatRelative(iso: string | null | undefined): string {
+ if (!iso) return "never";
+ const then = new Date(iso).getTime();
+ if (!Number.isFinite(then)) return "unknown";
+ const deltaSec = Math.round((Date.now() - then) / 1000);
+ if (deltaSec < 0) return "just now";
+ if (deltaSec < 60) return `${deltaSec}s ago`;
+ if (deltaSec < 3600) return `${Math.floor(deltaSec / 60)}m ago`;
+ if (deltaSec < 86_400) return `${Math.floor(deltaSec / 3600)}h ago`;
+ return `${Math.floor(deltaSec / 86_400)}d ago`;
+}
+
+function formatCountdown(iso: string | undefined): { label: string; expired: boolean; soon: boolean } {
+ if (!iso) return { label: "—", expired: false, soon: false };
+ const target = new Date(iso).getTime();
+ if (!Number.isFinite(target)) return { label: "unknown", expired: false, soon: false };
+ const deltaSec = Math.round((target - Date.now()) / 1000);
+ if (deltaSec <= 0) return { label: "expired", expired: true, soon: false };
+ const days = Math.floor(deltaSec / 86_400);
+ const hours = Math.floor((deltaSec % 86_400) / 3600);
+ const minutes = Math.floor((deltaSec % 3600) / 60);
+ const soon = deltaSec < 86_400;
+ if (days > 0) return { label: `${days}d ${hours}h`, expired: false, soon };
+ if (hours > 0) return { label: `${hours}h ${minutes}m`, expired: false, soon };
+ return { label: `${minutes}m`, expired: false, soon };
+}
+
+function summarizeLimits(limits: LiveMandateLimits | undefined): string {
+ if (!limits) return "";
+ const parts: string[] = [];
+ if (limits.max_order_usd != null) parts.push(`≤${formatUsd(limits.max_order_usd)}/order`);
+ if (limits.daily_trade_cap != null) parts.push(`${limits.daily_trade_cap}/day`);
+ if (limits.leverage != null) {
+ const lev = typeof limits.leverage === "number"
+ ? (limits.leverage <= 1 ? "no leverage" : `${limits.leverage}×`)
+ : (limits.leverage.toLowerCase() === "none" ? "no leverage" : limits.leverage);
+ parts.push(lev);
+ }
+ return parts.join(" · ");
+}
+
+function BrokerRow({
+ broker,
+ halted,
+ onRefresh,
+}: {
+ broker: LiveBrokerStatus;
+ halted: boolean;
+ onRefresh: () => void;
+}) {
+ const [busy, setBusy] = useState(false);
+ const runnerAlive = broker.runner?.alive ?? false;
+ const mandate = broker.mandate ?? null;
+ const countdown = formatCountdown(mandate?.expires_at);
+
+ const toggleRunner = useCallback(async () => {
+ if (busy) return;
+ setBusy(true);
+ try {
+ if (runnerAlive) {
+ await api.stopLiveRunner(broker.broker);
+ toast.success(`Runner stopped for ${broker.broker}`);
+ } else {
+ await api.startLiveRunner(broker.broker);
+ toast.success(`Runner started for ${broker.broker}`);
+ }
+ onRefresh();
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : "Runner control failed.");
+ } finally {
+ setBusy(false);
+ }
+ }, [broker.broker, busy, runnerAlive, onRefresh]);
+
+ return (
+ <div className="grid gap-2 rounded-lg border bg-muted/20 p-2.5">
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className="truncate text-xs font-semibold capitalize text-foreground">{broker.broker}</span>
+ {broker.authorized ? (
+ <span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-1.5 py-0.5 text-[10px] font-medium text-emerald-600 dark:text-emerald-400">
+ <ShieldCheck className="h-2.5 w-2.5" />
+ Authorized
+ </span>
+ ) : (
+ <span className="inline-flex items-center gap-1 rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">
+ <CircleSlash className="h-2.5 w-2.5" />
+ Not connected
+ </span>
+ )}
+ </div>
+ </div>
+
+ {/* Connect-broker on-ramp for unauthorized brokers (C2). The OAuth bootstrap
+ is a desktop-only CLI step (SPEC §4 headless behavior), so the web surface
+ surfaces the discoverable instruction rather than driving the browser flow. */}
+ {!broker.authorized ? (
+ <div className="grid gap-1.5 rounded-md border border-dashed border-primary/30 bg-primary/5 p-2">
+ <div className="flex items-center gap-1.5 text-[11px] font-medium text-primary">
+ <PlugZap className="h-3 w-3 shrink-0" />
+ Connect this broker to enable live trading
+ </div>
+ <p className="text-[10px] leading-relaxed text-muted-foreground">
+ Authorize on a desktop session:{" "}
+ <code className="rounded bg-background px-1 py-0.5 font-mono text-[10px] text-foreground">
+ vibe-trading live authorize {broker.broker}
+ </code>
+ . The channel stays read-only until OAuth succeeds and a mandate is committed.
+ </p>
+ </div>
+ ) : (
+ <>
+ <div className="grid grid-cols-2 gap-2">
+ <div className="rounded-md border bg-background/60 p-2">
+ <div className="flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
+ <CircleDot className={["h-2.5 w-2.5", runnerAlive ? "text-emerald-500" : "text-muted-foreground"].join(" ")} />
+ Runner
+ </div>
+ <div className={["mt-0.5 text-xs font-semibold", runnerAlive ? "text-emerald-600 dark:text-emerald-400" : "text-muted-foreground"].join(" ")}>
+ {runnerAlive ? "Running" : "Stopped"}
+ </div>
+ </div>
+ <div className="rounded-md border bg-background/60 p-2">
+ <div className="flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
+ <Activity className="h-2.5 w-2.5" />
+ Last tick
+ </div>
+ <div className="mt-0.5 text-xs font-medium text-foreground">
+ {formatRelative(broker.runner?.last_tick)}
+ </div>
+ </div>
+ </div>
+
+ {mandate ? (
+ <div className="rounded-md border bg-background/60 p-2">
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
+ <ShieldCheck className="h-2.5 w-2.5" />
+ Active mandate
+ </div>
+ {mandate.expires_at && (
+ <span
+ className={[
+ "inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[10px] font-medium",
+ countdown.expired
+ ? "bg-destructive/10 text-destructive"
+ : countdown.soon
+ ? "bg-amber-500/10 text-amber-600 dark:text-amber-400"
+ : "bg-muted text-muted-foreground",
+ ].join(" ")}
+ title={`Expires ${new Date(mandate.expires_at).toLocaleString()}`}
+ >
+ <Clock className="h-2.5 w-2.5" />
+ {countdown.expired ? "expired" : `expires in ${countdown.label}`}
+ </span>
+ )}
+ </div>
+ <div className="mt-0.5 font-mono text-[11px] text-foreground">
+ {summarizeLimits(mandate.limits) || "limits unavailable"}
+ </div>
+ </div>
+ ) : (
+ <div className="rounded-md border border-dashed bg-background/40 p-2 text-[10px] text-muted-foreground">
+ No active mandate. Ask the agent to propose one, then commit it to begin autonomous trading.
+ </div>
+ )}
+
+ <div className="flex items-center justify-between gap-2">
+ {halted ? (
+ <span className="inline-flex items-center gap-1 text-[10px] font-medium text-destructive">
+ <OctagonX className="h-3 w-3" />
+ Halted — runner controls disabled
+ </span>
+ ) : (
+ <span className="text-[10px] text-muted-foreground">
+ {runnerAlive ? "Trading autonomously inside mandate" : "Idle"}
+ </span>
+ )}
+ <button
+ type="button"
+ onClick={toggleRunner}
+ disabled={busy || halted || !mandate}
+ className={[
+ "inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium transition-colors disabled:opacity-40",
+ runnerAlive
+ ? "border-destructive/40 text-destructive hover:bg-destructive/10"
+ : "border-primary/40 text-primary hover:bg-primary/10",
+ ].join(" ")}
+ title={runnerAlive ? "Stop the persistent runner" : "Start the persistent runner"}
+ >
+ {busy ? <Loader2 className="h-3 w-3 animate-spin" /> : <Power className="h-3 w-3" />}
+ {runnerAlive ? "Stop runner" : "Start runner"}
+ </button>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
+
+/**
+ * Persistent live-runtime status panel (SPEC §7.5 + audit C2).
+ *
+ * Renders the shared `GET /live/status` snapshot (polled once by Agent.tsx and passed
+ * in as `status`, so the kill switch and this panel share a single poller). Per authorized
+ * broker: runner running state, last heartbeat tick, the active mandate's limits, and an
+ * expiry countdown. `onRefresh` asks the parent to re-poll after a runner start/stop. Unauthorized
+ * brokers get a "Connect broker" on-ramp so a web user can discover how to enable live
+ * trading. Runner start/stop are privileged surface fetches (`api.startLiveRunner` /
+ * `api.stopLiveRunner`), never chat messages. Collapses to a compact toggle.
+ */
+export const RunnerStatus = memo(function RunnerStatus({ status, unavailable, halted, onRefresh }: Props) {
+ const [open, setOpen] = useState(false);
+
+ if (unavailable) return null;
+ if (!status || status.brokers.length === 0) return null;
+
+ const isHalted = halted ?? status.halted;
+ const anyRunning = status.brokers.some((b) => b.runner?.alive);
+ const authorizedCount = status.brokers.filter((b) => b.authorized).length;
+
+ return (
+ <div className="grid gap-2">
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ className="inline-flex max-w-full items-center gap-1.5 justify-self-start rounded-lg bg-primary/10 px-2.5 py-1 text-left text-xs font-medium text-primary transition-colors hover:bg-primary/15"
+ aria-label="Live runtime status"
+ aria-expanded={open}
+ >
+ <Activity className="h-3 w-3 shrink-0" />
+ <span className="shrink-0">Live runtime</span>
+ <span className="truncate text-muted-foreground">
+ {authorizedCount > 0 ? `${authorizedCount} connected` : "no broker connected"}
+ </span>
+ {anyRunning && !isHalted && (
+ <span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-1.5 py-0.5 text-[10px] font-medium text-emerald-600 dark:text-emerald-400">
+ <CircleDot className="h-2.5 w-2.5" />
+ running
+ </span>
+ )}
+ {isHalted && (
+ <span className="inline-flex items-center gap-1 rounded-full bg-destructive/10 px-1.5 py-0.5 text-[10px] font-medium text-destructive">
+ <OctagonX className="h-2.5 w-2.5" />
+ halted
+ </span>
+ )}
+ <ChevronDown className={["h-3 w-3 shrink-0 transition-transform", open ? "rotate-180" : ""].join(" ")} aria-hidden="true" />
+ </button>
+
+ {open && (
+ <div className="grid gap-2 rounded-xl border border-primary/20 bg-background/95 p-3 shadow-sm">
+ {status.brokers.map((broker) => (
+ <BrokerRow key={broker.broker} broker={broker} halted={isHalted} onRefresh={onRefresh} />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+});
diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts
index 31929c6bc..7e3969c60 100644
--- a/frontend/src/hooks/useSSE.ts
+++ b/frontend/src/hooks/useSSE.ts
@@ -83,6 +83,7 @@ export function useSSE(config?: SSEConfig) {
"text_delta", "thinking_done", "tool_call", "tool_result", "compact",
"attempt.completed", "attempt.failed",
"goal.created", "goal.evidence", "goal.updated",
+ "mandate.proposal", "mandate.committed", "live.halted", "live.resumed", "live.action",
"heartbeat", "done",
];
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 046111582..79a128a90 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -155,6 +155,33 @@ export const api = {
}),
alphaBenchStreamUrl: (jobId: string) =>
withAuthQuery(`${BASE}/alpha/bench/${encodeURIComponent(jobId)}/stream`),
+
+ // Live trading channel — privileged surface actions (NOT agent tools).
+ // commit is the ONLY action that writes a mandate; halt trips the kill switch.
+ commitMandate: (body: CommitMandateRequest) =>
+ request<CommitMandateResponse>("/mandate/commit", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+ haltLive: (session_id: string) =>
+ request<HaltLiveResponse>("/live/halt", {
+ method: "POST",
+ body: JSON.stringify({ session_id }),
+ }),
+ // Read the persistent runtime status across all authorized brokers (SPEC §7.5).
+ // Polled by the RunnerStatus panel; a plain authenticated GET, never a chat message.
+ getLiveStatus: () => request<LiveStatus>("/live/status"),
+ // Start/stop the persistent runner (SPEC §7.5). Privileged surface actions, not agent tools.
+ startLiveRunner: (broker?: string) =>
+ request<LiveRunnerResponse>("/live/runner/start", {
+ method: "POST",
+ body: JSON.stringify(broker ? { broker } : {}),
+ }),
+ stopLiveRunner: (broker?: string) =>
+ request<LiveRunnerResponse>("/live/runner/stop", {
+ method: "POST",
+ body: JSON.stringify(broker ? { broker } : {}),
+ }),
};
// --- Swarm types ---
@@ -644,6 +671,148 @@ export interface AlphaBenchResult {
by_theme: Record<string, { alive: number; reversed: number; dead: number }>;
}
+// --- Live trading channel types ---
+
+/** One mandate profile inside a `mandate.proposal` event (SPEC Consent §1). */
+export interface MandateProfile {
+ ordinal: number;
+ label: string;
+ /** Concrete ticker list, or a structural universe descriptor (e.g. "tech_sector"). */
+ universe: string[] | string;
+ max_order_usd: number;
+ daily_trade_cap: number;
+ /** "none" for cash-only, otherwise a leverage descriptor/multiple. */
+ leverage: string | number;
+ instruments: string[];
+ notes?: string;
+}
+
+/** Account block of a `mandate.proposal` event. */
+export interface MandateProposalAccount {
+ broker: string;
+ type: string;
+ funded_by: string;
+}
+
+/** Payload of the `mandate.proposal` SSE event (SPEC Consent §1). */
+export interface MandateProposal {
+ type?: string;
+ proposal_id: string;
+ session_id?: string;
+ intent_normalized?: string;
+ account?: MandateProposalAccount;
+ ceilings_ref?: string;
+ profiles: MandateProfile[];
+ funding_note?: string;
+ halt_note?: string;
+ /** Present only when this proposal was triggered by a mandate breach (SPEC Consent §3). */
+ reauth_for?: { breach_id?: string } | null;
+}
+
+/** Payload of the `mandate.committed` SSE event (SPEC Consent §1 COMMIT). */
+export interface MandateCommitted {
+ proposal_id?: string;
+ mandate_id?: string;
+ consent_record_id?: string;
+ selected_ordinal?: number;
+ broker?: string;
+ /** Resolved limits, surfaced for the compact active-mandate badge. */
+ max_order_usd?: number;
+ daily_trade_cap?: number;
+ expires_at?: string;
+}
+
+/** Payload of the `live.halted` SSE event (SPEC Consent §4). */
+export interface LiveHalted {
+ broker?: string;
+ tripped_at?: string;
+ by?: string;
+ reason?: string;
+}
+
+/** Payload of the `live.action` SSE event (SPEC Consent §5 audit notify). */
+export interface LiveAction {
+ audit_id?: string;
+ ts?: string;
+ kind: string;
+ intent_normalized?: string;
+ outcome?: string;
+ broker?: string;
+ remote_tool?: string;
+ error?: string | null;
+}
+
+export interface CommitMandateRequest {
+ proposal_id: string;
+ selected_ordinal: number;
+ /** Present only on the adjust path (SPEC Consent §3); null otherwise. */
+ adjustments?: Record<string, unknown> | null;
+ /** Explicit affirmative consent; the surface sets it on the user's click. */
+ consent_ack: boolean;
+ session_id?: string;
+}
+
+export interface CommitMandateResponse {
+ mandate_id: string;
+ consent_record_id: string;
+ selected_ordinal?: number;
+ broker?: string;
+ max_order_usd?: number;
+ daily_trade_cap?: number;
+ expires_at?: string;
+}
+
+export interface HaltLiveResponse {
+ status: string;
+ tripped_at?: string;
+}
+
+/** Mandate limits surfaced inside a `GET /live/status` broker entry (SPEC §7.5). */
+export interface LiveMandateLimits {
+ max_order_usd?: number;
+ daily_trade_cap?: number;
+ leverage?: string | number;
+ instruments?: string[];
+ universe?: string[] | string;
+ [key: string]: unknown;
+}
+
+/** Active mandate block of a `GET /live/status` broker entry. */
+export interface LiveMandateStatus {
+ mandate_id?: string;
+ limits?: LiveMandateLimits;
+ /** ISO timestamp the mandate auto-expires (SPEC §7.5 #7 proactive expiry). */
+ expires_at?: string;
+}
+
+/** Runner liveness block of a `GET /live/status` broker entry (SPEC §7.5 #3). */
+export interface LiveRunnerLiveness {
+ alive: boolean;
+ /** ISO timestamp of the last heartbeat tick; null if the runner never started. */
+ last_tick?: string | null;
+}
+
+/** One broker entry in the `GET /live/status` response. */
+export interface LiveBrokerStatus {
+ broker: string;
+ authorized: boolean;
+ mandate?: LiveMandateStatus | null;
+ runner: LiveRunnerLiveness;
+}
+
+/** Response of `GET /live/status` (SPEC §7.5 runner status panel + C2). */
+export interface LiveStatus {
+ brokers: LiveBrokerStatus[];
+ halted: boolean;
+}
+
+/** Response of `POST /live/runner/start|stop`. */
+export interface LiveRunnerResponse {
+ status: string;
+ broker?: string;
+ alive?: boolean;
+}
+
export interface MessageItem {
message_id: string;
session_id: string;
diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsx
index f26654943..eb54c3889 100644
--- a/frontend/src/pages/Agent.tsx
+++ b/frontend/src/pages/Agent.tsx
@@ -1,10 +1,10 @@
import { useEffect, useRef, useState, useMemo, useCallback, type FormEvent } from "react";
import { useSearchParams } from "react-router-dom";
-import { Send, Loader2, ArrowDown, Square, Download, Plus, Paperclip, X, Users, Target, ChevronDown, Pencil, Check, Play } from "lucide-react";
+import { Send, Loader2, ArrowDown, Square, Download, Plus, Paperclip, X, Users, Target, ChevronDown, Pencil, Check, Play, OctagonX, Activity, Ban, CheckCircle2 } from "lucide-react";
import { toast } from "sonner";
import { useAgentStore } from "@/stores/agent";
import { useSSE } from "@/hooks/useSSE";
-import { ApiError, api, type GoalSnapshot } from "@/lib/api";
+import { ApiError, api, type GoalSnapshot, type MandateProposal, type MandateCommitted, type LiveAction, type LiveHalted, type LiveStatus } from "@/lib/api";
import { isReportWorthyRun } from "@/lib/runReports";
import type { AgentMessage, ToolCallEntry } from "@/types/agent";
import { AgentAvatar } from "@/components/chat/AgentAvatar";
@@ -13,6 +13,8 @@ import { MessageBubble } from "@/components/chat/MessageBubble";
import { ThinkingTimeline } from "@/components/chat/ThinkingTimeline";
import { ConversationTimeline } from "@/components/chat/ConversationTimeline";
import { ToolProgressIndicator } from "@/components/chat/ToolProgressIndicator";
+import { MandateProposalCard } from "@/components/chat/MandateProposalCard";
+import { RunnerStatus } from "@/components/chat/RunnerStatus";
/* ---------- Message grouping ---------- */
type MsgGroup =
@@ -37,6 +39,72 @@ function groupMessages(msgs: AgentMessage[]): MsgGroup[] {
const act = () => useAgentStore.getState();
+/** Poll cadence for the shared `GET /live/status` snapshot. */
+const LIVE_STATUS_POLL_INTERVAL_MS = 15_000;
+
+/* ---------- Live trading channel ----------
+ * Mandate proposals and live-action chips render as standalone timeline items,
+ * never folded into the thinking timeline (SPEC Consent §2 grouping note). They
+ * are driven by dedicated state rather than the chat message store because they
+ * are privileged-surface artifacts, not chat messages, and the proposal card
+ * needs commit/adjust callbacks the generic MessageBubble does not carry. */
+interface ProposalItem {
+ kind: "proposal";
+ timestamp: number;
+ proposal: MandateProposal;
+}
+interface LiveActionItem {
+ kind: "live_action";
+ timestamp: number;
+ action: LiveAction;
+}
+type LiveItem = ProposalItem | LiveActionItem;
+
+function liveActionStyle(kind: string): { icon: typeof Activity; tone: string } {
+ switch (kind) {
+ case "order_rejected":
+ case "breach":
+ return { icon: Ban, tone: "border-amber-500/40 bg-amber-500/5 text-amber-600 dark:text-amber-400" };
+ case "halt_tripped":
+ return { icon: OctagonX, tone: "border-destructive/40 bg-destructive/5 text-destructive" };
+ case "mandate_committed":
+ case "halt_cleared":
+ return { icon: CheckCircle2, tone: "border-emerald-500/40 bg-emerald-500/5 text-emerald-600 dark:text-emerald-400" };
+ default:
+ return { icon: Activity, tone: "border-sky-500/40 bg-sky-500/5 text-sky-600 dark:text-sky-400" };
+ }
+}
+
+function liveActionLabel(action: LiveAction): string {
+ return action.kind.replace(/_/g, " ");
+}
+
+function LiveActionChip({ action }: { action: LiveAction }) {
+ const { icon: Icon, tone } = liveActionStyle(action.kind);
+ return (
+ <div className="flex gap-3">
+ <AgentAvatar />
+ <div className="flex-1 min-w-0">
+ <div className={["inline-flex max-w-full flex-wrap items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs", tone].join(" ")}>
+ <Icon className="h-3 w-3 shrink-0" />
+ <span className="shrink-0 font-medium uppercase tracking-wide text-[10px]">LIVE</span>
+ <span className="shrink-0 font-medium">{liveActionLabel(action)}</span>
+ {action.intent_normalized && (
+ <span className="truncate text-foreground/80">· {action.intent_normalized}</span>
+ )}
+ {action.outcome && (
+ <span className="shrink-0 font-mono text-[10px] text-muted-foreground">· {action.outcome}</span>
+ )}
+ {action.remote_tool && (
+ <span className="shrink-0 font-mono text-[10px] text-muted-foreground">· {action.remote_tool}</span>
+ )}
+ {action.error && <span className="truncate text-destructive">· {action.error}</span>}
+ </div>
+ </div>
+ </div>
+ );
+}
+
function isCriterionStatusMet(status: string): boolean {
return !["", "pending", "open", "unsatisfied"].includes(status.toLowerCase());
}
@@ -138,6 +206,23 @@ export function Agent() {
const [goalEditActive, setGoalEditActive] = useState(false);
const [goalEditValue, setGoalEditValue] = useState("");
+ /* Live trading channel state (SPEC Consent §1/§4/§5) */
+ const [liveItems, setLiveItems] = useState<LiveItem[]>([]);
+ const [committedMandates, setCommittedMandates] = useState<Record<string, MandateCommitted>>({});
+ const [liveHalted, setLiveHalted] = useState<LiveHalted | null>(null);
+ const [halting, setHalting] = useState(false);
+ /* Bumped to force an immediate live-status re-poll on a live event
+ * (commit / halt / resume / runner-affecting action) rather than waiting a tick. */
+ const [liveStatusRefresh, setLiveStatusRefresh] = useState(0);
+ /* Shared `GET /live/status` snapshot. Owned here (single poller) and passed down
+ * to RunnerStatus, so the global kill switch can be shown whenever live trading
+ * could be active out-of-band (CLI/another session), not only off in-session SSE
+ * items (audit M2: always-available global halt — SPEC Consent §4). */
+ const [liveStatus, setLiveStatus] = useState<LiveStatus | null>(null);
+ /* The status endpoint is not wired on every backend; a 404/501 hides the panel
+ * and removes status from the kill-switch visibility condition. */
+ const [liveStatusUnavailable, setLiveStatusUnavailable] = useState(false);
+
const messages = useAgentStore(s => s.messages);
const streamingText = useAgentStore(s => s.streamingText);
const status = useAgentStore(s => s.status);
@@ -439,6 +524,59 @@ export function Agent() {
loadGoalSnapshot(sid);
},
+ "mandate.proposal": (d) => {
+ touch();
+ const proposal = d as unknown as MandateProposal;
+ if (!proposal.proposal_id || !Array.isArray(proposal.profiles)) return;
+ setLiveItems((items) => [...items, { kind: "proposal", timestamp: Date.now(), proposal }]);
+ scrollToBottom();
+ },
+
+ "mandate.committed": (d) => {
+ touch();
+ const committed = d as unknown as MandateCommitted;
+ if (!committed.proposal_id) return;
+ setCommittedMandates((prev) => ({ ...prev, [committed.proposal_id as string]: committed }));
+ // A fresh mandate may bring up the runner; refresh the runtime panel now.
+ setLiveStatusRefresh((n) => n + 1);
+ scrollToBottom();
+ },
+
+ "live.halted": (d) => {
+ touch();
+ const halted = d as unknown as LiveHalted;
+ // Preemptive kill switch: the server has cancelled resting orders and may have
+ // flattened positions (SPEC §7.5 #6). Reflect the halted state across surfaces;
+ // the RunnerStatus panel re-polls so its per-broker rows show "halted".
+ setLiveHalted(halted);
+ setLiveStatusRefresh((n) => n + 1);
+ toast.warning("Live trading halted — runner stopped, resting orders cancelled");
+ },
+
+ "live.resumed": (d) => {
+ touch();
+ // Kill switch cleared via a privileged surface action (SPEC Consent §4);
+ // clear the halted banner and re-poll runtime status.
+ void d;
+ setLiveHalted(null);
+ setLiveStatusRefresh((n) => n + 1);
+ toast.success("Live trading resumed");
+ },
+
+ "live.action": (d) => {
+ touch();
+ const action = d as unknown as LiveAction;
+ if (!action.kind) return;
+ setLiveItems((items) => [...items, { kind: "live_action", timestamp: Date.now(), action }]);
+ if (action.kind === "halt_tripped") setLiveHalted({ reason: action.intent_normalized });
+ if (action.kind === "halt_cleared") setLiveHalted(null);
+ // Mandate-affecting / runner-affecting actions should refresh the runtime panel.
+ if (["mandate_committed", "halt_tripped", "halt_cleared"].includes(action.kind)) {
+ setLiveStatusRefresh((n) => n + 1);
+ }
+ scrollToBottom();
+ },
+
heartbeat: () => {},
reconnect: (d) => { act().setSseStatus("reconnecting", Number(d.attempt ?? 0)); },
});
@@ -451,6 +589,11 @@ export function Agent() {
const gen = genRef.current + 1;
genRef.current = gen;
doDisconnect();
+ // Live-channel timeline items are per-session; clear on switch.
+ setLiveItems([]);
+ setCommittedMandates({});
+ setLiveHalted(null);
+ setLiveStatusRefresh((n) => n + 1);
if (curSid && curMsgs.length > 0) cacheSession(curSid, curMsgs);
// Atomic switch: cache hit = instant, cache miss = show loading skeleton
@@ -465,11 +608,44 @@ export function Agent() {
} else if (!urlSessionId && curSid) {
genRef.current += 1;
doDisconnect();
+ setLiveItems([]);
+ setCommittedMandates({});
+ setLiveHalted(null);
+ setLiveStatusRefresh((n) => n + 1);
if (curSid && curMsgs.length > 0) cacheSession(curSid, curMsgs);
reset();
}
}, [urlSessionId, doDisconnect, loadSessionMessages, setupSSE, forceScrollToBottom]);
+ /* Single shared poller for `GET /live/status`. RunnerStatus consumes this snapshot
+ * as a prop rather than polling independently, and the global kill switch reads it
+ * to stay available whenever live trading could be active out-of-band. */
+ const refreshLiveStatus = useCallback(async () => {
+ try {
+ const next = await api.getLiveStatus();
+ setLiveStatus(next);
+ setLiveStatusUnavailable(false);
+ } catch (error) {
+ // A 404/501 means the runtime endpoint is not wired on this backend; treat the
+ // status source as unavailable. Any other failure keeps the last snapshot.
+ if (error instanceof ApiError && (error.status === 404 || error.status === 501)) {
+ setLiveStatus(null);
+ setLiveStatusUnavailable(true);
+ }
+ }
+ }, []);
+
+ useEffect(() => {
+ refreshLiveStatus();
+ const timer = setInterval(refreshLiveStatus, LIVE_STATUS_POLL_INTERVAL_MS);
+ return () => clearInterval(timer);
+ }, [refreshLiveStatus]);
+
+ // Force an immediate re-poll when a live event bumps refreshKey (commit/halt/resume).
+ useEffect(() => {
+ if (liveStatusRefresh > 0) refreshLiveStatus();
+ }, [liveStatusRefresh, refreshLiveStatus]);
+
useEffect(() => {
if (!sessionId) {
setGoalSnapshot(null);
@@ -588,6 +764,28 @@ export function Agent() {
}
};
+ const handleHaltLive = useCallback(async () => {
+ if (halting) return;
+ setHalting(true);
+ try {
+ // The kill switch is global and must fire even with no active chat session
+ // (e.g. a runner started from the CLI / another session). The backend scopes
+ // the SSE broadcast by session_id when present; an empty string is a valid
+ // global trip.
+ await api.haltLive(sessionId ?? "");
+ // Preemptive halt: the server trips the kill switch (cancel resting orders +
+ // optional flatten per SPEC §7.5 #6) and broadcasts live.halted. Reflect
+ // optimistically and re-poll the runtime panel so the runner shows stopped.
+ setLiveHalted((cur) => cur ?? { by: "frontend", tripped_at: new Date().toISOString() });
+ setLiveStatusRefresh((n) => n + 1);
+ toast.success("Live trading halted");
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : "Failed to halt live trading.");
+ } finally {
+ setHalting(false);
+ }
+ }, [sessionId, halting]);
+
const handleCancelGoal = useCallback(async () => {
if (!sessionId || !goalSnapshot) return;
try {
@@ -734,6 +932,42 @@ export function Agent() {
const groups = useMemo(() => groupMessages(messages), [messages]);
const goalProgress = useMemo(() => getGoalProgress(goalSnapshot), [goalSnapshot]);
+ /* Merge message groups with live-channel items, ordered by timestamp, so a
+ * mandate proposal / live-action chip renders inline at the point it arrived. */
+ type TimelineRow =
+ | { sort: number; render: "group"; group: MsgGroup; key: string }
+ | { sort: number; render: "live"; item: LiveItem; key: string };
+ const timelineRows = useMemo<TimelineRow[]>(() => {
+ const rows: TimelineRow[] = groups.map((g, i) => {
+ const ts = g.kind === "timeline" ? g.msgs[0].timestamp : g.msg.timestamp;
+ const key = g.kind === "timeline" ? `g_${g.msgs[0].id || g.msgs[0].timestamp}` : `g_${g.msg.id || g.msg.timestamp}_${i}`;
+ return { sort: ts, render: "group", group: g, key };
+ });
+ for (const item of liveItems) {
+ const key = item.kind === "proposal" ? `lp_${item.proposal.proposal_id}` : `la_${item.action.audit_id || item.timestamp}`;
+ rows.push({ sort: item.timestamp, render: "live", item, key });
+ }
+ return rows.sort((a, b) => a.sort - b.sort);
+ }, [groups, liveItems]);
+
+ /* Whether live trading could be active *anywhere* — the global kill switch must be
+ * available whenever it could (audit M2 / SPEC Consent §4). Driven off both
+ * in-session SSE artifacts AND the shared `/live/status` snapshot, so a runner
+ * started from the CLI or another browser session still surfaces the halt button
+ * in a freshly-loaded web session. */
+ const liveStatusActive =
+ liveStatus != null &&
+ (liveStatus.halted ||
+ liveStatus.brokers.some((b) => b.authorized || b.runner?.alive || b.mandate != null));
+ const liveActive =
+ liveItems.length > 0 ||
+ Object.keys(committedMandates).length > 0 ||
+ liveHalted != null ||
+ liveStatusActive;
+ /* The kill switch reflects a halt from either an in-session SSE event or the polled
+ * status, so the halted/resumed state stays consistent across surfaces. */
+ const liveIsHalted = liveHalted != null || (liveStatus?.halted ?? false);
+
return (
<div className="flex flex-col flex-1 min-w-0 overflow-hidden h-full">
<div ref={listRef} className="flex-1 overflow-auto p-6 scroll-smooth relative">
@@ -753,19 +987,34 @@ export function Agent() {
)}
{!sessionLoading && messages.length === 0 && <WelcomeScreen onExample={runPrompt} />}
- {groups.map((g, i) => {
+ {timelineRows.map((row, rowIdx) => {
+ if (row.render === "live") {
+ if (row.item.kind === "proposal") {
+ return (
+ <MandateProposalCard
+ key={row.key}
+ proposal={row.item.proposal}
+ committed={committedMandates[row.item.proposal.proposal_id] ?? null}
+ onAdjust={runPrompt}
+ />
+ );
+ }
+ return <LiveActionChip key={row.key} action={row.item.action} />;
+ }
+ const g = row.group;
if (g.kind === "timeline") {
+ const isLastRow = rowIdx === timelineRows.length - 1;
return (
<ThinkingTimeline
- key={g.msgs[0].id || g.msgs[0].timestamp}
+ key={row.key}
messages={g.msgs}
- isLatest={i === groups.length - 1 && status === "streaming"}
+ isLatest={isLastRow && status === "streaming"}
/>
);
}
const msgIdx = messages.indexOf(g.msg);
return (
- <div key={g.msg.id || g.msg.timestamp} data-msg-idx={msgIdx}>
+ <div key={row.key} data-msg-idx={msgIdx}>
<MessageBubble msg={g.msg} onRetry={g.msg.type === "error" ? handleRetry : undefined} />
</div>
);
@@ -1002,6 +1251,14 @@ export function Agent() {
)}
</div>
)}
+ {/* Persistent live runtime status panel — sits alongside the goal/mandate
+ badges (SPEC §7.5 + audit C2). Self-hides when no broker is configured. */}
+ <RunnerStatus
+ status={liveStatus}
+ unavailable={liveStatusUnavailable}
+ halted={liveIsHalted}
+ onRefresh={refreshLiveStatus}
+ />
{/* Attachment badge */}
{attachment && (
<div className="flex items-center gap-1">
@@ -1021,6 +1278,29 @@ export function Agent() {
Uploading...
</div>
)}
+ {/* Persistent kill switch — distinct from the per-turn Stop button
+ above; disables all live order activity (SPEC Consent §4). */}
+ {liveActive && (
+ <div className="flex items-center gap-2">
+ {liveIsHalted ? (
+ <span className="inline-flex items-center gap-1.5 rounded-lg bg-destructive/10 px-2.5 py-1 text-xs font-medium text-destructive">
+ <OctagonX className="h-3 w-3" />
+ Live trading halted
+ </span>
+ ) : (
+ <button
+ type="button"
+ onClick={handleHaltLive}
+ disabled={halting}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-destructive/40 bg-destructive/5 px-2.5 py-1 text-xs font-medium text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-40"
+ title="Instantly halt all live trading for this session"
+ >
+ {halting ? <Loader2 className="h-3 w-3 animate-spin" /> : <OctagonX className="h-3 w-3" />}
+ Halt live trading
+ </button>
+ )}
+ </div>
+ )}
<div className="flex gap-2 items-end">
{/* "+" menu: PDF upload + Swarm presets */}
<div className="relative" ref={uploadMenuRef}>