diff --git a/.github/workflows/mutation-test.yml b/.github/workflows/mutation-test.yml new file mode 100644 index 00000000..89a18c53 --- /dev/null +++ b/.github/workflows/mutation-test.yml @@ -0,0 +1,44 @@ +name: Nightly Risk Mutation Tests + +on: + schedule: + - cron: '29 4 * * *' + workflow_dispatch: + +permissions: + contents: read + +jobs: + mutmut: + name: Mutate risk & position sizing core + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + + - name: Setup Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.11" + + - name: Install dependencies and mutmut + run: | + set -euo pipefail + python -m pip install --upgrade pip + python -m pip install -e . pytest mutmut==2.5.1 "jsonschema>=4.18,<5" "rfc3339-validator>=0.1.4,<1" + + - name: Run scoped mutation tests + run: | + set -euo pipefail + python -m pytest -q tests/test_position_sizing.py tests/test_promotion_sizing_chain.py + set +e + mutmut run \ + --paths-to-mutate=src/quant_platform_kit/position_sizing.py,src/quant_platform_kit/risk/promotion_sizing.py \ + --runner="python -m pytest -q tests/test_position_sizing.py tests/test_promotion_sizing_chain.py" + mutmut_rc=$? + set -e + mutmut results >> "$GITHUB_STEP_SUMMARY" + if [ "$mutmut_rc" -ne 0 ] && [ "$mutmut_rc" -ne 2 ]; then + exit "$mutmut_rc" + fi diff --git a/.ruff.toml b/.ruff.toml new file mode 100644 index 00000000..55d76910 --- /dev/null +++ b/.ruff.toml @@ -0,0 +1,123 @@ +target-version = "py310" + +[lint] +select = ["E4", "E7", "E9", "F", "B", "C901"] +ignore = ["E701", "E702", "E741", "B008", "E402"] + +[lint.mccabe] +max-complexity = 15 + +[lint.per-file-ignores] +"scripts/**/*.py" = ["B", "C901", "F401", "F841"] +"src/quant_platform_kit/adaptive_allocation/selector.py" = ["C901"] +"src/quant_platform_kit/binance/account.py" = ["C901"] +"src/quant_platform_kit/cloud/aws_provider.py" = ["B"] +"src/quant_platform_kit/common/__init__.py" = ["F401"] +"src/quant_platform_kit/common/_execution_state_session.py" = ["C901", "F401"] +"src/quant_platform_kit/common/_execution_state_store.py" = ["C901", "F401"] +"src/quant_platform_kit/common/_execution_state_submission_models.py" = ["F401"] +"src/quant_platform_kit/common/account_domain.py" = ["C901"] +"src/quant_platform_kit/common/automation_setup.py" = ["C901"] +"src/quant_platform_kit/common/broker_reconciliation.py" = ["C901", "F401"] +"src/quant_platform_kit/common/broker_reconciliation_enrollment.py" = ["C901"] +"src/quant_platform_kit/common/capital_base.py" = ["C901"] +"src/quant_platform_kit/common/cash_conservation.py" = ["C901"] +"src/quant_platform_kit/common/execution_state.py" = ["F401"] +"src/quant_platform_kit/common/execution_translation.py" = ["F401"] +"src/quant_platform_kit/common/feature_snapshot/__init__.py" = ["F401"] +"src/quant_platform_kit/common/feature_snapshot/fallback.py" = ["F401"] +"src/quant_platform_kit/common/feature_snapshot/guard.py" = ["C901"] +"src/quant_platform_kit/common/health.py" = ["F401"] +"src/quant_platform_kit/common/long_only_reduce.py" = ["C901", "F401"] +"src/quant_platform_kit/common/notification_localization.py" = ["C901"] +"src/quant_platform_kit/common/order_status.py" = ["C901"] +"src/quant_platform_kit/common/paper_execution_admission.py" = ["C901", "F401"] +"src/quant_platform_kit/common/paper_execution_command_consumer.py" = ["C901"] +"src/quant_platform_kit/common/pending_order_evidence.py" = ["C901"] +"src/quant_platform_kit/common/platform_runner/__init__.py" = ["F401"] +"src/quant_platform_kit/common/reconciliation_recovery.py" = ["C901"] +"src/quant_platform_kit/common/runtime_command_gate.py" = ["C901"] +"src/quant_platform_kit/common/runtime_heartbeat_policy.py" = ["C901"] +"src/quant_platform_kit/common/runtime_inputs.py" = ["B", "C901"] +"src/quant_platform_kit/common/runtime_target.py" = ["C901"] +"src/quant_platform_kit/common/small_account_compatibility.py" = ["C901"] +"src/quant_platform_kit/common/strategy_contracts.py" = ["C901"] +"src/quant_platform_kit/common/us_equity_sessions.py" = ["C901"] +"src/quant_platform_kit/data/decision_price_series_artifact.py" = ["C901", "F401"] +"src/quant_platform_kit/data/multisource_assurance.py" = ["B", "C901", "F401"] +"src/quant_platform_kit/data/research_input.py" = ["F401"] +"src/quant_platform_kit/data/research_mandate.py" = ["C901"] +"src/quant_platform_kit/data/version.py" = ["F401"] +"src/quant_platform_kit/ibkr/execution.py" = ["C901"] +"src/quant_platform_kit/ibkr/market_data.py" = ["B", "C901"] +"src/quant_platform_kit/ibkr/order_outcome.py" = ["C901"] +"src/quant_platform_kit/ibkr/portfolio.py" = ["C901"] +"src/quant_platform_kit/longbridge/portfolio.py" = ["C901"] +"src/quant_platform_kit/markets/sessions.py" = ["C901"] +"src/quant_platform_kit/notifications/digest_archive.py" = ["C901"] +"src/quant_platform_kit/notifications/digest_candidates.py" = ["C901"] +"src/quant_platform_kit/notifications/digest_routing.py" = ["C901"] +"src/quant_platform_kit/notifications/presentation.py" = ["B", "C901"] +"src/quant_platform_kit/notifications/renderer_base.py" = ["C901", "F401"] +"src/quant_platform_kit/notifications/strategy_plugin_webhook.py" = ["C901"] +"src/quant_platform_kit/operators/cloud_run_tags.py" = ["C901"] +"src/quant_platform_kit/position_sizing.py" = ["C901"] +"src/quant_platform_kit/research_factory/validation.py" = ["C901"] +"src/quant_platform_kit/research_stats/bootstrap.py" = ["C901"] +"src/quant_platform_kit/research_stats/cost_stress.py" = ["B", "C901"] +"src/quant_platform_kit/research_stats/overfitting.py" = ["C901"] +"src/quant_platform_kit/research_stats/security_netting.py" = ["C901"] +"src/quant_platform_kit/research_stats/sharpe_inference.py" = ["C901"] +"src/quant_platform_kit/research_stats/unified_report.py" = ["B", "C901"] +"src/quant_platform_kit/risk/attention.py" = ["C901"] +"src/quant_platform_kit/risk/contracts.py" = ["C901"] +"src/quant_platform_kit/risk/engine.py" = ["F401", "F841"] +"src/quant_platform_kit/risk/gate/__init__.py" = ["F401"] +"src/quant_platform_kit/risk/gate/assessment.py" = ["C901"] +"src/quant_platform_kit/risk/gate/mandates.py" = ["C901"] +"src/quant_platform_kit/risk/gate/static.py" = ["C901"] +"src/quant_platform_kit/risk/gate/support.py" = ["C901"] +"src/quant_platform_kit/risk/production_drift_new_risk.py" = ["B"] +"src/quant_platform_kit/risk/snapshot.py" = ["C901"] +"src/quant_platform_kit/risk/synthetic_combo_evidence.py" = ["C901"] +"src/quant_platform_kit/schwab/portfolio.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/_contracts_lifecycle.py" = ["F401"] +"src/quant_platform_kit/strategy_lifecycle/_contracts_observation.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/_contracts_research_cost.py" = ["B", "C901", "F401"] +"src/quant_platform_kit/strategy_lifecycle/_contracts_research_ledger.py" = ["C901", "F401"] +"src/quant_platform_kit/strategy_lifecycle/ai_patch.py" = ["B", "C901"] +"src/quant_platform_kit/strategy_lifecycle/ai_provider.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/ai_reviewer.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/backtest_orchestrator.py" = ["B", "C901"] +"src/quant_platform_kit/strategy_lifecycle/candidate_control.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/codex_integration.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/doctor.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/drift_alerts.py" = ["F401"] +"src/quant_platform_kit/strategy_lifecycle/drift_detector.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/evidence_gate.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/evidence_package_v2.py" = ["B", "C901"] +"src/quant_platform_kit/strategy_lifecycle/forward_observation.py" = ["C901", "F401"] +"src/quant_platform_kit/strategy_lifecycle/forward_observation_receipt.py" = ["C901", "F401"] +"src/quant_platform_kit/strategy_lifecycle/forward_risk_driver.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/legacy_profile_index.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/live_equity.py" = ["B", "C901"] +"src/quant_platform_kit/strategy_lifecycle/non_live_execution_evidence.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/paired_shadow_evidence.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/param_optimizer.py" = ["B", "C901"] +"src/quant_platform_kit/strategy_lifecycle/performance_monitor.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/performance_store.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/promotion_actionable_runner.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/release_readiness.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/research_driver.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/research_promotion/budget.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/research_promotion/console_client.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/research_promotion/cycle.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/research_promotion_cycle.py" = ["F401", "F841"] +"src/quant_platform_kit/strategy_lifecycle/research_task.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/return_collector.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/task_review.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/watch/runner.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/watch/strategy_automation_registry.py" = ["C901"] +"src/quant_platform_kit/strategy_lifecycle/watch/strategy_watch.py" = ["C901"] +"src/quant_platform_kit/strategy_spec/validation.py" = ["C901"] +"tests/**/*.py" = ["B", "C901", "E402", "F401", "F841"] diff --git a/src/quant_platform_kit/common/_strategy_plugin_alerts.py b/src/quant_platform_kit/common/_strategy_plugin_alerts.py new file mode 100644 index 00000000..691fe23a --- /dev/null +++ b/src/quant_platform_kit/common/_strategy_plugin_alerts.py @@ -0,0 +1,905 @@ +"""Localization, notification formatting, and alert message builders for strategy plugins.""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Mapping, Sequence +from typing import Any, Callable + +from quant_platform_kit.common._strategy_plugin_consumption import ( + _strategy_plugin_auto_consumption_allowed, + _strategy_plugin_enabled_label, + _is_strategy_position_control_notice, + _strategy_plugin_is_notification_only, +) +from quant_platform_kit.common._strategy_plugin_loading import _coerce_strategy_plugin_signal +from quant_platform_kit.common._strategy_plugin_helpers import ( + _as_bool, + _compact_strategy_plugin_error, + _normalize_strategy_plugin_field, + _optional_key_part, + _optional_string, + _sanitize_key_part, + _translate, + _translate_first, + _translator_uses_zh, +) +from quant_platform_kit.common._strategy_plugin_models import ( + PLUGIN_CRISIS_RESPONSE_SHADOW, + PLUGIN_MACRO_RISK_GOVERNOR, + PLUGIN_MARKET_REGIME_CONTROL, + PLUGIN_TACO_REBOUND_SHADOW, + STRATEGY_PLUGIN_ALERT_ACTIONS, + STRATEGY_PLUGIN_AUTOMATED_POSITION_ACTIONS, + STRATEGY_PLUGIN_NON_ALERT_ROUTES, + StrategyPluginAlertMessage, + StrategyPluginSignal, +) +from quant_platform_kit.common.display_names import display_name + +_DEFAULT_STRATEGY_PLUGIN_ALERT_GUIDANCE: Mapping[tuple[str, str, str], str] = { + ( + PLUGIN_CRISIS_RESPONSE_SHADOW, + "true_crisis", + "defend", + ): ( + "Consider reducing leveraged exposure, moving to defensive or cash-like positions, " + "and pausing new risk additions until the signal de-escalates." + ), + ( + PLUGIN_CRISIS_RESPONSE_SHADOW, + "no_action", + "blocked", + ): ( + "The crisis route was blocked by a guard; review data freshness and context before " + "acting on the signal." + ), + ( + PLUGIN_MACRO_RISK_GOVERNOR, + "delever", + "delever", + ): ( + "Deterministic macro risk governor suggests reducing leveraged exposure while preserving " + "unlevered risk exposure when the strategy opts in." + ), + ( + PLUGIN_MACRO_RISK_GOVERNOR, + "crisis", + "defend", + ): ( + "Deterministic macro risk governor suggests moving the risk sleeve toward defensive or " + "cash-like exposure until macro stress de-escalates." + ), + ( + PLUGIN_MARKET_REGIME_CONTROL, + "risk_off", + "defend", + ): ( + "Unified market regime control blocks opportunity overlays and suggests moving risk exposure " + "toward defensive or cash-like positions until the deterministic arbiter de-escalates." + ), + ( + PLUGIN_MARKET_REGIME_CONTROL, + "risk_reduced", + "delever", + ): ( + "Unified market regime control suggests reducing leveraged exposure while preserving only the " + "risk budget allowed by the strategy policy adapter." + ), + ( + PLUGIN_MARKET_REGIME_CONTROL, + "opportunity_watch", + "notify_manual_review", + ): ( + "Manual review only: the unified arbiter allows the bounded TACO opportunity context, but it " + "does not authorize broker orders or live allocation mutation." + ), + ( + PLUGIN_MARKET_REGIME_CONTROL, + "blocked", + "blocked", + ): ( + "Unified market regime control was blocked by data-quality or freshness guards; review source " + "artifacts before relying on the signal." + ), + ( + PLUGIN_TACO_REBOUND_SHADOW, + "taco_rebound", + "notify_manual_review", + ): ( + "Manual review only: consider a small, pre-sized probe or staged entry with a " + "predefined invalidation level; avoid full-size deployment from this alert alone." + ), +} +_DEFAULT_STRATEGY_PLUGIN_ALERT_SCOPE_NOTE = ( + "Manual review notice only; the plugin does not place orders or change allocations." +) + + +def translate_strategy_plugin_value( + category: str, + raw_value: str | None, + *, + translator: Callable[..., str] | None = None, +) -> str: + value = str(raw_value or "").strip() or "unknown" + if translator is None: + return value + key = f"strategy_plugin_{category}_{value}" + translated = translator(key) + return translated if translated != key else value + + +def _extract_strategy_plugin_localized_message( + signal: StrategyPluginSignal, + *, + section: str, + locale: str, +) -> str | None: + payload = signal.payload + normalized_section = str(section or "").strip() + normalized_locale = str(locale or "").strip() + if not normalized_section or not normalized_locale: + return None + + localized_messages = payload.get("localized_messages") + if isinstance(localized_messages, Mapping): + section_messages = localized_messages.get(normalized_section) + if isinstance(section_messages, Mapping): + localized = _optional_string(section_messages.get(normalized_locale)) + if localized: + return localized + default_locale = _optional_string(localized_messages.get("default_locale")) + if default_locale: + localized = _optional_string(section_messages.get(default_locale)) + if localized: + return localized + + if normalized_section == "notification": + notification = payload.get("notification") + if isinstance(notification, Mapping): + notification_messages = notification.get("localized_messages") + if isinstance(notification_messages, Mapping): + localized = _optional_string(notification_messages.get(normalized_locale)) + if localized: + return localized + default_locale = _optional_string(notification.get("default_locale")) + if default_locale: + localized = _optional_string(notification_messages.get(default_locale)) + if localized: + return localized + return None + + +def extract_strategy_plugin_localized_message( + signal: StrategyPluginSignal | Any, + *, + section: str, + locale: str, +) -> str | None: + return _extract_strategy_plugin_localized_message( + _coerce_strategy_plugin_signal(signal), + section=section, + locale=locale, + ) + + +def _strategy_plugin_consumption_notification_line( + signal: StrategyPluginSignal, + *, + translator: Callable[..., str] | None = None, +) -> str | None: + route = signal.normalized_route + action = signal.normalized_action + if _strategy_plugin_auto_consumption_allowed(signal, action=action): + if action == "defend" or route == "risk_off": + key = "strategy_plugin_consumption_auto_defend" + elif action == "delever" or route == "risk_reduced": + key = "strategy_plugin_consumption_auto_delever" + else: + key = "strategy_plugin_consumption_auto" + return _translate( + translator, + key, + fallback="Plugin impact this run: included in this cycle's position calculation", + ) + if _strategy_plugin_is_notification_only(signal): + return _translate( + translator, + "strategy_plugin_consumption_review_only", + fallback=( + "Plugin impact this run: review-only notice; current state did not trigger automatic " + "position rewrites" + ), + ) + if action in STRATEGY_PLUGIN_AUTOMATED_POSITION_ACTIONS: + return _translate( + translator, + "strategy_plugin_consumption_loaded_not_applied", + fallback=( + "Plugin impact this run: loaded; this state did not enable automatic position rewrites" + ), + ) + return None + + +def build_strategy_plugin_notification_lines( + signals: Sequence[StrategyPluginSignal | Any], + *, + translator: Callable[..., str] | None = None, + locale: str | None = None, +) -> tuple[str, ...]: + lines: list[str] = [] + for raw_signal in signals: + signal = _coerce_strategy_plugin_signal(raw_signal) + localized_line = ( + _extract_strategy_plugin_localized_message(signal, section="notification", locale=locale) + if locale is not None + else None + ) + if localized_line: + lines.append(localized_line) + if translator is not None: + consumption_line = _strategy_plugin_consumption_notification_line(signal, translator=translator) + if consumption_line: + lines.append(consumption_line) + continue + route = signal.canonical_route or "unknown_route" + action = signal.suggested_action or "unknown_action" + lines.append( + _translate( + translator, + "strategy_plugin_line", + fallback="Plugin: {plugin} | enabled: {enabled} | status: {route} | notice: {action}", + plugin=translate_strategy_plugin_value("name", signal.plugin, translator=translator), + enabled=_strategy_plugin_enabled_label(signal, translator=translator), + mode=translate_strategy_plugin_value("mode", signal.effective_mode, translator=translator), + route=translate_strategy_plugin_value("route", route, translator=translator), + action=translate_strategy_plugin_value("action", action, translator=translator), + ) + ) + consumption_line = _strategy_plugin_consumption_notification_line(signal, translator=translator) + if consumption_line: + lines.append(consumption_line) + return tuple(lines) + + +def _strategy_plugin_error_reason(error: object, *, translator: Callable[..., str] | None = None) -> str: + detail = _compact_strategy_plugin_error(error) + if not detail: + return "" + error_type = detail.split(":", 1)[0].rsplit(".", 1)[-1].strip() + reason_key = f"strategy_plugin_error_reason_{error_type}" if error_type else "" + if translator is not None and reason_key: + translated = translator(reason_key) + if translated != reason_key: + return translated + if _translator_uses_zh(translator): + translated = translator("strategy_plugin_error_reason_default") if translator is not None else "" + if translated and translated != "strategy_plugin_error_reason_default": + return translated + return detail + + +def build_strategy_plugin_error_notification_lines( + error: object, + *, + translator: Callable[..., str] | None = None, +) -> tuple[str, ...]: + reason = _strategy_plugin_error_reason(error, translator=translator) + if not reason: + return () + return ( + _translate( + translator, + "strategy_plugin_error_line", + fallback="Plugin signal failed to load: {reason}; this run falls back to built-in strategy rules", + reason=reason, + ), + _translate( + translator, + "strategy_plugin_consumption_unavailable", + fallback="Plugin impact this run: no usable plugin signal loaded", + ), + ) + + +def _should_alert_strategy_plugin_signal(signal: StrategyPluginSignal) -> bool: + route = signal.normalized_route + action = signal.normalized_action + if _is_strategy_position_control_notice(signal, action=action): + return False + if _is_strategy_manual_review_notification_delegated(signal): + return False + return ( + signal.would_trade_if_enabled + or route not in STRATEGY_PLUGIN_NON_ALERT_ROUTES + or action in STRATEGY_PLUGIN_ALERT_ACTIONS + ) + + +def should_alert_strategy_plugin_signal(signal: StrategyPluginSignal | Any) -> bool: + return _should_alert_strategy_plugin_signal(_coerce_strategy_plugin_signal(signal)) + + +def _is_strategy_manual_review_notification_delegated(signal: StrategyPluginSignal) -> bool: + """Return true when a strategy artifact delegates human-review alerts to a notification target.""" + + if signal.normalized_target_type != "strategy": + return False + controls = signal.execution_controls + if not _as_bool(controls.get("manual_review_notification_delegated"), default=False): + return False + return _optional_string(controls.get("manual_review_notification_target")) is not None + + +def _build_strategy_plugin_alert_guidance( + signal: StrategyPluginSignal, + *, + translator: Callable[..., str] | None = None, +) -> str | None: + plugin = signal.normalized_plugin + route = signal.normalized_route + action = signal.normalized_action + translated = _translate_first( + translator, + ( + f"strategy_plugin_guidance_{plugin}_{route}_{action}", + f"strategy_plugin_guidance_{plugin}_{route}", + f"strategy_plugin_guidance_{plugin}_{action}", + f"strategy_plugin_guidance_{plugin}", + f"strategy_plugin_guidance_{route}_{action}", + f"strategy_plugin_guidance_{action}", + ), + ) + if translated: + return translated + return _DEFAULT_STRATEGY_PLUGIN_ALERT_GUIDANCE.get((plugin, route, action)) + + +def build_strategy_plugin_alert_guidance( + signal: StrategyPluginSignal | Any, + *, + translator: Callable[..., str] | None = None, +) -> str | None: + return _build_strategy_plugin_alert_guidance( + _coerce_strategy_plugin_signal(signal), + translator=translator, + ) + + +def _build_strategy_plugin_alert_scope_note( + signal: StrategyPluginSignal, + *, + translator: Callable[..., str] | None = None, +) -> str | None: + controls = signal.execution_controls + notification_profile = str(controls.get("notification_profile") or "").strip().lower() + if notification_profile != "shadow_only" and any( + _as_bool(controls.get(field), default=False) + for field in ( + "broker_order_allowed", + "repository_broker_write_allowed", + "live_allocation_mutation_allowed", + "repository_allocation_mutation_allowed", + "allocation_recommendation_allowed", + "position_sizing_allowed", + "selection_allowed", + ) + ): + return None + return ( + _translate_first( + translator, + ( + f"strategy_plugin_alert_scope_{signal.normalized_plugin}", + "strategy_plugin_alert_scope", + ), + ) + or _DEFAULT_STRATEGY_PLUGIN_ALERT_SCOPE_NOTE + ) + + +def build_strategy_plugin_alert_scope_note( + signal: StrategyPluginSignal | Any, + *, + translator: Callable[..., str] | None = None, +) -> str | None: + return _build_strategy_plugin_alert_scope_note( + _coerce_strategy_plugin_signal(signal), + translator=translator, + ) + + +def _strategy_plugin_alert_locale(*, translator: Callable[..., str] | None = None) -> str: + locale = _translate(translator, "strategy_plugin_alert_locale", fallback="en-US") + return str(locale or "en-US").strip() or "en-US" + + +def _localized_strategy_plugin_label_values( + signal: StrategyPluginSignal, + label_name: str, + *, + locale: str, +) -> tuple[str, ...]: + localized_messages = signal.payload.get("localized_messages") + if not isinstance(localized_messages, Mapping): + return () + labels = localized_messages.get("labels") + if not isinstance(labels, Mapping): + return () + label_values = labels.get(label_name) + if not isinstance(label_values, Mapping): + return () + + candidates = [locale] + if "-" in locale: + candidates.append(locale.split("-", 1)[0]) + default_locale = _optional_string(localized_messages.get("default_locale")) + if default_locale: + candidates.append(default_locale) + + for candidate in candidates: + value = label_values.get(candidate) + if isinstance(value, str): + text = value.strip() + return (text,) if text else () + if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): + values = tuple(str(item).strip() for item in value if str(item).strip()) + if values: + return values + return () + + +def _strategy_plugin_reason_values(signal: StrategyPluginSignal, *, locale: str) -> tuple[str, ...]: + localized_reasons = _localized_strategy_plugin_label_values(signal, "reason_codes", locale=locale) + if localized_reasons: + return localized_reasons + + payload = signal.payload + for section_key in ("log_record", "position_control"): + section = payload.get(section_key) + if isinstance(section, Mapping): + reason_codes = section.get("reason_codes") + if isinstance(reason_codes, Sequence) and not isinstance(reason_codes, (str, bytes)): + values = tuple(str(item).strip() for item in reason_codes if str(item).strip()) + if values: + return values + return () + + +def _build_strategy_plugin_alert_reason_summary( + signal: StrategyPluginSignal, + *, + translator: Callable[..., str] | None = None, +) -> str: + locale = _strategy_plugin_alert_locale(translator=translator) + reasons = _strategy_plugin_reason_values(signal, locale=locale) + if not reasons: + return _translate( + translator, + "strategy_plugin_alert_reason_none", + fallback="no explicit reason provided", + ) + joiner = _translate(translator, "strategy_plugin_alert_reason_joiner", fallback=", ") + return str(joiner).join(reasons) + + +def build_strategy_plugin_alert_reason_summary( + signal: StrategyPluginSignal | Any, + *, + translator: Callable[..., str] | None = None, +) -> str: + return _build_strategy_plugin_alert_reason_summary( + _coerce_strategy_plugin_signal(signal), + translator=translator, + ) + + +def _alert_narrative_keys(kind: str, signal: StrategyPluginSignal) -> tuple[str, ...]: + plugin = signal.normalized_plugin + route = signal.normalized_route + action = signal.normalized_action + return ( + f"strategy_plugin_{kind}_{plugin}_{route}_{action}", + f"strategy_plugin_{kind}_{plugin}_{route}", + f"strategy_plugin_{kind}_{plugin}_{action}", + f"strategy_plugin_{kind}_{route}_{action}", + f"strategy_plugin_{kind}_{route}", + f"strategy_plugin_{kind}_{action}", + f"strategy_plugin_{kind}_default", + ) + + +def _build_strategy_plugin_alert_situation( + signal: StrategyPluginSignal, + *, + translator: Callable[..., str] | None = None, + reasons: str | None = None, +) -> str: + resolved_reasons = ( + reasons + if reasons is not None + else _build_strategy_plugin_alert_reason_summary(signal, translator=translator) + ) + translated = _translate_first( + translator, + _alert_narrative_keys("situation", signal), + reasons=resolved_reasons, + ) + if translated: + return translated + return f"The plugin found a market state that needs attention. Trigger: {resolved_reasons}." + + +def build_strategy_plugin_alert_situation( + signal: StrategyPluginSignal | Any, + *, + translator: Callable[..., str] | None = None, +) -> str: + return _build_strategy_plugin_alert_situation( + _coerce_strategy_plugin_signal(signal), + translator=translator, + ) + + +def _build_strategy_plugin_alert_recommendation( + signal: StrategyPluginSignal, + *, + translator: Callable[..., str] | None = None, +) -> str: + translated = _translate_first( + translator, + _alert_narrative_keys("recommendation", signal), + ) + if translated: + return translated + return ( + "Review manually first, then decide whether the action belongs to strategy rules or a manual process; " + "do not treat the plugin notice as a trade instruction." + ) + + +def build_strategy_plugin_alert_recommendation( + signal: StrategyPluginSignal | Any, + *, + translator: Callable[..., str] | None = None, +) -> str: + return _build_strategy_plugin_alert_recommendation( + _coerce_strategy_plugin_signal(signal), + translator=translator, + ) + + +def _strategy_plugin_alert_display_context( + raw_context: str, + signal: StrategyPluginSignal, + *, + target_label: str, + translator: Callable[..., str] | None = None, +) -> str: + context = str(raw_context or "").strip() + if not context: + return "" + normalized = context.strip().lower() + notification_target = signal.notification_target + if normalized == f"strategy-plugin-publish / {notification_target}".lower() and notification_target: + return _translate( + translator, + "strategy_plugin_alert_context_strategy_plugin_publish", + fallback="plugin publish / {target}", + target=target_label, + ) + return context + + +def _build_strategy_plugin_ai_audit_note( + signal: StrategyPluginSignal, + *, + translator: Callable[..., str] | None = None, +) -> str | None: + ai_audit = signal.payload.get("ai_audit") + if not isinstance(ai_audit, Mapping) or not _as_bool(ai_audit.get("enabled"), default=False): + return None + status = _normalize_strategy_plugin_field(_optional_string(ai_audit.get("status"))) + if status == "ok": + verdict = _optional_string(ai_audit.get("verdict")) or "unknown" + assessment = _optional_string(ai_audit.get("route_assessment")) or "unknown" + summary = _optional_string(ai_audit.get("summary")) or "no summary" + return _translate( + translator, + "strategy_plugin_alert_ai_audit", + fallback="AI audit: {status} | verdict={verdict} | assessment={assessment} | {summary}", + status=status, + verdict=verdict, + assessment=assessment, + summary=summary, + ) + reason = _optional_string(ai_audit.get("skip_reason")) or _optional_string(ai_audit.get("error")) or "no detail" + return _translate( + translator, + "strategy_plugin_alert_ai_audit_status", + fallback="AI audit: {status} | {reason}", + status=status, + reason=reason, + ) + + +def build_strategy_plugin_ai_audit_note( + signal: StrategyPluginSignal | Any, + *, + translator: Callable[..., str] | None = None, +) -> str | None: + return _build_strategy_plugin_ai_audit_note( + _coerce_strategy_plugin_signal(signal), + translator=translator, + ) + + +def _build_strategy_plugin_alert_key( + signal: StrategyPluginSignal, + *, + strategy_label: str | None = None, + context_label: str | None = None, + namespace: str = "strategy_plugin_alert", +) -> str: + target_label = ( + signal.strategy + or signal.notification_target + or _optional_key_part(strategy_label) + or "unknown" + ) + payload = { + "namespace": _optional_key_part(namespace) or "strategy_plugin_alert", + "context": _optional_key_part(context_label) or "default", + "target_type": signal.target_type or "strategy", + "target": target_label, + "plugin": signal.plugin or "unknown", + "mode": signal.effective_mode or "unknown", + "as_of": signal.as_of or "unknown", + "route": signal.canonical_route or "unknown", + "action": signal.suggested_action or "unknown", + "would_trade_if_enabled": signal.would_trade_if_enabled, + } + digest = hashlib.sha256( + json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8") + ).hexdigest()[:16] + return "/".join( + ( + _sanitize_key_part(payload["namespace"]), + _sanitize_key_part(payload["context"]), + _sanitize_key_part(payload["target"]), + _sanitize_key_part(payload["plugin"]), + _sanitize_key_part(payload["as_of"]), + _sanitize_key_part(payload["route"]), + _sanitize_key_part(payload["action"]), + digest, + ) + ) + + +def build_strategy_plugin_alert_key( + signal: StrategyPluginSignal | Any, + *, + strategy_label: str | None = None, + context_label: str | None = None, + namespace: str = "strategy_plugin_alert", +) -> str: + return _build_strategy_plugin_alert_key( + _coerce_strategy_plugin_signal(signal), + strategy_label=strategy_label, + context_label=context_label, + namespace=namespace, + ) + + +def build_strategy_plugin_alert_messages( + signals: Sequence[StrategyPluginSignal | Any], + *, + translator: Callable[..., str] | None = None, + strategy_label: str | None = None, + context_label: str | None = None, + alert_namespace: str = "strategy_plugin_alert", +) -> tuple[StrategyPluginAlertMessage, ...]: + messages: list[StrategyPluginAlertMessage] = [] + context = str(context_label or "").strip() + for raw_signal in signals: + signal = _coerce_strategy_plugin_signal(raw_signal) + if not _should_alert_strategy_plugin_signal(signal): + continue + route = signal.canonical_route or "unknown_route" + action = signal.suggested_action or "unknown_action" + plugin = translate_strategy_plugin_value("name", signal.plugin, translator=translator) + translated_mode = translate_strategy_plugin_value( + "mode", + signal.effective_mode, + translator=translator, + ) + translated_route = translate_strategy_plugin_value("route", route, translator=translator) + translated_action = translate_strategy_plugin_value("action", action, translator=translator) + target_type = signal.target_type + strategy = str(strategy_label or signal.strategy or "").strip() + notification_target = signal.notification_target + target_label = strategy or notification_target or "unknown" + display_target_label = target_label + if target_type == "notification_target" and notification_target: + display_target_label = translate_strategy_plugin_value( + "notification_target", + notification_target, + translator=translator, + ) + elif strategy: + display_target_label = translate_strategy_plugin_value("strategy", strategy, translator=translator) + # Presentation only: target_label still supplies alert keys and machine metadata. + display_target_label = display_name( + "strategies", + signal.strategy or strategy, + "zh" if _translator_uses_zh(translator) else "en", + fallback=display_target_label, + ) + display_context = _strategy_plugin_alert_display_context( + context, + signal, + target_label=display_target_label, + translator=translator, + ) + target_name_key = ( + "strategy_plugin_alert_target_name_notification_target" + if target_type == "notification_target" + else "strategy_plugin_alert_target_name_strategy" + ) + target_name = _translate( + translator, + target_name_key, + fallback="Notification target" if target_type == "notification_target" else "Strategy", + ) + guidance = _build_strategy_plugin_alert_guidance(signal, translator=translator) + reason_summary = _build_strategy_plugin_alert_reason_summary(signal, translator=translator) + situation = _build_strategy_plugin_alert_situation( + signal, + translator=translator, + reasons=reason_summary, + ) + recommendation = _build_strategy_plugin_alert_recommendation(signal, translator=translator) + scope_note = _build_strategy_plugin_alert_scope_note(signal, translator=translator) + ai_audit_note = _build_strategy_plugin_ai_audit_note(signal, translator=translator) + subject = _translate( + translator, + "strategy_plugin_alert_subject", + fallback="Strategy plugin alert: {plugin} | {route}", + strategy=display_target_label, + plugin=plugin, + route=translated_route, + ) + if display_context: + subject = f"[{display_context}] {subject}" + body_lines = [ + _translate(translator, "strategy_plugin_alert_title", fallback="Strategy Plugin Alert"), + "", + ] + if display_context: + body_lines.append( + _translate( + translator, + "strategy_plugin_alert_context", + fallback="Context: {context}", + context=display_context, + ) + ) + body_lines.extend( + [ + _translate( + translator, + "strategy_plugin_alert_target", + fallback="{target_name}: {target}", + target_name=target_name, + target=display_target_label, + ), + _translate( + translator, + "strategy_plugin_alert_plugin", + fallback="Plugin: {plugin}", + plugin=plugin, + ), + _translate( + translator, + "strategy_plugin_alert_as_of", + fallback="Signal as-of: {as_of}", + as_of=signal.as_of or "unknown", + ), + _translate( + translator, + "strategy_plugin_alert_situation", + fallback="Situation: {situation}", + situation=situation, + ), + _translate( + translator, + "strategy_plugin_alert_trigger", + fallback="Trigger: {reasons}", + reasons=reason_summary, + ), + _translate( + translator, + "strategy_plugin_alert_recommendation", + fallback="Suggested review: {recommendation}", + recommendation=recommendation, + ), + _translate( + translator, + "strategy_plugin_alert_status", + fallback="Status: {route}", + route=translated_route, + ), + _translate( + translator, + "strategy_plugin_alert_action", + fallback="Notice: {action}", + action=translated_action, + ), + _translate( + translator, + "strategy_plugin_alert_mode", + fallback="Mode: {mode}", + mode=translated_mode, + ), + ] + ) + if guidance: + body_lines.append( + _translate( + translator, + "strategy_plugin_alert_guidance", + fallback="Manual guidance: {guidance}", + guidance=guidance, + ) + ) + if ai_audit_note: + body_lines.append(ai_audit_note) + if scope_note: + body_lines.append( + _translate( + translator, + "strategy_plugin_alert_scope_note", + fallback="Scope: {scope_note}", + scope_note=scope_note, + ) + ) + metadata = { + "target_type": target_type, + "target": target_label, + "strategy": signal.strategy, + "strategy_label": strategy or None, + "notification_target": notification_target or None, + "plugin": signal.plugin, + "mode": signal.effective_mode, + "as_of": signal.as_of, + "canonical_route": signal.canonical_route, + "suggested_action": signal.suggested_action, + "would_trade_if_enabled": signal.would_trade_if_enabled, + "context_label": context or None, + "display_context_label": display_context or None, + "display_target": display_target_label, + "situation": situation, + "recommendation": recommendation, + "reason_summary": reason_summary, + "guidance": guidance, + "scope_note": scope_note, + "ai_audit": signal.payload.get("ai_audit"), + } + messages.append( + StrategyPluginAlertMessage( + subject=subject, + body="\n".join(body_lines), + alert_key=_build_strategy_plugin_alert_key( + signal, + strategy_label=target_label, + context_label=context, + namespace=alert_namespace, + ), + metadata=metadata, + ) + ) + return tuple(messages) + diff --git a/src/quant_platform_kit/common/_strategy_plugin_consumption.py b/src/quant_platform_kit/common/_strategy_plugin_consumption.py new file mode 100644 index 00000000..b9efcfce --- /dev/null +++ b/src/quant_platform_kit/common/_strategy_plugin_consumption.py @@ -0,0 +1,147 @@ +"""Runtime consumption policy & summary helpers for strategy plugins.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import Any, Callable + +from quant_platform_kit.common._strategy_plugin_helpers import ( + _as_bool, + _normalize_strategy_plugin_field, + _optional_string, + _translate, +) +from quant_platform_kit.common._strategy_plugin_models import ( + STRATEGY_PLUGIN_AUTOMATED_POSITION_ACTIONS, + STRATEGY_PLUGIN_DIRECT_POSITION_CONTROL_ALLOWED, + StrategyPluginSignal, + _strategy_plugin_consumption_policy, +) + +def _strategy_plugin_enabled_label( + signal: StrategyPluginSignal, + *, + translator: Callable[..., str] | None = None, +) -> str: + return _translate( + translator, + f"strategy_plugin_enabled_{str(signal.enabled).lower()}", + fallback="yes" if signal.enabled else "no", + ) + + +def _strategy_plugin_value_is_present(value: Any) -> bool: + if value is None: + return False + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + return value != 0 + if isinstance(value, str): + normalized = value.strip().lower() + return bool(normalized) and normalized not in {"none", "null", "unbounded", "unlimited", "infinite", "inf"} + if isinstance(value, Mapping): + return any(_strategy_plugin_value_is_present(item) for item in value.values()) + if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): + return any(_strategy_plugin_value_is_present(item) for item in value) + return bool(value) + + +def _strategy_plugin_find_field_value(value: Any, field_names: frozenset[str]) -> Any | None: + if isinstance(value, Mapping): + for key, item in value.items(): + if key in field_names and _strategy_plugin_value_is_present(item): + return item + found = _strategy_plugin_find_field_value(item, field_names) + if found is not None: + return found + elif isinstance(value, Sequence) and not isinstance(value, (str, bytes)): + for item in value: + found = _strategy_plugin_find_field_value(item, field_names) + if found is not None: + return found + return None + + +def _strategy_plugin_has_auditable_position_control(signal: StrategyPluginSignal) -> bool: + if not _strategy_plugin_policy_allows_position_control(signal): + return False + if _strategy_plugin_consumption_status(signal) != "automation_approved": + return False + evidence_sources: tuple[Any, ...] = (signal.execution_controls, signal.payload) + return all( + _strategy_plugin_find_field_value(evidence_sources, field_names) is not None + for field_names in ( + frozenset({"evidence_package_id", "evidence_package", "package_id"}), + frozenset( + { + "evidence_valid_until", + "evidence_valid_until_at", + "evidence_expires_at", + "valid_until", + "valid_until_at", + "expires_at", + } + ), + frozenset({"bounded_budget", "budget", "budget_limit"}), + ) + ) + + +def _strategy_plugin_consumption_status(signal: StrategyPluginSignal) -> str: + status = _optional_string(signal.execution_controls.get("consumption_evidence_status")) + if status is None: + status = _optional_string(_strategy_plugin_consumption_policy(signal).get("evidence_status")) + return _normalize_strategy_plugin_field(status) + + +def _strategy_plugin_policy_allows_position_control(signal: StrategyPluginSignal) -> bool: + if not STRATEGY_PLUGIN_DIRECT_POSITION_CONTROL_ALLOWED: + return False + controls = signal.execution_controls + if "position_control_allowed" in controls: + return _as_bool(controls.get("position_control_allowed"), default=False) + return _as_bool( + _strategy_plugin_consumption_policy(signal).get("position_control_allowed"), + default=False, + ) + + +def _strategy_plugin_is_notification_only(signal: StrategyPluginSignal) -> bool: + controls = signal.execution_controls + policy = _strategy_plugin_consumption_policy(signal) + if _strategy_plugin_consumption_status(signal) == "notification_only": + return True + if str(controls.get("capital_impact") or policy.get("capital_impact") or "").strip().lower() == "notification_only": + return True + if str(controls.get("notification_profile") or policy.get("notification_profile") or "").strip().lower() == "shadow_only": + return True + return False + + +def _strategy_plugin_auto_consumption_allowed(signal: StrategyPluginSignal, *, action: str) -> bool: + if _is_strategy_position_control_notice(signal, action=action): + return True + if signal.execution_controls: + return False + return bool( + action in STRATEGY_PLUGIN_AUTOMATED_POSITION_ACTIONS + and _strategy_plugin_policy_allows_position_control(signal) + and _strategy_plugin_consumption_status(signal) == "automation_approved" + and _strategy_plugin_has_auditable_position_control(signal) + ) + + +def _is_strategy_position_control_notice(signal: StrategyPluginSignal, *, action: str | None = None) -> bool: + """Return true when strategy runtime should carry the alert instead of the plugin bot.""" + + if signal.normalized_target_type != "strategy": + return False + normalized_action = action if action is not None else signal.normalized_action + if normalized_action not in STRATEGY_PLUGIN_AUTOMATED_POSITION_ACTIONS: + return False + if not _as_bool(signal.execution_controls.get("strategy_runtime_metadata_allowed"), default=False): + return False + return _strategy_plugin_has_auditable_position_control(signal) + + diff --git a/src/quant_platform_kit/common/_strategy_plugin_helpers.py b/src/quant_platform_kit/common/_strategy_plugin_helpers.py new file mode 100644 index 00000000..5daa0112 --- /dev/null +++ b/src/quant_platform_kit/common/_strategy_plugin_helpers.py @@ -0,0 +1,145 @@ +"""Internal shared helpers for strategy plugin loading, consumption, and alerts.""" + +from __future__ import annotations + +import tempfile +from pathlib import Path +from typing import Any, Callable, Sequence + +from quant_platform_kit.common.strategy_plugin_artifacts import ( + cache_path_for_remote_artifact, + download_remote_object, + materialize_local_or_remote_artifact, + parse_cloud_uri, +) + +DEFAULT_PLUGIN_ARTIFACT_CACHE_DIR = Path(tempfile.gettempdir()) / "quant_strategy_plugin_artifacts" + +def _compact_strategy_plugin_error(error: object, *, max_chars: int = 240) -> str: + text = " ".join(str(error or "").split()) + if not text: + return "" + if len(text) <= max_chars: + return text + return text[: max_chars - 1].rstrip() + "…" + + +def _optional_key_part(value: Any) -> str | None: + if value is None: + return None + text = str(value).strip() + return text or None + + +def _sanitize_key_part(value: Any) -> str: + text = str(value or "").strip().lower() + chars: list[str] = [] + previous_dash = False + for char in text: + if char.isalnum() or char in {"_", "."}: + chars.append(char) + previous_dash = False + elif not previous_dash: + chars.append("-") + previous_dash = True + sanitized = "".join(chars).strip("-._") + return sanitized[:80] or "unknown" + + +def _materialize_artifact_path(reference: str, *, client_factory: Any = None) -> tuple[Path, dict[str, str | None]]: + return materialize_local_or_remote_artifact( + reference, + cache_dir=DEFAULT_PLUGIN_ARTIFACT_CACHE_DIR, + client_factory=client_factory, + ) + + +def _download_remote_object(uri: str, destination: Path, *, client_factory: Any = None) -> None: + download_remote_object(uri, destination, client_factory=client_factory) + + +def _parse_cloud_uri(uri: str) -> tuple[str, str]: + return parse_cloud_uri(uri) + + +def _cache_path_for_remote_artifact(reference: str) -> Path: + return cache_path_for_remote_artifact(reference, cache_dir=DEFAULT_PLUGIN_ARTIFACT_CACHE_DIR) + + +def _as_bool(value: Any, *, default: bool = False) -> bool: + if value is None: + return default + if isinstance(value, bool): + return value + return str(value).strip().lower() in {"1", "true", "yes", "y", "on"} + + +def _optional_string(value: Any) -> str | None: + if value is None: + return None + text = str(value).strip() + return text or None + + +def _normalize_strategy_plugin_field(value: str | None) -> str: + return str(value or "").strip().lower() or "unknown" + + +def _translate( + translator: Callable[..., str] | None, + key: str, + *, + fallback: str, + **kwargs: Any, +) -> str: + if translator is None: + return fallback.format(**kwargs) + try: + translated = translator(key, **kwargs) + except TypeError: + translated = translator(key) + return translated if translated != key else fallback.format(**kwargs) + + +def _translator_uses_zh(translator: Callable[..., str] | None) -> bool: + if translator is None: + return False + for key in ("strategy_plugin_alert_locale", "no_trades"): + try: + sample = str(translator(key)) + except Exception: + continue + if sample.strip().lower().startswith("zh"): + return True + if any("\u4e00" <= char <= "\u9fff" for char in sample): + return True + return False + + +def _translate_first( + translator: Callable[..., str] | None, + keys: Sequence[str], + **kwargs: Any, +) -> str | None: + if translator is None: + return None + for key in keys: + if kwargs: + try: + translated = translator(key, **kwargs) + except TypeError: + translated = translator(key) + else: + translated = translator(key) + if translated != key: + text = str(translated).strip() + if text: + return text + return None + + +def _required_string(value: Any, *, field_name: str) -> str: + text = _optional_string(value) + if text is None: + raise ValueError(f"{field_name} is required") + return text diff --git a/src/quant_platform_kit/common/_strategy_plugin_loading.py b/src/quant_platform_kit/common/_strategy_plugin_loading.py new file mode 100644 index 00000000..ab370bc5 --- /dev/null +++ b/src/quant_platform_kit/common/_strategy_plugin_loading.py @@ -0,0 +1,594 @@ +"""Config parsers, payload validators, and artifact loaders for strategy plugins.""" + +from __future__ import annotations + +import json +from collections.abc import Mapping, Sequence +from dataclasses import replace as dataclass_replace +from typing import Any + +from quant_platform_kit.common._strategy_plugin_helpers import ( + _as_bool, + _materialize_artifact_path, + _optional_string, + _required_string, +) +from quant_platform_kit.common._strategy_plugin_models import ( + STRATEGY_PLUGIN_NOTIFICATION_TARGETS, + StrategyPluginDefinition, + StrategyPluginMountConfig, + StrategyPluginNotificationTargetConfig, + StrategyPluginSignal, + normalize_strategy_plugin_definitions, + normalize_strategy_plugin_mode, +) + +def validate_strategy_plugin_compatibility( + *, + strategy: str, + plugin: str, + mode: str | None = None, + plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, + source: str = "plugin", +) -> None: + strategy_name = _required_string(strategy, field_name="strategy") + plugin_name = _required_string(plugin, field_name="plugin") + definitions = normalize_strategy_plugin_definitions(plugin_definitions) + definition = definitions.get(plugin_name) + if definition is None: + return + if not definition.supports_strategy(strategy_name): + allowed = ", ".join(sorted(definition.supported_strategies or ())) or "any" + raise ValueError( + f"strategy plugin {plugin_name} does not support strategy {strategy_name} " + f"in {source}; supported strategies: {allowed}" + ) + if mode is None: + return + mode_name = normalize_strategy_plugin_mode(mode, field_name="mode") + if mode_name not in definition.supported_modes: + allowed_modes = ", ".join(sorted(definition.supported_modes)) + raise ValueError( + f"strategy plugin {plugin_name} does not support mode {mode_name} " + f"in {source}; supported modes: {allowed_modes}" + ) + + +def validate_strategy_plugin_notification_target( + *, + notification_target: str, + plugin: str, + source: str = "plugin", +) -> None: + target_name = _required_string(notification_target, field_name="notification_target") + plugin_name = _required_string(plugin, field_name="plugin") + allowed_targets = STRATEGY_PLUGIN_NOTIFICATION_TARGETS.get(plugin_name, frozenset()) + if target_name not in allowed_targets: + allowed = ", ".join(sorted(allowed_targets)) or "(none)" + raise ValueError( + f"strategy plugin {plugin_name} does not support notification target {target_name} " + f"in {source}; supported notification targets: {allowed}" + ) + + +def validate_strategy_plugin_schema_version( + *, + plugin: str, + schema_version: str | None, + expected_schema_version: str | None = None, + plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, + source: str = "artifact", +) -> None: + plugin_name = _required_string(plugin, field_name="plugin") + normalized_schema_version = _optional_string(schema_version) + normalized_expected_schema_version = _optional_string(expected_schema_version) + if normalized_expected_schema_version is not None and normalized_schema_version != normalized_expected_schema_version: + raise ValueError( + "strategy plugin artifact schema_version mismatch: " + f"expected {normalized_expected_schema_version}, got {normalized_schema_version or ''}" + ) + definitions = normalize_strategy_plugin_definitions(plugin_definitions) + definition = definitions.get(plugin_name) + if definition is None or not definition.supported_schema_versions or normalized_schema_version is None: + return + if normalized_schema_version not in definition.supported_schema_versions: + allowed = ", ".join(sorted(definition.supported_schema_versions)) + raise ValueError( + f"strategy plugin {plugin_name} does not support schema_version {normalized_schema_version} " + f"in {source}; supported schema versions: {allowed}" + ) + + +def parse_strategy_plugin_mounts( + raw_config: str | Sequence[Mapping[str, Any]] | Mapping[str, Any] | None, + *, + plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, +) -> tuple[StrategyPluginMountConfig, ...]: + if raw_config is None or raw_config == "": + return () + definitions = normalize_strategy_plugin_definitions(plugin_definitions) + payload: Any + if isinstance(raw_config, str): + payload = json.loads(raw_config) + else: + payload = raw_config + + if isinstance(payload, Mapping): + payload = payload.get("strategy_plugins", payload.get("plugins", ())) + if not isinstance(payload, Sequence) or isinstance(payload, (str, bytes)): + raise ValueError("strategy plugin mount config must be a JSON list or object with strategy_plugins") + + mounts: list[StrategyPluginMountConfig] = [] + seen: set[tuple[str, str]] = set() + for item in payload: + if not isinstance(item, Mapping): + raise ValueError("each strategy plugin mount must be an object") + if "mode" in item: + raise ValueError("platform plugin mount config must not set mode; read mode from the plugin artifact") + strategy = _required_string(item.get("strategy"), field_name="strategy") + plugin = _required_string(item.get("plugin"), field_name="plugin") + signal_path = _required_string( + item.get("signal_path") or item.get("latest_signal_path") or item.get("path"), + field_name="signal_path", + ) + key = (strategy, plugin) + if key in seen: + raise ValueError(f"duplicate strategy plugin mount: strategy={strategy} plugin={plugin}") + seen.add(key) + expected_mode = item.get("expected_mode") + normalized_expected_mode = ( + normalize_strategy_plugin_mode(expected_mode, field_name="expected_mode") + if expected_mode is not None + else None + ) + expected_schema_version = _optional_string(item.get("expected_schema_version")) + validate_strategy_plugin_schema_version( + plugin=plugin, + schema_version=expected_schema_version, + expected_schema_version=expected_schema_version, + plugin_definitions=definitions, + source="mount", + ) + validate_strategy_plugin_compatibility( + strategy=strategy, + plugin=plugin, + mode=normalized_expected_mode, + plugin_definitions=definitions, + source="mount", + ) + mounts.append( + StrategyPluginMountConfig( + strategy=strategy, + plugin=plugin, + signal_path=signal_path, + enabled=_as_bool(item.get("enabled"), default=True), + expected_mode=normalized_expected_mode, + expected_schema_version=expected_schema_version, + ) + ) + return tuple(mounts) + + +def parse_strategy_plugin_notification_targets( + raw_config: str | Sequence[Mapping[str, Any]] | Mapping[str, Any] | None, + *, + plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, +) -> tuple[StrategyPluginNotificationTargetConfig, ...]: + if raw_config is None or raw_config == "": + return () + definitions = normalize_strategy_plugin_definitions(plugin_definitions) + payload: Any + if isinstance(raw_config, str): + payload = json.loads(raw_config) + else: + payload = raw_config + + if isinstance(payload, Mapping): + payload = payload.get("notification_targets", ()) + if not isinstance(payload, Sequence) or isinstance(payload, (str, bytes)): + raise ValueError("strategy plugin notification target config must be a JSON list or object with notification_targets") + + targets: list[StrategyPluginNotificationTargetConfig] = [] + seen: set[tuple[str, str]] = set() + for item in payload: + if not isinstance(item, Mapping): + raise ValueError("each strategy plugin notification target must be an object") + if "mode" in item: + raise ValueError("notification target config must not set mode; read mode from the plugin artifact") + notification_target = _required_string(item.get("notification_target"), field_name="notification_target") + plugin = _required_string(item.get("plugin"), field_name="plugin") + signal_path = _required_string( + item.get("signal_path") or item.get("latest_signal_path") or item.get("path"), + field_name="signal_path", + ) + key = (notification_target, plugin) + if key in seen: + raise ValueError( + f"duplicate strategy plugin notification target: notification_target={notification_target} plugin={plugin}" + ) + seen.add(key) + expected_mode = item.get("expected_mode") + normalized_expected_mode = ( + normalize_strategy_plugin_mode(expected_mode, field_name="expected_mode") + if expected_mode is not None + else None + ) + expected_schema_version = _optional_string(item.get("expected_schema_version")) + validate_strategy_plugin_schema_version( + plugin=plugin, + schema_version=expected_schema_version, + expected_schema_version=expected_schema_version, + plugin_definitions=definitions, + source="notification_target", + ) + validate_strategy_plugin_notification_target( + notification_target=notification_target, + plugin=plugin, + source="notification_target", + ) + targets.append( + StrategyPluginNotificationTargetConfig( + notification_target=notification_target, + plugin=plugin, + signal_path=signal_path, + enabled=_as_bool(item.get("enabled"), default=True), + expected_mode=normalized_expected_mode, + expected_schema_version=expected_schema_version, + ) + ) + return tuple(targets) + + +def load_configured_strategy_plugin_signals( + mounts: Sequence[StrategyPluginMountConfig], + *, + strategy_profile: str | None = None, + client_factory: Any = None, + plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, +) -> tuple[StrategyPluginSignal, ...]: + selected_strategy = _optional_string(strategy_profile) + definitions = normalize_strategy_plugin_definitions(plugin_definitions) + signals: list[StrategyPluginSignal] = [] + for mount in mounts: + if not mount.enabled: + continue + if selected_strategy is not None and mount.strategy != selected_strategy: + continue + validate_strategy_plugin_compatibility( + strategy=mount.strategy, + plugin=mount.plugin, + mode=mount.expected_mode, + plugin_definitions=definitions, + source="mount", + ) + signals.append( + load_strategy_plugin_signal( + mount.signal_path, + expected_strategy=mount.strategy, + expected_plugin=mount.plugin, + expected_mode=mount.expected_mode, + expected_schema_version=mount.expected_schema_version, + client_factory=client_factory, + plugin_definitions=definitions, + ) + ) + return tuple(signals) + + +def load_configured_strategy_plugin_notification_target_signals( + targets: Sequence[StrategyPluginNotificationTargetConfig], + *, + notification_target: str | None = None, + client_factory: Any = None, + plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, +) -> tuple[StrategyPluginSignal, ...]: + selected_target = _optional_string(notification_target) + definitions = normalize_strategy_plugin_definitions(plugin_definitions) + signals: list[StrategyPluginSignal] = [] + for target in targets: + if not target.enabled: + continue + if selected_target is not None and target.notification_target != selected_target: + continue + validate_strategy_plugin_notification_target( + notification_target=target.notification_target, + plugin=target.plugin, + source="notification_target", + ) + signals.append( + load_strategy_plugin_signal( + target.signal_path, + expected_notification_target=target.notification_target, + expected_plugin=target.plugin, + expected_mode=target.expected_mode, + expected_schema_version=target.expected_schema_version, + client_factory=client_factory, + plugin_definitions=definitions, + ) + ) + return tuple(signals) + + +def load_strategy_plugin_signal( + reference: str, + *, + expected_strategy: str | None = None, + expected_notification_target: str | None = None, + expected_plugin: str | None = None, + expected_mode: str | None = None, + expected_schema_version: str | None = None, + client_factory: Any = None, + plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, +) -> StrategyPluginSignal: + local_path, metadata = _materialize_artifact_path(reference, client_factory=client_factory) + if not local_path.exists(): + raise FileNotFoundError(f"strategy plugin signal not found: {local_path}") + payload = json.loads(local_path.read_text(encoding="utf-8")) + if not isinstance(payload, Mapping): + raise ValueError("strategy plugin signal must be a JSON object") + return validate_strategy_plugin_signal_payload( + payload, + expected_strategy=expected_strategy, + expected_notification_target=expected_notification_target, + expected_plugin=expected_plugin, + expected_mode=expected_mode, + expected_schema_version=expected_schema_version, + source_uri=metadata.get("source_uri"), + local_path=str(local_path), + plugin_definitions=plugin_definitions, + ) + + +def validate_strategy_plugin_signal_payload( + payload: Mapping[str, Any], + *, + expected_strategy: str | None = None, + expected_notification_target: str | None = None, + expected_plugin: str | None = None, + expected_mode: str | None = None, + expected_schema_version: str | None = None, + source_uri: str | None = None, + local_path: str | None = None, + plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, +) -> StrategyPluginSignal: + target_type = _optional_string(payload.get("target_type")) or ( + "notification_target" if _optional_string(payload.get("notification_target")) else "strategy" + ) + if target_type not in {"strategy", "notification_target"}: + raise ValueError(f"strategy plugin signal target_type must be strategy or notification_target; got {target_type!r}") + if target_type == "notification_target": + notification_target = _required_string(payload.get("notification_target"), field_name="notification_target") + strategy = _optional_string(payload.get("strategy")) or "" + else: + strategy = _required_string(payload.get("strategy"), field_name="strategy") + notification_target = _optional_string(payload.get("notification_target")) or "" + plugin = _required_string(payload.get("plugin"), field_name="plugin") + mode = normalize_strategy_plugin_mode(payload.get("mode"), field_name="mode") + configured_mode = normalize_strategy_plugin_mode( + payload.get("configured_mode", mode), + field_name="configured_mode", + ) + effective_mode = normalize_strategy_plugin_mode( + payload.get("effective_mode", mode), + field_name="effective_mode", + ) + + expected_strategy = _optional_string(expected_strategy) + expected_notification_target = _optional_string(expected_notification_target) + expected_plugin = _optional_string(expected_plugin) + if expected_strategy is not None and target_type != "strategy": + raise ValueError( + "strategy plugin artifact target mismatch: " + f"expected strategy {expected_strategy}, got notification target {notification_target}" + ) + if expected_strategy is not None and strategy != expected_strategy: + raise ValueError(f"strategy plugin artifact strategy mismatch: expected {expected_strategy}, got {strategy}") + if expected_notification_target is not None and target_type != "notification_target": + raise ValueError( + "strategy plugin artifact target mismatch: " + f"expected notification target {expected_notification_target}, got strategy {strategy}" + ) + if expected_notification_target is not None and notification_target != expected_notification_target: + raise ValueError( + "strategy plugin artifact notification_target mismatch: " + f"expected {expected_notification_target}, got {notification_target}" + ) + if expected_plugin is not None and plugin != expected_plugin: + raise ValueError(f"strategy plugin artifact plugin mismatch: expected {expected_plugin}, got {plugin}") + if expected_mode is not None: + normalized_expected_mode = normalize_strategy_plugin_mode(expected_mode, field_name="expected_mode") + if effective_mode != normalized_expected_mode: + raise ValueError( + "strategy plugin artifact mode mismatch: " + f"expected {normalized_expected_mode}, got {effective_mode}" + ) + if target_type == "strategy": + validate_strategy_plugin_compatibility( + strategy=strategy, + plugin=plugin, + mode=effective_mode, + plugin_definitions=plugin_definitions, + source="artifact", + ) + else: + validate_strategy_plugin_notification_target( + notification_target=notification_target, + plugin=plugin, + source="artifact", + ) + schema_version = _optional_string(payload.get("schema_version")) or "" + definitions = normalize_strategy_plugin_definitions(plugin_definitions) + definition = definitions.get(plugin) + if definition is not None and definition.supported_schema_versions and not schema_version: + raise ValueError(f"strategy plugin {plugin} artifact schema_version is required") + validate_strategy_plugin_schema_version( + plugin=plugin, + schema_version=schema_version, + expected_schema_version=expected_schema_version, + plugin_definitions=definitions, + source="artifact", + ) + + execution_controls = payload.get("execution_controls") or {} + if not isinstance(execution_controls, Mapping): + raise ValueError("strategy plugin signal execution_controls must be an object") + + return StrategyPluginSignal( + strategy=strategy, + plugin=plugin, + mode=mode, + configured_mode=configured_mode, + effective_mode=effective_mode, + schema_version=schema_version, + as_of=_optional_string(payload.get("as_of")) or "", + canonical_route=_optional_string(payload.get("canonical_route")), + suggested_action=_optional_string(payload.get("suggested_action")), + would_trade_if_enabled=_as_bool(payload.get("would_trade_if_enabled"), default=False), + execution_controls=execution_controls, + payload=dict(payload), + source_uri=_optional_string(source_uri), + local_path=_optional_string(local_path), + deprecated_plugin=bool(definition.deprecated) if definition is not None else False, + successor_plugin=definition.successor_plugin if definition is not None else None, + supported_schema_versions=tuple(sorted(definition.supported_schema_versions)) if definition is not None else (), + target_type=target_type, + notification_target=notification_target, + ) + + +def _coerce_strategy_plugin_signal(signal: Any) -> StrategyPluginSignal: + """Normalize a StrategyPluginSignal, Mapping, or duck-typed object at public boundaries.""" + if isinstance(signal, StrategyPluginSignal): + return signal + if isinstance(signal, Mapping): + def _read(key: str, default: Any = None) -> Any: + return signal.get(key, default) + else: + def _read(key: str, default: Any = None) -> Any: + return getattr(signal, key, default) + effective_mode = _optional_string(_read("effective_mode")) or "" + mode = _optional_string(_read("mode")) or effective_mode + configured_mode = _optional_string(_read("configured_mode")) or mode + return StrategyPluginSignal( + strategy=_read("strategy") or "", + plugin=_read("plugin") or "", + mode=mode, + configured_mode=configured_mode, + effective_mode=effective_mode or mode, + schema_version=_read("schema_version") or "", + as_of=_read("as_of") or "", + canonical_route=_read("canonical_route"), + suggested_action=_read("suggested_action"), + would_trade_if_enabled=_as_bool(_read("would_trade_if_enabled", False), default=False), + execution_controls=_read("execution_controls") or {}, + payload=_read("payload") or {}, + source_uri=_read("source_uri"), + local_path=_read("local_path"), + deprecated_plugin=bool(_read("deprecated_plugin", False)), + successor_plugin=_read("successor_plugin"), + supported_schema_versions=_read("supported_schema_versions") or (), + target_type=_read("target_type") or "strategy", + notification_target=_read("notification_target") or "", + enabled=_as_bool(_read("enabled", True), default=True), + ) + + +def build_strategy_plugin_report_payload( + signals: Sequence[StrategyPluginSignal | Any], +) -> dict[str, Any]: + summaries: list[dict[str, Any]] = [] + for raw_signal in signals: + if isinstance(raw_signal, StrategyPluginSignal): + summaries.append(raw_signal.report_summary()) + elif not isinstance(raw_signal, Mapping) and callable(getattr(raw_signal, "report_summary", None)): + summaries.append(raw_signal.report_summary()) + else: + summaries.append(_coerce_strategy_plugin_signal(raw_signal).report_summary()) + return { + "strategy_plugins": summaries, + } + + +def build_strategy_plugin_metadata( + signals: Sequence[StrategyPluginSignal | Any], +) -> dict[str, Any]: + """Build portfolio-snapshot metadata consumed by deterministic strategies.""" + plugin_payloads: dict[str, Any] = {} + summaries: dict[str, Any] = {} + for raw_signal in signals: + signal = _coerce_strategy_plugin_signal(raw_signal) + if not _as_bool( + signal.execution_controls.get("strategy_runtime_metadata_allowed"), + default=False, + ): + continue + if not signal.plugin: + continue + plugin_payloads[signal.plugin] = _build_non_authoritative_runtime_plugin_payload(signal.payload) + custom_summary = ( + getattr(raw_signal, "report_summary", None) + if not isinstance(raw_signal, (StrategyPluginSignal, Mapping)) + else None + ) + summaries[signal.plugin] = custom_summary() if callable(custom_summary) else signal.report_summary() + if not plugin_payloads: + return {} + metadata: dict[str, Any] = { + "strategy_plugins": plugin_payloads, + "strategy_plugin_summaries": summaries, + } + metadata.update(plugin_payloads) + return metadata + + +def _build_non_authoritative_runtime_plugin_payload(payload: Mapping[str, Any] | object) -> dict[str, Any]: + """Copy a sidecar payload for strategy metadata without delegation rights. + + The V2 plugin contract permits strategy metadata for deterministic + observability and research. It does not permit a plugin artifact to grant + itself allocation or broker authority. Preserve the original artifact on + ``StrategyPluginSignal.payload`` for audit, while making this injected copy + explicitly non-authoritative for every strategy consumer. + """ + + if not isinstance(payload, Mapping): + return {"strategy_runtime_metadata_non_authoritative": True} + normalized = dict(payload) + for control_key in ("execution_controls", "consumption_policy"): + source = payload.get(control_key) + if not isinstance(source, Mapping): + continue + controls = dict(source) + controls.update( + { + "broker_order_allowed": False, + "live_allocation_mutation_allowed": False, + "repository_broker_write_allowed": False, + "repository_allocation_mutation_allowed": False, + "position_control_allowed": False, + "consumption_evidence_status": "shadow_only", + } + ) + normalized[control_key] = controls + normalized["strategy_runtime_metadata_non_authoritative"] = True + return normalized + + +def attach_strategy_plugin_metadata(snapshot: Any, signals: Sequence[StrategyPluginSignal]) -> Any: + """Return a snapshot copy with plugin payloads attached to metadata.""" + plugin_metadata = build_strategy_plugin_metadata(signals) + if not plugin_metadata: + return snapshot + current_metadata = getattr(snapshot, "metadata", {}) or {} + if not isinstance(current_metadata, Mapping): + current_metadata = {} + merged_metadata = {**dict(current_metadata), **plugin_metadata} + try: + return dataclass_replace(snapshot, metadata=merged_metadata) + except TypeError: + try: + snapshot.metadata = merged_metadata + except Exception: + return snapshot + return snapshot + diff --git a/src/quant_platform_kit/common/_strategy_plugin_models.py b/src/quant_platform_kit/common/_strategy_plugin_models.py new file mode 100644 index 00000000..bea7b5a1 --- /dev/null +++ b/src/quant_platform_kit/common/_strategy_plugin_models.py @@ -0,0 +1,363 @@ +"""Constants and core data models for strategy plugin artifacts.""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from typing import Any + +from quant_platform_kit.common._strategy_plugin_helpers import _as_bool, _optional_string, _required_string + +PLUGIN_CRISIS_RESPONSE_SHADOW = "crisis_response_shadow" +PLUGIN_MARKET_REGIME_CONTROL = "market_regime_control" +PLUGIN_MACRO_RISK_GOVERNOR = "macro_risk_governor" +PLUGIN_TACO_REBOUND_SHADOW = "taco_rebound_shadow" +PLUGIN_PANIC_REVERSAL_SHADOW = "panic_reversal_shadow" +GENERAL_MARKET_REGIME_NOTIFICATION_TARGET = "market_regime_notification" +PLUGIN_MODE_SHADOW = "shadow" +STRATEGY_PLUGIN_ALERT_CHANNEL_EMAIL = "email" +STRATEGY_PLUGIN_ALERT_CHANNEL_SMS = "sms" +STRATEGY_PLUGIN_ALERT_CHANNEL_PUSH = "push" +STRATEGY_PLUGIN_ALERT_CHANNEL_TELEGRAM = "telegram" +STRATEGY_PLUGIN_ALERT_CHANNEL_WEBHOOK = "webhook" +SUPPORTED_STRATEGY_PLUGIN_MODES = frozenset({PLUGIN_MODE_SHADOW}) +STRATEGY_PLUGIN_NON_ALERT_ROUTES = frozenset({"no_action"}) +STRATEGY_PLUGIN_ALERT_ACTIONS = frozenset({"defend", "blocked"}) +STRATEGY_PLUGIN_AUTOMATED_POSITION_ACTIONS = frozenset({"defend", "delever"}) +# Legacy v1 artifacts may still carry position-control-shaped metadata for +# replay and display. The V2 sidecar contract makes that metadata +# non-authoritative: a plugin cannot directly mutate a strategy allocation. +STRATEGY_PLUGIN_DIRECT_POSITION_CONTROL_ALLOWED = False +CRISIS_RESPONSE_SHADOW_SUPPORTED_STRATEGIES = frozenset( + { + "tqqq_growth_income", + } +) +TACO_REBOUND_SHADOW_SUPPORTED_STRATEGIES = frozenset({"tqqq_growth_income"}) +MACRO_RISK_GOVERNOR_SUPPORTED_STRATEGIES = frozenset({"tqqq_growth_income"}) +MARKET_REGIME_CONTROL_SUPPORTED_STRATEGIES = frozenset( + { + "tqqq_growth_income", + "soxl_soxx_trend_income", + "global_etf_rotation", + "russell_top50_leader_rotation", + "russell_1000_multi_factor_defensive", + "mega_cap_leader_rotation_top50_balanced", + } +) +STRATEGY_PLUGIN_NOTIFICATION_TARGETS: Mapping[str, frozenset[str]] = { + PLUGIN_MARKET_REGIME_CONTROL: frozenset({GENERAL_MARKET_REGIME_NOTIFICATION_TARGET}), +} +STRATEGY_PLUGIN_SCHEMA_VERSIONS: Mapping[str, frozenset[str]] = { + PLUGIN_CRISIS_RESPONSE_SHADOW: frozenset({"crisis_response_shadow.v1"}), + PLUGIN_MARKET_REGIME_CONTROL: frozenset({"market_regime_control.v1"}), + PLUGIN_MACRO_RISK_GOVERNOR: frozenset({"macro_risk_governor.v1"}), + PLUGIN_TACO_REBOUND_SHADOW: frozenset({"taco_rebound_shadow.v2"}), +} + + +@dataclass(frozen=True) +class StrategyPluginDefinition: + plugin: str + supported_strategies: frozenset[str] | None = None + supported_modes: frozenset[str] = field(default_factory=lambda: SUPPORTED_STRATEGY_PLUGIN_MODES) + supported_schema_versions: frozenset[str] = field(default_factory=frozenset) + default_schema_version: str | None = None + deprecated: bool = False + successor_plugin: str | None = None + alert_channels: tuple[str, ...] = () + + def normalized(self) -> "StrategyPluginDefinition": + plugin = _required_string(self.plugin, field_name="plugin") + supported_strategies = ( + frozenset(_required_string(strategy, field_name="supported_strategy") for strategy in self.supported_strategies) + if self.supported_strategies is not None + else None + ) + supported_modes = frozenset( + normalize_strategy_plugin_mode(mode, field_name="supported_mode") + for mode in self.supported_modes + ) + if not supported_modes: + raise ValueError(f"strategy plugin definition for {plugin} must include at least one supported mode") + supported_schema_versions = frozenset( + _required_string(version, field_name="supported_schema_version") + for version in self.supported_schema_versions + ) + default_schema_version = _optional_string(self.default_schema_version) + if default_schema_version is not None and supported_schema_versions and default_schema_version not in supported_schema_versions: + raise ValueError( + f"strategy plugin definition for {plugin} default_schema_version must be listed in supported_schema_versions" + ) + successor_plugin = _optional_string(self.successor_plugin) + alert_channels = tuple( + _required_string(channel, field_name="alert_channel") + for channel in self.alert_channels + ) + return StrategyPluginDefinition( + plugin=plugin, + supported_strategies=supported_strategies, + supported_modes=supported_modes, + supported_schema_versions=supported_schema_versions, + default_schema_version=default_schema_version, + deprecated=bool(self.deprecated), + successor_plugin=successor_plugin, + alert_channels=alert_channels, + ) + + def supports_strategy(self, strategy: str) -> bool: + if self.supported_strategies is None: + return True + return strategy in self.supported_strategies + + +DEFAULT_STRATEGY_PLUGIN_DEFINITIONS: Mapping[str, StrategyPluginDefinition] = { + PLUGIN_CRISIS_RESPONSE_SHADOW: StrategyPluginDefinition( + plugin=PLUGIN_CRISIS_RESPONSE_SHADOW, + supported_strategies=CRISIS_RESPONSE_SHADOW_SUPPORTED_STRATEGIES, + supported_modes=SUPPORTED_STRATEGY_PLUGIN_MODES, + supported_schema_versions=STRATEGY_PLUGIN_SCHEMA_VERSIONS[PLUGIN_CRISIS_RESPONSE_SHADOW], + default_schema_version="crisis_response_shadow.v1", + deprecated=True, + successor_plugin=PLUGIN_MARKET_REGIME_CONTROL, + alert_channels=( + STRATEGY_PLUGIN_ALERT_CHANNEL_EMAIL, + STRATEGY_PLUGIN_ALERT_CHANNEL_SMS, + STRATEGY_PLUGIN_ALERT_CHANNEL_PUSH, + STRATEGY_PLUGIN_ALERT_CHANNEL_TELEGRAM, + ), + ), + PLUGIN_TACO_REBOUND_SHADOW: StrategyPluginDefinition( + plugin=PLUGIN_TACO_REBOUND_SHADOW, + supported_strategies=TACO_REBOUND_SHADOW_SUPPORTED_STRATEGIES, + supported_modes=SUPPORTED_STRATEGY_PLUGIN_MODES, + supported_schema_versions=STRATEGY_PLUGIN_SCHEMA_VERSIONS[PLUGIN_TACO_REBOUND_SHADOW], + default_schema_version="taco_rebound_shadow.v2", + deprecated=True, + successor_plugin=PLUGIN_MARKET_REGIME_CONTROL, + alert_channels=( + STRATEGY_PLUGIN_ALERT_CHANNEL_EMAIL, + STRATEGY_PLUGIN_ALERT_CHANNEL_SMS, + STRATEGY_PLUGIN_ALERT_CHANNEL_PUSH, + STRATEGY_PLUGIN_ALERT_CHANNEL_TELEGRAM, + ), + ), + PLUGIN_MARKET_REGIME_CONTROL: StrategyPluginDefinition( + plugin=PLUGIN_MARKET_REGIME_CONTROL, + supported_strategies=MARKET_REGIME_CONTROL_SUPPORTED_STRATEGIES, + supported_modes=SUPPORTED_STRATEGY_PLUGIN_MODES, + supported_schema_versions=STRATEGY_PLUGIN_SCHEMA_VERSIONS[PLUGIN_MARKET_REGIME_CONTROL], + default_schema_version="market_regime_control.v1", + alert_channels=( + STRATEGY_PLUGIN_ALERT_CHANNEL_EMAIL, + STRATEGY_PLUGIN_ALERT_CHANNEL_SMS, + STRATEGY_PLUGIN_ALERT_CHANNEL_PUSH, + STRATEGY_PLUGIN_ALERT_CHANNEL_TELEGRAM, + ), + ), + PLUGIN_MACRO_RISK_GOVERNOR: StrategyPluginDefinition( + plugin=PLUGIN_MACRO_RISK_GOVERNOR, + supported_strategies=MACRO_RISK_GOVERNOR_SUPPORTED_STRATEGIES, + supported_modes=SUPPORTED_STRATEGY_PLUGIN_MODES, + supported_schema_versions=STRATEGY_PLUGIN_SCHEMA_VERSIONS[PLUGIN_MACRO_RISK_GOVERNOR], + default_schema_version="macro_risk_governor.v1", + deprecated=True, + successor_plugin=PLUGIN_MARKET_REGIME_CONTROL, + alert_channels=( + STRATEGY_PLUGIN_ALERT_CHANNEL_EMAIL, + STRATEGY_PLUGIN_ALERT_CHANNEL_SMS, + STRATEGY_PLUGIN_ALERT_CHANNEL_PUSH, + STRATEGY_PLUGIN_ALERT_CHANNEL_TELEGRAM, + ), + ), +} + + +@dataclass(frozen=True) +class StrategyPluginMountConfig: + strategy: str + plugin: str + signal_path: str + enabled: bool = True + expected_mode: str | None = None + expected_schema_version: str | None = None + + +@dataclass(frozen=True) +class StrategyPluginNotificationTargetConfig: + notification_target: str + plugin: str + signal_path: str + enabled: bool = True + expected_mode: str | None = None + expected_schema_version: str | None = None + + +@dataclass(frozen=True) +class StrategyPluginSignal: + strategy: str + plugin: str + mode: str + configured_mode: str + effective_mode: str + schema_version: str + as_of: str + canonical_route: str | None = None + suggested_action: str | None = None + would_trade_if_enabled: bool = False + execution_controls: Mapping[str, Any] = field(default_factory=dict) + payload: Mapping[str, Any] = field(default_factory=dict) + source_uri: str | None = None + local_path: str | None = None + deprecated_plugin: bool = False + successor_plugin: str | None = None + supported_schema_versions: tuple[str, ...] = () + target_type: str = "strategy" + notification_target: str = "" + enabled: bool = True + + def __post_init__(self) -> None: + object.__setattr__(self, "strategy", _optional_string(self.strategy) or "") + object.__setattr__(self, "plugin", _optional_string(self.plugin) or "") + object.__setattr__(self, "mode", _optional_string(self.mode) or "") + object.__setattr__(self, "configured_mode", _optional_string(self.configured_mode) or "") + object.__setattr__(self, "effective_mode", _optional_string(self.effective_mode) or "") + object.__setattr__(self, "schema_version", _optional_string(self.schema_version) or "") + object.__setattr__(self, "as_of", _optional_string(self.as_of) or "") + object.__setattr__(self, "canonical_route", _optional_string(self.canonical_route)) + object.__setattr__(self, "suggested_action", _optional_string(self.suggested_action)) + object.__setattr__( + self, + "would_trade_if_enabled", + _as_bool(self.would_trade_if_enabled, default=False), + ) + controls = dict(self.execution_controls) if isinstance(self.execution_controls, Mapping) else {} + payload = dict(self.payload) if isinstance(self.payload, Mapping) else {} + object.__setattr__(self, "execution_controls", controls) + object.__setattr__(self, "payload", payload) + object.__setattr__(self, "source_uri", _optional_string(self.source_uri)) + object.__setattr__(self, "local_path", _optional_string(self.local_path)) + object.__setattr__(self, "deprecated_plugin", bool(self.deprecated_plugin)) + object.__setattr__(self, "successor_plugin", _optional_string(self.successor_plugin)) + versions = self.supported_schema_versions + if isinstance(versions, (str, bytes, Mapping)) or not isinstance(versions, Iterable): + normalized_versions: tuple[str, ...] = () + else: + normalized_versions = tuple( + item for item in (_optional_string(version) for version in versions) if item + ) + object.__setattr__(self, "supported_schema_versions", normalized_versions) + object.__setattr__(self, "target_type", _optional_string(self.target_type) or "strategy") + object.__setattr__(self, "notification_target", _optional_string(self.notification_target) or "") + object.__setattr__(self, "enabled", _as_bool(self.enabled, default=True)) + + @property + def normalized_plugin(self) -> str: + return self.plugin.lower() or "unknown" + + @property + def normalized_route(self) -> str: + return (self.canonical_route or "").lower() or "unknown" + + @property + def normalized_action(self) -> str: + return (self.suggested_action or "").lower() or "unknown" + + @property + def normalized_target_type(self) -> str: + return self.target_type.lower() or "strategy" + + def report_summary(self) -> dict[str, Any]: + return { + "strategy": self.strategy, + "target_type": self.target_type, + "notification_target": self.notification_target, + "plugin": self.plugin, + "mode": self.mode, + "configured_mode": self.configured_mode, + "effective_mode": self.effective_mode, + "schema_version": self.schema_version, + "deprecated_plugin": self.deprecated_plugin, + "successor_plugin": self.successor_plugin, + "supported_schema_versions": self.supported_schema_versions, + "as_of": self.as_of, + "canonical_route": self.canonical_route, + "suggested_action": self.suggested_action, + "would_trade_if_enabled": self.would_trade_if_enabled, + "execution_controls": dict(self.execution_controls), + "runtime_consumption": _strategy_plugin_runtime_consumption_summary(self), + "source_uri": self.source_uri, + "local_path": self.local_path, + } + + +def _strategy_plugin_consumption_policy(signal: StrategyPluginSignal) -> Mapping[str, Any]: + policy = signal.payload.get("consumption_policy") or {} + return policy if isinstance(policy, Mapping) else {} + + +def _strategy_plugin_runtime_consumption_summary(signal: StrategyPluginSignal) -> dict[str, Any]: + """Describe the authority actually granted to a loaded sidecar. + + Artifact controls remain in ``execution_controls`` as source evidence. This + separate summary prevents a legacy artifact from making a runtime report + look authorized when the shared runtime deliberately clamps all direct + position control to shadow-only metadata. + """ + + controls = signal.execution_controls + policy = _strategy_plugin_consumption_policy(signal) + artifact_position_control_requested = _as_bool( + controls.get("position_control_allowed"), default=False + ) or _as_bool(policy.get("position_control_allowed"), default=False) + direct_position_control_allowed = bool(STRATEGY_PLUGIN_DIRECT_POSITION_CONTROL_ALLOWED) + return { + "authority": ( + "direct_position_control" if direct_position_control_allowed else "shadow_only" + ), + "direct_position_control_allowed": direct_position_control_allowed, + "broker_order_allowed": False, + "live_allocation_mutation_allowed": False, + "runtime_metadata_non_authoritative": not direct_position_control_allowed, + "artifact_position_control_requested": artifact_position_control_requested, + "artifact_schema_is_legacy_v1": signal.schema_version.endswith(".v1"), + } + + + +@dataclass(frozen=True) +class StrategyPluginAlertMessage: + subject: str + body: str + alert_key: str = "" + metadata: Mapping[str, Any] = field(default_factory=dict) + + +def normalize_strategy_plugin_mode(value: Any, *, field_name: str = "mode") -> str: + mode = str(value or "").strip().lower() + if mode not in SUPPORTED_STRATEGY_PLUGIN_MODES: + modes = ", ".join(sorted(SUPPORTED_STRATEGY_PLUGIN_MODES)) + raise ValueError(f"{field_name} must be one of {modes}; got {value!r}") + return mode + + +def normalize_strategy_plugin_definitions( + plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, +) -> Mapping[str, StrategyPluginDefinition]: + raw_definitions = ( + DEFAULT_STRATEGY_PLUGIN_DEFINITIONS.values() + if plugin_definitions is None + else plugin_definitions.values() + if isinstance(plugin_definitions, Mapping) + else plugin_definitions + ) + definitions: dict[str, StrategyPluginDefinition] = {} + for definition in raw_definitions: + if not isinstance(definition, StrategyPluginDefinition): + raise TypeError("strategy plugin definitions must be StrategyPluginDefinition objects") + normalized = definition.normalized() + if normalized.plugin in definitions: + raise ValueError(f"duplicate strategy plugin definition: plugin={normalized.plugin}") + definitions[normalized.plugin] = normalized + return definitions + diff --git a/src/quant_platform_kit/common/strategy_plugins.py b/src/quant_platform_kit/common/strategy_plugins.py index 940dc538..5a7b021b 100644 --- a/src/quant_platform_kit/common/strategy_plugins.py +++ b/src/quant_platform_kit/common/strategy_plugins.py @@ -1,2090 +1,227 @@ -"""Shared runtime helpers for sidecar strategy plugin artifacts.""" +"""Shared runtime helpers for sidecar strategy plugin artifacts (compatibility facade).""" from __future__ import annotations -from .display_names import display_name -from .notification_localization import translator_uses_zh - -import hashlib -import json -import tempfile -from collections.abc import Iterable, Mapping, Sequence -from dataclasses import dataclass, field -from dataclasses import replace as dataclass_replace -from pathlib import Path -from typing import Any, Callable - -from quant_platform_kit.common.strategy_plugin_artifacts import ( - cache_path_for_remote_artifact, - download_remote_object, - materialize_local_or_remote_artifact, - parse_cloud_uri, +from quant_platform_kit.common._strategy_plugin_helpers import ( # noqa: F401 + DEFAULT_PLUGIN_ARTIFACT_CACHE_DIR, + _as_bool, + _cache_path_for_remote_artifact, + _compact_strategy_plugin_error, + _download_remote_object, + _download_remote_object as _download_gcs_object, + _materialize_artifact_path, + _normalize_strategy_plugin_field, + _optional_key_part, + _optional_string, + _parse_cloud_uri, + _parse_cloud_uri as _parse_gcs_uri, + _required_string, + _sanitize_key_part, + _translate, + _translate_first, + _translator_uses_zh, ) - -PLUGIN_CRISIS_RESPONSE_SHADOW = "crisis_response_shadow" -PLUGIN_MARKET_REGIME_CONTROL = "market_regime_control" -PLUGIN_MACRO_RISK_GOVERNOR = "macro_risk_governor" -PLUGIN_TACO_REBOUND_SHADOW = "taco_rebound_shadow" -PLUGIN_PANIC_REVERSAL_SHADOW = "panic_reversal_shadow" -GENERAL_MARKET_REGIME_NOTIFICATION_TARGET = "market_regime_notification" -PLUGIN_MODE_SHADOW = "shadow" -STRATEGY_PLUGIN_ALERT_CHANNEL_EMAIL = "email" -STRATEGY_PLUGIN_ALERT_CHANNEL_SMS = "sms" -STRATEGY_PLUGIN_ALERT_CHANNEL_PUSH = "push" -STRATEGY_PLUGIN_ALERT_CHANNEL_TELEGRAM = "telegram" -STRATEGY_PLUGIN_ALERT_CHANNEL_WEBHOOK = "webhook" -SUPPORTED_STRATEGY_PLUGIN_MODES = frozenset({PLUGIN_MODE_SHADOW}) -DEFAULT_PLUGIN_ARTIFACT_CACHE_DIR = Path(tempfile.gettempdir()) / "quant_strategy_plugin_artifacts" -STRATEGY_PLUGIN_NON_ALERT_ROUTES = frozenset({"no_action"}) -STRATEGY_PLUGIN_ALERT_ACTIONS = frozenset({"defend", "blocked"}) -STRATEGY_PLUGIN_AUTOMATED_POSITION_ACTIONS = frozenset({"defend", "delever"}) -# Legacy v1 artifacts may still carry position-control-shaped metadata for -# replay and display. The V2 sidecar contract makes that metadata -# non-authoritative: a plugin cannot directly mutate a strategy allocation. -STRATEGY_PLUGIN_DIRECT_POSITION_CONTROL_ALLOWED = False -CRISIS_RESPONSE_SHADOW_SUPPORTED_STRATEGIES = frozenset( - { - "tqqq_growth_income", - } +from quant_platform_kit.common._strategy_plugin_models import ( # noqa: F401 + CRISIS_RESPONSE_SHADOW_SUPPORTED_STRATEGIES, + DEFAULT_STRATEGY_PLUGIN_DEFINITIONS, + GENERAL_MARKET_REGIME_NOTIFICATION_TARGET, + MACRO_RISK_GOVERNOR_SUPPORTED_STRATEGIES, + MARKET_REGIME_CONTROL_SUPPORTED_STRATEGIES, + PLUGIN_CRISIS_RESPONSE_SHADOW, + PLUGIN_MACRO_RISK_GOVERNOR, + PLUGIN_MARKET_REGIME_CONTROL, + PLUGIN_MODE_SHADOW, + PLUGIN_PANIC_REVERSAL_SHADOW, + PLUGIN_TACO_REBOUND_SHADOW, + STRATEGY_PLUGIN_ALERT_ACTIONS, + STRATEGY_PLUGIN_ALERT_CHANNEL_EMAIL, + STRATEGY_PLUGIN_ALERT_CHANNEL_PUSH, + STRATEGY_PLUGIN_ALERT_CHANNEL_SMS, + STRATEGY_PLUGIN_ALERT_CHANNEL_TELEGRAM, + STRATEGY_PLUGIN_ALERT_CHANNEL_WEBHOOK, + STRATEGY_PLUGIN_AUTOMATED_POSITION_ACTIONS, + STRATEGY_PLUGIN_DIRECT_POSITION_CONTROL_ALLOWED, + STRATEGY_PLUGIN_NON_ALERT_ROUTES, + STRATEGY_PLUGIN_NOTIFICATION_TARGETS, + STRATEGY_PLUGIN_SCHEMA_VERSIONS, + SUPPORTED_STRATEGY_PLUGIN_MODES, + StrategyPluginAlertMessage, + StrategyPluginDefinition, + StrategyPluginMountConfig, + StrategyPluginNotificationTargetConfig, + StrategyPluginSignal, + TACO_REBOUND_SHADOW_SUPPORTED_STRATEGIES, + _strategy_plugin_consumption_policy, + _strategy_plugin_runtime_consumption_summary, + normalize_strategy_plugin_definitions, + normalize_strategy_plugin_mode, ) -TACO_REBOUND_SHADOW_SUPPORTED_STRATEGIES = frozenset({"tqqq_growth_income"}) -MACRO_RISK_GOVERNOR_SUPPORTED_STRATEGIES = frozenset({"tqqq_growth_income"}) -MARKET_REGIME_CONTROL_SUPPORTED_STRATEGIES = frozenset( - { - "tqqq_growth_income", - "soxl_soxx_trend_income", - "global_etf_rotation", - "russell_top50_leader_rotation", - "russell_1000_multi_factor_defensive", - "mega_cap_leader_rotation_top50_balanced", - } +from quant_platform_kit.common._strategy_plugin_consumption import ( # noqa: F401 + _is_strategy_position_control_notice, + _strategy_plugin_auto_consumption_allowed, + _strategy_plugin_consumption_status, + _strategy_plugin_enabled_label, + _strategy_plugin_find_field_value, + _strategy_plugin_has_auditable_position_control, + _strategy_plugin_is_notification_only, + _strategy_plugin_policy_allows_position_control, + _strategy_plugin_value_is_present, ) -STRATEGY_PLUGIN_NOTIFICATION_TARGETS: Mapping[str, frozenset[str]] = { - PLUGIN_MARKET_REGIME_CONTROL: frozenset({GENERAL_MARKET_REGIME_NOTIFICATION_TARGET}), -} -STRATEGY_PLUGIN_SCHEMA_VERSIONS: Mapping[str, frozenset[str]] = { - PLUGIN_CRISIS_RESPONSE_SHADOW: frozenset({"crisis_response_shadow.v1"}), - PLUGIN_MARKET_REGIME_CONTROL: frozenset({"market_regime_control.v1"}), - PLUGIN_MACRO_RISK_GOVERNOR: frozenset({"macro_risk_governor.v1"}), - PLUGIN_TACO_REBOUND_SHADOW: frozenset({"taco_rebound_shadow.v2"}), -} -_DEFAULT_STRATEGY_PLUGIN_ALERT_GUIDANCE: Mapping[tuple[str, str, str], str] = { - ( - PLUGIN_CRISIS_RESPONSE_SHADOW, - "true_crisis", - "defend", - ): ( - "Consider reducing leveraged exposure, moving to defensive or cash-like positions, " - "and pausing new risk additions until the signal de-escalates." - ), - ( - PLUGIN_CRISIS_RESPONSE_SHADOW, - "no_action", - "blocked", - ): ( - "The crisis route was blocked by a guard; review data freshness and context before " - "acting on the signal." - ), - ( - PLUGIN_MACRO_RISK_GOVERNOR, - "delever", - "delever", - ): ( - "Deterministic macro risk governor suggests reducing leveraged exposure while preserving " - "unlevered risk exposure when the strategy opts in." - ), - ( - PLUGIN_MACRO_RISK_GOVERNOR, - "crisis", - "defend", - ): ( - "Deterministic macro risk governor suggests moving the risk sleeve toward defensive or " - "cash-like exposure until macro stress de-escalates." - ), - ( - PLUGIN_MARKET_REGIME_CONTROL, - "risk_off", - "defend", - ): ( - "Unified market regime control blocks opportunity overlays and suggests moving risk exposure " - "toward defensive or cash-like positions until the deterministic arbiter de-escalates." - ), - ( - PLUGIN_MARKET_REGIME_CONTROL, - "risk_reduced", - "delever", - ): ( - "Unified market regime control suggests reducing leveraged exposure while preserving only the " - "risk budget allowed by the strategy policy adapter." - ), - ( - PLUGIN_MARKET_REGIME_CONTROL, - "opportunity_watch", - "notify_manual_review", - ): ( - "Manual review only: the unified arbiter allows the bounded TACO opportunity context, but it " - "does not authorize broker orders or live allocation mutation." - ), - ( - PLUGIN_MARKET_REGIME_CONTROL, - "blocked", - "blocked", - ): ( - "Unified market regime control was blocked by data-quality or freshness guards; review source " - "artifacts before relying on the signal." - ), - ( - PLUGIN_TACO_REBOUND_SHADOW, - "taco_rebound", - "notify_manual_review", - ): ( - "Manual review only: consider a small, pre-sized probe or staged entry with a " - "predefined invalidation level; avoid full-size deployment from this alert alone." - ), -} -_DEFAULT_STRATEGY_PLUGIN_ALERT_SCOPE_NOTE = ( - "Manual review notice only; the plugin does not place orders or change allocations." +from quant_platform_kit.common._strategy_plugin_loading import ( # noqa: F401 + _build_non_authoritative_runtime_plugin_payload, + _coerce_strategy_plugin_signal, + attach_strategy_plugin_metadata, + build_strategy_plugin_metadata, + build_strategy_plugin_report_payload, + load_configured_strategy_plugin_notification_target_signals, + load_configured_strategy_plugin_signals, + load_strategy_plugin_signal, + parse_strategy_plugin_mounts, + parse_strategy_plugin_notification_targets, + validate_strategy_plugin_compatibility, + validate_strategy_plugin_notification_target, + validate_strategy_plugin_schema_version, + validate_strategy_plugin_signal_payload, +) +from quant_platform_kit.common._strategy_plugin_alerts import ( # noqa: F401 + _DEFAULT_STRATEGY_PLUGIN_ALERT_GUIDANCE, + _DEFAULT_STRATEGY_PLUGIN_ALERT_SCOPE_NOTE, + _alert_narrative_keys, + _build_strategy_plugin_ai_audit_note, + _build_strategy_plugin_alert_guidance, + _build_strategy_plugin_alert_key, + _build_strategy_plugin_alert_reason_summary, + _build_strategy_plugin_alert_recommendation, + _build_strategy_plugin_alert_scope_note, + _build_strategy_plugin_alert_situation, + _extract_strategy_plugin_localized_message, + _is_strategy_manual_review_notification_delegated, + _localized_strategy_plugin_label_values, + _should_alert_strategy_plugin_signal, + _strategy_plugin_alert_display_context, + _strategy_plugin_alert_locale, + _strategy_plugin_consumption_notification_line, + _strategy_plugin_error_reason, + _strategy_plugin_reason_values, + build_strategy_plugin_ai_audit_note, + build_strategy_plugin_alert_guidance, + build_strategy_plugin_alert_key, + build_strategy_plugin_alert_messages, + build_strategy_plugin_alert_reason_summary, + build_strategy_plugin_alert_recommendation, + build_strategy_plugin_alert_scope_note, + build_strategy_plugin_alert_situation, + build_strategy_plugin_error_notification_lines, + build_strategy_plugin_notification_lines, + extract_strategy_plugin_localized_message, + should_alert_strategy_plugin_signal, + translate_strategy_plugin_value, ) - -@dataclass(frozen=True) -class StrategyPluginDefinition: - plugin: str - supported_strategies: frozenset[str] | None = None - supported_modes: frozenset[str] = field(default_factory=lambda: SUPPORTED_STRATEGY_PLUGIN_MODES) - supported_schema_versions: frozenset[str] = field(default_factory=frozenset) - default_schema_version: str | None = None - deprecated: bool = False - successor_plugin: str | None = None - alert_channels: tuple[str, ...] = () - - def normalized(self) -> "StrategyPluginDefinition": - plugin = _required_string(self.plugin, field_name="plugin") - supported_strategies = ( - frozenset(_required_string(strategy, field_name="supported_strategy") for strategy in self.supported_strategies) - if self.supported_strategies is not None - else None - ) - supported_modes = frozenset( - normalize_strategy_plugin_mode(mode, field_name="supported_mode") - for mode in self.supported_modes - ) - if not supported_modes: - raise ValueError(f"strategy plugin definition for {plugin} must include at least one supported mode") - supported_schema_versions = frozenset( - _required_string(version, field_name="supported_schema_version") - for version in self.supported_schema_versions - ) - default_schema_version = _optional_string(self.default_schema_version) - if default_schema_version is not None and supported_schema_versions and default_schema_version not in supported_schema_versions: - raise ValueError( - f"strategy plugin definition for {plugin} default_schema_version must be listed in supported_schema_versions" - ) - successor_plugin = _optional_string(self.successor_plugin) - alert_channels = tuple( - _required_string(channel, field_name="alert_channel") - for channel in self.alert_channels - ) - return StrategyPluginDefinition( - plugin=plugin, - supported_strategies=supported_strategies, - supported_modes=supported_modes, - supported_schema_versions=supported_schema_versions, - default_schema_version=default_schema_version, - deprecated=bool(self.deprecated), - successor_plugin=successor_plugin, - alert_channels=alert_channels, - ) - - def supports_strategy(self, strategy: str) -> bool: - if self.supported_strategies is None: - return True - return strategy in self.supported_strategies - - -DEFAULT_STRATEGY_PLUGIN_DEFINITIONS: Mapping[str, StrategyPluginDefinition] = { - PLUGIN_CRISIS_RESPONSE_SHADOW: StrategyPluginDefinition( - plugin=PLUGIN_CRISIS_RESPONSE_SHADOW, - supported_strategies=CRISIS_RESPONSE_SHADOW_SUPPORTED_STRATEGIES, - supported_modes=SUPPORTED_STRATEGY_PLUGIN_MODES, - supported_schema_versions=STRATEGY_PLUGIN_SCHEMA_VERSIONS[PLUGIN_CRISIS_RESPONSE_SHADOW], - default_schema_version="crisis_response_shadow.v1", - deprecated=True, - successor_plugin=PLUGIN_MARKET_REGIME_CONTROL, - alert_channels=( - STRATEGY_PLUGIN_ALERT_CHANNEL_EMAIL, - STRATEGY_PLUGIN_ALERT_CHANNEL_SMS, - STRATEGY_PLUGIN_ALERT_CHANNEL_PUSH, - STRATEGY_PLUGIN_ALERT_CHANNEL_TELEGRAM, - ), - ), - PLUGIN_TACO_REBOUND_SHADOW: StrategyPluginDefinition( - plugin=PLUGIN_TACO_REBOUND_SHADOW, - supported_strategies=TACO_REBOUND_SHADOW_SUPPORTED_STRATEGIES, - supported_modes=SUPPORTED_STRATEGY_PLUGIN_MODES, - supported_schema_versions=STRATEGY_PLUGIN_SCHEMA_VERSIONS[PLUGIN_TACO_REBOUND_SHADOW], - default_schema_version="taco_rebound_shadow.v2", - deprecated=True, - successor_plugin=PLUGIN_MARKET_REGIME_CONTROL, - alert_channels=( - STRATEGY_PLUGIN_ALERT_CHANNEL_EMAIL, - STRATEGY_PLUGIN_ALERT_CHANNEL_SMS, - STRATEGY_PLUGIN_ALERT_CHANNEL_PUSH, - STRATEGY_PLUGIN_ALERT_CHANNEL_TELEGRAM, - ), - ), - PLUGIN_MARKET_REGIME_CONTROL: StrategyPluginDefinition( - plugin=PLUGIN_MARKET_REGIME_CONTROL, - supported_strategies=MARKET_REGIME_CONTROL_SUPPORTED_STRATEGIES, - supported_modes=SUPPORTED_STRATEGY_PLUGIN_MODES, - supported_schema_versions=STRATEGY_PLUGIN_SCHEMA_VERSIONS[PLUGIN_MARKET_REGIME_CONTROL], - default_schema_version="market_regime_control.v1", - alert_channels=( - STRATEGY_PLUGIN_ALERT_CHANNEL_EMAIL, - STRATEGY_PLUGIN_ALERT_CHANNEL_SMS, - STRATEGY_PLUGIN_ALERT_CHANNEL_PUSH, - STRATEGY_PLUGIN_ALERT_CHANNEL_TELEGRAM, - ), - ), - PLUGIN_MACRO_RISK_GOVERNOR: StrategyPluginDefinition( - plugin=PLUGIN_MACRO_RISK_GOVERNOR, - supported_strategies=MACRO_RISK_GOVERNOR_SUPPORTED_STRATEGIES, - supported_modes=SUPPORTED_STRATEGY_PLUGIN_MODES, - supported_schema_versions=STRATEGY_PLUGIN_SCHEMA_VERSIONS[PLUGIN_MACRO_RISK_GOVERNOR], - default_schema_version="macro_risk_governor.v1", - deprecated=True, - successor_plugin=PLUGIN_MARKET_REGIME_CONTROL, - alert_channels=( - STRATEGY_PLUGIN_ALERT_CHANNEL_EMAIL, - STRATEGY_PLUGIN_ALERT_CHANNEL_SMS, - STRATEGY_PLUGIN_ALERT_CHANNEL_PUSH, - STRATEGY_PLUGIN_ALERT_CHANNEL_TELEGRAM, - ), - ), -} - - -@dataclass(frozen=True) -class StrategyPluginMountConfig: - strategy: str - plugin: str - signal_path: str - enabled: bool = True - expected_mode: str | None = None - expected_schema_version: str | None = None - - -@dataclass(frozen=True) -class StrategyPluginNotificationTargetConfig: - notification_target: str - plugin: str - signal_path: str - enabled: bool = True - expected_mode: str | None = None - expected_schema_version: str | None = None - - -@dataclass(frozen=True) -class StrategyPluginSignal: - strategy: str - plugin: str - mode: str - configured_mode: str - effective_mode: str - schema_version: str - as_of: str - canonical_route: str | None = None - suggested_action: str | None = None - would_trade_if_enabled: bool = False - execution_controls: Mapping[str, Any] = field(default_factory=dict) - payload: Mapping[str, Any] = field(default_factory=dict) - source_uri: str | None = None - local_path: str | None = None - deprecated_plugin: bool = False - successor_plugin: str | None = None - supported_schema_versions: tuple[str, ...] = () - target_type: str = "strategy" - notification_target: str = "" - enabled: bool = True - - def __post_init__(self) -> None: - object.__setattr__(self, "strategy", _optional_string(self.strategy) or "") - object.__setattr__(self, "plugin", _optional_string(self.plugin) or "") - object.__setattr__(self, "mode", _optional_string(self.mode) or "") - object.__setattr__(self, "configured_mode", _optional_string(self.configured_mode) or "") - object.__setattr__(self, "effective_mode", _optional_string(self.effective_mode) or "") - object.__setattr__(self, "schema_version", _optional_string(self.schema_version) or "") - object.__setattr__(self, "as_of", _optional_string(self.as_of) or "") - object.__setattr__(self, "canonical_route", _optional_string(self.canonical_route)) - object.__setattr__(self, "suggested_action", _optional_string(self.suggested_action)) - object.__setattr__( - self, - "would_trade_if_enabled", - _as_bool(self.would_trade_if_enabled, default=False), - ) - controls = dict(self.execution_controls) if isinstance(self.execution_controls, Mapping) else {} - payload = dict(self.payload) if isinstance(self.payload, Mapping) else {} - object.__setattr__(self, "execution_controls", controls) - object.__setattr__(self, "payload", payload) - object.__setattr__(self, "source_uri", _optional_string(self.source_uri)) - object.__setattr__(self, "local_path", _optional_string(self.local_path)) - object.__setattr__(self, "deprecated_plugin", bool(self.deprecated_plugin)) - object.__setattr__(self, "successor_plugin", _optional_string(self.successor_plugin)) - versions = self.supported_schema_versions - if isinstance(versions, (str, bytes, Mapping)) or not isinstance(versions, Iterable): - normalized_versions: tuple[str, ...] = () - else: - normalized_versions = tuple( - item for item in (_optional_string(version) for version in versions) if item - ) - object.__setattr__(self, "supported_schema_versions", normalized_versions) - object.__setattr__(self, "target_type", _optional_string(self.target_type) or "strategy") - object.__setattr__(self, "notification_target", _optional_string(self.notification_target) or "") - object.__setattr__(self, "enabled", _as_bool(self.enabled, default=True)) - - @property - def normalized_plugin(self) -> str: - return self.plugin.lower() or "unknown" - - @property - def normalized_route(self) -> str: - return (self.canonical_route or "").lower() or "unknown" - - @property - def normalized_action(self) -> str: - return (self.suggested_action or "").lower() or "unknown" - - @property - def normalized_target_type(self) -> str: - return self.target_type.lower() or "strategy" - - def report_summary(self) -> dict[str, Any]: - return { - "strategy": self.strategy, - "target_type": self.target_type, - "notification_target": self.notification_target, - "plugin": self.plugin, - "mode": self.mode, - "configured_mode": self.configured_mode, - "effective_mode": self.effective_mode, - "schema_version": self.schema_version, - "deprecated_plugin": self.deprecated_plugin, - "successor_plugin": self.successor_plugin, - "supported_schema_versions": self.supported_schema_versions, - "as_of": self.as_of, - "canonical_route": self.canonical_route, - "suggested_action": self.suggested_action, - "would_trade_if_enabled": self.would_trade_if_enabled, - "execution_controls": dict(self.execution_controls), - "runtime_consumption": _strategy_plugin_runtime_consumption_summary(self), - "source_uri": self.source_uri, - "local_path": self.local_path, - } - - -def _strategy_plugin_runtime_consumption_summary(signal: StrategyPluginSignal) -> dict[str, Any]: - """Describe the authority actually granted to a loaded sidecar. - - Artifact controls remain in ``execution_controls`` as source evidence. This - separate summary prevents a legacy artifact from making a runtime report - look authorized when the shared runtime deliberately clamps all direct - position control to shadow-only metadata. - """ - - controls = signal.execution_controls - policy = _strategy_plugin_consumption_policy(signal) - artifact_position_control_requested = _as_bool( - controls.get("position_control_allowed"), default=False - ) or _as_bool(policy.get("position_control_allowed"), default=False) - direct_position_control_allowed = bool(STRATEGY_PLUGIN_DIRECT_POSITION_CONTROL_ALLOWED) - return { - "authority": ( - "direct_position_control" if direct_position_control_allowed else "shadow_only" - ), - "direct_position_control_allowed": direct_position_control_allowed, - "broker_order_allowed": False, - "live_allocation_mutation_allowed": False, - "runtime_metadata_non_authoritative": not direct_position_control_allowed, - "artifact_position_control_requested": artifact_position_control_requested, - "artifact_schema_is_legacy_v1": signal.schema_version.endswith(".v1"), - } - - -@dataclass(frozen=True) -class StrategyPluginAlertMessage: - subject: str - body: str - alert_key: str = "" - metadata: Mapping[str, Any] = field(default_factory=dict) - - -def normalize_strategy_plugin_mode(value: Any, *, field_name: str = "mode") -> str: - mode = str(value or "").strip().lower() - if mode not in SUPPORTED_STRATEGY_PLUGIN_MODES: - modes = ", ".join(sorted(SUPPORTED_STRATEGY_PLUGIN_MODES)) - raise ValueError(f"{field_name} must be one of {modes}; got {value!r}") - return mode - - -def normalize_strategy_plugin_definitions( - plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, -) -> Mapping[str, StrategyPluginDefinition]: - raw_definitions = ( - DEFAULT_STRATEGY_PLUGIN_DEFINITIONS.values() - if plugin_definitions is None - else plugin_definitions.values() - if isinstance(plugin_definitions, Mapping) - else plugin_definitions - ) - definitions: dict[str, StrategyPluginDefinition] = {} - for definition in raw_definitions: - if not isinstance(definition, StrategyPluginDefinition): - raise TypeError("strategy plugin definitions must be StrategyPluginDefinition objects") - normalized = definition.normalized() - if normalized.plugin in definitions: - raise ValueError(f"duplicate strategy plugin definition: plugin={normalized.plugin}") - definitions[normalized.plugin] = normalized - return definitions - - -def validate_strategy_plugin_compatibility( - *, - strategy: str, - plugin: str, - mode: str | None = None, - plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, - source: str = "plugin", -) -> None: - strategy_name = _required_string(strategy, field_name="strategy") - plugin_name = _required_string(plugin, field_name="plugin") - definitions = normalize_strategy_plugin_definitions(plugin_definitions) - definition = definitions.get(plugin_name) - if definition is None: - return - if not definition.supports_strategy(strategy_name): - allowed = ", ".join(sorted(definition.supported_strategies or ())) or "any" - raise ValueError( - f"strategy plugin {plugin_name} does not support strategy {strategy_name} " - f"in {source}; supported strategies: {allowed}" - ) - if mode is None: - return - mode_name = normalize_strategy_plugin_mode(mode, field_name="mode") - if mode_name not in definition.supported_modes: - allowed_modes = ", ".join(sorted(definition.supported_modes)) - raise ValueError( - f"strategy plugin {plugin_name} does not support mode {mode_name} " - f"in {source}; supported modes: {allowed_modes}" - ) - - -def validate_strategy_plugin_notification_target( - *, - notification_target: str, - plugin: str, - source: str = "plugin", -) -> None: - target_name = _required_string(notification_target, field_name="notification_target") - plugin_name = _required_string(plugin, field_name="plugin") - allowed_targets = STRATEGY_PLUGIN_NOTIFICATION_TARGETS.get(plugin_name, frozenset()) - if target_name not in allowed_targets: - allowed = ", ".join(sorted(allowed_targets)) or "(none)" - raise ValueError( - f"strategy plugin {plugin_name} does not support notification target {target_name} " - f"in {source}; supported notification targets: {allowed}" - ) - - -def validate_strategy_plugin_schema_version( - *, - plugin: str, - schema_version: str | None, - expected_schema_version: str | None = None, - plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, - source: str = "artifact", -) -> None: - plugin_name = _required_string(plugin, field_name="plugin") - normalized_schema_version = _optional_string(schema_version) - normalized_expected_schema_version = _optional_string(expected_schema_version) - if normalized_expected_schema_version is not None and normalized_schema_version != normalized_expected_schema_version: - raise ValueError( - "strategy plugin artifact schema_version mismatch: " - f"expected {normalized_expected_schema_version}, got {normalized_schema_version or ''}" - ) - definitions = normalize_strategy_plugin_definitions(plugin_definitions) - definition = definitions.get(plugin_name) - if definition is None or not definition.supported_schema_versions or normalized_schema_version is None: - return - if normalized_schema_version not in definition.supported_schema_versions: - allowed = ", ".join(sorted(definition.supported_schema_versions)) - raise ValueError( - f"strategy plugin {plugin_name} does not support schema_version {normalized_schema_version} " - f"in {source}; supported schema versions: {allowed}" - ) - - -def parse_strategy_plugin_mounts( - raw_config: str | Sequence[Mapping[str, Any]] | Mapping[str, Any] | None, - *, - plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, -) -> tuple[StrategyPluginMountConfig, ...]: - if raw_config is None or raw_config == "": - return () - definitions = normalize_strategy_plugin_definitions(plugin_definitions) - payload: Any - if isinstance(raw_config, str): - payload = json.loads(raw_config) - else: - payload = raw_config - - if isinstance(payload, Mapping): - payload = payload.get("strategy_plugins", payload.get("plugins", ())) - if not isinstance(payload, Sequence) or isinstance(payload, (str, bytes)): - raise ValueError("strategy plugin mount config must be a JSON list or object with strategy_plugins") - - mounts: list[StrategyPluginMountConfig] = [] - seen: set[tuple[str, str]] = set() - for item in payload: - if not isinstance(item, Mapping): - raise ValueError("each strategy plugin mount must be an object") - if "mode" in item: - raise ValueError("platform plugin mount config must not set mode; read mode from the plugin artifact") - strategy = _required_string(item.get("strategy"), field_name="strategy") - plugin = _required_string(item.get("plugin"), field_name="plugin") - signal_path = _required_string( - item.get("signal_path") or item.get("latest_signal_path") or item.get("path"), - field_name="signal_path", - ) - key = (strategy, plugin) - if key in seen: - raise ValueError(f"duplicate strategy plugin mount: strategy={strategy} plugin={plugin}") - seen.add(key) - expected_mode = item.get("expected_mode") - normalized_expected_mode = ( - normalize_strategy_plugin_mode(expected_mode, field_name="expected_mode") - if expected_mode is not None - else None - ) - expected_schema_version = _optional_string(item.get("expected_schema_version")) - validate_strategy_plugin_schema_version( - plugin=plugin, - schema_version=expected_schema_version, - expected_schema_version=expected_schema_version, - plugin_definitions=definitions, - source="mount", - ) - validate_strategy_plugin_compatibility( - strategy=strategy, - plugin=plugin, - mode=normalized_expected_mode, - plugin_definitions=definitions, - source="mount", - ) - mounts.append( - StrategyPluginMountConfig( - strategy=strategy, - plugin=plugin, - signal_path=signal_path, - enabled=_as_bool(item.get("enabled"), default=True), - expected_mode=normalized_expected_mode, - expected_schema_version=expected_schema_version, - ) - ) - return tuple(mounts) - - -def parse_strategy_plugin_notification_targets( - raw_config: str | Sequence[Mapping[str, Any]] | Mapping[str, Any] | None, - *, - plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, -) -> tuple[StrategyPluginNotificationTargetConfig, ...]: - if raw_config is None or raw_config == "": - return () - definitions = normalize_strategy_plugin_definitions(plugin_definitions) - payload: Any - if isinstance(raw_config, str): - payload = json.loads(raw_config) - else: - payload = raw_config - - if isinstance(payload, Mapping): - payload = payload.get("notification_targets", ()) - if not isinstance(payload, Sequence) or isinstance(payload, (str, bytes)): - raise ValueError("strategy plugin notification target config must be a JSON list or object with notification_targets") - - targets: list[StrategyPluginNotificationTargetConfig] = [] - seen: set[tuple[str, str]] = set() - for item in payload: - if not isinstance(item, Mapping): - raise ValueError("each strategy plugin notification target must be an object") - if "mode" in item: - raise ValueError("notification target config must not set mode; read mode from the plugin artifact") - notification_target = _required_string(item.get("notification_target"), field_name="notification_target") - plugin = _required_string(item.get("plugin"), field_name="plugin") - signal_path = _required_string( - item.get("signal_path") or item.get("latest_signal_path") or item.get("path"), - field_name="signal_path", - ) - key = (notification_target, plugin) - if key in seen: - raise ValueError( - f"duplicate strategy plugin notification target: notification_target={notification_target} plugin={plugin}" - ) - seen.add(key) - expected_mode = item.get("expected_mode") - normalized_expected_mode = ( - normalize_strategy_plugin_mode(expected_mode, field_name="expected_mode") - if expected_mode is not None - else None - ) - expected_schema_version = _optional_string(item.get("expected_schema_version")) - validate_strategy_plugin_schema_version( - plugin=plugin, - schema_version=expected_schema_version, - expected_schema_version=expected_schema_version, - plugin_definitions=definitions, - source="notification_target", - ) - validate_strategy_plugin_notification_target( - notification_target=notification_target, - plugin=plugin, - source="notification_target", - ) - targets.append( - StrategyPluginNotificationTargetConfig( - notification_target=notification_target, - plugin=plugin, - signal_path=signal_path, - enabled=_as_bool(item.get("enabled"), default=True), - expected_mode=normalized_expected_mode, - expected_schema_version=expected_schema_version, - ) - ) - return tuple(targets) - - -def load_configured_strategy_plugin_signals( - mounts: Sequence[StrategyPluginMountConfig], - *, - strategy_profile: str | None = None, - client_factory: Any = None, - plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, -) -> tuple[StrategyPluginSignal, ...]: - selected_strategy = _optional_string(strategy_profile) - definitions = normalize_strategy_plugin_definitions(plugin_definitions) - signals: list[StrategyPluginSignal] = [] - for mount in mounts: - if not mount.enabled: - continue - if selected_strategy is not None and mount.strategy != selected_strategy: - continue - validate_strategy_plugin_compatibility( - strategy=mount.strategy, - plugin=mount.plugin, - mode=mount.expected_mode, - plugin_definitions=definitions, - source="mount", - ) - signals.append( - load_strategy_plugin_signal( - mount.signal_path, - expected_strategy=mount.strategy, - expected_plugin=mount.plugin, - expected_mode=mount.expected_mode, - expected_schema_version=mount.expected_schema_version, - client_factory=client_factory, - plugin_definitions=definitions, - ) - ) - return tuple(signals) - - -def load_configured_strategy_plugin_notification_target_signals( - targets: Sequence[StrategyPluginNotificationTargetConfig], - *, - notification_target: str | None = None, - client_factory: Any = None, - plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, -) -> tuple[StrategyPluginSignal, ...]: - selected_target = _optional_string(notification_target) - definitions = normalize_strategy_plugin_definitions(plugin_definitions) - signals: list[StrategyPluginSignal] = [] - for target in targets: - if not target.enabled: - continue - if selected_target is not None and target.notification_target != selected_target: - continue - validate_strategy_plugin_notification_target( - notification_target=target.notification_target, - plugin=target.plugin, - source="notification_target", - ) - signals.append( - load_strategy_plugin_signal( - target.signal_path, - expected_notification_target=target.notification_target, - expected_plugin=target.plugin, - expected_mode=target.expected_mode, - expected_schema_version=target.expected_schema_version, - client_factory=client_factory, - plugin_definitions=definitions, - ) - ) - return tuple(signals) - - -def load_strategy_plugin_signal( - reference: str, - *, - expected_strategy: str | None = None, - expected_notification_target: str | None = None, - expected_plugin: str | None = None, - expected_mode: str | None = None, - expected_schema_version: str | None = None, - client_factory: Any = None, - plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, -) -> StrategyPluginSignal: - local_path, metadata = _materialize_artifact_path(reference, client_factory=client_factory) - if not local_path.exists(): - raise FileNotFoundError(f"strategy plugin signal not found: {local_path}") - payload = json.loads(local_path.read_text(encoding="utf-8")) - if not isinstance(payload, Mapping): - raise ValueError("strategy plugin signal must be a JSON object") - return validate_strategy_plugin_signal_payload( - payload, - expected_strategy=expected_strategy, - expected_notification_target=expected_notification_target, - expected_plugin=expected_plugin, - expected_mode=expected_mode, - expected_schema_version=expected_schema_version, - source_uri=metadata.get("source_uri"), - local_path=str(local_path), - plugin_definitions=plugin_definitions, - ) - - -def validate_strategy_plugin_signal_payload( - payload: Mapping[str, Any], - *, - expected_strategy: str | None = None, - expected_notification_target: str | None = None, - expected_plugin: str | None = None, - expected_mode: str | None = None, - expected_schema_version: str | None = None, - source_uri: str | None = None, - local_path: str | None = None, - plugin_definitions: Mapping[str, StrategyPluginDefinition] | Sequence[StrategyPluginDefinition] | None = None, -) -> StrategyPluginSignal: - target_type = _optional_string(payload.get("target_type")) or ( - "notification_target" if _optional_string(payload.get("notification_target")) else "strategy" - ) - if target_type not in {"strategy", "notification_target"}: - raise ValueError(f"strategy plugin signal target_type must be strategy or notification_target; got {target_type!r}") - if target_type == "notification_target": - notification_target = _required_string(payload.get("notification_target"), field_name="notification_target") - strategy = _optional_string(payload.get("strategy")) or "" - else: - strategy = _required_string(payload.get("strategy"), field_name="strategy") - notification_target = _optional_string(payload.get("notification_target")) or "" - plugin = _required_string(payload.get("plugin"), field_name="plugin") - mode = normalize_strategy_plugin_mode(payload.get("mode"), field_name="mode") - configured_mode = normalize_strategy_plugin_mode( - payload.get("configured_mode", mode), - field_name="configured_mode", - ) - effective_mode = normalize_strategy_plugin_mode( - payload.get("effective_mode", mode), - field_name="effective_mode", - ) - - expected_strategy = _optional_string(expected_strategy) - expected_notification_target = _optional_string(expected_notification_target) - expected_plugin = _optional_string(expected_plugin) - if expected_strategy is not None and target_type != "strategy": - raise ValueError( - "strategy plugin artifact target mismatch: " - f"expected strategy {expected_strategy}, got notification target {notification_target}" - ) - if expected_strategy is not None and strategy != expected_strategy: - raise ValueError(f"strategy plugin artifact strategy mismatch: expected {expected_strategy}, got {strategy}") - if expected_notification_target is not None and target_type != "notification_target": - raise ValueError( - "strategy plugin artifact target mismatch: " - f"expected notification target {expected_notification_target}, got strategy {strategy}" - ) - if expected_notification_target is not None and notification_target != expected_notification_target: - raise ValueError( - "strategy plugin artifact notification_target mismatch: " - f"expected {expected_notification_target}, got {notification_target}" - ) - if expected_plugin is not None and plugin != expected_plugin: - raise ValueError(f"strategy plugin artifact plugin mismatch: expected {expected_plugin}, got {plugin}") - if expected_mode is not None: - normalized_expected_mode = normalize_strategy_plugin_mode(expected_mode, field_name="expected_mode") - if effective_mode != normalized_expected_mode: - raise ValueError( - "strategy plugin artifact mode mismatch: " - f"expected {normalized_expected_mode}, got {effective_mode}" - ) - if target_type == "strategy": - validate_strategy_plugin_compatibility( - strategy=strategy, - plugin=plugin, - mode=effective_mode, - plugin_definitions=plugin_definitions, - source="artifact", - ) - else: - validate_strategy_plugin_notification_target( - notification_target=notification_target, - plugin=plugin, - source="artifact", - ) - schema_version = _optional_string(payload.get("schema_version")) or "" - definitions = normalize_strategy_plugin_definitions(plugin_definitions) - definition = definitions.get(plugin) - if definition is not None and definition.supported_schema_versions and not schema_version: - raise ValueError(f"strategy plugin {plugin} artifact schema_version is required") - validate_strategy_plugin_schema_version( - plugin=plugin, - schema_version=schema_version, - expected_schema_version=expected_schema_version, - plugin_definitions=definitions, - source="artifact", - ) - - execution_controls = payload.get("execution_controls") or {} - if not isinstance(execution_controls, Mapping): - raise ValueError("strategy plugin signal execution_controls must be an object") - - return StrategyPluginSignal( - strategy=strategy, - plugin=plugin, - mode=mode, - configured_mode=configured_mode, - effective_mode=effective_mode, - schema_version=schema_version, - as_of=_optional_string(payload.get("as_of")) or "", - canonical_route=_optional_string(payload.get("canonical_route")), - suggested_action=_optional_string(payload.get("suggested_action")), - would_trade_if_enabled=_as_bool(payload.get("would_trade_if_enabled"), default=False), - execution_controls=execution_controls, - payload=dict(payload), - source_uri=_optional_string(source_uri), - local_path=_optional_string(local_path), - deprecated_plugin=bool(definition.deprecated) if definition is not None else False, - successor_plugin=definition.successor_plugin if definition is not None else None, - supported_schema_versions=tuple(sorted(definition.supported_schema_versions)) if definition is not None else (), - target_type=target_type, - notification_target=notification_target, - ) - - -def _coerce_strategy_plugin_signal(signal: Any) -> StrategyPluginSignal: - """Normalize a StrategyPluginSignal, Mapping, or duck-typed object at public boundaries.""" - if isinstance(signal, StrategyPluginSignal): - return signal - if isinstance(signal, Mapping): - def _read(key: str, default: Any = None) -> Any: - return signal.get(key, default) - else: - def _read(key: str, default: Any = None) -> Any: - return getattr(signal, key, default) - effective_mode = _optional_string(_read("effective_mode")) or "" - mode = _optional_string(_read("mode")) or effective_mode - configured_mode = _optional_string(_read("configured_mode")) or mode - return StrategyPluginSignal( - strategy=_read("strategy") or "", - plugin=_read("plugin") or "", - mode=mode, - configured_mode=configured_mode, - effective_mode=effective_mode or mode, - schema_version=_read("schema_version") or "", - as_of=_read("as_of") or "", - canonical_route=_read("canonical_route"), - suggested_action=_read("suggested_action"), - would_trade_if_enabled=_as_bool(_read("would_trade_if_enabled", False), default=False), - execution_controls=_read("execution_controls") or {}, - payload=_read("payload") or {}, - source_uri=_read("source_uri"), - local_path=_read("local_path"), - deprecated_plugin=bool(_read("deprecated_plugin", False)), - successor_plugin=_read("successor_plugin"), - supported_schema_versions=_read("supported_schema_versions") or (), - target_type=_read("target_type") or "strategy", - notification_target=_read("notification_target") or "", - enabled=_as_bool(_read("enabled", True), default=True), - ) - - -def build_strategy_plugin_report_payload( - signals: Sequence[StrategyPluginSignal | Any], -) -> dict[str, Any]: - summaries: list[dict[str, Any]] = [] - for raw_signal in signals: - if isinstance(raw_signal, StrategyPluginSignal): - summaries.append(raw_signal.report_summary()) - elif not isinstance(raw_signal, Mapping) and callable(getattr(raw_signal, "report_summary", None)): - summaries.append(raw_signal.report_summary()) - else: - summaries.append(_coerce_strategy_plugin_signal(raw_signal).report_summary()) - return { - "strategy_plugins": summaries, - } - - -def build_strategy_plugin_metadata( - signals: Sequence[StrategyPluginSignal | Any], -) -> dict[str, Any]: - """Build portfolio-snapshot metadata consumed by deterministic strategies.""" - plugin_payloads: dict[str, Any] = {} - summaries: dict[str, Any] = {} - for raw_signal in signals: - signal = _coerce_strategy_plugin_signal(raw_signal) - if not _as_bool( - signal.execution_controls.get("strategy_runtime_metadata_allowed"), - default=False, - ): - continue - if not signal.plugin: - continue - plugin_payloads[signal.plugin] = _build_non_authoritative_runtime_plugin_payload(signal.payload) - custom_summary = ( - getattr(raw_signal, "report_summary", None) - if not isinstance(raw_signal, (StrategyPluginSignal, Mapping)) - else None - ) - summaries[signal.plugin] = custom_summary() if callable(custom_summary) else signal.report_summary() - if not plugin_payloads: - return {} - metadata: dict[str, Any] = { - "strategy_plugins": plugin_payloads, - "strategy_plugin_summaries": summaries, - } - metadata.update(plugin_payloads) - return metadata - - -def _build_non_authoritative_runtime_plugin_payload(payload: Mapping[str, Any] | object) -> dict[str, Any]: - """Copy a sidecar payload for strategy metadata without delegation rights. - - The V2 plugin contract permits strategy metadata for deterministic - observability and research. It does not permit a plugin artifact to grant - itself allocation or broker authority. Preserve the original artifact on - ``StrategyPluginSignal.payload`` for audit, while making this injected copy - explicitly non-authoritative for every strategy consumer. - """ - - if not isinstance(payload, Mapping): - return {"strategy_runtime_metadata_non_authoritative": True} - normalized = dict(payload) - for control_key in ("execution_controls", "consumption_policy"): - source = payload.get(control_key) - if not isinstance(source, Mapping): - continue - controls = dict(source) - controls.update( - { - "broker_order_allowed": False, - "live_allocation_mutation_allowed": False, - "repository_broker_write_allowed": False, - "repository_allocation_mutation_allowed": False, - "position_control_allowed": False, - "consumption_evidence_status": "shadow_only", - } - ) - normalized[control_key] = controls - normalized["strategy_runtime_metadata_non_authoritative"] = True - return normalized - - -def attach_strategy_plugin_metadata(snapshot: Any, signals: Sequence[StrategyPluginSignal]) -> Any: - """Return a snapshot copy with plugin payloads attached to metadata.""" - plugin_metadata = build_strategy_plugin_metadata(signals) - if not plugin_metadata: - return snapshot - current_metadata = getattr(snapshot, "metadata", {}) or {} - if not isinstance(current_metadata, Mapping): - current_metadata = {} - merged_metadata = {**dict(current_metadata), **plugin_metadata} - try: - return dataclass_replace(snapshot, metadata=merged_metadata) - except TypeError: - try: - snapshot.metadata = merged_metadata - except Exception: - return snapshot - return snapshot - - -def translate_strategy_plugin_value( - category: str, - raw_value: str | None, - *, - translator: Callable[..., str] | None = None, -) -> str: - value = str(raw_value or "").strip() or "unknown" - if translator is None: - return value - key = f"strategy_plugin_{category}_{value}" - translated = translator(key) - return translated if translated != key else value - - -def _extract_strategy_plugin_localized_message( - signal: StrategyPluginSignal, - *, - section: str, - locale: str, -) -> str | None: - payload = signal.payload - normalized_section = str(section or "").strip() - normalized_locale = str(locale or "").strip() - if not normalized_section or not normalized_locale: - return None - - localized_messages = payload.get("localized_messages") - if isinstance(localized_messages, Mapping): - section_messages = localized_messages.get(normalized_section) - if isinstance(section_messages, Mapping): - localized = _optional_string(section_messages.get(normalized_locale)) - if localized: - return localized - default_locale = _optional_string(localized_messages.get("default_locale")) - if default_locale: - localized = _optional_string(section_messages.get(default_locale)) - if localized: - return localized - - if normalized_section == "notification": - notification = payload.get("notification") - if isinstance(notification, Mapping): - notification_messages = notification.get("localized_messages") - if isinstance(notification_messages, Mapping): - localized = _optional_string(notification_messages.get(normalized_locale)) - if localized: - return localized - default_locale = _optional_string(notification.get("default_locale")) - if default_locale: - localized = _optional_string(notification_messages.get(default_locale)) - if localized: - return localized - return None - - -def extract_strategy_plugin_localized_message( - signal: StrategyPluginSignal | Any, - *, - section: str, - locale: str, -) -> str | None: - return _extract_strategy_plugin_localized_message( - _coerce_strategy_plugin_signal(signal), - section=section, - locale=locale, - ) - - -def _strategy_plugin_enabled_label( - signal: StrategyPluginSignal, - *, - translator: Callable[..., str] | None = None, -) -> str: - return _translate( - translator, - f"strategy_plugin_enabled_{str(signal.enabled).lower()}", - fallback="yes" if signal.enabled else "no", - ) - - -def _strategy_plugin_consumption_policy(signal: StrategyPluginSignal) -> Mapping[str, Any]: - policy = signal.payload.get("consumption_policy") or {} - return policy if isinstance(policy, Mapping) else {} - - -def _strategy_plugin_value_is_present(value: Any) -> bool: - if value is None: - return False - if isinstance(value, bool): - return value - if isinstance(value, (int, float)): - return value != 0 - if isinstance(value, str): - normalized = value.strip().lower() - return bool(normalized) and normalized not in {"none", "null", "unbounded", "unlimited", "infinite", "inf"} - if isinstance(value, Mapping): - return any(_strategy_plugin_value_is_present(item) for item in value.values()) - if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): - return any(_strategy_plugin_value_is_present(item) for item in value) - return bool(value) - - -def _strategy_plugin_find_field_value(value: Any, field_names: frozenset[str]) -> Any | None: - if isinstance(value, Mapping): - for key, item in value.items(): - if key in field_names and _strategy_plugin_value_is_present(item): - return item - found = _strategy_plugin_find_field_value(item, field_names) - if found is not None: - return found - elif isinstance(value, Sequence) and not isinstance(value, (str, bytes)): - for item in value: - found = _strategy_plugin_find_field_value(item, field_names) - if found is not None: - return found - return None - - -def _strategy_plugin_has_auditable_position_control(signal: StrategyPluginSignal) -> bool: - if not STRATEGY_PLUGIN_DIRECT_POSITION_CONTROL_ALLOWED: - return False - controls = signal.execution_controls - policy = _strategy_plugin_consumption_policy(signal) - if not ( - _as_bool(controls.get("position_control_allowed"), default=False) - or _as_bool(policy.get("position_control_allowed"), default=False) - ): - return False - if _strategy_plugin_consumption_status(signal) != "automation_approved": - return False - evidence_sources: tuple[Any, ...] = (controls, signal.payload) - return all( - _strategy_plugin_find_field_value(evidence_sources, field_names) is not None - for field_names in ( - frozenset({"evidence_package_id", "evidence_package", "package_id"}), - frozenset( - { - "evidence_valid_until", - "evidence_valid_until_at", - "evidence_expires_at", - "valid_until", - "valid_until_at", - "expires_at", - } - ), - frozenset({"bounded_budget", "budget", "budget_limit"}), - ) - ) - - -def _strategy_plugin_consumption_status(signal: StrategyPluginSignal) -> str: - status = _optional_string(signal.execution_controls.get("consumption_evidence_status")) - if status is None: - status = _optional_string(_strategy_plugin_consumption_policy(signal).get("evidence_status")) - return _normalize_strategy_plugin_field(status) - - -def _strategy_plugin_policy_allows_position_control(signal: StrategyPluginSignal) -> bool: - if not STRATEGY_PLUGIN_DIRECT_POSITION_CONTROL_ALLOWED: - return False - controls = signal.execution_controls - if "position_control_allowed" in controls: - return _as_bool(controls.get("position_control_allowed"), default=False) - return _as_bool( - _strategy_plugin_consumption_policy(signal).get("position_control_allowed"), - default=False, - ) - - -def _strategy_plugin_is_notification_only(signal: StrategyPluginSignal) -> bool: - controls = signal.execution_controls - policy = _strategy_plugin_consumption_policy(signal) - if _strategy_plugin_consumption_status(signal) == "notification_only": - return True - if str(controls.get("capital_impact") or policy.get("capital_impact") or "").strip().lower() == "notification_only": - return True - if str(controls.get("notification_profile") or policy.get("notification_profile") or "").strip().lower() == "shadow_only": - return True - return False - - -def _strategy_plugin_auto_consumption_allowed(signal: StrategyPluginSignal, *, action: str) -> bool: - if _is_strategy_position_control_notice(signal, action=action): - return True - if signal.execution_controls: - return False - return bool( - action in STRATEGY_PLUGIN_AUTOMATED_POSITION_ACTIONS - and _strategy_plugin_policy_allows_position_control(signal) - and _strategy_plugin_consumption_status(signal) == "automation_approved" - and _strategy_plugin_has_auditable_position_control(signal) - ) - - -def _strategy_plugin_consumption_notification_line( - signal: StrategyPluginSignal, - *, - translator: Callable[..., str] | None = None, -) -> str | None: - route = signal.normalized_route - action = signal.normalized_action - if _strategy_plugin_auto_consumption_allowed(signal, action=action): - if action == "defend" or route == "risk_off": - key = "strategy_plugin_consumption_auto_defend" - elif action == "delever" or route == "risk_reduced": - key = "strategy_plugin_consumption_auto_delever" - else: - key = "strategy_plugin_consumption_auto" - return _translate( - translator, - key, - fallback="Plugin impact this run: included in this cycle's position calculation", - ) - if _strategy_plugin_is_notification_only(signal): - return _translate( - translator, - "strategy_plugin_consumption_review_only", - fallback=( - "Plugin impact this run: review-only notice; current state did not trigger automatic " - "position rewrites" - ), - ) - if action in STRATEGY_PLUGIN_AUTOMATED_POSITION_ACTIONS: - return _translate( - translator, - "strategy_plugin_consumption_loaded_not_applied", - fallback=( - "Plugin impact this run: loaded; this state did not enable automatic position rewrites" - ), - ) - return None - - -def build_strategy_plugin_notification_lines( - signals: Sequence[StrategyPluginSignal | Any], - *, - translator: Callable[..., str] | None = None, - locale: str | None = None, -) -> tuple[str, ...]: - lines: list[str] = [] - for raw_signal in signals: - signal = _coerce_strategy_plugin_signal(raw_signal) - localized_line = ( - _extract_strategy_plugin_localized_message(signal, section="notification", locale=locale) - if locale is not None - else None - ) - if localized_line: - lines.append(localized_line) - if translator is not None: - consumption_line = _strategy_plugin_consumption_notification_line(signal, translator=translator) - if consumption_line: - lines.append(consumption_line) - continue - route = signal.canonical_route or "unknown_route" - action = signal.suggested_action or "unknown_action" - lines.append( - _translate( - translator, - "strategy_plugin_line", - fallback="Plugin: {plugin} | enabled: {enabled} | status: {route} | notice: {action}", - plugin=translate_strategy_plugin_value("name", signal.plugin, translator=translator), - enabled=_strategy_plugin_enabled_label(signal, translator=translator), - mode=translate_strategy_plugin_value("mode", signal.effective_mode, translator=translator), - route=translate_strategy_plugin_value("route", route, translator=translator), - action=translate_strategy_plugin_value("action", action, translator=translator), - ) - ) - consumption_line = _strategy_plugin_consumption_notification_line(signal, translator=translator) - if consumption_line: - lines.append(consumption_line) - return tuple(lines) - - -def _compact_strategy_plugin_error(error: object, *, max_chars: int = 240) -> str: - text = " ".join(str(error or "").split()) - if not text: - return "" - if len(text) <= max_chars: - return text - return text[: max_chars - 1].rstrip() + "…" - - -def _translator_uses_zh(translator: Callable[..., str] | None) -> bool: - if translator is None: - return False - for key in ("strategy_plugin_alert_locale", "no_trades"): - try: - sample = str(translator(key)) - except Exception: - continue - if sample.strip().lower().startswith("zh"): - return True - if any("\u4e00" <= char <= "\u9fff" for char in sample): - return True - return False - - -def _strategy_plugin_error_reason(error: object, *, translator: Callable[..., str] | None = None) -> str: - detail = _compact_strategy_plugin_error(error) - if not detail: - return "" - error_type = detail.split(":", 1)[0].rsplit(".", 1)[-1].strip() - reason_key = f"strategy_plugin_error_reason_{error_type}" if error_type else "" - if translator is not None and reason_key: - translated = translator(reason_key) - if translated != reason_key: - return translated - if _translator_uses_zh(translator): - translated = translator("strategy_plugin_error_reason_default") if translator is not None else "" - if translated and translated != "strategy_plugin_error_reason_default": - return translated - return detail - - -def build_strategy_plugin_error_notification_lines( - error: object, - *, - translator: Callable[..., str] | None = None, -) -> tuple[str, ...]: - reason = _strategy_plugin_error_reason(error, translator=translator) - if not reason: - return () - return ( - _translate( - translator, - "strategy_plugin_error_line", - fallback="Plugin signal failed to load: {reason}; this run falls back to built-in strategy rules", - reason=reason, - ), - _translate( - translator, - "strategy_plugin_consumption_unavailable", - fallback="Plugin impact this run: no usable plugin signal loaded", - ), - ) - - -def _should_alert_strategy_plugin_signal(signal: StrategyPluginSignal) -> bool: - route = signal.normalized_route - action = signal.normalized_action - if _is_strategy_position_control_notice(signal, action=action): - return False - if _is_strategy_manual_review_notification_delegated(signal): - return False - return ( - signal.would_trade_if_enabled - or route not in STRATEGY_PLUGIN_NON_ALERT_ROUTES - or action in STRATEGY_PLUGIN_ALERT_ACTIONS - ) - - -def should_alert_strategy_plugin_signal(signal: StrategyPluginSignal | Any) -> bool: - return _should_alert_strategy_plugin_signal(_coerce_strategy_plugin_signal(signal)) - - -def _is_strategy_position_control_notice(signal: StrategyPluginSignal, *, action: str | None = None) -> bool: - """Return true when strategy runtime should carry the alert instead of the plugin bot.""" - - if signal.normalized_target_type != "strategy": - return False - normalized_action = action if action is not None else signal.normalized_action - if normalized_action not in STRATEGY_PLUGIN_AUTOMATED_POSITION_ACTIONS: - return False - if not _as_bool(signal.execution_controls.get("strategy_runtime_metadata_allowed"), default=False): - return False - return _strategy_plugin_has_auditable_position_control(signal) - - -def _is_strategy_manual_review_notification_delegated(signal: StrategyPluginSignal) -> bool: - """Return true when a strategy artifact delegates human-review alerts to a notification target.""" - - if signal.normalized_target_type != "strategy": - return False - controls = signal.execution_controls - if not _as_bool(controls.get("manual_review_notification_delegated"), default=False): - return False - return _optional_string(controls.get("manual_review_notification_target")) is not None - - -def _build_strategy_plugin_alert_guidance( - signal: StrategyPluginSignal, - *, - translator: Callable[..., str] | None = None, -) -> str | None: - plugin = signal.normalized_plugin - route = signal.normalized_route - action = signal.normalized_action - translated = _translate_first( - translator, - ( - f"strategy_plugin_guidance_{plugin}_{route}_{action}", - f"strategy_plugin_guidance_{plugin}_{route}", - f"strategy_plugin_guidance_{plugin}_{action}", - f"strategy_plugin_guidance_{plugin}", - f"strategy_plugin_guidance_{route}_{action}", - f"strategy_plugin_guidance_{action}", - ), - ) - if translated: - return translated - return _DEFAULT_STRATEGY_PLUGIN_ALERT_GUIDANCE.get((plugin, route, action)) - - -def build_strategy_plugin_alert_guidance( - signal: StrategyPluginSignal | Any, - *, - translator: Callable[..., str] | None = None, -) -> str | None: - return _build_strategy_plugin_alert_guidance( - _coerce_strategy_plugin_signal(signal), - translator=translator, - ) - - -def _build_strategy_plugin_alert_scope_note( - signal: StrategyPluginSignal, - *, - translator: Callable[..., str] | None = None, -) -> str | None: - controls = signal.execution_controls - notification_profile = str(controls.get("notification_profile") or "").strip().lower() - if notification_profile != "shadow_only" and any( - _as_bool(controls.get(field), default=False) - for field in ( - "broker_order_allowed", - "repository_broker_write_allowed", - "live_allocation_mutation_allowed", - "repository_allocation_mutation_allowed", - "allocation_recommendation_allowed", - "position_sizing_allowed", - "selection_allowed", - ) - ): - return None - return ( - _translate_first( - translator, - ( - f"strategy_plugin_alert_scope_{signal.normalized_plugin}", - "strategy_plugin_alert_scope", - ), - ) - or _DEFAULT_STRATEGY_PLUGIN_ALERT_SCOPE_NOTE - ) - - -def build_strategy_plugin_alert_scope_note( - signal: StrategyPluginSignal | Any, - *, - translator: Callable[..., str] | None = None, -) -> str | None: - return _build_strategy_plugin_alert_scope_note( - _coerce_strategy_plugin_signal(signal), - translator=translator, - ) - - -def _strategy_plugin_alert_locale(*, translator: Callable[..., str] | None = None) -> str: - locale = _translate(translator, "strategy_plugin_alert_locale", fallback="en-US") - return str(locale or "en-US").strip() or "en-US" - - -def _localized_strategy_plugin_label_values( - signal: StrategyPluginSignal, - label_name: str, - *, - locale: str, -) -> tuple[str, ...]: - localized_messages = signal.payload.get("localized_messages") - if not isinstance(localized_messages, Mapping): - return () - labels = localized_messages.get("labels") - if not isinstance(labels, Mapping): - return () - label_values = labels.get(label_name) - if not isinstance(label_values, Mapping): - return () - - candidates = [locale] - if "-" in locale: - candidates.append(locale.split("-", 1)[0]) - default_locale = _optional_string(localized_messages.get("default_locale")) - if default_locale: - candidates.append(default_locale) - - for candidate in candidates: - value = label_values.get(candidate) - if isinstance(value, str): - text = value.strip() - return (text,) if text else () - if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): - values = tuple(str(item).strip() for item in value if str(item).strip()) - if values: - return values - return () - - -def _strategy_plugin_reason_values(signal: StrategyPluginSignal, *, locale: str) -> tuple[str, ...]: - localized_reasons = _localized_strategy_plugin_label_values(signal, "reason_codes", locale=locale) - if localized_reasons: - return localized_reasons - - payload = signal.payload - for section_key in ("log_record", "position_control"): - section = payload.get(section_key) - if isinstance(section, Mapping): - reason_codes = section.get("reason_codes") - if isinstance(reason_codes, Sequence) and not isinstance(reason_codes, (str, bytes)): - values = tuple(str(item).strip() for item in reason_codes if str(item).strip()) - if values: - return values - return () - - -def _build_strategy_plugin_alert_reason_summary( - signal: StrategyPluginSignal, - *, - translator: Callable[..., str] | None = None, -) -> str: - locale = _strategy_plugin_alert_locale(translator=translator) - reasons = _strategy_plugin_reason_values(signal, locale=locale) - if not reasons: - return _translate( - translator, - "strategy_plugin_alert_reason_none", - fallback="no explicit reason provided", - ) - joiner = _translate(translator, "strategy_plugin_alert_reason_joiner", fallback=", ") - return str(joiner).join(reasons) - - -def build_strategy_plugin_alert_reason_summary( - signal: StrategyPluginSignal | Any, - *, - translator: Callable[..., str] | None = None, -) -> str: - return _build_strategy_plugin_alert_reason_summary( - _coerce_strategy_plugin_signal(signal), - translator=translator, - ) - - -def _translate_first_formatted( - translator: Callable[..., str] | None, - keys: Sequence[str], - **kwargs: Any, -) -> str | None: - if translator is None: - return None - for key in keys: - try: - translated = translator(key, **kwargs) - except TypeError: - translated = translator(key) - if translated != key: - text = str(translated).strip() - if text: - return text - return None - - -def _alert_narrative_keys(kind: str, signal: StrategyPluginSignal) -> tuple[str, ...]: - plugin = signal.normalized_plugin - route = signal.normalized_route - action = signal.normalized_action - return ( - f"strategy_plugin_{kind}_{plugin}_{route}_{action}", - f"strategy_plugin_{kind}_{plugin}_{route}", - f"strategy_plugin_{kind}_{plugin}_{action}", - f"strategy_plugin_{kind}_{route}_{action}", - f"strategy_plugin_{kind}_{route}", - f"strategy_plugin_{kind}_{action}", - f"strategy_plugin_{kind}_default", - ) - - -def _build_strategy_plugin_alert_situation( - signal: StrategyPluginSignal, - *, - translator: Callable[..., str] | None = None, - reasons: str | None = None, -) -> str: - resolved_reasons = ( - reasons - if reasons is not None - else _build_strategy_plugin_alert_reason_summary(signal, translator=translator) - ) - translated = _translate_first_formatted( - translator, - _alert_narrative_keys("situation", signal), - reasons=resolved_reasons, - ) - if translated: - return translated - return f"The plugin found a market state that needs attention. Trigger: {resolved_reasons}." - - -def build_strategy_plugin_alert_situation( - signal: StrategyPluginSignal | Any, - *, - translator: Callable[..., str] | None = None, -) -> str: - return _build_strategy_plugin_alert_situation( - _coerce_strategy_plugin_signal(signal), - translator=translator, - ) - - -def _build_strategy_plugin_alert_recommendation( - signal: StrategyPluginSignal, - *, - translator: Callable[..., str] | None = None, -) -> str: - translated = _translate_first_formatted( - translator, - _alert_narrative_keys("recommendation", signal), - ) - if translated: - return translated - return ( - "Review manually first, then decide whether the action belongs to strategy rules or a manual process; " - "do not treat the plugin notice as a trade instruction." - ) - - -def build_strategy_plugin_alert_recommendation( - signal: StrategyPluginSignal | Any, - *, - translator: Callable[..., str] | None = None, -) -> str: - return _build_strategy_plugin_alert_recommendation( - _coerce_strategy_plugin_signal(signal), - translator=translator, - ) - - -def _strategy_plugin_alert_display_context( - raw_context: str, - signal: StrategyPluginSignal, - *, - target_label: str, - translator: Callable[..., str] | None = None, -) -> str: - context = str(raw_context or "").strip() - if not context: - return "" - normalized = context.strip().lower() - notification_target = signal.notification_target - if normalized == f"strategy-plugin-publish / {notification_target}".lower() and notification_target: - return _translate( - translator, - "strategy_plugin_alert_context_strategy_plugin_publish", - fallback="plugin publish / {target}", - target=target_label, - ) - return context - - -def _build_strategy_plugin_ai_audit_note( - signal: StrategyPluginSignal, - *, - translator: Callable[..., str] | None = None, -) -> str | None: - ai_audit = signal.payload.get("ai_audit") - if not isinstance(ai_audit, Mapping) or not _as_bool(ai_audit.get("enabled"), default=False): - return None - status = _normalize_strategy_plugin_field(_optional_string(ai_audit.get("status"))) - if status == "ok": - verdict = _optional_string(ai_audit.get("verdict")) or "unknown" - assessment = _optional_string(ai_audit.get("route_assessment")) or "unknown" - summary = _optional_string(ai_audit.get("summary")) or "no summary" - return _translate( - translator, - "strategy_plugin_alert_ai_audit", - fallback="AI audit: {status} | verdict={verdict} | assessment={assessment} | {summary}", - status=status, - verdict=verdict, - assessment=assessment, - summary=summary, - ) - reason = _optional_string(ai_audit.get("skip_reason")) or _optional_string(ai_audit.get("error")) or "no detail" - return _translate( - translator, - "strategy_plugin_alert_ai_audit_status", - fallback="AI audit: {status} | {reason}", - status=status, - reason=reason, - ) - - -def build_strategy_plugin_ai_audit_note( - signal: StrategyPluginSignal | Any, - *, - translator: Callable[..., str] | None = None, -) -> str | None: - return _build_strategy_plugin_ai_audit_note( - _coerce_strategy_plugin_signal(signal), - translator=translator, - ) - - -def _build_strategy_plugin_alert_key( - signal: StrategyPluginSignal, - *, - strategy_label: str | None = None, - context_label: str | None = None, - namespace: str = "strategy_plugin_alert", -) -> str: - target_label = ( - signal.strategy - or signal.notification_target - or _optional_key_part(strategy_label) - or "unknown" - ) - payload = { - "namespace": _optional_key_part(namespace) or "strategy_plugin_alert", - "context": _optional_key_part(context_label) or "default", - "target_type": signal.target_type or "strategy", - "target": target_label, - "plugin": signal.plugin or "unknown", - "mode": signal.effective_mode or "unknown", - "as_of": signal.as_of or "unknown", - "route": signal.canonical_route or "unknown", - "action": signal.suggested_action or "unknown", - "would_trade_if_enabled": signal.would_trade_if_enabled, - } - digest = hashlib.sha256( - json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8") - ).hexdigest()[:16] - return "/".join( - ( - _sanitize_key_part(payload["namespace"]), - _sanitize_key_part(payload["context"]), - _sanitize_key_part(payload["target"]), - _sanitize_key_part(payload["plugin"]), - _sanitize_key_part(payload["as_of"]), - _sanitize_key_part(payload["route"]), - _sanitize_key_part(payload["action"]), - digest, - ) - ) - - -def build_strategy_plugin_alert_key( - signal: StrategyPluginSignal | Any, - *, - strategy_label: str | None = None, - context_label: str | None = None, - namespace: str = "strategy_plugin_alert", -) -> str: - return _build_strategy_plugin_alert_key( - _coerce_strategy_plugin_signal(signal), - strategy_label=strategy_label, - context_label=context_label, - namespace=namespace, - ) - - -def build_strategy_plugin_alert_messages( - signals: Sequence[StrategyPluginSignal | Any], - *, - translator: Callable[..., str] | None = None, - strategy_label: str | None = None, - context_label: str | None = None, - alert_namespace: str = "strategy_plugin_alert", -) -> tuple[StrategyPluginAlertMessage, ...]: - messages: list[StrategyPluginAlertMessage] = [] - context = str(context_label or "").strip() - for raw_signal in signals: - signal = _coerce_strategy_plugin_signal(raw_signal) - if not _should_alert_strategy_plugin_signal(signal): - continue - route = signal.canonical_route or "unknown_route" - action = signal.suggested_action or "unknown_action" - plugin = translate_strategy_plugin_value("name", signal.plugin, translator=translator) - translated_mode = translate_strategy_plugin_value( - "mode", - signal.effective_mode, - translator=translator, - ) - translated_route = translate_strategy_plugin_value("route", route, translator=translator) - translated_action = translate_strategy_plugin_value("action", action, translator=translator) - target_type = signal.target_type - strategy = str(strategy_label or signal.strategy or "").strip() - notification_target = signal.notification_target - target_label = strategy or notification_target or "unknown" - display_target_label = target_label - if target_type == "notification_target" and notification_target: - display_target_label = translate_strategy_plugin_value( - "notification_target", - notification_target, - translator=translator, - ) - elif strategy: - display_target_label = translate_strategy_plugin_value("strategy", strategy, translator=translator) - # Presentation only: target_label still supplies alert keys and machine metadata. - display_target_label = display_name( - "strategies", - signal.strategy or strategy, - "zh" if translator and translator_uses_zh(translator) else "en", - fallback=display_target_label, - ) - display_context = _strategy_plugin_alert_display_context( - context, - signal, - target_label=display_target_label, - translator=translator, - ) - target_name_key = ( - "strategy_plugin_alert_target_name_notification_target" - if target_type == "notification_target" - else "strategy_plugin_alert_target_name_strategy" - ) - target_name = _translate( - translator, - target_name_key, - fallback="Notification target" if target_type == "notification_target" else "Strategy", - ) - guidance = _build_strategy_plugin_alert_guidance(signal, translator=translator) - reason_summary = _build_strategy_plugin_alert_reason_summary(signal, translator=translator) - situation = _build_strategy_plugin_alert_situation( - signal, - translator=translator, - reasons=reason_summary, - ) - recommendation = _build_strategy_plugin_alert_recommendation(signal, translator=translator) - scope_note = _build_strategy_plugin_alert_scope_note(signal, translator=translator) - ai_audit_note = _build_strategy_plugin_ai_audit_note(signal, translator=translator) - subject = _translate( - translator, - "strategy_plugin_alert_subject", - fallback="Strategy plugin alert: {plugin} | {route}", - strategy=display_target_label, - plugin=plugin, - route=translated_route, - ) - if display_context: - subject = f"[{display_context}] {subject}" - body_lines = [ - _translate(translator, "strategy_plugin_alert_title", fallback="Strategy Plugin Alert"), - "", - ] - if display_context: - body_lines.append( - _translate( - translator, - "strategy_plugin_alert_context", - fallback="Context: {context}", - context=display_context, - ) - ) - body_lines.extend( - [ - _translate( - translator, - "strategy_plugin_alert_target", - fallback="{target_name}: {target}", - target_name=target_name, - target=display_target_label, - ), - _translate( - translator, - "strategy_plugin_alert_plugin", - fallback="Plugin: {plugin}", - plugin=plugin, - ), - _translate( - translator, - "strategy_plugin_alert_as_of", - fallback="Signal as-of: {as_of}", - as_of=signal.as_of or "unknown", - ), - _translate( - translator, - "strategy_plugin_alert_situation", - fallback="Situation: {situation}", - situation=situation, - ), - _translate( - translator, - "strategy_plugin_alert_trigger", - fallback="Trigger: {reasons}", - reasons=reason_summary, - ), - _translate( - translator, - "strategy_plugin_alert_recommendation", - fallback="Suggested review: {recommendation}", - recommendation=recommendation, - ), - _translate( - translator, - "strategy_plugin_alert_status", - fallback="Status: {route}", - route=translated_route, - ), - _translate( - translator, - "strategy_plugin_alert_action", - fallback="Notice: {action}", - action=translated_action, - ), - _translate( - translator, - "strategy_plugin_alert_mode", - fallback="Mode: {mode}", - mode=translated_mode, - ), - ] - ) - if guidance: - body_lines.append( - _translate( - translator, - "strategy_plugin_alert_guidance", - fallback="Manual guidance: {guidance}", - guidance=guidance, - ) - ) - if ai_audit_note: - body_lines.append(ai_audit_note) - if scope_note: - body_lines.append( - _translate( - translator, - "strategy_plugin_alert_scope_note", - fallback="Scope: {scope_note}", - scope_note=scope_note, - ) - ) - metadata = { - "target_type": target_type, - "target": target_label, - "strategy": signal.strategy, - "strategy_label": strategy or None, - "notification_target": notification_target or None, - "plugin": signal.plugin, - "mode": signal.effective_mode, - "as_of": signal.as_of, - "canonical_route": signal.canonical_route, - "suggested_action": signal.suggested_action, - "would_trade_if_enabled": signal.would_trade_if_enabled, - "context_label": context or None, - "display_context_label": display_context or None, - "display_target": display_target_label, - "situation": situation, - "recommendation": recommendation, - "reason_summary": reason_summary, - "guidance": guidance, - "scope_note": scope_note, - "ai_audit": signal.payload.get("ai_audit"), - } - messages.append( - StrategyPluginAlertMessage( - subject=subject, - body="\n".join(body_lines), - alert_key=_build_strategy_plugin_alert_key( - signal, - strategy_label=target_label, - context_label=context, - namespace=alert_namespace, - ), - metadata=metadata, - ) - ) - return tuple(messages) - - -def _optional_key_part(value: Any) -> str | None: - if value is None: - return None - text = str(value).strip() - return text or None - - -def _sanitize_key_part(value: Any) -> str: - text = str(value or "").strip().lower() - chars: list[str] = [] - previous_dash = False - for char in text: - if char.isalnum() or char in {"_", "."}: - chars.append(char) - previous_dash = False - elif not previous_dash: - chars.append("-") - previous_dash = True - sanitized = "".join(chars).strip("-._") - return sanitized[:80] or "unknown" - - -def _materialize_artifact_path(reference: str, *, client_factory: Any = None) -> tuple[Path, dict[str, str | None]]: - return materialize_local_or_remote_artifact( - reference, - cache_dir=DEFAULT_PLUGIN_ARTIFACT_CACHE_DIR, - client_factory=client_factory, - ) - - -def _download_remote_object(uri: str, destination: Path, *, client_factory: Any = None) -> None: - download_remote_object(uri, destination, client_factory=client_factory) - - -def _parse_cloud_uri(uri: str) -> tuple[str, str]: - return parse_cloud_uri(uri) - - -# Backward-compatible aliases (used internally by notification modules) -_download_gcs_object = _download_remote_object -_parse_gcs_uri = _parse_cloud_uri - - -def _cache_path_for_remote_artifact(reference: str) -> Path: - return cache_path_for_remote_artifact(reference, cache_dir=DEFAULT_PLUGIN_ARTIFACT_CACHE_DIR) - - -def _as_bool(value: Any, *, default: bool = False) -> bool: - if value is None: - return default - if isinstance(value, bool): - return value - return str(value).strip().lower() in {"1", "true", "yes", "y", "on"} - - -def _optional_string(value: Any) -> str | None: - if value is None: - return None - text = str(value).strip() - return text or None - - -def _normalize_strategy_plugin_field(value: str | None) -> str: - return str(value or "").strip().lower() or "unknown" - - -def _translate( - translator: Callable[..., str] | None, - key: str, - *, - fallback: str, - **kwargs: Any, -) -> str: - if translator is None: - return fallback.format(**kwargs) - try: - translated = translator(key, **kwargs) - except TypeError: - translated = translator(key) - return translated if translated != key else fallback.format(**kwargs) - - -def _translate_first( - translator: Callable[..., str] | None, - keys: Sequence[str], -) -> str | None: - if translator is None: - return None - for key in keys: - translated = translator(key) - if translated != key: - text = str(translated).strip() - if text: - return text - return None - - -def _required_string(value: Any, *, field_name: str) -> str: - text = _optional_string(value) - if text is None: - raise ValueError(f"{field_name} is required") - return text +__all__ = [ + "CRISIS_RESPONSE_SHADOW_SUPPORTED_STRATEGIES", + "DEFAULT_PLUGIN_ARTIFACT_CACHE_DIR", + "DEFAULT_STRATEGY_PLUGIN_DEFINITIONS", + "GENERAL_MARKET_REGIME_NOTIFICATION_TARGET", + "MACRO_RISK_GOVERNOR_SUPPORTED_STRATEGIES", + "MARKET_REGIME_CONTROL_SUPPORTED_STRATEGIES", + "PLUGIN_CRISIS_RESPONSE_SHADOW", + "PLUGIN_MACRO_RISK_GOVERNOR", + "PLUGIN_MARKET_REGIME_CONTROL", + "PLUGIN_MODE_SHADOW", + "PLUGIN_PANIC_REVERSAL_SHADOW", + "PLUGIN_TACO_REBOUND_SHADOW", + "STRATEGY_PLUGIN_ALERT_ACTIONS", + "STRATEGY_PLUGIN_ALERT_CHANNEL_EMAIL", + "STRATEGY_PLUGIN_ALERT_CHANNEL_PUSH", + "STRATEGY_PLUGIN_ALERT_CHANNEL_SMS", + "STRATEGY_PLUGIN_ALERT_CHANNEL_TELEGRAM", + "STRATEGY_PLUGIN_ALERT_CHANNEL_WEBHOOK", + "STRATEGY_PLUGIN_AUTOMATED_POSITION_ACTIONS", + "STRATEGY_PLUGIN_DIRECT_POSITION_CONTROL_ALLOWED", + "STRATEGY_PLUGIN_NON_ALERT_ROUTES", + "STRATEGY_PLUGIN_NOTIFICATION_TARGETS", + "STRATEGY_PLUGIN_SCHEMA_VERSIONS", + "SUPPORTED_STRATEGY_PLUGIN_MODES", + "StrategyPluginAlertMessage", + "StrategyPluginDefinition", + "StrategyPluginMountConfig", + "StrategyPluginNotificationTargetConfig", + "StrategyPluginSignal", + "TACO_REBOUND_SHADOW_SUPPORTED_STRATEGIES", + "_DEFAULT_STRATEGY_PLUGIN_ALERT_GUIDANCE", + "_DEFAULT_STRATEGY_PLUGIN_ALERT_SCOPE_NOTE", + "_alert_narrative_keys", + "_as_bool", + "_build_non_authoritative_runtime_plugin_payload", + "_build_strategy_plugin_ai_audit_note", + "_build_strategy_plugin_alert_guidance", + "_build_strategy_plugin_alert_key", + "_build_strategy_plugin_alert_reason_summary", + "_build_strategy_plugin_alert_recommendation", + "_build_strategy_plugin_alert_scope_note", + "_build_strategy_plugin_alert_situation", + "_cache_path_for_remote_artifact", + "_coerce_strategy_plugin_signal", + "_compact_strategy_plugin_error", + "_download_gcs_object", + "_download_remote_object", + "_extract_strategy_plugin_localized_message", + "_is_strategy_manual_review_notification_delegated", + "_is_strategy_position_control_notice", + "_localized_strategy_plugin_label_values", + "_materialize_artifact_path", + "_normalize_strategy_plugin_field", + "_optional_key_part", + "_optional_string", + "_parse_cloud_uri", + "_parse_gcs_uri", + "_required_string", + "_sanitize_key_part", + "_should_alert_strategy_plugin_signal", + "_strategy_plugin_alert_display_context", + "_strategy_plugin_alert_locale", + "_strategy_plugin_auto_consumption_allowed", + "_strategy_plugin_consumption_notification_line", + "_strategy_plugin_consumption_policy", + "_strategy_plugin_consumption_status", + "_strategy_plugin_enabled_label", + "_strategy_plugin_error_reason", + "_strategy_plugin_find_field_value", + "_strategy_plugin_has_auditable_position_control", + "_strategy_plugin_is_notification_only", + "_strategy_plugin_policy_allows_position_control", + "_strategy_plugin_reason_values", + "_strategy_plugin_runtime_consumption_summary", + "_strategy_plugin_value_is_present", + "_translate", + "_translate_first", + "_translator_uses_zh", + "attach_strategy_plugin_metadata", + "build_strategy_plugin_ai_audit_note", + "build_strategy_plugin_alert_guidance", + "build_strategy_plugin_alert_key", + "build_strategy_plugin_alert_messages", + "build_strategy_plugin_alert_reason_summary", + "build_strategy_plugin_alert_recommendation", + "build_strategy_plugin_alert_scope_note", + "build_strategy_plugin_alert_situation", + "build_strategy_plugin_error_notification_lines", + "build_strategy_plugin_metadata", + "build_strategy_plugin_notification_lines", + "build_strategy_plugin_report_payload", + "extract_strategy_plugin_localized_message", + "load_configured_strategy_plugin_notification_target_signals", + "load_configured_strategy_plugin_signals", + "load_strategy_plugin_signal", + "normalize_strategy_plugin_definitions", + "normalize_strategy_plugin_mode", + "parse_strategy_plugin_mounts", + "parse_strategy_plugin_notification_targets", + "should_alert_strategy_plugin_signal", + "translate_strategy_plugin_value", + "validate_strategy_plugin_compatibility", + "validate_strategy_plugin_notification_target", + "validate_strategy_plugin_schema_version", + "validate_strategy_plugin_signal_payload", +] diff --git a/tests/test_strategy_plugins.py b/tests/test_strategy_plugins.py index a99ee0c8..daa14432 100644 --- a/tests/test_strategy_plugins.py +++ b/tests/test_strategy_plugins.py @@ -1393,6 +1393,47 @@ def test_public_entrypoints_coerce_duck_typed_and_mapping_signals_without_mutati self.assertEqual(dict(vars(ns)), before) + def test_error_notification_lines_handle_optional_translator_and_zh_locale_helper(self): + self.assertEqual( + build_strategy_plugin_error_notification_lines(RuntimeError("boom")), + ( + "Plugin signal failed to load: boom; this run falls back to built-in strategy rules", + "Plugin impact this run: no usable plugin signal loaded", + ), + ) + + def flaky_zh_translator(key: str) -> str: + if key == "strategy_plugin_alert_locale": + return "zh-CN" + if key == "strategy_plugin_error_reason_default": + return "插件读取异常" + return key + + self.assertEqual( + build_strategy_plugin_error_notification_lines(RuntimeError("boom"), translator=flaky_zh_translator), + ( + "Plugin signal failed to load: 插件读取异常; this run falls back to built-in strategy rules", + "Plugin impact this run: no usable plugin signal loaded", + ), + ) + + def raising_translator(key: str) -> str: + if key == "strategy_plugin_alert_locale": + raise KeyError(key) + if key == "no_trades": + return "暂无交易" + if key == "strategy_plugin_error_reason_default": + return "回退默认原因" + return key + + self.assertEqual( + build_strategy_plugin_error_notification_lines(RuntimeError("boom"), translator=raising_translator), + ( + "Plugin signal failed to load: 回退默认原因; this run falls back to built-in strategy rules", + "Plugin impact this run: no usable plugin signal loaded", + ), + ) + if __name__ == "__main__": unittest.main()