Previous commit 51e9dd2 changed Bot's InitBattle to push Matched and
Loaded to push BattleStart+Deal, on the theory that the architecture
spec's "no Matched in Bot mode" claim was wrong. That theory was based
on misreading Matching.cs:400 (the Matched handler) as a required
state-machine trigger.
End-to-end trace of the AI client flow shows:
1. _initNetworkSuccess (set when the client receives uri=InitNetwork,
i.e., our ack) is the actual trigger — MatchingNetworkConnectChecker
phase 3 sees it and calls MatchingInitBattle.
2. MatchingInitBattle (Matching.cs:298) for IsAINetwork IMMEDIATELY
calls StartBattleLoad + GotoBattle right after emitting InitBattle.
It does NOT wait for any wire envelope.
3. The Matched handler at Matching.cs:400 is gated on
status == Connect and is already past Prepared by the time the
wire round-trip completes — sending Matched is harmless but
unnecessary.
4. The BattleStart handler at Matching.cs:417 runs UNCONDITIONALLY and
SetNetworkInfo at RealTimeNetworkAgent.cs:1562 overwrites
OppoBattleStartInfo with the wire envelope's oppoInfo. Our oppoInfo
comes from NoOpBotParticipant.Context placeholders (classId/emblemId
etc. = 0), corrupting the good values the client set from the HTTP
AIBattleStart response.
The "Waiting for opponent" hang was caused by SBattleLoad.LoadOpponentAssets
trying to fetch emblemId=0, degreeId=0, etc. after BattleStart corrupted
OppoBattleStartInfo. The asset group load silently hangs on missing
assets, no error logged.
Restored the spec's original Bot arms: InitBattle ack-only, Loaded silent,
TurnEnd Judge-to-sender. ai-passive.md updated with the corrected reasoning
and a discovery-history note.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
SVSim.BattleNode
Socket.IO node-server scaffolding for in-battle traffic. Implements the second of the prod 4-server topology — the realtime channel that handles Matched / BattleStart / Deal / per-action PlayActions / Echo / TurnEnd between the client and a server-side opponent.
v1 scope is "scripted thin sequencer": the server accepts a connection, walks a hand-rolled lifecycle from InitNetwork to mulligan + first turn + opponent TurnStart, then sits at the opponent's-turn screen indefinitely. No real opponent, no battleCode validation, no recovery. v2 work targets each of those.
The library has no dependency on SVSim.EmulatedEntrypoint. It exposes one DI seam (IMatchingBridge) and one ASP.NET Core integration surface (AddBattleNode / UseBattleNode). Pulling the node into a separate process later is one interface and one Kestrel binding.
Architecture
SVSim.BattleNode/
├─ Bridge/ IMatchingBridge — what /do_matching calls to mint a battle id + node URL
├─ Hosting/ ASP.NET Core extensions + the /socket.io/ endpoint handler
├─ Lifecycle/ ScriptedLifecycle — the v1 hand-rolled Matched/BattleStart/Deal/Swap/Ready frames
├─ Protocol/ MsgEnvelope, NetworkBattleUri enum, msgpack ↔ envelope codec
├─ Reliability/ InboundTracker (pubSeq dedup), OutboundSequencer (playSeq archive), Gungnir
├─ Sessions/ BattleSession (per-connection state + WS pump), IBattleSessionStore
└─ Wire/ EIO3 framing, SIO2 framing, NodeCrypto (AES-256-CBC)
Connect handshake (verified end-to-end against the real client)
┌────────┐ ┌────────────┐
│ Client │ │ BattleNode │
└────┬───┘ └──────┬─────┘
│ │
│ HTTP POST /arena_two_pick_battle/do_matching │ (HTTP host)
├──────────────────────────────────────────────────────────────►│
│ ◄── { matching_state:3004, battle_id, node_server_url, │
│ card_master_id, ... } │
│ │
│ WS upgrade ws://<node>/socket.io/ │
│ headers: BattleId, viewerId=encryptForNode(uid) │
├──────────────────────────────────────────────────────────────►│ AcceptWebSocketAsync
│ ◄── EIO3 Open 0{sid,upgrades:[],pingInterval,pingTimeout} │
│ │
│ msg: InitNetwork (cat=99/general) │
├──────────────────────────────────────────────────────────────►│
│ ◄── synchronize: InitNetwork{resultCode:1} │
│ │
│ MatchingInitBattle: status=Connect; subscribe receiver │
│ msg: InitBattle (cat=2/matching) │
├──────────────────────────────────────────────────────────────►│
│ ◄── synchronize: Matched{selfInfo,oppoInfo,selfDeck,bid} │
│ │
│ client loads decks/scene │
│ msg: Loaded │
├──────────────────────────────────────────────────────────────►│
│ ◄── synchronize: BattleStart{turnState,battleType,...} │
│ ◄── synchronize: Deal{self,oppo} │
│ │
│ mulligan UI; player chooses cards to swap │
│ msg: Swap{idxList:[...]} │
├──────────────────────────────────────────────────────────────►│
│ ◄── synchronize: Swap{self:[post-mulligan hand]} │
│ ◄── synchronize: Ready{self,oppo,idxChangeSeed,spin} │
│ │
│ turn 1: TurnStart, PlayActions, ..., TurnEnd │
├──────────────────────────────────────────────────────────────►│
│ ◄── synchronize: TurnStart{spin} (opponent turn signal) │
│ │
│ sits at "Opponent's turn…" — v1 stopping point │
Each push from us carries a contiguous playSeq; client-emit pubSeq is echoed back via the Socket.IO ack callback. Gungnir runs a 5s alive heartbeat in parallel reporting scs:ONLINE,ocs:ONLINE.
Wire-format gotchas (discovered during v1 smoke)
These are not in the original protocol docs and tripped us during the smoke walkthrough — leaving them here so the next reader doesn't repeat the diagnosis.
| Spec said | Actual wire | Where it shows up |
|---|---|---|
AdditionalQueryParams on the WS upgrade |
HTTP request headers, not query string. BestHTTP misnames the API. | BattleNodeWebSocketHandler.ReadCredential reads BattleId / viewerId from headers first, query as fallback (for tests). |
node_server_url ws://host:port |
host:port/socket.io/ — no scheme prefix, path included. |
BattleNodeOptions.NodeServerUrl default + do_matching response. |
card_master_id optional |
Required when matching_state ∈ {3004,3007,3011} — no Keys.Contains guard client-side. |
Added to DoMatchingResponseDto with default 1. |
resultCode optional on pushes |
Required = 1 on every scripted synchronize frame; missing means "drop in error handler". | ScriptedLifecycle.EnvelopeForPush injects it. |
| Matched in response to InitNetwork | InitBattle. Matched in response to InitNetwork lands before the client's matching handler is subscribed and silently drops. | See dispatch in BattleSession.ComputeResponses. |
| WS binary frames carry raw msgpack | EIO3 prefixes binary frames with 0x04 (Message type byte), same as the leading digit on text frames. |
BattleSession.RunAsync strips on read; EncodeAndSendAsync prepends on send. |
There's also a JSON parsing pitfall worth knowing about (and that broke the mulligan): the inline conditional el.TryGetInt64(out var l) ? l : el.GetDouble() unifies its branches to the common implicit-convertible type. Since long → double is implicit, the long silently widens to double, and OfType<long> downstream drops every entry. See MsgEnvelope.ParseNumber for the fix — keep number parsing in a separate method so each branch boxes its own runtime type.
v1 scripted opponent — what the client sees
The player half of Matched / BattleStart reads from a MatchContext assembled in
SVSim.EmulatedEntrypoint/Services/MatchContextBuilder from the viewer's TK2 run + equipped
cosmetics + config — so the mulligan renders the real drafted deck, drafted class/leader,
and equipped emblem/degree. The opponent half stays scripted in ScriptedProfiles:
- Opponent is a fixed silhouette:
classId="8", JPN sleeve/emblem/degree, viewer id999999999. - Battle seed is
17548138Lin both info blocks (the seed is shared per battle per the spec). - Mulligan does real card replacement: any idx in your
idxListis swapped for the next unused deck idx (1..3dealt, so4..30are pool). - Opponent's turn never actually does anything — we push a single
TurnStart{spin:100}after yourTurnEndso the UI transitions to the opponent-turn display, then sit.
A few player-side fields are still hardcoded pending a follow-up slice — Rank, BattlePoint,
cardMasterName, fieldId, and the per-battle RNG seed. See the spec's §Deferred plumbing
table at docs/superpowers/specs/2026-06-01-battle-node-real-drafted-deck-design.md for
what each needs.
Where to extend
| You want to | Touch |
|---|---|
Wire a new mode's do_matching (rank, free, open-room, …) |
Add one BuildFor<Mode>Async(viewerId, …) method to IMatchContextBuilder reading that mode's deck source; the mode's controller calls IMatchingBridge.RegisterPendingBattle(vid, ctx). No changes to SVSim.BattleNode. |
| Add a real AI opponent | Replace the static dispatch in BattleSession.ComputeResponses (TurnEnd → opponent TurnStart case) with one that drives a decision engine. The OutboundSequencer already assigns playSeq for whatever you push. |
| Implement recovery | IBattleSessionStore already keeps the pending registry. Add a per-battle archive (the OutboundSequencer.Archive already retains every assigned-playSeq push) and bind it to the HTTP /battle/get_recovery_params endpoint. |
Validate battleCode |
Port NetworkConsistency.GetConsistency from the client decompilation. Hook into BattleSession.HandleMsgEventAsync on TurnEnd / Judge. |
Type the orderList register actions |
Spec at docs/api-spec/in-battle/register-actions.md catalogs the eight shapes observed in TK2 captures. Build a discriminated union; replace Dictionary<string, object?> in the Body for the relevant URIs. |
Test layout
SVSim.UnitTests/BattleNode/
├─ Bridge/ MatchingBridgeTests (3 tests — mint id, dedup, format)
├─ Integration/ BattleNodeFlowTests (end-to-end via WebApplicationFactory)
│ RawSocketIoTestClient (test helper)
├─ Lifecycle/ ScriptedLifecycleTests (11 tests)
├─ Protocol/ MsgEnvelopeTests (4 tests incl. number-array regression)
│ MsgPayloadCodecTests (2 tests — roundtrip + known vector)
├─ Reliability/ GungnirTests / InboundTrackerTests / OutboundSequencerTests
├─ Sessions/ BattleSessionDispatchTests (8 tests — phase-state machine)
│ InMemoryBattleSessionStoreTests
└─ Wire/ NodeCryptoTests (with fixed-vector regression)
EngineIoFrameTests
SocketIoFrameTests (incl. binary attachment + JSON escaping)
Total ~71 BattleNode-scoped tests. The integration test boots the EmulatedEntrypoint host via SVSimTestFactory, mints a battle through IMatchingBridge, opens a TestServer WebSocket, and walks the full handshake through Ready. It exercises every layer.
Related docs
docs/api-spec/in-battle/transport.md— Socket.IO + AES-for-node wire format, with smoke corrections inline.docs/api-spec/in-battle/matching.md—do_matchingbridge + client state machine.docs/api-spec/in-battle/server-to-client.md,client-to-server.md— per-uri frame shapes.docs/api-spec/in-battle/register-actions.md—orderListaction catalog (for v2).docs/api-spec/in-battle/reliability.md— pubSeq/playSeq stocking + Gungnir.docs/api-spec/in-battle/recovery.md— the reconnect handshake (deferred to v2).docs/operations/battle-node-smoke.md— manual end-to-end checklist.docs/operations/battle-node-smoke-walkthrough.md— annotated walkthrough with per-step diagnostics.docs/superpowers/specs/2026-05-31-battle-node-transport-design.md— v1 design.docs/superpowers/plans/2026-05-31-battle-node-transport.md— v1 implementation plan.