Download cases/emergency_response/runtime.py from JoeYing/ReScopeBench: direct link, hf CLI and curl.
- Browser
- Download file 60.5 kB
-
https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/emergency_response/runtime.py
- Command line
-
hf download hf://datasets/JoeYing/ReScopeBench/cases/emergency_response/runtime.py
-
curl -L -o runtime.py https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/emergency_response/runtime.py
60.5 kB
| """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) | |
| 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} | |
| 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} | |