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,635 @@
1
+ """ReflACT core Reflect engine -- minibatch trajectory analysis.
2
+
3
+ Provides environment-agnostic minibatch trajectory analysis: instead of
4
+ analyzing each trajectory independently, trajectories are grouped into
5
+ minibatches of size M and analyzed together -- analogous to minibatch SGD
6
+ vs per-sample SGD in neural network training.
7
+
8
+ Two-level prompt priority system:
9
+
10
+ 1. **Custom prompt** (adapter returns non-None) -- used as-is.
11
+ 2. **Generic default prompt** (adapter returns None) -- built-in defaults
12
+ that work for any environment without configuration.
13
+
14
+ Public API
15
+ ----------
16
+ - :func:`fmt_trajectory` -- format one conversation into text
17
+ - :func:`fmt_minibatch_trajectories` -- format multiple trajectories for batch analysis
18
+ - :func:`run_error_analyst_minibatch` -- one optimizer call for a group of failures
19
+ - :func:`run_success_analyst_minibatch` -- one optimizer call for a group of successes
20
+ - :func:`run_minibatch_reflect` -- full reflect stage dispatcher
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import os
26
+ import random
27
+ import traceback
28
+ from concurrent.futures import ThreadPoolExecutor, as_completed
29
+
30
+ from skillopt.model import chat_optimizer
31
+ from skillopt.optimizer.meta_skill import format_meta_skill_context
32
+ from skillopt.optimizer.skill_aware import (
33
+ augment_error_prompt,
34
+ augment_success_prompt,
35
+ extract_appendix_notes,
36
+ get_skill_aware_appendix_source,
37
+ is_skill_aware_enabled,
38
+ )
39
+ from skillopt.optimizer.update_modes import (
40
+ get_payload_items,
41
+ is_full_rewrite_minibatch_mode,
42
+ normalize_update_mode,
43
+ payload_key,
44
+ payload_label,
45
+ truncate_payload,
46
+ )
47
+ from skillopt.prompts import load_prompt
48
+ from skillopt.utils import extract_json
49
+
50
+
51
+ # ── Trajectory formatting ────────────────────────────────────────────────────
52
+
53
+
54
+ def _clip_text(value, limit: int | None = None) -> str:
55
+ """Render optional trajectory fields. Truncation is disabled: the optimizer
56
+ is given the full content so it can see exactly what the agent saw/did.
57
+
58
+ ``limit`` is accepted for backward compatibility but ignored.
59
+ """
60
+ if value is None:
61
+ return ""
62
+ return str(value)
63
+
64
+
65
+ def fmt_trajectory(
66
+ conversation: list[dict],
67
+ max_chars: int | None = None,
68
+ ) -> str:
69
+ """Format a conversation list into analyst-readable text.
70
+
71
+ Accepts two common formats:
72
+
73
+ 1. Tool-call records: ``{"type": "tool_call", "cmd": ..., "obs": ...}``
74
+ 2. Step records: ``{"step": N, "action": ..., "env_feedback": ..., "reasoning": ...}``
75
+
76
+ Any other dict is rendered via its ``"content"`` key.
77
+ """
78
+ lines: list[str] = []
79
+ for item in conversation:
80
+ if not isinstance(item, dict):
81
+ lines.append(f"[agent] {_clip_text(item)}")
82
+ continue
83
+ if item.get("type") == "tool_call":
84
+ cmd = _clip_text(item.get("cmd"))
85
+ obs = _clip_text(item.get("obs"))
86
+ lines.append(f"[action] {cmd}")
87
+ lines.append(f"[obs] {obs}")
88
+ elif "action" in item and "env_feedback" in item:
89
+ step = item.get("step", "?")
90
+ reasoning = _clip_text(item.get("reasoning"))
91
+ action = _clip_text(item.get("action"))
92
+ feedback = _clip_text(item.get("env_feedback"))
93
+ if reasoning:
94
+ lines.append(f"[step {step} think] {reasoning}")
95
+ lines.append(f"[step {step} action] {action}")
96
+ lines.append(f"[step {step} obs] {feedback}")
97
+ elif item.get("role") == "system":
98
+ # Post-execution verification / enrichment info
99
+ msg = _clip_text(item.get("content"))
100
+ lines.append(f"[verification] {msg}")
101
+ else:
102
+ msg = _clip_text(item.get("content"))
103
+ role = item.get("role", "agent")
104
+ lines.append(f"[{role}] {msg}")
105
+
106
+ return "\n".join(lines)
107
+
108
+
109
+ # ── Minibatch trajectory formatting ──────────────────────────────────────────
110
+
111
+
112
+ def fmt_minibatch_trajectories(
113
+ items: list[dict],
114
+ prediction_dir: str,
115
+ ) -> str:
116
+ """Format multiple trajectories for minibatch analyst consumption.
117
+
118
+ Each item is a rollout result dict with ``"id"``, ``"task_description"``,
119
+ ``"task_type"``, ``"fail_reason"``, etc. Reads ``conversation.json``
120
+ for each and formats them together with trajectory headers.
121
+
122
+ If available, includes the spreadsheet preview and target system prompt
123
+ so the analyst can see what the agent saw.
124
+
125
+ Parameters
126
+ ----------
127
+ items : list[dict]
128
+ Rollout result dicts belonging to one minibatch.
129
+ prediction_dir : str
130
+ Path to ``predictions/`` directory containing per-task
131
+ ``<task_id>/conversation.json`` files.
132
+
133
+ Returns
134
+ -------
135
+ str
136
+ Formatted text with all trajectories separated by ``---``.
137
+ """
138
+ parts: list[str] = []
139
+ for idx, item in enumerate(items, 1):
140
+ tid = str(item["id"])
141
+ conv_path = os.path.join(prediction_dir, tid, "conversation.json")
142
+ if not os.path.exists(conv_path):
143
+ continue
144
+ with open(conv_path) as f:
145
+ conversation = json.load(f)
146
+ if not conversation:
147
+ continue
148
+
149
+ traj_text = fmt_trajectory(conversation)
150
+ header = (
151
+ f"### Trajectory {idx} (id={tid})\n"
152
+ f"Task: {item.get('task_description', item.get('instruction', ''))}\n"
153
+ f"Task type: {item.get('task_type', item.get('instruction_type', ''))}\n"
154
+ )
155
+ fail_reason = item.get("fail_reason", "")
156
+ if fail_reason:
157
+ header += f"Failure reason: {fail_reason}\n"
158
+ header += f"Steps: {item.get('n_turns', '?')}\n"
159
+
160
+ reference_text = str(item.get("reference_text") or "").strip()
161
+ if reference_text:
162
+ header += (
163
+ f"\n#### Hidden Reference\n"
164
+ f"{reference_text}\n"
165
+ )
166
+
167
+ # ── Append target context (what the agent saw) ──────────────
168
+ target_prompt = item.get("target_system_prompt", "")
169
+ if not target_prompt:
170
+ prompt_path = os.path.join(prediction_dir, tid, "target_system_prompt.txt")
171
+ if os.path.exists(prompt_path):
172
+ with open(prompt_path) as f:
173
+ target_prompt = f.read()
174
+ if target_prompt:
175
+ header += (
176
+ f"\n#### Target System Prompt\n"
177
+ f"{target_prompt}\n"
178
+ )
179
+
180
+ user_prompt = item.get("target_user_prompt", "")
181
+ if not user_prompt:
182
+ user_prompt_path = os.path.join(prediction_dir, tid, "target_user_prompt.txt")
183
+ if os.path.exists(user_prompt_path):
184
+ with open(user_prompt_path) as f:
185
+ user_prompt = f.read()
186
+ if user_prompt:
187
+ header += (
188
+ f"\n#### Target User Prompt\n"
189
+ f"{user_prompt}\n"
190
+ )
191
+
192
+ if os.environ.get("REFLACT_CODEX_TRACE_TO_OPTIMIZER", "0") == "1":
193
+ codex_trace_summary = item.get("codex_trace_summary", "")
194
+ if not codex_trace_summary:
195
+ codex_trace_summary_path = os.path.join(prediction_dir, tid, "codex_trace_summary.txt")
196
+ if os.path.exists(codex_trace_summary_path):
197
+ with open(codex_trace_summary_path) as f:
198
+ codex_trace_summary = f.read()
199
+ if codex_trace_summary:
200
+ header += (
201
+ f"\n#### Codex Trace Summary\n"
202
+ f"{codex_trace_summary}\n"
203
+ )
204
+
205
+ codex_probe_trace_steps = str(item.get("codex_probe_trace_steps") or "").strip()
206
+ if codex_probe_trace_steps:
207
+ header += (
208
+ f"\n#### Codex Trace Steps\n"
209
+ f"{codex_probe_trace_steps}\n"
210
+ )
211
+
212
+ preview = item.get("spreadsheet_preview", "")
213
+ if not preview:
214
+ preview_path = os.path.join(prediction_dir, tid, "spreadsheet_preview.txt")
215
+ if os.path.exists(preview_path):
216
+ with open(preview_path) as f:
217
+ preview = f.read()
218
+ if preview:
219
+ header += (
220
+ f"\n#### Spreadsheet Preview\n"
221
+ f"{preview}\n"
222
+ )
223
+
224
+ parts.append(header + "\n" + traj_text)
225
+
226
+ return "\n\n---\n\n".join(parts)
227
+
228
+
229
+ # ── Prompt resolution ───────────────────────────────────────────────────────
230
+
231
+
232
+ def _resolve_prompt(custom: str | None, default_name: str, update_mode: str = "patch") -> str:
233
+ """Return *custom* if provided (non-None), otherwise load from file."""
234
+ if custom is not None:
235
+ return custom
236
+ mode = normalize_update_mode(update_mode)
237
+ actual_name = default_name
238
+ if is_full_rewrite_minibatch_mode(mode):
239
+ full_name = f"{default_name}_full_rewrite"
240
+ try:
241
+ return load_prompt(full_name)
242
+ except FileNotFoundError:
243
+ actual_name = default_name
244
+ elif mode == "rewrite_from_suggestions":
245
+ rewrite_name = f"{default_name}_rewrite"
246
+ try:
247
+ return load_prompt(rewrite_name)
248
+ except FileNotFoundError:
249
+ actual_name = default_name
250
+ return load_prompt(actual_name)
251
+
252
+
253
+ # ── Minibatch analysts ──────────────────────────────────────────────────────
254
+
255
+
256
+ def run_error_analyst_minibatch(
257
+ skill_content: str,
258
+ items: list[dict],
259
+ prediction_dir: str,
260
+ edit_budget: int = 4,
261
+ *,
262
+ system_prompt: str | None = None,
263
+ rejection_context: str = "",
264
+ trajectory_memory_context: str = "",
265
+ step_buffer_context: str = "",
266
+ meta_skill_context: str = "",
267
+ update_mode: str = "patch",
268
+ skill_aware_reflection: bool = False,
269
+ ) -> dict | None:
270
+ """Analyze a minibatch of failed trajectories in one optimizer call.
271
+
272
+ Parameters
273
+ ----------
274
+ skill_content : str
275
+ Current skill document text.
276
+ items : list[dict]
277
+ Rollout result dicts (all should have ``hard=0``).
278
+ prediction_dir : str
279
+ Path to ``predictions/`` directory.
280
+ edit_budget : int
281
+ Maximum number of edits (L).
282
+ system_prompt : str | None
283
+ Custom system prompt. ``None`` = use generic default.
284
+ rejection_context : str
285
+ *Deprecated* — use ``step_buffer_context``.
286
+ trajectory_memory_context : str
287
+ *Deprecated* — use ``step_buffer_context``.
288
+ step_buffer_context : str
289
+ Unified summary of previous steps (failure patterns + rejected edits).
290
+
291
+ Returns
292
+ -------
293
+ dict | None
294
+ Patch dict with ``source_type="failure"``, or ``None`` on error.
295
+ """
296
+ mode = normalize_update_mode(update_mode)
297
+ actual_system = _resolve_prompt(system_prompt, "analyst_error", mode)
298
+ # Skill-aware reflection: augment the resolved prompt at runtime so both
299
+ # env-specific and generic analyst prompts get the defect/lapse instruction.
300
+ # When the toggle is off this is a no-op (prompt byte-identical to baseline).
301
+ if skill_aware_reflection and not is_full_rewrite_minibatch_mode(mode):
302
+ actual_system = augment_error_prompt(actual_system)
303
+
304
+ trajectories_text = fmt_minibatch_trajectories(items, prediction_dir)
305
+ if not trajectories_text.strip():
306
+ return None
307
+
308
+ user = (
309
+ f"## Current Skill\n{skill_content}\n\n"
310
+ )
311
+ if is_full_rewrite_minibatch_mode(mode):
312
+ user += (
313
+ f"## Update Format\n"
314
+ f"Produce one complete replacement skill candidate for this minibatch. "
315
+ f"Do not output edits, patches, or revise suggestions.\n\n"
316
+ )
317
+ else:
318
+ user += (
319
+ f"## {payload_label(mode, title=True)} Budget\n"
320
+ f"Produce at most L={edit_budget} {payload_label(mode)}.\n\n"
321
+ )
322
+ # Unified step buffer context (preferred)
323
+ ctx = step_buffer_context or rejection_context or ""
324
+ if trajectory_memory_context:
325
+ ctx = f"{ctx}\n{trajectory_memory_context}" if ctx else trajectory_memory_context
326
+ if ctx.strip():
327
+ user += f"## Previous Steps in This Epoch\n{ctx}\n\n"
328
+ optimizer_ctx = format_meta_skill_context(meta_skill_context)
329
+ if optimizer_ctx:
330
+ user += optimizer_ctx + "\n\n"
331
+ user += f"## Failed Trajectories ({len(items)} total)\n{trajectories_text}"
332
+
333
+ try:
334
+ response, _ = chat_optimizer(
335
+ system=actual_system, user=user,
336
+ max_completion_tokens=64000 if is_full_rewrite_minibatch_mode(mode) else 16384,
337
+ retries=3,
338
+ stage="analyst",
339
+ )
340
+ result = extract_json(response)
341
+ if not result:
342
+ return None
343
+ notes = extract_appendix_notes(result) if skill_aware_reflection else []
344
+ if "patch" in result:
345
+ result["source_type"] = "failure"
346
+ if not is_full_rewrite_minibatch_mode(mode):
347
+ truncate_payload(result["patch"], edit_budget, mode)
348
+ if skill_aware_reflection:
349
+ result["appendix_notes"] = notes
350
+ return result
351
+ # Skill-aware: a batch may legitimately yield ONLY execution-lapse notes
352
+ # (no body edit). Return a no-op patch so the notes still reach the
353
+ # trainer via all_raw_patches; empty edits are dropped from the body
354
+ # pipeline by _normalise_patches, so body behavior is unchanged.
355
+ if skill_aware_reflection and notes:
356
+ return {
357
+ "source_type": "failure",
358
+ "patch": {"reasoning": "execution-lapse only", "edits": []},
359
+ "appendix_notes": notes,
360
+ }
361
+ except Exception: # noqa: BLE001
362
+ traceback.print_exc()
363
+ return None
364
+
365
+
366
+ def run_success_analyst_minibatch(
367
+ skill_content: str,
368
+ items: list[dict],
369
+ prediction_dir: str,
370
+ edit_budget: int = 4,
371
+ *,
372
+ system_prompt: str | None = None,
373
+ trajectory_memory_context: str = "",
374
+ step_buffer_context: str = "",
375
+ meta_skill_context: str = "",
376
+ update_mode: str = "patch",
377
+ skill_aware_reflection: bool = False,
378
+ emit_appendix_notes: bool = True,
379
+ ) -> dict | None:
380
+ """Analyze a minibatch of successful trajectories in one optimizer call.
381
+
382
+ Parameters
383
+ ----------
384
+ system_prompt : str | None
385
+ Custom system prompt. ``None`` = use generic default.
386
+ trajectory_memory_context : str
387
+ *Deprecated* — use ``step_buffer_context``.
388
+ step_buffer_context : str
389
+ Unified summary of previous steps (failure patterns + rejected edits).
390
+
391
+ Returns
392
+ -------
393
+ dict | None
394
+ Patch dict with ``source_type="success"``, or ``None`` on error.
395
+ """
396
+ mode = normalize_update_mode(update_mode)
397
+ actual_system = _resolve_prompt(system_prompt, "analyst_success", mode)
398
+ # Only augment + parse appendix notes on the success side when allowed.
399
+ # failure_only mode (paper-faithful S_app) suppresses success-side notes.
400
+ sa_emit = skill_aware_reflection and emit_appendix_notes
401
+ if sa_emit and not is_full_rewrite_minibatch_mode(mode):
402
+ actual_system = augment_success_prompt(actual_system)
403
+
404
+ trajectories_text = fmt_minibatch_trajectories(items, prediction_dir)
405
+ if not trajectories_text.strip():
406
+ return None
407
+
408
+ user = (
409
+ f"## Current Skill\n{skill_content}\n\n"
410
+ )
411
+ if is_full_rewrite_minibatch_mode(mode):
412
+ user += (
413
+ f"## Update Format\n"
414
+ f"Produce one complete replacement skill candidate for this minibatch. "
415
+ f"Do not output edits, patches, or revise suggestions.\n\n"
416
+ )
417
+ else:
418
+ user += (
419
+ f"## {payload_label(mode, title=True)} Budget\n"
420
+ f"Produce at most L={edit_budget} {payload_label(mode)}.\n\n"
421
+ )
422
+ ctx = step_buffer_context or trajectory_memory_context or ""
423
+ if ctx.strip():
424
+ user += f"## Previous Steps in This Epoch\n{ctx}\n\n"
425
+ optimizer_ctx = format_meta_skill_context(meta_skill_context)
426
+ if optimizer_ctx:
427
+ user += optimizer_ctx + "\n\n"
428
+ user += f"## Successful Trajectories ({len(items)} total)\n{trajectories_text}"
429
+
430
+ try:
431
+ response, _ = chat_optimizer(
432
+ system=actual_system, user=user,
433
+ max_completion_tokens=64000 if is_full_rewrite_minibatch_mode(mode) else 16384,
434
+ retries=3,
435
+ stage="analyst",
436
+ )
437
+ result = extract_json(response)
438
+ if result and "patch" in result:
439
+ result["source_type"] = "success"
440
+ if not is_full_rewrite_minibatch_mode(mode):
441
+ truncate_payload(result["patch"], edit_budget, mode)
442
+ if sa_emit:
443
+ result["appendix_notes"] = extract_appendix_notes(result)
444
+ return result
445
+ except Exception: # noqa: BLE001
446
+ traceback.print_exc()
447
+ return None
448
+
449
+
450
+ # ── Minibatch reflect dispatcher ────────────────────────────────────────────
451
+
452
+
453
+ def _split_minibatches(items: list, batch_size: int) -> list[list]:
454
+ """Split items into minibatches of at most *batch_size*."""
455
+ return [items[i : i + batch_size] for i in range(0, len(items), batch_size)]
456
+
457
+
458
+ def _shuffle_for_minibatch(items: list, seed: int | None) -> list:
459
+ """Return items in minibatch order.
460
+
461
+ Uses a deterministic shuffle when a seed is provided so resume runs keep
462
+ the same minibatch composition. Falls back to input order when no seed is
463
+ available.
464
+ """
465
+ ordered = list(items)
466
+ if seed is None:
467
+ return ordered
468
+ random.Random(seed).shuffle(ordered)
469
+ return ordered
470
+
471
+
472
+ def run_minibatch_reflect(
473
+ results: list[dict],
474
+ skill_content: str,
475
+ prediction_dir: str,
476
+ patches_dir: str,
477
+ workers: int,
478
+ failure_only: bool,
479
+ minibatch_size: int = 8,
480
+ edit_budget: int = 4,
481
+ random_seed: int | None = None,
482
+ *,
483
+ error_system: str | None = None,
484
+ success_system: str | None = None,
485
+ rejection_context: str = "",
486
+ trajectory_memory_context: str = "",
487
+ step_buffer_context: str = "",
488
+ meta_skill_context: str = "",
489
+ update_mode: str = "patch",
490
+ skill_aware_reflection: bool | None = None,
491
+ skill_aware_appendix_source: str | None = None,
492
+ ) -> list[dict | None]:
493
+ """Full minibatch reflect stage: group → parallel optimizer calls → patches.
494
+
495
+ Separates failure and success trajectories, splits each into minibatches
496
+ of size M, runs all minibatches in parallel, and saves patch files.
497
+
498
+ Parameters
499
+ ----------
500
+ results : list[dict]
501
+ Rollout result dicts; see :class:`~skillopt.types.RolloutResult`.
502
+ skill_content : str
503
+ Current skill document.
504
+ prediction_dir : str
505
+ Path to ``predictions/`` with ``conversation.json`` files.
506
+ patches_dir : str
507
+ Path to save per-minibatch patch JSON files.
508
+ workers : int
509
+ Max parallel optimizer calls.
510
+ failure_only : bool
511
+ If True, skip success trajectories.
512
+ minibatch_size : int
513
+ Trajectories per group (M).
514
+ edit_budget : int
515
+ Max edits per minibatch (L).
516
+ random_seed : int | None
517
+ Optional seed used to shuffle trajectories before minibatch splitting.
518
+ error_system, success_system : str | None
519
+ Optional custom prompts. ``None`` = use generic defaults.
520
+
521
+ Returns
522
+ -------
523
+ list[dict | None]
524
+ Patch dicts (with ``source_type`` "failure" or "success").
525
+ """
526
+ # Resolve the skill-aware toggle: explicit kwargs win; otherwise fall back
527
+ # to the process-wide config switch set by the trainer, so the feature is
528
+ # env-independent and adapters need no per-benchmark wiring.
529
+ if skill_aware_reflection is None:
530
+ skill_aware_reflection = is_skill_aware_enabled()
531
+ if skill_aware_appendix_source is None:
532
+ skill_aware_appendix_source = get_skill_aware_appendix_source()
533
+
534
+ os.makedirs(patches_dir, exist_ok=True)
535
+
536
+ # Separate failure / success
537
+ failures = [r for r in results if not r.get("hard") or float(r.get("hard", 0)) < 1e-9]
538
+ successes = [r for r in results if r.get("hard")] if not failure_only else []
539
+
540
+ failures = _shuffle_for_minibatch(failures, random_seed)
541
+ successes = _shuffle_for_minibatch(successes, None if random_seed is None else random_seed + 1)
542
+
543
+ # Split into minibatches
544
+ fail_batches = _split_minibatches(failures, minibatch_size)
545
+ succ_batches = _split_minibatches(successes, minibatch_size)
546
+
547
+ n_fail_batches = len(fail_batches)
548
+ n_succ_batches = len(succ_batches)
549
+ print(
550
+ f" [2/6 REFLECT minibatch] "
551
+ f"failure={len(failures)}→{n_fail_batches} groups "
552
+ f"success={len(successes)}→{n_succ_batches} groups "
553
+ f"(M={minibatch_size}, L={edit_budget}, workers={workers})"
554
+ )
555
+
556
+ raw_patches: list[dict | None] = []
557
+
558
+ # Resume support: check for already-done minibatch patches
559
+ pending_fail: list[tuple[int, list[dict]]] = []
560
+ for idx, batch in enumerate(fail_batches):
561
+ path = os.path.join(patches_dir, f"minibatch_fail_{idx:03d}.json")
562
+ if os.path.exists(path):
563
+ with open(path) as f:
564
+ raw_patches.append(json.load(f))
565
+ else:
566
+ pending_fail.append((idx, batch))
567
+
568
+ pending_succ: list[tuple[int, list[dict]]] = []
569
+ for idx, batch in enumerate(succ_batches):
570
+ path = os.path.join(patches_dir, f"minibatch_succ_{idx:03d}.json")
571
+ if os.path.exists(path):
572
+ with open(path) as f:
573
+ raw_patches.append(json.load(f))
574
+ else:
575
+ pending_succ.append((idx, batch))
576
+
577
+ # ── Worker functions ──────────────────────────────────────────────────
578
+ def _do_fail(idx: int, batch: list[dict]) -> tuple[str, dict | None]:
579
+ patch = run_error_analyst_minibatch(
580
+ skill_content, batch, prediction_dir,
581
+ edit_budget=edit_budget,
582
+ system_prompt=error_system,
583
+ step_buffer_context=step_buffer_context,
584
+ # backward compat fallback
585
+ rejection_context=rejection_context,
586
+ trajectory_memory_context=trajectory_memory_context,
587
+ meta_skill_context=meta_skill_context,
588
+ update_mode=update_mode,
589
+ skill_aware_reflection=skill_aware_reflection,
590
+ )
591
+ return f"minibatch_fail_{idx:03d}", patch
592
+
593
+ def _do_succ(idx: int, batch: list[dict]) -> tuple[str, dict | None]:
594
+ patch = run_success_analyst_minibatch(
595
+ skill_content, batch, prediction_dir,
596
+ edit_budget=edit_budget,
597
+ system_prompt=success_system,
598
+ step_buffer_context=step_buffer_context,
599
+ trajectory_memory_context=trajectory_memory_context,
600
+ meta_skill_context=meta_skill_context,
601
+ update_mode=update_mode,
602
+ skill_aware_reflection=skill_aware_reflection,
603
+ emit_appendix_notes=(skill_aware_appendix_source != "failure_only"),
604
+ )
605
+ return f"minibatch_succ_{idx:03d}", patch
606
+
607
+ # Run all pending minibatches in parallel
608
+ all_pending = (
609
+ [("fail", idx, batch) for idx, batch in pending_fail]
610
+ + [("succ", idx, batch) for idx, batch in pending_succ]
611
+ )
612
+
613
+ with ThreadPoolExecutor(max_workers=workers) as ex:
614
+ futs = {}
615
+ for kind, idx, batch in all_pending:
616
+ if kind == "fail":
617
+ futs[ex.submit(_do_fail, idx, batch)] = (kind, idx, len(batch))
618
+ else:
619
+ futs[ex.submit(_do_succ, idx, batch)] = (kind, idx, len(batch))
620
+
621
+ for i, fut in enumerate(as_completed(futs), 1):
622
+ kind, idx, batch_len = futs[fut]
623
+ tag, patch = fut.result()
624
+ if patch:
625
+ path = os.path.join(patches_dir, f"{tag}.json")
626
+ with open(path, "w") as f:
627
+ json.dump(patch, f, ensure_ascii=False, indent=2)
628
+ raw_patches.append(patch)
629
+ n_edits = len(get_payload_items(patch.get("patch", {}) if patch else {}, update_mode))
630
+ print(
631
+ f" [analyst] {i}/{len(all_pending)} {tag} "
632
+ f"({batch_len} trajs) → {n_edits} {payload_label(update_mode)}"
633
+ )
634
+
635
+ return raw_patches