feat(p10.1): add Siltwake region entry and save v7

This commit is contained in:
2026-08-15 21:23:11 +08:00
parent b677370348
commit c46af4e8e0
12 changed files with 1329 additions and 0 deletions
+97
View File
@@ -0,0 +1,97 @@
class_name P101RecruitBindingService
extends RefCounted
const BaseContent = preload("res://p10_0/content_registry.gd")
const BaseGenerator = preload("res://p10_0/offer_generator.gd")
const BaseMarket = preload("res://p10_0/market_service.gd")
const PROVIDER_CONTRACT_ID := "CTR-R1-01"
const PROVIDER_MARKET_INDEX := 1
var _generator = BaseGenerator.new(BaseContent.snapshot())
func materialize(run_seed: String) -> Dictionary:
if not _is_seed(run_seed):
return {"ok": false, "code": "invalid_run_seed"}
var generated: Dictionary = _generator.market_board(
run_seed,
PROVIDER_CONTRACT_ID,
PROVIDER_MARKET_INDEX,
0
)
if not generated.ok or generated.board.recruit_offers.size() != 3:
return {"ok": false, "code": "base_recruit_generation_failed"}
var offers: Array[Dictionary] = []
for slot in range(3):
var base: Dictionary = Dictionary(generated.board.recruit_offers[slot]).duplicate(true)
var upstream_offer_id := String(base.source_offer_id)
base["upstream_source_offer_id"] = upstream_offer_id
base["upstream_market_id"] = String(base.market_id)
base["source_offer_id"] = _low128(_digest(run_seed, "p10.1.recruit-offer", [slot, upstream_offer_id]))
base["market_id"] = "MKT-CTR-R2-01-01-R00"
base["region_id"] = "RG-02"
base["contract_id"] = "CTR-R2-01"
base["offer_index"] = slot
base["offer_level"] = maxi(2, int(base.level))
base["profession_tier"] = 0
base["list_price"] = BaseMarket.hire_list_price(int(base.offer_level), 0)
base["state"] = "market_offer"
base.erase("canonical_output_hash")
base["canonical_output_hash"] = _hash(base)
offers.append(base)
var materialization := {
"run_seed": run_seed,
"region_id": "RG-02",
"contract_id": "CTR-R2-01",
"provider": "p10_0.offer_generator.recruit_projection.v1",
"provider_contract_id": PROVIDER_CONTRACT_ID,
"provider_market_index": PROVIDER_MARKET_INDEX,
"offers": offers,
}
materialization["materialization_hash"] = _hash(materialization)
return {
"ok": true,
"code": "recruits_materialized",
"offers": offers,
"materialization": materialization,
}
func _is_seed(value: String) -> bool:
if value.length() != 32:
return false
for character in value:
if character not in "0123456789abcdef":
return false
return true
func _digest(seed: String, label: String, parts: Array = []) -> String:
return _hash({"seed": seed, "label": label, "parts": parts})
func _low128(value: String) -> String:
return value.substr(0, 32)
func _hash(value) -> String:
return JSON.stringify(_canonical(value)).sha256_text()
func _canonical(value):
if value is float and is_equal_approx(value, round(value)):
return int(round(value))
if value is Dictionary:
var result := {}
var keys: Array = value.keys()
keys.sort_custom(func(left, right): return String(left) < String(right))
for key in keys:
result[key] = _canonical(value[key])
return result
if value is Array:
var result: Array = []
for item in value:
result.append(_canonical(item))
return result
return value
@@ -0,0 +1 @@
uid://c3t7m9k2v5q8h
+467
View File
@@ -0,0 +1,467 @@
class_name P101RegionMarketService
extends RefCounted
const BaseMarket = preload("res://p10_0/market_service.gd")
const FirstMarketGenerator = preload("res://p10_1/first_market_generator.gd")
const RecruitBinding = preload("res://p10_1/recruit_binding_service.gd")
const State = preload("res://p10_1/region_run_state.gd")
const STARTING_COIN := 64
const DIFFICULTIES := ["wayfinder", "standard", "stormbound", "iron_oath"]
const ROLE_ORDER := {
"PF-B01": 0, "PF-B02": 1, "PF-B03": 2, "PF-B04": 3,
"PF-B08": 4, "PF-B09": 5, "PF-B11": 6, "PF-B07": 7,
"PF-B05": 8, "PF-B06": 9, "PF-B10": 10, "PF-B12": 11,
}
var state := State.new()
var valid := false
var error_code := "migration_required"
var market_generator = FirstMarketGenerator.new()
var recruit_binding = RecruitBinding.new()
func _init(snapshot_value: Dictionary = {}) -> void:
if not snapshot_value.is_empty():
valid = state.restore_snapshot(snapshot_value)
error_code = "" if valid else "invalid_state"
func restore_snapshot(raw: Dictionary) -> bool:
valid = state.restore_snapshot(raw)
error_code = "" if valid else "invalid_state"
return valid
func begin_region_run(operation_id: String, expected_revision: int, difficulty: String) -> Dictionary:
var intent := {"expected_revision": expected_revision, "difficulty": difficulty, "contract_id": "CTR-R2-01"}
var prior := _prior_operation(operation_id, "begin_region_run", intent)
if prior.known:
return prior.result
if not valid:
return _reject(error_code)
if expected_revision != state.revision:
return _reject("stale_revision")
if not state.current_run.is_empty():
return _reject("region_run_active")
if difficulty not in DIFFICULTIES:
return _reject("unknown_difficulty")
if "RG-02" not in state.guild_profile.unlocked_region_ids:
return _reject("region_locked")
var ordinal := state.next_region_run_ordinal
var run_seed := _low128(_digest(state.generation_root_seed, "p10.1.region-run-seed", [state.lineage_id, ordinal]))
var generated: Dictionary = market_generator.generate(run_seed)
var recruits: Dictionary = recruit_binding.materialize(run_seed)
if not generated.ok or not recruits.ok:
return _reject("first_market_generation_failed")
var board := _bind_board(generated.board, recruits)
if board.is_empty():
return _reject("first_market_binding_failed")
var before := state.snapshot()
var run_id := _low128(_digest(run_seed, "p10.1.run-id"))
state.next_region_run_ordinal += 1
state.current_run = {
"run_id": run_id,
"region_id": "RG-02",
"contract_id": "CTR-R2-01",
"difficulty": difficulty,
"run_seed": run_seed,
"status": "active",
"phase": "market",
"market_index": 1,
"coin": STARTING_COIN,
"refresh_count": 0,
"line_capacity": 4,
"market_board": board,
"available_recruit_offer_ids": _offer_ids(board.recruit_offers, "source_offer_id"),
"available_equipment_offer_ids": _offer_ids(board.equipment_offers, "offer_id"),
"available_battle_offer_ids": _offer_ids(board.battle_offers, "offer_id"),
"company": [],
"deployed_recruit_ids": [],
"reserve_recruit_ids": [],
"recruit_records": {},
"inventory": {},
"equipped_by_recruit": {},
"formation_proposal": [],
"selected_route_id": "",
"pending_encounter": {},
}
var receipt := {
"operation_id": operation_id,
"run_id": run_id,
"run_seed": run_seed,
"region_id": "RG-02",
"contract_id": "CTR-R2-01",
"market_index": 1,
"board_hash": String(board.board_hash),
"recruit_offer_ids": _offer_ids(board.recruit_offers, "source_offer_id"),
"next_region_run_ordinal": state.next_region_run_ordinal,
}
state.entry_commits[run_id] = receipt.duplicate(true)
return _commit(operation_id, "begin_region_run", intent, "region_run_created", receipt, before)
func refresh_equipment(operation_id: String, expected_revision: int, expected_cost: int) -> Dictionary:
var intent := {"expected_revision": expected_revision, "expected_cost": expected_cost}
var prior := _prior_operation(operation_id, "refresh_equipment", intent)
if prior.known:
return prior.result
var guard := _market_guard(expected_revision)
if not guard.is_empty():
return _reject(guard)
var cost := mini(18, 6 + 3 * int(state.current_run.refresh_count))
if expected_cost != cost:
return _reject("refresh_cost_mismatch")
if int(state.current_run.coin) < cost:
return _reject("insufficient_coin")
var refresh_index := int(state.current_run.refresh_count) + 1
var generated: Dictionary = market_generator.generate(String(state.current_run.run_seed), 1, refresh_index)
if not generated.ok:
return _reject("refresh_generation_failed")
var before := state.snapshot()
var old_board: Dictionary = state.current_run.market_board
var board: Dictionary = generated.board.duplicate(true)
board.erase("recruit_slots")
board["recruit_offers"] = Array(old_board.recruit_offers).duplicate(true)
board["generation_authority"] = Dictionary(old_board.generation_authority).duplicate(true)
_price_equipment(board, String(state.current_run.run_seed))
board.erase("board_hash")
board["board_hash"] = _hash(board)
state.current_run.coin = int(state.current_run.coin) - cost
state.current_run.refresh_count = refresh_index
state.current_run.market_board = board
state.current_run.available_equipment_offer_ids = _offer_ids(board.equipment_offers, "offer_id")
var receipt := {
"operation_id": operation_id,
"cost": cost,
"coin": int(state.current_run.coin),
"refresh_count": refresh_index,
"board_hash": String(board.board_hash),
}
return _commit(operation_id, "refresh_equipment", intent, "equipment_refreshed", receipt, before)
func hire(operation_id: String, expected_revision: int, offer_id: String, expected_price: int) -> Dictionary:
var intent := {"expected_revision": expected_revision, "offer_id": offer_id, "expected_price": expected_price}
var prior := _prior_operation(operation_id, "hire", intent)
if prior.known:
return prior.result
var guard := _market_guard(expected_revision)
if not guard.is_empty():
return _reject(guard)
if state.current_run.company.size() >= 4:
return _reject("company_capacity")
var offer := _find_offer("recruit", offer_id)
if offer.is_empty() or offer_id not in state.current_run.available_recruit_offer_ids:
return _reject("recruit_offer_unavailable")
if expected_price != int(offer.list_price):
return _reject("price_mismatch")
if int(state.current_run.coin) < expected_price:
return _reject("insufficient_coin")
var before := state.snapshot()
var record := offer.duplicate(true)
var recruit_id := String(record.recruit_id)
record.state = "living"
record.coin_price_paid = expected_price
record.original_list_price = expected_price
state.current_run.coin = int(state.current_run.coin) - expected_price
state.current_run.company.append(recruit_id)
state.current_run.recruit_records[recruit_id] = record
state.current_run.available_recruit_offer_ids.erase(offer_id)
var instance_id := String(record.equipment_instance_id)
state.current_run.inventory[instance_id] = {
"instance_id": instance_id,
"catalog_id": String(record.starting_equipment_id),
"coin_price_paid": 0,
"wearer_id": recruit_id,
"source": offer_id,
}
state.current_run.equipped_by_recruit[recruit_id] = instance_id
_apply_automatic_order()
var receipt := {
"operation_id": operation_id,
"offer_id": offer_id,
"recruit_id": recruit_id,
"coin_cost": expected_price,
"coin": int(state.current_run.coin),
"deployed_recruit_ids": Array(state.current_run.deployed_recruit_ids).duplicate(),
}
return _commit(operation_id, "hire", intent, "recruit_hired", receipt, before)
func buy_equipment(operation_id: String, expected_revision: int, offer_id: String, expected_price: int) -> Dictionary:
var intent := {"expected_revision": expected_revision, "offer_id": offer_id, "expected_price": expected_price}
var prior := _prior_operation(operation_id, "buy_equipment", intent)
if prior.known:
return prior.result
var guard := _market_guard(expected_revision)
if not guard.is_empty():
return _reject(guard)
var offer := _find_offer("equipment", offer_id)
if offer.is_empty() or offer_id not in state.current_run.available_equipment_offer_ids:
return _reject("equipment_offer_unavailable")
if expected_price != int(offer.list_price):
return _reject("price_mismatch")
if int(state.current_run.coin) < expected_price:
return _reject("insufficient_coin")
var before := state.snapshot()
var instance_id := String(offer.instance_id)
state.current_run.coin = int(state.current_run.coin) - expected_price
state.current_run.inventory[instance_id] = {
"instance_id": instance_id,
"catalog_id": String(offer.catalog_id),
"coin_price_paid": expected_price,
"wearer_id": "",
"source": offer_id,
}
state.current_run.available_equipment_offer_ids.erase(offer_id)
var receipt := {
"operation_id": operation_id,
"offer_id": offer_id,
"instance_id": instance_id,
"catalog_id": String(offer.catalog_id),
"coin_cost": expected_price,
"coin": int(state.current_run.coin),
}
return _commit(operation_id, "buy_equipment", intent, "equipment_bought", receipt, before)
func equip(operation_id: String, expected_revision: int, recruit_id: String, instance_id: String) -> Dictionary:
var intent := {"expected_revision": expected_revision, "recruit_id": recruit_id, "instance_id": instance_id}
var prior := _prior_operation(operation_id, "equip", intent)
if prior.known:
return prior.result
var guard := _market_guard(expected_revision)
if not guard.is_empty():
return _reject(guard)
if recruit_id not in state.current_run.company:
return _reject("recruit_unavailable")
if not state.current_run.inventory.has(instance_id):
return _reject("equipment_unavailable")
var item: Dictionary = state.current_run.inventory[instance_id]
if not String(item.wearer_id).is_empty() and String(item.wearer_id) != recruit_id:
return _reject("equipment_worn")
var previous_id := String(state.current_run.equipped_by_recruit.get(recruit_id, ""))
if previous_id == instance_id:
return _no_commit("equipment_already_equipped", {"recruit_id": recruit_id, "instance_id": instance_id})
var before := state.snapshot()
if not previous_id.is_empty():
state.current_run.inventory[previous_id].wearer_id = ""
state.current_run.inventory[instance_id].wearer_id = recruit_id
state.current_run.equipped_by_recruit[recruit_id] = instance_id
return _commit(operation_id, "equip", intent, "equipment_equipped", {
"operation_id": operation_id,
"recruit_id": recruit_id,
"instance_id": instance_id,
"previous_instance_id": previous_id,
}, before)
func commit_order(operation_id: String, expected_revision: int, recruit_ids: Array) -> Dictionary:
var intent := {"expected_revision": expected_revision, "recruit_ids": recruit_ids.duplicate()}
var prior := _prior_operation(operation_id, "commit_order", intent)
if prior.known:
return prior.result
var guard := _market_guard(expected_revision)
if not guard.is_empty():
return _reject(guard)
if not _unique(recruit_ids) or not _same_members(recruit_ids, state.current_run.company):
return _reject("order_membership_mismatch")
if recruit_ids == state.current_run.deployed_recruit_ids:
return _no_commit("order_unchanged", {"recruit_ids": recruit_ids.duplicate()})
var before := state.snapshot()
state.current_run.deployed_recruit_ids = recruit_ids.duplicate()
state.current_run.reserve_recruit_ids = []
state.current_run.formation_proposal = recruit_ids.duplicate()
return _commit(operation_id, "commit_order", intent, "order_committed", {
"operation_id": operation_id,
"recruit_ids": recruit_ids.duplicate(),
}, before)
func commit_route(operation_id: String, expected_revision: int, offer_id: String, expected_board_hash: String) -> Dictionary:
var intent := {"expected_revision": expected_revision, "offer_id": offer_id, "expected_board_hash": expected_board_hash}
var prior := _prior_operation(operation_id, "commit_route", intent)
if prior.known:
return prior.result
var guard := _market_guard(expected_revision)
if not guard.is_empty():
return _reject(guard)
if state.current_run.company.size() < 2:
return _reject("two_recruits_required")
if expected_board_hash != String(state.current_run.market_board.board_hash):
return _reject("board_hash_mismatch")
var offer := _find_offer("battle", offer_id)
if offer.is_empty() or offer_id not in state.current_run.available_battle_offer_ids:
return _reject("battle_offer_unavailable")
var before := state.snapshot()
state.current_run.phase = "prepared"
state.current_run.selected_route_id = offer_id
state.current_run.pending_encounter = offer.duplicate(true)
state.current_run.pending_encounter["deployed_recruit_ids"] = Array(state.current_run.deployed_recruit_ids).duplicate()
state.current_run.pending_encounter["board_hash"] = expected_board_hash
return _commit(operation_id, "commit_route", intent, "route_prepared", {
"operation_id": operation_id,
"offer_id": offer_id,
"route_id": String(offer.route_id),
"risk": int(offer.risk),
"board_hash": expected_board_hash,
"deployed_recruit_ids": Array(state.current_run.deployed_recruit_ids).duplicate(),
}, before)
func _bind_board(overlay: Dictionary, recruits: Dictionary) -> Dictionary:
var board := overlay.duplicate(true)
if not board.has("recruit_slots") or int(board.recruit_slots.get("count", 0)) != 3:
return {}
board.erase("recruit_slots")
board["recruit_offers"] = Array(recruits.offers).duplicate(true)
board["generation_authority"] = {
"provider": String(recruits.materialization.provider),
"materialization_hash": String(recruits.materialization.materialization_hash),
}
_price_equipment(board, String(board.run_seed))
board.erase("board_hash")
board["board_hash"] = _hash(board)
return board
func _price_equipment(board: Dictionary, run_seed: String) -> void:
for offer in board.equipment_offers:
offer["region_band"] = 1
offer["item_tier"] = 0
offer["list_price"] = BaseMarket.equipment_list_price(1, 0)
offer["instance_id"] = _low128(_digest(run_seed, "p10.1.equipment-instance", [offer.offer_id]))
func _apply_automatic_order() -> void:
var ordered: Array = Array(state.current_run.company).duplicate()
ordered.sort_custom(func(left, right):
var left_record: Dictionary = state.current_run.recruit_records[left]
var right_record: Dictionary = state.current_run.recruit_records[right]
var left_rank := int(ROLE_ORDER.get(String(left_record.profession_id), 99))
var right_rank := int(ROLE_ORDER.get(String(right_record.profession_id), 99))
return left_rank < right_rank if left_rank != right_rank else String(left) < String(right)
)
state.current_run.deployed_recruit_ids = ordered
state.current_run.reserve_recruit_ids = []
state.current_run.formation_proposal = ordered.duplicate()
func _market_guard(expected_revision: int) -> String:
if not valid:
return error_code
if expected_revision != state.revision:
return "stale_revision"
if state.current_run.is_empty() or String(state.current_run.phase) != "market":
return "market_required"
return ""
func _find_offer(kind: String, offer_id: String) -> Dictionary:
if state.current_run.is_empty():
return {}
var field := String({"recruit": "recruit_offers", "equipment": "equipment_offers", "battle": "battle_offers"}.get(kind, ""))
var id_field := "source_offer_id" if kind == "recruit" else "offer_id"
for offer in state.current_run.market_board.get(field, []):
if String(offer.get(id_field, "")) == offer_id:
return Dictionary(offer).duplicate(true)
return {}
func _prior_operation(operation_id: String, kind: String, intent: Dictionary) -> Dictionary:
if not valid or operation_id.is_empty() or not state.operation_receipts.has(operation_id):
return {"known": false}
var stored: Dictionary = state.operation_receipts[operation_id]
if String(stored.kind) != kind or String(stored.intent_hash) != _hash(intent):
return {"known": true, "result": _reject("operation_conflict")}
var result: Dictionary = Dictionary(stored.result).duplicate(true)
result["duplicate"] = true
return {"known": true, "result": result}
func _commit(operation_id: String, kind: String, intent: Dictionary, code: String, receipt: Dictionary, before: Dictionary) -> Dictionary:
state.revision += 1
var result := {
"ok": true,
"code": code,
"duplicate": false,
"revision": state.revision,
"receipt": receipt.duplicate(true),
"snapshot": state.snapshot(),
}
state.operation_receipts[operation_id] = {
"operation_id": operation_id,
"kind": kind,
"intent_hash": _hash(intent),
"result": result.duplicate(true),
}
if not state.invariants_hold():
state.restore_snapshot(before)
return _reject("postcondition_failed")
result.snapshot = state.snapshot()
state.operation_receipts[operation_id].result = result.duplicate(true)
return result
func _no_commit(code: String, receipt: Dictionary) -> Dictionary:
return {"ok": true, "code": code, "duplicate": true, "revision": state.revision, "receipt": receipt, "snapshot": state.snapshot()}
func _reject(code: String) -> Dictionary:
return {"ok": false, "code": code, "duplicate": false, "revision": state.revision if valid else -1}
func _offer_ids(offers: Array, field: String) -> Array[String]:
var result: Array[String] = []
for offer in offers:
result.append(String(offer.get(field, "")))
return result
func _same_members(left: Array, right: Array) -> bool:
if left.size() != right.size():
return false
for value in left:
if value not in right:
return false
return true
func _unique(values: Array) -> bool:
var seen := {}
for value in values:
if seen.has(value):
return false
seen[value] = true
return true
func _digest(seed: String, label: String, parts: Array = []) -> String:
return _hash({"seed": seed, "label": label, "parts": parts})
func _low128(value: String) -> String:
return value.substr(0, 32)
func _hash(value) -> String:
return JSON.stringify(_canonical(value)).sha256_text()
func _canonical(value):
if value is float and is_equal_approx(value, round(value)):
return int(round(value))
if value is Dictionary:
var result := {}
var keys: Array = value.keys()
keys.sort_custom(func(left, right): return String(left) < String(right))
for key in keys:
result[key] = _canonical(value[key])
return result
if value is Array:
var result: Array = []
for item in value:
result.append(_canonical(item))
return result
return value
@@ -0,0 +1 @@
uid://d6q2w8m4h9r5k
+298
View File
@@ -0,0 +1,298 @@
class_name P101RegionRunState
extends RefCounted
const P100State = preload("res://p10_0/run_state.gd")
const STATE_KIND := "p101_siltwake_run"
const RULESET_VERSION := "p10.1-siltwake-first-crossing-r1"
var state_kind := STATE_KIND
var ruleset := RULESET_VERSION
var revision := 0
var lineage_id := ""
var generation_root_seed := ""
var next_region_run_ordinal := 0
var migration_source_hash := ""
var guild_profile: Dictionary = {}
var current_run: Dictionary = {}
var operation_receipts: Dictionary = {}
var entry_commits: Dictionary = {}
func initialize_from_p100(p100_snapshot: Dictionary) -> bool:
var probe := P100State.new()
if not probe.restore_snapshot(p100_snapshot):
return false
var source := probe.snapshot()
if not source.current_run.is_empty() or not source.run_creation_draft.is_empty():
return false
if "RG-02" not in source.guild_profile.unlocked_region_ids:
return false
if "CLEAR-RG01-C01" not in source.guild_profile.contract_clear_ids or "CLEAR-RG01-C02" not in source.guild_profile.contract_clear_ids:
return false
state_kind = STATE_KIND
ruleset = RULESET_VERSION
revision = 0
lineage_id = String(source.lineage_id)
generation_root_seed = String(source.generation_root_seed)
next_region_run_ordinal = 0
migration_source_hash = _hash(source)
guild_profile = Dictionary(source.guild_profile).duplicate(true)
current_run = {}
operation_receipts = {}
entry_commits = {}
return invariants_hold()
func snapshot() -> Dictionary:
var raw := {
"state_kind": state_kind,
"ruleset": ruleset,
"revision": revision,
"lineage_id": lineage_id,
"generation_root_seed": generation_root_seed,
"next_region_run_ordinal": next_region_run_ordinal,
"migration_source_hash": migration_source_hash,
"guild_profile": guild_profile.duplicate(true),
"current_run": current_run.duplicate(true),
"operation_receipts": operation_receipts.duplicate(true),
"entry_commits": entry_commits.duplicate(true),
}
var normalized = JSON.parse_string(JSON.stringify(raw))
return Dictionary(normalized).duplicate(true) if normalized is Dictionary else {}
func restore_snapshot(raw: Dictionary) -> bool:
var normalized_value = JSON.parse_string(JSON.stringify(raw))
if not normalized_value is Dictionary:
return false
var normalized: Dictionary = normalized_value
var required := [
"state_kind", "ruleset", "revision", "lineage_id",
"generation_root_seed", "next_region_run_ordinal",
"migration_source_hash", "guild_profile", "current_run",
"operation_receipts", "entry_commits",
]
for key in required:
if not normalized.has(key):
return false
for key in ["guild_profile", "current_run", "operation_receipts", "entry_commits"]:
if not normalized[key] is Dictionary:
return false
var before := snapshot()
_assign(normalized)
if not invariants_hold():
if not before.is_empty():
_assign(before)
return false
return true
func invariants_hold() -> bool:
if state_kind != STATE_KIND or ruleset != RULESET_VERSION or revision < 0:
return false
if not _is_hex(lineage_id, 32) or not _is_hex(generation_root_seed, 32):
return false
if next_region_run_ordinal < 0 or not _is_hex(migration_source_hash, 64):
return false
if not _guild_invariants_hold() or not _receipts_hold():
return false
return current_run.is_empty() or _run_invariants_hold()
func _guild_invariants_hold() -> bool:
for key in ["persistent_renown", "contract_clear_ids", "discovery_ids", "company_records", "unlocked_region_ids", "clear_receipts"]:
if not guild_profile.has(key):
return false
for key in ["contract_clear_ids", "discovery_ids", "company_records", "unlocked_region_ids"]:
if not guild_profile[key] is Array:
return false
if not guild_profile.clear_receipts is Dictionary:
return false
if int(guild_profile.persistent_renown) < 0 or int(guild_profile.persistent_renown) > 9999:
return false
return (
"RG-01" in guild_profile.unlocked_region_ids
and "RG-02" in guild_profile.unlocked_region_ids
and "CLEAR-RG01-C01" in guild_profile.contract_clear_ids
and "CLEAR-RG01-C02" in guild_profile.contract_clear_ids
and _unique(guild_profile.unlocked_region_ids)
and _unique(guild_profile.contract_clear_ids)
)
func _run_invariants_hold() -> bool:
var required := [
"run_id", "region_id", "contract_id", "difficulty", "run_seed",
"status", "phase", "market_index", "coin", "refresh_count",
"line_capacity", "market_board", "available_recruit_offer_ids",
"available_equipment_offer_ids", "available_battle_offer_ids",
"company", "deployed_recruit_ids", "reserve_recruit_ids",
"recruit_records", "inventory", "equipped_by_recruit",
"formation_proposal", "selected_route_id", "pending_encounter",
]
for key in required:
if not current_run.has(key):
return false
for key in ["market_board", "recruit_records", "inventory", "equipped_by_recruit", "pending_encounter"]:
if not current_run[key] is Dictionary:
return false
for key in ["available_recruit_offer_ids", "available_equipment_offer_ids", "available_battle_offer_ids", "company", "deployed_recruit_ids", "reserve_recruit_ids", "formation_proposal"]:
if not current_run[key] is Array:
return false
if not _is_hex(String(current_run.run_id), 32) or not _is_hex(String(current_run.run_seed), 32):
return false
if String(current_run.region_id) != "RG-02" or String(current_run.contract_id) != "CTR-R2-01":
return false
if String(current_run.status) != "active" or String(current_run.phase) not in ["market", "prepared"]:
return false
if int(current_run.market_index) != 1 or int(current_run.coin) < 0 or int(current_run.refresh_count) < 0:
return false
if int(current_run.line_capacity) != 4:
return false
var board: Dictionary = current_run.market_board
for key in ["board_id", "board_hash", "run_seed", "contract_id", "region_id", "market_index", "refresh_index", "tide_disclosure", "recruit_offers", "equipment_offers", "battle_offers"]:
if not board.has(key):
return false
if not board.recruit_offers is Array or not board.equipment_offers is Array or not board.battle_offers is Array:
return false
if board.recruit_offers.size() != 3 or board.equipment_offers.size() != 4 or board.battle_offers.size() != 3:
return false
if String(board.run_seed) != String(current_run.run_seed) or int(board.refresh_index) != int(current_run.refresh_count):
return false
var recruit_ids := _offer_ids(board.recruit_offers, "source_offer_id")
var equipment_ids := _offer_ids(board.equipment_offers, "offer_id")
var battle_ids := _offer_ids(board.battle_offers, "offer_id")
if not _subset(current_run.available_recruit_offer_ids, recruit_ids) or not _subset(current_run.available_equipment_offer_ids, equipment_ids) or not _subset(current_run.available_battle_offer_ids, battle_ids):
return false
var company: Array = current_run.company
var deployed: Array = current_run.deployed_recruit_ids
var reserve: Array = current_run.reserve_recruit_ids
if not _unique(company) or not _unique(deployed) or not _unique(reserve):
return false
if company.size() > 4 or not _subset(deployed, company) or not _subset(reserve, company):
return false
if not _same_members(deployed + reserve, company) or not _disjoint(deployed, reserve):
return false
if current_run.recruit_records.size() != company.size() or current_run.equipped_by_recruit.size() != company.size():
return false
for recruit_id in company:
if not current_run.recruit_records.has(recruit_id) or not current_run.equipped_by_recruit.has(recruit_id):
return false
if String(current_run.recruit_records[recruit_id].get("state", "")) != "living":
return false
var worn := {}
for instance_id in current_run.inventory:
var item = current_run.inventory[instance_id]
if not item is Dictionary or String(item.get("instance_id", "")) != instance_id:
return false
var wearer := String(item.get("wearer_id", ""))
if not wearer.is_empty():
if wearer not in company or worn.has(wearer) or String(current_run.equipped_by_recruit.get(wearer, "")) != instance_id:
return false
worn[wearer] = instance_id
for recruit_id in current_run.equipped_by_recruit:
var equipped_id := String(current_run.equipped_by_recruit[recruit_id])
if not equipped_id.is_empty() and (not current_run.inventory.has(equipped_id) or String(current_run.inventory[equipped_id].wearer_id) != recruit_id):
return false
if String(current_run.phase) == "market":
return String(current_run.selected_route_id).is_empty() and current_run.pending_encounter.is_empty()
return (
String(current_run.selected_route_id) in battle_ids
and not current_run.pending_encounter.is_empty()
and String(current_run.pending_encounter.get("offer_id", "")) == String(current_run.selected_route_id)
and company.size() >= 2
)
func _receipts_hold() -> bool:
for operation_id in operation_receipts:
var row = operation_receipts[operation_id]
if not row is Dictionary or String(row.get("operation_id", "")) != operation_id:
return false
if not _is_hex(String(row.get("intent_hash", "")), 64) or not row.get("result", {}) is Dictionary:
return false
for run_id in entry_commits:
var row = entry_commits[run_id]
if not row is Dictionary or String(row.get("run_id", "")) != run_id:
return false
return true
func _assign(raw: Dictionary) -> void:
state_kind = String(raw.state_kind)
ruleset = String(raw.ruleset)
revision = int(raw.revision)
lineage_id = String(raw.lineage_id)
generation_root_seed = String(raw.generation_root_seed)
next_region_run_ordinal = int(raw.next_region_run_ordinal)
migration_source_hash = String(raw.migration_source_hash)
guild_profile = Dictionary(raw.guild_profile).duplicate(true)
current_run = Dictionary(raw.current_run).duplicate(true)
operation_receipts = Dictionary(raw.operation_receipts).duplicate(true)
entry_commits = Dictionary(raw.entry_commits).duplicate(true)
func _offer_ids(offers: Array, field: String) -> Array[String]:
var result: Array[String] = []
for offer in offers:
result.append(String(offer.get(field, "")))
return result
func _subset(values: Array, authority: Array) -> bool:
for value in values:
if value not in authority:
return false
return true
func _disjoint(left: Array, right: Array) -> bool:
for value in left:
if value in right:
return false
return true
func _same_members(left: Array, right: Array) -> bool:
return left.size() == right.size() and _subset(left, right) and _subset(right, left)
func _unique(values: Array) -> bool:
var seen := {}
for value in values:
if seen.has(value):
return false
seen[value] = true
return true
func _is_hex(value: String, length: int) -> bool:
if value.length() != length:
return false
for character in value:
if character not in "0123456789abcdef":
return false
return true
func _hash(value) -> String:
return JSON.stringify(_canonical(value)).sha256_text()
func _canonical(value):
if value is float and is_equal_approx(value, round(value)):
return int(round(value))
if value is Dictionary:
var result := {}
var keys: Array = value.keys()
keys.sort_custom(func(left, right): return String(left) < String(right))
for key in keys:
result[key] = _canonical(value[key])
return result
if value is Array:
var result: Array = []
for item in value:
result.append(_canonical(item))
return result
return value
+1
View File
@@ -0,0 +1 @@
uid://b9h4r2x7m5q3v
+203
View File
@@ -0,0 +1,203 @@
class_name P101SaveV7Service
extends RefCounted
const P100Save = preload("res://p10_0/save_service.gd")
const State = preload("res://p10_1/region_run_state.gd")
const SAVE_VERSION := 7
const SAVE_KIND := "aetherbound_guild_p10"
const OFFLINE_ZERO := {
"coin": 0,
"credit": 0,
"xp": 0,
"renown": 0,
"healing": 0,
"battle_ticks": 0,
}
func encode_snapshot(snapshot_value: Dictionary, sequence: int, previous_commit_hash: String = "") -> Dictionary:
var probe := State.new()
if not probe.restore_snapshot(snapshot_value):
return {"ok": false, "code": "invalid_state", "text": ""}
if sequence < 0:
return {"ok": false, "code": "invalid_sequence", "text": ""}
if not previous_commit_hash.is_empty() and not _is_hex(previous_commit_hash, 64):
return {"ok": false, "code": "invalid_previous_hash", "text": ""}
var envelope := {
"save_kind": SAVE_KIND,
"save_version": SAVE_VERSION,
"sequence": sequence,
"previous_commit_hash": previous_commit_hash,
"state": probe.snapshot(),
}
envelope["state_hash"] = _hash(envelope.state)
envelope["commit_hash"] = _hash({
"sequence": sequence,
"previous_commit_hash": previous_commit_hash,
"state_hash": envelope.state_hash,
})
envelope["checksum"] = _hash(envelope)
return {"ok": true, "code": "encoded", "text": JSON.stringify(_canonical(envelope)), "envelope": envelope}
func decode_text(text: String, minimum_sequence: int = -1) -> Dictionary:
if text.is_empty():
return {"ok": false, "code": "save_missing"}
var parser := JSON.new()
if parser.parse(text) != OK or not parser.data is Dictionary:
return {"ok": false, "code": "save_malformed"}
var envelope: Dictionary = parser.data
for key in ["save_kind", "save_version", "sequence", "previous_commit_hash", "state", "state_hash", "commit_hash", "checksum"]:
if not envelope.has(key):
return {"ok": false, "code": "save_field_missing:%s" % key}
if String(envelope.save_kind) != SAVE_KIND:
return {"ok": false, "code": "save_kind_unknown"}
if int(envelope.save_version) != SAVE_VERSION:
return {"ok": false, "code": "save_version_unknown"}
if int(envelope.sequence) < minimum_sequence:
return {"ok": false, "code": "rollback_rejected", "sequence": int(envelope.sequence)}
var checksum := String(envelope.checksum)
var checksum_input := envelope.duplicate(true)
checksum_input.erase("checksum")
if not _is_hex(checksum, 64) or _hash(checksum_input) != checksum:
return {"ok": false, "code": "checksum_mismatch"}
if String(envelope.state_hash) != _hash(envelope.state):
return {"ok": false, "code": "state_hash_mismatch"}
var expected_commit := _hash({
"sequence": int(envelope.sequence),
"previous_commit_hash": String(envelope.previous_commit_hash),
"state_hash": String(envelope.state_hash),
})
if String(envelope.commit_hash) != expected_commit:
return {"ok": false, "code": "commit_hash_mismatch"}
var state_probe := State.new()
if not envelope.state is Dictionary or not state_probe.restore_snapshot(envelope.state):
return {"ok": false, "code": "state_invalid"}
return {
"ok": true,
"code": "loaded",
"sequence": int(envelope.sequence),
"commit_hash": String(envelope.commit_hash),
"snapshot": state_probe.snapshot(),
"offline_delta": OFFLINE_ZERO.duplicate(true),
}
func migrate_v6_text(text: String, minimum_sequence: int = -1) -> Dictionary:
var decoded: Dictionary = P100Save.new().decode_text(text, minimum_sequence)
if not decoded.ok:
return {"ok": false, "code": "v6_%s" % String(decoded.code)}
if not decoded.snapshot.current_run.is_empty() or not decoded.snapshot.run_creation_draft.is_empty():
return {"ok": false, "code": "v6_active_run_not_migratable"}
if "RG-02" not in decoded.snapshot.guild_profile.unlocked_region_ids:
return {"ok": false, "code": "v6_region_locked"}
var state := State.new()
if not state.initialize_from_p100(decoded.snapshot):
return {"ok": false, "code": "v6_state_rejected"}
var encoded := encode_snapshot(state.snapshot(), int(decoded.sequence) + 1, String(decoded.commit_hash))
if not encoded.ok:
return {"ok": false, "code": "v7_encode_failed"}
return {
"ok": true,
"code": "v6_migrated_to_v7",
"text": String(encoded.text),
"envelope": encoded.envelope,
"snapshot": state.snapshot(),
"source_sequence": int(decoded.sequence),
"sequence": int(decoded.sequence) + 1,
"previous_commit_hash": String(decoded.commit_hash),
"offline_delta": OFFLINE_ZERO.duplicate(true),
}
func load_with_backup(active_text: String, backup_text: String, minimum_sequence: int = -1) -> Dictionary:
var active := decode_text(active_text, minimum_sequence)
if active.ok:
active["source"] = "active"
return active
var backup := decode_text(backup_text, minimum_sequence)
if backup.ok:
backup["source"] = "backup"
backup["active_failure"] = String(active.code)
return backup
return {
"ok": false,
"code": "no_valid_save",
"active_failure": String(active.code),
"backup_failure": String(backup.code),
}
func write_slot(active_path: String, snapshot_value: Dictionary, sequence: int, previous_commit_hash: String = "") -> Dictionary:
var encoded := encode_snapshot(snapshot_value, sequence, previous_commit_hash)
if not encoded.ok:
return encoded
var candidate_path := "%s.candidate" % active_path
var backup_path := "%s.bak" % active_path
var candidate := FileAccess.open(candidate_path, FileAccess.WRITE)
if candidate == null:
return {"ok": false, "code": "candidate_open_failed"}
candidate.store_string(String(encoded.text))
candidate.flush()
candidate.close()
var verified := decode_text(FileAccess.get_file_as_string(candidate_path), sequence)
if not verified.ok or String(verified.commit_hash) != String(encoded.envelope.commit_hash):
return {"ok": false, "code": "candidate_verify_failed"}
if FileAccess.file_exists(backup_path):
DirAccess.remove_absolute(backup_path)
if FileAccess.file_exists(active_path):
var backup_error := DirAccess.rename_absolute(active_path, backup_path)
if backup_error != OK:
return {"ok": false, "code": "backup_rotate_failed"}
var promote_error := DirAccess.rename_absolute(candidate_path, active_path)
if promote_error != OK:
if FileAccess.file_exists(backup_path) and not FileAccess.file_exists(active_path):
DirAccess.rename_absolute(backup_path, active_path)
return {"ok": false, "code": "candidate_promote_failed"}
return {
"ok": true,
"code": "saved",
"sequence": sequence,
"commit_hash": String(encoded.envelope.commit_hash),
"active_path": active_path,
"backup_path": backup_path,
}
func load_slot(active_path: String, minimum_sequence: int = -1) -> Dictionary:
var active_text := FileAccess.get_file_as_string(active_path) if FileAccess.file_exists(active_path) else ""
var backup_path := "%s.bak" % active_path
var backup_text := FileAccess.get_file_as_string(backup_path) if FileAccess.file_exists(backup_path) else ""
return load_with_backup(active_text, backup_text, minimum_sequence)
func _is_hex(value: String, length: int) -> bool:
if value.length() != length:
return false
for character in value:
if character not in "0123456789abcdef":
return false
return true
func _hash(value) -> String:
return JSON.stringify(_canonical(value)).sha256_text()
func _canonical(value):
if value is float and is_equal_approx(value, round(value)):
return int(round(value))
if value is Dictionary:
var result := {}
var keys: Array = value.keys()
keys.sort_custom(func(left, right): return String(left) < String(right))
for key in keys:
result[key] = _canonical(value[key])
return result
if value is Array:
var result: Array = []
for item in value:
result.append(_canonical(item))
return result
return value
+1
View File
@@ -0,0 +1 @@
uid://b2v8n5q7m4h9r
@@ -0,0 +1,127 @@
extends SceneTree
const P100Market = preload("res://p10_0/market_service.gd")
const RegionService = preload("res://p10_1/region_market_service.gd")
const State = preload("res://p10_1/region_run_state.gd")
var failures: Array[String] = []
var applied_operations := 0
var rejected_cases := 0
func _initialize() -> void:
call_deferred("run_test")
func run_test() -> void:
verify_deterministic_region_entry()
verify_market_transactions()
verify_atomic_boundaries()
if failures.is_empty():
print("ABG_P10_1_REGION_ENTRY_MARKET_OK migration=v6_guild_only run_seed=stable board=3,4,3 hire=2 equipment=buy,equip order=automatic,manual refresh=equipment_only route=prepared revisions=exact applied=%d rejected=%d" % [applied_operations, rejected_cases])
quit(0)
else:
for failure in failures:
push_error(failure)
quit(1)
func verify_deterministic_region_entry() -> void:
var first = migrated_service()
var before: Dictionary = first.state.snapshot()
var entered: Dictionary = apply(first, "enter-rg02", func(): return first.begin_region_run("enter-rg02", first.state.revision, "standard"), "Region entry")
expect(entered.ok and first.state.current_run.region_id == "RG-02", "entry creates exact RG-02 Run")
expect(first.state.current_run.market_board.recruit_offers.size() == 3 and first.state.current_run.market_board.equipment_offers.size() == 4 and first.state.current_run.market_board.battle_offers.size() == 3, "entry binds complete 3/4/3 board")
expect(first.state.current_run.market_board.recruit_offers.all(func(offer): return offer.region_id == "RG-02" and offer.contract_id == "CTR-R2-01"), "three Recruit offers are rebound to Siltwake without copying generation")
expect(first.state.current_run.coin == 64 and first.state.current_run.company.is_empty(), "Market begins funded and awaits Recruit decisions")
var after: Dictionary = first.state.snapshot()
var duplicate: Dictionary = first.begin_region_run("enter-rg02", 0, "standard")
expect(duplicate.ok and duplicate.duplicate and first.state.snapshot() == after, "entry retry cannot reserve a second seed")
var second = migrated_service()
expect(second.begin_region_run("enter-rg02", 0, "standard").ok, "second deterministic fixture enters")
expect(second.state.current_run == first.state.current_run, "same migrated Guild and intent produce byte-identical Run")
expect(before.next_region_run_ordinal == 0 and first.state.next_region_run_ordinal == 1, "entry consumes exactly one Region ordinal")
func verify_market_transactions() -> void:
var service = migrated_service()
apply(service, "flow-enter", func(): return service.begin_region_run("flow-enter", service.state.revision, "standard"), "flow entry")
var tide_before: Dictionary = service.state.current_run.market_board.tide_disclosure.duplicate(true)
var routes_before: Array = Array(service.state.current_run.market_board.battle_offers).duplicate(true)
apply(service, "flow-refresh", func(): return service.refresh_equipment("flow-refresh", service.state.revision, 6), "equipment refresh")
expect(service.state.current_run.market_board.tide_disclosure == tide_before and service.state.current_run.market_board.battle_offers == routes_before, "refresh preserves tide and routes")
var recruit_offers: Array = Array(service.state.current_run.market_board.recruit_offers).duplicate(true)
for index in range(2):
var offer: Dictionary = recruit_offers[index]
apply(service, "flow-hire-%d" % index, func(): return service.hire("flow-hire-%d" % index, service.state.revision, String(offer.source_offer_id), int(offer.list_price)), "hire %d" % index)
expect(service.state.current_run.company.size() == 2 and service.state.current_run.deployed_recruit_ids.size() == 2, "two hires automatically form the line")
var auto_order: Array = Array(service.state.current_run.deployed_recruit_ids).duplicate()
var equipment: Dictionary = service.state.current_run.market_board.equipment_offers[0]
var purchase: Dictionary = apply(service, "flow-buy", func(): return service.buy_equipment("flow-buy", service.state.revision, String(equipment.offer_id), int(equipment.list_price)), "buy regional equipment")
var wearer_id := String(service.state.current_run.company[0])
apply(service, "flow-equip", func(): return service.equip("flow-equip", service.state.revision, wearer_id, String(purchase.receipt.instance_id)), "equip regional response")
expect(String(service.state.current_run.inventory[purchase.receipt.instance_id].catalog_id).begins_with("EQ-04"), "regional equipment replaces one starting item")
var manual_order: Array = auto_order.duplicate()
manual_order.reverse()
if manual_order != auto_order:
apply(service, "flow-order", func(): return service.commit_order("flow-order", service.state.revision, manual_order), "manual order")
expect(service.state.current_run.deployed_recruit_ids == manual_order, "manual order overrides automatic proposal")
var route: Dictionary = service.state.current_run.market_board.battle_offers[2]
apply(service, "flow-route", func(): return service.commit_route("flow-route", service.state.revision, String(route.offer_id), String(service.state.current_run.market_board.board_hash)), "route commit")
expect(service.state.current_run.phase == "prepared" and service.state.current_run.pending_encounter.route_id == "RO-R2-03", "high route is saved as prepared without executing battle")
func verify_atomic_boundaries() -> void:
var locked_snapshot: Dictionary = P100Market.new().state.snapshot()
var locked := State.new()
expect(not locked.initialize_from_p100(locked_snapshot), "locked Guild cannot become P10.1 state")
var service = migrated_service()
apply(service, "atomic-enter", func(): return service.begin_region_run("atomic-enter", service.state.revision, "standard"), "atomic entry")
var before: Dictionary = service.state.snapshot()
expect_rejected(service.begin_region_run("second-entry", service.state.revision, "standard"), service, before, "active Run", "region_run_active")
expect_rejected(service.refresh_equipment("wrong-cost", service.state.revision, 99), service, before, "refresh price mismatch", "refresh_cost_mismatch")
var recruit: Dictionary = service.state.current_run.market_board.recruit_offers[0]
expect_rejected(service.hire("wrong-price", service.state.revision, String(recruit.source_offer_id), int(recruit.list_price) + 1), service, before, "hire price mismatch", "price_mismatch")
var route: Dictionary = service.state.current_run.market_board.battle_offers[0]
expect_rejected(service.commit_route("route-too-early", service.state.revision, String(route.offer_id), String(service.state.current_run.market_board.board_hash)), service, before, "route before two hires", "two_recruits_required")
func migrated_service():
var state := State.new()
expect(state.initialize_from_p100(unlocked_p100_snapshot()), "valid Windglass closure migrates to P10.1 state")
return RegionService.new(state.snapshot())
func unlocked_p100_snapshot() -> Dictionary:
var base := P100Market.new()
var raw := base.state.snapshot()
raw.guild_profile.persistent_renown = 32
raw.guild_profile.contract_clear_ids = ["CLEAR-RG01-C01", "CLEAR-RG01-C02"]
raw.guild_profile.unlocked_region_ids = ["RG-01", "RG-02"]
expect(base.restore_snapshot(raw), "P10.0 unlocked Guild fixture validates")
return base.state.snapshot()
func apply(service, label: String, operation: Callable, message: String) -> Dictionary:
var revision_before := int(service.state.revision)
var result: Dictionary = operation.call()
expect(result.ok and service.state.revision == revision_before + 1, "%s applies exactly one revision: %s" % [message, str(result)])
if result.ok and service.state.revision == revision_before + 1:
applied_operations += 1
return result
func expect_rejected(result: Dictionary, service, before: Dictionary, label: String, code: String) -> void:
var accepted: bool = not result.ok and result.code == code and service.state.snapshot() == before
expect(accepted, "%s rejects as %s without mutation: %s" % [label, code, str(result)])
if accepted:
rejected_cases += 1
func expect(condition: bool, message: String) -> void:
if not condition:
failures.append("P10.1 Region entry/Market: %s" % message)
@@ -0,0 +1 @@
uid://c7m3x9q5h2v8n
+131
View File
@@ -0,0 +1,131 @@
extends SceneTree
const P100Market = preload("res://p10_0/market_service.gd")
const P100Save = preload("res://p10_0/save_service.gd")
const RegionService = preload("res://p10_1/region_market_service.gd")
const SaveV7 = preload("res://p10_1/save_v7_service.gd")
const SLOT_PATH := "/private/tmp/abg-p101-save-v7-test.json"
var failures: Array[String] = []
func _initialize() -> void:
call_deferred("run_test")
func run_test() -> void:
cleanup_files()
verify_v6_migration_and_roundtrip()
verify_checksum_backup_and_rollback()
verify_atomic_file_rotation_and_interruption()
verify_migration_boundaries()
cleanup_files()
if failures.is_empty():
print("ABG_P10_1_SAVE_V7_OK version=7 migration=v6_exact region_entry=true checksum=true active_backup=true rollback=true candidate_interruption=true receipts=idempotent offline=coin0,credit0,xp0,renown0,healing0,ticks0")
quit(0)
else:
for failure in failures:
push_error(failure)
quit(1)
func verify_v6_migration_and_roundtrip() -> void:
var v6 := encoded_v6(unlocked_p100_snapshot(), 6)
var saves := SaveV7.new()
var migrated := saves.migrate_v6_text(String(v6.text), 6)
expect(migrated.ok and migrated.sequence == 7 and migrated.previous_commit_hash == v6.envelope.commit_hash, "migration advances sequence and binds the v6 commit")
expect(migrated.snapshot.guild_profile.persistent_renown == 32 and "RG-02" in migrated.snapshot.guild_profile.unlocked_region_ids, "migration preserves exact Guild facts")
expect(migrated.snapshot.current_run.is_empty() and migrated.offline_delta == SaveV7.OFFLINE_ZERO, "migration invents no Run or offline value")
var decoded := saves.decode_text(String(migrated.text), 7)
expect(decoded.ok and decoded.snapshot == migrated.snapshot, "migrated Save v7 roundtrips byte-equivalent")
var region := RegionService.new(decoded.snapshot)
var entered := region.begin_region_run("save-entry", region.state.revision, "standard")
expect(entered.ok, "loaded Save enters Siltwake")
var encoded := saves.encode_snapshot(region.state.snapshot(), 8, String(decoded.commit_hash))
expect(encoded.ok, "active Market 1 encodes")
var loaded := saves.decode_text(String(encoded.text), 8)
var resumed := RegionService.new(loaded.snapshot)
var duplicate := resumed.begin_region_run("save-entry", 0, "standard")
expect(duplicate.ok and duplicate.duplicate and resumed.state.snapshot() == loaded.snapshot, "entry receipt survives reload and prevents a duplicate seed")
func verify_checksum_backup_and_rollback() -> void:
var saves := SaveV7.new()
var migrated := saves.migrate_v6_text(String(encoded_v6(unlocked_p100_snapshot(), 3).text))
var first := saves.encode_snapshot(migrated.snapshot, 4, String(migrated.envelope.previous_commit_hash))
var region := RegionService.new(migrated.snapshot)
expect(region.begin_region_run("newer-entry", region.state.revision, "wayfinder").ok, "newer fixture enters")
var second := saves.encode_snapshot(region.state.snapshot(), 5, String(first.envelope.commit_hash))
expect(first.ok and second.ok, "adjacent v7 commits encode")
var corrupt = JSON.parse_string(String(second.text))
corrupt.state.current_run.coin = 999
var fallback := saves.load_with_backup(JSON.stringify(corrupt), String(first.text), 4)
expect(fallback.ok and fallback.source == "backup" and fallback.active_failure == "checksum_mismatch", "corrupt active falls back to valid backup")
var rollback := saves.load_with_backup(String(first.text), "", 5)
expect(not rollback.ok and rollback.active_failure == "rollback_rejected", "minimum sequence rejects rollback")
var future = JSON.parse_string(String(second.text))
future.save_version = 8
var rejected := saves.decode_text(JSON.stringify(future))
expect(not rejected.ok and rejected.code == "save_version_unknown", "future Save blocks instead of resetting")
func verify_atomic_file_rotation_and_interruption() -> void:
var saves := SaveV7.new()
var migrated := saves.migrate_v6_text(String(encoded_v6(unlocked_p100_snapshot(), 0).text))
var first := saves.write_slot(SLOT_PATH, migrated.snapshot, 1)
expect(first.ok and FileAccess.file_exists(SLOT_PATH), "first write promotes verified candidate")
var region := RegionService.new(migrated.snapshot)
expect(region.begin_region_run("file-entry", 0, "stormbound").ok, "file fixture enters")
var second := saves.write_slot(SLOT_PATH, region.state.snapshot(), 2, String(first.commit_hash))
expect(second.ok and FileAccess.file_exists("%s.bak" % SLOT_PATH), "second write rotates active to backup")
var candidate := FileAccess.open("%s.candidate" % SLOT_PATH, FileAccess.WRITE)
candidate.store_string("interrupted partial bytes")
candidate.close()
var after_interruption := saves.load_slot(SLOT_PATH, 2)
expect(after_interruption.ok and after_interruption.sequence == 2 and after_interruption.snapshot.current_run.region_id == "RG-02", "orphan candidate never overrides committed active")
var active := FileAccess.open(SLOT_PATH, FileAccess.WRITE)
active.store_string("corrupt active")
active.close()
var backup := saves.load_slot(SLOT_PATH, 1)
expect(backup.ok and backup.source == "backup" and backup.sequence == 1, "corrupt active falls back to committed backup")
func verify_migration_boundaries() -> void:
var saves := SaveV7.new()
var locked := saves.migrate_v6_text(String(encoded_v6(P100Market.new().state.snapshot(), 1).text))
expect(not locked.ok and locked.code == "v6_region_locked", "locked v6 Guild cannot enter RG-02")
var active_market := P100Market.new()
expect(active_market.begin_run_creation("active-draft", 0, "CTR-R1-01", "standard").ok, "active v6 fixture creates a draft")
var active := saves.migrate_v6_text(String(encoded_v6(active_market.state.snapshot(), 1).text))
expect(not active.ok and active.code == "v6_active_run_not_migratable", "active v6 Run cannot be silently discarded")
var malformed := saves.migrate_v6_text("not-json")
expect(not malformed.ok and malformed.code == "v6_save_malformed", "malformed v6 save rejects explicitly")
func unlocked_p100_snapshot() -> Dictionary:
var base := P100Market.new()
var raw := base.state.snapshot()
raw.guild_profile.persistent_renown = 32
raw.guild_profile.contract_clear_ids = ["CLEAR-RG01-C01", "CLEAR-RG01-C02"]
raw.guild_profile.unlocked_region_ids = ["RG-01", "RG-02"]
expect(base.restore_snapshot(raw), "P10.0 unlocked Guild fixture validates")
return base.state.snapshot()
func encoded_v6(snapshot_value: Dictionary, sequence: int) -> Dictionary:
var encoded := P100Save.new().encode_snapshot(snapshot_value, sequence)
expect(encoded.ok, "v6 fixture encodes")
return encoded
func cleanup_files() -> void:
for path in [SLOT_PATH, "%s.bak" % SLOT_PATH, "%s.candidate" % SLOT_PATH]:
if FileAccess.file_exists(path):
DirAccess.remove_absolute(path)
func expect(condition: bool, message: String) -> void:
if not condition:
failures.append("P10.1 Save v7: %s" % message)
+1
View File
@@ -0,0 +1 @@
uid://d4r8n2m7q5v9h