
    cDi;                        S r SSKrSSKJrJr  SSKJr  SSKJr  SSKrSSK	r	\	R                  " 5       S:X  a	  \" S5      rO\" S5      r\S	-  S
-  r\S-  S-  r\S	-  S-  r\S-  S-  S-  r\S-  S-  S-  r S3S\S\\   S\\   S\S\4
S jjrS4S\S\S\4S jjrS\4S jrS r\S:X  a  SSKr\" \R8                  5      S:  a  \" S 5        \R<                  " S!5        \R8                  S!   r\S":X  a-  \" S#5        \" S$S%S&// S'QS(S)9r \" \RB                  " \ SS*95        g\S+:X  a'  \" S,5        \" S-S.S/9r \" \RB                  " \ SS*95        g\S0:X  a  \" S15        \" 5       r"\" \"5        g\" S2\ 35        \R<                  " S!5        gg)5a  
Gemini CLI CTM (Commit To Memory) + State Flush Tool
=====================================================
Provides explicit memory persistence for Gemini CLI sessions.
Since Gemini CLI has no hook system, these functions can be called as MCP tools.

Functions:
- ctm_flush: Save session state to handoff files
- respawn_signal: Signal that a respawn is needed
- read_boot_context: Load context for new session startup

Author: Genesis Parallel Builder
Created: 2026-02-23
    N)datetimetimezone)Path)OptionalWindowszE:/genesis-systemz/mnt/e/genesis-systemhiveprogressz.gemini	knowledgesession_recoverydataobservabilityzevents.jsonlcontext_statezBOOT_CONTEXT.mdsession_summarykey_decisionspending_tasks
session_idreturnc           	      8    [         R                  " [        R                  5      nUR	                  S5      nU=(       d    SU 3n[
        R                  SSS9  [        R                  SSS9  SU SUR                  5        SU  S3nU(       a  U H  nUS	U S
3-  nM     OUS-  nUS-  nU(       a   [        US5       H  u  pXy SU
 S
3-  nM     OUS-  nUSUR                  5        S[        U5       S[        U5       S3-  n[
        SU S3-  n[        USSS9 nUR                  U5        SSS5        [        S-  n[        USSS9 nUR                  U5        SSS5         [        R                  R                  SSS9  UR                  5       SU[        U5      [        U5      [        U 5      S.n[        [        SSS9 nUR                  [        R                   " U5      S
-   5        SSS5        S[%        U5      [%        U5      [        U5      [        U5      UR                  5       S.$ ! , (       d  f       GN	= f! , (       d  f       N= f! , (       d  f       Nl= f! ["         a     N{f = f! ["         a  nS [%        U5      S!S".s SnA$ SnAff = f)#aY  
Commit current session state to memory (handoff files).

This is Gemini CLI's equivalent of Claude's pre_compact_ctm.py hook.
Call this before context gets too large or when ending a session.

Args:
    session_summary: Brief summary of work done this session
    key_decisions: List of important decisions made (strategic pivots, locked choices)
    pending_tasks: List of incomplete tasks for next session
    session_id: Optional session identifier (defaults to timestamp)

Returns:
    dict with status, handoff file path, and task count

Example:
    result = ctm_flush(
        session_summary="Built Telnyx KB, started voice widget polish",
        key_decisions=["Use Gemini Flash for voice AI", "Lock pricing at $197/mo"],
        pending_tasks=["Finish widget UI", "Test George's number", "Deploy to prod"],
        session_id="gemini-001"
    )
z%Y%m%d_%H%M%Sgemini_Tparentsexist_okz,# Gemini CLI Session Handoff
## Session ID: z
## Timestamp: z

---

## Session Summary
z

---

## Key Decisions Made
z- 
z$*(No major decisions this session)*
z
---

## Pending Tasks
   z. [ ] z*(No pending tasks)*
u|  
---

## Recovery Instructions
This is a Gemini CLI session handoff. Next Gemini session should:
1. Read this file to understand context
2. Read BOOT_CONTEXT.md for current mission state
3. Continue with highest-priority pending task
4. DO NOT ask user "what should I work on?" — pick up where this left off

## Handoff Metadata
- **Session Type**: Gemini CLI
- **Flushed At**: z
- **Tasks Pending**: z
- **Decisions Made**: z(

---
*Auto-generated by gemini_ctm.py*
gemini_session_z_handoff.mdwutf-8encodingNlatest_handoff.mdgemini_ctm_flush)	timestamp
event_typer   
task_countdecision_countsummary_lengthaflushed)statushandoff_pathlatest_handoff_pathtasks_saveddecisions_savedr"   errorr   )r)   r.   r,   )r   nowr   utcstrftimeHANDOFF_DIRmkdirGEMINI_KNOWLEDGE	isoformat	enumeratelenopenwriteEVENTS_FILEparentjsondumps	Exceptionstr)r   r   r   r   r/   r"   sidhandoff_contentdecisionitaskr*   fr+   eventes                   8E:\genesis-system\mcp-servers\genesis-core\gemini_ctm.py	ctm_flushrI   0   s   :g
ll8<<(LL1	1gi[1 	$6td;u }}  
    )Rz#44 * FFO  	
 $]A6StfB#77 7 77O   ==?# $-() *=)* + 	* #yk%MM,g6!GGO$ 7 /1DD%sW=GGO$ >	$$TD$A ]]_0!!-0"%m"4"%o"6E k39Q

5)D01 :  -#&':#;}-"=1
 	
3 76
 >= :9 		  
 V
 	

s   DI6 H20I6 II6 'AI& )I/I& 7:I6 2
I<I6 
II6 
I#I& "I6 #I& &
I30I6 2I33I6 6
J JJJreasoncontext_pctc                 &    [         R                  " [        R                  5      n[        R                  SSS9  [        S-  nSUR                  5        SU  SU S3n[        USS	S
9 nUR                  U5        SSS5        [        S-  nUR                  5       (       af  [        USS	S
9 nUR                  5       nSSS5        SUR                  5        SU  SU S3n[        USS	S
9 nUR                  UW-   5        SSS5         [        R                  R                  SSS9  UR                  5       SU US.n	[        [        SS	S
9 nUR                  [        R                  " U	5      S-   5        SSS5        SU U[#        U5      UR                  5       S.$ ! , (       d  f       GN&= f! , (       d  f       N= f! , (       d  f       N= f! , (       d  f       Na= f! [          a     Npf = f! [          a  n
S[#        U
5      S.s Sn
A
$ Sn
A
ff = f)a  
Signal that a Gemini CLI respawn is needed.

This creates a recovery file indicating the session needs to restart.
Use this when context is getting too large or when encountering
unrecoverable errors.

Args:
    reason: Why respawn is needed (e.g., "context overflow", "API error loop")
    context_pct: Estimated context usage percentage (0-100)

Returns:
    dict with status and reason

Example:
    respawn_signal("Context at 85%, time to hand off", context_pct=85)
Tr   GEMINI_RESPAWN.mdz-# GEMINI CLI RESPAWN NEEDED
**Signaled At**: z
**Reason**: z
**Context Usage**: a  %

---

## What happened
The current Gemini CLI session has signaled that it needs to respawn.
This is typically due to:
- Context window filling up (>80%)
- Repeated API errors
- Session instability
- Manual CTM flush before planned restart

## Recovery Steps
1. Read the latest handoff: `.gemini/knowledge/latest_handoff.md`
2. Read BOOT_CONTEXT.md for mission context
3. Continue with pending tasks from handoff
4. Delete this file after recovery

---
*Auto-generated by gemini_ctm.py respawn_signal()*
r   r   r   Nr    ru)   # ⚠️ RESPAWN NEEDED ⚠️
**Time**: z
**Context**: zZ% full

The previous Gemini session requested a respawn. Continue from tasks below.

---

gemini_respawn_signal)r"   r#   rJ   rK   r'   r   respawn_signaled)r)   rJ   rK   recovery_filer"   r.   )r)   r.   )r   r/   r   r0   RECOVERY_DIRr3   r5   r8   r9   r4   existsreadr:   r;   r<   r=   r>   r?   )rJ   rK   r/   respawn_filerespawn_contentrE   r+   existing_contentbannerrF   rG   s              rH   respawn_signalrY      s   $R
ll8<<( 	4$7 $&99--/" #H = !2 ,g6!GGO$ 7 /1DD%%'')3AQ#$668  B==?
 H ] 	F )3AQ!112 B	$$TD$A ]]_5 *	E k39Q

5)D01 : )& .
 	
K 76 BA BA :9 		  
V
 	

s   A&G. (F:1G. +F+<-G. )F<>G. AG 	)G2G :G. 
F(#G. +
F95G. <
G
G. 
GG G. G 
G+(G. *G++G. .
H8HHHc                      / n [         R                  5       (       a]   [        [         SSS9 nUR                  5       nSSS5        U R	                  S5        U R	                  W5        U R	                  S5        OU R	                  S5        [        S	-  nUR                  5       (       aY   [        USSS9 nUR                  5       nSSS5        U R	                  S
5        U R	                  W5        U R	                  S5        OU R	                  S5        [        S-  nUR                  5       (       aX   [        USSS9 nUR                  5       nSSS5        U R	                  S5        U R	                  W5        U R	                  S5        U R	                  S5        U R	                  S5        SR                  U 5      $ ! , (       d  f       GN= f! [
         a    U R	                  S5         GNaf = f! , (       d  f       GN1= f! [
         a    U R	                  S5         GNf = f! , (       d  f       N= f! [
         a     Nf = f! [
         a  nS[        U5       S3s SnA$ SnAff = f)ub  
Read combined boot context for a new Gemini session.

This loads:
1. BOOT_CONTEXT.md — current mission, stack status, priority tasks
2. latest_handoff.md — previous session's final state

Returns:
    Combined string with full boot context

Example:
    context = read_boot_context()
    # Use this as context when starting a new Gemini CLI session
rN   r   r   Nz# === GENESIS BOOT CONTEXT ===
z

u&   # BOOT_CONTEXT.md — could not read

u!   # BOOT_CONTEXT.md — not found

r    z## === PREVIOUS SESSION HANDOFF ===
u(   # latest_handoff.md — could not read

u3   # latest_handoff.md — no previous session found

rM   z"# === RESPAWN SIGNAL DETECTED ===
z# === BOOT INSTRUCTIONS ===
u.  
You are a Gemini CLI session starting up in Genesis.

IMMEDIATE ACTIONS:
1. Review BOOT_CONTEXT above for current mission and priorities
2. Review PREVIOUS SESSION HANDOFF for continuity
3. Pick up where the last session left off (do NOT ask user what to do)
4. If RESPAWN SIGNAL present, acknowledge and continue from pending tasks

REMEMBER:
- All work happens on E: drive (never C: drive)
- Use ctm_flush() before context fills up
- Signal respawn when context > 80%
- Genesis is proactive — show findings as they arrive, never wait

Ready to execute.
 z# ERROR reading boot context

z:

Falling back to minimal context. Check filesystem paths.)
BOOT_CONTEXT_FILErS   r8   rT   appendr>   r4   rR   joinr?   )outputrE   boot_contentr+   rA   rU   rV   rG   s           rH   read_boot_contextra     s   Bw ##%%J+S7Cq#$668L D@Al+f% MM?@ /1DD%%''L-sWE&'ffhO FDEo.f% MMQR $&99  ,g>!&'ffhO ?CDo.f%
 	56  	$ wwvq DC
  JHIJ FE
  LJKL ?>
  2  w1#a&9uvvws   I G F<;G 90I *H 5G0;H 0I 2H5 =H$;H5 	2I <
GG G-)I ,G--I 0
G?:H H!I  H!!I $
H2.H5 5
I?I II 
I(I#I(#I(c                 &   U R                  5        SS[        S[        [           S[        [           S[        S[        4
S jj5       nU R                  5       SS[        S[        S[        4S	 jj5       nU R                  5       S[        4S
 j5       ng)z
Register Gemini CTM tools with an MCP server instance.

Usage in server.py:
    from gemini_ctm import register_gemini_tools
    register_gemini_tools(mcp)

Args:
    mcp_server: FastMCP server instance
r   r   r   r   r   c                 D    [        XX#5      n[        R                  " USS9$ )ai  Commit Gemini CLI session state to memory (handoff files).

Call this before context fills up or when ending a session.

Args:
    session_summary: Brief summary of work done
    key_decisions: List of important decisions made
    pending_tasks: List of incomplete tasks
    session_id: Optional session identifier

Returns:
    JSON with status and file paths
   indent)rI   r<   r=   )r   r   r   r   results        rH   r!   /register_gemini_tools.<locals>.gemini_ctm_flush  s!    ( ?=Uzz&++    rJ   rK   c                 B    [        X5      n[        R                  " USS9$ )zSignal that Gemini CLI needs to respawn.

Use when context is too large or encountering errors.

Args:
    reason: Why respawn is needed
    context_pct: Estimated context usage (0-100)

Returns:
    JSON with status and recovery file path
rd   re   )rY   r<   r=   )rJ   rK   rg   s      rH   rO   4register_gemini_tools.<locals>.gemini_respawn_signal  s      4zz&++ri   c                      [        5       $ )zvRead combined boot context for new Gemini session.

Returns:
    Combined BOOT_CONTEXT.md + latest_handoff.md content
)ra    ri   rH   gemini_read_boot_context7register_gemini_tools.<locals>.gemini_read_boot_context  s     !""ri   Nr[   r   )toolr?   listint)
mcp_serverr!   rO   rn   s       rH   register_gemini_toolsrv   v  s     __
 	,,Cy, Cy, 	,
 
, ,, __,c , ,C , , __#c # #ri   __main__rd   zCUsage: python gemini_ctm.py [test_flush | test_respawn | test_boot]r   
test_flushzTesting CTM flush...zTest session for CTM validationzTest decision 1zTest decision 2)zTest task 1zTest task 2zTest task 3test_session_001)r   r   r   r   re   test_respawnzTesting respawn signal...zManual test of respawn signalK   )rK   	test_bootzTesting boot context read...zUnknown command: rp   rq   )#__doc__r<   r   r   pathlibr   typingr   osplatformsystemGENESIS_ROOTr2   r4   rR   r:   r\   r?   rs   dictrI   rt   rY   ra   rv   __name__sysr7   argvprintexitcommandrg   r=   contextrm   ri   rH   <module>r      s    '   
  ??	!+,L /0LV#j0)+k9 f$'99V#o5F 6)O;>OO  	D
D
9D
 9D
 	D

 
D
Nd
3 d
S d
 d
NQw3 Qwp:#B z
388}qSThhqkG,$%=,.?@G)	
 	djj*+	N	")* ?RPdjj*+	K	,-#%g 	!'+,? ri   