
    q0i&                         d Z ddlZddlZddlZddlZddlmZmZ ddlmZ  ed      Z	 ed      Z
 ed      Z ed      Zd	Zd
efdZd ZdedededefdZd Zedk(  r e        yy)a)  
Genesis PreCompact CTM Hook (Layer 3 of Defense System - Enhanced)
=================================================================
Fires before context compaction to backup transcript AND session state.
This is the LAST CHANCE to preserve context before summarization.

Enhanced after session 7e3fae84 crash:
  - Now also triggers a session heartbeat backup
  - Checks for active agents (danger condition for thinking block corruption)
  - Warns if compaction is happening during agent notification storm
  - Prunes old backups to prevent disk bloat
    N)datetimetimezone)Pathz*/mnt/e/genesis-system/data/context_backupsz(/mnt/e/genesis-system/data/context_statez+/mnt/e/genesis-system/hive/session_recoveryz(/mnt/e/genesis-system/data/observability   returnc                      	 t         dz  } | j                         r=t        | d      5 }t        j                  |      }|j                  dd      cddd       S 	 y# 1 sw Y   yxY w# t        $ r Y yw xY w)z%Check if agents are currently active.zmetrics.jsonragents_activer   N)
EVENTS_DIRexistsopenjsonloadget	Exception)metrics_filefmetricss      6/mnt/e/genesis-system/.claude/hooks/pre_compact_ctm.pyget_active_agent_countr      s~    !N2 lC( 7A))A,{{?A67 7 ! 7
   s.   %A& 'A	A& A#A& #A& &	A21A2c                      	 t        t        j                  d            } t        |       t        kD  r | dt          D ]  }|j                           yy# t        $ r Y yw xY w)z=Remove old backups, keeping only the most recent MAX_BACKUPS.zpre_compact_*.jsonlN)sorted
BACKUP_DIRgloblenMAX_BACKUPSunlinkr   )backupsold_files     r   prune_old_backupsr    +   sb    )>?@w<+%#Mk\2 "!" &  s   AA 	AA
session_idtriggeractive_agents	timestampc                     t         j                  dd       t         dz  }d| d|  d| d| d|d	kD  rd
nd d}	 t        |d      5 }|j                  |       ddd       y# 1 sw Y   yxY w# t        $ r Y yw xY w)z*Write a compaction-specific recovery note.Tparentsexist_okz	LATEST.mdzY# Session Recovery State
## Auto-generated by PreCompact CTM Hook

**Compaction Event**: z
**Session ID**: z
**Trigger**: z"
**Active Agents at Compaction**: 
r   zT**WARNING**: Agents were active during compaction -- thinking block corruption risk!z*No agents active during compaction (safe).a@  

## Recovery Instructions
1. If session crashed after this compaction, thinking blocks may have been corrupted
2. The pre-compaction transcript backup is in: `/mnt/e/genesis-system/data/context_backups/`
3. Read MEMORY.md for strategic context
4. Check `/mnt/e/genesis-system/hive/session_backups/` for heartbeat state
wN)RECOVERY_DIRmkdirr   writer   )r!   r"   r#   r$   recovery_filenoter   s          r   write_compaction_recoveryr0   6   s    td3 ;.M !k " Y ""/ 1[hkl[lW  s_  ` `D-% 	GGDM	 	 	 s/   A. A"A. "A+'A. +A. .	A:9A:c                  t   	 t        j                  t        j                  j	                               } | j                  dd      }| j                  dd      }| j                  dd      }t        j                  t        j                        }|j                  d      }t               }t         j#                  dd       |rFt$        j&                  j)                  |      r'	 t         d	| d
| dz  }t+        j,                  ||       t.        j#                  dd       	 |j1                         d||||dkD  d}t.        dz  }	t3        |	d      5 }
|
j5                  t        j                  |      dz          d d d        t7        ||||j1                                t9                i }|dkD  r	d| d|d<   t        t        j                  |             y # t         j
                  t        f$ r! t        t        j                  i              Y y w xY w# t        $ r Y w xY w# 1 sw Y   xY w# t        $ r Y w xY w)Ntranscript_path r"   unknownr!   z%Y%m%d_%H%M%STr&   pre_compact__z.jsonlpre_compactr   )r$   eventr"   r!   r#   dangerzcompaction_log.jsonlar)   zCOMPACTION DANGER: a   agent(s) still active during compaction. Post-compaction thinking blocks may be corrupted if agent notifications arrive during the next API call. Consider killing agents or waiting for them to complete before continuing. This is the exact scenario that killed session 7e3fae84.additionalContext)r   loadssysstdinreadJSONDecodeErrorr   printdumpsr   r   nowr   utcstrftimer   r   r,   ospathr   shutilcopy2	STATE_DIR	isoformatr   r-   r0   r    )
hook_inputr2   r"   r!   rC   r$   r#   backup_filer8   log_filer   results               r   mainrP   Q   s   ZZ		 01

 !nn%6;OnnY	2Gi8J
,,x||
$C_-I*,M TD1277>>/:	$gYa	{&'QQKLL+6
 OOD4O0"$*#a'
 55(C  	.AGGDJJu%,-	. j'=#--/R  Fq!- 1' ( 	"# 
$**V
q   ), djjn&  			. 	. sM   1G  &H /H+ (H5H+ 7HH	HHH($H+ +	H76H7__main__)__doc__r=   r   rF   rH   r   r   pathlibr   r   rJ   r+   r   r   intr   r    strr0   rP   __name__     r   <module>rY      s      	  ' >?
;<	AB<=
 
 
#  C \_ 6;| zF rX   