
    UHjE                       d Z ddlmZ ddlZddlZddlZddlZddlZddlm	Z	 ddl
mZ ej                  j                  d e e	e      j!                         j"                               ddlmZmZ  e	e      j!                         j*                  d   Zedz  Zd	Zd
Zg dZg dZdddddddddgZd&dZd&dZd'dZd(dZ d)dZ!d*dZ"d+dZ#d,dZ$d-dZ%d.dZ&d/dZ'd0dZ(d1d Z)d2d!Z*d2d"Z+efd3d#Z,d4d$Z-e.d%k(  r e-        yy)5zPSummarize script-local sources for the gate offsets before the current frontier.    )annotationsN)Path)Any)read_sectionsva_to_offset   outmap1_01amap2_02d)zscript-local-gate-byte-writerzglobal-script-gate-byte-writerz(runtime-inherited-selection-buffer-statezcontrol-path-fallthrough-proof)zRopcode 0x12/0x13 writer to selectionBuffer[0xe8] or [0xea] before the current gatezHruntime sample showing inherited gate bytes on the current selector pathzHcontrol-flow proof that the gate fallthrough reaches the frontier readerzUstrict hotspot or selected-root context tying the fallthrough to map1_01a -> map2_02dHwanse2.exezGdword-aligned save-selector script scan for gate-offset readers/writers)pathdescriptionzout/save_scene_selectors.jsonz@selector root ranges used to isolate the current 2:0 script rootz.out/save_selector_branch_gate_consistency.jsonzRnearest current writer/frontier reader gate rows that define offsets 0xe8 and 0xeac                    d| dS )N0x08x values    H/home/exedev/hwanse/tools/summarize_save_selector_gate_offset_sources.pyhex32r   2       c{    c                    d| dS )Nr   02xr   r   s    r   hex8r   6   r   r   c                p    | j                         s|S t        j                  | j                  d            S )Nutf-8encoding)existsjsonloads	read_text)r   fallbacks     r   	load_jsonr%   :   s*    ;;=::dnngn677r   c                V    | D ]  }|j                  d      dk(  s|c S  t        d      )Nnamez.dataz Hwanse2.exe has no .data section)get
ValueError)sectionssections     r   data_sectionr,   @   s5     ;;v')N 7
88r   c                v    t        ||      }||dz   t        |       kD  ry t        j                  d| |      d   S )N   <Ir   )r   lenstructunpack_from)exer*   vaoffsets       r   dword_atr6   G   s?    (B'F~!c#h.dC033r   c                0    dddddj                  | d      S )NfillBranchStateTablereadSelectedStateAndBranchselectActiveStateSlotselectMatchingRuntimeSlot)            other)r(   )opcodes    r   operation_for_opcoderB   N   s&    $*%)	
 
c&'r   c                    | dk(  rdS dS )Nr   primaryBranchStatesecondaryBranchStater   )stream_plus_1s    r   state_tablerG   W   s    #0A#5Q;QQr   c                    |dz  }|dvry |dz	  dz  }|dz	  dz  }| t        |       |t        |      |t        |      t        |      t        |      t        |      |t        |      |dv |dk(  d}|dk(  r|dk  |d	<   |S )
N   >   r<   r=   r>   r?      r<   >   r>   r?   r=   )r4   vaHexr   valueHexrA   	opcodeHex	operation
stateTablestreamPlus1HexselectionBufferOffsetselectionBufferOffsetHexwritesSelectionBufferreadsSelectionBuffer   validHelperDispatch)r   r   rB   rG   )r4   r   rA   rF   stream_plus_2rows         r   
decode_rowrY   [   s    T\F--aZ4'Mb[D(Mr%L&\)&1!-0}-!.$($7!'<!7 &$C ~%2d%:!"Jr   c           
        d }| d| }| D ]>  }|j                  d      |k(  s|j                  d      |k(  s-|j                  d      } n t        |t              st        d|       t	        | D ch c]'  }t        |j                  d      t              s#|d   ) c}      }|D cg c]
  }||kD  s	| }}||r|d   |fS |dz   |fS c c}w c c}w )N:groupslotselectedPointerzmissing selector r   i @  )r(   
isinstanceintr)   sorted)		selectorsr\   r]   selectedlabelrX   rootsroot
next_rootss	            r   selector_root_rangerh   u   s    HgQtfE 777u$D)@ww01H h$,UG455ios:cggVgNhjmCnC)*opE#(<4D8O$<J<jZ]NNh6GNN p<s   4$CC+
C6Cc                   t        |      }g }t        |d   |d   |d   z   dz
  d      D ]R  }t        j                  d| |      d   }|d   |z   |d   z
  }t	        ||      }|s:|d   |v sB|j                  |       T |S )	Nrawraw_size   r.   r/   r   r4   rQ   )r,   ranger1   r2   rY   append)	r3   r*   offsetsr+   rowsfile_offsetr   r4   rX   s	            r   scan_data_rowsrr      s    8$GDWU^WU^gj>Q-QTU-UWXY ""4k:1=T][(75>9U#3./7:KK Kr   c                   |D cg c]  }|d   | k(  s| }}|D cg c]  }||d   cxk  r|k  sn n| }}|D cg c]  }|d   |k  s| }}|D cg c]
  }|d   s	| }	}|D cg c]
  }|d   s	| }
}|D cg c]
  }|d   s	| }}i dt        |      d| dt        |       dt        |      dt        d |D              d	t        |	      d
t        d |D              dt        |      dt        d |D              dt        |
      dt        |      dt        |      d|d|d|d d dt	        |      dt	        |	      d|rdiS |	rdiS diS c c}w c c}w c c}w c c}w c c}w c c}w )NrQ   r4   rS   	gateVaHexrR   globalRowCountglobalReaderCountc              3  ,   K   | ]  }|d    s	d  ywrT   r   Nr   .0rX   s     r   	<genexpr>z!summarize_gate.<locals>.<genexpr>   s      YsSAW=X Y   
globalWriterCountglobalFillLikeCountc              3  2   K   | ]  }|d    dk(  sd  yw)rA   r<   r   Nr   ry   s     r   r{   z!summarize_gate.<locals>.<genexpr>   s     "Us8}PT?T1"Us   currentRootRowCountcurrentRootReaderCountc              3  ,   K   | ]  }|d    s	d  ywrx   r   ry   s     r   r{   z!summarize_gate.<locals>.<genexpr>   s     %\CDZ@[a%\r|   currentRootWriterCountcurrentRootRowsBeforeGateCount currentRootWriterBeforeGateCountcurrentRootRowscurrentRootRowsBeforeGateglobalSamples   scriptLocalSelectionWriterFound globalScriptSelectionWriterFoundsourceClassificationzscript-local writerz)global script writer outside current rootzJno opcode 0x12/0x13 script writer; inherited/runtime selection-buffer byte)r   r   r0   sumbool)r5   gate_varp   
root_startroot_endrX   global_rows	root_rowsroot_rows_before_gateglobal_writersroot_writersroot_writers_before_gates               r   summarize_gater      s.   "&Q3#.E*F&*P3QKQ +RzSY/Q/QRIR,5MSTW9LSMM%0QcC8O4PcQNQ#,MC4K0LCMLM/DeLcHdeeU7^ 	#DL 	#k*	
 	S Yk YY 	S0 	s"U"UU 	s9~ 	!#%\9%\"\ 	!#l"3 	)#.C*D 	+C0H,I 	9 	$%: 	Sb)  	*40H+I!" 	+D,@#$ 	' "' ,  =+ . ^/  RRMQMesC   E#E#E(E(E-E-
E2!E2+
E76E7 
E<E<c                   g }| j                  d      xs g D ]i  }|j                  d      dk7  rt        |d   d      }|j                  d      }t        |t              st        |d   d      }|j                  ||f       k |S )NselectionOpcodeRowsBetweenrM   0x11rK   r<   rQ   rR   )r(   r`   r_   rn   )gate_consistencyrp   rX   r4   r5   s        r   gate_offsets_from_consistencyr      s    D##$@AGR "77;6)Wr"01&#&78"=FVRL!" Kr   c                   t        |       }t        |dd      \  }}}t        |      }|D 	ch c]  \  }}	|	 }
}}	t        | ||
      }|D cg c]  \  }}t	        |||||       }}}t        d |D              }t        d |D              }d}i dt        dt        d|d	t        |      d
t        |       dt        |       dt        |      d|D 	cg c]  \  }}	t        |       c}	}d|d|dddddddddt        dt        dt        dt        t              d||dS c c}	}w c c}}w c c}	}w )N   r   c              3  &   K   | ]	  }|d      yw)r   Nr   ry   s     r   r{   z build_summary.<locals>.<genexpr>   s     !^S#&G"H!^   c              3  &   K   | ]	  }|d      yw)r   Nr   ry   s     r   r{   z build_summary.<locals>.<genexpr>   s     YC BCYr   a  The control gates before the current frontier reader use selectionBuffer offsets 0xe8 and 0xea, but the dword-aligned save-selector script scan finds no opcode 0x12/0x13 writer for either offset globally or inside the current 2:0 root. In the current root these offsets appear only as reader gates. That means the fallthrough path depends on inherited/runtime selection-buffer bytes rather than a script-local setup in this root, so control-flow proof remains open.sourcetargetselectorrootHexrootRangeHexz..	gateCountgateOffsetsHexanyScriptLocalSelectionWriteranyGlobalScriptSelectionWritercontrolPathGateStatuszinherited-runtime-statecontrolPathProofStatusblocked
proofFoundFgateOffsetSourceProofFoundfailedGateOffsetSourceGateIdsmissingEvidenceevidenceRefsevidenceRefCount)promotionStatusgates
conclusion)r   rh   r   rr   r   anySOURCETARGETr   r0   r   "FAILED_GATE_OFFSET_SOURCE_GATE_IDS#GATE_OFFSET_SOURCE_MISSING_EVIDENCE GATE_OFFSET_SOURCE_EVIDENCE_REFS)r3   rb   r   r*   r   r   r   r   r5   _varo   rp   r   	gate_rowsany_script_local_writerany_global_writerr   s                    r   build_summaryr      s   S!H%8Aq%I"J()*:;E)./+&#v/G/#x1D  %FG 	vwj(CI  "!^T]!^^YyYY	O && 	H 	5$	
 	5,-Rh/@A 	S^ 	5AKFC4<A 	()@ 	)*; 	 !: 	!) 	e 	%e 	()K 	>  	8!" 	C @A#$ % )  0( Bs   D1D7D=
c                0   ddd| d    d| d    d| d    d	| d
    d| d    dddj                  d | d   D               d| d    d| d    d| d    dd| d    dd| d    dd| d    dd| d     dd| d!   dd"dg}|j                  d# | d$   D               |j                  g d%       |j                  d& | d'   D               |j                  g d(       |j                  d) | d*   D               |j                  g d+       | d,   D ]>  }|j                  d-|d.    d/|d0    d1|d2    d3|d4    d3|d5    d3|d6    d3|d7    d8       @ |j                  g d9       | d,   D ]  }|j                  d:|d.    d;|d0    ddd<d=g       |d>   D ]H  }|j                  d-|d?    d/|d@    d/|dA    d1|dB    d3|dC    d3|dD   t        |d.   dE      k   d8       J |d>   s|j                  dF       |j                  d        dGj                  |      S )HNz## Save Selector Gate Offset Sources z	- route: r   z -> r   z- selector: `r   z` root `r   z` (`r   z`)z- gate offsets: , c              3  (   K   | ]
  }d | d   yw)`Nr   rz   items     r   r{   zmarkdown.<locals>.<genexpr>   s     $WTqa[$W   r   z%- any script-local selection writer: r   z&- any global script selection writer: r   z- control path gate status: `r   r   z- control path proof status: `r   z- proofFound: `r   z- gateOffsetSourceProofFound: `r   z- promotion status: `r   r   z## Failed Gatesc              3  (   K   | ]
  }d | d  yw)- `r   Nr   r   s     r   r{   zmarkdown.<locals>.<genexpr>   s     T43tfATr   r   )r   z## Missing Evidencer   c              3  &   K   | ]	  }d |   yw)z- Nr   r   s     r   r{   zmarkdown.<locals>.<genexpr>  s     D2dVDr   r   )r   z## Evidence Refsr   c              3  8   K   | ]  }d |d    d|d      yw)r   r   z`: r   Nr   ry   s     r   r{   zmarkdown.<locals>.<genexpr>
  s/       c&k]#c-012s   r   )r   z## Gatesr   zc| gate | offset | root rows | root writers before gate | global readers | global writers | source |z/| --- | --- | ---: | ---: | ---: | ---: | --- |r   z| `rt   z` | `rR   z` | r   z | r   rv   r}   r   z |)r   z## Current Root Rowsr   z
### Gate `z
` offset `z6| va | value | op | operation | table | before gate? |z%| --- | --- | --- | --- | --- | --- |r   rK   rL   rM   rN   rO   r4   r<   z| - | - | - | - | - | - |
)joinextendrn   r`   )summarylinesgaterX   s       r   markdownr      s5   -

GH%&d78+<*=>

+,HWY5G4HWUcMdLeegh
499$WWEU=V$WWXY
/8W0X/YZ
09Y1Z0[\
'0G(H'IK
(1I)J(K1M
',/02
)'2N*O)PPQR
(9 :;1=


#E& 
LLT73R+STT	LL  
 
LLD1B)CDD	LL  
 
LL >*  
LL     
${#$E$/I*J)K4)*+3t4V/W.XX['()T2E-F,Gs*+,B0	

 
LL12  k*+:d;U6V5WWXYD3	
 	 )* 	CLLc'l^5Z(9s;?O>PPT{#$CL(9':#c$i#dS^N_acJd>d=eegi	
 %&LL45R 99Ur   c                N   g }g }dj                  d | d   D              }dj                  d | d   D              }dj                  d | d   D              }| d   D ]u  }|j                  d	t        j                  |d
          dt        j                  |d          d|d    d|d    d|d    d|d    dt        j                  |d          d       g }t	        |d
   d      }|d   D ]  }	|j                  d	t        j                  |	d          dt        j                  |	d          dt        j                  |	d          dt        j                  |	d          dt        j                  |	d          d|	d   |k   d        |j                  dt        j                  |d
          dt        j                  |d          dd g|d!       x d"j                  g d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7t        j                  | d8          d9t        j                  | d:          d;t        j                  | d<          d=t        j                  | d>          d?	d@t        j                  dAj                  | dB                dC| dD    dE| dF    dGt        j                  | dH          dI| dJ    dKt        j                  | dL          d?dMt        j                  | dN          dOdPdQ| dRdSdQ| dRdTdQ| dRdUdV|dW|dXdYd      S )ZNr   c              3  N   K   | ]  }d t        j                  |       d  yw)
<li><code>z</code></li>Nhtmlescaper   s     r   r{   zhtml_page.<locals>.<genexpr>2  s+       T[[&'|4   #%r   c              3  N   K   | ]  }d t        j                  |       d  yw)z<li></li>Nr   r   s     r   r{   zhtml_page.<locals>.<genexpr>6  s+       t{{4 !'r   r   c              3     K   | ]9  }d t        j                  |d          dt        j                  |d          d ; yw)r   r   z	</code>: r   r   Nr   ry   s     r   r{   zhtml_page.<locals>.<genexpr>:  sE       T[[V-.iCDV8W7XX]^s   ?Ar   r   z<tr><td><code>rt   z</code></td><td><code>rR   z</code></td><td>r   z	</td><td>r   rv   r}   r   z
</td></tr>r<   r   rK   rL   rM   rN   rO   r4   z<h2>Gate <code>z</code> Offset <code>z</code></h2>z<table><thead><tr><th>va</th><th>value</th><th>op</th><th>operation</th><th>table</th><th>before gate?</th></tr></thead><tbody>z</tbody></table>r   z<!doctype html>z<html lang="en">z<head>z  <meta charset="utf-8">zF  <meta name="viewport" content="width=device-width, initial-scale=1">z2  <title>Save Selector Gate Offset Sources</title>z	  <style>zg    :root { color-scheme: dark; font-family: system-ui, sans-serif; background: #101010; color: #eee; }z&    body { margin: 0; padding: 24px; }z,    h1 { margin: 0 0 8px; font-size: 24px; }z/    h2 { margin: 24px 0 8px; font-size: 18px; }z<    p { max-width: 1120px; color: #bbb; line-height: 1.45; }z[    table { width: 100%; border-collapse: collapse; margin: 12px 0 20px; font-size: 13px; }zi    th, td { border-bottom: 1px solid #303030; padding: 7px 8px; text-align: left; vertical-align: top; }zF    th { position: sticky; top: 0; background: #181818; color: #ddd; }z    code { color: #d7f0ff; }z
  </style>z</head>z<body>z,  <h1>Save Selector Gate Offset Sources</h1>z  <p>route <code>r   z</code> -&gt; <code>r   z</code>; selector <code>r   z</code>; root <code>r   z</code>.</p>z  <p>gate offsets: r   r   z%; any script-local selection writer: r   z&; any global script selection writer: r   z"; control path gate status: <code>r   z</code>; proofFound <code>r   z!</code>; promotion status: <code>r   z  <p>r   z</p>z  <h2>Failed Gates</h2>z  <ul>z</ul>z  <h2>Missing Evidence</h2>z  <h2>Evidence Refs</h2>z  <h2>Gates</h2>z  <table><thead><tr><th>gate</th><th>offset</th><th>root rows</th><th>root writers before gate</th><th>global readers</th><th>global writers</th><th>source</th></tr></thead><tbody>z  </tbody></table>z</body>z</html>)r   rn   r   r   r`   r   )
r   r   detail_partsfailed_gatesmissing_evidenceevidence_refsr   rp   r   rX   s
             r   	html_pager   /  s
   IL77 ;< L ww -.  GG >* M   T+%678 9T*D%EFG H-./ 0:;< =+,- .+,- .;;t$:;<= >
	
 d;',)* 
	CKK![[W67 8![[Z9: ;![[[)9:; <{{3{#345 6{{3|#456 74y7*+ ,	
	 	dkk${*;<==RSWS^S^_cd~_  TA  SB  BN  O N
 
 	
 	3> 99 &&& 	& 	#	&
 	Q& 	=& 	& 	r& 	1& 	7& 	:& 	G& 	f& 	t& 	Q&  	'!&" 	#&$ 	%&& 	'&( 	7)&* DKK(9:;;OPTP[P[\cdl\mPnOo  pH  IM  IT  IT  U\  ]g  Uh  Ii  Hj  j~  C  J  J  KR  Sa  Kb  c  ~d  dp  	q+&, dkk$))G<L4M*NOPPuv}  ^  w_  v`  `F  GN  Oo  Gp  Fq  qS  TX  T_  T_  `g  h  `@  TA  SB  B\  ]d  eq  ]r  \s  sT  UY  U`  U`  ah  iz  a{  U|  T}  }I  	J-&. GL12348/&0 	"1&2 e$3&4 	&5&6 !"%(7&8 	#9&: u%;&< 	=&> 	?&@ 
A&B 	C&D 
E&F 	G&H 	I&J 	K& & &r   c                    |j                  dd       |dz  j                  t        j                  | dd      dz   d	       |d
z  j                  t	        |       d	       y )NT)parentsexist_okz&save_selector_gate_offset_sources.jsonFr   )ensure_asciiindentr   r   r   &save_selector_gate_offset_sources.html)mkdir
write_textr!   dumpsr   )r   out_dirs     r   write_outputsr     se    MM$M.77CC

7q9D@ D  77CCIgDVahCir   c                 F   t        j                  t              } | j                  dt        t
        dz         | j                  dt        t        dz         | j                  dt        t        dz         | j                  d	t        t               | j                         }t        |j                  j                         t        |j                  g       t        |j                  i             }t        ||j                         t!        d
|j                  dz          y )N)r   z--exer   )typedefaultz--selectorszsave_scene_selectors.jsonz--gate-consistencyz*save_selector_branch_gate_consistency.jsonz	--out-dirz+wrote save selector gate offset sources -> r   )argparseArgumentParser__doc__add_argumentr   ROOTOUT
parse_argsr   r3   
read_bytesr%   rb   r   r   r   print)parserargsr   s      r   mainr     s    $$9F
dD=4HI
D#@[:[\
,4GsAst
$<D$.."%$'',G
 '4<<(	7Go8o7p
qrr   __main__)r   r`   returnstr)r   r   r$   r   r   r   )r*   
list[dict]r   dict)r3   bytesr*   r  r4   r`   r   z
int | None)rA   r`   r   r  )rF   r`   r   r  )r4   r`   r   r`   r   zdict | None)rb   r  r\   r`   r]   r`   r   ztuple[int, int, str])r3   r  r*   r  ro   zset[int]r   r  )r5   r`   r   r`   rp   r  r   r`   r   r`   r   r  )r   r  r   zlist[tuple[int, int]])r3   r  rb   r  r   r  r   r  )r   r  r   r  )r   r  r   r   r   None)r   r  )/r   
__future__r   r   r   r!   r1   syspathlibr   typingr   r   insertr  __file__resolveparentprobe_exe_scene_tablesr   r   r   r   r   r   r   r   r   r   r   r   r%   r,   r6   rB   rG   rY   rh   rr   r   r   r   r   r   r   r   __name__r   r   r   <module>r     s7   V "     
   3tH~--/667 8 > H~''*
Ul		& "' # `
 0Y
 Ak$   894R4O	 F
(VBJTn 25 js  zF r   