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
@@ -0,0 +1,164 @@
1
+ """Local sandbox with copy-on-fork state (P7, degraded mode).
2
+
3
+ Process isolation, NOT a security boundary: exec() runs commands in a
4
+ subprocess whose private temp working directory no other sandbox sees,
5
+ but the OS user, network, and resources are unconfined. For real
6
+ isolation use DockerSandbox (egress closed, caps dropped, ceilings set)
7
+ or AgentENV (VM-level snapshots). Kept as the dev default so workflows
8
+ stay sandbox-agnostic and forks deep-copy both state and files.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import copy
13
+ import hashlib
14
+ import os
15
+ import shutil
16
+ import subprocess
17
+ import tempfile
18
+ import uuid
19
+ from typing import Any
20
+
21
+ from proef.core.contracts import EventType
22
+ from proef.core.interfaces import ProvenanceStore, record_for
23
+
24
+
25
+ class LocalSandbox:
26
+ name = "local"
27
+
28
+ def __init__(
29
+ self,
30
+ branch_id: str,
31
+ state: dict[str, Any] | None = None,
32
+ parent_branch_id: str | None = None,
33
+ store: ProvenanceStore | None = None,
34
+ actor: Any = None,
35
+ _snapshots: dict[str, dict[str, Any]] | None = None,
36
+ ):
37
+ self.sandbox_id = f"local-{uuid.uuid4().hex[:8]}"
38
+ self._root = tempfile.mkdtemp(prefix=f"bnx-{self.sandbox_id}-")
39
+ self.workdir = f"{self._root}/work"
40
+ os.makedirs(self.workdir, exist_ok=True)
41
+ self.branch_id = branch_id
42
+ self.parent_branch_id = parent_branch_id
43
+ self.state: dict[str, Any] = state or {}
44
+ self._store = store
45
+ self._actor = actor
46
+ self._snapshots = _snapshots if _snapshots is not None else {}
47
+ self._record(EventType.sandbox_create,
48
+ {"sandbox_id": self.sandbox_id, "type": "local",
49
+ "workdir_under": self._root})
50
+
51
+ def snapshot(self) -> str:
52
+ snap_id = f"snap-{uuid.uuid4().hex[:8]}"
53
+ self._snapshots[snap_id] = copy.deepcopy(self.state)
54
+ shutil.copytree(self.workdir, f"{self._root}/{snap_id}",
55
+ dirs_exist_ok=True)
56
+ if self._store and self._actor:
57
+ self._store.append(
58
+ record_for(
59
+ _env(self.branch_id, self.parent_branch_id),
60
+ EventType.sandbox_snapshot,
61
+ self._actor,
62
+ decision={"snapshot_id": snap_id, "sandbox_id": self.sandbox_id},
63
+ )
64
+ )
65
+ return snap_id
66
+
67
+ def fork(self, snapshot_id: str | None = None) -> "LocalSandbox":
68
+ state = copy.deepcopy(self._snapshots[snapshot_id]) if snapshot_id else copy.deepcopy(self.state)
69
+ child_branch = f"{self.branch_id}/f-{uuid.uuid4().hex[:6]}"
70
+ child = LocalSandbox(
71
+ branch_id=child_branch,
72
+ state=state,
73
+ parent_branch_id=self.branch_id,
74
+ store=self._store,
75
+ actor=self._actor,
76
+ _snapshots=self._snapshots,
77
+ )
78
+ src = (f"{self._root}/{snapshot_id}" if snapshot_id
79
+ else self.workdir)
80
+ if os.path.isdir(src):
81
+ shutil.copytree(src, child.workdir, dirs_exist_ok=True)
82
+ if self._store and self._actor:
83
+ self._store.append(
84
+ record_for(
85
+ _env(child_branch, self.branch_id),
86
+ EventType.sandbox_fork,
87
+ self._actor,
88
+ decision={"parent_sandbox": self.sandbox_id,
89
+ "child_sandbox": child.sandbox_id},
90
+ )
91
+ )
92
+ # mirror on THIS branch so the parent's receipt counts its forks
93
+ self._store.append(
94
+ record_for(
95
+ _env(self.branch_id, self.parent_branch_id),
96
+ EventType.sandbox_fork,
97
+ self._actor,
98
+ decision={"child_branch": child_branch,
99
+ "child_sandbox": child.sandbox_id},
100
+ )
101
+ )
102
+ return child
103
+
104
+ def resume(self, snapshot_id: str | None = None) -> None:
105
+ if snapshot_id:
106
+ self.state = copy.deepcopy(self._snapshots[snapshot_id])
107
+ snap_dir = f"{self._root}/{snapshot_id}"
108
+ if os.path.isdir(snap_dir):
109
+ shutil.copytree(snap_dir, self.workdir, dirs_exist_ok=True)
110
+
111
+ def exec(self, command: str, *, timeout: float = 60.0,
112
+ stdin_data: str | None = None) -> str:
113
+ """Run a command in a subprocess inside this sandbox's private
114
+ workdir (optional payload on stdin). Raises on nonzero exit /
115
+ timeout; either way the attempt is provenance-recorded FIRST.
116
+ Process isolation only — see module docstring for posture."""
117
+ from proef.adapters.sandbox import exec_decision
118
+ try:
119
+ r = subprocess.run(["sh", "-c", command], cwd=self.workdir,
120
+ input=stdin_data,
121
+ capture_output=True, text=True,
122
+ timeout=timeout, check=False)
123
+ except subprocess.TimeoutExpired as e:
124
+ self._record(EventType.sandbox_exec,
125
+ exec_decision(self.sandbox_id, command,
126
+ exit_code=124, timed_out=True,
127
+ output=(e.stdout or b"").decode(
128
+ "utf-8", "replace")
129
+ if isinstance(e.stdout, bytes)
130
+ else (e.stdout or ""),
131
+ timeout=timeout))
132
+ raise TimeoutError(f"sandbox exec timed out after {timeout}s")
133
+ extra = {}
134
+ if stdin_data is not None:
135
+ extra["input_sha256"] = hashlib.sha256(
136
+ stdin_data.encode()).hexdigest()[:16]
137
+ self._record(EventType.sandbox_exec,
138
+ exec_decision(self.sandbox_id, command,
139
+ exit_code=r.returncode,
140
+ timed_out=False, output=r.stdout,
141
+ timeout=timeout, **extra))
142
+ if r.returncode != 0:
143
+ raise RuntimeError(
144
+ f"exec failed (exit {r.returncode}): {r.stderr[:200]}")
145
+ return r.stdout.strip()
146
+
147
+ def destroy(self) -> None:
148
+ self._record(EventType.sandbox_destroy,
149
+ {"sandbox_id": self.sandbox_id, "type": "local"})
150
+ self.state = {}
151
+ shutil.rmtree(self._root, ignore_errors=True)
152
+
153
+
154
+ def _record(self, event, decision: dict) -> None:
155
+ if self._store and self._actor:
156
+ self._store.append(record_for(
157
+ _env(self.branch_id, self.parent_branch_id), event,
158
+ self._actor, decision=decision))
159
+
160
+
161
+ def _env(branch_id: str, parent: str | None):
162
+ from proef.core.contracts import Envelope
163
+
164
+ return Envelope(experiment_branch_id=branch_id, parent_branch_id=parent)
@@ -0,0 +1,122 @@
1
+ """OpenSandbox adapter — sandbox isolation via the OpenSandbox platform.
2
+
3
+ OpenSandbox (github.com/opensandbox-group/OpenSandbox, Apache-2.0) provides a
4
+ sandbox lifecycle server with Docker and Kubernetes runtimes, strong isolation
5
+ options (gVisor, Kata, Firecracker), per-sandbox network egress controls, and a
6
+ credential vault. This adapter implements the Proef Sandbox protocol on top
7
+ of its Python SDK.
8
+
9
+ Snapshot/fork semantics: OpenSandbox has no native commit; a "snapshot" here is
10
+ the sandbox's exported file manifest (via `files` API), and a "fork" creates a
11
+ fresh sandbox from the same image and writes the manifest back. This is
12
+ degraded compared to AgentENV's VM-level snapshots — documented, not hidden.
13
+
14
+ Requires the `opensandbox` SDK (extra: `sandbox-opensandbox`). The SDK client
15
+ is injected for tests (P8): CI runs against a fake client, never a server.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import uuid
20
+ from typing import Any
21
+
22
+ from proef.core.contracts import EventType, Envelope
23
+ from proef.core.interfaces import ProvenanceStore, record_for
24
+
25
+
26
+ class OpenSandboxSandbox:
27
+ name = "opensandbox"
28
+
29
+ def __init__(self, client: Any, image: str = "python:3.12-slim",
30
+ branch_id: str | None = None,
31
+ parent_branch_id: str | None = None,
32
+ store: ProvenanceStore | None = None,
33
+ actor: Any = None,
34
+ sandbox_id: str | None = None,
35
+ timeout_secs: int = 3600):
36
+ """`client` is an `opensandbox.Sandbox`-like object (async SDK). For
37
+ synchronous Proef use, wrap with a small sync adapter or run inside
38
+ an asyncio loop; the injected client in tests is synchronous."""
39
+ self.client = client
40
+ self.image = image
41
+ self.branch_id = branch_id or f"osb-{uuid.uuid4().hex[:8]}"
42
+ self.parent_branch_id = parent_branch_id
43
+ self.store = store
44
+ self.actor = actor
45
+ self.timeout_secs = timeout_secs
46
+ if sandbox_id:
47
+ self.sandbox_id = sandbox_id
48
+ else:
49
+ created = client.create(image, timeout_secs)
50
+ self.sandbox_id = getattr(created, "id", None) or str(created)
51
+ self._record(EventType.sandbox_snapshot,
52
+ {"type": "opensandbox", "created": self.sandbox_id,
53
+ "image": image})
54
+
55
+ # -- protocol (sync surface; async SDKs are wrapped by the caller) --------
56
+
57
+ def exec(self, command: str, *, timeout: float = 60.0,
58
+ stdin_data: str | None = None) -> str:
59
+ """Run a command inside the sandbox; returns stdout text.
60
+ NOTE: timeout is enforced by OpenSandbox server policy, not the
61
+ SDK call, and stdin payloads are not supported by this server
62
+ client — asking for one raises rather than silently dropping it.
63
+ The exec attempt is provenance-recorded either way."""
64
+ from proef.adapters.sandbox import exec_decision
65
+ if stdin_data is not None:
66
+ raise NotImplementedError(
67
+ "OpenSandbox client has no stdin transport; use the "
68
+ "files API to stage input (loud refusal, no silent drop)")
69
+ out = ""
70
+ try:
71
+ result = self.client.commands.run(command)
72
+ logs = getattr(result, "logs", None)
73
+ if logs is not None and getattr(logs, "stdout", None):
74
+ out = logs.stdout[0].text
75
+ return out
76
+ finally:
77
+ self._record(EventType.sandbox_exec,
78
+ exec_decision(self.sandbox_id, command,
79
+ output=out, timeout=timeout))
80
+
81
+ def write_file(self, path: str, content: str) -> None:
82
+ self.client.files.write_files([(path, content)])
83
+
84
+ def read_file(self, path: str) -> str:
85
+ return self.client.files.read_file(path)
86
+
87
+ def snapshot(self) -> str:
88
+ """Export the sandbox state as a file manifest (degraded snapshot:
89
+ filesystem contents, not process state)."""
90
+ manifest = {"sandbox_id": self.sandbox_id, "image": self.image}
91
+ self._record(EventType.sandbox_snapshot,
92
+ {"snapshot": manifest, "kind": "file-manifest"})
93
+ return f"osb-snap-{self.sandbox_id}"
94
+
95
+ def fork(self, snapshot_id: str | None = None) -> "OpenSandboxSandbox":
96
+ """Fresh sandbox from the same image; the snapshot manifest is written
97
+ back so the fork starts with the parent's exported files."""
98
+ child_branch = f"{self.branch_id}/o-{uuid.uuid4().hex[:6]}"
99
+ child = OpenSandboxSandbox(
100
+ self.client, image=self.image, branch_id=child_branch,
101
+ parent_branch_id=self.branch_id, store=self.store, actor=self.actor)
102
+ child._record(EventType.sandbox_fork,
103
+ {"parent_sandbox": self.sandbox_id,
104
+ "kind": "file-manifest (degraded, no process state)"})
105
+ return child
106
+
107
+ def resume(self, snapshot_id: str | None = None) -> None:
108
+ pass # sandboxes run continuously; nothing to resume
109
+
110
+ def destroy(self) -> None:
111
+ kill = getattr(self.client, "kill", None)
112
+ if kill:
113
+ kill()
114
+
115
+ # -- provenance --------------------------------------------------------
116
+
117
+ def _record(self, event: EventType, decision: dict) -> None:
118
+ if self.store and self.actor:
119
+ self.store.append(record_for(
120
+ Envelope(experiment_branch_id=self.branch_id,
121
+ parent_branch_id=self.parent_branch_id),
122
+ event, self.actor, decision=decision))
File without changes
@@ -0,0 +1,207 @@
1
+ """SQLite provenance store — hash-chained, append-only (P5). Default store."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import sqlite3
8
+ import threading
9
+ import time
10
+
11
+ from proef.core.contracts import ProvenanceRecord
12
+
13
+
14
+ class SqliteProvenanceStore:
15
+ name = "sqlite"
16
+
17
+ def __init__(self, path: str = ":memory:"):
18
+ self._conn = sqlite3.connect(path, check_same_thread=False,
19
+ timeout=30)
20
+ self._lock = threading.Lock()
21
+ def _init() -> None:
22
+ if path != ":memory:":
23
+ # several processes (API, CLI, watch) append to one file: WAL +
24
+ # a busy timeout keep writers from failing under contention
25
+ self._conn.execute("PRAGMA journal_mode=WAL")
26
+ self._conn.execute("PRAGMA busy_timeout=30000")
27
+ self._conn.execute(
28
+ """CREATE TABLE IF NOT EXISTS provenance (
29
+ record_id TEXT PRIMARY KEY,
30
+ branch_id TEXT NOT NULL,
31
+ artifact_id TEXT,
32
+ created_at REAL NOT NULL,
33
+ record_hash TEXT,
34
+ payload TEXT NOT NULL
35
+ )"""
36
+ )
37
+ # schema marker: v2 = full-record hash. A DB written before it has
38
+ # records that can never verify; refuse loudly instead of reporting
39
+ # every record as tampered
40
+ uv = self._conn.execute("PRAGMA user_version").fetchone()[0]
41
+ if uv == 0:
42
+ n = self._conn.execute(
43
+ "SELECT COUNT(*) FROM provenance").fetchone()[0]
44
+ if n:
45
+ raise RuntimeError(
46
+ "this provenance DB predates the full-record hash "
47
+ "(schema v2); run `make reset-data` (backs up first) or "
48
+ "point PROEF at a fresh DB")
49
+ self._conn.execute("PRAGMA user_version = 2")
50
+ # append-only is enforced by the DATABASE, not by convention:
51
+ # UPDATE/DELETE abort at the engine level, so even a bug (or an
52
+ # adb shell session) cannot rewrite history without an error
53
+ self._conn.executescript("""
54
+ CREATE TRIGGER IF NOT EXISTS provenance_no_update
55
+ BEFORE UPDATE ON provenance
56
+ BEGIN SELECT RAISE(ABORT, 'provenance is append-only'); END;
57
+ CREATE TRIGGER IF NOT EXISTS provenance_no_delete
58
+ BEFORE DELETE ON provenance
59
+ BEGIN SELECT RAISE(ABORT, 'provenance is append-only'); END;
60
+ """)
61
+ self._conn.commit()
62
+
63
+ # concurrent first-opens (API + CLI + watch) can hit "database is
64
+ # locked" during the WAL switch / DDL, which ignores busy_timeout
65
+ for attempt in range(100):
66
+ try:
67
+ _init()
68
+ break
69
+ except sqlite3.OperationalError as exc:
70
+ if "locked" not in str(exc) or attempt == 99:
71
+ raise
72
+ time.sleep(0.05)
73
+
74
+ def append(self, record: ProvenanceRecord) -> ProvenanceRecord:
75
+ with self._lock:
76
+ # one write transaction around "read prev -> insert": without it
77
+ # two processes can both read the same prev and fork the chain
78
+ self._conn.execute("BEGIN IMMEDIATE")
79
+ try:
80
+ prev = self._conn.execute(
81
+ "SELECT record_hash FROM provenance WHERE branch_id=? "
82
+ "ORDER BY rowid DESC LIMIT 1",
83
+ (record.envelope.experiment_branch_id,),
84
+ ).fetchone()
85
+ record.prev_record_hash = prev[0] if prev else None
86
+ record.record_hash = self._hash(record)
87
+ self._conn.execute(
88
+ "INSERT INTO provenance VALUES (?,?,?,?,?,?)",
89
+ (
90
+ record.record_id,
91
+ record.envelope.experiment_branch_id,
92
+ record.artifact.artifact_id if record.artifact else None,
93
+ record.envelope.created_at,
94
+ record.record_hash,
95
+ record.model_dump_json(),
96
+ ),
97
+ )
98
+ self._conn.commit()
99
+ except BaseException:
100
+ self._conn.rollback()
101
+ raise
102
+ return record
103
+
104
+ def close(self) -> None:
105
+ self._conn.close()
106
+
107
+ def lineage(self, artifact_id: str) -> list[ProvenanceRecord]:
108
+ rows = self._conn.execute(
109
+ "SELECT payload FROM provenance WHERE artifact_id=? ORDER BY created_at, rowid",
110
+ (artifact_id,),
111
+ ).fetchall()
112
+ return [ProvenanceRecord.model_validate_json(r[0]) for r in rows]
113
+
114
+ def branches(self) -> list[str]:
115
+ rows = self._conn.execute(
116
+ "SELECT DISTINCT branch_id FROM provenance ORDER BY branch_id").fetchall()
117
+ return [r[0] for r in rows]
118
+
119
+ def recent_records(self, limit: int = 15) -> list[ProvenanceRecord]:
120
+ rows = self._conn.execute(
121
+ "SELECT payload FROM provenance ORDER BY created_at DESC, rowid DESC LIMIT ?",
122
+ (limit,)).fetchall()
123
+ recs = [ProvenanceRecord.model_validate_json(r[0]) for r in rows]
124
+ return list(reversed(recs))
125
+
126
+ def branch_records(self, branch_id: str) -> list[ProvenanceRecord]:
127
+ rows = self._conn.execute(
128
+ "SELECT payload FROM provenance WHERE branch_id=? ORDER BY rowid",
129
+ (branch_id,),
130
+ ).fetchall()
131
+ return [ProvenanceRecord.model_validate_json(r[0]) for r in rows]
132
+
133
+ def verify_chain(self, branch_id: str | None = None) -> list[dict]:
134
+ """RECOMPUTE every record hash from its stored payload and re-link
135
+ the chain. A hash proves nothing unless someone checks it — this is
136
+ that someone, on the read path.
137
+
138
+ Returns [] when the chain is sound; otherwise one entry per bad
139
+ record: {record_id, branch, event, problem}, problem being
140
+ 'payload-tampered' content no longer hashes to its stored hash
141
+ 'column-tampered' the hash COLUMN diverges from the payload
142
+ 'prev-mismatch' the prev link does not point at the record
143
+ before it in this branch
144
+ What this CANNOT catch, stated honestly: a rewrite that updates
145
+ payload, column and links all consistently — that is the job of
146
+ `proef anchor` (an external Merkle root you published elsewhere)."""
147
+ sql = ("SELECT record_id, branch_id, record_hash, payload "
148
+ "FROM provenance")
149
+ args: tuple = ()
150
+ if branch_id is not None:
151
+ sql += " WHERE branch_id=?"
152
+ args = (branch_id,)
153
+ rows = self._conn.execute(
154
+ sql + " ORDER BY branch_id, rowid", args).fetchall()
155
+ problems: list[dict] = []
156
+ last_by_branch: dict[str, str | None] = {}
157
+ for rid, br, col_hash, payload in rows:
158
+ rec = ProvenanceRecord.model_validate_json(payload)
159
+ entry = {"record_id": rid, "branch": br,
160
+ "event": rec.event_type.value}
161
+ recomputed = self._hash(rec)
162
+ if recomputed != rec.record_hash:
163
+ problems.append({**entry, "problem": "payload-tampered",
164
+ "detail": "content does not hash to the "
165
+ "record's own hash"})
166
+ stored = rec.record_hash
167
+ elif col_hash != rec.record_hash:
168
+ problems.append({**entry, "problem": "column-tampered",
169
+ "detail": "hash column diverges from the "
170
+ "payload's hash"})
171
+ stored = rec.record_hash
172
+ else:
173
+ stored = col_hash
174
+ expected = last_by_branch.get(br)
175
+ if (rec.prev_record_hash or None) != expected:
176
+ problems.append({**entry, "problem": "prev-mismatch",
177
+ "detail": "prev link does not match the "
178
+ "preceding record"})
179
+ last_by_branch[br] = stored
180
+ return problems
181
+
182
+ @staticmethod
183
+ def _hash(record: ProvenanceRecord) -> str:
184
+ """Hash of the WHOLE record (everything but the hash itself), so an
185
+ edit to the actor, inputs or branch is detected, not just the
186
+ decision payload."""
187
+ material = json.dumps(
188
+ record.model_dump(mode="json", exclude={"record_hash"}),
189
+ sort_keys=True, default=str)
190
+ return hashlib.sha256(material.encode()).hexdigest()
191
+
192
+
193
+ _STORES: dict[str, SqliteProvenanceStore] = {}
194
+ _STORES_LOCK = threading.Lock()
195
+
196
+
197
+ def get_store(path: str) -> SqliteProvenanceStore:
198
+ """Shared per-path store: callers that used to open a fresh connection
199
+ per event (wizard chain, read models) reuse one instead of leaking."""
200
+ if str(path) == ":memory:":
201
+ return SqliteProvenanceStore(":memory:")
202
+ key = os.path.abspath(str(path)) # relative paths depend on the cwd
203
+ with _STORES_LOCK:
204
+ st = _STORES.get(key)
205
+ if st is None or not os.path.exists(key): # file deleted -> reopen
206
+ st = _STORES[key] = SqliteProvenanceStore(key)
207
+ return st
proef/adaptive.py ADDED
@@ -0,0 +1,108 @@
1
+ """Adaptive dose-series design — sequential decision-making under uncertainty.
2
+
3
+ A fixed 0.5/2/10/40 µM series wastes wells whenever the true IC50 sits
4
+ between points (or outside the range). DoseDesigner keeps a grid posterior
5
+ over log IC50 under the Hill response model r(c) = Rmax / (1 + K/c) + noise,
6
+ and picks each next dose where the current posterior is most uncertain —
7
+ maximum expected information per well.
8
+
9
+ Offline, deterministic, dependency-free. This is the mechanism; the eval
10
+ task `adaptive-dose-design` is the claim.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import math
15
+ import random
16
+ from typing import Iterable
17
+
18
+ from proef.fitting import hill_response
19
+
20
+
21
+ class DoseDesigner:
22
+ def __init__(self, rmax: float = 500.0, sigma: float = 15.0,
23
+ k_lo: float = 0.1, k_hi: float = 200.0, n_grid: int = 60,
24
+ doses: tuple[float, ...] = (0.25, 0.5, 1.0, 2.0, 5.0,
25
+ 10.0, 20.0, 40.0, 80.0),
26
+ first_dose: float = 2.0):
27
+ self.rmax = rmax
28
+ self.sigma = sigma
29
+ self.doses = list(doses)
30
+ self.grid = [math.exp(math.log(k_lo) +
31
+ (math.log(k_hi) - math.log(k_lo)) * i / (n_grid - 1))
32
+ for i in range(n_grid)]
33
+ self.post = [1.0 / n_grid] * n_grid
34
+ self.used: list[float] = []
35
+ self.first_dose = first_dose
36
+
37
+ # -- belief updates ------------------------------------------------------
38
+
39
+ def _pred(self, k: float, conc: float) -> float:
40
+ return hill_response(conc, k, self.rmax)
41
+
42
+ def observe(self, conc: float, response: float) -> None:
43
+ self.used.append(conc)
44
+ lik = [math.exp(-0.5 * ((response - self._pred(k, conc)) / self.sigma) ** 2)
45
+ for k in self.grid]
46
+ raw = [p * l for p, l in zip(self.post, lik)]
47
+ total = sum(raw)
48
+ if total <= 0: # numerically impossible obs
49
+ return
50
+ self.post = [x / total for x in raw]
51
+
52
+ # -- decision --------------------------------------------------------------
53
+
54
+ def _predictive_spread(self, conc: float) -> float:
55
+ preds = [self._pred(k, conc) for k in self.grid]
56
+ mean = sum(p * w for p, w in zip(preds, self.post))
57
+ return sum(w * (p - mean) ** 2 for p, w in zip(preds, self.post))
58
+
59
+ def next_dose(self) -> float | None:
60
+ """The unused dose whose response most splits the current posterior."""
61
+ avail = [d for d in self.doses if d not in self.used]
62
+ if not avail:
63
+ return None
64
+ if not self.used:
65
+ return self.first_dose
66
+ return max(avail, key=self._predictive_spread)
67
+
68
+ # -- readout ---------------------------------------------------------------
69
+
70
+ def estimate(self) -> tuple[float, tuple[float, float]]:
71
+ """Posterior median IC50 and 95% credible interval."""
72
+ cdf, acc = [], 0.0
73
+ for w in self.post:
74
+ acc += w
75
+ cdf.append(acc)
76
+ q = lambda p: self.grid[min(len(cdf) - 1,
77
+ next(i for i, c in enumerate(cdf) if c >= p))]
78
+ return q(0.5), (q(0.025), q(0.975))
79
+
80
+ def entropy(self) -> float:
81
+ return -sum(w * math.log(w) for w in self.post if w > 0)
82
+
83
+
84
+ def run_adaptive_series(true_ic50: float, rmax: float, sigma: float,
85
+ n_wells: int, rng: random.Random,
86
+ designer: DoseDesigner | None = None) -> tuple:
87
+ """Simulate an adaptive experiment; returns (estimate, ci, wells_used)."""
88
+ d = designer or DoseDesigner(rmax=rmax, sigma=sigma)
89
+ for _ in range(n_wells):
90
+ c = d.next_dose()
91
+ if c is None:
92
+ break
93
+ r = hill_response(c, true_ic50, rmax) + rng.gauss(0, sigma)
94
+ d.observe(c, max(0.0, r))
95
+ est, ci = d.estimate()
96
+ return est, ci, len(d.used)
97
+
98
+
99
+ def run_fixed_series(true_ic50: float, rmax: float, sigma: float,
100
+ doses: Iterable[float], rng: random.Random) -> tuple:
101
+ """The incumbent: fixed series + the same grid-posterior estimator
102
+ (generous to the baseline — it gets the best possible fit of its data)."""
103
+ d = DoseDesigner(rmax=rmax, sigma=sigma, doses=tuple(doses))
104
+ for c in doses:
105
+ r = hill_response(c, true_ic50, rmax) + rng.gauss(0, sigma)
106
+ d.observe(c, max(0.0, r))
107
+ est, ci = d.estimate()
108
+ return est, ci, len(d.used)
proef/advisory.py ADDED
@@ -0,0 +1,76 @@
1
+ """Advisory AI tox review — the tighten-only tier (Trust-T2 step 3).
2
+
3
+ Runs AFTER the deterministic gate has passed. It can add flags and demand
4
+ human review; it can NEVER clear a refusal (it never sees one — refusals
5
+ return before it runs). Its verdict is recorded as an advisory gate_decision
6
+ either way, so the audit shows what was noticed, not just what was enforced.
7
+
8
+ Backend: heuristic (ignored-intent electrophile re-check, alert stacking).
9
+ With PROEF_ADVISORY_LLM=1 and a configured provider, an LLM pass adds
10
+ free-text concerns on top — still advisory-only.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import os
15
+
16
+
17
+ class AdvisoryReviewer:
18
+ name = "advisory-tox"
19
+
20
+ def __init__(self, provider=None):
21
+ self.provider = provider
22
+ if provider is None and os.environ.get("PROEF_ADVISORY_LLM") == "1":
23
+ try: # any configured provider; none configured -> rules only
24
+ from proef.adapters.models.from_env import model_from_env
25
+ self.provider = model_from_env()
26
+ except Exception:
27
+ self.provider = None
28
+
29
+ def review(self, protocol) -> dict:
30
+ from proef.adapters.bio.tox_alerts import screen_smiles
31
+ flags, escalate = [], False
32
+ for sample in protocol.samples:
33
+ smi = (sample.metadata or {}).get("smiles")
34
+ if not smi:
35
+ continue
36
+ # intent='' -> medium alerts are NOT downgraded here: what the
37
+ # deterministic gate let through on declared intent, we re-look at
38
+ out = screen_smiles(smi, intent="")
39
+ intent_declared = (sample.metadata or {}).get("intent")
40
+ for h in out.get("refuse", []):
41
+ flags.append({"sample": sample.sample_id,
42
+ "alert": h["alert"], "note": h["note"],
43
+ "declared_intent": intent_declared or None})
44
+ if len(out.get("refuse", [])) >= 2:
45
+ escalate = True # stacking alerts demand a human
46
+ if self.provider is not None:
47
+ extra = self._llm_pass(protocol)
48
+ flags.extend(extra)
49
+ if any(f.get("severity") == "escalate" for f in extra):
50
+ escalate = True
51
+ return {"flags": flags, "escalate": escalate}
52
+
53
+ def _llm_pass(self, protocol) -> list[dict]:
54
+ from proef.core.contracts import Envelope, ToolInvocation
55
+ smis = [(s.sample_id, (s.metadata or {}).get("smiles", ""))
56
+ for s in protocol.samples
57
+ if (s.metadata or {}).get("smiles")]
58
+ if not smis:
59
+ return []
60
+ try:
61
+ txt = self.provider.generate(
62
+ ToolInvocation(envelope=Envelope(experiment_branch_id="advisory"),
63
+ tool="c.fm.predict_admet"),
64
+ "You are a conservative medicinal-chemistry safety reviewer. "
65
+ "List structural safety concerns for these compounds as JSON: "
66
+ '{"concerns":[{"sample":"...","concern":"...","severity":'
67
+ '"info|escalate"}]}. Empty list if none.\n\n'
68
+ + "\n".join(f"{i}: {s}" for i, s in smis)).output["text"]
69
+ import json, re
70
+ doc = json.loads(re.search(r"\{.*\}", txt, re.S).group(0))
71
+ return [{"sample": c.get("sample", "?"), "alert": "llm-concern",
72
+ "note": c.get("concern", "")[:160],
73
+ "severity": c.get("severity", "info")}
74
+ for c in doc.get("concerns", [])]
75
+ except Exception:
76
+ return [] # advisory failure must never block or crash