
    p#jz                       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mZ ddl	m	Z	m
Z
 ddlmZ ddlmZmZmZmZmZmZ ddlmZ dd	lmZ  ej        e          ZdZ	 ddlZn# e$ r dZ	 ddlZn# e$ r Y nw xY wY nw xY wd
ZdZdZ eee hZ!dTdZ"dTdZ#ed             Z$dTdZ%dUdZ&dVdZ'dWdZ(dXdZ)dYd Z*dYd!Z+dZd#Z,dTd$Z-dYd%Z.d[d(Z/d\d*Z0d\d+Z1d]d-Z2d]d.Z3d^d1Z4d_d2Z5d_d3Z6d_d4Z7d_d5Z8d`d6Z9dad7Z:dbd9Z;dcd;Z<ddd<Z=d\d=Z>d>d?dedAZ?d\dBZ@d\dCZAd\dDZBd\dEZCdfdGZDdgdIZEd\dJZFdhdLZGdhdMZHdidOZIdjdQZJdkdRZKdjdSZLdS )la  Skill usage telemetry + provenance tracking for the Curator feature.

Tracks per-skill usage metadata in a sidecar JSON file (~/.hermes/skills/.usage.json)
keyed by skill name. Counters are bumped by the existing skill tools (skill_view,
skill_manage); the curator orchestrator reads the derived activity timestamp to
decide lifecycle transitions.

Design notes:
  - Sidecar, not frontmatter. Keeps operational telemetry out of user-authored
    SKILL.md content and avoids conflict pressure for bundled/hub skills.
  - Atomic writes via tempfile + os.replace (same pattern as .bundled_manifest).
  - All counter bumps are best-effort: failures log at DEBUG and return silently.
    A broken sidecar never breaks the underlying tool call.
  - Provenance filter: curator-managed skills are explicitly marked when
    created through skill_manage. Bundled / hub-installed skills stay
    off-limits, and manually authored skills are not inferred from location.

Lifecycle states:
    active    -> default
    stale     -> unused > stale_after_days (config)
    archived  -> unused > archive_after_days (config); moved to .archive/
    pinned    -> opt-out from auto transitions (boolean flag, orthogonal to state)
    )annotationsN)contextmanager)datetimetimezone)Path)AnyDictListOptionalSetTupleget_hermes_home)is_excluded_skill_pathactivestalearchivedreturnr   c                 $    t                      dz  S )Nskillsr        6/home/ubuntu/.hermes/hermes-agent/tools/skill_usage.py_skills_dirr   ;   s    x''r   c                 $    t                      dz  S )Nz.usage.jsonr   r   r   r   _usage_filer   ?   s    ===((r   c               #  X  K   t                                          d          } | j                            dd           t          t
          dV  dS t
          rH|                                 r|                                 j        dk    r| 	                    dd           t          | t
          rd	nd
d          }	 t          r t	          j        |t          j                   nG|                    d           t          j        |                                t
          j        d           dV  t          r8	 t	          j        |t          j                   n~# t$          t&          f$ r Y nkw xY wt
          r`	 |                    d           t          j        |                                t
          j        d           n# t$          t&          f$ r Y nw xY w|                                 dS # t          r8	 t	          j        |t          j                   n~# t$          t&          f$ r Y nkw xY wt
          r`	 |                    d           t          j        |                                t
          j        d           n# t$          t&          f$ r Y nw xY w|                                 w xY w)z@Serialize .usage.json read-modify-write cycles across processes.z
.json.lockTparentsexist_okNr    utf-8encodingzr+za+   )r   with_suffixparentmkdirfcntlmsvcrtexistsstatst_size
write_textopenflockLOCK_EXseeklockingfilenoLK_LOCKLOCK_UNOSErrorIOErrorLK_UNLCKclose)	lock_pathfds     r   _usage_file_lockr>   C   s      )),77I4$777} 4y'')) 4Y^^-=-=-E-J-JS7333	i1TG	D	D	DB 	;KEM****GGAJJJN299;;::: 
	B....W%    	


ryy{{FOQ????W%   





  
	B....W%    	


ryy{{FOQ????W%   




s{   ?A2G- 9E E-,E-8AG   GG-J)6HJ)H*'J))H**
J)5AI=<J)=JJ)JJ)c                 $    t                      dz  S )Nz.archiver   r   r   r   _archive_dirr@   g   s    ==:%%r   strc                 b    t          j        t          j                                                  S )N)r   nowr   utc	isoformatr   r   r   _now_isorF   k   s     <%%//111r   valuer   Optional[datetime]c                    | sdS 	 t          j        t          |                     }n# t          t          f$ r Y dS w xY w|j         |                    t          j                  }|S )z<Parse an ISO timestamp defensively for activity comparisons.N)tzinfo)	r   fromisoformatrA   	TypeError
ValueErrorrJ   replacer   rD   )rG   parseds     r   _parse_iso_timestamprP   o   su     t'E

33z"   tt}x|44Ms   !( ==recordDict[str, Any]Optional[str]c                    d}d}dD ]B}|                      |          }t          |          }|)|||k    r|}t          |          }C|S )a(  Return the newest actual activity timestamp for a usage record.

    "Activity" means a skill was used, viewed, or patched. Creation time is
    intentionally excluded so callers can still distinguish never-active skills;
    lifecycle code can fall back to ``created_at`` as its own anchor.
    N)last_used_atlast_viewed_atlast_patched_at)getrP   rA   )rQ   	latest_dt
latest_rawkeyrawdts         r   latest_activity_atr^   |   sf     %)I $JD " "jjoo!#&&:YISJr   intc                    d}dD ]A}	 |t          |                     |          pd          z  }+# t          t          f$ r Y >w xY w|S )zFReturn the total observed activity count across use/view/patch events.r   )	use_count
view_countpatch_count)r_   rX   rL   rM   )rQ   totalr[   s      r   activity_countre      sh    E9  	SC-A...EE:& 	 	 	H	Ls   '0AASet[str]c                    t                      dz  } |                                 st                      S t                      }	 |                     d                                          D ]^}|                                }|s|                    dd          d                                         }|r|                    |           _n2# t          $ r%}t          
                    d|           Y d}~nd}~ww xY w|S )	zReturn the set of skill names that were seeded from the bundled repo.

    Reads ~/.hermes/skills/.bundled_manifest (format: "name:hash" per line).
    Returns empty set if the file is missing or unreadable.
    z.bundled_manifestr#   r$   :r&   r   z#Failed to read bundled manifest: %sN)r   r,   set	read_text
splitlinesstripsplitaddr8   loggerdebug)manifestnameslinenamees        r   _read_bundled_manifest_namesrv      s    }}22H?? uueeE	?&&&88CCEE 	  	 D::<<D ::c1%%a(..00D  		$	   ? ? ?:A>>>>>>>>?Ls   BC 
C:C55C:c                    t                      dz  dz  } |                                 st                      S 	 t          j        |                     d                    }t          |t                    r|                    d          pi }t          |t                    rZd |	                                D             }t                      }|
                                D ]}t          |t                    s|                    d          }t          |t                    r|                                sXt          |          }|                                s||z  }	 |                                }|                    |                                           n# t"          t$          f$ r Y w xY w|dz  }	|	                                r)|                    t)          |	|j        	                     |S n># t"          t          j        f$ r%}
t.                              d
|
           Y d}
~
nd}
~
ww xY wt                      S )zReturn the set of skill names installed via the Skills Hub.

    Reads ~/.hermes/skills/.hub/lock.json (see tools/skills_hub.py :: HubLockFile).
    z.hubz	lock.jsonr#   r$   	installedc                ,    h | ]}t          |          S r   )rA   ).0ks     r   	<setcomp>z,_read_hub_installed_names.<locals>.<setcomp>   s    :::AQ:::r   install_pathSKILL.mdfallbackz Failed to read hub lock file: %sN)r   r,   ri   jsonloadsrj   
isinstancedictrX   keysvaluesrA   rl   r   is_absoluteresolverelative_tor8   rM   rn   _read_skill_namert   JSONDecodeErrorro   rp   )r<   datarx   rr   
skills_direntryr}   	skill_dirresolvedskill_mdru   s              r   _read_hub_installed_namesr      sG   
 &4I uu<z)--w-??@@dD!! 	--3I)T** ::)9)9:::(]]
&--// V VE%eT22 ! #(99^#<#<L%lC88 !@R@R@T@T !  $\ 2 2I$0022 ;$.$:	!#,#4#4#6#6 ,,Z-?-?-A-ABBBB#Z0 ! ! ! !'*4H(( V		"28hm"T"T"TUUUT)* < < <7;;;;;;;;<55Ls=   D+G> $;F G>  F41G> 3F44AG> >H9H44H9boolc                 V   	 ddl m}   |             }t          |t                    r|                    d          nd}t          |t                    r#t          |                    dd                    S n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wdS )u  Whether bundled built-in skills are eligible for curator pruning.

    Reads ``curator.prune_builtins`` from config (default True). Lazy import
    keeps this module importable without the CLI config layer (e.g. in the
    update/sync context); on any failure we fall back to the default. The real
    safety against a mass-prune is the curator's seed-on-first-sight, not this
    flag — built-ins only archive after a fresh inactivity window.
    r   )load_configcuratorNprune_builtinsTz)Failed to read curator.prune_builtins: %s)	hermes_cli.configr   r   r   rX   r   	Exceptionro   rp   )r   cfgcurru   s       r   _prune_builtins_enabledr      s    E111111kmm$.sD$9$9Ccggi   tc4   	9 0$77888	9 E E E@!DDDDDDDDE4s   A3A7 7
B&B!!B&c                 $    t                      dz  S )Nz.curator_suppressedr   r   r   r   _suppressed_filer      s    ==000r   c                    t                      } |                                 st                      S t                      }	 |                     d                                          D ]B}|                                }|r*|                    d          s|                    |           Cn2# t          $ r%}t          
                    d|           Y d}~nd}~ww xY w|S )u  Built-in skills the curator pruned — the re-seeder must leave archived.

    One skill name per line in ``~/.hermes/skills/.curator_suppressed``. This is
    what makes pruning a built-in durable: without it, ``hermes update`` would
    re-copy the bundled skill on the next sync.
    r#   r$   #z+Failed to read curator suppression list: %sN)r   r,   ri   rj   rk   rl   
startswithrn   r8   ro   rp   )pathrr   rs   ru   s       r   read_suppressed_namesr      s     D;;== uueeEGNNGN44??AA 	  	 D::<<D  DOOC00  		$	   G G GBAFFFFFFFFGLs    A+B, ,
C6CCrr   Nonec                   t                      }	 |j                            dd           d                    t	          |                     | rdndz   }t          j        t          |j                  dd          \  }}	 t          j	        |dd	
          5 }|
                    |           |                                 t          j        |                                           d d d            n# 1 swxY w Y   t          j        ||           d S # t          $ r( 	 t          j        |           n# t"          $ r Y nw xY w w xY w# t$          $ r(}t&                              d|d           Y d }~d S d }~ww xY w)NTr   
 z.curator_suppressed_.tmpdirprefixsuffixwr#   r$   z,Failed to write curator suppression list: %sexc_info)r   r(   r)   joinsortedtempfilemkstemprA   osfdopenwriteflushfsyncr5   rN   BaseExceptionunlinkr8   r   ro   rp   )rr   r   r   r=   tmpfru   s          r   _write_suppressed_namesr   
  s   DW$666yy''5+@44bA"s4;'7'7@V_efffC	2sW555 %			$$$% % % % % % % % % % % % % % % JsD!!!!! 	 	 		#   	  W W WCQQUVVVVVVVVVWss   A1E D AC5)D 5C99D <C9=D 
E	"D76E	7
EE	EE		E 
E>E99E>
skill_namec                ~    | sdS t                      }| |vr&|                    |            t          |           dS dS )zBRecord that a built-in skill was pruned, so sync won't restore it.N)r   rn   r   r   rr   s     r   add_suppressed_namer      sS     !##E		*&&&&& r   c                ~    | sdS t                      }| |v r&|                    |            t          |           dS dS )z7Clear a built-in's suppression entry (e.g. on restore).N)r   discardr   r   s     r   remove_suppressed_namer   *  sS     !##EUj!!!&&&&& r   	List[str]c                 ~   t                      } |                                 sg S t                      }t                      }t	                      }t                      }g }|                     d          D ]}t          |          r	 |                    |            n# t          $ r Y 5w xY wt          ||j        j                  }||v rY||v r|s`|                    |           vt          |                    |                    s|                    |           t!          t#          |                    S )u  Enumerate skills the curator may manage.

    Always includes agent-authored skills (those marked in ``.usage.json`` via
    ``skill_manage(action="create")``). When ``curator.prune_builtins`` is
    enabled, bundled built-in skills are ALSO included even though they have no
    agent-created usage record — their inactivity clock is anchored on first
    sight (see ``apply_automatic_transitions``). Hub-installed skills are never
    included; manually authored skills are not inferred from filesystem
    location.
    r~   r   )r   r,   r   rv   r   
load_usagerglobr   r   rM   r   r(   rt   append_is_curator_managed_recordrX   r   ri   )basehubbundledr   usagerr   r   rt   s           r   list_agent_created_skill_namesr   4  sO    ==D;;== 	
#
%
%C*,,G,..NLLEEJJz**  !(++ 		  &&&& 	 	 	H	8?3GHHH3;;7?? " LL)%))D//:: 	T#e**s   B
B*)B*c                     t                      } |                                 sg S t          d |                                 D                       S )a  Enumerate skills in ``~/.hermes/skills/.archive/``.

    Archive layout is flat (``.archive/<skill>/``) as set by ``archive_skill``,
    so the directory name is the skill name. Used by ``hermes curator
    list-archived`` to help users pass a name to ``hermes curator restore``.
    c                D    h | ]}|                                 |j        S r   is_dirrt   )rz   ps     r   r|   z,list_archived_skill_names.<locals>.<setcomp>m  s'    HHHaQXXZZH16HHHr   )r@   r,   r   iterdir)archive_roots    r   list_archived_skill_namesr   c  sO      >>L   	HH<#7#7#9#9HHHIIIr   r   r   c                   	 |                      dd          dd         }n# t          $ r |cY S w xY wd}|                    d          D ]}|                                }|dk    r|r nbd	}#|r\|                    d
          rG|                    dd          d                                                             d          }|r|c S |S )z9Parse the `name:` field from a SKILL.md YAML frontmatter.r#   rN   )r%   errorsNi  Fr   z---Tzname:rh   r&   z"')rj   r8   rm   rl   r   )r   r   textin_frontmatterrs   strippedrG   s          r   r   r   p  s   !!79!EEeteL   N

4   
 
::<<u !N 	h11':: 	NN3**1-3355;;EBBE Os   " 11c                D    t                      t                      z  }| |vS )z:Whether *skill_name* is neither bundled nor hub-installed.)rv   r   )r   
off_limitss     r   is_agent_createdr     s$    -//2K2M2MMJZ''r   c                "    | t                      v S )z6Whether *skill_name* was installed via the Skills Hub.)r   r   s    r   is_hub_installedr     s    24444r   c                "    | t                      v S )z=Whether *skill_name* was seeded from the bundled repo skills.)rv   r   s    r   
is_bundledr     s    57777r   c                b    t          |           rdS t          |           rt                      S dS )u  Whether the curator may track/archive *skill_name*.

    Agent-created skills are always eligible. Bundled built-ins become eligible
    only when ``curator.prune_builtins`` is enabled. Hub-installed skills are
    NEVER eligible — they have an external upstream owner.
    FT)r   r   r   r   s    r   is_curation_eligibler     s:     
## u* )&(((4r   c                    t          | t                    sdS |                     d          dk    p|                     d          du S )zEReturn True when a usage record opts a skill into curator management.F
created_byagentagent_createdT)r   r   rX   )rQ   s    r   r   r     sG    fd## u::l##w.U&**_2M2MQU2UUr   c                 @    d ddd d dd t                      t          dd dS )Nr   F)r   ra   rb   rU   rV   rc   rW   
created_atstatepinnedarchived_at)rF   STATE_ACTIVEr   r   r   _empty_recordr     s6    jj  r   Dict[str, Dict[str, Any]]c                    t                      } |                                 si S 	 t          j        |                     d                    }nA# t
          t          j        f$ r(}t                              d| |           i cY d}~S d}~ww xY wt          |t                    si S i }|                                D ],\  }}t          |t                    r||t          |          <   -|S )zGRead the entire .usage.json map. Returns empty dict on missing/corrupt.r#   r$   zFailed to read %s: %sN)r   r,   r   r   rj   r8   r   ro   rp   r   r   itemsrA   )r   r   ru   cleanr{   vs         r   r   r     s    ==D;;== 	z$..'.::;;T)*   ,dA666						 dD!! 	')E

  1a 	E#a&&MLs   (A B%BBBr   c                   t                      }	 |j                            dd           t          j        t          |j                  dd          \  }}	 t          j        |dd          5 }t          j	        | |d	dd
           |
                                 t          j        |                                           ddd           n# 1 swxY w Y   t          j        ||           dS # t          $ r( 	 t          j        |           n# t           $ r Y nw xY w w xY w# t"          $ r)}t$                              d||d           Y d}~dS d}~ww xY w)uN   Write the usage map atomically. Best-effort — errors are logged, not raised.Tr   z.usage_r   r   r   r#   r$      F)indent	sort_keysensure_asciiNzFailed to write %s: %sr   )r   r(   r)   r   r   rA   r   r   r   dumpr   r   r5   rN   r   r   r8   r   ro   rp   )r   r   r=   tmp_pathr   ru   s         r   
save_usager     s   ==DG$666'DK  6
 
 
H	2sW555 %	$!t%PPPP			$$$% % % % % % % % % % % % % % % Jx&&&&& 	 	 		(####   	  G G G-tQFFFFFFFFFGss   AD' C2 0ACC2 CC2 CC2 2
D$=DD$
DD$DD$$D' '
E1EEc                   t                      }|                    |           }t          |t                    st	                      S t	                      }|                                D ]\  }}|                    ||           |S )zDReturn the record for *skill_name*, creating a fresh one if missing.)r   rX   r   r   r   r   
setdefault)r   r   recr   r{   r   s         r   
get_recordr    sx    <<D
((:

Cc4   ??D

  1q!Jr   c                   | rt          |           sdS 	 t                      5  t                      }t          |                    |           t
                    r	 ddd           dS t                      || <   t          |           ddd           dS # 1 swxY w Y   dS # t          $ r)}t          
                    d| |d           Y d}~dS d}~ww xY w)u  Persist a baseline usage record for a curation-eligible skill.

    Built-ins carry no usage record until something touches them, which leaves
    their inactivity clock with no anchor. Seeding a record here fixes
    ``created_at`` to the moment the curator first sees the skill, so the
    archive/stale clock measures non-use FROM THEN — not from epoch. No-op when
    a record already exists or the skill isn't curation-eligible.
    Nz1skill_usage.seed_record_if_missing(%s) failed: %sTr   )r   r>   r   r   rX   r   r   r   r   ro   rp   r   r   ru   s      r   seed_record_if_missingr    s[     1*== h 	 	<<D$((:..55 	 	 	 	 	 	 	 	  -Dt	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  h h hH*VWbfggggggggghsF   B" 8BB" ( BB" BB" BB" "
C,CCFrequire_curation_eligibler  c                  | sdS 	 |rt          |           sdS t                      5  t                      }|                    |           }t	          |t
                    st                      } ||           ||| <   t          |           ddd           dS # 1 swxY w Y   dS # t          $ r)}t          
                    d| |d           Y d}~dS d}~ww xY w)u  Load, apply *mutator(record)* in place, save. Best-effort.

    By default this records telemetry for ANY skill — bundled, hub-installed,
    or agent-created — because usage tracking is pure observability and is
    orthogonal to whether a skill is ever curated. Lifecycle mutators
    (``set_state``, ``set_pinned``, ``mark_agent_created``) pass
    ``require_curation_eligible=True`` so they never write meaningless state
    onto a skill the curator can't manage (e.g. an ``archived`` flag on a
    hub-installed skill).
    Nz"skill_usage._mutate(%s) failed: %sTr   )r   r>   r   rX   r   r   r   r   r   ro   rp   )r   mutatorr  r   r  ru   s         r   _mutater
    sQ     Y$ 	-A*-M-M 	F 	 	<<D((:&&Cc4(( &#ooGCLLL"Dt	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  Y Y Y9:qSWXXXXXXXXXYs@   B' B' A&BB' BB' !B"B' '
C1CCc                .    dd}t          | |           dS )u   Bump view_count and last_viewed_at. Called from skill_view().

    Tracks every skill regardless of provenance — built-ins and hub skills
    included. Usage telemetry is observability, not a curation signal.
    r  rR   r   r   c                |    t          |                     d          pd          dz   | d<   t                      | d<   d S )Nrb   r   r&   rV   r_   rX   rF   r  s    r   _applyzbump_view.<locals>._apply3  s?     5 5 :;;a?L (

r   Nr  rR   r   r   r
  r   r  s     r   	bump_viewr  -  s.    + + + + Jr   c                .    dd}t          | |           dS )zBump use_count and last_used_at. Called when a skill is actively used
    (e.g. loaded into the prompt path or referenced from an assistant turn).

    Tracks every skill regardless of provenance.
    r  rR   r   r   c                |    t          |                     d          pd          dz   | d<   t                      | d<   d S )Nra   r   r&   rU   r  r  s    r   r  zbump_use.<locals>._apply?  s>    sww{338q99A=K&jjNr   Nr  r  r  s     r   bump_user  9  s.    ) ) ) ) Jr   c                .    dd}t          | |           dS )zBump patch_count and last_patched_at. Called from skill_manage (patch/edit).

    Tracks every skill regardless of provenance.
    r  rR   r   r   c                |    t          |                     d          pd          dz   | d<   t                      | d<   d S )Nrc   r   r&   rW   r  r  s    r   r  zbump_patch.<locals>._applyJ  s?     !7!7!<1==AM!)r   Nr  r  r  s     r   
bump_patchr  E  s.    
, , , , Jr   c                2    d	d}t          | |d           dS )
zOpt a skill created by skill_manage into curator management.

    Viewing or invoking a manually authored skill may still create telemetry,
    but only this explicit marker makes it eligible for automatic curation.
    r  rR   r   r   c                    d| d<   d S )Nr   r   r   r  s    r   r  z"mark_agent_created.<locals>._applyV  s    #Lr   Tr  Nr  r  r  s     r   mark_agent_createdr  P  s1    $ $ $ $J$??????r   r   c                    t           vrt                              d|            dS d
fd}t          | |d	           dS )zSet lifecycle state. No-op if *state* is invalid or the skill isn't
    curator-manageable (hub skills, or built-ins with pruning disabled).z"set_state: invalid state %r for %sNr  rR   r   r   c                r    | d<   t           k    rt                      | d<   d S t          k    rd | d<   d S d S )Nr   r   )STATE_ARCHIVEDrF   r   )r  r   s    r   r  zset_state.<locals>._applya  sN    GN""!)Cl""!%C #"r   Tr  r  )_VALID_STATESro   rp   r
  )r   r   r  s    ` r   	set_stater!  [  sg     M!!95*MMM& & & & & & J$??????r   r   c                8    dfd}t          | |d           d S )	Nr  rR   r   r   c                ,    t                    | d<   d S )Nr   )r   )r  r   s    r   r  zset_pinned.<locals>._applyk  s    VHr   Tr  r  r  )r   r   r  s    ` r   
set_pinnedr$  j  s<    % % % % % %J$??????r   c                   | sdS 	 t                      5  t                      }| |v r|| = t          |           ddd           dS # 1 swxY w Y   dS # t          $ r)}t                              d| |d           Y d}~dS d}~ww xY w)zFDrop a skill's usage entry entirely. Called when the skill is deleted.Nz!skill_usage.forget(%s) failed: %sTr   )r>   r   r   r   ro   rp   r  s      r   forgetr&  p  s    X 	! 	!<<DT!!$4   		! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	!
  X X X8*aRVWWWWWWWWWXs9   A %AA A

A A
A 
BBBTuple[bool, str]c                T   t          |           st          |           rdd|  dfS dd|  dfS t          |           }|dd|  dfS t                      }	 |                    dd           n# t
          $ r}dd	| fcY d}~S d}~ww xY w||j        z  }|                                r>||j         d
t          j	        t          j                                      d           z  }	 |                    |           np# t
          $ rc}ddl}	 |                    t!          |          t!          |                     n## t"          $ r}dd| fcY d}~cY d}~S d}~ww xY wY d}~nd}~ww xY wt%          |           rt'          |            t)          | t*                     dd| fS )as  Move a curator-eligible skill directory to ~/.hermes/skills/.archive/.

    Returns (ok, message). Never archives hub-installed skills. Bundled
    built-ins are only archivable when ``curator.prune_builtins`` is enabled;
    when one is archived, its name is added to the suppression list so the
    update-time re-seeder leaves it archived instead of restoring it.
    Fskill 'z!' is hub-installed; never archivezJ' is a bundled built-in; enable curator.prune_builtins to allow pruning itNz' not foundTr   zfailed to create archive dir: -z%Y%m%d%H%M%Sr   zfailed to archive: zarchived to )r   r   _find_skill_dirr@   r)   r8   rt   r,   r   rC   r   rD   strftimerenameshutilmoverA   r   r   r   r!  r  )r   r   r   ru   destr.  e2s          r   archive_skillr2    s]     
++ 
J'' 	RQJQQQQQ9j 9 9 9
 	

  
++I7
77777>>L;4$7777 ; ; ;:q:::::::::;
 ).(D{{}} hgg(,x|2L2L2U2UVd2e2eggg5 5 5 5	5KKID		2222 	5 	5 	5444444444444444	5 32222	5 * (J'''j.)))&&&&&sl   A/ /
B
9B?B
B
*D   
E-
E(0E ?E( 
E 
EE E(E-E  E((E-c                6    t                     rdd  dfS t                     rt                      sdd  dfS t                      }|                                sdS  fd|                    d          D             }|s0t           fd|                    d          D             d	
          }|sdd  dfS |d         }t                       z  }|                                rdd| fS 	 |                    |           nf# t          $ rY ddl
}	 |                    t          |          t          |                     n # t          $ r}dd| fcY d}~cY S d}~ww xY wY nw xY wt                      t           t                      d	d| fS )u<  Move an archived skill back to ~/.hermes/skills/. Restores to the flat
    top-level layout; original category nesting is NOT reconstructed.

    Refuses to restore under a name that now collides with a hub-installed
    skill — that would shadow the upstream version. Also refuses to restore
    over a bundled built-in UNLESS ``curator.prune_builtins`` is enabled (in
    which case built-ins are curator-managed and restoring is the documented
    way to lift a prune). Restoring clears any suppression entry so future
    updates may re-seed the built-in again.
    Fr)  zA' is now hub-installed; restore would shadow the upstream versionz;' is now bundled; restore would shadow the upstream version)Fzno archive directoryc                R    g | ]#}|                                 |j        k    !|$S r   r   rz   r   r   s     r   
<listcomp>z!restore_skill.<locals>.<listcomp>  s3    \\\

\qvQ[G[G[!G[G[G[r   *c                v    g | ]5}|                                 |j                             d           3|6S )r*  )r   rt   r   r5  s     r   r6  z!restore_skill.<locals>.<listcomp>  s^     D D D1

D v00J1A1A1ABBDQ D D Dr   T)reversez' not found in archiver   zdestination already exists: Nzfailed to restore: zrestored to )r   r   r   r@   r,   r   r   r   r-  r8   r.  r/  rA   r   r   r!  r   )r   r   
candidatessrcr0  r.  ru   s   `      r   restore_skillr<    sj    
## 
8j 8 8 8
 	
 * 
&=&?&? 
8j 8 8 8
 	
  >>L   -,,
 ]\\\\//44\\\J 
D D D D**3// D D D
 
 


  CB
BBBBB
Q-C==:%D{{}} <;T;;;;4

4 4 4 4	4KKC#d)),,,, 	4 	4 	4333333333333	4 -,4 :&&&j,'''&&&&&sB   4D
 
E-0E
	E-

E'E"E'E-"E''E-,E-Optional[Path]c                    t                      }|                                sdS |                    d          D ]:}t          |          rt	          ||j        j                  | k    r	|j        c S ;dS )zLocate the directory for a skill by its frontmatter `name:` field.

    Handles both flat (~/.hermes/skills/<skill>/SKILL.md) and category-nested
    (~/.hermes/skills/<category>/<skill>/SKILL.md) layouts.
    Nr~   r   )r   r,   r   r   r   r(   rt   )r   r   r   s      r   r+  r+    s     ==D;;== tJJz** # #!(++ 	Hx/CDDD
RR?""" S4r   List[Dict[str, Any]]c                    t                      } g }t                      D ]}|                     |          }t          |t                    }t          |t                    r|nt                      }t                      }|                                D ]\  }}|                    ||           d|i|d|i}	t          |	          |	d<   t          |	          |	d<   |
                    |	           |S )a  Return a list of {name, state, pinned, last_activity_at, ...}
    records for every curator-managed skill. Missing usage records are
    backfilled with defaults so callers can always index fields.

    Each row carries ``_persisted``: True when a real record exists in
    ``.usage.json``, False when the row is a fresh backfill (e.g. a built-in
    seen for the first time). The curator uses this to seed the inactivity
    clock instead of treating an unrecorded skill as ancient.
    rt   
_persistedlast_activity_atre   )r   r   rX   r   r   r   r   r   r^   re   r   )
r   rowsrt   r\   	persistedr  r   r{   r   rows
             r   agent_created_reportrF    s     <<D!#D.00 
 
hhtnnsD))	%/T%:%:OccJJLL 	! 	!DAqNN1a    t<s<L)<<"4S"9"9 .s 3 3CKr   c                J    t          |           rdS t          |           rdS dS )u   Classify a skill's origin: 'hub', 'bundled', or 'agent'.

    'agent' covers both agent-authored and local manually-authored skills —
    anything not seeded from the bundled repo or installed via the hub.
    r   r   r   )r   r   r   s    r   
provenancerH  !  s3     
## u* y7r   c                 $   t                      } |                                 sg S t                      }g }t                      }|                     d          D ]&}t          |          rt          ||j        j                  }||v r3|	                    |           |
                    |          }t          |t                    }t          |t                    r|nt                      }t                      }	|	                                D ]\  }
}|                    |
|           d|i|t!          |          |d}t#          |          |d<   t%          |          |d<   |                    |           (t)          |d           S )	u  Return usage telemetry for EVERY skill on disk, with provenance.

    Unlike ``agent_created_report()`` (which is scoped to curator-managed
    candidates), this surfaces all skills — bundled built-ins and
    hub-installed included — so callers can answer "how often is this skill
    used" independent of whether it's ever curated. Rows carry a
    ``provenance`` field ('agent' | 'bundled' | 'hub') and ``_persisted``
    (whether a real ``.usage.json`` record backs the row).
    r~   r   rt   )rH  rA  rB  re   c                    | d         S )Nrt   r   )rs    r   <lambda>zusage_report.<locals>.<lambda>T  s
    ai r   )r[   )r   r,   r   ri   r   r   r   r(   rt   rn   rX   r   r   r   r   r   rH  r^   re   r   r   )r   r   rC  seenr   rt   r\   rD  r  base_recr{   r   rE  s                r   usage_reportrO  .  s    ==D;;== 	<<D!#DDJJz**  !(++ 	8?3GHHH4<<hhtnnsD))	%/T%:%:Occ ??NN$$ 	! 	!DAqNN1a    D

 %T**#	
 
 
 #5S"9"9 .s 3 3C$//0000r   )r   r   )r   rA   )rG   r   r   rH   )rQ   rR   r   rS   )rQ   rR   r   r_   )r   rf   )r   r   )rr   rf   r   r   )r   rA   r   r   )r   r   )r   r   r   rA   r   rA   )r   rA   r   r   )rQ   r   r   r   )r   rR   )r   r   )r   r   r   r   )r   rA   r   rR   )r   rA   r  r   r   r   )r   rA   r   rA   r   r   )r   rA   r   r   r   r   )r   rA   r   r'  )r   rA   r   r=  )r   r?  )r   rA   r   rA   )M__doc__
__future__r   r   loggingr   r   
contextlibr   r   r   pathlibr   typingr   r	   r
   r   r   r   hermes_constantsr   agent.skill_utilsr   	getLogger__name__ro   r+   r*   ImportErrorr   STATE_STALEr  r   r   r   r>   r@   rF   rP   r^   re   rv   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!  r$  r&  r2  r<  r+  rF  rH  rO  r   r   r   <module>r\     s   0 # " " " " "   				  % % % % % % ' ' ' ' ' ' ' '       8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 , , , , , , 4 4 4 4 4 4		8	$	$ 
LLLL   E   	 {N;( ( ( () ) ) )      F& & & &2 2 2 2
 
 
 
   (      .# # # #L   *1 1 1 1   *W W W W,' ' ' '' ' ' ', , , ,^
J 
J 
J 
J   *( ( ( (5 5 5 5
8 8 8 8
   V V V V       (G G G G0
 
 
 
h h h h, LQ Y Y Y Y Y Y@	  	  	  	 	  	  	  	        @ @ @ @@ @ @ @@ @ @ @X X X X$/' /' /' /'d;' ;' ;' ;'|   *   4
 
 
 
&1 &1 &1 &1 &1 &1s6   A! !A<)A.-A<.A63A<5A66A<;A<