File size: 82,447 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
"""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 timedelta as ext_timedelta
from functools import lru_cache
from pathlib import Path as ext_Path
from rescopebench.raw_module_isolation import load_isolated_modules as ext_load_isolated_modules
from typing import Any as ext_Any
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_MIGRATED_ATOMS, DATA_TICKET_KINDS, DATA_TASK_IDS, DATA_SCHEDULE_2, DATA_SCHEDULE_3, DATA_WRITE_TOOLS, DATA_TOOLS_2, DATA_CHANGED_BINDINGS, DATA_CHANGED_RULES, DATA_STREAM_CLUSTERS, DATA_TASK_IDS_2, DATA_DRIFT_CHANGED_RULES, DATA_RULE_LANES, DATA_OFFER_LANES, DATA_DRIFT_CHANGED_STRUCTURES, DATA_IDENTITY_FIELDS, DATA_ENTITY_ID_FIELDS, DATA_EVENT_KINDS, DATA_TOOLS_BY_NAME, DATA_RULE_PROFILES, DATA_CHANGED_RULES_2, DATA_STREAM_SCHEDULE, DATA_STREAM_CUSTOMER_NAMES

def fn_handle(kind, value):
    return f"{kind}-{fn_digest(['event-ticketing-v4', kind, value])[:14]}"

def fn_rekey_entities(entities, mappings):
    return {kind: [fn_rekey_record(row, mappings) for row in rows] for (kind, rows) in entities.items()}

def fn_rekey_record(record, mappings):
    """Only declared relational fields, not arbitrary strings or audit prose."""
    result = ext_deepcopy(record)
    for field in DATA_IDENTITY_FIELDS:
        if field in result:
            result[field] = mappings[field].get(result[field], result[field])
    if 'ticket_type_ids' in result:
        result['ticket_type_ids'] = [mappings['ticket_type_id'].get(x, x) for x in result['ticket_type_ids']]
    return result

def fn_rule_id(event_kind, ticket_kind):
    return f'R{DATA_EVENT_KINDS.index(event_kind) * 4 + DATA_TICKET_KINDS.index(ticket_kind) + 1:02d}'

def fn_profile(index):
    return {'offer_profile_id': fn_handle_2('profile', str(index)), 'audience_certificate': ('public', 'membership')[index // 4], 'redemption_channel': ('counter', 'electronic')[index // 2 % 2], 'reimbursement_cycle': ('weekly', 'monthly')[index % 2]}

def fn_rule_index(atom, epoch):
    value = DATA_RULE_PROFILES[int(atom[1:]) - 1]
    return value ^ 5 if epoch and atom in DATA_CHANGED_RULES else value

def fn_rule_index_2(atom, epoch):
    value = DATA_RULE_PROFILES[int(atom[1:]) - 1]
    return value ^ 5 if epoch and atom in DATA_CHANGED_RULES_2 else value

def fn_handle_2(kind, value):
    return f"{kind}-{fn_digest_2(['event-ticketing-v3', kind, value])[:14]}"

def fn__task_fixture(task_id, *, post_drift=None):
    if task_id not in DATA_STREAM_SCHEDULE:
        raise ValueError(f'unknown stream task: {task_id}')
    if post_drift is None:
        post_drift = int(task_id[1:]) >= 9
    fixture = fn__build_fixture(task_id, DATA_STREAM_CLUSTERS, DATA_STREAM_SCHEDULE[task_id], post_drift=post_drift)
    for (index, target) in enumerate(fixture['targets'], 1):
        old_customer_id = target['customer_id']
        customer = next((row for row in fixture['entities']['customer'] if row['customer_id'] == old_customer_id))
        suffix = mod_hashlib.sha256(f'event-ticketing-customer|{task_id}|{index}|{old_customer_id}'.encode('utf-8')).hexdigest()[:8]
        customer_id = f'{old_customer_id}-q{suffix}'
        customer['customer_id'] = customer_id
        customer['full_name'] = f'{DATA_STREAM_CUSTOMER_NAMES[index - 1]} Case {suffix.upper()}'
        customer['email_address'] = f'{customer_id}@example.invalid'
        target['customer_id'] = customer_id
        fixture['public_targets'][index - 1]['customer_name'] = customer['full_name']
        fixture['public_targets'][index - 1]['customer_reference'] = customer_id
    return fixture

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

def fn_digest(value):
    payload = mod_json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True)
    return mod_hashlib.sha256(payload.encode('ascii')).hexdigest()

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

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

def fn_digest_2(value):
    return mod_hashlib.sha256(mod_json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest()

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 = [f"ven-{cluster['code']}" for cluster in clusters]
    entities['operator'] = [{'operator_id': 'operator-dev-box-office', 'full_name': 'Development Box Office Operator', 'role': 'box_office_sales_operator', 'active': True, 'permission_scopes': ['orders:write', 'inventory:write'], '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 = (('Mara Voss', 'Ilan Beck', 'Nia Cole', 'Oren Pike'), ('Tessa Wynn', 'Bram Vale', 'Cora Reed', 'Deni Moss'))
    for (cluster_index, cluster) in enumerate(clusters):
        code = cluster['code']
        atom_id = cluster['atom_id']
        venue_id = f'ven-{code}'
        event_id = f'evt-{code}'
        live_performance_id = f'pf-{code}-n7'
        canceled_performance_id = f'pf-{code}-q2'
        start = ext_datetime.fromisoformat(cluster['starts_at'].replace('Z', '+00:00'))
        entities['venue'].append({'venue_id': venue_id, 'name': cluster['venue_name'], 'city': 'Test City', 'timezone': 'UTC', 'venue_type': 'theater', 'capacity': 16, 'status': 'active', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
        entities['event'].append({'event_id': event_id, 'venue_id': venue_id, 'name': cluster['event_name'], 'event_kind': cluster['event_kind'], 'status': 'on_sale', 'sales_start_at': '2026-05-01T00:00:00Z', 'sales_end_at': '2026-06-30T23:59:59Z', 'starts_at': cluster['starts_at'], 'ends_at': (start + ext_timedelta(hours=3)).strftime('%Y-%m-%dT%H:%M:%SZ'), 'public_capacity': 16, 'inventory_released': 16, 'inventory_sold': 0, 'inventory_held': 0, 'gross_sales_amount': 0.0, 'refund_amount': 0.0, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
        entities['performance'].extend([{'performance_id': canceled_performance_id, 'event_id': event_id, 'venue_id': venue_id, 'starts_at': (start - ext_timedelta(days=1)).strftime('%Y-%m-%dT%H:%M:%SZ'), 'ends_at': (start - ext_timedelta(days=1) + ext_timedelta(hours=3)).strftime('%Y-%m-%dT%H:%M:%SZ'), 'door_open_at': (start - ext_timedelta(days=1, hours=1)).strftime('%Y-%m-%dT%H:%M:%SZ'), 'status': 'canceled', 'capacity_override': None, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}, {'performance_id': live_performance_id, 'event_id': event_id, 'venue_id': venue_id, 'starts_at': cluster['starts_at'], 'ends_at': (start + ext_timedelta(hours=3)).strftime('%Y-%m-%dT%H:%M:%SZ'), 'door_open_at': (start - ext_timedelta(hours=1)).strftime('%Y-%m-%dT%H:%M:%SZ'), 'status': 'on_sale', 'capacity_override': None, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}])
        section_ids: list[str] = []
        for section_index in range(4):
            section_id = f"sec-{code}-{('q', 'm', 'x', 'b')[section_index]}"
            section_ids.append(section_id)
            entities['venue_section'].append({'venue_section_id': section_id, 'venue_id': venue_id, 'section_code': f'Z{cluster_index + 1}{section_index + 1}', 'name': ('Gallery', 'Terrace', 'Parterre', 'Loge')[section_index], 'section_type': ('balcony', 'floor', 'orchestra', 'suite')[section_index], 'capacity': 4, 'pricing_rank': section_index + 1, 'status': 'active', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
            for seat_number in range(1, 5):
                seat_id = f'st-{code}-{section_index + 1}-{seat_number:02d}'
                entities['seat'].append({'seat_id': seat_id, 'venue_id': venue_id, 'venue_section_id': section_id, 'row_label': chr(65 + section_index), 'seat_number': seat_number, 'seat_label': f'{chr(65 + section_index)}-{seat_number}', 'seat_type': 'standard', 'status': 'active', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
        type_records: dict[str, dict[str, ext_Any]] = {}
        tier_records: dict[str, dict[str, ext_Any]] = {}
        for (ticket_index, ticket_kind) in enumerate(DATA_TICKET_KINDS):
            section_id = section_ids[fn__section_index(cluster_index, ticket_index)]
            tier_id = f"pr-{code}-{('u', 'c', 'r', 'k')[ticket_index]}"
            ticket_type_id = f"tt-{code}-{('h', 's', 'v', 'g')[ticket_index]}"
            tier = {'price_tier_id': tier_id, 'event_id': event_id, 'venue_section_id': section_id, 'name': f'Price Band {ticket_index + 1}', 'currency': 'USD', 'base_price': float(55 + ticket_index * 17 + cluster_index), 'service_fee_rate': 0.1, 'active': True, 'inventory_limit': 4, 'inventory_released': 4, 'inventory_sold': 0, 'inventory_held': 0, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}
            ticket_type = {'ticket_type_id': ticket_type_id, 'event_id': event_id, 'price_tier_id': tier_id, 'name': f'Admission Class {ticket_index + 1}', 'ticket_kind': ticket_kind, 'sale_start_at': '2026-05-01T00:00:00Z', 'sale_end_at': '2026-06-30T23:59:59Z', 'inventory_limit': 4, 'released_quantity': 4, 'sold_quantity': 0, 'held_quantity': 0, 'per_order_limit': 4, 'refundable_until_hours': 24, 'status': 'active', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}
            entities['price_tier'].append(tier)
            entities['ticket_type'].append(ticket_type)
            type_records[ticket_kind] = ticket_type
            tier_records[ticket_kind] = tier
        campaigns: dict[str, str] = {}
        for (lane_index, lane) in enumerate(DATA_OFFER_LANES):
            campaign_id = f'offer-{code}-{lane}'
            campaigns[lane] = campaign_id
            eligible = [row['ticket_type_id'] for (kind, row) in type_records.items() if fn__lane_for(cluster['event_kind'], kind, post_drift=post_drift) == lane]
            entities['discount_campaign'].append({'discount_campaign_id': campaign_id, 'event_id': event_id, 'name': f'House Offer {lane.title()}', 'campaign_kind': ('early_bird', 'member_offer', 'group_bundle', 'promo_code')[lane_index], 'code': f'{code.upper()}{lane.upper()}' if lane_index in {1, 3} else None, 'discount_type': 'percent', 'discount_value': 10.0, 'starts_at': '2026-05-01T00:00:00Z', 'ends_at': '2026-06-30T23:59:59Z', 'status': 'active', 'ticket_type_ids': eligible, 'max_redemptions': 100, 'redemption_count': 0, 'min_quantity': 2, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
        for (ticket_index, ticket_kind) in enumerate(DATA_TICKET_KINDS):
            lane = fn__lane_for(cluster['event_kind'], ticket_kind, post_drift=post_drift)
            policy_customer_id = f'policy-{code}-{ticket_index + 1}'
            policy_name = f"Policy Sample {cluster['event_kind']} {ticket_kind.replace('_', ' ')}"
            entities['customer'].append({'customer_id': policy_customer_id, 'full_name': policy_name, 'email_address': f'{policy_customer_id}@example.invalid', 'phone': f'+1666{cluster_index:02d}{ticket_index:02d}2000', 'loyalty_tier': 'standard', 'marketing_opt_in': False, 'blocked': False, 'created_at': '2026-05-01T10:00:00Z', 'updated_at': '2026-05-01T10:10:00Z'})
            historical_order_id = f'archive-{code}-{ticket_index + 1}'
            historical_line_id = f'archive-line-{code}-{ticket_index + 1}'
            entities['order'].append({'order_id': historical_order_id, 'customer_id': policy_customer_id, 'event_id': event_id, 'performance_id': live_performance_id, 'order_status': 'refunded', 'payment_status': 'refunded', 'sales_channel': 'box_office', 'subtotal_amount': 100.0, 'discount_amount': 10.0, 'fee_amount': 10.0, 'total_amount': 100.0, 'refunded_amount': 100.0, 'currency': 'USD', 'line_count': 1, 'ticket_count': 0, 'applied_campaign_ids': [campaigns[lane]], 'expires_at': None, 'created_at': '2026-05-01T10:00:00Z', 'updated_at': '2026-05-02T10:00:00Z'})
            entities['order_line'].append({'order_line_id': historical_line_id, 'order_id': historical_order_id, 'event_id': event_id, 'performance_id': live_performance_id, 'ticket_type_id': type_records[ticket_kind]['ticket_type_id'], 'price_tier_id': tier_records[ticket_kind]['price_tier_id'], 'venue_section_id': tier_records[ticket_kind]['venue_section_id'], 'quantity': 2, 'unit_price': tier_records[ticket_kind]['base_price'], 'fee_amount': 10.0, 'discount_amount': 10.0, 'line_total': 100.0, 'seat_ids': [], 'status': 'refunded', 'created_at': '2026-05-01T10:00:00Z', 'updated_at': '2026-05-02T10:00:00Z'})
            if (atom_id, ticket_kind) not in target_set:
                continue
            if task_id == 'DEV01':
                customer_name = buyer_names[0][cluster_index]
            else:
                customer_name = f"{buyer_names[1][cluster_index % 4]} {atom_id} {ticket_kind.replace('_', ' ').title()}"
            customer_id = f"cu-{code}-{('a', 'e', 'i', 'o')[ticket_index]}"
            entities['customer'].append({'customer_id': customer_id, 'full_name': customer_name, 'email_address': f'{customer_id}@example.invalid', 'phone': f'+1555{cluster_index:02d}{ticket_index:02d}1000', 'loyalty_tier': ('standard', 'silver', 'gold', 'platinum')[ticket_index], 'marketing_opt_in': False, 'blocked': False, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
            section_id = tier_records[ticket_kind]['venue_section_id']
            section_seats = [row['seat_id'] for row in entities['seat'] if row['venue_section_id'] == section_id and row['status'] == 'active']
            target_id = f'request-{task_id.lower()}-{len(targets) + 1}'
            target = {'target_id': target_id, 'structure_atom': atom_id, 'rule_atom': fn_rule_id(cluster['event_kind'], ticket_kind), 'customer_id': customer_id, 'event_id': event_id, 'event_kind': cluster['event_kind'], 'performance_id': live_performance_id, 'ticket_type_id': type_records[ticket_kind]['ticket_type_id'], 'ticket_kind': ticket_kind, 'price_tier_id': tier_records[ticket_kind]['price_tier_id'], 'venue_id': venue_id, 'venue_section_id': section_id, 'quantity': 2, 'preferred_seat_ids': section_seats[:2], 'required_offer_lane': lane, 'required_campaign_id': campaigns[lane], 'campaign_ids_by_lane': ext_deepcopy(campaigns)}
            targets.append(target)
            public_targets.append({'target_id': target_id, 'customer_name': customer_name, 'event_name': cluster['event_name'], 'performance_starts_at': cluster['starts_at'], 'ticket_kind': ticket_kind, 'quantity': 2, 'offer_requirement': 'Apply the one currently eligible house offer before payment.'})
    if len(targets) != 4:
        raise ValueError(f'{task_id} must compile exactly four targets')
    return {'task_id': task_id, 'actor_user_id': 'operator-dev-box-office', 'entities': entities, 'targets': targets, 'public_targets': public_targets, 'post_drift': post_drift}

def fn__section_index(cluster_index, ticket_index):
    return (cluster_index * 3 + ticket_index * 2) % 4

def fn__lane_for(event_kind, ticket_kind, *, post_drift):
    lane = DATA_RULE_LANES[event_kind][ticket_kind]
    atom = fn_rule_id(event_kind, ticket_kind)
    if post_drift and atom in DATA_DRIFT_CHANGED_RULES:
        return DATA_OFFER_LANES[(DATA_OFFER_LANES.index(lane) + 1) % len(DATA_OFFER_LANES)]
    return lane

def fn__initial_entities():
    fixture = fn__task_fixture('T01', post_drift=False)
    target_customer_ids = {row['customer_id'] for row in fixture['targets']}
    entities = ext_deepcopy(fixture['entities'])
    entities['customer'] = [row for row in entities['customer'] if row['customer_id'] not in target_customer_ids]
    for ticket_type in entities['ticket_type']:
        ticket_type['inventory_limit'] = 16
        ticket_type['released_quantity'] = 16
    for tier in entities['price_tier']:
        tier['inventory_limit'] = 16
        tier['inventory_released'] = 16
    for event in entities['event']:
        event['public_capacity'] = 16 * len(DATA_TICKET_KINDS)
        event['inventory_released'] = 16 * len(DATA_TICKET_KINDS)
    for campaign in entities['discount_campaign']:
        campaign['max_redemptions'] = 64
    sections = {row['venue_section_id']: row for row in entities['venue_section']}
    existing = {row['seat_id'] for row in entities['seat']}
    for (section_id, section) in sections.items():
        section['capacity'] = 20
        code = section_id.split('-')[1]
        section_index = int(section['section_code'][-1])
        for seat_number in range(1, 20 + 1):
            seat_id = f'st-{code}-{section_index}-{seat_number:02d}'
            if seat_id in existing:
                continue
            entities['seat'].append({'seat_id': seat_id, 'venue_id': section['venue_id'], 'venue_section_id': section_id, 'row_label': chr(64 + section_index), 'seat_number': seat_number, 'seat_label': f'{chr(64 + section_index)}-{seat_number}', 'seat_type': 'standard', 'status': 'active', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
    return entities

@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:
        module = mod_importlib.import_module('mcp_servers.ticketing_logic')
        module.NOW = '2026-05-27T12:00:00Z'
        module.now_iso = lambda : '2026-05-27T12:00:00Z'
    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 module

class World:

    def apply_event(self, event_id):
        if event_id != 'E1' or event_id in self._applied_boundary_events:
            return self._ticketing_evolution_apply_event(event_id)
        before = self.business_hash()
        receipt = self._ticketing_evolution_apply_event(event_id)
        entities = self._state.list_snapshot()
        events = {self._catalog[atom]['event_id'] for atom in DATA_MIGRATED_ATOMS}
        mappings = {}
        for (kind, field) in (('event', 'event_id'), ('performance', 'performance_id'), ('ticket_type', 'ticket_type_id')):
            mappings[field] = {row[field]: fn_handle(kind, 'event-catalog-migration-evolution-v4' + ':' + row[field]) for row in entities[kind] if row['event_id'] in events}
        self._state.restore(fn_rekey_entities(entities, mappings))
        self._catalog = {atom: fn_rekey_record(row, mappings) for (atom, row) in self._catalog.items()}
        self._assert_inventory_invariants()
        return {**receipt, 'before': before, 'after': self.business_hash(), 'catalog_identity_migrations': mappings}

    def snapshot(self):
        value = self._event_independent_world_snapshot()
        value['catalog_migration_contract'] = 'event-catalog-migration-evolution-v4'
        return value

    def restore(self, snapshot):
        if snapshot.get('catalog_migration_contract') != 'event-catalog-migration-evolution-v4':
            raise ValueError('Event catalog migration snapshot identity differs')
        self._event_independent_world_restore(snapshot)

    def public_task(self):
        packet = self._event_independent_world_public_task()
        packet['operational_contract'] += ' ' + 'The top-level event_id in this task packet identifies the request batch, not an event in the ticket catalog. Tool parameters named event_id refer to catalog event records. Each requested performance is identified in the targets by its event_name and performance_starts_at.'
        return packet

    def _priority_guard(self, arguments):
        return None

    def _ensure_stream_capacity(self):
        """Keep the repeated 16-task path feasible without changing read cost."""
        entities = self._state.list_snapshot()
        for ticket_type in entities['ticket_type']:
            ticket_type['inventory_limit'] = 64
            ticket_type['released_quantity'] = 64
        for tier in entities['price_tier']:
            tier['inventory_limit'] = 64
            tier['inventory_released'] = 64
        for event in entities['event']:
            event['public_capacity'] = 64 * len(DATA_TICKET_KINDS)
            event['inventory_released'] = event['public_capacity']
        for venue in entities['venue']:
            venue['capacity'] = 64 * len(DATA_TICKET_KINDS)
        seats_by_section: dict[str, list[dict[str, ext_Any]]] = {}
        for seat in entities['seat']:
            seats_by_section.setdefault(seat['venue_section_id'], []).append(seat)
        for section in entities['venue_section']:
            section_id = section['venue_section_id']
            section['capacity'] = 64
            existing = seats_by_section.get(section_id, [])
            if not existing:
                raise RuntimeError(f'section {section_id} has no seat template')
            template = min(existing, key=lambda row: int(row['seat_number']))
            occupied_numbers = {int(row['seat_number']) for row in existing}
            for seat_number in range(1, 64 + 1):
                if seat_number in occupied_numbers:
                    continue
                row = ext_deepcopy(template)
                row.update({'seat_id': fn_handle('seat', f'{section_id}:{seat_number}'), 'seat_number': seat_number, 'seat_label': f"{template['row_label']}-{seat_number}", 'status': 'active', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
                entities['seat'].append(row)
        self._state = MemoryState(entities)
        self._assert_inventory_invariants()

    def _activate_without_events(self, task_id, *, evaluator_apply_scheduled_drift=True):
        if task_id != DATA_TASK_IDS[len(self._activated_tasks)]:
            raise ValueError('task boundary must be sequential')
        before = self.business_hash()
        closed = self._close_pending()
        drift = None
        if task_id == 'T09' and evaluator_apply_scheduled_drift:
            drift = self.apply_stream_drift()
        self._task_id = task_id
        self._task_targets = []
        for (position, (atom, ticket_kind)) in enumerate(DATA_SCHEDULE_2[task_id], 1):
            cluster = self._catalog[atom]
            customer_id = fn_handle('customer', f'{task_id}:{position}')
            self._state.add_entity('customer', {'customer_id': customer_id, 'full_name': f"Ticket request {fn_handle('ref', f'{task_id}:{position}')}", 'email_address': f'{customer_id}@example.invalid', 'loyalty_tier': 'standard', 'blocked': False}, 'customer_id')
            ticket = next((row for row in self._state.list_entities('ticket_type') if row['event_id'] == cluster['event_id'] and row['ticket_kind'] == ticket_kind))
            self._task_targets.append(self._active_target({'target_id': fn_handle('request', f'{task_id}:{position}'), 'structure_atom': atom, 'binding_atom': f'{atom}:{ticket_kind}', 'rule_atom': fn_rule_id(cluster['event_kind'], ticket_kind), 'customer_id': customer_id, 'event_id': cluster['event_id'], 'event_kind': cluster['event_kind'], 'performance_id': cluster['performance_id'], 'ticket_kind': ticket_kind, 'ticket_type_id': ticket['ticket_type_id'], 'venue_id': cluster['venue_id'], 'quantity': 2}))
        self._calls = self._read_units = self._write_attempts = 0
        self._active_event_start = len(self._events)
        self._activated_tasks.append(task_id)
        receipt = {'task_id': task_id, 'before_sha256': before, 'after_sha256': self.business_hash(), 'closed_pending_orders': closed, 'drift': drift}
        self._boundary_receipts_v4.append(receipt)
        return ext_deepcopy(receipt)

    def __init__(self, **kwargs):
        self._own_finalizations = {}
        self._ticketing_init(**kwargs)

    def activate_task(self, task_id, **kwargs):
        if self._task_id == task_id:
            return ext_deepcopy(self._boundary_receipts_v4[-1])
        if len(self._activated_tasks) >= len(DATA_TASK_IDS) or task_id != DATA_TASK_IDS[len(self._activated_tasks)]:
            raise ValueError('event-ticketing task prefix differs')
        before = self.business_hash()
        closed = self._close_pending()
        drift = None
        for event in DATA_SCHEDULE_3['events']:
            if int(task_id[1:]) == event['before_task']:
                drift = self.apply_event(event['event_id'])
        receipt = self._activate_without_events(task_id, evaluator_apply_scheduled_drift=False)
        receipt.update(before_sha256=before, closed_pending_orders=closed, drift=drift)
        self._boundary_receipts_v4[-1] = ext_deepcopy(receipt)
        self._own_finalizations = {}
        return receipt

    def dispatch(self, name, arguments, actor_user_id='operator-dev-box-office'):
        if name == 'get_order' and isinstance(arguments, dict) and (set(arguments) == {'order_id'}) and isinstance(arguments['order_id'], str) and (arguments['order_id'] in self._own_finalizations) and (self._own_finalizations[arguments['order_id']]['actor'] == actor_user_id):
            return {'status': 'success', 'data': {'confirmation_only': True, 'completion_receipt': ext_deepcopy(self._own_finalizations[arguments['order_id']]['receipt'])}, 'budget': self._budget()}
        result = self._ticketing_dispatch(name, arguments, actor_user_id)
        if result.get('status') == 'success' and name == 'finalize_order_to_tickets':
            self._own_finalizations[arguments['order_id']] = {'actor': actor_user_id, 'receipt': ext_deepcopy(result)}
        elif result.get('status') == 'success' and name in DATA_WRITE_TOOLS:
            self._own_finalizations.pop(arguments.get('order_id'), None)
        return result

    def _read(self, name, arguments):
        if name == 'list_ticket_types':
            return World._ticketing_read(self, name, ext_deepcopy(arguments))
        if name != 'read_offer_terms':
            return self._ticketing_read_2(name, arguments)
        atom = fn_rule_id(arguments['event_kind'], arguments['ticket_kind'])
        row = fn_profile(fn_rule_index(atom, self._epoch))
        fields = ('audience_certificate', 'redemption_channel') if arguments['document'] == 'audience_eligibility' else ('reimbursement_cycle',)
        return {'status': 'success', 'data': {'document': {'document_id': fn_handle('terms', f"{atom}:{arguments['document']}:{self._epoch}"), 'issuing_authority': 'Audience admission office' if len(fields) == 2 else 'Promoter accounts payable', 'scope': {'event_kind': arguments['event_kind'], 'ticket_kind': arguments['ticket_kind']}, 'requirements': {field: row[field] for field in fields}, 'authority': 'current commercial contract'}}}

    def _after_read(self, name, arguments, result):
        if result.get('status') == 'success':
            if name == 'list_ticket_types':
                key = self._binding_key_for_arguments(arguments)
                if key and self.structure_revalidation.get(key) == 'awaiting_exact_stale':
                    self.structure_revalidation[key] = 'awaiting_fresh_binding'
            elif name == 'read_offer_terms':
                atom = fn_rule_id(arguments['event_kind'], arguments['ticket_kind'])
                if self.rule_revalidation.get(atom) == 'awaiting_exact_stale':
                    self.rule_revalidation[atom] = 'awaiting_fresh_terms'
        self._ticketing_after_read(name, arguments, result)

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

    def public_tool_schemas(self, role):
        return ext_deepcopy(DATA_TOOLS_2) if role == 'box_office_sales_operator' else []

    def apply_stream_drift(self, event_id='ticketing-commercial-catalog-update-v4'):
        if event_id in self._applied_boundary_events:
            return {'status': 'success', 'idempotent': True}
        archived_before = [ext_deepcopy(row) for row in self._state.list_entities('order') if row['order_id'].startswith('archive-')]
        for key in DATA_CHANGED_BINDINGS:
            (atom, ticket_kind) = key.split(':')
            event_id_value = self._catalog[atom]['event_id']
            ticket = next((row for row in self._state.list_entities('ticket_type') if row['event_id'] == event_id_value and row['ticket_kind'] == ticket_kind))
            tiers = [row for row in self._state.list_entities('price_tier') if row['event_id'] == event_id_value]
            old_index = next((index for (index, row) in enumerate(tiers) if row['price_tier_id'] == ticket['price_tier_id']))
            old_tier = tiers[old_index]
            new_tier = tiers[(old_index + 1) % len(tiers)]
            self._stale_bindings[key] = {'event_id': event_id_value, 'ticket_kind': ticket_kind, 'ticket_type_id': ticket['ticket_type_id'], 'price_tier_id': old_tier['price_tier_id'], 'venue_section_id': old_tier['venue_section_id'], 'replacement_price_tier_id': new_tier['price_tier_id'], 'replacement_venue_section_id': new_tier['venue_section_id']}
            self._state.update_entity('ticket_type', ticket['ticket_type_id'], {'price_tier_id': new_tier['price_tier_id']}, 'ticket_type_id')
            self.structure_revalidation[key] = 'awaiting_exact_stale'
        self._epoch = 1
        for cluster in self._catalog.values():
            ticket_types = [row for row in self._state.list_entities('ticket_type') if row['event_id'] == cluster['event_id']]
            for campaign in self._state.list_entities('discount_campaign'):
                if campaign['event_id'] != cluster['event_id'] or 'offer_profile_id' not in campaign:
                    continue
                eligible = [row['ticket_type_id'] for row in ticket_types if fn_profile(fn_rule_index(fn_rule_id(cluster['event_kind'], row['ticket_kind']), 1))['offer_profile_id'] == campaign['offer_profile_id']]
                self._state.update_entity('discount_campaign', campaign['discount_campaign_id'], {'ticket_type_ids': eligible}, 'discount_campaign_id')
        for atom in DATA_CHANGED_RULES:
            self.rule_revalidation[atom] = 'awaiting_exact_stale'
            self.rule_documents_seen[atom] = set()
        self._applied_boundary_events.add(event_id)
        archived_after = [row for row in self._state.list_entities('order') if row['order_id'].startswith('archive-')]
        return {'status': 'success', 'idempotent': False, 'historical_transactions_unchanged': archived_before == archived_after}

    def _binding_key_for_arguments(self, arguments):
        event_id = arguments.get('event_id')
        ticket_kind = arguments.get('ticket_kind')
        return next((key for (key, stale) in self._stale_bindings.items() if stale['event_id'] == event_id and stale['ticket_kind'] == ticket_kind), None)

    def _target_for_order(self, order_id):
        order = self._state.get_entity('order', order_id, 'order_id') if order_id else None
        if order is None:
            return None
        return next((target for target in self._task_targets if target['customer_id'] == order.get('customer_id') and target['event_id'] == order.get('event_id') and (target['performance_id'] == order.get('performance_id'))), None)

    def _build_catalog(self):
        entities = self._state.list_snapshot()
        campaign_templates = {row['event_id']: ext_deepcopy(row) for row in entities['discount_campaign']}
        historical_campaigns = ext_deepcopy(entities['discount_campaign'])
        for row in historical_campaigns:
            row['status'] = 'expired'
            row['ticket_type_ids'] = []
        entities['discount_campaign'] = historical_campaigns
        for cluster in DATA_STREAM_CLUSTERS:
            code = cluster['code']
            event_id = f'evt-{code}'
            types = [x for x in entities['ticket_type'] if x['event_id'] == event_id]
            tiers = [x for x in entities['price_tier'] if x['event_id'] == event_id]
            sections = [x for x in entities['venue_section'] if x['venue_id'] == f'ven-{code}']
            for (i, row) in enumerate(tiers):
                row['venue_section_id'] = sections[i]['venue_section_id']
                row['inventory_limit'] = row['inventory_released'] = 20
            for row in types:
                row['inventory_limit'] = row['released_quantity'] = 20
            event = next((x for x in entities['event'] if x['event_id'] == event_id))
            event['public_capacity'] = event['inventory_released'] = 80
            next((x for x in entities['venue'] if x['venue_id'] == f'ven-{code}'))['capacity'] = 80
            for i in range(8):
                row = ext_deepcopy(campaign_templates[event_id])
                row.update(fn_profile(i))
                row.update({'discount_campaign_id': f'commercial-{code}-{i}', 'name': 'House commercial offer', 'status': 'active', 'code': None, 'max_redemptions': 256, 'redemption_count': 0})
                row['ticket_type_ids'] = [x['ticket_type_id'] for x in types if fn_rule_index_2(fn_rule_id(cluster['event_kind'], x['ticket_kind']), 0) == i]
                entities['discount_campaign'].append(row)
        ids = {}
        for (entity, rows) in entities.items():
            if entity in {'customer', 'operator', 'order', 'order_line', 'audit_log'}:
                continue
            id_field = {'venue_section': 'venue_section_id', 'discount_campaign': 'discount_campaign_id'}.get(entity, f'{entity}_id')
            for row in rows:
                if id_field in row:
                    ids[row[id_field]] = fn_handle_2(entity, row[id_field])

        def renamed(value):
            if isinstance(value, str):
                return ids.get(value, value)
            if isinstance(value, list):
                return [renamed(x) for x in value]
            if isinstance(value, dict):
                return {k: renamed(v) for (k, v) in value.items()}
            return value
        entities = renamed(entities)
        self._state = MemoryState(entities)
        for cluster in DATA_STREAM_CLUSTERS:
            self._catalog[cluster['atom_id']] = {**cluster, 'event_id': ids[f"evt-{cluster['code']}"], 'venue_id': ids[f"ven-{cluster['code']}"], 'performance_id': ids[f"pf-{cluster['code']}-n7"]}

    def _close_pending(self):
        closed = []
        for order in list(self._state.list_entities('order')):
            if order['order_status'] not in {'draft', 'pending_payment'}:
                continue
            for line in list(self._state.list_entities('order_line')):
                if line['order_id'] != order['order_id'] or line['status'] in {'canceled', 'refunded'}:
                    continue
                quantity = int(line['quantity'])
                for (entity, key, held) in (('event', 'event_id', 'inventory_held'), ('ticket_type', 'ticket_type_id', 'held_quantity'), ('price_tier', 'price_tier_id', 'inventory_held')):
                    record = self._state.get_entity(entity, line[key], key)
                    self._state.update_entity(entity, line[key], {held: int(record[held]) - quantity}, key)
                self._state.update_entity('order_line', line['order_line_id'], {'status': 'canceled'}, 'order_line_id')
            self._state.update_entity('order', order['order_id'], {'order_status': 'canceled'}, 'order_id')
            closed.append(order['order_id'])
        self._assert_inventory_invariants()
        return closed

    def grade(self, task_id):
        full = self._event_ticketing_adapter_grade(task_id)
        entities = self._state.list_snapshot()
        for (target, grade) in zip(self._task_targets, full['deliverables'], strict=True):
            orders = [x for x in entities['order'] if x.get('customer_id') == target['customer_id'] and x.get('event_id') == target['event_id'] and (x.get('performance_id') == target['performance_id']) and (x.get('order_status') != 'canceled')]
            lines = [x for x in entities['order_line'] if any((o['order_id'] == x['order_id'] for o in orders)) and x.get('ticket_type_id') == target['ticket_type_id'] and (x.get('venue_section_id') == target['venue_section_id']) and (x.get('quantity') == 2) and (x.get('status') not in {'canceled', 'refunded'})]
            seated = [x for x in lines if x.get('status') == 'confirmed' and len(set(x.get('seat_ids', []))) == 2]
            offer = any((target['required_campaign_id'] in x.get('applied_campaign_ids', []) for x in orders)) and bool(seated)
            duplicate = sum((x.get('order_status') == 'paid' for x in orders)) > 1
            complete = grade['score'] == 25 and (not duplicate)
            grade.update({'registered_order': bool(orders), 'inventory_held': bool(lines), 'seats_bound': bool(seated), 'eligible_offer_applied': offer, 'complete': complete, 'conflicting_duplicate': duplicate})
            grade['score'] = 0.0 if duplicate else 25.0 if complete else float(bool(orders)) + 2.0 * bool(lines) + 5.0 * bool(seated) + 2.0 * offer
        full['score'] = sum((x['score'] for x in full['deliverables']))
        full['completed_artifacts'] = sum((x['complete'] for x in full['deliverables']))
        return full

    def _activate_without_drift(self, task_id):
        if task_id != 'T09':
            raise ValueError('counterfactual activation is defined only at T09')
        expected = DATA_TASK_IDS_2[len(self._activated_tasks)]
        if task_id != expected:
            raise ValueError(f'expected {expected}, got {task_id}')
        fixture = fn__task_fixture(task_id, post_drift=False)
        fixture_customers = {row['customer_id']: row for row in fixture['entities']['customer']}
        targets = []
        for fixture_target in fixture['targets']:
            customer = fixture_customers[fixture_target['customer_id']]
            if self._state.get_entity('customer', customer['customer_id'], 'customer_id') is None:
                self._state.add_entity('customer', customer, 'customer_id')
            targets.append(self._active_target(fixture_target))
        self._task_id = task_id
        self._task_targets = targets
        self._calls = 0
        self._read_units = 0
        self._write_attempts = 0
        self._active_event_start = len(self._events)
        self._activated_tasks.append(task_id)
        return {'status': 'success', 'task_id': task_id, 'world_reset': False, 'budget_reset': True, 'boundary_event_applied': False, 'entry_business_hash': self.business_hash(), 'entry_lineage_hash': self.lineage_hash(), 'counterfactual_pre_event': True}

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

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

    @property
    def remaining(self):
        return self._budget()

    def business_hash(self):
        return self._business_hash()

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

    def _apply_drift(self, event_id='evt-ticket-policy-and-binding-2026-07-v2'):
        if event_id in self._applied_boundary_events:
            return {'status': 'success', 'idempotent': True, 'changed': []}
        changed: list[str] = []
        for cluster in DATA_STREAM_CLUSTERS:
            code = cluster['code']
            event_id_value = f'evt-{code}'
            section_ids = sorted((row['venue_section_id'] for row in self._state.list_entities('venue_section') if row['venue_id'] == f'ven-{code}'))
            for (ticket_index, ticket_kind) in enumerate(DATA_TICKET_KINDS):
                atom = fn_rule_id(cluster['event_kind'], ticket_kind)
                ticket_type_id = f"tt-{code}-{('h', 's', 'v', 'g')[ticket_index]}"
                if atom in DATA_DRIFT_CHANGED_RULES:
                    old_lane = DATA_RULE_LANES[cluster['event_kind']][ticket_kind]
                    new_lane = DATA_OFFER_LANES[(DATA_OFFER_LANES.index(old_lane) + 1) % len(DATA_OFFER_LANES)]
                    for campaign in self._state.list_entities('discount_campaign'):
                        if campaign['event_id'] != event_id_value:
                            continue
                        eligible = [value for value in campaign.get('ticket_type_ids', []) if value != ticket_type_id]
                        if campaign['discount_campaign_id'] == f'offer-{code}-{new_lane}':
                            eligible.append(ticket_type_id)
                        self._state.update_entity('discount_campaign', campaign['discount_campaign_id'], {'ticket_type_ids': sorted(set(eligible)), 'updated_at': '2026-05-27T12:00:00Z'}, 'discount_campaign_id')
                    archive_id = f'archive-{code}-{ticket_index + 1}'
                    self._state.update_entity('order', archive_id, {'applied_campaign_ids': [f'offer-{code}-{new_lane}'], 'updated_at': '2026-05-27T12:00:00Z'}, 'order_id')
                    changed.append(atom)
                if cluster['atom_id'] in DATA_DRIFT_CHANGED_STRUCTURES:
                    ticket_type = self._state.get_entity('ticket_type', ticket_type_id, 'ticket_type_id')
                    tier = self._state.get_entity('price_tier', ticket_type['price_tier_id'], 'price_tier_id')
                    current_index = section_ids.index(tier['venue_section_id'])
                    new_section_id = section_ids[(current_index + 1) % len(section_ids)]
                    self._state.update_entity('price_tier', tier['price_tier_id'], {'venue_section_id': new_section_id, 'updated_at': '2026-05-27T12:00:00Z'}, 'price_tier_id')
            if cluster['atom_id'] in DATA_DRIFT_CHANGED_STRUCTURES:
                changed.append(cluster['atom_id'])
        self._applied_boundary_events.add(event_id)
        return {'status': 'success', 'idempotent': False, 'changed': sorted(set(changed))}

    def _active_target(self, fixture_target):
        target = ext_deepcopy(fixture_target)
        ticket_type = self._state.get_entity('ticket_type', target['ticket_type_id'], 'ticket_type_id')
        tier = self._state.get_entity('price_tier', ticket_type['price_tier_id'], 'price_tier_id')
        target['price_tier_id'] = tier['price_tier_id']
        target['venue_section_id'] = tier['venue_section_id']
        campaigns = [row for row in self._state.list_entities('discount_campaign') if row['event_id'] == target['event_id'] and target['ticket_type_id'] in set(row.get('ticket_type_ids') or [])]
        if len(campaigns) != 1:
            raise AssertionError(f"expected one eligible campaign for {target['target_id']}")
        target['required_campaign_id'] = campaigns[0]['discount_campaign_id']
        target['required_offer_lane'] = campaigns[0]['discount_campaign_id'].rsplit('-', 1)[-1]
        target['preferred_seat_ids'] = self.available_seat_ids(target)[:target['quantity']]
        if len(target['preferred_seat_ids']) != target['quantity']:
            raise RuntimeError(f"insufficient seats for {target['target_id']}")
        return target

    def available_seat_ids(self, target):
        assigned = {seat_id for line in self._state.list_entities('order_line') if line.get('performance_id') == target['performance_id'] and line.get('status') not in {'canceled', 'refunded'} for seat_id in line.get('seat_ids') or []}
        assigned.update((row.get('seat_id') for row in self._state.list_entities('ticket') if row.get('performance_id') == target['performance_id'] and row.get('ticket_status') in {'issued', 'transferred'}))
        return sorted((row['seat_id'] for row in self._state.list_entities('seat') if row['venue_section_id'] == target['venue_section_id'] and row.get('status') == 'active' and (row['seat_id'] not in assigned)))

    def current_episode_events(self):
        return ext_deepcopy(self._events[self._active_event_start:])

    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', True) or actor.get('role') != 'box_office_sales_operator':
            return None
        return actor

    def _event(self, event_id):
        return self._state.get_entity('event', event_id, 'event_id') if event_id else None

    def _target_venue(self, name, arguments):
        if name == 'get_venue_seating_chart':
            return arguments.get('venue_id')
        if name in {'list_performances', 'list_ticket_types', 'list_price_tiers', 'get_event_sales_dashboard', 'create_order'}:
            event = self._event(arguments.get('event_id'))
            return event.get('venue_id') if event else None
        if name in {'add_order_line', 'apply_discount_to_order', 'finalize_order_to_tickets'}:
            order = self._state.get_entity('order', arguments.get('order_id'), 'order_id')
            event = self._event(order.get('event_id')) if order else None
            return event.get('venue_id') if event else None
        if name == 'assign_seats_to_order_line':
            line = self._state.get_entity('order_line', arguments.get('order_line_id'), 'order_line_id')
            event = self._event(line.get('event_id')) if line else None
            return event.get('venue_id') if event else None
        return None

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

    @staticmethod
    def _read_cost(name, result):
        if result.get('status') != 'success':
            return 1
        data = result.get('data') or {}
        if name == 'list_events':
            return 1 + len(data.get('events') or [])
        if name == 'list_performances':
            return 1 + len(data.get('performances') or [])
        if name == 'list_ticket_types':
            return 1 + len(data.get('ticket_types') or [])
        if name == 'list_price_tiers':
            return 1 + len(data.get('price_tiers') or [])
        if name == 'search_customers':
            return 1 + len(data.get('customers') or [])
        if name == 'get_customer_orders':
            return 1 + len(data.get('orders') or [])
        if name == 'get_venue_seating_chart':
            sections = data.get('sections') or []
            return 1 + len(sections) + sum((len(row.get('seats') or []) for row in sections))
        if name == 'get_event_sales_dashboard':
            return 1 + len(data.get('campaigns') or [])
        if name == 'get_order':
            return 5 + len(data.get('lines') or []) + len(data.get('tickets') or []) + len(data.get('refunds') or [])
        return 1

    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': cost, 'budget_after': self._budget(), 'state_hash_before': before_hash, 'state_hash_after': after_hash})

    def _assert_inventory_invariants(self):
        ticket_types = self._state.list_entities('ticket_type')
        tiers = self._state.list_entities('price_tier')
        events = self._state.list_entities('event')
        for row in ticket_types:
            held = int(row.get('held_quantity') or 0)
            sold = int(row.get('sold_quantity') or 0)
            released = int(row.get('released_quantity') or 0)
            if min(held, sold) < 0 or held + sold > released:
                raise ValueError('ticket-type inventory invariant failed')
        for row in tiers:
            held = int(row.get('inventory_held') or 0)
            sold = int(row.get('inventory_sold') or 0)
            released = int(row.get('inventory_released') or 0)
            if min(held, sold) < 0 or held + sold > released:
                raise ValueError('price-tier inventory invariant failed')
        for event in events:
            event_types = [row for row in ticket_types if row.get('event_id') == event['event_id']]
            event_tiers = [row for row in tiers if row.get('event_id') == event['event_id']]
            held = int(event.get('inventory_held') or 0)
            sold = int(event.get('inventory_sold') or 0)
            if min(held, sold) < 0 or held + sold > int(event.get('public_capacity') or 0):
                raise ValueError('event inventory invariant failed')
            if held != sum((int(row.get('held_quantity') or 0) for row in event_types)):
                raise ValueError('event and ticket-type held counters diverged')
            if sold != sum((int(row.get('sold_quantity') or 0) for row in event_types)):
                raise ValueError('event and ticket-type sold counters diverged')
            if held != sum((int(row.get('inventory_held') or 0) for row in event_tiers)):
                raise ValueError('event and price-tier held counters diverged')
            if sold != sum((int(row.get('inventory_sold') or 0) for row in event_tiers)):
                raise ValueError('event and price-tier sold counters diverged')

    def _ticketing_evolution_apply_event(self, event_id):
        if event_id not in {'E1', 'E2'}:
            raise ValueError('unknown event-ticketing 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 == 'E1':
            for binding in DATA_CHANGED_BINDINGS:
                (atom, kind) = binding.split(':')
                eid = self._catalog[atom]['event_id']
                ticket = next((t for t in self._state.list_entities('ticket_type') if t['event_id'] == eid and t['ticket_kind'] == kind))
                tiers = [t for t in self._state.list_entities('price_tier') if t['event_id'] == eid]
                index = next((i for (i, t) in enumerate(tiers) if t['price_tier_id'] == ticket['price_tier_id']))
                self._state.update_entity('ticket_type', ticket['ticket_type_id'], {'price_tier_id': tiers[(index + 1) % len(tiers)]['price_tier_id']}, 'ticket_type_id')
        else:
            if 'E1' not in self._applied_boundary_events:
                raise ValueError('event-ticketing events must be applied in order')
            self._epoch = 1
            for cluster in self._catalog.values():
                tickets = [t for t in self._state.list_entities('ticket_type') if t['event_id'] == cluster['event_id']]
                for campaign in self._state.list_entities('discount_campaign'):
                    if campaign['event_id'] != cluster['event_id'] or 'offer_profile_id' not in campaign:
                        continue
                    eligible = [t['ticket_type_id'] for t in tickets if fn_profile(fn_rule_index(fn_rule_id(cluster['event_kind'], t['ticket_kind']), 1))['offer_profile_id'] == campaign['offer_profile_id']]
                    self._state.update_entity('discount_campaign', campaign['discount_campaign_id'], {'ticket_type_ids': eligible}, 'discount_campaign_id')
        self._applied_boundary_events.add(event_id)
        self._assert_inventory_invariants()
        return {'event_id': event_id, 'applied': True, 'before': before, 'after': self.business_hash()}

    def _event_independent_world_snapshot(self):
        value = self._ticketing_evolution_snapshot()
        value['independent_purchase_contract'] = 'event-independent-purchases-evolution-v2'
        return value

    def _event_independent_world_restore(self, snapshot):
        if snapshot.get('independent_purchase_contract') != 'event-independent-purchases-evolution-v2':
            raise ValueError('Event independent purchase contract differs')
        self._ticketing_evolution_restore(snapshot)

    def _event_independent_world_public_task(self):
        packet = self._ticketing_evolution_public_task()
        if packet['objective'].count('Complete policy-compliant ticket purchases in listed priority order. A later request cannot be committed until every earlier request is complete.') != 1:
            raise ValueError('Parent Event ordering text differs')
        packet['objective'] = packet['objective'].replace('Complete policy-compliant ticket purchases in listed priority order. A later request cannot be committed until every earlier request is complete.', 'Complete policy-compliant ticket purchases in any order. An unfinished customer request does not block an unrelated purchase.')
        packet['completion'].update(mode='independent', priority_order='none', started_item_must_close=False)
        return packet

    def _ticketing_init(self, source_root=CASE_DIR / 'raw', snapshot=None):
        self._ticketing_init_2(source_root, snapshot=None)
        self._ensure_stream_capacity()
        self.structure_revalidation: dict[str, str] = {}
        self.rule_revalidation: dict[str, str] = {}
        self.rule_documents_seen: dict[str, set[str]] = {}
        self._stale_bindings: dict[str, dict[str, str]] = {}
        self._boundary_receipts_v4: list[dict[str, ext_Any]] = []
        if snapshot is not None:
            self.restore(snapshot)

    def _ticketing_dispatch(self, name, arguments, actor_user_id='operator-dev-box-office'):
        if self._task_id is None:
            return fn__error('TASK_NOT_ACTIVE', 'no active request event')
        if name not in DATA_TOOLS_BY_NAME or self._actor(actor_user_id) is None:
            return fn__error('TOOL_NOT_ALLOWED', 'tool or actor is not authorized')
        try:
            mod_jsonschema.validate(arguments, DATA_TOOLS_BY_NAME[name]['input_schema'])
        except mod_jsonschema.ValidationError:
            return fn__error('INVALID_ARGUMENTS', 'arguments do not match the public schema')
        write = name in DATA_WRITE_TOOLS
        if self._calls >= 96 or (self._write_attempts >= 22 if write else self._read_units >= 25):
            return {**fn__error('WRITE_BUDGET_EXHAUSTED' if write else 'READ_BUDGET_EXHAUSTED', 'the work allowance is exhausted'), 'budget': self._budget()}
        before = self._state.list_snapshot()
        before_hash = self.business_hash()
        args = ext_deepcopy(arguments)
        target = None
        stale_binding = False
        stale_rule = False
        selected_profile = args.get('offer_profile_id')
        try:
            if write:
                result = None
                if name == 'create_order':
                    result = self._priority_guard(args)
                if name in {'add_order_line', 'apply_discount_to_order'}:
                    target = self._target_for_order(args.get('order_id'))
                if target is not None and name == 'add_order_line':
                    key = target['binding_atom']
                    stale = self._stale_bindings.get(key, {})
                    stale_binding = bool(self.structure_revalidation.get(key) == 'awaiting_exact_stale' and args.get('ticket_type_id') == stale.get('ticket_type_id') and (args.get('venue_section_id') == stale.get('venue_section_id')))
                if target is not None and name == 'apply_discount_to_order':
                    atom = target['rule_atom']
                    stale_rule = bool(self.rule_revalidation.get(atom) == 'awaiting_exact_stale' and selected_profile == fn_profile(fn_rule_index(atom, 0))['offer_profile_id'])
                if result is None:
                    if name == 'apply_discount_to_order' and 'offer_profile_id' in args:
                        selected = args.pop('offer_profile_id')
                        order = self._state.get_entity('order', args['order_id'], 'order_id')
                        matches = [row for row in self._state.list_entities('discount_campaign') if order and row['event_id'] == order['event_id'] and (row.get('offer_profile_id') == selected) and (row['status'] == 'active')]
                        args['discount_campaign_id'] = matches[0]['discount_campaign_id'] if len(matches) == 1 else selected
                    if name in {'assign_seats_to_order_line', 'apply_discount_to_order', 'finalize_order_to_tickets'}:
                        args['operator_id'] = actor_user_id
                    result = self._logic.execute_tool(name, self._state, **args)
                    if result.get('status') == 'success':
                        self._assert_inventory_invariants()
            else:
                result = self._read(name, args)
        except Exception:
            self._state.restore(before)
            raise
        result = fn__normalize_result(result)
        if stale_binding and result.get('status') == 'error':
            result = fn__error('SECTION_PRICE_TIER_MISMATCH', 'ticket type and venue section do not match the current catalog binding')
            self.structure_revalidation[target['binding_atom']] = 'awaiting_fresh_binding'
        if stale_rule and result.get('status') == 'error':
            result = fn__error('NO_ELIGIBLE_LINES', 'the selected house offer is not eligible for the current order lines')
            self.rule_revalidation[target['rule_atom']] = 'awaiting_fresh_terms'
            self.rule_documents_seen[target['rule_atom']] = set()
        cost = {'read_work_units': 0, 'write_attempts': int(write)}
        if write:
            self._write_attempts += 1
            if result.get('status') != 'success':
                self._state.restore(before)
            elif target is not None and name == 'add_order_line':
                key = target['binding_atom']
                if self.structure_revalidation.get(key) == 'ready_current':
                    self.structure_revalidation[key] = 'validated_current'
            elif target is not None and name == 'apply_discount_to_order':
                atom = target['rule_atom']
                if self.rule_revalidation.get(atom) == 'ready_current':
                    self.rule_revalidation[atom] = 'validated_current'
        else:
            units = 2 if name == 'read_offer_terms' and result.get('status') == 'success' else self._read_cost(name, result)
            remaining = 25 - self._read_units
            cost['read_work_units'] = min(units, remaining)
            self._read_units += cost['read_work_units']
            if units > remaining:
                result = fn__error('READ_BUDGET_EXHAUSTED', 'read exceeds the remaining returned work', required_units=units, available_units=remaining)
            else:
                self._after_read(name, arguments, result)
        self._calls += 1
        result['budget'] = self._budget()
        self._record_event(name, actor_user_id, result, before_hash, self.business_hash(), cost)
        return ext_deepcopy(result)

    def _ticketing_read(self, name, arguments):
        args = ext_deepcopy(arguments)
        if name == 'read_offer_terms':
            atom = fn_rule_id(args['event_kind'], args['ticket_kind'])
            row = fn_profile(fn_rule_index_2(atom, self._epoch))
            fields = ('audience_certificate', 'redemption_channel') if args['document'] == 'audience_eligibility' else ('reimbursement_cycle',)
            return {'status': 'success', 'data': {'document': {'document_id': fn_handle_2('terms', f"{atom}:{args['document']}:{self._epoch}"), 'issuing_authority': 'Audience admission office' if len(fields) == 2 else 'Promoter accounts payable', 'scope': {'event_kind': args['event_kind'], 'ticket_kind': args['ticket_kind']}, 'requirements': {x: row[x] for x in fields}, 'authority': 'current commercial contract'}}}
        if name == 'get_venue_seating_chart':
            if args.get('available_only') and (not args.get('performance_id')):
                return fn__error('PERFORMANCE_REQUIRED', 'availability requires a performance scope')
            performance = self._state.get_entity('performance', args.get('performance_id'), 'performance_id') if args.get('performance_id') else None
            if args.get('performance_id') and (performance is None or performance['venue_id'] != args['venue_id']):
                return fn__error('PERFORMANCE_VENUE_MISMATCH', 'performance is not at this venue')
            occupied = {seat for line in self._state.list_entities('order_line') if line.get('performance_id') == args.get('performance_id') and line.get('status') not in {'canceled', 'refunded'} for seat in line.get('seat_ids', [])}
            sections = [ext_deepcopy(x) for x in self._state.list_entities('venue_section') if x['venue_id'] == args['venue_id'] and (not args.get('venue_section_id') or x['venue_section_id'] == args['venue_section_id']) and (not args.get('section_type_filter') or x['section_type'] == args['section_type_filter'])]
            section_ids = {x['venue_section_id'] for x in sections}
            seats = [ext_deepcopy(x) for x in self._state.list_entities('seat') if x['venue_section_id'] in section_ids and (not args.get('seat_status_filter') or x['status'] == args['seat_status_filter']) and (not args.get('available_only') or x['seat_id'] not in occupied)]
            seats.sort(key=lambda x: x['seat_id'])
            (offset, limit) = (args.get('offset', 0), args.get('limit', 2))
            page = seats[offset:offset + limit] if args.get('include_seats') else []
            for row in page:
                row['occupied'] = row['seat_id'] in occupied if performance else None
            for section in sections:
                section['seats'] = [x for x in page if x['venue_section_id'] == section['venue_section_id']]
            return {'status': 'success', 'data': {'sections': sections, 'total_seats': len(seats), 'next_offset': offset + limit if args.get('include_seats') and offset + limit < len(seats) else None, 'performance_id': args.get('performance_id')}}
        tier_id = args.pop('price_tier_id', None) if name == 'list_price_tiers' else None
        if tier_id:
            rows = [ext_deepcopy(x) for x in self._state.list_entities('price_tier') if x['event_id'] == args['event_id'] and x['price_tier_id'] == tier_id and (not args.get('active_only') or x['active'])]
            result = {'status': 'success', 'data': {'price_tiers': rows, 'total_count': len(rows)}}
        else:
            result = self._logic.execute_tool(name, self._state, **args)
        if name == 'get_event_sales_dashboard' and result.get('status') == 'success':
            current = [x for x in self._state.list_entities('discount_campaign') if x['event_id'] == args['event_id'] and x['status'] == 'active']
            result['data']['campaigns'] = [{k: x[k] for k in ('discount_campaign_id', 'offer_profile_id', 'audience_certificate', 'redemption_channel', 'reimbursement_cycle', 'status')} for x in current] if args.get('include_campaigns', True) else []
        return result

    def _ticketing_read_2(self, name, arguments):
        args = ext_deepcopy(arguments)
        if name == 'read_offer_terms':
            atom = fn_rule_id(args['event_kind'], args['ticket_kind'])
            state = self.rule_revalidation.get(atom)
            epoch = 0 if state == 'awaiting_exact_stale' else self._epoch
            row = fn_profile(fn_rule_index(atom, epoch))
            fields = ('audience_certificate', 'redemption_channel') if args['document'] == 'audience_eligibility' else ('reimbursement_cycle',)
            return {'status': 'success', 'data': {'document': {'document_id': fn_handle('terms', f"{atom}:{args['document']}:{epoch}"), 'issuing_authority': 'Audience admission office' if len(fields) == 2 else 'Promoter accounts payable', 'scope': {'event_kind': args['event_kind'], 'ticket_kind': args['ticket_kind']}, 'requirements': {field: row[field] for field in fields}, 'authority': 'current commercial contract'}}}
        if name == 'get_event_sales_dashboard':
            filters = {key: args.pop(key, None) for key in ('audience_certificate', 'redemption_channel', 'reimbursement_cycle')}
            result = self._ticketing_read(name, args)
            if result.get('status') == 'success':
                campaigns = result['data'].get('campaigns', [])
                result['data']['campaigns'] = [row for row in campaigns if all((value is None or row.get(key) == value for (key, value) in filters.items()))]
            return result
        result = self._ticketing_read(name, args)
        if name == 'list_ticket_types' and result.get('status') == 'success':
            for (key, stale) in self._stale_bindings.items():
                state = self.structure_revalidation.get(key)
                exact = args.get('event_id') == stale['event_id'] and args.get('ticket_kind') == stale['ticket_kind']
                reveal = state in {'ready_current', 'validated_current'} or (exact and state in {'awaiting_fresh_binding', 'awaiting_fresh_tier'})
                if reveal:
                    continue
                for row in result['data'].get('ticket_types', []):
                    if row.get('ticket_type_id') == stale['ticket_type_id']:
                        row['price_tier_id'] = stale['price_tier_id']
        return result

    def _ticketing_after_read(self, name, arguments, result):
        if result.get('status') != 'success':
            return
        if name == 'list_ticket_types':
            key = self._binding_key_for_arguments(arguments)
            if key and self.structure_revalidation.get(key) == 'awaiting_fresh_binding':
                self.structure_revalidation[key] = 'awaiting_fresh_tier'
        elif name == 'list_price_tiers':
            for (key, stale) in self._stale_bindings.items():
                if self.structure_revalidation.get(key) == 'awaiting_fresh_tier' and arguments.get('event_id') == stale['event_id'] and (arguments.get('price_tier_id') == stale['replacement_price_tier_id']):
                    self.structure_revalidation[key] = 'ready_current'
        elif name == 'read_offer_terms':
            atom = fn_rule_id(arguments['event_kind'], arguments['ticket_kind'])
            if self.rule_revalidation.get(atom) in {'awaiting_fresh_terms', 'awaiting_fresh_offer'}:
                self.rule_documents_seen.setdefault(atom, set()).add(arguments['document'])
                if self.rule_documents_seen[atom] == {'audience_eligibility', 'promoter_settlement'}:
                    self.rule_revalidation[atom] = 'awaiting_fresh_offer'
        elif name == 'get_event_sales_dashboard':
            exact_filters = all((arguments.get(key) is not None for key in ('audience_certificate', 'redemption_channel', 'reimbursement_cycle')))
            if not exact_filters or len(result.get('data', {}).get('campaigns', [])) != 1:
                return
            for target in self._task_targets:
                atom = target['rule_atom']
                expected = fn_profile(fn_rule_index(atom, 1))
                if self.rule_revalidation.get(atom) == 'awaiting_fresh_offer' and arguments.get('event_id') == target['event_id'] and all((arguments.get(key) == expected[key] for key in ('audience_certificate', 'redemption_channel', 'reimbursement_cycle'))):
                    self.rule_revalidation[atom] = 'ready_current'

    def _event_ticketing_adapter_grade(self, task_id):
        if task_id != self._task_id:
            raise ValueError('task is not active')
        entities = self._state.list_snapshot()
        deliverables = []
        for target in self._task_targets:
            candidates = [row for row in entities['order'] if row.get('customer_id') == target['customer_id'] and row.get('event_id') == target['event_id'] and (row.get('performance_id') == target['performance_id']) and (row.get('order_status') == 'paid') and (row.get('payment_status') == 'paid') and (target['required_campaign_id'] in (row.get('applied_campaign_ids') or []))]
            passed = None
            for order in candidates:
                lines = [row for row in entities['order_line'] if row.get('order_id') == order['order_id'] and row.get('ticket_type_id') == target['ticket_type_id'] and (row.get('venue_section_id') == target['venue_section_id']) and (int(row.get('quantity') or 0) == target['quantity']) and (row.get('status') == 'confirmed')]
                if len(lines) != 1:
                    continue
                line = lines[0]
                seat_ids = line.get('seat_ids') or []
                tickets = [row for row in entities['ticket'] if row.get('order_id') == order['order_id'] and row.get('order_line_id') == line['order_line_id'] and (row.get('ticket_status') == 'issued')]
                ticket_seats = {row.get('seat_id') for row in tickets}
                if len(seat_ids) != target['quantity'] or len(tickets) != target['quantity']:
                    continue
                if len(set(seat_ids)) != target['quantity'] or ticket_seats != set(seat_ids):
                    continue
                if any(((self._state.get_entity('seat', seat_id, 'seat_id') or {}).get('venue_section_id') != target['venue_section_id'] for seat_id in seat_ids)):
                    continue
                passed = {'order': order, 'line': line, 'tickets': tickets}
                break
            deliverables.append({'target_id': target['target_id'], 'structure_atom': target['structure_atom'], 'rule_atom': target['rule_atom'], 'paid_order': passed is not None, 'eligible_offer_applied': passed is not None, 'seats_bound': passed is not None, 'issued_tickets': passed is not None, 'inventory_conserved': passed is not None, 'order_id': passed['order']['order_id'] if passed else None, 'ticket_ids': [row['ticket_id'] for row in passed['tickets']] if passed else [], 'score': 25.0 if passed else 0.0})
        completed = sum((row['score'] == 25.0 for row in deliverables))
        return {'task_id': task_id, 'score': completed * 25.0, 'max_score': 100.0, 'completed_artifacts': completed, 'deliverables': deliverables, 'budget': self._budget()}

    def _ticketing_evolution_snapshot(self):
        value = self._ticketing_snapshot()
        value['evolution'] = {'case_version': 'event-ticketing-two-event-evolution-v1', 'schedule': ext_deepcopy(DATA_SCHEDULE_3), 'blueprint_sha256': fn_digest(DATA_SCHEDULE_2), 'own_finalizations': ext_deepcopy(self._own_finalizations)}
        return value

    def _ticketing_evolution_restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        metadata = value.pop('evolution')
        if metadata['case_version'] != 'event-ticketing-two-event-evolution-v1' or metadata['schedule'] != DATA_SCHEDULE_3 or metadata['blueprint_sha256'] != fn_digest(DATA_SCHEDULE_2):
            raise ValueError('event-ticketing evolution contract differs')
        active = value['activated_tasks']
        expected = [e['event_id'] for e in DATA_SCHEDULE_3['events'] if e['before_task'] <= len(active)]
        if active != list(DATA_TASK_IDS[:len(active)]) or value['task_id'] != (active[-1] if active else None) or value['applied_boundary_events'] != expected:
            raise ValueError('event-ticketing evolution prefix or event ledger differs')
        self._ticketing_restore(value)
        self._own_finalizations = metadata['own_finalizations']
        self._assert_inventory_invariants()
        if self.snapshot() != snapshot:
            raise ValueError('event-ticketing snapshot did not round trip')

    def _ticketing_evolution_public_task(self):
        value = self._ticketing_public_task()
        value['completion'].pop('verification_required')
        value['completion']['evidence'] = {'mode': 'authoritative_receipt', 'source': 'successful finalize_order_to_tickets', 'proves': 'paid order and issued ticket IDs'}
        value['operational_contract'] += ' Exact get_order confirmation of an order you finalized in this episode returns only its saved finalization receipt at zero read, write and business-call quota. Other order reads remain charged.'
        return value

    def _ticketing_init_2(self, source_root=CASE_DIR / 'raw', snapshot=None):
        self._event_ticketing_mixed_successor_init(source_root)
        self._epoch = 0
        self._boundary_receipts = []
        self._catalog = {}
        self._build_catalog()
        if snapshot is not None:
            self.restore(snapshot)

    def _ticketing_snapshot(self):
        value = self._ticketing_snapshot_2()
        value['v4'] = {'structure_revalidation': ext_deepcopy(self.structure_revalidation), 'rule_revalidation': ext_deepcopy(self.rule_revalidation), 'rule_documents_seen': {key: sorted(documents) for (key, documents) in self.rule_documents_seen.items()}, 'stale_bindings': ext_deepcopy(self._stale_bindings), 'boundary_receipts': ext_deepcopy(self._boundary_receipts_v4)}
        return value

    def _ticketing_restore(self, snapshot):
        self._ticketing_restore_2(snapshot)
        extra = snapshot.get('v4', {})
        self.structure_revalidation = ext_deepcopy(extra.get('structure_revalidation', {}))
        self.rule_revalidation = ext_deepcopy(extra.get('rule_revalidation', {}))
        self.rule_documents_seen = {key: set(documents) for (key, documents) in extra.get('rule_documents_seen', {}).items()}
        self._stale_bindings = ext_deepcopy(extra.get('stale_bindings', {}))
        self._boundary_receipts_v4 = ext_deepcopy(extra.get('boundary_receipts', []))

    def _ticketing_public_task(self):
        task = self._ticketing_public_task_2()
        task['operational_contract'] = task['operational_contract'].replace('Commercial conditions apply until a normal business action rejects the retained path.', 'Commercial conditions apply until contradicted by current authoritative terms or ordinary business evidence.')
        return task

    def _event_ticketing_mixed_successor_init(self, source_root=CASE_DIR / 'raw', snapshot=None):
        source_root = ext_Path(source_root).resolve()
        self._persistent_event_ticketing_adapter_init(source_root)
        ((logic,), _) = ext_load_isolated_modules(source_root, ('mcp_servers.ticketing_logic',))
        logic.NOW = '2026-05-27T12:00:00Z'
        logic.now_iso = lambda : '2026-05-27T12:00:00Z'
        self._logic = logic
        if snapshot is not None:
            self.restore(snapshot)

    def _ticketing_snapshot_2(self):
        value = self._persistent_event_ticketing_adapter_snapshot()
        value['v3'] = {'epoch': getattr(self, '_epoch', 0), 'catalog': ext_deepcopy(getattr(self, '_catalog', {})), 'boundary_receipts': ext_deepcopy(getattr(self, '_boundary_receipts', []))}
        return value

    def _ticketing_restore_2(self, snapshot):
        self._persistent_event_ticketing_adapter_restore(snapshot)
        extra = snapshot.get('v3', {})
        self._epoch = extra.get('epoch', 0)
        self._catalog = ext_deepcopy(extra.get('catalog', {}))
        self._boundary_receipts = ext_deepcopy(extra.get('boundary_receipts', []))

    def _ticketing_public_task_2(self):
        requests = []
        for target in self._task_targets:
            cluster = self._catalog[target['structure_atom']]
            requests.append({'request_reference': target['target_id'], 'customer_reference': target['customer_id'], 'event_name': cluster['event_name'], 'performance_starts_at': cluster['starts_at'], 'ticket_kind': target['ticket_kind'], 'quantity': 2})
        return {'schema': 'rescopebench-public-task/v5', 'case_id': 'event_ticketing', 'task_id': fn_handle('event', self._task_id), 'objective': 'Complete policy-compliant ticket purchases in listed priority order. A later request cannot be committed until every earlier request is complete. A complete purchase has one paid order, the requested admission class in its current bound section, two distinct available seats, the eligible house offer, and issued tickets.', 'requests': requests, 'completion': {'mode': 'ordered_independent', 'subset_allowed': True, 'priority_order': 'listed', 'started_item_must_close': True, 'verification_required': True}, 'budget': {'read_work_units': 25, 'write_attempts': 22}, 'operational_contract': 'Catalog IDs and seat-to-section membership persist until contradicted by current business evidence. Commercial conditions apply until a normal business action rejects the retained path. Seat occupancy is live and performance-scoped. At a request boundary, unpaid orders expire and release their own held inventory; paid records remain. Reads are charged by returned work, and rejected mutations consume a write attempt. A successful finalize_order_to_tickets response is authoritative completion evidence because it reports the paid state and issued ticket IDs; get_order is only needed when that receipt is incomplete or a concrete current conflict must be resolved.'}

    def _persistent_event_ticketing_adapter_init(self, source_root=CASE_DIR / 'raw'):
        self._event_ticketing_adapter_init(source_root)
        self._state = MemoryState(fn__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._active_event_start = 0

    def _persistent_event_ticketing_adapter_snapshot(self):
        return {'schema': 'rescopebench-event-ticketing-stream-snapshot/v1', '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, 'activated_tasks': list(self._activated_tasks), 'applied_boundary_events': sorted(self._applied_boundary_events), 'active_event_start': self._active_event_start}

    def _persistent_event_ticketing_adapter_restore(self, snapshot):
        if snapshot.get('schema') != 'rescopebench-event-ticketing-stream-snapshot/v1':
            raise ValueError('unsupported persistent stream 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)
        self._activated_tasks = list(snapshot.get('activated_tasks') or [])
        self._applied_boundary_events = set(snapshot.get('applied_boundary_events') or [])
        self._active_event_start = int(snapshot.get('active_event_start') or 0)

    def _event_ticketing_adapter_init(self, source_root=CASE_DIR / 'raw'):
        self._logic = 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)