self-evolve-framework 1.2.0 → 1.4.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 (64) hide show
  1. package/README.md +22 -11
  2. package/bin/cli.js +1 -0
  3. package/package.json +1 -1
  4. package/template/skills/ponytail/SKILL.md +133 -0
  5. package/template/skills/ponytail/scripts/hooks/claude-codex-hooks.json +44 -0
  6. package/template/skills/ponytail/scripts/hooks/copilot-hooks.json +21 -0
  7. package/template/skills/ponytail/scripts/hooks/ponytail-activate.js +91 -0
  8. package/template/skills/ponytail/scripts/hooks/ponytail-config.js +122 -0
  9. package/template/skills/ponytail/scripts/hooks/ponytail-instructions.js +94 -0
  10. package/template/skills/ponytail/scripts/hooks/ponytail-mode-tracker.js +55 -0
  11. package/template/skills/ponytail/scripts/hooks/ponytail-runtime.js +68 -0
  12. package/template/skills/ponytail/scripts/hooks/ponytail-statusline.ps1 +21 -0
  13. package/template/skills/ponytail/scripts/hooks/ponytail-statusline.sh +12 -0
  14. package/template/skills/ponytail/scripts/hooks/ponytail-subagent.js +22 -0
  15. package/template/skills/ponytail/scripts/mcp/README.md +46 -0
  16. package/template/skills/ponytail/scripts/mcp/index.js +48 -0
  17. package/template/skills/ponytail/scripts/mcp/instructions.js +26 -0
  18. package/template/skills/ponytail/scripts/mcp/package.json +13 -0
  19. package/template/skills/ponytail/scripts/mcp/test/instructions.test.js +22 -0
  20. package/template/skills/ponytail-audit/SKILL.md +41 -0
  21. package/template/skills/ponytail-debt/SKILL.md +44 -0
  22. package/template/skills/ponytail-gain/SKILL.md +50 -0
  23. package/template/skills/ponytail-help/SKILL.md +69 -0
  24. package/template/skills/ponytail-review/SKILL.md +57 -0
  25. package/template/skills/skillopt-sleep/SKILL.md +48 -34
  26. package/template/skills/skillopt-sleep/scripts/python/__init__.py +20 -0
  27. package/template/skills/skillopt-sleep/scripts/python/__main__.py +343 -0
  28. package/template/skills/skillopt-sleep/scripts/python/backend.py +1371 -0
  29. package/template/skills/skillopt-sleep/scripts/python/budget.py +75 -0
  30. package/template/skills/skillopt-sleep/scripts/python/config.py +162 -0
  31. package/template/skills/skillopt-sleep/scripts/python/consolidate.py +238 -0
  32. package/template/skills/skillopt-sleep/scripts/python/cycle.py +291 -0
  33. package/template/skills/skillopt-sleep/scripts/python/dream.py +138 -0
  34. package/template/skills/skillopt-sleep/scripts/python/experiments/__init__.py +1 -0
  35. package/template/skills/skillopt-sleep/scripts/python/experiments/gbrain_bench.py +119 -0
  36. package/template/skills/skillopt-sleep/scripts/python/experiments/personas.py +86 -0
  37. package/template/skills/skillopt-sleep/scripts/python/experiments/report.py +132 -0
  38. package/template/skills/skillopt-sleep/scripts/python/experiments/run_experiment.py +178 -0
  39. package/template/skills/skillopt-sleep/scripts/python/experiments/run_gbrain.py +209 -0
  40. package/template/skills/skillopt-sleep/scripts/python/experiments/run_transfer.py +155 -0
  41. package/template/skills/skillopt-sleep/scripts/python/experiments/sweep.py +164 -0
  42. package/template/skills/skillopt-sleep/scripts/python/gate.py +50 -0
  43. package/template/skills/skillopt-sleep/scripts/python/harvest.py +304 -0
  44. package/template/skills/skillopt-sleep/scripts/python/harvest_codex.py +253 -0
  45. package/template/skills/skillopt-sleep/scripts/python/harvest_sources.py +41 -0
  46. package/template/skills/skillopt-sleep/scripts/python/judges.py +84 -0
  47. package/template/skills/skillopt-sleep/scripts/python/llm_miner.py +134 -0
  48. package/template/skills/skillopt-sleep/scripts/python/memory.py +129 -0
  49. package/template/skills/skillopt-sleep/scripts/python/mine.py +312 -0
  50. package/template/skills/skillopt-sleep/scripts/python/replay.py +146 -0
  51. package/template/skills/skillopt-sleep/scripts/python/rollout.py +153 -0
  52. package/template/skills/skillopt-sleep/scripts/python/scheduler.py +138 -0
  53. package/template/skills/skillopt-sleep/scripts/python/slow_update.py +142 -0
  54. package/template/skills/skillopt-sleep/scripts/python/staging.py +103 -0
  55. package/template/skills/skillopt-sleep/scripts/python/state.py +96 -0
  56. package/template/skills/skillopt-sleep/scripts/python/tasks_file.py +81 -0
  57. package/template/skills/skillopt-sleep/scripts/python/types.py +146 -0
  58. package/template/skills/skillopt-sleep/scripts/shell/__init__.py +0 -0
  59. package/template/skills/skillopt-sleep/scripts/shell/eval_only.py +466 -0
  60. package/template/skills/skillopt-sleep/scripts/shell/materialize_searchqa.py +148 -0
  61. package/template/skills/skillopt-sleep/scripts/shell/run_alfworld.sh +60 -0
  62. package/template/skills/skillopt-sleep/scripts/shell/run_searchqa.sh +40 -0
  63. package/template/skills/skillopt-sleep/scripts/shell/run_spreadsheetbench.sh +39 -0
  64. package/template/skills/skillopt-sleep/scripts/shell/train.py +556 -0
@@ -0,0 +1,291 @@
1
+ """SkillOpt-Sleep — the nightly cycle orchestrator.
2
+
3
+ run_sleep_cycle() wires the stages:
4
+ harvest -> mine -> replay -> consolidate(gate) -> stage (-> optional adopt)
5
+
6
+ It is pure-Python and import-light; with backend="mock" it runs with no API
7
+ key and no third-party deps, which is what the deterministic experiment and
8
+ CI use. With backend="anthropic" it spends the user's budget for real lift.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import sys
14
+ from dataclasses import dataclass
15
+ from typing import List, Optional
16
+
17
+ from skillopt_sleep.backend import get_backend
18
+ from skillopt_sleep.config import SleepConfig, load_config
19
+ from skillopt_sleep.dream import dream_consolidate
20
+ from skillopt_sleep.harvest_sources import harvest_for_config
21
+ from skillopt_sleep.memory import ensure_skill_scaffold
22
+ from skillopt_sleep.mine import mine
23
+ from skillopt_sleep.staging import adopt as adopt_staging
24
+ from skillopt_sleep.staging import write_staging
25
+ from skillopt_sleep.state import SleepState, _now_iso
26
+ from skillopt_sleep.types import SessionDigest, SleepReport, TaskRecord
27
+
28
+
29
+ @dataclass
30
+ class CycleOutcome:
31
+ report: SleepReport
32
+ staging_dir: str
33
+ adopted: bool
34
+ adopted_paths: List[str]
35
+
36
+
37
+ def _project_paths(cfg: SleepConfig) -> str:
38
+ """Where live CLAUDE.md lives + which project we are evolving."""
39
+ if cfg.get("projects") == "invoked" and cfg.get("invoked_project"):
40
+ return cfg.get("invoked_project")
41
+ # default: the invoked cwd
42
+ return cfg.get("invoked_project") or os.getcwd()
43
+
44
+
45
+ def _read(path: str) -> str:
46
+ try:
47
+ with open(path, encoding="utf-8") as f:
48
+ return f.read()
49
+ except Exception:
50
+ return ""
51
+
52
+
53
+ def _progress(cfg: SleepConfig, message: str) -> None:
54
+ if cfg.get("progress", False):
55
+ print(f"[sleep] {message}", file=sys.stderr, flush=True)
56
+
57
+
58
+ def _render_report_md(report: SleepReport, cfg: SleepConfig) -> str:
59
+ lines = [
60
+ f"# SkillOpt-Sleep — night {report.night} report",
61
+ "",
62
+ f"- project: `{report.project}`",
63
+ f"- backend: `{cfg.get('backend')}` replay: `{cfg.get('replay_mode')}`",
64
+ f"- sessions harvested: {report.n_sessions}",
65
+ f"- tasks mined: {report.n_tasks} (replayed: {report.n_replayed})",
66
+ f"- held-out score: {report.baseline_score:.3f} -> {report.candidate_score:.3f}",
67
+ f"- gate: **{report.gate_action}** (accepted={report.accepted})",
68
+ f"- tokens used: {report.tokens_used}",
69
+ "",
70
+ ]
71
+ if report.edits:
72
+ lines.append("## Accepted edits")
73
+ for e in report.edits:
74
+ lines.append(f"- [{e.target}/{e.op}] {e.content} \n _why: {e.rationale}_")
75
+ lines.append("")
76
+ if report.rejected_edits:
77
+ lines.append("## Rejected by gate (kept as negative feedback)")
78
+ for e in report.rejected_edits:
79
+ lines.append(f"- [{e.target}/{e.op}] {e.content}")
80
+ lines.append("")
81
+ if report.notes:
82
+ lines.append("## Notes")
83
+ for n in report.notes:
84
+ lines.append(f"- {n}")
85
+ lines.append("")
86
+ lines.append("_Review, then run `/sleep adopt` to apply, or discard this folder._")
87
+ return "\n".join(lines)
88
+
89
+
90
+ def run_sleep_cycle(
91
+ cfg: Optional[SleepConfig] = None,
92
+ *,
93
+ seed_tasks: Optional[List[TaskRecord]] = None,
94
+ dry_run: bool = False,
95
+ clock: Optional[float] = None,
96
+ ) -> CycleOutcome:
97
+ """Run one full sleep cycle and return the outcome.
98
+
99
+ Parameters
100
+ ----------
101
+ cfg : SleepConfig
102
+ seed_tasks : optional pre-built TaskRecords (used by the experiment to
103
+ inject a known persona instead of harvesting ~/.claude).
104
+ dry_run : harvest+mine+replay but DO NOT stage/adopt (report only).
105
+ clock : fixed epoch seconds for deterministic timestamps in tests.
106
+ """
107
+ cfg = cfg or load_config()
108
+ state = SleepState.load(cfg.state_path)
109
+ night = state.begin_night(clock)
110
+ project = _project_paths(cfg)
111
+ started = _now_iso(clock)
112
+
113
+ backend = get_backend(
114
+ cfg.get("backend", "mock"),
115
+ model=cfg.get("model", ""),
116
+ codex_path=cfg.get("codex_path", ""),
117
+ project_dir=project,
118
+ )
119
+ _progress(cfg, f"night {night}: project={project} backend={backend.name}")
120
+
121
+ # ── live skill/memory docs ───────────────────────────────────────────
122
+ live_memory_path = os.path.join(project, "CLAUDE.md")
123
+ live_skill_path = cfg.managed_skill_path()
124
+ _progress(cfg, f"live skill: {live_skill_path}")
125
+ raw_skill = _read(live_skill_path)
126
+ skill = raw_skill
127
+ memory = _read(live_memory_path)
128
+ if not skill:
129
+ skill = ensure_skill_scaffold(
130
+ "", name=cfg.get("managed_skill_name", "skillopt-sleep-learned"),
131
+ description="Preferences and procedures learned from past local agent sessions.",
132
+ )
133
+ target_filter = bool(
134
+ cfg.get("target_task_filter", True)
135
+ and cfg.get("target_skill_path", "")
136
+ and raw_skill
137
+ )
138
+
139
+ # ── 1+2. harvest + mine (unless seed_tasks injected) ─────────────────
140
+ digests: List[SessionDigest] = []
141
+ if seed_tasks is not None:
142
+ tasks = seed_tasks
143
+ n_sessions = 0
144
+ _progress(cfg, f"using {len(tasks)} seeded tasks")
145
+ else:
146
+ since = state.last_harvest_for(project)
147
+ # On first run (no prior harvest), apply lookback_hours so we don't
148
+ # scan the entire transcript history and trigger massive LLM mining.
149
+ if since is None:
150
+ lookback_hours = cfg.get("lookback_hours", 72)
151
+ if lookback_hours is not None and lookback_hours > 0:
152
+ import time
153
+ ref_time = clock if clock is not None else time.time()
154
+ cutoff = ref_time - lookback_hours * 3600
155
+ since = _now_iso(cutoff)
156
+ max_tasks = cfg.get("max_tasks_per_night", 40)
157
+ max_sessions = cfg.get("max_sessions_per_night", 0) or max_tasks * 3
158
+ candidate_limit = max_tasks
159
+ if target_filter:
160
+ candidate_limit = max(max_tasks, max_tasks * 3)
161
+ _progress(
162
+ cfg,
163
+ f"harvest start: source={cfg.get('transcript_source')} max_sessions={max_sessions}",
164
+ )
165
+ digests = harvest_for_config(
166
+ cfg,
167
+ since_iso=since,
168
+ limit=max_sessions,
169
+ )
170
+ n_sessions = len(digests)
171
+ _progress(cfg, f"harvest done: sessions={n_sessions}")
172
+ # When a real backend is configured, use it to mine checkable tasks from
173
+ # the transcripts (rubric/rule judges); otherwise fall back to the
174
+ # heuristic miner (no API, no checkable reference).
175
+ llm_miner = None
176
+ if cfg.get("backend", "mock") != "mock" and cfg.get("llm_mine", True):
177
+ try:
178
+ from skillopt_sleep.llm_miner import make_llm_miner
179
+ llm_miner = make_llm_miner(
180
+ backend,
181
+ max_sessions=max_sessions,
182
+ max_tasks=candidate_limit,
183
+ )
184
+ except Exception:
185
+ llm_miner = None
186
+ _progress(
187
+ cfg,
188
+ f"mine start: max_tasks={max_tasks} candidate_limit={candidate_limit} "
189
+ f"llm_mine={llm_miner is not None} target_filter={target_filter}",
190
+ )
191
+ tasks = mine(
192
+ digests,
193
+ max_tasks=max_tasks,
194
+ candidate_limit=candidate_limit,
195
+ holdout_fraction=cfg.get("holdout_fraction", 0.34),
196
+ seed=cfg.get("seed", 42),
197
+ llm_miner=llm_miner,
198
+ target_skill_text=raw_skill if target_filter else "",
199
+ target_skill_path=live_skill_path if target_filter else "",
200
+ )
201
+ _progress(cfg, f"mine done: tasks={len(tasks)}")
202
+
203
+ report = SleepReport(
204
+ night=night, project=project, started_at=started,
205
+ n_sessions=n_sessions, n_tasks=len(tasks),
206
+ )
207
+
208
+ if not tasks:
209
+ report.ended_at = _now_iso(clock)
210
+ report.notes.append("no tasks mined — nothing to consolidate")
211
+ state.set_last_harvest(project, started)
212
+ state.record_night({"night": night, "accepted": False, "n_tasks": 0})
213
+ if not dry_run:
214
+ state.save()
215
+ staging_dir = ""
216
+ return CycleOutcome(report, staging_dir, False, [])
217
+
218
+ # ── 3+4. replay + consolidate (gate), with opt-in dream + recall ──────
219
+ # recall pulls similar past tasks from the persisted archive; dream_rollouts
220
+ # / dream_factor enrich the training signal. With the defaults (recall_k=0,
221
+ # dream_rollouts=1, dream_factor=0) this is exactly the prior single-shot
222
+ # consolidate — behavior is unchanged unless the user opts in.
223
+ _progress(cfg, "consolidate start")
224
+ recall_k = int(cfg.get("recall_k", 0) or 0)
225
+ history_tasks = []
226
+ if recall_k > 0:
227
+ history_tasks = [TaskRecord.from_dict(d) for d in state.task_archive()]
228
+ result = dream_consolidate(
229
+ backend, tasks, skill, memory,
230
+ history_tasks=history_tasks,
231
+ recall_k=recall_k,
232
+ dream_rollouts=int(cfg.get("dream_rollouts", 1) or 1),
233
+ dream_factor=int(cfg.get("dream_factor", 0) or 0),
234
+ edit_budget=cfg.get("edit_budget", 4),
235
+ gate_metric=cfg.get("gate_metric", "mixed"),
236
+ gate_mixed_weight=cfg.get("gate_mixed_weight", 0.5),
237
+ gate_mode=cfg.get("gate_mode", "on"),
238
+ evolve_skill=cfg.get("evolve_skill", True),
239
+ evolve_memory=cfg.get("evolve_memory", True),
240
+ night=night,
241
+ )
242
+ # archive tonight's real (non-dream) tasks so future nights can recall them
243
+ state.add_to_archive([t.to_dict() for t in tasks if t.origin != "dream"])
244
+ _progress(
245
+ cfg,
246
+ f"consolidate done: gate={result.gate_action} accepted={result.accepted} "
247
+ f"edits={len(result.applied_edits)} rejected={len(result.rejected_edits)}",
248
+ )
249
+
250
+ report.n_replayed = len(tasks)
251
+ report.baseline_score = result.baseline_score
252
+ report.candidate_score = result.candidate_score
253
+ report.accepted = result.accepted
254
+ report.gate_action = result.gate_action
255
+ report.no_edits_reason = getattr(result, "no_edits_reason", "")
256
+ report.edits = result.applied_edits
257
+ report.rejected_edits = result.rejected_edits
258
+ report.tokens_used = backend.tokens_used()
259
+ report.ended_at = _now_iso(clock)
260
+
261
+ # ── 5. stage (unless dry-run) ────────────────────────────────────────
262
+ staging_dir = ""
263
+ adopted = False
264
+ adopted_paths: List[str] = []
265
+ if not dry_run:
266
+ _progress(cfg, "staging start")
267
+ report_md = _render_report_md(report, cfg)
268
+ proposed_skill = result.new_skill if (cfg.get("evolve_skill") and result.accepted) else None
269
+ proposed_memory = result.new_memory if (cfg.get("evolve_memory") and result.accepted) else None
270
+ staging_dir = write_staging(
271
+ project,
272
+ report=report,
273
+ proposed_skill=proposed_skill,
274
+ proposed_memory=proposed_memory,
275
+ live_skill_path=live_skill_path,
276
+ live_memory_path=live_memory_path,
277
+ report_md=report_md,
278
+ )
279
+ state.set_last_harvest(project, started)
280
+ state.record_night({
281
+ "night": night, "accepted": result.accepted,
282
+ "baseline": result.baseline_score, "candidate": result.candidate_score,
283
+ "n_tasks": len(tasks), "staging": staging_dir,
284
+ })
285
+ # ── 6. adopt (opt-in) ────────────────────────────────────────────
286
+ if cfg.get("auto_adopt") and result.accepted:
287
+ adopted_paths = adopt_staging(staging_dir)
288
+ adopted = bool(adopted_paths)
289
+ state.save()
290
+
291
+ return CycleOutcome(report, staging_dir, adopted, adopted_paths)
@@ -0,0 +1,138 @@
1
+ """SkillOpt-Sleep — dream + associative recall for nightly consolidation.
2
+
3
+ Two opt-in mechanisms (both default OFF, so the cycle is unchanged unless the
4
+ user enables them) that the deployment experiments validated:
5
+
6
+ * dream rollouts — run each task K times and learn from the good-vs-bad
7
+ contrast (set ``dream_rollouts > 1``). Stronger signal than one failure.
8
+ * associative recall — each night, pull the K past tasks most similar to
9
+ tonight's new ones into the dream (set ``recall_k > 0``). Replays relevant
10
+ experience without re-running the whole history.
11
+
12
+ ``dream_consolidate`` wires recall + synthetic augmentation + multi-rollout
13
+ consolidation and is called by BOTH the shipped plugin cycle and the benchmark
14
+ experiment harness, so the reported numbers exercise the exact code the plugin
15
+ runs. Pure-stdlib, zero research/private dependency.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from typing import List, Optional
21
+
22
+ from skillopt_sleep.consolidate import ConsolidationResult, consolidate
23
+ from skillopt_sleep.types import TaskRecord
24
+
25
+
26
+ # ── synthetic augmentation ("dream up" variants of today's tasks) ─────────────
27
+
28
+ _WRAPPERS = [
29
+ "(quick one) {q}",
30
+ "Please handle this request: {q}",
31
+ "For the daily report: {q}",
32
+ ]
33
+
34
+
35
+ def dream_augment(real_tasks: List[TaskRecord], *, factor: int = 1) -> List[TaskRecord]:
36
+ """Create synthetic TRAIN variants of real tasks (origin='dream').
37
+
38
+ A light, deterministic rephrasing. Dream tasks are training-only — they
39
+ carry split='train' and never enter the val/test slices the gate scores on.
40
+ """
41
+ out: List[TaskRecord] = []
42
+ for t in real_tasks:
43
+ for k in range(max(0, factor)):
44
+ w = _WRAPPERS[k % len(_WRAPPERS)]
45
+ out.append(TaskRecord(
46
+ id=f"{t.id}_dream{k}", project=t.project,
47
+ intent=w.format(q=t.intent), context_excerpt=t.context_excerpt,
48
+ reference_kind=t.reference_kind, reference=t.reference,
49
+ judge=dict(t.judge), system=t.system,
50
+ tags=list(t.tags) + ["dream"], split="train",
51
+ origin="dream", derived_from=t.id,
52
+ ))
53
+ return out
54
+
55
+
56
+ # ── associative recall (experience replay of similar past tasks) ──────────────
57
+
58
+ def _tokens(text: str) -> set:
59
+ return {w for w in re.findall(r"[a-z0-9]+", (text or "").lower()) if len(w) > 2}
60
+
61
+
62
+ def recall_similar(new_tasks: List[TaskRecord], history: List[TaskRecord],
63
+ k: int) -> List[TaskRecord]:
64
+ """Return the ``k`` historical tasks most lexically similar to any of
65
+ tonight's ``new_tasks`` (max Jaccard token overlap). Recalled tasks are
66
+ returned as training material (split='train'); deterministic, stdlib-only.
67
+ """
68
+ if not history or k <= 0 or not new_tasks:
69
+ return []
70
+ new_tok = [_tokens(t.intent) for t in new_tasks]
71
+ new_ids = {t.id for t in new_tasks}
72
+ scored = []
73
+ for h in history:
74
+ if h.id in new_ids:
75
+ continue
76
+ ht = _tokens(h.intent)
77
+ if not ht:
78
+ continue
79
+ sim = max(((len(ht & nt) / len(ht | nt)) if (ht | nt) else 0.0) for nt in new_tok)
80
+ scored.append((sim, h.id, h))
81
+ scored.sort(key=lambda x: (-x[0], x[1]))
82
+ out = []
83
+ for sim, _id, h in scored[:max(0, k)]:
84
+ if sim <= 0.0:
85
+ break
86
+ # recall as training material; copy so the source archive is untouched
87
+ out.append(TaskRecord(
88
+ id=f"recall:{h.id}", project=h.project, intent=h.intent,
89
+ context_excerpt=h.context_excerpt, reference_kind=h.reference_kind,
90
+ reference=h.reference, judge=dict(h.judge), system=h.system,
91
+ tags=list(h.tags) + ["recall"], split="train", origin="real",
92
+ derived_from=h.id,
93
+ ))
94
+ return out
95
+
96
+
97
+ # ── the shared nightly consolidation step ─────────────────────────────────────
98
+
99
+ def dream_consolidate(
100
+ backend,
101
+ tasks: List[TaskRecord],
102
+ skill: str,
103
+ memory: str,
104
+ *,
105
+ history_tasks: Optional[List[TaskRecord]] = None,
106
+ recall_k: int = 0,
107
+ dream_rollouts: int = 1,
108
+ dream_factor: int = 0,
109
+ edit_budget: int = 4,
110
+ gate_metric: str = "mixed",
111
+ gate_mixed_weight: float = 0.5,
112
+ gate_mode: str = "on",
113
+ evolve_skill: bool = True,
114
+ evolve_memory: bool = True,
115
+ night: int = 1,
116
+ ) -> ConsolidationResult:
117
+ """Recall similar past experience + dream synthetic variants, then run one
118
+ gated consolidation epoch over the enlarged training pool.
119
+
120
+ ``tasks`` is the split-tagged pool for tonight (train + val); recall and
121
+ augmentation only enlarge the TRAIN split, so the val slice the gate scores
122
+ on is never polluted. With ``recall_k=0`` and ``dream_rollouts=1`` (the
123
+ defaults) this is exactly the previous single-shot ``consolidate``.
124
+ """
125
+ train = [t for t in tasks if t.split == "train"]
126
+ enlarged = list(tasks)
127
+ if recall_k > 0 and history_tasks:
128
+ enlarged += recall_similar(train, history_tasks, recall_k)
129
+ if dream_factor > 0:
130
+ seed = [t for t in enlarged if t.split == "train" and t.origin != "dream"]
131
+ enlarged += dream_augment(seed, factor=dream_factor)
132
+ return consolidate(
133
+ backend, enlarged, skill, memory,
134
+ edit_budget=edit_budget, gate_metric=gate_metric,
135
+ gate_mixed_weight=gate_mixed_weight, gate_mode=gate_mode,
136
+ rollouts_k=dream_rollouts, evolve_skill=evolve_skill,
137
+ evolve_memory=evolve_memory, night=night,
138
+ )
@@ -0,0 +1 @@
1
+ """SkillOpt-Sleep experiments."""
@@ -0,0 +1,119 @@
1
+ """SkillOpt-Sleep — gbrain-evals benchmark adapter.
2
+
3
+ Loads gbrain-evals' `skillopt-v1` benchmark (deficient skills + train/held-out
4
+ task sets with rule-based judges) into our TaskRecord format, so we can run the
5
+ SkillOpt-Sleep cycle against the SAME suite gbrain publishes a scorecard for:
6
+
7
+ docs/benchmarks/2026-06-03-skillopt.md — "4/4 skills 0 -> 1.00"
8
+
9
+ Each gbrain seed dir has:
10
+ SKILL.md — the deliberately deficient starting skill
11
+ benchmark.jsonl — training tasks {task_id, task, judge:{kind:"rule",checks}}
12
+ held-out.jsonl — held-out tasks (same judge shape, unseen items)
13
+
14
+ We map:
15
+ benchmark.jsonl -> TaskRecords with split="replay"
16
+ held-out.jsonl -> TaskRecords with split="holdout"
17
+ judge -> TaskRecord.judge (+ reference_kind="rule")
18
+
19
+ This lets us reproduce gbrain's headline result with our engine and either the
20
+ claude or codex backend, scoring locally via skillopt_sleep.judges (no judge API).
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import os
26
+ from typing import Dict, List, Optional, Tuple
27
+
28
+ from skillopt_sleep.types import TaskRecord
29
+
30
+
31
+ SEED_DIRS = {
32
+ "brief-writer": "seed-missing-structure",
33
+ "thorough-analyst": "seed-verbose",
34
+ "advisor": "seed-no-verdict",
35
+ "quick-answerer": "seed-no-brain-first",
36
+ }
37
+
38
+
39
+ def _load_jsonl(path: str) -> List[dict]:
40
+ out: List[dict] = []
41
+ if not os.path.exists(path):
42
+ return out
43
+ with open(path, encoding="utf-8") as f:
44
+ for line in f:
45
+ line = line.strip()
46
+ if line:
47
+ try:
48
+ out.append(json.loads(line))
49
+ except Exception:
50
+ pass
51
+ return out
52
+
53
+
54
+ def _to_task(rec: dict, *, seed: str, split: str) -> TaskRecord:
55
+ return TaskRecord(
56
+ id=f"{seed}:{rec.get('task_id', '')}",
57
+ project=f"gbrain/{seed}",
58
+ intent=str(rec.get("task", "")),
59
+ reference_kind="rule",
60
+ judge=rec.get("judge", {}) or {},
61
+ tags=[f"seed:{seed}"],
62
+ split=split,
63
+ )
64
+
65
+
66
+ def load_seed(data_root: str, seed: str, *, val_fraction: float = 0.34,
67
+ split_seed: int = 42) -> Tuple[str, List[TaskRecord]]:
68
+ """Return (deficient_skill_md, tasks) for one gbrain seed.
69
+
70
+ Faithful split mapping:
71
+ * gbrain held-out.jsonl -> our ``test`` (the true final measure)
72
+ * gbrain benchmark.jsonl -> split deterministically into ``train`` + ``val``
73
+ (val gates updates; train drives reflect)
74
+ All tasks are origin='real' (gbrain provides no synthetic tasks).
75
+ """
76
+ import hashlib
77
+ sub = SEED_DIRS.get(seed, seed)
78
+ seed_dir = os.path.join(data_root, sub)
79
+ skill_path = os.path.join(seed_dir, "SKILL.md")
80
+ skill = ""
81
+ if os.path.exists(skill_path):
82
+ with open(skill_path, encoding="utf-8") as f:
83
+ skill = f.read()
84
+ tasks: List[TaskRecord] = []
85
+ # benchmark pool -> train/val
86
+ val_cut = int(round(val_fraction * 100))
87
+ for rec in _load_jsonl(os.path.join(seed_dir, "benchmark.jsonl")):
88
+ t = _to_task(rec, seed=seed, split="train")
89
+ bucket = int(hashlib.sha256((str(split_seed) + t.id).encode()).hexdigest(), 16) % 100
90
+ t.split = "val" if bucket < val_cut else "train"
91
+ tasks.append(t)
92
+ # held-out -> test
93
+ for rec in _load_jsonl(os.path.join(seed_dir, "held-out.jsonl")):
94
+ tasks.append(_to_task(rec, seed=seed, split="test"))
95
+ # guarantee a non-empty val
96
+ if not any(t.split == "val" for t in tasks):
97
+ train_only = [t for t in tasks if t.split == "train"]
98
+ if train_only:
99
+ train_only[0].split = "val"
100
+ return skill, tasks
101
+
102
+
103
+ def available_seeds(data_root: str) -> List[str]:
104
+ return [s for s, sub in SEED_DIRS.items()
105
+ if os.path.isdir(os.path.join(data_root, sub))]
106
+
107
+
108
+ def find_data_root(explicit: str = "") -> Optional[str]:
109
+ """Locate eval/data/skillopt-v1 from common clone locations."""
110
+ cands = [explicit] if explicit else []
111
+ cands += [
112
+ os.path.expanduser("~/git/gbrain-evals/eval/data/skillopt-v1"),
113
+ "/tmp/gbrain-evals/eval/data/skillopt-v1",
114
+ os.path.expanduser("~/gbrain-evals/eval/data/skillopt-v1"),
115
+ ]
116
+ for c in cands:
117
+ if c and os.path.isdir(c):
118
+ return c
119
+ return None
@@ -0,0 +1,86 @@
1
+ """SkillOpt-Sleep — persona task fixtures for the validation experiment.
2
+
3
+ Each persona is a list of TaskRecords with EXACT checkable references and a
4
+ `rule:<key>` tag naming the single skill rule that makes the task solvable
5
+ (consumed by MockBackend). This lets the experiment prove — deterministically,
6
+ with no API — that nightly consolidation lifts a held-out score and that the
7
+ gate blocks regressions.
8
+
9
+ Personas mirror the user's framing: programmer / researcher / analyst.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from typing import List
14
+
15
+ from skillopt_sleep.types import TaskRecord
16
+
17
+
18
+ def _t(i, intent, ref, rule, project="/personas/demo", outcome="fail") -> TaskRecord:
19
+ return TaskRecord(
20
+ id=f"persona_{rule}_{i}",
21
+ project=project,
22
+ intent=intent,
23
+ context_excerpt="",
24
+ attempted_solution="",
25
+ outcome=outcome,
26
+ reference_kind="exact",
27
+ reference=ref,
28
+ tags=[f"rule:{rule}"],
29
+ source_sessions=[f"sess_{i}"],
30
+ )
31
+
32
+
33
+ def researcher_persona() -> List[TaskRecord]:
34
+ """Researcher who always wants arXiv ids wrapped in <answer> tags."""
35
+ items = [
36
+ ("Give me the arXiv id for the SkillOpt paper", "arXiv:2605.23904"),
37
+ ("What's the arXiv id of the Attention paper?", "arXiv:1706.03762"),
38
+ ("arXiv id for the GAN paper?", "arXiv:1406.2661"),
39
+ ("arXiv id for BERT?", "arXiv:1810.04805"),
40
+ ("arXiv id for the ResNet paper?", "arXiv:1512.03385"),
41
+ ("arXiv id for the Adam optimizer paper?", "arXiv:1412.6980"),
42
+ ("arXiv id for Dropout?", "arXiv:1207.0580"),
43
+ ("arXiv id for the Transformer-XL paper?", "arXiv:1901.02860"),
44
+ ("arXiv id for word2vec?", "arXiv:1301.3781"),
45
+ ("arXiv id for the VAE paper?", "arXiv:1312.6114"),
46
+ ("arXiv id for batch norm?", "arXiv:1502.03167"),
47
+ ("arXiv id for GPT-3?", "arXiv:2005.14165"),
48
+ ]
49
+ # Both rules required: format the id (arxiv-id) AND wrap in answer tags.
50
+ out: List[TaskRecord] = []
51
+ for i, (q, a) in enumerate(items):
52
+ t = _t(i, q, a, "wrap-answer")
53
+ t.tags = ["rule:wrap-answer", "rule:arxiv-id"]
54
+ out.append(t)
55
+ return out
56
+
57
+
58
+ def programmer_persona() -> List[TaskRecord]:
59
+ """Programmer who wants imperative-mood commit subjects."""
60
+ items = [
61
+ ("commit message for adding a login form", "Add login form"),
62
+ ("commit message for fixing the null pointer bug", "Fix null pointer in parser"),
63
+ ("commit message for updating the README", "Update README"),
64
+ ("commit message for removing dead code", "Remove dead code"),
65
+ ("commit message for bumping the version", "Bump version to 1.2.0"),
66
+ ("commit message for refactoring the auth module", "Refactor auth module"),
67
+ ("commit message for adding tests", "Add unit tests for scheduler"),
68
+ ("commit message for fixing the CI pipeline", "Fix CI pipeline"),
69
+ ]
70
+ return [_t(i, q, a, "commit-imperative") for i, (q, a) in enumerate(items)]
71
+
72
+
73
+ def harmful_edit_task() -> TaskRecord:
74
+ """A task whose 'fix' is a known-bad rule; used to prove the gate rejects
75
+ regressions. The MockBackend proposes the harmful rule on this failure,
76
+ but applying it does NOT raise the held-out score, so the gate must reject.
77
+ """
78
+ t = _t(99, "answer this freely", "THIS_WILL_NOT_MATCH", "__harmful__")
79
+ t.reference = "an-answer-that-the-harmful-rule-cannot-produce"
80
+ return t
81
+
82
+
83
+ PERSONAS = {
84
+ "researcher": researcher_persona,
85
+ "programmer": programmer_persona,
86
+ }