"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: Longbridge SDK security hardening and data source integration
rootea89dd17d550
diff --git a/agent/api_server.py b/agent/api_server.pyindex 97220d11b..e284587d3 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -268,6 +268,8 @@ from src.api.live_routes import ( # noqa: F401, E402_live_broker_adapter,_build_live_runner,_drive_runner,+ _connector_verify_cache,+ _check_connector_status,)# --- Alpha Zoo ---diff --git a/agent/backtest/loaders/longbridge.py b/agent/backtest/loaders/longbridge.pyindex 334b35f4f..be3cc8acb 100644--- a/agent/backtest/loaders/longbridge.py+++ b/agent/backtest/loaders/longbridge.py@@ -36,6 +36,10 @@ from backtest.loaders.base import (validate_date_range,)from backtest.loaders.registry import register+from src.trading.connectors.longbridge.credentials import (+ LongbridgeCredentialError,+ resolve_longbridge_credentials,+)logger = logging.getLogger(__name__)@@ -194,8 +198,8 @@ def _normalize_frame(bars: list[Any]) -> pd.DataFrame:class LongbridgeLoader:"""Fetch US and HK equity bars from LongPort OpenAPI.- Requires the environment variables ``LONGBRIDGE_APP_KEY``,- ``LONGBRIDGE_APP_SECRET`` and ``LONGBRIDGE_ACCESS_TOKEN``.+ Resolves one atomic credential set from the ``LONGBRIDGE_*`` environment+ variables or the backward-compatible runtime file."""name = "longbridge"@@ -203,12 +207,34 @@ class LongbridgeLoader:requires_auth = Truedef __init__(self) -> None:- from src.config.accessor import get_env_config+ try:+ resolution = resolve_longbridge_credentials()+ except LongbridgeCredentialError as exc:+ self._credential_source = None+ self._credential_error = exc+ self._app_key = self._app_secret = self._access_token = ""+ return+ self._credential_source = resolution.source+ self._credential_error: LongbridgeCredentialError | None = None+ if resolution.credentials is None:+ if resolution.conflict_fields:+ code = "credentials_conflict"+ fields = resolution.conflict_fields+ else:+ code = (+ "credentials_missing"+ if resolution.source is None+ else "credentials_partial"+ )+ fields = resolution.missing_fields+ self._credential_error = LongbridgeCredentialError(code, fields)+ self._app_key = self._app_secret = self._access_token = ""+ return- cfg = get_env_config().data- self._app_key = cfg.longbridge_app_key- self._app_secret = cfg.longbridge_app_secret- self._access_token = cfg.longbridge_access_token+ credentials = resolution.credentials+ self._app_key = credentials.app_key+ self._app_secret = credentials.app_secret+ self._access_token = credentials.access_tokendef is_available(self) -> bool:"""Return True if the LongPort SDK is installed and credentials exist.@@ -278,6 +304,24 @@ class LongbridgeLoader:if not pending:return results+ credential_error = getattr(self, "_credential_error", None)+ if credential_error is not None:+ if credential_error.code == "credentials_missing":+ message = (+ "Longbridge credentials are not configured; missing fields: "+ + ", ".join(credential_error.fields)+ )+ elif credential_error.code == "credentials_partial":+ message = (+ "Longbridge credentials_partial; missing fields: "+ + ", ".join(credential_error.fields)+ )+ else:+ message = (+ "Longbridge credentials_conflict; differing fields: "+ + ", ".join(credential_error.fields)+ )+ raise NoAvailableSourceError(message) from Noneif not (self._app_key and self._app_secret and self._access_token):raise NoAvailableSourceError("Longbridge credentials are not configured; set "@@ -286,6 +330,7 @@ class LongbridgeLoader:)openapi = _require_longbridge()+ _init_error: str | None = Nonetry:cfg = openapi.Config(self._app_key, self._app_secret, self._access_token,@@ -293,20 +338,24 @@ class LongbridgeLoader:ctx = openapi.QuoteContext(cfg)except LongbridgeDependencyError:raise- except Exception as exc:- raise NoAvailableSourceError(- f"Cannot initialise LongPort SDK config: {exc}"- ) from exc+ except Exception:+ # Capture only stable text; do NOT raise inside the handler so+ # the original exception (which may contain secrets) cannot+ # leak into __context__.+ _init_error = "Longbridge SDK initialization failed."++ if _init_error is not None:+ raise NoAvailableSourceError(_init_error)period = _to_longport_period(interval)adjust_type = getattr(openapi, "AdjustType").NoAdjusttry:start = dt.date.fromisoformat(start_date)end = dt.date.fromisoformat(end_date)- except Exception as exc:+ except (TypeError, ValueError):raise NoAvailableSourceError(- f"Invalid date range [{start_date}, {end_date}]: {exc}"- ) from exc+ "Invalid Longbridge date range."+ ) from Nonewindows = _date_windows(start, end)@@ -314,6 +363,7 @@ class LongbridgeLoader:for code in pending:lp_symbol = _to_longport_symbol(code)all_bars: list[Any] = []+ _window_error: str | None = Nonefor w_start, w_end in windows:try:bars = ctx.history_candlesticks_by_date(@@ -324,11 +374,14 @@ class LongbridgeLoader:all_bars.extend(bars)elif bars is not None:all_bars.append(bars)- except Exception as exc:- raise NoAvailableSourceError(- "incomplete Longbridge history for "- f"{lp_symbol}: window {w_start}..{w_end} failed: {exc}"- ) from exc+ except Exception:+ _window_error = "Longbridge history request failed."+ break+ else:+ _window_error = None++ if _window_error is not None:+ raise NoAvailableSourceError(_window_error)if not all_bars:logger.warning(diff --git a/agent/src/api/live_routes.py b/agent/src/api/live_routes.pyindex 420dbbe3f..9b4d81c15 100644--- a/agent/src/api/live_routes.py+++ b/agent/src/api/live_routes.py@@ -24,7 +24,7 @@ import asyncioimport loggingimport sys as _sysimport time-from datetime import datetime+from datetime import datetime, timezonefrom typing import Any, Awaitable, Callable, Dict, List, Optionalfrom fastapi import Depends, FastAPI, HTTPException, Query@@ -98,6 +98,17 @@ class BrokerAuthState(BaseModel):broker: stroauth_token_present: bool = Field(..., description="Whether an OAuth token cache exists")is_live_broker: bool = Field(..., description="Whether this key is a recognized live broker")+ transport: Optional[str] = Field(None, description="Transport type (broker_sdk, remote_mcp, local_tws)")+ connection_state: Optional[str] = Field(None, description="Broker_sdk connection state (connected, not_configured, error)")+ profile_id: Optional[str] = Field(None, description="Verified broker_sdk profile id")+ configured: Optional[bool] = Field(None, description="Whether the selected SDK profile is configured")+ credential_source: Optional[str] = Field(None, description="Credential source label; never credential material")+ sdk_installed: Optional[bool] = Field(None, description="Whether the connector SDK is installed")+ environment_identity: Optional[str] = Field(None, description="How the account environment was identified")+ capabilities: Optional[List[str]] = Field(None, description="Capabilities declared by the verified profile")+ readonly: Optional[bool] = Field(None, description="Whether the verified profile is structurally read-only")+ last_checked_at: Optional[str] = Field(None, description="Timestamp of the latest connector verification")+ error_code: Optional[str] = Field(None, description="Stable redaction-safe connector error code")class MandateLimits(BaseModel):@@ -158,6 +169,145 @@ _runner_tasks: Dict[str, "asyncio.Task[Any]"] = {}_runner_factory: Optional[Any] = None+# ============================================================================+# Connector verify cache (bounded 15s, credential-free, fake-clock testable)+# ============================================================================++_CACHE_TTL_SECONDS = 15.0+++class _ConnectorVerifyCache:+ """A bounded, credential-free cache for connector verify results.++ Each entry stores only the status-level envelope returned by+ ``service.check_connection`` — stripped of any ``config`` sub-dict that+ might contain secret material. The cache is keyed by profile id and+ expires after ``_CACHE_TTL_SECONDS``. An explicit ``force=True`` bypass+ always hits the service.++ The ``_clock`` attribute is a callable returning ``time.time()`` and is+ monkeypatchable by tests for deterministic TTL assertions.+ """++ def __init__(self, ttl: float = _CACHE_TTL_SECONDS) -> None:+ self._ttl = ttl+ self._store: Dict[str, Dict[str, Any]] = {}+ self._clock = time.time++ def get(self, profile_id: str) -> Optional[Dict[str, Any]]:+ """Return a cached entry if fresh, else ``None``."""+ entry = self._store.get(profile_id)+ if entry is None:+ return None+ age = self._clock() - entry["_cached_at"]+ if age >= self._ttl:+ self._store.pop(profile_id, None)+ return None+ return dict(entry)++ def put(self, profile_id: str, payload: Dict[str, Any]) -> None:+ """Store a sanitized copy (no ``config`` key, no secrets)."""+ sanitized = {k: v for k, v in payload.items() if k != "config"}+ sanitized["_cached_at"] = self._clock()+ self._store[profile_id] = sanitized++ def clear(self) -> None:+ """Drop all entries (used in test setup)."""+ self._store.clear()+++_connector_verify_cache = _ConnectorVerifyCache()+++_CREDENTIAL_SOURCES = frozenset({"environment", "runtime_file"})+_ENVIRONMENT_IDENTITIES = frozenset(+ {+ "config_declared",+ "config_declared_live",+ "config-declared",+ "header_flag+uid_pin",+ "host_separated",+ "read_only_no_runtime_discriminator",+ "simulated_locally",+ "trd_env_acc_list",+ }+)+_CONNECTION_STATES = frozenset({"connected", "error", "not_configured", "ready"})+_ERROR_CODES = frozenset(+ {+ "authentication_failed",+ "broker_error",+ "credentials_conflict",+ "credentials_missing",+ "credentials_partial",+ "network_unreachable",+ "sdk_missing",+ }+)+++def _closed_vocabulary(value: Any, allowed: frozenset[str]) -> Optional[str]:+ """Return a known diagnostic label, never arbitrary report-controlled text."""+ return value if type(value) is str and value in allowed else None+++def _canonical_utc_timestamp(value: Any) -> Optional[str]:+ """Validate an ISO-8601 timestamp and emit one canonical UTC representation."""+ if type(value) is not str:+ return None+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ if parsed.tzinfo is None or parsed.utcoffset() is None:+ return None+ return parsed.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")+ except (OverflowError, ValueError):+ return None+++def _check_connector_status(profile_id: str, force: bool = False) -> Dict[str, Any]:+ """Resolve a connector profile and return its verify envelope.++ Uses the bounded cache when ``force`` is ``False`` and the entry is fresh.+ Known broker/SDK exceptions are normalised into a stable envelope; raw+ exception objects and credential-bearing strings never escape.+ """+ if not force:+ cached = _connector_verify_cache.get(profile_id)+ if cached is not None:+ return cached++ from src.trading.service import check_connection++ try:+ report = check_connection(profile_id)+ except ValueError:+ report = {+ "status": "error",+ "configured": False,+ "connection_state": "error",+ "error": f"unknown connector profile: {profile_id}",+ "connector": None,+ "transport": None,+ "profile_id": profile_id,+ }+ except Exception as exc: # noqa: BLE001 - verify must never raise+ report = {+ "status": "error",+ "configured": False,+ "connection_state": "error",+ "error": f"unexpected error: {type(exc).__name__}",+ "connector": None,+ "transport": None,+ "profile_id": profile_id,+ }++ # Sanitize: strip any ``config`` sub-dict that may hold secrets+ sanitized = {k: v for k, v in report.items() if k != "config"}++ _connector_verify_cache.put(profile_id, sanitized)+ return sanitized++# ============================================================================# Exception (live-exclusive)# ============================================================================@@ -272,12 +422,31 @@ def _fetch_broker_ceilings(broker: str) -> Optional[Dict[str, Any]]:def _known_live_brokers() -> List[str]:- """Return the recognized live-broker keys (SPEC §7.2)."""+ """Return the recognized live-broker keys (SPEC §7.2) — OAuth/mandate path only."""from src.config.schema import LIVE_BROKER_SERVER_KEYSreturn sorted(LIVE_BROKER_SERVER_KEYS)+def _live_broker_sdk_connectors() -> List[str]:+ """Return the recognized broker_sdk connector keys from the profile registry.++ These are direct-SDK connectors (e.g. Longbridge) that appear in+ ``/live/status`` but are NOT OAuth/mandate live brokers. They are+ discovered from the profile registry rather than a hard-coded list.+ """+ from src.trading.profiles import list_profiles++ seen: set[str] = set()+ result: list[str] = []+ for profile in list_profiles():+ if profile.environment == "live" and profile.transport == "broker_sdk":+ if profile.connector not in seen:+ seen.add(profile.connector)+ result.append(profile.connector)+ return sorted(result)++def _oauth_token_present(broker: str) -> bool:"""Return whether an OAuth token cache exists for a broker (C2 auth state)."""try:@@ -552,27 +721,166 @@ def register_live_routes(@app.get("/live/status", response_model=LiveStatusResponse, dependencies=[Depends(require_auth)])async def live_status_endpoint(broker: Optional[str] = Query(None, max_length=64)):- """Return live-channel status: auth, active mandate, runner liveness, halt (C2)."""+ """Return live-channel status: auth, active mandate, runner liveness, halt (C2).++ Includes both OAuth/mandate live brokers (robinhood, ibkr) and+ broker_sdk connectors (longbridge, etc.) discovered from the profile+ registry.+ """from src.live.halt import halt_flag_set+ all_brokers = sorted(set(_known_live_brokers()) | set(_live_broker_sdk_connectors()))+if broker is not None:target = broker.strip().lower()if not target:raise HTTPException(status_code=400, detail="broker must not be blank")+ if target not in all_brokers:+ raise HTTPException(status_code=404, detail=f"unknown broker: {target}")brokers = [target]else:- brokers = _known_live_brokers()+ brokers = all_brokersknown = set(_known_live_brokers())h = _host()statuses: List[LiveBrokerStatus] = []for key in brokers:+ # Determine transport type and select the live broker_sdk profile from+ # the registry. Do not derive a profile id from the connector name.+ transport: Optional[str] = None+ selected_profile = None+ try:+ from src.trading.profiles import list_profiles++ live_profiles = [+ profile+ for profile in list_profiles()+ if profile.connector == key and profile.environment == "live"+ ]+ if live_profiles:+ transport = live_profiles[0].transport+ declared_readonly_sdk_profiles = [+ profile+ for profile in live_profiles+ if profile.transport == "broker_sdk"+ and type(profile.id) is str+ and type(profile.readonly) is bool+ and profile.readonly is True+ ]+ suffixed_readonly_profiles = [+ profile+ for profile in declared_readonly_sdk_profiles+ if profile.id.endswith("-readonly")+ ]+ # Registry readonly=True is mandatory even when an id ends in+ # ``-readonly``. Prefer one canonical suffixed profile; if none+ # exists, accept one unique declared-readonly profile. Any+ # ambiguity fails closed without making a connector request.+ if len(suffixed_readonly_profiles) == 1:+ selected_profile = suffixed_readonly_profiles[0]+ elif not suffixed_readonly_profiles and len(declared_readonly_sdk_profiles) == 1:+ selected_profile = declared_readonly_sdk_profiles[0]+ except Exception: # noqa: BLE001 - status must never raise+ pass++ # Explicit response allowlist. Unknown or mismatched verify reports+ # remain fail-closed and cannot supply permission metadata.+ sdk_metadata: Dict[str, Any] = {}+ if selected_profile is not None:+ try:+ verify_report = h._check_connector_status(selected_profile.id)+ if verify_report.get("profile_id") == selected_profile.id:+ def _normalize_capabilities(value: Any) -> Optional[tuple[str, ...]]:+ if not isinstance(value, (list, tuple)) or not value:+ return None+ if not all(+ type(item) is str and bool(item.strip()) for item in value+ ):+ return None+ return tuple(value)++ # Permissions are trusted registry declarations, never+ # reflected from a connector report. The exact profile-id+ # match above binds the report to this registry profile.+ registry_capabilities = _normalize_capabilities(+ selected_profile.capabilities+ )+ registry_readonly = (+ selected_profile.readonly+ if type(selected_profile.readonly) is bool+ else None+ )+ if registry_readonly is True and (+ registry_capabilities is None+ or any(+ not (+ capability.endswith(".read")+ or ".read." in capability+ )+ for capability in registry_capabilities+ )+ ):+ registry_readonly = None++ sdk_report = verify_report.get("sdk")+ sdk_installed = verify_report.get("sdk_installed")+ if not isinstance(sdk_installed, bool) and isinstance(sdk_report, dict):+ sdk_installed = sdk_report.get("installed")++ sdk_metadata = {+ "profile_id": selected_profile.id,+ "configured": verify_report.get("configured")+ if isinstance(verify_report.get("configured"), bool)+ else None,+ "credential_source": _closed_vocabulary(+ verify_report.get("credential_source"),+ _CREDENTIAL_SOURCES,+ ),+ "sdk_installed": sdk_installed+ if isinstance(sdk_installed, bool)+ else None,+ "environment_identity": next(+ (+ normalized+ for value in (+ verify_report.get("environment_identity"),+ verify_report.get("paper_guard"),+ )+ if (+ normalized := _closed_vocabulary(+ value, _ENVIRONMENT_IDENTITIES+ )+ )+ is not None+ ),+ None,+ ),+ "capabilities": list(registry_capabilities)+ if registry_capabilities is not None+ else None,+ "readonly": registry_readonly,+ "last_checked_at": _canonical_utc_timestamp(+ verify_report.get("last_checked_at")+ ),+ "error_code": _closed_vocabulary(+ verify_report.get("error_code"), _ERROR_CODES+ ),+ "connection_state": _closed_vocabulary(+ verify_report.get("connection_state"),+ _CONNECTION_STATES,+ ),+ }+ except Exception: # noqa: BLE001 - status must never raise+ sdk_metadata = {}+statuses.append(LiveBrokerStatus(auth=BrokerAuthState(broker=key,oauth_token_present=_oauth_token_present(key),is_live_broker=key in known,+ transport=transport,+ **sdk_metadata,),mandate=h._active_mandate_state(key),runner=_runner_liveness_state(key),@@ -610,6 +918,46 @@ def register_live_routes(),}+ @app.post("/live/connectors/{profile_id}/verify", dependencies=[Depends(require_auth)])+ async def verify_connector_endpoint(+ profile_id: str,+ force: bool = Query(False, description="Bypass the bounded status cache"),+ ):+ """Read-only idempotent verify for a connector profile (transport-neutral).++ Never requires a mandate. Never writes or mutates broker state.+ Longbridge and other broker_sdk profiles use this endpoint for a+ credential-free connectivity check. The result is cached for at most+ 15 seconds to avoid hammering the SDK; ``force=true`` bypasses the cache.+ """+ h = _host()++ # Validate the profile exists and is a live broker_sdk connector+ try:+ from src.trading.profiles import profile_by_id+ profile = profile_by_id(profile_id)+ except ValueError:+ raise HTTPException(status_code=404, detail=f"unknown connector profile: {profile_id}")++ if profile.environment != "live":+ raise HTTPException(+ status_code=400,+ detail=f"connector profile '{profile_id}' is not a live profile",+ )++ if profile.transport != "broker_sdk":+ raise HTTPException(+ status_code=400,+ detail=(+ f"connector profile '{profile_id}' uses transport "+ f"'{profile.transport}', not broker_sdk; verify is only "+ "supported for direct-SDK profiles"+ ),+ )++ report = h._check_connector_status(profile_id, force=force)+ return report+@app.post("/live/runner/start", dependencies=[Depends(require_auth)])async def start_runner_endpoint(payload: LiveRunnerControlRequest):"""Start the persistent live runner for a broker (SPEC §7.5)."""diff --git a/agent/src/tools/market_data_tool.py b/agent/src/tools/market_data_tool.pyindex 4c74a5e90..624e2c120 100644--- a/agent/src/tools/market_data_tool.py+++ b/agent/src/tools/market_data_tool.py@@ -37,6 +37,7 @@ class MarketDataTool(BaseTool):"type": "string","enum": ["auto",+ "longbridge","yfinance","yahoo","okx",@@ -56,6 +57,8 @@ class MarketDataTool(BaseTool):],"description": ("Data source. 'auto' detects from symbol format with fallback. "+ "Use 'longbridge' explicitly for US/HK OHLCV through the "+ "Longbridge OpenAPI (requires Longbridge credentials). ""Free, no key: yfinance/yahoo (US/HK equities), okx/ccxt ""(crypto), baostock/tencent/eastmoney/sina/akshare/mootdx ""(China A-shares), stooq (global EOD). Key-gated REST: tushare "diff --git a/agent/src/trading/connectors/longbridge/sdk.py b/agent/src/trading/connectors/longbridge/sdk.pyindex 6c83b69b0..60ffdb460 100644--- a/agent/src/trading/connectors/longbridge/sdk.py+++ b/agent/src/trading/connectors/longbridge/sdk.py@@ -18,13 +18,18 @@ environment.from __future__ import annotationsimport json+from datetime import datetime, timezonefrom decimal import Decimal-from dataclasses import asdict, dataclass+from dataclasses import asdict, dataclass, fieldfrom pathlib import Pathfrom types import ModuleTypefrom typing import Any, Mappingfrom src.config.paths import get_runtime_root+from src.trading.connectors.longbridge.credentials import (+ LongbridgeCredentialError,+ resolve_longbridge_credentials,+)CONFIG_FILENAME = "longbridge.json"@@ -64,13 +69,17 @@ class LongbridgeConfig:readonly: Always true for this layer; order methods are not exposed."""- app_key: str = ""- app_secret: str = ""- access_token: str = ""+ app_key: str = field(default="", repr=False)+ app_secret: str = field(default="", repr=False)+ access_token: str = field(default="", repr=False)profile: str = "paper"region: str = "global"timeout: float = 15.0readonly: bool = True+ _credential_source: str | None = field(default=None, repr=False, compare=False)+ _credential_error: LongbridgeCredentialError | None = field(+ default=None, repr=False, compare=False+ )@classmethoddef from_mapping(cls, data: Mapping[str, Any] | None = None) -> "LongbridgeConfig":@@ -90,6 +99,8 @@ class LongbridgeConfig:region=region,timeout=float(payload.get("timeout") or 15.0),readonly=bool(payload.get("readonly", True)),+ _credential_source=payload.get("_credential_source"),+ _credential_error=payload.get("_credential_error"),)def with_overrides(@@ -101,18 +112,23 @@ class LongbridgeConfig:profile: str | None = None,region: str | None = None,) -> "LongbridgeConfig":- """Return a copy with CLI/tool overrides applied."""- payload = asdict(self)- if app_key is not None:- payload["app_key"] = app_key- if app_secret is not None:- payload["app_secret"] = app_secret- if access_token is not None:- payload["access_token"] = access_token- if profile is not None:- payload["profile"] = profile- if region is not None:- payload["region"] = region+ """Return a copy with safe profile/region overlays applied.++ Credential arguments remain in the public signature for compatibility,+ but are ignored so callers cannot bypass atomic source resolution.+ """+ del app_key, app_secret, access_token+ payload = {+ "app_key": self.app_key,+ "app_secret": self.app_secret,+ "access_token": self.access_token,+ "profile": profile if profile is not None else self.profile,+ "region": region if region is not None else self.region,+ "timeout": self.timeout,+ "readonly": self.readonly,+ "_credential_source": self._credential_source,+ "_credential_error": self._credential_error,+ }return LongbridgeConfig.from_mapping(payload)@property@@ -121,30 +137,38 @@ class LongbridgeConfig:return PROFILE_ENVIRONMENTS.get(self.profile, "paper")-_OVERRIDE_KEYS = ("app_key", "app_secret", "access_token", "profile", "region")+_OVERLAY_KEYS = ("profile", "region")def build_config(profile_config: Mapping[str, Any] | None = None, overrides: Mapping[str, Any] | None = None) -> "LongbridgeConfig":- """Resolve the effective config: saved file ← profile defaults ← CLI overrides.+ """Resolve credentials atomically, then apply profile and region overlays.- Credentials (``app_key`` / ``app_secret`` / ``access_token``) come from the- saved ``~/.vibe-trading/longbridge.json``; the selected connector profile- supplies the ``profile`` / ``region`` intent; CLI/tool overrides win last.-- Args:- profile_config: The connector profile's ``config`` dict.- overrides: Per-call overrides (only known config keys are applied).-- Returns:- A normalized :class:`LongbridgeConfig`.+ The public return type and call signature are unchanged. Credential source+ and field-only resolution errors are tracked internally for ``check_status``.+ Credential-like profile/override values are ignored so callers cannot mix+ or bypass the shared resolver. Safety-critical profile identity comes only+ from the selected built-in profile/per-call overlay, never a credential file."""- base = asdict(load_config())- for key, value in dict(profile_config or {}).items():- if value is not None:- base[key] = value- cfg = LongbridgeConfig.from_mapping(base)- clean = {k: v for k, v in dict(overrides or {}).items() if k in _OVERRIDE_KEYS and v not in (None, "")}- return cfg.with_overrides(**clean) if clean else cfg+ resolution_error: LongbridgeCredentialError | None = None+ try:+ resolution = resolve_longbridge_credentials()+ except LongbridgeCredentialError as exc:+ resolution = None+ resolution_error = exc++ base: dict[str, Any] = {}+ if resolution is not None and resolution.credentials is not None:+ base.update(asdict(resolution.credentials))+ for payload in (profile_config, overrides):+ for key, value in dict(payload or {}).items():+ if key in _OVERLAY_KEYS and value not in (None, ""):+ base[key] = value++ base["_credential_source"] = resolution.source if resolution is not None else None+ base["_credential_error"] = (+ _credential_error(resolution) if resolution is not None else resolution_error+ )+ return LongbridgeConfig.from_mapping(base)def config_path() -> Path:@@ -153,21 +177,30 @@ def config_path() -> Path:def load_config() -> LongbridgeConfig:- """Load Longbridge settings from ``~/.vibe-trading/longbridge.json``."""+ """Load the legacy runtime-file settings without exposing parse details."""path = config_path()if not path.exists():return LongbridgeConfig()try:return LongbridgeConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))- except (OSError, ValueError, json.JSONDecodeError) as exc:- raise LongbridgeConfigError(f"invalid Longbridge config at {path}: {exc}") from exc+ except (OSError, UnicodeError, ValueError, json.JSONDecodeError) as exc:+ raise LongbridgeConfigError("invalid Longbridge runtime config") from excdef save_config(config: LongbridgeConfig) -> Path:- """Persist Longbridge settings with owner-only permissions."""+ """Persist public Longbridge settings with owner-only permissions."""path = config_path()path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(json.dumps(asdict(config), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ payload = {+ "app_key": config.app_key,+ "app_secret": config.app_secret,+ "access_token": config.access_token,+ "profile": config.profile,+ "region": config.region,+ "timeout": config.timeout,+ "readonly": config.readonly,+ }+ path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")try:path.chmod(0o600)except OSError:@@ -185,44 +218,109 @@ def longbridge_available() -> bool:def check_status(config: LongbridgeConfig | None = None) -> dict[str, Any]:- """Check SDK readiness and config completeness without mutating broker state."""- cfg = config or load_config()+ """Check read-only readiness with stable, redaction-safe diagnostics."""+ cfg = config or build_config()+ credential_error = cfg._credential_error+ credential_source = cfg._credential_source+ configured = credential_error is None and not _missing_fields(cfg)+ installed = longbridge_available()report: dict[str, Any] = {"status": "ok",+ "configured": configured,+ "credential_source": credential_source,+ "connection_state": "connected",+ "error_code": None,+ "error": None,"config": _public_config(cfg),- "sdk": {"package": "longbridge", "installed": longbridge_available()},+ "sdk": {"package": "longbridge", "installed": installed},"paper_guard": "config_declared",}- missing = _missing_fields(cfg)- if missing:- report["status"] = "error"- report["error"] = f"Longbridge connector not configured: missing {', '.join(missing)}."- return report+ if credential_error is None and not configured:+ credential_error = LongbridgeCredentialError(+ "credentials_missing", tuple(_missing_fields(cfg))+ )+ if credential_error is not None:+ return _status_error(+ report,+ credential_error.code,+ _credential_error_message(credential_error),+ )- if not report["sdk"]["installed"]:- report["status"] = "error"- report["error"] = "Optional dependency missing: install with `pip install longbridge`."- return report+ if not installed:+ return _status_error(+ report,+ "sdk_missing",+ "Optional dependency missing: install with `pip install longbridge`.",+ )try:snapshot = get_account_snapshot(cfg)- except Exception as exc: # noqa: BLE001 - health endpoint reports cleanly- report["status"] = "error"- report["error"] = str(exc)- return report+ except Exception as exc: # noqa: BLE001 - health endpoint reports safe codes+ code = _connection_error_code(exc)+ return _status_error(report, code, _connection_error_message(code))report["account"] = {"profile": cfg.profile,"region": cfg.region,"balances_currency": [row.get("currency") for row in snapshot.get("balances", [])],}+ report["last_checked_at"] = datetime.now(timezone.utc).isoformat()+ return report+++def _credential_error(resolution: Any) -> LongbridgeCredentialError | None:+ if resolution.credentials is not None:+ return None+ if resolution.conflict_fields:+ return LongbridgeCredentialError(+ "credentials_conflict", resolution.conflict_fields+ )+ code = "credentials_missing" if resolution.source is None else "credentials_partial"+ return LongbridgeCredentialError(code, resolution.missing_fields)+++def _credential_error_message(error: LongbridgeCredentialError) -> str:+ fields = ", ".join(error.fields)+ if error.code == "credentials_conflict":+ return f"Longbridge credential sources conflict for fields: {fields}."+ if error.code == "credentials_partial":+ return f"Longbridge credentials are partial; missing fields: {fields}."+ return f"Longbridge connector not configured: missing {fields}."+++def _status_error(report: dict[str, Any], code: str, message: str) -> dict[str, Any]:+ report.update(+ status="error",+ connection_state=(+ "not_configured" if code == "credentials_missing" else "error"+ ),+ error_code=code,+ error=message,+ )return report+def _connection_error_code(exc: Exception) -> str:+ if isinstance(exc, (ConnectionError, TimeoutError, OSError)):+ return "network_unreachable"+ text = type(exc).__name__.lower() + " " + str(exc).lower()+ if any(token in text for token in ("auth", "token", "permission", "unauthorized")):+ return "authentication_failed"+ return "broker_error"+++def _connection_error_message(code: str) -> str:+ return {+ "authentication_failed": "Longbridge authentication failed.",+ "network_unreachable": "Longbridge network is unreachable.",+ "broker_error": "Longbridge broker request failed.",+ }[code]++def get_account_snapshot(config: LongbridgeConfig | None = None) -> dict[str, Any]:"""Fetch account balances for the configured account."""- cfg = config or load_config()+ cfg = config or build_config()trade = _trade_context(cfg)balances = _call(trade, "account_balance")rows = [_balance_to_dict(item) for item in _as_iter(balances)]@@ -236,7 +334,7 @@ def get_account_snapshot(config: LongbridgeConfig | None = None) -> dict[str, Andef get_positions(config: LongbridgeConfig | None = None) -> dict[str, Any]:"""Fetch current stock positions for the configured account."""- cfg = config or load_config()+ cfg = config or build_config()trade = _trade_context(cfg)response = _call(trade, "stock_positions")rows = [_position_to_dict(item) for item in _iter_positions(response)]@@ -275,7 +373,7 @@ def get_open_orders(config: LongbridgeConfig | None = None, *, include_executionfilled/cancelled). We filter to non-terminal statuses so ``open_orders``means the same thing here as in the other connectors."""- cfg = config or load_config()+ cfg = config or build_config()trade = _trade_context(cfg)orders = _call(trade, "today_orders")mapped = [_order_to_dict(item) for item in _as_iter(orders)]@@ -293,7 +391,7 @@ def get_open_orders(config: LongbridgeConfig | None = None, *, include_executiondef get_quote(symbol: str, *, config: LongbridgeConfig | None = None, **_: Any) -> dict[str, Any]:"""Fetch a quote snapshot for ``symbol`` (top-of-book bid/ask via depth)."""- cfg = config or load_config()+ cfg = config or build_config()quote_ctx = _quote_context(cfg)clean = symbol.strip().upper()quotes = _call(quote_ctx, "quote", [clean])@@ -317,7 +415,7 @@ def get_historical_bars(**_: Any,) -> dict[str, Any]:"""Fetch historical OHLCV candlesticks for ``symbol`` (``period`` canonical)."""- cfg = config or load_config()+ cfg = config or build_config()quote_ctx = _quote_context(cfg)clean = symbol.strip().upper()period_enum, adjust_enum = _candlestick_enums(period)@@ -554,12 +652,27 @@ def _build_config(cfg: LongbridgeConfig):return config_cls.from_apikey(cfg.app_key, cfg.app_secret, cfg.access_token)+def _require_resolved_config(cfg: LongbridgeConfig) -> None:+ error = cfg._credential_error+ if error is not None:+ raise LongbridgeConfigError(_credential_error_message(error)) from error+ missing = _missing_fields(cfg)+ if missing:+ raise LongbridgeConfigError(+ _credential_error_message(+ LongbridgeCredentialError("credentials_missing", tuple(missing))+ )+ )++def _trade_context(cfg: LongbridgeConfig):+ _require_resolved_config(cfg)openapi = _require_openapi()return getattr(openapi, "TradeContext")(_build_config(cfg))def _quote_context(cfg: LongbridgeConfig):+ _require_resolved_config(cfg)openapi = _require_openapi()return getattr(openapi, "QuoteContext")(_build_config(cfg))@@ -599,7 +712,15 @@ def _missing_fields(cfg: LongbridgeConfig) -> list[str]:def _public_config(cfg: LongbridgeConfig) -> dict[str, Any]:"""Config snapshot with secrets redacted."""- data = asdict(cfg)+ data = {+ "app_key": cfg.app_key,+ "app_secret": cfg.app_secret,+ "access_token": cfg.access_token,+ "profile": cfg.profile,+ "region": cfg.region,+ "timeout": cfg.timeout,+ "readonly": cfg.readonly,+ }for secret in ("app_secret", "access_token"):if data.get(secret):data[secret] = "***redacted***"diff --git a/agent/tests/test_longbridge_loader.py b/agent/tests/test_longbridge_loader.pyindex e60848712..d192b24a7 100644--- a/agent/tests/test_longbridge_loader.py+++ b/agent/tests/test_longbridge_loader.py@@ -3,6 +3,7 @@from __future__ import annotationsimport datetime as dt+import jsonfrom types import SimpleNamespaceimport pandas as pd@@ -10,6 +11,7 @@ import pytestfrom backtest.loaders import longbridge as loader_modfrom backtest.loaders.base import NoAvailableSourceError+from src.trading.connectors.longbridge import credentials as lb_credentialsdef test_wide_date_range_never_truncates_silently() -> None:@@ -50,23 +52,43 @@ def test_normalize_frame_converts_intraday_timestamps_to_naive_utc() -> None:def test_is_available_does_not_make_a_market_data_request(- monkeypatch: pytest.MonkeyPatch,+ monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:monkeypatch.setenv("LONGBRIDGE_APP_KEY", "key")monkeypatch.setenv("LONGBRIDGE_APP_SECRET", "secret")monkeypatch.setenv("LONGBRIDGE_ACCESS_TOKEN", "token")+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)fake_openapi = SimpleNamespace()monkeypatch.setattr(loader_mod, "_require_longbridge", lambda: fake_openapi)assert loader_mod.LongbridgeLoader().is_available() is True+def test_is_available_contains_secret_bearing_sdk_exception(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ monkeypatch.setenv("LONGBRIDGE_APP_KEY", "availability-key")+ monkeypatch.setenv("LONGBRIDGE_APP_SECRET", "availability-secret")+ monkeypatch.setenv("LONGBRIDGE_ACCESS_TOKEN", "availability-token")+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(+ loader_mod,+ "_require_longbridge",+ lambda: (_ for _ in ()).throw(+ RuntimeError("SDK failure with access_token=availability-token")+ ),+ )++ assert loader_mod.LongbridgeLoader().is_available() is False++def test_fetch_rejects_missing_credentials_before_sdk_initialization(- monkeypatch: pytest.MonkeyPatch,+ monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:monkeypatch.delenv("LONGBRIDGE_APP_KEY", raising=False)monkeypatch.delenv("LONGBRIDGE_APP_SECRET", raising=False)monkeypatch.delenv("LONGBRIDGE_ACCESS_TOKEN", raising=False)+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)monkeypatch.setattr(loader_mod,"_require_longbridge",@@ -79,6 +101,88 @@ def test_fetch_rejects_missing_credentials_before_sdk_initialization()+def test_loader_partial_environment_with_complete_file_fails_before_sdk(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ secrets = {+ "environment": "loader-partial-environment-key-21ac",+ "file_key": "loader-complete-file-key-32bd",+ "file_secret": "loader-complete-file-secret-43ce",+ "file_token": "loader-complete-file-token-54df",+ }+ monkeypatch.setenv("LONGBRIDGE_APP_KEY", secrets["environment"])+ monkeypatch.delenv("LONGBRIDGE_APP_SECRET", raising=False)+ monkeypatch.delenv("LONGBRIDGE_ACCESS_TOKEN", raising=False)+ (tmp_path / "longbridge.json").write_text(+ json.dumps(+ {+ "app_key": secrets["file_key"],+ "app_secret": secrets["file_secret"],+ "access_token": secrets["file_token"],+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(+ loader_mod,+ "_require_longbridge",+ lambda: (_ for _ in ()).throw(AssertionError("SDK must not initialize")),+ )++ loader = loader_mod.LongbridgeLoader()+ assert loader.is_available() is False+ with pytest.raises(NoAvailableSourceError) as exc_info:+ loader.fetch(["AAPL"], "2026-01-01", "2026-01-02")++ diagnostic = str(exc_info.value)+ assert "credentials_partial" in diagnostic+ assert "app_secret" in diagnostic and "access_token" in diagnostic+ assert all(value not in diagnostic for value in secrets.values())+ assert exc_info.value.__cause__ is None+ assert exc_info.value.__context__ is None+++def test_loader_differing_complete_sources_fail_before_sdk(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ environment = {+ "app_key": "loader-conflict-environment-key-65e0",+ "app_secret": "loader-conflict-environment-secret-76f1",+ "access_token": "loader-conflict-environment-token-8702",+ }+ runtime_file = {+ "app_key": "loader-conflict-file-key-9813",+ "app_secret": "loader-conflict-file-secret-a924",+ "access_token": "loader-conflict-file-token-ba35",+ }+ monkeypatch.setenv("LONGBRIDGE_APP_KEY", environment["app_key"])+ monkeypatch.setenv("LONGBRIDGE_APP_SECRET", environment["app_secret"])+ monkeypatch.setenv("LONGBRIDGE_ACCESS_TOKEN", environment["access_token"])+ (tmp_path / "longbridge.json").write_text(json.dumps(runtime_file), encoding="utf-8")+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(+ loader_mod,+ "_require_longbridge",+ lambda: (_ for _ in ()).throw(AssertionError("SDK must not initialize")),+ )++ loader = loader_mod.LongbridgeLoader()+ assert loader.is_available() is False+ with pytest.raises(NoAvailableSourceError) as exc_info:+ loader.fetch(["AAPL"], "2026-01-01", "2026-01-02")++ diagnostic = str(exc_info.value)+ assert "credentials_conflict" in diagnostic+ assert all(field in diagnostic for field in ("app_key", "app_secret", "access_token"))+ assert all(+ value not in diagnostic+ for value in (*environment.values(), *runtime_file.values())+ )+ assert exc_info.value.__cause__ is None+ assert exc_info.value.__context__ is None++def _configured_loader() -> loader_mod.LongbridgeLoader:loader = loader_mod.LongbridgeLoader.__new__(loader_mod.LongbridgeLoader)loader._app_key = "key"@@ -152,13 +256,18 @@ def test_fetch_combines_all_windows_and_caches_complete_frame(def test_fetch_rejects_partial_history_when_a_window_fails(monkeypatch: pytest.MonkeyPatch,) -> None:+ secret = "sdk-window-exception-credential-cb46"++ class SecretBearingSdkError(RuntimeError):+ pass+class FakeQuoteContext:def __init__(self, config: object) -> None:passdef history_candlesticks_by_date(self, *args: object, **kwargs: object):if kwargs["start"] == dt.date(2026, 6, 30):- raise RuntimeError("quota exhausted")+ raise SecretBearingSdkError(f"quota failed with credential={secret}")return [SimpleNamespace(timestamp=pd.Timestamp(kwargs["start"]),@@ -184,7 +293,118 @@ def test_fetch_rejects_partial_history_when_a_window_fails(lambda **kwargs: (_ for _ in ()).throw(AssertionError("must not cache")),)- with pytest.raises(NoAvailableSourceError, match="incomplete Longbridge history"):+ with pytest.raises(NoAvailableSourceError) as exc_info:_configured_loader().fetch(["AAPL"], "2026-01-01", "2026-07-01", interval="1D")++ assert str(exc_info.value) == "Longbridge history request failed."+ assert secret not in str(exc_info.value)+ assert exc_info.value.__cause__ is None+ assert exc_info.value.__context__ is None+++def test_fetch_redacts_sdk_initialization_exception_and_drops_cause(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ secret = "sdk-init-exception-credential-dc57"++ class SecretBearingSdkError(RuntimeError):+ pass++ fake_openapi = SimpleNamespace(+ Config=lambda *args: (_ for _ in ()).throw(+ SecretBearingSdkError(f"invalid access_token={secret}")+ ),+ QuoteContext=lambda config: config,+ )+ monkeypatch.setattr(loader_mod, "_require_longbridge", lambda: fake_openapi)+ monkeypatch.setattr(loader_mod, "loader_cache_get", lambda **kwargs: None)++ with pytest.raises(NoAvailableSourceError) as exc_info:+ _configured_loader().fetch(["AAPL"], "2026-01-01", "2026-01-02")++ assert str(exc_info.value) == "Longbridge SDK initialization failed."+ assert secret not in str(exc_info.value)+ assert exc_info.value.__cause__ is None+ assert exc_info.value.__context__ is None+++# --------------------------------------------------------------------------- #+# Call-counter / spy tests: _require_longbridge must never be reached in+# both is_available and fetch when credentials are partial or conflicting.+# --------------------------------------------------------------------------- #+++def test_partial_credentials_never_call_require_longbridge(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ """is_available and fetch both exit before calling _require_longbridge."""+ call_count = 0++ def counting_require():+ nonlocal call_count+ call_count += 1+ raise AssertionError("_require_longbridge must not be called")++ secrets = {+ "app_key": "spy-partial-env-key-e1f2",+ }+ monkeypatch.setenv("LONGBRIDGE_APP_KEY", secrets["app_key"])+ monkeypatch.delenv("LONGBRIDGE_APP_SECRET", raising=False)+ monkeypatch.delenv("LONGBRIDGE_ACCESS_TOKEN", raising=False)+ (tmp_path / "longbridge.json").write_text(+ json.dumps(+ {+ "app_key": "spy-partial-file-key-a3b4",+ "app_secret": "spy-partial-file-secret-c5d6",+ "access_token": "spy-partial-file-token-e7f8",+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(loader_mod, "_require_longbridge", counting_require)++ loader = loader_mod.LongbridgeLoader()+ assert loader.is_available() is False+ with pytest.raises(NoAvailableSourceError):+ loader.fetch(["AAPL"], "2026-01-01", "2026-01-02")++ assert call_count == 0+++def test_conflict_credentials_never_call_require_longbridge(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ """is_available and fetch both exit before calling _require_longbridge."""+ call_count = 0++ def counting_require():+ nonlocal call_count+ call_count += 1+ raise AssertionError("_require_longbridge must not be called")++ env = {+ "app_key": "spy-conflict-env-key-g9h0",+ "app_secret": "spy-conflict-env-secret-i1j2",+ "access_token": "spy-conflict-env-token-k3l4",+ }+ file = {+ "app_key": "spy-conflict-file-key-m5n6",+ "app_secret": "spy-conflict-file-secret-o7p8",+ "access_token": "spy-conflict-file-token-q9r0",+ }+ monkeypatch.setenv("LONGBRIDGE_APP_KEY", env["app_key"])+ monkeypatch.setenv("LONGBRIDGE_APP_SECRET", env["app_secret"])+ monkeypatch.setenv("LONGBRIDGE_ACCESS_TOKEN", env["access_token"])+ (tmp_path / "longbridge.json").write_text(json.dumps(file), encoding="utf-8")+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(loader_mod, "_require_longbridge", counting_require)++ loader = loader_mod.LongbridgeLoader()+ assert loader.is_available() is False+ with pytest.raises(NoAvailableSourceError):+ loader.fetch(["AAPL"], "2026-01-01", "2026-01-02")++ assert call_count == 0diff --git a/agent/tests/test_market_data_tool.py b/agent/tests/test_market_data_tool.pyindex 2da6576d3..8719200b1 100644--- a/agent/tests/test_market_data_tool.py+++ b/agent/tests/test_market_data_tool.py@@ -11,7 +11,48 @@ from src.swarm.worker import build_worker_promptfrom src.tools import build_swarm_registry+def test_market_data_tool_exposes_longbridge_source():+ from src.tools.market_data_tool import MarketDataTool++ source_schema = MarketDataTool.parameters["properties"]["source"]+ assert "longbridge" in source_schema["enum"]+++def test_market_data_json_accepts_explicit_longbridge_source():+ idx = pd.date_range("2026-01-01", periods=1, freq="D")+ idx.name = "trade_date"+ df = pd.DataFrame(+ {+ "open": [1.0],+ "high": [2.0],+ "low": [0.5],+ "close": [1.5],+ "volume": [100],+ },+ index=idx,+ )+ seen = []++ class _LongbridgeLoader:+ def fetch(self, codes, start, end, interval="1D"):+ seen.append((codes, start, end, interval))+ return {codes[0]: df}++ text = fetch_market_data_json(+ codes=["AAPL.US"],+ start_date="2026-01-01",+ end_date="2026-01-02",+ source="longbridge",+ loader_resolver=lambda source: _LongbridgeLoader,+ )++ payload = json.loads(text)+ assert "AAPL.US" in payload+ assert seen == [(["AAPL.US"], "2026-01-01", "2026-01-02", "1D")]++def test_market_data_json_is_strict_when_loader_returns_nan():+idx = pd.date_range("2026-01-01", periods=1, freq="D")df = pd.DataFrame({diff --git a/agent/tests/test_sdk_connectors.py b/agent/tests/test_sdk_connectors.pyindex a41e450b8..f02a8d482 100644--- a/agent/tests/test_sdk_connectors.py+++ b/agent/tests/test_sdk_connectors.py@@ -8,9 +8,14 @@ and the service dispatch degrading cleanly when nothing is configured.from __future__ import annotations+import json+from types import SimpleNamespace+import pytest+from backtest.loaders import longbridge as longbridge_loaderfrom src.live.classification import ToolClass+from src.trading.connectors.longbridge import credentials as lb_credentialsfrom src.trading import profiles, servicefrom src.trading.connectors.alpaca import sdk as alfrom src.trading.connectors.alpaca.classification import ALPACA_TOOL_CLASS@@ -154,7 +159,14 @@ def test_tiger_invalid_profile_rejected() -> None:def test_longbridge_build_config_and_region(monkeypatch, tmp_path) -> None:+ for env_name in (+ "LONGBRIDGE_APP_KEY",+ "LONGBRIDGE_APP_SECRET",+ "LONGBRIDGE_ACCESS_TOKEN",+ ):+ monkeypatch.delenv(env_name, raising=False)monkeypatch.setattr(lb, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)cfg = lb.build_config({"profile": "live-readonly", "region": "cn"}, None)assert cfg.profile == "live-readonly"assert cfg.region == "cn"@@ -165,15 +177,190 @@ def test_longbridge_invalid_region_rejected() -> None:lb.LongbridgeConfig.from_mapping({"region": "moon"})+def test_longbridge_with_overrides_preserves_atomic_credentials() -> None:+ cfg = lb.LongbridgeConfig(+ app_key="atomic-key",+ app_secret="atomic-secret",+ access_token="atomic-token",+ _credential_source="environment",+ )++ updated = cfg.with_overrides(+ app_key="ignored-key", profile="live-readonly", region="cn"+ )++ assert (updated.app_key, updated.app_secret, updated.access_token) == (+ "atomic-key",+ "atomic-secret",+ "atomic-token",+ )+ assert updated._credential_source == "environment"+ assert updated.profile == "live-readonly"+ assert updated.region == "cn"++def test_longbridge_public_config_redacts_secrets() -> None:- """Secret material must never appear in a status payload."""- cfg = lb.LongbridgeConfig(app_key="abcd1234", app_secret="supersecret", access_token="tok-123")+ """Secret material must never appear in status payloads or config reprs."""+ values = {+ "app_key": "repr-distinctive-app-key-7f31",+ "app_secret": "repr-distinctive-app-secret-8a42",+ "access_token": "repr-distinctive-access-token-9b53",+ }+ cfg = lb.LongbridgeConfig(**values)pub = lb._public_config(cfg)assert pub["app_secret"] == "***redacted***"assert pub["access_token"] == "***redacted***"- assert "supersecret" not in str(pub)- assert "tok-123" not in str(pub)assert pub["app_key"].endswith("***")+ assert all(value not in repr(cfg) for value in values.values())+ assert all(value not in repr(pub) for value in values.values())+++def _set_longbridge_environment(monkeypatch, values) -> None:+ for field, env_name in {+ "app_key": "LONGBRIDGE_APP_KEY",+ "app_secret": "LONGBRIDGE_APP_SECRET",+ "access_token": "LONGBRIDGE_ACCESS_TOKEN",+ }.items():+ monkeypatch.setenv(env_name, values[field])+++def test_connector_uses_environment_credentials(monkeypatch, tmp_path) -> None:+ values = {+ "app_key": "connector-environment-key",+ "app_secret": "connector-environment-secret",+ "access_token": "connector-environment-token",+ }+ _set_longbridge_environment(monkeypatch, values)+ monkeypatch.setattr(lb, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)++ cfg = lb.build_config({"profile": "live-readonly", "region": "cn"}, None)++ assert (cfg.app_key, cfg.app_secret, cfg.access_token) == tuple(values.values())+ assert cfg.profile == "live-readonly"+ assert cfg.region == "cn"+ monkeypatch.setattr(lb, "longbridge_available", lambda: False)+ assert lb.check_status(cfg)["credential_source"] == "environment"+++def test_loader_and_connector_resolve_same_source(monkeypatch, tmp_path) -> None:+ values = {+ "app_key": "shared-file-key",+ "app_secret": "shared-file-secret",+ "access_token": "shared-file-token",+ }+ for env_name in (+ "LONGBRIDGE_APP_KEY",+ "LONGBRIDGE_APP_SECRET",+ "LONGBRIDGE_ACCESS_TOKEN",+ ):+ monkeypatch.delenv(env_name, raising=False)+ (tmp_path / "longbridge.json").write_text(json.dumps(values), encoding="utf-8")+ monkeypatch.setattr(lb, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)++ connector = lb.build_config()+ loader = longbridge_loader.LongbridgeLoader()++ assert (connector.app_key, connector.app_secret, connector.access_token) == (+ loader._app_key,+ loader._app_secret,+ loader._access_token,+ )+ monkeypatch.setattr(lb, "longbridge_available", lambda: False)+ assert lb.check_status(connector)["credential_source"] == "runtime_file"+ assert loader._credential_source == "runtime_file"+++def test_connector_reports_conflict_without_sdk_call(monkeypatch, tmp_path) -> None:+ environment = {+ "app_key": "conflict-environment-key",+ "app_secret": "conflict-environment-secret",+ "access_token": "conflict-environment-token",+ }+ runtime_file = {+ "app_key": "conflict-file-key",+ "app_secret": "conflict-file-secret",+ "access_token": "conflict-file-token",+ }+ _set_longbridge_environment(monkeypatch, environment)+ (tmp_path / "longbridge.json").write_text(json.dumps(runtime_file), encoding="utf-8")+ monkeypatch.setattr(lb, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(+ lb,+ "_trade_context",+ lambda cfg: (_ for _ in ()).throw(AssertionError("SDK must not initialize")),+ )++ report = lb.check_status(lb.build_config())++ assert report["configured"] is False+ assert report["connection_state"] == "error"+ assert report["credential_source"] is None+ assert report["error_code"] == "credentials_conflict"+ assert all(+ field in report["error"]+ for field in ("app_key", "app_secret", "access_token")+ )+ with pytest.raises(lb.LongbridgeConfigError, match="sources conflict"):+ lb._require_resolved_config(lb.build_config())+++def test_connector_status_redacts_credentials(monkeypatch, tmp_path) -> None:+ values = {+ "app_key": "status-sensitive-key",+ "app_secret": "status-sensitive-secret",+ "access_token": "status-sensitive-token",+ }+ secret_exception = RuntimeError(+ "authentication failed for " + "/".join(values.values())+ )+ _set_longbridge_environment(monkeypatch, values)+ monkeypatch.setattr(lb, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(lb, "longbridge_available", lambda: True)+ monkeypatch.setattr(+ lb,+ "_trade_context",+ lambda cfg: SimpleNamespace(+ account_balance=lambda: (_ for _ in ()).throw(secret_exception)+ ),+ )++ report = lb.check_status(lb.build_config())+ serialized = str(report)++ assert report["configured"] is True+ assert report["connection_state"] == "error"+ assert report["error_code"] == "authentication_failed"+ assert report["error"] == "Longbridge authentication failed."+ assert all(value not in serialized for value in values.values())+ assert report["error"].__class__ is str+ assert secret_exception not in _exception_chain_from_payload(report)+++def _exception_chain_from_payload(payload) -> tuple[BaseException, ...]:+ """Return exceptions publicly reachable from a returned payload."""+ seen: set[int] = set()+ found: list[BaseException] = []+ pending = list(payload.values()) if isinstance(payload, dict) else [payload]+ while pending:+ value = pending.pop()+ if id(value) in seen:+ continue+ seen.add(id(value))+ if isinstance(value, BaseException):+ found.append(value)+ if value.__cause__ is not None:+ pending.append(value.__cause__)+ if value.__context__ is not None:+ pending.append(value.__context__)+ elif isinstance(value, dict):+ pending.extend(value.values())+ elif isinstance(value, (list, tuple, set)):+ pending.extend(value)+ return tuple(found)# --------------------------------------------------------------------------- #@@ -210,7 +397,14 @@ def test_service_check_connection_unconfigured_tiger(monkeypatch, tmp_path) -> Ndef test_service_check_connection_unconfigured_longbridge(monkeypatch, tmp_path) -> None:+ for env_name in (+ "LONGBRIDGE_APP_KEY",+ "LONGBRIDGE_APP_SECRET",+ "LONGBRIDGE_ACCESS_TOKEN",+ ):+ monkeypatch.delenv(env_name, raising=False)monkeypatch.setattr(lb, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)result = service.check_connection("longbridge-paper-sdk")assert result["status"] == "error"assert "not configured" in result["error"]diff --git a/agent/tests/test_sdk_order_gate.py b/agent/tests/test_sdk_order_gate.pyindex 01c828cfb..de4173c75 100644--- a/agent/tests/test_sdk_order_gate.py+++ b/agent/tests/test_sdk_order_gate.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport pytest+from src.config.accessor import reset_env_configfrom src.live import sdk_order_gate as gatefrom src.live.enforcement import OrderIntentfrom src.live.mandate.model import (@@ -20,10 +21,24 @@ from src.live.mandate.model import (UniverseConstraint,)from src.trading import service+from src.trading.connectors.longbridge import credentials as lb_credentialspytestmark = pytest.mark.unit[email protected](autouse=True)+def _isolate_longbridge_credentials(monkeypatch, tmp_path):+ """Never let Longbridge cases consume workstation env/file credentials."""+ for env_name in (+ "LONGBRIDGE_APP_KEY",+ "LONGBRIDGE_APP_SECRET",+ "LONGBRIDGE_ACCESS_TOKEN",+ ):+ monkeypatch.delenv(env_name, raising=False)+ reset_env_config()+ monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)++class _FakeConnector:"""Minimal connector module stand-in capturing place_order calls."""