
    3j_                    v   d Z ddlmZ ddlZddlZddlmZmZ ddlm	Z	m
Z
mZmZmZ ddlmZmZmZmZ ddlmZmZmZmZmZmZmZ dZd	Zd
ZdZdZdZ dZ! e"ee e!h      Z#dZ$dZ%dZ&dZ'dZ(dZ)dZ*e	e+e
e+e,f   gdf   Z-d"dZ.d#dZ/e G d d             Z0e G d d             Z1 G d d      Z2dd	 	 	 	 	 d$d Z3g d!Z4y)%u	  anu_v3.runtime_event_enactor — bounded enactor for the +54 runtime-event
loop proposal candidates (task-2553+55, 회장 결정).

회장 §1 verbatim: "자동 loop 가 proposal 생성까지 완성됐고, 다음 단계는
proposal candidate 를 안전 조건 안에서 enact 하는 bounded enactor."

The +54 ``RuntimeEventLoop`` interprets the durable registry as progress
events and emits *proposal candidates only* (zero authority). This module is
the bounded enactor that consumes those candidates and, within strict safety
conditions, enacts ONLY what it is authorized to (회장 §2 1~10):

  1. input  = a +54 runtime-event-loop result (envelope or inner result).
  2. type   = consolidated_summary · closeout_candidate ·
              next_dispatch_candidate · hold_packet
              (``anu_v3.proposal_authorization_gate``).
  3. enact  = ONLY authorized actions.
  4. else   = the proposal is retained as a proposal (no enact).
  5. closeout = an ADDITIVE artifact ONLY (a brand-new file; zero
              modification of any existing artifact; zero merge/PR/branch).
  6. next dispatch = candidate->actual dispatch promotion ONLY on the §2.6
              triple AND an explicit chair grant (verify-only here — Track
              B never promotes; 회장 §3.B/§8/§10).
  7. merge / PR / credential / branch-write = BLOCKED by default.
  8. every enact decision is recorded in an enactor-result JSON.
  9. re-processing the same proposal is idempotent
              (``anu_v3.enactor_idempotency``).
  10. using a dead-man / fixed-time / fallback source as the progress
              trigger is a hard FAIL.

Track boundary (회장 §3):

  * Track A (final consolidated closeout) -> actually ENACTED here, as an
    ADDITIVE artifact only.
  * Track B (next_dispatch_candidate safety gate) -> verified ONLY.
  * Track C (hold_packet routing) -> verified ONLY.

Authority boundary: the enactor performs ZERO merge / PR / branch / main
write / credential op / cron register / dispatch / subprocess / cokacdir.
The ONLY side effect it is permitted is an *additive* artifact create, and
even that is delegated to an injected, allowlist-gated ``artifact_writer``
(the module never opens a file for write itself — pure core + injected
sink, fully testable with a tmp writer).

Layer A / NO-CRON.
    )annotationsN)	dataclassfield)CallableDictListOptionalSequence)IDEMPOTENT_BINDING_CONFLICTIDEMPOTENT_SKIPalready_enactedenact_id)ACTION_BLOCKEDACTION_DISPATCH_READYACTION_ENACT_ADDITIVEACTION_HOLD_ROUTEDPROPOSAL_CLOSEOUT_CANDIDATEPROPOSAL_CONSOLIDATED_SUMMARYauthorize_proposalzanu_v3.runtime_event_enactor.v1zruntime_event_enactor_result.v1z(task-2553.final-consolidated-closeout.v1registry_completed_eventfixed_time_gatedead_man_fallbackfallback_progressz?memory/events/task-2553.final-consolidated-closeout_260518.jsonnoneENACTEDr   	NO_ACTIONFORBIDDEN_TRIGGER_SOURCEHOLD_FOR_CHAIRc                    t        j                  t        j                  | ddd      j	                  d            j                         S )NFT),:)ensure_ascii	sort_keys
separatorszutf-8)hashlibsha256jsondumpsencode	hexdigest)values    3/home/jay/workspace/anu_v3/runtime_event_enactor.py_shar-   g   s:    >>

*	

&/ ik	    c                t    | j                  d      }t        |t              r|j                  d      dk(  r|S | S )zAccept either the +54 envelope (``...runtime-event-loop-result.v1``
    with a nested ``result``) or the inner ``runtime_event_loop_result.v1``.
    resultschemazruntime_event_loop_result.v1)get
isinstancedict)loop_resultinners     r,   _unwrap_loop_resultr7   o   s<     OOH%E%599X#6&$ r.   c                      e Zd ZU ded<   ded<   ded<   ded<   ded<   ded<   d	ed
<   d	ed<   ded<   ded<    ee      Zded<   ddZy)EnactionRecordstrproposal_typeaction	source_idbool
authorizedenactedidempotent_skipOptional[str]artifact_targetr   Dict[str, object]decisionzOptional[Dict[str, object]]idempotencydefault_factory	List[str]reasonsc                   | j                   | j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                  t        | j                        dS )Nr;   r<   r=   r?   r@   rA   rC   r   rE   rF   rJ   )r;   r<   r=   r?   r@   rA   rC   r   rE   rF   listrJ   selfs    r,   to_jsonzEnactionRecord.to_json   sf    !//kk//||#33#33++DLL)
 	
r.   NreturnrD   )__name__
__module____qualname____annotations__r   rM   rJ   rP    r.   r,   r9   r9   {   sO    KNM"",,t4GY4
r.   r9   c                      e Zd ZU ded<   ded<   ded<   ded<   ded<   ded	<   ded
<   ded<   ded<   ded<   ded<   ded<   ded<   ded<   ded<   ded<   ded<   ded<    ee      Zded<   edd       ZddZ	y) EnactorResultr:   r1   generated_at_kstverdictrB   progress_triggerr>   fixed_time_useddead_man_usedfallback_used	authorityloop_result_sha256intproposals_totalenacted_countidempotent_skip_countdispatch_ready_countblocked_counthold_routed_countList[Dict[str, object]]recordsadditive_artifactshold_for_chairrG   rI   rJ   c                2    | j                   t        t        fvS N)r[   ENACTOR_FORBIDDEN_TRIGGERENACTOR_HOLD_FOR_CHAIRrN   s    r,   okzEnactorResult.ok   s    ||%"$
 
 	
r.   c                ,   i d| j                   d| j                  d| j                  d| j                  d| j                  d| j
                  d| j                  d| j                  d	d
ddd| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  t        | j                         t        | j"                        | j$                  t        | j&                        dS )Nr1   rZ   r[   r\   r]   r^   r_   r`   auto_executedFmerge_pr_branch_credentialblockedra   rc   rd   re   rf   rg   rh   )rj   rk   rl   rJ   )r1   rZ   r[   r\   r]   r^   r_   r`   ra   rc   rd   re   rf   rg   rh   rM   rj   rk   rl   rJ   rN   s    r,   rP   zEnactorResult.to_json   s^   
dkk
 5 5
 t||
  5 5	

 t33
 T//
 T//
 
 U
 ))
 !$"9"9
 t33
 T//
 $T%?%?
 #D$=$=
  T//!
"  !7!7#
$ DLL)"&t'>'>"?"11DLL)+
 	
r.   N)rR   r>   rQ   )
rS   rT   rU   rV   r   rM   rJ   propertyrq   rP   rW   r.   r,   rY   rY      s    KL##N$$//t4GY4
 

r.   rY   c                      e Zd ZdZddd	 	 	 	 	 	 	 ddZ	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 	 ddZedd	edd
	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	y	)RuntimeEventEnactorzBounded enactor over +54 proposal candidates (read-mostly; the only
    side effect is an injected, allowlist-gated *additive* artifact write).
     z/home/jay/workspace)executor_self_keyworkspace_rootc               N    t        d |D              | _        || _        || _        y )Nc              3  &   K   | ]	  }|s|  y wrn   rW   ).0ks     r,   	<genexpr>z/RuntimeEventEnactor.__init__.<locals>.<genexpr>   s     7AQa7s   )tupleanu_keysrz   r{   )rO   r   rz   r{   s       r,   __init__zRuntimeEventEnactor.__init__   s&     777!2,r.   c                    g }dD ]M  }|j                  |      }t        |t              s%|D ]$  }t        |t              s|j	                  |       & O |S )N)consolidated_summary_candidatesdispatch_candidatesquarantined_events)r2   r3   rM   r4   append)rO   r6   outkeyseqitems         r,   _collect_candidatesz'RuntimeEventEnactor._collect_candidates   s_     (*
 		)C
 ))C.C#t$ )D!$-

4()		) 
r.   c               .   t         ||t        ddddd|j                  d      |j                  d      |j                  d      |j                  d	      |j                  d
      |j                  d      d||j                  d      xs g dddddddddddS )u^  Construct the ADDITIVE final-consolidated-closeout artifact.

        It is a brand-new, self-describing file: it carries the ``enact_id``
        (for idempotency), the consolidated batch identity, the source loop
        sha, and an explicit authority boundary. It NEVER references or
        mutates any existing artifact (회장 §2.5/§3.A/§8).enacted_additive_artifact_onlyFru   z	task-2553z*task-2553+55 bounded runtime-event enactorr1   statusbatch_idall_settledall_authoritative_passgenerated_basis)r1   r   r   r   r   r   track_statesFINAL_CONSOLIDATED_CLOSEOUTCLOSED_OUT_ADDITIVEz+54 runtime-event-loop consolidated_summary_candidate (all-settled & all-AUTHORITATIVE_PASS) enacted by the +55 bounded enactor as an additive artifact only.)kindr   basismergeprbranch_writecredential_opdispatchu   ADDITIVE ARTIFACT ONLY — this is a newly created closeout record. Zero existing artifact was modified; zero merge / PR / branch / main write / credential op / dispatch was performed (회장 §2.5/§3.A/§6/§8).)r1   r   rZ   r`   action_moders   rt   taskproduced_bysource_proposalsource_loop_result_sha256consolidated_track_statescloseoutnote)CLOSEOUT_ARTIFACT_SCHEMAAUTHORITY_NONEr2   )rO   eidrZ   summaryloop_shas        r,   _build_closeout_artifactz,RuntimeEventEnactor._build_closeout_artifact   s     / 0';"*3G!++h/!++h/#KK
3&{{=9*1++,+ $+;;/@#A	  *2)0^)D)J5/H  %!&!:K*
 *	
r.   FN)progress_trigger_sourceallow_actual_dispatchartifact_writercloseout_targetrZ   c               \
   g }t        |      }|t        v r|j                  d|dt        d       t	        d6i dt
        d|dt        ddd	|t        k(  d
|t        k(  d|t        k(  dt        d|dddddddddddddg dg ddd|S t        |      }	| j                  |	      }
g }g }dx}x}x}x}}d}t               }|
D ]  }t        || j                  | j                   |      }|j#                         }t%        |j&                  |j(                  |j*                  |j,                  dddd|dt/        |j0                              }|j(                  t2        k(  rP|j&                  t4        t6        fv r7|j9                  d      }t;        |t<              r|ni }t?        |j9                  d      xs |j9                  d      xs d      }tA        |j9                  d             xs tA        |j9                  d             }tC        d!|||g|"      }||_!        ||_"        ||v rJd#|_#        |d$z  }d%||d&d|d'gd(|_$        |j0                  j                  d)       |j                  |       |jK                  |       tM        ||| jN                  *      }|j#                         |_$        |jP                  tR        k(  rd#}|j0                  j                  d+       n|jP                  tT        k(  r)d#|_#        |d$z  }|j0                  j                  d,       nI| jW                  ||||-      }|1 |||       d#|_,        |d$z  }|j0                  j                  d.       n|j0                  j                  d/       |j                  |||jX                  |jF                  s|ndd0       n|j(                  tZ        k(  r!|d$z  }|j0                  j                  d1       n|j(                  t\        k(  r!|d$z  }|j0                  j                  d2       nO|j(                  t^        k(  r!|d$z  }|j0                  j                  d3       n|j0                  j                  d4       |j                  |        |rt`        }n|rtb        }n|rtd        }ntf        }|j                  d5       t	        d6i dt
        d|d|dt        d	dd
ddddt        d|dti        |
      d|d|d|d|d|d|D cg c]  }|j#                          c}d|d|d|S c c}w )7u  Consume +54 proposal candidates and enact only the authorized
        bounded actions (회장 §2 1~10).

        ``artifact_writer`` (optional) is the injected allowlist-gated
        additive sink. When omitted, the enactor still computes every
        decision + the would-be artifact + idempotency, but performs ZERO
        write (dry, fully deterministic). Track A actual enact requires the
        writer to be supplied by the allowlisted runner.
        zprogress_trigger_source=u    is a dead-man / fixed-time / fallback class trigger — FORBIDDEN as a progress trigger; the bounded enactor refuses to enact. Only u_    (a durable-registry append/update consumed by +54) drives progress (회장 §2.10/§6, reg 6).r1   rZ   r[   r\   Nr]   r^   r_   r`   ra   rc   r   rd   re   rf   rg   rh   rj   rk   rl   FrJ   )r   rz   r   rL   gate_evidencer   r=   ry   r   final_consolidated_closeout)r;   r=   settle_identityrC   T   zanu_v3.enactor_idempotency.v1r   u   same closeout already enacted earlier in THIS run (consolidated_summary + closeout candidate of one batch) — idempotent skip, no second write (회장 §2.9, reg 2).)r1   r   rC   classificationshould_writeexisting_enact_idrJ   uc   in-run duplicate of the same final consolidated closeout — idempotent skip (회장 §2.9, reg 2).)r   rC   r{   u   additive closeout path already bound to a DIFFERENT enact_id — never overwritten; escalated to HOLD (회장 §7 registry/binding mismatch).ud   same proposal re-processed — idempotent skip; additive artifact left byte-0 (회장 §2.9, reg 2).)r   rZ   r   r   u   Track A — final consolidated closeout ENACTED as an ADDITIVE artifact (new file; zero modification of any existing artifact; zero merge/PR/branch; 회장 §2.5/§3.A/§8, reg 1/7).u   Track A authorized & deterministic artifact computed, but no allowlisted artifact_writer injected — DRY (zero write). The allowlisted runner supplies the writer for the real enact.)targetr   writtenartifactu{   Track B — §2.6 triple PASSED -> DISPATCH-READY; verify-only, NO actual dispatch executed (회장 §3.B/§8/§10, reg 4).u_   merge/PR/credential/branch target -> BLOCKED; retained as a proposal (회장 §2.7/§6, reg 5).ul   Track C — hold_packet routed to the independent-ANU HOLD lane; verify-only (회장 §3.C/§8, reg 8/9/10).uQ   unauthorized action -> retained as a proposal, NOT enacted (회장 §2.4, reg 3).u   bounded enactor: Track A=additive closeout enact only · Track B/C=verify-only · merge/PR/credential/branch=blocked · zero auto-dispatch/merge/cron/subprocess · idempotent · executor self key never owns/operates a callback (회장 §2/§6/§8/§10).rW   )5r-   FORBIDDEN_PROGRESS_TRIGGERSr   TRIGGER_REGISTRY_COMPLETEDrY   RESULT_SCHEMAro   TRIGGER_FIXED_TIMETRIGGER_DEAD_MANTRIGGER_FALLBACKr   r7   r   setr   r   rz   rP   r9   r;   r<   r=   r?   rM   rJ   r   r   r   r2   r3   r4   r:   r>   r   rC   rA   rF   addr   r{   r   r   r   r   r@   r   r   r   rp   ENACTOR_ENACTEDENACTOR_IDEMPOTENT_SKIPENACTOR_NO_ACTIONlen) rO   r5   r   r   r   r   rZ   rJ   r   r6   
candidatesrj   rk   r@   	idem_skipdispatch_readyru   hold_routedholdseen_enact_idscandrE   djrecge	batch_keyall_apr   idemr   r[   rs                                    r,   enactzRuntimeEventEnactor.enact,  sJ   &  $ #&AANN*+B*E F  :< =.. ! $!1 2 "&	 ,/AA ,/?? ,/?? ) $,  !"!"  #$ '(%& &''(  )* #$+, -. $&/0  %12  3 8 $K0--e4
(*68GHHH)HnHw
 $'5 ]	 D)"&"8"8&;	H !!#B &44",,#.. % $ X--.C "77&&1/ XXo.%b$/RRHHZ(GDHH[,AGR	 dhh'?@A TFF34F "?'%.$7$3	  #&5#.(*.C'NI"A$'+:*;(--0;$'CO KK&&N NN3'""3'&$3#'#6#6
 #',,.&&*EEDKK&&J
 ((O;*.C'NIKK&&O
  $<<)9 $!)	  =  H '2'B&*1**Q **M '--&5(+'*{{#&#6#6 )1!%	 $99!#""(
 N21""? $66q ""M
 ""5 NN3{]	 ~ ,G%G-G'GQ	
  
 
-
 
 8	

 "
  
  
 %
  (
  
O
 "
 #,
 "0
 "
 *
  +22QQYY[2!
"  2#
$  %
& '
 	
  3s   T))r   zSequence[str]rz   r:   r{   r:   rR   None)r6   rD   rR   ri   )
r   r:   rZ   r:   r   rD   r   r:   rR   rD   )r5   rD   r   r:   r   r>   r   zOptional[ArtifactWriter]r   r:   rZ   r:   rR   rY   )
rS   rT   rU   __doc__r   r   r   r   CLOSEOUT_ARTIFACT_TARGETr   rW   r.   r,   rx   rx      s     "$3	-  	- 		-
 	- 
	-&	  8
 8
 	8

 #8
 8
 
8
~ (B&+487 "K
&K
 "%	K

  $K
 2K
 K
 K
 
K
r.   rx   ry   )rZ   c               T    d|xs | j                   t        dd| j                         dS )ug   Serialize the enactor result as the standalone enactor-result
    artifact (회장 §4 expected_files).ztask-2553+55.enactor-result.v1bounded_enactF)r1   rZ   r`   r   rs   r0   )rZ   r   rP   )r0   rZ   s     r,   enactor_result_enveloper   :  s2     3,G0G0G#&.." r.   )ENACTOR_SCHEMAr   r   r   r   r   r   r   r   r   r   r   r   ro   rp   r9   rY   rx   r   )r+   objectrR   r:   )r5   rD   rR   rD   )r0   rY   rZ   r:   rR   rD   )5r   
__future__r   r%   r'   dataclassesr   r   typingr   r   r   r	   r
   anu_v3.enactor_idempotencyr   r   r   r   "anu_v3.proposal_authorization_gater   r   r   r   r   r   r   r   r   r   r   r   r   r   	frozensetr   r   r   r   r   r   ro   rp   r:   r   ArtifactWriterr-   r7   r9   rY   rx   r   __all__rW   r.   r,   <module>r      s@  ,Z #   ( ; ;    31E  8 & & &  ()+;<  F   +  6 )  3S&[ 12D89	 
 
 
: 3
 3
 3
lg
 g
V 7903r.   