self-evolve-framework 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/package.json +1 -1
  2. package/template/skills/skillopt-sleep/SKILL.md +42 -0
  3. package/template/skills/skillopt-sleep/configs/_base_/default.yaml +103 -0
  4. package/template/skills/skillopt-sleep/configs/alfworld/default.yaml +29 -0
  5. package/template/skills/skillopt-sleep/configs/docvqa/default.yaml +28 -0
  6. package/template/skills/skillopt-sleep/configs/features/soft_gate.yaml +47 -0
  7. package/template/skills/skillopt-sleep/configs/livemathematicianbench/default.yaml +22 -0
  8. package/template/skills/skillopt-sleep/configs/officeqa/default.yaml +34 -0
  9. package/template/skills/skillopt-sleep/configs/searchqa/default.yaml +32 -0
  10. package/template/skills/skillopt-sleep/configs/spreadsheetbench/default.yaml +34 -0
  11. package/template/skills/skillopt-sleep/scripts/framework/skillopt/__init__.py +28 -0
  12. package/template/skills/skillopt-sleep/scripts/framework/skillopt/config.py +282 -0
  13. package/template/skills/skillopt-sleep/scripts/framework/skillopt/datasets/__init__.py +7 -0
  14. package/template/skills/skillopt-sleep/scripts/framework/skillopt/datasets/base.py +512 -0
  15. package/template/skills/skillopt-sleep/scripts/framework/skillopt/engine/__init__.py +9 -0
  16. package/template/skills/skillopt-sleep/scripts/framework/skillopt/engine/trainer.py +2379 -0
  17. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/__init__.py +1 -0
  18. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/_template/README.md +43 -0
  19. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/_template/config_template.yaml +55 -0
  20. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/_template/env_template.py +151 -0
  21. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/_template/loader_template.py +87 -0
  22. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/__init__.py +5 -0
  23. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/adapter.py +428 -0
  24. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/dataloader.py +123 -0
  25. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/analyst_error.md +55 -0
  26. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/analyst_success.md +33 -0
  27. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/rollout_no_history.md +8 -0
  28. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/rollout_with_history.md +9 -0
  29. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/rollout_with_memory.md +16 -0
  30. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/reflect.py +4 -0
  31. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/rollout.py +366 -0
  32. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/skills/initial.md +45 -0
  33. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/__init__.py +9 -0
  34. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/alfworld_envs.py +221 -0
  35. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/alfworld_projection.py +60 -0
  36. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/alfworld_prompts.py +8 -0
  37. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/config_tw.yaml +145 -0
  38. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/env_base.py +84 -0
  39. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/env_manager.py +139 -0
  40. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/memory.py +87 -0
  41. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/base.py +329 -0
  42. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/__init__.py +1 -0
  43. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/adapter.py +90 -0
  44. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/dataloader.py +61 -0
  45. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/evaluator.py +113 -0
  46. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/prompts/analyst_error.md +35 -0
  47. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/prompts/analyst_success.md +24 -0
  48. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/prompts/rollout_system.md +12 -0
  49. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/rollout.py +391 -0
  50. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/skills/initial.md +11 -0
  51. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/__init__.py +1 -0
  52. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/adapter.py +129 -0
  53. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/dataloader.py +308 -0
  54. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/evaluator.py +62 -0
  55. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/prompts/analyst_error.md +37 -0
  56. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/prompts/analyst_success.md +25 -0
  57. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/prompts/rollout_system.md +12 -0
  58. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/reflect.py +4 -0
  59. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/rollout.py +434 -0
  60. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/skills/initial.md +16 -0
  61. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/__init__.py +1 -0
  62. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/adapter.py +112 -0
  63. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/dataloader.py +71 -0
  64. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/evaluator.py +46 -0
  65. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/prompts/analyst_error.md +37 -0
  66. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/prompts/analyst_success.md +25 -0
  67. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/prompts/rollout_system.md +15 -0
  68. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/rollout.py +799 -0
  69. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/skills/initial.md +15 -0
  70. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/tool_runtime.py +552 -0
  71. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/__init__.py +1 -0
  72. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/adapter.py +96 -0
  73. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/dataloader.py +42 -0
  74. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/evaluator.py +100 -0
  75. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/prompts/analyst_error.md +46 -0
  76. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/prompts/analyst_success.md +32 -0
  77. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/prompts/rollout_system.md +13 -0
  78. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/reflect.py +4 -0
  79. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/rollout.py +494 -0
  80. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/skills/initial.md +3 -0
  81. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/__init__.py +5 -0
  82. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/adapter.py +159 -0
  83. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/codegen_agent.py +731 -0
  84. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/dataloader.py +37 -0
  85. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/evaluator.py +158 -0
  86. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/executor.py +67 -0
  87. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/analyst_error.md +46 -0
  88. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/analyst_success.md +32 -0
  89. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/codegen_system.md +1 -0
  90. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/critical_rules.md +9 -0
  91. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/react_system.md +21 -0
  92. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/react_agent.py +395 -0
  93. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/reflect.py +4 -0
  94. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/rollout.py +979 -0
  95. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/skills/initial.md +56 -0
  96. package/template/skills/skillopt-sleep/scripts/framework/skillopt/evaluation/__init__.py +13 -0
  97. package/template/skills/skillopt-sleep/scripts/framework/skillopt/evaluation/gate.py +148 -0
  98. package/template/skills/skillopt-sleep/scripts/framework/skillopt/gradient/__init__.py +15 -0
  99. package/template/skills/skillopt-sleep/scripts/framework/skillopt/gradient/aggregate.py +253 -0
  100. package/template/skills/skillopt-sleep/scripts/framework/skillopt/gradient/reflect.py +635 -0
  101. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/__init__.py +514 -0
  102. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/azure_openai.py +915 -0
  103. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/backend_config.py +185 -0
  104. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/claude_backend.py +371 -0
  105. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/codex_backend.py +666 -0
  106. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/codex_harness.py +1057 -0
  107. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/common.py +229 -0
  108. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/minimax_backend.py +277 -0
  109. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/qwen_backend.py +456 -0
  110. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/router.py +236 -0
  111. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/__init__.py +15 -0
  112. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/appendix.py +156 -0
  113. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/clip.py +109 -0
  114. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/lr_autonomous.py +108 -0
  115. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/meta_skill.py +79 -0
  116. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/rewrite.py +59 -0
  117. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/scheduler.py +127 -0
  118. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/select.py +4 -0
  119. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/skill.py +201 -0
  120. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/skill_aware.py +206 -0
  121. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/slow_update.py +396 -0
  122. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/update_modes.py +135 -0
  123. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/__init__.py +63 -0
  124. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_error.md +41 -0
  125. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_error_full_rewrite.md +32 -0
  126. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_error_rewrite.md +44 -0
  127. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_success.md +36 -0
  128. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_success_full_rewrite.md +30 -0
  129. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_success_rewrite.md +33 -0
  130. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/lr_autonomous.md +20 -0
  131. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_failure.md +30 -0
  132. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_failure_full_rewrite.md +28 -0
  133. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_failure_rewrite.md +26 -0
  134. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_final.md +33 -0
  135. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_final_full_rewrite.md +28 -0
  136. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_final_rewrite.md +25 -0
  137. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_success.md +28 -0
  138. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_success_full_rewrite.md +28 -0
  139. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_success_rewrite.md +25 -0
  140. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/meta_skill.md +40 -0
  141. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/ranking.md +20 -0
  142. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/ranking_rewrite.md +15 -0
  143. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/rewrite_skill.md +25 -0
  144. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/slow_update.md +60 -0
  145. package/template/skills/skillopt-sleep/scripts/framework/skillopt/scheduler/__init__.py +8 -0
  146. package/template/skills/skillopt-sleep/scripts/framework/skillopt/types.py +306 -0
  147. package/template/skills/skillopt-sleep/scripts/framework/skillopt/utils/__init__.py +4 -0
  148. package/template/skills/skillopt-sleep/scripts/framework/skillopt/utils/json_utils.py +172 -0
  149. package/template/skills/skillopt-sleep/scripts/framework/skillopt/utils/scoring.py +28 -0
@@ -0,0 +1,201 @@
1
+ """ReflACT skill operations — edit application and patch processing.
2
+
3
+ The Update stage (⑤) of the ReflACT pipeline: apply a ranked set of
4
+ edits to the current skill document, producing an updated candidate.
5
+ Analogous to optimizer.step() in neural network training.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import TYPE_CHECKING
10
+
11
+ if TYPE_CHECKING:
12
+ from skillopt.types import Edit as EditType, Patch as PatchType
13
+
14
+ SLOW_UPDATE_START = "<!-- SLOW_UPDATE_START -->"
15
+ SLOW_UPDATE_END = "<!-- SLOW_UPDATE_END -->"
16
+
17
+ # Skill-aware reflection (EmbodiSkill S_app) appendix region. Like the slow
18
+ # update region, it is protected: step-level analyst edits must not modify it.
19
+ APPENDIX_START = "<!-- APPENDIX_START -->"
20
+ APPENDIX_END = "<!-- APPENDIX_END -->"
21
+
22
+ # All protected (start, end) marker pairs. Step-level edits cannot target text
23
+ # inside any of these regions, and `append` / `insert_after`-fallback ops are
24
+ # inserted before the earliest-occurring region so protected blocks stay at the
25
+ # document tail. With only the slow-update region present, every helper reduces
26
+ # to the original slow-update-only behavior (byte-identical skill output).
27
+ _PROTECTED_REGIONS: tuple[tuple[str, str], ...] = (
28
+ (SLOW_UPDATE_START, SLOW_UPDATE_END),
29
+ (APPENDIX_START, APPENDIX_END),
30
+ )
31
+
32
+
33
+ def _earliest_protected_start(skill: str) -> int:
34
+ """Index of the earliest protected-region start marker, or -1 if none."""
35
+ positions = [
36
+ idx
37
+ for idx in (skill.find(start) for start, _ in _PROTECTED_REGIONS)
38
+ if idx != -1
39
+ ]
40
+ return min(positions) if positions else -1
41
+
42
+
43
+ def _is_in_protected_region(skill: str, target: str) -> bool:
44
+ """Check if *target* text falls within any protected region."""
45
+ if not target:
46
+ return False
47
+ target_idx = skill.find(target)
48
+ if target_idx == -1:
49
+ return False
50
+ for start_marker, end_marker in _PROTECTED_REGIONS:
51
+ start_idx = skill.find(start_marker)
52
+ end_idx = skill.find(end_marker)
53
+ if start_idx == -1 or end_idx == -1:
54
+ continue
55
+ region_end = end_idx + len(end_marker)
56
+ if start_idx <= target_idx < region_end:
57
+ return True
58
+ return False
59
+
60
+
61
+ def _is_in_slow_update_region(skill: str, target: str) -> bool:
62
+ """Backward-compatible alias kept for any external callers/tests."""
63
+ return _is_in_protected_region(skill, target)
64
+
65
+
66
+ def _strip_slow_update_markers(text: str) -> str:
67
+ """Remove any protected-region markers from edit content to prevent duplication."""
68
+ return (
69
+ text.replace(SLOW_UPDATE_START, "")
70
+ .replace(SLOW_UPDATE_END, "")
71
+ .replace(APPENDIX_START, "")
72
+ .replace(APPENDIX_END, "")
73
+ )
74
+
75
+
76
+ def _edit_fields(edit: EditType | dict) -> tuple[str, str, str]:
77
+ op = edit.op if hasattr(edit, "op") else edit.get("op", "")
78
+ content = _strip_slow_update_markers(
79
+ (edit.content if hasattr(edit, "content") else edit.get("content", "")).strip()
80
+ )
81
+ target = edit.target if hasattr(edit, "target") else edit.get("target", "")
82
+ return op, content, target
83
+
84
+
85
+ def _apply_edit_with_report(skill: str, edit: EditType | dict) -> tuple[str, dict]:
86
+ op, content, target = _edit_fields(edit)
87
+ report = {
88
+ "op": op,
89
+ "target": target[:200],
90
+ "content_preview": content[:200],
91
+ "status": "unknown",
92
+ }
93
+
94
+ if target and _is_in_protected_region(skill, target):
95
+ report["status"] = "skipped_protected_region"
96
+ return skill, report
97
+
98
+ if op == "append":
99
+ prot_start = _earliest_protected_start(skill)
100
+ if prot_start != -1:
101
+ before = skill[:prot_start].rstrip()
102
+ after = skill[prot_start:]
103
+ report["status"] = "applied_append_before_protected_region"
104
+ return before + "\n\n" + content + "\n\n" + after, report
105
+ report["status"] = "applied_append"
106
+ return skill.rstrip() + "\n\n" + content + "\n", report
107
+
108
+ if op == "insert_after":
109
+ if not target or target not in skill:
110
+ prot_start = _earliest_protected_start(skill)
111
+ if prot_start != -1:
112
+ before = skill[:prot_start].rstrip()
113
+ after = skill[prot_start:]
114
+ report["status"] = "applied_insert_after_fallback_before_protected_region"
115
+ return before + "\n\n" + content + "\n\n" + after, report
116
+ report["status"] = "applied_insert_after_fallback_append"
117
+ return skill.rstrip() + "\n\n" + content + "\n", report
118
+ idx = skill.index(target) + len(target)
119
+ newline = skill.find("\n", idx)
120
+ insert_at = newline + 1 if newline != -1 else len(skill)
121
+ report["status"] = "applied_insert_after"
122
+ return skill[:insert_at] + "\n" + content + "\n" + skill[insert_at:], report
123
+
124
+ if op == "replace":
125
+ if not target:
126
+ report["status"] = "skipped_replace_missing_target"
127
+ return skill, report
128
+ if target not in skill:
129
+ report["status"] = "skipped_replace_target_not_found"
130
+ return skill, report
131
+ report["status"] = "applied_replace"
132
+ return skill.replace(target, content, 1), report
133
+
134
+ if op == "delete":
135
+ if not target:
136
+ report["status"] = "skipped_delete_missing_target"
137
+ return skill, report
138
+ if target not in skill:
139
+ report["status"] = "skipped_delete_target_not_found"
140
+ return skill, report
141
+ report["status"] = "applied_delete"
142
+ return skill.replace(target, "", 1), report
143
+
144
+ report["status"] = "skipped_unknown_op"
145
+ return skill, report
146
+
147
+
148
+ def apply_edit(skill: str, edit: EditType | dict) -> str:
149
+ """Apply a single edit operation to the skill document.
150
+
151
+ Parameters
152
+ ----------
153
+ skill : str
154
+ Current skill document content.
155
+ edit : Edit | dict
156
+ An :class:`~skillopt.types.Edit` instance or a plain dict with
157
+ keys ``op``, ``content``, ``target``.
158
+
159
+ Edits targeting the protected slow-update region are silently skipped.
160
+ """
161
+ updated_skill, _ = _apply_edit_with_report(skill, edit)
162
+ return updated_skill
163
+
164
+
165
+ def apply_patch_with_report(
166
+ skill: str,
167
+ patch: PatchType | dict,
168
+ ) -> tuple[str, list[dict]]:
169
+ """Apply a patch and return a per-edit report for observability."""
170
+ edits = patch.edits if hasattr(patch, "edits") else patch.get("edits", [])
171
+ reports: list[dict] = []
172
+ for idx, edit in enumerate(edits, 1):
173
+ try:
174
+ skill, report = _apply_edit_with_report(skill, edit)
175
+ report["index"] = idx
176
+ except Exception as exc: # noqa: BLE001
177
+ report = {
178
+ "index": idx,
179
+ "op": "",
180
+ "target": "",
181
+ "content_preview": "",
182
+ "status": "error",
183
+ "error": str(exc),
184
+ }
185
+ reports.append(report)
186
+ return skill, reports
187
+
188
+
189
+ def apply_patch(skill: str, patch: PatchType | dict) -> str:
190
+ """Apply a patch (list of edits) to the skill document sequentially.
191
+
192
+ Parameters
193
+ ----------
194
+ skill : str
195
+ Current skill document content.
196
+ patch : Patch | dict
197
+ A :class:`~skillopt.types.Patch` instance or a plain dict with
198
+ key ``edits`` containing a list of edit operations.
199
+ """
200
+ updated_skill, _ = apply_patch_with_report(skill, patch)
201
+ return updated_skill
@@ -0,0 +1,206 @@
1
+ """Skill-Aware Reflection — analyst prompt augmentation (EmbodiSkill).
2
+
3
+ When ``use_skill_aware_reflection`` is enabled, the failure/success analysts are
4
+ asked to additionally classify each reflection by EmbodiSkill type and to route
5
+ **EXECUTION_LAPSE** reflections (the skill rule is correct, the executor just
6
+ failed to follow it) into a separate ``appendix_notes`` list instead of the body
7
+ patch. This module owns:
8
+
9
+ 1. the instruction text appended to the resolved analyst system prompt, and
10
+ 2. extraction of ``appendix_notes`` from the analyst JSON response.
11
+
12
+ Design notes
13
+ ------------
14
+ - The suffix is appended **at runtime, gated by the toggle**, so env-specific and
15
+ generic analyst prompts are augmented uniformly and — when the toggle is off —
16
+ remain byte-identical to baseline.
17
+ - Discrimination follows the paper / GMemory: ``SKILL_DEFECT`` = the skill rule is
18
+ wrong / missing / underspecified (→ body edit); ``EXECUTION_LAPSE`` = the rule
19
+ is valid but the agent didn't follow it (→ appendix reminder, body untouched).
20
+ **When unsure, default to EXECUTION_LAPSE** (protect the body — never delete a
21
+ valid rule over a one-off execution slip).
22
+ - Success reflections are labeled DISCOVERY / OPTIMIZATION for logging only; their
23
+ edit behavior is unchanged.
24
+ """
25
+ from __future__ import annotations
26
+
27
+
28
+ # ── Runtime switch (config-driven, env-independent) ─────────────────────────
29
+ #
30
+ # The trainer calls :func:`configure_skill_aware_reflection` once at startup
31
+ # from the resolved config. ``run_minibatch_reflect`` then picks these values
32
+ # up automatically, so env adapters never need to thread the toggle through —
33
+ # the feature is controlled purely by ``optimizer.use_skill_aware_reflection``
34
+ # regardless of benchmark. Mirrors the ``configure_azure_openai`` pattern in
35
+ # :mod:`skillopt.model`. Explicit kwargs at a call site still take precedence
36
+ # (backward compatible).
37
+
38
+ _RUNTIME: dict = {"enabled": False, "appendix_source": "both"}
39
+
40
+
41
+ def configure_skill_aware_reflection(
42
+ enabled: bool,
43
+ appendix_source: str = "both",
44
+ ) -> None:
45
+ """Set the process-wide skill-aware reflection switch from config."""
46
+ _RUNTIME["enabled"] = bool(enabled)
47
+ _RUNTIME["appendix_source"] = str(appendix_source or "both")
48
+
49
+
50
+ def is_skill_aware_enabled() -> bool:
51
+ return bool(_RUNTIME["enabled"])
52
+
53
+
54
+ def get_skill_aware_appendix_source() -> str:
55
+ return str(_RUNTIME["appendix_source"])
56
+
57
+
58
+ # ── Prompt suffixes ─────────────────────────────────────────────────────────
59
+
60
+ # Appended to the FAILURE analyst system prompt when the toggle is on.
61
+ ERROR_SUFFIX = """
62
+
63
+ ## Skill-Aware Reflection (EmbodiSkill)
64
+
65
+ Before proposing body edits, classify EACH failure pattern as one of:
66
+
67
+ - **SKILL_DEFECT**: the current skill is wrong, missing, or underspecified for
68
+ this situation — i.e. an agent that *followed the skill* would still fail, or
69
+ the skill gives no relevant guidance. These become normal body `edits`.
70
+ - **EXECUTION_LAPSE**: the skill ALREADY contains a relevant, correct rule that
71
+ would have avoided the failure, but the agent did not follow it (e.g. ignored a
72
+ rule, malformed output, copied the feedback text verbatim, emitted a non-action
73
+ token like "stop", or otherwise broke execution unrelated to skill content).
74
+
75
+ Discrimination test: "Is there a rule in the current skill that, if followed,
76
+ prevents this failure?" If yes → EXECUTION_LAPSE. If no (rule absent/wrong) →
77
+ SKILL_DEFECT. **When genuinely unsure, choose EXECUTION_LAPSE** — do not edit or
78
+ delete a valid rule over a one-off execution slip.
79
+
80
+ Routing:
81
+ - SKILL_DEFECT → put the fix in `patch.edits` (body), as usual.
82
+ - EXECUTION_LAPSE → put a concise reminder in `appendix_notes` (a flat list of
83
+ strings). DO NOT add a body edit for it. Each note should re-emphasize the
84
+ existing valid rule the agent failed to follow; it must NOT introduce a new
85
+ rule. Keep notes short, concrete, and reusable.
86
+
87
+ Add `appendix_notes` as a TOP-LEVEL key of your JSON output (a sibling of
88
+ `patch`), e.g. `"appendix_notes": ["Follow the existing X rule before Y."]`.
89
+ Use `[]` when there is no execution lapse. Body edits and appendix notes are
90
+ independent: a batch may yield only edits, only notes, both, or neither.
91
+ """
92
+
93
+ # Appended to the SUCCESS analyst system prompt when the toggle is on.
94
+ SUCCESS_SUFFIX = """
95
+
96
+ ## Skill-Aware Reflection (EmbodiSkill)
97
+
98
+ For each proposed edit, optionally label its `reflection_type` for logging:
99
+ - **DISCOVERY**: a useful new rule not yet in the skill (typically an `append`).
100
+ - **OPTIMIZATION**: a better way to perform an existing rule (typically a
101
+ `replace` of that rule).
102
+
103
+ This labeling does not change edit behavior. You may also add a top-level
104
+ `appendix_notes` list (flat strings) if a successful trajectory reveals an
105
+ existing valid rule worth re-emphasizing; otherwise use `[]`.
106
+ """
107
+
108
+
109
+ def augment_error_prompt(system_prompt: str) -> str:
110
+ """Append the failure-analyst skill-aware instruction."""
111
+ return system_prompt.rstrip() + "\n" + ERROR_SUFFIX
112
+
113
+
114
+ def augment_success_prompt(system_prompt: str) -> str:
115
+ """Append the success-analyst skill-aware instruction."""
116
+ return system_prompt.rstrip() + "\n" + SUCCESS_SUFFIX
117
+
118
+
119
+ # ── Response parsing ────────────────────────────────────────────────────────
120
+
121
+
122
+ def extract_appendix_notes(result: dict | None) -> list[str]:
123
+ """Pull a clean list of appendix-note strings from an analyst JSON result.
124
+
125
+ Tolerant of shape: accepts a top-level ``appendix_notes`` list, a single
126
+ string, or items wrapped in dicts with a ``note``/``content`` field. Returns
127
+ ``[]`` for anything missing or malformed (so a non-compliant model degrades
128
+ gracefully to baseline body-only behavior).
129
+ """
130
+ if not isinstance(result, dict):
131
+ return []
132
+ raw = result.get("appendix_notes")
133
+ if raw is None:
134
+ return []
135
+ if isinstance(raw, str):
136
+ raw = [raw]
137
+ if not isinstance(raw, list):
138
+ return []
139
+ notes: list[str] = []
140
+ for item in raw:
141
+ if isinstance(item, str):
142
+ text = item.strip()
143
+ elif isinstance(item, dict):
144
+ text = str(item.get("note") or item.get("content") or "").strip()
145
+ else:
146
+ text = ""
147
+ if text:
148
+ notes.append(text)
149
+ return notes
150
+
151
+
152
+ # ── Appendix consolidation (threshold-gated, paper Eq.11 UpdateSkillAppendix) ──
153
+
154
+ _CONSOLIDATE_SYSTEM = (
155
+ "You compact the Execution Notes Appendix of an agent skill. Each note "
156
+ "re-emphasizes an existing skill rule the agent failed to follow. Your job "
157
+ "is a periodic compaction pass: remove duplicates and redundant overlap, "
158
+ "merge near-identical reminders into one, and simplify phrasing while keeping "
159
+ "each note concrete and operational. Do not invent new rules. Preserve the "
160
+ "distinct actionable content. Return valid JSON only."
161
+ )
162
+
163
+
164
+ def consolidate_appendix_notes(
165
+ notes: list[str],
166
+ *,
167
+ chat_fn,
168
+ max_completion_tokens: int = 4096,
169
+ ) -> list[str]:
170
+ """LLM-consolidate appendix notes: dedupe / merge / compact.
171
+
172
+ Mirrors GMemory ``_maybe_refactor_execution_notes`` and paper Eq.11. ``chat_fn``
173
+ is the optimizer chat callable ``(system, user, max_completion_tokens, retries,
174
+ stage) -> (text, meta)``. On ANY failure (parse, empty, exception) the original
175
+ notes are returned unchanged, so consolidation can never lose the appendix.
176
+ """
177
+ from skillopt.utils import extract_json # local import to avoid cycles
178
+
179
+ clean = [str(n).strip() for n in (notes or []) if str(n).strip()]
180
+ if len(clean) < 2:
181
+ return clean
182
+
183
+ numbered = "\n".join(f"{i}. {n}" for i, n in enumerate(clean, 1))
184
+ user = (
185
+ f"## Current Execution Notes ({len(clean)} total)\n{numbered}\n\n"
186
+ "Compact these into a shorter list without losing distinct actionable "
187
+ "information. Merge duplicates and near-duplicates; keep each note short, "
188
+ "concrete, and reusable. Return valid JSON only with this schema:\n"
189
+ '{ "appendix_notes": ["compacted note 1", "compacted note 2"] }'
190
+ )
191
+ try:
192
+ response, _ = chat_fn(
193
+ system=_CONSOLIDATE_SYSTEM,
194
+ user=user,
195
+ max_completion_tokens=max_completion_tokens,
196
+ retries=2,
197
+ stage="appendix_consolidate",
198
+ )
199
+ result = extract_json(response)
200
+ compacted = extract_appendix_notes(result)
201
+ # Guard: only accept a non-empty result that actually shrinks the set.
202
+ if compacted and len(compacted) <= len(clean):
203
+ return compacted
204
+ except Exception: # noqa: BLE001
205
+ pass
206
+ return clean