File size: 60,473 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
"""Released environment operations and snapshot validation."""
from __future__ import annotations
from contextlib import contextmanager
from copy import deepcopy as ext_deepcopy
from pathlib import Path as ext_Path
from rescopebench.raw_module_isolation import load_isolated_modules as ext_load_isolated_modules
import copy as mod_copy
import hashlib as mod_hashlib
import json as mod_json
from .spec import CASE_DIR, DATA_TASK_IDS, DATA_CHANGED_AUTHORITY_ATOMS, DATA_CURRENT_RESPONSIBLE_AGENCY, DATA_POLICY_ROWS, DATA__STREAM_INCIDENT_IDS, DATA__STREAM_RESOURCE_IDS, DATA__STREAM_ORDER_IDS, DATA_SEVERITIES, DATA_TASK_BLUEPRINT, DATA__X, DATA_STRUCTURE_BY_ID, DATA_RULE_BY_ID, DATA_INCIDENT_TYPES, DATA_AUTHORITY_ATOM_BY_STRUCTURE, DATA_PRE_RESPONSIBLE_AGENCY, DATA__CANDIDATES_BY_STRUCTURE, DATA_RESPONSIBILITY_DOMAIN_BY_STRUCTURE, DATA__RESOURCE_ID_BY_BINDING, DATA_AGENCY_BY_TYPE, DATA_SCHEDULE_2, DATA_TASK_BLUEPRINT_2, DATA_CHANGED_AUTHORITY_ATOMS_2, DATA_PROVIDER_TOOLS, DATA_ALLOWED_TOOLS, DATA_CUSTOM_COSTS, DATA_VISIBLE_TOOL_NAMES, DATA_RAW_LIST_TOOLS, DATA_RAW_DETAIL_TOOLS, DATA_WRITE_COSTS, DATA_VISIBLE_TOOL_NAMES_2, DATA_TOOL_SCHEMAS, DATA_PROVIDER_TOOLS_2

def fn_scheduled_orders(task_id):
    if task_id not in DATA_TASK_IDS:
        raise ValueError(f'unknown stream task: {task_id}')
    task_position = int(task_id[1:])
    rows = []
    for (position, atom_id) in enumerate(DATA_TASK_BLUEPRINT[task_id], 1):
        (slot, structure_id, rule_id) = DATA__X[atom_id]
        structure = DATA_STRUCTURE_BY_ID[structure_id]
        rule = DATA_RULE_BY_ID[rule_id]
        if structure['mission_class'] != rule['mission_class']:
            raise ValueError(f'incompatible v7 atom: {atom_id}')
        identity = f'{task_id}|{position}|{slot}|{structure_id}|{rule_id}'
        request_code = fn__opaque('ER', identity, 10)
        priority = DATA_INCIDENT_TYPES.index(rule['incident_type']) + 1
        atom = DATA_AUTHORITY_ATOM_BY_STRUCTURE[structure_id]
        row = {'request_code': request_code, 'order_id': fn__opaque('dispatch-order', identity), 'roster_id': fn__opaque('dispatch-roster', identity), 'task_id': task_id, 'slot': slot, 'structure_atom': structure_id, 'rule_atom': rule_id, 'incident_id': fn__opaque('incident', identity), 'incident_type': rule['incident_type'], 'mission_class': rule['mission_class'], 'required_capability': structure['capability'], 'mission': f"{structure['mission_class']} support from {structure['sector']}", 'lead_agency_id': DATA_PRE_RESPONSIBLE_AGENCY[atom], 'priority': priority, 'dispatch_priority': 'routine' if priority == 1 else 'urgent' if priority < 4 else 'life_safety', 'reported_at': f'2026-07-{task_position + 1:02d}T{position + 4:02d}:00:00Z', 'title': f"{rule['incident_type'].replace('_', ' ').title()} response {request_code}", 'affected_area': f"{structure['sector']} service area", 'candidates': mod_copy.deepcopy(DATA__CANDIDATES_BY_STRUCTURE[structure_id]), 'authorized_owner_type': rule['authorized_owner_type'], 'responsibility_domain': DATA_RESPONSIBILITY_DOMAIN_BY_STRUCTURE[structure_id]}
        for candidate in row['candidates']:
            candidate['resource_id'] = DATA__RESOURCE_ID_BY_BINDING[structure_id, candidate['owning_agency_type']]
            candidate['owning_agency_id'] = DATA_AGENCY_BY_TYPE[candidate['owning_agency_type']]
            candidate['status'] = 'available'
            candidate['current_incident_id'] = None
        rows.append(row)
    return tuple(rows)

def fn__digest(value):
    return mod_hashlib.sha256(fn__canonical_2(value).encode('utf-8')).hexdigest()

def fn_authority_atom(order):
    return DATA_AUTHORITY_ATOM_BY_STRUCTURE[order['structure_atom']]

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

def fn__opaque(prefix, value, length=12):
    value_hash = mod_hashlib.sha256(f"{'emergency-response-permission-v7'}|{value}".encode('ascii')).hexdigest()
    return f'{prefix}-{value_hash[:length].upper()}'

def fn_scheduled_orders_2(task_id):
    if task_id not in DATA_TASK_IDS:
        raise ValueError(f'unknown stream task: {task_id}')
    task_position = int(task_id[1:])
    rows = []
    for (position, atom_id) in enumerate(DATA_TASK_BLUEPRINT_2[task_id], 1):
        (slot, structure_id, rule_id) = DATA__X[atom_id]
        structure = DATA_STRUCTURE_BY_ID[structure_id]
        rule = DATA_RULE_BY_ID[rule_id]
        if structure['mission_class'] != rule['mission_class']:
            raise ValueError(f'incompatible v7 atom: {atom_id}')
        identity = f'{task_id}|{position}|{slot}|{structure_id}|{rule_id}'
        request_code = fn__opaque('ER', identity, 10)
        priority = DATA_INCIDENT_TYPES.index(rule['incident_type']) + 1
        atom = DATA_AUTHORITY_ATOM_BY_STRUCTURE[structure_id]
        row = {'request_code': request_code, 'order_id': fn__opaque('dispatch-order', identity), 'roster_id': fn__opaque('dispatch-roster', identity), 'task_id': task_id, 'slot': slot, 'structure_atom': structure_id, 'rule_atom': rule_id, 'incident_id': fn__opaque('incident', identity), 'incident_type': rule['incident_type'], 'mission_class': rule['mission_class'], 'required_capability': structure['capability'], 'mission': f"{structure['mission_class']} support from {structure['sector']}", 'lead_agency_id': DATA_PRE_RESPONSIBLE_AGENCY[atom], 'priority': priority, 'dispatch_priority': 'routine' if priority == 1 else 'urgent' if priority < 4 else 'life_safety', 'reported_at': f'2026-07-{task_position + 1:02d}T{position + 4:02d}:00:00Z', 'title': f"{rule['incident_type'].replace('_', ' ').title()} response {request_code}", 'affected_area': f"{structure['sector']} service area", 'candidates': mod_copy.deepcopy(DATA__CANDIDATES_BY_STRUCTURE[structure_id]), 'authorized_owner_type': rule['authorized_owner_type'], 'responsibility_domain': DATA_RESPONSIBILITY_DOMAIN_BY_STRUCTURE[structure_id]}
        for candidate in row['candidates']:
            candidate['resource_id'] = DATA__RESOURCE_ID_BY_BINDING[structure_id, candidate['owning_agency_type']]
            candidate['owning_agency_id'] = DATA_AGENCY_BY_TYPE[candidate['owning_agency_type']]
            candidate['status'] = 'available'
            candidate['current_incident_id'] = None
        rows.append(row)
    return tuple(rows)

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

def fn__validate_arguments(tool, arguments):
    if not isinstance(arguments, dict):
        return 'arguments must be an object'
    schema = DATA_TOOL_SCHEMAS[tool]
    properties = schema['properties']
    unknown = sorted(set(arguments) - set(properties))
    if unknown:
        return f"unsupported argument(s): {', '.join(unknown)}"
    missing = [name for name in schema.get('required', []) if name not in arguments]
    if missing:
        return f"missing required argument(s): {', '.join(missing)}"
    for (name, value) in arguments.items():
        field = properties[name]
        if not fn__matches_type(value, field['type']):
            return f"{name} must be {field['type']}"
        if 'enum' in field and value not in field['enum']:
            return f"{name} must be one of: {', '.join(field['enum'])}"
        if 'minimum' in field and value < field['minimum']:
            return f"{name} must be at least {field['minimum']}"
        if 'maximum' in field and value > field['maximum']:
            return f"{name} must be at most {field['maximum']}"
        if 'minLength' in field and len(value) < field['minLength']:
            return f'{name} must not be empty'
    return None

def fn__sanitize_raw_result(tool, result):
    if not isinstance(result, dict) or not isinstance(result.get('content'), dict):
        return {'type': 'tool_result', 'tool': tool, 'content': {'status': 'error', 'data': {}, 'message': 'UPSTREAM_TOOL_ERROR: invalid raw response'}}
    content = result['content']
    if content.get('status') != 'error':
        return result
    message = str(content.get('message') or 'UPSTREAM_TOOL_ERROR: raw tool failed')
    if message.startswith('INTERNAL_ERROR') or 'traceback' in message.lower():
        message = 'UPSTREAM_TOOL_ERROR: raw tool execution failed'
    return {'type': 'tool_result', 'tool': tool, 'content': {'status': 'error', 'data': {}, 'message': message}}

def fn__bounded_limit(arguments):
    if not isinstance(arguments, dict):
        return 25
    value = arguments.get('limit', 25)
    if not isinstance(value, int) or isinstance(value, bool) or (not 1 <= value <= 50):
        return 25
    return value

def fn__tool_result(tool, data, message=''):
    return {'type': 'tool_result', 'tool': tool, 'content': {'status': 'success', 'data': data, 'message': message}}

def fn__matches_type(value, expected):
    if expected == 'boolean':
        return isinstance(value, bool)
    if expected == 'integer':
        return isinstance(value, int) and (not isinstance(value, bool))
    if expected == 'number':
        return isinstance(value, (int, float)) and (not isinstance(value, bool))
    if expected == 'string':
        return isinstance(value, str)
    return True

def fn__isolated_server(source):

    def initialize(modules):
        server = modules[0]
        server.init_database(str(source / 'data'))
        server.load_tools()
        return server
    (_, server) = ext_load_isolated_modules(source, ('mcp_servers.server',), initialize=initialize)
    assert server is not None
    return server

def fn_digest(value):
    return mod_hashlib.sha256(fn__canonical_3(value).encode('ascii')).hexdigest()

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

class World:

    def _set_orders(self, task_id):
        rows = fn_scheduled_orders(task_id) if task_id else ()
        self.orders = {row['order_id']: ext_deepcopy(row) for row in rows}
        self.orders_by_code = {row['request_code'].lower(): row['order_id'] for row in rows}
        self.rosters = {row['roster_id']: ext_deepcopy(row['candidates']) for row in rows}
        self._patch_current_responsibilities()

    def activate_task(self, task_id, *, replenish=True, evaluator_apply_scheduled_drift=None):
        index = len(self._activated_tasks)
        if index >= len(DATA_TASK_IDS) or task_id != DATA_TASK_IDS[index]:
            raise ValueError('out-of-order Emergency task activation')
        if evaluator_apply_scheduled_drift is not None and task_id != 'T09':
            raise ValueError('authority override is valid only at the event boundary')
        boundary = None
        if task_id == 'T09' and evaluator_apply_scheduled_drift is not False:
            boundary = self.apply_coordination_policy_drift('evt-coordination-policy-2026-09-v2')
            for atom in DATA_CHANGED_AUTHORITY_ATOMS:
                self.authority_revalidation.setdefault(atom, 'awaiting_exact_stale')
        elif task_id == 'T09':
            self.applied_boundary_events.add('evt-coordination-policy-2026-09-v2')
        for order in fn_scheduled_orders(task_id):
            self._inject_order(order)
        self.active_task_id = task_id
        self._set_orders(task_id)
        if replenish:
            self.remaining = self.initial_budget
        self._active_receipt_start = len(self.receipts)
        self._activated_tasks.append(task_id)
        for name in ('order_observations', 'incident_observations', 'roster_observations', 'resource_observations', 'resolved_order_handles', 'issued_assignment_handles'):
            setattr(self, name, set())
        return {'status': 'success', 'task_id': task_id, 'world_reset': False, 'budget_reset': replenish, 'boundary_event_applied': boundary is not None and (not boundary['idempotent']), 'entry_business_hash': self.business_hash(), 'entry_lineage_hash': self.lineage_hash()}

    def snapshot(self):
        state = self._emergency_independent_world_snapshot()
        state['formation_balance_contract'] = 'emergency-formation-balanced-evolution-v3'
        return state

    def restore(self, snapshot):
        if snapshot.get('formation_balance_contract') != 'emergency-formation-balanced-evolution-v3':
            raise ValueError('Emergency formation contract differs')
        self._emergency_independent_world_restore(snapshot)

    @contextmanager
    def _independent_target(self, order_id):
        original = self.orders
        if order_id in original:
            self.orders = {order_id: original[order_id], **{k: v for (k, v) in original.items() if k != order_id}}
        try:
            yield
        finally:
            self.orders = original

    def _assignment_guard(self, arguments):
        with self._independent_target(arguments.get('dispatch_order_id')):
            return self._emergency_response_permission_successor_assignment_guard(arguments)

    def _exact_stale_conflict(self, arguments, order):
        with self._independent_target(order['order_id']):
            return self._emergency_response_permission_successor_exact_stale_conflict(arguments, order)

    def _restore_unchecked(self, snapshot):
        self._emergency_response_permission_successor_restore_unchecked(snapshot)
        self._set_orders(self.active_task_id)

    def _own_released_assignment(self, arguments, actor):
        if actor != 'incident_dispatcher' or not isinstance(arguments, dict) or set(arguments) != {'resource_id', 'include_assignment_history'} or (arguments['include_assignment_history'] is not False) or (not isinstance(arguments['resource_id'], str)):
            return None
        receipts = self.receipts[self._active_receipt_start:]
        assigned = next((row for row in reversed(receipts) if row['actor'] == actor and row['status'] == 'success' and (row['tool'] == 'assign_resource_to_incident') and (row['arguments'].get('resource_id') == arguments['resource_id'])), None)
        if assigned is None:
            return None
        assignments = self.manager.query_entities('resource_assignment', lambda row: row.get('dispatch_order_id') == assigned['arguments']['dispatch_order_id'] and row.get('resource_id') == arguments['resource_id'])
        if not assignments:
            return None
        assignment = assignments[-1]
        released = any((row['actor'] == actor and row['status'] == 'success' and (row['tool'] == 'release_resource_assignment') and (row['index'] > assigned['index']) and (row['arguments'].get('assignment_id') == assignment['assignment_id']) for row in receipts))
        return assignment if released and assignment['status'] == 'released' else None

    def _cost(self, tool, arguments):
        if tool == 'get_resource_unit_status' and self._own_released_assignment(arguments, 'incident_dispatcher') is not None:
            return 0
        return self._emergency_response_permission_successor_cost(tool, arguments)

    def dispatch(self, tool, arguments, actor='incident_dispatcher'):
        assignment = self._own_released_assignment(arguments, actor) if tool == 'get_resource_unit_status' else None
        if assignment is None:
            return self._emergency_response_permission_successor_dispatch(tool, arguments, actor)
        resource = self.manager.get_entity('resource_unit', arguments['resource_id'])
        before = self.semantic_hash()
        self.resource_observations.add(arguments['resource_id'])
        result = {'type': 'tool_result', 'tool': tool, 'content': {'status': 'success', 'data': {'resource': {key: ext_deepcopy(resource[key]) for key in ('resource_id', 'status', 'current_incident_id')}, 'assignment': {key: ext_deepcopy(assignment[key]) for key in ('assignment_id', 'status')}, 'confirmation_only': True}, 'message': 'Current status of your released assignment.'}}
        return self._record(tool, actor, arguments, 0, before, result)

    def __init__(self, source=CASE_DIR / 'raw', snapshot=None):
        self._source = source
        self._emergency_response_permission_successor_init(source=source, snapshot=snapshot)

    def _custom_read(self, tool, arguments):
        result = self._emergency_response_permission_successor_custom_read(tool, arguments)
        if tool == 'inspect_dispatch_roster' and result['content']['status'] == 'success':
            for candidate in result['content']['data']['candidates']:
                current = self.manager.get_entity('resource_unit', candidate['resource_id'])
                for field in candidate:
                    candidate[field] = ext_deepcopy(current[field])
        return result

    def semantic_hash(self):
        return fn__digest({'base': self._persistent_emergency_dispatch_adapter_semantic_hash(), 'authority_revalidation': self.authority_revalidation, 'authority_bindings': self.authority_bindings})

    def _atom_for_order(self, order_id):
        order = self.orders.get(order_id)
        return None if order is None else fn_authority_atom(order)

    def _patch_current_responsibilities(self):
        if not self.responsibility_changed:
            return
        for order in self.orders.values():
            atom = fn_authority_atom(order)
            if atom not in DATA_CHANGED_AUTHORITY_ATOMS:
                continue
            agency_id = DATA_CURRENT_RESPONSIBLE_AGENCY[atom]
            order['lead_agency_id'] = agency_id
            incident = self.manager.get_entity('incident', order['incident_id'])
            if incident is not None and incident.get('lead_agency_id') != agency_id:
                self.manager.update_entity('incident', order['incident_id'], {'lead_agency_id': agency_id})

    def _current_episode_verification(self, order_id):
        assignment_receipt = None
        assignment_id = None
        resource_id = None
        for receipt in self.receipts[self._active_receipt_start:]:
            if receipt['status'] != 'success' or not isinstance(receipt['arguments'], dict):
                continue
            if receipt['tool'] == 'assign_resource_to_incident' and receipt['arguments'].get('dispatch_order_id') == order_id:
                assignment_receipt = receipt['index']
                resource_id = receipt['arguments'].get('resource_id')
                assignments = self.manager.query_entities('resource_assignment', lambda row: row.get('dispatch_order_id') == order_id and row.get('resource_id') == resource_id)
                if assignments:
                    assignment_id = assignments[-1].get('assignment_id')
                continue
            if assignment_receipt is not None and assignment_id is not None and (receipt['tool'] == 'release_resource_assignment') and (receipt['arguments'].get('assignment_id') == assignment_id):
                assignment_receipt = receipt['index']
                continue
            if assignment_receipt is not None and assignment_id is not None and (receipt['tool'] == 'get_resource_unit_status') and (receipt['arguments'].get('resource_id') == resource_id) and (receipt['index'] > assignment_receipt):
                assignment = self.manager.get_entity('resource_assignment', assignment_id)
                return bool(assignment and assignment.get('status') == 'released')
        return False

    def _order_is_complete(self, order_id):
        return self._emergency_response_permission_successor_order_is_complete(order_id) and self._current_episode_verification(order_id)

    def grade(self):
        artifacts = []
        for order in self.orders.values():
            passed = None
            if self._order_is_complete(order['order_id']):
                assignments = self.manager.query_entities('resource_assignment', lambda row: row.get('dispatch_order_id') == order['order_id'])
                passed = next((row for row in assignments if row.get('status') == 'released'), None)
            artifacts.append({'request_code': order['request_code'], 'structure_atom': order['structure_atom'], 'rule_atom': order['rule_atom'], 'authority_atom': fn_authority_atom(order), 'complete': passed is not None, 'assignment_id': passed.get('assignment_id') if passed else None, 'score': 25.0 if passed else 0.0})
        completed = sum((row['complete'] for row in artifacts))
        return {'task_id': self.active_task_id, 'score': completed * 25.0, 'max_score': 100.0, 'completed_artifacts': completed, 'artifacts': artifacts, 'remaining_budget': self.remaining}

    def _record(self, tool, actor, arguments, cost, before_hash, result):
        recorded = self._emergency_dispatch_adapter_record(tool, actor, arguments, cost, before_hash, result)
        self.receipts[-1]['task_id'] = self.active_task_id
        return recorded

    def _charged_evidence_error(self, tool, arguments, code, message):
        cost = self._cost(tool, arguments)
        if self.remaining < cost:
            return self._emergency_response_permission_successor_dispatch_2(tool, arguments, 'incident_dispatcher')
        before_hash = self.semantic_hash()
        self.remaining -= cost
        return self._record(tool, 'incident_dispatcher', arguments, cost, before_hash, self._error(tool, code, message, cost))

    def _policy(self, incident_type, mission_class):
        return DATA_POLICY_ROWS[incident_type][mission_class]

    def apply_coordination_policy_drift(self, event_id):
        if event_id in self.applied_boundary_events:
            return {'status': 'success', 'event_id': event_id, 'idempotent': True}
        self.responsibility_changed = True
        self.applied_boundary_events.add(event_id)
        return {'status': 'success', 'event_id': event_id, 'idempotent': False}

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

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

    def _stream_business_state(self):
        database = self.manager.db
        for entity_type in ('incident', 'resource_unit', 'resource_assignment'):
            database._ensure_loaded(entity_type)
        return {'incidents': [row for row in database._data['incident'] if row.get('incident_id') in DATA__STREAM_INCIDENT_IDS], 'resources': [row for row in database._data['resource_unit'] if row.get('resource_id') in DATA__STREAM_RESOURCE_IDS], 'assignments': [row for row in database._data['resource_assignment'] if row.get('dispatch_order_id') in DATA__STREAM_ORDER_IDS]}

    def business_hash(self):
        return mod_hashlib.sha256(fn__canonical(self._stream_business_state()).encode('utf-8')).hexdigest()

    def lineage_hash(self):
        return mod_hashlib.sha256(fn__canonical(self.snapshot()).encode('utf-8')).hexdigest()

    def close(self):
        self.server.cleanup_runtime()

    def _error(self, tool, code, message, cost=0):
        return {'type': 'tool_result', 'tool': tool, 'content': {'status': 'error', 'data': {}, 'message': f'{code}: {message}'}, 'budget': {'charged': cost, 'remaining': self.remaining}}

    def _inject_order(self, order):
        if self.manager.get_entity('incident', order['incident_id']) is None:
            self.manager.add_entity('incident', {'incident_id': order['incident_id'], 'title': order['title'], 'incident_type': order['incident_type'], 'severity': DATA_SEVERITIES[order['priority'] - 1], 'status': 'active', 'priority': order['priority'], 'lead_agency_id': order['lead_agency_id'], 'command_post': f"{order['affected_area']} command post", 'affected_area': order['affected_area'], 'reported_at': order['reported_at'], 'created_at': order['reported_at'], 'updated_at': order['reported_at'], 'closed_at': None, 'active_resource_count': 0, 'sheltering_required': order['mission_class'] == 'shelter', 'evacuation_required': order['mission_class'] == 'rescue', 'public_summary': f"Active dispatch request {order['request_code']}."})
        for candidate in order['candidates']:
            if self.manager.get_entity('resource_unit', candidate['resource_id']) is None:
                self.manager.add_entity('resource_unit', {**candidate, 'created_at': '2026-05-01T00:00:00Z', 'last_status_at': '2026-05-20T00:00:00Z', 'updated_at': '2026-05-20T00:00:00Z'})

    def _emergency_independent_world_snapshot(self):
        value = self._emergency_evolution_snapshot()
        value['independent_dispatch_contract'] = 'emergency-independent-dispatch-evolution-v2'
        return value

    def _emergency_independent_world_restore(self, snapshot):
        if snapshot.get('independent_dispatch_contract') != 'emergency-independent-dispatch-evolution-v2':
            raise ValueError('Emergency independent dispatch contract differs')
        self._emergency_evolution_restore(snapshot)

    def _emergency_response_permission_successor_assignment_guard(self, arguments):
        """Apply the v6 evidence gates without its obsolete slot-level authority gate."""
        order_id = arguments.get('dispatch_order_id', '')
        order = self.orders.get(order_id)
        if order is not None and order_id not in self.order_observations:
            return self._error('assign_resource_to_incident', 'ORDER_EVIDENCE_REQUIRED', 'the active dispatch order has not been read in this episode')
        if order is not None:
            for candidate_order_id in self.orders:
                if candidate_order_id == order_id:
                    break
                if not self._order_is_complete(candidate_order_id):
                    return self._error('assign_resource_to_incident', 'DISPATCH_PRIORITY_BLOCKED', 'complete and close earlier listed dispatch orders first')
        guarded = World._emergency_dispatch_adapter_assignment_guard(self, arguments)
        if guarded is not None or order is None:
            return guarded
        if order['roster_id'] not in self.roster_observations and arguments.get('resource_id') not in self.resource_observations:
            return self._error('assign_resource_to_incident', 'RESOURCE_STATE_UNCONFIRMED', 'the selected resource has not been verified in the current dispatch episode')
        if self.authority_bindings.get(order['responsibility_domain']) != arguments.get('requested_by_agency_id'):
            return self._error('assign_resource_to_incident', 'AUTHORITY_EVIDENCE_REQUIRED', 'the requesting authority lacks a publicly observed responsibility binding')
        return None

    def _emergency_response_permission_successor_exact_stale_conflict(self, arguments, order):
        atom = fn_authority_atom(order)
        if self.authority_revalidation.get(atom) != 'awaiting_exact_stale':
            return False
        expected = {'incident_id': order['incident_id'], 'requested_by_agency_id': DATA_PRE_RESPONSIBLE_AGENCY[atom], 'required_capability': order['required_capability'], 'mission': order['mission'], 'priority': order['dispatch_priority']}
        if any((arguments.get(field) != value for (field, value) in expected.items())):
            return False
        resource_id = arguments.get('resource_id')
        candidate = next((row for row in order['candidates'] if row['resource_id'] == resource_id), None)
        resource = self.manager.get_entity('resource_unit', resource_id or '')
        return bool(order['order_id'] in self.order_observations and self.authority_bindings.get(order['responsibility_domain']) == DATA_PRE_RESPONSIBLE_AGENCY[atom] and (candidate is not None) and (candidate['owning_agency_type'] == self._policy(order['incident_type'], order['mission_class'])) and (resource is not None) and (resource.get('status') in {'available', 'staged'}) and (resource.get('current_incident_id') is None) and (order['roster_id'] in self.roster_observations or resource_id in self.resource_observations) and all((earlier_id == order['order_id'] or self._order_is_complete(earlier_id) for earlier_id in self.orders if list(self.orders).index(earlier_id) < list(self.orders).index(order['order_id']))))

    def _emergency_response_permission_successor_restore_unchecked(self, snapshot):
        database = mod_copy.deepcopy(snapshot['raw']['database'])
        self.manager.db._data = database
        self.manager.db._id_counters = mod_copy.deepcopy(snapshot['db_id_counters'])
        self.manager.counters = mod_copy.deepcopy(snapshot['raw']['counters'])
        self.remaining = snapshot['remaining']
        self.receipts = mod_copy.deepcopy(snapshot['receipts'])
        self.applied_boundary_events = set(snapshot['applied_boundary_events'])
        self.policy_version = snapshot['policy_version']
        self.active_task_id = snapshot['active_task_id']
        self._activated_tasks = list(snapshot['activated_tasks'])
        self._active_receipt_start = snapshot['active_receipt_start']
        permission = snapshot['permission']
        self.responsibility_changed = permission['responsibility_changed']
        self.order_observations = set(permission['order_observations'])
        self.incident_observations = set(permission['incident_observations'])
        self.confirmed_authority_atoms = set(permission['confirmed_authority_atoms'])
        self.roster_observations = set(permission['roster_observations'])
        self.resource_observations = set(permission['resource_observations'])
        self.resolved_order_handles = set(permission['resolved_order_handles'])
        self.issued_resource_handles = set(permission['issued_resource_handles'])
        self.issued_assignment_handles = set(permission['issued_assignment_handles'])
        self.authority_bindings = dict(permission['authority_bindings'])
        self.authority_revalidation = dict(permission['authority_revalidation'])
        if self.active_task_id:
            rows = fn_scheduled_orders_2(self.active_task_id)
            self.orders = {row['order_id']: mod_copy.deepcopy(row) for row in rows}
            self.orders_by_code = {row['request_code'].lower(): row['order_id'] for row in rows}
            self.rosters = {row['roster_id']: mod_copy.deepcopy(row['candidates']) for row in rows}
        else:
            self.orders = {}
            self.orders_by_code = {}
            self.rosters = {}
        self._patch_current_responsibilities()

    def _emergency_response_permission_successor_cost(self, tool, arguments):
        if tool == 'inspect_dispatch_roster':
            return 29
        if tool == 'get_incident_detail' and isinstance(arguments, dict):
            return 20 if arguments.get('include_history', True) else 2
        return self._emergency_response_permission_successor_cost_2(tool, arguments)

    def _emergency_response_permission_successor_dispatch(self, tool, arguments, actor='incident_dispatcher'):
        if tool == 'assign_resource_to_incident':
            if actor != 'incident_dispatcher':
                return self._error(tool, 'ROLE_FORBIDDEN', 'actor is not an incident dispatcher')
            if self.remaining < self._cost(tool, arguments):
                return self._error(tool, 'WORK_QUOTA_EXHAUSTED', 'insufficient API-work quota')
        return self._emergency_response_permission_successor_dispatch_3(tool, arguments, actor)

    def _emergency_response_permission_successor_init(self, source=CASE_DIR / 'raw', snapshot=None):
        self.authority_revalidation: dict[str, str] = {}
        self._emergency_response_permission_successor_init_2(source=source)
        self.initial_budget = 104
        self.remaining = 104
        if snapshot is not None:
            self.restore(snapshot)

    def _emergency_response_permission_successor_custom_read(self, tool, arguments):
        if tool == 'get_dispatch_order' and arguments['order_id'] not in self.resolved_order_handles:
            return self._error(tool, 'ORDER_HANDLE_UNOBSERVED', 'resolve the request code before using its dispatch-order handle')
        if tool == 'inspect_dispatch_roster':
            issued_rosters = {self.orders[order_id]['roster_id'] for order_id in self.order_observations}
            if arguments['roster_id'] not in issued_rosters:
                return self._error(tool, 'ROSTER_HANDLE_UNOBSERVED', 'read the dispatch order before using its roster handle')
        if tool == 'get_coordination_policy' and (not any((order['incident_type'] == arguments['incident_type'] and order['mission_class'] == arguments['mission_class'] for (order_id, order) in self.orders.items() if order_id in self.order_observations))):
            return self._error(tool, 'POLICY_SCOPE_UNOBSERVED', 'the requested policy cell is not grounded in an observed active order')
        result = self._emergency_response_permission_successor_custom_read_2(tool, arguments)
        if result.get('content', {}).get('status') != 'success':
            return result
        if tool == 'search_dispatch_orders':
            self.resolved_order_handles.update((row['order_id'] for row in result['content']['data'].get('orders', [])))
        elif tool == 'inspect_dispatch_roster':
            self.issued_resource_handles.update((row['resource_id'] for row in result['content']['data'].get('candidates', [])))
        return result

    def _persistent_emergency_dispatch_adapter_semantic_hash(self):
        payload = {'business': self._stream_business_state(), 'remaining': self.remaining, 'receipts': self.receipts, 'boundary_events': sorted(self.applied_boundary_events), 'policy_version': self.policy_version, 'active_task_id': self.active_task_id, 'activated_tasks': self._activated_tasks}
        return mod_hashlib.sha256(fn__canonical(payload).encode('utf-8')).hexdigest()

    def _emergency_response_permission_successor_order_is_complete(self, order_id):
        order = self.orders[order_id]
        incident = self.manager.get_entity('incident', order['incident_id'])
        for assignment in self.manager.list_entities('resource_assignment'):
            if assignment.get('dispatch_order_id') != order_id:
                continue
            resource = self.manager.get_entity('resource_unit', assignment.get('resource_id', ''))
            if assignment.get('status') == 'released' and assignment.get('released_at') and (resource is not None) and (resource.get('status') == 'available') and (resource.get('current_incident_id') is None) and (incident is not None) and (incident.get('active_resource_count') == 0):
                return True
        return False

    def _emergency_dispatch_adapter_record(self, tool, actor, arguments, cost, before_hash, result):
        content = result.get('content', {})
        receipt = {'index': len(self.receipts) + 1, 'tool': tool, 'actor': actor, 'arguments': mod_copy.deepcopy(arguments), 'status': content.get('status'), 'cost': cost, 'before_hash': before_hash, 'after_hash': self.semantic_hash()}
        self.receipts.append(receipt)
        result['budget'] = {'charged': cost, 'remaining': self.remaining}
        result['receipt_index'] = receipt['index']
        return result

    def _emergency_response_permission_successor_dispatch_2(self, tool, arguments, actor='incident_dispatcher'):
        result = self._emergency_response_permission_successor_dispatch_4(tool, arguments, actor)
        if tool == 'get_resource_unit_status' and result.get('content', {}).get('status') == 'success':
            self.resource_observations.add(arguments['resource_id'])
        return result

    def _emergency_evolution_snapshot(self):
        value = self._emergency_confirmation_snapshot()
        value['evolution_contract'] = {'case_version': 'emergency-lifecycle-evolution-v1', 'schedule': ext_deepcopy(DATA_SCHEDULE_2)}
        return value

    def _emergency_evolution_restore(self, snapshot):
        if snapshot.get('evolution_contract') != {'case_version': 'emergency-lifecycle-evolution-v1', 'schedule': DATA_SCHEDULE_2}:
            raise ValueError('Emergency evolution contract differs')
        self._emergency_confirmation_restore(snapshot)

    def _emergency_dispatch_adapter_assignment_guard(self, arguments):
        order = self.orders.get(arguments.get('dispatch_order_id', ''))
        if order is None:
            return self._error('assign_resource_to_incident', 'DISPATCH_ORDER_NOT_FOUND', 'the order is not active')
        for assignment in self.manager.list_entities('resource_assignment'):
            if assignment.get('dispatch_order_id') == order['order_id']:
                return self._error('assign_resource_to_incident', 'DISPATCH_ORDER_ALREADY_USED', 'the order already has an assignment')
        expected = {'incident_id': order['incident_id'], 'requested_by_agency_id': order['lead_agency_id'], 'required_capability': order['required_capability'], 'mission': order['mission'], 'priority': order['dispatch_priority']}
        if any((arguments.get(field) != value for (field, value) in expected.items())):
            return self._error('assign_resource_to_incident', 'DISPATCH_ORDER_MISMATCH', 'assignment fields do not match the active order')
        roster_ids = {candidate['resource_id'] for candidate in order['candidates']}
        if arguments.get('resource_id') not in roster_ids:
            return self._error('assign_resource_to_incident', 'RESOURCE_OUTSIDE_ROSTER', 'the selected resource is not in the order roster')
        resource = self.manager.get_entity('resource_unit', arguments['resource_id'])
        incident = self.manager.get_entity('incident', order['incident_id'])
        agency = self.manager.get_entity('agency', resource.get('owning_agency_id', '')) if resource else None
        if resource is None or incident is None or agency is None:
            return self._error('assign_resource_to_incident', 'ORDER_BINDING_STALE', 'an order binding no longer resolves')
        if order['required_capability'] not in set(resource.get('capability_tags') or []):
            return self._error('assign_resource_to_incident', 'CAPABILITY_MISMATCH', 'the selected resource lacks the order capability')
        if resource.get('status') not in {'available', 'staged'} or resource.get('current_incident_id'):
            return self._error('assign_resource_to_incident', 'RESOURCE_NOT_DEPLOYABLE', 'the selected resource is already committed')
        if int(resource.get('fuel_or_supply_percent') or 0) < 30:
            return self._error('assign_resource_to_incident', 'RESOURCE_LOW_SUPPLY', 'the selected resource is below dispatch reserve')
        authorized_owner_type = self._policy(order['incident_type'], order['mission_class'])
        if agency.get('agency_type') != authorized_owner_type:
            return self._error('assign_resource_to_incident', 'COORDINATION_POLICY_REJECTED', 'the selected roster candidate is not authorized for this incident and mission cell')
        return None

    def _emergency_response_permission_successor_cost_2(self, tool, arguments):
        if tool == 'inspect_dispatch_roster':
            return 22
        return self._emergency_response_permission_successor_cost_3(tool, arguments)

    def _emergency_response_permission_successor_dispatch_3(self, tool, arguments, actor='incident_dispatcher'):
        result = self._emergency_response_permission_successor_dispatch_5(tool, arguments, actor)
        if actor == 'incident_dispatcher' and tool == 'get_resource_unit_status' and (result.get('content', {}).get('status') == 'success'):
            data = result['content']['data']
            self.issued_assignment_handles.update((row['assignment_id'] for row in data.get('assignment_history', []) if row['resource_id'] == data['resource']['resource_id']))
            if self.receipts and self.receipts[-1]['index'] == result.get('receipt_index'):
                self.receipts[-1]['after_hash'] = self.semantic_hash()
        return result

    def _emergency_response_permission_successor_init_2(self, source=CASE_DIR / 'raw', snapshot=None):
        self._emergency_response_permission_successor_init_3(source=source)
        self.initial_budget = 104
        self.remaining = 104
        self.resolved_order_handles: set[str] = set()
        self.issued_resource_handles: set[str] = set()
        self.issued_assignment_handles: set[str] = set()
        self.authority_bindings: dict[str, str] = {}
        if snapshot is not None:
            self.restore(snapshot)

    def _emergency_response_permission_successor_custom_read_2(self, tool, arguments):
        result = self._emergency_response_permission_successor_custom_read_3(tool, arguments)
        if result.get('content', {}).get('status') != 'success':
            return result
        if tool == 'get_dispatch_order':
            order = result['content']['data']['order']
            source = self.orders[arguments['order_id']]
            order.pop('lead_agency_id', None)
            order['responsibility_domain'] = source['responsibility_domain']
        elif tool == 'inspect_dispatch_roster':
            self.roster_observations.add(arguments['roster_id'])
        return result

    def _emergency_response_permission_successor_dispatch_4(self, tool, arguments, actor='incident_dispatcher'):
        result = self._emergency_dispatch_adapter_dispatch(tool, arguments, actor)
        if tool == 'get_incident_detail' and result.get('content', {}).get('status') == 'success':
            self.incident_observations.add(arguments['incident_id'])
        if tool == 'assign_resource_to_incident' and result.get('content', {}).get('status') == 'success':
            atom = self._atom_for_order(arguments['dispatch_order_id'])
            order = self.orders[arguments['dispatch_order_id']]
            if self.responsibility_changed and atom in DATA_CHANGED_AUTHORITY_ATOMS_2 and (order['order_id'] in self.order_observations) and (order['incident_id'] in self.incident_observations):
                self.confirmed_authority_atoms.add(atom)
        return result

    def _emergency_confirmation_snapshot(self):
        snapshot = self._emergency_response_permission_successor_snapshot()
        snapshot['confirmation_contract'] = 'emergency-own-release-confirmation/v1'
        snapshot['permission']['tool_surface_sha256'] = fn__digest(DATA_PROVIDER_TOOLS)
        return snapshot

    def _emergency_confirmation_restore(self, snapshot):
        if not isinstance(snapshot, dict) or snapshot.get('confirmation_contract') != 'emergency-own-release-confirmation/v1':
            raise ValueError('Emergency confirmation contract differs')
        self._emergency_response_permission_successor_restore(snapshot)

    def _emergency_response_permission_successor_cost_3(self, tool, arguments):
        if tool in {'get_dispatch_order', 'get_incident_detail'}:
            return 2
        return self._emergency_dispatch_adapter_cost(tool, arguments)

    def _emergency_response_permission_successor_dispatch_5(self, tool, arguments, actor='incident_dispatcher'):
        order = None
        atom = None
        if tool == 'assign_resource_to_incident' and isinstance(arguments, dict):
            order = self.orders.get(arguments.get('dispatch_order_id', ''))
            atom = fn_authority_atom(order) if order is not None else None
        result = self._emergency_response_permission_successor_dispatch_6(tool, arguments, actor)
        changed = False
        if tool == 'get_incident_detail' and isinstance(arguments, dict) and (result.get('content', {}).get('status') == 'success'):
            incident = result['content']['data']['incident']
            order = next((row for row in self.orders.values() if row['incident_id'] == incident['incident_id']), None)
            if order is not None:
                atom = fn_authority_atom(order)
                full_history = arguments.get('include_history', True)
                result['content']['data']['authority_evidence'] = {'source': 'command_history' if full_history else 'dispatch_summary', 'freshness': 'current_reconciled' if full_history else 'not_reconciled'}
                state = self.authority_revalidation.get(atom)
                if atom in DATA_CHANGED_AUTHORITY_ATOMS and state in {'awaiting_exact_stale', 'awaiting_full_history'}:
                    if full_history:
                        self.authority_revalidation[atom] = 'ready_current'
                    else:
                        incident['lead_agency_id'] = DATA_PRE_RESPONSIBLE_AGENCY[atom]
                        self.authority_bindings[order['responsibility_domain']] = DATA_PRE_RESPONSIBLE_AGENCY[atom]
                    changed = True
        elif tool == 'assign_resource_to_incident' and order is not None and (atom in DATA_CHANGED_AUTHORITY_ATOMS):
            status = result.get('content', {}).get('status')
            if status == 'error' and self._exact_stale_conflict(arguments, order):
                self.authority_revalidation[atom] = 'awaiting_full_history'
                changed = True
            elif status == 'success' and self.authority_revalidation.get(atom) == 'ready_current':
                self.authority_revalidation[atom] = 'validated'
                changed = True
        if changed and self.receipts and (self.receipts[-1]['index'] == result.get('receipt_index')):
            self.receipts[-1]['after_hash'] = self.semantic_hash()
        return result

    def _emergency_response_permission_successor_init_3(self, source=CASE_DIR / 'raw', snapshot=None):
        self._emergency_response_permission_successor_init_4(source=source)
        self.roster_observations: set[str] = set()
        self.resource_observations: set[str] = set()
        if snapshot is not None:
            self.restore(snapshot)

    def _emergency_response_permission_successor_custom_read_3(self, tool, arguments):
        result = self._emergency_dispatch_adapter_custom_read(tool, arguments)
        if tool == 'get_dispatch_order' and result.get('content', {}).get('status') == 'success':
            self.order_observations.add(arguments['order_id'])
        return result

    def _emergency_dispatch_adapter_dispatch(self, tool, arguments, actor='incident_dispatcher'):
        if actor != 'incident_dispatcher':
            return self._error(tool, 'ROLE_FORBIDDEN', 'actor is not an incident dispatcher')
        if tool not in DATA_ALLOWED_TOOLS:
            return self._error(tool, 'TOOL_FORBIDDEN', 'tool is outside the dispatcher slice')
        cost = self._cost(tool, arguments)
        if self.remaining < cost:
            return self._error(tool, 'WORK_QUOTA_EXHAUSTED', 'insufficient API-work quota')
        validation_error = fn__validate_arguments(tool, arguments)
        before_hash = self.semantic_hash()
        if validation_error is not None:
            self.remaining -= cost
            return self._record(tool, actor, arguments, cost, before_hash, self._error(tool, 'INVALID_ARGUMENTS', validation_error, cost))
        if tool == 'assign_resource_to_incident':
            guarded = self._assignment_guard(arguments)
            if guarded is not None:
                self.remaining -= cost
                return self._record(tool, actor, arguments, cost, before_hash, guarded)
        self.remaining -= cost
        if tool in DATA_CUSTOM_COSTS:
            result = self._custom_read(tool, arguments)
            return self._record(tool, actor, arguments, cost, before_hash, result)
        raw_arguments = mod_copy.deepcopy(arguments)
        order_id = raw_arguments.pop('dispatch_order_id', None)
        raw_arguments.pop('required_capability', None)
        try:
            raw_result = self.server.call_tool(tool, state_manager=self.manager, **raw_arguments)
        except Exception:
            raw_result = None
        result = fn__sanitize_raw_result(tool, raw_result)
        if tool == 'assign_resource_to_incident' and result.get('content', {}).get('status') == 'success':
            assignment_id = result['content']['data']['assignment_id']
            order = self.orders[order_id]
            self.manager.update_entity('resource_assignment', assignment_id, {'dispatch_order_id': order_id, 'coordination_cell': order['rule_atom'], 'required_capability': order['required_capability'], 'authorized_owner_type': self._policy(order['incident_type'], order['mission_class'])})
            result['content']['data'].update(dispatch_order_id=order_id, coordination_cell=order['rule_atom'])
        return self._record(tool, actor, arguments, cost, before_hash, result)

    def _emergency_response_permission_successor_snapshot(self):
        snapshot = self._emergency_response_permission_successor_snapshot_2()
        snapshot['schema'] = 'rescopebench-emergency-response-permission-snapshot/v7.4'
        snapshot['schedule_version'] = 'emergency-response-permission-v7.4'
        return snapshot

    def _emergency_response_permission_successor_restore(self, snapshot):
        if not isinstance(snapshot, dict) or snapshot.get('schema') != 'rescopebench-emergency-response-permission-snapshot/v7.4' or snapshot.get('schedule_version') != 'emergency-response-permission-v7.4':
            raise ValueError('Unsupported Emergency Response v7.4 snapshot')
        (activated, receipts, permission) = (snapshot.get(k) for k in ('activated_tasks', 'receipts', 'permission'))
        if not isinstance(activated, list) or activated != list(DATA_TASK_IDS[:len(activated)]) or (not isinstance(receipts, list)) or (len(receipts) > 1024) or (not isinstance(permission, dict)) or (type(permission.get('responsibility_changed')) is not bool):
            raise ValueError('Malformed Emergency Response v7.4 replay input')
        if any((not isinstance(r, dict) or r.get('tool') not in DATA_VISIBLE_TOOL_NAMES or r.get('actor') != 'incident_dispatcher' or (not isinstance(r.get('arguments'), dict)) for r in receipts)):
            raise ValueError('Malformed Emergency Response v7.4 receipt')
        replay = type(self)(source=self._source)
        try:
            cursor = 0
            for task_id in activated:
                drift = False if task_id == 'T09' and (not permission['responsibility_changed']) else None
                replay.activate_task(task_id, evaluator_apply_scheduled_drift=drift)
                while cursor < len(receipts) and receipts[cursor].get('task_id') == task_id:
                    receipt = receipts[cursor]
                    count = len(replay.receipts)
                    replay.dispatch(receipt['tool'], ext_deepcopy(receipt['arguments']), receipt['actor'])
                    if len(replay.receipts) != count + 1 or replay.receipts[-1] != receipt:
                        raise ValueError('Emergency Response v7.4 receipt replay diverged')
                    cursor += 1
            if cursor != len(receipts) or replay.snapshot() != snapshot:
                raise ValueError('Emergency Response v7.4 canonical replay diverged')
        finally:
            replay.close()
        self._restore_unchecked(snapshot)
        if self.snapshot() != snapshot:
            raise ValueError('Emergency Response v7.4 snapshot did not round trip')

    def _emergency_dispatch_adapter_cost(self, tool, arguments):
        if tool in DATA_CUSTOM_COSTS:
            return DATA_CUSTOM_COSTS[tool]
        if tool in DATA_RAW_LIST_TOOLS:
            return 2 + fn__bounded_limit(arguments)
        if tool in DATA_RAW_DETAIL_TOOLS:
            return 1
        return DATA_WRITE_COSTS[tool]

    def _emergency_response_permission_successor_dispatch_6(self, tool, arguments, actor='incident_dispatcher'):
        if actor == 'incident_dispatcher' and tool not in DATA_VISIBLE_TOOL_NAMES_2:
            return self._error(tool, 'TOOL_FORBIDDEN', 'tool is outside the public dispatcher slice')
        if actor == 'incident_dispatcher' and tool in {'get_incident_detail', 'get_resource_unit_status', 'release_resource_assignment'} and (fn__validate_arguments(tool, arguments) is None):
            if tool == 'get_incident_detail':
                issued_incidents = {self.orders[order_id]['incident_id'] for order_id in self.order_observations}
                if arguments['incident_id'] not in issued_incidents:
                    return self._charged_evidence_error(tool, arguments, 'INCIDENT_HANDLE_UNOBSERVED', 'read the dispatch order before using its incident handle')
            elif tool == 'get_resource_unit_status' and arguments['resource_id'] not in self.issued_resource_handles:
                return self._charged_evidence_error(tool, arguments, 'RESOURCE_HANDLE_UNOBSERVED', 'inspect a dispatch roster before using its resource handle')
            elif tool == 'release_resource_assignment' and arguments['assignment_id'] not in self.issued_assignment_handles:
                return self._charged_evidence_error(tool, arguments, 'ASSIGNMENT_HANDLE_UNOBSERVED', 'release only an assignment returned in the current episode')
        result = self._emergency_response_permission_successor_dispatch_2(tool, arguments, actor)
        if actor != 'incident_dispatcher' or result.get('content', {}).get('status') != 'success':
            return result
        if tool == 'get_incident_detail':
            incident = result['content']['data']['incident']
            order = next((row for (order_id, row) in self.orders.items() if order_id in self.order_observations and row['incident_id'] == incident['incident_id']))
            self.authority_bindings[order['responsibility_domain']] = incident['lead_agency_id']
        elif tool == 'assign_resource_to_incident':
            self.issued_assignment_handles.add(result['content']['data']['assignment_id'])
        return result

    def _emergency_response_permission_successor_init_4(self, source=CASE_DIR / 'raw', snapshot=None):
        self._emergency_response_permission_successor_init_5(source=source)
        if snapshot is not None:
            self.restore(snapshot)

    def _emergency_dispatch_adapter_custom_read(self, tool, arguments):
        if tool == 'search_dispatch_orders':
            code = arguments['request_code'].strip().lower()
            order_id = self.orders_by_code.get(code)
            rows = [] if order_id is None else [{'request_code': self.orders[order_id]['request_code'], 'order_id': order_id, 'status': 'open'}]
            return fn__tool_result(tool, {'total_count': len(rows), 'orders': rows})
        if tool == 'get_dispatch_order':
            order = self.orders.get(arguments['order_id'])
            if order is None:
                return self._error(tool, 'DISPATCH_ORDER_NOT_FOUND', 'no active dispatch order matches order_id')
            fields = ('request_code', 'order_id', 'incident_id', 'incident_type', 'mission_class', 'required_capability', 'mission', 'lead_agency_id', 'dispatch_priority', 'roster_id')
            return fn__tool_result(tool, {'order': {field: order[field] for field in fields}})
        if tool == 'inspect_dispatch_roster':
            candidates = self.rosters.get(arguments['roster_id'])
            if candidates is None:
                return self._error(tool, 'DISPATCH_ROSTER_NOT_FOUND', 'no active dispatch roster matches roster_id')
            fields = ('resource_id', 'owning_agency_id', 'owning_agency_type', 'resource_type', 'capability_tags', 'status', 'current_incident_id', 'staging_location', 'fuel_or_supply_percent')
            return fn__tool_result(tool, {'candidates': [{field: row[field] for field in fields} for row in candidates]})
        incident_type = arguments['incident_type']
        mission_class = arguments['mission_class']
        return fn__tool_result(tool, {'incident_type': incident_type, 'mission_class': mission_class, 'authorized_owner_type': self._policy(incident_type, mission_class), 'policy_version': self.policy_version})

    def _emergency_response_permission_successor_snapshot_2(self):
        snapshot = self._emergency_response_permission_successor_snapshot_3()
        snapshot['schema'] = 'rescopebench-emergency-response-permission-snapshot/v7.3'
        snapshot['schedule_version'] = 'emergency-response-permission-v7.3'
        snapshot['permission']['tool_surface_sha256'] = '93712b33cffcabf42d15afc865efe4b0f33b89f46c323071cdda22fe2b0b41b2'
        return snapshot

    def _emergency_response_permission_successor_init_5(self, source=CASE_DIR / 'raw', snapshot=None):
        source = ext_Path(source).resolve()
        self._stream_bootstrap = False
        self._activated_tasks = []
        self.server = fn__isolated_server(source)
        self.manager = self.server.get_state_manager()
        self.manager.db._flush = lambda _entity_type: None
        self.initial_budget = 74
        self.remaining = 74
        self.receipts = []
        self.applied_boundary_events = set()
        self.policy_version = 'fixed'
        self.active_task_id = ''
        self.orders = {}
        self.orders_by_code = {}
        self.rosters = {}
        self._active_receipt_start = 0
        self.responsibility_changed = False
        self.order_observations: set[str] = set()
        self.incident_observations: set[str] = set()
        self.confirmed_authority_atoms: set[str] = set()
        if snapshot is not None:
            self.restore(snapshot)

    def _emergency_response_permission_successor_snapshot_3(self):
        value = self._emergency_response_permission_successor_snapshot_4()
        value['schema'] = 'rescopebench-emergency-response-permission-snapshot/v7'
        value['schedule_version'] = 'emergency-response-permission-v7.1'
        value['permission']['tool_surface_sha256'] = 'c6f98989b4f91cb55f32b9131cd9c858dc2fc4d3f21b7078227adfe8f508bd48'
        value['permission']['authority_revalidation'] = dict(sorted(self.authority_revalidation.items()))
        return value

    def _emergency_response_permission_successor_snapshot_4(self):
        value = self._emergency_response_permission_successor_snapshot_5()
        value['schema'] = 'rescopebench-emergency-response-permission-snapshot/v6'
        value['schedule_version'] = 'emergency-response-permission-v6'
        value['permission']['tool_surface_sha256'] = 'fea5842206db73dbf129acb407adb35767f35e3e37e12c9bb2613ed3f56cb66e'
        value['permission']['resolved_order_handles'] = sorted(self.resolved_order_handles)
        value['permission']['issued_resource_handles'] = sorted(self.issued_resource_handles)
        value['permission']['issued_assignment_handles'] = sorted(self.issued_assignment_handles)
        value['permission']['authority_bindings'] = dict(sorted(self.authority_bindings.items()))
        return value

    def _emergency_response_permission_successor_snapshot_5(self):
        value = self._emergency_response_permission_successor_snapshot_6()
        value['schema'] = 'rescopebench-emergency-response-permission-snapshot/v4'
        value['schedule_version'] = 'emergency-response-permission-v4'
        value['permission']['roster_observations'] = sorted(self.roster_observations)
        value['permission']['resource_observations'] = sorted(self.resource_observations)
        return value

    def _emergency_response_permission_successor_snapshot_6(self):
        value = self._emergency_response_permission_successor_snapshot_7()
        value['schema'] = 'rescopebench-emergency-response-permission-snapshot/v3'
        value['schedule_version'] = 'emergency-response-permission-v3'
        return value

    def _emergency_response_permission_successor_snapshot_7(self):
        value = self._persistent_emergency_dispatch_adapter_snapshot()
        value['schema'] = 'rescopebench-emergency-response-permission-snapshot/v2'
        value['permission'] = {'responsibility_changed': self.responsibility_changed, 'order_observations': sorted(self.order_observations), 'incident_observations': sorted(self.incident_observations), 'confirmed_authority_atoms': sorted(self.confirmed_authority_atoms), 'tool_surface_sha256': fn_digest(DATA_PROVIDER_TOOLS_2)}
        return value

    def _persistent_emergency_dispatch_adapter_snapshot(self):
        value = self._emergency_dispatch_adapter_snapshot()
        value.update({'schema': 'rescopebench-emergency-response-stream-snapshot/v1', 'activated_tasks': list(self._activated_tasks), 'active_receipt_start': self._active_receipt_start})
        return value

    def _emergency_dispatch_adapter_snapshot(self):
        return {'raw': mod_copy.deepcopy(self.manager.snapshot()), 'db_id_counters': mod_copy.deepcopy(self.manager.db._id_counters), 'remaining': self.remaining, 'receipts': mod_copy.deepcopy(self.receipts), 'applied_boundary_events': sorted(self.applied_boundary_events), 'policy_version': self.policy_version, 'active_task_id': self.active_task_id}