
    PJjvf                       d Z ddlmZ ddlZddlmZmZ ddlmZ ddl	m
Z
mZmZ ddlmZmZ ddlmZmZmZmZmZmZmZ dd	lmZmZmZmZmZ d
ZdZ ed       G d d             Z d dZ!dd	 	 	 	 	 d!dZ"dd	 	 	 	 	 d"dZ#dd	 	 	 	 	 d#dZ$e G d d             Z%	 	 	 	 	 	 	 	 d$dZ&dZ'd%dZ(	 	 	 	 	 	 	 	 d&dZ)dddddddedddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d'dZ*g dZ+y)(uJ  utils/normal_completion_callback_collector_entrypoint.py

task-2553+37 — CANCEL-ON-SUCCESS COLLECTOR-PATH WIRING micro-fix.

진단 (memory/events/task-2553.cancel-on-success-noop-diagnosis_260518.json):
  PRIMARY   = COLLECTOR_PATH_NOT_WIRED
  SECONDARY = FALLBACK_ID_NOT_BOUND

  +25 가 cancel-on-success seam 을 ``operational_collector_wiring`` 모듈에
  결선했으나, 실제 운영 normal completion callback 경로(ANU/bot 가 등록하는
  자유형 'ANU Result Collector' cron prompt)는 그 모듈 entrypoint
  (``run_operational_completion_callback_collector``)를 경유하지 않았고,
  fallback_cron_id 도 normal callback prompt/contract 에 바인딩되지 않아
  durable-success 후에도 seam 미진입 → live verifier 5조건 미도달 →
  cron-remove 미호출 → fallback 잔존·발화 (안전망 DUPLICATE_CALLBACK_IGNORED
  /RESULT_READY_NO_NORMAL_CALLBACK 만 작동).

본 모듈 (회장 verbatim task-2553+37 §2 1~10 — 결선 micro-fix):
  1. 표준 normal completion callback collector entrypoint =
     ``run_wired_normal_completion_callback_collector`` 이며, durable-success
     판정·seam 결선은 전적으로 +25
     ``operational_collector_wiring::run_operational_completion_callback_collector``
     를 **경유**한다 (PRIMARY 결선 — COLLECTOR_PATH_NOT_WIRED 해소).
  2. durable-success 후 +25 wiring 이 ``run_operational_cancel_seam
     (operational=True)`` 을 1회 호출한다 (+25 무회귀, 본 모듈은 결선만).
  3. live cron-state verifier 5조건 AND PASS 일 때만 bound fallback cron
     1건이 제거된다 (+23/+25 verifier 권위 그대로, 본 모듈 우회 0).
  4. ``fallback_cron_id`` binding 을 normal callback prompt/contract 에
     **필수화**한다 — ``build_normal_completion_callback_prompt`` /
     ``NormalCallbackBinding`` / ``validate_normal_callback_binding``
     (SECONDARY 해소 — FALLBACK_ID_NOT_BOUND). +32
     ``dispatch.executor_completion_contract`` 4-tuple 규칙과 정합
     (normal_collector_cron_id·fallback_callback_cron_id 둘 다 필수).
  5. fallback_cron_id 가 없거나(missing) dispatch-fired marker 와
     mismatch 이면 seam 미진입·cron-remove 0·fallback 보존.
  6. cancel-audit JSON 을 생성한다 (binding-valid → +25 cancel-audit 위임;
     binding-invalid → 본 모듈이 BINDING_* 레코드 생성, 동일 필수 필드).
  7. cron-remove 실패/skip/exception 은 normal collector success 를 실패로
     바꾸지 않는다 (+25 디커플 상속 + binding-invalid 경로도 collector
     결과 그대로 반환).
  8. DUPLICATE_CALLBACK_IGNORED fallback safety path 무회귀 (+25/frozen
     경유 — 비-PASS·ack loser → seam 미진입).
  9. +32 executor completion callback mandatory contract 와 충돌 0 — 본
     모듈은 +32 를 read-only import 하여 4-tuple 을 검증할 뿐 약화하지 않음.
 10. registry/checkpoint(+29/+30/+31) 는 recovery layer 로 유지 — 본
     entrypoint 가 primary path 이며 registry 가 이를 대체하지 않는다.

설계 규율:
  * frozen anchor ``utils/anu_delegation_completion_callback.py``
    (sha256 83b3e307…) 무접촉 — read-only import 만. +25 wiring·+23 seam·
    verifier·+9a·+32 contract 전부 무수정 (strict-additive 신규 모듈).
  * cancel-audit 산출 보장 (ANU-Codex adjudication, Codex HIGH 수용):
    **권위 artifact = 항상 채워지는 in-memory ``WiredCollectorResult.
    cancel_audit`` dict** 이며, 이를 executor 가 durable deliverable
    ``memory/events/task-2553+37.cancel-audit.json`` 으로 영속한다(본 task
    필수 산출). 함수 레벨 on-disk write 는 best-effort 다중후보 시도이며,
    write OSError 를 raise 로 전파하지 않는 것은 §2.7 디커플 의무(감사기록
    파일 IO 실패가 normal 성공을 뒤집어선 안 됨)이자 +25
    ``build_cancel_audit`` 의 기존(회장 승인·frozen) 동일 패턴과 정합이다.
    따라서 RO/full filesystem 에서도 "생성"(§2.6)은 dict+deliverable 로
    보장되고, 디스크 단일경로 실패가 산출 손실로 이어지지 않는다.
  * 본 task 구현/테스트는 실 운영 cron 절대 비접촉 (§6 9-R.4): cron_lister
    /remover 는 항상 fake/격리 주입, 실 cokacdir subprocess 0. 실
    cron-remove 는 결선완료·verifier 5조건 PASS 후 운영단계 동작이며
    본 task 행위가 아니다.
    )annotationsN)	dataclassfield)Path)CallableOptionalUnion)Callback4Tuplevalidate_4tuple)ANU_CALLBACK_CHAT_IDCallbackInputClassificationCollectorResultPostResultReview no_real_codex_post_result_review!run_completion_callback_collector)SCHEMA_CANCEL_AUDITOperationalSeamParamsOperationalWiringResultcompute_event_id-run_operational_completion_callback_collectorz'task-2553+37.normal_callback_binding_v1ztask-2553+37T)frozenc                  P    e Zd ZU dZded<   ded<   ded<   ded<   eZded	<   dd
Zy)NormalCallbackBindingu   normal completion callback prompt/contract 에 박힌 4-tuple binding.

    ``fallback_cron_id`` 는 **필수**다 (회장 §2.4). 부재·공백이면 binding
    invalid → seam 미진입·cron-remove 0·fallback 보존 (회장 §2.5).
    strtask_iddispatch_cron_idOptional[str]normal_collector_cron_idfallback_cron_idintchat_idc                x    t        | j                  | j                  | j                  | j                  xs d      S )u8   +32 Callback4Tuple 로 사상 (mandatory 규칙 공유). )r   r   r   fallback_callback_cron_id)r
   r   r   r   r    )selfs    L/home/jay/workspace/utils/normal_completion_callback_collector_entrypoint.py	as_4tuplezNormalCallbackBinding.as_4tuple|   s6    LL!22%)%B%B&*&;&;&Ar	
 	
    N)returnr
   )__name__
__module____qualname____doc____annotations__r   r"   r(    r)   r'   r   r   n   s/     L++##'GS'
r)   r   c                <   	 t        j                  t        |       j                  d            }t        |t              r|j                  d      nd}t        |t              r%|j                  d      }t        |t              r|r|S y# t        t
        f$ r Y yw xY w)u   dispatch-fired marker 의 사전등록 fallback callback cron id 추출.

    +23/+25 verifier 가 교차검증하는 동일 토큰. 부재·파싱불가 → None
    (보수적 — binding mismatch 로 취급되어 seam 미진입).
    utf-8encodingNcallback_policy_ar%   )
jsonloadsr   	read_textOSError
ValueError
isinstancedictgetr   )dispatch_fired_marker_pathrawpolfids       r'   _marker_fallback_idrB      s    jj+,666H

 +5S$*?#''%
&TC#tgg12c3CJ Z  s   .B	 	BBr>   c                  g }|t        | j                               D cg c]  }d| 	 c}z  }| j                  s|j                  d       | j                  t
        k7  r|j                  d| j                          |\| j                  rPt        |      }||j                  d       |S || j                  k7  r!|j                  d| j                   d|        |S c c}w )u  binding 무결성 검증 — 빈 리스트 = valid (회장 §2.4/§2.5).

    검사:
      * +32 4-tuple mandatory (task_id/dispatch/normal_collector/fallback).
      * fallback_cron_id 부재 → ``fallback_cron_id_missing`` (seam 미진입).
      * chat_id 가 ANU 소유 아님 → mismatch.
      * dispatch-fired marker 제공 시: marker.fallback_callback_cron_id 와
        binding.fallback_cron_id 불일치 → ``fallback_cron_id_marker_mismatch``
        (live verifier ④ 도달 전 binding 단계 차단 — 회장 §2.5).
    4tuple:fallback_cron_id_missingzchat_id_not_anu_owned:(dispatch_fired_marker_fallback_id_absentz)fallback_cron_id_marker_mismatch:binding=z	!=marker=)r   r(   r    appendr"   r   rB   )bindingr>   reasonsr
marker_fids        r'    validate_normal_callback_bindingrM      s     Gw7H7H7J'KL!'!LLG##12..//@AB!-'2J2J()CD
NNEF N 7333NN"334Ij\K N Ms   Cc                   t        | |       S )NrC   )rM   )rI   r>   s     r'   binding_is_validrO      s    
 0,F  r)   z	<anu-key>)anu_key_refc                  t        |       }|D cg c]  }|j                  d      s|dk(  r| }}|rt        d|       d| j                   d| j                   d| j                   d| j
                   d| j                   d	| j                   d
| }t        | j                  | j                  | j                  | j
                  | j                  dd|t        | j                                d
S c c}w )u  normal completion callback prompt/contract 템플릿 — fallback_cron_id
    binding **필수** (SECONDARY 해소).

    실제 cron 을 등록하지 않는다 (schema 산출만 — frozen 무접촉, dispatch
    외 추가발사 0). 운영 caller 는 이 contract 의 ``fallback_cron_id`` 를
    그대로 entrypoint binding 으로 전달해야 한다.

    Raises:
        ValueError: fallback_cron_id 또는 normal_collector_cron_id 부재 시
            (binding mandatory — NO-CRON 으로도 면제 불가, +32 §6.12 정합).
    rE   rF   ui   normal completion callback prompt 는 fallback_cron_id binding 필수 (회장 §2.4, +32 §6.12 정합): zcokacdir --cron "[u    normal completion callback] ANU Result Collector — collector path MUST route via operational_collector_wiring::run_operational_completion_callback_collector. task_id=z normal_collector_cron_id=z fallback_cron_id=z dispatch_cron_id=u   " --at "<즉시>" --chat z --key Tu   run_wired_normal_completion_callback_collector → operational_collector_wiring::run_operational_completion_callback_collector (PRIMARY path; registry/checkpoint = recovery layer only, never replaces this))
schemar   r   r   r    r"   !fallback_cron_id_binding_requiredcollector_path_contract"callback_register_command_templateplus32_4tuple_valid)rM   
startswithr:   r   r   r    r   r"   SCHEMA_BINDINGr   r(   )rI   rP   rJ   rK   hardcmds         r'   'build_normal_completion_callback_promptr[      s5     /w7G <<	"a+E&E 	
D 
 99=@
 	

 W__- . ??# $$$+$D$D#E F#445 6#445 6"")//!2'+	H  !??#44$+$D$D#44??-1N
 /2#273D3D3F#GG +s   C/c                      e Zd ZU dZded<   ded<   ded<   ded<    ee      Zd	ed
<   dZded<   dZ	ded<   dZ
ded<   dZded<   dZded<    ee      Zded<   dZded<    ee      Zd	ed<   y)WiredCollectorResultu  표준 wired entrypoint 1회 실행 결과.

    ``collector_result`` 는 frozen collector 가 반환한 값 그대로 (디커플 —
    seam/binding 결과로 변경 0). binding-valid 경로는 +25
    ``OperationalWiringResult`` 를 ``wiring_result`` 로 보유한다.
    r   collector_resultbooldurable_success&wired_via_operational_collector_wiringbinding_valid)default_factorylistbinding_invalid_reasonsFseam_invokedTfallback_preservedcron_remove_invokedr$   r   event_idNr   cancel_audit_pathr<   cancel_auditz!Optional[OperationalWiringResult]wiring_resultnotes)r+   r,   r-   r.   r/   r   rd   re   rf   rg   rh   ri   rj   r<   rk   rl   rm   r0   r)   r'   r]   r]     s     &%,00$)$$?T?L$## %%Hc'+}+t4L$47;M4;-E4-r)   r]   c                    t        d |D              }|rdnd}t        | |dd|t        |      ddddddddd	|rd
ndz   dz   dddS )u   binding-invalid cancel-audit (회장 §2.6 — +25 cancel-audit 와 동일
    필수 필드, lookup_status = BINDING_*).

    fallback_cron_id missing/mismatch → remove 0·fallback 보존·디커플 증명.
    c              3  L   K   | ]  }|j                  d       xs |dk(    yw) fallback_cron_id_marker_mismatchrG   N)rW   ).0rK   s     r'   	<genexpr>z)_binding_invalid_audit.<locals>.<genexpr>'  s7        	
78 	;::	;s   "$BINDING_MISMATCHBINDING_MISSINGFTNc1_task_id_matchc2_chat_id_ownedc3_role_fallbackc4_marker_id_crosscheck c5_pending_not_fired_not_removedNOT_ATTEMPTEDzfallback_cron_id binding mismatchmissinguB    → seam 미진입, cron-remove 0, fallback 보존 (회장 §2.5))rR   ri   target_cron_idrf   ra   lookup_statusre   five_condition_resultsremove_attemptedremove_resultskip_reasonalready_removed_or_missingnormal_success_unchanged)anyr   rd   )ri   r~   rJ   r|   lookups        r'   _binding_invalid_auditr     s        H
 $,1BF%(26#'= $ $ $'+04#
 "('%z96RS ',$(1 r)   )
rR   ri   r~   r   r   r   r   r   r   r   c          	        t        | t              rt        |       ni }|j                  dt               |j                  d|       |j                  d|       |j                  dd       |j                  ddddddd       |j                  d	d
       |j                  dd       |j                  dd       |j                  dd
       d|d<   |j                  dd       |S )u   필수 필드 전수 보장 — 누락 시 안전 기본값 backfill (Codex MED 해소).

    디커플 불변: ``normal_success_unchanged`` 는 무엇이 와도 True.
    rR   ri   r~   r   NOT_INVOKEDr   Nru   r   Fr   r{   r   r$   r   Tr   ra   )r;   r<   
setdefaultr   )auditri   r~   as       r'   _normalize_cancel_auditr   Y  s    
 "%.UBALL./LLX&LL!>2LL-0LL  $ $ $'+04	
	 LL#U+LL/2LL#LL-u5$(A !LL94@Hr)   c                  t        j                  | dd      }|g|D cg c]  }||	 c}D ]?  }	 |j                  j                  dd       |j	                  |d       t        |      c S  yc c}w # t        $ r Y Sw xY w)	u  cancel-audit JSON on-disk 산출 보장 (Codex HIGH 해소).

    primary → fallback 들 순차 시도. 단일 디렉터리 실패가 artifact 손실로
    이어지지 않게 다중 후보에 기록을 시도한다. 반환 = 최초 성공 경로
    (전부 실패해도 in-memory ``cancel_audit`` dict 는 항상 result 에 보존되어
    executor result/decision JSON 으로 영속 — 산출 보장).
    F   )ensure_asciiindentNT)parentsexist_okr2   r3   )r6   dumpsparentmkdir
write_textr   r9   )r   primary	fallbacksbodypcands         r'   _guaranteed_write_auditr   v  s     ::e%:D$1y1CqQ]C 	KKdT:OOD7O3t9	  D
  		s   A2A2:A77	BB)rj   cron_listerremoverfallback_cancelled_marker_pathcancel_lock_pathseam_audit_pathcallback_contractpost_result_review_fnduplicate_callback_seenevidence_pathspost_result_review_marker_pathc                 ! t        |      }t        ||      }|rt        | |||||      }|j                  t        j
                  k(  xr |j                  du xr |j                  du }t        | j                  |j                  xs d||      }|j                  xs d}t        t        |||      ||      !|t        |      nt        |      t         d	z  }t        !|t        |      t         d
| dz  g      }t        ||dd|ddd||!ddg      S t!        |j                  xs d|t        |      t        |      t        |      |rt        |      nd|	|
|rt        |      nd|rt        |      nd|      }t#        | ||||||||	      }|j$                  }|rt'        |j(                        nd}|rt'        |j*                        nd }t        t-        |j.                        |j0                  |j                  xs d      !t3        !fdt4        D              sJ |j6                  xsO t        !|t        |      nt        |      t         d	z  t        |      t         d
|j0                   dz  g      } t        |j8                  |j:                  ddg |j<                  |||j0                  | !|g d      S )u  표준 normal completion callback collector entrypoint (회장 §2 1~10).

    절차:
      A. fallback_cron_id binding 검증 (mandatory + marker cross-check).
      B. binding invalid (missing/mismatch) → frozen collector 만 read-only
         호출해 분류, seam 미진입, cron-remove 0, fallback 보존, BINDING_*
         cancel-audit 기록 — collector_result 그대로 (디커플).
      C. binding valid → +25
         ``run_operational_completion_callback_collector`` **경유**
         (PRIMARY 결선). durable-success → +23 seam(operational=True) 1회
         → live verifier 5조건 AND → bound fallback cron-remove. seam/
         cancel-audit/exact-once/디커플은 전부 +25 권위 그대로.
    rC   )r   r   r   r   Tz	<UNBOUND>)r   r    r>   result)ri   r~   rJ   )ri   r~   Nz.cancel-audit.jsonz.cancel-audit.z.json)r   r   Fu   FALLBACK_ID_NOT_BOUND 해소 가드: binding missing/mismatch → +25 seam 미경유, cron-remove 0, fallback 보존 (회장 §2.5)u~   디커플: binding invalid 는 normal collector 성공과 무관 — collector_result 그대로, normal_success_unchanged=True)r^   r`   ra   rb   re   rf   rg   rh   ri   rj   rk   rm   r$   )r~   r>   result_json_pathreport_pathcollector_result_marker_path
audit_pathr   r   r   r   r   )seam_params	claim_dirr   r   r   r   rj   c              3  &   K   | ]  }|v  
 y w)Nr0   )rq   kr   s     r'   rr   zArun_wired_normal_completion_callback_collector.<locals>.<genexpr>'  s     :aqEz:s   )u   COLLECTOR_PATH_NOT_WIRED 해소: 표준 entrypoint → +25 operational_collector_wiring::run_operational_completion_callback_collector 경유 (PRIMARY)u   durable-success 후 +23 run_operational_cancel_seam(operational=True) 1회 (+25 권위, verifier 5조건 AND 단독 remove 권위)u   디커플: seam/cron-remove 결과와 무관하게 collector_result 불변 — registry/checkpoint 는 recovery layer, 본 path 가 primary)r^   r`   ra   rb   re   rf   rg   rh   ri   rj   rk   rl   rm   )r   rM   r   classificationr   PASScloseout_candidateack_acquiredr   r   r    r   r   TASK_MARKER_PREFIXr   r]   r   r   seam_outcomer_   rh   fallback_cancelledr<   rk   ri   all_REQUIRED_AUDIT_FIELDSrj   r^   r`   rf   )"inpack_pathrI   r>   r   r   r   r   rj   r   r   r   r   r   r   r   r   r   r   dfmrJ   r^   r`   ri   tgtr   audit_writtenr   rl   sorh   rg   audit_path_outr   s"                                    @r'   .run_wired_normal_completion_callback_collectorr     sY   J )
*C.CG
 <"7$;)+I
 ++~/B/BB 6 33t;6 --5 	
 $KK$55D'*#	
 &&5+'"!#w 
 !, "#i&8%99K#LL 	
 0Y'(xjFG
 $-+37$+# %+XL
 	
* (//52#&./%%)*F%G,;4( . /0 '7D!"D+#K8 B3 7%'E+
M 
	#	#B:<$r556%=?d2#8#89UK#]''(''//52E :#9:::: #44 8O !, "#i&8%99K#LL O#$N=3I3I2J%PQ
9N  &77%55/3 ""//-/''(#	
 r)   )rX   r   r   rM   rO   r[   r]   r   )r>   r   r*   r   )rI   r   r>   Optional[Path]r*   z	list[str])rI   r   r>   r   r*   r_   )rI   r   rP   r   r*   r<   )ri   r   r~   r   rJ   rd   r*   r<   )r   r<   ri   r   r~   r   r*   r<   )r   r<   r   r   r   rd   r*   r   )(r   r   r   Union[str, Path]rI   r   r>   r   r   r   r   r   r   r   r   r   rj   Optional[Union[str, Path]]r   zOptional[Callable[[], dict]]r   zOptional[Callable[..., object]]r   r   r   r   r   r   r   zOptional[dict]r   z2Callable[[dict, Classification], PostResultReview]r   Optional[list]r   r   r   r   r*   r]   ),r.   
__future__r   r6   dataclassesr   r   pathlibr   typingr   r   r	   %dispatch.executor_completion_contractr
   r   (utils.anu_delegation_completion_callbackr   r   r   r   r   r   r   "utils.operational_collector_wiringr   r   r   r   r   rX   r   r   rB   rM   rO   r[   r]   r   r   r   r   r   __all__r0   r)   r'   <module>r      sm  AD #  (  , ,    ; $  $
 
 
.. 26" !/ 	J 26" !/ 
	 #7"7 7 
	7| . . ..** * 	*
 
*^ :  	
 D 5904/3AE3726(, 	).2%)AE-	 #	
 !1 ' " #3   2 . - %? 1 0  &!"#( ,)* #+, %?-. /D	r)   