
    @=j                     z    d Z ddlmZ ddlZddlmZmZ ddlmZ  G d de          Z	dd
Z
 G d de	          ZdS )u"  CronScheduler provider interface (Axis B — the trigger).

⚠️ EXPERIMENTAL — this interface is validated by exactly ONE consumer (the
built-in) until an external provider (Chronos, Phase 4) shakes it out. Until
then the module path, method signatures, and start() kwargs MAY change without
a deprecation cycle. Once a second provider validates the shape it becomes
stable. Any growth MUST be additive (new optional method with a default), never
a changed signature on start() or a new abstractmethod.

A CronScheduler decides *when* a due job fires. It does NOT decide what firing
means: execution + delivery stay in cron.scheduler.run_job / _deliver_result,
shared by all providers. Providers must never reimplement agent construction or
delivery.

The built-in InProcessCronScheduler runs the historical 60s daemon-thread
ticker. Alternative providers (e.g. Chronos, a NAS-mediated managed-cron
provider for scale-to-zero deployments) live under plugins/cron_providers/<name>/ and are
selected via the `cron.provider` config key (empty = built-in).
    )annotationsN)ABCabstractmethod)Anyc                      e Zd ZdZeedd                        ZddZedddd	dd            ZddZ	ddZ
dddddZddZdS )CronScheduleru  Axis-B trigger provider. Decides WHEN a due cron job fires.

    Required surface is intentionally minimal: ``name`` + ``start``. ``stop``
    and ``is_available`` carry safe defaults. The three Phase-4 hooks
    (``on_jobs_changed`` / ``fire_due`` / ``reconcile``) are added later as
    NON-abstract methods so the built-in keeps satisfying the ABC without
    overriding them — see ``test_abc_growth_stays_additive``.
    returnstrc                    dS )z,Short identifier, e.g. 'builtin', 'chronos'.N selfs    =/home/rurouni/.hermes/hermes-agent/cron/scheduler_provider.pynamezCronScheduler.name%             boolc                    dS )a)  Whether this provider can run in the current environment.

        MUST NOT make network calls. The built-in is always available; an
        external provider checks for configured endpoint/credentials. When a
        named provider returns False, the resolver falls back to the built-in.
        Tr   r   s    r   is_availablezCronScheduler.is_available*   s	     tr   N<   adaptersloopinterval
stop_eventthreading.Eventr   r   r   r   intNonec                   dS )aP  Begin firing due jobs.

        For the built-in this BLOCKS in the 60s loop until stop_event is set
        (it is run inside a daemon thread by the caller, exactly as today).
        An external provider may register a schedule/webhook and return
        immediately; in that case it must still honor stop_event for teardown.
        Nr   )r   r   r   r   r   s        r   startzCronScheduler.start3   r   r   c                    dS )zOptional eager teardown hook. Default no-op; setting the stop_event
        is the primary stop signal. Override for providers holding external
        resources (queue consumers, HTTP servers).Nr   r   s    r   stopzCronScheduler.stopD   	     tr   c                    dS )a  Called after a successful store mutation (create/update/remove/
        pause/resume). External providers reconcile their registry here (e.g.
        Chronos re-provisions/cancels the affected one-shot via NAS).
        Built-in: no-op (it re-reads jobs.json on every tick).Nr   r   s    r   on_jobs_changedzCronScheduler.on_jobs_changedN   s	    
 tr   r   r   job_idc               r    ddl m}m} ddlm}  ||          sdS  ||          }|dS  ||||          S )aL  Run a single job NOW via the shared orchestrator. Called by the
        inbound fire webhook when an external scheduler signals a job is due.

        The default claims the job with a store-level compare-and-set
        (multi-machine at-most-once), then runs it via the shared
        ``run_one_job`` body. Built-in never calls this (it has its own tick
        loop); an external provider routes its inbound fire here.

        Returns True if THIS caller claimed and ran the job, False if the claim
        was lost (another machine/retry won it) or the job no longer exists.
        r   )claim_job_for_fireget_job)run_one_jobFNr&   )	cron.jobsr)   r*   cron.schedulerr+   )r   r'   r   r   r)   r*   r+   jobs           r   fire_duezCronScheduler.fire_dueU   st     	:9999999......!!&)) 	5gfoo;5{3====r   c                    dS )zConverge the external registry toward jobs.json (the desired state):
        arm missing one-shots, cancel orphaned ones, re-arm changed times.
        Built-in: no-op.Nr   r   s    r   	reconcilezCronScheduler.reconcilek   r#   r   r	   r
   )r	   r   )
r   r   r   r   r   r   r   r   r	   r   )r	   r   )r'   r
   r   r   r   r   r	   r   )__name__
__module____qualname____doc__propertyr   r   r   r    r"   r%   r/   r1   r   r   r   r   r      s          ; ; ; ^ X;    
      ^        8< > > > > > >,     r   r   r	   'CronScheduler'c                 |   ddl } |                     d          }d}	 ddlm}m}  | |            ddd          pd                                }n# t          $ r Y nw xY w|r|d	v rt                      S 	 dd
lm	}  ||          }|$|
                    d|           t                      S |                                s$|
                    d|           t                      S |                    d|j                   |S # t          $ r/}|
                    d||           t                      cY d}~S d}~ww xY w)u1  Return the active cron scheduler provider.

    Reads ``cron.provider`` from config. Empty/absent → built-in. A named
    provider that is missing, fails to load, or reports ``is_available() ==
    False`` falls back to the built-in with a warning — cron must never be left
    without a trigger.
    r   Ncron.scheduler_provider )cfg_getload_configcronprovider)default)builtinz
in-process	inprocess)load_cron_schedulerz3cron.provider '%s' not found; using built-in tickerz7cron.provider '%s' not available; using built-in tickerz!Using cron scheduler provider: %sz=Failed to load cron.provider '%s' (%s); using built-in ticker)logging	getLoggerhermes_cli.configr<   r=   strip	ExceptionInProcessCronSchedulerplugins.cron_providersrC   warningr   infor   )rD   loggerr   r<   r=   rC   r?   es           r   resolve_cron_schedulerrO   r   s    NNN899FD::::::::vz2FFFL"SSUU     (4AAA%'''(>>>>>>&&t,,NNPRVWWW)+++$$&& 	,NNTVZ[[[)+++7GGG ( ( (KTST	
 	
 	
 &''''''''	(s;   3A 
AA66D -7D %D 
D;$D60D;6D;c                  :    e Zd ZdZed	d            ZdddddZdS )
rI   zDefault provider: the historical in-process 60s ticker.

    ``start()`` blocks in the tick loop until ``stop_event`` is set, identical
    to the pre-refactor ``_start_cron_ticker`` core loop. The caller runs it in
    a daemon thread.
    r	   r
   c                    dS )NrA   r   r   s    r   r   zInProcessCronScheduler.name   s    yr   Nr   r   c                  dd l }ddlm} ddlm} |                    d          }|                    d|            |             |                                s{d}		  |d||d           d}	n/# t          $ r"}
|	                    d	|
d
           Y d }
~
nd }
~
ww xY w ||	           |
                    |           |                                yd S d S )Nr   )tick)record_ticker_heartbeatr:   z0In-process cron scheduler started (interval=%ds)F)verboser   r   syncTzCron tick error: %s)exc_info)success)rD   r-   rS   r,   rT   rE   rL   is_setBaseExceptionerrorwait)r   r   r   r   r   rD   	cron_tickrT   rM   okrN   s              r   r    zInProcessCronScheduler.start   sG   444444555555""#<==FQQQ 	 !!!##%% 	&BF	%(ERRRR  F F F 2AEEEEEEEEF $#B////OOH%%%% ##%% 	& 	& 	& 	& 	&s   A/ /
B9BBr2   )r3   r4   r5   r6   r7   r   r    r   r   r   rI   rI      s`             X -1tb & & & & & & &r   rI   )r	   r8   )r6   
__future__r   	threadingabcr   r   typingr   r   rO   rI   r   r   r   <module>rc      s    & # " " " " "     # # # # # # # #      T T T T TC T T Tn%( %( %( %(P(& (& (& (& (&] (& (& (& (& (&r   