
    *"hjN.                        d Z ddlmZ ddlZddlZddlZddlmZ ddlm	Z	 ddl
mZmZmZmZ ddlmZ  ej"                  e      Zd	Zd
ZdZdZ G d d      Zy)u  
Workspace management for the agent engine under ``evolve_server``.

Handles preparing the local workspace directory that OpenClaw operates on,
snapshotting skill state before agent execution, and collecting changes
(new / modified skill bundles) after the agent finishes.

Key design note on OpenClaw bootstrap integration:
  OpenClaw's ``ensureAgentWorkspace()`` creates template bootstrap files
  (AGENTS.md, SOUL.md, USER.md, IDENTITY.md, …) using ``writeFileIfMissing``
  with ``flag: 'wx'`` — it will NOT overwrite files that already exist.
  We exploit this by pre-writing our own versions of these files during
  ``prepare()`` so OpenClaw picks them up as-is.
    )annotationsN)Path)Any)bundle_entrypoint_textbundle_tree_sha256read_skill_bundlewrite_skill_bundle   )parse_skill_contentuC  # Skill Evolution Agent

You are a **skill evolution engineer**. Your sole task is to analyze agent
session data in this workspace and evolve the skill library.

## First Step — ALWAYS

Read `EVOLVE_AGENTS.md` in this workspace **before doing anything else**.
It contains the full methodology, workspace layout, editing principles,
and all instructions you need.

```
cat EVOLVE_AGENTS.md
```

## Workspace Quick Reference

```
workspace/
├── EVOLVE_AGENTS.md   ← full evolution methodology (READ THIS FIRST)
├── sessions/          ← agent session JSON files to analyze
├── skills/            ← current skill library (read + write)
│   └── <name>/
│       ├── SKILL.md
│       ├── references/
│       ├── scripts/
│       ├── assets/
│       └── history/
├── manifest.json      ← skill manifest (read-only)
└── skill_registry.json
```

## Constraints

- **All file operations** stay within this workspace directory.
- Do NOT modify `sessions/`, `manifest.json`, or `skill_registry.json`.
- Write changes only inside `skills/<name>/` bundles.
- You may inspect and edit `SKILL.md`, `references/`, `scripts/`, `assets/`,
  `history/`, and other supporting files that belong to a skill.
- If there are no actionable patterns, make no changes — that is fine.
- Before finalizing any changed skill, complete the self-validation required
  by `EVOLVE_AGENTS.md`; if validation fails, keep editing or revert the
  change rather than leaving a known-failing skill in `skills/`.
- Record self-validation results in the paired `history/v<N>_evidence.md` file.

## Memory

You may use `memory/` and `MEMORY.md` for long-term notes across rounds.
Append daily observations to `memory/YYYY-MM-DD.md`. Keep `MEMORY.md` for
curated, high-level summaries of skill evolution decisions.
zYou analyze agent session data and evolve reusable skills.
Be methodical: read all sessions, aggregate patterns, then make targeted
changes. Prefer conservative edits over rewrites. Skip when evidence is weak.
u$   Skill Evolution Agent — SkillClaw
zFThe operator is the SkillClaw evolve server. Follow EVOLVE_AGENTS.md.
c                  b    e Zd ZdZd	dZd
dZ	 d	 	 	 	 	 	 	 	 	 	 	 ddZddZ	 	 	 	 ddZd
dZ	y)AgentWorkspacezFManages the filesystem workspace that the OpenClaw agent reads/writes.c                t    t        |      | _        | j                  dz  | _        | j                  dz  | _        y )Nsessionsskills)r   rootsessions_dir
skills_dir)selfr   s     @/root/.hermes/SkillClaw/evolve_server/engines/agent_workspace.py__init__zAgentWorkspace.__init__o   s.    J	 II
2))h.    c                    | j                   j                         rt        j                  | j                          | j                   j	                  dd       t
        j                  d| j                          y)z@Completely wipe and recreate the workspace (used in fresh mode).Tparentsexist_okz [AgentWorkspace] reset: wiped %sN)r   existsshutilrmtreemkdirloggerinfor   s    r   resetzAgentWorkspace.resett   sI    99MM$))$		t46		Br   Nc                   | j                   j                         rt        j                  | j                          | j                   j	                  dd       |D ]  }|j                  dd      }||j                  dd      |j                  dt        |j                  dg                   |j                  d	      t        |j                  d
      xs g       |j                  d      |j                  dd      |j                  dd      |j                  dd      d	}| j                   | dz  }	|	j                  t        j                  |dd      d        | j                  j	                  dd       t        | j                  j                               D ]7  }	|	j                         s|	j                  |vs#t        j                  |	       9 |j                         D ]C  \  }
}| j                  |
z  }t!        |t"              rt%        ||d       4t%        |d|id       E | j&                  dz  }|j                  t        j                  |dd      d       |r8| j&                  dz  }|j                  t        j                  |dd      d       | j&                  dz  }|j                  |d       t(        t*        t,        t.        d}|j                         D ]=  \  }}| j&                  |z  }|j                  |d       t0        j3                  d|       ? t0        j5                  dt        |      t        |      | j&                         y)a[  Populate the workspace with input data for the agent.

        Parameters
        ----------
        sessions:
            Raw session dicts drained from storage.
        existing_skills:
            ``{skill_name: bundle}`` for all current skills, where bundle is
            either a raw ``SKILL.md`` string or ``{rel_path: bytes}``.
        manifest:
            Current manifest dict ``{skill_name: metadata}``.
        agents_md:
            Full text of the AGENTS.md to write into the workspace.
        skill_registry_info:
            Optional registry metadata to expose to the agent.
        Tr   
session_idunknowntask_id 	num_turnsturns	aggregate_skills_referenced_avg_prm_has_tool_errorsF_trajectory_summary)	r%   r'   r)   r+   r,   r-   r.   r/   r0   z.jsonr
   )ensure_asciiindentzutf-8)encoding)cleanSKILL.mdzmanifest.jsonzskill_registry.jsonzEVOLVE_AGENTS.md)z	AGENTS.mdzSOUL.mdzIDENTITY.mdzUSER.mdz#[AgentWorkspace] wrote bootstrap %szY[AgentWorkspace] prepared: %d sessions, %d existing skills, bootstrap files written in %sN)r   r   r   r   r   getlensorted
write_textjsondumpsr   iterdiris_dirnameitems
isinstancedictr	   r   _EVOLVE_AGENTS_MD_EVOLVE_SOUL_MD_EVOLVE_IDENTITY_MD_EVOLVE_USER_MDr    debugr!   )r   r   existing_skillsmanifest	agents_mdskill_registry_infossidcompactpathr>   content	skill_dirmanifest_pathregistry_pathagents_md_pathbootstrap_filesfilenamefpaths                      r   preparezAgentWorkspace.prepare{   s   2 ##%MM$++,t<  	aA%%i0C!55B/UU;AEE'24F0GHUU;/&,QUU3G-H-NB&OEE*-$%EE*<e$D uu]B7EE*b1
G $$#e}4DOODJJwU1MX_O`	a" 	dT:4??2245 	$D{{}/!Ad#	$ -224 	QMD'$.I'4("9gTB"9z7.C4P	Q 		O3  JJxeA> 	! 	
  II(==M$$

.U1M  %  %77!!)g!>" +&.&	
 "1!6!6!8 	JHgII(EWw7LL>I	J
 	gM II		
r   c                   i }| j                   j                         s|S t        | j                   j                               D ];  }|j	                         st        |      }d|v s$t        |      ||j                  <   = |S )zEReturn ``{skill_name: tree_sha256}`` for all skills in the workspace.r5   )r   r   r8   r<   r=   r   r   r>   )r   snapshotrP   bundles       r   snapshot_skillszAgentWorkspace.snapshot_skills   sz    #%%%'O 7 7 9: 	FI##%&y1FV#+=f+E(	F r   c           
        | j                         }g }|j                         D ]  \  }}|j                  |      }||k(  rt        | j                  |z        }d|vrt
        j                  d|       Pt        |      }t        ||      }	|dnd}
|j                  ||
|	|||d       t
        j                  d|
||xs ddd	 |dd	         t        |      t        |      z
  }t        |      D ]  }t
        j                  d
|        |S )a  Compare current skills against *before_snapshot* and return changed/new skills.

        Returns a list of dicts, each with:
        - ``name``: skill name
        - ``action``: ``"create"`` or ``"improve"``
        - ``skill``: parsed skill dict (name, description, content, ...)
        - ``raw_md``: the raw SKILL.md text
        - ``bundle_files``: full bundle contents ``{rel_path: bytes}``
        - ``tree_sha256``: directory-level fingerprint
        r5   zA[AgentWorkspace] changed skill '%s' is missing SKILL.md; skippingNcreateimprove)r>   actionskillraw_mdbundle_filestree_sha256z7[AgentWorkspace] detected %s: skill '%s' (sha %s -> %s)new   uF   [AgentWorkspace] skill '%s' was deleted by agent — ignoring deletion)r[   r?   r6   r   r   r    warningr   r   appendr!   setr8   )r   before_snapshotafter_snapshotchangesr>   	after_sha
before_sharb   ra   parsedr_   deleteds               r   collect_changeszAgentWorkspace.collect_changes   s7    --/(*-335 !	OD)(,,T2JY&,T__t-CDL-W +L9F(v6F!+!3XFNN $#$$0#,	 KKI$ucr*#27!	F o&^)<<7O 	DNNX	 r   c                    | j                   j                         r=t        j                  | j                          | j                   j	                  dd       yy)z9Remove session files from the workspace after processing.Tr   N)r   r   r   r   r   r"   s    r   cleanup_sessionszAgentWorkspace.cleanup_sessions2  sD    ##%MM$++,##D4#@ &r   )r   z
str | PathreturnNone)rs   rt   )N)r   z
list[dict]rG   z3dict[str, str | dict[str, bytes | bytearray | str]]rH   zdict[str, dict]rI   strrJ   zdict[str, Any] | Noners   rt   )rs   dict[str, str])ri   rv   rs   zlist[dict[str, Any]])
__name__
__module____qualname____doc__r   r#   rW   r[   rp   rr    r   r   r   r   l   s    P/
C 6:k
k
 Mk
 "	k

 k
 3k
 
k
Z;'; 
;zAr   r   )rz   
__future__r   r:   loggingr   pathlibr   typingr   skillclaw.skill_bundler   r   r   r	   
core.utilsr   	getLoggerrw   r    rB   rC   rD   rE   r   r{   r   r   <module>r      sl    #       -			8	$3 j 
JA JAr   