
    ^i1                         d Z ddlZddlZddlmZ ddlmZmZ ddlmZ ddl	m
Z
 dZ e ej                  dd	            Zd
Z G d d      Zy)u   
MemGPTEscalation — Opus escalation handler.
When MVFL correction loop exhausts 3 attempts, this handler
builds full failure context and dispatches to Opus for resolution.
    N)	dataclass)datetimetimezone)Path)Optionalzclaude-opus-4-6EVENTS_LOG_PATHz5/mnt/e/genesis-system/data/observability/events.jsonlzYou are the Genesis Maximum-Effort Resolver. Previous agents have failed {attempt_count} times. Full failure history:
{failure_history}

Resolve this definitively. Provide a complete, correct output.c            	       Z    e Zd ZdZddZ	 ddededee   defdZd	ede	fd
Z
deddfdZy)MemGPTEscalationu  
    Opus escalation handler for the MVFL correction pipeline.

    When the CorrectionLoop exhausts MAX_CORRECTION_ATTEMPTS, this class
    takes over: it builds a rich context prompt from all failure history
    and dispatches the task to claude-opus-4-6 for a definitive resolution.

    The dispatch function is injected for full testability — no real API
    calls are made in unit tests.
    Nc                     || _         y)z
        Args:
            dispatch_fn: async callable (model, system_prompt, task_payload) -> dict
                         If None, returns a stub escalated response (used in tests).
        N)	_dispatch)selfdispatch_fns     4/mnt/e/genesis-system/core/mvfl/memgpt_escalation.py__init__zMemGPTEscalation.__init__#   s     %    task_payloadfailed_outputfailure_historyreturnc           	        K   |j                  dd      }||n|g}t        |      }| j                  |      }t        j	                  ||      }| j                  d|t        |t        j                  t        j                        j                         d       	 | j                  r!| j                  t        ||       d{   }	|	S |dt        dt         d	|d
S 7 # t        $ r}
|ddt        |
      t        dcY d}
~
S d}
~
ww xY ww)uQ  
        Escalate to Opus with full failure context.

        Builds a system prompt that includes all failed attempt details,
        then dispatches to ESCALATION_MODEL. Logs an "mvfl_escalation"
        event to the observability log regardless of outcome.

        Args:
            task_payload:    Original task that failed (must contain 'task_id').
            failed_output:   The last failed output from the CorrectionLoop.
            failure_history: List of all failed attempt dicts. If not provided,
                             [failed_output] is used as a single-item history.

        Returns:
            Standard output dict from Opus dispatch, OR:
              - {"status": "escalated", ...}  — when no dispatch_fn configured
              - {"status": "error", "error": "MVFL_ESCALATION_FAILED", ...} — on exception
        task_idunknownN)attempt_countr   mvfl_escalation)eventr   modelr   	timestamp	escalatedzEscalation to z, requested (no dispatch function configured))r   statusr   outputr   errorMVFL_ESCALATION_FAILED)r   r   r!   error_detailr   )getlen_build_history_stringESCALATION_SYSTEM_PROMPTformat
_log_eventESCALATION_MODELr   nowr   utc	isoformatr   	Exceptionstr)r   r   r   r   r   historyr   history_strsystem_promptresultes              r   escalatezMemGPTEscalation.escalate+   s     0 ""9i8%4%@/}oG 009 177'' 8 
 	&%*!hll3==?
 		~~#~~.>|\\  ')-()9(: ;< < &3	 		 ]  	"!1 #A) 	sT   BD&C  CC DC DC 	D&D :D;D DDr0   c                 "   g }t        |d      D ]n  \  }}|j                  d| d       t        |t              r0|j	                         D ]  \  }}|j                  d| d|         [|j                  d|        p dj                  |      S )a  
        Format failure history list into a numbered, human-readable string.

        Each attempt is shown as a numbered block with all key-value pairs
        (or a raw string representation for non-dict entries).

        Args:
            history: List of attempt dicts or raw values.

        Returns:
            Multi-line string suitable for inclusion in the Opus system prompt.
           z--- Attempt z ---z  z: 
)	enumerateappend
isinstancedictitemsjoin)r   r0   partsiattemptkvs          r   r&   z&MemGPTEscalation._build_history_strings   s     #GQ/ 	-JAwLL<s$/0'4(#MMO 0DAqLL2aS1#/0 r'^,	- yyr   r   c                     	 t         j                  j                  dd       t        t         d      5 }|j	                  t        j                  |      dz          ddd       y# 1 sw Y   yxY w# t        $ r Y yw xY w)u   
        Append a JSON event line to the observability events log.
        Never raises — telemetry must not break the pipeline.
        T)parentsexist_okar8   N)r   parentmkdiropenwritejsondumpsr.   )r   r   fs      r   r)   zMemGPTEscalation._log_event   sl    
	""(((Eos+ 2q

5)D012 2 2 		s.   1A0 (A$A0 $A-)A0 -A0 0	A<;A<)N)__name__
__module____qualname____doc__r   r<   r   listr5   r/   r&   r)    r   r   r
   r
      sl    	% +/	FF F "$	F
 
FP T  c  .
 
 
r   r
   )rR   rL   osdataclassesr   r   r   pathlibr   typingr   r*   getenvr   r'   r
   rT   r   r   <module>rZ      sT   
  	 ! '  $ yryy!24klmE } }r   