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/wizard_chain.py ADDED
@@ -0,0 +1,25 @@
1
+ """Wizard provenance chain — manual experiments hash-chain too (P5).
2
+
3
+ The wizard's lifecycle steps (definition, readiness review, uploaded
4
+ results, verdict) are recorded as provenance records on a `wizard/<id>`
5
+ branch, so `proef prove wizard/<id>` audits a scientist-defined experiment
6
+ exactly like an agent-driven one.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from proef.adapters.store.sqlite import get_store
11
+ from proef.core.contracts import Envelope, EventType
12
+ from proef.core.interfaces import record_for, system_actor
13
+
14
+ ACTOR = system_actor("scientist")
15
+
16
+
17
+ def wizard_branch(eid: str) -> str:
18
+ return f"wizard/{eid}"
19
+
20
+
21
+ def record_wizard_event(eid: str, event: EventType, decision: dict,
22
+ db_path: str = "proef.db"):
23
+ store = get_store(db_path)
24
+ env = Envelope(experiment_branch_id=wizard_branch(eid))
25
+ return store.append(record_for(env, event, ACTOR, decision=decision))
proef/wizard_store.py ADDED
@@ -0,0 +1,373 @@
1
+ """Persistent experiment state for the workbench wizard (DMTA spans days).
2
+
3
+ The wizard saves each experiment after every step, so an experiment defined
4
+ today can be resumed next week. One SQLite table, explicit status; status
5
+ only moves forward.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import sqlite3
11
+ import threading
12
+ import time
13
+ import uuid
14
+ from pathlib import Path
15
+
16
+ from proef.paths import DATA_DIR
17
+
18
+ DB_PATH = DATA_DIR / "wizard.db"
19
+
20
+ # ordered; index = wizard step to resume from (1-based, +2 for steps 3..6)
21
+ STATUSES = ["defining", "designing", "readiness_ok", "ready_blocked",
22
+ "executing", "results_uploaded", "verdict_recorded",
23
+ "completed", "failed", "interrupted"]
24
+
25
+
26
+ class WizardStore:
27
+ def __init__(self, path: Path | str = DB_PATH):
28
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
29
+ self._conn = sqlite3.connect(str(path), check_same_thread=False)
30
+ self._lock = threading.Lock()
31
+ self._conn.execute(
32
+ """CREATE TABLE IF NOT EXISTS experiments (
33
+ id TEXT PRIMARY KEY,
34
+ created_at REAL NOT NULL,
35
+ updated_at REAL NOT NULL,
36
+ status TEXT NOT NULL,
37
+ question TEXT NOT NULL,
38
+ payload TEXT NOT NULL
39
+ )""")
40
+ self._conn.execute("""
41
+ CREATE TABLE IF NOT EXISTS programs (
42
+ slug TEXT PRIMARY KEY,
43
+ name TEXT NOT NULL,
44
+ doc TEXT NOT NULL,
45
+ created_at REAL NOT NULL,
46
+ updated_at REAL NOT NULL
47
+ )""")
48
+ self._conn.execute("""
49
+ CREATE TABLE IF NOT EXISTS meta (
50
+ key TEXT PRIMARY KEY,
51
+ value TEXT NOT NULL
52
+ )""")
53
+ self._backfill_program_ids()
54
+ self._conn.execute("""
55
+ CREATE TABLE IF NOT EXISTS campaign_specs (
56
+ experiment_id TEXT PRIMARY KEY
57
+ REFERENCES experiments(id) ON DELETE CASCADE,
58
+ program_slug TEXT REFERENCES programs(slug),
59
+ objective TEXT NOT NULL,
60
+ constraints_json TEXT,
61
+ success_metric TEXT,
62
+ k INTEGER,
63
+ rounds INTEGER,
64
+ autonomy TEXT,
65
+ hypothesis_source TEXT,
66
+ n_candidates INTEGER,
67
+ modality TEXT,
68
+ created_at REAL NOT NULL
69
+ )""")
70
+ self._conn.execute("""
71
+ CREATE TABLE IF NOT EXISTS program_experiments (
72
+ program_slug TEXT NOT NULL
73
+ REFERENCES programs(slug) ON DELETE CASCADE,
74
+ experiment_id TEXT NOT NULL,
75
+ role TEXT NOT NULL DEFAULT 'leaf',
76
+ campaign_root TEXT,
77
+ question TEXT,
78
+ status TEXT,
79
+ created_at REAL NOT NULL,
80
+ PRIMARY KEY (program_slug, experiment_id)
81
+ )""")
82
+
83
+ def _row(self, r) -> dict:
84
+ return {"id": r[0], "created_at": r[1], "updated_at": r[2],
85
+ "status": r[3], "question": r[4], "payload": json.loads(r[5])}
86
+
87
+ def create(self, question: str, claim: str, target: str,
88
+ eid: str | None = None) -> str:
89
+ eid = eid or uuid.uuid4().hex[:12]
90
+ with self._lock:
91
+ now = time.time()
92
+ self._conn.execute(
93
+ "INSERT OR REPLACE INTO experiments VALUES (?,?,?,?,?,?)",
94
+ (eid, now, now, "defining", question,
95
+ json.dumps({"problem": {"question": question, "claim": claim,
96
+ "target": target}})))
97
+ self._conn.commit()
98
+ return eid
99
+
100
+ def set_status(self, eid: str, status: str) -> None:
101
+ with self._lock:
102
+ self._conn.execute(
103
+ "UPDATE experiments SET status=?, updated_at=? WHERE id=?",
104
+ (status, time.time(), eid))
105
+ self._conn.commit()
106
+
107
+ def register_agent(self, eid: str, objective: str, log: str,
108
+ autonomy: str = "act", pid: int | None = None,
109
+ status: str = "executing",
110
+ program: str | None = None) -> str:
111
+ """One registry: agent-driven experiments live in the same table as
112
+ wizard-defined ones, tagged by origin (and program when launched
113
+ from one)."""
114
+ with self._lock:
115
+ now = time.time()
116
+ payload = {"agent": {"log": log, "autonomy": autonomy,
117
+ "pid": pid, "problem_id": None}}
118
+ if program:
119
+ payload["program"] = program
120
+ self._conn.execute(
121
+ "INSERT OR REPLACE INTO experiments VALUES (?,?,?,?,?,?)",
122
+ (eid, now, now, status, objective, json.dumps(payload)))
123
+ self._conn.commit()
124
+ return eid
125
+
126
+ # ------------------------------------------------ program relations
127
+ def _next_program_seq(self) -> int:
128
+ row = self._conn.execute(
129
+ "SELECT value FROM meta WHERE key='program_seq'").fetchone()
130
+ n = int(row[0]) + 1 if row else 1
131
+ self._conn.execute(
132
+ "INSERT INTO meta VALUES ('program_seq',?) "
133
+ "ON CONFLICT(key) DO UPDATE SET value=?",
134
+ (str(n), str(n)))
135
+ return n
136
+
137
+ def _backfill_program_ids(self) -> None:
138
+ """One-time: mint PRG-00N ids for programs created before the
139
+ counter existed, in creation order."""
140
+ with self._lock:
141
+ rows = self._conn.execute(
142
+ "SELECT slug, doc, created_at FROM programs "
143
+ "ORDER BY created_at, rowid").fetchall()
144
+ seq = 0
145
+ for slug, doc, _ in rows:
146
+ d = json.loads(doc)
147
+ if d.get("program_id"):
148
+ seq = max(seq, int(d["program_id"].split("-")[1]))
149
+ for slug, doc, _ in rows:
150
+ d = json.loads(doc)
151
+ if d.get("program_id"):
152
+ continue
153
+ seq += 1
154
+ d["program_id"] = f"PRG-{seq:03d}"
155
+ self._conn.execute(
156
+ "UPDATE programs SET doc=? WHERE slug=?",
157
+ (json.dumps(d), slug))
158
+ if seq:
159
+ self._conn.execute(
160
+ "INSERT INTO meta VALUES ('program_seq',?) "
161
+ "ON CONFLICT(key) DO UPDATE SET value=?",
162
+ (str(seq), str(seq)))
163
+ self._conn.commit()
164
+
165
+ def upsert_program(self, slug: str, name: str, doc: dict) -> None:
166
+ with self._lock:
167
+ now = time.time()
168
+ exists = self._conn.execute(
169
+ "SELECT 1 FROM programs WHERE slug=?", (slug,)).fetchone()
170
+ if not exists:
171
+ if not doc.get("program_id"):
172
+ # every program gets a stable human id: PRG-001, PRG-002, …
173
+ doc = {**doc,
174
+ "program_id": f"PRG-{self._next_program_seq():03d}"}
175
+ elif not doc.get("program_id"):
176
+ prev = self._conn.execute(
177
+ "SELECT doc FROM programs WHERE slug=?", (slug,)).fetchone()
178
+ pid = json.loads(prev[0]).get("program_id") if prev else None
179
+ if pid:
180
+ doc = {**doc, "program_id": pid}
181
+ self._conn.execute(
182
+ "INSERT INTO programs VALUES (?,?,?,?,?) "
183
+ "ON CONFLICT(slug) DO UPDATE SET name=?, doc=?, updated_at=?",
184
+ (slug, name, json.dumps(doc), now, now,
185
+ name, json.dumps(doc), now))
186
+ self._conn.commit()
187
+
188
+ def delete_program(self, slug: str) -> None:
189
+ """Remove the program and its links (relations cascade via FK;
190
+ experiments survive unlinked)."""
191
+ with self._lock:
192
+ self._conn.execute("PRAGMA foreign_keys=ON")
193
+ self._conn.execute(
194
+ "DELETE FROM program_experiments WHERE program_slug=?",
195
+ (slug,))
196
+ # campaign specs survive with the experiment; detach the program
197
+ self._conn.execute(
198
+ "UPDATE campaign_specs SET program_slug=NULL "
199
+ "WHERE program_slug=?", (slug,))
200
+ self._conn.execute(
201
+ "DELETE FROM programs WHERE slug=?", (slug,))
202
+ self._conn.commit()
203
+
204
+ def get_program(self, slug: str) -> dict | None:
205
+ row = self._conn.execute(
206
+ "SELECT doc FROM programs WHERE slug=?", (slug,)).fetchone()
207
+ return json.loads(row[0]) if row else None
208
+
209
+ def db_programs(self) -> list[dict]:
210
+ out = []
211
+ for slug, name, doc, ts in self._conn.execute(
212
+ "SELECT slug, name, doc, updated_at FROM programs "
213
+ "ORDER BY created_at"):
214
+ out.append({"slug": slug, "name": name,
215
+ "doc": json.loads(doc), "updated_at": ts})
216
+ return out
217
+
218
+ def db_program_count(self) -> int:
219
+ return self._conn.execute(
220
+ "SELECT COUNT(*) FROM programs").fetchone()[0]
221
+
222
+ def delete_experiment(self, eid: str) -> bool:
223
+ """Hard-remove an experiment row (registry only — the provenance
224
+ ledger is WORM and keeps the audit trail)."""
225
+ with self._lock:
226
+ cur = self._conn.execute(
227
+ "DELETE FROM experiments WHERE id=?", (eid,))
228
+ self._conn.commit()
229
+ return cur.rowcount > 0
230
+
231
+ def link_experiment(self, program_slug: str, eid: str, role: str = "leaf", campaign_root: str | None = None,
232
+ question: str = "", status: str = "executing") -> None:
233
+ """The Program-Experiment relation: role 'campaign' marks a
234
+ problem-tree ROOT (campaign container), role 'leaf' marks a
235
+ single experiment under the program (campaign_root set when it
236
+ belongs to a decomposed campaign)."""
237
+ with self._lock:
238
+ now = time.time()
239
+ self._conn.execute(
240
+ "INSERT INTO program_experiments VALUES (?,?,?,?,?,?,?) "
241
+ "ON CONFLICT(program_slug, experiment_id) DO UPDATE SET "
242
+ "role=?, campaign_root=?, question=?, status=?",
243
+ (program_slug, eid, role, campaign_root,
244
+ (question or "")[:120], status, now,
245
+ role, campaign_root, (question or "")[:120], status))
246
+ self._conn.commit()
247
+
248
+ def program_links(self, slug: str) -> list[dict]:
249
+ return [{"program": r[0], "eid": r[1], "role": r[2],
250
+ "campaign_root": r[3], "question": r[4], "status": r[5]}
251
+ for r in self._conn.execute(
252
+ "SELECT program_slug, experiment_id, role, "
253
+ "campaign_root, question, status "
254
+ "FROM program_experiments WHERE program_slug=? "
255
+ "ORDER BY created_at", (slug,))]
256
+
257
+ def set_campaign_spec(self, eid: str, *, objective: str,
258
+ program_slug: str | None = None,
259
+ constraints: list | None = None,
260
+ success_metric: str | None = None,
261
+ k: int | None = None, rounds: int | None = None,
262
+ autonomy: str | None = None,
263
+ hypothesis_source: str | None = None,
264
+ n_candidates: int | None = None,
265
+ modality: str | None = None) -> None:
266
+ with self._lock:
267
+ self._conn.execute(
268
+ "INSERT OR REPLACE INTO campaign_specs VALUES "
269
+ "(?,?,?,?,?,?,?,?,?,?,?,?)",
270
+ (eid, program_slug, objective,
271
+ json.dumps(constraints) if constraints else None,
272
+ success_metric, k, rounds, autonomy, hypothesis_source,
273
+ n_candidates, modality, time.time()))
274
+ self._conn.commit()
275
+
276
+ def get_campaign_spec(self, eid: str) -> dict | None:
277
+ row = self._conn.execute(
278
+ "SELECT experiment_id, program_slug, objective, "
279
+ "constraints_json, success_metric, k, rounds, autonomy, "
280
+ "hypothesis_source, n_candidates, modality "
281
+ "FROM campaign_specs WHERE experiment_id=?", (eid,)).fetchone()
282
+ if not row:
283
+ return None
284
+ return {"experiment_id": row[0], "program_slug": row[1],
285
+ "objective": row[2],
286
+ "constraints": json.loads(row[3]) if row[3] else [],
287
+ "success_metric": row[4], "k": row[5], "rounds": row[6],
288
+ "autonomy": row[7], "hypothesis_source": row[8],
289
+ "n_candidates": row[9], "modality": row[10]}
290
+
291
+ def set_question(self, eid: str, question: str) -> None:
292
+ """Retitle: question is a column, not payload fields."""
293
+ with self._lock:
294
+ self._conn.execute(
295
+ "UPDATE experiments SET question=?, updated_at=? "
296
+ "WHERE id=?", (question, time.time(), eid))
297
+ self._conn.commit()
298
+
299
+ def link_problem(self, eid: str, problem_id: str) -> None:
300
+ with self._lock:
301
+ row = self._conn.execute(
302
+ "SELECT payload FROM experiments WHERE id=?", (eid,)).fetchone()
303
+ if not row:
304
+ return
305
+ payload = json.loads(row[0])
306
+ if payload.get("agent") is not None:
307
+ payload["agent"]["problem_id"] = problem_id
308
+ self._conn.execute(
309
+ "UPDATE experiments SET payload=?, updated_at=? WHERE id=?",
310
+ (json.dumps(payload), time.time(), eid))
311
+ self._conn.commit()
312
+
313
+ def update(self, eid: str, status: str, **fields) -> None:
314
+ assert status in STATUSES
315
+ with self._lock:
316
+ row = self._conn.execute(
317
+ "SELECT payload FROM experiments WHERE id=?", (eid,)).fetchone()
318
+ if not row:
319
+ raise KeyError(eid)
320
+ payload = json.loads(row[0])
321
+ payload.update(fields)
322
+ self._conn.execute(
323
+ "UPDATE experiments SET status=?, payload=?, updated_at=? WHERE id=?",
324
+ (status, json.dumps(payload, default=str), time.time(), eid))
325
+ self._conn.commit()
326
+
327
+ def get(self, eid: str) -> dict | None:
328
+ r = self._conn.execute(
329
+ "SELECT * FROM experiments WHERE id=?", (eid,)).fetchone()
330
+ return self._row(r) if r else None
331
+
332
+ def _visible(self, where: str, limit: int | None = None) -> list[dict]:
333
+ sql = (f"SELECT * FROM experiments WHERE {where} "
334
+ "AND (payload NOT LIKE '%\"archived\": true%') "
335
+ "ORDER BY updated_at DESC")
336
+ args = ()
337
+ if limit is not None:
338
+ sql += " LIMIT ?"
339
+ args = (limit,)
340
+ return [self._row(r) for r in
341
+ self._conn.execute(sql, args).fetchall()]
342
+
343
+ def ongoing(self) -> list[dict]:
344
+ return self._visible("status != 'verdict_recorded'")
345
+
346
+ def finished(self, limit: int = 20) -> list[dict]:
347
+ return self._visible("status = 'verdict_recorded'", limit)
348
+
349
+ def purge_archived(self) -> int:
350
+ """Hard-delete archived REGISTRY rows. Provenance (proef.db)
351
+ is untouched — only the working-set registration is removed."""
352
+ cur = self._conn.execute(
353
+ "DELETE FROM experiments "
354
+ "WHERE payload LIKE '%\"archived\": true%'")
355
+ # drop program links whose experiment no longer exists
356
+ self._conn.execute(
357
+ "DELETE FROM program_experiments WHERE experiment_id NOT IN "
358
+ "(SELECT id FROM experiments)")
359
+ self._conn.commit()
360
+ return cur.rowcount
361
+
362
+ def archived(self, limit: int = 100) -> list[dict]:
363
+ rows = self._conn.execute(
364
+ "SELECT * FROM experiments "
365
+ "WHERE payload LIKE '%\"archived\": true%' "
366
+ "ORDER BY updated_at DESC LIMIT ?", (limit,)).fetchall()
367
+ return [self._row(r) for r in rows]
368
+
369
+ def set_archived(self, eid: str, archived: bool = True) -> None:
370
+ """Archive = out of the working set, but never deleted: the
371
+ provenance record is WORM, so experiments are retired, not
372
+ erased."""
373
+ self.update(eid, self.get(eid)["status"], archived=archived)