P04-01: 同時発生の更新規約

This commit is contained in:
Agent Control Runner
2026-10-18 10:58:54 +09:00
parent 2dde7596a8
commit 20d0ae5990
32 changed files with 11890 additions and 314 deletions
@@ -0,0 +1,31 @@
# S5 — pending implementation, not a native run plan
No S5 executable driver or native receipt is supplied by this partial repair.
Do not start the once-only Q native/full batch from this directory.
The four required cases remain unchanged:
1. Real mana depletion, NO_POWER, no charge/progress, reservation retained,
recovery and one completion. S4's `disconnect_nodes` is not depletion.
The existing cafeteria fixture has an operating kitchen prerequisite;
global depletion can select RELATED_FACILITY_INACTIVE first. A driver must
observe that distinction rather than relabel the reason or mutate power
availability directly. A separate combined-cause case must prove the
approved RELATED-before-NO_POWER reason priority.
2. Actual accident or raid destruction during completion: valid minute-N
sale; next-minute failure/release for unfinished affected work; compare
command destruction before completion. S3 B4a/B4b use a registered event
with SET_FACILITY_STATE and must not simply be renamed an actual raid.
3. 00:00 completion: retain the S2a paid-midnight setup and full typed
snapshots, add phase observations proving prior-day settlement/upkeep
precede the sale, and independently join the sale to the new accounting
day. Retain replay/no-double-settlement proof.
4. Command exit versus AI planned exit at completion: retain actual public
commands and guest/service/reservation/ledger joins. Observe the AI
DECIDING predicate after completion, without forcing guest state or
treating a due exit time as universal active-service cancellation.
All prices, durations, resource rules and thresholds come from the selected
Q definitions and current public runtime. No new original values or rules
are supplied here. These notes identify implementation work; they are not
engine evidence and confer no condition credit.
@@ -0,0 +1,22 @@
# Concrete32 power pair — unexecuted, not batch admission
`p04_s5_power_probe.gd` supplies S5A_PURE (paid public bath, genuine mana
depletion) and S5B_DEPENDENCY (cafeteria plus kitchen, RELATED-before-NO_POWER).
Both use public resource commands, observed recovery, formal packages, independent
Reader replay, phase raw and resource-command replay receipts. The bath has no
item reservation; the dependent case retains and consumes the actual meal ID.
`run_s5_native.py` retains the S4 ownership/engine/cleanup safeguards and historical
template bindings. It is not fresh-Q plumbing. Do not run it against Q or start
the once-only native/full batch until the separately pending identity work is
finished. No old S1–S4 record is renamed or reused as fresh proof.
Root later stages the wrapper, probe and this document in its own build area.
The adapter takes `--raw-root`, `--writer-sha256`, `--reader-sha256` from verified
native records. It verifies referenced typed/JSON hashes and derives existing
measurement keys. It does not qualify source, engine, settings or full evidence.
S5 destruction, midnight and exit cases remain unimplemented. The preserved
`PENDING.md` is historical partial31 text; this document records only the added,
unexecuted power pair. D05 six approvals, A01, frozen M, 16/88 and P04 credit 0
are unchanged. Root alone runs engines and scratch fixtures.
@@ -0,0 +1,466 @@
extends "res://tests/s3/test_runtime_actor_hardening.gd"
const CASES: Array[String] = ["S5A_PURE", "S5B_DEPENDENCY"]
const SEEDS: Dictionary = {"S5A_PURE": 420550, "S5B_DEPENDENCY": 420551}
const GUEST: StringName = &"p04.s5.guest.a"
const REQUEST: StringName = &"p04.s5.request.a"
const QUEUED_GUEST: StringName = &"p04.s5.guest.b"
const QUEUED_REQUEST: StringName = &"p04.s5.request.b"
const SERVERS: Array[StringName] = [&"p04.order.server.a", &"p04.order.server.b"]
const SNAPSHOT_SERVERS: Array[String] = ["p04.order.server.a", "p04.order.server.b"]
var _evidence_dir: String = ""
var _mode: String = ""
var _case: String = ""
var _serial: int = 0
var _facility_id: StringName = &""
var _service_id: StringName = &""
var _boundary: int = 960
var _price: int = 0
var _duration: int = 0
var _patience: int = 0
var _reserve: int = 0
var _recovery: Dictionary = {}
var _commands: Array = []
var _results: Array = []
var _receipts: Array = []
var _phases: Array = []
var _points: Dictionary = {}
var _branches: Dictionary = {}
var _slots: Dictionary = {}
var _replay_reference: Dictionary = {}
func _run() -> void:
_evidence_dir = OS.get_environment("THE_TREE_S5_EVIDENCE")
_mode = OS.get_environment("THE_TREE_S5_MODE")
if _evidence_dir.is_empty() or _mode not in ["writer", "reader"]:
quit(2)
return
_expect(DirAccess.make_dir_recursive_absolute(_evidence_dir) == OK, "external evidence directory")
if _mode == "writer":
for branch: String in CASES:
_case = branch
_writer_case()
else:
_reader()
_write(_mode, {&"pid": OS.get_process_id(), &"profile": OS.get_user_data_dir(), &"slots": _slots,
&"branches": _branches, &"checks": _checks, &"failures": _failures,
&"whole_goal_accepted": false, &"unit_accepted": false}, true)
_cleanup()
print("S5 power: %d checks, %d failures" % [_checks, _failures])
quit(1 if _failures else 0)
func _fresh() -> void:
_serial = 0
_facility_id = &""
_service_id = &""
_boundary = 960
_price = 0
_duration = 0
_patience = 0
_reserve = 0
_recovery = {}
_replay_reference = {}
_commands = []
_results = []
_receipts = []
_phases = []
_points = {}
_reset_runtime(SEEDS[_case])
_runtime.configure_save_policy({&"enabled": false, &"daily_checkpoint_enabled": false})
_runtime.command_completed.connect(func(result: CommandResult) -> void:
_results.append({&"minute": _clock.absolute_minute, &"result": result.to_dictionary()})
_expect(result.is_success(), "actual public command completion " + str(result.command_id))
)
func _cmd(kind: StringName, payload: Dictionary, at: int = -1) -> CommandResult:
_serial += 1
var key: StringName = StringName("p04.s5.%s.command.%d" % [_case, _serial])
var result: CommandResult = _runtime.submit_command(kind, payload, &"player", &"", 10, at, key)
_commands.append({&"serial": _serial, &"kind": kind, &"payload": payload.duplicate(true),
&"at": at, &"issued_at": _clock.absolute_minute, &"idempotency_key": key, &"result": result.to_dictionary()})
_expect(result.is_success(), "public command " + String(kind))
return result
func _queue(guest_id: StringName, request_id: StringName, exit_at: int) -> void:
_cmd(&"spawn_guest", {&"guest_id": guest_id, &"guest_type_id": &"traveler", &"gold": _price * 2,
&"options": {&"state": GuestRuntime.State.DECIDING, &"current_cell": Vector3i.ZERO, &"planned_exit_at": exit_at}})
_cmd(&"create_service_request", {&"facility_id": _facility_id, &"request_id": request_id, &"guest_ids": [guest_id]})
var guest: GuestRuntime = _runtime.guest_service.get_guest(guest_id)
var request: ServiceRequest = _runtime.facility_service.get_request(request_id)
_expect(guest != null and request != null, "actual Guest and request exist")
if guest == null or request == null: return
_expect(guest.state == GuestRuntime.State.QUEUING and guest.queue_request_id == request_id, "actual queued ownership before advancing clock")
_expect(request.quoted_price == _price and request.service_minutes == _duration and request.reserved_inventory_ids.size() == (1 if _case == "S5B_DEPENDENCY" else 0), "definition price/duration and one meal reservation")
for id: StringName in request.reserved_inventory_ids:
var reservation: InventoryReservation = _runtime.inventory_service.get_reservation(id)
_expect(reservation != null and reservation.is_active() and reservation.requester_id == request_id, "public queue actually reserves meal")
func _prepare() -> bool:
_fresh()
var facility: FacilityInstance
if _case == "S5B_DEPENDENCY":
facility = _build_cafeteria(true)
else:
var bath: FacilityDefinition = _runtime.definition_registry.get_facility(&"public_bath")
_expect(bath != null and bath.build_minutes > 0, "registered public bath definition")
if bath == null: return false
var build: CommandResult = _cmd(&"build_facility", {&"definition_id": &"public_bath", &"origin": Vector3i(-5, 0, WorldService.LAYER_FRONT)})
if not build.is_success(): return false
var began: int = _clock.absolute_minute
while _runtime.construction_service.get_facilities().is_empty() and _clock.absolute_minute <= began + bath.build_minutes:
_clock.advance_one_minute()
var built: Array[Dictionary] = _runtime.construction_service.get_facilities()
_expect(built.size() == 1 and _clock.absolute_minute - began == bath.build_minutes, "definition build duration and one constructed bath")
if built.size() != 1: return false
facility = _runtime.facility_service.get_instance(StringName(built[0][&"instance_id"]))
if facility == null: return false
_facility_id = facility.instance_id
var definition: FacilityDefinition = _runtime.definition_registry.get_facility(facility.definition_id)
_price = definition.base_price
_duration = definition.base_service_minutes
_patience = _runtime.guest_service.get_definition(&"traveler").base_patience
_expect(_price > 0 and _duration > 1, "paid natural service definition")
var staff_ids: Array[StringName] = []
for index: int in range(definition.staff_min):
var id: StringName = StringName("p04.s5.staff.%d" % index)
staff_ids.append(id)
_cmd(&"register_staff", {&"staff_id": id, &"role_id": &"server" if _case == "S5B_DEPENDENCY" else &"attendant", &"options": {&"state": StaffRuntime.State.OFF_DUTY, &"current_cell": Vector3i.ZERO}})
_cmd(&"set_staff_work_assignment", {&"staff_id": id, &"template_id": &"DAY", &"facility_id": _facility_id})
_expect(_clock.absolute_minute < _boundary - _duration - 1, "setup before fixed boundary")
if _clock.absolute_minute >= _boundary - _duration - 1: return false
_clock.advance_minutes(_boundary - _duration - 1 - _clock.absolute_minute)
_expect(facility.active_staff_ids == staff_ids, "public staff attendance")
if _case == "S5B_DEPENDENCY":
_expect(_stock(facility.local_inventory_id, &"ingredient/basic_meal", 1, &"p04.s5.stock"), "one actual meal")
_queue(GUEST, REQUEST, _boundary + _duration + 1)
_clock.advance_one_minute()
var active: Array = _runtime.facility_service.get_active_services(_facility_id)
_expect(active.size() == 1, "one actual started service")
if active.size() != 1: return false
var service: ServiceInstance = active[0]
_service_id = service.service_id
_expect(service.started_at + _duration == _boundary, "natural completion boundary")
_clock.advance_minutes(_boundary - 1 - _clock.absolute_minute)
_reserve = _state.get_resource(&"mana")
_recovery = {&"staff_ids": staff_ids, &"resume_minute": -1}
_expect(_reserve > 0 and service.elapsed_minutes == _duration - 1, "positive reserve and duration-1 progress")
return _clock.absolute_minute == _boundary - 1
func _connect_observations() -> void:
_runtime.economy_service.transaction_posted.connect(func(id: StringName, entries: Array) -> void:
var rows: Array = []
for entry: LedgerEntry in entries: rows.append(entry.to_dictionary())
_receipts.append({&"id": id, &"minute": _clock.absolute_minute, &"entries": rows})
)
_clock.tick_phase_started.connect(func(phase: int, minute: int) -> void:
var label: String = "phase-%d-%s" % [minute, SimulationKernel.TickPhase.keys()[phase]]
var row: Dictionary = _capture()
row[&"phase"] = SimulationKernel.TickPhase.keys()[phase]
_assert_phase(row)
_phases.append(_write(label, row))
)
func _assert_phase(point: Dictionary) -> void:
_expect(point.has(&"snapshot") and point.has(&"mana"), "complete raw phase observation")
func _capture() -> Dictionary:
var snapshot: Dictionary = _runtime.create_snapshot()
var operations: Dictionary = snapshot[&"systems"][&"runtime"][&"operations"]
var facility: FacilityInstance = _runtime.facility_service.get_instance(_facility_id)
var service: ServiceInstance = _runtime.facility_service.get_service(_service_id)
var event: EventInstance = _runtime.event_service.get_instance(&"p04.destroy.instance")
var kitchen: FacilityInstance = _runtime.facility_service.get_instance(facility.related_facility_id)
var actors: Dictionary = {}
var requests: Dictionary = {}
var wallets: Dictionary = {}
for id: StringName in [GUEST, QUEUED_GUEST]:
var guest: GuestRuntime = _runtime.guest_service.get_guest(id)
actors[String(id)] = guest.create_snapshot() if guest != null else {}
wallets[String(id)] = _runtime.economy_service.get_balance(StringName("GUEST_WALLET:" + String(id)))
for id: StringName in [REQUEST, QUEUED_REQUEST]:
var request: ServiceRequest = _runtime.facility_service.get_request(id)
requests[String(id)] = request.create_snapshot() if request != null else {}
var reservations: Array = []
for reservation: InventoryReservation in _runtime.inventory_service.get_reservations(false): reservations.append(reservation.create_snapshot())
var ledger: Array = []
for entry: LedgerEntry in _runtime.economy_service.get_entries(): ledger.append(entry.to_dictionary())
return {&"snapshot": snapshot, &"minute": _clock.absolute_minute,
&"inputs": {&"case": _case, &"seed": SEEDS[_case], &"serial": _serial, &"facility_id": _facility_id, &"service_id": _service_id,
&"boundary": _boundary, &"price": _price, &"duration": _duration, &"patience": _patience, &"reserve": _reserve, &"recovery": _recovery.duplicate(true),
&"kitchen_premise": "ActorHardening physical FLEX fixture; not natural hire/unlock"},
&"related_facility_operating": facility.related_facility_operating, &"mana": _state.get_resource(&"mana"), &"kitchen": kitchen.create_snapshot() if kitchen != null else {}, &"graph_invariants": _runtime.mana_network_service.validate_invariants(),
&"facility": facility.create_snapshot(), &"service": service.create_snapshot() if service != null else {},
&"event": event.create_snapshot() if event != null else {}, &"guests": actors, &"requests": requests, &"wallets": wallets,
&"reservations": reservations, &"ledger": ledger, &"receipts": _receipts.duplicate(true),
&"player_cash": _runtime.economy_service.get_balance(_runtime.PLAYER_CASH_ACCOUNT),
&"available_meals": _runtime.inventory_service.available_quantity(facility.local_inventory_id, &"ingredient/basic_meal"),
&"active_services": _runtime.facility_service.get_active_services(_facility_id).size(),
&"operations_enabled": operations[&"enabled"], &"saved_coordinator": operations[&"coordinator"],
&"actual_coordinator_absent": _runtime.operations_coordinator == null, &"unrelated_getters_called": false}
func _labels() -> Array[String]:
return ["boundary", "held", "recovered"]
func _advance(label: String) -> void:
if label == "boundary":
_cmd(&"spend_resources", {&"cost": {&"mana": _reserve}})
_clock.advance_one_minute()
elif label == "recovered":
_expect(_clock.absolute_minute == _boundary + 1, "recover only after held")
_cmd(&"change_resources", {&"deltas": {&"mana": _reserve}})
_recovery[&"key"] = _commands.back()[&"idempotency_key"]
while _clock.absolute_minute < _boundary + _duration:
_clock.advance_one_minute()
var point: Dictionary = _capture()
if point[&"service"][&"state"] == "COMPLETED":
_recovery[&"resume_minute"] = _clock.absolute_minute
break
_assert_stopped(point)
_expect(_recovery[&"resume_minute"] > 0, "bounded observed recovery completion")
elif label == "duplicate_guard":
var before_replay: Dictionary = _runtime.create_snapshot()
var replay: CommandResult = _runtime.submit_command(&"change_resources", {&"deltas": {&"mana": _reserve}}, &"player", &"", 10, -1, _recovery[&"key"])
var after_replay: Dictionary = _runtime.create_snapshot()
_expect(replay.is_success() and replay.is_replay and var_to_bytes(before_replay) == var_to_bytes(after_replay), "same key replay changes no Runtime field")
_replay_reference = _write("resource-replay", {&"before": before_replay, &"after": after_replay, &"result": replay.to_dictionary()})
_clock.advance_one_minute()
else:
_clock.advance_one_minute()
func _writer_case() -> void:
if not _prepare(): return
var before: Dictionary = _capture()
_assert_before(before)
_points["before"] = _write("before", before)
_connect_observations()
for label: String in _labels():
_advance(label)
var actual: Dictionary = _capture()
_assert_outcome(before, actual)
_save_point(label, actual)
_advance("duplicate_guard")
var guard: Dictionary = _capture()
_assert_outcome(before, guard)
_points["duplicate_guard"] = _write("duplicate_guard", guard)
_branches[_case] = _write("case", {&"resource_replay": _replay_reference, &"points": _points.duplicate(true), &"phases": _phases.duplicate(true),
&"commands": _write("commands", {&"submitted": _commands, &"completed_including_fixture": _results})})
func _assert_before(point: Dictionary) -> void:
_assert_unconfounded(point)
_expect(point[&"mana"] > 0 and point[&"facility"][&"power_available"] and point[&"related_facility_operating"], "initial power and dependency")
_expect(point[&"service"][&"state"] == "ACTIVE" and point[&"service"][&"elapsed_minutes"] == _duration - 1, "natural pre-completion point")
func _assert_unconfounded(point: Dictionary) -> void:
_expect(not point[&"operations_enabled"] and point[&"actual_coordinator_absent"], "isolated fixture")
_expect(point[&"facility"][&"operator_open"] and point[&"facility"][&"durability"] > 0 and point[&"event"].is_empty(), "no closure or destruction")
_expect(point[&"facility"][&"active_staff_ids"] == _recovery[&"staff_ids"], "no shift confound")
_expect(point[&"graph_invariants"][&"valid"], "graph invariants")
if point[&"service"][&"state"] != "COMPLETED":
_expect(point[&"guests"][String(GUEST)][&"state"] == "RECEIVING_SERVICE" and point[&"guests"][String(GUEST)][&"planned_exit_at"] > point[&"minute"], "guest ownership and no exit")
func _assert_stopped(point: Dictionary) -> void:
_assert_unconfounded(point)
var expected_reason: String = "RELATED_FACILITY_INACTIVE" if _case == "S5B_DEPENDENCY" and not point[&"related_facility_operating"] else "NO_POWER"
_expect(point[&"service"][&"state"] == "PAUSED" and point[&"service"][&"interruption_reason"] == expected_reason, "approved actual reason priority")
_expect(point[&"service"][&"elapsed_minutes"] == _duration - 1 and point[&"receipts"].is_empty(), "stopped progress and no payment")
if point[&"minute"] <= _boundary + 1:
_expect(point[&"mana"] == 0 and not point[&"facility"][&"power_available"], "real depleted reserve projects no power")
if _case == "S5B_DEPENDENCY":
_expect(point[&"kitchen"][&"state"] == "NO_POWER" and not point[&"related_facility_operating"], "kitchen NO_POWER before dependent reason")
else:
_expect(point[&"related_facility_operating"], "pure no dependency")
func _assert_reservation(before: Dictionary, point: Dictionary, request_id: StringName, state: String, terminal: int) -> void:
var prior: Array = []
var current: Array = []
for row: Dictionary in before[&"reservations"]:
if row[&"requester_id"] == String(request_id): prior.append(row)
for row: Dictionary in point[&"reservations"]:
if row[&"requester_id"] == String(request_id): current.append(row)
_expect(prior.size() == 1 and current.size() == 1, "one original reservation per request")
if prior.size() != 1 or current.size() != 1: return
_expect(prior[0][&"reservation_id"] == current[0][&"reservation_id"] and current[0][&"state"] == state and current[0][&"terminal_at"] == terminal, "same reservation ID/state/terminal time; no second release")
if state == "ACTIVE":
_expect(var_to_bytes(prior[0]) == var_to_bytes(current[0]), "entire held reservation unchanged")
var request: Dictionary = point[&"requests"][String(request_id)]
_expect(not request.is_empty() and request[&"reserved_inventory_ids"].has(current[0][&"reservation_id"]), "active reservation has live request owner")
else:
_expect(point[&"requests"][String(request_id)].is_empty(), "terminal reservation has no orphan request")
if state == "RELEASED":
var release_count: int = 0
var inventory: Dictionary = point[&"snapshot"][&"systems"][&"runtime"][&"inventory"]
for operation: Dictionary in inventory[&"idempotency_results"]:
var result: Dictionary = operation[&"result"]
if operation[&"action"] == "release" and String(result.get(&"reservation_id", "")) == current[0][&"reservation_id"]:
release_count += 1
_expect(bool(result.get(&"ok", false)) and result.get(&"quantity", 0) == current[0][&"quantity"], "release returned actual reserved quantity, not an orphan repair/retry")
_expect(release_count == 1, "one raw inventory release operation for original reservation")
func _assert_outcome(before: Dictionary, point: Dictionary) -> void:
_assert_unconfounded(point)
var service: Dictionary = point[&"service"]
_expect(service[&"service_id"] == before[&"service"][&"service_id"], "same service ID")
var paid: bool = service[&"state"] == "COMPLETED"
if not paid:
_assert_stopped(point)
_expect(var_to_bytes(point[&"ledger"]) == var_to_bytes(before[&"ledger"]), "entire stopped ledger unchanged")
_expect(var_to_bytes(point[&"requests"][String(REQUEST)]) == var_to_bytes(before[&"requests"][String(REQUEST)]), "same live request and ownership")
else:
_expect(point[&"facility"][&"power_available"] and service[&"elapsed_minutes"] == _duration and point[&"active_services"] == 0, "one recovered completion")
_expect(point[&"receipts"].size() == 1, "exactly one receipt")
var expected: Array = before[&"ledger"].duplicate(true)
for receipt: Dictionary in point[&"receipts"]: expected.append_array(receipt[&"entries"])
_expect(var_to_bytes(expected) == var_to_bytes(point[&"ledger"]), "ledger exactly one receipt")
if _case == "S5B_DEPENDENCY":
_assert_reservation(before, point, REQUEST, "CONSUMED" if paid else "ACTIVE", service[&"completed_at"] if paid else -1)
else:
_expect(point[&"reservations"].is_empty(), "bath has no item inputs; ownership proven through request, service and guest")
_expect(point[&"wallets"][String(GUEST)] == _price * (1 if paid else 2) and point[&"player_cash"] == before[&"player_cash"] + (_price if paid else 0), "one price or zero")
func _save_point(label: String, point: Dictionary) -> void:
_points[label] = _write(label, point)
var path: String = "user://saves/p04_s5/" + _case + "-" + label
var saved: Dictionary = SaveService.save_snapshot(path, point[&"snapshot"])
var inspected: Dictionary = SaveService.inspect_snapshot(path)
_expect(bool(saved.get(&"ok", false)) and bool(inspected.get(&"ok", false)) and bool(inspected.get(&"read_only", false)), "public formal save/inspect")
_expect(var_to_bytes(inspected.get(&"snapshot", {})) == var_to_bytes(point[&"snapshot"]), "all typed fields preserved by formal package")
_expect(var_to_bytes(_runtime.create_snapshot()) == var_to_bytes(point[&"snapshot"]), "formal saving leaves Runtime unchanged")
_slots[_case + "-" + label] = ProjectSettings.globalize_path(path)
# Snapshot bytes exist once in point raw and once in the required formal
# package; indexes do not embed inspection/load copies of those bytes.
func _write(label: String, value: Variant, global_name: bool = false) -> Dictionary:
var name: String = label if global_name else _mode + "-" + _case + "-" + label
var reference: Dictionary = {}
for extension: String in ["var", "json"]:
var path: String = _evidence_dir.path_join(name + "." + extension)
_expect(not FileAccess.file_exists(path), "raw point written exactly once " + name)
var file: FileAccess = FileAccess.open(path, FileAccess.WRITE)
_expect(file != null, "raw file " + name)
if file == null: continue
if extension == "var": file.store_buffer(var_to_bytes(value))
else: file.store_string(JSON.stringify(value, "\t"))
file.flush()
file.close()
reference[extension] = {&"path": path, &"sha256": FileAccess.get_sha256(path)}
return reference
func _read(reference: Dictionary) -> Dictionary:
var item: Dictionary = reference["var"]
var path: String = item["path"]
_expect(FileAccess.get_sha256(path) == item["sha256"], "raw typed SHA")
var json_ref: Dictionary = reference["json"]
_expect(FileAccess.get_sha256(json_ref["path"]) == json_ref["sha256"], "raw JSON SHA")
var file: FileAccess = FileAccess.open(path, FileAccess.READ)
_expect(file != null, "typed input readable")
if file == null: return {}
var value: Variant = bytes_to_var(file.get_buffer(file.get_length()))
file.close()
_expect(value is Dictionary, "typed input dictionary")
return value if value is Dictionary else {}
func _restore_inputs(point: Dictionary) -> void:
var inputs: Dictionary = point[&"inputs"]
_expect(_serial == 0, "Reader starts with serial zero before importing external inputs")
_serial = inputs[&"serial"]
_facility_id = inputs[&"facility_id"]
_service_id = inputs[&"service_id"]
_boundary = inputs[&"boundary"]
_price = inputs[&"price"]
_duration = inputs[&"duration"]
_patience = inputs[&"patience"]
_reserve = inputs[&"reserve"]
_recovery = inputs[&"recovery"].duplicate(true)
func _load_point(path: String, expected: Dictionary) -> bool:
_fresh()
_restore_inputs(expected)
var loaded: Dictionary = SaveService.load_snapshot(path)
_expect(bool(loaded.get(&"ok", false)), "public formal load")
if not bool(loaded.get(&"ok", false)): return false
_expect(var_to_bytes(loaded[&"snapshot"]) == var_to_bytes(expected[&"snapshot"]), "all saved typed fields equal Writer")
var restored: bool = _runtime.restore_snapshot(loaded[&"snapshot"])
_expect(restored, "public Runtime restore")
_expect(var_to_bytes(_runtime.create_snapshot()) == var_to_bytes(expected[&"snapshot"]), "all restored typed fields equal Writer")
return restored
func _is_replayed_phase(row: Dictionary) -> bool:
return int(row[&"minute"]) > _boundary or (int(row[&"minute"]) == _boundary and row[&"phase"] == SimulationKernel.TickPhase.keys()[SimulationKernel.TickPhase.APPLY_COMMANDS])
func _assert_expected_phase_roster(references: Array) -> void:
var expected_pairs: Array = []
var end: int = int(_recovery[&"resume_minute"]) + 1
for minute: int in range(_boundary, end):
for phase: int in range(SimulationKernel.TickPhase.size()):
expected_pairs.append([minute if phase == SimulationKernel.TickPhase.APPLY_COMMANDS else minute + 1, SimulationKernel.TickPhase.keys()[phase]])
var actual_pairs: Array = []
for reference: Dictionary in references:
var row: Dictionary = _read(reference)
actual_pairs.append([int(row[&"minute"]), row[&"phase"]])
_expect(actual_pairs == expected_pairs, "complete dynamic replay phase roster with no omissions")
func _reader() -> void:
var file: FileAccess = FileAccess.open(_evidence_dir.path_join("writer.json"), FileAccess.READ)
_expect(file != null, "Writer receipt")
if file == null: return
var writer: Dictionary = JSON.parse_string(file.get_as_text())
file.close()
_expect(int(writer["pid"]) != OS.get_process_id() and writer["profile"] != OS.get_user_data_dir(), "independent Reader PID/profile")
for branch: String in CASES:
_case = branch
var writer_case: Dictionary = _read(writer["branches"][branch])
var hashes: Dictionary = {}
var restored_refs: Dictionary = {}
for label: String in _labels():
var key: String = branch + "-" + label
var original: String = writer["slots"][key]
var target: String = ProjectSettings.globalize_path("user://saves/p04_s5/" + key)
_expect(DirAccess.make_dir_recursive_absolute(target) == OK, "private Reader formal slot")
var directory: DirAccess = DirAccess.open(original)
_expect(directory != null, "Writer formal slot readable")
if directory == null: return
var members: PackedStringArray = directory.get_files()
members.sort()
_expect(directory.get_directories().is_empty() and members == PackedStringArray(["journal.log", "manifest.json", "thumbnail.png", "world.bin"]), "all formal members enumerated")
var member_hashes: Dictionary = {}
for member: String in members:
var sha: String = FileAccess.get_sha256(original.path_join(member))
_expect(DirAccess.copy_absolute(original.path_join(member), target.path_join(member)) == OK, "copy every formal member")
var copied_sha: String = FileAccess.get_sha256(target.path_join(member))
_expect(not sha.is_empty() and sha == copied_sha, "original/copy member SHA equality")
member_hashes[member] = {&"original_before": sha, &"copy_before": copied_sha}
hashes[key] = {&"original": original, &"copy": target, &"members": member_hashes}
_slots[key] = target
var expected: Dictionary = _read(writer_case[&"points"][label])
if not _load_point(target, expected): return
restored_refs[label] = _write(label + "-restored", _capture())
var before: Dictionary = _read(writer_case[&"points"]["before"])
var boundary: Dictionary = _read(writer_case[&"points"]["boundary"])
if not _load_point(_slots[branch + "-boundary"], boundary): return
_assert_stopped(_capture())
_connect_observations()
var replay_refs: Dictionary = {}
for label: String in ["held", "recovered", "duplicate_guard"]:
_advance(label)
var actual: Dictionary = _capture()
var expected: Dictionary = _read(writer_case[&"points"][label])
_expect(var_to_bytes(actual) == var_to_bytes(expected), "replay complete typed point including Runtime, inputs, receipts " + label)
_assert_outcome(before, actual)
replay_refs[label] = _write(label + "-replay", actual)
var expected_phases: Array = []
for reference: Dictionary in writer_case[&"phases"]:
if _is_replayed_phase(_read(reference)): expected_phases.append(reference)
_assert_expected_phase_roster(expected_phases)
_expect(_phases.size() == expected_phases.size(), "complete phase count")
if _phases.size() == expected_phases.size():
for index: int in range(_phases.size()):
_expect(var_to_bytes(_read(_phases[index])) == var_to_bytes(_read(expected_phases[index])), "same phase order and all typed phase state")
for key: String in hashes:
var row: Dictionary = hashes[key]
for member: String in row[&"members"]:
var item: Dictionary = row[&"members"][member]
item[&"original_after"] = FileAccess.get_sha256(String(row[&"original"]).path_join(member))
item[&"copy_after"] = FileAccess.get_sha256(String(row[&"copy"]).path_join(member))
_expect(item[&"original_before"] == item[&"original_after"] and item[&"copy_before"] == item[&"copy_after"], "original/copy unchanged after all loads and replay")
_branches[branch] = _write("case", {&"resource_replay": _replay_reference, &"restored": restored_refs, &"replay": replay_refs, &"phases": _phases,
&"member_hashes": hashes, &"recovery_commands": _commands, &"replay_completed_commands": _results})
@@ -0,0 +1,405 @@
#!/usr/bin/env python3
"""S5-only native entry. --check-only never loads ownership helpers or starts Godot."""
from pathlib import Path
import argparse
import copy
import hashlib
import importlib.util
import json
import os
import shutil
import subprocess
import stat
import sys
sys.dont_write_bytecode = True
HERE = Path(__file__).resolve().parent
BUILD = Path("/Users/korizatou114/Projects/TheTree-managed-worktrees/p04-01/.runtime/P04-01/build")
PRODUCT = BUILD / "audit-support/p04-r17-full-inputs-r01/product"
CACHE_RUN = BUILD / "p04-final-product-full-r01"
TEST = "tests/s3/test_runtime_staff_assignment.gd"
QA = HERE / "p04_s5_power_probe.gd"
ENGINE = Path("/Applications/Godot.app/Contents/MacOS/Godot")
ENGINE_SHA256 = "c7cccbf8fb143e34e02fd6521e09be2c2b974f0d5db080b19071c9c570718ccf"
MANIFEST = BUILD / "audit-support/p04-r17-full-inputs-r01/MANIFEST.json"
MANIFEST_SHA = "a15f29fa12537f6d8aaf7cabea390922a9f16e3eb9c10981e5742aafc8c4c8a8"
CONTRACTS = BUILD / "audit-support/p04-r17-full-inputs-r01/fixed/6ce6b28c5985e8a4f13b78bfeb1f1e09f6216d874fb01e0656ec1633bfa01cd7/completion_marker_contracts.json"
CASES = ["S5A_PURE", "S5B_DEPENDENCY"]
LABELS = {case: ["boundary", "held", "recovered"] for case in CASES}
SLOTS = sorted(case + "-" + label for case in CASES for label in LABELS[case])
MATERIALS = [MANIFEST, BUILD / "audit-support/p04-review-repair22-r01/ACTUAL_CURRENT_PUBLIC_POWER_FUNCTIONS.json"]
def template_guard(root):
if root != PRODUCT.resolve() or not HERE.is_relative_to(BUILD.resolve()):
raise ValueError("Root must stage this exact QA/wrapper/plan inside own B")
if pin(MANIFEST)["sha256"] != MANIFEST_SHA:
raise ValueError("immutable full R17 relocation manifest")
manifest = json.loads(MANIFEST.read_text())
for name, source in manifest["product_source"].items():
# Old absolute paths are lookup keys only. Never open them.
row = manifest["original_to_relocated"][source["path"]]
actual = pin(root / name)
if Path(row["relocated"]).resolve() != root / name or any(
actual[k] != source[k] or actual[k] != row[k] for k in ("bytes", "sha256")):
raise ValueError("relocated product differs: " + name)
probe = QA.read_text()
import re
if ":=" in probe or re.search(r"\bvar\s+\w+\s*=", probe) or re.search(r"\bfor\s+\w+\s+in\b", probe):
raise ValueError("explicit typed declarations/loops required")
if re.search(r"\.(?:patience_remaining|elapsed_minutes|power_available|capacity|hold_until)\s*=(?!=)", probe):
raise ValueError("forbidden direct state mutation")
for forbidden in ["evaluate_now(", "configure_operations(", "._update_shift_states(", ".record_duty_minute("]:
if forbidden in probe:
raise ValueError("forbidden bypass: " + forbidden)
# Constants and public bodies are read from the actual selected source, not a memo.
mana = (root / "scripts/mana/mana_network_service.gd").read_text()
for key in ("EVALUATION_INTERVAL_MINUTES", "MINIMUM_OFF_HOLD_MINUTES"):
if not re.search(r"const " + key + r" := 10\b", mana):
raise ValueError("source timing changed: " + key)
def module(name, path):
spec = importlib.util.spec_from_file_location(name, path)
value = importlib.util.module_from_spec(spec)
spec.loader.exec_module(value)
return value
def pin(path):
path = Path(path)
if path.is_symlink() or not path.is_file():
raise ValueError("missing exact input: " + str(path))
data = path.read_bytes()
return dict(path=str(path), bytes=len(data), sha256=hashlib.sha256(data).hexdigest())
def engine_pin(path, expected=None):
path = Path(path)
if path != ENGINE or any(p.is_symlink() for p in (path, *path.parents)):
raise ValueError("exact installed engine required; no symlink or relocated input")
if path.resolve(strict=True) != ENGINE:
raise ValueError("installed engine resolved path changed")
before = path.stat()
if not stat.S_ISREG(before.st_mode):
raise ValueError("installed engine must be regular")
digest = hashlib.sha256(path.read_bytes()).hexdigest()
after = path.stat()
fields = ("st_dev", "st_ino", "st_size", "st_mtime_ns", "st_ctime_ns", "st_mode")
if any(getattr(before, k) != getattr(after, k) for k in fields):
raise ValueError("engine changed while hashing")
if any(p.is_symlink() for p in (path, *path.parents)) or path.resolve(strict=True) != ENGINE:
raise ValueError("engine path changed while hashing")
value = dict(path=str(path), resolved_path=str(path.resolve(strict=True)),
bytes=after.st_size, mtime_ns=after.st_mtime_ns, mode=after.st_mode,
device=after.st_dev, inode=after.st_ino, ctime_ns=after.st_ctime_ns, sha256=digest)
if digest != ENGINE_SHA256:
raise ValueError("engine differs from installed engine constant")
if expected is not None and value != expected:
raise ValueError("engine identity changed")
return value
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--project-root", type=Path, default=PRODUCT)
parser.add_argument("--output", type=Path, default=BUILD / "p04-s5-native-r32")
parser.add_argument("--plan", type=Path, default=BUILD / "p04-s5-plan-r32.json")
parser.add_argument("--cache-run", type=Path, default=None,
help="optional passed registered cache; default is fresh, without cache access")
parser.add_argument("--godot", type=Path, default=ENGINE)
parser.add_argument("--check-only", action="store_true")
args = parser.parse_args()
engine_descriptor = engine_pin(args.godot)
if args.cache_run is not None and args.cache_run.resolve() != CACHE_RUN.resolve():
raise ValueError("only registered own-B full-run cache")
root = args.project_root.resolve()
out = args.output.resolve()
if not out.is_relative_to(BUILD.resolve()) or not args.plan.resolve().is_relative_to(BUILD.resolve()):
raise ValueError("plan/output must stay in task build")
if out.exists() or out.is_symlink():
raise ValueError("fresh output required")
if args.check_only and (args.plan.exists() or args.plan.is_symlink()):
raise ValueError("fresh plan required")
r = module("s5_standard_runner", root / "tools/run_all_tests.py")
# Preserve the reviewed source_refs -> exactly one QA override order.
source_before = r.source_refs(root)
refs = dict(source_before)
refs[TEST] = pin(QA)
template_guard(root)
expected = {n: dict(bytes=p["bytes"], sha256=p["sha256"]) for n, p in refs.items()}
fixed = [pin(p) for p in MATERIALS + [
QA, Path(__file__), HERE / "S5_ROOT_RUN.md",
root / "tests/transport/test_runtime_transport.gd",
root / "tests/staff/test_rescue_elevator.gd",
CONTRACTS,
]]
selected = dict(root_before=source_before, map={n: p["sha256"] for n, p in refs.items()}, timeout=1200)
cache_note = None
cache_receipts = []
if args.cache_run is not None:
# Reject failed caches before reading their inputs or cache contents.
r.require(r.read(args.cache_run / "runner-ended.json")["passed"] is True,
"failed cache is ineligible")
for leaf in (["runner-ended.json", "runner-input.json"] if args.cache_run is not None else []):
path = args.cache_run / leaf
try:
cache_receipts.append(pin(path))
except OSError as caught:
cache_note = dict(path=str(path), error=type(caught).__name__ + ": " + str(caught),
required_before_native=True)
break
plan = dict(protocol="p04-s5-preparation-v1", project_root=str(root), output=str(out), engine_path=str(args.godot.resolve()),
source_before=source_before, selected_source_map=selected["map"],
QA_overrides=[TEST], fixed_input_pins=fixed,
cache_run=str(args.cache_run) if args.cache_run is not None else None,
import_mode="cache" if args.cache_run is not None else "fresh",
engine_sha256=ENGINE_SHA256, engine=engine_descriptor,
cache_receipts=cache_receipts, cache_access=cache_note,
phases=["import", "parse", "writer", "reader"],
native_engine_launches=0, whole_goal_accepted=False, unit_accepted=False)
# Check-only only reads source/materials and writes the plan in task build.
# Reads engine identity; never launches Godot or inspects players/processes.
if args.check_only:
args.plan.parent.mkdir(parents=True, exist_ok=True)
r.write(args.plan, plan)
print(json.dumps(dict(check_only=True, engines=0, source_files=len(source_before),
QA_overrides=[TEST], fixed_pins=len(fixed), plan=str(args.plan),
plan_sha256=r.sha(args.plan), cache_access=cache_note), ensure_ascii=False))
return 0
r.require(root == PRODUCT.resolve() and len(source_before) == 1338, "Root native requires product 1338; worker plan is not native evidence")
r.require(args.plan.is_file() and r.read(args.plan) == plan, "run exact check-only plan first")
engine_observations = []
engine_identity = dict(before=engine_descriptor, during=[], after=None)
def repin(label):
try:
value = engine_pin(args.godot, engine_descriptor)
engine_observations.append(dict(stage=label, descriptor=value))
if label == "after-cleanup":
engine_identity["after"] = value
else:
engine_identity["during"].append(value)
except BaseException as caught:
engine_observations.append(dict(stage=label, error=str(caught)))
raise
def fixed_guard():
repin("cleanup-fixed-guard")
template_guard(root)
for value in fixed + cache_receipts:
r.require(pin(value["path"]) == value, "fixed input changed: " + value["path"])
fixed_guard()
old = args.cache_run
if old is not None:
# Native cache admission remains Root-only and fails closed.
r.require(cache_note is None, "Root must read exact cache receipts: " + str(cache_note))
r.require(r.read(old / "runner-ended.json")["passed"], "ended cache run must have passed")
cache_input = r.read(old / "runner-input.json")
r.require(cache_input["engine_sha256"] == ENGINE_SHA256, "cache engine identity")
old_map = cache_input["selected_source_map"]
current_map = {n: p["sha256"] for n, p in source_before.items()}
r.require({k: v for k, v in old_map.items() if k != "tools/check_p04_order_evidence.py"} == current_map and len(old_map) == 1339, "immutable full cache: all 1338 product inputs equal; checker is not parsed/executed by product suites")
protected = r.default_player(root)
outer = module("s5_owned_outer", r.SUPPORT / "owned_outer.py")
r.require(not outer.native.helper["live_engines"](), "another Godot owns CPU")
engine = ENGINE
repin("native-admission")
r.require(shutil.disk_usage(out.parent).free >= 1024**3 + engine.stat().st_size + 136*1024**2,
"reviewed native disk admission")
r.require(not out.exists(), "fresh output required; preserve previous attempts")
out.mkdir()
stage = out / "stage"
stage.mkdir()
(out / "starters").mkdir()
(out / "bootstrap").mkdir()
phases = []
previous = {}
error = None
guards = []
cleanup = []
cleanup_errors = []
cache_before = None
formal_before = None
formal_after = None
original_phase = outer.run_phase
def run_phase(argv, folder, timeout, env, **kwargs):
env = dict(env)
if folder.name in ["writer", "reader"]:
env.update(THE_TREE_S5_EVIDENCE=str(out / "raw"), THE_TREE_S5_MODE=folder.name)
return original_phase(argv, folder, timeout, env, **kwargs)
outer.run_phase = run_phase
try:
r.write(out / "runner-started.json", dict(started=r.now(), owner_runner_pid=os.getpid(),
plan=pin(args.plan), engines_launched=0))
r.write(out / "source_before.json", source_before)
r.write(out / "selected-source-map.json", refs)
# Private source stage first, then literal reviewed bootstrap.
for name, value in refs.items():
target = stage / name
target.parent.mkdir(parents=True, exist_ok=True)
r.copy_source(Path(value["path"]), target)
r.require(r.inventory(stage, stage=True) == expected, "whole private source")
for name, value in r.read(r.SUPPORT / "bootstrap-scripts.json").items():
data = value["text"].encode()
r.require(hashlib.sha256(data).hexdigest() == value["sha256"], "bootstrap pin")
(out / "bootstrap" / name).write_bytes(data)
if old is not None:
cache = old / "stage/.godot"
cache_before = r.inventory(cache)
r.require(bool(cache_before), "nonempty ended cache")
for name in cache_before:
src = cache / name
dst = stage / ".godot" / name
dst.parent.mkdir(parents=True, exist_ok=True)
subprocess.run(["/bin/cp", "-c", str(src), str(dst)], check=True)
r.require((src.stat().st_dev, src.stat().st_ino) != (dst.stat().st_dev, dst.stat().st_ino),
"cache clone is a separate inode")
r.require(r.inventory(stage / ".godot") == cache_before, "whole cache clone hashes")
r.write(out / "cache-reuse.json", dict(ended_run=str(old), receipts=cache_receipts,
whole_cache=cache_before, independent_inode=True,
ordinary_import_required=True, ordinary_parse_required=True))
paths = ["res://" + n for n in sorted(refs) if n.endswith(".gd")]
r.require(len(paths) == 316, "complete 316-script parse roster")
r.write(out / "parse-paths.json", paths)
markers = module("s5_markers", root / "tools/strict_test_markers.py")
contracts = markers.load_contracts(CONTRACTS)
contracts[TEST] = dict(test=TEST, template="S5 power: <checks> checks, <failures> failures", required=True)
policy = r.read(r.SUPPORT / "suite-policy.json")
r.require(TEST not in policy["suite_policies"], "no normal suite watchdog/policy override")
r.write(out / "contracts.json", contracts)
r.write(out / "runner-input.json", dict(plan, owner_runner_pid=os.getpid(),
wrapper_sha256=r.sha(__file__), QA=pin(QA), engine=engine_descriptor,
engine_identity_before=engine_descriptor, engine_identity_initial=copy.deepcopy(engine_identity),
runner_sha256=r.sha(root / "tools/run_all_tests.py"),
default_player_before=protected, fixed_input_pins=fixed,
functional_watchdog_seconds=1200, source_adoption=False))
diagnostics = module("s5_diagnostics", r.SUPPORT / "diagnostic_gate.py")
owners = module("s5_owners", r.SUPPORT / "ordinary_proof_gate.py")
audio = module("s5_audio", r.SUPPORT / "audio_evidence_gate.py")
public = (stage / "project.godot").read_bytes()
for phase, test in [("import", None), ("parse", None), ("writer", TEST), ("reader", TEST)]:
if phase == "reader":
writer = r.read(out / "raw/writer.json")
formal_before = {n: r.inventory(Path(p)) for n, p in writer["slots"].items()}
r.require(sorted(formal_before) == SLOTS, "exact three formal points for isolated power case")
if phase == "import" and old is None:
r.require(not (stage / ".godot").exists() and not (stage / ".godot").is_symlink(),
"fresh private .godot absent at actual import")
repin("before-" + phase)
r.write(out / ("engine-identity-before-" + phase + ".json"),
dict(engine_observations[-1], observation_index=len(engine_observations)-1))
row = r.execute_phase(str(engine), stage, out, phase, test, selected, expected,
previous, policy, contracts, paths, public, protected, root,
outer, markers, diagnostics, owners, audio)
phases.append(row)
# execute_phase writer/reader share out/<test>.log via write_text.
# Keep binary per-phase copies under these existing unique names.
# The shared runner log is not write-once; see S5_ROOT_RUN.md.
if test and row.get("log"):
(out / (phase + "-combined-raw.log")).write_bytes((out / row["log"]).read_bytes())
row["strict_runner_log_path"] = row["log"]
row["log"] = phase + "-combined-raw.log"
r.write(out / (phase + "-actual-phase.json"), row)
print(json.dumps(dict(phase=phase, passed=row["passed"], error=row.get("validation_error"))), flush=True)
r.require(row["passed"], "first strict phase failure: " + phase)
if phase in ["writer", "reader"]:
receipt = r.read(out / ("raw/" + phase + ".json"))
r.require(receipt["checks"] > 0 and receipt["failures"] == 0,
"S5 actual outcome receipt")
r.require(sorted(receipt["branches"]) == CASES,
"exact one independent Writer/Reader case")
r.require(sorted(receipt["slots"]) == SLOTS, "all formal point slots")
r.require(receipt["pid"] == row["actual_pid"], "actual native PID/receipt")
repin("after-collection")
writer = r.read(out / "raw/writer.json")
reader = r.read(out / "raw/reader.json")
r.require(writer["pid"] != reader["pid"] and writer["profile"] != reader["profile"], "distinct formal processes")
formal_after = {n: r.inventory(Path(p)) for n, p in writer["slots"].items()}
r.require(formal_before == formal_after, "Reader leaves Writer packages unchanged")
except BaseException as caught:
error = type(caught).__name__ + ": " + str(caught)
finally:
try:
cleanup, cleanup_errors = outer.finish_captured(outer.OWNED)
except BaseException as caught:
cleanup_errors.append(str(caught))
try:
r.write(out / "outer-owned-finally.json", dict(cleanup=cleanup, errors=cleanup_errors))
except BaseException as caught:
guards.append("finally receipt: " + type(caught).__name__ + ": " + str(caught))
# Explicit re-pin after cleanup is independent of other fixed-input guards.
try:
repin("after-cleanup")
except BaseException as caught:
guards.append(type(caught).__name__ + ": " + str(caught))
# Fixed guard always follows ownership cleanup, even if setup or an engine failed.
try:
fixed_guard()
after = r.source_refs(root)
r.write(out / "source_after.json", after)
r.require(after == source_before, "whole product source unchanged")
r.require(r.default_player(root) == protected, "default player unchanged")
if (stage / "project.godot").exists():
r.require(r.inventory(stage, stage=True) == dict(expected, **previous), "whole private source unchanged")
if cache_before is not None:
r.require(r.inventory(old / "stage/.godot") == cache_before, "original cache unchanged")
if formal_before is not None:
writer = r.read(out / "raw/writer.json")
formal_after = {n: r.inventory(Path(p)) for n, p in writer["slots"].items()}
r.require(formal_before == formal_after, "Writer formal packages unchanged after Reader, including failure")
except BaseException as caught:
guards.append(type(caught).__name__ + ": " + str(caught))
pids = [p.pid for p in outer.OWNED]
passed = (error is None and not guards and not cleanup_errors and len(phases) == 4
and all(p["passed"] for p in phases) and len(pids) == len(set(pids)) == 4
and all(p["engine_ended"] for p in cleanup))
execution = dict(passed=passed, error=error, guard_errors=guards, phases=phases,
actual_captured_PIDs=pids, cleanup=cleanup, cleanup_errors=cleanup_errors,
formal_before=formal_before, formal_after=formal_after,
whole_goal_accepted=False, unit_accepted=False)
# IO1 has already copied all four members into a separate Reader profile.
# Mirror those exact complete directories to own B for read-only R verification.
# Original profile paths are provenance after this step, never verifier inputs.
try:
if passed:
relocated = {}
for role in ("writer", "reader"):
receipt = r.read(out / ("raw/" + role + ".json"))
relocated[role] = {}
for slot, original in receipt["slots"].items():
target = out / "formal" / role / slot
target.mkdir(parents=True)
members = r.inventory(Path(original))
r.require(set(members) == {"journal.log", "manifest.json", "thumbnail.png", "world.bin"}, "all formal members")
for member in members:
shutil.copyfile(Path(original) / member, target / member)
r.require(r.inventory(target) == members == formal_before[slot], "whole formal mirror")
relocated[role][slot] = dict(provenance=original, relative=str(target.relative_to(out)), members=members)
r.write(out / "formal-relocation.json", relocated)
r.write(out / "raw-inventory.json", r.inventory(out / "raw"))
r.write(out / "PID-set.json", dict(owner_runner_pid=os.getpid(), engine_PIDs=pids))
except BaseException as caught:
guards.append("output collection: " + type(caught).__name__ + ": " + str(caught))
passed = False
execution["passed"] = False
try:
repin("after-output-collection")
except BaseException as caught:
guards.append(str(caught))
passed = False
execution["passed"] = False
try:
r.write(out / "engine-identity.json",
dict(observations=engine_observations, identity=engine_identity))
except BaseException as caught:
guards.append("engine identity receipt: " + type(caught).__name__ + ": " + str(caught))
passed = False
execution["passed"] = False
execution["engine_observations"] = engine_observations
execution["engine_identity"] = engine_identity
r.write(out / "execution.json", execution)
r.write(out / "runner-ended.json", dict(execution, ended=r.now()))
print(json.dumps(dict(passed=passed, error=error, guard_errors=guards, output=str(out))))
return 0 if passed else 1
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as caught:
print(type(caught).__name__ + ": " + str(caught), file=sys.stderr)
raise SystemExit(2)
@@ -0,0 +1,145 @@
#!/usr/bin/env python3
"""Derive S5 power measurements from hashed writer/reader raw, not test counts.
This semantic adapter does not verify engine provenance, Q or full-suite joins.
Its output is preparation only and cannot replace the registered evidence gate.
"""
import argparse
import hashlib
import json
from pathlib import Path
CASES = ("S5A_PURE", "S5B_DEPENDENCY")
GUEST = "p04.s5.guest.a"
REQUEST = "p04.s5.request.a"
def require(value, message):
if not value:
raise ValueError(message)
def unique(pairs):
result = {}
for key, value in pairs:
require(key not in result, "duplicate raw key")
result[key] = value
return result
class Raw:
def __init__(self, root):
self.root = root.resolve(strict=True)
self.hashes = {}
def pin(self, path, expected):
path = Path(path)
require(path.is_file() and not path.is_symlink() and path.resolve().is_relative_to(self.root), "raw reference outside root/missing")
data = path.read_bytes()
digest = hashlib.sha256(data).hexdigest()
require(digest == expected, "raw reference SHA mismatch")
self.hashes[str(path)] = digest
return data
def reference(self, reference):
require(set(reference) == {"var", "json"}, "typed and JSON raw references required")
self.pin(reference["var"]["path"], reference["var"]["sha256"])
return json.loads(self.pin(reference["json"]["path"], reference["json"]["sha256"]), object_pairs_hook=unique)
def derive(root, writer_sha, reader_sha):
raw = Raw(root)
writer = json.loads(raw.pin(root / "writer.json", writer_sha), object_pairs_hook=unique)
reader = json.loads(raw.pin(root / "reader.json", reader_sha), object_pairs_hook=unique)
require(writer["pid"] != reader["pid"] and writer["profile"] != reader["profile"], "independent reader required")
require(set(writer["branches"]) == set(reader["branches"]) == set(CASES), "exact case pair")
output = {}
for case in CASES:
branch = raw.reference(writer["branches"][case])
replay = raw.reference(reader["branches"][case])
raw.reference(branch["commands"])
for role in (branch, replay):
guard = raw.reference(role["resource_replay"])
require(guard["result"]["is_replay"] is True and guard["result"]["code"] == "OK"
and guard["before"] == guard["after"], "resource replay changes no Runtime field")
points = {name: raw.reference(ref) for name, ref in branch["points"].items()}
require(set(points) == {"before", "boundary", "held", "recovered", "duplicate_guard"}, "full point roster")
before = points["before"]
price, duration = before["inputs"]["price"], before["inputs"]["duration"]
require(price > 0 and duration > 1 and before["mana"] > 0, "paid natural service")
service_id = before["service"]["service_id"]
require(before["service"]["state"] == "ACTIVE" and before["service"]["elapsed_minutes"] == duration - 1, "pre-boundary progress")
reservations = before["requests"][REQUEST]["reserved_inventory_ids"]
require(len(reservations) == (1 if case == "S5B_DEPENDENCY" else 0), "item premise")
for label in ("boundary", "held"):
point = points[label]
service = point["service"]
require(point["minute"] == before["inputs"]["boundary"] + (label == "held"), "boundary minute")
require(point["mana"] == 0 and point["facility"]["power_available"] is False, "real depletion projection")
reason = "RELATED_FACILITY_INACTIVE" if case == "S5B_DEPENDENCY" else "NO_POWER"
require(service["state"] == "PAUSED" and service["interruption_reason"] == reason
and service["elapsed_minutes"] == duration - 1 and service["service_id"] == service_id, "stopped reason/progress/service")
require(point["receipts"] == [] and point["ledger"] == before["ledger"]
and point["wallets"][GUEST] == price * 2 and point["player_cash"] == before["player_cash"], "zero stopped charge")
require(point["requests"][REQUEST] == before["requests"][REQUEST]
and point["guests"][GUEST]["state"] == "RECEIVING_SERVICE", "live request/guest ownership")
require(point["reservations"] == before["reservations"], "entire reservation retained")
if case == "S5B_DEPENDENCY":
require(point["kitchen"]["state"] == "NO_POWER" and point["related_facility_operating"] is False, "RELATED-before-NO_POWER")
require(all(r["state"] == "ACTIVE" and r["requester_id"] == REQUEST for r in point["reservations"]), "active item owner")
else:
require(point["related_facility_operating"] is True, "pure power premise")
recovered = points["recovered"]
resume = recovered["inputs"]["recovery"]["resume_minute"]
require(recovered["minute"] == resume and resume <= before["inputs"]["boundary"] + duration, "bounded observed resume")
for label in ("recovered", "duplicate_guard"):
point = points[label]
service = point["service"]
require(service["service_id"] == service_id and service["state"] == "COMPLETED"
and service["elapsed_minutes"] == duration and point["active_services"] == 0, "one completed service")
require(len(point["receipts"]) == 1 and point["ledger"] == before["ledger"] + point["receipts"][0]["entries"], "whole ledger single receipt")
require(point["wallets"][GUEST] == price and point["player_cash"] == before["player_cash"] + price, "single price")
require(point["receipts"] == recovered["receipts"] and point["ledger"] == recovered["ledger"], "no duplicate sale")
if reservations:
require(len(point["reservations"]) == 1, "same item count")
r = point["reservations"][0]
require(r["reservation_id"] == reservations[0] and r["state"] == "CONSUMED"
and r["terminal_at"] == service["completed_at"] and point["requests"][REQUEST] == {}, "consumed without orphan")
for label in ("held", "recovered", "duplicate_guard"):
require(raw.reference(replay["replay"][label]) == points[label], "reader full raw replay mismatch")
for label in ("boundary", "held", "recovered"):
require(raw.reference(replay["restored"][label])["snapshot"] == points[label]["snapshot"], "formal restore snapshot mismatch")
phases = [raw.reference(ref) for ref in branch["phases"]]
expected_replay = [p for p in phases if p["minute"] > before["inputs"]["boundary"] or
(p["minute"] == before["inputs"]["boundary"] and p["phase"] == "APPLY_COMMANDS")]
require([raw.reference(ref) for ref in replay["phases"]] == expected_replay, "all reader phase raw mismatch")
reasons = []
for p in phases:
reason = p["service"].get("interruption_reason", "")
if not reasons or reasons[-1] != reason:
reasons.append(reason)
output[case] = dict(measurements={
**({"power_stop": {"charges": 0}} if case == "S5A_PURE" else
{"dependency_stop": {"charges": 0, "progress_delta": 0, "reservation_ids_preserved": True, "service_id_preserved": True}}),
"recovery_completion": {"completions": 1, "charges": 1}},
reason_sequence=reasons, resume_minute=resume)
return dict(cases=output, raw_sha256=raw.hashes, native_provenance_verified=False,
whole_goal_accepted=False, unit_accepted=False)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--raw-root", type=Path, required=True)
parser.add_argument("--writer-sha256", required=True)
parser.add_argument("--reader-sha256", required=True)
args = parser.parse_args()
try:
print(json.dumps(derive(args.raw_root, args.writer_sha256, args.reader_sha256), sort_keys=True))
except (OSError, ValueError, KeyError, TypeError) as error:
print(json.dumps({"error": str(error), "whole_goal_accepted": False}))
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())