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.
- proef/__init__.py +25 -0
- proef/acquisition.py +244 -0
- proef/ad.py +159 -0
- proef/adapters/__init__.py +0 -0
- proef/adapters/admet.py +196 -0
- proef/adapters/bio/__init__.py +0 -0
- proef/adapters/bio/rdkit_ops.py +52 -0
- proef/adapters/bio/safety_rules.json +146 -0
- proef/adapters/bio/seq_alerts.py +79 -0
- proef/adapters/bio/structure_score.py +85 -0
- proef/adapters/bio/tox_alerts.py +99 -0
- proef/adapters/data/__init__.py +0 -0
- proef/adapters/data/admet.py +62 -0
- proef/adapters/data/chembl.py +110 -0
- proef/adapters/data/frozen/admet/MANIFEST.json +48 -0
- proef/adapters/data/frozen/admet/bbb_martins/test.csv +407 -0
- proef/adapters/data/frozen/admet/bbb_martins/train_val.csv +1625 -0
- proef/adapters/data/frozen/admet/caco2_wang/test.csv +183 -0
- proef/adapters/data/frozen/admet/caco2_wang/train_val.csv +729 -0
- proef/adapters/data/frozen/admet/hia_hou/test.csv +118 -0
- proef/adapters/data/frozen/admet/hia_hou/train_val.csv +462 -0
- proef/adapters/data/moleculenet.py +60 -0
- proef/adapters/databases/__init__.py +0 -0
- proef/adapters/databases/chembl_gates.py +121 -0
- proef/adapters/databases/chembl_lookup.py +35 -0
- proef/adapters/databases/open_targets.py +102 -0
- proef/adapters/databases/pubmed.py +94 -0
- proef/adapters/devices/__init__.py +0 -0
- proef/adapters/devices/ezo_ph.py +251 -0
- proef/adapters/devices/hcs_microscope.py +143 -0
- proef/adapters/devices/lcms.py +123 -0
- proef/adapters/devices/scheduler.py +84 -0
- proef/adapters/devices/sila2.py +134 -0
- proef/adapters/genomics/alphagenome.py +146 -0
- proef/adapters/lab/__init__.py +0 -0
- proef/adapters/lab/bioprocess.py +32 -0
- proef/adapters/lab/devices.py +170 -0
- proef/adapters/lab/imaging.py +226 -0
- proef/adapters/lab/mhs_driver.py +124 -0
- proef/adapters/lab/opentrons.py +222 -0
- proef/adapters/lab/ot2_sim.py +174 -0
- proef/adapters/lab/plate_reader_share.py +108 -0
- proef/adapters/lab/protein_design.py +199 -0
- proef/adapters/lab/recording.py +119 -0
- proef/adapters/lab/replay.py +107 -0
- proef/adapters/lab/simulator.py +282 -0
- proef/adapters/lab/synthesis.py +92 -0
- proef/adapters/models/__init__.py +0 -0
- proef/adapters/models/anthropic_provider.py +157 -0
- proef/adapters/models/assayloop_ranker.py +67 -0
- proef/adapters/models/from_env.py +93 -0
- proef/adapters/models/gp_policy.py +93 -0
- proef/adapters/models/gp_policy_gp.py +36 -0
- proef/adapters/models/llm_policy.py +187 -0
- proef/adapters/models/openai_compat.py +150 -0
- proef/adapters/models/sklearn_policy.py +65 -0
- proef/adapters/retrosynthesis.py +247 -0
- proef/adapters/sandbox/__init__.py +20 -0
- proef/adapters/sandbox/agentenv.py +145 -0
- proef/adapters/sandbox/docker.py +217 -0
- proef/adapters/sandbox/local.py +164 -0
- proef/adapters/sandbox/opensandbox.py +122 -0
- proef/adapters/store/__init__.py +0 -0
- proef/adapters/store/sqlite.py +207 -0
- proef/adaptive.py +108 -0
- proef/advisory.py +76 -0
- proef/analysis_profiles/__init__.py +8 -0
- proef/analysis_profiles/measurements.py +266 -0
- proef/analysis_profiles/plate_assay.py +316 -0
- proef/analysis_report.py +195 -0
- proef/analysis_store.py +183 -0
- proef/anchor.py +154 -0
- proef/api/app.py +107 -0
- proef/api/launch.py +170 -0
- proef/api/v1/__init__.py +29 -0
- proef/api/v1/analyses.py +367 -0
- proef/api/v1/campaigns.py +802 -0
- proef/api/v1/deps.py +10 -0
- proef/api/v1/evals.py +16 -0
- proef/api/v1/evidence.py +132 -0
- proef/api/v1/governance.py +35 -0
- proef/api/v1/inbox.py +119 -0
- proef/api/v1/lab.py +110 -0
- proef/api/v1/pauses.py +77 -0
- proef/api/v1/programs.py +397 -0
- proef/api/v1/results.py +147 -0
- proef/api/v1/schemas.py +932 -0
- proef/api/v1/system.py +79 -0
- proef/api/v1/trees.py +216 -0
- proef/api/wizard_sessions.py +253 -0
- proef/approvals.py +102 -0
- proef/assays/__init__.py +15 -0
- proef/assays/dls.py +114 -0
- proef/assays/dsf.py +81 -0
- proef/assays/elisa.py +58 -0
- proef/assays/properties.py +65 -0
- proef/assays/simulate.py +157 -0
- proef/audit.py +152 -0
- proef/autoloop.py +1620 -0
- proef/benchmark.py +442 -0
- proef/campaign_fsm.py +151 -0
- proef/citations.py +141 -0
- proef/cli.py +1249 -0
- proef/connect.py +74 -0
- proef/core/__init__.py +0 -0
- proef/core/contracts/__init__.py +35 -0
- proef/core/contracts/analysis.py +100 -0
- proef/core/contracts/models.py +395 -0
- proef/core/device_card.py +125 -0
- proef/core/hypothesis.py +720 -0
- proef/core/interfaces.py +164 -0
- proef/core/registry.py +123 -0
- proef/core/safety.py +324 -0
- proef/core/workflow.py +159 -0
- proef/critic.py +62 -0
- proef/demo.py +164 -0
- proef/derivation.py +128 -0
- proef/diary.py +301 -0
- proef/eln.py +87 -0
- proef/evals/__init__.py +1 -0
- proef/evals/hallucination.py +86 -0
- proef/evals/harness.py +358 -0
- proef/evals/orchestration.py +254 -0
- proef/evals/tasks.py +1010 -0
- proef/evals/toolcalls.py +425 -0
- proef/experiment.py +172 -0
- proef/experiment_analysis.py +114 -0
- proef/experiments/__init__.py +0 -0
- proef/experiments/grounding_exp.py +689 -0
- proef/figures.py +218 -0
- proef/fitting.py +309 -0
- proef/fixtures.py +140 -0
- proef/flywheel.py +125 -0
- proef/followup.py +126 -0
- proef/governance.py +290 -0
- proef/groundedness.py +361 -0
- proef/grounding.py +202 -0
- proef/hypothesis_agent.py +369 -0
- proef/ingest.py +157 -0
- proef/instruments.json +173 -0
- proef/interpret.py +95 -0
- proef/kinetic.py +102 -0
- proef/labread/__init__.py +45 -0
- proef/labread/analysis.py +428 -0
- proef/labread/common.py +153 -0
- proef/labread/formats.py +190 -0
- proef/labread/layout.py +168 -0
- proef/labread/pubchem.py +179 -0
- proef/labselect.py +431 -0
- proef/materials.py +140 -0
- proef/mcp_instrument.py +396 -0
- proef/mcp_server.py +283 -0
- proef/modality.py +111 -0
- proef/model_guard.py +245 -0
- proef/output_blocks.py +183 -0
- proef/paths.py +32 -0
- proef/physfail.py +55 -0
- proef/plan.py +160 -0
- proef/plots.py +123 -0
- proef/predictors.py +217 -0
- proef/probes.py +79 -0
- proef/problem_tree.py +581 -0
- proef/program.py +308 -0
- proef/protocol_design.py +42 -0
- proef/proxy.py +78 -0
- proef/readiness.py +259 -0
- proef/reliability.py +49 -0
- proef/report.py +117 -0
- proef/reproduce.py +310 -0
- proef/reviewer.py +254 -0
- proef/sandbox_session.py +247 -0
- proef/sandboxd.py +109 -0
- proef/scaffold.py +195 -0
- proef/series.py +327 -0
- proef/skills.py +203 -0
- proef/sweep.py +83 -0
- proef/taste.py +177 -0
- proef/templates/confirmatory-followup.json +34 -0
- proef/templates/dose-response-screen.json +39 -0
- proef/templates/sar-exploration.json +38 -0
- proef/templates.py +124 -0
- proef/toolkit.py +433 -0
- proef/toolloop.py +133 -0
- proef/tools.py +441 -0
- proef/tpp.py +185 -0
- proef/views/__init__.py +14 -0
- proef/views/counts.py +102 -0
- proef/views/experiment.py +154 -0
- proef/views/ids.py +49 -0
- proef/views/narrative.py +294 -0
- proef/views/pipeline.py +370 -0
- proef/vision.py +165 -0
- proef/watch.py +790 -0
- proef/wizard_chain.py +25 -0
- proef/wizard_store.py +373 -0
- proef-0.2.0.dist-info/METADATA +662 -0
- proef-0.2.0.dist-info/RECORD +200 -0
- proef-0.2.0.dist-info/WHEEL +4 -0
- proef-0.2.0.dist-info/entry_points.txt +14 -0
- proef-0.2.0.dist-info/licenses/LICENSE +202 -0
proef/reproduce.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"""`proef campaign reproduce`, replay a recorded experiment and diff the verdicts.
|
|
2
|
+
|
|
3
|
+
Reads a provenance branch, reconstructs the campaign EXACTLY as recorded
|
|
4
|
+
(hypotheses, criteria, lab adapter + seed, concentrations, autonomy, dose
|
|
5
|
+
design), re-runs it offline, and compares verdict-by-verdict. Reproducibility
|
|
6
|
+
as a command, not a promise.
|
|
7
|
+
|
|
8
|
+
Honest limits: LLM-proposed portfolios and live instruments cannot be replayed
|
|
9
|
+
byte-exactly (model drift, real-world noise), those branches report
|
|
10
|
+
`not-reproducible: <reason>` rather than faking a match.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def reproduce(branch: str, db_path: str = "proef.db",
|
|
19
|
+
inbox: str | Path | None = None) -> dict:
|
|
20
|
+
from proef.adapters.store.sqlite import SqliteProvenanceStore, get_store
|
|
21
|
+
store = get_store(db_path)
|
|
22
|
+
recs = store.branch_records(branch)
|
|
23
|
+
if not recs:
|
|
24
|
+
return {"status": "error", "reason": f"no records for '{branch}'"}
|
|
25
|
+
|
|
26
|
+
env: dict = {}
|
|
27
|
+
hypotheses: dict[str, dict] = {}
|
|
28
|
+
recorded: dict[str, dict] = {}
|
|
29
|
+
id_to_cand: dict[str, str] = {}
|
|
30
|
+
removed_ids: set[str] = set()
|
|
31
|
+
plan_declined = False
|
|
32
|
+
replanned = False
|
|
33
|
+
followed_up = False
|
|
34
|
+
responses: list[dict] = [] # sealed model answers, in call order
|
|
35
|
+
plan_decisions: list[dict] = [] # the person's plan reviews, in order
|
|
36
|
+
sealed_tools: list[dict] = [] # knowledge-tool results the original sealed
|
|
37
|
+
|
|
38
|
+
gen_contexts: list[str] = [] # what the flywheel put in each generation prompt
|
|
39
|
+
old_gen_contexts: list[str] = [] # branches recorded before attempts were: one per SUCCESSFUL generation
|
|
40
|
+
predictions: list[dict] = [] # every prediction the original sealed, so a replay runs no tool
|
|
41
|
+
first_score: dict[str, float] = {} # hypothesis id -> the score it was first selected on
|
|
42
|
+
for r in recs:
|
|
43
|
+
d = r.decision or {}
|
|
44
|
+
et = r.event_type.value
|
|
45
|
+
if et == "problem_defined":
|
|
46
|
+
env = d.get("environment") or {}
|
|
47
|
+
problem_doc = d
|
|
48
|
+
elif et == "hypothesis_proposed":
|
|
49
|
+
art = (r.artifact.metadata if r.artifact else {}) or {}
|
|
50
|
+
cand = art.get("candidate")
|
|
51
|
+
predictions.extend(p for p in (d.get("predictions") or []) if isinstance(p, dict))
|
|
52
|
+
if cand and r.artifact:
|
|
53
|
+
id_to_cand[r.artifact.artifact_id] = cand
|
|
54
|
+
if cand:
|
|
55
|
+
hypotheses[cand] = {
|
|
56
|
+
"statement": d.get("statement", ""),
|
|
57
|
+
"candidate": cand,
|
|
58
|
+
"assay_type": art.get("assay", "binding"),
|
|
59
|
+
"predicted": d.get("predicted", ""),
|
|
60
|
+
"predicted_value": (d.get("criteria") or {}).get(
|
|
61
|
+
"threshold"),
|
|
62
|
+
"mechanism": d.get("mechanism", ""),
|
|
63
|
+
"refutation_condition": d.get("refutation_condition", ""),
|
|
64
|
+
"citation": d.get("citation", ""),
|
|
65
|
+
"citation_status": d.get("citation_status", "unverified"),
|
|
66
|
+
# the family drives the per-round diversity cap and the flywheel prior: without it the
|
|
67
|
+
# replay would choose different batches than the original did
|
|
68
|
+
**({"family": d["family"]} if d.get("family") else {}),
|
|
69
|
+
**({"smiles": d["smiles"]} if d.get("smiles") else {}),
|
|
70
|
+
# the validator's verdict on the lab pick: a hypothesis the campaign's lab could not serve was never
|
|
71
|
+
# submitted, and its replay must not submit it either
|
|
72
|
+
**({"metadata": {"lab_check": d["lab_check"]}} if d.get("lab_check") else {}),
|
|
73
|
+
}
|
|
74
|
+
elif et == "tool_invocation" and d.get("kind") in ("model_response", "model_error"):
|
|
75
|
+
responses.append(d) # a call that FAILED is replayed as a failure, so the same fallback runs
|
|
76
|
+
elif et == "tool_invocation" and d.get("kind") == "tool_result":
|
|
77
|
+
sealed_tools.append(d) # a knowledge result (PubMed, ChEMBL...) the original sealed, played back with no network
|
|
78
|
+
elif et == "tool_invocation" and d.get("kind") == "generation_attempt":
|
|
79
|
+
gen_contexts.append(d.get("flywheel_context") or "")
|
|
80
|
+
elif et == "tool_invocation" and d.get("kind") == "hypothesis_generation":
|
|
81
|
+
old_gen_contexts.append(d.get("flywheel_context") or "")
|
|
82
|
+
elif et == "gate_decision" and d.get("kind") == "followup_proposal" and d.get("executes") and d.get("validation", {}).get("ok"):
|
|
83
|
+
followed_up = True
|
|
84
|
+
elif et == "hypotheses_filtered" and d.get("kind") not in ("plan_review", "acquisition_selection"):
|
|
85
|
+
for dec in d.get("decisions") or []:
|
|
86
|
+
if dec.get("score") is not None:
|
|
87
|
+
first_score.setdefault(dec.get("hypothesis_id"), float(dec["score"]))
|
|
88
|
+
elif et == "gate_decision" and d.get("kind") == "plan_decision":
|
|
89
|
+
plan_decisions.append(d)
|
|
90
|
+
# the person's review of a model's plan decides WHAT was run: replay the same plan
|
|
91
|
+
if d.get("stage", "initial") != "initial":
|
|
92
|
+
replanned = True
|
|
93
|
+
continue
|
|
94
|
+
plan_declined = plan_declined or not d.get("approved")
|
|
95
|
+
removed_ids |= set(d.get("removed") or [])
|
|
96
|
+
elif et in ("hypothesis_validated", "hypothesis_invalidated",
|
|
97
|
+
"hypothesis_inconclusive",
|
|
98
|
+
"hypothesis_tested"):
|
|
99
|
+
art = (r.artifact.metadata if r.artifact else {}) or {}
|
|
100
|
+
cand = art.get("candidate")
|
|
101
|
+
if cand and d.get("verdict"):
|
|
102
|
+
recorded[cand] = d # last one wins (final state)
|
|
103
|
+
|
|
104
|
+
agent_replay = bool(responses) and env.get("hypothesis_source") == "agent"
|
|
105
|
+
if followed_up and not agent_replay and any((r.decision or {}).get("followup_of") for r in recs if r.event_type.value == "hypothesis_proposed"):
|
|
106
|
+
return {"status": "not-reproducible",
|
|
107
|
+
"reason": "the model suggested follow-ups after a round and they were run; that step needs the model and is not replayed"}
|
|
108
|
+
if replanned and not agent_replay:
|
|
109
|
+
return {"status": "not-reproducible",
|
|
110
|
+
"reason": "the model re-planned after a round; that step needs the model and is not replayed"}
|
|
111
|
+
if plan_declined:
|
|
112
|
+
return {"status": "not-reproducible", "reason": "the research plan was declined: nothing was run"}
|
|
113
|
+
for hid in removed_ids:
|
|
114
|
+
hypotheses.pop(id_to_cand.get(hid, ""), None)
|
|
115
|
+
# the original run ranked its hypotheses by the model's own confidences, which a replay does not have:
|
|
116
|
+
# reuse the scores it recorded, so the same batches are chosen in the same order (and the lab's noise,
|
|
117
|
+
# which depends on run order, comes out the same)
|
|
118
|
+
cand_score = {id_to_cand[h]: s for h, s in first_score.items() if h in id_to_cand}
|
|
119
|
+
|
|
120
|
+
if not env.get("lab_seed") and env.get("lab") != "simulator":
|
|
121
|
+
return {"status": "not-reproducible",
|
|
122
|
+
"reason": "no recorded lab environment (pre-environment "
|
|
123
|
+
"provenance) or live lab, re-run once to capture"}
|
|
124
|
+
if not hypotheses and not agent_replay:
|
|
125
|
+
return {"status": "not-reproducible",
|
|
126
|
+
"reason": "no candidate hypotheses in branch"}
|
|
127
|
+
|
|
128
|
+
from proef.adapters.lab.simulator import SimulatorLab
|
|
129
|
+
from proef.autoloop import CampaignConfig, run_campaign
|
|
130
|
+
from proef.core.hypothesis import Constraint, ProblemStatement
|
|
131
|
+
|
|
132
|
+
labs = {"simulator": SimulatorLab}
|
|
133
|
+
lab_cls = labs.get(env.get("lab", "simulator"))
|
|
134
|
+
if lab_cls is None:
|
|
135
|
+
return {"status": "not-reproducible",
|
|
136
|
+
"reason": f"no replay adapter for lab '{env.get('lab')}' "
|
|
137
|
+
"(live labs replay via recording playback, not here)"}
|
|
138
|
+
|
|
139
|
+
_replay_base = (problem_doc.get("problem_id") or "prob") + "-replay"
|
|
140
|
+
_replay_id, _k = _replay_base, 1
|
|
141
|
+
while store.branch_records(f"problem/{_replay_id}"):
|
|
142
|
+
_k += 1
|
|
143
|
+
_replay_id = f"{_replay_base}-{_k}"
|
|
144
|
+
problem = ProblemStatement(
|
|
145
|
+
objective=problem_doc.get("objective", ""),
|
|
146
|
+
problem_id=_replay_id,
|
|
147
|
+
constraints=[Constraint(**c)
|
|
148
|
+
for c in problem_doc.get("constraints", [])])
|
|
149
|
+
from proef.core.hypothesis import explanatory_bonus
|
|
150
|
+
from proef.flywheel import Flywheel
|
|
151
|
+
cfg = CampaignConfig(
|
|
152
|
+
problem=problem,
|
|
153
|
+
score_fn=(lambda h: cand_score.get(h.candidate, 0.5) - explanatory_bonus(h)) if cand_score else None,
|
|
154
|
+
hypotheses=list(hypotheses.values()),
|
|
155
|
+
# replay runs the loop the way it was recorded: an approval-gated run did not auto-confirm, so neither
|
|
156
|
+
# does its replay (the person's earlier approvals are stood in for by an auto-approver below).
|
|
157
|
+
# Records from before the rounds were captured replay as one round, as they always did.
|
|
158
|
+
k=env.get("k", 2), rounds=int(env.get("rounds", 1)),
|
|
159
|
+
autonomy=env.get("autonomy") if env.get("autonomy") in ("gate", "act") else "act",
|
|
160
|
+
inbox=str(inbox or ".data/reproduce-inbox"),
|
|
161
|
+
concentrations=tuple(env.get("concentrations",
|
|
162
|
+
["0.5uM", "2uM", "10uM", "40uM"])),
|
|
163
|
+
dose_design=env.get("dose_design", "fixed"),
|
|
164
|
+
poll_secs=0.05,
|
|
165
|
+
# a replay must start from a clean memory and must not feed the user's real flywheel
|
|
166
|
+
flywheel=Flywheel(":memory:"))
|
|
167
|
+
rm = None
|
|
168
|
+
if agent_replay:
|
|
169
|
+
# an agent campaign replays with the model's sealed answers, never a model: re-plans and follow-ups included
|
|
170
|
+
cfg, rm = _agent_cfg(cfg, env, responses, plan_decisions, gen_contexts or old_gen_contexts, first_score, predictions, sealed_tools)
|
|
171
|
+
_seed = env.get("lab_seed")
|
|
172
|
+
if _seed is None:
|
|
173
|
+
_seed = 7 # pre-seed-capture branches default
|
|
174
|
+
_knobs = (env.get("lab_config") or ({"instruments": env["lab_capabilities"]} if env.get("lab_capabilities") else {})) if agent_replay else {}
|
|
175
|
+
lab = lab_cls(seed=_seed, **_knobs)
|
|
176
|
+
report = run_campaign(cfg, lab, SqliteProvenanceStore(),
|
|
177
|
+
approver=(lambda title: True) if cfg.autonomy == "gate" else None)
|
|
178
|
+
divergences = list(getattr(rm, "divergences", []) or [])
|
|
179
|
+
if rm is not None and not divergences and rm.remaining():
|
|
180
|
+
divergences.append({"call": len(responses) - rm.remaining() + 1, "why": f"the replay stopped {rm.remaining()} model call(s) short of the original"})
|
|
181
|
+
|
|
182
|
+
diffs, matches = [], 0
|
|
183
|
+
for cand, rec in sorted(recorded.items()):
|
|
184
|
+
new_v = report.verdicts.get(cand)
|
|
185
|
+
old_v = rec.get("verdict")
|
|
186
|
+
if new_v == old_v:
|
|
187
|
+
matches += 1
|
|
188
|
+
else:
|
|
189
|
+
diffs.append({"candidate": cand, "recorded": old_v,
|
|
190
|
+
"replayed": new_v})
|
|
191
|
+
# the other direction: anything the replay judged that the original never did is a difference too. Before this, a
|
|
192
|
+
# replay that ran extra hypotheses was reported as a match, because only the recorded verdicts were compared.
|
|
193
|
+
for cand, new_v in sorted(report.verdicts.items()):
|
|
194
|
+
if cand not in recorded and new_v not in (None, "proposed"):
|
|
195
|
+
diffs.append({"candidate": cand, "recorded": None, "replayed": new_v})
|
|
196
|
+
for d in divergences:
|
|
197
|
+
diffs.append({"candidate": None, "recorded": "model call", "replayed": d["why"], "call": d["call"]})
|
|
198
|
+
n = len(recorded)
|
|
199
|
+
return {
|
|
200
|
+
"status": "match" if not diffs and n else ("differs" if n else
|
|
201
|
+
"no-verdicts"),
|
|
202
|
+
"branch": branch, "recorded_verdicts": n, "matched": matches,
|
|
203
|
+
"diffs": diffs,
|
|
204
|
+
"environment": env,
|
|
205
|
+
"model_pinned": rm is not None,
|
|
206
|
+
"model_calls_replayed": (len(responses) - rm.remaining()) if rm is not None else 0,
|
|
207
|
+
"note": (("simulated replay: identical lab seeds & structures, and every model answer played back from the ledger "
|
|
208
|
+
"(the model is never asked, and any call that differs from the original is reported)")
|
|
209
|
+
if rm is not None else
|
|
210
|
+
("simulated replay: identical lab seeds & structures; "
|
|
211
|
+
"the generation model "
|
|
212
|
+
f"{env.get('model') or 'n/a'} is NOT re-invoked: "
|
|
213
|
+
"hypotheses are replayed exactly as recorded. "
|
|
214
|
+
"Reproduced: the EXECUTION path, not the model's "
|
|
215
|
+
"creative step.")),
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _sealed_tool_results(sealed: list[dict]) -> dict:
|
|
220
|
+
"""The knowledge results the original sealed, by (tool, arguments hash): a replay plays them back and never calls the network."""
|
|
221
|
+
return {(d.get("tool"), d.get("args_hash")) + ((d["scope"],) if d.get("scope") else ()): d.get("result") for d in sealed}
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class _FrozenFlywheel:
|
|
225
|
+
"""What a replay uses in place of the flywheel: the contexts the original put in its prompts, in order, and no priors. The
|
|
226
|
+
original's priors are not reconstructible, so selection scores come from the recorded ones instead (`_agent_cfg`)."""
|
|
227
|
+
|
|
228
|
+
def __init__(self, contexts: list[str]):
|
|
229
|
+
self._ctx = list(contexts)
|
|
230
|
+
self._i = 0
|
|
231
|
+
|
|
232
|
+
def prompt_context(self) -> str:
|
|
233
|
+
c = self._ctx[self._i] if self._i < len(self._ctx) else ""
|
|
234
|
+
self._i += 1
|
|
235
|
+
return c
|
|
236
|
+
|
|
237
|
+
def prior_bonus(self, family: str | None) -> float:
|
|
238
|
+
return 0.0
|
|
239
|
+
|
|
240
|
+
def submit(self, *a, **kw) -> None:
|
|
241
|
+
return None
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _agent_cfg(cfg, env: dict, responses: list[dict], plan_decisions: list[dict], gen_contexts: list[str], first_score: dict,
|
|
245
|
+
predictions: list[dict] | None = None, sealed_tools: list[dict] | None = None):
|
|
246
|
+
"""Turn the replay config into an AGENT campaign driven by the recorded model answers and the recorded plan reviews."""
|
|
247
|
+
from dataclasses import replace
|
|
248
|
+
|
|
249
|
+
from proef.autoloop import ResourceBudget
|
|
250
|
+
from proef.core.hypothesis import explanatory_bonus
|
|
251
|
+
from proef.model_guard import RecordedModel
|
|
252
|
+
from proef.plan import PlanDecision
|
|
253
|
+
rm = RecordedModel(responses)
|
|
254
|
+
pending = iter(plan_decisions)
|
|
255
|
+
|
|
256
|
+
def approver(plan: dict, problem_id: str):
|
|
257
|
+
try:
|
|
258
|
+
d = next(pending)
|
|
259
|
+
except StopIteration:
|
|
260
|
+
rm.divergences.append({"call": 0, "why": "the replay asked for a plan review the original did not have"})
|
|
261
|
+
return PlanDecision(approved=False, by="replay")
|
|
262
|
+
return PlanDecision(approved=bool(d.get("approved")), excluded=set(d.get("removed") or []), by=d.get("decided_by") or "replay",
|
|
263
|
+
note=d.get("note") or "")
|
|
264
|
+
return replace(
|
|
265
|
+
cfg, hypotheses=None, hypothesis_source="agent", model=rm, critic_model=rm if env.get("critic") else None,
|
|
266
|
+
followups=bool(env.get("followups")), replan=bool(env.get("replan")),
|
|
267
|
+
orchestrator="model" if env.get("orchestrator") == "model" else "fixed",
|
|
268
|
+
max_families=int(env.get("max_families", cfg.max_families)),
|
|
269
|
+
max_variants_per_family=int(env.get("max_variants_per_family", cfg.max_variants_per_family)),
|
|
270
|
+
modality=env.get("modality") or None, prediction_tools=list(env.get("prediction_tools") or []) or None,
|
|
271
|
+
prediction_registry=_RecordedPredictors(predictions or [], rm) if env.get("prediction_tools") else None,
|
|
272
|
+
labs=env.get("labs") or None, lab_requirement=env.get("lab_requirement") or None,
|
|
273
|
+
budget=ResourceBudget(**env["budget"]) if env.get("budget") else None,
|
|
274
|
+
plan_approver=approver if env.get("plan_review") else None,
|
|
275
|
+
# the original's selection scores, by hypothesis id (ids are a hash of the statement, candidate and round, so a replay
|
|
276
|
+
# that gets the same answers makes the same ids)
|
|
277
|
+
score_fn=(lambda h: first_score.get(h.hypothesis_id, 0.5) - explanatory_bonus(h)) if first_score else None,
|
|
278
|
+
grounding_tools=tuple(env.get("grounding_tools") or ()), ground_hypotheses=bool(env.get("ground_hypotheses")), ground_compute=tuple(env.get("ground_compute") or ()), grounding_decide=bool(env.get("grounding_decide", True)), grounding_names=env.get("grounding_names") or "all",
|
|
279
|
+
blinding=({"exclude": [], "cutoff": env["blinding"].get("cutoff"), "off_tools": env["blinding"].get("off_tools") or []} if env.get("blinding") else None), loop_compute=tuple(env.get("loop_compute") or ()),
|
|
280
|
+
grounding_public_names=tuple(env.get("grounding_public_names") or ()), grounding_replay=_sealed_tool_results(sealed_tools or []),
|
|
281
|
+
flywheel=_FrozenFlywheel(gen_contexts)), rm
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
class _RecordedPredictors:
|
|
285
|
+
"""A replay's stand-in for the prediction registry: the menu text comes from the real registry (it is part of the prompt, which is
|
|
286
|
+
checked), but a prediction is looked up in what the original sealed, by tool and input. No tool is ever run. A prediction the
|
|
287
|
+
original did not make is a divergence."""
|
|
288
|
+
|
|
289
|
+
def __init__(self, recorded: list[dict], rm):
|
|
290
|
+
from proef.predictors import DEFAULT
|
|
291
|
+
self._real, self._rm = DEFAULT, rm
|
|
292
|
+
self._by = {(p.get("tool"), p.get("input") or ""): p for p in recorded}
|
|
293
|
+
|
|
294
|
+
def menu(self, enabled, modality):
|
|
295
|
+
return self._real.menu(enabled, modality)
|
|
296
|
+
|
|
297
|
+
def menu_text(self, specs):
|
|
298
|
+
return self._real.menu_text(specs)
|
|
299
|
+
|
|
300
|
+
def run(self, requested, inputs, enabled, modality):
|
|
301
|
+
out = []
|
|
302
|
+
from proef.predictors import MAX_TOOLS_PER_VARIANT
|
|
303
|
+
for name in list(dict.fromkeys(str(n)[:80] for n in (requested or [])))[:MAX_TOOLS_PER_VARIANT]:
|
|
304
|
+
hit = self._by.get((name, str((inputs or {}).get("smiles") or "")[:120])) or self._by.get((name, ""))
|
|
305
|
+
if hit is None:
|
|
306
|
+
self._rm.divergences.append({"call": 0, "why": f"a prediction by {name} that the original did not make"})
|
|
307
|
+
out.append({"tool": name, "kind": "prediction", "evidence": False, "status": "error", "reason": "not in the recording"})
|
|
308
|
+
else:
|
|
309
|
+
out.append(hit)
|
|
310
|
+
return out
|
proef/reviewer.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""The reviewer pass — an independent audit over a campaign's analysis.
|
|
2
|
+
|
|
3
|
+
Pattern from Anthropic's science stack and The Virtual Biotech: a
|
|
4
|
+
separate reviewer inspects methodology and claims before results are
|
|
5
|
+
finalized. Design rules that keep it tiered-trust compliant:
|
|
6
|
+
|
|
7
|
+
- Deterministic, rule-based, OFFLINE: the reviewer is ordinary
|
|
8
|
+
verification code, not an LLM's opinion — the same findings on the
|
|
9
|
+
same records, eval-verifiable.
|
|
10
|
+
- It may DEMAND REVISION (findings are recorded as provenance and
|
|
11
|
+
surfaced in the workbench) but it can NEVER clear a refusal or
|
|
12
|
+
overturn a gate — tightening only, like every AI actor here.
|
|
13
|
+
- It reviews the ANALYSIS, not the science: math consistency
|
|
14
|
+
(verdict labels vs observed values vs CIs vs gates), evidence
|
|
15
|
+
linkage (every verdict traceable to a recorded run), citation
|
|
16
|
+
integrity (invalid citations cannot back validated claims).
|
|
17
|
+
|
|
18
|
+
Findings: [{severity: critical|warning, kind, candidate?, detail}].
|
|
19
|
+
critical = the verdict as recorded contradicts the recorded evidence.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
|
|
25
|
+
from proef.core.contracts import (
|
|
26
|
+
Envelope, ToolInvocation, ToolName)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def review_campaign(recs) -> dict:
|
|
30
|
+
findings: list[dict] = []
|
|
31
|
+
runs: set[str] = set()
|
|
32
|
+
verdicts: dict[str, dict] = {} # candidate -> latest final event
|
|
33
|
+
tests: dict[str, int] = {} # candidate -> analyzed-run count
|
|
34
|
+
for r in recs:
|
|
35
|
+
d = r.decision or {}
|
|
36
|
+
et = r.event_type.value
|
|
37
|
+
art_meta = (r.artifact.metadata or {}) if r.artifact else {}
|
|
38
|
+
cand = d.get("candidate") or art_meta.get("candidate")
|
|
39
|
+
if et == "lab_run" and d.get("run_id"):
|
|
40
|
+
runs.add(d["run_id"])
|
|
41
|
+
elif et == "hypothesis_tested":
|
|
42
|
+
# any tested record (attach or legacy verdict) = an analyzed read
|
|
43
|
+
if cand:
|
|
44
|
+
tests[str(cand)] = tests.get(str(cand), 0) + 1
|
|
45
|
+
elif d.get("verdict") and et in (
|
|
46
|
+
"hypothesis_validated", "hypothesis_invalidated",
|
|
47
|
+
"hypothesis_inconclusive", "hypothesis_tested"):
|
|
48
|
+
# EVERY verdict is audited — including refuted confirmations and
|
|
49
|
+
# abstentions, which is exactly where the contradictions hide
|
|
50
|
+
key = str(cand or d.get("hypothesis_id") or art_meta.get(
|
|
51
|
+
"candidate") or len(verdicts))
|
|
52
|
+
verdicts[key] = {"verdict": d.get("verdict"),
|
|
53
|
+
"observed": d.get("observed"),
|
|
54
|
+
"ci": d.get("observed_ci"),
|
|
55
|
+
"threshold": d.get("threshold"),
|
|
56
|
+
"metric": d.get("metric"),
|
|
57
|
+
"direction": d.get("direction"),
|
|
58
|
+
"candidate": str(cand) if cand else None,
|
|
59
|
+
"evidence": d.get("evidence_run_id"),
|
|
60
|
+
"event": et}
|
|
61
|
+
|
|
62
|
+
# pre-registered gate directions: constraint descriptions carry the
|
|
63
|
+
# comparison (>= / <=); verdict records may omit direction, so the
|
|
64
|
+
# pre-registration wins as the fallback
|
|
65
|
+
gate_dirs: dict[str, str] = {}
|
|
66
|
+
for r in recs:
|
|
67
|
+
if r.event_type.value == "problem_defined":
|
|
68
|
+
for c in (r.decision or {}).get("constraints") or []:
|
|
69
|
+
if c.get("name"):
|
|
70
|
+
gate_dirs[c["name"]] = (
|
|
71
|
+
"max" if ">=" in (c.get("description") or "")
|
|
72
|
+
else "min")
|
|
73
|
+
|
|
74
|
+
for key, v in verdicts.items():
|
|
75
|
+
cand = v.get("candidate") or key
|
|
76
|
+
verdict, observed, ci = v.get("verdict"), v.get("observed"), v.get("ci")
|
|
77
|
+
gate = v.get("threshold")
|
|
78
|
+
direction = v.get("direction") or gate_dirs.get(
|
|
79
|
+
v.get("metric") or "", "min")
|
|
80
|
+
|
|
81
|
+
# 1. label vs observation vs gate — direction-aware: min-metrics
|
|
82
|
+
# (ic50) want observed below the gate; max-metrics (tensile
|
|
83
|
+
# strength, t_half, yield) want it above. Inconclusive is exempt,
|
|
84
|
+
# and an abstention may carry NO observation (censored plates):
|
|
85
|
+
# compute the comparison only when a number exists.
|
|
86
|
+
worse_than_gate = (observed is not None and gate is not None
|
|
87
|
+
and (observed > gate if direction == "min"
|
|
88
|
+
else observed < gate))
|
|
89
|
+
if verdict in ("validated", "confirmed") and observed is not None \
|
|
90
|
+
and gate is not None and worse_than_gate:
|
|
91
|
+
if not (ci and ci[0] <= gate <= ci[1]):
|
|
92
|
+
sym = ">" if direction == "min" else "<"
|
|
93
|
+
findings.append({
|
|
94
|
+
"severity": "critical", "kind": "label-vs-data",
|
|
95
|
+
"candidate": cand,
|
|
96
|
+
"detail": f"{verdict} but {observed} {sym} gate "
|
|
97
|
+
f"{gate} and CI does not straddle the gate"})
|
|
98
|
+
|
|
99
|
+
# 2. CI sanity
|
|
100
|
+
if ci and len(ci) == 2 and ci[0] > ci[1]:
|
|
101
|
+
findings.append({"severity": "critical", "kind": "ci-malformed",
|
|
102
|
+
"candidate": cand,
|
|
103
|
+
"detail": f"CI {ci} is inverted"})
|
|
104
|
+
|
|
105
|
+
# 3. evidence linkage: a final verdict must point at a recorded run
|
|
106
|
+
if verdict in ("validated", "confirmed", "refuted", "invalidated",
|
|
107
|
+
"inconclusive") and runs:
|
|
108
|
+
ev = v.get("evidence")
|
|
109
|
+
if not ev:
|
|
110
|
+
findings.append({"severity": "warning", "kind": "no-evidence",
|
|
111
|
+
"candidate": cand,
|
|
112
|
+
"detail": f"{verdict} without an "
|
|
113
|
+
"evidence_run_id"})
|
|
114
|
+
elif ev not in runs:
|
|
115
|
+
findings.append({"severity": "critical",
|
|
116
|
+
"kind": "evidence-unrecorded",
|
|
117
|
+
"candidate": cand,
|
|
118
|
+
"detail": f"evidence run {ev} is not in "
|
|
119
|
+
"the recorded lab runs"})
|
|
120
|
+
|
|
121
|
+
# 4. a final claim needs at least one analyzed read
|
|
122
|
+
if verdict in ("validated", "confirmed") and not tests.get(cand):
|
|
123
|
+
findings.append({"severity": "warning", "kind": "no-analyzed-read",
|
|
124
|
+
"candidate": cand,
|
|
125
|
+
"detail": f"{verdict} without any analyzed "
|
|
126
|
+
"hypothesis_tested record"})
|
|
127
|
+
|
|
128
|
+
critical = sum(1 for f in findings if f["severity"] == "critical")
|
|
129
|
+
return {"findings": findings, "critical": critical,
|
|
130
|
+
"warnings": len(findings) - critical,
|
|
131
|
+
"verdicts_reviewed": len(verdicts),
|
|
132
|
+
"review": "reviewer-v1"}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# ---------------------------------------------------------- LLM advisory
|
|
136
|
+
|
|
137
|
+
LLM_REVIEW_VERSION = "reviewer-llm-v1"
|
|
138
|
+
FLAG_KINDS = ("mechanism-concern", "evidence-quality", "dose-design",
|
|
139
|
+
"confounder", "citation-relevance")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _campaign_summary(recs) -> dict:
|
|
143
|
+
"""Compact deterministic summary the LLM reviews — never raw files."""
|
|
144
|
+
verdicts, runs, citations, refusals = [], set(), [], 0
|
|
145
|
+
for r in recs:
|
|
146
|
+
d = r.decision or {}
|
|
147
|
+
et = r.event_type.value
|
|
148
|
+
cand = ((r.artifact.metadata or {}).get("candidate")
|
|
149
|
+
if r.artifact else None) or d.get("candidate")
|
|
150
|
+
if et == "lab_run" and d.get("run_id"):
|
|
151
|
+
runs.add(d["run_id"])
|
|
152
|
+
elif et == "gate_decision":
|
|
153
|
+
refusals += 1
|
|
154
|
+
elif et in ("hypothesis_validated", "hypothesis_invalidated",
|
|
155
|
+
"hypothesis_inconclusive",
|
|
156
|
+
"hypothesis_tested") and (d.get("verdict") or cand):
|
|
157
|
+
if d.get("verdict"):
|
|
158
|
+
verdicts.append({
|
|
159
|
+
"candidate": str(cand) if cand else None,
|
|
160
|
+
"verdict": d.get("verdict"),
|
|
161
|
+
"observed": d.get("observed"),
|
|
162
|
+
"ci": d.get("observed_ci"),
|
|
163
|
+
"gate": d.get("threshold"),
|
|
164
|
+
"evidence": d.get("evidence_run_id"),
|
|
165
|
+
"method": (d.get("derivation") or {}).get("method")
|
|
166
|
+
if isinstance(d.get("derivation"), dict)
|
|
167
|
+
else None})
|
|
168
|
+
if d.get("citation"):
|
|
169
|
+
citations.append({"candidate": str(cand) if cand else None,
|
|
170
|
+
"citation": d.get("citation"),
|
|
171
|
+
"status": d.get("citation_status",
|
|
172
|
+
"unverified")})
|
|
173
|
+
return {"verdicts": verdicts, "citations": citations,
|
|
174
|
+
"runs_recorded": len(runs), "gate_refusals": refusals}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
SYSTEM_PROMPT = (
|
|
178
|
+
"You are the scientific reviewer in a drug-discovery provenance "
|
|
179
|
+
"system. You review a campaign's analysis summary. You may ONLY add "
|
|
180
|
+
"up to 5 advisory flags about methodology, evidence quality, dose "
|
|
181
|
+
"design, confounders, or citation relevance. You CANNOT validate, "
|
|
182
|
+
"invalidate, clear refusals, or change any verdict — attempts to do "
|
|
183
|
+
"so are discarded. Respond with STRICT JSON only: "
|
|
184
|
+
'{\"flags\": [{\"kind\": one of ["mechanism-concern", '
|
|
185
|
+
'\"evidence-quality\", \"dose-design\", \"confounder\", '
|
|
186
|
+
'\"citation-relevance\"], \"candidate\": optional, '
|
|
187
|
+
'\"detail\": ..., \"evidence_quote\": optional}]}. '
|
|
188
|
+
"If nothing warrants a flag, respond with {\"flags\": []}.")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def review_llm(recs, provider) -> dict:
|
|
192
|
+
"""The LLM reviewer variant — advisory layer over the deterministic
|
|
193
|
+
floor. May ADD flags; structurally cannot alter verdicts or gates
|
|
194
|
+
(the flag schema has no such field, and flags never enter the
|
|
195
|
+
verdict pipeline). Failures are honest and non-blocking."""
|
|
196
|
+
import hashlib
|
|
197
|
+
summary = _campaign_summary(recs)
|
|
198
|
+
prompt = ("Review this campaign analysis summary and add advisory "
|
|
199
|
+
"flags where methodology, evidence quality, dose design, "
|
|
200
|
+
"confounders, or citation relevance warrant them:\n"
|
|
201
|
+
+ json.dumps(summary, default=str))
|
|
202
|
+
prompt_hash = hashlib.sha256(prompt.encode()).hexdigest()[:12]
|
|
203
|
+
invocation = ToolInvocation(envelope=Envelope(
|
|
204
|
+
experiment_branch_id="review"), tool=ToolName.kb_search_literature)
|
|
205
|
+
try:
|
|
206
|
+
result = provider.generate(invocation, prompt,
|
|
207
|
+
system=SYSTEM_PROMPT)
|
|
208
|
+
except Exception as exc: # noqa: BLE001
|
|
209
|
+
return {"review": LLM_REVIEW_VERSION, "unavailable":
|
|
210
|
+
f"provider failed: {str(exc)[:120]}",
|
|
211
|
+
"model": getattr(provider, "name", "?"),
|
|
212
|
+
"prompt_hash": prompt_hash, "flags": []}
|
|
213
|
+
text = ""
|
|
214
|
+
if isinstance(result.output, dict):
|
|
215
|
+
text = str(result.output.get("text", ""))
|
|
216
|
+
# extract the first JSON object
|
|
217
|
+
start = text.find("{")
|
|
218
|
+
parsed = None
|
|
219
|
+
if start >= 0:
|
|
220
|
+
depth = 0
|
|
221
|
+
for i in range(start, len(text)):
|
|
222
|
+
if text[i] == "{":
|
|
223
|
+
depth += 1
|
|
224
|
+
elif text[i] == "}":
|
|
225
|
+
depth -= 1
|
|
226
|
+
if depth == 0:
|
|
227
|
+
try:
|
|
228
|
+
parsed = json.loads(text[start:i + 1])
|
|
229
|
+
except json.JSONDecodeError:
|
|
230
|
+
parsed = None
|
|
231
|
+
break
|
|
232
|
+
if not isinstance(parsed, dict):
|
|
233
|
+
return {"review": LLM_REVIEW_VERSION,
|
|
234
|
+
"unavailable": "response was not parseable JSON",
|
|
235
|
+
"model": f"{getattr(provider, 'name', '?')}/"
|
|
236
|
+
f"{getattr(provider, 'model_version', '?')}",
|
|
237
|
+
"prompt_hash": prompt_hash, "flags": []}
|
|
238
|
+
flags = []
|
|
239
|
+
for f in (parsed.get("flags") or [])[:5]:
|
|
240
|
+
if not isinstance(f, dict):
|
|
241
|
+
continue
|
|
242
|
+
if f.get("kind") not in FLAG_KINDS:
|
|
243
|
+
continue # out-of-whitelist: discarded
|
|
244
|
+
flags.append({"kind": f["kind"],
|
|
245
|
+
"candidate": str(f.get("candidate", "")) or None,
|
|
246
|
+
"detail": str(f.get("detail", ""))[:300],
|
|
247
|
+
"evidence_quote": str(f.get("evidence_quote", ""))[:200]
|
|
248
|
+
or None})
|
|
249
|
+
return {"review": LLM_REVIEW_VERSION,
|
|
250
|
+
"model": f"{getattr(provider, 'name', '?')}/"
|
|
251
|
+
f"{getattr(provider, 'model_version', '?')}",
|
|
252
|
+
"prompt_hash": prompt_hash,
|
|
253
|
+
"flags": flags}
|
|
254
|
+
|