Compare commits

..

8 Commits

Author SHA1 Message Date
gamer147
7bd2c0f2d7 test(battle-node): lock relayed uList shape vs prod recv capture (line 75)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 11:20:03 -04:00
gamer147
a0aa58cfbe feat(battle-node): relay uList on PvP PlayActions
Forwards the sender's deck-sourced summons/fetches to the opponent
(closes the spin-independent slice of direct-to-field summons). uList
coexists with the synthesized knownList in the same frame.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 11:18:20 -04:00
gamer147
c0309061fa feat(battle-node): UnapprovedCardEntry + RelayUList pure transform
Verbatim uList relay shape + transform (deck-sourced summons/fetches),
mirroring RenameTargets. Not yet wired into the handler.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 11:17:10 -04:00
gamer147
61080adace test(battle-node): lock copy-op parse vs prod capture line 196
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 10:12:20 -04:00
gamer147
b6edfbcf15 feat(battle-node): reveal copy tokens on play via baseIdx resolution
PlayActionsHandler + EchoHandler now call RecordCopyTokensFrom (ordered
after plain/choice mining) to resolve a copy add's baseIdx against the
side's live idx->cardId map and record copyIdx->cardId. A copy played in a
later (or same) frame synthesizes a knownList instead of degrading.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 10:11:34 -04:00
gamer147
f9c7e6124b feat(battle-node): resolve copy-token cardIds from baseIdx (pure)
KnownListBuilder.MineCopyTokens resolves a copy add's baseIdx against the
actor's own idx->cardId map (self/other by isSelf), yielding (idx,cardId,
isSelf). Skips concrete/choice adds, string (private-group) baseIdx, and
unknown sources (degrade). Third token-reveal slice.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 10:09:36 -04:00
gamer147
5c3835f4fd feat(battle-node): reveal choice/Discover tokens to opponent
Choice/Discover-into-hand fanfares add a candidates-only token to hand; the
chosen cardId rides keyAction.selectCard on the generating play, not the
orderList add op. Record idx->chosenCardId at generation (candidate-membership
join) so the later play reveals the real identity via the existing
BuildPlayedCard path; forward {type,cardId} to the opponent and strip
selectCard for hidden (open:0) picks (pass through for open:1, provisional).

- KnownListBuilder.MineChoicePicks + StripKeyActionForOpponent (pure)
- BattleSessionState.RecordChoicePicksFrom (reuses IdxToCardId, no new state)
- PlayActionsBroadcastBody.keyAction + KeyActionEntry/SelectCardEntry
- PlayActionsHandler wires both; EchoHandler unchanged (picks ride the send)

Tests (TDD red->green): 8 KnownListBuilder + 2 dispatch + 2 conformance
(shape-locked to tk2_regular L151 generation / L193 reveal). Full suite 976/0.

Spec: docs/superpowers/specs/2026-06-04-battle-node-choice-token-reveal-design.md

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 08:53:48 -04:00
gamer147
62251482e4 feat(battle-node): cross-side gift + Echo-frame token mining
Close the two generated-token gaps that desynced PvP live test #3 (the
Forestcraft Fairy), both sourced from the 2026-06-03 decomp-validation table.

- MineAddOps now returns (idx, cardId, isSelf) and no longer drops isSelf:0.
  isSelf is the sender's perspective tag on CardObj.IsPlayer (RegisterToken.cs:22)
  and a card has one CardObj.Index, so an isSelf:0 add is the opponent's card.
- New shared BattleSessionState.RecordTokensFrom routes isSelf:1 -> sender,
  isSelf:0 -> opponent (the gift lives in the recipient's map, consulted when
  they play it). PlayActionsHandler delegates to it.
- EchoHandler now mines via the same helper but still returns no routes. An
  Echo's orderList carries the same add-op shape as a send (MakeEchoData ->
  MakeCommonSendAndEchoCardData), so MineAddOps applies verbatim; mining != relaying.

Choice/copy/private-group adds stay skipped (no concrete cardId). Full solution
963/963 green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 07:59:46 -04:00
8 changed files with 1216 additions and 34 deletions

View File

@@ -5,13 +5,34 @@ namespace SVSim.BattleNode.Protocol.Bodies;
/// <summary>Opponent-facing PlayActions frame the node synthesizes from the active player's
/// send. <c>KnownList</c> reveals the played card's identity (null = token reveal deferred, see
/// the deterministic-turn slice). <c>OppoTargetList</c> is the renamed <c>targetList</c>
/// (independent of KnownList — a targeted hand play carries both). Both omitted when null via the
/// envelope's WhenWritingNull policy.</summary>
/// (independent of KnownList — a targeted hand play carries both). <c>KeyAction</c> forwards a
/// choice/Discover play's <c>{type,cardId}</c> so the opponent renders the choice-token generation;
/// the pick (<c>selectCard</c>) is stripped for a hidden (open:0) draw-to-hand choice. <c>UList</c>
/// forwards the sender's unapproved-movement list (deck-sourced summons/fetches) verbatim. All are
/// omitted when null via the envelope's WhenWritingNull policy (a vanilla play carries none).</summary>
public sealed record PlayActionsBroadcastBody(
[property: JsonPropertyName("playIdx")] int PlayIdx,
[property: JsonPropertyName("type")] int Type,
[property: JsonPropertyName("knownList")] IReadOnlyList<KnownCardEntry>? KnownList,
[property: JsonPropertyName("oppoTargetList")] IReadOnlyList<OppoTargetEntry>? OppoTargetList) : IMsgBody;
[property: JsonPropertyName("oppoTargetList")] IReadOnlyList<OppoTargetEntry>? OppoTargetList,
[property: JsonPropertyName("uList")] IReadOnlyList<UnapprovedCardEntry>? UList = null,
[property: JsonPropertyName("keyAction")] IReadOnlyList<KeyActionEntry>? KeyAction = null) : IMsgBody;
/// <summary>Opponent-facing keyAction entry for a choice/Discover play. <c>type</c>/<c>cardId</c>
/// (the GENERATING card) pass through so the opponent re-derives the candidate pool from that card's
/// skill; <c>selectCard</c> is stripped (null) for a hidden (open:0) choice — the pick stays secret
/// until the chosen card is played — and passed through for a visible (open:1) board choice (§6,
/// provisional pending live confirmation).</summary>
public sealed record KeyActionEntry(
[property: JsonPropertyName("type")] int Type,
[property: JsonPropertyName("cardId")] long CardId,
[property: JsonPropertyName("selectCard")] SelectCardEntry? SelectCard);
/// <summary>A visible choice's revealed pick: the chosen <c>cardId</c>(s) and the <c>open</c> flag.
/// Only emitted for the open:1 pass-through case (open:0 strips the whole <c>selectCard</c>).</summary>
public sealed record SelectCardEntry(
[property: JsonPropertyName("cardId")] IReadOnlyList<long> CardId,
[property: JsonPropertyName("open")] int Open);
/// <summary>One revealed card in a <c>knownList</c>. Vanilla slice fills cardId from the sender's
/// deck map and leaves spellboost 0 / attachTarget "" (cost/clan/tribe deferred to the card-master
@@ -28,3 +49,23 @@ public sealed record KnownCardEntry(
public sealed record OppoTargetEntry(
[property: JsonPropertyName("targetIdx")] int TargetIdx,
[property: JsonPropertyName("isSelf")] int IsSelf);
/// <summary>One entry in a relayed <c>uList</c> (the unapproved-movement list) — a skill-driven
/// card movement (fetch / search / summon-from-deck / discard-reveal) the node forwards VERBATIM
/// (bullet-3 audit F1; the node makes no reveal decision — <c>cardId</c> presence is the sender's
/// call). The first five fields are always emitted; the rest are conditional in
/// <c>SendCardDataMaker.MakeUList</c> (cardId when revealed, clan/cost when set, etc.) and omit when
/// null. <c>isSelf</c> is actor-relative and passes through unchanged (F2).</summary>
public sealed record UnapprovedCardEntry(
[property: JsonPropertyName("idxList")] IReadOnlyList<int> IdxList,
[property: JsonPropertyName("from")] int From,
[property: JsonPropertyName("to")] int To,
[property: JsonPropertyName("isSelf")] int IsSelf,
[property: JsonPropertyName("skill")] string Skill,
[property: JsonPropertyName("cardId")] long? CardId = null,
[property: JsonPropertyName("clan")] int? Clan = null,
[property: JsonPropertyName("cost")] int? Cost = null,
[property: JsonPropertyName("skillKeyCardIdx")] IReadOnlyList<int>? SkillKeyCardIdx = null,
[property: JsonPropertyName("randomTargetIdx")] IReadOnlyList<int>? RandomTargetIdx = null,
[property: JsonPropertyName("isInvoke")] int? IsInvoke = null,
[property: JsonPropertyName("attachTarget")] string? AttachTarget = null);

View File

@@ -41,4 +41,47 @@ internal sealed class BattleSessionState
GetOrSeedDeckMap(side); // ensure the per-side map exists (deck-seeded)
IdxToCardId[side][idx] = cardId; // overwrite-on-conflict: latest identity wins
}
/// <summary>Mine generated-token identities from a sender's <c>orderList</c> <c>add</c> ops and
/// record each into the correct side's map. <c>isSelf:1</c> → the sender's own token (<paramref
/// name="from"/>); <c>isSelf:0</c> → a cross-side gift living at that idx in the OPPONENT's index
/// space (<paramref name="other"/>) — <c>isSelf</c> is the sender's perspective tag on
/// <c>CardObj.IsPlayer</c> (RegisterToken.cs:22), and a card has a single <c>CardObj.Index</c>, so
/// the gifted idx is the same slot in the recipient's own map (the one consulted when the recipient
/// later plays it). Shared by <c>PlayActionsHandler</c> and <c>EchoHandler</c> — an Echo's orderList
/// carries the same add-op shape (<c>SendCardDataMaker.MakeEchoData</c>), so both mine identically;
/// Echo is mined but never relayed.</summary>
public void RecordTokensFrom(IBattleParticipant from, IBattleParticipant other, object? orderList)
{
foreach (var (idx, cardId, isSelf) in KnownListBuilder.MineAddOps(orderList))
RecordToken(isSelf == 1 ? from : other, idx, cardId);
}
/// <summary>Mine + record choice/Discover-token picks (<see cref="KnownListBuilder.MineChoicePicks"/>)
/// into the correct side's map, by the same <c>isSelf</c> routing as <see cref="RecordTokensFrom"/>.
/// The chosen cardId rides the generating send's <c>keyAction.selectCard</c> (not the orderList add
/// op, which carries candidates only); recorded regardless of the choice's <c>open</c> visibility —
/// an unplayed idx is never queried, so a stray record is harmless.</summary>
public void RecordChoicePicksFrom(IBattleParticipant from, IBattleParticipant other, object? orderList, object? keyAction)
{
foreach (var (idx, cardId, isSelf) in KnownListBuilder.MineChoicePicks(orderList, keyAction))
RecordToken(isSelf == 1 ? from : other, idx, cardId);
}
/// <summary>Mine + record copy/clone-token identities (<see cref="KnownListBuilder.MineCopyTokens"/>)
/// into the correct side's map. A copy's source lives at <c>baseIdx</c> in the actor's own index
/// space, so the resolution side == the record side, both selected by the same <c>isSelf</c> routing
/// as <see cref="RecordTokensFrom"/>. Passing the LIVE per-side maps (via
/// <see cref="GetOrSeedDeckMap"/>, not snapshots) lets a copy that references a plain/choice token
/// added earlier THIS frame resolve — provided this runs AFTER
/// <see cref="RecordTokensFrom"/>/<see cref="RecordChoicePicksFrom"/> (the handler orders it last).
/// Seeding both maps up front matters because a copy-only frame (no concrete/choice add) would never
/// have hit <see cref="RecordToken"/> yet, leaving the maps unseeded.</summary>
public void RecordCopyTokensFrom(IBattleParticipant from, IBattleParticipant other, object? orderList)
{
var selfMap = GetOrSeedDeckMap(from);
var otherMap = GetOrSeedDeckMap(other);
foreach (var (idx, cardId, isSelf) in KnownListBuilder.MineCopyTokens(orderList, selfMap, otherMap))
RecordToken(isSelf == 1 ? from : other, idx, cardId);
}
}

View File

@@ -1,8 +1,28 @@
using SVSim.BattleNode.Protocol;
namespace SVSim.BattleNode.Sessions.Dispatch.Handlers;
/// <summary>Echo is the receiver's per-frame ack; the client has no inbound Echo handler, so the
/// node consumes it (bullet-2 audit). Relaying would risk an echo->echo storm.</summary>
/// node never relays it (bullet-2 audit — relaying would risk an echo->echo storm). It IS mined,
/// though: an Echo's orderList carries the same add-op shape as PlayActions
/// (SendCardDataMaker.MakeEchoData -> MakeCommonSendAndEchoCardData), so it can hold a token's real
/// identity — notably the receiver's own (isSelf:1) view of a cross-side gift. We mine it (concrete
/// tokens and baseIdx copies) into the right side's idx->cardId map and still return no routes
/// (mining != relaying).</summary>
internal sealed class EchoHandler : IFrameHandler
{
public IReadOnlyList<DispatchRoute> Handle(FrameDispatchContext ctx) => Array.Empty<DispatchRoute>();
public IReadOnlyList<DispatchRoute> Handle(FrameDispatchContext ctx)
{
if (ctx.Type == BattleType.Pvp && ctx.BothAfterReady())
{
var orderList = (ctx.Env.Body as RawBody)?.Entries.GetValueOrDefault("orderList");
ctx.State.RecordTokensFrom(ctx.From, ctx.Other, orderList);
// Copy tokens ride Echo too (same add-op shape); resolve baseIdx against the side's map.
ctx.State.RecordCopyTokensFrom(ctx.From, ctx.Other, orderList);
// No RecordChoicePicksFrom here: choice picks ride keyAction.selectCard on the generating
// SEND, not the receiver's Echo (Echo carries orderList only) — the pick is already
// recorded by PlayActionsHandler. MineChoicePicks(orderList, null) would yield nothing.
}
return Array.Empty<DispatchRoute>();
}
}

View File

@@ -3,11 +3,13 @@ using SVSim.BattleNode.Protocol.Bodies;
namespace SVSim.BattleNode.Sessions.Dispatch.Handlers;
/// <summary>PvP PlayActions translator (vanilla deck-card slice). Synthesizes the opponent-facing
/// knownList from the sender's idx->cardId map + the orderList move op, renames targetList ->
/// oppoTargetList, drops orderList, consumes keyAction.
/// Token plays resolve their cardId from add ops mined on earlier frames; an un-generated token
/// idx still degrades to {playIdx,type} (no knownList). Bot drop (no rule).</summary>
/// <summary>PvP PlayActions translator. Synthesizes the opponent-facing knownList from the sender's
/// idx->cardId map + the orderList move op, renames targetList -> oppoTargetList, drops orderList,
/// and forwards a stripped keyAction for choice/Discover plays ({type,cardId}; selectCard dropped
/// for a hidden open:0 pick). Token plays resolve their cardId from add ops (concrete tokens),
/// keyAction.selectCard (choice picks), or a baseIdx copy resolved against the side's map — all mined
/// on earlier (or the same) frames; an un-generated token idx still degrades to {playIdx,type}
/// (no knownList). Bot drop (no rule).</summary>
internal sealed class PlayActionsHandler : IFrameHandler
{
public IReadOnlyList<DispatchRoute> Handle(FrameDispatchContext ctx)
@@ -20,21 +22,41 @@ internal sealed class PlayActionsHandler : IFrameHandler
var type = (int)KnownListBuilder.AsLong(entries.GetValueOrDefault("type"));
var orderList = entries.GetValueOrDefault("orderList");
var keyAction = entries.GetValueOrDefault("keyAction");
// Mine generated-token identities from this frame's add ops into the sender's idx->cardId
// map, so a token played in a LATER frame resolves its cardId (bullet-3 audit F1).
foreach (var (idx, cardId) in KnownListBuilder.MineAddOps(orderList))
ctx.State.RecordToken(ctx.From, idx, cardId);
// Mine generated-token identities from this frame's add ops into the right side's idx->cardId
// map (isSelf:1 → sender; isSelf:0 → opponent, a cross-side gift), so a token played in a LATER
// frame resolves its cardId — by whichever side ends up playing it (bullet-3 audit F1).
ctx.State.RecordTokensFrom(ctx.From, ctx.Other, orderList);
// Choice/Discover-into-hand: the chosen cardId rides keyAction.selectCard (the orderList's
// choiceAdd carries candidates only). Record idx->chosenCardId now so the later play reveals it.
ctx.State.RecordChoicePicksFrom(ctx.From, ctx.Other, orderList, keyAction);
// Copy/clone tokens: card:{baseIdx} points at a card in the actor's own index space; resolve it
// against that side's map and record copyIdx->cardId so the later play reveals it. Ordered after
// the plain/choice mining so a same-frame copy of a just-added token resolves against the live map.
ctx.State.RecordCopyTokensFrom(ctx.From, ctx.Other, orderList);
var deckMap = ctx.State.GetOrSeedDeckMap(ctx.From);
var played = KnownListBuilder.BuildPlayedCard(deckMap, playIdx, orderList);
var oppoTargets = KnownListBuilder.RenameTargets(entries.GetValueOrDefault("targetList"));
// Deck-sourced movements (fetch / search / summon-from-deck) ride the uList — a verbatim,
// separate receive slot the node forwards unchanged (bullet-3 audit F1). The node makes no
// reveal decision; cardId presence is the sender's call. Coexists with the synthesized
// knownList in the same frame (capture line 75).
var uList = KnownListBuilder.RelayUList(entries.GetValueOrDefault("uList"));
var body = new PlayActionsBroadcastBody(
PlayIdx: playIdx,
Type: type,
KnownList: played is null ? null : new[] { played },
OppoTargetList: oppoTargets);
OppoTargetList: oppoTargets,
UList: uList,
// {type,cardId} forwarded so the opponent renders the choice token; selectCard dropped
// when open==0 (hidden draw-to-hand pick). Null for a vanilla play (no keyAction).
KeyAction: KnownListBuilder.StripKeyActionForOpponent(keyAction));
var frame = ctx.Env with { Body = body };
return new[] { new DispatchRoute(ctx.Other, frame, false) };

View File

@@ -42,17 +42,19 @@ internal static class KnownListBuilder
return null;
}
/// <summary>Mine generated-token identities from the sender's <c>add</c> ops: yields
/// <c>(idx, cardId)</c> for every idx in each <c>{add:{idx:[...], isSelf:1, card:{cardId}}}</c>
/// op. Skips <c>isSelf:0</c> adds (cross-side gifts — belong in the other side's map, deferred)
/// and any add whose <c>card</c> has no concrete <c>cardId</c> — choice tokens
/// (<c>card:{candidates}</c>, <c>RegisterChoiceAdd</c>), copy tokens (<c>card:{baseIdx}</c>,
/// <c>RegisterCopyToken</c>), and private-group adds (string <c>idx</c>) — all deferred and all
/// caught by the <c>cardId</c>-key / <c>idx</c>-is-list guards. This is the only place a
/// freshly-generated card's identity exists on the wire (bullet-3 audit F1; producing code
/// <c>RegisterToken</c>/<c>RegisterActionBase</c>) — the played-card op itself never carries a
/// <c>cardId</c>.</summary>
public static IEnumerable<(int Idx, long CardId)> MineAddOps(object? orderList)
/// <summary>Mine generated-token identities from a sender's <c>add</c> ops: yields
/// <c>(idx, cardId, isSelf)</c> for every idx in each <c>{add:{idx:[...], isSelf, card:{cardId}}}</c>
/// op. <c>isSelf</c> is surfaced verbatim (the sender's perspective tag on <c>CardObj.IsPlayer</c>,
/// <c>RegisterToken.cs:22</c>) so the caller can route the identity into the correct side's map —
/// <c>isSelf:1</c> = the sender's own token, <c>isSelf:0</c> = a cross-side gift living at this idx
/// in the OPPONENT's index space (<see cref="BattleSessionState.RecordTokensFrom"/>). Skips any add
/// whose <c>card</c> has no concrete <c>cardId</c> — choice tokens (<c>card:{candidates}</c>,
/// <c>RegisterChoiceAdd</c>), copy tokens (<c>card:{baseIdx}</c>, <c>RegisterCopyToken</c>), and
/// private-group adds (string <c>idx</c>) — all deferred and all caught by the <c>cardId</c>-key /
/// <c>idx</c>-is-list guards. This is the only place a freshly-generated card's identity exists on
/// the wire (bullet-3 audit F1; producing code <c>RegisterToken</c>/<c>RegisterActionBase</c>) —
/// the played-card op itself never carries a <c>cardId</c>.</summary>
public static IEnumerable<(int Idx, long CardId, int IsSelf)> MineAddOps(object? orderList)
{
if (orderList is not IEnumerable<object?> ops) yield break;
foreach (var op in ops)
@@ -61,7 +63,7 @@ internal static class KnownListBuilder
if (!opDict.TryGetValue("add", out var addRaw) || addRaw is not IDictionary<string, object?> add) continue;
add.TryGetValue("isSelf", out var isSelfRaw);
if (AsLong(isSelfRaw) != 1) continue; // own tokens only; cross-side gifts deferred
var isSelf = (int)AsLong(isSelfRaw);
if (!add.TryGetValue("card", out var cardRaw) || cardRaw is not IDictionary<string, object?> card) continue;
if (!card.TryGetValue("cardId", out var cardIdRaw)) continue; // candidates/isChoice → no identity yet
@@ -69,10 +71,139 @@ internal static class KnownListBuilder
if (!add.TryGetValue("idx", out var idxRaw) || idxRaw is not IEnumerable<object?> idxList) continue;
foreach (var i in idxList)
yield return ((int)AsLong(i), cardId);
yield return ((int)AsLong(i), cardId, isSelf);
}
}
/// <summary>Mine choice/Discover-token identities: for each <c>isChoice</c> add op (idx, isSelf,
/// candidates), resolve its cardId from the keyAction <c>selectCard</c> pick whose cardId is in that
/// op's candidate pool. Yields <c>(idx, cardId, isSelf)</c> — same shape as <see cref="MineAddOps"/>,
/// routed by the same <see cref="BattleSessionState.RecordTokensFrom"/> rule. The pick is on
/// keyAction.selectCard, NOT the add op (RegisterChoiceAdd strips the concrete cardId,
/// <c>NetworkBattleSetupCardEvent.cs:531-543</c>); the candidate-membership join handles the single
/// case unambiguously (multi-choice: each chosen cardId matches the one choiceAdd whose candidates
/// contain it). <c>type</c>/<c>cardId</c>/<c>open</c> on the keyAction are ignored here — <c>open</c>
/// only gates the strip (<see cref="StripKeyActionForOpponent"/>), not the recording. An add whose
/// candidates contain none of the picks is skipped (defensive — no record, no desync); Echo (no
/// keyAction) yields nothing, leaving it mining-only via <see cref="MineAddOps"/>.</summary>
public static IEnumerable<(int Idx, long CardId, int IsSelf)> MineChoicePicks(object? orderList, object? keyAction)
{
if (orderList is not IEnumerable<object?> ops) yield break;
// Flatten every selectCard.cardId pick across all keyAction entries into a membership set.
var picks = new HashSet<long>();
if (keyAction is IEnumerable<object?> kaEntries)
{
foreach (var ka in kaEntries)
{
if (ka is not IDictionary<string, object?> kaDict) continue;
if (!kaDict.TryGetValue("selectCard", out var scRaw) || scRaw is not IDictionary<string, object?> sc) continue;
if (!sc.TryGetValue("cardId", out var idsRaw) || idsRaw is not IEnumerable<object?> ids) continue;
foreach (var id in ids) picks.Add(AsLong(id));
}
}
if (picks.Count == 0) yield break;
foreach (var op in ops)
{
if (op is not IDictionary<string, object?> opDict) continue;
if (!opDict.TryGetValue("add", out var addRaw) || addRaw is not IDictionary<string, object?> add) continue;
if (!add.ContainsKey("isChoice")) continue;
if (!add.TryGetValue("card", out var cardRaw) || cardRaw is not IDictionary<string, object?> card) continue;
if (!card.TryGetValue("candidates", out var candRaw) || candRaw is not IEnumerable<object?> candidates) continue;
// The chosen cardId is the candidate that the active player picked (∈ picks). One per op.
long? chosen = null;
foreach (var c in candidates)
{
var cid = AsLong(c);
if (picks.Contains(cid)) { chosen = cid; break; }
}
if (chosen is null) continue; // no pick in this op's pool — skip (no desync, just no record)
add.TryGetValue("isSelf", out var isSelfRaw);
var isSelf = (int)AsLong(isSelfRaw);
if (!add.TryGetValue("idx", out var idxRaw) || idxRaw is not IEnumerable<object?> idxList) continue;
foreach (var i in idxList)
yield return ((int)AsLong(i), chosen.Value, isSelf);
}
}
/// <summary>Mine copy/clone-token identities: for each copy <c>add</c> op
/// (<c>{idx:[...], isSelf, card:{baseIdx, isPremium}}</c>), resolve its cardId from the appropriate
/// side's idx->cardId map. The copied card lives at <c>baseIdx</c> in the actor's OWN index space —
/// <c>RegisterCopyToken</c> is emitted only for <c>!IsReferenceOpponenCard</c>
/// (<c>NetworkBattleManagerBase.cs:1106</c>); a cross-side copy sends a concrete <c>cardId</c> via a
/// plain <c>RegisterToken</c> instead (handled by <see cref="MineAddOps"/>). Yields
/// <c>(idx, cardId, isSelf)</c> — same shape as <see cref="MineAddOps"/>, routed by the same
/// <see cref="BattleSessionState.RecordTokensFrom"/> rule: <c>isSelf:1</c> resolves+records into the
/// sender's map (<paramref name="selfMap"/>), <c>isSelf:0</c> into the opponent's
/// (<paramref name="otherMap"/>). Skips an add with a concrete <c>cardId</c> (→ MineAddOps), one with
/// <c>candidates</c> (→ MineChoicePicks), a <c>string</c> <c>baseIdx</c> (private-group copy,
/// <c>RegisterCopyToken.cs:19-22</c>), and a <c>baseIdx</c> absent from the chosen map (unknown source
/// → degrade, no desync). <c>isPremium</c> (IsFoil) is cosmetic and ignored.</summary>
public static IEnumerable<(int Idx, long CardId, int IsSelf)> MineCopyTokens(
object? orderList,
IReadOnlyDictionary<int, long> selfMap,
IReadOnlyDictionary<int, long> otherMap)
{
if (orderList is not IEnumerable<object?> ops) yield break;
foreach (var op in ops)
{
if (op is not IDictionary<string, object?> opDict) continue;
if (!opDict.TryGetValue("add", out var addRaw) || addRaw is not IDictionary<string, object?> add) continue;
if (!add.TryGetValue("card", out var cardRaw) || cardRaw is not IDictionary<string, object?> card) continue;
if (card.ContainsKey("cardId")) continue; // concrete token → MineAddOps
if (!card.TryGetValue("baseIdx", out var baseRaw)) continue; // not a copy (candidates → MineChoicePicks)
if (baseRaw is string) continue; // private-group copy → string baseIdx, skip
var baseIdx = (int)AsLong(baseRaw);
add.TryGetValue("isSelf", out var isSelfRaw);
var isSelf = (int)AsLong(isSelfRaw);
var map = isSelf == 1 ? selfMap : otherMap;
if (!map.TryGetValue(baseIdx, out var cardId)) continue; // unknown source → degrade
if (!add.TryGetValue("idx", out var idxRaw) || idxRaw is not IEnumerable<object?> idxList) continue;
foreach (var i in idxList)
yield return ((int)AsLong(i), cardId, isSelf);
}
}
/// <summary>Map an inbound keyAction (the active player's send) to the opponent-facing list:
/// for each Choice(1)/HaveBeforeSkillChoice(5) entry, keep <c>{type,cardId}</c> and drop
/// <c>selectCard</c> when its <c>open==0</c> (hidden draw-to-hand pick stays secret), pass it
/// through when <c>open==1</c> (visible board choice — provisional reveal-immediately, §6).
/// Non-choice KeyActionTypes are dropped (current behavior) until their own specs. Returns null
/// for absent/empty keyAction or when every entry was dropped (vanilla play unchanged).</summary>
public static IReadOnlyList<KeyActionEntry>? StripKeyActionForOpponent(object? keyAction)
{
if (keyAction is not IEnumerable<object?> entries) return null;
var result = new List<KeyActionEntry>();
foreach (var e in entries)
{
if (e is not IDictionary<string, object?> d) continue;
d.TryGetValue("type", out var typeRaw);
var type = (int)AsLong(typeRaw);
if (type is not (1 or 5)) continue; // only Choice / HaveBeforeSkillChoice handled
d.TryGetValue("cardId", out var cardIdRaw);
var cardId = AsLong(cardIdRaw);
SelectCardEntry? selectCard = null;
if (d.TryGetValue("selectCard", out var scRaw) && scRaw is IDictionary<string, object?> sc)
{
sc.TryGetValue("open", out var openRaw);
var open = (int)AsLong(openRaw);
if (open != 0 && sc.TryGetValue("cardId", out var idsRaw) && idsRaw is IEnumerable<object?> ids)
selectCard = new SelectCardEntry(ids.Select(AsLong).ToList(), open);
}
result.Add(new KeyActionEntry(type, cardId, selectCard));
}
return result.Count == 0 ? null : result;
}
/// <summary>Rename <c>targetList</c> -> <c>oppoTargetList</c>; <c>isSelf</c> is actor-relative
/// and passes through unchanged (F2). Null for a missing/empty list.</summary>
public static IReadOnlyList<OppoTargetEntry>? RenameTargets(object? targetList)
@@ -91,6 +222,49 @@ internal static class KnownListBuilder
return result.Count == 0 ? null : result;
}
/// <summary>Map the sender's <c>uList</c> (unapproved-movement list) to the opponent-facing
/// <see cref="UnapprovedCardEntry"/> list, VERBATIM — the node makes no reveal decision; it forwards
/// whatever the sender emitted (cardId present = the sender chose to reveal). The five always-present
/// fields (idxList/from/to/isSelf/skill) map directly; the conditionals map only when their key is
/// present (mirroring the emitter, <c>SendCardDataMaker.MakeUList:188-244</c>). Null for an
/// absent/empty list (mirrors <see cref="RenameTargets"/>). isSelf/place-states pass through unchanged
/// (F2; same verbatim assumption already shipped for the synthesized knownList).</summary>
public static IReadOnlyList<UnapprovedCardEntry>? RelayUList(object? uList)
{
if (uList is not IEnumerable<object?> entries) return null;
var result = new List<UnapprovedCardEntry>();
foreach (var e in entries)
{
if (e is not IDictionary<string, object?> d) continue;
d.TryGetValue("idxList", out var idxRaw);
d.TryGetValue("from", out var fromRaw);
d.TryGetValue("to", out var toRaw);
d.TryGetValue("isSelf", out var isSelfRaw);
d.TryGetValue("skill", out var skillRaw);
result.Add(new UnapprovedCardEntry(
IdxList: AsIntList(idxRaw) ?? new List<int>(),
From: (int)AsLong(fromRaw),
To: (int)AsLong(toRaw),
IsSelf: (int)AsLong(isSelfRaw),
Skill: skillRaw as string ?? "",
CardId: d.TryGetValue("cardId", out var c) ? AsLong(c) : null,
Clan: d.TryGetValue("clan", out var cl) ? (int)AsLong(cl) : null,
Cost: d.TryGetValue("cost", out var co) ? (int)AsLong(co) : null,
SkillKeyCardIdx: AsIntList(d.TryGetValue("skillKeyCardIdx", out var sk) ? sk : null),
RandomTargetIdx: AsIntList(d.TryGetValue("randomTargetIdx", out var rt) ? rt : null),
IsInvoke: d.TryGetValue("isInvoke", out var iv) ? (int)AsLong(iv) : null,
AttachTarget: d.TryGetValue("attachTarget", out var at) ? at as string : null));
}
return result.Count == 0 ? null : result;
}
/// <summary>Coerce a boxed RawBody list leaf to <c>List&lt;int&gt;</c> (each element via
/// <see cref="AsLong"/>); null when the value isn't a list.</summary>
private static IReadOnlyList<int>? AsIntList(object? value) =>
value is IEnumerable<object?> items ? items.Select(i => (int)AsLong(i)).ToList() : null;
/// <summary>Coerce a boxed RawBody numeric leaf (long/int/double/decimal/string) to long; 0 for
/// null/unparseable.</summary>
public static long AsLong(object? value) => value switch

View File

@@ -322,7 +322,7 @@ public class CaptureConformanceTests
["card"] = new Dictionary<string, object?> { ["cardId"] = 900811111L } } },
};
var map = new Dictionary<int, long>();
foreach (var (idx, cardId) in SVSim.BattleNode.Sessions.Dispatch.KnownListBuilder.MineAddOps(generatingOrderList))
foreach (var (idx, cardId, _) in SVSim.BattleNode.Sessions.Dispatch.KnownListBuilder.MineAddOps(generatingOrderList))
map[idx] = cardId;
var playOrderList = new List<object?>
@@ -352,6 +352,190 @@ public class CaptureConformanceTests
Assert.That(ourEntry.GetProperty("cardId").GetInt64(), Is.EqualTo(900811111L));
Assert.That(ourEntry.GetProperty("to").GetInt32(), Is.EqualTo(20));
}
[Test]
public void RelayedUList_matches_prod_recv_uList_shape()
{
// Prod recv PlayActions uList entry (battle-traffic_tk2_regular.ndjson:75) — a deck-fetch the
// official node relayed to the opponent. We forward it verbatim; assert the always-present keys
// round-trip with matching value-kinds (capture ⊆ ours).
const string prodEntry = """
{ "idxList": [16, 22], "from": 0, "to": 10, "isSelf": 1, "skill": "37|36|0" }
""";
var uListRaw = new List<object?>
{
new Dictionary<string, object?>
{
["idxList"] = new List<object?> { 16L, 22L },
["from"] = 0L, ["to"] = 10L, ["isSelf"] = 1L, ["skill"] = "37|36|0",
},
};
var relayed = SVSim.BattleNode.Sessions.Dispatch.KnownListBuilder.RelayUList(uListRaw);
Assert.That(relayed, Is.Not.Null);
var body = new SVSim.BattleNode.Protocol.Bodies.PlayActionsBroadcastBody(
PlayIdx: 37, Type: 30, KnownList: null, OppoTargetList: null, UList: relayed);
var env = new MsgEnvelope(NetworkBattleUri.PlayActions, ViewerId: 1, Uuid: "u", Bid: null, Try: 0,
Cat: EmitCategory.Battle, PubSeq: null, PlaySeq: null, Body: body);
using var ourDoc = JsonDocument.Parse(MsgEnvelope.ToJson(env));
var ourEntry = ourDoc.RootElement.GetProperty("uList")[0];
using var prodDoc = JsonDocument.Parse(prodEntry);
foreach (var key in new[] { "idxList", "from", "to", "isSelf", "skill" })
{
Assert.That(ourEntry.TryGetProperty(key, out var ours), Is.True, $"uList entry missing '{key}'");
var prodVal = prodDoc.RootElement.GetProperty(key);
Assert.That(ours.ValueKind, Is.EqualTo(prodVal.ValueKind), $"'{key}' type category mismatch");
}
Assert.That(ourEntry.GetProperty("idxList").GetArrayLength(), Is.EqualTo(2));
Assert.That(ourEntry.GetProperty("skill").GetString(), Is.EqualTo("37|36|0"));
// No cardId on a hidden fetch — confirm we didn't invent one.
Assert.That(ourEntry.TryGetProperty("cardId", out _), Is.False, "hidden fetch carries no cardId");
}
[Test]
public void MineCopyTokens_extracts_the_prod_capture_copy_op_shape()
{
// Prod copy op (battle-traffic_tk2_regular.ndjson:196) — the ONLY copy op in any capture, an
// isSelf:0 Echo: {add:{idx:[49], isSelf:0, card:{baseIdx:21, isPremium:0}}}. No later play-reveal
// of idx 49 exists, so this locks the copy-op PARSE + map-resolution only (spec §5), not a reveal.
var orderList = new List<object?>
{
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 49L }, ["isSelf"] = 0L,
["card"] = new Dictionary<string, object?> { ["baseIdx"] = 21L, ["isPremium"] = 0L } } },
};
// baseIdx 21 lives in the opponent's (isSelf:0 -> otherMap) index space. The capture never reveals
// idx 21's cardId, so seed a sentinel; this verifies parse + resolution of the op shape, not an id.
var otherMap = new Dictionary<int, long> { [21] = 123_456_789L };
var mined = SVSim.BattleNode.Sessions.Dispatch.KnownListBuilder
.MineCopyTokens(orderList, new Dictionary<int, long>(), otherMap)
.ToList();
Assert.That(mined, Is.EquivalentTo(new[] { (49, 123_456_789L, 0) }));
}
[Test]
public void SynthesizedChoiceGeneration_matches_prod_recv_keyAction_and_knownList_shape()
{
// Prod recv PlayActions for the generating card play (battle-traffic_tk2_regular.ndjson:151):
// keyAction is {type,cardId} only (selectCard stripped for the hidden open:0 choice); knownList
// reveals the generating DECK card. The choiceAdd lands a hidden token at idx 46 (candidates).
// Subset check covers playIdx/type/keyAction — the parts we own; knownList idx/cardId/to are
// asserted explicitly below (cost/clan/tribe are deferred, re-derived by the receiver from cardId).
const string prodFrame = """
{ "playIdx": 18, "type": 30,
"keyAction": [ { "type": 1, "cardId": 810014030 } ] }
""";
var deckMap = new Dictionary<int, long> { [18] = 810014030L };
var orderList = new List<object?>
{
new Dictionary<string, object?> { ["move"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 18L }, ["isSelf"] = 1L, ["from"] = 10L, ["to"] = 30L } },
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 46L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?>
{ ["candidates"] = new List<object?> { 810041260L, 101041020L } },
["isChoice"] = "1" } },
};
var keyActionIn = new List<object?>
{
new Dictionary<string, object?>
{
["type"] = 1L, ["cardId"] = 810014030L,
["selectCard"] = new Dictionary<string, object?>
{ ["cardId"] = new List<object?> { 810041260L }, ["open"] = 0L },
}
};
var played = SVSim.BattleNode.Sessions.Dispatch.KnownListBuilder.BuildPlayedCard(deckMap, 18, orderList);
var keyActionOut = SVSim.BattleNode.Sessions.Dispatch.KnownListBuilder.StripKeyActionForOpponent(keyActionIn);
var body = new SVSim.BattleNode.Protocol.Bodies.PlayActionsBroadcastBody(
PlayIdx: 18, Type: 30, KnownList: new[] { played! }, OppoTargetList: null, KeyAction: keyActionOut);
var env = new MsgEnvelope(NetworkBattleUri.PlayActions, ViewerId: 1, Uuid: "u", Bid: null, Try: 0,
Cat: EmitCategory.Battle, PubSeq: null, PlaySeq: null, Body: body);
using var ourDoc = JsonDocument.Parse(MsgEnvelope.ToJson(env));
using var prodDoc = JsonDocument.Parse(prodFrame);
var failures = new List<string>();
CompareSubset(prodDoc.RootElement, ourDoc.RootElement, "PlayActions", isRoot: true, failures);
Assert.That(failures, Is.Empty, string.Join("\n", failures));
// The hidden pick must NOT leak: keyAction[0] carries no selectCard.
var ourKa = ourDoc.RootElement.GetProperty("keyAction")[0];
Assert.That(ourKa.TryGetProperty("selectCard", out _), Is.False, "selectCard must be stripped for open:0");
Assert.That(ourKa.GetProperty("type").GetInt32(), Is.EqualTo(1));
Assert.That(ourKa.GetProperty("cardId").GetInt64(), Is.EqualTo(810014030L));
// The generating deck card reveals on its own play (idx 18 -> 810014030, to 30). cost/clan/tribe
// are deferred (receiver re-derives from cardId), so only idx/cardId/to are checked — as in the
// sibling SynthesizedKnownList_* tests.
var ourKnown = ourDoc.RootElement.GetProperty("knownList")[0];
Assert.That(ourKnown.GetProperty("idx").GetInt32(), Is.EqualTo(18));
Assert.That(ourKnown.GetProperty("cardId").GetInt64(), Is.EqualTo(810014030L));
Assert.That(ourKnown.GetProperty("to").GetInt32(), Is.EqualTo(30));
}
[Test]
public void SynthesizedChoiceReveal_matches_prod_recv_knownList_shape()
{
// Prod recv PlayActions for the chosen token play (battle-traffic_tk2_regular.ndjson:193):
// knownList:[{idx:46, cardId:810041260,...}] — the pick recorded at generation, revealed on play.
const string prodEntry = """
{ "idx": 46, "cardId": 810041260, "to": 20, "cost": 5, "clan": 0, "tribe": "0", "spellboost": 0, "attachTarget": "" }
""";
// Mine the pick from the generating frame (choiceAdd ∩ selectCard), then build the played entry.
var generatingOrderList = new List<object?>
{
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 46L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?>
{ ["candidates"] = new List<object?> { 810041260L, 101041020L } },
["isChoice"] = "1" } },
};
var keyAction = new List<object?>
{
new Dictionary<string, object?>
{
["type"] = 1L, ["cardId"] = 810014030L,
["selectCard"] = new Dictionary<string, object?>
{ ["cardId"] = new List<object?> { 810041260L }, ["open"] = 0L },
}
};
var map = new Dictionary<int, long>();
foreach (var (idx, cardId, _) in SVSim.BattleNode.Sessions.Dispatch.KnownListBuilder.MineChoicePicks(generatingOrderList, keyAction))
map[idx] = cardId;
var playOrderList = new List<object?>
{
new Dictionary<string, object?> { ["move"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 46L }, ["isSelf"] = 1L, ["from"] = 10L, ["to"] = 20L } },
};
var entry = SVSim.BattleNode.Sessions.Dispatch.KnownListBuilder.BuildPlayedCard(map, 46, playOrderList);
Assert.That(entry, Is.Not.Null, "the mined choice pick resolves to a knownList entry");
var body = new SVSim.BattleNode.Protocol.Bodies.PlayActionsBroadcastBody(
PlayIdx: 46, Type: 30, KnownList: new[] { entry! }, OppoTargetList: null);
var env = new MsgEnvelope(NetworkBattleUri.PlayActions, ViewerId: 1, Uuid: "u", Bid: null, Try: 0,
Cat: EmitCategory.Battle, PubSeq: null, PlaySeq: null, Body: body);
using var ourDoc = JsonDocument.Parse(MsgEnvelope.ToJson(env));
var ourEntry = ourDoc.RootElement.GetProperty("knownList")[0];
using var prodDoc = JsonDocument.Parse(prodEntry);
foreach (var key in new[] { "idx", "cardId", "to" })
{
Assert.That(ourEntry.TryGetProperty(key, out var ours), Is.True, $"knownList entry missing '{key}'");
var prodVal = prodDoc.RootElement.GetProperty(key);
Assert.That(ours.ValueKind, Is.EqualTo(prodVal.ValueKind), $"'{key}' type category mismatch");
}
Assert.That(ourEntry.GetProperty("cardId").GetInt64(), Is.EqualTo(810041260L));
Assert.That(ourEntry.GetProperty("to").GetInt32(), Is.EqualTo(20));
}
}
/// <summary>

View File

@@ -249,6 +249,58 @@ public class BattleSessionDispatchTests
Assert.That(pb.OppoTargetList[0].IsSelf, Is.EqualTo(0));
}
[Test]
public void Pvp_PlayActions_relays_uList_verbatim()
{
// A deck-fetch rides the uList (battle-traffic_tk2_regular.ndjson:75); the node forwards it
// verbatim alongside the synthesized knownList for the played card.
var (s, a, b) = NewPvpSession();
DriveToAfterReady(s, a);
DriveToAfterReady(s, b);
var body = MoveOrderList(idx: 3, from: 10, to: 20);
body["playIdx"] = 3L;
body["type"] = 30L;
body["uList"] = new List<object?>
{
new Dictionary<string, object?>
{
["idxList"] = new List<object?> { 16L, 22L },
["from"] = 0L, ["to"] = 10L, ["isSelf"] = 1L, ["skill"] = "37|36|0",
},
};
var routes = s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, body));
Assert.That(routes.Count, Is.EqualTo(1));
Assert.That(routes[0].Target, Is.SameAs(b));
var pb = (PlayActionsBroadcastBody)routes[0].Frame.Body;
Assert.That(pb.KnownList!.Count, Is.EqualTo(1), "played card still synthesized in the same frame");
Assert.That(pb.UList, Is.Not.Null);
Assert.That(pb.UList!.Count, Is.EqualTo(1));
Assert.That(pb.UList[0].IdxList, Is.EqualTo(new[] { 16, 22 }));
Assert.That(pb.UList[0].From, Is.EqualTo(0));
Assert.That(pb.UList[0].To, Is.EqualTo(10));
Assert.That(pb.UList[0].IsSelf, Is.EqualTo(1));
Assert.That(pb.UList[0].Skill, Is.EqualTo("37|36|0"));
}
[Test]
public void Pvp_PlayActions_without_uList_leaves_it_null()
{
var (s, a, b) = NewPvpSession();
DriveToAfterReady(s, a);
DriveToAfterReady(s, b);
var body = MoveOrderList(idx: 3, from: 10, to: 20);
body["playIdx"] = 3L;
body["type"] = 30L;
var routes = s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, body));
var pb = (PlayActionsBroadcastBody)routes[0].Frame.Body;
Assert.That(pb.UList, Is.Null);
}
[Test]
public void Pvp_PlayActions_ungenerated_token_idx_degrades_to_no_knownList()
{
@@ -311,6 +363,314 @@ public class BattleSessionDispatchTests
Assert.That(pb.KnownList[0].To, Is.EqualTo(20));
}
[Test]
public void Pvp_PlayActions_cross_side_gift_is_revealed_when_the_opponent_plays_it()
{
var (s, a, b) = NewPvpSession();
DriveToAfterReady(s, a);
DriveToAfterReady(s, b);
// A plays a card whose effect GIFTS B a token at idx 31 (isSelf:0 — from A's perspective the
// card lives in the OPPONENT's index space; RegisterToken.cs:22 sets isSelf = CardObj.IsPlayer).
// The node must record it into B's map, not A's.
var gift = new Dictionary<string, object?>
{
["playIdx"] = 3L,
["type"] = 30L,
["orderList"] = new List<object?>
{
new Dictionary<string, object?> { ["move"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 3L }, ["isSelf"] = 1L, ["from"] = 10L, ["to"] = 30L } },
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 31L }, ["isSelf"] = 0L,
["card"] = new Dictionary<string, object?> { ["cardId"] = 900111010L } } },
},
};
s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, gift));
// Later, B plays the gifted token idx 31 (hand 10 -> field 20). A must see its real identity.
var play = MoveOrderList(idx: 31, from: 10, to: 20);
play["playIdx"] = 31L;
play["type"] = 30L;
var routes = s.ComputeFrames(b, EnvWith(NetworkBattleUri.PlayActions, play));
var pb = (PlayActionsBroadcastBody)routes[0].Frame.Body;
Assert.That(routes[0].Target, Is.SameAs(a));
Assert.That(pb.KnownList, Is.Not.Null, "the gifted token's identity was recorded into B's map");
Assert.That(pb.KnownList!.Single().Idx, Is.EqualTo(31));
Assert.That(pb.KnownList[0].CardId, Is.EqualTo(900_111_010L), "mined cross-side gift cardId");
Assert.That(pb.KnownList[0].To, Is.EqualTo(20));
}
[Test]
public void Pvp_PlayActions_reveals_copy_token_generated_in_an_earlier_frame()
{
var (s, a, b) = NewPvpSession();
DriveToAfterReady(s, a);
DriveToAfterReady(s, b);
// Frame 1: A plays deck card idx 3; its fanfare ADDS a concrete token idx 31 (cardId 900_111_010)
// to A's hand (limbo 50 -> hand 10).
var gen = new Dictionary<string, object?>
{
["playIdx"] = 3L, ["type"] = 30L,
["orderList"] = new List<object?>
{
new Dictionary<string, object?> { ["move"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 3L }, ["isSelf"] = 1L, ["from"] = 10L, ["to"] = 30L } },
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 31L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?> { ["cardId"] = 900_111_010L } } },
new Dictionary<string, object?> { ["move"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 31L }, ["isSelf"] = 1L, ["from"] = 50L, ["to"] = 10L } },
},
};
s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, gen));
// Frame 2: A plays deck card idx 4; its effect COPIES the token at idx 31 into a new token idx 32
// (card:{baseIdx:31}) in A's hand.
var copy = new Dictionary<string, object?>
{
["playIdx"] = 4L, ["type"] = 30L,
["orderList"] = new List<object?>
{
new Dictionary<string, object?> { ["move"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 4L }, ["isSelf"] = 1L, ["from"] = 10L, ["to"] = 30L } },
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 32L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?> { ["baseIdx"] = 31L, ["isPremium"] = 0L } } },
new Dictionary<string, object?> { ["move"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 32L }, ["isSelf"] = 1L, ["from"] = 50L, ["to"] = 10L } },
},
};
s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, copy));
// Frame 3: A plays the copy token idx 32 from hand (10) to field (20).
var play = MoveOrderList(idx: 32, from: 10, to: 20);
play["playIdx"] = 32L; play["type"] = 30L;
var routes = s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, play));
var pb = (PlayActionsBroadcastBody)routes[0].Frame.Body;
Assert.That(pb.PlayIdx, Is.EqualTo(32));
Assert.That(pb.KnownList, Is.Not.Null, "the copy's identity was resolved from baseIdx and remembered");
Assert.That(pb.KnownList!.Single().Idx, Is.EqualTo(32));
Assert.That(pb.KnownList[0].CardId, Is.EqualTo(900_111_010L), "copy resolved to its source token's cardId");
Assert.That(pb.KnownList[0].To, Is.EqualTo(20));
}
[Test]
public void Pvp_PlayActions_copy_of_a_token_added_in_the_same_frame_resolves()
{
var (s, a, b) = NewPvpSession();
DriveToAfterReady(s, a);
DriveToAfterReady(s, b);
// One frame: A's play ADDS concrete token idx 40 (cardId 900_222_020), then COPIES it to idx 41
// (card:{baseIdx:40}) — copy op AFTER the concrete add in the same orderList. The copy must
// resolve against the live map (copy mining runs after plain mining).
var frame = new Dictionary<string, object?>
{
["playIdx"] = 3L, ["type"] = 30L,
["orderList"] = new List<object?>
{
new Dictionary<string, object?> { ["move"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 3L }, ["isSelf"] = 1L, ["from"] = 10L, ["to"] = 30L } },
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 40L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?> { ["cardId"] = 900_222_020L } } },
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 41L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?> { ["baseIdx"] = 40L, ["isPremium"] = 0L } } },
},
};
s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, frame));
// Later: A plays the copy idx 41 (hand 10 -> field 20). Reveal proves same-frame chaining.
var play = MoveOrderList(idx: 41, from: 10, to: 20);
play["playIdx"] = 41L; play["type"] = 30L;
var routes = s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, play));
var pb = (PlayActionsBroadcastBody)routes[0].Frame.Body;
Assert.That(pb.KnownList, Is.Not.Null, "copy of a same-frame add resolved against the live map");
Assert.That(pb.KnownList!.Single().CardId, Is.EqualTo(900_222_020L));
}
[Test]
public void Pvp_PlayActions_copy_with_unknown_baseIdx_degrades_to_no_knownList()
{
var (s, a, b) = NewPvpSession();
DriveToAfterReady(s, a);
DriveToAfterReady(s, b);
// A's play copies a baseIdx (99) that was never recorded → no identity to resolve.
var frame = new Dictionary<string, object?>
{
["playIdx"] = 3L, ["type"] = 30L,
["orderList"] = new List<object?>
{
new Dictionary<string, object?> { ["move"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 3L }, ["isSelf"] = 1L, ["from"] = 10L, ["to"] = 30L } },
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 32L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?> { ["baseIdx"] = 99L, ["isPremium"] = 0L } } },
new Dictionary<string, object?> { ["move"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 32L }, ["isSelf"] = 1L, ["from"] = 50L, ["to"] = 10L } },
},
};
s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, frame));
var play = MoveOrderList(idx: 32, from: 10, to: 20);
play["playIdx"] = 32L; play["type"] = 30L;
var routes = s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, play));
var pb = (PlayActionsBroadcastBody)routes[0].Frame.Body;
Assert.That(pb.KnownList, Is.Null, "unknown baseIdx → no record → degrade to {playIdx,type}");
}
[Test]
public void Pvp_Echo_mines_copy_token_for_a_later_reveal()
{
var (s, a, b) = NewPvpSession();
DriveToAfterReady(s, a);
DriveToAfterReady(s, b);
// Frame 1: A plays a card adding a concrete token idx 31 (cardId 900_333_030) to A's hand.
var gen = new Dictionary<string, object?>
{
["playIdx"] = 3L, ["type"] = 30L,
["orderList"] = new List<object?>
{
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 31L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?> { ["cardId"] = 900_333_030L } } },
},
};
s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, gen));
// Frame 2: B sends an Echo describing a copy of A's idx 31 (isSelf:0 from B = the opponent A's
// index space) into a new token idx 32. Echo is mined but returns no routes.
var echo = new Dictionary<string, object?>
{
["playIdx"] = 5L, ["type"] = 31L,
["orderList"] = new List<object?>
{
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 32L }, ["isSelf"] = 0L,
["card"] = new Dictionary<string, object?> { ["baseIdx"] = 31L, ["isPremium"] = 0L } } },
},
};
var echoRoutes = s.ComputeFrames(b, EnvWith(NetworkBattleUri.Echo, echo));
Assert.That(echoRoutes, Is.Empty, "Echo is mined, never relayed");
// Frame 3: A plays the copy token idx 32; B must see its real identity.
var play = MoveOrderList(idx: 32, from: 10, to: 20);
play["playIdx"] = 32L; play["type"] = 30L;
var routes = s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, play));
var pb = (PlayActionsBroadcastBody)routes[0].Frame.Body;
Assert.That(routes[0].Target, Is.SameAs(b));
Assert.That(pb.KnownList, Is.Not.Null, "copy mined from the Echo into A's map");
Assert.That(pb.KnownList!.Single().CardId, Is.EqualTo(900_333_030L));
}
[Test]
public void Pvp_PlayActions_choice_token_records_pick_and_strips_selectCard()
{
var (s, a, b) = NewPvpSession();
DriveToAfterReady(s, a);
DriveToAfterReady(s, b);
// A plays a generating deck card (idx 3) whose fanfare is a hidden draw-to-hand choice: a
// choiceAdd lands a token at idx 31 (candidates only), the move pulls it limbo->hand, and
// keyAction.selectCard names the chosen cardId with open:0 (hidden).
var gen = new Dictionary<string, object?>
{
["playIdx"] = 3L,
["type"] = 30L,
["orderList"] = new List<object?>
{
new Dictionary<string, object?> { ["move"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 3L }, ["isSelf"] = 1L, ["from"] = 10L, ["to"] = 30L } },
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 31L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?>
{ ["candidates"] = new List<object?> { 810041260L, 101041020L } },
["isChoice"] = "1" } },
new Dictionary<string, object?> { ["move"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 31L }, ["isSelf"] = 1L, ["from"] = 50L, ["to"] = 10L } },
},
["keyAction"] = new List<object?>
{
new Dictionary<string, object?>
{
["type"] = 1L, ["cardId"] = 100_011_010L,
["selectCard"] = new Dictionary<string, object?>
{ ["cardId"] = new List<object?> { 810041260L }, ["open"] = 0L },
}
},
};
var routes = s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, gen));
Assert.That(routes.Count, Is.EqualTo(1));
Assert.That(routes[0].Target, Is.SameAs(b));
var pb = (PlayActionsBroadcastBody)routes[0].Frame.Body;
// The generating deck card reveals from A's deck map (idx 3).
Assert.That(pb.KnownList!.Single().CardId, Is.EqualTo(100_011_010L), "generating deck card revealed");
// keyAction forwarded as {type,cardId}; selectCard stripped for the hidden choice.
Assert.That(pb.KeyAction, Is.Not.Null);
Assert.That(pb.KeyAction!.Single().Type, Is.EqualTo(1));
Assert.That(pb.KeyAction.Single().CardId, Is.EqualTo(100_011_010L));
Assert.That(pb.KeyAction.Single().SelectCard, Is.Null, "the pick stays hidden for open:0");
}
[Test]
public void Pvp_PlayActions_reveals_choice_token_when_chosen_card_is_played()
{
var (s, a, b) = NewPvpSession();
DriveToAfterReady(s, a);
DriveToAfterReady(s, b);
// Generation frame: records idx 31 -> chosen cardId 810041260 into A's map (from selectCard).
var gen = new Dictionary<string, object?>
{
["playIdx"] = 3L,
["type"] = 30L,
["orderList"] = new List<object?>
{
new Dictionary<string, object?> { ["move"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 3L }, ["isSelf"] = 1L, ["from"] = 10L, ["to"] = 30L } },
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 31L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?>
{ ["candidates"] = new List<object?> { 810041260L, 101041020L } },
["isChoice"] = "1" } },
},
["keyAction"] = new List<object?>
{
new Dictionary<string, object?>
{
["type"] = 1L, ["cardId"] = 100_011_010L,
["selectCard"] = new Dictionary<string, object?>
{ ["cardId"] = new List<object?> { 810041260L }, ["open"] = 0L },
}
},
};
s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, gen));
// Later A plays the chosen token idx 31 (hand 10 -> field 20). B must see its real identity.
var play = MoveOrderList(idx: 31, from: 10, to: 20);
play["playIdx"] = 31L;
play["type"] = 30L;
var routes = s.ComputeFrames(a, EnvWith(NetworkBattleUri.PlayActions, play));
var pb = (PlayActionsBroadcastBody)routes[0].Frame.Body;
Assert.That(pb.PlayIdx, Is.EqualTo(31));
Assert.That(pb.KnownList, Is.Not.Null, "the choice pick was recorded at generation");
Assert.That(pb.KnownList!.Single().Idx, Is.EqualTo(31));
Assert.That(pb.KnownList[0].CardId, Is.EqualTo(810041260L), "the chosen cardId surfaces on play");
Assert.That(pb.KnownList[0].To, Is.EqualTo(20));
}
[Test]
public void Pvp_PlayActions_when_B_still_AwaitingSwap_drops()
{
@@ -335,6 +695,41 @@ public class BattleSessionDispatchTests
Assert.That(routes, Is.Empty, "Echo has no inbound handler on the client; relaying risks an echo storm.");
}
[Test]
public void Pvp_Echo_mines_token_identity_for_a_later_reveal()
{
var (s, a, b) = NewPvpSession();
DriveToAfterReady(s, a);
DriveToAfterReady(s, b);
// B's Echo carries its own (isSelf:1) view of a token it received at idx 31. An Echo's
// orderList carries the SAME add-op shape as PlayActions (SendCardDataMaker.MakeEchoData ->
// MakeCommonSendAndEchoCardData), so the node MINES it for the identity — but still never
// relays the Echo (no inbound client handler). Mining != relaying.
var echo = new Dictionary<string, object?>
{
["orderList"] = new List<object?>
{
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 31L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?> { ["cardId"] = 900111010L } } },
},
};
var echoRoutes = s.ComputeFrames(b, EnvWith(NetworkBattleUri.Echo, echo));
Assert.That(echoRoutes, Is.Empty, "Echo is mined, not relayed.");
// B plays the token idx 31 (hand 10 -> field 20); A must now see its real identity.
var play = MoveOrderList(idx: 31, from: 10, to: 20);
play["playIdx"] = 31L;
play["type"] = 30L;
var routes = s.ComputeFrames(b, EnvWith(NetworkBattleUri.PlayActions, play));
var pb = (PlayActionsBroadcastBody)routes[0].Frame.Body;
Assert.That(pb.KnownList, Is.Not.Null, "Echo-mined token identity surfaces on play");
Assert.That(pb.KnownList!.Single().Idx, Is.EqualTo(31));
Assert.That(pb.KnownList[0].CardId, Is.EqualTo(900_111_010L), "mined-from-Echo token cardId");
}
[Test]
public void Pvp_TurnEndActions_from_A_emits_empty_body_to_B()
{

View File

@@ -1,4 +1,5 @@
using NUnit.Framework;
using SVSim.BattleNode.Protocol.Bodies;
using SVSim.BattleNode.Sessions.Dispatch;
namespace SVSim.UnitTests.BattleNode.Sessions;
@@ -129,15 +130,18 @@ public class KnownListBuilderTests
var orderList = new List<object?> { AddOp(new[] { 31L, 32L }, 900111010L) };
var mined = KnownListBuilder.MineAddOps(orderList).ToList();
Assert.That(mined, Is.EquivalentTo(new[] { (31, 900111010L), (32, 900111010L) }));
Assert.That(mined, Is.EquivalentTo(new[] { (31, 900111010L, 1), (32, 900111010L, 1) }));
}
[Test]
public void MineAddOps_skips_add_ops_for_the_opponent_isSelf_0()
public void MineAddOps_yields_cross_side_gifts_with_isSelf_0()
{
// A card given to the opponent (isSelf:0) belongs in the other side's map — deferred.
// A card gifted to the opponent (isSelf:0) is the opponent's card at this idx (isSelf is the
// sender's perspective tag on CardObj.IsPlayer — RegisterToken.cs:22). The extractor surfaces
// it; the caller routes it into the OTHER side's map.
var orderList = new List<object?> { AddOp(new[] { 31L }, 900111010L, isSelf: 0) };
Assert.That(KnownListBuilder.MineAddOps(orderList), Is.Empty);
Assert.That(KnownListBuilder.MineAddOps(orderList),
Is.EquivalentTo(new[] { (31, 900111010L, 0) }));
}
[Test]
@@ -200,6 +204,305 @@ public class KnownListBuilderTests
AddOp(new[] { 32L }, 900811090L),
};
var mined = KnownListBuilder.MineAddOps(orderList).ToList();
Assert.That(mined, Is.EquivalentTo(new[] { (31, 900111010L), (32, 900811090L) }));
Assert.That(mined, Is.EquivalentTo(new[] { (31, 900111010L, 1), (32, 900811090L, 1) }));
}
// A choice/Discover add op as it arrives in a RawBody: candidates-only (no concrete cardId —
// RegisterChoiceAdd strips it), with isChoice present. Capture battle-traffic_tk2_regular line 152.
private static Dictionary<string, object?> ChoiceAddOp(long idx, long[] candidates, long isSelf = 1) => new()
{
["add"] = new Dictionary<string, object?>
{
["idx"] = new List<object?> { idx },
["isSelf"] = isSelf,
["card"] = new Dictionary<string, object?>
{
["candidates"] = candidates.Select(c => (object?)c).ToList(),
},
["isChoice"] = "1",
}
};
// A keyAction entry: { type, cardId (the GENERATING card), selectCard:{ cardId:[chosen...], open } }.
private static List<object?> KeyActionChoice(long generatingCardId, long[] chosen, long open) => new()
{
new Dictionary<string, object?>
{
["type"] = 1L,
["cardId"] = generatingCardId,
["selectCard"] = new Dictionary<string, object?>
{
["cardId"] = chosen.Select(c => (object?)c).ToList(),
["open"] = open,
},
}
};
[Test]
public void MineChoicePicks_resolves_idx_to_chosen_cardId_from_selectCard()
{
// The choiceAdd carries only candidates; the pick rides keyAction.selectCard.cardId. The node
// joins them by candidate membership. Capture lines 151/152/193: chosen = candidates[0].
var orderList = new List<object?> { ChoiceAddOp(46, new[] { 810041260L, 101041020L }) };
var keyAction = KeyActionChoice(generatingCardId: 810014030L, chosen: new[] { 810041260L }, open: 0);
Assert.That(KnownListBuilder.MineChoicePicks(orderList, keyAction),
Is.EquivalentTo(new[] { (46, 810041260L, 1) }));
}
[Test]
public void MineChoicePicks_routes_cross_side_choice_by_isSelf()
{
// A choiceAdd with isSelf:0 (a gifted choice in the opponent's index space) surfaces isSelf:0
// so the caller routes it into the OTHER side's map (same rule as MineAddOps).
var orderList = new List<object?> { ChoiceAddOp(46, new[] { 810041260L, 101041020L }, isSelf: 0) };
var keyAction = KeyActionChoice(810014030L, new[] { 101041020L }, open: 0);
Assert.That(KnownListBuilder.MineChoicePicks(orderList, keyAction),
Is.EquivalentTo(new[] { (46, 101041020L, 0) }));
}
[Test]
public void MineChoicePicks_yields_nothing_when_no_pick_matches_candidates()
{
var orderList = new List<object?> { ChoiceAddOp(46, new[] { 810041260L, 101041020L }) };
var keyAction = KeyActionChoice(810014030L, new[] { 999999999L }, open: 0);
Assert.That(KnownListBuilder.MineChoicePicks(orderList, keyAction), Is.Empty);
}
[Test]
public void MineChoicePicks_ignores_non_choice_add_ops()
{
// A concrete-token add (cardId, no candidates) is MineAddOps' job — even if its cardId happens
// to equal a selectCard pick, MineChoicePicks only mines isChoice/candidates adds.
var orderList = new List<object?> { AddOp(new[] { 31L }, 900111010L) };
var keyAction = KeyActionChoice(810014030L, new[] { 900111010L }, open: 0);
Assert.That(KnownListBuilder.MineChoicePicks(orderList, keyAction), Is.Empty);
}
[Test]
public void MineChoicePicks_yields_nothing_when_keyAction_absent()
{
// Echo carries orderList but no keyAction; choice mining keys on keyAction, so Echo yields
// nothing here and stays mining-only via MineAddOps (§3.5).
var orderList = new List<object?> { ChoiceAddOp(46, new[] { 810041260L, 101041020L }) };
Assert.That(KnownListBuilder.MineChoicePicks(orderList, null), Is.Empty);
}
[Test]
public void StripKeyActionForOpponent_drops_selectCard_when_open_0()
{
// Hidden draw-to-hand choice: opponent gets {type,cardId} only; the pick stays secret.
// Capture line 151: keyAction:[{type:1, cardId:810014030}].
var keyAction = KeyActionChoice(810014030L, new[] { 810041260L }, open: 0);
var stripped = KnownListBuilder.StripKeyActionForOpponent(keyAction);
Assert.That(stripped, Is.Not.Null);
Assert.That(stripped!.Count, Is.EqualTo(1));
Assert.That(stripped[0].Type, Is.EqualTo(1));
Assert.That(stripped[0].CardId, Is.EqualTo(810014030L));
Assert.That(stripped[0].SelectCard, Is.Null);
}
[Test]
public void StripKeyActionForOpponent_passes_selectCard_through_when_open_1()
{
// Visible board choice — provisional reveal-immediately behavior (§6, flagged for the live run).
var keyAction = KeyActionChoice(810014030L, new[] { 810041260L }, open: 1);
var stripped = KnownListBuilder.StripKeyActionForOpponent(keyAction);
Assert.That(stripped![0].SelectCard, Is.Not.Null);
Assert.That(stripped[0].SelectCard!.CardId, Is.EqualTo(new[] { 810041260L }));
Assert.That(stripped[0].SelectCard.Open, Is.EqualTo(1));
}
[Test]
public void StripKeyActionForOpponent_drops_non_choice_types()
{
// Only Choice(1)/HaveBeforeSkillChoice(5) are handled; other KeyActionTypes are dropped
// (current behavior) until their own specs (§6).
var keyAction = new List<object?>
{
new Dictionary<string, object?> { ["type"] = 2L, ["cardId"] = 123L },
};
Assert.That(KnownListBuilder.StripKeyActionForOpponent(keyAction), Is.Null);
}
[Test]
public void StripKeyActionForOpponent_returns_null_for_absent_keyAction()
{
Assert.That(KnownListBuilder.StripKeyActionForOpponent(null), Is.Null);
Assert.That(KnownListBuilder.StripKeyActionForOpponent(new List<object?>()), Is.Null);
}
// A copy add op as it arrives in a RawBody: { "add": { "idx":[..], "isSelf":n, "card":{ "baseIdx":m, "isPremium":0 } } }
private static Dictionary<string, object?> CopyOp(long[] idxs, long baseIdx, long isSelf = 1) => new()
{
["add"] = new Dictionary<string, object?>
{
["idx"] = idxs.Select(i => (object?)i).ToList(),
["isSelf"] = isSelf,
["card"] = new Dictionary<string, object?> { ["baseIdx"] = baseIdx, ["isPremium"] = 0L },
}
};
[Test]
public void MineCopyTokens_resolves_baseIdx_against_selfMap_for_isSelf_1()
{
var orderList = new List<object?> { CopyOp(new[] { 31L }, baseIdx: 5L, isSelf: 1) };
var selfMap = new Dictionary<int, long> { [5] = 100_011_010L };
var otherMap = new Dictionary<int, long>();
var mined = KnownListBuilder.MineCopyTokens(orderList, selfMap, otherMap).ToList();
Assert.That(mined, Is.EquivalentTo(new[] { (31, 100_011_010L, 1) }));
}
[Test]
public void MineCopyTokens_resolves_baseIdx_against_otherMap_for_isSelf_0()
{
// Cross-side copy shape (battle-traffic_tk2_regular.ndjson:196 is an isSelf:0 Echo, baseIdx 21):
// the source lives in the OPPONENT's index space, so resolve against otherMap and record there.
var orderList = new List<object?> { CopyOp(new[] { 49L }, baseIdx: 21L, isSelf: 0) };
var selfMap = new Dictionary<int, long>();
var otherMap = new Dictionary<int, long> { [21] = 900_841_330L };
var mined = KnownListBuilder.MineCopyTokens(orderList, selfMap, otherMap).ToList();
Assert.That(mined, Is.EquivalentTo(new[] { (49, 900_841_330L, 0) }));
}
[Test]
public void MineCopyTokens_skips_copy_when_baseIdx_absent_from_map()
{
// Unknown source (e.g. a card the node never recorded) → no record, no desync, the play degrades.
var orderList = new List<object?> { CopyOp(new[] { 31L }, baseIdx: 99L, isSelf: 1) };
Assert.That(
KnownListBuilder.MineCopyTokens(orderList, new Dictionary<int, long>(), new Dictionary<int, long>()),
Is.Empty);
}
[Test]
public void MineCopyTokens_ignores_concrete_and_choice_adds()
{
// A concrete-cardId add is MineAddOps' job; a candidates add is MineChoicePicks' — both skipped here.
var orderList = new List<object?>
{
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 31L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?> { ["cardId"] = 900_111_010L } } },
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 32L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?> { ["candidates"] = new List<object?> { 1L, 2L } },
["isChoice"] = "1" } },
};
var map = new Dictionary<int, long> { [1] = 5L };
Assert.That(KnownListBuilder.MineCopyTokens(orderList, map, map), Is.Empty);
}
[Test]
public void MineCopyTokens_skips_string_baseIdx_private_group()
{
// PrivateGroupIndexMsg != "" makes baseIdx a STRING (RegisterCopyToken.cs:19-22) — the hidden
// private-card path; skipped just like private-group idx in MineAddOps.
var orderList = new List<object?>
{
new Dictionary<string, object?> { ["add"] = new Dictionary<string, object?>
{ ["idx"] = new List<object?> { 31L }, ["isSelf"] = 1L,
["card"] = new Dictionary<string, object?> { ["baseIdx"] = "g1", ["isPremium"] = 0L } } },
};
Assert.That(
KnownListBuilder.MineCopyTokens(orderList, new Dictionary<int, long>(), new Dictionary<int, long>()),
Is.Empty);
}
[Test]
public void MineCopyTokens_yields_for_every_idx_in_a_multi_idx_copy_op()
{
var orderList = new List<object?> { CopyOp(new[] { 31L, 32L }, baseIdx: 5L, isSelf: 1) };
var selfMap = new Dictionary<int, long> { [5] = 700L };
var mined = KnownListBuilder.MineCopyTokens(orderList, selfMap, new Dictionary<int, long>()).ToList();
Assert.That(mined, Is.EquivalentTo(new[] { (31, 700L, 1), (32, 700L, 1) }));
}
// A uList entry as it arrives in a RawBody. Minimal = the 5 always-present fields
// (capture battle-traffic_tk2_regular.ndjson:75). Optional fields added per-test.
private static Dictionary<string, object?> UListEntry(
long[] idxList, int from, int to, int isSelf, string skill) => new()
{
["idxList"] = idxList.Select(i => (object?)i).ToList(),
["from"] = (long)from, ["to"] = (long)to, ["isSelf"] = (long)isSelf, ["skill"] = skill,
};
[Test]
public void RelayUList_maps_the_minimal_capture_entry_shape()
{
// battle-traffic_tk2_regular.ndjson:75 — a hidden deck-fetch (no cardId), the only uList shape
// in any capture. The 5 always-present fields map; conditionals stay null.
var uList = new List<object?> { UListEntry(new[] { 16L, 22L }, from: 0, to: 10, isSelf: 1, skill: "37|36|0") };
var relayed = KnownListBuilder.RelayUList(uList);
Assert.That(relayed, Is.Not.Null);
Assert.That(relayed!.Count, Is.EqualTo(1));
var e = relayed[0];
Assert.That(e.IdxList, Is.EqualTo(new[] { 16, 22 }));
Assert.That(e.From, Is.EqualTo(0));
Assert.That(e.To, Is.EqualTo(10));
Assert.That(e.IsSelf, Is.EqualTo(1));
Assert.That(e.Skill, Is.EqualTo("37|36|0"));
Assert.That(e.CardId, Is.Null);
Assert.That(e.Clan, Is.Null);
Assert.That(e.Cost, Is.Null);
Assert.That(e.SkillKeyCardIdx, Is.Null);
Assert.That(e.RandomTargetIdx, Is.Null);
Assert.That(e.IsInvoke, Is.Null);
Assert.That(e.AttachTarget, Is.Null);
}
[Test]
public void RelayUList_maps_a_revealed_summon_with_all_conditional_fields()
{
// Decomp-grounded (no capture): a revealed summon-to-field carries cardId + clan + cost etc.
var entry = UListEntry(new[] { 40L }, from: 0, to: 20, isSelf: 1, skill: "5|3|0");
entry["cardId"] = 900111010L;
entry["clan"] = 8L;
entry["cost"] = 2L;
entry["skillKeyCardIdx"] = new List<object?> { 7L };
entry["randomTargetIdx"] = new List<object?> { 2L, 3L };
entry["isInvoke"] = 1L;
entry["attachTarget"] = "12,13";
var relayed = KnownListBuilder.RelayUList(new List<object?> { entry });
var e = relayed![0];
Assert.That(e.To, Is.EqualTo(20));
Assert.That(e.CardId, Is.EqualTo(900111010L));
Assert.That(e.Clan, Is.EqualTo(8));
Assert.That(e.Cost, Is.EqualTo(2));
Assert.That(e.SkillKeyCardIdx, Is.EqualTo(new[] { 7 }));
Assert.That(e.RandomTargetIdx, Is.EqualTo(new[] { 2, 3 }));
Assert.That(e.IsInvoke, Is.EqualTo(1));
Assert.That(e.AttachTarget, Is.EqualTo("12,13"));
}
[Test]
public void RelayUList_preserves_multiple_entries_in_order()
{
var uList = new List<object?>
{
UListEntry(new[] { 16L }, 0, 10, 1, "a"),
UListEntry(new[] { 22L }, 0, 20, 0, "b"),
};
var relayed = KnownListBuilder.RelayUList(uList);
Assert.That(relayed!.Count, Is.EqualTo(2));
Assert.That(relayed[0].Skill, Is.EqualTo("a"));
Assert.That(relayed[1].Skill, Is.EqualTo("b"));
Assert.That(relayed[1].IsSelf, Is.EqualTo(0));
}
[Test]
public void RelayUList_returns_null_for_missing_or_empty()
{
Assert.That(KnownListBuilder.RelayUList(null), Is.Null);
Assert.That(KnownListBuilder.RelayUList(new List<object?>()), Is.Null);
}
}