from pathlib import Path import hashlib,importlib.util,json,shutil R=Path('/Users/korizatou114/Projects/とりにく工房ゲーム制作部');A=R/'artifacts/original-completion-2026-10-02';P=A/'p04-paid-shift-midnight-formal-prep-r01';P.mkdir(exist_ok=True);N=A/'p04-paid-shift-midnight-native-r01';sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest();assert json.loads((N/'execution.json').read_text())['passed'];base=A/'p04-01-formal-boundary-reload-r01.gd';s=base.read_text();s=s[:s.index('func _branch(')]+'''func _run() -> void: _folder = OS.get_environment("THE_TREE_BOUNDARY_RESTART_EVIDENCE") _mode = OS.get_environment("THE_TREE_BOUNDARY_RESTART_MODE") if _folder.is_empty() or _mode not in ["writer", "reader"]: quit(2); return _expect(DirAccess.make_dir_recursive_absolute(_folder) == OK, "fresh formal output") var manifest: Dictionary = _json(OS.get_environment("THE_TREE_BOUNDARY_RESTART_INPUT")) var inputs: Dictionary = manifest["whole_typed_inputs"] _reset() if _mode == "writer": for point: String in inputs: _write_save(point, _input(inputs[point])) else: var writer: Dictionary = _json(_folder.path_join("writer.json")) _expect(int(writer["pid"]) != OS.get_process_id() and String(writer["profile"]) != OS.get_user_data_dir(), "distinct actual Writer/Reader PID and private profiles") for label: String in writer["slots"]: _copy_package(String(writer["slots"][label]), label) for point: String in inputs: _load_save(point, _input(inputs[point])) _load_save("before", _input(inputs["before"])) var receipts: Array = [] _runtime.economy_service.transaction_posted.connect(func(id: StringName, entries: Array): var rows: Array = [] for row: LedgerEntry in entries: rows.append(row.to_dictionary()) receipts.append({&"id": id, &"minute": _clock.absolute_minute, &"rows": rows}) ) for point: String in ["midnight", "paused", "after", "next"]: if point == "after": var id := StringName(manifest["kitchen_id"]) var command: CommandResult = _runtime.submit_command(&"set_facility_policy", {&"facility_id": id, &"patch": {&"business_open": true}}, &"player", &"", 10, -1, &"p04.dependency.reopen") _expect(command.is_success(), "same public dependency reopen after formal restart") _clock.advance_one_minute() var expected := _input(inputs[point]) _expect(var_to_bytes(_runtime.create_snapshot()) == var_to_bytes(expected), "all typed state after formal restart equals original native " + point) _proof("replayed-" + point, _runtime.create_snapshot()) var sale_count := 0 for receipt: Dictionary in receipts: for row: Dictionary in receipt[&"rows"]: if row[&"category"] == &"SERVICE_SALE": sale_count += 1 _expect(receipt[&"minute"] == 1442 and row[&"amount"] == 25, "exact original service sale after formal restart") _expect(sale_count == 1, "one sale notification across paused midnight and recovery") _results.append({&"receipts": receipts, &"sale_count": sale_count}) _proof("receipts", receipts) _finish() func _finish() -> void: var file := FileAccess.open(_folder.path_join(_mode + ".json"), FileAccess.WRITE) if file != null: file.store_string(JSON.stringify({&"pid": OS.get_process_id(), &"profile": OS.get_user_data_dir(), &"slots": _slots, &"results": _results, &"checks": _checks, &"failures": _failures}, "\\t")); file.flush(); file.close() _cleanup() print("Dependency formal restart: %d checks, %d failures" % [_checks, _failures]) quit(1 if _failures else 0) ''' # Price assertion is bound to exact original definition/input, not a new product value. s=s.replace('row[&"amount"] == 25','row[&"amount"] == int(manifest["original_price"])');Q=P/'dependency-formal.gd';assert not Q.exists() or Q.read_text()==s;Q.write_text(s) obs=json.loads((N/'order-evidence/observations.json').read_text());kitchen=None before=json.loads((N/'order-evidence/midnight-before.json').read_text());facilities=before['systems']['runtime']['facilities']['instances'];dining=next(f for f in facilities if f['definition_id']=='cafeteria');kitchen=dining['related_facility_id'];inputs={} for point in ['before','midnight','paused','after','next']: f=N/'order-evidence'/('midnight-'+point+'.var');inputs[point]={'path':str(f),'bytes':f.stat().st_size,'sha256':sha(f)} M=P/'INPUT.json';M.write_text(json.dumps({'source_native':str(N),'execution_sha256':sha(N/'execution.json'),'source_refs':1338,'whole_typed_inputs':inputs,'kitchen_id':kitchen,'original_price':next(z['service']['price_snapshot'] for z in obs['observations'] if 'price_snapshot' in z.get('service',{}))},indent=2)+'\n') w=(A/'p04-approved-shift-current-native-r01.py').read_text().replace('p04-approved-shift-current-native-r01','p04-paid-shift-midnight-formal-native-r01').replace("QA = A / 'p04-approved-shift-current-prep-r01/approved-shift.gd'","QA = A / 'p04-paid-shift-midnight-formal-prep-r01/dependency-formal.gd'\nINPUT = A / 'p04-paid-shift-midnight-formal-prep-r01/INPUT.json'") w=w.replace("Order boundary diagnostic:","Dependency formal restart:").replace('P04-01 approved 18:00 completion-before-handover diagnostic on current source','P04-01 public formal SaveService Writer and distinct-PID Reader for approved dependency pause/resume across midnight on current source') w=w.replace("if folder.name=='repro': env['THE_TREE_ORDER_EVIDENCE']=str(OUT/'order-evidence')","if folder.name in ['writer','reader']: env.update(THE_TREE_BOUNDARY_RESTART_EVIDENCE=str(OUT/'restart-evidence'), THE_TREE_BOUNDARY_RESTART_MODE=folder.name, THE_TREE_BOUNDARY_RESTART_INPUT=str(INPUT))") w=w.replace("[('import',None),('parse',None),('repro',TEST)]","[('import',None),('parse',None),('writer',TEST),('reader',TEST)]") w=w.replace('len(phases)==3','len(phases)==4').replace('phases=[]; previous={}; error=None;', 'phases=[]; previous={}; error=None; formal_before=None;') w=w.replace(" row=r.execute_phase("," if phase == 'reader': formal_before = {n:r.inventory(Path(p)) for n,p in r.read(OUT/'restart-evidence/writer.json')['slots'].items()}\n row=r.execute_phase(") w=w.replace(' passed=error is None'," formal_after = {n:r.inventory(Path(p)) for n,p in r.read(OUT/'restart-evidence/writer.json')['slots'].items()} if (OUT/'restart-evidence/writer.json').exists() else None\n formal_unchanged = formal_before is not None and formal_after == formal_before\n passed=formal_unchanged and error is None") w=w.replace('whole_goal_accepted=False,unit_accepted=False','formal_before=formal_before,formal_after=formal_after,formal_unchanged=formal_unchanged,whole_goal_accepted=False,unit_accepted=False') # Guard the raw inputs and QA before/after execution, besides existing source/profile/cache guards. w=w.replace(' protected = r.default_player(R)'," fixed = list(r.read(INPUT)['whole_typed_inputs'].values()) + [dict(path=str(INPUT),bytes=INPUT.stat().st_size,sha256=r.sha(INPUT)),dict(path=str(QA),bytes=QA.stat().st_size,sha256=r.sha(QA))]\n def fixed_guard():\n for pin in fixed:\n f=Path(pin['path']); assert not f.is_symlink() and f.stat().st_size==pin['bytes'] and r.sha(f)==pin['sha256']\n fixed_guard()\n protected = r.default_player(R)") w=w.replace(' assert r.source_refs(R)==root',' fixed_guard()\n assert r.source_refs(R)==root').replace('source_adoption=False,QA_overrides=[TEST]','fixed_input_pins=fixed,source_adoption=False,QA_overrides=[TEST]') w=w.replace('P04-01 public formal SaveService Writer and distinct-PID Reader for approved dependency pause/resume across midnight on current source','P04-01 existing paid catalog payroll and DAY/NIGHT handover with dependency pause/resume across midnight using public formal SaveService and distinct-PID Reader').replace('no formal save, Windows or whole-unit acceptance','not Windows or whole-unit acceptance');W=A/'p04-paid-shift-midnight-formal-native-r01.py';compile(w,str(W),'exec');W.write_text(w);floor=1024**3+Path('/Applications/Godot.app/Contents/MacOS/Godot').stat().st_size+136*1024**2;free=shutil.disk_usage(A).free;assert free>=floor;rec={'scope':'Root formal save/restore acceptance fixture only; no worker or product edit','source_native':str(N),'probe_sha256':sha(Q),'wrapper_sha256':sha(W),'input_manifest_sha256':sha(M),'original_public_formal_pattern':str(base),'original_pattern_sha256':sha(base),'planned_phases':['import','parse','writer','reader'],'free_before':free,'required_free':floor,'estimated_seconds':90,'formal_credit':0};(P/'ADMISSION.json').write_text(json.dumps(rec,indent=2)+'\n');print(rec)