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/deps.py ADDED
@@ -0,0 +1,10 @@
1
+ """Shared helpers for the v1 routers."""
2
+ from __future__ import annotations
3
+
4
+ from fastapi import Request
5
+
6
+
7
+ def who(request: Request) -> str:
8
+ """The acting person: the authenticated token's owner, never a body field
9
+ (the guard middleware sets request.state.user)."""
10
+ return getattr(request.state, "user", None) or "local-user"
proef/api/v1/evals.py ADDED
@@ -0,0 +1,16 @@
1
+ """/api/v1/evals, the last `proef eval` leaderboard, with the honest sub-1.0
2
+ deductions surfaced (the harness refusing to overcredit its own agent).
3
+ A read-model of the committed artifacts, not a live re-run."""
4
+ from __future__ import annotations
5
+
6
+ from typing import Any
7
+
8
+ from fastapi import APIRouter
9
+
10
+ router = APIRouter(tags=["evals"])
11
+
12
+
13
+ @router.get("/evals")
14
+ def evals() -> dict[str, Any]:
15
+ from proef.evals.harness import leaderboard_payload
16
+ return leaderboard_payload()
@@ -0,0 +1,132 @@
1
+ """/api/v1/evidence, can I defend this record?
2
+
3
+ The ledger (every record re-hashed on demand), the external anchor (a Merkle
4
+ root of the whole ledger, meaningful only once it is published outside this
5
+ system's control), and per-campaign exports (report, lab notebook, ELN CSV).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import tempfile
11
+ import time
12
+ from pathlib import Path
13
+
14
+ from fastapi import APIRouter, HTTPException, Query
15
+ from fastapi.responses import FileResponse, HTMLResponse
16
+
17
+ from proef import anchor as anchor_mod
18
+ from proef.api.v1 import schemas as S
19
+ from proef.api.v1 import system as system_mod
20
+ from proef.api.v1.campaigns import _load, campaign_for_problem
21
+ from proef.views import ids as _ids
22
+
23
+ router = APIRouter(prefix="/evidence", tags=["evidence"])
24
+
25
+
26
+ def _db() -> str:
27
+ return str(_ids.PROVENANCE_DB)
28
+
29
+
30
+ def _ledger() -> S.LedgerView:
31
+ t0 = time.time()
32
+ if not Path(_db()).exists():
33
+ return S.LedgerView(chain=S.ChainStatus(verified=True, records=0),
34
+ branches=[], verified_in_ms=0, checked_at=t0)
35
+ from proef.adapters.store.sqlite import get_store
36
+ store = get_store(_db())
37
+ problems = store.verify_chain()
38
+ bad = {p["branch"] for p in problems}
39
+ rows = store._conn.execute(
40
+ "SELECT branch_id, COUNT(*) FROM provenance GROUP BY branch_id").fetchall()
41
+ branches = []
42
+ for bid, n in rows:
43
+ if bid.startswith("problem/"):
44
+ camp = campaign_for_problem(bid.split("/", 1)[1])
45
+ branches.append(S.BranchInfo(
46
+ id=bid, kind="campaign", records=n, verified=bid not in bad,
47
+ campaign_id=camp[0] if camp else None,
48
+ campaign_title=camp[1] if camp else None))
49
+ else:
50
+ branches.append(S.BranchInfo(
51
+ id=bid, kind="program" if bid.startswith("programs/") else "other",
52
+ records=n, verified=bid not in bad))
53
+ total = sum(n for _, n in rows)
54
+ value = S.ChainStatus(verified=not problems, records=total,
55
+ problems=problems[:10])
56
+ system_mod._chain_cache.update(at=time.time(), db=_db(), value=value)
57
+ return S.LedgerView(
58
+ chain=value, branches=sorted(branches, key=lambda b: -b.records),
59
+ verified_in_ms=int((time.time() - t0) * 1000), checked_at=time.time())
60
+
61
+
62
+ @router.get("/ledger", response_model=S.LedgerView)
63
+ def ledger() -> S.LedgerView:
64
+ return _ledger()
65
+
66
+
67
+ @router.post("/verify", response_model=S.LedgerView)
68
+ def verify() -> S.LedgerView:
69
+ """Re-hash every record from its stored payload, right now."""
70
+ return _ledger()
71
+
72
+
73
+ def _anchors() -> list[dict]:
74
+ path = Path(anchor_mod.ANCHORS)
75
+ try:
76
+ return json.loads(path.read_text()) if path.exists() else []
77
+ except ValueError:
78
+ return []
79
+
80
+
81
+ def _anchor_view() -> S.AnchorView:
82
+ entries = [S.AnchorEntry(ts=a["ts"], records=a["records"],
83
+ merkle_root=a["merkle_root"],
84
+ published=a.get("published"))
85
+ for a in _anchors()]
86
+ check = None
87
+ if entries and Path(_db()).exists():
88
+ v = anchor_mod.verify(_db())
89
+ check = S.AnchorCheck(
90
+ match=bool(v["match"]),
91
+ appended_since_anchor=v.get("appended_since_anchor", 0),
92
+ content_tampered=bool(v["content_tampered"]),
93
+ current_root=v["current_root"], anchored_root=v.get("anchored_root"))
94
+ note = ("An anchor protects only once PUBLISHED outside this system's "
95
+ "control: anyone who can edit this database can edit a local "
96
+ "anchor file too." if not entries or not any(
97
+ e.published for e in entries) else "")
98
+ return S.AnchorView(anchors=list(reversed(entries)), check=check, note=note)
99
+
100
+
101
+ @router.get("/anchor", response_model=S.AnchorView)
102
+ def get_anchor() -> S.AnchorView:
103
+ return _anchor_view()
104
+
105
+
106
+ @router.post("/anchor", response_model=S.AnchorView, status_code=201)
107
+ def create_anchor() -> S.AnchorView:
108
+ """Commit the ledger's Merkle root (appended to the local anchor log)."""
109
+ if not Path(_db()).exists():
110
+ raise HTTPException(409, S.Problem(
111
+ type="no-ledger", title="There is no ledger to anchor yet").model_dump())
112
+ anchor_mod.anchor(_db())
113
+ return _anchor_view()
114
+
115
+
116
+ @router.get("/export/{eid}")
117
+ def export(eid: str, kind: str = Query("report", pattern="^(report|notebook|eln)$")):
118
+ """A campaign's record as a shareable file."""
119
+ _, _, _, branch, recs = _load(eid)
120
+ if not recs or not branch:
121
+ raise HTTPException(404, S.Problem(
122
+ type="no-records", title="This campaign has no records").model_dump())
123
+ if kind == "report":
124
+ from proef.report import build_report
125
+ return HTMLResponse(build_report(recs))
126
+ if kind == "notebook":
127
+ from proef.diary import build_diary_html
128
+ return HTMLResponse(build_diary_html(recs, branch))
129
+ from proef.eln import export_eln
130
+ out = Path(tempfile.mkdtemp()) / f"{eid}-eln.csv"
131
+ export_eln(recs, str(out), None)
132
+ return FileResponse(out, media_type="text/csv", filename=out.name)
@@ -0,0 +1,35 @@
1
+ """/api/v1/halt, the operator stop-condition, outside the agent's reach."""
2
+ from __future__ import annotations
3
+
4
+ from fastapi import APIRouter, Request
5
+
6
+ from proef.api.v1 import schemas as S
7
+ from proef.api.v1.deps import who
8
+
9
+ router = APIRouter(tags=["governance"])
10
+
11
+
12
+ def _state() -> S.HaltState:
13
+ from proef.governance import HaltSwitch
14
+ hs = HaltSwitch()
15
+ halt = hs.engaged()
16
+ reason = (halt.get("reason") if isinstance(halt, dict) else str(halt)) if halt else None
17
+ return S.HaltState(halted=halt is not None, reason=reason, history=hs.history())
18
+
19
+
20
+ @router.get("/halt", response_model=S.HaltState)
21
+ def get_halt() -> S.HaltState:
22
+ return _state()
23
+
24
+
25
+ @router.post("/halt", response_model=S.HaltState)
26
+ def set_halt(body: S.HaltIn, request: Request) -> S.HaltState:
27
+ """Engage or clear the halt. Clearing is a deliberate human act and is
28
+ attributed to the authenticated person, like every other decision."""
29
+ from proef.governance import HaltSwitch
30
+ hs = HaltSwitch()
31
+ if body.halted:
32
+ hs.engage(f"{body.reason or 'operator halt (workbench)'} [by {who(request)}]")
33
+ else:
34
+ hs.clear()
35
+ return _state()
proef/api/v1/inbox.py ADDED
@@ -0,0 +1,119 @@
1
+ """/api/v1/inbox, everything pending a human decision, in one queue.
2
+
3
+ Two kinds of item: APPROVALS (a lab submission paused at the gate) and REVIEWS
4
+ (a candidate whose interval straddles the gate and that nobody has decided on
5
+ yet). Approvals are decided here; reviews are decided on the hypothesis.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from fastapi import APIRouter, HTTPException, Query, Request
10
+
11
+ from proef.api.v1 import schemas as S
12
+ from proef.api.v1.campaigns import _PID, _program_index, campaign_for_problem, plan_of
13
+ from proef.api.v1.deps import who
14
+ from proef.api.v1.programs import collect
15
+
16
+ router = APIRouter(prefix="/inbox", tags=["inbox"])
17
+
18
+
19
+ def _approval_items() -> list[S.InboxItem]:
20
+ from proef.approvals import ApprovalInbox
21
+ from proef.paths import APPROVALS_FILE
22
+ out = []
23
+ for k, v in ApprovalInbox(str(APPROVALS_FILE)).state().items():
24
+ m = _PID.search(v.get("title", ""))
25
+ camp = campaign_for_problem(m.group(1)) if m else None
26
+ out.append(S.InboxItem(
27
+ id=k, kind="approval", title=v["title"], detail=v.get("detail", ""),
28
+ ts=v.get("ts"), status=v.get("status", "pending"),
29
+ decided_by=v.get("decided_by"), plan=plan_of(v.get("payload")),
30
+ campaign_id=camp[0] if camp else None,
31
+ campaign_title=camp[1] if camp else None))
32
+ return out
33
+
34
+
35
+ _VERB = {"follow_up": "followed up", "accept": "accepted as inconclusive",
36
+ "drop": "dropped"}
37
+
38
+
39
+ def _review_items() -> list[S.InboxItem]:
40
+ out = []
41
+ for dg, hyps in collect():
42
+ for h in hyps:
43
+ if h.state != "abstained":
44
+ continue
45
+ v = h.verdict
46
+ rng = f" [{v.ci[0]:.3g} – {v.ci[1]:.3g}]" if v and v.ci else ""
47
+ base = dict(id=f"rev:{dg.id}:{h.id}", kind="review",
48
+ campaign_id=dg.id, campaign_title=dg.title,
49
+ hypothesis_id=h.id, candidate=h.head)
50
+ if h.review is None:
51
+ out.append(S.InboxItem(
52
+ **base, title=f"{h.head} abstained", ts=dg.updated_at, suggestion=h.suggestion,
53
+ detail=(f"{v.unit_label or 'value'} {v.observed:.3g}{rng}: "
54
+ "the interval straddles the gate. Follow up, accept "
55
+ "the abstention, or drop it." if v and v.observed
56
+ is not None else "No claim either way.")))
57
+ else:
58
+ r = h.review
59
+ out.append(S.InboxItem(
60
+ **base, status="reviewed", ts=r.ts, decided_by=r.by,
61
+ decision=r.decision,
62
+ follow_up_campaign_id=r.follow_up_campaign_id,
63
+ title=f"{h.head}: {_VERB[r.decision]}",
64
+ detail=(f"“{r.note}”" if r.note else "")))
65
+ return out
66
+
67
+
68
+ @router.get("", response_model=list[S.InboxItem])
69
+ def list_inbox(status: str = Query("pending", pattern="^(pending|all)$"),
70
+ program: str | None = Query(None, description="only this program's campaigns")
71
+ ) -> list[S.InboxItem]:
72
+ """A decision belongs to a CAMPAIGN (its lab submission or its abstained
73
+ candidate); a program sees the decisions of all its campaigns."""
74
+ items = _approval_items() + _review_items()
75
+ progs = _program_index()
76
+ for i in items:
77
+ i.program = progs.get(i.campaign_id) if i.campaign_id else None
78
+ if program:
79
+ items = [i for i in items if i.program and i.program.slug == program]
80
+ if status == "pending":
81
+ items = [i for i in items if i.status == "pending"]
82
+ return sorted(items, key=lambda i: -(i.ts or 0))
83
+
84
+
85
+ @router.post("/{item_id}/decision", response_model=S.InboxItem)
86
+ def decide(item_id: str, body: S.DecisionIn, request: Request) -> S.InboxItem:
87
+ """Approve or decline a paused lab submission. The decider is the
88
+ authenticated person, never a field in the body."""
89
+ from proef.approvals import ApprovalInbox
90
+ from proef.paths import APPROVALS_FILE
91
+ inbox = ApprovalInbox(str(APPROVALS_FILE))
92
+ if item_id not in inbox.state():
93
+ raise HTTPException(404, S.Problem(
94
+ type="approval-not-found", title="Approval not found",
95
+ detail=item_id).model_dump())
96
+ user = who(request)
97
+ inbox.decide(item_id, body.approve, by=user,
98
+ data={"exclude": body.exclude, "note": body.note} if (body.exclude or body.note) else None)
99
+ _seal(item_id, inbox.state()[item_id]["title"], body, user)
100
+ return next(i for i in _approval_items() if i.id == item_id)
101
+
102
+
103
+ def _seal(item_id: str, title: str, body: S.DecisionIn, user: str) -> None:
104
+ """A human approval is a governance event: seal it in the campaign's
105
+ hash-chained branch under the approver's name (the approvals log alone is
106
+ not tamper-evident)."""
107
+ m = _PID.search(title)
108
+ if not m:
109
+ return
110
+ from proef.adapters.store.sqlite import get_store
111
+ from proef.core.contracts import Actor, ActorKind, Envelope, EventType
112
+ from proef.core.interfaces import record_for
113
+ from proef.views import ids as _ids
114
+ get_store(str(_ids.PROVENANCE_DB)).append(record_for(
115
+ Envelope(experiment_branch_id=f"problem/{m.group(1)}"),
116
+ EventType.gate_decision, Actor(kind=ActorKind.human, id=user),
117
+ decision={"kind": "human_approval", "approval_id": item_id,
118
+ "title": _PID.sub("", title).strip(), "approve": body.approve,
119
+ "note": body.note[:500], **({"removed": body.exclude} if body.exclude else {})}))
proef/api/v1/lab.py ADDED
@@ -0,0 +1,110 @@
1
+ """/api/v1/lab, what hardware exists (real vs simulated) and what the agents may do."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+
6
+ from fastapi import APIRouter, HTTPException, Request
7
+
8
+ from proef.api.v1 import schemas as S
9
+ from proef.api.v1.deps import who
10
+ from proef.api.v1.governance import _state as halt_state
11
+
12
+ router = APIRouter(prefix="/lab", tags=["lab"])
13
+
14
+
15
+ @router.get("/instruments", response_model=list[S.Instrument])
16
+ def instruments() -> list[S.Instrument]:
17
+ from proef.labselect import available_instruments
18
+ out = []
19
+ for i in available_instruments():
20
+ out.append(S.Instrument(
21
+ id=i["id"], name=i.get("name") or i["id"], kind=i.get("kind", "?"),
22
+ vendor=i.get("vendor"), simulated=bool(i.get("simulated")),
23
+ hardware_validated=bool(i.get("hardware_validated")),
24
+ installed=bool(i.get("installed", True)),
25
+ requires_network=i.get("requires_network"),
26
+ assay_types=list(i.get("assay_types") or []),
27
+ readouts=list(i.get("readouts") or []), note=i.get("note")))
28
+ # honest ordering: validated hardware first, then real-but-unvalidated, then simulated
29
+ return sorted(out, key=lambda x: (not x.hardware_validated, x.simulated, x.name))
30
+
31
+
32
+ def _check(i: dict) -> S.DriverCheck:
33
+ """Does this instrument's driver start and answer its handshake HERE? Run in simulation mode, so
34
+ the check never moves hardware; which device a campaign addresses is configured in its `labs` setting."""
35
+ import importlib
36
+ import sys
37
+
38
+ from proef.labselect import _catalog_entry, _config_args, _resolve_cmd
39
+ cat = _catalog_entry(i["id"])
40
+ ok = lambda detail, tools=(): S.DriverCheck(id=i["id"], status="ready", detail=detail, tools=list(tools), checked_at=time.time()) # noqa: E731
41
+ if cat["kind"] == "simulator":
42
+ return ok("Built in. It always answers, and every result it produces is synthetic.")
43
+ if not i.get("installed"):
44
+ exe = cat.get("availability_executable") or (cat.get("adapter") or "").rsplit(":", 1)[0]
45
+ return S.DriverCheck(id=i["id"], status="not-installed", checked_at=time.time(),
46
+ detail=f"The driver ({exe}) is not installed on this machine.")
47
+ if cat["kind"] == "mcp":
48
+ from proef.mcp_instrument import McpLabAdapter
49
+ cmd = _resolve_cmd([c.replace("{python}", sys.executable) for c in cat["command"]])
50
+ has_sim = any(f.get("key") == "simulate" for f in cat.get("config_schema") or [])
51
+ cmd += _config_args(cat, {"simulate": True} if has_sim else {})
52
+ try:
53
+ lab = McpLabAdapter(command=cmd, timeout=10.0, profile=dict(cat["profile"]))
54
+ except Exception as exc: # noqa: BLE001 - any failure to start or speak MCP is a failed check
55
+ return S.DriverCheck(id=i["id"], status="failed", checked_at=time.time(), detail=f"{type(exc).__name__}: {exc}"[:300])
56
+ try:
57
+ return ok("The driver started and answered its handshake.", [t.get("name", "?") for t in lab._tools])
58
+ finally:
59
+ lab.close()
60
+ try:
61
+ importlib.import_module(cat["adapter"].rsplit(":", 1)[0])
62
+ except Exception as exc: # noqa: BLE001
63
+ return S.DriverCheck(id=i["id"], status="failed", checked_at=time.time(), detail=f"{type(exc).__name__}: {exc}"[:300])
64
+ if cat.get("requires_network"):
65
+ return S.DriverCheck(id=i["id"], status="needs-configuration", checked_at=time.time(),
66
+ detail="The driver loads. Reaching the device needs its address, which is set in a campaign's "
67
+ "`labs` configuration; this check does not touch the network.")
68
+ return ok("The driver loads.")
69
+
70
+
71
+ @router.post("/instruments/{instrument_id}/check", response_model=S.DriverCheck)
72
+ def check_instrument(instrument_id: str, request: Request) -> S.DriverCheck:
73
+ """Check a driver, on request. Recorded as an action by the person; it can never mark an instrument validated."""
74
+ from proef.labselect import available_instruments
75
+ i = next((x for x in available_instruments() if x["id"] == instrument_id), None)
76
+ if i is None:
77
+ raise HTTPException(404, S.Problem(type="instrument-not-found", title="Instrument not found", detail=instrument_id).model_dump())
78
+ res = _check(i)
79
+ from proef.adapters.store.sqlite import get_store
80
+ from proef.core.contracts import Actor, ActorKind, Envelope, EventType
81
+ from proef.core.interfaces import record_for
82
+ from proef.views import ids as _ids
83
+ get_store(str(_ids.PROVENANCE_DB)).append(record_for(
84
+ Envelope(experiment_branch_id=f"lab/{instrument_id}"), EventType.gate_decision,
85
+ Actor(kind=ActorKind.human, id=who(request)),
86
+ decision={"kind": "driver_check", "instrument": instrument_id, "status": res.status, "detail": res.detail,
87
+ "simulation_only": True}))
88
+ return res
89
+
90
+
91
+ @router.get("/authority", response_model=S.Authority)
92
+ def authority() -> S.Authority:
93
+ from proef.adapters.bio.tox_alerts import RULES_VERSION
94
+ from proef.governance import AuthorizationMatrix, SopRegistry
95
+ return S.Authority(
96
+ rules=[S.AuthorityRule(**r) for r in AuthorizationMatrix().describe()],
97
+ sops_pending=[S.Sop(id=p["id"], objective=p.get("objective", ""),
98
+ assay=p.get("assay")) for p in SopRegistry().pending()],
99
+ halt=halt_state(), safety_rules=str(RULES_VERSION))
100
+
101
+
102
+ @router.post("/sops/{sop_id}/approve", response_model=S.Authority)
103
+ def approve_sop(sop_id: str, request: Request) -> S.Authority:
104
+ """Sign off a recurring procedure: from now on it may run unattended.
105
+ Attributed to the authenticated person."""
106
+ from proef.governance import SopRegistry
107
+ if not SopRegistry().approve(sop_id, by=who(request)):
108
+ raise HTTPException(404, S.Problem(
109
+ type="sop-not-found", title="SOP not found", detail=sop_id).model_dump())
110
+ return authority()
proef/api/v1/pauses.py ADDED
@@ -0,0 +1,77 @@
1
+ """/api/v1/.../pause: a routine, scoped pause of one program or one campaign.
2
+
3
+ Not the emergency stop (that is /halt, global, and refuses). A pause HOLDS the scope's lab submissions at the gateway
4
+ and releases them on resume, so a campaign never loses rounds to it. Running plates finish. Pausing and resuming are
5
+ attributed to the authenticated person and sealed in the ledger like every other human decision."""
6
+ from __future__ import annotations
7
+
8
+ from fastapi import APIRouter, HTTPException, Request
9
+
10
+ from proef import program as program_cfg
11
+ from proef.api.v1 import schemas as S
12
+ from proef.api.v1.campaigns import _load, problem_id_for
13
+ from proef.api.v1.deps import who
14
+ from proef.governance import PauseRegistry
15
+
16
+ router = APIRouter(tags=["governance"])
17
+
18
+
19
+ def pause_state(entry: dict | None) -> S.PauseState | None:
20
+ if not entry:
21
+ return None
22
+ scope = str(entry.get("scope", ""))
23
+ return S.PauseState(scope=scope, kind="program" if scope.startswith("program:") else "campaign",
24
+ reason=entry.get("reason") or "", by=entry.get("by") or "someone", ts=entry.get("ts"))
25
+
26
+
27
+ def pauses_for(problem_id: str | None, slug: str | None) -> tuple[S.PauseState | None, S.PauseState | None]:
28
+ """(this campaign's own pause, the pause on its program) for the detail views."""
29
+ act = PauseRegistry().active()
30
+ own = act.get(f"campaign:{problem_id}") if problem_id else None
31
+ prog = act.get(f"program:{slug}") if slug else None
32
+ return pause_state(own), pause_state(prog)
33
+
34
+
35
+ def _seal(branch: str, user: str, decision: dict) -> None:
36
+ from proef.adapters.store.sqlite import get_store
37
+ from proef.core.contracts import Actor, ActorKind, Envelope, EventType
38
+ from proef.core.interfaces import record_for
39
+ from proef.views import ids as _ids
40
+ get_store(str(_ids.PROVENANCE_DB)).append(record_for(
41
+ Envelope(experiment_branch_id=branch), EventType.gate_decision, Actor(kind=ActorKind.human, id=user), decision=decision))
42
+
43
+
44
+ def _apply(scope: str, branch: str, body: S.PauseIn, user: str) -> S.PauseResult:
45
+ reg = PauseRegistry()
46
+ if body.paused:
47
+ entry = reg.pause(scope, body.reason.strip(), user)
48
+ _seal(branch, user, {"kind": "pause", "scope": scope, "reason": entry.get("reason", ""),
49
+ "note": "new lab submissions are held until resumed; running plates finish"})
50
+ else:
51
+ if reg.resume(scope, user):
52
+ _seal(branch, user, {"kind": "resume", "scope": scope})
53
+ return S.PauseResult(paused=scope in reg.active(), pause=pause_state(reg.active().get(scope)))
54
+
55
+
56
+ @router.get("/pauses", response_model=list[S.PauseState])
57
+ def list_pauses() -> list[S.PauseState]:
58
+ return [s for s in (pause_state(e) for e in PauseRegistry().active().values()) if s]
59
+
60
+
61
+ @router.post("/programs/{slug}/pause", response_model=S.PauseResult)
62
+ def pause_program(slug: str, body: S.PauseIn, request: Request) -> S.PauseResult:
63
+ if not any(p["slug"] == slug for p in program_cfg.list_programs()):
64
+ raise HTTPException(404, S.Problem(type="program-not-found", title="Program not found", detail=slug).model_dump())
65
+ return _apply(f"program:{slug}", f"programs/{slug}", body, who(request))
66
+
67
+
68
+ @router.post("/campaigns/{eid}/pause", response_model=S.PauseResult)
69
+ def pause_campaign(eid: str, body: S.PauseIn, request: Request) -> S.PauseResult:
70
+ _, _, detail, branch, _ = _load(eid)
71
+ pid = problem_id_for(eid, detail)
72
+ if not pid:
73
+ raise HTTPException(409, S.Problem(
74
+ type="not-started", title="This campaign has not started yet",
75
+ detail="It can be paused once it has a record, which happens as soon as it begins.").model_dump())
76
+ # a RUNNING campaign is not linked in the registry yet (no branch), but it has announced its problem id
77
+ return _apply(f"campaign:{pid}", branch or f"problem/{pid}", body, who(request))