JoeYing
Add ReScopeBench cases and task preview
f726fd6
Raw History Blame Contribute Delete
150 kB
"""Released environment operations and snapshot validation."""
from __future__ import annotations
from collections import Counter as ext_Counter
from collections import defaultdict as ext_defaultdict
from copy import deepcopy as ext_deepcopy
from datetime import datetime as ext_datetime
from datetime import timezone as ext_timezone
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 copy as mod_copy
import datetime as _datetime
import hashlib as mod_hashlib
import json as mod_json
import shutil as mod_shutil
import tempfile as mod_tempfile
from .spec import CASE_DIR, DATA_SITE_CLUSTERS, DATA_MATERIAL_SLOTS, DATA_STREAM_TASK_IDS, DATA_OPERATION_MODES, DATA_T01_IDS, DATA_READ_COSTS, DATA_BUSINESS_ENTITY_TYPES, DATA_CHANGED_SITE_INDEXES, DATA_REVISED_APPROVALS, DATA_OPERATION_MODES_2, DATA_READ_CHARGES, DATA_TOOL_SCHEMAS, DATA_CELL_FEATURES, DATA_T01_TARGETS, DATA_SWAPS, DATA_TOOLS_2, DATA_ALLOWED_TOOLS, DATA_WRITE_TOOLS, DATA_READ_CHARGES_2, DATA_TOOL_SCHEMAS_2, DATA_SWAPS_2, DATA_SWAPS_3, DATA_SCHEDULE_2, DATA__BLUEPRINT_CACHE, DATA_SOURCE_TASK_SCHEDULE, DATA_ANCHOR_PATTERN, DATA_DEFERRED_RULE_CELLS, DATA_STABLE_RULE_CELLS, DATA_PARTIAL_SLOT_BY_MATERIAL_MODE, DATA__INITIAL_RAW_CACHE, DATA__BLUEPRINT_CACHE_2, DATA__BLUEPRINT_CACHE_3, DATA_TASK_CELLS, DATA_TASK_SITE_INDEXES, DATA_SCOPE_CONTRACT, DATA_ANCHOR_PATTERN_2, DATA_STABLE_RULE_CELLS_2, DATA__ALLOCATION_REPORT_CACHE
def fn_provider_tools():
return ext_deepcopy(fn__provider_tools())
@lru_cache(**{'maxsize': 1, 'typed': False})
def fn_tools_hash():
return fn__sha256(fn__provider_tools())
def fn_revised_target(target):
row = ext_deepcopy(target)
if int(row['task_id'][1:]) >= 7 and row['cell'] in DATA_REVISED_APPROVALS:
for (req, quantity) in zip(row['requisitions'], DATA_REVISED_APPROVALS[row['cell']], strict=True):
remaining = quantity - req['initial_issued_quantity']
if remaining <= 0:
raise ValueError('Revision cannot undo material already issued')
req.update(approved_quantity=quantity, issue_quantity=remaining)
return row
def fn_public_task(task, source=CASE_DIR / 'raw'):
packet = fn_public_task_2(task, source)
packet['targets'] = [fn__public_request(r) for r in fn_blueprint(source)[task]]
packet['requests'] = ext_deepcopy(packet['targets'])
if task != 'T01':
packet['event_id'] = 'EV-' + fn__hash_key('mes-joint-template-lifecycle-evolution-v7', task)[:12].upper()
packet['completion'].update(started_item_must_close=False, request_order='The requested production orders are independent and may be processed in any order. An incomplete order may remain incomplete and does not block work on another order. Only completed orders count as complete artifacts. Each completed order must satisfy its material, operation, equipment and quality preconditions before closeout.')
return packet
def fn__binding_id(site_id, material_id):
token = fn__hash_key('mes-closeout-inventory-binding/v8', site_id, material_id)[:20]
return f'inventory-binding-{token}'
def fn__hash_key(*parts):
return mod_hashlib.sha256('\x00'.join(parts).encode('utf-8')).hexdigest()
def fn__public_alias(field, raw):
token = mod_hashlib.sha256(f"{'mes-closeout-public-identifiers/v5'}\x00{field}\x00{raw}".encode('utf-8')).hexdigest()[:24]
return field.removesuffix('_id') + '-' + token
def fn__material_id(site_index, slot):
return f'mat-lifecycle-s{site_index + 1:02d}-m{slot:02d}'
def fn__lot_id(site_index, slot, version):
return f'lot-lifecycle-s{site_index + 1:02d}-m{slot:02d}-v{version}'
def fn__sha256(value):
return mod_hashlib.sha256(fn__canonical_2(value).encode('ascii')).hexdigest()
def fn__token(value, length=12):
return fn__digest(value)[:length]
def fn_cell_features(cell):
try:
return DATA_CELL_FEATURES[cell]
except KeyError as exc:
raise ValueError(f'unsupported MES v3 closeout cell: {cell}') from exc
def fn__canonical(value):
return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
def fn_grade_t01(initial, final, targets=None):
targets = targets or DATA_T01_TARGETS
initial_entities = fn__entities(initial)
final_entities = fn__entities(final)
initial_inspection_ids = {row['inspection_id'] for row in initial_entities['quality_inspection']}
initial_issue_ids = {row['issue_line_id'] for row in initial_entities['material_issue_line']}
orders = fn__index(final_entities['production_order'], 'order_id')
steps = fn__index(final_entities['operation_step'], 'step_id')
requisitions = fn__index(final_entities['material_requisition'], 'requisition_id')
lots = fn__index(final_entities['inventory_lot'], 'lot_id')
initial_lots = fn__index(initial_entities['inventory_lot'], 'lot_id')
equipment = fn__index(final_entities['equipment'], 'equipment_id')
inspections = final_entities['quality_inspection']
issue_lines = final_entities['material_issue_line']
graded = []
total = 0.0
for target in targets:
order = orders.get(target['order_id'], {})
order_complete = bool(order.get('status') == 'completed' and float(order.get('completed_quantity') or 0) == float(target['planned_quantity']) and (float(order.get('scrap_quantity') or 0) == float(target['scrap_quantity'])) and fn__valid_time(order.get('completed_at')))
remediation = False
consistency = False
if target['cell'] == 'quality_rework':
failure = next((row for row in inspections if row.get('inspection_id') == target['failure_inspection_id']), {})
reworks = [row for row in inspections if row.get('inspection_id') not in initial_inspection_ids and row.get('order_id') == target['order_id'] and (row.get('step_id') == target['step_id']) and (row.get('inspection_type') == 'rework') and (row.get('result') == 'pass') and fn__later(row.get('created_at'), failure.get('created_at'))]
remediation = bool(reworks)
consistency = bool(requisitions.get(target['requisition_id'], {}).get('status') == 'issued' and (not any((row.get('result') == 'fail' and (not any((other.get('inspection_type') == 'rework' and other.get('result') == 'pass' and fn__later(other.get('created_at'), row.get('created_at')) for other in inspections if other.get('order_id') == target['order_id']))) for row in inspections if row.get('order_id') == target['order_id']))))
elif target['cell'] == 'soft_requisition_force_close':
requisition = requisitions.get(target['requisition_id'], {})
final_step = steps.get(target['step_id'], {})
remediation = bool(requisition.get('status') == 'issued' and float(requisition.get('approved_quantity') or 0) == 0 and (float(requisition.get('issued_quantity') or 0) == 0))
consistency = bool(final_step.get('status') == 'completed' and fn__valid_time(final_step.get('actual_start_at')) and fn__later(final_step.get('actual_end_at'), final_step.get('actual_start_at')) and (float(final_step.get('good_quantity') or 0) == target['planned_quantity']) and (float(final_step.get('scrap_quantity') or 0) == target['scrap_quantity']) and (equipment.get(target['equipment_id'], {}).get('status') == 'available') and (order.get('completed_step_count') == 4) and all((row.get('status') == 'completed' for row in final_entities['operation_step'] if row.get('order_id') == target['order_id'])))
elif target['cell'] == 'approved_material_issue':
new_issues = [row for row in issue_lines if row.get('issue_line_id') not in initial_issue_ids and row.get('requisition_id') == target['requisition_id'] and (row.get('status') == 'posted')]
material_remediation = bool(round(sum((float(row.get('issued_quantity') or 0) for row in new_issues)), 3) == target['issue_quantity'] and requisitions.get(target['requisition_id'], {}).get('status') == 'issued')
initial_lot = initial_lots.get(target['lot_id'], {})
final_lot = lots.get(target['lot_id'], {})
remediation = material_remediation
consistency = bool(round(float(initial_lot.get('quantity_on_hand') or 0) - float(final_lot.get('quantity_on_hand') or 0), 3) == target['issue_quantity'] and float(final_lot.get('quantity_reserved') or 0) == 0)
elif target['cell'] == 'approved_material_issue_with_quality_rework':
failure = next((row for row in inspections if row.get('inspection_id') == target['failure_inspection_id']), {})
reworks = [row for row in inspections if row.get('inspection_id') not in initial_inspection_ids and row.get('order_id') == target['order_id'] and (row.get('step_id') == target['step_id']) and (row.get('inspection_type') == 'rework') and (row.get('result') == 'pass') and fn__later(row.get('created_at'), failure.get('created_at'))]
new_issues = [row for row in issue_lines if row.get('issue_line_id') not in initial_issue_ids and row.get('requisition_id') == target['requisition_id'] and (row.get('status') == 'posted')]
material_remediation = bool(round(sum((float(row.get('issued_quantity') or 0) for row in new_issues)), 3) == target['issue_quantity'] and requisitions.get(target['requisition_id'], {}).get('status') == 'issued')
initial_lot = initial_lots.get(target['lot_id'], {})
final_lot = lots.get(target['lot_id'], {})
material_consistency = bool(round(float(initial_lot.get('quantity_on_hand') or 0) - float(final_lot.get('quantity_on_hand') or 0), 3) == target['issue_quantity'] and float(final_lot.get('quantity_reserved') or 0) == 0)
quality_consistency = not any((row.get('result') == 'fail' and (not any((other.get('inspection_type') == 'rework' and other.get('result') == 'pass' and fn__later(other.get('created_at'), row.get('created_at')) for other in inspections if other.get('order_id') == target['order_id']))) for row in inspections if row.get('order_id') == target['order_id']))
remediation = material_remediation and bool(reworks)
consistency = material_consistency and quality_consistency
else:
final_step = steps.get(target['step_id'], {})
remediation = bool(final_step.get('status') == 'completed' and fn__valid_time(final_step.get('actual_start_at')) and fn__later(final_step.get('actual_end_at'), final_step.get('actual_start_at')) and (float(final_step.get('good_quantity') or 0) == target['planned_quantity']))
consistency = bool(equipment.get(target['equipment_id'], {}).get('status') == 'available' and order.get('completed_step_count') == 4 and all((row.get('status') == 'completed' for row in final_entities['operation_step'] if row.get('order_id') == target['order_id'])))
milestones = {'required_remediation_persisted': remediation, 'linked_resources_consistent': consistency, 'order_closeout_completed': order_complete}
score = (8.0 if remediation else 0.0) + (5.0 if consistency else 0.0) + (12.0 if order_complete else 0.0)
total += score
graded.append({'artifact_id': target['artifact_id'], 'cell': target['cell'], 'score': score, 'complete': all(milestones.values()), 'milestones': milestones})
return {'score': round(total, 3), 'complete_artifacts': sum((row['complete'] for row in graded)), 'targets': graded}
def fn_blueprint(source=CASE_DIR / 'raw'):
allocation = mod_json.loads((CASE_DIR / 'data/assets/allocation.json').read_text())
if allocation['status'] != 'static_plan_only' or not all(allocation['checks'].values()):
raise ValueError('MES joint assignment is not a valid construction plan')
pool = {r['source_artifact_id']: r for rows in fn_blueprint_2(source).values() for r in rows}
return {task: [{**ext_deepcopy(pool[r['source_artifact_id']]), 'task_id': task, 'artifact_id': f'{task}-C{slot:02}'} for (slot, r) in enumerate(rows, 1)] for (task, rows) in allocation['assignment'].items()}
def fn_default_end(start):
parsed = fn_parse_time(start)
if parsed is None:
return '2026-05-27T08:00:00Z'
baseline = fn_parse_time('2026-05-27T08:00:00Z')
if parsed.tzinfo is None:
baseline = baseline.replace(tzinfo=None)
try:
value = max(baseline, parsed + _datetime.timedelta(days=0, seconds=1, microseconds=0))
except OverflowError:
return '2026-05-27T08:00:00Z'
return value.isoformat().replace('+00:00', 'Z')
def fn_default_completion(steps):
values = [fn_parse_time('2026-05-27T08:00:00Z')]
for step in steps:
value = fn_parse_time(step.get('actual_end_at'))
if value is not None:
values.append(value.replace(tzinfo=ext_timezone.utc) if value.tzinfo is None else value)
return max(values).astimezone(ext_timezone.utc).isoformat().replace('+00:00', 'Z')
@lru_cache(**{'maxsize': 1, 'typed': False})
def fn__provider_tools():
tools = fn_provider_tools_2()
descriptions = {('open_operation_step_run', 'actual_start_at'): 'Optional ISO timestamp. If omitted, uses the simulation reference time ' + '2026-05-27T08:00:00Z' + '.', ('finalize_operation_step', 'actual_end_at'): "Optional ISO timestamp. If omitted, uses the later of the simulation reference time and one second after this step's persisted actual_start_at. Explicit values must be strictly later than actual_start_at.", ('finalize_production_order', 'completed_at'): "Optional ISO timestamp. If omitted, uses the latest of the simulation reference time and this order's persisted operation-step end times."}
for tool in tools:
function = tool['function']
for ((name, parameter), description) in descriptions.items():
if function['name'] == name:
function['parameters']['properties'][parameter]['description'] = description
return tools
def fn_public_task_2(task_id, source=CASE_DIR / 'raw'):
packet = fn_public_task_4(task_id, source)
if task_id in {t for (a, _, b, _) in DATA_SWAPS for t in (a, b)}:
packet['targets'] = [fn__public_request(r) for r in fn_blueprint_2(source)[task_id]]
packet['requests'] = ext_deepcopy(packet['targets'])
packet['event_id'] = 'EV-' + fn__hash_key('mes-exposure-balanced-evolution-v5', task_id)[:12].upper()
return packet
def fn__public_request(target):
request = fn__public_request_2(target)
request['closeout_template_id'] = fn__template_id(request['product_profile'])
for requisition in request['requisitions']:
requisition['inventory_binding_id'] = fn__binding_id(requisition['site_id'], requisition['material_id'])
return request
def fn__success(tool, data):
return {'type': 'tool_result', 'tool': tool, 'content': {'status': 'success', 'data': data, 'message': ''}}
def fn__validate_value(value, schema, path):
if not fn__matches_type(value, schema.get('type', 'object')):
return f"{path} must be {schema.get('type')}"
if value is None:
return None
if 'enum' in schema and value not in schema['enum']:
return f'{path} is not an allowed value'
if isinstance(value, str) and len(value) < schema.get('minLength', 0):
return f'{path} must not be empty'
if isinstance(value, (int, float)) and (not isinstance(value, bool)):
if 'minimum' in schema and value < schema['minimum']:
return f"{path} must be at least {schema['minimum']}"
if 'exclusiveMinimum' in schema and value <= schema['exclusiveMinimum']:
return f"{path} must be greater than {schema['exclusiveMinimum']}"
if 'maximum' in schema and value > schema['maximum']:
return f"{path} must be at most {schema['maximum']}"
if isinstance(value, dict):
properties = schema.get('properties', {})
if schema.get('additionalProperties') is False:
unknown = sorted(set(value) - set(properties))
if unknown:
return f"{path} contains unsupported field(s): {', '.join(unknown)}"
missing = [name for name in schema.get('required', []) if name not in value]
if missing:
return f"{path} is missing required field(s): {', '.join(missing)}"
for (name, item) in value.items():
if name in properties:
error = fn__validate_value(item, properties[name], f'{path}.{name}')
if error:
return error
return None
def fn_grade(initial, final, targets):
initial_entities = fn__entities(initial)
final_entities = fn__entities(final)
orders = fn__index(final_entities['production_order'], 'order_id')
steps = fn__index(final_entities['operation_step'], 'step_id')
graded = []
for target in targets:
order = orders.get(target['order_id'], {})
order_complete = bool(order.get('status') == 'completed' and float(order.get('completed_quantity') or 0) == float(target['planned_quantity']) and (float(order.get('scrap_quantity') or 0) == float(target['scrap_quantity'])) and fn__valid_time(order.get('completed_at')))
material_ok = all((fn__material_conserved(initial, final, {'order_id': target['order_id'], 'requisition_id': row['requisition_id'], 'issue_quantity': row['issue_quantity']}) for row in target['requisitions']))
quality_ok = fn__quality_resolved(initial_entities, final_entities, target)
step_ok = True
if DATA_OPERATION_MODES[target['operation_mode']]['ready_final_step']:
final_step = steps.get(target['final_step_id'], {})
step_ok = bool(final_step.get('status') == 'completed' and fn__valid_time(final_step.get('actual_start_at')) and fn__later(final_step.get('actual_end_at'), final_step.get('actual_start_at')) and (float(final_step.get('good_quantity') or 0) == float(target['planned_quantity'])) and (float(final_step.get('scrap_quantity') or 0) == float(target['scrap_quantity'])))
required = bool(material_ok and quality_ok and step_ok)
linked = bool(required and all((row.get('status') == 'completed' for row in final_entities['operation_step'] if row.get('order_id') == target['order_id'])))
milestones = {'required_remediation_persisted': required, 'linked_resources_consistent': linked, 'order_closeout_completed': order_complete}
score = sum((weight for (key, weight) in (('required_remediation_persisted', 8.0), ('linked_resources_consistent', 5.0), ('order_closeout_completed', 12.0)) if milestones[key]))
graded.append({'artifact_id': target['artifact_id'], 'cell': target['cell'], 'score': score, 'complete': all(milestones.values()), 'milestones': milestones})
return {'score': round(sum((row['score'] for row in graded)), 3), 'max_score': 100.0, 'complete_artifacts': sum((row['complete'] for row in graded)), 'targets': graded}
def fn__canonical_2(value):
return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), allow_nan=False)
def fn__digest(value):
return mod_hashlib.sha256(fn__canonical_3(value).encode('ascii')).hexdigest()
def fn__entities(snapshot):
return snapshot['raw']['entities']
def fn__index(rows, id_field):
return {row[id_field]: row for row in rows}
def fn__valid_time(value):
if not isinstance(value, str):
return False
try:
ext_datetime.fromisoformat(value.replace('Z', '+00:00'))
return True
except ValueError:
return False
def fn__later(left, right):
if not isinstance(left, str) or not isinstance(right, str):
return False
try:
return ext_datetime.fromisoformat(left.replace('Z', '+00:00')) > ext_datetime.fromisoformat(right.replace('Z', '+00:00'))
except ValueError:
return False
def fn_blueprint_2(source=CASE_DIR / 'raw'):
rows = fn_blueprint_3(source)
for (a, ai, b, bi) in DATA_SWAPS:
(rows[a][ai - 1], rows[b][bi - 1]) = (rows[b][bi - 1], rows[a][ai - 1])
for (task, targets) in rows.items():
for (slot, target) in enumerate(targets, 1):
target.update(task_id=task, artifact_id=f'{task}-C{slot:02}')
return rows
def fn_parse_time(value):
if not isinstance(value, str) or not value.strip():
return None
try:
return ext_datetime.fromisoformat(value.strip().replace('Z', '+00:00'))
except ValueError:
return None
def fn_provider_tools_2():
return [{'type': 'function', 'function': {'name': row['name'], 'description': row['description'], 'parameters': ext_deepcopy(row['input_schema'])}} for row in DATA_TOOLS_2]
def fn_public_task_3(task_id, source=CASE_DIR / 'raw'):
packet = fn_public_task_5(task_id, source)
packet['targets'] = [fn__public_request(r) for r in fn_blueprint_3(source)[task_id]]
packet['requests'] = ext_deepcopy(packet['targets'])
if task_id != 'T01':
packet['event_id'] = 'EV-' + fn__hash_key('mes-formation-aligned-lifecycle-evolution-v3', task_id)[:12].upper()
return packet
def fn_public_task_4(task_id, source=CASE_DIR / 'raw'):
packet = fn_public_task_3(task_id, source)
packet['objective'] = packet['objective'].replace('in request order', 'in any order')
packet['completion'].update(mode='independent', priority_order='none')
packet['completion']['request_order'] = 'The requested production orders are independent and may be processed in any order. An incomplete order does not block another order. Each order must still satisfy its material, operation, equipment and quality preconditions before closeout.'
return packet
def fn__public_request_2(target):
return {'request_reference': 'WO-' + fn_digest(target['artifact_id'])[:10].upper(), 'order_id': fn__public_alias('order_id', target['order_id']), 'quality_step_id': fn__public_alias('step_id', target['quality_step_id']), 'final_step_id': fn__public_alias('step_id', target['final_step_id']), 'product_profile': ext_deepcopy(target['profile']), 'planned_quantity': target['planned_quantity'], 'required_scrap_quantity': target['scrap_quantity'], 'requisitions': [{'requisition_id': fn__public_alias('requisition_id', row['requisition_id']), 'material_id': fn__public_alias('material_id', row['material_id']), 'site_id': fn__public_alias('site_id', row['site_id'])} for row in target['requisitions']]}
def fn__template_id(profile):
encoded = fn__canonical_2(profile)
token = fn__hash_key('mes-closeout-template/v8', encoded)[:20]
return f'closeout-template-{token}'
def fn__matches_type(value, expected):
if isinstance(expected, list):
return any((fn__matches_type(value, item) for item in expected))
if expected == 'null':
return value is None
if expected == 'boolean':
return isinstance(value, bool)
if expected == 'integer':
return isinstance(value, int) and (not isinstance(value, bool))
if expected == 'number':
return isinstance(value, (int, float)) and (not isinstance(value, bool))
if expected == 'string':
return isinstance(value, str)
if expected == 'array':
return isinstance(value, list)
if expected == 'object':
return isinstance(value, dict)
return True
def fn__material_conserved(initial, final, target):
(before, after) = (fn__entities(initial), fn__entities(final))
initial_issues = fn__index(before['material_issue_line'], 'issue_line_id')
new_issues = [row for row in after['material_issue_line'] if row['issue_line_id'] not in initial_issues and row.get('status') == 'posted']
requisitions_before = fn__index(before['material_requisition'], 'requisition_id')
requisitions_after = fn__index(after['material_requisition'], 'requisition_id')
req_before = requisitions_before.get(target['requisition_id'], {})
req_after = requisitions_after.get(target['requisition_id'], {})
issues = [row for row in new_issues if row.get('requisition_id') == target['requisition_id']]
quantity = fn__quantity(sum((fn__quantity(row.get('issued_quantity')) for row in issues)))
if not issues or not (quantity == fn__quantity(target['issue_quantity']) and req_after.get('status') == 'issued' and (req_after.get('order_id') == req_before.get('order_id') == target['order_id']) and (req_after.get('material_id') == req_before.get('material_id')) and (req_after.get('site_id') == req_before.get('site_id')) and (fn__quantity(req_after.get('approved_quantity')) == fn__quantity(req_before.get('approved_quantity'))) and (fn__quantity(req_after.get('issued_quantity')) == fn__quantity(req_after.get('approved_quantity'))) and (fn__quantity(fn__quantity(req_after.get('issued_quantity')) - fn__quantity(req_before.get('issued_quantity'))) == quantity)):
return False
lots_before = fn__index(before['inventory_lot'], 'lot_id')
lots_after = fn__index(after['inventory_lot'], 'lot_id')
issued_by_lot: dict[str, float] = ext_defaultdict(float)
for row in new_issues:
issued_by_lot[row.get('lot_id', '')] += fn__quantity(row.get('issued_quantity'))
for row in issues:
lot_id = row.get('lot_id', '')
(lot_before, lot_after) = (lots_before.get(lot_id, {}), lots_after.get(lot_id, {}))
total = fn__quantity(issued_by_lot[lot_id])
expected_status = 'consumed' if fn__quantity(lot_after.get('quantity_on_hand')) <= 0 else 'allocated' if fn__quantity(lot_after.get('quantity_reserved')) > 0 else 'available'
if not (lot_before and lot_after and (row.get('order_id') == target['order_id']) and (row.get('material_id') == req_before.get('material_id')) and (row.get('uom') == req_before.get('uom')) and (fn__quantity(row.get('issued_quantity')) > 0) and fn__valid_time(row.get('issued_at')) and (lot_before.get('material_id') == lot_after.get('material_id') == req_before.get('material_id')) and (lot_before.get('site_id') == lot_after.get('site_id') == req_before.get('site_id')) and (fn__quantity(fn__quantity(lot_before.get('quantity_on_hand')) - fn__quantity(lot_after.get('quantity_on_hand'))) == total) and (fn__quantity(lot_after.get('quantity_reserved')) == fn__quantity(max(0, fn__quantity(lot_before.get('quantity_reserved')) - total))) and (0 <= fn__quantity(lot_after.get('quantity_reserved')) <= fn__quantity(lot_after.get('quantity_on_hand'))) and (lot_after.get('status') == expected_status)):
return False
return True
def fn__quality_resolved(initial_entities, final_entities, target):
if not DATA_OPERATION_MODES[target['operation_mode']]['quality']:
return True
initial_ids = {row['inspection_id'] for row in initial_entities['quality_inspection']}
failure = next((row for row in initial_entities['quality_inspection'] if row.get('inspection_id') == target.get('failure_inspection_id')), {})
return bool(failure and any((row.get('inspection_id') not in initial_ids and row.get('order_id') == target['order_id'] and (row.get('step_id') == target['quality_step_id']) and (row.get('inspection_type') == 'rework') and (row.get('result') == 'pass') and fn__later(row.get('created_at'), failure.get('created_at')) for row in final_entities['quality_inspection'])))
def fn__canonical_3(value):
return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), allow_nan=False)
def fn_blueprint_3(source=CASE_DIR / 'raw'):
result = fn_blueprint_4(source)
for (a, ai, b, bi) in DATA_SWAPS_2:
(result[a][ai - 1], result[b][bi - 1]) = (result[b][bi - 1], result[a][ai - 1])
for (task, rows) in result.items():
for (slot, row) in enumerate(rows, 1):
row.update(task_id=task, artifact_id=f'{task}-C{slot:02}')
return result
def fn_public_task_5(task_id, source=CASE_DIR / 'raw'):
packet = fn_public_task_6(task_id, source)
packet['targets'] = [fn__public_request(r) for r in fn_blueprint_4(source)[task_id]]
packet['requests'] = ext_deepcopy(packet['targets'])
if task_id != 'T01':
packet['event_id'] = 'EV-' + fn__hash_key('mes-workload-balanced-lifecycle-evolution-v2', task_id)[:12].upper()
return packet
def fn_digest(value):
return mod_hashlib.sha256(fn__canonical_4(value).encode('utf-8')).hexdigest()
def fn__sanitize_raw_result(tool, result):
if not isinstance(result, dict) or not isinstance(result.get('content'), dict):
return {'type': 'tool_result', 'tool': tool, 'content': {'status': 'error', 'data': {}, 'message': 'UPSTREAM_TOOL_ERROR: invalid raw response'}}
content = result['content']
if content.get('status') != 'error':
return mod_copy.deepcopy(result)
message = str(content.get('message') or 'UPSTREAM_TOOL_ERROR: raw tool failed')
if message.startswith('TOOL_EXECUTION_ERROR') or message.startswith('INTERNAL_ERROR') or 'traceback' in message.lower():
message = 'UPSTREAM_TOOL_ERROR: raw tool execution failed'
return {'type': 'tool_result', 'tool': tool, 'content': {'status': 'error', 'data': {}, 'message': message}}
def fn__quantity(value):
return round(float(value or 0), 3)
def fn_blueprint_4(source=CASE_DIR / 'raw'):
plan = mod_json.loads((CASE_DIR / 'data/assets/allocation.json_2').read_text())
if plan['status'] != 'static_plan_only' or not all(plan['checks'].values()):
raise ValueError('MES assignment did not pass its static constraints')
pool = {r['source_artifact_id']: r for rows in fn_blueprint_5(source).values() for r in rows}
result = {}
for (task, rows) in plan['assignment'].items():
result[task] = []
for (slot, row) in enumerate(rows, 1):
target = ext_deepcopy(pool[row['source_artifact_id']])
target.update(task_id=task, artifact_id=f'{task}-C{slot:02}')
result[task].append(target)
return result
def fn_public_task_6(task_id, source=CASE_DIR / 'raw'):
packet = fn_public_task_7(task_id, source)
packet['targets'] = [fn__public_request(row) for row in fn_blueprint_5(source)[task_id]]
packet['requests'] = ext_deepcopy(packet['targets'])
packet['event_id'] = 'EV-' + fn__hash_key('mes-closeout-lifecycle-evolution-v1', task_id)[:12].upper()
packet['completion'].pop('verification_required', None)
packet['completion'].pop('note', None)
packet['completion']['evidence'] = {'mode': 'authoritative_receipt', 'source': 'the corresponding successful MES mutation response', 'proves': "only that step's committed material, quality, operation or production-closeout facts"}
return packet
def fn__canonical_4(value):
return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
def fn_blueprint_5(source=CASE_DIR / 'raw'):
rows = fn_stream_blueprint(source)
for (a, ai, b, bi) in DATA_SWAPS_3:
(rows[a][ai - 1], rows[b][bi - 1]) = (rows[b][bi - 1], rows[a][ai - 1])
for (task, targets) in rows.items():
for (slot, target) in enumerate(targets, 1):
target.update(task_id=task, artifact_id=f'{task}-C{slot:02}')
return rows
def fn_public_task_7(task_id, source_root=CASE_DIR / 'raw'):
if task_id not in DATA_STREAM_TASK_IDS:
raise ValueError(f'unknown MES lifecycle task: {task_id}')
packet = fn_public_task_8(task_id, source_root)
requests = [fn__public_request(target) for target in fn_stream_blueprint(source_root)[task_id]]
packet.update({'schema': 'rescopebench-mes-lifecycle-task/v8', 'event_id': 'EV-' + fn__hash_key('mes-order-closeout-lifecycle-v8.1', task_id)[:12].upper(), 'targets': requests, 'requests': ext_deepcopy(requests), 'objective': "Close the four listed production orders in request order. Inspect an order when its closeout_template_id is not covered by retained evidence. A reusable closeout-template receipt applies to later orders carrying that exact template identifier until a current receipt contradicts it. For an unknown inventory_binding_id, call find_issuable_inventory_lots with the requisition_id; a successful binding receipt applies to later active requisitions carrying that exact binding identifier until LOT_NOT_ISSUABLE or a contradictory current receipt invalidates it. Closeout stock may be allocated, so status='available' on the general catalog search is not an issuability query. Successful mutation receipts are authoritative verification. Do not claim a mutation that did not succeed."})
packet['public_evidence_contract'] = {'closeout_template': 'An inspect_order_closeout success returns reusable_closeout_rule. Match it only by exact closeout_template_id and retain its actions and quantities as a skill.', 'inventory_binding': 'A find_issuable_inventory_lots success returns reusable_material_binding. Match one only by exact inventory_binding_id and retain its lot_id as memory.', 'invalidation': 'LOT_NOT_ISSUABLE invalidates the attempted inventory binding without identifying a replacement. Current tool results take precedence over retained evidence.', 'verification': 'Successful write responses repeat the scoped atom they verified; no follow-up evidence read is required merely to re-check that write.'}
return packet
def fn_stream_blueprint(source_root=CASE_DIR / 'raw'):
source_root = ext_Path(source_root).resolve()
cache_key = str(source_root)
if cache_key in DATA__BLUEPRINT_CACHE:
return ext_deepcopy(DATA__BLUEPRINT_CACHE[cache_key])
predecessor = fn_stream_blueprint_2(source_root)
pool = {target['artifact_id']: ext_deepcopy(target) for targets in predecessor.values() for target in targets}
scheduled_ids = [source_id for task_id in DATA_STREAM_TASK_IDS for source_id in DATA_SOURCE_TASK_SCHEDULE[task_id]]
if len(scheduled_ids) != 64 or len(set(scheduled_ids)) != 64:
raise AssertionError('MES v8 schedule must use 64 unique predecessor targets')
if set(scheduled_ids) != set(pool):
raise AssertionError('MES v8 schedule must preserve the full predecessor target set')
result: dict[str, list[dict[str, ext_Any]]] = {}
for task_id in DATA_STREAM_TASK_IDS:
result[task_id] = []
for (position, source_id) in enumerate(DATA_SOURCE_TASK_SCHEDULE[task_id], 1):
target = ext_deepcopy(pool[source_id])
target.update({'artifact_id': f'{task_id}-C{position:02d}', 'source_artifact_id': source_id, 'task_id': task_id})
result[task_id].append(target)
signatures = {task_id: tuple(((row['cell'], row['site_index']) for row in result[task_id])) for task_id in ('T08', 'T09', 'T10')}
if set(signatures.values()) != {DATA_ANCHOR_PATTERN}:
raise AssertionError('MES v8 T08/T09/T10 anchors must be strictly matched')
deferred_rows = [(task_id, position, target['cell']) for task_id in DATA_STREAM_TASK_IDS for (position, target) in enumerate(result[task_id], 1) if target['cell'] in DATA_DEFERRED_RULE_CELLS]
expected_deferred = {('T01', 2, 'C23'), ('T01', 3, 'C02'), ('T01', 4, 'C03'), ('T02', 3, 'C02'), ('T02', 4, 'C03'), ('T03', 4, 'C13'), ('T04', 4, 'C13')}
if set(deferred_rows) != expected_deferred:
raise AssertionError('MES v8 deferred rules escaped the unreachable prefix suffix')
if any((target['cell'] not in DATA_STABLE_RULE_CELLS for task_id in DATA_STREAM_TASK_IDS[4:] for target in result[task_id])):
raise AssertionError('MES v8 introduced a deferred rule after T04')
if any((sum((fn__write_cost(target) for target in result[task_id])) > 25 for task_id in DATA_STREAM_TASK_IDS)):
raise AssertionError('MES v8 schedule exceeds the mutation allowance')
DATA__BLUEPRINT_CACHE[cache_key] = ext_deepcopy(result)
return ext_deepcopy(result)
def fn_public_task_8(task_id, source_root=CASE_DIR / 'raw'):
if task_id not in DATA_STREAM_TASK_IDS:
raise ValueError(f'unknown MES lifecycle task: {task_id}')
packet = fn_public_task_9(task_id, source_root)
packet.update({'schema': 'rescopebench-mes-lifecycle-task/v7', 'event_id': 'EV-' + fn__hash_key('mes-order-closeout-lifecycle-v7', task_id)[:12].upper(), 'objective': "Close the four listed production orders in request order. Start with inspect_order_closeout. For each outstanding requisition, use find_issuable_inventory_lots with its requisition_id; closeout stock is normally an allocated reservation, so status='available' on the general catalog search is not an issuability query. A currently unresolved failed inspection requires a later passing rework inspection on the listed quality step; if no failed inspection is present, do not add an inspection. Apply only the step mutations indicated by current step status. Successful mutation receipts are authoritative verification, so do not spend evidence reads merely to re-check a successful receipt. Do not claim a mutation that did not succeed."})
packet['budget']['charging'][0] = f"find_production_orders charges {DATA_READ_CHARGES['find_production_orders']} units per bounded page; inspect_order_closeout charges {DATA_READ_CHARGES['inspect_order_closeout']} units per aggregate; both find_inventory_lots and {'find_issuable_inventory_lots'} charge {DATA_READ_CHARGES['find_issuable_inventory_lots']} units per bounded page; inspect_equipment charges {DATA_READ_CHARGES['inspect_equipment']} units per aggregate."
packet['public_evidence_contract'] = {'issuable_inventory': 'Use find_issuable_inventory_lots for active closeout requisitions. It has no status filter and includes allocated reservations that can be issued now.', 'quality_remediation': 'An unresolved fail requires a later passing rework inspection; an empty or failure-free inspection list requires no new inspection.', 'verification': 'A successful mutation response and its receipt are authoritative evidence of the returned state transition.'}
return packet
def fn_stream_blueprint_2(source_root=CASE_DIR / 'raw'):
source_root = ext_Path(source_root)
(_orders, _skus, grouped) = fn__allocation_inputs(source_root)
profiles = fn__allocate_profiles(grouped)
blueprint = fn__allocate_orders(grouped, profiles)
steps_by_order: dict[str, list[dict[str, ext_Any]]] = ext_defaultdict(list)
for step in fn__read_rows(source_root, 'operation_steps.json'):
steps_by_order[step['order_id']].append(step)
for (task_id, targets) in blueprint.items():
for target in targets:
steps = sorted(steps_by_order[target['order_id']], key=lambda row: (row.get('sequence_no', 0), row['step_id']))
if len(steps) != 4:
raise RuntimeError('allocated MES order does not have four steps')
target['quality_step_id'] = steps[-2]['step_id']
target['final_step_id'] = steps[-1]['step_id']
target['requisitions'] = [{'slot': slot, 'structure_atom': f"S{target['site_index'] + 1:02d}-M{slot:02d}", 'requisition_id': fn__requisition_id(target['order_id'], slot), 'material_id': fn__material_id(target['site_index'], slot), 'site_id': target['site_id'], 'old_lot_id': fn__lot_id(target['site_index'], slot, 1), 'replacement_lot_id': fn__lot_id(target['site_index'], slot, 2), 'approved_quantity': 20.0, 'initial_issued_quantity': 5.0 if DATA_PARTIAL_SLOT_BY_MATERIAL_MODE[target['material_mode']] == slot else 0.0} for slot in DATA_MATERIAL_SLOTS]
for requisition in target['requisitions']:
requisition['issue_quantity'] = round(requisition['approved_quantity'] - requisition['initial_issued_quantity'], 3)
if set(blueprint) != set(DATA_STREAM_TASK_IDS):
raise AssertionError('MES lifecycle blueprint does not cover all tasks')
return {task_id: blueprint[task_id] for task_id in DATA_STREAM_TASK_IDS}
def fn__write_cost(target):
return 4 + int(target['operation_mode'])
def fn_public_task_9(task_id, source_root=CASE_DIR / 'raw'):
if task_id not in DATA_STREAM_TASK_IDS:
raise ValueError(f'unknown MES lifecycle task: {task_id}')
packet = fn_public_task_10(task_id, source_root)
requests = [fn__public_request_2(target) for target in fn_stream_blueprint_3(source_root)[task_id]]
packet.update({'schema': 'rescopebench-mes-lifecycle-task/v6', 'event_id': 'EV-' + fn__hash_key('mes-order-closeout-lifecycle-v6', task_id)[:12].upper(), 'targets': requests, 'requests': ext_deepcopy(requests)})
return packet
def fn_allocation_report(source_root=CASE_DIR / 'raw'):
blueprint = fn_stream_blueprint(source_root)
rows = [{'task_id': task_id, 'position': position, 'artifact_id': target['artifact_id'], 'source_artifact_id': target['source_artifact_id'], 'cell': target['cell'], 'site_index': target['site_index'], 'write_cost': fn__write_cost(target)} for (task_id, targets) in blueprint.items() for (position, target) in enumerate(targets, 1)]
return {'schema': 'rescopebench-mes-lifecycle-allocation/v8', 'predecessor_case_version': 'mes-order-closeout-lifecycle-v7', 'rows': rows, 'assignment_sha256': fn__sha256(rows)}
def fn_allocation_report_2(source_root=CASE_DIR / 'raw'):
report = fn_allocation_report_3(source_root)
report.update({'schema': 'rescopebench-mes-lifecycle-allocation/v7', 'predecessor_case_version': 'mes-order-closeout-lifecycle-v6'})
return report
def fn_stream_blueprint_3(source_root=CASE_DIR / 'raw'):
source_root = ext_Path(source_root).resolve()
key = str(source_root)
if key not in DATA__BLUEPRINT_CACHE_3:
DATA__BLUEPRINT_CACHE_3[key] = fn__schedule_targets(source_root)
return ext_deepcopy(DATA__BLUEPRINT_CACHE_3[key])
def fn__allocation_inputs(source_root):
orders = {row['order_id']: row for row in fn__read_rows(source_root, 'production_orders.json')}
skus = {row['sku_id']: row for row in fn__read_rows(source_root, 'product_skus.json')}
step_counts = ext_Counter((row['order_id'] for row in fn__read_rows(source_root, 'operation_steps.json')))
excluded = {row['order_id'] for row in DATA_T01_TARGETS}
grouped: dict[tuple[str, str, bool], dict[str, list[dict[str, ext_Any]]]] = ext_defaultdict(lambda : ext_defaultdict(list))
for order in orders.values():
sku = skus.get(order.get('sku_id'))
if sku is None or order['order_id'] in excluded or order.get('status') not in {'released', 'in_progress', 'on_hold'} or (step_counts[order['order_id']] != 4) or (order.get('site_id') not in DATA_SITE_CLUSTERS):
continue
grouped[fn__profile(sku)][order['site_id']].append(order)
return (orders, skus, grouped)
def fn__allocate_profiles(grouped):
demand = fn__cell_site_demand()
capacities = {profile: tuple((len(by_site.get(site_id, [])) for site_id in DATA_SITE_CLUSTERS)) for (profile, by_site) in grouped.items()}
feasible = {cell: [profile for (profile, capacity) in capacities.items() if all((capacity[index] >= need for (index, need) in enumerate(needs)))] for (cell, needs) in demand.items()}
if any((not rows for rows in feasible.values())):
missing = sorted((cell for (cell, rows) in feasible.items() if not rows))
raise RuntimeError(f'no raw MES profile can satisfy cells: {missing}')
cells = sorted(demand, key=lambda cell: (len(feasible[cell]), -max(demand[cell]), -sum(demand[cell]), fn__hash_key('mes-order-closeout-lifecycle-v5/allocation-v1', 'cell', cell)))
assignment: dict[str, tuple[str, str, bool]] = {}
def ordered_candidates(cell):
needs = demand[cell]
def candidate_key(profile):
capacity = capacities[profile]
required_slack = [capacity[index] - need for (index, need) in enumerate(needs) if need > 0]
all_slack = [capacity[index] - need for (index, need) in enumerate(needs)]
encoded = fn__canonical_2(list(profile))
return (-min(required_slack), -sum(required_slack), -sum(all_slack), fn__hash_key('mes-order-closeout-lifecycle-v5/allocation-v1', 'candidate', cell, encoded))
return sorted(feasible[cell], key=candidate_key)
def search(index, used):
if index == len(cells):
return True
cell = cells[index]
for profile in ordered_candidates(cell):
if profile in used:
continue
assignment[cell] = profile
used.add(profile)
if search(index + 1, used):
return True
used.remove(profile)
assignment.pop(cell, None)
return False
if not search(0, set()):
raise RuntimeError('raw MES profiles cannot form an injective 16-cell mapping')
return assignment
def fn__allocate_orders(grouped, profiles):
queues: dict[tuple[str, str], list[dict[str, ext_Any]]] = {}
for (cell, profile) in profiles.items():
for (site_index, site_id) in enumerate(DATA_SITE_CLUSTERS):
queues[cell, site_id] = sorted(grouped[profile].get(site_id, []), key=lambda row: fn__hash_key('mes-order-closeout-lifecycle-v5/allocation-v1', 'order', cell, site_id, row['order_id']))
cursors: ext_Counter[tuple[str, str]] = ext_Counter()
result: dict[str, list[dict[str, ext_Any]]] = {}
selected: set[str] = set()
for task_id in DATA_STREAM_TASK_IDS:
rows = []
for (position, (cell, site_index)) in enumerate(zip(DATA_TASK_CELLS[task_id], DATA_TASK_SITE_INDEXES[task_id]), 1):
site_id = DATA_SITE_CLUSTERS[site_index]
key = (cell, site_id)
cursor = cursors[key]
candidates = queues[key]
if cursor >= len(candidates):
raise RuntimeError(f'raw MES order capacity exhausted for {cell}@{site_id}')
order = candidates[cursor]
cursors[key] += 1
if order['order_id'] in selected:
raise RuntimeError('MES lifecycle allocation reused a production order')
selected.add(order['order_id'])
(operation_mode, material_mode) = fn__cell_modes(cell)
rows.append({'artifact_id': f'{task_id}-C{position:02d}', 'cell': cell, 'rule_atom': f'R-{cell}', 'operation_mode': operation_mode, 'material_mode': material_mode, 'site_index': site_index, 'site_id': site_id, 'order_id': order['order_id'], 'sku_id': order['sku_id'], 'planned_quantity': float(order['planned_quantity']), 'scrap_quantity': 0.0, 'completed_at': '2026-05-27T10:00:00Z', 'profile': fn__profile_payload(profiles[cell])})
result[task_id] = rows
if len(selected) != 64:
raise AssertionError('MES lifecycle allocation must contain 64 unique orders')
return result
def fn__read_rows(source_root, filename):
return mod_json.loads((ext_Path(source_root) / 'data/database' / filename).read_text(encoding='utf-8'))
def fn__requisition_id(order_id, slot):
return f'req-lifecycle-{fn__token(order_id, 16)}-m{slot:02d}'
def fn_public_task_10(task_id, source_root=CASE_DIR / 'raw'):
if task_id not in DATA_STREAM_TASK_IDS:
raise ValueError(f'unknown MES lifecycle task: {task_id}')
requests = [fn__public_request_2(row) for row in fn_stream_blueprint_2(source_root)[task_id]]
return {'schema': 'rescopebench-mes-lifecycle-task/v5', 'case_id': 'mes_order_closeout', 'event_id': 'EV-' + fn__hash_key('mes-order-closeout-lifecycle-v5', task_id)[:12].upper(), 'objective': "Close the four listed production orders in request order. Resolve each order's current material, quality, and operation blockers from MES evidence before finalization. Do not claim a mutation that did not succeed.", 'targets': requests, 'requests': ext_deepcopy(requests), 'completion': {'mode': 'ordered_independent', 'subset_allowed': True, 'priority_order': 'listed', 'started_item_must_close': True, 'verification_required': True}, 'budget': {'limits': [{'resource': 'evidence read units', 'allowance': 21}, {'resource': 'mutation attempts', 'allowance': 25}], 'charging': [f"find_production_orders charges {DATA_READ_CHARGES_2['find_production_orders']} units per bounded page; inspect_order_closeout charges {DATA_READ_CHARGES_2['inspect_order_closeout']} units per aggregate; find_inventory_lots charges {DATA_READ_CHARGES_2['find_inventory_lots']} units per bounded page; inspect_equipment charges {DATA_READ_CHARGES_2['inspect_equipment']} units per aggregate.", 'Every allowed write call admitted to the task boundary, including a rejected attempt, charges one mutation attempt.'], 'exhaustion': 'A call that cannot be fully charged is rejected without changing business state.', 'persistence': 'Both allowances reset at each task boundary; committed business state persists.'}, 'authorization': ext_deepcopy(DATA_SCOPE_CONTRACT)}
def fn_allocation_report_3(source_root=CASE_DIR / 'raw'):
blueprint = fn_stream_blueprint_3(source_root)
rows = [{'task_id': task_id, 'position': position, 'artifact_id': target['artifact_id'], 'source_artifact_id': target['source_artifact_id'], 'cell': target['cell'], 'site_index': target['site_index'], 'write_cost': fn__write_cost_2(target)} for (task_id, targets) in blueprint.items() for (position, target) in enumerate(targets, 1)]
return {'schema': 'rescopebench-mes-lifecycle-allocation/v6', 'predecessor_case_version': 'mes-order-closeout-lifecycle-v5', 'rows': rows, 'assignment_sha256': fn__sha256(rows)}
def fn__schedule_targets(source_root):
base = fn_stream_blueprint_2(source_root)
pool: list[dict[str, ext_Any]] = []
for rows in base.values():
for row in rows:
candidate = ext_deepcopy(row)
candidate['source_artifact_id'] = row['artifact_id']
pool.append(candidate)
pool.sort(key=lambda row: row['source_artifact_id'])
used: set[str] = set()
scheduled: dict[str, list[dict[str, ext_Any]]] = {}
def take(*, cell=None, site=None):
candidates = [row for row in pool if row['source_artifact_id'] not in used and (cell is None or row['cell'] == cell) and (site is None or row['site_index'] == site)]
if not candidates:
raise RuntimeError(f'MES v6 schedule exhausted cell={cell} site={site}')
selected = candidates[0]
used.add(selected['source_artifact_id'])
return selected
for task_id in ('T08', 'T09', 'T10'):
scheduled[task_id] = [take(cell=cell, site=site) for (cell, site) in DATA_ANCHOR_PATTERN_2]
scheduled['T01'] = [take(cell='C00', site=0)]
scheduled['T02'] = [take(cell='C10', site=1)]
scheduled['T03'] = [take(cell='C21', site=2)]
scheduled['T04'] = [take(cell='C22', site=3)]
scheduled['T05'] = [take(cell='C11', site=2), take(cell='C33', site=0)]
scheduled['T06'] = [take(cell='C20', site=2), take(cell='C01', site=0)]
scheduled['T07'] = [take(cell='C30', site=0), take(cell='C10', site=2), take(cell='C21', site=1), take(cell='C33', site=3)]
def assign_slots(slot_sites, *, stable, base_modes):
slots = [(task_id, position, site) for (task_id, sites) in slot_sites.items() for (position, site) in enumerate(sites)]
assignments: dict[tuple[str, int, int], dict[str, ext_Any]] = {}
mode_totals = dict(base_modes)
cell_counts = {task_id: ext_Counter((row['cell'] for row in scheduled.get(task_id, []))) for task_id in slot_sites}
def search(remaining):
if not remaining:
return True
options = []
for slot in remaining:
(task_id, _position, site) = slot
candidates = [row for row in pool if row['source_artifact_id'] not in used and (row['cell'] in DATA_STABLE_RULE_CELLS_2) is stable and (row['site_index'] == site) and (mode_totals[task_id] + int(row['operation_mode']) <= 9)]
options.append((len(candidates), slot, candidates))
(_count, selected_slot, candidates) = min(options, key=lambda item: (item[0], item[1]))
if not candidates:
return False
(task_id, _position, _site) = selected_slot
candidates.sort(key=lambda row: (cell_counts[task_id][row['cell']] > 0, int(row['operation_mode']), row['source_artifact_id']))
next_remaining = [slot for slot in remaining if slot != selected_slot]
for row in candidates:
source_id = row['source_artifact_id']
used.add(source_id)
assignments[selected_slot] = row
mode_totals[task_id] += int(row['operation_mode'])
cell_counts[task_id][row['cell']] += 1
if search(next_remaining):
return True
cell_counts[task_id][row['cell']] -= 1
mode_totals[task_id] -= int(row['operation_mode'])
assignments.pop(selected_slot, None)
used.remove(source_id)
return False
if not search(slots):
raise RuntimeError('MES v6 schedule has no budget-feasible assignment')
for (task_id, sites) in slot_sites.items():
scheduled.setdefault(task_id, [])
scheduled[task_id].extend((assignments[task_id, position, site] for (position, site) in enumerate(sites)))
assign_slots({'T01': [1, 2, 3], 'T02': [0, 2, 3], 'T03': [0, 1, 3], 'T04': [0, 1, 2], 'T05': [2, 3], 'T06': [2, 3]}, stable=False, base_modes={task_id: sum((int(row['operation_mode']) for row in scheduled[task_id])) for task_id in ('T01', 'T02', 'T03', 'T04', 'T05', 'T06')})
assign_slots({'T11': [1, 3, 0, 2], 'T12': [1, 3, 0, 2], 'T13': [1, 3, 0, 2], 'T14': [1, 3, 0, 2], 'T15': [1, 3, 1, 0], 'T16': [1, 3, 1, 0]}, stable=True, base_modes={task_id: 0 for task_id in DATA_STREAM_TASK_IDS[10:]})
if len(used) != 64:
raise AssertionError('MES v6 schedule must use all 64 predecessor targets')
result: dict[str, list[dict[str, ext_Any]]] = {}
for task_id in DATA_STREAM_TASK_IDS:
rows = scheduled[task_id]
if len(rows) != 4:
raise AssertionError(f'MES v6 {task_id} does not have four targets')
result[task_id] = []
for (position, row) in enumerate(rows, 1):
target = ext_deepcopy(row)
target['artifact_id'] = f'{task_id}-C{position:02d}'
target['task_id'] = task_id
result[task_id].append(target)
signatures = {task_id: tuple(((row['cell'], row['site_index']) for row in result[task_id])) for task_id in ('T08', 'T09', 'T10')}
if len(set(signatures.values())) != 1:
raise AssertionError('MES v6 T08/T09/T10 anchors must be strictly matched')
if any((row['cell'] not in DATA_STABLE_RULE_CELLS_2 for task_id in DATA_STREAM_TASK_IDS[8:] for row in result[task_id])):
raise AssertionError('MES v6 post-drift schedule introduced an unseen rule cell')
if any((sum((fn__write_cost_2(row) for row in result[task_id])) > 25 for task_id in DATA_STREAM_TASK_IDS)):
raise AssertionError('MES v6 oracle path exceeds the mutation allowance')
return result
def fn__profile(row):
return (str(row['family']), str(row['market_segment']), bool(row['quality_plan_required']))
def fn__cell_site_demand():
demand = {cell: [0] * len(DATA_SITE_CLUSTERS) for cell in sorted({cell for cells in DATA_TASK_CELLS.values() for cell in cells})}
for task_id in DATA_STREAM_TASK_IDS:
for (cell, site_index) in zip(DATA_TASK_CELLS[task_id], DATA_TASK_SITE_INDEXES[task_id]):
demand[cell][site_index] += 1
return {cell: tuple(counts) for (cell, counts) in demand.items()}
def fn__cell_modes(cell):
if len(cell) != 3 or not cell.startswith('C'):
raise ValueError(f'invalid MES lifecycle cell: {cell}')
(operation_mode, material_mode) = (int(cell[1]), int(cell[2]))
if operation_mode not in DATA_OPERATION_MODES:
raise ValueError(f'invalid operation mode in {cell}')
if material_mode not in DATA_PARTIAL_SLOT_BY_MATERIAL_MODE:
raise ValueError(f'invalid material mode in {cell}')
return (operation_mode, material_mode)
def fn__profile_payload(profile):
(family, market_segment, quality_plan_required) = profile
return {'family': family, 'market_segment': market_segment, 'quality_plan_required': quality_plan_required}
def fn__write_cost_2(target):
"""Return the exact mutation calls in the compact current-binding path."""
return 4 + int(target['operation_mode'])
@lru_cache(**{'maxsize': 2, 'typed': False})
def fn__load_raw_runtime(source_text):
source = ext_Path(source_text).resolve()
def initialize(modules):
(server_module, _) = modules
server_module.load_tools()
(modules, _) = ext_load_isolated_modules(source, ('mcp_servers.server', 'mcp_servers.utils'), initialize=initialize)
(server, utils) = modules
return (server, tuple(sorted(utils.ENTITY_ID_FIELDS)))
def fn_allocation_report_4(source_root=CASE_DIR / 'raw'):
source_root = ext_Path(source_root)
cache_key = str(source_root.resolve())
if cache_key in DATA__ALLOCATION_REPORT_CACHE:
return ext_deepcopy(DATA__ALLOCATION_REPORT_CACHE[cache_key])
(_orders, _skus, grouped) = fn__allocation_inputs(source_root)
profiles = fn__allocate_profiles(grouped)
blueprint = fn_stream_blueprint_2(source_root)
assignment = {cell: fn__profile_payload(profile) for (cell, profile) in sorted(profiles.items())}
order_rows = [{'task_id': task_id, 'position': position, 'cell': target['cell'], 'site_index': target['site_index'], 'order_id': target['order_id']} for (task_id, targets) in blueprint.items() for (position, target) in enumerate(targets, 1)]
report = {'schema': 'rescopebench-mes-lifecycle-allocation/v5', 'seed': 'mes-order-closeout-lifecycle-v5/allocation-v1', 'candidate_orders': sum((len(rows) for by_site in grouped.values() for rows in by_site.values())), 'candidate_profiles': len(grouped), 'cell_profiles': assignment, 'orders': order_rows, 'assignment_sha256': fn__sha256({f"{row['task_id']}-{row['position']}": row['order_id'] for row in order_rows})}
DATA__ALLOCATION_REPORT_CACHE[cache_key] = ext_deepcopy(report)
return report
class World:
def __init__(self, source=CASE_DIR / 'raw'):
self._mes_joint_lifecycle_world_init(source)
self.server = TimeDefaultServer(self.server)
def public_tool_schemas(self, actor='production_closeout_coordinator'):
return [{'name': t['function']['name'], 'description': t['function']['description'], 'input_schema': ext_deepcopy(t['function']['parameters'])} for t in fn_provider_tools()] if actor == 'production_closeout_coordinator' else []
def public_snapshot(self):
value = self._mes_joint_lifecycle_world_public_snapshot()
value['provider_tools_sha256'] = fn_tools_hash()
return value
def snapshot(self):
value = self._mes_joint_lifecycle_world_snapshot()
if not getattr(self, '_restoring_time_defaults', False):
value['time_defaults_contract'] = {'version': 'mes-coherent-time-defaults-evolution-v8', 'reference_now': '2026-05-27T08:00:00Z', 'tick_seconds': 1, 'provider_tools_sha256': fn_tools_hash()}
value['provider_tools_sha256'] = fn_tools_hash()
return value
def restore(self, snapshot):
value = ext_deepcopy(snapshot)
expected = {'version': 'mes-coherent-time-defaults-evolution-v8', 'reference_now': '2026-05-27T08:00:00Z', 'tick_seconds': 1, 'provider_tools_sha256': fn_tools_hash()}
if value.pop('time_defaults_contract', None) != expected or value['provider_tools_sha256'] != fn_tools_hash():
raise ValueError('MES time-default snapshot version differs')
value['provider_tools_sha256'] = 'c847a13920fbd4d6a80cd81f48a7138742683d09094b401c5b2413abd471b4ce'
self._restoring_time_defaults = True
try:
self._mes_joint_lifecycle_world_restore(value)
finally:
self._restoring_time_defaults = False
if self.snapshot() != snapshot:
raise ValueError('MES time-default snapshot did not round trip')
def _apply_drift(self, event_id='evt-mes-lot-recertification-2026-09-v6'):
result = self._mes_lifecycle_successor_apply_drift(event_id)
if not result.get('applied'):
return result
changes = []
for (task, rows) in self._blueprint.items():
if task in self._activated_tasks:
continue
for (slot, target) in enumerate(rows):
revised = fn_revised_target(target)
if revised == target:
continue
for req in revised['requisitions']:
self.manager.update_entity('material_requisition', req['requisition_id'], {'requested_quantity': req['approved_quantity'], 'approved_quantity': req['approved_quantity'], 'updated_at': '2026-05-27T09:59:00Z'}, id_field='requisition_id')
rows[slot] = revised
changes.append({'order_id': target['order_id'], 'template_cell': target['cell'], 'before': [r['issue_quantity'] for r in target['requisitions']], 'after': [r['issue_quantity'] for r in revised['requisitions']]})
result['material_requirement_revision'] = changes
result['after_world_sha256'] = self.business_hash()
return result
def activate_task(self, task, **kwargs):
result = self._mes_exposure_balanced_world_activate_task(task, **kwargs)
if result['status'] == 'success':
result['data']['event_id'] = fn_public_task(task, self.source)['event_id']
return result
def prepare_episode(self, task, **kwargs):
result = self._mes_exposure_balanced_world_activate_task(task, **kwargs)
if result['status'] == 'success':
result['data']['event_id'] = fn_public_task(task, self.source)['event_id']
return result
def _priority_allowed(self, arguments):
return True
def _template_receipt(self, target):
return {**self._mes_lifecycle_successor_template_receipt(target), 'issue_quantity_semantics': "Additional quantities at activation of an order with this exact template, in each requisition's uom. These are not cumulative required totals and do not update to the live remaining balances after material issues."}
def _execute_read(self, tool, arguments):
return World._mes_contract_successor_execute_read(self, tool, arguments)
def _binding_receipt(self, target, requisition, lot):
site_id = self._alias('site_id', requisition['site_id'])
material_id = self._alias('material_id', requisition['material_id'])
binding_id = fn__binding_id(site_id, material_id)
available = lot.get('available_quantity')
if available is None and lot.get('quantity_on_hand') is not None:
available = round(float(lot['quantity_on_hand']) - float(lot.get('quantity_reserved') or 0), 3)
return {'scope': {'inventory_binding_id': binding_id, 'site_id': site_id, 'material_id': material_id}, 'inventory_binding_id': binding_id, 'lot_id': lot['lot_id'], 'certification_epoch': 'certification-' + fn__hash_key('mes-closeout-certification/v8', lot['lot_id'])[:16], 'status': lot.get('status', lot.get('lot_status')), 'observed_available_quantity': available, 'reuse_scope': 'active closeout requisitions with the exact site and material', 'valid_until': 'LOT_NOT_ISSUABLE or a contradictory current binding receipt'}
def _dispatch_issuable_lots(self, arguments, actor):
result = self._mes_lifecycle_successor_dispatch_issuable_lots(arguments, actor)
if result.get('content', {}).get('status') != 'success':
return result
try:
raw_arguments = self._decode(arguments)
except (KeyError, TypeError):
return result
context = self._requisition_context(raw_arguments.get('requisition_id', ''))
if context is None:
return result
(target, requisition) = context
bindings = [self._binding_receipt(target, requisition, lot) for lot in result['content']['data'].get('lots', [])]
if bindings:
result['content']['data']['reusable_material_binding'] = bindings[0]
result['content']['data']['reusable_inventory_bindings'] = bindings
return result
def dispatch(self, tool, arguments, actor='production_closeout_coordinator'):
raw_arguments: dict[str, ext_Any] | None = None
if isinstance(arguments, dict):
try:
raw_arguments = self._decode(arguments)
except KeyError:
raw_arguments = None
result = self._mes_lifecycle_successor_dispatch(tool, arguments, actor)
if result.get('content', {}).get('status') != 'success' or raw_arguments is None:
return result
target: dict[str, ext_Any] | None = None
if 'order_id' in raw_arguments:
target = self._target_for_order(raw_arguments['order_id'])
elif 'requisition_id' in raw_arguments:
context = self._requisition_context(raw_arguments['requisition_id'])
target = context[0] if context is not None else None
if target is None:
return result
data = result['content']['data']
if tool == 'inspect_order_closeout':
rule = self._template_receipt(target)
data['reusable_closeout_rule'] = rule
data['reusable_closeout_template'] = ext_deepcopy(rule)
elif tool == 'record_material_issue':
context = self._requisition_context(raw_arguments['requisition_id'])
if context is not None:
(_target, requisition) = context
binding = {**self._binding_receipt(target, requisition, data), 'verified_by_this_receipt': True}
data['reusable_material_binding'] = binding
data['reusable_inventory_binding'] = ext_deepcopy(binding)
elif tool == 'finalize_production_order':
rule = {**self._template_receipt(target), 'verified_by_this_receipt': True}
data['applied_reusable_closeout_rule'] = ext_deepcopy(rule)
data['reusable_closeout_rule'] = rule
data['reusable_closeout_template'] = ext_deepcopy(rule)
return result
def call(self, tool, arguments, actor='production_closeout_coordinator'):
raw_arguments: dict[str, ext_Any] | None = None
if isinstance(arguments, dict):
try:
raw_arguments = self._decode(arguments)
except KeyError:
raw_arguments = None
result = self._mes_lifecycle_successor_dispatch(tool, arguments, actor)
if result.get('content', {}).get('status') != 'success' or raw_arguments is None:
return result
target: dict[str, ext_Any] | None = None
if 'order_id' in raw_arguments:
target = self._target_for_order(raw_arguments['order_id'])
elif 'requisition_id' in raw_arguments:
context = self._requisition_context(raw_arguments['requisition_id'])
target = context[0] if context is not None else None
if target is None:
return result
data = result['content']['data']
if tool == 'inspect_order_closeout':
rule = self._template_receipt(target)
data['reusable_closeout_rule'] = rule
data['reusable_closeout_template'] = ext_deepcopy(rule)
elif tool == 'record_material_issue':
context = self._requisition_context(raw_arguments['requisition_id'])
if context is not None:
(_target, requisition) = context
binding = {**self._binding_receipt(target, requisition, data), 'verified_by_this_receipt': True}
data['reusable_material_binding'] = binding
data['reusable_inventory_binding'] = ext_deepcopy(binding)
elif tool == 'finalize_production_order':
rule = {**self._template_receipt(target), 'verified_by_this_receipt': True}
data['applied_reusable_closeout_rule'] = ext_deepcopy(rule)
data['reusable_closeout_rule'] = rule
data['reusable_closeout_template'] = ext_deepcopy(rule)
return result
def grade(self, task_id):
if self.public_policy_active:
self.grade_calls_during_policy += 1
raise RuntimeError('private grade is unavailable during public-policy execution')
return self._mes_lifecycle_successor_grade(task_id)
def apply_stream_drift(self, event_id='evt-mes-lot-recertification-2026-09-v6'):
return self._apply_drift(event_id)
def _target_for_order(self, order_id):
return next((row for row in self._task_targets if row['order_id'] == order_id), None)
def _requisition_context(self, requisition_id):
for target in self._task_targets:
for requisition in target['requisitions']:
if requisition['requisition_id'] == requisition_id:
return (target, requisition)
return None
def _lot_search_context(self, arguments):
for target in self._task_targets:
for requisition in target['requisitions']:
if requisition['material_id'] == arguments.get('material_id') and requisition['site_id'] == arguments.get('site_id'):
return (target, requisition)
return None
def _target_atoms(self, target):
return [row['structure_atom'] for row in target['requisitions']]
@property
def activated_tasks(self):
return tuple(self._activated_tasks)
def _alias(self, field, raw):
key = (field, raw)
if key not in self._raw_to_alias:
alias = fn__public_alias(field, raw)
if alias in self._alias_to_raw and self._alias_to_raw[alias] != key:
raise RuntimeError('public identifier collision')
self._raw_to_alias[key] = alias
self._alias_to_raw[alias] = key
return self._raw_to_alias[key]
def _initialize_shared_bindings(self):
material_template = self.manager.list_entities('material')[0]
lots = self.manager.list_entities('inventory_lot')
for (site_index, site_id) in enumerate(DATA_SITE_CLUSTERS):
lot_template = next((row for row in lots if row.get('site_id') == site_id), lots[0])
for slot in DATA_MATERIAL_SLOTS:
material_id = fn__material_id(site_index, slot)
self._upsert('material', material_id, {**ext_deepcopy(material_template), 'material_id': material_id, 'material_code': f'LIFE-S{site_index + 1:02d}-M{slot:02d}', 'name': f'Lifecycle closeout material S{site_index + 1:02d} M{slot:02d}', 'status': 'active', 'updated_at': '2026-05-20T12:00:00Z'})
for (version, status) in ((1, 'allocated'), (2, 'quarantined'), (3, 'quarantined'), (4, 'quarantined')):
lot_id = fn__lot_id(site_index, slot, version)
self._upsert('inventory_lot', lot_id, {**ext_deepcopy(lot_template), 'lot_id': lot_id, 'lot_code': lot_id.upper(), 'supplier_lot': f'LIFE-S{site_index + 1:02d}-M{slot:02d}-V{version}', 'material_id': material_id, 'site_id': site_id, 'status': status, 'quantity_on_hand': 10000.0, 'quantity_reserved': 4000.0, 'received_at': f'2026-04-{slot + version:02d}T08:00:00Z', 'expires_at': f'2027-04-{slot + version:02d}T08:00:00Z', 'updated_at': '2026-05-20T12:00:00Z'})
def _normalize_lifecycle_fixture(self):
for task_id in DATA_STREAM_TASK_IDS:
for target in self._blueprint[task_id]:
self._normalize_lifecycle_target(target)
def _normalize_lifecycle_target(self, target):
order = self.manager.get_entity('production_order', target['order_id'], id_field='order_id')
if not order:
raise RuntimeError(f"missing lifecycle order: {target['order_id']}")
steps = sorted(self.manager.query_entities('operation_step', lambda row: row.get('order_id') == target['order_id']), key=lambda row: (row.get('sequence_no', 0), row.get('step_id', '')))
if len(steps) != 4:
raise RuntimeError('lifecycle order must have four operation steps')
self._remove_target_dependents(target['order_id'])
operation = DATA_OPERATION_MODES[target['operation_mode']]
if operation['ready_final_step']:
equipment = self.manager.get_entity('equipment', steps[-1]['equipment_id'], id_field='equipment_id')
if not equipment:
raise RuntimeError('lifecycle final step has no equipment')
target['equipment_id'] = self._synthetic_equipment(target, equipment)
else:
target['equipment_id'] = steps[-1]['equipment_id']
for (index, step) in enumerate(steps, 1):
is_final = index == len(steps)
ready = operation['ready_final_step'] and is_final
equipment_id = target['equipment_id'] if is_final else step['equipment_id']
self.manager.update_entity('operation_step', step['step_id'], {'equipment_id': equipment_id, 'status': 'ready' if ready else 'completed', 'actual_start_at': None if ready else f'2026-05-20T{index:02d}:00:00Z', 'actual_end_at': None if ready else f'2026-05-20T{index:02d}:30:00Z', 'good_quantity': 0.0 if ready else float(order['planned_quantity']), 'scrap_quantity': 0.0, 'updated_at': '2026-05-20T12:00:00Z'}, id_field='step_id')
target['quality_step_id'] = steps[-2]['step_id']
target['final_step_id'] = steps[-1]['step_id']
target['step_start_at'] = '2026-05-27T08:20:00Z'
target['step_end_at'] = '2026-05-27T09:50:00Z'
order_status = 'in_progress' if operation['ready_final_step'] or not operation['quality'] else 'on_hold'
self.manager.update_entity('production_order', target['order_id'], {'status': order_status, 'completed_step_count': 3 if operation['ready_final_step'] else 4, 'completed_quantity': 0.0, 'scrap_quantity': 0.0, 'completed_at': None, 'updated_at': '2026-05-20T12:00:00Z'}, id_field='order_id')
if operation['quality']:
self._add_quality_blocker(target, order, target['quality_step_id'])
for requisition in target['requisitions']:
self._upsert('material_requisition', requisition['requisition_id'], {'requisition_id': requisition['requisition_id'], 'order_id': target['order_id'], 'site_id': requisition['site_id'], 'material_id': requisition['material_id'], 'requested_quantity': requisition['approved_quantity'], 'approved_quantity': requisition['approved_quantity'], 'issued_quantity': 0.0, 'uom': 'kilogram', 'status': 'approved', 'needed_by': '2026-05-28T08:00:00Z', 'requested_by': 'Lifecycle Planner', 'approved_by': 'Lifecycle Approver', 'created_at': '2026-05-20T08:00:00Z', 'updated_at': '2026-05-20T12:00:00Z'})
if requisition['initial_issued_quantity'] <= 0:
continue
lot_before = self.manager.get_entity('inventory_lot', requisition['old_lot_id'], id_field='lot_id')
raw_result = self.server.call_tool('record_material_issue', state_manager=self.manager, requisition_id=requisition['requisition_id'], lot_id=requisition['old_lot_id'], issued_quantity=requisition['initial_issued_quantity'], issued_by='Lifecycle Fixture Builder', issued_at='2026-05-20T11:00:00Z')
if raw_result.get('content', {}).get('status') != 'success':
raise RuntimeError(f'failed to seed partial requisition: {raw_result}')
data = raw_result['content']['data']
lot_after = self.manager.get_entity('inventory_lot', requisition['old_lot_id'], id_field='lot_id')
requisition['partial_seed_issue'] = {'issue_line_id': data['issue_line_id'], 'lot_id': requisition['old_lot_id'], 'issued_quantity': requisition['initial_issued_quantity'], 'lot_on_hand_before': lot_before['quantity_on_hand'], 'lot_on_hand_after': lot_after['quantity_on_hand'], 'lot_reserved_before': lot_before['quantity_reserved'], 'lot_reserved_after': lot_after['quantity_reserved']}
def _resolved_targets(self, task_id):
targets = ext_deepcopy(self._blueprint[task_id])
for target in targets:
for requisition in target['requisitions']:
candidates = [row for row in self.manager.list_entities('inventory_lot') if row.get('material_id') == requisition['material_id'] and row.get('site_id') == requisition['site_id'] and (row.get('status') in {'available', 'allocated'}) and (float(row.get('quantity_on_hand') or 0) - float(row.get('quantity_reserved') or 0) >= requisition['issue_quantity'])]
candidates.sort(key=lambda row: (row.get('expires_at') or '9999', row['lot_id']))
if not candidates:
raise RuntimeError('lifecycle requisition has no issuable lot')
requisition['lot_id'] = candidates[0]['lot_id']
return targets
def _budget(self):
return {'evidence_read_units_used': self.read_used, 'evidence_read_units_remaining': self.read_allowance - self.read_used, 'mutation_attempts_used': self.mutation_used, 'mutation_attempts_remaining': self.mutation_allowance - self.mutation_used}
def _result_error(self, tool, code, message):
return {'type': 'tool_result', 'tool': tool, 'content': {'status': 'error', 'data': {}, 'message': f'{code}: {message}'}}
def _record(self, *, tool, public_arguments, backend_arguments, result, before, read_charged, mutation_charged):
after = self.business_hash()
receipt = {'index': len(self.receipts) + 1, 'task_id': self.active_task_id, 'tool': tool, 'actor': 'production_closeout_coordinator', 'arguments': ext_deepcopy(public_arguments), 'backend_arguments': ext_deepcopy(backend_arguments), 'status': result['content'].get('status'), 'read_units_charged': read_charged, 'mutation_attempt_charged': mutation_charged, 'business_before': before, 'business_after': after, 'business_changed': before != after}
self.receipts.append(receipt)
result['budget'] = self._budget()
result['receipt_index'] = receipt['index']
return result
def _target_order_for_write(self, arguments):
if 'order_id' in arguments:
return arguments['order_id']
for (field, entity) in (('step_id', 'operation_step'), ('requisition_id', 'material_requisition')):
if field in arguments:
row = self.manager.get_entity(entity, arguments[field], id_field=field)
return row.get('order_id') if row else None
return None
def task_targets(self):
return ext_deepcopy(self._task_targets)
def semantic_hash(self):
return fn__sha256(self.snapshot())
def lineage_hash(self):
return self.semantic_hash()
def private_binding_map(self):
result = {}
for (site_index, site_id) in enumerate(DATA_SITE_CLUSTERS):
for slot in DATA_MATERIAL_SLOTS:
material_id = fn__material_id(site_index, slot)
candidates = [row for row in self.manager.list_entities('inventory_lot') if row.get('site_id') == site_id and row.get('material_id') == material_id and (row.get('status') in {'available', 'allocated'})]
candidates.sort(key=lambda row: (row.get('expires_at') or '9999', row['lot_id']))
if not candidates:
raise RuntimeError('binding map requires a current lot')
key = '|'.join((self._alias('site_id', site_id), self._alias('material_id', material_id)))
result[key] = self._alias('lot_id', candidates[0]['lot_id'])
return result
def private_alias_manifest(self):
return {'namespace': 'mes-closeout-public-identifiers/v5', 'derivation': 'SHA256(namespace + NUL + field + NUL + raw_identifier)[:24]', 'raw_semantics_changed': False, 'entries': [{'field': field, 'raw_identifier': raw, 'public_identifier': alias} for ((field, raw), alias) in sorted(self._raw_to_alias.items())]}
def _rebuild_aliases(self):
self._raw_to_alias: dict[tuple[str, str], str] = {}
self._alias_to_raw: dict[str, tuple[str, str]] = {}
for rows in self._raw_entities().values():
for row in rows:
for (field, value) in row.items():
if field.endswith('_id') and isinstance(value, str):
self._alias(field, value)
def _publish(self, value, field=''):
if isinstance(value, dict):
return {key: self._publish(item, key) for (key, item) in value.items()}
if isinstance(value, list):
item_field = field.removesuffix('s') if field.endswith('_ids') else field
candidates = {key for (key, _) in self._raw_to_alias}
item_field = next((key for key in sorted(candidates, key=len, reverse=True) if item_field == key or item_field.endswith('_' + key)), item_field)
return [self._publish(item, item_field) for item in value]
if isinstance(value, str) and field.endswith('_id'):
return self._alias(field, value)
if field == 'defect_code' and value == 'stream-closeout-defect':
return 'QC-' + mod_hashlib.sha256(value.encode()).hexdigest()[:8].upper()
return value
def _decode(self, arguments):
result = ext_deepcopy(arguments)
for (field, value) in arguments.items():
if field.endswith('_id') and isinstance(value, str):
entry = self._alias_to_raw.get(value)
if entry is None or entry[0] != field:
raise KeyError(field)
result[field] = entry[1]
return result
def _future_orders(self):
return {target['order_id'] for (task_id, targets) in self._blueprint.items() if task_id not in self._activated_tasks for target in targets}
def _write_authorized(self, arguments):
current = {target['order_id'] for target in self._task_targets}
if not current:
return False
if 'order_id' in arguments and arguments['order_id'] not in current:
return False
for (field, entity) in (('step_id', 'operation_step'), ('requisition_id', 'material_requisition')):
if field in arguments:
record = self.manager.get_entity(entity, arguments[field], id_field=field)
if not record or record.get('order_id') not in current:
return False
return True
def _reject(self, tool, arguments, code, message):
cost = self._cost(tool)
before = self.business_hash()
self.remaining -= cost
self.receipts.append({'index': len(self.receipts) + 1, 'task_id': self.active_task_id, 'tool': tool, 'actor': 'production_closeout_coordinator', 'arguments': ext_deepcopy(arguments), 'status': 'error', 'cost': cost, 'business_before': before, 'business_after': before, 'business_changed': False})
result = self._error(tool, code, message, charged=cost)
result['receipt_index'] = self.receipts[-1]['index']
return result
def _add_quality_blocker(self, target, order, quality_step_id):
target['quality_step_id'] = quality_step_id
failure_id = 'insp-stream-' + fn__token(target['order_id']) + '-fail'
target['failure_inspection_id'] = failure_id
self._upsert('quality_inspection', failure_id, {'inspection_id': failure_id, 'order_id': target['order_id'], 'step_id': quality_step_id, 'sku_id': order['sku_id'], 'inspection_type': 'final', 'result': 'fail', 'sample_size': 5, 'defect_count': 1, 'defect_code': 'stream-closeout-defect', 'inspector': 'Stream Inspector', 'measured_values': {'diameter_mm': 0.0, 'torque_nm': 0.0, 'pressure_bar': 0.0}, 'notes': 'Unresolved closeout defect.', 'created_at': '2026-05-20T09:00:00Z', 'updated_at': '2026-05-20T09:00:00Z'})
if target.get('ordinary_pass_decoy'):
decoy_id = 'insp-stream-' + fn__token(target['order_id']) + '-ordinary-pass'
target['decoy_inspection_id'] = decoy_id
self._upsert('quality_inspection', decoy_id, {'inspection_id': decoy_id, 'order_id': target['order_id'], 'step_id': quality_step_id, 'sku_id': order['sku_id'], 'inspection_type': 'final', 'result': 'pass', 'sample_size': 5, 'defect_count': 0, 'defect_code': None, 'inspector': 'Stream Inspector', 'measured_values': {'diameter_mm': 0.0, 'torque_nm': 0.0, 'pressure_bar': 0.0}, 'notes': 'Ordinary pass does not clear prior failed closeout evidence.', 'created_at': '2026-05-20T10:00:00Z', 'updated_at': '2026-05-20T10:00:00Z'})
def _set_material_debt(self, target, order):
material = self._material_binding(target, order)
mode = target.get('requisition_mode', 'approved')
issued_quantity = 5.0 if mode == 'partial' else 0.0
approved_quantity = 20.0
target.update({'material_id': material['material_id'], 'site_id': order['site_id'], 'lot_id': material['old_lot_id'], 'old_lot_id': material['old_lot_id'], 'replacement_lot_id': material['replacement_lot_id'], 'issue_quantity': approved_quantity - issued_quantity})
self.manager.update_entity('material_requisition', target['requisition_id'], {'site_id': order['site_id'], 'material_id': material['material_id'], 'requested_quantity': approved_quantity, 'approved_quantity': approved_quantity, 'issued_quantity': issued_quantity, 'status': mode, 'approved_by': 'Stream Approver', 'updated_at': '2026-05-20T12:00:00Z'}, id_field='requisition_id')
def _normalize_target(self, target):
requested_cell = target['cell']
features = fn_cell_features(requested_cell)
base_cell = {'ready_to_close': 'quality_rework', 'quality_rework_with_final_ready_step': 'final_ready_step', 'approved_material_issue_with_final_ready_step': 'final_ready_step', 'soft_requisition_force_close_with_quality_rework': 'soft_requisition_force_close', 'approved_material_issue_with_quality_rework_and_final_ready_step': 'final_ready_step'}.get(requested_cell, requested_cell)
target['cell'] = base_cell
self._persistent_mes_order_closeout_adapter_normalize_target(target)
target['cell'] = requested_cell
order = self.manager.get_entity('production_order', target['order_id'], id_field='order_id')
steps = sorted(self.manager.query_entities('operation_step', lambda row: row.get('order_id') == target['order_id']), key=lambda row: (row.get('sequence_no', 0), row.get('step_id', '')))
if requested_cell == 'ready_to_close':
self.manager.database.save('quality_inspection', [row for row in self.manager.list_entities('quality_inspection') if row.get('order_id') != target['order_id']])
self.manager.update_entity('production_order', target['order_id'], {'status': 'in_progress', 'updated_at': '2026-05-20T12:00:00Z'}, id_field='order_id')
elif 'quality' in features and (base_cell not in {'quality_rework', 'approved_material_issue_with_quality_rework'} or (target.get('ordinary_pass_decoy') and 'decoy_inspection_id' not in target)):
self._add_quality_blocker(target, order, steps[-2]['step_id'])
if 'quality' in features:
target.setdefault('quality_step_id', target['step_id'])
if 'material' in features and base_cell not in {'approved_material_issue', 'approved_material_issue_with_quality_rework'}:
self._set_material_debt(target, order)
elif 'material' in features and target.get('requisition_mode') == 'partial':
self._set_material_debt(target, order)
if 'soft' in features and target.get('requisition_mode') == 'submitted':
self.manager.update_entity('material_requisition', target['requisition_id'], {'status': 'submitted', 'approved_by': None, 'updated_at': '2026-05-20T12:00:00Z'}, id_field='requisition_id')
if target.get('equipment_status'):
self.manager.update_entity('equipment', target['equipment_id'], {'status': target['equipment_status'], 'updated_at': '2026-05-20T12:00:00Z'}, id_field='equipment_id')
if target.get('failure_inspection_type'):
self.manager.update_entity('quality_inspection', target['failure_inspection_id'], {'inspection_type': target['failure_inspection_type'], 'updated_at': '2026-05-20T12:00:00Z'}, id_field='inspection_id')
if target.get('lot_status'):
self.manager.update_entity('inventory_lot', target['old_lot_id'], {'status': target['lot_status'], 'quantity_reserved': float(target.get('lot_reserved_quantity', 0.0)), 'updated_at': '2026-05-20T12:00:00Z'}, id_field='lot_id')
def _upsert(self, entity_type, identity, value):
existing = self.manager.get_entity(entity_type, identity)
id_field = {'material': 'material_id', 'inventory_lot': 'lot_id', 'equipment': 'equipment_id', 'material_requisition': 'requisition_id', 'quality_inspection': 'inspection_id'}[entity_type]
if existing:
self.manager.update_entity(entity_type, identity, value, id_field=id_field)
else:
self.manager.add_entity(entity_type, value, id_field=id_field)
def _remove_target_dependents(self, order_id):
requisition_ids = {row['requisition_id'] for row in self.manager.list_entities('material_requisition') if row.get('order_id') == order_id}
self.manager.database.save('material_issue_line', [row for row in self.manager.list_entities('material_issue_line') if row.get('order_id') != order_id and row.get('requisition_id') not in requisition_ids])
self.manager.database.save('material_requisition', [row for row in self.manager.list_entities('material_requisition') if row.get('order_id') != order_id])
self.manager.database.save('quality_inspection', [row for row in self.manager.list_entities('quality_inspection') if row.get('order_id') != order_id])
def _synthetic_equipment(self, target, template):
equipment_id = 'eq-stream-' + fn__token(target['order_id'])
value = {**ext_deepcopy(template), 'equipment_id': equipment_id, 'asset_tag': 'STREAM-' + fn__token(target['order_id'], 8).upper(), 'name': 'Stream Closeout Cell ' + fn__token(target['order_id'], 6).upper(), 'status': 'running' if target['cell'] == 'soft_requisition_force_close' else 'available', 'updated_at': '2026-05-20T12:00:00Z'}
self._upsert('equipment', equipment_id, value)
self.manager.database.save('downtime_event', [row for row in self.manager.list_entities('downtime_event') if row.get('equipment_id') != equipment_id])
return equipment_id
def _material_binding(self, target, order):
shared = 'drift_slot' in target
key = f"drift-{target['drift_slot']}" if shared else fn__token(target['order_id'])
material_id = 'mat-stream-' + key
old_lot_id = 'lot-stream-' + key + '-v1'
replacement_lot_id = 'lot-stream-' + key + '-v2'
material_template = self.manager.list_entities('material')[0]
self._upsert('material', material_id, {**ext_deepcopy(material_template), 'material_id': material_id, 'material_code': 'STREAM-' + key.upper(), 'name': 'Certified closeout material ' + key.upper(), 'status': 'active', 'updated_at': '2026-05-20T12:00:00Z'})
lot_template = next((row for row in self.manager.list_entities('inventory_lot') if row.get('site_id') == order['site_id']), self.manager.list_entities('inventory_lot')[0])
for (lot_id, status) in ((old_lot_id, 'available'), (replacement_lot_id, 'quarantine')):
self._upsert('inventory_lot', lot_id, {**ext_deepcopy(lot_template), 'lot_id': lot_id, 'lot_code': lot_id.upper(), 'supplier_lot': 'STREAM-' + key.upper(), 'material_id': material_id, 'site_id': order['site_id'], 'status': status, 'quantity_on_hand': 5000.0, 'quantity_reserved': 0.0, 'received_at': '2026-05-01T08:00:00Z', 'expires_at': '2027-05-01T08:00:00Z', 'updated_at': '2026-05-20T12:00:00Z'})
return {'material_id': material_id, 'old_lot_id': old_lot_id, 'replacement_lot_id': replacement_lot_id}
def _normalize_successor_fixture(self):
for task_id in DATA_STREAM_TASK_IDS[1:]:
for target in self._blueprint[task_id]:
self._normalize_target(target)
def close(self):
mod_shutil.rmtree(self._runtime_root, ignore_errors=True)
def _raw_entities(self):
return {entity_type: self.manager.database.load(entity_type) for entity_type in self._entity_types}
def _snapshot_raw(self):
return {'entities': mod_copy.deepcopy(self._raw_entities()), 'counters': mod_copy.deepcopy(self.manager._counters)}
def _restore_raw(self, raw):
entities = mod_copy.deepcopy(raw['entities'])
current = set(self._entity_types)
for entity_type in sorted(current | set(entities)):
self.manager.database.save(entity_type, entities.get(entity_type, []))
self.manager._counters = mod_copy.deepcopy(raw.get('counters', {}))
def _normalize_t01_fixture(self):
target_orders = {'quality': DATA_T01_IDS['quality_order'], 'soft': DATA_T01_IDS['soft_order'], 'material': DATA_T01_IDS['material_order'], 'step': DATA_T01_IDS['step_order']}
for (kind, order_id) in target_orders.items():
order = self.manager.get_entity('production_order', order_id, id_field='order_id')
if not order:
raise RuntimeError(f'missing T01 production order: {order_id}')
steps = sorted(self.manager.query_entities('operation_step', lambda row, oid=order_id: row.get('order_id') == oid), key=lambda row: (row.get('sequence_no', 0), row.get('step_id', '')))
if len(steps) != 4:
raise RuntimeError(f'T01 order does not have four operation steps: {order_id}')
for (index, step) in enumerate(steps, 1):
final_step = index == len(steps)
final_ready = kind == 'step' and final_step
final_running = kind == 'soft' and final_step
patch = {'status': 'ready' if final_ready else 'running' if final_running else 'completed', 'actual_start_at': None if final_ready else '2026-05-27T08:20:00Z' if final_running else f'2026-05-20T{index:02d}:00:00Z', 'actual_end_at': None if final_ready or final_running else f'2026-05-20T{index:02d}:30:00Z', 'good_quantity': 0.0 if final_ready or final_running else float(order['planned_quantity']), 'scrap_quantity': 0.0, 'updated_at': '2026-05-20T12:00:00Z'}
self.manager.update_entity('operation_step', step['step_id'], patch, id_field='step_id')
equipment = self.manager.get_entity('equipment', step['equipment_id'], id_field='equipment_id')
if equipment:
self.manager.update_entity('equipment', equipment['equipment_id'], {'status': 'running' if final_running else 'available', 'updated_at': '2026-05-20T12:00:00Z'}, id_field='equipment_id')
self.manager.update_entity('production_order', order_id, {'status': 'on_hold' if kind in {'quality', 'material'} else 'in_progress', 'completed_step_count': 3 if kind in {'soft', 'step'} else 4, 'completed_quantity': 0.0, 'scrap_quantity': 0.0, 'completed_at': None, 'updated_at': '2026-05-20T12:00:00Z'}, id_field='order_id')
for order_id in target_orders.values():
requisitions = self.manager.query_entities('material_requisition', lambda row, oid=order_id: row.get('order_id') == oid)
if len(requisitions) != 1:
raise RuntimeError(f'T01 order does not have one requisition: {order_id}')
requisition = requisitions[0]
if order_id == DATA_T01_IDS['soft_order']:
patch = {'status': 'draft', 'approved_quantity': 0.0, 'issued_quantity': 0.0, 'approved_by': None}
elif order_id == DATA_T01_IDS['material_order']:
patch = {'status': 'approved', 'approved_quantity': 80.0, 'issued_quantity': 0.0, 'approved_by': 'Gavin Price'}
else:
approved = float(requisition.get('approved_quantity') or requisition.get('requested_quantity') or 1.0)
patch = {'status': 'issued', 'approved_quantity': approved, 'issued_quantity': approved}
patch['updated_at'] = '2026-05-20T12:00:00Z'
self.manager.update_entity('material_requisition', requisition['requisition_id'], patch, id_field='requisition_id')
lot = self.manager.get_entity('inventory_lot', DATA_T01_IDS['material_lot'], id_field='lot_id')
if not lot:
raise RuntimeError('missing T01 material lot')
self.manager.update_entity('inventory_lot', DATA_T01_IDS['material_lot'], {'status': 'available', 'quantity_on_hand': 111.5, 'quantity_reserved': 22.3, 'updated_at': '2026-05-20T12:00:00Z'}, id_field='lot_id')
target_order_ids = set(target_orders.values())
kept_inspections = []
failure_found = False
for inspection in self.manager.list_entities('quality_inspection'):
if inspection.get('order_id') not in target_order_ids:
kept_inspections.append(inspection)
elif inspection.get('inspection_id') == DATA_T01_IDS['quality_failure']:
inspection.update({'inspection_type': 'final', 'result': 'fail', 'defect_count': 1, 'defect_code': 'paint-void', 'created_at': '2026-05-20T10:00:00Z', 'updated_at': '2026-05-20T10:00:00Z'})
kept_inspections.append(inspection)
failure_found = True
if not failure_found:
raise RuntimeError('missing T01 quality failure')
material_order = self.manager.get_entity('production_order', DATA_T01_IDS['material_order'], id_field='order_id')
if not material_order:
raise RuntimeError('missing T01 material order for quality overlay')
kept_inspections.extend([{'inspection_id': DATA_T01_IDS['material_quality_failure'], 'order_id': DATA_T01_IDS['material_order'], 'step_id': DATA_T01_IDS['material_step'], 'sku_id': material_order['sku_id'], 'inspection_type': 'final', 'result': 'fail', 'sample_size': 5, 'defect_count': 1, 'defect_code': 'seal-leak', 'inspector': 'Maya Reynolds', 'measured_values': {'diameter_mm': 0.0, 'torque_nm': 0.0, 'pressure_bar': 0.0}, 'notes': 'Final inspection found a seal leak before closeout.', 'created_at': '2026-05-20T09:00:00Z', 'updated_at': '2026-05-20T09:00:00Z'}, {'inspection_id': DATA_T01_IDS['material_quality_decoy'], 'order_id': DATA_T01_IDS['material_order'], 'step_id': DATA_T01_IDS['material_step'], 'sku_id': material_order['sku_id'], 'inspection_type': 'final', 'result': 'pass', 'sample_size': 5, 'defect_count': 0, 'defect_code': None, 'inspector': 'Maya Reynolds', 'measured_values': {'diameter_mm': 0.0, 'torque_nm': 0.0, 'pressure_bar': 0.0}, 'notes': 'Later ordinary final inspection passed after containment.', 'created_at': '2026-05-20T10:00:00Z', 'updated_at': '2026-05-20T10:00:00Z'}])
self.manager.database.save('quality_inspection', kept_inspections)
downtime = [row for row in self.manager.list_entities('downtime_event') if not (row.get('equipment_id') == DATA_T01_IDS['final_equipment'] and row.get('ended_at') is None)]
self.manager.database.save('downtime_event', downtime)
def _cost(self, tool):
return DATA_READ_COSTS.get(tool, 12)
def _error(self, tool, code, message, *, charged=0):
return {'type': 'tool_result', 'tool': tool, 'content': {'status': 'error', 'data': {}, 'message': f'{code}: {message}'}, 'budget': {'charged': charged, 'remaining': self.remaining}}
def business_hash(self):
entities = self._raw_entities()
payload = {entity_type: entities.get(entity_type, []) for entity_type in DATA_BUSINESS_ENTITY_TYPES}
return mod_hashlib.sha256(fn__canonical(payload).encode('ascii')).hexdigest()
def business_events(self, since_receipt=0):
return mod_copy.deepcopy([row for row in self.receipts if row['index'] > since_receipt])
def grade_targets(self, targets):
grade_t01 = fn_grade_t01
initial = {'raw': mod_copy.deepcopy(self._entry_raw), 'remaining': self.initial_budget, 'receipts': []}
return grade_t01(initial, self.snapshot(), targets)
def _mes_joint_lifecycle_world_init(self, source=CASE_DIR / 'raw'):
self._mes_exposure_balanced_world_init(source)
pool = {r['source_artifact_id']: ext_deepcopy(r) for rows in self._blueprint.values() for r in rows}
self._blueprint = {task: [{**pool[r['source_artifact_id']], 'task_id': task, 'artifact_id': r['artifact_id']} for r in rows] for (task, rows) in fn_blueprint(source).items()}
self._joint_original = ext_deepcopy(self._blueprint)
def _mes_joint_lifecycle_world_public_snapshot(self):
value = self._mes_exposure_balanced_world_public_snapshot()
if self.active_task_id:
value['active_event_id'] = fn_public_task(self.active_task_id, self.source)['event_id']
return value
def _mes_joint_lifecycle_world_snapshot(self):
value = self._mes_exposure_balanced_world_snapshot()
if not getattr(self, '_restoring_joint', False):
value['joint_template_contract'] = {'version': 'mes-joint-template-lifecycle-evolution-v7', 'allocation_sha256': mod_hashlib.sha256((CASE_DIR / 'data/assets/allocation.json').read_bytes()).hexdigest()}
return value
def _mes_joint_lifecycle_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('joint_template_contract', None) != {'version': 'mes-joint-template-lifecycle-evolution-v7', 'allocation_sha256': mod_hashlib.sha256((CASE_DIR / 'data/assets/allocation.json').read_bytes()).hexdigest()}:
raise ValueError('MES joint template snapshot version differs')
self._restoring_joint = True
try:
self._mes_exposure_balanced_world_restore(value)
finally:
self._restoring_joint = False
self._blueprint = ext_deepcopy(self._joint_original)
if 'evt-mes-lot-recertification-2026-09-v6' in self.applied_boundary_events:
self._blueprint = {task: [fn_revised_target(r) for r in rows] for (task, rows) in self._blueprint.items()}
if self.snapshot() != snapshot:
raise ValueError('MES joint template snapshot did not round trip')
def _mes_lifecycle_successor_apply_drift(self, event_id='evt-mes-lot-recertification-2026-09-v6'):
result = self._mes_lifecycle_successor_apply_drift_2(event_id)
if result.get('applied'):
self.binding_revalidation = {f'S{site_index + 1:02d}-M{slot:02d}': 'awaiting_exact_stale' for site_index in DATA_CHANGED_SITE_INDEXES for slot in DATA_MATERIAL_SLOTS}
return result
def _mes_exposure_balanced_world_activate_task(self, task_id, **kwargs):
result = self._mes_formation_aligned_world_activate_task(task_id, **kwargs)
if result['status'] == 'success':
result['data']['event_id'] = fn_public_task_2(task_id, self.source)['event_id']
return result
def _mes_lifecycle_successor_template_receipt(self, target):
public = fn__public_request(target)
operation = DATA_OPERATION_MODES_2[int(target['operation_mode'])]
issue_quantities = [float(row['issue_quantity']) for row in target['requisitions']]
return {'scope': {'product_profile': ext_deepcopy(public['product_profile']), 'closeout_template_id': public['closeout_template_id']}, 'quality_rework_required': bool(operation['quality']), 'final_step_run_required': bool(operation['ready_final_step']), 'issue_quantities': issue_quantities, 'issue_quantities_by_requisition_position': issue_quantities, 'reuse_scope': 'active orders with the exact product profile and closeout template', 'valid_until': 'a current inspection receipt for this template contradicts it'}
def _mes_contract_successor_execute_read(self, tool, arguments):
future = self._future_orders()
if tool == 'inspect_order_closeout' and arguments['order_id'] in future:
return self._error(tool, 'ORDER_NOT_ACTIVE', 'closeout assignment is not active')
if tool != 'find_production_orders':
return self._mes_order_closeout_adapter_execute_read(tool, arguments)
sites = {row['site_id']: row for row in self.manager.list_entities('site') if row.get('name') == arguments['site_name']}
skus = {row['sku_id']: row for row in self.manager.list_entities('sku') if row.get('name') == arguments['sku_name']}
rows = sorted((row for row in self.manager.list_entities('production_order') if row['order_id'] not in future and row.get('site_id') in sites and (row.get('sku_id') in skus) and (row.get('customer_reference') == arguments['customer_reference']) and (row.get('planned_start_at') == arguments['planned_start_at']) and (arguments.get('status') is None or row.get('status') == arguments['status'])), key=lambda row: row['order_id'])[:3]
projected = [{**{key: row.get(key) for key in ('order_id', 'site_id', 'sku_id', 'customer_reference', 'planned_quantity', 'status', 'planned_start_at')}, 'site_name': sites[row['site_id']]['name'], 'sku_name': skus[row['sku_id']]['name']} for row in rows]
return fn__success(tool, {'count': len(projected), 'orders': projected})
def _mes_lifecycle_successor_dispatch_issuable_lots(self, arguments, actor):
tool = 'find_issuable_inventory_lots'
if actor != 'production_closeout_coordinator':
result = self._result_error(tool, 'ROLE_FORBIDDEN', 'actor is not a production closeout coordinator')
result['budget'] = self._budget()
return result
before = self.business_hash()
charge = DATA_READ_CHARGES[tool]
if self.read_used + charge > self.read_allowance:
return self._record(tool=tool, public_arguments=arguments, backend_arguments=None, result=self._result_error(tool, 'EVIDENCE_READ_EXHAUSTED', 'insufficient evidence read units'), before=before, read_charged=0, mutation_charged=0)
self.read_used += charge
self.remaining = self.read_allowance - self.read_used
validation_error = fn__validate_value(arguments, DATA_TOOL_SCHEMAS[tool], 'arguments')
if validation_error is not None:
return self._record(tool=tool, public_arguments=arguments, backend_arguments=None, result=self._result_error(tool, 'INVALID_ARGUMENTS', validation_error), before=before, read_charged=charge, mutation_charged=0)
try:
raw_arguments = self._decode(arguments)
except KeyError:
return self._record(tool=tool, public_arguments=arguments, backend_arguments=None, result=self._result_error(tool, 'IDENTIFIER_UNKNOWN', 'identifier is not a public MES identifier'), before=before, read_charged=charge, mutation_charged=0)
context = self._requisition_context(raw_arguments['requisition_id'])
if context is None:
return self._record(tool=tool, public_arguments=arguments, backend_arguments=raw_arguments, result=self._result_error(tool, 'ASSIGNMENT_FORBIDDEN', 'requisition is outside the current closeout assignment'), before=before, read_charged=charge, mutation_charged=0)
(_target, requisition) = context
current = self.manager.get_entity('material_requisition', requisition['requisition_id'], id_field='requisition_id')
if current is None:
return self._record(tool=tool, public_arguments=arguments, backend_arguments=raw_arguments, result=self._result_error(tool, 'REQUISITION_NOT_FOUND', 'active requisition no longer exists'), before=before, read_charged=charge, mutation_charged=0)
remaining = round(max(0.0, float(current.get('approved_quantity') or 0) - float(current.get('issued_quantity') or 0)), 3)
backend_arguments = {'material_id': requisition['material_id'], 'site_id': requisition['site_id'], 'min_available_quantity': remaining}
result = self._execute_read('find_inventory_lots', backend_arguments)
result = self._publish(result)
result['tool'] = tool
if result.get('content', {}).get('status') == 'success':
result['content']['data'].update({'requisition_id': arguments['requisition_id'], 'remaining_approved_quantity': remaining, 'selection_semantics': 'currently_issuable_including_allocated'})
return self._record(tool=tool, public_arguments=arguments, backend_arguments=backend_arguments, result=result, before=before, read_charged=charge, mutation_charged=0)
def _mes_lifecycle_successor_dispatch(self, tool, arguments, actor='production_closeout_coordinator'):
if tool == 'find_issuable_inventory_lots':
return self._dispatch_issuable_lots(arguments, actor)
return self._mes_lifecycle_successor_dispatch_2(tool, arguments, actor)
def _mes_lifecycle_successor_grade(self, task_id):
if task_id != self.active_task_id:
raise ValueError('grade requested for a task that is not active')
return fn_grade({'raw': ext_deepcopy(self._entry_raw)}, self.snapshot(), self._task_targets)
def _persistent_mes_order_closeout_adapter_normalize_target(self, target):
order = self.manager.get_entity('production_order', target['order_id'], id_field='order_id')
if not order:
raise RuntimeError(f"missing stream order: {target['order_id']}")
steps = sorted(self.manager.query_entities('operation_step', lambda row: row.get('order_id') == target['order_id']), key=lambda row: (row.get('sequence_no', 0), row.get('step_id', '')))
if len(steps) != 4:
raise RuntimeError(f"stream order does not have four steps: {target['order_id']}")
self._remove_target_dependents(target['order_id'])
final_step = steps[-1]
if target['cell'] in {'soft_requisition_force_close', 'final_ready_step'}:
template_equipment = self.manager.get_entity('equipment', final_step['equipment_id'], id_field='equipment_id')
if not template_equipment:
raise RuntimeError('stream final step has no equipment')
final_step['equipment_id'] = self._synthetic_equipment(target, template_equipment)
for (index, step) in enumerate(steps, 1):
is_final = index == len(steps)
ready = target['cell'] == 'final_ready_step' and is_final
running = target['cell'] == 'soft_requisition_force_close' and is_final
patch = {'equipment_id': final_step['equipment_id'] if is_final else step['equipment_id'], 'status': 'ready' if ready else 'running' if running else 'completed', 'actual_start_at': None if ready else '2026-05-27T08:20:00Z' if running else f'2026-05-20T{index:02d}:00:00Z', 'actual_end_at': None if ready or running else f'2026-05-20T{index:02d}:30:00Z', 'good_quantity': 0.0 if ready or running else float(order['planned_quantity']), 'scrap_quantity': 0.0, 'updated_at': '2026-05-20T12:00:00Z'}
self.manager.update_entity('operation_step', step['step_id'], patch, id_field='step_id')
target['step_id'] = steps[-2]['step_id'] if target['cell'] in {'quality_rework', 'approved_material_issue_with_quality_rework'} else steps[-1]['step_id']
if target['cell'] in {'soft_requisition_force_close', 'final_ready_step'}:
target['equipment_id'] = final_step['equipment_id']
target['step_start_at'] = '2026-05-27T08:20:00Z'
target['step_end_at'] = '2026-05-27T09:50:00Z'
status = 'on_hold' if target['cell'] in {'quality_rework', 'approved_material_issue_with_quality_rework'} else 'in_progress'
self.manager.update_entity('production_order', target['order_id'], {'status': status, 'completed_step_count': 3 if target['cell'] in {'soft_requisition_force_close', 'final_ready_step'} else 4, 'completed_quantity': 0.0, 'scrap_quantity': 0.0, 'completed_at': None, 'updated_at': '2026-05-20T12:00:00Z'}, id_field='order_id')
material_cell = target['cell'] in {'approved_material_issue', 'approved_material_issue_with_quality_rework'}
material = self._material_binding(target, order) if material_cell else None
requisition_id = 'req-stream-' + fn__token(target['order_id'])
target['requisition_id'] = requisition_id
issue_quantity = 20.0
if material_cell:
target.update({'material_id': material['material_id'], 'site_id': order['site_id'], 'lot_id': material['old_lot_id'], 'old_lot_id': material['old_lot_id'], 'replacement_lot_id': material['replacement_lot_id'], 'issue_quantity': issue_quantity})
else:
material_id = 'mat-stream-inert-' + fn__token(target['order_id'])
material_template = self.manager.list_entities('material')[0]
self._upsert('material', material_id, {**ext_deepcopy(material_template), 'material_id': material_id, 'material_code': 'INERT-' + fn__token(target['order_id'], 8).upper(), 'name': 'Issued closeout material ' + fn__token(target['order_id'], 6).upper(), 'status': 'active'})
requisition_status = 'approved' if material_cell else 'draft' if target['cell'] == 'soft_requisition_force_close' else 'issued'
approved_quantity = issue_quantity if material_cell else 0.0 if requisition_status == 'draft' else 1.0
issued_quantity = 0.0 if requisition_status in {'approved', 'draft'} else approved_quantity
self._upsert('material_requisition', requisition_id, {'requisition_id': requisition_id, 'order_id': target['order_id'], 'site_id': order['site_id'], 'material_id': material['material_id'] if material_cell else material_id, 'requested_quantity': approved_quantity if approved_quantity > 0 else 1.0, 'approved_quantity': approved_quantity, 'issued_quantity': issued_quantity, 'uom': 'kilogram', 'status': requisition_status, 'needed_by': '2026-05-28T08:00:00Z', 'requested_by': 'Stream Planner', 'approved_by': 'Stream Approver' if requisition_status != 'draft' else None, 'created_at': '2026-05-20T08:00:00Z', 'updated_at': '2026-05-20T12:00:00Z'})
if target['cell'] in {'quality_rework', 'approved_material_issue_with_quality_rework'}:
failure_id = 'insp-stream-' + fn__token(target['order_id']) + '-fail'
target['failure_inspection_id'] = failure_id
self._upsert('quality_inspection', failure_id, {'inspection_id': failure_id, 'order_id': target['order_id'], 'step_id': target['step_id'], 'sku_id': order['sku_id'], 'inspection_type': 'final', 'result': 'fail', 'sample_size': 5, 'defect_count': 1, 'defect_code': 'stream-closeout-defect', 'inspector': 'Stream Inspector', 'measured_values': {'diameter_mm': 0.0, 'torque_nm': 0.0, 'pressure_bar': 0.0}, 'notes': 'Unresolved closeout defect.', 'created_at': '2026-05-20T09:00:00Z', 'updated_at': '2026-05-20T09:00:00Z'})
if target['cell'] == 'approved_material_issue_with_quality_rework':
decoy_id = 'insp-stream-' + fn__token(target['order_id']) + '-ordinary-pass'
target['decoy_inspection_id'] = decoy_id
self._upsert('quality_inspection', decoy_id, {'inspection_id': decoy_id, 'order_id': target['order_id'], 'step_id': target['step_id'], 'sku_id': order['sku_id'], 'inspection_type': 'final', 'result': 'pass', 'sample_size': 5, 'defect_count': 0, 'defect_code': None, 'inspector': 'Stream Inspector', 'measured_values': {'diameter_mm': 0.0, 'torque_nm': 0.0, 'pressure_bar': 0.0}, 'notes': 'Ordinary pass does not clear prior failed closeout evidence.', 'created_at': '2026-05-20T10:00:00Z', 'updated_at': '2026-05-20T10:00:00Z'})
def _mes_exposure_balanced_world_init(self, source=CASE_DIR / 'raw'):
self._mes_formation_aligned_world_init(source)
pool = {r['source_artifact_id']: ext_deepcopy(r) for rows in self._blueprint.values() for r in rows}
self._blueprint = {task: [{**pool[r['source_artifact_id']], **{key: r[key] for key in ('task_id', 'artifact_id')}} for r in rows] for (task, rows) in fn_blueprint_2(source).items()}
def _mes_exposure_balanced_world_public_snapshot(self):
value = self._mes_formation_aligned_world_public_snapshot()
if self.active_task_id:
value['active_event_id'] = fn_public_task_2(self.active_task_id, self.source)['event_id']
return value
def _mes_exposure_balanced_world_snapshot(self):
value = self._mes_independent_world_snapshot()
if not getattr(self, '_restoring_exposure_balance', False):
value['exposure_balance_contract'] = 'mes-exposure-balanced-evolution-v5'
return value
def _mes_exposure_balanced_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('exposure_balance_contract', None) != 'mes-exposure-balanced-evolution-v5':
raise ValueError('MES exposure snapshot version differs')
self._restoring_exposure_balance = True
try:
self._mes_independent_world_restore(value)
finally:
self._restoring_exposure_balance = False
if self.snapshot() != snapshot:
raise ValueError('MES exposure snapshot did not round trip')
def _mes_lifecycle_successor_apply_drift_2(self, event_id='evt-mes-lot-recertification-2026-09-v5'):
before = self.business_hash()
if event_id in self.applied_boundary_events:
return {'status': 'success', 'applied': False, 'idempotent': True, 'changed': [], 'before_world_sha256': before, 'after_world_sha256': before, 'public_notice': ''}
changed = []
for site_index in DATA_CHANGED_SITE_INDEXES:
for slot in DATA_MATERIAL_SLOTS:
old_lot_ids = [fn__lot_id(site_index, slot, 1)]
replacement_lot_ids = [fn__lot_id(site_index, slot, 2)]
for old_lot_id in old_lot_ids:
self.manager.update_entity('inventory_lot', old_lot_id, {'status': 'quarantined', 'updated_at': '2026-05-27T09:59:00Z'}, id_field='lot_id')
for replacement_lot_id in replacement_lot_ids:
self.manager.update_entity('inventory_lot', replacement_lot_id, {'status': 'allocated', 'updated_at': '2026-05-27T09:59:00Z'}, id_field='lot_id')
changed.append({'structure_atom': f'S{site_index + 1:02d}-M{slot:02d}', 'old_lot_ids': old_lot_ids, 'replacement_lot_ids': replacement_lot_ids})
self.applied_boundary_events.add(event_id)
return {'status': 'success', 'applied': True, 'idempotent': False, 'changed': changed, 'before_world_sha256': before, 'after_world_sha256': self.business_hash(), 'public_notice': ''}
def _mes_formation_aligned_world_activate_task(self, task_id, **kwargs):
result = self._mes_workload_balanced_world_activate_task(task_id, **kwargs)
if result['status'] == 'success':
result['data']['event_id'] = fn_public_task_3(task_id, self.source)['event_id']
return result
def _mes_order_closeout_adapter_execute_read(self, tool, arguments):
if tool == 'find_production_orders':
sites = {row['site_id']: row for row in self.manager.list_entities('site') if row.get('name') == arguments['site_name']}
skus = {row['sku_id']: row for row in self.manager.list_entities('sku') if row.get('name') == arguments['sku_name']}
rows = [row for row in self.manager.list_entities('production_order') if row.get('site_id') in sites and row.get('sku_id') in skus and (row.get('customer_reference') == arguments['customer_reference']) and (row.get('planned_start_at') == arguments['planned_start_at']) and (arguments.get('status') is None or row.get('status') == arguments['status'])]
rows = sorted(rows, key=lambda row: row['order_id'])[:3]
projected = [{'order_id': row['order_id'], 'site_id': row['site_id'], 'site_name': sites[row['site_id']]['name'], 'sku_id': row['sku_id'], 'sku_name': skus[row['sku_id']]['name'], 'customer_reference': row.get('customer_reference'), 'planned_quantity': row.get('planned_quantity'), 'status': row.get('status'), 'planned_start_at': row.get('planned_start_at')} for row in rows]
return fn__success(tool, {'count': len(projected), 'orders': projected})
if tool == 'inspect_order_closeout':
order_id = arguments['order_id']
order = self.manager.get_entity('production_order', order_id, id_field='order_id')
if not order:
return self._error(tool, 'ORDER_NOT_FOUND', 'order does not exist')
steps = sorted(self.manager.query_entities('operation_step', lambda row: row.get('order_id') == order_id), key=lambda row: (row.get('sequence_no', 0), row.get('step_id', '')))
requisitions = sorted(self.manager.query_entities('material_requisition', lambda row: row.get('order_id') == order_id), key=lambda row: row.get('requisition_id', ''))
inspections = sorted(self.manager.query_entities('quality_inspection', lambda row: row.get('order_id') == order_id), key=lambda row: (row.get('created_at', ''), row.get('inspection_id', '')))
return fn__success(tool, {'order': {key: order.get(key) for key in ('order_id', 'site_id', 'sku_id', 'customer_reference', 'planned_quantity', 'completed_quantity', 'scrap_quantity', 'status', 'planned_start_at', 'completed_at', 'completed_step_count', 'total_step_count')}, 'steps': [{key: row.get(key) for key in ('step_id', 'sequence_no', 'name', 'status', 'equipment_id', 'actual_start_at', 'actual_end_at', 'good_quantity', 'scrap_quantity')} for row in steps], 'requisitions': [{key: row.get(key) for key in ('requisition_id', 'site_id', 'material_id', 'requested_quantity', 'approved_quantity', 'issued_quantity', 'uom', 'status')} for row in requisitions], 'inspections': [{key: row.get(key) for key in ('inspection_id', 'step_id', 'inspection_type', 'result', 'sample_size', 'defect_count', 'defect_code', 'created_at')} for row in inspections]})
if tool == 'find_inventory_lots':
minimum = float(arguments['min_available_quantity'])
status = arguments.get('status')
rows = [row for row in self.manager.list_entities('inventory_lot') if row.get('material_id') == arguments['material_id'] and row.get('site_id') == arguments['site_id'] and (row.get('status') in {'available', 'allocated'} if status is None else row.get('status') == status) and (float(row.get('quantity_on_hand') or 0) - float(row.get('quantity_reserved') or 0) >= minimum)]
rows.sort(key=lambda row: (row.get('expires_at') or '9999', row['lot_id']))
projected = []
for row in rows[:3]:
projected.append({'lot_id': row['lot_id'], 'material_id': row.get('material_id'), 'site_id': row.get('site_id'), 'status': row.get('status'), 'quantity_on_hand': row.get('quantity_on_hand'), 'quantity_reserved': row.get('quantity_reserved'), 'available_quantity': round(float(row.get('quantity_on_hand') or 0) - float(row.get('quantity_reserved') or 0), 3), 'received_at': row.get('received_at'), 'expires_at': row.get('expires_at')})
return fn__success(tool, {'count': len(projected), 'lots': projected})
equipment = self.manager.get_entity('equipment', arguments['equipment_id'], id_field='equipment_id')
if not equipment:
return self._error(tool, 'EQUIPMENT_NOT_FOUND', 'equipment does not exist')
active = sorted(self.manager.query_entities('downtime_event', lambda row: row.get('equipment_id') == arguments['equipment_id'] and row.get('ended_at') is None), key=lambda row: row.get('started_at', ''))
return fn__success(tool, {'equipment': {key: equipment.get(key) for key in ('equipment_id', 'site_id', 'work_center_id', 'name', 'equipment_type', 'status')}, 'active_downtime': [{key: row.get(key) for key in ('downtime_id', 'reason_code', 'started_at')} for row in active]})
def _mes_lifecycle_successor_dispatch_2(self, tool, arguments, actor='production_closeout_coordinator'):
before_state = ext_deepcopy(self.binding_revalidation)
raw_arguments: dict[str, ext_Any] | None = None
if isinstance(arguments, dict):
try:
raw_arguments = self._decode(arguments)
except KeyError:
raw_arguments = None
result = self._mes_lifecycle_successor_dispatch_3(tool, arguments, actor)
status = result.get('content', {}).get('status')
message = result.get('content', {}).get('message', '')
code = message.split(':', 1)[0] if message else ''
if tool == 'record_material_issue' and raw_arguments is not None:
context = self._requisition_context(raw_arguments.get('requisition_id', ''))
if context is not None:
(_target, requisition) = context
atom = requisition['structure_atom']
state = self.binding_revalidation.get(atom)
if state == 'awaiting_exact_stale' and raw_arguments.get('lot_id') == requisition['old_lot_id'] and (status == 'error') and (code == 'LOT_NOT_ISSUABLE'):
self.binding_revalidation[atom] = 'stale_observed'
elif state in {'awaiting_exact_stale', 'stale_observed', 'awaiting_targeted_lot_search', 'ready_current'} and status == 'success' and (raw_arguments.get('lot_id') != requisition['old_lot_id']):
self.binding_revalidation[atom] = 'validated'
if tool == 'inspect_order_closeout' and raw_arguments is not None and (status == 'success'):
target = self._target_for_order(raw_arguments.get('order_id', ''))
if target is not None:
atoms = self._target_atoms(target)
if atoms and all((self.binding_revalidation.get(atom) == 'stale_observed' for atom in atoms)):
for atom in atoms:
self.binding_revalidation[atom] = 'awaiting_targeted_lot_search'
if self.receipts and self.receipts[-1].get('index') == result.get('receipt_index'):
self.receipts[-1]['revalidation_before'] = before_state
self.receipts[-1]['revalidation_after'] = ext_deepcopy(self.binding_revalidation)
return result
def _mes_formation_aligned_world_init(self, source=CASE_DIR / 'raw'):
self._mes_workload_balanced_world_init(source)
original = {r['source_artifact_id']: ext_deepcopy(r) for rows in self._blueprint.values() for r in rows}
self._blueprint = {task: [{**original[r['source_artifact_id']], **{key: r[key] for key in ('source_artifact_id', 'task_id', 'artifact_id')}} for r in rows] for (task, rows) in fn_blueprint_3(source).items()}
def _mes_formation_aligned_world_public_snapshot(self):
value = self._mes_workload_balanced_world_public_snapshot()
if self.active_task_id:
value['active_event_id'] = fn_public_task_3(self.active_task_id, self.source)['event_id']
return value
def _mes_independent_world_snapshot(self):
value = self._mes_formation_aligned_world_snapshot()
if not getattr(self, '_restoring_independent_orders', False):
value['independent_orders_contract'] = 'mes-independent-orders-evolution-v4'
return value
def _mes_independent_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('independent_orders_contract', None) != 'mes-independent-orders-evolution-v4':
raise ValueError('MES independent-order snapshot version differs')
self._restoring_independent_orders = True
try:
self._mes_formation_aligned_world_restore(value)
finally:
self._restoring_independent_orders = False
if self.snapshot() != snapshot:
raise ValueError('MES independent-order snapshot did not round trip')
def _mes_workload_balanced_world_activate_task(self, task_id, **kwargs):
result = self._mes_evolution_activate_task(task_id, **kwargs)
if result['status'] == 'success':
result['data']['event_id'] = fn_public_task_5(task_id, self.source)['event_id']
return result
def _mes_lifecycle_successor_dispatch_3(self, tool, arguments, actor='production_closeout_coordinator'):
if actor != 'production_closeout_coordinator':
result = self._result_error(tool, 'ROLE_FORBIDDEN', 'actor is not a production closeout coordinator')
result['budget'] = self._budget()
return result
if tool not in DATA_ALLOWED_TOOLS:
result = self._result_error(tool, 'TOOL_FORBIDDEN', 'tool is outside the closeout slice')
result['budget'] = self._budget()
return result
before = self.business_hash()
is_write = tool in DATA_WRITE_TOOLS
read_charge = DATA_READ_CHARGES_2.get(tool, 0)
if is_write and self.mutation_used >= self.mutation_allowance:
return self._record(tool=tool, public_arguments=arguments, backend_arguments=None, result=self._result_error(tool, 'MUTATION_ATTEMPTS_EXHAUSTED', 'no mutation attempts remain'), before=before, read_charged=0, mutation_charged=0)
if not is_write and self.read_used + read_charge > self.read_allowance:
return self._record(tool=tool, public_arguments=arguments, backend_arguments=None, result=self._result_error(tool, 'EVIDENCE_READ_EXHAUSTED', 'insufficient evidence read units'), before=before, read_charged=0, mutation_charged=0)
if is_write:
self.mutation_used += 1
mutation_charge = 1
else:
self.read_used += read_charge
mutation_charge = 0
self.remaining = self.read_allowance - self.read_used
validation_error = fn__validate_value(arguments, DATA_TOOL_SCHEMAS_2[tool], 'arguments')
if validation_error is not None:
return self._record(tool=tool, public_arguments=arguments, backend_arguments=None, result=self._result_error(tool, 'INVALID_ARGUMENTS', validation_error), before=before, read_charged=read_charge if not is_write else 0, mutation_charged=mutation_charge)
try:
raw_arguments = self._decode(arguments)
except KeyError:
return self._record(tool=tool, public_arguments=arguments, backend_arguments=None, result=self._result_error(tool, 'IDENTIFIER_UNKNOWN', 'identifier is not a public MES identifier'), before=before, read_charged=read_charge if not is_write else 0, mutation_charged=mutation_charge)
if is_write and (not self._write_authorized(raw_arguments)):
return self._record(tool=tool, public_arguments=arguments, backend_arguments=raw_arguments, result=self._result_error(tool, 'ASSIGNMENT_FORBIDDEN', 'mutation is outside the current closeout assignment'), before=before, read_charged=0, mutation_charged=mutation_charge)
if is_write and (not self._priority_allowed(raw_arguments)):
return self._record(tool=tool, public_arguments=arguments, backend_arguments=raw_arguments, result=self._result_error(tool, 'PRIOR_TARGET_INCOMPLETE', 'complete earlier listed requests before this request'), before=before, read_charged=0, mutation_charged=mutation_charge)
if not is_write:
result = self._execute_read(tool, raw_arguments)
else:
raw_before = self._snapshot_raw()
try:
raw_result = self.server.call_tool(tool, state_manager=self.manager, **raw_arguments)
except Exception:
raw_result = None
result = fn__sanitize_raw_result(tool, raw_result)
if result['content'].get('status') != 'success':
self._restore_raw(raw_before)
result = self._publish(result)
return self._record(tool=tool, public_arguments=arguments, backend_arguments=raw_arguments, result=result, before=before, read_charged=read_charge if not is_write else 0, mutation_charged=mutation_charge)
def _mes_workload_balanced_world_init(self, source=CASE_DIR / 'raw'):
self._mes_evolution_init(source)
original = {row['source_artifact_id']: ext_deepcopy(row) for rows in self._blueprint.values() for row in rows}
self._blueprint = {task: [{**original[row['source_artifact_id']], **{key: row[key] for key in ('source_artifact_id', 'artifact_id', 'task_id')}} for row in rows] for (task, rows) in fn_blueprint_4(source).items()}
def _mes_workload_balanced_world_public_snapshot(self):
value = self._mes_lifecycle_successor_public_snapshot()
if self.active_task_id:
value['active_event_id'] = fn_public_task_5(self.active_task_id, self.source)['event_id']
return value
def _mes_formation_aligned_world_snapshot(self):
value = self._mes_workload_balanced_world_snapshot()
if not getattr(self, '_restoring_formation_alignment', False):
value['formation_alignment_contract'] = 'mes-formation-aligned-lifecycle-evolution-v3'
return value
def _mes_formation_aligned_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('formation_alignment_contract', None) != 'mes-formation-aligned-lifecycle-evolution-v3':
raise ValueError('MES formation snapshot version differs')
self._restoring_formation_alignment = True
try:
self._mes_workload_balanced_world_restore(value)
finally:
self._restoring_formation_alignment = False
if self.snapshot() != snapshot:
raise ValueError('MES formation snapshot did not round trip')
def _mes_evolution_activate_task(self, task_id, *, apply_boundary_drift=True):
expected = f'T{len(self._activated_tasks) + 1:02}'
if task_id != expected or task_id not in DATA_STREAM_TASK_IDS:
return {'status': 'error', 'data': {'error_code': 'TASK_ORDER_INVALID'}}
if task_id == 'T07' and apply_boundary_drift:
self.apply_stream_drift()
result = self._mes_lifecycle_successor_activate_task(task_id, apply_boundary_drift=False)
result['data']['event_id'] = fn_public_task_6(task_id, self.source)['event_id']
return result
def _mes_evolution_init(self, source=CASE_DIR / 'raw'):
self._mes_lifecycle_successor_init(source)
original = {row['source_artifact_id']: ext_deepcopy(row) for rows in self._blueprint.values() for row in rows}
self._blueprint = {task: [{**original[row['source_artifact_id']], **{key: row[key] for key in ('source_artifact_id', 'artifact_id', 'task_id')}} for row in rows] for (task, rows) in fn_blueprint_5(source).items()}
def _mes_lifecycle_successor_public_snapshot(self):
value = self._mes_lifecycle_successor_public_snapshot_2()
value['schema'] = 'rescopebench-mes-lifecycle-public-snapshot/v8'
if self.active_task_id:
value['active_event_id'] = fn_public_task_7(self.active_task_id, self.source)['event_id']
value['provider_tools_sha256'] = 'c847a13920fbd4d6a80cd81f48a7138742683d09094b401c5b2413abd471b4ce'
return value
def _mes_workload_balanced_world_snapshot(self):
value = self._mes_evolution_snapshot()
value['workload_contract'] = {'case_version': 'mes-workload-balanced-lifecycle-evolution-v2', 'allocation_sha256': mod_hashlib.sha256((CASE_DIR / 'data/assets/allocation.json_2').read_bytes()).hexdigest()}
return value
def _mes_workload_balanced_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
expected = {'case_version': 'mes-workload-balanced-lifecycle-evolution-v2', 'allocation_sha256': mod_hashlib.sha256((CASE_DIR / 'data/assets/allocation.json_2').read_bytes()).hexdigest()}
if value.pop('workload_contract', None) != expected:
raise ValueError('MES workload snapshot version differs')
self._mes_evolution_restore(value)
if self.snapshot() != snapshot:
raise ValueError('MES workload snapshot did not round trip')
def _mes_lifecycle_successor_activate_task(self, task_id, *, apply_boundary_drift=True):
result = self._mes_lifecycle_successor_activate_task_2(task_id, apply_boundary_drift=apply_boundary_drift)
if result.get('status') == 'success':
result['data']['event_id'] = fn_public_task_7(task_id, self.source)['event_id']
return result
def _mes_lifecycle_successor_init(self, source=CASE_DIR / 'raw'):
self._mes_lifecycle_successor_init_2(source)
normalized = {row['source_artifact_id']: ext_deepcopy(row) for rows in self._blueprint.values() for row in rows}
scheduled = fn_stream_blueprint(self.source)
self._blueprint = {}
for (task_id, rows) in scheduled.items():
self._blueprint[task_id] = []
for row in rows:
target = normalized[row['source_artifact_id']]
target.update({'artifact_id': row['artifact_id'], 'source_artifact_id': row['source_artifact_id'], 'task_id': task_id})
self._blueprint[task_id].append(target)
def _mes_lifecycle_successor_public_snapshot_2(self):
value = self._mes_lifecycle_successor_public_snapshot_3()
value['schema'] = 'rescopebench-mes-lifecycle-public-snapshot/v7'
if self.active_task_id:
value['active_event_id'] = fn_public_task_8(self.active_task_id, self.source)['event_id']
value['provider_tools_sha256'] = '609ea1b829df55dccf7fe0a1349baa1d5d4e4b38d90891f9699d747a856413dc'
return value
def _mes_evolution_snapshot(self):
value = self._mes_lifecycle_successor_snapshot()
value['evolution_contract'] = {'case_version': 'mes-closeout-lifecycle-evolution-v1', 'schedule': ext_deepcopy(DATA_SCHEDULE_2), 'swaps': [list(x) for x in DATA_SWAPS_3]}
return value
def _mes_evolution_restore(self, snapshot):
value = ext_deepcopy(snapshot)
expected = {'case_version': 'mes-closeout-lifecycle-evolution-v1', 'schedule': DATA_SCHEDULE_2, 'swaps': [list(x) for x in DATA_SWAPS_3]}
if value.pop('evolution_contract', None) != expected:
raise ValueError('MES evolution contract differs')
self._mes_lifecycle_successor_restore(value)
def _mes_lifecycle_successor_activate_task_2(self, task_id, *, apply_boundary_drift=True):
result = self._mes_lifecycle_successor_activate_task_3(task_id, apply_boundary_drift=apply_boundary_drift)
if result.get('status') == 'success':
result['data']['event_id'] = fn_public_task_8(task_id, self.source)['event_id']
return result
def _mes_lifecycle_successor_init_2(self, source=CASE_DIR / 'raw'):
self.public_policy_active = False
self.grade_calls_during_policy = 0
self._mes_lifecycle_successor_init_3(source)
def _mes_lifecycle_successor_public_snapshot_3(self):
value = self._mes_lifecycle_successor_public_snapshot_4()
value['schema'] = 'rescopebench-mes-lifecycle-public-snapshot/v6'
if self.active_task_id:
value['active_event_id'] = fn_public_task_9(self.active_task_id, self.source)['event_id']
return value
def _mes_lifecycle_successor_snapshot(self):
value = self._mes_lifecycle_successor_snapshot_2()
value['schema'] = 'rescopebench-mes-lifecycle-stream/v8'
value['provider_tools_sha256'] = 'c847a13920fbd4d6a80cd81f48a7138742683d09094b401c5b2413abd471b4ce'
value['allocation_sha256'] = fn_allocation_report(self.source)['assignment_sha256']
return value
def _mes_lifecycle_successor_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-mes-lifecycle-stream/v8':
raise ValueError('unsupported MES lifecycle v8 snapshot schema')
value = ext_deepcopy(snapshot)
value['schema'] = 'rescopebench-mes-lifecycle-stream/v7'
value['provider_tools_sha256'] = '609ea1b829df55dccf7fe0a1349baa1d5d4e4b38d90891f9699d747a856413dc'
value['allocation_sha256'] = fn_allocation_report_2(self.source)['assignment_sha256']
self._mes_lifecycle_successor_restore_2(value)
def _mes_lifecycle_successor_activate_task_3(self, task_id, *, apply_boundary_drift=True):
result = self._mes_lifecycle_successor_activate_task_4(task_id, apply_boundary_drift=apply_boundary_drift)
if result.get('status') == 'success':
result['data']['event_id'] = fn_public_task_9(task_id, self.source)['event_id']
return result
def _mes_lifecycle_successor_init_3(self, source=CASE_DIR / 'raw'):
self.binding_revalidation: dict[str, str] = {}
self._mes_lifecycle_successor_init_4(source)
normalized = {row['artifact_id']: ext_deepcopy(row) for rows in self._blueprint.values() for row in rows}
scheduled = fn_stream_blueprint_3(self.source)
self._blueprint = {}
for (task_id, rows) in scheduled.items():
self._blueprint[task_id] = []
for row in rows:
target = normalized[row['source_artifact_id']]
target.update({'artifact_id': row['artifact_id'], 'source_artifact_id': row['source_artifact_id'], 'task_id': task_id})
self._blueprint[task_id].append(target)
self._entry_raw = self._snapshot_raw()
def _mes_lifecycle_successor_public_snapshot_4(self):
packet = fn_public_task_10(self.active_task_id, self.source) if self.active_task_id else None
return {'schema': 'rescopebench-mes-lifecycle-public-snapshot/v5', 'active_event_id': packet['event_id'] if packet else None, 'budget': self._budget(), 'budget_contract': {'evidence_read_units_allowance': self.read_allowance, 'mutation_attempts_allowance': self.mutation_allowance}}
def _mes_lifecycle_successor_snapshot_2(self):
value = self._mes_lifecycle_successor_snapshot_3()
value['schema'] = 'rescopebench-mes-lifecycle-stream/v7'
value['provider_tools_sha256'] = '609ea1b829df55dccf7fe0a1349baa1d5d4e4b38d90891f9699d747a856413dc'
value['allocation_sha256'] = fn_allocation_report_2(self.source)['assignment_sha256']
return value
def _mes_lifecycle_successor_restore_2(self, snapshot):
if snapshot.get('schema') != 'rescopebench-mes-lifecycle-stream/v7':
raise ValueError('unsupported MES lifecycle v7 snapshot schema')
value = ext_deepcopy(snapshot)
value['schema'] = 'rescopebench-mes-lifecycle-stream/v6'
value['provider_tools_sha256'] = 'c781596331405790a753f40c31b864fb1ff867aed767f4206987c5d3ad6022bc'
self._mes_lifecycle_successor_restore_3(value)
def _mes_lifecycle_successor_activate_task_4(self, task_id, *, apply_boundary_drift=True):
if task_id not in DATA_STREAM_TASK_IDS:
return {'status': 'error', 'data': {'error_code': 'TASK_NOT_EXECUTABLE'}}
expected = f'T{len(self._activated_tasks) + 1:02d}'
if task_id != expected:
return {'status': 'error', 'data': {'error_code': 'TASK_ORDER_INVALID'}}
boundary = None
if task_id == 'T09' and apply_boundary_drift:
boundary = self._apply_drift()
self.active_task_id = task_id
self.read_allowance = 21
self.read_used = 0
self.mutation_allowance = 25
self.mutation_used = 0
self.initial_budget = self.read_allowance
self.remaining = self.read_allowance
self.receipts = []
self._task_targets = self._resolved_targets(task_id)
self._entry_raw = self._snapshot_raw()
self._activated_tasks.append(task_id)
packet = fn_public_task_10(task_id, self.source)
return {'status': 'success', 'data': {'event_id': packet['event_id'], 'public_notice': '', 'budget': self._budget(), 'boundary_applied': bool(boundary and boundary.get('applied'))}, 'boundary': boundary}
def _mes_lifecycle_successor_init_4(self, source=CASE_DIR / 'raw'):
self.source = ext_Path(source).resolve()
World._mes_order_closeout_adapter_init(self, self.source, budget=10 ** 9)
self._activated_tasks: list[str] = []
self._task_targets: list[dict[str, ext_Any]] = []
cache_key = str(self.source)
if cache_key in DATA__INITIAL_RAW_CACHE:
self._blueprint = ext_deepcopy(DATA__BLUEPRINT_CACHE_2[cache_key])
self._restore_raw(ext_deepcopy(DATA__INITIAL_RAW_CACHE[cache_key]))
else:
self._blueprint = fn_stream_blueprint_2(self.source)
self._initialize_shared_bindings()
self._normalize_lifecycle_fixture()
DATA__INITIAL_RAW_CACHE[cache_key] = self._snapshot_raw()
DATA__BLUEPRINT_CACHE_2[cache_key] = ext_deepcopy(self._blueprint)
self._rebuild_aliases()
self._entry_raw = self._snapshot_raw()
self.read_allowance = 21
self.read_used = 0
self.mutation_allowance = 25
self.mutation_used = 0
self.initial_budget = 21
self.remaining = 21
def _mes_lifecycle_successor_snapshot_3(self):
value = self._mes_lifecycle_successor_snapshot_4()
value['schema'] = 'rescopebench-mes-lifecycle-stream/v6'
value['binding_revalidation'] = ext_deepcopy(self.binding_revalidation)
value['allocation_sha256'] = fn_allocation_report_3(self.source)['assignment_sha256']
return value
def _mes_lifecycle_successor_restore_3(self, snapshot):
if snapshot.get('schema') != 'rescopebench-mes-lifecycle-stream/v6':
raise ValueError('unsupported MES lifecycle v6 snapshot schema')
value = ext_deepcopy(snapshot)
self.binding_revalidation = ext_deepcopy(value.pop('binding_revalidation', {}))
value['schema'] = 'rescopebench-mes-lifecycle-stream/v5'
self._mes_lifecycle_successor_restore_4(value)
def _mes_order_closeout_adapter_init(self, source, budget=132):
source = ext_Path(source).resolve()
if not source.is_dir():
raise FileNotFoundError(source)
(self.server, entity_types) = fn__load_raw_runtime(str(source))
self._runtime_root = ext_Path(mod_tempfile.mkdtemp(prefix='mes_closeout_runtime_'))
mod_shutil.copytree(source / 'data/database', self._runtime_root / 'data/database')
(self._runtime_root / 'data/temp').mkdir(parents=True, exist_ok=True)
self.manager = self.server.StateManager(str(self._runtime_root / 'data'))
self._entity_types = entity_types
self.initial_budget = int(budget)
self.remaining = int(budget)
self.receipts: list[dict[str, ext_Any]] = []
self.active_task_id: str | None = None
self.applied_boundary_events: set[str] = set()
self._normalize_t01_fixture()
self._entry_raw = self._snapshot_raw()
def _mes_lifecycle_successor_snapshot_4(self):
return {'schema': 'rescopebench-mes-lifecycle-stream/v5', 'raw': self._snapshot_raw(), 'active_task_id': self.active_task_id, 'applied_boundary_events': sorted(self.applied_boundary_events), 'receipts': ext_deepcopy(self.receipts), 'budget': self._budget(), 'budget_contract': {'evidence_read_units_allowance': self.read_allowance, 'mutation_attempts_allowance': self.mutation_allowance}, 'stream': {'activated_tasks': list(self._activated_tasks), 'task_targets': ext_deepcopy(self._task_targets), 'entry_raw': ext_deepcopy(self._entry_raw)}, 'interface_contract': {'alias_namespace': 'mes-closeout-public-identifiers/v5', 'scope': ext_deepcopy(DATA_SCOPE_CONTRACT), 'read_charges': ext_deepcopy(DATA_READ_CHARGES_2)}, 'allocation_sha256': fn_allocation_report_4(self.source)['assignment_sha256'], 'provider_tools_sha256': 'c781596331405790a753f40c31b864fb1ff867aed767f4206987c5d3ad6022bc'}
def _mes_lifecycle_successor_restore_4(self, snapshot):
if snapshot.get('schema') != 'rescopebench-mes-lifecycle-stream/v5':
raise ValueError('unsupported MES lifecycle snapshot schema')
self._restore_raw(ext_deepcopy(snapshot['raw']))
self.active_task_id = snapshot.get('active_task_id')
self.applied_boundary_events = set(snapshot.get('applied_boundary_events', []))
self.receipts = ext_deepcopy(snapshot.get('receipts', []))
budget = snapshot['budget']
contract = snapshot['budget_contract']
self.read_allowance = int(contract['evidence_read_units_allowance'])
self.read_used = int(budget['evidence_read_units_used'])
self.mutation_allowance = int(contract['mutation_attempts_allowance'])
self.mutation_used = int(budget['mutation_attempts_used'])
self.initial_budget = self.read_allowance
self.remaining = self.read_allowance - self.read_used
stream = snapshot['stream']
self._activated_tasks = list(stream['activated_tasks'])
self._task_targets = ext_deepcopy(stream['task_targets'])
self._entry_raw = ext_deepcopy(stream['entry_raw'])
self._rebuild_aliases()
class TimeDefaultServer:
def __init__(self, server):
self.server = server
def __getattr__(self, name):
return getattr(self.server, name)
def call_tool(self, tool_name, state_manager=None, **arguments):
if tool_name == 'finalize_operation_step' and 'actual_end_at' not in arguments:
step = state_manager.get_entity('operation_step', arguments.get('step_id'), id_field='step_id')
if step and step.get('status') == 'running':
arguments['actual_end_at'] = fn_default_end(step.get('actual_start_at'))
elif tool_name == 'finalize_production_order' and 'completed_at' not in arguments:
steps = state_manager.query_entities('operation_step', lambda s: s.get('order_id') == arguments.get('order_id'))
arguments['completed_at'] = fn_default_completion(steps)
return self.server.call_tool(tool_name, state_manager=state_manager, **arguments)