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/flywheel.py ADDED
@@ -0,0 +1,125 @@
1
+ """The flywheel — negative results are data.
2
+
3
+ Every verdict (validated / invalidated / inconclusive) is submitted here.
4
+ Future campaigns consult it twice:
5
+
6
+ 1. the hypothesis AGENT is shown what the lab already ruled out (prompt
7
+ context — don't re-propose dead mechanisms), and
8
+ 2. the portfolio SCORER gets a family prior (families that keep failing are
9
+ discounted; families that win are favored).
10
+
11
+ Backed by a small local SQLite table — append-only submissions, no
12
+ durability theater (this is a hint store, provenance remains the record).
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import sqlite3
17
+ import threading
18
+ import time
19
+ from typing import Any
20
+
21
+
22
+ class Flywheel:
23
+ def __init__(self, path: str | None = ".data/flywheel.db"):
24
+ self._lock = threading.Lock()
25
+ if path is None:
26
+ self._conn = None
27
+ return
28
+ import os
29
+ if os.path.dirname(path):
30
+ os.makedirs(os.path.dirname(path), exist_ok=True)
31
+ self._conn = sqlite3.connect(path, check_same_thread=False)
32
+ if True:
33
+ self._conn.execute(
34
+ """CREATE TABLE IF NOT EXISTS outcomes (
35
+ ts REAL NOT NULL,
36
+ problem_id TEXT,
37
+ candidate TEXT NOT NULL,
38
+ family TEXT,
39
+ assay TEXT,
40
+ outcome TEXT NOT NULL,
41
+ observed REAL,
42
+ ci_low REAL,
43
+ ci_high REAL,
44
+ threshold REAL,
45
+ evidence_run TEXT
46
+ )""")
47
+ for col in ("threshold REAL", "evidence_run TEXT"):
48
+ try: # migrate pre-existing stores
49
+ self._conn.execute(f"ALTER TABLE outcomes ADD COLUMN {col}")
50
+ except sqlite3.OperationalError:
51
+ pass
52
+ self._conn.commit()
53
+
54
+ # -- write side -----------------------------------------------------------
55
+
56
+ def submit(self, candidate: str, family: str | None, assay: str,
57
+ outcome: str, observed: float | None = None,
58
+ ci: tuple | None = None, problem_id: str | None = None,
59
+ threshold: float | None = None,
60
+ evidence_run: str | None = None) -> None:
61
+ if self._conn is None or outcome == "tested":
62
+ return
63
+ with self._lock:
64
+ self._conn.execute(
65
+ "INSERT INTO outcomes VALUES (?,?,?,?,?,?,?,?,?,?,?)",
66
+ (time.time(), problem_id, candidate, family or "unassigned",
67
+ assay, outcome, observed,
68
+ ci[0] if ci else None, ci[1] if ci else None,
69
+ threshold, evidence_run))
70
+ self._conn.commit()
71
+
72
+ # -- read side --------------------------------------------------------------
73
+
74
+ def negative_summary(self, problem_id: str | None = None,
75
+ limit: int = 20) -> list[dict[str, Any]]:
76
+ q = ("SELECT candidate, family, assay, outcome, observed, ts, "
77
+ "ci_low, ci_high, threshold, evidence_run "
78
+ "FROM outcomes WHERE outcome IN ('invalidated','refuted')")
79
+ args: list = []
80
+ if problem_id:
81
+ q += " AND problem_id = ?"
82
+ args.append(problem_id)
83
+ q += " ORDER BY ts DESC LIMIT ?"
84
+ args.append(limit)
85
+ rows = self._conn.execute(q, args).fetchall()
86
+ return [{"candidate": c, "family": f, "assay": a, "outcome": o,
87
+ "observed": obs, "ts": ts, "ci_low": clo, "ci_high": chi,
88
+ "threshold": thr, "evidence_run": run}
89
+ for c, f, a, o, obs, ts, clo, chi, thr, run in rows]
90
+
91
+ def family_prior(self, family: str | None) -> float:
92
+ """Multiplicative prior in [0.5, 1.5]: what does history say about
93
+ this mechanistic family? Neutral (1.0) when unseen."""
94
+ if self._conn is None or not family:
95
+ return 1.0
96
+ rows = self._conn.execute(
97
+ "SELECT outcome, COUNT(*) FROM outcomes WHERE family=? "
98
+ "GROUP BY outcome", (family,)).fetchall()
99
+ counts = dict(rows)
100
+ good = counts.get("validated", 0) + counts.get("confirmed", 0)
101
+ bad = counts.get("invalidated", 0) + counts.get("refuted", 0)
102
+ if good + bad == 0:
103
+ return 1.0
104
+ rate = good / (good + bad)
105
+ return round(0.5 + rate, 3)
106
+
107
+ def prior_bonus(self, family: str | None) -> float:
108
+ """Additive portfolio bonus: unseen neutral, all-win +0.15,
109
+ all-fail -0.15 — enough to steer, not to silence a strong score."""
110
+ p = self.family_prior(family)
111
+ return round((p - 1.0) * 0.3, 4)
112
+
113
+ def prompt_context(self, limit: int = 10) -> str:
114
+ """The block injected into the hypothesis-agent prompt."""
115
+ negs = self.negative_summary(limit=limit)
116
+ if not negs:
117
+ return ""
118
+ lines = [f"- {n['candidate']} ({n['family']} family, {n['assay']}): "
119
+ f"{n['outcome']}"
120
+ + (f" — observed IC50 {n['observed']:.1f} µM"
121
+ if n.get("observed") else "")
122
+ for n in negs]
123
+ return ("ALREADY RULED OUT BY THE LAB (do NOT re-propose these "
124
+ "candidates or near-clones of their mechanisms):\n"
125
+ + "\n".join(lines))
proef/followup.py ADDED
@@ -0,0 +1,126 @@
1
+ """Model-proposed follow-ups on abstained results, validated by code.
2
+
3
+ After a round, a hypothesis whose 95% interval straddles the gate (or whose QC failed) is abstained. The model may SUGGEST what
4
+ to do with each one from a closed set: follow up (test it again, with a replicate count and a dose ladder), accept it as
5
+ inconclusive, or drop it. Code validates every suggestion on facts and records it. The model decides nothing:
6
+ - accept and drop are a person's recorded decision (`human_review`), so they stay suggestions and are never executed here;
7
+ - a follow-up runs only under `act`, or after a person approves it in plan review under `gate`, inside every gate;
8
+ - the validation result has the same shape as the lab check and the predictions: {ok, status, reasons}.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import re
14
+ from typing import Any
15
+
16
+ from proef.protocol_design import sanitize_protocol
17
+
18
+ ACTIONS = ("follow_up", "accept", "drop")
19
+ MIN_REPLICATES, DEFAULT_REPLICATES, MAX_REPLICATES = 3, 6, 12
20
+
21
+ PROMPT = """You review ABSTAINED results of a research campaign.
22
+
23
+ GATE (fixed by a person before any data): {gate}
24
+
25
+ ABSTAINED HYPOTHESES (the 95% interval straddles the gate, or the QC failed)
26
+ {items}
27
+
28
+ For each one choose ONE action:
29
+ - "follow_up": test it again. Give "replicates" ({lo} to {hi}) and "concentrations_uM", a ladder of 3 to 8 doses that
30
+ brackets the gate on both sides.
31
+ - "accept": leave it as inconclusive.
32
+ - "drop": stop spending on it.
33
+ You do not decide anything. A person decides accept and drop, and the lab checks every follow-up before it runs.
34
+
35
+ Reply ONLY with JSON:
36
+ {{"proposals": [{{"hypothesis_id": "id from the list", "action": "follow_up|accept|drop", "replicates": 6,
37
+ "concentrations_uM": [0.5, 5, 20, 80], "why": "one sentence"}}]}}"""
38
+
39
+
40
+ def describe_abstained(hyps: list[Any]) -> str:
41
+ lines = []
42
+ for h in hyps:
43
+ ci = f", 95% interval {h.observed_ci[0]:g} to {h.observed_ci[1]:g}" if h.observed_ci else ", no interval"
44
+ obs = f"observed {h.observed_value:g}" if isinstance(h.observed_value, (int, float)) else "no usable value"
45
+ qc = "" if h.qc_passed is not False else ", QC FAILED"
46
+ lines.append(f"- {h.hypothesis_id} ({h.candidate}): {obs}{ci}{qc}")
47
+ return "\n".join(lines)[:4000]
48
+
49
+
50
+ def propose_followups(model: Any, abstained: list[Any], gate_text: str, background: str | None = None) -> list[dict]:
51
+ """Ask the model. Returns the raw proposals (untrusted): at most one per abstained hypothesis is looked at later."""
52
+ from proef.core.contracts import Envelope, ToolInvocation
53
+ prompt = PROMPT.format(gate=gate_text or "the program's gate", items=describe_abstained(abstained),
54
+ lo=MIN_REPLICATES, hi=MAX_REPLICATES) + ("\n\n" + background[:3000] if background else "")
55
+ inv = ToolInvocation(envelope=Envelope(experiment_branch_id="followup"), tool="c.fm.generate_molecules")
56
+ raw = model.generate(inv, prompt).output["text"]
57
+ m = re.search(r"\{.*\}", raw, re.S)
58
+ items = (json.loads(m.group(0)).get("proposals") if m else None) or []
59
+ return [x for x in items if isinstance(x, dict)][: max(1, len(abstained)) * 2]
60
+
61
+
62
+ def _verdict(ok: bool, status: str, *reasons: str) -> dict:
63
+ return {"ok": ok, "status": status, "reasons": list(reasons)}
64
+
65
+
66
+ def validate_followup(raw: dict, ctx: dict) -> dict:
67
+ """Validate ONE raw proposal on facts. `ctx`: abstained {hypothesis_id: hypothesis}, gate (SuccessCriteria or None),
68
+ runs_left, hyp_room (hypotheses the campaign may still add, or None), followed_up (candidates already followed up),
69
+ seen (hypothesis ids already proposed for), supports_replicates (does this lab honor a replicate request)."""
70
+ hid = str(raw.get("hypothesis_id") or "")[:80]
71
+ action = str(raw.get("action") or "")[:20]
72
+ h = ctx["abstained"].get(hid)
73
+ out = {"kind": "followup", "action": action, "hypothesis_id": hid, "candidate": getattr(h, "candidate", None),
74
+ "params": {}, "executes": False, "source": "model", "rationale": str(raw.get("why") or "")[:300]}
75
+ if action not in ACTIONS:
76
+ return {**out, "validation": _verdict(False, "bad_action", f"'{action}' is not one of {', '.join(ACTIONS)}")}
77
+ if h is None:
78
+ return {**out, "validation": _verdict(False, "unknown_hypothesis", "not one of the abstained hypotheses listed")}
79
+ if hid in ctx["seen"]:
80
+ return {**out, "validation": _verdict(False, "duplicate_proposal", "this hypothesis already has a proposal")}
81
+ ctx["seen"].add(hid)
82
+ if action in ("accept", "drop"):
83
+ # a person's decision: a suggestion, shown and recorded, never executed by the engine
84
+ return {**out, "validation": _verdict(True, "ok", "a suggestion: a person records this decision")}
85
+ if h.candidate in ctx["followed_up"]:
86
+ return {**out, "validation": _verdict(False, "already_followed_up", "one follow-up per candidate")}
87
+ applied = bool(ctx.get("supports_replicates"))
88
+ reps = raw.get("replicates")
89
+ if isinstance(reps, float) and reps.is_integer():
90
+ reps = int(reps) # 6.0 is six
91
+ if reps is None:
92
+ reps = DEFAULT_REPLICATES
93
+ valid_reps = isinstance(reps, int) and not isinstance(reps, bool) and MIN_REPLICATES <= reps <= MAX_REPLICATES
94
+ if applied and not valid_reps:
95
+ return {**out, "validation": _verdict(False, "replicates_out_of_bounds",
96
+ f"replicates must be a whole number from {MIN_REPLICATES} to {MAX_REPLICATES}")}
97
+ if not valid_reps:
98
+ reps = None # this lab ignores a replicate request, so a bad value is advisory and must not sink the follow-up
99
+ gate = getattr(h, "criteria", None) or ctx.get("gate")
100
+ ladder = None
101
+ if gate is not None and gate.metric == "ic50_um":
102
+ ladder = sanitize_protocol({"concentrations_uM": raw.get("concentrations_uM"), "why": raw.get("why")})
103
+ if ladder is None:
104
+ return {**out, "validation": _verdict(False, "bad_ladder", "needs 3 to 8 doses between 0.001 and 1000 uM")}
105
+ doses = [float(c.replace("uM", "")) for c in ladder["concentrations"]]
106
+ if not (min(doses) < gate.threshold < max(doses)):
107
+ return {**out, "validation": _verdict(False, "does_not_bracket_gate",
108
+ f"the ladder {ladder['concentrations'][0]} to {ladder['concentrations'][-1]} "
109
+ f"does not bracket the gate at {gate.threshold:g} uM")}
110
+ if ctx["runs_left"] < 1:
111
+ return {**out, "validation": _verdict(False, "no_budget", "no lab runs remain in the budget")}
112
+ if not applied and ladder is None:
113
+ # nothing about the test would change: the lab ignores a replicate request and no ladder applies. That is the same
114
+ # run again, paid for twice
115
+ return {**out, "validation": _verdict(False, "no_change", "this lab ignores replicate requests and the gate's metric takes "
116
+ "no dose ladder, so the follow-up would repeat the same test")}
117
+ if ctx.get("hyp_room") is not None and ctx["hyp_room"] < 1:
118
+ return {**out, "validation": _verdict(False, "no_hypothesis_budget", "the campaign is at its hypothesis limit")}
119
+ ctx["runs_left"] -= 1 # each valid follow-up spends a run, so a second one cannot claim the same last run
120
+ if ctx.get("hyp_room") is not None:
121
+ ctx["hyp_room"] -= 1
122
+ reasons = [] if applied else ["this lab does not take a replicate request: the ladder is followed up, replicates stay as the lab runs them"]
123
+ return {**out, "executes": True,
124
+ "params": {"replicates": reps if applied else None, "replicates_requested": reps, "replicates_applied": applied,
125
+ "concentrations": ladder["concentrations"] if ladder else None, "why": (ladder or {}).get("why", "")},
126
+ "validation": _verdict(True, "ok", *reasons)}
proef/governance.py ADDED
@@ -0,0 +1,290 @@
1
+ """Execution governance — the parts of the harness the agent cannot reach.
2
+
3
+ Four structural guarantees, all enforced in gateway code OUTSIDE the agent's
4
+ tool surface (the Run-Data-Run critique: prose safety is suggestion; code
5
+ safety is physics):
6
+
7
+ 1. AuthorizationMatrix — an explicit three-column rulebook
8
+ (autonomous | human-required | never), evaluated per submission.
9
+ Default columns cover BSL, dual-use text, and recurring (SOP-class)
10
+ protocols; operators extend via a JSON file (PROEF_AUTHZ).
11
+ 2. HaltSwitch — a kill switch on the filesystem. Engaged by a human
12
+ (`proef halt`), checked by the gateway on EVERY submission, cleared only by
13
+ a human (`proef halt --clear`). The agent has no tool that touches it.
14
+ 3. SopRegistry — anything flagged `recurring` (run unattended on future
15
+ samples) is treated as a standard operating procedure: it needs
16
+ human sign-off before it runs at all, and the approval is recorded.
17
+ One-off commands can be fast; procedures get review, like code.
18
+ 4. Every governance decision is a provenance event — the audit answers
19
+ "what did the harness allow, refuse, or escalate, and why", not just
20
+ "runtime error, retried".
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import json
26
+ import time
27
+ import uuid
28
+ from pathlib import Path
29
+ from typing import Any
30
+
31
+ from proef.adapters.bio.tox_alerts import durc_screen
32
+
33
+ HALT_FILE = Path(".data/HALT")
34
+ HALT_HISTORY = Path(".data/HALT-history.json")
35
+ PAUSES_FILE = Path(".data/PAUSES.json")
36
+ PAUSES_HISTORY = Path(".data/PAUSES-history.json")
37
+ SOPS_FILE = Path(".data/sops.json")
38
+ AUTHZ_ENV = "PROEF_AUTHZ"
39
+
40
+
41
+ def execution_governance() -> dict:
42
+ """The governance bundle every gateway needs: kill switch +
43
+ authorization matrix, constructed from current defaults/env config.
44
+
45
+ Governance is not optional at ANY surface: an agent that reaches the
46
+ gateway via MCP or the CLI is subject to the same physics as a
47
+ campaign. Any LabGateway built outside `run_campaign` SHOULD pass
48
+ `governance=execution_governance()`."""
49
+ return {"matrix": AuthorizationMatrix(), "halt": HaltSwitch()}
50
+
51
+
52
+ # ------------------------------------------------------------ halt switch
53
+
54
+ class HaltSwitch:
55
+ """Clearing is recorded too: a halt that leaves no trace once lifted
56
+ would hide exactly the episode an audit needs to see."""
57
+
58
+ def __init__(self, path: Path | None = None,
59
+ history_path: Path | None = None):
60
+ self.path = path or HALT_FILE
61
+ self.history_path = history_path or HALT_HISTORY
62
+
63
+ def engaged(self) -> dict | None:
64
+ if self.path.exists():
65
+ try:
66
+ return json.loads(self.path.read_text())
67
+ except Exception:
68
+ return {"reason": "manual halt"}
69
+ return None
70
+
71
+ def history(self, limit: int = 10) -> list[dict]:
72
+ try:
73
+ h = json.loads(self.history_path.read_text())
74
+ return h[-limit:]
75
+ except Exception:
76
+ return []
77
+
78
+ def engage(self, reason: str = "operator halt") -> dict:
79
+ entry = {"reason": reason, "ts": time.time(),
80
+ "id": f"halt-{uuid.uuid4().hex[:6]}"}
81
+ self.path.parent.mkdir(parents=True, exist_ok=True)
82
+ self.path.write_text(json.dumps(entry, indent=1))
83
+ return entry
84
+
85
+ def clear(self, by: str = "operator") -> bool:
86
+ if not self.path.exists():
87
+ return False
88
+ try:
89
+ entry = json.loads(self.path.read_text())
90
+ except Exception:
91
+ entry = {"reason": "manual halt"}
92
+ entry["cleared_ts"] = time.time()
93
+ entry["cleared_by"] = by
94
+ hist: list = []
95
+ try:
96
+ hist = json.loads(self.history_path.read_text())
97
+ except Exception:
98
+ pass
99
+ # the history file has its OWN parent directory (a custom halt path with the default history path puts them in different places); create the one we write to
100
+ self.history_path.parent.mkdir(parents=True, exist_ok=True)
101
+ self.history_path.write_text(
102
+ json.dumps(hist + [entry], indent=1))
103
+ self.path.unlink()
104
+ return True
105
+
106
+
107
+ # ----------------------------------------------------------- pauses
108
+
109
+ class PauseRegistry:
110
+ """A routine, scoped pause: one program, or one campaign. Unlike the HaltSwitch (global, an emergency stop that
111
+ REFUSES submissions) a pause HOLDS them: the campaign waits at the lab gateway and carries on when it is resumed,
112
+ so a pause never burns a campaign's rounds. Running plates finish. Every pause and resume is kept in a history.
113
+
114
+ Scopes are strings: "program:<slug>" or "campaign:<problem id>"."""
115
+
116
+ def __init__(self, path: Path | None = None, history_path: Path | None = None):
117
+ self.path = path or PAUSES_FILE
118
+ self.history_path = history_path or PAUSES_HISTORY
119
+
120
+ def active(self) -> dict[str, dict]:
121
+ try:
122
+ d = json.loads(self.path.read_text())
123
+ return d if isinstance(d, dict) else {}
124
+ except Exception:
125
+ return {}
126
+
127
+ def _save(self, d: dict) -> None:
128
+ self.path.parent.mkdir(parents=True, exist_ok=True)
129
+ self.path.write_text(json.dumps(d, indent=1))
130
+
131
+ def pause(self, scope: str, reason: str = "", by: str = "operator") -> dict:
132
+ d = self.active()
133
+ entry = d.get(scope) or {"scope": scope, "reason": reason, "by": by, "ts": time.time(),
134
+ "id": f"pause-{uuid.uuid4().hex[:6]}"}
135
+ d[scope] = entry # pausing twice keeps the first pause (who and why)
136
+ self._save(d)
137
+ return entry
138
+
139
+ def resume(self, scope: str, by: str = "operator") -> bool:
140
+ d = self.active()
141
+ entry = d.pop(scope, None)
142
+ if entry is None:
143
+ return False
144
+ entry = {**entry, "resumed_ts": time.time(), "resumed_by": by}
145
+ try:
146
+ hist = json.loads(self.history_path.read_text())
147
+ except Exception:
148
+ hist = []
149
+ self.history_path.parent.mkdir(parents=True, exist_ok=True)
150
+ self.history_path.write_text(json.dumps(hist + [entry], indent=1))
151
+ self._save(d)
152
+ return True
153
+
154
+ def history(self, limit: int = 20) -> list[dict]:
155
+ try:
156
+ return json.loads(self.history_path.read_text())[-limit:]
157
+ except Exception:
158
+ return []
159
+
160
+ def blocking(self, problem_id: str | None, program: str | None) -> dict | None:
161
+ """The pause that holds this campaign, if any: its own first, then its program's."""
162
+ d = self.active()
163
+ if problem_id and f"campaign:{problem_id}" in d:
164
+ return d[f"campaign:{problem_id}"]
165
+ if program and f"program:{program}" in d:
166
+ return d[f"program:{program}"]
167
+ return None
168
+
169
+
170
+ # -------------------------------------------------------- sop registry
171
+
172
+ class SopRegistry:
173
+ def __init__(self, path: Path | None = None):
174
+ self.path = path or SOPS_FILE
175
+
176
+ def _load(self) -> dict:
177
+ try:
178
+ return json.loads(self.path.read_text())
179
+ except Exception:
180
+ return {}
181
+
182
+ @staticmethod
183
+ def sop_id(protocol) -> str:
184
+ basis = "|".join([str(protocol.assay_type),
185
+ ",".join(sorted(str(s.op) for s in protocol.steps)),
186
+ protocol.title.split("-")[0]])
187
+ return "sop-" + hashlib.sha1(basis.encode()).hexdigest()[:8] # noqa: S324
188
+
189
+ def propose(self, protocol) -> str:
190
+ sid = self.sop_id(protocol)
191
+ reg = self._load()
192
+ if sid not in reg:
193
+ reg[sid] = {"status": "pending", "objective": protocol.title,
194
+ "assay": str(protocol.assay_type),
195
+ "proposed_ts": time.time(),
196
+ "samples_seen": [s.sample_id
197
+ for s in protocol.samples[:5]]}
198
+ self.path.parent.mkdir(parents=True, exist_ok=True)
199
+ self.path.write_text(json.dumps(reg, indent=1))
200
+ return sid
201
+
202
+ def approved(self, sid: str) -> bool:
203
+ return self._load().get(sid, {}).get("status") == "approved"
204
+
205
+ def approve(self, sid: str, by: str = "operator") -> bool:
206
+ reg = self._load()
207
+ if sid not in reg:
208
+ return False
209
+ reg[sid].update(status="approved", approved_by=by,
210
+ approved_ts=time.time())
211
+ self.path.write_text(json.dumps(reg, indent=1))
212
+ return True
213
+
214
+ def pending(self) -> list[dict]:
215
+ return [dict(v, id=k) for k, v in self._load().items()
216
+ if v.get("status") == "pending"]
217
+
218
+
219
+ # --------------------------------------------------- authorization matrix
220
+
221
+ class AuthorizationMatrix:
222
+ """Three columns: autonomous | human | never. Checked in order; first
223
+ match decides. Defaults encode today's sane policy; a JSON file
224
+ (env PROEF_AUTHZ) can add rules: [{"name", "assay", "min_bsl",
225
+ "recurring", "text", "column"}]."""
226
+
227
+ def __init__(self, config_path: str | Path | None = None):
228
+ self.extra: list[dict] = []
229
+ path = (config_path or __import__("os").environ.get(AUTHZ_ENV, ""))
230
+ if path and Path(path).exists():
231
+ self.extra = json.loads(Path(path).read_text())
232
+ self.sops = SopRegistry()
233
+
234
+ # the standing policy, in the order classify() applies it — kept beside the
235
+ # code so the workbench shows what the gate really does (a test pins them)
236
+ DEFAULT_POLICY = (
237
+ ("never", "Dual-use (DURC) content: a select agent or regulated toxin"),
238
+ ("never", "Biosafety level 3 or higher"),
239
+ ("human", "Biosafety level 2 material needs a named approval"),
240
+ ("human", "A recurring procedure, until a human signs off its SOP"),
241
+ ("autonomous", "Everything else, within the safety gate"),
242
+ )
243
+
244
+ def describe(self) -> list[dict]:
245
+ """Operator-added rules first (they win), then the standing policy."""
246
+ rules = [{"column": r.get("column", "human"),
247
+ "when": r.get("text") or r.get("name", "custom rule"),
248
+ "custom": True} for r in self.extra]
249
+ return rules + [{"column": c, "when": w, "custom": False}
250
+ for c, w in self.DEFAULT_POLICY]
251
+
252
+ def classify(self, protocol) -> tuple[str, str]:
253
+ """-> (column, reason)."""
254
+ blob = " ".join([protocol.title]
255
+ + [s.sample_id for s in protocol.samples]
256
+ + [r.name for r in protocol.reagents])
257
+ max_bsl = max([r.bsl_level for r in protocol.reagents] or [0])
258
+ recurring = bool((protocol.constraints or {}).get("recurring"))
259
+ for rule in self.extra:
260
+ if self._matches(rule, protocol, max_bsl, recurring):
261
+ return rule.get("column", "human"), f"rule '{rule.get('name', '?')}'"
262
+ if durc_screen(blob):
263
+ return ("never",
264
+ "dual-use content: " + ", ".join(durc_screen(blob))[:80])
265
+ if max_bsl >= 3:
266
+ return "never", f"BSL-{max_bsl} work is outside program scope"
267
+ if max_bsl >= 2:
268
+ return "human", f"BSL-{max_bsl} material requires named approval"
269
+ if recurring:
270
+ sid = self.sops.sop_id(protocol)
271
+ if self.sops.approved(sid):
272
+ return "autonomous", f"SOP {sid} signed off"
273
+ self.sops.propose(protocol)
274
+ return ("human",
275
+ f"recurring procedure needs SOP sign-off ({sid})")
276
+ return "autonomous", "within standing policy"
277
+
278
+ @staticmethod
279
+ def _matches(rule: dict, protocol, max_bsl: int, recurring: bool) -> bool:
280
+ if "assay" in rule and str(protocol.assay_type) != rule["assay"]:
281
+ return False
282
+ if "min_bsl" in rule and max_bsl < rule["min_bsl"]:
283
+ return False
284
+ if "recurring" in rule and bool(recurring) != rule["recurring"]:
285
+ return False
286
+ if "text" in rule and rule["text"].lower() not in json.dumps(
287
+ [protocol.title, [s.sample_id for s in protocol.samples]]
288
+ ).lower():
289
+ return False
290
+ return True