diff --git a/CURRENT_CHECKPOINT.md b/CURRENT_CHECKPOINT.md index b9258e6c..ce33bf9c 100644 --- a/CURRENT_CHECKPOINT.md +++ b/CURRENT_CHECKPOINT.md @@ -14,7 +14,7 @@ ## Current State - Stage: `DEV-5_BATTLE_RESULT_RECOVERY_IN_PROGRESS` -- Active implementation step: `DEV-5A_BATTLE_FOUNDATION` +- Active implementation step: `DEV-5B_BATTLE_OPENING_LIVE` - Planning baseline: `d59555c5a3cf95fc44de79ba06c02e650eb3df3b` - Documentation consolidation baseline: `53824d2394e7facdc8dca19aa20a690a5c960aca` @@ -256,6 +256,12 @@ current battle receipt, deterministic event timeline, result/diagnosis data and battle-local knockout state around the accepted DEV-4 snapshot. DEV-5B-D runtime/result/recovery pages and DEV-6 Company management remain pending. +- DEV-5A is locally complete: one idempotent current battle receipt freezes the + accepted Party/risk, persists nine exact event kinds, settles pressured + victory once at Coin `24 -> 51`, records one battle-local knockout without + removing a Recruit and recovers the same four stable IDs for the next stage. + Focused domain and DEV-3/4 regressions pass with strict runner cleanup. DEV-5B + Battle Opening/Live is active. - Broader human comprehension/fun, device, package and release gates remain `OPEN`. @@ -270,7 +276,7 @@ ## Frozen -- DEV-5B and later product changes until DEV-5A is verified, committed and +- DEV-5C and later product changes until DEV-5B is verified, committed and pushed. - Pixel asset expansion. - FG-5 and later Regions. @@ -280,7 +286,6 @@ ## Next Action -Verify and push the DEV-5 activation record, then implement only `DEV-5A`: -create the current battle receipt and deterministic event timeline around the -accepted DEV-4 snapshot. DEV-5B and later remain pending until that domain -boundary passes and is pushed. +Verify and push DEV-5A, then implement only `DEV-5B`: connect Risk Commitment +to Battle Opening/Live with automatic deterministic playback, pause/resume and +the event rail. Result navigation remains pending. diff --git a/docs/06_DEVELOPMENT_AND_REVIEW.md b/docs/06_DEVELOPMENT_AND_REVIEW.md index 52ffd6f3..f93b44b5 100644 --- a/docs/06_DEVELOPMENT_AND_REVIEW.md +++ b/docs/06_DEVELOPMENT_AND_REVIEW.md @@ -424,17 +424,16 @@ signing, device installation, stores and publishing remain outside this plan. ### Immediate Next Action -Implement `DEV-5A` only: add the authoritative deterministic battle receipt, -event timeline, result and next-stage recovery state around the accepted -formation/risk snapshot. Do not change runtime pages until this domain boundary -passes. +Implement `DEV-5B` only: connect Risk Commitment to Battle Opening and one +actor-dominant automatic observation scene with pause/resume and the exact +DEV-5A event rail. Result navigation remains DEV-5C. ## FG-4 Japanese 2D Hand-Drawn Redevelopment Plan > Status: `OWNER_APPROVED` -> Active implementation step: `DEV-5A_BATTLE_FOUNDATION` +> Active implementation step: `DEV-5B_BATTLE_OPENING_LIVE` > Goal: `06_DEVELOPMENT_AND_REVIEW.md` > Contract: `06_DEVELOPMENT_AND_REVIEW.md` > Page plan: `03_PAGES_AND_UX.md` @@ -792,8 +791,8 @@ Only one row may be `IN_PROGRESS`. A failed check keeps that row active. | Substep | Status | Owned product boundary | Narrow acceptance check | Commit boundary | | --- | --- | --- | --- | --- | -| `DEV-5A` Battle foundation | `IN_PROGRESS` | In-place Contract extension creates one retry-safe battle receipt from accepted formation/risk, deterministic event timeline and strict terminal/result/recovery predicates without using historical casualty code | `ABG_DEV5_BATTLE_OK`; begin validation, duplicate/conflict, snapshot/risk identity, exact event kinds/order, deterministic outcome, interruption and no duplicate reward pass | Focused battle service/domain test, plan/checkpoint update and push | -| `DEV-5B` Battle opening/live observation | `PENDING` | Real Godot Battle Opening and Live Battle scene uses the painted environment, four compact actors, enemy-facing gap, disclosed threat, automatic playback, pause/resume and causal event rail | `ABG_DEV5_BATTLE_UI_OK`; Title/Continue -> battle, actual actor order, event timing, pause/resume, 130% layouts, touch/controller path and no combat command prompt pass | Focused battle runtime/input/capture test, plan/checkpoint update and push | +| `DEV-5A` Battle foundation | `COMPLETE` | In-place Contract extension creates one retry-safe battle receipt from accepted formation/risk, deterministic event timeline and strict terminal/result/recovery predicates without using historical casualty code | `ABG_DEV5_BATTLE_OK`; begin validation, duplicate/conflict, snapshot/risk identity, exact event kinds/order, deterministic outcome, interruption and no duplicate reward pass | Focused battle service/domain test, plan/checkpoint update and push | +| `DEV-5B` Battle opening/live observation | `IN_PROGRESS` | Real Godot Battle Opening and Live Battle scene uses the painted environment, four compact actors, enemy-facing gap, disclosed threat, automatic playback, pause/resume and causal event rail | `ABG_DEV5_BATTLE_UI_OK`; Title/Continue -> battle, actual actor order, event timing, pause/resume, 130% layouts, touch/controller path and no combat command prompt pass | Focused battle runtime/input/capture test, plan/checkpoint update and push | | `DEV-5C` Result and diagnosis | `PENDING` | Victory/Defeat result names objective, first decisive event, reward, XP and downstream state; one reviewable causal chain precedes Continue | `ABG_DEV5_RESULT_OK`; result receipt, duplicate settlement, reward/XP totals, cause inspect, restart and truthful loss state pass | Focused result/diagnosis UI/domain test, plan/checkpoint update and push | | `DEV-5D` Knockout and next-stage recovery | `PENDING` | Knockout review names stable Recruit identity, current-battle absence and next-stage return; recovery atomically restores battle readiness without permanent death or roster replacement | `ABG_DEV5_RECOVERY_OK`; same ID/Profession/Trait/equipment, recovery receipt, duplicate/retry/candidate recovery, no permanent removal and next-stage handoff pass | Focused recovery UI/persistence/input test, plan/checkpoint update and push | | `DEV-5E` First-cycle candidate | `PENDING` | Source-bound Title/Continue -> Market -> Party -> Readiness -> Risk -> Battle -> Result -> Recovery path completes one first cycle at required landscape sizes and stops before DEV-6 management | All applicable DEV-1/2/3/4/5 markers, parsed touch and representative 760x360/844x390/1280x720 zh_CN/en 100/130% normal-render states pass with strict diagnostics 0 | Candidate evidence closure commit and push | @@ -828,7 +827,7 @@ visual/comprehension/fun, device, package, store and release gates remain | ID | Status | Boundary | | --- | --- | --- | -| `DEV5-I01` | `ACTIVE_DEV-5A` | Historical battle controllers encode superseded casualty/run semantics. The new receipt/timeline must be independently authored and attach only to the current schema-v2 Company/Contract. | +| `DEV5-I01` | `RESOLVED_DEV-5A` | `BattleService` independently attaches one current receipt/timeline to the schema-v2 Company/Contract and never calls historical casualty/run services. | | `DEV5-I02` | `FROZEN_LEGACY` | Existing permanent-death, Replacement Credit, Company-collapse and roster-archive behavior cannot be surfaced as current product truth. | | `DEV5-I03` | `ACTIVE_RECURRENCE_CHECK` | Battle must keep actors and event projections dominant, preserve the accepted Japanese 2D scale, and avoid a dashboard/card wall or combat command prompt. | | `DEV5-I04` | `OPEN_HUMAN_GATE` | Automated evidence cannot prove that the player understands the first decisive cause, battle-local knockout, reward or next-stage return. | @@ -1660,3 +1659,27 @@ they are not duplicated here. deterministic event timeline around the accepted DEV-4 formation/risk state. Historical battle/casualty services remain preserved but cannot be used as current persistence authority. + +### 2026-08-18 - DEV-5A Battle Foundation Implemented + +- `BattleService` consumes the exact accepted Party snapshot and one stable + risk option to create a single idempotent battle receipt in the existing + Contract. A second operation cannot replace it; every phase persists through + the same redundant atomic Company store. +- The deterministic first-battle timeline is exactly opening, telegraph, guard, + ranged, magic, healing, damage, knockout and result. Pressured risk awards 27 + Coin once (`24 -> 51`), records one victory for all four participants and one + battle-local knockout for the exposed position-0 Recruit. No roster record is + removed or replaced. +- Next-stage recovery records one receipt, keeps all four stable IDs and their + Profession/Trait/equipment facts, returns Contract status to Market and + releases the old formation snapshot. Duplicate settlement/recovery cannot + duplicate Coin or receipts; backup recovery preserves the terminal state. +- Focused domain PASS: + `/private/tmp/aetherbound-guild-test-evidence/dev5-battle-foundation-worktree/20260817T183617Z-16166`. + DEV-4 foundation/risk and DEV-3 hire regressions PASS at + `/private/tmp/aetherbound-guild-test-evidence/dev5-foundation-dev4-regression/20260817T183633Z-17719`, + `/private/tmp/aetherbound-guild-test-evidence/dev5-foundation-risk-regression/20260817T183633Z-17721` + and `/private/tmp/aetherbound-guild-test-evidence/dev5-foundation-dev3-regression/20260817T183633Z-17720`. + All attempts have strict diagnostics 0 and complete runner cleanup. DEV-5B + Battle Opening/Live is now the only active step. diff --git a/runtime/entry/battle_service.gd b/runtime/entry/battle_service.gd new file mode 100644 index 00000000..4e303c17 --- /dev/null +++ b/runtime/entry/battle_service.gd @@ -0,0 +1,362 @@ +class_name ABGBattleService +extends RefCounted + +const DraftService = preload("res://entry/initial_company_draft_service.gd") + +const DEFAULT_COMPANY_PATH := "user://aetherbound_expedition_company.json" +const TOTAL_PHASES := 9 + +var company_path := DEFAULT_COMPANY_PATH + + +func load_company() -> Dictionary: + return _store().load_company() + + +func begin_battle(operation_id: String, risk_option_id: String) -> Dictionary: + if not _is_hex(operation_id, 32): + return {"ok": false, "code": "BATTLE_OPERATION_ID_INVALID"} + if not _is_hex(risk_option_id, 32): + return {"ok": false, "code": "BATTLE_RISK_ID_INVALID"} + var loaded: Dictionary = load_company() + if not loaded.ok: + return loaded + var company: Dictionary = loaded.company.duplicate(true) + var contract: Dictionary = company.active_contract + var formation: Dictionary = contract.get("formation", {}) + if formation.is_empty() or String(formation.get("status", "")) != "ready": + return {"ok": false, "code": "BATTLE_READINESS_REQUIRED"} + var option := _risk_option_by_id(formation, risk_option_id) + if option.is_empty(): + return {"ok": false, "code": "BATTLE_RISK_UNAVAILABLE"} + if contract.has("battle_state") and not Dictionary(contract.battle_state).is_empty(): + var existing: Dictionary = contract.battle_state + if String(existing.get("operation_id", "")) == operation_id and String(existing.get("risk_option_id", "")) == risk_option_id: + return {"ok": true, "code": "battle_already_started", "company": company, "battle": existing} + return {"ok": false, "code": "BATTLE_ALREADY_ACTIVE"} + var party_ids: Array[String] = [] + party_ids.assign(formation.accepted_party_snapshot.front_to_rear_ids) + var snapshot_hash := String(formation.accepted_party_snapshot.snapshot_hash) + var intent := { + "company_id": String(company.company_id), + "run_id": String(contract.run_id), + "risk_option_id": risk_option_id, + "snapshot_hash": snapshot_hash, + } + var intent_hash := _hash(intent) + for prior in contract.get("battle_receipts", []): + if String(prior.get("operation_id", "")) == operation_id: + if String(prior.get("intent_hash", "")) != intent_hash: + return {"ok": false, "code": "BATTLE_OPERATION_CONFLICT"} + return {"ok": true, "code": "battle_already_started", "company": company, "battle": contract.battle_state} + var battle := { + "battle_version": 1, + "status": "active", + "operation_id": operation_id, + "intent_hash": intent_hash, + "company_id": String(company.company_id), + "run_id": String(contract.run_id), + "risk_option_id": risk_option_id, + "risk": int(option.risk), + "snapshot_id": String(formation.accepted_party_snapshot.snapshot_id), + "snapshot_hash": snapshot_hash, + "front_to_rear_ids": party_ids, + "enemy_ids": Array(option.enemy_ids).duplicate(), + "phase_index": 0, + "total_phases": TOTAL_PHASES, + "phase_events": [], + "knocked_out_ids": [], + "result": {}, + } + _refresh_hash(battle, "battle_hash") + var receipt := { + "operation_id": operation_id, + "intent_hash": intent_hash, + "company_id": String(company.company_id), + "run_id": String(contract.run_id), + "risk_option_id": risk_option_id, + "snapshot_id": String(battle.snapshot_id), + "snapshot_hash": snapshot_hash, + "event_count": 0, + } + _refresh_hash(receipt, "receipt_hash") + contract.status = "battle" + contract.battle_state = battle + contract.battle_receipts = [receipt] + contract.battle_settlement_receipts = [] + _refresh_hash(contract, "contract_hash") + company.active_contract = contract + _refresh_hash(company, "company_hash") + var saved: Dictionary = _store().save_company(company) + if not saved.ok: + return saved + return {"ok": true, "code": "battle_started", "company": saved.company, "battle": saved.company.active_contract.battle_state, "receipt": receipt} + + +func advance_battle(operation_id: String) -> Dictionary: + if not _is_hex(operation_id, 32): + return {"ok": false, "code": "BATTLE_OPERATION_ID_INVALID"} + var loaded: Dictionary = load_company() + if not loaded.ok: + return loaded + var company: Dictionary = loaded.company.duplicate(true) + var contract: Dictionary = company.active_contract + var battle: Dictionary = contract.get("battle_state", {}) + if battle.is_empty() or String(battle.get("operation_id", "")) != operation_id: + return {"ok": false, "code": "BATTLE_NOT_FOUND"} + if String(battle.status) == "result" or String(battle.status) == "recovered": + return {"ok": true, "code": "battle_already_settled", "company": company, "battle": battle} + var phase: int = int(battle.phase_index) + if phase >= TOTAL_PHASES: + return _settle_battle(company, battle) + var event := _event_for_phase(company, battle, phase) + battle.phase_events.append(event) + battle.phase_index = phase + 1 + if String(event.kind) == "knockout" and not String(event.target_id).is_empty(): + battle.knocked_out_ids = [String(event.target_id)] + if String(event.kind) == "result": + return _settle_battle(company, battle) + _refresh_hash(battle, "battle_hash") + contract.battle_state = battle + _refresh_hash(contract, "contract_hash") + company.active_contract = contract + _refresh_hash(company, "company_hash") + var saved: Dictionary = _store().save_company(company) + if not saved.ok: + return saved + return {"ok": true, "code": "battle_advanced", "company": saved.company, "battle": saved.company.active_contract.battle_state, "event": event} + + +func recover_next_stage(operation_id: String) -> Dictionary: + if not _is_hex(operation_id, 32): + return {"ok": false, "code": "RECOVERY_OPERATION_ID_INVALID"} + var loaded: Dictionary = load_company() + if not loaded.ok: + return loaded + var company: Dictionary = loaded.company.duplicate(true) + var contract: Dictionary = company.active_contract + var battle: Dictionary = contract.get("battle_state", {}) + for prior in contract.get("recovery_receipts", []): + if String(prior.get("operation_id", "")) == operation_id: + return {"ok": true, "code": "recovery_already_applied", "company": company, "receipt": prior} + if battle.is_empty() or String(battle.status) != "result": + return {"ok": false, "code": "RECOVERY_RESULT_REQUIRED"} + var knocked: Array[String] = [] + knocked.assign(battle.get("knocked_out_ids", [])) + var receipt := { + "operation_id": operation_id, + "company_id": String(company.company_id), + "run_id": String(contract.run_id), + "battle_operation_id": String(battle.operation_id), + "battle_hash": String(battle.battle_hash), + "recruited_ids": knocked, + "return_rule": "returns_next_stage_same_identity", + "next_stage_ready": true, + } + _refresh_hash(receipt, "receipt_hash") + var recovery_receipts: Array = contract.get("recovery_receipts", []).duplicate(true) + recovery_receipts.append(receipt) + contract.recovery_receipts = recovery_receipts + contract.status = "market" + battle.status = "recovered" + battle.recovery_receipt = receipt + _refresh_hash(battle, "battle_hash") + contract.battle_state = battle + contract.erase("formation") + _refresh_hash(contract, "contract_hash") + company.active_contract = contract + _refresh_hash(company, "company_hash") + var saved: Dictionary = _store().save_company(company) + if not saved.ok: + return saved + return {"ok": true, "code": "recovered", "company": saved.company, "receipt": receipt, "recruited_ids": knocked} + + +func _settle_battle(company: Dictionary, battle: Dictionary) -> Dictionary: + var contract: Dictionary = company.active_contract + if String(battle.status) == "result": + return {"ok": true, "code": "battle_already_settled", "company": company, "battle": battle} + var option := _risk_option_by_id(contract.formation, String(battle.risk_option_id)) + if option.is_empty(): + return {"ok": false, "code": "BATTLE_RISK_UNAVAILABLE"} + var knocked: Array[String] = [] + knocked.assign(battle.knocked_out_ids) + var reward := int(option.reward_coin) + var xp := 12 + int(option.risk) * 4 + var coin_before := int(contract.coin) + var coin_after := coin_before + reward + var result_event := { + "kind": "result", + "phase": int(battle.phase_index), + "actor_id": "", + "target_id": "", + "caption_id": "victory", + "outcome": "victory", + "reward_coin": reward, + "xp_award": xp, + "knocked_out_ids": knocked, + } + _refresh_hash(result_event, "event_hash") + battle.phase_events.append(result_event) + battle.phase_index = TOTAL_PHASES + battle.status = "result" + battle.result = { + "outcome": "victory", + "reward_coin": reward, + "xp_award": xp, + "coin_before": coin_before, + "coin_after": coin_after, + "knocked_out_ids": knocked, + "decisive_event_hash": String(battle.phase_events[maxi(0, battle.phase_events.size() - 2)].event_hash), + } + _refresh_hash(battle.result, "result_hash") + contract.coin = coin_after + for recruit in company.owned_recruits: + var recruit_id := String(recruit.recruit_id) + var history: Dictionary = recruit.battle_history.duplicate(true) + history.battles_entered = int(history.battles_entered) + 1 + history.victories = int(history.victories) + 1 + if recruit_id in knocked: + history.knockouts = int(history.knockouts) + 1 + recruit.battle_history = history + recruit.recruit_hash = _hash_without(recruit, "recruit_hash") + var settlement := { + "operation_id": String(battle.operation_id), + "company_id": String(company.company_id), + "run_id": String(contract.run_id), + "battle_hash": String(battle.battle_hash), + "outcome": "victory", + "reward_coin": reward, + "xp_award": xp, + "coin_before": coin_before, + "coin_after": coin_after, + "knocked_out_ids": knocked, + } + _refresh_hash(settlement, "receipt_hash") + contract.battle_settlement_receipts = [settlement] + contract.status = "result" + battle.settlement_receipt = settlement + _refresh_hash(battle, "battle_hash") + contract.battle_state = battle + _refresh_hash(contract, "contract_hash") + company.active_contract = contract + _refresh_hash(company, "company_hash") + var saved: Dictionary = _store().save_company(company) + if not saved.ok: + return saved + return {"ok": true, "code": "battle_settled", "company": saved.company, "battle": saved.company.active_contract.battle_state, "event": result_event} + + +func _event_for_phase(company: Dictionary, battle: Dictionary, phase: int) -> Dictionary: + var ids: Array = battle.front_to_rear_ids + var actor_id := String(ids[0]) if not ids.is_empty() else "" + var rear_id := String(ids[ids.size() - 1]) if not ids.is_empty() else "" + var target_id := String(battle.enemy_ids[0]) if not battle.enemy_ids.is_empty() else "enemy-front" + var event := { + "phase": phase, + "actor_id": actor_id, + "target_id": target_id, + "amount": 0, + "outcome": "observed", + } + match phase: + 0: + event.kind = "opening" + event.caption_id = "battle_opening" + event.actor_id = "" + event.target_id = "" + 1: + event.kind = "telegraph" + event.caption_id = "incoming_threat" + 2: + event.kind = "guard" + event.caption_id = "protection_intercepts" + event.actor_id = rear_id if not rear_id.is_empty() else actor_id + event.target_id = actor_id + event.amount = 8 + 3: + event.kind = "ranged" + event.caption_id = "ranged_contact" + event.actor_id = rear_id if not rear_id.is_empty() else actor_id + event.amount = 10 + 4: + event.kind = "magic" + event.caption_id = "magic_break" + event.actor_id = actor_id + event.amount = 12 + 5: + event.kind = "healing" + event.caption_id = "healing_link" + event.actor_id = String(ids[mini(1, ids.size() - 1)]) if not ids.is_empty() else actor_id + event.target_id = actor_id + event.amount = 6 + 6: + event.kind = "damage" + event.caption_id = "decisive_damage" + event.actor_id = actor_id + event.amount = 22 + 7: + event.kind = "knockout" if int(battle.risk) > 0 else "guarded_recovery" + event.caption_id = "knockout" if int(battle.risk) > 0 else "line_holds" + event.target_id = actor_id if int(battle.risk) > 0 else "" + 8: + event.kind = "result" + event.caption_id = "victory" + event.outcome = "victory" + _refresh_hash(event, "event_hash") + return event + + +func _risk_option_by_id(formation: Dictionary, option_id: String) -> Dictionary: + for option in formation.get("risk_options", []): + if String(option.get("risk_option_id", "")) == option_id: + return Dictionary(option) + return {} + + +func _store() -> RefCounted: + var store := DraftService.new() + store.company_path = company_path + return store + + +func _refresh_hash(value: Dictionary, field: String) -> void: + value.erase(field) + value[field] = _hash(value) + + +func _hash_without(value: Dictionary, field: String) -> String: + var copy := value.duplicate(true) + copy.erase(field) + return _hash(copy) + + +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 diff --git a/runtime/entry/initial_company_draft_service.gd b/runtime/entry/initial_company_draft_service.gd index 251b4240..416ce4f8 100644 --- a/runtime/entry/initial_company_draft_service.gd +++ b/runtime/entry/initial_company_draft_service.gd @@ -458,7 +458,7 @@ func _validate_owned_recruit(value, draft_id: String) -> Dictionary: if not recruit.battle_history is Dictionary: return {"ok": false, "code": "COMPANY_RECRUIT_HISTORY_INVALID"} for field in ["battles_entered", "victories", "knockouts"]: - if int(recruit.battle_history.get(field, -1)) != 0: + if int(recruit.battle_history.get(field, -1)) < 0: return {"ok": false, "code": "COMPANY_RECRUIT_HISTORY_INVALID"} var unhashed := recruit.duplicate(true) unhashed.erase("recruit_hash") @@ -520,9 +520,9 @@ func _validate_active_contract(value: Dictionary, company: Dictionary) -> Dictio return {"ok": false, "code": "CONTRACT_IDENTITY_INVALID"} if String(value.difficulty) not in ["wayfinder", "standard", "stormbound", "iron_oath"]: return {"ok": false, "code": "CONTRACT_DIFFICULTY_INVALID"} - if String(value.status) != "market" or int(value.market_index) != 1: + if String(value.status) not in ["market", "battle", "result", "recovery"] or int(value.market_index) != 1: return {"ok": false, "code": "CONTRACT_PHASE_INVALID"} - if int(value.coin) < 0 or int(value.coin) > 52 or int(value.line_capacity) != 4: + if int(value.coin) < 0 or int(value.coin) > 999 or int(value.line_capacity) != 4: return {"ok": false, "code": "CONTRACT_RESOURCE_INVALID"} if not value.market_board is Dictionary: return {"ok": false, "code": "CONTRACT_MARKET_INVALID"} @@ -561,11 +561,14 @@ func _validate_active_contract(value: Dictionary, company: Dictionary) -> Dictio return {"ok": false, "code": "CONTRACT_HIRED_OFFER_AVAILABLE"} hired_offer_ids.append(String(receipt.offer_id)) hired_recruit_ids.append(String(receipt.recruit_id)) + var opening_coin: int = 52 - 14 * value.hire_receipts.size() + var has_battle_progress: bool = value.has("battle_state") or (value.has("battle_settlement_receipts") and not value.battle_settlement_receipts.is_empty()) if ( value.available_recruit_offer_ids.size() != 3 - value.hire_receipts.size() or value.available_equipment_offer_ids.size() != 4 or value.available_battle_offer_ids.size() != 3 - or int(value.coin) != 52 - 14 * value.hire_receipts.size() + or (not has_battle_progress and int(value.coin) != opening_coin) + or (has_battle_progress and int(value.coin) < opening_coin) ): return {"ok": false, "code": "CONTRACT_OPENING_STATE_INVALID"} var receipt_validation := _validate_contract_creation_receipt(value.creation_receipt, value) diff --git a/runtime/tests/dev5/battle_foundation_test.gd b/runtime/tests/dev5/battle_foundation_test.gd new file mode 100644 index 00000000..2a4a7634 --- /dev/null +++ b/runtime/tests/dev5/battle_foundation_test.gd @@ -0,0 +1,193 @@ +extends SceneTree + +const DraftService = preload("res://entry/initial_company_draft_service.gd") +const ContractService = preload("res://entry/guild_contract_service.gd") +const FormationService = preload("res://entry/formation_risk_service.gd") +const BattleService = preload("res://entry/battle_service.gd") + +const DRAFT_PATH := "user://dev5_battle_draft.json" +const COMPANY_PATH := "user://dev5_battle_company.json" +const SEED := "0123456789abcdeffedcba9876543210" +const CONTRACT_OP := "abcdef0123456789abcdef0123456789" +const HIRE_OP_1 := "11111111222222223333333344444444" +const HIRE_OP_2 := "55555555666666667777777788888888" +const ORDER_OP := "99999999aaaaaaaabbbbbbbbcccccccc" +const READY_OP := "ddddddddeeeeeeeeffffffff00000000" +const BATTLE_OP := "1234567890abcdef1234567890abcdef" +const OTHER_BATTLE_OP := "fedcba0987654321fedcba0987654321" +const RECOVERY_OP := "0f0f0f0ff0f0f0f00f0f0f0fff0f0f0f" + +var failures: Array[String] = [] + + +func _initialize() -> void: + call_deferred("run_test") + + +func run_test() -> void: + _cleanup() + var prepared := _create_prepared_company() + if not prepared.is_empty(): + verify_begin_and_timeline(prepared) + verify_recovery_and_restart() + _cleanup() + if failures.is_empty(): + print("ABG_DEV5_BATTLE_OK begin=atomic,idempotent conflict=true snapshot=true phases=opening,telegraph,guard,ranged,magic,healing,damage,knockout,result outcome=victory reward=27 coin=24,51 history=true knockout=one same_identity=true recovery=next_stage,candidate duplicate_reward=false battle_receipts=1") + quit(0) + else: + for failure in failures: + push_error(failure) + quit(1) + + +func verify_begin_and_timeline(prepared: Dictionary) -> void: + var service := _battle_service() + var before: Dictionary = _draft_service().load_company() + var contract: Dictionary = before.company.active_contract + var option_id := String(contract.formation.risk_options[1].risk_option_id) + var started: Dictionary = service.begin_battle(BATTLE_OP, option_id) + expect(started.ok and started.code == "battle_started", "accepted party/risk creates one battle receipt") + if not started.ok: + return + expect(started.company.active_contract.status == "battle" and started.battle.phase_index == 0 and started.battle.total_phases == 9, "battle starts at deterministic opening phase") + expect(started.battle.front_to_rear_ids == contract.formation.accepted_party_snapshot.front_to_rear_ids and started.battle.snapshot_hash == contract.formation.accepted_party_snapshot.snapshot_hash, "battle receipt freezes the exact accepted Party snapshot") + var duplicate: Dictionary = service.begin_battle(BATTLE_OP, option_id) + expect(duplicate.ok and duplicate.code == "battle_already_started" and String(duplicate.battle.battle_hash) == String(started.battle.battle_hash), "duplicate begin returns the original battle receipt") + var conflict: Dictionary = service.begin_battle(OTHER_BATTLE_OP, option_id) + expect(not conflict.ok and conflict.code == "BATTLE_ALREADY_ACTIVE", "a second operation cannot create a second active battle") + var kinds: Array[String] = [] + var last: Dictionary = started + for _phase in range(9): + last = service.advance_battle(BATTLE_OP) + expect(last.ok, "battle phase advances without mutation error") + if not last.ok: + return + if last.has("event"): + kinds.append(String(last.event.kind)) + expect(kinds == ["opening", "telegraph", "guard", "ranged", "magic", "healing", "damage", "knockout", "result"], "event timeline contains the exact authored event order") + var result_company: Dictionary = last.company + var result_battle: Dictionary = last.battle + expect(result_battle.status == "result" and result_battle.result.outcome == "victory" and int(result_battle.result.reward_coin) == 27, "result settles a truthful victory and pressed reward") + expect(int(result_company.active_contract.coin) == 51 and result_company.active_contract.battle_settlement_receipts.size() == 1, "result awards 27 Coin once from the 24 Coin opening balance") + var knocked: Array = result_battle.result.knocked_out_ids + expect(knocked.size() == 1, "pressed risk creates exactly one battle-local knockout") + if knocked.size() == 1: + var knocked_id := String(knocked[0]) + var recruit := _recruit_by_id(result_company, knocked_id) + expect(not recruit.is_empty() and int(recruit.battle_history.battles_entered) == 1 and int(recruit.battle_history.victories) == 1 and int(recruit.battle_history.knockouts) == 1, "knocked Recruit keeps stable history instead of being removed") + var settled_retry: Dictionary = service.advance_battle(BATTLE_OP) + expect(settled_retry.ok and settled_retry.code == "battle_already_settled" and int(settled_retry.company.active_contract.coin) == 51, "settlement retry cannot duplicate reward") + + +func verify_recovery_and_restart() -> void: + var settled: Dictionary = _draft_service().load_company() + expect(settled.ok and settled.company.active_contract.battle_state.status == "result", "result state survives process restart") + if not settled.ok: + return + var before_ids := _recruit_ids(settled.company) + var recovered: Dictionary = _battle_service().recover_next_stage(RECOVERY_OP) + expect(recovered.ok and recovered.code == "recovered", "next-stage recovery creates one receipt") + if not recovered.ok: + return + expect(recovered.company.active_contract.status == "market" and not recovered.company.active_contract.has("formation"), "recovery returns to next-stage preparation without stale frozen order") + expect(_recruit_ids(recovered.company) == before_ids and recovered.company.active_contract.recovery_receipts.size() == 1, "recovery retains every Recruit identity and one recovery receipt") + expect(recovered.receipt.return_rule == "returns_next_stage_same_identity" and recovered.receipt.next_stage_ready, "recovery names the same-identity next-stage rule") + var duplicate: Dictionary = _battle_service().recover_next_stage(RECOVERY_OP) + expect(duplicate.ok and duplicate.code == "recovery_already_applied" and duplicate.company.active_contract.recovery_receipts.size() == 1, "duplicate recovery does not create another receipt") + var saved: Dictionary = _draft_service().load_company() + expect(saved.ok and _draft_service().validate_company(saved.company).ok, "recovered Company remains strictly valid") + var expected_hash := String(saved.company.company_hash) + _write(COMPANY_PATH, "{broken primary") + var backup: Dictionary = _battle_service().load_company() + expect(backup.ok and backup.code == "recovered_backup" and String(backup.company.company_hash) == expected_hash, "backup recovery preserves result and next-stage state") + + +func _create_prepared_company() -> Dictionary: + var draft: Dictionary = _draft_service().begin_or_load(SEED) + if not draft.ok: + expect(false, "fixture creates opening draft") + return {} + var selected: Dictionary = _draft_service().set_selection([String(draft.draft.offers[0].offer_id), String(draft.draft.offers[3].offer_id)]) + var committed: Dictionary = _draft_service().commit_company() + if not selected.ok or not committed.ok: + expect(false, "fixture commits opening Company") + return {} + var created: Dictionary = _contract_service().create_contract(CONTRACT_OP, "CTR-R1-01", "standard") + if not created.ok: + expect(false, "fixture creates first Contract") + return {} + var offers: Array = created.company.active_contract.market_board.recruit_offers + _contract_service().hire_recruit(HIRE_OP_1, String(offers[0].source_offer_id), 14) + var hired: Dictionary = _contract_service().hire_recruit(HIRE_OP_2, String(offers[1].source_offer_id), 14) + if not hired.ok: + expect(false, "fixture completes both opening hires") + return {} + var begun: Dictionary = _formation_service().begin_formation() + if not begun.ok: + expect(false, "fixture creates formation") + return {} + var saved: Dictionary = _formation_service().save_order(ORDER_OP, begun.formation.base_front_to_rear_ids) + if not saved.ok: + expect(false, "fixture saves formation") + return {} + var ready: Dictionary = _formation_service().accept_readiness(READY_OP, String(saved.receipt.order_hash)) + return ready.company if ready.ok else {} + + +func _draft_service() -> RefCounted: + var service := DraftService.new() + service.path = DRAFT_PATH + service.company_path = COMPANY_PATH + return service + + +func _contract_service() -> RefCounted: + var service := ContractService.new() + service.company_path = COMPANY_PATH + return service + + +func _formation_service() -> RefCounted: + var service := FormationService.new() + service.company_path = COMPANY_PATH + return service + + +func _battle_service() -> RefCounted: + var service := BattleService.new() + service.company_path = COMPANY_PATH + return service + + +func _recruit_by_id(company: Dictionary, recruit_id: String) -> Dictionary: + for recruit in company.owned_recruits: + if String(recruit.recruit_id) == recruit_id: + return Dictionary(recruit) + return {} + + +func _recruit_ids(company: Dictionary) -> Array[String]: + var ids: Array[String] = [] + for recruit in company.owned_recruits: + ids.append(String(recruit.recruit_id)) + return ids + + +func _write(path: String, text_value: String) -> void: + var file := FileAccess.open(path, FileAccess.WRITE) + if file == null: + expect(false, "fixture writes %s" % path) + return + file.store_string(text_value) + file.close() + + +func _cleanup() -> void: + for path in [DRAFT_PATH, "%s.bak" % DRAFT_PATH, "%s.candidate" % DRAFT_PATH, "%s.bak.candidate" % DRAFT_PATH, COMPANY_PATH, "%s.bak" % COMPANY_PATH, "%s.candidate" % COMPANY_PATH, "%s.bak.candidate" % COMPANY_PATH, "%s.corrupt" % COMPANY_PATH]: + if FileAccess.file_exists(path): + DirAccess.remove_absolute(path) + + +func expect(condition: bool, message: String) -> void: + if not condition: + failures.append("DEV-5 battle foundation: %s" % message)