File size: 91,219 Bytes
f726fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
"""Released environment operations and snapshot validation."""
from __future__ import annotations
from copy import deepcopy as ext_deepcopy
from datetime import datetime as ext_datetime
from datetime import timezone as ext_timezone
from functools import lru_cache
from pathlib import Path as ext_Path
from typing import Any as ext_Any
import datetime as _datetime
import hashlib as mod_hashlib
import importlib as mod_importlib
import json as mod_json
import jsonschema as mod_jsonschema
import sys as mod_sys
from .spec import CASE_DIR, DATA_STREAM_CLUSTERS, DATA_CHANGED_S, DATA_CHANGED_R, DATA__SCOPED_TOOLS, DATA_TASK_IDS, DATA_SCHEDULE_2, DATA_REGISTERED_DELTA, DATA_DRIFT_STRUCTURE_ATOMS, DATA_CHANGED_ATOMS, DATA_WRITE_TOOLS, DATA_PUBLIC_TOOLS, DATA_TASK_BLUEPRINT, DATA_CHECKOUT_CHANNELS, DATA_ENTITY_ID_FIELDS, DATA_DRIFT_CHANGED_STRUCTURES, DATA_PRICE_ZONES, DATA_TICKET_TYPES, DATA_TOOL_BY_NAME, DATA_DRIFT_CHANGED_RULES, DATA_STRUCTURE_CANDIDATE_VARIANTS, DATA_STREAM_TASK_BLUEPRINT

def fn_public_task(task_id):
    packet = fn_public_task_2(task_id)
    packet['budget']['charging'].append('Except for a documented free completion confirmation, each admitted read costs at least one work unit, including an empty result or a read-level error. If its computed returned-work cost exceeds the remaining read allowance, the call returns READ_BUDGET_EXHAUSTED without data and consumes that remaining read allowance. No booking, ticket, payment or seat is changed by a read. Calls rejected before admission, including an already exhausted read allowance, consume no additional work.')
    return packet

def fn_screening_plan_id(original_id):
    return 'fare-' + mod_hashlib.sha256(f"{'cinema-screening-contract-evolution-v5'}|{original_id}".encode()).hexdigest()[:12]

def fn_replacement_id(plan_id):
    return 'fare-' + mod_hashlib.sha256(f"{'cinema-catalogue-replacement-evolution-v4'}|{plan_id}".encode()).hexdigest()[:12]

def fn_assigned_plan_id(original_id, rule, events):
    identity = fn_screening_plan_id(original_id)
    return fn_replacement_id(identity) if 'E2' in events and rule in DATA_CHANGED_R else identity

def fn__replacement_showtime_id(atom_id):
    return fn__opaque('show', atom_id, 'replacement')

def fn__error(code, message, **data):
    return {'status': 'error', 'data': {'error_code': code, **data}, 'message': message}

def fn__success(data):
    return {'status': 'success', 'data': data, 'message': ''}

def fn_dispatch(self, name, arguments, actor_user_id):
    if self._task_id is None:
        return fn__error('TASK_NOT_ACTIVE', 'activate a task before dispatch')
    tool = DATA__SCOPED_TOOLS.get(name)
    if tool is None:
        return fn__error('TOOL_NOT_ALLOWED', 'tool is not in the learner allowlist')
    actor = self._actor(actor_user_id)
    if actor is None:
        return fn__error('ACTOR_NOT_AUTHORIZED', 'actor is not an active booking service agent')
    try:
        mod_jsonschema.validate(arguments, tool['input_schema'])
    except mod_jsonschema.ValidationError:
        return fn__error('INVALID_ARGUMENTS', 'arguments do not match the public tool schema')
    if self._calls >= 48:
        return fn__error('CALL_GUARD_EXHAUSTED', 'the runaway safety guard is exhausted')
    if name in DATA_WRITE_TOOLS and self._write_attempts >= 9:
        result = fn__error('WRITE_BUDGET_EXHAUSTED', 'the mutation-attempt budget is exhausted')
        result['budget'] = self._budget()
        return result
    if name not in DATA_WRITE_TOOLS and self._read_units >= 9:
        result = fn__error('READ_BUDGET_EXHAUSTED', 'the returned-work budget is exhausted')
        result['budget'] = self._budget()
        return result
    target_venue = self._target_venue(name, arguments)
    allowed_venues = set(actor.get('venue_ids') or [])
    if target_venue is not None and target_venue not in allowed_venues:
        return fn__error('ACTOR_VENUE_SCOPE_DENIED', 'actor is not assigned to the venue')
    before = self.snapshot()
    before_hash = self._business_hash()
    try:
        if name in DATA_WRITE_TOOLS:
            result = self._write(name, ext_deepcopy(arguments))
            if result.get('status') == 'success':
                self._assert_state_invariants()
        else:
            result = self._scope_read_result(name, self._read(name, ext_deepcopy(arguments)), allowed_venues)
    except Exception:
        self._state.restore(before['entities'])
        result = fn__error('ADAPTER_EXECUTION_FAILED', 'operation failed without committing state')
    cost = {'read_work_units': 0, 'write_attempts': 0}
    if name in DATA_WRITE_TOOLS:
        self._write_attempts += 1
        cost['write_attempts'] = 1
        if result.get('status') != 'success':
            self._state.restore(before['entities'])
    else:
        read_cost = self._read_cost(name, result)
        remaining = 9 - self._read_units
        if read_cost > remaining:
            self._read_units = 9
            result = fn__error('READ_BUDGET_EXHAUSTED', 'this read exceeds the remaining returned-work budget', required_units=read_cost, available_units=remaining)
            read_cost = remaining
        else:
            self._read_units += read_cost
        cost['read_work_units'] = read_cost
    self._calls += 1
    after_hash = self._business_hash()
    result['budget'] = self._budget()
    self._record_event(name, actor_user_id, result, before_hash, after_hash, cost)
    return ext_deepcopy(result)

def fn_opaque_event_id(task_id):
    if task_id not in DATA_TASK_IDS:
        raise ValueError(f'unknown Cinema stream task: {task_id}')
    return fn__opaque('EV', task_id).upper()

def fn_budget_contract():
    return {'limits': [{'resource': 'returned_work_units', 'allowance': 9}, {'resource': 'mutation_attempts', 'allowance': 9}, {'resource': 'maximum_tool_calls', 'allowance': 48}], 'charging': ['Returned venue, movie, and showtime rows consume one work unit each.', 'Each returned pricing-plan row consumes three work units.', 'A bounded live availability read consumes one work unit.', 'Every attempted business mutation consumes one mutation attempt, including a rejected attempt.'], 'exhaustion': 'An unfunded business call fails without changing business state.', 'persistence': 'Bookings and catalogue state persist; episode work limits replenish.'}

def fn__ordered_fixture(task_id):
    pairs = DATA_TASK_BLUEPRINT.get(task_id)
    if pairs is None:
        raise ValueError(f'unknown Cinema stream task: {task_id}')
    fixture = fn__build_fixture(task_id, DATA_STREAM_CLUSTERS, pairs, post_drift=False)
    rows = {(private['structure_atom'], private['rule_atom']): (private, public) for (private, public) in zip(fixture['targets'], fixture['public_targets'])}
    ordered_private = []
    ordered_public = []
    for (index, (atom_id, fare_key)) in enumerate(pairs, 1):
        rule_atom = fn__fare(atom_id, fare_key)['rule_atom']
        (private, public) = rows[atom_id, rule_atom]
        token = mod_hashlib.sha256(f"{'cinema-two-event-lifecycle-evolution-v1'}|{task_id}|customer|{index}".encode('ascii')).hexdigest()[:10]
        name = f'Customer {token[:6].upper()}'
        email = f'cinema-{token}@example.invalid'
        private['customer_name'] = public['customer_name'] = name
        private['customer_email'] = public['customer_email'] = email
        ordered_private.append(private)
        ordered_public.append(public)
    fixture['targets'] = ordered_private
    fixture['public_targets'] = ordered_public
    return fixture

def fn__binding_key(structure_atom, rule_atom):
    return f'{structure_atom}:{rule_atom}'

def fn__fare(atom_id, fare_key='b'):
    return fn__cluster(atom_id)['fares'][fare_key]

def fn__pre_showtime_id(atom_id):
    return fn__opaque_id('show', atom_id, 'showtime-pre-drift')

def fn__changed_binding_key(atom_id):
    return fn__binding_key(atom_id, fn__fare(atom_id)['rule_atom'])

def fn__changed_channel(atom_id):
    original = fn__fare(atom_id)['checkout_channel']
    return DATA_CHECKOUT_CHANNELS[(DATA_CHECKOUT_CHANNELS.index(original) + 1) % len(DATA_CHECKOUT_CHANNELS)]

def fn__canonical_hash(value):
    payload = mod_json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
    return mod_hashlib.sha256(payload.encode('utf-8')).hexdigest()

def fn__parse_datetime(value):
    if not isinstance(value, str):
        return None
    try:
        parsed = ext_datetime.fromisoformat(value.replace('Z', '+00:00'))
    except ValueError:
        return None
    if parsed.tzinfo is None:
        parsed = parsed.replace(tzinfo=ext_timezone.utc)
    return parsed.astimezone(ext_timezone.utc)

def fn__normalize_result(result):
    normalized = ext_deepcopy(result)
    if normalized.get('status') == 'error':
        data = normalized.setdefault('data', {})
        if not data.get('error_code'):
            message = str(normalized.get('message') or '')
            data['error_code'] = message.split(':', 1)[0] if ':' in message else 'OPERATION_FAILED'
    return normalized

def fn_public_task_2(task_id):
    packet = fn_public_task_3(task_id)
    packet['pricing_evidence_contract'] += ' ' + "Venue-active pricing plans need not be assigned to every screening. A plan's assignment to a showtime is a catalogue relationship, not a per-request quote. list_pricing_plans accepts an optional showtime_id to restrict results to that screening's assigned plans. Both scoped and venue-wide queries charge three work units per returned pricing-plan row. Previously observed assignments and terms may be reused; no current-request pricing query is required."
    return packet

def fn__opaque(prefix, *parts, length=14):
    material = '|'.join(['cinema-paid-admission-business-v4', *(str(part) for part in parts)])
    value = mod_hashlib.sha256(material.encode('ascii')).hexdigest()[:length]
    return f'{prefix}-{value}'

def fn__add_replacement_candidates(world):
    for atom_id in DATA_DRIFT_STRUCTURE_ATOMS:
        seed = world._state.get_entity('showtime', fn__pre_showtime_id(atom_id), 'showtime_id')
        if seed is None:
            raise ValueError(f'missing pre-drift showtime for {atom_id}')
        auditorium_id = fn__replacement_auditorium_id(atom_id)
        showtime_id = fn__replacement_showtime_id(atom_id)
        if world._state.get_entity('showtime', showtime_id, 'showtime_id'):
            continue
        world._state.add_entity('auditorium', {'auditorium_id': auditorium_id, 'venue_id': seed['venue_id'], 'name': f'Replacement Screen {atom_id}', 'screen_format': 'standard', 'capacity': 2 * 16, 'status': 'active', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}, 'auditorium_id')
        for zone in ('standard', 'premium'):
            for index in range(1, 16 + 1):
                world._state.add_entity('seat', {'seat_id': fn__replacement_seat_id(atom_id, zone, index), 'auditorium_id': auditorium_id, 'row_label': 'A', 'seat_number': index, 'seat_type': zone, 'status': 'available', 'price_zone': zone, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}, 'seat_id')
        world._state.add_entity('showtime', {**seed, 'showtime_id': showtime_id, 'auditorium_id': auditorium_id, 'status': 'cancelled', 'capacity': 2 * 16, 'seats_sold': 0, 'seats_held': 0, 'seats_available': 2 * 16, 'revenue_gross': 0.0, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}, 'showtime_id')

def fn__build_fixture(task_id, clusters, target_pairs, *, post_drift=False):
    entities: dict[str, list[dict[str, ext_Any]]] = {name: [] for name in DATA_ENTITY_ID_FIELDS}
    venue_ids = [fn__opaque_id('ven', cluster['atom_id'], 'venue') for cluster in clusters]
    entities['operator'] = [{'operator_id': 'agent-cinema-dev', 'full_name': 'Cinema Development Booking Agent', 'role': 'booking_service_agent', 'active': True, 'venue_ids': venue_ids, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}]
    target_set = set(target_pairs)
    targets: list[dict[str, ext_Any]] = []
    public_targets: list[dict[str, ext_Any]] = []
    buyer_names = ('Avery Moss', 'Blair Chen', 'Casey Noor', 'Devon Pike', 'Emery Vale', 'Finley Ross', 'Gray Sato', 'Harper Wynn')
    for (cluster_index, cluster) in enumerate(clusters):
        code = cluster['code']
        atom_id = cluster['atom_id']
        venue_id = fn__opaque_id('ven', atom_id, 'venue')
        auditorium_id = fn__opaque_id('aud', atom_id, 'auditorium')
        movie_id = fn__opaque_id('mov', atom_id, 'movie')
        showtime_role = 'showtime-post-drift' if post_drift and atom_id in DATA_DRIFT_CHANGED_STRUCTURES else 'showtime-pre-drift'
        showtime_id = fn__opaque_id('show', atom_id, showtime_role)
        entities['venue'].append({'venue_id': venue_id, 'name': cluster['venue_name'], 'city': cluster['city'], 'state': 'TS', 'timezone': 'UTC', 'status': 'open', 'amenities': ['reserved_seating'], 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
        entities['auditorium'].append({'auditorium_id': auditorium_id, 'venue_id': venue_id, 'name': f'Screen {cluster_index + 1}', 'screen_format': 'standard', 'capacity': 8, 'status': 'active', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
        entities['movie'].append({'movie_id': movie_id, 'title': cluster['movie_title'], 'rating': 'PG', 'runtime_minutes': 118, 'genres': ['drama'], 'release_date': '2026-05-01', 'status': 'now_playing', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
        seat_ids_by_zone: dict[str, list[str]] = {zone: [] for zone in DATA_PRICE_ZONES}
        for seat_index in range(1, 9):
            zone = 'standard' if seat_index <= 4 else 'premium'
            seat_state = 'post-drift' if post_drift and atom_id in DATA_DRIFT_CHANGED_STRUCTURES else 'pre-drift'
            seat_id = fn__opaque_id('seat', atom_id, f'{seat_state}-{seat_index:02d}')
            status = 'maintenance' if post_drift and atom_id in DATA_DRIFT_CHANGED_STRUCTURES and (seat_index == 1) else 'available'
            entities['seat'].append({'seat_id': seat_id, 'auditorium_id': auditorium_id, 'row_label': 'A' if seat_index <= 4 else 'B', 'seat_number': (seat_index - 1) % 4 + 1, 'seat_type': 'premium' if zone == 'premium' else 'standard', 'status': status, 'price_zone': zone, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
            if status == 'available':
                seat_ids_by_zone[zone].append(seat_id)
        fares = {key: fn__effective_fare(value, post_drift=post_drift) for (key, value) in cluster['fares'].items()}
        used_types = {fare['ticket_type'] for fare in fares.values()}
        distractor_types = [ticket_type for ticket_type in DATA_TICKET_TYPES if ticket_type not in used_types][:2]
        plan_rows: list[dict[str, ext_Any]] = []
        for (key, fare) in fares.items():
            broad_channel = 'online' if fare['checkout_channel'] in {'web', 'mobile'} else 'box_office' if fare['checkout_channel'] == 'box_office' else 'both'
            plan_rows.append({'pricing_plan_id': fare['pricing_plan_id'], 'venue_id': venue_id, 'name': f'Fare Terms {key.upper()}-{cluster_index + 1}', 'ticket_type': fare['ticket_type'], 'base_price': fare['base_price'], 'service_fee': fare['service_fee'], 'currency': 'USD', 'channel': broad_channel, 'status': 'active', 'rules': {'checkout_channel': fare['checkout_channel'], 'seat_zone': fare['price_zone'], 'policy_version': fare['policy_version']}, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
        for (distractor_index, ticket_type) in enumerate(distractor_types, 1):
            zone = 'premium' if ticket_type == 'premium' else 'standard'
            plan_rows.append({'pricing_plan_id': f'fare-{code}-d{distractor_index}', 'venue_id': venue_id, 'name': f'Alternate Fare {distractor_index}', 'ticket_type': ticket_type, 'base_price': 13.0 + distractor_index, 'service_fee': 1.75, 'currency': 'USD', 'channel': 'both', 'status': 'active', 'rules': {'checkout_channel': DATA_CHECKOUT_CHANNELS[(cluster_index + distractor_index) % 4], 'seat_zone': zone, 'policy_version': 'v1'}, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
        entities['pricing_plan'].extend(plan_rows)
        entities['showtime'].append({'showtime_id': showtime_id, 'venue_id': venue_id, 'auditorium_id': auditorium_id, 'movie_id': movie_id, 'starts_at': cluster['starts_at'], 'ends_at': cluster['starts_at'], 'business_date': cluster['starts_at'][:10], 'language': 'English', 'format': 'standard', 'status': 'sales_open', 'pricing_plan_ids': [row['pricing_plan_id'] for row in plan_rows], 'capacity': 8, 'seats_sold': 0, 'seats_held': 0, 'seats_available': 7 if post_drift and atom_id in DATA_DRIFT_CHANGED_STRUCTURES else 8, 'revenue_gross': 0.0, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
        if task_id == 'DEV01' and cluster_index == 0:
            expired_seat = seat_ids_by_zone['standard'][0]
            entities['seat_hold'].append({'hold_id': 'hold-expired-dev-1', 'showtime_id': showtime_id, 'member_id': None, 'channel': 'web', 'seat_ids': [expired_seat], 'status': 'active', 'expires_at': '2026-05-27T11:50:00Z', 'converted_booking_id': None, 'pricing_plan_id': fares['a']['pricing_plan_id'], 'ticket_type': fares['a']['ticket_type'], 'created_at': '2026-05-27T11:35:00Z', 'updated_at': '2026-05-27T11:35:00Z'})
        for (fare_key, fare) in fares.items():
            if (atom_id, fare_key) not in target_set:
                continue
            target_id = f'admission-{task_id.lower()}-{len(targets) + 1}'
            customer_name = f'{buyer_names[cluster_index]} {task_id}'
            customer_email = f'{target_id}@example.invalid'
            target = {'target_id': target_id, 'structure_atom': atom_id, 'rule_atom': fare['rule_atom'], 'venue_id': venue_id, 'auditorium_id': auditorium_id, 'movie_id': movie_id, 'showtime_id': showtime_id, 'preferred_seat_ids': seat_ids_by_zone[fare['price_zone']][:2], 'pricing_plan_id': fare['pricing_plan_id'], 'ticket_type': fare['ticket_type'], 'price_zone': fare['price_zone'], 'checkout_channel': fare['checkout_channel'], 'customer_name': customer_name, 'customer_email': customer_email, 'quantity': 1, 'expected_total': round(fare['base_price'] + fare['service_fee'], 2), 'policy_version': fare['policy_version']}
            targets.append(target)
            public_targets.append({'target_id': target_id, 'customer_name': customer_name, 'customer_email': customer_email, 'venue_name': cluster['venue_name'], 'city': cluster['city'], 'movie_title': cluster['movie_title'], 'starts_at': cluster['starts_at'], 'ticket_type': fare['ticket_type'], 'price_zone': fare['price_zone'], 'quantity': 1})
    if len(targets) != 4:
        raise ValueError(f'{task_id} must compile exactly four targets')
    return {'task_id': task_id, 'actor_user_id': 'agent-cinema-dev', 'entities': entities, 'targets': targets, 'public_targets': public_targets, 'post_drift': post_drift}

def fn__cluster(atom_id):
    return next((row for row in DATA_STREAM_CLUSTERS if row['atom_id'] == atom_id))

def fn__opaque_id(prefix, atom_id, role):
    digest = mod_hashlib.sha256(f'rescope-cinema-successor-v3|{atom_id}|{role}'.encode('utf-8')).hexdigest()[:12]
    return f'{prefix}-{digest}'

def fn_public_task_3(task_id):
    packet = fn_public_task_4(task_id)
    packet['objective'] = packet['objective'].replace('in priority order', 'in any order')
    packet['completion'].update(mode='independent', priority_order='none', started_item_must_close=False)
    packet['completion']['request_order'] = "Customer admissions are independent. An incomplete request does not block another customer's booking. Each booking still requires eligible current pricing, current-request live-seat evidence, available seats and payment."
    return packet

def fn_channel_category(checkout):
    if checkout in {'web', 'mobile'}:
        return 'online'
    if checkout == 'box_office':
        return 'box_office'
    if checkout == 'group_sales':
        return 'both'
    raise ValueError('Unknown cinema checkout channel')

def fn__replacement_auditorium_id(atom_id):
    return fn__opaque('aud', atom_id, 'replacement')

def fn__replacement_seat_id(atom_id, zone, index):
    zone_code = 'p' if zone == 'premium' else 's'
    return fn__opaque('seat', atom_id, zone_code, index, length=12)

def fn__effective_fare(fare, *, post_drift):
    value = ext_deepcopy(fare)
    if post_drift and value['rule_atom'] in DATA_DRIFT_CHANGED_RULES:
        value['checkout_channel'] = fn__rotated_channel(value['checkout_channel'])
        value['policy_version'] = 'v2'
    else:
        value['policy_version'] = 'v1'
    return value

def fn_public_task_4(task_id):
    packet = fn_public_task_5(task_id)
    packet['pricing_evidence_contract'] = 'A posted pricing plan and its checkout terms are venue/ticket-type catalogue facts, not a quote or authorization that expires at the end of a request. A paid booking does not itself change those terms. Booking validates the currently applicable plan, ticket type, seat zone and checkout channel; a current-request pricing query is not a prerequisite. Catalogue updates can invalidate earlier terms. Seat availability is different: seats must have been returned as available in this request, and booking checks their current availability again. The pricing channel category groups the exact checkout channel; rules.checkout_channel specifies the accepted checkout value.'
    return packet

def fn__add_structure_candidates(adapter):
    cluster = fn__cluster_2('S03')
    seed = adapter._state.get_entity('showtime', fn__pre_showtime_id_2('S03'), 'showtime_id')
    if seed is None:
        raise AssertionError('Cinema S03 seed showtime is absent')
    for (variant_index, variant) in enumerate(DATA_STRUCTURE_CANDIDATE_VARIANTS, 1):
        auditorium_id = fn__candidate_auditorium_id(variant)
        showtime_id = fn__candidate_showtime_id(variant)
        adapter._state.add_entity('auditorium', {'auditorium_id': auditorium_id, 'venue_id': seed['venue_id'], 'name': f'Reserve Screen {variant_index}', 'screen_format': 'standard', 'capacity': 2 * 16, 'status': 'active', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}, 'auditorium_id')
        for zone in ('standard', 'premium'):
            for index in range(1, 16 + 1):
                adapter._state.add_entity('seat', {'seat_id': fn__candidate_seat_id(variant, zone, index), 'auditorium_id': auditorium_id, 'row_label': 'A', 'seat_number': index, 'seat_type': zone, 'status': 'available', 'price_zone': zone, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}, 'seat_id')
        adapter._state.add_entity('showtime', {**seed, 'showtime_id': showtime_id, 'auditorium_id': auditorium_id, 'status': 'cancelled', 'capacity': 2 * 16, 'seats_sold': 0, 'seats_held': 0, 'seats_available': 2 * 16, 'revenue_gross': 0.0, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}, 'showtime_id')

def fn__rotated_channel(channel):
    return DATA_CHECKOUT_CHANNELS[(DATA_CHECKOUT_CHANNELS.index(channel) + 1) % len(DATA_CHECKOUT_CHANNELS)]

def fn_public_task_5(task_id):
    return {'schema': 'rescopebench-cinema-evolution-task/v1', 'event_id': fn_opaque_event_id(task_id), 'objective': 'Complete paid cinema admissions for the listed customers, venue, film, time, ticket type and seat zone in priority order. Select currently eligible pricing terms and read live available seats before booking. A successful paid-booking receipt confirms its issued tickets, captured payment and allocation; no additional readback is required.', 'targets': fn_public_stream_targets(task_id), 'budget': fn_budget_contract(), 'completion': {'mode': 'ordered_independent', 'subset_allowed': True, 'priority_order': 'listed', 'started_item_must_close': True, 'evidence': {'mode': 'authoritative_receipt', 'source': 'successful paid create_booking', 'proves': 'issued tickets, captured payment and committed seats'}}}

def fn__expanded_initial_entities():
    entities = ext_deepcopy(fn__pre_fixture('T01')['entities'])
    seats = entities['seat']
    existing = {row['seat_id'] for row in seats}
    auditoriums = {row['auditorium_id']: row for row in entities['auditorium']}
    showtimes = {row['auditorium_id']: row for row in entities['showtime']}
    for cluster in DATA_STREAM_CLUSTERS:
        auditorium_id = fn__opaque_id('aud', cluster['atom_id'], 'auditorium')
        for zone in DATA_PRICE_ZONES:
            if zone == 'accessibility':
                continue
            prefix = 's' if zone == 'standard' else 'p'
            current = [row for row in seats if row['auditorium_id'] == auditorium_id and row['price_zone'] == zone]
            for index in range(len(current) + 1, 16 + 1):
                seat_id = f"seat-{cluster['code']}-stream-{prefix}{index:02d}"
                if seat_id in existing:
                    continue
                seats.append({'seat_id': seat_id, 'auditorium_id': auditorium_id, 'row_label': 'S' if zone == 'standard' else 'P', 'seat_number': index, 'seat_type': zone, 'status': 'available', 'price_zone': zone, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
                existing.add(seat_id)
        auditoriums[auditorium_id]['capacity'] = 2 * 16
        showtime = showtimes[auditorium_id]
        showtime.update({'capacity': 2 * 16, 'seats_sold': 0, 'seats_held': 0, 'seats_available': 2 * 16, 'revenue_gross': 0.0})
    return entities

def fn__cluster_2(atom_id):
    return next((row for row in DATA_STREAM_CLUSTERS if row['atom_id'] == atom_id))

def fn__pre_showtime_id_2(atom_id):
    return fn__opaque_id('show', atom_id, 'showtime-pre-drift')

def fn__candidate_auditorium_id(variant):
    return fn__opaque_2('aud', 'S03', variant)

def fn__candidate_showtime_id(variant):
    return fn__opaque_2('show', 'S03', variant)

def fn__candidate_seat_id(variant, zone, index):
    token = fn__opaque_2('seat', 'S03', variant, length=10)
    zone_code = 'p' if zone == 'premium' else 's'
    return f'{token}-{index:02d}-{zone_code}'

def fn_public_stream_targets(task_id):
    return [{'request_reference': fn_opaque_request_id(task_id, index), 'customer_name': target['customer_name'], 'customer_email': target['customer_email'], 'venue_name': target['venue_name'], 'city': target['city'], 'movie_title': target['movie_title'], 'starts_at': target['starts_at'], 'ticket_type': target['ticket_type'], 'price_zone': target['price_zone'], 'quantity': target['quantity']} for (index, target) in enumerate(fn__ordered_fixture(task_id)['public_targets'], 1)]

@lru_cache(**{'maxsize': 4, 'typed': False})
def fn__load_raw_logic(source_root):
    prefix = 'mcp_servers'
    saved = {name: module for (name, module) in list(mod_sys.modules.items()) if name == prefix or name.startswith(f'{prefix}.')}
    for name in saved:
        mod_sys.modules.pop(name, None)
    mod_sys.path.insert(0, source_root)
    try:
        library = mod_importlib.import_module('mcp_servers.cinema_lib')
        implementation = mod_importlib.import_module('mcp_servers.tool_impl')

        def expiry_aware_active_hold_seats(state_manager, showtime_id, *, except_hold_id=None):
            held: set[str] = set()
            for hold in state_manager.list_entities('seat_hold'):
                expires_at = library.parse_datetime(hold.get('expires_at'))
                if hold.get('showtime_id') == showtime_id and hold.get('status') == 'active' and (hold.get('hold_id') != except_hold_id) and (expires_at is not None) and (expires_at > library.RUNTIME_NOW):
                    held.update(hold.get('seat_ids') or [])
            return held
        library.active_hold_seats = expiry_aware_active_hold_seats
        implementation.active_hold_seats = expiry_aware_active_hold_seats
    finally:
        mod_sys.path.remove(source_root)
        for name in list(mod_sys.modules):
            if name == prefix or name.startswith(f'{prefix}.'):
                mod_sys.modules.pop(name, None)
        mod_sys.modules.update(saved)
    return (implementation, library)

def fn__pre_fixture(task_id):
    pairs = DATA_STREAM_TASK_BLUEPRINT.get(task_id)
    if pairs is None:
        raise ValueError(f'unknown Cinema stream task: {task_id}')
    fixture = fn__build_fixture(task_id, DATA_STREAM_CLUSTERS, pairs, post_drift=False)
    for (index, (private, public)) in enumerate(zip(fixture['targets'], fixture['public_targets']), 1):
        token = fn__digest({'case': 'cinema_c_20_04_03', 'task': task_id, 'customer': index})[:10]
        name = f'Customer {token[:6].upper()}'
        email = f'cinema-{token}@example.invalid'
        private['customer_name'] = public['customer_name'] = name
        private['customer_email'] = public['customer_email'] = email
    return fixture

def fn__opaque_2(prefix, *parts, length=14):
    material = '|'.join(['cinema-paid-admission-business-v2', *(str(part) for part in parts)])
    value = mod_hashlib.sha256(material.encode('ascii')).hexdigest()[:length]
    return f'{prefix}-{value}'

def fn_opaque_request_id(task_id, index):
    return fn__opaque('RQ', task_id, index, length=10).upper()

def fn__digest(value):
    return mod_hashlib.sha256(fn__canonical(value).encode('ascii')).hexdigest()

def fn__canonical(value):
    return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), allow_nan=False)

class World:

    def public_task(self):
        return fn_public_task(self._task_id)

    def _apply_event(self, event_id):
        receipt = self._cinema_catalogue_world_apply_event(event_id)
        if not receipt['applied']:
            return receipt
        for cluster in DATA_STREAM_CLUSTERS:
            if cluster['atom_id'] not in DATA_CHANGED_S:
                continue
            replacements = {}
            for fare in cluster['fares'].values():
                (original_id, rule) = (fare['pricing_plan_id'], fare['rule_atom'])
                first_id = fn_screening_plan_id(original_id)
                if event_id == 'E1':
                    plan = ext_deepcopy(self._state.get_entity('pricing_plan', original_id, 'pricing_plan_id'))
                    plan['pricing_plan_id'] = first_id
                    self._state.add_entity('pricing_plan', plan, 'pricing_plan_id')
                elif rule in DATA_CHANGED_R:
                    current = self._state.get_entity('pricing_plan', fn_replacement_id(original_id), 'pricing_plan_id')
                    plan = ext_deepcopy(current)
                    plan['pricing_plan_id'] = fn_replacement_id(first_id)
                    self._state.add_entity('pricing_plan', plan, 'pricing_plan_id')
                    self._state.update_entity('pricing_plan', first_id, {'status': 'inactive'}, 'pricing_plan_id')
                replacements[original_id] = fn_assigned_plan_id(original_id, rule, self._applied_boundary_events)
            show_id = fn__replacement_showtime_id(cluster['atom_id'])
            show = self._state.get_entity('showtime', show_id, 'showtime_id')
            superseded = set(replacements) | {fn_replacement_id(p) for p in replacements}
            superseded |= {fn_screening_plan_id(p) for p in replacements}
            assigned = [p for p in show['pricing_plan_ids'] if p not in superseded]
            self._state.update_entity('showtime', show_id, {'pricing_plan_ids': list(dict.fromkeys([*assigned, *replacements.values()]))}, 'showtime_id')
        self._assert_state_invariants()
        receipt['after'] = self.business_hash()
        return receipt

    def _resolve_target(self, target):
        value = self._cinema_catalogue_world_resolve_target(target)
        if 'E1' in self._applied_boundary_events and target['structure_atom'] in DATA_CHANGED_S:
            value['pricing_plan_id'] = fn_assigned_plan_id(target['pricing_plan_id'], target['rule_atom'], self._applied_boundary_events)
        return value

    def _read(self, name, arguments):
        if name != 'list_pricing_plans' or 'showtime_id' not in arguments:
            return self._cinema_current_pricing_read(name, arguments)
        show = self._state.get_entity('showtime', arguments['showtime_id'], 'showtime_id')
        if show is None:
            return fn__error('SHOWTIME_NOT_FOUND', 'showtime does not exist')
        if show['venue_id'] != arguments['venue_id']:
            return fn__error('SHOWTIME_VENUE_MISMATCH', 'showtime does not belong to the requested venue')
        rows = [r for r in self._state.list_entities('pricing_plan') if r['pricing_plan_id'] in show['pricing_plan_ids'] and r['venue_id'] == arguments['venue_id']]
        for field in ('ticket_type', 'status'):
            if arguments.get(field):
                rows = [r for r in rows if r.get(field) == arguments[field]]
        rows.sort(key=lambda r: (r.get('ticket_type', ''), r['pricing_plan_id']))
        (total, rows) = self._page(rows, arguments.get('offset', 0), arguments.get('limit', 4))
        fields = ('pricing_plan_id', 'name', 'ticket_type', 'base_price', 'service_fee', 'currency', 'channel', 'status', 'rules')
        projected = [{key: ext_deepcopy(row.get(key)) for key in fields} for row in rows]
        for row in projected:
            row['rules'].pop('policy_version', None)
        return fn__success({'total_count': total, 'pricing_plans': projected})

    def dispatch(self, name, arguments, actor_user_id):
        if name == 'list_pricing_plans' and 'showtime_id' in arguments:
            return fn_dispatch(self, name, arguments, actor_user_id)
        return self._business_cinema_successor_dispatch(name, arguments, actor_user_id)

    def public_tool_schemas(self, role):
        tools = ext_deepcopy(self._business_cinema_successor_public_tool_schemas(role))
        for tool in tools:
            if tool['name'] == 'list_pricing_plans':
                tool['input_schema'] = ext_deepcopy(DATA__SCOPED_TOOLS['list_pricing_plans']['input_schema'])
                tool['description'] += ' ' + "Venue-active pricing plans need not be assigned to every screening. A plan's assignment to a showtime is a catalogue relationship, not a per-request quote. list_pricing_plans accepts an optional showtime_id to restrict results to that screening's assigned plans. Both scoped and venue-wide queries charge three work units per returned pricing-plan row. Previously observed assignments and terms may be reused; no current-request pricing query is required."
        return tools

    def snapshot(self):
        value = self._cinema_catalogue_world_snapshot()
        value['evolution']['case_version'] = 'cinema-screening-contract-evolution-v5'
        return value

    def restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        if value.get('evolution', {}).get('case_version') != 'cinema-screening-contract-evolution-v5':
            raise ValueError('Cinema screening-contract snapshot version differs')
        value['evolution']['case_version'] = 'cinema-catalogue-replacement-evolution-v4'
        self._cinema_catalogue_world_restore(value)

    def _priority_guard(self, arguments):
        return None

    def __init__(self, source_root=CASE_DIR / 'raw'):
        self._business_cinema_successor_init(source_root=source_root)
        for auditorium in self._state.list_entities('auditorium'):
            aid = auditorium['auditorium_id']
            for zone in ('standard', 'premium'):
                existing = [s for s in self._state.list_entities('seat') if s['auditorium_id'] == aid and s['price_zone'] == zone]
                for index in range(len(existing) + 1, 32 + 1):
                    self._state.add_entity('seat', {'seat_id': 'seat-' + mod_hashlib.sha256(f"{'cinema-two-event-lifecycle-evolution-v1'}|{aid}|{zone}|{index}".encode()).hexdigest()[:16], 'auditorium_id': aid, 'row_label': 'E', 'seat_number': index, 'seat_type': zone, 'status': 'available', 'price_zone': zone, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}, 'seat_id')
            self._state.update_entity('auditorium', aid, {'capacity': 32 * 2}, 'auditorium_id')
        for show in self._state.list_entities('showtime'):
            self._state.update_entity('showtime', show['showtime_id'], {'capacity': 32 * 2}, 'showtime_id')
        self._recompute_all_showtimes()
        self._assert_state_invariants()

    def activate_task(self, task_id, **kwargs):
        if task_id not in DATA_TASK_IDS:
            raise ValueError('unknown cinema task')
        receipt = fn__success({'event_id': fn_opaque_event_id(task_id), 'public_notice': '', 'budget': fn_budget_contract()})
        if task_id == self._task_id:
            return receipt
        if task_id != DATA_TASK_IDS[len(self._activated_tasks)]:
            raise ValueError('cinema tasks must follow their declared persistent prefix')
        for event in DATA_SCHEDULE_2['events']:
            if event['before_task'] == int(task_id[1:]):
                self._apply_event(event['event_id'])
        self._task_id = task_id
        self._activated_tasks.append(task_id)
        self._task_targets = [self._resolve_target(t) for t in fn__ordered_fixture(task_id)['targets']]
        self._calls = self._read_units = self._write_attempts = 0
        self._fresh_available_seats = {}
        return receipt

    @staticmethod
    def _showtime_projection(row):
        return {key: row.get(key) for key in ('showtime_id', 'venue_id', 'movie_id', 'auditorium_id', 'starts_at', 'status', 'format', 'seats_available')}

    def _observe_cancelled_showtimes(self, rows):
        cancelled_ids = {row['showtime_id'] for row in rows if row.get('status') == 'cancelled'}
        if not cancelled_ids:
            return
        for (key, expected) in self._expected_stale_bindings.items():
            if expected.get('showtime_id') in cancelled_ids and self._binding_revalidation.get(key) == 'awaiting_exact_stale':
                self._binding_revalidation[key] = 'awaiting_current_evidence'

    def _search_showtimes(self, arguments):
        if set(arguments) != {'venue_id', 'movie_id', 'starts_at', 'status'}:
            return fn__error('EXACT_SALES_OPEN_TUPLE_REQUIRED', 'venue_id, movie_id, starts_at, and status=sales_open are required')
        if arguments.get('status') != 'sales_open':
            return fn__error('SALES_OPEN_REQUIRED', 'exact showtime resolution requires status=sales_open')
        candidates = [row for row in self._state.list_entities('showtime') if row.get('venue_id') == arguments['venue_id'] and row.get('movie_id') == arguments['movie_id'] and (row.get('starts_at') == arguments['starts_at'])]
        feasible = [row for row in candidates if row.get('status') == 'sales_open']
        negative = sorted((row for row in candidates if row.get('status') != 'sales_open'), key=lambda row: (row.get('status', ''), row['showtime_id']))
        self._observe_cancelled_showtimes(negative)
        if len(feasible) > 1:
            return fn__error('AMBIGUOUS_SALES_OPEN_SHOWTIME', 'the exact tuple has multiple sales-open showtimes')
        resolved = self._showtime_projection(feasible[0]) if feasible else None
        negative_evidence = [{'showtime_id': row['showtime_id'], 'auditorium_id': row.get('auditorium_id'), 'status': row.get('status'), 'reason': 'not_sales_open'} for row in negative]
        return fn__success({'resolution_status': 'resolved' if resolved else 'no_sales_open_match', 'resolved_showtime': resolved, 'total_count': int(resolved is not None), 'showtimes': [resolved] if resolved else [], 'negative_evidence': negative_evidence, 'matched_candidate_count': len(candidates)})

    def _get_showtime_availability(self, arguments):
        showtime = self._state.get_entity('showtime', arguments['showtime_id'], 'showtime_id')
        if showtime is None:
            return fn__error('SHOWTIME_NOT_FOUND', 'showtime does not exist')
        if showtime.get('status') != 'sales_open':
            self._observe_cancelled_showtimes([showtime])
            data: dict[str, ext_Any] = {'showtime_id': showtime['showtime_id'], 'status': showtime.get('status'), 'availability': self._seat_summary(showtime), 'evidence_kind': 'non_bookable_status'}
            if arguments.get('include_seat_details', False):
                data['seat_total_count'] = 0
                data['seats'] = []
            return fn__success(data)
        return self._business_cinema_successor_get_showtime_availability(arguments)

    @staticmethod
    def _read_cost(name, result):
        if result.get('status') != 'success':
            return 1
        data = result.get('data') or {}
        if name == 'get_showtime_availability':
            return 1
        if name == 'list_pricing_plans':
            return max(1, 3 * len(data.get('pricing_plans') or []))
        return World._cinema_adapter_read_cost(name, result)

    def _target_key(self, target):
        return fn__binding_key(target['structure_atom'], target['rule_atom'])

    def _target_index_for_booking(self, arguments):
        return next((index for (index, target) in enumerate(self._task_targets) if target['customer_name'] == arguments.get('customer_name') and target['customer_email'] == arguments.get('customer_email')), None)

    def _is_exact_stale_attempt(self, target, arguments):
        expected = self._expected_stale_bindings.get(self._target_key(target))
        if expected is None:
            return False
        requested = set(arguments.get('seat_ids') or [])
        showtime_id = arguments.get('showtime_id')
        fresh = self._fresh_available_seats.get(showtime_id, set())
        showtime = self._state.get_entity('showtime', showtime_id, 'showtime_id')
        seats = [self._state.get_entity('seat', seat_id, 'seat_id') for seat_id in requested]
        valid_showtimes = {expected['showtime_id'], DATA_REGISTERED_DELTA['after'][target['structure_atom']]['showtime_id']}
        return bool(requested and len(requested) == target['quantity'] and (requested <= fresh) and (showtime_id in valid_showtimes) and (showtime is not None) and all((seat is not None and seat.get('auditorium_id') == showtime.get('auditorium_id') and (seat.get('price_zone') == target['price_zone']) for seat in seats)) and (arguments.get('pricing_plan_id') == expected['pricing_plan_id']) and (arguments.get('ticket_type') == target['ticket_type']) and (arguments.get('channel') == expected['checkout_channel']) and (not arguments.get('hold_id')) and (arguments.get('capture_payment', True) is True))

    def _create_booking(self, arguments):
        priority_error = self._priority_guard(arguments)
        if priority_error is not None:
            return priority_error
        target_index = self._target_index_for_booking(arguments)
        target = self._task_targets[target_index] if target_index is not None else None
        exact_stale = bool(target is not None and self._binding_revalidation.get(self._target_key(target)) == 'awaiting_exact_stale' and self._is_exact_stale_attempt(target, arguments))
        result = self._business_cinema_successor_create_booking(arguments)
        if target_index is not None:
            assert target is not None
            key = self._target_key(target)
            if exact_stale and result.get('data', {}).get('error_code') in {'SHOWTIME_NOT_BOOKABLE', 'CHECKOUT_CHANNEL_MISMATCH'}:
                self._binding_revalidation[key] = 'awaiting_current_evidence'
        return result

    def _apply_drift(self, event_id='evt-cinema-independent-routing-91d80e63'):
        before = self.business_hash()
        if event_id in self._applied_boundary_events:
            return {'event_id': event_id, 'application_count': self._business_event_application_count, 'applied': False, 'idempotent_noop': True, 'before_world_sha256': before, 'after_world_sha256': before, 'registered_delta_sha256': 'ef0bbf84b8c737cd6ba5e25b2dea7b3f4b50af80bdc2af67a33a76e7e0306de1'}
        expected: dict[str, dict[str, ext_Any]] = {}
        for atom_id in DATA_DRIFT_STRUCTURE_ATOMS:
            fare = fn__fare(atom_id)
            old_showtime = self._state.get_entity('showtime', fn__pre_showtime_id(atom_id), 'showtime_id')
            replacement = self._state.get_entity('showtime', fn__replacement_showtime_id(atom_id), 'showtime_id')
            plan = self._state.get_entity('pricing_plan', fare['pricing_plan_id'], 'pricing_plan_id')
            if old_showtime is None or replacement is None or plan is None:
                raise ValueError(f'Cinema v4 drift authority is incomplete for {atom_id}')
            key = fn__changed_binding_key(atom_id)
            expected[key] = {'structure_atom': atom_id, 'rule_atom': fare['rule_atom'], 'showtime_id': old_showtime['showtime_id'], 'pricing_plan_id': plan['pricing_plan_id'], 'checkout_channel': (plan.get('rules') or {})['checkout_channel']}
            self._state.update_entity('showtime', old_showtime['showtime_id'], {'status': 'cancelled', 'updated_at': '2026-05-27T12:00:00Z'}, 'showtime_id')
            self._state.update_entity('showtime', replacement['showtime_id'], {'status': 'sales_open', 'updated_at': '2026-05-27T12:00:00Z'}, 'showtime_id')
            rules = ext_deepcopy(plan.get('rules') or {})
            rules.update({'checkout_channel': fn__changed_channel(atom_id), 'policy_version': 'current'})
            self._state.update_entity('pricing_plan', plan['pricing_plan_id'], {'rules': rules, 'updated_at': '2026-05-27T12:00:00Z'}, 'pricing_plan_id')
        self._expected_stale_bindings = expected
        self._binding_revalidation = {key: 'awaiting_exact_stale' for key in expected}
        self._applied_boundary_events.add(event_id)
        self._business_event_application_count = 1
        self._recompute_all_showtimes()
        self._assert_state_invariants()
        after = self.business_hash()
        return {'event_id': event_id, 'application_count': 1, 'applied': True, 'idempotent_noop': False, 'changed_atoms': list(DATA_CHANGED_ATOMS), 'before_world_sha256': before, 'after_world_sha256': after, 'registered_delta_sha256': 'ef0bbf84b8c737cd6ba5e25b2dea7b3f4b50af80bdc2af67a33a76e7e0306de1'}

    def apply_business_event(self):
        return self._apply_drift('evt-cinema-independent-routing-91d80e63')

    @property
    def activated_tasks(self):
        return tuple(self._activated_tasks)

    @property
    def applied_boundary_events(self):
        return frozenset(self._applied_boundary_events)

    def business_hash(self):
        return fn__canonical_hash({'entities': self._state.list_snapshot(), 'applied_boundary_events': sorted(self._applied_boundary_events)})

    def lineage_hash(self):
        return fn__canonical_hash(self.snapshot())

    def _active_showtime(self, target):
        seed = self._state.get_entity('showtime', target['showtime_id'], 'showtime_id')
        if seed is None:
            raise AssertionError('seed showtime disappeared from the persistent world')
        rows = [row for row in self._state.list_entities('showtime') if row.get('venue_id') == seed['venue_id'] and row.get('movie_id') == seed['movie_id'] and (row.get('starts_at') == seed['starts_at']) and (row.get('status') == 'sales_open')]
        if len(rows) != 1:
            raise AssertionError('expected one active showtime for the stream target')
        return rows[0]

    def apply_stream_drift(self, event_id='evt-cinema-catalog-policy-2026-07-v2'):
        return self._apply_drift(event_id)

    def close(self):
        return None

    def semantic_hash(self, snapshot=None):
        return fn__canonical_hash(snapshot if snapshot is not None else self.snapshot())

    def business_events(self, since=0):
        if not isinstance(since, int) or isinstance(since, bool) or since < 0:
            raise ValueError('since must be a non-negative integer')
        return ext_deepcopy(self._events[since:])

    def task_targets(self):
        return ext_deepcopy(self._task_targets)

    def _actor(self, actor_user_id):
        actor = self._state.get_entity('operator', actor_user_id, 'operator_id')
        if not actor or not actor.get('active') or actor.get('role') != 'booking_service_agent':
            return None
        return actor

    def _budget(self):
        return {'read_work_units_used': self._read_units, 'read_work_units_remaining': max(0, 9 - self._read_units), 'write_attempts_used': self._write_attempts, 'write_attempts_remaining': max(0, 9 - self._write_attempts)}

    def _business_hash(self):
        return fn__canonical_hash(self._state.list_snapshot())

    def _active_hold_seats(self, showtime_id, except_hold_id=None):
        return self._lib.active_hold_seats(self._state, showtime_id, except_hold_id=except_hold_id)

    def _issued_ticket_seats(self, showtime_id):
        return self._lib.issued_ticket_seats(self._state, showtime_id)

    def _seat_summary(self, showtime):
        return self._lib.showtime_seat_summary(self._state, showtime)

    def _recompute_all_showtimes(self):
        for showtime in self._state.list_entities('showtime'):
            self._lib.recompute_showtime(self._state, showtime['showtime_id'])

    @staticmethod
    def _page(rows, offset, limit):
        return (len(rows), rows[offset:offset + limit])

    def _list_venues(self, arguments):
        rows = self._state.list_entities('venue')
        if arguments.get('name_keyword'):
            needle = arguments['name_keyword'].lower()
            rows = [row for row in rows if needle in row.get('name', '').lower()]
        if arguments.get('city_keyword'):
            needle = arguments['city_keyword'].lower()
            rows = [row for row in rows if needle in row.get('city', '').lower()]
        if arguments.get('status'):
            rows = [row for row in rows if row.get('status') == arguments['status']]
        rows.sort(key=lambda row: (row.get('name', ''), row['venue_id']))
        (total, page) = self._page(rows, arguments.get('offset', 0), arguments.get('limit', 4))
        return fn__success({'total_count': total, 'venues': [{key: row.get(key) for key in ('venue_id', 'name', 'city', 'state', 'status')} for row in page]})

    def _list_movies(self, arguments):
        rows = self._state.list_entities('movie')
        if arguments.get('keyword'):
            needle = arguments['keyword'].lower()
            rows = [row for row in rows if needle in row.get('title', '').lower()]
        if arguments.get('status'):
            rows = [row for row in rows if row.get('status') == arguments['status']]
        rows.sort(key=lambda row: (row.get('title', ''), row['movie_id']))
        (total, page) = self._page(rows, arguments.get('offset', 0), arguments.get('limit', 4))
        return fn__success({'total_count': total, 'movies': [{key: row.get(key) for key in ('movie_id', 'title', 'rating', 'runtime_minutes', 'status')} for row in page]})

    def _list_pricing_plans(self, arguments):
        venue = self._state.get_entity('venue', arguments['venue_id'], 'venue_id')
        if not venue:
            return fn__error('VENUE_NOT_FOUND', 'venue does not exist')
        rows = [row for row in self._state.list_entities('pricing_plan') if row.get('venue_id') == arguments['venue_id']]
        if arguments.get('ticket_type'):
            rows = [row for row in rows if row.get('ticket_type') == arguments['ticket_type']]
        if arguments.get('status'):
            rows = [row for row in rows if row.get('status') == arguments['status']]
        rows.sort(key=lambda row: (row.get('ticket_type', ''), row['pricing_plan_id']))
        (total, page) = self._page(rows, arguments.get('offset', 0), arguments.get('limit', 4))
        return fn__success({'total_count': total, 'pricing_plans': [{key: ext_deepcopy(row.get(key)) for key in ('pricing_plan_id', 'name', 'ticket_type', 'base_price', 'service_fee', 'currency', 'channel', 'status', 'rules')} for row in page]})

    @staticmethod
    def _hold_is_live(hold):
        expires_at = fn__parse_datetime(hold.get('expires_at'))
        return hold.get('status') == 'active' and expires_at is not None and (expires_at > _datetime.datetime.fromisoformat('2026-05-27T12:00:00+00:00'))

    def _create_seat_hold(self, arguments):
        return fn__normalize_result(self._impl.create_seat_hold(self._state, showtime_id=arguments['showtime_id'], seat_ids=ext_deepcopy(arguments['seat_ids']), channel=arguments['channel'], hold_minutes=arguments.get('hold_minutes', 12), pricing_plan_id=arguments['pricing_plan_id'], ticket_type=arguments['ticket_type']))

    def _release_seat_hold(self, arguments):
        hold = self._state.get_entity('seat_hold', arguments['hold_id'], 'hold_id')
        if not hold:
            return fn__error('HOLD_NOT_FOUND', 'seat hold does not exist')
        if hold.get('status') != 'active':
            return fn__error('HOLD_NOT_ACTIVE', 'seat hold is not active')
        if not self._hold_is_live(hold):
            return fn__error('HOLD_EXPIRED', 'seat hold has expired')
        return fn__normalize_result(self._impl.release_seat_hold(self._state, hold_id=arguments['hold_id'], release_reason=arguments.get('release_reason')))

    def _cancel_booking(self, arguments):
        return fn__normalize_result(self._impl.cancel_booking(self._state, booking_id=arguments['booking_id'], refund_mode=arguments['refund_mode'], reason=arguments['reason']))

    def _write(self, name, arguments):
        return {'create_seat_hold': self._create_seat_hold, 'release_seat_hold': self._release_seat_hold, 'create_booking': self._create_booking, 'cancel_booking': self._cancel_booking}[name](arguments)

    def _target_venue(self, name, arguments):
        if name == 'list_pricing_plans':
            return arguments.get('venue_id')
        if name == 'search_showtimes' and arguments.get('venue_id'):
            return arguments['venue_id']
        if name in {'get_showtime_availability', 'create_seat_hold', 'create_booking'}:
            showtime = self._state.get_entity('showtime', arguments.get('showtime_id'), 'showtime_id')
            return showtime.get('venue_id') if showtime else None
        if name == 'release_seat_hold':
            hold = self._state.get_entity('seat_hold', arguments.get('hold_id'), 'hold_id')
            showtime = self._state.get_entity('showtime', hold.get('showtime_id'), 'showtime_id') if hold else None
            return showtime.get('venue_id') if showtime else None
        if name == 'cancel_booking':
            booking = self._state.get_entity('booking', arguments.get('booking_id'), 'booking_id')
            showtime = self._state.get_entity('showtime', booking.get('showtime_id'), 'showtime_id') if booking else None
            return showtime.get('venue_id') if showtime else None
        return None

    @staticmethod
    def _scope_read_result(name, result, allowed_venue_ids):
        if result.get('status') != 'success':
            return result
        scoped = ext_deepcopy(result)
        data = scoped.get('data') or {}
        if name == 'list_venues':
            rows = [row for row in data.get('venues') or [] if row.get('venue_id') in allowed_venue_ids]
            data['venues'] = rows
            data['total_count'] = len(rows)
        elif name == 'search_showtimes':
            rows = [row for row in data.get('showtimes') or [] if row.get('venue_id') in allowed_venue_ids]
            data['showtimes'] = rows
            data['total_count'] = len(rows)
        return scoped

    def _record_event(self, name, actor_user_id, result, before_hash, after_hash, cost):
        self._events.append({'sequence': len(self._events) + 1, 'channel': 'learner', 'tool': name, 'actor_user_id': actor_user_id, 'status': result.get('status'), 'error_code': result.get('data', {}).get('error_code'), 'cost': ext_deepcopy(cost), 'budget_after': self._budget(), 'state_hash_before': before_hash, 'state_hash_after': after_hash})

    def _assert_state_invariants(self):
        active_ticket_seats: dict[str, set[str]] = {}
        for ticket in self._state.list_entities('ticket'):
            booking = self._state.get_entity('booking', ticket.get('booking_id'), 'booking_id')
            showtime = self._state.get_entity('showtime', ticket.get('showtime_id'), 'showtime_id')
            seat = self._state.get_entity('seat', ticket.get('seat_id'), 'seat_id')
            plan = self._state.get_entity('pricing_plan', ticket.get('pricing_plan_id'), 'pricing_plan_id')
            if not booking or not showtime or (not seat) or (not plan):
                raise ValueError('ticket references missing business state')
            if booking.get('showtime_id') != showtime.get('showtime_id'):
                raise ValueError('booking and ticket showtimes diverged')
            if seat.get('auditorium_id') != showtime.get('auditorium_id'):
                raise ValueError('ticket seat belongs to another auditorium')
            if plan.get('venue_id') != showtime.get('venue_id'):
                raise ValueError('ticket pricing plan belongs to another venue')
            if ticket.get('status') in {'issued', 'checked_in'}:
                used = active_ticket_seats.setdefault(showtime['showtime_id'], set())
                if ticket['seat_id'] in used:
                    raise ValueError('multiple active tickets occupy one seat')
                used.add(ticket['seat_id'])
        live_hold_seats: dict[str, set[str]] = {}
        for hold in self._state.list_entities('seat_hold'):
            if not self._hold_is_live(hold):
                continue
            showtime = self._state.get_entity('showtime', hold.get('showtime_id'), 'showtime_id')
            if not showtime:
                raise ValueError('live seat hold references a missing showtime')
            used = live_hold_seats.setdefault(showtime['showtime_id'], set())
            for seat_id in hold.get('seat_ids') or []:
                seat = self._state.get_entity('seat', seat_id, 'seat_id')
                if not seat or seat.get('auditorium_id') != showtime.get('auditorium_id'):
                    raise ValueError('live seat hold references an invalid seat')
                if seat_id in used or seat_id in active_ticket_seats.get(showtime['showtime_id'], set()):
                    raise ValueError('live seat custody overlaps')
                used.add(seat_id)
        for showtime in self._state.list_entities('showtime'):
            summary = self._seat_summary(showtime)
            persisted = {'capacity': int(showtime.get('capacity') or 0), 'sold': int(showtime.get('seats_sold') or 0), 'held': int(showtime.get('seats_held') or 0), 'available': int(showtime.get('seats_available') or 0)}
            if any((persisted[key] != summary[key] for key in persisted)):
                raise ValueError('showtime availability counters diverged')
            if sum((summary[key] for key in ('sold', 'held', 'available', 'blocked', 'maintenance'))) != summary['capacity']:
                raise ValueError('showtime seat inventory is not conserved')
        for booking in self._state.list_entities('booking'):
            tickets = [row for row in self._state.list_entities('ticket') if row.get('booking_id') == booking.get('booking_id')]
            payments = [row for row in self._state.list_entities('payment') if row.get('booking_id') == booking.get('booking_id')]
            if booking.get('status') == 'paid':
                issued = [row for row in tickets if row.get('status') == 'issued']
                captured = [row for row in payments if row.get('status') == 'captured']
                if len(issued) != int(booking.get('ticket_count') or 0):
                    raise ValueError('paid booking ticket count diverged')
                if len(captured) != 1 or round(float(captured[0].get('amount') or 0), 2) != round(float(booking.get('total_amount') or 0), 2):
                    raise ValueError('paid booking payment is not conserved')
            captured_total = round(sum((float(row.get('amount') or 0) for row in payments if row.get('status') == 'captured')), 2)
            refunded_total = round(sum((float(row.get('amount') or 0) for row in payments if row.get('status') == 'refunded')), 2)
            if refunded_total > captured_total:
                raise ValueError('booking refunds exceed captured payment')
        expected_revenue: dict[str, float] = {}
        for payment in self._state.list_entities('payment'):
            booking = self._state.get_entity('booking', payment.get('booking_id'), 'booking_id')
            showtime_id = booking.get('showtime_id') if booking else None
            if not showtime_id:
                continue
            sign = 1.0 if payment.get('status') == 'captured' else -1.0 if payment.get('status') == 'refunded' else 0.0
            expected_revenue[showtime_id] = expected_revenue.get(showtime_id, 0.0) + sign * float(payment.get('amount') or 0)
        for showtime in self._state.list_entities('showtime'):
            if round(float(showtime.get('revenue_gross') or 0), 2) != round(expected_revenue.get(showtime['showtime_id'], 0.0), 2):
                raise ValueError('showtime revenue does not reconcile to payments')

    def grade(self, task_id):
        if task_id != self._task_id:
            raise ValueError('task is not active')
        entities = self._state.list_snapshot()
        deliverables: list[dict[str, ext_Any]] = []
        for target in self._task_targets:
            target_bookings = [row for row in entities['booking'] if row.get('showtime_id') == target['showtime_id'] and row.get('customer_name') == target['customer_name'] and (row.get('customer_email') == target['customer_email'])]
            target_holds = [row for row in entities['seat_hold'] if row.get('showtime_id') == target['showtime_id'] and row.get('pricing_plan_id') == target['pricing_plan_id'] and (row.get('ticket_type') == target['ticket_type']) and (row.get('channel') == target['checkout_channel']) and self._hold_is_live(row)]
            showtime_binding_verified = bool(target_bookings or target_holds)
            valid_seat_custody = False
            ticket_issued = False
            payment_captured = False
            fully_valid: list[dict[str, ext_Any]] = []
            for hold in target_holds:
                hold_seats = hold.get('seat_ids') or []
                if len(hold_seats) != target['quantity'] or len(set(hold_seats)) != target['quantity']:
                    continue
                if all(((self._state.get_entity('seat', seat_id, 'seat_id') or {}).get('price_zone') == target['price_zone'] for seat_id in hold_seats)):
                    valid_seat_custody = True
            for booking in target_bookings:
                tickets = [row for row in entities['ticket'] if row.get('booking_id') == booking['booking_id'] and row.get('showtime_id') == target['showtime_id'] and (row.get('status') == 'issued')]
                seat_ids = [row.get('seat_id') for row in tickets]
                ticket_facts_valid = len(tickets) == target['quantity'] and len(set(seat_ids)) == target['quantity'] and all((row.get('pricing_plan_id') == target['pricing_plan_id'] for row in tickets)) and all((row.get('ticket_type') == target['ticket_type'] for row in tickets)) and all(((self._state.get_entity('seat', seat_id, 'seat_id') or {}).get('price_zone') == target['price_zone'] for seat_id in seat_ids))
                if ticket_facts_valid:
                    valid_seat_custody = True
                    ticket_issued = True
                captured = [row for row in entities['payment'] if row.get('booking_id') == booking['booking_id'] and row.get('status') == 'captured' and (round(float(row.get('amount') or 0), 2) == target['expected_total'])]
                if captured:
                    payment_captured = True
                showtime = self._state.get_entity('showtime', target['showtime_id'], 'showtime_id')
                availability_reconciled = bool(showtime and all((int(showtime.get(field) or 0) == self._seat_summary(showtime)[summary_key] for (field, summary_key) in (('capacity', 'capacity'), ('seats_sold', 'sold'), ('seats_held', 'held'), ('seats_available', 'available')))))
                if booking.get('status') == 'paid' and booking.get('payment_status') == 'captured' and (booking.get('pricing_plan_id') == target['pricing_plan_id']) and (booking.get('ticket_type') == target['ticket_type']) and (booking.get('price_zone') == target['price_zone']) and (booking.get('channel') == target['checkout_channel']) and (int(booking.get('ticket_count') or 0) == target['quantity']) and (round(float(booking.get('total_amount') or 0), 2) == target['expected_total']) and ticket_facts_valid and (len(captured) == 1) and availability_reconciled:
                    fully_valid.append({'booking': booking, 'tickets': tickets, 'payment': captured[0]})
            booking_reconciled = len(fully_valid) == 1
            facts = {'showtime_binding_verified': showtime_binding_verified, 'valid_seat_custody': valid_seat_custody, 'ticket_issued': ticket_issued, 'payment_captured': payment_captured, 'booking_reconciled': booking_reconciled}
            points = {'showtime_binding_verified': 2.5, 'valid_seat_custody': 5.0, 'ticket_issued': 5.0, 'payment_captured': 5.0, 'booking_reconciled': 7.5}
            passed = fully_valid[0] if booking_reconciled else None
            deliverables.append({'target_id': target['target_id'], 'structure_atom': target['structure_atom'], 'rule_atom': target['rule_atom'], **facts, 'booking_id': passed['booking']['booking_id'] if passed else None, 'ticket_ids': [row['ticket_id'] for row in passed['tickets']] if passed else [], 'payment_id': passed['payment']['payment_id'] if passed else None, 'score': sum((points[name] for (name, value) in facts.items() if value)), 'completed': all(facts.values())})
        return {'task_id': task_id, 'score': sum((row['score'] for row in deliverables)), 'max_score': 100.0, 'completed_artifacts': sum((row['completed'] for row in deliverables)), 'deliverables': deliverables, 'budget': self._budget()}

    def _cinema_catalogue_world_apply_event(self, event_id):
        receipt = self._cinema_contract_world_apply_event(event_id)
        if event_id == 'E2' and receipt['applied']:
            for cluster in DATA_STREAM_CLUSTERS:
                for fare in cluster['fares'].values():
                    if fare['rule_atom'] not in DATA_CHANGED_R:
                        continue
                    old_id = fare['pricing_plan_id']
                    plan = self._state.get_entity('pricing_plan', old_id, 'pricing_plan_id')
                    replacement = ext_deepcopy(plan)
                    replacement['pricing_plan_id'] = fn_replacement_id(old_id)
                    self._state.add_entity('pricing_plan', replacement, 'pricing_plan_id')
                    self._state.update_entity('pricing_plan', old_id, {'status': 'inactive'}, 'pricing_plan_id')
                    for show in self._state.list_entities('showtime'):
                        if old_id in show.get('pricing_plan_ids', []):
                            self._state.update_entity('showtime', show['showtime_id'], {'pricing_plan_ids': [*show['pricing_plan_ids'], replacement['pricing_plan_id']]}, 'showtime_id')
            self._assert_state_invariants()
            receipt['after'] = self.business_hash()
        return receipt

    def _cinema_catalogue_world_resolve_target(self, target):
        value = ext_deepcopy(target)
        if 'E2' in self._applied_boundary_events and value['rule_atom'] in DATA_CHANGED_R:
            value['pricing_plan_id'] = fn_replacement_id(value['pricing_plan_id'])
        return self._persistent_cinema_adapter_resolve_target(value)

    def _cinema_current_pricing_read(self, name, arguments):
        if name != 'list_pricing_plans':
            return self._business_cinema_successor_read(name, arguments)
        result = World._cinema_adapter_read(self, name, arguments)
        if result.get('status') == 'success':
            for row in result['data'].get('pricing_plans', []):
                rules = ext_deepcopy(row.get('rules') or {})
                rules.pop('policy_version', None)
                row['rules'] = rules
        return result

    def _business_cinema_successor_dispatch(self, name, arguments, actor_user_id):
        result = self._business_cinema_successor_dispatch_2(name, arguments, actor_user_id)
        if result.get('status') == 'success':
            if name == 'create_booking':
                target_index = self._target_index_for_booking(arguments)
                if target_index is not None:
                    key = self._target_key(self._task_targets[target_index])
                    if self._binding_revalidation.get(key) == 'awaiting_current_evidence':
                        self._binding_revalidation[key] = 'validated'
        return result

    def _business_cinema_successor_public_tool_schemas(self, role):
        return ext_deepcopy(DATA_PUBLIC_TOOLS) if role == 'booking_service_agent' else []

    def _cinema_catalogue_world_snapshot(self):
        value = self._cinema_independent_world_snapshot()
        value['evolution']['case_version'] = 'cinema-catalogue-replacement-evolution-v4'
        return value

    def _cinema_catalogue_world_restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        if value.get('evolution', {}).get('case_version') != 'cinema-catalogue-replacement-evolution-v4':
            raise ValueError('Cinema catalogue snapshot version differs')
        value['evolution']['case_version'] = 'cinema-independent-admissions-evolution-v3'
        self._cinema_independent_world_restore(value)

    def _business_cinema_successor_init(self, source_root=CASE_DIR / 'raw'):
        self._binding_revalidation: dict[str, str] = {}
        self._expected_stale_bindings: dict[str, dict[str, ext_Any]] = {}
        self._business_cinema_successor_init_2(source_root=source_root)
        fn__add_replacement_candidates(self)
        self._recompute_all_showtimes()
        self._assert_state_invariants()

    def _business_cinema_successor_get_showtime_availability(self, arguments):
        showtime = self._state.get_entity('showtime', arguments['showtime_id'], 'showtime_id')
        if showtime is None:
            return fn__error('SHOWTIME_NOT_FOUND', 'showtime does not exist')
        if showtime.get('status') != 'sales_open':
            self._observe_cancelled_showtimes([showtime])
            data: dict[str, ext_Any] = {'showtime_id': showtime['showtime_id'], 'status': showtime.get('status'), 'availability': self._seat_summary(showtime), 'evidence_kind': 'non_bookable_status'}
            if arguments.get('include_seat_details', False):
                data['seat_total_count'] = 0
                data['seats'] = []
            return fn__success(data)
        return self._business_cinema_successor_get_showtime_availability_2(arguments)

    @staticmethod
    def _cinema_adapter_read_cost(name, result):
        if result.get('status') != 'success':
            return 1
        data = result.get('data') or {}
        if name == 'list_venues':
            return max(1, len(data.get('venues') or []))
        if name == 'list_movies':
            return max(1, len(data.get('movies') or []))
        if name == 'search_showtimes':
            return max(1, len(data.get('showtimes') or []))
        if name == 'get_showtime_availability':
            return 1 + len(data.get('seats') or [])
        if name == 'list_pricing_plans':
            return max(1, 4 * len(data.get('pricing_plans') or []))
        return 1

    def _business_cinema_successor_create_booking(self, arguments):
        fresh = self._fresh_available_seats.get(arguments['showtime_id'], set())
        requested = set(arguments['seat_ids'])
        if not requested or not requested <= fresh:
            return fn__error('FRESH_AVAILABILITY_REQUIRED', 'read current seat details and choose a returned available seat before booking')
        result = self._cinema_adapter_create_booking(arguments)
        if result.get('status') == 'success':
            fresh.difference_update(requested)
        return result

    def _cinema_contract_world_apply_event(self, event_id):
        receipt = self._cinema_evolution_apply_event(event_id)
        if event_id == 'E2' and receipt['applied']:
            for cluster in DATA_STREAM_CLUSTERS:
                for fare in cluster['fares'].values():
                    if fare['rule_atom'] not in DATA_CHANGED_R:
                        continue
                    plan_id = fare['pricing_plan_id']
                    plan = self._state.get_entity('pricing_plan', plan_id, 'pricing_plan_id')
                    self._state.update_entity('pricing_plan', plan_id, {'channel': fn_channel_category(plan['rules']['checkout_channel'])}, 'pricing_plan_id')
            receipt['after'] = self.business_hash()
        return receipt

    def _persistent_cinema_adapter_resolve_target(self, target):
        value = ext_deepcopy(target)
        showtime = self._active_showtime(value)
        plan = self._state.get_entity('pricing_plan', value['pricing_plan_id'], 'pricing_plan_id')
        if plan is None:
            raise AssertionError('stream pricing plan disappeared')
        rules = plan.get('rules') or {}
        seats = sorted((row['seat_id'] for row in self._state.list_entities('seat') if row.get('auditorium_id') == showtime['auditorium_id'] and row.get('price_zone') == rules.get('seat_zone') and (row.get('status') == 'available') and (row['seat_id'] not in self._active_hold_seats(showtime['showtime_id'])) and (row['seat_id'] not in self._issued_ticket_seats(showtime['showtime_id']))))
        if len(seats) < value['quantity']:
            raise RuntimeError('stream target has insufficient current seats')
        value.update({'showtime_id': showtime['showtime_id'], 'auditorium_id': showtime['auditorium_id'], 'preferred_seat_ids': seats, 'price_zone': rules['seat_zone'], 'checkout_channel': rules['checkout_channel'], 'policy_version': rules['policy_version'], 'expected_total': round(float(plan['base_price']) + float(plan['service_fee']), 2)})
        return value

    def _business_cinema_successor_read(self, name, arguments):
        result = self._cinema_adapter_read(name, arguments)
        if result.get('status') != 'success':
            return result
        data = result.get('data') or {}
        if name == 'list_pricing_plans':
            for row in data.get('pricing_plans') or []:
                rules = ext_deepcopy(row.get('rules') or {})
                rules.pop('policy_version', None)
                for atom_id in DATA_DRIFT_STRUCTURE_ATOMS:
                    if row.get('pricing_plan_id') != fn__fare(atom_id)['pricing_plan_id']:
                        continue
                    key = fn__changed_binding_key(atom_id)
                    if self._binding_revalidation.get(key) == 'awaiting_exact_stale':
                        rules['checkout_channel'] = fn__fare(atom_id)['checkout_channel']
                row['rules'] = rules
        return result

    def _cinema_adapter_read(self, name, arguments):
        return {'list_venues': self._list_venues, 'list_movies': self._list_movies, 'search_showtimes': self._search_showtimes, 'get_showtime_availability': self._get_showtime_availability, 'list_pricing_plans': self._list_pricing_plans}[name](arguments)

    def _business_cinema_successor_dispatch_2(self, name, arguments, actor_user_id):
        result = self._cinema_adapter_dispatch(name, arguments, actor_user_id)
        if name == 'get_showtime_availability' and result.get('status') == 'success' and arguments.get('include_seat_details', False):
            seats = {row['seat_id'] for row in result.get('data', {}).get('seats', []) if row.get('availability_state') == 'available'}
            self._fresh_available_seats.setdefault(arguments['showtime_id'], set()).update(seats)
        return result

    def _cinema_independent_world_snapshot(self):
        value = self._cinema_contract_world_snapshot()
        value['evolution']['case_version'] = 'cinema-independent-admissions-evolution-v3'
        return value

    def _cinema_independent_world_restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        if value.get('evolution', {}).get('case_version') != 'cinema-independent-admissions-evolution-v3':
            raise ValueError('Cinema independent-admission snapshot version differs')
        value['evolution']['case_version'] = 'cinema-pricing-contract-evolution-v2'
        self._cinema_contract_world_restore(value)

    def _business_cinema_successor_init_2(self, source_root=CASE_DIR / 'raw'):
        self._fresh_available_seats: dict[str, set[str]] = {}
        self._business_cinema_successor_init_3(source_root=source_root)

    def _business_cinema_successor_get_showtime_availability_2(self, arguments):
        showtime = self._state.get_entity('showtime', arguments['showtime_id'], 'showtime_id')
        if not showtime:
            return fn__error('SHOWTIME_NOT_FOUND', 'showtime does not exist')
        summary = self._seat_summary(showtime)
        data: dict[str, ext_Any] = {'showtime_id': showtime['showtime_id'], 'status': showtime.get('status'), 'availability': summary}
        if arguments.get('include_seat_details', False):
            held = self._active_hold_seats(showtime['showtime_id'])
            ticketed = self._issued_ticket_seats(showtime['showtime_id'])
            seats = [row for row in self._state.list_entities('seat') if row.get('auditorium_id') == showtime.get('auditorium_id') and row.get('status') == 'available' and (row['seat_id'] not in held) and (row['seat_id'] not in ticketed) and (not arguments.get('price_zone') or row.get('price_zone') == arguments['price_zone'])]
            seats.sort(key=lambda row: (row.get('row_label', ''), row.get('seat_number', 0), row['seat_id']))
            (total, page) = self._page(seats, arguments.get('offset', 0), arguments.get('limit', 4))
            data['seat_total_count'] = total
            data['seats'] = [{'seat_id': row['seat_id'], 'row_label': row.get('row_label'), 'seat_number': row.get('seat_number'), 'price_zone': row.get('price_zone'), 'availability_state': 'available'} for row in page]
        return fn__success(data)

    def _cinema_adapter_create_booking(self, arguments):
        return fn__normalize_result(self._impl.create_booking(self._state, showtime_id=arguments['showtime_id'], seat_ids=ext_deepcopy(arguments['seat_ids']), customer_name=arguments['customer_name'], customer_email=arguments['customer_email'], hold_id=arguments.get('hold_id'), channel=arguments['channel'], payment_method=arguments['payment_method'], capture_payment=arguments.get('capture_payment', True), pricing_plan_id=arguments['pricing_plan_id'], ticket_type=arguments['ticket_type']))

    def _cinema_evolution_apply_event(self, event_id):
        if event_id not in {'E1', 'E2'}:
            raise ValueError('unknown cinema evolution event')
        before = self.business_hash()
        if event_id in self._applied_boundary_events:
            return {'event_id': event_id, 'applied': False, 'before': before, 'after': before}
        if event_id == 'E2' and 'E1' not in self._applied_boundary_events:
            raise ValueError('cinema events must be applied in order')
        if event_id == 'E1':
            for atom in DATA_CHANGED_S:
                self._state.update_entity('showtime', fn__pre_showtime_id(atom), {'status': 'cancelled'}, 'showtime_id')
                self._state.update_entity('showtime', fn__replacement_showtime_id(atom), {'status': 'sales_open'}, 'showtime_id')
        else:
            for cluster in DATA_STREAM_CLUSTERS:
                for fare in cluster['fares'].values():
                    if fare['rule_atom'] not in DATA_CHANGED_R:
                        continue
                    plan = self._state.get_entity('pricing_plan', fare['pricing_plan_id'], 'pricing_plan_id')
                    rules = ext_deepcopy(plan['rules'])
                    channel = rules['checkout_channel']
                    rules['checkout_channel'] = DATA_CHECKOUT_CHANNELS[(DATA_CHECKOUT_CHANNELS.index(channel) + 1) % len(DATA_CHECKOUT_CHANNELS)]
                    rules['policy_version'] = 'evolution-E2'
                    self._state.update_entity('pricing_plan', plan['pricing_plan_id'], {'rules': rules}, 'pricing_plan_id')
        self._applied_boundary_events.add(event_id)
        self._business_event_application_count = len(self._applied_boundary_events)
        self._recompute_all_showtimes()
        self._assert_state_invariants()
        return {'event_id': event_id, 'applied': True, 'before': before, 'after': self.business_hash()}

    def _cinema_adapter_dispatch(self, name, arguments, actor_user_id):
        if self._task_id is None:
            return fn__error('TASK_NOT_ACTIVE', 'activate a task before dispatch')
        tool = DATA_TOOL_BY_NAME.get(name)
        if tool is None:
            return fn__error('TOOL_NOT_ALLOWED', 'tool is not in the learner allowlist')
        actor = self._actor(actor_user_id)
        if actor is None:
            return fn__error('ACTOR_NOT_AUTHORIZED', 'actor is not an active booking service agent')
        try:
            mod_jsonschema.validate(arguments, tool['input_schema'])
        except mod_jsonschema.ValidationError:
            return fn__error('INVALID_ARGUMENTS', 'arguments do not match the public tool schema')
        if self._calls >= 48:
            return fn__error('CALL_GUARD_EXHAUSTED', 'the runaway safety guard is exhausted')
        if name in DATA_WRITE_TOOLS and self._write_attempts >= 9:
            result = fn__error('WRITE_BUDGET_EXHAUSTED', 'the mutation-attempt budget is exhausted')
            result['budget'] = self._budget()
            return result
        if name not in DATA_WRITE_TOOLS and self._read_units >= 9:
            result = fn__error('READ_BUDGET_EXHAUSTED', 'the returned-work budget is exhausted')
            result['budget'] = self._budget()
            return result
        target_venue = self._target_venue(name, arguments)
        allowed_venues = set(actor.get('venue_ids') or [])
        if target_venue is not None and target_venue not in allowed_venues:
            return fn__error('ACTOR_VENUE_SCOPE_DENIED', 'actor is not assigned to the venue')
        before = self.snapshot()
        before_hash = self._business_hash()
        try:
            if name in DATA_WRITE_TOOLS:
                result = self._write(name, ext_deepcopy(arguments))
                if result.get('status') == 'success':
                    self._assert_state_invariants()
            else:
                result = self._scope_read_result(name, self._read(name, ext_deepcopy(arguments)), allowed_venues)
        except Exception:
            self._state.restore(before['entities'])
            result = fn__error('ADAPTER_EXECUTION_FAILED', 'operation failed without committing state')
        cost = {'read_work_units': 0, 'write_attempts': 0}
        if name in DATA_WRITE_TOOLS:
            self._write_attempts += 1
            cost['write_attempts'] = 1
            if result.get('status') != 'success':
                self._state.restore(before['entities'])
        else:
            read_cost = self._read_cost(name, result)
            remaining = 9 - self._read_units
            if read_cost > remaining:
                self._read_units = 9
                result = fn__error('READ_BUDGET_EXHAUSTED', 'this read exceeds the remaining returned-work budget', required_units=read_cost, available_units=remaining)
                read_cost = remaining
            else:
                self._read_units += read_cost
            cost['read_work_units'] = read_cost
        self._calls += 1
        after_hash = self._business_hash()
        result['budget'] = self._budget()
        self._record_event(name, actor_user_id, result, before_hash, after_hash, cost)
        return ext_deepcopy(result)

    def _cinema_contract_world_snapshot(self):
        value = self._cinema_evolution_snapshot()
        value['evolution']['case_version'] = 'cinema-pricing-contract-evolution-v2'
        return value

    def _cinema_contract_world_restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        if value.get('evolution', {}).get('case_version') != 'cinema-pricing-contract-evolution-v2':
            raise ValueError('Cinema pricing-contract snapshot version differs')
        value['evolution']['case_version'] = 'cinema-two-event-lifecycle-evolution-v1'
        self._cinema_evolution_restore(value)

    def _business_cinema_successor_init_3(self, source_root=CASE_DIR / 'raw'):
        self._persistent_cinema_adapter_init(source_root=source_root)
        fn__add_structure_candidates(self)
        self._business_event_application_count = 0
        self._recompute_all_showtimes()
        self._assert_state_invariants()

    def _cinema_evolution_snapshot(self):
        value = World._cinema_adapter_snapshot(self)
        value['schema'] = 'rescopebench-cinema-evolution-world/v1'
        value['evolution'] = {'case_version': 'cinema-two-event-lifecycle-evolution-v1', 'schedule': ext_deepcopy(DATA_SCHEDULE_2), 'blueprint_sha256': fn__canonical_hash(DATA_TASK_BLUEPRINT), 'activated_tasks': list(self._activated_tasks), 'events': sorted(self._applied_boundary_events), 'fresh_available_seats': {k: sorted(v) for (k, v) in self._fresh_available_seats.items()}}
        return value

    def _cinema_evolution_restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        if value.get('schema') != 'rescopebench-cinema-evolution-world/v1':
            raise ValueError('cinema evolution snapshot identity differs')
        metadata = value.pop('evolution')
        if metadata['case_version'] != 'cinema-two-event-lifecycle-evolution-v1' or metadata['schedule'] != DATA_SCHEDULE_2 or metadata['blueprint_sha256'] != fn__canonical_hash(DATA_TASK_BLUEPRINT):
            raise ValueError('cinema evolution contract differs')
        active = metadata['activated_tasks']
        if active != list(DATA_TASK_IDS[:len(active)]) or value['task_id'] != (active[-1] if active else None):
            raise ValueError('cinema evolution prefix differs')
        expected = [e['event_id'] for e in DATA_SCHEDULE_2['events'] if e['before_task'] <= len(active)]
        if metadata['events'] != expected:
            raise ValueError('cinema evolution event ledger differs')
        value['schema'] = 'rescopebench-cinema-snapshot/v2'
        World._cinema_adapter_restore(self, value)
        self._activated_tasks = active
        self._applied_boundary_events = set(expected)
        self._business_event_application_count = len(expected)
        self._fresh_available_seats = {k: set(v) for (k, v) in metadata['fresh_available_seats'].items()}
        self._binding_revalidation = {}
        self._expected_stale_bindings = {}
        self._assert_state_invariants()

    def _persistent_cinema_adapter_init(self, source_root=CASE_DIR / 'raw'):
        self._cinema_adapter_init(source_root)
        self._state = MemoryState(fn__expanded_initial_entities())
        self._task_id = None
        self._task_targets = []
        self._events = []
        self._calls = 0
        self._read_units = 0
        self._write_attempts = 0
        self._activated_tasks: list[str] = []
        self._applied_boundary_events: set[str] = set()
        self._recompute_all_showtimes()
        self._assert_state_invariants()

    def _cinema_adapter_snapshot(self):
        return {'schema': 'rescopebench-cinema-snapshot/v2', 'task_id': self._task_id, 'task_targets': ext_deepcopy(self._task_targets), 'entities': self._state.list_snapshot(), 'events': ext_deepcopy(self._events), 'calls': self._calls, 'read_units': self._read_units, 'write_attempts': self._write_attempts}

    def _cinema_adapter_restore(self, snapshot):
        if snapshot.get('schema') != 'rescopebench-cinema-snapshot/v2':
            raise ValueError('unsupported snapshot schema')
        self._task_id = snapshot.get('task_id')
        self._task_targets = ext_deepcopy(snapshot.get('task_targets') or [])
        self._state.restore(snapshot.get('entities') or {})
        self._events = ext_deepcopy(snapshot.get('events') or [])
        self._calls = int(snapshot.get('calls') or 0)
        self._read_units = int(snapshot.get('read_units') or 0)
        self._write_attempts = int(snapshot.get('write_attempts') or 0)

    def _cinema_adapter_init(self, source_root=CASE_DIR / 'raw'):
        (self._impl, self._lib) = fn__load_raw_logic(str(ext_Path(source_root).resolve()))
        self._state = MemoryState({name: [] for name in DATA_ENTITY_ID_FIELDS})
        self._task_id: str | None = None
        self._task_targets: list[dict[str, ext_Any]] = []
        self._events: list[dict[str, ext_Any]] = []
        self._calls = 0
        self._read_units = 0
        self._write_attempts = 0

class MemoryState:

    def __init__(self, entities):
        self._entities = ext_deepcopy(entities)

    def get_entity(self, entity_type, entity_id, id_field='id'):
        field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
        return next((ext_deepcopy(row) for row in self._entities.get(entity_type, []) if row.get(field) == entity_id), None)

    def list_entities(self, entity_type):
        return ext_deepcopy(self._entities.get(entity_type, []))

    def add_entity(self, entity_type, record, id_field='id'):
        field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
        identity = record.get(field)
        if identity is None or self.get_entity(entity_type, identity, field) is not None:
            raise ValueError(f'duplicate or missing identity for {entity_type}')
        self._entities.setdefault(entity_type, []).append(ext_deepcopy(record))
        return ext_deepcopy(record)

    def update_entity(self, entity_type, entity_id, patch, id_field='id'):
        field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
        for row in self._entities.get(entity_type, []):
            if row.get(field) == entity_id:
                row.update(ext_deepcopy(patch))
                return ext_deepcopy(row)
        return None

    def delete_entity(self, entity_type, entity_id, id_field='id'):
        field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
        rows = self._entities.get(entity_type, [])
        kept = [row for row in rows if row.get(field) != entity_id]
        self._entities[entity_type] = kept
        return len(kept) != len(rows)

    def list_snapshot(self):
        return ext_deepcopy(self._entities)

    def restore(self, entities):
        self._entities = ext_deepcopy(entities)