"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: complete protected PDF surfaces and fail incomplete KIS reads
Haozhe Wu391d7217a1bd
diff --git a/agent/cli/commands/research_playbook.py b/agent/cli/commands/research_playbook.pyindex b9527c6bf..99a9aa4be 100644--- a/agent/cli/commands/research_playbook.py+++ b/agent/cli/commands/research_playbook.py@@ -167,6 +167,7 @@ def build_job_from_playbook(job_id: Optional[str] = None,delivery_target_ref: Optional[str] = None,delivery_format: Optional[str] = None,+ protect_pdf: bool = False,) -> Tuple[Optional[Any], Optional[str]]:"""Build (but do not persist) a scheduled job from a template.@@ -184,6 +185,7 @@ def build_job_from_playbook(job_id: Explicit job id, or ``None`` for a generated one.delivery_target_ref: Configured delivery destination reference.delivery_format: Email format (html/pdf), or None for plain text.+ protect_pdf: Encrypt a PDF Email report with the configured channel password.Returns:A ``(job, error)`` pair; exactly one side is populated.@@ -194,6 +196,7 @@ def build_job_from_playbook("variables": variables or {},"delivery_target_ref": delivery_target_ref,"delivery_format": delivery_format,+ "protect_pdf": protect_pdf,}if schedule is not None:kwargs["schedule"] = schedule@@ -202,6 +205,11 @@ def build_job_from_playbook(if job_id:kwargs["job_id"] = job_idtry:+ if protect_pdf:+ from src.scheduled_research.service import email_pdf_password_configured++ if not email_pdf_password_configured():+ raise ValueError("PDF protection requested but no PDF password is configured")return build_job(slug, **kwargs), Noneexcept (ValueError, OSError) as exc:# PlaybookError and PlaybookNotFoundError both subclass ValueError.@@ -531,6 +539,7 @@ def add_subparser(subparsers: Any) -> argparse.ArgumentParser:p_create.add_argument("--id", dest="playbook_id", default=None, help="Explicit job id")p_create.add_argument("--delivery-target-ref", default=None, help="Configured delivery destination reference")p_create.add_argument("--delivery-format", choices=("html", "pdf"), default=None, help="Email format; omit for plain text")+ p_create.add_argument("--protect-pdf", action="store_true", help="Encrypt the PDF using the private Email channel password")p_create.add_argument("--dry-run",dest="playbook_dry_run",@@ -608,6 +617,7 @@ def _cmd_create(args: argparse.Namespace) -> int:job_id=getattr(args, "playbook_id", None),delivery_target_ref=getattr(args, "delivery_target_ref", None),delivery_format=getattr(args, "delivery_format", None),+ protect_pdf=getattr(args, "protect_pdf", False),)if job is None:_print(f"[bold red]{build_error}[/bold red]")diff --git a/agent/cli/main.py b/agent/cli/main.pyindex ec6fd8c48..fd71d8020 100644--- a/agent/cli/main.py+++ b/agent/cli/main.py@@ -1085,6 +1085,9 @@ def _render_scheduled_proposal(console: Any, proposal: Dict[str, Any]) -> None:if delivery.get("channel") == "email":label = {"html": "HTML", "pdf": "PDF"}.get(delivery.get("format"), "纯文本")console.print(f" 邮件格式: {label}")+ if delivery.get("format") == "pdf":+ protection = "开启" if delivery.get("protect_pdf") is True else "关闭"+ console.print(f" PDF 密码保护: {protection}")console.print("确认执行? [y/N]", style="bold", markup=False)diff --git a/agent/src/api/scheduled_routes.py b/agent/src/api/scheduled_routes.pyindex b3ed52523..70eee738c 100644--- a/agent/src/api/scheduled_routes.py+++ b/agent/src/api/scheduled_routes.py@@ -429,19 +429,9 @@ def _job_to_response(job: ScheduledResearchJob) -> "ScheduledRunResponse":def _email_pdf_password_configured() -> bool:"""Read only whether the private Email PDF password is configured."""- host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")- manager = getattr(host, "_channel_manager", None) if host else None- adapter = manager.get_channel("email") if manager is not None else None- if adapter is not None:- return bool(getattr(getattr(adapter, "config", None), "pdf_password", ""))- try:- from src.channels.config import load_channels_config+ from src.scheduled_research.service import email_pdf_password_configured- section = load_channels_config().get("email", {})- return bool(section.get("pdf_password")) if isinstance(section, dict) else False- except Exception:- # A configuration read/parse failure must not authorize protected jobs.- return False+ return email_pdf_password_configured()# ---------------------------------------------------------------------------diff --git a/agent/src/channels/runtime.py b/agent/src/channels/runtime.pyindex 516648cdf..4c4d9041f 100644--- a/agent/src/channels/runtime.py+++ b/agent/src/channels/runtime.py@@ -209,6 +209,9 @@ class ChannelRuntime:if delivery.get("channel") == "email":label = {"html": "HTML", "pdf": "PDF"}.get(delivery.get("format"), "plain text")email_format = f"Email format: {label}\n"+ if delivery.get("format") == "pdf":+ protection = "on" if delivery.get("protect_pdf") is True else "off"+ email_format += f"PDF password protection: {protection}\n"reply_content = (f"{reply_content}\n\n"f"[Scheduled research confirmation · {action}]\n"diff --git a/agent/src/scheduled_research/models.py b/agent/src/scheduled_research/models.pyindex 56094b528..523290b19 100644--- a/agent/src/scheduled_research/models.py+++ b/agent/src/scheduled_research/models.py@@ -406,6 +406,10 @@ class ScheduledResearchJob:"""if contains_pdf_password(self.config):raise ValueError("scheduled research config must not contain pdf_password")+ if not isinstance(self.protect_pdf, bool):+ raise TypeError("'protect_pdf' must be a boolean")+ if self.protect_pdf and (self.delivery_channel != "email" or self.delivery_format != "pdf"):+ raise ValueError("'protect_pdf' requires PDF email delivery")return {"id": self.id,"prompt": self.prompt,@@ -514,8 +518,8 @@ class ScheduledResearchJob:protect_pdf = data.get("protect_pdf", False)if not isinstance(protect_pdf, bool):raise TypeError("'protect_pdf' must be a boolean")- if protect_pdf and delivery_format != "pdf":- raise ValueError("'protect_pdf' requires delivery_format='pdf'")+ if protect_pdf and (delivery_channel != "email" or delivery_format != "pdf"):+ raise ValueError("'protect_pdf' requires PDF email delivery")for name, value in (("delivery_channel", delivery_channel),("delivery_target", delivery_target),diff --git a/agent/src/scheduled_research/proposals.py b/agent/src/scheduled_research/proposals.pyindex 5478ea1d5..8748ca73f 100644--- a/agent/src/scheduled_research/proposals.py+++ b/agent/src/scheduled_research/proposals.py@@ -174,6 +174,11 @@ def commit_proposal(proposal_id: str) -> dict[str, Any]:from src.scheduled_research.models import ScheduledResearchJobjob = ScheduledResearchJob.from_dict(payload["internal_job"])+ if job.protect_pdf:+ from src.scheduled_research.service import email_pdf_password_configured++ if not email_pdf_password_configured():+ raise ProposalError("PDF protection requested but no PDF password is configured")store.upsert(job)payload["committed_job_id"] = job.idelif payload["operation"] == "cancel":diff --git a/agent/src/scheduled_research/service.py b/agent/src/scheduled_research/service.pyindex f526a7caa..6e9823dde 100644--- a/agent/src/scheduled_research/service.py+++ b/agent/src/scheduled_research/service.py@@ -47,6 +47,7 @@ def public_job(job: ScheduledResearchJob) -> dict[str, Any]:"target_ref": job.delivery_target_ref,"target_label": job.delivery_target_label,"format": job.delivery_format,+ "protect_pdf": job.protect_pdf,"status": job.delivery.status.value,"attempts": job.delivery.attempts,"provider_message_id": job.delivery.provider_message_id,@@ -75,6 +76,26 @@ def scheduler_status() -> dict[str, Any]:return {"enabled": enabled, "running": running, "executable": enabled and running}+def email_pdf_password_configured() -> bool:+ """Return whether the active Email channel has a private PDF password.++ Returns:+ Password presence only, preferring the running adapter configuration.+ """+ host = sys.modules.get("api_server") or sys.modules.get("agent.api_server")+ manager = getattr(host, "_channel_manager", None) if host else None+ adapter = manager.get_channel("email") if manager is not None else None+ if adapter is not None:+ return bool(getattr(getattr(adapter, "config", None), "pdf_password", ""))+ try:+ from src.channels.config import load_channels_config++ section = load_channels_config().get("email", {})+ return bool(section.get("pdf_password")) if isinstance(section, dict) else False+ except Exception:+ return False++def _parse_end_at(value: Any) -> int | None:if value in (None, ""):return None@@ -193,6 +214,8 @@ def build_job_from_draft(raise ValueError("delivery.format is supported only for email delivery")if protect_pdf and delivery_format != "pdf":raise ValueError("delivery.protect_pdf requires PDF email delivery")+ if protect_pdf and not email_pdf_password_configured():+ raise ValueError("PDF protection requested but no PDF password is configured")return ScheduledResearchJob(id=str(draft.get("id") or f"sr-{uuid.uuid4().hex[:12]}"),diff --git a/agent/src/tools/scheduled_research_tool.py b/agent/src/tools/scheduled_research_tool.pyindex 14807d05a..51b307fd0 100644--- a/agent/src/tools/scheduled_research_tool.py+++ b/agent/src/tools/scheduled_research_tool.py@@ -77,6 +77,10 @@ class ScheduledResearchTool(BaseTool):"enum": ["html", "pdf", None],"description": "Email only; omit or null for plain text. Destination must be configured or from the origin session.",},+ "protect_pdf": {+ "type": "boolean",+ "description": "Encrypt a PDF Email report using the private channel password configured by the user; never supply the password in a draft.",+ },},"required": ["mode"],},diff --git a/agent/src/trading/connectors/kis/sdk.py b/agent/src/trading/connectors/kis/sdk.pyindex 44b2ae750..0eef2ec2c 100644--- a/agent/src/trading/connectors/kis/sdk.py+++ b/agent/src/trading/connectors/kis/sdk.py@@ -366,6 +366,8 @@ def get_open_orders(items.append(item)open_orders, executions = [], []+ if venue_errors:+ raise KISAPIError("KIS order inquiry is incomplete: " + "; ".join(venue_errors))for item in items:row = _order_to_dict(item)remaining = _as_float(item.get("rmn_qty"))@@ -382,8 +384,6 @@ def get_open_orders(}if include_executions:result["executions"] = executions- if venue_errors:- result["venue_errors"] = venue_errorsreturn result@@ -790,6 +790,8 @@ def _get_paginated(for _ in range(_MAX_CONTINUATION_PAGES):body, headers = _request(cfg, "GET", path, tr_id=tr_id, params=page_params, tr_cont=tr_cont)last_body = body+ if not isinstance(body.get(rows_key), list):+ raise KISAPIError(f"KIS {path} returned no valid {rows_key} list; inquiry is incomplete")rows.extend(_as_list(body.get(rows_key)))if str(headers.get("tr_cont", "")) not in ("F", "M"):break@@ -834,8 +836,6 @@ def _request(except requests.RequestException as exc:raise KISAPIError(f"KIS request failed: {exc}") from exc- if response.status_code in (401, 403):- raise KISAPIError("KIS API authentication failed: check app_key/app_secret.")if response.status_code >= 400:message = _error_message(response)# KIS issues ONE token per app_key: a token minted for the other@@ -846,20 +846,33 @@ def _request(if attempt == 0 and _is_expired_token(message):_clear_token_cache(cfg)continue+ if response.status_code in (401, 403):+ raise KISAPIError("KIS API authentication failed: check app_key/app_secret.")raise KISAPIError(f"KIS API returned HTTP {response.status_code}: {message}")try:- return response.json(), response.headers+ payload = response.json()except ValueError as exc:raise KISAPIError("KIS API returned invalid JSON.") from exc+ if not isinstance(payload, dict):+ raise KISAPIError("KIS API returned a non-object response.")+ if payload.get("rt_cd") is not None and str(payload["rt_cd"]) != "0":+ message = _error_message(response)+ if attempt == 0 and _is_expired_token(message):+ _clear_token_cache(cfg)+ continue+ raise KISAPIError(f"KIS API rejected the request: {message}")+ return payload, response.headersraise KISAPIError("KIS API rejected the token twice; re-issue failed.")def _is_expired_token(message: str) -> bool:+ """Recognize the broker's explicit token-expiry rejection."""low = message.lower()- return "만료된 token" in message or "expired" in low and "token" in low+ return "만료된 token" in low or "expired" in low and "token" in lowdef _clear_token_cache(cfg: KISConfig) -> None:+ """Discard this environment's rejected token before one bounded retry."""try:_token_cache_path(cfg).unlink(missing_ok=True)except OSError:diff --git a/agent/tests/test_binance_fallback.py b/agent/tests/test_binance_fallback.pyindex 2c4c8f044..b7c839d75 100644--- a/agent/tests/test_binance_fallback.py+++ b/agent/tests/test_binance_fallback.py@@ -39,3 +39,20 @@ def test_market_data_falls_back_from_okx_to_binance() -> None:assert calls[:2] == ["okx", "binance"]assert "BTC-USDT" in result+def test_binance_loader_canonical_frame_uses_shared_contract(monkeypatch):+ import pandas as pd++ from backtest.loaders.binance_loader import DataLoader+ from tests.loader_contract import assert_loader_contract++ class Exchange:+ def fetch_ohlcv(self, symbol, timeframe, **_kwargs):+ assert (symbol, timeframe) == ("BTC/USDT", "1d")+ day = 86_400_000+ start = int(pd.Timestamp("2026-10-01", tz="UTC").timestamp() * 1000)+ return [[start + i * day, 100 + i, 102 + i, 99 + i, 101 + i, 20] for i in range(3)]++ monkeypatch.setenv("VIBE_TRADING_DATA_CACHE", "0")+ monkeypatch.setattr(DataLoader, "_get_exchange", lambda *_args: Exchange())+ result = DataLoader().fetch(["BTC-USDT"], "2026-10-01", "2026-10-03")+ assert_loader_contract(result["BTC-USDT"], context="binance daily")diff --git a/agent/tests/test_kis_recovery.py b/agent/tests/test_kis_recovery.pynew file mode 100644index 000000000..a01e4e552--- /dev/null+++ b/agent/tests/test_kis_recovery.py@@ -0,0 +1,79 @@+"""Broker rejections remain errors and explicit token expiry retries once."""++from __future__ import annotations++import json++import pytest+import requests++from src.trading.connectors.kis import sdk as kis+++def config():+ return kis.KISConfig(app_key="fixture-key", app_secret="fixture-secret", account_no="12345678", profile="live-readonly")+++def _response(status, body):+ response = requests.Response()+ response.status_code = status+ response._content = json.dumps(body).encode()+ return response++[email protected]("status", [200, 401, 403, 500])+def test_expired_token_refreshes_once_on_explicit_broker_rejection(monkeypatch, config, status):+ responses = iter([+ _response(status, {"rt_cd": "1", "msg1": "기간이 만료된 token 입니다"}),+ _response(200, {"rt_cd": "0", "output1": []}),+ ])+ calls, cleared = [], []+ monkeypatch.setattr(kis, "_headers", lambda *_args: {})+ monkeypatch.setattr(kis, "_clear_token_cache", lambda cfg: cleared.append(cfg))+ def request(*args, **kwargs):+ calls.append(args)+ return next(responses)+ monkeypatch.setattr(kis.requests, "request", request)+ payload, _ = kis._request(config, "GET", "/read", tr_id="fixture")+ assert payload["rt_cd"] == "0"+ assert len(calls) == 2+ assert cleared == [config]+++def test_success_http_with_broker_error_is_not_empty_success(monkeypatch, config):+ monkeypatch.setattr(kis, "_headers", lambda *_args: {})+ monkeypatch.setattr(kis.requests, "request", lambda *_args, **_kwargs: _response(200, {"rt_cd": "1", "msg1": "invalid account"}))+ with pytest.raises(kis.KISAPIError, match="invalid account"):+ kis._request(config, "GET", "/read", tr_id="fixture")+++def test_incomplete_venue_reads_cannot_look_complete(monkeypatch, config):+ def paginated(_cfg, _path, *, tr_id, params):+ if params["EXCG_ID_DVSN_CD"] == "SOR":+ raise kis.KISAPIError("temporary venue failure")+ return {"output1": []}+ monkeypatch.setattr(kis, "_get_paginated", paginated)+ with pytest.raises(kis.KISAPIError, match="incomplete"):+ kis.get_open_orders(config)+++def test_expiry_cannot_retry_indefinitely(monkeypatch, config):+ calls, cleared = [], []+ monkeypatch.setattr(kis, "_headers", lambda *_args: {})+ monkeypatch.setattr(kis, "_clear_token_cache", lambda cfg: cleared.append(cfg))+ def request(*args, **kwargs):+ calls.append(args)+ return _response(200, {"rt_cd": "1", "msg1": "expired token"})+ monkeypatch.setattr(kis.requests, "request", request)+ with pytest.raises(kis.KISAPIError, match="expired token"):+ kis._request(config, "GET", "/read", tr_id="fixture")+ assert len(calls) == 2+ assert len(cleared) == 1++[email protected]("body", [{"rt_cd": "0"}, {"rt_cd": "0", "output1": None}])+def test_missing_order_list_cannot_mean_no_orders(monkeypatch, config, body):+ monkeypatch.setattr(kis, "_request", lambda *args, **kwargs: (body, {}))+ with pytest.raises(kis.KISAPIError, match="incomplete"):+ kis.get_open_orders(config)diff --git a/agent/tests/test_loader_contract.py b/agent/tests/test_loader_contract.pynew file mode 100644index 000000000..1c5ba3a9e--- /dev/null+++ b/agent/tests/test_loader_contract.py@@ -0,0 +1,89 @@+"""Pin the shared checker to the health lane and every registered source."""++from __future__ import annotations++import ast+from pathlib import Path++import numpy as np+import pandas as pd+import pytest++from backtest.loader_health import check_frame+from backtest.loaders.registry import VALID_SOURCES+from tests.loader_contract import loader_contract_errors+++CONTRACT_SUITES = {+ "akshare": "test_akshare_loader.py",+ "alphavantage": "test_alphavantage_loader.py",+ "baostock": "test_baostock_loader.py",+ "binance": "test_binance_fallback.py",+ "ccxt": "test_ccxt_loader_bounded.py",+ "eastmoney": "test_eastmoney_loader.py",+ "finnhub": "test_finnhub_loader.py",+ "fmp": "test_fmp_loader.py",+ "futu": "test_futu_loader.py",+ "gildata": "test_gildata_loader.py",+ "india_broker": "test_india_broker_loader.py",+ "local": "test_local_loader.py",+ "longbridge": "test_longbridge_loader.py",+ "mootdx": "test_mootdx_loader.py",+ "mt5": "test_mt5_loader.py",+ "nobitex": "test_nobitex_loader.py",+ "okx": "test_okx_loader_bounded.py",+ "pykrx": "test_pykrx_loader.py",+ "qveris": "test_qveris_loader.py",+ "sina": "test_sina_loader.py",+ "stooq": "test_stooq_loader.py",+ "tencent": "test_tencent_loader.py",+ "tickerall": "test_tickerall_loader.py",+ "tiingo": "test_tiingo_loader.py",+ "tushare": "test_tushare_loader.py",+ "wallex": "test_wallex_loader.py",+ "yahoo": "test_yahoo_loader.py",+ "yfinance": "test_yfinance_crypto.py",+}+++def test_every_loader_has_a_canonical_contract_assertion():+ assert CONTRACT_SUITES.keys() == VALID_SOURCES - {"auto"}+ root = Path(__file__).parent+ for source, filename in CONTRACT_SUITES.items():+ tree = ast.parse((root / filename).read_text())+ assert any(+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "assert_loader_contract"+ for function in tree.body+ if isinstance(function, (ast.FunctionDef, ast.ClassDef))+ for node in ast.walk(function)+ ), source++[email protected]("fault", [None, "empty_frame", "schema", "datetime_index", "index_order", "numeric_columns", "nonfinite_values", "invalid_prices_or_volume", "ohlc_order"])+def test_offline_contract_agrees_with_health_lane(fault):+ frame = pd.DataFrame(+ {"open": [10., 11.], "high": [12., 13.], "low": [9., 10.], "close": [11., 12.], "volume": [0., 5.]},+ index=pd.date_range("2026-10-01", periods=2, tz="UTC"),+ )+ if fault == "empty_frame":+ frame = frame.iloc[:0]+ elif fault == "schema":+ frame = frame.drop(columns="volume")+ elif fault == "datetime_index":+ frame.index = [1, 2]+ elif fault == "index_order":+ frame = frame.iloc[::-1]+ elif fault == "numeric_columns":+ frame["open"] = ["10", "11"]+ elif fault == "nonfinite_values":+ frame.loc[frame.index[0], "close"] = np.nan+ elif fault == "invalid_prices_or_volume":+ frame.loc[frame.index[0], "volume"] = -1.+ elif fault == "ohlc_order":+ frame.loc[frame.index[0], "high"] = 1.+ errors = loader_contract_errors(frame)+ live = check_frame(frame, today=pd.Timestamp("2026-10-02").date())+ assert errors == ([] if fault is None else [fault])+ assert live.get("reason") == faultdiff --git a/agent/tests/test_pdf_protection_surfaces.py b/agent/tests/test_pdf_protection_surfaces.pynew file mode 100644index 000000000..611542b16--- /dev/null+++ b/agent/tests/test_pdf_protection_surfaces.py@@ -0,0 +1,125 @@+"""PDF protection survives real CLI and agent confirmation surfaces."""++from __future__ import annotations++import json++import pytest++from src.channels.targets import DeliveryTarget+from src.scheduled_research import proposals, service+from src.scheduled_research.models import ScheduledResearchJob+from src.scheduled_research.store import ScheduledResearchJobStore+from src.tools.scheduled_research_tool import ScheduledResearchTool+++def email_target(monkeypatch):+ target = DeliveryTarget("reports", "Reports", "email", "[email protected]")+ monkeypatch.setattr(service, "resolve_delivery_target", lambda _ref: target)+ monkeypatch.setattr("src.channels.targets.resolve_delivery_target", lambda _ref: target)+ return target+++def test_protected_agent_proposal_keeps_choice_through_confirmation(+ tmp_path, monkeypatch, email_target+):+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path))+ monkeypatch.setattr(service, "email_pdf_password_configured", lambda: True, raising=False)+ monkeypatch.setattr(proposals, "scheduler_status", lambda: {"executable": True})+ store = ScheduledResearchJobStore(tmp_path / "jobs.json")+ monkeypatch.setattr(proposals, "default_store", lambda: store)+ result = json.loads(ScheduledResearchTool().execute(+ action="propose_create",+ draft={+ "title": "Protected report",+ "source": {"kind": "prompt", "prompt": "Prepare a report"},+ "schedule": {"expression": "60000"},+ "end_at": None,+ "delivery": {"mode": "configured", "target_ref": "reports", "format": "pdf", "protect_pdf": True},+ },+ ))+ assert result["job"]["delivery"]["protect_pdf"] is True+ assert store.load() == {}+ committed = proposals.commit_proposal(result["proposal_id"])+ job = store.get(committed["committed_job_id"])+ assert job.protect_pdf is True+ assert service.public_job(job)["delivery"]["protect_pdf"] is True+ assert "pdf_password" not in json.dumps(job.to_dict())+++def test_agent_schema_exposes_pdf_protection_choice():+ properties = ScheduledResearchTool.parameters["properties"]["draft"]["properties"]["delivery"]["properties"]+ assert properties["protect_pdf"]["type"] == "boolean"+ assert "pdf_password" not in properties+++def test_cli_creates_protected_pdf_job(tmp_path, monkeypatch, capsys, email_target):+ from cli import _legacy++ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path))+ monkeypatch.setattr(service, "email_pdf_password_configured", lambda: True, raising=False)+ code = _legacy.main([+ "playbook", "create", "premarket-brief", "--delivery-target-ref", "reports",+ "--delivery-format", "pdf", "--protect-pdf", "--dry-run", "--json",+ ])+ assert code == 0+ payload = json.loads(capsys.readouterr().out)+ assert payload["protect_pdf"] is True+ assert payload["dry_run"] is True+ assert "pdf_password" not in payload++[email protected]("channel,format", [("telegram", "pdf"), ("email", "html"), (None, "pdf")])+def test_protection_cannot_be_serialized_for_incompatible_delivery(channel, format):+ job = ScheduledResearchJob(+ id="invalid", prompt="report", schedule="60000", next_run_at=1,+ delivery_channel=channel, delivery_format=format, protect_pdf=True,+ )+ with pytest.raises(ValueError, match="PDF email"):+ job.to_dict()+++def test_cli_protection_refuses_missing_password(monkeypatch, email_target):+ from cli.commands.research_playbook import build_job_from_playbook++ monkeypatch.setattr(service, "email_pdf_password_configured", lambda: False)+ job, error = build_job_from_playbook(+ "premarket-brief", delivery_target_ref="reports", delivery_format="pdf", protect_pdf=True+ )+ assert job is None+ assert "no PDF password" in error+++def test_removed_password_refuses_proposal_commit(tmp_path, monkeypatch, email_target):+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path))+ monkeypatch.setattr(service, "email_pdf_password_configured", lambda: True)+ monkeypatch.setattr(proposals, "scheduler_status", lambda: {"executable": True})+ store = ScheduledResearchJobStore(tmp_path / "jobs.json")+ monkeypatch.setattr(proposals, "default_store", lambda: store)+ draft = {+ "title": "Protected report", "source": {"kind": "prompt", "prompt": "report"},+ "schedule": {"expression": "60000"}, "end_at": None,+ "delivery": {"mode": "configured", "target_ref": "reports", "format": "pdf", "protect_pdf": True},+ }+ result = proposals.propose_create(draft)+ monkeypatch.setattr(service, "email_pdf_password_configured", lambda: False)+ with pytest.raises(proposals.ProposalError, match="no PDF password"):+ proposals.commit_proposal(result["proposal_id"])+ assert store.load() == {}++[email protected]("enabled,label", [(True, "开启"), (False, "关闭")])+def test_cli_confirmation_shows_protection_choice(enabled, label):+ from io import StringIO++ from rich.console import Console++ from cli.main import _render_scheduled_proposal++ output = StringIO()+ _render_scheduled_proposal(Console(file=output, color_system=None), {+ "operation": "create",+ "job": {"delivery": {"channel": "email", "format": "pdf", "protect_pdf": enabled}},+ })+ assert f"PDF 密码保护: {label}" in output.getvalue()diff --git a/agent/tests/test_sdk_connectors_kis.py b/agent/tests/test_sdk_connectors_kis.pyindex e13408f50..2a585fce9 100644--- a/agent/tests/test_sdk_connectors_kis.py+++ b/agent/tests/test_sdk_connectors_kis.py@@ -404,8 +404,8 @@ def test_kis_open_orders_dedupes_an_order_reported_by_two_venues(monkeypatch) ->assert len(result["executions"]) == 1-def test_kis_open_orders_survives_one_venue_rejecting_the_filter(monkeypatch) -> None:- """A venue the broker does not accept must not hide the other venues' fills."""+def test_kis_open_orders_reports_an_incomplete_venue_inquiry(monkeypatch) -> None:+ """Known rows cannot authorize reporting an incomplete inquiry as complete."""cfg = kis.KISConfig(app_key="k", app_secret="s", account_no="12345678", profile="paper")def fake_paginated(_cfg, _path, *, tr_id, params):@@ -414,6 +414,5 @@ def test_kis_open_orders_survives_one_venue_rejecting_the_filter(monkeypatch) ->return {"output1": [{"ord_dt": "20261006", "odno": "1", "pdno": "069500", "rmn_qty": "0"}]}monkeypatch.setattr(kis, "_get_paginated", fake_paginated)- result = kis.get_open_orders(cfg, include_executions=True)- assert [r["symbol"] for r in result["executions"]] == ["069500"]- assert len(result["venue_errors"]) == 2+ with pytest.raises(kis.KISAPIError, match="incomplete.*SOR.*NXT"):+ kis.get_open_orders(cfg, include_executions=True)diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 490a0bc0c..efdfbb03d 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -234,8 +234,8 @@"deliveryTargetPlaceholder_destination": "معرّف محادثة / مجموعة / مستخدم","deliveryTargetPlaceholder_slack_destination": "#قناة أو @مستخدم أو معرّف محادثة","deliveryTargetKind_slack_destination": "الوجهة",- "deliveryProtectPdf": "Protect PDF with password",- "deliveryProtectPdfUnavailable": "No PDF password is configured. Set one in Settings > Channels > Email to enable protection."+ "deliveryProtectPdf": "حماية ملف PDF بكلمة مرور",+ "deliveryProtectPdfUnavailable": "لم تُضبط كلمة مرور PDF. اضبطها في الإعدادات > القنوات > البريد الإلكتروني لتفعيل الحماية."},"reports": {"badge": "التقارير",@@ -689,8 +689,8 @@"help": "معرّف authserv-id لخادم الاستلام، مثل mx.google.com. يجب على مزود البريد إزالة ترويسات Authentication-Results الواردة المزوّرة التي تحمل هذا المعرّف. مطلوب عند تفعيل SPF أو DKIM؛ تركه فارغًا يرفض البريد الوارد."},"pdf_password": {- "label": "PDF report password",- "help": "Optional password for scheduled PDF reports that explicitly request protection. Stored server-side and never included in scheduled jobs or returned to the browser."+ "label": "كلمة مرور تقرير PDF",+ "help": "كلمة مرور اختيارية للتقارير المجدولة بصيغة PDF التي تطلب الحماية صراحةً. تُحفظ على الخادم ولا تُضمّن في المهام المجدولة أو تُعاد إلى المتصفح."}},"websocket": {diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.jsonindex f8467b839..28d7398cf 100644--- a/frontend/src/i18n/locales/de.json+++ b/frontend/src/i18n/locales/de.json@@ -239,8 +239,8 @@"deliveryTargetPlaceholder_destination": "Chat- / Gruppen- / Benutzer-ID","deliveryTargetPlaceholder_slack_destination": "#Kanal, @Benutzer oder Konversations-ID","deliveryTargetKind_slack_destination": "Ziel",- "deliveryProtectPdf": "Protect PDF with password",- "deliveryProtectPdfUnavailable": "No PDF password is configured. Set one in Settings > Channels > Email to enable protection."+ "deliveryProtectPdf": "PDF mit Passwort schützen",+ "deliveryProtectPdfUnavailable": "Es ist kein PDF-Passwort eingerichtet. Lege eines unter Einstellungen > Kanäle > E-Mail fest, um den Schutz zu aktivieren."},"reports": {"badge": "Berichte",@@ -694,8 +694,8 @@"help": "authserv-id des empfangenden Servers, z. B. mx.google.com. Der Mailanbieter muss gefälschte eingehende Authentication-Results-Header mit dieser ID entfernen. Bei SPF- oder DKIM-Prüfung erforderlich; leer wird eingehende Mail abgewiesen."},"pdf_password": {- "label": "PDF report password",- "help": "Optional password for scheduled PDF reports that explicitly request protection. Stored server-side and never included in scheduled jobs or returned to the browser."+ "label": "Passwort für PDF-Berichte",+ "help": "Optionales Passwort für geplante PDF-Berichte, deren Schutz ausdrücklich aktiviert wurde. Es wird auf dem Server gespeichert und weder in geplante Aufgaben aufgenommen noch an den Browser zurückgegeben."}},"websocket": {diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex 0e375cf4a..91a2e39c1 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -240,7 +240,7 @@"deliveryTargetPlaceholder_slack_destination": "#canal, @usuario o ID de conversación","deliveryTargetKind_slack_destination": "Destino","deliveryProtectPdf": "Proteger el PDF con contraseña",- "deliveryProtectPdfUnavailable": "No hay una contraseña PDF configurada. Configurala en Configuración > Canales > Email para habilitar la protección."+ "deliveryProtectPdfUnavailable": "No hay una contraseña de PDF configurada. Defínela en Ajustes > Canales > Correo electrónico para activar la protección."},"reports": {"badge": "Informes",@@ -694,8 +694,8 @@"help": "authserv-id del servidor receptor, p. ej. mx.google.com. Tu proveedor debe eliminar las cabeceras Authentication-Results falsificadas entrantes que usen este ID. Obligatorio al verificar SPF o DKIM; vacío rechaza el correo entrante."},"pdf_password": {- "label": "Contraseña de informes PDF",- "help": "Contraseña opcional para los informes PDF programados que soliciten protección. Se guarda en el servidor y nunca se incluye en los trabajos programados ni se devuelve al navegador."+ "label": "Contraseña del informe PDF",+ "help": "Contraseña opcional para informes PDF programados que soliciten protección expresamente. Se guarda en el servidor y nunca se incluye en las tareas programadas ni se devuelve al navegador."}},"websocket": {diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.jsonindex e179180ef..3f7f7b6c3 100644--- a/frontend/src/i18n/locales/id.json+++ b/frontend/src/i18n/locales/id.json@@ -239,8 +239,8 @@"deliveryTargetPlaceholder_destination": "ID chat / grup / pengguna","deliveryTargetPlaceholder_slack_destination": "#kanal, @pengguna, atau ID percakapan","deliveryTargetKind_slack_destination": "Tujuan",- "deliveryProtectPdf": "Protect PDF with password",- "deliveryProtectPdfUnavailable": "No PDF password is configured. Set one in Settings > Channels > Email to enable protection."+ "deliveryProtectPdf": "Lindungi PDF dengan kata sandi",+ "deliveryProtectPdfUnavailable": "Kata sandi PDF belum diatur. Atur di Pengaturan > Kanal > Email untuk mengaktifkan perlindungan."},"reports": {"badge": "Laporan",@@ -694,8 +694,8 @@"help": "authserv-id server penerima, misalnya mx.google.com. Penyedia email harus menghapus header Authentication-Results masuk palsu yang memakai ID ini. Wajib saat verifikasi SPF atau DKIM aktif; kosong menolak email masuk."},"pdf_password": {- "label": "PDF report password",- "help": "Optional password for scheduled PDF reports that explicitly request protection. Stored server-side and never included in scheduled jobs or returned to the browser."+ "label": "Kata sandi laporan PDF",+ "help": "Kata sandi opsional untuk laporan PDF terjadwal yang secara khusus meminta perlindungan. Disimpan di server dan tidak dimasukkan ke tugas terjadwal atau dikirim kembali ke browser."}},"websocket": {diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex 31a122e4a..ee40854eb 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -234,8 +234,8 @@"deliveryTargetPlaceholder_destination": "チャット / グループ / ユーザー ID","deliveryTargetPlaceholder_slack_destination": "#チャンネル、@ユーザー、会話 ID","deliveryTargetKind_slack_destination": "送信先",- "deliveryProtectPdf": "Protect PDF with password",- "deliveryProtectPdfUnavailable": "No PDF password is configured. Set one in Settings > Channels > Email to enable protection."+ "deliveryProtectPdf": "PDF をパスワードで保護",+ "deliveryProtectPdfUnavailable": "PDF のパスワードが未設定です。「設定 > チャネル > メール」で設定すると保護を有効にできます。"},"reports": {"badge": "レポート",@@ -689,8 +689,8 @@"help": "受信サーバーの authserv-id(例:mx.google.com)。メール提供者が、この ID を偽装した外部の Authentication-Results ヘッダーを削除する必要があります。SPF または DKIM 検証時は必須です。空欄では受信メールを拒否します。"},"pdf_password": {- "label": "PDF report password",- "help": "Optional password for scheduled PDF reports that explicitly request protection. Stored server-side and never included in scheduled jobs or returned to the browser."+ "label": "PDF レポートのパスワード",+ "help": "保護を明示的に指定した定期 PDF レポート用の任意のパスワードです。サーバー側で保存され、定期ジョブやブラウザーへの応答には含まれません。"}},"websocket": {diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex e94a8378d..3989fba0b 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -234,8 +234,8 @@"deliveryTargetPlaceholder_destination": "채팅 / 그룹 / 사용자 ID","deliveryTargetPlaceholder_slack_destination": "#채널, @사용자 또는 대화 ID","deliveryTargetKind_slack_destination": "대상",- "deliveryProtectPdf": "Protect PDF with password",- "deliveryProtectPdfUnavailable": "No PDF password is configured. Set one in Settings > Channels > Email to enable protection."+ "deliveryProtectPdf": "PDF 비밀번호 보호",+ "deliveryProtectPdfUnavailable": "PDF 비밀번호가 설정되지 않았습니다. 설정 > 채널 > 이메일에서 비밀번호를 설정하세요."},"reports": {"badge": "리포트",@@ -689,8 +689,8 @@"help": "수신 서버의 authserv-id(예: mx.google.com)입니다. 메일 제공자는 이 ID를 위조한 외부 Authentication-Results 헤더를 제거해야 합니다. SPF 또는 DKIM 검증을 사용하면 필수이며, 비워 두면 수신 메일이 거부됩니다."},"pdf_password": {- "label": "PDF report password",- "help": "Optional password for scheduled PDF reports that explicitly request protection. Stored server-side and never included in scheduled jobs or returned to the browser."+ "label": "PDF 보고서 비밀번호",+ "help": "보호를 명시적으로 요청한 예약 PDF 보고서에 사용하는 선택 사항입니다. 서버에만 저장되며 예약 작업이나 브라우저 응답에 포함되지 않습니다."}},"websocket": {diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.jsonindex 1ea784c57..755dea4b2 100644--- a/frontend/src/i18n/locales/pt-BR.json+++ b/frontend/src/i18n/locales/pt-BR.json@@ -239,8 +239,8 @@"deliveryTargetPlaceholder_destination": "chat / grupo / ID de usuário","deliveryTargetPlaceholder_slack_destination": "#canal, @usuário ou ID da conversa","deliveryTargetKind_slack_destination": "Destino",- "deliveryProtectPdf": "Protect PDF with password",- "deliveryProtectPdfUnavailable": "No PDF password is configured. Set one in Settings > Channels > Email to enable protection."+ "deliveryProtectPdf": "Proteger PDF com senha",+ "deliveryProtectPdfUnavailable": "Nenhuma senha de PDF foi configurada. Defina uma em Configurações > Canais > E-mail para ativar a proteção."},"reports": {"badge": "Relatórios",@@ -694,8 +694,8 @@"help": "authserv-id do servidor receptor, por exemplo mx.google.com. O provedor deve remover cabeçalhos Authentication-Results recebidos e forjados com esse ID. Obrigatório ao verificar SPF ou DKIM; vazio rejeita emails recebidos."},"pdf_password": {- "label": "PDF report password",- "help": "Optional password for scheduled PDF reports that explicitly request protection. Stored server-side and never included in scheduled jobs or returned to the browser."+ "label": "Senha do relatório PDF",+ "help": "Senha opcional para relatórios PDF agendados que solicitem proteção explicitamente. Armazenada no servidor e nunca incluída nas tarefas agendadas nem retornada ao navegador."}},"websocket": {diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 615dffcfc..6450a4d86 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -234,8 +234,8 @@"deliveryTargetPlaceholder_destination": "会话 / 群 / 用户 id","deliveryTargetPlaceholder_slack_destination": "#频道、@用户或会话 ID","deliveryTargetKind_slack_destination": "目标",- "deliveryProtectPdf": "Protect PDF with password",- "deliveryProtectPdfUnavailable": "No PDF password is configured. Set one in Settings > Channels > Email to enable protection."+ "deliveryProtectPdf": "为 PDF 设置密码保护",+ "deliveryProtectPdfUnavailable": "尚未配置 PDF 密码。请在“设置 > 通讯渠道 > 电子邮件”中设置后启用保护。"},"reports": {"badge": "报告",@@ -689,8 +689,8 @@"help": "收件服务器的 authserv-id,例如 mx.google.com。邮件服务商必须移除外部伪造且使用此 ID 的 Authentication-Results 邮件头。启用 SPF 或 DKIM 验证时必填;留空会拒收邮件。"},"pdf_password": {- "label": "PDF report password",- "help": "Optional password for scheduled PDF reports that explicitly request protection. Stored server-side and never included in scheduled jobs or returned to the browser."+ "label": "PDF 报告密码",+ "help": "可选密码,仅用于明确启用保护的定时 PDF 报告。保存在服务端,不写入定时任务,也不会回显到浏览器。"}},"websocket": {