
    _iA                        S r SSKrSSKrSSKrSSKrSSKJr  SSKJr  SSKJ	r	J
r
JrJr  \" S5      r\S-  S-  r\S-  S	-  r\S
-  r\S-  r\S-  S-  S-  rSr/ SQr " S S5      r\S:X  Ga  SSKr\R0                  " SS9r\R5                  S\SS9  \R5                  S\SSS9  \R5                  S\SSS9  \R5                  S S!S"S#9  \R9                  5       r\" 5       r\R>                  (       a&  \ " \RB                  " \RE                  5       S$S%95        g\RF                  (       aS  \RI                  \RJ                  \RL                  \RF                  S&.5      r'\ " \RB                  " \'S$S%95        \ " S'5        g\ " S(5        \ " S)5        gg)*uB  
GENESIS EVOLUTION ENGINE
=========================
Implements RULE 14: Failure Is Our Greatest Ally.

Every failure that enters this engine is processed through the full
4-step Evolution Protocol:
  Step 1: DIAGNOSE  — What happened, exactly?
  Step 2: ROOT CAUSE — Why? (5-Why analysis)
  Step 3: PRE-MORTEM — Guardrail to prevent recurrence
  Step 4: EVOLVE    — Write to KG, axioms, CLAUDE.md, GLOBAL_GENESIS_RULES.md

Also implements:
  - TITAN MEMORY updates (CLAUDE.md Titan Memory section)
  - RLM Worker pattern (watchful, associative, insatiable, fast)
  - Failure log persistence to KNOWLEDGE_GRAPH/entities/failure_evolution_log.jsonl
  - Axiom generation to KNOWLEDGE_GRAPH/axioms/

Usage:
    from core.evolution_engine import EvolutionEngine

    engine = EvolutionEngine()
    engine.process_failure({
        "project": "receptionistai",
        "task": "RAI-003",
        "what": "Telnyx API returned 422 on assistant clone",
        "root_cause": ""
    })

    # Also callable from CLI:
    python core/evolution_engine.py --failure "Gemini rate limit exceeded"
    N)datetime)Path)DictListOptionalAnyzE:/genesis-systemKNOWLEDGE_GRAPHentitiesaxiomszfailure_evolution_log.jsonlz	CLAUDE.mdz.clauderuleszGLOBAL_GENESIS_RULES.mdg      ?)
receptionistaiaivasunaivarevenueclienttelnyxstripeghlvoice
productionc                   |   \ rS rSrSrS rS\\\4   S\\\4   4S jr	S\S\4S jr
S\S\4S jrS\S\4S	 jrS\4S
 jrS\S\4S jrS\S\4S jrS\S\4S jrS\S\S\\   4S jrS\S\S\4S jrS\S\4S jrS\S\4S jrS\4S jrS\4S jrS\S\4S jrS\4S jrS\\   S\\   4S jrS\4S jrSrg)EvolutionEngine=   a  
Processes failures and surprises through the Genesis Evolution Protocol.

This is the LEARNING brain of Genesis. Every failure makes Genesis smarter.
The engine:
1. Diagnoses failures with structured analysis
2. Performs 5-Why root cause analysis
3. Designs guardrails to prevent recurrence
4. Writes findings to the living knowledge base
5. Updates TITAN MEMORY in CLAUDE.md
6. Generates axioms for the RLM bloodstream

RULE 14 compliance is mandatory. This engine is NOT optional.
c                 p    [         R                  SSS9  [        R                  SSS9  SU l        SU l        g )NT)parentsexist_okr   )KG_ENTITIES_PATHmkdirKG_AXIOMS_PATHfailures_processedaxioms_generated)selfs    *E:\genesis-system\core\evolution_engine.py__init__EvolutionEngine.__init__M   s8    td;TD9"# !    failurereturnc                     U R                  U5      nU R                  U5      nU R                  U5      nU R                  U5        U =R                  S-  sl        U$ )z
Main entry point. Process a failure through all 4 evolution steps.

Args:
    failure: Dict with keys: project, task, what, root_cause (optional)

Returns:
    Enriched failure dict with diagnosis, guardrail, axiom
   )_step1_diagnose_step2_root_cause_step3_premortem_step4_evolver    r"   r'   s     r#   process_failureEvolutionEngine.process_failureS   s^     &&w/ ((1 ''0 	7#1$r&   c                    UR                  SS[        [        R                  " 5       5       35        UR                  S[        R                  " 5       R                  S5      5        UR                  S[        R                  " 5       R                  5       5        UR                  SS5        UR                  SS5        UR                  S	S
5        U R                  U5      US'   U R                  U5      US'   U$ )z&Step 1: Clarify exactly what happened.idfailure_date%Y-%m-%d	timestampprojectunknowntaskwhatzUnspecified failureseveritysurprise_score)	
setdefaultinttimer   nowstrftime	isoformat_score_severity_score_surpriser/   s     r#   r+   EvolutionEngine._step1_diagnosel   s    48C		,<+=!>?68<<>#:#::#FG;(@(@(BC9i069-6#89 #227;
$($8$8$A !r&   c                     UR                  SS5      R                  5       nUR                  SS5      nU(       a  US:X  a  U R                  U5      nX1S'   U R                  X#5      US'   U$ )z:Step 2: 5-Why root cause analysis (rule-based heuristics).r;    
root_causezNot yet determined	five_whys)getlower_infer_root_cause_build_five_whys)r"   r'   r;   rI   s       r#   r,   !EvolutionEngine._step2_root_cause{   sj    {{62&,,. [[r2
Z+??//5J *#44TFr&   c                     UR                  SS5      R                  5       nUR                  SS5      R                  5       nU R                  X#5      nXAS'   SU R                  U5       SUR                  5        3US'   U$ )z6Step 3: Design the guardrail that prevents recurrence.r;   rH   rI   guardrail_addedzBefore z	, always never_again)rK   rL   _design_guardrail_extract_action)r"   r'   r;   rI   	guardrails        r#   r-    EvolutionEngine._step3_premortem   s    {{62&,,.[[r288:
**4<	%.!"d**4019??;L:MN 	 r&   c                     U R                  U5        U R                  U5        U R                  U5      nU R                  X!5        UR	                  SS5      S;   a  U R                  U5        gg)z.Step 4: Write failure to all knowledge stores.r<   low)highcriticalN)_write_failure_log_write_kg_entity_generate_axiom_write_axiomrK   _update_titan_memory)r"   r'   axioms      r#   r.   EvolutionEngine._step4_evolve   sl     	( 	g& $$W-%) ;;z5)-AA%%g. Br&   c                 2  ^^ UR                  SS5      R                  5       mUR                  SS5      R                  5       m[        U4S j[         5       5      (       a  [        U4S jS 5       5      (       a  gg[        U4S	 jS
 5       5      (       a  gg)z7Score failure severity: low / medium / high / critical.r;   rH   r8   c              3   ,   >#    U  H	  oT;   v   M     g 7fN ).0domainr8   s     r#   	<genexpr>2EvolutionEngine._score_severity.<locals>.<genexpr>   s     C/BV /B   c              3   ,   >#    U  H	  oT;   v   M     g 7frd   re   rf   kwr;   s     r#   rh   ri      s     g(f":(frj   )z	data losszproduction downr   r   crashrZ   rY   c              3   ,   >#    U  H	  oT;   v   M     g 7frd   re   rl   s     r#   rh   ri      s     V$UbTz$Urj   )errorfail	exceptionrn   brokenmediumrX   )rK   rL   anyHIGH_STAKES_DOMAINS)r"   r'   r8   r;   s     @@r#   rD   EvolutionEngine._score_severity   sw    {{62&,,.++i,224C/BCCCg(fggg!V$UVVVr&   c                    ^ UR                  SS5      R                  5       m[        U4S jS 5       5      (       a  g[        U4S jS 5       5      (       a  gg	)
z
Score how surprising this failure is (0.0 - 1.0).
Higher = more surprising = more learning value.
RLM workers activate on score >= SURPRISE_THRESHOLD (0.50).
r;   rH   c              3   ,   >#    U  H	  oT;   v   M     g 7frd   re   rl   s     r#   rh   2EvolutionEngine._score_surprise.<locals>.<genexpr>   s     i$hbTz$hrj   )
unexpectedzshould havethoughtassumedzworked before333333?c              3   ,   >#    U  H	  oT;   v   M     g 7frd   re   rl   s     r#   rh   rz      s     b$abTz$arj   )
rate limittimeoutauth
permission404422g333333?gffffff?)rK   rL   ru   )r"   r'   r;   s     @r#   rE   EvolutionEngine._score_surprise   sQ     {{62&,,. i$hiii b$abbb r&   r;   c                    ^ / SQS4/ SQS4/ SQS4/ SQS4/ S	QS
4/ SQS4/ SQS4/ SQS4/ SQS4/ SQS4/
nU H#  u  p4[        U4S jU 5       5      (       d  M!  Us  $    g)z9Rule-based root cause inference from failure description.)r   429quotaz0API rate limits not pre-checked before execution)r   401403r   unauthorizedz1Authentication state not verified before API call)r   zconnection refusednetworkz3Network/connectivity not validated before operation)r   	not foundmissingz#Resource existence not pre-verified)r   invalid
validationz=Input data not validated against API schema before submission)importzmodule not foundz	no modulez/Dependency not installed or path not configured)c: drivezc:\z	disk fullspaceu6   C: drive used instead of E: drive — RULE 6 violation)sqlitez.db filesqlite3u;   SQLite used instead of Elestio storage — RULE 7 violation)asked kinanzmanual stepzhuman neededu@   Automation not attempted before escalating — RULE 11 violation)
assumptionr}   guesseduD   Decision made without research — RULE 8 (Research-First) violationc              3   ,   >#    U  H	  oT;   v   M     g 7frd   re   rl   s     r#   rh   4EvolutionEngine._infer_root_cause.<locals>.<genexpr>   s     1":rj   uC   Systemic gap not yet categorized — requires manual 5-Why analysisru   )r"   r;   patternskeywordscauses    `   r#   rM   !EvolutionEngine._infer_root_cause   s     ,-_`ACvw9;pq,.ST-/no8:kl79qr.0mn;=  A13yz
  (OH1111  ( Ur&   rI   c                 "    SUSS  3SU 3SSS/$ )zGenerate the 5-Why chain.u   Why did this fail? — Nd   u   Why did that happen? — uN   Why was that gap present? — No pre-execution check existed for this scenariouS   Why was no check present? — Rule not yet codified or enforcement mechanism absentuQ   Why was the rule absent? — This failure pattern had not been encountered beforere   )r"   r;   rI   s      r#   rN    EvolutionEngine._build_five_whys   s1     &d4Cj\2'
|4\a_
 	
r&   c           
         ^^ / SQS4/ SQS4SS/S4SS	/S
4SS/S4SS/S4S/S4SS/S4SS/S4/	nU H$  u  pE[        UU4S jU 5       5      (       d  M"  Us  $    g)z2Design a specific guardrail to prevent recurrence.)r   r   r   z:Check rate limit capacity before submitting batch requests)r   r   r   zEVerify authentication token is valid and non-expired before API callsr   r   z<Implement retry with exponential backoff and circuit breakerr   r   z>Pre-verify resource existence with GET before PUT/PATCH/DELETEr   r   z5Validate payload against API schema before submissionr   diskzAAssert working directory starts with E: before any file operationr   u?   Grep for 'import sqlite3' before commit — fail build if foundr   manualz7Run browser automation check before escalating to Kinanr   r}   z6Locate and read research files before writing any codec              3   D   >#    U  H  oT;   =(       d    UT;   v   M     g 7frd   re   )rf   rm   rI   r;   s     r#   rh   4EvolutionEngine._design_guardrail.<locals>.<genexpr>   s      EHb:1z!11Hs    zMAdd pre-execution verification step and automated test to detect this patternr   )r"   r;   rI   guardrail_mapr   rU   s    ``   r#   rS   !EvolutionEngine._design_guardrail   s     ,-ij#%lm#%cd5!#cd\"$[\&!#fgZZ[X&(abI&(`a

 $1HEHEEE   $1 _r&   c                 0    / SQnU H  nX1;   d  M
  Us  $    g)zJExtract the verb/action from failure description for the never_again rule.)calling
submittingwritingreading	executingrunning	deployingr   re   )r"   r;   action_wordswords       r#   rT   EvolutionEngine._extract_action   s     k D| ! r&   c           
          UR                  SS5      nUR                  SS5      nSUR                  5        SU SUR                  SS	5      S
S  SUR                  S5       S3	$ )z/Generate a single crisp axiom from the failure.rQ   verify before actingr8   general[z
] Lesson: z. Root: rI   r9   NP   z. Date: r5   .)rK   upper)r"   r'   rU   r8   s       r#   r]   EvolutionEngine._generate_axiom   sv    KK 13IJ	++i3 
9+ 6[[y9#2>? @[[(),	
r&   c                     [        [        S5       nUR                  [        R                  " U5      S-   5        SSS5        g! , (       d  f       g= f)z3Append failure to the master failure evolution log.a
N)openFAILURE_LOG_PATHwritejsondumps)r"   r'   fs      r#   r[   "EvolutionEngine._write_failure_log	  s5    "C(AGGDJJw'$./ )((s   )A
Ac                 V   [         R                  " 5       R                  S5      n[        SU S3-  nSUS   UR	                  S5      UR	                  S5      UR	                  S5      UR	                  S	5      UR	                  S
5      UR	                  S5      UR	                  S5      UR	                  S5      UR	                  S5      UR	                  S/ 5      SS.n[        US5       nUR                  [        R                  " U5      S-   5        SSS5        g! , (       d  f       g= f)zWrite failure as a KG entity.%Y_%m_%dfailure_evolution_.jsonlfailure_eventr3   r7   r8   r:   r<   r=   r;   rI   rQ   rR   rJ   evolution_engine_v1)entity_type	entity_idr7   r8   r:   r<   r=   r;   rI   rU   rR   rJ   processed_byr   r   N)	r   rA   rB   r   rK   r   r   r   r   )r"   r'   todayentity_pathentityr   s         r#   r\    EvolutionEngine._write_kg_entity  s    ''
3&+=eWF)KK*  [1{{9-KK'J/%kk*:;KK'!++l3 %67";;}5 ["51
 +s#qGGDJJv&-. $##s   ()D
D(
axiom_textc                    [         R                  " 5       R                  S5      n[        SU S3-  nUSUR	                  S5      UR	                  S5      S[         R                  " 5       R                  5       S.n[        US	5       nUR                  [        R                  " U5      S
-   5        SSS5        U =R                  S-  sl
        g! , (       d  f       N$= f)z$Write axiom to the axioms directory.r   failure_axioms_r   evolution_enginer3   r8   r~   )r`   source
failure_idr8   
confidence
created_atr   r   Nr*   )r   rA   rB   r   rK   rC   r   r   r   r   r!   )r"   r   r'   r   
axiom_pathaxiom_entryr   s          r#   r^   EvolutionEngine._write_axiom$  s    ''
3#wf&EE
(!++d+{{9-",,.224
 *c"aGGDJJ{+d23 #" #"s   )C
Cc                    [         R                  5       (       d  gUR                  SS5      nUR                  SS5      nUR                  S[        R                  " 5       R                  S5      5      nSU S	U S
U S3n[        [         SSS9 nUR                  5       nSSS5        SnUW;   ap  UR                  U5      [        U5      -   S-   n	XyS R                  S5      n
USU	 S-   U-   S-   XyS -   n[        [         SSS9 nUR                  U5        SSS5        gg! , (       d  f       N= f! , (       d  f       g= f)zt
Update the TITAN MEMORY section in CLAUDE.md with high-severity learnings.
Only called for high/critical failures.
Nr8   systemrQ   r   r5   r6   z- **z**: z ()rzutf-8)encodingz### Recent Learningsr*   r   w)CLAUDE_MD_PATHexistsrK   r   rA   rB   r   readindexlensplitr   )r"   r'   learning_taglearning_textdate_strnew_learningr   contenttarget
insert_poslinesupdateds               r#   r_   $EvolutionEngine._update_titan_memory4  sF   
 $$&&{{9h7$57MN;;vx||~'>'>z'JKl^4b
!L.#8AffhG 9 (W v.V<q@JK(..t4E $  +&	'  ncG<  =<  98" =<s   D D1 
D.1
D?eventsc                     / nU H7  nU R                  U5      nU[        :  d  M   UR                  0 UESU0E5        M9     U$ )zy
RLM Worker pattern: scan recent events for surprise patterns.
Returns events with surprise_score >= SURPRISE_THRESHOLD.
r=   )rE   SURPRISE_THRESHOLDappend)r"   r   	surpriseseventscores        r#   scan_for_surprises"EvolutionEngine.scan_for_surprisesU  sP    
 	E((/E**  !CE!C+;U!CD  r&   c                     Sn[         R                  5       (       a+  [        [         S5       n[        S U 5       5      nSSS5        U R                  U R
                  U[        [        S.$ ! , (       d  f       N2= f)zReturn engine statistics.r   r   c              3   R   #    U  H  oR                  5       (       d  M  S v   M     g7f)r*   N)strip)rf   lines     r#   rh   ,EvolutionEngine.get_stats.<locals>.<genexpr>f  s     #D!$zz|AA!s   '	'N)failures_processed_this_sessionaxioms_generated_this_sessiontotal_failures_in_logsurprise_thresholdhigh_stakes_domains)r   r   r   sumr    r!   r   rv   )r"   failure_countr   s      r#   	get_statsEvolutionEngine.get_statsa  sh    ""$$&, ##D!#D D - 04/F/F-1-B-B%2"4#6
 	
 -,s   A++
A9)r!   r    N)__name__
__module____qualname____firstlineno____doc__r$   r   strr   r0   r+   r,   r-   r.   rD   floatrE   rM   r   rN   rS   rT   r]   r[   r\   r^   r_   r   r  __static_attributes__re   r&   r#   r   r   =   sq   "tCH~ $sCx. 2t   $ 
 
 
/T / t  t  &Uc Uc U*
S 
c 
d3i 
_c _s _s _(C C 
t 
 
0$ 0
/ /,#s #T # !D !B
d 
T
 

4 
r&   r   __main__zGenesis Evolution Engine)descriptionz	--failurezFailure description to process)typehelpz	--projectr   z
Project ID)r  defaultr  z--taskr   zTask IDz--stats
store_truezShow engine stats)actionr     )indent)r8   r:   r;   z 
Axiom written. Genesis evolves.zTUsage: python evolution_engine.py --failure 'description' [--project id] [--task id]z)       python evolution_engine.py --stats)(r  r   r@   sysrer   pathlibr   typingr   r   r   r   GENESIS_ROOTr   r   r   r   GLOBAL_RULES_PATHr   rv   r   r  argparseArgumentParserparseradd_argumentr  
parse_argsargsenginestatsprintr   r  r'   r0   r8   r:   resultre   r&   r#   <module>r.     s  B   
 	   , , '("33j@  11H<#&CC + 9,w69RR    q
 q
h	 z$$1KLF
#4TU
#y|T
sH9M
	,=PQDFzzdjj))+A67	''||IILL)
 
 	djj*+13de9:1 r&   