fix(battlenode): shadow engine tracks live PvP wire-truth (full battle, multiple bid regressions)

Six distinct fixes accumulated over live-test iterations against four bids
(654473755566, 806245601092, 283192092460, 131549100204, 799755786270) — together
they take the shadow engine from "throws on the first non-mulligan play" to
"survives a full PvP battle, only weird-edge-case Unity touches still left to whack".

1. Engine StableRandom seed aligned with clients' Matched.seed
   (BattleSession.EnsureEngineSetup, NodeNativeBattleHarness.Create). Clients seed
   _stableRandom with BattleSeeds.Stable(masterSeed) (the value the node ships in
   Matched.seed); we were passing the RAW masterSeed to engine.Setup, so every
   StableRandom call diverged from call #1 onward — every turn-1+ draw picked a
   different deck position than the clients. Verified Stable(1184631275)=1543475792
   matches the wire on bid 654473755566.

2. SeedDeck advances cardTotalNum to deck.Count+1 + pins BattleStartDeckCardList.
   Mirrors SBattleLoad.InitPlayer's tail (SBattleLoad.cs:1292). Without it,
   skill-generated tokens auto-assigned Index 0,1,... and COLLIDED with deck-loaded
   indices 1..40 — silent until something addressed the deck card with the
   colliding Index (Hoverboarder at deck idx 1 + a token at engine Index 1 made
   GetBattleCardIdx's SingleOrDefault throw on bid 806245601092).

3. BattleCardView.GameObject lazily non-null in the shim (ViewUiTouchStubs.cs).
   The IsRecovery card-create delegate (NetworkBattleManagerBase.cs:379) passes
   null cardGameObject; Skill_metamorphose.cs:147 in the in-play branch then NRE'd
   on `metamorphosedCard.BattleCardView.GameObject.transform.rotation = identity`,
   a purely cosmetic touch with no game-state implication. Bid 283192092460:
   Petrification on a board follower.

4. TranslateChoiceKeyAction unwraps wrapped selectCard on shadow ingest
   (SessionBattleEngine.cs, sibling to TranslateTargetOwners). Live sender-send
   wires Choice plays as selectCard:{cardId:[...], open:0}; engine's
   ConvertToListInt does `value as List<object>` — a Dict casts to null and
   foreach NREs. The receiver's swallow-all catch (NetworkBattleReceiver.cs:1255)
   logs to Debug.LogError + LocalLog — both shimmed/no-op'd headlessly — and
   returns false, but Receive calls ReceivedMessage with checkBreakData:false so
   the false isn't propagated. The play continues with choiceIdList=[], the chosen
   branch never resolves, the played card stays in hand; a later targeted play
   (A's bounce on B's "board" idx 20) then can't find the target → NRE on null in
   ActionProcessor.PlayCard:407. Bid 131549100204: B's Resonance + A's bounce.
   Opponent-relay path is unaffected — node strips selectCard from broadcasts.

5. HeadlessHandViewStub overrides HandUnfocus/HandFocus/FocusRearrangeHandHand
   to return NullVfx. CreateHandControl returns null in headless; the base
   methods unconditionally deref `_handControl.SetHandState(...)`. A follower
   with a when_spell_play Heal trigger fired on its leader for amount 0 — even
   a 0-heal drives ApplyHealing → CreatePullHandInVfx → HandUnfocus → NRE.
   Bid 799755786270: two consecutive spell plays both crashed this stack.
   Added InternalsVisibleTo("SVSim.BattleEngine.Tests") so the shim-level
   regression tests can pin the no-op contracts directly.

Plus the previous-session fixes carried in this same uncommitted state
(see docs/superpowers/plans/2026-06-07-shadow-engine-desync-handoff.md):
  - doesPlayerGoFirst:true + mgr.IsFirst:true (turn-1 draw count correct
    per seat)
  - RecoveryOperationCollection.PlayHandCardOperation routes all type:30
    through PlaySkillSelectHandCardOperation (skips the two-phase user-select
    guard that aborts targeted spells in recovery)
  - ShadowFeed + ToRawBody: server-generated typed bodies (DealBody, etc.)
    converted to RawBody before engine.Receive (`env.Body as RawBody`
    returned null for typed bodies)
  - Ready idxChangeSeed seeds A's XorShift via the receiver; B's seed is
    injected via SeedOppoIdxChange (BattleSeeds.IdxChange + viewerId)
  - ReadySpin defaulted to 0 (was 243) — non-zero double-cranks the shadow
    which ingests BOTH sides' Ready frames on one stream

Test counts: SVSim.UnitTests 1054/1054, SVSim.BattleEngine.Tests 34/34.

Open: known-residual Unity touches are individual whack-a-mole now (per-card
skill edge cases), not the structural divergences fixed here.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
gamer147
2026-06-07 19:05:07 -04:00
parent 2a8c44a6d7
commit addeb021d2
22 changed files with 2263 additions and 62 deletions

View File

@@ -1,4 +1,5 @@
using SVSim.BattleNode.Bridge;
using SVSim.BattleNode.Lifecycle;
using SVSim.BattleNode.Protocol;
using SVSim.BattleNode.Sessions;
using SVSim.BattleNode.Sessions.Dispatch;
@@ -219,7 +220,10 @@ internal sealed class NodeNativeBattleHarness : IDisposable
var shuffledB = state.GetShuffledDeck(b);
var engine = new SessionBattleEngine();
engine.Setup(state.MasterSeed, shuffledA, shuffledB,
// Mirror BattleSession.EnsureEngineSetup: engine's StableRandom is seeded with
// BattleSeeds.Stable(MasterSeed), the value the Matched frame ships to clients
// (InitBattleHandler.cs:28). See BattleSession.cs for the full root-cause comment.
engine.Setup(BattleSeeds.Stable(state.MasterSeed), shuffledA, shuffledB,
(int)a.Context.ClassId, (int)b.Context.ClassId);
return new NodeNativeBattleHarness(state, a, b, engine, shuffledA, shuffledB);
@@ -259,6 +263,17 @@ internal sealed class NodeNativeBattleHarness : IDisposable
/// <summary>The engine Index of the hand card at <paramref name="handPos"/> on the given seat.</summary>
public int HandCardIndex(bool playerSeat, int handPos) => Engine.HandCardIndex(playerSeat, handPos);
/// <summary>TEST/DEBUG: pull one value from the engine's shared <c>_stableRandom</c> stream. Mirrors the
/// engine's <see cref="SessionBattleEngine.DebugStableRandomDouble"/> seam; lets a regression test
/// assert seed alignment with the wire (clients seed their <c>_stableRandom</c> with the Matched.seed,
/// which is <c>BattleSeeds.Stable(masterSeed)</c>).</summary>
public double DebugStableRandomDouble() => Engine.DebugStableRandomDouble();
/// <summary>TEST/DEBUG: read the seat's auto-assign Index counter (<c>cardTotalNum</c>). After
/// Setup it must equal <c>deck.Count + 1</c> so the next skill-generated token gets an Index
/// clear of the deck-loaded 1..40 (= the real client's SBattleLoad behavior).</summary>
public int DebugCardTotalNum(bool playerSeat) => Engine.DebugCardTotalNum(playerSeat);
/// <summary>The real wire <c>CardId</c> of the in-play follower at <paramref name="boardPos"/> on the
/// given seat (0-based, leader excluded). Asserts an opponent reveal seated the substituted identity
/// (M-HC-2).</summary>
@@ -286,6 +301,19 @@ internal sealed class NodeNativeBattleHarness : IDisposable
/// <summary>Turns remaining until the seat may evolve (0 == unlocked) (M-HC-4b).</summary>
public int EvolveWaitTurnCount(bool playerSeat) => Engine.EvolveWaitTurnCount(playerSeat);
// --- TEST/DEBUG seams (Phase 4 root-cause verification: post-mulligan reshuffle) ---------------
/// <summary>TEST/DEBUG: is the engine's SELF-seat XorShift idx-change RNG active (the gate the
/// post-mulligan reshuffle checks)? Live recovery setup leaves it FALSE.</summary>
public bool SelfXorShiftActive => Engine.SelfXorShiftActive;
/// <summary>TEST/DEBUG: opponent-seat XorShift active state.</summary>
public bool OppoXorShiftActive => Engine.OppoXorShiftActive;
/// <summary>TEST/DEBUG: inject the per-seat idxChange seeds (call before the Ready mulligan-end frame
/// to activate the engine's own post-mulligan reshuffle).</summary>
public void DebugSeedIdxChange(int selfSeed, int oppoSeed) => Engine.DebugSeedIdxChange(selfSeed, oppoSeed);
/// <summary>Build an envelope for <paramref name="body"/> and ingest it into the engine for the
/// given seat (player == seat A). Mirrors <c>BattleNodeFlowTests.MakeEnvelopeWith</c> +
/// <c>SessionBattleEngine.Receive</c>.</summary>
@@ -420,6 +448,36 @@ internal sealed class NodeNativeBattleHarness : IDisposable
},
};
/// <summary>VERBATIM CLIENT-SEND Choice play shape — the wrapped form
/// <c>selectCard:{cardId:[&lt;tokenId&gt;], open:&lt;0|1&gt;}</c> the sender's wire actually carries
/// (data_dumps/captures/battle_test/cl1/battle-traffic.ndjson, live bid 131549100204:
/// <c>"selectCard":{"cardId":[121011010],"open":0}</c>). The shadow engine's ingest receives this
/// wrapper directly (the node strips selectCard from the opponent broadcast, so opponent-facing
/// frames never see it); <see cref="Engine.SessionBattleEngine.TranslateChoiceKeyAction"/>
/// unwraps it on the engine's own dict copy before the receiver parses keyAction. This driver
/// exists so a regression test can pin that unwrap end-to-end against the SAME shape the live
/// wire delivers, distinct from <see cref="ChoicePlayBody"/> which fast-paths the flat list.
/// <paramref name="open"/> defaults to 0 (choice hidden from opponent) — the value the live
/// capture carries; flag is dropped by the unwrap and irrelevant to resolution.</summary>
public static Dictionary<string, object?> ChoicePlayBodyWrapped(int playIdx, long playedCardId, long chosenTokenId, int open = 0) => new()
{
["playIdx"] = playIdx,
["type"] = 30,
["keyAction"] = new List<object?>
{
new Dictionary<string, object?>
{
["type"] = "Choice",
["cardId"] = playedCardId,
["selectCard"] = new Dictionary<string, object?>
{
["cardId"] = new List<object?> { chosenTokenId },
["open"] = open,
},
},
},
};
/// <summary>The engine's <c>NetworkBattleDefine.PlayActionType.EVOLUTION</c> opcode — confirmed
/// <c>= 20</c> in <c>SVSim.BattleEngine/Engine/NetworkBattleDefine.cs</c> (EVOLUTION_SELECT is 21). The
/// receiver maps the wire <c>type</c> int straight to the enum; EVOLUTION/EVOLUTION_SELECT route through