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/api/v1/system.py ADDED
@@ -0,0 +1,79 @@
1
+ """/api/v1/system, global status for the top bar and trust strip."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+ from pathlib import Path
6
+
7
+ from fastapi import APIRouter
8
+
9
+ from proef.api.v1 import schemas as S
10
+ from proef.views import ids as _ids
11
+
12
+ router = APIRouter(prefix="/system", tags=["system"])
13
+
14
+ _chain_cache: dict = {"at": 0.0, "db": None, "value": None}
15
+
16
+
17
+ def _chain() -> S.ChainStatus:
18
+ """Whole-ledger verification, cached for 30 s (it re-hashes every record)."""
19
+ db = str(_ids.PROVENANCE_DB)
20
+ now = time.time()
21
+ if (_chain_cache["db"] == db and _chain_cache["value"] is not None
22
+ and now - _chain_cache["at"] < 30):
23
+ return _chain_cache["value"]
24
+ if not Path(db).exists():
25
+ value = S.ChainStatus(verified=True, records=0)
26
+ else:
27
+ from proef.adapters.store.sqlite import get_store
28
+ store = get_store(db)
29
+ problems = store.verify_chain()
30
+ n = store._conn.execute("SELECT COUNT(*) FROM provenance").fetchone()[0]
31
+ value = S.ChainStatus(verified=not problems, records=n,
32
+ problems=problems[:10])
33
+ _chain_cache.update(at=now, db=db, value=value)
34
+ return value
35
+
36
+
37
+ def _anchor() -> S.AnchorStatus | None:
38
+ import json
39
+
40
+ from proef import anchor
41
+ path = Path(anchor.ANCHORS)
42
+ if not path.exists():
43
+ return None
44
+ try:
45
+ last = json.loads(path.read_text())[-1]
46
+ except (ValueError, IndexError):
47
+ return None
48
+ return S.AnchorStatus(records=last.get("records", 0),
49
+ age_s=time.time() - last["ts"] if last.get("ts") else None,
50
+ published=last.get("published"))
51
+
52
+
53
+ def _eval() -> S.EvalSummary | None:
54
+ try:
55
+ from proef.evals.harness import leaderboard_payload
56
+ p = leaderboard_payload()
57
+ except Exception:
58
+ return None
59
+ if not p.get("available"):
60
+ return None
61
+ return S.EvalSummary(mean=p["mean"], tasks=p["n_tasks"],
62
+ all_pass=bool(p.get("all_pass")))
63
+
64
+
65
+ @router.get("/status", response_model=S.SystemStatus)
66
+ def status() -> S.SystemStatus:
67
+ from proef.approvals import ApprovalInbox
68
+ from proef.governance import HaltSwitch
69
+ from proef.paths import APPROVALS_FILE
70
+ halt = HaltSwitch().engaged()
71
+ reason = None
72
+ if halt:
73
+ reason = halt.get("reason") if isinstance(halt, dict) else str(halt)
74
+ from proef.adapters.models.from_env import model_status
75
+ return S.SystemStatus(
76
+ model=S.ModelStatus(**model_status()),
77
+ halted=halt is not None, halt_reason=reason,
78
+ pending_approvals=len(ApprovalInbox(str(APPROVALS_FILE)).pending()),
79
+ chain=_chain(), anchor=_anchor(), eval=_eval())
proef/api/v1/trees.py ADDED
@@ -0,0 +1,216 @@
1
+ """/api/v1/programs/{slug}/decompose and /trees, a research tree: an objective split into sub-problems.
2
+
3
+ A model PROPOSES the split (nothing is recorded). The person keeps the sub-problems that are real questions and
4
+ may change each gate; starting the tree seals their decision in the ledger and launches one budgeted campaign per
5
+ leaf. Every runaway guard is the engine's (`problem_tree`): depth, children per node, total nodes, and a run budget
6
+ that flows DOWN the tree so a leaf can never spend more than its share. The roll-up (a node is achieved only when
7
+ its required children are) is computed from the leaves' recorded verdicts each time it is read.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import time
12
+ import uuid
13
+
14
+ from fastapi import APIRouter, HTTPException, Request
15
+
16
+ from proef import program as program_cfg
17
+ from proef.api.launch import spawn_campaign
18
+ from proef.api.v1 import schemas as S
19
+ from proef.api.v1.deps import who
20
+ from proef.api.v1.programs import _digest, _gate, _limits, campaign_doc, runs_left
21
+ from proef.problem_tree import ProblemTree, TreeLimits
22
+
23
+ MIN_MODEL_CALLS_PER_LEAF = 3 # a proposal, a critic note and a review is the least a leaf campaign uses
24
+
25
+ router = APIRouter(tags=["programs"])
26
+
27
+ _RUNNING = ("running", "executing", "awaiting_results")
28
+ _MAX_CHILDREN = 4
29
+
30
+
31
+ def _program_or_404(slug: str) -> dict:
32
+ p = next((x for x in program_cfg.list_programs() if x["slug"] == slug), None)
33
+ if p is None:
34
+ raise HTTPException(404, S.Problem(type="program-not-found", title="Program not found", detail=slug).model_dump())
35
+ return p
36
+
37
+
38
+ def _tree_limits(lim: S.Limits) -> TreeLimits:
39
+ return TreeLimits(max_depth=lim.max_depth, max_children=_MAX_CHILDREN, max_nodes=lim.max_subproblems + 1)
40
+
41
+
42
+ def _nodes_of(tree: ProblemTree, alloc: dict[str, int] | None = None) -> list[S.TreeNode]:
43
+ """Depth-first, parents before children; the root (the objective itself) is not a node."""
44
+ out: list[S.TreeNode] = []
45
+
46
+ def walk(nid: str) -> None:
47
+ for k in sorted(tree.children(nid), key=lambda n: n.id):
48
+ out.append(S.TreeNode(id=k.id, parent=None if k.parent == tree.root.id else k.parent,
49
+ objective=k.objective, metric=k.metric, direction=k.direction, gate=k.gate,
50
+ priority=k.priority, rationale=k.rationale, depth=tree.depth_of(k.id)))
51
+ walk(k.id)
52
+ walk(tree.root.id)
53
+ return out
54
+
55
+
56
+ def _build(objective: str, nodes: list[S.TreeNode], lim: S.Limits, run_budget: int | None = None) -> ProblemTree:
57
+ """Rebuild a tree from what the client sent, through the engine's own guardrails: whatever the browser
58
+ claims, a tree deeper or wider than the program's limits is refused."""
59
+ tree = ProblemTree.create(objective, limits=_tree_limits(lim), run_budget=lim.max_lab_runs if run_budget is None else run_budget)
60
+ ids = {n.id for n in nodes}
61
+ if len(ids) != len(nodes):
62
+ raise HTTPException(422, S.Problem(type="bad-tree", title="Duplicate sub-problem ids").model_dump())
63
+ pending = list(nodes)
64
+ placed = {None}
65
+ while pending:
66
+ ready = [n for n in pending if n.parent in placed]
67
+ if not ready:
68
+ raise HTTPException(422, S.Problem(type="bad-tree", title="A sub-problem points at a parent that is not in the tree",
69
+ detail=", ".join(n.id for n in pending)).model_dump())
70
+ for n in ready:
71
+ try:
72
+ tree.add(tree.root.id if n.parent is None else n.parent, id=n.id, objective=n.objective, metric=n.metric,
73
+ direction=n.direction, gate=n.gate, priority=n.priority, rationale=n.rationale)
74
+ except ValueError as exc: # depth / breadth / node caps
75
+ raise HTTPException(422, S.Problem(type="tree-over-limit", title="This tree exceeds the program's limits",
76
+ detail=str(exc)).model_dump()) from exc
77
+ placed.add(n.id)
78
+ pending.remove(n)
79
+ return tree
80
+
81
+
82
+ @router.post("/programs/{slug}/decompose", response_model=S.Decomposition)
83
+ def decompose_program(slug: str, body: S.DecomposeIn | None = None) -> S.Decomposition:
84
+ """A model proposes how to split the program's objective (recursively, within the program's depth and size
85
+ limits). A proposal only: nothing is recorded or run until the person starts the tree."""
86
+ p = _program_or_404(slug)
87
+ from proef.adapters.models.from_env import model_from_env, model_status
88
+ if not model_status()["configured"]:
89
+ raise HTTPException(409, S.Problem(type="model-not-configured", title="No model is configured",
90
+ detail="Splitting an objective needs a model. See docs/MODELS.md.").model_dump())
91
+ from proef.problem_tree import decompose_with_agent
92
+ doc = p.get("program") or {}
93
+ lim = _limits(doc)
94
+ objective = ((body and body.objective) or "").strip() or doc.get("objective") or p["name"]
95
+ try:
96
+ tree = decompose_with_agent(model_from_env(), objective, context=f"program gate: {_gate(doc).label}",
97
+ limits=_tree_limits(lim))
98
+ except Exception as exc: # noqa: BLE001 - the model's reply is untrusted
99
+ raise HTTPException(502, S.Problem(type="decomposition-failed", title="The model's split could not be read",
100
+ detail=f"{type(exc).__name__}: {exc}"[:300]).model_dump()) from exc
101
+ nodes = [n for n in _nodes_of(tree) if n.objective.strip()]
102
+ return S.Decomposition(objective=objective, nodes=nodes, model=model_status()["model"],
103
+ max_depth=lim.max_depth, max_subproblems=lim.max_subproblems)
104
+
105
+
106
+ @router.post("/programs/{slug}/trees", response_model=S.TreeView, status_code=201)
107
+ def start_tree(slug: str, body: S.TreeCreate, request: Request) -> S.TreeView:
108
+ p = _program_or_404(slug)
109
+ lim = _limits(p.get("program") or {})
110
+ left = runs_left(slug, lim) # the program's other campaigns already hold part of its lab runs
111
+ tree = _build(body.objective, body.nodes, lim, run_budget=left)
112
+ alloc = tree.allocation()
113
+ leaves = tree.leaves() if len(tree.nodes) > 1 else []
114
+ if leaves and left < 2 * len(leaves): # every leaf needs a floor of 2 runs to mean anything
115
+ raise HTTPException(409, S.Problem(
116
+ type="program-budget-exhausted", title="Not enough lab runs left for this many sub-problems",
117
+ detail=f"{left} of the program's {lim.max_lab_runs} lab runs are unspent and unreserved; "
118
+ f"{len(leaves)} sub-problems need at least {2 * len(leaves)}.").model_dump())
119
+ if not leaves:
120
+ raise HTTPException(422, S.Problem(type="bad-tree", title="Keep at least one sub-problem").model_dump())
121
+ from proef.adapters.models.from_env import model_status
122
+ if not model_status()["configured"]:
123
+ raise HTTPException(409, S.Problem(type="model-not-configured", title="No model is configured",
124
+ detail="Each sub-problem is researched by a model.").model_dump())
125
+ if lim.max_model_calls // len(leaves) < MIN_MODEL_CALLS_PER_LEAF:
126
+ # a floor here would let the leaves together exceed the program's cap, so the tree is refused instead
127
+ raise HTTPException(422, S.Problem(
128
+ type="model-call-cap-too-small", title="Not enough model calls for this many sub-problems",
129
+ detail=f"This program allows {lim.max_model_calls} model calls: {lim.max_model_calls // len(leaves)} each for "
130
+ f"{len(leaves)} sub-problems, and each needs at least {MIN_MODEL_CALLS_PER_LEAF}. Keep fewer sub-problems "
131
+ "or raise the program's model-call limit.").model_dump())
132
+ by = who(request)
133
+ tree_id = f"tree-{uuid.uuid4().hex[:8]}"
134
+ share_h = max(1, lim.max_hypotheses // len(leaves))
135
+ share_m = lim.max_model_calls // len(leaves) # model calls are shared across leaves like lab runs, never rounded up
136
+ campaigns: dict[str, str] = {}
137
+ failed: list[str] = []
138
+ for leaf in leaves:
139
+ c = S.CampaignCreate(
140
+ sub_problem=S.SubProblem(objective=leaf.objective, metric=leaf.metric, direction=leaf.direction, gate=leaf.gate,
141
+ priority=leaf.priority),
142
+ autonomy=body.autonomy, rounds=body.rounds, replan=False)
143
+ cid = spawn_campaign(campaign_doc(p, c, runs=alloc.get(leaf.id), hypotheses=share_h, model_calls=share_m), p["name"])
144
+ (campaigns.__setitem__(leaf.id, cid) if cid else failed.append(leaf.id))
145
+ from proef.adapters.store.sqlite import get_store
146
+ from proef.core.contracts import Actor, ActorKind, Envelope, EventType
147
+ from proef.core.interfaces import record_for
148
+ from proef.views import ids as _ids
149
+ get_store(str(_ids.PROVENANCE_DB)).append(record_for(
150
+ Envelope(experiment_branch_id=f"programs/{slug}"), EventType.gate_decision,
151
+ Actor(kind=ActorKind.human, id=by),
152
+ decision={"kind": "research_tree", "tree_id": tree_id, "objective": body.objective, "by": by,
153
+ "nodes": [n.model_dump() for n in _nodes_of(tree)], "campaigns": campaigns,
154
+ "allocation": alloc, "run_budget": left,
155
+ "limits": {"max_depth": lim.max_depth, "max_subproblems": lim.max_subproblems}}))
156
+ if failed:
157
+ raise HTTPException(500, S.Problem(type="launch-failed", title="Some sub-problems did not start",
158
+ detail=f"{len(campaigns)} started, {len(failed)} did not").model_dump())
159
+ return _view(tree_id, body.objective, by, time.time(), tree, campaigns, alloc)
160
+
161
+
162
+ def _leaf_statuses(cid: str) -> tuple[str, dict[str, str]]:
163
+ """(running?|done, {candidate: verdict}) for one leaf's campaign."""
164
+ try:
165
+ dg, hyps = _digest(cid)
166
+ except HTTPException:
167
+ return "gone", {}
168
+ if dg.status in _RUNNING:
169
+ return "running", {}
170
+ verdicts = {(h.candidate or h.head): h.state for h in hyps
171
+ if h.state in ("confirmed", "validated", "refuted", "abstained")}
172
+ return "done", verdicts
173
+
174
+
175
+ def _view(tree_id, objective, by, ts, tree: ProblemTree, campaigns: dict[str, str], alloc: dict[str, int]) -> S.TreeView:
176
+ pending: set[str] = set() # leaves still being worked on, and everything above them
177
+ for leaf_id, cid in campaigns.items():
178
+ state, verdicts = _leaf_statuses(cid)
179
+ if state == "done":
180
+ tree.set_leaf_status(leaf_id, verdicts)
181
+ else: # running, or not registered yet (just launched)
182
+ nid = leaf_id
183
+ while nid:
184
+ pending.add(nid)
185
+ nid = tree.nodes[nid].parent
186
+ roll = tree.rollup()
187
+ nodes = [S.TreeNodeView(**n.model_dump(), status="in lab" if n.id in pending else roll.get(n.id, "open"),
188
+ runs=alloc.get(n.id), campaign_id=campaigns.get(n.id), verdicts=tree.nodes[n.id].verdicts)
189
+ for n in _nodes_of(tree)]
190
+ return S.TreeView(id=tree_id, objective=objective, by=by, ts=ts,
191
+ status="in lab" if tree.root.id in pending else roll.get(tree.root.id, "open"),
192
+ nodes=nodes, run_budget=tree.run_budget)
193
+
194
+
195
+ @router.get("/programs/{slug}/trees", response_model=list[S.TreeView])
196
+ def list_trees(slug: str) -> list[S.TreeView]:
197
+ _program_or_404(slug)
198
+ from proef.adapters.store.sqlite import get_store
199
+ from proef.views import ids as _ids
200
+ lim = _limits(_program_or_404(slug).get("program") or {})
201
+ out: list[S.TreeView] = []
202
+ for r in get_store(str(_ids.PROVENANCE_DB)).branch_records(f"programs/{slug}"):
203
+ d = r.decision or {}
204
+ if d.get("kind") != "research_tree":
205
+ continue
206
+ try:
207
+ tree = _build(d["objective"], [S.TreeNode(**n) for n in d["nodes"]],
208
+ lim.model_copy(update={"max_depth": max(lim.max_depth, d["limits"]["max_depth"]),
209
+ "max_subproblems": max(lim.max_subproblems, d["limits"]["max_subproblems"]),
210
+ "max_lab_runs": d.get("run_budget", lim.max_lab_runs)}))
211
+ except HTTPException:
212
+ continue
213
+ out.append(_view(d["tree_id"], d["objective"], d.get("by", "someone"),
214
+ r.ts.timestamp() if getattr(r, "ts", None) else None,
215
+ tree, d.get("campaigns", {}), {k: int(v) for k, v in (d.get("allocation") or {}).items()}))
216
+ return list(reversed(out))
@@ -0,0 +1,253 @@
1
+ """Guided wizard sessions (P2.3): the 6-step flow as a stateless API.
2
+
3
+ State lives in the wizard_sessions table (one JSON doc per session);
4
+ each step is one endpoint call. Provenance is recorded on the
5
+ experiment's wizard branch via wizard_chain.record_wizard_event.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import time
11
+ import uuid
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from proef.paths import DATA_DIR
16
+ from proef.wizard_store import WizardStore
17
+
18
+ UPLOAD_DIR = DATA_DIR / "wizard-uploads"
19
+
20
+
21
+ def ensure_tables() -> None:
22
+ ws = WizardStore()
23
+ ws._conn.execute("""
24
+ CREATE TABLE IF NOT EXISTS wizard_sessions (
25
+ id TEXT PRIMARY KEY,
26
+ eid TEXT,
27
+ step INTEGER NOT NULL,
28
+ doc TEXT NOT NULL,
29
+ created_at REAL NOT NULL,
30
+ updated_at REAL NOT NULL
31
+ )""")
32
+ ws._conn.commit()
33
+
34
+
35
+ def _ws() -> WizardStore:
36
+ return WizardStore()
37
+
38
+
39
+ def create_session(question: str, target: str, claim: str,
40
+ program: str | None = None) -> dict:
41
+ """Step 1: define the problem; creates the registry experiment too.
42
+ When launched from a program (guided), the experiment is linked to
43
+ it relationally so it nests in the workspace like any campaign."""
44
+ from proef.experiment import ClaimType
45
+ if claim not in {c.value for c in ClaimType}:
46
+ claim = ClaimType.causal_modification.value
47
+ ensure_tables()
48
+ ws = _ws()
49
+ eid = ws.create(question, claim, target)
50
+ if program:
51
+ try:
52
+ from proef import program as program_cfg
53
+ from proef.wizard_store import WizardStore as _WS
54
+ _w = _WS()
55
+ _pdoc = _w.get_program(program_cfg._slug(program)) or {}
56
+ _w.set_campaign_spec(
57
+ eid, objective=question,
58
+ program_slug=program_cfg._slug(program),
59
+ k=int(_pdoc.get("k", 2)), rounds=int(_pdoc.get("rounds", 2)),
60
+ autonomy="act", hypothesis_source="config",
61
+ n_candidates=0, modality=_pdoc.get("modality") or None)
62
+ program_cfg.link_leaf(program, eid, campaign_root=None,
63
+ question=question, status="designing")
64
+ except Exception:
65
+ pass
66
+ fence: list[dict] = []
67
+ if program:
68
+ try:
69
+ from proef import program as program_cfg
70
+ from proef.labselect import fence_info
71
+ _pdoc = _w.get_program(program_cfg._slug(program)) or {}
72
+ fence = fence_info(_pdoc.get("labs"))
73
+ except Exception:
74
+ fence = []
75
+ sid = f"wsn-{uuid.uuid4().hex[:8]}"
76
+ doc = {"question": question, "target": target, "claim": claim,
77
+ "eid": eid, "controls": [], "selected": [], "fence": fence}
78
+ try:
79
+ from proef.wizard_chain import record_wizard_event
80
+ from proef.core.contracts import EventType
81
+ if fence:
82
+ record_wizard_event(eid, EventType.gate_decision, {
83
+ "kind": "lab_fence_declared",
84
+ "instruments": [f["name"] for f in fence],
85
+ "note": "guided experiment: the scientist operates the "
86
+ "declared instrument(s) and uploads the export; "
87
+ "Proef governs the analysis and verdict"})
88
+ except Exception:
89
+ pass
90
+ now = time.time()
91
+ ws._conn.execute(
92
+ "INSERT INTO wizard_sessions VALUES (?,?,?,?,?,?)",
93
+ (sid, eid, 2, json.dumps(doc), now, now))
94
+ ws._conn.commit()
95
+ ws.set_status(eid, "designing") if hasattr(ws, "set_status") else None
96
+ return {"sid": sid, "eid": eid, "step": 2}
97
+
98
+
99
+ def _load(sid: str) -> tuple[dict, dict]:
100
+ row = _ws()._conn.execute(
101
+ "SELECT eid, step, doc FROM wizard_sessions WHERE id=?",
102
+ (sid,)).fetchone()
103
+ if not row:
104
+ raise KeyError(f"wizard session {sid} not found")
105
+ return json.loads(row[2]), {"step": row[1]}
106
+
107
+
108
+ def _save(sid: str, eid: str, step: int, doc: dict) -> None:
109
+ ws = _ws()
110
+ ws._conn.execute(
111
+ "UPDATE wizard_sessions SET eid=?, step=?, doc=?, updated_at=? "
112
+ "WHERE id=?", (eid, step, json.dumps(doc, default=str), time.time(),
113
+ sid))
114
+ ws._conn.commit()
115
+
116
+
117
+ def design(sid: str, site: str | None, half_life: int, edited_frac: bool,
118
+ mimetic: bool, controls: list[str], mechanism: str = "",
119
+ refutation: str = "", citation: str = "") -> dict:
120
+ """Step 2: build the ExperimentDefinition, run the readiness review,
121
+ verify the citation, record experiment_defined provenance."""
122
+ from proef.experiment import (BiologicalSystem, ClaimType,
123
+ DeliveryConditions,
124
+ ExperimentDefinition,
125
+ Intervention, ReadoutSpec)
126
+ from proef.readiness import review_experiment
127
+ doc, _ = _load(sid)
128
+ eid = doc["eid"]
129
+ claim = doc.get("claim") or "causal_modification"
130
+ exp = ExperimentDefinition(
131
+ scientific_question=doc.get("question", "user experiment"),
132
+ claim_type=claim,
133
+ intervention=Intervention(kind="user_defined",
134
+ target=doc.get("target", "user-target"),
135
+ site=site or None),
136
+ system=BiologicalSystem(cell_line="user",
137
+ target_half_life_min=half_life),
138
+ delivery=DeliveryConditions(method="user",
139
+ per_cell_loading_measured=True),
140
+ readout=ReadoutSpec(assay="user",
141
+ measures_edited_fraction=edited_frac,
142
+ distinguishes_modified_from_mimetic=mimetic),
143
+ controls=controls)
144
+ fence_caps = None
145
+ if doc.get("fence"):
146
+ try:
147
+ from proef.labselect import fence_declared_caps
148
+ fence_caps = fence_declared_caps(doc.get("fence"))
149
+ except Exception:
150
+ fence_caps = None
151
+ review = review_experiment(exp, available_caps=fence_caps)
152
+ extras: dict[str, Any] = {"mechanism": mechanism,
153
+ "refutation_condition": refutation,
154
+ "citation": citation}
155
+ if citation:
156
+ from proef import citations
157
+ res = citations.verify(citation)
158
+ extras["citation_status"] = res["status"]
159
+ extras["citation_detail"] = res["detail"]
160
+ doc.update({"site": site, "half_life": half_life,
161
+ "edited_frac": edited_frac, "mimetic": mimetic,
162
+ "controls": controls, "exp_def": exp.model_dump(mode="json"),
163
+ "readiness": {"verdict": review.verdict.value,
164
+ "findings": [f.model_dump(mode="json")
165
+ for f in review.findings]},
166
+ **extras})
167
+ _save(sid, eid, 3, doc)
168
+ from proef.wizard_chain import record_wizard_event
169
+ from proef.core.contracts import EventType
170
+ record_wizard_event(eid, EventType.experiment_defined, {
171
+ "statement": exp.scientific_question,
172
+ "claim_type": exp.claim_type.value,
173
+ "target": exp.intervention.target,
174
+ "controls": exp.controls,
175
+ **extras})
176
+ return {"step": 3, "readiness": doc["readiness"]}
177
+
178
+
179
+ def execute(sid: str) -> dict:
180
+ """Step 3 -> 4: readiness passed; mark executing."""
181
+ doc, _ = _load(sid)
182
+ if doc.get("readiness", {}).get("verdict") == "blocked":
183
+ raise ValueError("readiness blocked — redesign first")
184
+ _save(sid, doc["eid"], 4, doc)
185
+ _ws().set_status(doc["eid"], "executing")
186
+ return {"step": 4}
187
+
188
+
189
+ def upload(sid: str, filename: str, content: bytes) -> dict:
190
+ """Step 5: store the instrument export and read it."""
191
+ UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
192
+ doc, _ = _load(sid)
193
+ path = UPLOAD_DIR / f"{sid}-{filename}"
194
+ path.write_bytes(content)
195
+ from proef.labread import read_plate
196
+ r = read_plate(path)
197
+ fence = doc.get("fence") or []
198
+ if fence:
199
+ ident = getattr(r, "instrument", None) or {}
200
+ identity = " ".join(str(v) for v in ident.values()).strip()
201
+ if not identity:
202
+ raise ValueError(
203
+ "fenced program: this export carries no device identity "
204
+ "(reader/serial metadata) — uploads must come from an "
205
+ "identified instrument")
206
+ declared = [str(p).lower() for f in fence
207
+ for p in (f.get("match") or [])]
208
+ if declared and not any(p in identity.lower() for p in declared):
209
+ raise ValueError(
210
+ f"fenced program: device '{identity[:60]}' does not match "
211
+ f"the program's declared instruments {declared}")
212
+ doc["plate"] = {"path": str(path), "format": r.format,
213
+ "n_wells": len(r.records), "z_prime": r.z_prime,
214
+ "samples": list(r.analysis["compounds"]),
215
+ "compounds": {c: {"ic50_um": dd.get("ic50_um"),
216
+ "ic50_ci": dd.get("ic50_ci"),
217
+ "n_points": dd.get("n_points"),
218
+ "fit_quality": dd.get("fit_quality", "")}
219
+ for c, dd in
220
+ r.analysis["compounds"].items()}}
221
+ _save(sid, doc["eid"], 6, doc)
222
+ from proef.core.contracts import EventType
223
+ from proef.wizard_chain import record_wizard_event
224
+ record_wizard_event(doc["eid"], EventType.evaluation, {
225
+ "artifact": "uploaded instrument export", "format": r.format,
226
+ "instrument": getattr(r, "instrument", None) or {},
227
+ "n_wells": len(r.records), "z_prime": r.z_prime,
228
+ "fits": {c: dd.get("ic50_um")
229
+ for c, dd in r.analysis["compounds"].items()}})
230
+ return {"step": 6, "plate": {k: v for k, v in doc["plate"].items()
231
+ if k != "path"}}
232
+
233
+
234
+ def analyze(sid: str, selected: list[str]) -> dict:
235
+ """Step 6: record the hit selection as the session verdict."""
236
+ doc, _ = _load(sid)
237
+ doc["selected"] = selected
238
+ _save(sid, doc["eid"], 6, doc)
239
+ _ws().set_status(doc["eid"], "completed")
240
+ from proef.core.contracts import EventType
241
+ from proef.wizard_chain import record_wizard_event
242
+ record_wizard_event(doc["eid"], EventType.gate_decision, {
243
+ "kind": "wizard_verdict", "hits": selected,
244
+ "plate": doc.get("plate", {}).get("samples")})
245
+ return {"step": 6, "selected": selected, "done": True}
246
+
247
+
248
+ def get_session(sid: str) -> dict:
249
+ doc, meta = _load(sid)
250
+ safe = {k: v for k, v in doc.items() if k != "plate"}
251
+ safe["plate"] = {k: v for k, v in (doc.get("plate") or {}).items()
252
+ if k != "path"}
253
+ return {"sid": sid, "eid": doc["eid"], "step": meta["step"], **safe}
proef/approvals.py ADDED
@@ -0,0 +1,102 @@
1
+ """Approval inbox — the scientist's button, backed by an append-only log.
2
+
3
+ Autonomy `gate` mode: every lab submission writes a request here and waits for
4
+ an operator decision. the workbench (`make run`) renders the inbox as a web page with
5
+ Approve/Deny buttons; decisions append to the same log. Both sides are
6
+ multi-writer-safe (append-only events, folded on read).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import time
12
+ import uuid
13
+ from pathlib import Path
14
+ from typing import Any, Callable
15
+
16
+ from proef.paths import APPROVALS_FILE
17
+
18
+ DEFAULT_INBOX = str(APPROVALS_FILE)
19
+
20
+
21
+ class ApprovalInbox:
22
+ def __init__(self, path: str | Path = DEFAULT_INBOX):
23
+ self.path = Path(path)
24
+ self.path.parent.mkdir(parents=True, exist_ok=True)
25
+
26
+ # -- write side (campaigns request, server decides) ----------------------
27
+
28
+ def _append(self, event: dict[str, Any]) -> None:
29
+ with self.path.open("a") as f:
30
+ f.write(json.dumps(event) + "\n")
31
+
32
+ def request(self, title: str, detail: str = "", payload: dict | None = None) -> str:
33
+ """`payload` is structured context for the reviewer (e.g. a research plan)."""
34
+ aid = f"apr-{uuid.uuid4().hex[:8]}"
35
+ self._append({"event": "request", "id": aid, "title": title, "detail": detail,
36
+ "ts": time.time(), **({"payload": payload} if payload is not None else {})})
37
+ return aid
38
+
39
+ def decide(self, approval_id: str, approve: bool, by: str = "operator", data: dict | None = None) -> None:
40
+ """`data` is structured input from the decider (e.g. hypotheses removed from a plan)."""
41
+ self._append({"event": "decision", "id": approval_id, "approve": bool(approve), "by": by,
42
+ "ts": time.time(), **({"data": data} if data else {})})
43
+
44
+ # -- read side -------------------------------------------------------------
45
+
46
+ def state(self) -> dict[str, dict[str, Any]]:
47
+ """Fold the event log: id -> {title, detail, status, ts}."""
48
+ out: dict[str, dict[str, Any]] = {}
49
+ if not self.path.exists():
50
+ return out
51
+ for line in self.path.read_text().splitlines():
52
+ if not line.strip():
53
+ continue
54
+ try:
55
+ ev = json.loads(line)
56
+ except json.JSONDecodeError:
57
+ continue
58
+ if ev.get("event") == "request":
59
+ out[ev["id"]] = {"title": ev["title"], "detail": ev.get("detail", ""),
60
+ "status": "pending", "ts": ev["ts"], "payload": ev.get("payload")}
61
+ elif ev.get("event") == "decision" and ev["id"] in out:
62
+ out[ev["id"]]["status"] = "approved" if ev["approve"] else "denied"
63
+ out[ev["id"]]["decided_ts"] = ev.get("ts")
64
+ out[ev["id"]]["decided_by"] = ev.get("by", "operator")
65
+ out[ev["id"]]["data"] = ev.get("data") or {}
66
+ return out
67
+
68
+ def pending(self) -> list[dict[str, Any]]:
69
+ return sorted(({"id": k, **v} for k, v in self.state().items()
70
+ if v["status"] == "pending"), key=lambda d: d["ts"])
71
+
72
+ def status_of(self, approval_id: str) -> str | None:
73
+ rec = self.state().get(approval_id)
74
+ return rec["status"] if rec else None
75
+
76
+
77
+ def web_approver(inbox: ApprovalInbox | str | Path = DEFAULT_INBOX,
78
+ poll_secs: float = 2.0, timeout_secs: float = 24 * 3600,
79
+ notify: Callable[[str], None] | None = None
80
+ ) -> Callable[[str], bool]:
81
+ """Approver callback for `gate` autonomy: request into the inbox, wait for
82
+ the operator's decision in the workbench. Denies on timeout."""
83
+ box = inbox if isinstance(inbox, ApprovalInbox) else ApprovalInbox(inbox)
84
+ say = notify or (lambda m: None)
85
+
86
+ def approver(title: str) -> bool:
87
+ aid = box.request(title)
88
+ say(f"approval requested: '{title}' ({aid}) — pending in the workbench (Decisions)")
89
+ deadline = time.time() + timeout_secs
90
+ while time.time() < deadline:
91
+ status = box.status_of(aid)
92
+ if status == "approved":
93
+ say(f"operator APPROVED: {title}")
94
+ return True
95
+ if status == "denied":
96
+ say(f"operator DENIED: {title}")
97
+ return False
98
+ time.sleep(poll_secs)
99
+ say(f"approval timed out: {title}")
100
+ return False
101
+
102
+ return approver
@@ -0,0 +1,15 @@
1
+ """Assay analysis adapters — real instruments, raw files in, results out.
2
+
3
+ Each adapter parses a standard raw export and produces provenance-ready
4
+ results for the Analyze phase:
5
+
6
+ - ELISA (`elisa`) — plate-reader OD files via labread; blank+cutoff
7
+ serology, endpoint titers from dilution series
8
+ - DSF (`dsf`) — thermal melt curves (qPCR-style T vs fluorescence);
9
+ Tm per curve from the derivative peak
10
+ - DLS (`dls`) — autocorrelation curves; cumulant fit -> hydrodynamic
11
+ radius (Stokes-Einstein) + polydispersity flag
12
+
13
+ Dependency policy: pure Python, no numpy/scipy required — these run in
14
+ the core install so any lab file can be analyzed anywhere.
15
+ """