proef 0.2.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 (200) hide show
  1. proef/__init__.py +25 -0
  2. proef/acquisition.py +244 -0
  3. proef/ad.py +159 -0
  4. proef/adapters/__init__.py +0 -0
  5. proef/adapters/admet.py +196 -0
  6. proef/adapters/bio/__init__.py +0 -0
  7. proef/adapters/bio/rdkit_ops.py +52 -0
  8. proef/adapters/bio/safety_rules.json +146 -0
  9. proef/adapters/bio/seq_alerts.py +79 -0
  10. proef/adapters/bio/structure_score.py +85 -0
  11. proef/adapters/bio/tox_alerts.py +99 -0
  12. proef/adapters/data/__init__.py +0 -0
  13. proef/adapters/data/admet.py +62 -0
  14. proef/adapters/data/chembl.py +110 -0
  15. proef/adapters/data/frozen/admet/MANIFEST.json +48 -0
  16. proef/adapters/data/frozen/admet/bbb_martins/test.csv +407 -0
  17. proef/adapters/data/frozen/admet/bbb_martins/train_val.csv +1625 -0
  18. proef/adapters/data/frozen/admet/caco2_wang/test.csv +183 -0
  19. proef/adapters/data/frozen/admet/caco2_wang/train_val.csv +729 -0
  20. proef/adapters/data/frozen/admet/hia_hou/test.csv +118 -0
  21. proef/adapters/data/frozen/admet/hia_hou/train_val.csv +462 -0
  22. proef/adapters/data/moleculenet.py +60 -0
  23. proef/adapters/databases/__init__.py +0 -0
  24. proef/adapters/databases/chembl_gates.py +121 -0
  25. proef/adapters/databases/chembl_lookup.py +35 -0
  26. proef/adapters/databases/open_targets.py +102 -0
  27. proef/adapters/databases/pubmed.py +94 -0
  28. proef/adapters/devices/__init__.py +0 -0
  29. proef/adapters/devices/ezo_ph.py +251 -0
  30. proef/adapters/devices/hcs_microscope.py +143 -0
  31. proef/adapters/devices/lcms.py +123 -0
  32. proef/adapters/devices/scheduler.py +84 -0
  33. proef/adapters/devices/sila2.py +134 -0
  34. proef/adapters/genomics/alphagenome.py +146 -0
  35. proef/adapters/lab/__init__.py +0 -0
  36. proef/adapters/lab/bioprocess.py +32 -0
  37. proef/adapters/lab/devices.py +170 -0
  38. proef/adapters/lab/imaging.py +226 -0
  39. proef/adapters/lab/mhs_driver.py +124 -0
  40. proef/adapters/lab/opentrons.py +222 -0
  41. proef/adapters/lab/ot2_sim.py +174 -0
  42. proef/adapters/lab/plate_reader_share.py +108 -0
  43. proef/adapters/lab/protein_design.py +199 -0
  44. proef/adapters/lab/recording.py +119 -0
  45. proef/adapters/lab/replay.py +107 -0
  46. proef/adapters/lab/simulator.py +282 -0
  47. proef/adapters/lab/synthesis.py +92 -0
  48. proef/adapters/models/__init__.py +0 -0
  49. proef/adapters/models/anthropic_provider.py +157 -0
  50. proef/adapters/models/assayloop_ranker.py +67 -0
  51. proef/adapters/models/from_env.py +93 -0
  52. proef/adapters/models/gp_policy.py +93 -0
  53. proef/adapters/models/gp_policy_gp.py +36 -0
  54. proef/adapters/models/llm_policy.py +187 -0
  55. proef/adapters/models/openai_compat.py +150 -0
  56. proef/adapters/models/sklearn_policy.py +65 -0
  57. proef/adapters/retrosynthesis.py +247 -0
  58. proef/adapters/sandbox/__init__.py +20 -0
  59. proef/adapters/sandbox/agentenv.py +145 -0
  60. proef/adapters/sandbox/docker.py +217 -0
  61. proef/adapters/sandbox/local.py +164 -0
  62. proef/adapters/sandbox/opensandbox.py +122 -0
  63. proef/adapters/store/__init__.py +0 -0
  64. proef/adapters/store/sqlite.py +207 -0
  65. proef/adaptive.py +108 -0
  66. proef/advisory.py +76 -0
  67. proef/analysis_profiles/__init__.py +8 -0
  68. proef/analysis_profiles/measurements.py +266 -0
  69. proef/analysis_profiles/plate_assay.py +316 -0
  70. proef/analysis_report.py +195 -0
  71. proef/analysis_store.py +183 -0
  72. proef/anchor.py +154 -0
  73. proef/api/app.py +107 -0
  74. proef/api/launch.py +170 -0
  75. proef/api/v1/__init__.py +29 -0
  76. proef/api/v1/analyses.py +367 -0
  77. proef/api/v1/campaigns.py +802 -0
  78. proef/api/v1/deps.py +10 -0
  79. proef/api/v1/evals.py +16 -0
  80. proef/api/v1/evidence.py +132 -0
  81. proef/api/v1/governance.py +35 -0
  82. proef/api/v1/inbox.py +119 -0
  83. proef/api/v1/lab.py +110 -0
  84. proef/api/v1/pauses.py +77 -0
  85. proef/api/v1/programs.py +397 -0
  86. proef/api/v1/results.py +147 -0
  87. proef/api/v1/schemas.py +932 -0
  88. proef/api/v1/system.py +79 -0
  89. proef/api/v1/trees.py +216 -0
  90. proef/api/wizard_sessions.py +253 -0
  91. proef/approvals.py +102 -0
  92. proef/assays/__init__.py +15 -0
  93. proef/assays/dls.py +114 -0
  94. proef/assays/dsf.py +81 -0
  95. proef/assays/elisa.py +58 -0
  96. proef/assays/properties.py +65 -0
  97. proef/assays/simulate.py +157 -0
  98. proef/audit.py +152 -0
  99. proef/autoloop.py +1620 -0
  100. proef/benchmark.py +442 -0
  101. proef/campaign_fsm.py +151 -0
  102. proef/citations.py +141 -0
  103. proef/cli.py +1249 -0
  104. proef/connect.py +74 -0
  105. proef/core/__init__.py +0 -0
  106. proef/core/contracts/__init__.py +35 -0
  107. proef/core/contracts/analysis.py +100 -0
  108. proef/core/contracts/models.py +395 -0
  109. proef/core/device_card.py +125 -0
  110. proef/core/hypothesis.py +720 -0
  111. proef/core/interfaces.py +164 -0
  112. proef/core/registry.py +123 -0
  113. proef/core/safety.py +324 -0
  114. proef/core/workflow.py +159 -0
  115. proef/critic.py +62 -0
  116. proef/demo.py +164 -0
  117. proef/derivation.py +128 -0
  118. proef/diary.py +301 -0
  119. proef/eln.py +87 -0
  120. proef/evals/__init__.py +1 -0
  121. proef/evals/hallucination.py +86 -0
  122. proef/evals/harness.py +358 -0
  123. proef/evals/orchestration.py +254 -0
  124. proef/evals/tasks.py +1010 -0
  125. proef/evals/toolcalls.py +425 -0
  126. proef/experiment.py +172 -0
  127. proef/experiment_analysis.py +114 -0
  128. proef/experiments/__init__.py +0 -0
  129. proef/experiments/grounding_exp.py +689 -0
  130. proef/figures.py +218 -0
  131. proef/fitting.py +309 -0
  132. proef/fixtures.py +140 -0
  133. proef/flywheel.py +125 -0
  134. proef/followup.py +126 -0
  135. proef/governance.py +290 -0
  136. proef/groundedness.py +361 -0
  137. proef/grounding.py +202 -0
  138. proef/hypothesis_agent.py +369 -0
  139. proef/ingest.py +157 -0
  140. proef/instruments.json +173 -0
  141. proef/interpret.py +95 -0
  142. proef/kinetic.py +102 -0
  143. proef/labread/__init__.py +45 -0
  144. proef/labread/analysis.py +428 -0
  145. proef/labread/common.py +153 -0
  146. proef/labread/formats.py +190 -0
  147. proef/labread/layout.py +168 -0
  148. proef/labread/pubchem.py +179 -0
  149. proef/labselect.py +431 -0
  150. proef/materials.py +140 -0
  151. proef/mcp_instrument.py +396 -0
  152. proef/mcp_server.py +283 -0
  153. proef/modality.py +111 -0
  154. proef/model_guard.py +245 -0
  155. proef/output_blocks.py +183 -0
  156. proef/paths.py +32 -0
  157. proef/physfail.py +55 -0
  158. proef/plan.py +160 -0
  159. proef/plots.py +123 -0
  160. proef/predictors.py +217 -0
  161. proef/probes.py +79 -0
  162. proef/problem_tree.py +581 -0
  163. proef/program.py +308 -0
  164. proef/protocol_design.py +42 -0
  165. proef/proxy.py +78 -0
  166. proef/readiness.py +259 -0
  167. proef/reliability.py +49 -0
  168. proef/report.py +117 -0
  169. proef/reproduce.py +310 -0
  170. proef/reviewer.py +254 -0
  171. proef/sandbox_session.py +247 -0
  172. proef/sandboxd.py +109 -0
  173. proef/scaffold.py +195 -0
  174. proef/series.py +327 -0
  175. proef/skills.py +203 -0
  176. proef/sweep.py +83 -0
  177. proef/taste.py +177 -0
  178. proef/templates/confirmatory-followup.json +34 -0
  179. proef/templates/dose-response-screen.json +39 -0
  180. proef/templates/sar-exploration.json +38 -0
  181. proef/templates.py +124 -0
  182. proef/toolkit.py +433 -0
  183. proef/toolloop.py +133 -0
  184. proef/tools.py +441 -0
  185. proef/tpp.py +185 -0
  186. proef/views/__init__.py +14 -0
  187. proef/views/counts.py +102 -0
  188. proef/views/experiment.py +154 -0
  189. proef/views/ids.py +49 -0
  190. proef/views/narrative.py +294 -0
  191. proef/views/pipeline.py +370 -0
  192. proef/vision.py +165 -0
  193. proef/watch.py +790 -0
  194. proef/wizard_chain.py +25 -0
  195. proef/wizard_store.py +373 -0
  196. proef-0.2.0.dist-info/METADATA +662 -0
  197. proef-0.2.0.dist-info/RECORD +200 -0
  198. proef-0.2.0.dist-info/WHEEL +4 -0
  199. proef-0.2.0.dist-info/entry_points.txt +14 -0
  200. proef-0.2.0.dist-info/licenses/LICENSE +202 -0
proef/problem_tree.py ADDED
@@ -0,0 +1,581 @@
1
+ """Problem trees — recursive decomposition with guardrails at every level.
2
+
3
+ A compound objective ("potent AND selective AND soluble") is not one
4
+ question; it is a tree of sub-problems, each with its own metric, gate,
5
+ hypothesis space, and slice of the experiment budget. Recursion is allowed
6
+ (any node may decompose further) but bounded: max_depth, max_children,
7
+ max_nodes, and a run budget that allocates DOWN the tree — a leaf can never
8
+ spend more than it was given, so decomposition cannot silently multiply
9
+ experiments.
10
+
11
+ Verdicts roll UP: a node is achieved only when its required children are;
12
+ the roll-up itself is a provenance event, so "how did we conclude the
13
+ program is working?" is answerable from the chain.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import time
19
+ import uuid
20
+ from typing import Any
21
+
22
+ from pydantic import BaseModel, Field
23
+
24
+
25
+ class TreeLimits(BaseModel):
26
+ """The anti-runaway guardrails. Every knob is configurable per plan."""
27
+ max_depth: int = 2 # root = 0
28
+ max_children: int = 4 # per node
29
+ max_nodes: int = 12 # whole tree
30
+ max_hypotheses_per_leaf: int = 4
31
+ k_per_leaf: int = 2 # lab slots per leaf campaign
32
+
33
+
34
+ class ProblemNode(BaseModel):
35
+ id: str = Field(default_factory=lambda: f"sp-{uuid.uuid4().hex[:6]}")
36
+ parent: str | None = None
37
+ objective: str
38
+ metric: str | None = None # e.g. ic50_um, fold_change
39
+ direction: str = "min"
40
+ gate: float | None = None
41
+ priority: float = 1.0 # budget weight among siblings
42
+ required: bool = True
43
+ rationale: str = ""
44
+ status: str = "open" # open|achieved|partial|failed|inconclusive
45
+ verdicts: dict[str, str] = Field(default_factory=dict)
46
+
47
+ def branch(self, root_id: str) -> str:
48
+ return f"problem/{root_id}/{self.id}"
49
+
50
+
51
+ class ProblemTree(BaseModel):
52
+ root: ProblemNode
53
+ nodes: dict[str, ProblemNode] # includes root, keyed by id
54
+ limits: TreeLimits = Field(default_factory=TreeLimits)
55
+ run_budget: int = 20 # total lab runs across all leaves
56
+ modality: str = "" # small molecule | biologic | ... free text
57
+
58
+ # ------------------------------------------------------------ building
59
+
60
+ @classmethod
61
+ def create(cls, objective: str, *, limits: TreeLimits | None = None,
62
+ run_budget: int = 20, metric: str | None = None,
63
+ gate: float | None = None,
64
+ modality: str = "") -> "ProblemTree":
65
+ root = ProblemNode(objective=objective, metric=metric, gate=gate)
66
+ return cls(root=root, nodes={root.id: root},
67
+ limits=limits or TreeLimits(), run_budget=run_budget,
68
+ modality=modality)
69
+
70
+ def depth_of(self, node_id: str) -> int:
71
+ d, cur = 0, self.nodes[node_id]
72
+ while cur.parent:
73
+ d += 1
74
+ cur = self.nodes[cur.parent]
75
+ return d
76
+
77
+ def children(self, node_id: str) -> list[ProblemNode]:
78
+ return [n for n in self.nodes.values() if n.parent == node_id]
79
+
80
+ def add(self, parent_id: str, **spec: Any) -> ProblemNode:
81
+ """Guardrailed growth: depth, breadth and total-node caps, each
82
+ refusal explicit (mirrors the hypothesis-budget pattern)."""
83
+ parent = self.nodes[parent_id]
84
+ if self.depth_of(parent_id) + 1 > self.limits.max_depth:
85
+ raise ValueError(
86
+ f"max_depth={self.limits.max_depth}: '{parent.objective[:40]}'"
87
+ " cannot decompose further (recorded, not silently dropped)")
88
+ if len(self.children(parent_id)) >= self.limits.max_children:
89
+ raise ValueError(
90
+ f"max_children={self.limits.max_children} reached under "
91
+ f"'{parent.objective[:40]}'")
92
+ if len(self.nodes) >= self.limits.max_nodes:
93
+ raise ValueError(
94
+ f"max_nodes={self.limits.max_nodes} — tree is full")
95
+ node = ProblemNode(parent=parent_id, **spec)
96
+ self.nodes[node.id] = node
97
+ return node
98
+
99
+ def leaves(self) -> list[ProblemNode]:
100
+ return [n for n in self.nodes.values() if not self.children(n.id)]
101
+
102
+ # ------------------------------------------------------------ budgets
103
+
104
+ def allocation(self) -> dict[str, int]:
105
+ """Hierarchical run budget: the root's budget flows down the tree —
106
+ each intermediate node splits its OWN slice among its children by
107
+ priority weight, so a branch's share is protected from siblings
108
+ regardless of depth (a deep subtree cannot soak another branch's
109
+ budget). Leaves end up with concrete budgets; a floor of 2 keeps
110
+ any leaf meaningful; totals never exceed run_budget unless the
111
+ floors alone demand more."""
112
+ out: dict[str, int] = {}
113
+ if self.run_budget <= 0 or not self.leaves():
114
+ return out
115
+
116
+ def share(budget: int, nid: str) -> None:
117
+ kids = self.children(nid)
118
+ if not kids:
119
+ out[nid] = budget
120
+ return
121
+ weights = [max(0.1, k.priority) for k in kids]
122
+ total_w = sum(weights)
123
+ alloc = []
124
+ for k, w in zip(kids, weights):
125
+ floor = 0 if self.children(k.id) else 2
126
+ alloc.append(max(floor, int(budget * w / total_w)))
127
+ # trim to the parent's slice, largest first, honoring floors
128
+ while sum(alloc) > budget:
129
+ idx = max(range(len(kids)),
130
+ key=lambda i: alloc[i]
131
+ - (0 if self.children(kids[i].id) else 2))
132
+ floor = 0 if self.children(kids[idx].id) else 2
133
+ if alloc[idx] <= floor:
134
+ break
135
+ alloc[idx] -= 1
136
+ for k, a in zip(kids, alloc):
137
+ share(a, k.id)
138
+
139
+ share(self.run_budget, self.root.id)
140
+ return out
141
+
142
+ def subtree_leaves(self, nid: str) -> list[ProblemNode]:
143
+ """Leaves beneath a node (the node itself if it is a leaf)."""
144
+ kids = self.children(nid)
145
+ if not kids:
146
+ return [self.nodes[nid]]
147
+ out: list[ProblemNode] = []
148
+ for k in kids:
149
+ out.extend(self.subtree_leaves(k.id))
150
+ return out
151
+
152
+ # ------------------------------------------------------------ roll-up
153
+
154
+ def set_leaf_status(self, leaf_id: str, statuses: dict[str, str]) -> None:
155
+ """Leaf statuses: achieved | partial | failed | inconclusive.
156
+ ABSTENTION IS NOT FAILURE: a leaf whose candidates all abstained
157
+ (borderline CIs) is inconclusive — evidence that neither supports
158
+ nor refutes — never a false 'failed' that rolls up as refutation."""
159
+ node = self.nodes[leaf_id]
160
+ node.verdicts = dict(statuses)
161
+ vals = set(statuses.values())
162
+ hit = vals & {"validated", "confirmed"}
163
+ miss = vals & {"invalidated", "refuted"}
164
+ if not vals:
165
+ node.status = "inconclusive"
166
+ elif hit and hit <= {"confirmed"} and not miss:
167
+ node.status = "achieved"
168
+ elif hit and not miss:
169
+ # hits exist but some are preliminary (validated, unconfirmed)
170
+ node.status = "achieved" if vals <= {"validated", "confirmed"} \
171
+ else "partial"
172
+ elif hit:
173
+ node.status = "partial"
174
+ elif miss and vals <= {"invalidated", "refuted"}:
175
+ node.status = "failed" # every judged candidate was refuted
176
+ else: # refuted mixed with abstained: not enough to call the leaf failed
177
+ node.status = "inconclusive"
178
+
179
+ def rollup(self) -> dict[str, str]:
180
+ """Bottom-up: a node is achieved iff all required children are."""
181
+ out: dict[str, str] = {}
182
+
183
+ def resolve(nid: str) -> str:
184
+ n = self.nodes[nid]
185
+ kids = self.children(nid)
186
+ if not kids:
187
+ out[nid] = n.status
188
+ return n.status
189
+ kid_states = [resolve(k.id) for k in kids]
190
+ req = [s for k, s in zip(kids, kid_states) if k.required]
191
+ if req and all(s == "achieved" for s in req):
192
+ n.status = "achieved"
193
+ elif any(s == "failed" for s in req):
194
+ n.status = "partial" if any(
195
+ s == "achieved" for s in req) else "failed"
196
+ elif any(s == "partial" for s in req):
197
+ n.status = "partial"
198
+ elif any(s == "inconclusive" for s in req):
199
+ # nothing failed: abstaining evidence is undecided, not
200
+ # refutation — but a mix of achieved + abstained is
201
+ # (partially) earned
202
+ n.status = "partial" if any(
203
+ s == "achieved" for s in req) else "inconclusive"
204
+ else:
205
+ n.status = "partial"
206
+ out[nid] = n.status
207
+ return n.status
208
+
209
+ resolve(self.root.id)
210
+ return out
211
+
212
+ # ------------------------------------------------------------ display
213
+
214
+ def render(self) -> str:
215
+ lines = []
216
+
217
+ def walk(nid: str, indent: int) -> None:
218
+ n = self.nodes[nid]
219
+ alloc = self.allocation().get(nid)
220
+ gtxt = ""
221
+ if n.gate is not None and n.metric:
222
+ op = "≤" if n.direction == "min" else "≥"
223
+ gtxt = f" [{n.metric} {op} {n.gate:g}]"
224
+ mark = {"open": "○", "achieved": "✅", "partial": "◐",
225
+ "failed": "❌", "inconclusive": "∅",
226
+ "in lab": "🔬"}.get(n.status, "○")
227
+ budget = f" · {alloc} runs" if alloc is not None else ""
228
+ lines.append(" " * indent + f"{mark} {n.objective[:60]}{gtxt}"
229
+ + (f" (p={n.priority:g}){budget}"))
230
+ for k in self.children(nid):
231
+ walk(k.id, indent + 1)
232
+
233
+ walk(self.root.id, 0)
234
+ return "\n".join(lines)
235
+
236
+
237
+ # ------------------------------------------------------------------ agent
238
+
239
+ DECOMPOSE_PROMPT = """You are the study director of a drug-discovery program.
240
+ Decompose this objective into independent, separately-testable SUB-PROBLEMS.
241
+
242
+ Objective: {objective}
243
+ Program context: {context}
244
+
245
+ Rules:
246
+ - At most {max_children} sub-problems. Fewer is better; only split what is
247
+ genuinely a distinct question with its own measurement.
248
+ - Each sub-problem: a one-line objective, the metric it is judged on
249
+ (e.g. ic50_um, selectivity_ratio, fold_change, solubility_uM), direction
250
+ ('min' lower-is-better / 'max'), a numeric gate, and a priority weight
251
+ (relative importance, any positive number).
252
+ - Do NOT propose experiments or hypotheses — only the decomposition.
253
+
254
+ Reply ONLY with JSON:
255
+ {{"sub_problems": [
256
+ {{"objective": "...", "metric": "...", "direction": "min|max",
257
+ "gate": 0.0, "priority": 1.0, "rationale": "why this is its own question"}}
258
+ ]}}"""
259
+
260
+ RECURSE_PROMPT = """You are the study director refining a problem tree.
261
+ Below are sub-problems of a program (index -> objective). A node stays a
262
+ leaf only if it is independently testable with ONE measurement. If a node
263
+ still hides two distinct questions, split it.
264
+
265
+ {sub_problems_json}
266
+
267
+ Guardrails: at most {max_children} children per node; prefer NOT to split.
268
+
269
+ Reply ONLY with JSON:
270
+ {{"splits": [
271
+ {{"index": 0,
272
+ "sub_problems": [
273
+ {{"objective": "...", "metric": "...", "direction": "min|max",
274
+ "gate": 0.0, "priority": 1.0}}
275
+ ]}}
276
+ ]}}
277
+ Include an entry ONLY for nodes that must split; omit the rest."""
278
+
279
+
280
+ def _recurse_decompose(tree: "ProblemTree", model: Any,
281
+ node_ids: list[str], depth: int, say: Any) -> list[str]:
282
+ """One level of second-pass decomposition: ask which nodes at this
283
+ depth are still composites and split them. Returns the new frontier.
284
+ Guardrail failures in add() are announced and skipped."""
285
+ if not node_ids:
286
+ return []
287
+ from proef.core.contracts import Envelope, ToolInvocation
288
+ listing = [{"index": i, "objective": tree.nodes[nid].objective}
289
+ for i, nid in enumerate(node_ids)]
290
+ prompt = RECURSE_PROMPT.format(
291
+ sub_problems_json=json.dumps(listing, indent=1),
292
+ max_children=tree.limits.max_children)
293
+ inv = ToolInvocation(envelope=Envelope(experiment_branch_id="plan"),
294
+ tool="c.fm.generate_molecules")
295
+ raw = model.generate(inv, prompt).output["text"]
296
+ import re
297
+ try:
298
+ doc = json.loads(re.search(r"\{.*\}", raw, re.S).group(0))
299
+ except Exception:
300
+ say("sub-decomposition: unparseable model reply — level stays flat")
301
+ return []
302
+ frontier: list[str] = []
303
+ for split in doc.get("splits", []):
304
+ try:
305
+ idx = int(split.get("index"))
306
+ parent = node_ids[idx]
307
+ except (TypeError, ValueError, IndexError):
308
+ continue
309
+ for s in (split.get("sub_problems") or [])[:tree.limits.max_children]:
310
+ try:
311
+ node = tree.add(parent,
312
+ objective=str(s.get("objective", ""))[:160],
313
+ metric=s.get("metric"),
314
+ direction="max" if s.get("direction") == "max"
315
+ else "min",
316
+ gate=_num(s.get("gate")),
317
+ priority=_num(s.get("priority"), 1.0) or 1.0)
318
+ frontier.append(node.id)
319
+ except Exception as exc: # guardrails: depth/nodes caps
320
+ say(f"sub-split rejected: {exc}")
321
+ return frontier
322
+
323
+
324
+ def decompose_with_agent(model: Any, objective: str, context: str = "",
325
+ limits: TreeLimits | None = None,
326
+ say: Any = None) -> ProblemTree:
327
+ """Agent-assisted decomposition, guardrailed: over-proposals are
328
+ truncated (and announced), never silently accepted."""
329
+ limits = limits or TreeLimits()
330
+ say = say or (lambda m: None)
331
+ from proef.core.contracts import Envelope, ToolInvocation
332
+ prompt = DECOMPOSE_PROMPT.format(objective=objective,
333
+ context=context or "-",
334
+ max_children=limits.max_children)
335
+ inv = ToolInvocation(envelope=Envelope(experiment_branch_id="plan"),
336
+ tool="c.fm.generate_molecules")
337
+ raw = model.generate(inv, prompt).output["text"]
338
+ import re
339
+ doc = json.loads(re.search(r"\{.*\}", raw, re.S).group(0))
340
+ subs = doc.get("sub_problems", [])
341
+ if len(subs) > limits.max_children:
342
+ say(f"model proposed {len(subs)} sub-problems; truncated to "
343
+ f"max_children={limits.max_children} (recorded)")
344
+ tree = ProblemTree.create(objective, limits=limits)
345
+ for s in subs[:limits.max_children]:
346
+ tree.add(tree.root.id, objective=str(s.get("objective", ""))[:160],
347
+ metric=s.get("metric"),
348
+ direction="max" if s.get("direction") == "max" else "min",
349
+ gate=_num(s.get("gate")),
350
+ priority=_num(s.get("priority"), 1.0) or 1.0,
351
+ rationale=str(s.get("rationale", ""))[:200])
352
+ # recursive second pass: ask which sub-problems are still composites
353
+ # (bounded by max_depth and max_nodes; a model that cannot answer the
354
+ # refinement prompt leaves the level flat)
355
+ frontier = [n.id for n in tree.children(tree.root.id)]
356
+ depth = 1
357
+ while model is not None and frontier and depth < limits.max_depth:
358
+ say(f"decompose: asking which of {len(frontier)} level-{depth} "
359
+ f"sub-problems are still composites...")
360
+ frontier = _recurse_decompose(tree, model, frontier, depth, say)
361
+ depth += 1
362
+ if model is not None and len(tree.nodes) > 1:
363
+ say(f"tree: {len(tree.nodes)} nodes · {len(tree.leaves())} leaves")
364
+ return tree
365
+
366
+
367
+ def _num(v: Any, default: float | None = None) -> float | None:
368
+ try:
369
+ return float(v)
370
+ except (TypeError, ValueError):
371
+ return default
372
+
373
+
374
+ # ------------------------------------------------------------------ execution
375
+
376
+ def default_hypotheses(tree: "ProblemTree", candidates: list[str]) -> dict[str, list]:
377
+ """Config-path hypothesis space: one claim per candidate per leaf,
378
+ phrased against that leaf's own gate."""
379
+ out: dict[str, list] = {}
380
+ for leaf in tree.leaves():
381
+ # per-leaf prefix: SOL-1 / PKA-1 ... so each sub-problem's
382
+ # hypotheses are distinct records, not clones of each other
383
+ tag = "".join(w[0] for w in leaf.objective.split()[:3]).upper()
384
+ specs = []
385
+ for i, c in enumerate(candidates, 1):
386
+ cid = f"{tag}-{i}"
387
+ pred = (f"{leaf.metric} "
388
+ f"{'<=' if leaf.direction == 'min' else '>='} "
389
+ f"{leaf.gate:g}" if leaf.gate is not None else "meets bar")
390
+ specs.append({
391
+ "statement": f"{cid} ({c}) — {leaf.objective} ({pred})",
392
+ "candidate": cid, "assay_type": "binding",
393
+ "metadata": {"source_candidate": c},
394
+ "predicted": pred,
395
+ "predicted_value": leaf.gate,
396
+ "family": leaf.id,
397
+ "rationale": leaf.rationale or ""})
398
+ for sp in specs:
399
+ sp.setdefault("metadata", {})
400
+ if tree.modality:
401
+ sp["metadata"].setdefault("modality", tree.modality)
402
+ out[leaf.id] = specs
403
+ return out
404
+
405
+
406
+ def _record_root(tree, store, root_branch: str, say) -> None:
407
+ """Root problem record (+ the program link when launched from one)."""
408
+ import os as _os
409
+
410
+ from proef.core.contracts import Envelope, EventType
411
+ from proef.core.interfaces import record_for, system_actor
412
+ # launched from a program (workbench dialog): link the tree root to
413
+ # it once, in provenance — the workspace nests on this record
414
+ _bn_prog = _os.environ.get("PROEF_PROGRAM")
415
+ if _bn_prog:
416
+ try:
417
+ from proef import program as _program
418
+ _program.record_launch(_bn_prog, tree.root.id,
419
+ tree.root.objective)
420
+ except Exception as exc:
421
+ say(f"warning: could not link tree {tree.root.id} to program "
422
+ f"{_bn_prog}: {exc}")
423
+ store.append(record_for(
424
+ Envelope(experiment_branch_id=root_branch), EventType.problem_defined,
425
+ system_actor("planner"),
426
+ decision={"problem_id": tree.root.id, "objective": tree.root.objective,
427
+ "constraints": [], "success_metric": "all required sub-problems",
428
+ "environment": {"kind": "problem-tree",
429
+ "tree": tree.model_dump(),
430
+ "run_budget": tree.run_budget}}))
431
+
432
+
433
+ def _leaf_campaign(tree, leaf, alloc, specs, model, candidates, rounds,
434
+ autonomy, labs, inbox):
435
+ """The leaf's own budgeted CampaignConfig -> (cfg, problem, budget)."""
436
+ from pathlib import Path
437
+
438
+ from proef.autoloop import CampaignConfig, ResourceBudget
439
+ from proef.core.hypothesis import Constraint, ProblemStatement
440
+ # agent mode: a leaf with no config hypotheses (no candidate
441
+ # list given) proposes its own via the model — same contract as
442
+ # direct campaigns with hypothesis_source "agent"
443
+ agent_mode = not specs and model is not None
444
+ cons = []
445
+ if leaf.gate is not None and leaf.metric:
446
+ cons = [Constraint(
447
+ name=leaf.metric,
448
+ description=f"{leaf.metric} "
449
+ f"{'<=' if leaf.direction == 'min' else '>='} "
450
+ f"{leaf.gate:g}",
451
+ kind="hard", limit=leaf.gate)]
452
+ # the leaf's registered objective must say more than its own
453
+ # name: state the purpose within the tree (parent context, gate,
454
+ # metric) so the experiment page's Objective line carries
455
+ # information instead of echoing the title
456
+ gate_txt = (f"{leaf.metric} "
457
+ f"{'<=' if leaf.direction == 'min' else '>='} "
458
+ f"{leaf.gate:g}" if leaf.metric and
459
+ leaf.gate is not None else "its registered gate")
460
+ if leaf.parent and leaf.parent != tree.root.id:
461
+ parent = (f"a {tree.nodes[leaf.parent].objective} sub-problem")
462
+ else:
463
+ parent = "a direct sub-problem"
464
+ problem = ProblemStatement(
465
+ objective=(f"{leaf.objective} — {parent} of "
466
+ f"'{tree.root.objective}': show {gate_txt}"),
467
+ problem_id=f"{tree.root.id}-{leaf.id}",
468
+ constraints=cons,
469
+ success_metric=f"{leaf.metric or 'objective'} gate met")
470
+ budget = ResourceBudget(
471
+ max_total_runs=alloc.get(leaf.id, 2),
472
+ max_hypotheses_total=tree.limits.max_hypotheses_per_leaf,
473
+ max_confirmations=max(0, alloc.get(leaf.id, 2) - 1))
474
+ k_eff = min(tree.limits.k_per_leaf, alloc.get(leaf.id, 2))
475
+ cfg = CampaignConfig(
476
+ problem=problem,
477
+ hypotheses=None if agent_mode
478
+ else specs[: tree.limits.max_hypotheses_per_leaf],
479
+ hypothesis_source="agent" if agent_mode else "config",
480
+ model=model, candidates=candidates,
481
+ k=k_eff,
482
+ rounds=(max(2, len(specs) // max(1, k_eff))
483
+ if not rounds else rounds),
484
+ autonomy=autonomy, labs=labs,
485
+ inbox=str(Path(inbox) / leaf.id), poll_secs=0.05,
486
+ budget=budget)
487
+ return cfg, problem, budget
488
+
489
+
490
+ def _register_leaf(tree, leaf, leaf_eid: str, leaf_log, autonomy: str,
491
+ problem, say) -> None:
492
+ """The leaf surfaces in the workbench Experiments list like any other
493
+ agent run (one registry, tagged by origin)."""
494
+ # the leaf surfaces in the workbench Experiments list like any
495
+ # other agent run (one registry, tagged by origin)
496
+ try:
497
+ from proef.wizard_store import WizardStore
498
+ _ws = WizardStore()
499
+ _eid = leaf_eid
500
+ _root_name = tree.root.objective.split(":")[0].strip()[:40]
501
+ import os as _os
502
+ _status = ("completed" if leaf.status == "achieved"
503
+ else ("failed" if leaf.status == "failed"
504
+ else "verdict_recorded"))
505
+ _ws.register_agent(
506
+ _eid, f"{leaf.objective} · sub-problem of {_root_name}",
507
+ log=str(leaf_log), autonomy=autonomy, status=_status)
508
+ _bn_prog = _os.environ.get("PROEF_PROGRAM")
509
+ if _bn_prog:
510
+ try:
511
+ from proef import program as _program
512
+ _program.link_leaf(_bn_prog, _eid, tree.root.id,
513
+ leaf.objective, _status)
514
+ except Exception as _exc:
515
+ say(f"warning: leaf {_eid} not linked to program "
516
+ f"{_bn_prog}: {_exc}")
517
+ _ws.link_problem(_eid, problem.problem_id)
518
+ except Exception as _exc:
519
+ say(f"warning: leaf {leaf.id} registration incomplete: {_exc}")
520
+
521
+
522
+ def run_tree(tree: "ProblemTree", lab_factory, store, *,
523
+ hypotheses: dict[str, list] | None = None,
524
+ model: Any = None, candidates: list[dict] | None = None,
525
+ inbox: str = ".data/inbox-tree", autonomy: str = "act",
526
+ rounds: int | None = None,
527
+ notify: Any = None, labs: list | None = None) -> dict[str, str]:
528
+ """Each leaf runs as its own budgeted campaign; the roll-up is recorded
529
+ on the root branch. Resumable: achieved leaves are skipped."""
530
+ from proef.autoloop import announce_branch, run_campaign
531
+ from proef.core.contracts import Envelope, EventType
532
+ from proef.core.interfaces import record_for, system_actor
533
+
534
+ say = notify or (lambda m: print(f"[plan] {m}"))
535
+ alloc = tree.allocation()
536
+ hyps = hypotheses or default_hypotheses(
537
+ tree, [c["sample_id"] if isinstance(c, dict) else str(c)
538
+ for c in (candidates or [])])
539
+ root_branch = f"problem/{tree.root.id}"
540
+ _record_root(tree, store, root_branch, say)
541
+ for leaf in tree.leaves():
542
+ if leaf.status == "achieved":
543
+ say(f"leaf {leaf.id} already achieved — skipping (resumable)")
544
+ continue
545
+ cfg, problem, budget = _leaf_campaign(
546
+ tree, leaf, alloc, hyps.get(leaf.id) or [], model, candidates,
547
+ rounds, autonomy, labs, inbox)
548
+ say(f"leaf {leaf.id}: '{leaf.objective[:50]}' — "
549
+ f"{budget.max_total_runs} runs allocated")
550
+ # the leaf's workbench id, announced BEFORE the campaign runs so
551
+ # the API watcher streams its records while it is still in flight
552
+ leaf_eid = f"tree-{tree.root.id}-{leaf.id}"
553
+ announce_branch(leaf_eid, problem.problem_id)
554
+ # per-leaf log: the leaf's Trace log is its own campaign diary
555
+ from proef.paths import CAMPAIGN_DIR, ensure_dirs
556
+ ensure_dirs()
557
+ leaf_log = CAMPAIGN_DIR / f"{tree.root.id}-{leaf.id}.log"
558
+ leaf_log.write_text("")
559
+ def _tee(msg, _f=leaf_log):
560
+ with open(_f, "a") as fh:
561
+ fh.write(str(msg) + "\n")
562
+ say(msg)
563
+ report = run_campaign(cfg, lab_factory(), store, notify=_tee)
564
+ tree.set_leaf_status(leaf.id, report.verdicts)
565
+ _register_leaf(tree, leaf, leaf_eid, leaf_log, autonomy, problem, say)
566
+ store.append(record_for(
567
+ Envelope(experiment_branch_id=leaf.branch(tree.root.id),
568
+ parent_branch_id=root_branch),
569
+ EventType.stage_transition, system_actor("planner"),
570
+ decision={"stage": "leaf-complete", "leaf": leaf.id,
571
+ "objective": leaf.objective,
572
+ "status": leaf.status, "verdicts": report.verdicts}))
573
+ summary = tree.rollup()
574
+ store.append(record_for(
575
+ Envelope(experiment_branch_id=root_branch), EventType.gate_decision,
576
+ system_actor("planner"),
577
+ decision={"kind": "tree-rollup", "root_status": summary[tree.root.id],
578
+ "statuses": {n: summary[n] for n in summary},
579
+ "tree": tree.model_dump()}))
580
+ say("TREE ROLL-UP: " + summary[tree.root.id])
581
+ return summary