sciel 0.23.2__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 (305) hide show
  1. sciel/__init__.py +1 -0
  2. sciel/campaign/__init__.py +0 -0
  3. sciel/campaign/budget.py +467 -0
  4. sciel/campaign/identity.py +97 -0
  5. sciel/campaign/memory.py +298 -0
  6. sciel/campaign/no_regression.py +118 -0
  7. sciel/candidate_modules/__init__.py +239 -0
  8. sciel/causal/__init__.py +4 -0
  9. sciel/causal/estimators.py +70 -0
  10. sciel/causal/ledger.py +134 -0
  11. sciel/causal/sequential.py +102 -0
  12. sciel/cli/__init__.py +0 -0
  13. sciel/cli/live.py +144 -0
  14. sciel/cli/main.py +335 -0
  15. sciel/cli/profile.py +65 -0
  16. sciel/cli/start.py +189 -0
  17. sciel/cli/supervise.py +202 -0
  18. sciel/components/__init__.py +0 -0
  19. sciel/components/bets/__init__.py +0 -0
  20. sciel/components/code_novelty.py +105 -0
  21. sciel/components/containers.py +374 -0
  22. sciel/components/policy/__init__.py +0 -0
  23. sciel/components/policy/base.py +52 -0
  24. sciel/components/policy/code_embed.py +472 -0
  25. sciel/components/policy/controller.py +166 -0
  26. sciel/components/policy/mode_bandit.py +93 -0
  27. sciel/components/policy/mode_features.py +30 -0
  28. sciel/components/policy/mode_policy_mlp.py +102 -0
  29. sciel/components/policy/pop_features.py +29 -0
  30. sciel/components/policy/preset_weights.py +127 -0
  31. sciel/components/policy/three_head.py +167 -0
  32. sciel/components/policy/tilt.py +40 -0
  33. sciel/components/selection/__init__.py +0 -0
  34. sciel/components/selection/kernels.py +206 -0
  35. sciel/components/selection/novelty_chain.py +82 -0
  36. sciel/config.py +155 -0
  37. sciel/config_validation.py +180 -0
  38. sciel/culture/__init__.py +3 -0
  39. sciel/culture/methods.py +52 -0
  40. sciel/culture/repertoire.py +90 -0
  41. sciel/demo/__init__.py +5 -0
  42. sciel/demo/circles.py +54 -0
  43. sciel/diagnostics/__init__.py +1 -0
  44. sciel/diagnostics/methods_observer.py +427 -0
  45. sciel/diagnostics/paired_eval.py +244 -0
  46. sciel/engine/__init__.py +0 -0
  47. sciel/engine/admission.py +358 -0
  48. sciel/engine/assay.py +81 -0
  49. sciel/engine/bootstrap.py +270 -0
  50. sciel/engine/capacity.py +425 -0
  51. sciel/engine/checkpoint.py +133 -0
  52. sciel/engine/checkpoint_identity.py +230 -0
  53. sciel/engine/checkpoint_restore.py +248 -0
  54. sciel/engine/container_db.py +212 -0
  55. sciel/engine/cooperative_io.py +420 -0
  56. sciel/engine/db.py +259 -0
  57. sciel/engine/decisions.py +85 -0
  58. sciel/engine/determinism.py +24 -0
  59. sciel/engine/evaluation.py +199 -0
  60. sciel/engine/evaluation_timing.py +114 -0
  61. sciel/engine/evaluator_fifo.py +209 -0
  62. sciel/engine/eviction_planner.py +22 -0
  63. sciel/engine/factory.py +104 -0
  64. sciel/engine/incubator.py +201 -0
  65. sciel/engine/initialization.py +354 -0
  66. sciel/engine/journal_anchor.py +26 -0
  67. sciel/engine/knockout.py +91 -0
  68. sciel/engine/lifecycle.py +251 -0
  69. sciel/engine/llm/__init__.py +0 -0
  70. sciel/engine/llm/anthropic_api.py +78 -0
  71. sciel/engine/llm/claude_code.py +149 -0
  72. sciel/engine/llm/client.py +443 -0
  73. sciel/engine/llm/codex.py +368 -0
  74. sciel/engine/llm/codex_protocol.py +252 -0
  75. sciel/engine/llm/errors.py +132 -0
  76. sciel/engine/llm/mock.py +109 -0
  77. sciel/engine/llm/trace.py +133 -0
  78. sciel/engine/loop.py +98 -0
  79. sciel/engine/loop_contracts.py +105 -0
  80. sciel/engine/novelty.py +376 -0
  81. sciel/engine/observed_changes.py +404 -0
  82. sciel/engine/observed_schema.py +189 -0
  83. sciel/engine/operators.py +107 -0
  84. sciel/engine/output_measurements.py +44 -0
  85. sciel/engine/output_novelty.py +256 -0
  86. sciel/engine/parallel.py +472 -0
  87. sciel/engine/parallel_calls.py +330 -0
  88. sciel/engine/parallel_control.py +51 -0
  89. sciel/engine/parallel_recovery.py +363 -0
  90. sciel/engine/parallel_schedule.py +215 -0
  91. sciel/engine/parallel_store.py +433 -0
  92. sciel/engine/population_view.py +113 -0
  93. sciel/engine/portfolio_allocation.py +74 -0
  94. sciel/engine/probe.py +75 -0
  95. sciel/engine/prompt/__init__.py +0 -0
  96. sciel/engine/prompt/budget.py +20 -0
  97. sciel/engine/prompt/build.py +202 -0
  98. sciel/engine/prompt/parse.py +54 -0
  99. sciel/engine/prompt/patch.py +101 -0
  100. sciel/engine/prompt/sources.py +10 -0
  101. sciel/engine/prompt/templates/cross.txt +26 -0
  102. sciel/engine/prompt/templates/diff.txt +24 -0
  103. sciel/engine/prompt/templates/error_repair.txt +23 -0
  104. sciel/engine/prompt/templates/fix.txt +8 -0
  105. sciel/engine/prompt/templates/full_rewrite.txt +24 -0
  106. sciel/engine/prompt/templates/idea.txt +27 -0
  107. sciel/engine/provider_abandonment.py +15 -0
  108. sciel/engine/recovery.py +85 -0
  109. sciel/engine/repeat_execution.py +177 -0
  110. sciel/engine/repeat_journal.py +91 -0
  111. sciel/engine/repeat_learning.py +20 -0
  112. sciel/engine/repeat_planning.py +128 -0
  113. sciel/engine/repeat_policy.py +131 -0
  114. sciel/engine/repeat_promotion.py +147 -0
  115. sciel/engine/repeat_state.py +253 -0
  116. sciel/engine/repeat_support.py +175 -0
  117. sciel/engine/research_artifacts.py +323 -0
  118. sciel/engine/research_candidate.py +84 -0
  119. sciel/engine/research_cells_context.py +168 -0
  120. sciel/engine/research_culture.py +119 -0
  121. sciel/engine/research_queue.py +129 -0
  122. sciel/engine/research_search_evidence.py +160 -0
  123. sciel/engine/research_targets.py +204 -0
  124. sciel/engine/research_tool_signals.py +57 -0
  125. sciel/engine/run_lock.py +37 -0
  126. sciel/engine/runtime.py +165 -0
  127. sciel/engine/schedule.py +179 -0
  128. sciel/engine/siblings.py +135 -0
  129. sciel/engine/source_identity.py +16 -0
  130. sciel/engine/step_cycle.py +217 -0
  131. sciel/engine/step_plan.py +405 -0
  132. sciel/engine/telemetry.py +168 -0
  133. sciel/engine/types.py +87 -0
  134. sciel/engine/validation.py +444 -0
  135. sciel/engine/viability.py +431 -0
  136. sciel/engine/warm_start.py +69 -0
  137. sciel/engine/worker.py +294 -0
  138. sciel/engine/worker_feedback.py +131 -0
  139. sciel/eval/__init__.py +0 -0
  140. sciel/eval/_candidate_worker.py +131 -0
  141. sciel/eval/_repeat_runner.py +229 -0
  142. sciel/eval/_runner.py +280 -0
  143. sciel/eval/_scorer_worker.py +24 -0
  144. sciel/eval/candidate_backend.py +209 -0
  145. sciel/eval/candidate_config.py +58 -0
  146. sciel/eval/candidate_evidence.py +52 -0
  147. sciel/eval/candidate_receipts.py +272 -0
  148. sciel/eval/candidate_registry.py +2 -0
  149. sciel/eval/cascade.py +55 -0
  150. sciel/eval/facade.py +153 -0
  151. sciel/eval/native_geometry.py +251 -0
  152. sciel/eval/near_output.py +147 -0
  153. sciel/eval/output_identity.py +308 -0
  154. sciel/eval/packing_geometry.py +185 -0
  155. sciel/eval/registry.py +251 -0
  156. sciel/eval/repeat_docker.py +187 -0
  157. sciel/eval/repeat_draw.py +466 -0
  158. sciel/eval/repeat_io.py +51 -0
  159. sciel/eval/sandbox.py +350 -0
  160. sciel/eval/scorer_container.py +186 -0
  161. sciel/eval/task_prompt.py +82 -0
  162. sciel/eval/trusted_scoring/__init__.py +1 -0
  163. sciel/eval/trusted_scoring/adapter.py +125 -0
  164. sciel/eval/trusted_scoring/beat.py +191 -0
  165. sciel/eval/trusted_scoring/circle.py +102 -0
  166. sciel/eval/trusted_scoring/heil.py +107 -0
  167. sciel/eval/trusted_scoring/transport.py +120 -0
  168. sciel/evidence/__init__.py +1 -0
  169. sciel/evidence/change_audit.py +243 -0
  170. sciel/evidence/eligibility.py +110 -0
  171. sciel/evidence/measurement.py +186 -0
  172. sciel/evidence/restart_optimizer_trace.py +189 -0
  173. sciel/evidence/restart_trace.py +54 -0
  174. sciel/evidence/restart_trace_recorder.py +253 -0
  175. sciel/evidence/restart_trace_source.py +31 -0
  176. sciel/evidence/restart_trace_validation.py +234 -0
  177. sciel/evidence/restart_trace_values.py +231 -0
  178. sciel/local_task.py +142 -0
  179. sciel/methods/__init__.py +11 -0
  180. sciel/methods/__main__.py +397 -0
  181. sciel/methods/_loader.py +99 -0
  182. sciel/methods/_runner.py +225 -0
  183. sciel/methods/budget.py +322 -0
  184. sciel/methods/campaign.py +372 -0
  185. sciel/methods/configuration.py +139 -0
  186. sciel/methods/coordinator.py +368 -0
  187. sciel/methods/coordinator_context.py +108 -0
  188. sciel/methods/coordinator_contracts.py +42 -0
  189. sciel/methods/coordinator_episode.py +251 -0
  190. sciel/methods/coordinator_exchange.py +156 -0
  191. sciel/methods/coordinator_execution.py +170 -0
  192. sciel/methods/coordinator_planning.py +156 -0
  193. sciel/methods/coordinator_policy.py +193 -0
  194. sciel/methods/engine_bridge.py +342 -0
  195. sciel/methods/evidence.py +384 -0
  196. sciel/methods/examples.py +255 -0
  197. sciel/methods/executor.py +519 -0
  198. sciel/methods/funding.py +119 -0
  199. sciel/methods/materialize.py +248 -0
  200. sciel/methods/models.py +242 -0
  201. sciel/methods/proposals.py +289 -0
  202. sciel/methods/provider_budget.py +71 -0
  203. sciel/methods/registry.py +500 -0
  204. sciel/methods/registry_records.py +117 -0
  205. sciel/methods/resource_values.py +129 -0
  206. sciel/methods/tasks.py +203 -0
  207. sciel/methods/technical.py +167 -0
  208. sciel/methods/transport.py +217 -0
  209. sciel/population.py +15 -0
  210. sciel/research_tools/__init__.py +2 -0
  211. sciel/research_tools/artifact_manifest.py +207 -0
  212. sciel/research_tools/artifact_reading.py +34 -0
  213. sciel/research_tools/canonical_diagnostics.py +241 -0
  214. sciel/research_tools/canonical_evidence.py +94 -0
  215. sciel/research_tools/cells.py +394 -0
  216. sciel/research_tools/comparison_assessment.py +89 -0
  217. sciel/research_tools/config.py +174 -0
  218. sciel/research_tools/continuations.py +289 -0
  219. sciel/research_tools/controller.py +236 -0
  220. sciel/research_tools/controller_jobs.py +315 -0
  221. sciel/research_tools/controller_state.py +204 -0
  222. sciel/research_tools/decision_projection.py +116 -0
  223. sciel/research_tools/episode_evidence.py +129 -0
  224. sciel/research_tools/episode_execution.py +249 -0
  225. sciel/research_tools/episode_results.py +224 -0
  226. sciel/research_tools/experiment_protocol.py +271 -0
  227. sciel/research_tools/followups.py +442 -0
  228. sciel/research_tools/job_worker.py +240 -0
  229. sciel/research_tools/jobs.py +364 -0
  230. sciel/research_tools/library.py +357 -0
  231. sciel/research_tools/lifecycle.py +377 -0
  232. sciel/research_tools/lifecycle_delivery.py +198 -0
  233. sciel/research_tools/lifecycle_evidence.py +324 -0
  234. sciel/research_tools/observation_cards.py +179 -0
  235. sciel/research_tools/planning.py +152 -0
  236. sciel/research_tools/projection_data.py +169 -0
  237. sciel/research_tools/projection_validation.py +133 -0
  238. sciel/research_tools/prompt_builder.py +393 -0
  239. sciel/research_tools/prompt_sections.py +377 -0
  240. sciel/research_tools/replay_feedback.py +153 -0
  241. sciel/research_tools/research_steps.py +222 -0
  242. sciel/research_tools/result_contract.py +73 -0
  243. sciel/research_tools/result_projection.py +319 -0
  244. sciel/research_tools/retained_observations.py +227 -0
  245. sciel/research_tools/sequential_research.py +371 -0
  246. sciel/research_tools/shared_evidence.py +408 -0
  247. sciel/research_tools/sharing.py +287 -0
  248. sciel/research_tools/stage_data.py +68 -0
  249. sciel/research_tools/tool_actions.py +241 -0
  250. sciel/research_tools/tool_artifacts.py +175 -0
  251. sciel/research_tools/tool_protocol.py +41 -0
  252. sciel/research_tools/transfer_jobs.py +190 -0
  253. sciel/reward.py +181 -0
  254. sciel/rl/__init__.py +3 -0
  255. sciel/rl/critic.py +104 -0
  256. sciel/rl/policy.py +235 -0
  257. sciel/rl/returns.py +56 -0
  258. sciel/rng.py +38 -0
  259. sciel/run_log.py +212 -0
  260. sciel/solvers/__init__.py +1 -0
  261. sciel/solvers/circle_anytime.py +257 -0
  262. sciel/solvers/circle_lp_initializer.py +132 -0
  263. sciel/solvers/circle_relocation.py +121 -0
  264. sciel/stats.py +217 -0
  265. sciel/swm/__init__.py +6 -0
  266. sciel/swm/archive.py +91 -0
  267. sciel/swm/diffusion.py +61 -0
  268. sciel/swm/embedding.py +94 -0
  269. sciel/swm/model.py +200 -0
  270. sciel/swm/niches.py +46 -0
  271. sciel/swm/sets.py +63 -0
  272. sciel/swm/tabular.py +66 -0
  273. sciel/swm/targets.py +63 -0
  274. sciel/swm/world.py +500 -0
  275. sciel/task.py +21 -0
  276. sciel/taskbuilder/__init__.py +118 -0
  277. sciel/taskbuilder/audit.py +92 -0
  278. sciel/taskbuilder/draft.py +69 -0
  279. sciel/taskbuilder/materials.py +88 -0
  280. sciel/theory/__init__.py +7 -0
  281. sciel/theory/assumptions.py +131 -0
  282. sciel/theory/claims.py +138 -0
  283. sciel/theory/experiments.py +106 -0
  284. sciel/theory/findings.py +148 -0
  285. sciel/theory/procedures.py +89 -0
  286. sciel/theory/schools.py +64 -0
  287. sciel/theory/strategies.py +85 -0
  288. sciel/theory/trials.py +107 -0
  289. sciel/tui/__init__.py +0 -0
  290. sciel/tui/board.py +52 -0
  291. sciel/ui/__init__.py +1 -0
  292. sciel/ui/activity.py +112 -0
  293. sciel/ui/engine.py +169 -0
  294. sciel/ui/render.py +165 -0
  295. sciel/ui/state.py +343 -0
  296. sciel/ui/static/engine.js +162 -0
  297. sciel/ui/static/index.html +397 -0
  298. sciel/ui/terminal.py +455 -0
  299. sciel/ui/views.py +307 -0
  300. sciel/ui/web.py +144 -0
  301. sciel-0.23.2.dist-info/METADATA +508 -0
  302. sciel-0.23.2.dist-info/RECORD +305 -0
  303. sciel-0.23.2.dist-info/WHEEL +5 -0
  304. sciel-0.23.2.dist-info/entry_points.txt +2 -0
  305. sciel-0.23.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,147 @@
1
+ """Opt-in, output-only repeat promotion with durable, non-replayed draw identities.
2
+
3
+ The caller must durably checkpoint every accepted plan, then acknowledge that
4
+ checkpoint before dispatch. This component never changes search fitness or RNG.
5
+ """
6
+
7
+ from __future__ import annotations
8
+ from copy import deepcopy
9
+ from datetime import datetime, timezone
10
+ import fcntl
11
+ from fractions import Fraction
12
+ import hashlib
13
+ import math
14
+ from pathlib import Path
15
+ import time
16
+ from .repeat_journal import Journal, digest, encoded, fsync_directory, immutable_file
17
+ from .repeat_policy import (
18
+ CONTRACT,
19
+ RepeatPromotionError,
20
+ SEED_CONTRACT,
21
+ _FIXED,
22
+ _LIMITS,
23
+ _REQUIRED,
24
+ _aggregate,
25
+ _finite,
26
+ _fraction,
27
+ _numeric_capture,
28
+ _rational,
29
+ _source_sha,
30
+ _valid,
31
+ bootstrap_decision,
32
+ paired_dominance,
33
+ validate_config,
34
+ )
35
+
36
+ from .repeat_planning import RepeatPlanning
37
+ from .repeat_execution import RepeatExecution
38
+ from .repeat_state import RepeatState
39
+
40
+
41
+ class RepeatPromotion(
42
+ RepeatPlanning,
43
+ RepeatExecution,
44
+ RepeatState,
45
+ ):
46
+ CONTRACT = CONTRACT
47
+
48
+ DIRECTORY = "repeat_promotion"
49
+
50
+ IDENTITY_REQUIRED_EXTRA = frozenset()
51
+
52
+
53
+ def __init__(self, run_dir, config, identity, draw_fn):
54
+ self.config = validate_config(config)
55
+ if not self.config["enabled"]:
56
+ raise ValueError("do not construct RepeatPromotion for disabled configuration")
57
+ required = {"contract", "task", "task_hash", "canonical_initial_source_sha256",
58
+ "task_evaluator_sha256", "adapter"} | self.IDENTITY_REQUIRED_EXTRA
59
+ if (not isinstance(identity, dict) or required - set(identity)
60
+ or set(identity) - required - {"integration_sha256"}
61
+ or identity["contract"] != self.CONTRACT):
62
+ raise ValueError("repeat identity fields/contract differ")
63
+ for key in ("task_hash", "canonical_initial_source_sha256", "task_evaluator_sha256"):
64
+ if not isinstance(identity[key], str) or len(identity[key]) != 64 or any(c not in "0123456789abcdef" for c in identity[key]):
65
+ raise ValueError(f"invalid repeat identity {key}")
66
+ if not isinstance(identity["task"], str) or not identity["task"] or not isinstance(identity["adapter"], dict):
67
+ raise ValueError("invalid task/adapter identity")
68
+ if "integration_sha256" in identity:
69
+ pins = identity["integration_sha256"]
70
+ if (not isinstance(pins, dict) or not pins or any(not isinstance(k, str) or not k
71
+ or not isinstance(v, str) or len(v) != 64 or any(c not in "0123456789abcdef" for c in v)
72
+ for k, v in pins.items())):
73
+ raise ValueError("invalid integration source hashes")
74
+ self.identity = deepcopy(identity)
75
+ self.contract_hash = digest({"contract": self.CONTRACT, "seed_contract": SEED_CONTRACT,
76
+ "config": self.config, "identity": self.identity})
77
+ self.directory = Path(run_dir) / self.DIRECTORY
78
+ self.journal = Journal(self.directory / "journal.jsonl")
79
+ self.draw_fn = draw_fn
80
+ self._lock = None
81
+ self._ack = None
82
+ self._data = None
83
+
84
+ def _acquire(self):
85
+ self._lock = (self.directory / "coordinator.lock").open("a+b")
86
+ try:
87
+ fcntl.flock(self._lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
88
+ except OSError:
89
+ self._lock.close()
90
+ self._lock = None
91
+ raise RepeatPromotionError("repeat coordinator already active") from None
92
+
93
+ def close(self):
94
+ if self._lock is not None:
95
+ self._lock.close()
96
+ self._lock = None
97
+
98
+ def start(self, run_id):
99
+ if self._data is not None:
100
+ if run_id != self._data["run_id"]:
101
+ raise RepeatPromotionError("repeat run ID changed")
102
+ return
103
+ if not isinstance(run_id, str) or not run_id or len(run_id) > 200:
104
+ raise ValueError("invalid repeat run ID")
105
+ self.directory.mkdir() # exclusive; an existing run must use load_state
106
+ fsync_directory(self.directory.parent)
107
+ self._acquire()
108
+ (self.directory / "sources").mkdir()
109
+ (self.directory / "receipts").mkdir()
110
+ fsync_directory(self.directory)
111
+ self._append({"type": "header", "run_id": run_id, "contract_hash": self.contract_hash,
112
+ "config": self.config, "identity": self.identity})
113
+
114
+ @property
115
+ def pending(self):
116
+ return bool(self._data and self._data["batches"] and self._data["batches"][-1]["decision"] is None)
117
+
118
+ @property
119
+ def stopped_reason(self):
120
+ return self._data["stopped_reason"] if self._data else None
121
+
122
+ def _batch(self):
123
+ return self._data["batches"][-1]
124
+
125
+ def _append(self, event):
126
+ self._check_live()
127
+ self.journal.append(deepcopy(event))
128
+ self._apply(event)
129
+
130
+ def _check_live(self):
131
+ if self._lock is None:
132
+ raise RepeatPromotionError("repeat coordinator is not active")
133
+ if digest({"contract": self.CONTRACT, "seed_contract": SEED_CONTRACT,
134
+ "config": self.config, "identity": self.identity}) != self.contract_hash:
135
+ raise RepeatPromotionError("repeat configuration/identity changed in memory")
136
+
137
+ def _source(self, sha):
138
+ code = (self.directory / "sources" / (sha + ".py")).read_bytes().decode("utf-8")
139
+ if _source_sha(code) != sha:
140
+ raise RepeatPromotionError("retained source hash mismatch")
141
+ return code
142
+
143
+ def checkpoint_ack(self, anchor):
144
+ self._check_live()
145
+ if anchor != self.journal.anchor:
146
+ raise RepeatPromotionError("checkpoint does not bind the current repeat ledger")
147
+ self._ack = deepcopy(anchor)
@@ -0,0 +1,253 @@
1
+ """Repeat journal reduction, restored state and exported comparisons."""
2
+ from __future__ import annotations
3
+
4
+ from copy import deepcopy
5
+ import math
6
+ from .repeat_journal import digest, encoded
7
+ from .repeat_policy import (RepeatPromotionError, _source_sha)
8
+
9
+
10
+ class RepeatState:
11
+
12
+ def _apply(self, event):
13
+ kind = event["type"]
14
+ if kind == "header":
15
+ if self._data is not None or event != {"type": "header", "run_id": event["run_id"],
16
+ "contract_hash": self.contract_hash, "config": self.config, "identity": self.identity}:
17
+ raise RepeatPromotionError("repeat header identity mismatch")
18
+ self._data = {"run_id": event["run_id"], "batches": [], "sources": {}, "claimed_sources": [],
19
+ "confirmed": None, "budget_unavailable": [], "unexamined_candidates": [],
20
+ "stopped_reason": None}
21
+ return
22
+ if self._data is None:
23
+ raise RepeatPromotionError("repeat header missing")
24
+ if kind == "unexamined_candidate":
25
+ if (set(event) != {"type", "source_sha256", "program_id", "screening", "reason"}
26
+ or self.pending or self.stopped_reason
27
+ or not isinstance(event["reason"], str) or not event["reason"].strip()
28
+ or len(event["reason"]) > 200):
29
+ raise RepeatPromotionError("invalid unexamined candidate event")
30
+ code = self._source(event["source_sha256"])
31
+ screening = self._screen_candidate(code, event["screening"], event["program_id"])
32
+ if screening is None or encoded(screening) != encoded(event["screening"]):
33
+ raise RepeatPromotionError("unexamined candidate was not eligible")
34
+ self._data["sources"][event["source_sha256"]] = code
35
+ self._data["unexamined_candidates"].append(deepcopy(event))
36
+ self._data["stopped_reason"] = "search_step_incomplete"
37
+ return
38
+ if kind == "budget_unavailable":
39
+ if self.pending:
40
+ raise RepeatPromotionError("budget event inside pending batch")
41
+ self._data["budget_unavailable"].append(deepcopy(event))
42
+ if event["kind"] == "bootstrap":
43
+ self._data["stopped_reason"] = "bootstrap_budget_unavailable"
44
+ return
45
+ if kind == "plan":
46
+ if self.pending or self.stopped_reason:
47
+ raise RepeatPromotionError("new plan while pending/stopped")
48
+ plan = event["plan"]
49
+ if "research_context" in plan:
50
+ if plan["kind"] != "comparison" or plan["research_context"] is None:
51
+ raise RepeatPromotionError("research context requires a comparison plan")
52
+ self._research_context(plan["research_context"], plan["challenger"])
53
+ seq = len(self._data["batches"])
54
+ expected_incumbent = self._data["confirmed"]["source_sha256"] if self._data["confirmed"] else None
55
+ if (plan["sequence"] != seq or plan["batch_id"] != f"b{seq:06d}"
56
+ or plan["kind"] != ("bootstrap" if seq == 0 else "comparison")
57
+ or plan["incumbent"] != expected_incumbent
58
+ or (seq == 0 and plan["challenger"] != self.identity["canonical_initial_source_sha256"])
59
+ or plan["challenger"] in self._data["claimed_sources"]
60
+ or plan["draws"] != self._planned_draws(seq, plan["kind"], plan["challenger"], plan["incumbent"])):
61
+ raise RepeatPromotionError("repeat plan source/seed/order mismatch")
62
+ n = len(plan["draws"])
63
+ counters = self.summary()["counters"]
64
+ wall = n * (self.config["timeout_seconds"] + self.config["certification_seconds"])
65
+ if (plan["reserved_wall_seconds"] != wall
66
+ or counters["reserved_draw_attempts"] + n > self.config["max_draw_attempts"]
67
+ or counters["planned_wall_seconds"] + wall > self.config["max_wall_seconds"]
68
+ or (seq and counters["comparisons"] >= self.config["max_comparisons"])):
69
+ raise RepeatPromotionError("repeat plan budget mismatch")
70
+ for sha in {d["source_sha256"] for d in plan["draws"]}:
71
+ self._data["sources"][sha] = self._source(sha)
72
+ self._data["claimed_sources"].append(plan["challenger"])
73
+ self._data["batches"].append({"plan": deepcopy(plan), "intents": [], "receipts": {}, "decision": None})
74
+ return
75
+ if not self.pending:
76
+ raise RepeatPromotionError("repeat event outside pending batch")
77
+ batch = self._batch()
78
+ if kind == "decision":
79
+ decision = event["decision"]
80
+ if decision != self._decision(batch):
81
+ raise RepeatPromotionError("repeat decision differs from receipts")
82
+ if len(batch["receipts"]) < len(batch["plan"]["draws"]) and decision["stopped_reason"] not in ("unknown_dispatch", "infrastructure"):
83
+ raise RepeatPromotionError("premature repeat decision")
84
+ batch["decision"] = deepcopy(decision)
85
+ self._data["stopped_reason"] = decision["stopped_reason"]
86
+ if decision["result"]["status"] in ("confirmed", "promote"):
87
+ metrics = decision["result"]["aggregates"]
88
+ if batch["plan"]["kind"] == "comparison":
89
+ metrics = metrics["challenger"]
90
+ self._data["confirmed"] = {"source_sha256": batch["plan"]["challenger"],
91
+ "decision_id": decision["decision_id"], "batch_id": batch["plan"]["batch_id"],
92
+ "metrics": deepcopy(metrics), "program_id": batch["plan"]["program_id"]}
93
+ return
94
+ if event.get("batch_id") != batch["plan"]["batch_id"]:
95
+ raise RepeatPromotionError("repeat event batch mismatch")
96
+ key = event.get("draw_id")
97
+ draw = next((d for d in batch["plan"]["draws"] if d["draw_id"] == key), None)
98
+ if draw is None or key in batch["receipts"]:
99
+ raise RepeatPromotionError("unknown or repeated repeat draw key")
100
+ if kind == "intent":
101
+ remaining = [d["draw_id"] for d in batch["plan"]["draws"] if d["draw_id"] not in batch["receipts"]]
102
+ if (key in batch["intents"] or key != remaining[0]
103
+ or any(r["status"] in ("infrastructure", "unknown") for r in batch["receipts"].values())
104
+ or any(i not in batch["receipts"] for i in batch["intents"])):
105
+ raise RepeatPromotionError("repeat dispatch order/replay violation")
106
+ batch["intents"].append(key)
107
+ elif kind in ("terminal", "unknown"):
108
+ if key not in batch["intents"]:
109
+ raise RepeatPromotionError("repeat terminal lacks dispatch intent")
110
+ batch["receipts"][key] = (self._read_receipt(event, draw) if kind == "terminal" else
111
+ {"status": "unknown", "raw_sum": None, "certified_sum": None,
112
+ "reason": "dispatch_intent_without_terminal_receipt"})
113
+ else:
114
+ raise RepeatPromotionError("unknown repeat event type")
115
+
116
+ def state(self):
117
+ if self._data is None:
118
+ raise RepeatPromotionError("repeat coordinator not started")
119
+ return {"contract": self.CONTRACT, "contract_hash": self.contract_hash,
120
+ "run_id": self._data["run_id"], "ledger_anchor": deepcopy(self.journal.anchor),
121
+ "data": deepcopy(self._data)}
122
+
123
+ def load_state(self, saved):
124
+ if self._data is not None or self._lock is not None:
125
+ raise RepeatPromotionError("repeat state already initialized")
126
+ if not isinstance(saved, dict) or set(saved) != {"contract", "contract_hash", "run_id", "ledger_anchor", "data"}:
127
+ raise RepeatPromotionError("missing/unbound repeat checkpoint")
128
+ if saved["contract"] != self.CONTRACT or saved["contract_hash"] != self.contract_hash:
129
+ raise RepeatPromotionError("repeat checkpoint identity mismatch")
130
+ self._acquire()
131
+ try:
132
+ rows = self.journal.read()
133
+ anchor = saved["ledger_anchor"]
134
+ size = anchor.get("entries")
135
+ if (type(size) is not int or not 1 <= size <= len(rows)
136
+ or anchor != {"entries": size, "sha256": rows[size - 1]["sha256"]}):
137
+ raise RepeatPromotionError("repeat checkpoint ledger prefix mismatch")
138
+ for row in rows[:size]:
139
+ self._apply(row["event"])
140
+ if self._data != saved["data"] or self._data["run_id"] != saved["run_id"]:
141
+ raise RepeatPromotionError("repeat checkpoint state differs from journal prefix")
142
+ pending_id = self._batch()["plan"]["batch_id"] if self.pending else None
143
+ for row in rows[size:]:
144
+ event = row["event"]
145
+ batch_id = event.get("batch_id", event.get("decision", {}).get("batch_id"))
146
+ if event["type"] not in ("intent", "terminal", "unknown", "decision") or batch_id != pending_id:
147
+ raise RepeatPromotionError("uncheckpointed repeat plan or unrelated journal tail")
148
+ self._apply(event)
149
+ self.journal.rows = rows
150
+ self._ack = deepcopy(anchor)
151
+ if self.pending:
152
+ batch = self._batch()
153
+ unresolved = [key for key in batch["intents"] if key not in batch["receipts"]]
154
+ if unresolved:
155
+ self._append({"type": "unknown", "batch_id": batch["plan"]["batch_id"], "draw_id": unresolved[0]})
156
+ self._finish()
157
+ elif len(batch["receipts"]) == len(batch["plan"]["draws"]) or any(r["status"] in ("infrastructure", "unknown") for r in batch["receipts"].values()):
158
+ self._finish()
159
+ except BaseException:
160
+ self.close()
161
+ raise
162
+
163
+ def terminal_comparisons(self):
164
+ """Export durable paired batches, preserving absent versus unknown draws.
165
+
166
+ The decision-prefix anchor remains stable when later batches are added.
167
+ Bootstrap is not a comparison. This method neither creates measurements
168
+ nor changes promotion/search state, and works after the lock is closed.
169
+ """
170
+ if self._data is None:
171
+ return []
172
+ rows = self.journal.read()
173
+ if rows != self.journal.rows:
174
+ raise RepeatPromotionError("repeat journal changed before comparison export")
175
+ decisions = {r["event"]["decision"]["batch_id"]: r for r in rows
176
+ if r["event"]["type"] == "decision"}
177
+ terminals = {r["event"]["draw_id"]: r["event"] for r in rows
178
+ if r["event"]["type"] == "terminal"}
179
+ result = []
180
+ for batch in self._data["batches"]:
181
+ plan, decision = batch["plan"], batch["decision"]
182
+ if plan["kind"] != "comparison" or decision is None:
183
+ continue
184
+ row = decisions.get(plan["batch_id"])
185
+ if row is None or row["event"]["decision"] != decision:
186
+ raise RepeatPromotionError("comparison lacks its durable decision")
187
+ pairs = [{"seed": self._seed(plan["sequence"], i),
188
+ "comparator": None, "challenger": None} for i in range(3)]
189
+ ordered = []
190
+ for draw in plan["draws"]:
191
+ key = draw["draw_id"]
192
+ receipt = batch["receipts"].get(key)
193
+ event = terminals.get(key)
194
+ if event is not None and self._read_receipt(event, draw) != receipt:
195
+ raise RepeatPromotionError("comparison receipt differs from durable artifact")
196
+ pairs[draw["draw_index"]]["comparator" if draw["role"] == "incumbent"
197
+ else "challenger"] = deepcopy(receipt)
198
+ ordered.append({**deepcopy(draw), "receipt_sha256":
199
+ event["artifact_sha256"] if event else None})
200
+ result.append({"namespace": "h15:" + digest([self._data["run_id"], self.contract_hash]),
201
+ "batch_id": plan["batch_id"], "program_id": plan["program_id"],
202
+ "research_context": deepcopy(plan.get("research_context")),
203
+ "comparator_source_sha256": plan["incumbent"],
204
+ "challenger_source_sha256": plan["challenger"],
205
+ "source_pair": {"comparator": self._source(plan["incumbent"]),
206
+ "challenger": self._source(plan["challenger"])},
207
+ "adapter_identity": deepcopy(self.identity["adapter"]),
208
+ "limits": self._receipt_limits(), "pairs": pairs,
209
+ "provenance": {"kind": "h15_terminal_batch/1", "run_id": self._data["run_id"],
210
+ "contract_hash": self.contract_hash,
211
+ "decision_anchor": {"entries": row["sequence"] + 1, "sha256": row["sha256"]},
212
+ "plan": deepcopy(plan), "decision": deepcopy(decision), "ordered_draws": ordered}})
213
+ return result
214
+
215
+ def summary(self):
216
+ batches = self._data["batches"] if self._data else []
217
+ receipts = [r for b in batches for r in b["receipts"].values()]
218
+ cap = self.config["timeout_seconds"] + self.config["certification_seconds"]
219
+ reserved = sum(len(b["plan"]["draws"]) for b in batches)
220
+ terminal = [r for r in receipts if r["status"] != "unknown"]
221
+ actual = math.fsum(r["elapsed_seconds"] for r in terminal)
222
+ held = (reserved - len(terminal)) * cap
223
+ released = math.fsum(max(0.0, cap - r["elapsed_seconds"]) for r in terminal)
224
+ confirmed = self._data["confirmed"] if self._data else None
225
+ return {"contract": self.CONTRACT, "status": self.stopped_reason or
226
+ ("pending" if self.pending else "confirmed" if confirmed else "uninitialized"),
227
+ "stopped_reason": self.stopped_reason, "confirmed_source_sha256": confirmed["source_sha256"] if confirmed else None,
228
+ "pending": self.pending, "counters": {
229
+ "reserved_draw_attempts": reserved, "draw_attempts": sum(len(b["intents"]) for b in batches),
230
+ "comparisons": sum(b["plan"]["kind"] == "comparison" for b in batches),
231
+ "completed": len(terminal), "failed": sum(r["status"] in ("candidate_failure", "infrastructure") for r in receipts),
232
+ "unknown": sum(r["status"] == "unknown" for r in receipts),
233
+ "certified_draws": sum(r["status"] == "valid" for r in receipts),
234
+ "planned_wall_seconds": reserved * cap, "actual_wall_seconds": actual,
235
+ "held_wall_seconds": held, "released_wall_seconds": released},
236
+ "budget_unavailable": deepcopy(self._data["budget_unavailable"] if self._data else []),
237
+ "unexamined_candidates": deepcopy(self._data["unexamined_candidates"] if self._data else []),
238
+ "coverage_complete": bool(confirmed and not self.pending and not self.stopped_reason
239
+ and not self._data["budget_unavailable"]),
240
+ "decisions": [deepcopy(b["decision"]) for b in batches if b["decision"] is not None],
241
+ "wall_budget_policy": "lifetime_planned_phase_allowances_no_reallocation; actual includes adapter elapsed and cleanup"}
242
+
243
+ def export(self, observed_program=None):
244
+ observed = None
245
+ if observed_program is not None:
246
+ def value(name):
247
+ return observed_program.get(name) if isinstance(observed_program, dict) else getattr(observed_program, name, None)
248
+ observed = {"id": value("id"), "source_sha256": _source_sha(value("code")), "score": value("score")}
249
+ confirmed = deepcopy(self._data["confirmed"]) if self._data else None
250
+ if confirmed:
251
+ confirmed["code"] = self._source(confirmed["source_sha256"])
252
+ return {"status": self.summary()["status"], "observed_search_best": observed,
253
+ "confirmed_output_incumbent": confirmed, "repeat_summary": self.summary()}
@@ -0,0 +1,175 @@
1
+ """H15 integration boundary: canonical task, search safe points and explicit export.
2
+
3
+ Imported only when repeat promotion is enabled. Legacy search observations,
4
+ population fitness and research outcomes remain independent of repeat receipts.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from functools import partial
9
+ import hashlib
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+
14
+ CANONICAL_TASK_HASH = 'a6e2fdbc46d97d4d3a7bd1959fa501b3331c5e2303364c4bfd89356fb84244d6'
15
+ INITIAL_SHA = 'd432ec2da7c307180a4dafff1be1ca47cf37be07c40b12c5fedae69417fd639e'
16
+ EVALUATOR_SHA = 'e996baad4acf38ebe8faab8fb2e5d91bb691c7255e26257bdaa4d8efc9494f85'
17
+ BODY_TASK_HASH = '6aea22dd864e8788a5e58a4aac257bbd4451ba9cfa4a6f4f97d487f39665420a'
18
+ BODY_INITIAL_SHA = '3089f4e36bf787275ade5c3c24d4836ad8dc26e409185c0679c3377f4ce9c5f9'
19
+ TRACED_BODY_TASK_HASH = '0726f12ed2a03a754a0a25049268a37e2ad7ff9773db66d7113305383c122095'
20
+ TRACED_BODY_INITIAL_SHA = '2f4bd6cc96eb780a73f547f1e24f28961a3b3a70478a04e4c6fc4a864e76e34d'
21
+ TRACED_EXECUTION_PROFILE = 'paired_restart_trace/1'
22
+ OPTIMIZER_TRACED_EXECUTION_PROFILE = 'paired_restart_trace/2'
23
+ OPTIMIZER_TRACED_TASK_HASH = 'd1b5422d2a943f4757b7db09381a8e49d6d138f6ec9994fdc834630fba4c3e0e'
24
+ OPTIMIZER_TRACED_INITIAL_SHA = '93bc6ed5658a2a299c660de06d5dc4bf0e623f1d8a258aa2504b2a8a5ad98cae'
25
+
26
+ # Old observations remain readable under their original metric identity. These
27
+ # hashes do not authorize executing an old task with the current repeat mode.
28
+ LEGACY_GEOMETRY_EVALUATOR_SHA = '6ca0714c55f7101c3145b030c3a5e754ec94401fabedd4952fe319572edd3ead'
29
+ HISTORICAL_NATIVE_GEOMETRY_TASK_EVALUATORS = dict.fromkeys((
30
+ '34f919d0c1937a79ce039bcdf75b863443f1f63edb77734bc7b506ae17f91aeb',
31
+ '149a3887108c5ff96ac783036ea62b318433ec8a0104f8bcf6db9e31253297ef',
32
+ '5f65a12e159ced391a1635833cb2d24f60813763e5a6e237de228eea7d68987e',
33
+ 'a936b3365f80fcff7da567c5985e5d327295c66b75ce3144253405f1ebde6481',
34
+ ), LEGACY_GEOMETRY_EVALUATOR_SHA)
35
+ # Before the shared importable-candidate loader, this evaluator already used
36
+ # binary64 constraint checks. Its recorded observations retain that exact
37
+ # evaluator identity; these entries never authorize a new repeat execution.
38
+ HISTORICAL_NATIVE_GEOMETRY_TASK_EVALUATORS.update(dict.fromkeys((
39
+ 'a597f167ece11256458997773abbf009ce569b06518f88b17325eb585289d614',
40
+ 'e3549f4cb473e8ae8bc319680f9f12a9a761f6520ee31c182682bb17b7acbc0e',
41
+ '976d9ae145dd3cd7c897bfde304c913e6c16b4e4fc0391a4137032191f823926',
42
+ '3fc57bfd26a6164671df0bf4fe3013387a1f9dda5b603b806f82c1b598fbf944',
43
+ ), '44366fd28850b02da1303a7f1616b0e724f28b837d6ea506b26d4a91096523f4'))
44
+ # Public task instructions changed the task hash, not its evaluator or seed.
45
+ # Keep every previously recorded metric identity readable without authorizing
46
+ # execution under a stale task descriptor.
47
+ HISTORICAL_NATIVE_GEOMETRY_TASK_EVALUATORS.update(dict.fromkeys((
48
+ '4a2bfdd6e0eb925e88560bbde9e3f6fab9b63f7e9058c9966393476ee7adff60',
49
+ 'fe5a424943169db9b29798713ae0465c4ed02c4e7bc215eff2e3edf0457a17c8',
50
+ '8dc9f2f9e1fa842e22fc68c5642691aba41c8fadec7128c4430b63cf32ba3f67',
51
+ '85b24214a299c3ef6e01c127a4e7875774d2902741d167be839ff445f462856d',
52
+ ), EVALUATOR_SHA))
53
+ HISTORICAL_CIRCLE_TASK_HASHES = (
54
+ '899687d940b3dc83c43db7be6b9a78b3e3c2119fcbfff069f7126e1bdd77f228',
55
+ 'd85ebdd86dc5dfccf3663624e74c4a063c7e2b03b1e0595291d261b64fc6c2c9',
56
+ *HISTORICAL_NATIVE_GEOMETRY_TASK_EVALUATORS,
57
+ )
58
+ KNOWN_CIRCLE_TASK_HASHES = (CANONICAL_TASK_HASH, BODY_TASK_HASH, TRACED_BODY_TASK_HASH, OPTIMIZER_TRACED_TASK_HASH,
59
+ *HISTORICAL_CIRCLE_TASK_HASHES)
60
+ NATIVE_GEOMETRY_TASK_EVALUATORS = {**HISTORICAL_NATIVE_GEOMETRY_TASK_EVALUATORS,
61
+ CANONICAL_TASK_HASH: EVALUATOR_SHA,
62
+ BODY_TASK_HASH: EVALUATOR_SHA, TRACED_BODY_TASK_HASH: EVALUATOR_SHA,
63
+ OPTIMIZER_TRACED_TASK_HASH: EVALUATOR_SHA}
64
+
65
+
66
+ def _sha(data):
67
+ return hashlib.sha256(data).hexdigest()
68
+
69
+
70
+ def validate_registered_native_task(task):
71
+ """Preflight known native evaluators using file hashes, without execution.
72
+
73
+ Unregistered/third-party evaluators are outside this registry. A registered
74
+ evaluator must retain an explicitly reviewed complete task identity.
75
+ """
76
+ evaluator_sha = _sha(Path(task.evaluator_path).read_bytes())
77
+ if evaluator_sha not in set(NATIVE_GEOMETRY_TASK_EVALUATORS.values()):
78
+ return None
79
+ if NATIVE_GEOMETRY_TASK_EVALUATORS.get(task.task_hash) != evaluator_sha:
80
+ raise ValueError('unregistered native evaluator/task tuple')
81
+ return {'task_hash': task.task_hash, 'evaluator_sha256': evaluator_sha}
82
+
83
+
84
+ def validate_circle_task(task):
85
+ """Accept one pinned task/seed pair, never an arbitrary named Circle task."""
86
+ from ..eval.registry import load_task
87
+ current = load_task(task.root)
88
+ initial = Path(task.initial_program_path).read_bytes()
89
+ evaluator = Path(task.evaluator_path).read_bytes()
90
+ if (task.qualified_name != 'oe/circle_packing' or current.task_hash != CANONICAL_TASK_HASH
91
+ or task.task_hash != current.task_hash or _sha(initial) != INITIAL_SHA
92
+ or _sha(evaluator) != EVALUATOR_SHA):
93
+ raise ValueError('repeat_promotion requires the pinned canonical Circle task and initial source')
94
+ return initial, evaluator
95
+
96
+
97
+ def create(config, task, run_dir, python):
98
+ from ..eval.repeat_draw import adapter_identity, draw
99
+ from .repeat_promotion import CONTRACT, RepeatPromotion
100
+
101
+ runtime = config.get('runtime', {'backend': 'native'})
102
+ initial, evaluator = validate_circle_task(task)
103
+ # Runtime/source hashes belong to this enabled mode's identity, not to the
104
+ # default Engine contract or any historical experimental manifest.
105
+ here = Path(__file__).resolve().parent
106
+ identity = {'contract': CONTRACT, 'task': task.qualified_name, 'task_hash': task.task_hash,
107
+ 'canonical_initial_source_sha256': _sha(initial), 'task_evaluator_sha256': _sha(evaluator),
108
+ 'adapter': adapter_identity(python=python, runtime=runtime),
109
+ 'integration_sha256': {name: _sha((here / name).read_bytes()) for name in
110
+ ('repeat_support.py', 'repeat_promotion.py', 'repeat_journal.py',
111
+ 'loop.py', 'checkpoint.py', '../config.py', '../run_log.py')}}
112
+ return RepeatPromotion(run_dir, config, identity,
113
+ partial(draw, python=python, runtime=runtime,
114
+ expected_identity=identity['adapter']))
115
+
116
+
117
+ def assert_search_anchor(log_path, anchor):
118
+ """Refuse to replay a post-checkpoint search step when restoring H15 state."""
119
+ if not isinstance(anchor, dict):
120
+ raise ValueError('repeat promotion requires a bound search journal anchor')
121
+ offset = anchor.get('byte_offset')
122
+ if type(offset) is not int or offset < 1:
123
+ raise ValueError('invalid repeat promotion search journal anchor')
124
+ data = Path(log_path).read_bytes()
125
+ if len(data) < offset or _sha(data[:offset]) != anchor.get('prefix_sha256'):
126
+ raise ValueError('repeat promotion search journal prefix differs')
127
+ if not data.endswith(b'\n'):
128
+ raise ValueError('incomplete search journal tail')
129
+ allowed = {'checkpoint', 'run_end', 'run_start', 'checkpoint_restore'}
130
+ for line in data[offset:].splitlines():
131
+ item = json.loads(line)
132
+ if not isinstance(item, dict) or item.get('event') not in allowed:
133
+ raise ValueError('uncheckpointed search activity; refusing repeat/search replay')
134
+
135
+
136
+ def durable_write(path, data):
137
+ """Replace an export only after all bytes are durable; fsync its directory."""
138
+ path = Path(path)
139
+ temporary = path.with_name(path.name + '.tmp')
140
+ with temporary.open('wb') as stream:
141
+ stream.write(data)
142
+ stream.flush()
143
+ os.fsync(stream.fileno())
144
+ os.replace(temporary, path)
145
+ directory = os.open(path.parent, os.O_RDONLY)
146
+ try:
147
+ os.fsync(directory)
148
+ finally:
149
+ os.close(directory)
150
+
151
+
152
+ def export(engine):
153
+ observed = None
154
+ if engine.db.pop_best_id is not None:
155
+ p = engine.db.get(engine.db.pop_best_id)
156
+ observed = p
157
+ result = engine.repeat_promotion.export(observed)
158
+ confirmed = result.get('confirmed_output_incumbent')
159
+ path = Path(engine.run_dir) / 'confirmed_program.py'
160
+ if confirmed is not None:
161
+ code = confirmed['code']
162
+ if _sha(code.encode()) != confirmed['source_sha256']:
163
+ raise ValueError('confirmed output source digest differs')
164
+ durable_write(path, code.encode())
165
+ # The retained source lives in the repeat ledger; the user-facing summary
166
+ # links to its explicit artifact rather than silently replacing pop_best.
167
+ result = {**result, 'confirmed_output_incumbent':
168
+ {k: v for k, v in confirmed.items() if k != 'code'}}
169
+ result['confirmed_output_incumbent']['path'] = str(path.resolve())
170
+ elif path.exists():
171
+ # A stale export from another state must not look like a current result.
172
+ raise ValueError('unconfirmed state has an existing confirmed_program.py')
173
+ durable_write(Path(engine.run_dir) / 'repeat_promotion.json',
174
+ (json.dumps(result, indent=2, allow_nan=False) + '\n').encode())
175
+ return result