forked from HKUDS/OpenSpace
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevolver.py
More file actions
1393 lines (1187 loc) · 56.7 KB
/
Copy pathevolver.py
File metadata and controls
1393 lines (1187 loc) · 56.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""SkillEvolver — execute skill evolution actions.
Three evolution types:
FIX — repair broken/outdated instructions (in-place, same name)
DERIVED — create enhanced version from existing skill (new directory)
CAPTURED — capture novel reusable pattern from execution (brand new skill)
Three trigger sources:
1. Post-analysis — analyzer found evolution suggestions for a specific task
2. Tool degradation — ToolQualityManager detected problematic tools
3. Metric monitor — periodic scan of skill health indicators
All triggers produce an EvolutionContext → evolve() → LLM agent loop →
apply-retry cycle → validation → store persistence.
"""
from __future__ import annotations
import asyncio
import copy
import json
import re
import shutil
import uuid
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set
from openspace.prompts import SkillEnginePrompts
from openspace.utils.logging import Logger
from .evolution.models import (
EvolutionContext,
EvolutionTrigger,
_sanitize_skill_name,
)
from .evolution.orchestrator import (
dispatch_evolution as _dispatch_evolution,
execute_contexts as _execute_contexts_impl,
log_background_result as _log_background_result_impl,
schedule_background as _schedule_background_impl,
)
from .patch import (
SKILL_FILENAME,
PatchType,
SkillEditResult,
collect_skill_snapshot,
create_skill,
derive_skill,
fix_skill,
)
from .registry import write_skill_id
from .skill_utils import (
extract_change_summary as _extract_change_summary,
)
from .skill_utils import (
get_frontmatter_field as _extract_frontmatter_field,
)
from .skill_utils import (
set_frontmatter_field as _set_frontmatter_field,
)
from .skill_utils import (
strip_markdown_fences as _strip_markdown_fences,
)
from .skill_utils import (
truncate as _truncate,
)
from .skill_utils import (
validate_skill_dir as _validate_skill_dir,
)
from .store import SkillStore
from .types import (
EvolutionSuggestion,
EvolutionType,
ExecutionAnalysis,
SkillCategory,
SkillLineage,
SkillOrigin,
SkillRecord,
)
if TYPE_CHECKING:
from openspace.grounding.core.quality.types import ToolQualityRecord
from openspace.grounding.core.tool import BaseTool
from openspace.llm import LLMClient
from .registry import SkillRegistry
logger = Logger.get_logger(__name__)
EVOLUTION_COMPLETE = SkillEnginePrompts.EVOLUTION_COMPLETE
EVOLUTION_FAILED = SkillEnginePrompts.EVOLUTION_FAILED
_SKILL_CONTENT_MAX_CHARS = 12_000 # Max chars of SKILL.md in evolution prompt
_ANALYSIS_CONTEXT_MAX = 5 # Max recent analyses to include in prompt
_ANALYSIS_NOTE_MAX_CHARS = 500 # Per-analysis note truncation
# Agent loop / retry constants
_MAX_EVOLUTION_ITERATIONS = 5 # Max tool-calling rounds for evolution agent
_MAX_EVOLUTION_ATTEMPTS = 3 # Max apply-retry attempts per evolution
# Rule-based thresholds for candidate screening (relaxed — LLM confirms)
_FALLBACK_THRESHOLD = 0.4 # Relaxed from 0.5 for wider screening
_LOW_COMPLETION_THRESHOLD = 0.35 # Relaxed from 0.3
_HIGH_APPLIED_FOR_FIX = 0.4 # Relaxed from 0.5
_MODERATE_EFFECTIVE_THRESHOLD = 0.55 # Relaxed from 0.5
_MIN_APPLIED_FOR_DERIVED = 0.25 # Relaxed from 0.3
class SkillEvolver:
"""Execute skill evolution actions.
Single entry point: ``evolve()`` takes an EvolutionContext, runs an
LLM agent loop (with optional tool use), applies the edit with retry,
validates the result, and persists the new SkillRecord via ``SkillStore``.
Concurrency:
``max_concurrent`` controls the semaphore that throttles parallel
evolutions across all trigger types. File I/O is synchronous and
naturally serialized by the event loop; only LLM calls run in
parallel.
Anti-loop (Trigger 2 — tool degradation):
``_addressed_degradations`` is a ``Dict[str, Set[str]]`` mapping
``tool_key → {skill_id, …}`` for skills that have already been
evolved to handle a specific tool's degradation. At the start of
each ``process_tool_degradation`` call, tools that are no longer
in the problematic list are pruned — so if a tool **recovers and
then degrades again**, all its dependent skills are re-evaluated.
Anti-loop (Trigger 3 — metric check):
Newly-evolved skills have ``total_selections=0``, requiring
``min_selections`` (default 5) fresh data points before being
re-evaluated. This is data-driven and needs no time-based guard.
Background:
Trigger 2 and 3 are always launched as ``asyncio.Task``s via
``schedule_background()`` so they never block the main flow.
"""
def __init__(
self,
store: SkillStore,
registry: "SkillRegistry",
llm_client: "LLMClient",
model: Optional[str] = None,
available_tools: Optional[List["BaseTool"]] = None,
*,
max_concurrent: int = 3,
) -> None:
self._store = store
self._registry = registry
self._llm_client = llm_client
self._model = model
self._available_tools: List["BaseTool"] = available_tools or []
# Concurrency: semaphore limits parallel LLM sessions
self._max_concurrent = max(1, max_concurrent)
self._semaphore = asyncio.Semaphore(self._max_concurrent)
# Anti-loop for Trigger 2: tracks which skills have already been
# evolved for each degraded tool. Keyed by tool_key.
# Pruned when a tool leaves the problematic list (= recovered).
self._addressed_degradations: Dict[str, Set[str]] = {}
# Track background tasks so they can be awaited on shutdown.
self._background_tasks: Set[asyncio.Task] = set()
def set_available_tools(self, tools: List["BaseTool"]) -> None:
"""Update the tools available for evolution agent loops."""
self._available_tools = list(tools)
async def wait_background(self) -> None:
"""Await all outstanding background evolution tasks.
Call this during shutdown / cleanup to ensure nothing is lost.
"""
if self._background_tasks:
logger.info(f"Waiting for {len(self._background_tasks)} background evolution task(s) to finish...")
await asyncio.gather(*self._background_tasks, return_exceptions=True)
self._background_tasks.clear()
async def evolve(self, ctx: EvolutionContext) -> Optional[SkillRecord]:
"""Execute one evolution action. Returns new SkillRecord or None.
The global semaphore is NOT acquired here — it is managed at the
trigger-method level so the concurrency limit covers the whole batch.
"""
return await _dispatch_evolution(self, ctx)
# Trigger 1: post-analysis
async def process_analysis(
self,
analysis: ExecutionAnalysis,
) -> List[SkillRecord]:
"""Process all evolution suggestions from a completed analysis.
Called immediately after ``ExecutionAnalyzer.analyze_execution()``.
Each suggestion becomes one evolution action, executed in parallel
(throttled by semaphore).
"""
if not analysis.candidate_for_evolution:
return []
# Build contexts first (cheap, no LLM calls)
contexts: List[EvolutionContext] = []
for suggestion in analysis.evolution_suggestions:
ctx = self._build_context_from_analysis(analysis, suggestion)
if ctx is not None:
contexts.append(ctx)
if not contexts:
return []
results = await self._execute_contexts(contexts, "analysis")
if results:
names = [r.name for r in results]
logger.info(f"[Trigger:analysis] Evolved {len(results)} skill(s): {names} from task {analysis.task_id}")
return results
# Trigger 2: tool quality degradation
async def process_tool_degradation(
self,
problematic_tools: List["ToolQualityRecord"],
) -> List[SkillRecord]:
"""Fix skills that depend on degraded tools.
Two-phase: rule-based candidate screening → LLM confirmation.
Anti-loop (state-driven):
``_addressed_degradations[tool_key]`` records skill names that
have already been evolved for that tool's degradation. They are
skipped on subsequent calls as long as the tool stays degraded.
At the start of each call, tools that **recovered** (no longer
in ``problematic_tools``) are pruned from the dict — so if the
tool degrades again later, all dependent skills are re-evaluated.
"""
if not problematic_tools:
return []
# Prune recovered tools: if a tool_key used to be tracked but is
# no longer in the current problematic list, it recovered — clear
# its addressed set so future re-degradation gets a fresh pass.
current_tool_keys = {t.tool_key for t in problematic_tools}
recovered = [k for k in self._addressed_degradations if k not in current_tool_keys]
for k in recovered:
logger.debug(f"[Trigger:tool_degradation] Tool '{k}' recovered, clearing addressed set")
del self._addressed_degradations[k]
# Phase 1: screen & confirm candidates
confirmed_contexts: List[EvolutionContext] = []
seen_skills: set = set() # de-dup by skill_id within this call
for tool_rec in problematic_tools:
addressed = self._addressed_degradations.get(tool_rec.tool_key, set())
skill_ids = self._store.find_skills_by_tool(tool_rec.tool_key)
for skill_id in skill_ids:
skill_record = self._store.load_record(skill_id)
if not skill_record or not skill_record.is_active:
continue
# De-duplicate by skill_id within this call
if skill_record.skill_id in seen_skills:
continue
seen_skills.add(skill_record.skill_id)
# Anti-loop: already evolved for this tool's degradation
if skill_record.skill_id in addressed:
logger.debug(
f"[Trigger:tool_degradation] Skipping '{skill_record.skill_id}' "
f"(already addressed for tool '{tool_rec.tool_key}')"
)
continue
recent = self._store.load_analyses(skill_id=skill_record.skill_id, limit=_ANALYSIS_CONTEXT_MAX)
content = self._load_skill_content(skill_record)
if not content:
continue
issue_summary = (
f"Tool `{tool_rec.tool_key}` degraded — "
f"recent success rate: {tool_rec.recent_success_rate:.0%}, "
f"total calls: {tool_rec.total_calls}, "
f"LLM flagged: {tool_rec.llm_flagged_count} time(s)."
)
direction = (
f"Tool `{tool_rec.tool_key}` has degraded "
f"(success_rate={tool_rec.recent_success_rate:.0%}). "
f"Update skill instructions to handle this tool's "
f"failures gracefully or suggest alternatives."
)
# LLM confirmation: ask whether this skill truly needs fixing
confirmed = await self._llm_confirm_evolution(
skill_record=skill_record,
skill_content=content,
proposed_type=EvolutionType.FIX,
proposed_direction=direction,
trigger_context=f"Tool degradation: {issue_summary}",
recent_analyses=recent,
)
if not confirmed:
logger.debug(
f"[Trigger:tool_degradation] LLM rejected evolution "
f"for skill '{skill_record.skill_id}' (tool={tool_rec.tool_key})"
)
# Even if LLM rejected, mark as addressed to avoid
# repeated LLM confirmation calls on every cycle.
self._addressed_degradations.setdefault(tool_rec.tool_key, set()).add(skill_record.skill_id)
continue
skill_dir = Path(skill_record.path).parent if skill_record.path else None
confirmed_contexts.append(
EvolutionContext(
trigger=EvolutionTrigger.TOOL_DEGRADATION,
suggestion=EvolutionSuggestion(
evolution_type=EvolutionType.FIX,
target_skill_ids=[skill_record.skill_id],
direction=direction,
),
skill_records=[skill_record],
skill_contents=[content],
skill_dirs=[skill_dir] if skill_dir else [],
recent_analyses=recent,
tool_issue_summary=issue_summary,
available_tools=self._available_tools,
)
)
# Mark as addressed regardless of whether evolution succeeds
# (if it fails, Trigger 1/3 can pick it up on new data)
self._addressed_degradations.setdefault(tool_rec.tool_key, set()).add(skill_record.skill_id)
if not confirmed_contexts:
return []
# Phase 2: execute confirmed evolutions in parallel
results = await self._execute_contexts(confirmed_contexts, "tool_degradation")
return results
# Trigger 3: periodic metric check
async def process_metric_check(
self,
min_selections: int = 5,
) -> List[SkillRecord]:
"""Scan active skills and evolve those with poor health metrics.
Two-phase: rule-based candidate screening (relaxed thresholds) →
LLM confirmation. Called periodically (e.g., every N executions).
Only considers skills with enough data (``min_selections``).
Anti-loop (data-driven): newly-evolved skills start with
``total_selections=0``, so they naturally need ``min_selections``
fresh executions before being re-evaluated. No time-based
cooldown is needed.
"""
# Phase 1: screen & confirm candidates
confirmed_contexts: List[EvolutionContext] = []
all_active = self._store.load_active()
for skill_id, record in all_active.items():
if record.total_selections < min_selections:
continue
evo_type, direction = self._diagnose_skill_health(record)
if evo_type is None:
continue
content = self._load_skill_content(record)
if not content:
continue
recent = self._store.load_analyses(skill_id=record.skill_id, limit=_ANALYSIS_CONTEXT_MAX)
metric_summary = (
f"selections={record.total_selections}, "
f"applied_rate={record.applied_rate:.0%}, "
f"completion_rate={record.completion_rate:.0%}, "
f"effective_rate={record.effective_rate:.0%}, "
f"fallback_rate={record.fallback_rate:.0%}"
)
# LLM confirmation: ask whether this skill truly needs evolution
confirmed = await self._llm_confirm_evolution(
skill_record=record,
skill_content=content,
proposed_type=evo_type,
proposed_direction=direction,
trigger_context=f"Metric check: {metric_summary}",
recent_analyses=recent,
)
if not confirmed:
logger.debug(
f"[Trigger:metric_monitor] LLM rejected evolution for skill '{record.name}' ({evo_type.value})"
)
continue
skill_dir = Path(record.path).parent if record.path else None
confirmed_contexts.append(
EvolutionContext(
trigger=EvolutionTrigger.METRIC_MONITOR,
suggestion=EvolutionSuggestion(
evolution_type=evo_type,
target_skill_ids=[record.skill_id],
direction=direction,
),
skill_records=[record],
skill_contents=[content],
skill_dirs=[skill_dir] if skill_dir else [],
recent_analyses=recent,
metric_summary=metric_summary,
available_tools=self._available_tools,
)
)
if not confirmed_contexts:
return []
# Phase 2: execute confirmed evolutions in parallel
results = await self._execute_contexts(confirmed_contexts, "metric_monitor")
return results
async def _execute_contexts(
self,
contexts: List[EvolutionContext],
trigger_label: str,
) -> List[SkillRecord]:
"""Execute a list of evolution contexts in parallel (throttled).
Used by all three triggers after building/confirming contexts.
"""
return await _execute_contexts_impl(self, contexts, trigger_label)
def schedule_background(
self,
coro,
*,
label: str = "background_evolution",
) -> Optional[asyncio.Task]:
"""Launch a coroutine as a background ``asyncio.Task``.
Used by the caller (``OpenSpace._maybe_evolve_quality``) when
``background_triggers`` is True. The task is tracked so it can
be awaited on shutdown via ``wait_background()``.
"""
return _schedule_background_impl(
self._background_tasks, coro, label=label,
)
_log_background_result = staticmethod(_log_background_result_impl)
# LLM confirmation for Trigger 2/3
async def _llm_confirm_evolution(
self,
*,
skill_record: SkillRecord,
skill_content: str,
proposed_type: EvolutionType,
proposed_direction: str,
trigger_context: str,
recent_analyses: List[ExecutionAnalysis],
) -> bool:
"""Ask LLM to confirm whether a rule-based evolution candidate
truly needs evolution.
Returns True if LLM agrees, False otherwise.
This prevents false positives from rigid threshold-based rules.
The confirmation prompt and response are recorded to
``conversations.jsonl`` under agent_name="SkillEvolver.confirm".
"""
from openspace.recording import RecordingManager
analysis_ctx = self._format_analysis_context(recent_analyses)
prompt = SkillEnginePrompts.evolution_confirm(
skill_id=skill_record.skill_id,
skill_content=_truncate(skill_content, _SKILL_CONTENT_MAX_CHARS // 2),
proposed_type=proposed_type.value,
proposed_direction=proposed_direction,
trigger_context=trigger_context,
recent_analyses=analysis_ctx,
)
confirm_messages = [{"role": "user", "content": prompt}]
# Record confirmation setup
await RecordingManager.record_conversation_setup(
setup_messages=copy.deepcopy(confirm_messages),
agent_name="SkillEvolver.confirm",
extra={
"skill_id": skill_record.skill_id,
"proposed_type": proposed_type.value,
"trigger_context": trigger_context[:200],
},
)
model = self._model or self._llm_client.model
try:
result = await self._llm_client.complete(
messages=confirm_messages,
model=model,
)
content = result["message"].get("content", "").strip().lower()
confirmed = self._parse_confirmation(content)
# Record confirmation response
await RecordingManager.record_iteration_context(
iteration=1,
delta_messages=[{"role": "assistant", "content": content}],
response_metadata={
"has_tool_calls": False,
"confirmed": confirmed,
},
agent_name="SkillEvolver.confirm",
)
return confirmed
except Exception as e:
logger.warning(f"LLM confirmation failed, defaulting to skip: {e}")
return False
@staticmethod
def _parse_confirmation(response: str) -> bool:
"""Parse LLM confirmation response (expects JSON with 'proceed' field)."""
# Try JSON parse first
try:
# Strip markdown fences
cleaned = response.strip()
if cleaned.startswith("```"):
cleaned = re.sub(r"^```(?:json)?\s*\n?", "", cleaned)
cleaned = re.sub(r"\n?```\s*$", "", cleaned)
data = json.loads(cleaned)
if isinstance(data, dict):
return bool(data.get("proceed", False))
except (json.JSONDecodeError, ValueError):
pass
# Fallback: look for keywords.
# - yes/no use strict word boundaries to avoid false positives
# (e.g. "know" matching "no").
# - confirm/reject/skip use stem-style matching so that common
# LLM variants like "confirmed", "rejected", "skipping" still
# parse correctly.
_wb = re.search # shorthand
if (
any(w in response for w in ('"proceed": true', "proceed: true"))
or _wb(r"\byes\b", response)
or _wb(r"\bconfirm\w*\b", response)
):
return True
if (
any(w in response for w in ('"proceed": false', "proceed: false"))
or _wb(r"\bno\b", response)
or _wb(r"\breject\w*\b", response)
or _wb(r"\bskip\w*\b", response)
):
return False
# Default: skip — ambiguous response should not trigger costly evolution
logger.debug("LLM confirmation response was ambiguous, defaulting to skip")
return False
async def _evolve_fix(self, ctx: EvolutionContext) -> Optional[SkillRecord]:
"""In-place fix: same name, same directory, new version record.
Uses agent loop for information gathering + apply-retry cycle.
"""
if not ctx.skill_records or not ctx.skill_contents or not ctx.skill_dirs:
logger.warning("FIX requires exactly 1 parent (skill_records/contents/dirs)")
return None
parent = ctx.skill_records[0]
parent_content = ctx.skill_contents[0]
parent_dir = ctx.skill_dirs[0]
# Build prompt with full directory content for multi-file skills
dir_content = self._format_skill_dir_content(parent_dir)
prompt = SkillEnginePrompts.evolution_fix(
current_content=_truncate(dir_content or parent_content, _SKILL_CONTENT_MAX_CHARS),
direction=ctx.suggestion.direction,
failure_context=self._format_analysis_context(ctx.recent_analyses),
tool_issue_summary=ctx.tool_issue_summary,
metric_summary=ctx.metric_summary,
)
# Agent loop: LLM can gather information via tools before generating edits
new_content = await self._run_evolution_loop(prompt, ctx)
if not new_content:
return None
# Extract change_summary from LLM output (first line if prefixed)
new_content, change_summary = _extract_change_summary(new_content)
# Apply-retry cycle
edit_result = await self._apply_with_retry(
apply_fn=lambda content: fix_skill(parent_dir, content, PatchType.AUTO),
initial_content=new_content,
skill_dir=parent_dir,
ctx=ctx,
prompt=prompt,
)
if edit_result is None or not edit_result.ok:
return None
# Re-read name/description from the updated SKILL.md on disk —
# the LLM may have refined the description (or even name) during the fix.
updated_skill_md = edit_result.content_snapshot.get(SKILL_FILENAME, "")
fixed_name = _extract_frontmatter_field(updated_skill_md, "name") or parent.name
fixed_desc = _extract_frontmatter_field(updated_skill_md, "description") or parent.description
new_id = f"{fixed_name}__v{parent.lineage.generation + 1}_{uuid.uuid4().hex[:8]}"
model = self._model or self._llm_client.model
new_record = SkillRecord(
skill_id=new_id,
name=fixed_name,
description=fixed_desc,
path=parent.path,
category=parent.category,
tags=list(parent.tags),
visibility=parent.visibility,
creator_id=parent.creator_id,
lineage=SkillLineage(
origin=SkillOrigin.FIXED,
generation=parent.lineage.generation + 1,
parent_skill_ids=[parent.skill_id],
source_task_id=ctx.source_task_id,
change_summary=change_summary or ctx.suggestion.direction,
content_diff=edit_result.content_diff,
content_snapshot=edit_result.content_snapshot,
created_by=model,
),
tool_dependencies=list(parent.tool_dependencies),
critical_tools=list(parent.critical_tools),
)
await self._store.evolve_skill(new_record, [parent.skill_id])
# Stamp the new skill_id into the sidecar file so next discover()
write_skill_id(parent_dir, new_id)
from .registry import SkillMeta
new_meta = SkillMeta(
skill_id=new_id,
name=fixed_name,
description=fixed_desc,
path=Path(parent.path),
)
self._registry.update_skill(parent.skill_id, new_meta)
logger.info(
f"FIX: {parent.name} gen{parent.lineage.generation} → gen{new_record.lineage.generation} [{new_id}]"
)
return new_record
async def _evolve_derived(self, ctx: EvolutionContext) -> Optional[SkillRecord]:
"""Create enhanced version in a new directory.
Supports single-parent (enhance) and multi-parent (merge/fuse).
Uses agent loop for information gathering + apply-retry cycle.
"""
if not ctx.skill_records or not ctx.skill_contents or not ctx.skill_dirs:
logger.warning("DERIVED requires at least one parent skill_record + content + dir")
return None
first_parent = ctx.skill_records[0] # For fallback defaults only
is_merge = len(ctx.skill_records) > 1
# Build prompt — include all parent contents for multi-parent merge
if is_merge:
parent_sections = []
for i, (rec, sd) in enumerate(zip(ctx.skill_records, ctx.skill_dirs)):
dir_content = self._format_skill_dir_content(sd)
label = f"Parent {i + 1}: {rec.name}"
parent_sections.append(
f"## {label}\n{_truncate(dir_content or ctx.skill_contents[i], _SKILL_CONTENT_MAX_CHARS)}"
)
combined_content = "\n\n---\n\n".join(parent_sections)
else:
dir_content = self._format_skill_dir_content(ctx.skill_dirs[0])
combined_content = _truncate(dir_content or ctx.skill_contents[0], _SKILL_CONTENT_MAX_CHARS)
prompt = SkillEnginePrompts.evolution_derived(
parent_content=combined_content,
direction=ctx.suggestion.direction,
execution_insights=self._format_analysis_context(ctx.recent_analyses),
metric_summary=ctx.metric_summary,
)
# Agent loop
new_content = await self._run_evolution_loop(prompt, ctx)
if not new_content:
return None
new_content, change_summary = _extract_change_summary(new_content)
# Determine new skill name from frontmatter, or generate one
new_name = _extract_frontmatter_field(new_content, "name")
if not new_name or new_name == first_parent.name:
suffix = "-merged" if is_merge else "-enhanced"
new_name = f"{first_parent.name}{suffix}"
new_content = _set_frontmatter_field(new_content, "name", new_name)
# Cap name length to avoid ever-growing chains like
# "panel-component-enhanced-enhanced-merged_abc123"
new_name = _sanitize_skill_name(new_name)
new_content = _set_frontmatter_field(new_content, "name", new_name)
# Directory name always matches the skill name
target_dir = ctx.skill_dirs[0].parent / new_name
if target_dir.exists():
new_name = f"{new_name}-{uuid.uuid4().hex[:6]}"
new_name = _sanitize_skill_name(new_name)
target_dir = ctx.skill_dirs[0].parent / new_name
new_content = _set_frontmatter_field(new_content, "name", new_name)
# Apply-retry cycle for derive_skill
edit_result = await self._apply_with_retry(
apply_fn=lambda content: derive_skill(ctx.skill_dirs, target_dir, content, PatchType.AUTO),
initial_content=new_content,
skill_dir=target_dir,
ctx=ctx,
prompt=prompt,
cleanup_on_retry=target_dir, # Remove failed target dir before retry
)
if edit_result is None or not edit_result.ok:
return None
# Extract description from new content
new_desc = _extract_frontmatter_field(new_content, "description") or first_parent.description
# Collect parent info from ALL parents
parent_ids = [r.skill_id for r in ctx.skill_records]
max_gen = max(r.lineage.generation for r in ctx.skill_records)
all_tool_deps: set = set()
all_critical: set = set()
all_tags: set = set()
for rec in ctx.skill_records:
all_tool_deps.update(rec.tool_dependencies)
all_critical.update(rec.critical_tools)
all_tags.update(rec.tags)
new_id = f"{new_name}__v0_{uuid.uuid4().hex[:8]}"
model = self._model or self._llm_client.model
new_record = SkillRecord(
skill_id=new_id,
name=new_name,
description=new_desc,
path=str(target_dir / SKILL_FILENAME),
category=ctx.suggestion.category or first_parent.category,
tags=sorted(all_tags),
visibility=first_parent.visibility,
creator_id=first_parent.creator_id,
lineage=SkillLineage(
origin=SkillOrigin.DERIVED,
generation=max_gen + 1,
parent_skill_ids=parent_ids,
source_task_id=ctx.source_task_id,
change_summary=change_summary or ctx.suggestion.direction,
content_diff=edit_result.content_diff,
content_snapshot=edit_result.content_snapshot,
created_by=model,
),
tool_dependencies=sorted(all_tool_deps),
critical_tools=sorted(all_critical),
)
await self._store.evolve_skill(new_record, parent_ids)
# Stamp skill_id sidecar so discover() uses this ID on restart
write_skill_id(target_dir, new_id)
# Register the new skill so it's immediately available for selection
from .registry import SkillMeta
new_meta = SkillMeta(
skill_id=new_id,
name=new_name,
description=new_desc,
path=target_dir / SKILL_FILENAME,
)
self._registry.add_skill(new_meta)
parent_names = " + ".join(r.name for r in ctx.skill_records)
logger.info(f"DERIVED: {parent_names} → {new_name} [{new_id}]")
return new_record
async def _evolve_captured(self, ctx: EvolutionContext) -> Optional[SkillRecord]:
"""Capture a novel pattern as a brand-new skill.
Uses agent loop for information gathering + apply-retry cycle.
"""
# Build prompt and call LLM
# For CAPTURED, we use analyses as context (the tasks where the pattern was observed)
task_descriptions = []
for a in ctx.recent_analyses[:_ANALYSIS_CONTEXT_MAX]:
if a.execution_note:
task_descriptions.append(f"- task={a.task_id}: {a.execution_note[:200]}")
prompt = SkillEnginePrompts.evolution_captured(
direction=ctx.suggestion.direction,
category=(ctx.suggestion.category or SkillCategory.WORKFLOW).value,
execution_highlights="\n".join(task_descriptions) if task_descriptions else "(no task context available)",
)
# Agent loop
new_content = await self._run_evolution_loop(prompt, ctx)
if not new_content:
return None
new_content, change_summary = _extract_change_summary(new_content)
# Extract name/description from the generated content
new_name = _extract_frontmatter_field(new_content, "name")
new_desc = _extract_frontmatter_field(new_content, "description")
if not new_name:
logger.warning("CAPTURED: LLM did not produce a valid skill name")
return None
# Sanitize name (enforce length limit + valid chars)
new_name = _sanitize_skill_name(new_name)
new_content = _set_frontmatter_field(new_content, "name", new_name)
# Create new skill directory via create_skill (handles multi-file FULL)
skill_dirs = self._registry._skill_dirs
if not skill_dirs:
logger.warning("CAPTURED: no skill directories configured")
return None
# Directory name always matches the skill name
base_dir = skill_dirs[0] # Primary user skill directory
target_dir = base_dir / new_name
if target_dir.exists():
new_name = f"{new_name}-{uuid.uuid4().hex[:6]}"
new_name = _sanitize_skill_name(new_name)
target_dir = base_dir / new_name
new_content = _set_frontmatter_field(new_content, "name", new_name)
# Apply-retry cycle for create_skill
edit_result = await self._apply_with_retry(
apply_fn=lambda content: create_skill(target_dir, content, PatchType.AUTO),
initial_content=new_content,
skill_dir=target_dir,
ctx=ctx,
prompt=prompt,
cleanup_on_retry=target_dir,
)
if edit_result is None or not edit_result.ok:
return None
snapshot = edit_result.content_snapshot
add_all_diff = edit_result.content_diff
new_id = f"{new_name}__v0_{uuid.uuid4().hex[:8]}"
model = self._model or self._llm_client.model
new_record = SkillRecord(
skill_id=new_id,
name=new_name,
description=new_desc or new_name,
path=str(target_dir / SKILL_FILENAME),
category=ctx.suggestion.category or SkillCategory.WORKFLOW,
lineage=SkillLineage(
origin=SkillOrigin.CAPTURED,
generation=0,
parent_skill_ids=[],
source_task_id=ctx.source_task_id,
change_summary=change_summary or ctx.suggestion.direction,
content_diff=add_all_diff,
content_snapshot=snapshot,
created_by=model,
),
)
await self._store.save_record(new_record)
# Stamp skill_id sidecar so discover() uses this ID on restart
write_skill_id(target_dir, new_id)
# Register the new skill so it's immediately available
from .registry import SkillMeta
new_meta = SkillMeta(
skill_id=new_id,
name=new_name,
description=new_desc or new_name,
path=target_dir / SKILL_FILENAME,
)
self._registry.add_skill(new_meta)
logger.info(f"CAPTURED: {new_name} [{new_id}]")
return new_record
async def _run_evolution_loop(
self,
prompt: str,
ctx: EvolutionContext,
) -> Optional[str]:
"""Run evolution as a token-driven agent loop.
Modeled after ``GroundingAgent.process()`` — the loop continues
until the LLM outputs an explicit completion/failure token, NOT
based on whether tools were called.
Termination signals (checked every iteration, regardless of tool use):
- ``EVOLUTION_COMPLETE`` in assistant content → success, return edit.
- ``EVOLUTION_FAILED`` in assistant content → failure, return None.
Tool availability:
- Iterations 1 … N-1: tools enabled (LLM may gather information).
- Iteration N (final): tools disabled, LLM must output a decision.
Each non-final iteration without a token gets a nudge message
telling the LLM which iteration it is on and how many remain.
Conversations are recorded to ``conversations.jsonl`` via
``RecordingManager`` (agent_name="SkillEvolver") so the full
evolution dialogue is preserved for debugging and replay.
"""
from openspace.recording import RecordingManager
model = self._model or self._llm_client.model
# Merge tools from context and instance-level
evolution_tools: List["BaseTool"] = list(ctx.available_tools or [])
if not evolution_tools:
evolution_tools = list(self._available_tools)
messages: List[Dict[str, Any]] = [
{"role": "user", "content": prompt},
]
# Record initial conversation setup
await RecordingManager.record_conversation_setup(
setup_messages=copy.deepcopy(messages),
tools=evolution_tools if evolution_tools else None,
agent_name="SkillEvolver",
extra={
"evolution_type": ctx.suggestion.evolution_type.value,
"trigger": ctx.trigger.value,
"target_skills": ctx.suggestion.target_skill_ids,
},
)
for iteration in range(_MAX_EVOLUTION_ITERATIONS):
is_last = iteration == _MAX_EVOLUTION_ITERATIONS - 1
# Snapshot message count before any additions + LLM call
msg_count_before = len(messages)
# Final round: disable tools and force a decision
if is_last:
messages.append(
{
"role": "system",
"content": (
f"This is your FINAL round (iteration "
f"{iteration + 1}/{_MAX_EVOLUTION_ITERATIONS}) — "
f"no more tool calls allowed. "
f"You MUST output the skill edit content now based on "
f"all information gathered so far. Follow the output "
f"format specified in the original instructions. "
f"End with {EVOLUTION_COMPLETE} if the edit is satisfactory, "
f"or {EVOLUTION_FAILED} with a reason if you cannot produce one."
),
}
)
try:
result = await self._llm_client.complete(
messages=messages,
tools=evolution_tools if (evolution_tools and not is_last) else None,
execute_tools=True,
model=model,
)
except Exception as e:
logger.error(f"Evolution LLM call failed (iter {iteration + 1}): {e}")
return None
content = result["message"].get("content", "")
updated_messages = result["messages"]
has_tool_calls = result.get("has_tool_calls", False)
# Record iteration delta
delta = updated_messages[msg_count_before:]
await RecordingManager.record_iteration_context(
iteration=iteration + 1,
delta_messages=copy.deepcopy(delta),
response_metadata={
"has_tool_calls": has_tool_calls,
"tool_calls_count": len(result.get("tool_results", [])),
"has_completion_token": bool(
content and (EVOLUTION_COMPLETE in content or EVOLUTION_FAILED in content)
),
},