# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """Self-evolution loop for MBPP / SWE-Bench. Each round: 1. eval on fixed held-out set (generalisation) 2. train on fixed train set (writes failure capsules) 3. critic (Verdict per train capsule → Evidence) 4. synth skills (clusters of failures → CANDIDATE) 5. curate skills (CANDIDATE → ACTIVE / DEPRECATED) When EITHER cadence gate fires (cfg.metaskill_refresh_every_rounds or cfg.metaskill_refresh_every_tasks): 6. meta-synth (Verdict evidence → MetaSkill) 7. curate meta (deprecate conflicted meta-skills) Skills update every round; MetaSkills update on a slower cadence so the evidence corpus is large enough to distinguish real patterns from noise (Verbal-RL Ref §3.2 two-speed libraries). """ from __future__ import annotations import argparse import json import os import shutil import sys import time from contextlib import contextmanager from dataclasses import asdict, dataclass, field, is_dataclass from datetime import datetime, timezone from pathlib import Path from typing import Callable, Iterable import yaml from skillevo.adapters import ( ADAPTERS, BenchResult as _BenchResultPublic, SuiteAdapter as _SuiteAdapterPublic, load_external_adapters, register as _register_adapter, ) from skillevo.capsule.query import CapsuleQuery from skillevo.capsule.store import CapsuleStore from skillevo.core.config import get_config from skillevo.core.constants import NO_SKILL_SENTINEL from skillevo.core.types import Capsule, SkillStatus from skillevo.curator.lifecycle import LifecycleCurator from skillevo.engine.critic import Critic from skillevo.engine.engine import Engine from skillevo.engine.solver import ( CachedTaskSolver, TaskSolver, ) from skillevo.engine.solver_cache import SolverCache from skillevo.llm.client import get_llm_client from skillevo.metaskill.registry import MetaSkillRegistry from skillevo.storage.checkpoint import CheckpointManager from skillevo.skill.loader import SkillLoader from skillevo.skill.registry import SkillRegistry from skillevo.storage.sqlite_store import SQLiteStorage from skillevo.synthesizer.metaskill_synth import MetaSynthesizer from skillevo.synthesizer.skill_synth import Synthesizer # ---------------------------------------------------------------------- data @dataclass class RoundMetrics: round_idx: int eval_pass_at_1: float eval_total: int eval_resolved: int train_pass_at_1: float train_total: int train_resolved: int skills_synthesised: list[str] metaskills_synthesised: list[str] verdicts_written: int bank_active_before_curate: int bank_active_after_curate: int bank_deprecated_after_curate: int wall_time_s: float rolled_back: bool = False rollback_to_round: int | None = None eval_baseline_pass_at_1: float | None = None eval_delta_over_baseline: float | None = None phase_timings_s: dict = field(default_factory=dict) @dataclass class LoopReport: suite: str run_dir: str started_at: str rounds: list[RoundMetrics] = field(default_factory=list) train_ids: list[str] = field(default_factory=list) eval_ids: list[str] = field(default_factory=list) early_stopped: bool = False early_stop_reason: str | None = None # --------------------------------------------------------------- suite glue # Public re-exports — kept here for back-compat with any code that # imported these names from this module before the registry split. SuiteAdapter = _SuiteAdapterPublic BenchResult = _BenchResultPublic class _SuiteAdapterBase: """Base class for the in-tree MBPP/SWE-Bench adapters. External adapters can subclass either this class (gives ``__init__`` boilerplate for free) or just satisfy the ``SuiteAdapter`` protocol directly. ``pack_cli_kwargs`` defaults to empty — built-in adapters override it; custom adapters that don't need extra CLI flags can leave it alone. """ def __init__(self, name: str): self.name = name def load(self, n_train, n_eval, seed, **suite_kwargs) -> tuple[list, list]: raise NotImplementedError def run(self, engine, capsules, tasks, **suite_kwargs) -> "BenchResult": raise NotImplementedError def pack_cli_kwargs(self, args) -> dict: return {} def _filter_by_ids( all_tasks: list, *, id_attr: str, train_ids: list[str], eval_ids: list[str], suite: str, ) -> tuple[list, list]: """Split ``all_tasks`` by explicit id lists (from a subset JSON). Preserves the order given in ``train_ids`` / ``eval_ids`` so runs are deterministic against the same subset file. Raises if any id is missing or if train/eval overlap. """ by_id = {str(getattr(t, id_attr)): t for t in all_tasks} overlap = set(train_ids) & set(eval_ids) if overlap: raise ValueError( f"subset for {suite}: train/eval overlap on {len(overlap)} ids " f"(sample: {sorted(overlap)[:5]})" ) missing_train = [tid for tid in train_ids if tid not in by_id] missing_eval = [tid for tid in eval_ids if tid not in by_id] if missing_train or missing_eval: raise ValueError( f"subset for {suite}: {len(missing_train)} train ids + " f"{len(missing_eval)} eval ids not in dataset " f"(sample missing: {missing_train[:3] + missing_eval[:3]})" ) train = [by_id[tid] for tid in train_ids] eval_ = [by_id[tid] for tid in eval_ids] return train, eval_ class _MBPPAdapter(_SuiteAdapterBase): """MBPP+ only (378 tasks in the single test split).""" def __init__(self): super().__init__("mbpp") def pack_cli_kwargs(self, args) -> dict: kw = {} if getattr(args, "dataset", None): kw["dataset"] = args.dataset kw["concurrency"] = args.concurrency if getattr(args, "timeout", None) is not None: kw["timeout"] = args.timeout return kw def load( self, n_train, n_eval, seed, *, dataset=None, train_ids=None, eval_ids=None, **_ignored, ): import random from skillevo.evaluator.datasets.mbpp import load_mbpp_dataset ds = dataset or "evalplus/mbppplus" all_tasks = load_mbpp_dataset(ds) # Subset path: if the caller supplied exact train/eval ids # (from results/subsets/.json), use them verbatim and # ignore n_train/n_eval/seed. Enforces the hard-subset the # baseline script identified. if train_ids is not None and eval_ids is not None: return _filter_by_ids( all_tasks, id_attr="task_id", train_ids=list(train_ids), eval_ids=list(eval_ids), suite="MBPP+", ) rng = random.Random(seed) shuffled = list(all_tasks) rng.shuffle(shuffled) train = shuffled[:n_train] eval_ = shuffled[n_train : n_train + n_eval] if not eval_: raise ValueError( f"n_train+n_eval ({n_train + n_eval}) > dataset size " f"({len(shuffled)}) — MBPP+ has 378 tasks; reduce " f"n_train/n_eval." ) return train, eval_ def run( self, engine, capsules, tasks, *, dataset=None, timeout=10, concurrency=8, **_ignored, ): from skillevo.evaluator.datasets.mbpp import MBPPRunner runner = MBPPRunner( engine, capsules, dataset_name=dataset or "evalplus/mbppplus", eval_timeout_s=timeout, concurrency=concurrency, ) r = runner.run(tasks) return BenchResult(total=r.total, resolved=r.resolved, pass_at_1=r.pass_at_1) class _SWEBenchAdapter(_SuiteAdapterBase): def __init__(self): super().__init__("swebench") def pack_cli_kwargs(self, args) -> dict: kw = {} if getattr(args, "dataset", None): kw["dataset"] = args.dataset kw["concurrency"] = args.concurrency if getattr(args, "work_dir", None): kw["work_dir"] = args.work_dir if getattr(args, "timeout", None) is not None: kw["timeout"] = args.timeout return kw def load( self, n_train, n_eval, seed, *, dataset=None, work_dir=None, train_ids=None, eval_ids=None, **_ignored, ): from skillevo.evaluator.datasets.swebench import ( load_swebench_dataset, select_tasks, ) ds = dataset or "princeton-nlp/SWE-bench_Verified" all_tasks = load_swebench_dataset(ds) # Subset path: explicit train/eval ids override stratified # random selection. if train_ids is not None and eval_ids is not None: return _filter_by_ids( all_tasks, id_attr="instance_id", train_ids=list(train_ids), eval_ids=list(eval_ids), suite="SWE-Bench Verified", ) picked = select_tasks(all_tasks, n=n_train + n_eval, seed=seed) train = picked[:n_train] eval_ = picked[n_train : n_train + n_eval] if not eval_: raise ValueError( f"n_train+n_eval ({n_train + n_eval}) > available SWE-Bench " f"instances ({len(picked)})" ) return train, eval_ def run( self, engine, capsules, tasks, *, dataset=None, work_dir=None, timeout=300, concurrency=8, **_ignored, ): from skillevo.evaluator.datasets.swebench import SWEBenchRunner runner = SWEBenchRunner( engine, capsules, work_dir=work_dir, dataset_name=dataset or "princeton-nlp/SWE-bench_Verified", eval_timeout_s=timeout, concurrency=concurrency, ) r = runner.run(tasks) return BenchResult(total=r.total, resolved=r.resolved, pass_at_1=r.pass_at_1) # Register the built-in adapters into the public registry. External # adapters can register themselves the same way after being loaded via # SKILLEVO_ADAPTERS (see skillevo.adapters.load_external_adapters). _register_adapter("mbpp", _MBPPAdapter) _register_adapter("swebench", _SWEBenchAdapter) def _dataset_key(suite: str, suite_kwargs: dict) -> str: # noqa: ARG001 # "mbpp" → MBPP+; "swebench" → SWE-bench Verified. The suite name # is already the file name — no "_verified" / "_plus" suffixes. return suite def _scope_root(cfg, db_mode: str, dataset_key: str, run_dir: Path) -> Path: """The root dir that holds EVERYTHING this run writes: skill bank, meta-skill bank, DB, checkpoints, solver cache, per-run reports. * ``per-dataset`` (default): ``results//`` — shared across runs on the same suite. Two runs of MBPP+ see each other's skills; an MBPP+ run never sees SWE-bench state. * ``per-run``: the run dir itself (already lives under ``results//`` to keep the tree tidy). Self-contained: delete the run dir and everything this run did is gone. """ if db_mode == "per-run": return run_dir return cfg.results_dir / dataset_key def _resolve_db_path( cfg, db_mode: str, dataset_key: str, run_dir: Path ) -> Path: """Pick the SQLite file for this run. Always named ``history.db`` — it's the append-only evidence log (capsules + verdicts + skills + meta-skills + stats + audit) for whatever scope the directory implies. * ``per-dataset`` (default): ``results//history.db``. * ``per-run``: ``/history.db``. """ return _scope_root(cfg, db_mode, dataset_key, run_dir) / "history.db" # --------------------------------------------------------------- persistence class RunStore: """Owns the timestamped run dir + round subdirs.""" def __init__(self, root: Path): self.root = root self.root.mkdir(parents=True, exist_ok=True) self.log_path = self.root / "run.log" self._log = open(self.log_path, "a", encoding="utf-8") def close(self) -> None: self._log.close() def log(self, msg: str) -> None: print(msg, flush=True) self._log.write(msg + "\n") self._log.flush() def round_dir(self, idx: int) -> Path: d = self.root / f"round_{idx:02d}" d.mkdir(parents=True, exist_ok=True) return d def write_json(self, path: Path, obj) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(_jsonable(obj), indent=2, default=str)) def write_jsonl(self, path: Path, rows: Iterable) -> None: path.parent.mkdir(parents=True, exist_ok=True) with open(path, "w", encoding="utf-8") as f: for r in rows: f.write(json.dumps(_jsonable(r), default=str) + "\n") def write_yaml(self, path: Path, obj) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(yaml.safe_dump(_jsonable(obj), sort_keys=False)) def copy_db(self, src: Path) -> Path: dst = self.root / src.name if src.exists(): shutil.copy2(src, dst) return dst def _jsonable(obj): if is_dataclass(obj) and not isinstance(obj, type): return _jsonable(asdict(obj)) if isinstance(obj, dict): return {str(k): _jsonable(v) for k, v in obj.items()} if isinstance(obj, (list, tuple)): return [_jsonable(x) for x in obj] if isinstance(obj, (datetime,)): return obj.isoformat() if hasattr(obj, "value") and hasattr(obj, "name"): # Enum return obj.value if hasattr(obj, "__dict__") and not isinstance(obj, type): return _jsonable(vars(obj)) return obj def _capsule_row(c: Capsule) -> dict: row = asdict(c) row["outcome"] = c.outcome.value row["timestamp"] = c.timestamp.isoformat() return row def _router_pick_rate(capsules: list[Capsule]) -> tuple[int, int, float]: """Return (picked, total, rate) — how often the Router chose a skill vs NO_SKILL_SENTINEL on this batch of capsules. A low rate with a non-empty ACTIVE bank indicates the ``select_skill`` prompt is too NONE-biased.""" total = len(capsules) if total == 0: return 0, 0, 0.0 picked = sum(1 for c in capsules if c.skill_id != NO_SKILL_SENTINEL) return picked, total, picked / total def _snapshot_bank( skill_reg: SkillRegistry, meta_reg: MetaSkillRegistry, round_dir: Path ) -> None: loader = SkillLoader() # noqa: F841 — kept for future parity writes skills_out = round_dir / "bank_skills.yaml" entries = [] for s in skill_reg.list_skills(): entry = asdict(s) entry["status"] = s.status.value entry.pop("created_at", None) entry.pop("updated_at", None) entries.append(entry) skills_out.write_text(yaml.safe_dump({"skills": entries}, sort_keys=False)) metas_out = round_dir / "bank_metaskills.yaml" ms_entries = [] for m in meta_reg.list_metaskills(): ms = asdict(m) ms["status"] = m.status.value ms_entries.append(ms) metas_out.write_text(yaml.safe_dump({"metaskills": ms_entries}, sort_keys=False)) @contextmanager def _capsules_since(store: RunStore, storage: SQLiteStorage): boundary = datetime.now(timezone.utc) captured: list[Capsule] = [] def _fetch() -> list[Capsule]: captured.clear() captured.extend( storage.query_capsules(since=boundary, limit=100000) ) return captured yield _fetch # ------------------------------------------------------------------- loop def _count_by_status(registry: SkillRegistry) -> dict[SkillStatus, int]: out: dict[SkillStatus, int] = {s: 0 for s in SkillStatus} for s in registry.list_skills(): out[s.status] = out.get(s.status, 0) + 1 return out def _task_id(task) -> str: for attr in ("instance_id", "task_id"): v = getattr(task, attr, None) if v is not None: return str(v) return repr(task) def _critic_phase( critic: Critic, capsules_this_round: list[Capsule], skill_reg: SkillRegistry, storage: SQLiteStorage, round_idx: int, ) -> int: """Run the critic on every capsule written during the train pass; persist each Verdict. Returns the number of verdicts written.""" n = 0 for cap in capsules_this_round: skill = None if cap.skill_id and cap.skill_id != NO_SKILL_SENTINEL: skill = skill_reg.get_skill(cap.skill_id) verdict = critic.judge(cap, skill=skill, round_idx=round_idx) storage.save_verdict(verdict) n += 1 return n def run_loop( suite: str, n_train: int, n_eval: int, rounds: int, seed: int, run_dir: Path, min_delta: float, min_rounds: int, suite_kwargs: dict, db_mode: str, rollback_threshold: float, rollback_consecutive: int = 5, keep_last_snapshots: int = -1, use_solver_cache: bool = False, # kept for backwards compat: when set, overrides cfg.metaskill_refresh_every_rounds meta_every: int | None = None, skill_bank_max: int | None = None, # Ablation switches (default: full system). See Config docstring. force_no_skill: bool = False, retrieval_only: bool = False, no_meta_injection: bool = False, no_synth: bool = False, skill_retire_min_tasks: int | None = None, skill_retire_contribution_threshold: float | None = None, pattern_canon_threshold: float | None = None, pattern_canon_already_covered_threshold: float | None = None, max_skills_per_round: int | None = None, ) -> LoopReport: if suite not in ADAPTERS: raise SystemExit(f"unknown suite: {suite} (one of {sorted(ADAPTERS)})") adapter = ADAPTERS[suite]() cfg = get_config() # meta-skill cadence: CLI can override cfg.metaskill_refresh_every_rounds # via --meta-every; the task-count trigger always uses cfg. refresh_rounds = ( meta_every if meta_every is not None else cfg.metaskill_refresh_every_rounds ) refresh_tasks = cfg.metaskill_refresh_every_tasks # Skill-bank capacity override: CLI --skill-bank-max for per-run # experiments without editing config. Mutates the shared cfg so # all downstream components (Synthesizer, bank-cap eviction) see # the new value. if skill_bank_max is not None: cfg.skill_bank_max = skill_bank_max # Ablation switches. All default to cfg defaults (= full system) # so passing nothing leaves every knob alone. if force_no_skill: cfg.force_no_skill = True if retrieval_only: cfg.retrieval_only = True if no_meta_injection: cfg.no_meta_injection = True if skill_retire_min_tasks is not None: cfg.skill_retire_min_tasks = skill_retire_min_tasks if skill_retire_contribution_threshold is not None: cfg.skill_retire_contribution_threshold = ( skill_retire_contribution_threshold ) if pattern_canon_threshold is not None: cfg.pattern_canon_threshold = pattern_canon_threshold if pattern_canon_already_covered_threshold is not None: cfg.pattern_canon_already_covered_threshold = ( pattern_canon_already_covered_threshold ) dataset_key = _dataset_key(suite, suite_kwargs) run_id = run_dir.name # Scope root: every path this run uses lives under this dir. # per-dataset → results// # per-run → / scope_root = _scope_root(cfg, db_mode, dataset_key, run_dir) scope_root.mkdir(parents=True, exist_ok=True) cfg.results_dir = scope_root cfg.skills_dir = scope_root / "skills" cfg.meta_skills_dir = scope_root / "meta-skills" db_path = scope_root / "history.db" cfg.db_path = db_path cfg.skills_dir.mkdir(parents=True, exist_ok=True) cfg.meta_skills_dir.mkdir(parents=True, exist_ok=True) storage = SQLiteStorage(db_path) skill_reg = SkillRegistry(storage, cfg) meta_reg = MetaSkillRegistry(storage, cfg) # Guarantee the Synthesizer always has a schema lock — install the # canonical default meta-skill if no active one exists yet. meta_reg.ensure_default() capsules = CapsuleStore( storage, default_metadata={ "run_id": run_id, "dataset_key": dataset_key, "suite": suite, "db_mode": db_mode, }, ) store = RunStore(run_dir) try: store.log(f"run_dir: {run_dir}") store.log(f"db_mode={db_mode} db_path={db_path}") store.log(f"dataset={dataset_key} run_id={run_id}") # Load first so n_train/n_eval in config.json reflect the # subset's real shape, not the --n-train CLI default. train_tasks, eval_tasks = adapter.load( n_train=n_train, n_eval=n_eval, seed=seed, **suite_kwargs ) n_train = len(train_tasks) n_eval = len(eval_tasks) train_ids = [_task_id(t) for t in train_tasks] eval_ids = [_task_id(t) for t in eval_tasks] store.write_json(run_dir / "train_ids.json", train_ids) store.write_json(run_dir / "eval_ids.json", eval_ids) subset_source = suite_kwargs.get("subset_source") store.write_json( run_dir / "config.json", { "suite": suite, "dataset": dataset_key, "run_id": run_id, "db_mode": db_mode, "n_train": n_train, "n_eval": n_eval, "rounds": rounds, "seed": seed, "min_delta": min_delta, "min_rounds": min_rounds, "subset_source": str(subset_source) if subset_source else None, "metaskill_refresh_every_rounds": refresh_rounds, "metaskill_refresh_every_tasks": refresh_tasks, "suite_kwargs": { k: v for k, v in suite_kwargs.items() if k not in ("train_ids", "eval_ids", "subset_source") }, "config": { "db_path": str(db_path), "skills_dir": str(cfg.skills_dir), "meta_skills_dir": str(cfg.meta_skills_dir), "inline_bootstrap": cfg.inline_bootstrap, "skill_bank_max": cfg.skill_bank_max, "skill_max_chars": cfg.skill_max_chars, "skill_retire_min_tasks": cfg.skill_retire_min_tasks, "skill_retire_contribution_threshold": ( cfg.skill_retire_contribution_threshold ), "pattern_canon_threshold": cfg.pattern_canon_threshold, "pattern_canon_already_covered_threshold": ( cfg.pattern_canon_already_covered_threshold ), "force_no_skill": cfg.force_no_skill, "retrieval_only": cfg.retrieval_only, "no_meta_injection": cfg.no_meta_injection, "no_synth": no_synth, "metaskill_max_chars": cfg.metaskill_max_chars, "bedrock_llm_model_id": cfg.bedrock_llm_model_id, "bedrock_embed_model_id": cfg.bedrock_embed_model_id, }, }, ) # Resume from existing loop.json if present (partial run). existing_loop = run_dir / "loop.json" resume_from = 0 if existing_loop.exists(): try: prev = json.loads(existing_loop.read_text()) resume_from = len(prev.get("rounds") or []) if resume_from > 0: report = LoopReport( suite=prev.get("suite", suite), run_dir=str(run_dir), started_at=prev.get( "started_at", datetime.now(timezone.utc).isoformat(), ), train_ids=train_ids, eval_ids=eval_ids, ) for r in prev["rounds"]: report.rounds.append(RoundMetrics(**r)) store.log( f"Resuming from round {resume_from}/{rounds}" ) except Exception: resume_from = 0 if resume_from == 0: report = LoopReport( suite=suite, run_dir=str(run_dir), started_at=datetime.now(timezone.utc).isoformat(), train_ids=train_ids, eval_ids=eval_ids, ) engine = Engine(storage, cfg, capsules=capsules) query = CapsuleQuery(storage) curator = LifecycleCurator(storage, skill_reg, cfg) critic = Critic(llm=get_llm_client(cfg)) solver_cache: SolverCache | None = None cached_solver = None uncached_solver = engine.solver if use_solver_cache: solver_cache = SolverCache( cfg.results_dir / "solver_cache", enabled=True ) inner = ( uncached_solver if isinstance(uncached_solver, TaskSolver) else TaskSolver() ) cached_solver = CachedTaskSolver( inner, solver_cache, dataset_key=dataset_key ) # Single Synthesizer / MetaSynthesizer across rounds so the # "already tried this cluster" memory persists. synth_kwargs: dict = {} if max_skills_per_round is not None: synth_kwargs["max_skills_per_round"] = max_skills_per_round synth = Synthesizer(skill_reg, query, meta_registry=meta_reg, **synth_kwargs) meta_synth = MetaSynthesizer(meta_reg, skill_reg) checkpointer = CheckpointManager(cfg) snapshots: dict[int, Path] = { -1: checkpointer.snapshot(label=f"{run_id}_init"), } # Separate bucket: parked "bad state" snapshots from rolled-back # rounds. GC-exempt — they stay as long as the run dir so the # bad round is auditable after the fact. rolled_back_snapshots: list[Path] = [] best_idx: int = -1 best_pass: float = -1.0 # Counter: how many rounds in a row have eval sit more than # ``rollback_threshold`` below ``best_pass``. Fires rollback # when it reaches ``rollback_consecutive``. Resets to 0 the # moment any round's eval recovers above the threshold — # this is a persistence gate, not a monotone-decline check. consecutive_regressions: int = 0 last_eval_pass: float | None = None # Bookkeeping for meta-skill cadence: time since the active # meta-skill was last refreshed, measured both in rounds and # in tasks (train+eval). A refresh fires when EITHER threshold # is crossed. rounds_since_meta = 0 tasks_since_meta = 0 if resume_from > 0: for r in report.rounds: ep = r.eval_pass_at_1 if ep > best_pass: best_pass = ep best_idx = r.round_idx last_eval_pass = ep for idx in range(resume_from, rounds): t0 = time.monotonic() round_dir = store.round_dir(idx) store.log(f"\n=== round {idx} — {round_dir.name} ===") phase_t: dict = {} # Stamp the current round on every capsule written this # round so StatsAggregator can compute last_used_round. capsules.default_metadata["round_idx"] = idx # 1. eval — ACTIVE-only routing so the bank doesn't grade itself. engine.include_candidates = False if cached_solver is not None: engine.solver = cached_solver _eval_t0 = time.monotonic() try: with _capsules_since(store, storage) as fetch_eval: eval_result = adapter.run( engine, capsules, eval_tasks, **suite_kwargs ) eval_capsules = fetch_eval() finally: engine.solver = uncached_solver phase_t["eval"] = time.monotonic() - _eval_t0 extra = "" if solver_cache is not None: s = solver_cache.stats() extra = ( f" [cache h={s['hits']} m={s['misses']} " f"w={s['writes']}]" ) baseline_pass = ( report.rounds[0].eval_pass_at_1 if report.rounds else eval_result.pass_at_1 ) delta_str = f" Δ {eval_result.pass_at_1 - baseline_pass:+.3f}" store.log( f" eval pass@1 = {eval_result.pass_at_1:.3f} " f"({eval_result.resolved}/{eval_result.total})" f"{delta_str}{extra}" ) picked, picked_total, picked_rate = _router_pick_rate(eval_capsules) store.log( f" eval router: picked skill on {picked}/{picked_total} " f"= {picked_rate:.0%}" ) store.write_json(round_dir / "eval.json", eval_result) store.write_jsonl( round_dir / "eval_capsules.jsonl", (_capsule_row(c) for c in eval_capsules), ) # 1b. regression check — requires ``rollback_consecutive`` # below-threshold rounds in a row to fire. A single noisy # round bumps the counter but doesn't restore; the counter # resets as soon as eval recovers above the threshold. regressed = ( rollback_threshold > 0 and best_pass >= 0 and eval_result.pass_at_1 < best_pass - rollback_threshold ) if regressed: consecutive_regressions += 1 else: consecutive_regressions = 0 if regressed and consecutive_regressions >= rollback_consecutive: # Park the bad state BEFORE reverting so we can audit # what the round tried to change. GC-exempt via the # ``rolled_back_snapshots`` list; stays as long as the # run dir exists. bad_snapshot = checkpointer.snapshot( label=f"{run_id}_round_{idx:02d}_rolled_back" ) rolled_back_snapshots.append(bad_snapshot) snapshot = snapshots[best_idx] checkpointer.restore(snapshot) store.log( f" ROLLBACK: eval {eval_result.pass_at_1:.3f} " f"regressed > {rollback_threshold:.3f} below best " f"{best_pass:.3f} (round {best_idx}) for " f"{consecutive_regressions} consecutive rounds; " f"restored {snapshot.name}; bad state parked at " f"{bad_snapshot.name}" ) # Re-measure eval on the restored bank. The solver # cache may have filled since the restored snapshot # was first taken (if enabled) and the solver is # non-deterministic (if not), so the restored state's # current eval is NOT guaranteed to match its # historical peak. Use the re-measured value as the # new high-water mark so the next regression check is # against a reachable target. engine.include_candidates = False if cached_solver is not None: engine.solver = cached_solver try: with _capsules_since(store, storage) as fetch_restore_eval: restored_eval = adapter.run( engine, capsules, eval_tasks, **suite_kwargs ) _restore_capsules = fetch_restore_eval() finally: engine.solver = uncached_solver store.log( f" post-restore eval pass@1 = {restored_eval.pass_at_1:.3f} " f"(was {best_pass:.3f} at snapshot time)" ) # Rebase the high-water mark and clear the regression # counter so the restored state can't immediately # re-trigger rollback against its own stale peak. best_pass = restored_eval.pass_at_1 consecutive_regressions = 0 report.rounds.append( RoundMetrics( round_idx=idx, eval_pass_at_1=eval_result.pass_at_1, eval_total=eval_result.total, eval_resolved=eval_result.resolved, train_pass_at_1=0.0, train_total=0, train_resolved=0, skills_synthesised=[], metaskills_synthesised=[], verdicts_written=0, bank_active_before_curate=0, bank_active_after_curate=0, bank_deprecated_after_curate=0, wall_time_s=time.monotonic() - t0, rolled_back=True, rollback_to_round=best_idx, eval_baseline_pass_at_1=baseline_pass, eval_delta_over_baseline=( eval_result.pass_at_1 - baseline_pass ), phase_timings_s=dict(phase_t), ) ) store.write_json(run_dir / "loop.json", report) last_eval_pass = eval_result.pass_at_1 continue # 2. train. engine.include_candidates = True _train_t0 = time.monotonic() with _capsules_since(store, storage) as fetch_train: train_result = adapter.run( engine, capsules, train_tasks, **suite_kwargs ) train_capsules = fetch_train() phase_t["train"] = time.monotonic() - _train_t0 store.log( f" train pass@1 = {train_result.pass_at_1:.3f} " f"({train_result.resolved}/{train_result.total})" ) picked, picked_total, picked_rate = _router_pick_rate(train_capsules) store.log( f" train router: picked skill on {picked}/{picked_total} " f"= {picked_rate:.0%}" ) store.write_json(round_dir / "train.json", train_result) store.write_jsonl( round_dir / "train_capsules.jsonl", (_capsule_row(c) for c in train_capsules), ) # 3. critic — write Verdicts for every train capsule. _critic_t0 = time.monotonic() n_verdicts = _critic_phase( critic, train_capsules, skill_reg, storage, idx ) phase_t["critic"] = time.monotonic() - _critic_t0 store.log(f" critic wrote {n_verdicts} verdicts") # Update cadence counters AFTER we know how many tasks ran # this round (train + eval). The meta-synth gate fires when # EITHER the round budget OR the task budget is exhausted. rounds_since_meta += 1 tasks_since_meta += train_result.total + eval_result.total # 4. metaskill synth FIRST (if cadence gate fires) so the # new schema lock is in place when the skill synthesizer # runs below. Old active is retired inside meta_synth.run. meta_synth_report = None meta_fire = ( rounds_since_meta >= refresh_rounds or tasks_since_meta >= refresh_tasks ) if meta_fire: _msynth_t0 = time.monotonic() # Meta-skills are per-suite; the loop runs one suite # per invocation, so pass that straight through. # Window: last cfg.metasynth_lookback_rounds rounds of # verdicts (clamped to >= 0). metasynth_floor = max( 0, idx - cfg.metasynth_lookback_rounds + 1 ) meta_synth_report = meta_synth.run( suite=suite, min_round_idx=metasynth_floor ) phase_t["synth_metaskills"] = time.monotonic() - _msynth_t0 if meta_synth_report.created: rounds_since_meta = 0 tasks_since_meta = 0 store.log( f" meta-synth: created={meta_synth_report.created} " f"retired={meta_synth_report.retired} " f"skipped={meta_synth_report.skipped_reasons}" ) store.write_json( round_dir / "synth_metaskills.json", meta_synth_report ) else: store.log( f" meta-synth skipped: rounds_since_meta=" f"{rounds_since_meta}/{refresh_rounds} " f"tasks_since_meta={tasks_since_meta}/{refresh_tasks}" ) # 5. synth skills — uses the active meta-skill as schema lock. # Window: last cfg.synth_lookback_rounds rounds of failure # capsules so rare patterns can accumulate to min_cluster_size. _ssynth_t0 = time.monotonic() if no_synth: # Audit mode: capsules + verdicts + curator still run # against the existing bank, but no new skills are # authored. Useful for evaluating an imported customer # bank without modifying it. from skillevo.synthesizer.skill_synth import SynthesisReport skill_synth = SynthesisReport(created=[], evicted=[], skipped=[]) store.log(" synth skipped: --no-synth") else: synth_floor = max(0, idx - cfg.synth_lookback_rounds + 1) skill_synth = synth.run(min_round_idx=synth_floor) store.log( f" synth skills={skill_synth.created} " f"evicted={skill_synth.evicted} " f"skipped={skill_synth.skipped}" ) phase_t["synth_skills"] = time.monotonic() - _ssynth_t0 store.write_json(round_dir / "synth_skills.json", skill_synth) # 6. curate skills (contribution-score retirement → DEPRECATED; # rows and evidence retained). _cur_t0 = time.monotonic() before = _count_by_status(skill_reg) curate_reports = curator.curate_all() after = _count_by_status(skill_reg) phase_t["curate"] = time.monotonic() - _cur_t0 store.log( f" bank ACTIVE {before.get(SkillStatus.ACTIVE, 0)}" f" → {after.get(SkillStatus.ACTIVE, 0)}," f" DEPRECATED {before.get(SkillStatus.DEPRECATED, 0)}" f" → {after.get(SkillStatus.DEPRECATED, 0)}" ) store.write_json(round_dir / "curate.json", curate_reports) _snap_t0 = time.monotonic() _snapshot_bank(skill_reg, meta_reg, round_dir) phase_t["snapshot"] = time.monotonic() - _snap_t0 timing_summary = " ".join( f"{k}={v:.1f}s" for k, v in phase_t.items() ) store.log(f" phases: {timing_summary}") report.rounds.append( RoundMetrics( round_idx=idx, eval_pass_at_1=eval_result.pass_at_1, eval_total=eval_result.total, eval_resolved=eval_result.resolved, train_pass_at_1=train_result.pass_at_1, train_total=train_result.total, train_resolved=train_result.resolved, skills_synthesised=skill_synth.created, metaskills_synthesised=( meta_synth_report.created if meta_synth_report else [] ), verdicts_written=n_verdicts, bank_active_before_curate=before.get(SkillStatus.ACTIVE, 0), bank_active_after_curate=after.get(SkillStatus.ACTIVE, 0), bank_deprecated_after_curate=after.get(SkillStatus.DEPRECATED, 0), wall_time_s=time.monotonic() - t0, eval_baseline_pass_at_1=baseline_pass, eval_delta_over_baseline=( eval_result.pass_at_1 - baseline_pass ), phase_timings_s=phase_t, ) ) store.write_json(run_dir / "loop.json", report) if eval_result.pass_at_1 > best_pass: best_pass = eval_result.pass_at_1 best_idx = idx snapshots[idx] = checkpointer.snapshot( label=f"{run_id}_round_{idx:02d}" ) if idx + 1 >= min_rounds and last_eval_pass is not None: if abs(eval_result.pass_at_1 - last_eval_pass) < min_delta: report.early_stopped = True report.early_stop_reason = ( f"|Δpass@1| < {min_delta:.3f} after round {idx}" ) store.log(f" early-stop: {report.early_stop_reason}") break last_eval_pass = eval_result.pass_at_1 store.write_json(run_dir / "loop.json", report) if db_path.parent != run_dir: store.copy_db(db_path) _gc_checkpoints(snapshots, best_idx, keep_last=keep_last_snapshots, store=store) if rolled_back_snapshots: store.log( f"rolled-back snapshots (GC-exempt): " f"{[p.name for p in rolled_back_snapshots]}" ) if solver_cache is not None: s = solver_cache.stats() store.log( f"solver cache: hits={s['hits']} misses={s['misses']} " f"writes={s['writes']} hit_rate={s['hit_rate']:.2f} " f"entries={s['entries_on_disk']} at {s['root']}" ) totals: dict[str, float] = {} for r in report.rounds: for k, v in (r.phase_timings_s or {}).items(): totals[k] = totals.get(k, 0.0) + float(v) if totals: pretty = " ".join(f"{k}={v:.1f}s" for k, v in sorted(totals.items())) store.log(f"phase totals: {pretty}") store.log(f"\nwrote {run_dir / 'loop.json'}") store.log(f"run dir: {run_dir}") return report finally: store.close() def _gc_checkpoints( snapshots: dict[int, Path], best_idx: int, *, keep_last: int, store: RunStore, ) -> None: if keep_last < 0: return round_idxs = sorted(i for i in snapshots if i >= 0) keep: set[int] = {-1, best_idx} keep.update(round_idxs[-keep_last:] if keep_last else []) removed = 0 for idx, path in snapshots.items(): if idx in keep: continue if path.exists(): shutil.rmtree(path, ignore_errors=True) removed += 1 if removed: store.log( f"checkpoint gc: removed {removed}, kept " f"{sorted(i for i in keep if i in snapshots)}" ) # ---------------------------------------------------------------------- cli def _build_parser() -> argparse.ArgumentParser: p = argparse.ArgumentParser(prog="run_skill_loop") p.add_argument("suite", choices=sorted(ADAPTERS.keys())) p.add_argument("--n-train", type=int, default=150) p.add_argument("--n-eval", type=int, default=100) p.add_argument("--rounds", type=int, default=3) p.add_argument("--seed", type=int, default=42) p.add_argument( "--subset", type=Path, default=None, help=( "path to a subset JSON produced by " "``scripts/select_hard_subset.py``. When set, " "``train_ids`` + ``eval_ids`` from the file override " "``--n-train``/``--n-eval``/``--seed`` random selection. " "Training thus focuses on the hard cases the baseline " "found, skipping tasks the LLM already solves." ), ) p.add_argument("--min-delta", type=float, default=0.01) p.add_argument("--min-rounds", type=int, default=2) p.add_argument( "--meta-every", type=int, default=None, help=( "refresh the ACTIVE meta-skill every N rounds (overrides " "cfg.metaskill_refresh_every_rounds). A refresh also fires " "when cfg.metaskill_refresh_every_tasks tasks have passed, " "whichever hits first. Omit to use the config defaults " "(rounds=5, tasks=300)." ), ) p.add_argument( "--skill-bank-max", type=int, default=None, help=( "cap on ACTIVE skills in the bank (overrides " "cfg.skill_bank_max = 100). When the cap is hit and a " "new skill is about to be added, the worst existing " "skill is evicted (policy-consistent first, then " "contribution-score-worst as fallback)." ), ) # ---------------- Ablation flags (A1-A6) ---------------- # A7 (BANK-CAP=100) reuses ``--skill-bank-max`` above. p.add_argument( "--force-no-skill", action="store_true", help=( "A1 ablation: Router always returns no skill. The Engine " "runs the base solver with no bank injection, so every " "task uses only the prompt + model weights. Isolates the " "ceiling attainable without learned skills." ), ) p.add_argument( "--retrieval-only", action="store_true", help=( "A2 ablation: Router skips the ``select_skill`` LLM gate " "and returns the rank-0 skill from the tf-idf ∪ embed " "retrieval union. Isolates the contribution of the LLM " "gate on top of retrieval." ), ) p.add_argument( "--no-meta-injection", action="store_true", help=( "A3 ablation: Synthesizer runs with empty authoring " "guidance (no active meta-skill schema + priors). " "Isolates whether meta-skills add signal over the base " "synth prompt." ), ) p.add_argument( "--no-synth", action="store_true", help=( "Audit mode: skip the per-round skill-synthesis phase. " "Capsules, verdicts, stats, and the curator still run, so " "an imported (e.g. customer-supplied) skill bank gets scored " "without any new skills being authored. Combine with " "do_not_retire on individual skills to lock the bank " "entirely while still gathering evidence." ), ) p.add_argument( "--skill-retire-min-tasks", type=int, default=None, help=( "A4 ablation: override cfg.skill_retire_min_tasks (100). " "The HARSH-RETIRE ablation sets this to 20 (v5-pre-tuning) " "so skills are judged on much less evidence." ), ) p.add_argument( "--skill-retire-contribution-threshold", type=float, default=None, help=( "A4 ablation: override cfg.skill_retire_contribution_threshold " "(-0.10). The HARSH-RETIRE ablation sets this to 0.0 so any " "skill below break-even is retired." ), ) p.add_argument( "--pattern-canon-threshold", type=float, default=None, help=( "A5 ablation: override cfg.pattern_canon_threshold (0.85). " "Set to 1.0 to disable canonicalization — near-duplicate " "critic pattern labels no longer collapse into one class, " "so evidence fragments across rounds." ), ) p.add_argument( "--pattern-canon-already-covered-threshold", type=float, default=None, help=( "A6 ablation: override " "cfg.pattern_canon_already_covered_threshold (0.85). " "Set to 1.0 to disable the 'already covered' guard — " "synth will produce near-duplicate skills addressing " "patterns an ACTIVE skill already covers." ), ) p.add_argument( "--rollback-threshold", type=float, default=0.10, help=( "if a round's eval pass@1 regresses by more than this from " "the best so far (and the regression persists for " "--rollback-consecutive rounds), restore the best round's " "bank snapshot and skip synth/curate. 0 disables rollback." ), ) p.add_argument( "--rollback-consecutive", type=int, default=5, help=( "rollback fires only after N rounds in a row each sit " "more than --rollback-threshold below the best-so-far. " "It's a persistence gate, NOT a trend check — any round " "that recovers above the threshold resets the counter. " "Default 5 so four noisy rounds plus a fifth still can't " "trip the restore. Lower values fire on transient dips, " "and the restore then tends to land near the pre-rollback " "eval without gaining ground." ), ) p.add_argument( "--keep-last-snapshots", type=int, default=-1, help=( "at end of run, keep init + best-eval round + the last N " "round snapshots; delete the rest. Default -1 keeps " "everything (GC off) — matches the no-delete policy the " "skill bank + capsules + verdicts already follow. " "Set to a non-negative integer to enable GC; 0 keeps only " "init + best; rolled-back snapshots are GC-exempt either way." ), ) p.add_argument( "--solver-cache", action=argparse.BooleanOptionalAction, default=os.environ.get("SKILLEVO_SOLVER_CACHE", "0").lower() in ("1", "true", "yes"), help=( "read-through cache for eval solver LLM calls (default OFF). " "Caching eval replies cross-round means tasks the router " "never picks a skill for stay frozen at round-0 outcome, " "making the learning curve look flat. Turn ON for " "inspection runs where you want deterministic eval. " "Training pass always bypasses the cache regardless." ), ) p.add_argument( "--out", type=Path, default=None, help=( "run dir; defaults to " "//_r_t_e_/" ), ) p.add_argument( "--max-skills-per-round", type=int, default=None, help=( "cap on how many new skills the Synthesizer creates per " "round (default 2). Larger datasets benefit from higher " "values since more failure clusters form per round." ), ) p.add_argument("--tag", default=None) p.add_argument( "--db-mode", choices=("per-run", "per-dataset"), default="per-run", help=( "per-run (default): ``/`` holds everything — " "history.db, skills/, meta-skills/, checkpoints/, " "solver_cache/. Each training run starts from a clean " "slate, which is what training loops want. " "per-dataset: ``results//`` is the scope root, " "shared across runs on the same dataset (useful for " "inspection / CLI-only workflows)." ), ) p.add_argument("--dataset", default=None) p.add_argument("--work-dir", default=None, help="SWE-Bench repo checkout root") p.add_argument("--timeout", type=int, default=None) p.add_argument( "--concurrency", type=int, default=8, help=( "thread pool size for MBPP per-task execution (default 8)." ), ) return p def _default_run_dir( cfg, suite: str, tag: str | None, *, rounds: int, n_train: int, n_eval: int, ) -> Path: """Default run-dir: ``results//_r_t_e_[_]/`` The name carries the run's shape (rounds + train/eval sizes) so you can tell two runs apart from ``ls -l results//`` without opening each ``config.json``. Two runs with the same shape collide only if they start in the same UTC second, which is fine — the timestamp is at second resolution. """ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") name = f"{suite}_r{rounds}_t{n_train}_e{n_eval}_{ts}" if tag: name += f"_{tag}" return cfg.results_dir / suite / name def main(argv: list[str] | None = None) -> int: # Load any external adapters declared in $SKILLEVO_ADAPTERS before # argparse builds --suite choices, so a customer's plug-in shows # up as a valid suite name. load_external_adapters() args = _build_parser().parse_args(argv) cfg = get_config() # If --subset was given, its train/eval ids are authoritative; use # their lengths for the run-dir name instead of --n-train/--n-eval. n_train_effective = args.n_train n_eval_effective = args.n_eval subset_data: dict | None = None if args.subset: if not args.subset.exists(): raise SystemExit(f"--subset file not found: {args.subset}") subset_data = json.loads(args.subset.read_text()) # Suite must match the subset's suite so MBPP+ ids don't get # fed to a swebench run or vice versa. if subset_data.get("suite") and subset_data["suite"] != args.suite: raise SystemExit( f"--subset suite={subset_data['suite']!r} does not match " f"--suite={args.suite!r}" ) n_train_effective = len(subset_data["train_ids"]) n_eval_effective = len(subset_data["eval_ids"]) run_dir = args.out or _default_run_dir( cfg, args.suite, args.tag, rounds=args.rounds, n_train=n_train_effective, n_eval=n_eval_effective, ) # Each adapter declares its own CLI surface via pack_cli_kwargs — # the loop body doesn't need to know which suite is selected. adapter = ADAPTERS[args.suite]() suite_kwargs: dict = adapter.pack_cli_kwargs(args) if subset_data is not None: suite_kwargs["train_ids"] = subset_data["train_ids"] suite_kwargs["eval_ids"] = subset_data["eval_ids"] # Audit trail in config.json so you can trace "which subset # did this run use" without diff'ing train_ids.json vs the # subset files on disk. suite_kwargs["subset_source"] = str(args.subset) run_loop( suite=args.suite, n_train=args.n_train, n_eval=args.n_eval, rounds=args.rounds, seed=args.seed, run_dir=run_dir, min_delta=args.min_delta, min_rounds=args.min_rounds, suite_kwargs=suite_kwargs, db_mode=args.db_mode, rollback_threshold=args.rollback_threshold, rollback_consecutive=args.rollback_consecutive, keep_last_snapshots=args.keep_last_snapshots, use_solver_cache=args.solver_cache, meta_every=args.meta_every, skill_bank_max=args.skill_bank_max, force_no_skill=args.force_no_skill, retrieval_only=args.retrieval_only, no_meta_injection=args.no_meta_injection, no_synth=args.no_synth, skill_retire_min_tasks=args.skill_retire_min_tasks, skill_retire_contribution_threshold=( args.skill_retire_contribution_threshold ), pattern_canon_threshold=args.pattern_canon_threshold, pattern_canon_already_covered_threshold=( args.pattern_canon_already_covered_threshold ), max_skills_per_round=args.max_skills_per_round, ) return 0 if __name__ == "__main__": sys.exit(main())