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/cli.py ADDED
@@ -0,0 +1,1249 @@
1
+ """`proef` CLI, boring on purpose (P1).
2
+
3
+ proef campaign run workflow.yml # execute a workflow against configured adapters
4
+ proef demo # guided first run on the virtual lab
5
+ proef prove <branch_id> # print the hash-chained provenance for a branch
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from proef.paths import APPROVALS_FILE
10
+
11
+ import argparse
12
+ import json
13
+ import sys
14
+ from pathlib import Path
15
+
16
+
17
+ def _load_workflow(path: str) -> dict:
18
+ import yaml # optional extra; kept out of core deps
19
+
20
+ with open(path) as f:
21
+ return yaml.safe_load(f)
22
+
23
+
24
+ def _build_default_registry(cfg: dict):
25
+ from proef.adapters.lab.simulator import SimulatorLab
26
+ from proef.adapters.store.sqlite import SqliteProvenanceStore
27
+ from proef.adapters.models.openai_compat import OpenAICompatProvider
28
+ from proef.core.registry import Registry
29
+
30
+ registry = Registry()
31
+ model_cfg = cfg.get("model", {})
32
+ provider = OpenAICompatProvider(
33
+ model=model_cfg.get("name", "stub-1"),
34
+ base_url=model_cfg.get("base_url"),
35
+ )
36
+ registry.register_model(provider, default=True)
37
+ lab_cfg = cfg.get("lab", {})
38
+ lab = (
39
+ SimulatorLab(seed=lab_cfg.get("seed", 7))
40
+ if lab_cfg.get("adapter", "simulator") == "simulator"
41
+ else _load_adapter(lab_cfg["adapter"], lab_cfg.get("options", {}))
42
+ )
43
+ store = SqliteProvenanceStore(cfg.get("store", {}).get("path", "proef.db"))
44
+ return registry, lab, store
45
+
46
+
47
+ def _load_adapter(path: str, options: dict):
48
+ from proef.core.registry import import_string
49
+
50
+ cls = import_string(path)
51
+ return cls(**options)
52
+
53
+
54
+ def cmd_run(args: argparse.Namespace) -> int:
55
+ cfg = _load_workflow(args.workflow)
56
+ registry, lab, store = _build_default_registry(cfg)
57
+ from proef.core.contracts import Actor, Envelope, ToolInvocation
58
+ from proef.core.safety import LabGateway, SafetyEngine
59
+ from proef.core.workflow import HypothesisTournament, TournamentConfig
60
+
61
+ actor = Actor(kind="service", id="proef-cli")
62
+ branch = cfg.get("branch", "run-1")
63
+ envelope = Envelope(experiment_branch_id=branch)
64
+ safety = SafetyEngine() # operator rules may be extended via cfg["safety"]
65
+ from proef.governance import execution_governance
66
+ # same physics as a campaign: halt + authorization matrix bind here too
67
+ gateway = LabGateway(lab, safety, store, actor,
68
+ governance=execution_governance())
69
+
70
+ tcfg = cfg.get("tournament", {})
71
+ tournament = HypothesisTournament(
72
+ registry.model,
73
+ TournamentConfig(
74
+ population=tcfg.get("population", 8),
75
+ survivors=tcfg.get("survivors", 3),
76
+ waves=tcfg.get("waves", 2),
77
+ ),
78
+ )
79
+ inv = ToolInvocation(envelope=envelope, tool="c.fm.generate_molecules", args={})
80
+ target = cfg.get("target", "target-1")
81
+ gen = registry.model.generate(inv, f"generate candidates for {target}", n=tcfg.get("population", 8))
82
+ candidates = json.loads(gen.output["text"])
83
+ ranked = tournament.run(
84
+ branch,
85
+ seed_context={"target": target},
86
+ generate_fn=lambda ctx: candidates,
87
+ score_fn=lambda p: int(p.get("smiles", "").count("C")) * 0.1,
88
+ )
89
+ print(f"[proef] survivors: {[c['smiles'] for c in ranked]}")
90
+
91
+ if cfg.get("assay", {}).get("enabled", True):
92
+ from proef.core.contracts import (
93
+ ProtocolOp,
94
+ ProtocolStep,
95
+ ProtocolSubmission,
96
+ ReagentSpec,
97
+ SampleKind,
98
+ SampleSpec,
99
+ )
100
+ top = ranked[0]["smiles"]
101
+ protocol = ProtocolSubmission(
102
+ envelope=envelope,
103
+ title=f"assay {top}",
104
+ assay_type=cfg["assay"].get("type", "binding"),
105
+ steps=[ProtocolStep(seq=1, op=ProtocolOp.dispense, params={"volume_ul": 50})],
106
+ samples=[SampleSpec(sample_id=top, kind=SampleKind.compound)],
107
+ reagents=[ReagentSpec(name="buffer-A", amount="10 mL", bsl_level=1)],
108
+ )
109
+ run_id, rejection = gateway.submit(protocol)
110
+ if rejection:
111
+ print(f"[proef] safety rejected: {rejection}")
112
+ return 1
113
+ result = gateway.results(envelope, run_id)
114
+ print(f"[proef] run {run_id}: {result.measurements[0].value} {result.measurements[0].unit}")
115
+ print(f"[proef] provenance: proef prove {branch}")
116
+ return 0
117
+
118
+
119
+ def cmd_audit(args: argparse.Namespace) -> int:
120
+ from proef.adapters.store.sqlite import SqliteProvenanceStore
121
+ from proef.audit import audit_campaign
122
+
123
+ store = SqliteProvenanceStore(args.db)
124
+ records = store.branch_records(args.branch)
125
+ if not records:
126
+ print(f"no records for branch '{args.branch}' in {args.db}")
127
+ return 1
128
+ violations = audit_campaign(records, store=store, branch=args.branch)
129
+ if not violations:
130
+ print(f"audit clean: {len(records)} records, 0 violations")
131
+ return 0
132
+ print(f"{len(violations)} violation(s) in {len(records)} records:")
133
+ for v in violations:
134
+ print(f" - {v}")
135
+ return 2
136
+
137
+
138
+ def cmd_prove(args: argparse.Namespace) -> int:
139
+ from proef.adapters.store.sqlite import SqliteProvenanceStore
140
+
141
+ store = SqliteProvenanceStore(args.db)
142
+ records = store.branch_records(args.branch)
143
+ if not records:
144
+ print(f"no records for branch '{args.branch}' in {args.db}")
145
+ return 1
146
+ # hashes are RECOMPUTED from every payload, not copied from the chain
147
+ problems = store.verify_chain(args.branch)
148
+ bad = {p["record_id"]: p for p in problems}
149
+ prev_ok = True
150
+ prev_hash = None
151
+ for r in records:
152
+ ok = (r.prev_record_hash == prev_hash) and r.record_id not in bad
153
+ prev_ok &= ok
154
+ prev_hash = r.record_hash
155
+ print(f"{r.envelope.created_at:>14.0f} {r.event_type.value:<18} "
156
+ f"hash={r.record_hash[:12]}… prev={'genesis' if not r.prev_record_hash else r.prev_record_hash[:12] + '…'} "
157
+ f"[{'ok' if ok else 'BROKEN'}]")
158
+ for p in problems:
159
+ print(f"TAMPERED {p['record_id']} ({p['event']}): {p['problem']}"
160
+ + (f", {p['detail']}" if p.get("detail") else ""))
161
+ print(f"chain intact: {prev_ok and not problems} "
162
+ f"({len(records)} records, hashes recomputed from payload)")
163
+ if not prev_ok or problems:
164
+ print(" note: a consistent rewrite of payload+column+links is only "
165
+ "caught by an EXTERNAL anchor, run `proef anchor --verify`")
166
+ return 1
167
+ if args.html:
168
+ from proef.report import write_report
169
+
170
+ path = write_report(records, args.html)
171
+ print(f"report: {path}")
172
+ if getattr(args, "eln", None):
173
+ from proef.eln import export_eln
174
+
175
+ p = export_eln(records, args.eln,
176
+ args.eln + ".json" if getattr(args, "eln_json", True)
177
+ else None)
178
+ print(f"ELN export: {p} (+ .json sidecar)")
179
+ return 0
180
+
181
+
182
+ def cmd_mcp(args: argparse.Namespace) -> int:
183
+ from proef.mcp_server import serve
184
+
185
+ serve()
186
+ return 0
187
+
188
+
189
+ def cmd_new_adapter(args: argparse.Namespace) -> int:
190
+ from proef.scaffold import main as scaffold_main
191
+
192
+ return scaffold_main([args.kind, args.name, "--dir", args.dir]
193
+ + (["--cap", args.cap] if args.cap else []))
194
+
195
+
196
+ def cmd_skills(args: argparse.Namespace) -> int:
197
+ from proef.skills import discover_skills, install_skills, recommend_for_role
198
+
199
+ if args.command == "list":
200
+ found = discover_skills()
201
+ if not found:
202
+ print("no skills discovered")
203
+ return 0
204
+ for name, info in sorted(found.items()):
205
+ desc = (info["description"] or "-")[:80]
206
+ print(f"{name:28} v{info['version'] or '-':<6} [{info['source']}] {desc}")
207
+ return 0
208
+ if args.command == "role":
209
+ recs = recommend_for_role(args.role, auto_install=args.install)
210
+ print(f"role '{args.role}': {len(recs)} skill(s) available")
211
+ for r in recs:
212
+ print(f" {r['path']} v{r['version'] or '-'}")
213
+ return 0
214
+ if args.command == "install":
215
+ installed = install_skills(args.names, args.dest)
216
+ for pth in installed:
217
+ print(f"installed: {pth}")
218
+ return 0
219
+ return 2
220
+
221
+
222
+ def cmd_read(args: argparse.Namespace) -> int:
223
+ from pathlib import Path
224
+
225
+ from proef.labread import read_plate
226
+
227
+ result = read_plate(args.path, max_response=args.max_response,
228
+ layout=args.layout, cycles=args.cycles,
229
+ normalize=args.normalize)
230
+ print(result)
231
+ if args.csv:
232
+ print(f"csv: {result.to_csv(args.csv)}")
233
+ if args.html:
234
+ Path(args.html).write_text(
235
+ "<!DOCTYPE html><meta charset='utf-8'><title>Proef read</title>"
236
+ f"<h1>{result.source}</h1><pre>{result}</pre>")
237
+ print(f"report: {args.html}")
238
+ return 0
239
+
240
+
241
+ def cmd_demo(args: argparse.Namespace) -> int:
242
+ import json as _json
243
+
244
+ from proef.demo import EXPECTED, run_demo
245
+
246
+ print("Proef demo, a scripted campaign on the REAL machinery. "
247
+ "All numbers SIMULATED; the discipline is production.")
248
+ rep = run_demo(db_path=args.db, html_path=args.html, echo=not args.quiet)
249
+ print()
250
+ for line in rep["narration"]:
251
+ print(" * " + line)
252
+ ok = rep["verdicts"] == EXPECTED
253
+ print(f"\nverdicts: {rep['verdicts']} "
254
+ f"({'the two moments landed' if ok else 'UNEXPECTED, demo drift?'})")
255
+ print(f"provenance: {rep['records']} hash-chained records on "
256
+ f"'{rep['branch']}' in {rep['db']} · chain verified: "
257
+ f"{'OK' if rep['chain_ok'] else 'PROBLEMS'}")
258
+ if args.html:
259
+ print(f"diary: {args.html}")
260
+ print("next: proef read <your-plate.csv>, the same verdict machinery runs "
261
+ "on YOUR data (try tests/data/instruments/ exports)")
262
+ if args.json:
263
+ print(_json.dumps({k: v for k, v in rep.items() if k != "lines"},
264
+ indent=1, default=str))
265
+ return 0 if ok and rep["chain_ok"] else 1
266
+
267
+
268
+ def cmd_why(args: argparse.Namespace) -> int:
269
+ """Attribution panel: fit a policy on a labeled CSV (smiles,value cols),
270
+ then per prediction: top driving n-grams / importance-weighted bits,
271
+ the stated caveats, and the applicability-domain stamp."""
272
+ import csv as _csv
273
+ import json as _json
274
+ from pathlib import Path as _P
275
+
276
+ from proef import interpret
277
+
278
+ rows = list(_csv.DictReader(_P(args.data).open(newline="",
279
+ encoding="utf-8-sig")))
280
+ if not rows:
281
+ print("empty training csv", file=sys.stderr)
282
+ return 2
283
+ lower = {c.lower().strip(): c for c in rows[0] if c}
284
+ sc = next((lower[k] for k in ("smiles", "cml", "structure") if k in lower),
285
+ None)
286
+ vc = next((lower[k] for k in ("value", "y", "label", "activity",
287
+ "pchembl", "ic50_um") if k in lower), None)
288
+ if not sc or not vc:
289
+ print(f"need smiles+value columns, have: {sorted(lower)}",
290
+ file=sys.stderr)
291
+ return 2
292
+ data = []
293
+ for r in rows:
294
+ try:
295
+ data.append((r[sc], float(r[vc])))
296
+ except (TypeError, ValueError, KeyError):
297
+ continue
298
+ if args.policy == "char-ridge":
299
+ from proef.benchmark import CharRidgePolicy
300
+ pol = CharRidgePolicy()
301
+ else:
302
+ from proef.adapters.models.sklearn_policy import \
303
+ MorganFingerprintRF
304
+ pol = MorganFingerprintRF(seed=0)
305
+ pol.fit(data)
306
+ out = []
307
+ for smi in args.smiles:
308
+ exp = interpret.explain_prediction(pol, smi)
309
+ try:
310
+ exp["ad"] = pol.ad.check(smi)
311
+ except AttributeError:
312
+ pass
313
+ out.append(exp)
314
+ if args.json:
315
+ continue
316
+ print(f"\n{smi}")
317
+ print(f" {exp['policy']}: prediction={exp.get('prediction')} "
318
+ f"[{exp['method']}]")
319
+ ad = exp.get("ad")
320
+ if ad:
321
+ print(" applicability domain: " + (
322
+ f"in-domain (nn Tanimoto {ad['nn_tanimoto']})"
323
+ if not ad["extrapolation"] else
324
+ f"EXTRAPOLATION (nn {ad['nn_tanimoto']} < {ad['ad_floor']}, "
325
+ f"{ad['ad_basis']} basis), claim-grade use vetoed"))
326
+ for key, sign in (("top_positive", "+"), ("top_negative", "−")):
327
+ for g, w in exp.get(key, []):
328
+ print(f" {sign} {g}: {w:+.3f}")
329
+ for b, w in exp.get("top_bits", []):
330
+ print(f" · bit {b}: importance {w:.4f} "
331
+ f"(active={exp.get('n_active_bits')} bits)")
332
+ if exp.get("caveat"):
333
+ print(f" caveat: {exp['caveat']}")
334
+ if args.json:
335
+ print(_json.dumps(out, indent=1))
336
+ return 0
337
+
338
+
339
+ def cmd_ingest(args: argparse.Namespace) -> int:
340
+ from proef.flywheel import Flywheel
341
+ from proef.ingest import ingest_eln
342
+
343
+ fw = Flywheel(args.flywheel_db)
344
+ store = None
345
+ if not args.no_chain:
346
+ from proef.adapters.store.sqlite import SqliteProvenanceStore
347
+ store = SqliteProvenanceStore(args.db)
348
+ rep = ingest_eln(args.path, flywheel=fw, store=store,
349
+ problem_id=args.problem_id, dry_run=args.dry_run)
350
+ print(f"ingest: {rep['rows']} rows read · {rep['ingested']} outcomes "
351
+ f"imported · {len(rep['skipped'])} note(s)/skip(s) · "
352
+ f"sha256 {rep['sha256'][:12]}")
353
+ if rep["checksum_match"] is False:
354
+ print(" !! EDITED AFTER EXPORT, .sha256 seal mismatch; values "
355
+ "imported UNSEALED, verify against the ELN system of record")
356
+ elif rep["checksum_match"] is True:
357
+ print(" seal verified (.sha256 sidecar matches the CSV)")
358
+ for sk in rep["skipped"]:
359
+ print(f" row {sk['row']}: {sk['reason']}")
360
+ if rep["provenance_written"]:
361
+ print(f" provenance: {rep['provenance_written']} records on branch "
362
+ f"external/{args.path.split('/')[-1].removesuffix('.csv')}")
363
+ if args.dry_run:
364
+ print(" (dry-run: nothing written)")
365
+ return 0
366
+
367
+
368
+ def cmd_watch(args: argparse.Namespace) -> int:
369
+ from proef.watch import watch
370
+
371
+ watch(inbox=args.inbox, poll_secs=args.poll)
372
+ return 0
373
+
374
+
375
+ def _campaign_from_doc(cfg_doc: dict) -> "CampaignConfig":
376
+ from proef.autoloop import CampaignConfig, ResourceBudget
377
+ from proef.core.hypothesis import Constraint, ProblemStatement
378
+
379
+ problem = ProblemStatement(
380
+ objective=cfg_doc["problem"]["objective"],
381
+ context=cfg_doc["problem"].get("context", ""),
382
+ constraints=[Constraint(**c) for c in cfg_doc["problem"].get("constraints", [])],
383
+ success_metric=cfg_doc["problem"].get("success_metric"))
384
+ k_cfg = cfg_doc.get("k", 2)
385
+ k_schedule = tuple(k_cfg) if isinstance(k_cfg, (list, tuple)) else ()
386
+ return CampaignConfig(
387
+ problem=problem, hypotheses=cfg_doc.get("hypotheses") or None,
388
+ hypothesis_source=cfg_doc.get("hypothesis_source", "config"),
389
+ model=cfg_doc.get("_model"), critic_model=cfg_doc.get("_critic"),
390
+ k=(k_cfg[0] if isinstance(k_cfg, (list, tuple)) else k_cfg),
391
+ k_schedule=k_schedule,
392
+ labs=cfg_doc.get('labs') or (None if cfg_doc.get('lab')
393
+ else [{'instrument': 'proef-virtual-lab'}]),
394
+ lab_requirement=cfg_doc.get('lab_requirement'),
395
+ autonomy=cfg_doc.get("autonomy", "act"),
396
+ rounds=cfg_doc.get("rounds", 1),
397
+ inbox=cfg_doc.get("inbox", ".data/inbox"),
398
+ concentrations=tuple(cfg_doc.get("concentrations",
399
+ ["0.5uM", "2uM", "10uM", "40uM"])),
400
+ budget=(ResourceBudget(**cfg_doc["budget"]) if cfg_doc.get("budget") else None),
401
+ replan=bool(cfg_doc.get("replan", False)),
402
+ followups=bool(cfg_doc.get("followups", False)),
403
+ orchestrator=("model" if cfg_doc.get("orchestrator") == "model" else "fixed"),
404
+ modality=(cfg_doc.get("modality") or None),
405
+ prediction_tools=(list(cfg_doc["prediction_tools"]) if cfg_doc.get("prediction_tools") else None),
406
+ max_families=cfg_doc.get("max_families", 3),
407
+ max_variants_per_family=cfg_doc.get("max_variants_per_family", 3),
408
+ dose_design=cfg_doc.get("dose_design", "fixed"),
409
+ acquisition=cfg_doc.get("acquisition", ""),
410
+ seed=cfg_doc.get("seed"))
411
+
412
+
413
+ def _campaign_doc_from_args(args) -> dict | None:
414
+ """Load a campaign config from --template or a config path (shared by
415
+ `proef campaign auto` and `proef campaign select` so the two never drift on how a campaign is
416
+ specified). Returns None if neither source was given."""
417
+ if getattr(args, "template", None):
418
+ from proef.templates import build_campaign, fill, load_template
419
+ fields = dict(f.split("=", 1) for f in (args.field or []))
420
+ return build_campaign(fill(load_template(args.template), fields,
421
+ prompt_missing=not getattr(args, "yes",
422
+ False)))
423
+ if getattr(args, "config", None):
424
+ raw = Path(args.config).read_text()
425
+ try:
426
+ import yaml
427
+ return yaml.safe_load(raw)
428
+ except ImportError:
429
+ return json.loads(raw)
430
+ return None
431
+
432
+
433
+ def cmd_select(args) -> int:
434
+ """Preview the EI batch WITHOUT submitting anything: the same observe
435
+ path a real campaign runs through, so 'what would run' is the real
436
+ policy answer, every pick with its acquisition arithmetic, every
437
+ refusal with the named gate. `--acquisition bo-ei` (default) is the
438
+ policy under review."""
439
+ from proef.adapters.lab.simulator import SimulatorLab
440
+ from proef.adapters.store.sqlite import SqliteProvenanceStore
441
+ from proef.autoloop import run_campaign
442
+
443
+ cfg_doc = _campaign_doc_from_args(args)
444
+ if cfg_doc is None:
445
+ print("proef campaign select: pass a config file or --template NAME",
446
+ file=sys.stderr)
447
+ return 2
448
+ cfg_doc["acquisition"] = args.acquisition or "bo-ei"
449
+ cfg_doc["autonomy"] = "observe" # selects + explains, submits zero
450
+ if getattr(args, "seed", None) is not None:
451
+ cfg_doc["seed"] = args.seed
452
+ cfg = _campaign_from_doc(cfg_doc)
453
+ store = SqliteProvenanceStore() # in-memory: preview leaves no state
454
+ # silence the campaign's own narration: select is a clean preview, the
455
+ # policy's picks/refusals are printed below from the sealed record
456
+ run_campaign(cfg, SimulatorLab(seed=args.seed if args.seed is not None else 42),
457
+ store, notify=lambda *a: None)
458
+ branch = f"problem/{cfg.problem.problem_id or 'auto'}"
459
+ sel = next(((r.decision or {}) for r in store.branch_records(branch)
460
+ if (r.decision or {}).get("kind") == "acquisition_selection"),
461
+ None)
462
+ if not sel:
463
+ print("select: no acquisition_selection produced (empty portfolio or "
464
+ "the policy is off?)", file=sys.stderr)
465
+ return 1
466
+ print(f"acquisition[{sel['policy']} v{sel.get('policy_version')}] "
467
+ f"· k={sel.get('k')} · target={sel.get('target')} "
468
+ f"{sel.get('direction','')} · seed={sel.get('seed')}")
469
+ print("\nPicks (this is the batch that WOULD run):")
470
+ for p in sel.get("picks") or []:
471
+ print(f" + {p['candidate']:10s} EI={p['acquisition']:<9} {p['reason']}")
472
+ refusals = sel.get("refusals") or []
473
+ if refusals:
474
+ print(f"\nRefused ({len(refusals)}), why they did NOT make the plate:")
475
+ for x in refusals:
476
+ print(f" - {x['candidate']:10s} {x['reason']}")
477
+ if sel.get("note"):
478
+ print(f"\n note: {sel['note']}")
479
+ print("\n(nothing was submitted; a real campaign applies the safety, "
480
+ "budget and approval gates on top of this batch)")
481
+ return 0
482
+
483
+
484
+ def cmd_auto(args: argparse.Namespace) -> int:
485
+ import json # noqa: F401 (used below for report serialization)
486
+ from proef.autoloop import run_campaign
487
+ from proef.adapters.lab.simulator import SimulatorLab
488
+ from proef.adapters.store.sqlite import SqliteProvenanceStore
489
+
490
+ cfg_doc = _campaign_doc_from_args(args)
491
+ if cfg_doc is None:
492
+ print("proef campaign auto: pass a config file or --template NAME", file=sys.stderr)
493
+ return 2
494
+ if args.autonomy:
495
+ cfg_doc["autonomy"] = args.autonomy
496
+ if cfg_doc.get("hypothesis_source") == "agent" and not cfg_doc.get("model"):
497
+ try:
498
+ from proef.adapters.models.from_env import model_from_env
499
+ cfg_doc["_model"] = model_from_env()
500
+ from proef.adapters.models.from_env import model_status
501
+ if model_status("critic")["configured"]:
502
+ cfg_doc["_critic"] = model_from_env("critic") # the critic is the main model unless PROEF_LLM_CRITIC_* says otherwise
503
+ except Exception as exc:
504
+ print(f"agent hypothesis source needs a model: {exc}",
505
+ file=sys.stderr)
506
+ return 2
507
+ if getattr(args, "dose_design", None):
508
+ cfg_doc["dose_design"] = args.dose_design
509
+ if getattr(args, "acquisition", None):
510
+ cfg_doc["acquisition"] = args.acquisition
511
+ if getattr(args, "seed", None) is not None:
512
+ cfg_doc["seed"] = args.seed
513
+ if getattr(args, "dry_run", False):
514
+ cfg_doc["acquisition"] = cfg_doc.get("acquisition") or "bo-ei"
515
+ cfg_doc["autonomy"] = "observe" # selects + explains, submits nothing
516
+ cfg = _campaign_from_doc(cfg_doc)
517
+ approver = None
518
+ if cfg.autonomy == "gate":
519
+ from proef.approvals import web_approver
520
+ approver = web_approver(inbox=args.inbox or str(APPROVALS_FILE),
521
+ notify=lambda m: print(f"[campaign] {m}"))
522
+ if cfg.hypothesis_source == "agent": # a model's plan is reviewed before anything is submitted
523
+ from proef.plan import web_plan_approver
524
+ cfg.plan_approver = web_plan_approver(args.inbox or str(APPROVALS_FILE),
525
+ notify=lambda m: print(f"[campaign] {m}"))
526
+ if cfg_doc.get("lab") and "adapter" in (cfg_doc.get("lab") or {}):
527
+ lab = _load_adapter(cfg_doc["lab"]["adapter"],
528
+ cfg_doc["lab"].get("options", {}))
529
+ else:
530
+ lab = SimulatorLab(seed=cfg_doc.get("seed", 42))
531
+
532
+ import time as _time
533
+ def _ts_notify(msg: str) -> None:
534
+ print(f"[{_time.strftime('%H:%M:%S')}] {msg}", flush=True)
535
+ store = SqliteProvenanceStore(args.db)
536
+ sbx_cfg = cfg_doc.get("sandbox") or {}
537
+ session = None
538
+ if sbx_cfg.get("mode", "off") != "off":
539
+ from proef.sandbox_session import SandboxSession
540
+ from proef.core.interfaces import system_actor as _sa
541
+ branch = f"problem/{cfg.problem.problem_id or 'auto'}"
542
+ session = SandboxSession(
543
+ mode=sbx_cfg["mode"], sandbox=sbx_cfg.get("type", "local"),
544
+ branch_id=branch, store=store, actor=_sa("sandbox-lifecycle"),
545
+ image=sbx_cfg.get("image"))
546
+ _ts_notify(f"sandbox: {sbx_cfg['mode']} ({sbx_cfg.get('type', 'local')}) "
547
+ f"branch={branch}, lifecycle provenance-sealed; lab ops "
548
+ f"route in-sandbox inside run_campaign; registry()/tool "
549
+ f"calls route when routed through this session")
550
+ try:
551
+ report = run_campaign(cfg, lab, store,
552
+ approver=approver, notify=_ts_notify,
553
+ sandbox=session)
554
+ finally:
555
+ if session:
556
+ session.destroy()
557
+ print(json.dumps({"problem": report.problem_id, "selected": report.selected,
558
+ "verdicts": report.verdicts}, indent=1))
559
+ return 0
560
+
561
+
562
+ def cmd_sandboxd(args: argparse.Namespace) -> int:
563
+ """In-sandbox tool worker (internal): reads a ToolInvocation request,
564
+ executes inside this process, writes a ToolResult. See sandboxd.py."""
565
+ from proef.sandboxd import main as _dmain
566
+ return _dmain(sys.argv[2:])
567
+
568
+
569
+ def cmd_eval(args: argparse.Namespace) -> int:
570
+ import time as _t
571
+ from proef.evals import tasks as _tasks # registers suite
572
+ from proef.evals.harness import TASKS, PASS_THRESHOLD
573
+
574
+ suites = None
575
+ if getattr(args, "all", False) or args.task:
576
+ suites = None
577
+ elif getattr(args, "suite", None):
578
+ suites = {s.strip() for s in args.suite.split(",")}
579
+ else:
580
+ suites = {"epistemics"}
581
+ results = []
582
+ for task in TASKS:
583
+ if args.task and args.task != task.task_id:
584
+ continue
585
+ if suites and task.suite not in suites:
586
+ continue
587
+ t0 = _t.time()
588
+ try:
589
+ r = task.run()
590
+ except Exception as exc:
591
+ from proef.evals.harness import TaskResult
592
+ r = TaskResult(task.task_id, task.description, 0.0, False,
593
+ notes=f"ERROR: {exc}")
594
+ r.metrics["duration_s"] = round(_t.time() - t0, 1)
595
+ results.append(r)
596
+ skipped = r.notes.startswith("SKIPPED")
597
+ mark = "⏭ " if skipped else ("✅" if r.passed else "❌")
598
+ print(f"{mark} {r.task_id:24s} "
599
+ f"{', ' if skipped else f'score={r.score:.3f}'} "
600
+ f"({r.metrics.get('duration_s')}s) {r.notes}")
601
+
602
+ if not results:
603
+ print("no tasks matched", file=sys.stderr)
604
+ return 2
605
+ scored = [r for r in results if not r.notes.startswith("SKIPPED")]
606
+ overall = sum(r.score for r in scored) / len(scored) if scored else 0.0
607
+ all_pass = all(r.passed for r in scored)
608
+ print(f"\n{'PASS' if all_pass else 'FAIL'}, {len(results)} tasks, "
609
+ f"mean score {overall:.3f} (pass bar {PASS_THRESHOLD})")
610
+
611
+ if args.task or (getattr(args, "suite", None) and not args.all):
612
+ # debug run (single task or custom suite): never clobber the
613
+ # committed epistemics artifacts — report and exit
614
+ return 0 if all_pass else 1
615
+ import json as _json
616
+ from pathlib import Path as _P
617
+ out = _P("evals/leaderboard.md")
618
+ out.parent.mkdir(exist_ok=True)
619
+ by_suite: dict[str, list] = {}
620
+ _suite_of = {t.task_id: t.suite for t in TASKS}
621
+ for r in results: # keyed by RESULT id, never positional zip —
622
+ # a mismatched task id must land in "other", not vanish silently
623
+ by_suite.setdefault(_suite_of.get(r.task_id, "other"), []).append(r)
624
+ sections = ""
625
+ for suite, rs in by_suite.items():
626
+ rows = "\n".join(
627
+ f"| {r.task_id} | {r.score:.3f} | "
628
+ f"{'⏭' if r.notes.startswith('SKIPPED') else ('✅' if r.passed else '❌')} | "
629
+ f"{r.metrics.get('duration_s', ', ')}s | {r.notes} |" for r in rs)
630
+ sections += (f"\n### {suite}, mean "
631
+ f"{sum(x.score for x in rs) / len(rs):.3f}\n\n"
632
+ f"| task | score | pass | time | notes |\n"
633
+ f"|---|---|---|---|---|\n{rows}\n")
634
+ out.write_text(
635
+ f"# Proef eval leaderboard\n\n"
636
+ f"Run {_t.strftime('%Y-%m-%d %H:%M')} · mean **{overall:.3f}** · "
637
+ f"{'all pass' if all_pass else 'FAILING'}\n{sections}")
638
+ _P("evals/results.json").write_text(_json.dumps(
639
+ [{"task": r.task_id, "score": r.score, "passed": r.passed,
640
+ "metrics": r.metrics, "notes": r.notes} for r in results], indent=1))
641
+ return 0 if all_pass else 1
642
+
643
+
644
+ def cmd_anchor(args: argparse.Namespace) -> int:
645
+ from proef.anchor import anchor as make_anchor, verify
646
+
647
+ if args.verify:
648
+ res = verify(args.db, args.root)
649
+ ok = res["match"]
650
+ print(f"current root: {res['current_root'][:16]}… "
651
+ f"anchored: {(res['anchored_root'] or ', ')[:16]}… "
652
+ f"records: {res['records']} -> {'MATCH' if ok else 'MISMATCH'}")
653
+ if res.get("content_tampered"):
654
+ print(" ⚠ CONTENT TAMPERED: stored hashes do not match what the "
655
+ "payloads actually contain")
656
+ for p in (res.get("problems") or [])[:5]:
657
+ print(f" {p['record_id']} [{p['branch']}]: {p['problem']}")
658
+ return 0 if ok and not res.get("content_tampered") else 1
659
+ entry = make_anchor(args.db, publish_cmd=args.publish_cmd)
660
+ print(f"anchored {entry['records']} records -> root "
661
+ f"{entry['merkle_root'][:16]}…")
662
+ if "published" in entry:
663
+ print("published" if entry["published"]
664
+ else f"publish FAILED: {entry.get('publish_error', '')}")
665
+ return 0
666
+
667
+
668
+ def cmd_fixtures(args: argparse.Namespace) -> int:
669
+ from proef import fixtures
670
+ study = args.study
671
+ if args.command == "verify":
672
+ ok, problems = fixtures.verify(study)
673
+ for p in problems:
674
+ print(p)
675
+ print(f"{study}: {'all fixtures intact' if ok else 'DRIFT DETECTED'}")
676
+ return 0 if ok else 1
677
+ if args.command == "materialize":
678
+ n = fixtures.materialize(study)
679
+ print(f"restored {n} cache file(s)")
680
+ return 0
681
+ print("freeze is dev-only; use proef.fixtures.freeze(study, sources)",
682
+ file=sys.stderr)
683
+ return 2
684
+
685
+
686
+ def cmd_sweep(args: argparse.Namespace) -> int:
687
+ from proef.adapters.lab.simulator import SimulatorLab
688
+ from proef.adapters.store.sqlite import SqliteProvenanceStore
689
+ from proef.core.hypothesis import ProblemStatement
690
+ from proef.sweep import run_sweep
691
+ cands = [c.strip() for c in args.candidates.split(",") if c.strip()]
692
+ from pathlib import Path as _P
693
+ _dbp = _P(args.db)
694
+ _dbp.parent.mkdir(parents=True, exist_ok=True)
695
+ problem = ProblemStatement(objective=args.objective)
696
+ res = run_sweep(problem, cands, lambda: SimulatorLab(seed=args.seed),
697
+ SqliteProvenanceStore(args.db), fan=args.fan,
698
+ k_per_shard=args.k, threshold=args.gate,
699
+ unit=args.unit, metric=args.metric, seed=args.seed,
700
+ rounds=args.rounds, notify=print)
701
+ import json as _json
702
+ print(_json.dumps({"best": res["best"], "tally": res["tally"]}, indent=1))
703
+ return 0
704
+
705
+
706
+ def cmd_taste(args: argparse.Namespace) -> int:
707
+ from proef.taste import render_taste, taste_report
708
+ print(render_taste(taste_report(args.db)))
709
+ return 0
710
+
711
+
712
+ def cmd_reproduce(args: argparse.Namespace) -> int:
713
+ from proef.reproduce import reproduce
714
+ res = reproduce(args.branch, db_path=args.db)
715
+ status = res["status"]
716
+ icon = {"match": "✅", "differs": "⚠️", "not-reproducible": "⏭",
717
+ "error": "❌"}.get(status, "•")
718
+ print(f"{icon} {status}", end="")
719
+ if status in ("match", "differs"):
720
+ print(f", {res['matched']}/{res['recorded_verdicts']} verdicts "
721
+ f"identical on the REPLAYED execution path")
722
+ print(f" {res.get('note', '')}")
723
+ for d in res["diffs"]:
724
+ print(f" Δ {d['candidate']}: recorded={d['recorded']} "
725
+ f"replayed={d['replayed']}")
726
+ print(f" env: {res['environment'].get('lab')} "
727
+ f"seed={res['environment'].get('lab_seed')} "
728
+ f"conc={res['environment'].get('concentrations')}")
729
+ else:
730
+ print(f", {res.get('reason', '')}")
731
+ return 0 if status == "match" else 1
732
+
733
+
734
+ def cmd_plan(args: argparse.Namespace) -> int:
735
+ from proef.problem_tree import (ProblemTree, TreeLimits,
736
+ decompose_with_agent, run_tree)
737
+
738
+ limits = TreeLimits(max_children=args.max_children,
739
+ max_depth=args.max_depth, max_nodes=args.max_nodes)
740
+ rounds = max(1, args.rounds)
741
+ model = None
742
+ if args.model == "anthropic":
743
+ from proef.adapters.models.anthropic_provider import \
744
+ AnthropicProvider
745
+ model = AnthropicProvider()
746
+ tree = decompose_with_agent(model, args.objective,
747
+ context=args.context or "",
748
+ limits=limits, say=print)
749
+ else:
750
+ tree = ProblemTree.create(args.objective, limits=limits,
751
+ metric=None, gate=None, modality=args.modality)
752
+ tree.run_budget = args.run_budget
753
+ print(tree.render())
754
+ print("run allocation:", tree.allocation())
755
+ if not args.run:
756
+ print("(dry plan, add --run to execute the leaves)")
757
+ return 0
758
+ from proef.adapters.lab.simulator import SimulatorLab
759
+ from proef.adapters.store.sqlite import SqliteProvenanceStore
760
+ cands = [{"sample_id": x.strip()} for x in args.candidates.split(",")
761
+ if x.strip()]
762
+ if not cands and model is None:
763
+ print("--run needs --candidates (or --model, for agent-proposed "
764
+ "hypotheses)")
765
+ return 2
766
+ import json as _j
767
+ _labs = _j.loads(args.labs_json) if getattr(args, "labs_json", None) else None
768
+ summary = run_tree(tree, lambda: SimulatorLab(seed=args.seed),
769
+ SqliteProvenanceStore(args.db), candidates=cands,
770
+ model=model, autonomy=args.autonomy,
771
+ rounds=rounds, notify=print, labs=_labs)
772
+ print("root status:", summary[tree.root.id])
773
+ return 0
774
+
775
+
776
+ def cmd_materials_run(args: argparse.Namespace) -> int:
777
+ from proef.materials import run_materials_sweep
778
+ from proef.adapters.store.sqlite import SqliteProvenanceStore
779
+ import json as _json
780
+ forms = [float(x) for x in args.formulations.split(",") if x.strip()]
781
+ rep = run_materials_sweep(
782
+ args.objective, forms, gate=args.gate, unit=args.unit,
783
+ metric=args.metric, param=args.param, direction=args.direction,
784
+ store=SqliteProvenanceStore(args.db),
785
+ notify=print)
786
+ from proef import program as _prog
787
+ _doc = _prog.load()
788
+ if _doc.get("program"):
789
+ try:
790
+ _prog.attach_experiment(_doc["program"],
791
+ f"materials-{rep['problem_id']}",
792
+ rep["problem_id"], args.objective,
793
+ status="verdict_recorded" if
794
+ rep["verdict"] == "validated" else
795
+ "failed")
796
+ except Exception:
797
+ pass
798
+ print(_json.dumps({"problem": rep["problem_id"],
799
+ "verdict": rep["verdict"],
800
+ "best": rep["best"]}, indent=1))
801
+ return 0
802
+
803
+
804
+ def cmd_modalities(args: argparse.Namespace) -> int:
805
+ from proef.modality import PACKS
806
+ for name, pack in PACKS.items():
807
+ print(f"{name}")
808
+ print(f" make: {pack.production_action}")
809
+ print(f" test: {', '.join(pack.test_assays)}")
810
+ print(f" gate: {', '.join(pack.safety_rule_names)}")
811
+ if pack.notes:
812
+ print(f" note: {pack.notes}")
813
+ return 0
814
+
815
+
816
+ def cmd_halt(args: argparse.Namespace) -> int:
817
+ from proef.governance import HaltSwitch
818
+ hs = HaltSwitch(path=args.path)
819
+ if args.clear:
820
+ print("halt cleared" if hs.clear() else "no halt was engaged")
821
+ return 0
822
+ if args.engage:
823
+ entry = hs.engage(args.reason)
824
+ print(f"HALT ENGAGED ({entry['id']}): {entry['reason']}")
825
+ print("all submissions refused until `proef halt --clear` by an operator")
826
+ return 0
827
+ state = hs.engaged()
828
+ print(f"HALTED: {state}" if state else "not halted")
829
+ return 1 if state else 0
830
+
831
+
832
+ def cmd_sop(args: argparse.Namespace) -> int:
833
+ from proef.governance import SopRegistry
834
+ reg = SopRegistry()
835
+ if args.command == "list":
836
+ pend = reg.pending()
837
+ for p in pend:
838
+ print(f"pending {p['id']}: {p['objective'][:50]} "
839
+ f"(assay {p['assay']})")
840
+ if not pend:
841
+ print("no SOPs awaiting sign-off")
842
+ return 0
843
+ if args.command == "approve":
844
+ ok = reg.approve(args.sop_id, by=args.by)
845
+ print(f"approved {args.sop_id}, recurring runs of this procedure "
846
+ "are now authorized" if ok else f"unknown SOP {args.sop_id}")
847
+ return 0 if ok else 1
848
+ return 2
849
+
850
+
851
+ def cmd_templates(args: argparse.Namespace) -> int:
852
+ from proef.templates import list_templates, load_template
853
+
854
+ if args.name:
855
+ doc = load_template(args.name)
856
+ print(json.dumps(doc, indent=2) if False else json.dumps(doc, indent=2))
857
+ return 0
858
+ for t in list_templates():
859
+ print(f"{t['name']:26} {t['description']}")
860
+ return 0
861
+
862
+
863
+ def cmd_connect(args: argparse.Namespace) -> int:
864
+ from proef.connect import format_scan, probe_robot, scan_share
865
+
866
+ if args.command == "scan":
867
+ print(format_scan(scan_share(args.path)))
868
+ return 0
869
+ if args.command == "describe":
870
+ from proef.core.device_card import save_operator_tags, to_agent_text, \
871
+ builtin_card, load_card
872
+ print(f"Interview: what should an agent know to operate "
873
+ f"'{args.device}' safely? Enter notes one per line; "
874
+ f"empty line finishes.")
875
+ notes = []
876
+ prompts = [
877
+ "What does it measure / adjust?",
878
+ "Any physical quirks not in the manual?",
879
+ "Safety limits an agent must respect?",
880
+ "Anything else (free notes)?",
881
+ ]
882
+ for p in prompts:
883
+ line = input(f" {p} > ").strip()
884
+ if line:
885
+ notes.append(line)
886
+ base = builtin_card(args.device, args.device, {}) if args.builtin else None
887
+ card = save_operator_tags(args.device, notes, base=base)
888
+ card = load_card(args.device, base=card) or card
889
+ print("\nReference file:\n")
890
+ print(to_agent_text(card))
891
+ return 0
892
+ if args.command == "card":
893
+ from proef.core.device_card import load_card, to_agent_text, \
894
+ builtin_card
895
+ base = builtin_card(args.device, args.device, {}) if args.builtin else None
896
+ card = load_card(args.device, base=base)
897
+ if not card:
898
+ print(f"no card for '{args.device}', run "
899
+ f"`proef connect describe {args.device}` first")
900
+ return 1
901
+ print(to_agent_text(card))
902
+ return 0
903
+ if args.command == "robot":
904
+ info = probe_robot(args.ip)
905
+ if info.get("reachable"):
906
+ print(f"robot found: {info['name']} (API {info['api_version']})")
907
+ print(f" setup: {info['usage']}")
908
+ else:
909
+ print(f"no robot at {info['base_url']}: {info.get('error')}")
910
+ return 0 if info.get("reachable") else 1
911
+ return 2
912
+
913
+
914
+ def cmd_diary(args: argparse.Namespace) -> int:
915
+ from proef.adapters.store.sqlite import SqliteProvenanceStore
916
+ from proef.diary import write_diary
917
+
918
+ store = SqliteProvenanceStore(args.db)
919
+ records = store.branch_records(args.branch)
920
+ if not records:
921
+ print(f"no records for branch '{args.branch}' in {args.db}")
922
+ return 1
923
+ path = write_diary(records, args.branch, args.html)
924
+ print(f"diary: {path}")
925
+ return 0
926
+
927
+
928
+ def _register_core(sub):
929
+ """Campaign group + the read/ingest/connect family. Returns the
930
+ `proef campaign` subparsers so later groups can attach to it."""
931
+ camp = sub.add_parser(
932
+ "campaign", help="start or inspect a campaign (auto, plan, sweep, "
933
+ "run, materials, select, reproduce)")
934
+ csub = camp.add_subparsers(dest="campaign_cmd", required=True)
935
+
936
+ run = csub.add_parser("run", help="run a workflow YAML")
937
+ run.add_argument("workflow")
938
+ run.set_defaults(func=cmd_run)
939
+
940
+
941
+ prove = sub.add_parser("prove", help="print provenance chain for a branch")
942
+ prove.add_argument("branch")
943
+ prove.add_argument("--db", default="proef.db")
944
+ prove.add_argument("--html", metavar="PATH",
945
+ help="also write a self-contained HTML report")
946
+ prove.add_argument("--eln", help="export branch as ELN CSV (+ .json sidecar)")
947
+ prove.set_defaults(func=cmd_prove)
948
+
949
+ aud = sub.add_parser("audit", help="check a campaign branch against the checkpoint rules")
950
+ aud.add_argument("branch")
951
+ aud.add_argument("--db", default="proef.db")
952
+ aud.set_defaults(func=cmd_audit)
953
+
954
+ sbxd = sub.add_parser("sandboxd",
955
+ help=argparse.SUPPRESS) # internal worker
956
+ sbxd.set_defaults(func=cmd_sandboxd)
957
+
958
+ demo = sub.add_parser("demo",
959
+ help="guided first run: watch the system ABSTAIN on "
960
+ "a borderline result and REFUTE its own fake "
961
+ "hit (simulated numbers, real machinery)")
962
+ demo.add_argument("--db", default=None,
963
+ help="where to write the demo chain (default "
964
+ ".data/demo.db, overwritten)")
965
+ demo.add_argument("--html", default=None,
966
+ help="also render the campaign diary as HTML")
967
+ demo.add_argument("--quiet", action="store_true",
968
+ help="suppress the live campaign log")
969
+ demo.add_argument("--json", action="store_true")
970
+ demo.set_defaults(func=cmd_demo)
971
+
972
+ why = sub.add_parser(
973
+ "why", help="attribution panel: per-prediction drivers (n-grams / "
974
+ "importance-weighted bits) with caveats + applicability "
975
+ "domain, from a labeled CSV")
976
+ why.add_argument("policy", choices=["char-ridge", "morgan-rf"])
977
+ why.add_argument("data", help="training CSV with smiles + value columns")
978
+ why.add_argument("smiles", nargs="+")
979
+ why.add_argument("--json", action="store_true")
980
+ why.set_defaults(func=cmd_why)
981
+
982
+ ing = sub.add_parser("ingest",
983
+ help="import institutional memory: an ELN CSV "
984
+ "(inverse of prove --eln) into the flywheel "
985
+ "and provenance chain")
986
+ ing.add_argument("path")
987
+ ing.add_argument("--problem-id", default=None)
988
+ ing.add_argument("--db", default="proef.db", help="provenance store")
989
+ ing.add_argument("--flywheel-db", default=".data/flywheel.db")
990
+ ing.add_argument("--no-chain", action="store_true",
991
+ help="feed only the flywheel, write no provenance")
992
+ ing.add_argument("--dry-run", action="store_true")
993
+ ing.set_defaults(func=cmd_ingest)
994
+
995
+ mcp = sub.add_parser("mcp", help="serve Proef tools over MCP (stdio)")
996
+ mcp.set_defaults(func=cmd_mcp)
997
+
998
+ new_adapter = sub.add_parser("new-adapter", help="scaffold a tested adapter")
999
+ new_adapter.add_argument("kind", choices=["lab", "tool"])
1000
+ new_adapter.add_argument("name")
1001
+ new_adapter.add_argument("--dir", default="adapters-contrib")
1002
+ new_adapter.add_argument("--cap", default=None)
1003
+ new_adapter.set_defaults(func=cmd_new_adapter)
1004
+
1005
+ read = sub.add_parser("read", help="auto-read an instrument/lab result file")
1006
+ read.add_argument("path")
1007
+ read.add_argument("--max-response", type=float, default=None,
1008
+ help="known maximal assay response (enables IC50 vs fixed max)")
1009
+ read.add_argument("--layout", default=None,
1010
+ help="plate-layout CSV (well -> sample/conc) to join onto "
1011
+ "grid/kinetic exports that carry no compound identity")
1012
+ read.add_argument("--cycles", default="last", choices=["last", "first", "mean"],
1013
+ help="kinetic reduction per well (default: last = endpoint)")
1014
+ read.add_argument("--normalize", default=None, choices=["pct_inhibition"],
1015
+ help="rescale non-control wells to %% inhibition against the "
1016
+ "plate's own blank + full-inhibition controls")
1017
+ read.add_argument("--html", default=None, help="write an HTML summary")
1018
+ read.add_argument("--csv", default=None, help="export standardized records to CSV")
1019
+ read.set_defaults(func=cmd_read)
1020
+
1021
+ conn = sub.add_parser("connect", help="find your instruments: scan a share or probe a robot")
1022
+ conns = conn.add_subparsers(dest="command", required=True)
1023
+ cscan = conns.add_parser("scan", help="detect instruments writing files into a folder")
1024
+ cscan.add_argument("path")
1025
+ crob = conns.add_parser("robot", help="probe an Opentrons robot (IP or URL)")
1026
+ crob.add_argument("ip")
1027
+ cdesc = conns.add_parser("describe",
1028
+ help="interview the operator; produce an agent reference file for a device")
1029
+ cdesc.add_argument("device")
1030
+ cdesc.add_argument("--builtin", action="store_true",
1031
+ help="seed with the built-in capability card")
1032
+ ccard = conns.add_parser("card", help="print the agent reference file for a device")
1033
+ ccard.add_argument("device")
1034
+ ccard.add_argument("--builtin", action="store_true")
1035
+ conn.set_defaults(func=cmd_connect)
1036
+
1037
+ diary = sub.add_parser("diary", help="render provenance as a lab-notebook narrative")
1038
+ diary.add_argument("branch")
1039
+ diary.add_argument("--db", default="proef.db")
1040
+ diary.add_argument("--html", default="diary.html")
1041
+ diary.set_defaults(func=cmd_diary)
1042
+ return csub
1043
+
1044
+
1045
+ def _register_flow(sub, csub) -> None:
1046
+ """watch, campaign auto/select."""
1047
+ watch_p = sub.add_parser("watch", help="watch an instrument outbox; agent notices results automatically")
1048
+ watch_p.add_argument("inbox")
1049
+ watch_p.add_argument("--poll", type=float, default=1.0)
1050
+ watch_p.set_defaults(func=cmd_watch)
1051
+
1052
+ auto = csub.add_parser("auto", help="start the whole campaign flow (config or --template)")
1053
+ auto.add_argument("--dose-design", choices=("fixed", "adaptive"),
1054
+ help="adaptive = Bayesian sequential dosing (3 wells/compound)")
1055
+ auto.add_argument("config", nargs="?", default=None)
1056
+ auto.add_argument("--template", default=None, help="preset template name (see: proef templates)")
1057
+ auto.add_argument("--field", action="append", metavar="KEY=VALUE",
1058
+ help="template field, e.g. --field compounds=C1,C2")
1059
+ auto.add_argument("--autonomy", choices=["observe", "gate", "act"], default=None)
1060
+ auto.add_argument("--acquisition", choices=("bo-ei",), default=None,
1061
+ help="batch policy: bo-ei = expected-improvement over "
1062
+ "declared posteriors, AD-gated (default: score/policy)")
1063
+ auto.add_argument("--seed", type=int, default=None,
1064
+ help="acquisition determinism seed")
1065
+ auto.add_argument("--dry-run", action="store_true",
1066
+ help="preview the batch (EI values + every refusal), "
1067
+ "submit nothing (forces bo-ei + observe)")
1068
+ auto.add_argument("--yes", action="store_true",
1069
+ help="never prompt for template fields; fail instead")
1070
+ auto.add_argument("--db", default="proef.db",
1071
+ help="provenance DB (shown in the workbench)")
1072
+ auto.add_argument("--inbox", default=None,
1073
+ help="approval inbox file for gate mode (default <data dir>/approvals.jsonl)")
1074
+ auto.set_defaults(func=cmd_auto)
1075
+
1076
+ sel = csub.add_parser(
1077
+ "select",
1078
+ help="preview the EI batch (picks + every refusal) without "
1079
+ "submitting anything, the what-would-run probe for "
1080
+ "acquisition policies")
1081
+ sel.add_argument("config", nargs="?", default=None)
1082
+ sel.add_argument("--template", default=None, help="preset template name")
1083
+ sel.add_argument("--field", action="append", metavar="KEY=VALUE",
1084
+ help="template field, e.g. --field compounds=C1,C2")
1085
+ sel.add_argument("--acquisition", choices=("bo-ei",), default="bo-ei",
1086
+ help="policy to preview (default: bo-ei)")
1087
+ sel.add_argument("--seed", type=int, default=None,
1088
+ help="acquisition determinism seed")
1089
+ sel.add_argument("--yes", action="store_true",
1090
+ help="never prompt for template fields; fail instead")
1091
+ sel.set_defaults(func=cmd_select)
1092
+
1093
+
1094
+ def _register_governance(sub, csub) -> None:
1095
+ """fixtures, anchor, halt, sop, campaign plan/materials."""
1096
+ fx = sub.add_parser("fixtures", help="case-study data fixtures: verify / materialize")
1097
+ fxsub = fx.add_subparsers(dest="command", required=True)
1098
+ for name in ("verify", "materialize"):
1099
+ sp = fxsub.add_parser(name)
1100
+ sp.add_argument("study")
1101
+ fx.set_defaults(func=cmd_fixtures)
1102
+ anc = sub.add_parser("anchor", help="Merkle-root the provenance store; "
1103
+ "publish the root for external tamper-evidence")
1104
+ anc.add_argument("--db", default="proef.db")
1105
+ anc.add_argument("--verify", action="store_true",
1106
+ help="recompute and compare against the latest anchor")
1107
+ anc.add_argument("--root", help="explicit root to verify against")
1108
+ anc.add_argument("--publish-cmd",
1109
+ help="command (split like a shell line, run WITHOUT a shell, "
1110
+ "no pipes/&&) receiving the anchor JSON on stdin, "
1111
+ "e.g. 'gh gist create -'. Wrap pipelines in a "
1112
+ "script. An anchor that is never published to "
1113
+ "somewhere you do not control gives no protection "
1114
+ "against someone who can edit the DB file.")
1115
+ anc.set_defaults(func=cmd_anchor)
1116
+ ht = sub.add_parser("halt", help="operator stop-condition outside the "
1117
+ "agent's reach: engage/status/clear")
1118
+ ht.add_argument("--engage", action="store_true")
1119
+ ht.add_argument("--clear", action="store_true")
1120
+ ht.add_argument("--reason", default="operator halt")
1121
+ ht.add_argument("--path", default=None,
1122
+ help="halt file path (default .data/HALT)")
1123
+ ht.set_defaults(func=cmd_halt)
1124
+ so = sub.add_parser("sop", help="sign off agent-proposed recurring "
1125
+ "procedures (SOPs) before they run unattended")
1126
+ sosub = so.add_subparsers(dest="command", required=True)
1127
+ sosub.add_parser("list")
1128
+ ap = sosub.add_parser("approve")
1129
+ ap.add_argument("sop_id")
1130
+ ap.add_argument("--by", default="operator")
1131
+ so.set_defaults(func=cmd_sop)
1132
+ pl = csub.add_parser("plan", help="decompose a compound objective into a "
1133
+ "guarded problem tree (dry plan, or --run the leaves)")
1134
+ pl.add_argument("--objective", required=True)
1135
+ pl.add_argument("--context", default="")
1136
+ pl.add_argument("--model", choices=("anthropic", "none"), default="none",
1137
+ help="anthropic = LLM-assisted decomposition (env-configured)")
1138
+ pl.add_argument("--max-children", type=int, default=4)
1139
+ pl.add_argument("--max-depth", type=int, default=2)
1140
+ pl.add_argument("--max-nodes", type=int, default=12)
1141
+ pl.add_argument("--labs-json", default=None,
1142
+ help='operator-declared instrument pool (S-T5): JSON '
1143
+ 'array of {"instrument": "<catalog-id>"} entries')
1144
+ matp = csub.add_parser("materials",
1145
+ help="run a materials formulation sweep against "
1146
+ "the program gate (material modality)")
1147
+ matp.add_argument("--objective", required=True)
1148
+ matp.add_argument("--formulations", required=True,
1149
+ help="comma-separated parameter values, e.g. 2,4,6,8,10")
1150
+ matp.add_argument("--gate", type=float, required=True)
1151
+ matp.add_argument("--unit", default="MPa")
1152
+ matp.add_argument("--metric", default="tensile_strength_mpa")
1153
+ matp.add_argument("--param", default="crosslinker_pct")
1154
+ matp.add_argument("--direction", choices=["min", "max"], default="max")
1155
+ matp.add_argument("--db", default="proef.db")
1156
+ matp.set_defaults(func=cmd_materials_run)
1157
+ pl.add_argument("--modality", default="",
1158
+ help="optional: small molecule, biologic, cell therapy, "
1159
+ "mRNA, agrochemical, material, words the Make "
1160
+ "step and selects the pack")
1161
+ pl.add_argument("--rounds", type=int, default=0,
1162
+ help="DMTA rounds per leaf (0 = auto: hypotheses / k)")
1163
+ pl.add_argument("--run-budget", type=int, default=20,
1164
+ help="total lab runs the whole tree may spend")
1165
+ pl.add_argument("--run", action="store_true")
1166
+ pl.add_argument("--candidates", default="", help="comma list for leaf hypotheses")
1167
+ pl.add_argument("--seed", type=int, default=7)
1168
+ pl.add_argument("--db", default="proef.db")
1169
+ pl.add_argument("--autonomy", choices=("act", "gate", "observe"), default="act")
1170
+ pl.set_defaults(func=cmd_plan)
1171
+
1172
+
1173
+ def _register_tools(sub, csub) -> None:
1174
+ """modalities, campaign reproduce, eval, templates, skills, campaign
1175
+ sweep, taste."""
1176
+ modp = sub.add_parser("modalities",
1177
+ help="registered DMTA modality packs, how "
1178
+ "Design/Make/Test/Analyze specialize")
1179
+ modp.set_defaults(func=cmd_modalities)
1180
+ rep = csub.add_parser("reproduce",
1181
+ help="replay a recorded experiment; diff verdicts")
1182
+ rep.add_argument("branch")
1183
+ rep.add_argument("--db", default="proef.db")
1184
+ rep.set_defaults(func=cmd_reproduce)
1185
+ ev = sub.add_parser("eval", help="run the eval suite (tasks, scores, leaderboard)")
1186
+ ev.add_argument("--task", help="run a single task by id")
1187
+ ev.add_argument("--suite", help="comma list: epistemics,models,reproductions "
1188
+ "(default: epistemics)")
1189
+ ev.add_argument("--all", action="store_true", help="every suite")
1190
+ ev.set_defaults(func=cmd_eval)
1191
+ templates = sub.add_parser("templates", help="list campaign templates")
1192
+ templates.add_argument("name", nargs="?", default=None)
1193
+ templates.set_defaults(func=cmd_templates)
1194
+
1195
+ sk = sub.add_parser("skills", help="discover/install scientific agent skills")
1196
+ sksub = sk.add_subparsers(dest="command", required=True)
1197
+ sksub.add_parser("list", help="list discovered skills")
1198
+ role = sksub.add_parser("role", help="skills recommended for an agent role")
1199
+ role.add_argument("role", choices=["design-agent", "target-agent",
1200
+ "assay-planning-agent", "analysis-agent",
1201
+ "trial-agent"])
1202
+ role.add_argument("--install", action="store_true",
1203
+ help="auto-install missing recommended skills")
1204
+ inst = sksub.add_parser("install", help="install skills from scientific-agent-skills")
1205
+ inst.add_argument("names", nargs="+")
1206
+ inst.add_argument("--dest", default=".agents/skills")
1207
+ sk.set_defaults(func=cmd_skills)
1208
+
1209
+ sw = csub.add_parser("sweep", help="fan one problem across candidate "
1210
+ "shards (parallel campaign harness) and roll up")
1211
+ sw.add_argument("--objective", required=True)
1212
+ sw.add_argument("--candidates", required=True,
1213
+ help="comma-separated candidate ids")
1214
+ sw.add_argument("--gate", type=float, default=20.0)
1215
+ sw.add_argument("--metric", default="potency")
1216
+ sw.add_argument("--unit", default="uM")
1217
+ sw.add_argument("--fan", type=int, default=3, help="number of shards")
1218
+ sw.add_argument("--k", type=int, default=2, help="hypotheses per shard round")
1219
+ sw.add_argument("--rounds", type=int, default=1)
1220
+ sw.add_argument("--seed", type=int, default=0)
1221
+ sw.add_argument("--db", default="proef.db")
1222
+ sw.set_defaults(func=cmd_sweep)
1223
+
1224
+ ta = sub.add_parser("taste", help="what distinguishes accepted "
1225
+ "hypotheses? accept-rate deltas + advisory "
1226
+ "prompt amendments (tighten-only)")
1227
+ ta.add_argument("--db", default="proef.db")
1228
+ ta.set_defaults(func=cmd_taste)
1229
+
1230
+
1231
+ def main(argv: list[str] | None = None) -> int:
1232
+ from proef.paths import migrate_legacy_workspace
1233
+ migrate_legacy_workspace()
1234
+ parser = argparse.ArgumentParser(prog="proef", description="Proef CLI")
1235
+ sub = parser.add_subparsers(dest="cmd", required=True)
1236
+ csub = _register_core(sub)
1237
+ _register_flow(sub, csub)
1238
+ _register_governance(sub, csub)
1239
+ _register_tools(sub, csub)
1240
+ args = parser.parse_args(argv)
1241
+ try:
1242
+ return args.func(args)
1243
+ except Exception as exc: # noqa: BLE001
1244
+ print(f"proef: error: {exc}", file=sys.stderr)
1245
+ return 2
1246
+
1247
+
1248
+ if __name__ == "__main__":
1249
+ raise SystemExit(main())