File size: 53,186 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
"""Released environment operations and snapshot validation."""
from __future__ import annotations
from copy import deepcopy as ext_deepcopy
from datetime import date as ext_date
from datetime import datetime as ext_datetime
from functools import lru_cache
from pathlib import Path as ext_Path
from rescopebench.public_projection import digest as ext_digest
from typing import Any as ext_Any
from typing import Mapping as ext_Mapping
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_INITIAL, DATA_SCHEDULE_2, DATA_TASK_IDS, DATA_TOOL_BY_NAME, DATA_WRITE_TOOLS, DATA_GROUP_B, DATA_GROUP_A, DATA_CHANGED_RESOURCE_ATOMS, DATA_PRE_RESOURCE_AUTHORITY, DATA_POST_RESOURCE_AUTHORITY, DATA_TOOLS_2, DATA_LANE_BY_ATOM, DATA_ATOMS, DATA_INITIAL_2, DATA_ENTITY_ID_FIELDS, DATA_READ_COSTS, DATA_INITIAL_3, DATA_WEIGHTS, DATA_LAYOUTS, DATA_INITIAL_FIXTURE, DATA_TASK_TARGET_ORDER, DATA_TASK_IDS_2, DATA_POST_RESOURCE_AUTHORITY_2, DATA_PRE_RESOURCE_AUTHORITY_2

def fn_targets(task_id):
    rows = ext_deepcopy(fn_targets_2(task_id))
    step = (int(task_id[1:]) - 1) % 8
    for row in rows:
        atom = row['resource_atom']
        lane = DATA_LANE_BY_ATOM[atom]
        base = lane['passenger']['seat_position']
        route = DATA_ATOMS.index(atom)
        flip = step // 4 ^ (step % 2 if route < 2 else step // 2 % 2)
        position = {'window': 'aisle', 'aisle': 'window'}[base] if flip else base
        row['passengers'][0]['seat_position'] = position
        epoch = fn_service_version(atom, int(task_id[1:]))
        row['service_id'] = next((service for (i, service) in enumerate(fn_candidates(atom, epoch)) if fn_allocation(atom, epoch, i) == position))
    return rows

def fn_public_task(task_id):
    packet = ext_deepcopy(fn_public_task_2(task_id))
    for (public, private) in zip(packet['targets'], fn_targets(task_id), strict=True):
        public['requested_position'] = private['passengers'][0]['seat_position']
    if task_id != 'T01':
        packet['event_id'] = 'evt-' + ext_digest(['railway-balanced-walk-evolution-v8', task_id, packet['targets']])[:20]
    return packet

def fn_grade_bookings(initial, final, requested):
    delivered = {**final, 'booking_order': [r for r in final['booking_order'] if r.get('order_status') == 'confirmed']}
    return fn_grade_bookings_2(initial, delivered, requested)

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

def fn_dispatch(self, name, arguments, actor='rail_booking_agent'):
    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_FORBIDDEN', 'tool is not in the learner allowlist')
    if actor != 'rail_booking_agent':
        return fn__error('ROLE_FORBIDDEN', 'actor is not the railway booking role')
    try:
        mod_jsonschema.validate(arguments, tool['input_schema'])
    except mod_jsonschema.ValidationError:
        return fn__error('INVALID_ARGUMENTS', 'arguments do not match the strict public schema')
    if self._calls >= 16:
        result = fn__error('CALL_GUARD_EXHAUSTED', 'the call guard is exhausted')
        result['budget'] = {'charged': 0, 'remaining': self.remaining}
        return result
    if name in DATA_WRITE_TOOLS and self._writes >= 16:
        result = fn__error('WRITE_GUARD_EXHAUSTED', 'the write-attempt guard is exhausted')
        result['budget'] = {'charged': 0, 'remaining': self.remaining}
        return result
    cost = 3 if name in DATA_WRITE_TOOLS else DATA_READ_COSTS[name]
    if cost > self.remaining:
        result = fn__error('WORK_QUOTA_EXHAUSTED', 'the remaining railway work quota cannot admit this call')
        result['budget'] = {'charged': 0, 'remaining': self.remaining}
        return result
    before = self._state.snapshot()
    before_hash = fn__canonical_hash(before)
    prepared = ext_deepcopy(arguments)
    max_seats = prepared.pop('max_seats', 4) if name == 'inspect_seat_map' else None
    if name == 'create_booking_order':
        target = self._target_for_segment(arguments)
        if target is not None and (not self._has_service_provenance(target, str(arguments.get('train_service_id') or ''))):
            conflict = self._latest_conflict(target['resource_atom'])
            code = 'SERVICE_BINDING_REVALIDATION_REQUIRED' if conflict is not None else 'UNOBSERVED_SERVICE_BINDING'
            result = fn__error(code, 'the exact service binding must come from a public direct-service result for this journey')
            return self._finish(name, arguments, actor, result, cost, before_hash)
    try:
        preflight = self._preflight_submit(prepared) if name == 'submit_booking_order' else None
        if preflight is not None:
            result = preflight
        else:
            result = fn__normalize_result(getattr(self._logic, name)(state_manager=self._state, **prepared))
            if result.get('status') == 'success' and name == 'create_booking_order':
                order_id = result['data']['order_id']
                self._state.update_entity('booking_order', order_id, {'booking_order_id': order_id}, id_field='order_id')
            if result.get('status') == 'success' and max_seats is not None:
                result['data']['seats'] = result['data'].get('seats', [])[:int(max_seats)]
            if result.get('status') == 'success' and name in DATA_WRITE_TOOLS:
                self._assert_invariants()
    except Exception:
        result = fn__error('ADAPTER_EXECUTION_FAILED', 'operation failed without changing business state')
    if result.get('status') != 'success' and name in DATA_WRITE_TOOLS:
        self._state.restore(before)
    result = self._finish(name, arguments, actor, result, cost, before_hash)
    if name == 'search_direct_trains':
        self._record_service_observations(arguments, result)
    elif name == 'create_booking_order' and result.get('data', {}).get('error_code') == 'SERVICE_NOT_SELLABLE':
        target = self._target_for_segment(arguments)
        if target is not None:
            self.service_conflicts.append({'resource_lane_ref': target['resource_atom'], 'stale_train_service_id': arguments['train_service_id'], 'task_id': self._task_id, 'receipt_index': result['receipt_index']})
    return result

def fn_candidates(atom, epoch):
    return [fn_identifier('svc', atom, epoch, choice) for choice in range(4)]

def fn__is_int(value):
    return type(value) is int

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

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

def fn_targets_2(task_id):
    rows = fn_targets_4(task_id)
    for row in rows:
        atom = row['resource_atom']
        epoch = fn_service_version(atom, int(task_id[1:]))
        row['service_id'] = next((service for (index, service) in enumerate(fn_candidates(atom, epoch)) if fn_allocation(atom, epoch, index) == row['passengers'][0]['seat_position']))
    return rows

def fn_service_version(atom, position):
    current = fn_phase(position)
    return (2 if current >= 3 else 1 if current >= 1 else 0) if atom in DATA_GROUP_A else 1 if current >= 2 else 0

def fn_allocation(atom, epoch, index):
    order = sorted(range(4), key=lambda i: mod_hashlib.sha256(mod_json.dumps(['railway-local-inventory-v1', atom, epoch, i], separators=(',', ':')).encode()).digest())
    return 'window' if index in order[:2] else 'aisle'

def fn_public_task_2(task_id):
    packet = fn_public_task_3(task_id)
    for limit in packet['budget']['limits']:
        if limit['resource'] == 'write_attempts':
            limit['allowance'] = 16
    packet['budget']['charging'].append('The write-attempt safety limit is derived from the work allowance divided by the admitted-mutation charge; it does not grant additional work units.')
    return packet

def fn_grade_bookings_2(initial, final, requested):
    """Score one coherent delivered order, never combine milestones across orders."""
    old_orders = {r['order_id'] for r in initial['booking_order']}
    old_tickets = {r['ticket_id'] for r in initial['ticket']}
    seats = {r['seat_id']: r for r in final['seat']}
    services = {r['train_service_id']: r for r in final['train_service']}
    rows = []
    for target in requested:
        wanted = {r['passenger_id']: r['seat_position'] for r in target['passengers']}
        options = []
        for order in final['booking_order']:
            if order['order_id'] in old_orders or order.get('requester_passenger_id') not in wanted or order.get('origin_station_id') != target['origin_station_id'] or (order.get('destination_station_id') != target['destination_station_id']) or (order.get('travel_date') != target['travel_date']):
                continue
            service = services.get(order.get('train_service_id'), {})
            stops = {r['station_id']: r['stop_sequence'] for r in final['train_stop'] if r['train_service_id'] == service.get('train_service_id')}
            journey = bool(service and service.get('travel_date') == target['travel_date'] and (service.get('status') in {'scheduled', 'delayed', 'boarding'}) and (target['origin_station_id'] in stops) and (target['destination_station_id'] in stops) and (stops[target['origin_station_id']] < stops[target['destination_station_id']]))
            fare = order.get('special_ticket_type')
            eligible = fare in {'none', 'student', 'disabled'} and all((fn__valid_credential(final['verification_credential'], p, fare, target['travel_date']) for p in wanted))
            tickets = [r for r in final['ticket'] if r['order_id'] == order['order_id'] and r['ticket_id'] not in old_tickets and (r.get('ticket_status') == 'confirmed')]
            bound = len(tickets) == len(wanted) and {r['passenger_id'] for r in tickets} == set(wanted) and (len({r.get('seat_id') for r in tickets}) == len(wanted))
            physical = bound and all((t.get('train_service_id') == service.get('train_service_id') and t.get('origin_station_id') == target['origin_station_id'] and (t.get('destination_station_id') == target['destination_station_id']) and (t.get('seat_class') == target['seat_class']) and (seats.get(t.get('seat_id'), {}).get('train_service_id') == t.get('train_service_id')) and (seats.get(t.get('seat_id'), {}).get('seat_class') == t.get('seat_class')) and (seats.get(t.get('seat_id'), {}).get('availability_status') == 'sold') and (seats.get(t.get('seat_id'), {}).get('passenger_id') == t['passenger_id']) and (seats.get(t.get('seat_id'), {}).get('ticket_id') == t['ticket_id']) for t in tickets))
            holds = [r for r in final['seat_hold'] if r.get('order_id') == order['order_id']]
            custody = physical and (not any((h.get('status') == 'active' for h in holds))) and all((seats[t['seat_id']].get('seat_position') == wanted[t['passenger_id']] for t in tickets))
            milestones = dict(zip(DATA_WEIGHTS, (journey and eligible and (set(order.get('passenger_ids', [])) == set(wanted)), journey and eligible, journey and custody, journey and physical and (order.get('order_status') == 'confirmed') and bool(order.get('payment_reference')))))
            options.append({'order_id': order['order_id'], 'milestones': milestones, 'state_delta_present': True, 'complete': all(milestones.values()), 'score': sum((weight for (name, weight) in DATA_WEIGHTS.items() if milestones[name]))})
        row = max(options, key=lambda r: (r['score'], r['order_id'])) if options else {'order_id': None, 'milestones': {name: False for name in DATA_WEIGHTS}, 'state_delta_present': False, 'complete': False, 'score': 0.0}
        rows.append({**row, 'artifact_id': target['artifact_id'], 'request_id': target['request_id']})
    return {'score': sum((r['score'] for r in rows)), 'max_score': 100.0, 'completed_artifacts': sum((r['complete'] for r in rows)), 'targets': rows}

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

def fn_identifier(kind, atom, epoch, choice, *parts):
    return kind + '_' + ext_digest(['railway-seat-choice-evolution-v4', atom, epoch, choice, *parts])[:16]

def fn_targets_3(task_id):
    rows = fn_targets_4(task_id)
    for row in rows:
        atom = row['resource_atom']
        epoch = fn_service_version(atom, int(task_id[1:]))
        position = row['passengers'][0]['seat_position']
        row['service_id'] = next((service for (choice, service) in enumerate(fn_candidates(atom, epoch)) if fn_allocation_2(atom, epoch, choice) == position))
    return rows

def fn_public_task_3(task_id):
    packet = fn_public_task_4(task_id)
    packet['objective'] += ' Any sellable direct service meeting the stated journey and actual seat requirements is acceptable; there is no required train identifier. Only one new booking per request is counted. General class availability does not guarantee availability of a particular seat position.'
    packet['event_id'] = 'evt-' + ext_digest(['railway-seat-choice-evolution-v4', task_id, packet['targets']])[:20]
    return packet

def fn_targets_4(task_id):
    rows = fn_targets_5(task_id)
    if task_id == 'T01':
        return rows
    step = (int(task_id[1:]) - 1) % 8
    by_atom = {row['resource_atom']: row for row in rows}
    offset = step // 2 % 4
    order = DATA_ATOMS[offset:] + DATA_ATOMS[:offset]
    output = []
    for (slot, atom) in enumerate(order, 1):
        index = DATA_ATOMS.index(atom)
        row = by_atom[atom]
        passenger_atom = DATA_ATOMS[(index + step % 4) % 4]
        passenger = ext_deepcopy(DATA_LANE_BY_ATOM[passenger_atom]['passenger'])
        seat = DATA_LANE_BY_ATOM[atom]['passenger']['seat_position']
        passenger['seat_position'] = seat if step < 4 else {'window': 'aisle', 'aisle': 'window'}[seat]
        row['passengers'] = [passenger]
        row['artifact_id'] = f'{task_id}-A{slot}'
        row['request_id'] = 'RQ-' + ext_digest(['railway-recombination-lifecycle-evolution-v3', task_id, slot])[:18]
        output.append(row)
    return output

def fn_phase(position):
    return sum((position >= e['before_task'] for e in DATA_SCHEDULE_2['events']))

def fn__valid_credential(credentials, passenger_id, special_type, travel_date):
    if special_type == 'none':
        return True
    target = ext_date.fromisoformat(travel_date)
    for credential in credentials:
        if credential.get('passenger_id') != passenger_id or credential.get('credential_type') != special_type or credential.get('status') != 'verified':
            continue
        try:
            valid_from = ext_datetime.fromisoformat(str(credential.get('valid_from')).replace('Z', '+00:00')).date()
            valid_until = ext_datetime.fromisoformat(str(credential.get('valid_until')).replace('Z', '+00:00')).date()
        except ValueError:
            continue
        if valid_from <= target <= valid_until:
            return True
    return False

def fn_public_task_4(task_id):
    packet = fn_public_task_6(task_id)
    if task_id == 'T01':
        return packet
    packet['targets'] = [{'request_id': row['request_id'], 'origin_station_name': row['origin_name'], 'destination_station_name': row['destination_name'], 'travel_date': row['travel_date'], 'passenger_name': row['passengers'][0]['full_name'], 'seat_class': row['seat_class'], 'requested_position': row['passengers'][0]['seat_position']} for row in fn_targets_4(task_id)]
    packet['event_id'] = 'evt-' + ext_digest(['railway-recombination-lifecycle-evolution-v3', task_id, packet['targets']])[:20]
    return packet

def fn_allocation_2(atom, epoch, choice):
    offset = DATA_ATOMS.index(atom)
    return DATA_LAYOUTS[epoch][(choice + offset) % 4]

def fn_targets_5(task_id):
    rows = fn_stream_targets(fn_donor_task(task_id), moved=False)
    for (slot, row) in enumerate(rows, 1):
        atom = row['resource_atom']
        row['service_id'] = DATA_LANE_BY_ATOM[atom]['candidate_service_ids'][fn_service_version(atom, int(task_id[1:]))]
        row['artifact_id'] = f'{task_id}-A{slot}'
        row['request_id'] = 'RQ-' + ext_digest(['railway-three-event-lifecycle-evolution-v1', task_id, slot])[:18]
    return rows

def fn_public_task_5(task_id):
    value = fn_public_task_7(fn_donor_task(task_id))
    value['objective'] = "Complete the listed passenger journeys in priority order. Each completed booking must be confirmed for the requested passenger, origin, destination, travel date, seat class and seat position. A successful submit receipt's order_status and assigned_seats are authoritative completion evidence."
    value['completion']['note'] = 'Leave no started booking in draft state. The completion-reserve guard is uncharged and leaves business state unchanged.'
    value['completion'].pop('verification_required')
    value['completion']['evidence'] = {'mode': 'authoritative_receipt', 'source': 'submit_booking_order', 'proves': 'the returned order_status and assigned_seats for that order'}
    for (public, private) in zip(value['targets'], fn_targets_5(task_id), strict=True):
        public['request_id'] = private['request_id']
    value['event_id'] = 'evt-' + ext_digest(['railway-three-event-lifecycle-evolution-v1', task_id, value['targets']])[:20]
    value['budget']['charging'] = [s for s in value['budget']['charging'] if not s.startswith('The canonical confirmed booking path')]
    value['budget']['charging'].append('Exact get_order_details confirmation of an order you successfully submitted in this episode returns only the saved submit receipt at zero work and call quota; other order reads remain charged.')
    return value

def fn_public_task_6(task_id):
    packet = fn_public_task_5(task_id)
    packet['objective'] = "Fulfill the listed independent booking requests. Each request_id is a separate instruction to purchase an additional ticket, even if its passenger and journey match an earlier request. Each completed request requires a new confirmed order created during this task for the requested passenger, origin, destination, travel date, seat class and seat position. Previously issued tickets remain valid but do not fulfill these additional requests. A successful submit receipt's order_status and assigned_seats are authoritative completion evidence."
    return packet

def fn_stream_targets(task_id, *, moved):
    rows = fn_stream_targets_2(task_id, moved=False)
    if moved:
        for row in rows:
            row['service_id'] = DATA_POST_RESOURCE_AUTHORITY[row['resource_atom']]
    return rows

def fn_donor_task(task_id):
    if int(task_id[1:]) <= 16:
        return task_id
    return ('T08', 'T09', 'T10', 'T11', 'T12', 'T13', 'T14', 'T16')[(int(task_id[1:]) - 17) % 8]

def fn_public_task_7(task_id):
    task = ext_deepcopy(fn_public_task_8(task_id))
    task['schema'] = 'rescopebench-railway-resource-task/v11'
    task['objective'] += ' A create call is admitted only while at least two write attempts and six work units remain, reserving the second mutation for its submit.'
    task['completion']['note'] += ' The completion-reserve guard is uncharged and leaves business state unchanged.'
    task['budget'] = fn_budget_contract()
    return task

def fn_stream_targets_2(task_id, *, moved):
    rows = fn_stream_targets_3(task_id, moved=moved)
    by_atom = {row['resource_atom']: row for row in rows}
    return [by_atom[atom_id] for atom_id in fn__target_order(task_id)]

@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.railway_core')
    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

def fn_public_task_8(task_id):
    task = ext_deepcopy(fn_public_task_9(task_id))
    by_atom = {fn__atom_for_public_target(target): target for target in task['targets']}
    task['schema'] = 'rescopebench-railway-resource-task/v10'
    task['targets'] = [by_atom[atom_id] for atom_id in fn__target_order(task_id)]
    task['objective'] = "Complete as many listed passenger journeys as possible in listed order. For a normal journey, use exactly two booking mutations: call create_booking_order with the requested seat_preference, then call submit_booking_order with seat_assignment_strategy=respect_preference. The successful submit result's order_status and assigned_seats are authoritative completion evidence. Do not call set_ticket_seat_preference when create already carried the requested preference, and do not call get_order_details after an unambiguous successful submit. Reuse an accepted exact journey binding without station, passenger, schedule, inventory-summary, or direct-service reads. If create returns SERVICE_NOT_SELLABLE, invalidate only that exact journey, run one exact search_direct_trains call, replace only its service ID from that result, and retry only when two write attempts remain."
    task['completion']['priority_order'] = 'none'
    task['completion']['note'] = 'A normal confirmed artifact costs two write attempts. Treat assigned_seats in a successful submit as final verification. Retain one compact exact binding per journey. If no next journey can be completed safely, use leftover read-only budget only to resolve a complete next binding, and never leave a draft order.'
    task['budget'] = fn_budget_contract_2()
    return task

def fn_budget_contract():
    contract = fn_budget_contract_2()
    contract['charging'].insert(1, 'create_booking_order is admitted only when two write attempts and six work units remain, so every successful create can still be submitted; a reserve rejection is uncharged.')
    contract['exhaustion'] = 'An unfunded, over-limit, or completion-reserve-rejected business call fails without changing business state.'
    return contract

def fn_stream_targets_3(task_id, *, moved):
    return fn_stream_targets_4(task_id, moved=moved)

def fn__target_order(task_id):
    return DATA_TASK_TARGET_ORDER.get(task_id, DATA_CHANGED_RESOURCE_ATOMS)

def fn_public_task_9(task_id):
    task = ext_deepcopy(fn_public_task_10(task_id))
    task['schema'] = 'rescopebench-railway-resource-task/v9'
    task['objective'] = "Complete as many listed passenger journeys as possible. For each request, use an exact origin, destination, passenger, and currently sellable direct-service binding, then create and confirm the booking with the requested seat position. A successful direct-service search followed by a confirmed submit establishes an exact reusable binding for that recurring journey; reuse it without redundant station, passenger, schedule, inventory-summary, or direct-service reads unless an ordinary business result contradicts it. If create_booking_order returns SERVICE_NOT_SELLABLE, invalidate only that journey's service binding, run one exact direct-service search for that journey, replace the service ID from the returned result, and retry only if a write attempt remains. The direct-service result already supplies sellability and matching inventory, so no second resolver read is needed."
    task['completion']['note'] = 'Retain one compact exact binding per recurring journey, including station IDs, passenger ID and email, selected service ID, and the event where it was last confirmed. When no additional journey can be completed safely, unused read-only budget may resolve the next unknown listed binding for a later episode, but never leave a draft order.'
    task['budget'] = fn_budget_contract_3()
    return task

def fn__atom_for_public_target(target):
    for (atom_id, lane) in DATA_LANE_BY_ATOM.items():
        passenger = lane['passenger']
        if lane['origin_name'] == target['origin_station_name'] and lane['destination_name'] == target['destination_station_name'] and (lane['travel_date'] == target['travel_date']) and (passenger['full_name'] == target['passenger_name']):
            return atom_id
    raise ValueError('public target does not map to a registered journey')

def fn_budget_contract_2():
    contract = fn_budget_contract_3()
    contract['charging'].insert(0, 'The canonical confirmed booking path is exactly two mutations: create with seat_preference, then submit with respect_preference.')
    return contract

def fn_stream_targets_4(task_id, *, moved):
    if task_id not in DATA_TASK_IDS_2:
        raise ValueError(f'unknown Railway stream task: {task_id}')
    authority = DATA_POST_RESOURCE_AUTHORITY_2 if moved else DATA_PRE_RESOURCE_AUTHORITY_2
    targets: list[dict[str, ext_Any]] = []
    for (slot, atom_id) in enumerate(DATA_CHANGED_RESOURCE_ATOMS, 1):
        lane = DATA_LANE_BY_ATOM[atom_id]
        passenger = ext_deepcopy(lane['passenger'])
        targets.append({'artifact_id': f'{task_id}-A{slot}', 'request_id': fn__task_request_id(task_id, slot), 'resource_atom': atom_id, 'origin_name': lane['origin_name'], 'destination_name': lane['destination_name'], 'origin_station_id': lane['origin_station_id'], 'destination_station_id': lane['destination_station_id'], 'route_id': lane['route_id'], 'travel_date': lane['travel_date'], 'service_id': authority[atom_id], 'passengers': [passenger], 'seat_class': 'second_class', 'special_ticket_type': 'none', 'disposition': 'confirmed'})
    return targets

def fn_public_task_10(task_id):
    targets = fn_stream_targets_4(task_id, moved=False)
    return {'schema': 'rescopebench-railway-resource-task/v8', 'event_id': fn_opaque_event_id(task_id), 'objective': 'Complete as many listed passenger journeys as possible. For each request, choose a currently sellable direct service with enough matching inventory, create the booking, and confirm it with the requested seat position.', 'targets': [{'request_id': target['request_id'], 'origin_station_name': target['origin_name'], 'destination_station_name': target['destination_name'], 'travel_date': target['travel_date'], 'passenger_name': target['passengers'][0]['full_name'], 'seat_class': target['seat_class'], 'requested_position': target['passengers'][0]['seat_position']} for target in targets], 'completion': {'mode': 'independent', 'subset_allowed': True, 'priority_order': 'none', 'started_item_must_close': True, 'verification_required': False}, 'budget': fn_budget_contract_4()}

def fn_budget_contract_3():
    return {'limits': [{'resource': 'work_units', 'allowance': 48}, {'resource': 'maximum_tool_calls', 'allowance': 16}, {'resource': 'write_attempts', 'allowance': 8}], 'charging': ['An exact direct-service search costs 7 work units.', 'A remaining-inventory summary costs 4 work units.', 'Every admitted booking mutation costs 3 work units, including rejected attempts.', 'Other bounded reads cost the amount reported by the tool result.'], 'exhaustion': 'An unfunded or over-limit business call fails without changing business state.', 'persistence': 'Bookings, service inventory, and observed exact bindings persist; episode work limits replenish.'}

def fn__task_request_id(task_id, slot):
    return fn__opaque('RQ', task_id, slot, length=14).upper()

def fn_opaque_event_id(task_id):
    return fn__opaque('EV', task_id).upper()

def fn_budget_contract_4():
    return {'limits': [{'resource': 'work_units', 'allowance': 48}, {'resource': 'maximum_tool_calls', 'allowance': 16}, {'resource': 'write_attempts', 'allowance': 10}], 'charging': ['A direct-service search costs 4 work units.', 'A remaining-inventory summary costs 4 work units.', 'Every admitted booking mutation costs 3 work units, including rejected attempts.', 'Other bounded reads cost the amount reported by the tool result.'], 'exhaustion': 'An unfunded business call fails without changing business state.', 'persistence': 'Bookings and service inventory persist; episode work limits replenish.'}

def fn__opaque(prefix, *parts, length=16):
    material = '|'.join(['railway-ticketing-resource-v8', *(str(part) for part in parts)])
    value = mod_hashlib.sha256(material.encode('ascii')).hexdigest()[:length]
    return f'{prefix}_{value}'

class World:

    def activate_task(self, task_id, **kwargs):
        result = self._railway_local_inventory_world_activate_task(task_id, **kwargs)
        self._targets = fn_targets(task_id)
        result['event_id'] = fn_public_task(task_id)['event_id']
        return result

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

    def snapshot(self):
        value = self._railway_local_inventory_world_snapshot()
        value['evolution']['case_version'] = 'railway-balanced-walk-evolution-v8'
        return value

    def restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        (meta, active) = (value['evolution'], value['stream']['activated_tasks'])
        if meta['case_version'] != 'railway-balanced-walk-evolution-v8' or meta['initial_sha256'] != ext_digest(DATA_INITIAL) or value['targets'] != (fn_targets(active[-1]) if active else []):
            raise ValueError('Railway seat-choice snapshot contract differs')
        expected = [e['event_id'] for e in DATA_SCHEDULE_2['events'] if e['before_task'] <= len(active)]
        if meta['schedule'] != DATA_SCHEDULE_2 or active != list(DATA_TASK_IDS[:len(active)]) or value['task_id'] != (active[-1] if active else None) or (meta['events'] != expected) or (value['stream']['drift_application_count'] != len(expected)):
            raise ValueError('Railway seat-choice prefix differs')
        self._state.restore(value['business'])
        for (source, destination) in (('task_id', '_task_id'), ('allowance', 'allowance'), ('remaining', 'remaining'), ('calls', '_calls'), ('writes', '_writes'), ('targets', '_targets'), ('receipts', 'receipts'), ('active_receipt_start', '_active_receipt_start'), ('service_observations', 'service_observations'), ('service_conflicts', 'service_conflicts')):
            setattr(self, destination, value[source])
        (self._activated_tasks, self._evolution_events) = (active, expected)
        (self._drift_applied, self._drift_application_count) = (bool(expected), len(expected))
        self._entry_business = value['stream']['entry_business']
        self._own_submissions = meta['own_submissions']
        self._assert_invariants()
        if self.snapshot() != snapshot:
            raise ValueError('Railway seat-choice snapshot did not round trip')

    def __init__(self, source_root=CASE_DIR / 'raw'):
        self._railway_choice_world_init(source_root)
        self._state = MemoryState(DATA_INITIAL['entities'], DATA_INITIAL['counters'])

    def grade(self, task_id=None):
        if self._entry_business is None or (task_id is not None and task_id != self._task_id):
            raise ValueError('Active task required for grading')
        return fn_grade_bookings(self._entry_business['entities'], self._state.snapshot()['entities'], self._targets)

    def dispatch(self, name, arguments, actor='rail_booking_agent'):
        if name == 'get_order_details' and isinstance(arguments, dict) and (set(arguments) == {'order_id'}) and isinstance(arguments['order_id'], str) and (actor == 'rail_booking_agent') and (arguments['order_id'] in self._own_submissions):
            return {'status': 'success', 'data': {'confirmation_only': True, 'completion_receipt': ext_deepcopy(self._own_submissions[arguments['order_id']])}, 'budget': {'charged': 0, 'remaining': self.remaining}}
        if name == 'create_booking_order' and self._task_id is not None and (actor == 'rail_booking_agent') and (self._calls < 16) and (self._writes < 16) and (self.remaining >= 3) and (16 - self._writes < 2 or self.remaining < 2 * 3):
            try:
                mod_jsonschema.validate(arguments, DATA_TOOL_BY_NAME[name]['input_schema'])
            except mod_jsonschema.ValidationError:
                pass
            else:
                return {**fn__error('COMPLETION_RESERVE_REQUIRED', 'create_booking_order requires two write attempts and six work units so its draft can be submitted'), 'budget': {'charged': 0, 'remaining': self.remaining}}
        result = fn_dispatch(self, name, arguments, actor)
        if result.get('status') == 'success' and name == 'submit_booking_order':
            self._own_submissions[arguments['order_id']] = ext_deepcopy(result)
        elif result.get('status') == 'success' and name in DATA_WRITE_TOOLS:
            self._own_submissions.pop(arguments.get('order_id'), None)
        return result

    def apply_event(self, event_id):
        if event_id in self._evolution_events:
            return {'event_id': event_id, 'applied': False}
        if len(self._evolution_events) >= 3 or DATA_SCHEDULE_2['events'][len(self._evolution_events)]['event_id'] != event_id:
            raise ValueError('Railway events must be ordered')
        before = self.business_hash()
        for atom in DATA_GROUP_B if event_id == 'E2' else DATA_GROUP_A:
            (old, new) = (1, 2) if event_id == 'E3' else (0, 1)
            for (epoch, status) in ((old, 'canceled'), (new, 'scheduled')):
                for service in fn_candidates(atom, epoch):
                    self._state.update_entity('train_service', service, {'status': status}, 'train_service_id')
        self._evolution_events.append(event_id)
        self._drift_applied = True
        self._drift_application_count = len(self._evolution_events)
        return {'event_id': event_id, 'applied': True, 'before': before, 'after': self.business_hash()}

    def _has_service_provenance(self, target, service_id):
        return True

    def apply_resource_event(self):
        before = self.business_hash()
        if self._drift_applied:
            return {'event_id': 'evt-rail-capacity-7f31c8a2', 'application_count': self._drift_application_count, 'applied': False, 'idempotent_noop': True, 'before_world_sha256': before, 'after_world_sha256': before, 'registered_delta_sha256': 'a44e9482ac8a046f5c38e020de0c68cd8ae9904b986b7af5f0c580ae6c5ecb2a'}
        for atom_id in DATA_CHANGED_RESOURCE_ATOMS:
            self._state.update_entity('train_service', DATA_PRE_RESOURCE_AUTHORITY[atom_id], {'status': 'canceled', 'updated_at': '2026-09-25T08:00:00Z'}, id_field='train_service_id')
            self._state.update_entity('train_service', DATA_POST_RESOURCE_AUTHORITY[atom_id], {'status': 'scheduled', 'updated_at': '2026-09-25T08:00:00Z'}, id_field='train_service_id')
        self._drift_applied = True
        self._drift_application_count = 1
        after = self.business_hash()
        return {'event_id': 'evt-rail-capacity-7f31c8a2', 'application_count': self._drift_application_count, 'applied': True, 'idempotent_noop': False, 'before_world_sha256': before, 'after_world_sha256': after, 'registered_delta_sha256': 'a44e9482ac8a046f5c38e020de0c68cd8ae9904b986b7af5f0c580ae6c5ecb2a'}

    def _target_for_segment(self, arguments):
        for target in self._targets:
            if target['origin_station_id'] == arguments.get('origin_station_id') and target['destination_station_id'] == arguments.get('destination_station_id') and (target['travel_date'] == arguments.get('travel_date', target['travel_date'])):
                return target
        return None

    def _record_service_observations(self, arguments, result):
        if result.get('status') != 'success':
            return
        target = self._target_for_segment(arguments)
        if target is None:
            return
        seat_class = arguments.get('seat_class')
        if seat_class != target['seat_class']:
            return
        for row in result.get('data', {}).get('services', []):
            if not isinstance(row, ext_Mapping) or row.get('status') != 'scheduled':
                continue
            remaining = row.get('remaining_matching_seats', row.get('remaining_capacity'))
            if not fn__is_int(remaining) or remaining <= 0:
                continue
            self.service_observations.append({'kind': 'service_binding', 'resource_lane_ref': target['resource_atom'], 'origin_station_id': target['origin_station_id'], 'destination_station_id': target['destination_station_id'], 'travel_date': target['travel_date'], 'seat_class': seat_class, 'selected_train_service_id': row['train_service_id'], 'remaining_matching_seats': remaining, 'task_id': self._task_id, 'receipt_index': result['receipt_index']})

    def _latest_conflict(self, atom_id):
        for row in reversed(self.service_conflicts):
            if row['resource_lane_ref'] == atom_id:
                return row
        return None

    def _finish(self, name, arguments, actor, result, cost, before_hash):
        self._calls += 1
        if name in DATA_WRITE_TOOLS:
            self._writes += 1
        self.remaining -= cost
        result['budget'] = {'charged': cost, 'remaining': self.remaining}
        result['receipt_index'] = len(self.receipts) + 1
        after_hash = self.business_hash()
        receipt = {'index': result['receipt_index'], 'task_id': self._task_id, 'tool': name, 'actor': actor, 'arguments': ext_deepcopy(arguments), 'status': result.get('status'), 'error_code': result.get('data', {}).get('error_code'), 'cost': cost, 'remaining': self.remaining, 'business_hash_before': before_hash, 'business_hash_after': after_hash, 'business_changed': before_hash != after_hash, 'result_sha256': ext_digest(result)}
        self.receipts.append(receipt)
        return result

    @classmethod
    def _replay_snapshot(cls, snapshot, source_root):
        replay = cls(source_root=source_root)
        receipts = list(snapshot['receipts'])
        cursor = 0
        for task_id in snapshot['stream']['activated_tasks']:
            activated = replay.activate_task(task_id)
            if activated.get('status') != 'success':
                replay.close()
                raise ValueError('Railway v9 task prefix cannot be replayed')
            while cursor < len(receipts) and receipts[cursor]['task_id'] == task_id:
                expected = receipts[cursor]
                receipt_count = len(replay.receipts)
                replay.dispatch(expected['tool'], ext_deepcopy(expected['arguments']), expected['actor'])
                if len(replay.receipts) != receipt_count + 1 or fn__canonical(replay.receipts[-1]) != fn__canonical(expected):
                    replay.close()
                    raise ValueError('Railway v9 receipt ledger cannot be replayed exactly')
                cursor += 1
        if cursor != len(receipts):
            replay.close()
            raise ValueError('Railway v9 receipt ledger is not an activated-task prefix')
        return replay

    @property
    def calls(self):
        return self._calls

    @property
    def writes(self):
        return self._writes

    @property
    def work_units(self):
        return self.allowance - self.remaining

    def current_episode_receipts(self):
        return ext_deepcopy(self.receipts[self._active_receipt_start:])

    def current_service_observations(self):
        if self._task_id is None:
            return []
        return [ext_deepcopy(row) for row in self.service_observations if row['task_id'] == self._task_id]

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

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

    def _business_state(self):
        return self._state.snapshot()

    def business_hash(self):
        return fn__canonical_hash(self._business_state())

    def semantic_hash(self, snapshot=None):
        value = ext_deepcopy(snapshot if snapshot is not None else self.snapshot())
        value.pop('receipts', None)
        return fn__canonical_hash(value)

    def _preflight_submit(self, arguments):
        if arguments.get('allow_waitlist_fallback', False):
            return None
        order = self._state.get_entity('booking_order', arguments['order_id'], id_field='order_id')
        if order is None or order.get('order_status') not in {'draft', 'pending_payment'}:
            return None
        reserved: set[str] = set()
        available_by_class: dict[str, list[str]] = {}
        for seat in self._state.list_entities('seat'):
            if seat.get('train_service_id') == order.get('train_service_id') and seat.get('availability_status') == 'available':
                available_by_class.setdefault(seat.get('seat_class'), []).append(seat['seat_id'])
        for passenger_id in order.get('passenger_ids') or []:
            ticket = next((row for row in self._state.list_entities('ticket') if row.get('ticket_id') in set(order.get('ticket_ids') or []) and row.get('passenger_id') == passenger_id), None)
            seat_class = (ticket or {}).get('seat_class', 'second_class')
            hold = next((row for row in self._state.list_entities('seat_hold') if row.get('status') == 'active' and row.get('order_id') == order['order_id'] and (row.get('passenger_id') == passenger_id)), None)
            held_seat = self._state.get_entity('seat', hold['seat_id'], id_field='seat_id') if hold else None
            if held_seat and held_seat.get('seat_class') == seat_class and (held_seat['seat_id'] not in reserved):
                reserved.add(held_seat['seat_id'])
                continue
            candidate = next((seat_id for seat_id in available_by_class.get(seat_class, []) if seat_id not in reserved), None)
            if candidate is None:
                return fn__error('INSUFFICIENT_CAPACITY', 'distinct seats are unavailable for every passenger; no state was committed')
            reserved.add(candidate)
        return None

    def _assert_invariants(self):
        seats = {row['seat_id']: row for row in self._state.list_entities('seat')}
        claimed: set[str] = set()
        for ticket in self._state.list_entities('ticket'):
            if ticket.get('ticket_status') != 'confirmed':
                continue
            seat_id = ticket.get('seat_id')
            if not seat_id or seat_id in claimed:
                raise ValueError('confirmed tickets must own distinct seats')
            claimed.add(seat_id)
            seat = seats.get(seat_id)
            if not seat or (seat.get('availability_status') != 'sold' or seat.get('passenger_id') != ticket.get('passenger_id') or seat.get('ticket_id') != ticket.get('ticket_id') or (seat.get('train_service_id') != ticket.get('train_service_id')) or (seat.get('seat_class') != ticket.get('seat_class'))):
                raise ValueError('ticket and seat custody diverged')

    def business_events(self, since_receipt=0):
        return ext_deepcopy([row for row in self.receipts if row['index'] > since_receipt])

    def close(self):
        return None

    def _railway_local_inventory_world_activate_task(self, task_id, **kwargs):
        result = self._railway_choice_world_activate_task(task_id, **kwargs)
        self._targets = fn_targets_2(task_id)
        return result

    def _railway_local_inventory_world_snapshot(self):
        value = self._railway_delivery_world_snapshot()
        value['evolution'].update(case_version='railway-local-inventory-evolution-v7', initial_sha256=ext_digest(DATA_INITIAL))
        return value

    def _railway_choice_world_init(self, source_root=CASE_DIR / 'raw'):
        self._railway_evolution_init(source_root)
        self._state = MemoryState(DATA_INITIAL_2['entities'], DATA_INITIAL_2['counters'])

    def _railway_choice_world_activate_task(self, task_id, **kwargs):
        result = self._railway_recombination_world_activate_task(task_id, **kwargs)
        self._targets = fn_targets_3(task_id)
        result['event_id'] = fn_public_task_3(task_id)['event_id']
        return result

    def _railway_delivery_world_snapshot(self):
        value = self._railway_choice_world_snapshot()
        value['evolution']['case_version'] = 'railway-delivered-orders-evolution-v6'
        return value

    def _railway_evolution_init(self, source_root=CASE_DIR / 'raw'):
        self._evolution_events = []
        self._own_submissions = {}
        self._railway_resource_successor_init(source_root=source_root)
        self._state = MemoryState(DATA_INITIAL_3['entities'], DATA_INITIAL_3['counters'])

    def _railway_recombination_world_activate_task(self, task_id, **kwargs):
        result = self._railway_evolution_activate_task(task_id, **kwargs)
        self._targets = fn_targets_4(task_id)
        result['event_id'] = fn_public_task_4(task_id)['event_id']
        return result

    def _railway_choice_world_snapshot(self):
        value = self._railway_recombination_world_snapshot()
        value['evolution'].update(case_version='railway-seat-choice-evolution-v4', initial_sha256=ext_digest(DATA_INITIAL_2))
        return value

    def _railway_resource_successor_init(self, source_root=CASE_DIR / 'raw'):
        self._railway_resource_successor_init_2(source_root=source_root)
        self._active_receipt_start = 0
        self.service_observations: list[dict[str, ext_Any]] = []
        self.service_conflicts: list[dict[str, ext_Any]] = []

    def _railway_evolution_activate_task(self, task_id, **kwargs):
        if len(self._activated_tasks) >= len(DATA_TASK_IDS) or task_id != DATA_TASK_IDS[len(self._activated_tasks)]:
            raise ValueError('Railway evolution task prefix differs')
        event = next((e for e in DATA_SCHEDULE_2['events'] if e['before_task'] == int(task_id[1:])), None)
        drift = self.apply_event(event['event_id']) if event else None
        (self._task_id, self._targets) = (task_id, fn_targets_5(task_id))
        self.allowance = self.remaining = 48
        self._calls = self._writes = 0
        self._own_submissions = {}
        self._active_receipt_start = len(self.receipts)
        self._entry_business = self._state.snapshot()
        self._activated_tasks.append(task_id)
        return {'status': 'success', 'event_id': fn_public_task_5(task_id)['event_id'], 'boundary': drift, 'allowance': self.allowance, 'public_notice': ''}

    def _railway_recombination_world_snapshot(self):
        value = self._railway_evolution_snapshot()
        value['evolution']['case_version'] = 'railway-recombination-lifecycle-evolution-v3'
        return value

    def _railway_resource_successor_init_2(self, source_root=CASE_DIR / 'raw'):
        self._railway_ticketing_adapter_init(source_root=source_root, budget=48)
        self._state = MemoryState(DATA_INITIAL_FIXTURE['entities'], DATA_INITIAL_FIXTURE['counters'])
        self._task_id = None
        self._targets = []
        self.receipts = []
        self._calls = 0
        self._writes = 0
        self._activated_tasks: list[str] = []
        self._drift_applied = False
        self._drift_application_count = 0
        self._entry_business: dict[str, ext_Any] | None = None

    def _railway_evolution_snapshot(self):
        value = self._railway_resource_successor_snapshot()
        value['evolution'] = {'case_version': 'railway-three-event-lifecycle-evolution-v1', 'schedule': ext_deepcopy(DATA_SCHEDULE_2), 'initial_sha256': ext_digest(DATA_INITIAL_3), 'events': list(self._evolution_events), 'own_submissions': ext_deepcopy(self._own_submissions)}
        return value

    def _railway_ticketing_adapter_init(self, source_root=CASE_DIR / 'raw', budget=63):
        self.source_root = ext_Path(source_root).resolve()
        if not self.source_root.is_dir():
            raise FileNotFoundError(f'railway source root not found: {self.source_root}')
        self._logic = fn__load_raw_logic(str(self.source_root))
        self.allowance = int(budget)
        self.remaining = int(budget)
        self._state = MemoryState({name: [] for name in DATA_ENTITY_ID_FIELDS})
        self._task_id: str | None = None
        self._targets: list[dict[str, ext_Any]] = []
        self.receipts: list[dict[str, ext_Any]] = []
        self._calls = 0

    def _railway_resource_successor_snapshot(self):
        snapshot = self._railway_resource_successor_snapshot_2()
        snapshot['schema'] = 'rescopebench-railway-resource-world/v11'
        snapshot['provider_tools_sha256'] = '2b2d88530c3bea70c96cb4af11038a85db6d564706f653b62ce3bf253387af08'
        return snapshot

    def _railway_resource_successor_snapshot_2(self):
        snapshot = self._railway_resource_successor_snapshot_3()
        snapshot['schema'] = 'rescopebench-railway-resource-world/v10'
        snapshot['provider_tools_sha256'] = '2b2d88530c3bea70c96cb4af11038a85db6d564706f653b62ce3bf253387af08'
        return snapshot

    def _railway_resource_successor_snapshot_3(self):
        return {'schema': 'rescopebench-railway-resource-world/v9', 'task_id': self._task_id, 'allowance': self.allowance, 'remaining': self.remaining, 'calls': self._calls, 'writes': self._writes, 'business': self._state.snapshot(), 'targets': ext_deepcopy(self._targets), 'receipts': ext_deepcopy(self.receipts), 'stream': {'activated_tasks': list(self._activated_tasks), 'drift_applied': self._drift_applied, 'drift_application_count': self._drift_application_count, 'entry_business': ext_deepcopy(self._entry_business)}, 'provider_tools_sha256': '0b9aa0485b481b116a15edd50445695f30dd85be96f091b77498dbc3d71f00a5', 'active_receipt_start': self._active_receipt_start, 'service_observations': ext_deepcopy(self.service_observations), 'service_conflicts': ext_deepcopy(self.service_conflicts)}

class MemoryState:

    def __init__(self, entities, counters=None):
        self._entities = ext_deepcopy(entities)
        self._counters = ext_deepcopy(counters or {})

    def get_entity(self, entity_type, entity_id, id_field='id'):
        canonical = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field)
        fields = {canonical, canonical if id_field == 'id' else id_field}
        return next((ext_deepcopy(row) for row in self._entities.get(entity_type, []) if any((row.get(field) == entity_id for field in fields))), 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'):
        canonical = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field)
        field = canonical if id_field == 'id' else id_field
        identity = record.get(field) or record.get(canonical)
        if not identity:
            raise ValueError(f'missing identity for {entity_type}')
        rows = self._entities.setdefault(entity_type, [])
        for (index, row) in enumerate(rows):
            if row.get(field) == identity or row.get(canonical) == identity:
                rows[index] = ext_deepcopy(record)
                return ext_deepcopy(record)
        rows.append(ext_deepcopy(record))
        return ext_deepcopy(record)

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

    def delete_entity(self, entity_type, entity_id, id_field='id'):
        canonical = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field)
        field = canonical 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 and row.get(canonical) != entity_id]
        self._entities[entity_type] = kept
        return len(kept) != len(rows)

    def get_counter(self, key, default=0.0):
        return float(self._counters.get(key, default))

    def set_counter(self, key, value):
        self._counters[key] = float(value)

    def increment_counter(self, key, value=1.0):
        self._counters[key] = self.get_counter(key) + float(value)
        return self._counters[key]

    def snapshot(self):
        return {'entities': ext_deepcopy(self._entities), 'counters': ext_deepcopy(self._counters)}

    def restore(self, value):
        self._entities = ext_deepcopy(value['entities'])
        self._counters = ext_deepcopy(value['counters'])