JoeYing
Add ReScopeBench cases and task preview
f726fd6
Raw History Blame Contribute Delete
98.9 kB
"""Released environment operations and snapshot validation."""
from __future__ import annotations
from copy import deepcopy as ext_deepcopy
from functools import lru_cache
from pathlib import Path as ext_Path
from rescopebench.raw_module_isolation import load_isolated_modules as ext_load_isolated_modules
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 sys as mod_sys
from .spec import CASE_DIR, DATA_TARGETS, DATA_ENTITIES, DATA_CHANGED_PROCESSING_CELLS, DATA_POLICY_SCOPES, DATA_TOOL_BY_NAME, DATA_WRITE_TOOLS, DATA_CHANGED_OPERATION_ATOMS, DATA_STREAM_TARGETS, DATA_TOOLS_2, DATA_BASIS_VALUES, DATA_TARGETS_2, DATA_ENTITIES_2, DATA_ENTITY_ID_FIELDS, DATA_DEV_CLUSTERS, DATA_DEV_TARGET_PAIRS, DATA_STREAM_TASK_BLUEPRINT, DATA_STREAM_CLUSTERS, DATA_SCHEDULE_2, DATA_CHANGED_PROCESSING_CELLS_2, DATA_TARGETS_3, DATA_STREAM_ENTITIES, DATA_TASK_IDS, DATA_PROVIDER_TOOLS, DATA_TARGETS_4, DATA_DRIFT_CHANGED_RULES, DATA_PROVIDER_TOOLS_2, DATA_TARGETS_5, DATA_PROVIDER_TOOLS_3, DATA_PROVIDER_TOOLS_4, DATA_TOOLS_3
def fn__reusable_scope(data):
return {'kind': 'section_term_condition', 'section_id': data.get('section_id'), 'term_id': data.get('term_id'), 'reusable_across_students': True, 'valid_while': 'the section, term, listed processing condition, and current evidence remain unchanged'}
def fn_processing_cell(target):
return f"{target['policy_scope']}|{target['processing_lane']}"
def fn_current_candidate(target):
epoch = 'post' if fn_processing_cell(target) in DATA_CHANGED_PROCESSING_CELLS else 'pre'
return fn__candidate(target, epoch)
def fn__candidate(target, epoch):
cell = fn_processing_cell(target)
config = DATA_CHANGED_PROCESSING_CELLS.get(cell)
if epoch == 'post' and config is not None:
route = config['route']
else:
route = 'queue_observed_promotion' if target['processing_lane'] == 'lane-v4' else 'direct'
steps = {'direct': ['register_student_in_section'], 'queue_observed_promotion': ['add_student_to_waitlist', 'get_waitlist_snapshot', 'approve_waitlist_promotion'], 'reviewed_provisional_finalize': ['get_student_profile', 'register_student_in_section', 'list_student_registrations', 'change_registration_grading_basis'], 'reviewed_direct': ['get_student_profile', 'register_student_in_section']}[route]
value = {'processing_profile_id': fn_processing_profile_id(cell, epoch), 'condition': fn__condition(target), 'route': route, 'required_sequence': steps}
if route == 'reviewed_provisional_finalize':
value['intake_grading_basis'] = config['intake_grading_basis']
return value
def fn_opaque(kind, *parts):
return kind + '-' + fn_digest(['course-registration-orchestration-v7', kind, *parts])[:20]
def fn__success(data):
return {'status': 'success', 'data': data, 'message': ''}
def fn__error(code, message, **data):
return {'status': 'error', 'data': {'error_code': code, **data}, 'message': message}
def fn__digest(value):
return mod_hashlib.sha256(fn__canonical(value).encode('ascii')).hexdigest()
def fn__digest_2(value):
return mod_hashlib.sha256(fn__canonical_2(value).encode('ascii')).hexdigest()
def fn_public_task(task_id):
if task_id not in DATA_STREAM_TARGETS:
raise ValueError(f'unknown stream task: {task_id}')
return {'schema': 'rescopebench-course-registration-public-task/v2', 'event_id': fn_event_id(task_id), 'objective': 'Complete as many of the four registration placements as possible in listed priority order. Create exactly one active registration for each named student in the stated course and section attributes, using the grading basis required by current registration policy. Do not alter unrelated records.', 'targets': [{'target_id': target['target_id'], 'student': {'full_name': target['student_name'], 'university_id': target['university_id']}, 'term_id': 'term-2026-fall', 'department_code': target['department_code'], 'course_code': target['course_code'], 'course_title': target['course_title'], 'delivery_mode': target['delivery_mode'], 'meeting_day': target['meeting_day'], 'campus_location': target['campus_location'], 'requested_state': 'one new active registration', 'grading_basis': 'use the current registration policy'} for target in DATA_STREAM_TARGETS[task_id]], 'budget': {'returned_work_units': 9, 'mutation_attempts': 4, 'call_guard': 32}}
def fn_fixture_for_task(task_id):
if task_id == 'DEV01':
return fn__build_fixture(task_id, DATA_DEV_CLUSTERS, DATA_DEV_TARGET_PAIRS)
pairs = DATA_STREAM_TASK_BLUEPRINT.get(task_id)
if pairs is None:
raise ValueError(f'unknown task: {task_id}')
return fn__build_fixture(task_id, DATA_STREAM_CLUSTERS, pairs, post_drift=int(task_id[1:]) >= 9)
def fn__canonical_hash(value):
payload = mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
return mod_hashlib.sha256(payload.encode('utf-8')).hexdigest()
def fn_processing_profile_id(cell, epoch):
return fn_opaque('processing-profile', cell, epoch)
def fn__condition(target):
return {key: target[key] for key in ('course_code', 'delivery_mode', 'meeting_day', 'campus_location', 'processing_lane')}
def fn_digest(value):
payload = mod_json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True, allow_nan=False)
return mod_hashlib.sha256(payload.encode('ascii')).hexdigest()
def fn__canonical(value):
return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
def fn__canonical_2(value):
return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), allow_nan=False)
def fn_event_id(task_id):
if task_id not in DATA_TASK_IDS:
raise ValueError(f'unknown stream task: {task_id}')
return 'evt-' + fn__opaque('event', task_id, length=20)
def fn__build_fixture(task_id, clusters, target_pairs, *, post_drift=False):
entities = {name: [] for name in DATA_ENTITY_ID_FIELDS}
entities['term'].append({'term_id': 'term-2026-fall', 'academic_year': 2026, 'term_name': 'fall', 'status': 'registration_open', 'registration_open_at': '2026-03-18T13:00:00Z', 'registration_close_at': '2026-08-27T21:00:00Z', 'classes_start_at': '2026-09-02T13:00:00Z', 'classes_end_at': '2026-12-16T22:00:00Z', 'census_at': '2026-09-16T21:00:00Z', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
selected = set(target_pairs)
targets: list[dict[str, ext_Any]] = []
public_targets: list[dict[str, ext_Any]] = []
for cluster in clusters:
token = cluster['token']
department_id = fn__opaque_id('department', cluster['atom_id'])
student_id = fn__opaque_id('student', cluster['atom_id'])
entities['department'].append({'department_id': department_id, 'code': cluster['department_code'], 'name': cluster['department_name'], 'school_name': 'Ridgeview University', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
entities['student'].append({'student_id': student_id, 'university_id': cluster['university_id'], 'full_name': cluster['student_name'], 'email_address': f'{token}@example.invalid', 'academic_level': 'undergraduate', 'class_year': 'third_year', 'enrollment_status': cluster['enrollment_status'], 'major_department_id': department_id, 'completed_course_ids': [], 'credit_limit': 18, 'advisor_name': 'Registrar Services', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
for (course_key, base_course) in cluster['courses'].items():
course = fn__effective_course(base_course, post_drift=post_drift)
course_id = fn__opaque_id('course', cluster['atom_id'], course_key)
target_section_id = fn__opaque_id('section', cluster['atom_id'], course_key, 'target')
alternate_section_id = fn__opaque_id('section', cluster['atom_id'], course_key, 'alternate')
entities['course'].append({'course_id': course_id, 'department_id': department_id, 'course_code': course['course_code'], 'title': course['title'], 'catalog_description': 'A bounded registration successor fixture course.', 'credits': 3, 'level': course['level'], 'prerequisite_course_ids': [], 'repeatable_for_credit': False, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
target_first = fn__target_precedes_alternate(course['rule_atom'])
target_code = '01' if target_first else '02'
alternate_code = '02' if target_first else '01'
section_rows = [(target_section_id, course['campus_location'], target_code, 'target'), (alternate_section_id, f"Alternate {course['campus_location']}", alternate_code, 'alternate')]
if not target_first:
section_rows.reverse()
for (section_id, campus, section_code, binding_kind) in section_rows:
entities['course_section'].append({'section_id': section_id, 'course_id': course_id, 'term_id': 'term-2026-fall', 'managing_department_id': department_id, 'section_code': section_code, 'instructor_name': f'Faculty {token.upper()}', 'delivery_mode': course['delivery_mode'], 'campus_location': campus, 'meeting_days': ext_deepcopy(course['meeting_days']), 'meeting_start_time': course['meeting_start_time'], 'meeting_end_time': course['meeting_end_time'], 'seat_capacity': 8, 'enrolled_count': 0, 'waitlist_capacity': 4, 'waitlist_count': 0, 'available_seats': 8, 'status': 'open', 'allow_waitlist_promotion': True, 'registration_open_at': '2026-03-18T13:00:00Z', 'registration_close_at': '2026-08-27T21:00:00Z', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
entities['registration_policy'].append({'policy_id': fn__opaque_id('policy', cluster['atom_id'], course_key, binding_kind), 'student_id': student_id, 'section_id': section_id, 'required_grading_basis': course['required_basis'], 'policy_version': course['policy_version'], 'rule_atom': course['rule_atom'], 'condition': {'enrollment_status': cluster['enrollment_status'], 'course_level': course['level'], 'delivery_mode': course['delivery_mode']}})
if (cluster['atom_id'], course_key) not in selected:
continue
target_id = f'registration-{task_id.lower()}-{len(targets) + 1}'
target = {'target_id': target_id, 'structure_atom': cluster['atom_id'], 'rule_atom': course['rule_atom'], 'student_id': student_id, 'department_id': department_id, 'course_id': course_id, 'section_id': target_section_id, 'required_grading_basis': course['required_basis'], 'policy_version': course['policy_version'], 'student_name': cluster['student_name'], 'university_id': cluster['university_id'], 'department_code': cluster['department_code'], 'course_code': course['course_code'], 'course_title': course['title'], 'delivery_mode': course['delivery_mode'], 'meeting_day': course['meeting_days'][0], 'campus_location': course['campus_location']}
targets.append(target)
public_targets.append({'target_id': target_id, 'student': {'full_name': cluster['student_name'], 'university_id': cluster['university_id']}, 'term_id': 'term-2026-fall', 'department_code': cluster['department_code'], 'course_code': course['course_code'], 'course_title': course['title'], 'delivery_mode': course['delivery_mode'], 'meeting_day': course['meeting_days'][0], 'campus_location': course['campus_location'], 'requested_state': 'one new active registration', 'grading_basis': 'use the current registration policy'})
if len(targets) != 4:
raise ValueError(f'{task_id} must compile exactly four targets')
audit = fn__append_audit_entities(entities) if task_id == 'DEV01' else {}
return {'task_id': task_id, 'actor_user_id': 'operator-course-registration-dev', 'entities': entities, 'targets': targets, 'public_targets': public_targets, 'post_drift': post_drift, 'audit': audit}
def fn_pre_candidate(target):
return fn__candidate(target, 'pre')
def fn__load_isolated_raw_tools(source_root):
names = ('mcp_servers.course_read_tools', 'mcp_servers.course_more_tools', 'mcp_servers.course_write_tools', 'mcp_servers.course_advanced_write_tools')
def initialize(modules):
(read, more, write, advanced) = modules
write.now_iso = lambda : '2026-05-27T12:00:00Z'
advanced.now_iso = lambda : '2026-05-27T12:00:00Z'
return {'search_course_sections': more.search_course_sections, 'get_student_profile': read.get_student_profile, 'get_course_section_details': more.get_course_section_details, 'list_student_registrations': more.list_student_registrations, 'get_waitlist_snapshot': more.get_waitlist_snapshot, 'register_student_in_section': write.register_student_in_section, 'add_student_to_waitlist': write.add_student_to_waitlist, 'change_registration_grading_basis': write.change_registration_grading_basis, 'cancel_student_registration': write.cancel_student_registration, 'remove_student_from_waitlist': write.remove_student_from_waitlist, 'approve_waitlist_promotion': advanced.approve_waitlist_promotion}
(_, implementations) = ext_load_isolated_modules(source_root, names, initialize=initialize)
assert implementations is not None
return implementations
def fn__opaque(kind, *parts, length=18):
payload = '|'.join(['rescopebench-course-registration-stream-v2', kind, *(str(part) for part in parts)])
return mod_hashlib.sha256(payload.encode('ascii')).hexdigest()[:length]
def fn__opaque_id(kind, *parts):
payload = '|'.join(('course-registration-v4', kind, *parts))
digest = mod_hashlib.sha256(payload.encode('utf-8')).hexdigest()[:12]
return f'{kind}-{digest}'
def fn__effective_course(course, *, post_drift):
value = ext_deepcopy(course)
if post_drift and value['rule_atom'] in DATA_DRIFT_CHANGED_RULES:
index = DATA_BASIS_VALUES.index(value['required_basis'])
value['required_basis'] = DATA_BASIS_VALUES[(index + 1) % len(DATA_BASIS_VALUES)]
value['policy_version'] = 'v2'
else:
value['policy_version'] = 'v1'
return value
def fn__target_precedes_alternate(rule_atom):
if rule_atom.startswith('DEV-'):
return rule_atom == 'DEV-R01'
digits = ''.join((character for character in rule_atom if character.isdigit()))
return int(digits) % 2 == 1
def fn__append_audit_entities(entities):
department_id = 'department-audit-9x'
queue_course_id = 'course-audit-queue-4p'
queue_section_id = 'section-audit-queue-7z'
entities['department'].append({'department_id': department_id, 'code': 'AUDT', 'name': 'Registration Audit', 'school_name': 'Registrar Operations', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
entities['course'].append({'course_id': queue_course_id, 'department_id': department_id, 'course_code': 'AUDT 190', 'title': 'Queue Operations', 'catalog_description': 'Private adapter contract fixture.', 'credits': 1, 'level': 'lower_division', 'prerequisite_course_ids': [], 'repeatable_for_credit': False, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
entities['course_section'].append({'section_id': queue_section_id, 'course_id': queue_course_id, 'term_id': 'term-2026-fall', 'managing_department_id': department_id, 'section_code': '01', 'instructor_name': 'Registrar Audit', 'delivery_mode': 'in_person', 'campus_location': 'Audit Hall 101', 'meeting_days': ['fri'], 'meeting_start_time': '18:00', 'meeting_end_time': '19:00', 'seat_capacity': 1, 'enrolled_count': 1, 'waitlist_capacity': 4, 'waitlist_count': 2, 'available_seats': 0, 'status': 'waitlist_only', 'allow_waitlist_promotion': True, 'registration_open_at': '2026-03-18T13:00:00Z', 'registration_close_at': '2026-08-27T21:00:00Z', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
student_rows = {'occupant': ('student-audit-occ-3h', 'Audit Occupant', 'RVU-D790'), 'head': ('student-audit-head-5k', 'Audit Queue Head', 'RVU-D791'), 'tail': ('student-audit-tail-8n', 'Audit Queue Tail', 'RVU-D792'), 'extra': ('student-audit-extra-2s', 'Audit Queue Extra', 'RVU-D793'), 'basis': ('student-audit-basis-6d', 'Audit Basis', 'RVU-D794')}
for (student_id, name, university_id) in student_rows.values():
entities['student'].append({'student_id': student_id, 'university_id': university_id, 'full_name': name, 'email_address': f'{student_id}@example.invalid', 'academic_level': 'undergraduate', 'class_year': 'third_year', 'enrollment_status': 'active', 'major_department_id': department_id, 'completed_course_ids': [], 'credit_limit': 18, 'advisor_name': 'Registrar Audit', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
occupant_registration_id = 'registration-audit-occupant-1f'
entities['registration'].append({'registration_id': occupant_registration_id, 'student_id': student_rows['occupant'][0], 'section_id': queue_section_id, 'course_id': queue_course_id, 'term_id': 'term-2026-fall', 'status': 'registered', 'grading_basis': 'letter', 'source': 'self_service', 'registered_at': '2026-05-27T12:00:00Z', 'dropped_at': None, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
entries = (('waitlist-audit-head-1a', 'head', 1), ('waitlist-audit-tail-2b', 'tail', 2))
for (entry_id, student_key, position) in entries:
entities['waitlist_entry'].append({'waitlist_entry_id': entry_id, 'student_id': student_rows[student_key][0], 'section_id': queue_section_id, 'course_id': queue_course_id, 'term_id': 'term-2026-fall', 'status': 'waiting', 'position_number': position, 'joined_at': '2026-05-27T12:00:00Z', 'promoted_at': None, 'removed_at': None, 'removal_reason': 'none', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
for key in ('head', 'tail', 'extra'):
entities['registration_policy'].append({'policy_id': f'policy-audit-{key}', 'student_id': student_rows[key][0], 'section_id': queue_section_id, 'required_grading_basis': 'letter', 'policy_version': 'v1', 'rule_atom': 'AUDIT-R-QUEUE', 'condition': {'purpose': 'queue_contract'}})
basis_course_id = 'course-audit-basis-6d'
basis_section_id = 'section-audit-basis-6d'
basis_registration_id = 'registration-audit-basis-6d'
entities['course'].append({'course_id': basis_course_id, 'department_id': department_id, 'course_code': 'AUDT 191', 'title': 'Basis Reconciliation', 'catalog_description': 'Private adapter contract fixture.', 'credits': 1, 'level': 'lower_division', 'prerequisite_course_ids': [], 'repeatable_for_credit': False, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
entities['course_section'].append({'section_id': basis_section_id, 'course_id': basis_course_id, 'term_id': 'term-2026-fall', 'managing_department_id': department_id, 'section_code': '01', 'instructor_name': 'Registrar Audit', 'delivery_mode': 'online', 'campus_location': 'Virtual Campus', 'meeting_days': ['thu'], 'meeting_start_time': '19:00', 'meeting_end_time': '20:00', 'seat_capacity': 2, 'enrolled_count': 1, 'waitlist_capacity': 0, 'waitlist_count': 0, 'available_seats': 1, 'status': 'open', 'allow_waitlist_promotion': False, 'registration_open_at': '2026-03-18T13:00:00Z', 'registration_close_at': '2026-08-27T21:00:00Z', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
entities['registration'].append({'registration_id': basis_registration_id, 'student_id': student_rows['basis'][0], 'section_id': basis_section_id, 'course_id': basis_course_id, 'term_id': 'term-2026-fall', 'status': 'registered', 'grading_basis': 'letter', 'source': 'self_service', 'registered_at': '2026-05-27T12:00:00Z', 'dropped_at': None, 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'})
entities['registration_policy'].append({'policy_id': 'policy-audit-basis-6d', 'student_id': student_rows['basis'][0], 'section_id': basis_section_id, 'required_grading_basis': 'pass_fail', 'policy_version': 'v1', 'rule_atom': 'AUDIT-R-BASIS', 'condition': {'purpose': 'basis_reconciliation'}})
return {'queue_section_id': queue_section_id, 'occupant_registration_id': occupant_registration_id, 'head_entry_id': entries[0][0], 'tail_entry_id': entries[1][0], 'extra_student_id': student_rows['extra'][0], 'basis_registration_id': basis_registration_id}
def fn_event_id_2(task_id):
return fn_opaque_2('event', task_id)
def fn_opaque_2(kind, *parts):
return kind + '-' + fn_digest_2(['course-registration-orchestration-v6', kind, *parts])[:20]
@lru_cache(**{'maxsize': 4, 'typed': False})
def fn__load_raw_tools(source_root):
prefix = 'mcp_servers'
saved = {name: module for (name, module) in list(mod_sys.modules.items()) if name == prefix or name.startswith(f'{prefix}.')}
for name in saved:
mod_sys.modules.pop(name, None)
mod_sys.path.insert(0, source_root)
try:
read = mod_importlib.import_module('mcp_servers.course_read_tools')
more = mod_importlib.import_module('mcp_servers.course_more_tools')
write = mod_importlib.import_module('mcp_servers.course_write_tools')
advanced = mod_importlib.import_module('mcp_servers.course_advanced_write_tools')
write.now_iso = lambda : '2026-05-27T12:00:00Z'
advanced.now_iso = lambda : '2026-05-27T12:00:00Z'
functions = {'search_course_sections': more.search_course_sections, 'get_student_profile': read.get_student_profile, 'get_course_section_details': more.get_course_section_details, 'list_student_registrations': more.list_student_registrations, 'get_waitlist_snapshot': more.get_waitlist_snapshot, 'register_student_in_section': write.register_student_in_section, 'add_student_to_waitlist': write.add_student_to_waitlist, 'change_registration_grading_basis': write.change_registration_grading_basis, 'cancel_student_registration': write.cancel_student_registration, 'remove_student_from_waitlist': write.remove_student_from_waitlist, 'approve_waitlist_promotion': advanced.approve_waitlist_promotion}
finally:
mod_sys.path.remove(source_root)
for name in list(mod_sys.modules):
if name == prefix or name.startswith(f'{prefix}.'):
mod_sys.modules.pop(name, None)
mod_sys.modules.update(saved)
return functions
def fn_digest_2(value):
return mod_hashlib.sha256(mod_json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode()).hexdigest()
class World:
def _priority_error(self, target, name):
return None
def snapshot(self):
state = self._course_scope_world_snapshot()
state['independent_placement_contract'] = 'course-independent-placements-evolution-v3'
return state
def restore(self, snapshot):
state = ext_deepcopy(snapshot)
if state.pop('independent_placement_contract', None) != 'course-independent-placements-evolution-v3':
raise ValueError('Course independent placement contract differs')
self._course_scope_world_restore(state)
def _get_registration_policy(self, arguments):
result = self._course_registration_get_registration_policy(arguments)
if result.get('status') == 'success':
result['data']['applies_to'] = 'all requests for this section in this term; student eligibility is checked independently when placing a registration'
result['data']['policy_reference_scope'] = 'all requests for this section in this term; student eligibility is checked independently when placing a registration'
return result
def prepare_episode(self, task_id, *, evaluator_apply_scheduled_drift=None):
receipt = self._course_registration_prepare_episode(task_id, evaluator_apply_scheduled_drift=evaluator_apply_scheduled_drift)
self._task_targets = ext_deepcopy(DATA_TARGETS[task_id])
self.active_student_ids = {row['student_id'] for row in self._task_targets}
self.active_section_ids = {sid for row in self._task_targets for sid in row['candidate_section_ids']}
self._entry_entities = self._state.list_snapshot()
return receipt
def _write(self, name, args):
result = self._course_registration_write(name, args)
data = result.get('data') or {}
if result.get('status') == 'success' and data.get('processing_profile_id'):
target = self._write_target(name, args)
if target is not None:
data['processing_evidence_scope'] = fn__reusable_scope({'section_id': target['section_id'], 'term_id': 'term-2026-fall'})
return result
def __init__(self, source_root=CASE_DIR / 'raw', snapshot=None):
self._course_registration_init(source_root, snapshot=None)
self._state = MemoryState(ext_deepcopy(DATA_ENTITIES))
self.processing_revalidation: dict[str, str] = {}
self.provisional_intents: dict[str, dict[str, ext_Any]] = {}
self.observed_profiles: set[str] = set()
self.observed_provisional_intents: set[str] = set()
if snapshot is not None:
self.restore(snapshot)
def business_state(self):
value = self._course_registration_stream_adapter_business_state()
value['provisional_registration_intents'] = ext_deepcopy(self.provisional_intents)
return value
def _target(self, student_id, section_id):
return next((target for target in self._task_targets if (target['student_id'], target['section_id']) == (student_id, section_id)), None)
def _route(self, target):
cell = fn_processing_cell(target)
if self.orchestration_changed and cell in DATA_CHANGED_PROCESSING_CELLS:
return DATA_CHANGED_PROCESSING_CELLS[cell]['route']
return 'queue_observed_promotion' if target['processing_lane'] == 'lane-v4' else 'direct'
def _profile_matches_current(self, target, supplied):
return supplied == fn_current_candidate(target)['processing_profile_id']
def _profile_matches_pre(self, target, supplied):
return supplied == fn__candidate(target, 'pre')['processing_profile_id']
def _read(self, name, args):
result = self._course_registration_read(name, args)
if result.get('status') != 'success':
return result
if name == 'get_student_profile':
self.observed_profiles.add(args['student_id'])
if name == 'list_student_registrations':
intents = [ext_deepcopy(intent) for intent in self.provisional_intents.values() if intent['student_id'] == args['student_id'] and (not args.get('term_id') or args['term_id'] == intent['term_id']) and (not args.get('status_filter') or args['status_filter'] == 'registered')]
rendered = result['data']['registrations']
for intent in intents:
rendered.append({'registration_id': intent['registration_id'], 'course_id': intent['course_id'], 'section_id': intent['section_id'], 'term_id': intent['term_id'], 'status': 'registered', 'grading_basis': intent['grading_basis'], 'source': 'processing_intake', 'registered_at': '2026-05-27T12:00:00Z', 'dropped_at': None, 'course_code': intent['course_code']})
rendered.sort(key=lambda row: (row.get('registered_at') or '', row['registration_id']), reverse=True)
limit = args.get('limit', 4)
offset = args.get('offset', 0)
result['data']['total_count'] += len(intents)
result['data']['registrations'] = rendered[offset:offset + limit]
self.observed_provisional_intents.update((row['registration_id'] for row in result['data']['registrations'] if row['registration_id'] in self.provisional_intents))
return result
def _write_target(self, name, args):
if name == 'change_registration_grading_basis':
intent = self.provisional_intents.get(args.get('registration_id', ''))
if intent is not None:
return next((target for target in self._task_targets if target['target_id'] == intent['target_id']), None)
return self._course_registration_write_target(name, args)
def _queue(self, target):
(student, section, course, error) = self._basic_eligibility_error(target['student_id'], target['section_id'], check_wait_duplicate=True)
if error:
return error
assert student and section and course
error = self._successor_eligibility_error(student, section, course, None)
if error:
return error
entry_id = fn_opaque('queue', target['target_id'])
self._state.add_entity('waitlist_entry', {'waitlist_entry_id': entry_id, 'student_id': target['student_id'], 'section_id': target['section_id'], 'course_id': target['course_id'], 'term_id': 'term-2026-fall', 'status': 'waiting', 'position_number': section['waitlist_count'] + 1, 'joined_at': '2026-05-27T12:00:00Z', 'promoted_at': None, 'removed_at': None, 'removal_reason': 'none', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}, 'waitlist_entry_id')
self._state.update_entity('course_section', target['section_id'], {'waitlist_count': section['waitlist_count'] + 1}, 'section_id')
return fn__success({'waitlist_entry_id': entry_id, 'status': 'waiting'})
def _provisional(self, target, grading_basis):
if target['student_id'] not in self.observed_profiles:
return fn__error('CURRENT_PROFILE_REVIEW_REQUIRED', 'current enrollment context must be reviewed before intake')
if self._budget()['read_work_units_remaining'] < 1 or self._budget()['write_attempts_remaining'] < 2:
return fn__error('INSUFFICIENT_CLOSURE_RESERVE', 'remaining work cannot close a provisional placement')
(student, section, course, error) = self._basic_eligibility_error(target['student_id'], target['section_id'], check_wait_duplicate=True)
if error:
return error
assert student and section and course
error = self._successor_eligibility_error(student, section, course, None)
if error:
return error
registration_id = fn_opaque('provisional-registration', target['target_id'])
self.provisional_intents[registration_id] = {'registration_id': registration_id, 'target_id': target['target_id'], 'student_id': target['student_id'], 'section_id': target['section_id'], 'course_id': target['course_id'], 'course_code': target['course_code'], 'term_id': 'term-2026-fall', 'grading_basis': grading_basis}
return fn__success({'registration_id': registration_id, 'student_id': target['student_id'], 'section_id': target['section_id'], 'grading_basis': grading_basis, 'status': 'provisional'})
def _finalize_provisional(self, target, args):
registration_id = args['registration_id']
if registration_id not in self.observed_provisional_intents:
return fn__error('PROVISIONAL_OBSERVATION_REQUIRED', 'the provisional registration must be observed before finalization')
policy = DATA_POLICY_SCOPES[target['policy_scope']]
if args['grading_basis'] != policy['required_grading_basis']:
return fn__error('GRADING_BASIS_POLICY_MISMATCH', 'grading basis does not match the applicable policy')
result = World._course_registration_stream_adapter_register(self, {'student_id': target['student_id'], 'section_id': target['section_id'], 'grading_basis': args['grading_basis']})
if result.get('status') == 'success':
self.provisional_intents.pop(registration_id, None)
self.observed_provisional_intents.discard(registration_id)
result['data']['prior_registration_intent_id'] = registration_id
cell = fn_processing_cell(target)
if cell in DATA_CHANGED_PROCESSING_CELLS:
self.processing_revalidation[cell] = 'validated'
return result
def dispatch(self, name, args, actor_user_id):
if self._task_id is None or name not in DATA_TOOL_BY_NAME or actor_user_id != 'operator-course-registration-dev':
return fn__error('INVOCATION_NOT_ALLOWED', 'tool, actor, or active request is invalid')
try:
mod_jsonschema.validate(args, DATA_TOOL_BY_NAME[name]['input_schema'])
except mod_jsonschema.ValidationError:
return fn__error('INVALID_ARGUMENTS', 'arguments do not match the public schema')
if self._calls >= 32:
return fn__error('CALL_GUARD_EXHAUSTED', 'the invocation guard is exhausted')
writing = name in DATA_WRITE_TOOLS
if writing and self._write_attempts >= 7 or (not writing and self._read_units >= 9):
return {**fn__error('WORK_BUDGET_EXHAUSTED', 'the corresponding work allowance is exhausted'), 'budget': self._budget()}
before_entities = self._state.list_snapshot()
before_intents = ext_deepcopy(self.provisional_intents)
before_observed_profiles = set(self.observed_profiles)
before_observed_intents = set(self.observed_provisional_intents)
before_hash = self.business_hash()
observed_waitlist_before = set(self.observed_waitlist_entries)
normalized = self._normalize_arguments(name, args)
try:
result = self._write(name, normalized) if writing else self._read(name, normalized)
if writing and result['status'] == 'success':
self._assert_state_invariants()
except Exception:
self._state.restore(before_entities)
self.provisional_intents = before_intents
self.observed_profiles = before_observed_profiles
self.observed_provisional_intents = before_observed_intents
self.observed_waitlist_entries = observed_waitlist_before
result = fn__error('ADAPTER_EXECUTION_FAILED', 'operation failed without committing state')
costs = {'read_work_units': 0, 'write_attempts': 0}
if writing:
self._write_attempts += 1
costs['write_attempts'] = 1
if result['status'] != 'success':
self._state.restore(before_entities)
self.provisional_intents = before_intents
self.observed_waitlist_entries = observed_waitlist_before
else:
cost = self._read_cost(name, result)
remaining = 9 - self._read_units
if cost > remaining:
result = fn__error('READ_BUDGET_EXHAUSTED', 'this read exceeds the remaining allowance', required_units=cost, available_units=remaining)
self.observed_profiles = before_observed_profiles
self.observed_provisional_intents = before_observed_intents
self.observed_waitlist_entries = observed_waitlist_before
cost = remaining
self._read_units += cost
costs['read_work_units'] = cost
self._calls += 1
if isinstance(result.get('data'), dict):
result['data'].pop('policy_version', None)
result['budget'] = self._budget()
self._record_event(name, actor_user_id, result, before_hash, self.business_hash(), costs)
return ext_deepcopy(result)
def _search(self, args):
courses = {row['course_id']: row for row in self._state.list_entities('course')}
rows = []
for section in self._state.list_entities('course_section'):
course = courses[section['course_id']]
if section['term_id'] != args['term_id']:
continue
if args.get('keyword') and args['keyword'].lower() not in (course['course_code'] + ' ' + course['title']).lower():
continue
if any((args.get(arg) and section.get(field) != args[arg] for (arg, field) in (('delivery_mode', 'delivery_mode'), ('status_filter', 'status'), ('campus_location', 'campus_location')))):
continue
if args.get('department_id') and course['department_id'] != args['department_id']:
continue
if args.get('day_filter') and args['day_filter'] not in section['meeting_days']:
continue
if args.get('only_with_open_seats') and section['available_seats'] <= 0:
continue
rows.append({key: ext_deepcopy(section[key]) for key in ('section_id', 'course_id', 'term_id', 'campus_location', 'delivery_mode', 'meeting_days', 'available_seats', 'seat_capacity', 'status')})
rows[-1].update(course_code=course['course_code'], title=course['title'])
rows.sort(key=lambda row: (row['course_code'], row['section_id']))
(offset, limit) = (args.get('offset', 0), args.get('limit', 4))
return fn__success({'total_count': len(rows), 'sections': rows[offset:offset + limit], 'identity_scope': 'section IDs remain valid across request batches; availability is live'})
def grade(self, task_id=None):
grade = self._course_registration_stream_adapter_grade(task_id)
for (target, row) in zip(self._task_targets, grade['deliverables']):
queued = any((entry['student_id'] == target['student_id'] and entry['section_id'] == target['section_id'] and (entry['status'] == 'waiting') for entry in self._state.list_entities('waitlist_entry')))
row['queue_custody'] = queued
if not row['complete']:
row['score'] = 5.0 if queued else 0.0
grade['score'] = sum((row['score'] for row in grade['deliverables']))
return grade
def _budget(self):
return {'read_work_units_used': self._read_units, 'calls_remaining': max(0, 32 - self._calls), 'read_work_units_remaining': max(0, 9 - self._read_units), 'write_attempts_used': self._write_attempts, 'write_attempts_remaining': max(0, 7 - self._write_attempts)}
def _apply_stream_drift(self):
before = self.business_hash()
if 'course-registration-routing-control-v3' in self.applied_boundary_events:
return {'event_id': 'evt-' + fn__digest('course-registration-routing-control-v3')[:20], 'applied_now': False, 'duplicate_noop': before == self.business_hash(), 'before_sha256': before, 'after_sha256': self.business_hash(), 'event_sequence': self.drift_event_sequence}
self.orchestration_changed = True
self.applied_boundary_events.add('course-registration-routing-control-v3')
self.drift_event_sequence += 1
return {'event_id': 'evt-' + fn__digest('course-registration-routing-control-v3')[:20], 'applied_now': True, 'duplicate_noop': False, 'before_sha256': before, 'after_sha256': self.business_hash(), 'event_sequence': self.drift_event_sequence}
def _active_target(self, student_id, section_id):
return next((row for row in self._task_targets if row['student_id'] == student_id and row['section_id'] == section_id), None)
def _register(self, arguments):
target = self._active_target(arguments['student_id'], arguments['section_id'])
if target and self.orchestration_changed and (target['operation_atom'] in DATA_CHANGED_OPERATION_ATOMS):
return fn__error('DIRECT_PLACEMENT_NOT_ACCEPTED', 'the requested placement was not accepted by current registration processing')
return self._course_registration_stream_adapter_register(arguments)
def _waitlist(self, arguments):
target = self._active_target(arguments['student_id'], arguments['section_id'])
if not target or target['operation_atom'] not in DATA_CHANGED_OPERATION_ATOMS:
return self._course_registration_adapter_waitlist(arguments)
(student, section, course, error) = self._basic_eligibility_error(arguments['student_id'], arguments['section_id'], check_wait_duplicate=True)
if error:
return error
assert student and section and course
error = self._successor_eligibility_error(student, section, course, None)
if error:
return error
entry_id = 'waitlist-orch-' + fn__digest([self._task_id, arguments])[:18]
waiting = [row for row in self._state.list_entities('waitlist_entry') if row.get('section_id') == section['section_id'] and row.get('status') == 'waiting']
self._state.add_entity('waitlist_entry', {'waitlist_entry_id': entry_id, 'student_id': student['student_id'], 'section_id': section['section_id'], 'course_id': course['course_id'], 'term_id': section['term_id'], 'status': 'waiting', 'position_number': len(waiting) + 1, 'joined_at': '2026-05-27T12:00:00Z', 'promoted_at': None, 'removed_at': None, 'removal_reason': 'none', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}, 'waitlist_entry_id')
self._state.update_entity('course_section', section['section_id'], {'waitlist_count': len(waiting) + 1, 'updated_at': '2026-05-27T12:00:00Z'}, 'section_id')
return fn__success({'waitlist_entry_id': entry_id, 'status': 'waiting'})
def _promote(self, arguments):
if arguments['waitlist_entry_id'] not in self.observed_waitlist_entries:
return fn__error('QUEUE_OBSERVATION_REQUIRED', 'the current queue state must be observed before promotion')
return self._course_registration_adapter_promote(arguments)
def semantic_hash(self, snapshot=None):
return fn__digest_2(snapshot if snapshot is not None else self.snapshot())
def business_hash(self):
return fn__digest_2(self.business_state())
def public_snapshot(self):
packet = fn_public_task(self._task_id) if self._task_id in DATA_STREAM_TARGETS else None
return {'schema': 'rescopebench-course-registration-public-snapshot/v1', 'active_event_id': packet['event_id'] if packet else None, 'active_target_ids': [row['target_id'] for row in packet['targets']] if packet else [], 'budget': self._budget()}
def task_targets(self):
if self._task_id not in DATA_STREAM_TARGETS:
raise RuntimeError('no stream task is active')
return ext_deepcopy(self._task_targets)
def activate_task(self, task_id):
try:
fixture = fn_fixture_for_task(task_id)
except ValueError:
return fn__error('TASK_NOT_EXECUTABLE', 'task has no compiled fixture')
self._state = MemoryState(fixture['entities'])
self._task_id = task_id
self._task_targets = ext_deepcopy(fixture['targets'])
self._entry_entities = self._state.list_snapshot()
self._audit = ext_deepcopy(fixture.get('audit') or {})
self._events = []
self._calls = 0
self._read_units = 0
self._write_attempts = 0
self._assert_state_invariants()
return fn__success({'task_id': task_id})
def public_tool_schemas(self, role):
return ext_deepcopy(DATA_TOOLS_2) if role == 'registration_operator' else []
def business_events(self, since=0):
if not isinstance(since, int) or isinstance(since, bool) or since < 0:
raise ValueError('since must be a non-negative integer')
return ext_deepcopy(self._events[since:])
def audit_handles(self):
return ext_deepcopy(self._audit)
def _actor_allowed(self, actor_user_id):
return actor_user_id == 'operator-course-registration-dev'
def _business_hash(self):
return fn__canonical_hash(self._state.list_snapshot())
@staticmethod
def _page(rows, offset, limit):
return (len(rows), rows[offset:offset + limit])
@staticmethod
def _normalize_arguments(name, arguments):
value = ext_deepcopy(arguments)
if name in {'list_departments', 'list_students', 'list_courses', 'search_course_sections', 'list_student_registrations', 'get_waitlist_snapshot'}:
value.setdefault('limit', 4)
value.setdefault('offset', 0)
if name == 'search_course_sections':
value.setdefault('only_with_open_seats', False)
if name == 'list_student_registrations':
value.setdefault('include_waitlist_context', False)
if name == 'cancel_student_registration':
value.setdefault('drop_reason', 'student_request')
return value
@staticmethod
def _normalize_raw(result):
if not isinstance(result, dict):
return fn__error('RAW_RESPONSE_INVALID', 'raw operation returned an invalid response')
normalized = ext_deepcopy(result)
if normalized.get('status') not in {'success', 'error'}:
return fn__error('RAW_RESPONSE_INVALID', 'raw operation returned an invalid status')
data = normalized.get('data')
normalized['data'] = data if isinstance(data, dict) else {}
normalized['message'] = str(normalized.get('message') or '')
if normalized['status'] == 'error' and (not normalized['data'].get('error_code')):
(prefix, separator, detail) = normalized['message'].partition(':')
code = prefix.strip()
if separator and code and code.replace('_', '').isalnum():
normalized['data']['error_code'] = code
normalized['message'] = detail.strip()
else:
normalized['data']['error_code'] = 'RAW_OPERATION_REJECTED'
return normalized
def _list_departments(self, arguments):
rows = self._state.list_entities('department')
if arguments.get('code'):
needle = arguments['code'].strip().lower()
rows = [row for row in rows if str(row.get('code') or '').strip().lower() == needle]
if arguments.get('name_contains'):
needle = arguments['name_contains'].strip().lower()
rows = [row for row in rows if needle in str(row.get('name') or '').strip().lower()]
rows.sort(key=lambda row: (row.get('code', ''), row['department_id']))
(total, page) = self._page(rows, arguments['offset'], arguments['limit'])
return fn__success({'total_count': total, 'departments': [{'department_id': row['department_id'], 'code': row.get('code'), 'name': row.get('name'), 'school_name': row.get('school_name')} for row in page]})
def _list_students(self, arguments):
rows = self._state.list_entities('student')
if arguments.get('university_id'):
needle = arguments['university_id'].strip().lower()
rows = [row for row in rows if str(row.get('university_id') or '').strip().lower() == needle]
if arguments.get('full_name_contains'):
needle = arguments['full_name_contains'].strip().lower()
rows = [row for row in rows if needle in str(row.get('full_name') or '').strip().lower()]
if arguments.get('academic_level'):
rows = [row for row in rows if row.get('academic_level') == arguments['academic_level']]
if arguments.get('enrollment_status'):
rows = [row for row in rows if row.get('enrollment_status') == arguments['enrollment_status']]
active_holds = {row['student_id'] for row in self._state.list_entities('advising_hold') if row.get('status') == 'active' and row.get('prevents_registration') is True}
rows.sort(key=lambda row: (row.get('full_name', ''), row['student_id']))
(total, page) = self._page(rows, arguments['offset'], arguments['limit'])
return fn__success({'total_count': total, 'students': [{'student_id': row['student_id'], 'university_id': row.get('university_id'), 'full_name': row.get('full_name'), 'academic_level': row.get('academic_level'), 'class_year': row.get('class_year'), 'enrollment_status': row.get('enrollment_status'), 'major_department_id': row.get('major_department_id'), 'has_active_hold': row['student_id'] in active_holds} for row in page]})
def _list_courses(self, arguments):
rows = self._state.list_entities('course')
if arguments.get('department_id'):
rows = [row for row in rows if row.get('department_id') == arguments['department_id']]
if arguments.get('course_code'):
needle = arguments['course_code'].strip().lower()
rows = [row for row in rows if str(row.get('course_code') or '').strip().lower() == needle]
if arguments.get('level'):
rows = [row for row in rows if row.get('level') == arguments['level']]
lower = arguments.get('credits_min', 1)
upper = arguments.get('credits_max', 5)
if lower > upper:
return fn__error('INVALID_CREDIT_WINDOW', 'credits_min must be less than or equal to credits_max')
rows = [row for row in rows if lower <= int(row.get('credits') or 0) <= upper]
if 'has_prerequisites' in arguments:
rows = [row for row in rows if bool(row.get('prerequisite_course_ids')) is arguments['has_prerequisites']]
rows.sort(key=lambda row: (row.get('course_code', ''), row['course_id']))
(total, page) = self._page(rows, arguments['offset'], arguments['limit'])
return fn__success({'total_count': total, 'courses': page})
@staticmethod
def _read_cost(name, result):
if result.get('status') != 'success':
return 1
if name == 'get_registration_policy':
return 4
data = result.get('data') or {}
row_fields = {'list_departments': 'departments', 'list_students': 'students', 'list_courses': 'courses', 'search_course_sections': 'sections', 'list_student_registrations': 'registrations', 'get_waitlist_snapshot': 'entries'}
if name in row_fields:
return max(1, int(data.get('total_count') or 0), len(data.get(row_fields[name]) or []))
return 1
def _policy(self, student_id, section_id):
return next((row for row in self._state.list_entities('registration_policy') if row.get('student_id') == student_id and row.get('section_id') == section_id), None)
def _active_registrations(self, student_id, term_id):
return [row for row in self._state.list_entities('registration') if row.get('student_id') == student_id and row.get('term_id') == term_id and (row.get('status') == 'registered')]
@staticmethod
def _time_minutes(value):
(hour, minute) = str(value).split(':', 1)
return int(hour) * 60 + int(minute)
def _meeting_conflict(self, student_id, section):
requested_days = set(section.get('meeting_days') or [])
requested_start = self._time_minutes(section.get('meeting_start_time'))
requested_end = self._time_minutes(section.get('meeting_end_time'))
for registration in self._active_registrations(student_id, section['term_id']):
other = self._state.get_entity('course_section', registration['section_id'], 'section_id')
if not other or not requested_days.intersection(other.get('meeting_days') or []):
continue
other_start = self._time_minutes(other.get('meeting_start_time'))
other_end = self._time_minutes(other.get('meeting_end_time'))
if requested_start < other_end and other_start < requested_end:
return registration
return None
def _active_credit_total(self, student_id, term_id):
courses = {row['course_id']: row for row in self._state.list_entities('course')}
return sum((int((courses.get(row.get('course_id')) or {}).get('credits') or 0) for row in self._active_registrations(student_id, term_id)))
def _basic_eligibility_error(self, student_id, section_id, *, check_wait_duplicate):
student = self._state.get_entity('student', student_id, 'student_id')
if not student:
return (None, None, None, fn__error('STUDENT_NOT_FOUND', 'student does not exist'))
section = self._state.get_entity('course_section', section_id, 'section_id')
if not section:
return (student, None, None, fn__error('SECTION_NOT_FOUND', 'section does not exist'))
course = self._state.get_entity('course', section['course_id'], 'course_id')
if not course:
return (student, section, None, fn__error('COURSE_NOT_FOUND', 'section course does not exist'))
if student.get('enrollment_status') == 'leave':
return (student, section, course, fn__error('STUDENT_NOT_ELIGIBLE', 'student enrollment status is leave'))
if section.get('status') == 'cancelled':
return (student, section, course, fn__error('SECTION_CANCELLED', 'section is cancelled'))
if not str(section.get('registration_open_at')) <= '2026-05-27T12:00:00Z' <= str(section.get('registration_close_at')):
return (student, section, course, fn__error('REGISTRATION_CLOSED', 'section registration window is closed'))
active_hold = any((row.get('student_id') == student_id and row.get('term_id') == section.get('term_id') and (row.get('status') == 'active') and (row.get('prevents_registration') is True) for row in self._state.list_entities('advising_hold')))
if active_hold:
return (student, section, course, fn__error('ADVISING_HOLD_ACTIVE', 'student has an active registration hold'))
active_registrations = self._active_registrations(student_id, section['term_id'])
if any((row.get('section_id') == section_id for row in active_registrations)):
return (student, section, course, fn__error('DUPLICATE_REGISTRATION', 'student already has an active registration'))
if check_wait_duplicate and any((row.get('student_id') == student_id and row.get('section_id') == section_id and (row.get('status') == 'waiting') for row in self._state.list_entities('waitlist_entry'))):
return (student, section, course, fn__error('DUPLICATE_WAITLIST_ENTRY', 'student already has an active waitlist entry'))
completed = set(student.get('completed_course_ids') or [])
if any((course_id not in completed for course_id in course.get('prerequisite_course_ids') or [])):
return (student, section, course, fn__error('PREREQUISITE_NOT_MET', 'student has not completed every prerequisite'))
return (student, section, course, None)
def _successor_eligibility_error(self, student, section, course, grading_basis):
if course.get('level') == 'graduate' and student.get('academic_level') != 'graduate':
return fn__error('ACADEMIC_LEVEL_MISMATCH', 'student academic level does not permit the course level')
current_credits = self._active_credit_total(student['student_id'], section['term_id'])
requested_credits = int(course.get('credits') or 0)
credit_limit = int(student.get('credit_limit') or 0)
if current_credits + requested_credits > credit_limit:
return fn__error('CREDIT_LIMIT_EXCEEDED', 'registration would exceed the student credit limit', current_credits=current_credits, requested_credits=requested_credits, credit_limit=credit_limit)
conflict = self._meeting_conflict(student['student_id'], section)
if conflict:
return fn__error('MEETING_TIME_CONFLICT', 'section overlaps an active registration', conflicting_registration_id=conflict['registration_id'])
if grading_basis is not None:
policy = self._policy(student['student_id'], section['section_id'])
if not policy:
return fn__error('REGISTRATION_POLICY_NOT_FOUND', 'no current registration policy matches the student and section')
if grading_basis != policy.get('required_grading_basis'):
return fn__error('GRADING_BASIS_POLICY_MISMATCH', 'grading basis does not match the current registration policy', policy_version=policy.get('policy_version'))
return None
def _change_basis(self, arguments):
registration = self._state.get_entity('registration', arguments['registration_id'], 'registration_id')
if not registration:
return fn__error('REGISTRATION_NOT_FOUND', 'registration does not exist')
if registration.get('status') != 'registered':
return fn__error('REGISTRATION_NOT_ACTIVE', 'registration is not active')
policy = self._policy(registration['student_id'], registration['section_id'])
if not policy:
return fn__error('REGISTRATION_POLICY_NOT_FOUND', 'no current registration policy matches the registration')
if arguments['grading_basis'] != policy.get('required_grading_basis'):
return fn__error('GRADING_BASIS_POLICY_MISMATCH', 'grading basis does not match the current registration policy', policy_version=policy.get('policy_version'))
return self._normalize_raw(self._impl['change_registration_grading_basis'](self._state, **ext_deepcopy(arguments)))
def _record_event(self, name, actor_user_id, result, before_hash, after_hash, cost):
self._events.append({'sequence': len(self._events) + 1, 'channel': 'learner', 'tool': name, 'actor_user_id': actor_user_id, 'status': result.get('status'), 'error_code': result.get('data', {}).get('error_code'), 'cost': ext_deepcopy(cost), 'budget_after': self._budget(), 'state_hash_before': before_hash, 'state_hash_after': after_hash})
def _assert_state_invariants(self):
entities = self._state.list_snapshot()
students = {row['student_id']: row for row in entities['student']}
courses = {row['course_id']: row for row in entities['course']}
sections = {row['section_id']: row for row in entities['course_section']}
terms = {row['term_id'] for row in entities['term']}
active_by_student_term: dict[tuple[str, str], list[dict[str, ext_Any]]] = {}
active_pairs: set[tuple[str, str]] = set()
active_by_section: dict[str, int] = {}
for registration in entities['registration']:
student = students.get(registration.get('student_id'))
section = sections.get(registration.get('section_id'))
course = courses.get(registration.get('course_id'))
if not student or not section or (not course):
raise ValueError('registration references missing business state')
if registration.get('term_id') not in terms:
raise ValueError('registration references a missing term')
if section.get('course_id') != registration.get('course_id') or section.get('term_id') != registration.get('term_id'):
raise ValueError('registration binding diverged from its section')
if registration.get('status') != 'registered':
continue
pair = (registration['student_id'], registration['section_id'])
if pair in active_pairs:
raise ValueError('duplicate active registration')
active_pairs.add(pair)
active_by_section[registration['section_id']] = active_by_section.get(registration['section_id'], 0) + 1
active_by_student_term.setdefault((registration['student_id'], registration['term_id']), []).append(registration)
if course.get('level') == 'graduate' and student.get('academic_level') != 'graduate':
raise ValueError('active registration violates academic level')
for ((student_id, _term_id), registrations) in active_by_student_term.items():
student = students[student_id]
credits = sum((int(courses[row['course_id']].get('credits') or 0) for row in registrations))
if credits > int(student.get('credit_limit') or 0):
raise ValueError('active registration credits exceed the limit')
for (index, left) in enumerate(registrations):
left_section = sections[left['section_id']]
left_days = set(left_section.get('meeting_days') or [])
left_start = self._time_minutes(left_section['meeting_start_time'])
left_end = self._time_minutes(left_section['meeting_end_time'])
for right in registrations[index + 1:]:
right_section = sections[right['section_id']]
if not left_days.intersection(right_section.get('meeting_days') or []):
continue
right_start = self._time_minutes(right_section['meeting_start_time'])
right_end = self._time_minutes(right_section['meeting_end_time'])
if left_start < right_end and right_start < left_end:
raise ValueError('active registration schedules overlap')
waiting_pairs: set[tuple[str, str]] = set()
waiting_by_section: dict[str, list[dict[str, ext_Any]]] = {}
for entry in entities['waitlist_entry']:
section = sections.get(entry.get('section_id'))
if entry.get('student_id') not in students or not section or entry.get('course_id') not in courses or (entry.get('term_id') not in terms):
raise ValueError('waitlist entry references missing business state')
if section.get('course_id') != entry.get('course_id') or section.get('term_id') != entry.get('term_id'):
raise ValueError('waitlist binding diverged from its section')
if entry.get('status') != 'waiting':
continue
pair = (entry['student_id'], entry['section_id'])
if pair in waiting_pairs or pair in active_pairs:
raise ValueError('active queue custody is duplicated')
waiting_pairs.add(pair)
waiting_by_section.setdefault(entry['section_id'], []).append(entry)
for (section_id, section) in sections.items():
enrolled = active_by_section.get(section_id, 0)
waiting = sorted(waiting_by_section.get(section_id, []), key=lambda row: int(row.get('position_number') or 999999))
capacity = int(section.get('seat_capacity') or 0)
wait_capacity = int(section.get('waitlist_capacity') or 0)
if enrolled > capacity or len(waiting) > wait_capacity:
raise ValueError('section capacity is exceeded')
if int(section.get('enrolled_count') or 0) != enrolled:
raise ValueError('section enrollment counter diverged')
if int(section.get('available_seats') or 0) != capacity - enrolled:
raise ValueError('section available-seat counter diverged')
if int(section.get('waitlist_count') or 0) != len(waiting):
raise ValueError('section waitlist counter diverged')
positions = [int(row.get('position_number') or 0) for row in waiting]
if positions != list(range(1, len(waiting) + 1)):
raise ValueError('waiting queue positions are not contiguous')
if section.get('status') != 'cancelled':
expected_status = 'open' if capacity - enrolled > 0 else 'waitlist_only' if section.get('allow_waitlist_promotion') is True and len(waiting) < wait_capacity else 'closed'
if section.get('status') != expected_status:
raise ValueError('section status diverged from capacity')
for hold in entities['advising_hold']:
if hold.get('student_id') not in students or hold.get('term_id') not in terms:
raise ValueError('advising hold references missing business state')
for policy in entities['registration_policy']:
if policy.get('student_id') not in students or policy.get('section_id') not in sections or policy.get('required_grading_basis') not in DATA_BASIS_VALUES:
raise ValueError('registration policy references invalid state')
def _course_scope_world_snapshot(self):
value = self._course_evolution_snapshot()
value['evolution_contract']['case_version'] = 'course-policy-scope-evolution-v2'
return value
def _course_scope_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.get('evolution_contract', {}).get('case_version') != 'course-policy-scope-evolution-v2':
raise ValueError('Course policy-scope snapshot version differs')
value['evolution_contract']['case_version'] = 'course-lifecycle-evolution-v1'
self._course_evolution_restore(value)
def _course_registration_get_registration_policy(self, args):
before = ext_deepcopy(self.processing_revalidation)
result = self._course_registration_get_registration_policy_2(args)
if result.get('status') != 'success' or self._read_units + self._read_cost('get_registration_policy', result) > 9:
self.processing_revalidation = before
return result
def _course_registration_prepare_episode(self, task_id, *, evaluator_apply_scheduled_drift=None):
receipt = self._course_registration_prepare_episode_2(task_id, evaluator_apply_scheduled_drift=evaluator_apply_scheduled_drift)
self._task_targets = ext_deepcopy(DATA_TARGETS_2[task_id])
self.active_student_ids = {target['student_id'] for target in self._task_targets}
self.active_section_ids = {section_id for target in self._task_targets for section_id in target['candidate_section_ids']}
self._entry_entities = self._state.list_snapshot()
return receipt
def _course_registration_write(self, name, args):
target = self._write_target(name, args)
if target is None:
return fn__error('RECORD_OUTSIDE_ACTIVE_REQUEST', 'mutation is outside the active request scope')
priority = self._priority_error(target, name)
if priority is not None:
return priority
if name in {'register_student_in_section', 'approve_waitlist_promotion', 'change_registration_grading_basis'}:
expected = DATA_POLICY_SCOPES[target['policy_scope']]['policy_reference']
if args.get('policy_reference') != expected:
return fn__error('POLICY_REFERENCE_MISMATCH', 'the policy reference does not apply to this section')
cell = fn_processing_cell(target)
changed = self.orchestration_changed and cell in DATA_CHANGED_PROCESSING_CELLS
route = self._route(target)
supplied_profile = args.get('processing_profile_id')
current_profile = self._profile_matches_current(target, supplied_profile)
raw_args = {key: value for (key, value) in args.items() if key not in {'policy_reference', 'processing_profile_id'}}
if name == 'register_student_in_section':
final_basis = DATA_POLICY_SCOPES[target['policy_scope']]['required_grading_basis']
if changed and (not current_profile):
if raw_args.get('grading_basis') == final_basis and self._profile_matches_pre(target, supplied_profile):
if self.processing_revalidation.get(cell) == 'awaiting_exact_stale':
self.processing_revalidation[cell] = 'awaiting_fresh_policy'
return fn__error('DIRECT_PLACEMENT_NOT_ACCEPTED', 'current processing did not accept the placement')
return fn__error('PROCESSING_PROFILE_MISMATCH', 'the supplied processing evidence is not current for this request')
if changed and route == 'queue_observed_promotion':
return fn__error('DIRECT_PLACEMENT_NOT_ACCEPTED', 'current processing did not accept a direct placement')
if changed and route == 'reviewed_provisional_finalize':
intake = DATA_CHANGED_PROCESSING_CELLS[cell]['intake_grading_basis']
if raw_args.get('grading_basis') != intake:
return fn__error('PROVISIONAL_BASIS_REQUIRED', 'the reviewed intake basis is required before finalization')
return self._provisional(target, intake)
if changed and route == 'reviewed_direct':
if target['student_id'] not in self.observed_profiles:
return fn__error('CURRENT_PROFILE_REVIEW_REQUIRED', 'current enrollment context must be reviewed before placement')
result = World._course_registration_stream_adapter_register(self, raw_args)
if result.get('status') == 'success':
self.processing_revalidation[cell] = 'validated'
return result
if not changed and route == 'queue_observed_promotion':
return fn__error('DIRECT_PLACEMENT_NOT_ACCEPTED', 'current processing did not accept a direct placement')
result = World._course_registration_stream_adapter_register(self, raw_args)
if result.get('status') == 'success':
result['data']['processing_profile_id'] = fn__candidate(target, 'pre')['processing_profile_id']
result['data']['processing_evidence_scope'] = 'exact active student-section request'
return result
if name == 'add_student_to_waitlist':
if changed:
if route != 'queue_observed_promotion' or not current_profile:
return fn__error('PROCESSING_PROFILE_MISMATCH', 'current processing evidence does not admit this queue path')
elif route != 'queue_observed_promotion':
return fn__error('QUEUED_PLACEMENT_NOT_ACCEPTED', 'current processing did not accept the queued placement')
if self._budget()['read_work_units_remaining'] < 1 or self._budget()['write_attempts_remaining'] < 2:
return fn__error('INSUFFICIENT_CLOSURE_RESERVE', 'remaining work cannot observe and promote a new queue entry')
return self._queue(target)
if name == 'approve_waitlist_promotion':
if changed and (route != 'queue_observed_promotion' or not current_profile):
return fn__error('PROCESSING_PROFILE_MISMATCH', 'current processing evidence does not admit this promotion')
result = World._promote(self, raw_args)
if result.get('status') == 'success' and changed:
self.processing_revalidation[cell] = 'validated'
return result
if name == 'change_registration_grading_basis':
if args['registration_id'] in self.provisional_intents:
if not changed or route != 'reviewed_provisional_finalize' or (not current_profile):
return fn__error('PROCESSING_PROFILE_MISMATCH', 'current processing evidence does not admit finalization')
return self._finalize_provisional(target, raw_args)
return World._course_registration_adapter_write(self, name, raw_args)
return World._course_registration_adapter_write(self, name, raw_args)
def _course_registration_init(self, source_root=CASE_DIR / 'raw', snapshot=None):
self._course_registration_orchestration_successor_init(source_root, snapshot=None)
self._state = MemoryState(ext_deepcopy(DATA_ENTITIES_2))
if snapshot is not None:
self.restore(snapshot)
def _course_registration_stream_adapter_business_state(self):
return {'entities': self._state.list_snapshot(), 'applied_boundary_events': sorted(self.applied_boundary_events)}
def _course_registration_read(self, name, args):
if name == 'search_course_sections':
return self._search(args)
if name == 'list_students':
rows = [row for row in self._state.list_entities('student') if row['student_id'] in self.active_student_ids]
if args.get('university_id'):
rows = [row for row in rows if row['university_id'].lower() == args['university_id'].lower()]
if args.get('full_name_contains'):
rows = [row for row in rows if args['full_name_contains'].lower() in row['full_name'].lower()]
for field in ('academic_level', 'enrollment_status'):
if args.get(field):
rows = [row for row in rows if row[field] == args[field]]
rows.sort(key=lambda row: (row['full_name'], row['student_id']))
(offset, limit) = (args.get('offset', 0), args.get('limit', 4))
fields = ('student_id', 'university_id', 'full_name', 'academic_level', 'class_year', 'enrollment_status', 'major_department_id')
return fn__success({'total_count': len(rows), 'students': [{field: row[field] for field in fields} for row in rows[offset:offset + limit]], 'identity_scope': 'student identity is request-scoped'})
if name in {'get_student_profile', 'list_student_registrations'} and args['student_id'] not in self.active_student_ids:
return fn__error('STUDENT_OUTSIDE_ACTIVE_REQUEST', 'student is outside the active request scope')
return self._course_registration_orchestration_successor_read(name, args)
def _course_registration_write_target(self, name, args):
if 'student_id' in args and 'section_id' in args:
return self._target(args['student_id'], args['section_id'])
(entity, key) = ('waitlist_entry', 'waitlist_entry_id') if 'waitlist_entry_id' in args else ('registration', 'registration_id')
row = self._state.get_entity(entity, args.get(key), key)
return self._target(row['student_id'], row['section_id']) if row else None
def _course_registration_stream_adapter_register(self, arguments):
allowed = {(target['student_id'], target['section_id']) for target in self._task_targets}
if (arguments.get('student_id'), arguments.get('section_id')) not in allowed:
return fn__error('REGISTRATION_TARGET_NOT_ACTIVE', 'student-section pair is not in the current request scope')
return self._course_registration_adapter_register(arguments)
def _course_registration_stream_adapter_grade(self, task_id=None):
return self._course_registration_adapter_grade(task_id or str(self._task_id))
def _course_registration_adapter_waitlist(self, arguments):
(student, section, course, error) = self._basic_eligibility_error(arguments['student_id'], arguments['section_id'], check_wait_duplicate=True)
if error:
return error
assert student and section and course
error = self._successor_eligibility_error(student, section, course, None)
if error:
return error
return self._normalize_raw(self._impl['add_student_to_waitlist'](self._state, **ext_deepcopy(arguments)))
def _course_registration_adapter_promote(self, arguments):
entry = self._state.get_entity('waitlist_entry', arguments['waitlist_entry_id'], 'waitlist_entry_id')
if not entry:
return fn__error('WAITLIST_ENTRY_NOT_FOUND', 'waitlist entry does not exist')
if entry.get('status') != 'waiting':
return fn__error('WAITLIST_ENTRY_NOT_WAITING', 'waitlist entry is not waiting')
waiting = sorted((row for row in self._state.list_entities('waitlist_entry') if row.get('section_id') == entry['section_id'] and row.get('status') == 'waiting'), key=lambda row: (int(row.get('position_number') or 999999), row.get('joined_at') or '', row['waitlist_entry_id']))
if not waiting or waiting[0]['waitlist_entry_id'] != entry['waitlist_entry_id']:
return fn__error('WAITLIST_ORDER_VIOLATION', 'only the current queue head can be promoted')
(student, section, course, error) = self._basic_eligibility_error(entry['student_id'], entry['section_id'], check_wait_duplicate=False)
if error:
return error
assert student and section and course
error = self._successor_eligibility_error(student, section, course, arguments['grading_basis'])
if error:
return error
return self._normalize_raw(self._impl['approve_waitlist_promotion'](self._state, **ext_deepcopy(arguments)))
def _course_evolution_snapshot(self):
value = self._course_registration_snapshot()
value['evolution_contract'] = {'case_version': 'course-lifecycle-evolution-v1', 'schedule': ext_deepcopy(DATA_SCHEDULE_2), 'targets_sha256': fn_digest(DATA_TARGETS)}
return value
def _course_evolution_restore(self, snapshot):
value = ext_deepcopy(snapshot)
expected = {'case_version': 'course-lifecycle-evolution-v1', 'schedule': DATA_SCHEDULE_2, 'targets_sha256': fn_digest(DATA_TARGETS)}
if value.pop('evolution_contract', None) != expected:
raise ValueError('Course evolution contract differs')
self._course_registration_restore(value)
def _course_registration_get_registration_policy_2(self, args):
result = World._course_registration_get_registration_policy_3(self, args)
if result.get('status') != 'success':
return result
target = self._target(args['student_id'], args['section_id'])
if target is None:
return result
cell = fn_processing_cell(target)
pre = fn_pre_candidate(target)
state = self.processing_revalidation.get(cell)
if not self.orchestration_changed or cell not in DATA_CHANGED_PROCESSING_CELLS_2:
evidence = [pre]
elif state == 'awaiting_fresh_policy':
if self._read_units + 4 <= 9:
evidence = [{**pre, 'observed_outcome': 'not_accepted_for_current_request'}, {**fn_current_candidate(target), 'observed_outcome': 'current_candidate'}]
self.processing_revalidation[cell] = 'ready_current'
else:
evidence = [pre]
else:
evidence = [{**fn_current_candidate(target), 'observed_outcome': 'current_candidate'}]
if state == 'awaiting_exact_stale':
self.processing_revalidation[cell] = 'ready_current'
result['data']['processing_evidence'] = evidence
result['data']['policy_reference_scope'] = 'all active students requesting this section in this term'
result['data']['processing_evidence_scope'] = fn__reusable_scope(result['data'])
return result
def _course_registration_prepare_episode_2(self, task_id, *, evaluator_apply_scheduled_drift=None):
receipt = self._course_registration_prepare_episode_3(task_id, evaluator_apply_scheduled_drift=evaluator_apply_scheduled_drift)
self._task_targets = ext_deepcopy(DATA_TARGETS_3[task_id])
self.active_student_ids = {target['student_id'] for target in self._task_targets}
self.active_section_ids = {section_id for target in self._task_targets for section_id in target['candidate_section_ids']}
self._entry_entities = self._state.list_snapshot()
return receipt
def _course_registration_adapter_write(self, name, arguments):
if name == 'register_student_in_section':
return self._register(arguments)
if name == 'add_student_to_waitlist':
return self._waitlist(arguments)
if name == 'approve_waitlist_promotion':
return self._promote(arguments)
if name == 'change_registration_grading_basis':
return self._change_basis(arguments)
return self._normalize_raw(self._impl[name](self._state, **arguments))
def _course_registration_orchestration_successor_init(self, source_root=CASE_DIR / 'raw', snapshot=None):
self._course_registration_stream_adapter_init(source_root=source_root, snapshot=None)
self._impl = fn__load_isolated_raw_tools(source_root)
self._state.restore(ext_deepcopy(DATA_STREAM_ENTITIES))
self.orchestration_changed = False
self.observed_waitlist_entries: set[str] = set()
if snapshot is not None:
self.restore(snapshot)
def _course_registration_orchestration_successor_read(self, name, arguments):
result = self._course_registration_adapter_read(name, arguments)
if name == 'get_waitlist_snapshot' and result.get('status') == 'success':
self.observed_waitlist_entries.update((row['waitlist_entry_id'] for row in (result.get('data') or {}).get('entries', [])))
return result
def _course_registration_adapter_register(self, arguments):
(student, section, course, error) = self._basic_eligibility_error(arguments['student_id'], arguments['section_id'], check_wait_duplicate=True)
if error:
return error
assert student and section and course
error = self._successor_eligibility_error(student, section, course, arguments['grading_basis'])
if error:
return error
return self._normalize_raw(self._impl['register_student_in_section'](self._state, **ext_deepcopy(arguments)))
def _course_registration_adapter_grade(self, task_id):
if task_id != self._task_id:
raise ValueError('task is not active')
entities = self._state.list_snapshot()
entry_ids = {row['registration_id'] for row in self._entry_entities.get('registration', [])}
integrity = True
try:
self._assert_state_invariants()
except ValueError:
integrity = False
deliverables: list[dict[str, ext_Any]] = []
completed = 0
for target in self._task_targets:
registrations = [row for row in entities['registration'] if row.get('registration_id') not in entry_ids and row.get('student_id') == target['student_id'] and (row.get('section_id') == target['section_id']) and (row.get('course_id') == target['course_id']) and (row.get('term_id') == 'term-2026-fall') and (row.get('status') == 'registered')]
target_resolved = len(registrations) == 1
transition_committed = target_resolved and registrations[0].get('grading_basis') == target['required_grading_basis']
eligibility_verified = transition_committed
invariants_hold = transition_committed and integrity
score = (2.5 if target_resolved else 0.0) + (5.0 if eligibility_verified else 0.0) + (7.5 if transition_committed else 0.0) + (10.0 if invariants_hold else 0.0)
complete = score == 25.0
if complete:
completed += 1
deliverables.append({'target_id': target['target_id'], 'score': score, 'complete': complete, 'target_resolved': target_resolved, 'eligibility_verified': eligibility_verified, 'transition_committed': transition_committed, 'seat_credit_invariants_hold': invariants_hold, 'registration_ids': [row['registration_id'] for row in registrations]})
target_pairs = {(row['student_id'], row['section_id']) for row in self._task_targets}
unrelated_new = [row['registration_id'] for row in entities['registration'] if row['registration_id'] not in entry_ids and (row.get('student_id'), row.get('section_id')) not in target_pairs]
return {'task_id': task_id, 'score': sum((row['score'] for row in deliverables)), 'completed_artifacts': completed, 'deliverables': deliverables, 'business_invariants_hold': integrity, 'unrelated_new_registration_ids': unrelated_new, 'budget': self._budget()}
def _course_registration_snapshot(self):
value = self._course_registration_snapshot_2()
value['schema'] = 'rescopebench-course-registration/v9'
value['v9_identity'] = fn_digest([DATA_TARGETS_2, DATA_PROVIDER_TOOLS])
return value
def _course_registration_restore(self, value):
if value.get('schema') != 'rescopebench-course-registration/v9' or value.get('v9_identity') != fn_digest([DATA_TARGETS_2, DATA_PROVIDER_TOOLS]):
raise ValueError('Course v9 snapshot identity mismatch')
parent = ext_deepcopy(value)
parent.pop('v9_identity')
parent['schema'] = 'rescopebench-course-registration/v8'
self._course_registration_restore_2(parent)
def _course_registration_get_registration_policy_3(self, args):
target = self._target(args['student_id'], args['section_id'])
if target is None:
return fn__error('REGISTRATION_POLICY_NOT_ACTIVE', 'policy is outside the active request scope')
scope = ext_deepcopy(DATA_POLICY_SCOPES[target['policy_scope']])
scope['student_id'] = args['student_id']
return fn__success(scope)
def _course_registration_prepare_episode_3(self, task_id, *, evaluator_apply_scheduled_drift=None):
if self._task_id == task_id:
return self._course_registration_prepare_episode_4(task_id, evaluator_apply_scheduled_drift=evaluator_apply_scheduled_drift)
expired = sorted(self.provisional_intents)
self.provisional_intents = {}
self.observed_profiles = set()
self.observed_provisional_intents = set()
receipt = self._course_registration_prepare_episode_4(task_id, evaluator_apply_scheduled_drift=evaluator_apply_scheduled_drift)
self._task_targets = ext_deepcopy(DATA_TARGETS_4[task_id])
self.active_student_ids = {target['student_id'] for target in self._task_targets}
self.active_section_ids = {section_id for target in self._task_targets for section_id in target['candidate_section_ids']}
self._entry_entities = self._state.list_snapshot()
if task_id == 'T09' and self.orchestration_changed:
for cell in DATA_CHANGED_PROCESSING_CELLS:
self.processing_revalidation.setdefault(cell, 'awaiting_exact_stale')
self.applied_boundary_events.discard('registration-processing-v6')
self.applied_boundary_events.add('registration-processing-cell-refresh-v7')
receipt['event_id'] = fn_event_id_2(task_id)
receipt['expired_processing_intents'] = expired
receipt['public_notice'] = 'A new registration request batch is active.'
if self.boundary_receipts:
self.boundary_receipts[-1] = ext_deepcopy(receipt)
return receipt
def _course_registration_stream_adapter_init(self, source_root=CASE_DIR / 'raw', snapshot=None):
self._course_registration_adapter_init(source_root)
self._state = MemoryState(ext_deepcopy(DATA_STREAM_ENTITIES))
self.prepared_tasks: list[str] = []
self.boundary_receipts: list[dict[str, ext_Any]] = []
self.applied_boundary_events: set[str] = set()
self.drift_event_sequence = 0
self.active_student_ids: set[str] = set()
self.active_section_ids: set[str] = set()
if snapshot is not None:
self.restore(snapshot)
def _course_registration_adapter_read(self, name, arguments):
if name == 'list_departments':
return self._list_departments(arguments)
if name == 'list_students':
return self._list_students(arguments)
if name == 'list_courses':
return self._list_courses(arguments)
if name == 'get_registration_policy':
return self._get_registration_policy(arguments)
raw_arguments = ext_deepcopy(arguments)
if name == 'search_course_sections':
raw_arguments.update({'sort_by': 'course_code', 'sort_direction': 'asc'})
result = self._impl[name](self._state, **raw_arguments)
return self._normalize_raw(result)
def _course_registration_snapshot_2(self):
value = self._course_registration_snapshot_3()
value['schema'] = 'rescopebench-course-registration/v8'
value['v8_identity'] = fn_digest([DATA_TARGETS_3, DATA_PROVIDER_TOOLS_2])
return value
def _course_registration_restore_2(self, value):
if value.get('schema') != 'rescopebench-course-registration/v8' or value.get('v8_identity') != fn_digest([DATA_TARGETS_3, DATA_PROVIDER_TOOLS_2]):
raise ValueError('Course v8 snapshot identity mismatch')
parent = ext_deepcopy(value)
parent.pop('v8_identity')
parent['schema'] = 'rescopebench-course-registration/v7'
self._course_registration_restore_3(parent)
def _course_registration_prepare_episode_4(self, task_id, *, evaluator_apply_scheduled_drift=None):
if self._task_id == task_id:
return {'event_id': fn_event_id_2(task_id), 'already_prepared': True, 'public_notice': 'A new registration request batch is active.'}
if len(self.prepared_tasks) >= 16 or task_id != DATA_TASK_IDS[len(self.prepared_tasks)]:
raise ValueError('request batches cannot be skipped or reordered')
before = self.business_hash()
closed = []
for entry in self._state.list_entities('waitlist_entry'):
if entry.get('status') == 'waiting':
entry_id = entry['waitlist_entry_id']
self._state.update_entity('waitlist_entry', entry_id, {'status': 'removed', 'removed_at': '2026-05-27T12:00:00Z', 'removal_reason': 'request_batch_closed'}, 'waitlist_entry_id')
section = self._state.get_entity('course_section', entry['section_id'], 'section_id')
self._state.update_entity('course_section', entry['section_id'], {'waitlist_count': section['waitlist_count'] - 1}, 'section_id')
closed.append(entry_id)
applied = False
if task_id == 'T09' and evaluator_apply_scheduled_drift is not False:
self.orchestration_changed = True
self.applied_boundary_events.add('registration-processing-v6')
self.drift_event_sequence += 1
applied = True
self._task_id = task_id
self._task_targets = ext_deepcopy(DATA_TARGETS_5[task_id])
self.active_student_ids = {target['student_id'] for target in self._task_targets}
self.active_section_ids = {sid for target in self._task_targets for sid in target['candidate_section_ids']}
self._entry_entities = self._state.list_snapshot()
(self._audit, self._events) = ({}, [])
self._calls = self._read_units = self._write_attempts = 0
self.observed_waitlist_entries = set()
self.prepared_tasks.append(task_id)
self._assert_state_invariants()
receipt = {'event_id': fn_event_id_2(task_id), 'before_sha256': before, 'after_sha256': self.business_hash(), 'expired_queue_entries': closed, 'drift_applied': applied, 'public_notice': 'A new registration request batch is active.'}
self.boundary_receipts.append(ext_deepcopy(receipt))
return receipt
def _course_registration_adapter_init(self, source_root=CASE_DIR / 'raw'):
self._impl = fn__load_raw_tools(str(ext_Path(source_root).resolve()))
self._state = MemoryState({name: [] for name in DATA_ENTITY_ID_FIELDS})
self._task_id: str | None = None
self._task_targets: list[dict[str, ext_Any]] = []
self._entry_entities: dict[str, list[dict[str, ext_Any]]] = {}
self._audit: dict[str, str] = {}
self._events: list[dict[str, ext_Any]] = []
self._calls = 0
self._read_units = 0
self._write_attempts = 0
def _course_registration_snapshot_3(self):
value = self._course_registration_snapshot_4()
value['schema'] = 'rescopebench-course-registration/v7'
value['v7_identity'] = fn_digest([DATA_TARGETS_4, DATA_PROVIDER_TOOLS_3])
value['processing_v7'] = {'revalidation': ext_deepcopy(self.processing_revalidation), 'provisional_intents': ext_deepcopy(self.provisional_intents), 'observed_profiles': sorted(self.observed_profiles), 'observed_provisional_intents': sorted(self.observed_provisional_intents)}
return value
def _course_registration_restore_3(self, value):
if value.get('schema') != 'rescopebench-course-registration/v7' or value.get('v7_identity') != fn_digest([DATA_TARGETS_4, DATA_PROVIDER_TOOLS_3]):
raise ValueError('Course v7 snapshot identity mismatch')
parent = ext_deepcopy(value)
state = parent.pop('processing_v7')
parent.pop('v7_identity')
parent['schema'] = 'rescopebench-course-registration/v6'
self._course_registration_restore_4(parent)
self.processing_revalidation = ext_deepcopy(state['revalidation'])
self.provisional_intents = ext_deepcopy(state['provisional_intents'])
self.observed_profiles = set(state['observed_profiles'])
self.observed_provisional_intents = set(state['observed_provisional_intents'])
def _course_registration_snapshot_4(self):
value = self._course_registration_orchestration_successor_snapshot()
value['schema'] = 'rescopebench-course-registration/v6'
value['v6_identity'] = fn_digest_2([DATA_TARGETS_5, DATA_POLICY_SCOPES, DATA_PROVIDER_TOOLS_4])
return value
def _course_registration_restore_4(self, value):
if value.get('schema') != 'rescopebench-course-registration/v6' or value.get('v6_identity') != fn_digest_2([DATA_TARGETS_5, DATA_POLICY_SCOPES, DATA_PROVIDER_TOOLS_4]):
raise ValueError('Course v6 snapshot identity mismatch')
parent = ext_deepcopy(value)
parent.pop('v6_identity')
parent['schema'] = 'rescopebench-course-registration-orchestration-stream/v3'
self._course_registration_orchestration_successor_restore(parent)
def _course_registration_orchestration_successor_snapshot(self):
parent = self._course_registration_stream_adapter_snapshot()
parent['schema'] = 'rescopebench-course-registration-orchestration-stream/v3'
parent['orchestration'] = {'changed': self.orchestration_changed, 'observed_waitlist_entries': sorted(self.observed_waitlist_entries), 'tool_surface_sha256': fn__digest(DATA_TOOLS_3)}
return parent
def _course_registration_orchestration_successor_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-course-registration-orchestration-stream/v3':
raise ValueError('unsupported orchestration stream snapshot')
parent = ext_deepcopy(snapshot)
parent['schema'] = 'rescopebench-course-registration-persistent-stream/v2'
parent.pop('orchestration', None)
self._course_registration_stream_adapter_restore(parent)
state = snapshot.get('orchestration') or {}
self.orchestration_changed = bool(state.get('changed'))
self.observed_waitlist_entries = set(state.get('observed_waitlist_entries') or [])
def _course_registration_stream_adapter_snapshot(self):
return {'schema': 'rescopebench-course-registration-persistent-stream/v2', 'base': self._course_registration_adapter_snapshot(), 'stream': {'prepared_tasks': list(self.prepared_tasks), 'boundary_receipts': ext_deepcopy(self.boundary_receipts), 'applied_boundary_events': sorted(self.applied_boundary_events), 'drift_event_sequence': self.drift_event_sequence, 'active_student_ids': sorted(self.active_student_ids), 'active_section_ids': sorted(self.active_section_ids)}}
def _course_registration_stream_adapter_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-course-registration-persistent-stream/v2':
raise ValueError('unsupported Course Registration stream snapshot')
self._course_registration_adapter_restore(ext_deepcopy(snapshot['base']))
stream = snapshot.get('stream') or {}
self.prepared_tasks = list(stream.get('prepared_tasks') or [])
self.boundary_receipts = ext_deepcopy(stream.get('boundary_receipts') or [])
self.applied_boundary_events = set(stream.get('applied_boundary_events') or [])
self.drift_event_sequence = int(stream.get('drift_event_sequence') or 0)
self.active_student_ids = set(stream.get('active_student_ids') or [])
self.active_section_ids = set(stream.get('active_section_ids') or [])
def _course_registration_adapter_snapshot(self):
return {'schema': 'rescopebench-course-registration-snapshot/v4', 'task_id': self._task_id, 'task_targets': ext_deepcopy(self._task_targets), 'entry_entities': ext_deepcopy(self._entry_entities), 'audit': ext_deepcopy(self._audit), 'entities': self._state.list_snapshot(), 'events': ext_deepcopy(self._events), 'calls': self._calls, 'read_units': self._read_units, 'write_attempts': self._write_attempts}
def _course_registration_adapter_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-course-registration-snapshot/v4':
raise ValueError('unsupported snapshot schema')
self._task_id = snapshot.get('task_id')
self._task_targets = ext_deepcopy(snapshot.get('task_targets') or [])
self._entry_entities = ext_deepcopy(snapshot.get('entry_entities') or {})
self._audit = ext_deepcopy(snapshot.get('audit') or {})
self._state.restore(snapshot.get('entities') or {})
self._events = ext_deepcopy(snapshot.get('events') or [])
self._calls = int(snapshot.get('calls') or 0)
self._read_units = int(snapshot.get('read_units') or 0)
self._write_attempts = int(snapshot.get('write_attempts') or 0)
self._assert_state_invariants()
class MemoryState:
def __init__(self, entities):
self._entities = ext_deepcopy(entities)
def get_entity(self, entity_type, entity_id, id_field='id'):
field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
return next((ext_deepcopy(row) for row in self._entities.get(entity_type, []) if row.get(field) == entity_id or row.get('id') == entity_id), None)
def list_entities(self, entity_type):
return ext_deepcopy(self._entities.get(entity_type, []))
def add_entity(self, entity_type, record, id_field='id'):
field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
identity = record.get(field) or record.get('id')
if identity is None:
raise ValueError(f'missing identity for {entity_type}')
rows = self._entities.setdefault(entity_type, [])
for (index, row) in enumerate(rows):
if row.get(field) == identity or row.get('id') == identity:
rows[index] = ext_deepcopy(record)
return ext_deepcopy(record)
rows.append(ext_deepcopy(record))
return ext_deepcopy(record)
def update_entity(self, entity_type, entity_id, patch, id_field='id'):
field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
for row in self._entities.get(entity_type, []):
if row.get(field) == entity_id or row.get('id') == entity_id:
row.update(ext_deepcopy(patch))
return ext_deepcopy(row)
return None
def delete_entity(self, entity_type, entity_id, id_field='id'):
field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
rows = self._entities.get(entity_type, [])
kept = [row for row in rows if row.get(field) != entity_id and row.get('id') != entity_id]
self._entities[entity_type] = kept
return len(kept) != len(rows)
def list_snapshot(self):
return ext_deepcopy(self._entities)
def restore(self, entities):
self._entities = ext_deepcopy(entities)