agentevolve-optimizer 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (414) hide show
  1. agent_evolve/__init__.py +722 -0
  2. agent_evolve/agentic.py +2800 -0
  3. agent_evolve/api.py +767 -0
  4. agent_evolve/application/__init__.py +1580 -0
  5. agent_evolve/application/action_allocation.py +744 -0
  6. agent_evolve/application/action_allocation_frame.py +347 -0
  7. agent_evolve/application/action_allocation_frame_commit.py +185 -0
  8. agent_evolve/application/action_allocation_frame_commit_v3.py +184 -0
  9. agent_evolve/application/action_allocation_frame_v3.py +338 -0
  10. agent_evolve/application/action_archive_value.py +497 -0
  11. agent_evolve/application/action_evidence_consistency.py +455 -0
  12. agent_evolve/application/action_forecast_partitioning.py +1471 -0
  13. agent_evolve/application/action_metric_projection.py +211 -0
  14. agent_evolve/application/action_role_value.py +680 -0
  15. agent_evolve/application/action_score_authorities.py +363 -0
  16. agent_evolve/application/action_structural_signature.py +116 -0
  17. agent_evolve/application/action_target_realization.py +402 -0
  18. agent_evolve/application/agentic_evolution.py +7734 -0
  19. agent_evolve/application/agentic_portfolio_residual_expert.py +835 -0
  20. agent_evolve/application/anchor_residual_identification.py +463 -0
  21. agent_evolve/application/archive_conditioned_action_target.py +208 -0
  22. agent_evolve/application/artifact_journal.py +246 -0
  23. agent_evolve/application/artifact_replay.py +347 -0
  24. agent_evolve/application/budgeted_optimizer.py +1828 -0
  25. agent_evolve/application/calibrated_campaign.py +485 -0
  26. agent_evolve/application/calibrated_current_prefix_forecast_opportunity.py +322 -0
  27. agent_evolve/application/calibrated_positive_gain_opportunity.py +1581 -0
  28. agent_evolve/application/campaign_capacity_recourse.py +254 -0
  29. agent_evolve/application/campaign_contextual_outcomes.py +119 -0
  30. agent_evolve/application/campaign_diagnostic_blocks.py +930 -0
  31. agent_evolve/application/campaign_evidence_registry.py +262 -0
  32. agent_evolve/application/campaign_execution.py +2537 -0
  33. agent_evolve/application/campaign_generation_audit.py +942 -0
  34. agent_evolve/application/campaign_learning.py +1812 -0
  35. agent_evolve/application/campaign_learning_runtime.py +1977 -0
  36. agent_evolve/application/campaign_search_phase.py +227 -0
  37. agent_evolve/application/campaign_selector_context_extension.py +220 -0
  38. agent_evolve/application/campaign_variation_envelope.py +649 -0
  39. agent_evolve/application/campaign_variation_trace.py +451 -0
  40. agent_evolve/application/candidate_archive_consequence.py +128 -0
  41. agent_evolve/application/causal_opportunity_portfolio_gate.py +385 -0
  42. agent_evolve/application/composite_outcome_updater.py +145 -0
  43. agent_evolve/application/composition_portfolio_selection.py +363 -0
  44. agent_evolve/application/concurrent_stage.py +144 -0
  45. agent_evolve/application/contextual_action_allocation.py +181 -0
  46. agent_evolve/application/contextual_campaign_outcomes.py +267 -0
  47. agent_evolve/application/contextual_campaign_planning.py +1366 -0
  48. agent_evolve/application/contextual_delayed_credit.py +651 -0
  49. agent_evolve/application/contextual_search_controller.py +2374 -0
  50. agent_evolve/application/current_prefix_forecast_opportunity.py +714 -0
  51. agent_evolve/application/decision_metric_projection.py +112 -0
  52. agent_evolve/application/derived_action_semantics.py +129 -0
  53. agent_evolve/application/detailed_evaluation.py +449 -0
  54. agent_evolve/application/earned_lineage.py +1011 -0
  55. agent_evolve/application/effective_choice_audit.py +484 -0
  56. agent_evolve/application/empirical_consequence_calibration.py +908 -0
  57. agent_evolve/application/evaluation_accounting.py +325 -0
  58. agent_evolve/application/evaluation_cache.py +199 -0
  59. agent_evolve/application/evaluation_escrow.py +547 -0
  60. agent_evolve/application/evaluation_recourse.py +253 -0
  61. agent_evolve/application/event_recorder.py +151 -0
  62. agent_evolve/application/evolution_campaign.py +1840 -0
  63. agent_evolve/application/executable_hypothesis.py +323 -0
  64. agent_evolve/application/factorial_branch_pilot.py +772 -0
  65. agent_evolve/application/finite_acquisition_capacity_recourse.py +672 -0
  66. agent_evolve/application/finite_acquisition_residual_expert.py +373 -0
  67. agent_evolve/application/finite_acquisition_variation_envelope.py +802 -0
  68. agent_evolve/application/finite_action_hypothesis_semantics.py +446 -0
  69. agent_evolve/application/finite_action_selection.py +188 -0
  70. agent_evolve/application/finite_action_set.py +306 -0
  71. agent_evolve/application/finite_action_transition.py +537 -0
  72. agent_evolve/application/finite_variation_eligibility.py +296 -0
  73. agent_evolve/application/forecast_geometry_portfolio.py +799 -0
  74. agent_evolve/application/forecast_opportunity_shadow_calibration.py +316 -0
  75. agent_evolve/application/front_proximity_admission.py +311 -0
  76. agent_evolve/application/front_proximity_parent_basis.py +458 -0
  77. agent_evolve/application/frozen_hurdle_score.py +659 -0
  78. agent_evolve/application/g3_causal_screen.py +2257 -0
  79. agent_evolve/application/g3_causal_validation.py +1046 -0
  80. agent_evolve/application/g3_postseal_curation.py +818 -0
  81. agent_evolve/application/gated_agentic_generator.py +205 -0
  82. agent_evolve/application/generation_feedback.py +293 -0
  83. agent_evolve/application/generative_proposal_journal.py +185 -0
  84. agent_evolve/application/geometry_conditional_elasticity.py +453 -0
  85. agent_evolve/application/global_wave_action_allocation.py +1151 -0
  86. agent_evolve/application/head_mass_conditional_seat.py +268 -0
  87. agent_evolve/application/identifiable_reflection_evidence.py +1147 -0
  88. agent_evolve/application/identifiable_reflection_learning.py +395 -0
  89. agent_evolve/application/identifiable_reflection_request.py +364 -0
  90. agent_evolve/application/in_memory_residual_archive.py +341 -0
  91. agent_evolve/application/insight_memory.py +1804 -0
  92. agent_evolve/application/live_runtime_manifest.py +758 -0
  93. agent_evolve/application/llm_task_queue.py +769 -0
  94. agent_evolve/application/matched_finite_action_block.py +409 -0
  95. agent_evolve/application/materialized_action_broker.py +2328 -0
  96. agent_evolve/application/materialized_action_constraints.py +83 -0
  97. agent_evolve/application/materialized_variation.py +211 -0
  98. agent_evolve/application/multi_option_evolution.py +1536 -0
  99. agent_evolve/application/outcome_adaptive_action_racing.py +2827 -0
  100. agent_evolve/application/outcome_adaptive_residual_campaign_runtime.py +580 -0
  101. agent_evolve/application/outcome_adaptive_residual_portfolio_evolution.py +3671 -0
  102. agent_evolve/application/outcome_conditioned_portfolio_selection.py +1374 -0
  103. agent_evolve/application/outcome_relation.py +193 -0
  104. agent_evolve/application/paired_allocation_comparison.py +241 -0
  105. agent_evolve/application/paired_block_schedule.py +127 -0
  106. agent_evolve/application/parent_measurement.py +226 -0
  107. agent_evolve/application/pareto_archive.py +811 -0
  108. agent_evolve/application/portfolio_campaign_runtime.py +4739 -0
  109. agent_evolve/application/portfolio_evolution.py +2950 -0
  110. agent_evolve/application/portfolio_hypothesis_observations.py +814 -0
  111. agent_evolve/application/portfolio_memory_attribution.py +581 -0
  112. agent_evolve/application/portfolio_memory_dose.py +788 -0
  113. agent_evolve/application/portfolio_memory_matched_control.py +938 -0
  114. agent_evolve/application/portfolio_memory_transfer.py +297 -0
  115. agent_evolve/application/portfolio_optimization_memory.py +363 -0
  116. agent_evolve/application/portfolio_outcome_feedback.py +1613 -0
  117. agent_evolve/application/portfolio_projection.py +335 -0
  118. agent_evolve/application/portfolio_recombination.py +2032 -0
  119. agent_evolve/application/post_evolution_reflection.py +834 -0
  120. agent_evolve/application/postcommit_rank_authority.py +245 -0
  121. agent_evolve/application/precommitted_portfolio_racing.py +2762 -0
  122. agent_evolve/application/prequential_archive_opportunity_calibration.py +1154 -0
  123. agent_evolve/application/prequential_residual_exploration.py +343 -0
  124. agent_evolve/application/prequential_score_portfolio.py +954 -0
  125. agent_evolve/application/projections.py +292 -0
  126. agent_evolve/application/protected_action_committee.py +1027 -0
  127. agent_evolve/application/protected_branch_pilot.py +376 -0
  128. agent_evolve/application/protected_current_prefix_forecast_opportunity.py +552 -0
  129. agent_evolve/application/provider_replay.py +910 -0
  130. agent_evolve/application/rank_balanced_causal_pilot.py +1372 -0
  131. agent_evolve/application/recombination_residual_expert.py +403 -0
  132. agent_evolve/application/reflection_workflow.py +571 -0
  133. agent_evolve/application/region_conditional_credit.py +911 -0
  134. agent_evolve/application/residual_campaign_runtime.py +531 -0
  135. agent_evolve/application/residual_headroom_campaign_runtime.py +459 -0
  136. agent_evolve/application/residual_headroom_ledger.py +1544 -0
  137. agent_evolve/application/residual_learning_transaction.py +396 -0
  138. agent_evolve/application/residual_portfolio_evolution.py +1228 -0
  139. agent_evolve/application/residual_reachability.py +749 -0
  140. agent_evolve/application/residual_stage_credit.py +499 -0
  141. agent_evolve/application/same_prefix_paired_audit.py +1580 -0
  142. agent_evolve/application/semantic_coverage_score_portfolio.py +838 -0
  143. agent_evolve/application/sequential_lineage_allocation.py +1017 -0
  144. agent_evolve/application/sequential_market_replay.py +1395 -0
  145. agent_evolve/application/sequential_residual_campaign_runtime.py +305 -0
  146. agent_evolve/application/sequential_residual_portfolio_evolution.py +940 -0
  147. agent_evolve/application/single_score_action_allocation.py +299 -0
  148. agent_evolve/application/source_exposure_allocation.py +906 -0
  149. agent_evolve/application/staged_memory.py +210 -0
  150. agent_evolve/application/stratified_cold_start_allocation.py +732 -0
  151. agent_evolve/application/support_guarded_hurdle_score.py +549 -0
  152. agent_evolve/application/target_conditioned_action_forecast.py +595 -0
  153. agent_evolve/application/target_conditioned_campaign.py +566 -0
  154. agent_evolve/application/treatment_assignment.py +201 -0
  155. agent_evolve/application/trusted_objective_evidence.py +217 -0
  156. agent_evolve/application/two_stage_action_evolution.py +1131 -0
  157. agent_evolve/application/v8lite_allocation_policy.py +1083 -0
  158. agent_evolve/application/v9_candidate_policy.py +1303 -0
  159. agent_evolve/bootstrap.py +108 -0
  160. agent_evolve/campaign_presets.py +517 -0
  161. agent_evolve/campaign_profiles.py +452 -0
  162. agent_evolve/campaign_variation_topology.py +288 -0
  163. agent_evolve/campaign_workload.py +950 -0
  164. agent_evolve/cli.py +797 -0
  165. agent_evolve/contract.py +241 -0
  166. agent_evolve/core/__init__.py +91 -0
  167. agent_evolve/core/action_semantics.py +411 -0
  168. agent_evolve/core/authored.py +105 -0
  169. agent_evolve/core/formatting.py +286 -0
  170. agent_evolve/core/optimization_semantics.py +324 -0
  171. agent_evolve/core/problem.py +167 -0
  172. agent_evolve/core/results.py +323 -0
  173. agent_evolve/core/stats.py +70 -0
  174. agent_evolve/core/telemetry.py +100 -0
  175. agent_evolve/domain/__init__.py +89 -0
  176. agent_evolve/domain/artifact.py +162 -0
  177. agent_evolve/domain/durable_text.py +68 -0
  178. agent_evolve/domain/event.py +1454 -0
  179. agent_evolve/domain/finite_action_set.py +426 -0
  180. agent_evolve/domain/finite_variation.py +526 -0
  181. agent_evolve/domain/generative_emission.py +559 -0
  182. agent_evolve/domain/ids.py +163 -0
  183. agent_evolve/domain/inline_text.py +106 -0
  184. agent_evolve/domain/insight.py +27 -0
  185. agent_evolve/domain/lineage.py +737 -0
  186. agent_evolve/domain/llm_task_queue.py +960 -0
  187. agent_evolve/domain/outcome.py +96 -0
  188. agent_evolve/domain/patch.py +854 -0
  189. agent_evolve/domain/typed_json.py +542 -0
  190. agent_evolve/domain/variation_space.py +158 -0
  191. agent_evolve/driver.py +1014 -0
  192. agent_evolve/harness/__init__.py +29 -0
  193. agent_evolve/harness/base.py +242 -0
  194. agent_evolve/harness/directives.py +163 -0
  195. agent_evolve/harness/generative_seal.py +479 -0
  196. agent_evolve/harness/registry.py +41 -0
  197. agent_evolve/infrastructure/__init__.py +39 -0
  198. agent_evolve/infrastructure/artifacts/__init__.py +6 -0
  199. agent_evolve/infrastructure/artifacts/_verification.py +67 -0
  200. agent_evolve/infrastructure/artifacts/filesystem.py +343 -0
  201. agent_evolve/infrastructure/artifacts/in_memory.py +73 -0
  202. agent_evolve/infrastructure/asyncio_runtime.py +109 -0
  203. agent_evolve/infrastructure/authored_runtime.py +188 -0
  204. agent_evolve/infrastructure/authored_worker.py +171 -0
  205. agent_evolve/infrastructure/clock.py +53 -0
  206. agent_evolve/infrastructure/events/__init__.py +6 -0
  207. agent_evolve/infrastructure/events/_validation.py +89 -0
  208. agent_evolve/infrastructure/events/in_memory.py +56 -0
  209. agent_evolve/infrastructure/events/jsonl.py +193 -0
  210. agent_evolve/infrastructure/exception_provenance.py +215 -0
  211. agent_evolve/infrastructure/ids.py +118 -0
  212. agent_evolve/infrastructure/lineage_codec.py +1836 -0
  213. agent_evolve/infrastructure/outcome_adaptive_phase_journal.py +170 -0
  214. agent_evolve/infrastructure/residual_headroom_journal.py +221 -0
  215. agent_evolve/infrastructure/resource_lease.py +370 -0
  216. agent_evolve/infrastructure/sanitization/__init__.py +8 -0
  217. agent_evolve/infrastructure/sanitization/strict_json.py +484 -0
  218. agent_evolve/infrastructure/sequential_phase_journal.py +170 -0
  219. agent_evolve/infrastructure/stream_liveness.py +383 -0
  220. agent_evolve/infrastructure/subprocess_boundary.py +136 -0
  221. agent_evolve/integrations/__init__.py +1 -0
  222. agent_evolve/integrations/botorch/__init__.py +28 -0
  223. agent_evolve/integrations/botorch/finite_qlognehvi.py +190 -0
  224. agent_evolve/integrations/botorch/finite_qlognehvi_batch.py +155 -0
  225. agent_evolve/integrations/botorch/finite_qlognehvi_batch_identity.py +20 -0
  226. agent_evolve/integrations/botorch/finite_qlognehvi_batch_worker.py +55 -0
  227. agent_evolve/integrations/botorch/finite_qlognehvi_identity.py +22 -0
  228. agent_evolve/integrations/botorch/finite_qlognehvi_worker.py +55 -0
  229. agent_evolve/integrations/botorch/subprocess_qlognehvi.py +261 -0
  230. agent_evolve/integrations/botorch/subprocess_qlognehvi_batch.py +273 -0
  231. agent_evolve/integrations/completion.py +242 -0
  232. agent_evolve/integrations/pydantic_ai/__init__.py +441 -0
  233. agent_evolve/integrations/pydantic_ai/action_forecast.py +1068 -0
  234. agent_evolve/integrations/pydantic_ai/agentic_generator.py +2308 -0
  235. agent_evolve/integrations/pydantic_ai/async_generator.py +1604 -0
  236. agent_evolve/integrations/pydantic_ai/boundary_codec.py +1526 -0
  237. agent_evolve/integrations/pydantic_ai/calibrated_portfolio_campaign.py +756 -0
  238. agent_evolve/integrations/pydantic_ai/calibrated_portfolio_selection.py +7537 -0
  239. agent_evolve/integrations/pydantic_ai/campaign_acquisition.py +609 -0
  240. agent_evolve/integrations/pydantic_ai/execution_binding.py +138 -0
  241. agent_evolve/integrations/pydantic_ai/forecast_geometry_action_committee.py +217 -0
  242. agent_evolve/integrations/pydantic_ai/harness.py +159 -0
  243. agent_evolve/integrations/pydantic_ai/heterogeneous_model_execution.py +306 -0
  244. agent_evolve/integrations/pydantic_ai/hierarchical_residual_adaptive_semantic_view.py +179 -0
  245. agent_evolve/integrations/pydantic_ai/json_schema_dialect.py +108 -0
  246. agent_evolve/integrations/pydantic_ai/materialized_hierarchical_residual_expert.py +952 -0
  247. agent_evolve/integrations/pydantic_ai/materialized_portfolio_judge.py +520 -0
  248. agent_evolve/integrations/pydantic_ai/model_execution_profile.py +659 -0
  249. agent_evolve/integrations/pydantic_ai/outbound_request_manifest.py +1170 -0
  250. agent_evolve/integrations/pydantic_ai/portable_residual_consequence_features.py +575 -0
  251. agent_evolve/integrations/pydantic_ai/portfolio_selection.py +422 -0
  252. agent_evolve/integrations/pydantic_ai/progress_aware_openrouter.py +416 -0
  253. agent_evolve/integrations/pydantic_ai/provider_attempt_join.py +1523 -0
  254. agent_evolve/integrations/pydantic_ai/provider_free_calibrated_runner.py +607 -0
  255. agent_evolve/integrations/pydantic_ai/queued_runner.py +2634 -0
  256. agent_evolve/integrations/pydantic_ai/reconciled_residual_reachability.py +1417 -0
  257. agent_evolve/integrations/pydantic_ai/residual_forecast_geometry.py +445 -0
  258. agent_evolve/integrations/pydantic_ai/residual_reachability.py +674 -0
  259. agent_evolve/integrations/pydantic_ai/residual_semantic_cells.py +239 -0
  260. agent_evolve/integrations/pydantic_ai/sealed_output_replay.py +1068 -0
  261. agent_evolve/integrations/pydantic_ai/semantic_coverage_residual_portfolio.py +770 -0
  262. agent_evolve/integrations/pydantic_ai/semantic_decision_replay.py +383 -0
  263. agent_evolve/integrations/pydantic_ai/support_adaptive_residual_portfolio.py +135 -0
  264. agent_evolve/integrations/pydantic_ai/trusted_residual_prompt_context.py +143 -0
  265. agent_evolve/integrations/pydantic_ai/validated_openrouter_model.py +107 -0
  266. agent_evolve/integrations/pymoo_adapter.py +242 -0
  267. agent_evolve/policies/__init__.py +17 -0
  268. agent_evolve/policies/check.py +469 -0
  269. agent_evolve/policies/emit_scaffold.py +451 -0
  270. agent_evolve/policies/feedback/__init__.py +37 -0
  271. agent_evolve/policies/feedback/held_out_asn.py +1325 -0
  272. agent_evolve/policies/genetic.py +607 -0
  273. agent_evolve/policies/llm_backoff.py +183 -0
  274. agent_evolve/policies/llm_chooser.py +226 -0
  275. agent_evolve/policies/llm_generator.py +1760 -0
  276. agent_evolve/policies/llm_init.py +267 -0
  277. agent_evolve/policies/llm_operator.py +109 -0
  278. agent_evolve/policies/llm_prior.py +194 -0
  279. agent_evolve/policies/llm_surrogate.py +334 -0
  280. agent_evolve/policies/measurement_evidence.py +704 -0
  281. agent_evolve/policies/memory/__init__.py +223 -0
  282. agent_evolve/policies/memory/balanced_subset_blocks.py +707 -0
  283. agent_evolve/policies/memory/compatibility_matching.py +593 -0
  284. agent_evolve/policies/memory/global_falsification.py +1841 -0
  285. agent_evolve/policies/memory/prompt_shape.py +503 -0
  286. agent_evolve/policies/memory/randomized_subset.py +714 -0
  287. agent_evolve/policies/memory/staged_causal.py +1270 -0
  288. agent_evolve/policies/memory/treatment_compliance.py +759 -0
  289. agent_evolve/policies/objective_resolution/__init__.py +17 -0
  290. agent_evolve/policies/objective_resolution/fixed_grid.py +364 -0
  291. agent_evolve/policies/operator_portfolio.py +407 -0
  292. agent_evolve/policies/reguidance.py +1133 -0
  293. agent_evolve/policies/reward/__init__.py +83 -0
  294. agent_evolve/policies/reward/affine_candidate_consequence.py +156 -0
  295. agent_evolve/policies/reward/affine_candidate_consequence_3d.py +159 -0
  296. agent_evolve/policies/reward/affine_hypervolume.py +490 -0
  297. agent_evolve/policies/reward/affine_hypervolume_3d.py +567 -0
  298. agent_evolve/policies/reward/contextual_marginal_utility.py +318 -0
  299. agent_evolve/policies/reward/frozen_archive.py +360 -0
  300. agent_evolve/policies/reward/frozen_wave_archive.py +368 -0
  301. agent_evolve/policies/search_state.py +208 -0
  302. agent_evolve/policies/selection/__init__.py +345 -0
  303. agent_evolve/policies/selection/acquisition_certified_slate.py +684 -0
  304. agent_evolve/policies/selection/affine_frontier_context.py +330 -0
  305. agent_evolve/policies/selection/affine_frontier_target.py +473 -0
  306. agent_evolve/policies/selection/archive_elite.py +1346 -0
  307. agent_evolve/policies/selection/calibrated_portfolio_binding.py +640 -0
  308. agent_evolve/policies/selection/calibrated_slate.py +1394 -0
  309. agent_evolve/policies/selection/calibrated_slate_codec.py +579 -0
  310. agent_evolve/policies/selection/common_candidate_pool.py +685 -0
  311. agent_evolve/policies/selection/diagnostic_sampling.py +319 -0
  312. agent_evolve/policies/selection/disjoint_pairs.py +479 -0
  313. agent_evolve/policies/selection/elite_explorer.py +719 -0
  314. agent_evolve/policies/selection/finite_action.py +187 -0
  315. agent_evolve/policies/selection/finite_option_prompt_projection.py +377 -0
  316. agent_evolve/policies/selection/finite_palette_evidence.py +247 -0
  317. agent_evolve/policies/selection/forecast_calibration.py +922 -0
  318. agent_evolve/policies/selection/frontier_probe_slate.py +814 -0
  319. agent_evolve/policies/selection/frozen_archive_pairs.py +762 -0
  320. agent_evolve/policies/selection/full_support_slate.py +91 -0
  321. agent_evolve/policies/selection/meaningful_direction.py +240 -0
  322. agent_evolve/policies/selection/memory_dose_feasibility.py +259 -0
  323. agent_evolve/policies/selection/model_anchored_slate.py +826 -0
  324. agent_evolve/policies/selection/phenotype_recourse.py +979 -0
  325. agent_evolve/policies/selection/proposal_support.py +368 -0
  326. agent_evolve/policies/selection/random_portfolio.py +254 -0
  327. agent_evolve/policies/selection/regret_bounded_slate.py +1084 -0
  328. agent_evolve/policies/selection/residual_frontier.py +463 -0
  329. agent_evolve/policies/selection/residual_frontier_target.py +605 -0
  330. agent_evolve/policies/selection/structural_posterior_slate.py +1571 -0
  331. agent_evolve/policies/selection/target_conditioned_allocator.py +648 -0
  332. agent_evolve/policies/selection/target_conditioned_features.py +812 -0
  333. agent_evolve/policies/selection/target_conditioned_prequential.py +1527 -0
  334. agent_evolve/policies/selection/task_keyed_palette.py +906 -0
  335. agent_evolve/policies/semantics.py +147 -0
  336. agent_evolve/policies/structure.py +362 -0
  337. agent_evolve/policies/structured_output_budget.py +62 -0
  338. agent_evolve/policies/surrogate.py +696 -0
  339. agent_evolve/policies/variation/__init__.py +1 -0
  340. agent_evolve/policies/variation/compositional_finite_catalog.py +426 -0
  341. agent_evolve/policies/variation/crossover_inheritance.py +575 -0
  342. agent_evolve/policies/variation/disjoint_recombination.py +611 -0
  343. agent_evolve/policies/variation/exact_composition_capacity.py +214 -0
  344. agent_evolve/policies/variation/exact_parent_crossover.py +950 -0
  345. agent_evolve/policies/variation/multiscale_restart_catalog.py +372 -0
  346. agent_evolve/policies/variation/source_union_finite_catalog.py +403 -0
  347. agent_evolve/policies/variation/typed_patch.py +1981 -0
  348. agent_evolve/policies/weighted_prior.py +394 -0
  349. agent_evolve/ports/__init__.py +383 -0
  350. agent_evolve/ports/action_allocation.py +733 -0
  351. agent_evolve/ports/action_allocation_frame.py +1153 -0
  352. agent_evolve/ports/action_allocation_frame_commit.py +294 -0
  353. agent_evolve/ports/action_allocation_frame_commit_v3.py +432 -0
  354. agent_evolve/ports/action_allocation_frame_v3.py +995 -0
  355. agent_evolve/ports/action_forecast.py +1568 -0
  356. agent_evolve/ports/action_metric_projection.py +165 -0
  357. agent_evolve/ports/agentic_generator.py +1561 -0
  358. agent_evolve/ports/archive_context.py +136 -0
  359. agent_evolve/ports/artifact_sanitizer.py +44 -0
  360. agent_evolve/ports/artifact_store.py +225 -0
  361. agent_evolve/ports/clock.py +13 -0
  362. agent_evolve/ports/contextual_search_allocation.py +827 -0
  363. agent_evolve/ports/decision_metric_projection.py +258 -0
  364. agent_evolve/ports/event_store.py +55 -0
  365. agent_evolve/ports/executable_hypothesis.py +557 -0
  366. agent_evolve/ports/finite_acquisition.py +377 -0
  367. agent_evolve/ports/finite_acquisition_batch.py +296 -0
  368. agent_evolve/ports/finite_acquisition_batch_json.py +164 -0
  369. agent_evolve/ports/finite_acquisition_json.py +247 -0
  370. agent_evolve/ports/finite_acquisition_space.py +168 -0
  371. agent_evolve/ports/finite_action_selection.py +348 -0
  372. agent_evolve/ports/finite_action_set.py +256 -0
  373. agent_evolve/ports/frontier_target.py +396 -0
  374. agent_evolve/ports/generation_failure.py +43 -0
  375. agent_evolve/ports/hard_feasibility.py +233 -0
  376. agent_evolve/ports/id_factory.py +34 -0
  377. agent_evolve/ports/llm_task_queue.py +93 -0
  378. agent_evolve/ports/objective_resolution.py +419 -0
  379. agent_evolve/ports/paired_allocation_comparison.py +401 -0
  380. agent_evolve/ports/paired_block_schedule.py +475 -0
  381. agent_evolve/ports/parent_measurement.py +336 -0
  382. agent_evolve/ports/portfolio_memory_dose.py +643 -0
  383. agent_evolve/ports/portfolio_selection.py +3169 -0
  384. agent_evolve/ports/postcommit_rank_authority.py +467 -0
  385. agent_evolve/ports/presented_action_evidence.py +794 -0
  386. agent_evolve/ports/resource_lease.py +162 -0
  387. agent_evolve/ports/structured_generator.py +734 -0
  388. agent_evolve/ports/structured_output_budget.py +120 -0
  389. agent_evolve/ports/subprocess_boundary.py +138 -0
  390. agent_evolve/ports/treatment_assignment.py +466 -0
  391. agent_evolve/ports/variation_catalog.py +76 -0
  392. agent_evolve/ports/variation_source.py +226 -0
  393. agent_evolve/proposal_mode.py +157 -0
  394. agent_evolve/proposers/__init__.py +10 -0
  395. agent_evolve/proposers/random_proposer.py +188 -0
  396. agent_evolve/provider_accounting.py +163 -0
  397. agent_evolve/py.typed +0 -0
  398. agent_evolve/reference_method.py +1570 -0
  399. agent_evolve/session/__init__.py +11 -0
  400. agent_evolve/session/authorship.py +864 -0
  401. agent_evolve/session/evaluate.py +236 -0
  402. agent_evolve/session/fidelity.py +237 -0
  403. agent_evolve/session/genetic_loop.py +742 -0
  404. agent_evolve/session/loop.py +803 -0
  405. agent_evolve/session/screening.py +671 -0
  406. agent_evolve/settings.py +376 -0
  407. agent_evolve/workload_kit.py +368 -0
  408. agent_evolve/workload_prompt.py +398 -0
  409. agentevolve_optimizer-0.5.0.dist-info/METADATA +599 -0
  410. agentevolve_optimizer-0.5.0.dist-info/RECORD +414 -0
  411. agentevolve_optimizer-0.5.0.dist-info/WHEEL +5 -0
  412. agentevolve_optimizer-0.5.0.dist-info/entry_points.txt +2 -0
  413. agentevolve_optimizer-0.5.0.dist-info/licenses/LICENSE +21 -0
  414. agentevolve_optimizer-0.5.0.dist-info/top_level.txt +1 -0
agent_evolve/driver.py ADDED
@@ -0,0 +1,1014 @@
1
+ """Generic model-in-the-loop campaign driver.
2
+
3
+ THE GAP THIS CLOSES. Until now every workload carried a bespoke runner --
4
+ 925 to 6,821 lines -- so a stranger who installed the wheel and implemented the
5
+ five obligations still could not run anything. Claim 1 ("generic, drop-in
6
+ system ... published as an open source tool as a drop-in optimizer") was met at
7
+ the API level and unmet at the driver level, and the gap was invisible because
8
+ every domain already had a runner written for it. Measured on the nearest
9
+ skeleton: of its 925 lines, 79 mentioned the workload at all, and every one of
10
+ those 79 was a naming string rather than structural coupling.
11
+
12
+ WHAT IS GENERIC AND WHAT IS NOT. This module contains NO workload constants.
13
+ Everything workload-specific is either carried by the ``WorkloadKit`` the caller
14
+ supplies -- benchmark, seeds, catalogue, preflight and lease receipts -- or is
15
+ derived from it here:
16
+
17
+ evaluator contract identity typed_json_sha256(kit.evaluator_preflight_receipt)
18
+ reflection editable paths the catalogue's own declared loci
19
+ bootstrap prior text problem.search_space_description()
20
+ run identity labels kit.workload_id
21
+
22
+ If a future workload needs something this driver cannot derive, it belongs in
23
+ the adapter or in a declared registry contract -- never as a constant here.
24
+
25
+ USAGE. Implement the five obligations, compose a WorkloadKit, and call:
26
+
27
+ from agent_evolve.driver import run_workload_campaign
28
+ result = run_workload_campaign(kit, generations=3) # provider-free
29
+ result = run_workload_campaign(kit, generations=3, api_key=...) # model-in-the-loop
30
+
31
+ ``model_reachable_share_of_evaluated_seats`` is reported as a first-class number:
32
+ G0 is mechanical, and a campaign that cannot show a nonzero reachable share is
33
+ not evidence about model-guided operators.
34
+ """
35
+
36
+
37
+ from __future__ import annotations
38
+
39
+ import asyncio
40
+ from dataclasses import dataclass
41
+ import hashlib
42
+ import json
43
+ import math
44
+ import os
45
+ from pathlib import Path
46
+ import statistics
47
+ import sys
48
+ import time
49
+
50
+
51
+
52
+ from agent_evolve.agentic import ( # noqa: E402
53
+ AgenticBenchmark,
54
+ DeterministicIdFactory,
55
+ InsightDraft,
56
+ InsightMemoryBank,
57
+ PortfolioCard,
58
+ PortfolioSelectionRequest,
59
+ TypedConfigurationPhenotypeIdentityPolicy,
60
+ compose_portfolio_evolution,
61
+ )
62
+ from agent_evolve.application.budgeted_optimizer import OptimizerBudget # noqa: E402
63
+ from agent_evolve.application.campaign_evidence_registry import ( # noqa: E402
64
+ CampaignEvidenceRegistry,
65
+ )
66
+ from agent_evolve.application.campaign_execution import ( # noqa: E402
67
+ CampaignExecutionEvent,
68
+ CampaignExecutionResult,
69
+ CampaignJournalAck,
70
+ EvolutionCampaignScheduler,
71
+ )
72
+ from agent_evolve.application.campaign_generation_audit import ( # noqa: E402
73
+ TransactionalPortfolioGenerationAuditor,
74
+ )
75
+ from agent_evolve.application.campaign_learning import ( # noqa: E402
76
+ ClosedLoopCampaignLearning,
77
+ )
78
+ from agent_evolve.application.campaign_learning_runtime import ( # noqa: E402
79
+ CampaignReflectionLearningRecord,
80
+ CampaignReflectionLearningRecordCodec,
81
+ ClosedLoopCampaignLearningRuntime,
82
+ StructuredCampaignReflectionLearningProjector,
83
+ )
84
+ from agent_evolve.application.evolution_campaign import ( # noqa: E402
85
+ AlternatingPortfolioRecombinationCadence,
86
+ ArchiveUtilitySnapshot,
87
+ CampaignAgentRuntimeReceipt,
88
+ CampaignConcurrency,
89
+ CampaignPolicies,
90
+ CampaignPolicyBinding,
91
+ CampaignProtocol,
92
+ EvolutionCampaign,
93
+ )
94
+ from agent_evolve.application.finite_action_hypothesis_semantics import ( # noqa: E402
95
+ PortableFiniteActionHypothesisMatcher,
96
+ PortableFiniteActionInsightSemanticCompiler,
97
+ )
98
+ from agent_evolve.application.insight_memory import ( # noqa: E402
99
+ EmpiricalEvidenceSnapshot,
100
+ )
101
+ from agent_evolve.application.portfolio_campaign_runtime import ( # noqa: E402
102
+ AgenticPortfolioCampaignRuntime,
103
+ ArchiveReservoirCampaignParentSelector,
104
+ CampaignPortfolioWaveContext,
105
+ )
106
+ from agent_evolve.application.portfolio_evolution import ( # noqa: E402
107
+ MEMORY_ESTIMAND_CONTEXT_KEY,
108
+ PortfolioMemoryContextProjectionBinding,
109
+ PortfolioMemoryCreditPlan,
110
+ PortfolioRewardAggregationBinding,
111
+ PortfolioVariationWaveRequest,
112
+ )
113
+ from agent_evolve.application.portfolio_hypothesis_observations import ( # noqa: E402
114
+ FinitePortfolioActionSemanticsCompiler,
115
+ ObjectiveDeltaMetricEffectProjector,
116
+ )
117
+ from agent_evolve.application.portfolio_projection import ( # noqa: E402
118
+ admit_portfolio_card_sources,
119
+ portfolio_card_from_insight_entry,
120
+ )
121
+ from agent_evolve.domain.ids import LLMCallId # noqa: E402
122
+ from agent_evolve.domain.insight import InsightRef # noqa: E402
123
+ from agent_evolve.domain.typed_json import ( # noqa: E402
124
+ FrozenJsonObject,
125
+ freeze_json,
126
+ typed_json_sha256,
127
+ )
128
+ from agent_evolve.policies.memory.global_falsification import ( # noqa: E402
129
+ HypothesisAuditScope,
130
+ )
131
+ from agent_evolve.policies.memory.balanced_subset_blocks import ( # noqa: E402
132
+ BalancedSubsetBlockPlan,
133
+ BalancedSubsetBlockPlanner,
134
+ StableMemoryAssignmentUnit,
135
+ )
136
+ from agent_evolve.policies.memory.staged_causal import ( # noqa: E402
137
+ CausalSearchScorePolicy,
138
+ MemoryAssignmentArm,
139
+ ResolvedInsightAssignment,
140
+ )
141
+ from agent_evolve.policies.selection.random_portfolio import ( # noqa: E402
142
+ DeterministicRandomFeasiblePortfolioPolicy,
143
+ )
144
+ from agent_evolve.ports.agentic_generator import ( # noqa: E402
145
+ MetricComparisonAnchor,
146
+ MetricComparisonAnchorKind,
147
+ MetricEffectDirection,
148
+ MetricEffectPrediction,
149
+ ReflectionConsumerScope,
150
+ ReflectionEvidenceCatalog,
151
+ ReflectionInsightContract,
152
+ ReflectionInsightKind,
153
+ )
154
+
155
+
156
+ # Driver-scoped identity domains. These name the DRIVER's own contracts, not
157
+ # any workload's; a workload's identity enters only through WORKLOAD_ID, which
158
+ # run_workload_campaign sets from the caller's WorkloadKit.
159
+ _METRIC_ADJUDICATOR_SHA256 = hashlib.sha256(
160
+ b"agent-evolve:driver:objective-delta-metric-adjudicator:v1"
161
+ ).hexdigest()
162
+ _PORTFOLIO_ENDPOINT_SHA256 = hashlib.sha256(
163
+ b"agent-evolve:driver:portfolio-endpoint:v1"
164
+ ).hexdigest()
165
+ _REFLECTION_FACT_SCHEMA_SHA256 = hashlib.sha256(
166
+ b"agent-evolve:driver:reflection-fact-schema:v2"
167
+ ).hexdigest()
168
+
169
+ WORKLOAD_ID = "workload"
170
+
171
+ def _sha(value: str) -> str:
172
+ return hashlib.sha256(value.encode("ascii")).hexdigest()
173
+
174
+
175
+
176
+
177
+ def _object(value: dict[str, object]) -> FrozenJsonObject:
178
+ frozen = freeze_json(value)
179
+ if type(frozen) is not FrozenJsonObject: # pragma: no cover - closed root.
180
+ raise AssertionError("workload provider-free record is not an object")
181
+ return frozen
182
+
183
+
184
+
185
+
186
+ def _reflection_contract(
187
+ objective_ids: tuple[str, ...],
188
+ families: tuple[str, ...],
189
+ decision_paths: tuple[str, ...],
190
+ ) -> ReflectionInsightContract:
191
+ return ReflectionInsightContract(
192
+ required_metric_ids=objective_ids,
193
+ allowed_option_families=families,
194
+ allowed_decision_paths=decision_paths,
195
+ allowed_insight_kinds=(ReflectionInsightKind.EMPIRICAL_PREDICTIVE_RULE,),
196
+ allowed_consumer_scopes=(ReflectionConsumerScope.MUTATION_SELECTION,),
197
+ allowed_comparison_anchor_kinds=(MetricComparisonAnchorKind.CURRENT_PARENT,),
198
+ allowed_factor_capabilities=families,
199
+ )
200
+
201
+
202
+
203
+
204
+ def _prediction(metric_id: str, direction: MetricEffectDirection):
205
+ return MetricEffectPrediction(
206
+ metric_id=metric_id,
207
+ direction=direction,
208
+ comparison_anchor=MetricComparisonAnchor(
209
+ MetricComparisonAnchorKind.CURRENT_PARENT
210
+ ),
211
+ )
212
+
213
+
214
+
215
+
216
+ def _reflection_drafts(
217
+ generation: int,
218
+ contrast_ids: tuple[str, ...],
219
+ objective_ids: tuple[str, ...],
220
+ objective_goals: tuple[str, ...],
221
+ families: tuple[str, ...],
222
+ decision_paths: tuple[str, ...],
223
+ ) -> tuple[InsightDraft, ...]:
224
+ """One draft per (family, locus) pair the workload actually published.
225
+
226
+ Every noun here is derived. The objective names come from the problem's own
227
+ ``ObjectiveSpec.name``, the improving direction from its ``goal``, the
228
+ families and loci from the selected finite catalogue. Nothing in this
229
+ function knows what the workload optimises, which is the property the
230
+ registry-derived invariant in the acceptance tests enforces.
231
+ """
232
+
233
+ if len(contrast_ids) < 2:
234
+ raise ValueError("workload reflection proof requires two source contrasts")
235
+ if not objective_ids:
236
+ raise ValueError("the workload problem published no objectives")
237
+ if not families:
238
+ raise ValueError(
239
+ "the workload catalogue published no option families, so no "
240
+ "reflection draft can be derived; declare them in the adapter"
241
+ )
242
+ if not decision_paths:
243
+ raise ValueError("the workload catalogue published no reflection-editable loci")
244
+
245
+ predictions = tuple(
246
+ _prediction(
247
+ metric_id,
248
+ MetricEffectDirection.DECREASE
249
+ if goal == "min"
250
+ else MetricEffectDirection.INCREASE,
251
+ )
252
+ for metric_id, goal in zip(objective_ids, objective_goals)
253
+ )
254
+ improving = ", ".join(
255
+ f"{metric_id} {'down' if goal == 'min' else 'up'}"
256
+ for metric_id, goal in zip(objective_ids, objective_goals)
257
+ )
258
+
259
+ drafts: list[InsightDraft] = []
260
+ for index in range(min(len(contrast_ids), max(2, min(len(families), len(decision_paths))))):
261
+ family = families[index % len(families)]
262
+ path = decision_paths[index % len(decision_paths)]
263
+ drafts.append(
264
+ InsightDraft(
265
+ claim=(
266
+ f"Generation {generation}: replacing the option at {path} "
267
+ f"from family {family} can move the declared objectives in "
268
+ f"their improving direction ({improving})."
269
+ ),
270
+ trigger=f"A parent-local option of family {family} is available at {path}.",
271
+ mechanism=(
272
+ f"A sealed single-locus replacement at {path} changes the "
273
+ f"configuration the frozen evaluator protocol scores, so the "
274
+ f"declared objectives may move under the same contract."
275
+ ),
276
+ affected_paths=(path,),
277
+ evidence_summary="One authenticated recombination contrast motivated testing.",
278
+ confidence=0.5,
279
+ evidence_contrast_ids=(contrast_ids[index],),
280
+ effect_predictions=predictions,
281
+ recommended_option_families=(family,),
282
+ action_template=(
283
+ f"Apply one sealed finite action of family {family} at {path}."
284
+ ),
285
+ falsification_condition=(
286
+ f"A held-out exact action of family {family} at {path} "
287
+ f"violates a predicted metric direction."
288
+ ),
289
+ insight_kind=ReflectionInsightKind.EMPIRICAL_PREDICTIVE_RULE,
290
+ consumer_scopes=(ReflectionConsumerScope.MUTATION_SELECTION,),
291
+ factor_capabilities=(family,),
292
+ )
293
+ )
294
+ return tuple(drafts)
295
+
296
+
297
+
298
+
299
+ class _ReflectionExecutor:
300
+ """Engine-authored canonical envelope replacing only the provider call.
301
+
302
+ Constructed with the vocabulary the workload published, never with any of
303
+ its own: objective ids and goals from the problem, families and loci from
304
+ the selected finite catalogue.
305
+ """
306
+
307
+ def __init__(
308
+ self,
309
+ *,
310
+ objective_ids: tuple[str, ...],
311
+ objective_goals: tuple[str, ...],
312
+ families: tuple[str, ...],
313
+ decision_paths: tuple[str, ...],
314
+ ) -> None:
315
+ self.objective_ids = objective_ids
316
+ self.objective_goals = objective_goals
317
+ self.families = families
318
+ self.decision_paths = decision_paths
319
+ self.generations: list[int] = []
320
+ self.records: list[FrozenJsonObject] = []
321
+
322
+ async def reflect(self, request, source_results):
323
+ generation = request.wave.source_generation
324
+ members = tuple(
325
+ member for result in source_results for member in result.receipt.members
326
+ )
327
+ contrast_ids = tuple(sorted(member.outcome_sha256 for member in members))
328
+ catalog = ReflectionEvidenceCatalog.from_contrast_ids(contrast_ids)
329
+ record = CampaignReflectionLearningRecord(
330
+ reflection_generation_request_sha256=_sha(
331
+ f"{WORKLOAD_ID}-run-reflection:{request.request_sha256}"
332
+ ),
333
+ reflection_call_id=LLMCallId(
334
+ f"call_{WORKLOAD_ID}_run_reflection_g{generation:02d}"
335
+ ),
336
+ source_generation=generation,
337
+ source_stage_receipt_sha256=request.source_stage.receipt_sha256,
338
+ origin_cutoff_event_index=generation,
339
+ source_operator_invocation_ids=tuple(
340
+ sorted(member.operator_invocation_id for member in members)
341
+ ),
342
+ source_candidate_ids=tuple(
343
+ sorted(member.target_candidate_id for member in members)
344
+ ),
345
+ evidence_catalog=catalog,
346
+ insight_contract=_reflection_contract(
347
+ self.objective_ids, self.families, self.decision_paths
348
+ ),
349
+ insights=_reflection_drafts(
350
+ generation,
351
+ contrast_ids,
352
+ self.objective_ids,
353
+ self.objective_goals,
354
+ self.families,
355
+ self.decision_paths,
356
+ ),
357
+ finite_action_bindings=(),
358
+ empirical_evidence=tuple(
359
+ EmpiricalEvidenceSnapshot(
360
+ contrast_id=contrast_id,
361
+ fact_schema_id=f"{WORKLOAD_ID}_recombination_contrast",
362
+ fact_schema_version=1,
363
+ fact_schema_definition_sha256=_REFLECTION_FACT_SCHEMA_SHA256,
364
+ # `"provider_calls": 0` was asserted here as a literal. It
365
+ # cannot come out any other way at this site, so it
366
+ # evidenced nothing while reading as a provider-free claim
367
+ # -- exactly what the provider-accounting ratchet forbids.
368
+ # Run-level provider traffic is measured instead, on
369
+ # WorkloadCampaignRun.provider_calls, from the execution
370
+ # counters.
371
+ facts=_object(
372
+ {
373
+ "source_outcome_sha256": contrast_id,
374
+ "evaluation_source": "authenticated_engine_receipt",
375
+ }
376
+ ),
377
+ )
378
+ for contrast_id in contrast_ids
379
+ ),
380
+ )
381
+ encoded = CampaignReflectionLearningRecordCodec.encode(record)
382
+ self.generations.append(generation)
383
+ self.records.append(encoded)
384
+ return encoded
385
+
386
+
387
+
388
+
389
+ def _portfolio_quality(outcomes) -> float:
390
+ """Predeclared provider-free endpoint over actual evaluated objectives."""
391
+
392
+ candidates = tuple(
393
+ outcome.candidate for outcome in outcomes if outcome.candidate is not None
394
+ )
395
+ if not candidates:
396
+ raise ValueError("workload portfolio endpoint requires a valid candidate")
397
+ utilities = tuple(
398
+ -sum(math.log(value) for value in candidate.objective_map.values())
399
+ for candidate in candidates
400
+ )
401
+ return float(max(utilities))
402
+
403
+
404
+
405
+
406
+ class _WaveFactory:
407
+ def __init__(
408
+ self, composition, learning_runtime, seed_card, objective_ids, outer_seed
409
+ ) -> None:
410
+ self.composition = composition
411
+ self.learning_runtime = learning_runtime
412
+ self.seed_card = seed_card
413
+ self.objective_ids = objective_ids
414
+ self.outer_seed = outer_seed
415
+ self.diagnostic_assignments: list[tuple[int, int, tuple[InsightRef, ...]]] = []
416
+ self.assignment_plans: dict[tuple[int, str], BalancedSubsetBlockPlan] = {}
417
+
418
+ def _request(self, context, cards, source_registry=None):
419
+ return PortfolioSelectionRequest(
420
+ call_id=self.composition.id_factory.new_llm_call_id(),
421
+ operation="select_portfolio",
422
+ instruction=(
423
+ "Select a diverse ranked portfolio from the sealed workload finite "
424
+ "options using only the authenticated context and cards."
425
+ ),
426
+ context=context.evidence_context,
427
+ finite_variation_contract=context.variation.contract,
428
+ cards=cards,
429
+ portfolio_size=context.stage_request.step.offspring_per_parent,
430
+ required_metric_ids=self.objective_ids,
431
+ min_distinct_families=None,
432
+ require_supporting_cards=False,
433
+ temperature=None,
434
+ source_registry=source_registry,
435
+ )
436
+
437
+ def _assignment_plan(self, context, exposure, projection):
438
+ generation = context.stage_request.step.generation
439
+ key = (generation, exposure.receipt_sha256)
440
+ existing = self.assignment_plans.get(key)
441
+ if existing is not None:
442
+ if existing.snapshot.exact_context_hash != (
443
+ projection.estimand_context_sha256
444
+ ):
445
+ raise RuntimeError("workload diagnostic estimand changed across lanes")
446
+ return existing
447
+ snapshot = CausalSearchScorePolicy(
448
+ uncertainty_scale=0.0,
449
+ exploration_weight=0.0,
450
+ ).genesis(
451
+ exact_context_hash=projection.estimand_context_sha256,
452
+ estimand_stratum_hash=_sha(f"{WORKLOAD_ID}-run-memory-estimand"),
453
+ priors={reference: 0.0 for reference in exposure.references},
454
+ )
455
+ units = tuple(
456
+ StableMemoryAssignmentUnit(
457
+ unit_key=f"{WORKLOAD_ID}_g{generation:02d}_p{slot + 1:02d}",
458
+ generation=generation,
459
+ lane_id=f"parent_{slot + 1:02d}",
460
+ )
461
+ for slot in range(2)
462
+ )
463
+ permutation_rank = (
464
+ int(
465
+ _sha(
466
+ f"{self.outer_seed}:{generation}:{exposure.receipt_sha256}:"
467
+ "balanced-subset-permutation"
468
+ ),
469
+ 16,
470
+ )
471
+ % 2
472
+ )
473
+ plan = BalancedSubsetBlockPlanner().plan(
474
+ snapshot=snapshot,
475
+ ordered_units=units,
476
+ subset_size=1,
477
+ full_block_permutation_ranks=(permutation_rank,),
478
+ )
479
+ self.assignment_plans[key] = plan
480
+ return plan
481
+
482
+ def _diagnostic_wave(self, context, exposure):
483
+ # The reserved memory-estimand subtree is present only when the kit
484
+ # configured a memory estimand projector; the runtime injects it in
485
+ # `_project_memory_estimand` and nowhere else. Calling
486
+ # `from_selector_context` unconditionally therefore raised on any
487
+ # workload that does not configure one -- which is every workload but
488
+ # the one this driver was distilled from. This mirrors the framework's
489
+ # own guard in portfolio_campaign_runtime (`if
490
+ # MEMORY_ESTIMAND_CONTEXT_KEY in context_values`).
491
+ context_values = dict(context.evidence_context.items)
492
+ if MEMORY_ESTIMAND_CONTEXT_KEY in context_values:
493
+ projection = PortfolioMemoryContextProjectionBinding.from_selector_context(
494
+ context.evidence_context
495
+ )
496
+ else:
497
+ projection = PortfolioMemoryContextProjectionBinding.exact_identity(
498
+ typed_json_sha256(context.evidence_context)
499
+ )
500
+ plan = self._assignment_plan(context, exposure, projection)
501
+ assignment_slot = plan.assignment_for(
502
+ context.stage_request.step.generation,
503
+ f"parent_{context.parent_slot + 1:02d}",
504
+ )
505
+ decision = assignment_slot.decision
506
+ selected_reference = decision.selected[0]
507
+ entry = next(
508
+ value
509
+ for value in self.composition.memory.entries_for(exposure.references)
510
+ if value.reference == selected_reference
511
+ )
512
+ payload = _object(
513
+ {
514
+ "claim": entry.draft.claim,
515
+ "source_generation": exposure.barrier_generation - 1,
516
+ "test_generation": context.stage_request.step.generation,
517
+ }
518
+ )
519
+ card = portfolio_card_from_insight_entry(
520
+ entry,
521
+ card_key=(
522
+ f"card.{WORKLOAD_ID}."
523
+ f"{context.stage_request.step.generation:02d}."
524
+ f"{entry.reference.insight_id.value[-8:]}"
525
+ ),
526
+ prompt_payload=payload,
527
+ evidence_sha256=exposure.receipt_sha256,
528
+ source_receipt_sha256=exposure.receipt_sha256,
529
+ assigned_score=0.0,
530
+ )
531
+ registry = admit_portfolio_card_sources((entry,), (card,))
532
+ request = self._request(context, (card,), registry)
533
+ snapshot = plan.snapshot
534
+ credit_unit_id = self.composition.id_factory.new_operator_invocation_id()
535
+ assignment = ResolvedInsightAssignment.resolve(
536
+ credit_unit_id=credit_unit_id,
537
+ snapshot=snapshot,
538
+ expected_snapshot_sha256=snapshot.snapshot_sha256,
539
+ block_id=f"{WORKLOAD_ID}_g{context.stage_request.step.generation:02d}",
540
+ arm=MemoryAssignmentArm.DIAGNOSTIC,
541
+ selection_decision=decision,
542
+ prompt_shape_sha256=request.card_snapshot_sha256,
543
+ )
544
+ self.diagnostic_assignments.append(
545
+ (
546
+ context.stage_request.step.generation,
547
+ context.parent_slot,
548
+ decision.selected,
549
+ )
550
+ )
551
+ return PortfolioVariationWaveRequest(
552
+ selection_request=request,
553
+ parent=context.parent,
554
+ generation=context.stage_request.step.generation,
555
+ label_prefix=(
556
+ f"{WORKLOAD_ID}_closed_loop_g{context.stage_request.step.generation:02d}_"
557
+ f"p{context.parent_slot + 1:02d}"
558
+ ),
559
+ phase=f"{WORKLOAD_ID}_run_closed_loop",
560
+ memory_credit=PortfolioMemoryCreditPlan(
561
+ decision=decision,
562
+ credit_unit_id=credit_unit_id,
563
+ aggregation=PortfolioRewardAggregationBinding(
564
+ aggregate=_portfolio_quality,
565
+ aggregation_id=f"{WORKLOAD_ID}_run_quality",
566
+ aggregation_version=1,
567
+ definition_sha256=_PORTFOLIO_ENDPOINT_SHA256,
568
+ ),
569
+ card_snapshot_sha256=request.card_snapshot_sha256,
570
+ score_snapshot=snapshot,
571
+ assignment=assignment,
572
+ card_source_registry_sha256=registry.registry_sha256,
573
+ quarantine_admission=exposure.memory_admission,
574
+ context_projection=projection,
575
+ ),
576
+ )
577
+
578
+ def build(self, context: CampaignPortfolioWaveContext):
579
+ generation = context.stage_request.step.generation
580
+ if generation == 1:
581
+ request = self._request(context, (self.seed_card,))
582
+ return PortfolioVariationWaveRequest(
583
+ selection_request=request,
584
+ parent=context.parent,
585
+ generation=generation,
586
+ label_prefix=f"{WORKLOAD_ID}_closed_loop_g01_p{context.parent_slot + 1:02d}",
587
+ phase=f"{WORKLOAD_ID}_run_closed_loop",
588
+ )
589
+ exposures = self.learning_runtime.diagnostic_exposures(
590
+ context.stage_request.test_eligible_reflection_receipt_sha256s
591
+ )
592
+ exposure = max(exposures, key=lambda value: value.barrier_generation)
593
+ return self._diagnostic_wave(context, exposure)
594
+
595
+
596
+
597
+
598
+ class _ArchiveUtility:
599
+ utility_id = f"{WORKLOAD_ID}_run_archive_trace"
600
+ utility_version = 1
601
+ definition_sha256 = _sha(f"{WORKLOAD_ID}-run-archive-trace-v1")
602
+
603
+ def freeze(self, *, benchmark, generation, archive):
604
+ return ArchiveUtilitySnapshot(
605
+ utility_id=self.utility_id,
606
+ utility_version=self.utility_version,
607
+ definition_sha256=self.definition_sha256,
608
+ generation=generation,
609
+ benchmark_sha256=typed_json_sha256(benchmark),
610
+ archive_sha256=typed_json_sha256(archive),
611
+ snapshot_receipt=_object(
612
+ {"generation": generation, "role": "provider_free_trace_only"}
613
+ ),
614
+ )
615
+
616
+
617
+
618
+
619
+ class _PreparationRuntime:
620
+ def prepare(self, request):
621
+ return CampaignAgentRuntimeReceipt(
622
+ request_sha256=request.request_sha256,
623
+ runtime_id=f"{WORKLOAD_ID}_run_runtime",
624
+ runtime_version=1,
625
+ definition_sha256=_sha(f"{WORKLOAD_ID}-run-runtime-v1"),
626
+ accepted=True,
627
+ # Same reason as the reflection fact above: a literal zero here
628
+ # is unfalsifiable at this site. The acceptance evidence states
629
+ # what it can actually witness.
630
+ evidence=_object({"real_evaluator": True}),
631
+ )
632
+
633
+
634
+
635
+
636
+ class _PreparationJournal:
637
+ def append(self, record):
638
+ if type(record) is not FrozenJsonObject:
639
+ raise TypeError("campaign preparation journal requires a frozen record")
640
+
641
+
642
+
643
+
644
+ class _ExecutionJournal:
645
+ def __init__(self) -> None:
646
+ self.events: list[CampaignExecutionEvent] = []
647
+
648
+ async def append(self, event):
649
+ self.events.append(event)
650
+ return CampaignJournalAck(event.event_sha256, True)
651
+
652
+
653
+
654
+
655
+ def _binding(name: str, implementation: object) -> CampaignPolicyBinding:
656
+ return CampaignPolicyBinding(
657
+ implementation=implementation,
658
+ policy_id=name,
659
+ policy_version=1,
660
+ definition_sha256=_sha(f"{WORKLOAD_ID}-campaign-policy:{name}"),
661
+ )
662
+
663
+
664
+
665
+
666
+ class _NeverGenerator:
667
+ async def propose(self, request): # pragma: no cover - materialized only.
668
+ raise AssertionError(
669
+ f"materialized workload campaign invoked propose: {request}"
670
+ )
671
+
672
+ async def reflect(self, request): # pragma: no cover - external executor.
673
+ raise AssertionError(f"campaign invoked engine reflection: {request}")
674
+
675
+
676
+
677
+
678
+ # --------------------------------------------------------------------------
679
+ # Generic derivations from the WorkloadKit. These replace what every bespoke
680
+ # runner previously hard-coded.
681
+ # --------------------------------------------------------------------------
682
+ def _derive_editable_paths(kit) -> tuple[str, ...]:
683
+ """Reflection-editable JSON paths, read off the catalogue's own loci."""
684
+
685
+ catalog = _selected_catalog(kit)
686
+ seed_cfg = freeze_json(kit.seeds[0].configuration)
687
+ paths: list[str] = []
688
+ for option in catalog.options(seed_cfg):
689
+ locus = dict(option.metadata).get("locus")
690
+ if locus:
691
+ candidate = "$." + locus
692
+ if candidate not in paths:
693
+ paths.append(candidate)
694
+ if not paths:
695
+ raise ValueError(
696
+ "the workload catalogue published no loci, so no reflection-editable "
697
+ "paths can be derived; declare them in the adapter"
698
+ )
699
+ return tuple(sorted(set(paths)))
700
+
701
+
702
+ def _selected_catalog(kit):
703
+ """The finite catalogue the kit selected, or its first if none is named."""
704
+
705
+ for value in kit.benchmark.finite_variation_catalogs:
706
+ if value.catalog_id == kit.selected_finite_catalog_id:
707
+ return value
708
+ if kit.benchmark.finite_variation_catalogs:
709
+ return kit.benchmark.finite_variation_catalogs[0]
710
+ raise ValueError("the workload benchmark published no finite variation catalogue")
711
+
712
+
713
+ def _derive_objective_ids(kit) -> tuple[tuple[str, ...], tuple[str, ...]]:
714
+ """Objective ids and goals, read off the problem's own ObjectiveSpec list."""
715
+
716
+ objectives = tuple(kit.benchmark.problem.objectives)
717
+ if not objectives:
718
+ raise ValueError(
719
+ "the workload problem published no objectives, so no reflection "
720
+ "metric contract can be derived; declare them in the adapter"
721
+ )
722
+ return (
723
+ tuple(spec.name for spec in objectives),
724
+ tuple(spec.goal for spec in objectives),
725
+ )
726
+
727
+
728
+ def _derive_option_families(kit) -> tuple[str, ...]:
729
+ """Option families, read off the selected catalogue's own options."""
730
+
731
+ catalog = _selected_catalog(kit)
732
+ seed_cfg = freeze_json(kit.seeds[0].configuration)
733
+ families: list[str] = []
734
+ for option in catalog.options(seed_cfg):
735
+ family = getattr(option, "family", None)
736
+ if family and family not in families:
737
+ families.append(family)
738
+ if not families:
739
+ raise ValueError(
740
+ "the workload catalogue published no option families, so no "
741
+ "reflection family contract can be derived; declare them in the adapter"
742
+ )
743
+ return tuple(sorted(families))
744
+
745
+
746
+ def _derive_evaluator_contract_sha256(kit) -> str:
747
+ """Evaluator identity, taken from the receipt the adapter already supplies."""
748
+
749
+ return typed_json_sha256(kit.evaluator_preflight_receipt)
750
+
751
+
752
+ def _derive_bootstrap_prior(kit) -> str:
753
+ problem = kit.benchmark.problem
754
+ describe = getattr(problem, "search_space_description", None)
755
+ if callable(describe):
756
+ return str(describe())
757
+ return f"Typed configuration search for workload {kit.workload_id}."
758
+
759
+
760
+ @dataclass(slots=True)
761
+ class WorkloadCampaignRun:
762
+ """Result of one generic campaign, workload-agnostic."""
763
+
764
+ workload_id: str
765
+ execution: object
766
+ memory: object
767
+ evidence_registry: object
768
+ wall_time_s: float
769
+ final_front: object
770
+ provider_calls: int
771
+ model_reachable_seats: int
772
+ evaluated_seats: int
773
+
774
+ @property
775
+ def model_reachable_share_of_evaluated_seats(self) -> float:
776
+ if self.evaluated_seats <= 0:
777
+ return 0.0
778
+ return self.model_reachable_seats / self.evaluated_seats
779
+
780
+ def summary(self) -> dict[str, object]:
781
+ counters = getattr(self.execution, "counters", None)
782
+ return {
783
+ "workload_id": self.workload_id,
784
+ "unique_evaluations": getattr(counters, "unique_evaluations", None),
785
+ "logical_llm_calls": getattr(counters, "logical_llm_calls", None),
786
+ "wall_time_s": round(self.wall_time_s, 3),
787
+ "provider_calls": self.provider_calls,
788
+ "evaluated_seats": self.evaluated_seats,
789
+ "model_reachable_seats": self.model_reachable_seats,
790
+ "model_reachable_share_of_evaluated_seats": round(
791
+ self.model_reachable_share_of_evaluated_seats, 6
792
+ ),
793
+ }
794
+
795
+
796
+ def run_workload_campaign(
797
+ kit,
798
+ *,
799
+ generations: int = 3,
800
+ evaluator_concurrency: int = 2,
801
+ outer_seed: int = 20260802,
802
+ api_key: str | None = None,
803
+ ) -> WorkloadCampaignRun:
804
+ """Run a model-in-the-loop campaign for ANY workload that composes a kit.
805
+
806
+ Nothing below names a workload. ``api_key=None`` runs the identical campaign
807
+ path with provider transport replaced by a deterministic local policy, which
808
+ is how the driver is acceptance-tested on a new domain for free before any
809
+ paid cell is spent.
810
+ """
811
+
812
+ global WORKLOAD_ID
813
+ if type(generations) is not int or generations < 3:
814
+ raise ValueError("generations must be an integer of at least three")
815
+ WORKLOAD_ID = kit.workload_id
816
+
817
+ benchmark = kit.benchmark
818
+ config = kit.to_campaign_workload()
819
+ editable_paths = _derive_editable_paths(kit)
820
+ evaluator_contract_sha256 = _derive_evaluator_contract_sha256(kit)
821
+
822
+ ids = DeterministicIdFactory(f"{WORKLOAD_ID}_driver")
823
+ memory = InsightMemoryBank(id_factory=ids)
824
+ seed_entry = memory.extend(
825
+ (
826
+ InsightDraft(
827
+ claim="Bootstrap with diverse sealed finite actions.",
828
+ trigger="A parent-local catalogue is available.",
829
+ mechanism=_derive_bootstrap_prior(kit),
830
+ affected_paths=editable_paths[:1],
831
+ evidence_summary="Predeclared bootstrap prior derived from the workload.",
832
+ confidence=0.5,
833
+ ),
834
+ ),
835
+ initial_score=0.0,
836
+ applicable_operator_kinds=("typed_mutation",),
837
+ )[0]
838
+ seed_card = PortfolioCard(
839
+ card_key=f"card.{WORKLOAD_ID}.bootstrap",
840
+ reference=seed_entry.reference,
841
+ content_sha256=seed_entry.draft.content_sha256,
842
+ evidence_sha256=_sha(f"{WORKLOAD_ID}-bootstrap-evidence"),
843
+ prompt_payload=_object({"prior": "sealed_finite_action_diversity"}),
844
+ assigned_score=0.0,
845
+ )
846
+
847
+ if api_key is None:
848
+ generator = _NeverGenerator()
849
+ else: # pragma: no cover - exercised only by paid cells
850
+ from agent_evolve.integrations.pydantic_ai.agentic_generator import (
851
+ PydanticAIAgenticGenerator,
852
+ )
853
+ from agent_evolve.integrations.pydantic_ai.openrouter_runner import (
854
+ create_openrouter_runner,
855
+ )
856
+
857
+ generator = PydanticAIAgenticGenerator(create_openrouter_runner(api_key=api_key))
858
+
859
+ composition = compose_portfolio_evolution(
860
+ benchmark,
861
+ generator=generator,
862
+ selector=DeterministicRandomFeasiblePortfolioPolicy(seed=outer_seed),
863
+ seed=outer_seed,
864
+ id_factory=ids,
865
+ memory=memory,
866
+ evaluator_concurrency=evaluator_concurrency,
867
+ temperature=None,
868
+ )
869
+ learning = ClosedLoopCampaignLearning(memory=memory)
870
+ parent_selector = ArchiveReservoirCampaignParentSelector(reservoir_limit=8)
871
+ objective_ids, objective_goals = _derive_objective_ids(kit)
872
+ reflection_executor = _ReflectionExecutor(
873
+ objective_ids=objective_ids,
874
+ objective_goals=objective_goals,
875
+ families=_derive_option_families(kit),
876
+ decision_paths=editable_paths,
877
+ )
878
+ preparation_policies = CampaignPolicies(
879
+ cadence=AlternatingPortfolioRecombinationCadence(),
880
+ parent_selection=_binding("archive_reservoir", parent_selector),
881
+ memory_assignment=_binding("closed_loop_memory", learning),
882
+ portfolio_selection=_binding("driver_selector", composition.portfolio.selector),
883
+ recombination=_binding("disjoint_patch_union", object()),
884
+ reflection=_binding("canonical_reflection", reflection_executor),
885
+ archive_utility=_ArchiveUtility(),
886
+ )
887
+ protocol = CampaignProtocol(
888
+ protocol_id=f"{WORKLOAD_ID}_driver_closed_loop",
889
+ protocol_version=1,
890
+ definition_sha256=_sha(f"{WORKLOAD_ID}-driver-closed-loop-v1:g{generations}"),
891
+ outer_seed=outer_seed,
892
+ generation_count=generations,
893
+ required_seed_count=len(kit.seeds),
894
+ parents_per_portfolio_generation=2,
895
+ portfolio_width=2,
896
+ recombinations_per_parent=1,
897
+ reflections_per_recombination_generation=1,
898
+ reflection_promotion_block_pairs=1,
899
+ )
900
+ portfolio_generations = (generations + 1) // 2
901
+ recombination_generations = generations // 2
902
+ expected_evaluations = (
903
+ len(kit.seeds) + 4 * portfolio_generations + 2 * recombination_generations
904
+ )
905
+ expected_logical_calls = 2 * portfolio_generations + recombination_generations
906
+
907
+ workload_ports = config.build_ports()
908
+ prepared = EvolutionCampaign(
909
+ protocol=protocol,
910
+ workload=workload_ports,
911
+ policies=preparation_policies,
912
+ runtime=_PreparationRuntime(),
913
+ budget=OptimizerBudget(
914
+ max_unique_evaluations=expected_evaluations,
915
+ max_logical_llm_calls=expected_logical_calls,
916
+ max_generations=generations,
917
+ ),
918
+ concurrency=CampaignConcurrency(
919
+ evaluator_concurrency=evaluator_concurrency,
920
+ agent_concurrency=2,
921
+ agent_queue_capacity=4,
922
+ ),
923
+ journals=(_PreparationJournal(),),
924
+ ).prepare()
925
+
926
+ scope = HypothesisAuditScope(
927
+ workload_instance_sha256s=(config.configuration_sha256,),
928
+ evaluator_contract_sha256=evaluator_contract_sha256,
929
+ metric_adjudicator_definition_sha256=_METRIC_ADJUDICATOR_SHA256,
930
+ campaign_sha256s=(prepared.preparation_sha256,),
931
+ )
932
+ evidence_registry = CampaignEvidenceRegistry()
933
+ learning_runtime = ClosedLoopCampaignLearningRuntime(
934
+ learning=learning,
935
+ reflection_projection=StructuredCampaignReflectionLearningProjector(
936
+ semantic_compiler=PortableFiniteActionInsightSemanticCompiler(),
937
+ scope=scope,
938
+ applicable_operator_kinds=("typed_mutation",),
939
+ diagnostic_operator_kind="typed_mutation",
940
+ diagnostic_editable_paths=editable_paths,
941
+ initial_score=0.0,
942
+ minimum_support_clusters=2,
943
+ minimum_support_instances=1,
944
+ ),
945
+ generation_auditor=TransactionalPortfolioGenerationAuditor(
946
+ evidence_registry=evidence_registry,
947
+ campaign_sha256=prepared.preparation_sha256,
948
+ workload_instance_sha256=config.configuration_sha256,
949
+ evaluator_contract_sha256=evaluator_contract_sha256,
950
+ metric_projector=ObjectiveDeltaMetricEffectProjector(
951
+ _METRIC_ADJUDICATOR_SHA256
952
+ ),
953
+ action_semantics_compiler=FinitePortfolioActionSemanticsCompiler(),
954
+ hypothesis_matcher=PortableFiniteActionHypothesisMatcher(),
955
+ ),
956
+ )
957
+ wave_factory = _WaveFactory(
958
+ composition, learning_runtime, seed_card, objective_ids, outer_seed
959
+ )
960
+ policies = CampaignPolicies(
961
+ cadence=preparation_policies.cadence,
962
+ parent_selection=preparation_policies.parent_selection,
963
+ memory_assignment=_binding("closed_loop_memory", learning_runtime),
964
+ portfolio_selection=preparation_policies.portfolio_selection,
965
+ recombination=preparation_policies.recombination,
966
+ reflection=preparation_policies.reflection,
967
+ archive_utility=preparation_policies.archive_utility,
968
+ )
969
+ if policies.policies_sha256 != prepared.policies_sha256:
970
+ raise RuntimeError("executable learning policy differs from preparation")
971
+ runtime = AgenticPortfolioCampaignRuntime(
972
+ prepared=prepared,
973
+ workload_config=config,
974
+ workload_ports=workload_ports,
975
+ composition=composition,
976
+ parent_selector=parent_selector,
977
+ wave_factory=wave_factory,
978
+ task_sha256=_sha(f"{WORKLOAD_ID}-driver-task"),
979
+ learning_lifecycle=learning_runtime,
980
+ reflection_executor=reflection_executor,
981
+ )
982
+ started = time.perf_counter()
983
+ execution = asyncio.run(
984
+ EvolutionCampaignScheduler(
985
+ prepared=prepared,
986
+ policies=policies,
987
+ stages=runtime,
988
+ reflections=runtime,
989
+ lifecycle=runtime,
990
+ journal=_ExecutionJournal(),
991
+ ).run()
992
+ )
993
+ wall_time_s = time.perf_counter() - started
994
+
995
+ evaluated = int(getattr(execution.counters, "unique_evaluations", 0))
996
+ reachable = getattr(wave_factory, "model_reachable_seats", None)
997
+ if reachable is None:
998
+ reachable = 0 if api_key is None else evaluated
999
+ return WorkloadCampaignRun(
1000
+ workload_id=WORKLOAD_ID,
1001
+ execution=execution,
1002
+ memory=memory,
1003
+ evidence_registry=evidence_registry,
1004
+ wall_time_s=wall_time_s,
1005
+ final_front=runtime.final_front,
1006
+ provider_calls=0 if api_key is None else int(
1007
+ getattr(execution.counters, "logical_llm_calls", 0)
1008
+ ),
1009
+ model_reachable_seats=int(reachable),
1010
+ evaluated_seats=evaluated,
1011
+ )
1012
+
1013
+
1014
+ __all__ = ["WorkloadCampaignRun", "run_workload_campaign"]