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,431 @@
1
+ """Viability contract: one typed Propose->Validate->Repair cycle for candidates.
2
+
3
+ The engine cannot constrain a closed API model's decoding with a grammar, so the
4
+ only available form of "constrained decoding" is post-hoc: classify what is wrong
5
+ with a completion into a typed Violation, then apply a declarative repair policy.
6
+ This module supplies classification and mechanical repairs. validation.validate_candidate
7
+ composes them with graft/duplicate/novelty decisions; run_worker owns requests and evals.
8
+
9
+ Violation kinds (checked in this priority order per attempt):
10
+ empty -- thinking-only / no code extracted
11
+ syntax -- does not parse (incl. the mid-docstring completion family)
12
+ resource -- statically-fatal in the sandbox (multiprocessing + local workers)
13
+ interface -- dropped an entry-point the evaluator calls (repaired by graft)
14
+ duplicate -- normalized code already seen on the island
15
+
16
+ `empty`, `syntax`, `resource` are PRE-EVAL: caught before spending a sandbox run.
17
+ `interface` is repaired unconditionally by graft (no-op when nothing was dropped).
18
+ `duplicate` is checked after graft. The repair table below is declarative; the
19
+ RepairPolicy indirection is where a learned policy will later live (the journal
20
+ already records grafted / empty_responses / gate_rejections outcomes)."""
21
+
22
+ from __future__ import annotations
23
+
24
+ import ast
25
+ from dataclasses import dataclass, field
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Violation:
30
+ kind: str # empty | syntax | resource | interface | duplicate
31
+ detail: str = ""
32
+
33
+
34
+ def _docstring_repair(child: str) -> str | None:
35
+ """One observed cheap syntax family: the completion starts mid-docstring
36
+ (prose preamble swallowed the opening quotes). If prepending quotes makes the
37
+ module parse, return the repaired text; else None."""
38
+ if child.lstrip().startswith(('"""', "'''", "#", "import ", "from ", "def ",
39
+ "class ", "@")):
40
+ return None
41
+ fixed = '"""' + child
42
+ return fixed if _parses(fixed) else None
43
+
44
+
45
+ def _parses(code: str) -> bool:
46
+ try:
47
+ ast.parse(code)
48
+ return True
49
+ except SyntaxError:
50
+ return False
51
+
52
+
53
+ def _strip_fences(child: str) -> str | None:
54
+ """Stray markdown fence or backtick lines left inside the extracted code."""
55
+ kept = [line for line in child.split("\n") if not line.strip().startswith("```")]
56
+ return "\n".join(kept) if len(kept) != child.count("\n") + 1 else None
57
+
58
+
59
+ def _expand_tabs(child: str) -> str | None:
60
+ return child.expandtabs(4) if "\t" in child else None
61
+
62
+
63
+ def _dedent_module(child: str) -> str | None:
64
+ """A module whose every code line carries the same leading indent."""
65
+ lines = [line for line in child.split("\n") if line.strip()]
66
+ if not lines:
67
+ return None
68
+ common = min(len(line) - len(line.lstrip(" ")) for line in lines)
69
+ if common == 0:
70
+ return None
71
+ return "\n".join(line[common:] if line[:common].isspace() else line.lstrip(" ")
72
+ for line in child.split("\n"))
73
+
74
+
75
+ SYNTAX_REPAIRS = (("strip_fences", _strip_fences), ("expand_tabs", _expand_tabs),
76
+ ("dedent_module", _dedent_module), ("prepend_docstring", _docstring_repair))
77
+
78
+
79
+ def _syntax_repair(child: str) -> tuple[str, str] | None:
80
+ """Try each repair alone, then cumulatively; return the first parsing variant and its name."""
81
+ for name, fn in SYNTAX_REPAIRS:
82
+ fixed = fn(child)
83
+ if fixed is not None and _parses(fixed):
84
+ return fixed, name
85
+ code, names = child, []
86
+ for name, fn in SYNTAX_REPAIRS:
87
+ fixed = fn(code)
88
+ if fixed is not None:
89
+ code, names = fixed, names + [name]
90
+ if _parses(code):
91
+ return code, "+".join(names)
92
+ return None
93
+
94
+
95
+ _POOL_TYPES = {"multiprocessing.Pool", "multiprocessing.pool.Pool",
96
+ "concurrent.futures.ProcessPoolExecutor",
97
+ "concurrent.futures.process.ProcessPoolExecutor"}
98
+ _PROCESS_TYPES = {"multiprocessing.Process", "multiprocessing.context.Process",
99
+ "multiprocessing.context.SpawnProcess", "multiprocessing.context.ForkServerProcess"}
100
+ _POOL_METHODS = {"map", "imap", "imap_unordered", "starmap", "apply", "apply_async",
101
+ "map_async", "starmap_async", "submit"}
102
+
103
+
104
+ @dataclass
105
+ class _Scope:
106
+ parent: _Scope | None = None
107
+ kind: str = "module"
108
+ bindings: dict = field(default_factory=dict)
109
+ redirects: dict = field(default_factory=dict)
110
+
111
+ def bind(self, name, value):
112
+ scope = self.redirects.get(name, self)
113
+ scope.bindings.setdefault(name, []).append(value)
114
+
115
+
116
+ class _ResourceScan(ast.NodeVisitor):
117
+ """Resolve only unambiguous imports/aliases, respecting lexical shadowing.
118
+
119
+ Bindings are collected before calls are inspected, so an import below a
120
+ function definition and aliases such as ``P = mp.Pool`` work. An ambiguous
121
+ reassignment is deliberately left for the evaluator, not called fatal here.
122
+ """
123
+ def __init__(self):
124
+ self.scope = _Scope()
125
+ self.calls = []
126
+ self.parents = {}
127
+ self._visiting = None
128
+
129
+ def visit(self, node):
130
+ parent = self._visiting
131
+ self.parents[id(node)] = parent
132
+ self._visiting = node
133
+ try:
134
+ return super().visit(node)
135
+ finally:
136
+ self._visiting = parent
137
+
138
+ def _target(self, target, value=None):
139
+ if isinstance(target, ast.Name):
140
+ self.scope.bind(target.id, value)
141
+ elif isinstance(target, (ast.Tuple, ast.List)):
142
+ for item in target.elts:
143
+ self._target(item)
144
+ elif isinstance(target, ast.Starred):
145
+ self._target(target.value)
146
+
147
+ def visit_Name(self, node):
148
+ if isinstance(node.ctx, (ast.Store, ast.Del)):
149
+ self._target(node)
150
+
151
+ def visit_Import(self, node):
152
+ for alias in node.names:
153
+ self.scope.bind(alias.asname or alias.name.split(".")[0],
154
+ ("path", alias.name if alias.asname else alias.name.split(".")[0]))
155
+
156
+ def visit_ImportFrom(self, node):
157
+ for alias in node.names:
158
+ self.scope.bind(alias.asname or alias.name,
159
+ ("path", f"{node.module}.{alias.name}") if not node.level else None)
160
+
161
+ def visit_Assign(self, node):
162
+ self.visit(node.value)
163
+ for target in node.targets:
164
+ self._target(target, ("expr", node.value, self.scope))
165
+
166
+ def visit_AnnAssign(self, node):
167
+ if node.value is not None:
168
+ self.visit(node.value)
169
+ self._target(node.target, ("expr", node.value, self.scope))
170
+
171
+ def visit_NamedExpr(self, node):
172
+ self.visit(node.value)
173
+ self._target(node.target, ("expr", node.value, self.scope))
174
+
175
+ def visit_With(self, node):
176
+ for item in node.items:
177
+ self.visit(item.context_expr)
178
+ self._target(item.optional_vars, ("expr", item.context_expr, self.scope))
179
+ for statement in node.body:
180
+ self.visit(statement)
181
+
182
+ visit_AsyncWith = visit_With
183
+
184
+ def visit_Global(self, node):
185
+ root = self.scope
186
+ while root.parent is not None:
187
+ root = root.parent
188
+ self.scope.redirects.update((name, root) for name in node.names)
189
+
190
+ def visit_Nonlocal(self, node):
191
+ for name in node.names:
192
+ outer = self.scope.parent
193
+ while outer is not None and outer.parent is not None:
194
+ if name in outer.bindings:
195
+ self.scope.redirects[name] = outer
196
+ break
197
+ outer = outer.parent
198
+
199
+ def _nested(self, node, kind):
200
+ enclosing = self.scope
201
+ parent = enclosing
202
+ while parent.kind == "class":
203
+ parent = parent.parent
204
+ self.scope = _Scope(parent, kind)
205
+ if kind == "function":
206
+ args = node.args
207
+ for arg in [*args.posonlyargs, *args.args, *args.kwonlyargs, args.vararg, args.kwarg]:
208
+ if arg is not None:
209
+ self.scope.bind(arg.arg, None)
210
+ body = node.body if isinstance(node.body, list) else [node.body]
211
+ for statement in body:
212
+ self.visit(statement)
213
+ self.scope = enclosing
214
+
215
+ def visit_FunctionDef(self, node):
216
+ outer = self.scope
217
+ while outer.kind == "class":
218
+ outer = outer.parent
219
+ self.scope.bind(node.name, ("local", "function") if outer.kind == "function" else None)
220
+ for expression in [*node.decorator_list, *node.args.defaults, *node.args.kw_defaults]:
221
+ if expression is not None:
222
+ self.visit(expression)
223
+ self._nested(node, "function")
224
+
225
+ visit_AsyncFunctionDef = visit_FunctionDef
226
+
227
+ def visit_Lambda(self, node):
228
+ for expression in [*node.args.defaults, *node.args.kw_defaults]:
229
+ if expression is not None:
230
+ self.visit(expression)
231
+ self._nested(node, "function")
232
+
233
+ def visit_ClassDef(self, node):
234
+ self.scope.bind(node.name, None)
235
+ for expression in [*node.decorator_list, *node.bases, *(k.value for k in node.keywords)]:
236
+ self.visit(expression)
237
+ self._nested(node, "class")
238
+
239
+ def _comprehension(self, node):
240
+ self.visit(node.generators[0].iter)
241
+ enclosing = self.scope
242
+ parent = enclosing.parent if enclosing.kind == "class" else enclosing
243
+ self.scope = _Scope(parent, "comprehension")
244
+ for i, generator in enumerate(node.generators):
245
+ if i:
246
+ self.visit(generator.iter)
247
+ self._target(generator.target)
248
+ for condition in generator.ifs:
249
+ self.visit(condition)
250
+ for expression in ([node.key, node.value] if isinstance(node, ast.DictComp) else [node.elt]):
251
+ self.visit(expression)
252
+ self.scope = enclosing
253
+
254
+ visit_ListComp = visit_SetComp = visit_DictComp = visit_GeneratorExp = _comprehension
255
+
256
+ def visit_Call(self, node):
257
+ self.calls.append((node, self.scope))
258
+ self.generic_visit(node)
259
+
260
+
261
+ def _resolve_resource(expr, scope, seen=frozenset()):
262
+ if isinstance(expr, ast.Lambda):
263
+ return "local", "lambda"
264
+ if isinstance(expr, ast.Name):
265
+ while scope is not None:
266
+ scope = scope.redirects.get(expr.id, scope)
267
+ if expr.id in scope.bindings:
268
+ key = (id(scope), expr.id)
269
+ if key in seen:
270
+ return None
271
+ values = set()
272
+ for binding in scope.bindings[expr.id]:
273
+ value = (_resolve_resource(binding[1], binding[2], seen | {key})
274
+ if binding is not None and binding[0] == "expr" else binding)
275
+ values.add(value)
276
+ return next(iter(values)) if len(values) == 1 else None
277
+ scope = scope.parent
278
+ elif isinstance(expr, ast.Attribute):
279
+ base = _resolve_resource(expr.value, scope, seen)
280
+ if base is not None and base[0] == "path":
281
+ return "path", f"{base[1]}.{expr.attr}"
282
+ if base == ("pool", "") and expr.attr in _POOL_METHODS:
283
+ return "worker_call", expr.attr
284
+ if base is not None and base[0] == "context":
285
+ if expr.attr == "Pool":
286
+ return "path", "multiprocessing.Pool"
287
+ if expr.attr == "Process":
288
+ return "process", base[1]
289
+ elif isinstance(expr, ast.Call):
290
+ callee = _resolve_resource(expr.func, scope, seen)
291
+ if callee is not None and callee[0] == "path":
292
+ if callee[1] in _POOL_TYPES:
293
+ return "pool", ""
294
+ if callee[1] == "multiprocessing.get_context":
295
+ method = next((kw.value for kw in expr.keywords if kw.arg == "method"),
296
+ expr.args[0] if expr.args else None)
297
+ # Explicit fork does not pickle a Process target; pool submissions
298
+ # still pickle workers under every start method.
299
+ if method is None or isinstance(method, ast.Constant) and method.value is None:
300
+ return "context", "default"
301
+ return "context", method.value if isinstance(method, ast.Constant) else "unknown"
302
+ return None
303
+
304
+
305
+ def _statement_block(node, parents):
306
+ while node is not None and not isinstance(node, ast.stmt):
307
+ node = parents.get(id(node))
308
+ parent = parents.get(id(node))
309
+ if parent is not None:
310
+ for field_name, value in ast.iter_fields(parent):
311
+ if isinstance(value, list) and any(item is node for item in value):
312
+ return (id(parent), field_name), node
313
+ return None, node
314
+
315
+
316
+ def _guaranteed_fork(node, scope, scan):
317
+ """Only a preceding unconditional setter in this same block proves fork.
318
+
319
+ Setters in another function or a conditional branch do not establish the
320
+ runtime context here. A later competing/unknown setter removes the proof.
321
+ Pool workers and explicit spawn/forkserver contexts still require pickling.
322
+ """
323
+ prior = [(call, call_scope) for call, call_scope in scan.calls
324
+ if (call.lineno, call.col_offset) < (node.lineno, node.col_offset)
325
+ and _resolve_resource(call.func, call_scope) == ("path", "multiprocessing.set_start_method")]
326
+ if not prior:
327
+ return False
328
+ setter, setter_scope = max(prior, key=lambda item: (item[0].lineno, item[0].col_offset))
329
+ if setter_scope is not scope:
330
+ return False
331
+ setter_block, statement = _statement_block(setter, scan.parents)
332
+ block, _ = _statement_block(node, scan.parents)
333
+ if (setter_block is None or setter_block != block
334
+ or not isinstance(statement, ast.Expr) or statement.value is not setter):
335
+ return False
336
+ # Default Process chooses its context at start(), not at construction. A
337
+ # later conflicting setter can therefore invalidate a previously built one.
338
+ for call, call_scope in scan.calls:
339
+ if call_scope is scope and (call.lineno, call.col_offset) > (setter.lineno, setter.col_offset) \
340
+ and _resolve_resource(call.func, call_scope) == ("path", "multiprocessing.set_start_method"):
341
+ later_method = next((kw.value for kw in call.keywords if kw.arg == "method"),
342
+ call.args[0] if call.args else None)
343
+ if not isinstance(later_method, ast.Constant) or later_method.value != "fork":
344
+ return False
345
+ # An arbitrary intervening helper could change the process-wide method.
346
+ # Permit ordinary multiprocessing setup, but do not guess through user calls.
347
+ setup_calls = {f"multiprocessing.{name}" for name in (
348
+ "Queue", "SimpleQueue", "Pipe", "Lock", "RLock", "Semaphore",
349
+ "BoundedSemaphore", "Condition", "Event", "Value", "Array",
350
+ "RawValue", "RawArray", "get_context")}
351
+ for call, call_scope in scan.calls:
352
+ if (call_scope is scope
353
+ and (setter.lineno, setter.col_offset) < (call.lineno, call.col_offset)
354
+ < (node.lineno, node.col_offset)):
355
+ callee = _resolve_resource(call.func, call_scope)
356
+ if callee is None or callee[0] != "path" or callee[1] not in setup_calls:
357
+ return False
358
+ method = next((kw.value for kw in setter.keywords if kw.arg == "method"),
359
+ setter.args[0] if setter.args else None)
360
+ return isinstance(method, ast.Constant) and method.value == "fork"
361
+
362
+
363
+ def _resource_fatal(tree: ast.AST) -> str | None:
364
+ """Reject a local worker only when it is handed to a known process API."""
365
+ scan = _ResourceScan()
366
+ scan.visit(tree)
367
+ for node, scope in scan.calls:
368
+ callee = _resolve_resource(node.func, scope)
369
+ if callee is None:
370
+ continue
371
+ if callee[0] == "worker_call":
372
+ index, keyword = 0, "fn" if callee[1] == "submit" else "func"
373
+ elif callee[0] == "process":
374
+ if callee[1] == "fork" or callee[1] == "default" and _guaranteed_fork(node, scope, scan):
375
+ continue
376
+ index, keyword = 1, "target"
377
+ elif callee[0] == "path" and callee[1] in _PROCESS_TYPES:
378
+ if callee[1] in {"multiprocessing.Process", "multiprocessing.context.Process"} \
379
+ and _guaranteed_fork(node, scope, scan):
380
+ continue
381
+ index, keyword = 1, "target"
382
+ else:
383
+ continue
384
+ worker = next((kw.value for kw in node.keywords if kw.arg == keyword),
385
+ node.args[index] if len(node.args) > index else None)
386
+ resolved = _resolve_resource(worker, scope)
387
+ if resolved is not None and resolved[0] == "local":
388
+ return (f"multiprocessing cannot pickle a {resolved[1]} worker defined locally; "
389
+ "define the worker at module level or drop multiprocessing")
390
+ return None
391
+
392
+
393
+ def precheck(child: str) -> Violation | None:
394
+ """Pre-eval classification: empty / syntax / resource, in priority order.
395
+ Returns None when the candidate may proceed to graft + duplicate check."""
396
+ if not child.strip():
397
+ return Violation("empty")
398
+ try:
399
+ tree = ast.parse(child)
400
+ except SyntaxError as e:
401
+ return Violation("syntax", f"{e.msg} (line {e.lineno})")
402
+ res = _resource_fatal(tree)
403
+ if res is not None:
404
+ return Violation("resource", res)
405
+ return None
406
+
407
+
408
+ # Declarative repair table: kind -> mechanical repair fn (None => no mechanical
409
+ # fix, resample instead). `interface` is handled by graft in validation, not here;
410
+ # `duplicate`/`empty` have no mechanical repair. This dict is the policy surface a
411
+ # learned RepairPolicy will consume.
412
+ REPAIR_TABLE = {
413
+ "syntax": _syntax_repair,
414
+ "resource": None,
415
+ "empty": None,
416
+ "duplicate": None,
417
+ }
418
+
419
+
420
+ def mechanical_repair(v: Violation, child: str) -> tuple[str, str] | None:
421
+ """Apply the declared mechanical repair for a violation: (fixed code, repair name) or None."""
422
+ fn = REPAIR_TABLE.get(v.kind)
423
+ return fn(child) if fn is not None else None
424
+
425
+
426
+ # Backward-compatible facade: the old pre_eval_gate returned a reason string.
427
+ def pre_eval_gate(child: str) -> str | None:
428
+ v = precheck(child)
429
+ if v is None or v.kind == "empty":
430
+ return None
431
+ return f"{v.kind} error before eval: {v.detail}" if v.kind == "syntax" else v.detail
@@ -0,0 +1,69 @@
1
+ """Audited new search from a checkpoint's best source, with a fresh evaluation.
2
+
3
+ This transfers code, not scores, lessons, budgets, or a stopped research state.
4
+ The source checkpoint and journal stay unchanged.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import json
10
+ import math
11
+ from pathlib import Path
12
+
13
+ from .run_lock import RunDirectoryLock
14
+
15
+ SCHEMA = 'sciel-warm-start/1'
16
+
17
+
18
+ def validate_warm_start(value):
19
+ if not isinstance(value, dict) or set(value) != {'schema', 'source', 'source_sha256', 'parent'}:
20
+ raise ValueError('invalid warm_start fields')
21
+ source = value['source']
22
+ if (value['schema'] != SCHEMA or not isinstance(source, str) or not source.strip()
23
+ or hashlib.sha256(source.encode()).hexdigest() != value['source_sha256']):
24
+ raise ValueError('warm_start source identity differs')
25
+ parent = value['parent']
26
+ if not isinstance(parent, dict) or not all(parent.get(key) for key in (
27
+ 'run_id', 'checkpoint_sha256', 'journal_sha256', 'task', 'task_hash', 'program_id')):
28
+ raise ValueError('warm_start parent provenance is missing')
29
+ return value
30
+
31
+
32
+ def from_run(directory, task):
33
+ directory = Path(directory).resolve()
34
+ # Serialize against a running writer while taking the immutable source view.
35
+ lock = RunDirectoryLock(directory)
36
+ try:
37
+ raw = (directory / 'checkpoint.json').read_bytes()
38
+ saved = json.loads(raw)
39
+ provenance = saved.get('provenance') or {}
40
+ if provenance.get('schema') != 'sciel-checkpoint-provenance/1':
41
+ raise ValueError('warm start requires a checkpoint with bound provenance')
42
+ identity = saved.get('identity') or {}
43
+ if identity.get('task') != task:
44
+ raise ValueError('warm start task name differs')
45
+ from .journal_anchor import assert_no_uncheckpointed_research
46
+ assert_no_uncheckpointed_research(directory / 'sciel_events.jsonl', provenance.get('journal_anchor'))
47
+ journal = (directory / 'sciel_events.jsonl').read_bytes()
48
+ rows = [json.loads(line) for line in journal.splitlines()]
49
+ checkpoint_sha = hashlib.sha256(raw).hexdigest()
50
+ if not any(row.get('event') == 'checkpoint'
51
+ and row.get('checkpoint_sha256') == checkpoint_sha
52
+ and row.get('checkpoint_id') == provenance.get('checkpoint_id') for row in rows):
53
+ raise ValueError('warm start checkpoint digest is not recorded in the journal')
54
+ best = saved['db']['pop_best_id']
55
+ program = next(p for p in saved['db']['programs'] if p['id'] == best)
56
+ if type(program['score']) not in (int, float) or not math.isfinite(program['score']):
57
+ raise ValueError('warm start has no finite best score')
58
+ source = program['code']
59
+ value = dict(schema=SCHEMA, source=source,
60
+ source_sha256=hashlib.sha256(source.encode()).hexdigest(),
61
+ parent=dict(run_id=provenance['run_id'], path=str(directory),
62
+ checkpoint_sha256=checkpoint_sha, journal_sha256=hashlib.sha256(journal).hexdigest(),
63
+ task=task, task_hash=identity['task_hash'], program_id=best,
64
+ previous_score=program['score'], previous_known_cost=saved.get('cost_total'),
65
+ stopped_reason=(saved.get('research') or {}).get('stopped_reason'),
66
+ transfer='source_only_fresh_evaluation'))
67
+ return validate_warm_start(value)
68
+ finally:
69
+ lock.close()