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/views/counts.py ADDED
@@ -0,0 +1,102 @@
1
+ """DMTA / verdict tallies and series rollups over a campaign's records."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+
7
+ # ------------------------------------------------------------- dmta counts
8
+ def dmta_counts(recs) -> dict:
9
+ """DMTA phase counts for a slice of provenance records. Test counts
10
+ unique lab_run submissions (one submission = one run = one analyzed
11
+ export); Analyze counts verdict-bearing decisions, deduplicated ,
12
+ a hypothesis earns ONE verdict: its latest. Port of
13
+ webview._dmta_counts."""
14
+ c = {"proposed": 0, "selected": 0, "submitted": 0, "refused": 0,
15
+ "runs": 0, "verdicts": 0,
16
+ "validated": 0, "confirmed": 0, "inconclusive": 0,
17
+ "refuted": 0}
18
+ final: dict[str, str] = {}
19
+ orphan = 0
20
+ for r in recs:
21
+ d = r.decision or {}
22
+ et = r.event_type.value
23
+ if et == "hypothesis_proposed":
24
+ c["proposed"] += 1
25
+ elif et == "hypotheses_filtered":
26
+ c["selected"] += sum(1 for x in d.get("decisions", [])
27
+ if x.get("selected"))
28
+ elif et == "lab_run" and d.get("run_id"):
29
+ c["submitted"] += 1
30
+ c["runs"] += 1
31
+ elif et == "gate_decision":
32
+ k = d.get("kind")
33
+ if k in ("halt_refusal", "safety_refusal", "authorization",
34
+ "synthesis_failed") \
35
+ and d.get("column") != "autonomous":
36
+ c["refused"] += 1
37
+ elif et in ("hypothesis_validated", "hypothesis_invalidated",
38
+ "hypothesis_inconclusive",
39
+ "hypothesis_tested") and d.get("verdict"):
40
+ hid = d.get("hypothesis_id") \
41
+ or (r.artifact.artifact_id if r.artifact else None)
42
+ if not hid:
43
+ orphan += 1
44
+ continue
45
+ final[hid] = str(d.get("verdict"))
46
+ for v in final.values():
47
+ c["verdicts"] += 1
48
+ if v in ("validated", "confirmed"):
49
+ c[v] += 1
50
+ elif v == "invalidated":
51
+ c["refuted"] += 1
52
+ elif v in ("inconclusive", "refuted"):
53
+ c[v] += 1
54
+ return c
55
+
56
+
57
+ def verdict_tally(recs) -> dict[str, int]:
58
+ """Final verdicts, one per hypothesis (latest wins), bucketed for
59
+ the workspace chips. CONFIRMED means orthogonal agreement was recorded;
60
+ a preliminary `validated` is NOT confirmed, it counts as preliminary.
61
+ refuted = invalidated/refuted; inconclusive = abstention."""
62
+ t = {"confirmed": 0, "preliminary": 0, "refuted": 0, "inconclusive": 0}
63
+ final: dict[str, str] = {}
64
+ for r in recs:
65
+ d = r.decision or {}
66
+ if r.event_type.value in ("hypothesis_validated",
67
+ "hypothesis_invalidated",
68
+ "hypothesis_inconclusive",
69
+ "hypothesis_tested") and d.get("verdict"):
70
+ hid = d.get("hypothesis_id") \
71
+ or (r.artifact.artifact_id if r.artifact else None)
72
+ if hid:
73
+ final[hid] = str(d.get("verdict"))
74
+ for v in final.values():
75
+ if v == "confirmed":
76
+ t["confirmed"] += 1
77
+ elif v == "validated":
78
+ t["preliminary"] += 1
79
+ elif v in ("refuted", "invalidated", "failed"):
80
+ t["refuted"] += 1
81
+ else:
82
+ t["inconclusive"] += 1
83
+ return t
84
+
85
+
86
+ def series_view(recs) -> list[dict[str, Any]]:
87
+ """S-T1 chemotype/SAR series rollup for the workbench: per-series
88
+ verdict counts + matched-pair SAR table. Grouping backend
89
+ (Murcko/family/exact-id) stamps itself, see proef.series."""
90
+ from proef.series import series_summary
91
+ return series_summary(recs)
92
+
93
+
94
+ def round_markers(recs) -> list[tuple[int, list[str]]]:
95
+ """[(round_no, [candidates])] sorted by round, from round_start
96
+ markers."""
97
+ markers = [(int((r.decision or {}).get("round", 0)),
98
+ [str(c) for c in (r.decision or {}).get("candidates") or []])
99
+ for r in recs
100
+ if r.event_type.value == "stage_transition"
101
+ and (r.decision or {}).get("kind") == "round_start"]
102
+ return sorted(markers)
@@ -0,0 +1,154 @@
1
+ """Experiment detail: one experiment's full read-model."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+
6
+ from proef.views.counts import dmta_counts, series_view
7
+ from proef.views.ids import resolve_problem, row_status
8
+ from proef.views.pipeline import _rounds_with_verdicts, _sandbox_summary, pipeline_cards
9
+ from proef.views import ids as _ids
10
+
11
+
12
+ # --------------------------------------------- experiment/workspace detail
13
+ def _problem_id(eid: str, ag: dict) -> str | None:
14
+ """The campaign's problem id: log > registry payload > a campaign-root
15
+ program link (relational fallback when the row carries neither)."""
16
+ logf = Path(ag["log"]) if ag.get("log") else None
17
+ problem_id = ag.get("problem_id")
18
+ if logf is not None:
19
+ problem_id = resolve_problem(ag, logf) or problem_id
20
+ if not problem_id:
21
+ from proef import program as program_cfg
22
+ for p in program_cfg.list_programs():
23
+ for l in program_cfg.links_for(p["slug"]):
24
+ if l["eid"] == eid and l.get("campaign_root"):
25
+ return l["campaign_root"]
26
+ return problem_id
27
+
28
+
29
+ def _branch_records(branch: str | None, provenance_db) -> list:
30
+ if not (branch and Path(provenance_db).exists()):
31
+ return []
32
+ from proef.adapters.store.sqlite import get_store
33
+ try:
34
+ return get_store(str(provenance_db)).branch_records(branch)
35
+ except Exception:
36
+ return []
37
+
38
+
39
+ def _eliminated(recs) -> list[dict]:
40
+ """Graveyard: hypotheses the portfolio filter rejected, with reasons ,
41
+ elimination is evidence too, and the scientist should audit it."""
42
+ id2cand: dict[str, str] = {}
43
+ for r in recs:
44
+ if r.event_type.value == "hypothesis_proposed" and r.artifact:
45
+ cand = (r.artifact.metadata or {}).get("candidate")
46
+ if cand:
47
+ id2cand[r.artifact.artifact_id] = str(cand)
48
+ eliminated: dict[str, dict] = {}
49
+ for r in recs:
50
+ if r.event_type.value != "hypotheses_filtered":
51
+ continue
52
+ for dec in (r.decision or {}).get("decisions", []):
53
+ if dec.get("selected"):
54
+ continue
55
+ cand = id2cand.get(dec.get("hypothesis_id")) \
56
+ or dec.get("hypothesis_id")
57
+ eliminated[cand] = {
58
+ "candidate": cand,
59
+ "reason": dec.get("reason") or "not selected",
60
+ "score": dec.get("score")}
61
+ return list(eliminated.values())
62
+
63
+
64
+ def _program_relation(eid: str, spec: dict | None) -> dict | None:
65
+ """Which program links this experiment (None when none / unreadable)."""
66
+ try:
67
+ from proef import program as program_cfg
68
+ slug = (spec or {}).get("program_slug")
69
+ if not slug:
70
+ for p in program_cfg.list_programs():
71
+ if any(a.get("eid") == eid
72
+ for a in p.get("attachments", [])):
73
+ slug = p["slug"]
74
+ break
75
+ if not slug:
76
+ return None
77
+ prow = next((p for p in program_cfg.list_programs()
78
+ if p["slug"] == slug), None)
79
+ if not prow:
80
+ return None
81
+ pd = prow.get("program") or {}
82
+ return {"slug": slug, "name": prow["name"],
83
+ "gate": {"metric": pd.get("metric"),
84
+ "direction": pd.get("direction"),
85
+ "value": pd.get("gate_value"),
86
+ "unit": pd.get("unit"),
87
+ "symbol": program_cfg.gate_symbol(pd)},
88
+ "modality": pd.get("modality"),
89
+ "mode": pd.get("mode")}
90
+ except Exception:
91
+ return None
92
+
93
+
94
+ def experiment_detail(eid: str, wizard_store,
95
+ provenance_db: str | Path | None = None) -> dict | None:
96
+ """Full experiment read-model: registry row + campaign spec + program
97
+ relation + provenance merge. Precedence: provenance problem_defined
98
+ overrides campaign_specs for objective/constraints; the spec always
99
+ supplies k/rounds/autonomy/candidate policy."""
100
+ provenance_db = provenance_db or _ids.PROVENANCE_DB
101
+ row = wizard_store.get(eid)
102
+ if not row:
103
+ return None
104
+ payload = row["payload"] or {}
105
+ ag = payload.get("agent") or {}
106
+ spec = wizard_store.get_campaign_spec(eid)
107
+ problem_id = _problem_id(eid, ag)
108
+ branch = f"problem/{problem_id}" if problem_id else None
109
+ recs = _branch_records(branch, provenance_db)
110
+ pdef = next((r.decision for r in recs
111
+ if r.event_type.value == "problem_defined"), None)
112
+ eliminated = _eliminated(recs)
113
+ objective = (pdef or {}).get("objective") \
114
+ or (spec or {}).get("objective") \
115
+ or row.get("question")
116
+ constraints = (pdef or {}).get("constraints") \
117
+ if pdef and pdef.get("constraints") else \
118
+ ((spec or {}).get("constraints") or [])
119
+ program = _program_relation(eid, spec)
120
+
121
+ cards = pipeline_cards(recs) if recs else []
122
+ return {
123
+ "id": eid,
124
+ "question": row.get("question"),
125
+ "status": row_status(row),
126
+ "registry_status": row.get("status"),
127
+ "updated_at": row.get("updated_at"),
128
+ "agent": {"autonomy": ag.get("autonomy", "act"),
129
+ "problem_id": problem_id,
130
+ "log_path": ag.get("log")},
131
+ "branch": branch,
132
+ "record_count": len(recs),
133
+ "series": series_view(recs),
134
+ "program": program,
135
+ "spec": {"objective": (spec or {}).get("objective"),
136
+ "program_slug": (spec or {}).get("program_slug"),
137
+ "k": (spec or {}).get("k"),
138
+ "rounds": (spec or {}).get("rounds"),
139
+ "autonomy": (spec or {}).get("autonomy"),
140
+ "hypothesis_source": (spec or {}).get("hypothesis_source"),
141
+ "n_candidates": (spec or {}).get("n_candidates"),
142
+ "modality": (spec or {}).get("modality"),
143
+ "constraints": (spec or {}).get("constraints") or []}
144
+ if spec else None,
145
+ "objective": objective,
146
+ "constraints": constraints or [],
147
+ "success_metric": (pdef or {}).get("success_metric")
148
+ or (spec or {}).get("success_metric"),
149
+ "counts": dmta_counts(recs),
150
+ "rounds": _rounds_with_verdicts(recs),
151
+ "sandbox": _sandbox_summary(recs),
152
+ "cards": cards,
153
+ "eliminated": eliminated,
154
+ }
proef/views/ids.py ADDED
@@ -0,0 +1,49 @@
1
+ """Id conventions and registry helpers shared by every read-model."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import re
6
+ from pathlib import Path
7
+
8
+ from proef.paths import DATA_DIR
9
+
10
+
11
+ PROVENANCE_DB = "proef.db"
12
+
13
+
14
+ # --------------------------------------------------------------- row status
15
+ def row_status(e: dict) -> str:
16
+ """Registry status for log-less runs (tree leaves), log/pid-derived
17
+ status for launched campaigns. Port of webview._row_status."""
18
+ ag = e["payload"].get("agent") or {}
19
+ if not ag:
20
+ return e["status"].replace("_", " ")
21
+ log = ag.get("log") or ""
22
+ logf = Path(log)
23
+ if log and logf.is_file() and "CAMPAIGN COMPLETE" in logf.read_text(
24
+ errors="replace"):
25
+ return "completed"
26
+ pid = ag.get("pid")
27
+ if pid:
28
+ try:
29
+ os.kill(pid, 0)
30
+ return "running"
31
+ except OSError:
32
+ return "interrupted"
33
+ return e["status"]
34
+
35
+
36
+ # ------------------------------------------------------- problem id helpers
37
+ def resolve_problem(meta: dict, logf: Path) -> str | None:
38
+ """Latest prob-* id for a campaign: explicit metadata wins; else the
39
+ log is searched (problem-registration lines first, then any
40
+ CAMPAIGN COMPLETE-style token). Port of Overview._resolve_problem."""
41
+ problem_id = meta.get("problem_id")
42
+ if logf and str(logf) != "." and Path(logf).is_file():
43
+ txt = Path(logf).read_text(errors="replace")
44
+ m = re.findall(r"problem (prob-\w+):", txt) \
45
+ or re.findall(r"\b(prob-[0-9a-f]+)\b", txt)
46
+ latest = m[-1] if m else None
47
+ if latest and latest != problem_id:
48
+ problem_id = latest
49
+ return problem_id
@@ -0,0 +1,294 @@
1
+ """The experiment narrative / lab-diary read-model."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+
8
+ def _proposed(recs):
9
+ return [r for r in recs
10
+ if r.event_type.value == "hypothesis_proposed" and r.decision]
11
+
12
+
13
+ def _candidate(r):
14
+ d = r.decision or {}
15
+ cand = d.get("candidate")
16
+ if cand:
17
+ return str(cand)
18
+ if r.artifact:
19
+ return str((r.artifact.metadata or {}).get("candidate") or "")
20
+ return ""
21
+
22
+
23
+ def _portfolio(recs, out) -> None:
24
+ # portfolio scores
25
+ filt = next((r for r in recs
26
+ if r.event_type.value == "hypotheses_filtered"), None)
27
+ if filt:
28
+ id2cand = {}
29
+ for r in _proposed(recs):
30
+ hid = (r.decision or {}).get("hypothesis_id")
31
+ if hid:
32
+ id2cand[hid] = _candidate(r)
33
+ if r.artifact:
34
+ id2cand[r.artifact.artifact_id] = _candidate(r)
35
+ out["portfolio"] = [{
36
+ "hypothesis": id2cand.get(d.get("hypothesis_id"),
37
+ d.get("hypothesis_id", "?")),
38
+ "score": d.get("score"),
39
+ "selected": bool(d.get("selected")),
40
+ "reason": d.get("reason", "")}
41
+ for d in (filt.decision or {}).get("decisions", [])]
42
+
43
+
44
+ def _gates(recs, log_lines, out):
45
+ # gates / refusals
46
+ refusals = [l for l in log_lines if "rejected" in l]
47
+ advs = [r for r in recs
48
+ if (r.decision or {}).get("kind") == "advisory"]
49
+ durc = [r for r in recs
50
+ if (r.decision or {}).get("kind") == "durc_refusal"]
51
+ if refusals or advs or durc:
52
+ out["gates"] = {
53
+ "refusals": [l.replace("[campaign] ", "")
54
+ .replace("[agent] ", "") for l in refusals],
55
+ "advisories": [{
56
+ "flags": [{
57
+ "sample": f.get("sample"),
58
+ "alert": f.get("alert"),
59
+ "declared_intent": f.get("declared_intent")}
60
+ for f in (a.decision or {}).get("flags", [])]}
61
+ for a in advs],
62
+ "durc": [", ".join((d.decision or {}).get("agents", []))
63
+ for d in durc]}
64
+ return advs, durc
65
+
66
+
67
+ def _make(recs, out) -> None:
68
+ # make / test
69
+ runs = [r for r in recs if r.event_type.value == "lab_run"
70
+ and (r.decision or {}).get("run_id")]
71
+ make_refusals = [r for r in recs
72
+ if r.event_type.value == "gate_decision"
73
+ and (r.decision or {}).get("kind") in
74
+ ("safety_refusal", "halt_refusal", "authorization",
75
+ "durc_refusal", "operator_declined",
76
+ "synthesis_failed", "stability_failed")
77
+ and (r.decision or {}).get("column") != "autonomous"]
78
+ synth = [r for r in recs if r.event_type.value == "synthesis_complete"]
79
+ bio_qc = [r for r in recs
80
+ if r.event_type.value == "stage_transition"
81
+ and (r.decision or {}).get("kind") == "bioprocess_qc"]
82
+ if runs or make_refusals:
83
+ make: dict[str, Any] = {}
84
+ if bio_qc:
85
+ make["bio_qc"] = [{
86
+ "candidate": (r.decision or {}).get("candidate", "?"),
87
+ "lot": (r.decision or {}).get("lot", ", "),
88
+ "aggregation_risk": (r.decision or {}).get(
89
+ "aggregation_risk", ", "),
90
+ "t_half_h": (r.decision or {}).get("t_half_h", ", "),
91
+ "passed": bool((r.decision or {}).get("ok"))}
92
+ for r in bio_qc]
93
+ if synth:
94
+ make["synthesis"] = [{
95
+ "candidate": (r.decision or {}).get("candidate", "?"),
96
+ "lot": (r.decision or {}).get("lot", ", "),
97
+ "yield_pct": (r.decision or {}).get("yield_pct", ", "),
98
+ "purity": (r.decision or {}).get("purity", ", "),
99
+ "passed": bool((r.decision or {}).get("ok"))}
100
+ for r in synth]
101
+ make["no_synthesis_note"] = bool(runs and not synth)
102
+ if runs:
103
+ make["runs"] = [{
104
+ "run_id": (r.decision or {}).get("run_id"),
105
+ "title": ((r.decision or {}).get("title") or ", ")[:48],
106
+ "assay": (r.decision or {}).get("assay", ", "),
107
+ "n_samples": (r.decision or {}).get("n_samples", ", "),
108
+ "concentrations": (r.decision or {}).get(
109
+ "concentrations") or [],
110
+ "replicates": (r.decision or {}).get("replicates", ", "),
111
+ "n_controls": (r.decision or {}).get("n_controls", ", "),
112
+ "instrument": (r.decision or {}).get("instrument", "lab"),
113
+ "instrument_version": (r.decision or {}).get(
114
+ "instrument_version")}
115
+ for r in runs]
116
+ d0 = runs[0].decision or {}
117
+ make["protocol_summary"] = (
118
+ f"dispense {d0.get('n_samples', '?')} sample well(s) at "
119
+ f"{d0.get('replicates', '?')} replicates per concentration "
120
+ f"({', '.join(str(c) for c in d0.get('concentrations') or [])}"
121
+ f" µM) plus {d0.get('n_controls', '?')} controls, incubate, "
122
+ f"then read on {d0.get('instrument', 'the reader')}")
123
+ if make_refusals:
124
+ make["refused_count"] = len(make_refusals)
125
+ out["make"] = make
126
+
127
+
128
+ def _verdicts(recs, out) -> dict:
129
+ """Verdict rows (last per candidate) + derivation descriptions; returns
130
+ the last-verdict map the trust and evidence sections reuse."""
131
+ # verdicts (last per candidate) + derivation descriptions
132
+ last: dict[str, dict] = {}
133
+ for r in recs:
134
+ if r.event_type.value.startswith("hypothesis_"):
135
+ d = r.decision or {}
136
+ cand = _candidate(r)
137
+ if cand and d.get("verdict"):
138
+ last[cand] = d
139
+ if last:
140
+ from proef.derivation import criteria_label, metric_label
141
+ _metrics = [d.get("metric") for d in last.values() if d.get("metric")]
142
+ mlabel = metric_label(_metrics[0] if _metrics else None)
143
+ has_ci = any(d.get("observed_ci") for d in last.values())
144
+ rows = []
145
+ for c, d in sorted(last.items()):
146
+ row: dict = {"candidate": c, "verdict": d.get("verdict"),
147
+ "estimated_label": f"estimated {mlabel}",
148
+ "estimated": d.get("observed")}
149
+ if has_ci:
150
+ row["ci95"] = ("–".join(str(x) for x in d["observed_ci"])
151
+ if d.get("observed_ci") else ", ")
152
+ if d.get("threshold") is not None:
153
+ row["gate"] = criteria_label(
154
+ d.get("metric"), None,
155
+ d.get("threshold")).replace("= ", "")
156
+ row["evidence_run"] = d.get("evidence_run_id") or "never ran"
157
+ rows.append(row)
158
+ out["verdicts"] = {
159
+ "rows": rows,
160
+ "derivations": [
161
+ {"candidate": c,
162
+ "description": __import__(
163
+ "proef.derivation",
164
+ fromlist=["describe"]).describe(d.get("derivation"))}
165
+ for c, d in sorted(last.items())],
166
+ "claimed": sum(1 for d in last.values()
167
+ if d.get("verdict") in ("validated",
168
+ "confirmed")),
169
+ "abstained": sum(1 for d in last.values()
170
+ if d.get("verdict") in ("inconclusive",
171
+ "proposed"))}
172
+ return last
173
+
174
+
175
+ def _reviewer(recs, out) -> None:
176
+ # reviewer
177
+ reviews = [r for r in recs
178
+ if r.event_type.value == "stage_transition"
179
+ and (r.decision or {}).get("kind") == "review_report"]
180
+ if reviews:
181
+ d = reviews[-1].decision or {}
182
+ reviewer: dict[str, Any] = {
183
+ "review": d.get("review", "reviewer-v1"),
184
+ "critical": d.get("critical", 0),
185
+ "warnings": d.get("warnings", 0),
186
+ "verdicts_reviewed": d.get("verdicts_reviewed", 0),
187
+ "findings": [{"severity": f.get("severity", "?"),
188
+ "kind": f.get("kind", "?"),
189
+ "candidate": f.get("candidate"),
190
+ "detail": f.get("detail", "")}
191
+ for f in (d.get("findings") or [])]}
192
+ llm = [r for r in recs
193
+ if r.event_type.value == "stage_transition"
194
+ and (r.decision or {}).get("kind") == "review_report_llm"]
195
+ if llm:
196
+ ld = llm[-1].decision or {}
197
+ reviewer["llm"] = {
198
+ "model": ld.get("model", "?"),
199
+ "unavailable": ld.get("unavailable"),
200
+ "prompt_hash": ld.get("prompt_hash", ""),
201
+ "flags": [{"kind": f.get("kind", "?"),
202
+ "candidate": f.get("candidate"),
203
+ "detail": f.get("detail", "")}
204
+ for f in (ld.get("flags") or [])]}
205
+ out["reviewer"] = reviewer
206
+
207
+
208
+ def _trust(recs, out, advs, durc, last) -> None:
209
+ # trust checks
210
+ cstates = [(r.decision or {}).get("citation_status")
211
+ for r in _proposed(recs) if (r.decision or {}).get("citation")]
212
+ n_flags = sum(len((a.decision or {}).get("flags", [])) for a in advs)
213
+ checks = []
214
+ if cstates:
215
+ ok = sum(1 for c in cstates if c == "verified")
216
+ bad = sum(1 for c in cstates if c == "invalid")
217
+ checks.append(f"citations: {ok} verified, {bad} invalid, "
218
+ f"{len(cstates) - ok - bad} unverified")
219
+ if durc:
220
+ checks.append("dual-use screening refused this branch's work")
221
+ if n_flags:
222
+ checks.append(f"advisory flags raised (non-blocking): {n_flags}")
223
+ abstained = sum(1 for d in last.values()
224
+ if d.get("verdict") in ("inconclusive", "proposed"))
225
+ if abstained:
226
+ checks.append(f"{abstained} verdict(s) abstained, CI straddled "
227
+ "the gate; abstention is reported, not hidden")
228
+ from proef.adapters.bio.tox_alerts import RULES_VERSION
229
+ checks.append(f"safety rules: {RULES_VERSION}")
230
+ out["trust"] = {"checks": checks}
231
+
232
+
233
+ def _evidence(recs, out, last, data_dir) -> None:
234
+ # evidence: recorded plate files for this branch's runs
235
+ # a plate is evidence whether the lab ran it or a person submitted it
236
+ run_ids = {d.get("run_id") for r in recs
237
+ if (d := r.decision or {}) and d.get("run_id")
238
+ and (r.event_type.value == "lab_run"
239
+ or d.get("kind") == "results_submitted")}
240
+ run2cand: dict[str, str] = {}
241
+ for r in recs: # a verdict names the run it was judged on
242
+ d = r.decision or {}
243
+ if d.get("verdict") and d.get("evidence_run_id") and _candidate(r):
244
+ run2cand.setdefault(d["evidence_run_id"], _candidate(r))
245
+ for r in recs:
246
+ d = r.decision or {}
247
+ if r.event_type.value == "hypothesis_tested" and d.get("run_id"):
248
+ cand = (d.get("candidate")
249
+ or ((r.artifact.metadata or {}).get("candidate")
250
+ if r.artifact else None)) or d.get("candidate")
251
+ if cand:
252
+ run2cand[d["run_id"]] = cand
253
+ import glob
254
+ branch = ""
255
+ if recs:
256
+ env = getattr(recs[0], "envelope", None)
257
+ branch = getattr(env, "experiment_branch_id", "") or ""
258
+ pid = branch.split("/", 1)[1] if "/" in branch else branch
259
+ items = []
260
+ for rid in sorted(run_ids):
261
+ hits = (glob.glob(f"**/{pid}/**/{rid}.csv", root_dir=data_dir,
262
+ recursive=True)
263
+ or glob.glob(f"**/{pid}/{rid}.csv", root_dir=data_dir,
264
+ recursive=True)
265
+ or glob.glob(f"**/{rid}.csv", root_dir=data_dir,
266
+ recursive=True))
267
+ if hits:
268
+ items.append({"run_id": rid,
269
+ "path": str(Path(data_dir) / hits[0]),
270
+ "candidate": run2cand.get(rid, rid),
271
+ "verdict": (last.get(run2cand.get(rid, ""), {})
272
+ .get("verdict"))})
273
+ out["evidence"] = {
274
+ "curves": items, # FE renders these client-side
275
+ "svg_fallback": bool(items),
276
+ "empty_note": None if items else
277
+ "No recorded plate files found for these runs, evidence "
278
+ "curves unavailable (honestly shown, not simulated)."}
279
+
280
+
281
+ # --------------------------------------------------------- narrative data
282
+ def narrative_data(recs, log_lines=(), data_dir=".data") -> dict:
283
+ """Read-model for 'The record of this run'. Port of narrative.render:
284
+ portfolio, gates, make, test, evidence, verdicts, reviewer, trust.
285
+ Sections with no data come back as None so the FE can skip them."""
286
+ out: dict[str, Any] = {"title": "The record of this run"}
287
+ _portfolio(recs, out)
288
+ advs, durc = _gates(recs, log_lines, out)
289
+ _make(recs, out)
290
+ last = _verdicts(recs, out)
291
+ _reviewer(recs, out)
292
+ _trust(recs, out, advs, durc, last)
293
+ _evidence(recs, out, last, data_dir)
294
+ return out