feat(p9.8): add contract state and save v3

This commit is contained in:
2026-08-15 09:03:19 +08:00
parent e50c878d5f
commit e8b5817767
10 changed files with 1115 additions and 0 deletions
+166
View File
@@ -0,0 +1,166 @@
class_name P98ContractService
extends RefCounted
const Content = preload("res://content/p9_8_content.gd")
const State = preload("res://p9_8/contract_state.gd")
var content: Dictionary = Content.snapshot()
var state := State.new()
func _init(p97_snapshot: Dictionary = {}) -> void:
assert(Content.validate(content).ok)
if not p97_snapshot.is_empty():
assert(state.initialize_from_p97(p97_snapshot))
func choose_artifact(operation_id: String, artifact_id: String) -> Dictionary:
var intent := {"artifact_id": artifact_id, "draft_id": String(state.artifact_draft.get("id", ""))}
var prior := _prior_operation(operation_id, "choose_artifact", intent)
if prior.known:
return prior.result
if not state.p98_activated or state.phase != State.ContractPhase.MARKET or state.current_market != 8:
return _reject("artifact_market_required")
if not state.selected_artifact_id.is_empty():
return _reject("artifact_already_selected")
if artifact_id not in state.artifact_draft.get("offer_ids", []):
return _reject("artifact_not_offered")
state.selected_artifact_id = artifact_id
state.market_board = State.market_board_for(state.current_market, artifact_id)
state.available_recruit_offer_ids = _intersect(state.available_recruit_offer_ids, state.market_board.recruit_offer_ids)
state.available_equipment_offer_ids = _intersect(state.available_equipment_offer_ids, state.market_board.equipment_offer_ids)
var receipt := {
"index": state.artifact_receipts.size(),
"operation_id": operation_id,
"draft_id": String(state.artifact_draft.id),
"artifact_id": artifact_id,
"apply_from_market": int(state.artifact_draft.apply_from_market),
"board_hash": String(state.market_board.board_hash),
}
state.artifact_receipts.append(receipt)
return _commit_operation(operation_id, "choose_artifact", intent, "artifact_committed", receipt)
func open_promotion_draft(recruit_id := "") -> Dictionary:
if not state.p98_activated or state.phase != State.ContractPhase.MARKET:
return _reject("promotion_market_required")
var target_id := recruit_id if not recruit_id.is_empty() else state.first_eligible_promotion_recruit()
if target_id.is_empty() or target_id not in state.company:
return _reject("no_eligible_promotion")
var record: Dictionary = state.recruit_records[target_id]
if int(record.get("level", 0)) < 4 or int(record.get("survival_battles", 0)) < 3 or not String(record.get("promotion_id", "")).is_empty():
return _reject("promotion_ineligible")
var options := state.promotion_options(target_id)
if options.size() != 2:
return _reject("promotion_options_unavailable")
var draft := {
"id": "P98-PROMOTION-%s" % target_id,
"recruit_id": target_id,
"parent_profession_id": String(record.profession_id),
"offer_ids": options,
"level": int(record.level),
"survival_battles": int(record.survival_battles),
}
if state.promotion_draft == draft:
return _success("promotion_draft_already_open")
state.promotion_draft = draft
state.revision += 1
return _success("promotion_draft_opened")
func cancel_promotion_draft() -> Dictionary:
if state.promotion_draft.is_empty():
return _reject("promotion_draft_missing")
state.promotion_draft.clear()
state.revision += 1
return _success("promotion_draft_cancelled")
func confirm_promotion(operation_id: String, recruit_id: String, promotion_id: String) -> Dictionary:
var intent := {"recruit_id": recruit_id, "promotion_id": promotion_id, "draft_id": "P98-PROMOTION-%s" % recruit_id}
var prior := _prior_operation(operation_id, "confirm_promotion", intent)
if prior.known:
return prior.result
if not state.p98_activated or state.phase != State.ContractPhase.MARKET:
return _reject("promotion_market_required")
if String(state.promotion_draft.get("recruit_id", "")) != recruit_id:
return _reject("promotion_draft_required")
if promotion_id not in state.promotion_draft.get("offer_ids", []) or not content.promotions.has(promotion_id):
return _reject("promotion_not_offered")
if recruit_id not in state.company:
return _reject("promotion_target_missing")
var record: Dictionary = state.recruit_records[recruit_id]
if int(record.get("level", 0)) < 4 or int(record.get("survival_battles", 0)) < 3 or not String(record.get("promotion_id", "")).is_empty():
return _reject("promotion_ineligible")
var parent_id := String(record.profession_id)
if String(content.promotions[promotion_id].parent_id) != parent_id:
return _reject("promotion_parent_mismatch")
var hp_before := int(state.member_condition[recruit_id])
var equipment_before := String(state.equipped_by_recruit[recruit_id])
var company_index := state.company.find(recruit_id)
var deployed_index := state.deployed_recruit_ids.find(recruit_id)
state.recruit_records[recruit_id]["base_profession_id"] = parent_id
state.recruit_records[recruit_id]["profession_id"] = promotion_id
state.recruit_records[recruit_id]["promotion_id"] = promotion_id
state.recruit_records[recruit_id]["promotion_behavior"] = String(content.promotions[promotion_id].behavior)
state.promotion_draft.clear()
var receipt := {
"index": state.promotion_receipts.size(),
"operation_id": operation_id,
"recruit_id": recruit_id,
"parent_profession_id": parent_id,
"promotion_id": promotion_id,
"level": int(record.level),
"survival_battles": int(record.survival_battles),
"hp_before": hp_before,
"hp_after": int(state.member_condition[recruit_id]),
"equipment_instance_id": equipment_before,
"company_index": company_index,
"deployed_index": deployed_index,
}
state.promotion_receipts.append(receipt)
return _commit_operation(operation_id, "confirm_promotion", intent, "promotion_committed", receipt)
func board_preview(market_index: int, artifact_id := "") -> Dictionary:
var selected := artifact_id if not artifact_id.is_empty() else state.selected_artifact_id
return State.market_board_for(market_index, selected)
func _prior_operation(operation_id: String, kind: String, payload: Dictionary) -> Dictionary:
if operation_id.is_empty():
return {"known": true, "result": _reject("operation_id_required")}
if not state.operation_receipts.has(operation_id):
return {"known": false}
var stored: Dictionary = state.operation_receipts[operation_id]
if String(stored.intent_hash) != _intent_hash(kind, payload):
return {"known": true, "result": _reject("operation_id_conflict")}
return {"known": true, "result": {"ok": true, "code": "already_applied", "duplicate": true, "receipt": Dictionary(stored.receipt).duplicate(true), "snapshot": state.snapshot()}}
func _commit_operation(operation_id: String, kind: String, payload: Dictionary, code: String, receipt: Dictionary) -> Dictionary:
state.operation_receipts[operation_id] = {"intent_hash": _intent_hash(kind, payload), "kind": kind, "receipt": receipt.duplicate(true)}
state.revision += 1
assert(state.invariants_hold())
return _success(code, receipt)
func _intent_hash(kind: String, payload: Dictionary) -> String:
return JSON.stringify({"kind": kind, "payload": payload}).sha256_text()
func _intersect(values: Array, authority: Array) -> Array[String]:
var result: Array[String] = []
for value in values:
if value in authority:
result.append(String(value))
return result
func _success(code: String, receipt: Dictionary = {}) -> Dictionary:
assert(state.invariants_hold())
return {"ok": true, "code": code, "duplicate": false, "receipt": receipt.duplicate(true), "snapshot": state.snapshot()}
func _reject(code: String) -> Dictionary:
return {"ok": false, "code": code, "duplicate": false, "receipt": {}, "snapshot": state.snapshot()}
+1
View File
@@ -0,0 +1 @@
uid://d9x3m6q2v8k1b
+368
View File
@@ -0,0 +1,368 @@
class_name P98ContractState
extends "res://p9_7/market_state.gd"
const P97State = preload("res://p9_7/market_state.gd")
const P97Content = preload("res://content/p9_7_content.gd")
const P98Content = preload("res://content/p9_8_content.gd")
enum ContractPhase { MARKET, ENCOUNTER, BOSS_MUSTER, BOSS_ENCOUNTER, CONTRACT_RESULT, RUN_CLOSED }
var p98_activated := false
var artifact_draft: Dictionary = {}
var selected_artifact_id := ""
var artifact_receipts: Array[Dictionary] = []
var promotion_draft: Dictionary = {}
var promotion_receipts: Array[Dictionary] = []
var boss_muster: Dictionary = {}
var selected_boss_plan := ""
var pending_boss_result: Dictionary = {}
var boss_result_receipts: Array[Dictionary] = []
var persistent_renown := 0
var contract_clear_ids: Array[String] = []
var discovery_ids: Array[String] = []
var company_records: Array[Dictionary] = []
var run_closed := false
var close_receipts: Array[Dictionary] = []
func initialize_from_p97(raw: Dictionary) -> bool:
var prior = P97State.new()
if not prior.restore_snapshot(raw):
return false
if not _assign_snapshot(prior.snapshot()):
return false
_reset_contract_fields()
p98_activated = current_market == 8 and cleared_rounds == 7 and continuation_locked and relay_restored
if p98_activated:
var content: Dictionary = P98Content.snapshot()
content_revision = String(content.revision)
content_hash = String(content.content_hash)
continuation_locked = false
market_board = market_board_for(8, "")
available_recruit_offer_ids.assign(market_board.recruit_offer_ids)
available_equipment_offer_ids.assign(market_board.equipment_offer_ids)
available_battle_offer_ids.assign(market_board.battle_offer_ids)
artifact_draft = Dictionary(content.artifact_drafts["P98-ARTIFACT-DRAFT-1"]).duplicate(true)
_refresh_focus()
revision += 1
return invariants_hold()
func snapshot() -> Dictionary:
var result: Dictionary = super.snapshot()
result.merge({
"p98_activated": p98_activated,
"artifact_draft": artifact_draft.duplicate(true),
"selected_artifact_id": selected_artifact_id,
"artifact_receipts": artifact_receipts.duplicate(true),
"promotion_draft": promotion_draft.duplicate(true),
"promotion_receipts": promotion_receipts.duplicate(true),
"boss_muster": boss_muster.duplicate(true),
"selected_boss_plan": selected_boss_plan,
"pending_boss_result": pending_boss_result.duplicate(true),
"boss_result_receipts": boss_result_receipts.duplicate(true),
"persistent_renown": persistent_renown,
"contract_clear_ids": contract_clear_ids.duplicate(),
"discovery_ids": discovery_ids.duplicate(),
"company_records": company_records.duplicate(true),
"run_closed": run_closed,
"close_receipts": close_receipts.duplicate(true),
}, true)
return result.duplicate(true)
func restore_snapshot(raw: Dictionary) -> bool:
var normalized_value = _normalize_serialized(raw)
if not normalized_value is Dictionary:
return false
var normalized: Dictionary = normalized_value
var required := [
"p98_activated", "artifact_draft", "selected_artifact_id",
"artifact_receipts", "promotion_draft", "promotion_receipts",
"boss_muster", "selected_boss_plan", "pending_boss_result",
"boss_result_receipts", "persistent_renown", "contract_clear_ids",
"discovery_ids", "company_records", "run_closed", "close_receipts",
]
for key in required:
if not normalized.has(key):
return false
var before := snapshot()
if not _assign_snapshot(normalized) or not _assign_contract_fields(normalized) or not invariants_hold():
_assign_snapshot(before)
_assign_contract_fields(before)
return false
return true
func invariants_hold() -> bool:
if not p98_activated:
return super.invariants_hold() and _contract_fields_empty()
if revision < 0 or coin < 0 or phase < ContractPhase.MARKET or phase > ContractPhase.RUN_CLOSED:
return false
if cleared_rounds < 7 or cleared_rounds > 12:
return false
if line_capacity != P98Content.capacity_for_clears(cleared_rounds):
return false
if current_market != cleared_rounds + 1 or current_market < 8 or current_market > 13:
return false
if company.is_empty() and not run_closed:
return false
if not run_closed and (deployed_recruit_ids.is_empty() or deployed_recruit_ids.size() > line_capacity):
return false
if not _unique(company) or not _unique(deployed_recruit_ids) or not _unique(reserve_recruit_ids):
return false
if not _validate_company_collections():
return false
var content: Dictionary = P98Content.snapshot()
if content_revision != String(content.revision) or content_hash != String(content.content_hash):
return false
if phase in [ContractPhase.MARKET, ContractPhase.ENCOUNTER]:
if current_market > 12 or run_closed:
return false
var expected_board := market_board_for(current_market, selected_artifact_id)
if market_board != expected_board:
return false
if not _subset(available_recruit_offer_ids, market_board.recruit_offer_ids):
return false
if not _subset(available_equipment_offer_ids, market_board.equipment_offer_ids):
return false
if not _subset(available_battle_offer_ids, market_board.battle_offer_ids):
return false
if not focused_recruit_offer.is_empty() and focused_recruit_offer not in available_recruit_offer_ids:
return false
if not focused_equipment_offer.is_empty() and focused_equipment_offer not in available_equipment_offer_ids:
return false
if not focused_route_offer.is_empty() and focused_route_offer not in available_battle_offer_ids:
return false
if not selected_route.is_empty() and selected_route not in market_board.battle_offer_ids:
return false
if phase == ContractPhase.ENCOUNTER and (selected_route.is_empty() or battle_checkpoint.is_empty() or recovery_required):
return false
if phase == ContractPhase.MARKET and not selected_route.is_empty():
return false
if phase in [ContractPhase.BOSS_MUSTER, ContractPhase.BOSS_ENCOUNTER] and cleared_rounds != 12:
return false
if phase == ContractPhase.BOSS_MUSTER and (boss_muster.is_empty() or not selected_route.is_empty()):
return false
if phase == ContractPhase.BOSS_ENCOUNTER and (boss_muster.is_empty() or selected_boss_plan.is_empty() or battle_checkpoint.is_empty()):
return false
if phase == ContractPhase.CONTRACT_RESULT and pending_boss_result.is_empty():
return false
if phase == ContractPhase.RUN_CLOSED and not run_closed:
return false
if not _validate_new_decisions(content):
return false
if not _validate_recovery(content):
return false
if not pending_dismissal.is_empty():
var dismissal_target := String(pending_dismissal.get("recruit_id", ""))
if phase != ContractPhase.MARKET or dismissal_target not in company or company.size() <= 1:
return false
for receipts in [hire_receipts, purchase_receipts, equip_receipts, dismissal_receipts, deployment_receipts, route_receipts, battle_settlement_receipts, recovery_receipts, artifact_receipts, promotion_receipts, boss_result_receipts, close_receipts]:
if not _receipt_indices_hold(receipts):
return false
for operation_id in operation_receipts:
var operation = operation_receipts[operation_id]
if String(operation_id).is_empty() or not operation is Dictionary:
return false
if String(operation.get("intent_hash", "")).length() != 64 or not operation.get("receipt", {}) is Dictionary:
return false
if persistent_renown < 0 or not _unique(contract_clear_ids) or not _unique(discovery_ids):
return false
return true
func first_eligible_promotion_recruit() -> String:
for recruit_id in company:
var record: Dictionary = recruit_records.get(recruit_id, {})
if int(record.get("level", 0)) >= 4 and int(record.get("survival_battles", 0)) >= 3 and String(record.get("promotion_id", "")).is_empty():
var profession_id := String(record.get("profession_id", ""))
if profession_id in P98Content.BASE_PROFESSION_IDS:
return recruit_id
return ""
func promotion_options(recruit_id: String) -> Array[String]:
if recruit_id not in company:
return []
var parent_id := String(recruit_records[recruit_id].get("profession_id", ""))
var options: Array[String] = []
for promotion_id in P98Content.PROMOTIONS:
if String(P98Content.PROMOTIONS[promotion_id].parent_id) == parent_id:
options.append(String(promotion_id))
options.sort()
return options
static func market_board_for(market_index: int, artifact_id: String) -> Dictionary:
var content: Dictionary = P98Content.snapshot()
if not content.boards.has(market_index):
return {}
var source: Dictionary = content.boards[market_index]
var board := {
"id": String(source.id),
"market": market_index,
"recruit_offer_ids": Array(source.recruit_offer_ids).duplicate(),
"equipment_offer_ids": Array(source.equipment_offer_ids).duplicate(),
"battle_offer_ids": Array(source.battle_offer_ids).duplicate(),
"artifact_id": artifact_id,
"reserve_capacity_bonus": 0,
"reserve_upkeep_per_member": 0,
}
if market_index >= 9 and artifact_id == "AR-001":
board.recruit_offer_ids.append(String(source.extra_recruit_offer_id))
board.equipment_offer_ids.pop_back()
elif market_index >= 9 and artifact_id == "AR-002":
board.equipment_offer_ids.append(String(source.extra_equipment_offer_id))
board.recruit_offer_ids.pop_back()
elif market_index >= 9 and artifact_id == "AR-007":
board.reserve_capacity_bonus = 2
board.reserve_upkeep_per_member = 1
board["board_hash"] = JSON.stringify(board).sha256_text()
return board
func _assign_contract_fields(raw: Dictionary) -> bool:
for key in ["artifact_receipts", "promotion_receipts", "boss_result_receipts", "contract_clear_ids", "discovery_ids", "company_records", "close_receipts"]:
if not raw[key] is Array:
return false
for key in ["artifact_draft", "promotion_draft", "boss_muster", "pending_boss_result"]:
if not raw[key] is Dictionary:
return false
p98_activated = bool(raw.p98_activated)
artifact_draft = Dictionary(raw.artifact_draft).duplicate(true)
selected_artifact_id = String(raw.selected_artifact_id)
artifact_receipts.assign(raw.artifact_receipts)
promotion_draft = Dictionary(raw.promotion_draft).duplicate(true)
promotion_receipts.assign(raw.promotion_receipts)
boss_muster = Dictionary(raw.boss_muster).duplicate(true)
selected_boss_plan = String(raw.selected_boss_plan)
pending_boss_result = Dictionary(raw.pending_boss_result).duplicate(true)
boss_result_receipts.assign(raw.boss_result_receipts)
persistent_renown = int(raw.persistent_renown)
contract_clear_ids.assign(raw.contract_clear_ids)
discovery_ids.assign(raw.discovery_ids)
company_records.assign(raw.company_records)
run_closed = bool(raw.run_closed)
close_receipts.assign(raw.close_receipts)
return true
func _reset_contract_fields() -> void:
p98_activated = false
artifact_draft.clear()
selected_artifact_id = ""
artifact_receipts.clear()
promotion_draft.clear()
promotion_receipts.clear()
boss_muster.clear()
selected_boss_plan = ""
pending_boss_result.clear()
boss_result_receipts.clear()
persistent_renown = 0
contract_clear_ids.clear()
discovery_ids.clear()
company_records.clear()
run_closed = false
close_receipts.clear()
func _contract_fields_empty() -> bool:
return artifact_draft.is_empty() and selected_artifact_id.is_empty() and artifact_receipts.is_empty() and promotion_draft.is_empty() and promotion_receipts.is_empty() and boss_muster.is_empty() and selected_boss_plan.is_empty() and pending_boss_result.is_empty() and boss_result_receipts.is_empty() and persistent_renown == 0 and contract_clear_ids.is_empty() and discovery_ids.is_empty() and company_records.is_empty() and not run_closed and close_receipts.is_empty()
func _validate_company_collections() -> bool:
var expected_reserve: Array[String] = []
for recruit_id in company:
if not recruit_records.has(recruit_id) or not member_condition.has(recruit_id) or not equipped_by_recruit.has(recruit_id):
return false
if recruit_id not in deployed_recruit_ids:
expected_reserve.append(recruit_id)
if int(member_condition[recruit_id]) < 0:
return false
for recruit_id in deployed_recruit_ids:
if recruit_id not in company:
return false
if reserve_recruit_ids != expected_reserve:
return false
for recruit_id in recruit_records:
if recruit_id not in company:
return false
var profession_id := String(recruit_records[recruit_id].get("profession_id", ""))
if profession_id not in P98Content.BASE_PROFESSION_IDS and not P98Content.PROMOTIONS.has(profession_id):
return false
for recruit_id in member_condition:
if recruit_id not in company:
return false
var worn := {}
for recruit_id in equipped_by_recruit:
if recruit_id not in company:
return false
var instance_id := String(equipped_by_recruit[recruit_id])
if not instance_id.is_empty() and (not inventory.has(instance_id) or String(inventory[instance_id].get("wearer_id", "")) != recruit_id):
return false
for instance_id in inventory:
var item = inventory[instance_id]
if not item is Dictionary or String(item.get("instance_id", "")) != String(instance_id) or not _known_equipment(String(item.get("catalog_id", ""))):
return false
var wearer_id := String(item.get("wearer_id", ""))
if not wearer_id.is_empty():
if wearer_id not in company or String(equipped_by_recruit.get(wearer_id, "")) != instance_id or worn.has(instance_id):
return false
worn[instance_id] = true
return true
func _validate_new_decisions(content: Dictionary) -> bool:
if not artifact_draft.is_empty():
if String(artifact_draft.get("id", "")) != "P98-ARTIFACT-DRAFT-1" or artifact_draft != content.artifact_drafts["P98-ARTIFACT-DRAFT-1"]:
return false
if not selected_artifact_id.is_empty():
if artifact_receipts.size() != 1 or selected_artifact_id not in content.artifacts:
return false
if selected_artifact_id not in artifact_draft.get("offer_ids", []):
return false
if not promotion_draft.is_empty():
var recruit_id := String(promotion_draft.get("recruit_id", ""))
var offer_ids = promotion_draft.get("offer_ids", [])
if recruit_id not in company or not offer_ids is Array or offer_ids != promotion_options(recruit_id):
return false
for receipt in promotion_receipts:
var recruit_id := String(receipt.get("recruit_id", ""))
var promotion_id := String(receipt.get("promotion_id", ""))
if recruit_id not in company or not content.promotions.has(promotion_id) or String(recruit_records[recruit_id].get("profession_id", "")) != promotion_id:
return false
if not boss_muster.is_empty():
if String(boss_muster.get("boss_id", "")) != "BO-R1-01" or String(boss_muster.get("boss_hash", "")).length() != 64:
return false
if not selected_boss_plan.is_empty() and selected_boss_plan not in ["rotate", "brace"]:
return false
return true
func _validate_recovery(content: Dictionary) -> bool:
if recovery_required:
if phase not in [ContractPhase.MARKET, ContractPhase.BOSS_MUSTER] or recovery_kind not in ["defeat", "victory", "boss_defeat"] or recovery_cost <= 0 or injured_recruit_ids.is_empty():
return false
for recruit_id in injured_recruit_ids:
if recruit_id not in company or int(member_condition.get(recruit_id, 1)) > 0:
return false
else:
if not recovery_kind.is_empty() or recovery_cost != 0 or not injured_recruit_ids.is_empty():
return false
if not retry_route.is_empty() and not content.routes.has(retry_route):
return false
return true
func _refresh_focus() -> void:
focused_recruit_offer = ""
focused_equipment_offer = ""
focused_route_offer = ""
pending_dismissal.clear()
selected_route = ""
battle_checkpoint.clear()
func _known_equipment(catalog_id: String) -> bool:
return catalog_id in LEGACY_EQUIPMENT or P98Content.snapshot().equipment.has(catalog_id)
+1
View File
@@ -0,0 +1 @@
uid://c7n2q5m8v1x4a
+190
View File
@@ -0,0 +1,190 @@
class_name P98SaveService
extends RefCounted
const ContractState = preload("res://p9_8/contract_state.gd")
const P97State = preload("res://p9_7/market_state.gd")
const LegacyState = preload("res://p9_3/core_loop_state.gd")
const Rules = preload("res://domain/p9_2/battle_rules.gd")
const SAVE_VERSION := 3
const OFFLINE_CAP_SECONDS := 24 * 60 * 60
const DEFAULT_PATH := "user://aetherbound_p9_8_save.json"
var save_path := DEFAULT_PATH
func save_snapshot(snapshot: Dictionary, now_unix := -1) -> Dictionary:
var candidate = ContractState.new()
if not candidate.restore_snapshot(snapshot):
return {"ok": false, "code": "invalid_state"}
var saved_at := _now(now_unix)
var envelope := envelope_for_snapshot(candidate.snapshot(), SAVE_VERSION, saved_at)
var write_result := _atomic_write(JSON.stringify(envelope))
if not write_result.ok:
return write_result
return {"ok": true, "code": "saved", "version": SAVE_VERSION, "saved_at_unix": saved_at, "checksum": envelope.checksum}
func load_snapshot(now_unix := -1) -> Dictionary:
var primary := _load_path(save_path, now_unix)
if primary.ok:
return primary
var backup_path := save_path + ".bak"
if FileAccess.file_exists(backup_path):
var backup := _load_path(backup_path, now_unix)
if backup.ok:
backup.code = "backup_recovered"
backup.primary_error = primary.code
return backup
if primary.code == "missing":
return {"ok": false, "code": "no_save"}
return primary
func clear() -> Dictionary:
for path in [save_path, save_path + ".tmp", save_path + ".bak"]:
if FileAccess.file_exists(path):
var error := DirAccess.remove_absolute(_absolute(path))
if error != OK:
return {"ok": false, "code": "clear_failed", "error": error}
return {"ok": true, "code": "cleared"}
func envelope_for_snapshot(snapshot: Dictionary, version := SAVE_VERSION, saved_at_unix := -1) -> Dictionary:
var core := {"version": version, "saved_at_unix": _now(saved_at_unix), "state": snapshot.duplicate(true)}
var normalized = JSON.parse_string(JSON.stringify(core))
assert(normalized is Dictionary)
var envelope: Dictionary = Dictionary(normalized).duplicate(true)
envelope.checksum = _checksum(envelope)
return envelope
func _load_path(path: String, now_unix: int) -> Dictionary:
if not FileAccess.file_exists(path):
return {"ok": false, "code": "missing"}
var file := FileAccess.open(path, FileAccess.READ)
if file == null:
return {"ok": false, "code": "read_failed"}
var parser := JSON.new()
if parser.parse(file.get_as_text()) != OK or not parser.data is Dictionary:
return {"ok": false, "code": "malformed_json"}
var envelope: Dictionary = parser.data
for key in ["checksum", "version", "saved_at_unix", "state"]:
if not envelope.has(key):
return {"ok": false, "code": "malformed_envelope"}
var expected_checksum := String(envelope.checksum)
var core := envelope.duplicate(true)
core.erase("checksum")
if expected_checksum.is_empty() or expected_checksum.to_lower() != _checksum(core):
return {"ok": false, "code": "checksum_mismatch"}
if not envelope.state is Dictionary:
return {"ok": false, "code": "invalid_state"}
var version := int(envelope.version)
var candidate = ContractState.new()
var migrated := version != SAVE_VERSION
var battle_interrupted := false
if version == SAVE_VERSION:
if not candidate.restore_snapshot(Dictionary(envelope.state)):
return {"ok": false, "code": "invalid_state"}
if candidate.phase in [ContractState.ContractPhase.ENCOUNTER, ContractState.ContractPhase.BOSS_ENCOUNTER]:
var checkpoint = ContractState.new()
if candidate.battle_checkpoint.is_empty() or not checkpoint.restore_snapshot(candidate.battle_checkpoint):
return {"ok": false, "code": "invalid_battle_checkpoint"}
candidate = checkpoint
battle_interrupted = true
elif version == 2:
var prior = P97State.new()
if not prior.restore_snapshot(Dictionary(envelope.state)):
return {"ok": false, "code": "invalid_state"}
if prior.phase == P97State.Phase.ENCOUNTER:
var checkpoint = P97State.new()
if prior.battle_checkpoint.is_empty() or not checkpoint.restore_snapshot(prior.battle_checkpoint):
return {"ok": false, "code": "invalid_battle_checkpoint"}
prior = checkpoint
battle_interrupted = true
if not candidate.initialize_from_p97(prior.snapshot()):
return {"ok": false, "code": "invalid_state"}
elif version in [0, 1]:
var legacy_raw: Dictionary = Dictionary(envelope.state).duplicate(true)
if version == 0:
legacy_raw = _migrate_v0_to_v1(legacy_raw)
var legacy = LegacyState.new()
var prior = P97State.new()
if not legacy.restore_snapshot(legacy_raw) or not prior.initialize_from_p96(legacy.snapshot()) or not candidate.initialize_from_p97(prior.snapshot()):
return {"ok": false, "code": "invalid_state"}
else:
return {"ok": false, "code": "unsupported_version", "version": version}
var now := _now(now_unix)
var saved_at := int(envelope.saved_at_unix)
var rollback := now < saved_at
var elapsed := 0 if rollback else mini(OFFLINE_CAP_SECONDS, maxi(0, now - saved_at))
return {
"ok": true, "code": "loaded", "version": SAVE_VERSION,
"source_version": version, "migrated": migrated,
"p98_activated": candidate.p98_activated,
"battle_interrupted": battle_interrupted,
"snapshot": candidate.snapshot(), "saved_at_unix": saved_at,
"elapsed_seconds": elapsed, "clock_rollback": rollback,
"offline_coin": 0, "offline_xp": 0, "offline_healing": 0,
"offline_battle_ticks": 0,
}
func _migrate_v0_to_v1(raw: Dictionary) -> Dictionary:
var migrated := raw.duplicate(true)
var company: Array = migrated.get("company", ["Hearthguard"])
var condition := {}
for raw_member_id in company:
var member_id := String(raw_member_id)
condition[member_id] = int(Rules.member_definition(member_id).get("max_hp", 0))
migrated["member_condition"] = condition
migrated["rift_tide_plan"] = ""
migrated["rift_tide_wave"] = 0
migrated["rift_tide_wave_receipts"] = []
migrated["rift_tide_result_receipts"] = []
migrated["recovery_required"] = false
migrated["injured_members"] = []
migrated["recovery_receipts"] = []
return migrated
func _atomic_write(contents: String) -> Dictionary:
var absolute := _absolute(save_path)
var temporary := _absolute(save_path + ".tmp")
var backup := _absolute(save_path + ".bak")
var directory_error := DirAccess.make_dir_recursive_absolute(absolute.get_base_dir())
if directory_error != OK:
return {"ok": false, "code": "directory_failed", "error": directory_error}
if FileAccess.file_exists(save_path + ".tmp"):
DirAccess.remove_absolute(temporary)
var file := FileAccess.open(temporary, FileAccess.WRITE)
if file == null:
return {"ok": false, "code": "write_failed"}
file.store_string(contents)
file.flush()
file = null
if FileAccess.file_exists(save_path):
if FileAccess.file_exists(save_path + ".bak"):
DirAccess.remove_absolute(backup)
var backup_error := DirAccess.rename_absolute(absolute, backup)
if backup_error != OK:
DirAccess.remove_absolute(temporary)
return {"ok": false, "code": "backup_failed", "error": backup_error}
var promote_error := DirAccess.rename_absolute(temporary, absolute)
if promote_error != OK:
if FileAccess.file_exists(save_path + ".bak") and not FileAccess.file_exists(save_path):
DirAccess.rename_absolute(backup, absolute)
return {"ok": false, "code": "promote_failed", "error": promote_error}
return {"ok": true, "code": "written"}
func _checksum(core: Dictionary) -> String:
return JSON.stringify(core).sha256_text()
func _absolute(path: String) -> String:
return path if path.is_absolute_path() else ProjectSettings.globalize_path(path)
func _now(override: int) -> int:
return override if override >= 0 else int(Time.get_unix_time_from_system())
+1
View File
@@ -0,0 +1 @@
uid://b8m4q1v7x5n2c
+168
View File
@@ -0,0 +1,168 @@
extends SceneTree
const LegacyService = preload("res://p9_3/core_loop_service.gd")
const LegacyState = preload("res://p9_3/core_loop_state.gd")
const P97MarketService = preload("res://p9_7/market_service.gd")
const P97BattleService = preload("res://p9_7/battle_service.gd")
const State = preload("res://p9_8/contract_state.gd")
const Service = preload("res://p9_8/contract_service.gd")
var failures: Array[String] = []
func _initialize() -> void:
call_deferred("run_test")
func run_test() -> void:
var market8 := prepare_market8()
verify_activation(market8)
verify_artifact_transaction(market8)
verify_artifact_market_shapes(market8)
verify_promotion_transaction(market8)
verify_rejections_are_atomic(market8)
if failures.is_empty():
print("ABG_P9_8_CONTRACT_STATE_OK migration=p9.7_market8 artifact=AR-001,AR-002 apply=market9 shapes=4x3,2x5 promotion=level4+survival3 identity_hp_equipment_order=preserved operations=idempotent conflict=blocked invalid_mutations=0")
quit(0)
else:
for failure in failures:
push_error(failure)
quit(1)
func verify_activation(market8: Dictionary) -> void:
var state = State.new()
expect(state.initialize_from_p97(market8), "P9.7 Market 8 activates P9.8")
expect(state.p98_activated and state.current_market == 8 and state.cleared_rounds == 7, "activation preserves threshold and opens Market 8")
expect(not state.continuation_locked and state.relay_restored, "P9.7 continuation lock becomes playable without losing Relay")
expect(state.available_recruit_offer_ids.size() == 3 and state.available_equipment_offer_ids.size() == 4 and state.available_battle_offer_ids.size() == 3, "Market 8 has exact base shape")
expect(state.artifact_draft.offer_ids == ["AR-001", "AR-002"] and state.selected_artifact_id.is_empty(), "fixed Artifact draft is visible and unselected")
expect(state.company == market8.company and state.inventory == market8.inventory and state.member_condition == market8.member_condition, "Company, inventory and HP migrate exactly")
expect(state.route_history == market8.route_history and state.operation_receipts == market8.operation_receipts, "route and operation history migrate exactly")
expect(state.invariants_hold(), "activated state satisfies P9.8 invariants")
func verify_artifact_transaction(market8: Dictionary) -> void:
var service = Service.new(market8)
var before: Dictionary = service.state.snapshot()
var selected: Dictionary = service.choose_artifact("p98-artifact-ledger", "AR-001")
expect(selected.ok and selected.code == "artifact_committed", "Open Ledger commits")
expect(service.state.selected_artifact_id == "AR-001" and service.state.artifact_receipts.size() == 1, "Artifact selection writes one state and receipt")
expect(service.state.revision == int(before.revision) + 1, "Artifact commit increments one revision")
var after: Dictionary = service.state.snapshot()
var duplicate: Dictionary = service.choose_artifact("p98-artifact-ledger", "AR-001")
expect(duplicate.ok and duplicate.duplicate and service.state.snapshot() == after, "duplicate Artifact commit is inert")
var conflict: Dictionary = service.choose_artifact("p98-artifact-ledger", "AR-002")
expect(not conflict.ok and conflict.code == "operation_id_conflict" and service.state.snapshot() == after, "Artifact operation conflict is inert")
var second: Dictionary = service.choose_artifact("p98-artifact-second", "AR-002")
expect(not second.ok and second.code == "artifact_already_selected" and service.state.snapshot() == after, "a second Artifact cannot replace the committed rule")
func verify_artifact_market_shapes(market8: Dictionary) -> void:
var service = Service.new(market8)
var base: Dictionary = service.board_preview(9)
var recruit_wide: Dictionary = service.board_preview(9, "AR-001")
var item_wide: Dictionary = service.board_preview(9, "AR-002")
var bench: Dictionary = service.board_preview(9, "AR-007")
expect(base.recruit_offer_ids.size() == 3 and base.equipment_offer_ids.size() == 4, "base next Market is 3 Recruit and 4 equipment")
expect(recruit_wide.recruit_offer_ids.size() == 4 and recruit_wide.equipment_offer_ids.size() == 3, "Open Ledger exchanges one equipment slot for one Recruit")
expect(item_wide.recruit_offer_ids.size() == 2 and item_wide.equipment_offer_ids.size() == 5, "Toolwright exchanges one Recruit slot for one equipment")
expect(int(bench.reserve_capacity_bonus) == 2 and int(bench.reserve_upkeep_per_member) == 1, "Full Bench retains its catalog capacity/upkeep rule")
expect(base.board_hash != recruit_wide.board_hash and recruit_wide.board_hash != item_wide.board_hash, "Artifact board lineage is explicit")
func verify_promotion_transaction(market8: Dictionary) -> void:
var eligible := market8.duplicate(true)
eligible.recruit_records["Hearthguard"].level = 4
eligible.recruit_records["Hearthguard"].survival_battles = 7
var service = Service.new(eligible)
var company_before: Array[String] = service.state.company.duplicate()
var deployed_before: Array[String] = service.state.deployed_recruit_ids.duplicate()
var hp_before := int(service.state.member_condition.Hearthguard)
var equipment_before := String(service.state.equipped_by_recruit.Hearthguard)
var opened: Dictionary = service.open_promotion_draft("Hearthguard")
expect(opened.ok and service.state.promotion_draft.offer_ids == ["PF-A01", "PF-A02"], "eligible Hearthguard receives both canonical branches")
var before_confirm: Dictionary = service.state.snapshot()
var promoted: Dictionary = service.confirm_promotion("p98-promote-guard", "Hearthguard", "PF-A01")
expect(promoted.ok and promoted.code == "promotion_committed", "Gatebearer promotion commits")
expect(service.state.recruit_records.Hearthguard.profession_id == "PF-A01" and service.state.recruit_records.Hearthguard.base_profession_id == "PF-B01", "promotion preserves parent and changes grammar")
expect(service.state.company == company_before and service.state.deployed_recruit_ids == deployed_before, "promotion preserves Company and line order")
expect(int(service.state.member_condition.Hearthguard) == hp_before and String(service.state.equipped_by_recruit.Hearthguard) == equipment_before, "promotion preserves HP and equipment")
expect(service.state.revision == int(before_confirm.revision) + 1 and service.state.promotion_receipts.size() == 1, "promotion writes one revision and receipt")
var after: Dictionary = service.state.snapshot()
var duplicate: Dictionary = service.confirm_promotion("p98-promote-guard", "Hearthguard", "PF-A01")
expect(duplicate.ok and duplicate.duplicate and service.state.snapshot() == after, "duplicate promotion is inert")
var conflict: Dictionary = service.confirm_promotion("p98-promote-guard", "Hearthguard", "PF-A02")
expect(not conflict.ok and conflict.code == "operation_id_conflict" and service.state.snapshot() == after, "promotion operation conflict is inert")
func verify_rejections_are_atomic(market8: Dictionary) -> void:
var service = Service.new(market8)
var checks := [
func(): return service.choose_artifact("", "AR-001"),
func(): return service.choose_artifact("bad-artifact", "AR-007"),
func(): return service.open_promotion_draft("missing"),
func(): return service.confirm_promotion("bad-promotion", "Hearthguard", "PF-A01"),
]
for check in checks:
var before: Dictionary = service.state.snapshot()
var result: Dictionary = check.call()
expect(not result.ok and service.state.snapshot() == before, "invalid Contract operation preserves the complete snapshot")
func prepare_market8() -> Dictionary:
var market = P97MarketService.new(complete_p96())
for step in [
{"market": 5, "recruit": "P97-M5-R2", "route": "P97-R5-Q0"},
{"market": 6, "recruit": "P97-M6-R2", "route": "P97-R6-Q0"},
{"market": 7, "recruit": "P97-M7-R3", "route": "P97-R7-Q0"},
]:
market.focus_recruit_offer(String(step.recruit))
market.hire("p98-fixture-hire-%d" % int(step.market), String(step.recruit))
market.commit_deployment("p98-fixture-deploy-%d" % int(step.market), market.auto_order_candidate())
market.focus_route(String(step.route))
market.commit_route("p98-fixture-route-%d" % int(step.market), String(step.route))
var battle = P97BattleService.new()
battle.start_from_market(market.state)
var guard := 0
while not battle.state.terminal and guard < 2000:
battle.advance_ticks(1)
guard += 1
expect(guard < 2000 and battle.state.outcome == "victory", "fixture Round %d wins" % int(step.market))
market.settle_battle("p98-fixture-settle-%d" % int(step.market), battle.state.snapshot())
if market.state.recovery_required:
market.recover_injured_company("p98-fixture-recover-%d" % int(step.market))
expect(market.state.current_market == 8 and market.state.continuation_locked, "fixture reaches exact P9.7 Market 8")
return market.state.snapshot()
func complete_p96() -> Dictionary:
var service = LegacyService.new()
service.enter_hall()
service.focus_offer("Farstring")
service.hire("Farstring")
complete_legacy_battle(service, "open_road")
service.focus_offer("Kindhand")
service.hire("Kindhand")
complete_legacy_battle(service, "crosswind")
service.focus_equipment("EQ-002")
service.equip_focused("Hearthguard")
complete_legacy_battle(service, "bell_breach")
service.choose_rift_tide_plan("press_on")
complete_legacy_battle(service, "rift_tide")
return service.state.snapshot()
func complete_legacy_battle(service, encounter_id: String) -> void:
service.select_encounter(encounter_id)
service.start_battle()
var guard := 0
while service.state.phase == LegacyState.Phase.BATTLE and guard < 4000:
service.advance_battle_ticks(1)
guard += 1
service.claim_and_return()
func expect(condition: bool, message: String) -> void:
if not condition:
failures.append("P9.8 Contract state: %s" % message)
@@ -0,0 +1 @@
uid://e2v8m5q1x7k3c
+218
View File
@@ -0,0 +1,218 @@
extends SceneTree
const LegacyService = preload("res://p9_3/core_loop_service.gd")
const LegacyState = preload("res://p9_3/core_loop_state.gd")
const P97MarketService = preload("res://p9_7/market_service.gd")
const P97BattleService = preload("res://p9_7/battle_service.gd")
const State = preload("res://p9_8/contract_state.gd")
const Service = preload("res://p9_8/contract_service.gd")
const SaveService = preload("res://p9_8/save_service.gd")
var failures: Array[String] = []
var save_root := ""
func _initialize() -> void:
call_deferred("run_test")
func run_test() -> void:
save_root = OS.get_environment("ABG_P9_8_SAVE_TEST_ROOT")
if save_root.is_empty():
save_root = "/private/tmp/abg-p98-persistence-default"
DirAccess.make_dir_recursive_absolute(save_root)
var legacy := complete_p96()
var market8 := prepare_market8(legacy)
verify_v3_round_trip(market8)
verify_v2_market8_migration(market8)
verify_v1_and_v0_chain(legacy)
verify_interruption(market8)
verify_time_corruption_and_backup(market8)
if failures.is_empty():
print("ABG_P9_8_PERSISTENCE_OK version=3 migration=0,1,2_to_3 p97_market8=exact artifact_promotion=preserved interruption=pre_battle_market corruption=true backup=true rollback=true offline_cap=86400 offline_rewards=0 duplicate_after_reload=0 temp_clean=true")
quit(0)
else:
for failure in failures:
push_error(failure)
quit(1)
func verify_v3_round_trip(market8: Dictionary) -> void:
var eligible := market8.duplicate(true)
eligible.recruit_records.Hearthguard.level = 4
eligible.recruit_records.Hearthguard.survival_battles = 7
var service = Service.new(eligible)
service.choose_artifact("persist-artifact", "AR-002")
service.open_promotion_draft("Hearthguard")
service.confirm_promotion("persist-promotion", "Hearthguard", "PF-A02")
var saves = fresh_saves("v3")
var original: Dictionary = service.state.snapshot()
var saved: Dictionary = saves.save_snapshot(original, 1000)
expect(saved.ok and int(saved.version) == 3, "v3 state saves")
expect(not FileAccess.file_exists(saves.save_path + ".tmp"), "atomic write leaves no temp file")
var loaded: Dictionary = saves.load_snapshot(1060)
expect(loaded.ok and not loaded.migrated and loaded.snapshot == original, "v3 round trip is byte-stable")
expect(loaded.snapshot.selected_artifact_id == "AR-002" and loaded.snapshot.recruit_records.Hearthguard.profession_id == "PF-A02", "Artifact and promotion persist")
var restored = Service.new()
expect(restored.state.restore_snapshot(loaded.snapshot), "loaded v3 restores")
var before: Dictionary = restored.state.snapshot()
var duplicate: Dictionary = restored.choose_artifact("persist-artifact", "AR-002")
expect(duplicate.ok and duplicate.duplicate and restored.state.snapshot() == before, "reloaded operation remains idempotent")
expect(int(loaded.elapsed_seconds) == 60 and int(loaded.offline_coin) == 0 and int(loaded.offline_xp) == 0, "elapsed time grants no progress")
func verify_v2_market8_migration(market8: Dictionary) -> void:
var saves = fresh_saves("v2")
write_json(saves.save_path, saves.envelope_for_snapshot(market8, 2, 2000))
var loaded: Dictionary = saves.load_snapshot(2010)
expect(loaded.ok and loaded.migrated and int(loaded.source_version) == 2 and loaded.p98_activated, "v2 Market 8 activates P9.8")
expect(loaded.snapshot.company == market8.company and loaded.snapshot.inventory == market8.inventory and loaded.snapshot.member_condition == market8.member_condition, "v2 migration preserves Company, inventory and HP")
expect(loaded.snapshot.route_history == market8.route_history and loaded.snapshot.operation_receipts == market8.operation_receipts, "v2 migration preserves exact receipts")
expect(loaded.snapshot.market_board.recruit_offer_ids.size() == 3 and loaded.snapshot.artifact_draft.offer_ids == ["AR-001", "AR-002"], "v2 migration opens deterministic Market 8")
func verify_v1_and_v0_chain(legacy: Dictionary) -> void:
var v1 = fresh_saves("v1")
write_json(v1.save_path, v1.envelope_for_snapshot(legacy, 1, 2100))
var loaded_v1: Dictionary = v1.load_snapshot(2110)
expect(loaded_v1.ok and loaded_v1.migrated and not loaded_v1.p98_activated, "v1 follows adjacent migration into preserved Market 5")
expect(int(loaded_v1.snapshot.current_market) == 5 and loaded_v1.snapshot.content_revision == "p9.7-content-r1", "pre-P9.8 migration retains P9.7 authority")
var legacy_v0 := legacy.duplicate(true)
for key in ["member_condition", "rift_tide_plan", "rift_tide_wave", "rift_tide_wave_receipts", "rift_tide_result_receipts", "recovery_required", "injured_members", "recovery_receipts"]:
legacy_v0.erase(key)
var v0 = fresh_saves("v0")
write_json(v0.save_path, v0.envelope_for_snapshot(legacy_v0, 0, 2200))
var loaded_v0: Dictionary = v0.load_snapshot(2210)
expect(loaded_v0.ok and loaded_v0.migrated and int(loaded_v0.source_version) == 0, "v0 follows adjacent migration chain")
expect(loaded_v0.snapshot.member_condition == {"Hearthguard": 130, "Farstring": 85, "Kindhand": 90}, "v0 migration supplies safe condition")
func verify_interruption(market8: Dictionary) -> void:
var state = State.new()
expect(state.initialize_from_p97(market8), "interruption fixture activates")
var checkpoint: Dictionary = state.snapshot()
var encounter := checkpoint.duplicate(true)
encounter.phase = State.ContractPhase.ENCOUNTER
encounter.selected_route = "P98-R8-Q0"
encounter.route_history.append("P98-R8-Q0")
encounter.battle_checkpoint = checkpoint
var encounter_state = State.new()
expect(encounter_state.restore_snapshot(encounter), "active P9.8 encounter fixture restores")
var saves = fresh_saves("encounter")
expect(saves.save_snapshot(encounter_state.snapshot(), 2500).ok, "active encounter saves")
var loaded: Dictionary = saves.load_snapshot(2510)
expect(loaded.ok and loaded.battle_interrupted and loaded.snapshot == checkpoint, "interruption restores exact pre-battle Market")
func verify_time_corruption_and_backup(market8: Dictionary) -> void:
var service = Service.new(market8)
var rollback = fresh_saves("rollback")
expect(rollback.save_snapshot(service.state.snapshot(), 3000).ok, "rollback fixture writes")
var rolled: Dictionary = rollback.load_snapshot(2900)
expect(rolled.ok and rolled.clock_rollback and int(rolled.elapsed_seconds) == 0, "clock rollback is inert")
var capped: Dictionary = rollback.load_snapshot(999999)
expect(capped.ok and int(capped.elapsed_seconds) == SaveService.OFFLINE_CAP_SECONDS, "offline duration is capped")
var malformed = fresh_saves("malformed")
write_text(malformed.save_path, "{")
expect(not malformed.load_snapshot(4000).ok and malformed.load_snapshot(4000).code == "malformed_json", "malformed JSON is rejected")
var checksum = fresh_saves("checksum")
var bad_checksum: Dictionary = checksum.envelope_for_snapshot(service.state.snapshot(), 3, 4000)
bad_checksum.checksum = "0".repeat(64)
write_json(checksum.save_path, bad_checksum)
expect(not checksum.load_snapshot(4001).ok and checksum.load_snapshot(4001).code == "checksum_mismatch", "checksum drift is rejected")
var unknown = fresh_saves("unknown")
write_json(unknown.save_path, unknown.envelope_for_snapshot(service.state.snapshot(), 99, 4000))
expect(not unknown.load_snapshot(4001).ok and unknown.load_snapshot(4001).code == "unsupported_version", "unknown version is rejected")
var invalid = fresh_saves("invalid")
var invalid_state: Dictionary = service.state.snapshot()
invalid_state.coin = -1
write_json(invalid.save_path, invalid.envelope_for_snapshot(invalid_state, 3, 4000))
expect(not invalid.load_snapshot(4001).ok and invalid.load_snapshot(4001).code == "invalid_state", "valid-checksum invalid state is rejected")
var backup = fresh_saves("backup")
var first: Dictionary = service.state.snapshot()
expect(backup.save_snapshot(first, 5000).ok, "backup first save writes")
service.choose_artifact("backup-artifact", "AR-001")
var second: Dictionary = service.state.snapshot()
expect(backup.save_snapshot(second, 5010).ok and FileAccess.file_exists(backup.save_path + ".bak"), "second save retains backup")
write_text(backup.save_path, "broken")
var recovered: Dictionary = backup.load_snapshot(5020)
expect(recovered.ok and recovered.code == "backup_recovered" and recovered.primary_error == "malformed_json", "corrupt primary falls back explicitly")
expect(recovered.snapshot == first and recovered.snapshot != second, "backup restores previous complete state")
func prepare_market8(legacy: Dictionary) -> Dictionary:
var market = P97MarketService.new(legacy)
for step in [
{"market": 5, "recruit": "P97-M5-R2", "route": "P97-R5-Q0"},
{"market": 6, "recruit": "P97-M6-R2", "route": "P97-R6-Q0"},
{"market": 7, "recruit": "P97-M7-R3", "route": "P97-R7-Q0"},
]:
market.focus_recruit_offer(String(step.recruit))
market.hire("persist-hire-%d" % int(step.market), String(step.recruit))
market.commit_deployment("persist-deploy-%d" % int(step.market), market.auto_order_candidate())
market.focus_route(String(step.route))
market.commit_route("persist-route-%d" % int(step.market), String(step.route))
var battle = P97BattleService.new()
battle.start_from_market(market.state)
var guard := 0
while not battle.state.terminal and guard < 2000:
battle.advance_ticks(1)
guard += 1
market.settle_battle("persist-settle-%d" % int(step.market), battle.state.snapshot())
if market.state.recovery_required:
market.recover_injured_company("persist-recover-%d" % int(step.market))
return market.state.snapshot()
func fresh_saves(name: String):
var saves = SaveService.new()
saves.save_path = save_root.path_join(name + ".json")
saves.clear()
return saves
func complete_p96() -> Dictionary:
var service = LegacyService.new()
service.enter_hall()
service.focus_offer("Farstring")
service.hire("Farstring")
complete_legacy_battle(service, "open_road")
service.focus_offer("Kindhand")
service.hire("Kindhand")
complete_legacy_battle(service, "crosswind")
service.focus_equipment("EQ-002")
service.equip_focused("Hearthguard")
complete_legacy_battle(service, "bell_breach")
service.choose_rift_tide_plan("press_on")
complete_legacy_battle(service, "rift_tide")
return service.state.snapshot()
func complete_legacy_battle(service, encounter_id: String) -> void:
service.select_encounter(encounter_id)
service.start_battle()
var guard := 0
while service.state.phase == LegacyState.Phase.BATTLE and guard < 4000:
service.advance_battle_ticks(1)
guard += 1
service.claim_and_return()
func write_json(path: String, value: Dictionary) -> void:
write_text(path, JSON.stringify(value))
func write_text(path: String, value: String) -> void:
var file := FileAccess.open(path, FileAccess.WRITE)
expect(file != null, "fixture opens %s" % path)
if file != null:
file.store_string(value)
file.flush()
func expect(condition: bool, message: String) -> void:
if not condition:
failures.append("P9.8 persistence: %s" % message)
@@ -0,0 +1 @@
uid://f6q2n8v4m1x7c