File size: 44,255 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
"""Released environment operations and snapshot validation."""
from __future__ import annotations
from copy import deepcopy as ext_deepcopy
from datetime import datetime as ext_datetime
from datetime import timedelta as ext_timedelta
from datetime import timezone as ext_timezone
from pathlib import Path as ext_Path
from rescopebench.raw_module_isolation import isolated_package_namespace as ext_isolated_package_namespace
from rescopebench.raw_module_isolation import load_isolated_modules as ext_load_isolated_modules
from typing import Any as ext_Any
import copy as mod_copy
import hashlib as mod_hashlib
import json as mod_json
from .spec import CASE_DIR, DATA_TASK_IDS, DATA_SCHEDULE_2, DATA_POST_DRIFT_POLICY_OVERRIDES, DATA_CHANGED_RULE_IDS, DATA_PRE_RULES, DATA_PROFILE_REQUIREMENTS, DATA_CARE_TIERS, DATA_REQUEST_CLASSES, DATA_ALLOWED_TOOLS, DATA_READ_COSTS, DATA_WRITE_COSTS, DATA_POLICY_MATRIX, DATA_POLICY_PROFILE_IDS, DATA_REPLACEMENTS, DATA_STRUCTURE_BY_ID, DATA_TOOL_SCHEMAS, DATA_LIMIT_SCHEMA, DATA_TASK_BLUEPRINT, DATA_STREAM_TARGETS, DATA_CHANGED_RULE_IDS_2, DATA_T01_TARGETS

def fn_delivered_grade(original):
    grade = ext_deepcopy(original)
    for artifact in grade['artifacts']:
        artifact['observation_diagnostics'] = artifact['milestones']
        committed = bool(artifact['complete'])
        artifact['milestones'] = {'source_encounter_linked': committed, 'eligible_slot_booked': committed, 'follow_up_committed': committed}
        artifact['score'] = 25.0 if committed else 0.0
    grade['score'] = sum((row['score'] for row in grade['artifacts']))
    grade['score_basis'] = 'committed_policy_compliant_followups_only'
    return grade

def fn_targets(task_id):
    rows = list(ext_deepcopy(fn_targets_2(task_id)))
    if task_id == 'T13':
        rows[0]['request_class'] = 'routine_review'
        rows[0]['rule_atom_id'] = fn_rule_atom_id(rows[0]['care_tier'], 'routine_review')
    if task_id == 'T15':
        rows[3]['request_class'] = 'care_plan_update'
        rows[3]['rule_atom_id'] = fn_rule_atom_id(rows[3]['care_tier'], 'care_plan_update')
    return tuple(rows)

def fn_rule_atom_id(care_tier, request_class):
    return f'R{DATA_CARE_TIERS.index(care_tier) * len(DATA_REQUEST_CLASSES) + DATA_REQUEST_CLASSES.index(request_class) + 1:02d}'

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

def fn_candidate_slots(target):
    date = ext_datetime.fromisoformat(target['date'] + 'T09:00:00+00:00')
    combinations = ((target['source_practitioner_id'], 'in_person'), (target['alternate_practitioner_id'], 'in_person'), (target['source_practitioner_id'], 'virtual'), (target['alternate_practitioner_id'], 'virtual'))
    rows = []
    for (index, (practitioner_id, visit_mode)) in enumerate(combinations):
        start = date + ext_timedelta(hours=index)
        end = start + ext_timedelta(minutes=30)
        practitioner_slug = practitioner_id.removeprefix('practitioner-')
        patient_slug = target['patient_id'].removeprefix('patient-')
        rows.append({'slot_id': f"slot-followup-{patient_slug}-{start.strftime('%Y-%m-%dt%H-%M-%S').lower()}-{practitioner_slug}", 'site_id': target['site_id'], 'practitioner_id': practitioner_id, 'specialty': target['specialty'], 'visit_mode': visit_mode, 'start_at': start.astimezone(ext_timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'), 'end_at': end.astimezone(ext_timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'), 'slot_status': 'open', 'booking_hold_reason': None, 'created_at': '2026-05-25T12:00:00Z', 'updated_at': '2026-05-25T12:00:00Z'})
    return rows

def fn_policy_cell(care_tier, request_class):
    behavior = DATA_POLICY_MATRIX[care_tier][request_class]
    return {'policy_id': f'followup-v1-{care_tier}-{request_class}', 'care_tier': care_tier, 'request_class': request_class, 'routing_profile_id': DATA_POLICY_PROFILE_IDS[care_tier][request_class], 'routing_behavior': behavior, **DATA_PROFILE_REQUIREMENTS[behavior], 'policy_version': 'followup-routing-v1'}

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

def fn_targets_2(task_id):
    rows = [ext_deepcopy(row) for row in fn_stream_targets(task_id)]
    for (slot, (structure_id, request_class)) in DATA_REPLACEMENTS.get(task_id, {}).items():
        row = rows[slot - 1]
        row.update(ext_deepcopy(DATA_STRUCTURE_BY_ID[structure_id]))
        row.update({'structure_atom_id': structure_id, 'request_class': request_class, 'rule_atom_id': fn_rule_atom_id(row['care_tier'], request_class), 'date': fn__stream_date(int(task_id[1:]), row['care_tier'])})
    return tuple(rows)

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

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']}"
    return None

def fn__bounded_limit(arguments):
    if not isinstance(arguments, dict):
        return int(DATA_LIMIT_SCHEMA['default'])
    value = arguments.get('limit', DATA_LIMIT_SCHEMA['default'])
    if not isinstance(value, int) or isinstance(value, bool):
        return int(DATA_LIMIT_SCHEMA['default'])
    if not DATA_LIMIT_SCHEMA['minimum'] <= value <= DATA_LIMIT_SCHEMA['maximum']:
        return int(DATA_LIMIT_SCHEMA['default'])
    return value

def fn_stream_targets(task_id):
    if task_id not in DATA_TASK_BLUEPRINT:
        raise ValueError(f'unknown stream task: {task_id}')
    if task_id == 'T01':
        return tuple(ext_deepcopy(fn_stream_targets_2(task_id)))
    position = int(task_id[1:])
    targets = []
    for (slot, (structure_id, request_class)) in enumerate(DATA_TASK_BLUEPRINT[task_id], 1):
        target = ext_deepcopy(DATA_STRUCTURE_BY_ID[structure_id])
        target.update({'date': fn__stream_date(position, target['care_tier']), 'task_id': task_id, 'slot': slot, 'request_id': f'followup-request-{position:02d}-{slot:02d}', 'request_class': request_class, 'structure_atom_id': structure_id, 'rule_atom_id': fn_rule_atom_id(target['care_tier'], request_class), 'epoch': 'pre' if position <= 8 else 'post'})
        targets.append(target)
    return tuple(targets)

def fn__stream_date(position, care_tier):
    if position == 1:
        raise ValueError('T01 retains its frozen representative dates')
    start = ext_datetime(2026, 7, 1, tzinfo=ext_timezone.utc)
    value = start + ext_timedelta(days=(position - 2) * 7 + DATA_CARE_TIERS.index(care_tier))
    return value.strftime('%Y-%m-%d')

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_stream_targets_2(task_id):
    targets = list(ext_deepcopy(DATA_STREAM_TARGETS[task_id]))
    if task_id in {'T08', 'T09'}:
        targets.sort(key=lambda row: row['rule_atom_id'] in DATA_CHANGED_RULE_IDS_2)
    return tuple(targets)

def fn__load_isolated_runtime(source):

    def initialize(modules):
        (healthcare_logic, server) = modules
        healthcare_logic.now_iso = lambda : '2026-05-25T12:00:00Z'
        server.load_tools()
        server.init_database(str(source / 'data'))
        return server.get_state_manager()
    (modules, manager) = ext_load_isolated_modules(source, ('mcp_servers.healthcare_logic', 'mcp_servers.server'), initialize=initialize)
    assert manager is not None
    return (modules[0], modules[1], manager)

class World:

    def grade(self):
        return fn_delivered_grade(self._appointment_adapter_grade())

    def snapshot(self):
        value = self._medical_portable_world_snapshot()
        if not getattr(self, '_restoring_delivery', False):
            value['delivery_scoring_contract'] = 'medical-delivered-followups-evolution-v5'
        return value

    def restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        if value.pop('delivery_scoring_contract', None) != 'medical-delivered-followups-evolution-v5':
            raise ValueError('Medical delivered-followup snapshot version differs')
        self._restoring_delivery = True
        try:
            self._medical_portable_world_restore(value)
        finally:
            self._restoring_delivery = False
        if self.snapshot() != snapshot:
            raise ValueError('Medical delivered-followup snapshot did not round trip')

    def _priority_guard(self, arguments):
        return None

    def activate_task(self, task_id):
        if task_id not in DATA_TASK_IDS:
            raise ValueError('unknown Medical task')
        if self.active_task_id == task_id and self.activation_ledger:
            return {'status': 'success', 'task_id': task_id, 'idempotent': True, 'entry_lineage_hash': self.lineage_hash()}
        if task_id != f'T{len(self.activation_ledger) + 1:02d}':
            raise ValueError('out-of-order Medical task activation')
        (before_semantic, before_business) = (self.semantic_hash(), self.business_hash())
        drift = None
        if int(task_id[1:]) == DATA_SCHEDULE_2['events'][0]['before_task']:
            drift = self.apply_policy_drift('followup-routing-v2-onset', DATA_POST_DRIFT_POLICY_OVERRIDES)
            for atom in DATA_CHANGED_RULE_IDS:
                self.rule_revalidation.setdefault(atom, 'awaiting_exact_stale')
        self.active_task_id = task_id
        self.active_targets = fn_targets(task_id)
        self._install_follow_up_fixture(self.active_targets)
        self.active_by_patient = {row['patient_id']: row for row in self.active_targets}
        self.remaining = self.initial_budget
        self.episode_receipt_start = len(self.receipts)
        event = {'sequence': len(self.activation_ledger) + 1, 'task_id': task_id, 'event_id': f'activate-{task_id.lower()}', 'drift_event_id': 'followup-routing-v2-onset' if drift else None, 'drift_applied': bool(drift and (not drift.get('idempotent'))), 'before_semantic_hash': before_semantic, 'before_business_hash': before_business, 'entry_semantic_hash': self.semantic_hash(), 'entry_business_hash': self.business_hash(), 'receipt_start': self.episode_receipt_start, 'request_ids': [row['request_id'] for row in self.active_targets]}
        self.activation_ledger.append(ext_deepcopy(event))
        return {'status': 'success', 'idempotent': False, **ext_deepcopy(event), 'entry_lineage_hash': self.lineage_hash()}

    def _policy_evidence(self, care_tier, request_class):
        result = World._medical_rule_successor_policy_evidence(self, care_tier, request_class)
        atom = fn_rule_atom_id(care_tier, request_class)
        if self.rule_revalidation.get(atom) in {'awaiting_exact_stale', 'awaiting_fresh_policy'}:
            self.rule_revalidation[atom] = 'ready_current'
        return result

    def __init__(self, source=CASE_DIR / 'raw', budget=72):
        self.rule_revalidation: dict[str, str] = {}
        self._medical_rule_successor_init(source=source, budget=budget)

    def semantic_hash(self):
        return fn_digest({'base': self._appointment_adapter_semantic_hash(), 'rule_revalidation': self.rule_revalidation})

    def _target_for_source(self, source_appointment_id):
        return next((target for target in self.active_targets if target['source_appointment_id'] == source_appointment_id), None)

    def _matches_rule_tuple(self, target, slot, arguments, rule):
        same_practitioner = slot.get('practitioner_id') == target['source_practitioner_id']
        relation_matches = same_practitioner if rule['practitioner_relation'] == 'source_practitioner' else not same_practitioner
        return bool(arguments.get('routing_profile_id') == rule['routing_profile_id'] and slot.get('site_id') == target['site_id'] and (slot.get('specialty') == target['specialty']) and (slot.get('visit_mode') == rule['visit_mode']) and str(slot.get('start_at', '')).startswith(target['date']) and relation_matches)

    def _follow_up_guard(self, arguments):
        priority_error = self._priority_guard(arguments)
        if priority_error is not None:
            return priority_error
        target = self._target_for_source(arguments.get('source_appointment_id', ''))
        if target is not None:
            atom_id = target['rule_atom_id']
            if self.rule_revalidation.get(atom_id) == 'awaiting_exact_stale':
                slot = self.manager.get_entity('schedule_slot', arguments.get('new_slot_id', ''), id_field='slot_id')
                if slot is not None and self._matches_rule_tuple(target, slot, arguments, DATA_PRE_RULES[atom_id]):
                    self.rule_revalidation[atom_id] = 'awaiting_fresh_policy'
        return self._medical_rule_successor_follow_up_guard(arguments)

    def dispatch(self, tool, arguments, actor='follow_up_scheduler'):
        target = None
        if tool == 'create_follow_up_appointment' and isinstance(arguments, dict):
            target = self._target_for_source(arguments.get('source_appointment_id', ''))
        result = self._medical_rule_successor_dispatch(tool, arguments, actor)
        if target is not None and result.get('content', {}).get('status') == 'success' and (target['rule_atom_id'] in self.rule_revalidation):
            self.rule_revalidation[target['rule_atom_id']] = 'validated'
            if self.receipts and self.receipts[-1]['index'] == result.get('receipt_index'):
                self.receipts[-1]['after_hash'] = self.semantic_hash()
        return result

    def _cost(self, tool, arguments):
        if tool == 'get_patient_scheduling_context':
            return 16
        return self._appointment_adapter_cost(tool, arguments)

    def _slot_observed_in_current_episode(self, slot_id):
        for receipt in self.current_episode_receipts():
            if receipt.get('tool') != 'search_appointment_slots' or receipt.get('status') != 'success':
                continue
            if any((slot.get('slot_id') == slot_id for slot in receipt.get('observed', {}).get('slots', []))):
                return True
        return False

    def _patient_context(self, patient_id):
        result = self._medical_rule_successor_patient_context(patient_id)
        if result.get('content', {}).get('status') == 'success':
            result = ext_deepcopy(result)
            result['content']['data'].pop('routing_policy_epoch', None)
        return result

    @property
    def routing_epoch(self):
        return 'routing-epoch-8f34' if self.policy_overrides else 'routing-epoch-5c21'

    def apply_policy_drift(self, event_id, changed_cells):
        result = self._appointment_adapter_apply_policy_drift(event_id, changed_cells)
        result.pop('changed_cells', None)
        result['public_notice'] = ''
        return result

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

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

    def _manager_snapshot(self):
        with ext_isolated_package_namespace(self.source):
            return self.manager.snapshot()

    def _install_follow_up_fixture(self, targets):
        for target in targets:
            patient = self.manager.get_entity('patient_profile', target['patient_id'], id_field='patient_id')
            source = self.manager.get_entity('appointment', target['source_appointment_id'], id_field='appointment_id')
            site = self.manager.get_entity('clinic_site', target['site_id'], id_field='site_id')
            source_slot = self.manager.get_entity('schedule_slot', source.get('slot_id', '') if source else '', id_field='slot_id')
            alternate = self.manager.get_entity('practitioner', target['alternate_practitioner_id'], id_field='practitioner_id')
            if patient is None or source is None or site is None or (source_slot is None) or (alternate is None):
                raise RuntimeError(f"missing follow-up fixture source for {target['patient_id']}")
            if patient.get('care_tier') != target['care_tier']:
                raise RuntimeError(f"care-tier drift for {target['patient_id']}")
            fixture_checks = {'patient': source.get('patient_id') == target['patient_id'], 'completed_source': source.get('status') == 'completed', 'patient_home_site': patient.get('primary_site_id') == target['site_id'], 'source_site': source.get('site_id') == target['site_id'], 'source_practitioner': source.get('practitioner_id') == target['source_practitioner_id'], 'source_specialty': source_slot.get('specialty') == target['specialty'], 'schedulable_site': site.get('operating_status') in {'open', 'limited'}, 'virtual_capability': site.get('supports_virtual') is True}
            if not all(fixture_checks.values()):
                failed = sorted((name for (name, passed) in fixture_checks.items() if not passed))
                raise RuntimeError(f"invalid follow-up fixture for {target['patient_id']}: {', '.join(failed)}")
            self.manager.update_entity('appointment', target['source_appointment_id'], {'follow_up_required': True}, id_field='appointment_id')
            for slot in fn_candidate_slots(target):
                if self.manager.get_entity('schedule_slot', slot['slot_id'], id_field='slot_id') is None:
                    self.manager.add_entity('schedule_slot', slot, id_field='slot_id')

    def _result(self, tool, status, data=None, message=''):
        return {'type': 'tool_result', 'tool': tool, 'content': {'status': status, 'data': data or {}, 'message': message}}

    def _error(self, tool, code, message, cost=0):
        result = self._result(tool, 'error', message=f'{code}: {message}')
        result['budget'] = {'charged': cost, 'remaining': self.remaining}
        return result

    def _record(self, tool, actor, arguments, cost, before_hash, result):
        receipt = {'index': len(self.receipts) + 1, 'tool': tool, 'actor': actor, 'arguments': mod_copy.deepcopy(arguments), 'status': result.get('content', {}).get('status'), 'observed': mod_copy.deepcopy(result.get('content', {}).get('data', {})), '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 _current_policy(self, care_tier, request_class):
        row = fn_policy_cell(care_tier, request_class)
        override = self.policy_overrides.get((care_tier, request_class))
        if override is not None:
            row['routing_profile_id'] = override['routing_profile_id']
            row['routing_behavior'] = override['routing_behavior']
            row.update(DATA_PROFILE_REQUIREMENTS[override['routing_behavior']])
            row['policy_version'] = 'followup-routing-v2'
        return row

    def business_hash(self):
        return mod_hashlib.sha256(fn__canonical(self._manager_snapshot()['database']).encode('utf-8')).hexdigest()

    def lineage_hash(self):
        payload = {'semantic_hash': self.semantic_hash(), 'initial_budget': self.initial_budget, 'active_task_id': self.active_task_id, 'active_request_ids': [row.get('request_id') for row in self.active_targets], 'episode_receipt_start': self.episode_receipt_start, 'activation_ledger': self.activation_ledger}
        return mod_hashlib.sha256(fn__canonical(payload).encode('utf-8')).hexdigest()

    def _episode_receipts(self):
        return self.receipts[self.episode_receipt_start:]

    def _observed_context(self, patient_id):
        return any((receipt.get('tool') == 'get_patient_scheduling_context' and receipt.get('status') == 'success' and (receipt.get('observed', {}).get('patient_id') == patient_id) for receipt in self._episode_receipts()))

    def _observed_eligible_slot(self, target):
        expected = self._current_policy(target['care_tier'], target['request_class'])
        for receipt in self._episode_receipts():
            if receipt.get('tool') != 'search_appointment_slots' or receipt.get('status') != 'success':
                continue
            for slot in receipt.get('observed', {}).get('slots', []):
                same_practitioner = slot.get('practitioner_id') == target['source_practitioner_id']
                relation_matches = same_practitioner if expected['practitioner_relation'] == 'source_practitioner' else not same_practitioner
                if slot.get('site_id') == target['site_id'] and slot.get('specialty') == target['specialty'] and (slot.get('visit_mode') == expected['visit_mode']) and str(slot.get('start_at', '')).startswith(target['date']) and relation_matches:
                    return True
        return False

    def _appointment_adapter_grade(self):
        database = self._manager_snapshot()['database']
        appointments = database.get('appointment', [])
        slots = {row.get('slot_id'): row for row in database.get('schedule_slot', [])}
        artifacts = []
        for target in self.active_targets:
            expected = self._current_policy(target['care_tier'], target['request_class'])
            matches = [row for row in appointments if row.get('follow_up_for_appointment_id') == target['source_appointment_id']]
            source = self.manager.get_entity('appointment', target['source_appointment_id'], id_field='appointment_id')
            appointment: dict[str, ext_Any] = {}
            for candidate in reversed(matches):
                candidate_slot = slots.get(candidate.get('slot_id'), {})
                same_practitioner = candidate_slot.get('practitioner_id') == target['source_practitioner_id']
                relation_matches = same_practitioner if expected['practitioner_relation'] == 'source_practitioner' else bool(candidate_slot) and (not same_practitioner)
                if candidate.get('status') == 'scheduled' and candidate.get('patient_id') == target['patient_id'] and (candidate_slot.get('slot_status') == 'booked') and (candidate_slot.get('site_id') == target['site_id']) and (candidate_slot.get('specialty') == target['specialty']) and (candidate_slot.get('visit_mode') == expected['visit_mode']) and str(candidate_slot.get('start_at', '')).startswith(target['date']) and relation_matches:
                    appointment = candidate
                    break
            completed = bool(appointment and source is not None and (source.get('follow_up_required') is False))
            milestones = {'context_resolved': completed or self._observed_context(target['patient_id']), 'eligible_slot_identified': completed or self._observed_eligible_slot(target), 'follow_up_committed': completed}
            score = 25.0 if completed else 2.5 * milestones['context_resolved'] + 2.5 * milestones['eligible_slot_identified']
            artifacts.append({'patient_id': target['patient_id'], 'request_class': target['request_class'], 'score': score, 'complete': completed, 'appointment_id': appointment.get('appointment_id'), 'slot_id': appointment.get('slot_id'), 'milestones': milestones})
        return {'task_id': self.active_task_id, 'score': sum((row['score'] for row in artifacts)), 'completed_artifacts': sum((row['complete'] for row in artifacts)), 'artifacts': artifacts}

    def _medical_portable_world_snapshot(self):
        value = World._medical_context_world_snapshot(self)
        value['active_targets'] = list(value['active_targets'])
        value['independent_followups_contract'] = 'medical-independent-portable-evolution-v4'
        return value

    def _medical_portable_world_restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        if value.pop('independent_followups_contract', None) != 'medical-independent-portable-evolution-v4':
            raise ValueError('Medical portable-followup snapshot version differs')
        World._medical_context_world_restore(self, value)
        if self.snapshot() != snapshot:
            raise ValueError('Medical portable-followup snapshot did not round trip')

    def _medical_rule_successor_policy_evidence(self, care_tier, request_class):
        old = fn_policy_cell(care_tier, request_class)
        current = self._current_policy(care_tier, request_class)
        rows = [old]
        if current != old:
            rows.append(current)
        evidence = []
        for row in rows:
            candidate = {key: ext_deepcopy(value) for (key, value) in row.items() if key != 'policy_version'}
            candidate['evidence_id'] = 'PE-' + fn_digest({'care_tier': care_tier, 'request_class': request_class, 'routing_profile_id': row['routing_profile_id']})[:12].upper()
            evidence.append(candidate)
        evidence.sort(key=lambda row: row['evidence_id'])
        return self._result('get_follow_up_policy', 'success', {'care_tier': care_tier, 'request_class': request_class, 'evidence': evidence})

    def _medical_rule_successor_init(self, source=CASE_DIR / 'raw', budget=72):
        self._medical_rule_successor_init_2(source=source, budget=budget)

    def _appointment_adapter_semantic_hash(self):
        payload = {'database': self._manager_snapshot()['database'], 'remaining': self.remaining, 'receipts': self.receipts, 'policy_overrides': sorted(((care_tier, request_class, fn__canonical(profile)) for ((care_tier, request_class), profile) in self.policy_overrides.items())), 'boundary_events': sorted(self.applied_boundary_events)}
        return mod_hashlib.sha256(fn__canonical(payload).encode('utf-8')).hexdigest()

    def _medical_rule_successor_follow_up_guard(self, arguments):
        if not self._slot_observed_in_current_episode(arguments['new_slot_id']):
            return self._error('create_follow_up_appointment', 'SLOT_EVIDENCE_REQUIRED', 'the selected slot must be observed by a successful search in this episode')
        return self._appointment_adapter_follow_up_guard(arguments)

    def _medical_rule_successor_dispatch(self, tool, arguments, actor='follow_up_scheduler'):
        if tool != 'get_follow_up_policy':
            return self._appointment_adapter_dispatch(tool, arguments, actor)
        if actor != 'follow_up_scheduler':
            return self._error(tool, 'ROLE_FORBIDDEN', 'actor is not a follow-up scheduler')
        if tool not in DATA_ALLOWED_TOOLS:
            return self._error(tool, 'TOOL_FORBIDDEN', 'tool is outside the follow-up slice')
        cost = self._cost(tool, arguments)
        if self.remaining < cost:
            return self._error(tool, 'WORK_QUOTA_EXHAUSTED', 'insufficient API-work quota')
        before_hash = self.semantic_hash()
        validation_error = fn__validate_arguments(tool, arguments)
        self.remaining -= cost
        if validation_error is not None:
            result = self._error(tool, 'INVALID_ARGUMENTS', validation_error, cost)
        else:
            result = self._policy_evidence(arguments['care_tier'], arguments['request_class'])
        return self._record(tool, actor, arguments, cost, before_hash, result)

    def _appointment_adapter_cost(self, tool, arguments):
        if tool in DATA_READ_COSTS:
            return DATA_READ_COSTS[tool]
        if tool == 'search_appointment_slots':
            return 2 + fn__bounded_limit(arguments)
        return DATA_WRITE_COSTS[tool]

    def _medical_rule_successor_patient_context(self, patient_id):
        result = self._appointment_adapter_patient_context(patient_id)
        if result.get('content', {}).get('status') == 'success':
            result = ext_deepcopy(result)
            result['content']['data']['routing_policy_epoch'] = self.routing_epoch
        return result

    def _appointment_adapter_apply_policy_drift(self, event_id, changed_cells):
        if event_id in self.applied_boundary_events:
            return {'status': 'success', 'event_id': event_id, 'idempotent': True}
        for (cell, profile) in changed_cells.items():
            (care_tier, request_class) = cell
            if care_tier not in DATA_POLICY_MATRIX or request_class not in DATA_POLICY_MATRIX[care_tier]:
                raise ValueError(f'unknown policy cell: {cell}')
            behavior = profile.get('routing_behavior')
            profile_id = profile.get('routing_profile_id')
            if behavior not in DATA_PROFILE_REQUIREMENTS:
                raise ValueError(f'unknown routing behavior: {behavior}')
            if not isinstance(profile_id, str) or not profile_id:
                raise ValueError('routing_profile_id must be a non-empty string')
            if profile_id in {value for rows in DATA_POLICY_PROFILE_IDS.values() for value in rows.values()}:
                raise ValueError('drift profile id must differ from every pre-drift id')
            self.policy_overrides[care_tier, request_class] = mod_copy.deepcopy(profile)
        self.applied_boundary_events.add(event_id)
        return {'status': 'success', 'event_id': event_id, 'idempotent': False, 'changed_cells': [f'{a}|{b}' for (a, b) in changed_cells]}

    def _medical_context_world_snapshot(self):
        value = self._medical_evolution_snapshot()
        value['evolution_contract']['case_version'] = 'medical-context-scope-evolution-v2'
        return value

    def _medical_context_world_restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        if value.get('evolution_contract', {}).get('case_version') != 'medical-context-scope-evolution-v2':
            raise ValueError('Medical context-scope snapshot version differs')
        value['evolution_contract']['case_version'] = 'medical-lifecycle-evolution-v1'
        self._medical_evolution_restore(value)

    def _medical_rule_successor_init_2(self, source=CASE_DIR / 'raw', budget=72):
        self._medical_rule_successor_init_3(source=source, budget=budget)

    def _appointment_adapter_follow_up_guard(self, arguments):
        source = self.manager.get_entity('appointment', arguments['source_appointment_id'], id_field='appointment_id')
        if source is None:
            return None
        patient = self.manager.get_entity('patient_profile', source.get('patient_id', ''), id_field='patient_id')
        if patient is None:
            return self._error('create_follow_up_appointment', 'FOLLOW_UP_CONTEXT_INCOMPLETE', 'the source encounter has no patient scheduling context')
        target = self.active_by_patient.get(patient.get('patient_id'))
        if target is None or target['source_appointment_id'] != source.get('appointment_id'):
            return self._error('create_follow_up_appointment', 'FOLLOW_UP_REQUEST_NOT_ACTIVE', 'the source encounter is not the active follow-up request')
        slot = self.manager.get_entity('schedule_slot', arguments['new_slot_id'], id_field='slot_id')
        if slot is None:
            return None
        source_slot = self.manager.get_entity('schedule_slot', source.get('slot_id', ''), id_field='slot_id')
        if source_slot is None:
            return self._error('create_follow_up_appointment', 'FOLLOW_UP_CONTEXT_INCOMPLETE', 'the source encounter has no complete scheduling context')
        if arguments['request_class'] != target['request_class']:
            return self._error('create_follow_up_appointment', 'REQUEST_CLASS_MISMATCH', 'the supplied request class does not match the active request')
        expected = self._current_policy(patient['care_tier'], arguments['request_class'])
        if arguments['routing_profile_id'] != expected['routing_profile_id']:
            return self._error('create_follow_up_appointment', 'FOLLOW_UP_POLICY_MISMATCH', 'the selected routing profile id does not satisfy the current policy cell')
        if slot.get('site_id') != patient.get('primary_site_id'):
            return self._error('create_follow_up_appointment', 'FOLLOW_UP_SITE_MISMATCH', "the selected slot is outside the patient's home-site continuity group")
        if slot.get('specialty') != source_slot.get('specialty'):
            return self._error('create_follow_up_appointment', 'FOLLOW_UP_SPECIALTY_MISMATCH', 'the selected slot does not preserve the source specialty')
        if not str(slot.get('start_at', '')).startswith(target['date']):
            return self._error('create_follow_up_appointment', 'FOLLOW_UP_DATE_MISMATCH', 'the selected slot is outside the active request date')
        if slot.get('visit_mode') != expected['visit_mode']:
            return self._error('create_follow_up_appointment', 'FOLLOW_UP_MODE_MISMATCH', 'the selected slot mode does not satisfy the routing profile')
        same_practitioner = slot.get('practitioner_id') == source.get('practitioner_id')
        relation = expected['practitioner_relation']
        if relation == 'source_practitioner' and (not same_practitioner):
            return self._error('create_follow_up_appointment', 'FOLLOW_UP_CONTINUITY_MISMATCH', 'the selected slot does not preserve source-clinician continuity')
        if relation == 'alternate_same_specialty' and same_practitioner:
            return self._error('create_follow_up_appointment', 'FOLLOW_UP_TEAM_MISMATCH', 'the selected slot does not use an alternate clinician from the specialty team')
        return None

    def _appointment_adapter_dispatch(self, tool, arguments, actor='follow_up_scheduler'):
        if actor != 'follow_up_scheduler':
            return self._error(tool, 'ROLE_FORBIDDEN', 'actor is not a follow-up scheduler')
        if tool not in DATA_ALLOWED_TOOLS:
            return self._error(tool, 'TOOL_FORBIDDEN', 'tool is outside the follow-up slice')
        cost = self._cost(tool, arguments)
        if self.remaining < cost:
            return self._error(tool, 'WORK_QUOTA_EXHAUSTED', 'insufficient API-work quota')
        before_hash = self.semantic_hash()
        validation_error = fn__validate_arguments(tool, arguments)
        self.remaining -= cost
        if validation_error is not None:
            result = self._error(tool, 'INVALID_ARGUMENTS', validation_error, cost)
            return self._record(tool, actor, arguments, cost, before_hash, result)
        if tool == 'get_patient_scheduling_context':
            result = self._patient_context(arguments['patient_id'])
        elif tool == 'get_follow_up_policy':
            result = self._result(tool, 'success', self._current_policy(arguments['care_tier'], arguments['request_class']))
        elif tool == 'search_appointment_slots':
            result = self.server.call_tool(tool, state_manager=self.manager, **arguments)
        else:
            guarded = self._follow_up_guard(arguments)
            if guarded is not None:
                result = guarded
            else:
                raw_arguments = mod_copy.deepcopy(arguments)
                raw_arguments.pop('request_class')
                raw_arguments.pop('routing_profile_id')
                result = self.server.call_tool('create_follow_up_appointment', state_manager=self.manager, **raw_arguments)
                result['tool'] = tool
        return self._record(tool, actor, arguments, cost, before_hash, result)

    def _appointment_adapter_patient_context(self, patient_id):
        target = self.active_by_patient.get(patient_id)
        if target is None:
            return self._error('get_patient_scheduling_context', 'FOLLOW_UP_REQUEST_NOT_ACTIVE', 'no active follow-up request matches this patient')
        patient = self.manager.get_entity('patient_profile', patient_id, id_field='patient_id')
        source = self.manager.get_entity('appointment', target['source_appointment_id'], id_field='appointment_id')
        source_slot = self.manager.get_entity('schedule_slot', source.get('slot_id', '') if source else '', id_field='slot_id')
        if patient is None or source is None or source_slot is None:
            return self._error('get_patient_scheduling_context', 'FOLLOW_UP_CONTEXT_INCOMPLETE', 'the active follow-up dossier is incomplete')
        return self._result('get_patient_scheduling_context', 'success', {'patient_id': patient_id, 'care_tier': patient.get('care_tier'), 'home_site_id': patient.get('primary_site_id'), 'source_appointment_id': source.get('appointment_id'), 'source_status': source.get('status'), 'source_follow_up_required': bool(source.get('follow_up_required')), 'source_practitioner_id': source.get('practitioner_id'), 'source_specialty': source_slot.get('specialty'), 'source_visit_mode': source.get('visit_mode'), 'last_verified': '2026-05-25T12:00:00Z'})

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

    def _medical_evolution_restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        if value.pop('evolution_contract', None) != {'case_version': 'medical-lifecycle-evolution-v1', 'schedule': DATA_SCHEDULE_2}:
            raise ValueError('Medical evolution snapshot contract differs')
        self._medical_rule_successor_restore(value)

    def _medical_rule_successor_init_3(self, source=CASE_DIR / 'raw', budget=132):
        self._appointment_adapter_init(ext_Path(source), budget=budget, auto_activate_t01=False)

    def _medical_rule_successor_snapshot(self):
        value = self._medical_rule_successor_snapshot_2()
        value['schema'] = 'rescopebench-medical-rule-stream/v6'
        value['rule_revalidation'] = ext_deepcopy(self.rule_revalidation)
        return value

    def _medical_rule_successor_restore(self, snapshot):
        if snapshot.get('schema') != 'rescopebench-medical-rule-stream/v6':
            raise ValueError('unsupported Medical rule v6 snapshot')
        value = ext_deepcopy(snapshot)
        self.rule_revalidation = ext_deepcopy(value.pop('rule_revalidation', {}))
        value['schema'] = 'rescopebench-medical-rule-stream/v4'
        self._medical_rule_successor_restore_2(value)

    def _appointment_adapter_init(self, source, budget=56, *, auto_activate_t01=True):
        source = ext_Path(source).resolve()
        self.source = source
        (self.logic, self.server, self.manager) = fn__load_isolated_runtime(source)
        self.initial_budget = int(budget)
        self.remaining = int(budget)
        self.receipts: list[dict[str, ext_Any]] = []
        self.policy_overrides: dict[tuple[str, str], dict[str, str]] = {}
        self.applied_boundary_events: set[str] = set()
        self.active_task_id: str | None = 'T01' if auto_activate_t01 else None
        self.active_targets: tuple[dict[str, ext_Any], ...] = tuple(mod_copy.deepcopy(DATA_T01_TARGETS)) if auto_activate_t01 else ()
        self.active_by_patient: dict[str, dict[str, ext_Any]] = {row['patient_id']: row for row in self.active_targets}
        self.episode_receipt_start = 0
        self.activation_ledger: list[dict[str, ext_Any]] = []
        if auto_activate_t01:
            self._install_follow_up_fixture(self.active_targets)

    def _medical_rule_successor_snapshot_2(self):
        value = self._medical_rule_successor_snapshot_3()
        value['schema'] = 'rescopebench-medical-rule-stream/v4'
        return value

    def _medical_rule_successor_restore_2(self, snapshot):
        if snapshot.get('schema') != 'rescopebench-medical-rule-stream/v4':
            raise ValueError('unsupported Medical rule v4 snapshot')
        value = ext_deepcopy(snapshot)
        value['schema'] = 'rescopebench-medical-rule-stream/v3'
        self._medical_rule_successor_restore_3(value)

    def _medical_rule_successor_snapshot_3(self):
        value = self._medical_rule_successor_snapshot_4()
        value['schema'] = 'rescopebench-medical-rule-stream/v3'
        value['provider_tools_sha256'] = '1d5426ebbfdd2204858a0dabdca9acec0cab6cd23642748680fa0f888237999b'
        return value

    def _medical_rule_successor_restore_3(self, snapshot):
        if snapshot.get('schema') != 'rescopebench-medical-rule-stream/v3':
            raise ValueError('unsupported Medical rule v3 snapshot')
        value = ext_deepcopy(snapshot)
        value['schema'] = 'rescopebench-medical-rule-stream/v2'
        value['provider_tools_sha256'] = self._medical_rule_successor_snapshot_4()['provider_tools_sha256']
        self._medical_rule_successor_restore_4(value)

    def _medical_rule_successor_snapshot_4(self):
        value = self._appointment_adapter_snapshot()
        value['schema'] = 'rescopebench-medical-rule-stream/v2'
        value['provider_tools_sha256'] = '52f5daa6af97aedf70819ce08e378bdf9538e8fa4c3cd28714a74172c75e3260'
        return value

    def _medical_rule_successor_restore_4(self, snapshot):
        if snapshot.get('schema') != 'rescopebench-medical-rule-stream/v2':
            raise ValueError('unsupported Medical rule successor snapshot')
        value = ext_deepcopy(snapshot)
        value.pop('schema', None)
        value.pop('provider_tools_sha256', None)
        self._appointment_adapter_restore(value)

    def _appointment_adapter_snapshot(self):
        return {'raw': mod_copy.deepcopy(self._manager_snapshot()), 'db_id_counters': mod_copy.deepcopy(self.manager.db._id_counters), 'initial_budget': self.initial_budget, 'remaining': self.remaining, 'receipts': mod_copy.deepcopy(self.receipts), 'policy_overrides': {f'{care_tier}|{request_class}': mod_copy.deepcopy(profile) for ((care_tier, request_class), profile) in self.policy_overrides.items()}, 'applied_boundary_events': sorted(self.applied_boundary_events), 'active_task_id': self.active_task_id, 'active_targets': mod_copy.deepcopy(self.active_targets), 'episode_receipt_start': self.episode_receipt_start, 'activation_ledger': mod_copy.deepcopy(self.activation_ledger)}

    def _appointment_adapter_restore(self, snapshot):
        database = mod_copy.deepcopy(snapshot['raw']['database'])
        self.manager.db._data = database
        self.manager.db._id_counters = mod_copy.deepcopy(snapshot.get('db_id_counters', {}))
        for entity_type in database:
            self.manager.db._flush(entity_type)
        self.manager._counters = mod_copy.deepcopy(snapshot['raw'].get('counters', {}))
        self.manager.invalidate_core_state()
        self.initial_budget = int(snapshot.get('initial_budget', self.initial_budget))
        self.remaining = int(snapshot['remaining'])
        self.receipts = mod_copy.deepcopy(snapshot['receipts'])
        self.policy_overrides = {tuple(key.split('|', 1)): mod_copy.deepcopy(value) for (key, value) in snapshot.get('policy_overrides', {}).items()}
        self.applied_boundary_events = set(snapshot.get('applied_boundary_events', []))
        self.active_task_id = snapshot.get('active_task_id', 'T01')
        fallback_targets = DATA_T01_TARGETS if self.active_task_id == 'T01' else ()
        self.active_targets = tuple(mod_copy.deepcopy(snapshot.get('active_targets', fallback_targets)))
        self.active_by_patient = {row['patient_id']: row for row in self.active_targets}
        self.episode_receipt_start = int(snapshot.get('episode_receipt_start', 0))
        self.activation_ledger = mod_copy.deepcopy(snapshot.get('activation_ledger', []))