"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Complete UTF-8 recovery, channel review, pinned portfolio surfaces and validation repairs
Haozhe Wu54e225de9fe7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex aa237fbc6..ba0a5ebac 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,37 @@ This project adheres to [Semantic Versioning](https://semver.org/).## [Unreleased]+### Maintenance — 2026-10-10++- Slack and Discord gain localized connection forms and read-only credential+ probes (#1764, #1777). Slack verifies both bot identity and Socket Mode app+ access; Discord requires a bot identity. HTTP 408/429 report temporary errors.+ Failed probes leave saved settings unchanged. Discord admission policies+ refresh without reconnecting.+- Recover sessions and attempts with invalid UTF-8 metadata, and skip malformed+ message records while preserving readable neighbors and original files (#1775).+ Redact environment-style credentials and URL userinfo (#1765); generic trade+ journals retain quantities and prices instead of being misclassified as Futu+ exports (#1766).+- Memory links recognize two-character identifiers (#1771). FTS recall expands+ past stale index rows until enough current memories are found or the index is+ exhausted (#1772).+- Pin portfolio research to an immutable snapshot (#1769): the agent accepts+ `snapshot_id`, the CLI supports `portfolio show --snapshot-id ID`, REST accepts+ the same identifier, and Web exports the displayed sanitized research snapshot+ as JSON. Unavailable or revoked snapshots never fall back to newer data.+ Technical indicators accept an optional ISO `end_date` and report provenance+ plus a fingerprint of their exact input bars (#1768).+- Exclude top-level process exit codes and elapsed times from observed financial+ evidence (#1767). Register existing figure/identity checks without changing+ their predicates (#1691); extract compaction, tuning, usage accounting and+ terminal outcome policy from the agent loop (#1631, #1678, #1662, #1641).+- Expand the options connector evidence checklist (#1770). Update compatible+ Python/frontend dependencies and pinned CI actions (#1692, #1668, #1667,+ #1666, #1665); align Vitest with its coverage plugin. Keep `uuid-utils` at+ 0.17.0 because the proposed 1.0.0 upgrade (#1670) conflicts with the current+ LangChain constraint. Preserve mootdx's retirement from the public canary.+### Maintenance — 2026-10-09- Channel edits to live-read settings apply without reconnecting, including adiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 6a91544ba..2fe698ec0 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -263,7 +263,8 @@ matrix row records a declaration; attach separate evidence for runtime claims.from read-side contract shapes. Keep unsupported shapes gated off; verifysupported shapes through the existing mandate caps against priced notional(premium times multiplier), one audit event per decision, and red-first- live-safety tests.+ live-safety tests. Premium notional is not maximum loss or exercise exposure;+ validate those limits separately where the instrument requires them.- [ ] Test live risk-increasing actions through the shared mandate gate,including account selection, limits, kill switch, and audit. Verify cancel,flatten, position management, and copy paths separately where implemented;diff --git a/README.md b/README.mdindex d97daffa7..b94dcc08b 100644--- a/README.md+++ b/README.md@@ -52,15 +52,18 @@> ⚠️ **Security warning:** The X account `VibeTrading_HKU`, Virtuals project `101845`, and token contract `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` are not official Vibe-Trading assets. We have never launched or endorsed any token or memecoin. Do not buy, connect a wallet, or sign anything. [Details](SECURITY.md#official-channels--impersonation).+- **2026-10-10** 🛠️ **Slack/Discord setup and reproducible research**: Localized channel forms verify bot credentials without saving changes ([#1764](https://github.com/HKUDS/Vibe-Trading/pull/1764), [#1777](https://github.com/HKUDS/Vibe-Trading/pull/1777)). Portfolio research can reuse an immutable snapshot, and Web exports its sanitized JSON ([#1769](https://github.com/HKUDS/Vibe-Trading/pull/1769)). Indicators report their date boundary and exact input fingerprint; corrupted session records recover without rewriting files. Memory recall, credential redaction and trade-journal detection are corrected. See [CHANGELOG](CHANGELOG.md).+- **2026-10-09** 🛠️ **Channel updates and backtest correctness**: Channel settings preserve embedded URL credentials and authenticated WeChat endpoints during in-place updates, with save/reset feedback in all nine languages ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737), [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742), [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). Cross-market option volatility uses only timestamps known at each bar; drawdown includes starting capital. Crypto/precious-metal routing, HK duplicate detection, cache recovery, scientific-notation amounts and missing-equity validation are corrected. mootdx leaves the default A-share chain. See [CHANGELOG](CHANGELOG.md) for all thirteen PRs.- **2026-10-08** 🔐 **Protected PDF reports and clearer broker reads**: Scheduled Email PDFs support optional AES-256 password protection across Web, CLI playbooks and agent confirmations; the password stays in private channel configuration ([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709)). KIS queries all three venue buckets, refreshes an explicitly expired token once, and reports incomplete reads as errors ([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726)). Derived formulas keep their arithmetic after descriptive labels while evidence checks remain enforced ([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728)).-- **2026-10-07** 🛠️ **Research continuity and reliable risk metrics**: Volatile workspace state now travels outside the system prompt, preserving its stable prefix ([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708)). Cross-market dates align correctly, missing prices no longer bridge return observations, and options Sortino uses full-sample downside deviation ([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710), [#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717), [#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727)). Loader fixtures share one OHLCV contract; credit valuation, style exposures, walk-forward folds and audit diagnostics are corrected.<details><summary>Earlier news</summary>+- **2026-10-07** 🛠️ **Research continuity and reliable risk metrics**: Volatile workspace state now travels outside the system prompt, preserving its stable prefix ([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708)). Cross-market dates align correctly, missing prices no longer bridge return observations, and options Sortino uses full-sample downside deviation ([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710), [#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717), [#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727)). Loader fixtures share one OHLCV contract; credit valuation, style exposures, walk-forward folds and audit diagnostics are corrected.+- **2026-10-06** 🛠️ **Live controls and report corrections**: Stopping a live runner cancels its current analysis and waits for scheduler cleanup, including startup cancellation and API shutdown; status timestamps use the correct units ([#1704](https://github.com/HKUDS/Vibe-Trading/pull/1704)). Emergency cancel/flatten scans skip malformed records without abandoning the remaining book ([#1703](https://github.com/HKUDS/Vibe-Trading/pull/1703)); broker schedules are stored separately and writes handle concurrency and partial writes. US equity half-days respect the early closing bell ([#1706](https://github.com/HKUDS/Vibe-Trading/pull/1706)). Report corrections preserve figures that passed validation, and bounded feedback no longer implies that unlisted figures passed ([#1702](https://github.com/HKUDS/Vibe-Trading/pull/1702)).- **2026-10-05** 🛠️ **Research prompts and calculation fixes**: Chat accepts longer research prompts and gives a localized recovery message when input is too large ([#1701](https://github.com/HKUDS/Vibe-Trading/pull/1701)). Backtests use full-sample Sortino downside deviation; grouped validation purges overlapping labels, covariance weights remain finite, shadow RSI uses Wilder seeds, and memory removal accepts filename stems. Invalid call aliases now receive exact source references for correction ([#1638](https://github.com/HKUDS/Vibe-Trading/pull/1638)); numeric validation stays unchanged.diff --git a/README_ar.md b/README_ar.mdindex 83574454d..ef43dc4d5 100644--- a/README_ar.md+++ b/README_ar.md@@ -52,15 +52,18 @@> ⚠️ **تحذير أمني:** حساب X باسم `VibeTrading_HKU`، ومشروع Virtuals رقم `101845`، وعقد التوكن `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` كلّها غير رسمية ولا تتبع Vibe-Trading. لم نُطلق أو نؤيد مطلقًا أي توكن أو عملة ميم. لا تشترِ هذا التوكن، ولا تربط محفظتك، ولا توقّع أي شيء. [التفاصيل](SECURITY.md#official-channels--impersonation).+- **2026-10-10** 🛠️ **إعداد Slack وDiscord وبحث قابل لإعادة الإنتاج**: تتحقق النماذج المترجمة من بيانات اعتماد البوت دون حفظ التغييرات ([#1764](https://github.com/HKUDS/Vibe-Trading/pull/1764)، [#1777](https://github.com/HKUDS/Vibe-Trading/pull/1777)). يعيد بحث المحفظة استخدام لقطات ثابتة، وتصدّر واجهة الويب JSON دون بيانات اعتماد أو أرقام حسابات ([#1769](https://github.com/HKUDS/Vibe-Trading/pull/1769)). تذكر المؤشرات حد التاريخ وبصمة المدخلات؛ تُستعاد سجلات الجلسة التالفة دون إعادة كتابة الملفات الأصلية. أُصلح استرجاع الذاكرة وإخفاء بيانات الاعتماد والتعرف على سجل التداول. راجع [CHANGELOG](CHANGELOG.md).+- **2026-10-09** 🛠️ **إعدادات القنوات ودقة الاختبارات التاريخية**: تحافظ تحديثات الإعدادات دون إعادة الاتصال على بيانات اعتماد الروابط وعنوان خادم WeChat الناتج عن المصادقة، وتعرض الواجهة نتائج الحفظ وإعادة التشغيل بتسع لغات ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737)، [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742)، [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). يعتمد تقلب الخيارات عبر الأسواق على التوقيتات المعروفة عند كل شمعة فقط، ويشمل التراجع رأس المال الأولي. صُححت مسارات بيانات العملات الرقمية والمعادن الثمينة، وكشف تكرار أسهم هونغ كونغ، واستعادة الذاكرة المؤقتة، والمبالغ بالصيغة العلمية، والتحقق من قيم حقوق الملكية المفقودة. أُزيل mootdx من سلسلة أسهم A الافتراضية. تفاصيل طلبات الدمج الثلاثة عشر في [CHANGELOG](CHANGELOG.md).- **2026-10-08** 🔐 **حماية تقارير PDF وتصحيح قراءات الوسيط**: تدعم تقارير البريد المجدولة حماية اختيارية بكلمة مرور عبر AES-256 في الويب وCLI وتأكيدات الوكيل؛ تُحفظ كلمة المرور في إعدادات القناة الخاصة فقط ([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709)). يستعلم KIS عن مسارات التداول الثلاثة ويجدد الرمز المنتهي صراحةً مرة واحدة ويرفض القراءة غير المكتملة ([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726)). تُحفظ الصيغة الحسابية بعد الوصف مع استمرار التحقق من الأدلة ([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728)).-- **2026-10-07** 🛠️ **استمرارية البحث وتصحيح مقاييس المخاطر**: نُقلت حالة التشغيل خارج تعليمات النظام للحفاظ على بادئة ثابتة ([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708)). صُححت محاذاة التواريخ بين الأسواق وعوائد الأسعار المفقودة وحساب Sortino للخيارات باستخدام العينة كاملةً ([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710)، [#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717)، [#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727)). تشترك اختبارات مصادر البيانات في عقد OHLCV واحد، مع إصلاحات لتقييم الائتمان والتعرضات والتحقق الزمني وتشخيص التدقيق.<details><summary>أخبار سابقة</summary>+- **2026-10-07** 🛠️ **استمرارية البحث وتصحيح مقاييس المخاطر**: نُقلت حالة التشغيل خارج تعليمات النظام للحفاظ على بادئة ثابتة ([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708)). صُححت محاذاة التواريخ بين الأسواق وعوائد الأسعار المفقودة وحساب Sortino للخيارات باستخدام العينة كاملةً ([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710)، [#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717)، [#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727)). تشترك اختبارات مصادر البيانات في عقد OHLCV واحد، مع إصلاحات لتقييم الائتمان والتعرضات والتحقق الزمني وتشخيص التدقيق.+- **2026-10-06** 🛠️ **إصلاح التحكم بالتداول وتصحيح التقارير**: يلغي إيقاف مشغّل التداول الفعلي التحليل الجاري وينتظر انتهاء المجدول، بما يشمل الإلغاء أثناء بدء التشغيل وإغلاق API، مع تصحيح وحدات الوقت في الحالة ([#1704](https://github.com/HKUDS/Vibe-Trading/pull/1704)). يتجاوز إلغاء الأوامر وإغلاق المراكز في الطوارئ السجلات غير الصالحة ويواصل معالجة الباقي ([#1703](https://github.com/HKUDS/Vibe-Trading/pull/1703)). تُحفظ جداول الوسطاء بصورة منفصلة مع معالجة الكتابات المتزامنة والجزئية. تُراعى ساعات الإغلاق المبكر للأسهم الأمريكية ([#1706](https://github.com/HKUDS/Vibe-Trading/pull/1706)). تحافظ تصحيحات التقارير على الأرقام التي اجتازت التحقق، ولا توحي الملاحظات المحدودة بأن الأرقام غير المذكورة قد اجتازته ([#1702](https://github.com/HKUDS/Vibe-Trading/pull/1702)).- **2026-10-05** 🛠️ **إدخال البحث وتصحيح الحسابات**: تدعم المحادثة نصوص بحث أطول وتوضح باللغة الحالية كيفية تقصير النص عند تجاوز الحد ([#1701](https://github.com/HKUDS/Vibe-Trading/pull/1701)). يستخدم Sortino انحراف الجانب السلبي عبر جميع الفترات، ويستبعد التحقق الجماعي التسميات المتداخلة. تحسنت أوزان التباين وRSI بمتوسط Wilder الأولي وحذف الذاكرة باسم الملف. عند استخدام اسم مستعار غير صحيح للاستدعاء، يقترح التصحيح مراجع الحقول الفعلية مع بقاء التحقق من الأرقام كما هو ([#1638](https://github.com/HKUDS/Vibe-Trading/pull/1638)).diff --git a/README_es.md b/README_es.mdindex e7b05fe51..c1eb5fdd6 100644--- a/README_es.md+++ b/README_es.md@@ -52,15 +52,18 @@> ⚠️ **Advertencia de seguridad:** la cuenta de X `VibeTrading_HKU`, el proyecto de Virtuals `101845` y el contrato de token `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` no son activos oficiales de Vibe-Trading. Nunca hemos lanzado ni respaldado ningún token o memecoin. No compres, conectes una wallet ni firmes nada. [Detalles](SECURITY.md#official-channels--impersonation).+- **2026-10-10** 🛠️ **Configuración de Slack/Discord y análisis reproducible**: Los formularios traducidos verifican credenciales del bot sin guardar cambios ([#1764](https://github.com/HKUDS/Vibe-Trading/pull/1764), [#1777](https://github.com/HKUDS/Vibe-Trading/pull/1777)). El análisis de cartera reutiliza instantáneas inmutables y la Web exporta JSON sin datos sensibles ([#1769](https://github.com/HKUDS/Vibe-Trading/pull/1769)). Los indicadores informan la fecha límite y la huella de los datos. Los registros de sesión dañados se recuperan sin reescribir los originales. También se corrigen búsqueda de memoria, filtrado de credenciales e importación de operaciones. Consulta [CHANGELOG](CHANGELOG.md).+- **2026-10-09** 🛠️ **Configuración de canales y correcciones de backtests**: Las actualizaciones sin reconexión conservan las credenciales de las URL y la dirección del servidor autenticado de WeChat; la web explica guardados y reinicios en nueve idiomas ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737), [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742), [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). La volatilidad de opciones entre mercados usa solo marcas temporales conocidas en cada barra; la caída máxima incluye el capital inicial. Corregimos las rutas de criptoactivos y metales preciosos, los duplicados de Hong Kong, la recuperación de caché, los importes en notación científica y la validación de valores ausentes. mootdx sale de la cadena predeterminada de acciones A. Los trece PR están en [CHANGELOG](CHANGELOG.md).- **2026-10-08** 🔐 **Informes PDF protegidos y lecturas del bróker corregidas**: Los PDF de correo programado admiten protección AES-256 opcional en Web, CLI y confirmaciones del agente; la contraseña permanece en la configuración privada del canal ([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709)). KIS consulta las tres rutas, renueva una sola vez un token explícitamente caducado y rechaza lecturas incompletas ([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726)). Las fórmulas conservan la expresión tras las etiquetas descriptivas y mantienen la verificación de evidencias ([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728)).-- **2026-10-07** 🛠️ **Continuidad de investigación y métricas de riesgo corregidas**: El estado de ejecución se separa del mensaje del sistema para preservar su prefijo estable ([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708)). Se corrigen las fechas entre mercados, los retornos alrededor de precios ausentes y el Sortino de opciones con toda la muestra ([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710), [#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717), [#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727)). Los cargadores comparten un contrato OHLCV; también se corrigen valoración crediticia, exposiciones, validación temporal y diagnóstico de auditoría.<details><summary>Noticias anteriores</summary>+- **2026-10-07** 🛠️ **Continuidad de investigación y métricas de riesgo corregidas**: El estado de ejecución se separa del mensaje del sistema para preservar su prefijo estable ([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708)). Se corrigen las fechas entre mercados, los retornos alrededor de precios ausentes y el Sortino de opciones con toda la muestra ([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710), [#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717), [#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727)). Los cargadores comparten un contrato OHLCV; también se corrigen valoración crediticia, exposiciones, validación temporal y diagnóstico de auditoría.+- **2026-10-06** 🛠️ **Control de operaciones reales y corrección de informes**: Detener el agente de operaciones reales cancela el análisis en curso y espera a que termine el planificador, incluso al cancelar durante el inicio o cerrar la API; se corrigen también las unidades de tiempo del estado ([#1704](https://github.com/HKUDS/Vibe-Trading/pull/1704)). La cancelación y el cierre de posiciones de emergencia omiten registros inválidos y continúan con los restantes ([#1703](https://github.com/HKUDS/Vibe-Trading/pull/1703)); cada bróker conserva su propia programación y las escrituras manejan concurrencia y escrituras parciales. Las sesiones reducidas de acciones estadounidenses respetan el cierre anticipado ([#1706](https://github.com/HKUDS/Vibe-Trading/pull/1706)). Las correcciones conservan las cifras verificadas y no presentan las cifras omitidas de los comentarios limitados como aprobadas ([#1702](https://github.com/HKUDS/Vibe-Trading/pull/1702)).- **2026-10-05** 🛠️ **Consultas de investigación y cálculos corregidos**: El chat admite consultas más largas e indica en el idioma actual cómo acortarlas cuando superan el límite ([#1701](https://github.com/HKUDS/Vibe-Trading/pull/1701)). Sortino usa la desviación a la baja de todos los períodos; la validación por grupos excluye etiquetas solapadas. También mejoran los pesos de covarianza, el RSI con media inicial de Wilder y la eliminación de memorias por nombre de archivo. Los alias de llamada incorrectos reciben referencias exactas para corregirlos, conservando la validación numérica ([#1638](https://github.com/HKUDS/Vibe-Trading/pull/1638)).diff --git a/README_id.md b/README_id.mdindex 7e4811b07..91e4cf6b1 100644--- a/README_id.md+++ b/README_id.md@@ -53,15 +53,18 @@> ⚠️ **Peringatan keamanan:** Akun X `VibeTrading_HKU`, proyek Virtuals `101845`, dan kontrak token `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` bukan aset resmi Vibe-Trading. Kami tidak pernah meluncurkan atau mendukung token maupun memecoin apa pun. Jangan membeli, menghubungkan wallet, atau menandatangani apa pun. [Detail](SECURITY.md#official-channels--impersonation).+- **2026-10-10** 🛠️ **Pengaturan Slack/Discord dan riset yang dapat direproduksi**: Formulir terjemahan memverifikasi kredensial bot tanpa menyimpan perubahan ([#1764](https://github.com/HKUDS/Vibe-Trading/pull/1764), [#1777](https://github.com/HKUDS/Vibe-Trading/pull/1777)). Riset portofolio dapat memakai ulang snapshot yang tidak berubah; Web mengekspor JSON tanpa data sensitif ([#1769](https://github.com/HKUDS/Vibe-Trading/pull/1769)). Indikator mencatat batas tanggal dan sidik data masukan. Catatan sesi rusak dipulihkan tanpa menulis ulang berkas asli. Pencarian memori, penyamaran kredensial, dan impor transaksi juga diperbaiki. Lihat [CHANGELOG](CHANGELOG.md).+- **2026-10-09** 🛠️ **Pengaturan kanal dan perbaikan backtest**: Pembaruan tanpa menyambungkan ulang mempertahankan kredensial URL dan alamat server WeChat hasil autentikasi; web menjelaskan hasil penyimpanan dan mulai ulang dalam sembilan bahasa ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737), [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742), [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). Volatilitas opsi lintas pasar hanya memakai waktu yang sudah diketahui pada setiap bar; drawdown mencakup modal awal. Perbaikan meliputi rute data kripto/logam mulia, duplikat saham Hong Kong, pemulihan cache, nominal notasi ilmiah, dan validasi nilai ekuitas yang hilang. mootdx dikeluarkan dari rantai saham A bawaan. Ketiga belas PR tercantum dalam [CHANGELOG](CHANGELOG.md).- **2026-10-08** 🔐 **Laporan PDF terlindungi dan pembacaan broker diperbaiki**: PDF Email terjadwal mendukung perlindungan AES-256 opsional melalui Web, CLI, dan konfirmasi agen; kata sandi hanya disimpan dalam konfigurasi privat kanal ([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709)). KIS menanyakan ketiga jalur perdagangan, memperbarui token yang secara eksplisit kedaluwarsa satu kali, dan menolak pembacaan yang tidak lengkap ([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726)). Rumus turunan tetap utuh setelah label deskriptif dengan pemeriksaan bukti tetap berlaku ([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728)).-- **2026-10-07** 🛠️ **Kesinambungan riset dan koreksi metrik risiko**: Status eksekusi dipindahkan dari prompt sistem agar prefiksnya tetap stabil ([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708)). Tanggal lintas pasar, imbal hasil di sekitar harga yang hilang, dan Sortino opsi berdasarkan seluruh sampel diperbaiki ([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710), [#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717), [#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727)). Pengujian loader memakai satu kontrak OHLCV, disertai koreksi valuasi kredit, eksposur, validasi berjalan, dan diagnosis audit.<details><summary>Berita sebelumnya</summary>+- **2026-10-07** 🛠️ **Kesinambungan riset dan koreksi metrik risiko**: Status eksekusi dipindahkan dari prompt sistem agar prefiksnya tetap stabil ([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708)). Tanggal lintas pasar, imbal hasil di sekitar harga yang hilang, dan Sortino opsi berdasarkan seluruh sampel diperbaiki ([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710), [#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717), [#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727)). Pengujian loader memakai satu kontrak OHLCV, disertai koreksi valuasi kredit, eksposur, validasi berjalan, dan diagnosis audit.+- **2026-10-06** 🛠️ **Kontrol trading langsung dan koreksi laporan**: Menghentikan runner trading langsung membatalkan analisis aktif dan menunggu penjadwal selesai, termasuk pembatalan saat mulai dan penutupan API; satuan waktu pada status juga diperbaiki ([#1704](https://github.com/HKUDS/Vibe-Trading/pull/1704)). Pembatalan order dan penutupan posisi darurat melewati catatan tidak valid lalu melanjutkan catatan lainnya ([#1703](https://github.com/HKUDS/Vibe-Trading/pull/1703)); jadwal setiap broker disimpan terpisah dengan penanganan penulisan bersamaan dan parsial. Sesi saham AS yang dipersingkat mengikuti waktu tutup lebih awal ([#1706](https://github.com/HKUDS/Vibe-Trading/pull/1706)). Koreksi laporan mempertahankan angka yang lolos verifikasi, dan umpan balik terbatas tidak menyiratkan bahwa angka yang tidak tercantum sudah lolos ([#1702](https://github.com/HKUDS/Vibe-Trading/pull/1702)).- **2026-10-05** 🛠️ **Input riset dan perbaikan perhitungan**: Chat menerima input riset lebih panjang dan memberi petunjuk dalam bahasa aktif untuk mempersingkat teks yang melampaui batas ([#1701](https://github.com/HKUDS/Vibe-Trading/pull/1701)). Sortino memakai deviasi penurunan dari seluruh periode; validasi grup membuang label yang tumpang tindih. Bobot kovarians, RSI dengan rata-rata awal Wilder, dan penghapusan memori lewat nama file juga diperbaiki. Alias panggilan yang keliru kini mendapat referensi sumber yang tepat untuk koreksi, dengan validasi angka tetap berlaku ([#1638](https://github.com/HKUDS/Vibe-Trading/pull/1638)).diff --git a/README_ja.md b/README_ja.mdindex 0a7502222..f612652fb 100644--- a/README_ja.md+++ b/README_ja.md@@ -52,15 +52,18 @@> ⚠️ **セキュリティ警告:** Xアカウント `VibeTrading_HKU`、Virtualsプロジェクト `101845`、およびトークンコントラクト `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` は、いずれもVibe-Trading公式のものではありません。Vibe-Tradingはこれまで、いかなるトークンやミームコインも発行・公認していません。購入、ウォレットの接続、署名は行わないでください。[詳細](SECURITY.md#official-channels--impersonation)+- **2026-10-10** 🛠️ **Slack/Discord 設定と再現可能な調査**:翻訳済みフォームでボット認証情報を検証できます。テストは変更を保存しません([#1764](https://github.com/HKUDS/Vibe-Trading/pull/1764)、[#1777](https://github.com/HKUDS/Vibe-Trading/pull/1777))。ポートフォリオ調査は不変のスナップショットを再利用でき、Web から認証情報や口座番号を除いた JSON を出力できます([#1769](https://github.com/HKUDS/Vibe-Trading/pull/1769))。指標は取得日と入力の指紋を報告し、破損したセッション記録は元のファイルを書き換えずに復旧します。メモリ検索、認証情報の秘匿、取引履歴の識別も修正しました。[CHANGELOG](CHANGELOG.md) を参照。+- **2026-10-09** 🛠️ **チャンネル設定とバックテストの修正**:再接続なしの設定更新で URL 内の認証情報と WeChat 認証後のサーバーアドレスを保持し、保存・再起動の結果を Web で9言語表示します([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737)、[#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742)、[#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744))。複数市場のオプション価格に使うボラティリティは各時点までのタイムスタンプだけで計算し、ドローダウンには初期資金を反映。暗号資産・貴金属のデータ取得経路、香港株の重複判定、キャッシュ復旧、科学表記の金額、欠損資産額の検証を修正しました。mootdx は標準の A 株取得経路から外れます。全13件は [CHANGELOG](CHANGELOG.md)。- **2026-10-08** 🔐 **PDF レポートのパスワード保護とブローカー読み取り修正**:定期メール PDF に AES-256 保護を選択でき、Web、CLI、エージェント確認画面に反映されます。パスワードは非公開のチャネル設定だけに保存します([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709))。KIS は三つの取引経路を照会し、明示的なトークン失効を一度だけ再取得、不完全な読み取りはエラーにします([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726))。説明ラベルの後の導出式を保持し、証拠検証を維持します([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728))。-- **2026-10-07** 🛠️ **リサーチの継続性とリスク指標の修正**:実行状態をシステムプロンプトから分離し、安定したプレフィックスを保ちます([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708))。市場間の日付整列、欠損価格前後のリターン、全標本によるオプションのソルティノ比率を修正しました([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710)、[#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717)、[#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727))。データ取得テストは共通の OHLCV 契約を使い、信用評価、スタイル・エクスポージャー、時系列検証、監査診断も改善しました。<details><summary>過去のニュース</summary>+- **2026-10-07** 🛠️ **リサーチの継続性とリスク指標の修正**:実行状態をシステムプロンプトから分離し、安定したプレフィックスを保ちます([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708))。市場間の日付整列、欠損価格前後のリターン、全標本によるオプションのソルティノ比率を修正しました([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710)、[#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717)、[#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727))。データ取得テストは共通の OHLCV 契約を使い、信用評価、スタイル・エクスポージャー、時系列検証、監査診断も改善しました。+- **2026-10-06** 🛠️ **ライブ運用制御とレポート修正**:ライブランナーの停止は実行中の分析をキャンセルしてスケジューラーの終了を待ち、起動中のキャンセルと API 終了にも対応します。状態の時刻単位も修正しました([#1704](https://github.com/HKUDS/Vibe-Trading/pull/1704))。緊急キャンセル・決済処理は不正なレコードを除外して残りの注文・保有を処理します([#1703](https://github.com/HKUDS/Vibe-Trading/pull/1703))。ブローカーごとにスケジュールを保存し、並行書き込みと部分書き込みに対応。米国株の短縮取引日は早い閉場時刻を守ります([#1706](https://github.com/HKUDS/Vibe-Trading/pull/1706))。レポート修正は検証済みの数値を保持し、省略された指摘を検証済みと誤認させません([#1702](https://github.com/HKUDS/Vibe-Trading/pull/1702))。- **2026-10-05** 🛠️ **調査入力と計算の修正**:チャットで長い調査入力に対応し、上限を超えた場合は現在の言語で短縮を案内します([#1701](https://github.com/HKUDS/Vibe-Trading/pull/1701))。Sortino は全期間の下方偏差を使用し、グループ検証は重複ラベルを除外します。共分散ウェイト、Wilder 初期平均による RSI、ファイル名によるメモリ削除も改善しました。 呼び出しの別名を誤って引用した場合、修正用に実際のフィールド参照を提示します([#1638](https://github.com/HKUDS/Vibe-Trading/pull/1638))。数値の検証規則は維持されます。diff --git a/README_ko.md b/README_ko.mdindex 8b1240df6..acfcf1297 100644--- a/README_ko.md+++ b/README_ko.md@@ -52,15 +52,18 @@> ⚠️ **보안 경고:** X 계정 `VibeTrading_HKU`, Virtuals 프로젝트 `101845`, 토큰 컨트랙트 `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4`는 모두 Vibe-Trading 공식과 무관합니다. Vibe-Trading은 어떠한 토큰이나 밈코인도 발행하거나 공식적으로 지지한 적이 없습니다. 해당 토큰을 구매하거나 지갑을 연결하거나 어떠한 서명도 하지 마세요. [자세히 보기](SECURITY.md#official-channels--impersonation).+- **2026-10-10** 🛠️ **Slack/Discord 설정과 재현 가능한 연구**: 번역된 양식에서 봇 인증 정보를 검증하며 테스트는 변경 사항을 저장하지 않습니다([#1764](https://github.com/HKUDS/Vibe-Trading/pull/1764), [#1777](https://github.com/HKUDS/Vibe-Trading/pull/1777)). 포트폴리오 연구는 불변 스냅샷을 재사용하고 Web에서 인증 정보와 계좌 번호를 제거한 JSON을 내보냅니다([#1769](https://github.com/HKUDS/Vibe-Trading/pull/1769)). 지표는 조회 날짜와 입력 지문을 보고하며 손상된 세션 기록은 원본을 다시 쓰지 않고 복구합니다. 메모리 검색, 인증 정보 마스킹, 거래 내역 식별도 수정했습니다. [CHANGELOG](CHANGELOG.md)를 참조하세요.+- **2026-10-09** 🛠️ **채널 설정 및 백테스트 수정**: 재연결 없는 설정 업데이트에서 URL 인증 정보와 WeChat 인증 후 서버 주소를 보존하며, 저장·재시작 결과를 웹에서 9개 언어로 표시합니다 ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737), [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742), [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). 여러 시장의 옵션 변동성은 각 시점까지 알려진 타임스탬프만 사용하고, 낙폭은 초기 자금을 반영합니다. 암호화폐·귀금속 데이터 경로, 홍콩 주식 중복 판별, 캐시 복구, 과학적 표기 금액 및 누락된 자산 값 검증을 수정했습니다. 기본 A주 경로에서 mootdx를 제외했습니다. 13개 PR은 [CHANGELOG](CHANGELOG.md)를 참조하세요.- **2026-10-08** 🔐 **PDF 보고서 비밀번호 보호와 증권사 조회 수정**: 예약 이메일 PDF에 AES-256 보호를 선택할 수 있으며 Web, CLI 및 에이전트 확인에 반영됩니다. 비밀번호는 비공개 채널 설정에만 저장합니다([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709)). KIS는 세 거래 경로를 조회하고 명시적으로 만료된 토큰을 한 번만 갱신하며 불완전한 조회는 오류로 처리합니다([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726)). 설명 뒤의 전체 파생 수식을 보존하고 증거 검증을 유지합니다([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728)).-- **2026-10-07** 🛠️ **리서치 연속성과 위험 지표 수정**: 실행 상태를 시스템 프롬프트 밖으로 옮겨 안정적인 접두부를 유지합니다([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708)). 시장 간 날짜 정렬, 누락 가격 주변의 수익률, 전체 표본을 사용하는 옵션 Sortino 계산을 수정했습니다([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710), [#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717), [#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727)). 데이터 로더 테스트는 공통 OHLCV 계약을 사용하며 신용 평가, 스타일 노출, 순차 검증 및 감사 진단도 개선했습니다.<details><summary>이전 뉴스</summary>+- **2026-10-07** 🛠️ **리서치 연속성과 위험 지표 수정**: 실행 상태를 시스템 프롬프트 밖으로 옮겨 안정적인 접두부를 유지합니다([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708)). 시장 간 날짜 정렬, 누락 가격 주변의 수익률, 전체 표본을 사용하는 옵션 Sortino 계산을 수정했습니다([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710), [#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717), [#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727)). 데이터 로더 테스트는 공통 OHLCV 계약을 사용하며 신용 평가, 스타일 노출, 순차 검증 및 감사 진단도 개선했습니다.+- **2026-10-06** 🛠️ **실거래 제어와 보고서 수정**: 실거래 러너 중지는 현재 분석을 취소하고 스케줄러 종료를 기다리며 시작 중 취소와 API 종료도 처리합니다. 상태 시간의 단위도 수정했습니다([#1704](https://github.com/HKUDS/Vibe-Trading/pull/1704)). 긴급 취소·청산은 잘못된 레코드를 건너뛰고 나머지 주문과 포지션을 계속 처리합니다([#1703](https://github.com/HKUDS/Vibe-Trading/pull/1703)). 증권사별 일정을 따로 저장하고 동시 쓰기와 부분 쓰기를 처리합니다. 미국 주식 단축 거래일의 조기 폐장 시간을 반영합니다([#1706](https://github.com/HKUDS/Vibe-Trading/pull/1706)). 보고서 수정은 검증된 수치를 유지하며 생략된 오류가 검증을 통과한 것처럼 안내하지 않습니다([#1702](https://github.com/HKUDS/Vibe-Trading/pull/1702)).- **2026-10-05** 🛠️ **리서치 입력과 계산 수정**: 더 긴 리서치 입력을 지원하며 한도를 넘으면 현재 언어로 줄이도록 안내합니다([#1701](https://github.com/HKUDS/Vibe-Trading/pull/1701)). Sortino는 전체 기간의 하방 편차를 사용하고 그룹 검증은 겹치는 레이블을 제외합니다. 공분산 가중치, Wilder 초기 평균을 사용하는 RSI, 파일명으로 메모리 삭제도 개선했습니다. 잘못된 호출 별칭을 인용하면 수정할 수 있도록 실제 필드 참조를 안내하며 수치 검증 규칙은 유지합니다([#1638](https://github.com/HKUDS/Vibe-Trading/pull/1638)).diff --git a/README_zh.md b/README_zh.mdindex 70af20f37..138721ce1 100644--- a/README_zh.md+++ b/README_zh.md@@ -52,15 +52,18 @@> ⚠️ **安全警告:** X 账号 `VibeTrading_HKU`、Virtuals 项目 `101845` 及代币合约 `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` 均非 Vibe-Trading 官方。我们从未发行或背书任何代币或 meme 币。请勿购买、连接钱包或签名。[详细说明](SECURITY.md#official-channels--impersonation)。+- **2026-10-10** 🛠️ **Slack/Discord 配置与可复现研究**:本地化配置表单可测试机器人凭证,测试不会保存改动([#1764](https://github.com/HKUDS/Vibe-Trading/pull/1764)、[#1777](https://github.com/HKUDS/Vibe-Trading/pull/1777))。组合研究可复用不可变快照,Web 可导出脱敏 JSON([#1769](https://github.com/HKUDS/Vibe-Trading/pull/1769))。技术指标报告日期边界和输入指纹;损坏的会话记录可恢复且不重写原文件。另修复记忆召回、凭证脱敏和交易流水格式识别。详见 [CHANGELOG](CHANGELOG.md)。+- **2026-10-09** 🛠️ **渠道设置与回测修正**:原地更新渠道设置时保留 URL 内嵌凭证和微信认证后的服务地址,Web 以九种语言说明保存与重启结果([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737)、[#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742)、[#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744))。跨市场期权波动率仅使用截至当前时点的时间戳,回撤纳入初始资金。修正加密货币/贵金属数据源路由、港股重复识别、缓存恢复、科学计数金额解析及缺失净值验证;mootdx 移出默认 A 股链。全部十三项 PR 见 [CHANGELOG](CHANGELOG.md)。- **2026-10-08** 🔐 **PDF 报告密码保护与券商读取修复**:定时邮件 PDF 可选 AES-256 密码保护,覆盖 Web、CLI 模板和 Agent 确认入口;密码只保存在渠道私有配置中([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709))。KIS 读取三个交易场所的订单,明确过期的 token 只刷新一次,不完整的读取返回错误([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726))。派生公式保留说明标签之后的完整算式,证据核验规则保持不变([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728))。-- **2026-10-07** 🛠️ **研究连续性与风险指标修正**:运行状态移出系统提示词,保留稳定前缀以利于缓存([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708))。跨市场日期正确对齐,缺失价格不再拼接跨期收益,期权 Sortino 按全样本计算下行偏差([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710)、[#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717)、[#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727))。数据源测试共用 OHLCV 契约,并修正信用估值、风格敞口、滚动验证和审计诊断。<details><summary>更早的新闻</summary>+- **2026-10-07** 🛠️ **研究连续性与风险指标修正**:运行状态移出系统提示词,保留稳定前缀以利于缓存([#1708](https://github.com/HKUDS/Vibe-Trading/pull/1708))。跨市场日期正确对齐,缺失价格不再拼接跨期收益,期权 Sortino 按全样本计算下行偏差([#1710](https://github.com/HKUDS/Vibe-Trading/pull/1710)、[#1717](https://github.com/HKUDS/Vibe-Trading/pull/1717)、[#1727](https://github.com/HKUDS/Vibe-Trading/pull/1727))。数据源测试共用 OHLCV 契约,并修正信用估值、风格敞口、滚动验证和审计诊断。+- **2026-10-06** 🛠️ **实盘控制与报告纠错修复**:停止实盘运行会取消当前分析并等待调度器完成清理,覆盖启动期间取消及 API 关闭,运行状态时间单位也已修正([#1704](https://github.com/HKUDS/Vibe-Trading/pull/1704))。紧急撤单/平仓扫描跳过异常记录,继续处理其余订单和持仓([#1703](https://github.com/HKUDS/Vibe-Trading/pull/1703));不同券商的调度独立保存,持久化正确处理并发写入与短写入。美股半日交易遵循提前收市时间([#1706](https://github.com/HKUDS/Vibe-Trading/pull/1706))。报告纠错保留已核验通过的数字,反馈截断也不会暗示未列出的数字已通过([#1702](https://github.com/HKUDS/Vibe-Trading/pull/1702))。- **2026-10-05** 🛠️ **研究输入与计算修复**:聊天支持更长的研究输入,超限时以当前语言提示缩短([#1701](https://github.com/HKUDS/Vibe-Trading/pull/1701))。回测 Sortino 使用全样本下行偏差;分组验证剔除重叠标签,协方差权重保持有限,影子账户 RSI 使用 Wilder 初始均值,记忆支持按文件名删除。 报告误用调用别名时,纠正提示提供真实字段引用([#1638](https://github.com/HKUDS/Vibe-Trading/pull/1638)),数值校验保持不变。diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex 0aac8b47d..dbf04227c 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -4203,17 +4203,22 @@ def _print_portfolio_snapshot(snapshot: dict[str, Any]) -> None:console.print(f"[yellow]![/yellow] {rich_escape(str(warning))}")-def cmd_portfolio_show(service: Any | None = None) -> int:- """Print the latest stored portfolio snapshot.+def cmd_portfolio_show(service: Any | None = None, snapshot_id: str | None = None) -> int:+ """Print the latest snapshot or one exact stored observation.Args:service: Optional ``PortfolioService`` (tests inject a stub).+ snapshot_id: Optional immutable snapshot id; never falls back to latest.Returns:The process exit code."""- snapshot = _portfolio_service(service).latest()+ instance = _portfolio_service(service)+ snapshot = instance.latest() if snapshot_id is None else instance.snapshot_by_id(snapshot_id)if snapshot is None:+ if snapshot_id is not None:+ console.print("[red]The requested portfolio snapshot is unavailable.[/red]")+ return EXIT_RUN_FAILEDconsole.print("[dim]No portfolio snapshot yet. Select sources on the Web UI Portfolio page ""(or `vibe-trading portfolio sources`), then run `vibe-trading portfolio refresh`.[/dim]"@@ -4296,7 +4301,7 @@ def _dispatch_portfolio(args: argparse.Namespace) -> int:"""sub = getattr(args, "portfolio_command", None) or "show"if sub == "show":- return cmd_portfolio_show()+ return cmd_portfolio_show(snapshot_id=getattr(args, "snapshot_id", None))if sub == "refresh":return cmd_portfolio_refresh()if sub == "sources":@@ -5522,7 +5527,8 @@ def _build_parser() -> argparse.ArgumentParser:help="Read-only multi-broker portfolio (the Web UI /portfolio page, in the terminal)",)portfolio_subparsers = portfolio_parser.add_subparsers(dest="portfolio_command")- portfolio_subparsers.add_parser("show", help="Print the latest stored snapshot")+ portfolio_show_parser = portfolio_subparsers.add_parser("show", help="Print a stored snapshot")+ portfolio_show_parser.add_argument("--snapshot-id", help="Read this exact immutable snapshot")portfolio_subparsers.add_parser("refresh", help="Read every enabled source now, store a new snapshot, and print it")diff --git a/agent/src/api/portfolio_routes.py b/agent/src/api/portfolio_routes.pyindex 21ad5fcd6..74441e258 100644--- a/agent/src/api/portfolio_routes.py+++ b/agent/src/api/portfolio_routes.py@@ -253,10 +253,10 @@ def register_portfolio_routes(app: FastAPI) -> None:return {"status": "ok", "history": service().history(limit)}@app.get("/api/portfolio/analysis-context", dependencies=[Depends(require_auth)])- def portfolio_analysis_context():- context = service().analysis_context()+ def portfolio_analysis_context(snapshot_id: str | None = Query(None, min_length=1)):+ context = service().analysis_context(snapshot_id=snapshot_id)if context is None:- raise HTTPException(status_code=404, detail="no portfolio snapshot exists")+ raise HTTPException(status_code=404, detail="portfolio snapshot unavailable")return {"status": "ok", "context": context}@app.get("/api/portfolio/export.csv", dependencies=[Depends(require_auth)])diff --git a/agent/src/channels/slack_probe.py b/agent/src/channels/slack_probe.pyindex 427e7d903..0b78c5b01 100644--- a/agent/src/channels/slack_probe.py+++ b/agent/src/channels/slack_probe.py@@ -17,7 +17,8 @@ JSON body, so both legs pass the shared probe's optional ``headers`` withan empty payload. Note that Slack answers HTTP 200 with ``{"ok": false,"error": "invalid_auth"}`` for bad tokens; ``token_key="ok"`` routes thatthrough the shared "200 but no token" branch, which already classifies it-as ``invalid_credentials``.+as ``invalid_credentials``. Requiring the documented ``bot_id`` field also+refuses a user token, whose successful ``auth.test`` response has no bot identity.Leg 1 (``auth.test``) validates the bot token. Leg 2(``apps.connections.open``) validates the app token AND that Socket Mode@@ -72,6 +73,13 @@ async def test_connection("""secrets = (config.bot_token, config.app_token)+ if config.mode != "socket":+ return {+ "ok": False,+ "code": "invalid_credentials",+ "detail": "Slack supports socket mode only",+ "sdk_available": sdk_available,+ }if not config.bot_token:return {"ok": False,@@ -79,7 +87,7 @@ async def test_connection("detail": "missing bot token","sdk_available": sdk_available,}- if config.mode == "socket" and not config.app_token:+ if not config.app_token:return {"ok": False,"code": "invalid_credentials",@@ -92,6 +100,7 @@ async def test_connection(payload={},headers={"Authorization": f"Bearer {config.bot_token}"},token_key="ok",+ required_fields=("bot_id",),secrets=secrets,sdk_available=sdk_available,)diff --git a/agent/src/channels/token_probe.py b/agent/src/channels/token_probe.pyindex 0d6f6fb26..4f3d5cfed 100644--- a/agent/src/channels/token_probe.py+++ b/agent/src/channels/token_probe.py@@ -74,6 +74,7 @@ async def probe_token_endpoint(token_key: str,secrets: Sequence[str],sdk_available: bool,+ required_fields: Sequence[str] = (),headers: dict[str, str] | None = None,method: str = "POST",transport: httpx.AsyncHTTPTransport | None = None,@@ -92,6 +93,8 @@ async def probe_token_endpoint(secrets: Credential values to scrub from every ``detail``.sdk_available: Whether the channel's optional SDK imported; echoedback so the caller's envelope carries it unchanged.+ required_fields: Additional truthy response fields required for+ success, such as Slack's bot identity when checking a bot token.headers: Optional request headers for endpoints that authenticateoutside the JSON body (e.g. Slack's ``Authorization: Bearer``).method: HTTP method for the request. ``"GET"`` sends no JSON body,@@ -133,7 +136,7 @@ async def probe_token_endpoint(# middlebox) must classify, never raise: .get on a non-dict would# surface as a bare 500 on the unguarded /test route.token = body.get(token_key) if isinstance(body, dict) else None- if not token:+ if not token or any(not body.get(key) for key in required_fields):return {"ok": False,"code": "invalid_credentials",@@ -142,7 +145,9 @@ async def probe_token_endpoint(}return {"ok": True, "code": "ok", "sdk_available": sdk_available}- if 400 <= resp.status_code < 500:+ # A timed-out or rate-limited request says nothing about the credentials.+ # Keep enable verification fail-closed while reporting a retryable failure.+ if 400 <= resp.status_code < 500 and resp.status_code not in (408, 429):return {"ok": False,"code": "invalid_credentials",diff --git a/agent/src/memory/persistent.py b/agent/src/memory/persistent.pyindex 1af6c7705..9b6c30da0 100644--- a/agent/src/memory/persistent.py+++ b/agent/src/memory/persistent.py@@ -370,11 +370,8 @@ class PersistentMemory:try:from src.memory.search_index import get_shared_indexindex = get_shared_index()- # The on-disk memory files are canonical. The FTS database can- # briefly retain rows for files removed outside this process,- # so fetch a small candidate buffer before discarding rows that- # no longer map to a current entry.- matches = index.search(query, max_results=max_results * 4)+ candidate_limit = max_results+ matches = index.search(query, max_results=candidate_limit)# Auto-rebuild on first empty search if entries exist on diskall_entries = None@@ -387,7 +384,7 @@ class PersistentMemory:]index.rebuild_all(entries_data)index._auto_rebuilt = True- matches = index.search(query, max_results=max_results)+ matches = index.search(query, max_results=candidate_limit)if matches:# Map FTS results back to full entries@@ -397,6 +394,22 @@ class PersistentMemory:fts_pairs = [(m, entry_map[m.entry_id]) for m in matches if m.entry_id in entry_map]+ # Files are canonical. Keep the FTS ordering but expand the+ # candidate window until enough current entries survive,+ # or the index is exhausted; a fixed buffer can still be+ # filled entirely by externally removed memories.+ while (+ candidate_limit > 0+ and len(matches) == candidate_limit+ and len(fts_pairs) < max_results+ ):+ candidate_limit *= 2+ matches = index.search(query, max_results=candidate_limit)+ fts_pairs = [+ (m, entry_map[m.entry_id])+ for m in matches+ if m.entry_id in entry_map+ ]if fts_pairs:if _is_decay_enabled():# FTS5's rank is more negative for stronger matches;diff --git a/agent/src/session/store.py b/agent/src/session/store.pyindex d29a160de..12f5f6266 100644--- a/agent/src/session/store.py+++ b/agent/src/session/store.py@@ -179,20 +179,32 @@ class SessionStore:if not path.exists():return []messages: List[Message] = []- for line in path.read_text(encoding="utf-8").strip().splitlines():- if line.strip():+ # Decode physical JSONL records separately: one unreadable byte must+ # cost one record, never the intact messages on either side of it.+ with path.open("rb") as log:+ for line_number, raw_line in enumerate(log, start=1):+ if not raw_line.strip():+ continuetry:+ line = raw_line.decode("utf-8")payload = json.loads(line)if not isinstance(payload, dict):raise TypeError(f"message line must be a JSON object, got {type(payload).__name__}")messages.append(Message.from_dict(payload))- except (json.JSONDecodeError, TypeError, ValueError, KeyError):+ except (+ json.JSONDecodeError,+ UnicodeDecodeError,+ TypeError,+ ValueError,+ KeyError,+ ) as exc:logger.warning(- "Skipping corrupted message line in session %s: %s",+ "Skipping corrupted message record %d in session %s (%s)",+ line_number,session_id,- line[:200],+ type(exc).__name__,)return messages[-limit:]@@ -345,5 +357,10 @@ class SessionStore:return Nonetry:return json.loads(path.read_text(encoding="utf-8"))- except (json.JSONDecodeError, OSError):+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:+ logger.warning(+ "Skipping corrupt JSON file %s (%s)", path.name, type(exc).__name__+ )+ return None+ except OSError:return Nonediff --git a/agent/tests/memory/test_tier2_integration.py b/agent/tests/memory/test_tier2_integration.pyindex 64b61b12a..e9649de56 100644--- a/agent/tests/memory/test_tier2_integration.py+++ b/agent/tests/memory/test_tier2_integration.py@@ -223,6 +223,34 @@ class TestFtsAddThenSearchFinds:assert [entry.title for entry in results] == ["first recall", "second recall"]+ @pytest.mark.parametrize("requested", [2, 3])+ def test_real_fts_finds_current_rows_beyond_a_fixed_buffer(+ self, tmp_path, monkeypatch, fts_db, requested+ ):+ """Expand past stale rows and stop when the real SQLite index ends."""+ from src.memory.search_index import get_shared_index++ monkeypatch.setenv("VT_MEMORY_FTS_INDEX", "false")+ reset_env_config()+ mem = PersistentMemory(tmp_path / "memories")+ mem.add("first recall", "evidence retrieval", "project")+ mem.add("second recall", "evidence retrieval", "project")+ entries = {entry.title: entry for entry in mem.list_entries()}+ first, second = entries["first recall"], entries["second recall"]++ index = get_shared_index()+ for entry_id in [first.id, *(f"stale{i}" for i in range(12)), second.id]:+ index.index_entry(entry_id, "recall", "", "", "evidence retrieval")+ ranked = index.search("evidence retrieval", max_results=100)+ assert [match.entry_id for match in ranked] == [+ first.id, *(f"stale{i}" for i in range(12)), second.id+ ]++ monkeypatch.setenv("VT_MEMORY_FTS_INDEX", "true")+ reset_env_config()+ results = mem.find_relevant("evidence retrieval", max_results=requested)+ assert [entry.id for entry in results] == [first.id, second.id]+# ---------------------------------------------------------------------------# 4a. Fallback token-scan must find the same short-token content the FTS5diff --git a/agent/tests/test_channels_config_api.py b/agent/tests/test_channels_config_api.pyindex 6b91bc9e8..fec0d3402 100644--- a/agent/tests/test_channels_config_api.py+++ b/agent/tests/test_channels_config_api.py@@ -1310,7 +1310,7 @@ def test_post_slack_test_runs_two_leg_probe_not_unsupported(def handler(request: httpx.Request) -> httpx.Response:seen.append(str(request.url))if seen[-1].endswith("/api/auth.test"):- return httpx.Response(200, json={"ok": True})+ return httpx.Response(200, json={"ok": True, "bot_id": "B12345"})return httpx.Response(200, json={"ok": True, "url": "wss://wss-primary.slack.com/link/"})diff --git a/agent/tests/test_cli_portfolio.py b/agent/tests/test_cli_portfolio.pyindex b561bbc2d..17ed4bcd9 100644--- a/agent/tests/test_cli_portfolio.py+++ b/agent/tests/test_cli_portfolio.py@@ -30,6 +30,9 @@ class _Service:"""Return the scripted snapshot (``None`` when nothing is stored)."""return self._snapshot+ def snapshot_by_id(self, snapshot_id):+ return self._snapshot if self._snapshot and self._snapshot["snapshot_id"] == snapshot_id else None+def refresh(self):"""Return the scripted snapshot or raise the scripted error."""self.refresh_calls += 1@@ -98,6 +101,14 @@ def test_show_without_snapshot_points_at_refresh(capsys) -> None:assert "portfolio refresh" in out+def test_show_pinned_snapshot_and_missing_id_never_falls_back(capsys) -> None:+ service = _Service(snapshot=_SNAPSHOT)+ assert _legacy.cmd_portfolio_show(service, snapshot_id="abc") == _legacy.EXIT_SUCCESS+ assert "AAPL" in capsys.readouterr().out+ assert _legacy.cmd_portfolio_show(service, snapshot_id="gone") == _legacy.EXIT_RUN_FAILED+ assert "unavailable" in capsys.readouterr().out++def test_refresh_prints_and_exits_nonzero_when_incomplete(capsys) -> None:service = _Service(snapshot=_SNAPSHOT)rc = _legacy.cmd_portfolio_refresh(service=service)@@ -157,19 +168,22 @@ def test_sources_without_connections_explains_where_to_create_one(capsys) -> Nondef test_dispatch_defaults_to_show_and_routes_subcommands(monkeypatch) -> None:calls: list[str] = []- monkeypatch.setattr(_legacy, "cmd_portfolio_show", lambda: calls.append("show") or 0)+ monkeypatch.setattr(_legacy, "cmd_portfolio_show", lambda **kwargs: calls.append(kwargs.get("snapshot_id") or "show") or 0)monkeypatch.setattr(_legacy, "cmd_portfolio_refresh", lambda: calls.append("refresh") or 0)monkeypatch.setattr(_legacy, "cmd_portfolio_sources", lambda: calls.append("sources") or 0)assert _legacy._dispatch_portfolio(Namespace(portfolio_command=None)) == 0assert _legacy._dispatch_portfolio(Namespace(portfolio_command="refresh")) == 0assert _legacy._dispatch_portfolio(Namespace(portfolio_command="sources")) == 0assert calls == ["show", "refresh", "sources"]+ assert _legacy._dispatch_portfolio(Namespace(portfolio_command="show", snapshot_id="abc")) == 0+ assert calls[-1] == "abc"assert _legacy._dispatch_portfolio(Namespace(portfolio_command="bogus")) == _legacy.EXIT_USAGE_ERRORdef test_parser_registers_the_portfolio_subcommands() -> None:parser = _legacy._build_parser()assert parser.parse_args(["portfolio"]).portfolio_command is None+ assert parser.parse_args(["portfolio", "show", "--snapshot-id", "abc"]).snapshot_id == "abc"for sub in ("show", "refresh", "sources"):args = parser.parse_args(["portfolio", sub])assert args.command == "portfolio" and args.portfolio_command == subdiff --git a/agent/tests/test_portfolio_routes.py b/agent/tests/test_portfolio_routes.pyindex 81df981a3..04905aa60 100644--- a/agent/tests/test_portfolio_routes.py+++ b/agent/tests/test_portfolio_routes.py@@ -39,8 +39,8 @@ class _Service:def export_csv(self):return "broker,symbol\nibkr,AAPL\n"- def analysis_context(self):- return {"privacy": "sanitized"}+ def analysis_context(self, snapshot_id=None):+ return None if snapshot_id == "gone" else {"privacy": "sanitized", "snapshot_id": snapshot_id}def test_portfolio_routes_are_readonly_and_return_expected_shapes(monkeypatch):@@ -109,6 +109,18 @@ def test_portfolio_routes_are_readonly_and_return_expected_shapes(monkeypatch):assert "ibkr,AAPL" in exported.text+def test_analysis_context_route_pins_snapshot_and_never_falls_back(monkeypatch):+ monkeypatch.setattr(portfolio_routes, "PortfolioService", _Service)+ app = FastAPI()+ portfolio_routes.register_portfolio_routes(app)+ client = TestClient(app)+ response = client.get("/api/portfolio/analysis-context?snapshot_id=first")+ assert response.status_code == 200+ assert response.json()["context"]["snapshot_id"] == "first"+ assert client.get("/api/portfolio/analysis-context?snapshot_id=gone").status_code == 404+ assert client.get("/api/portfolio/analysis-context?snapshot_id=").status_code == 422++def test_concurrent_portfolio_reconnect_returns_conflict(monkeypatch):monkeypatch.setattr(portfolio_routes, "PortfolioService", _Service)app = FastAPI()diff --git a/agent/tests/test_readonly_replay_after_microcompact.py b/agent/tests/test_readonly_replay_after_microcompact.pyindex 586266374..bec79457d 100644--- a/agent/tests/test_readonly_replay_after_microcompact.py+++ b/agent/tests/test_readonly_replay_after_microcompact.py@@ -301,7 +301,7 @@ class _VisibilityLLM:))self.monkeypatch.setattr(- loop_mod,+ __import__("src.agent.tuning", fromlist=["TOKEN_THRESHOLD"]),"TOKEN_THRESHOLD",max(2, int(loop_mod.estimate_tokens(future) * 1.6)),raising=False,diff --git a/agent/tests/test_session_store_encoding_corrupt.py b/agent/tests/test_session_store_encoding_corrupt.pynew file mode 100644index 000000000..c6614d311--- /dev/null+++ b/agent/tests/test_session_store_encoding_corrupt.py@@ -0,0 +1,66 @@+"""Unreadable UTF-8 records must not hide intact saved-session records."""++from pathlib import Path++import pytest++from src.session.models import Attempt, Message, Session+from src.session.store import SessionStore++[email protected]("bad_bytes", [b'\xff', b'{"title":"\xe4\xb8"}'])+def test_bad_session_encoding_keeps_order_limit_and_original_bytes(+ tmp_path: Path, caplog, bad_bytes: bytes+) -> None:+ store = SessionStore(tmp_path / "sessions")+ store.create_session(Session(session_id="older", updated_at="2026-01-01"))+ store.create_session(Session(session_id="newer", updated_at="2026-01-02"))+ path = store._session_file("broken")+ path.parent.mkdir()+ path.write_bytes(bad_bytes)++ assert [s.session_id for s in store.list_sessions()] == ["newer", "older"]+ assert [s.session_id for s in store.list_sessions(limit=1)] == ["newer"]+ assert store.get_session("broken") is None+ assert path.read_bytes() == bad_bytes+ assert "Skipping corrupt JSON" in caplog.text++[email protected]("bad_bytes", [b'\xff', b'{"prompt":"\xe4\xb8"}'])+def test_bad_attempt_encoding_keeps_siblings_and_original_bytes(+ tmp_path: Path, caplog, bad_bytes: bytes+) -> None:+ store = SessionStore(tmp_path / "sessions")+ store.create_session(Session(session_id="sample"))+ store.create_attempt(Attempt(session_id="sample", attempt_id="intact"))+ path = store._attempt_file("sample", "broken")+ path.parent.mkdir()+ path.write_bytes(bad_bytes)++ assert [a.attempt_id for a in store.list_attempts()] == ["intact"]+ assert store.get_attempt("sample", "broken") is None+ assert path.read_bytes() == bad_bytes+ assert "Skipping corrupt JSON" in caplog.text++[email protected]("bad_line", [b'{"content":"\xff"}\n', b'\xe4\xb8\r\n'])+def test_bad_message_encoding_preserves_neighbors_limits_and_original_bytes(+ tmp_path: Path, caplog, bad_line: bytes+) -> None:+ store = SessionStore(tmp_path / "sessions")+ store.create_session(Session(session_id="sample"))+ store.append_message(Message(session_id="sample", content="之前 😀"))+ path = store._messages_file("sample")+ with path.open("ab") as log:+ log.write(bad_line)+ store.append_message(Message(session_id="sample", content="之后 café"))+ original = path.read_bytes()++ assert [m.content for m in store.get_messages("sample")] == [+ "之前 😀", "之后 café"+ ]+ assert [m.content for m in store.get_messages("sample", limit=1)] == [+ "之后 café"+ ]+ assert path.read_bytes() == original+ assert "Skipping corrupted message" in caplog.textdiff --git a/agent/tests/test_slack_connection_test.py b/agent/tests/test_slack_connection_test.pyindex 2d7f0f472..aa4c22fe0 100644--- a/agent/tests/test_slack_connection_test.py+++ b/agent/tests/test_slack_connection_test.py@@ -86,7 +86,9 @@ def _run(coro: Any) -> Any:def _ok_handler(request: httpx.Request) -> httpx.Response:"""Answer both legs the way Slack answers valid credentials."""if str(request.url) == AUTH_TEST_URL:- return httpx.Response(200, json={"ok": True, "user_id": "U12345"})+ return httpx.Response(+ 200, json={"ok": True, "user_id": "U12345", "bot_id": "B12345"}+ )if str(request.url) == CONNECTIONS_OPEN_URL:return httpx.Response(200, json={"ok": True, "url": WSS_URL})raise AssertionError(f"unexpected URL {request.url}") # pragma: no cover@@ -162,7 +164,7 @@ def test_socket_mode_disabled_reports_invalid_credentials_on_leg_two(def handler(request: httpx.Request) -> httpx.Response:if str(request.url) == AUTH_TEST_URL:- return httpx.Response(200, json={"ok": True})+ return httpx.Response(200, json={"ok": True, "bot_id": "B12345"})return httpx.Response(200, json={"ok": False, "error": "not_allowed"})requests = _inject_mock_transport(monkeypatch, handler)@@ -234,7 +236,7 @@ def test_leg_two_server_error_reports_network() -> None:def handler(request: httpx.Request) -> httpx.Response:if str(request.url) == AUTH_TEST_URL:- return httpx.Response(200, json={"ok": True})+ return httpx.Response(200, json={"ok": True, "bot_id": "B12345"})return httpx.Response(503, text="upstream exploded")_inject_mock_transport(monkeypatch, handler)@@ -273,7 +275,7 @@ def test_rejection_detail_scrubs_echoed_tokens(# Force leg 2 to be the echoing leg.def leg2_handler(request: httpx.Request) -> httpx.Response:if str(request.url) == AUTH_TEST_URL:- return httpx.Response(200, json={"ok": True})+ return httpx.Response(200, json={"ok": True, "bot_id": "B12345"})return httpx.Response(500, text=f"exploded with {APP_TOKEN}")_inject_mock_transport(monkeypatch, leg2_handler)@@ -296,3 +298,38 @@ def test_probe_never_logs_tokens_or_wss_url(assert BOT_TOKEN not in caplog.textassert APP_TOKEN not in caplog.textassert WSS_URL not in caplog.text+++def test_user_token_is_rejected_before_opening_socket(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ requests = _inject_mock_transport(+ monkeypatch,+ lambda request: httpx.Response(200, json={"ok": True, "user_id": "U12345"}),+ )+ result = _run(_make_channel().test_connection())+ assert result["ok"] is False+ assert result["code"] == "invalid_credentials"+ assert len(requests) == 1+++def test_unsupported_mode_is_rejected_without_http(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ requests = _inject_mock_transport(monkeypatch, _ok_handler)+ result = _run(_make_channel(mode="http").test_connection())+ assert result["ok"] is False+ assert result["code"] == "invalid_credentials"+ assert not requests++[email protected]("status", [408, 429])+def test_transient_http_failure_is_not_invalid_credentials(+ monkeypatch: pytest.MonkeyPatch, status: int+) -> None:+ _inject_mock_transport(+ monkeypatch, lambda request: httpx.Response(status, text="try again later")+ )+ result = _run(_make_channel().test_connection())+ assert result["ok"] is False+ assert result["code"] == "network"diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 8297f2e53..c8000bcaf 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -2142,7 +2142,9 @@"errorReconnect": "فشلت إعادة ربط الحساب","errorReconnectTimeout": "انتهت مهلة تفويض المتصفح. أعد الاتصال وأكمل تفويض الوسيط سريعًا.","errorSaveSettings": "تعذّر حفظ إعدادات المحفظة",- "errorExport": "فشل التصدير"+ "errorExport": "فشل التصدير",+ "exportResearch": "تصدير لقطة البحث",+ "researchSnapshotHint": "صدّر هذه الملاحظة دون بيانات اعتماد أو أرقام حسابات. أعد استخدام معرّف اللقطة في portfolio_summary."},"metrics": {"total": "إجمالي الأصول",diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.jsonindex d92c81288..fe75b172e 100644--- a/frontend/src/i18n/locales/de.json+++ b/frontend/src/i18n/locales/de.json@@ -2142,7 +2142,9 @@"errorReconnect": "Erneutes Verbinden des Kontos fehlgeschlagen","errorReconnectTimeout": "Die Browser-Autorisierung ist abgelaufen. Verbinden Sie sich erneut und schließen Sie die Broker-Autorisierung zeitnah ab.","errorSaveSettings": "Portfolio-Einstellungen konnten nicht gespeichert werden",- "errorExport": "Export fehlgeschlagen"+ "errorExport": "Export fehlgeschlagen",+ "exportResearch": "Analyse-Snapshot exportieren",+ "researchSnapshotHint": "Diese Beobachtung ohne Zugangsdaten oder Kontonummern exportieren. Die Snapshot-ID kann in portfolio_summary wiederverwendet werden."},"metrics": {"total": "Gesamtvermögen",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 78ffb0881..25b0cebd6 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -2142,7 +2142,9 @@"errorReconnect": "Account reconnect failed","errorReconnectTimeout": "Browser authorization timed out. Reconnect and complete the broker authorization promptly.","errorSaveSettings": "Unable to save portfolio settings",- "errorExport": "Export failed"+ "errorExport": "Export failed",+ "exportResearch": "Export research snapshot",+ "researchSnapshotHint": "Export this exact observation without credentials or account numbers. Reuse its snapshot ID in portfolio_summary."},"metrics": {"total": "Total assets",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex 923ef9ad2..3b5d42f14 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -2142,7 +2142,9 @@"errorReconnect": "No se pudo volver a conectar la cuenta","errorReconnectTimeout": "La autorización del navegador agotó el tiempo. Vuelve a conectar y completa pronto la autorización del bróker.","errorSaveSettings": "No se pudieron guardar los ajustes de la cartera",- "errorExport": "Fallo al exportar"+ "errorExport": "Fallo al exportar",+ "exportResearch": "Exportar instantánea de análisis",+ "researchSnapshotHint": "Exporta esta observación sin credenciales ni números de cuenta. Reutiliza su ID de instantánea en portfolio_summary."},"metrics": {"total": "Activos totales",diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.jsonindex 17b860b81..869e823ec 100644--- a/frontend/src/i18n/locales/id.json+++ b/frontend/src/i18n/locales/id.json@@ -2142,7 +2142,9 @@"errorReconnect": "Gagal menghubungkan ulang akun","errorReconnectTimeout": "Otorisasi browser mengalami timeout. Hubungkan ulang dan selesaikan otorisasi broker sesegera mungkin.","errorSaveSettings": "Tidak dapat menyimpan pengaturan portofolio",- "errorExport": "Ekspor gagal"+ "errorExport": "Ekspor gagal",+ "exportResearch": "Ekspor snapshot riset",+ "researchSnapshotHint": "Ekspor pengamatan ini tanpa kredensial atau nomor rekening. Gunakan kembali ID snapshot di portfolio_summary."},"metrics": {"total": "Total aset",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex 1a3827ec2..999d98a9d 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -2142,7 +2142,9 @@"errorReconnect": "口座の再接続に失敗しました","errorReconnectTimeout": "ブラウザー認証がタイムアウトしました。再接続し、ブローカー認証を速やかに完了してください。","errorSaveSettings": "ポートフォリオ設定を保存できません",- "errorExport": "書き出しに失敗しました"+ "errorExport": "書き出しに失敗しました",+ "exportResearch": "調査用スナップショットを出力",+ "researchSnapshotHint": "認証情報や口座番号を含めず、この観測を出力します。portfolio_summary でスナップショット ID を再利用できます。"},"metrics": {"total": "総資産",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex 99a5eb565..014bb9536 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -2142,7 +2142,9 @@"errorReconnect": "계좌 재연결에 실패했습니다","errorReconnectTimeout": "브라우저 인증 시간이 초과되었습니다. 다시 연결하고 브로커 인증을 신속히 완료하세요.","errorSaveSettings": "포트폴리오 설정을 저장할 수 없습니다",- "errorExport": "내보내기에 실패했습니다"+ "errorExport": "내보내기에 실패했습니다",+ "exportResearch": "연구 스냅샷 내보내기",+ "researchSnapshotHint": "인증 정보나 계좌 번호 없이 이 관측을 내보냅니다. portfolio_summary에서 스냅샷 ID를 재사용할 수 있습니다."},"metrics": {"total": "총자산",diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.jsonindex 07c8fd23d..dbcfe26ba 100644--- a/frontend/src/i18n/locales/pt-BR.json+++ b/frontend/src/i18n/locales/pt-BR.json@@ -2142,7 +2142,9 @@"errorReconnect": "Falha na reconexão da conta","errorReconnectTimeout": "A autorização do navegador expirou. Reconecte-se e conclua a autorização do corretora imediatamente.","errorSaveSettings": "Não foi possível salvar as configurações do portfólio",- "errorExport": "Falha na exportação"+ "errorExport": "Falha na exportação",+ "exportResearch": "Exportar snapshot de análise",+ "researchSnapshotHint": "Exporte esta observação sem credenciais ou números de conta. Reutilize seu ID de snapshot em portfolio_summary."},"metrics": {"total": "Ativos totais",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex de27095fc..6c6c87b35 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -2142,7 +2142,9 @@"errorReconnect": "账户重新连接失败","errorReconnectTimeout": "等待浏览器授权超时,请重新连接并及时完成券商授权","errorSaveSettings": "无法保存持仓设置",- "errorExport": "导出失败"+ "errorExport": "导出失败",+ "exportResearch": "导出研究快照",+ "researchSnapshotHint": "导出当前这份观测,不含凭证和账户号码。可在 portfolio_summary 中复用其快照 ID。"},"metrics": {"total": "总资产",diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex a9f72b541..3ca18817d 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -439,6 +439,8 @@ export const api = {`/correlation/regime?codes=${encodeURIComponent(codes)}&days=${encodeURIComponent(String(days))}`,),getPortfolio: () => request<{ status: string; snapshot: PortfolioSnapshot | null }>("/api/portfolio"),+ getPortfolioAnalysisContext: (snapshotId: string) =>+ request<{ status: string; context: Record<string, unknown> }>(`/api/portfolio/analysis-context?snapshot_id=${encodeURIComponent(snapshotId)}`),refreshPortfolio: () => request<{ status: string; snapshot: PortfolioSnapshot }>("/api/portfolio/refresh", { method: "POST" }),getPortfolioRefreshStatus: () => request<{ status: string; refresh: PortfolioRefreshState }>("/api/portfolio/refresh-status"),reconnectPortfolioSource: (sourceId: string) =>diff --git a/frontend/src/pages/Portfolio.tsx b/frontend/src/pages/Portfolio.tsxindex c69a8b9a0..aeeb93b91 100644--- a/frontend/src/pages/Portfolio.tsx+++ b/frontend/src/pages/Portfolio.tsx@@ -256,6 +256,22 @@ export function Portfolio() {}}+ async function downloadResearchSnapshot() {+ if (!snapshot) return;+ try {+ const result = await api.getPortfolioAnalysisContext(snapshot.snapshot_id);+ const blob = new Blob([JSON.stringify(result.context, null, 2)], { type: "application/json" });+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = `portfolio-research-${snapshot.snapshot_id}.json`;+ anchor.click();+ URL.revokeObjectURL(url);+ } catch (err) {+ setError(err instanceof Error ? err.message : t("portfolio.page.errorExport"));+ }+ }+useEffect(() => { void load(); }, []);const positions = useMemo(() => {@@ -338,6 +354,9 @@ export function Portfolio() {<button onClick={() => void download()} disabled={!snapshot} className="inline-flex items-center gap-2 rounded-md border bg-card px-4 py-2 text-sm disabled:opacity-50"><Download className="h-4 w-4" />{t("portfolio.page.exportCsv")}</button>+ <button onClick={() => void downloadResearchSnapshot()} disabled={!snapshot} className="inline-flex items-center gap-2 rounded-md border bg-card px-4 py-2 text-sm disabled:opacity-50" title={t("portfolio.page.researchSnapshotHint")}>+ <Download className="h-4 w-4" />{t("portfolio.page.exportResearch")}+ </button><button onClick={() => void refresh()} disabled={refreshing || reconnectingSource !== null} className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50">{refreshing ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}{refreshing ? t("portfolio.page.refreshing") : t("portfolio.page.refreshAll")}diff --git a/frontend/src/pages/__tests__/Portfolio.test.tsx b/frontend/src/pages/__tests__/Portfolio.test.tsxindex 0dd71054f..542eb4d2d 100644--- a/frontend/src/pages/__tests__/Portfolio.test.tsx+++ b/frontend/src/pages/__tests__/Portfolio.test.tsx@@ -11,6 +11,7 @@ vi.mock("@/lib/api", async () => {api: {...actual.api,getPortfolio: vi.fn(),+ getPortfolioAnalysisContext: vi.fn(),refreshPortfolio: vi.fn(),getPortfolioRefreshStatus: vi.fn(),reconnectPortfolioSource: vi.fn(),@@ -30,6 +31,7 @@ vi.mock("@/lib/api", async () => {const mocked = api as unknown as {getPortfolio: ReturnType<typeof vi.fn>;+ getPortfolioAnalysisContext: ReturnType<typeof vi.fn>;refreshPortfolio: ReturnType<typeof vi.fn>;getPortfolioRefreshStatus: ReturnType<typeof vi.fn>;reconnectPortfolioSource: ReturnType<typeof vi.fn>;@@ -133,6 +135,35 @@ const portfolioConfiguration = {};describe("Portfolio page", () => {+ it("exports the displayed observation by id and reports a revoked snapshot", async () => {+ const context = { snapshot_id: "snap-1", totals: { usd: 1000 }, read_identity: { mode: "pinned" } };+ mocked.getPortfolioAnalysisContext.mockResolvedValue({ status: "ok", context });+ const create = vi.fn(() => "blob:research");+ const revoke = vi.fn();+ vi.stubGlobal("URL", class extends URL {+ static createObjectURL = create;+ static revokeObjectURL = revoke;+ });+ const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});+ try {+ render(<Portfolio />);+ const button = await screen.findByRole("button", { name: "Export research snapshot" });+ await waitFor(() => expect(button).toBeEnabled());+ fireEvent.click(button);+ await waitFor(() => expect(click).toHaveBeenCalledOnce());+ expect(mocked.getPortfolioAnalysisContext).toHaveBeenCalledWith("snap-1");+ expect(create).toHaveBeenCalledWith(expect.any(Blob));+ expect(revoke).toHaveBeenCalledWith("blob:research");+ mocked.getPortfolioAnalysisContext.mockRejectedValue(new Error("portfolio snapshot unavailable"));+ fireEvent.click(button);+ expect(await screen.findByText("portfolio snapshot unavailable")).toBeInTheDocument();+ expect(click).toHaveBeenCalledOnce();+ } finally {+ click.mockRestore();+ vi.unstubAllGlobals();+ }+ });+beforeEach(() => {vi.clearAllMocks();mocked.getPortfolio.mockResolvedValue({ status: "ok", snapshot });