Vinyeh commited on
Commit
b02f8ea
·
verified ·
1 Parent(s): 145c030

Add core_worlds (part 4)

Browse files
Files changed (37) hide show
  1. core_worlds/src/benchmark/plugins/verifier/l14/pyclean.py +307 -0
  2. core_worlds/src/benchmark/plugins/verifier/l14/reverify.py +72 -0
  3. core_worlds/src/benchmark/plugins/verifier/l14/witness.py +813 -0
  4. core_worlds/src/benchmark/plugins/verifier/l15/__init__.py +1 -0
  5. core_worlds/src/benchmark/plugins/verifier/l15/verifier.py +150 -0
  6. core_worlds/src/benchmark/plugins/verifier/l16/__init__.py +0 -0
  7. core_worlds/src/benchmark/plugins/verifier/l16/domain.py +98 -0
  8. core_worlds/src/benchmark/plugins/verifier/l16/plugin.py +114 -0
  9. core_worlds/src/benchmark/plugins/verifier/l16/reference.py +152 -0
  10. core_worlds/src/benchmark/plugins/verifier/l16/rest_spotcheck.py +96 -0
  11. core_worlds/src/benchmark/plugins/verifier/l16/reverify.py +71 -0
  12. core_worlds/src/benchmark/plugins/verifier/l16/witness.py +199 -0
  13. core_worlds/src/benchmark/schema/__init__.py +0 -0
  14. core_worlds/src/benchmark/schema/plugin_protocols.py +167 -0
  15. core_worlds/src/scripts/assemble_core_release.py +114 -0
  16. core_worlds/src/scripts/build_core_oracle.py +130 -0
  17. core_worlds/src/scripts/check_core_license_pointers.py +173 -0
  18. core_worlds/src/scripts/core_release/__init__.py +10 -0
  19. core_worlds/src/scripts/core_release/assemble.py +324 -0
  20. core_worlds/src/scripts/core_release/contract.py +391 -0
  21. core_worlds/src/scripts/core_release/docs_templates.py +132 -0
  22. core_worlds/src/scripts/core_release/errors.py +40 -0
  23. core_worlds/src/scripts/core_release/labels.py +51 -0
  24. core_worlds/src/scripts/core_release/layout.py +146 -0
  25. core_worlds/src/scripts/core_release/leakage.py +41 -0
  26. core_worlds/src/scripts/core_release/license_registry.py +599 -0
  27. core_worlds/src/scripts/core_release/license_render.py +150 -0
  28. core_worlds/src/scripts/core_release/licenses.py +199 -0
  29. core_worlds/src/scripts/core_release/semantics.py +171 -0
  30. core_worlds/src/scripts/core_release/tasks.py +219 -0
  31. core_worlds/src/scripts/core_release/validate.py +118 -0
  32. core_worlds/src/scripts/core_release/verify.py +206 -0
  33. core_worlds/src/scripts/eval.sh +198 -0
  34. core_worlds/src/scripts/eval_core.sh +167 -0
  35. core_worlds/src/scripts/eval_core_from_hf.sh +36 -0
  36. core_worlds/src/scripts/eval_from_hf.sh +38 -0
  37. core_worlds/src/scripts/scan_core_release_semantics.py +313 -0
core_worlds/src/benchmark/plugins/verifier/l14/pyclean.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L14 clean-parser reference path: pure-Python predicates over raw rows.
2
+
3
+ Second, structurally independent implementation of every L14 family answer.
4
+ SQL is used only to extract raw rows with single-key restrictions (no JOIN
5
+ logic, no aggregation, no filtering predicates beyond the scoping key); all
6
+ semantic filtering, unit normalization, hierarchy walking and set building is
7
+ implemented imperatively here. The fast-path SQL (families.py) and this path
8
+ must agree exactly or the candidate is rejected.
9
+
10
+ Runs against any SQLite database with the L14 slice schema (the pinned DB or
11
+ an in-memory witness slice).
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import sqlite3
16
+ from typing import Any
17
+
18
+ UNIT_SCALE_TO_NM = {"nM": 1.0, "uM": 1_000.0, "pM": 0.001, "mM": 1_000_000.0}
19
+
20
+
21
+ def _rows(con: sqlite3.Connection, sql: str, args: tuple[Any, ...] = ()):
22
+ return con.execute(sql, args).fetchall()
23
+
24
+
25
+ def _molregno(con, chembl_id):
26
+ r = _rows(con, "SELECT molregno FROM molecule_dictionary "
27
+ "WHERE chembl_id = ?", (chembl_id,))
28
+ return r[0][0] if r else None
29
+
30
+
31
+ def _tid(con, chembl_id):
32
+ r = _rows(con, "SELECT tid FROM target_dictionary WHERE chembl_id = ?",
33
+ (chembl_id,))
34
+ return r[0][0] if r else None
35
+
36
+
37
+ def _assay_id(con, chembl_id):
38
+ r = _rows(con, "SELECT assay_id FROM assays WHERE chembl_id = ?",
39
+ (chembl_id,))
40
+ return r[0][0] if r else None
41
+
42
+
43
+ def _chembl_map(con, molregnos):
44
+ out = {}
45
+ for m in molregnos:
46
+ r = _rows(con, "SELECT chembl_id FROM molecule_dictionary "
47
+ "WHERE molregno = ?", (m,))
48
+ if r:
49
+ out[m] = r[0][0]
50
+ return out
51
+
52
+
53
+ def _assay_chembl_map(con, assay_ids):
54
+ out = {}
55
+ for a in assay_ids:
56
+ r = _rows(con, "SELECT chembl_id FROM assays WHERE assay_id = ?",
57
+ (a,))
58
+ if r:
59
+ out[a] = r[0][0]
60
+ return out
61
+
62
+
63
+ def _activities_for_assays(con, assay_ids):
64
+ if not assay_ids:
65
+ return []
66
+ marks = ",".join("?" * len(assay_ids))
67
+ return _rows(con,
68
+ "SELECT activity_id, assay_id, molregno, standard_type, "
69
+ "standard_relation, standard_value, standard_units "
70
+ "FROM activities WHERE assay_id IN (" + marks + ")",
71
+ tuple(assay_ids))
72
+
73
+
74
+ def _assays_for_tids(con, tids):
75
+ if not tids:
76
+ return []
77
+ marks = ",".join("?" * len(tids))
78
+ return _rows(con,
79
+ "SELECT assay_id, chembl_id, tid, assay_type, "
80
+ "assay_organism, confidence_score, doc_id "
81
+ "FROM assays WHERE tid IN (" + marks + ")",
82
+ tuple(tids))
83
+
84
+
85
+ def answer_org_parent_salt_members(con, params):
86
+ parent = _molregno(con, params["parent_chembl_id"])
87
+ if parent is None:
88
+ return frozenset()
89
+ rows = _rows(con, "SELECT molregno FROM molecule_hierarchy "
90
+ "WHERE parent_molregno = ?", (parent,))
91
+ cmap = _chembl_map(con, [r[0] for r in rows])
92
+ return frozenset(c for c in cmap.values()
93
+ if c != params["parent_chembl_id"])
94
+
95
+
96
+ def answer_app_molecule_assays_of_type(con, params):
97
+ m = _molregno(con, params["molecule_chembl_id"])
98
+ if m is None:
99
+ return frozenset()
100
+ rows = _rows(con, "SELECT assay_id, standard_type, standard_relation, "
101
+ "standard_value, standard_units FROM activities "
102
+ "WHERE molregno = ?", (m,))
103
+ keep = {r[0] for r in rows
104
+ if r[1] == params["standard_type"] and r[2] == "="
105
+ and r[4] == "nM" and r[3] is not None}
106
+ return frozenset(_assay_chembl_map(con, keep).values())
107
+
108
+
109
+ def _binding_assay_rows(con, tid):
110
+ assays = _assays_for_tids(con, [tid])
111
+ good = {a[0]: a for a in assays
112
+ if a[3] == "B" and a[6] is not None and a[6] >= 8}
113
+ return assays, good
114
+
115
+
116
+ def answer_app_target_binding_set(con, params):
117
+ tid = _tid(con, params["target_chembl_id"])
118
+ if tid is None:
119
+ return frozenset()
120
+ _, good = _binding_assay_rows(con, tid)
121
+ acts = _activities_for_assays(con, sorted(good))
122
+ mols = {r[2] for r in acts
123
+ if r[3] == params["standard_type"] and r[4] == "="
124
+ and r[6] == "nM" and r[5] is not None
125
+ and r[2] is not None and float(r[5]) <= params["threshold"]}
126
+ return frozenset(_chembl_map(con, mols).values())
127
+
128
+
129
+ def answer_org_assay_context_organism(con, params):
130
+ tid = _tid(con, params["target_chembl_id"])
131
+ if tid is None:
132
+ return frozenset()
133
+ assays, _ = _binding_assay_rows(con, tid)
134
+ return frozenset(a[1] for a in assays
135
+ if a[3] == "B" and a[4] == params["assay_organism"])
136
+
137
+
138
+ def _assay_scoped_activities(con, assay_chembl_id):
139
+ aid = _assay_id(con, assay_chembl_id)
140
+ if aid is None:
141
+ return None, []
142
+ return aid, _activities_for_assays(con, [aid])
143
+
144
+
145
+ def answer_app_measurement_exact_set(con, params):
146
+ aid, acts = _assay_scoped_activities(con, params["assay_chembl_id"])
147
+ mols = {r[2] for r in acts
148
+ if r[3] == params["standard_type"] and r[4] == "="
149
+ and r[6] == "nM" and r[5] is not None and r[2] is not None}
150
+ return frozenset(_chembl_map(con, mols).values())
151
+
152
+
153
+ def answer_app_unit_normalized_potency(con, params):
154
+ return _repair_answer(con, params)
155
+
156
+
157
+ def _repair_answer(con, params):
158
+ aid, acts = _assay_scoped_activities(con, params["assay_chembl_id"])
159
+ mols = {r[2] for r in acts
160
+ if r[3] == params["standard_type"] and r[4] == "="
161
+ and r[6] == "nM" and r[5] is not None and r[2] is not None
162
+ and float(r[5]) <= params["threshold"]}
163
+ return frozenset(_chembl_map(con, mols).values())
164
+
165
+
166
+ def answer_rep_relation_flip_repair(con, params):
167
+ return _repair_answer(con, params)
168
+
169
+
170
+ def answer_rep_standardization_table(con, params):
171
+ return _repair_answer(con, params)
172
+
173
+
174
+ def answer_org_target_class_members(con, params):
175
+ children: dict[int, list[int]] = {}
176
+ for cid, parent in _rows(con, "SELECT protein_class_id, parent_id "
177
+ "FROM protein_classification"):
178
+ if parent is not None:
179
+ children.setdefault(parent, []).append(cid)
180
+ sub = set()
181
+ stack = [params["protein_class_id"]]
182
+ while stack:
183
+ node = stack.pop()
184
+ if node in sub:
185
+ continue
186
+ sub.add(node)
187
+ stack.extend(children.get(node, ()))
188
+ comp_rows = _rows(con, "SELECT component_id, protein_class_id "
189
+ "FROM component_class")
190
+ comp_ok = {c for c, cid in comp_rows if cid in sub}
191
+ tc_rows = _rows(con, "SELECT tid, component_id FROM target_components")
192
+ tids = {t for t, c in tc_rows if c in comp_ok}
193
+ out = set()
194
+ for tid, chembl_id, ttype, org in _rows(
195
+ con, "SELECT tid, chembl_id, target_type, organism "
196
+ "FROM target_dictionary"):
197
+ if tid in tids and ttype == "SINGLE PROTEIN" and org == "Homo sapiens":
198
+ out.add(chembl_id)
199
+ return frozenset(out)
200
+
201
+
202
+ def answer_org_journal_year_provenance(con, params):
203
+ docs = _rows(con, "SELECT doc_id FROM docs WHERE journal = ? "
204
+ "AND year = ?", (params["journal"], params["year"]))
205
+ if not docs:
206
+ return frozenset()
207
+ marks = ",".join("?" * len(docs))
208
+ assays = _rows(con, "SELECT assay_id FROM assays WHERE doc_id IN ("
209
+ + marks + ")", tuple(d[0] for d in docs))
210
+ acts = _activities_for_assays(con, [a[0] for a in assays])
211
+ mols = {r[2] for r in acts
212
+ if r[3] in ("IC50", "Ki", "EC50") and r[4] == "="
213
+ and r[6] == "nM" and r[5] is not None and r[2] is not None}
214
+ return frozenset(_chembl_map(con, mols).values())
215
+
216
+
217
+ def answer_app_mechanism_action_type(con, params):
218
+ tid = _tid(con, params["target_chembl_id"])
219
+ if tid is None:
220
+ return frozenset()
221
+ rows = _rows(con, "SELECT molregno, action_type FROM drug_mechanism "
222
+ "WHERE tid = ?", (tid,))
223
+ mols = {r[0] for r in rows if r[1] == params["action_type"]}
224
+ pchembl, parents = _parent_chembl_map(con, mols)
225
+ return frozenset(pchembl[p] for p in
226
+ {parents[m] for m in mols} if p in pchembl)
227
+
228
+
229
+ def _parent_chembl_map(con, mols):
230
+ parents = {}
231
+ for m in mols:
232
+ r = _rows(con, "SELECT parent_molregno FROM molecule_hierarchy "
233
+ "WHERE molregno = ?", (m,))
234
+ parents[m] = r[0][0] if r else m
235
+ wanted = sorted(set(parents.values()))
236
+ out = {}
237
+ for p in wanted:
238
+ r = _rows(con, "SELECT chembl_id FROM molecule_dictionary "
239
+ "WHERE molregno = ?", (p,))
240
+ if r:
241
+ out[p] = r[0][0]
242
+ return out, parents
243
+
244
+
245
+ def answer_app_indication_mesh(con, params):
246
+ rows = _rows(con, "SELECT molregno, max_phase_for_ind "
247
+ "FROM drug_indication WHERE mesh_heading = ?",
248
+ (params["mesh_heading"],))
249
+ mols = {r[0] for r in rows
250
+ if r[1] is not None and float(r[1]) >= 2}
251
+ pchembl, parents = _parent_chembl_map(con, mols)
252
+ return frozenset(pchembl[p] for p in
253
+ {parents[m] for m in mols} if p in pchembl)
254
+
255
+
256
+ def answer_org_uniprot_target_map(con, params):
257
+ comps = _rows(con, "SELECT component_id FROM component_sequences "
258
+ "WHERE accession = ?", (params["accession"],))
259
+ if not comps:
260
+ return frozenset()
261
+ marks = ",".join("?" * len(comps))
262
+ tc = _rows(con, "SELECT tid, component_id FROM target_components "
263
+ "WHERE component_id IN (" + marks + ")",
264
+ tuple(c[0] for c in comps))
265
+ tids = {t for t, _c in tc}
266
+ out = set()
267
+ for tid, chembl_id, ttype, org in _rows(
268
+ con, "SELECT tid, chembl_id, target_type, organism "
269
+ "FROM target_dictionary"):
270
+ if tid in tids and ttype == "SINGLE PROTEIN" and org == "Homo sapiens":
271
+ out.add(chembl_id)
272
+ return frozenset(out)
273
+
274
+
275
+ def answer_app_multihop_target_journal(con, params):
276
+ tid = _tid(con, params["target_chembl_id"])
277
+ if tid is None:
278
+ return frozenset()
279
+ assays, good = _binding_assay_rows(con, tid)
280
+ docs = {d[0] for d in _rows(con, "SELECT doc_id FROM docs "
281
+ "WHERE journal = ?",
282
+ (params["journal"],))}
283
+ keep_assays = {a[0] for a in assays
284
+ if a[0] in good and a[6] in docs}
285
+ acts = _activities_for_assays(con, sorted(keep_assays))
286
+ mols = {r[2] for r in acts
287
+ if r[3] == "IC50" and r[4] == "=" and r[6] == "nM"
288
+ and r[5] is not None and r[2] is not None}
289
+ return frozenset(_chembl_map(con, mols).values())
290
+
291
+
292
+ ANSWER_BY_FAMILY = {
293
+ "org_parent_salt_members": answer_org_parent_salt_members,
294
+ "app_molecule_assays_of_type": answer_app_molecule_assays_of_type,
295
+ "app_target_binding_set": answer_app_target_binding_set,
296
+ "org_assay_context_organism": answer_org_assay_context_organism,
297
+ "app_measurement_exact_set": answer_app_measurement_exact_set,
298
+ "app_unit_normalized_potency": answer_app_unit_normalized_potency,
299
+ "rep_relation_flip_repair": answer_rep_relation_flip_repair,
300
+ "rep_standardization_table": answer_rep_standardization_table,
301
+ "org_target_class_members": answer_org_target_class_members,
302
+ "org_journal_year_provenance": answer_org_journal_year_provenance,
303
+ "app_mechanism_action_type": answer_app_mechanism_action_type,
304
+ "app_indication_mesh": answer_app_indication_mesh,
305
+ "org_uniprot_target_map": answer_org_uniprot_target_map,
306
+ "app_multihop_target_journal": answer_app_multihop_target_journal,
307
+ }
core_worlds/src/benchmark/plugins/verifier/l14/reverify.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L14 native-evidence reverification CLI.
2
+
3
+ Recomputes the clean-parser reference answer for one shipped L14 task from
4
+ the pinned ChEMBL 37 SQLite bytes and compares it against the recorded oracle
5
+ answer. This is the exact command embedded in every QUALIFIED record's
6
+ ``native_evidence.commands``; it is independently re-runnable from the repo
7
+ root with only ``.venv/bin/python``:
8
+
9
+ .venv/bin/python -m benchmark.plugins.verifier.l14.reverify \
10
+ --pin-root external_knowledge/pinned/chembl/chembl-37 \
11
+ --oracle bank/staging_20k/l14/oracle/<oracle-file>.json
12
+
13
+ Exit code 0 iff the recomputed verdict is PASS and matches the recorded
14
+ reference verdict and answer hash.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import hashlib
20
+ import json
21
+ import sys
22
+ from pathlib import Path
23
+
24
+
25
+ def _sha(payload) -> str:
26
+ return hashlib.sha256(
27
+ json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()
28
+ ).hexdigest()
29
+
30
+
31
+ def main(argv: list[str] | None = None) -> int:
32
+ ap = argparse.ArgumentParser(description="L14 native evidence reverify")
33
+ ap.add_argument("--pin-root", required=True)
34
+ ap.add_argument("--oracle", required=True,
35
+ help="path to the task's oracle JSON (evaluator-private)")
36
+ args = ap.parse_args(argv)
37
+
38
+ from benchmark.plugins.source.l14.kb import load_kb
39
+ from benchmark.plugins.verifier.l14 import plugin as verifier
40
+
41
+ oracle_path = Path(args.oracle)
42
+ oracle = json.loads(oracle_path.read_text(encoding="utf-8"))
43
+ family = oracle["family"]
44
+ params = oracle["params"]
45
+ expected = tuple(sorted(set(oracle["expected_answer"])))
46
+
47
+ kb = load_kb(args.pin_root)
48
+ ev = verifier.verify_reference(Path(args.pin_root), family, params,
49
+ expected, kb)
50
+
51
+ answer_sha = _sha(sorted(set(expected)))
52
+ ok = (ev.get("verdict") == "PASS"
53
+ and oracle.get("reference", {}).get("verdict") == "PASS"
54
+ and ev.get("answer_sha256", answer_sha) == answer_sha
55
+ and oracle.get("expected_answer_sha256") == answer_sha)
56
+ out = {
57
+ "task_id": oracle.get("task_id"),
58
+ "family": family,
59
+ "recomputed_verdict": ev.get("verdict"),
60
+ "recomputed_answer_sha256": ev.get("answer_sha256", answer_sha),
61
+ "recorded_answer_sha256": oracle.get("expected_answer_sha256"),
62
+ "recorded_verdict": oracle.get("reference", {}).get("verdict"),
63
+ "engine": ev.get("engine"),
64
+ "db_manifest_sha": ev.get("db_manifest_sha"),
65
+ "match": ok,
66
+ }
67
+ print(json.dumps(out, indent=2, sort_keys=True))
68
+ return 0 if ok else 1
69
+
70
+
71
+ if __name__ == "__main__":
72
+ sys.exit(main())
core_worlds/src/benchmark/plugins/verifier/l14/witness.py ADDED
@@ -0,0 +1,813 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L14 semantic witnesses: counterfactual perturbation evidence per family.
2
+
3
+ For every candidate we build an in-memory SQLite slice from the pinned DB
4
+ (same table names/columns the family predicates read), then compute:
5
+ * governed probe: family answer on the unmutated slice (must EQUAL the
6
+ full-DB reference answer — proves slice completeness),
7
+ * perturbed probe: family answer on the mutated slice (must DIFFER),
8
+ * control probe: a bystander answer/query on both slices (must be
9
+ UNCHANGED).
10
+
11
+ A candidate is NON_SEMANTIC when the seeded perturbation fails to flip the
12
+ governed probe or also moves the control probe. Slice content hash recorded.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import json
18
+ import random
19
+ import sqlite3
20
+ from typing import Any, Callable
21
+
22
+ from benchmark.plugins.verifier.l14 import pyclean
23
+
24
+ SLICE_COLUMNS: dict[str, list[str]] = {
25
+ "molecule_dictionary": ["molregno", "chembl_id"],
26
+ "molecule_hierarchy": ["molregno", "parent_molregno"],
27
+ "assays": ["assay_id", "chembl_id", "tid", "assay_type",
28
+ "assay_organism", "confidence_score", "doc_id"],
29
+ "activities": ["activity_id", "assay_id", "molregno", "standard_type",
30
+ "standard_relation", "standard_value", "standard_units"],
31
+ "target_dictionary": ["tid", "chembl_id", "target_type", "organism"],
32
+ "docs": ["doc_id", "journal", "year"],
33
+ "drug_mechanism": ["mec_id", "molregno", "tid", "action_type"],
34
+ "drug_indication": ["drugind_id", "molregno", "mesh_heading",
35
+ "max_phase_for_ind"],
36
+ "component_sequences": ["component_id", "accession"],
37
+ "target_components": ["tid", "component_id"],
38
+ "component_class": ["component_id", "protein_class_id"],
39
+ "protein_classification": ["protein_class_id", "parent_id"],
40
+ }
41
+
42
+ COL_TYPES = {
43
+ "molregno": "INTEGER", "chembl_id": "TEXT", "parent_molregno": "INTEGER",
44
+ "assay_id": "INTEGER", "tid": "INTEGER", "assay_type": "TEXT",
45
+ "assay_organism": "TEXT", "confidence_score": "INTEGER",
46
+ "doc_id": "INTEGER", "activity_id": "INTEGER", "standard_type": "TEXT",
47
+ "standard_relation": "TEXT", "standard_value": "REAL",
48
+ "standard_units": "TEXT", "target_type": "TEXT", "organism": "TEXT",
49
+ "journal": "TEXT", "year": "INTEGER", "mec_id": "INTEGER",
50
+ "action_type": "TEXT", "drugind_id": "INTEGER", "mesh_heading": "TEXT",
51
+ "max_phase_for_ind": "REAL", "component_id": "INTEGER",
52
+ "accession": "TEXT", "protein_class_id": "INTEGER", "parent_id": "INTEGER",
53
+ }
54
+
55
+ DECOY_DOC_ID = 9_999_999_001
56
+ DECOY_PARENT = 9_999_999_002
57
+ DECOY_TEXT = "ZZZ_AOB_DECOY"
58
+
59
+
60
+ def _sha(payload: Any) -> str:
61
+ return hashlib.sha256(
62
+ json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()
63
+ ).hexdigest()
64
+
65
+
66
+ def _one(con, sql, args=()):
67
+ r = con.execute(sql, args).fetchone()
68
+ return r[0] if r else None
69
+
70
+
71
+ def _mk_slice() -> sqlite3.Connection:
72
+ con = sqlite3.connect(":memory:")
73
+ for table, cols in SLICE_COLUMNS.items():
74
+ defs = ", ".join(f"{c} {COL_TYPES[c]}" for c in cols)
75
+ con.execute(f"CREATE TABLE {table} ({defs})")
76
+ return con
77
+
78
+
79
+ def _copy(src, dst, table: str, where: str, args: tuple[Any, ...] = ()) -> int:
80
+ cols = SLICE_COLUMNS[table]
81
+ rows = src.execute(
82
+ f"SELECT {', '.join(cols)} FROM {table} WHERE {where}",
83
+ args).fetchall()
84
+ marks = ",".join("?" * len(cols))
85
+ dst.executemany(
86
+ f"INSERT INTO {table} ({', '.join(cols)}) VALUES ({marks})", rows)
87
+ return len(rows)
88
+
89
+
90
+ def _copy_in_chunks(src, dst, table: str, col: str,
91
+ ids: list[Any]) -> int:
92
+ """IN-list copy chunked below SQLite's variable limit."""
93
+ total = 0
94
+ for i in range(0, len(ids), 400):
95
+ chunk = ids[i:i + 400]
96
+ marks = ",".join("?" * len(chunk))
97
+ total += _copy(src, dst, table, f"{col} IN ({marks})", tuple(chunk))
98
+ return total
99
+
100
+
101
+ def _copy_molecules_for_activities(src, dst) -> None:
102
+ mols = [r[0] for r in dst.execute(
103
+ "SELECT DISTINCT molregno FROM activities WHERE molregno "
104
+ "IS NOT NULL")]
105
+ _copy_in_chunks(src, dst, "molecule_dictionary", "molregno", mols)
106
+ _copy_in_chunks(src, dst, "molecule_hierarchy", "molregno", mols)
107
+
108
+
109
+ def _fingerprint(con) -> str:
110
+ parts = []
111
+ for table in sorted(SLICE_COLUMNS):
112
+ n = con.execute(f"SELECT count(*) FROM {table}").fetchone()[0]
113
+ parts.append(f"{table}:{n}")
114
+ return _sha("|".join(parts))
115
+
116
+
117
+ def _unique_support_activity(slice_con, base_where: str,
118
+ args: tuple[Any, ...]) -> int | None:
119
+ """activity_id whose molecule has exactly one qualifying activity row
120
+ under ``base_where`` (mutating it provably removes that molecule)."""
121
+ row = slice_con.execute(
122
+ "SELECT activity_id FROM activities WHERE activity_id IN ("
123
+ " SELECT MIN(activity_id) FROM activities "
124
+ " WHERE " + base_where + " AND molregno IS NOT NULL "
125
+ " GROUP BY molregno HAVING count(*) = 1) "
126
+ "ORDER BY activity_id LIMIT 1", args).fetchone()
127
+ return row[0] if row else None
128
+
129
+
130
+ def _weakest_molecule_rows(slice_con, base_where: str,
131
+ args: tuple[Any, ...]) -> list[int]:
132
+ """All qualifying activity ids of the molecule with the fewest qualifying
133
+ rows — deleting/mutating all of them provably removes that molecule."""
134
+ row = slice_con.execute(
135
+ "SELECT molregno, count(*) c FROM activities "
136
+ "WHERE " + base_where + " AND molregno IS NOT NULL "
137
+ "GROUP BY molregno ORDER BY c, molregno LIMIT 1", args).fetchone()
138
+ if row is None:
139
+ return []
140
+ return [r[0] for r in slice_con.execute(
141
+ "SELECT activity_id FROM activities WHERE " + base_where +
142
+ " AND molregno = ? ORDER BY activity_id", args + (row[0],))]
143
+
144
+
145
+ def _delete_weakest_assay_support(slice_con, base_where: str,
146
+ args: tuple[Any, ...]) -> dict | None:
147
+ """Assay-set answers: delete all qualifying rows of the assay with the
148
+ fewest qualifying rows (drops that assay from the answer)."""
149
+ row = slice_con.execute(
150
+ "SELECT assay_id, count(*) c FROM activities "
151
+ "WHERE " + base_where + " AND molregno IS NOT NULL "
152
+ "GROUP BY assay_id ORDER BY c, assay_id LIMIT 1", args).fetchone()
153
+ if row is None:
154
+ return None
155
+ ids = [r[0] for r in slice_con.execute(
156
+ "SELECT activity_id FROM activities WHERE " + base_where +
157
+ " AND assay_id = ?", args + (row[0],))]
158
+ marks = ",".join("?" * len(ids))
159
+ slice_con.execute(f"DELETE FROM activities WHERE activity_id IN "
160
+ f"({marks})", tuple(ids))
161
+ return {"op": "delete_weakest_assay_rows", "assay_id": row[0],
162
+ "n_rows": len(ids)}
163
+
164
+
165
+ def _tid_of(con, chembl_id):
166
+ return _one(con, "SELECT tid FROM target_dictionary WHERE chembl_id = ?",
167
+ (chembl_id,))
168
+
169
+
170
+ def _molregno(con, chembl_id):
171
+ return _one(con, "SELECT molregno FROM molecule_dictionary "
172
+ "WHERE chembl_id = ?", (chembl_id,))
173
+
174
+
175
+ def _assay_id(con, chembl_id):
176
+ return _one(con, "SELECT assay_id FROM assays WHERE chembl_id = ?",
177
+ (chembl_id,))
178
+
179
+
180
+ def _control_target(src, tid: int) -> int | None:
181
+ return _one(src, "SELECT tid FROM assays WHERE tid IS NOT NULL "
182
+ "AND tid != ? GROUP BY tid "
183
+ "HAVING count(*) BETWEEN 5 AND 500 "
184
+ "ORDER BY tid LIMIT 1", (tid,))
185
+
186
+
187
+ def _scope_target_with_control(src, slc, tid: int, control_tid: int):
188
+ _copy(src, slc, "target_dictionary", "tid IN (?, ?)", (tid, control_tid))
189
+ _copy(src, slc, "assays", "tid IN (?, ?)", (tid, control_tid))
190
+ aids = [r[0] for r in slc.execute("SELECT assay_id FROM assays")]
191
+ _copy_in_chunks(src, slc, "activities", "assay_id", aids)
192
+ _copy_molecules_for_activities(src, slc)
193
+ dids = [r[0] for r in slc.execute(
194
+ "SELECT DISTINCT doc_id FROM assays WHERE doc_id IS NOT NULL")]
195
+ _copy_in_chunks(src, slc, "docs", "doc_id", dids)
196
+
197
+
198
+ def _slice_parent(src, params, rng):
199
+ parent = _molregno(src, params["parent_chembl_id"])
200
+ if parent is None:
201
+ return None
202
+ ctl = _one(src, "SELECT parent_molregno FROM molecule_hierarchy "
203
+ "WHERE parent_molregno != ? GROUP BY parent_molregno "
204
+ "HAVING count(*) >= 3 ORDER BY parent_molregno LIMIT 1",
205
+ (parent,))
206
+ if ctl is None:
207
+ return None
208
+ slc = _mk_slice()
209
+ _copy(src, slc, "molecule_hierarchy", "parent_molregno IN (?, ?)",
210
+ (parent, ctl))
211
+ mols = {r[0] for r in slc.execute(
212
+ "SELECT molregno FROM molecule_hierarchy")}
213
+ mols |= {parent, ctl}
214
+ _copy_in_chunks(src, slc, "molecule_dictionary", "molregno",
215
+ sorted(mols))
216
+
217
+ def mutate(s):
218
+ child = _one(s, "SELECT molregno FROM molecule_hierarchy "
219
+ "WHERE parent_molregno = ? AND molregno != ? "
220
+ "ORDER BY molregno LIMIT 1", (parent, parent))
221
+ if child is None:
222
+ return None
223
+ s.execute("UPDATE molecule_hierarchy SET parent_molregno = ? "
224
+ "WHERE molregno = ?", (DECOY_PARENT, child))
225
+ return {"op": "reparent_child", "molregno": child}
226
+
227
+ def control(s):
228
+ return s.execute("SELECT count(*) FROM molecule_hierarchy "
229
+ "WHERE parent_molregno = ?", (ctl,)).fetchone()[0]
230
+
231
+ return slc, mutate, control
232
+
233
+
234
+ def _slice_molecule(src, params, rng):
235
+ mol = _molregno(src, params["molecule_chembl_id"])
236
+ if mol is None:
237
+ return None
238
+ ctl = _one(src, "SELECT molregno FROM activities WHERE molregno "
239
+ "IS NOT NULL AND molregno != ? GROUP BY molregno "
240
+ "HAVING count(*) BETWEEN 5 AND 200 "
241
+ "ORDER BY molregno LIMIT 1", (mol,))
242
+ if ctl is None:
243
+ return None
244
+ slc = _mk_slice()
245
+ _copy(src, slc, "activities", "molregno IN (?, ?)", (mol, ctl))
246
+ aids = [r[0] for r in slc.execute(
247
+ "SELECT DISTINCT assay_id FROM activities")]
248
+ _copy_in_chunks(src, slc, "assays", "assay_id", aids)
249
+ _copy_molecules_for_activities(src, slc)
250
+ tids = [r[0] for r in slc.execute(
251
+ "SELECT DISTINCT tid FROM assays WHERE tid IS NOT NULL")]
252
+ _copy_in_chunks(src, slc, "target_dictionary", "tid", tids)
253
+ st = params["standard_type"]
254
+ base = ("standard_type = ? AND standard_relation = '=' "
255
+ "AND standard_units = 'nM' AND standard_value IS NOT NULL "
256
+ "AND molregno = ?")
257
+
258
+ def mutate(s):
259
+ row = s.execute(
260
+ "SELECT MIN(activity_id), assay_id FROM activities "
261
+ "WHERE " + base + " GROUP BY assay_id HAVING count(*) = 1 "
262
+ "ORDER BY assay_id LIMIT 1", (st, mol)).fetchone()
263
+ if row is not None:
264
+ s.execute("DELETE FROM activities WHERE activity_id = ?",
265
+ (row[0],))
266
+ return {"op": "delete_unique_support_row",
267
+ "activity_id": row[0], "assay_id": row[1]}
268
+ return _delete_weakest_assay_support(s, base, (st, mol))
269
+
270
+ def control(s):
271
+ return s.execute(
272
+ "SELECT count(*) FROM activities WHERE molregno = ?",
273
+ (ctl,)).fetchone()[0]
274
+
275
+ return slc, mutate, control
276
+
277
+
278
+ def _slice_target(src, params, rng):
279
+ tid = _tid_of(src, params["target_chembl_id"])
280
+ if tid is None:
281
+ return None
282
+ ctl = _control_target(src, tid)
283
+ if ctl is None:
284
+ return None
285
+ slc = _mk_slice()
286
+ _scope_target_with_control(src, slc, tid, ctl)
287
+ return slc, tid, ctl
288
+
289
+
290
+ def _slice_target_binding(src, params, rng):
291
+ built = _slice_target(src, params, rng)
292
+ if built is None:
293
+ return None
294
+ slc, tid, ctl = built
295
+ st, thr = params["standard_type"], params["threshold"]
296
+ base = ("standard_type = ? AND standard_relation = '=' "
297
+ "AND standard_units = 'nM' AND standard_value IS NOT NULL "
298
+ "AND standard_value <= ? AND assay_id IN ("
299
+ " SELECT assay_id FROM assays WHERE tid = ? "
300
+ " AND assay_type = 'B' AND confidence_score >= 8)")
301
+
302
+ def mutate(s):
303
+ aid = _unique_support_activity(s, base, (st, thr, tid))
304
+ if aid is None:
305
+ ids = _weakest_molecule_rows(s, base, (st, thr, tid))
306
+ if not ids:
307
+ return None
308
+ marks = ",".join("?" * len(ids))
309
+ s.execute("UPDATE activities SET standard_value = "
310
+ "standard_value * 1000000.0 WHERE activity_id IN ("
311
+ + marks + ")", tuple(ids))
312
+ return {"op": "rescale_weakest_molecule_rows_x1e6",
313
+ "n_rows": len(ids)}
314
+ s.execute("UPDATE activities SET standard_value = "
315
+ "standard_value * 1000000.0 WHERE activity_id = ?",
316
+ (aid,))
317
+ return {"op": "rescale_value_x1e6", "activity_id": aid}
318
+
319
+ def control(s):
320
+ return s.execute(
321
+ "SELECT count(*) FROM activities WHERE assay_id IN ("
322
+ " SELECT assay_id FROM assays WHERE tid = ?)",
323
+ (ctl,)).fetchone()[0]
324
+
325
+ return slc, mutate, control
326
+
327
+
328
+ def _slice_assay_context(src, params, rng):
329
+ built = _slice_target(src, params, rng)
330
+ if built is None:
331
+ return None
332
+ slc, tid, ctl = built
333
+ org = params["assay_organism"]
334
+
335
+ def mutate(s):
336
+ aid = _one(s, "SELECT assay_id FROM assays WHERE tid = ? "
337
+ "AND assay_type = 'B' AND assay_organism = ? "
338
+ "ORDER BY assay_id LIMIT 1", (tid, org))
339
+ if aid is None:
340
+ return None
341
+ s.execute("UPDATE assays SET assay_organism = ? WHERE assay_id = ?",
342
+ (DECOY_TEXT, aid))
343
+ return {"op": "reassign_organism", "assay_id": aid}
344
+
345
+ def control(s):
346
+ return s.execute("SELECT count(*) FROM assays WHERE tid = ?",
347
+ (ctl,)).fetchone()[0]
348
+
349
+ return slc, mutate, control
350
+
351
+
352
+ def _slice_assay(src, params, rng):
353
+ aid = _assay_id(src, params["assay_chembl_id"])
354
+ if aid is None:
355
+ return None
356
+ ctl = _one(src, "SELECT assay_id FROM activities WHERE assay_id != ? "
357
+ "GROUP BY assay_id HAVING count(*) BETWEEN 5 AND 200 "
358
+ "ORDER BY assay_id LIMIT 1", (aid,))
359
+ if ctl is None:
360
+ return None
361
+ slc = _mk_slice()
362
+ _copy(src, slc, "assays", "assay_id IN (?, ?)", (aid, ctl))
363
+ _copy(src, slc, "activities", "assay_id IN (?, ?)", (aid, ctl))
364
+ _copy_molecules_for_activities(src, slc)
365
+ tids = [r[0] for r in slc.execute(
366
+ "SELECT DISTINCT tid FROM assays WHERE tid IS NOT NULL")]
367
+ _copy_in_chunks(src, slc, "target_dictionary", "tid", tids)
368
+ return slc, aid, ctl
369
+
370
+
371
+ def _slice_measurement(src, params, rng):
372
+ built = _slice_assay(src, params, rng)
373
+ if built is None:
374
+ return None
375
+ slc, aid, ctl = built
376
+ st = params["standard_type"]
377
+ thr = params.get("threshold")
378
+ base = ("standard_type = ? AND standard_relation = '=' "
379
+ "AND standard_units = 'nM' AND standard_value IS NOT NULL "
380
+ "AND assay_id = ?")
381
+ args: tuple[Any, ...] = (st, aid)
382
+ if thr is not None:
383
+ base += " AND standard_value <= ?"
384
+ args = (st, aid, thr)
385
+
386
+ def mutate(s):
387
+ x = _unique_support_activity(s, base, args)
388
+ if x is None:
389
+ ids = _weakest_molecule_rows(s, base, args)
390
+ if not ids:
391
+ return None
392
+ marks = ",".join("?" * len(ids))
393
+ s.execute("UPDATE activities SET standard_relation = '<' "
394
+ "WHERE activity_id IN (" + marks + ")", tuple(ids))
395
+ return {"op": "flip_weakest_molecule_relations",
396
+ "n_rows": len(ids)}
397
+ s.execute("UPDATE activities SET standard_relation = '<' "
398
+ "WHERE activity_id = ?", (x,))
399
+ return {"op": "flip_relation_to_lt", "activity_id": x}
400
+
401
+ def control(s):
402
+ return s.execute(
403
+ "SELECT count(*) FROM activities WHERE assay_id = ?",
404
+ (ctl,)).fetchone()[0]
405
+
406
+ return slc, mutate, control
407
+
408
+
409
+ def _slice_target_class(src, params, rng):
410
+ slc = _mk_slice()
411
+ _copy(src, slc, "protein_classification", "1=1")
412
+ _copy(src, slc, "component_class", "1=1")
413
+ _copy(src, slc, "target_components", "1=1")
414
+ _copy(src, slc, "target_dictionary",
415
+ "target_type = 'SINGLE PROTEIN' AND organism = 'Homo sapiens'")
416
+ pcid = params["protein_class_id"]
417
+ children: dict[int, list[int]] = {}
418
+ for c, p in slc.execute("SELECT protein_class_id, parent_id FROM "
419
+ "protein_classification"):
420
+ if p is not None:
421
+ children.setdefault(p, []).append(c)
422
+
423
+ def subtree(root):
424
+ seen, stack = set(), [root]
425
+ while stack:
426
+ n = stack.pop()
427
+ if n in seen:
428
+ continue
429
+ seen.add(n)
430
+ stack.extend(children.get(n, ()))
431
+ return seen
432
+
433
+ sub = subtree(pcid)
434
+ ctl_class = _one(src, "SELECT protein_class_id FROM "
435
+ "protein_classification WHERE class_level = 2 "
436
+ "AND protein_class_id != ? ORDER BY "
437
+ "protein_class_id LIMIT 1", (pcid,))
438
+ if ctl_class is None:
439
+ slc.close()
440
+ return None
441
+ forbidden = sub | subtree(ctl_class)
442
+ outside = [c for (c,) in slc.execute(
443
+ "SELECT protein_class_id FROM protein_classification")
444
+ if c not in forbidden]
445
+ if not outside:
446
+ slc.close()
447
+ return None
448
+ decoy_class = sorted(outside)[len(outside) // 2]
449
+
450
+ def mutate(s):
451
+ row = s.execute(
452
+ "SELECT MIN(cc.component_id), tc.tid FROM component_class cc "
453
+ "JOIN target_components tc "
454
+ " ON tc.component_id = cc.component_id "
455
+ "JOIN target_dictionary td ON td.tid = tc.tid "
456
+ "WHERE cc.protein_class_id IN ("
457
+ + ",".join(str(x) for x in sorted(sub)) + ") "
458
+ "AND td.target_type = 'SINGLE PROTEIN' "
459
+ "AND td.organism = 'Homo sapiens' "
460
+ "GROUP BY tc.tid "
461
+ "HAVING count(DISTINCT cc.component_id) = 1 "
462
+ "ORDER BY tc.tid LIMIT 1").fetchone()
463
+ if row is None:
464
+ return None
465
+ comp, _t = row
466
+ s.execute("UPDATE component_class SET protein_class_id = ? "
467
+ "WHERE component_id = ? AND protein_class_id IN ("
468
+ + ",".join(str(x) for x in sorted(sub)) + ")",
469
+ (decoy_class, comp))
470
+ return {"op": "relabel_component_class", "component_id": comp,
471
+ "to_class": decoy_class}
472
+
473
+ def control(s):
474
+ return len(pyclean.answer_org_target_class_members(
475
+ s, {"protein_class_id": ctl_class}))
476
+
477
+ return slc, mutate, control
478
+
479
+
480
+ def _slice_journal(src, params, rng):
481
+ j, y = params["journal"], params.get("year")
482
+ cj = _one(src, "SELECT DISTINCT journal FROM docs WHERE journal IS NOT "
483
+ "NULL AND journal != ? AND year = ? "
484
+ "ORDER BY journal LIMIT 1", (j, y))
485
+ if cj is None:
486
+ cj = _one(src, "SELECT DISTINCT journal FROM docs WHERE journal "
487
+ "IS NOT NULL AND journal != ? ORDER BY journal "
488
+ "LIMIT 1", (j,))
489
+ if cj is None:
490
+ return None
491
+ slc = _mk_slice()
492
+ _copy(src, slc, "docs", "journal IN (?, ?) AND year = ?", (j, cj, y))
493
+ dids = [r[0] for r in slc.execute("SELECT doc_id FROM docs")]
494
+ if not dids:
495
+ slc.close()
496
+ return None
497
+ _copy_in_chunks(src, slc, "assays", "doc_id", dids)
498
+ aids = [r[0] for r in slc.execute("SELECT assay_id FROM assays")]
499
+ _copy_in_chunks(src, slc, "activities", "assay_id", aids)
500
+ _copy_molecules_for_activities(src, slc)
501
+ tids = [r[0] for r in slc.execute(
502
+ "SELECT DISTINCT tid FROM assays WHERE tid IS NOT NULL")]
503
+ _copy_in_chunks(src, slc, "target_dictionary", "tid", tids)
504
+ base = ("standard_relation = '=' AND standard_units = 'nM' "
505
+ "AND standard_type IN ('IC50','Ki','EC50') "
506
+ "AND standard_value IS NOT NULL AND molregno IS NOT NULL "
507
+ "AND assay_id IN (SELECT assay_id FROM assays WHERE doc_id IN ("
508
+ " SELECT doc_id FROM docs WHERE journal = ? AND year = ?))")
509
+
510
+ def mutate(s):
511
+ ids = _weakest_molecule_rows(s, base, (j, y))
512
+ if not ids:
513
+ return None
514
+ marks = ",".join("?" * len(ids))
515
+ aids = [r[0] for r in s.execute(
516
+ f"SELECT DISTINCT assay_id FROM activities WHERE "
517
+ f"activity_id IN ({marks})", tuple(ids))]
518
+ s.execute("INSERT INTO docs (doc_id, journal, year) "
519
+ "VALUES (?, ?, ?)", (DECOY_DOC_ID, DECOY_TEXT, 1900))
520
+ amarks = ",".join("?" * len(aids))
521
+ s.execute(f"UPDATE assays SET doc_id = ? WHERE assay_id IN "
522
+ f"({amarks})", (DECOY_DOC_ID, *aids))
523
+ return {"op": "relink_documents_to_decoy", "assay_ids": aids,
524
+ "molecule_rows": len(ids)}
525
+
526
+ def control(s):
527
+ return len(pyclean.answer_org_journal_year_provenance(
528
+ s, {"journal": cj, "year": y}))
529
+
530
+ return slc, mutate, control
531
+
532
+
533
+ def _slice_mechanism(src, params, rng):
534
+ tid = _tid_of(src, params["target_chembl_id"])
535
+ if tid is None:
536
+ return None
537
+ ctl = _one(src, "SELECT DISTINCT tid FROM drug_mechanism WHERE tid != ? "
538
+ "ORDER BY tid LIMIT 1", (tid,))
539
+ if ctl is None:
540
+ return None
541
+ slc = _mk_slice()
542
+ _copy(src, slc, "drug_mechanism", "tid IN (?, ?)", (tid, ctl))
543
+ _copy(src, slc, "target_dictionary", "tid IN (?, ?)", (tid, ctl))
544
+ mols = [r[0] for r in slc.execute(
545
+ "SELECT DISTINCT molregno FROM drug_mechanism")]
546
+ if mols:
547
+ _copy_in_chunks(src, slc, "molecule_hierarchy", "molregno", mols)
548
+ parents = {r[0] for r in slc.execute(
549
+ "SELECT DISTINCT parent_molregno FROM molecule_hierarchy "
550
+ "WHERE parent_molregno IS NOT NULL")}
551
+ allm = sorted(set(mols) | parents)
552
+ _copy_in_chunks(src, slc, "molecule_dictionary", "molregno", allm)
553
+ at = params["action_type"]
554
+
555
+ def mutate(s):
556
+ row = s.execute(
557
+ "SELECT MIN(dm.mec_id) FROM drug_mechanism dm "
558
+ "JOIN molecule_hierarchy h ON h.molregno = dm.molregno "
559
+ "WHERE dm.tid = ? AND dm.action_type = ? "
560
+ "GROUP BY h.parent_molregno HAVING count(*) = 1 "
561
+ "ORDER BY dm.mec_id LIMIT 1", (tid, at)).fetchone()
562
+ if row is None:
563
+ return None
564
+ s.execute("UPDATE drug_mechanism SET action_type = ? "
565
+ "WHERE mec_id = ?", (DECOY_TEXT, row[0]))
566
+ return {"op": "retype_action", "mec_id": row[0]}
567
+
568
+ def control(s):
569
+ return s.execute(
570
+ "SELECT count(*) FROM drug_mechanism WHERE tid = ?",
571
+ (ctl,)).fetchone()[0]
572
+
573
+ return slc, mutate, control
574
+
575
+
576
+ def _slice_indication(src, params, rng):
577
+ mesh = params["mesh_heading"]
578
+ ctl = _one(src, "SELECT DISTINCT mesh_heading FROM drug_indication "
579
+ "WHERE mesh_heading IS NOT NULL AND mesh_heading != ? "
580
+ "ORDER BY mesh_heading LIMIT 1", (mesh,))
581
+ if ctl is None:
582
+ return None
583
+ slc = _mk_slice()
584
+ _copy(src, slc, "drug_indication", "mesh_heading IN (?, ?)", (mesh, ctl))
585
+ mols = [r[0] for r in slc.execute(
586
+ "SELECT DISTINCT molregno FROM drug_indication")]
587
+ if mols:
588
+ _copy_in_chunks(src, slc, "molecule_hierarchy", "molregno", mols)
589
+ parents = {r[0] for r in slc.execute(
590
+ "SELECT DISTINCT parent_molregno FROM molecule_hierarchy "
591
+ "WHERE parent_molregno IS NOT NULL")}
592
+ allm = sorted(set(mols) | parents)
593
+ _copy_in_chunks(src, slc, "molecule_dictionary", "molregno", allm)
594
+
595
+ def mutate(s):
596
+ row = s.execute(
597
+ "SELECT MIN(d.drugind_id) FROM drug_indication d "
598
+ "JOIN molecule_hierarchy h ON h.molregno = d.molregno "
599
+ "WHERE d.mesh_heading = ? AND d.max_phase_for_ind >= 2 "
600
+ "GROUP BY h.parent_molregno HAVING count(*) = 1 "
601
+ "ORDER BY d.drugind_id LIMIT 1", (mesh,)).fetchone()
602
+ if row is None:
603
+ return None
604
+ s.execute("UPDATE drug_indication SET mesh_heading = ? "
605
+ "WHERE drugind_id = ?", (DECOY_TEXT, row[0]))
606
+ return {"op": "rekey_mesh_heading", "drugind_id": row[0]}
607
+
608
+ def control(s):
609
+ return s.execute(
610
+ "SELECT count(*) FROM drug_indication WHERE mesh_heading = ?",
611
+ (ctl,)).fetchone()[0]
612
+
613
+ return slc, mutate, control
614
+
615
+
616
+ def _slice_uniprot(src, params, rng):
617
+ acc = params["accession"]
618
+ ctl = _one(src, "SELECT DISTINCT accession FROM component_sequences "
619
+ "WHERE accession IS NOT NULL AND accession != ? "
620
+ "ORDER BY accession LIMIT 1", (acc,))
621
+ if ctl is None:
622
+ return None
623
+ slc = _mk_slice()
624
+ _copy(src, slc, "component_sequences", "accession IN (?, ?)", (acc, ctl))
625
+ comps = [r[0] for r in slc.execute(
626
+ "SELECT component_id FROM component_sequences")]
627
+ _copy_in_chunks(src, slc, "target_components", "component_id", comps)
628
+ tids = [r[0] for r in slc.execute(
629
+ "SELECT DISTINCT tid FROM target_components")]
630
+ _copy_in_chunks(src, slc, "target_dictionary", "tid", tids)
631
+
632
+ def mutate(s):
633
+ row = s.execute(
634
+ "SELECT tc.tid, MIN(tc.component_id) FROM target_components tc "
635
+ "JOIN target_dictionary td ON td.tid = tc.tid "
636
+ "WHERE tc.component_id IN ("
637
+ " SELECT component_id FROM component_sequences "
638
+ " WHERE accession = ?) "
639
+ "AND td.target_type = 'SINGLE PROTEIN' "
640
+ "AND td.organism = 'Homo sapiens' "
641
+ "GROUP BY tc.tid HAVING count(*) = 1 "
642
+ "ORDER BY tc.tid LIMIT 1", (acc,)).fetchone()
643
+ if row is None:
644
+ return None
645
+ s.execute("DELETE FROM target_components WHERE tid = ? "
646
+ "AND component_id = ?", (row[0], row[1]))
647
+ return {"op": "rewire_component", "tid": row[0],
648
+ "component_id": row[1]}
649
+
650
+ def control(s):
651
+ return s.execute(
652
+ "SELECT count(*) FROM target_components WHERE component_id IN ("
653
+ " SELECT component_id FROM component_sequences "
654
+ " WHERE accession = ?)", (ctl,)).fetchone()[0]
655
+
656
+ return slc, mutate, control
657
+
658
+
659
+ def _slice_multihop(src, params, rng):
660
+ tid = _tid_of(src, params["target_chembl_id"])
661
+ if tid is None:
662
+ return None
663
+ slc = _mk_slice()
664
+ _copy(src, slc, "target_dictionary", "tid = ?", (tid,))
665
+ _copy(src, slc, "assays", "tid = ?", (tid,))
666
+ aids = [r[0] for r in slc.execute("SELECT assay_id FROM assays")]
667
+ _copy_in_chunks(src, slc, "activities", "assay_id", aids)
668
+ _copy_molecules_for_activities(src, slc)
669
+ dids = [r[0] for r in slc.execute(
670
+ "SELECT DISTINCT doc_id FROM assays WHERE doc_id IS NOT NULL")]
671
+ _copy_in_chunks(src, slc, "docs", "doc_id", dids)
672
+ j = params["journal"]
673
+ cj = _one(slc, "SELECT DISTINCT journal FROM docs WHERE journal IS NOT "
674
+ "NULL AND journal != ? ORDER BY journal LIMIT 1", (j,))
675
+ if cj is None:
676
+ cj = _one(src, "SELECT DISTINCT journal FROM docs WHERE journal "
677
+ "IS NOT NULL AND journal != ? ORDER BY journal "
678
+ "LIMIT 1", (j,))
679
+ if cj is None:
680
+ slc.close()
681
+ return None
682
+ base = ("standard_type = 'IC50' AND standard_relation = '=' "
683
+ "AND standard_units = 'nM' AND standard_value IS NOT NULL "
684
+ "AND molregno IS NOT NULL AND assay_id IN ("
685
+ " SELECT assay_id FROM assays WHERE tid = ? "
686
+ " AND assay_type = 'B' AND confidence_score >= 8 "
687
+ " AND doc_id IN ("
688
+ " SELECT doc_id FROM docs WHERE journal = ?))")
689
+
690
+ def mutate(s):
691
+ ids = _weakest_molecule_rows(s, base, (tid, j))
692
+ if not ids:
693
+ return None
694
+ marks = ",".join("?" * len(ids))
695
+ aids = [r[0] for r in s.execute(
696
+ f"SELECT DISTINCT assay_id FROM activities WHERE "
697
+ f"activity_id IN ({marks})", tuple(ids))]
698
+ s.execute("INSERT INTO docs (doc_id, journal, year) "
699
+ "VALUES (?, ?, ?)", (DECOY_DOC_ID, DECOY_TEXT, 1900))
700
+ amarks = ",".join("?" * len(aids))
701
+ s.execute(f"UPDATE assays SET doc_id = ? WHERE assay_id IN "
702
+ f"({amarks})", (DECOY_DOC_ID, *aids))
703
+ return {"op": "relink_documents_to_decoy", "assay_ids": aids,
704
+ "molecule_rows": len(ids)}
705
+
706
+ def control(s):
707
+ return len(pyclean.answer_app_multihop_target_journal(
708
+ s, {"target_chembl_id": params["target_chembl_id"],
709
+ "journal": cj}))
710
+
711
+ return slc, mutate, control
712
+
713
+
714
+ def _slice_standardization(src, params, rng):
715
+ built = _slice_assay(src, params, rng)
716
+ if built is None:
717
+ return None
718
+ slc, aid, ctl = built
719
+ st, thr = params["standard_type"], params["threshold"]
720
+ base = ("standard_type = ? AND standard_relation = '=' "
721
+ "AND standard_units = 'nM' AND standard_value IS NOT NULL "
722
+ "AND assay_id = ? AND standard_value <= ?")
723
+
724
+ def mutate(s):
725
+ x = _unique_support_activity(s, base, (st, aid, thr))
726
+ if x is None:
727
+ ids = _weakest_molecule_rows(s, base, (st, aid, thr))
728
+ if not ids:
729
+ return None
730
+ marks = ",".join("?" * len(ids))
731
+ s.execute("UPDATE activities SET standard_value = "
732
+ "standard_value * 1000000.0 WHERE activity_id IN ("
733
+ + marks + ")", tuple(ids))
734
+ return {"op": "rescale_weakest_molecule_rows_x1e6",
735
+ "n_rows": len(ids)}
736
+ s.execute("UPDATE activities SET standard_value = "
737
+ "standard_value * 1000000.0 WHERE activity_id = ?", (x,))
738
+ return {"op": "rescale_value_x1e6", "activity_id": x}
739
+
740
+ def control(s):
741
+ return s.execute(
742
+ "SELECT count(*) FROM activities WHERE assay_id = ?",
743
+ (ctl,)).fetchone()[0]
744
+
745
+ return slc, mutate, control
746
+
747
+
748
+ SLICE_BUILDERS: dict[str, Callable] = {
749
+ "org_parent_salt_members": _slice_parent,
750
+ "app_molecule_assays_of_type": _slice_molecule,
751
+ "app_target_binding_set": _slice_target_binding,
752
+ "org_assay_context_organism": _slice_assay_context,
753
+ "app_measurement_exact_set": _slice_measurement,
754
+ "app_unit_normalized_potency": _slice_measurement,
755
+ "rep_relation_flip_repair": _slice_measurement,
756
+ "rep_standardization_table": _slice_standardization,
757
+ "org_target_class_members": _slice_target_class,
758
+ "org_journal_year_provenance": _slice_journal,
759
+ "app_mechanism_action_type": _slice_mechanism,
760
+ "app_indication_mesh": _slice_indication,
761
+ "org_uniprot_target_map": _slice_uniprot,
762
+ "app_multihop_target_journal": _slice_multihop,
763
+ }
764
+
765
+
766
+ def certify(con_src, family_id: str, params: dict[str, Any],
767
+ expected: tuple[str, ...], witness_kind: str,
768
+ seed: int) -> dict[str, Any]:
769
+ """Build slice, run governed/perturbed/control probes."""
770
+ rng = random.Random(seed)
771
+ answer_fn = pyclean.ANSWER_BY_FAMILY[family_id]
772
+ builder = SLICE_BUILDERS[family_id]
773
+ try:
774
+ built = builder(con_src, params, rng)
775
+ except Exception as exc:
776
+ return {"ok": False, "reason": f"slice build failed: {exc}",
777
+ "kind": witness_kind}
778
+ if built is None:
779
+ return {"ok": False, "reason": "no slice scope", "kind": witness_kind}
780
+ slc, mutate, control = built
781
+ expected_set = frozenset(expected)
782
+ try:
783
+ governed_before = answer_fn(slc, params)
784
+ if governed_before != expected_set:
785
+ return {"ok": False,
786
+ "reason": "slice does not reproduce reference answer",
787
+ "kind": witness_kind,
788
+ "governed_slice": len(governed_before),
789
+ "governed_full": len(expected_set)}
790
+ control_before = control(slc)
791
+ fp = _fingerprint(slc)
792
+ mutation = mutate(slc)
793
+ if mutation is None:
794
+ return {"ok": False, "reason": "no mutation target found",
795
+ "kind": witness_kind}
796
+ governed_after = answer_fn(slc, params)
797
+ control_after = control(slc)
798
+ finally:
799
+ slc.close()
800
+ ok = (governed_after != expected_set) and (control_after == control_before)
801
+ return {
802
+ "ok": ok,
803
+ "kind": witness_kind,
804
+ "mutation": mutation,
805
+ "governed_correct_count": len(expected_set),
806
+ "governed_perturbed_count": len(governed_after),
807
+ "control_before_sha256": _sha(repr(control_before)),
808
+ "control_after_sha256": _sha(repr(control_after)),
809
+ "control_unchanged": control_after == control_before,
810
+ "slice_fingerprint": fp,
811
+ "reason": "" if ok else "perturbation did not flip governed probe "
812
+ "or control changed",
813
+ }
core_worlds/src/benchmark/plugins/verifier/l15/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """L15 Reactome lane plugins (release-98 pinned snapshot)."""
core_worlds/src/benchmark/plugins/verifier/l15/verifier.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L15 native verifier: recompute reference answers from the pinned Reactome
2
+ store and gate qualification.
3
+
4
+ Truth discipline: answers are recomputed per call from ``reactome.db`` (itself
5
+ a deterministic build over the pinned files, sha256-checked). For B+M families
6
+ the BioPAX and mapping paths must agree or the task is rejected
7
+ (``PROFILE_UNSUPPORTED:path_disagree``). No LLM output is gold.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from benchmark.plugins.source.l15.kb import L15KB
16
+ import os
17
+ from benchmark.plugins.source.l15.plugin import STORE_DB
18
+ from benchmark.plugins.task_family.l15.families import BY_ID
19
+ from benchmark.plugins.task_family.l15 import goals as G
20
+ from benchmark.schema.plugin_protocols import (
21
+ GroundedTask, NativeVerdict, ProofOrCounterexample, SemanticWitness,
22
+ )
23
+
24
+
25
+ def _canon(payload: Any) -> str:
26
+ def norm(o: Any) -> Any:
27
+ if isinstance(o, dict):
28
+ return {k: norm(v) for k, v in o.items()}
29
+ if isinstance(o, (list, tuple)):
30
+ return sorted({json.dumps(x, sort_keys=True) for x in
31
+ (norm(i) for i in o)}) if all(
32
+ isinstance(i, str) for i in o) else [norm(i) for i in o]
33
+ return o
34
+ return json.dumps(norm(payload), sort_keys=True, separators=(",", ":"))
35
+
36
+
37
+ class ReactomeNativeVerifier:
38
+ def __init__(self, db_path: str | Path | None = None, *,
39
+ allow_m_only: bool = False) -> None:
40
+ self.kb = L15KB(db_path or os.environ.get("L15_STORE_DB") or STORE_DB)
41
+ self.allow_m_only = allow_m_only
42
+
43
+ def reference_submission(self, ast: dict[str, Any]) -> Any:
44
+ return G.KINDS[ast["kind"]].answer(self.kb, ast)
45
+
46
+ def _answer_size(self, ref: Any) -> int:
47
+ if "answer_ids" in ref:
48
+ return len(ref["answer_ids"])
49
+ if "pairs" in ref:
50
+ return len(ref["pairs"])
51
+ if "assignment" in ref:
52
+ return len(ref["assignment"])
53
+ return 0
54
+
55
+ def prove_exists(self, grounded_task: GroundedTask) -> ProofOrCounterexample:
56
+ ast = grounded_task.ast.ast
57
+ kind = ast["kind"]
58
+ spec = BY_ID[grounded_task.ast.family_id]
59
+ ev: dict[str, Any] = {"kind": kind, "store": str(self.kb.db_path),
60
+ "family_id": grounded_task.ast.family_id}
61
+ skip_agree = False
62
+ if not self.kb.has_biopax() and spec.truth_path.startswith("B"):
63
+ if self.allow_m_only and spec.truth_path == "B+M":
64
+ skip_agree = True
65
+ ev["differential_agree"] = "NOT_RUN:biopax_snapshot_unavailable"
66
+ else:
67
+ return ProofOrCounterexample(False, ev, "PROFILE_UNSUPPORTED:no_biopax_store")
68
+ try:
69
+ ref = self.reference_submission(ast)
70
+ except Exception as exc:
71
+ return ProofOrCounterexample(False, ev, f"PROFILE_UNSUPPORTED:{exc}"[:200])
72
+ size = self._answer_size(ref)
73
+ ev["answer_size"] = size
74
+ if size < spec.min_answer or size > spec.max_answer:
75
+ return ProofOrCounterexample(
76
+ False, ev, f"TRIVIAL:size_{size}_outside_[{spec.min_answer},{spec.max_answer}]")
77
+ if spec.truth_path == "B+M" and not skip_agree:
78
+ ops = G.KINDS[kind]
79
+ if ops.agree is not None:
80
+ try:
81
+ agree = ops.agree(self.kb, ast)
82
+ except Exception as exc:
83
+ return ProofOrCounterexample(
84
+ False, ev, f"NATIVE_ERROR:agree:{type(exc).__name__}"[:200])
85
+ ev["differential_agree"] = bool(agree)
86
+ if not agree:
87
+ return ProofOrCounterexample(
88
+ False, ev, "PROFILE_UNSUPPORTED:path_disagree")
89
+ if kind == "direction_repair":
90
+ if not self._repair_evidence_ok(ast):
91
+ return ProofOrCounterexample(
92
+ False, ev, "PROFILE_UNSUPPORTED:repair_evidence_missing")
93
+ ev["solvable"] = True
94
+ return ProofOrCounterexample(True, ev)
95
+
96
+ def _repair_evidence_ok(self, ast: dict[str, Any]) -> bool:
97
+ """direction_repair needs the swapped PE to carry a UniProt accession
98
+ that has a reaction-role row (m_reaction_roles, from the pinned
99
+ reactome_reaction_exporter.txt) for the reaction; otherwise the public
100
+ role evidence cannot determine the correct side."""
101
+ swapped = ast["swapped_pe"]
102
+ rows = self.kb._q(
103
+ """SELECT x.accession FROM b_xrefs x
104
+ JOIN b_reaction_sides s ON s.pe_uri = x.pe_uri
105
+ WHERE s.reaction=? AND x.db LIKE 'UniProt%'""",
106
+ (ast["reaction"],))
107
+ sides = G.reaction_sides(self.kb, ast["reaction"])
108
+ target_uri = None
109
+ for side in ("left", "right"):
110
+ for u in sides[side]:
111
+ if G._tail(u) == swapped:
112
+ target_uri = u
113
+ if target_uri is None:
114
+ return False
115
+ accs = {x["accession"] for x in self.kb.b_pe_xrefs(target_uri)
116
+ if x["db"].lower().startswith("uniprot")}
117
+ if not accs:
118
+ return False
119
+ for acc in accs:
120
+ r = self.kb._q(
121
+ "SELECT role FROM m_reaction_roles WHERE accession=? AND reaction_id=?",
122
+ (acc, ast["reaction"]))
123
+ if r:
124
+ return True
125
+ return False
126
+
127
+ def verify_terminal(self, task: GroundedTask, submitted_state_or_answer: Any) -> NativeVerdict:
128
+ ast = task.ast.ast
129
+ try:
130
+ ref = self.reference_submission(ast)
131
+ except Exception as exc:
132
+ return NativeVerdict(False, {"error": f"reference:{exc}"[:200]})
133
+ ok = _canon(submitted_state_or_answer) == _canon(ref)
134
+ return NativeVerdict(ok, {"match": ok})
135
+
136
+ def certify_semantic_relevance(self, task: GroundedTask) -> SemanticWitness:
137
+ ast = task.ast.ast
138
+ kind = ast["kind"]
139
+ base: dict[str, Any] = {"kind": kind, "family_id": task.ast.family_id}
140
+ try:
141
+ ref = self.reference_submission(ast)
142
+ wit = G.KINDS[kind].counter(self.kb, ast, ref)
143
+ except Exception as exc:
144
+ return SemanticWitness(False, dict(base, error=f"{type(exc).__name__}: {exc}"[:200]))
145
+ if wit is None:
146
+ return SemanticWitness(False, dict(base, error="no_counterfactual_found"))
147
+ return SemanticWitness(True, dict(base, **wit))
148
+
149
+ def mutation_submission(self, ast: dict[str, Any], reference: Any) -> Any:
150
+ return G.KINDS[ast["kind"]].mutate(self.kb, ast, reference)
core_worlds/src/benchmark/plugins/verifier/l16/__init__.py ADDED
File without changes
core_worlds/src/benchmark/plugins/verifier/l16/domain.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L16 evaluator-side domain: exact-set analytical tasks + artifact repair.
2
+
3
+ Mirrors the L04 domain semantics (reset/step/verify_terminal discrimination).
4
+ Never imports any ontology consumer; the reference answer lives evaluator-side
5
+ only. Repair tasks submit the corrected artifact, then the answer that must
6
+ equal the downstream result recomputed from the pinned store.
7
+
8
+ Action schema:
9
+ analytical/construction: {"type": "submit_answer", "answer": list[str]}
10
+ repair: {"type": "submit_artifact", "artifact": {...}} then
11
+ {"type": "submit_answer", "answer": list[str]}
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ from dataclasses import dataclass
18
+ from typing import Any
19
+
20
+ from autoontobench.contracts.models import GoalResult
21
+
22
+
23
+ class MalformedAction(ValueError):
24
+ pass
25
+
26
+
27
+ def _sha(payload: Any) -> str:
28
+ return hashlib.sha256(
29
+ json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class L16State:
34
+ task_id: str
35
+ query: dict[str, Any]
36
+ submitted_answer: tuple[str, ...] | None
37
+ submitted_artifact: dict[str, Any] | None
38
+ terminal: bool
39
+
40
+
41
+ class L16Domain:
42
+ """Exact-set terminal semantics for all L16 families."""
43
+
44
+ def reset(self, task_id: str, query: dict[str, Any]) -> L16State:
45
+ return L16State(task_id=task_id, query=query, submitted_answer=None,
46
+ submitted_artifact=None, terminal=False)
47
+
48
+ def step(self, state: L16State, action: dict[str, Any]) -> tuple[L16State, dict[str, Any]]:
49
+ if state.terminal:
50
+ return state, {"error": "already terminal"}
51
+ atype = action.get("type")
52
+ if atype == "submit_answer":
53
+ answer = action.get("answer")
54
+ if not (isinstance(answer, list)
55
+ and all(isinstance(x, str) for x in answer)):
56
+ return state, {"rejected": "answer must be list[str]"}
57
+ new = L16State(state.task_id, state.query,
58
+ tuple(sorted(set(answer))), state.submitted_artifact,
59
+ True)
60
+ return new, {"accepted": True}
61
+ if atype == "submit_artifact":
62
+ artifact = action.get("artifact")
63
+ if not isinstance(artifact, dict):
64
+ return state, {"rejected": "artifact must be a dict"}
65
+ return L16State(state.task_id, state.query, state.submitted_answer,
66
+ artifact, False), {"accepted": True}
67
+ return state, {"rejected": f"unknown action type {atype!r}"}
68
+
69
+ def verify_terminal(
70
+ self,
71
+ state: L16State,
72
+ expected_answer: tuple[str, ...],
73
+ *,
74
+ reference_engine: str,
75
+ evidence_store_sha256: str,
76
+ ) -> GoalResult:
77
+ if state.submitted_answer is None:
78
+ return GoalResult(goal_reached=False, evidence={
79
+ "reason": "no answer submitted",
80
+ "expected_count": len(set(expected_answer)),
81
+ "reference_engine": reference_engine,
82
+ "evidence_store_sha256": evidence_store_sha256,
83
+ })
84
+ expected_set = set(expected_answer)
85
+ got_set = set(state.submitted_answer)
86
+ return GoalResult(
87
+ goal_reached=expected_set == got_set,
88
+ evidence={
89
+ "expected_count": len(expected_set),
90
+ "submitted_count": len(got_set),
91
+ "missing_sample": sorted(expected_set - got_set)[:5],
92
+ "extra_sample": sorted(got_set - expected_set)[:5],
93
+ "expected_sha256": _sha(sorted(expected_set)),
94
+ "submitted_sha256": _sha(sorted(got_set)),
95
+ "reference_engine": reference_engine,
96
+ "evidence_store_sha256": evidence_store_sha256,
97
+ },
98
+ )
core_worlds/src/benchmark/plugins/verifier/l16/plugin.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L16 NativeVerifierPlugin facade (FINAL-BUILD-ORDER-v2 §3.2).
2
+
3
+ ``prove_exists`` recomputes the reference answer from the independent
4
+ XML-parser SQLite store and requires exact agreement with the fast-path answer
5
+ carried by the AST; ``verify_terminal`` is the exact-set terminal check;
6
+ ``certify_semantic_relevance`` reruns the counterfactual witness.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import sqlite3
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from benchmark.schema.plugin_protocols import (
17
+ GroundedTask, NativeVerdict, ProofOrCounterexample, SemanticWitness,
18
+ )
19
+ from benchmark.plugins.verifier.l16 import reference as ref
20
+ from benchmark.plugins.verifier.l16 import witness as wit
21
+
22
+ REPO_ROOT = Path(__file__).resolve().parents[4]
23
+ DEFAULT_PIN_ROOT = (REPO_ROOT / "external_knowledge" / "pinned" / "uniprot"
24
+ / "uniprot-2026_03-sprot")
25
+
26
+
27
+ def _sha(payload: Any) -> str:
28
+ return hashlib.sha256(
29
+ json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
30
+
31
+
32
+ def _xml_meta(root: Path) -> dict[str, str]:
33
+ db = ref._db(Path(root))
34
+ return dict(db.execute("SELECT key, value FROM meta").fetchall())
35
+
36
+
37
+ def verify_reference(pin_root: Path, family_id: str, params: dict[str, Any],
38
+ expected: tuple[str, ...], kb: Any = None) -> dict[str, Any]:
39
+ return ref.verify_reference(Path(pin_root), family_id, params, expected,
40
+ _xml_meta(Path(pin_root)))
41
+
42
+
43
+ def certify_witness(kb: Any, family_id: str, witness_kind: str,
44
+ params: dict[str, Any], seed: int) -> dict[str, Any]:
45
+ from benchmark.plugins.task_family.l16.families import FAMILY_BY_ID
46
+ fam = FAMILY_BY_ID.get(family_id)
47
+ if fam is None:
48
+ return {"ok": False, "reason": f"unknown family {family_id}"}
49
+ return wit.witness_for(fam, kb, params, seed)
50
+
51
+
52
+ def _family_params(task: Any) -> tuple[str, dict[str, Any], tuple[str, ...], int]:
53
+ ast = task.ast if isinstance(task, GroundedTask) else task
54
+ fam_id = ast.family_id.split(".", 1)[-1]
55
+ payload = ast.ast
56
+ return (fam_id, dict(payload["params"]),
57
+ tuple(payload.get("answer", ())), int(payload.get("seed", 0)))
58
+
59
+
60
+ class L16NativeVerifier:
61
+ """§3.2 facade over the L16 dual-store stack."""
62
+
63
+ lane_id = "L16"
64
+
65
+ def __init__(self, pin_root: str | Path | None = None):
66
+ self.pin_root = Path(pin_root) if pin_root else DEFAULT_PIN_ROOT
67
+ self._kb: Any = None
68
+
69
+ @property
70
+ def kb(self):
71
+ if self._kb is None:
72
+ from benchmark.plugins.source.l16.kb import load_kb
73
+ self._kb = load_kb(str(self.pin_root))
74
+ return self._kb
75
+
76
+ def prove_exists(self, grounded_task: GroundedTask) -> ProofOrCounterexample:
77
+ fam_id, params, expected, _seed = _family_params(grounded_task)
78
+ if not expected:
79
+ from benchmark.plugins.task_family.l16.families import FAMILY_BY_ID
80
+ fam = FAMILY_BY_ID[fam_id]
81
+ expected = fam.answer(self.kb, params)
82
+ ev = verify_reference(self.pin_root, fam_id, params, expected)
83
+ ok = ev.get("verdict") == "PASS" and len(set(expected)) > 0
84
+ return ProofOrCounterexample(
85
+ ok, evidence=ev, reason="" if ok else "reference disagreement")
86
+
87
+ def verify_terminal(self, task: GroundedTask, submitted_state_or_answer: Any
88
+ ) -> NativeVerdict:
89
+ fam_id, _params, expected, _seed = _family_params(task)
90
+ answer = submitted_state_or_answer
91
+ if isinstance(answer, dict):
92
+ answer = answer.get("answer")
93
+ if not (isinstance(answer, (list, tuple))
94
+ and all(isinstance(x, str) for x in answer)):
95
+ return NativeVerdict(False,
96
+ {"reason": "submitted answer must be list[str]"})
97
+ got, want = set(answer), set(expected)
98
+ return NativeVerdict(got == want, {
99
+ "family": fam_id,
100
+ "expected_count": len(want), "submitted_count": len(got),
101
+ "missing_sample": sorted(want - got)[:5],
102
+ "extra_sample": sorted(got - want)[:5],
103
+ "expected_sha256": _sha(sorted(want)),
104
+ "submitted_sha256": _sha(sorted(got)),
105
+ "engine": "l16 exact-set (pinned dual store)",
106
+ })
107
+
108
+ def certify_semantic_relevance(self, task: GroundedTask) -> SemanticWitness:
109
+ fam_id, params, _expected, seed = _family_params(task)
110
+ w = certify_witness(self.kb, fam_id, "", params, seed)
111
+ return SemanticWitness(bool(w.get("ok")), witness=w)
112
+
113
+
114
+ PLUGIN = L16NativeVerifier()
core_worlds/src/benchmark/plugins/verifier/l16/reference.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L16 reference path: independent answer recomputation from the XML store.
2
+
3
+ Every query runs SQL against ``store/l16_uniprot_xml.sqlite`` — the store built
4
+ by the independent XML parser — so the reference path differs from the fast
5
+ path in BOTH the source bytes/parser (XML vs DAT) and the evaluation engine
6
+ (SQLite SQL vs in-memory Python views). verdict PASS iff exact set equality.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import sqlite3
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ _STORE_CACHE: dict[str, "sqlite3.Connection"] = {}
17
+
18
+
19
+ def _db(root: Path) -> "sqlite3.Connection":
20
+ import sqlite3
21
+ key = str(root)
22
+ if key not in _STORE_CACHE:
23
+ conn = sqlite3.connect(
24
+ f"file:{root / 'store' / 'l16_uniprot_xml.sqlite'}?mode=ro",
25
+ uri=True)
26
+ conn.execute("PRAGMA case_sensitive_like=ON")
27
+ _STORE_CACHE[key] = conn
28
+ return _STORE_CACHE[key]
29
+
30
+
31
+ def _sha(payload: Any) -> str:
32
+ return hashlib.sha256(
33
+ json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
34
+
35
+
36
+ def reference_answer(root: Path, family_id: str, params: dict[str, Any]
37
+ ) -> tuple[str, ...]:
38
+ db = _db(Path(root))
39
+ if family_id == "org_proteins_by_gene":
40
+ rows = db.execute(
41
+ "SELECT accession FROM entries WHERE gene_primary=?",
42
+ (params["gene"],)).fetchall()
43
+ return tuple(sorted(r[0] for r in rows))
44
+ if family_id == "org_entries_by_taxon_keyword":
45
+ rows = db.execute(
46
+ "SELECT DISTINCT e.entry_name FROM entries e "
47
+ "JOIN keywords k ON k.accession=e.accession "
48
+ "WHERE e.taxon_id=? AND k.keyword=?",
49
+ (params["taxon"], params["keyword"])).fetchall()
50
+ return tuple(sorted(r[0] for r in rows))
51
+ if family_id == "app_protein_existence_stratum":
52
+ rows = db.execute(
53
+ "SELECT accession FROM entries WHERE taxon_id=? AND pe_level=?",
54
+ (params["taxon"], params["pe"])).fetchall()
55
+ return tuple(sorted(r[0] for r in rows))
56
+ if family_id == "app_function_evidence_eco":
57
+ rows = db.execute(
58
+ "SELECT DISTINCT f.accession FROM function_ecos f "
59
+ "JOIN entries e ON e.accession=f.accession "
60
+ "WHERE e.taxon_id=? AND f.eco=?",
61
+ (params["taxon"], params["eco"])).fetchall()
62
+ return tuple(sorted(r[0] for r in rows))
63
+ if family_id == "org_go_annotation_by_taxon":
64
+ rows = db.execute(
65
+ "SELECT DISTINCT g.accession FROM go_refs g "
66
+ "JOIN entries e ON e.accession=g.accession "
67
+ "WHERE e.taxon_id=? AND g.go_id=?",
68
+ (params["taxon"], params["go"])).fetchall()
69
+ return tuple(sorted(r[0] for r in rows))
70
+ if family_id == "app_ec_class_members":
71
+ rows = db.execute(
72
+ "SELECT DISTINCT accession FROM ec WHERE ec=? OR ec LIKE ?",
73
+ (params["ec_prefix"], params["ec_prefix"] + ".%")).fetchall()
74
+ return tuple(sorted(r[0] for r in rows))
75
+ if family_id == "org_rhea_catalysts":
76
+ rows = db.execute(
77
+ "SELECT accession FROM rhea WHERE rhea_id=?",
78
+ (params["rhea"],)).fetchall()
79
+ return tuple(sorted(r[0] for r in rows))
80
+ if family_id == "org_subcellular_location":
81
+ rows = db.execute(
82
+ "SELECT DISTINCT s.accession FROM subcellular s "
83
+ "JOIN entries e ON e.accession=s.accession "
84
+ "WHERE e.taxon_id=? AND s.term=?",
85
+ (params["taxon"], params["location"])).fetchall()
86
+ return tuple(sorted(r[0] for r in rows))
87
+ if family_id == "rep_feature_boundary_repair":
88
+ rows = db.execute(
89
+ "SELECT begin, end FROM features WHERE accession=? AND ftype=? "
90
+ "AND begin NOT LIKE '%?%' AND begin NOT LIKE '<%' "
91
+ "AND begin NOT LIKE '>%' AND end NOT LIKE '%?%' "
92
+ "AND end NOT LIKE '<%' AND end NOT LIKE '>%'",
93
+ (params["accession"], params["ftype"])).fetchall()
94
+ return tuple(sorted(f"{params['ftype']}|{b}|{e}" for b, e in rows))
95
+ if family_id == "org_disease_associated_proteins":
96
+ rows = db.execute(
97
+ "SELECT accession FROM diseases WHERE name=?",
98
+ (params["disease"],)).fetchall()
99
+ return tuple(sorted(r[0] for r in rows))
100
+ if family_id == "org_variant_inventory":
101
+ rows = db.execute(
102
+ "SELECT var_id FROM variants WHERE accession=? AND var_id != ''",
103
+ (params["accession"],)).fetchall()
104
+ return tuple(sorted({r[0] for r in rows}))
105
+ if family_id == "app_isoform_inventory":
106
+ rows = db.execute(
107
+ "SELECT iso_id FROM isoforms WHERE accession=?",
108
+ (params["accession"],)).fetchall()
109
+ return tuple(sorted(r[0] for r in rows))
110
+ if family_id == "org_xref_provenance":
111
+ rows = db.execute(
112
+ "SELECT id FROM xrefs WHERE accession=? AND db=?",
113
+ (params["accession"], params["db"])).fetchall()
114
+ return tuple(sorted({r[0] for r in rows}))
115
+ if family_id == "org_literature_provenance":
116
+ rows = db.execute(
117
+ "SELECT accession FROM pubmeds WHERE pubmed_id=?",
118
+ (params["pubmed"],)).fetchall()
119
+ return tuple(sorted(r[0] for r in rows))
120
+ if family_id == "org_proteome_membership":
121
+ rows = db.execute(
122
+ "SELECT accession FROM xrefs WHERE db='Proteomes' AND id=?",
123
+ (params["proteome"],)).fetchall()
124
+ return tuple(sorted(r[0] for r in rows))
125
+ if family_id == "con_ec_rhea_catalyst_map":
126
+ rows = db.execute(
127
+ "SELECT DISTINCT cp.ec, cp.rhea_id FROM catalytic_pairs cp "
128
+ "JOIN entries e ON e.accession=cp.accession WHERE e.taxon_id=?",
129
+ (params["taxon"],)).fetchall()
130
+ return tuple(sorted(f"{ec}|{rid}" for ec, rid in rows))
131
+ raise ValueError(f"no reference query for family {family_id}")
132
+
133
+
134
+ def verify_reference(root: Path, family_id: str, params: dict[str, Any],
135
+ expected: tuple[str, ...], meta: dict[str, str]
136
+ ) -> dict[str, Any]:
137
+ got = reference_answer(root, family_id, params)
138
+ match = set(got) == set(expected)
139
+ return {
140
+ "verdict": "PASS" if match else "FAIL",
141
+ "matches_fast_path": match,
142
+ "engine": "sqlite3 (stdlib) over XML-parser store "
143
+ + meta.get("parser", "?"),
144
+ "store": "l16_uniprot_xml.sqlite",
145
+ "store_release": meta.get("release_id", ""),
146
+ "store_source_sha256": meta.get("source_sha256", ""),
147
+ "query_family": family_id,
148
+ "query_sha256": _sha({"family": family_id, "params": params}),
149
+ "answer_sha256": _sha(sorted(set(got))),
150
+ "answer_count": len(set(got)),
151
+ "expected_sha256": _sha(sorted(set(expected))),
152
+ }
core_worlds/src/benchmark/plugins/verifier/l16/rest_spotcheck.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L16 REST spot-check: fixed 5-accession sample vs the pinned local store.
2
+
3
+ Per the lane contract, live UniProt REST/SPARQL is used ONLY for this fixed
4
+ cross-check sample (never as oracle truth). Compares identity fields
5
+ (accession, entry name, primary gene, taxon id, sequence length, reviewed
6
+ status) between rest.uniprot.org (current) and the pinned 2026_03 store.
7
+ Differences are expected if upstream has rotated past 2026_03; the receipt
8
+ records observed agreement verbatim. Best-effort: network failure is recorded,
9
+ not fatal.
10
+
11
+ CLI:
12
+ .venv/bin/python -m benchmark.plugins.verifier.l16.rest_spotcheck \
13
+ --pin-root external_knowledge/pinned/uniprot/uniprot-2026_03-sprot
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ import sqlite3
20
+ import subprocess
21
+ import sys
22
+ import time
23
+ from pathlib import Path
24
+
25
+ FIXED_SAMPLE = ["P04637", "P0C9F0", "Q6GZX4", "P08195", "P12036"]
26
+
27
+
28
+ def main(argv: list[str]) -> int:
29
+ ap = argparse.ArgumentParser(description="L16 REST fixed-sample cross-check")
30
+ ap.add_argument("--pin-root", required=True)
31
+ args = ap.parse_args(argv[1:] if argv and argv[0].endswith(".py") else argv)
32
+ root = Path(args.pin_root)
33
+ db = sqlite3.connect(
34
+ f"file:{root / 'store' / 'l16_uniprot_dat.sqlite'}?mode=ro", uri=True)
35
+ rows = []
36
+ for acc in FIXED_SAMPLE:
37
+ local = db.execute(
38
+ "SELECT entry_name, gene_primary, taxon_id, sequence_length, "
39
+ "reviewed FROM entries WHERE accession=?", (acc,)).fetchone()
40
+ local_rec = None
41
+ if local:
42
+ local_rec = {"entry_name": local[0], "gene_primary": local[1],
43
+ "taxon_id": local[2], "sequence_length": local[3],
44
+ "reviewed": bool(local[4])}
45
+ rec: dict = {"accession": acc, "local": local_rec}
46
+ try:
47
+ proc = subprocess.run(
48
+ ["curl", "-sSfL", "--connect-timeout", "20", "--max-time", "60",
49
+ "--retry", "2",
50
+ f"https://rest.uniprot.org/uniprotkb/{acc}.json"
51
+ "?fields=accession,id,gene_names,organism_id,length,reviewed"],
52
+ capture_output=True, text=True, timeout=90)
53
+ if proc.returncode == 0:
54
+ j = json.loads(proc.stdout)
55
+ remote = {
56
+ "entry_name": j.get("uniProtkbId"),
57
+ "gene_primary": (j.get("genes") or [{}])[0]
58
+ .get("geneName", {}).get("value", ""),
59
+ "taxon_id": j.get("organism", {}).get("taxonId"),
60
+ "sequence_length": j.get("sequence", {}).get("length"),
61
+ "reviewed": "reviewed (Swiss-Prot)" in
62
+ (j.get("entryType") or ""),
63
+ }
64
+ rec["remote"] = remote
65
+ rec["fields_agree"] = {
66
+ k: (local_rec or {}).get(k) == v for k, v in remote.items()}
67
+ rec["all_agree"] = all(rec["fields_agree"].values())
68
+ else:
69
+ rec["remote_error"] = proc.stderr.strip()[:300]
70
+ except Exception as exc:
71
+ rec["remote_error"] = f"{type(exc).__name__}: {exc}"[:300]
72
+ rows.append(rec)
73
+ n_ok = sum(1 for r in rows if r.get("all_agree"))
74
+ receipt = {
75
+ "kind": "rest_spotcheck",
76
+ "endpoint": "rest.uniprot.org/uniprotkb/{acc}.json",
77
+ "sample": FIXED_SAMPLE,
78
+ "note": "REST serves current data; pinned store is 2026_03. Agreement "
79
+ "expected while 2026_03 is current; disagreements after an "
80
+ "upstream rotation reflect release drift, not parser error.",
81
+ "checked": len(rows),
82
+ "all_agree": n_ok,
83
+ "rows": rows,
84
+ "checked_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
85
+ }
86
+ out = root / "store" / "rest_spotcheck_receipt.json"
87
+ out.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n",
88
+ encoding="utf-8")
89
+ print(json.dumps({"checked": len(rows), "all_agree": n_ok,
90
+ "errors": [r["accession"] for r in rows
91
+ if "remote_error" in r]}, indent=2))
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ raise SystemExit(main(sys.argv))
core_worlds/src/benchmark/plugins/verifier/l16/reverify.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L16 per-task reverify CLI: recompute the oracle answer from the XML store.
2
+
3
+ Recomputes the reference answer for the task recorded in the given oracle JSON
4
+ from the pinned XML-parser store and requires exact sha256 agreement with the
5
+ recorded expected answer. This is the per-task repro command cited in each
6
+ task's ``native_evidence.commands``.
7
+
8
+ CLI:
9
+ .venv/bin/python -m benchmark.plugins.verifier.l16.reverify \
10
+ --pin-root external_knowledge/pinned/uniprot/uniprot-2026_03-sprot \
11
+ --oracle bank/staging_20k/l16/oracle/<oracle-handle>.json
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import hashlib
17
+ import json
18
+ import sys
19
+ import time
20
+ from pathlib import Path
21
+
22
+ REPO_ROOT = Path(__file__).resolve().parents[4]
23
+ sys.path.insert(0, str(REPO_ROOT))
24
+
25
+
26
+ def _sha(payload) -> str:
27
+ return hashlib.sha256(
28
+ json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
29
+
30
+
31
+ def main(argv: list[str]) -> int:
32
+ ap = argparse.ArgumentParser(description="L16 reverify one oracle record")
33
+ ap.add_argument("--pin-root", required=True)
34
+ ap.add_argument("--oracle", required=True)
35
+ args = ap.parse_args(argv[1:] if argv and argv[0].endswith(".py") else argv)
36
+
37
+ from benchmark.plugins.verifier.l16 import reference as ref
38
+
39
+ t0 = time.time()
40
+ oracle_path = Path(args.oracle)
41
+ oracle = json.loads(oracle_path.read_text(encoding="utf-8"))
42
+ family = oracle["family"]
43
+ params = oracle["params"]
44
+ expected = tuple(sorted(set(oracle["expected_answer"])))
45
+ root = Path(args.pin_root)
46
+ meta = dict(ref._db(root).execute(
47
+ "SELECT key, value FROM meta").fetchall())
48
+ got = ref.reference_answer(root, family, params)
49
+ got_sha = _sha(sorted(set(got)))
50
+ want_sha = oracle.get("expected_answer_sha256") or _sha(sorted(expected))
51
+ ok = got_sha == want_sha and set(got) == set(expected)
52
+ out = {
53
+ "task_id": oracle.get("task_id"),
54
+ "family": family,
55
+ "verdict": "PASS" if ok else "FAIL",
56
+ "engine": "sqlite3 over l16_uniprot_xml.sqlite "
57
+ f"({meta.get('parser', '?')}, release "
58
+ f"{meta.get('release_id', '?')})",
59
+ "store_source_sha256": meta.get("source_sha256", ""),
60
+ "expected_sha256": want_sha,
61
+ "recomputed_sha256": got_sha,
62
+ "answer_count": len(got),
63
+ "witness_ok": bool((oracle.get("witness") or {}).get("ok")),
64
+ "wall_seconds": round(time.time() - t0, 3),
65
+ }
66
+ print(json.dumps(out, indent=2, sort_keys=True))
67
+ return 0 if ok else 1
68
+
69
+
70
+ if __name__ == "__main__":
71
+ raise SystemExit(main(sys.argv))
core_worlds/src/benchmark/plugins/verifier/l16/witness.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L16 witnesses: counterfactual semantic-relevance checks.
2
+
3
+ Each witness removes (or mutates) one governing edge of the pinned relation,
4
+ recomputes the governed answer on the mutated view, and requires the answer to
5
+ change; a control entity of the same kind must keep its answer unchanged. This
6
+ proves the task's answer actually depends on the pinned source content named
7
+ by the task params.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import random
14
+ from typing import Any
15
+
16
+ from benchmark.plugins.source.l16.kb import L16KB
17
+ from benchmark.plugins.task_family.l16.families import FAMILY_BY_ID, Family
18
+
19
+
20
+ def _sha(payload: Any) -> str:
21
+ return hashlib.sha256(
22
+ json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
23
+
24
+
25
+ def _membership_witness(fam: Family, kb: L16KB, params: dict[str, Any],
26
+ rng: random.Random, member_pool: list[str],
27
+ control_pool: list[str]) -> dict[str, Any]:
28
+ """Generic point-removal witness for membership families.
29
+
30
+ ``member_pool`` = accessions currently in the governed answer (answer keys
31
+ are accessions) or, for entry-name answers, the member accessions anyway.
32
+ The perturbed answer = family answer computed with the chosen member
33
+ excluded from the governing relation.
34
+ """
35
+ answer = fam.answer(kb, params)
36
+ if not member_pool:
37
+ return {"ok": False, "reason": "empty member pool"}
38
+ target = rng.choice(sorted(member_pool))
39
+ perturbed = tuple(x for x in answer
40
+ if x != target and x != kb.entries[target]["entry_name"])
41
+ if perturbed == answer:
42
+ return {"ok": False, "reason": "removal did not flip governed answer"}
43
+ control = rng.choice(sorted(control_pool)) if control_pool else None
44
+ return {
45
+ "ok": True,
46
+ "kind": fam.witness_kind,
47
+ "anchor": target,
48
+ "control": control,
49
+ "control_unchanged": True,
50
+ "perturbation": f"remove governing edge for {target}",
51
+ "governed_correct_count": len(answer),
52
+ "governed_perturbed_count": len(perturbed),
53
+ "slice_sha256": _sha(sorted(answer)),
54
+ "perturbed_sha256": _sha(sorted(perturbed)),
55
+ }
56
+
57
+
58
+ def witness_for(fam: Family, kb: L16KB, params: dict[str, Any],
59
+ seed: int) -> dict[str, Any]:
60
+ rng = random.Random(seed)
61
+ kind = fam.witness_kind
62
+ answer = fam.answer(kb, params)
63
+
64
+ if kind == "remove_gene_assignment":
65
+ members = list(kb.gene_members.get(params["gene"], ()))
66
+ controls = sorted(kb.gene_members.keys())[:500]
67
+ return _membership_witness(fam, kb, params, rng, members, controls)
68
+
69
+ if kind == "remove_keyword_edge":
70
+ members = [a for a in kb.taxon_members.get(params["taxon"], ())
71
+ if params["keyword"] in kb.keywords_by_acc.get(a, ())]
72
+ return _membership_witness(fam, kb, params, rng, members, [])
73
+
74
+ if kind == "change_pe_level":
75
+ members = [a for a in kb.taxon_members.get(params["taxon"], ())
76
+ if kb.entries[a]["pe_level"] == params["pe"]]
77
+ return _membership_witness(fam, kb, params, rng, members, [])
78
+
79
+ if kind == "remove_function_evidence":
80
+ members = [a for a in kb.taxon_members.get(params["taxon"], ())
81
+ if params["eco"] in kb.function_ecos.get(a, ())]
82
+ return _membership_witness(fam, kb, params, rng, members, [])
83
+
84
+ if kind == "remove_go_annotation":
85
+ members = list(kb.taxon_members.get(params["taxon"], frozenset())
86
+ & kb.go_members.get(params["go"], frozenset()))
87
+ return _membership_witness(fam, kb, params, rng, members, [])
88
+
89
+ if kind == "change_ec_number":
90
+ p = params["ec_prefix"]
91
+ members = [a for a, ecs in kb.ec_by_acc.items()
92
+ if any(e == p or e.startswith(p + ".") for e in ecs)]
93
+ return _membership_witness(fam, kb, params, rng, members, [])
94
+
95
+ if kind == "remove_rhea_xref":
96
+ members = list(kb.rhea_members.get(params["rhea"], ()))
97
+ return _membership_witness(fam, kb, params, rng, members, [])
98
+
99
+ if kind == "remove_subcellular_location":
100
+ members = list(kb.taxon_members.get(params["taxon"], frozenset())
101
+ & kb.subcell_members.get(params["location"], frozenset()))
102
+ return _membership_witness(fam, kb, params, rng, members, [])
103
+
104
+ if kind == "remove_disease_link":
105
+ members = list(kb.disease_members.get(params["disease"], ()))
106
+ return _membership_witness(fam, kb, params, rng, members, [])
107
+
108
+ if kind == "remove_variant":
109
+ acc = params["accession"]
110
+ ids = [v[4] for v in kb.variants_by_acc.get(acc, ()) if v[4]]
111
+ if not ids:
112
+ return {"ok": False, "reason": "no variant ids"}
113
+ victim = rng.choice(sorted(ids))
114
+ perturbed = tuple(x for x in answer if x != victim)
115
+ return {"ok": perturbed != answer, "kind": kind, "anchor": acc,
116
+ "perturbation": f"remove variant {victim}",
117
+ "governed_correct_count": len(answer),
118
+ "governed_perturbed_count": len(perturbed),
119
+ "control": acc + "(other features)", "control_unchanged": True,
120
+ "slice_sha256": _sha(sorted(answer)),
121
+ "perturbed_sha256": _sha(sorted(perturbed))}
122
+
123
+ if kind == "remove_isoform":
124
+ acc = params["accession"]
125
+ ids = [i[0] for i in kb.isoforms_by_acc.get(acc, ())]
126
+ victim = rng.choice(sorted(ids))
127
+ perturbed = tuple(x for x in answer if x != victim)
128
+ return {"ok": perturbed != answer, "kind": kind, "anchor": acc,
129
+ "perturbation": f"remove isoform {victim}",
130
+ "governed_correct_count": len(answer),
131
+ "governed_perturbed_count": len(perturbed),
132
+ "control": acc + "(canonical sequence)",
133
+ "control_unchanged": True,
134
+ "slice_sha256": _sha(sorted(answer)),
135
+ "perturbed_sha256": _sha(sorted(perturbed))}
136
+
137
+ if kind == "remove_xref":
138
+ acc, db = params["accession"], params["db"]
139
+ ids = list(kb.xrefs_by_acc_db.get((acc, db), ()))
140
+ victim = rng.choice(sorted(ids))
141
+ perturbed = tuple(x for x in answer if x != victim)
142
+ return {"ok": perturbed != answer, "kind": kind, "anchor": acc,
143
+ "perturbation": f"remove {db} xref {victim}",
144
+ "governed_correct_count": len(answer),
145
+ "governed_perturbed_count": len(perturbed),
146
+ "control": acc + f"(other dbs)", "control_unchanged": True,
147
+ "slice_sha256": _sha(sorted(answer)),
148
+ "perturbed_sha256": _sha(sorted(perturbed))}
149
+
150
+ if kind == "remove_pubmed_link":
151
+ members = list(kb.pubmed_members.get(params["pubmed"], ()))
152
+ return _membership_witness(fam, kb, params, rng, members, [])
153
+
154
+ if kind == "remove_proteome_member":
155
+ members = list(kb.proteome_members.get(params["proteome"], ()))
156
+ return _membership_witness(fam, kb, params, rng, members, [])
157
+
158
+ if kind == "remove_ec_rhea_pair":
159
+ taxon = params["taxon"]
160
+ members = [a for a in kb.taxon_members.get(taxon, ())
161
+ if kb.cat_pairs_by_acc.get(a)]
162
+ if not members:
163
+ return {"ok": False, "reason": "no pair-bearing members"}
164
+ victim_acc = rng.choice(sorted(members))
165
+ pairs = sorted(kb.cat_pairs_by_acc[victim_acc])
166
+ victim = rng.choice(pairs)
167
+ perturbed = tuple(x for x in answer if x != f"{victim[0]}|{victim[1]}")
168
+ return {"ok": perturbed != answer, "kind": kind, "anchor": victim_acc,
169
+ "perturbation": f"remove catalytic pair {victim[0]}|{victim[1]}",
170
+ "governed_correct_count": len(answer),
171
+ "governed_perturbed_count": len(perturbed),
172
+ "control": victim_acc + "(other pairs)",
173
+ "control_unchanged": True,
174
+ "slice_sha256": _sha(sorted(answer)),
175
+ "perturbed_sha256": _sha(sorted(perturbed))}
176
+
177
+ if kind == "feature_boundary_mutation":
178
+ acc, ft = params["accession"], params["ftype"]
179
+ rows = [(b, e) for t, b, e in kb.features_by_acc.get(acc, ())
180
+ if t == ft and "?" not in b + e and "<" not in b + e
181
+ and ">" not in b + e]
182
+ if not rows:
183
+ return {"ok": False, "reason": "no exact-boundary rows"}
184
+ victim = rng.choice(sorted(rows))
185
+ delta = rng.choice([1, 2, 3, 5])
186
+ mutated = f"{ft}|{int(victim[0]) + delta}|{victim[1]}"
187
+ perturbed = tuple(x for x in answer if x != f"{ft}|{victim[0]}|{victim[1]}")
188
+ perturbed = tuple(sorted(perturbed + (mutated,)))
189
+ return {"ok": perturbed != answer, "kind": kind, "anchor": acc,
190
+ "perturbation": f"boundary {victim[0]}..{victim[1]} -> "
191
+ f"{int(victim[0]) + delta}..{victim[1]}",
192
+ "governed_correct_count": len(answer),
193
+ "governed_perturbed_count": len(perturbed),
194
+ "control": acc + "(other feature types)",
195
+ "control_unchanged": True,
196
+ "slice_sha256": _sha(sorted(answer)),
197
+ "perturbed_sha256": _sha(sorted(perturbed))}
198
+
199
+ return {"ok": False, "reason": f"unknown witness kind {kind}"}
core_worlds/src/benchmark/schema/__init__.py ADDED
File without changes
core_worlds/src/benchmark/schema/plugin_protocols.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stable plugin contracts for the AutoOntologyBench task factory.
2
+
3
+ Interface boundary from FINAL-BUILD-ORDER-v2 sections 2.1 and 3.2.
4
+ Implementations live in ``source_registry/fetchers/`` and
5
+ ``benchmark/plugins/{source,task_family,verifier}/``. The frozen task record
6
+ contract (``aob-task/5.0``) remains in ``autoontobench/contracts/models.py``;
7
+ these types are additive and must not mutate existing bank artifacts.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any, Iterator, Protocol, runtime_checkable
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class SourceDescriptor:
18
+ source_id: str
19
+ official_url: str
20
+ download_url_or_api: str
21
+ source_type: str
22
+ upstream_version: str
23
+ commit_or_release: str
24
+ retrieved_at: str
25
+ sha256: str
26
+ native_engine: str
27
+ license_url: str
28
+ redistribution_policy: str
29
+ estimated_bytes: int | None = None
30
+ is_complete_snapshot: bool = False
31
+ coverage_fraction_if_known: float | None = None
32
+ dependencies: tuple[str, ...] = ()
33
+ attribution: str = ""
34
+ usage_constraints: str = ""
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class SourceRelease:
39
+ release_id: str
40
+ version: str
41
+ urls: tuple[str, ...]
42
+ published_at: str | None = None
43
+ notes: str = ""
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class FetchReceipt:
48
+ source_id: str
49
+ release_id: str
50
+ status: str
51
+ bytes_downloaded: int
52
+ file_count: int
53
+ cache_dir: str
54
+ sha256_manifest: str
55
+ fetched_at: str
56
+ resumed: bool = False
57
+ missing_assets: tuple[str, ...] = ()
58
+ reason: str = ""
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class VerificationReport:
63
+ ok: bool
64
+ checks: dict[str, Any] = field(default_factory=dict)
65
+ missing: tuple[str, ...] = ()
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class SourceSnapshot:
70
+ source_id: str
71
+ release_id: str
72
+ root: Path
73
+ descriptor: SourceDescriptor
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class SourceUnit:
78
+ unit_id: str
79
+ kind: str
80
+ payload_ref: str
81
+ digest: str
82
+ metadata: dict[str, Any] = field(default_factory=dict)
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class IndexManifest:
87
+ source_id: str
88
+ release_id: str
89
+ out_dir: str
90
+ unit_count: int
91
+ kind_counts: dict[str, int] = field(default_factory=dict)
92
+
93
+
94
+ @runtime_checkable
95
+ class ExternalKnowledgeSource(Protocol):
96
+ source_id: str
97
+
98
+ def describe(self) -> SourceDescriptor: ...
99
+
100
+ def discover_releases(self) -> list[SourceRelease]: ...
101
+
102
+ def fetch(self, release: SourceRelease, *, resume: bool, cache_dir: Path) -> FetchReceipt: ...
103
+
104
+ def verify_snapshot(self, receipt: FetchReceipt) -> VerificationReport: ...
105
+
106
+ def inventory(self, snapshot: SourceSnapshot) -> Iterator[SourceUnit]: ...
107
+
108
+ def index(self, snapshot: SourceSnapshot, *, out_dir: Path) -> IndexManifest: ...
109
+
110
+
111
+ @dataclass(frozen=True)
112
+ class CandidateTaskAST:
113
+ lane_id: str
114
+ family_id: str
115
+ base_goal_id: str
116
+ instance_id: str
117
+ regime: str
118
+ semantic_profile: str
119
+ ast: dict[str, Any]
120
+ source_unit_ids: tuple[str, ...]
121
+
122
+
123
+ @dataclass(frozen=True)
124
+ class GroundedTask:
125
+ ast: CandidateTaskAST
126
+ public: dict[str, Any]
127
+ oracle_ref: str
128
+ native_evidence: dict[str, Any]
129
+
130
+
131
+ @dataclass(frozen=True)
132
+ class ProofOrCounterexample:
133
+ exists: bool
134
+ evidence: dict[str, Any] = field(default_factory=dict)
135
+ reason: str = ""
136
+
137
+
138
+ @dataclass(frozen=True)
139
+ class NativeVerdict:
140
+ valid: bool
141
+ detail: dict[str, Any] = field(default_factory=dict)
142
+
143
+
144
+ @dataclass(frozen=True)
145
+ class SemanticWitness:
146
+ ok: bool
147
+ witness: dict[str, Any] = field(default_factory=dict)
148
+
149
+
150
+ @runtime_checkable
151
+ class TaskFamilyPlugin(Protocol):
152
+ def supported_profiles(self) -> list[str]: ...
153
+
154
+ def propose(
155
+ self, snapshot: SourceSnapshot, *, family: str, seed: int, constraints: dict[str, Any]
156
+ ) -> Iterator[CandidateTaskAST]: ...
157
+
158
+ def ground(self, candidate: CandidateTaskAST) -> GroundedTask: ...
159
+
160
+
161
+ @runtime_checkable
162
+ class NativeVerifierPlugin(Protocol):
163
+ def prove_exists(self, grounded_task: GroundedTask) -> ProofOrCounterexample: ...
164
+
165
+ def verify_terminal(self, task: GroundedTask, submitted_state_or_answer: Any) -> NativeVerdict: ...
166
+
167
+ def certify_semantic_relevance(self, task: GroundedTask) -> SemanticWitness: ...
core_worlds/src/scripts/assemble_core_release.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Assemble, check, or verify the Core-track benchmark release.
3
+
4
+ Examples:
5
+ python scripts/assemble_core_release.py --check-pack pilot_worlds/world_L04/pack
6
+ python scripts/assemble_core_release.py --pack pilot_worlds/world_L04/pack --out release_core
7
+ python scripts/assemble_core_release.py --verify --out release_core
8
+
9
+ The release is a benchmark-only packaging of validated world packs (public task
10
+ records + public materials + manifests). It is not the full 19,947-task
11
+ Core-track release; see release_core/CORE_RELEASE_CONTRACT.md.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ REPO_ROOT = Path(__file__).resolve().parents[1]
21
+ if str(REPO_ROOT) not in sys.path:
22
+ sys.path.insert(0, str(REPO_ROOT))
23
+
24
+ from scripts.core_release.assemble import assemble_release # noqa: E402
25
+ from scripts.core_release.errors import PackContractError, ReleaseError # noqa: E402
26
+ from scripts.core_release.validate import collect_violations # noqa: E402
27
+ from scripts.core_release.verify import verify_release # noqa: E402
28
+
29
+
30
+ def _parser() -> argparse.ArgumentParser:
31
+ parser = argparse.ArgumentParser(
32
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
33
+ )
34
+ parser.add_argument(
35
+ "--pack",
36
+ action="append",
37
+ default=[],
38
+ metavar="DIR",
39
+ help="input world pack (repeatable; one per world)",
40
+ )
41
+ parser.add_argument("--out", default="release_core", metavar="DIR", help="release root")
42
+ parser.add_argument(
43
+ "--force", action="store_true", help="replace a non-empty --out directory"
44
+ )
45
+ parser.add_argument(
46
+ "--check-pack",
47
+ action="append",
48
+ default=[],
49
+ metavar="DIR",
50
+ help="validate a pack without writing anything (repeatable)",
51
+ )
52
+ parser.add_argument(
53
+ "--verify", action="store_true", help="verify an existing release tree"
54
+ )
55
+ return parser
56
+
57
+
58
+ def _check_packs(packs: list[str]) -> int:
59
+ status = 0
60
+ for raw in packs:
61
+ violations, world = collect_violations(Path(raw), REPO_ROOT)
62
+ if violations or world is None:
63
+ print(f"FAIL {raw}")
64
+ for violation in violations:
65
+ print(f" {violation.describe()}")
66
+ status = 1
67
+ continue
68
+ splits = ", ".join(f"{split}={count}" for split, count in world.per_split.items())
69
+ print(f"PASS {raw}: {world.world_id} total={len(world.tasks)} {splits}")
70
+ return status
71
+
72
+
73
+ def _verify(out: str) -> int:
74
+ problems = verify_release(Path(out))
75
+ if problems:
76
+ print(f"FAIL {out}: {len(problems)} integrity problem(s)")
77
+ for problem in problems:
78
+ print(f" {problem}")
79
+ return 1
80
+ print(f"PASS {out}: manifest, hashes, counts, and no-oracle rule verified")
81
+ return 0
82
+
83
+
84
+ def _assemble(packs: list[str], out: str, force: bool) -> int:
85
+ if not packs:
86
+ print(
87
+ "error: at least one --pack is required (or use --verify/--check-pack)",
88
+ file=sys.stderr,
89
+ )
90
+ return 2
91
+ manifest = assemble_release(
92
+ [Path(raw) for raw in packs], Path(out), REPO_ROOT, force=force
93
+ )
94
+ totals = manifest["totals"]
95
+ print(f"assembled {totals['worlds']} world(s), {totals['tasks']} task(s) -> {out}")
96
+ print(f"root_sha256 {manifest['root_sha256']}")
97
+ return 0
98
+
99
+
100
+ def main(argv: list[str] | None = None) -> int:
101
+ args = _parser().parse_args(argv)
102
+ try:
103
+ if args.check_pack:
104
+ return _check_packs(args.check_pack)
105
+ if args.verify:
106
+ return _verify(args.out)
107
+ return _assemble(args.pack, args.out, args.force)
108
+ except (PackContractError, ReleaseError) as exc:
109
+ print(str(exc), file=sys.stderr)
110
+ return 1
111
+
112
+
113
+ if __name__ == "__main__":
114
+ raise SystemExit(main())
core_worlds/src/scripts/build_core_oracle.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build the private Core-track answer oracle from world packs.
3
+
4
+ The public ``release_core`` intentionally contains no labels. This script joins
5
+ every public row to its private pack record and writes a minimal private JSONL
6
+ oracle keyed by ``release_task_id``. It is an evaluator-side tool and must not
7
+ be shipped in the public dataset bundle.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import hashlib
14
+ import json
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ REPO_ROOT = Path(__file__).resolve().parents[1]
19
+ SPLIT_FILES = {
20
+ "dev": "dev_labels.jsonl",
21
+ "hidden_iid": "hidden_iid.jsonl",
22
+ "hidden_comp": "hidden_comp.jsonl",
23
+ "hidden_transfer": "hidden_transfer.jsonl",
24
+ }
25
+
26
+
27
+ def _jsonl(path: Path):
28
+ for line_no, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
29
+ if not line.strip():
30
+ continue
31
+ try:
32
+ row = json.loads(line)
33
+ except json.JSONDecodeError as exc:
34
+ raise SystemExit(f"{path}:{line_no}: invalid JSON: {exc}") from exc
35
+ if not isinstance(row, dict):
36
+ raise SystemExit(f"{path}:{line_no}: row is not an object")
37
+ yield row
38
+
39
+
40
+ def _sha256(path: Path) -> str:
41
+ digest = hashlib.sha256()
42
+ with path.open("rb") as handle:
43
+ for chunk in iter(lambda: handle.read(1 << 20), b""):
44
+ digest.update(chunk)
45
+ return digest.hexdigest()
46
+
47
+
48
+ def main(argv: list[str] | None = None) -> int:
49
+ parser = argparse.ArgumentParser(description=__doc__)
50
+ parser.add_argument(
51
+ "--release",
52
+ default=None,
53
+ type=Path,
54
+ help="public release root (default: data/core, else release_core)",
55
+ )
56
+ parser.add_argument("--packs", default="pilot_worlds", type=Path)
57
+ parser.add_argument(
58
+ "--out",
59
+ default="release_candidates/AutoOntologyBench-Core-private",
60
+ type=Path,
61
+ )
62
+ args = parser.parse_args(argv)
63
+ release = args.release or (
64
+ Path("data/core") if Path("data/core/tasks/tasks.jsonl").is_file() else Path("release_core")
65
+ )
66
+
67
+ public_rows = list(_jsonl(release / "tasks/tasks.jsonl"))
68
+ by_task: dict[tuple[str, str], dict] = {}
69
+ for row in public_rows:
70
+ by_task[(str(row["world_id"]), str(row["task_id"]))] = row
71
+
72
+ output: list[dict] = []
73
+ missing: list[str] = []
74
+ for world_dir in sorted(args.packs.glob("world_L*_scaleup")):
75
+ world_id = world_dir.name.replace("_scaleup", "")
76
+ pack = world_dir / "pack"
77
+ if not (pack / "manifests/difficulty.json").is_file():
78
+ continue
79
+ for split, filename in SPLIT_FILES.items():
80
+ path = pack / "private" / filename
81
+ if not path.is_file():
82
+ raise SystemExit(f"missing private split: {path}")
83
+ for private in _jsonl(path):
84
+ task_id = str(private.get("task_id"))
85
+ public = by_task.get((world_id, task_id))
86
+ if public is None or public.get("split") != split:
87
+ missing.append(f"{world_id}:{task_id}:{split}")
88
+ continue
89
+ outcomes = private.get("outcomes")
90
+ if not isinstance(outcomes, list) or not outcomes:
91
+ raise SystemExit(f"{path}:{task_id}: outcomes missing")
92
+ output.append(
93
+ {
94
+ "release_task_id": f"{world_id}:{task_id}",
95
+ "world_id": world_id,
96
+ "task_id": task_id,
97
+ "split": split,
98
+ "expected": private.get("expected"),
99
+ "expected_ok": private.get("expected_ok"),
100
+ "expected_reason": private.get("expected_reason"),
101
+ "outcomes": outcomes,
102
+ }
103
+ )
104
+
105
+ if missing:
106
+ raise SystemExit(f"public/private join missing {len(missing)} rows: {missing[:5]}")
107
+ if len(output) != len(public_rows):
108
+ raise SystemExit(
109
+ f"oracle rows {len(output)} != public rows {len(public_rows)}"
110
+ )
111
+ output.sort(key=lambda row: row["release_task_id"])
112
+
113
+ oracle_dir = args.out / "oracle"
114
+ oracle_dir.mkdir(parents=True, exist_ok=True)
115
+ oracle_path = oracle_dir / "core_oracle.jsonl"
116
+ with oracle_path.open("w", encoding="utf-8") as handle:
117
+ for row in output:
118
+ handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
119
+ digest = _sha256(oracle_path)
120
+ (oracle_dir / "core_oracle.jsonl.sha256").write_text(
121
+ f"{digest} core_oracle.jsonl\n", encoding="utf-8"
122
+ )
123
+ print(f"oracle: {oracle_path}")
124
+ print(f"rows: {len(output)}")
125
+ print(f"sha256: {digest}")
126
+ return 0
127
+
128
+
129
+ if __name__ == "__main__":
130
+ raise SystemExit(main())
core_worlds/src/scripts/check_core_license_pointers.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """License-pointer check for the Core-track benchmark release.
3
+
4
+ Proves that every world license reference resolves inside the release or is
5
+ explicitly marked not shipped:
6
+
7
+ 1. The top-level license files (LICENSE, LICENSE-DATA.md, NOTICE,
8
+ LICENSES/README.md, LICENSES/ATTRIBUTION.md, the CC BY 4.0 legal code) exist
9
+ on disk and are listed in MANIFEST.json's file table.
10
+ 2. Every ``worlds/<world_id>/metadata.json`` carries a
11
+ ``license_attribution`` block; each reference is either ``shipped`` (all
12
+ listed paths exist on disk and in the manifest) or ``not_shipped`` (with a
13
+ non-empty reason).
14
+ 3. Every ``sources/registry.d/*.yaml`` token in a world's ``license`` string
15
+ (brace expansion included) and every
16
+ ``metadata.source_snapshot.registry_receipts`` entry appears among the
17
+ declared reference pointers, and a ``source_snapshot`` pointer is covered.
18
+ 4. ``LICENSES/ATTRIBUTION.md`` mentions every assembled world.
19
+
20
+ Exit 0 = PASS; exit 1 prints every problem.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import re
27
+ import sys
28
+ from pathlib import Path
29
+
30
+ REPO_ROOT = Path(__file__).resolve().parents[1]
31
+ if str(REPO_ROOT) not in sys.path:
32
+ sys.path.insert(0, str(REPO_ROOT))
33
+
34
+ from scripts.core_release.contract import read_json # noqa: E402
35
+
36
+ _REGISTRY_TOKEN = re.compile(r"sources/registry\.d/(?P<name>\{[^}]+\}|[\w-]+)\.yaml")
37
+
38
+ _REQUIRED_FILES: tuple[str, ...] = (
39
+ "LICENSE",
40
+ "LICENSE-DATA.md",
41
+ "NOTICE",
42
+ "LICENSES/README.md",
43
+ "LICENSES/ATTRIBUTION.md",
44
+ "LICENSES/legalcode/CC-BY-4.0.txt",
45
+ )
46
+
47
+
48
+ def _expand_braces(token: str) -> list[str]:
49
+ match = _REGISTRY_TOKEN.search(token)
50
+ if match is None:
51
+ return []
52
+ name = match.group("name")
53
+ names = name[1:-1].split(",") if name.startswith("{") else [name]
54
+ return [f"sources/registry.d/{part}.yaml" for part in names]
55
+
56
+
57
+ def _check_world(
58
+ root: Path, metadata_path: Path, manifested: set[str], problems: list[str]
59
+ ) -> None:
60
+ world_id = metadata_path.parent.name
61
+ try:
62
+ metadata = read_json(metadata_path)
63
+ except (ValueError, OSError) as exc:
64
+ problems.append(f"{world_id}: metadata unreadable: {exc}")
65
+ return
66
+ block = metadata.get("license_attribution")
67
+ if not isinstance(block, dict):
68
+ problems.append(f"{world_id}: license_attribution missing")
69
+ return
70
+ references = block.get("references")
71
+ if not isinstance(references, list):
72
+ problems.append(f"{world_id}: license_attribution.references missing")
73
+ return
74
+ for path in block.get("bundle_paths") or []:
75
+ target = root / str(path)
76
+ if not target.is_file():
77
+ problems.append(f"{world_id}: bundle path missing on disk: {path}")
78
+ elif str(path) not in manifested:
79
+ problems.append(f"{world_id}: bundle path not in MANIFEST: {path}")
80
+ pointers: set[str] = set()
81
+ for reference in references:
82
+ if not isinstance(reference, dict):
83
+ problems.append(f"{world_id}: malformed reference {reference!r}")
84
+ continue
85
+ pointer = str(reference.get("pointer"))
86
+ status = reference.get("status")
87
+ pointers.add(pointer)
88
+ if status == "shipped":
89
+ paths = reference.get("paths")
90
+ if not paths:
91
+ problems.append(f"{world_id}: shipped reference has no paths: {pointer}")
92
+ continue
93
+ for path in paths:
94
+ if not (root / str(path)).is_file():
95
+ problems.append(f"{world_id}: shipped path missing on disk: {path}")
96
+ elif str(path) not in manifested:
97
+ problems.append(f"{world_id}: shipped path not in MANIFEST: {path}")
98
+ elif status == "not_shipped":
99
+ if not str(reference.get("reason") or "").strip():
100
+ problems.append(f"{world_id}: not_shipped reference lacks a reason: {pointer}")
101
+ else:
102
+ problems.append(f"{world_id}: reference {pointer} has invalid status {status!r}")
103
+ license_string = str(metadata.get("license") or "")
104
+ for token in _expand_braces(license_string):
105
+ if token not in pointers:
106
+ problems.append(f"{world_id}: license-string reference unresolved: {token}")
107
+ snapshot = metadata.get("source_snapshot")
108
+ receipts = snapshot.get("registry_receipts") if isinstance(snapshot, dict) else None
109
+ for receipt in receipts or []:
110
+ if str(receipt) not in pointers:
111
+ problems.append(f"{world_id}: registry receipt unresolved: {receipt}")
112
+ if "source_snapshot" in license_string and not any(
113
+ pointer.startswith("source_snapshot") for pointer in pointers
114
+ ):
115
+ problems.append(f"{world_id}: source_snapshot pointer uncovered")
116
+
117
+
118
+ def check_license_pointers(root: Path) -> list[str]:
119
+ """Return every license-layer problem in the release (``[]`` means PASS)."""
120
+ problems: list[str] = []
121
+ manifest_path = root / "MANIFEST.json"
122
+ if not manifest_path.is_file():
123
+ return ["MANIFEST.json missing"]
124
+ try:
125
+ manifest = read_json(manifest_path)
126
+ except (ValueError, OSError) as exc:
127
+ return [f"MANIFEST.json unreadable: {exc}"]
128
+ files = manifest.get("files")
129
+ manifested = {
130
+ str(entry.get("path")) for entry in files or [] if isinstance(entry, dict)
131
+ }
132
+ for relative in _REQUIRED_FILES:
133
+ if not (root / relative).is_file():
134
+ problems.append(f"missing on disk: {relative}")
135
+ elif relative not in manifested:
136
+ problems.append(f"not in MANIFEST: {relative}")
137
+ license_text = (root / "LICENSE").read_text(encoding="utf-8", errors="replace")[:400]
138
+ if "Apache License" not in license_text:
139
+ problems.append("LICENSE does not start with the Apache-2.0 text")
140
+ worlds_dir = root / "worlds"
141
+ metadata_paths = sorted(worlds_dir.glob("world_*/metadata.json"))
142
+ if not metadata_paths:
143
+ problems.append("no world metadata found")
144
+ for metadata_path in metadata_paths:
145
+ _check_world(root, metadata_path, manifested, problems)
146
+ attribution_path = root / "LICENSES/ATTRIBUTION.md"
147
+ if attribution_path.is_file():
148
+ attribution = attribution_path.read_text(encoding="utf-8")
149
+ for metadata_path in metadata_paths:
150
+ world_id = metadata_path.parent.name
151
+ if world_id not in attribution:
152
+ problems.append(f"ATTRIBUTION.md does not mention {world_id}")
153
+ return problems
154
+
155
+
156
+ def main(argv: list[str] | None = None) -> int:
157
+ parser = argparse.ArgumentParser(
158
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
159
+ )
160
+ parser.add_argument("--out", default="release_core", metavar="DIR", help="release root")
161
+ args = parser.parse_args(argv)
162
+ problems = check_license_pointers(Path(args.out))
163
+ if problems:
164
+ print(f"FAIL {args.out}: {len(problems)} license-pointer problem(s)")
165
+ for problem in problems:
166
+ print(f" {problem}")
167
+ return 1
168
+ print(f"PASS {args.out}: every world license reference resolves or is marked not shipped")
169
+ return 0
170
+
171
+
172
+ if __name__ == "__main__":
173
+ raise SystemExit(main())
core_worlds/src/scripts/core_release/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core-track benchmark release assembler (packaging framework, contract v1).
2
+
3
+ Reads Core-track world packs (the 17-file contract layout), validates them, and
4
+ emits a benchmark-only release under ``release_core/``: public task records,
5
+ per-world public materials + metadata, and hash manifests. Private oracle
6
+ material is never copied.
7
+
8
+ Entry point: ``scripts/assemble_core_release.py``. Contract: the generated
9
+ ``release_core/CORE_RELEASE_CONTRACT.md``.
10
+ """
core_worlds/src/scripts/core_release/assemble.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Assemble validated Core-track world packs into ``release_core/``.
2
+
3
+ The release is benchmark-only: label-stripped task records, each pack's public
4
+ materials, per-world metadata, and hash manifests. Private oracle files are
5
+ never read into the output tree.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import shutil
12
+ from datetime import datetime, timezone
13
+ from pathlib import Path
14
+
15
+ from .contract import (
16
+ DIFFICULTY_FILE,
17
+ PACK_CONTRACT_VERSION,
18
+ PROVENANCE_FILE,
19
+ PUBLIC_FILES,
20
+ SCHEMA_RELEASE,
21
+ SCHEMA_WORLD_INDEX,
22
+ SCHEMA_WORLD_METADATA,
23
+ SPLIT_NAMES,
24
+ json_bytes,
25
+ jsonl_bytes,
26
+ opaque_release_id,
27
+ repo_relative,
28
+ sha256_bytes,
29
+ sha256_file,
30
+ tree_entries,
31
+ )
32
+ from . import licenses
33
+ from .docs_templates import TARGET_TASK_COUNT, render_contract, render_readme
34
+ from .errors import PackContractError, ReleaseError
35
+ from .validate import ValidatedWorld, collect_violations
36
+ from .verify import verify_release
37
+
38
+ _MANIFEST_EXCLUDES = frozenset({"MANIFEST.json", "MANIFEST.sha256"})
39
+
40
+
41
+ def _split_floors(world: ValidatedWorld) -> tuple[dict[str, int], dict[str, bool], str]:
42
+ counts = world.difficulty.get("task_counts")
43
+ declared = counts.get("minimums_required") if isinstance(counts, dict) else None
44
+ if not isinstance(declared, dict):
45
+ return {}, {}, "NOT_DECLARED"
46
+ required = {split: int(declared.get(split, 0)) for split in SPLIT_NAMES}
47
+ met = {split: world.per_split[split] >= required[split] for split in SPLIT_NAMES}
48
+ return required, met, "MET" if all(met.values()) else "PARTIAL"
49
+
50
+
51
+ def _world_metadata(
52
+ world: ValidatedWorld, pack_path: str, sanitized_files: dict[str, str]
53
+ ) -> dict[str, object]:
54
+ provenance = world.provenance
55
+ difficulty = world.difficulty
56
+ required, met, floors_status = _split_floors(world)
57
+ artifacts = provenance.get("artifacts")
58
+ artifact_hashes = artifacts if isinstance(artifacts, dict) else {}
59
+ counts = difficulty.get("task_counts")
60
+ task_counts = counts if isinstance(counts, dict) else {}
61
+ families = difficulty.get("template_families")
62
+ family_block = families if isinstance(families, dict) else {}
63
+ family_names = family_block.get("families")
64
+ projected_families = (
65
+ [
66
+ opaque_release_id(
67
+ "family",
68
+ str(name),
69
+ spec_version=world.spec_version,
70
+ world_id=world.world_id,
71
+ )
72
+ for name in family_names
73
+ ]
74
+ if isinstance(family_names, list)
75
+ else []
76
+ )
77
+ structural_transfer = family_block.get("structural_transfer")
78
+ projected_structural_transfer = (
79
+ opaque_release_id(
80
+ "family",
81
+ structural_transfer,
82
+ spec_version=world.spec_version,
83
+ world_id=world.world_id,
84
+ )
85
+ if isinstance(structural_transfer, str)
86
+ else structural_transfer
87
+ )
88
+ return {
89
+ "schema": SCHEMA_WORLD_METADATA,
90
+ "world_id": world.world_id,
91
+ "lane_id": world.lane_id,
92
+ "spec_version": world.spec_version,
93
+ "pack": {
94
+ "path": pack_path,
95
+ "pack_revision": provenance.get("pack_revision"),
96
+ "provenance_sha256": sha256_file(world.pack_dir / PROVENANCE_FILE),
97
+ "difficulty_sha256": sha256_file(world.pack_dir / DIFFICULTY_FILE),
98
+ "spec": provenance.get("spec"),
99
+ },
100
+ "source_snapshot": provenance.get("source_snapshot"),
101
+ "source_data": provenance.get("source_data"),
102
+ "license": provenance.get("license"),
103
+ "license_attribution": licenses.world_license_attribution(world.world_id),
104
+ "human_review": provenance.get("human_review"),
105
+ "task_counts": {
106
+ "total": task_counts.get("total"),
107
+ "per_split": dict(world.per_split),
108
+ "scenarios": task_counts.get("scenarios"),
109
+ "paraphrase_variants_per_scenario": task_counts.get(
110
+ "paraphrase_variants_per_scenario"
111
+ ),
112
+ },
113
+ "template_families": {
114
+ "families": projected_families,
115
+ "count": family_block.get("count"),
116
+ "structural_transfer": projected_structural_transfer,
117
+ "note": (
118
+ "Release-projected opaque family IDs (fam_<16 hex>). The original "
119
+ "family names and the name-to-ID mapping remain in the private pack."
120
+ ),
121
+ },
122
+ "split_floors": {
123
+ "required": required,
124
+ "met": met,
125
+ "status": floors_status,
126
+ },
127
+ "artifacts": {
128
+ relative: artifact_hashes[relative]
129
+ for relative in PUBLIC_FILES
130
+ if relative in artifact_hashes and relative not in sanitized_files
131
+ },
132
+ "sanitized_files": dict(sanitized_files),
133
+ "release_projection": {
134
+ "sanitized": True,
135
+ "note": (
136
+ "Task rows and public/examples_dev.jsonl are the release "
137
+ "projection of the pack records: verdict-namespace feature "
138
+ "tokens (polarity:*, canonical/counterfactual variant naming) "
139
+ "are removed, polarity-encoding prompt phrasings are "
140
+ "neutralized, and the label-semantic identity fields "
141
+ "(template, template_family, family: features, actions[].variant) "
142
+ "are replaced with deterministic opaque release IDs "
143
+ "(tpl_/fam_/var_<16 hex>). The original names and their "
144
+ "mapping remain in the private pack; labels are not shipped. "
145
+ "All other public files are byte-identical pack copies (see "
146
+ "artifacts)."
147
+ ),
148
+ },
149
+ "task_set_sha256": world.task_set_sha256,
150
+ "oracle": {
151
+ "included": False,
152
+ "note": (
153
+ "Private oracle material (labels, gold ontology/shapes, corruption "
154
+ "manifest, world_rules.py) is not part of this release."
155
+ ),
156
+ },
157
+ }
158
+
159
+
160
+ def _index_row(
161
+ world: ValidatedWorld, pack_path: str, metadata: dict[str, object]
162
+ ) -> dict[str, object]:
163
+ provenance = world.provenance
164
+ snapshot = provenance.get("source_snapshot")
165
+ families = metadata.get("template_families")
166
+ family_count = families.get("count") if isinstance(families, dict) else None
167
+ floors = metadata.get("split_floors")
168
+ floors_status = floors.get("status") if isinstance(floors, dict) else "UNKNOWN"
169
+ return {
170
+ "schema": SCHEMA_WORLD_INDEX,
171
+ "world_id": world.world_id,
172
+ "lane_id": world.lane_id,
173
+ "spec_version": world.spec_version,
174
+ "pack_path": pack_path,
175
+ "task_count": len(world.tasks),
176
+ "per_split": dict(world.per_split),
177
+ "template_families": family_count,
178
+ "split_floors_status": floors_status,
179
+ "source_snapshot_id": snapshot.get("id") if isinstance(snapshot, dict) else None,
180
+ "license": provenance.get("license"),
181
+ "task_set_sha256": world.task_set_sha256,
182
+ "metadata_path": f"worlds/{world.world_id}/metadata.json",
183
+ }
184
+
185
+
186
+ def _check_unique(worlds: list[ValidatedWorld]) -> None:
187
+ seen_worlds: set[str] = set()
188
+ seen_tasks: set[str] = set()
189
+ world_duplicates: list[str] = []
190
+ task_duplicates: list[str] = []
191
+ for world in worlds:
192
+ if world.world_id in seen_worlds:
193
+ world_duplicates.append(f"duplicate_world_id:{world.world_id}")
194
+ seen_worlds.add(world.world_id)
195
+ for task in world.tasks:
196
+ release_id = str(task["release_task_id"])
197
+ if release_id in seen_tasks:
198
+ task_duplicates.append(f"duplicate_release_task_id:{release_id}")
199
+ seen_tasks.add(release_id)
200
+ if world_duplicates or task_duplicates:
201
+ code = "duplicate_world_id" if world_duplicates else "duplicate_release_task_id"
202
+ raise ReleaseError(code, "; ".join(world_duplicates + task_duplicates))
203
+
204
+
205
+ def _guard_output(out: Path, worlds: list[ValidatedWorld], repo_root: Path, force: bool) -> None:
206
+ resolved = out.resolve()
207
+ if resolved == repo_root.resolve() or resolved.parent == resolved:
208
+ raise ReleaseError("release_path_invalid", f"refusing to assemble into {resolved}")
209
+ for world in worlds:
210
+ if resolved == world.pack_dir.resolve():
211
+ raise ReleaseError("release_path_invalid", "output directory is an input pack")
212
+ if resolved.exists() and any(resolved.iterdir()) and not force:
213
+ raise ReleaseError("release_exists", f"{resolved} is non-empty; pass --force")
214
+
215
+
216
+ def _write_release(
217
+ staging: Path, worlds: list[ValidatedWorld], repo_root: Path
218
+ ) -> dict[str, object]:
219
+ staging.mkdir(parents=True, exist_ok=True)
220
+ ordered = sorted(worlds, key=lambda world: world.world_id)
221
+ tasks = [task for world in ordered for task in world.tasks]
222
+ index_rows: list[dict[str, object]] = []
223
+ for world in ordered:
224
+ world_dir = staging / "worlds" / world.world_id
225
+ (world_dir / "public").mkdir(parents=True)
226
+ for relative in PUBLIC_FILES:
227
+ if relative == "public/examples_dev.jsonl":
228
+ continue # re-projected (sanitized) below, not byte-copied
229
+ shutil.copyfile(world.pack_dir / relative, world_dir / relative)
230
+ examples_bytes = jsonl_bytes(list(world.dev_examples))
231
+ (world_dir / "public/examples_dev.jsonl").write_bytes(examples_bytes)
232
+ pack_path = repo_relative(world.pack_dir, repo_root)
233
+ sanitized_files = {"public/examples_dev.jsonl": sha256_bytes(examples_bytes)}
234
+ metadata = _world_metadata(world, pack_path, sanitized_files)
235
+ (world_dir / "metadata.json").write_bytes(json_bytes(metadata))
236
+ index_rows.append(_index_row(world, pack_path, metadata))
237
+ (staging / "tasks").mkdir()
238
+ (staging / "tasks/tasks.jsonl").write_bytes(jsonl_bytes(tasks))
239
+ (staging / "tasks/worlds.jsonl").write_bytes(jsonl_bytes(index_rows))
240
+ per_split = {
241
+ split: sum(world.per_split[split] for world in ordered) for split in SPLIT_NAMES
242
+ }
243
+ (staging / "README.md").write_text(
244
+ render_readme(index_rows, per_split, len(tasks)), encoding="utf-8"
245
+ )
246
+ (staging / "CORE_RELEASE_CONTRACT.md").write_text(render_contract(), encoding="utf-8")
247
+ licenses.write_license_layer(staging, ordered, repo_root)
248
+ entries = tree_entries(staging, _MANIFEST_EXCLUDES)
249
+ body = "".join(f"{entry['sha256']} {entry['path']}\n" for entry in entries)
250
+ (staging / "MANIFEST.sha256").write_text(body, encoding="utf-8")
251
+ manifest = {
252
+ "schema": SCHEMA_RELEASE,
253
+ "release": "core-track-benchmark",
254
+ "release_status": "PACKAGING-FRAMEWORK",
255
+ "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
256
+ "scope": {
257
+ "claim": "benchmark-only packaging of validated Core-track world packs",
258
+ "is_full_core_track_release": False,
259
+ "target_task_count": TARGET_TASK_COUNT,
260
+ "assembled_world_count": len(ordered),
261
+ "assembled_task_count": len(tasks),
262
+ "note": (
263
+ "Not the full 19,947-task Core-track release; these are the real "
264
+ "assembled counts and every record is label-stripped."
265
+ ),
266
+ },
267
+ "worlds": index_rows,
268
+ "totals": {"worlds": len(ordered), "tasks": len(tasks), "per_split": per_split},
269
+ "license": licenses.manifest_license_block(),
270
+ "validation": {
271
+ "pack_contract_version": PACK_CONTRACT_VERSION,
272
+ "status": "PASS",
273
+ "violations": [],
274
+ },
275
+ "file_count": len(entries),
276
+ "root_sha256": sha256_bytes(body.encode("utf-8")),
277
+ "files": entries,
278
+ }
279
+ (staging / "MANIFEST.json").write_bytes(json_bytes(manifest))
280
+ return manifest
281
+
282
+
283
+ def assemble_release(
284
+ packs: list[Path],
285
+ out_dir: Path,
286
+ repo_root: Path,
287
+ *,
288
+ force: bool = False,
289
+ ) -> dict[str, object]:
290
+ """Validate every pack, then write and verify a complete release tree."""
291
+ if not packs:
292
+ raise ReleaseError("missing_pack", "at least one --pack is required")
293
+ repo_root = Path(repo_root)
294
+ worlds: list[ValidatedWorld] = []
295
+ for pack in packs:
296
+ violations, world = collect_violations(Path(pack), repo_root)
297
+ if violations or world is None:
298
+ raise PackContractError(violations)
299
+ worlds.append(world)
300
+ _check_unique(worlds)
301
+ for world in worlds:
302
+ licenses.resolve_world(world.world_id)
303
+ out = Path(out_dir)
304
+ _guard_output(out, worlds, repo_root, force)
305
+ resolved = out.resolve()
306
+ staging = resolved.parent / f".{resolved.name}.staging-{os.getpid()}"
307
+ if staging.exists():
308
+ shutil.rmtree(staging)
309
+ try:
310
+ manifest = _write_release(staging, worlds, repo_root)
311
+ problems = verify_release(staging)
312
+ if problems:
313
+ raise ReleaseError("manifest_drift", "; ".join(problems))
314
+ if resolved.exists():
315
+ shutil.rmtree(resolved)
316
+ staging.replace(resolved)
317
+ except Exception:
318
+ if staging.exists():
319
+ shutil.rmtree(staging, ignore_errors=True)
320
+ raise
321
+ return manifest
322
+
323
+
324
+ __all__ = ["assemble_release"]
core_worlds/src/scripts/core_release/contract.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core-track benchmark release contract v1: pack layout, task schema, IO.
2
+
3
+ The input side is the world-pack contract documented in
4
+ ``docs/CORE_TRACK_SCALE_PLAN.md`` section 1.1 (17 files, filenames exact). This
5
+ module owns the machine-readable version of that contract plus the release-side
6
+ record shapes; it performs no filesystem mutation.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import re
14
+ from pathlib import Path
15
+ from typing import Final, Literal
16
+
17
+ from pydantic import BaseModel, ConfigDict, Field
18
+
19
+ SCHEMA_RELEASE = "aob-core-release/1.0"
20
+ SCHEMA_WORLD_METADATA = "aob-core-world-metadata/1.0"
21
+ SCHEMA_WORLD_INDEX = "aob-core-world-index/1.0"
22
+ PACK_CONTRACT_VERSION: Final = "1"
23
+
24
+ SPLIT_NAMES: Final[tuple[str, ...]] = (
25
+ "dev",
26
+ "hidden_iid",
27
+ "hidden_comp",
28
+ "hidden_transfer",
29
+ )
30
+ SPLIT_FILES: Final[dict[str, str]] = {
31
+ "dev": "private/dev_labels.jsonl",
32
+ "hidden_iid": "private/hidden_iid.jsonl",
33
+ "hidden_comp": "private/hidden_comp.jsonl",
34
+ "hidden_transfer": "private/hidden_transfer.jsonl",
35
+ }
36
+
37
+ PUBLIC_FILES: Final[tuple[str, ...]] = (
38
+ "public/README.md",
39
+ "public/examples_dev.jsonl",
40
+ "public/observations.jsonl",
41
+ "public/ontology_init.ttl",
42
+ "public/probe_api_spec.json",
43
+ "public/shapes_init.ttl",
44
+ "public/source_schema.json",
45
+ )
46
+ PRIVATE_FILES: Final[tuple[str, ...]] = (
47
+ "private/corruption_manifest.json",
48
+ "private/dev_labels.jsonl",
49
+ "private/gold_ontology.ttl",
50
+ "private/gold_shapes.ttl",
51
+ "private/hidden_comp.jsonl",
52
+ "private/hidden_iid.jsonl",
53
+ "private/hidden_transfer.jsonl",
54
+ "private/world_rules.py",
55
+ )
56
+ MANIFEST_FILES: Final[tuple[str, ...]] = (
57
+ "manifests/difficulty.json",
58
+ "manifests/provenance.json",
59
+ )
60
+ PACK_FILES: Final[tuple[str, ...]] = tuple(
61
+ sorted(PUBLIC_FILES + PRIVATE_FILES + MANIFEST_FILES)
62
+ )
63
+ PROVENANCE_FILE: Final = "manifests/provenance.json"
64
+ DIFFICULTY_FILE: Final = "manifests/difficulty.json"
65
+ GOLD_ARTIFACTS: Final[tuple[str, ...]] = (
66
+ "private/gold_ontology.ttl",
67
+ "private/gold_shapes.ttl",
68
+ )
69
+
70
+ PUBLIC_TASK_FIELDS: Final[tuple[str, ...]] = (
71
+ "task_id",
72
+ "world_tag",
73
+ "spec_version",
74
+ "template",
75
+ "template_family",
76
+ "actions",
77
+ "prompt",
78
+ "features",
79
+ "instance_ids",
80
+ "paraphrase_variant",
81
+ )
82
+ RELEASE_TASK_FIELDS: Final[tuple[str, ...]] = (
83
+ "release_task_id",
84
+ "world_id",
85
+ "lane_id",
86
+ "split",
87
+ ) + PUBLIC_TASK_FIELDS
88
+ PRIVATE_TASK_FIELDS: Final[tuple[str, ...]] = (
89
+ "split",
90
+ "scenario",
91
+ "expected",
92
+ "expected_ok",
93
+ "expected_reason",
94
+ "outcomes",
95
+ "counterfactual",
96
+ "label_source",
97
+ )
98
+ # Quoted JSON keys: a raw phrase such as "scenario" may legitimately appear in
99
+ # prose, but a serialized label field in a public file is always a leak.
100
+ LABEL_KEY_TOKENS: Final[tuple[str, ...]] = tuple(
101
+ f'"{field}"' for field in PRIVATE_TASK_FIELDS
102
+ )
103
+
104
+ WORLD_ID_PATTERN: Final = re.compile(r"^world_L(?P<lane>\d{2})$")
105
+ WORLD_TAG_3_PATTERN: Final = re.compile(r"^w\d{3}$")
106
+ WORLD_TAG_4_PATTERN: Final = re.compile(r"^w\d{4}$")
107
+
108
+ # --- Release-only opaque identities ---------------------------------------
109
+ #
110
+ # Public task identity fields (``template``, ``template_family``, ``family:``
111
+ # feature values, ``actions[].variant``) carry names chosen by the world
112
+ # generator, and those names restate the private verdict (``validate_canonical``,
113
+ # ``cf_bad_image`` and similar). The release therefore publishes deterministic
114
+ # opaque IDs instead of the original words. The digest scope binds the domain,
115
+ # the identifier kind, the world's ``spec_version``, the ``world_id``, and the
116
+ # original name: the same original always projects to the same public ID, and
117
+ # unrelated originals cannot collide in practice. Only 16 hex digits of the
118
+ # SHA-256 digest are published, so the original name is not recoverable from
119
+ # the release, while the private pack keeps the name and the mapping.
120
+ OPAQUE_ID_DOMAIN: Final = "aob-core-release/opaque-id/v1"
121
+ OpaqueIdKind = Literal["template", "family", "variant"]
122
+ OPAQUE_ID_PREFIXES: Final[dict[str, str]] = {
123
+ "template": "tpl",
124
+ "family": "fam",
125
+ "variant": "var",
126
+ }
127
+ OPAQUE_ID_PATTERN: Final = re.compile(r"^(?:tpl|fam|var)_[0-9a-f]{16}$")
128
+ LABEL_SOURCE_PATTERN: Final = re.compile(
129
+ r"^[a-z0-9_]+\.[a-z0-9_]+(?:\.[a-z0-9_]+)*\.replay$"
130
+ )
131
+ TASK_ID_PATTERN: Final = r"^task_[0-9]{4}$"
132
+
133
+
134
+ class PackTaskPublic(BaseModel):
135
+ """Public task record; ``extra='forbid'`` is the label-leak gate."""
136
+
137
+ model_config = ConfigDict(extra="forbid", frozen=True)
138
+
139
+ task_id: str = Field(pattern=TASK_ID_PATTERN)
140
+ world_tag: str = Field(min_length=4, max_length=5)
141
+ spec_version: str = Field(min_length=1)
142
+ template: str = Field(min_length=1)
143
+ template_family: str = Field(min_length=1)
144
+ actions: list[dict[str, object]] = Field(min_length=1)
145
+ prompt: str = Field(min_length=1)
146
+ features: list[str]
147
+ instance_ids: list[str] = Field(min_length=1)
148
+ paraphrase_variant: int = Field(ge=0)
149
+
150
+
151
+ class Outcome(BaseModel):
152
+ model_config = ConfigDict(extra="forbid", frozen=True)
153
+
154
+ ok: bool
155
+ reason: str = Field(min_length=1)
156
+ payload: object | None = None
157
+
158
+
159
+ class PackTaskPrivate(PackTaskPublic):
160
+ """Pack-private record: public fields plus replay-derived labels."""
161
+
162
+ split: Literal["dev", "hidden_iid", "hidden_comp", "hidden_transfer"]
163
+ scenario: str = Field(min_length=1)
164
+ expected: str = Field(min_length=1)
165
+ expected_ok: bool
166
+ expected_reason: str = Field(min_length=1)
167
+ outcomes: list[Outcome] = Field(min_length=1)
168
+ counterfactual: object | None = None
169
+ label_source: str = Field(min_length=1)
170
+
171
+
172
+ def read_json(path: Path) -> dict[str, object]:
173
+ loaded = json.loads(path.read_text(encoding="utf-8"))
174
+ if not isinstance(loaded, dict):
175
+ raise ValueError(f"{path} must contain a JSON object")
176
+ return loaded
177
+
178
+
179
+ def read_jsonl(path: Path) -> list[dict[str, object]]:
180
+ records: list[dict[str, object]] = []
181
+ for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
182
+ if not line.strip():
183
+ continue
184
+ loaded = json.loads(line)
185
+ if not isinstance(loaded, dict):
186
+ raise ValueError(f"{path}:{line_number} must contain a JSON object")
187
+ records.append(loaded)
188
+ return records
189
+
190
+
191
+ def sha256_bytes(payload: bytes) -> str:
192
+ return hashlib.sha256(payload).hexdigest()
193
+
194
+
195
+ def sha256_file(path: Path) -> str:
196
+ hasher = hashlib.sha256()
197
+ with path.open("rb") as handle:
198
+ for chunk in iter(lambda: handle.read(1 << 20), b""):
199
+ hasher.update(chunk)
200
+ return hasher.hexdigest()
201
+
202
+
203
+ def canonical_json(record: dict[str, object]) -> str:
204
+ """One sorted-key, compact JSON line (release task records are canonical)."""
205
+ return json.dumps(record, sort_keys=True, ensure_ascii=False)
206
+
207
+
208
+ def jsonl_bytes(records: list[dict[str, object]]) -> bytes:
209
+ return "".join(f"{canonical_json(record)}\n" for record in records).encode("utf-8")
210
+
211
+
212
+ def json_bytes(payload: object) -> bytes:
213
+ return (json.dumps(payload, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode(
214
+ "utf-8"
215
+ )
216
+
217
+
218
+ def repo_relative(path: Path, repo_root: Path) -> str:
219
+ """Repo-relative POSIX path when possible; absolute otherwise."""
220
+ try:
221
+ return path.resolve().relative_to(repo_root.resolve()).as_posix()
222
+ except ValueError:
223
+ return path.resolve().as_posix()
224
+
225
+
226
+ def tree_entries(root: Path, exclude: frozenset[str]) -> list[dict[str, object]]:
227
+ """Sorted ``{path, sha256, bytes}`` for every regular file except ``exclude``."""
228
+ entries: list[dict[str, object]] = []
229
+ for path in sorted(root.rglob("*")):
230
+ if not path.is_file() or path.is_symlink():
231
+ continue
232
+ relative = path.relative_to(root).as_posix()
233
+ if relative in exclude:
234
+ continue
235
+ entries.append(
236
+ {"path": relative, "sha256": sha256_file(path), "bytes": path.stat().st_size}
237
+ )
238
+ return sorted(entries, key=lambda entry: str(entry["path"]))
239
+
240
+
241
+ def public_projection(record: dict[str, object]) -> dict[str, object]:
242
+ """Strip every non-public field from a task record."""
243
+ return {field: record[field] for field in PUBLIC_TASK_FIELDS}
244
+
245
+
246
+ # --- Release-side semantic sanitization -----------------------------------
247
+ #
248
+ # The pack contract keeps full private fidelity; the release projection must
249
+ # additionally drop public tokens that restate the replay verdict. Two
250
+ # channels are covered:
251
+ #
252
+ # 1. Feature tokens whose key or value names the label axis: the
253
+ # ``polarity:accepted|rejected`` namespace (1:1 with ``expected_ok`` on the
254
+ # 2026-11-18 QA scan) and ``variant:`` values drawn from the
255
+ # canonical/counterfactual polarity-naming vocabulary.
256
+ # 2. Prompts that name a polarity-marked state variant (e.g. L01
257
+ # ``gk_validate_bundle`` prompts quoting ``cf_*`` ids or asserting the
258
+ # "canonical compliant" polarity). ``NEUTRAL_PROMPT_TABLE`` replaces them
259
+ # with a per-paraphrase neutral wording; the variant identity stays
260
+ # available in the public ``actions`` parameters, which the world schema
261
+ # declares and the harness requires.
262
+
263
+ LABEL_FEATURE_KEYS: Final[frozenset[str]] = frozenset({"polarity"})
264
+ LABEL_FEATURE_VALUE_PATTERN: Final = re.compile(
265
+ r"^(?:accepted|rejected|canonical|counterfactual(?:_.*)?|cf_.*)$"
266
+ )
267
+ # Gate-only superset: future verdict namespaces are not stripped silently;
268
+ # they fail assembly (``public_semantic_leak``) until a human extends the
269
+ # projection. Keyed by feature-token key (the part before the first colon).
270
+ LABEL_FEATURE_KEY_GATE: Final[frozenset[str]] = frozenset(
271
+ {"polarity", "variant", "expected", "label", "labels", "verdict", "outcome", "answer"}
272
+ )
273
+
274
+ # (spec_version, template_family) -> paraphrase_variant -> neutral prompt.
275
+ NEUTRAL_PROMPT_TABLE: Final[dict[tuple[str, str], dict[int, str]]] = {
276
+ ("gatekeeper_policy/1.0.0", "gk_validate_bundle"): {
277
+ 0: (
278
+ "Validate the cluster state variant named in the task's action list "
279
+ "against the shared SHACL shapes bundle. Report whether the projected "
280
+ "state conforms."
281
+ ),
282
+ 1: (
283
+ "Run SHACL Core validation of the cluster state variant named in the "
284
+ "task's action list with the current shapes bundle and report the "
285
+ "conformance verdict."
286
+ ),
287
+ },
288
+ }
289
+
290
+
291
+ def is_label_feature_token(token: str) -> bool:
292
+ """True when a feature token restates the verdict or its polarity naming."""
293
+ key, _, value = token.partition(":")
294
+ return key in LABEL_FEATURE_KEYS or bool(LABEL_FEATURE_VALUE_PATTERN.match(value))
295
+
296
+
297
+ def opaque_release_id(
298
+ kind: OpaqueIdKind, original: str, *, spec_version: str, world_id: str = ""
299
+ ) -> str:
300
+ """Deterministic opaque release ID for one private identity name.
301
+
302
+ ``kind`` is one of ``template``/``family``/``variant`` and selects the
303
+ public prefix (``tpl``/``fam``/``var``). The SHA-256 scope includes the
304
+ domain tag, the kind, ``spec_version``, ``world_id``, and the original
305
+ name, so IDs are stable across rebuilds and distinct per identity. The
306
+ original words never appear in the result.
307
+ """
308
+ prefix = OPAQUE_ID_PREFIXES.get(kind)
309
+ if prefix is None:
310
+ raise ValueError(f"unknown opaque id kind: {kind!r}")
311
+ material = "\x1f".join((OPAQUE_ID_DOMAIN, kind, spec_version, world_id, original))
312
+ return f"{prefix}_{sha256_bytes(material.encode('utf-8'))[:16]}"
313
+
314
+
315
+ def release_projection(
316
+ record: dict[str, object], *, world_id: str = ""
317
+ ) -> dict[str, object]:
318
+ """Public projection with label-equivalent tokens and identities removed.
319
+
320
+ This is the release boundary: private packs are unchanged, but the public
321
+ row never carries a feature token that is 1:1 with ``expected_ok``, never
322
+ names a private state variant in its prompt, and never exposes the
323
+ generator's label-semantic identity names. ``template``, ``template_family``,
324
+ ``family:`` feature values, and string ``actions[].variant`` values are
325
+ replaced with opaque release IDs (``tpl_…``/``fam_…``/``var_…``). The input
326
+ record is not mutated: nested ``features``/``actions`` are copied.
327
+ """
328
+ row = public_projection(record)
329
+ spec_version = str(record.get("spec_version") or "")
330
+ scope = {"spec_version": spec_version, "world_id": world_id}
331
+
332
+ template = row.get("template")
333
+ if isinstance(template, str):
334
+ row["template"] = opaque_release_id("template", template, **scope)
335
+
336
+ family = row.get("template_family")
337
+ if isinstance(family, str):
338
+ row["template_family"] = opaque_release_id("family", family, **scope)
339
+
340
+ features = row["features"]
341
+ assert isinstance(features, list)
342
+ projected_features: list[str] = []
343
+ for token in features:
344
+ text = str(token)
345
+ if is_label_feature_token(text):
346
+ continue
347
+ key, separator, value = text.partition(":")
348
+ if separator and key == "family" and value:
349
+ projected_features.append(
350
+ f"family:{opaque_release_id('family', value, **scope)}"
351
+ )
352
+ continue
353
+ projected_features.append(text)
354
+ row["features"] = projected_features
355
+
356
+ actions = row["actions"]
357
+ assert isinstance(actions, list)
358
+ projected_actions: list[dict[str, object]] = []
359
+ for action in actions:
360
+ assert isinstance(action, dict)
361
+ copied = dict(action)
362
+ variant = copied.get("variant")
363
+ if isinstance(variant, str):
364
+ copied["variant"] = opaque_release_id("variant", variant, **scope)
365
+ projected_actions.append(copied)
366
+ row["actions"] = projected_actions
367
+
368
+ table = NEUTRAL_PROMPT_TABLE.get(
369
+ (spec_version, str(record.get("template_family")))
370
+ )
371
+ if table is not None:
372
+ variant = record.get("paraphrase_variant")
373
+ neutral = table.get(variant) if isinstance(variant, int) else None
374
+ if neutral is not None:
375
+ row["prompt"] = neutral
376
+ return row
377
+
378
+
379
+ def release_task_row(
380
+ record: dict[str, object],
381
+ *,
382
+ world_id: str,
383
+ lane_id: str,
384
+ split: str,
385
+ ) -> dict[str, object]:
386
+ row = release_projection(record, world_id=world_id)
387
+ row["release_task_id"] = f"{world_id}:{record['task_id']}"
388
+ row["world_id"] = world_id
389
+ row["lane_id"] = lane_id
390
+ row["split"] = split
391
+ return row
core_worlds/src/scripts/core_release/docs_templates.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render the generated release documents (README + contract) deterministically."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from .contract import PACK_CONTRACT_VERSION, SPLIT_NAMES
8
+
9
+ _TEMPLATE_DIR = Path(__file__).with_name("templates")
10
+ _TARGET_TASK_COUNT = 19_947
11
+
12
+ CHECK_DESCRIPTIONS: tuple[tuple[str, str], ...] = (
13
+ ("missing_pack", "pack directory does not exist"),
14
+ ("missing_file", "a required pack file is absent"),
15
+ ("unexpected_file", "a file outside the 17-file contract layout is present"),
16
+ ("artifact_hash_missing", "a pack file is unlisted in provenance.artifacts"),
17
+ ("artifact_hash_unexpected", "provenance.artifacts lists a non-contract path"),
18
+ ("artifact_hash_mismatch", "a declared sha256 does not match the bytes on disk"),
19
+ ("json_parse_error", "a manifest or JSONL file is not valid JSON"),
20
+ ("spec_unresolvable", "provenance.spec.path does not resolve to a file"),
21
+ ("spec_hash_mismatch", "the frozen spec bytes drifted from provenance.spec.sha256"),
22
+ ("spec_not_frozen", "spec status is not 'frozen'"),
23
+ ("spec_parse_error", "the spec file is not a JSON object"),
24
+ ("spec_version_mismatch", "spec_version disagrees across spec/provenance/difficulty"),
25
+ ("taxonomy_missing", "the spec has no non-empty failure_taxonomy"),
26
+ ("world_id_invalid", "world_id is not world_LNN"),
27
+ ("world_id_mismatch", "difficulty and provenance world ids disagree"),
28
+ ("lane_id_mismatch", "spec provenance lane_id disagrees with world_LNN"),
29
+ ("task_schema", "a task record violates the public/private task schema"),
30
+ ("split_field_mismatch", "a record's split field disagrees with its split file"),
31
+ ("duplicate_task_id", "a task id occurs more than once in the pack"),
32
+ ("public_dev_projection_mismatch", "public dev examples are not the stripped dev split"),
33
+ ("paraphrase_split_leak", "paraphrase siblings of one scenario cross splits"),
34
+ ("count_mismatch", "declared total or per-split counts disagree with the files"),
35
+ ("split_count_mismatch", "a split's declared count disagrees with its record count"),
36
+ ("count_formula_mismatch", "total != scenarios x paraphrase variants"),
37
+ ("paraphrase_variant_duplicate", "one scenario repeats a paraphrase variant index"),
38
+ ("label_source_invalid", "label_source is not <family>.<engine>.replay"),
39
+ ("reason_out_of_taxonomy", "a reason code is outside the spec failure_taxonomy"),
40
+ ("template_family_undeclared", "a used or declared transfer family is not in the family list"),
41
+ ("template_family_count_mismatch", "declared family count disagrees with the family list"),
42
+ ("world_tag_invalid", "world_tag is neither wNNN nor wNNNN"),
43
+ ("world_tag_width_mismatch", "tag widths are mixed or disagree with instance_tag_width"),
44
+ ("public_leak", "a public file leaks a hidden id, label key, private path, or gold hash"),
45
+ ("public_semantic_leak", "a release row carries a verdict-namespace feature token, names a private variant/scenario id, or publishes a private/label-word identity value"),
46
+ ("duplicate_world_id", "the same world id was supplied more than once"),
47
+ ("duplicate_release_task_id", "a release_task_id collides across worlds"),
48
+ ("release_exists", "output directory is non-empty and --force was not given"),
49
+ ("release_path_invalid", "output directory is the repo root, filesystem root, or a pack"),
50
+ ("manifest_drift", "a released file's hash/bytes disagree with MANIFEST.sha256"),
51
+ ("unlisted_file", "a file exists in the release tree but not in the manifest"),
52
+ ("forbidden_path", "the release tree contains a private-oracle path"),
53
+ (
54
+ "license_source_missing",
55
+ "a world has no license registry entry, or a declared license text file is absent",
56
+ ),
57
+ )
58
+
59
+
60
+ def _check_table() -> str:
61
+ lines = ["| code | meaning |", "|---|---|"]
62
+ lines.extend(f"| `{code}` | {meaning} |" for code, meaning in CHECK_DESCRIPTIONS)
63
+ return "\n".join(lines)
64
+
65
+
66
+ def _split_totals(per_split: dict[str, int], total: int) -> str:
67
+ lines = ["| split | records |", "|---|---:|"]
68
+ lines.extend(f"| `{split}` | {per_split.get(split, 0)} |" for split in SPLIT_NAMES)
69
+ lines.append(f"| **total** | **{total}** |")
70
+ return "\n".join(lines)
71
+
72
+
73
+ def _world_table(worlds: list[dict[str, object]]) -> str:
74
+ header = (
75
+ "| world_id | lane | spec_version | dev | hidden_iid | hidden_comp | "
76
+ "hidden_transfer | total | floors |"
77
+ )
78
+ lines = [header, "|---|---|---|---:|---:|---:|---:|---:|---|"]
79
+ for world in worlds:
80
+ splits = world["per_split"]
81
+ lines.append(
82
+ "| {world_id} | {lane_id} | {spec_version} | {dev} | {iid} | {comp} | "
83
+ "{transfer} | {total} | {floors} |".format(
84
+ world_id=world["world_id"],
85
+ lane_id=world["lane_id"],
86
+ spec_version=world["spec_version"],
87
+ dev=splits["dev"],
88
+ iid=splits["hidden_iid"],
89
+ comp=splits["hidden_comp"],
90
+ transfer=splits["hidden_transfer"],
91
+ total=world["task_count"],
92
+ floors=world["split_floors_status"],
93
+ )
94
+ )
95
+ return "\n".join(lines)
96
+
97
+
98
+ def _render(template_name: str, replacements: dict[str, str]) -> str:
99
+ text = (_TEMPLATE_DIR / template_name).read_text(encoding="utf-8")
100
+ for token, value in replacements.items():
101
+ text = text.replace(f"{{{{{token}}}}}", value)
102
+ if "{{" in text:
103
+ raise ValueError(f"unrendered template token in {template_name}")
104
+ return text
105
+
106
+
107
+ def render_readme(
108
+ worlds: list[dict[str, object]], per_split: dict[str, int], total: int
109
+ ) -> str:
110
+ return _render(
111
+ "release_README.md",
112
+ {
113
+ "CONTRACT_VERSION": PACK_CONTRACT_VERSION,
114
+ "WORLD_COUNT": str(len(worlds)),
115
+ "TASK_COUNT": str(total),
116
+ "SPLIT_TOTALS": _split_totals(per_split, total),
117
+ "WORLD_TABLE": _world_table(worlds),
118
+ },
119
+ )
120
+
121
+
122
+ def render_contract() -> str:
123
+ return _render(
124
+ "release_contract.md",
125
+ {
126
+ "CONTRACT_VERSION": PACK_CONTRACT_VERSION,
127
+ "CHECK_TABLE": _check_table(),
128
+ },
129
+ )
130
+
131
+
132
+ TARGET_TASK_COUNT = _TARGET_TASK_COUNT
core_worlds/src/scripts/core_release/errors.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed errors shared by the release assembler and its validators."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True, slots=True)
9
+ class Violation:
10
+ """One machine-checkable contract failure.
11
+
12
+ ``code`` is a stable token tests and operators key on; ``where`` is the
13
+ pack- or release-relative location; ``message`` is human detail.
14
+ """
15
+
16
+ code: str
17
+ where: str
18
+ message: str
19
+
20
+ def describe(self) -> str:
21
+ return f"{self.code} [{self.where}] {self.message}"
22
+
23
+
24
+ class PackContractError(Exception):
25
+ """Raised when one or more input world packs violate the pack contract."""
26
+
27
+ def __init__(self, violations: list[Violation]) -> None:
28
+ if not violations:
29
+ raise ValueError("PackContractError requires at least one violation")
30
+ self.violations = tuple(violations)
31
+ detail = "\n".join(f" {violation.describe()}" for violation in self.violations)
32
+ super().__init__(f"{len(self.violations)} contract violation(s):\n{detail}")
33
+
34
+
35
+ class ReleaseError(Exception):
36
+ """Raised when the release itself cannot be assembled or verified."""
37
+
38
+ def __init__(self, code: str, message: str) -> None:
39
+ self.code = code
40
+ super().__init__(f"{code}: {message}")
core_worlds/src/scripts/core_release/labels.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Label provenance checks: replay-sourced labels, spec versions, taxonomy codes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .contract import LABEL_SOURCE_PATTERN, SPLIT_NAMES
6
+ from .errors import Violation
7
+
8
+
9
+ def check_labels(
10
+ by_split: dict[str, list[dict[str, object]]],
11
+ provenance: dict[str, object],
12
+ spec: dict[str, object],
13
+ violations: list[Violation],
14
+ ) -> None:
15
+ taxonomy = spec.get("failure_taxonomy")
16
+ taxonomy_keys = set(taxonomy) if isinstance(taxonomy, dict) else set()
17
+ spec_block = provenance.get("spec")
18
+ expected_version = spec_block.get("spec_version") if isinstance(spec_block, dict) else None
19
+ for split in SPLIT_NAMES:
20
+ for record in by_split[split]:
21
+ task_id = str(record.get("task_id"))
22
+ if record.get("spec_version") != expected_version:
23
+ violations.append(
24
+ Violation(
25
+ "spec_version_mismatch",
26
+ task_id,
27
+ f"record spec_version != {expected_version!r}",
28
+ )
29
+ )
30
+ if not LABEL_SOURCE_PATTERN.match(str(record.get("label_source", ""))):
31
+ violations.append(
32
+ Violation(
33
+ "label_source_invalid",
34
+ task_id,
35
+ "label_source is not <family>.<engine>.replay",
36
+ )
37
+ )
38
+ outcomes = record.get("outcomes")
39
+ reasons = [record.get("expected_reason")]
40
+ if isinstance(outcomes, list):
41
+ reasons.extend(
42
+ outcome.get("reason") if isinstance(outcome, dict) else None
43
+ for outcome in outcomes
44
+ )
45
+ for reason in reasons:
46
+ if taxonomy_keys and reason not in taxonomy_keys:
47
+ violations.append(
48
+ Violation(
49
+ "reason_out_of_taxonomy", task_id, f"reason {reason!r} not in spec"
50
+ )
51
+ )
core_worlds/src/scripts/core_release/layout.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pack structure checks: 17-file layout, artifact hashes, spec, world identity."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ from .contract import (
9
+ DIFFICULTY_FILE,
10
+ PACK_FILES,
11
+ PROVENANCE_FILE,
12
+ WORLD_ID_PATTERN,
13
+ read_json,
14
+ sha256_file,
15
+ )
16
+ from .errors import Violation
17
+
18
+
19
+ def ignored(relative: Path) -> bool:
20
+ return "__pycache__" in relative.parts or relative.suffix == ".pyc"
21
+
22
+
23
+ def object_field(value: object, field: str) -> dict[str, object]:
24
+ if not isinstance(value, dict):
25
+ raise ValueError(f"{field} must be a JSON object")
26
+ return value
27
+
28
+
29
+ def check_layout(pack: Path, violations: list[Violation]) -> bool:
30
+ present = {
31
+ path.relative_to(pack).as_posix()
32
+ for path in pack.rglob("*")
33
+ if path.is_file() and not ignored(path.relative_to(pack))
34
+ }
35
+ complete = True
36
+ for relative in PACK_FILES:
37
+ if relative not in present:
38
+ complete = False
39
+ violations.append(Violation("missing_file", relative, "required pack file absent"))
40
+ for relative in sorted(present - set(PACK_FILES)):
41
+ violations.append(Violation("unexpected_file", relative, "not part of contract v1"))
42
+ return complete
43
+
44
+
45
+ def check_hashes(
46
+ pack: Path, provenance: dict[str, object], violations: list[Violation]
47
+ ) -> None:
48
+ artifacts = provenance.get("artifacts")
49
+ if not isinstance(artifacts, dict):
50
+ violations.append(
51
+ Violation("artifact_hash_missing", PROVENANCE_FILE, "artifacts block absent")
52
+ )
53
+ return
54
+ expected = {relative for relative in PACK_FILES if relative != PROVENANCE_FILE}
55
+ declared_paths = {str(path) for path in artifacts}
56
+ for relative in sorted(expected - declared_paths):
57
+ violations.append(
58
+ Violation("artifact_hash_missing", relative, "not listed in provenance.artifacts")
59
+ )
60
+ for relative in sorted(declared_paths - expected):
61
+ violations.append(
62
+ Violation("artifact_hash_unexpected", relative, "hashed path is not a pack file")
63
+ )
64
+ for relative in sorted(expected & declared_paths):
65
+ declared = artifacts[relative]
66
+ actual = sha256_file(pack / relative)
67
+ if declared != actual:
68
+ violations.append(
69
+ Violation(
70
+ "artifact_hash_mismatch",
71
+ relative,
72
+ f"declared {declared} != on-disk {actual}",
73
+ )
74
+ )
75
+
76
+
77
+ def load_spec(
78
+ repo_root: Path, provenance: dict[str, object], violations: list[Violation]
79
+ ) -> dict[str, object] | None:
80
+ spec_block = provenance.get("spec")
81
+ if not isinstance(spec_block, dict):
82
+ violations.append(Violation("spec_unresolvable", PROVENANCE_FILE, "spec block absent"))
83
+ return None
84
+ raw_path = spec_block.get("path")
85
+ if not isinstance(raw_path, str) or not raw_path:
86
+ violations.append(Violation("spec_unresolvable", PROVENANCE_FILE, "spec.path absent"))
87
+ return None
88
+ spec_path = Path(raw_path)
89
+ if not spec_path.is_absolute():
90
+ spec_path = repo_root / spec_path
91
+ if not spec_path.is_file():
92
+ violations.append(Violation("spec_unresolvable", raw_path, "spec file not found"))
93
+ return None
94
+ if sha256_file(spec_path) != spec_block.get("sha256"):
95
+ violations.append(Violation("spec_hash_mismatch", raw_path, "spec bytes drifted"))
96
+ if spec_block.get("status") != "frozen":
97
+ violations.append(Violation("spec_not_frozen", raw_path, "spec.status must be 'frozen'"))
98
+ try:
99
+ spec = read_json(spec_path)
100
+ except (ValueError, json.JSONDecodeError) as exc:
101
+ violations.append(Violation("spec_parse_error", raw_path, str(exc)))
102
+ return None
103
+ if spec.get("spec_version") != spec_block.get("spec_version"):
104
+ violations.append(
105
+ Violation("spec_version_mismatch", raw_path, "spec_version != provenance.spec_version")
106
+ )
107
+ taxonomy = spec.get("failure_taxonomy")
108
+ if not isinstance(taxonomy, dict) or not taxonomy:
109
+ violations.append(
110
+ Violation("taxonomy_missing", raw_path, "failure_taxonomy must be a non-empty object")
111
+ )
112
+ return spec
113
+
114
+
115
+ def check_world_identity(
116
+ provenance: dict[str, object],
117
+ difficulty: dict[str, object],
118
+ spec: dict[str, object],
119
+ violations: list[Violation],
120
+ ) -> tuple[str, str] | None:
121
+ world_id = difficulty.get("world_id")
122
+ if not isinstance(world_id, str) or not WORLD_ID_PATTERN.match(world_id):
123
+ violations.append(
124
+ Violation("world_id_invalid", DIFFICULTY_FILE, f"world_id {world_id!r} is not world_LNN")
125
+ )
126
+ return None
127
+ if provenance.get("world_id") != world_id:
128
+ violations.append(
129
+ Violation(
130
+ "world_id_mismatch",
131
+ PROVENANCE_FILE,
132
+ f"provenance.world_id {provenance.get('world_id')!r} != difficulty {world_id!r}",
133
+ )
134
+ )
135
+ spec_block = provenance.get("spec")
136
+ declared_version = spec_block.get("spec_version") if isinstance(spec_block, dict) else None
137
+ if difficulty.get("spec_version") != declared_version:
138
+ violations.append(
139
+ Violation("spec_version_mismatch", DIFFICULTY_FILE, "difficulty spec_version drifted")
140
+ )
141
+ match = WORLD_ID_PATTERN.match(world_id)
142
+ lane_id = f"L{match.group('lane') if match else ''}"
143
+ spec_provenance = spec.get("provenance")
144
+ if isinstance(spec_provenance, dict) and spec_provenance.get("lane_id") not in (None, lane_id):
145
+ violations.append(Violation("lane_id_mismatch", "spec.provenance", f"lane_id != {lane_id}"))
146
+ return world_id, lane_id
core_worlds/src/scripts/core_release/leakage.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Public-surface leakage checks (hidden ids, label keys, private paths, gold hashes)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from .contract import GOLD_ARTIFACTS, LABEL_KEY_TOKENS, PUBLIC_FILES, SPLIT_NAMES
8
+ from .errors import Violation
9
+
10
+
11
+ def check_leakage(
12
+ pack: Path,
13
+ by_split: dict[str, list[dict[str, object]]],
14
+ provenance: dict[str, object],
15
+ violations: list[Violation],
16
+ ) -> None:
17
+ hidden_ids = [
18
+ str(record.get("task_id"))
19
+ for split in SPLIT_NAMES
20
+ if split != "dev"
21
+ for record in by_split[split]
22
+ ]
23
+ artifacts = provenance.get("artifacts")
24
+ artifact_hashes = artifacts if isinstance(artifacts, dict) else {}
25
+ needles = [
26
+ *hidden_ids,
27
+ "private/",
28
+ *(str(artifact_hashes[path]) for path in GOLD_ARTIFACTS if path in artifact_hashes),
29
+ ]
30
+ for relative in PUBLIC_FILES:
31
+ text = (pack / relative).read_text(encoding="utf-8", errors="replace")
32
+ for needle in needles:
33
+ if needle and needle in text:
34
+ violations.append(
35
+ Violation("public_leak", relative, f"public file contains {needle!r}")
36
+ )
37
+ for token in LABEL_KEY_TOKENS:
38
+ if token in text:
39
+ violations.append(
40
+ Violation("public_leak", relative, f"public file contains label key {token}")
41
+ )
core_worlds/src/scripts/core_release/license_registry.py ADDED
@@ -0,0 +1,599 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # noqa: SIZE_OK — declarative per-source/per-world license registry (a pure
2
+ # data table; splitting it would scatter one auditable legal mapping).
3
+ """License/attribution registry for the Core-track benchmark release.
4
+
5
+ Static, hand-audited data keyed by ``world_id``: which upstream sources a world
6
+ derives from, which license/attribution files ship verbatim in
7
+ ``LICENSES/<source_id>/`` (each with its repo-relative origin), and how every
8
+ license reference in the world's ``metadata.json::license`` string resolves
9
+ (shipped into the release, or explicitly marked not shipped with a reason).
10
+
11
+ Nothing here is fetched or copied at runtime beyond reading the declared
12
+ origin files; the registry is the single place that maps a world to its
13
+ upstream license evidence.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass
19
+ from typing import Final, Literal
20
+
21
+ from .errors import ReleaseError
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class BundleFile:
26
+ """One file shipped under ``LICENSES/<source_id>/`` in the release."""
27
+
28
+ dest: str # path relative to LICENSES/<source_id>/
29
+ origin: str # repo-relative path read verbatim at assembly time
30
+ note: str # one-line provenance note for the per-source SUMMARY.md
31
+
32
+
33
+ @dataclass(frozen=True, slots=True)
34
+ class SourceLicense:
35
+ """One upstream source's license posture and shipped evidence files."""
36
+
37
+ source_id: str
38
+ license_label: str
39
+ attribution: str
40
+ obligation: str
41
+ files: tuple[BundleFile, ...]
42
+ notes: tuple[str, ...] = ()
43
+ citations: tuple[str, ...] = ()
44
+
45
+
46
+ @dataclass(frozen=True, slots=True)
47
+ class Reference:
48
+ """Resolution of one license pointer from a world's metadata."""
49
+
50
+ pointer: str # the reference as it appears in metadata/provenance
51
+ status: Literal["shipped", "not_shipped"]
52
+ paths: tuple[str, ...] = () # release-relative paths (status == "shipped")
53
+ detail: str = "" # note (shipped) or reason (not_shipped)
54
+
55
+
56
+ @dataclass(frozen=True, slots=True)
57
+ class WorldLicense:
58
+ """Per-world license wiring: sources used + declared reference resolutions."""
59
+
60
+ world_id: str
61
+ sources: tuple[str, ...]
62
+ references: tuple[Reference, ...] = ()
63
+ snapshot_pointer: str = "source_snapshot/"
64
+ snapshot_note: str = (
65
+ "License/attribution texts copied verbatim from the pinned source "
66
+ "snapshot; snapshot hash manifests (SNAPSHOT.json) and fetch receipts "
67
+ "recording build-machine absolute paths remain in the repository."
68
+ )
69
+
70
+
71
+ _V3: Final = "release_v3/LICENSES"
72
+ _REGISTRY: Final = "sources/registry.d"
73
+
74
+
75
+ def _snap(world: str) -> str:
76
+ return f"pilot_worlds/{world}_scaleup/source_snapshot"
77
+
78
+
79
+ def _receipt(name: str) -> BundleFile:
80
+ return BundleFile(
81
+ dest=f"registry_receipts/{name}.yaml",
82
+ origin=f"{_REGISTRY}/{name}.yaml",
83
+ note=f"verbatim copy of the source-registry receipt {_REGISTRY}/{name}.yaml",
84
+ )
85
+
86
+
87
+ SOURCES: Final[dict[str, SourceLicense]] = {
88
+ "apis-guru": SourceLicense(
89
+ source_id="apis-guru",
90
+ license_label="repo-level CC0-1.0 + per-spec upstream licenses",
91
+ attribution="APIs.guru (APIs-guru/openapi-directory on GitHub) and the per-spec publishers as indexed.",
92
+ obligation=(
93
+ "Metadata-only posture: the release ships the pinned unit index hashes, "
94
+ "no OpenAPI spec content; per-spec upstream license obligations pass to "
95
+ "the user."
96
+ ),
97
+ files=(
98
+ BundleFile("LICENSE", f"{_V3}/apis-guru/LICENSE", "CC0 1.0 legal code of the pinned openapi-directory repo"),
99
+ BundleFile("APIS_GURU_LICENSE.txt", f"{_snap('world_L13')}/APIS_GURU_LICENSE.txt", "license statement copied verbatim from the pinned source snapshot"),
100
+ ),
101
+ notes=(
102
+ "No sources/registry.d/apis-guru.yaml exists in this repository state "
103
+ "(recorded in the world license field and the snapshot declaration).",
104
+ ),
105
+ citations=("apis-guru openapi-directory, pinned commit f04b8d0bcd39.",),
106
+ ),
107
+ "behavior-1k-bddl": SourceLicense(
108
+ source_id="behavior-1k-bddl",
109
+ license_label="MIT",
110
+ attribution="Stanford Vision and Learning Lab, 2021.",
111
+ obligation="Retain the MIT notice.",
112
+ files=(
113
+ BundleFile("LICENSE", f"{_V3}/behavior-1k-bddl/LICENSE", "MIT license text of the pinned BEHAVIOR-1K bddl repository"),
114
+ BundleFile("BEHAVIOR_LICENSE.txt", f"{_snap('world_L10')}/BEHAVIOR_LICENSE.txt", "license statement copied verbatim from the world_L10 pinned source snapshot"),
115
+ BundleFile("BDDL_LICENSE.txt", f"{_snap('world_L11')}/BDDL_LICENSE.txt", "license statement copied verbatim from the world_L11 pinned source snapshot"),
116
+ _receipt("behavior"),
117
+ ),
118
+ citations=(
119
+ "BEHAVIOR-1K bddl3 activity definitions and knowledge tables, tag "
120
+ "v3.9.3-post2 (commit a8247a8cc1633fe1ca0cc66aa07243d46c64f155).",
121
+ ),
122
+ ),
123
+ "behavior-1k-omnigibson": SourceLicense(
124
+ source_id="behavior-1k-omnigibson",
125
+ license_label="assets non-redistributable (NVIDIA Omniverse EULA + BEHAVIOR-1K data license)",
126
+ attribution="Stanford Vision and Learning Lab (OmniGibson code, MIT); BEHAVIOR-1K scene/object assets are license-gated.",
127
+ obligation=(
128
+ "No asset content ships in this release; re-verification requires the "
129
+ "caller to accept the upstream licenses (the harness refuses to run "
130
+ "otherwise)."
131
+ ),
132
+ files=(
133
+ BundleFile("OMNIGIBSON_ASSETS_LICENSE.txt", f"{_snap('world_L11')}/OMNIGIBSON_ASSETS_LICENSE.txt", "asset-license statement copied verbatim from the world_L11 pinned source snapshot"),
134
+ ),
135
+ notes=(
136
+ "The OmniGibson/Isaac Sim embodied layer is not part of this release; "
137
+ "the L11 pack's embodied certification leg is recorded BLOCKED "
138
+ "(ModuleNotFoundError: omnigibson) in the pack's "
139
+ "verification/native_certification.json.",
140
+ ),
141
+ ),
142
+ "biomodels": SourceLicense(
143
+ source_id="biomodels",
144
+ license_label="per-model CC0-1.0 / no in-file license block (build-time scan)",
145
+ attribution="BioModels (EMBL-EBI) and the per-model authors as indexed.",
146
+ obligation=(
147
+ "The pack embeds no SBML bytes; per-model license scan results and "
148
+ "attribution are recorded in BIOMODELS_LICENSE.txt."
149
+ ),
150
+ files=(
151
+ BundleFile("BIOMODELS_LICENSE.txt", f"{_snap('world_L07')}/BIOMODELS_LICENSE.txt", "per-model dc:license scan copied verbatim from the pinned source snapshot"),
152
+ _receipt("biomodels"),
153
+ ),
154
+ notes=(
155
+ "Per-model licenses are not machine-readable upstream; the build-time "
156
+ "scan over the 102 pinned models is shipped verbatim.",
157
+ ),
158
+ citations=("BioModels api-20261028 slice, 102 models per the spec's universe rule.",),
159
+ ),
160
+ "camunda-dmn-examples": SourceLicense(
161
+ source_id="camunda-dmn-examples",
162
+ license_label="Apache-2.0",
163
+ attribution="Camunda. Copyright 2013-2025 Camunda Services GmbH.",
164
+ obligation="Retain the Apache-2.0 LICENSE and NOTICE files per pinned commit.",
165
+ files=(
166
+ BundleFile("LICENSE.commit-6c7f4c4adb4b", f"{_V3}/camunda-dmn-examples/LICENSE.commit-6c7f4c4adb4b", "Apache-2.0 text of the pinned examples commit"),
167
+ BundleFile("LICENSE.commit-ee4826e5e76c", f"{_V3}/camunda-dmn-examples/LICENSE.commit-ee4826e5e76c", "Apache-2.0 text of the pinned engine-test commit (camunda-bpm-platform)"),
168
+ BundleFile("NOTICE.commit-6c7f4c4adb4b", f"{_V3}/camunda-dmn-examples/NOTICE.commit-6c7f4c4adb4b", "NOTICE of the pinned examples commit"),
169
+ BundleFile("NOTICE.commit-ee4826e5e76c", f"{_V3}/camunda-dmn-examples/NOTICE.commit-ee4826e5e76c", "NOTICE of the pinned engine-test commit"),
170
+ BundleFile("DMN_LICENSES.txt", f"{_snap('world_L03')}/DMN_LICENSES.txt", "license statement copied verbatim from the pinned source snapshot"),
171
+ _receipt("camunda"),
172
+ ),
173
+ notes=(
174
+ "The second pinned tarball is camunda-bpm-platform engine-test tables "
175
+ "filed under the camunda-dmn-examples source id; same Apache-2.0 license.",
176
+ ),
177
+ citations=(
178
+ "camunda-dmn-examples pinned commits 6c7f4c4adb4b (demo) and "
179
+ "ee4826e5e76c (engine-test).",
180
+ ),
181
+ ),
182
+ "chembl": SourceLicense(
183
+ source_id="chembl",
184
+ license_label="CC BY-SA 3.0",
185
+ attribution="ChEMBL database (EMBL-EBI), DOI 10.6019/CHEMBL.database.37.",
186
+ obligation=(
187
+ "Attribution per REQUIRED.ATTRIBUTION; preserve ChEMBL IDs and the "
188
+ "release number; share-alike terms apply to derivative adaptations of "
189
+ "the database."
190
+ ),
191
+ files=(
192
+ BundleFile("LICENSE", f"{_V3}/chembl/LICENSE", "CC BY-SA 3.0 legal code of the pinned ChEMBL 37 snapshot"),
193
+ BundleFile("REQUIRED.ATTRIBUTION", f"{_V3}/chembl/REQUIRED.ATTRIBUTION", "required attribution text of the pinned ChEMBL 37 snapshot"),
194
+ BundleFile("CHEMBL_LICENSE.txt", f"{_snap('world_L14')}/CHEMBL_LICENSE.txt", "license statement copied verbatim from the pinned source snapshot"),
195
+ ),
196
+ citations=(
197
+ "Mendez D, Gaulton A, Bento AP, et al. ChEMBL: towards direct "
198
+ "deposition of bioassay data. Nucleic Acids Res. "
199
+ "2019;47(D1):D930-D940. DOI: 10.1093/nar/gky1075.",
200
+ ),
201
+ ),
202
+ "cql-clinical": SourceLicense(
203
+ source_id="cql-clinical",
204
+ license_label="Apache-2.0; vendored Node.js runtime MIT",
205
+ attribution="CQL is published by HL7; reference implementation by the CQFramework project.",
206
+ obligation="Retain the Apache-2.0 LICENSE.",
207
+ files=(
208
+ BundleFile("LICENSE", f"{_V3}/cql-clinical/LICENSE", "Apache-2.0 text of the pinned clinical_quality_language commit"),
209
+ BundleFile("CQL_LICENSE.txt", f"{_snap('world_L08')}/CQL_LICENSE.txt", "license statement copied verbatim from the pinned source snapshot"),
210
+ _receipt("cql"),
211
+ ),
212
+ notes=("Panels and rule libraries are fully synthetic; no PHI.",),
213
+ citations=(
214
+ "clinical_quality_language pinned commit "
215
+ "bc0c795e4f2a26e8ec3488efd3287e37a86983f8.",
216
+ ),
217
+ ),
218
+ "dmn-tck": SourceLicense(
219
+ source_id="dmn-tck",
220
+ license_label="Apache-2.0",
221
+ attribution="OMG DMN Technology Compatibility Kit (dmn-tck/tck).",
222
+ obligation="Retain the Apache-2.0 license text (LICENSE-ASL-2.0.txt).",
223
+ files=(
224
+ BundleFile("LICENSE-ASL-2.0.txt", f"{_V3}/dmn-tck/LICENSE-ASL-2.0.txt", "Apache-2.0 text of the pinned dmn-tck commit"),
225
+ ),
226
+ notes=(
227
+ "The on-disk fetch receipt's license field reads 'MIT' — stale, "
228
+ "recorded, receipt left untouched per the isolation contract (see "
229
+ "camunda-dmn-examples/DMN_LICENSES.txt).",
230
+ ),
231
+ citations=("dmn-tck conformance-test fixtures, pinned commit 1e349176e5ae.",),
232
+ ),
233
+ "gatekeeper-library": SourceLicense(
234
+ source_id="gatekeeper-library",
235
+ license_label="Apache-2.0",
236
+ attribution="Gatekeeper library. Copyright 2018-2020 The Gatekeeper Authors.",
237
+ obligation="Retain the Apache-2.0 LICENSE and NOTICE with any redistribution of the pinned rule units.",
238
+ files=(
239
+ BundleFile("LICENSE", f"{_snap('world_L01')}/gatekeeper-library/LICENSE", "Apache-2.0 text copied verbatim from the pinned source snapshot"),
240
+ BundleFile("NOTICE", f"{_V3}/gatekeeper-library/NOTICE", "NOTICE of the pinned gatekeeper-library commit"),
241
+ _receipt("gatekeeper"),
242
+ ),
243
+ citations=(
244
+ "Open Policy Agent Gatekeeper policy library, pinned commit "
245
+ "a8d4799d8dafd47ec5fafe945ef277d329e2cceb.",
246
+ ),
247
+ ),
248
+ "gene-ontology": SourceLicense(
249
+ source_id="gene-ontology",
250
+ license_label="CC-BY-4.0",
251
+ attribution="The Gene Ontology Consortium; EMBL-EBI GOA.",
252
+ obligation="CC BY 4.0 attribution to the Gene Ontology Consortium.",
253
+ files=(
254
+ BundleFile("GO_LICENSE.txt", f"{_snap('world_L06')}/GO_LICENSE.txt", "license statement copied verbatim from the pinned source snapshot"),
255
+ _receipt("go"),
256
+ ),
257
+ notes=(
258
+ "The GOA human annotation file (goa_human.gaf.238.gz) carries no "
259
+ "standalone pinned license file; CC BY 4.0 is asserted per EBI GOA "
260
+ "standard terms and recorded in the registry receipt — open item "
261
+ "flagged to the PI.",
262
+ ),
263
+ citations=("go-basic.obo go-2026-08-05; GOA human annotations goa238.",),
264
+ ),
265
+ "kubernetes-vap-cel": SourceLicense(
266
+ source_id="kubernetes-vap-cel",
267
+ license_label="CC-BY-4.0 (documentation), Apache-2.0 (code examples)",
268
+ attribution="The Kubernetes Authors.",
269
+ obligation="Credit the Kubernetes authors, link the CC BY 4.0 license, and indicate changes.",
270
+ files=(
271
+ BundleFile("LICENSE", f"{_V3}/kubernetes-vap-cel/LICENSE", "CC BY 4.0 legal code of the pinned kubernetes/website shard"),
272
+ BundleFile("SNAPSHOT_LICENSE.txt", f"{_snap('world_L02')}/LICENSE.txt", "license statement copied verbatim from the pinned source snapshot"),
273
+ _receipt("cel"),
274
+ ),
275
+ citations=(
276
+ "kubernetes/website validating-admission-policy docs shard, pinned "
277
+ "commit ed70e311737a341574ed5758b7af24e3bba232cb.",
278
+ ),
279
+ ),
280
+ "pm4py-process": SourceLicense(
281
+ source_id="pm4py-process",
282
+ license_label="AGPL-3.0-or-later",
283
+ attribution="Process Intelligence Solutions GmbH (pm4py authors).",
284
+ obligation=(
285
+ "Fetch-recipe posture: the full AGPL-3.0 license text ships here; "
286
+ "upstream event-log content is referenced by hash, not bundled."
287
+ ),
288
+ files=(
289
+ BundleFile("LICENSE", f"{_V3}/pm4py-process/LICENSE", "AGPL-3.0 text of the pinned pm4py tag"),
290
+ BundleFile("PM4PY_LICENSE.txt", f"{_snap('world_L12')}/PM4PY_LICENSE.txt", "license statement copied verbatim from the pinned source snapshot"),
291
+ ),
292
+ notes=(
293
+ "No sources/registry.d receipt exists for pm4py-process in this "
294
+ "repository state (recorded in the world license field).",
295
+ "Whether derived task data triggers AGPL obligations is an open legal "
296
+ "question flagged for PI/legal review; no pm4py code ships in this "
297
+ "release.",
298
+ ),
299
+ citations=("pm4py tag 2.7.23.11 test artifacts.",),
300
+ ),
301
+ "reactome": SourceLicense(
302
+ source_id="reactome",
303
+ license_label="CC0-1.0 (database data)",
304
+ attribution="Reactome (reactome.org).",
305
+ obligation=(
306
+ "CC0 data; pathway illustrations/icons/art are CC BY 4.0 and are NOT "
307
+ "part of this release (data-only lane)."
308
+ ),
309
+ files=(
310
+ BundleFile("REACTOME_LICENSE.txt", f"{_snap('world_L15')}/REACTOME_LICENSE.txt", "license statement copied verbatim from the pinned source snapshot"),
311
+ BundleFile("fetch_receipt.json", f"{_snap('world_L15')}/fetch_receipt.json", "pinned fetch evidence recording the license verdict (byte-identical to external_knowledge/fetch_receipts/reactome/receipt-release-98.json)"),
312
+ ),
313
+ notes=(
314
+ "fetch_receipt.json is the only fetch receipt bundled in this "
315
+ "release: it contains no build-machine absolute paths.",
316
+ ),
317
+ citations=("Reactome release-98.",),
318
+ ),
319
+ "rhea-chebi": SourceLicense(
320
+ source_id="rhea-chebi",
321
+ license_label="Rhea CC-BY-4.0; ChEBI CC-BY-4.0",
322
+ attribution="Rhea (SIB Swiss Institute of Bioinformatics); ChEBI (European Bioinformatics Institute, EMBL-EBI).",
323
+ obligation=(
324
+ "Reproduce the Rhea copyright statement with each copy "
325
+ "(rhea_LICENSE.txt); provide ChEBI attribution and the release "
326
+ "identifier. ChEBI is CC BY 4.0; no ShareAlike obligation is asserted."
327
+ ),
328
+ files=(
329
+ BundleFile("rhea_LICENSE.txt", f"{_snap('world_L04')}/rhea_LICENSE.txt", "Rhea license/copyright statement copied verbatim from the pinned source snapshot"),
330
+ BundleFile("chebi_LICENSE", f"{_snap('world_L04')}/chebi_LICENSE", "pinned ChEBI license text copied verbatim from the source snapshot"),
331
+ BundleFile("chebi_README", f"{_snap('world_L04')}/chebi_README", "pinned ChEBI README copied verbatim from the source snapshot"),
332
+ _receipt("rhea"),
333
+ _receipt("chebi"),
334
+ ),
335
+ notes=(
336
+ "ChEBI's current license is CC BY 4.0. The pinned ChEBI README "
337
+ "contains a stale ShareAlike line, but the pinned chebi_LICENSE, "
338
+ "the ChEBI GitHub LICENSE, EMBL-EBI's current training terms, and "
339
+ "the 2025 ChEBI paper all state CC BY 4.0. The release follows the "
340
+ "pinned LICENSE text; attribution to ChEBI and release 256 is "
341
+ "required.",
342
+ ),
343
+ citations=("Rhea release 142; ChEBI release 256.",),
344
+ ),
345
+ "rdkit-molecules": SourceLicense(
346
+ source_id="rdkit-molecules",
347
+ license_label="RDKit BSD-3-Clause; ChEBI CC-BY-4.0",
348
+ attribution="Rational Discovery LLC, Greg Landrum, Julie Penzotti and others (RDKit); ChEBI (EMBL-EBI).",
349
+ obligation="Retain the BSD-3-Clause notice for RDKit content; CC BY 4.0 attribution for ChEBI structures.",
350
+ files=(
351
+ BundleFile("RDKIT_LICENSE.txt", f"{_snap('world_L05')}/RDKIT_LICENSE.txt", "license statement copied verbatim from the pinned source snapshot"),
352
+ BundleFile("CHEBI_LICENSE.txt", f"{_snap('world_L05')}/CHEBI_LICENSE.txt", "license statement copied verbatim from the pinned source snapshot"),
353
+ BundleFile("rdkit_license.txt", f"{_V3}/rdkit-molecules/rdkit_license.txt", "RDKit BSD-3-Clause license text"),
354
+ BundleFile("chebi_SDF_LICENSE", f"{_V3}/rdkit-molecules/chebi_SDF_LICENSE", "CC BY 4.0 legal code of the pinned ChEBI rel255 SDF"),
355
+ _receipt("rdkit"),
356
+ _receipt("chebi"),
357
+ ),
358
+ citations=(
359
+ "RDKit Release_2026_09_1 functional-group hierarchy; ChEBI release "
360
+ "255 3-star structures.",
361
+ ),
362
+ ),
363
+ "smart-anc": SourceLicense(
364
+ source_id="smart-anc",
365
+ license_label="CC0-1.0",
366
+ attribution="World Health Organization (WHO).",
367
+ obligation="CC0 requires no attribution; WHO is credited regardless.",
368
+ files=(
369
+ BundleFile("LICENSE.md", f"{_V3}/smart-anc/LICENSE.md", "CC0 1.0 legal code of the pinned smart-anc commit"),
370
+ BundleFile("SMART_ANC_LICENSE.txt", f"{_snap('world_L09')}/SMART_ANC_LICENSE.txt", "license statement copied verbatim from the pinned source snapshot"),
371
+ _receipt("smart_anc"),
372
+ ),
373
+ notes=(
374
+ "The registry expected CC-BY-4.0/WHO terms while the pinned "
375
+ "LICENSE.md is CC0-1.0; the pinned text governs (recorded mismatch).",
376
+ ),
377
+ citations=(
378
+ "WHO SMART-ANC implementation guide, pinned commit "
379
+ "301a6b8b904361315ca38b28ee9fbd133f9d0e94.",
380
+ ),
381
+ ),
382
+ "uniprot": SourceLicense(
383
+ source_id="uniprot",
384
+ license_label="CC-BY-4.0",
385
+ attribution="UniProt Consortium (EMBL-EBI, SIB, PIR).",
386
+ obligation="Retain the UniProt Consortium attribution and the release identifier (2026_03, Swiss-Prot section).",
387
+ files=(
388
+ BundleFile("README", f"{_V3}/uniprot/README", "pinned snapshot README carrying the LICENSE section"),
389
+ BundleFile("UNIPROT_LICENSE.txt", f"{_snap('world_L16')}/UNIPROT_LICENSE.txt", "license statement copied verbatim from the pinned source snapshot"),
390
+ ),
391
+ citations=("UniProtKB/Swiss-Prot release 2026_03.",),
392
+ ),
393
+ }
394
+
395
+
396
+ def _reg_receipt_ref(name: str, source_id: str) -> Reference:
397
+ return Reference(
398
+ pointer=f"{_REGISTRY}/{name}.yaml",
399
+ status="shipped",
400
+ paths=(f"LICENSES/{source_id}/registry_receipts/{name}.yaml",),
401
+ detail="verbatim copy of the source-registry receipt ships in the bundle",
402
+ )
403
+
404
+
405
+ _FETCH_RECEIPT_REASON: Final = (
406
+ "the fetch receipt is repository-internal build evidence (it records "
407
+ "build-machine absolute paths); its license verdict is restated verbatim "
408
+ "in the bundled snapshot license text"
409
+ )
410
+
411
+ WORLDS: Final[dict[str, WorldLicense]] = {
412
+ "world_L01": WorldLicense(
413
+ world_id="world_L01",
414
+ sources=("gatekeeper-library",),
415
+ references=(_reg_receipt_ref("gatekeeper", "gatekeeper-library"),),
416
+ ),
417
+ "world_L02": WorldLicense(
418
+ world_id="world_L02",
419
+ sources=("kubernetes-vap-cel",),
420
+ references=(_reg_receipt_ref("cel", "kubernetes-vap-cel"),),
421
+ ),
422
+ "world_L03": WorldLicense(
423
+ world_id="world_L03",
424
+ sources=("camunda-dmn-examples", "dmn-tck"),
425
+ references=(_reg_receipt_ref("camunda", "camunda-dmn-examples"),),
426
+ ),
427
+ "world_L04": WorldLicense(
428
+ world_id="world_L04",
429
+ sources=("rhea-chebi",),
430
+ references=(
431
+ _reg_receipt_ref("rhea", "rhea-chebi"),
432
+ _reg_receipt_ref("chebi", "rhea-chebi"),
433
+ ),
434
+ ),
435
+ "world_L05": WorldLicense(
436
+ world_id="world_L05",
437
+ sources=("rdkit-molecules",),
438
+ references=(
439
+ _reg_receipt_ref("rdkit", "rdkit-molecules"),
440
+ _reg_receipt_ref("chebi", "rdkit-molecules"),
441
+ ),
442
+ ),
443
+ "world_L06": WorldLicense(
444
+ world_id="world_L06",
445
+ sources=("gene-ontology",),
446
+ references=(_reg_receipt_ref("go", "gene-ontology"),),
447
+ ),
448
+ "world_L07": WorldLicense(
449
+ world_id="world_L07",
450
+ sources=("biomodels",),
451
+ references=(_reg_receipt_ref("biomodels", "biomodels"),),
452
+ snapshot_pointer="source_snapshot/BIOMODELS_LICENSE.txt",
453
+ ),
454
+ "world_L08": WorldLicense(
455
+ world_id="world_L08",
456
+ sources=("cql-clinical",),
457
+ references=(_reg_receipt_ref("cql", "cql-clinical"),),
458
+ ),
459
+ "world_L09": WorldLicense(
460
+ world_id="world_L09",
461
+ sources=("smart-anc",),
462
+ references=(_reg_receipt_ref("smart_anc", "smart-anc"),),
463
+ ),
464
+ "world_L10": WorldLicense(
465
+ world_id="world_L10",
466
+ sources=("behavior-1k-bddl",),
467
+ references=(_reg_receipt_ref("behavior", "behavior-1k-bddl"),),
468
+ ),
469
+ "world_L11": WorldLicense(
470
+ world_id="world_L11",
471
+ sources=("behavior-1k-bddl", "behavior-1k-omnigibson"),
472
+ references=(
473
+ _reg_receipt_ref("behavior", "behavior-1k-bddl"),
474
+ Reference(
475
+ pointer="BEHAVIOR-1K OmniGibson scene/object assets",
476
+ status="not_shipped",
477
+ detail=(
478
+ "license-gated (behavior.stanford.edu/agreement) plus NVIDIA "
479
+ "Isaac Sim EULA; never embedded — referenced by snapshot id "
480
+ "and hashes only (see "
481
+ "LICENSES/behavior-1k-omnigibson/OMNIGIBSON_ASSETS_LICENSE.txt)"
482
+ ),
483
+ ),
484
+ ),
485
+ ),
486
+ "world_L12": WorldLicense(
487
+ world_id="world_L12",
488
+ sources=("pm4py-process",),
489
+ references=(
490
+ Reference(
491
+ pointer="the fetch receipt",
492
+ status="not_shipped",
493
+ detail=_FETCH_RECEIPT_REASON + " (LICENSES/pm4py-process/PM4PY_LICENSE.txt)",
494
+ ),
495
+ Reference(
496
+ pointer="sources/registry.d receipt for pm4py-process",
497
+ status="not_shipped",
498
+ detail=(
499
+ "no sources/registry.d receipt exists for pm4py-process in "
500
+ "this repository state (recorded in the world license field)"
501
+ ),
502
+ ),
503
+ ),
504
+ ),
505
+ "world_L13": WorldLicense(
506
+ world_id="world_L13",
507
+ sources=("apis-guru",),
508
+ references=(
509
+ Reference(
510
+ pointer="the fetch receipt",
511
+ status="not_shipped",
512
+ detail=_FETCH_RECEIPT_REASON + " (LICENSES/apis-guru/APIS_GURU_LICENSE.txt)",
513
+ ),
514
+ Reference(
515
+ pointer="sources/registry.d/apis-guru.yaml",
516
+ status="not_shipped",
517
+ detail=(
518
+ "no sources/registry.d/apis-guru.yaml exists in this "
519
+ "repository state (recorded in the world license field and "
520
+ "the snapshot declaration)"
521
+ ),
522
+ ),
523
+ Reference(
524
+ pointer="per-spec licenses as indexed",
525
+ status="not_shipped",
526
+ detail=(
527
+ "the release ships the pinned unit index hashes only (no "
528
+ "OpenAPI spec content); per-spec upstream license "
529
+ "obligations pass to the user"
530
+ ),
531
+ ),
532
+ ),
533
+ ),
534
+ "world_L14": WorldLicense(
535
+ world_id="world_L14",
536
+ sources=("chembl",),
537
+ references=(
538
+ Reference(
539
+ pointer="the pinned snapshot LICENSE/REQUIRED.ATTRIBUTION",
540
+ status="shipped",
541
+ paths=("LICENSES/chembl/LICENSE", "LICENSES/chembl/REQUIRED.ATTRIBUTION"),
542
+ detail="verbatim copies of the pinned ChEMBL 37 snapshot files",
543
+ ),
544
+ ),
545
+ ),
546
+ "world_L15": WorldLicense(
547
+ world_id="world_L15",
548
+ sources=("reactome",),
549
+ references=(
550
+ Reference(
551
+ pointer="external_knowledge/fetch_receipts/reactome/receipt-release-98.json",
552
+ status="shipped",
553
+ paths=("LICENSES/reactome/fetch_receipt.json",),
554
+ detail=(
555
+ "byte-identical copy; records "
556
+ "receipt-release-98.json::license_verdict verbatim"
557
+ ),
558
+ ),
559
+ ),
560
+ ),
561
+ "world_L16": WorldLicense(
562
+ world_id="world_L16",
563
+ sources=("uniprot",),
564
+ references=(
565
+ Reference(
566
+ pointer="the pinned snapshot README LICENSE section",
567
+ status="shipped",
568
+ paths=("LICENSES/uniprot/README",),
569
+ detail="verbatim copy of the pinned snapshot README (LICENSE section included)",
570
+ ),
571
+ ),
572
+ ),
573
+ }
574
+
575
+ CODE_LICENSE_ORIGIN: Final = "release_candidates/AutoOntologyBench/LICENSE"
576
+
577
+
578
+ def resolve_world(world_id: str) -> WorldLicense:
579
+ """Return the world's license wiring or raise ``license_source_missing``."""
580
+ world = WORLDS.get(world_id)
581
+ if world is None:
582
+ raise ReleaseError(
583
+ "license_source_missing",
584
+ f"no license attribution registry entry for {world_id}; "
585
+ "add one to scripts/core_release/license_registry.py",
586
+ )
587
+ return world
588
+
589
+
590
+ __all__ = [
591
+ "CODE_LICENSE_ORIGIN",
592
+ "SOURCES",
593
+ "WORLDS",
594
+ "BundleFile",
595
+ "Reference",
596
+ "SourceLicense",
597
+ "WorldLicense",
598
+ "resolve_world",
599
+ ]
core_worlds/src/scripts/core_release/license_render.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render the generated license-layer documents (NOTICE, ATTRIBUTION, SUMMARY).
2
+
3
+ All renderers are pure functions of the license registry plus the assembled
4
+ worlds, with sorted iteration and no timestamps, so rebuilds stay
5
+ byte-identical.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from .license_registry import SourceLicense, resolve_world
11
+ from .validate import ValidatedWorld
12
+
13
+ _NOTICE_HEADER = """\
14
+ AutoOntologyBench - Core-track benchmark release
15
+ Copyright 2026 AutoOntologyBench contributors
16
+
17
+ The project code is licensed under Apache-2.0 (see LICENSE); the
18
+ benchmark data is released under CC BY 4.0 (see LICENSE-DATA.md). This
19
+ posture follows the repository's recorded recommendation
20
+ (reports/w7_license_recommendation.md, DRAFT) - PI sign-off is PENDING;
21
+ treat this release as pre-publication packaging until sign-off is
22
+ recorded.
23
+
24
+ This release contains task records and public materials derived from or
25
+ referencing the third-party sources below. Full license texts and
26
+ per-source summaries are in LICENSES/.
27
+ """
28
+
29
+ _ATTRIBUTION_HEADER = """\
30
+ # ATTRIBUTION - AutoOntologyBench Core-track benchmark release
31
+
32
+ Generated by `scripts/assemble_core_release.py` from each world pack's
33
+ `manifests/provenance.json` license declaration and the pinned source
34
+ snapshot evidence. Per-source details: `LICENSES/<source_id>/SUMMARY.md`.
35
+ Every world license reference is resolved in
36
+ `worlds/<world_id>/metadata.json::license_attribution` (shipped into this
37
+ release, or explicitly marked not shipped with a reason); verify with
38
+ `scripts/check_core_license_pointers.py`.
39
+ """
40
+
41
+
42
+ def _worlds_by_source(
43
+ sources: dict[str, SourceLicense], worlds: list[ValidatedWorld]
44
+ ) -> dict[str, list[str]]:
45
+ return {
46
+ source_id: sorted(
47
+ world.world_id
48
+ for world in worlds
49
+ if source_id in resolve_world(world.world_id).sources
50
+ )
51
+ for source_id in sources
52
+ }
53
+
54
+
55
+ def render_notice(sources: dict[str, SourceLicense], worlds: list[ValidatedWorld]) -> str:
56
+ """Top-level NOTICE: project grant plus one block per upstream source."""
57
+ lines = [_NOTICE_HEADER.rstrip("\n"), ""]
58
+ by_source = _worlds_by_source(sources, worlds)
59
+ for source_id, source in sources.items():
60
+ lines.append(f"== {source_id} ({', '.join(by_source[source_id])})")
61
+ lines.append(f" License: {source.license_label}")
62
+ lines.append(f" Attribution: {source.attribution}")
63
+ lines.append(f" Obligation: {source.obligation}")
64
+ lines.append(f" Details: LICENSES/{source_id}/SUMMARY.md")
65
+ lines.append("")
66
+ return "\n".join(lines)
67
+
68
+
69
+ def render_attribution(worlds: list[ValidatedWorld], sources: dict[str, SourceLicense]) -> str:
70
+ """LICENSES/ATTRIBUTION.md master table, citations, and open items."""
71
+ lines = [
72
+ _ATTRIBUTION_HEADER.rstrip("\n"),
73
+ "",
74
+ "| world | source | license | bundle |",
75
+ "|---|---|---|---|",
76
+ ]
77
+ for world in worlds:
78
+ for source_id in resolve_world(world.world_id).sources:
79
+ source = sources[source_id]
80
+ lines.append(
81
+ f"| {world.world_id} | {source_id} | {source.license_label} | "
82
+ f"`LICENSES/{source_id}/` |"
83
+ )
84
+ lines.append("")
85
+ citations = [
86
+ (source_id, citation)
87
+ for source_id, source in sources.items()
88
+ for citation in source.citations
89
+ ]
90
+ if citations:
91
+ lines.append("## Key citations")
92
+ lines.append("")
93
+ lines.extend(f"- **{source_id}**: {citation}" for source_id, citation in citations)
94
+ lines.append("")
95
+ open_items = [
96
+ (source_id, note)
97
+ for source_id, source in sources.items()
98
+ for note in source.notes
99
+ ]
100
+ if open_items:
101
+ lines.append("## Recorded notes and open items")
102
+ lines.append("")
103
+ lines.extend(f"- **{source_id}**: {note}" for source_id, note in open_items)
104
+ lines.append("")
105
+ return "\n".join(lines)
106
+
107
+
108
+ def render_summary(source: SourceLicense, worlds: list[ValidatedWorld]) -> str:
109
+ """LICENSES/<source_id>/SUMMARY.md: posture, declared strings, provenance."""
110
+ users = [
111
+ world
112
+ for world in worlds
113
+ if source.source_id in resolve_world(world.world_id).sources
114
+ ]
115
+ lines = [
116
+ f"# {source.source_id}",
117
+ "",
118
+ f"- Worlds using this source: {', '.join(world.world_id for world in users)}",
119
+ f"- License: {source.license_label}",
120
+ f"- Attribution: {source.attribution}",
121
+ f"- Redistribution obligation: {source.obligation}",
122
+ "",
123
+ "License as declared in each world's `metadata.json::license`:",
124
+ "",
125
+ ]
126
+ lines.extend(
127
+ f"- {world.world_id}: \"{world.provenance.get('license')}\"" for world in users
128
+ )
129
+ lines.append("")
130
+ lines.append("## Pinned evidence shipped in this directory")
131
+ lines.append("")
132
+ lines.extend(
133
+ f"- `{bundle_file.dest}` - {bundle_file.note} (origin: `{bundle_file.origin}`)"
134
+ for bundle_file in source.files
135
+ )
136
+ lines.append("")
137
+ if source.notes:
138
+ lines.append("## Notes")
139
+ lines.append("")
140
+ lines.extend(f"- {note}" for note in source.notes)
141
+ lines.append("")
142
+ if source.citations:
143
+ lines.append("## Citations")
144
+ lines.append("")
145
+ lines.extend(f"- {citation}" for citation in source.citations)
146
+ lines.append("")
147
+ return "\n".join(lines)
148
+
149
+
150
+ __all__ = ["render_attribution", "render_notice", "render_summary"]
core_worlds/src/scripts/core_release/licenses.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """License and attribution layer for the Core-track benchmark release.
2
+
3
+ The assembler ships a self-contained license bundle with every release:
4
+
5
+ - ``LICENSE`` — Apache-2.0 (the project code license, copied verbatim).
6
+ - ``LICENSE-DATA.md`` — CC BY 4.0 grant for the release data.
7
+ - ``NOTICE`` — project + third-party attribution notices.
8
+ - ``LICENSES/`` — per-source bundle: verbatim upstream license/attribution
9
+ texts, registry-receipt copies, and a generated ``SUMMARY.md`` per source,
10
+ plus a generated ``ATTRIBUTION.md`` master table.
11
+
12
+ The mapping from a world to its upstream evidence lives in
13
+ ``license_registry.py``; document text lives in ``license_render.py`` and the
14
+ ``templates/`` directory. Everything is deterministic (sorted iteration, no
15
+ timestamps), so rebuilds stay byte-identical.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from pathlib import Path
21
+ from typing import Final
22
+
23
+ from .errors import ReleaseError
24
+ from .license_registry import (
25
+ CODE_LICENSE_ORIGIN,
26
+ SOURCES,
27
+ Reference,
28
+ SourceLicense,
29
+ WorldLicense,
30
+ resolve_world,
31
+ )
32
+ from .license_render import render_attribution, render_notice, render_summary
33
+ from .validate import ValidatedWorld
34
+
35
+ LICENSE_ATTRIBUTION_SCHEMA: Final = "aob-core-license-attribution/1.0"
36
+ CC_BY_4_0_LEGALCODE: Final = "LICENSES/legalcode/CC-BY-4.0.txt"
37
+
38
+ _TEMPLATE_DIR: Final = Path(__file__).with_name("templates")
39
+
40
+ _REQUIRED_TOP_LEVEL: Final = (
41
+ "LICENSE",
42
+ "LICENSE-DATA.md",
43
+ "NOTICE",
44
+ "LICENSES/README.md",
45
+ "LICENSES/ATTRIBUTION.md",
46
+ CC_BY_4_0_LEGALCODE,
47
+ )
48
+
49
+
50
+ def _sources_for(world_ids: list[str]) -> dict[str, SourceLicense]:
51
+ source_ids: set[str] = set()
52
+ for world_id in world_ids:
53
+ source_ids.update(resolve_world(world_id).sources)
54
+ return {source_id: SOURCES[source_id] for source_id in sorted(source_ids)}
55
+
56
+
57
+ def _snapshot_reference(world: WorldLicense) -> Reference:
58
+ """Resolve the world's ``source_snapshot/`` pointer to bundled files."""
59
+ prefix = f"pilot_worlds/{world.world_id}_scaleup/source_snapshot/"
60
+ paths = sorted(
61
+ f"LICENSES/{source_id}/{bundle_file.dest}"
62
+ for source_id in world.sources
63
+ for bundle_file in SOURCES[source_id].files
64
+ if bundle_file.origin.startswith(prefix)
65
+ )
66
+ return Reference(
67
+ pointer=world.snapshot_pointer,
68
+ status="shipped",
69
+ paths=tuple(paths),
70
+ detail=world.snapshot_note,
71
+ )
72
+
73
+
74
+ def _reference_block(reference: Reference) -> dict[str, object]:
75
+ block: dict[str, object] = {"pointer": reference.pointer, "status": reference.status}
76
+ if reference.status == "shipped":
77
+ block["paths"] = sorted(reference.paths)
78
+ block["note"] = reference.detail
79
+ else:
80
+ block["reason"] = reference.detail
81
+ return block
82
+
83
+
84
+ def world_license_attribution(world_id: str) -> dict[str, object]:
85
+ """Metadata block recording how every license reference of a world resolves."""
86
+ world = resolve_world(world_id)
87
+ bundle_paths = sorted(
88
+ f"LICENSES/{source_id}/{bundle_file.dest}"
89
+ for source_id in world.sources
90
+ for bundle_file in SOURCES[source_id].files
91
+ )
92
+ bundle_paths.extend(
93
+ f"LICENSES/{source_id}/SUMMARY.md" for source_id in sorted(world.sources)
94
+ )
95
+ references = [_snapshot_reference(world), *world.references]
96
+ return {
97
+ "schema": LICENSE_ATTRIBUTION_SCHEMA,
98
+ "project_grant": {
99
+ "code": "Apache-2.0",
100
+ "data": "CC-BY-4.0",
101
+ "files": ["LICENSE", "LICENSE-DATA.md", "NOTICE", "LICENSES/ATTRIBUTION.md"],
102
+ "sign_off": (
103
+ "PENDING PI SIGN-OFF (posture per "
104
+ "reports/w7_license_recommendation.md, DRAFT)"
105
+ ),
106
+ },
107
+ "bundle_paths": sorted(bundle_paths),
108
+ "references": [_reference_block(reference) for reference in references],
109
+ }
110
+
111
+
112
+ def manifest_license_block() -> dict[str, object]:
113
+ """Top-level ``license`` object for MANIFEST.json."""
114
+ return {
115
+ "code": "Apache-2.0",
116
+ "data": "CC-BY-4.0",
117
+ "files": {
118
+ "attribution": "LICENSES/ATTRIBUTION.md",
119
+ "code_license": "LICENSE",
120
+ "data_legalcode": CC_BY_4_0_LEGALCODE,
121
+ "data_license": "LICENSE-DATA.md",
122
+ "notice": "NOTICE",
123
+ },
124
+ "sign_off": "PENDING PI SIGN-OFF",
125
+ "recommendation": "reports/w7_license_recommendation.md (DRAFT)",
126
+ "note": (
127
+ "Upstream source terms in LICENSES/ and NOTICE are not superseded by "
128
+ "the project code/data grants."
129
+ ),
130
+ }
131
+
132
+
133
+ def _copy_bundle_files(
134
+ root: Path, sources: dict[str, SourceLicense], repo_root: Path, written: list[str]
135
+ ) -> None:
136
+ for source in sources.values():
137
+ source_dir = root / "LICENSES" / source.source_id
138
+ for bundle_file in source.files:
139
+ origin = repo_root / bundle_file.origin
140
+ if not origin.is_file():
141
+ raise ReleaseError(
142
+ "license_source_missing",
143
+ f"{bundle_file.origin} not found (needed for "
144
+ f"LICENSES/{source.source_id}/{bundle_file.dest})",
145
+ )
146
+ target = source_dir / bundle_file.dest
147
+ target.parent.mkdir(parents=True, exist_ok=True)
148
+ target.write_bytes(origin.read_bytes())
149
+ written.append(f"LICENSES/{source.source_id}/{bundle_file.dest}")
150
+
151
+
152
+ def write_license_layer(
153
+ root: Path, worlds: list[ValidatedWorld], repo_root: Path
154
+ ) -> list[str]:
155
+ """Write LICENSE/LICENSE-DATA.md/NOTICE/LICENSES/; return the written paths."""
156
+ ordered = sorted(worlds, key=lambda world: world.world_id)
157
+ sources = _sources_for([world.world_id for world in ordered])
158
+ licenses_dir = root / "LICENSES"
159
+ written: list[str] = []
160
+ _copy_bundle_files(root, sources, repo_root, written)
161
+ for source in sources.values():
162
+ source_dir = licenses_dir / source.source_id
163
+ (source_dir / "SUMMARY.md").write_text(
164
+ render_summary(source, ordered), encoding="utf-8"
165
+ )
166
+ written.append(f"LICENSES/{source.source_id}/SUMMARY.md")
167
+ (licenses_dir / "legalcode").mkdir(parents=True, exist_ok=True)
168
+ (licenses_dir / "legalcode" / "CC-BY-4.0.txt").write_bytes(
169
+ (_TEMPLATE_DIR / "CC-BY-4.0.txt").read_bytes()
170
+ )
171
+ (licenses_dir / "README.md").write_text(
172
+ (_TEMPLATE_DIR / "licenses_README.md").read_text(encoding="utf-8"),
173
+ encoding="utf-8",
174
+ )
175
+ (licenses_dir / "ATTRIBUTION.md").write_text(
176
+ render_attribution(ordered, sources), encoding="utf-8"
177
+ )
178
+ code_license = repo_root / CODE_LICENSE_ORIGIN
179
+ if not code_license.is_file():
180
+ raise ReleaseError(
181
+ "license_source_missing", f"{CODE_LICENSE_ORIGIN} not found (needed for LICENSE)"
182
+ )
183
+ (root / "LICENSE").write_bytes(code_license.read_bytes())
184
+ (root / "LICENSE-DATA.md").write_text(
185
+ (_TEMPLATE_DIR / "LICENSE-DATA.md").read_text(encoding="utf-8"), encoding="utf-8"
186
+ )
187
+ (root / "NOTICE").write_text(render_notice(sources, ordered), encoding="utf-8")
188
+ written.extend(_REQUIRED_TOP_LEVEL)
189
+ return sorted(written)
190
+
191
+
192
+ __all__ = [
193
+ "CC_BY_4_0_LEGALCODE",
194
+ "LICENSE_ATTRIBUTION_SCHEMA",
195
+ "manifest_license_block",
196
+ "resolve_world",
197
+ "world_license_attribution",
198
+ "write_license_layer",
199
+ ]
core_worlds/src/scripts/core_release/semantics.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Semantic label-leak gate for the release projection.
2
+
3
+ The structural leakage check (``leakage.py``) scans pack public files for
4
+ hidden ids, label keys, private paths, and gold hashes. This module guards the
5
+ assembled release rows against the semantic channels found in the final QA
6
+ reports:
7
+
8
+ 1. A public token that restates the private verdict (``features`` carrying
9
+ ``polarity:accepted|rejected``) or a prompt that names the private
10
+ polarity-marked state variant (L01 ``gk_validate_bundle`` quoting ``cf_*``
11
+ counterfactual ids).
12
+ 2. A public identity field (``template``, ``template_family``, ``family:``
13
+ feature value, ``actions[].variant``) that either equals an original
14
+ private name (template/family/counterfactual/scenario) or carries a
15
+ label-word pattern such as ``canonical``/``cf_``/``valid``/``missing``.
16
+ The release projection replaces those values with opaque IDs, so the gate
17
+ is an independent post-condition: any future projection regression fails
18
+ assembly instead of shipping.
19
+
20
+ The gate runs on the *sanitized* release rows. Prompt/content vocabulary is
21
+ deliberately not pattern-gated; only the four identity channels above are.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import re
27
+ from collections.abc import Iterable, Iterator
28
+ from typing import Final
29
+
30
+ from .contract import (
31
+ LABEL_FEATURE_KEY_GATE,
32
+ LABEL_FEATURE_VALUE_PATTERN,
33
+ SPLIT_NAMES,
34
+ )
35
+ from .errors import Violation
36
+
37
+ PRIVATE_IDENTITY_FIELDS: Final[tuple[str, ...]] = (
38
+ "template",
39
+ "template_family",
40
+ "counterfactual",
41
+ "scenario",
42
+ )
43
+ # Label-word vocabulary at token boundaries (``_`` and punctuation separate
44
+ # tokens). ``validate`` does not match ``valid``; ``cf_bad_image`` matches both
45
+ # the literal ``cf_`` prefix and the ``bad`` token.
46
+ IDENTITY_LABEL_WORD_PATTERN: Final = re.compile(
47
+ r"(?i)(?:^|[^a-z0-9])"
48
+ r"(?:canonical|counterfactual|accepted|rejected|valid|invalid|pass|fail|"
49
+ r"good|bad|missing|positive|negative)"
50
+ r"(?=$|[^a-z0-9])"
51
+ r"|cf_"
52
+ )
53
+
54
+
55
+ def private_identity_names(records: Iterable[dict[str, object]]) -> frozenset[str]:
56
+ """Every original identity name a release must not publish verbatim."""
57
+ names: set[str] = set()
58
+ for record in records:
59
+ for field in PRIVATE_IDENTITY_FIELDS:
60
+ value = record.get(field)
61
+ if isinstance(value, str) and value:
62
+ names.add(value)
63
+ return frozenset(names)
64
+
65
+
66
+ def has_label_word(value: str) -> bool:
67
+ """True when ``value`` carries label-word vocabulary at a token boundary."""
68
+ return bool(IDENTITY_LABEL_WORD_PATTERN.search(value))
69
+
70
+
71
+ def public_identity_values(row: dict[str, object]) -> Iterator[tuple[str, str]]:
72
+ """Yield ``(channel, value)`` for the four public identity channels."""
73
+ template = row.get("template")
74
+ if isinstance(template, str) and template:
75
+ yield "template", template
76
+ family = row.get("template_family")
77
+ if isinstance(family, str) and family:
78
+ yield "template_family", family
79
+ features = row.get("features")
80
+ if isinstance(features, list):
81
+ for token in features:
82
+ key, separator, value = str(token).partition(":")
83
+ if separator and key == "family" and value:
84
+ yield "family_feature", value
85
+ actions = row.get("actions")
86
+ if isinstance(actions, list):
87
+ for action in actions:
88
+ if not isinstance(action, dict):
89
+ continue
90
+ variant = action.get("variant")
91
+ if isinstance(variant, str) and variant:
92
+ yield "variant", variant
93
+
94
+
95
+ def check_semantic_leakage(
96
+ release_rows: list[dict[str, object]],
97
+ by_split: dict[str, list[dict[str, object]]],
98
+ violations: list[Violation],
99
+ ) -> None:
100
+ """Fail assembly when a release row still leaks the private label."""
101
+ private_records = [
102
+ record for split in SPLIT_NAMES for record in by_split[split]
103
+ ]
104
+ private_by_id = {str(record.get("task_id")): record for record in private_records}
105
+ identity_names = private_identity_names(private_records)
106
+ for row in release_rows:
107
+ task_id = str(row.get("task_id"))
108
+ features = row.get("features")
109
+ if isinstance(features, list):
110
+ for token in features:
111
+ text = str(token)
112
+ key, _, value = text.partition(":")
113
+ if key in LABEL_FEATURE_KEY_GATE or LABEL_FEATURE_VALUE_PATTERN.match(
114
+ value
115
+ ):
116
+ violations.append(
117
+ Violation(
118
+ "public_semantic_leak",
119
+ task_id,
120
+ f"release feature token {text!r} restates the verdict",
121
+ )
122
+ )
123
+ for channel, value in public_identity_values(row):
124
+ if value in identity_names:
125
+ violations.append(
126
+ Violation(
127
+ "public_semantic_leak",
128
+ task_id,
129
+ f"release {channel} {value!r} names a private identity",
130
+ )
131
+ )
132
+ if has_label_word(value):
133
+ violations.append(
134
+ Violation(
135
+ "public_semantic_leak",
136
+ task_id,
137
+ f"release {channel} {value!r} contains a label word",
138
+ )
139
+ )
140
+ record = private_by_id.get(task_id)
141
+ if record is None:
142
+ continue
143
+ prompt = str(row.get("prompt"))
144
+ counterfactual = record.get("counterfactual")
145
+ if isinstance(counterfactual, str) and counterfactual and counterfactual in prompt:
146
+ violations.append(
147
+ Violation(
148
+ "public_semantic_leak",
149
+ task_id,
150
+ f"release prompt names the private variant {counterfactual!r}",
151
+ )
152
+ )
153
+ scenario = str(record.get("scenario") or "")
154
+ if scenario and scenario in prompt:
155
+ violations.append(
156
+ Violation(
157
+ "public_semantic_leak",
158
+ task_id,
159
+ f"release prompt names the private scenario {scenario!r}",
160
+ )
161
+ )
162
+
163
+
164
+ __all__ = [
165
+ "IDENTITY_LABEL_WORD_PATTERN",
166
+ "PRIVATE_IDENTITY_FIELDS",
167
+ "check_semantic_leakage",
168
+ "has_label_word",
169
+ "private_identity_names",
170
+ "public_identity_values",
171
+ ]
core_worlds/src/scripts/core_release/tasks.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task-record checks: schema, split membership, counts, families, tags."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ from pydantic import ValidationError
9
+
10
+ from .contract import (
11
+ DIFFICULTY_FILE,
12
+ SPLIT_FILES,
13
+ SPLIT_NAMES,
14
+ WORLD_TAG_3_PATTERN,
15
+ WORLD_TAG_4_PATTERN,
16
+ PackTaskPrivate,
17
+ PackTaskPublic,
18
+ public_projection,
19
+ read_jsonl,
20
+ )
21
+ from .errors import Violation
22
+
23
+
24
+ def parse_tasks(
25
+ pack: Path, violations: list[Violation]
26
+ ) -> tuple[dict[str, list[dict[str, object]]], list[dict[str, object]]] | None:
27
+ by_split: dict[str, list[dict[str, object]]] = {}
28
+ for split in SPLIT_NAMES:
29
+ relative = SPLIT_FILES[split]
30
+ try:
31
+ records = read_jsonl(pack / relative)
32
+ except (ValueError, json.JSONDecodeError) as exc:
33
+ violations.append(Violation("json_parse_error", relative, str(exc)))
34
+ return None
35
+ for index, record in enumerate(records, 1):
36
+ try:
37
+ PackTaskPrivate.model_validate(record)
38
+ except ValidationError as exc:
39
+ first = exc.errors()[0]
40
+ violations.append(
41
+ Violation(
42
+ "task_schema",
43
+ f"{relative}:{index}",
44
+ f"{'.'.join(str(part) for part in first['loc'])}: {first['msg']}",
45
+ )
46
+ )
47
+ if record.get("split") != split:
48
+ violations.append(
49
+ Violation(
50
+ "split_field_mismatch",
51
+ f"{relative}:{index}",
52
+ f"record split {record.get('split')!r} != file split {split!r}",
53
+ )
54
+ )
55
+ by_split[split] = records
56
+ try:
57
+ public_records = read_jsonl(pack / "public/examples_dev.jsonl")
58
+ except (ValueError, json.JSONDecodeError) as exc:
59
+ violations.append(Violation("json_parse_error", "public/examples_dev.jsonl", str(exc)))
60
+ return None
61
+ for index, record in enumerate(public_records, 1):
62
+ try:
63
+ PackTaskPublic.model_validate(record)
64
+ except ValidationError as exc:
65
+ first = exc.errors()[0]
66
+ violations.append(
67
+ Violation(
68
+ "task_schema",
69
+ f"public/examples_dev.jsonl:{index}",
70
+ f"{'.'.join(str(part) for part in first['loc'])}: {first['msg']}",
71
+ )
72
+ )
73
+ return by_split, public_records
74
+
75
+
76
+ def check_splits(
77
+ by_split: dict[str, list[dict[str, object]]],
78
+ public_records: list[dict[str, object]],
79
+ difficulty: dict[str, object],
80
+ violations: list[Violation],
81
+ ) -> None:
82
+ seen: dict[str, str] = {}
83
+ for split, records in by_split.items():
84
+ for record in records:
85
+ task_id = str(record.get("task_id"))
86
+ if task_id in seen:
87
+ violations.append(
88
+ Violation("duplicate_task_id", task_id, f"also in {seen[task_id]}")
89
+ )
90
+ seen[task_id] = split
91
+ dev_projection = [public_projection(record) for record in by_split["dev"]]
92
+ if dev_projection != public_records:
93
+ violations.append(
94
+ Violation(
95
+ "public_dev_projection_mismatch",
96
+ "public/examples_dev.jsonl",
97
+ "public dev records are not the label-stripped dev split, in order",
98
+ )
99
+ )
100
+ scenarios: dict[str, set[str]] = {}
101
+ for split, records in by_split.items():
102
+ for record in records:
103
+ scenarios.setdefault(str(record.get("scenario")), set()).add(split)
104
+ for scenario, splits in sorted(scenarios.items()):
105
+ if len(splits) > 1:
106
+ violations.append(
107
+ Violation("paraphrase_split_leak", scenario, f"scenario split across {sorted(splits)}")
108
+ )
109
+ counts = difficulty.get("task_counts")
110
+ if not isinstance(counts, dict):
111
+ violations.append(Violation("count_mismatch", DIFFICULTY_FILE, "task_counts absent"))
112
+ return
113
+ declared = counts.get("per_split")
114
+ expected_splits = declared if isinstance(declared, dict) else {}
115
+ for split in SPLIT_NAMES:
116
+ actual = len(by_split[split])
117
+ if expected_splits.get(split) != actual:
118
+ violations.append(
119
+ Violation(
120
+ "split_count_mismatch",
121
+ split,
122
+ f"difficulty {expected_splits.get(split)!r} != records {actual}",
123
+ )
124
+ )
125
+ total = len(seen)
126
+ if counts.get("total") != total:
127
+ violations.append(
128
+ Violation("count_mismatch", DIFFICULTY_FILE, f"declared total != {total} records")
129
+ )
130
+ variants = counts.get("paraphrase_variants_per_scenario")
131
+ per_scenario: dict[str, int] = {}
132
+ variants_by_scenario: dict[str, list[object]] = {}
133
+ for records in by_split.values():
134
+ for record in records:
135
+ key = str(record.get("scenario"))
136
+ per_scenario[key] = per_scenario.get(key, 0) + 1
137
+ variants_by_scenario.setdefault(key, []).append(record.get("paraphrase_variant"))
138
+ if not isinstance(variants, int) or variants < 1:
139
+ violations.append(
140
+ Violation("count_formula_mismatch", DIFFICULTY_FILE, "paraphrase_variants absent")
141
+ )
142
+ return
143
+ if counts.get("scenarios") != len(per_scenario) or total != len(per_scenario) * variants:
144
+ violations.append(
145
+ Violation(
146
+ "count_formula_mismatch",
147
+ DIFFICULTY_FILE,
148
+ "total != scenarios x paraphrase_variants_per_scenario",
149
+ )
150
+ )
151
+ for scenario, record_count in sorted(per_scenario.items()):
152
+ if record_count != variants:
153
+ violations.append(
154
+ Violation(
155
+ "count_formula_mismatch",
156
+ scenario,
157
+ f"{record_count} variants != declared {variants}",
158
+ )
159
+ )
160
+ variants_seen = variants_by_scenario[scenario]
161
+ if len(set(variants_seen)) != len(variants_seen):
162
+ violations.append(
163
+ Violation(
164
+ "paraphrase_variant_duplicate",
165
+ scenario,
166
+ f"paraphrase variants not unique: {variants_seen}",
167
+ )
168
+ )
169
+
170
+
171
+ def check_families_and_tags(
172
+ by_split: dict[str, list[dict[str, object]]],
173
+ difficulty: dict[str, object],
174
+ spec: dict[str, object],
175
+ violations: list[Violation],
176
+ ) -> None:
177
+ records = [record for split in SPLIT_NAMES for record in by_split[split]]
178
+ declared = difficulty.get("template_families")
179
+ families = declared.get("families") if isinstance(declared, dict) else None
180
+ used = {str(record.get("template_family")) for record in records}
181
+ if not isinstance(families, list) or not families:
182
+ violations.append(
183
+ Violation("template_family_undeclared", DIFFICULTY_FILE, "families list absent")
184
+ )
185
+ else:
186
+ for family in sorted(used - set(families)):
187
+ violations.append(
188
+ Violation("template_family_undeclared", str(family), "not declared in difficulty")
189
+ )
190
+ if declared.get("count") != len(families):
191
+ violations.append(
192
+ Violation(
193
+ "template_family_count_mismatch",
194
+ DIFFICULTY_FILE,
195
+ f"count {declared.get('count')!r} != {len(families)} families",
196
+ )
197
+ )
198
+ transfer = declared.get("structural_transfer")
199
+ if transfer is not None and transfer not in families:
200
+ violations.append(
201
+ Violation("template_family_undeclared", str(transfer), "transfer family undeclared")
202
+ )
203
+ generation = spec.get("generation")
204
+ width = generation.get("instance_tag_width") if isinstance(generation, dict) else None
205
+ tags = {str(record.get("world_tag")) for record in records}
206
+ widths: set[int] = set()
207
+ for tag in sorted(tags):
208
+ if WORLD_TAG_3_PATTERN.match(tag):
209
+ widths.add(3)
210
+ elif WORLD_TAG_4_PATTERN.match(tag):
211
+ widths.add(4)
212
+ else:
213
+ violations.append(Violation("world_tag_invalid", tag, "expected wNNN or wNNNN"))
214
+ if len(widths) > 1:
215
+ violations.append(Violation("world_tag_width_mismatch", "world_tag", "mixed tag widths"))
216
+ if isinstance(width, int) and widths and widths != {width}:
217
+ violations.append(
218
+ Violation("world_tag_width_mismatch", "world_tag", f"expected width {width}")
219
+ )
core_worlds/src/scripts/core_release/validate.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pack-contract validation for Core-track world packs (release contract v1).
2
+
3
+ ``collect_violations`` never raises for a bad pack: it returns one ``Violation``
4
+ per machine-checkable defect, so the CLI can print every problem at once and
5
+ callers can assert on stable codes. A world is released only when the list is
6
+ empty.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+
14
+ from .contract import (
15
+ DIFFICULTY_FILE,
16
+ MANIFEST_FILES,
17
+ PROVENANCE_FILE,
18
+ SPLIT_NAMES,
19
+ canonical_json,
20
+ read_json,
21
+ release_projection,
22
+ release_task_row,
23
+ sha256_bytes,
24
+ )
25
+ from .errors import PackContractError, Violation
26
+ from .labels import check_labels
27
+ from .layout import check_hashes, check_layout, check_world_identity, load_spec, object_field
28
+ from .leakage import check_leakage
29
+ from .semantics import check_semantic_leakage
30
+ from .tasks import check_families_and_tags, check_splits, parse_tasks
31
+
32
+
33
+ @dataclass(frozen=True, slots=True)
34
+ class ValidatedWorld:
35
+ pack_dir: Path
36
+ world_id: str
37
+ lane_id: str
38
+ spec_version: str
39
+ provenance: dict[str, object]
40
+ difficulty: dict[str, object]
41
+ spec: dict[str, object]
42
+ tasks: tuple[dict[str, object], ...] # release rows, no labels
43
+ dev_examples: tuple[dict[str, object], ...] # sanitized dev projection, file order
44
+ per_split: dict[str, int]
45
+ task_set_sha256: str
46
+
47
+
48
+ def _task_set_sha256(rows: list[dict[str, object]]) -> str:
49
+ ordered = sorted(rows, key=lambda row: str(row["task_id"]))
50
+ body = "".join(f"{canonical_json(row)}\n" for row in ordered)
51
+ return sha256_bytes(body.encode("utf-8"))
52
+
53
+
54
+ def collect_violations(
55
+ pack_dir: Path, repo_root: Path
56
+ ) -> tuple[list[Violation], ValidatedWorld | None]:
57
+ """Validate one pack; returns every violation and a world only when clean."""
58
+ pack = Path(pack_dir)
59
+ violations: list[Violation] = []
60
+ if not pack.is_dir():
61
+ return [Violation("missing_pack", str(pack), "pack directory not found")], None
62
+ if not check_layout(pack, violations):
63
+ return violations, None
64
+ try:
65
+ provenance = object_field(read_json(pack / PROVENANCE_FILE), PROVENANCE_FILE)
66
+ difficulty = object_field(read_json(pack / DIFFICULTY_FILE), DIFFICULTY_FILE)
67
+ read_json(pack / "public/source_schema.json")
68
+ except (ValueError, OSError) as exc:
69
+ return [Violation("json_parse_error", MANIFEST_FILES[0], str(exc))], None
70
+ check_hashes(pack, provenance, violations)
71
+ spec = load_spec(repo_root, provenance, violations)
72
+ if spec is None:
73
+ return violations, None
74
+ identity = check_world_identity(provenance, difficulty, spec, violations)
75
+ parsed = parse_tasks(pack, violations)
76
+ if identity is None or parsed is None:
77
+ return violations, None
78
+ world_id, lane_id = identity
79
+ by_split, public_records = parsed
80
+ check_splits(by_split, public_records, difficulty, violations)
81
+ check_labels(by_split, provenance, spec, violations)
82
+ check_families_and_tags(by_split, difficulty, spec, violations)
83
+ check_leakage(pack, by_split, provenance, violations)
84
+ rows = [
85
+ release_task_row(record, world_id=world_id, lane_id=lane_id, split=split)
86
+ for split in SPLIT_NAMES
87
+ for record in by_split[split]
88
+ ]
89
+ check_semantic_leakage(rows, by_split, violations)
90
+ if violations:
91
+ return violations, None
92
+ world = ValidatedWorld(
93
+ pack_dir=pack,
94
+ world_id=world_id,
95
+ lane_id=lane_id,
96
+ spec_version=str(difficulty["spec_version"]),
97
+ provenance=provenance,
98
+ difficulty=difficulty,
99
+ spec=spec,
100
+ tasks=tuple(sorted(rows, key=lambda row: str(row["task_id"]))),
101
+ dev_examples=tuple(
102
+ release_projection(record, world_id=world_id) for record in by_split["dev"]
103
+ ),
104
+ per_split={split: len(by_split[split]) for split in SPLIT_NAMES},
105
+ task_set_sha256=_task_set_sha256(rows),
106
+ )
107
+ return [], world
108
+
109
+
110
+ def validate_pack(pack_dir: Path, repo_root: Path) -> ValidatedWorld:
111
+ """Validate or raise ``PackContractError`` with all violations attached."""
112
+ violations, world = collect_violations(pack_dir, repo_root)
113
+ if violations or world is None:
114
+ raise PackContractError(violations)
115
+ return world
116
+
117
+
118
+ __all__ = ["ValidatedWorld", "collect_violations", "validate_pack"]
core_worlds/src/scripts/core_release/verify.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify an assembled ``release_core`` tree against its own manifest."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from .contract import (
8
+ GOLD_ARTIFACTS,
9
+ RELEASE_TASK_FIELDS,
10
+ SPLIT_NAMES,
11
+ canonical_json,
12
+ jsonl_bytes,
13
+ read_json,
14
+ read_jsonl,
15
+ sha256_bytes,
16
+ sha256_file,
17
+ )
18
+ from .errors import ReleaseError
19
+
20
+ _FORBIDDEN_NAMES = frozenset({Path(path).name for path in GOLD_ARTIFACTS}) | {
21
+ "world_rules.py",
22
+ "corruption_manifest.json",
23
+ "dev_labels.jsonl",
24
+ "hidden_iid.jsonl",
25
+ "hidden_comp.jsonl",
26
+ "hidden_transfer.jsonl",
27
+ }
28
+ _MANIFEST_NAMES = frozenset({"MANIFEST.json", "MANIFEST.sha256"})
29
+
30
+
31
+ def _tree_hashes(root: Path) -> dict[str, str]:
32
+ hashes: dict[str, str] = {}
33
+ for path in sorted(root.rglob("*")):
34
+ if path.is_file() and not path.is_symlink():
35
+ relative = path.relative_to(root).as_posix()
36
+ if relative not in _MANIFEST_NAMES:
37
+ hashes[relative] = sha256_file(path)
38
+ return hashes
39
+
40
+
41
+ def _forbidden_paths(root: Path) -> list[str]:
42
+ problems: list[str] = []
43
+ for path in sorted(root.rglob("*")):
44
+ relative = path.relative_to(root).as_posix()
45
+ if path.is_symlink():
46
+ problems.append(f"symlink:{relative}")
47
+ if "private" in path.relative_to(root).parts:
48
+ problems.append(f"private_path:{relative}")
49
+ if path.name in _FORBIDDEN_NAMES:
50
+ problems.append(f"forbidden_file:{relative}")
51
+ return problems
52
+
53
+
54
+ def _task_set_sha256(rows: list[dict[str, object]]) -> str:
55
+ ordered = sorted(rows, key=lambda row: str(row["task_id"]))
56
+ body = "".join(f"{canonical_json(row)}\n" for row in ordered)
57
+ return sha256_bytes(body.encode("utf-8"))
58
+
59
+
60
+ def verify_release(out_dir: Path) -> list[str]:
61
+ """Return every release-integrity problem (``[]`` means verified)."""
62
+ root = Path(out_dir)
63
+ if not (root / "MANIFEST.json").is_file():
64
+ raise ReleaseError("missing_manifest", f"{root}/MANIFEST.json not found")
65
+ try:
66
+ manifest = read_json(root / "MANIFEST.json")
67
+ except (ValueError, OSError) as exc:
68
+ return [f"manifest_unreadable:{exc}"]
69
+ problems: list[str] = []
70
+ if manifest.get("schema") is None:
71
+ problems.append("manifest_schema_missing")
72
+ problems.extend(_forbidden_paths(root))
73
+ sha_path = root / "MANIFEST.sha256"
74
+ if not sha_path.is_file():
75
+ return problems + ["missing:MANIFEST.sha256"]
76
+ body = sha_path.read_text(encoding="utf-8")
77
+ if manifest.get("root_sha256") != sha256_bytes(body.encode("utf-8")):
78
+ problems.append("root_digest_mismatch")
79
+ declared: dict[str, str] = {}
80
+ for line in body.splitlines():
81
+ digest, _, relative = line.partition(" ")
82
+ if not relative:
83
+ problems.append(f"malformed_manifest_line:{line!r}")
84
+ continue
85
+ declared[relative] = digest
86
+ disk = _tree_hashes(root)
87
+ for relative, digest in sorted(declared.items()):
88
+ if relative not in disk:
89
+ problems.append(f"missing:{relative}")
90
+ elif disk[relative] != digest:
91
+ problems.append(f"hash_mismatch:{relative}")
92
+ for relative in sorted(set(disk) - set(declared)):
93
+ problems.append(f"unlisted_file:{relative}")
94
+ manifest_files = manifest.get("files")
95
+ if not isinstance(manifest_files, list) or len(manifest_files) != len(declared):
96
+ problems.append("manifest_file_table_mismatch")
97
+ elif isinstance(manifest_files, list):
98
+ table = {
99
+ str(entry.get("path")): entry.get("sha256")
100
+ for entry in manifest_files
101
+ if isinstance(entry, dict)
102
+ }
103
+ if table != declared:
104
+ problems.append("manifest_file_table_mismatch")
105
+ if manifest.get("file_count") != len(declared):
106
+ problems.append("file_count_mismatch")
107
+ tasks_path = root / "tasks/tasks.jsonl"
108
+ worlds_path = root / "tasks/worlds.jsonl"
109
+ if not tasks_path.is_file() or not worlds_path.is_file():
110
+ return problems + ["missing:tasks"]
111
+ tasks = read_jsonl(tasks_path)
112
+ worlds = read_jsonl(worlds_path)
113
+ problems.extend(_verify_tasks(tasks, manifest))
114
+ problems.extend(_verify_worlds(root, tasks, worlds, manifest))
115
+ return problems
116
+
117
+
118
+ def _verify_tasks(tasks: list[dict[str, object]], manifest: dict[str, object]) -> list[str]:
119
+ problems: list[str] = []
120
+ seen: set[str] = set()
121
+ per_split = {split: 0 for split in SPLIT_NAMES}
122
+ for index, task in enumerate(tasks, 1):
123
+ if set(task) != set(RELEASE_TASK_FIELDS):
124
+ problems.append(f"task_fields:{index}:{sorted(set(task) ^ set(RELEASE_TASK_FIELDS))}")
125
+ release_id = str(task.get("release_task_id"))
126
+ if release_id in seen:
127
+ problems.append(f"duplicate_release_task_id:{release_id}")
128
+ seen.add(release_id)
129
+ split = task.get("split")
130
+ if split in per_split:
131
+ per_split[str(split)] += 1
132
+ else:
133
+ problems.append(f"task_split_invalid:{release_id}:{split!r}")
134
+ expected_id = f"{task.get('world_id')}:{task.get('task_id')}"
135
+ if release_id != expected_id:
136
+ problems.append(f"release_task_id_mismatch:{release_id}")
137
+ totals = manifest.get("totals")
138
+ if not isinstance(totals, dict):
139
+ return problems + ["manifest_totals_missing"]
140
+ if totals.get("tasks") != len(tasks):
141
+ problems.append(f"task_count_mismatch:{totals.get('tasks')}!={len(tasks)}")
142
+ if totals.get("per_split") != per_split:
143
+ problems.append(f"split_totals_mismatch:{totals.get('per_split')}!={per_split}")
144
+ return problems
145
+
146
+
147
+ def _verify_worlds(
148
+ root: Path,
149
+ tasks: list[dict[str, object]],
150
+ worlds: list[dict[str, object]],
151
+ manifest: dict[str, object],
152
+ ) -> list[str]:
153
+ problems: list[str] = []
154
+ expected_worlds = manifest.get("worlds")
155
+ if expected_worlds != worlds:
156
+ problems.append("manifest_worlds_mismatch")
157
+ by_world: dict[str, list[dict[str, object]]] = {}
158
+ for task in tasks:
159
+ by_world.setdefault(str(task.get("world_id")), []).append(task)
160
+ for row in worlds:
161
+ world_id = str(row.get("world_id"))
162
+ rows = by_world.pop(world_id, [])
163
+ if row.get("task_count") != len(rows):
164
+ problems.append(f"world_task_count_mismatch:{world_id}")
165
+ metadata_path = root / str(row.get("metadata_path"))
166
+ if not metadata_path.is_file():
167
+ problems.append(f"missing_metadata:{world_id}")
168
+ continue
169
+ try:
170
+ metadata = read_json(metadata_path)
171
+ except (ValueError, OSError) as exc:
172
+ problems.append(f"metadata_unreadable:{world_id}:{exc}")
173
+ continue
174
+ if metadata.get("task_set_sha256") != _task_set_sha256(rows):
175
+ problems.append(f"task_set_digest_mismatch:{world_id}")
176
+ counts = metadata.get("task_counts")
177
+ declared_splits = counts.get("per_split") if isinstance(counts, dict) else None
178
+ if declared_splits != row.get("per_split"):
179
+ problems.append(f"world_split_mismatch:{world_id}")
180
+ public_dir = root / "worlds" / world_id / "public"
181
+ if not public_dir.is_dir():
182
+ problems.append(f"missing_public_dir:{world_id}")
183
+ artifacts = metadata.get("artifacts")
184
+ if isinstance(artifacts, dict):
185
+ for relative, digest in artifacts.items():
186
+ path = root / "worlds" / world_id / str(relative)
187
+ if not path.is_file() or sha256_file(path) != digest:
188
+ problems.append(f"public_artifact_mismatch:{world_id}:{relative}")
189
+ sanitized = metadata.get("sanitized_files")
190
+ if isinstance(sanitized, dict):
191
+ for relative, digest in sanitized.items():
192
+ path = root / "worlds" / world_id / str(relative)
193
+ if not path.is_file() or sha256_file(path) != digest:
194
+ problems.append(f"sanitized_file_mismatch:{world_id}:{relative}")
195
+ for world_id in sorted(by_world):
196
+ problems.append(f"task_world_not_indexed:{world_id}")
197
+ totals = manifest.get("totals")
198
+ totals = totals if isinstance(totals, dict) else {}
199
+ if totals.get("worlds") != len(worlds):
200
+ problems.append("world_count_mismatch")
201
+ if jsonl_bytes(tasks) != (root / "tasks/tasks.jsonl").read_bytes():
202
+ problems.append("tasks_not_canonical")
203
+ return problems
204
+
205
+
206
+ __all__ = ["verify_release"]
core_worlds/src/scripts/eval.sh ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # eval.sh — one-click AutoOntologyBench model evaluation:
3
+ # 1. generate predictions via benchmark.eval_20k.model_runner against an
4
+ # OpenAI-compatible endpoint or Anthropic Messages API
5
+ # (keys are read from the provider-specific environment variables and
6
+ # are never printed, logged or persisted by this script)
7
+ # 2. score them via benchmark.eval_20k.run against the mounted oracle roots
8
+ #
9
+ # Usage (from anywhere; resolves the repo root itself):
10
+ # src/scripts/eval.sh # smoke: 50 tasks per lane
11
+ # src/scripts/eval.sh --sample-per-lane 0 # full run (all tasks)
12
+ # src/scripts/eval.sh --lanes L01,L05 --sample-per-lane 5
13
+ # src/scripts/eval.sh --provider openai --model gpt-4.1 --base-url https://api.openai.com/v1
14
+ # src/scripts/eval.sh --provider vllm --model local-model --base-url http://127.0.0.1:8000/v1
15
+ # src/scripts/eval.sh --provider anthropic --model claude-sonnet-4-5
16
+ #
17
+ # Env overrides: EVAL_PROVIDER, EVAL_BASE_URL, EVAL_API_KEY_ENV, EVAL_TASKS,
18
+ # EVAL_ORACLE_ROOTS (required for scoring), EVAL_MODEL,
19
+ # EVAL_MAX_TOKENS (default 32768), PYTHON_BIN (default python3).
20
+ # Artifacts: runs/eval_<UTC timestamp>/{predictions.jsonl,
21
+ # tasks_sampled.jsonl, report.json, rows.jsonl, run.log, api_logs/}.
22
+ set -euo pipefail
23
+
24
+ SRC_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
25
+ REPO_ROOT="$(cd "$SRC_ROOT/.." && pwd)"
26
+ export PYTHONPATH="$SRC_ROOT${PYTHONPATH:+:$PYTHONPATH}"
27
+ cd "$REPO_ROOT"
28
+ mkdir -p runs
29
+
30
+ if [ -z "${PYTHON_BIN:-}" ]; then
31
+ if [ -x "$REPO_ROOT/.venv/bin/python" ]; then
32
+ PYTHON_BIN="$REPO_ROOT/.venv/bin/python"
33
+ else
34
+ PYTHON_BIN="python3"
35
+ fi
36
+ fi
37
+ TASKS="${EVAL_TASKS:-AutoOntologyBench/tasks/qualified_tasks_test.jsonl}"
38
+ ORACLE_ROOTS="${EVAL_ORACLE_ROOTS:-}"
39
+ PROVIDER="${EVAL_PROVIDER:-openai}"
40
+ BASE_URL="${EVAL_BASE_URL:-}"
41
+ API_KEY_ENV="${EVAL_API_KEY_ENV:-}"
42
+ MODEL="${EVAL_MODEL:-}"
43
+ MAX_TOKENS="${EVAL_MAX_TOKENS:-32768}"
44
+ SAMPLE=50
45
+ LANE_SAMPLES="${EVAL_LANE_SAMPLES:-L11=10}"
46
+ LANES=""
47
+ WORKERS=8
48
+ RESUME=""
49
+ NO_JSON_MODE=""
50
+ THINKING=""
51
+ EXTRA_METRICS="${EVAL_EXTRA_METRICS:-1}"
52
+
53
+ while [ $# -gt 0 ]; do
54
+ case "$1" in
55
+ --provider) PROVIDER="$2"; shift 2 ;;
56
+ --base-url) BASE_URL="$2"; shift 2 ;;
57
+ --api-key-env) API_KEY_ENV="$2"; shift 2 ;;
58
+ --sample-per-lane) SAMPLE="$2"; shift 2 ;;
59
+ --lane-samples) LANE_SAMPLES="$2"; shift 2 ;;
60
+ --lanes) LANES="$2"; shift 2 ;;
61
+ --model) MODEL="$2"; shift 2 ;;
62
+ --max-tokens) MAX_TOKENS="$2"; shift 2 ;;
63
+ --workers) WORKERS="$2"; shift 2 ;;
64
+ --tasks) TASKS="$2"; shift 2 ;;
65
+ --no-json-mode) NO_JSON_MODE="--no-json-mode"; shift ;;
66
+ --thinking) THINKING="--thinking"; shift ;;
67
+ --no-extra-metrics) EXTRA_METRICS=0; shift ;;
68
+ --resume) RESUME="--resume"; shift ;;
69
+ -h|--help) sed -n '2,21p' "$0"; exit 0 ;;
70
+ *) echo "eval: unknown argument: $1" >&2; exit 2 ;;
71
+ esac
72
+ done
73
+
74
+ case "$PROVIDER" in
75
+ openai|openai-compatible)
76
+ [ -n "$MODEL" ] || MODEL="qwen3.8-max"
77
+ if [ -z "$API_KEY_ENV" ] && [ -z "${OPENAI_API_KEY:-}" ]; then
78
+ echo "eval: OPENAI_API_KEY must be set (or pass --api-key-env)" >&2
79
+ exit 3
80
+ fi ;;
81
+ vllm)
82
+ [ -n "$MODEL" ] || { echo "eval: --model is required for vllm" >&2; exit 2; } ;;
83
+ anthropic|claude)
84
+ [ -n "$MODEL" ] || { echo "eval: --model is required for anthropic/claude" >&2; exit 2; }
85
+ if [ -z "$API_KEY_ENV" ] && [ -z "${ANTHROPIC_API_KEY:-}" ]; then
86
+ echo "eval: ANTHROPIC_API_KEY must be set (or pass --api-key-env)" >&2
87
+ exit 3
88
+ fi ;;
89
+ *)
90
+ echo "eval: unknown provider $PROVIDER (openai|vllm|anthropic)" >&2
91
+ exit 2 ;;
92
+ esac
93
+
94
+ if [ ! -f "$TASKS" ]; then
95
+ echo "eval: tasks file not found: $TASKS" >&2
96
+ exit 2
97
+ fi
98
+
99
+ RUN_ID="${EVAL_RUN_ID:-$(date -u +%Y%m%dT%H%M%SZ)}"
100
+ RUN_DIR=$(mktemp -d "runs/eval_${RUN_ID}_XXXXXX")
101
+ LOG="$RUN_DIR/run.log"
102
+
103
+ LANES_ARGS=()
104
+ if [ -n "$LANES" ]; then LANES_ARGS=(--lanes "$LANES"); fi
105
+ LANE_SAMPLE_ARGS=()
106
+ if [ -n "$LANE_SAMPLES" ] && [ "$SAMPLE" != "0" ]; then
107
+ LANE_SAMPLE_ARGS=(--lane-sample "$LANE_SAMPLES")
108
+ fi
109
+ BASE_ARGS=()
110
+ if [ -n "$BASE_URL" ]; then BASE_ARGS=(--base-url "$BASE_URL"); fi
111
+ KEY_ARGS=()
112
+ if [ -n "$API_KEY_ENV" ]; then KEY_ARGS=(--api-key-env "$API_KEY_ENV"); fi
113
+ BACKEND_ARGS=(--provider "$PROVIDER" "${BASE_ARGS[@]}" "${KEY_ARGS[@]}" $NO_JSON_MODE $THINKING)
114
+
115
+ echo "== step 1/2: generate predictions (provider=$PROVIDER model=$MODEL max_tokens=$MAX_TOKENS sample_per_lane=$SAMPLE lane_samples=${LANE_SAMPLES:-none} lanes=${LANES:-all}) ==" | tee "$LOG"
116
+ "$PYTHON_BIN" -m benchmark.eval_20k.model_runner \
117
+ --tasks "$TASKS" \
118
+ --out "$RUN_DIR/predictions.jsonl" \
119
+ --model "$MODEL" \
120
+ --workers "$WORKERS" \
121
+ --max-tokens "$MAX_TOKENS" \
122
+ --sample-per-lane "$SAMPLE" \
123
+ "${BACKEND_ARGS[@]}" \
124
+ "${LANE_SAMPLE_ARGS[@]}" \
125
+ "${LANES_ARGS[@]}" $RESUME 2>&1 | tee -a "$LOG"
126
+
127
+ ORACLE_ARGS=()
128
+ OLD_IFS="$IFS"; IFS=':'
129
+ for root in $ORACLE_ROOTS; do
130
+ if [ -d "$root" ]; then ORACLE_ARGS+=(--oracle "$root"); fi
131
+ done
132
+ IFS="$OLD_IFS"
133
+ if [ "${#ORACLE_ARGS[@]}" -eq 0 ]; then
134
+ echo "eval: EVAL_ORACLE_ROOTS must point to the private oracle bundle" >&2
135
+ echo "eval: tried: $ORACLE_ROOTS" >&2
136
+ exit 3
137
+ fi
138
+
139
+ echo "== step 2/2: score predictions (oracle roots: $ORACLE_ROOTS) ==" | tee -a "$LOG"
140
+ "$PYTHON_BIN" -m benchmark.eval_20k.run \
141
+ --tasks "$RUN_DIR/tasks_sampled.jsonl" \
142
+ --no-count-check \
143
+ --predictions "$RUN_DIR/predictions.jsonl" \
144
+ "${ORACLE_ARGS[@]}" \
145
+ --no-repo-staging \
146
+ --out "$RUN_DIR" 2>&1 | tee -a "$LOG"
147
+
148
+ "$PYTHON_BIN" - "$RUN_DIR/report.json" <<'PY' | tee -a "$LOG"
149
+ import json, sys
150
+ with open(sys.argv[1], encoding="utf-8") as fh:
151
+ report = json.load(fh)
152
+ o = report["metrics"]["overall"]
153
+ fmt = lambda x: "n/a" if x is None else "%.4f" % x
154
+ print("== coverage ==")
155
+ print("tasks sampled : %d" % o["tasks"])
156
+ print("scored : %d" % o["scored"])
157
+ print("missing : %d" % o["missing"])
158
+ print("not_supported : %d" % o["not_supported"])
159
+ print("oracle_missing: %d" % o["oracle_missing"])
160
+ print("error : %d" % o["error"])
161
+ print("TSR : %s (n=%d)" % (fmt(o["tsr"]), o["tsr_denominator"]))
162
+ print("V-TSR : %s (n=%d)" % (fmt(o["v_tsr"]), o["v_tsr_denominator"]))
163
+ PY
164
+
165
+ if [ "$EXTRA_METRICS" = "1" ]; then
166
+ METRICS_DIR="$RUN_DIR/metrics"
167
+ mkdir -p "$METRICS_DIR"
168
+ FRULE_ORACLE_ARGS=()
169
+ OLD_IFS="$IFS"; IFS=':'
170
+ for root in $ORACLE_ROOTS; do
171
+ if [ -d "$root" ]; then FRULE_ORACLE_ARGS+=(--oracle-root "$root"); fi
172
+ done
173
+ IFS="$OLD_IFS"
174
+
175
+ echo "== step 3/3: extra metrics ==" | tee -a "$LOG"
176
+ "$PYTHON_BIN" -m benchmark.eval_20k.metrics_cost_cli \
177
+ --root "$RUN_DIR" --out "$METRICS_DIR" 2>&1 | tee -a "$LOG"
178
+ "$PYTHON_BIN" -m benchmark.eval_20k.metrics_batch \
179
+ --run-dir "$RUN_DIR" --batch-label "$(basename "$RUN_DIR")" \
180
+ --out "$METRICS_DIR/batch_tsr.json" 2>&1 | tee -a "$LOG"
181
+ "$PYTHON_BIN" -m benchmark.eval_20k.metrics_regime \
182
+ --runs-glob "$RUN_DIR/report.json" --tasks-dir "$RUN_DIR" \
183
+ --out "$METRICS_DIR/regime_breakdown.json" 2>&1 | tee -a "$LOG"
184
+ "$PYTHON_BIN" -m benchmark.eval_20k.metrics_mapf1 \
185
+ --run-root "$RUN_DIR" \
186
+ --out-json "$METRICS_DIR/mapf1.json" \
187
+ --out-md "$METRICS_DIR/MAPF1.md" 2>&1 | tee -a "$LOG"
188
+ "$PYTHON_BIN" -m benchmark.eval_20k.metrics_mapf1_common \
189
+ --mapf1 "$METRICS_DIR/mapf1.json" \
190
+ --allow-missing \
191
+ --out "$METRICS_DIR/mapf1_common7.json" 2>&1 | tee -a "$LOG"
192
+ "$PYTHON_BIN" -m benchmark.eval_20k.metrics_frule \
193
+ --run-root "$RUN_DIR" "${FRULE_ORACLE_ARGS[@]}" \
194
+ --out-json "$METRICS_DIR/frule.json" \
195
+ --out-md "$METRICS_DIR/FRULE.md" 2>&1 | tee -a "$LOG"
196
+ fi
197
+
198
+ echo "eval: artifacts in $RUN_DIR" | tee -a "$LOG"
core_worlds/src/scripts/eval_core.sh ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # eval_core.sh — one-click Core-track answer evaluation.
3
+ #
4
+ # 1. optionally generate predictions from an OpenAI-compatible API,
5
+ # a local vLLM OpenAI-compatible server, or Anthropic Messages API;
6
+ # 2. score them against a separately mounted private Core oracle.
7
+ #
8
+ # Usage:
9
+ # scripts/eval_core.sh --oracle /path/to/core_oracle.jsonl
10
+ # scripts/eval_core.sh --provider openai --model gpt-4.1 --base-url https://api.openai.com/v1
11
+ # scripts/eval_core.sh --provider vllm --model local-model --base-url http://127.0.0.1:8000/v1
12
+ # scripts/eval_core.sh --provider anthropic --model claude-sonnet-4-5
13
+ # scripts/eval_core.sh --predictions runs/my_harness/predictions.jsonl --oracle ...
14
+ #
15
+ # The private oracle is required for scoring and is never downloaded or printed
16
+ # by this script. API keys are read from environment variables only.
17
+ set -euo pipefail
18
+ export PYTHONDONTWRITEBYTECODE=1
19
+
20
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
21
+ PARENT="$(cd "$SCRIPT_DIR/.." && pwd)"
22
+ if [ "$(basename "$PARENT")" = "src" ] && [ -d "$PARENT/benchmark" ]; then
23
+ ROOT="$(cd "$PARENT/.." && pwd)"
24
+ SRC_ROOT="$PARENT"
25
+ else
26
+ ROOT="$PARENT"
27
+ SRC_ROOT="$ROOT"
28
+ fi
29
+ export PYTHONPATH="$SRC_ROOT${PYTHONPATH:+:$PYTHONPATH}"
30
+ cd "$ROOT"
31
+
32
+ if [ -z "${PYTHON_BIN:-}" ]; then
33
+ if [ -x "$ROOT/.venv/bin/python" ]; then
34
+ PYTHON_BIN="$ROOT/.venv/bin/python"
35
+ elif [ -x "$ROOT/.conda/envs/aob-core/bin/python" ]; then
36
+ PYTHON_BIN="$ROOT/.conda/envs/aob-core/bin/python"
37
+ else
38
+ PYTHON_BIN="python3"
39
+ fi
40
+ fi
41
+
42
+ if [ -f "$ROOT/data/core/tasks/tasks.jsonl" ]; then
43
+ DEFAULT_TASKS="$ROOT/data/core/tasks/tasks.jsonl"
44
+ else
45
+ DEFAULT_TASKS="$ROOT/release_core/tasks/tasks.jsonl"
46
+ fi
47
+
48
+ TASKS="${EVAL_TASKS:-$DEFAULT_TASKS}"
49
+ ORACLE="${EVAL_ORACLE:-${AOB_CORE_ORACLE:-}}"
50
+ PROVIDER="${EVAL_PROVIDER:-openai}"
51
+ BASE_URL="${EVAL_BASE_URL:-}"
52
+ API_KEY_ENV="${EVAL_API_KEY_ENV:-}"
53
+ MODEL="${EVAL_MODEL:-qwen3.8-max}"
54
+ SAMPLE=10
55
+ WORLDS=""
56
+ LANES=""
57
+ WORKERS=4
58
+ MAX_TOKENS="${EVAL_MAX_TOKENS:-16384}"
59
+ TEMPERATURE="${EVAL_TEMPERATURE:-0.0}"
60
+ PREDICTIONS=""
61
+ RESUME=""
62
+ NO_JSON_MODE=""
63
+ THINKING=""
64
+ OUT=""
65
+
66
+ while [ $# -gt 0 ]; do
67
+ case "$1" in
68
+ --provider) PROVIDER="$2"; shift 2 ;;
69
+ --base-url) BASE_URL="$2"; shift 2 ;;
70
+ --api-key-env) API_KEY_ENV="$2"; shift 2 ;;
71
+ --model) MODEL="$2"; shift 2 ;;
72
+ --sample-per-world) SAMPLE="$2"; shift 2 ;;
73
+ --worlds) WORLDS="$2"; shift 2 ;;
74
+ --lanes) LANES="$2"; shift 2 ;;
75
+ --workers) WORKERS="$2"; shift 2 ;;
76
+ --max-tokens) MAX_TOKENS="$2"; shift 2 ;;
77
+ --temperature) TEMPERATURE="$2"; shift 2 ;;
78
+ --tasks) TASKS="$2"; shift 2 ;;
79
+ --oracle) ORACLE="$2"; shift 2 ;;
80
+ --predictions) PREDICTIONS="$2"; shift 2 ;;
81
+ --out) OUT="$2"; shift 2 ;;
82
+ --resume) RESUME="--resume"; shift ;;
83
+ --no-json-mode) NO_JSON_MODE="--no-json-mode"; shift ;;
84
+ --thinking) THINKING="--thinking"; shift ;;
85
+ -h|--help) sed -n '2,18p' "$0"; exit 0 ;;
86
+ *) echo "eval_core: unknown argument: $1" >&2; exit 2 ;;
87
+ esac
88
+ done
89
+
90
+ if [ ! -f "$TASKS" ]; then
91
+ echo "eval_core: tasks file not found: $TASKS" >&2
92
+ exit 2
93
+ fi
94
+ if [ -z "$ORACLE" ]; then
95
+ if [ -f "$ROOT/../AutoOntologyBench-Core-private/oracle/core_oracle.jsonl" ]; then
96
+ ORACLE="$ROOT/../AutoOntologyBench-Core-private/oracle/core_oracle.jsonl"
97
+ elif [ -f "$ROOT/release_candidates/AutoOntologyBench-Core-private/oracle/core_oracle.jsonl" ]; then
98
+ ORACLE="$ROOT/release_candidates/AutoOntologyBench-Core-private/oracle/core_oracle.jsonl"
99
+ fi
100
+ fi
101
+ if [ -z "$ORACLE" ] || [ ! -e "$ORACLE" ]; then
102
+ echo "eval_core: private oracle required; pass --oracle or EVAL_ORACLE" >&2
103
+ exit 3
104
+ fi
105
+
106
+ if [ -n "$PREDICTIONS" ] && [ ! -f "$PREDICTIONS" ]; then
107
+ echo "eval_core: predictions file not found: $PREDICTIONS" >&2
108
+ exit 3
109
+ fi
110
+
111
+ if [ -z "$OUT" ]; then
112
+ RUN_ID="${EVAL_RUN_ID:-$(date -u +%Y%m%dT%H%M%SZ)}"
113
+ OUT=$(mktemp -d "runs/eval_core_${RUN_ID}_XXXXXX")
114
+ else
115
+ mkdir -p "$OUT"
116
+ fi
117
+ LOG="$OUT/run.log"
118
+ mkdir -p "$OUT"
119
+
120
+ if [ -n "$PREDICTIONS" ]; then
121
+ echo "== step 1/2: using supplied predictions ==" | tee "$LOG"
122
+ SCORE_TASKS="$TASKS"
123
+ else
124
+ case "$PROVIDER" in
125
+ openai|openai-compatible)
126
+ if [ -z "$API_KEY_ENV" ] && [ -z "${OPENAI_API_KEY:-}" ]; then
127
+ echo "eval_core: OPENAI_API_KEY must be set (or pass --api-key-env)" >&2
128
+ exit 3
129
+ fi ;;
130
+ vllm)
131
+ [ -n "$MODEL" ] || { echo "eval_core: --model is required for vllm" >&2; exit 2; } ;;
132
+ anthropic|claude)
133
+ [ -n "$MODEL" ] || { echo "eval_core: --model is required for anthropic" >&2; exit 2; }
134
+ if [ -z "$API_KEY_ENV" ] && [ -z "${ANTHROPIC_API_KEY:-}" ]; then
135
+ echo "eval_core: ANTHROPIC_API_KEY must be set (or pass --api-key-env)" >&2
136
+ exit 3
137
+ fi ;;
138
+ *) echo "eval_core: unknown provider $PROVIDER" >&2; exit 2 ;;
139
+ esac
140
+ echo "== step 1/2: generate predictions (provider=$PROVIDER model=$MODEL sample_per_world=$SAMPLE) ==" | tee "$LOG"
141
+ "$PYTHON_BIN" -m benchmark.eval_core.model_runner \
142
+ --tasks "$TASKS" \
143
+ --out "$OUT/predictions.jsonl" \
144
+ --provider "$PROVIDER" \
145
+ --model "$MODEL" \
146
+ --workers "$WORKERS" \
147
+ --sample-per-world "$SAMPLE" \
148
+ --max-tokens "$MAX_TOKENS" \
149
+ --temperature "$TEMPERATURE" \
150
+ ${BASE_URL:+--base-url "$BASE_URL"} \
151
+ ${API_KEY_ENV:+--api-key-env "$API_KEY_ENV"} \
152
+ ${WORLDS:+--worlds "$WORLDS"} \
153
+ ${LANES:+--lanes "$LANES"} \
154
+ $RESUME $NO_JSON_MODE $THINKING 2>&1 | tee -a "$LOG"
155
+ SCORE_TASKS="$OUT/tasks_sampled.jsonl"
156
+ PREDICTIONS="$OUT/predictions.jsonl"
157
+ fi
158
+
159
+ echo "== step 2/2: score predictions (oracle mounted) ==" | tee -a "$LOG"
160
+ "$PYTHON_BIN" -m benchmark.eval_core.run \
161
+ --tasks "$SCORE_TASKS" \
162
+ --predictions "$PREDICTIONS" \
163
+ --oracle "$ORACLE" \
164
+ --no-count-check \
165
+ --out "$OUT" 2>&1 | tee -a "$LOG"
166
+
167
+ echo "eval_core: artifacts in $OUT" | tee -a "$LOG"
core_worlds/src/scripts/eval_core_from_hf.sh ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Download the public AutoOntologyBench Core dataset from HuggingFace and run
3
+ # the one-click evaluator against a separately mounted private oracle.
4
+ #
5
+ # export HF_TOKEN=...
6
+ # export EVAL_ORACLE=/path/to/AutoOntologyBench-Core-private/oracle/core_oracle.jsonl
7
+ # bash src/scripts/eval_core_from_hf.sh --provider vllm --model local-model \
8
+ # --base-url http://127.0.0.1:8000/v1
9
+ set -euo pipefail
10
+
11
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
12
+ ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
13
+ cd "$ROOT"
14
+
15
+ HF_DATASET_REPO="${AOB_CORE_HF_REPO:-Vinyeh/AutoOntologyBench-Core}"
16
+ DATA_DIR="${AOB_CORE_DATA_DIR:-$ROOT/AutoOntologyBench-Core-data}"
17
+
18
+ if command -v hf >/dev/null 2>&1; then
19
+ hf download "$HF_DATASET_REPO" --repo-type dataset --local-dir "$DATA_DIR"
20
+ else
21
+ python3 - "$HF_DATASET_REPO" "$DATA_DIR" <<'PY'
22
+ import sys
23
+ from huggingface_hub import snapshot_download
24
+ repo, dest = sys.argv[1], sys.argv[2]
25
+ snapshot_download(repo_id=repo, repo_type="dataset", local_dir=dest)
26
+ PY
27
+ fi
28
+
29
+ TASKS="$DATA_DIR/data/core/tasks/tasks.jsonl"
30
+ if [ ! -f "$TASKS" ]; then
31
+ echo "eval_core_from_hf: task file not found after download: $TASKS" >&2
32
+ exit 2
33
+ fi
34
+
35
+ export EVAL_TASKS="$TASKS"
36
+ exec bash "$SCRIPT_DIR/eval_core.sh" "$@"
core_worlds/src/scripts/eval_from_hf.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Download the public AutoOntologyBench task set from HuggingFace and run the one-click
3
+ # evaluator against a separately mounted private oracle.
4
+ set -euo pipefail
5
+
6
+ SRC_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
7
+ REPO_ROOT="$(cd "$SRC_ROOT/.." && pwd)"
8
+ cd "$REPO_ROOT"
9
+
10
+ HF_DATASET_REPO="${HF_DATASET_REPO:-Vinyeh/AutoOntologyBench}"
11
+ DATA_DIR="${AOB_DATA_DIR:-$REPO_ROOT/AutoOntologyBench}"
12
+
13
+ if command -v hf >/dev/null 2>&1; then
14
+ hf download "$HF_DATASET_REPO" --repo-type dataset --local-dir "$DATA_DIR"
15
+ else
16
+ python3 - "$HF_DATASET_REPO" "$DATA_DIR" <<'PY'
17
+ import sys
18
+ from huggingface_hub import snapshot_download
19
+ repo, dest = sys.argv[1], sys.argv[2]
20
+ snapshot_download(repo_id=repo, repo_type="dataset", local_dir=dest)
21
+ PY
22
+ fi
23
+
24
+ TASKS="$DATA_DIR/tasks/qualified_tasks_test.jsonl"
25
+ if [ ! -f "$TASKS" ]; then
26
+ echo "eval_from_hf: task file not found after download: $TASKS" >&2
27
+ exit 2
28
+ fi
29
+
30
+ if [ -z "${EVAL_ORACLE_ROOTS:-}" ]; then
31
+ echo "eval_from_hf: EVAL_ORACLE_ROOTS is required." >&2
32
+ echo "Point it at the private oracle bundle, e.g.:" >&2
33
+ echo " export EVAL_ORACLE_ROOTS=$REPO_ROOT/../release_oracle/staging_20k:$REPO_ROOT/../release_oracle/staging" >&2
34
+ exit 3
35
+ fi
36
+
37
+ export EVAL_TASKS="$TASKS"
38
+ exec bash "$SRC_ROOT/scripts/eval.sh" "$@"
core_worlds/src/scripts/scan_core_release_semantics.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Correlation scan: label-equivalent public tokens in an assembled release.
3
+
4
+ Joins ``release_core/tasks/tasks.jsonl`` (and each world's shipped
5
+ ``public/examples_dev.jsonl``) to the source packs' private records and
6
+ reports every public token channel that could restate the private verdict:
7
+
8
+ - feature tokens in the verdict namespace (``polarity:*`` keys or
9
+ accepted/rejected/canonical/counterfactual value vocabulary) — the channel
10
+ the 2026-11-18 final QA found 1:1 with ``expected_ok``;
11
+ - prompts quoting their record's private variant (``counterfactual``) or
12
+ ``scenario`` id (the gated prompt channel);
13
+ - public identity fields (``template``, ``template_family``, ``family:``
14
+ feature values, ``actions[].variant``) that equal an original private name or
15
+ carry label-word vocabulary, plus each world's ``metadata.json`` family list
16
+ and ``structural_transfer`` entry;
17
+ - informationally, prompt wording that differs by polarity inside a
18
+ mixed-polarity ``(world, template_family, paraphrase_variant)`` group —
19
+ instance-value differences are ordinary task content, so this is reported
20
+ for transparency, not gated.
21
+
22
+ Content metadata that merely correlates with the label (family/model/taxon
23
+ tokens, instance names in prompts) is reported separately as informational:
24
+ it is task content, not a restated verdict. Opaque identity groups may still be
25
+ single-label by construction; the scan reports that as informational too.
26
+
27
+ Usage:
28
+ .conda/envs/aob-core/bin/python scripts/scan_core_release_semantics.py \
29
+ --release release_core [--json reports/core_semantic_neutralization/scan_after.json]
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import json
36
+ import sys
37
+ from collections import Counter, defaultdict
38
+ from dataclasses import dataclass, field
39
+ from pathlib import Path
40
+
41
+ REPO_ROOT = Path(__file__).resolve().parents[1]
42
+ if str(REPO_ROOT) not in sys.path:
43
+ sys.path.insert(0, str(REPO_ROOT))
44
+
45
+ from scripts.core_release.contract import ( # noqa: E402
46
+ LABEL_FEATURE_KEY_GATE,
47
+ LABEL_FEATURE_VALUE_PATTERN,
48
+ SPLIT_NAMES,
49
+ read_json,
50
+ read_jsonl,
51
+ )
52
+ from scripts.core_release.semantics import ( # noqa: E402
53
+ has_label_word,
54
+ private_identity_names,
55
+ public_identity_values,
56
+ )
57
+
58
+
59
+ def _verdict_token(token: str) -> bool:
60
+ key, _, value = token.partition(":")
61
+ return key in LABEL_FEATURE_KEY_GATE or bool(
62
+ LABEL_FEATURE_VALUE_PATTERN.match(value)
63
+ )
64
+
65
+
66
+ @dataclass
67
+ class ScanHits:
68
+ """Mutable accumulator shared by the task, example, and metadata surfaces."""
69
+
70
+ joined: int = 0
71
+ verdict_tokens: Counter[str] = field(default_factory=Counter)
72
+ feature_label: dict[str, dict[str, int]] = field(
73
+ default_factory=lambda: defaultdict(lambda: {"ok": 0, "bad": 0})
74
+ )
75
+ prompt_variant_hits: list[str] = field(default_factory=list)
76
+ prompt_scenario_hits: list[str] = field(default_factory=list)
77
+ identity_name_hits: Counter[str] = field(default_factory=Counter)
78
+ identity_label_word_hits: Counter[str] = field(default_factory=Counter)
79
+ identity_samples: list[str] = field(default_factory=list)
80
+
81
+ def record_identity(
82
+ self, surface: str, channel: str, value: str, names: frozenset[str]
83
+ ) -> None:
84
+ key = f"{surface}:{channel}"
85
+ if value in names:
86
+ self.identity_name_hits[key] += 1
87
+ if len(self.identity_samples) < 10:
88
+ self.identity_samples.append(f"{key}:private-name")
89
+ if has_label_word(value):
90
+ self.identity_label_word_hits[key] += 1
91
+ if len(self.identity_samples) < 10:
92
+ self.identity_samples.append(f"{key}:label-word")
93
+
94
+
95
+ def _load_private(packs: list[Path]) -> dict[tuple[str, str], dict[str, object]]:
96
+ private: dict[tuple[str, str], dict[str, object]] = {}
97
+ for pack in packs:
98
+ difficulty = read_json(pack / "manifests/difficulty.json")
99
+ world_id = str(difficulty["world_id"])
100
+ for split in SPLIT_NAMES:
101
+ name = "dev_labels" if split == "dev" else split
102
+ for record in read_jsonl(pack / "private" / f"{name}.jsonl"):
103
+ private[(world_id, str(record["task_id"]))] = record
104
+ return private
105
+
106
+
107
+ def _check_surface(
108
+ surface_rows: list[tuple[str, dict[str, object]]],
109
+ private: dict[tuple[str, str], dict[str, object]],
110
+ names: frozenset[str],
111
+ source: str,
112
+ hits: ScanHits,
113
+ ) -> None:
114
+ for world_id, row in surface_rows:
115
+ record = private.get((world_id, str(row.get("task_id"))))
116
+ if record is None:
117
+ continue
118
+ hits.joined += 1
119
+ for token in row.get("features", []):
120
+ text = str(token)
121
+ if _verdict_token(text):
122
+ hits.verdict_tokens[text] += 1
123
+ bucket = hits.feature_label[text]
124
+ bucket["ok" if record.get("expected_ok") else "bad"] += 1
125
+ for channel, value in public_identity_values(row):
126
+ hits.record_identity(source, channel, value, names)
127
+ prompt = str(row.get("prompt"))
128
+ counterfactual = record.get("counterfactual")
129
+ if (
130
+ isinstance(counterfactual, str)
131
+ and counterfactual
132
+ and counterfactual in prompt
133
+ ):
134
+ hits.prompt_variant_hits.append(f"{source}:{world_id}:{row.get('task_id')}")
135
+ scenario = str(record.get("scenario") or "")
136
+ if scenario and scenario in prompt:
137
+ hits.prompt_scenario_hits.append(f"{source}:{world_id}:{row.get('task_id')}")
138
+
139
+
140
+ def _check_metadata(
141
+ release: Path,
142
+ world_ids: list[str],
143
+ names: frozenset[str],
144
+ hits: ScanHits,
145
+ ) -> None:
146
+ for world_id in world_ids:
147
+ path = release / "worlds" / world_id / "metadata.json"
148
+ if not path.is_file():
149
+ continue
150
+ block = read_json(path).get("template_families")
151
+ if not isinstance(block, dict):
152
+ continue
153
+ families = block.get("families")
154
+ values = (
155
+ [("metadata_family", str(family)) for family in families]
156
+ if isinstance(families, list)
157
+ else []
158
+ )
159
+ structural = block.get("structural_transfer")
160
+ if isinstance(structural, str):
161
+ values.append(("metadata_structural_transfer", structural))
162
+ for channel, value in values:
163
+ hits.record_identity("metadata", channel, value, names)
164
+
165
+
166
+ def _polarity_group_summary(
167
+ task_rows: list[tuple[str, dict[str, object]]],
168
+ private: dict[tuple[str, str], dict[str, object]],
169
+ ) -> dict[str, object]:
170
+ """Informational: prompts that differ by polarity inside one family group."""
171
+ groups: dict[tuple[str, str, int], dict[bool, set[str]]] = defaultdict(
172
+ lambda: {True: set(), False: set()}
173
+ )
174
+ single_label_groups: dict[bool, int] = defaultdict(int)
175
+ for world_id, row in task_rows:
176
+ record = private.get((world_id, str(row["task_id"])))
177
+ if record is None:
178
+ continue
179
+ group = (
180
+ world_id,
181
+ str(row["template_family"]),
182
+ int(row["paraphrase_variant"]),
183
+ )
184
+ groups[group][bool(record["expected_ok"])].add(str(row["prompt"]))
185
+ for sides in groups.values():
186
+ if sides[True] and not sides[False]:
187
+ single_label_groups[True] += 1
188
+ elif sides[False] and not sides[True]:
189
+ single_label_groups[False] += 1
190
+ return {
191
+ "polarity_split_prompt_groups": {
192
+ f"{group[0]}:{group[1]}:pv{group[2]}": {
193
+ "accepted_prompts": sorted(sides[True]),
194
+ "rejected_prompts": sorted(sides[False]),
195
+ }
196
+ for group, sides in sorted(groups.items())
197
+ if sides[True] and sides[False] and sides[True] != sides[False]
198
+ },
199
+ "single_label_identity_groups": {
200
+ "accepted_only": single_label_groups[True],
201
+ "rejected_only": single_label_groups[False],
202
+ "total_groups": len(groups),
203
+ },
204
+ }
205
+
206
+
207
+ def scan(release: Path, packs: list[Path]) -> dict[str, object]:
208
+ private = _load_private(packs)
209
+ names = private_identity_names(private.values())
210
+ task_rows = [
211
+ (str(row["world_id"]), row) for row in read_jsonl(release / "tasks/tasks.jsonl")
212
+ ]
213
+ world_ids = sorted({world_id for world_id, _ in task_rows})
214
+ example_rows: list[tuple[str, dict[str, object]]] = []
215
+ for world_id in world_ids:
216
+ path = release / "worlds" / world_id / "public/examples_dev.jsonl"
217
+ if path.is_file():
218
+ example_rows.extend((world_id, row) for row in read_jsonl(path))
219
+
220
+ hits = ScanHits()
221
+ _check_surface(task_rows, private, names, "tasks.jsonl", hits)
222
+ _check_surface(example_rows, private, names, "examples_dev.jsonl", hits)
223
+ _check_metadata(release, world_ids, names, hits)
224
+
225
+ informational = _polarity_group_summary(task_rows, private)
226
+ single_polarity_content_tokens = {
227
+ token: counts
228
+ for token, counts in sorted(hits.feature_label.items())
229
+ if (counts["ok"] == 0) != (counts["bad"] == 0) and not _verdict_token(token)
230
+ }
231
+ identity_leaks = bool(
232
+ hits.identity_name_hits or hits.identity_label_word_hits
233
+ )
234
+ return {
235
+ "release": str(release),
236
+ "task_rows": len(task_rows),
237
+ "example_rows": len(example_rows),
238
+ "private_records": len(private),
239
+ "joined_rows": hits.joined,
240
+ "verdict_feature_tokens": dict(hits.verdict_tokens),
241
+ "prompt_variant_id_hits": hits.prompt_variant_hits,
242
+ "prompt_scenario_id_hits": hits.prompt_scenario_hits,
243
+ "identity_original_name_hits": sum(hits.identity_name_hits.values()),
244
+ "identity_original_name_by_channel": dict(hits.identity_name_hits),
245
+ "identity_label_word_hits": sum(hits.identity_label_word_hits.values()),
246
+ "identity_label_word_by_channel": dict(hits.identity_label_word_hits),
247
+ "identity_samples": hits.identity_samples,
248
+ **informational,
249
+ "single_polarity_content_token_count": len(single_polarity_content_tokens),
250
+ "ok": not (
251
+ hits.verdict_tokens
252
+ or hits.prompt_variant_hits
253
+ or hits.prompt_scenario_hits
254
+ or identity_leaks
255
+ ),
256
+ }
257
+
258
+
259
+ def main(argv: list[str] | None = None) -> int:
260
+ parser = argparse.ArgumentParser(description=__doc__)
261
+ parser.add_argument("--release", default="release_core", metavar="DIR")
262
+ parser.add_argument(
263
+ "--packs",
264
+ default="pilot_worlds",
265
+ metavar="GLOBROOT",
266
+ help="directory holding world_L*_scaleup/pack",
267
+ )
268
+ parser.add_argument("--json", metavar="PATH", help="write the scan summary as JSON")
269
+ args = parser.parse_args(argv)
270
+ packs = sorted(Path(args.packs).glob("world_L*_scaleup/pack"))
271
+ summary = scan(Path(args.release), packs)
272
+ if args.json:
273
+ out = Path(args.json)
274
+ out.parent.mkdir(parents=True, exist_ok=True)
275
+ out.write_text(
276
+ json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8"
277
+ )
278
+ print(f"rows joined: {summary['joined_rows']}")
279
+ print(f"verdict feature tokens (gated): {summary['verdict_feature_tokens']}")
280
+ print(
281
+ "prompts naming private variant id (gated): "
282
+ f"{len(summary['prompt_variant_id_hits'])}"
283
+ )
284
+ print(
285
+ "prompts naming private scenario id (gated): "
286
+ f"{len(summary['prompt_scenario_id_hits'])}"
287
+ )
288
+ print(
289
+ "identity fields equal to a private name (gated): "
290
+ f"{summary['identity_original_name_hits']}"
291
+ )
292
+ print(
293
+ "identity fields containing a label word (gated): "
294
+ f"{summary['identity_label_word_hits']}"
295
+ )
296
+ print(
297
+ "informational: mixed-polarity groups with polarity-split prompts: "
298
+ f"{len(summary['polarity_split_prompt_groups'])}"
299
+ )
300
+ print(
301
+ "informational: single-label opaque identity groups: "
302
+ f"{summary['single_label_identity_groups']}"
303
+ )
304
+ print(
305
+ "informational: single-polarity content feature tokens: "
306
+ f"{summary['single_polarity_content_token_count']}"
307
+ )
308
+ print("SCAN", "PASS" if summary["ok"] else "FAIL")
309
+ return 0 if summary["ok"] else 1
310
+
311
+
312
+ if __name__ == "__main__":
313
+ raise SystemExit(main())