"""Digital Optimus - Brain Adapter (Host Side)
Bridges Brain Host HTTPS endpoints to the real Reasoning Core.
Maintains complete isolation from the frozen V8.3.8 runtime.
"""
from __future__ import annotations

import os
import re
import sys
import time
import uuid
from pathlib import Path
from typing import Any, Dict, Optional, Tuple

# Ensure repository root is on sys.path
REPO_ROOT = Path(__file__).resolve().parent.parent.parent
if str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))

# Safe import of Reasoning Core components
try:
    from runtime_v1.foundation.reasoning_core import (
        REASONING_CORE,
        ReasoningContext,
        ReasoningResult,
        TASK_REASONING,
    )
    CORE_AVAILABLE = True
except Exception:
    REASONING_CORE = None
    ReasoningContext = None
    ReasoningResult = None
    TASK_REASONING = "reasoning"
    CORE_AVAILABLE = False

try:
    from runtime_v1.foundation.model_router import (
        MODEL_ROUTER,
        ReasoningModelRouter,
        TIER_CHEAP,
        TIER_DEFAULT,
        TIER_HEAVY,
    )
except Exception:
    MODEL_ROUTER = None
    ReasoningModelRouter = object
    TIER_CHEAP = "cheap"
    TIER_DEFAULT = "default"
    TIER_HEAVY = "heavy"

import threading
import logging
logger = logging.getLogger("BrainHost.Adapter")

try:
    from artifacts.brain_host.continuity_engine import (
        CONTINUITY,
        normalize_for_search,
        extract_explicit_project_mind_update,
        contains_suspicious_credentials,
        ALLOWED_EVIDENCE_SOURCE_TYPES,
    )
except Exception:
    try:
        from continuity_engine import (
            CONTINUITY,
            normalize_for_search,
            extract_explicit_project_mind_update,
            contains_suspicious_credentials,
            ALLOWED_EVIDENCE_SOURCE_TYPES,
        )
    except Exception:
        CONTINUITY = None
        def normalize_for_search(text: str) -> str:
            return text.lower().strip()
        def extract_explicit_project_mind_update(text: str) -> Optional[Dict[str, Any]]:
            return None
        def contains_suspicious_credentials(text: str) -> bool:
            return False
        ALLOWED_EVIDENCE_SOURCE_TYPES = {"CREATOR_EXPLICIT", "VERIFIED_SYSTEM", "MISSION_VERIFIED"}

try:
    from runtime_v1.foundation.executive_brain import (
        is_executive_request,
        build_executive_state,
        build_executive_reasoning_request,
        finalize_executive_decision,
        format_executive_response,
    )
    EXECUTIVE_BRAIN_AVAILABLE = True
except Exception:
    is_executive_request = None
    build_executive_state = None
    build_executive_reasoning_request = None
    finalize_executive_decision = None
    format_executive_response = None
    EXECUTIVE_BRAIN_AVAILABLE = False

try:
    from artifacts.developer_workspace import get_developer_service
except Exception:
    try:
        from developer_workspace import get_developer_service
    except Exception:
        get_developer_service = None


class BrainHostModelRouter(ReasoningModelRouter):
    """Compatibility router outside frozen core (Alpha60).
    Ensures explicit model and effort are honored without modifying frozen reasoning_core.
    Supports thread-local explicit context for concurrent safety.
    """
    def __init__(self, base_router: Optional[Any] = None) -> None:
        if hasattr(super(), "__init__"):
            try:
                super().__init__()
            except Exception:
                pass
        self._base_router = base_router or MODEL_ROUTER
        self._local = threading.local()

    class _ContextManager:
        def __init__(self, router: "BrainHostModelRouter", model: Optional[str], effort: Optional[str], tier: Optional[str]):
            self.router = router
            self.model = model
            self.effort = effort
            self.tier = tier
            self.prev = None

        def __enter__(self):
            self.prev = getattr(self.router._local, "explicit_info", None)
            if self.model:
                self.router._local.explicit_info = {
                    "explicit_model": self.model,
                    "explicit_effort": self.effort,
                    "tier": self.tier
                }
            else:
                self.router._local.explicit_info = None
            return self

        def __exit__(self, exc_type, exc_val, exc_tb):
            self.router._local.explicit_info = self.prev

    def explicit_context(self, model: Optional[str], effort: Optional[str] = None, tier: Optional[str] = None):
        return self._ContextManager(self, model, effort, tier)

    def route(self, task_types=None, *, risk="low", complexity="balanced", escalation=False,
              confidence_override_tier=None, model_ids_available_check=None):
        info = getattr(self._local, "explicit_info", None)
        if info and info.get("explicit_model"):
            exp_model = info["explicit_model"]
            exp_tier = info.get("tier") or "default"
            exp_effort = info.get("explicit_effort") or "medium"
            reason = f"explicit_contract:model={exp_model};effort={exp_effort};tier={exp_tier}"
            notes = ""
            return exp_model, exp_tier, reason, notes
        if self._base_router and hasattr(self._base_router, "route"):
            return self._base_router.route(
                task_types=task_types,
                risk=risk,
                complexity=complexity,
                escalation=escalation,
                confidence_override_tier=confidence_override_tier,
                model_ids_available_check=model_ids_available_check
            )
        return "gpt-5.6-terra", "default", "fallback_default", ""

    def default_model(self) -> str:
        info = getattr(self._local, "explicit_info", None)
        if info and info.get("explicit_model") and (info.get("tier") in ("default", None) or info.get("tier") not in ("cheap", "heavy")):
            return info["explicit_model"]
        if self._base_router and hasattr(self._base_router, "default_model"):
            return self._base_router.default_model()
        return "gpt-5.6-terra"

    def cheap_model(self) -> str:
        info = getattr(self._local, "explicit_info", None)
        if info and info.get("explicit_model") and info.get("tier") == "cheap":
            return info["explicit_model"]
        if self._base_router and hasattr(self._base_router, "cheap_model"):
            return self._base_router.cheap_model()
        return "gpt-5.6-luna"

    def heavy_model(self) -> str:
        info = getattr(self._local, "explicit_info", None)
        if info and info.get("explicit_model") and info.get("tier") == "heavy":
            return info["explicit_model"]
        if self._base_router and hasattr(self._base_router, "heavy_model"):
            return self._base_router.heavy_model()
        return "gpt-5.6-sol"

    def get_config(self):
        cfg = self._base_router.get_config() if (self._base_router and hasattr(self._base_router, "get_config")) else None
        info = getattr(self._local, "explicit_info", None)
        if cfg and info and info.get("explicit_model"):
            tier = info.get("tier") or "default"
            if tier == "cheap":
                cfg.cheap_model = info["explicit_model"]
            elif tier == "heavy":
                cfg.heavy_model = info["explicit_model"]
            else:
                cfg.default_model = info["explicit_model"]
        return cfg


class BrainAdapter:
    """Adapter bridging HTTP requests from Brain Host to Optimus Reasoning Core."""

    def __init__(self, core: Optional[Any] = None, continuity_engine: Optional[Any] = None) -> None:
        self.core = core if core is not None else REASONING_CORE
        self.continuity = continuity_engine if continuity_engine is not None else CONTINUITY
        try:
            from runtime_v1.foundation.effector_runtime import EffectorRegistry
            self.effector_registry = EffectorRegistry.get_instance()
        except Exception:
            self.effector_registry = None
        # Wire compatibility router outside frozen core (Alpha60)
        self.router = BrainHostModelRouter(getattr(self.core, "_router", None) if self.core else None)
        if self.core and hasattr(self.core, "set_router"):
            try:
                self.core.set_router(self.router)
            except Exception:
                pass
        if self.core and (not hasattr(self.core, "_provider") or self.core._provider is None):
            try:
                from runtime_v1.foundation.reasoning import _init_real_reasoning_if_available
                _init_real_reasoning_if_available()
            except Exception:
                pass
        if self.core and hasattr(self.core, "_provider") and self.core._provider:
            try:
                self.core._provider.timeout_seconds = 75
            except Exception:
                pass

        # Optional fail-open NeuralAdvisor shadow client (Alpha66)
        try:
            try:
                from app.advisor.neural_advisor_shadow_client import NeuralAdvisorShadowClient
            except Exception:
                import importlib.util
                client_file = REPO_ROOT / "app" / "advisor" / "neural_advisor_shadow_client.py"
                if client_file.exists():
                    spec = importlib.util.spec_from_file_location("app.advisor.neural_advisor_shadow_client", str(client_file))
                    if spec and spec.loader:
                        mod = importlib.util.module_from_spec(spec)
                        sys.modules["app.advisor.neural_advisor_shadow_client"] = mod
                        spec.loader.exec_module(mod)
                        NeuralAdvisorShadowClient = getattr(mod, "NeuralAdvisorShadowClient", None)
                    else:
                        NeuralAdvisorShadowClient = None
                else:
                    NeuralAdvisorShadowClient = None

            if NeuralAdvisorShadowClient:
                self.neural_advisor = NeuralAdvisorShadowClient()
            else:
                self.neural_advisor = None
        except Exception:
            self.neural_advisor = None

        # FASE 11: Executive Core Initialization
        try:
            from runtime_v1.foundation.executive_core import ExecutiveCore
            self.executive_core = ExecutiveCore()
        except Exception as ex_exec:
            logger.warning("[EXECUTIVE_CORE_INIT_ERROR] %s: %s", type(ex_exec).__name__, ex_exec)
            self.executive_core = None

        # V1 DECISION TOKEN & CHAT REPLAY INFRASTRUCTURE (Memory-only, zero persistence, zero logs)
        self._decision_secret: bytes = os.urandom(32)
        self._consumed_chat_cache: Dict[str, Tuple[float, Dict[str, Any]]] = {}
        self._chat_cache_lock = threading.Lock()
        self._active_operational_tasks: Dict[str, Dict[str, Any]] = {}
        self._operational_tasks_lock = threading.RLock()

    @staticmethod
    def canonicalize_prompt(prompt: str) -> str:
        """Single Brain-side prompt canonicalization for deterministic hashing."""
        if not prompt or not isinstance(prompt, str):
            return ""
        return " ".join(prompt.strip().split())

    def compute_prompt_hash(self, prompt: str) -> str:
        """Computes SHA-256 hash of the canonicalized prompt."""
        import hashlib
        canon = self.canonicalize_prompt(prompt)
        return hashlib.sha256(canon.encode("utf-8")).hexdigest()

    @staticmethod
    def derive_client_task_id(turn_id: str) -> str:
        """Option A: Deterministically derives client_task_id from turn_id."""
        raw = (turn_id or "").strip()
        if raw.startswith("turn_"):
            raw = raw[len("turn_"):]
        return f"task_{raw}"

    def sign_decision(
        self,
        *,
        turn_id: str,
        prompt: str,
        intent: str,
        workspace_disposition: str,
        conversation_id: Optional[str] = None,
        source: str = "LOCAL",
        decision_id: Optional[str] = None,
        ttl_seconds: int = 60
    ) -> Tuple[str, Dict[str, Any]]:
        """Signs an authoritative semantic preclassification decision using process-local HMAC-SHA256."""
        import base64
        import hashlib
        import hmac
        import json

        now_ts = int(time.time())
        dec_id = decision_id or f"dec_cls_{int(now_ts * 1000)}_{uuid.uuid4().hex[:8]}"
        payload = {
            "version": 1,
            "decision_id": dec_id,
            "turn_id": str(turn_id or "").strip(),
            "prompt_hash": self.compute_prompt_hash(prompt),
            "conversation_id": str(conversation_id or "").strip(),
            "intent": str(intent or "").strip(),
            "workspace_disposition": str(workspace_disposition or "NOT_APPLICABLE").strip(),
            "source": str(source or "").strip(),
            "issued_at": now_ts,
            "expires_at": now_ts + ttl_seconds
        }
        payload_json = json.dumps(payload, sort_keys=True, separators=(',', ':'))
        b64_payload = base64.urlsafe_b64encode(payload_json.encode("utf-8")).decode("ascii").rstrip("=")
        sig = hmac.new(self._decision_secret, payload_json.encode("utf-8"), hashlib.sha256).hexdigest()
        token = f"{b64_payload}.{sig}"
        return token, payload

    def verify_decision(
        self,
        token: str,
        prompt: str,
        turn_id: Optional[str] = None,
        conversation_id: Optional[str] = None,
        expected_intent: Optional[str] = None,
        client_task_id: Optional[str] = None
    ) -> Tuple[bool, Optional[str], Optional[Dict[str, Any]]]:
        """Cryptographically verifies a decision token and validates all turn constraints.
        Returns: (is_valid, error_code, payload)
        """
        import base64
        import hashlib
        import hmac
        import json

        if not token or not isinstance(token, str) or "." not in token:
            return False, "CLASSIFICATION_INVALID", None
        parts = token.split(".")
        if len(parts) != 2:
            return False, "CLASSIFICATION_INVALID", None
        b64_payload, received_sig = parts
        rem = len(b64_payload) % 4
        if rem > 0:
            b64_payload += "=" * (4 - rem)
        try:
            payload_bytes = base64.urlsafe_b64decode(b64_payload)
            payload = json.loads(payload_bytes.decode("utf-8"))
        except Exception:
            return False, "CLASSIFICATION_INVALID", None

        payload_json = json.dumps(payload, sort_keys=True, separators=(',', ':'))
        expected_sig = hmac.new(self._decision_secret, payload_json.encode("utf-8"), hashlib.sha256).hexdigest()
        if not hmac.compare_digest(received_sig, expected_sig):
            return False, "CLASSIFICATION_INVALID", None

        if payload.get("version") != 1:
            return False, "CLASSIFICATION_INVALID", None

        now_ts = int(time.time())
        if now_ts > int(payload.get("expires_at", 0)):
            return False, "CLASSIFICATION_EXPIRED", None

        expected_prompt_hash = self.compute_prompt_hash(prompt)
        if payload.get("prompt_hash") != expected_prompt_hash:
            return False, "PROMPT_MISMATCH", None

        if turn_id and str(payload.get("turn_id", "")).strip() != str(turn_id).strip():
            return False, "TURN_MISMATCH", None

        if conversation_id and payload.get("conversation_id"):
            if str(payload.get("conversation_id", "")).strip() != str(conversation_id).strip():
                return False, "CONVERSATION_MISMATCH", None

        if expected_intent and str(payload.get("intent", "")).strip() != str(expected_intent).strip():
            return False, "INTENT_MISMATCH", None

        if client_task_id is not None:
            signed_turn_id = payload.get("turn_id", "")
            expected_task_id = self.derive_client_task_id(signed_turn_id)
            if str(client_task_id).strip() != expected_task_id:
                return False, "TASK_ID_BINDING_MISMATCH", None

        return True, None, payload

    def _bounded_semantic_classify(self, user_text: str) -> Dict[str, Any]:
        """Performs a strictly bounded semantic classification via OpenAIReasoningProvider with hard cap of 1 call and 0 retries."""
        import json
        if not self.core or not hasattr(self.core, "_provider") or not self.core._provider:
            return {
                "intent": "CLASSIFICATION_UNAVAILABLE",
                "workspace_disposition": "NOT_APPLICABLE",
                "confidence": 0.0,
                "source": "PROVIDER_UNINITIALIZED"
            }
        provider = self.core._provider
        respond_fn = getattr(provider, "respond", None)
        if not callable(respond_fn):
            return {
                "intent": "CLASSIFICATION_UNAVAILABLE",
                "workspace_disposition": "NOT_APPLICABLE",
                "confidence": 0.0,
                "source": "PROVIDER_NO_RESPOND"
            }

        system_prompt = (
            "Eres el clasificador semántico de intenciones de Digital Optimus.\n"
            "Clasifica la solicitud del usuario en exactamente uno de estos tres valores de intent:\n"
            "- CHAT: conversación general, saludos, preguntas teóricas, dudas de conceptos, explicaciones.\n"
            "- OPERATIONAL: solicitudes que implican desarrollo de software, creación de proyectos, modificación de archivos, creación de código, refactorización o ejecución de pruebas.\n"
            "- CLARIFICATION: peticiones incompletas, ambiguas o que requieren confirmación antes de actuar.\n\n"
            "Si el intent es OPERATIONAL, determina workspace_disposition:\n"
            "- CREATE_NEW: si el usuario solicita crear un proyecto nuevo desde cero (o si no tiene workspace y requiere inicializar uno nuevo).\n"
            "- REQUIRE_EXISTING: si la instrucción requiere modificar, corregir o inspeccionar un proyecto/archivo existente.\n"
            "- OPTIONAL: si es independiente del workspace.\n"
            "Para CHAT o CLARIFICATION, workspace_disposition debe ser NOT_APPLICABLE.\n\n"
            "Responde ÚNICAMENTE en JSON válido con este esquema exacto:\n"
            "{\"intent\": \"CHAT\"|\"OPERATIONAL\"|\"CLARIFICATION\", \"workspace_disposition\": \"NOT_APPLICABLE\"|\"CREATE_NEW\"|\"REQUIRE_EXISTING\"|\"OPTIONAL\", \"confidence\": float}"
        )
        try:
            resp = respond_fn(
                model=None,
                user_message=user_text,
                system_prompt=system_prompt,
                tools=None,
                images=None,
                max_output_tokens=64,
                call_type="INTENT_CLASSIFIER",
                _skip_cost_record=False
            )
            if not resp or not resp.success or not resp.answer:
                return {
                    "intent": "CLASSIFICATION_UNAVAILABLE",
                    "workspace_disposition": "NOT_APPLICABLE",
                    "confidence": 0.0,
                    "source": "PROVIDER_CALL_FAILED"
                }

            raw_ans = resp.answer.strip()
            if raw_ans.startswith("```"):
                lines = raw_ans.splitlines()
                if len(lines) >= 3 and lines[0].startswith("```"):
                    raw_ans = "\n".join(lines[1:-1]).strip()
            data = json.loads(raw_ans)
            intent = str(data.get("intent") or "CLASSIFICATION_UNAVAILABLE").upper().strip()
            disp = str(data.get("workspace_disposition") or "NOT_APPLICABLE").upper().strip()
            conf = float(data.get("confidence", 0.95))
            if intent not in ("CHAT", "OPERATIONAL", "CLARIFICATION"):
                intent = "CLASSIFICATION_UNAVAILABLE"
            if disp not in ("NOT_APPLICABLE", "CREATE_NEW", "REQUIRE_EXISTING", "OPTIONAL"):
                disp = "NOT_APPLICABLE" if intent != "OPERATIONAL" else "OPTIONAL"
            return {
                "intent": intent,
                "workspace_disposition": disp,
                "confidence": conf,
                "source": "BOUNDED_SEMANTIC_CLASSIFIER"
            }
        except Exception as ex:
            logger.warning("[BOUNDED_CLASSIFIER_ERROR] %s: %s", type(ex).__name__, ex)
            return {
                "intent": "CLASSIFICATION_UNAVAILABLE",
                "workspace_disposition": "NOT_APPLICABLE",
                "confidence": 0.0,
                "source": "CLASSIFIER_EXCEPTION"
            }

    def classify_turn(self, prompt: str, context: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """Pre-classifies a user turn into CHAT vs OPERATIONAL with authoritative signed decision.
        Side-effect-free: no missions, no tasks, no workspace mutation, no continuity writes.
        """
        ctx = context or {}
        clean_prompt = (prompt or "").strip()
        turn_id = str(ctx.get("turn_id") or f"turn_{int(time.time()*1000)}_{uuid.uuid4().hex[:8]}").strip()
        conv_id = str(ctx.get("conversation_id") or "").strip()

        if not clean_prompt:
            token, payload = self.sign_decision(
                turn_id=turn_id,
                prompt="",
                intent="CHAT",
                workspace_disposition="NOT_APPLICABLE",
                conversation_id=conv_id,
                source="EMPTY_INPUT"
            )
            return {
                "status": "success",
                "intent": "CHAT",
                "workspace_disposition": "NOT_APPLICABLE",
                "confidence": 1.0,
                "source": "EMPTY_INPUT",
                "decision_token": token,
                "decision_payload": payload,
                "side_effect_free": True
            }

        # 1. Fast-Path: LocalAnswerRouter (pure, provider_calls=0)
        try:
            from runtime_v1.foundation.local_answer_router import get_shared_router
            local_rtr = get_shared_router()
            matched_intent = local_rtr.classify_intent(clean_prompt)
            if matched_intent not in ("GENERIC", "EMPTY"):
                token, payload = self.sign_decision(
                    turn_id=turn_id,
                    prompt=clean_prompt,
                    intent="CHAT",
                    workspace_disposition="NOT_APPLICABLE",
                    conversation_id=conv_id,
                    source=f"LOCAL_ANSWER_ROUTER:{matched_intent}"
                )
                return {
                    "status": "success",
                    "intent": "CHAT",
                    "workspace_disposition": "NOT_APPLICABLE",
                    "confidence": 0.98,
                    "source": f"LOCAL_ANSWER_ROUTER:{matched_intent}",
                    "decision_token": token,
                    "decision_payload": payload,
                    "side_effect_free": True
                }
        except Exception as ex_rtr:
            logger.warning("[LOCAL_ROUTER_CLASSIFY_ERROR] %s: %s", type(ex_rtr).__name__, ex_rtr)

        # 2. Bounded Semantic Classification (hard cap of 1 call, 0 retries)
        sem_res = self._bounded_semantic_classify(clean_prompt)
        intent = sem_res.get("intent", "CLASSIFICATION_UNAVAILABLE")
        disp = sem_res.get("workspace_disposition", "NOT_APPLICABLE")
        conf = float(sem_res.get("confidence", 0.0))
        src = sem_res.get("source", "BOUNDED_SEMANTIC_CLASSIFIER")

        # 3. If primary semantic classifier is unavailable: record health event & invoke Safe Local Fallback
        if intent == "CLASSIFICATION_UNAVAILABLE":
            try:
                from app.system_health import get_health_supervisor
                sup = get_health_supervisor()
                sup.record_system_event(
                    event_type="CLASSIFICATION_UNAVAILABLE",
                    details={
                        "component_id": "INTENT_CLASSIFIER",
                        "prompt": clean_prompt,
                        "turn_id": turn_id,
                        "symptom": "CLASSIFICATION_UNAVAILABLE",
                        "root_cause": sem_res.get("error") or "PRIMARY_SEMANTIC_CLASSIFIER_FAILED",
                        "root_cause_status": "PROVEN",
                        "recovery_class": "RECOVERABLE",
                    }
                )
            except Exception as ex_sh:
                logger.warning("[SYSTEM_HEALTH_EVENT_ERROR] %s: %s", type(ex_sh).__name__, ex_sh)

            try:
                from app.system_health import classify_safe_local_fallback
                fallback_res = classify_safe_local_fallback(clean_prompt)
                intent = fallback_res.get("intent", "CLASSIFICATION_UNAVAILABLE")
                disp = fallback_res.get("workspace_disposition", "NOT_APPLICABLE")
                conf = float(fallback_res.get("confidence", 0.85))
                src = fallback_res.get("source", "LOCAL_SAFE_FALLBACK")
            except Exception as ex_fb:
                logger.warning("[SAFE_LOCAL_FALLBACK_ERROR] %s: %s", type(ex_fb).__name__, ex_fb)

        token, payload = self.sign_decision(
            turn_id=turn_id,
            prompt=clean_prompt,
            intent=intent,
            workspace_disposition=disp,
            conversation_id=conv_id,
            source=src
        )

        status = "success" if intent != "CLASSIFICATION_UNAVAILABLE" else "error"
        return {
            "status": status,
            "intent": intent,
            "workspace_disposition": disp,
            "confidence": conf,
            "source": src,
            "decision_token": token,
            "decision_payload": payload,
            "side_effect_free": True
        }

    def _query_neural_shadow(
        self,
        user_text: str,
        reasoner_decision_id: str,
        session_info: Optional[Dict[str, Any]] = None,
        effective_model: str = "",
        effective_effort: str = "",
        project_mind_summary: Optional[str] = None,
        project_mind: Optional[Dict[str, Any]] = None,
        continuity_project_id: Optional[str] = None
    ) -> Dict[str, Any]:
        """Safely queries NeuralAdvisor in shadow observability mode (Alpha66 / Alpha67).
        Strictly fail-open: exceptions or unavailable status never impede normal reasoning.
        """
        if not self.neural_advisor:
            return {
                "queried": False,
                "status": "UNAVAILABLE",
                "mode": None,
                "model_id": None,
                "observation_id": None,
                "score": None,
                "prediction": None,
                "confidence_band": None,
                "authoritative": False,
                "execution_authority": False,
                "latency_ms": 0.0
            }

        try:
            proj_id = (session_info.get("current_project") if session_info else "") or ""
            sess_id = str(session_info.get("token", "") if session_info else "")
            
            shadow_context: Dict[str, Any] = {
                "reasoner_decision_id": reasoner_decision_id,
                "project_id": continuity_project_id or proj_id,
                "workbench_project_id": proj_id,
                "continuity_project_id": continuity_project_id,
                "session_id": sess_id,
                "requested_model": effective_model,
                "requested_effort": effective_effort
            }
            if project_mind_summary and str(project_mind_summary).strip():
                shadow_context["project_mind_summary"] = str(project_mind_summary)[:1000]

            if project_mind and isinstance(project_mind, dict):
                sanitized_pm = {}
                for k in ("vision", "long_term_goals", "capabilities", "limitations", "products", "roadmap", "priorities", "decision_history", "learned_facts", "next_strategic_action"):
                    v = project_mind.get(k)
                    if v:
                        sanitized_pm[k] = v
                if sanitized_pm:
                    shadow_context["project_mind"] = sanitized_pm

            task_data = {
                "goal": user_text,
                "target": continuity_project_id or proj_id,
                "environment": "digital_optimus_current_brain_host",
                "allowed_actions": [],
                "context": shadow_context
            }

            res = self.neural_advisor.query_shadow_advice(
                task_data,
                task_id=reasoner_decision_id
            )

            status = res.get("advisor_status", "UNKNOWN")
            shadow = res.get("shadow_neural_advice") or {}
            latency = res.get("latency_ms", 0.0)

            return {
                "queried": True,
                "status": status,
                "mode": shadow.get("mode") if shadow else (self.neural_advisor.mode if hasattr(self.neural_advisor, "mode") else None),
                "model_id": shadow.get("model_id") if shadow else None,
                "observation_id": shadow.get("observation_id") if shadow else None,
                "score": shadow.get("score") if shadow else None,
                "prediction": shadow.get("prediction") if shadow else None,
                "confidence_band": shadow.get("confidence_band") if shadow else None,
                "authoritative": False,
                "execution_authority": False,
                "latency_ms": latency
            }
        except Exception as ex:
            logger.warning("[NEURAL_SHADOW_QUERY_ERROR] %s: %s", type(ex).__name__, ex)
            return {
                "queried": True,
                "status": "ERROR",
                "mode": None,
                "model_id": None,
                "observation_id": None,
                "score": None,
                "prediction": None,
                "confidence_band": None,
                "authoritative": False,
                "execution_authority": False,
                "latency_ms": 0.0
            }

    def parse_action_intent(self, user_text: str) -> Optional[Dict[str, Any]]:
        """Parses user input for known safe desktop action requests.
        Reuses patterns matching historical evidence and desktop_control allowlist.
        """
        if not user_text or not isinstance(user_text, str):
            return None
        import re
        raw = user_text.strip()

        # Clean trailing punctuation and whitespace for regex matching
        clean_raw = re.sub(r'[\s.,;:?!¡¿]+$', '', raw).strip()

        # 1. Type text command with optional app opening
        # e.g.: "abre bloc de notas y escribe Hola mundo", "abre notepad y escribe: test",
        #       "escribe en bloc de notas: hola", "teclea en bloc de notas ..."
        # Generic or compound action: open app and type text
        m_compound = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:abre|abrir|inicia|iniciar|lanzar)\s+(?:el\s+|la\s+)?([a-zA-Z0-9_\-\s]+?)\s+y\s+(?:escribe|teclea|escribir)(?:[:\s]+exactamente)?[:\s]+(.+)$',
            raw,
            re.IGNORECASE | re.DOTALL
        )
        if m_compound:
            app_name = m_compound.group(1).strip()
            payload = m_compound.group(2).strip()
            if (payload.startswith('"') and payload.endswith('"')) or (payload.startswith("'") and payload.endswith("'")):
                payload = payload[1:-1]
            alias = "notepad" if "bloc" in app_name.lower() or "notepad" in app_name.lower() else app_name
            return {
                "action": "OPEN_AND_TYPE_TEXT",
                "app_alias": alias,
                "text": payload,
                "return_to_optimus": True,
            }

        # Generic type direct
        m_type_direct = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:escribe|escribir|teclea|teclear)(?:\s+en\s+(?:el\s+|la\s+)?([a-zA-Z0-9_\-\s]+?))?[:\s]+(.+)$',
            raw,
            re.IGNORECASE | re.DOTALL
        )
        if m_type_direct:
            app_name = (m_type_direct.group(1) or "notepad").strip()
            payload = m_type_direct.group(2).strip()
            if (payload.startswith('"') and payload.endswith('"')) or (payload.startswith("'") and payload.endswith("'")):
                payload = payload[1:-1]
            alias = "notepad" if "bloc" in app_name.lower() or "notepad" in app_name.lower() else app_name
            return {
                "action": "OPEN_AND_TYPE_TEXT",
                "app_alias": alias,
                "text": payload,
                "return_to_optimus": True,
            }

        # Generic open application: "abre bloc de notas", "abre notepad", "abre calculadora", "abre browser", etc.
        m_open = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:abre|abrir|inicia|iniciar|lanzar)\s+(?:el\s+|la\s+)?([a-zA-Z0-9_\-\s]+)[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_open:
            app_name = m_open.group(1).strip()
            alias = "notepad" if "bloc" in app_name.lower() or "notepad" in app_name.lower() else app_name
            return {
                "action": "OPEN_APPLICATION",
                "app_alias": alias,
                "return_to_optimus": False,
            }

        # 3. MOUSE_MOVE
        # "Optimus, mueve el cursor al centro de la pantalla", "mueve el mouse al centro"
        m_move_center = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:mueve|mover)\s+(?:el\s+)?(?:cursor|raton|ratón|mouse)\s+al\s+centro(?:\s+de\s+la\s+pantalla)?[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_move_center:
            return {
                "action": "MOUSE_MOVE",
                "parameters": {"target": "center"}
            }

        # "Optimus, mueve el cursor a 500, 400"
        m_move_coords = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:mueve|mover)\s+(?:el\s+)?(?:cursor|raton|ratón|mouse)\s+(?:a|hacia)\s*\(?(\d+)[,\s]+(\d+)\)?[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_move_coords:
            return {
                "action": "MOUSE_MOVE",
                "parameters": {"x": int(m_move_coords.group(1)), "y": int(m_move_coords.group(2))}
            }

        # 3.5 SAFE_CLICK_TEST (Canonical: "Optimus, realiza la prueba segura de clic.")
        m_safe_click = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:realiza|realizar|haz|hacer)\s+(?:la\s+)?prueba\s+segura\s+de\s+(?:clic|click)[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_safe_click:
            return {
                "action": "SAFE_CLICK_TEST",
                "parameters": {"target": "SAFE_CLICK_TARGET", "button": "left"}
            }

        # 3.6 SAFE_KEY_TEST (Canonical: "Optimus, realiza la prueba segura de tecla.")
        m_safe_key = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:realiza|realizar|haz|hacer)\s+(?:la\s+)?prueba\s+segura\s+de\s+(?:tecla|teclado)[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_safe_key:
            return {
                "action": "SAFE_KEY_TEST",
                "parameters": {"target": "SAFE_KEY_TARGET", "key": "ENTER"}
            }

        # 3.7 SAFE_WINDOW_TEST (Canonical: "Optimus, realiza la prueba segura de ventana.")
        m_safe_win = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:(?:realiza|realizar|haz|hacer)\s+(?:la\s+)?prueba\s+(?:segura\s+)?de\s+ventana|(?:minimiza|minimizar)\s+y\s+(?:restaura|restaurar)\s+(?:la\s+)?ventana)[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_safe_win:
            return {
                "action": "SAFE_WINDOW_TEST",
                "parameters": {"command": "MINIMIZE_RESTORE"}
            }

        # 4. MOUSE_CLICK
        # "Optimus, haz clic", "haz click", "da un clic"
        m_click = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:haz|hacer|da|dar)\s+(?:un\s+)?(?:clic|click)(?:\s+(?:izquierdo|left))?[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_click:
            return {
                "action": "MOUSE_CLICK",
                "parameters": {"button": "left"}
            }

        # 5. KEY_PRESS
        # "Optimus, presiona ENTER", "pulsa la tecla ESC", "presiona TAB"
        m_key = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:presiona|presionar|pulsa|pulsar|tecla)\s+(?:la\s+tecla\s+)?([A-Za-z_]+)[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_key:
            k = m_key.group(1).upper()
            KEY_MAP = {
                "ENTER": "ENTER",
                "INTRO": "ENTER",
                "ESC": "ESC",
                "ESCAPE": "ESC",
                "TAB": "TAB",
                "BACKSPACE": "BACKSPACE",
                "BORRAR": "BACKSPACE",
                "ARRIBA": "ARROW_UP",
                "UP": "ARROW_UP",
                "ABAJO": "ARROW_DOWN",
                "DOWN": "ARROW_DOWN",
                "IZQUIERDA": "ARROW_LEFT",
                "LEFT": "ARROW_LEFT",
                "DERECHA": "ARROW_RIGHT",
                "RIGHT": "ARROW_RIGHT",
            }
            if k in KEY_MAP:
                return {
                    "action": "KEY_PRESS",
                    "parameters": {"key": KEY_MAP[k]}
                }

        # 6. OBSERVE_SCREEN / OBSERVE_ACTIVE_WINDOW
        # "Optimus, observa la pantalla", "captura la pantalla"
        m_obs_screen = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:observa|observar|captura|capturar)\s+(?:la\s+)?pantalla[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_obs_screen:
            return {
                "action": "OBSERVE_SCREEN",
                "parameters": {}
            }

        # "Optimus, observa la ventana activa", "¿qué ventana está activa?"
        m_obs_win = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:(?:observa|observar)\s+(?:la\s+)?ventana(?:\s+activa)?|¿?qu[eé]\s+ventana\s+est[aá]\s+activa\??)[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_obs_win:
            return {
                "action": "OBSERVE_ACTIVE_WINDOW",
                "parameters": {}
            }

        # 7. SAFETY CONTROLS (PAUSE, RESUME, CANCEL, KILL_SWITCH, RESET)
        # 7.1 KILL_SWITCH / PARADA DE EMERGENCIA
        m_kill = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:(?:parada\s+(?:de\s+)?emergencia)|(?:activa(?:r)?\s+(?:el\s+)?(?:kill\s*switch|bot[oó]n\s+de\s+emergencia))|(?:det[eé]n\s+todo(?:\s+inmediatamente)?)|kill\s*switch)[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_kill:
            return {
                "action": "SAFETY_KILL_SWITCH",
                "parameters": {"command": "KILL_SWITCH"}
            }

        # 7.2 RESET / RESTABLECER
        m_reset = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:restablece(?:r)?(?:\s+(?:(?:el\s+)?sistema|(?:el\s+)?control|(?:la\s+)?seguridad))?|resetear\s+seguridad)[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_reset:
            return {
                "action": "SAFETY_RESET",
                "parameters": {"command": "RESET"}
            }

        # 7.3 PAUSE
        m_pause = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:(?:pon(?:er)?\s+en\s+pausa\s+(?:las\s+)?acciones)|(?:pausa(?:r)?(?:\s+(?:las\s+)?acciones)?))[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_pause:
            return {
                "action": "SAFETY_PAUSE",
                "parameters": {"command": "PAUSE"}
            }

        # 7.4 RESUME
        m_resume = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:(?:reanuda(?:r)?(?:\s+(?:las\s+)?acciones)?)|(?:contin[uú]a(?:r)?(?:\s+(?:con\s+las\s+|las\s+)?acciones)?))[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_resume:
            return {
                "action": "SAFETY_RESUME",
                "parameters": {"command": "RESUME"}
            }

        # 7.5 CANCEL
        m_cancel = re.match(
            r'^(?:por\s+favor\s+)?(?:optimus\s*[,:]?\s*)?(?:cancela(?:r)?(?:\s+(?:la\s+)?(?:acci[oó]n|ejecuci[oó]n))?)[\s.?!]*$',
            raw,
            re.IGNORECASE
        )
        if m_cancel:
            return {
                "action": "SAFETY_CANCEL",
                "parameters": {"command": "CANCEL"}
            }

        return None

    def _format_continuity_fallback(self, ctx_data: Optional[Dict[str, Any]]) -> str:
        if not ctx_data:
            return "Entendido. ¿En qué punto deseas continuar el trabajo?"

        active_proj = ctx_data.get("active_project")
        active_tasks = ctx_data.get("active_tasks", [])
        curr_focus = ctx_data.get("current_focus") or (active_proj.get("metadata", {}).get("current_focus") if active_proj else None)
        if active_proj or active_tasks or curr_focus:
            parts = []
            if active_proj:
                parts.append(f"en el proyecto '{active_proj.get('name')}'")
            if curr_focus:
                parts.append(f"con foco en '{curr_focus}'")
            if active_tasks:
                top_t = active_tasks[0]
                if not curr_focus or curr_focus.lower() not in top_t.get("request", "").lower():
                    parts.append(f"trabajando en la tarea '{top_t.get('request')}'")
                plan = top_t.get("plan", [])
                if plan and (not curr_focus or plan[0].lower() != curr_focus.lower()):
                    parts.append(f"con el siguiente paso planificado: '{plan[0]}'")
            return f"Nos habíamos quedado {' '.join(parts)}. ¿Deseas continuar desde aquí?"

        recent_msgs = ctx_data.get("recent_messages", []) if ctx_data else []
        active_proj = ctx_data.get("active_project") if ctx_data else None
        active_proj_id = active_proj.get("id") if active_proj else (ctx_data.get("project_id") if ctx_data else None)

        user_msgs = []
        for m in recent_msgs:
            if m.get("role") != "user":
                continue
            meta = m.get("metadata") or {}
            # HARD BOUNDARY: Ignore test environment messages (Section 3 & 5)
            if meta.get("environment") in ("TEST", "E2E", "STAGING_TEST", "TESTING") or meta.get("is_test"):
                continue
            if m.get("quarantine") is True:
                continue
            cnt = m.get("content", "")
            if "REALISTIC_COMPLEX_LANDING_V1" in cnt or "TEST_LEAK_CONTAMINATED_ENTRY" in cnt:
                continue
            # Cross-project boundary (Section 14)
            m_proj = meta.get("project_id") or m.get("project_id")
            if active_proj_id and m_proj and m_proj != active_proj_id:
                continue
            user_msgs.append(m)

        if len(user_msgs) > 1:
            substantive = [m["content"] for m in user_msgs[:-1] if len(m.get("content", "")) > 5]
            if substantive:
                summary = " // ".join(substantive[-3:])
                return f"Nos habíamos quedado revisando lo siguiente en esta conversación: {summary}. ¿Continuamos desde aquí?"
        return "Entendido. Revisé el historial de esta conversación. ¿En qué punto deseas retomar el trabajo?"

    def _resolve_executive_operational_state(
        self,
        ctx_data: Optional[Dict[str, Any]],
        session_info: Optional[Dict[str, Any]],
        explicit_mission_id: Optional[str] = None,
        developer_service: Optional[Any] = None
    ) -> Dict[str, Any]:
        """Resolves Developer Workspace operational state snapshot for Executive Brain.
        Pure observation only: does not write, does not mutate ctx_data or session_info.
        Fails open on any error and returns {}.
        """
        try:
            service = developer_service
            if service is None and get_developer_service is not None:
                service = get_developer_service()

            if service is None:
                return {}

            # 1. External Project ID resolution
            # Priority:
            # 1. session_info["current_project"]
            # 2. ctx_data["project_mind"]["identity"]["external_project_id"]
            # 3. active_project metadata external_project_id
            external_proj_id = None
            if session_info and session_info.get("current_project"):
                external_proj_id = str(session_info["current_project"]).strip()

            if not external_proj_id and ctx_data:
                pm = ctx_data.get("project_mind")
                if isinstance(pm, dict):
                    pm_ident = pm.get("identity")
                    if isinstance(pm_ident, dict) and pm_ident.get("external_project_id"):
                        external_proj_id = str(pm_ident["external_project_id"]).strip()

            if not external_proj_id and ctx_data:
                act_proj = ctx_data.get("active_project")
                if isinstance(act_proj, dict):
                    act_meta = act_proj.get("metadata")
                    if isinstance(act_meta, dict) and act_meta.get("external_project_id"):
                        external_proj_id = str(act_meta["external_project_id"]).strip()
                    elif act_proj.get("external_project_id"):
                        external_proj_id = str(act_proj["external_project_id"]).strip()

            # 2. Mission ID resolution
            # Priority:
            # 1. explicit_mission_id / session_info["current_mission"]
            # 2. Look from the end of ctx_data["recent_messages"] for metadata["mission_id"]
            # 3. If still no mission_id and external_project_id exists: service.list_missions(...)
            mission_id = None
            if explicit_mission_id:
                mission_id = str(explicit_mission_id).strip()
            elif session_info and session_info.get("current_mission"):
                mission_id = str(session_info["current_mission"]).strip()

            if not mission_id and ctx_data and ctx_data.get("recent_messages"):
                for msg in reversed(ctx_data["recent_messages"]):
                    if isinstance(msg, dict):
                        m_meta = msg.get("metadata")
                        if isinstance(m_meta, dict) and m_meta.get("mission_id"):
                            m_id_str = str(m_meta["mission_id"]).strip()
                            if m_id_str:
                                mission_id = m_id_str
                                break

            if not mission_id and external_proj_id and hasattr(service, "list_missions"):
                missions_list = service.list_missions(project_id=external_proj_id)
                if isinstance(missions_list, list) and missions_list:
                    matching = [
                        m for m in missions_list
                        if isinstance(m, dict) and str(m.get("project_id") or "").strip() == external_proj_id
                    ]
                    if matching:
                        def _m_sort_key(m_dict: Dict[str, Any]) -> str:
                            return str(m_dict.get("updated_at") or m_dict.get("created_at") or "")

                        # a) pending_request.status == "PENDING" or creator_dependency WAITING_FOR_CREATOR
                        group_a = []
                        for m in matching:
                            pr = m.get("pending_request") if isinstance(m.get("pending_request"), dict) else {}
                            pr_pending = (str(pr.get("status") or "").upper() == "PENDING")
                            cds = m.get("creator_dependencies") if isinstance(m.get("creator_dependencies"), list) else []
                            cd_waiting = any(
                                isinstance(cd, dict) and str(cd.get("status") or "").upper() == "WAITING_FOR_CREATOR"
                                for cd in cds
                            )
                            if pr_pending or cd_waiting:
                                group_a.append(m)

                        if group_a:
                            selected = max(enumerate(group_a), key=lambda x: (_m_sort_key(x[1]), x[0]))[1]
                            mission_id = selected.get("mission_id")
                        else:
                            # b) non-terminal / operational states
                            terminal_states = {"FAILED", "CANCELLED", "ABORTED", "ARCHIVED", "REJECTED"}
                            group_b = [
                                m for m in matching
                                if str(m.get("status") or "").upper() not in terminal_states
                            ]
                            if group_b:
                                selected = max(enumerate(group_b), key=lambda x: (_m_sort_key(x[1]), x[0]))[1]
                                mission_id = selected.get("mission_id")
                            else:
                                # c) most recently updated
                                selected = max(enumerate(matching), key=lambda x: (_m_sort_key(x[1]), x[0]))[1]
                                mission_id = selected.get("mission_id")

            if not mission_id or not hasattr(service, "get_mission"):
                return {}

            mission = service.get_mission(mission_id)
            if not mission or not isinstance(mission, dict):
                return {}

            activity = []
            if hasattr(service, "get_mission_activity"):
                raw_act = service.get_mission_activity(mission_id)
                if isinstance(raw_act, list):
                    activity = raw_act[-20:]

            return {
                "source": "developer_workspace",
                "external_project_id": external_proj_id,
                "mission": mission,
                "activity": activity
            }
        except Exception as ex:
            logger.warning("[EXECUTIVE_OPERATIONAL_STATE_ERROR] %s: %s", type(ex).__name__, ex)
            return {}

    def _try_execute_executive_admin_step(
        self,
        clean_text: str,
        executive_decision: Any,
        operational_state: Optional[Dict[str, Any]]
    ) -> Dict[str, Any]:
        """
        Executive Administrator Safe Tools V2 / Alpha72 bridge.
        Allows executing bounded consecutive explicit safe steps (max 3) belonging to the safe allowlist
        ONLY if the user explicitly provided EXEC_ADMIN_EXECUTE and all authority/mission/step
        policies pass.
        """
        result = {
            "triggered": False,
            "allowed": False,
            "executed": False,
            "mission_id": "",
            "authority_mode": "",
            "action_type": "",
            "target": "",
            "execution_result": None,
            "block_reason": "",
            "steps_executed": 0,
            "max_steps": 3,
        }

        # 1. Trigger Check: EXEC_ADMIN_EXECUTE debe ser una directiva explícita
        # y aparecer como línea independiente. Una simple mención dentro de una frase NO activa ejecución.
        trigger_present = bool(
            clean_text
            and any(
                line.strip() == "EXEC_ADMIN_EXECUTE"
                for line in clean_text.splitlines()
            )
        )
        if not trigger_present:
            return result

        result["triggered"] = True

        # 2. Política de Autoridad Obligatoria
        if executive_decision is None:
            result["block_reason"] = "MISSING_EXECUTIVE_DECISION"
            return result

        auth_mode = str(getattr(executive_decision, "authority_mode", "") or "").upper()
        result["authority_mode"] = auth_mode

        if auth_mode not in ("AUTO", "NOTIFY_AND_CONTINUE"):
            result["block_reason"] = f"AUTHORITY_MODE_NOT_PERMITTED_{auth_mode}"
            return result

        if getattr(executive_decision, "can_continue_now", False) is not True:
            result["block_reason"] = "CAN_CONTINUE_NOW_FALSE"
            return result

        if getattr(executive_decision, "requires_creator_approval", True) is not False:
            result["block_reason"] = "REQUIRES_CREATOR_APPROVAL_TRUE"
            return result

        # 3. Misión desde operational_state["mission"]
        if not operational_state or not isinstance(operational_state, dict):
            result["block_reason"] = "MISSING_OPERATIONAL_STATE"
            return result

        mission = operational_state.get("mission")
        if not mission or not isinstance(mission, dict):
            result["block_reason"] = "MISSING_MISSION"
            return result

        mission_id = str(mission.get("mission_id") or "").strip()
        result["mission_id"] = mission_id
        if not mission_id:
            result["block_reason"] = "EMPTY_MISSION_ID"
            return result

        blocked_statuses = {
            "COMPLETED", "FAILED", "CANCELLED", "PAUSED", "PAUSE_REQUESTED",
            "WAITING_CREATOR_REVIEW", "WAITING_FOR_CREATOR_REVIEW",
            "WAITING_DEPENDENCY", "WAITING_FOR_DEPENDENCY", "BLOCKED", "BLOCKED_CAPABILITY"
        }
        mission_status = str(mission.get("status") or "").strip().upper()
        if mission_status in blocked_statuses:
            result["block_reason"] = f"BLOCKED_MISSION_STATUS_{mission_status}"
            return result

        # 4. Paso desde mission["steps"] (Alpha72: al menos un runnable step)
        steps = mission.get("steps")
        if not isinstance(steps, list):
            result["block_reason"] = "INVALID_MISSION_STEPS"
            return result

        curr_idx = mission.get("current_step_index", 0)
        step = None
        if isinstance(curr_idx, int) and 0 <= curr_idx < len(steps):
            cs = steps[curr_idx]
            if isinstance(cs, dict):
                cs_status = str(cs.get("status") or "").strip().upper()
                cs_dep = cs.get("blocking_dependency_id")
                if cs_status in ("PENDING", "READY") and not cs_dep:
                    step = cs

        if step is None:
            for s in steps:
                if not isinstance(s, dict):
                    continue
                s_status = str(s.get("status") or "").strip().upper()
                s_dep = s.get("blocking_dependency_id")
                if s_status in ("PENDING", "READY") and not s_dep:
                    step = s
                    break

        if step is None:
            result["block_reason"] = "NO_RUNNABLE_STEPS"
            return result

        action_type = str(step.get("action_type") or "").strip().upper()
        target = str(step.get("target") or "").strip()
        result["action_type"] = action_type
        result["target"] = target

        allowed_actions = {
            "CREATE_FILE",
            "READ_FILE",
            "FILE_EXISTS",
            "LIST_DIRECTORY",
            "CREATE_DIRECTORY",
            "WRITE_FILE",
        }

        # 5. Allowlist Safe Tools V2 / Alpha72 / Alpha73
        if action_type not in allowed_actions:
            result["block_reason"] = "EXEC_ADMIN_ACTION_NOT_ALLOWED"
            return result

        step_payload = step.get("payload")
        if not isinstance(step_payload, dict):
            step_payload = {}
        if action_type == "CREATE_FILE" and bool(step_payload.get("overwrite", False)) is True:
            result["block_reason"] = "EXEC_ADMIN_CREATE_FILE_OVERWRITE_FORBIDDEN"
            return result
        if action_type == "WRITE_FILE":
            if not isinstance(step_payload, dict) or "content" not in step_payload or not isinstance(step_payload.get("content"), str):
                result["block_reason"] = "EXEC_ADMIN_WRITE_CONTENT_REQUIRED"
                return result
            base_sha = step_payload.get("base_sha256")
            if not isinstance(base_sha, str) or not bool(re.fullmatch(r"^[0-9a-fA-F]{64}$", base_sha.strip())):
                result["block_reason"] = "EXEC_ADMIN_WRITE_BASE_SHA_REQUIRED"
                return result

        # 6. Delegar via EffectorRegistry canónico (sin DeveloperWorkspaceService en host)
        try:
            from foundation.contracts import ActionRequest
            from foundation.effector_runtime import EffectorRegistry
            req = ActionRequest(
                action_id=f"act_admin_{int(time.time()*1000)}",
                mission_id=mission_id,
                capability="filesystem",
                action_type=action_type,
                target=target,
                payload=step_payload or {}
            )
            act_res = EffectorRegistry.get_instance().execute_action(req)
            result["execution_result"] = {
                "status": act_res.status,
                "error": act_res.error,
                "evidence": act_res.evidence,
                "sha256": act_res.sha256,
                "bytes_written": act_res.bytes_written
            }
            if act_res.status == "SUCCESS":
                result["allowed"] = True
                result["executed"] = True
                result["steps_executed"] = 1
                return result
            else:
                result["allowed"] = False
                result["executed"] = False
                result["block_reason"] = act_res.error or "ACTION_FAILED"
                return result
        except Exception as ex_exec:
            result["executed"] = False
            result["block_reason"] = f"EXECUTION_ERROR_{type(ex_exec).__name__}"
            return result

        fresh_mission = service.get_mission(mission_id)
        if not fresh_mission or not isinstance(fresh_mission, dict):
            result["block_reason"] = "FRESH_MISSION_NOT_FOUND"
            return result

        fresh_status = str(fresh_mission.get("status") or "").strip().upper()
        if fresh_status in blocked_statuses:
            result["block_reason"] = f"FRESH_MISSION_STATUS_BLOCKED_{fresh_status}"
            return result

        fresh_steps = fresh_mission.get("steps")
        if not isinstance(fresh_steps, list):
            result["block_reason"] = "FRESH_MISSION_INVALID_STEPS"
            return result

        fresh_curr_idx = fresh_mission.get("current_step_index", 0)
        fresh_step = None
        if isinstance(fresh_curr_idx, int) and 0 <= fresh_curr_idx < len(fresh_steps):
            fcs = fresh_steps[fresh_curr_idx]
            if isinstance(fcs, dict):
                fcs_status = str(fcs.get("status") or "").strip().upper()
                fcs_dep = fcs.get("blocking_dependency_id")
                if fcs_status in ("PENDING", "READY") and not fcs_dep:
                    fresh_step = fcs

        if fresh_step is None:
            for fs in fresh_steps:
                if not isinstance(fs, dict):
                    continue
                fs_status = str(fs.get("status") or "").strip().upper()
                fs_dep = fs.get("blocking_dependency_id")
                if fs_status in ("PENDING", "READY") and not fs_dep:
                    fresh_step = fs
                    break

        if fresh_step is None:
            result["block_reason"] = "NO_RUNNABLE_STEPS"
            return result

        fresh_action_type = str(fresh_step.get("action_type") or "").strip().upper()
        fresh_target = str(fresh_step.get("target") or "").strip()
        result["action_type"] = fresh_action_type
        result["target"] = fresh_target

        if fresh_action_type not in allowed_actions:
            result["block_reason"] = "EXEC_ADMIN_ACTION_NOT_ALLOWED"
            return result

        fresh_payload = fresh_step.get("payload")
        if not isinstance(fresh_payload, dict):
            fresh_payload = {}
        if fresh_action_type == "CREATE_FILE" and bool(fresh_payload.get("overwrite", False)) is True:
            result["block_reason"] = "EXEC_ADMIN_CREATE_FILE_OVERWRITE_FORBIDDEN"
            return result
        if fresh_action_type == "WRITE_FILE":
            if not isinstance(fresh_payload, dict) or "content" not in fresh_payload or not isinstance(fresh_payload.get("content"), str):
                result["block_reason"] = "EXEC_ADMIN_WRITE_CONTENT_REQUIRED"
                return result
            fresh_base_sha = fresh_payload.get("base_sha256")
            if not isinstance(fresh_base_sha, str) or not bool(re.fullmatch(r"^[0-9a-fA-F]{64}$", fresh_base_sha.strip())):
                result["block_reason"] = "EXEC_ADMIN_WRITE_BASE_SHA_REQUIRED"
                return result

        # 7. Ejecución Bounded Multi-Step (Alpha72)
        result["allowed"] = True
        try:
            bounded_result = service.run_explicit_steps_bounded(mission_id, max_steps=3)
            result["execution_result"] = bounded_result

            if isinstance(bounded_result, dict):
                st_exec = int(bounded_result.get("steps_executed", 0) or 0)
                result["steps_executed"] = st_exec
                all_verified = bool(bounded_result.get("all_executed_steps_verified", False))

                if st_exec > 0 and all_verified is True:
                    result["executed"] = True
                else:
                    result["executed"] = False
                    result["block_reason"] = str(
                        bounded_result.get("stop_reason")
                        or bounded_result.get("reason")
                        or "STEP_EXECUTION_NOT_VERIFIED"
                    )
            else:
                result["executed"] = False
                result["block_reason"] = "INVALID_EXECUTION_RESULT"
        except Exception as ex_exec:
            result["executed"] = False
            result["block_reason"] = f"EXECUTION_ERROR_{type(ex_exec).__name__}"

        return result

    @staticmethod
    def is_protected_core_path(path: Optional[str]) -> bool:
        """Determines if the given path is equal to or inside the protected core (Digital Optimus)."""
        if not path or not str(path).strip():
            return False
        try:
            norm_p = os.path.normcase(os.path.normpath(os.path.abspath(str(path).strip())))
            core_roots = [
                os.path.normcase(os.path.normpath(os.path.abspath(str(REPO_ROOT)))),
                os.path.normcase(os.path.normpath(os.path.abspath(r"C:\xampp\htdocs\Digital Optimus")))
            ]
            for c in core_roots:
                if norm_p == c:
                    return True
                try:
                    if os.path.commonpath([norm_p, c]) == c:
                        return True
                except Exception:
                    pass
            return False
        except Exception:
            return False

    _PROHIBITED_EXISTING_WS_REGEX = re.compile(
        r'\b(?:no|sin|nunca|jam[aá]s|evit(?:a|ar|e|en)?)\b'
        r'(?:'
        r'[\s,]+'
        r'(?:ni|o|tampoco|de|en|para|dentro\s+de)?'
        r'[\s,]*'
        r'(?:'
        r'reutili[cz](?:es|ar|e|en|éis)?|'
        r'us(?:es|ar|e|en|éis)?|'
        r'utili[cz](?:es|ar|e|en|éis)?|'
        r'escrib(?:as|ir|a|an|áis)?|'
        r'modif(?:iques|icar|ique|iquen|iquéis)?|'
        r'toqu(?:es|ar|e|en|éis)?|'
        r'abr(?:as|ir|a|an|áis)?|'
        r'trabaj(?:es|ar|e|en|éis)?|'
        r'tom(?:es|ar|e|en|éis)?|'
        r'part(?:as|ir|a|an|áis)?|'
        r'depend(?:as|er|a|an|áis)?|'
        r'recurr(?:as|ir|a|an)?'
        r')'
        r')*'
        r'[\s,]+'
        r'(?:dentro\s+de\s+|en\s+|de\s+)?'
        r'(?:ning[uú]n|ningun[oa]s?|cualquier|est(?:e|os)|el|los|un|unos)?\s*'
        r'(?:'
        r'proyectos?(?:\s+(?:existent(?:e|es)|anterior(?:es)?|actual(?:es)?|abiert(?:o|os)|previ(?:o|os)))?|'
        r'workspaces?(?:\s+(?:existent(?:e|es)|anterior(?:es)?|actual(?:es)?|abiert(?:o|os)|previ(?:o|os)))?|'
        r'repositorios?(?:\s+(?:existent(?:e|es)|anterior(?:es)?|actual(?:es)?))?|'
        r'(?:carpeta|directorio)(?:\s+(?:actual|existent(?:e|es)|anterior(?:es)?))?|'
        r'archivos?(?:\s+(?:existent(?:e|es)|anterior(?:es)?))?|'
        r'c[oó]digo(?:\s+(?:actual|anterior|existente))?|'
        r'sistemas?(?:\s+(?:abiert(?:o|os)|existent(?:e|es)|actual(?:es)?|anterior(?:es)?))?|'
        r'aplicaci[oó]n(?:es)?(?:\s+(?:abiert(?:a|as)|existent(?:e|es)|actual(?:es)?|anterior(?:es)?))?'
        r')\b',
        re.IGNORECASE
    )

    _EXISTING_WS_INDICATORS = (
        "proyecto abierto", "proyecto actual", "este proyecto", "proyecto existente",
        "proyectos existentes", "proyecto anterior", "proyectos anteriores",
        "archivos existentes", "archivo existente", "revisa estos archivos", "revisa este",
        "modifica este", "mejora index.html", "en este directorio", "en la carpeta actual",
        "dentro del proyecto", "en el proyecto", "trabaja dentro", "este repositorio",
        "código actual", "codigo actual", "este código", "este codigo",
        "sistema abierto", "aplicación abierta", "aplicacion abierta"
    )

    @classmethod
    def has_positive_existing_ws_intent(cls, clean_text: str) -> bool:
        """
        Classifies whether clean_text contains positive, affirmative intent to work
        within an existing/open project, as opposed to negated or prohibited references
        (e.g., 'no reutilices ningún proyecto existente', 'sin usar proyectos anteriores').
        """
        if not clean_text:
            return False
        clean_lower = clean_text.lower()
        if not any(k in clean_lower for k in cls._EXISTING_WS_INDICATORS):
            return False

        # Scrub negated/prohibited clauses to evaluate whether any affirmative
        # existing workspace requests remain.
        scrubbed = cls._PROHIBITED_EXISTING_WS_REGEX.sub(lambda m: " " * len(m.group(0)), clean_lower)
        return any(k in scrubbed for k in cls._EXISTING_WS_INDICATORS)

    @classmethod
    def resolve_canonical_workspace(
        cls,
        session_info: Optional[Dict[str, Any]],
        clean_text: str = ""
    ) -> Tuple[Optional[str], Optional[str], bool]:
        """
        Resolves canonical workspace from session_info using priority order:
        1. workspace_root
        2. project_root
        3. requested_workspace
        4. project_path

        CRITICAL ARCHITECTURAL CONTRACT:
        - If session_info explicitly has workspace_root as None/empty, that window has NO open workspace.
        - If the Creator requested to work on an existing/open project ('has_existing_ws_intent') or did not explicitly request a new project bootstrap, NO workspace may be inferred from clean_text or another instance.
        - Bootstrap is ONLY permitted when the prompt explicitly requests a brand-new project ('is_explicit_new_project').
        """
        clean_lower = clean_text.lower()
        has_existing_ws_intent = cls.has_positive_existing_ws_intent(clean_text)

        explicit_new_indicators = (
            "crea un proyecto nuevo", "crea un nuevo proyecto", "crear un proyecto nuevo",
            "crear un nuevo proyecto", "nuevo proyecto llamado", "crea proyecto nuevo",
            "inicia un proyecto nuevo", "inicia un nuevo proyecto", "iniciar un proyecto nuevo",
            "crea una carpeta nueva", "crear una carpeta nueva", "crea una página web nueva para",
            "crea una pagina web nueva para", "crea un sitio web nuevo para",
            "crear una página web nueva para", "crear una pagina web nueva para",
            "crear un sitio web nuevo para"
        )
        # Semantic detection of new workspace/project intent
        semantic_new_patterns = (
            # Masculine and feminine adjective after noun (e.g. "proyecto nuevo", "aplicación nueva", "página web nueva", "sistema nuevo")
            r'\b(?:aplicaci[oó]n|proyecto|sistema|herramienta|sitio|p[aá]gina|workspace)\s+(?:web\s+)?nuev[oa]\b',
            # "nuevo proyecto y separado", "proyecto nuevo y separado", "proyecto separado"
            r'\b(?:proyecto|sistema|workspace)\s+(?:nuev[oa]\s+y\s+)?separad[oa]\b',
            r'\b(?:proyecto|sistema|workspace)\s+separad[oa]\b',
            # Adjective before noun (e.g. "nuevo proyecto", "nueva aplicación", "nueva página web", "nuevo sistema")
            r'\bnuev[oa]\s+(?:proyecto|aplicaci[oó]n|sistema|desarrollo|workspace|herramienta|sitio|p[aá]gina(?:\s+web)?)\b',
            # Action verb + flexible words/adverbs + target + nuev[oa]
            # e.g., "crear automáticamente un proyecto nuevo", "crea desde cero una aplicación web nueva"
            r'\b(?:crea[rn]?|inicia[rn]?|constru[iy]?[rn]?|desarrolla[rn]?)\b(?:\s+\w+){0,6}\s+\b(?:un[oa]?\s+)?(?:workspace|proyecto|sistema|aplicaci[oó]n|sitio|p[aá]gina(?:\s+web)?)\b(?:\s+\w+){0,4}\s+\bnuev[oa]\b',
            # Action verb + flexible words + nuev[oa] + target
            # e.g., "crear automáticamente un nuevo proyecto"
            r'\b(?:crea[rn]?|inicia[rn]?|constru[iy]?[rn]?|desarrolla[rn]?)\b(?:\s+\w+){0,6}\s+\bnuev[oa]\s+(?:workspace|proyecto|sistema|aplicaci[oó]n|sitio|p[aá]gina(?:\s+web)?)\b',
            # Negative assertions against reuse
            r'\bno\s+(?:existe\s+(?:un\s+)?(?:proyecto|workspace)|hay\s+(?:un\s+)?(?:workspace|proyecto))\b',
            r'\bno\s+reutili[cz](?:es|ar)\s+(?:workspaces?|proyectos?)\b',
            # Create from scratch (e.g., "crea desde cero una aplicación web")
            r'\bcrea[rn]?\s+desde\s+cero\s+(?:un[oa]?\s+)?(?:workspace|proyecto|sistema|aplicaci[oó]n|sitio|p[aá]gina(?:\s+web)?)\b',
            # Generic create project / workspace
            r'\b(?:crea[rn]?|inicia[rn]?|constru[iy]?[rn]?|desarrolla[rn]?)\b(?:\s+\w+){0,4}\s+\b(?:un\s+)?(?:workspace|proyecto)\b',
        )
        auth_intent = str((session_info.get("resolved_intent") or "") if session_info else "").strip().upper()
        auth_workspace_disposition = str((session_info.get("workspace_disposition") or "") if session_info else "").strip().upper()

        if auth_intent == "OPERATIONAL" and auth_workspace_disposition in ("CREATE_NEW", "REQUIRE_EXISTING", "OPTIONAL"):
            is_explicit_new_project = (auth_workspace_disposition == "CREATE_NEW")
            has_existing_ws_intent = (auth_workspace_disposition == "REQUIRE_EXISTING")
        else:
            is_semantic_new = any(bool(re.search(p, clean_lower)) for p in semantic_new_patterns)
            is_explicit_new_project = (is_semantic_new or any(k in clean_lower for k in explicit_new_indicators)) and not has_existing_ws_intent

        source_key = None
        raw_candidate = None

        # 0. Explicit authorized workspace in session_info takes absolute precedence
        if session_info and isinstance(session_info, dict):
            for k in ("workspace_root", "project_root", "requested_workspace", "project_path"):
                v = session_info.get(k)
                if v and str(v).strip():
                    raw_candidate = str(v).strip()
                    source_key = k
                    break

        # 1. Explicit/Semantic new project bootstrap (ONLY if no explicit workspace was authorized)
        if not raw_candidate and is_explicit_new_project:
            from artifacts.brain_host.generic_developer_executor import extract_clean_project_name
            m_path = re.search(r'\ben\s+(?:(?:la\s+carpeta|el\s+directorio|el\s+workspace|la\s+ruta|el\s+path)\s+)?([a-zA-Z]:[\\/][^\r\n"\'`]+)', clean_text)
            explicit_path = m_path.group(1).rstrip(r'\/.,;') if m_path else None
            cand = extract_clean_project_name(clean_text) if clean_text else None
            if explicit_path and explicit_path.lower().startswith(('c:\\optimusprojects', 'c:/optimusprojects')):
                raw_candidate = explicit_path
                source_key = 'explicit_bootstrap_inferred'
            elif cand and cand != "OptimusProject" and cand.lower() not in ('activo', 'actual', 'este', 'nuevo', 'abierto'):
                cand_folder = re.sub(r'[\\/*?:"<>|]', '_', cand).strip()
                raw_candidate = os.path.join(r'C:\OptimusProjects', cand_folder)
                source_key = 'explicit_bootstrap_inferred'
            else:
                proj_slug = re.sub(r'[^a-zA-Z0-9_]', '_', cand).strip('_') if cand else "project"
                raw_candidate = os.path.join(r'C:\OptimusProjects', f"{proj_slug}_{int(time.time())}")
                source_key = 'explicit_bootstrap_inferred'

        # If workspace was explicitly provided as None/empty in session_info:
        if not raw_candidate and session_info and isinstance(session_info, dict) and "workspace_root" in session_info:
            if has_existing_ws_intent:
                return None, "no_workspace", False

        if not raw_candidate:
            return None, source_key or "no_workspace", False

        try:
            from pathlib import Path as _P_ws
            norm_ws = os.path.normpath(str(_P_ws(raw_candidate).resolve()))
        except Exception:
            norm_ws = os.path.normpath(os.path.abspath(raw_candidate))

        if cls.is_protected_core_path(norm_ws):
            # En modo LAB_TEST con sesión INTERNAL_BOUNDED de auto-reparación enfocada, permitir candidate_workspace
            is_lab_internal = (
                os.environ.get("OPTIMUS_RUN_MODE") == "LAB_TEST"
                and session_info
                and isinstance(session_info, dict)
                and session_info.get("candidate_trust_level") == "INTERNAL_BOUNDED"
                and "C:\\xampp\\htdocs\\Digital Optimus".lower() not in norm_ws.lower()
            )
            if not is_lab_internal:
                return None, source_key, True

        return norm_ws, source_key, False

    def execute_executive_mission(
        self,
        creator_goal: str,
        business_goal: str = "",
        workspace: str = "",
        max_cycles: int = 20
    ) -> Dict[str, Any]:
        """FASE 11: Direct entrypoint for ExecutiveCore mission orchestration through BrainAdapter."""
        if not self.executive_core:
            from runtime_v1.foundation.executive_core import ExecutiveCore
            self.executive_core = ExecutiveCore()

        mission = self.executive_core.create_mission(
            creator_goal=creator_goal,
            business_goal=business_goal,
            workspace=workspace
        )
        completed_mission = self.executive_core.run_mission_until_complete(mission, max_cycles=max_cycles)
        return completed_mission.to_dict()

    def process_chat(
        self,
        user_text: str,
        session_info: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:

        """Processes a chat message by checking for desktop actions or delegating to Reasoning Core."""
        t0_chat = time.time()
        turn_id = str((session_info.get("turn_id") if session_info else None) or f"turn_{int(t0_chat*1000)}_{uuid.uuid4().hex[:8]}").strip()
        conv_id_hint = str((session_info.get("conversation_id") if session_info else None) or "").strip()
        logger.info(f"[CHAT_STAGE] stage=CHAT_RECEIVED turn_id={turn_id} conversation_id={conv_id_hint} elapsed_ms=0")
        logger.info(f"[CHAT_STAGE] stage=INTENT_START turn_id={turn_id} conversation_id={conv_id_hint} elapsed_ms={int((time.time()-t0_chat)*1000)}")

        # Alpha60 Request Contract Resolution
        dec_id = (session_info.get("reasoner_decision_id") if session_info else None) or f"dec_{uuid.uuid4().hex[:12]}"
        task_id = (session_info.get("task_id") if session_info else None) or f"task_{uuid.uuid4().hex[:12]}"
        client_task_id = (session_info.get("client_task_id") if session_info else None) or task_id
        explicit_model = str(session_info.get("model") or session_info.get("model_id") or "").strip() if session_info else ""
        explicit_effort = str(session_info.get("reasoning_effort") or session_info.get("effort_selected") or "").strip() if session_info else ""
        legacy_tier = str(session_info.get("tier") or session_info.get("confidence_override_tier") or "").strip().lower() if session_info else ""
        client_provider = str(session_info.get("provider") or "").strip() if session_info else ""
        client_fallback_used = bool(session_info.get("fallback_used", False)) if session_info else False
        client_fallback_reason = str(session_info.get("fallback_reason") or "") if session_info else ""

        brain_received_model = explicit_model
        brain_received_effort = explicit_effort

        if explicit_model:
            brain_effective_model = explicit_model
            if explicit_effort in ("low", "medium", "high"):
                brain_effective_effort = explicit_effort
            elif explicit_effort:
                brain_effective_effort = explicit_effort
            else:
                if legacy_tier == "cheap":
                    brain_effective_effort = "low"
                elif legacy_tier == "heavy":
                    brain_effective_effort = "high"
                else:
                    brain_effective_effort = "medium"

            if brain_effective_effort == "low":
                mapped_tier = "cheap"
            elif brain_effective_effort == "high":
                mapped_tier = "heavy"
            else:
                mapped_tier = "default"
        else:
            # Legacy routing by tier
            if legacy_tier == "heavy":
                brain_effective_model = "gpt-5.6-sol"
                brain_effective_effort = "high"
                mapped_tier = "heavy"
            elif legacy_tier == "cheap":
                brain_effective_model = "gpt-5.6-luna"
                brain_effective_effort = "low"
                mapped_tier = "cheap"
            else:
                brain_effective_model = "gpt-5.6-terra"
                brain_effective_effort = "medium"
                mapped_tier = "default"

        project_mind_telemetry: Dict[str, Any] = {
            "bound": False,
            "workbench_project_id": session_info.get("current_project") if session_info else None,
            "continuity_project_id": None,
            "schema_version": None,
            "loaded": False,
            "nonempty_sections": [],
            "strategic_update": {
                "attempted": False,
                "applied": False,
                "source_type": None,
                "sections": [],
                "evidence_recorded": False,
            }
        }

        auth_decision_id = str((session_info.get("decision_id") or "") if session_info else "").strip()
        auth_intent = str((session_info.get("resolved_intent") or "") if session_info else "").strip().upper()
        logger.info(f"[CHAT_STAGE] stage=INTENT_END intent={auth_intent} turn_id={turn_id} conversation_id={conv_id_hint} elapsed_ms={int((time.time()-t0_chat)*1000)}")

        def _wrap_response(res_dict: Dict[str, Any], outbound_model: str = "", outbound_effort: str = "", prov_err: str = "", neural_evidence: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
            logger.info(f"[CHAT_STAGE] stage=RESPONSE_WRAP turn_id={turn_id} conversation_id={res_dict.get('conversation_id') or conv_id_hint} elapsed_ms={int((time.time()-t0_chat)*1000)}")
            out_model = outbound_model or brain_effective_model
            out_effort = outbound_effort or brain_effective_effort
            p_err = prov_err or res_dict.get("provider_error", "")
            tel = {
                "reasoner_decision_id": dec_id,
                "brain_received_model": brain_received_model,
                "brain_received_effort": brain_received_effort,
                "brain_effective_model": brain_effective_model,
                "brain_effective_effort": brain_effective_effort,
                "provider_outbound_model": out_model,
                "provider_outbound_effort": out_effort,
                "fallback_used": client_fallback_used,
                "fallback_reason": client_fallback_reason,
                "provider_error": p_err or "",
            }
            logger.info(
                "[REASONER_TELEMETRY] decision_id=%s received_model=%s received_effort=%s "
                "effective_model=%s effective_effort=%s outbound_model=%s outbound_effort=%s "
                "fallback_used=%s fallback_reason=%s provider_error=%s",
                dec_id, brain_received_model, brain_received_effort,
                brain_effective_model, brain_effective_effort,
                out_model, out_effort,
                client_fallback_used, client_fallback_reason, p_err or ""
            )
            res_dict.update(tel)
            res_dict["server_telemetry"] = tel
            if neural_evidence is not None:
                res_dict["neural_advisor"] = neural_evidence
            if "project_mind" not in res_dict:
                res_dict["project_mind"] = project_mind_telemetry
            # Real runtime ACK guarantees & task correlation
            if auth_intent == "CHAT":
                res_dict["operational_task"] = False
                res_dict["task_id"] = None
                res_dict["client_task_id"] = None
                res_dict["mission_id"] = None
                res_dict["active_mission_id"] = None
                res_dict["runtime_ack"] = True
                res_dict["task_status"] = "COMPLETED"
            else:
                if "runtime_ack" not in res_dict:
                    res_dict["runtime_ack"] = bool(res_dict.get("status") in ("success", "ok") and not res_dict.get("error"))
                if "task_id" not in res_dict or not res_dict["task_id"]:
                    res_dict["task_id"] = task_id
                res_dict["client_task_id"] = client_task_id or task_id

                # Section 13: Terminal Truth - Never falsely mark operational task as COMPLETED
                canon_term = res_dict.get("canonical_terminal_status") or res_dict.get("terminal_mission_status")
                if canon_term:
                    res_dict["task_status"] = canon_term
                    res_dict["canonical_terminal_status"] = canon_term
                elif "task_status" not in res_dict:
                    # Default without completion claim:
                    res_dict["task_status"] = "RUNNING" if res_dict.get("runtime_ack") else "FAILED"
                    res_dict["canonical_terminal_status"] = res_dict["task_status"]
            if "final_result" not in res_dict and res_dict.get("response"):
                res_dict["final_result"] = res_dict.get("response")

            # CHAT replay cache storage (thread-safe, bounded, TTL 60s)
            if auth_decision_id and auth_intent == "CHAT":
                with self._chat_cache_lock:
                    if len(self._consumed_chat_cache) >= 500:
                        oldest_k = min(self._consumed_chat_cache.keys(), key=lambda k: self._consumed_chat_cache[k][0])
                        self._consumed_chat_cache.pop(oldest_k, None)
                    self._consumed_chat_cache[auth_decision_id] = (time.time(), dict(res_dict))

            logger.info(f"[CHAT_STAGE] stage=HISTORY_COMMIT turn_id={turn_id} conversation_id={res_dict.get('conversation_id') or conv_id_hint} elapsed_ms={int((time.time()-t0_chat)*1000)}")
            logger.info(f"[CHAT_STAGE] stage=CHAT_RETURN turn_id={turn_id} conversation_id={res_dict.get('conversation_id') or conv_id_hint} elapsed_ms={int((time.time()-t0_chat)*1000)}")
            return res_dict

        # 1 & 2. Validate input
        if not isinstance(user_text, str) or not user_text.strip():
            return _wrap_response({
                "status": "error",
                "message": "Empty or invalid input text.",
                "response": "Por favor escribe un mensaje valido.",
                "availability_status": "INPUT_INVALID"
            })

        clean_text = user_text.strip()

        # 8. CHAT Replay check (MUST occur before ANY continuity mutation, conversation append, ledger, or telemetry)
        if auth_decision_id:
            with self._chat_cache_lock:
                now_ts = time.time()
                expired_keys = [k for k, v in self._consumed_chat_cache.items() if now_ts - v[0] > 60]
                for k in expired_keys:
                    self._consumed_chat_cache.pop(k, None)
                if auth_decision_id in self._consumed_chat_cache:
                    cached_resp = dict(self._consumed_chat_cache[auth_decision_id][1])
                    cached_resp["replayed"] = True
                    cached_resp["provider_calls"] = 0
                    return cached_resp

        # 3. Generate or correlate unique task ID
        client_task_id = str(session_info.get("client_task_id") or session_info.get("task_id") or "").strip() if session_info else ""
        task_id = client_task_id or f"chat_{uuid.uuid4().hex[:12]}"
        logger.info(f"[BrainAdapter.process_chat] TASK_ID={task_id} CLIENT_TASK_ID={client_task_id}")

        # Continuity Engine Integration
        active_conv_id = None
        user_msg_id = None
        recalled_mem_list = []
        ctx_data = None

        # Environment & Session Isolation (Sections 2, 3, 4, 5)
        env = (session_info.get("environment") or "PRODUCTION").upper() if session_info else "PRODUCTION"
        is_test = env in ("TEST", "E2E", "STAGING_TEST", "TESTING")
        workbench_project_id = session_info.get("current_project") if session_info else None
        proj_id = workbench_project_id
        continuity_project_id = None
        mis_id = (
            session_info.get("active_mission_id")
            or session_info.get("mission_id")
            or session_info.get("current_mission")
        ) if session_info else None

        if self.continuity is not None:
            if is_test:
                # ISOLATED TEST NAMESPACE: never share device or conversation with production
                test_token = session_info.get("test_run_id") or session_info.get("session_id") or session_info.get("token") or uuid.uuid4().hex[:8]
                dev_id = f"test_{test_token}"
                req_conv_id = session_info.get("conversation_id") or f"test_conv_{test_token}"
            else:
                dev_id = str(session_info.get("device_id") or session_info.get("token") or "default_device") if session_info else "default_device"
                req_conv_id = session_info.get("conversation_id") if session_info else None

            if req_conv_id:
                conv = self.continuity.history.get_conversation(req_conv_id)
                if not conv:
                    conv = self.continuity.history.get_or_create_active_conversation(dev_id)
            else:
                conv = self.continuity.history.get_or_create_active_conversation(dev_id)

            active_conv_id = conv["id"]

            # Canonical external workbench project resolution & idempotent conversation binding (Alpha67)
            if workbench_project_id:
                try:
                    ws_root = (session_info.get("workspace_root") or session_info.get("project_root") or session_info.get("requested_workspace") or session_info.get("project_path")) if session_info else None
                    if hasattr(self.continuity, "projects") and hasattr(self.continuity.projects, "get_or_create_external_project"):
                        canonical_proj = self.continuity.projects.get_or_create_external_project(
                            external_project_id=str(workbench_project_id),
                            display_name=str(workbench_project_id),
                            workspace_root=str(ws_root) if ws_root else None
                        )
                        if canonical_proj and canonical_proj.get("id"):
                            continuity_project_id = canonical_proj["id"]
                            if hasattr(self.continuity, "history") and hasattr(self.continuity.history, "get_conversation_project"):
                                curr_bound = self.continuity.history.get_conversation_project(active_conv_id)
                                if curr_bound != continuity_project_id:
                                    self.continuity.history.set_conversation_project(active_conv_id, continuity_project_id)
                except Exception as ex_proj:
                    logger.warning("[CANONICAL_PROJECT_RESOLVER_ERROR] %s: %s", type(ex_proj).__name__, ex_proj)

            in_mode = session_info.get("input_mode", "TEXT") if session_info else "TEXT"
            msg_meta = {
                "device_id": dev_id,
                "environment": env,
                "project_id": continuity_project_id or proj_id,
                "workbench_project_id": workbench_project_id,
                "continuity_project_id": continuity_project_id,
                "mission_id": mis_id,
            }
            if is_test:
                msg_meta["is_test"] = True
                msg_meta["test_run_id"] = test_token

            user_msg = self.continuity.history.add_message(
                conv_id=active_conv_id,
                role="user",
                content=clean_text,
                input_mode=in_mode,
                metadata=msg_meta
            )
            user_msg_id = user_msg["id"]

            # Operational state extraction from natural conversation
            if hasattr(self.continuity, "extract_and_apply_operational_state"):
                self.continuity.extract_and_apply_operational_state(clean_text, active_conv_id)

            # Strategic Memory Extractor (Alpha68 - Evidence-gated)
            strat_attempted = False
            strat_applied = False
            strat_sections = []
            strat_evidence_recorded = False

            strat_patch = extract_explicit_project_mind_update(clean_text)
            if strat_patch:
                strat_attempted = True
                strat_sections = list(strat_patch.keys())

                has_creds = False
                for sk, sv in strat_patch.items():
                    if isinstance(sv, list):
                        if any(contains_suspicious_credentials(x) for x in sv):
                            has_creds = True
                            break
                    elif isinstance(sv, str) and contains_suspicious_credentials(sv):
                        has_creds = True
                        break

                if has_creds:
                    logger.warning("[STRATEGIC_MEMORY_GUARD] Rejected strategic memory update containing suspicious credentials.")
                    strat_applied = False
                    strat_evidence_recorded = False
                elif continuity_project_id and hasattr(self.continuity, "projects") and hasattr(self.continuity.projects, "apply_evidenced_project_mind_update"):
                    try:
                        source_ref = user_msg_id or active_conv_id or task_id
                        self.continuity.projects.apply_evidenced_project_mind_update(
                            project_id=continuity_project_id,
                            patch=strat_patch,
                            source_type="CREATOR_EXPLICIT",
                            source_ref=source_ref,
                            actor="CREATOR"
                        )
                        strat_applied = True
                        strat_evidence_recorded = True
                        logger.info(
                            "[STRATEGIC_MEMORY_APPLIED] project=%s sections=%s source_type=CREATOR_EXPLICIT source_ref=%s",
                            continuity_project_id, strat_sections, source_ref
                        )
                    except Exception as ex_strat:
                        logger.error("[STRATEGIC_MEMORY_ERROR] Failed to apply evidenced update: %s", ex_strat)
                        strat_applied = False
                        strat_evidence_recorded = False

            ctx_data = self.continuity.context_builder.build_context(clean_text, active_conv_id)

            # Calculate truthful Project Mind telemetry (Patch G)
            pm_obj = ctx_data.get("project_mind") if ctx_data else None
            nonempty_sections = []
            if pm_obj and isinstance(pm_obj, dict):
                ident = pm_obj.get("identity") or {}
                if any(ident.get(k) for k in ("external_project_id", "display_name", "workspace_root")):
                    nonempty_sections.append("identity")
                for sec_key in ("vision", "long_term_goals", "capabilities", "limitations", "products", "roadmap", "priorities", "decision_history", "learned_facts", "next_strategic_action"):
                    val = pm_obj.get(sec_key)
                    if val:
                        nonempty_sections.append(sec_key)

            project_mind_telemetry = {
                "bound": bool(continuity_project_id),
                "workbench_project_id": workbench_project_id,
                "continuity_project_id": continuity_project_id,
                "schema_version": pm_obj.get("schema_version", 1) if pm_obj else None,
                "loaded": bool(pm_obj and (continuity_project_id or nonempty_sections)),
                "nonempty_sections": nonempty_sections,
                "strategic_update": {
                    "attempted": strat_attempted,
                    "applied": strat_applied,
                    "source_type": "CREATOR_EXPLICIT" if strat_applied else None,
                    "sections": strat_sections,
                    "evidence_recorded": strat_evidence_recorded
                }
            }

            if ctx_data:
                for m in ctx_data.get("retrieved_memories", []):
                    m_meta = m.get("metadata") or {}
                    # Exclude test memories from entering production context
                    if not is_test and (m_meta.get("environment") in ("TEST", "E2E", "STAGING_TEST", "TESTING") or m_meta.get("is_test")):
                        continue
                    # Cross-project boundary
                    m_proj = m_meta.get("project_id")
                    if continuity_project_id and m_proj and m_proj not in (continuity_project_id, workbench_project_id):
                        continue
                    elif proj_id and m_proj and m_proj != proj_id:
                        continue
                    recalled_mem_list.append(m["content"])

        # 6. CHAT_LOCAL via LocalAnswerRouter (pure, provider_calls=0)
        if auth_intent == "CHAT":
            try:
                from runtime_v1.foundation.local_answer_router import get_shared_router
                local_rtr = get_shared_router()
                route_res = local_rtr.route(clean_text)
                if route_res and getattr(route_res, "handled", False):
                    ans_text = getattr(route_res, "answer", "")
                    if self.continuity is not None and active_conv_id:
                        self.continuity.history.add_message(
                            conv_id=active_conv_id,
                            role="assistant",
                            content=ans_text,
                            metadata={"intent": "CHAT", "mode": "CHAT_LOCAL"}
                        )
                    return _wrap_response({
                        "status": "success",
                        "response": ans_text,
                        "final_result": ans_text,
                        "intent": "CHAT",
                        "route_mode": "CHAT_LOCAL",
                        "operational_task": False,
                        "task_id": None,
                        "client_task_id": None,
                        "mission_id": None,
                        "active_mission_id": None,
                        "provider_calls": 0,
                        "conversation_id": active_conv_id,
                        "message_id": user_msg_id,
                        "runtime_ack": True,
                        "availability_status": "READY",
                        "source": getattr(route_res, "source", "local_answer_router")
                    })
            except Exception as ex_rtr:
                logger.warning("[CHAT_LOCAL_ROUTER_ERROR] %s: %s", type(ex_rtr).__name__, ex_rtr)

        # WORKSPACE_REQUIRED GATING (SSOT: only block when prompt unequivocally targets an existing open workspace)
        # Brain is SSOT: with workspace=None, do NOT block by default.
        client_ws = (session_info.get("workspace_root") or session_info.get("project_root")) if session_info else None
        clean_lower = clean_text.lower()
        requested_ws, ws_source_key, is_ws_protected_core = self.resolve_canonical_workspace(session_info, clean_text)

        auth_intent = str(
            (session_info.get("resolved_intent") or "")
            if session_info else ""
        ).strip().upper()
        auth_workspace_disposition = str(
            (session_info.get("workspace_disposition") or "")
            if session_info else ""
        ).strip().upper()

        if auth_intent == "OPERATIONAL" and auth_workspace_disposition in ("CREATE_NEW", "REQUIRE_EXISTING", "OPTIONAL"):
            is_explicit_new_project = (auth_workspace_disposition == "CREATE_NEW")
            has_existing_ws_intent = (auth_workspace_disposition == "REQUIRE_EXISTING")
        else:
            is_explicit_new_project = (ws_source_key == 'explicit_bootstrap_inferred')
            has_existing_ws_intent = self.has_positive_existing_ws_intent(clean_text) and not is_explicit_new_project

        if auth_intent != "CHAT" and session_info and not client_ws:
            if has_existing_ws_intent:
                resp_text = (
                    "**WORKSPACE_REQUIRED**\n\n"
                    "Esta instrucción solicita trabajar dentro del proyecto abierto, pero esta ventana "
                    "no tiene ningún proyecto abierto (`workspace = None`).\n\n"
                    "Por favor abre o crea un proyecto primero (`File -> Open Folder...`)."
                )
                if self.continuity is not None and active_conv_id:
                    self.continuity.history.add_message(
                        conv_id=active_conv_id,
                        role="assistant",
                        content=resp_text,
                        metadata={"intent": "WORKSPACE_REQUIRED"}
                    )
                return _wrap_response({
                    "status": "error",
                    "intent": "WORKSPACE_REQUIRED",
                    "response": resp_text,
                    "message": resp_text,
                    "task_id": task_id,
                    "task_status": "FAILED",
                    "runtime_ack": False,
                    "actions_executed": [],
                    "availability_status": "WORKSPACE_REQUIRED"
                })

        # 1. Capability Mission Dispatch (Brain Decides, Remote Effectors Execute)
        try:
            current_cap_mission_res = None
            cap_planner = None
            if auth_intent != "CHAT":
                from artifacts.brain_host.capability_mission_planner import CapabilityMissionPlanner
                gateway_url = session_info.get("gateway_url") if session_info else None
                requested_ws, ws_source_key, _ = self.resolve_canonical_workspace(session_info, clean_text)
                if is_explicit_new_project and not requested_ws:
                    from artifacts.brain_host.generic_developer_executor import extract_clean_project_name
                    m_path = re.search(r'\ben\s+(?:(?:la\s+carpeta|el\s+directorio|el\s+workspace|la\s+ruta|el\s+path)\s+)?([a-zA-Z]:[\\/][^\r\n"\'`]+)', clean_text)
                    explicit_path = m_path.group(1).rstrip(r'\/.,;') if m_path else None
                    cand = extract_clean_project_name(clean_text) if clean_text else None
                    if explicit_path and explicit_path.lower().startswith(('c:\\optimusprojects', 'c:/optimusprojects')):
                        requested_ws = explicit_path
                    elif cand and cand != "OptimusProject" and cand.lower() not in ('activo', 'actual', 'este', 'nuevo', 'abierto'):
                        cand_folder = re.sub(r'[\\/*?:"<>|]', '_', cand).strip()
                        requested_ws = os.path.join(r'C:\OptimusProjects', cand_folder)
                    else:
                        proj_slug = re.sub(r'[^a-zA-Z0-9_]', '_', cand).strip('_') if cand else "project"
                        requested_ws = os.path.join(r'C:\OptimusProjects', f"{proj_slug}_{int(time.time())}")
                    ws_source_key = 'explicit_bootstrap_inferred'

                ws_for_caps = requested_ws or (session_info.get("workspace_root") if session_info else None)
                if not ws_for_caps and not is_explicit_new_project:
                    ws_for_caps = None
                # Do not mutate shared self.workspace_root to prevent cross-window contamination
                pass
                cap_planner = getattr(self, "cap_planner", None) or CapabilityMissionPlanner(self.effector_registry, gateway_url=gateway_url)

            # Check for verification follow-up first (e.g. "nunca vi que se abrió bloc de notas verifica")
            if cap_planner and hasattr(cap_planner, "is_verification_followup") and cap_planner.is_verification_followup(clean_text):
                fol_res = cap_planner.handle_verification_followup(
                    prompt=clean_text,
                    workspace_root=ws_for_caps,
                    mission_id=mis_id,
                    instance_id=(session_info.get("instance_id") if session_info else None),
                    conversation_id=active_conv_id,
                    task_id=task_id
                )
                resp_text = fol_res["response"]
                is_verif_ok = (fol_res.get("verification_status") == "VERIFIED")
                if self.continuity is not None and active_conv_id:
                    self.continuity.history.add_message(
                        conv_id=active_conv_id,
                        role="assistant",
                        content=resp_text,
                        metadata={"intent": "VERIFICATION_FOLLOWUP", "mission_id": fol_res["mission_id"]}
                    )
                return _wrap_response({
                    "status": "success" if is_verif_ok else "failed",
                    "response": resp_text,
                    "intent": "VERIFICATION_FOLLOWUP",
                    "mission_id": fol_res["mission_id"],
                    "task_id": task_id,
                    "task_status": "COMPLETED" if is_verif_ok else "NOT_VERIFIED",
                    "verification_status": fol_res.get("verification_status", "NOT_VERIFIED"),
                    "canonical_terminal_status": "COMPLETED_AND_E2E_VERIFIED" if is_verif_ok else "FAILED",
                    "runtime_ack": True,
                    "actions_executed": fol_res.get("actions_executed", []),
                    "confidence": 0.99 if is_verif_ok else 0.0,
                    "availability_status": "READY",
                    "provider_used": "capability_mission_planner",
                    "conversation_id": active_conv_id,
                    "message_id": user_msg_id,
                    "recalled_memories": recalled_mem_list
                }, outbound_model="capability_planner_v1")

            sess_instance_id = (session_info.get("instance_id") or "") if session_info else ""
            if not sess_instance_id and hasattr(cap_planner, "registry") and cap_planner.registry and hasattr(cap_planner.registry, "get_workspace") and ws_for_caps:
                ws_reg = cap_planner.registry.get_workspace(ws_for_caps)
                if ws_reg and getattr(ws_reg, "instance_id", None):
                    sess_instance_id = ws_reg.instance_id
            req_focused_test = (session_info.get("focused_test") if session_info else None) or None
            if cap_planner and (
                (hasattr(cap_planner, "is_capability_request") and cap_planner.is_capability_request(clean_text))
                or bool(req_focused_test)
            ):
                planned_actions = cap_planner.plan_actions(
                    clean_text,
                    ws_for_caps,
                    mission_id=mis_id or task_id,
                    instance_id=sess_instance_id,
                    focused_test=req_focused_test,
                )
                if planned_actions:
                    mission_res = cap_planner.execute_and_verify(
                        planned_actions,
                        ws_for_caps,
                        current_mission_id=mis_id or task_id,
                        instance_id=sess_instance_id
                    )
                    current_cap_mission_res = mission_res
                    resp_text = cap_planner.synthesize_response(mission_res, clean_text)

                    if self.continuity is not None and active_conv_id:
                        asst_meta = {
                            "intent": "CAPABILITY_MISSION",
                            "mission_id": mission_res["mission_id"],
                            "actions_executed": mission_res["actions_executed"],
                            "environment": env,
                            "project_id": proj_id
                        }
                        if is_test:
                            asst_meta["is_test"] = True
                        self.continuity.history.add_message(
                            conv_id=active_conv_id,
                            role="assistant",
                            content=resp_text,
                            metadata=asst_meta
                        )
                        if user_msg_id and not is_test:
                            self.continuity.memory.extract_and_store_candidates(clean_text, resp_text, active_conv_id, user_msg_id)

                    task_passed = bool(mission_res.get("all_passed", True) and not getattr(cap_planner, "last_planning_errors", None))
                    actions_exec = mission_res.get("actions_executed", [])

                    # Verification contract: Only mark VERIFICATION_FAILED if there is a demonstrated real failure
                    # Invariant A: A recoverable intermediate failure MUST NOT remain the canonical failure if recovery succeeded
                    verification_failure_record = None
                    verification_reason = None

                    # FIX 8: Prioritize physical command/test failure over pseudo-action VERIFY_EDIT failure
                    cmd_failure_record = None
                    for a in actions_exec:
                        if a.get("action_type") == "EXECUTE_COMMAND":
                            ec = a.get("exit_code")
                            st = str(a.get("status") or "")
                            if (ec is not None and ec != 0) or st in ("FAILED", "BLOCKED"):
                                cmd_failure_record = a
                                break

                    if cmd_failure_record is not None:
                        verification_failure_record = cmd_failure_record
                        out_s = (cmd_failure_record.get("stdout") or "").strip()
                        err_s = (cmd_failure_record.get("stderr") or "").strip()
                        err_m = str(cmd_failure_record.get("error") or "").strip()
                        comb = f"{out_s}\n{err_s}".strip()
                        ec_val = cmd_failure_record.get("exit_code")
                        if comb:
                            verification_reason = f"COMMAND_FAILED_EXIT_CODE_{ec_val}: {comb}"
                        else:
                            verification_reason = err_m or f"COMMAND_FAILED_EXIT_CODE_{ec_val}"
                    else:
                        for a in actions_exec:
                            # Skip actions that were successfully resolved via recovery
                            if a.get("resolved") is True or a.get("recovery_status") == "SUCCESS" or a.get("is_recovered") or a.get("recovered_by_action_id"):
                                continue

                            err = str(a.get("error") or "")
                            st = str(a.get("status") or "")
                            req_v = a.get("evidence", {}).get("requirement_verification") if isinstance(a.get("evidence"), dict) else None
                            if st in ("FAILED", "BLOCKED"):
                                verification_failure_record = a
                                verification_reason = err or f"ACTION_STATUS_{st}"
                                break
                            if "VERIFICATION_FAILED" in err:
                                verification_failure_record = a
                                verification_reason = err
                                break
                            elif req_v and req_v.get("status") not in ("COMPLETED_AND_E2E_VERIFIED", "VERIFIED", "PASS", None):
                                verification_failure_record = a
                                verification_reason = f"{req_v.get('status')}: {req_v.get('message')}"
                                break
                            elif a.get("action_type") == "EXECUTE_COMMAND" and a.get("exit_code") not in (0, None):
                                verification_failure_record = a
                                verification_reason = f"COMMAND_FAILED_EXIT_CODE_{a.get('exit_code')}"
                                break

                    is_real_verification_failure = (
                        verification_failure_record is not None or
                        mission_res.get("terminal_mission_status") == "VERIFICATION_FAILED" or
                        bool(mission_res.get("final_ui_error")) or
                        mission_res.get("creator_requirements_satisfied") is False or
                        mission_res.get("objective_requirements_satisfied") is False
                    )

                    # Section 19/C13-08 Deliverable Artifact Contract Check
                    try:
                        from app.system_health.recovery_orchestrator import verify_deliverable_artifacts
                        art_ok, art_reason, art_missing = verify_deliverable_artifacts(ws_for_caps, actions_exec)
                        if not art_ok:
                            is_real_verification_failure = True
                            verification_reason = art_reason or "REQUIRED_ARTIFACT_MISSING"
                            task_passed = False
                            mission_res["all_passed"] = False
                            mission_res["terminal_mission_status"] = "VERIFICATION_FAILED"
                            mission_res["error"] = verification_reason
                            mission_res["verification_reason"] = verification_reason
                            mission_res["missing_artifacts"] = art_missing
                    except Exception as _ex_art:
                        logger.debug("[BrainAdapter] Deliverable artifact check exception: %s", _ex_art)
                    creator_reqs_ok = bool(mission_res.get("creator_requirements_satisfied", True) and mission_res.get("objective_requirements_satisfied", True))
                    if not verification_reason and mission_res.get("final_ui_error"):
                        verification_reason = mission_res.get("final_ui_error")
                    elif not verification_reason and not creator_reqs_ok:
                        verification_reason = "CREATOR_REQUIREMENTS_NOT_SATISFIED"
                    elif not verification_reason and not task_passed:
                        verification_reason = "MISSION_VERIFICATION_FAILED"

                    if is_real_verification_failure:
                        canonical_terminal_status = "VERIFICATION_FAILED"
                        status_str = "failed"
                    elif task_passed and not is_real_verification_failure and creator_reqs_ok:
                        canonical_terminal_status = "COMPLETED_AND_E2E_VERIFIED"
                        status_str = "success"
                    else:
                        canonical_terminal_status = "FAILED"
                        status_str = "failed"

                    terminal_task_status = canonical_terminal_status
                    terminal_mission_status = canonical_terminal_status
                    workbench_status = canonical_terminal_status
                    workbench_state = canonical_terminal_status
                    brain_terminal_status = canonical_terminal_status
                    conversation_terminal_status = canonical_terminal_status

                    artifacts_created = any(a.get("action_type") in ("WRITE_FILE", "VERIFY_EDIT") and a.get("status") == "SUCCESS" for a in actions_exec)
                    workspace_inspected = any(a.get("action_type") in ("READ_FILE", "DIRECTORY_LIST") and a.get("status") == "SUCCESS" for a in actions_exec) or bool(ws_for_caps)
                    commands_run = any(a.get("action_type") == "EXECUTE_COMMAND" and a.get("status") == "SUCCESS" for a in actions_exec)

                    task_stages = {
                        "ANALYZE_REQUIREMENTS": {"status": "completed", "percent": 100},
                        "INSPECT_WORKSPACE": {"status": "completed" if workspace_inspected else "skipped", "percent": 100 if workspace_inspected else 0},
                        "CREATE_OR_MODIFY_ARTIFACTS": {"status": "completed" if artifacts_created else ("failed" if not task_passed and not artifacts_created else "completed"), "percent": 100 if artifacts_created else (0 if not task_passed else 100)},
                        "RUN_OR_PREVIEW": {"status": "completed" if commands_run else ("failed" if not task_passed and not commands_run else "completed"), "percent": 100 if commands_run else (0 if not task_passed else 100)},
                        "VERIFY_OUTPUT": {"status": "completed" if task_passed else "failed", "percent": 100 if task_passed else 0}
                    }
                    tasks_list = [
                        {"name": k, "status": v["status"], "percent": v["percent"]}
                        for k, v in task_stages.items()
                    ]

                    canonical_mission_id = mis_id or mission_res.get("mission_id") or task_id
                    return _wrap_response({
                        "status": status_str,
                        "response": resp_text,
                        "intent": "CAPABILITY_MISSION",
                        "mission_id": canonical_mission_id,
                        "active_mission_id": canonical_mission_id,
                        "task_id": task_id,
                        "client_task_id": client_task_id or task_id,
                        "canonical_terminal_status": canonical_terminal_status,
                        "brain_terminal_status": brain_terminal_status,
                        "conversation_terminal_status": conversation_terminal_status,
                        "task_status": terminal_task_status,
                        "mission_status": terminal_mission_status,
                        "terminal_mission_status": terminal_mission_status,
                        "badge": "COMPLETED" if canonical_terminal_status == "COMPLETED_AND_E2E_VERIFIED" else "FAILED",
                        "workbench_status": workbench_status,
                        "workbench_state": workbench_state,
                        "verification_status": "PASSED" if task_passed and not is_real_verification_failure else ("FAILED" if is_real_verification_failure else "UNVERIFIED"),
                        "verification_reason": verification_reason,
                        "error": (verification_reason or mission_res.get("final_ui_error") or "VERIFICATION_FAILED") if status_str != "success" else None,
                        "final_ui_error": mission_res.get("final_ui_error"),
                        "creator_requirements_satisfied": (canonical_terminal_status == "COMPLETED_AND_E2E_VERIFIED"),
                        "objective_requirements_satisfied": (canonical_terminal_status == "COMPLETED_AND_E2E_VERIFIED"),
                        "runtime_ack": True,
                        "actions_executed": actions_exec,
                        "focused_test": req_focused_test,
                        "target_file": session_info.get("target_file") if session_info else None,
                        "target_files": session_info.get("target_files") if session_info else None,
                        "creator_request": session_info.get("creator_request") if session_info else None,
                        "workspace_is_disposable": session_info.get("workspace_is_disposable") if session_info else None,
                        "expected_artifact_rel": session_info.get("expected_artifact_rel") if session_info else None,
                        "task_stages": task_stages,
                        "tasks": tasks_list,
                        "workspace_root": ws_for_caps,
                        "confidence": 0.99 if task_passed else 0.0,
                        "availability_status": "READY",
                        "provider_used": "capability_mission_planner",
                        "conversation_id": active_conv_id,
                        "message_id": user_msg_id,
                        "recalled_memories": recalled_mem_list
                    }, outbound_model="capability_planner_v1")
                elif getattr(cap_planner, "last_planning_errors", None):
                    err_lines = [e for e in cap_planner.last_planning_errors]
                    is_blocker = any("CAPABILITY_BLOCKER" in e for e in err_lines)
                    resp_text = "\n".join(err_lines)
                    canonical_mission_id = mis_id or task_id
                    return _wrap_response({
                        "status": "blocked" if is_blocker else "failed",
                        "response": resp_text,
                        "intent": "CAPABILITY_MISSION",
                        "mission_id": canonical_mission_id,
                        "active_mission_id": canonical_mission_id,
                        "task_id": task_id,
                        "client_task_id": client_task_id or task_id,
                        "task_status": "CAPABILITY_BLOCKER" if is_blocker else "FAILED",
                        "mission_status": "CAPABILITY_BLOCKER" if is_blocker else "FAILED",
                        "terminal_mission_status": "CAPABILITY_BLOCKER" if is_blocker else "FAILED",
                        "badge": "FAILED",
                        "workbench_status": "BLOCKED" if is_blocker else "FAILED",
                        "workbench_state": "BLOCKED" if is_blocker else "FAILED",
                        "runtime_ack": False,
                        "actions_executed": [],
                        "confidence": 0.0,
                        "availability_status": "BLOCKED" if is_blocker else "READY",
                        "provider_used": "capability_mission_planner",
                        "conversation_id": active_conv_id,
                        "message_id": user_msg_id,
                        "recalled_memories": recalled_mem_list
                    }, outbound_model="capability_planner_v1")
                else:
                    canonical_mission_id = mis_id or task_id
                    resp_text = "No se pudieron planificar acciones físicas ejecutables para esta orden operacional."
                    return _wrap_response({
                        "status": "failed",
                        "response": resp_text,
                        "error": "NO_ACTIONS_PLANNED: La solicitud fue clasificada como operacional pero no se generaron acciones válidas.",
                        "error_code": "NO_ACTIONS_PLANNED",
                        "intent": "CAPABILITY_MISSION",
                        "mission_id": canonical_mission_id,
                        "active_mission_id": canonical_mission_id,
                        "task_id": task_id,
                        "client_task_id": client_task_id or task_id,
                        "task_status": "FAILED",
                        "mission_status": "FAILED",
                        "terminal_mission_status": "FAILED",
                        "canonical_terminal_status": "FAILED",
                        "badge": "FAILED",
                        "workbench_status": "FAILED",
                        "workbench_state": "FAILED",
                        "verification_status": "FAILED",
                        "creator_requirements_satisfied": False,
                        "objective_requirements_satisfied": False,
                        "runtime_ack": False,
                        "actions_executed": [],
                        "confidence": 0.0,
                        "availability_status": "READY",
                        "provider_used": "capability_mission_planner",
                        "conversation_id": active_conv_id,
                        "message_id": user_msg_id,
                        "recalled_memories": recalled_mem_list
                    }, outbound_model="capability_planner_v1")
        except Exception as ex_cap:
            logger.error(f"[BrainAdapter] Capability mission planner error: {ex_cap}", exc_info=True)
            import sys
            executed = (current_cap_mission_res.get("actions_executed", []) if isinstance(current_cap_mission_res, dict) else [])
            succ_acts = [a for a in executed if a.get("status") in ("SUCCESS", "VERIFIED") or a.get("verified")]
            if auth_intent != "CHAT" and (succ_acts or is_explicit_new_project or (cap_planner and hasattr(cap_planner, "is_capability_request") and cap_planner.is_capability_request(clean_text))):
                is_real_verif_fail = any("VERIFICATION_FAILED" in str(a.get("error") or "") for a in executed)
                fail_status = "VERIFICATION_FAILED" if is_real_verif_fail else "FAILED"
                err_resp = f"Error en ejecución de misión operativa: {ex_cap}"
                if succ_acts:
                    err_resp = f"Acciones físicas ejecutadas ({len(succ_acts)} exitosas). Error posterior: {ex_cap}"
                ex_str = str(ex_cap)
                err_code = "DOMAIN_CONTRACT_MISSING" if "DOMAIN_CONTRACT_MISSING" in ex_str else (getattr(ex_cap, "error_code", None) or "CAPABILITY_PLANNER_ERROR")
                err_stage = "DOMAIN_CONTRACT" if "DOMAIN_CONTRACT_MISSING" in ex_str else "PLANNING"
                canonical_mission_id = mis_id or (current_cap_mission_res.get("mission_id") if isinstance(current_cap_mission_res, dict) else None) or task_id
                try:
                    import traceback
                    from app.system_health.health_supervisor import get_health_supervisor
                    sup = get_health_supervisor()
                    if sup:
                        sup.record_system_event(
                            event_type=err_code,
                            details={
                                "error": ex_str,
                                "symptom": ex_str,
                                "exception": ex_cap,
                                "traceback": traceback.format_exc(),
                                "task_id": task_id,
                                "mission_id": canonical_mission_id,
                                "workspace": ws_for_caps,
                                "creator_request": clean_text,
                                "component_id": "MISSION_PLANNER",
                            },
                            auto_recover=True,
                        )
                except Exception as _ex_sup:
                    logger.debug("[BrainAdapter] Health supervisor event logging error: %s", _ex_sup)

                return _wrap_response({
                    "status": "failed",
                    "response": err_resp,
                    "error": ex_str,
                    "error_code": err_code,
                    "stage": err_stage,
                    "final_result": err_resp,
                    "intent": "CAPABILITY_MISSION",
                    "mission_id": canonical_mission_id,
                    "active_mission_id": canonical_mission_id,
                    "task_id": task_id,
                    "client_task_id": client_task_id or task_id,
                    "task_status": fail_status,
                    "mission_status": fail_status,
                    "workbench_status": "FAILED",
                    "workbench_state": "FAILED",
                    "terminal_mission_status": "FAILED",
                    "verification_status": "FAILED" if is_real_verif_fail else "ERROR",
                    "runtime_ack": True,
                    "actions_executed": executed,
                    "physical_action_count": len(succ_acts),
                    "confidence": 0.0,
                    "availability_status": "READY",
                    "provider_used": "capability_mission_planner",
                    "conversation_id": active_conv_id,
                    "message_id": user_msg_id,
                    "recalled_memories": recalled_mem_list
                }, outbound_model="capability_planner_v1")

        # 2. Follow-up / URL Query Interceptor: Handle questions about URL / link without triggering a build pipeline
        import re
        is_info_url_req = bool(re.search(
            r"\b(?:dame|cu[aá]l|p[aá]same|mu[eé]strame|qu[eé]\s+es|expl[ií]came|c[oó]mo\s+abrir|d[oó]nde)\b",
            clean_text,
            re.IGNORECASE
        ))
        is_operational_open_req = (not is_info_url_req) and bool(re.search(
            r"\b(?:abre|abrir|entra|entrar|navega|navegar|visita|visitar|accede|acceder|carga|cargar)\b.*?(?:https?://|[a-zA-Z0-9_\-]+\.(?:com|org|net|io|local|html)|enlace|link|url|navegador|browser|sitio|web|p[aá]gina)",
            clean_text,
            re.IGNORECASE
        ))

        is_url_query = (not is_operational_open_req) and bool(re.search(
            r"\b(dame|cu[aá]l|p[aá]same|mu[eé]strame|ver)?\s*(el|la)?\s*(url|link|enlace)\b|\b(d[oó]nde|como)\s+(lo\s+veo|ver|abrir)\b|\b(qu[eé]\s+es|expl[ií]came)\b.*?https?://",
            clean_text,
            re.IGNORECASE
        ))
        if is_url_query:
            requested_ws, ws_source_key, _ = self.resolve_canonical_workspace(session_info, clean_text)
            if not requested_ws and session_info:
                requested_ws = session_info.get("workspace_root") or session_info.get("project_root")

            import socket
            from urllib.parse import quote
            apache_running = False
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.settimeout(0.8)
                apache_running = (s.connect_ex(('127.0.0.1', 80)) == 0)
                s.close()
            except Exception:
                apache_running = False

            htdocs_norm = os.path.normcase(os.path.abspath(r"C:\xampp\htdocs"))
            ws_norm = os.path.normcase(os.path.abspath(requested_ws)) if requested_ws else ""
            if ws_norm and (ws_norm == htdocs_norm or ws_norm.startswith(htdocs_norm + os.sep)):
                rel_parts = os.path.relpath(requested_ws, r"C:\xampp\htdocs").replace("\\", "/")
                url_path = "/".join(quote(p) for p in rel_parts.split("/") if p)
                final_url = f"http://localhost/{url_path}/"
                if apache_running:
                    answer_text = (
                        f"La página está disponible en:\n"
                        f"{final_url}\n\n"
                        f"(Servidor Apache verificado físicamente en http://localhost)"
                    )
                else:
                    answer_text = (
                        f"El proyecto está listo en `{requested_ws}`, pero Apache no está activo en el puerto 80, "
                        f"por eso todavía no puedo darte una URL funcional."
                    )
            elif requested_ws:
                index_p = os.path.join(requested_ws, "index.html") if requested_ws else ""
                if index_p and os.path.exists(index_p):
                    answer_text = f"El proyecto está ubicado en `{requested_ws}`. Al estar fuera de htdocs, puedes abrir `index.html` directamente en tu navegador o servirlo con `python -m http.server`."
                else:
                    answer_text = f"El proyecto está ubicado en `{requested_ws}`. Nota: `index.html` no existe todavía en el workspace."
            else:
                answer_text = "No hay un proyecto web activo seleccionado en este momento."

            try:
                from runtime_v1.foundation.self_dev_loop import validate_response_references
                _, answer_text = validate_response_references(answer_text, requested_ws)
            except Exception:
                pass

            return {
                "status": "success",
                "runtime_ack": True,
                "task_status": "COMPLETED",
                "response": answer_text,
                "final_result": answer_text,
                "conversation_id": active_conv_id,
                "message_id": user_msg_id,
                "availability_status": "READY",
                "provider_used": "brain_adapter_url_resolver"
            }

        # 2. Operational Task Bridge to optimus_user_agent -> run_self_dev_pipeline
        # REQUISITO 1: task_id debe llegar intacto al runtime.
        # REQUISITO 2: operational_task=True debe forzar ruta runtime/self-dev.
        # REQUISITO 3: no usar DIRECT_CREATOR_CHAT para tareas complejas.
        if auth_intent == "CHAT":
            is_operational = False
        else:
            is_operational = bool(session_info and (
                session_info.get("operational_task") or 
                session_info.get("is_project_task") or
                str(session_info.get("task_id") or "").startswith("task_") or
                str(session_info.get("client_task_id") or "").startswith("task_")
            ))
            clean_lower = clean_text.lower()
            if not is_operational and any(k in clean_lower for k in [
                "alpha", "alphas", "self_dev", "e2e_runtime_probe", "crea dentro de un workspace",
                "pagina web", "página web", "sitio web", "website",
                "sistema", "software", "portal web", "optimusprojects", "optimus developer", "crear proyecto"
            ]):
                is_question = bool(re.search(r"^(qu[eé]|c[oó]mo|d[oó]nde|por\s+qu[eé]|cu[aá]l|hola|ayuda)\b", clean_lower))
                if not is_question:
                    is_operational = True

        # Workspace handoff: Resolve canonical external workspace (priority: workspace_root -> project_root -> requested_workspace -> project_path)
        requested_ws, ws_source_key, is_ws_protected_core = self.resolve_canonical_workspace(session_info, clean_text)

        # REQUISITO 4: Rechazar/proteger C:\xampp\htdocs\Digital Optimus y cualquier ruta hija
        if is_ws_protected_core:
            raw_core_ws = (session_info.get(ws_source_key) if (session_info and ws_source_key) else None) or "Digital Optimus"
            logger.error(
                "[BrainAdapter] Operational task rejected: attempted to use protected core as mutable workspace: %s (source_key=%s)",
                raw_core_ws, ws_source_key
            )
            handoff_trace = (
                f"[WORKSPACE_HANDOFF]\n"
                f"task_id={task_id}\n"
                f"source_key={ws_source_key}\n"
                f"resolved_workspace=None\n"
                f"protected_core=True"
            )
            logger.warning(handoff_trace)
            print(handoff_trace)

            err_payload = {
                "status": "error",
                "runtime_ack": False,
                "task_id": task_id,
                "client_task_id": client_task_id or task_id,
                "task_status": "ERROR",
                "error": f"PROTECTED_CORE_REJECTED: {raw_core_ws} is protected core and cannot be used as mutable workspace",
                "response": f"Error: La ruta '{raw_core_ws}' pertenece al núcleo protegido y no puede ser modificada como workspace externo.",
                "availability_status": "RUNTIME_ERROR",
                "provider_used": "optimus_user_agent_pipeline",
                "conversation_id": active_conv_id,
                "message_id": user_msg_id,
                "PROTECTED_CORE_WRITABLE": False,
                "RUNTIME_WORKSPACE_ROOT": None,
            }
            return _wrap_response(err_payload, outbound_model="self_dev_loop_v1")

        requested_ws_created = False
        if requested_ws and is_operational:
            try:
                ws_existed_before = os.path.exists(requested_ws)
                os.makedirs(requested_ws, exist_ok=True)
                requested_ws_created = (not ws_existed_before) and os.path.isdir(requested_ws)
            except Exception as ex_mk:
                logger.warning(f"[WORKSPACE_CREATE_ERROR] {ex_mk}")

            project_name = os.path.basename(requested_ws)
            if self.continuity is not None and hasattr(self.continuity, "projects") and hasattr(self.continuity.projects, "get_or_create_external_project"):
                try:
                    canonical_proj = self.continuity.projects.get_or_create_external_project(
                        external_project_id=project_name,
                        display_name=project_name,
                        workspace_root=requested_ws
                    )
                    if canonical_proj and canonical_proj.get("id"):
                        continuity_project_id = canonical_proj["id"]
                        workbench_project_id = project_name
                except Exception as ex_reg:
                    logger.warning("[CANONICAL_PROJECT_RESOLVER_ERROR] %s: %s", type(ex_reg).__name__, ex_reg)

        # FASE 11: Executive Core Dispatch Bridge
        is_executive = bool(session_info and (
            session_info.get("executive_mission") or
            session_info.get("mode") == "executive"
        ))
        if is_executive:
            exec_res = self.execute_executive_mission(
                creator_goal=clean_text,
                business_goal=session_info.get("business_goal", clean_text),
                workspace=requested_ws or "",
                max_cycles=session_info.get("max_cycles", 20)
            )
            return _wrap_response({
                "status": "success" if exec_res.get("status") == "COMPLETED" else "blocked",
                "task_id": exec_res.get("mission_id"),
                "task_status": exec_res.get("status"),
                "response": f"Executive Mission {exec_res.get('status')}: {exec_res.get('mission_id')}",
                "executive_mission": exec_res,
                "provider_used": "executive_core",
                "conversation_id": active_conv_id,
                "message_id": user_msg_id,
            }, outbound_model="executive_core_v1")

        if is_operational:
            try:
                import sys
                from pathlib import Path
                rt_dir = str(REPO_ROOT / "runtime_v1")
                if rt_dir not in sys.path:
                    sys.path.insert(0, rt_dir)
                try:
                    import optimus_user_agent
                except Exception as ex_import:
                    logger.warning(f"[BrainAdapter] optimus_user_agent import failed ({ex_import}). Checking focused_test fallback.")
                    optimus_user_agent = None

                if optimus_user_agent is None and session_info and session_info.get("focused_test"):
                    import subprocess
                    f_test = session_info.get("focused_test")
                    eff_test_cwd = str(requested_ws) if (requested_ws and os.path.isdir(str(requested_ws))) else str(REPO_ROOT)
                    logger.info(f"[BrainAdapter] Running focused test directly in {eff_test_cwd}: {f_test}")
                    p_res = subprocess.run(
                        [sys.executable, "-m", "pytest", "-q", f_test],
                        cwd=eff_test_cwd,
                        capture_output=True,
                        text=True,
                        timeout=30
                    )
                    test_passed = (p_res.returncode == 0)
                    failure_tb = p_res.stdout + "\n" + p_res.stderr
                    logger.info(f"[BrainAdapter] Focused test returned {p_res.returncode}; passed={test_passed}")
                    if not test_passed:
                        raise RuntimeError(f"VERIFICATION_FAILED in {session_info.get('target_file')}: {failure_tb}")
                    else:
                        sd_task_id = task_id
                        sd_report = {
                            "RLOOP": {"stop_reason": "OBJECTIVE_SATISFIED", "iterations_run": 1},
                            "execution_verified": True,
                            "objective_met": True,
                        }
                        sd_err = None
                elif optimus_user_agent is not None:
                    # REQUISITO 9: Trazabilidad focal antes de dispatch
                    handoff_trace = (
                        f"[WORKSPACE_HANDOFF]\n"
                        f"task_id={task_id}\n"
                        f"source_key={ws_source_key or 'workspace_root'}\n"
                        f"resolved_workspace={requested_ws}\n"
                        f"protected_core=False"
                    )
                    logger.info(handoff_trace)
                    print(handoff_trace)

                    intent_meta = {
                        "task_id": task_id,
                        "client_task_id": client_task_id or task_id,
                        "workspace_root": requested_ws,
                        "project_id": workbench_project_id or (session_info.get("project_id") if session_info else None),
                        "requested_workspace_created": requested_ws_created,
                    }
                    if session_info:
                        for k in ("mission_contract", "required_effects", "deliverables", "expected_artifacts", "actions", "creator_requirements"):
                            if k in session_info and k not in intent_meta:
                                intent_meta[k] = session_info[k]

                    # Section 4: Task Idempotency Guard (SLICE != FRESH DISPATCH)
                    # Guard against repeated fresh dispatch for RUNNING, STALLED, RECOVERING, WAITING_VALID_DEPENDENCY
                    with self._operational_tasks_lock:
                        existing_entry = self._active_operational_tasks.get(task_id) or (self._active_operational_tasks.get(client_task_id) if client_task_id else None)
                        if existing_entry:
                            cur_status = existing_entry.get("canonical_terminal_status") or existing_entry.get("task_status") or existing_entry.get("status")
                            if cur_status in ("RUNNING", "STALLED", "RECOVERING", "WAITING_VALID_DEPENDENCY"):
                                logger.info(f"[BrainAdapter] Task idempotency guard: task {task_id} is {cur_status}. Returning existing task without fresh dispatch.")
                                existing_res = dict(existing_entry.get("response_payload") or {})
                                existing_res["replayed"] = True
                                existing_res["fresh_dispatch"] = False
                                existing_res["dispatch_count"] = existing_entry.get("dispatch_count", 1)
                                existing_res["task_id"] = task_id
                                existing_res["task_status"] = cur_status
                                existing_res["canonical_terminal_status"] = cur_status
                                return _wrap_response(existing_res, outbound_model="self_dev_loop_v1")

                    logger.info(f"[BrainAdapter] Dispatching operational task to optimus_user_agent.run_self_dev_pipeline: task_id={task_id}")
                    sd_task_id, sd_report, sd_err = optimus_user_agent.run_self_dev_pipeline(
                        clean_text,
                        intent_meta=intent_meta,
                        progress_sender=lambda msg: logger.info(f"[SelfDevProgress] {msg}")
                    )
                    logger.info(f"[BrainAdapter] run_self_dev_pipeline finished: task_id={sd_task_id} err={sd_err}")
                else:
                    raise RuntimeError("optimus_user_agent not available and no focused_test specified")

                summary_msg = ""
                stop = ""
                iters = 0
                rloop: Dict[str, Any] = {}
                if sd_report:
                    rloop = sd_report.get("RLOOP") or {}
                    iters = rloop.get("iterations_run", 0)
                    stop = (
                        rloop.get("stop_reason")
                        or sd_report.get("stop_reason")
                        or sd_report.get("CAPABILITY_BLOCKER")
                        or (rloop.get("capability_blocker") if isinstance(rloop, dict) else None)
                        or "STOP_REPORT_NO_REASON"
                    )
                elif sd_err:
                    stop = str(sd_err)
                else:
                    stop = "STOP_EMPTY_PIPELINE_OUTPUT"

                # Verify real ACK and real success (never treat LIMIT, BLOCKED, ERROR, or STOP_BLOCKED_NO_MUTATION_EVIDENCE as success)
                valid_stops = ("OBJECTIVE_SATISFIED", "STOP_OBJECTIVE_SATISFIED", "SUCCESS", "COMPLETED", "RESEARCH_COMPLETED")
                invalid_prefixes = ("LIMIT", "BLOCKED", "STOP_BLOCKED", "ERROR")
                is_stop_valid = bool(
                    stop in valid_stops
                    and not any(str(stop).startswith(prefix) for prefix in invalid_prefixes)
                    and stop != "STOP_BLOCKED_NO_MUTATION_EVIDENCE"
                )

                has_mutative_evidence = True
                if isinstance(sd_report, dict) and sd_report:
                    fi_n = len(sd_report.get("FILES_INSPECTED", []))
                    ce_n = len(sd_report.get("COMMANDS_EXECUTED", []))
                    fc_n = len(sd_report.get("FILES_CREATED", []))
                    cc_n = len(sd_report.get("CHANGES_CREATED", []))
                    all_exp_created = bool(sd_report.get("ALL_EXPECTED_ARTIFACTS_CREATED"))
                    exec_ver = bool(sd_report.get("execution_verified"))
                    obj_met = bool(sd_report.get("objective_met"))
                    rloop_dict = sd_report.get("RLOOP") if isinstance(sd_report.get("RLOOP"), dict) else {}
                    rloop_ledger_n = int(rloop_dict.get("ledger_len", 0))
                    ledger = sd_report.get("EXECUTION_LEDGER") or rloop_dict.get("ledger") or []

                    user_lower = (clean_text or "").lower()
                    is_mutative = any(k in user_lower for k in [
                        "crea", "crear", "escribe", "escribir", "modifica", "modificar",
                        "edita", "editar", "elimina", "ejecuta", "build", "run"
                    ])
                    if is_mutative:
                        has_mutative_evidence = bool(
                            ce_n > 0 or fi_n > 0 or fc_n > 0 or cc_n > 0
                            or all_exp_created or exec_ver or len(ledger) > 0
                            or rloop_ledger_n > 0 or obj_met
                        )

                is_real_success = bool(
                    not sd_err
                    and isinstance(sd_report, dict)
                    and sd_report
                    and is_stop_valid
                    and has_mutative_evidence
                )

                # Capability blocker requires explicit evidence of capability/tool/resource/permission/safety blocker
                sd_rep = sd_report or {}
                explicit_capability_blocker = (
                    sd_rep.get("CAPABILITY_BLOCKER")
                    or (isinstance(rloop, dict) and rloop.get("capability_blocker"))
                    or sd_rep.get("MISSING_CAPABILITY")
                    or sd_rep.get("MISSING_TOOL")
                )
                stop_str = str(stop)
                has_explicit_blocker_kw = bool(
                    "CAPABILITY_BLOCKER" in stop_str
                    or any(k in stop_str.lower() for k in (
                        "missing_tool", "missing tool", "missing_capability", "missing capability",
                        "missing dependency", "missing permission", "herramienta faltante", "capacidad faltante"
                    ))
                )
                is_heuristic_stuck = bool(
                    stop == "BLOCKED_WITH_EVIDENCE"
                    or "BLOCKED_WITH_EVIDENCE" in stop_str
                    or stop_str.startswith("STOP_BLOCKED")
                    or "stuck sin progreso" in stop_str.lower()
                    or "stuck repeticion" in stop_str.lower()
                )

                is_real_blocker = bool(
                    isinstance(sd_report, dict)
                    and (explicit_capability_blocker or has_explicit_blocker_kw)
                    and not (is_heuristic_stuck and not explicit_capability_blocker)
                )

                is_slice_limit = bool(
                    not sd_err
                    and not is_real_success
                    and not is_real_blocker
                    and isinstance(sd_report, dict)
                    and (
                        "LIMIT" in stop_str
                        or "max_iterations" in stop_str
                        or is_heuristic_stuck
                    )
                    and not any(k in stop_str for k in ("SAFETY_STOP", "INPUT_INVALID", "ERROR", "CRASH"))
                )

                if is_real_success:
                    task_status = "COMPLETED"
                    resp_status = "success"
                elif is_slice_limit:
                    task_status = "PARTIAL_COMPLETE"
                    resp_status = "success"
                elif is_real_blocker:
                    task_status = "CAPABILITY_BLOCKER"
                    resp_status = "error"
                elif any(w in str(stop).upper() for w in ("WAITING_CREATOR", "WAITING_APPROVAL")):
                    task_status = "WAITING_CREATOR_APPROVAL"
                    resp_status = "waiting"
                elif any(w in str(stop).upper() for w in ("WAITING_EXTERNAL", "WAITING_DEPENDENCY")):
                    task_status = "WAITING_EXTERNAL"
                    resp_status = "waiting"
                elif "SAFETY_STOP" in str(stop).upper():
                    task_status = "SAFETY_STOP"
                    resp_status = "error"
                elif sd_err:
                    task_status = "FAILED"
                    resp_status = "error"
                else:
                    task_status = "BLOCKED" if not sd_err else "ERROR"
                    resp_status = "error"

                proj_label = workbench_project_id or (os.path.basename(requested_ws) if requested_ws else "el proyecto")
                arts_modified = []
                if isinstance(sd_report, dict) and sd_report:
                    rloop_d = sd_report.get("RLOOP") if isinstance(sd_report.get("RLOOP"), dict) else {}
                    led = sd_report.get("EXECUTION_LEDGER") or rloop_d.get("ledger") or []
                    for item in led:
                        if item.get("action") in ("write_file", "edit_file") and item.get("status") == "ok":
                            t = item.get("target")
                            if t and t not in arts_modified:
                                arts_modified.append(os.path.basename(str(t)))

                if is_real_success:
                    if isinstance(sd_report, dict) and sd_report.get("PRODUCT_BOOTSTRAP"):
                        p_name = sd_report.get("PRODUCT_NAME") or proj_label
                        created_files = ", ".join(arts_modified) if arts_modified else "archivos base"
                        raw_pending = sd_report.get("PENDING_CAPABILITIES", [])
                        pending_filtered = [c for c in raw_pending if c not in ("image_generation", "voice", "lip_sync", "tiktok_live")]
                        pending_str = f" Capacidades en preparación: {', '.join(pending_filtered)}." if pending_filtered else ""
                        summary_msg = (
                            f"Producto '{p_name}' inicializado correctamente con entregables físicos: {created_files}. "
                            f"Interfaz y estructura base listas.{pending_str}"
                        )
                    elif arts_modified:
                        files_str = ", ".join(arts_modified)
                        summary_msg = f"Listo. Guardé y verifiqué los cambios solicitados ({files_str}) en {proj_label}."
                    else:
                        summary_msg = f"Listo. Completé la tarea en {proj_label} y verifiqué físicamente los resultados."
                elif is_slice_limit:
                    if is_heuristic_stuck:
                        summary_msg = f"Slice de razonamiento completado (evidencia parcial recogida en {proj_label}). Continuando automáticamente en el siguiente ciclo."
                    else:
                        summary_msg = f"Slice de razonamiento completado (límite alcanzado en {proj_label}). Continuando automáticamente en el siguiente ciclo."
                elif sd_err:
                    summary_msg = f"No pude completar la tarea en {proj_label}: {sd_err}"
                else:
                    summary_msg = f"No pude completar la tarea en {proj_label} (estado: {stop}). He registrado los detalles para subsanarlo."

                try:
                    from runtime_v1.foundation.self_dev_loop import validate_response_references
                    _, summary_msg = validate_response_references(
                        summary_msg,
                        requested_ws,
                        sd_report.get("PROJECT_STATE") if isinstance(sd_report, dict) else None
                    )
                except Exception:
                    pass
                canon_st = "COMPLETED_AND_E2E_VERIFIED" if is_real_success else ("PARTIAL_COMPLETE" if is_slice_limit else ("MISSION_CONTRACT_INCOMPLETE" if stop == "STOP_MISSION_CONTRACT_INCOMPLETE" else task_status))
                resp_payload = {
                    "status": resp_status,
                    "runtime_ack": bool(is_real_success or is_slice_limit),
                    "task_id": sd_task_id or task_id,
                    "client_task_id": client_task_id or task_id,
                    "task_status": task_status,
                    "canonical_terminal_status": canon_st,
                    "continuation_required": bool(is_slice_limit),
                    "CONTINUATION_REQUIRED": bool(is_slice_limit),
                    "objective_satisfied": bool(is_real_success),
                    "nonterminal": bool(is_slice_limit),
                    "NONTERMINAL": bool(is_slice_limit),
                    "is_slice_limit": bool(is_slice_limit),
                    "slice_yield": bool(is_slice_limit),
                    "BLOCKED": False if (is_real_success or is_slice_limit) else True,
                    "CAPABILITY_BLOCKER": True if task_status == "CAPABILITY_BLOCKER" else False,
                    "response": summary_msg,
                    "self_dev_report": sd_report,
                    "execution_result": sd_report,
                    "final_result": summary_msg if is_real_success else None,
                    "availability_status": "READY" if (is_real_success or is_slice_limit) else "RUNTIME_ERROR",
                    "provider_used": "optimus_user_agent_pipeline",
                    "conversation_id": active_conv_id,
                    "message_id": user_msg_id,
                }
                if requested_ws or (sd_report and isinstance(sd_report, dict) and "RUNTIME_WORKSPACE_ROOT" in sd_report):
                    effective_ws = sd_report.get("RUNTIME_WORKSPACE_ROOT", requested_ws) if isinstance(sd_report, dict) else requested_ws
                    resp_payload["REQUESTED_WORKSPACE_CREATED"] = bool(sd_report.get("REQUESTED_WORKSPACE_CREATED", requested_ws_created) if isinstance(sd_report, dict) else requested_ws_created)
                    resp_payload["RUNTIME_WORKSPACE_ROOT"] = effective_ws
                    resp_payload["FILESYSTEM_TOOLS_AVAILABLE"] = bool(sd_report.get("FILESYSTEM_TOOLS_AVAILABLE", True) if isinstance(sd_report, dict) else True)
                    resp_payload["TERMINAL_AVAILABLE"] = bool(sd_report.get("TERMINAL_AVAILABLE", True) if isinstance(sd_report, dict) else True)
                    resp_payload["PROTECTED_CORE_WRITABLE"] = bool(sd_report.get("PROTECTED_CORE_WRITABLE", False) if isinstance(sd_report, dict) else False)
                if not is_real_success and not is_slice_limit:
                    resp_payload["error"] = sd_err or f"Pipeline terminó sin satisfacción de objetivo (estado: {stop or 'SIN_REPORTE'})"

                if self.continuity is not None and active_conv_id:
                    self.continuity.history.add_message(
                        conv_id=active_conv_id,
                        role="assistant",
                        content=summary_msg,
                        metadata={"intent": "OPERATIONAL_PIPELINE", "task_id": sd_task_id or task_id}
                    )
                with self._operational_tasks_lock:
                    eff_tid = sd_task_id or task_id
                    prev_dispatch = (self._active_operational_tasks.get(eff_tid) or {}).get("dispatch_count", 0)
                    self._active_operational_tasks[eff_tid] = {
                        "status": task_status,
                        "canonical_terminal_status": canon_st,
                        "dispatch_count": prev_dispatch + 1,
                        "response_payload": dict(resp_payload),
                        "task_id": eff_tid,
                        "workspace": requested_ws,
                    }
                    if client_task_id and client_task_id != eff_tid:
                        self._active_operational_tasks[client_task_id] = self._active_operational_tasks[eff_tid]
                return _wrap_response(resp_payload, outbound_model="self_dev_loop_v1")
            except Exception as ex_op:
                logger.error(f"[BrainAdapter] Operational pipeline dispatch error: {ex_op}", exc_info=True)
                err_payload = {
                    "status": "error",
                    "runtime_ack": False,
                    "task_id": task_id,
                    "client_task_id": client_task_id or task_id,
                    "task_status": "FAILED",
                    "canonical_terminal_status": "VERIFICATION_FAILED" if (session_info and session_info.get("focused_test")) else "FAILED",
                    "error": f"OPERATIONAL_PIPELINE_ERROR: {ex_op}",
                    "response": f"Error ejecutando pipeline en runtime: {ex_op}",
                    "availability_status": "RUNTIME_ERROR",
                    "provider_used": "optimus_user_agent_pipeline",
                    "conversation_id": active_conv_id,
                    "message_id": user_msg_id,
                }
                if session_info and session_info.get("focused_test"):
                    err_payload["verification"] = {
                        "passed": False,
                        "status": "VERIFICATION_FAILED",
                        "verification_reason": str(ex_op),
                        "focused_test": session_info.get("focused_test"),
                        "focused_test_command": session_info.get("focused_test_command"),
                        "regression_tests": session_info.get("regression_tests"),
                        "verification_dependencies": session_info.get("verification_dependencies"),
                        "target_file": session_info.get("target_file"),
                    }
                return _wrap_response(err_payload, outbound_model="self_dev_loop_v1")

        # 3. Check for desktop action intent (Brain Decides) only when NOT an operational task
        action_plan = self.parse_action_intent(clean_text)
        if action_plan:
            req_id = f"act_{uuid.uuid4().hex[:8]}"
            act_type = action_plan["action"]
            act_params = dict(action_plan.get("parameters", {}))
            if "text" in action_plan:
                act_params["text"] = action_plan["text"]
            if "return_to_optimus" in action_plan:
                act_params["return_to_optimus"] = action_plan["return_to_optimus"]

            action_req = {
                "request_id": req_id,
                "action": act_type,
                "app_alias": action_plan.get("app_alias", ""),
                "parameters": act_params
            }

            if act_type == "OPEN_AND_TYPE_TEXT":
                txt_preview = action_plan.get("text", "")
                if len(txt_preview) > 30:
                    txt_preview = txt_preview[:27] + "..."
                resp_text = f"Entendido. Abriendo Bloc de notas en tu laptop y escribiendo: \"{txt_preview}\""
            elif act_type == "OPEN_APPLICATION":
                resp_text = "Entendido. Abriendo Bloc de notas en tu laptop."
            elif act_type == "MOUSE_MOVE":
                t_desc = act_params.get("target") or f"({act_params.get('x')}, {act_params.get('y')})"
                if t_desc in ("center", "SCREEN_CENTER"):
                    resp_text = "Entendido. Moviendo el cursor al centro de la pantalla en tu laptop."
                else:
                    resp_text = f"Entendido. Moviendo el cursor al {t_desc} en tu laptop."
            elif act_type == "SAFE_CLICK_TEST":
                resp_text = "Entendido. Ejecutando prueba segura de clic en el target de diagnóstico de tu laptop."
            elif act_type == "SAFE_KEY_TEST":
                resp_text = f"Entendido. Ejecutando prueba segura de tecla {act_params.get('key', 'ENTER')} en el target de diagnóstico de tu laptop."
            elif act_type == "SAFE_WINDOW_TEST":
                resp_text = "Entendido. Ejecutando prueba segura de minimizado y restauración de ventana en tu laptop."
            elif act_type == "MOUSE_CLICK":
                resp_text = "Entendido. Ejecutando clic izquierdo en tu laptop."
            elif act_type == "KEY_PRESS":
                resp_text = f"Entendido. Presionando tecla {act_params.get('key')} en tu laptop."
            elif act_type == "OBSERVE_SCREEN":
                resp_text = "Entendido. Observando la pantalla y cursor de tu laptop."
            elif act_type == "OBSERVE_ACTIVE_WINDOW":
                resp_text = "Entendido. Observando el entorno visual de tu laptop."
            elif act_type == "SAFETY_PAUSE":
                resp_text = "Entendido. Acciones locales pausadas en tu laptop."
            elif act_type == "SAFETY_RESUME":
                resp_text = "Entendido. Acciones locales reanudadas en tu laptop."
            elif act_type == "SAFETY_CANCEL":
                resp_text = "Entendido. Cancelando acción en tu laptop."
            elif act_type == "SAFETY_KILL_SWITCH":
                resp_text = "Entendido. Parada de emergencia activada. Acciones locales deshabilitadas."
            elif act_type == "SAFETY_RESET":
                resp_text = "Entendido. Sistema restablecido. Acciones locales autorizadas nuevamente."
            else:
                resp_text = f"Entendido. Ejecutando acción {act_type} en tu laptop."

            # Persist assistant response and extract candidates (exclude test from persistent candidates)
            if self.continuity is not None and active_conv_id:
                asst_meta = {"intent": "DESKTOP_ACTION", "action": act_type, "environment": env, "project_id": proj_id, "mission_id": mis_id}
                if is_test:
                    asst_meta["is_test"] = True
                self.continuity.history.add_message(
                    conv_id=active_conv_id,
                    role="assistant",
                    content=resp_text,
                    metadata=asst_meta
                )
                if user_msg_id and not is_test:
                    self.continuity.memory.extract_and_store_candidates(clean_text, resp_text, active_conv_id, user_msg_id)

            return _wrap_response({
                "status": "success",
                "response": resp_text,
                "action_request": action_req,
                "intent": "DESKTOP_ACTION",
                "confidence": 0.98,
                "availability_status": "READY",
                "provider_used": "desktop_action_bridge",
                "provider_model": "action_planner_v1",
                "task_id": task_id,
                "conversation_id": active_conv_id,
                "message_id": user_msg_id,
                "recalled_memories": recalled_mem_list
            }, outbound_model="action_planner_v1")

        # Check for explicit memory store instruction vs direct memory recall / continuity query
        import re
        norm_clean_text = normalize_for_search(clean_text)
        is_store_instruction = bool(re.search(
            r'^(?:(?:por\s+favor\s+)?(?:recuerda|anota|guarda|ten\s+en\s+cuenta|ten\s+presente)\s+que\s+)',
            norm_clean_text,
            re.IGNORECASE
        ))

        is_recall_query = bool(re.search(
            r'(?:(?:cual\s+era|como\s+se\s+llamaba)\s+(?:el\s+)?(?:nombre|codigo|proyecto|sistema|portal|precio|valor)|recuerdas\s+(?:cual|como|que)|que\s+decidimos|sabes\s+cual\s+es|\bque\s+errores\s+tuviste|\brevisa\s+lo\s+que\s+hicimos|\bque\s+codigo\s+(?:te\s+pedi\s+)?recordar|\bcual\s+era\s+el\s+codigo)',
            norm_clean_text,
            re.IGNORECASE
        )) and not is_store_instruction

        # Explicit mission detection: NEVER treat mission command as conversational continuity
        is_explicit_mission = bool(re.search(
            r'(?:OPTIMUS_|INDEX_|_V\d+|MISSION|misi[oó]n\s+[A-Za-z0-9_\-]+|mis_[a-z0-9]+)',
            clean_text,
            re.IGNORECASE
        )) or bool(mis_id and any(w in norm_clean_text for w in ["continua", "reanuda", "ejecuta", "inicia"]))

        is_continuity_query = (
            bool(re.search(
                r'(?:(?:en\s+qu[eé]\s+(?:parte\s+)?(?:nos\s+)?(?:hab[ií]amos\s+)?quedado|d[oó]nde\s+(?:nos\s+)?quedamos|de\s+qu[eé]\s+(?:est[aá]bamos\s+)?hablando|qu[eé]\s+est[aá]bamos\s+haciendo)|(?:sigamos|continuemos|retomar)\s*(?:desde|con)?|\bcontin[uú]a\b)',
                norm_clean_text,
                re.IGNORECASE
            ))
            and not is_store_instruction
            and not is_explicit_mission
            and not bool(re.search(r'(?:Mission Planner|MISSION ID:|MISSION_PLAN)', clean_text, re.IGNORECASE))
        )

        is_report_generation = bool(re.search(
            r'(?:genera|crea|elabora|redacta|haz|generar|crear)\s+(?:un\s+)?(?:informe|reporte)',
            norm_clean_text
        ))

        is_report_query = bool(re.search(
            r'(?:(?:mu[eé]strame|ver|consultar|recupera|d[oó]nde\s+est[aá]|cu[aá]l\s+es|qu[eé]\s+dice)\s+(?:el\s+)?(?:informe|reporte)|(?:el\s+)?[uú]ltimo\s+informe)',
            norm_clean_text
        )) and not is_report_generation

        # Handle Report Generation Intent
        if is_report_generation and self.continuity is not None and active_conv_id:
            proj_name = "Proyecto General"
            proj_id = None
            if ctx_data and ctx_data.get("active_project"):
                proj_name = ctx_data["active_project"]["name"]
                proj_id = ctx_data["active_project"]["id"]
            else:
                p = self.continuity.projects.get_or_create_project(proj_name)
                proj_id = p["id"]

            curr_focus = ctx_data.get("current_focus") if ctx_data else None
            active_tasks = ctx_data.get("active_tasks", []) if ctx_data else []
            recent_msgs = ctx_data.get("recent_messages", []) if ctx_data else []

            report_title = f"Informe de Avance — {proj_name}"
            report_content = ""
            reasoning_invoked = False
            provider_invoked = False
            final_from_reasoning = False

            if self.core is not None and CORE_AVAILABLE and ReasoningContext is not None:
                reasoning_invoked = True
                provider_invoked = True
                try:
                    rep_ctx = ReasoningContext(
                        task_id=f"rep_task_{uuid.uuid4().hex[:8]}",
                        project_id=proj_id,
                        session_id=str(session_info.get("token", "")),
                        user_request=f"Genera un informe estructurado de avance para el proyecto {proj_name}. Foco actual: {curr_focus or 'General'}.",
                        observations=ctx_data.get("observations", []) if ctx_data else [],
                        known_facts=ctx_data.get("known_facts", []) if ctx_data else [],
                        goals=[{"goal": f"Informe de {proj_name}", "status": "PLANNED"}],
                        risk_level="low",
                        complexity="balanced",
                        task_types=[TASK_REASONING]
                    )
                    core_res = self.core.run(rep_ctx)
                    ans = (core_res.answer or "").strip()
                    if ans and "WAITING" not in ans and "UNAVAILABLE" not in ans and "i don't know" not in ans.lower():
                        report_content = ans
                        final_from_reasoning = True
                except Exception:
                    pass

            if not report_content:
                lines_sec = [
                    f"Consolidación de avances para el proyecto {proj_name}."
                ]
                if curr_focus:
                    lines_sec.append(f"- Foco de trabajo activo: {curr_focus}.")
                if active_tasks:
                    lines_sec.append("- Tareas registradas:")
                    for at in active_tasks[:4]:
                        lines_sec.append(f"  * [{at.get('status', 'PLANNED')}] {at.get('request', '')}")
                if recent_msgs:
                    substantive = [m["content"] for m in recent_msgs if m.get("role") == "user" and len(m.get("content", "")) > 10]
                    if substantive:
                        lines_sec.append(f"- Temas abordados recientemente: {'; '.join(substantive[-3:])}.")
                report_content = "\n".join(lines_sec)

            rep = self.continuity.reports.create_report(
                project_id=proj_id,
                title=report_title,
                content=report_content,
                conversation_id=active_conv_id,
                report_type="CHECKPOINT",
                status="COMPLETED",
                objective=f"Consolidar el avance operativo del proyecto {proj_name}."
            )

            resp_text = (
                f"Informe generado con éxito para el proyecto '{proj_name}'.\n"
                f"- Título: {report_title}\n"
                f"- ID: {rep['id']}\n"
                f"- Ubicación: {rep['markdown_path']}\n\n"
                f"Resumen del informe:\n{report_content[:300]}..."
            )

            self.continuity.history.add_message(
                conv_id=active_conv_id,
                role="assistant",
                content=resp_text,
                metadata={"intent": "REPORT_GENERATION", "report_id": rep["id"]}
            )

            return _wrap_response({
                "status": "success",
                "response": resp_text,
                "intent": "REPORT_GENERATION",
                "report_id": rep["id"],
                "report_title": report_title,
                "project_id": proj_id,
                "confidence": 0.99,
                "availability_status": "READY",
                "provider_used": "continuity_report_engine",
                "provider_model": "persistent_report_v1",
                "task_id": task_id,
                "conversation_id": active_conv_id,
                "message_id": user_msg_id,
                "reasoning_core_invoked": reasoning_invoked,
                "provider_invoked": provider_invoked,
                "final_content_from_reasoning": final_from_reasoning,
                "report_data": rep
            }, outbound_model="persistent_report_v1")

        # Handle Report Query Intent
        if is_report_query and self.continuity is not None and active_conv_id:
            proj_id = ctx_data.get("project_id") if ctx_data else None
            rep_res = self.continuity.reports.find_reports_by_title(clean_text, project_id=proj_id, conversation_id=active_conv_id)
            if rep_res.get("is_ambiguous"):
                candidates = rep_res.get("matches", [])
                c_titles = [f"'{c['title']}' (ID: {c['id']})" for c in candidates[:3]]
                resp_text = f"Encontré múltiples informes coincidentes: {', '.join(c_titles)}. Por favor especifica cuál deseas consultar."
                self.continuity.history.add_message(
                    conv_id=active_conv_id,
                    role="assistant",
                    content=resp_text,
                    metadata={"intent": "REPORT_QUERY_AMBIGUOUS"}
                )
                return _wrap_response({
                    "status": "success",
                    "response": resp_text,
                    "intent": "REPORT_QUERY",
                    "confidence": 0.95,
                    "availability_status": "READY",
                    "provider_used": "continuity_report_engine",
                    "is_ambiguous": True,
                    "conversation_id": active_conv_id
                }, outbound_model="continuity_report_engine")

            top_rep = rep_res.get("top_match")
            if not top_rep:
                top_rep = self.continuity.reports.get_latest_report(project_id=proj_id, conversation_id=active_conv_id)

            if top_rep:
                resp_text = (
                    f"Informe encontrado: {top_rep['title']} (ID: {top_rep['id']})\n"
                    f"Estado: {top_rep.get('final_status', 'COMPLETED')}\n\n"
                    f"Resumen:\n{top_rep.get('summary', '')}\n\n"
                    f"Ubicación: {top_rep.get('markdown_path', '')}"
                )
            else:
                resp_text = "No encontré informes registrados para este proyecto o consulta."

            self.continuity.history.add_message(
                conv_id=active_conv_id,
                role="assistant",
                content=resp_text,
                metadata={"intent": "REPORT_QUERY", "report_id": top_rep["id"] if top_rep else None}
            )
            return _wrap_response({
                "status": "success",
                "response": resp_text,
                "intent": "REPORT_QUERY",
                "report_id": top_rep["id"] if top_rep else None,
                "confidence": 0.99,
                "availability_status": "READY",
                "provider_used": "continuity_report_engine",
                "task_id": task_id,
                "conversation_id": active_conv_id,
                "message_id": user_msg_id
            }, outbound_model="continuity_report_engine")

        # Check core availability for general reasoning
        if self.core is None or not CORE_AVAILABLE or ReasoningContext is None:
            # If explicit store instruction, acknowledge and store directly
            if is_store_instruction:
                stored = []
                if self.continuity is not None and active_conv_id and user_msg_id:
                    stored = self.continuity.memory.extract_and_store_candidates(clean_text, "", active_conv_id, user_msg_id)
                ans_text = f"Anotado: {clean_text}."
                if stored:
                    ans_text = f"Anotado: {stored[0]['content']}"
                if self.continuity is not None and active_conv_id:
                    self.continuity.history.add_message(
                        conv_id=active_conv_id,
                        role="assistant",
                        content=ans_text,
                        metadata={"intent": "MEMORY_STORE"}
                    )
                return _wrap_response({
                    "status": "success",
                    "response": ans_text,
                    "intent": "MEMORY_STORE",
                    "confidence": 0.99,
                    "availability_status": "READY",
                    "provider_used": "continuity_memory_engine",
                    "provider_model": "explicit_store_v1",
                    "task_id": task_id,
                    "conversation_id": active_conv_id,
                    "message_id": user_msg_id,
                    "recalled_memories": recalled_mem_list
                }, outbound_model="explicit_store_v1")

            # If core unavailable but we have recalled memory for a recall query, answer directly
            if is_recall_query and ctx_data and ctx_data.get("retrieved_memories"):
                top_m = ctx_data["retrieved_memories"][0]
                src_c = top_m.get("source_conversation_id") or "anterior"
                direct_ans = f"{top_m['content']} (Recuperado de tu memoria persistente, fuente: {src_c})."

                if self.continuity is not None and active_conv_id:
                    self.continuity.history.add_message(
                        conv_id=active_conv_id,
                        role="assistant",
                        content=direct_ans,
                        metadata={"intent": "MEMORY_RECALL", "source_conv": src_c}
                    )

                return _wrap_response({
                    "status": "success",
                    "response": direct_ans,
                    "intent": "MEMORY_RECALL",
                    "confidence": 0.99,
                    "availability_status": "READY",
                    "provider_used": "continuity_memory_engine",
                    "provider_model": "selective_retrieval_v1",
                    "task_id": task_id,
                    "conversation_id": active_conv_id,
                    "message_id": user_msg_id,
                    "recalled_memories": recalled_mem_list
                }, outbound_model="selective_retrieval_v1")

            if is_continuity_query:
                cont_ans = self._format_continuity_fallback(ctx_data)
                if self.continuity is not None and active_conv_id:
                    asst_m = {"intent": "SESSION_CONTINUITY", "environment": env, "project_id": proj_id, "mission_id": mis_id}
                    if is_test:
                        asst_m["is_test"] = True
                    self.continuity.history.add_message(
                        conv_id=active_conv_id,
                        role="assistant",
                        content=cont_ans,
                        metadata=asst_m
                    )
                return _wrap_response({
                    "status": "success",
                    "response": cont_ans,
                    "intent": "SESSION_CONTINUITY",
                    "confidence": 0.95,
                    "availability_status": "READY",
                    "provider_used": "continuity_memory_engine",
                    "provider_model": "session_continuity_v1",
                    "task_id": task_id,
                    "conversation_id": active_conv_id,
                    "message_id": user_msg_id,
                    "recalled_memories": recalled_mem_list
                }, outbound_model="session_continuity_v1")

            return _wrap_response({
                "status": "error",
                "message": "Reasoning Core runtime unavailable.",
                "response": "WAITING_FOR_REMOTE_REASONING_CORE",
                "availability_status": "EXTERNAL_REASONING_UNAVAILABLE",
                "task_id": task_id,
                "conversation_id": active_conv_id,
                "message_id": user_msg_id
            }, prov_err="Reasoning Core runtime unavailable.")

        # 4 & 5. Build ReasoningContext using canonical contract with bounded memory injection
        session_id = str(session_info.get("token", "")) if session_info else ""
        known_facts = ctx_data.get("known_facts", []) if ctx_data else []
        relevant_mem = ctx_data.get("retrieved_memories", []) if ctx_data else []
        observations = ctx_data.get("observations", []) if ctx_data else []
        active_proj_id = ctx_data.get("project_id", "") if ctx_data else ""
        goals = []
        if ctx_data and ctx_data.get("active_tasks"):
            for at in ctx_data["active_tasks"][:4]:
                goals.append({"goal": at.get("request", ""), "status": at.get("status", "PLANNED")})

        # Optimus Workbench / IDE active editor & project contextual awareness
        if session_info:
            if session_info.get("current_project"):
                active_proj_id = session_info["current_project"]
                known_facts.append(f"Proyecto activo en Optimus Workbench / IDE: {session_info['current_project']}")
            if session_info.get("current_mission"):
                known_facts.append(f"Misión activa: {session_info['current_mission']}")
            if session_info.get("current_open_file"):
                known_facts.append(f"Archivo actualmente abierto en editor: {session_info['current_open_file']} (Ruta: {session_info.get('current_file_path', '')})")
            if session_info.get("current_selection"):
                known_facts.append(f"Código/Texto seleccionado por el Creador:\n```\n{session_info['current_selection']}\n```")

        # Project Mind V1 Context Injection (Patch E: ONLY real nonempty fields)
        if ctx_data and ctx_data.get("project_mind"):
            pm = ctx_data["project_mind"]
            if isinstance(pm, dict):
                pm_ident = pm.get("identity") or {}
                pm_name = pm_ident.get("display_name") or pm_ident.get("external_project_id") or ""
                proj_label = f" ({pm_name})" if pm_name else ""

                if pm.get("vision") and str(pm["vision"]).strip():
                    known_facts.append(f"Visión del proyecto{proj_label}: {str(pm['vision']).strip()}")
                if pm.get("capabilities") and isinstance(pm["capabilities"], list):
                    v_caps = [str(c).strip() for c in pm["capabilities"] if str(c).strip()]
                    if v_caps:
                        known_facts.append(f"Capacidades del proyecto{proj_label}: {', '.join(v_caps)}")
                if pm.get("limitations") and isinstance(pm["limitations"], list):
                    v_lims = [str(l).strip() for l in pm["limitations"] if str(l).strip()]
                    if v_lims:
                        known_facts.append(f"Limitaciones del proyecto{proj_label}: {', '.join(v_lims)}")
                if pm.get("products") and isinstance(pm["products"], list):
                    v_prods = [str(p).strip() for p in pm["products"] if str(p).strip()]
                    if v_prods:
                        known_facts.append(f"Productos del proyecto{proj_label}: {', '.join(v_prods)}")
                if pm.get("roadmap") and isinstance(pm["roadmap"], list):
                    v_rm = [str(r).strip() for r in pm["roadmap"] if str(r).strip()]
                    if v_rm:
                        known_facts.append(f"Hoja de ruta del proyecto{proj_label}: {', '.join(v_rm)}")
                if pm.get("priorities") and isinstance(pm["priorities"], list):
                    v_pri = [str(p).strip() for p in pm["priorities"] if str(p).strip()]
                    if v_pri:
                        known_facts.append(f"Prioridades del proyecto{proj_label}: {', '.join(v_pri)}")
                if pm.get("decision_history") and isinstance(pm["decision_history"], list):
                    v_dec = [str(d).strip() for d in pm["decision_history"] if str(d).strip()]
                    if v_dec:
                        known_facts.append(f"Decisiones del proyecto{proj_label}: {', '.join(v_dec)}")
                if pm.get("learned_facts") and isinstance(pm["learned_facts"], list):
                    v_facts = [str(f).strip() for f in pm["learned_facts"] if str(f).strip()]
                    if v_facts:
                        known_facts.append(f"Hechos aprendidos del proyecto{proj_label}: {', '.join(v_facts)}")
                if pm.get("next_strategic_action") and str(pm["next_strategic_action"]).strip():
                    known_facts.append(f"Próxima acción estratégica del proyecto{proj_label}: {str(pm['next_strategic_action']).strip()}")

                # Long-term goals become reasoning goals ONLY when nonempty
                if pm.get("long_term_goals") and isinstance(pm["long_term_goals"], list):
                    for g in pm["long_term_goals"]:
                        g_str = str(g).strip()
                        if g_str:
                            goals.append({"goal": g_str, "status": "LONG_TERM"})

        executive_mode = False
        executive_state = None
        operational_state = None
        executive_execution = None
        reasoning_request = clean_text

        exec_admin_trigger_present = bool(
            clean_text
            and any(
                line.strip() == "EXEC_ADMIN_EXECUTE"
                for line in clean_text.splitlines()
            )
        )

        if (
            EXECUTIVE_BRAIN_AVAILABLE
            and (
                exec_admin_trigger_present
                or (
                    is_executive_request
                    and is_executive_request(clean_text)
                )
            )
        ):
            executive_mode = True
            executive_ctx_data = dict(ctx_data or {})
            operational_state = self._resolve_executive_operational_state(ctx_data, session_info)
            if operational_state:
                executive_ctx_data["executive_operational_state"] = operational_state

            executive_state = build_executive_state(executive_ctx_data)
            if build_executive_reasoning_request:
                reasoning_request = build_executive_reasoning_request(
                    clean_text,
                    executive_state
                )

        ctx = ReasoningContext(
            task_id=task_id,
            project_id=active_proj_id,
            session_id=session_id,
            user_request=reasoning_request,
            observations=observations,
            known_facts=known_facts,
            relevant_memory=relevant_mem,
            goals=goals,
            risk_level="low",
            complexity="balanced",
            task_types=[TASK_REASONING]
        )
        ctx.confidence_override_tier = mapped_tier
        if self.effector_registry:
            try:
                caps_info = self.effector_registry.get_capabilities_info()
                ctx.available_tools = [f"{cap}:{','.join(info.get('available_actions', []))}" for cap, info in caps_info.items()]
                ctx.available_skills = list(caps_info.keys())
            except Exception:
                pass

        # Ensure real reasoning provider is wired if credentials exist
        if self.core and (not hasattr(self.core, "_provider") or self.core._provider is None):
            try:
                from runtime_v1.foundation.reasoning import _init_real_reasoning_if_available
                _init_real_reasoning_if_available()
            except Exception:
                pass

        # 6 & 7. Invoke REASONING_CORE.run(ctx) with explicit router context & full error isolation
        # Shadow observability: query NeuralAdvisor in parallel/adjacent to reasoning path (Alpha66 / Alpha67)
        neural_shadow_result = self._query_neural_shadow(
            user_text=clean_text,
            reasoner_decision_id=dec_id,
            session_info=session_info,
            effective_model=brain_effective_model,
            effective_effort=brain_effective_effort,
            project_mind_summary=ctx_data.get("project_mind_summary") if ctx_data else None,
            project_mind=ctx_data.get("project_mind") if ctx_data else None,
            continuity_project_id=continuity_project_id
        )

        try:
            if self.core and hasattr(self.core, "_provider") and self.core._provider:
                try:
                    self.core._provider.timeout_seconds = max(getattr(self.core._provider, "timeout_seconds", 20), 75)
                except Exception:
                    pass

            logger.info(f"[CHAT_STAGE] stage=REASONER_START turn_id={turn_id} conversation_id={active_conv_id} elapsed_ms={int((time.time()-t0_chat)*1000)}")
            if auth_intent == "CHAT":
                import concurrent.futures
                chat_timeout = float(os.environ.get("TEITAN_CHAT_TIMEOUT_SECONDS", "30.0"))
                with self.router.explicit_context(
                    model=brain_effective_model if explicit_model else None,
                    effort=brain_effective_effort if explicit_model else None,
                    tier=mapped_tier if explicit_model else None
                ):
                    with concurrent.futures.ThreadPoolExecutor(max_workers=1) as t_exec:
                        t_future = t_exec.submit(self.core.run, ctx)
                        try:
                            res: ReasoningResult = t_future.result(timeout=chat_timeout)
                        except concurrent.futures.TimeoutError:
                            logger.warning(f"[CHAT_STAGE] stage=REASONER_END status=TIMEOUT turn_id={turn_id} conversation_id={active_conv_id} elapsed_ms={int((time.time()-t0_chat)*1000)}")
                            return _wrap_response({
                                "status": "error",
                                "error": "CHAT_REASONING_TIMEOUT",
                                "response": "El procesamiento del mensaje superó el tiempo límite. Por favor intenta de nuevo.",
                                "availability_status": "TIMEOUT",
                                "intent": "CHAT",
                                "route_mode": "CHAT_TIMEOUT",
                                "operational_task": False,
                                "task_id": None,
                                "client_task_id": None,
                                "mission_id": None,
                                "provider_calls": 0,
                                "conversation_id": active_conv_id,
                                "message_id": user_msg_id,
                                "runtime_ack": True,
                            })
            else:
                with self.router.explicit_context(
                    model=brain_effective_model if explicit_model else None,
                    effort=brain_effective_effort if explicit_model else None,
                    tier=mapped_tier if explicit_model else None
                ):
                    res: ReasoningResult = self.core.run(ctx)
            logger.info(f"[CHAT_STAGE] stage=REASONER_END turn_id={turn_id} conversation_id={active_conv_id} elapsed_ms={int((time.time()-t0_chat)*1000)}")
            answer = (res.answer or "").strip()

            executive_decision = None
            if executive_mode and executive_state is not None and finalize_executive_decision and format_executive_response:
                executive_decision = finalize_executive_decision(
                    executive_state,
                    res
                )
                answer = format_executive_response(
                    executive_state,
                    executive_decision
                )
                try:
                    executive_execution = self._try_execute_executive_admin_step(
                        clean_text=clean_text,
                        executive_decision=executive_decision,
                        operational_state=operational_state
                    )
                except Exception as ex_bridge:
                    logger.warning("[EXECUTIVE_ADMIN_BRIDGE_ERROR] %s: %s", type(ex_bridge).__name__, ex_bridge)
                    executive_execution = {
                        "triggered": bool(clean_text and any(line.strip() == "EXEC_ADMIN_EXECUTE" for line in clean_text.splitlines())),
                        "allowed": False,
                        "executed": False,
                        "mission_id": (operational_state.get("mission") or {}).get("mission_id", "") if isinstance(operational_state, dict) else "",
                        "authority_mode": getattr(executive_decision, "authority_mode", ""),
                        "action_type": "",
                        "target": "",
                        "execution_result": None,
                        "block_reason": f"BRIDGE_EXCEPTION: {type(ex_bridge).__name__}: {ex_bridge}"
                    }

                if executive_execution and executive_execution.get("triggered"):
                    exec_st_str = "EXECUTED" if executive_execution.get("executed") else "BLOCKED"
                    m_id_str = executive_execution.get("mission_id") or "Desconocida"
                    act_str = executive_execution.get("action_type") or "Ninguna"
                    tgt_str = executive_execution.get("target") or "Ninguno"
                    e_res = executive_execution.get("execution_result")
                    ver_str = None
                    if isinstance(e_res, dict):
                        ver_str = e_res.get("verification_status") or e_res.get("status")
                    if not ver_str:
                        ver_str = "No ejecutado" if not executive_execution.get("executed") else "Sin verificación explícita"

                    answer += (
                        f"\n\nEXECUTIVE ADMINISTRATOR\n\n"
                        f"Ejecución:\n{exec_st_str}\n\n"
                        f"Misión:\n{m_id_str}\n\n"
                        f"Acción:\n{act_str} -> {tgt_str}\n\n"
                        f"Verificación:\n{ver_str}"
                    )
            else:
                if is_store_instruction and (
                    not answer
                    or answer in ("WAITING_FOR_REASONING_CORE", "EXTERNAL_REASONING_UNAVAILABLE")
                    or getattr(res, "availability_status", "") == "EXTERNAL_REASONING_UNAVAILABLE"
                    or "no sé" in answer.lower()
                    or "i don't know" in answer.lower()
                ):
                    answer = f"Anotado: {clean_text}."

                # If core returns waiting or unknown, and we have matching memory, fallback to memory
                if (
                    not answer
                    or answer in ("WAITING_FOR_REASONING_CORE", "EXTERNAL_REASONING_UNAVAILABLE")
                    or getattr(res, "availability_status", "") == "EXTERNAL_REASONING_UNAVAILABLE"
                    or "i don't know" in answer.lower()
                ) and is_recall_query and relevant_mem:
                    top_m = relevant_mem[0]
                    src_c = top_m.get("source_conversation_id") or "anterior"
                    answer = f"{top_m['content']} (Recuperado de tu memoria persistente, fuente: {src_c})."
                elif (
                    not answer
                    or answer in ("WAITING_FOR_REASONING_CORE", "EXTERNAL_REASONING_UNAVAILABLE")
                    or getattr(res, "availability_status", "") == "EXTERNAL_REASONING_UNAVAILABLE"
                    or "i don't know" in answer.lower()
                ) and is_continuity_query and (observations or (ctx_data and (ctx_data.get("active_project") or ctx_data.get("recent_messages")))):
                    answer = self._format_continuity_fallback(ctx_data)
                elif is_recall_query and relevant_mem and "fuente:" not in answer.lower():
                    top_m = relevant_mem[0]
                    src_c = top_m.get("source_conversation_id") or "anterior"
                    answer = f"{answer} (Fuente: {src_c})."

            # Section 4 Invariant: successful_remote_action_count > 0 -> NO_TOOL_ACCESS fallback forbidden
            import sys
            last_cap_mission = getattr(sys, "_global_optimus_last_cap_mission", None)
            executed_caps = last_cap_mission.get("actions_executed", []) if isinstance(last_cap_mission, dict) else []
            succ_caps = [a for a in executed_caps if a.get("status") in ("SUCCESS", "VERIFIED") or a.get("verified")]
            if succ_caps:
                is_no_tool_fallback = any(phrase in answer.lower() for phrase in (
                    "no tengo acceso",
                    "no tengo acceso operativo",
                    "sin acceso operativo",
                    "herramientas de sistema",
                    "i don't know",
                    "no sé",
                    "unknown:"
                ))
                if is_no_tool_fallback or not answer:
                    if cap_planner and hasattr(cap_planner, "synthesize_response"):
                        answer = cap_planner.synthesize_response(last_cap_mission, clean_text)
                    else:
                        answer = f"Misión ejecutada físicamente ({len(succ_caps)} acciones exitosas)."

            if not answer:
                answer = "El nucleo de razonamiento no devolvio una respuesta."

            # Persist assistant response
            if self.continuity is not None and active_conv_id:
                asst_meta = {"intent": "EXECUTIVE_ASSESSMENT" if executive_mode else getattr(res, "intent", "REASONING_CHAT")}
                self.continuity.history.add_message(
                    conv_id=active_conv_id,
                    role="assistant",
                    content=answer,
                    metadata=asst_meta
                )
                if user_msg_id:
                    self.continuity.memory.extract_and_store_candidates(clean_text, answer, active_conv_id, user_msg_id)

            provider_outbound_model = getattr(res, "provider_model", "") or brain_effective_model
            provider_outbound_effort = brain_effective_effort
            provider_error = getattr(res, "error_sanitized", "")
            if not provider_error and getattr(res, "unknowns", None):
                for u in res.unknowns:
                    if "UNAVAILABLE" in u or "ERROR" in u:
                        provider_error = u
                        break

            if auth_intent == "CHAT":
                chat_intent = "CHAT"
                chat_route_mode = "CHAT_REASONED"
            else:
                chat_intent = "EXECUTIVE_ASSESSMENT" if executive_mode else getattr(res, "intent", "")
                chat_route_mode = None

            resp_payload = {
                "status": "success",
                "response": answer,
                "intent": chat_intent,
                "route_mode": chat_route_mode,
                "operational_task": False if auth_intent == "CHAT" else bool(session_info.get("operational_task") if session_info else False),
                "confidence": getattr(res, "confidence", 0.0),
                "availability_status": getattr(res, "availability_status", "READY"),
                "provider_used": getattr(res, "provider_used", ""),
                "provider_model": provider_outbound_model,
                "task_id": None if auth_intent == "CHAT" else task_id,
                "client_task_id": None if auth_intent == "CHAT" else client_task_id,
                "mission_id": None if auth_intent == "CHAT" else (mis_id or task_id),
                "active_mission_id": None if auth_intent == "CHAT" else (mis_id or task_id),
                "conversation_id": active_conv_id,
                "message_id": user_msg_id,
                "recalled_memories": recalled_mem_list
            }
            if succ_caps:
                all_p = bool(last_cap_mission.get("all_passed"))
                is_real_verif_fail = any("VERIFICATION_FAILED" in str(a.get("error") or "") for a in executed_caps)
                t_st = "COMPLETED" if all_p else ("VERIFICATION_FAILED" if is_real_verif_fail else "FAILED")
                resp_payload["actions_executed"] = executed_caps
                resp_payload["task_status"] = t_st
                resp_payload["mission_status"] = t_st
                resp_payload["workbench_status"] = "COMPLETED" if all_p else "FAILED"
                resp_payload["workbench_state"] = "COMPLETED" if all_p else "FAILED"
                resp_payload["mission_id"] = mis_id or last_cap_mission.get("mission_id") or task_id
                resp_payload["active_mission_id"] = mis_id or last_cap_mission.get("mission_id") or task_id

            if executive_mode:
                resp_payload["executive_mode"] = True
                resp_payload["executive_decision"] = executive_decision.to_dict() if executive_decision and hasattr(executive_decision, "to_dict") else {}
                resp_payload["executive_execution"] = executive_execution

            return _wrap_response(resp_payload, outbound_model=provider_outbound_model, outbound_effort=provider_outbound_effort, prov_err=provider_error, neural_evidence=neural_shadow_result)
        except Exception as e:
            err_name = type(e).__name__
            err_msg = str(e)
            is_timeout = "timeout" in err_name.lower() or "timeout" in err_msg.lower()
            is_unavail = any(k in err_msg.lower() for k in ("unavailable", "connection", "503", "unreachable", "refused", "disabled"))
            
            if auth_intent == "CHAT":
                chat_err_code = "CHAT_REASONING_TIMEOUT" if is_timeout else ("EXTERNAL_REASONING_UNAVAILABLE" if is_unavail else "CHAT_REASONING_ERROR")
                chat_resp_msg = "El procesamiento del mensaje superó el tiempo límite." if is_timeout else "El proveedor de razonamiento no está disponible en este momento."
                err_payload = {
                    "status": "error",
                    "error": chat_err_code,
                    "message": f"{err_name}: {err_msg}",
                    "response": chat_resp_msg,
                    "availability_status": "TIMEOUT" if is_timeout else "DEGRADED",
                    "intent": "CHAT",
                    "route_mode": "CHAT_ERROR",
                    "operational_task": False,
                    "task_id": None,
                    "client_task_id": None,
                    "mission_id": None,
                    "conversation_id": active_conv_id,
                    "message_id": user_msg_id,
                    "runtime_ack": True,
                }
                return _wrap_response(err_payload, prov_err=f"{err_name}: {err_msg}", neural_evidence=neural_shadow_result)

            err_payload = {
                "status": "error",
                "message": f"Reasoning core execution error: {type(e).__name__}: {e}",
                "response": "Lo siento, ocurrio un error temporal en el nucleo de razonamiento.",
                "availability_status": "DEGRADED",
                "task_id": task_id,
                "conversation_id": active_conv_id,
                "message_id": user_msg_id
            }
            if executive_mode:
                err_payload["executive_mode"] = True
                if executive_decision:
                    err_payload["executive_decision"] = executive_decision.to_dict() if hasattr(executive_decision, "to_dict") else {}
                err_payload["executive_execution"] = executive_execution
            return _wrap_response(err_payload, prov_err=f"{type(e).__name__}: {e}", neural_evidence=neural_shadow_result)

    def process_voice(
        self,
        audio_data: Any = None,
        session_info: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """Transcribes real WAV audio via speech_recognition and delegates to process_chat."""
        if not audio_data or not isinstance(audio_data, (bytes, bytearray)):
            return {
                "status": "error",
                "message": "Datos de audio vacios o invalidos.",
                "response": "No se recibio audio valido.",
                "transcription": "",
                "stt_status": "INVALID_AUDIO",
                "availability_status": "INPUT_INVALID"
            }

        import io
        try:
            import speech_recognition as sr
        except ImportError:
            return {
                "status": "error",
                "message": "Modulo speech_recognition no disponible en el host.",
                "response": "El servicio de reconocimiento de voz no esta instalado en el host.",
                "transcription": "",
                "stt_status": "SERVICE_ERROR",
                "availability_status": "STT_MODULE_UNAVAILABLE"
            }

        r = sr.Recognizer()
        try:
            with sr.AudioFile(io.BytesIO(audio_data)) as source:
                audio = r.record(source)
        except Exception as e:
            return {
                "status": "error",
                "message": f"Formato de audio no reconocido: {type(e).__name__}: {e}",
                "response": "No se pudo leer el archivo de audio. Formato WAV invalido.",
                "transcription": "",
                "stt_status": "INVALID_AUDIO",
                "availability_status": "AUDIO_DECODE_ERROR"
            }

        try:
            transcribed_text = r.recognize_google(audio, language="es-ES")
        except sr.UnknownValueError:
            return {
                "status": "error",
                "message": "No se detecto voz comprensible en el audio.",
                "response": "No pude entender lo que dijiste. Por favor intenta hablar mas cerca del microfono.",
                "transcription": "",
                "stt_status": "UNKNOWN_AUDIO",
                "availability_status": "AUDIO_NOT_UNDERSTOOD"
            }
        except sr.RequestError as e:
            return {
                "status": "error",
                "message": f"Servicio de transcripcion no disponible: {e}",
                "response": "El servicio de transcripcion no respondio en este momento.",
                "transcription": "",
                "stt_status": "SERVICE_ERROR",
                "availability_status": "STT_SERVICE_UNAVAILABLE"
            }
        except Exception as e:
            return {
                "status": "error",
                "message": f"Error inesperado en transcripcion: {type(e).__name__}: {e}",
                "response": "Ocurrio un error al transcribir el audio.",
                "transcription": "",
                "stt_status": "SERVICE_ERROR",
                "availability_status": "STT_ERROR"
            }

        clean_text = (transcribed_text or "").strip()
        if not clean_text:
            return {
                "status": "error",
                "message": "Transcripcion vacia.",
                "response": "No se detectaron palabras en la grabacion.",
                "transcription": "",
                "stt_status": "EMPTY_AUDIO",
                "availability_status": "AUDIO_EMPTY"
            }

        if session_info and session_info.get("transcribe_only"):
            return {
                "status": "success",
                "transcription": clean_text,
                "stt_status": "SUCCESS",
                "message": "Transcripción completada exitosamente.",
                "response": clean_text
            }

        # Delegate to existing validated process_chat
        chat_res = self.process_chat(clean_text, session_info)
        chat_res["transcription"] = clean_text
        chat_res["stt_status"] = "SUCCESS"
        return chat_res

    def analyze_visual_evidence(self, prepared_images, context=None) -> Dict[str, Any]:
        """
        ALPHA75 — PHYSICAL EYES V1: Semantic visual analysis bridge.
        Decouples capture availability from semantic analysis status.
        """
        import json
        import time

        if not isinstance(prepared_images, list) or not prepared_images:
            return {
                "status": "error",
                "analysis_status": "UNAVAILABLE",
                "error": "NO_PREPARED_IMAGES",
                "message": "No se recibieron imagenes preparadas para analisis visual."
            }

        valid_images = []
        max_img_len = 20 * 1024 * 1024
        for img in prepared_images[:2]:
            if isinstance(img, dict):
                d_url = img.get("data_url")
                if isinstance(d_url, str) and d_url.startswith("data:image/") and ";base64," in d_url and len(d_url) <= max_img_len:
                    valid_images.append(img)

        if not valid_images:
            return {
                "status": "error",
                "analysis_status": "UNAVAILABLE",
                "error": "NO_VALID_IMAGES",
                "message": "Ninguna de las imagenes proporcionadas contiene un data_url valido."
            }

        # D2. Asegurar provider real utilizando el mecanismo existente
        if self.core and (not hasattr(self.core, "_provider") or self.core._provider is None):
            try:
                from runtime_v1.foundation.reasoning import _init_real_reasoning_if_available
                _init_real_reasoning_if_available()
            except Exception:
                pass

        if not self.core or not hasattr(self.core, "analyze_visual"):
            return {
                "status": "error",
                "analysis_status": "UNAVAILABLE",
                "error": "CORE_UNAVAILABLE",
                "message": "Reasoning Core no disponible para analisis visual."
            }

        # D3. Prompt de analisis estricto
        analysis_prompt = (
            "Analyze only the supplied screenshot evidence.\n"
            "Return a strict JSON object with this exact shape:\n"
            "{\n"
            '  "summary": "...",\n'
            '  "foreground_assessment": "...",\n'
            '  "visible_text": [],\n'
            '  "ui_elements": [],\n'
            '  "errors": [],\n'
            '  "confidence": 0.0\n'
            "}\n"
            "Rules:\n"
            "- Do not invent text that is not clearly visible.\n"
            "- Do not invent windows or application state.\n"
            "- Do not assert nonexistent buttons or elements.\n"
            "- Do not assume UI success or status by guess.\n"
            "- confidence must be a float between 0.0 and 1.0.\n"
            "- visible_text: at most 20 elements (strings).\n"
            "- ui_elements: at most 20 elements (strings or dicts).\n"
            "- errors: at most 10 elements (strings).\n"
            "Output valid JSON only. Do not wrap in markdown or backticks."
        )

        task_id = f"vis_{int(time.time()*1000)}"
        if context and isinstance(context, dict):
            ctx_scope = context.get("scope")
            ctx_fg = context.get("foreground")
            if ctx_scope or ctx_fg:
                analysis_prompt += f"\nContext note: scope={ctx_scope or 'unknown'}, foreground={ctx_fg or 'unknown'}."

        try:
            prov_resp = self.core.analyze_visual(
                task_id=task_id,
                prompt=analysis_prompt,
                images=valid_images
            )
        except Exception as e:
            return {
                "status": "error",
                "analysis_status": "UNAVAILABLE",
                "error": "VISUAL_ANALYSIS_FAILED",
                "message": f"Error during visual analysis execution: {type(e).__name__}"
            }

        # D4. Validar respuesta del provider
        if not prov_resp or not getattr(prov_resp, "success", False):
            err_sanitized = getattr(prov_resp, "error_sanitized", None) or "PROVIDER_UNSUCCESSFUL"
            return {
                "status": "error",
                "analysis_status": "UNAVAILABLE",
                "error": err_sanitized,
                "message": "Reasoning provider no pudo completar el analisis visual."
            }

        raw_answer = (getattr(prov_resp, "answer", "") or "").strip()
        if not raw_answer:
            return {
                "status": "error",
                "analysis_status": "UNAVAILABLE",
                "error": "EMPTY_PROVIDER_ANSWER",
                "message": "El provider devolvio una respuesta vacia para el analisis visual."
            }

        clean_json_str = raw_answer
        if "```" in clean_json_str:
            m = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", clean_json_str, re.DOTALL)
            if m:
                clean_json_str = m.group(1)
            else:
                m2 = re.search(r"(\{.*\})", clean_json_str, re.DOTALL)
                if m2:
                    clean_json_str = m2.group(1)
        else:
            m2 = re.search(r"(\{.*\})", clean_json_str, re.DOTALL)
            if m2:
                clean_json_str = m2.group(1)

        try:
            parsed = json.loads(clean_json_str)
        except Exception:
            return {
                "status": "error",
                "analysis_status": "UNAVAILABLE",
                "error": "INVALID_JSON_RESPONSE",
                "message": "La respuesta del provider visual no pudo ser parseada como JSON valido."
            }

        if not isinstance(parsed, dict):
            return {
                "status": "error",
                "analysis_status": "UNAVAILABLE",
                "error": "INVALID_ANALYSIS_FORMAT",
                "message": "El analisis visual parseado no es un objeto JSON."
            }

        summary = parsed.get("summary")
        if not summary or not isinstance(summary, str) or not summary.strip():
            return {
                "status": "error",
                "analysis_status": "UNAVAILABLE",
                "error": "EMPTY_SUMMARY",
                "message": "El analisis visual no contiene un summary valido o no vacio."
            }

        fg_assess = parsed.get("foreground_assessment")
        fg_assess_str = str(fg_assess) if fg_assess is not None else ""

        vis_text = parsed.get("visible_text")
        if isinstance(vis_text, list):
            vis_text_clamped = [str(item)[:300] for item in vis_text[:20]]
        else:
            vis_text_clamped = []

        ui_elem = parsed.get("ui_elements")
        if isinstance(ui_elem, list):
            ui_elem_clamped = []
            for item in ui_elem[:20]:
                if isinstance(item, dict):
                    ui_elem_clamped.append({str(k)[:50]: str(v)[:300] for k, v in item.items()})
                else:
                    ui_elem_clamped.append(str(item)[:300])
        else:
            ui_elem_clamped = []

        errs = parsed.get("errors")
        if isinstance(errs, list):
            errs_clamped = [str(item)[:300] for item in errs[:10]]
        else:
            errs_clamped = []

        conf = parsed.get("confidence")
        try:
            conf_val = float(conf)
            conf_val = max(0.0, min(1.0, conf_val))
        except (TypeError, ValueError):
            conf_val = 0.5

        validated_analysis = {
            "summary": summary.strip()[:2000],
            "foreground_assessment": fg_assess_str.strip()[:1000],
            "visible_text": vis_text_clamped,
            "ui_elements": ui_elem_clamped,
            "errors": errs_clamped,
            "confidence": conf_val
        }

        provider_used = getattr(prov_resp, "provider", None) or getattr(getattr(self.core, "_provider", None), "provider_id", "openai")
        provider_model = getattr(prov_resp, "model", None) or getattr(getattr(self.core, "_provider", None), "default_model", "unknown")

        return {
            "status": "success",
            "analysis_status": "ANALYZED",
            "analysis": validated_analysis,
            "provider_used": provider_used,
            "provider_model": provider_model
        }

