Skip to content

Mission reference

Public Pydantic Graph assembly for the Lycurgus mission orchestrator.

(c) Mike Casale 2026. Licensed under the MIT License.

Durable five-phase mission graph executed only in isolated worker processes.

(c) Mike Casale 2026. Licensed under the MIT License.

MissionState

Bases: BaseModel

Versioned replay state, with submission uncertainty preserved across restarts.

Source code in agent_k/mission.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
class MissionState(BaseModel):
    """Versioned replay state, with submission uncertainty preserved across restarts."""

    schema_version: str = "2.0"
    mission_id: uuid.UUID
    competition: Competition | None = None
    criteria: MissionCriteria = Field(default_factory=MissionCriteria)
    phases_completed: list[str] = Field(default_factory=list)
    manifest: DatasetManifest | None = None
    splits: PreparedSplitSet | None = None
    research: ResearchReport | None = None
    baseline_spec: CandidateSpec | None = None
    baseline: EvaluationResult | None = None
    reference_baseline: EvaluationResult | None = None
    reference_spec: CandidateSpec | None = None
    baselines: list[EvaluationResult] = Field(default_factory=list)
    evolution: EvolutionOutcome | None = None
    acceptance: EvaluationResult | None = None
    native_checkpoint: str | None = None
    evolution_iterations: int = 0
    selected_program: str | None = None
    seed_program: str | None = None
    submission_state: Literal[
        "none", "prepared", "uncertain", "pending", "complete", "disabled"
    ] = "none"
    submission: Submission | None = None
    submission_sha256: str | None = None
    historical_submission_ids: tuple[str, ...] = ()
    submission_reconciliation_required: bool = False
    artifact_references: list[ArtifactReference] = Field(default_factory=list)
    legacy_program_code: str | None = None

MissionContext dataclass

Services and paths owned by one mission subprocess.

Source code in agent_k/mission.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
@dataclass
class MissionContext:
    """Services and paths owned by one mission subprocess."""

    job: JobLease
    client: WorkerApiClient
    workdir: Path
    settings: Settings
    adapter: KaggleAdapter
    http_client: httpx.AsyncClient
    tracker: MissionTracker
    emitter: EventEmitter
    started: float = field(default_factory=time.monotonic)
    data_artifact: dict[str, Any] | None = None

    async def phase(
        self,
        name: str,
        state: MissionState,
        operation: Callable[[MissionState], Awaitable[None]],
    ) -> None:
        """Execute one phase with a hard deadline and durable completion boundary."""
        await self.check_control(state)
        if name in state.phases_completed:
            return
        started = time.monotonic()
        await self.emitter.emit_phase_start(name, [f"Complete {name} using validated evidence"])
        with logfire.span("mission_phase {phase}", phase=name, mission_id=str(state.mission_id)):
            try:
                async with asyncio.timeout(self.settings.phase_timeout_seconds):
                    await operation(state)
            except MissionInterrupted:
                raise
            except Exception as exc:
                await self.emitter.emit_phase_error(name, str(exc), recoverable=False)
                raise
        state.phases_completed.append(name)
        await self.emitter.emit_phase_complete(name, True, int((time.monotonic() - started) * 1000))
        await self.checkpoint(state)

    async def discovery(self, state: MissionState) -> None:
        """Select an observed competition or resolve the explicitly supplied slug."""
        await self.adapter.authenticate()
        if self.job.command.competition_id:
            state.competition = await self.adapter.get_competition(self.job.command.competition_id)
            return
        deps = LobbyistDeps(self.adapter, state.criteria)
        candidates = await search_candidates(deps)
        if not candidates:
            raise ValueError("No active competition satisfies the mission criteria")
        if len(candidates) == 1:
            state.competition = candidates[0]
            return
        result = await lobbyist_agent.run(
            state.criteria.model_dump_json(),
            deps=deps,
            model=self._agent_model(),
            model_settings=self._agent_model_settings(),
            usage_limits=self._agent_usage_limits(),
        )
        state.competition = deps.observed[result.output.competition_id]

    async def research(self, state: MissionState) -> None:
        """Download, discover, split, and research without reading acceptance labels."""
        competition = _competition(state)
        dataset_root = self.workdir / "dataset"
        await self.adapter.download_data(competition.id, str(dataset_root))
        _extract_archives(dataset_root)
        manifest = discover_dataset(dataset_root, metric_id=_metric(competition).value)
        splits = await asyncio.to_thread(
            materialize_trusted_splits,
            manifest,
            dataset_root,
            self.workdir / "inputs",
            self.workdir / "trusted",
        )
        state.manifest, state.splits = manifest, splits
        if state.research is not None:
            return
        training = await asyncio.to_thread(
            read_table,
            Path(splits.validation.candidate_input_root) / splits.validation.manifest.train.path,
        )
        profile = profile_training_data(training)
        deps = ScientistDeps(self.http_client, self.adapter, competition, profile)
        try:
            result = await scientist_agent.run(
                json.dumps(
                    {
                        "competition": competition.model_dump(mode="json"),
                        "problem_type": manifest.problem_type.value,
                        "profile": summarize_profile(profile),
                    }
                ),
                deps=deps,
                model=self._agent_model(),
                model_settings=self._agent_model_settings(),
                usage_limits=self._agent_usage_limits(),
            )
        except (AgentRunError, FallbackExceptionGroup, httpx.HTTPError) as exc:
            # Research is advisory: measured baselines and evolution do not depend on it.
            reason = type(exc).__name__
            logfire.warn("research_agent_unavailable", error_type=reason)
            await self.emitter.emit(
                "task-error",
                {
                    "taskId": "research-agent",
                    "error": reason,
                    "message": "Research agent failed; continuing with training-profile guidance",
                },
            )
            state.research = profile_report(profile, reason=reason)
            return
        state.research = result.output

    async def prototype(self, state: MissionState) -> None:
        """Evaluate a real baseline and, when configured, a fixed Kumo challenger."""
        manifest, splits = _dataset(state)
        engine = {
            DataModality.TABULAR: CandidateEngine.LIGHTGBM,
            DataModality.VISION: CandidateEngine.RESNET18,
            DataModality.TEXT: CandidateEngine.TFIDF_LINEAR,
        }[manifest.problem_type.modality]
        parameters: dict[str, Any] = {}
        if engine is CandidateEngine.LIGHTGBM:
            loss = "squared_error"
            if manifest.problem_type.task is TaskKind.CLASSIFICATION:
                loss = (
                    "binary_log_loss" if len(manifest.class_labels) == 2 else "multiclass_log_loss"
                )
            parameters["loss"] = {"loss_id": loss}
        assets = self._offline_assets(engine, Path(splits.validation.candidate_input_root))
        spec = build_candidate_spec(
            splits.validation,
            candidate_id="baseline",
            engine=engine,
            metric_id=_metric(_competition(state)),
            hyperparameters=parameters,
            offline_assets=assets,
        )
        program = self.workdir / "baseline.py"
        write_seed_program(program)
        context = self._evaluation_context(state, spec)
        score = await asyncio.to_thread(evaluate_program, program, context)
        state.baseline, state.baseline_spec = score, spec
        state.reference_baseline, state.reference_spec = score, spec
        state.baselines.append(score)
        state.selected_program = str(program)
        if state.criteria.enable_kumo and manifest.problem_type.modality is DataModality.TABULAR:
            await self._kumo_challenger(state, program)
        if state.legacy_program_code:
            await self._legacy_challenger(state)
        state.seed_program = state.selected_program

    async def evolution(self, state: MissionState) -> None:
        """Run OpenEvolve's native search with per-iteration durable checkpoints."""
        if state.baseline is None or state.baseline_spec is None or state.selected_program is None:
            raise ValueError("A validated baseline is required before evolution")

        async def publish(checkpoint: Path, iteration: int) -> None:
            state.native_checkpoint = str(checkpoint)
            state.evolution_iterations = iteration
            await self.checkpoint(state)
            metrics = [
                json.loads(path.read_text(encoding="utf-8")).get("metrics", {})
                for path in checkpoint.glob("programs/*.json")
            ]
            scores = [
                float(item["combined_score"])
                for item in metrics
                if item.get("valid") == 1 and item.get("full_evaluation") == 1
            ]
            if scores:
                await self.emitter.emit_generation_complete(
                    iteration,
                    best_fitness=max(scores),
                    mean_fitness=sum(scores) / len(scores),
                    worst_fitness=min(scores),
                    population_size=len(scores),
                    mutations={},
                    iteration=iteration,
                    total_iterations=state.criteria.max_evolution_rounds,
                )

        settings = EvolutionSettings(
            iterations=state.criteria.max_evolution_rounds,
            minimum_iterations=state.criteria.min_evolution_iterations,
            minimum_improvements=state.criteria.min_improvements_required,
            model_specs=state.criteria.evolution_models or (self.settings.model,),
            guidance=state.research.recommendations if state.research else (),
            parallel_evaluations=self.settings.evaluation_parallelism,
            evaluation_timeout_seconds=self.settings.evaluation_timeout_seconds,
        )
        state.evolution = await run_evolution(
            initial_program=Path(state.selected_program),
            baseline=state.baseline,
            context=self._evaluation_context(state, state.baseline_spec),
            settings=settings,
            checkpoint_callback=publish,
            checkpoint_path=Path(state.native_checkpoint) if state.native_checkpoint else None,
        )
        state.selected_program = state.evolution.program_path
        state.evolution_iterations = state.evolution.iterations
        await self.check_control(state)

    async def submission(self, state: MissionState) -> None:
        """Accept the selected candidate independently and optionally submit exactly once."""
        if state.submission_state == "uncertain":
            raise ValueError(
                "Previous submission receipt is uncertain; reconcile it before resuming"
            )
        if state.submission is not None:
            await self._await_submission(state)
            return
        artifact = self.workdir / "submission.csv"
        if state.submission_state == "prepared":
            if not artifact.is_file() or _digest(artifact) != state.submission_sha256:
                raise ValueError(
                    "Prepared submission artifact failed checkpoint integrity validation"
                )
        else:
            await self._accept_selected(state)
            artifact = await self._prepare_submission(state)
            state.artifact_references.append(await self.tracker.upload(artifact, role="submission"))
            state.submission_sha256 = _digest(artifact)
            state.submission_state = "prepared"
            await self.checkpoint(state)
        if not (self.settings.allow_submissions and state.criteria.allow_submission):
            state.submission_state = "disabled"
            return
        if state.evolution is None:
            raise ValueError("Evolution evidence is missing")
        if state.evolution.iterations < state.criteria.min_evolution_iterations:
            raise ValueError("Minimum evolution iteration requirement was not met")
        if state.evolution.improvements < state.criteria.min_improvements_required:
            raise ValueError("Minimum validated improvement requirement was not met")
        state.submission_state = "uncertain"
        await self.checkpoint(state)
        state.submission = await self.adapter.submit(
            _competition(state).id,
            str(artifact),
            message=f"AGENT-K mission {state.mission_id}",
        )
        state.submission_state = "pending"
        await self.checkpoint(state)
        await self._await_submission(state)

    async def checkpoint(self, state: MissionState) -> None:
        """Publish replayable data once and a compact runtime archive at each boundary."""
        archive_root = self.workdir / "archives"
        archive_root.mkdir(exist_ok=True)
        if self.data_artifact is None and state.splits is not None:
            data_path = archive_root / "dataset.tar.gz"
            _archive_paths(data_path, self.workdir, ("dataset", "inputs", "trusted"))
            reference = await self.tracker.upload(data_path, role="dataset-checkpoint")
            self.data_artifact = {
                "artifactId": str(reference.artifact_id),
                "sha256": _digest(data_path),
                "sizeBytes": data_path.stat().st_size,
            }
        state_file = self.workdir / "mission.json"
        state_file.write_text(state.model_dump_json(), encoding="utf-8")
        state_file.chmod(0o600)
        runtime = archive_root / f"runtime-{uuid.uuid4().hex}.tar.gz"
        names = ["mission.json", "baseline.py", "submission.csv"]
        if state.selected_program:
            names.append(str(Path(state.selected_program).relative_to(self.workdir)))
        if state.seed_program:
            names.append(str(Path(state.seed_program).relative_to(self.workdir)))
        if state.native_checkpoint:
            names.append(str(Path(state.native_checkpoint).relative_to(self.workdir)))
        _archive_paths(runtime, self.workdir, tuple(dict.fromkeys(names)))
        reference = await self.tracker.upload(runtime, role="runtime-checkpoint")
        payload = {
            "workspaceRoot": str(self.workdir),
            "state": state.model_dump(mode="json"),
            "dataArtifact": self.data_artifact,
            "runtimeArtifact": {
                "artifactId": str(reference.artifact_id),
                "sha256": _digest(runtime),
                "sizeBytes": runtime.stat().st_size,
            },
        }
        await self.emitter.emit(
            "checkpoint-created",
            {
                "name": runtime.name,
                "phase": state.phases_completed[-1] if state.phases_completed else "discovery",
            },
        )
        await self.client.save_snapshot(
            self.job,
            MissionSnapshot(
                sequence=self.tracker.sequence, created_at=datetime.now(UTC), payload=payload
            ),
        )
        runtime.unlink()

    async def check_control(self, state: MissionState) -> None:
        """Acknowledge pause or cancel only after a durable snapshot exists."""
        directive = await self.client.get_control(self.job)
        if directive.action is ControlAction.CONTINUE:
            return
        await self.checkpoint(state)
        action: Literal["pause", "cancel"] = (
            "pause" if directive.action is ControlAction.PAUSE else "cancel"
        )
        if action == "pause":
            await self.emitter.emit(
                "state-delta",
                [
                    {"op": "replace", "path": "/status", "value": "paused"},
                ],
            )
        else:
            await self.emitter.emit_mission_complete(
                success=False,
                final_rank=None,
                final_score=None,
                error_message=directive.reason or action,
                total_submissions=int(state.submission is not None),
                evolution_generations=state.evolution_iterations,
                evolution_iterations=state.evolution_iterations,
                duration_ms=int((time.monotonic() - self.started) * 1000),
                phases_completed=state.phases_completed,
            )
        raise MissionInterrupted(
            action, directive.reason, final_event_sequence=self.tracker.sequence
        )

    def _agent_model(self) -> Model | str:
        return resolve_model(self.settings.model, *self.settings.fallback_models)

    def _agent_model_settings(self) -> ModelSettings:
        return ModelSettings(timeout=self.settings.agent_request_timeout_seconds)

    def _agent_usage_limits(self) -> UsageLimits:
        return UsageLimits(request_limit=self.settings.agent_request_limit)

    def _evaluation_context(
        self, state: MissionState, spec: CandidateSpec, *, acceptance: bool = False
    ) -> EvolutionContext:
        _, splits = _dataset(state)
        if self.settings.sandbox_image is None:
            raise ValueError("AGENT_K_SANDBOX_IMAGE must pin an immutable candidate image digest")
        return EvolutionContext(
            split=splits.acceptance if acceptance else splits.validation,
            spec=spec,
            image=self.settings.sandbox_image,
            workdir=str(self.workdir / "evolution"),
            limits=SandboxLimits(wall_seconds=self.settings.evaluation_timeout_seconds),
            gpu_devices=self.settings.gpu_devices
            if spec.engine
            in {
                CandidateEngine.KUMO,
                CandidateEngine.RESNET18,
                CandidateEngine.TRANSFORMER,
            }
            else (),
        )

    async def _kumo_challenger(self, state: MissionState, program: Path) -> None:
        _, splits = _dataset(state)
        if not self.settings.gpu_devices:
            await self.emitter.emit(
                "task-progress",
                {
                    "taskId": "kumo",
                    "progress": 100,
                    "message": "Kumo skipped: a validated GPU worker is not configured",
                },
            )
            return
        if self.settings.kumo_cache is None:
            await self.emitter.emit(
                "task-progress",
                {
                    "taskId": "kumo",
                    "progress": 100,
                    "message": "Kumo skipped: verified offline weights are not configured",
                },
            )
            return
        assets = self._offline_assets(
            CandidateEngine.KUMO, Path(splits.validation.candidate_input_root)
        )
        spec = build_candidate_spec(
            splits.validation,
            candidate_id="kumo",
            engine=CandidateEngine.KUMO,
            metric_id=_metric(_competition(state)),
            hyperparameters={"size": "small", "num_estimators": 8},
            offline_assets=assets,
        )
        try:
            result = await asyncio.to_thread(
                evaluate_program, program, self._evaluation_context(state, spec)
            )
        except (ValueError, RuntimeError, FileNotFoundError) as exc:
            await self.emitter.emit(
                "task-error",
                {
                    "taskId": "kumo",
                    "error": str(exc),
                    "message": "Kumo evaluation failed; retaining the validated LightGBM baseline",
                },
            )
            return
        state.baselines.append(result)
        if state.baseline is not None and _better(result, state.baseline):
            state.baseline, state.baseline_spec = result, spec

    def _offline_assets(self, engine: CandidateEngine, input_root: Path) -> dict[str, str]:
        sources = {
            CandidateEngine.KUMO: ("kumo", self.settings.kumo_cache),
            CandidateEngine.RESNET18: ("vision", self.settings.vision_weights),
            CandidateEngine.TRANSFORMER: ("transformer", self.settings.transformer_cache),
        }
        if engine not in sources:
            return {}
        name, source = sources[engine]
        if source is None:
            if engine is CandidateEngine.RESNET18:
                return {}
            raise ValueError(f"Verified offline assets are required for {engine.value}")
        if engine is CandidateEngine.RESNET18 and not source.is_file():
            raise ValueError("Vision pretrained weights must be a checkpoint file")
        destination = input_root / "assets" / name
        if not destination.exists():
            destination.parent.mkdir(exist_ok=True)
            if source.is_dir():
                shutil.copytree(source, destination)
            else:
                shutil.copy2(source, destination)
        relative = str(destination.relative_to(input_root))
        if engine is CandidateEngine.KUMO:
            return {
                "hf_cache": relative + "/hf-cache",
                "kumo_manifest": relative + "/manifest.json",
            }
        if engine is CandidateEngine.RESNET18:
            return {"resnet18_weights": relative}
        return {"transformer_model": relative}

    async def _accept_selected(self, state: MissionState) -> None:
        _, splits = _dataset(state)
        if state.baseline_spec is None or state.selected_program is None:
            raise ValueError("Missing selected candidate")
        assets = self._offline_assets(
            state.baseline_spec.engine, Path(splits.acceptance.candidate_input_root)
        )
        spec = build_candidate_spec(
            splits.acceptance,
            candidate_id="acceptance",
            engine=state.baseline_spec.engine,
            metric_id=state.baseline_spec.metric_id,
            hyperparameters=state.baseline_spec.hyperparameters,
            offline_assets=assets,
        )
        context = self._evaluation_context(state, spec, acceptance=True)
        baseline_program = self.workdir / "baseline.py"
        reference_spec = state.reference_spec or state.baseline_spec
        reference_assets = self._offline_assets(
            reference_spec.engine, Path(splits.acceptance.candidate_input_root)
        )
        reference = build_candidate_spec(
            splits.acceptance,
            candidate_id="acceptance-baseline",
            engine=reference_spec.engine,
            metric_id=reference_spec.metric_id,
            hyperparameters=reference_spec.hyperparameters,
            offline_assets=reference_assets,
        )
        baseline = await asyncio.to_thread(
            evaluate_program,
            baseline_program,
            self._evaluation_context(state, reference, acceptance=True),
        )
        winning_spec = reference_spec
        winning_validation = state.reference_baseline or state.baseline
        seed_program = Path(state.seed_program) if state.seed_program else baseline_program
        if seed_program != baseline_program or state.baseline_spec != reference_spec:
            try:
                seed = await asyncio.to_thread(evaluate_program, seed_program, context)
            except ValueError as exc:
                await self.emitter.emit(
                    "task-error",
                    {
                        "taskId": "acceptance-seed",
                        "error": str(exc),
                    },
                )
            else:
                if _better(seed, baseline):
                    baseline = seed
                    baseline_program = seed_program
                    winning_spec = state.baseline_spec
                    winning_validation = state.baseline
        try:
            selected = await asyncio.to_thread(
                evaluate_program, Path(state.selected_program), context
            )
        except ValueError as exc:
            await self.emitter.emit(
                "task-error",
                {
                    "taskId": "acceptance-selected",
                    "error": str(exc),
                },
            )
            selected = baseline
        state.acceptance = selected
        if not _better(selected, baseline):
            state.selected_program = str(baseline_program)
            state.acceptance = baseline
            state.baseline_spec = winning_spec
            state.baseline = winning_validation
            if state.evolution is not None:
                state.evolution = state.evolution.model_copy(
                    update={
                        "selected_baseline": True,
                        "program_path": str(baseline_program),
                        "improvements": 0,
                        "validation": state.baseline,
                    }
                )

    async def _await_submission(self, state: MissionState) -> None:
        if state.submission is None:
            raise ValueError("Cannot await a submission without a receipt")
        deadline = time.monotonic() + min(300, self.settings.phase_timeout_seconds - 1)
        while time.monotonic() < deadline:
            await self.check_control(state)
            state.submission = await self.adapter.get_submission_status(
                _competition(state).id,
                state.submission.id,
            )
            if state.submission.status == "complete":
                state.submission_state = "complete"
                return
            if state.submission.status == "error":
                raise ValueError(state.submission.error_message or "Kaggle rejected the submission")
            await asyncio.sleep(10)
        await self.checkpoint(state)
        raise TimeoutError("Kaggle evaluation is pending; resume will poll the existing receipt")

    async def _legacy_challenger(self, state: MissionState) -> None:
        if not state.legacy_program_code or state.baseline_spec is None or state.baseline is None:
            return
        program = self.workdir / "legacy.py"
        program.write_text(state.legacy_program_code, encoding="utf-8")
        try:
            result = await asyncio.to_thread(
                evaluate_program,
                program,
                self._evaluation_context(state, state.baseline_spec),
            )
        except (ValueError, OSError, RuntimeError) as exc:
            await self.emitter.emit(
                "task-error",
                {
                    "taskId": "legacy-validation",
                    "error": str(exc),
                    "message": "Legacy program did not pass the current prediction contract; using the validated baseline",
                },
            )
        else:
            state.baselines.append(result)
            if _better(result, state.baseline):
                state.baseline = result
                state.selected_program = str(program)
        state.legacy_program_code = None

    async def _prepare_submission(self, state: MissionState) -> Path:
        from .evaluator import write_submission

        manifest, _ = _dataset(state)
        if state.baseline_spec is None or state.selected_program is None:
            raise ValueError("Missing selected candidate")
        input_root = self.workdir / "dataset"
        assets = self._offline_assets(state.baseline_spec.engine, input_root)
        spec = build_submission_spec(
            manifest,
            candidate_id="submission",
            engine=state.baseline_spec.engine,
            metric_id=state.baseline_spec.metric_id,
            hyperparameters=state.baseline_spec.hyperparameters,
            offline_assets=assets,
        )
        (input_root / "spec.json").write_text(spec.model_dump_json(), encoding="utf-8")
        output_root = self.workdir / "submission"
        output_root.mkdir(exist_ok=True)
        if self.settings.sandbox_image is None:
            raise ValueError("Sandbox image is required")
        execution = await run_candidate_sandbox(
            SandboxRequest(
                image=self.settings.sandbox_image,
                input_root=input_root,
                output_root=output_root,
                candidate_program=Path(state.selected_program),
                limits=SandboxLimits(wall_seconds=self.settings.evaluation_timeout_seconds),
                gpu_devices=self.settings.gpu_devices
                if spec.engine
                in {
                    CandidateEngine.KUMO,
                    CandidateEngine.RESNET18,
                    CandidateEngine.TRANSFORMER,
                }
                else (),
            ),
        )
        if (
            execution.exit_code
            or execution.timed_out
            or execution.oom_killed
            or execution.output_limit_exceeded
        ):
            raise ValueError("Submission inference failed")
        result = CandidateResult.model_validate_json((output_root / "result.json").read_bytes())
        if (
            result.status is not CandidateStatus.SUCCEEDED
            or result.candidate_id != spec.candidate_id
        ):
            raise ValueError("Submission result identity or terminal status is invalid")
        if result.predictions_path is None:
            raise ValueError("Submission inference produced no predictions")
        prediction = (output_root / result.predictions_path).resolve()
        if not prediction.is_relative_to(output_root.resolve()) or prediction.is_symlink():
            raise ValueError("Submission predictions escaped their output directory")
        if _digest(prediction) != result.predictions_sha256:
            raise ValueError("Submission prediction digest does not match the result contract")
        destination = self.workdir / "submission.csv"
        write_submission(prediction, manifest, input_root, destination, metric_id=spec.metric_id)
        return destination

phase async

phase(name: str, state: MissionState, operation: Callable[[MissionState], Awaitable[None]]) -> None

Execute one phase with a hard deadline and durable completion boundary.

Source code in agent_k/mission.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
async def phase(
    self,
    name: str,
    state: MissionState,
    operation: Callable[[MissionState], Awaitable[None]],
) -> None:
    """Execute one phase with a hard deadline and durable completion boundary."""
    await self.check_control(state)
    if name in state.phases_completed:
        return
    started = time.monotonic()
    await self.emitter.emit_phase_start(name, [f"Complete {name} using validated evidence"])
    with logfire.span("mission_phase {phase}", phase=name, mission_id=str(state.mission_id)):
        try:
            async with asyncio.timeout(self.settings.phase_timeout_seconds):
                await operation(state)
        except MissionInterrupted:
            raise
        except Exception as exc:
            await self.emitter.emit_phase_error(name, str(exc), recoverable=False)
            raise
    state.phases_completed.append(name)
    await self.emitter.emit_phase_complete(name, True, int((time.monotonic() - started) * 1000))
    await self.checkpoint(state)

discovery async

discovery(state: MissionState) -> None

Select an observed competition or resolve the explicitly supplied slug.

Source code in agent_k/mission.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
async def discovery(self, state: MissionState) -> None:
    """Select an observed competition or resolve the explicitly supplied slug."""
    await self.adapter.authenticate()
    if self.job.command.competition_id:
        state.competition = await self.adapter.get_competition(self.job.command.competition_id)
        return
    deps = LobbyistDeps(self.adapter, state.criteria)
    candidates = await search_candidates(deps)
    if not candidates:
        raise ValueError("No active competition satisfies the mission criteria")
    if len(candidates) == 1:
        state.competition = candidates[0]
        return
    result = await lobbyist_agent.run(
        state.criteria.model_dump_json(),
        deps=deps,
        model=self._agent_model(),
        model_settings=self._agent_model_settings(),
        usage_limits=self._agent_usage_limits(),
    )
    state.competition = deps.observed[result.output.competition_id]

research async

research(state: MissionState) -> None

Download, discover, split, and research without reading acceptance labels.

Source code in agent_k/mission.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
async def research(self, state: MissionState) -> None:
    """Download, discover, split, and research without reading acceptance labels."""
    competition = _competition(state)
    dataset_root = self.workdir / "dataset"
    await self.adapter.download_data(competition.id, str(dataset_root))
    _extract_archives(dataset_root)
    manifest = discover_dataset(dataset_root, metric_id=_metric(competition).value)
    splits = await asyncio.to_thread(
        materialize_trusted_splits,
        manifest,
        dataset_root,
        self.workdir / "inputs",
        self.workdir / "trusted",
    )
    state.manifest, state.splits = manifest, splits
    if state.research is not None:
        return
    training = await asyncio.to_thread(
        read_table,
        Path(splits.validation.candidate_input_root) / splits.validation.manifest.train.path,
    )
    profile = profile_training_data(training)
    deps = ScientistDeps(self.http_client, self.adapter, competition, profile)
    try:
        result = await scientist_agent.run(
            json.dumps(
                {
                    "competition": competition.model_dump(mode="json"),
                    "problem_type": manifest.problem_type.value,
                    "profile": summarize_profile(profile),
                }
            ),
            deps=deps,
            model=self._agent_model(),
            model_settings=self._agent_model_settings(),
            usage_limits=self._agent_usage_limits(),
        )
    except (AgentRunError, FallbackExceptionGroup, httpx.HTTPError) as exc:
        # Research is advisory: measured baselines and evolution do not depend on it.
        reason = type(exc).__name__
        logfire.warn("research_agent_unavailable", error_type=reason)
        await self.emitter.emit(
            "task-error",
            {
                "taskId": "research-agent",
                "error": reason,
                "message": "Research agent failed; continuing with training-profile guidance",
            },
        )
        state.research = profile_report(profile, reason=reason)
        return
    state.research = result.output

prototype async

prototype(state: MissionState) -> None

Evaluate a real baseline and, when configured, a fixed Kumo challenger.

Source code in agent_k/mission.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
async def prototype(self, state: MissionState) -> None:
    """Evaluate a real baseline and, when configured, a fixed Kumo challenger."""
    manifest, splits = _dataset(state)
    engine = {
        DataModality.TABULAR: CandidateEngine.LIGHTGBM,
        DataModality.VISION: CandidateEngine.RESNET18,
        DataModality.TEXT: CandidateEngine.TFIDF_LINEAR,
    }[manifest.problem_type.modality]
    parameters: dict[str, Any] = {}
    if engine is CandidateEngine.LIGHTGBM:
        loss = "squared_error"
        if manifest.problem_type.task is TaskKind.CLASSIFICATION:
            loss = (
                "binary_log_loss" if len(manifest.class_labels) == 2 else "multiclass_log_loss"
            )
        parameters["loss"] = {"loss_id": loss}
    assets = self._offline_assets(engine, Path(splits.validation.candidate_input_root))
    spec = build_candidate_spec(
        splits.validation,
        candidate_id="baseline",
        engine=engine,
        metric_id=_metric(_competition(state)),
        hyperparameters=parameters,
        offline_assets=assets,
    )
    program = self.workdir / "baseline.py"
    write_seed_program(program)
    context = self._evaluation_context(state, spec)
    score = await asyncio.to_thread(evaluate_program, program, context)
    state.baseline, state.baseline_spec = score, spec
    state.reference_baseline, state.reference_spec = score, spec
    state.baselines.append(score)
    state.selected_program = str(program)
    if state.criteria.enable_kumo and manifest.problem_type.modality is DataModality.TABULAR:
        await self._kumo_challenger(state, program)
    if state.legacy_program_code:
        await self._legacy_challenger(state)
    state.seed_program = state.selected_program

evolution async

evolution(state: MissionState) -> None

Run OpenEvolve's native search with per-iteration durable checkpoints.

Source code in agent_k/mission.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
async def evolution(self, state: MissionState) -> None:
    """Run OpenEvolve's native search with per-iteration durable checkpoints."""
    if state.baseline is None or state.baseline_spec is None or state.selected_program is None:
        raise ValueError("A validated baseline is required before evolution")

    async def publish(checkpoint: Path, iteration: int) -> None:
        state.native_checkpoint = str(checkpoint)
        state.evolution_iterations = iteration
        await self.checkpoint(state)
        metrics = [
            json.loads(path.read_text(encoding="utf-8")).get("metrics", {})
            for path in checkpoint.glob("programs/*.json")
        ]
        scores = [
            float(item["combined_score"])
            for item in metrics
            if item.get("valid") == 1 and item.get("full_evaluation") == 1
        ]
        if scores:
            await self.emitter.emit_generation_complete(
                iteration,
                best_fitness=max(scores),
                mean_fitness=sum(scores) / len(scores),
                worst_fitness=min(scores),
                population_size=len(scores),
                mutations={},
                iteration=iteration,
                total_iterations=state.criteria.max_evolution_rounds,
            )

    settings = EvolutionSettings(
        iterations=state.criteria.max_evolution_rounds,
        minimum_iterations=state.criteria.min_evolution_iterations,
        minimum_improvements=state.criteria.min_improvements_required,
        model_specs=state.criteria.evolution_models or (self.settings.model,),
        guidance=state.research.recommendations if state.research else (),
        parallel_evaluations=self.settings.evaluation_parallelism,
        evaluation_timeout_seconds=self.settings.evaluation_timeout_seconds,
    )
    state.evolution = await run_evolution(
        initial_program=Path(state.selected_program),
        baseline=state.baseline,
        context=self._evaluation_context(state, state.baseline_spec),
        settings=settings,
        checkpoint_callback=publish,
        checkpoint_path=Path(state.native_checkpoint) if state.native_checkpoint else None,
    )
    state.selected_program = state.evolution.program_path
    state.evolution_iterations = state.evolution.iterations
    await self.check_control(state)

submission async

submission(state: MissionState) -> None

Accept the selected candidate independently and optionally submit exactly once.

Source code in agent_k/mission.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
async def submission(self, state: MissionState) -> None:
    """Accept the selected candidate independently and optionally submit exactly once."""
    if state.submission_state == "uncertain":
        raise ValueError(
            "Previous submission receipt is uncertain; reconcile it before resuming"
        )
    if state.submission is not None:
        await self._await_submission(state)
        return
    artifact = self.workdir / "submission.csv"
    if state.submission_state == "prepared":
        if not artifact.is_file() or _digest(artifact) != state.submission_sha256:
            raise ValueError(
                "Prepared submission artifact failed checkpoint integrity validation"
            )
    else:
        await self._accept_selected(state)
        artifact = await self._prepare_submission(state)
        state.artifact_references.append(await self.tracker.upload(artifact, role="submission"))
        state.submission_sha256 = _digest(artifact)
        state.submission_state = "prepared"
        await self.checkpoint(state)
    if not (self.settings.allow_submissions and state.criteria.allow_submission):
        state.submission_state = "disabled"
        return
    if state.evolution is None:
        raise ValueError("Evolution evidence is missing")
    if state.evolution.iterations < state.criteria.min_evolution_iterations:
        raise ValueError("Minimum evolution iteration requirement was not met")
    if state.evolution.improvements < state.criteria.min_improvements_required:
        raise ValueError("Minimum validated improvement requirement was not met")
    state.submission_state = "uncertain"
    await self.checkpoint(state)
    state.submission = await self.adapter.submit(
        _competition(state).id,
        str(artifact),
        message=f"AGENT-K mission {state.mission_id}",
    )
    state.submission_state = "pending"
    await self.checkpoint(state)
    await self._await_submission(state)

checkpoint async

checkpoint(state: MissionState) -> None

Publish replayable data once and a compact runtime archive at each boundary.

Source code in agent_k/mission.py
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
async def checkpoint(self, state: MissionState) -> None:
    """Publish replayable data once and a compact runtime archive at each boundary."""
    archive_root = self.workdir / "archives"
    archive_root.mkdir(exist_ok=True)
    if self.data_artifact is None and state.splits is not None:
        data_path = archive_root / "dataset.tar.gz"
        _archive_paths(data_path, self.workdir, ("dataset", "inputs", "trusted"))
        reference = await self.tracker.upload(data_path, role="dataset-checkpoint")
        self.data_artifact = {
            "artifactId": str(reference.artifact_id),
            "sha256": _digest(data_path),
            "sizeBytes": data_path.stat().st_size,
        }
    state_file = self.workdir / "mission.json"
    state_file.write_text(state.model_dump_json(), encoding="utf-8")
    state_file.chmod(0o600)
    runtime = archive_root / f"runtime-{uuid.uuid4().hex}.tar.gz"
    names = ["mission.json", "baseline.py", "submission.csv"]
    if state.selected_program:
        names.append(str(Path(state.selected_program).relative_to(self.workdir)))
    if state.seed_program:
        names.append(str(Path(state.seed_program).relative_to(self.workdir)))
    if state.native_checkpoint:
        names.append(str(Path(state.native_checkpoint).relative_to(self.workdir)))
    _archive_paths(runtime, self.workdir, tuple(dict.fromkeys(names)))
    reference = await self.tracker.upload(runtime, role="runtime-checkpoint")
    payload = {
        "workspaceRoot": str(self.workdir),
        "state": state.model_dump(mode="json"),
        "dataArtifact": self.data_artifact,
        "runtimeArtifact": {
            "artifactId": str(reference.artifact_id),
            "sha256": _digest(runtime),
            "sizeBytes": runtime.stat().st_size,
        },
    }
    await self.emitter.emit(
        "checkpoint-created",
        {
            "name": runtime.name,
            "phase": state.phases_completed[-1] if state.phases_completed else "discovery",
        },
    )
    await self.client.save_snapshot(
        self.job,
        MissionSnapshot(
            sequence=self.tracker.sequence, created_at=datetime.now(UTC), payload=payload
        ),
    )
    runtime.unlink()

check_control async

check_control(state: MissionState) -> None

Acknowledge pause or cancel only after a durable snapshot exists.

Source code in agent_k/mission.py
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
async def check_control(self, state: MissionState) -> None:
    """Acknowledge pause or cancel only after a durable snapshot exists."""
    directive = await self.client.get_control(self.job)
    if directive.action is ControlAction.CONTINUE:
        return
    await self.checkpoint(state)
    action: Literal["pause", "cancel"] = (
        "pause" if directive.action is ControlAction.PAUSE else "cancel"
    )
    if action == "pause":
        await self.emitter.emit(
            "state-delta",
            [
                {"op": "replace", "path": "/status", "value": "paused"},
            ],
        )
    else:
        await self.emitter.emit_mission_complete(
            success=False,
            final_rank=None,
            final_score=None,
            error_message=directive.reason or action,
            total_submissions=int(state.submission is not None),
            evolution_generations=state.evolution_iterations,
            evolution_iterations=state.evolution_iterations,
            duration_ms=int((time.monotonic() - self.started) * 1000),
            phases_completed=state.phases_completed,
        )
    raise MissionInterrupted(
        action, directive.reason, final_event_sequence=self.tracker.sequence
    )

DiscoveryNode dataclass

Bases: BaseNode[MissionState, MissionContext, MissionRunResult]

Select a competition and transition to research.

Source code in agent_k/mission.py
759
760
761
762
763
764
765
766
@dataclass
class DiscoveryNode(BaseNode[MissionState, MissionContext, MissionRunResult]):
    """Select a competition and transition to research."""

    async def run(self, ctx: GraphRunContext[MissionState, MissionContext]) -> ResearchNode:
        """Complete discovery through the shared phase lifecycle."""
        await ctx.deps.phase("discovery", ctx.state, ctx.deps.discovery)
        return ResearchNode()

run async

run(ctx: GraphRunContext[MissionState, MissionContext]) -> ResearchNode

Complete discovery through the shared phase lifecycle.

Source code in agent_k/mission.py
763
764
765
766
async def run(self, ctx: GraphRunContext[MissionState, MissionContext]) -> ResearchNode:
    """Complete discovery through the shared phase lifecycle."""
    await ctx.deps.phase("discovery", ctx.state, ctx.deps.discovery)
    return ResearchNode()

ResearchNode dataclass

Bases: BaseNode[MissionState, MissionContext, MissionRunResult]

Discover dataset structure and collect evidence.

Source code in agent_k/mission.py
769
770
771
772
773
774
775
776
@dataclass
class ResearchNode(BaseNode[MissionState, MissionContext, MissionRunResult]):
    """Discover dataset structure and collect evidence."""

    async def run(self, ctx: GraphRunContext[MissionState, MissionContext]) -> PrototypeNode:
        """Complete research through the shared phase lifecycle."""
        await ctx.deps.phase("research", ctx.state, ctx.deps.research)
        return PrototypeNode()

run async

run(ctx: GraphRunContext[MissionState, MissionContext]) -> PrototypeNode

Complete research through the shared phase lifecycle.

Source code in agent_k/mission.py
773
774
775
776
async def run(self, ctx: GraphRunContext[MissionState, MissionContext]) -> PrototypeNode:
    """Complete research through the shared phase lifecycle."""
    await ctx.deps.phase("research", ctx.state, ctx.deps.research)
    return PrototypeNode()

PrototypeNode dataclass

Bases: BaseNode[MissionState, MissionContext, MissionRunResult]

Establish independently scored baselines.

Source code in agent_k/mission.py
779
780
781
782
783
784
785
786
@dataclass
class PrototypeNode(BaseNode[MissionState, MissionContext, MissionRunResult]):
    """Establish independently scored baselines."""

    async def run(self, ctx: GraphRunContext[MissionState, MissionContext]) -> EvolutionNode:
        """Complete prototyping through the shared phase lifecycle."""
        await ctx.deps.phase("prototype", ctx.state, ctx.deps.prototype)
        return EvolutionNode()

run async

run(ctx: GraphRunContext[MissionState, MissionContext]) -> EvolutionNode

Complete prototyping through the shared phase lifecycle.

Source code in agent_k/mission.py
783
784
785
786
async def run(self, ctx: GraphRunContext[MissionState, MissionContext]) -> EvolutionNode:
    """Complete prototyping through the shared phase lifecycle."""
    await ctx.deps.phase("prototype", ctx.state, ctx.deps.prototype)
    return EvolutionNode()

EvolutionNode dataclass

Bases: BaseNode[MissionState, MissionContext, MissionRunResult]

Optimize with OpenEvolve only.

Source code in agent_k/mission.py
789
790
791
792
793
794
795
796
@dataclass
class EvolutionNode(BaseNode[MissionState, MissionContext, MissionRunResult]):
    """Optimize with OpenEvolve only."""

    async def run(self, ctx: GraphRunContext[MissionState, MissionContext]) -> SubmissionNode:
        """Complete native evolution through the shared phase lifecycle."""
        await ctx.deps.phase("evolution", ctx.state, ctx.deps.evolution)
        return SubmissionNode()

run async

run(ctx: GraphRunContext[MissionState, MissionContext]) -> SubmissionNode

Complete native evolution through the shared phase lifecycle.

Source code in agent_k/mission.py
793
794
795
796
async def run(self, ctx: GraphRunContext[MissionState, MissionContext]) -> SubmissionNode:
    """Complete native evolution through the shared phase lifecycle."""
    await ctx.deps.phase("evolution", ctx.state, ctx.deps.evolution)
    return SubmissionNode()

SubmissionNode dataclass

Bases: BaseNode[MissionState, MissionContext, MissionRunResult]

Perform independent acceptance and prepare the final artifact.

Source code in agent_k/mission.py
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
@dataclass
class SubmissionNode(BaseNode[MissionState, MissionContext, MissionRunResult]):
    """Perform independent acceptance and prepare the final artifact."""

    async def run(
        self, ctx: GraphRunContext[MissionState, MissionContext]
    ) -> End[MissionRunResult]:
        """Finish the mission with truthful local and external result separation."""
        await ctx.deps.phase("submission", ctx.state, ctx.deps.submission)
        state = ctx.state
        duration = int((time.monotonic() - ctx.deps.started) * 1000)
        score = state.submission.public_score if state.submission else None
        await ctx.deps.emitter.emit_mission_complete(
            success=True,
            error_message=None,
            final_rank=None,
            final_score=score,
            total_submissions=int(state.submission is not None),
            evolution_generations=state.evolution_iterations,
            evolution_iterations=state.evolution_iterations,
            duration_ms=duration,
            phases_completed=state.phases_completed,
        )
        return End(
            MissionRunResult(
                mission_id=state.mission_id,
                competition_id=_competition(state).id,
                final_score=score,
                total_submissions=int(state.submission is not None),
                evolution_generations=state.evolution_iterations,
                evolution_iterations=state.evolution_iterations,
                duration_ms=duration,
                phases_completed=tuple(state.phases_completed),
                final_event_sequence=ctx.deps.tracker.sequence,
                artifacts=tuple(state.artifact_references),
            )
        )

run async

run(ctx: GraphRunContext[MissionState, MissionContext]) -> End[MissionRunResult]

Finish the mission with truthful local and external result separation.

Source code in agent_k/mission.py
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
async def run(
    self, ctx: GraphRunContext[MissionState, MissionContext]
) -> End[MissionRunResult]:
    """Finish the mission with truthful local and external result separation."""
    await ctx.deps.phase("submission", ctx.state, ctx.deps.submission)
    state = ctx.state
    duration = int((time.monotonic() - ctx.deps.started) * 1000)
    score = state.submission.public_score if state.submission else None
    await ctx.deps.emitter.emit_mission_complete(
        success=True,
        error_message=None,
        final_rank=None,
        final_score=score,
        total_submissions=int(state.submission is not None),
        evolution_generations=state.evolution_iterations,
        evolution_iterations=state.evolution_iterations,
        duration_ms=duration,
        phases_completed=state.phases_completed,
    )
    return End(
        MissionRunResult(
            mission_id=state.mission_id,
            competition_id=_competition(state).id,
            final_score=score,
            total_submissions=int(state.submission is not None),
            evolution_generations=state.evolution_iterations,
            evolution_iterations=state.evolution_iterations,
            duration_ms=duration,
            phases_completed=tuple(state.phases_completed),
            final_event_sequence=ctx.deps.tracker.sequence,
            artifacts=tuple(state.artifact_references),
        )
    )

run_mission async

run_mission(job: JobLease, client: WorkerApiClient, workdir: Path) -> MissionRunResult

Execute one fenced mission, restoring verified durable state when present.

Parameters:

Name Type Description Default
job JobLease

Current server-issued job lease, command, and event sequence.

required
client WorkerApiClient

Authenticated worker client used for fenced state and artifact writes.

required
workdir Path

Private directory owned exclusively by this worker attempt.

required

Returns:

Type Description
MissionRunResult

A terminal result referencing verified artifacts and the final event sequence.

Raises:

Type Description
MissionInterrupted

A pause or cancellation has been durably acknowledged.

ValueError

Configuration, restored state, or a mission contract is invalid.

TimeoutError

A phase or remote submission remains incomplete past its deadline.

Provider and Kaggle failures propagate to the worker's retry policy. A submission with an uncertain remote outcome is reconciled before any new submission attempt.

Source code in agent_k/mission.py
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
async def run_mission(job: JobLease, client: WorkerApiClient, workdir: Path) -> MissionRunResult:
    """Execute one fenced mission, restoring verified durable state when present.

    Args:
        job: Current server-issued job lease, command, and event sequence.
        client: Authenticated worker client used for fenced state and artifact writes.
        workdir: Private directory owned exclusively by this worker attempt.

    Returns:
        A terminal result referencing verified artifacts and the final event sequence.

    Raises:
        MissionInterrupted: A pause or cancellation has been durably acknowledged.
        ValueError: Configuration, restored state, or a mission contract is invalid.
        TimeoutError: A phase or remote submission remains incomplete past its deadline.

    Provider and Kaggle failures propagate to the worker's retry policy. A submission
    with an uncertain remote outcome is reconciled before any new submission attempt.
    """
    from .lycurgus import mission_graph

    settings = load_settings()
    if not settings.sandbox_image:
        raise ValueError("Worker requires AGENT_K_SANDBOX_IMAGE before accepting ML jobs")
    workdir.mkdir(parents=True, exist_ok=True, mode=0o700)
    tracker = MissionTracker(job, client, sequence=job.event_sequence)
    state = MissionState(
        mission_id=job.mission_id, criteria=MissionCriteria.model_validate(job.command.criteria)
    )
    async with httpx.AsyncClient(follow_redirects=False) as http:
        context = MissionContext(
            job=job,
            client=client,
            workdir=workdir,
            settings=settings,
            adapter=KaggleAdapter(KaggleSettings(), http),
            http_client=http,
            tracker=tracker,
            emitter=EventEmitter(str(job.mission_id), tracker),
        )
        if job.command.checkpoint_id:
            state = await _restore(context, job.command.checkpoint_id)
        if (
            state.submission_state == "uncertain"
            and state.historical_submission_ids
            and not state.submission_reconciliation_required
        ):
            receipts = [
                await context.adapter.get_submission_status(_competition(state).id, receipt_id)
                for receipt_id in state.historical_submission_ids
            ]
            if all(receipt.status == "complete" for receipt in receipts):
                state.submission = receipts[-1]
                state.submission_state = "complete"
                await context.checkpoint(state)
        if state.submission_state == "uncertain":
            raise ValueError(
                "A previous submission may have succeeded; reconcile its receipt before resuming"
            )
        if "evolution" not in state.phases_completed:
            validate_model_specs(state.criteria.evolution_models or (settings.model,))
        first: DiscoveryNode | SubmissionNode = (
            SubmissionNode() if state.submission else DiscoveryNode()
        )
        result = await mission_graph.run(first, state=state, deps=context)
        return result.output

Competition discovery with runtime dependency injection.

(c) Mike Casale 2026. Licensed under the MIT License.

LobbyistDeps dataclass

Services and evidence scoped to one discovery run.

Source code in agent_k/lobbyist.py
41
42
43
44
45
46
47
@dataclass
class LobbyistDeps:
    """Services and evidence scoped to one discovery run."""

    platform_adapter: PlatformAdapter
    criteria: MissionCriteria
    observed: dict[str, Competition] = field(default_factory=dict)

DiscoveryResult

Bases: BaseModel

Selection constrained to an observed competition identifier.

Source code in agent_k/lobbyist.py
50
51
52
53
54
55
class DiscoveryResult(BaseModel):
    """Selection constrained to an observed competition identifier."""

    model_config = ConfigDict(frozen=True)
    competition_id: str
    rationale: str = Field(min_length=1)

CompetitionSummary

Bases: BaseModel

Bounded competition evidence shown to the selecting model.

Source code in agent_k/lobbyist.py
58
59
60
61
62
63
64
65
66
67
68
69
70
class CompetitionSummary(BaseModel):
    """Bounded competition evidence shown to the selecting model."""

    model_config = ConfigDict(frozen=True)
    id: str
    title: str
    competition_type: str
    metric: str
    days_remaining: int
    prize_pool: int | None
    max_team_size: int
    tags: tuple[str, ...]
    description: str | None

search_candidates async

search_candidates(deps: LobbyistDeps) -> list[Competition]

Collect observed competitions satisfying the mission's hard constraints.

Parameters:

Name Type Description Default
deps LobbyistDeps

Platform adapter, criteria, and the evidence map to populate.

required

Returns:

Type Description
list[Competition]

At most MAX_CANDIDATES competitions, each recorded in deps.observed.

Source code in agent_k/lobbyist.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
async def search_candidates(deps: LobbyistDeps) -> list[Competition]:
    """Collect observed competitions satisfying the mission's hard constraints.

    Args:
        deps: Platform adapter, criteria, and the evidence map to populate.

    Returns:
        At most ``MAX_CANDIDATES`` competitions, each recorded in ``deps.observed``.
    """
    criteria = deps.criteria
    found: list[Competition] = []
    async for competition in deps.platform_adapter.search_competitions(
        categories=[category.value for category in criteria.target_competition_types],
        min_prize=criteria.min_prize_pool,
    ):
        if competition.days_remaining < criteria.min_days_remaining:
            continue
        if criteria.max_team_size and competition.max_team_size > criteria.max_team_size:
            continue
        if criteria.exclude_domains & competition.tags:
            continue
        if criteria.target_domains and not criteria.target_domains & competition.tags:
            continue
        found.append(competition)
        deps.observed[competition.id] = competition
        if len(found) >= MAX_CANDIDATES:
            break
    return found

discover async

discover(ctx: RunContext[LobbyistDeps]) -> list[CompetitionSummary]

Find real competitions satisfying the user's hard constraints.

Source code in agent_k/lobbyist.py
106
107
108
109
110
@lobbyist_toolset.tool
async def discover(ctx: RunContext[LobbyistDeps]) -> list[CompetitionSummary]:
    """Find real competitions satisfying the user's hard constraints."""
    candidates = list(ctx.deps.observed.values()) or await search_candidates(ctx.deps)
    return [_summarize(competition) for competition in candidates]

Evidence-bound research for an already discovered dataset.

(c) Mike Casale 2026. Licensed under the MIT License.

ResearchFinding

Bases: BaseModel

A recommendation with an observed source and a measurable validation step.

Source code in agent_k/scientist.py
48
49
50
51
52
53
54
class ResearchFinding(BaseModel):
    """A recommendation with an observed source and a measurable validation step."""

    model_config = ConfigDict(frozen=True)
    recommendation: str
    source: HttpUrl
    validation: str

ResearchReport

Bases: BaseModel

Research output, separate from measured evaluation results.

Source code in agent_k/scientist.py
57
58
59
60
61
62
63
64
65
class ResearchReport(BaseModel):
    """Research output, separate from measured evaluation results."""

    model_config = ConfigDict(frozen=True)
    summary: str
    findings: tuple[ResearchFinding, ...] = ()
    recommendations: tuple[str, ...] = Field(min_length=1)
    external_data_allowed: bool = False
    external_data_evidence: str | None = None

ScientistDeps dataclass

Research services and training-only evidence for one mission.

Source code in agent_k/scientist.py
68
69
70
71
72
73
74
75
76
@dataclass
class ScientistDeps:
    """Research services and training-only evidence for one mission."""

    http_client: httpx.AsyncClient
    platform_adapter: PlatformAdapter
    competition: Competition
    profile: DatasetProfile
    observed_urls: set[str] = field(default_factory=set)

leaderboard async

leaderboard(ctx: RunContext[ScientistDeps]) -> list[LeaderboardEntry] | str

Inspect actual public leaderboard values without estimating missing values.

Source code in agent_k/scientist.py
88
89
90
91
92
93
94
95
96
97
@scientist_toolset.tool
async def leaderboard(ctx: RunContext[ScientistDeps]) -> list[LeaderboardEntry] | str:
    """Inspect actual public leaderboard values without estimating missing values."""
    try:
        return await ctx.deps.platform_adapter.get_leaderboard(
            ctx.deps.competition.id, limit=_LEADERBOARD_LIMIT
        )
    except (httpx.HTTPError, AgentKError, ValueError) as exc:
        logfire.warn("leaderboard_unavailable", error_type=type(exc).__name__)
        return "The leaderboard is unavailable; do not estimate scores or ranks."

search_papers async

search_papers(ctx: RunContext[ScientistDeps], query: str) -> list[_Paper] | str

Search arXiv for a bounded set of relevant primary research sources.

Parameters:

Name Type Description Default
ctx RunContext[ScientistDeps]

Research dependencies for the current mission.

required
query str

Plain keywords describing the technique or problem to look up.

required
Source code in agent_k/scientist.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
@scientist_toolset.tool
async def search_papers(ctx: RunContext[ScientistDeps], query: str) -> list[_Paper] | str:
    """Search arXiv for a bounded set of relevant primary research sources.

    Args:
        ctx: Research dependencies for the current mission.
        query: Plain keywords describing the technique or problem to look up.
    """
    if not query.strip():
        raise ModelRetry("Provide non-empty search keywords")
    try:
        response = await ctx.deps.http_client.get(
            "https://export.arxiv.org/api/query",
            params={"search_query": f"all:{query}", "max_results": str(_PAPER_LIMIT)},
            timeout=30,
        )
        response.raise_for_status()
        if len(response.content) > 2_000_000:
            raise ValueError("Paper response exceeds byte limit")
        root = ET.fromstring(response.content)
    except (httpx.HTTPError, ET.ParseError, ValueError) as exc:
        logfire.warn("paper_search_unavailable", error_type=type(exc).__name__)
        return "Paper search is unavailable; continue without citing papers."
    namespace = {"atom": "http://www.w3.org/2005/Atom"}
    papers: list[_Paper] = []
    for entry in root.findall("atom:entry", namespace):
        url = entry.findtext("atom:id", namespaces=namespace)
        title = entry.findtext("atom:title", namespaces=namespace)
        summary = entry.findtext("atom:summary", namespaces=namespace)
        if not url or not title or not summary:
            continue
        papers.append(
            _Paper(
                title=" ".join(title.split()),
                url=url,
                summary=" ".join(summary.split())[:_SUMMARY_LIMIT],
            )
        )
        ctx.deps.observed_urls.add(url)
    return papers

profile_report

profile_report(profile: DatasetProfile, *, reason: str) -> ResearchReport

Build a citation-free report from measured training-profile guidance.

Parameters:

Name Type Description Default
profile DatasetProfile

Training-only profile whose recommendations were derived from data.

required
reason str

Why model-authored research is unavailable for this mission.

required

Returns:

Type Description
ResearchReport

A report that states its provenance and claims no external evidence.

Source code in agent_k/scientist.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def profile_report(profile: DatasetProfile, *, reason: str) -> ResearchReport:
    """Build a citation-free report from measured training-profile guidance.

    Args:
        profile: Training-only profile whose recommendations were derived from data.
        reason: Why model-authored research is unavailable for this mission.

    Returns:
        A report that states its provenance and claims no external evidence.
    """
    return ResearchReport(
        summary=f"Model-authored research is unavailable ({reason}); using profile guidance only.",
        recommendations=profile.recommendations,
    )

Bridge mission events and artifacts to the fenced worker API.

(c) Mike Casale 2026. Licensed under the MIT License.

MissionTracker dataclass

Serialize worker writes with deterministic event identities.

Source code in agent_k/tracking.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
@dataclass
class MissionTracker:
    """Serialize worker writes with deterministic event identities."""

    lease: JobLease
    client: WorkerApiClient
    sequence: int = 0
    _lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)

    async def append_event(
        self,
        mission_id: str,
        event_type: EventType,
        data: EventData,
        *,
        timestamp: datetime,
    ) -> AgentKEvent:
        """Persist an event before returning its browser representation."""
        if mission_id != str(self.lease.mission_id):
            raise ValueError("Event mission does not match the fenced lease")
        async with self._lock:
            sequence = self.sequence + 1
            event_id = uuid5(NAMESPACE_URL, f"agent-k:{self.lease.job_id}:{sequence}")
            event = WorkerEvent(
                event_id=event_id,
                sequence=sequence,
                type=event_type,
                timestamp=timestamp,
                data=data,
            )
            await self.client.append_events(self.lease, (event,))
            self.sequence = sequence
        return AgentKEvent(
            event_id=str(event_id),
            sequence=sequence,
            mission_id=mission_id,
            type=event_type,
            timestamp=timestamp,
            data=data,
        )

    async def upload(self, path: Path, *, role: str) -> ArtifactReference:
        """Upload an immutable artifact through a scoped, expiring URL."""
        signed = await self.client.request_upload(
            self.lease,
            path,
            content_type="application/octet-stream",
            role=role,
        )
        return await self.client.upload_file(self.lease, signed, path, role=role)

append_event async

append_event(mission_id: str, event_type: EventType, data: EventData, *, timestamp: datetime) -> AgentKEvent

Persist an event before returning its browser representation.

Source code in agent_k/tracking.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
async def append_event(
    self,
    mission_id: str,
    event_type: EventType,
    data: EventData,
    *,
    timestamp: datetime,
) -> AgentKEvent:
    """Persist an event before returning its browser representation."""
    if mission_id != str(self.lease.mission_id):
        raise ValueError("Event mission does not match the fenced lease")
    async with self._lock:
        sequence = self.sequence + 1
        event_id = uuid5(NAMESPACE_URL, f"agent-k:{self.lease.job_id}:{sequence}")
        event = WorkerEvent(
            event_id=event_id,
            sequence=sequence,
            type=event_type,
            timestamp=timestamp,
            data=data,
        )
        await self.client.append_events(self.lease, (event,))
        self.sequence = sequence
    return AgentKEvent(
        event_id=str(event_id),
        sequence=sequence,
        mission_id=mission_id,
        type=event_type,
        timestamp=timestamp,
        data=data,
    )

upload async

upload(path: Path, *, role: str) -> ArtifactReference

Upload an immutable artifact through a scoped, expiring URL.

Source code in agent_k/tracking.py
66
67
68
69
70
71
72
73
74
async def upload(self, path: Path, *, role: str) -> ArtifactReference:
    """Upload an immutable artifact through a scoped, expiring URL."""
    signed = await self.client.request_upload(
        self.lease,
        path,
        content_type="application/octet-stream",
        role=role,
    )
    return await self.client.upload_file(self.lease, signed, path, role=role)

OpenEvolve orchestration and independent sandbox scoring.

(c) Mike Casale 2026. Licensed under the MIT License.

EvolutionSettings

Bases: BaseModel

A single source of truth for the native OpenEvolve search.

Source code in agent_k/evolution.py
56
57
58
59
60
61
62
63
64
65
66
67
class EvolutionSettings(BaseModel):
    """A single source of truth for the native OpenEvolve search."""

    model_config = ConfigDict(frozen=True)
    iterations: int = Field(default=20, ge=1, le=200)
    minimum_iterations: int = Field(default=1, ge=1, le=200)
    minimum_improvements: int = Field(default=0, ge=0)
    model_specs: tuple[str, ...]
    parallel_evaluations: int = Field(default=1, ge=1, le=16)
    evaluation_timeout_seconds: int = Field(default=1200, ge=1)
    guidance: tuple[str, ...] = ()
    """Advisory research recommendations; never treated as measured evidence."""

guidance class-attribute instance-attribute

guidance: tuple[str, ...] = ()

Advisory research recommendations; never treated as measured evidence.

EvolutionContext

Bases: BaseModel

Host-only evaluator configuration; this file is never mounted in a candidate.

Source code in agent_k/evolution.py
70
71
72
73
74
75
76
77
78
79
class EvolutionContext(BaseModel):
    """Host-only evaluator configuration; this file is never mounted in a candidate."""

    model_config = ConfigDict(frozen=True)
    split: PreparedSplit
    spec: CandidateSpec
    image: str
    workdir: str
    limits: SandboxLimits = Field(default_factory=SandboxLimits)
    gpu_devices: tuple[str, ...] = ()

EvolutionOutcome

Bases: BaseModel

A fully evaluated candidate with native-search provenance.

Source code in agent_k/evolution.py
82
83
84
85
86
87
88
89
90
91
class EvolutionOutcome(BaseModel):
    """A fully evaluated candidate with native-search provenance."""

    model_config = ConfigDict(frozen=True)
    program_path: str
    validation: EvaluationResult
    iterations: int = Field(ge=0)
    improvements: int = Field(ge=0)
    checkpoint_path: str | None = None
    selected_baseline: bool

write_seed_program

write_seed_program(path: Path) -> None

Write the executable baseline that OpenEvolve may mutate inside isolation.

Source code in agent_k/evolution.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def write_seed_program(path: Path) -> None:
    """Write the executable baseline that OpenEvolve may mutate inside isolation."""
    path.write_text(
        '''"""Train a candidate and write prediction evidence in the isolated container."""
import json
from pathlib import Path
from agent_k.evaluator import CandidateSpec

# EVOLVE-BLOCK-START
# Tune preprocessing, model parameters, and true LightGBM gradient/Hessian losses.
# Never use validation labels or emit a claimed metric as a substitute for predictions.
def main():
    spec = CandidateSpec.model_validate_json(Path("/run/input/spec.json").read_text())
    parameters = dict(spec.hyperparameters)
    spec = CandidateSpec.model_validate_json(
        json.dumps({**spec.model_dump(mode="json"), "hyperparameters": parameters})
    )
    if spec.problem_type.modality.value == "tabular":
        from agent_k.tabular import run_candidate
    elif spec.problem_type.modality.value == "vision":
        from agent_k.vision import run_candidate
    else:
        from agent_k.text import run_candidate
    result = run_candidate(spec, Path("/run/input"), Path("/run/output"))
    Path("/run/output/result.json").write_text(result.model_dump_json())
# EVOLVE-BLOCK-END

if __name__ == "__main__":
    main()
''',
        encoding="utf-8",
    )

build_system_message

build_system_message(spec: CandidateSpec, baseline: EvaluationResult, settings: EvolutionSettings) -> str

Compose the mutation prompt from the candidate contract and advisory research.

Parameters:

Name Type Description Default
spec CandidateSpec

Validation candidate contract whose engine and problem stay fixed.

required
baseline EvaluationResult

Trusted validation score the search must beat.

required
settings EvolutionSettings

Search settings carrying bounded research guidance.

required

Returns:

Type Description
str

Instructions naming the measured objective, the accepted hyperparameters,

str

and research recommendations labeled as unverified.

Source code in agent_k/evolution.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def build_system_message(
    spec: CandidateSpec,
    baseline: EvaluationResult,
    settings: EvolutionSettings,
) -> str:
    """Compose the mutation prompt from the candidate contract and advisory research.

    Args:
        spec: Validation candidate contract whose engine and problem stay fixed.
        baseline: Trusted validation score the search must beat.
        settings: Search settings carrying bounded research guidance.

    Returns:
        Instructions naming the measured objective, the accepted hyperparameters,
        and research recommendations labeled as unverified.
    """
    direction = "higher" if baseline.direction is MetricDirection.MAXIMIZE else "lower"
    sections = [
        "Improve the supplied ML training program using validation feedback. "
        f"Keep the configured {spec.engine.value} engine and "
        f"{spec.problem_type.value} problem type fixed. "
        "Use LightGBM for tree models; evolve actual custom loss gradients and Hessians. "
        "Preserve the prediction/result artifact contract. No network or hidden labels exist "
        "in the sandbox. Only fully scored predictions are valid. For enabled Kumo candidates "
        "keep pretrained weights fixed; vary context, estimators, preprocessing, and blending.",
        f"Objective: the trusted validation metric is {spec.metric_id.value}; {direction} is "
        f"better. The baseline scores {baseline.score:.6g} on {baseline.row_count} validation "
        "rows and is reported back as metric_value. Training data has "
        f"{spec.train_row_count} rows and {len(spec.feature_columns)} feature columns.",
        "Contract: set values in the `parameters` dictionary before the spec is rebuilt; "
        "names outside the accepted set fail validation and score as invalid. "
        + _hyperparameter_contract(spec.engine, spec.problem_type.modality),
    ]
    guidance = [
        " ".join(item.split())[:_GUIDANCE_CHARACTERS]
        for item in settings.guidance[:_GUIDANCE_ITEMS]
        if item.strip()
    ]
    if guidance:
        sections.append(
            "Unverified research suggestions to test, never to assume: "
            + " ".join(f"({index}) {item}" for index, item in enumerate(guidance, start=1))
        )
    return "\n\n".join(sections)

evaluate_program

evaluate_program(program_path: Path, context: EvolutionContext) -> EvaluationResult

Run untrusted code in Docker, then score its predictions with hidden labels.

Parameters:

Name Type Description Default
program_path Path

Candidate Python file mounted read-only into the container.

required
context EvolutionContext

Trusted split, prediction contract, immutable image, and runtime limits.

required

Returns:

Type Description
EvaluationResult

A host-computed score after identity, checksum, schema, and row validation.

Raises:

Type Description
ValueError

Candidate execution fails or its output violates the contract.

OSError

Required candidate inputs or result artifacts cannot be read.

Hidden labels remain on the host. Candidate stdout and claimed scores never determine the returned fitness.

Source code in agent_k/evolution.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
def evaluate_program(program_path: Path, context: EvolutionContext) -> EvaluationResult:
    """Run untrusted code in Docker, then score its predictions with hidden labels.

    Args:
        program_path: Candidate Python file mounted read-only into the container.
        context: Trusted split, prediction contract, immutable image, and runtime limits.

    Returns:
        A host-computed score after identity, checksum, schema, and row validation.

    Raises:
        ValueError: Candidate execution fails or its output violates the contract.
        OSError: Required candidate inputs or result artifacts cannot be read.

    Hidden labels remain on the host. Candidate stdout and claimed scores never
    determine the returned fitness.
    """
    code_hash = hashlib.sha256(
        program_path.read_bytes() + context.spec.model_dump_json().encode(),
    ).hexdigest()
    run_root = Path(context.workdir) / "evaluations" / f"{code_hash[:16]}-{uuid.uuid4().hex}"
    input_root = run_root / "input"
    output_root = run_root / "output"
    run_root.mkdir(parents=True, mode=0o700)
    shutil.copytree(context.split.candidate_input_root, input_root, copy_function=os.link)
    output_root.mkdir()
    spec = CandidateSpec.model_validate_json(
        json.dumps(
            {
                **context.spec.model_dump(mode="json"),
                "candidate_id": code_hash,
            }
        )
    )
    (input_root / "spec.json").write_text(spec.model_dump_json(), encoding="utf-8")
    outcome = run_candidate_sandbox_sync(
        SandboxRequest(
            image=context.image,
            input_root=input_root,
            output_root=output_root,
            candidate_program=program_path,
            limits=context.limits,
            gpu_devices=context.gpu_devices,
            environment={"OMP_NUM_THREADS": str(max(1, int(context.limits.cpus)))},
        ),
    )
    if (
        outcome.exit_code
        or outcome.timed_out
        or outcome.oom_killed
        or outcome.output_limit_exceeded
    ):
        raise ValueError(
            f"Candidate failed: exit={outcome.exit_code}, timeout={outcome.timed_out}, "
            f"oom={outcome.oom_killed}, output_limit={outcome.output_limit_exceeded}; "
            f"stderr={outcome.stderr[-4000:]}",
        )
    result_path = output_root / "result.json"
    if result_path.is_symlink() or result_path.stat().st_size > 1_000_000:
        raise ValueError("Invalid candidate result metadata")
    result = CandidateResult.model_validate_json(result_path.read_bytes())
    if result.candidate_id != spec.candidate_id:
        raise ValueError("Candidate result identity does not match the evaluated program")
    return evaluate_candidate(
        EvaluationRequest(
            candidate_result=result,
            metric_id=spec.metric_id,
            prediction_root=str(output_root),
            trusted_labels_path=context.split.trusted_labels_path,
            id_columns=spec.id_columns,
            target_columns=spec.target_columns,
            class_labels=spec.class_labels,
        ),
    )

evaluate_stage1

evaluate_stage1(program_path: str) -> dict[str, float]

Give syntactically valid code partial fidelity, always below complete results.

Source code in agent_k/evolution.py
250
251
252
253
254
255
256
257
258
259
def evaluate_stage1(program_path: str) -> dict[str, float]:
    """Give syntactically valid code partial fidelity, always below complete results."""
    try:
        code = Path(program_path).read_text(encoding="utf-8")
        if len(code) > 100_000:
            raise ValueError("Candidate exceeds code size limit")
        ast.parse(code)
    except (OSError, SyntaxError, ValueError):
        return {"combined_score": -1.0, "valid": 0.0, "full_evaluation": 0.0}
    return {"combined_score": 0.05, "valid": 0.0, "full_evaluation": 0.0}

evaluate_stage2

evaluate_stage2(program_path: str) -> EvaluationResult

Perform full validation scoring after the cheap syntax gate.

Source code in agent_k/evolution.py
262
263
264
def evaluate_stage2(program_path: str) -> NativeEvaluationResult:
    """Perform full validation scoring after the cheap syntax gate."""
    return evaluate(program_path)

evaluate

evaluate(program_path: str) -> EvaluationResult

OpenEvolve evaluator entry point loaded in the isolated mission's process pool.

Source code in agent_k/evolution.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
def evaluate(program_path: str) -> NativeEvaluationResult:
    """OpenEvolve evaluator entry point loaded in the isolated mission's process pool."""
    try:
        context = EvolutionContext.model_validate_json(
            Path(os.environ[_CONTEXT_ENVIRONMENT]).read_bytes(),
        )
        result = evaluate_program(Path(program_path), context)
        quality = (
            result.score if result.direction is MetricDirection.MAXIMIZE else 1 / (1 + result.score)
        )
        fitness = 0.3 + 0.7 * max(0.0, min(1.0, quality))
        return NativeEvaluationResult(
            metrics={
                "combined_score": fitness,
                "metric_value": result.score,
                "valid": 1.0,
                "full_evaluation": 1.0,
                "rows": float(result.row_count),
            },
            artifacts={"validation": result.model_dump_json()},
        )
    except Exception as exc:
        # Invalid, incomplete, timed-out, and failed runs cannot outrank a full result.
        return NativeEvaluationResult(
            metrics={"combined_score": -1.0, "valid": 0.0, "full_evaluation": 0.0},
            artifacts={"error": f"{type(exc).__name__}: {str(exc)[:4000]}"},
        )

run_evolution async

run_evolution(*, initial_program: Path, baseline: EvaluationResult, context: EvolutionContext, settings: EvolutionSettings, checkpoint_callback: Callable[[Path, int], Awaitable[None]], checkpoint_path: Path | None = None) -> EvolutionOutcome

Run the sole native evolution loop and independently revalidate its winner.

Parameters:

Name Type Description Default
initial_program Path

Existing seed program executed only inside the sandbox.

required
baseline EvaluationResult

Trusted validation score for the seed program.

required
context EvolutionContext

Host-only evaluation inputs, hidden-label paths, and sandbox limits.

required
settings EvolutionSettings

Search budget, model specifications, and evaluation concurrency.

required
checkpoint_callback Callable[[Path, int], Awaitable[None]]

Persist each native checkpoint before reporting progress.

required
checkpoint_path Path | None

Optional verified native checkpoint from a previous attempt.

None

Returns:

Type Description
EvolutionOutcome

The independently validated winner, or the measured baseline when search fails

EvolutionOutcome

to produce an eligible improvement, with iteration and checkpoint provenance.

Raises:

Type Description
ValueError

No evolution model is configured or a contract is invalid.

Exception

Native search, sandbox execution, or durable checkpointing fails.

Source code in agent_k/evolution.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
async def run_evolution(
    *,
    initial_program: Path,
    baseline: EvaluationResult,
    context: EvolutionContext,
    settings: EvolutionSettings,
    checkpoint_callback: Callable[[Path, int], Awaitable[None]],
    checkpoint_path: Path | None = None,
) -> EvolutionOutcome:
    """Run the sole native evolution loop and independently revalidate its winner.

    Args:
        initial_program: Existing seed program executed only inside the sandbox.
        baseline: Trusted validation score for the seed program.
        context: Host-only evaluation inputs, hidden-label paths, and sandbox limits.
        settings: Search budget, model specifications, and evaluation concurrency.
        checkpoint_callback: Persist each native checkpoint before reporting progress.
        checkpoint_path: Optional verified native checkpoint from a previous attempt.

    Returns:
        The independently validated winner, or the measured baseline when search fails
        to produce an eligible improvement, with iteration and checkpoint provenance.

    Raises:
        ValueError: No evolution model is configured or a contract is invalid.
        Exception: Native search, sandbox execution, or durable checkpointing fails.
    """
    from openevolve import OpenEvolve
    from openevolve.config import Config

    validate_model_specs(settings.model_specs)
    output = Path(context.workdir) / "native"
    output.mkdir(parents=True, exist_ok=True)
    context_path = Path(context.workdir) / "context.json"
    context_path.write_text(context.model_dump_json(), encoding="utf-8")
    context_path.chmod(0o600)
    evaluator_file = Path(context.workdir) / "evaluate.py"
    evaluator_file.write_text(
        "from agent_k.evolution import evaluate, evaluate_stage1, evaluate_stage2\n",
        encoding="utf-8",
    )
    os.environ[_CONTEXT_ENVIRONMENT] = str(context_path)
    config = Config()
    config.max_iterations = settings.iterations
    config.checkpoint_interval = 1
    config.language = "python"
    config.max_code_length = 100_000
    config.evaluator.cascade_evaluation = True
    config.evaluator.cascade_thresholds = [0.01]
    config.evaluator.timeout = settings.evaluation_timeout_seconds + 60
    config.evaluator.max_retries = 0
    config.evaluator.parallel_evaluations = settings.parallel_evaluations
    config.llm.models = [_model_config(spec) for spec in settings.model_specs]
    config.prompt.system_message = build_system_message(context.spec, baseline, settings)
    evolver = OpenEvolve(
        initial_program_path=str(initial_program),
        evaluation_file=str(evaluator_file),
        config=config,
        output_dir=str(output),
    )
    observed: set[Path] = set()

    async def publish_checkpoints() -> None:
        while True:
            await _publish_new_checkpoints(output, observed, checkpoint_callback)
            await asyncio.sleep(0.5)

    publisher = asyncio.create_task(publish_checkpoints())
    native_task: asyncio.Task[Any] | None = None
    try:
        resumed_iteration = 0
        if checkpoint_path:
            evolver.database.load(str(checkpoint_path))
            resumed_iteration = int(evolver.database.last_iteration)
        remaining = max(0, settings.iterations - resumed_iteration)
        if remaining:
            native_task = asyncio.create_task(
                evolver.run(
                    iterations=remaining,
                    checkpoint_path=str(checkpoint_path) if checkpoint_path else None,
                )
            )
            done, _ = await asyncio.wait(
                {native_task, publisher},
                return_when=asyncio.FIRST_COMPLETED,
            )
            if publisher in done:
                await publisher
            await native_task
    finally:
        if native_task is not None and not native_task.done():
            native_task.cancel()
            with contextlib.suppress(asyncio.CancelledError):
                await native_task
        publisher.cancel()
        with contextlib.suppress(asyncio.CancelledError):
            await publisher
        await _publish_new_checkpoints(output, observed, checkpoint_callback)
    programs = list(evolver.database.programs.values())
    full = [
        program
        for program in programs
        if program.metrics.get("valid") == 1.0 and program.metrics.get("full_evaluation") == 1.0
    ]
    completed = max((_checkpoint_iteration(path) for path in observed), default=0)
    baseline_quality = _quality(baseline.score, baseline.direction)
    improvements = 0
    best_quality = baseline_quality
    for program in sorted(full, key=lambda item: item.iteration_found):
        quality = _quality(float(program.metrics["metric_value"]), baseline.direction)
        if quality > best_quality:
            improvements += 1
            best_quality = quality
    selected = initial_program
    selected_result = baseline
    if full:
        winner = max(
            full,
            key=lambda program: _quality(
                float(program.metrics["metric_value"]), baseline.direction
            ),
        )
        candidate = Path(context.workdir) / "selected.py"
        candidate.write_text(winner.code, encoding="utf-8")
        try:
            verified = await asyncio.to_thread(evaluate_program, candidate, context)
        except ValueError:
            verified = baseline
        if _quality(verified.score, baseline.direction) > baseline_quality:
            selected, selected_result = candidate, verified
    checkpoints = sorted(observed, key=_checkpoint_iteration)
    return EvolutionOutcome(
        program_path=str(selected),
        validation=selected_result,
        iterations=completed,
        improvements=improvements,
        checkpoint_path=str(checkpoints[-1]) if checkpoints else None,
        selected_baseline=selected == initial_program,
    )

validate_model_specs

validate_model_specs(specs: Sequence[str]) -> None

Reject evolution models that cannot be reached before a mission spends its budget.

Parameters:

Name Type Description Default
specs Sequence[str]

Ordered model specifications for the native search.

required

Raises:

Type Description
ValueError

No model is configured, a provider is unsupported, or a required provider credential is absent from the environment.

Source code in agent_k/evolution.py
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
def validate_model_specs(specs: Sequence[str]) -> None:
    """Reject evolution models that cannot be reached before a mission spends its budget.

    Args:
        specs: Ordered model specifications for the native search.

    Raises:
        ValueError: No model is configured, a provider is unsupported, or a
            required provider credential is absent from the environment.
    """
    if not specs:
        raise ValueError("At least one evolution model must be configured")
    for spec in specs:
        try:
            _model_config(spec)
        except KeyError as exc:
            raise ValueError(
                f"Evolution model {spec!r} requires the {exc.args[0]} environment variable"
            ) from exc