File size: 100,028 Bytes
f726fd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 | """Released environment operations and snapshot validation."""
from __future__ import annotations
from copy import deepcopy as ext_deepcopy
from functools import lru_cache
from pathlib import Path as ext_Path
from rescopebench.agent_runtime.protocol import public_feedback as ext_public_feedback
from typing import Any as ext_Any
import hashlib as mod_hashlib
import importlib as mod_importlib
import json as mod_json
import jsonschema as mod_jsonschema
import re as mod_re
import sys as mod_sys
from .spec import CASE_DIR, DATA_SCHEDULE_2, DATA_INSTANCE_SPECS, DATA_STREAM_TASK_IDS, DATA_CHANGED_STRUCTURE_ATOMS, DATA_DRIFT_WORKSPACE_ATOMS, DATA_POLICY_EXECUTION_FIELDS, DATA_LANE_NAMES, DATA_TOOLS_2, DATA_TOOL_BY_NAME, DATA_WRITE_TOOLS, DATA__PUBLIC_TARGET_IDS, DATA_STREAM_TASK_BLUEPRINT, DATA_STREAM_CLUSTERS, DATA_DEV_CLUSTERS, DATA_DEV_TARGET_PAIRS, DATA_STREAM_TASK_BLUEPRINT_2, DATA_ENTITY_ID_FIELDS, DATA_DRIFT_CHANGED_STRUCTURES, DATA_INSTANCE_SPECS_2, DATA__SNAPSHOT_METADATA_FIELDS, DATA_INSTANCE_SPECS_3, DATA_DRIFT_CHANGED_RULES, DATA_STREAM_TASK_BLUEPRINT_3, DATA_STREAM_TASK_BLUEPRINT_4, DATA_INSTANCE_SPECS_4, DATA_INSTANCE_SPECS_5, DATA_STREAM_TASK_BLUEPRINT_5, DATA_INSTANCE_SPECS_6, DATA_TOOLS_3, DATA_INSTANCE_SPECS_7, DATA_STREAM_TASK_BLUEPRINT_6, DATA_STREAM_TASK_BLUEPRINT_7
def fn_public_boundary_projection(receipt):
activation = receipt.get('activation')
notice = receipt.get('public_notice')
if not isinstance(activation, dict) or not isinstance(notice, str):
raise ValueError('boundary receipt is missing public activation data')
result = {'schema': 'rescopebench-filesystem-stream-boundary-public/v1', 'event_id': activation.get('event_id'), 'activation': {'event_type': 'manifest_request_activation', 'event_id': activation.get('event_id'), 'request_ids': ext_deepcopy(activation.get('request_ids') or []), 'world_reset': False}, 'public_notice': notice}
encoded = mod_json.dumps(result, ensure_ascii=True, sort_keys=True).casefold()
forbidden = ('t09', 'drift', 'policy_version', 'rule_atom', 'structure_atom', 'environment change', 'routing token changed')
if any((value in encoded for value in forbidden)):
raise ValueError('public boundary exposes a private stream transition')
return result
def fn_public_grade(grade):
components: dict[str, dict[str, int]] = {}
for row in grade.get('deliverables', []):
target_id = row.get('target_id')
if not isinstance(target_id, str) or target_id not in DATA__PUBLIC_TARGET_IDS:
raise ValueError('grade contains a non-public target reference')
for (milestone, passed) in row.get('milestones', {}).items():
if type(passed) is not bool:
raise ValueError('grade milestones must be booleans')
components[f'{target_id}:{milestone}'] = {'correct': int(passed), 'total': 1}
if len(components) != 20:
raise ValueError('grade must expose five milestones for four requests')
result = {'score': grade['score'], 'public_components': components}
ext_public_feedback(result)
return result
def fn__error(code, message, **data):
return {'status': 'error', 'data': {'error_code': code, **data}, 'message': message}
def fn_public_task(task_id):
packet = fn_public_task_2(task_id)
packet['schema'] = 'rescopebench-filesystem-stream-task/independent-v2'
packet['objective'] = packet['objective'].replace('listed priority order', 'any order')
packet['completion'].update(mode='independent', priority_order='none')
packet['completion']['request_order'] = 'These manifest requests are independent. An incomplete request does not block another request; permissions, current delivery policies, destination capacity and existing-file constraints still apply to every materialization.'
return packet
def fn__render_manifest(manifest, selected_nodes):
criteria = manifest.get('criteria') or {}
lines = [f"Manifest: {manifest.get('name')}", f"Base path: {criteria.get('base_path')}", f"Extensions: {', '.join(criteria.get('extensions') or [])}", '']
for node in sorted(selected_nodes, key=lambda item: item.get('path', '')):
lines.append(f"- {node.get('path')} ({node.get('node_type')}, {node.get('size_bytes')} bytes)")
return '\n'.join(lines)
def fn__operation_filename(public_name, task_id, slot):
internal_name = f'{public_name} Batch {fn__batch_token(task_id, slot)}'
return f'{fn__slugify(internal_name)}-index.md'
def fn__checksum_text(text):
return 'sha256:' + mod_hashlib.sha256(text.encode('utf-8')).hexdigest()
def fn__line_count(text):
return 0 if text == '' else len(text.splitlines()) or 1
@lru_cache(**{'maxsize': 64, 'typed': False})
def fn__binding_fixture(task_id):
pairs = DATA_STREAM_TASK_BLUEPRINT.get(task_id)
if pairs is None:
raise ValueError(f'unknown stream task: {task_id}')
fixture = fn__build_fixture('private-template', DATA_STREAM_CLUSTERS, pairs, post_drift=False)
by_pair = {(row['structure_atom'], 'a' if int(row['rule_atom'][1:]) % 2 else 'b'): row for row in fixture['targets']}
fixture['targets'] = [by_pair[pair] for pair in pairs]
public_by_name = {row['manifest_name']: row for row in fixture['public_targets']}
fixture['public_targets'] = [public_by_name[row['manifest_name']] for row in fixture['targets']]
return ext_deepcopy(fixture)
def fn__source_manifest(fixture, manifest_id):
return next((row for row in fixture['entities']['manifest'] if row['manifest_id'] == manifest_id))
def fn__copy_binding(manifest, source, *, task_id, slot):
value = ext_deepcopy(manifest)
value.update({'workspace_id': source['workspace_id'], 'criteria': ext_deepcopy(source['criteria']), 'selected_node_ids': ext_deepcopy(source['selected_node_ids']), 'delivery_policy': ext_deepcopy(source['delivery_policy']), 'rule_atom': source['rule_atom'], 'updated_at': '2026-05-28T12:00:00Z'})
value['name'] = f"{value['public_name']} Batch {fn__batch_token(task_id, slot)}"
return value
def fn__event_id(task_id):
return 'evt-' + fn__opaque('event', task_id, length=20)
def fn__successor_lane_id(atom_id, lane_name):
material = f"{'filesystem-c-14-01-54-structure-v9'}|lane|{atom_id}|{lane_name}"
return 'node-lane-' + mod_hashlib.sha256(material.encode('ascii')).hexdigest()[:24]
def fn__drift_event_id():
material = f"{'filesystem-c-14-01-54-structure-v9'}|multi-workspace-destination-handle-rotation"
return 'change-' + mod_hashlib.sha256(material.encode('ascii')).hexdigest()[:20]
def fn__workspace_id(atom_id):
cluster = fn__cluster(atom_id)
return f"workspace-{cluster['code']}-k4"
def fn__successor_lane_id_2(lane_name):
return 'node-lane-' + fn__opaque_2('lane', 'S07', lane_name)
def fn__successor_lane_id_3(atom_id, lane_name):
return 'node-lane-' + fn__opaque_3('lane', atom_id, lane_name)
def fn__digest(value):
payload = mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), allow_nan=False).encode('ascii')
return mod_hashlib.sha256(payload).hexdigest()
def fn__success(data):
return {'status': 'success', 'data': data, 'message': ''}
def fn__workspace_id_2(atom_id, *, post_drift):
cluster = fn__cluster_by_atom(atom_id)
suffix = fn__handle_suffix(atom_id, post_drift=post_drift)
return f"workspace-{cluster['code']}-{suffix}"
def fn_fixture_for_task(task_id):
if task_id == 'DEV01':
return fn__build_fixture(task_id, DATA_DEV_CLUSTERS, DATA_DEV_TARGET_PAIRS)
pairs = DATA_STREAM_TASK_BLUEPRINT_2.get(task_id)
if pairs is None:
raise ValueError(f'unknown task: {task_id}')
return fn__build_fixture(task_id, DATA_STREAM_CLUSTERS, pairs, post_drift=int(task_id[1:]) >= 9)
def fn__canonical_hash(value):
payload = mod_json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
return mod_hashlib.sha256(payload.encode('utf-8')).hexdigest()
def fn__normalize_result(result):
normalized = ext_deepcopy(result)
if normalized.get('status') == 'error':
data = normalized.setdefault('data', {})
if not data.get('error_code'):
message = str(normalized.get('message') or '')
data['error_code'] = message.split(':', 1)[0] if ':' in message else 'OPERATION_FAILED'
return normalized
def fn__initial_entities():
entities = fn__initial_entities_2()
entities['manifest'] = []
entities['operation'] = []
entities['snapshot'] = []
created: set[str] = set()
for task_id in DATA_STREAM_TASK_IDS:
fixture = fn__binding_fixture(task_id)
for (spec, target) in zip(DATA_INSTANCE_SPECS[task_id], fixture['targets']):
if spec['manifest_id'] in created:
continue
source = fn__source_manifest(fixture, target['manifest_id'])
manifest = ext_deepcopy(source)
manifest.update({'manifest_id': spec['manifest_id'], 'public_name': spec['public_name'], 'request_id': spec['request_id'], 'private_activation_task_id': task_id, 'private_activation_slot': spec['slot'], 'experience_activation_state': 'inactive', 'status': 'draft', 'materialized_node_id': None, 'materialized_destination_node_id': None, 'materialized_policy_version': None})
manifest = fn__copy_binding(manifest, source, task_id=task_id, slot=spec['slot'])
entities['manifest'].append(manifest)
created.add(spec['manifest_id'])
return entities
def fn__validated_metadata(snapshot):
if not isinstance(snapshot, dict):
raise ValueError('filesystem v9 snapshot must be an object')
if 'stable_identity_v9' not in snapshot:
raise ValueError('filesystem v9 snapshot metadata is missing')
converted = ext_deepcopy(snapshot)
converted['stable_identity_v8'] = converted.pop('stable_identity_v9')
return fn__validated_metadata_2(converted)
def fn_public_task_2(task_id):
packet = fn_rebound(fn_public_task_3, INSTANCE_SPECS=DATA_INSTANCE_SPECS)(task_id)
packet['schema'] = 'rescopebench-filesystem-stream-task/evolution-v1'
packet['completion'].pop('verification_required')
packet['completion']['evidence'] = {'mode': 'authoritative_receipt', 'source': 'materialize_manifest', 'proves': 'the generated index, committed destination and policy linkage reported in the receipt'}
return packet
def fn__batch_token(task_id, slot):
return fn__opaque('batch', task_id, slot, length=12).upper()
def fn__slugify(value):
text = mod_re.sub('[^a-z0-9]+', '-', str(value or '').strip().lower())
return mod_re.sub('-+', '-', text).strip('-') or 'item'
def fn__build_fixture(task_id, clusters, target_pairs, *, post_drift=False):
entities: dict[str, list[dict[str, ext_Any]]] = {name: [] for name in DATA_ENTITY_ID_FIELDS}
entities['user'] = [{'user_id': 'user-filesystem-dev', 'full_name': 'Filesystem Development Editor', 'email_address': 'filesystem.editor@example.invalid', 'role': 'workspace_editor', 'status': 'active', 'created_at': '2026-05-28T12:00:00Z', 'updated_at': '2026-05-28T12:00:00Z'}, {'user_id': 'user-filesystem-maintainer', 'full_name': 'Filesystem Fixture Maintainer', 'email_address': 'filesystem.maintainer@example.invalid', 'role': 'workspace_maintainer', 'status': 'active', 'created_at': '2026-05-28T12:00:00Z', 'updated_at': '2026-05-28T12:00:00Z'}]
target_set = set(target_pairs)
targets: list[dict[str, ext_Any]] = []
public_targets: list[dict[str, ext_Any]] = []
for (cluster_index, cluster) in enumerate(clusters):
atom_id = cluster['atom_id']
code = cluster['code']
suffix = fn__handle_suffix(atom_id, post_drift=post_drift)
workspace_id = f'workspace-{code}-{suffix}'
team_id = f'team-{code}-{suffix}'
root_id = f'node-{code}-{suffix}-r8'
source_hub_id = f'node-{code}-{suffix}-s3'
lane_hub_id = f'node-{code}-{suffix}-d6'
root_path = f"/{fn__slugify(cluster['workspace_name'])}"
base_permission = {'mode': 'rwxr-x---', 'inheritance': 'explicit', 'inherited_from_node_id': None, 'owner_user_id': 'user-filesystem-dev', 'owner_team_id': team_id, 'team_overrides': [], 'user_overrides': []}
inherited_from_root = {'inheritance': 'inherited', 'inherited_from_node_id': root_id}
inherited_from_source = {'inheritance': 'inherited', 'inherited_from_node_id': source_hub_id}
inherited_from_lanes = {'inheritance': 'inherited', 'inherited_from_node_id': lane_hub_id}
entities['workspace'].append({'workspace_id': workspace_id, 'name': cluster['workspace_name'], 'workspace_kind': 'records', 'root_node_id': root_id, 'status': 'active', 'quota_bytes': 8192, 'used_bytes': 0, 'default_retention_days': 180, 'created_at': '2026-05-28T12:00:00Z', 'updated_at': '2026-05-28T12:00:00Z'})
entities['team'].append({'team_id': team_id, 'workspace_id': workspace_id, 'name': f"{cluster['workspace_name']} Team", 'status': 'active', 'maintainer_user_ids': ['user-filesystem-maintainer'], 'member_user_ids': ['user-filesystem-dev'], 'created_at': '2026-05-28T12:00:00Z', 'updated_at': '2026-05-28T12:00:00Z'})
nodes = [fn__directory_node(node_id=root_id, workspace_id=workspace_id, parent_node_id=None, name=cluster['workspace_name'], path=root_path, depth=0, permission=base_permission), fn__directory_node(node_id=source_hub_id, workspace_id=workspace_id, parent_node_id=root_id, name='source-records', path=f'{root_path}/source-records', depth=1, permission=inherited_from_root), fn__directory_node(node_id=lane_hub_id, workspace_id=workspace_id, parent_node_id=root_id, name='delivery-lanes', path=f'{root_path}/delivery-lanes', depth=1, permission=inherited_from_root)]
lane_nodes: dict[str, dict[str, ext_Any]] = {}
for lane_name in DATA_LANE_NAMES:
lane = fn__directory_node(node_id=fn__lane_node_id(cluster, lane_name, post_drift=post_drift), workspace_id=workspace_id, parent_node_id=lane_hub_id, name=lane_name, path=f'{root_path}/delivery-lanes/{lane_name}', depth=2, permission=inherited_from_lanes, purpose='delivery_lane')
lane_nodes[lane_name] = lane
nodes.append(lane)
source_nodes: list[dict[str, ext_Any]] = []
for source_index in range(1, 5):
file_name = f'record-{cluster_index + 1}-{source_index}.txt'
node_id = f'node-{code}-{suffix}-f{source_index}'
content_id = f'content-{code}-{suffix}-f{source_index}'
text = f"workspace={cluster['workspace_name']}\nrecord={source_index}\ncontrol={code}-{source_index}\n"
node = {'node_id': node_id, 'workspace_id': workspace_id, 'parent_node_id': source_hub_id, 'name': file_name, 'node_type': 'file', 'path': f'{root_path}/source-records/{file_name}', 'extension': 'txt', 'mime_type': 'text/plain', 'size_bytes': len(text.encode('utf-8')), 'content_ref': content_id, 'checksum': fn__checksum_text(text), 'depth': 2, 'is_deleted': False, 'is_archived': False, 'permission': inherited_from_source, 'created_by': 'user-filesystem-maintainer', 'updated_by': 'user-filesystem-maintainer', 'created_at': '2026-05-28T12:00:00Z', 'updated_at': '2026-05-28T12:00:00Z'}
source_nodes.append(node)
nodes.append(node)
entities['file_content'].append({'content_id': content_id, 'node_id': node_id, 'encoding': 'utf-8', 'line_count': fn__line_count(text), 'text': text, 'created_at': '2026-05-28T12:00:00Z', 'updated_at': '2026-05-28T12:00:00Z'})
entities['node'].extend(nodes)
for (manifest_key, manifest_spec) in cluster['manifests'].items():
policy = fn__effective_policy(manifest_spec, post_drift=post_drift)
manifest_id = f'manifest-{code}-{suffix}-{manifest_key}5'
selected = source_nodes[:2] if manifest_key == 'a' else source_nodes[2:]
manifest = {'manifest_id': manifest_id, 'workspace_id': workspace_id, 'name': manifest_spec['name'], 'criteria': {'base_path': f'{root_path}/source-records', 'extensions': ['txt'], 'include_archived': False}, 'selected_node_ids': [node['node_id'] for node in selected], 'status': 'draft', 'materialized_node_id': None, 'delivery_policy': {'lane_name': policy['lane_name'], 'policy_version': policy['policy_version'], 'routing_token': policy['routing_token']}, 'rule_atom': policy['rule_atom'], 'created_by': 'user-filesystem-maintainer', 'created_at': '2026-05-28T12:00:00Z', 'updated_at': '2026-05-28T12:00:00Z'}
entities['manifest'].append(manifest)
if (atom_id, manifest_key) not in target_set:
continue
lane = lane_nodes[policy['lane_name']]
expected_text = fn__render_manifest(manifest, selected)
target_id = f'manifest-{task_id.lower()}-{len(targets) + 1}'
target = {'target_id': target_id, 'structure_atom': atom_id, 'rule_atom': policy['rule_atom'], 'workspace_id': workspace_id, 'workspace_name': cluster['workspace_name'], 'manifest_id': manifest_id, 'manifest_name': manifest_spec['name'], 'lane_hub_id': lane_hub_id, 'delivery_lanes': {name: {'node_id': value['node_id'], 'path': value['path']} for (name, value) in lane_nodes.items()}, 'delivery_lane': policy['lane_name'], 'destination_parent_node_id': lane['node_id'], 'policy_version': policy['policy_version'], 'routing_token': policy['routing_token'], 'selected_node_ids': [node['node_id'] for node in selected], 'expected_file_name': f"{fn__slugify(manifest_spec['name'])}-index.md", 'expected_path': f"{lane['path']}/{fn__slugify(manifest_spec['name'])}-index.md", 'expected_text': expected_text, 'expected_checksum': fn__checksum_text(expected_text), 'expected_size_bytes': len(expected_text.encode('utf-8')), 'expected_line_count': fn__line_count(expected_text)}
targets.append(target)
public_targets.append({'target_id': target_id, 'workspace_name': cluster['workspace_name'], 'manifest_name': manifest_spec['name']})
entities['workspace'][-1]['used_bytes'] = sum((int(node.get('size_bytes') or 0) for node in nodes if node.get('node_type') == 'file' and (not node.get('is_deleted'))))
if len(targets) != 4:
raise ValueError(f'{task_id} must compile exactly four targets')
return {'task_id': task_id, 'actor_user_id': 'user-filesystem-dev', 'entities': entities, 'targets': targets, 'public_targets': public_targets, 'post_drift': post_drift}
def fn__opaque(kind, *parts, length=24):
material = '|'.join(['rescopebench-filesystem-stream-v2', kind, *(str(part) for part in parts)])
return mod_hashlib.sha256(material.encode('ascii')).hexdigest()[:length]
def fn__workspace_name(atom_id):
return next((row['workspace_name'] for row in DATA_STREAM_CLUSTERS if row['atom_id'] == atom_id))
def fn__cluster(atom_id):
return next((row for row in DATA_STREAM_CLUSTERS if row['atom_id'] == atom_id))
def fn__opaque_2(kind, *parts, length=24):
material = '|'.join(['filesystem-c-14-01-54-structure-v4', kind, *(str(part) for part in parts)])
return mod_hashlib.sha256(material.encode('ascii')).hexdigest()[:length]
def fn__opaque_3(kind, *parts, length=24):
material = '|'.join(['filesystem-c-14-01-54-structure-v3', kind, *(str(part) for part in parts)])
return mod_hashlib.sha256(material.encode('ascii')).hexdigest()[:length]
def fn__cluster_by_atom(atom_id):
return next((row for row in DATA_STREAM_CLUSTERS if row['atom_id'] == atom_id))
def fn__handle_suffix(atom_id, *, post_drift):
return 'z9' if post_drift and atom_id in DATA_DRIFT_CHANGED_STRUCTURES else 'k4'
def fn__initial_entities_2():
pre = fn__binding_fixture_2('T01', False)
post = fn__binding_fixture_2('T01', True)
entities = ext_deepcopy(pre['entities'])
entities['manifest'] = []
entities['operation'] = []
entities['snapshot'] = []
pre_workspace_ids = {row['workspace_id'] for row in entities['workspace']}
changed_post_workspace_ids = {fn__workspace_id_2(atom_id, post_drift=True) for atom_id in DATA_DRIFT_CHANGED_STRUCTURES}
post_nodes = {row['node_id'] for row in post['entities']['node'] if row.get('workspace_id') in changed_post_workspace_ids}
for entity_type in ('workspace', 'team', 'node'):
id_field = DATA_ENTITY_ID_FIELDS[entity_type]
existing = {row[id_field] for row in entities[entity_type]}
for row in post['entities'][entity_type]:
if row.get('workspace_id') not in changed_post_workspace_ids:
continue
if row[id_field] not in existing:
entities[entity_type].append(ext_deepcopy(row))
existing.add(row[id_field])
content_ids = {row['content_id'] for row in entities['file_content']}
for row in post['entities']['file_content']:
if row.get('node_id') in post_nodes and row['content_id'] not in content_ids:
entities['file_content'].append(ext_deepcopy(row))
content_ids.add(row['content_id'])
for workspace in entities['workspace']:
workspace['stream_generation'] = 'post_drift' if workspace['workspace_id'] in changed_post_workspace_ids else 'pre_drift'
workspace['experience_activation_state'] = 'inactive' if workspace['workspace_id'] in changed_post_workspace_ids else 'active'
if len(pre_workspace_ids) != len(DATA_STREAM_CLUSTERS):
raise ValueError('pre-drift world does not contain every stream workspace')
for task_id in DATA_STREAM_TASK_IDS:
fixture = fn__binding_fixture_2(task_id, False)
for (spec, target) in zip(DATA_INSTANCE_SPECS_2[task_id], fixture['targets']):
source = fn__source_manifest(fixture, target['manifest_id'])
manifest = ext_deepcopy(source)
manifest.update({'manifest_id': spec['manifest_id'], 'public_name': spec['public_name'], 'request_id': spec['request_id'], 'private_activation_task_id': task_id, 'private_activation_slot': spec['slot'], 'experience_activation_state': 'inactive', 'status': 'draft', 'materialized_node_id': None, 'materialized_destination_node_id': None, 'materialized_policy_version': None})
manifest = fn__copy_binding(manifest, source, task_id=task_id, slot=spec['slot'])
entities['manifest'].append(manifest)
return entities
def fn__validated_metadata_2(snapshot):
if not isinstance(snapshot, dict):
raise ValueError('filesystem v8 snapshot must be an object')
if 'stable_identity_v8' not in snapshot:
raise ValueError('filesystem v8 snapshot metadata is missing')
metadata = snapshot['stable_identity_v8']
if not isinstance(metadata, dict) or set(metadata) != DATA__SNAPSHOT_METADATA_FIELDS:
raise ValueError('filesystem v8 snapshot metadata shape differs')
for field in ('pending_policy_revalidation', 'fresh_policy_evidence', 'attempted_t09_manifests'):
values = metadata[field]
if not isinstance(values, list) or not all((isinstance(value, str) for value in values)):
raise ValueError(f'filesystem v8 snapshot {field} must be string list')
expected = metadata['expected_t09_stale_bindings']
if not isinstance(expected, dict) or not all((isinstance(key, str) and isinstance(value, dict) for (key, value) in expected.items())):
raise ValueError('filesystem v8 snapshot expected stale bindings must be an object')
return ext_deepcopy(metadata)
def fn_rebound(function, **overrides):
result = function(function.__code__, {**function.__globals__, **overrides}, function.__name__, function.__defaults__, function.__closure__)
result.__kwdefaults__ = ext_deepcopy(function.__kwdefaults__)
return result
def fn_public_task_3(task_id):
if task_id not in DATA_INSTANCE_SPECS_3:
raise ValueError(f'unknown stream task: {task_id}')
packet = ext_deepcopy(fn_public_task_4(task_id))
packet['schema'] = 'rescopebench-filesystem-stream-task/v9'
packet['targets'] = [{'target_id': row['request_id'], 'workspace_name': row['workspace_name'], 'manifest_name': row['public_name']} for row in DATA_INSTANCE_SPECS_3[task_id]]
return packet
def fn__directory_node(*, node_id, workspace_id, parent_node_id, name, path, depth, permission, purpose=None):
node = {'node_id': node_id, 'workspace_id': workspace_id, 'parent_node_id': parent_node_id, 'name': name, 'node_type': 'directory', 'path': path, 'extension': None, 'mime_type': None, 'size_bytes': 0, 'content_ref': None, 'checksum': None, 'depth': depth, 'is_deleted': False, 'is_archived': False, 'permission': ext_deepcopy(permission), 'created_by': 'user-filesystem-maintainer', 'updated_by': 'user-filesystem-maintainer', 'created_at': '2026-05-28T12:00:00Z', 'updated_at': '2026-05-28T12:00:00Z'}
if purpose:
node['purpose'] = purpose
return node
def fn__lane_node_id(cluster, lane_name, *, post_drift):
tokens = cluster['lane_tokens']
if post_drift and cluster['atom_id'] in DATA_DRIFT_CHANGED_STRUCTURES:
tokens = cluster['post_drift_lane_tokens']
if not tokens or lane_name not in tokens:
raise ValueError(f"{cluster['atom_id']} has no opaque lane token for {lane_name}")
return f'node-lane-{tokens[lane_name]}'
def fn__effective_policy(policy, *, post_drift):
value = ext_deepcopy(policy)
if post_drift and value['rule_atom'] in DATA_DRIFT_CHANGED_RULES:
value['lane_name'] = fn__rotated_lane(value['lane_name'])
value['policy_version'] = 'v2'
else:
value['policy_version'] = 'v1'
token_material = f"rescopebench-filesystem-route-capability-v1|{value['rule_atom']}|{value['policy_version']}"
value['routing_token'] = 'route-' + mod_hashlib.sha256(token_material.encode('ascii')).hexdigest()[:24]
return value
def fn__initial_entities_3():
entities = fn__initial_entities_2()
entities['manifest'] = []
entities['operation'] = []
entities['snapshot'] = []
created: set[str] = set()
for task_id in DATA_STREAM_TASK_IDS:
fixture = fn__binding_fixture_3(task_id)
for (spec, target) in zip(DATA_INSTANCE_SPECS_3[task_id], fixture['targets']):
if spec['manifest_id'] in created:
continue
source = fn__source_manifest(fixture, target['manifest_id'])
manifest = ext_deepcopy(source)
manifest.update({'manifest_id': spec['manifest_id'], 'public_name': spec['public_name'], 'request_id': spec['request_id'], 'private_activation_task_id': task_id, 'private_activation_slot': spec['slot'], 'experience_activation_state': 'inactive', 'status': 'draft', 'materialized_node_id': None, 'materialized_destination_node_id': None, 'materialized_policy_version': None})
manifest = fn__copy_binding(manifest, source, task_id=task_id, slot=spec['slot'])
entities['manifest'].append(manifest)
created.add(spec['manifest_id'])
return entities
@lru_cache(**{'maxsize': 64, 'typed': False})
def fn__binding_fixture_2(task_id, post_drift):
pairs = DATA_STREAM_TASK_BLUEPRINT_3.get(task_id)
if pairs is None:
raise ValueError(f'unknown stream task: {task_id}')
fixture = fn__build_fixture('private-template', DATA_STREAM_CLUSTERS, pairs, post_drift=post_drift)
return ext_deepcopy(fixture)
def fn_public_task_4(task_id):
packet = ext_deepcopy(fn_public_task_5(task_id))
packet['schema'] = 'rescopebench-filesystem-stream-task/v8'
return packet
def fn__rotated_lane(lane_name):
return DATA_LANE_NAMES[(DATA_LANE_NAMES.index(lane_name) + 1) % len(DATA_LANE_NAMES)]
@lru_cache(**{'maxsize': 64, 'typed': False})
def fn__binding_fixture_3(task_id):
pairs = DATA_STREAM_TASK_BLUEPRINT_4.get(task_id)
if pairs is None:
raise ValueError(f'unknown stream task: {task_id}')
fixture = fn__build_fixture('private-template', DATA_STREAM_CLUSTERS, pairs, post_drift=False)
by_pair = {(row['structure_atom'], 'a' if int(row['rule_atom'][1:]) % 2 else 'b'): row for row in fixture['targets']}
fixture['targets'] = [by_pair[pair] for pair in pairs]
public_by_name = {row['manifest_name']: row for row in fixture['public_targets']}
fixture['public_targets'] = [public_by_name[row['manifest_name']] for row in fixture['targets']]
return ext_deepcopy(fixture)
def fn_public_task_5(task_id):
if task_id not in DATA_INSTANCE_SPECS_4:
raise ValueError(f'unknown stream task: {task_id}')
packet = ext_deepcopy(fn_public_task_6(task_id))
packet['schema'] = 'rescopebench-filesystem-stream-task/v7'
packet['objective'] = 'Materialize as many of the four requested manifest indexes as possible in listed priority order. Resolve each current manifest and its workspace delivery-lane handles, obey the current delivery policy, and place the generated index in the exact eligible lane. A successful materialize_manifest receipt confirms completion; no extra readback is required. Retain exact manifest identity, workspace-to-lane, and policy bindings so a recurring manifest can be executed without redundant reads unless ordinary tool evidence shows that a binding is stale.'
packet['targets'] = [{'target_id': row['request_id'], 'workspace_name': row['workspace_name'], 'manifest_name': row['public_name']} for row in DATA_INSTANCE_SPECS_4[task_id]]
return packet
def fn__initial_entities_4():
entities = fn__initial_entities_2()
entities['manifest'] = []
entities['operation'] = []
entities['snapshot'] = []
created: set[str] = set()
for task_id in DATA_STREAM_TASK_IDS:
fixture = fn__binding_fixture_4(task_id)
for (spec, target) in zip(DATA_INSTANCE_SPECS_4[task_id], fixture['targets']):
if spec['manifest_id'] in created:
continue
source = fn__source_manifest(fixture, target['manifest_id'])
manifest = ext_deepcopy(source)
manifest.update({'manifest_id': spec['manifest_id'], 'public_name': spec['public_name'], 'request_id': spec['request_id'], 'private_activation_task_id': task_id, 'private_activation_slot': spec['slot'], 'experience_activation_state': 'inactive', 'status': 'draft', 'materialized_node_id': None, 'materialized_destination_node_id': None, 'materialized_policy_version': None})
manifest = fn__copy_binding(manifest, source, task_id=task_id, slot=spec['slot'])
entities['manifest'].append(manifest)
created.add(spec['manifest_id'])
return entities
def fn_public_task_6(task_id):
if task_id not in DATA_INSTANCE_SPECS_5:
raise ValueError(f'unknown stream task: {task_id}')
return {'schema': 'rescopebench-filesystem-stream-task/v6', 'task_id': fn__event_id(task_id), 'episode_id': fn__event_id(task_id), 'event_id': fn__event_id(task_id), 'objective': 'Materialize as many of the four requested manifest indexes as possible in listed priority order. Resolve each current manifest and its workspace delivery-lane handles, obey the current delivery policy, and place the generated index in the exact eligible lane. A successful materialize_manifest receipt confirms completion; no extra readback is required. Retain exact workspace-to-lane and manifest-policy bindings separately so either stable component can be reused.', 'targets': [{'target_id': row['request_id'], 'workspace_name': row['workspace_name'], 'manifest_name': row['public_name']} for row in DATA_INSTANCE_SPECS_5[task_id]], 'completion': {'mode': 'ordered_independent', 'subset_allowed': True, 'priority_order': 'listed', 'started_item_must_close': True, 'verification_required': True, 'verification_evidence': 'successful materialize_manifest receipt', 'extra_readback_required': False}, 'budget': ext_deepcopy(fn_public_task_7(task_id)['budget'])}
def fn__initial_entities_5():
entities = fn__initial_entities_2()
entities['manifest'] = []
entities['operation'] = []
entities['snapshot'] = []
for task_id in DATA_STREAM_TASK_IDS:
fixture = fn__binding_fixture_4(task_id)
for (spec, target) in zip(DATA_INSTANCE_SPECS_5[task_id], fixture['targets']):
source = fn__source_manifest(fixture, target['manifest_id'])
manifest = ext_deepcopy(source)
manifest.update({'manifest_id': spec['manifest_id'], 'public_name': spec['public_name'], 'request_id': spec['request_id'], 'private_activation_task_id': task_id, 'private_activation_slot': spec['slot'], 'experience_activation_state': 'inactive', 'status': 'draft', 'materialized_node_id': None, 'materialized_destination_node_id': None, 'materialized_policy_version': None})
manifest = fn__copy_binding(manifest, source, task_id=task_id, slot=spec['slot'])
entities['manifest'].append(manifest)
return entities
@lru_cache(**{'maxsize': 64, 'typed': False})
def fn__binding_fixture_4(task_id):
pairs = DATA_STREAM_TASK_BLUEPRINT_5.get(task_id)
if pairs is None:
raise ValueError(f'unknown stream task: {task_id}')
fixture = fn__build_fixture('private-template', DATA_STREAM_CLUSTERS, pairs, post_drift=False)
by_pair = {(row['structure_atom'], 'a' if int(row['rule_atom'][1:]) % 2 else 'b'): row for row in fixture['targets']}
fixture['targets'] = [by_pair[pair] for pair in pairs]
public_by_name = {row['manifest_name']: row for row in fixture['public_targets']}
fixture['public_targets'] = [public_by_name[row['manifest_name']] for row in fixture['targets']]
return ext_deepcopy(fixture)
def fn_public_task_7(task_id):
if task_id not in DATA_INSTANCE_SPECS_6:
raise ValueError(f'unknown stream task: {task_id}')
return {'schema': 'rescopebench-filesystem-stream-task/v5', 'task_id': fn__event_id(task_id), 'episode_id': fn__event_id(task_id), 'event_id': fn__event_id(task_id), 'objective': 'Materialize as many of the four requested manifest indexes as possible in listed priority order. Resolve each current manifest and its workspace delivery-lane handles, obey the current delivery policy, and place the generated index in the exact eligible lane. A successful materialize_manifest receipt confirms completion; no extra readback is required.', 'targets': [{'target_id': row['request_id'], 'workspace_name': row['workspace_name'], 'manifest_name': row['public_name']} for row in DATA_INSTANCE_SPECS_6[task_id]], 'completion': {'mode': 'ordered_independent', 'subset_allowed': True, 'priority_order': 'listed', 'started_item_must_close': True, 'verification_required': True, 'verification_evidence': 'successful materialize_manifest receipt', 'extra_readback_required': False}, 'budget': {'limits': [{'resource': 'returned_work_units', 'allowance': 9}, {'resource': 'mutation_attempts', 'allowance': 9}, {'resource': 'call_guard', 'allowance': 32}], 'charging': ['Each returned manifest row consumes one returned-work unit.', 'Each returned delivery-lane row consumes one returned-work unit.', 'A successful detailed manifest policy result consumes three returned-work units, one for each executable field: delivery_lane, routing_token, and overwrite_existing.', 'Every schema-valid materialization attempt consumes one mutation attempt.'], 'exhaustion': 'An unfunded business call fails without committing business-state changes.', 'persistence': 'Allowances reset at each request event; committed filesystem records persist.'}}
def fn__initial_entities_6():
entities = fn__initial_entities_2()
entities['manifest'] = []
entities['operation'] = []
entities['snapshot'] = []
for task_id in DATA_STREAM_TASK_IDS:
fixture = fn__binding_fixture_5(task_id)
for (spec, target) in zip(DATA_INSTANCE_SPECS_6[task_id], fixture['targets']):
source = fn__source_manifest(fixture, target['manifest_id'])
manifest = ext_deepcopy(source)
manifest.update({'manifest_id': spec['manifest_id'], 'public_name': spec['public_name'], 'request_id': spec['request_id'], 'private_activation_task_id': task_id, 'private_activation_slot': spec['slot'], 'experience_activation_state': 'inactive', 'status': 'draft', 'materialized_node_id': None, 'materialized_destination_node_id': None, 'materialized_policy_version': None})
manifest = fn__copy_binding(manifest, source, task_id=task_id, slot=spec['slot'])
entities['manifest'].append(manifest)
return entities
def fn__initial_entities_7():
entities = fn__initial_entities_2()
entities['manifest'] = []
entities['operation'] = []
entities['snapshot'] = []
for task_id in DATA_STREAM_TASK_IDS:
fixture = fn__binding_fixture_6(task_id)
for (spec, target) in zip(DATA_INSTANCE_SPECS_7[task_id], fixture['targets']):
source = fn__source_manifest(fixture, target['manifest_id'])
manifest = ext_deepcopy(source)
manifest.update({'manifest_id': spec['manifest_id'], 'public_name': spec['public_name'], 'request_id': spec['request_id'], 'private_activation_task_id': task_id, 'private_activation_slot': spec['slot'], 'experience_activation_state': 'inactive', 'status': 'draft', 'materialized_node_id': None, 'materialized_destination_node_id': None, 'materialized_policy_version': None})
manifest = fn__copy_binding(manifest, source, task_id=task_id, slot=spec['slot'])
entities['manifest'].append(manifest)
return entities
@lru_cache(**{'maxsize': 64, 'typed': False})
def fn__binding_fixture_5(task_id):
pairs = DATA_STREAM_TASK_BLUEPRINT_6.get(task_id)
if pairs is None:
raise ValueError(f'unknown stream task: {task_id}')
fixture = fn__build_fixture('private-template', DATA_STREAM_CLUSTERS, pairs, post_drift=False)
by_pair = {(row['structure_atom'], 'a' if int(row['rule_atom'][1:]) % 2 else 'b'): row for row in fixture['targets']}
fixture['targets'] = [by_pair[pair] for pair in pairs]
public_by_name = {row['manifest_name']: row for row in fixture['public_targets']}
fixture['public_targets'] = [public_by_name[row['manifest_name']] for row in fixture['targets']]
return ext_deepcopy(fixture)
@lru_cache(**{'maxsize': 64, 'typed': False})
def fn__binding_fixture_6(task_id):
pairs = DATA_STREAM_TASK_BLUEPRINT_7.get(task_id)
if pairs is None:
raise ValueError(f'unknown stream task: {task_id}')
return ext_deepcopy(fn__build_fixture('private-template', DATA_STREAM_CLUSTERS, pairs, post_drift=False))
@lru_cache(**{'maxsize': 4, 'typed': False})
def fn__load_raw_logic(source_root):
prefix = 'mcp_servers'
saved = {name: module for (name, module) in list(mod_sys.modules.items()) if name == prefix or name.startswith(f'{prefix}.')}
for name in saved:
mod_sys.modules.pop(name, None)
mod_sys.path.insert(0, source_root)
try:
implementation = mod_importlib.import_module('mcp_servers.filesystem')
def recursive_effective_permission(state_manager, node):
current = ext_deepcopy(node)
seen: set[str] = set()
while True:
permission = ext_deepcopy(current.get('permission') or {})
parent_id = permission.get('inherited_from_node_id')
if permission.get('inheritance') != 'inherited' or not parent_id:
return permission
if parent_id in seen:
return permission
seen.add(parent_id)
parent = state_manager.get_entity('node', parent_id)
if parent is None:
return permission
current = parent
implementation._effective_permission = recursive_effective_permission
implementation.now_iso = lambda : '2026-05-28T12:00:00Z'
finally:
mod_sys.path.remove(source_root)
for name in list(mod_sys.modules):
if name == prefix or name.startswith(f'{prefix}.'):
mod_sys.modules.pop(name, None)
mod_sys.modules.update(saved)
return implementation
class World:
def __init__(self, *args, **kwargs):
self._filesystem_evolution_init(*args, **kwargs)
self._enforce_t09_priority = False
def _materialize_manifest(self, arguments, actor_user_id):
manifest = self._state.get_entity('manifest', arguments['manifest_id'], 'manifest_id')
if not self._is_active_manifest(manifest):
return fn__error('MANIFEST_NOT_ACTIVE', 'manifest is not active in the current request batch')
return self._file_system_progressive_structure_stream_adapter_materialize_manifest(arguments, actor_user_id)
def snapshot(self):
value = self._file_system_smoothed_multi_drift_stream_adapter_snapshot()
value['evolution_contract'] = {'case_version': 'filesystem-independent-requests-evolution-v2', 'schedule': ext_deepcopy(DATA_SCHEDULE_2)}
return value
def restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('evolution_contract', None) != {'case_version': 'filesystem-independent-requests-evolution-v2', 'schedule': DATA_SCHEDULE_2}:
raise ValueError('Filesystem evolution contract differs')
self._file_system_smoothed_multi_drift_stream_adapter_restore(value)
def public_snapshot(self):
task = fn_public_task(self._task_id) if self._task_id else None
return {'schema': 'rescopebench-filesystem-stream-public-snapshot/v1', 'active_event_id': task['event_id'] if task else None, 'active_request_ids': [row['target_id'] for row in task['targets']] if task else [], 'budget': self._budget()}
def _manifest_for_spec(self, task_id, slot):
manifest_id = DATA_INSTANCE_SPECS[task_id][slot - 1]['manifest_id']
manifest = self._state.get_entity('manifest', manifest_id, 'manifest_id')
if manifest is None:
raise ValueError('stable stream manifest is missing')
return manifest
def _current_target(self, task_id, slot):
spec = DATA_INSTANCE_SPECS[task_id][slot - 1]
manifest = self._manifest_for_spec(task_id, slot)
workspace = self._state.get_entity('workspace', manifest['workspace_id'], 'workspace_id')
if workspace is None:
raise ValueError('target workspace is missing')
lane_nodes = {row['name']: row for row in self._state.list_entities('node') if row.get('workspace_id') == workspace['workspace_id'] and row.get('purpose') == 'delivery_lane' and (not row.get('is_deleted'))}
policy = manifest.get('delivery_policy') or {}
lane = lane_nodes.get(policy.get('lane_name'))
if lane is None:
raise ValueError('target delivery lane is missing')
nodes = {row['node_id']: row for row in self._state.list_entities('node')}
selected = [nodes[node_id] for node_id in manifest['selected_node_ids']]
expected_text = fn__render_manifest(manifest, selected)
filename = fn__operation_filename(spec['public_name'], task_id, slot)
return {'target_id': spec['request_id'], 'structure_atom': spec['structure_atom'], 'binding_atom': spec['binding_atom'], 'rule_atom': spec['rule_atom'], 'workspace_id': workspace['workspace_id'], 'workspace_name': spec['workspace_name'], 'manifest_id': manifest['manifest_id'], 'manifest_name': spec['public_name'], 'delivery_lanes': {name: {'node_id': row['node_id'], 'path': row['path']} for (name, row) in lane_nodes.items()}, 'delivery_lane': policy['lane_name'], 'destination_parent_node_id': lane['node_id'], 'policy_version': policy['policy_version'], 'routing_token': policy['routing_token'], 'selected_node_ids': ext_deepcopy(manifest['selected_node_ids']), 'expected_file_name': filename, 'expected_path': f"{lane['path']}/{filename}", 'expected_text': expected_text, 'expected_checksum': fn__checksum_text(expected_text), 'expected_size_bytes': len(expected_text.encode('utf-8')), 'expected_line_count': fn__line_count(expected_text)}
def _activate(self, task_id):
request_ids = []
fixture = fn__binding_fixture(task_id)
for (slot, (spec, target)) in enumerate(zip(DATA_INSTANCE_SPECS[task_id], fixture['targets']), 1):
manifest = self._manifest_for_spec(task_id, slot)
if manifest.get('experience_activation_state') not in {'inactive', 'closed'}:
raise ValueError('stable manifest is already active')
source = fn__source_manifest(fixture, target['manifest_id'])
activated = fn__copy_binding(manifest, source, task_id=task_id, slot=slot)
activated.update({'public_name': spec['public_name'], 'request_id': spec['request_id'], 'private_activation_task_id': task_id, 'private_activation_slot': slot, 'experience_activation_state': 'active', 'status': 'draft', 'materialized_node_id': None, 'materialized_destination_node_id': None, 'materialized_policy_version': None, 'updated_at': '2026-05-28T12:00:00Z'})
if not self._workspace_allowed(activated['workspace_id'], 'user-filesystem-dev'):
raise ValueError('next manifest belongs to an inactive workspace')
self._state.add_entity('manifest', activated, 'manifest_id')
request_ids.append(spec['request_id'])
self._task_id = task_id
self._stream_position = DATA_STREAM_TASK_IDS.index(task_id) + 1
self._task_targets = [self._current_target(task_id, slot) for slot in range(1, 5)]
self._events = []
self._calls = 0
self._read_units = 0
self._write_attempts = 0
self._fresh_policy_evidence = set()
self._attempted_t09_manifests = set()
self._assert_state_invariants()
return {'event_type': 'manifest_request_activation', 'event_id': fn__event_id(task_id), 'private_task_id': task_id, 'request_ids': sorted(request_ids), 'created_manifest_ids': sorted((target['manifest_id'] for target in self._task_targets)), 'world_reset': False}
def _capture_t09_stale_bindings(self):
bindings: dict[str, dict[str, ext_Any]] = {}
active_lanes = {(row.get('workspace_id'), row.get('name')): row for row in self._state.list_entities('node') if row.get('purpose') == 'delivery_lane' and (not row.get('is_deleted'))}
for spec in DATA_INSTANCE_SPECS['T07']:
if spec['binding_atom'] not in DATA_CHANGED_STRUCTURE_ATOMS:
continue
manifest = self._state.get_entity('manifest', spec['manifest_id'], 'manifest_id')
if manifest is None:
raise ValueError('T09 stable stale-binding manifest is missing')
policy = manifest.get('delivery_policy') or {}
lane = active_lanes.get((manifest['workspace_id'], policy.get('lane_name')))
if lane is None:
raise ValueError('T09 pre-drift delivery lane is missing')
bindings[manifest['manifest_id']] = {'workspace_id': manifest['workspace_id'], 'manifest_id': manifest['manifest_id'], 'destination_parent_node_id': lane['node_id'], 'routing_token': policy.get('routing_token'), 'overwrite_existing': False}
if len(bindings) != len(DATA_CHANGED_STRUCTURE_ATOMS):
raise ValueError('T09 stale-binding coverage is incomplete')
return bindings
def _repeat_receipt(self, task_id):
current = self.business_semantic_hash()
drift = self._apply_scheduled_drift() if task_id == 'T07' and self._drift_applied else None
receipt = {'schema': 'rescopebench-filesystem-stream-boundary/v2', 'previous_private_task_id': task_id, 'next_private_task_id': task_id, 'already_prepared': True, 'before_sha256': current, 'after_sha256': current, 'closed': {'closed_request_ids': [], 'preserved_output_node_ids': []}, 'drift': drift, 'activation': {'event_type': 'manifest_request_activation', 'event_id': fn__event_id(task_id), 'private_task_id': task_id, 'request_ids': sorted((row['request_id'] for row in DATA_INSTANCE_SPECS[task_id])), 'created_manifest_ids': [], 'world_reset': False}, 'public_notice': f'Manifest request event {fn__event_id(task_id)} is active. The current request batch is ready; prior business records were preserved.', 'preservation_contract': {'world_reset': False, 'completed_manifests_preserved': True, 'generated_files_preserved': True, 'operation_records_preserved': True, 'episode_budgets_unchanged_on_repeat': True}}
fn_public_boundary_projection(receipt)
return receipt
def _rotate_workspace_destination_handles(self, atom_id):
if atom_id != 'S07':
return self._file_system_smoothed_multi_drift_stream_adapter_rotate_workspace_destination_handles(atom_id)
target = next((row for row in fn__binding_fixture('T07')['targets'] if row['structure_atom'] == 'S07'))
workspace = next((row for row in self._state.list_entities('workspace') if row['name'] == target['workspace_name']))
old = next((row for row in self._state.list_entities('node') if row['workspace_id'] == workspace['workspace_id'] and row.get('purpose') == 'delivery_lane' and (not row.get('is_deleted')) and (row['name'] == target['delivery_lane'])))
new_id = fn__successor_lane_id(atom_id, old['name'])
if self._state.get_entity('node', new_id, 'node_id') is not None:
raise ValueError('successor lane exists before drift')
self._state.update_entity('node', old['node_id'], {'is_deleted': True, 'purpose': 'retired_delivery_lane', 'updated_at': '2026-05-28T12:00:00Z'}, 'node_id')
self._state.add_entity('node', {**ext_deepcopy(old), 'node_id': new_id, 'updated_at': '2026-05-28T12:00:00Z'}, 'node_id')
return {old['node_id']: new_id}
def prepare_episode(self, task_id, *, evaluator_apply_scheduled_drift=None):
if task_id == self._task_id:
return self._repeat_receipt(task_id)
tasks = DATA_STREAM_TASK_IDS
if self._stream_position >= len(tasks) or task_id != tasks[self._stream_position]:
raise ValueError('out-of-order Filesystem task activation')
if evaluator_apply_scheduled_drift is not None and task_id != 'T07':
raise ValueError('drift override outside the event boundary')
(before, previous_task) = (self.business_semantic_hash(), self._task_id)
(closed, drift) = (self._close_current(), None)
if task_id == 'T07':
if evaluator_apply_scheduled_drift is not False:
drift = self._apply_scheduled_drift()
else:
self._counterfactual_no_drift = True
elif self._stream_position >= DATA_SCHEDULE_2['events'][0]['before_task'] and (not self._drift_applied):
raise ValueError('post-boundary tasks require the scheduled event')
activation = self._activate(task_id)
receipt = {'schema': 'rescopebench-filesystem-stream-boundary/v2', 'previous_private_task_id': previous_task, 'next_private_task_id': task_id, 'already_prepared': False, 'before_sha256': before, 'after_sha256': self.business_semantic_hash(), 'closed': closed, 'drift': drift, 'activation': activation, 'public_notice': f'Manifest request event {fn__event_id(task_id)} is active. The new request batch is ready; prior business records were preserved.', 'preservation_contract': {'world_reset': False, 'completed_manifests_preserved': True, 'generated_files_preserved': True, 'operation_records_preserved': True, 'episode_budgets_reset': True}}
fn_public_boundary_projection(receipt)
return receipt
def _apply_scheduled_drift(self):
if self._drift_applied:
current = self.business_semantic_hash()
return {'schema': 'rescopebench-filesystem-drift-application/v1', 'event_id': fn__drift_event_id(), 'status': 'already_applied', 'applied_now': False, 'duplicate_noop': True, 'exactly_once': True, 'publicly_announced': False, 'application_before_sha256': self._drift_application_before_sha256, 'application_after_sha256': self._drift_application_after_sha256, 'call_before_sha256': current, 'call_after_sha256': current, 'event_sequence': self._drift_event_seq}
expected = self._capture_t09_stale_bindings()
before = self.business_semantic_hash()
rotated = {atom_id: self._rotate_workspace_destination_handles(atom_id) for atom_id in DATA_DRIFT_WORKSPACE_ATOMS}
self._expected_t09_stale_bindings = expected
self._drift_applied = True
self._drift_event_seq += 1
self._drift_application_before_sha256 = before
after = self.business_semantic_hash()
self._drift_application_after_sha256 = after
self._assert_state_invariants()
return {'schema': 'rescopebench-filesystem-drift-application/v1', 'event_id': fn__drift_event_id(), 'status': 'applied', 'applied_now': True, 'duplicate_noop': False, 'exactly_once': True, 'publicly_announced': False, 'changed_structure_atoms': sorted(DATA_CHANGED_STRUCTURE_ATOMS), 'changed_rule_atoms': [], 'rotated_destination_handles': rotated, 'application_before_sha256': before, 'application_after_sha256': after, 'call_before_sha256': before, 'call_after_sha256': after, 'event_sequence': self._drift_event_seq}
def _arguments_match_current_policy(self, arguments):
manifest = self._state.get_entity('manifest', arguments['manifest_id'], 'manifest_id')
if not manifest or manifest.get('workspace_id') != arguments['workspace_id']:
return False
destination = self._state.get_entity('node', arguments['destination_parent_node_id'], 'node_id')
if not destination or destination.get('workspace_id') != arguments['workspace_id']:
return False
policy = manifest.get('delivery_policy') or {}
return bool(arguments['routing_token'] == policy.get('routing_token') and destination.get('purpose') == 'delivery_lane' and (destination.get('name') == policy.get('lane_name')))
def _stable_binding_key(self, manifest):
workspace = self._state.get_entity('workspace', manifest['workspace_id'], 'workspace_id')
if workspace is None:
raise ValueError('manifest workspace is missing')
return f"{workspace['name']}\x1f{manifest['public_name']}"
def _matches_expected_t09_stale_binding(self, arguments):
expected = self._expected_t09_stale_bindings.get(arguments['manifest_id'])
return expected is not None and all((arguments.get(field) == value for (field, value) in expected.items()))
def call(self, name, arguments):
result = self._file_system_stream_adapter_call(name, arguments)
if name == 'get_delivery_policy' and result.get('status') == 'success':
manifest = self._state.get_entity('manifest', arguments['manifest_id'], 'manifest_id')
if manifest is not None:
key = self._stable_binding_key(manifest)
if key in self._pending_policy_revalidation:
self._fresh_policy_evidence.add(key)
return result
@staticmethod
def _read_cost(name, result):
if name == 'get_delivery_policy' and result.get('status') == 'success':
data = result.get('data') or {}
if all((field in data for field in DATA_POLICY_EXECUTION_FIELDS)):
return 3
return World._file_system_adapter_read_cost(name, result)
def _rotate_s07_destination_handles(self):
workspace_id = fn__workspace_id('S07')
lanes = [row for row in self._state.list_entities('node') if row.get('workspace_id') == workspace_id and row.get('purpose') == 'delivery_lane' and (not row.get('is_deleted'))]
if {row.get('name') for row in lanes} != set(DATA_LANE_NAMES):
raise ValueError('S07 does not have one active handle per lane')
rotated: dict[str, str] = {}
for old in lanes:
lane_name = old['name']
new_id = fn__successor_lane_id_2(lane_name)
if self._state.get_entity('node', new_id, 'node_id') is not None:
raise ValueError('successor lane handle already exists before the event')
self._state.update_entity('node', old['node_id'], {'is_deleted': True, 'purpose': 'retired_delivery_lane', 'updated_at': '2026-05-28T12:00:00Z'}, 'node_id')
current = ext_deepcopy(old)
current.update({'node_id': new_id, 'is_deleted': False, 'purpose': 'delivery_lane', 'updated_at': '2026-05-28T12:00:00Z'})
self._state.add_entity('node', current, 'node_id')
rotated[old['node_id']] = new_id
return rotated
def _get_delivery_policy(self, arguments, actor_user_id):
result = self._file_system_stream_adapter_get_delivery_policy(arguments, actor_user_id)
if result.get('status') == 'success':
result.get('data', {}).pop('policy_version', None)
return result
def _rotate_destination_handles(self, atom_id):
workspace_id = fn__workspace_id(atom_id)
lanes = [row for row in self._state.list_entities('node') if row.get('workspace_id') == workspace_id and row.get('purpose') == 'delivery_lane' and (not row.get('is_deleted'))]
if {row.get('name') for row in lanes} != set(DATA_LANE_NAMES):
raise ValueError(f'{atom_id} does not have one active handle per lane')
rotated: dict[str, str] = {}
for old in lanes:
lane_name = old['name']
new_id = fn__successor_lane_id_3(atom_id, lane_name)
if self._state.get_entity('node', new_id, 'node_id') is not None:
raise ValueError('successor lane handle already exists before the event')
self._state.update_entity('node', old['node_id'], {'is_deleted': True, 'purpose': 'retired_delivery_lane', 'updated_at': '2026-05-28T12:00:00Z'}, 'node_id')
current = ext_deepcopy(old)
current.update({'node_id': new_id, 'is_deleted': False, 'purpose': 'delivery_lane', 'updated_at': '2026-05-28T12:00:00Z'})
self._state.add_entity('node', current, 'node_id')
rotated[old['node_id']] = new_id
return rotated
def _stream_metadata(self):
return {'position': self._stream_position, 'drift_applied': self._drift_applied, 'drift_event_seq': self._drift_event_seq, 'drift_application_before_sha256': self._drift_application_before_sha256, 'drift_application_after_sha256': self._drift_application_after_sha256, 'counterfactual_no_drift': self._counterfactual_no_drift}
def semantic_hash(self, snapshot=None):
return fn__digest(snapshot if snapshot is not None else self.snapshot())
def business_state(self):
return {'entities': self._state.list_snapshot(), 'stream': {'position': self._stream_position, 'drift_applied': self._drift_applied, 'drift_event_seq': self._drift_event_seq}}
def business_semantic_hash(self):
return fn__digest(self.business_state())
def _workspace_by_name(self, workspace_name):
needle = workspace_name.strip().lower()
rows = [row for row in self._state.list_entities('workspace') if str(row.get('name') or '').strip().lower() == needle and row.get('experience_activation_state') == 'active']
if len(rows) > 1:
raise ValueError('multiple active workspace generations share one name')
return rows[0] if rows else None
def _workspace_allowed(self, workspace_id, actor_user_id):
workspace = self._state.get_entity('workspace', workspace_id, 'workspace_id')
return bool(workspace and workspace.get('experience_activation_state') == 'active' and self._file_system_adapter_workspace_allowed(workspace_id, actor_user_id))
@staticmethod
def _is_active_manifest(manifest):
return bool(manifest and manifest.get('experience_activation_state') == 'active')
def _list_manifest_requests(self, arguments, actor_user_id):
workspace = self._workspace_by_name(arguments['workspace_name'])
if not workspace:
return fn__error('WORKSPACE_NOT_FOUND', 'workspace does not exist')
workspace_id = workspace['workspace_id']
if not self._workspace_allowed(workspace_id, actor_user_id):
return fn__error('ACTOR_WORKSPACE_SCOPE_DENIED', 'actor is not assigned to the active workspace')
needle = arguments['manifest_name'].strip().lower()
rows = [row for row in self._state.list_entities('manifest') if row.get('workspace_id') == workspace_id and row.get('experience_activation_state') == 'active' and (str(row.get('public_name') or '').strip().lower() == needle)]
rows.sort(key=lambda row: row['manifest_id'])
return fn__success({'manifests': [{'manifest_id': row['manifest_id'], 'workspace_id': row['workspace_id'], 'name': row['public_name'], 'status': row.get('status'), 'selected_node_count': len(row.get('selected_node_ids') or [])} for row in rows[:1]], 'total_count': len(rows)})
def _close_current(self):
if self._task_id is None:
return {'closed_request_ids': [], 'preserved_output_node_ids': []}
closed = []
outputs = []
for target in self._task_targets:
manifest = self._state.get_entity('manifest', target['manifest_id'], 'manifest_id')
if manifest is None:
raise ValueError('active manifest disappeared before boundary')
if manifest.get('materialized_node_id'):
outputs.append(manifest['materialized_node_id'])
self._state.update_entity('manifest', manifest['manifest_id'], {'experience_activation_state': 'closed', 'updated_at': '2026-05-28T12:00:00Z'}, 'manifest_id')
closed.append(target['target_id'])
return {'closed_request_ids': sorted(closed), 'preserved_output_node_ids': sorted(outputs)}
def _set_workspace_generation(self, atom_id, *, post_drift):
pre_id = fn__workspace_id_2(atom_id, post_drift=False)
post_id = fn__workspace_id_2(atom_id, post_drift=True)
self._state.update_entity('workspace', pre_id, {'experience_activation_state': 'retired' if post_drift else 'active'}, 'workspace_id')
self._state.update_entity('workspace', post_id, {'experience_activation_state': 'active' if post_drift else 'inactive'}, 'workspace_id')
def activate_task(self, task_id):
try:
fixture = fn_fixture_for_task(task_id)
except ValueError:
return fn__error('TASK_NOT_EXECUTABLE', 'task has no compiled fixture')
self._state = MemoryState(fixture['entities'])
self._task_id = task_id
self._task_targets = ext_deepcopy(fixture['targets'])
self._events = []
self._calls = 0
self._read_units = 0
self._write_attempts = 0
self._assert_state_invariants()
return fn__success({'task_id': task_id})
def public_tool_schemas(self, role):
return ext_deepcopy(DATA_TOOLS_2) if role == 'workspace_editor' else []
def business_events(self, since=0):
if not isinstance(since, int) or isinstance(since, bool) or since < 0:
raise ValueError('since must be a non-negative integer')
return ext_deepcopy(self._events[since:])
def task_targets(self):
return ext_deepcopy(self._task_targets)
def _actor(self, actor_user_id):
actor = self._state.get_entity('user', actor_user_id, 'user_id')
if not actor or actor.get('status') != 'active' or actor.get('role') != 'workspace_editor':
return None
return actor
def _budget(self):
return {'read_work_units_used': self._read_units, 'read_work_units_remaining': max(0, 9 - self._read_units), 'write_attempts_used': self._write_attempts, 'write_attempts_remaining': max(0, 9 - self._write_attempts)}
def _business_hash(self):
return fn__canonical_hash({'entities': self._state.list_snapshot(), 'counters': self._state.counters_snapshot()})
def _list_delivery_lanes(self, arguments, actor_user_id):
workspace_id = arguments['workspace_id']
workspace = self._state.get_entity('workspace', workspace_id, 'workspace_id')
if not workspace:
return fn__error('WORKSPACE_NOT_FOUND', 'workspace does not exist')
if not self._workspace_allowed(workspace_id, actor_user_id):
return fn__error('ACTOR_WORKSPACE_SCOPE_DENIED', 'actor is not assigned to the workspace')
rows = [row for row in self._state.list_entities('node') if row.get('workspace_id') == workspace_id and row.get('purpose') == 'delivery_lane' and (not row.get('is_deleted'))]
rows.sort(key=lambda row: row.get('name', ''))
return fn__success({'workspace_id': workspace_id, 'lanes': [{'name': row['name'], 'node_id': row['node_id'], 'path': row['path']} for row in rows]})
def _get_node(self, arguments, actor_user_id):
node = self._state.get_entity('node', arguments['node_id'], 'node_id')
if not node or node.get('workspace_id') != arguments['workspace_id']:
return fn__error('NODE_NOT_FOUND', 'node does not exist in the workspace')
if not self._workspace_allowed(arguments['workspace_id'], actor_user_id) or not self._impl._can_read(self._state, node, actor_user_id):
return fn__error('PERMISSION_DENIED', 'actor cannot read the node')
result = fn__normalize_result(self._impl.get_node(self._state, workspace_id=arguments['workspace_id'], node_id=arguments['node_id'], include_deleted=False))
if result.get('status') == 'success':
result.get('data', {}).get('node', {}).pop('permission', None)
return result
def _get_file_content(self, arguments, actor_user_id):
node = self._state.get_entity('node', arguments['node_id'], 'node_id')
if not node or node.get('workspace_id') != arguments['workspace_id']:
return fn__error('NODE_NOT_FOUND', 'file does not exist in the workspace')
if not self._workspace_allowed(arguments['workspace_id'], actor_user_id) or not self._impl._can_read(self._state, node, actor_user_id):
return fn__error('PERMISSION_DENIED', 'actor cannot read the file')
return fn__normalize_result(self._impl.get_file_content(self._state, workspace_id=arguments['workspace_id'], node_id=arguments['node_id'], start_line=arguments.get('start_line', 1), line_count=arguments.get('line_count', 20)))
def _inspect_quota(self, arguments, actor_user_id):
if not self._workspace_allowed(arguments['workspace_id'], actor_user_id):
return fn__error('ACTOR_WORKSPACE_SCOPE_DENIED', 'actor is not assigned to the workspace')
return fn__normalize_result(self._impl.inspect_quota(self._state, workspace_id=arguments['workspace_id'], include_breakdown=False))
def _read(self, name, arguments, actor_user_id):
return {'list_manifest_requests': self._list_manifest_requests, 'list_delivery_lanes': self._list_delivery_lanes, 'get_delivery_policy': self._get_delivery_policy, 'get_node': self._get_node, 'get_file_content': self._get_file_content, 'inspect_quota': self._inspect_quota}[name](arguments, actor_user_id)
def _write(self, name, arguments, actor_user_id):
return {'materialize_manifest': self._materialize_manifest}[name](arguments, actor_user_id)
def _record_event(self, name, actor_user_id, result, before_hash, after_hash, cost):
self._events.append({'sequence': len(self._events) + 1, 'channel': 'learner', 'tool': name, 'actor_user_id': actor_user_id, 'status': result.get('status'), 'error_code': result.get('data', {}).get('error_code'), 'cost': ext_deepcopy(cost), 'budget_after': self._budget(), 'state_hash_before': before_hash, 'state_hash_after': after_hash})
def _assert_state_invariants(self):
nodes = self._state.list_entities('node')
by_id = {row['node_id']: row for row in nodes}
contents = {row['content_id']: row for row in self._state.list_entities('file_content')}
sibling_keys: set[tuple[str, str]] = set()
for node in nodes:
if node.get('is_deleted'):
continue
parent_id = node.get('parent_node_id')
if parent_id:
parent = by_id.get(parent_id)
if not parent:
raise ValueError('node references a missing parent')
expected_path = f"{parent.get('path').rstrip('/')}/{node.get('name')}"
if node.get('path') != expected_path:
raise ValueError('node path does not match its parent')
sibling_key = (parent_id, str(node.get('name') or '').strip().lower())
if sibling_key in sibling_keys:
raise ValueError('live sibling names are not unique')
sibling_keys.add(sibling_key)
if node.get('node_type') == 'file':
content = contents.get(node.get('content_ref'))
if not content:
raise ValueError('file node has no content row')
text = str(content.get('text') or '')
if int(node.get('size_bytes') or 0) != len(text.encode('utf-8')):
raise ValueError('file byte accounting diverged')
if node.get('checksum') != fn__checksum_text(text):
raise ValueError('file checksum diverged')
if int(content.get('line_count') or 0) != fn__line_count(text):
raise ValueError('file line accounting diverged')
for workspace in self._state.list_entities('workspace'):
live_bytes = sum((int(node.get('size_bytes') or 0) for node in nodes if node.get('workspace_id') == workspace['workspace_id'] and node.get('node_type') == 'file' and (not node.get('is_deleted'))))
if int(workspace.get('used_bytes') or 0) != live_bytes:
raise ValueError('workspace usage does not reconcile')
if live_bytes > int(workspace.get('quota_bytes') or 0):
raise ValueError('workspace quota is exceeded')
for manifest in self._state.list_entities('manifest'):
if manifest.get('status') != 'materialized':
continue
materialized = by_id.get(manifest.get('materialized_node_id'))
if not materialized or materialized.get('node_type') != 'file':
raise ValueError('materialized manifest has no generated file')
selected = [by_id.get(node_id) for node_id in manifest.get('selected_node_ids') or []]
if any((node is None for node in selected)):
raise ValueError('manifest selection references missing nodes')
content = contents.get(materialized.get('content_ref'))
if not content or content.get('text') != fn__render_manifest(manifest, selected):
raise ValueError('materialized manifest content diverged from provenance')
policy = manifest.get('delivery_policy') or {}
destination = by_id.get(materialized.get('parent_node_id'))
if not destination or destination.get('name') != policy.get('lane_name'):
raise ValueError('materialized manifest violates its delivery policy')
def dispatch(self, name, arguments, actor_user_id):
if self._task_id is None:
return fn__error('TASK_NOT_ACTIVE', 'activate a task before dispatch')
tool = DATA_TOOL_BY_NAME.get(name)
if tool is None:
return fn__error('TOOL_NOT_ALLOWED', 'tool is not in the learner allowlist')
if self._actor(actor_user_id) is None:
return fn__error('ACTOR_NOT_AUTHORIZED', 'actor is not an active workspace editor')
try:
mod_jsonschema.validate(arguments, tool['input_schema'])
except mod_jsonschema.ValidationError:
return fn__error('INVALID_ARGUMENTS', 'arguments do not match the public tool schema')
if self._calls >= 32:
return fn__error('CALL_GUARD_EXHAUSTED', 'the runaway safety guard is exhausted')
if name in DATA_WRITE_TOOLS and self._write_attempts >= 9:
result = fn__error('WRITE_BUDGET_EXHAUSTED', 'the mutation-attempt budget is exhausted')
result['budget'] = self._budget()
return result
if name not in DATA_WRITE_TOOLS and self._read_units >= 9:
result = fn__error('READ_BUDGET_EXHAUSTED', 'the returned-work budget is exhausted')
result['budget'] = self._budget()
return result
before = self.snapshot()
before_hash = self._business_hash()
try:
if name in DATA_WRITE_TOOLS:
result = self._write(name, ext_deepcopy(arguments), actor_user_id)
if result.get('status') == 'success':
self._assert_state_invariants()
else:
result = self._read(name, ext_deepcopy(arguments), actor_user_id)
except Exception:
self._state.restore(before['entities'], before['counters'])
result = fn__error('ADAPTER_EXECUTION_FAILED', 'operation failed without committing state')
cost = {'read_work_units': 0, 'write_attempts': 0}
if name in DATA_WRITE_TOOLS:
self._write_attempts += 1
cost['write_attempts'] = 1
if result.get('status') != 'success':
self._state.restore(before['entities'], before['counters'])
else:
read_cost = self._read_cost(name, result)
remaining = 9 - self._read_units
if read_cost > remaining:
self._read_units = 9
result = fn__error('READ_BUDGET_EXHAUSTED', 'this read exceeds the remaining returned-work budget', required_units=read_cost, available_units=remaining)
read_cost = remaining
else:
self._read_units += read_cost
cost['read_work_units'] = read_cost
self._calls += 1
after_hash = self._business_hash()
result['budget'] = self._budget()
self._record_event(name, actor_user_id, result, before_hash, after_hash, cost)
return ext_deepcopy(result)
def grade(self, task_id):
if task_id != self._task_id:
raise ValueError('task is not active')
entities = self._state.list_snapshot()
nodes = {row['node_id']: row for row in entities['node']}
contents = {row['content_id']: row for row in entities['file_content']}
deliverables: list[dict[str, ext_Any]] = []
for target in self._task_targets:
manifest = next((row for row in entities['manifest'] if row.get('manifest_id') == target['manifest_id']), None)
materialized = nodes.get(manifest.get('materialized_node_id')) if manifest else None
content = contents.get(materialized.get('content_ref')) if materialized else None
matching_files = [row for row in entities['node'] if not row.get('is_deleted') and row.get('workspace_id') == target['workspace_id'] and (row.get('name') == target['expected_file_name'])]
manifest_bound = bool(manifest and manifest.get('status') == 'materialized' and materialized and (len(matching_files) == 1))
correct_destination = bool(materialized and materialized.get('parent_node_id') == target['destination_parent_node_id'] and (materialized.get('path') == target['expected_path']) and (manifest.get('materialized_destination_node_id') == target['destination_parent_node_id']) and (manifest.get('materialized_policy_version') == target['policy_version']))
provenance_complete = bool(content and all((nodes.get(node_id) and nodes[node_id].get('path') in str(content.get('text') or '') for node_id in target['selected_node_ids'])) and (str(content.get('text') or '').count('\n- ') == len(target['selected_node_ids'])))
content_integrity = bool(materialized and content and (content.get('text') == target['expected_text']) and (materialized.get('checksum') == target['expected_checksum']) and (int(materialized.get('size_bytes') or 0) == target['expected_size_bytes']) and (int(content.get('line_count') or 0) == target['expected_line_count']))
workspace = next((row for row in entities['workspace'] if row['workspace_id'] == target['workspace_id']))
live_bytes = sum((int(row.get('size_bytes') or 0) for row in entities['node'] if row.get('workspace_id') == target['workspace_id'] and row.get('node_type') == 'file' and (not row.get('is_deleted'))))
operations = [row for row in entities['operation'] if materialized and row.get('target_node_id') == materialized.get('node_id') and (row.get('action') == 'create') and (row.get('status') == 'success')]
accounting_reconciled = bool(manifest_bound and int(workspace.get('used_bytes') or 0) == live_bytes and (live_bytes <= int(workspace.get('quota_bytes') or 0)) and (len(operations) == 1))
milestones = {'manifest_bound': manifest_bound, 'correct_destination': correct_destination, 'provenance_complete': provenance_complete, 'content_integrity': content_integrity, 'accounting_reconciled': accounting_reconciled}
points = {'manifest_bound': 2.5, 'correct_destination': 5.0, 'provenance_complete': 5.0, 'content_integrity': 5.0, 'accounting_reconciled': 7.5}
score = sum((points[name] for (name, passed) in milestones.items() if passed))
deliverables.append({'target_id': target['target_id'], 'score': score, 'completed': all(milestones.values()), 'milestones': milestones, 'materialized_node_id': materialized.get('node_id') if materialized else None})
return {'task_id': task_id, 'score': sum((row['score'] for row in deliverables)), 'max_score': 100.0, 'completed_artifacts': sum((row['completed'] for row in deliverables)), 'deliverables': deliverables, 'budget': self._budget()}
def _filesystem_evolution_init(self, snapshot=None, source_root=CASE_DIR / 'raw', *, _initialize=True):
self._file_system_structural_revision_init(snapshot=None, source_root=source_root, _initialize=False)
if snapshot is not None:
self.restore(snapshot)
elif _initialize:
self._state = MemoryState(fn__initial_entities())
self._assert_state_invariants()
def _file_system_progressive_structure_stream_adapter_materialize_manifest(self, arguments, actor_user_id):
if self._enforce_t09_priority and self._task_id == 'T09':
target_index = next((index for (index, target) in enumerate(self._task_targets) if target['manifest_id'] == arguments['manifest_id'] and target['workspace_id'] == arguments['workspace_id']), None)
if target_index is not None and target_index > 0:
prior_complete = all((self._state.get_entity('manifest', target['manifest_id'], 'manifest_id').get('status') == 'materialized' or target['manifest_id'] in self._attempted_t09_manifests for target in self._task_targets[:target_index]))
if not prior_complete:
return fn__error('PRIOR_TARGET_INCOMPLETE', 'complete earlier listed requests before this request')
manifest = self._state.get_entity('manifest', arguments['manifest_id'], 'manifest_id')
key = self._stable_binding_key(manifest) if manifest is not None else None
if self._enforce_revalidation and key in self._pending_policy_revalidation and (key not in self._fresh_policy_evidence) and self._arguments_match_current_policy(arguments):
return fn__error('REVALIDATION_REQUIRED', 'read current manifest policy evidence before retrying this binding')
result = self._file_system_structure_stream_adapter_materialize_manifest(arguments, actor_user_id)
error_code = result.get('data', {}).get('error_code')
if self._task_id == 'T09' and error_code == 'DELIVERY_POLICY_MISMATCH' and self._matches_expected_t09_stale_binding(arguments):
self._attempted_t09_manifests.add(arguments['manifest_id'])
if key is not None:
self._pending_policy_revalidation.add(key)
elif result.get('status') == 'success':
if self._task_id == 'T09':
self._attempted_t09_manifests.add(arguments['manifest_id'])
if key in self._fresh_policy_evidence:
self._pending_policy_revalidation.discard(key)
return result
def _file_system_smoothed_multi_drift_stream_adapter_snapshot(self):
value = self._file_system_closed_snapshot_stream_adapter_snapshot()
value['stable_identity_v9'] = value.pop('stable_identity_v8')
return value
def _file_system_smoothed_multi_drift_stream_adapter_restore(self, snapshot):
metadata = fn__validated_metadata(snapshot)
inherited = ext_deepcopy(snapshot)
inherited.pop('stable_identity_v9')
inherited['stable_identity_v8'] = metadata
self._file_system_closed_snapshot_stream_adapter_restore(inherited)
def _file_system_smoothed_multi_drift_stream_adapter_rotate_workspace_destination_handles(self, atom_id):
workspace_name = fn__workspace_name(atom_id)
workspace = next((row for row in self._state.list_entities('workspace') if row.get('name') == workspace_name and row.get('status') == 'active'))
lanes = [row for row in self._state.list_entities('node') if row.get('workspace_id') == workspace['workspace_id'] and row.get('purpose') == 'delivery_lane' and (not row.get('is_deleted'))]
if {row.get('name') for row in lanes} != set(DATA_LANE_NAMES):
raise ValueError(f'{atom_id} does not have one active handle per lane')
rotated: dict[str, str] = {}
for old in lanes:
new_id = fn__successor_lane_id(atom_id, old['name'])
if self._state.get_entity('node', new_id, 'node_id') is not None:
raise ValueError('successor lane handle already exists before drift')
self._state.update_entity('node', old['node_id'], {'is_deleted': True, 'purpose': 'retired_delivery_lane', 'updated_at': '2026-05-28T12:00:00Z'}, 'node_id')
current = ext_deepcopy(old)
current.update({'node_id': new_id, 'is_deleted': False, 'purpose': 'delivery_lane', 'updated_at': '2026-05-28T12:00:00Z'})
self._state.add_entity('node', current, 'node_id')
rotated[old['node_id']] = new_id
return rotated
def _file_system_stream_adapter_call(self, name, arguments):
return self.dispatch(name, arguments, 'user-filesystem-dev')
@staticmethod
def _file_system_adapter_read_cost(name, result):
if result.get('status') != 'success':
return 1
data = result.get('data') or {}
if name == 'list_manifest_requests':
return max(1, len(data.get('manifests') or []))
if name == 'list_delivery_lanes':
return max(1, len(data.get('lanes') or []))
if name == 'get_delivery_policy':
return 4
if name == 'get_file_content':
text = str((data.get('content') or {}).get('text') or '')
return max(1, (len(text.encode('utf-8')) + 127) // 128)
return 1
def _file_system_stream_adapter_get_delivery_policy(self, arguments, actor_user_id):
manifest = self._state.get_entity('manifest', arguments['manifest_id'], 'manifest_id')
if not self._is_active_manifest(manifest):
return fn__error('MANIFEST_NOT_ACTIVE', 'manifest is not active in the current request batch')
result = self._file_system_adapter_get_delivery_policy(arguments, actor_user_id)
if result.get('status') == 'success':
result['data']['manifest_name'] = manifest['public_name']
return result
def _file_system_adapter_workspace_allowed(self, workspace_id, actor_user_id):
return actor_user_id in self._impl._workspace_members(self._state, workspace_id)
def _file_system_structural_revision_init(self, snapshot=None, source_root=CASE_DIR / 'raw', *, _initialize=True):
self._file_system_smoothed_multi_drift_stream_adapter_init(snapshot=snapshot, source_root=source_root, _initialize=_initialize, _enforce_t09_priority=True, _enforce_revalidation=False)
def _file_system_structure_stream_adapter_materialize_manifest(self, arguments, actor_user_id):
result = self._file_system_stream_adapter_materialize_manifest(arguments, actor_user_id)
if result.get('status') == 'success':
result.get('data', {}).pop('policy_version', None)
return result
def _file_system_closed_snapshot_stream_adapter_snapshot(self):
value = self._file_system_stable_identity_stream_adapter_snapshot()
metadata = value.pop('stable_identity_v7')
value['stable_identity_v8'] = metadata
return value
def _file_system_closed_snapshot_stream_adapter_restore(self, snapshot):
metadata = fn__validated_metadata_2(snapshot)
inherited = ext_deepcopy(snapshot)
inherited.pop('stable_identity_v8')
inherited['stable_identity_v7'] = metadata
self._file_system_stable_identity_stream_adapter_restore(inherited)
def _file_system_adapter_get_delivery_policy(self, arguments, actor_user_id):
manifest = self._state.get_entity('manifest', arguments['manifest_id'], 'manifest_id')
if not manifest:
return fn__error('MANIFEST_NOT_FOUND', 'manifest does not exist')
if not self._workspace_allowed(manifest['workspace_id'], actor_user_id):
return fn__error('ACTOR_WORKSPACE_SCOPE_DENIED', 'actor is not assigned to the workspace')
policy = manifest.get('delivery_policy') or {}
return fn__success({'manifest_id': manifest['manifest_id'], 'manifest_name': manifest['name'], 'delivery_lane': policy.get('lane_name'), 'policy_version': policy.get('policy_version'), 'routing_token': policy.get('routing_token'), 'overwrite_existing': False})
def _file_system_smoothed_multi_drift_stream_adapter_init(self, snapshot=None, source_root=CASE_DIR / 'raw', *, _initialize=True, _enforce_t09_priority=True, _enforce_revalidation=True):
self._file_system_closed_snapshot_stream_adapter_init(snapshot=None, source_root=source_root, _initialize=False, _enforce_t09_priority=_enforce_t09_priority, _enforce_revalidation=_enforce_revalidation)
if snapshot is not None:
self.restore(snapshot)
elif _initialize:
self._state = MemoryState(fn__initial_entities_3())
self._assert_state_invariants()
def _file_system_stream_adapter_materialize_manifest(self, arguments, actor_user_id):
manifest = self._state.get_entity('manifest', arguments['manifest_id'], 'manifest_id')
if not self._is_active_manifest(manifest):
return fn__error('MANIFEST_NOT_ACTIVE', 'manifest is not active in the current request batch')
return self._file_system_adapter_materialize_manifest(arguments, actor_user_id)
def _file_system_stable_identity_stream_adapter_snapshot(self):
value = self._file_system_progressive_structure_stream_adapter_snapshot()
metadata = value.pop('progressive_v6')
value['stable_identity_v7'] = metadata
return value
def _file_system_stable_identity_stream_adapter_restore(self, snapshot):
metadata = ext_deepcopy(snapshot.get('stable_identity_v7') or {})
inherited = ext_deepcopy(snapshot)
inherited.pop('stable_identity_v7', None)
inherited['progressive_v6'] = metadata
self._file_system_progressive_structure_stream_adapter_restore(inherited)
def _file_system_closed_snapshot_stream_adapter_init(self, snapshot=None, source_root=CASE_DIR / 'raw', *, _initialize=True, _enforce_t09_priority=True, _enforce_revalidation=True):
self._file_system_stable_identity_stream_adapter_init(snapshot=None, source_root=source_root, _initialize=_initialize if snapshot is None else False, _enforce_t09_priority=_enforce_t09_priority, _enforce_revalidation=_enforce_revalidation)
if snapshot is not None:
self.restore(snapshot)
def _file_system_adapter_materialize_manifest(self, arguments, actor_user_id):
manifest = self._state.get_entity('manifest', arguments['manifest_id'], 'manifest_id')
if not manifest or manifest.get('workspace_id') != arguments['workspace_id']:
return fn__error('MANIFEST_NOT_FOUND', 'manifest does not exist in the workspace')
if not self._workspace_allowed(arguments['workspace_id'], actor_user_id):
return fn__error('ACTOR_WORKSPACE_SCOPE_DENIED', 'actor is not assigned to the workspace')
destination = self._state.get_entity('node', arguments['destination_parent_node_id'], 'node_id')
if not destination or destination.get('workspace_id') != arguments['workspace_id']:
return fn__error('NODE_NOT_FOUND', 'destination does not exist in the workspace')
policy = manifest.get('delivery_policy') or {}
if arguments['routing_token'] != policy.get('routing_token') or destination.get('purpose') != 'delivery_lane' or destination.get('name') != policy.get('lane_name'):
return fn__error('DELIVERY_POLICY_MISMATCH', 'request does not satisfy the current manifest delivery policy')
for selected_id in manifest.get('selected_node_ids') or []:
selected = self._state.get_entity('node', selected_id, 'node_id')
if not selected or not self._impl._can_read(self._state, selected, actor_user_id):
return fn__error('PERMISSION_DENIED', 'actor cannot read every selected manifest node')
result = fn__normalize_result(self._impl.materialize_manifest(self._state, workspace_id=arguments['workspace_id'], manifest_id=arguments['manifest_id'], destination_parent_node_id=arguments['destination_parent_node_id'], actor_user_id=actor_user_id, overwrite_existing=arguments.get('overwrite_existing', False)))
if result.get('status') == 'success':
self._state.update_entity('manifest', manifest['manifest_id'], {'materialized_destination_node_id': destination['node_id'], 'materialized_policy_version': policy.get('policy_version')}, 'manifest_id')
result['data'].update({'delivery_lane': policy.get('lane_name'), 'policy_version': policy.get('policy_version')})
return result
def _file_system_progressive_structure_stream_adapter_snapshot(self):
value = self._file_system_stream_adapter_snapshot()
value['progressive_v6'] = {'pending_policy_revalidation': sorted(self._pending_policy_revalidation), 'fresh_policy_evidence': sorted(self._fresh_policy_evidence), 'attempted_t09_manifests': sorted(self._attempted_t09_manifests), 'expected_t09_stale_bindings': ext_deepcopy(self._expected_t09_stale_bindings)}
return value
def _file_system_progressive_structure_stream_adapter_restore(self, snapshot):
metadata = ext_deepcopy(snapshot.get('progressive_v6') or {})
inherited = ext_deepcopy(snapshot)
inherited.pop('progressive_v6', None)
self._file_system_stream_adapter_restore(inherited)
self._pending_policy_revalidation = set(metadata.get('pending_policy_revalidation') or [])
self._fresh_policy_evidence = set(metadata.get('fresh_policy_evidence') or [])
self._attempted_t09_manifests = set(metadata.get('attempted_t09_manifests') or [])
self._expected_t09_stale_bindings = ext_deepcopy(metadata.get('expected_t09_stale_bindings') or {})
def _file_system_stable_identity_stream_adapter_init(self, snapshot=None, source_root=CASE_DIR / 'raw', *, _initialize=True, _enforce_t09_priority=True, _enforce_revalidation=True):
self._file_system_progressive_structure_stream_adapter_init(snapshot=None, source_root=source_root, _initialize=False, _enforce_t09_priority=_enforce_t09_priority, _enforce_revalidation=_enforce_revalidation)
if snapshot is not None:
self.restore(snapshot)
elif _initialize:
self._state = MemoryState(fn__initial_entities_4())
self._assert_state_invariants()
def _file_system_stream_adapter_snapshot(self):
value = self._file_system_adapter_snapshot()
value['schema'] = 'rescopebench-filesystem-stream-snapshot/v2'
value['stream'] = self._stream_metadata()
return value
def _file_system_stream_adapter_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-filesystem-stream-snapshot/v2':
raise ValueError('unsupported stream snapshot schema')
stream = snapshot.get('stream')
if not isinstance(stream, dict):
raise ValueError('stream snapshot metadata is missing')
base_snapshot = ext_deepcopy(snapshot)
base_snapshot['schema'] = 'rescopebench-filesystem-snapshot/v2'
base_snapshot.pop('stream', None)
self._file_system_adapter_restore(base_snapshot)
self._stream_position = int(stream.get('position') or 0)
self._drift_applied = bool(stream.get('drift_applied'))
self._drift_event_seq = int(stream.get('drift_event_seq') or 0)
self._drift_application_before_sha256 = stream.get('drift_application_before_sha256')
self._drift_application_after_sha256 = stream.get('drift_application_after_sha256')
self._counterfactual_no_drift = bool(stream.get('counterfactual_no_drift'))
self._assert_state_invariants()
def _file_system_progressive_structure_stream_adapter_init(self, snapshot=None, source_root=CASE_DIR / 'raw', *, _initialize=True, _enforce_t09_priority=True, _enforce_revalidation=True):
self._pending_policy_revalidation: set[str] = set()
self._fresh_policy_evidence: set[str] = set()
self._attempted_t09_manifests: set[str] = set()
self._expected_t09_stale_bindings: dict[str, dict[str, ext_Any]] = {}
self._file_system_learnable_structure_stream_adapter_init(snapshot=None, source_root=source_root, _initialize=False)
self._enforce_t09_priority = _enforce_t09_priority
self._enforce_revalidation = _enforce_revalidation
if snapshot is not None:
self.restore(snapshot)
elif _initialize:
self._state = MemoryState(fn__initial_entities_5())
self._assert_state_invariants()
def _file_system_adapter_snapshot(self):
return {'schema': 'rescopebench-filesystem-snapshot/v2', 'task_id': self._task_id, 'task_targets': ext_deepcopy(self._task_targets), 'entities': self._state.list_snapshot(), 'counters': self._state.counters_snapshot(), 'events': ext_deepcopy(self._events), 'calls': self._calls, 'read_units': self._read_units, 'write_attempts': self._write_attempts}
def _file_system_adapter_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-filesystem-snapshot/v2':
raise ValueError('unsupported snapshot schema')
self._task_id = snapshot.get('task_id')
self._task_targets = ext_deepcopy(snapshot.get('task_targets') or [])
self._state.restore(snapshot.get('entities') or {}, snapshot.get('counters') or {})
self._events = ext_deepcopy(snapshot.get('events') or [])
self._calls = int(snapshot.get('calls') or 0)
self._read_units = int(snapshot.get('read_units') or 0)
self._write_attempts = int(snapshot.get('write_attempts') or 0)
def _file_system_learnable_structure_stream_adapter_init(self, snapshot=None, source_root=CASE_DIR / 'raw', *, _initialize=True):
self._file_system_adaptive_structure_stream_adapter_init(snapshot=None, source_root=source_root, _initialize=False)
if snapshot is not None:
self.restore(snapshot)
elif _initialize:
self._state = MemoryState(fn__initial_entities_6())
self._assert_state_invariants()
def _file_system_adaptive_structure_stream_adapter_init(self, snapshot=None, source_root=CASE_DIR / 'raw', *, _initialize=True):
self._file_system_stream_adapter_init(snapshot=None, source_root=source_root, _initialize=False)
if snapshot is not None:
self.restore(snapshot)
elif _initialize:
self._state = MemoryState(fn__initial_entities_7())
self._assert_state_invariants()
def _file_system_stream_adapter_init(self, snapshot=None, source_root=CASE_DIR / 'raw', *, _initialize=True):
self._file_system_adapter_init(source_root)
self.tools = ext_deepcopy(DATA_TOOLS_3)
self._stream_position = 0
self._drift_applied = False
self._drift_event_seq = 0
self._drift_application_before_sha256: str | None = None
self._drift_application_after_sha256: str | None = None
self._counterfactual_no_drift = False
if snapshot is not None:
self.restore(snapshot)
elif _initialize:
self._state = MemoryState(fn__initial_entities_2())
self._assert_state_invariants()
def _file_system_adapter_init(self, source_root=CASE_DIR / 'raw'):
self._impl = fn__load_raw_logic(str(ext_Path(source_root).resolve()))
self._state = MemoryState({name: [] for name in DATA_ENTITY_ID_FIELDS})
self._task_id: str | None = None
self._task_targets: list[dict[str, ext_Any]] = []
self._events: list[dict[str, ext_Any]] = []
self._calls = 0
self._read_units = 0
self._write_attempts = 0
class MemoryState:
def __init__(self, entities):
self._entities = ext_deepcopy(entities)
self._counters: dict[str, ext_Any] = {}
def get_entity(self, entity_type, entity_id, id_field='id'):
field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
return next((ext_deepcopy(row) for row in self._entities.get(entity_type, []) if row.get(field) == entity_id), None)
def list_entities(self, entity_type):
return ext_deepcopy(self._entities.get(entity_type, []))
def add_entity(self, entity_type, record, id_field='id'):
field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
identity = record.get(field)
if identity is None:
raise ValueError(f'missing identity for {entity_type}')
rows = self._entities.setdefault(entity_type, [])
for (index, row) in enumerate(rows):
if row.get(field) == identity:
merged = ext_deepcopy(row)
merged.update(ext_deepcopy(record))
rows[index] = merged
return ext_deepcopy(merged)
rows.append(ext_deepcopy(record))
return ext_deepcopy(record)
def update_entity(self, entity_type, entity_id, patch, id_field='id'):
current = self.get_entity(entity_type, entity_id, id_field)
if current is None:
return None
current.update(ext_deepcopy(patch))
return self.add_entity(entity_type, current, id_field)
def delete_entity(self, entity_type, entity_id, id_field='id'):
field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
rows = self._entities.get(entity_type, [])
kept = [row for row in rows if row.get(field) != entity_id]
self._entities[entity_type] = kept
return len(kept) != len(rows)
def increment_counter(self, key, value=1.0):
next_value = float(self._counters.get(key, 0.0)) + float(value)
self._counters[key] = next_value
return next_value
def get_counter(self, key, default=0.0):
return ext_deepcopy(self._counters.get(key, default))
def list_snapshot(self):
return ext_deepcopy(self._entities)
def counters_snapshot(self):
return ext_deepcopy(self._counters)
def restore(self, entities, counters=None):
self._entities = ext_deepcopy(entities)
self._counters = ext_deepcopy(counters or {})
|