feat(runtime): add P10.3 growth persistence

This commit is contained in:
2026-08-16 09:57:28 +08:00
parent 4f3dbe52fd
commit 26ef043bfb
16 changed files with 1639 additions and 0 deletions
@@ -0,0 +1,98 @@
class_name P103DeepChannelsFixture
extends RefCounted
const P102Fixture = preload("res://tests/p10_2/mid_contract_fixture.gd")
const SaveV8 = preload("res://p10_2/save_v8_service.gd")
const BoardService = preload("res://p10_3/market_board_service.gd")
const GrowthService = preload("res://p10_3/growth_service.gd")
const SaveV9 = preload("res://p10_3/save_v9_service.gd")
const State = preload("res://p10_3/run_state.gd")
func p102_market_5_snapshot() -> Dictionary:
var service = P102Fixture.new().market_service_at(5)
return service.state.snapshot() if service != null else {}
func encoded_v8(sequence: int = 20) -> Dictionary:
return SaveV8.new().encode_snapshot(p102_market_5_snapshot(), sequence)
func migrated_snapshot(sequence: int = 20) -> Dictionary:
var source := encoded_v8(sequence)
if not source.ok:
return {}
var migrated := SaveV9.new().migrate_v8_text(String(source.text), sequence)
return migrated.snapshot if migrated.ok else {}
func market_7_snapshot(eligible: bool = true) -> Dictionary:
var raw := migrated_snapshot()
if raw.is_empty():
return {}
var generated := BoardService.new().generate(String(raw.current_run.run_seed), 7, 0)
if not generated.ok:
return {}
var run: Dictionary = raw.current_run
run.phase = "market"
run.market_index = 7
run.round_index = 7
run.cleared_rounds = 6
run.line_capacity = 7
run.refresh_count = 0
run.market_board = Dictionary(generated.board).duplicate(true)
run.available_recruit_offer_ids = _offer_ids(generated.board.recruit_offers, "source_offer_id")
run.available_equipment_offer_ids = _offer_ids(generated.board.equipment_offers, "offer_id")
run.available_battle_offer_ids = _offer_ids(generated.board.battle_offers, "offer_id")
run.locked_offer_ids = []
run.selected_route_id = ""
run.pending_encounter = {}
run.pre_battle_checkpoint_id = ""
run.recovery_required = false
run.recovery_cost = 0
for round_index in [5, 6]:
run.route_history.append({
"round_index": round_index,
"route_id": "RO-R2-M%02d-Q0" % round_index,
"plan_id": "fixture_only",
"outcome": "victory",
"battle_hash": "%s|%d" % [run.run_seed, round_index],
"reward_coin": 18 + 2 * round_index + 2,
})
run.artifact_draft = GrowthService.artifact_draft_for(String(run.run_seed))
run.active_artifact_ids = []
run.artifact_rule_state = {}
run.promotion_draft = {}
var candidate_id := ""
for recruit_id in run.company:
var record: Dictionary = run.recruit_records[recruit_id]
record.level = mini(int(record.level), 3)
record.survived_battles = mini(int(record.survived_battles), 2)
if String(record.profession_id) == "PF-B07" and candidate_id.is_empty():
candidate_id = String(recruit_id)
run.recruit_records[recruit_id] = record
if eligible:
if candidate_id.is_empty():
return {}
var candidate: Dictionary = run.recruit_records[candidate_id]
candidate.level = 4
candidate.xp = 8
candidate.survived_battles = 3
candidate.current_hp = maxi(1, int(floor(float(candidate.max_hp) * 0.5)))
candidate.custom_history_probe = ["round-1", "round-3", "round-6"]
run.recruit_records[candidate_id] = candidate
raw.current_run = run
var probe := State.new()
return probe.snapshot() if probe.restore_snapshot(raw) else {}
func growth_service(eligible: bool = true):
var snapshot_value := market_7_snapshot(eligible)
return GrowthService.new(snapshot_value) if not snapshot_value.is_empty() else null
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
@@ -0,0 +1 @@
uid://bsp103fixture
+143
View File
@@ -0,0 +1,143 @@
extends SceneTree
const Growth = preload("res://p10_3/growth_service.gd")
const SaveV9 = preload("res://p10_3/save_v9_service.gd")
const Fixture = preload("res://tests/p10_3/deep_channels_fixture.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_profession_tree()
verify_artifact_choices()
verify_artifact_defer_and_reload()
verify_promotion_defer_reload_and_confirm()
verify_atomic_boundaries()
if failures.is_empty():
print("ABG_P10_3_GROWTH_CHOICES_OK artifacts=AR-011,AR-012,AR-015 capacities=6,8,7 artifact_defer_resume=true professions=12x2 first_eligible=PF-B07 options=PF-A13,PF-A14 promotion_defer_resume=true identity_hp_trait_item_order_history=preserved receipts=exact applied=%d rejected=%d" % [applied_operations, rejected_cases])
quit(0)
else:
for failure in failures:
push_error(failure)
quit(1)
func verify_profession_tree() -> void:
var mapping := Growth.profession_descendants()
expect(mapping.size() == 12, "all twelve base Profession families are present")
expect(Growth.artifact_draft_for("bad-seed").is_empty(), "malformed Run seed cannot create an Artifact draft")
for base_index in range(1, 13):
var base_id := "PF-B%02d" % base_index
var expected := ["PF-A%02d" % (2 * base_index - 1), "PF-A%02d" % (2 * base_index)]
expect(mapping.get(base_id, []) == expected, "%s has exact regular descendants %s" % [base_id, str(expected)])
func verify_artifact_choices() -> void:
var expected_capacities := {"AR-011": 6, "AR-012": 8, "AR-015": 7}
for artifact_id in Growth.ARTIFACT_IDS:
var service = Fixture.new().growth_service()
expect(service != null and service.valid, "%s fixture is valid" % artifact_id)
var draft: Dictionary = service.artifact_draft().receipt
expect(draft.offer_ids == Growth.ARTIFACT_IDS and String(draft.draft_hash).length() == 64, "%s sees the exact stable draft" % artifact_id)
var revision_before := int(service.state.revision)
var selected := apply(service, "select-%s" % artifact_id, func(): return service.select_artifact("select-%s" % artifact_id, revision_before, String(draft.draft_hash), artifact_id), "select %s" % artifact_id)
expect(selected.ok and service.state.current_run.active_artifact_ids == [artifact_id], "%s becomes the sole Run rule" % artifact_id)
expect(service.state.current_run.line_capacity == 7 and service.effective_line_capacity() == expected_capacities[artifact_id], "%s changes only effective capacity" % artifact_id)
var after: Dictionary = service.state.snapshot()
var duplicate: Dictionary = service.select_artifact("select-%s" % artifact_id, revision_before, String(draft.draft_hash), artifact_id)
expect(duplicate.ok and duplicate.duplicate and service.state.snapshot() == after, "%s retry returns one stored receipt" % artifact_id)
expect_rejected(service.select_artifact("second-%s" % artifact_id, service.state.revision, String(draft.draft_hash), "AR-012" if artifact_id != "AR-012" else "AR-011"), service, after, "%s conflicting second Artifact" % artifact_id, "artifact_already_selected")
func verify_artifact_defer_and_reload() -> void:
var service = Fixture.new().growth_service()
var draft: Dictionary = service.artifact_draft().receipt
apply(service, "defer-artifact", func(): return service.defer_artifact("defer-artifact", service.state.revision, String(draft.draft_hash)), "defer Artifact")
expect(service.state.current_run.artifact_draft.status == "deferred" and service.state.current_run.artifact_draft.offer_ids == Growth.ARTIFACT_IDS, "deferral preserves the exact Artifact draft")
expect(service.route_growth_ready().receipt.ready, "explicit Artifact deferral unblocks a Round-7 route")
var encoded := SaveV9.new().encode_snapshot(service.state.snapshot(), 30)
var decoded := SaveV9.new().decode_text(String(encoded.text), 30)
expect(decoded.ok and decoded.snapshot.current_run.artifact_draft == service.state.current_run.artifact_draft, "deferred Artifact survives Save v9 reload")
var resumed = Growth.new(decoded.snapshot)
apply(resumed, "resume-artifact", func(): return resumed.select_artifact("resume-artifact", resumed.state.revision, String(draft.draft_hash), "AR-015"), "resume deferred Artifact")
expect(resumed.state.current_run.active_artifact_ids == ["AR-015"] and resumed.effective_line_capacity() == 7, "deferred Artifact can later be selected without redraw")
func verify_promotion_defer_reload_and_confirm() -> void:
var service = Fixture.new().growth_service()
var artifact_hash := String(service.artifact_draft().receipt.draft_hash)
apply(service, "promotion-artifact-defer", func(): return service.defer_artifact("promotion-artifact-defer", service.state.revision, artifact_hash), "defer Artifact before promotion")
var opened := apply(service, "open-promotion", func(): return service.open_promotion_draft("open-promotion", service.state.revision), "open first eligible promotion")
var draft: Dictionary = opened.receipt.draft
expect(draft.current_profession_id == "PF-B07" and draft.option_ids == ["PF-A13", "PF-A14"], "first eligible Kindhand receives Fieldmender and Aftercare")
var recruit_id := String(draft.recruit_id)
var before_record: Dictionary = service.state.current_run.recruit_records[recruit_id].duplicate(true)
var company_before: Array = Array(service.state.current_run.company).duplicate()
var deployed_before: Array = Array(service.state.current_run.deployed_recruit_ids).duplicate()
var reserve_before: Array = Array(service.state.current_run.reserve_recruit_ids).duplicate()
var item_before := String(service.state.current_run.equipped_by_recruit[recruit_id])
apply(service, "defer-promotion", func(): return service.defer_promotion("defer-promotion", service.state.revision, String(draft.draft_hash)), "defer promotion")
var encoded := SaveV9.new().encode_snapshot(service.state.snapshot(), 31)
var decoded := SaveV9.new().decode_text(String(encoded.text), 31)
expect(decoded.ok and decoded.snapshot.current_run.promotion_draft.status == "deferred", "deferred promotion survives Save v9 reload")
var resumed = Growth.new(decoded.snapshot)
var promoted := apply(resumed, "confirm-promotion", func(): return resumed.confirm_promotion("confirm-promotion", resumed.state.revision, String(draft.draft_hash), recruit_id, "PF-B07", "PF-A14"), "confirm Aftercare")
var after_record: Dictionary = resumed.state.current_run.recruit_records[recruit_id]
expect(promoted.ok and after_record.profession_id == "PF-A14" and after_record.origin_profession_id == "PF-B07", "promotion changes only current Profession authority")
expect(after_record.recruit_id == before_record.recruit_id and after_record.trait_id == before_record.trait_id, "promotion preserves Recruit ID and Trait")
expect(after_record.level == before_record.level and after_record.xp == before_record.xp and after_record.current_hp == before_record.current_hp and after_record.max_hp == before_record.max_hp, "promotion preserves level, XP and exact HP ratio")
expect(resumed.state.current_run.equipped_by_recruit[recruit_id] == item_before and after_record.custom_history_probe == before_record.custom_history_probe, "promotion preserves equipment and history")
expect(resumed.state.current_run.company == company_before and resumed.state.current_run.deployed_recruit_ids == deployed_before and resumed.state.current_run.reserve_recruit_ids == reserve_before, "promotion preserves stable Company/Line/Reserve order")
var final_state: Dictionary = resumed.state.snapshot()
expect_rejected(resumed.confirm_promotion("promote-twice", resumed.state.revision, String(draft.draft_hash), recruit_id, "PF-A14", "PF-A13"), resumed, final_state, "second permanent promotion", "promotion_already_selected")
func verify_atomic_boundaries() -> void:
var pending = Fixture.new().growth_service()
var pending_before: Dictionary = pending.state.snapshot()
expect_rejected(pending.open_promotion_draft("blocked-promotion", pending.state.revision), pending, pending_before, "promotion before Artifact decision", "artifact_decision_required")
var draft_hash := String(pending.artifact_draft().receipt.draft_hash)
expect_rejected(pending.select_artifact("", pending.state.revision, draft_hash, "AR-011"), pending, pending_before, "empty operation ID", "operation_id_required")
expect_rejected(pending.select_artifact("bad-artifact", pending.state.revision, draft_hash, "AR-999"), pending, pending_before, "unknown Artifact", "artifact_unavailable")
expect_rejected(pending.defer_artifact("bad-hash", pending.state.revision, "0".repeat(64)), pending, pending_before, "wrong Artifact draft hash", "artifact_draft_hash_mismatch")
var no_candidate = Fixture.new().growth_service(false)
var no_candidate_hash := String(no_candidate.artifact_draft().receipt.draft_hash)
apply(no_candidate, "no-candidate-defer", func(): return no_candidate.defer_artifact("no-candidate-defer", no_candidate.state.revision, no_candidate_hash), "defer Artifact without eligible Recruit")
var no_candidate_before: Dictionary = no_candidate.state.snapshot()
expect_rejected(no_candidate.open_promotion_draft("no-candidate", no_candidate.state.revision), no_candidate, no_candidate_before, "no eligible promotion", "promotion_not_eligible")
var wrong_option = Fixture.new().growth_service()
var wrong_hash := String(wrong_option.artifact_draft().receipt.draft_hash)
apply(wrong_option, "wrong-option-defer", func(): return wrong_option.defer_artifact("wrong-option-defer", wrong_option.state.revision, wrong_hash), "defer Artifact for wrong-option fixture")
var opened := apply(wrong_option, "wrong-option-open", func(): return wrong_option.open_promotion_draft("wrong-option-open", wrong_option.state.revision), "open wrong-option fixture")
var promotion: Dictionary = opened.receipt.draft
var wrong_before: Dictionary = wrong_option.state.snapshot()
expect_rejected(wrong_option.confirm_promotion("wrong-option", wrong_option.state.revision, String(promotion.draft_hash), String(promotion.recruit_id), String(promotion.current_profession_id), "PF-H01"), wrong_option, wrong_before, "hidden hybrid selection", "promotion_option_unavailable")
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.3 growth choices: %s" % message)
@@ -0,0 +1 @@
uid://bsp103growthtest
+139
View File
@@ -0,0 +1,139 @@
extends SceneTree
const SaveV8 = preload("res://p10_2/save_v8_service.gd")
const SaveV9 = preload("res://p10_3/save_v9_service.gd")
const Fixture = preload("res://tests/p10_3/deep_channels_fixture.gd")
const SLOT_PATH := "/private/tmp/abg-p103-save-v9-test.json"
var failures: Array[String] = []
func _initialize() -> void:
call_deferred("run_test")
func run_test() -> void:
cleanup_files()
verify_exact_v8_migration_and_roundtrip()
verify_checksum_backup_and_rollback()
verify_atomic_file_rotation_and_interruption()
verify_migration_boundaries()
verify_state_corruption_boundaries()
cleanup_files()
if failures.is_empty():
print("ABG_P10_3_SAVE_V9_OK version=9 migration=v8_market5_exact board=3,4,3 cleared=4 capacity=6 company=true route_history=4 artifact_state=true promotion_state=true checksum=true active_backup=true rollback=true candidate_interruption=true legacy_receipts=true offline=coin0,credit0,xp0,renown0,healing0,ticks0")
quit(0)
else:
for failure in failures:
push_error(failure)
quit(1)
func verify_exact_v8_migration_and_roundtrip() -> void:
var fixture = Fixture.new()
var source_snapshot: Dictionary = fixture.p102_market_5_snapshot()
var v8 := SaveV8.new().encode_snapshot(source_snapshot, 20)
expect(v8.ok, "stable Market 5 fixture encodes as Save v8")
var saves := SaveV9.new()
var migrated := saves.migrate_v8_text(String(v8.text), 20)
expect(migrated.ok and migrated.sequence == 21 and migrated.previous_commit_hash == v8.envelope.commit_hash, "migration advances sequence and binds the v8 commit")
expect(migrated.snapshot.current_run.run_id == source_snapshot.current_run.run_id and migrated.snapshot.current_run.run_seed == source_snapshot.current_run.run_seed, "migration preserves exact Run identity")
expect(migrated.snapshot.current_run.company == source_snapshot.current_run.company and migrated.snapshot.current_run.coin == source_snapshot.current_run.coin, "migration preserves Company and Coin")
expect(migrated.snapshot.current_run.inventory == source_snapshot.current_run.inventory and migrated.snapshot.current_run.equipped_by_recruit == source_snapshot.current_run.equipped_by_recruit, "migration preserves equipment ownership")
expect(migrated.snapshot.current_run.market_index == 5 and migrated.snapshot.current_run.phase == "market" and migrated.snapshot.current_run.cleared_rounds == 4, "migration opens exact deep-channel Market 5")
expect(migrated.snapshot.current_run.line_capacity == 6 and migrated.snapshot.current_run.market_board.recruit_offers.size() == 3 and migrated.snapshot.current_run.market_board.equipment_offers.size() == 4 and migrated.snapshot.current_run.market_board.battle_offers.size() == 3, "migration binds exact capacity and 3/4/3 board")
expect(migrated.snapshot.current_run.route_history == source_snapshot.current_run.route_history, "four completed routes remain byte-equivalent")
expect(migrated.snapshot.current_run.active_artifact_ids.is_empty() and migrated.snapshot.current_run.artifact_draft.is_empty() and migrated.snapshot.current_run.promotion_draft.is_empty(), "growth state starts empty before Round 6")
for recruit_id in migrated.snapshot.current_run.company:
var before: Dictionary = source_snapshot.current_run.recruit_records[recruit_id]
var after: Dictionary = migrated.snapshot.current_run.recruit_records[recruit_id]
expect(after.origin_profession_id == before.base_profession_id and after.profession_id == before.profession_id, "%s preserves Profession identity" % recruit_id)
expect(after.level == before.level and after.xp == before.xp and after.current_hp == before.current_hp and after.max_hp == before.max_hp, "%s preserves level, XP and HP" % recruit_id)
expect(after.promotion_state == "base" and after.promotion_history.is_empty(), "%s receives an empty promotion state" % recruit_id)
for operation_id in source_snapshot.operation_receipts:
expect(migrated.snapshot.legacy_operation_receipts.has(operation_id), "P10.2 operation %s is retained" % operation_id)
expect(migrated.offline_delta == SaveV9.OFFLINE_ZERO, "migration invents no offline value")
var decoded := saves.decode_text(String(migrated.text), 21)
expect(decoded.ok and decoded.snapshot == migrated.snapshot, "migrated Save v9 roundtrips byte-equivalent")
func verify_checksum_backup_and_rollback() -> void:
var saves := SaveV9.new()
var snapshot_value := Fixture.new().migrated_snapshot(4)
var first := saves.encode_snapshot(snapshot_value, 5)
var selected_value := Fixture.new().market_7_snapshot()
var second := saves.encode_snapshot(selected_value, 6, String(first.envelope.commit_hash))
expect(first.ok and second.ok, "adjacent v9 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), 5)
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), "", 6)
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 = 10
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 := SaveV9.new()
var first := saves.write_slot(SLOT_PATH, Fixture.new().migrated_snapshot(), 1)
expect(first.ok and FileAccess.file_exists(SLOT_PATH), "first write promotes verified candidate")
var second := saves.write_slot(SLOT_PATH, Fixture.new().market_7_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 growth 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.market_index == 7, "orphan candidate never overrides committed growth state")
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 Market-5 backup")
func verify_migration_boundaries() -> void:
var p102_market_4 = preload("res://tests/p10_2/mid_contract_fixture.gd").new().market_service_at(4)
var active_v8 := SaveV8.new().encode_snapshot(p102_market_4.state.snapshot(), 1)
expect(active_v8.ok, "active P10.2 Market 4 fixture is a valid v8 state")
var active := SaveV9.new().migrate_v8_text(String(active_v8.text))
expect(not active.ok and active.code == "v8_saved_market_5_required", "active Round 4 cannot skip into deep channels")
var malformed := SaveV9.new().migrate_v8_text("not-json")
expect(not malformed.ok and malformed.code == "v8_save_malformed", "malformed v8 save rejects explicitly")
var source := Fixture.new().encoded_v8(2)
var corrupt = JSON.parse_string(String(source.text))
corrupt.state.current_run.reed_ferry_restored = false
var rejected := SaveV9.new().migrate_v8_text(JSON.stringify(corrupt))
expect(not rejected.ok and rejected.code == "v8_checksum_mismatch", "tampered Ferry handoff cannot migrate")
func verify_state_corruption_boundaries() -> void:
var saves := SaveV9.new()
var market_7 := Fixture.new().market_7_snapshot()
var wrong_seed := market_7.duplicate(true)
wrong_seed.current_run.artifact_draft.run_seed = "0".repeat(32)
expect(not saves.encode_snapshot(wrong_seed, 1).ok, "Artifact draft bound to another Run rejects")
var wrong_level := market_7.duplicate(true)
wrong_level.current_run.market_board.offer_level = 2
wrong_level.current_run.market_board.erase("board_hash")
wrong_level.current_run.market_board.board_hash = preload("res://p10_3/market_board_service.gd").hash_value(wrong_level.current_run.market_board)
expect(not saves.encode_snapshot(wrong_level, 1).ok, "Market-7 offer-level drift rejects even with a recomputed board hash")
var wrong_growth := market_7.duplicate(true)
wrong_growth.current_run.market_board.growth_disclosure.milestone = "linked_positions"
wrong_growth.current_run.market_board.erase("board_hash")
wrong_growth.current_run.market_board.board_hash = preload("res://p10_3/market_board_service.gd").hash_value(wrong_growth.current_run.market_board)
expect(not saves.encode_snapshot(wrong_growth, 1).ok, "Market-7 growth disclosure drift rejects even with a recomputed board hash")
func cleanup_files() -> void:
for file_path in [SLOT_PATH, "%s.bak" % SLOT_PATH, "%s.candidate" % SLOT_PATH]:
if FileAccess.file_exists(file_path):
DirAccess.remove_absolute(file_path)
func expect(condition: bool, message: String) -> void:
if not condition:
failures.append("P10.3 Save v9: %s" % message)
+1
View File
@@ -0,0 +1 @@
uid://bsp103savev9test