Download cases/robot/runtime.py from JoeYing/ReScopeBench: direct link, hf CLI and curl.
- Browser
- Download file 188 kB
-
https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/robot/runtime.py
- Command line
-
hf download hf://datasets/JoeYing/ReScopeBench/cases/robot/runtime.py
-
curl -L -o runtime.py https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/robot/runtime.py
188 kB
| """Released environment operations and snapshot validation.""" | |
| from __future__ import annotations | |
| from contextlib import contextmanager | |
| from contextvars import ContextVar | |
| 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.public_projection import assert_hard_public_projection as ext_assert_hard_public_projection | |
| from typing import Any as ext_Any | |
| import hashlib as mod_hashlib | |
| import importlib as mod_importlib | |
| import json as mod_json | |
| import jsonschema as mod_jsonschema | |
| import math as mod_math | |
| import re as _re | |
| import re as mod_re | |
| import shutil as mod_shutil | |
| import sys as mod_sys | |
| import tempfile as mod_tempfile | |
| from .spec import CASE_DIR, DATA_BUSINESS_CALL_LIMITS, DATA_ZONE_ADJACENCY, DATA_ORDERED_MUTATIONS, DATA_CONTRACT, DATA_ORDER_INDEX_BLUEPRINT, DATA_EPISODE_BUDGETS, DATA_TOOLS_2, DATA_TASK_IDS, DATA_SCHEDULE_2, DATA_EPISODE_BUDGETS_2, DATA_CHANGED_HANDLING_ATOMS, DATA_ID_FIELDS, DATA_STATE_TABLES, DATA_ORDER_INDEX_BLUEPRINT_2, DATA_TOOLS_3, DATA__TRAVERSE_PARAMETERS, DATA_TRANSFER_PROFILES, DATA__TOOL_BY_NAME, DATA__ID_FIELDS, DATA_ORDER_INDEX_BLUEPRINT_3, DATA_TOOLS_4, DATA_TOOLS_5, DATA__SNAPSHOT_FIELDS, DATA_TOOLS_6, DATA_INTAKE_CODES, DATA_HANDLING_CODES, DATA__SNAPSHOT_FIELDS_2, DATA__TRANSFER_EVIDENCE_FIELDS, DATA_REVALIDATION_STATES, DATA__PRIVATE_KEYS, DATA_TOOLS_7, DATA__SNAPSHOT_TABLES | |
| _BOUNDARY_TIME = ContextVar('robot_boundary_timestamp', default=None) | |
| def fn_scoped_staging_result(result, target_group): | |
| def visit(value): | |
| if isinstance(value, list): | |
| return [visit(item) for item in value] | |
| if not isinstance(value, dict): | |
| return value | |
| row = {key: visit(child) for (key, child) in value.items()} | |
| if 'access_state' in row and 'storage_handle' in row and ('stock_group' in row) and (row['stock_group'] != target_group): | |
| row.pop('stock_group') | |
| row.pop('calibration_records', None) | |
| row['objects'] = [] | |
| row['matches_pending_stock_group'] = False | |
| row['scope'] = 'current_priority_order' | |
| return row | |
| scoped = visit(result) | |
| if scoped.get('data', {}).get('outcome') == 'retained_source_unavailable' and scoped.get('message') == 'OK': | |
| scoped['message'] = 'RETAINED_SOURCE_UNAVAILABLE: requested parcel is absent from the supplied source' | |
| return scoped | |
| def fn_episode_spec(task_id): | |
| episode = next((row for row in mod_json.loads((CASE_DIR / 'data/world/private/config.json').read_text())['episodes'] if row['episode_id'] == task_id)) | |
| if int(task_id[1:]) >= 9: | |
| for order in episode['orders']: | |
| order['source'] = fn_destinations().get(order['stock_group'], order['source']) | |
| return episode | |
| def fn_destinations(): | |
| return mod_json.loads((CASE_DIR / 'data/assets/design.json').read_text())['destinations'] | |
| def fn_prepare_episode(case, state_dir, episode_id): | |
| (case, state_dir) = (ext_Path(case).resolve(), ext_Path(state_dir).resolve()) | |
| config = fn_read(case / 'private/config.json') | |
| requested = fn__episode(config, episode_id) | |
| episode_budget = fn__episode_budget(config, episode_id) | |
| sm = fn_open_state(case / 'private/world', state_dir) | |
| facility = sm.get_entity('facility', config['facility_id'], id_field='facility_id') | |
| current = facility.get('experience_active_episode') if facility else None | |
| boundary_config = ext_deepcopy(config) | |
| boundary_config['budget'] = episode_budget | |
| if current == episode_id: | |
| receipt = fn__advance_boundary(sm, boundary_config, current, episode_id) | |
| else: | |
| if current is None: | |
| previous_episode_id = None | |
| if episode_id != 'T01': | |
| raise ValueError('a fresh state can only prepare T01') | |
| else: | |
| current_episode = fn__episode(config, current) | |
| if current_episode['next_episode_id'] != episode_id: | |
| raise ValueError('persistent state cannot skip or rewind episodes') | |
| previous_episode_id = current | |
| receipt = fn__advance_boundary(sm, boundary_config, previous_episode_id, episode_id) | |
| return (fn_restore_adapter(case, state_dir, episode_id), receipt) | |
| def fn_public_task(task_id): | |
| task = fn_public_task_2(task_id) | |
| by_index = {row['order_index']: row['work_order'] for row in fn_episode_spec_3(task_id)['orders']} | |
| ordered = [by_index[index] for index in DATA_ORDER_INDEX_BLUEPRINT[task_id]] | |
| marker = '\n\nUse the work-order and local observation tools' | |
| (heading, remainder) = task['query'].split(marker, 1) | |
| task['work_orders'] = ordered | |
| task['query'] = heading.split('\n- ', 1)[0] + '\n- ' + '\n- '.join(ordered) + marker + remainder | |
| task['query'] = mod_re.sub('The starting battery is \\d+ units', f'The starting battery is {DATA_EPISODE_BUDGETS[task_id]} units', task['query'], count=1) | |
| task['query'] = task['query'].replace('and at most one previously unseen stock binding can be authorized in this episode. ', 'and each newly verified binding remains provisional until its own order closes. ') | |
| task['budget'] = {'battery_units': DATA_EPISODE_BUDGETS[task_id], 'business_call_limit': DATA_BUSINESS_CALL_LIMITS[task_id]} | |
| return task | |
| def fn__zone_for_room_id(room_id): | |
| if not isinstance(room_id, str): | |
| return None | |
| for (token, zone) in (('-ground-', 'Zone-Ground'), ('-level-one-', 'Zone-Level-One'), ('-level-two-', 'Zone-Level-Two'), ('-mezzanine-', 'Zone-Mezzanine')): | |
| if token in room_id: | |
| return zone | |
| return None | |
| def fn__profiles(): | |
| prepare = next((row for row in DATA_TOOLS_2 if row['function']['name'] == 'prepare_transfer')) | |
| return tuple(prepare['function']['parameters']['properties']['profile']['enum']) | |
| def fn_checkpoint_state(adapter, state_dir): | |
| return fn_checkpoint_state_2(adapter, state_dir) | |
| def fn_load_config(): | |
| return mod_json.loads((CASE_DIR / 'data/world/private/config.json').read_text(encoding='utf-8')) | |
| def fn_episode_spec_2(task_id): | |
| if task_id not in DATA_TASK_IDS: | |
| raise ValueError(f'unknown Robot stream task: {task_id}') | |
| return ext_deepcopy(next((row for row in fn_load_config()['episodes'] if row['episode_id'] == task_id))) | |
| def fn_restore_adapter(case, state_dir, task_id, **kwargs): | |
| adapter = fn_adapter_for(case, state_dir, task_id, **kwargs) | |
| ledger = kwargs.get('observation_ledger') | |
| path = ext_Path(state_dir) / 'observation-ledger.json' | |
| if ledger is None and path.is_file(): | |
| ledger = mod_json.loads(path.read_text()) | |
| if ledger is not None: | |
| fn_retain_observed_identities(adapter, ledger, task_id) | |
| return adapter | |
| def fn_scoped_storage_diagnostics(value, object_name): | |
| """A failed compound action must not return the underlying unfiltered store.""" | |
| if isinstance(value, dict): | |
| return {key: [fn_scoped_storage_diagnostics(row, object_name) for row in child if isinstance(row, dict) and row.get('display_name') == object_name] if key == 'objects' and isinstance(child, list) else fn_scoped_storage_diagnostics(child, object_name) for (key, child) in value.items()} | |
| if isinstance(value, list): | |
| return [fn_scoped_storage_diagnostics(child, object_name) for child in value] | |
| return value | |
| def fn_read(path): | |
| return fn_read_2(path) | |
| def fn__episode(config, episode_id): | |
| row = next((item for item in config['episodes'] if item['episode_id'] == episode_id), None) | |
| if row is None: | |
| raise ValueError(f'unknown episode: {episode_id}') | |
| return row | |
| def fn__episode_budget(config, episode_id): | |
| episode = fn__episode(config, episode_id) | |
| value = episode.get('budget', config.get('budget')) | |
| if type(value) is not int or value <= 0: | |
| raise ValueError(f'invalid budget for {episode_id}: {value!r}') | |
| return value | |
| def fn_open_state(world_dir, state_dir): | |
| """Open persistent stream state, seeding it from the world only once.""" | |
| world_dir = ext_Path(world_dir).resolve() | |
| state_dir = ext_Path(state_dir).resolve() | |
| environment = world_dir / 'environment' | |
| source_database = environment / 'data' / 'database' | |
| if not source_database.is_dir(): | |
| raise FileNotFoundError(source_database) | |
| state_dir.mkdir(parents=True, exist_ok=True) | |
| state_database = state_dir / 'database' | |
| if not state_database.exists(): | |
| mod_shutil.copytree(source_database, state_database) | |
| elif not state_database.is_dir(): | |
| raise NotADirectoryError(state_database) | |
| environment_path = str(environment) | |
| if environment_path in mod_sys.path: | |
| mod_sys.path.remove(environment_path) | |
| mod_sys.path.insert(0, environment_path) | |
| from mcp_servers.state.state_manager import StateManager | |
| return StateManager(db_path=str(state_dir)) | |
| def fn__advance_boundary(sm, config, previous_episode_id, next_episode_id): | |
| token = _BOUNDARY_TIME.set(fn__logical_boundary_time(fn_semantic_state(sm))) | |
| try: | |
| return fn_advance_boundary(sm, config, previous_episode_id, next_episode_id) | |
| finally: | |
| _BOUNDARY_TIME.reset(token) | |
| def fn_public_task_2(task_id): | |
| task = fn_public_task_3(task_id) | |
| budget = DATA_EPISODE_BUDGETS_2[task_id] | |
| (query, count) = mod_re.subn('The starting battery is \\d+ units', f'The starting battery is {budget} units', task['query'], count=1) | |
| if count != 1: | |
| raise ValueError(f'Robot {task_id} public budget sentence changed upstream') | |
| task['query'] = query.rstrip() + f' Use locate_order_zone for the first pending listed order before cold search. Search is target-scoped: unrelated cabinets do not reveal their stock group or parcel identities, and at most one previously unseen stock binding can be authorized in this episode. The external business-tool limit is {32} calls, including rejected calls. Prefer execute_transfer_attempt once explicit route handles and an exact profile candidate are available. Benchmark credit is awarded only for fully closed work orders; partial milestones are diagnostics.' | |
| task['budget'] = {'battery_units': budget, 'business_call_limit': 32, 'new_stock_binding_limit': 1} | |
| task['scoring'] = {'complete_work_order_points': 25.0, 'partial_milestones': 'diagnostic_only'} | |
| return task | |
| def fn_episode_spec_3(task_id): | |
| return ext_deepcopy(fn_episode_spec_4(task_id)) | |
| def fn_checkpoint_state_2(adapter, state_dir): | |
| ledger = adapter.export_observation_ledger() | |
| path = fn__ledger_path(ext_Path(state_dir)) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(mod_json.dumps(ledger, indent=2, sort_keys=True, ensure_ascii=True) + '\n', encoding='utf-8') | |
| return {'ledger': ledger, 'sha256': fn_digest(ledger), 'path': str(path.resolve())} | |
| def fn_adapter_for(case, state_dir, episode_id, *, observation_ledger=None, rule_epoch_override=None, public_policy_version_override=None): | |
| (case, state_dir) = (ext_Path(case).resolve(), ext_Path(state_dir).resolve()) | |
| config = fn_read_3(case / 'private/config.json') | |
| episode = fn__episode_3(config, episode_id) | |
| sm = fn_open_state(case / 'private/world', state_dir) | |
| facility = sm.get_entity('facility', config['facility_id'], id_field='facility_id') | |
| if facility is None or facility.get('experience_active_episode') != episode_id: | |
| raise ValueError('episode has not been prepared in this persistent state') | |
| rule_epoch = rule_epoch_override or episode['rule_epoch'] | |
| private_version = public_policy_version_override or episode['public_policy_version'] | |
| rule_table = config['pre_rule_table'] if rule_epoch == 'pre' else config['post_rule_table'] | |
| adapter = RobotExperienceStreamAdapter(sm, robot_id=config['robot_id'], handle_seed=config['handle_seed'], task_ids=[row['task_id'] for row in episode['orders']], rubric=fn__rubric(config, episode), rule_table=rule_table, active_object_ids={row['object_id'] for row in episode['orders']}, public_policy_version=private_version, expected_rule_epoch=rule_epoch, facility_id=config['facility_id']) | |
| adapter._construction_environment = str((case / 'private/world/environment').resolve()) | |
| ledger = observation_ledger | |
| ledger_path = fn__ledger_path(state_dir) | |
| if ledger is None and ledger_path.is_file(): | |
| ledger = fn_read_3(ledger_path) | |
| if ledger is not None: | |
| adapter.import_observation_ledger(ledger) | |
| return adapter | |
| def fn_retain_observed_identities(adapter, ledger, task_id): | |
| """Past visibility survives relocation; current action permissions do not change.""" | |
| requested = ledger.get('object_handles', []) | |
| if not isinstance(requested, list) or not all((isinstance(h, str) for h in requested)): | |
| raise ValueError('object_handles must be a list of strings') | |
| position = int(task_id[1:]) | |
| prefix = {f'T{i:02d}' for i in range(1, position + 1)} | |
| objects = {row['object_id'] for row in adapter._all('object_item')} | |
| past = {row.get('object_id') for row in adapter._all('service_task') if row.get('experience_episode_id') in prefix} | |
| allowed = {adapter._handle('object', key) for key in objects & past} | |
| if not set(requested) <= allowed: | |
| raise ValueError('Observed identity must belong to an existing prefix object') | |
| adapter.issued_object_handles.update(requested) | |
| def fn_public_retained_source_evidence(evidence): | |
| """Project retained source evidence onto fields safe for the learner.""" | |
| return {key: str(evidence[key]) for key in ('station', 'storage_handle', 'zone') if isinstance(evidence.get(key), str)} | |
| def fn_read_2(path): | |
| return fn_read_4(path) | |
| def fn__logical_boundary_time(state): | |
| timestamps = [] | |
| for rows in state.values(): | |
| for row in rows: | |
| for field in ('created_at', 'updated_at', 'completed_at', 'released_at', 'accepted_at'): | |
| value = row.get(field) | |
| if not isinstance(value, str) or not value: | |
| continue | |
| parsed = ext_datetime.fromisoformat(value.replace('Z', '+00:00')) | |
| timestamps.append(parsed.replace(tzinfo=ext_timezone.utc) if parsed.tzinfo is None else parsed) | |
| if not timestamps: | |
| raise ValueError('Robot boundary requires a timestamped source state') | |
| return (max(timestamps).astimezone(ext_timezone.utc) + ext_timedelta(seconds=1)).strftime('%Y-%m-%dT%H:%M:%SZ') | |
| def fn_semantic_state(sm): | |
| return {table: sorted((ext_deepcopy(row) for row in sm.list_entities(table)), key=lambda row: str(row.get(DATA_ID_FIELDS[table], ''))) for table in DATA_STATE_TABLES} | |
| def fn_advance_boundary(sm, config, previous_episode_id, next_episode_id): | |
| """Advance persistent state without announcing the private rule epoch.""" | |
| facility = sm.get_entity('facility', config['facility_id'], id_field='facility_id') | |
| if facility is None: | |
| raise ValueError('stream facility is missing') | |
| if facility.get('experience_active_episode') == next_episode_id: | |
| return fn__repeat_boundary(sm, config, previous_episode_id, next_episode_id) | |
| before_policy = fn__policy_state(sm, config) | |
| raw = fn_advance_boundary_2(sm, config, previous_episode_id, next_episode_id) | |
| after_policy = fn__policy_state(sm, config) | |
| drift = None | |
| if raw.get('drift') is not None: | |
| drift = fn__drift_receipt(config, before_policy, after_policy, duplicate=False) | |
| raw['drift'] = drift | |
| raw['activation'] = fn_activation_receipt(fn__episode_4(config, next_episode_id)) | |
| raw['schema'] = 'robot-experience-stream-boundary/v4' | |
| raw['public_notice'] = fn__public_notice(config, previous_episode_id, raw['activation']['event_id']) | |
| fn_public_boundary_projection(raw) | |
| return raw | |
| def fn_public_task_3(task_id): | |
| task = fn_public_task_4(task_id) | |
| if task_id != 'T09': | |
| by_index = {row['order_index']: row['work_order'] for row in fn_episode_spec_6(task_id)['orders']} | |
| indices = DATA_ORDER_INDEX_BLUEPRINT_2.get(task_id, tuple(sorted(by_index))) | |
| ordered = [by_index[index] for index in indices] | |
| marker = '\n\nUse the work-order and local observation tools' | |
| (heading, remainder) = task['query'].split(marker, 1) | |
| task['work_orders'] = ordered | |
| task['query'] = heading.split('\n- ', 1)[0] + '\n- ' + '\n- '.join(ordered) + marker + remainder | |
| if task_id == 'T01': | |
| before = task['query'] | |
| task['query'] = before.replace(f'The starting battery is {93} units', f'The starting battery is {72} units') | |
| if task['query'] == before: | |
| raise ValueError('Robot T01 public budget sentence changed upstream') | |
| return task | |
| def fn_episode_spec_4(task_id): | |
| spec = fn_episode_spec_5(task_id) | |
| spec['budget'] = DATA_EPISODE_BUDGETS_2[task_id] | |
| return spec | |
| def fn__ledger_path(state_dir): | |
| return ext_Path(state_dir) / 'observation-ledger.json' | |
| def fn_digest(value): | |
| return fn_digest_3(value) | |
| def fn_read_3(path): | |
| return fn_read_2(path) | |
| def fn__episode_3(config, episode_id): | |
| row = next((item for item in config['episodes'] if item['episode_id'] == episode_id), None) | |
| if row is None: | |
| raise ValueError(f'unknown episode: {episode_id}') | |
| return row | |
| def fn__rubric(config, episode): | |
| return {'version': 'robot-experience-rubric/v1', 'policy_version': 'PV-18', 'home_room_id': config['home_room_id'], 'orders': [{'work_order': row['work_order'], 'task_id': row['task_id'], 'object_id': row['object_id'], 'destination_room_id': row['target']} for row in episode['orders']]} | |
| def fn_episode_spec_5(task_id): | |
| return fn_episode_spec_6(task_id) | |
| def fn_load_config_2(): | |
| config = fn_load_config_3() | |
| config['episode_budgets']['T01'] = 72 | |
| return config | |
| def fn_digest_2(value): | |
| return mod_hashlib.sha256(fn__canonical(value)).hexdigest() | |
| def fn_read_4(path): | |
| return fn_read_5(path) | |
| def fn__repeat_boundary(sm, config, previous_episode_id, next_episode_id): | |
| if previous_episode_id != next_episode_id: | |
| raise ValueError('an idempotent replay must name the active episode') | |
| episode = fn__episode_4(config, next_episode_id) | |
| activation = fn_activation_receipt(episode) | |
| before_state = fn_semantic_state(sm) | |
| before_policy = fn__policy_state(sm, config) | |
| drift = None | |
| if next_episode_id == config['drift']['effective_episode_id']: | |
| prior_policy = {**before_policy, 'experience_rule_epoch': config['drift']['from_rule_epoch'], 'experience_policy_version': config['drift']['from_policy_version'], 'experience_policy_event_seq': before_policy['experience_policy_event_seq'] - 1} | |
| if prior_policy['experience_policy_event_seq'] < 0: | |
| raise ValueError('drift event sequence is inconsistent') | |
| drift = fn__drift_receipt(config, prior_policy, before_policy, duplicate=True) | |
| receipt = {'schema': 'robot-experience-stream-boundary/v4', 'previous_episode_id': previous_episode_id, 'next_episode_id': next_episode_id, 'already_prepared': True, 'before_sha256': fn__digest(before_state), 'after_sha256': fn__digest(before_state), 'closed': {'closed_orders': [], 'cancelled_assignments': []}, 'supervisor_recovery': {'performed': False}, 'drift': drift, 'activation': activation, 'public_notice': fn__public_notice(config, None if next_episode_id == config['episodes'][0]['episode_id'] else 'prior', activation['event_id']), 'changes': [], 'preservation_contract': {'world_reset': False, 'opened_storage_preserved': True, 'completed_records_preserved': True, 'unrelated_object_locations_preserved': True, 'payload_parking_is_not_delivery': True}} | |
| fn_public_boundary_projection(receipt) | |
| return receipt | |
| def fn__policy_state(sm, config): | |
| facility = sm.get_entity('facility', config['facility_id'], id_field='facility_id') | |
| if facility is None: | |
| raise ValueError('stream facility is missing') | |
| return {'experience_rule_epoch': facility.get('experience_rule_epoch'), 'experience_policy_version': facility.get('experience_policy_version'), 'experience_policy_event_seq': int(facility.get('experience_policy_event_seq', 0))} | |
| def fn_advance_boundary_2(sm, config, previous_episode_id, next_episode_id): | |
| """Close one episode and activate the next without resetting world state.""" | |
| previous_episode = fn__episode_5(config, previous_episode_id) | |
| next_episode = fn__episode_5(config, next_episode_id) | |
| if next_episode is None: | |
| raise ValueError('unknown next episode') | |
| if previous_episode_id is not None and previous_episode is None: | |
| raise ValueError('unknown previous episode') | |
| if previous_episode is not None: | |
| expected = previous_episode['next_episode_id'] | |
| if expected != next_episode_id: | |
| raise ValueError('episode boundary is not sequential') | |
| before = fn_semantic_state_2(sm) | |
| closed = fn__close_previous(sm, previous_episode) | |
| recovery = fn__recover_robot(sm, budget=config['budget']) | |
| drift = fn__apply_drift(sm, config, next_episode_id) | |
| activation = fn__activate_next(sm, config, next_episode) | |
| after = fn_semantic_state_2(sm) | |
| changes = fn_state_diff(before, after) | |
| notice = f"Episode {next_episode_id} is active. The supervisor placed the robot at the service hub with {config['budget']} battery units and activated the new work orders." | |
| if previous_episode_id is not None: | |
| notice += ' Any payload left from the prior episode was parked at its actual terminal room without delivery credit; other world state and completed records were preserved.' | |
| if drift is not None: | |
| notice += ' ' + drift['public_notice'] | |
| return {'schema': 'robot-experience-stream-boundary/v2', 'previous_episode_id': previous_episode_id, 'next_episode_id': next_episode_id, 'before_sha256': fn__digest_2(before), 'after_sha256': fn__digest_2(after), 'closed': closed, 'supervisor_recovery': recovery, 'drift': drift, 'activation': activation, 'public_notice': notice, 'changes': changes, 'preservation_contract': {'world_reset': False, 'opened_storage_preserved': True, 'completed_records_preserved': True, 'unrelated_object_locations_preserved': True, 'payload_parking_is_not_delivery': True}} | |
| def fn__drift_receipt(config, before, after, *, duplicate): | |
| drift = config['drift'] | |
| if after != {'experience_rule_epoch': drift['to_rule_epoch'], 'experience_policy_version': drift['to_policy_version'], 'experience_policy_event_seq': before['experience_policy_event_seq'] + 1}: | |
| raise ValueError('drift receipt does not match the expected policy transition') | |
| return {'schema': 'robot-experience-drift-application/v1', 'event_id': fn__drift_event_id(config), 'event_type': 'external_policy_update', 'receipt_kind': 'duplicate_application' if duplicate else 'first_application', 'status': 'already_applied' if duplicate else 'applied', 'applied_now': not duplicate, 'duplicate_noop': duplicate, 'exactly_once': True, 'application_before_sha256': fn__digest(before), 'application_after_sha256': fn__digest(after), 'call_before_sha256': fn__digest(after if duplicate else before), 'call_after_sha256': fn__digest(after), 'state_unchanged': duplicate, 'effective_episode_id': drift['effective_episode_id'], 'publicly_announced': False, 'policy_version_before': drift['from_policy_version'], 'policy_version_after': drift['to_policy_version'], 'changed_cell_count': len(drift['changed_cells'])} | |
| def fn_activation_receipt(episode): | |
| """Project an active private episode into the exact public receipt.""" | |
| orders = episode.get('orders') | |
| if not isinstance(episode.get('episode_id'), str) or not episode['episode_id']: | |
| raise ValueError('episode must define a non-empty episode_id') | |
| if not isinstance(orders, list) or not orders: | |
| raise ValueError('episode must define active work orders') | |
| work_orders = [row.get('work_order') for row in orders if isinstance(row, dict)] | |
| if len(work_orders) != len(orders) or any((not isinstance(value, str) or not value for value in work_orders)) or len(set(work_orders)) != len(work_orders): | |
| raise ValueError('episode work orders must be unique non-empty strings') | |
| return {'schema': 'robot-experience-activation-public/v4', 'event_type': 'work_order_activation', 'event_id': fn_opaque_event_id(work_orders), 'work_orders': sorted(work_orders), 'created_object_ids': [], 'world_reset': False} | |
| def fn__episode_4(config, episode_id): | |
| episode = next((row for row in config.get('episodes', []) if row.get('episode_id') == episode_id), None) | |
| if episode is None: | |
| raise ValueError('unknown next episode') | |
| return episode | |
| def fn__public_notice(config, previous_episode_id, event_id): | |
| notice = f"Work-order event {event_id} is active. The supervisor placed the robot at the service hub with {config['budget']} battery units and activated the new work orders." | |
| if previous_episode_id is not None: | |
| notice += ' Any payload left from the prior episode was parked at its actual terminal room without delivery credit; other business state and completed records were preserved.' | |
| return notice | |
| def fn_public_boundary_projection(receipt): | |
| """Return only the boundary fields admitted to a learner/provider request.""" | |
| activation = receipt.get('activation') | |
| notice = receipt.get('public_notice') | |
| if not isinstance(activation, dict) or not isinstance(notice, str): | |
| raise ValueError('boundary receipt is missing its public fields') | |
| projection = {'schema': 'robot-experience-stream-boundary-public/v2', 'event_id': activation.get('event_id'), 'activation': ext_deepcopy(activation), 'public_notice': notice} | |
| encoded = mod_json.dumps(projection, sort_keys=True, ensure_ascii=True).casefold() | |
| forbidden = ('pv-', 'policy_version', 'rule_epoch', 'drift', 'policy update', 'transfer policy', 'changed cell', 'rule change', 'environment change', 'prior compatibility', 'selective revision') | |
| if any((token in encoded for token in forbidden)): | |
| raise ValueError('learner-visible boundary exposes a private transition marker') | |
| fn_assert_opaque_learner_surface(projection, surface='public boundary') | |
| return projection | |
| def fn_public_task_4(task_id): | |
| task = fn_public_task_5(task_id) | |
| if task_id != 'T09': | |
| by_index = {row['order_index']: row['work_order'] for row in fn_episode_spec_6(task_id)['orders']} | |
| indices = DATA_ORDER_INDEX_BLUEPRINT_3.get(task_id, tuple(sorted(by_index))) | |
| ordered = [by_index[index] for index in indices] | |
| marker = '\n\nUse the work-order and local observation tools' | |
| (heading, remainder) = task['query'].split(marker, 1) | |
| task['work_orders'] = ordered | |
| task['query'] = heading.split('\n- ', 1)[0] + '\n- ' + '\n- '.join(ordered) + marker + remainder | |
| sentence = ' Process the work orders in the listed priority order: do not start a later order until every earlier listed order has been fully closed.' | |
| if sentence.strip() not in task['query']: | |
| task['query'] = task['query'].rstrip() + sentence | |
| task['completion'] = {'mode': 'ordered_independent', 'subset_allowed': True, 'priority_order': 'listed', 'started_item_must_close': True, 'verification_required': True} | |
| return task | |
| def fn_episode_spec_6(task_id): | |
| return fn_episode_spec_2(task_id) | |
| def fn_digest_3(value): | |
| return fn_digest_4(value) | |
| def fn__error(code, message, data=None): | |
| return {'status': 'error', 'data': data or {}, 'message': f'{code}: {message}'} | |
| def fn__code(result): | |
| message = str(result.get('message') or '') | |
| return message.split(':', 1)[0] if ':' in message else 'OK' if result.get('status') == 'success' else 'ERROR' | |
| def fn__success(data, message='OK'): | |
| return {'status': 'success', 'data': data, 'message': message} | |
| def fn__timestamp(): | |
| return ext_datetime.now(ext_timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') | |
| def fn_load_config_3(): | |
| config = fn_load_config() | |
| config['episode_budgets']['T01'] = 93 | |
| return config | |
| def fn__canonical(value): | |
| return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), allow_nan=False).encode('ascii') | |
| def fn__validate_snapshot_extensions(snapshot): | |
| if not isinstance(snapshot, dict) or set(snapshot) != DATA__SNAPSHOT_FIELDS: | |
| raise ValueError('Robot v8 snapshot fields are incomplete or unexpected') | |
| if type(snapshot.get('business_call_count')) is not int: | |
| raise ValueError('Robot v8 business_call_count must be an integer') | |
| if snapshot['business_call_count'] < 0: | |
| raise ValueError('Robot v8 business_call_count must be non-negative') | |
| authorized = snapshot.get('authorized_new_stock_group') | |
| if authorized is not None and (not isinstance(authorized, str) or not authorized): | |
| raise ValueError('Robot v8 authorized stock group must be null or a string') | |
| provisional = snapshot.get('provisional_stock_groups') | |
| verified = snapshot.get('verified_stock_groups') | |
| if not isinstance(provisional, dict): | |
| raise ValueError('Robot v8 provisional_stock_groups must be an object') | |
| if not isinstance(verified, dict): | |
| raise ValueError('Robot v8 verified_stock_groups must be an object') | |
| if len(provisional) > 1: | |
| raise ValueError('Robot v8 provisional stock bindings exceed the task limit') | |
| if set(provisional) & set(verified): | |
| raise ValueError('Robot v8 stock evidence cannot be both provisional and verified') | |
| required = {'task_id', 'station', 'storage_handle', 'zone'} | |
| for (stock_group, evidence) in {**verified, **provisional}.items(): | |
| if not isinstance(stock_group, str) or not stock_group: | |
| raise ValueError('Robot v8 verified stock-group keys must be strings') | |
| if not isinstance(evidence, dict) or set(evidence) != required: | |
| raise ValueError('Robot v8 verified stock evidence is malformed') | |
| if any((not isinstance(evidence[field], str) or not evidence[field] for field in required)): | |
| raise ValueError('Robot v8 verified stock evidence values must be strings') | |
| if evidence['task_id'] not in DATA_TASK_IDS: | |
| raise ValueError('Robot v8 verified stock evidence has an invalid task') | |
| if any((evidence['task_id'] != snapshot.get('task_id') for evidence in provisional.values())): | |
| raise ValueError('Robot v8 provisional stock evidence crossed a task boundary') | |
| visible_handles = snapshot.get('visible_object_handles') | |
| if not isinstance(visible_handles, list) or any((not isinstance(handle, str) or not handle for handle in visible_handles)) or len(visible_handles) != len(set(visible_handles)): | |
| raise ValueError('Robot v8 visible object handles must be unique strings') | |
| def fn_read_5(path): | |
| return mod_json.loads(ext_Path(path).read_text(encoding='utf-8')) | |
| def fn__digest(value): | |
| return mod_hashlib.sha256(mod_json.dumps(value, sort_keys=True, ensure_ascii=True, separators=(',', ':'), allow_nan=False).encode('ascii')).hexdigest() | |
| def fn__episode_5(config, episode_id): | |
| if episode_id is None: | |
| return None | |
| return next((row for row in config['episodes'] if row['episode_id'] == episode_id), None) | |
| def fn_semantic_state_2(sm): | |
| return {table: sorted((ext_deepcopy(row) for row in sm.list_entities(table)), key=lambda row: str(row.get(DATA_ID_FIELDS[table], ''))) for table in DATA_STATE_TABLES} | |
| def fn__close_previous(sm, episode): | |
| if episode is None: | |
| return {'closed_orders': [], 'cancelled_assignments': []} | |
| (closed, cancelled) = ([], []) | |
| task_ids = {row['task_id'] for row in episode['orders']} | |
| for spec in episode['orders']: | |
| task = sm.get_entity('service_task', spec['task_id'], id_field='task_id') | |
| obj = sm.get_entity('object_item', spec['object_id'], id_field='object_id') | |
| if task is None or obj is None: | |
| raise ValueError('previous episode records are missing') | |
| task_changes = {'experience_activation_state': 'closed', 'updated_at': fn__boundary_timestamp()} | |
| if task.get('status') != 'completed': | |
| task_changes.update(status='paused', assigned_robot_id=None, failure_reason='episode_closed_by_supervisor') | |
| fn__update(sm, 'service_task', spec['task_id'], task_changes) | |
| fn__update(sm, 'object_item', spec['object_id'], {'experience_activation_state': 'closed', 'updated_at': fn__boundary_timestamp()}) | |
| closed.append(spec['work_order']) | |
| for assignment in sm.list_entities('task_assignment'): | |
| if assignment.get('task_id') in task_ids and assignment.get('status') == 'active': | |
| fn__update(sm, 'task_assignment', assignment['assignment_id'], {'status': 'cancelled', 'completed_at': fn__boundary_timestamp()}) | |
| cancelled.append(assignment['assignment_id']) | |
| return {'closed_orders': sorted(closed), 'cancelled_assignments': sorted(cancelled)} | |
| def fn__recover_robot(sm, *, budget): | |
| robot = sm.get_entity('robot_unit', 'robot-porter-atlas-north-one', id_field='robot_id') | |
| if robot is None: | |
| raise ValueError('controlled robot is missing') | |
| parked = None | |
| payload_id = robot.get('payload_object_id') | |
| if payload_id is not None: | |
| payload = sm.get_entity('object_item', payload_id, id_field='object_id') | |
| if payload is None or payload.get('held_by_robot_id') != 'robot-porter-atlas-north-one': | |
| raise ValueError('robot payload custody is inconsistent at the boundary') | |
| parked = {'object_id': payload_id, 'room_id': robot.get('current_room_id'), 'delivery_receipt_created': False} | |
| fn__update(sm, 'object_item', payload_id, {'current_room_id': robot.get('current_room_id'), 'held_by_robot_id': None, 'handling_state': 'stored', 'updated_at': fn__boundary_timestamp()}) | |
| before = {key: ext_deepcopy(robot.get(key)) for key in ('current_room_id', 'battery_percent', 'payload_object_id', 'operational_status', 'active_task_id')} | |
| fn__update(sm, 'robot_unit', 'robot-porter-atlas-north-one', {'current_room_id': 'room-atlas-north-level-one-central-return-sort', 'battery_percent': budget, 'payload_object_id': None, 'operational_status': 'available', 'active_task_id': None, 'updated_at': fn__boundary_timestamp()}) | |
| after_row = sm.get_entity('robot_unit', 'robot-porter-atlas-north-one', id_field='robot_id') | |
| return {'before': before, 'after': {key: ext_deepcopy(after_row.get(key)) for key in before}, 'parked_payload': parked} | |
| def fn__apply_drift(sm, config, next_episode_id): | |
| drift = config['drift'] | |
| if next_episode_id != drift['effective_episode_id']: | |
| return None | |
| facility = sm.get_entity('facility', config['facility_id'], id_field='facility_id') | |
| if facility is None: | |
| raise ValueError('stream facility is missing') | |
| if facility.get('experience_rule_epoch') != drift['from_rule_epoch']: | |
| raise ValueError('drift must be applied exactly once from the pre-drift epoch') | |
| before = {'experience_rule_epoch': facility.get('experience_rule_epoch'), 'experience_policy_version': facility.get('experience_policy_version')} | |
| fn__update(sm, 'facility', config['facility_id'], {'experience_rule_epoch': 'post', 'experience_policy_version': 'PV-19', 'experience_policy_event_seq': int(facility.get('experience_policy_event_seq', 0)) + 1}) | |
| return {'event_type': 'external_policy_update', 'effective_episode_id': next_episode_id, 'publicly_announced': True, 'policy_version_before': before['experience_policy_version'], 'policy_version_after': 'PV-19', 'changed_cell_count': len(drift['changed_cells']), 'public_notice': f"Transfer policy {'PV-19'} is effective for {next_episode_id}. Current work-order records show the active policy version; prior compatibility experience may need selective revision."} | |
| def fn__activate_next(sm, config, episode): | |
| facility = sm.get_entity('facility', config['facility_id'], id_field='facility_id') | |
| if facility is None: | |
| raise ValueError('stream facility is missing') | |
| if facility.get('experience_rule_epoch') != episode['rule_epoch']: | |
| raise ValueError('next episode expects a different rule epoch') | |
| activated = [] | |
| for spec in episode['orders']: | |
| task = sm.get_entity('service_task', spec['task_id'], id_field='task_id') | |
| obj = sm.get_entity('object_item', spec['object_id'], id_field='object_id') | |
| if task is None or obj is None: | |
| raise ValueError('next episode records are missing') | |
| if task.get('experience_activation_state') != 'inactive': | |
| raise ValueError('next service task is not inactive') | |
| if obj.get('experience_activation_state') != 'inactive': | |
| raise ValueError('next parcel is not inactive') | |
| fn__update(sm, 'service_task', spec['task_id'], {'experience_activation_state': 'active', 'updated_at': fn__boundary_timestamp()}) | |
| fn__update(sm, 'object_item', spec['object_id'], {'experience_activation_state': 'active', 'updated_at': fn__boundary_timestamp()}) | |
| activated.append(spec['work_order']) | |
| fn__update(sm, 'facility', config['facility_id'], {'experience_active_episode': episode['episode_id']}) | |
| return {'schema': 'robot-experience-activation-public/v2', 'event_type': 'work_order_activation', 'episode_id': episode['episode_id'], 'work_orders': sorted(activated), 'policy_version': episode['public_policy_version'], 'created_object_ids': [], 'world_reset': False} | |
| def fn_state_diff(before, after): | |
| changes = [] | |
| for table in DATA_STATE_TABLES: | |
| (left, right) = (fn__row_index(before, table), fn__row_index(after, table)) | |
| for identifier in sorted(set(left) | set(right)): | |
| if left.get(identifier) != right.get(identifier): | |
| changes.append({'table': table, 'id': identifier, 'before': ext_deepcopy(left.get(identifier)), 'after': ext_deepcopy(right.get(identifier))}) | |
| return changes | |
| def fn__digest_2(value): | |
| payload = mod_json.dumps(value, sort_keys=True, ensure_ascii=True, separators=(',', ':')).encode('utf-8') | |
| return mod_hashlib.sha256(payload).hexdigest() | |
| def fn__drift_event_id(config): | |
| drift = config['drift'] | |
| payload = {'schema': 'robot-experience-drift-application/v1', 'facility_id': config['facility_id'], 'from_rule_epoch': drift['from_rule_epoch'], 'to_rule_epoch': drift['to_rule_epoch'], 'from_policy_version': drift['from_policy_version'], 'to_policy_version': drift['to_policy_version'], 'changed_cells': drift['changed_cells']} | |
| return 'evt-' + fn__digest(payload)[:20] | |
| def fn_opaque_event_id(work_orders): | |
| """Derive a stable, non-sequential public ID from the public order set.""" | |
| if not isinstance(work_orders, list) or not work_orders or any((not isinstance(value, str) or not value for value in work_orders)) or (len(set(work_orders)) != len(work_orders)): | |
| raise ValueError('opaque event IDs require unique non-empty work orders') | |
| payload = mod_json.dumps(['robot-final-public-event/v1', *sorted(work_orders)], ensure_ascii=True, separators=(',', ':')).encode('ascii') | |
| return 'evt-' + mod_hashlib.sha256(payload).hexdigest()[:20] | |
| def fn_assert_opaque_learner_surface(value, *, surface): | |
| hits = fn_leakage_hits(value) | |
| present = {name: rows for (name, rows) in hits.items() if rows} | |
| if present: | |
| raise ValueError(f'{surface} exposes private lifecycle metadata: {present}') | |
| try: | |
| ext_assert_hard_public_projection(value) | |
| except ValueError as error: | |
| raise ValueError(f'{surface} exposes private lifecycle metadata: {error}') from error | |
| def fn_public_task_5(task_id): | |
| task = fn_public_task_6(task_id) | |
| if task_id == 'T01': | |
| before = task['query'] | |
| task['query'] = before.replace('The starting battery is 98 units', f'The starting battery is {93} units') | |
| if task['query'] == before: | |
| raise ValueError('Robot T01 public budget sentence changed upstream') | |
| return task | |
| def fn_digest_4(value): | |
| return mod_hashlib.sha256(mod_json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode()).hexdigest() | |
| def fn__validate_snapshot_extensions_2(snapshot): | |
| if not isinstance(snapshot, dict) or set(snapshot) != DATA__SNAPSHOT_FIELDS_2: | |
| raise ValueError('Robot v7 snapshot fields are incomplete or unexpected') | |
| evidence = snapshot.get('transfer_evidence') | |
| revalidation = snapshot.get('rule_revalidation') | |
| if not isinstance(evidence, dict) or not isinstance(revalidation, dict): | |
| raise ValueError('Robot v7 snapshot extensions must be objects') | |
| profiles = set(fn__profiles()) | |
| for (cell, row) in evidence.items(): | |
| (handling, intake) = fn__validate_cell(cell) | |
| if not isinstance(row, dict) or set(row) != DATA__TRANSFER_EVIDENCE_FIELDS: | |
| raise ValueError(f'Robot v7 transfer evidence is malformed for {cell}') | |
| if any((not isinstance(row[field], str) or not row[field] for field in row)): | |
| raise ValueError(f'Robot v7 transfer evidence values must be strings for {cell}') | |
| if row['task_id'] not in DATA_TASK_IDS or row['cell'] != cell: | |
| raise ValueError(f'Robot v7 transfer evidence identity mismatch for {cell}') | |
| if row['handling_code'] != handling or row['intake_code'] != intake: | |
| raise ValueError(f'Robot v7 transfer evidence crosses exact cells for {cell}') | |
| if row['profile'] not in profiles: | |
| raise ValueError(f'Robot v7 transfer evidence profile is invalid for {cell}') | |
| for (cell, state) in revalidation.items(): | |
| fn__validate_cell(cell) | |
| if cell not in evidence or state not in DATA_REVALIDATION_STATES: | |
| raise ValueError(f'Robot v7 revalidation state is invalid for {cell}') | |
| def fn__boundary_timestamp(): | |
| return _BOUNDARY_TIME.get() | |
| def fn__update(sm, table, identifier, changes): | |
| sm.update_entity(table, identifier, changes, id_field=DATA_ID_FIELDS[table]) | |
| def fn__row_index(state, table): | |
| field = DATA_ID_FIELDS[table] | |
| return {str(row[field]): row for row in state[table]} | |
| def fn_leakage_hits(value): | |
| """Report private lifecycle labels in a learner/provider-visible value.""" | |
| encoded = mod_json.dumps(value, ensure_ascii=True, sort_keys=True, allow_nan=False) | |
| private_keys: set[str] = set() | |
| def visit(item): | |
| if isinstance(item, dict): | |
| private_keys.update((str(key) for key in item if key in DATA__PRIVATE_KEYS)) | |
| for nested in item.values(): | |
| visit(nested) | |
| elif isinstance(item, list): | |
| for nested in item: | |
| visit(nested) | |
| visit(value) | |
| return {'private_episode_ids': sorted(set(_re.compile('(?<![A-Za-z0-9])T(?:0[1-9]|1[0-6])(?![A-Za-z0-9]|:[0-5][0-9])', 34).findall(encoded))), 'arm_labels': sorted(set(_re.compile('(?<![A-Za-z0-9])(?:native|reset|reflect)\\d{2}(?![A-Za-z0-9])', 34).findall(encoded))), 'run_paths': sorted(set(_re.compile('(?:benchmark_outputs[/\\\\]robot|robot-final-v\\d+[/\\\\]20\\d{6}-\\d{6})', 34).findall(encoded))), 'private_keys': sorted(private_keys)} | |
| def fn_public_task_6(task_id): | |
| if task_id not in DATA_TASK_IDS: | |
| raise ValueError(f'unknown Robot stream task: {task_id}') | |
| return mod_json.loads((CASE_DIR / 'data/world' / f'public/tasks/{task_id}.json').read_text(encoding='utf-8')) | |
| def fn__validate_rule_table(value): | |
| table = ext_deepcopy(value if value is not None else fn_default_rule_table()) | |
| expected = {f'{handling}:{intake}' for handling in DATA_HANDLING_CODES for intake in DATA_INTAKE_CODES} | |
| if set(table) != expected or any((profile not in DATA_TRANSFER_PROFILES for profile in table.values())): | |
| raise ValueError('rule_table must define every handling:intake cell') | |
| return table | |
| def fn__validate_cell(cell): | |
| if not isinstance(cell, str) or cell.count(':') != 1: | |
| raise ValueError('transfer evidence key must be an exact handling:intake cell') | |
| (handling, intake) = cell.split(':', 1) | |
| if not handling or not intake: | |
| raise ValueError('transfer evidence cell components must be non-empty') | |
| return (handling, intake) | |
| def fn_default_rule_table(): | |
| """Return the private finite relation used by the first candidate.""" | |
| handling_rank = (2, 0, 3, 1) | |
| intake_rank = (1, 3, 0, 2) | |
| return {f'{handling}:{intake}': DATA_TRANSFER_PROFILES[(handling_rank[handling_index] + intake_rank[intake_index]) % len(DATA_TRANSFER_PROFILES)] for (handling_index, handling) in enumerate(DATA_HANDLING_CODES) for (intake_index, intake) in enumerate(DATA_INTAKE_CODES)} | |
| def fn__strip_volatile(value): | |
| if isinstance(value, dict): | |
| return {key: fn__strip_volatile(item) for (key, item) in sorted(value.items()) if not key.endswith('_at')} | |
| if isinstance(value, list): | |
| return [fn__strip_volatile(item) for item in value] | |
| return ext_deepcopy(value) | |
| class World: | |
| def __init__(self): | |
| self.runtime = RobotSourceScopeRuntime() | |
| self.t01_boundary = self.runtime.activate_task('T01') | |
| self.t01_pending = True | |
| def snapshot(self): | |
| return {'schema': 'rescopebench-robot-rule-formal-world/v6', 'runtime': self.runtime.snapshot(), 't01_boundary': ext_deepcopy(self.t01_boundary), 't01_pending': self.t01_pending} | |
| def restore(self, snapshot): | |
| if not isinstance(snapshot, dict) or set(snapshot) != {'schema', 'runtime', 't01_boundary', 't01_pending'}: | |
| raise ValueError('invalid Robot rule-v9 formal snapshot fields') | |
| if snapshot.get('schema') != 'rescopebench-robot-rule-formal-world/v6': | |
| raise ValueError('unsupported Robot rule-v9 formal snapshot') | |
| if not isinstance(snapshot.get('t01_pending'), bool): | |
| raise ValueError('Robot rule-v9 pending flag must be boolean') | |
| self.runtime.restore(ext_deepcopy(snapshot['runtime'])) | |
| self.t01_boundary = ext_deepcopy(snapshot['t01_boundary']) | |
| self.t01_pending = snapshot['t01_pending'] | |
| if self.snapshot() != snapshot: | |
| raise ValueError('Robot rule-v9 formal snapshot did not round trip') | |
| def activate(self, task_id): | |
| if task_id == 'T01' and self.t01_pending: | |
| self.t01_pending = False | |
| return ext_deepcopy(self.t01_boundary) | |
| self.t01_pending = False | |
| return self.runtime.activate_task(task_id) | |
| def close(self): | |
| self.runtime.close() | |
| class RobotSourceScopeRuntime: | |
| def _stage_retained_source(self, arguments): | |
| result = self._robot_local_rule_runtime_stage_retained_source(arguments) | |
| order = self._task_order(arguments.get('work_order', '')) | |
| return fn_scoped_staging_result(result, (order or {}).get('stock_group')) | |
| def _validate_restored_evidence_against_world(self): | |
| try: | |
| return self._robot_source_runtime_validate_restored_evidence_against_world() | |
| except ValueError as error: | |
| if str(error) != 'Robot v8 replacement state lacks a stale rejection': | |
| raise | |
| original = self.rule_revalidation | |
| self.rule_revalidation = {cell: 'awaiting_exact_stale' if state == 'awaiting_replacement' else state for (cell, state) in original.items()} | |
| try: | |
| return self._robot_source_runtime_validate_restored_evidence_against_world() | |
| finally: | |
| self.rule_revalidation = original | |
| def __init__(self, *args, **kwargs): | |
| self._restoring_source = False | |
| self._robot_route_runtime_init(*args, **kwargs) | |
| def _task_order(self, work_order): | |
| if self.current_task_id is None: | |
| return None | |
| return next((row for row in fn_episode_spec(self.current_task_id)['orders'] if row['work_order'] == work_order), None) | |
| def activate_task(self, task_id): | |
| receipt = self._robot_route_runtime_activate_task(task_id) | |
| if int(task_id[1:]) >= 9: | |
| with self.isolated_raw(): | |
| self._relocate_stock() | |
| return receipt | |
| def _relocate_stock(self): | |
| (adapter, moves) = (self.adapter, fn_destinations()) | |
| facility = next((row for row in adapter._all('facility') if row['facility_id'] == mod_json.loads((CASE_DIR / 'data/assets/config.json').read_text())['facility_id'])) | |
| if facility.get('stock_relocation_version') == 'robot-stock-relocation-evolution-v9': | |
| return | |
| rooms = {row['room_id']: ext_deepcopy(row) for row in adapter._all('room')} | |
| stores = {unit['stock_group']: (room['room_id'], ext_deepcopy(unit)) for room in rooms.values() for unit in room.get('storage_units', [])} | |
| targets = {} | |
| for (group, destination) in moves.items(): | |
| (old_room, old_unit) = stores[group] | |
| target_group = next((key for key in moves if stores[key][0] == destination)) | |
| target_unit = stores[target_group][1] | |
| targets[group] = (old_room, old_unit['unit_id'], destination, target_unit['unit_id']) | |
| unit = next((row for row in rooms[destination]['storage_units'] if row['unit_id'] == target_unit['unit_id'])) | |
| unit['stock_group'] = group | |
| unit['calibration_records'] = ext_deepcopy(old_unit['calibration_records']) | |
| for destination in set(moves.values()): | |
| adapter.sm.update_entity('room', destination, {'storage_units': rooms[destination]['storage_units']}, id_field='room_id') | |
| for obj in adapter._all('object_item'): | |
| move = targets.get(obj.get('stock_group')) | |
| if move and obj.get('current_room_id') == move[0] and (obj.get('storage_unit_id') == move[1]) and (obj.get('handling_state') == 'stored') and (not obj.get('held_by_robot_id')): | |
| adapter.sm.update_entity('object_item', obj['object_id'], {'current_room_id': move[2], 'storage_unit_id': move[3]}, id_field='object_id') | |
| moved_tasks = {} | |
| for task in adapter._all('service_task'): | |
| target = moves.get(task.get('stock_group')) | |
| position = task.get('experience_episode_id', '') | |
| if target and position in {f'T{i:02}' for i in range(9, 17)}: | |
| adapter.sm.update_entity('service_task', task['task_id'], {'source_room_id': target}, id_field='task_id') | |
| moved_tasks[task['task_id']] = target | |
| for step in adapter._all('task_step'): | |
| if step['task_id'] in moved_tasks and step['step_type'] in {'navigate', 'pick'}: | |
| adapter.sm.update_entity('task_step', step['step_id'], {'room_id': moved_tasks[step['task_id']]}, id_field='step_id') | |
| adapter.sm.update_entity('facility', facility['facility_id'], {'stock_relocation_version': 'robot-stock-relocation-evolution-v9'}, id_field='facility_id') | |
| def _open_storage(self, arguments): | |
| result = self._robot_rule_successor_open_storage(arguments) | |
| data = result.get('data', {}) | |
| if result.get('status') == 'success' and data.get('matches_pending_stock_group'): | |
| order = self._task_order(self._first_pending_work_order() or '') | |
| group = (order or {}).get('stock_group') | |
| prior = self.verified_stock_groups.get(group) | |
| robot = self.adapter._robot() | |
| room = self.adapter._room(robot['current_room_id']) | |
| if prior and (prior['station'] != room['name'] or prior['storage_handle'] != arguments['storage_handle']): | |
| del self.verified_stock_groups[group] | |
| self.authorized_new_stock_group = group | |
| self.provisional_stock_groups[group] = {'task_id': self.current_task_id, 'station': room['name'], 'storage_handle': arguments['storage_handle'], 'zone': self._room_zone(room['room_id'])} | |
| data['binding_retention_status'] = 'provisional_until_work_order_closed' | |
| return result | |
| def snapshot(self): | |
| value = self._robot_route_runtime_snapshot() | |
| if not self._restoring_source: | |
| value['source_relocation_contract'] = {'case_version': 'robot-stock-relocation-evolution-v9', 'design_sha256': mod_hashlib.sha256((CASE_DIR / 'data/assets/design.json').read_bytes()).hexdigest()} | |
| return value | |
| def restore(self, snapshot): | |
| value = ext_deepcopy(snapshot) | |
| expected = {'case_version': 'robot-stock-relocation-evolution-v9', 'design_sha256': mod_hashlib.sha256((CASE_DIR / 'data/assets/design.json').read_bytes()).hexdigest()} | |
| if value.pop('source_relocation_contract', None) != expected: | |
| raise ValueError('Robot source relocation identity differs') | |
| self._restoring_source = True | |
| try: | |
| self._robot_route_runtime_restore(value) | |
| finally: | |
| self._restoring_source = False | |
| if self.snapshot() != snapshot: | |
| raise ValueError('Robot source relocation snapshot did not round trip') | |
| def _locate_order_zone(self, arguments): | |
| before = self.authorized_new_stock_group | |
| try: | |
| response = self._robot_rule_successor_locate_order_zone(arguments) | |
| except Exception: | |
| self.authorized_new_stock_group = before | |
| raise | |
| if response.get('status') != 'success': | |
| self.authorized_new_stock_group = before | |
| return response | |
| def dispatch(self, tool, arguments): | |
| if tool == 'observe_self' and arguments == {}: | |
| result = RobotSourceScopeRuntime._robot_rule_successor_dispatch(self, tool, arguments) | |
| self._annotate_zone_response(tool, result) | |
| return self._attach_call_budget(result) | |
| if tool == 'read_work_order' and isinstance(arguments, dict) and (set(arguments) == {'work_order'}) and isinstance(arguments['work_order'], str) and (arguments['work_order'] in self._own_closeouts): | |
| return self._attach_call_budget({'status': 'success', 'data': {'work_order': arguments['work_order'], 'confirmation_only': True, 'completion_receipt': ext_deepcopy(self._own_closeouts[arguments['work_order']])}, 'message': 'Previously committed closeout from this episode.'}) | |
| result = self._robot_rule_successor_dispatch_2(tool, arguments) | |
| if result.get('status') == 'success' and tool in {'finalize', 'execute_transfer_attempt'}: | |
| receipt = result | |
| if tool == 'execute_transfer_attempt': | |
| receipt = next((r['result'] for r in result.get('data', {}).get('steps', []) if r['tool'] == 'finalize'), None) | |
| if receipt is not None and receipt.get('status') == 'success': | |
| self._own_closeouts[arguments['work_order']] = ext_deepcopy(receipt) | |
| return result | |
| def _prepare_episode(self, task_id): | |
| return fn_prepare_episode(CASE_DIR / 'data/world', self.state_dir, task_id) | |
| def _revalidation_error(self, tool, context): | |
| return None | |
| def _listed_orders(self): | |
| if self.current_task_id is None: | |
| return [] | |
| return list(fn_public_task(self.current_task_id)['work_orders']) | |
| def business_call_limit(self): | |
| return DATA_BUSINESS_CALL_LIMITS.get(self.current_task_id, 36) | |
| def _valid_retained_arguments(arguments): | |
| required = {'work_order', 'source_station', 'storage_handle', 'source_exit_handles'} | |
| if set(arguments) != required: | |
| return False | |
| if not all((isinstance(arguments[key], str) for key in ('work_order', 'source_station', 'storage_handle'))): | |
| return False | |
| return all((isinstance(arguments[key], list) and len(arguments[key]) <= 16 and all((isinstance(handle, str) for handle in arguments[key])) for key in ('source_exit_handles',))) | |
| def _attach_call_budget(self, result): | |
| value = ext_deepcopy(result) | |
| value['business_call_budget'] = {'used': self.business_call_count, 'limit': self.business_call_limit(), 'remaining': max(0, self.business_call_limit() - self.business_call_count)} | |
| return value | |
| def _first_pending_work_order(self): | |
| if self.adapter is None: | |
| return None | |
| completed = {row['work_order']: bool(row['workflow_completed']) for row in self.adapter.grade()['orders']} | |
| return next((work_order for work_order in self._listed_orders() if not completed.get(work_order, False)), None) | |
| def _room_zone(self, room_id): | |
| return fn__zone_for_room_id(room_id) | |
| def _station_zone(self, station_name): | |
| if self.adapter is None or not isinstance(station_name, str): | |
| return None | |
| room = next((row for row in self.adapter._all('room') if row.get('name') == station_name), None) | |
| return self._room_zone((room or {}).get('room_id')) | |
| def _zone_counts(self): | |
| if self.adapter is None: | |
| return {} | |
| counts = {zone: 0 for zone in DATA_ZONE_ADJACENCY} | |
| for room in self.adapter._all('room'): | |
| zone = self._room_zone(room.get('room_id')) | |
| if zone in counts and room.get('is_robot_accessible') is True: | |
| counts[zone] += 1 | |
| return counts | |
| def _annotate_zone_response(self, tool, result): | |
| if result.get('status') != 'success' or self.adapter is None: | |
| return | |
| data = result.get('data') or {} | |
| if tool == 'observe_self': | |
| room = data.get('current_room') or {} | |
| room['zone'] = self._station_zone(room.get('name')) | |
| return | |
| if tool == 'scan_current_room': | |
| robot = self.adapter._robot() or {} | |
| room_id = robot.get('current_room_id') | |
| room = data.get('room') or {} | |
| room['zone'] = self._room_zone(room_id) | |
| for exit_row in data.get('exits', []): | |
| edge_id = self.adapter._edge_by_handle.get(exit_row.get('exit_handle')) | |
| edge = self.adapter._get('map_edge', 'edge_id', edge_id) | |
| destination_id = self.adapter._edge_destination(edge or {}, room_id) | |
| exit_row['destination_zone'] = self._room_zone(destination_id) | |
| pending = self._task_order(self._first_pending_work_order() or '') | |
| object_name = (pending or {}).get('object_name') | |
| data['objects'] = [row for row in data.get('objects', []) if row.get('display_name') == object_name] | |
| return | |
| if tool == 'traverse_known_exit': | |
| for key in ('previous_room', 'current_room'): | |
| room = data.get(key) | |
| if isinstance(room, dict): | |
| room['zone'] = self._station_zone(room.get('name')) | |
| for segment in data.get('segments', []): | |
| segment_data = segment.get('data') or {} | |
| for key in ('previous_room', 'current_room'): | |
| room = segment_data.get(key) | |
| if isinstance(room, dict): | |
| room['zone'] = self._station_zone(room.get('name')) | |
| def _visible_object_handles(value): | |
| handles: set[str] = set() | |
| if isinstance(value, dict): | |
| handle = value.get('object_handle') | |
| if isinstance(handle, str): | |
| handles.add(handle) | |
| for child in value.values(): | |
| handles.update(RobotSourceScopeRuntime._visible_object_handles(child)) | |
| elif isinstance(value, list): | |
| for child in value: | |
| handles.update(RobotSourceScopeRuntime._visible_object_handles(child)) | |
| return handles | |
| def _revoke_hidden_object_handles(self, before, result): | |
| if self.adapter is None: | |
| return | |
| newly_issued = set(self.adapter.issued_object_handles) - before | |
| visible = self._visible_object_handles(result.get('data') or {}) | |
| self.adapter.issued_object_handles.difference_update(newly_issued - visible) | |
| def _promote_completed_binding(self, work_order): | |
| if self.adapter is None: | |
| return | |
| order = self._task_order(work_order) | |
| if order is None: | |
| return | |
| completed = next((bool(row.get('workflow_completed')) for row in self.adapter.grade().get('orders', []) if row.get('work_order') == work_order), False) | |
| stock_group = order.get('stock_group') | |
| if completed and isinstance(stock_group, str): | |
| evidence = self.provisional_stock_groups.pop(stock_group, None) | |
| if evidence is not None: | |
| self.verified_stock_groups.setdefault(stock_group, evidence) | |
| def _valid_execute_arguments(arguments): | |
| required = {'work_order', 'object_handle', 'profile', 'delivery_exit_handles', 'closeout_exit_handles'} | |
| if set(arguments) != required: | |
| return False | |
| if not all((isinstance(arguments[key], str) for key in ('work_order', 'object_handle', 'profile'))): | |
| return False | |
| if arguments['profile'] not in fn__profiles(): | |
| return False | |
| for key in ('delivery_exit_handles', 'closeout_exit_handles'): | |
| value = arguments[key] | |
| if not isinstance(value, list) or len(value) > 16 or any((not isinstance(row, str) for row in value)): | |
| return False | |
| return True | |
| def _execute_transfer_attempt(self, arguments): | |
| if not self._valid_execute_arguments(arguments): | |
| return {'status': 'error', 'data': {}, 'message': 'INVALID_ARGUMENTS: arguments do not match the tool schema'} | |
| work_order = arguments['work_order'] | |
| reference = {'work_order': work_order} | |
| steps: list[dict[str, ext_Any]] = [] | |
| robot = self.adapter._robot() if self.adapter is not None else None | |
| order = self.adapter._order(work_order) if self.adapter is not None else None | |
| if robot is None or order is None: | |
| return {'status': 'error', 'data': {'steps': steps}, 'message': 'WORK_ORDER_UNAVAILABLE: the requested work order is unavailable'} | |
| if robot.get('active_task_id') is None: | |
| assigned = self._robot_rule_successor_dispatch('assign_work_order', reference) | |
| steps.append({'tool': 'assign_work_order', 'result': assigned}) | |
| if assigned.get('status') != 'success': | |
| return {'status': 'error', 'data': {'steps': steps}, 'message': assigned.get('message')} | |
| elif robot.get('active_task_id') != order['task_id']: | |
| return {'status': 'error', 'data': {'steps': steps}, 'message': 'ROBOT_BUSY: another work order is active'} | |
| prepared = self._robot_rule_successor_dispatch('prepare_transfer', {**reference, 'profile': arguments['profile']}) | |
| steps.append({'tool': 'prepare_transfer', 'result': prepared}) | |
| if prepared.get('status') != 'success': | |
| return {'status': 'error', 'data': {'steps': steps}, 'message': prepared.get('message')} | |
| robot = self.adapter._robot() | |
| if not robot.get('payload_object_id'): | |
| picked = self._robot_rule_successor_dispatch('pickup', {**reference, 'object_handle': arguments['object_handle']}) | |
| steps.append({'tool': 'pickup', 'result': picked}) | |
| if picked.get('status') != 'success': | |
| return {'status': 'error', 'data': {'steps': steps}, 'message': picked.get('message')} | |
| delivery_handles = arguments['delivery_exit_handles'] | |
| if delivery_handles: | |
| moved = self._robot_rule_successor_dispatch('traverse_known_exit', {'exit_handles': delivery_handles}) | |
| steps.append({'tool': 'traverse_known_exit', 'result': moved}) | |
| if moved.get('status') != 'success': | |
| return {'status': 'error', 'data': {'steps': steps}, 'message': moved.get('message')} | |
| released = self._robot_rule_successor_dispatch('release', reference) | |
| steps.append({'tool': 'release', 'result': released}) | |
| if released.get('status') != 'success': | |
| recovery = None | |
| if delivery_handles: | |
| recovery = self._robot_rule_successor_dispatch('traverse_known_exit', {'exit_handles': list(reversed(delivery_handles))}) | |
| steps.append({'tool': 'return_to_source', 'result': recovery}) | |
| message = str(released.get('message')) | |
| if 'EXACT_STALE_TUPLE_REQUIRED' in message: | |
| outcome = 'exact_stale_tuple_required' | |
| elif 'INTAKE_REJECTED' in message: | |
| outcome = 'intake_rejected' | |
| else: | |
| outcome = 'release_rejected' | |
| return {'status': 'error', 'data': {'outcome': outcome, 'returned_to_source': bool(recovery is None or recovery.get('status') == 'success'), 'steps': steps}, 'message': released.get('message')} | |
| closeout_handles = arguments['closeout_exit_handles'] | |
| if closeout_handles: | |
| returned = self._robot_rule_successor_dispatch('traverse_known_exit', {'exit_handles': closeout_handles}) | |
| steps.append({'tool': 'traverse_known_exit', 'result': returned}) | |
| if returned.get('status') != 'success': | |
| return {'status': 'error', 'data': {'outcome': 'delivered_not_closed', 'steps': steps}, 'message': returned.get('message')} | |
| finalized = self._robot_rule_successor_dispatch('finalize', reference) | |
| steps.append({'tool': 'finalize', 'result': finalized}) | |
| if finalized.get('status') != 'success': | |
| return {'status': 'error', 'data': {'outcome': 'delivered_not_closed', 'steps': steps}, 'message': finalized.get('message')} | |
| self._promote_completed_binding(work_order) | |
| return {'status': 'success', 'data': {'outcome': 'workflow_completed', 'work_order': work_order, 'steps': steps}, 'message': 'OK'} | |
| def grade(self): | |
| raw = self._robot_rule_successor_grade() | |
| completed = sum((bool(row['workflow_completed']) for row in raw['orders'])) | |
| result = ext_deepcopy(raw) | |
| result['diagnostic_partial_score'] = raw['score'] | |
| result['score'] = 25.0 * completed | |
| result['score_contract'] = '25 points per fully closed work order' | |
| result['partial_milestones'] = 'diagnostic_only' | |
| return result | |
| def _priority_error(self, tool, arguments): | |
| if tool not in DATA_ORDERED_MUTATIONS or self.adapter is None: | |
| return None | |
| if not self.adapter._schema_valid(tool, arguments): | |
| return None | |
| work_order = arguments.get('work_order') | |
| listed = self._listed_orders() | |
| if work_order not in listed: | |
| return None | |
| completed = {row['work_order']: bool(row['workflow_completed']) for row in self.adapter.grade()['orders']} | |
| requested_index = listed.index(work_order) | |
| pending = next((prior for prior in listed[:requested_index] if not completed.get(prior, False)), None) | |
| if pending is None: | |
| return None | |
| return self.adapter._attempt(tool, lambda : {'status': 'error', 'data': {}, 'message': f'PRIORITY_WORK_ORDER_PENDING: an earlier listed work order must be fully closed first ({pending})'}) | |
| def _release_context(self, arguments): | |
| if self.adapter is None or not isinstance(arguments.get('work_order'), str): | |
| return None | |
| order = self.adapter._order(arguments['work_order']) | |
| if order is None: | |
| return None | |
| (task, obj) = self.adapter._work_context(order) | |
| if task is None or obj is None: | |
| return None | |
| handling = obj.get('handling_code') | |
| intake = task.get('intake_code') | |
| profile = task.get('transfer_profile_submitted') | |
| if not all((isinstance(value, str) for value in (handling, intake, profile))): | |
| return None | |
| storage_handle = None | |
| if isinstance(obj.get('storage_unit_id'), str): | |
| storage_handle = self.adapter._handle('storage', obj['storage_unit_id']) | |
| return {'task_id': self.current_task_id, 'work_order': arguments['work_order'], 'cell': f'{handling}:{intake}', 'handling_code': handling, 'intake_code': intake, 'profile': profile, 'stock_group': task.get('stock_group'), 'source_station': self.adapter._room_name(task.get('source_room_id')), 'destination_station': self.adapter._room_name(task.get('target_room_id')), 'storage_handle': storage_handle, 'object_name': obj.get('display_name')} | |
| def _record_release(self, context, result): | |
| if context is None: | |
| return | |
| cell = context['cell'] | |
| state = self.rule_revalidation.get(cell) | |
| if state == 'awaiting_exact_stale' and result.get('status') == 'error' and ('INTAKE_REJECTED' in str(result.get('message'))) and (context['profile'] == (self.transfer_evidence.get(cell) or {}).get('profile')): | |
| self.rule_revalidation[cell] = 'awaiting_replacement' | |
| return | |
| if result.get('status') != 'success': | |
| return | |
| self.transfer_evidence[cell] = ext_deepcopy(context) | |
| if state in {'awaiting_exact_stale', 'awaiting_replacement'}: | |
| self.rule_revalidation[cell] = 'validated' | |
| def isolated_raw(self): | |
| with ext_isolated_package_namespace(CASE_DIR / 'data/world/private/world/environment'): | |
| yield | |
| def checkpoint(self): | |
| if self.adapter is None: | |
| raise RuntimeError('activate a task before checkpointing') | |
| with self.isolated_raw(): | |
| return ext_deepcopy(fn_checkpoint_state(self.adapter, self.state_dir)) | |
| def raw_database(self): | |
| return ext_deepcopy(self.snapshot()['database']) | |
| def close(self): | |
| if self._temporary is not None: | |
| self._temporary.cleanup() | |
| self._temporary = None | |
| def _robot_local_rule_runtime_stage_retained_source(self, arguments): | |
| result = self._robot_rule_successor_stage_retained_source(arguments) | |
| order = self._task_order(arguments.get('work_order', '')) | |
| return fn_scoped_storage_diagnostics(result, (order or {}).get('object_name')) | |
| def _robot_source_runtime_validate_restored_evidence_against_world(self): | |
| if self.current_task_id is None or int(self.current_task_id[1:]) < 9: | |
| return self._robot_rule_successor_validate_restored_evidence_against_world() | |
| fields = ('verified_stock_groups', 'transfer_evidence', 'rule_revalidation', 'provisional_stock_groups') | |
| original = {name: getattr(self, name) for name in fields} | |
| adapter = self.adapter | |
| moved = fn_destinations() | |
| old_source = {key for (key, row) in original['verified_stock_groups'].items() if key in moved and row['task_id'] < 'T09'} | |
| old_transfer = {key for (key, row) in original['transfer_evidence'].items() if row.get('stock_group') in moved and row['task_id'] < 'T09'} | |
| try: | |
| for historical in (False, True): | |
| self.verified_stock_groups = {key: row for (key, row) in original['verified_stock_groups'].items() if (key in old_source) == historical} | |
| self.transfer_evidence = {key: row for (key, row) in original['transfer_evidence'].items() if (key in old_transfer) == historical} | |
| self.rule_revalidation = {key: row for (key, row) in original['rule_revalidation'].items() if key in self.transfer_evidence} | |
| self.provisional_stock_groups = {} if historical else original['provisional_stock_groups'] | |
| self.adapter = HistoricalStorageView(adapter) if historical else adapter | |
| self._robot_rule_successor_validate_restored_evidence_against_world() | |
| finally: | |
| self.adapter = adapter | |
| for (name, value) in original.items(): | |
| setattr(self, name, value) | |
| def _robot_route_runtime_init(self, *args, **kwargs): | |
| self._restoring_route = False | |
| self._robot_intake_runtime_init(*args, **kwargs) | |
| def _robot_route_runtime_activate_task(self, task_id): | |
| receipt = self._robot_intake_runtime_activate_task(task_id) | |
| if int(task_id[1:]) >= DATA_CONTRACT['before_task']: | |
| with self.isolated_raw(): | |
| edge = next((row for row in self.adapter._all('map_edge') if row['edge_id'] == 'edge-atlas-north-ground-south-specimen-intake-to-level-one-central-return-sort')) | |
| if edge['status'] != 'blocked': | |
| self.adapter.sm.update_entity('map_edge', 'edge-atlas-north-ground-south-specimen-intake-to-level-one-central-return-sort', {'status': 'blocked'}, id_field='edge_id') | |
| return receipt | |
| def _robot_rule_successor_open_storage(self, arguments): | |
| if self.adapter is None: | |
| raise RuntimeError('activate a task before calling tools') | |
| handle = arguments.get('storage_handle') | |
| if not isinstance(handle, str): | |
| return self._robot_rule_successor_dispatch('open_storage', arguments) | |
| pending = self._task_order(self._first_pending_work_order() or '') | |
| target_group = (pending or {}).get('stock_group') | |
| resolved = self.adapter._storage(handle) | |
| actual_group = resolved[1].get('stock_group') if resolved else None | |
| authorized = actual_group in self.verified_stock_groups or (actual_group is not None and actual_group == self.authorized_new_stock_group) | |
| if actual_group == target_group and (not authorized): | |
| return self.adapter._attempt('open_storage', lambda : {'status': 'error', 'data': {}, 'message': 'SEARCH_SCOPE_NOT_AUTHORIZED: call locate_order_zone for the first pending listed order'}) | |
| issued_before = set(self.adapter.issued_object_handles) | |
| result = self._robot_rule_successor_dispatch('open_storage', arguments) | |
| if result.get('status') != 'success': | |
| self._revoke_hidden_object_handles(issued_before, result) | |
| return result | |
| data = result.get('data') or {} | |
| if actual_group != target_group: | |
| data.pop('stock_group', None) | |
| data.pop('calibration_records', None) | |
| data['objects'] = [] | |
| data['matches_pending_stock_group'] = False | |
| data['scope'] = 'current_priority_order' | |
| self._revoke_hidden_object_handles(issued_before, result) | |
| return result | |
| object_name = (pending or {}).get('object_name') | |
| data['objects'] = [row for row in data.get('objects', []) if row.get('display_name') == object_name] | |
| data['matches_pending_stock_group'] = True | |
| data['scope'] = 'current_priority_order' | |
| data['binding_retention_status'] = 'retained_verified' if actual_group in self.verified_stock_groups else 'provisional_until_work_order_closed' | |
| robot = self.adapter._robot() or {} | |
| room = self.adapter._room(robot.get('current_room_id')) or {} | |
| if isinstance(actual_group, str): | |
| evidence = {'task_id': str(self.current_task_id), 'station': str(room.get('name')), 'storage_handle': handle, 'zone': str(self._room_zone(room.get('room_id')))} | |
| if actual_group in self.verified_stock_groups: | |
| self.verified_stock_groups.setdefault(actual_group, evidence) | |
| else: | |
| self.provisional_stock_groups.setdefault(actual_group, evidence) | |
| self._revoke_hidden_object_handles(issued_before, result) | |
| return result | |
| def _robot_route_runtime_snapshot(self): | |
| value = self._robot_intake_runtime_snapshot() | |
| if not self._restoring_route: | |
| value['route_migration_contract'] = ext_deepcopy(DATA_CONTRACT) | |
| return value | |
| def _robot_route_runtime_restore(self, snapshot): | |
| value = ext_deepcopy(snapshot) | |
| if value.pop('route_migration_contract', None) != DATA_CONTRACT: | |
| raise ValueError('Robot route migration identity differs') | |
| self._restoring_route = True | |
| try: | |
| self._robot_intake_runtime_restore(value) | |
| finally: | |
| self._restoring_route = False | |
| if self.snapshot() != snapshot: | |
| raise ValueError('Robot route migration snapshot did not round trip') | |
| def _robot_rule_successor_locate_order_zone(self, arguments): | |
| spec = self._task_order(arguments.get('work_order', '')) | |
| if spec is not None and spec['stock_group'] not in self.verified_stock_groups: | |
| self.authorized_new_stock_group = None | |
| result = self._robot_rule_successor_locate_order_zone_2(arguments) | |
| if result.get('status') == 'success': | |
| data = result.get('data') or {} | |
| data.pop('new_stock_binding_limit', None) | |
| return result | |
| def _robot_rule_successor_dispatch(self, tool, arguments): | |
| if self.adapter is None: | |
| raise RuntimeError('activate a task before calling tools') | |
| values = ext_deepcopy(arguments) | |
| with self.isolated_raw(): | |
| priority = self._priority_error(tool, values) | |
| if priority is not None: | |
| return ext_deepcopy(priority) | |
| context = self._release_context(values) if tool == 'release' else None | |
| revalidation = self._revalidation_error(tool, context) | |
| if revalidation is not None: | |
| return ext_deepcopy(revalidation) | |
| result = ext_deepcopy(self.adapter.call(tool, values)) | |
| if tool == 'release': | |
| self._record_release(context, result) | |
| return result | |
| def _robot_rule_successor_dispatch_2(self, tool, arguments): | |
| if self.adapter is None: | |
| raise RuntimeError('activate a task before calling tools') | |
| self.business_call_count += 1 | |
| if self.business_call_count > self.business_call_limit(): | |
| return self._attach_call_budget({'status': 'error', 'data': {}, 'message': 'BUSINESS_CALL_LIMIT_EXHAUSTED: no further business calls are available in this episode'}) | |
| values = ext_deepcopy(arguments) | |
| if tool == 'stage_retained_source': | |
| result = self._stage_retained_source(values) | |
| elif tool == 'locate_order_zone': | |
| result = self._locate_order_zone(values) | |
| elif tool == 'execute_transfer_attempt': | |
| result = self._execute_transfer_attempt(values) | |
| elif tool == 'open_storage': | |
| result = self._open_storage(values) | |
| else: | |
| issued_before = set(self.adapter.issued_object_handles) if tool == 'scan_current_room' else set() | |
| result = RobotSourceScopeRuntime._robot_rule_successor_dispatch(self, tool, values) | |
| self._annotate_zone_response(tool, result) | |
| if tool == 'scan_current_room': | |
| self._revoke_hidden_object_handles(issued_before, result) | |
| if tool == 'finalize' and result.get('status') == 'success': | |
| work_order = values.get('work_order') | |
| if isinstance(work_order, str): | |
| self._promote_completed_binding(work_order) | |
| self.visible_object_handles.update(self._visible_object_handles(result)) | |
| return self._attach_call_budget(result) | |
| def _robot_rule_successor_grade(self): | |
| if self.adapter is None: | |
| raise RuntimeError('activate a task before grading') | |
| with self.isolated_raw(): | |
| return ext_deepcopy(self.adapter.grade()) | |
| def _robot_rule_successor_stage_retained_source(self, arguments): | |
| if not self._valid_retained_arguments(arguments): | |
| return {'status': 'error', 'data': {}, 'message': 'INVALID_ARGUMENTS: arguments do not match the tool schema'} | |
| spec = self._task_order(arguments['work_order']) | |
| evidence = self.verified_stock_groups.get((spec or {}).get('stock_group')) | |
| if spec is None or evidence is None or evidence.get('station') != arguments['source_station'] or (evidence.get('storage_handle') != arguments['storage_handle']): | |
| return {'status': 'error', 'data': {'outcome': 'retained_binding_mismatch'}, 'message': 'RETAINED_BINDING_MISMATCH: exact verified source evidence is required'} | |
| source_handles = arguments['source_exit_handles'] | |
| if source_handles: | |
| moved = RobotSourceScopeRuntime._robot_rule_successor_dispatch(self, 'traverse_known_exit', {'exit_handles': source_handles}) | |
| if moved.get('status') != 'success': | |
| return {'status': 'error', 'data': {'outcome': 'source_route_stale', 'steps': [moved]}, 'message': moved.get('message')} | |
| robot = self.adapter._robot() | |
| room = self.adapter._room(robot.get('current_room_id')) if robot else None | |
| if (room or {}).get('name') != arguments['source_station']: | |
| return {'status': 'error', 'data': {'outcome': 'source_route_mismatch'}, 'message': 'SOURCE_ROUTE_MISMATCH: route did not reach retained station'} | |
| issued_before = set(self.adapter.issued_object_handles) | |
| opened = RobotSourceScopeRuntime._robot_rule_successor_dispatch(self, 'open_storage', {'storage_handle': arguments['storage_handle']}) | |
| objects = (opened.get('data') or {}).get('objects') or [] | |
| matches = [row for row in objects if row.get('display_name') == spec['object_name']] | |
| if opened.get('status') != 'success' or len(matches) != 1: | |
| self._revoke_hidden_object_handles(issued_before, {'data': {'objects': matches}}) | |
| return {'status': 'error', 'data': {'outcome': 'retained_source_unavailable', 'steps': [opened]}, 'message': opened.get('message') or 'retained source object unavailable'} | |
| object_row = matches[0] | |
| self._revoke_hidden_object_handles(issued_before, {'data': {'objects': matches}}) | |
| inspected = RobotSourceScopeRuntime._robot_rule_successor_dispatch(self, 'inspect_local_object', {'object_handle': object_row['object_handle']}) | |
| if inspected.get('status') != 'success': | |
| return {'status': 'error', 'data': {'outcome': 'retained_object_unavailable', 'steps': [opened, inspected]}, 'message': inspected.get('message')} | |
| return {'status': 'success', 'data': {'outcome': 'retained_source_staged', 'retained_source': fn_public_retained_source_evidence(evidence), 'object': ext_deepcopy(object_row), 'inspection': ext_deepcopy(inspected.get('data') or {}), 'battery_percent': self.adapter._battery()}, 'message': 'OK'} | |
| def _robot_rule_successor_validate_restored_evidence_against_world(runtime): | |
| try: | |
| RobotSourceScopeRuntime._robot_rule_successor_validate_restored_evidence_against_world_2(runtime) | |
| except ValueError as error: | |
| if str(error) != 'Robot v8 snapshot contains object handles absent from public evidence': | |
| raise | |
| current = DATA_TASK_IDS.index(runtime.current_task_id) | |
| objects = {row.get('object_id') for row in runtime.adapter._all('object_item')} | |
| ids = {row.get('object_id') for row in runtime.adapter._all('service_task') if row.get('experience_episode_id') in DATA_TASK_IDS[:current + 1]} | |
| allowed = {runtime.adapter._handle('object', ident) for ident in ids & objects if isinstance(ident, str)} | |
| visible = set(runtime.visible_object_handles) | |
| if visible != set(runtime.adapter.issued_object_handles) or not visible <= allowed: | |
| raise | |
| def _robot_intake_runtime_init(self, *args, **kwargs): | |
| self._own_closeouts = {} | |
| self._restoring_evolution = False | |
| self._robot_rule_successor_init(*args, **kwargs) | |
| def _robot_intake_runtime_activate_task(self, task_id): | |
| old = self.current_task_id | |
| result = self._robot_rule_successor_activate_task(task_id) | |
| if old != self.current_task_id: | |
| self._own_closeouts = {} | |
| return result | |
| def _robot_intake_runtime_snapshot(self): | |
| value = self._robot_rule_successor_snapshot() | |
| if not self._restoring_evolution: | |
| value['evolution_contract'] = {'case_version': 'robot-scope-reuse-evolution-v12', 'schedule': ext_deepcopy(DATA_SCHEDULE_2), 'config_sha256': mod_hashlib.sha256((CASE_DIR / 'data/world/private/config.json').read_bytes()).hexdigest()} | |
| value['own_closeout_receipts'] = ext_deepcopy(self._own_closeouts) | |
| return value | |
| def _robot_intake_runtime_restore(self, snapshot): | |
| value = ext_deepcopy(snapshot) | |
| expected = {'case_version': 'robot-scope-reuse-evolution-v12', 'schedule': DATA_SCHEDULE_2, 'config_sha256': mod_hashlib.sha256((CASE_DIR / 'data/world/private/config.json').read_bytes()).hexdigest()} | |
| if value.pop('evolution_contract', None) != expected: | |
| raise ValueError('Robot intake-balanced contract differs') | |
| receipts = value.pop('own_closeout_receipts') | |
| self._restoring_evolution = True | |
| try: | |
| self._robot_rule_successor_restore(value) | |
| finally: | |
| self._restoring_evolution = False | |
| self._own_closeouts = receipts | |
| if self.snapshot() != snapshot: | |
| raise ValueError('Robot intake-balanced snapshot did not round trip') | |
| def _robot_rule_successor_locate_order_zone_2(self, arguments): | |
| if set(arguments) != {'work_order'} or not isinstance(arguments.get('work_order'), str): | |
| return {'status': 'error', 'data': {}, 'message': 'INVALID_ARGUMENTS: arguments do not match the tool schema'} | |
| work_order = arguments['work_order'] | |
| pending = self._first_pending_work_order() | |
| if work_order != pending: | |
| return {'status': 'error', 'data': {'first_pending_work_order': pending}, 'message': 'PRIORITY_WORK_ORDER_PENDING: zone lookup is limited to the first pending listed work order'} | |
| spec = self._task_order(work_order) | |
| if spec is None: | |
| return {'status': 'error', 'data': {}, 'message': 'WORK_ORDER_NOT_FOUND: the work-order reference is unknown'} | |
| stock_group = spec['stock_group'] | |
| retained = stock_group in self.verified_stock_groups | |
| if not retained: | |
| if self.authorized_new_stock_group is None: | |
| self.authorized_new_stock_group = stock_group | |
| elif self.authorized_new_stock_group != stock_group: | |
| return {'status': 'error', 'data': {'new_stock_bindings_authorized': 1, 'new_stock_binding_limit': 1}, 'message': 'NEW_STOCK_BINDING_LIMIT: this episode already authorized one previously unseen stock binding'} | |
| return {'status': 'success', 'data': {'work_order': work_order, 'source_zone': self._room_zone(spec['source']), 'destination_zone': self._room_zone(spec['target']), 'zone_adjacency': ext_deepcopy(DATA_ZONE_ADJACENCY), 'candidate_station_counts': self._zone_counts(), 'binding_status': 'retained_verified' if retained else 'new_authorized', 'exact_source_disclosed': False}, 'message': 'OK'} | |
| def _robot_rule_successor_validate_restored_evidence_against_world_2(self): | |
| if self.adapter is None or self.current_task_id is None: | |
| raise ValueError('Robot v8 restore did not create an active world') | |
| current_index = DATA_TASK_IDS.index(self.current_task_id) | |
| def task_is_in_prefix(task_id): | |
| return isinstance(task_id, str) and task_id in DATA_TASK_IDS and (DATA_TASK_IDS.index(task_id) <= current_index) | |
| rooms = {row.get('room_id'): row for row in self.adapter._all('room')} | |
| objects = {row.get('object_id'): row for row in self.adapter._all('object_item')} | |
| service_tasks = self.adapter._all('service_task') | |
| def storage_matches(stock_group, evidence): | |
| resolved = self.adapter._storage(evidence['storage_handle']) | |
| if resolved is None: | |
| return False | |
| (room, storage) = resolved | |
| return bool(storage.get('stock_group') == stock_group and room.get('name') == evidence['station'] and (self._room_zone(room.get('room_id')) == evidence['zone'])) | |
| for (stock_group, evidence) in self.verified_stock_groups.items(): | |
| if not task_is_in_prefix(evidence['task_id']): | |
| raise ValueError('Robot v8 verified stock evidence is from the future') | |
| if not storage_matches(stock_group, evidence): | |
| raise ValueError('Robot v8 verified stock evidence does not match storage') | |
| completed = any((row.get('experience_episode_id') == evidence['task_id'] and row.get('stock_group') == stock_group and (row.get('status') == 'completed') and ((row.get('source_inspection_receipt') or {}).get('status') == 'verified') and ((rooms.get(row.get('source_room_id')) or {}).get('name') == evidence['station']) for row in service_tasks)) | |
| if not completed: | |
| raise ValueError('Robot v8 verified stock evidence lacks a completed work order') | |
| pending_order = self._task_order(self._first_pending_work_order() or '') | |
| for (stock_group, evidence) in self.provisional_stock_groups.items(): | |
| if evidence['task_id'] != self.current_task_id: | |
| raise ValueError('Robot v8 provisional stock evidence crossed tasks') | |
| if stock_group != self.authorized_new_stock_group: | |
| raise ValueError('Robot v8 provisional stock evidence lacks matching authorization') | |
| if (pending_order or {}).get('stock_group') != stock_group: | |
| raise ValueError('Robot v8 provisional stock evidence is not the current target') | |
| if not storage_matches(stock_group, evidence): | |
| raise ValueError('Robot v8 provisional stock evidence does not match storage') | |
| current_groups = {row['stock_group'] for row in fn_episode_spec_5(self.current_task_id)['orders']} | |
| if self.authorized_new_stock_group is not None and self.authorized_new_stock_group not in current_groups: | |
| raise ValueError('Robot v8 stock authorization is outside the current task') | |
| config = fn_load_config_2() | |
| rule_epoch = str(self.adapter.snapshot().get('rule_epoch')) | |
| rule_table = config['pre_rule_table'] if rule_epoch == config['drift']['from_rule_epoch'] else config['post_rule_table'] | |
| for (cell, evidence) in self.transfer_evidence.items(): | |
| if not task_is_in_prefix(evidence.get('task_id')): | |
| raise ValueError('Robot v8 transfer evidence is from the future') | |
| order_spec = next((row for row in fn_episode_spec_5(evidence['task_id'])['orders'] if row.get('work_order') == evidence.get('work_order')), None) | |
| task = next((row for row in service_tasks if row.get('task_id') == (order_spec or {}).get('task_id')), None) | |
| obj = objects.get((task or {}).get('object_id')) | |
| source = rooms.get((task or {}).get('source_room_id')) | |
| destination = rooms.get((task or {}).get('target_room_id')) | |
| intake_receipt = (task or {}).get('intake_receipt') or {} | |
| inspection = (task or {}).get('source_inspection_receipt') or {} | |
| storage_ok = storage_matches(evidence.get('stock_group', ''), {'station': str(evidence.get('source_station')), 'storage_handle': str(evidence.get('storage_handle')), 'zone': str(self._room_zone((source or {}).get('room_id'))), 'task_id': str(evidence.get('task_id'))}) | |
| if not (task is not None and obj is not None and (order_spec is not None) and (task.get('experience_episode_id') == evidence.get('task_id')) and (task.get('stock_group') == evidence.get('stock_group')) and (task.get('intake_code') == evidence.get('intake_code')) and (source is not None) and (source.get('name') == evidence.get('source_station')) and (destination is not None) and (destination.get('name') == evidence.get('destination_station')) and (obj.get('display_name') == evidence.get('object_name')) and (inspection.get('status') == 'verified') and (inspection.get('handling_code') == evidence.get('handling_code')) and (intake_receipt.get('status') == 'accepted') and (intake_receipt.get('profile') == evidence.get('profile')) and storage_ok): | |
| raise ValueError(f'Robot v8 transfer evidence does not match business state for {cell}') | |
| action_reasons = {str(row.get('reason')) for row in self.adapter.snapshot().get('action_ledger', [])} | |
| for (cell, state) in self.rule_revalidation.items(): | |
| evidence = self.transfer_evidence[cell] | |
| evidence_task = evidence['task_id'] | |
| (handling, intake) = cell.split(':', 1) | |
| if current_index < DATA_TASK_IDS.index('T09'): | |
| raise ValueError('Robot v8 revalidation state appeared before drift') | |
| if state in {'awaiting_exact_stale', 'awaiting_replacement'}: | |
| if not (evidence_task < 'T09' and handling in DATA_CHANGED_HANDLING_ATOMS and (config['pre_rule_table'][cell] == evidence['profile'])): | |
| raise ValueError('Robot v8 stale revalidation evidence is invalid') | |
| if state == 'awaiting_replacement' and 'INTAKE_REJECTED' not in action_reasons: | |
| raise ValueError('Robot v8 replacement state lacks a stale rejection') | |
| elif state == 'validated': | |
| if not (evidence_task >= 'T09' and rule_table[cell] == evidence['profile']): | |
| raise ValueError('Robot v8 validated revalidation state is invalid') | |
| allowed_object_ids = set() | |
| for row in service_tasks: | |
| episode_id = row.get('experience_episode_id') | |
| if not task_is_in_prefix(episode_id): | |
| continue | |
| if row.get('status') == 'completed' or (row.get('source_inspection_receipt') or {}).get('status') == 'verified': | |
| allowed_object_ids.add(row.get('object_id')) | |
| robot = self.adapter._robot() or {} | |
| if isinstance(robot.get('payload_object_id'), str): | |
| allowed_object_ids.add(robot['payload_object_id']) | |
| if pending_order is not None: | |
| allowed_object_ids.add(pending_order['object_id']) | |
| allowed_handles = {self.adapter._handle('object', object_id) for object_id in allowed_object_ids if isinstance(object_id, str)} | |
| issued_handles = set(self.adapter.issued_object_handles) | |
| if issued_handles != self.visible_object_handles: | |
| raise ValueError('Robot v8 object capability ledger differs from public visibility') | |
| hidden_handles = self.visible_object_handles - allowed_handles | |
| if hidden_handles: | |
| raise ValueError('Robot v8 snapshot contains object handles absent from public evidence') | |
| def _robot_rule_successor_init(self, state_dir=None, *, snapshot=None): | |
| self._restoring_v8_snapshot = False | |
| self._robot_rule_successor_init_2(state_dir=state_dir, snapshot=snapshot) | |
| def _robot_rule_successor_activate_task(self, task_id): | |
| receipt = self._robot_rule_successor_activate_task_2(task_id) | |
| if receipt.get('already_prepared') is True: | |
| return receipt | |
| with self.isolated_raw(): | |
| self.adapter._set_battery(170) | |
| after = fn_semantic_state(self.adapter.sm) | |
| receipt = ext_deepcopy(receipt) | |
| recovery = receipt.get('supervisor_recovery') or {} | |
| if isinstance(recovery.get('after'), dict): | |
| recovery['after']['battery_percent'] = 170 | |
| for change in receipt.get('changes', []): | |
| if change.get('table') == 'robot_unit' and isinstance(change.get('after'), dict): | |
| change['after'] = next((row for row in after['robot_unit'] if row['robot_id'] == change['id'])) | |
| receipt['after_sha256'] = fn_digest_2(after) | |
| if isinstance(receipt.get('public_notice'), str): | |
| receipt['public_notice'] = mod_re.sub('with \\d+ battery units', f'with {170} battery units', receipt['public_notice']) | |
| receipt['successor_budget_override'] = {'task_id': task_id, 'battery_units': 170, 'business_call_limit': self.business_call_limit(), 'basis': 'one physical allowance independent of stream position and rule epoch'} | |
| return receipt | |
| def _robot_rule_successor_snapshot(self): | |
| value = self._robot_rule_successor_snapshot_2() | |
| if self._restoring_v8_snapshot: | |
| return value | |
| value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v9' | |
| return value | |
| def _robot_rule_successor_restore(self, snapshot): | |
| if not isinstance(snapshot, dict) or snapshot.get('schema') != 'rescopebench-robot-rule-runtime-snapshot/v9': | |
| raise ValueError('unsupported Robot rule v9 snapshot') | |
| value = ext_deepcopy(snapshot) | |
| value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v8' | |
| self._restoring_v8_snapshot = True | |
| try: | |
| self._robot_rule_successor_restore_2(value) | |
| finally: | |
| self._restoring_v8_snapshot = False | |
| if self.snapshot() != snapshot: | |
| raise ValueError('Robot rule v9 snapshot did not round trip') | |
| def _robot_rule_successor_init_2(self, state_dir=None, *, snapshot=None): | |
| self.business_call_count = 0 | |
| self.authorized_new_stock_group: str | None = None | |
| self.provisional_stock_groups: dict[str, dict[str, str]] = {} | |
| self.verified_stock_groups: dict[str, dict[str, str]] = {} | |
| self.visible_object_handles: set[str] = set() | |
| self._restoring_v7_snapshot = False | |
| self._robot_rule_successor_init_3(state_dir=state_dir, snapshot=snapshot) | |
| def _robot_rule_successor_activate_task_2(self, task_id): | |
| receipt = self._robot_rule_successor_activate_task_3(task_id) | |
| if receipt.get('already_prepared') is not True: | |
| budget = DATA_EPISODE_BUDGETS[task_id] | |
| with self.isolated_raw(): | |
| self.adapter._set_battery(budget) | |
| receipt = ext_deepcopy(receipt) | |
| recovery = receipt.get('supervisor_recovery') or {} | |
| if isinstance(recovery.get('after'), dict): | |
| recovery['after']['battery_percent'] = budget | |
| for change in receipt.get('changes', []): | |
| if change.get('table') == 'robot_unit' and isinstance(change.get('after'), dict): | |
| change['after']['battery_percent'] = budget | |
| notice = receipt.get('public_notice') | |
| if isinstance(notice, str): | |
| receipt['public_notice'] = mod_re.sub('with \\d+ battery units', f'with {budget} battery units', notice) | |
| receipt['successor_budget_override'] = {'task_id': task_id, 'battery_units': budget, 'business_call_limit': self.business_call_limit(), 'basis': 'uniform post-cold physical envelope with public call frontier'} | |
| return receipt | |
| def _robot_rule_successor_snapshot_2(self): | |
| value = self._robot_rule_successor_snapshot_3() | |
| if self._restoring_v7_snapshot: | |
| return value | |
| value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v8' | |
| value['business_call_count'] = self.business_call_count | |
| value['authorized_new_stock_group'] = self.authorized_new_stock_group | |
| value['provisional_stock_groups'] = ext_deepcopy(self.provisional_stock_groups) | |
| value['verified_stock_groups'] = ext_deepcopy(self.verified_stock_groups) | |
| value['visible_object_handles'] = sorted(self.visible_object_handles) | |
| return value | |
| def _robot_rule_successor_restore_2(self, snapshot): | |
| if not isinstance(snapshot, dict) or snapshot.get('schema') != 'rescopebench-robot-rule-runtime-snapshot/v8': | |
| raise ValueError('unsupported Robot rule v8 snapshot') | |
| fn__validate_snapshot_extensions(snapshot) | |
| value = ext_deepcopy(snapshot) | |
| self.business_call_count = value.pop('business_call_count') | |
| self.authorized_new_stock_group = value.pop('authorized_new_stock_group') | |
| self.provisional_stock_groups = value.pop('provisional_stock_groups') | |
| self.verified_stock_groups = value.pop('verified_stock_groups') | |
| self.visible_object_handles = set(value.pop('visible_object_handles')) | |
| value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v7' | |
| self._restoring_v7_snapshot = True | |
| try: | |
| self._robot_rule_successor_restore_3(value) | |
| finally: | |
| self._restoring_v7_snapshot = False | |
| self._validate_restored_evidence_against_world() | |
| if self.snapshot() != snapshot: | |
| raise ValueError('Robot rule v8 snapshot did not round trip') | |
| def _robot_rule_successor_init_3(self, state_dir=None, *, snapshot=None): | |
| self._restoring_v6_snapshot = False | |
| self._robot_rule_successor_init_4(state_dir=state_dir, snapshot=snapshot) | |
| def _robot_rule_successor_activate_task_3(self, task_id): | |
| receipt = self._robot_rule_successor_activate_task_4(task_id) | |
| if receipt.get('already_prepared') is not True: | |
| self.business_call_count = 0 | |
| self.authorized_new_stock_group = None | |
| self.provisional_stock_groups = {} | |
| budget = DATA_EPISODE_BUDGETS_2[task_id] | |
| with self.isolated_raw(): | |
| self.adapter._set_battery(budget) | |
| receipt = ext_deepcopy(receipt) | |
| recovery = receipt.get('supervisor_recovery') or {} | |
| if isinstance(recovery.get('after'), dict): | |
| recovery['after']['battery_percent'] = budget | |
| for change in receipt.get('changes', []): | |
| if change.get('table') == 'robot_unit' and isinstance(change.get('after'), dict): | |
| change['after']['battery_percent'] = budget | |
| notice = receipt.get('public_notice') | |
| if isinstance(notice, str): | |
| receipt['public_notice'] = mod_re.sub('with \\d+ battery units', f'with {budget} battery units', notice) | |
| receipt['successor_budget_override'] = {'task_id': task_id, 'battery_units': budget, 'business_call_limit': 32, 'new_stock_binding_limit': 1, 'basis': 'full informed replay plus worst-order bounded zone search'} | |
| return receipt | |
| def _robot_rule_successor_snapshot_3(self): | |
| value = self._robot_rule_successor_snapshot_4() | |
| if self._restoring_v6_snapshot: | |
| return value | |
| value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v7' | |
| return value | |
| def _robot_rule_successor_restore_3(self, snapshot): | |
| if not isinstance(snapshot, dict) or snapshot.get('schema') != 'rescopebench-robot-rule-runtime-snapshot/v7': | |
| raise ValueError('unsupported Robot rule v7 snapshot') | |
| fn__validate_snapshot_extensions_2(snapshot) | |
| value = ext_deepcopy(snapshot) | |
| value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v6' | |
| self._restoring_v6_snapshot = True | |
| try: | |
| self._robot_rule_successor_restore_4(value) | |
| finally: | |
| self._restoring_v6_snapshot = False | |
| if self.snapshot() != snapshot: | |
| raise ValueError('Robot rule v7 snapshot did not round trip') | |
| def _robot_rule_successor_init_4(self, state_dir=None, *, snapshot=None): | |
| self.transfer_evidence: dict[str, dict[str, ext_Any]] = {} | |
| self.rule_revalidation: dict[str, str] = {} | |
| self._restoring_parent_snapshot = False | |
| self._robot_rule_successor_init_5(state_dir=state_dir, snapshot=snapshot) | |
| def _robot_rule_successor_activate_task_4(self, task_id): | |
| receipt = self._robot_rule_successor_activate_task_5(task_id) | |
| if task_id != 'T01' or receipt.get('already_prepared') is True: | |
| return receipt | |
| with self.isolated_raw(): | |
| self.adapter._set_battery(72) | |
| receipt = ext_deepcopy(receipt) | |
| recovery = receipt.get('supervisor_recovery') or {} | |
| if isinstance(recovery.get('after'), dict): | |
| recovery['after']['battery_percent'] = 72 | |
| for change in receipt.get('changes', []): | |
| if change.get('table') == 'robot_unit' and isinstance(change.get('after'), dict): | |
| change['after']['battery_percent'] = 72 | |
| notice = receipt.get('public_notice') | |
| if isinstance(notice, str): | |
| receipt['public_notice'] = notice.replace(f'with {93} battery units', f'with {72} battery units') | |
| receipt['successor_budget_override'] = {'task_id': 'T01', 'battery_units': 72, 'basis': 'provider-free cold cap plus honest weighted cost intervals'} | |
| return receipt | |
| def _robot_rule_successor_snapshot_4(self): | |
| value = self._robot_rule_successor_snapshot_5() | |
| if self._restoring_parent_snapshot: | |
| return value | |
| value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v6' | |
| value['transfer_evidence'] = ext_deepcopy(self.transfer_evidence) | |
| value['rule_revalidation'] = ext_deepcopy(self.rule_revalidation) | |
| return value | |
| def _robot_rule_successor_restore_4(self, snapshot): | |
| if snapshot.get('schema') != 'rescopebench-robot-rule-runtime-snapshot/v6': | |
| raise ValueError('unsupported Robot rule v6 snapshot') | |
| value = ext_deepcopy(snapshot) | |
| self.transfer_evidence = ext_deepcopy(value.pop('transfer_evidence', {})) | |
| self.rule_revalidation = ext_deepcopy(value.pop('rule_revalidation', {})) | |
| value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v4' | |
| self._restoring_parent_snapshot = True | |
| try: | |
| self._robot_rule_successor_restore_5(value) | |
| finally: | |
| self._restoring_parent_snapshot = False | |
| def _robot_rule_successor_init_5(self, state_dir=None, *, snapshot=None): | |
| self._temporary = None | |
| if state_dir is None: | |
| self._temporary = mod_tempfile.TemporaryDirectory(prefix='robot-rule-v4-') | |
| state_dir = ext_Path(self._temporary.name) / 'state' | |
| self.state_dir = ext_Path(state_dir).resolve() | |
| self.current_task_id: str | None = None | |
| self.adapter = None | |
| if snapshot is not None: | |
| self.restore(snapshot) | |
| def _robot_rule_successor_activate_task_5(self, task_id): | |
| receipt = self._robot_rule_successor_activate_task_6(task_id) | |
| if task_id == 'T09': | |
| for (cell, evidence) in self.transfer_evidence.items(): | |
| handling = cell.split(':', 1)[0] | |
| if handling in DATA_CHANGED_HANDLING_ATOMS and evidence.get('task_id', 'T99') < 'T09': | |
| self.rule_revalidation.setdefault(cell, 'awaiting_exact_stale') | |
| return receipt | |
| def _robot_rule_successor_snapshot_5(self): | |
| if self.adapter is None or self.current_task_id is None: | |
| raise RuntimeError('activate a task before snapshotting') | |
| with self.isolated_raw(): | |
| fn_checkpoint_state(self.adapter, self.state_dir) | |
| adapter_state = ext_deepcopy(self.adapter.snapshot()) | |
| database = {path.name: mod_json.loads(path.read_text(encoding='utf-8')) for path in sorted((self.state_dir / 'database').glob('*.json'))} | |
| return {'schema': 'rescopebench-robot-rule-runtime-snapshot/v4', 'task_id': self.current_task_id, 'database': database, 'adapter': adapter_state} | |
| def _robot_rule_successor_restore_5(self, snapshot): | |
| if snapshot.get('schema') != 'rescopebench-robot-rule-runtime-snapshot/v4': | |
| raise ValueError('unsupported Robot rule successor snapshot') | |
| task_id = snapshot.get('task_id') | |
| if task_id not in DATA_TASK_IDS or not isinstance(snapshot.get('database'), dict): | |
| raise ValueError('invalid Robot rule successor snapshot') | |
| if self.state_dir.exists(): | |
| mod_shutil.rmtree(self.state_dir) | |
| database_dir = self.state_dir / 'database' | |
| database_dir.mkdir(parents=True) | |
| for (name, value) in snapshot['database'].items(): | |
| if ext_Path(name).name != name or not name.endswith('.json'): | |
| raise ValueError('snapshot database contains an invalid file name') | |
| (database_dir / name).write_text(mod_json.dumps(value, ensure_ascii=True, indent=2, sort_keys=True) + '\n', encoding='utf-8') | |
| adapter_state = ext_deepcopy(snapshot.get('adapter') or {}) | |
| ledger = adapter_state.get('observation_ledger') | |
| if not isinstance(ledger, dict): | |
| raise ValueError('snapshot is missing its observation ledger') | |
| (self.state_dir / 'observation-ledger.json').write_text(mod_json.dumps(ledger, ensure_ascii=True, indent=2, sort_keys=True) + '\n', encoding='utf-8') | |
| with self.isolated_raw(): | |
| self.adapter = fn_restore_adapter(CASE_DIR / 'data/world', self.state_dir, task_id) | |
| self.adapter._actions = ext_deepcopy(adapter_state.get('action_ledger', [])) | |
| self.adapter._next_action_index = 1 + max((int(row.get('index', 0)) for row in self.adapter._actions), default=0) | |
| metering = adapter_state.get('episode_metering') or {} | |
| self.adapter._scanned_rooms_this_episode = set(metering.get('scanned_room_ids', [])) | |
| self.adapter._accessed_storage_this_episode = set(metering.get('accessed_storage_handles', [])) | |
| self.current_task_id = task_id | |
| if self.snapshot() != snapshot: | |
| raise ValueError('Robot rule successor snapshot did not round trip') | |
| def _robot_rule_successor_activate_task_6(self, task_id): | |
| receipt = self._robot_rule_successor_activate_task_7(task_id) | |
| if task_id != 'T01' or receipt.get('already_prepared') is True: | |
| return receipt | |
| with self.isolated_raw(): | |
| self.adapter._set_battery(93) | |
| receipt = ext_deepcopy(receipt) | |
| recovery = receipt.get('supervisor_recovery') or {} | |
| if isinstance(recovery.get('after'), dict): | |
| recovery['after']['battery_percent'] = 93 | |
| for change in receipt.get('changes', []): | |
| if change.get('table') == 'robot_unit' and isinstance(change.get('after'), dict): | |
| change['after']['battery_percent'] = 93 | |
| notice = receipt.get('public_notice') | |
| if isinstance(notice, str): | |
| receipt['public_notice'] = notice.replace('with 98 battery units', f'with {93} battery units') | |
| receipt['successor_budget_override'] = {'task_id': 'T01', 'battery_units': 93, 'basis': 'deterministic action-cost frontier'} | |
| return receipt | |
| def _robot_rule_successor_activate_task_7(self, task_id): | |
| if task_id not in DATA_TASK_IDS: | |
| raise ValueError(f'unknown Robot stream task: {task_id}') | |
| with self.isolated_raw(): | |
| if self.adapter is not None and self.current_task_id != task_id: | |
| fn_checkpoint_state(self.adapter, self.state_dir) | |
| (self.adapter, receipt) = self._prepare_episode(task_id) | |
| self.current_task_id = task_id | |
| return ext_deepcopy(receipt) | |
| class HistoricalStorageView: | |
| def __init__(self, adapter): | |
| self.adapter = adapter | |
| source = CASE_DIR / 'data/assets/rooms.json' | |
| self.units = {unit['unit_id']: unit for room in mod_json.loads(source.read_text()) for unit in room.get('storage_units', [])} | |
| def __getattr__(self, name): | |
| return getattr(self.adapter, name) | |
| def _storage(self, handle): | |
| found = self.adapter._storage(handle) | |
| if found is None: | |
| return None | |
| (room, unit) = found | |
| historical = self.units.get(unit['unit_id']) | |
| return (room, {**unit, 'stock_group': historical['stock_group']}) if historical else found | |
| class RobotExperienceStreamAdapter: | |
| def __init__(self, *args, **kwargs): | |
| self._robot_experience_stream_adapter_init(*args, **kwargs) | |
| self.tools = ext_deepcopy(DATA_TOOLS_3) | |
| def traverse_known_exit(self, exit_handle=None, exit_handles=None): | |
| if exit_handles is None: | |
| return self._robot_state_action_adapter_traverse_known_exit(exit_handle) | |
| segments = [] | |
| total_cost = 0 | |
| for (index, handle) in enumerate(exit_handles, 1): | |
| result = self._robot_state_action_adapter_traverse_known_exit(handle) | |
| data = ext_deepcopy(result.get('data') or {}) | |
| total_cost += int(data.get('battery_cost') or 0) | |
| segments.append({'index': index, 'exit_handle': handle, 'status': result.get('status'), 'message': result.get('message'), 'data': data}) | |
| if result.get('status') != 'success': | |
| return fn__error(fn__code(result), 'known-route execution stopped at the first failed edge', {'requested_segments': len(exit_handles), 'completed_segments': index - 1, 'stopped_at_index': index, 'segments': segments, 'battery_percent': self._battery(), 'battery_cost': total_cost}) | |
| return fn__success({'requested_segments': len(exit_handles), 'completed_segments': len(exit_handles), 'stopped_at_index': None, 'segments': segments, 'battery_percent': self._battery(), 'battery_cost': total_cost}) | |
| def call(self, name, arguments): | |
| if name != 'traverse_known_exit': | |
| return self._robot_experience_adapter_call(name, arguments) | |
| try: | |
| mod_jsonschema.validate(arguments, DATA__TRAVERSE_PARAMETERS) | |
| except mod_jsonschema.ValidationError: | |
| return self._finish(name, fn__error('INVALID_ARGUMENTS', 'arguments do not match the tool schema')) | |
| has_single = 'exit_handle' in arguments | |
| has_batch = 'exit_handles' in arguments | |
| if has_single == has_batch: | |
| return self._finish(name, fn__error('INVALID_ARGUMENTS', 'provide exactly one of exit_handle or exit_handles')) | |
| return self.traverse_known_exit(**ext_deepcopy(arguments)) | |
| def snapshot(self): | |
| state = self._robot_experience_stream_adapter_snapshot() | |
| state['schema'] = 'robot-experience-stream-snapshot/v4' | |
| return state | |
| def _scan_observation(self): | |
| robot = self._robot() | |
| room = self._room((robot or {}).get('current_room_id')) | |
| if not robot or not room: | |
| return fn__error('CURRENT_ROOM_NOT_FOUND', 'the controlled robot has no valid current room') | |
| room_id = room['room_id'] | |
| exits = [] | |
| for edge in sorted(self._all('map_edge'), key=lambda row: row.get('edge_id', '')): | |
| destination = self._edge_destination(edge, room_id) | |
| if not destination: | |
| continue | |
| handle = self._handle('exit', edge['edge_id']) | |
| self.issued_exit_handles.add(handle) | |
| exits.append({'exit_handle': handle, 'route_type': edge.get('route_type'), 'distance_m': edge.get('distance_m'), 'status': 'open' if self._edge_usable(edge, destination) else 'blocked'}) | |
| units = [] | |
| for unit in sorted(room.get('storage_units', []), key=lambda row: row['unit_id']): | |
| handle = self._handle('storage', unit['unit_id']) | |
| self.issued_storage_handles.add(handle) | |
| units.append({'storage_handle': handle, 'display_name': unit.get('display_name') or f'Storage-{handle[-8:].upper()}', 'access_state': 'open' if unit.get('opened') else 'closed'}) | |
| objects = [] | |
| for obj in sorted(self._all('object_item'), key=lambda row: row.get('object_id', '')): | |
| if not self._object_visible_in_room(obj, room_id): | |
| continue | |
| handle = self._handle('object', obj['object_id']) | |
| self.issued_object_handles.add(handle) | |
| objects.append({'object_handle': handle, 'display_name': obj.get('display_name'), 'handling_state': obj.get('handling_state'), 'actionable': self._active_handle(handle)}) | |
| peers = [] | |
| for peer in sorted(self._all('robot_unit'), key=lambda row: row.get('robot_id', '')): | |
| if peer.get('robot_id') == self.robot_id or peer.get('current_room_id') != room_id: | |
| continue | |
| robot_handle = self._handle('robot', peer['robot_id']) | |
| self.issued_robot_handles.add(robot_handle) | |
| peers.append({'robot_handle': robot_handle, 'display_name': peer.get('display_name'), 'operational_status': peer.get('operational_status')}) | |
| obstacles = [{'obstacle_type': row.get('obstacle_type'), 'severity': row.get('severity')} for row in sorted(self._all('obstacle'), key=lambda item: item.get('obstacle_id', '')) if row.get('room_id') == room_id and row.get('status') == 'active'] | |
| condition = self._condition(room_id) | |
| return fn__success({'room': {'name': room.get('name')}, 'room_state': {'access_state': (condition or {}).get('access_state'), 'occupancy': (condition or {}).get('occupancy')}, 'peers': peers, 'storage_units': units, 'objects': objects, 'active_obstacles': obstacles, 'exits': exits}) | |
| def scan_current_room(self): | |
| robot = self._robot() | |
| room_id = (robot or {}).get('current_room_id') | |
| if not isinstance(room_id, str): | |
| return self._finish('scan_current_room', self._scan_observation()) | |
| if room_id in self._scanned_rooms_this_episode: | |
| result = self._scan_observation() | |
| result.setdefault('data', {}).update({'battery_percent': self._battery(), 'battery_cost': 0}) | |
| return self._finish('scan_current_room', result) | |
| result = self._attempt('scan_current_room', self._scan_observation) | |
| if result.get('status') == 'success': | |
| self._scanned_rooms_this_episode.add(room_id) | |
| return result | |
| def open_storage(self, storage_handle): | |
| if not isinstance(storage_handle, str) or storage_handle not in self.issued_storage_handles: | |
| return self._finish('open_storage', fn__error('STORAGE_NOT_OBSERVED', 'scan the local room before accessing a storage unit')) | |
| resolved = self._storage(storage_handle) | |
| robot = self._robot() | |
| if resolved is None or not robot or resolved[0].get('room_id') != robot.get('current_room_id'): | |
| return self._finish('open_storage', fn__error('STORAGE_NOT_LOCAL', 'the storage unit is not in the current room')) | |
| def access(): | |
| current = self._storage(storage_handle) | |
| if current is None: | |
| return fn__error('STORAGE_NOT_FOUND', 'the storage unit is unavailable') | |
| (current_room, current_unit) = current | |
| if current_unit.get('opened') is not True: | |
| current_unit['opened'] = True | |
| current_room['storage_units'] = [current_unit if row.get('unit_id') == current_unit['unit_id'] else row for row in current_room.get('storage_units', [])] | |
| self._save('room', current_room) | |
| return fn__success(self._storage_view(current_room, current_unit)) | |
| if storage_handle in self._accessed_storage_this_episode: | |
| result = access() | |
| result.setdefault('data', {}).update({'battery_percent': self._battery(), 'battery_cost': 0}) | |
| return self._finish('open_storage', result) | |
| result = self._attempt('open_storage', access) | |
| if result.get('status') == 'success': | |
| self._accessed_storage_this_episode.add(storage_handle) | |
| return result | |
| def read_work_order(self, work_order): | |
| result = self._robot_experience_stream_adapter_read_work_order(work_order) | |
| if result.get('status') == 'success': | |
| result.get('data', {}).pop('policy_version', None) | |
| return result | |
| def public_snapshot(self): | |
| """Return a minimal learner-safe projection of current runtime state. | |
| This is intentionally not a reload format. In particular, it exposes | |
| episode-local metering counts rather than private room IDs or a cache that | |
| a later adapter could silently restore. | |
| """ | |
| robot = self._robot() or {} | |
| room = self._room(robot.get('current_room_id')) | |
| active_work_order = next((work_order for (work_order, order) in self._orders.items() if order['task_id'] == robot.get('active_task_id')), None) | |
| return {'schema': 'robot-experience-stream-public-snapshot/v1', 'robot': {'operational_status': robot.get('operational_status'), 'battery_percent': int(robot.get('battery_percent') or 0), 'current_room_name': (room or {}).get('name'), 'active_work_order': active_work_order, 'carrying_payload': robot.get('payload_object_id') is not None}, 'work_orders': sorted(self._orders), 'episode_metering': {'rooms_scanned': len(self._scanned_rooms_this_episode), 'storage_units_accessed': len(self._accessed_storage_this_episode), 'cache_scope': 'current_adapter_instance'}, 'actions': ext_deepcopy(self._actions)} | |
| def _active_handle(self, object_handle): | |
| return isinstance(object_handle, str) and self._object_by_handle.get(object_handle) in self.active_object_ids | |
| def _storage_view(self, room, unit): | |
| result = self._robot_experience_adapter_storage_view(room, unit) | |
| for row in result['objects']: | |
| row['actionable'] = self._active_handle(row['object_handle']) | |
| return result | |
| def inspect_local_object(self, object_handle): | |
| if not self._active_handle(object_handle): | |
| return self._finish('inspect_local_object', fn__error('OBJECT_NOT_IN_ACTIVE_EPISODE', 'the parcel is visible but its private attributes are not actionable now')) | |
| return self._robot_experience_adapter_inspect_local_object(object_handle) | |
| def pickup(self, work_order, object_handle): | |
| if not self._active_handle(object_handle): | |
| return self._finish('pickup', fn__error('OBJECT_NOT_IN_ACTIVE_EPISODE', 'the parcel is visible but cannot be moved in this episode')) | |
| return self._robot_experience_adapter_pickup(work_order, object_handle) | |
| def import_observation_ledger(self, ledger): | |
| """Restore learned handles without allowing memory to mutate physical state.""" | |
| if not isinstance(ledger, dict): | |
| raise ValueError('observation ledger must be an object') | |
| opened = ledger.get('opened_storage_handles', []) | |
| if not isinstance(opened, list) or not all((isinstance(value, str) for value in opened)): | |
| raise ValueError('opened_storage_handles must be a list of strings') | |
| physically_open = {handle for handle in self._storage_by_handle if (resolved := self._storage(handle)) is not None and resolved[1].get('opened') is True} | |
| sanitized = ext_deepcopy(ledger) | |
| sanitized['opened_storage_handles'] = sorted(set(opened) & physically_open) | |
| counts = self._robot_experience_adapter_import_observation_ledger(sanitized) | |
| counts['stale_opened_storage_handles_rejected'] = len(set(opened) - physically_open) | |
| return counts | |
| def grade(self): | |
| result = self._robot_experience_adapter_grade() | |
| result['public_components'] = {f"{row['work_order']}:{name}": {'correct': int(row[name]), 'total': 1} for row in result['orders'] for name in ('source_verified', 'transfer_authorized', 'custody_obtained', 'physical_delivery', 'workflow_completed')} | |
| return result | |
| def _storage(self, storage_handle): | |
| binding = self._storage_by_handle.get(storage_handle) | |
| if binding is None: | |
| return None | |
| room = self._room(binding[0]) | |
| if not room: | |
| return None | |
| unit = next((row for row in room.get('storage_units', []) if row.get('unit_id') == binding[1]), None) | |
| return (room, unit) if unit else None | |
| def _storage_for_object(self, obj): | |
| unit_id = obj.get('storage_unit_id') | |
| if not unit_id: | |
| return None | |
| for room in self._all('room'): | |
| unit = next((row for row in room.get('storage_units', []) if row.get('unit_id') == unit_id), None) | |
| if unit: | |
| return (room, unit) | |
| return None | |
| def _object_visible_in_room(self, obj, room_id): | |
| if obj.get('held_by_robot_id') or obj.get('current_room_id') != room_id: | |
| return False | |
| storage = self._storage_for_object(obj) | |
| if storage is None: | |
| return True | |
| (storage_room, unit) = storage | |
| return storage_room.get('room_id') != room_id or unit.get('opened') is True | |
| def _source_inspection_valid(order, task, obj): | |
| receipt = task.get('source_inspection_receipt') or {} | |
| return bool(receipt.get('status') == 'verified' and receipt.get('object_id') == order.get('object_id') == obj.get('object_id') and (receipt.get('source_room_id') == task.get('source_room_id')) and (receipt.get('handling_code') == obj.get('handling_code')) and (receipt.get('stock_group') == task.get('stock_group') == obj.get('stock_group'))) | |
| def _source_storage_open(self, task, obj): | |
| unit_id = obj.get('storage_unit_id') | |
| if not unit_id: | |
| return True | |
| room = self._room(task.get('source_room_id')) | |
| unit = next((row for row in (room or {}).get('storage_units', []) if row.get('unit_id') == unit_id), None) | |
| return bool(unit and unit.get('opened') is True) | |
| def assign_work_order(self, work_order): | |
| order = self._order(work_order) | |
| if not order: | |
| return self._finish('assign_work_order', fn__error('WORK_ORDER_NOT_FOUND', 'unknown work order')) | |
| def mutate(): | |
| (task, obj) = self._work_context(order) | |
| actor = self._robot() | |
| if not task or not obj or (not actor): | |
| return fn__error('WORK_ORDER_UNAVAILABLE', 'incomplete work-order records') | |
| if task.get('status') != 'queued' or task.get('assigned_robot_id') or self._active_assignments(task_id=task['task_id']): | |
| return fn__error('WORK_ORDER_NOT_QUEUED', 'work order is not queued') | |
| if actor.get('operational_status') != 'available' or actor.get('active_task_id') or actor.get('payload_object_id') or self._active_assignments(robot_id=self.robot_id): | |
| return fn__error('ROBOT_NOT_AVAILABLE', 'the robot is occupied') | |
| if actor.get('facility_id') != task.get('facility_id'): | |
| return fn__error('FACILITY_MISMATCH', 'robot and work order are in different facilities') | |
| if obj.get('requires_gripper') and 'grasp' not in actor.get('capabilities', []): | |
| return fn__error('CAPABILITY_MISMATCH', 'required actuator is unavailable') | |
| now = fn__timestamp() | |
| task.update(status='assigned', assigned_robot_id=self.robot_id, updated_at=now) | |
| actor.update(operational_status='busy', active_task_id=task['task_id'], updated_at=now) | |
| domain = mod_importlib.import_module('mcp_servers.robot_domain') | |
| domain._make_assignment(self.sm, task, actor, note='Metered delivery assignment.') | |
| self._save('service_task', task) | |
| self._save('robot_unit', actor) | |
| return fn__success({'work_order': work_order, 'status': 'assigned'}) | |
| return self._attempt('assign_work_order', mutate) | |
| def prepare_transfer(self, work_order, profile): | |
| order = self._order(work_order) | |
| if not order: | |
| return self._finish('prepare_transfer', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown')) | |
| if profile not in DATA_TRANSFER_PROFILES: | |
| return self._finish('prepare_transfer', fn__error('INVALID_ARGUMENTS', 'the transfer profile is not declared')) | |
| def mutate(): | |
| (task, obj) = self._work_context(order) | |
| actor = self._robot() | |
| if not task or not obj or (not actor): | |
| return fn__error('WORK_ORDER_UNAVAILABLE', 'the work-order records are incomplete') | |
| if task.get('status') not in {'assigned', 'in_progress'}: | |
| return fn__error('WORK_ORDER_NOT_CONFIGURABLE', 'the work order is not active') | |
| if task.get('assigned_robot_id') != self.robot_id or len(self._active_assignments(task_id=task['task_id'], robot_id=self.robot_id)) != 1 or actor.get('active_task_id') != task['task_id']: | |
| return fn__error('ASSIGNMENT_REQUIRED', 'the work order is not actively assigned') | |
| if not self._source_inspection_valid(order, task, obj): | |
| return fn__error('LOCAL_INSPECTION_REQUIRED', 'inspect the target parcel before configuration') | |
| at_source = actor.get('current_room_id') == task.get('source_room_id') | |
| unheld_local = obj.get('current_room_id') == actor.get('current_room_id') and (not obj.get('held_by_robot_id')) | |
| held_by_actor = actor.get('payload_object_id') == obj['object_id'] and obj.get('held_by_robot_id') == self.robot_id | |
| if not at_source or not (unheld_local or held_by_actor): | |
| return fn__error('SOURCE_CONFIGURATION_REQUIRED', 'configure this parcel at its opened source storage location') | |
| if not self._source_storage_open(task, obj): | |
| return fn__error('SOURCE_STORAGE_CLOSED', "open the parcel's local source storage before configuration") | |
| now = fn__timestamp() | |
| task.update(transfer_profile_submitted=profile, transfer_policy_version=task['policy_version'], transfer_object_id=obj['object_id'], transfer_authorized=False, intake_receipt=None, updated_at=now) | |
| self._save('service_task', task) | |
| return fn__success({'work_order': work_order, 'transfer_state': 'configured_unverified'}) | |
| return self._attempt('prepare_transfer', mutate) | |
| def _configured_profile_valid(self, task, obj): | |
| key = f"{obj.get('handling_code')}:{task.get('intake_code')}" | |
| return task.get('policy_version') == 'PV-18' and task.get('transfer_policy_version') == task.get('policy_version') and (task.get('transfer_object_id') == obj.get('object_id')) and (task.get('transfer_profile_submitted') == self.rule_table.get(key)) | |
| def release(self, work_order): | |
| order = self._order(work_order) | |
| if not order: | |
| return self._finish('release', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown')) | |
| (task, obj) = self._work_context(order) | |
| actor = self._robot() | |
| if not task or not obj or (not actor) or (actor.get('current_room_id') != order['destination_room_id']) or (actor.get('payload_object_id') != obj.get('object_id')) or (obj.get('held_by_robot_id') != self.robot_id): | |
| return self._robot_state_action_adapter_release(work_order) | |
| if task.get('transfer_profile_submitted') not in DATA_TRANSFER_PROFILES or task.get('transfer_policy_version') != task.get('policy_version') or task.get('transfer_object_id') != obj.get('object_id'): | |
| return self._attempt('release', lambda : fn__error('TRANSFER_NOT_CONFIGURED', 'destination intake requires a current parcel-bound configuration')) | |
| if not self._configured_profile_valid(task, obj): | |
| return self._attempt('release', lambda : fn__error('INTAKE_REJECTED', 'destination intake did not accept the configured transfer')) | |
| result = self._robot_state_action_adapter_release(work_order) | |
| if result.get('status') == 'success': | |
| task = self._get('service_task', 'task_id', order['task_id']) | |
| if task: | |
| task.update(transfer_authorized=True, intake_receipt={'status': 'accepted', 'object_id': obj['object_id'], 'policy_version': task['policy_version'], 'profile': task['transfer_profile_submitted'], 'destination_room_id': order['destination_room_id'], 'accepted_at': fn__timestamp()}, updated_at=fn__timestamp()) | |
| self._save('service_task', task) | |
| result.setdefault('data', {})['intake_state'] = 'accepted' | |
| return result | |
| def finalize(self, work_order): | |
| order = self._order(work_order) | |
| if not order: | |
| return self._finish('finalize', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown')) | |
| (task, obj) = self._work_context(order) | |
| actor = self._robot() | |
| receipt = (task or {}).get('intake_receipt') or {} | |
| if not task or not obj or task.get('transfer_authorized') is not True or (receipt.get('status') != 'accepted') or (receipt.get('object_id') != obj.get('object_id')) or (receipt.get('policy_version') != task.get('policy_version')) or (receipt.get('destination_room_id') != order['destination_room_id']): | |
| return self._attempt('finalize', lambda : fn__error('INTAKE_RECEIPT_REQUIRED', "closure requires this parcel's current accepted intake receipt")) | |
| if not actor or actor.get('current_room_id') != self.home_room_id: | |
| return self._attempt('finalize', lambda : fn__error('SERVICE_HUB_REQUIRED', 'return to the service hub before closing the work order')) | |
| return self._robot_state_action_adapter_finalize(work_order) | |
| def export_observation_ledger(self): | |
| ledger = self._robot_state_action_adapter_export_observation_ledger() | |
| ledger['storage_handles'] = sorted(self.issued_storage_handles) | |
| ledger['opened_storage_handles'] = sorted((handle for handle in self._storage_by_handle if (resolved := self._storage(handle)) is not None and resolved[1].get('opened') is True)) | |
| ledger['inspected_target_object_ids'] = sorted(self._inspected_target_ids) | |
| return ledger | |
| def _schema_valid(self, name, arguments): | |
| if name not in DATA__TOOL_BY_NAME or not isinstance(arguments, dict): | |
| return False | |
| schema = DATA__TOOL_BY_NAME[name] | |
| properties = schema.get('properties', {}) | |
| if set(arguments) - set(properties) or any((key not in arguments for key in schema.get('required', []))): | |
| return False | |
| for (key, value) in arguments.items(): | |
| spec = properties[key] | |
| if spec.get('type') == 'string' and (not isinstance(value, str)): | |
| return False | |
| if spec.get('type') == 'array' and (not isinstance(value, list) or not all((isinstance(item, str) for item in value))): | |
| return False | |
| if 'enum' in spec and value not in spec['enum']: | |
| return False | |
| return True | |
| def _handle(self, kind, internal_id): | |
| token = mod_hashlib.sha256(f'{self.handle_seed}:{kind}:{internal_id}'.encode('utf-8')).hexdigest()[:16] | |
| return f'{kind}-{token}' | |
| def _all(self, entity): | |
| return self.sm.list_entities(entity) | |
| def _get(self, entity, id_field, entity_id): | |
| if not entity_id: | |
| return None | |
| return self.sm.get_entity(entity, entity_id, id_field=id_field) | |
| def _save(self, entity, row): | |
| return self.sm.replace_entity(entity, row) | |
| def _refresh_plan_handles(self): | |
| self._plan_by_handle = {self._handle('plan', row['plan_id']): row['plan_id'] for row in self._all('navigation_plan')} | |
| def _finish(self, tool, result, battery_cost=0): | |
| self._actions.append({'index': self._next_action_index, 'tool': tool, 'status': result.get('status'), 'battery_cost': battery_cost, 'reason': fn__code(result)}) | |
| self._next_action_index += 1 | |
| if len(self._actions) > 256: | |
| self._actions = self._actions[-256:] | |
| return result | |
| def _robot(self): | |
| return self._get('robot_unit', 'robot_id', self.robot_id) | |
| def _room(self, room_id): | |
| return self._get('room', 'room_id', room_id) | |
| def _room_name(self, room_id): | |
| room = self._room(room_id) | |
| return room.get('name') if room else None | |
| def _robot_name(self, robot_id): | |
| robot = self._get('robot_unit', 'robot_id', robot_id) | |
| return robot.get('display_name') if robot else None | |
| def _order(self, work_order): | |
| return self._orders.get(work_order) if isinstance(work_order, str) else None | |
| def _task_steps(self, task_id): | |
| return sorted((row for row in self._all('task_step') if row.get('task_id') == task_id), key=lambda row: (row.get('step_order', 0), row.get('step_id', ''))) | |
| def _active_assignments(self, task_id=None, robot_id=None): | |
| rows = [] | |
| for row in self._all('task_assignment'): | |
| if row.get('status') != 'active': | |
| continue | |
| if task_id is not None and row.get('task_id') != task_id: | |
| continue | |
| if robot_id is not None and row.get('robot_id') != robot_id: | |
| continue | |
| rows.append(row) | |
| return rows | |
| def _condition(self, room_id): | |
| return next((row for row in self._all('room_condition') if row.get('room_id') == room_id), None) | |
| def _room_open(self, room_id): | |
| room = self._room(room_id) | |
| condition = self._condition(room_id) if room_id else None | |
| return bool(room and room.get('is_robot_accessible') and (not condition or condition.get('access_state') != 'closed')) | |
| def _edge_destination(self, edge, room_id): | |
| if edge.get('from_room_id') == room_id: | |
| return edge.get('to_room_id') | |
| if edge.get('is_bidirectional') and edge.get('to_room_id') == room_id: | |
| return edge.get('from_room_id') | |
| return None | |
| def _active_edge_blockers(self, edge_id): | |
| return [row for row in self._all('obstacle') if row.get('status') == 'active' and edge_id in (row.get('affects_edge_ids') or [])] | |
| def _edge_usable(self, edge, destination_id): | |
| return bool(edge.get('status') == 'open' and (not self._active_edge_blockers(edge['edge_id'])) and self._room_open(destination_id)) | |
| def _capture_state(self): | |
| if hasattr(self.sm, 'get_full_state'): | |
| return ext_deepcopy(self.sm.get_full_state()) | |
| return {entity: ext_deepcopy(self._all(entity)) for entity in DATA__ID_FIELDS} | |
| def _restore_state(self, state): | |
| if hasattr(self.sm, 'database') and isinstance(self.sm.database, dict): | |
| self.sm.database = ext_deepcopy(state) | |
| return | |
| for (entity, rows) in state.items(): | |
| id_field = DATA__ID_FIELDS.get(entity) | |
| if not id_field: | |
| continue | |
| if hasattr(self.sm, 'delete_entity'): | |
| desired = {row.get(id_field) for row in rows} | |
| for current in self._all(entity): | |
| entity_id = current.get(id_field) | |
| if entity_id not in desired: | |
| self.sm.delete_entity(entity, entity_id, id_field=id_field) | |
| for row in rows: | |
| self._save(entity, ext_deepcopy(row)) | |
| def _battery(self): | |
| robot = self._robot() | |
| return int((robot or {}).get('battery_percent') or 0) | |
| def _set_battery(self, value): | |
| self.sm.update_entity('robot_unit', self.robot_id, {'battery_percent': value}, id_field='robot_id') | |
| def _attempt(self, tool, mutation): | |
| starting_battery = self._battery() | |
| if starting_battery < 1: | |
| return self._finish(tool, fn__error('INSUFFICIENT_BATTERY', 'the controlled robot cannot pay the one-unit attempt cost', {'battery_percent': starting_battery, 'battery_cost': 0}), 0) | |
| before = self._capture_state() | |
| try: | |
| result = mutation() | |
| except Exception: | |
| self._restore_state(before) | |
| raise | |
| if result.get('status') != 'success': | |
| self._restore_state(before) | |
| self._set_battery(starting_battery - 1) | |
| result.setdefault('data', {}) | |
| result['data'].update({'battery_percent': starting_battery - 1, 'battery_cost': 1}) | |
| self._refresh_plan_handles() | |
| return self._finish(tool, result, 1) | |
| def _work_context(self, order): | |
| task = self._get('service_task', 'task_id', order['task_id']) | |
| obj = self._get('object_item', 'object_id', order['object_id']) | |
| return (task, obj) | |
| def _required_destination(self, task, obj): | |
| pick_done = any((row.get('step_type') == 'pick' and row.get('status') == 'completed' for row in self._task_steps(task['task_id']))) | |
| if obj and (obj.get('held_by_robot_id') or pick_done or obj.get('handling_state') in {'in_transit', 'delivered'}): | |
| return task.get('target_room_id') | |
| return task.get('source_room_id') | |
| def observe_self(self): | |
| robot = self._robot() | |
| if not robot: | |
| return self._finish('observe_self', fn__error('ROBOT_NOT_FOUND', 'the controlled robot is missing')) | |
| payload = self._get('object_item', 'object_id', robot.get('payload_object_id')) | |
| payload_view = None | |
| if payload: | |
| handle = self._handle('object', payload['object_id']) | |
| self.issued_object_handles.add(handle) | |
| payload_view = {'object_handle': handle, 'display_name': payload.get('display_name'), 'handling_state': payload.get('handling_state')} | |
| active_order = next((ref for (ref, row) in self._orders.items() if row['task_id'] == robot.get('active_task_id')), None) | |
| return self._finish('observe_self', fn__success({'robot': {'display_name': robot.get('display_name'), 'operational_status': robot.get('operational_status'), 'capabilities': ext_deepcopy(robot.get('capabilities') or []), 'battery_percent': int(robot.get('battery_percent') or 0)}, 'current_room': {'name': self._room_name(robot.get('current_room_id'))}, 'payload': payload_view, 'active_work_order': active_order})) | |
| def _route_consistent(self, plan): | |
| route = plan.get('route_room_ids') or [] | |
| if not route or route[0] != plan.get('origin_room_id') or route[-1] != plan.get('destination_room_id'): | |
| return False | |
| edges = self._all('map_edge') | |
| for (left, right) in zip(route, route[1:]): | |
| if not any((edge.get('from_room_id') == left and edge.get('to_room_id') == right or (edge.get('is_bidirectional') and edge.get('from_room_id') == right and (edge.get('to_room_id') == left)) for edge in edges)): | |
| return False | |
| return True | |
| def _route_currently_usable(self, plan): | |
| route = plan.get('route_room_ids') or [] | |
| if not self._route_consistent(plan) or not self._room_open(route[0]): | |
| return False | |
| edges = self._all('map_edge') | |
| for (left, right) in zip(route, route[1:]): | |
| edge = next((row for row in edges if row.get('from_room_id') == left and row.get('to_room_id') == right or (row.get('is_bidirectional') and row.get('from_room_id') == right and (row.get('to_room_id') == left))), None) | |
| if edge is None or not self._edge_usable(edge, right): | |
| return False | |
| return True | |
| def inspect_plan(self, plan_handle): | |
| self._refresh_plan_handles() | |
| if not isinstance(plan_handle, str) or plan_handle not in self.issued_plan_handles or plan_handle not in self._plan_by_handle: | |
| return self._finish('inspect_plan', fn__error('PLAN_NOT_OBSERVED', 'read the work order before inspecting its plan')) | |
| plan = self._get('navigation_plan', 'plan_id', self._plan_by_handle[plan_handle]) | |
| if not plan: | |
| return self._finish('inspect_plan', fn__error('PLAN_UNAVAILABLE', 'the observed plan no longer exists')) | |
| owner = self._get('robot_unit', 'robot_id', plan.get('robot_id')) | |
| active_obstacles = {row.get('obstacle_id') for row in self._all('obstacle') if row.get('status') == 'active'} | |
| blockers = set(plan.get('blocked_by_obstacle_ids') or []) & active_obstacles | |
| order = next((row for row in self._orders.values() if row['task_id'] == plan.get('task_id')), None) | |
| task = self._get('service_task', 'task_id', plan.get('task_id')) | |
| obj = self._get('object_item', 'object_id', (order or {}).get('object_id')) | |
| required = self._required_destination(task, obj) if task else None | |
| return self._finish('inspect_plan', fn__success({'plan_handle': plan_handle, 'status': plan.get('status'), 'owner': {'display_name': (owner or {}).get('display_name'), 'operational_status': (owner or {}).get('operational_status')}, 'blocker_count': len(blockers), 'owned_by_controlled_robot': plan.get('robot_id') == self.robot_id, 'origin_is_owner_current_room': bool(owner and plan.get('origin_room_id') == owner.get('current_room_id')), 'destination_matches_unfinished_work': plan.get('destination_room_id') == required, 'route_is_contiguous': self._route_consistent(plan)})) | |
| def handoff_work_order(self, work_order): | |
| order = self._order(work_order) | |
| if not order: | |
| return self._finish('handoff_work_order', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown')) | |
| def mutate(): | |
| (task, obj) = self._work_context(order) | |
| actor = self._robot() | |
| if not task or not obj or (not actor): | |
| return fn__error('WORK_ORDER_UNAVAILABLE', 'the work-order records are incomplete') | |
| source_id = task.get('assigned_robot_id') | |
| source = self._get('robot_unit', 'robot_id', source_id) | |
| active = self._active_assignments(task_id=task['task_id'], robot_id=source_id) | |
| if not source or source_id == self.robot_id or len(active) != 1: | |
| return fn__error('HANDOFF_SOURCE_INVALID', 'the work order has no coherent peer assignment') | |
| if actor.get('operational_status') != 'available' or actor.get('active_task_id') or actor.get('payload_object_id'): | |
| return fn__error('CONTROLLED_ROBOT_NOT_AVAILABLE', "finish the controlled robot's current work before handoff") | |
| held = obj.get('held_by_robot_id') is not None or source.get('payload_object_id') is not None | |
| if held and (not (obj.get('held_by_robot_id') == source_id and source.get('payload_object_id') == obj.get('object_id'))): | |
| return fn__error('CUSTODY_INCOHERENT', 'peer and parcel custody records disagree') | |
| if held and actor.get('current_room_id') != source.get('current_room_id'): | |
| return fn__error('HANDOFF_ROOM_MISMATCH', 'held cargo requires both robots in the same room') | |
| source_status = source.get('operational_status') | |
| old_steps = self._task_steps(task['task_id']) | |
| old_plans = [row for row in self._all('navigation_plan') if row.get('task_id') == task['task_id']] | |
| domain = mod_importlib.import_module('mcp_servers.robot_domain') | |
| native = domain.execute_task_handoff(self.sm, task_id=task['task_id'], from_robot_id=source_id, to_robot_id=self.robot_id, handoff_room_id=source.get('current_room_id'), handoff_reason='Interrupted work-order recovery.') | |
| if native.get('status') != 'success': | |
| return fn__error(fn__code(native), 'handoff was rejected') | |
| self.sm.update_entity('robot_unit', source_id, {'operational_status': source_status}, id_field='robot_id') | |
| for row in old_steps: | |
| self._save('task_step', row) | |
| for row in old_plans: | |
| self._save('navigation_plan', row) | |
| current = self._get('service_task', 'task_id', task['task_id']) | |
| return fn__success({'work_order': work_order, 'status': (current or {}).get('status'), 'physical_custody_transferred': held, 'former_robot_status': source_status}) | |
| return self._attempt('handoff_work_order', mutate) | |
| def _validate_supplied_route(self, handles, start, destination): | |
| rooms = [start] | |
| distance = 0.0 | |
| current = start | |
| for handle in handles: | |
| edge = self._get('map_edge', 'edge_id', self._edge_by_handle[handle]) | |
| nxt = self._edge_destination(edge or {}, current) | |
| if not edge or not nxt: | |
| return (None, 0.0, 'ROUTE_NOT_CONTIGUOUS') | |
| if not self._edge_usable(edge, nxt): | |
| return (None, 0.0, 'ROUTE_NOT_TRAVERSABLE') | |
| rooms.append(nxt) | |
| current = nxt | |
| distance += float(edge.get('distance_m') or 1) | |
| if current != destination: | |
| return (None, 0.0, 'ROUTE_WRONG_DESTINATION') | |
| return (rooms, distance, None) | |
| def _new_plan_id(self, task_id): | |
| existing = {row.get('plan_id') for row in self._all('navigation_plan')} | |
| ordinal = 1 | |
| while True: | |
| token = mod_hashlib.sha256(f'{self.handle_seed}:recovery-plan:{task_id}:{ordinal}'.encode('utf-8')).hexdigest()[:16] | |
| candidate = f'plan-recovery-{token}' | |
| if candidate not in existing: | |
| return candidate | |
| ordinal += 1 | |
| def resolve_work_order(self, work_order, action, route_exit_handles=None): | |
| order = self._order(work_order) | |
| if not order: | |
| return self._finish('resolve_work_order', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown')) | |
| if action not in {'retry', 'reroute'} or (route_exit_handles is not None and (not isinstance(route_exit_handles, list) or not all((isinstance(value, str) for value in route_exit_handles)))): | |
| return self._finish('resolve_work_order', fn__error('INVALID_ARGUMENTS', 'action or route handles do not match the tool schema')) | |
| handles = list(route_exit_handles or []) | |
| if any((handle not in self.issued_exit_handles or handle not in self._edge_by_handle for handle in handles)): | |
| return self._finish('resolve_work_order', fn__error('EXIT_NOT_KNOWN', 'every route exit must have been observed locally')) | |
| def mutate(): | |
| (task, obj) = self._work_context(order) | |
| actor = self._robot() | |
| if not task or not actor or task.get('status') != 'blocked': | |
| return fn__error('WORK_ORDER_NOT_BLOCKED', 'only a blocked work order can be resolved') | |
| if task.get('assigned_robot_id') != self.robot_id or len(self._active_assignments(task_id=task['task_id'], robot_id=self.robot_id)) != 1: | |
| return fn__error('ASSIGNMENT_REQUIRED', 'the blocked work order is not coherently assigned to the controlled robot') | |
| if int(actor.get('battery_percent') or 0) < 10: | |
| return fn__error('LOW_BATTERY_PRECONDITION_FAILED', 'robot battery is below the recovery threshold') | |
| destination = self._required_destination(task, obj) | |
| now = fn__timestamp() | |
| plan = None | |
| if action == 'retry': | |
| if handles: | |
| return fn__error('ROUTE_NOT_ALLOWED_FOR_RETRY', 'retry reuses an existing plan') | |
| active_obstacles = {row.get('obstacle_id') for row in self._all('obstacle') if row.get('status') == 'active'} | |
| candidates = [row for row in self._all('navigation_plan') if row.get('task_id') == task['task_id'] and row.get('robot_id') == self.robot_id and (row.get('status') == 'draft') and (row.get('origin_room_id') == actor.get('current_room_id')) and (row.get('destination_room_id') == destination) and (not set(row.get('blocked_by_obstacle_ids') or []) & active_obstacles) and self._route_currently_usable(row)] | |
| if len(candidates) != 1: | |
| return fn__error('REUSABLE_PLAN_NOT_FOUND', 'retry requires one current, unblocked, controlled draft plan') | |
| plan = candidates[0] | |
| plan.update(status='active', updated_at=now) | |
| self._save('navigation_plan', plan) | |
| else: | |
| (route, distance, failure) = self._validate_supplied_route(handles, actor.get('current_room_id'), destination) | |
| if failure: | |
| return fn__error(failure, 'the supplied observed route cannot resume this work order') | |
| plan = {'plan_id': self._new_plan_id(task['task_id']), 'facility_id': task.get('facility_id'), 'robot_id': self.robot_id, 'task_id': task['task_id'], 'origin_room_id': actor.get('current_room_id'), 'destination_room_id': destination, 'route_room_ids': route, 'route_edge_ids': [self._edge_by_handle[value] for value in handles], 'status': 'active', 'blocked_by_obstacle_ids': [], 'estimated_distance_m': round(distance, 2), 'estimated_duration_seconds': max(30, len(handles) * 30), 'created_at': now, 'updated_at': now} | |
| self._save('navigation_plan', plan) | |
| for step in self._task_steps(task['task_id']): | |
| if step.get('status') == 'blocked': | |
| step.update(status='in_progress', blocked_reason=None, updated_at=now) | |
| self._save('task_step', step) | |
| task.update(status='in_progress', failure_reason=None, updated_at=now) | |
| actor.update(operational_status='busy', active_task_id=task['task_id'], updated_at=now) | |
| self._save('service_task', task) | |
| self._save('robot_unit', actor) | |
| handle = self._handle('plan', plan['plan_id']) | |
| self.issued_plan_handles.add(handle) | |
| return fn__success({'work_order': work_order, 'status': 'in_progress', 'action': action, 'plan_handle': handle}) | |
| return self._attempt('resolve_work_order', mutate) | |
| def _robot_experience_stream_adapter_init(self, *args, **kwargs): | |
| self._scanned_rooms_this_episode: set[str] = set() | |
| self._accessed_storage_this_episode: set[str] = set() | |
| self._robot_experience_stream_adapter_init_2(*args, **kwargs) | |
| self.tools = ext_deepcopy(DATA_TOOLS_5) | |
| def _robot_state_action_adapter_traverse_known_exit(self, exit_handle): | |
| if not isinstance(exit_handle, str) or exit_handle not in self.issued_exit_handles or exit_handle not in self._edge_by_handle: | |
| return self._finish('traverse_known_exit', fn__error('EXIT_NOT_KNOWN', 'scan the current room before using an exit')) | |
| robot = self._robot() | |
| edge = self._get('map_edge', 'edge_id', self._edge_by_handle[exit_handle]) | |
| destination = self._edge_destination(edge or {}, (robot or {}).get('current_room_id')) | |
| if not robot or not edge or (not destination): | |
| return self._finish('traverse_known_exit', fn__error('EXIT_CHANGED', 'the observed exit is not adjacent now')) | |
| if not self._edge_usable(edge, destination): | |
| return self._finish('traverse_known_exit', fn__error('EXIT_BLOCKED', 'the observed exit is not traversable now')) | |
| cost = max(1, mod_math.ceil(float(edge.get('distance_m') or 1) / 10)) | |
| if int(robot.get('battery_percent') or 0) < cost: | |
| return self._finish('traverse_known_exit', fn__error('INSUFFICIENT_BATTERY', 'movement cannot be paid', {'battery_percent': int(robot.get('battery_percent') or 0), 'battery_cost': 0})) | |
| previous_name = self._room_name(robot.get('current_room_id')) | |
| domain = mod_importlib.import_module('mcp_servers.robot_domain') | |
| result = domain.move_robot_to_room(self.sm, robot_id=self.robot_id, destination_room_id=destination, battery_cost_percent=cost) | |
| if result.get('status') != 'success': | |
| return self._finish('traverse_known_exit', fn__error(fn__code(result), 'movement was rejected', {'battery_percent': self._battery(), 'battery_cost': 0})) | |
| now = fn__timestamp() | |
| actor = self._robot() | |
| active_task_id = (actor or {}).get('active_task_id') | |
| task = self._get('service_task', 'task_id', active_task_id) | |
| if task: | |
| for step in self._task_steps(active_task_id): | |
| if step.get('step_type') == 'navigate' and step.get('room_id') == destination and (step.get('status') in {'pending', 'in_progress'}): | |
| step.update(status='completed', completed_at=now, blocked_reason=None, updated_at=now) | |
| self._save('task_step', step) | |
| if task.get('status') == 'assigned': | |
| task.update(status='in_progress', updated_at=now) | |
| self._save('service_task', task) | |
| break | |
| for plan in self._all('navigation_plan'): | |
| if plan.get('robot_id') == self.robot_id and plan.get('status') == 'active' and (plan.get('destination_room_id') == destination): | |
| plan.update(status='completed', updated_at=now) | |
| self._save('navigation_plan', plan) | |
| return self._finish('traverse_known_exit', fn__success({'previous_room': {'name': previous_name}, 'current_room': {'name': self._room_name(destination)}, 'battery_percent': self._battery(), 'battery_cost': cost}), cost) | |
| def _robot_experience_adapter_call(self, name, arguments): | |
| if name not in DATA__TOOL_BY_NAME: | |
| return self._finish(str(name), fn__error('UNKNOWN_TOOL', 'tool is not in the public experience profile')) | |
| if not self._schema_valid(name, arguments): | |
| return self._finish(name, fn__error('INVALID_ARGUMENTS', 'arguments do not match the tool schema')) | |
| return getattr(self, name)(**ext_deepcopy(arguments)) | |
| def _robot_experience_stream_adapter_snapshot(self): | |
| """Return the complete private checkpoint used for replay and grading.""" | |
| state = self._robot_experience_stream_adapter_snapshot_2() | |
| state['schema'] = 'robot-experience-stream-snapshot/v3' | |
| state['episode_metering'] = {'scanned_room_ids': sorted(self._scanned_rooms_this_episode), 'accessed_storage_handles': sorted(self._accessed_storage_this_episode)} | |
| return state | |
| def _robot_experience_stream_adapter_read_work_order(self, work_order): | |
| result = self._robot_experience_adapter_read_work_order(work_order) | |
| if result.get('status') == 'success': | |
| result['data']['policy_version'] = self.public_policy_version | |
| return result | |
| def _robot_experience_adapter_storage_view(self, room, unit): | |
| objects = [] | |
| for obj in sorted(self._all('object_item'), key=lambda row: row.get('object_id', '')): | |
| if obj.get('current_room_id') == room['room_id'] and (not obj.get('held_by_robot_id')) and (obj.get('storage_unit_id') == unit['unit_id']): | |
| handle = self._handle('object', obj['object_id']) | |
| self.issued_object_handles.add(handle) | |
| objects.append({'object_handle': handle, 'display_name': obj.get('display_name'), 'handling_state': obj.get('handling_state')}) | |
| return {'storage_handle': self._handle('storage', unit['unit_id']), 'display_name': unit.get('display_name') or f"Storage-{self._handle('storage', unit['unit_id'])[-8:].upper()}", 'access_state': 'open', 'stock_group': unit.get('stock_group'), 'objects': objects, 'calibration_records': ext_deepcopy(unit.get('calibration_records', []))} | |
| def _robot_experience_adapter_inspect_local_object(self, object_handle): | |
| if not isinstance(object_handle, str) or object_handle not in self.issued_object_handles or object_handle not in self._object_by_handle: | |
| return self._finish('inspect_local_object', fn__error('OBJECT_NOT_OBSERVED', 'observe the parcel locally before inspecting it')) | |
| robot = self._robot() | |
| obj = self._get('object_item', 'object_id', self._object_by_handle[object_handle]) | |
| if not robot or not obj or (not self._object_visible_in_room(obj, robot.get('current_room_id'))): | |
| return self._finish('inspect_local_object', fn__error('OBJECT_NOT_LOCAL', 'the observed parcel is no longer visible here')) | |
| matching_order = next((order for order in self._orders.values() if order['object_id'] == obj['object_id']), None) | |
| if matching_order is not None: | |
| (task, _) = self._work_context(matching_order) | |
| if task and robot.get('current_room_id') == task.get('source_room_id') and (obj.get('current_room_id') == task.get('source_room_id')) and (not obj.get('held_by_robot_id')): | |
| task.update(source_inspection_receipt={'status': 'verified', 'object_id': obj['object_id'], 'source_room_id': task.get('source_room_id'), 'handling_code': obj.get('handling_code'), 'stock_group': task.get('stock_group')}, updated_at=fn__timestamp()) | |
| self._save('service_task', task) | |
| self._inspected_target_ids.add(obj['object_id']) | |
| return self._finish('inspect_local_object', fn__success({'object': {'object_handle': object_handle, 'display_name': obj.get('display_name'), 'handling_state': obj.get('handling_state'), 'handling_code': obj.get('handling_code')}})) | |
| def _robot_experience_adapter_pickup(self, work_order, object_handle): | |
| order = self._order(work_order) | |
| if not order: | |
| return self._finish('pickup', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown')) | |
| (task, obj) = self._work_context(order) | |
| if not task or not obj or (not self._source_inspection_valid(order, task, obj)) or (task.get('transfer_profile_submitted') not in DATA_TRANSFER_PROFILES) or (task.get('transfer_policy_version') != task.get('policy_version')) or (task.get('transfer_object_id') != obj['object_id']): | |
| return self._attempt('pickup', lambda : fn__error('TRANSFER_NOT_CONFIGURED', 'pickup requires a current parcel-bound transfer configuration')) | |
| return self._robot_state_action_adapter_pickup(work_order, object_handle) | |
| def _robot_experience_adapter_import_observation_ledger(self, ledger): | |
| if not isinstance(ledger, dict): | |
| raise ValueError('observation ledger must be an object') | |
| storage_handles = ledger.get('storage_handles', []) | |
| opened_handles = ledger.get('opened_storage_handles', []) | |
| if not isinstance(storage_handles, list) or not all((isinstance(value, str) for value in storage_handles)): | |
| raise ValueError('storage_handles must be a list of strings') | |
| if not isinstance(opened_handles, list) or not all((isinstance(value, str) for value in opened_handles)): | |
| raise ValueError('opened_storage_handles must be a list of strings') | |
| accepted_storage = set(storage_handles) & set(self._storage_by_handle) | |
| accepted_opened = set(opened_handles) & accepted_storage | |
| before_storage = len(self.issued_storage_handles) | |
| self.issued_storage_handles.update(accepted_storage) | |
| for handle in accepted_opened: | |
| resolved = self._storage(handle) | |
| if resolved and resolved[1].get('opened') is not True: | |
| (room, unit) = resolved | |
| unit['opened'] = True | |
| room['storage_units'] = [unit if row.get('unit_id') == unit['unit_id'] else row for row in room.get('storage_units', [])] | |
| self._save('room', room) | |
| allowed_object_handles = set() | |
| for (handle, object_id) in self._object_by_handle.items(): | |
| obj = self._get('object_item', 'object_id', object_id) | |
| storage = self._storage_for_object(obj or {}) if obj else None | |
| if not storage or storage[1].get('opened') is True or obj.get('held_by_robot_id'): | |
| allowed_object_handles.add(handle) | |
| sanitized = ext_deepcopy(ledger) | |
| sanitized['object_handles'] = [handle for handle in ledger.get('object_handles', []) if handle in allowed_object_handles] | |
| counts = self._robot_state_action_adapter_import_observation_ledger(sanitized) | |
| inspected = ledger.get('inspected_target_object_ids', []) | |
| if not isinstance(inspected, list) or not all((isinstance(value, str) for value in inspected)): | |
| raise ValueError('inspected_target_object_ids must be a list of strings') | |
| durable_targets = set() | |
| for order in self._orders.values(): | |
| (task, obj) = self._work_context(order) | |
| if task and obj and self._source_inspection_valid(order, task, obj): | |
| durable_targets.add(order['object_id']) | |
| before_inspected = len(self._inspected_target_ids) | |
| self._inspected_target_ids.update(set(inspected) & durable_targets) | |
| counts['storage_handles_imported'] = len(self.issued_storage_handles) - before_storage | |
| counts['opened_storage_handles_imported'] = len(accepted_opened) | |
| counts['inspected_target_object_ids_imported'] = len(self._inspected_target_ids) - before_inspected | |
| return counts | |
| def _robot_experience_adapter_grade(self): | |
| rows = [] | |
| total = 0.0 | |
| for (work_order, order) in self._orders.items(): | |
| (task, obj) = self._work_context(order) | |
| steps = self._task_steps(order['task_id']) | |
| assignments = [row for row in self._all('task_assignment') if row.get('task_id') == order['task_id']] | |
| plans = [row for row in self._all('navigation_plan') if row.get('task_id') == order['task_id']] | |
| source_verified = bool(task and obj and self._source_inspection_valid(order, task, obj)) | |
| receipt = (task or {}).get('intake_receipt') or {} | |
| authorized = bool(task and obj and (task.get('transfer_authorized') is True) and (receipt.get('status') == 'accepted') and (receipt.get('object_id') == obj.get('object_id')) and (receipt.get('policy_version') == task.get('policy_version')) and (receipt.get('destination_room_id') == order['destination_room_id'])) | |
| custody_obtained = any((row.get('step_type') == 'pick' and row.get('status') == 'completed' for row in steps)) | |
| physical = bool(authorized and obj and (obj.get('current_room_id') == order['destination_room_id']) and (not obj.get('held_by_robot_id')) and (obj.get('handling_state') in {'stored', 'delivered'})) | |
| workflow = bool(physical and task and (task.get('status') == 'completed') and (obj.get('handling_state') == 'delivered') and steps and all((row.get('status') == 'completed' for row in steps)) and (not any((row.get('status') == 'active' for row in assignments))) and any((row.get('status') == 'completed' for row in assignments)) and (not any((row.get('status') == 'active' for row in plans))) and (not any((row.get('payload_object_id') == order['object_id'] for row in self._all('robot_unit')))) and (not any((row.get('active_task_id') == order['task_id'] for row in self._all('robot_unit'))))) | |
| anchors = {'source_verified': 2.5 if source_verified else 0.0, 'transfer_authorized': 5.0 if authorized else 0.0, 'custody_obtained': 5.0 if custody_obtained else 0.0, 'physical_delivery': 5.0 if physical else 0.0, 'workflow_completed': 7.5 if workflow else 0.0} | |
| score = sum(anchors.values()) | |
| total += score | |
| rows.append({'work_order': work_order, **{key: value > 0 for (key, value) in anchors.items()}, 'score': score, 'max_score': 25.0}) | |
| components = {f'item_{index}_{name}': {'correct': int(row[name]), 'total': 1} for (index, row) in enumerate(rows, 1) for name in ('source_verified', 'transfer_authorized', 'custody_obtained', 'physical_delivery', 'workflow_completed')} | |
| return {'score': total, 'max_score': 100.0, 'orders': rows, 'public_components': components} | |
| def _robot_state_action_adapter_release(self, work_order): | |
| order = self._order(work_order) | |
| if not order: | |
| return self._finish('release', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown')) | |
| def mutate(): | |
| (task, obj) = self._work_context(order) | |
| actor = self._robot() | |
| if not task or not obj or (not actor): | |
| return fn__error('WORK_ORDER_UNAVAILABLE', 'the work-order records are incomplete') | |
| if task.get('status') not in {'assigned', 'in_progress'}: | |
| return fn__error('WORK_ORDER_NOT_RELEASABLE', 'blocked or terminal work cannot record release') | |
| if task.get('assigned_robot_id') != self.robot_id or len(self._active_assignments(task_id=task['task_id'], robot_id=self.robot_id)) != 1: | |
| return fn__error('ASSIGNMENT_REQUIRED', "release requires the controlled robot's active assignment") | |
| if actor.get('payload_object_id') != obj.get('object_id') or obj.get('held_by_robot_id') != self.robot_id: | |
| return fn__error('CUSTODY_MISMATCH', 'the controlled robot does not hold this work-order parcel') | |
| if actor.get('current_room_id') != order['destination_room_id']: | |
| return fn__error('WRONG_DESTINATION', 'the parcel can only be released at the work-order destination') | |
| steps = self._task_steps(task['task_id']) | |
| place_index = next((index for (index, row) in enumerate(steps) if row.get('step_type') == 'place'), None) | |
| if place_index is None or steps[place_index].get('status') not in {'pending', 'in_progress'} or any((row.get('status') != 'completed' for row in steps[:place_index])): | |
| return fn__error('WORKFLOW_NOT_READY_FOR_RELEASE', 'earlier work-order obligations are not complete') | |
| domain = mod_importlib.import_module('mcp_servers.robot_domain') | |
| native = domain.release_object_at_room(self.sm, object_id=obj['object_id'], robot_id=self.robot_id, room_id=order['destination_room_id'], delivery_state='stored', task_id=task['task_id']) | |
| if native.get('status') != 'success': | |
| return fn__error(fn__code(native), 'release was rejected') | |
| return fn__success({'work_order': work_order, 'destination': {'name': self._room_name(order['destination_room_id'])}, 'physical_state': 'stored'}) | |
| return self._attempt('release', mutate) | |
| def _robot_state_action_adapter_finalize(self, work_order): | |
| order = self._order(work_order) | |
| if not order: | |
| return self._finish('finalize', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown')) | |
| def mutate(): | |
| (task, obj) = self._work_context(order) | |
| actor = self._robot() | |
| if not task or not obj or (not actor): | |
| return fn__error('WORK_ORDER_UNAVAILABLE', 'the work-order records are incomplete') | |
| if task.get('status') not in {'assigned', 'in_progress'}: | |
| return fn__error('WORK_ORDER_NOT_COMPLETABLE', 'the work order is blocked or terminal') | |
| steps = self._task_steps(task['task_id']) | |
| if not steps or any((row.get('status') != 'completed' for row in steps)): | |
| return fn__error('REQUIRED_STEPS_OPEN', 'finalize cannot create or skip execution evidence') | |
| if obj.get('current_room_id') != order['destination_room_id'] or obj.get('held_by_robot_id') or obj.get('handling_state') != 'stored': | |
| return fn__error('PHYSICAL_DELIVERY_INCOMPLETE', 'the parcel must already be stored unheld at the destination') | |
| if any((row.get('payload_object_id') == obj.get('object_id') for row in self._all('robot_unit'))): | |
| return fn__error('PAYLOAD_REFERENCE_CONFLICT', 'a robot still references the delivered parcel') | |
| active = self._active_assignments(task_id=task['task_id']) | |
| if task.get('assigned_robot_id') != self.robot_id or len(active) != 1 or active[0].get('robot_id') != self.robot_id or (actor.get('active_task_id') != task['task_id']) or (actor.get('operational_status') != 'busy'): | |
| return fn__error('ASSIGNMENT_INCOHERENT', 'strict completion requires one coherent controlled assignment') | |
| now = fn__timestamp() | |
| assignment = active[0] | |
| assignment.update(status='completed', released_at=now, updated_at=now) | |
| self._save('task_assignment', assignment) | |
| for plan in self._all('navigation_plan'): | |
| if plan.get('task_id') == task['task_id'] and plan.get('robot_id') == self.robot_id and (plan.get('status') in {'active', 'draft'}): | |
| plan.update(status='completed', updated_at=now) | |
| self._save('navigation_plan', plan) | |
| actor.update(operational_status='available', active_task_id=None, payload_object_id=None, updated_at=now) | |
| obj.update(handling_state='delivered', held_by_robot_id=None, current_room_id=order['destination_room_id'], updated_at=now) | |
| task.update(status='completed', completed_at=now, failure_reason=None, updated_at=now) | |
| self._save('robot_unit', actor) | |
| self._save('object_item', obj) | |
| self._save('service_task', task) | |
| return fn__success({'work_order': work_order, 'status': 'completed', 'object_state': 'delivered', 'controlled_robot_status': 'available'}) | |
| return self._attempt('finalize', mutate) | |
| def _robot_state_action_adapter_export_observation_ledger(self): | |
| return {'exit_handles': sorted(self.issued_exit_handles), 'object_handles': sorted(self.issued_object_handles), 'plan_handles': sorted(self.issued_plan_handles), 'robot_handles': sorted(self.issued_robot_handles), 'work_orders': sorted(self.issued_work_orders)} | |
| def _robot_experience_stream_adapter_init_2(self, sm, *, active_object_ids, public_policy_version, expected_rule_epoch, facility_id, **kwargs): | |
| if not isinstance(active_object_ids, set) or len(active_object_ids) != 4: | |
| raise ValueError('active_object_ids must contain exactly four objects') | |
| if public_policy_version not in {'PV-18', 'PV-19'}: | |
| raise ValueError('unknown public policy version') | |
| if expected_rule_epoch not in {'pre', 'post'}: | |
| raise ValueError('unknown rule epoch') | |
| self.active_object_ids = frozenset(active_object_ids) | |
| self.public_policy_version = public_policy_version | |
| self.expected_rule_epoch = expected_rule_epoch | |
| self.facility_id = facility_id | |
| self._robot_experience_adapter_init(sm, **kwargs) | |
| self.tools = ext_deepcopy(DATA_TOOLS_4) | |
| inventory = {row['object_id'] for row in self._all('object_item')} | |
| if (missing := (self.active_object_ids - inventory)): | |
| raise ValueError(f'active episode references missing objects: {sorted(missing)}') | |
| facility = self._get('facility', 'facility_id', facility_id) | |
| if facility is None: | |
| raise ValueError('stream facility is missing') | |
| if facility.get('experience_rule_epoch') != expected_rule_epoch: | |
| raise ValueError('physical state rule epoch does not match the requested episode') | |
| if facility.get('experience_policy_version') != public_policy_version: | |
| raise ValueError('physical state policy version does not match the requested episode') | |
| for order in self._orders.values(): | |
| (task, obj) = self._work_context(order) | |
| if task is None or obj is None: | |
| raise ValueError('active episode has an incomplete order') | |
| if obj['object_id'] not in self.active_object_ids: | |
| raise ValueError('rubric contains a non-active object') | |
| if task.get('experience_activation_state') != 'active': | |
| raise ValueError('active service task is not activated') | |
| if obj.get('experience_activation_state') != 'active': | |
| raise ValueError('active parcel is not activated') | |
| if task.get('experience_policy_version') != public_policy_version: | |
| raise ValueError('service task policy version differs from the episode') | |
| def _robot_experience_stream_adapter_snapshot_2(self): | |
| state = self._robot_experience_adapter_snapshot() | |
| state['schema'] = 'robot-experience-stream-snapshot/v2' | |
| state['active_object_ids'] = sorted(self.active_object_ids) | |
| state['public_policy_version'] = self.public_policy_version | |
| state['rule_epoch'] = self.expected_rule_epoch | |
| return state | |
| def _robot_experience_adapter_read_work_order(self, work_order): | |
| order = self._order(work_order) | |
| if not order: | |
| return self._finish('read_work_order', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown')) | |
| (task, obj) = self._work_context(order) | |
| if not task or not obj: | |
| return self._finish('read_work_order', fn__error('WORK_ORDER_UNAVAILABLE', 'the work-order records are incomplete')) | |
| if (task.get('intake_receipt') or {}).get('status') == 'accepted': | |
| transfer_state = 'intake_accepted' | |
| elif task.get('transfer_profile_submitted'): | |
| transfer_state = 'configured_unverified' | |
| else: | |
| transfer_state = 'unconfigured' | |
| assigned = self._get('robot_unit', 'robot_id', task.get('assigned_robot_id')) | |
| return self._finish('read_work_order', fn__success({'work_order': work_order, 'status': task.get('status'), 'destination': {'name': self._room_name(order['destination_room_id'])}, 'object': {'display_name': obj.get('display_name')}, 'stock_group': task.get('stock_group'), 'intake_code': task.get('intake_code'), 'policy_version': task.get('policy_version'), 'transfer_state': transfer_state, 'assigned_robot_display_name': (assigned or {}).get('display_name')})) | |
| def _robot_state_action_adapter_pickup(self, work_order, object_handle): | |
| order = self._order(work_order) | |
| if not order: | |
| return self._finish('pickup', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown')) | |
| if not isinstance(object_handle, str) or object_handle not in self.issued_object_handles or object_handle not in self._object_by_handle: | |
| return self._finish('pickup', fn__error('OBJECT_NOT_OBSERVED', 'observe the parcel locally before pickup')) | |
| def mutate(): | |
| (task, obj) = self._work_context(order) | |
| actor = self._robot() | |
| if not task or not obj or (not actor): | |
| return fn__error('WORK_ORDER_UNAVAILABLE', 'the work-order records are incomplete') | |
| if task.get('status') not in {'assigned', 'in_progress'}: | |
| return fn__error('WORK_ORDER_NOT_PICKABLE', 'blocked or terminal work cannot record pickup') | |
| if task.get('assigned_robot_id') != self.robot_id or len(self._active_assignments(task_id=task['task_id'], robot_id=self.robot_id)) != 1: | |
| return fn__error('ASSIGNMENT_REQUIRED', "pickup requires the controlled robot's active assignment") | |
| if self._object_by_handle[object_handle] != order['object_id']: | |
| return fn__error('WORK_ORDER_OBJECT_MISMATCH', 'the observed parcel does not belong to this work order') | |
| if actor.get('payload_object_id') or obj.get('held_by_robot_id') or obj.get('current_room_id') != actor.get('current_room_id') or (actor.get('current_room_id') != task.get('source_room_id')): | |
| return fn__error('PICKUP_LOCATION_OR_CUSTODY_INVALID', 'the work-order parcel is not locally pickable') | |
| steps = self._task_steps(task['task_id']) | |
| pick_index = next((index for (index, row) in enumerate(steps) if row.get('step_type') == 'pick'), None) | |
| if pick_index is None or steps[pick_index].get('status') not in {'pending', 'in_progress'}: | |
| return fn__error('PICK_STEP_NOT_OPEN', 'the pickup obligation is not open') | |
| now = fn__timestamp() | |
| for step in steps[:pick_index]: | |
| if step.get('step_type') == 'navigate' and step.get('room_id') == actor.get('current_room_id') and (step.get('status') in {'pending', 'in_progress'}): | |
| step.update(status='completed', completed_at=now, blocked_reason=None, updated_at=now) | |
| self._save('task_step', step) | |
| elif step.get('status') != 'completed': | |
| return fn__error('PRIOR_STEP_OPEN', 'pickup requires earlier obligations to be complete') | |
| domain = mod_importlib.import_module('mcp_servers.robot_domain') | |
| native = domain.attach_object_to_robot(self.sm, object_id=obj['object_id'], robot_id=self.robot_id, task_id=task['task_id']) | |
| if native.get('status') != 'success': | |
| return fn__error(fn__code(native), 'pickup was rejected') | |
| task = self._get('service_task', 'task_id', task['task_id']) | |
| if task and task.get('status') == 'assigned': | |
| task.update(status='in_progress', updated_at=now) | |
| self._save('service_task', task) | |
| return fn__success({'work_order': work_order, 'object_handle': object_handle, 'handling_state': 'in_transit'}) | |
| return self._attempt('pickup', mutate) | |
| def _robot_state_action_adapter_import_observation_ledger(self, ledger): | |
| if not isinstance(ledger, dict): | |
| raise ValueError('observation ledger must be an object') | |
| self._refresh_plan_handles() | |
| specs = {'exit_handles': (self.issued_exit_handles, set(self._edge_by_handle)), 'object_handles': (self.issued_object_handles, set(self._object_by_handle)), 'plan_handles': (self.issued_plan_handles, set(self._plan_by_handle)), 'robot_handles': (self.issued_robot_handles, set(self._robot_by_handle)), 'work_orders': (self.issued_work_orders, set(self._orders))} | |
| counts = {} | |
| for (key, (target, known)) in specs.items(): | |
| values = ledger.get(key, []) | |
| if not isinstance(values, list) or not all((isinstance(value, str) for value in values)): | |
| raise ValueError(f'{key} must be a list of strings') | |
| accepted = set(values) & known | |
| before = len(target) | |
| target.update(accepted) | |
| counts[f'{key}_imported'] = len(target) - before | |
| return counts | |
| def _robot_experience_adapter_init(self, sm, *, robot_id, handle_seed, task_ids, rubric, rule_table=None): | |
| if not isinstance(rubric, dict) or rubric.get('version') != 'robot-experience-rubric/v1': | |
| raise ValueError('unsupported robot experience rubric') | |
| if rubric.get('policy_version') != 'PV-18': | |
| raise ValueError('rubric policy version does not match the adapter') | |
| home_room_id = rubric.get('home_room_id') | |
| if not isinstance(home_room_id, str) or not home_room_id: | |
| raise ValueError('rubric must define a home_room_id') | |
| legacy_rubric = {'version': 'robot-state-action-rubric/v1', 'orders': ext_deepcopy(rubric.get('orders'))} | |
| self._robot_state_action_adapter_init(sm, robot_id=robot_id, handle_seed=handle_seed, task_ids=task_ids, rubric=legacy_rubric) | |
| self.tools = ext_deepcopy(DATA_TOOLS_6) | |
| self.home_room_id = home_room_id | |
| self.rule_table = fn__validate_rule_table(rule_table) | |
| self._rubric_v3 = ext_deepcopy(rubric) | |
| self._inspected_target_ids: set[str] = set() | |
| self._storage_by_handle: dict[str, tuple[str, str]] = {} | |
| seen_unit_ids: set[str] = set() | |
| for room in self._all('room'): | |
| units = room.get('storage_units', []) | |
| if not isinstance(units, list): | |
| raise ValueError('room storage_units must be a list') | |
| for unit in units: | |
| unit_id = unit.get('unit_id') if isinstance(unit, dict) else None | |
| if not isinstance(unit_id, str) or not unit_id or unit_id in seen_unit_ids: | |
| raise ValueError('storage unit IDs must be unique non-empty strings') | |
| if not isinstance(unit.get('stock_group'), str) or not unit['stock_group']: | |
| raise ValueError('storage units must define a stock_group') | |
| if not isinstance(unit.get('opened'), bool): | |
| raise ValueError('storage units must define boolean opened state') | |
| if not isinstance(unit.get('calibration_records'), list): | |
| raise ValueError('storage calibration_records must be a list') | |
| seen_unit_ids.add(unit_id) | |
| self._storage_by_handle[self._handle('storage', unit_id)] = (room['room_id'], unit_id) | |
| self.issued_storage_handles: set[str] = set() | |
| for (work_order, order) in self._orders.items(): | |
| (task, obj) = self._work_context(order) | |
| if not task or not obj: | |
| raise ValueError(f'incomplete records for {work_order}') | |
| if task.get('policy_version') != 'PV-18': | |
| raise ValueError('task policy version does not match the adapter') | |
| if task.get('intake_code') not in DATA_INTAKE_CODES: | |
| raise ValueError('task has an unknown intake code') | |
| if obj.get('handling_code') not in DATA_HANDLING_CODES: | |
| raise ValueError('object has an unknown handling code') | |
| if task.get('stock_group') != obj.get('stock_group'): | |
| raise ValueError('work order and parcel stock groups differ') | |
| if self._source_inspection_valid(order, task, obj): | |
| self._inspected_target_ids.add(obj['object_id']) | |
| def _robot_experience_adapter_snapshot(self): | |
| state = self._robot_state_action_adapter_snapshot() | |
| state['schema'] = 'robot-experience-snapshot/v1' | |
| state['inspected_target_object_ids'] = sorted(self._inspected_target_ids) | |
| return state | |
| def _robot_state_action_adapter_init(self, sm, *, robot_id, handle_seed, task_ids, rubric): | |
| if not isinstance(robot_id, str) or not robot_id: | |
| raise ValueError('robot_id must be a non-empty string') | |
| if not isinstance(handle_seed, str) or not handle_seed: | |
| raise ValueError('handle_seed must be a non-empty string') | |
| if not isinstance(task_ids, list) or len(task_ids) != 4 or len(set(task_ids)) != 4 or (not all((isinstance(x, str) and x for x in task_ids))): | |
| raise ValueError('task_ids must contain four unique strings') | |
| if not isinstance(rubric, dict) or rubric.get('version') != 'robot-state-action-rubric/v1': | |
| raise ValueError('unsupported robot state-action rubric') | |
| orders = rubric.get('orders') | |
| if not isinstance(orders, list) or len(orders) != 4: | |
| raise ValueError('rubric must contain exactly four orders') | |
| self.sm = sm | |
| self.robot_id = robot_id | |
| self.handle_seed = handle_seed | |
| self.tools = ext_deepcopy(DATA_TOOLS_7) | |
| self._task_ids = tuple(task_ids) | |
| self._orders: dict[str, dict[str, str]] = {} | |
| for row in orders: | |
| if not isinstance(row, dict) or any((not isinstance(row.get(key), str) or not row[key] for key in ('work_order', 'task_id', 'object_id', 'destination_room_id'))): | |
| raise ValueError('rubric order fields must be non-empty strings') | |
| if row['work_order'] in self._orders: | |
| raise ValueError('work_order values must be unique') | |
| self._orders[row['work_order']] = {key: row[key] for key in ('work_order', 'task_id', 'object_id', 'destination_room_id')} | |
| if set(self._task_ids) != {row['task_id'] for row in self._orders.values()}: | |
| raise ValueError('task_ids and rubric orders differ') | |
| if self._get('robot_unit', 'robot_id', robot_id) is None: | |
| raise ValueError('controlled robot does not exist') | |
| self._edge_by_handle = {self._handle('exit', row['edge_id']): row['edge_id'] for row in self._all('map_edge')} | |
| self._object_by_handle = {self._handle('object', row['object_id']): row['object_id'] for row in self._all('object_item')} | |
| self._robot_by_handle = {self._handle('robot', row['robot_id']): row['robot_id'] for row in self._all('robot_unit')} | |
| self._plan_by_handle: dict[str, str] = {} | |
| self.issued_exit_handles: set[str] = set() | |
| self.issued_object_handles: set[str] = set() | |
| self.issued_plan_handles: set[str] = set() | |
| self.issued_robot_handles: set[str] = set() | |
| self.issued_work_orders: set[str] = set(self._orders) | |
| self._actions: list[dict[str, ext_Any]] = [] | |
| self._next_action_index = 1 | |
| self._refresh_plan_handles() | |
| def _robot_state_action_adapter_snapshot(self): | |
| state: dict[str, ext_Any] = {'schema': 'robot-state-action-snapshot/v1'} | |
| relevant_tasks = set(self._task_ids) | |
| for (output_key, (entity, id_field)) in DATA__SNAPSHOT_TABLES.items(): | |
| rows = self._all(entity) | |
| if entity == 'service_task': | |
| rows = [row for row in rows if row.get('task_id') in relevant_tasks] | |
| elif entity in {'task_step', 'task_assignment', 'navigation_plan'}: | |
| rows = [row for row in rows if row.get('task_id') in relevant_tasks] | |
| state[output_key] = [fn__strip_volatile(row) for row in sorted(rows, key=lambda row: str(row.get(id_field) or ''))] | |
| state['observation_ledger'] = self.export_observation_ledger() | |
| state['action_ledger'] = ext_deepcopy(self._actions) | |
| return state | |