wire

package
v0.5.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package wire is the PvP protocol: the ten messages two peers exchange, the three version numbers they check before they start, and the codes a refusal is reported in. It is the format and nothing else — no room, no socket, no I/O, not one read of a clock.

Everything here is stdlib over types that already exist. That is the whole design, and it is the reason this package is small: a squad is already a wire format (placement.Squad is a *reference*, so a client cannot send an inflated stat line), a resolved unit is already tagged for JSON (battle.Roster), an aim is already a hex.Cell with its own absence, a taken turn is already a battle.Decision, and the data fingerprint is already seed.Digest. A second declaration of any of them would drift from the first, which is the mistake this repository has recorded more times than any other.

Three rules come straight off the design record (README.md § PvP over a LAN) and every type below is shaped by them:

  • **Kinds and codes serialise by name, never by number.** This is already hard law for event kinds, sides and outcomes: a saved log — or here, a peer one commit older — would silently reinterpret itself the next time a constant was inserted. Renaming a kind or a code is a wire break, so the names *are* the format.
  • **Nothing on the wire is prose.** The server sends a Code and the client words it. A server that sent sentences would be a server deciding what language its clients read in, and the client is Vietnamese-first.
  • **The clock is not part of the battle.** The turn allowance is room configuration and rides on Welcome; no battle-carrying message holds a reading of a clock. This package imports `time` not at all, and TestTheProtocolCannotReadAClock holds it mechanically.

⚠️ Why this imports internal/seed. The data digest must be *the same type* on both sides of a comparison — a room's gate that compared two strings would accept a peer whose digest had been mangled into the same characters by some other path, and would compile if somebody handed it an event digest by mistake. seed.Digest is that type, seed does not and cannot import wire (it is data over internal/core, and this is a protocol over both), so there is no cycle. The cost is that a binary importing wire embeds the fifteen data files — and both peers already import seed, because neither can *compute* its own digest, resolve a squad or draw a description without it. So the cost is zero in practice and the alternative was a second digest type.

Index

Constants

View Source
const ClosureCount = int(ClosureDraftExpired) + 1

ClosureCount is the number of closures, and it exists so a test can walk them rather than range over the table of names and ask it whether it holds what it holds.

⚠️ **Every ending is worded and every ending is drawn** — the same state CodeCount is in, and worded in the same place for the same reason: wire must not import internal/i18n, because the whole point of sending an id is that the wording lives at the far end. Lang.Closure is that end, internal/i18n/protocol_test.go is the walk over this count against both books, and cmd/hexarena-tui's TestEveryRefusalIsShownAndEveryClosureIsShown is what reads each sentence back off the result screen.

⚠️ Note the asymmetry with CodeCount, which is worth knowing rather than smoothing over: a closure needs no producer to be *drawable*, because the result screen words whatever closure it is handed — so ClosureDraftExpired is read by a player from the day it exists, while CodeSquadUnwanted is owed a room. What neither test can see is whether a room ever *sends* this one. → TODO.md § *The draft on the wire*.

View Source
const CodeCount = int(CodeWatchingClosed) + 1

CodeCount is the number of codes, and it exists so a test can walk them rather than range over the table of names and ask it whether it holds what it holds.

⚠️ **Every code is worded and every code is drawn.** Lang.Refusal in internal/i18n carries a line per code in both books, and the walk over this count against those books is internal/i18n/protocol_test.go — it could never be here, because wire must not import internal/i18n (the whole point of a code is that the wording lives at the far end, and a protocol that imported the word book would be the server holding the sentences again). So this count is what is held here. cmd/hexarena-tui's TestEveryRefusalIsShownAndEveryClosureIsShown is the other half: it produces every code out of a real room and reads its sentence back off a drawn screen.

⚠️ **This paragraph used to name CodeSquadUnwanted as the one exception, and that debt has been paid twice over.** It read that no room answered that code yet and that the drawing test held an `owed` set of exactly one; a room drafts now, so the entry went and the set is empty. CodeTooManyWatchers arrived with its producer already written — the transport refuses the watcher over its cap — so it never joined that set either, and neither did CodeWatchingClosed, which the gate answers the moment the constant exists. The mechanism is what to keep: a value declared ahead of anything that answers it belongs in `owed` with the step that owes it, because a code nothing produces is a wording no player ever reads.

View Source
const KindCount = int(KindDrafted) + 1

KindCount is the number of message kinds.

It exists so a test can walk the kinds rather than range over a table and ask it whether it holds what it holds. A kind added without a name, without a decoder or without a golden entry is then a red test rather than a message nothing measures — the shape cmd/hexarena-tui's screenCount established after five screens slipped into the authoring client unmeasured.

View Source
const Protocol = 1

Protocol is the version of this format. It moves when the messages change and for no other reason: the wire changes independently of the game, which is the whole argument for it being a number of its own rather than a byte of the build string.

What moves it: a kind or a code renamed or removed, a field renamed, a field's meaning changed. What does not: a new balance number, a new character, a new screen, or a code appended (a peer that meets an unknown code refuses cleanly and says so, which is a worse conversation than a good one and a much better one than a wrong one).

View Source
const RoomCodeLength = 12

RoomCodeLength is how many characters a room code is: always twelve, never eleven or thirteen.

Seven bytes — four of address, two of port and one of **room** — is fifty-six bits, and base32 spends five bits a character, so twelve characters carry exactly sixty. The four spare bits are why the padding is off: with padding the encoder would write sixteen characters, four of them '='.

⚠️ **It was ten, and the ten-character claim is retired.** A code carried six bytes while the open reading was one listener *per room*; one process now runs many rooms behind **one** listener, so the address and the port name the process and the seventh byte names the room. → EncodeRoom for why that is the cheaper answer, and README.md § *A room, and getting into one*.

⚠️ Two spare bits became four, so the number of strings base32 will decode to one room's bytes went from four to sixteen. That is not a curiosity: a code is a **map key** in the registry. → Decode, which refuses every variant but one.

View Source
const RoomsPerProcess = 256

RoomsPerProcess is how many rooms behind one address a code can tell apart: the room is one byte, so 256. The bound is the **width of the field** rather than a policy anybody picked, and it is far past what a LAN wants.

View Source
const Unstamped = "devel"

Unstamped is what a binary that was never stamped and knows nothing about its own source calls itself. It is a word rather than an empty string because it goes on a screen beside the data digest, and a blank there reads as a bug in the printing rather than as a fact about the binary.

Variables

This section is empty.

Functions

func BuildOf

func BuildOf(stamped string, info *debug.BuildInfo) string

BuildOf is the build string a binary announces, from the four sources in the order they are trusted. It is **pure** so the ordering is testable without a linker: the stamp is a parameter and the build info is a parameter, and neither is read from the process here.

  1. **The -ldflags stamp**, if there is one. It is a deliberate act by whoever produced the binary, so nothing may override it.
  2. **The VCS revision** the toolchain records — runtime/debug's `vcs.revision`, with `+dirty` appended when `vcs.modified` says the tree had uncommitted changes. ⚠️ The dirty marker is worth the characters: two people comparing builds over a LAN game are usually comparing one release against one working copy, and a working copy that says nothing about being modified is the one that wastes the conversation.
  3. **The module version**, `info.Main.Version` — which is what a binary produced by `go install pkg@version` has and the only thing it has. ⚠️ **`go install` stamps no VCS settings at all**: the toolchain records those only when it builds out of a local checkout, so step 2 is empty for every binary anybody installs from the proxy. Measured on the published module — `go install github.com/vukyn/hexarena/cmd/hexarena-host@latest` printed `build devel` on its banner while the version `v0.0.0-20260904055522-983dbc63ceef` had scrolled past during the download. The toolchain knew the whole time and this step is the one that reads it.
  4. **Unstamped**, for a `go run` — which records neither a revision nor a module version, so this is the ordinary case during development rather than an error path.

⚠️ **It lives here and the stamp does not, which is the whole shape of the split.** Version.Local's comment says wire has no way to know a build string — a version is stamped at build time and read by the binary's own main — and that stays true: what is here is the pure two-argument *derivation*, and each binary keeps its own `var build string` for the linker to write into and its own debug.ReadBuildInfo call. It moved out of cmd/hexarena-host because a second binary needs the same fallback, and a second spelling of a fallback is how two peers come to disagree about what they are.

func Encode

func Encode(body Body) ([]byte, error)

Encode wraps a body in its own envelope and returns the bytes that travel.

The kind comes from the body rather than from an argument, so a message labelled as something it is not is unrepresentable rather than a bug to be found on the far end.

Types

type Act

type Act struct {
	// Skill is the id of the skill to use, out of the four the unit brought.
	Skill string `json:"skill"`
	// Aim is the cell to point it at, absent for a skill that points nowhere.
	// hex.Cell's absence is the real thing rather than a coordinate standing in
	// for one — an aim of nought would be the ally back corner.
	Aim hex.Cell `json:"aim,omitzero"`
}

Act is a client spending its turn: a skill and where it is pointed. Client → server.

⚠️ It carries **no unit**. The server knows whose turn it is — it holds the authoritative battle and it is the thing that produced the prompt — so a unit on this message would be a second statement of a fact one side already owns, and the only thing it could add is a disagreement to resolve. The same reason keeps a whole battle.Decision off this side of the wire: a Decision carries the unit, the turn number and a pass reason, and every one of those three is the server's to record.

func (Act) Kind

func (Act) Kind() Kind

Kind is KindAct.

type Body

type Body interface {
	// Kind is which envelope this body travels in.
	Kind() Kind
}

Body is one of the ten message bodies, and the interface exists for exactly one reason: it makes the pairing of a kind with a body a property of the type rather than of whoever remembered to set the field. Encode never takes a kind.

func Decode

func Decode(raw []byte) (Body, error)

Decode reads an envelope and its body, returning a pointer to one of the ten structs. The caller switches on the type, or asks the result for its Kind.

Every failure is an error and never a usable-looking zero value: an unknown kind, a body that does not fit the kind it claims, and trailing bytes after the envelope are each a refusal. A peer that guessed would be a peer that fights a different battle for a while before anybody noticed.

type Closed

type Closed struct {
	Reason Closure `json:"reason"`
}

Closed is the room saying the match is over for a reason the board cannot show. Server → client, at most once, and **not to the peer that caused it**.

It exists because one thing genuinely needed saying and nothing said it. A departure ends a match in the middle of a battle: there is no Ended for the battle in progress — the engine concluded nothing about it — and no further Start, so a mirror that was handed nothing would simply hang on its own open prompt, waiting for a turn that is never coming.

⚠️ **It is not "the match ended" in general**, and a reader will want to send it for every ending. A match played out to its end needs no message: the client learns each battle's outcome from its own Ended event and the series length from Welcome.Battles, so announcing the result would be a second declaration of a fact the client computes — which is exactly what the missing series-standing message is missing for. A **capped** battle needs none either: Welcome.TurnCap is what lets the mirror stop on the same turn by the same arithmetic.

So the field is a Closure and the message is not one kind per reason: a further thing a board cannot show is an entry in that enum rather than a kind of its own. ClosureStopped and ClosureDraftExpired are what that has cost so far — two constants, two names, no new message — which is the evidence for the shape rather than a claim about it.

func (Closed) Kind

func (Closed) Kind() Kind

Kind is KindClosed.

type Closure

type Closure uint8

Closure is why a room closed a match, and it is the whole of a Closed.

It is an enum rather than a sentence for the reason a Code is: a server that sent prose would be a server deciding what language its clients read in, and this client is Vietnamese-first with an English toggle. The client words it; the id is the only thing that travels.

⚠️ **A match played out to its end closes nothing.** The client is a mirror: it learns each battle's outcome from its own Ended event and it knows the series length from Welcome.Battles, so a room that announced "you won" would be declaring a second time what the client has already computed — the mistake the missing series-standing message exists to avoid. What this enum names is the *other* kind of ending: a match stopped for a reason the board cannot show, which a mirror has no way to reach on its own.

There are **three of those** and the enum is shaped for a fourth: a value added here is an entry in a table rather than a new message kind, which is the whole reason the reason is a field and not a Kind. ClosureStopped and ClosureDraftExpired are what the second and third cost — one constant and one name each, and no new message either time — which is the evidence for the shape rather than a claim about it.

const (
	// ClosureNone is no closure at all, and it is the zero value for exactly the
	// reason CodeNone is: an absent field must not read as a real reason. A
	// Closed carrying it would be a room saying the match is over and declining
	// to say why, so no room may send one — Closure.Closes is the question to
	// ask.
	ClosureNone Closure = iota
	// ClosureLeft is the opponent having gone away.
	//
	// ⚠️ Whether a peer has really gone or is merely slow is the **transport's**
	// judgement and never the room's: the room is told, exactly as it is told
	// about a timeout, and a reconnect window sits in front of that report
	// rather than inside the room. So this is not "the opponent quit" — it is
	// "the thing that owns the connection has decided there is nobody there".
	//
	// ⚠️ It is **not a loss for the leaver and not a win for the one still
	// there**, and that is a decision rather than an omission: on a LAN between
	// friends the enforcement of walking away is social. → README.md § PvP over
	// a LAN, where the cost is written down.
	//
	ClosureLeft
	// ClosureStopped is the host having stopped serving: the process is going
	// away, so the match is over wherever it had got to.
	//
	// ⚠️ **It is a different fact from ClosureLeft and sending that one instead
	// would be a lie.** A departure is a judgement about a *peer* — the thing
	// that owns the connection decided there was nobody at the other end — and
	// this is the thing that owns the connection deciding to stop. A player told
	// "your opponent left" while their opponent was sitting right there would go
	// looking for a network fault that does not exist. The other way round is no
	// better: sending nothing at all leaves a player staring at a socket that
	// died for no stated reason, which is the one thing a Closed exists to
	// prevent.
	//
	// ⚠️ Like ClosureLeft it is **not a loss for anybody**. Nothing about the
	// host's process ending is a fact about the board, so the match has no
	// winner and the room's own verdict for it is room.VerdictAbandoned — the
	// same one a departure produces, because "nobody played this out" is the
	// same statement either way.
	ClosureStopped
	// ClosureDraftExpired is an allowance running out during the ban and pick:
	// **a draft that runs out of time is not resumed**, the room closes, and the
	// match is played again from a new code.
	//
	// ⚠️ **That is the one place the design does not follow "a timeout announces
	// and passes"**, and the reason is that there is nothing honest to pass with:
	// a side that never picked has no squad to fight with, and a defaulted pick
	// or a defaulted formation would hand somebody a side they did not choose and
	// call it theirs — where placement alone is worth nineteen points of win rate
	// (27.6% → 47.3% ally on the shipped roster). → TODO.md § "Ban and pick" (c).
	//
	// ⚠️ **It is a closure and not a refusal, which is what makes it belong
	// here.** A Refused answers one message and the match carries on; this ends
	// the match, and a mirror that was only refused would sit holding an open
	// draft decision waiting for a decision nobody is coming to take — the exact
	// hang Closed exists to prevent.
	//
	// ⚠️ Like both closures above it is **not a loss for anybody**. Nobody
	// drafted a squad, so there is no board to have a verdict about.
	//
	// Declared last, which is the rule this enum shares with Kind, Code and
	// battle.Kind: a closure serialises by name, so appending cannot
	// reinterpret an ending a peer already knows how to word. ⚠️ **The comment
	// moves with the last constant** — left on ClosureStopped it would say
	// something false about this file.
	ClosureDraftExpired
)

func (Closure) Closes

func (c Closure) Closes() bool

Closes reports whether the closure names an actual ending, which is what a Closed has to carry.

func (Closure) MarshalJSON

func (c Closure) MarshalJSON() ([]byte, error)

MarshalJSON writes the closure by name, so the format does not depend on the order these constants are declared in.

func (Closure) String

func (c Closure) String() string

func (*Closure) UnmarshalJSON

func (c *Closure) UnmarshalJSON(raw []byte) error

UnmarshalJSON reads a closure written by name, and refuses one it does not know.

A reason a peer cannot read is worse than no reason: it would be worded from whatever constant happened to sit at zero, so a client would tell its player nothing had happened and then go quiet on a match that was over.

type Code

type Code uint8

Code is why a peer was turned away. It is the whole of a Refused, and it is a code rather than a sentence for the reason the design record gives: a server that sent prose would be a server deciding what language its clients read in, and this client is Vietnamese-first with an English toggle. The client words it; the id is the only thing that travels.

A code says nothing about *which* battle or *whose* turn, because a refusal this protocol can produce is always about the join or about the last message, both of which the peer already knows. Anything a code would have to explain with a number is a message of its own or nothing at all.

const (
	// CodeNone is no refusal, and it is the zero value on purpose — the same
	// choice hex.SideNone makes and for the same reason. Version.Check returns
	// it to mean "join accepted", and a Refused carrying it would be a refusal
	// that says nothing, so the room must never send one. Code.Refuses is the
	// question to ask.
	CodeNone Code = iota
	// CodeProtocolMismatch is a peer this one cannot talk to at all. It is
	// checked and answered *before* the digest: telling a peer its data is wrong
	// when it cannot even read the message saying so is telling it something it
	// has no way to act on, and the update it actually needs is the binary.
	CodeProtocolMismatch
	// CodeDataMismatch is a peer whose embedded data is not this data, so the
	// two would not simulate the same battle. Refused at the gate rather than
	// discovered on the eleventh minute of a battle that was never the same
	// battle twice — which the mirror's per-turn digest would catch eventually,
	// and eventually is the whole problem.
	CodeDataMismatch
	// CodeBadPassword is the room's password not matching. ⚠️ The password is
	// **not** security (see Password) and this code is not a security answer: it
	// says the same thing to a stranger in the house as to a friend who typed it
	// wrong, which is all a gate on a LAN is for.
	CodeBadPassword
	// CodeRoomUnknown is a code that names no room this process is running: the
	// address in it resolved, so something answered, and the room it names is
	// gone or was never here. A room code carries its own address (see
	// RoomCode), so this is what a restarted host looks like.
	CodeRoomUnknown
	// CodeRoomFull is both **seats** taken, and it means that and nothing wider: a
	// client that came to play arriving at a room two players are already in.
	//
	// ⚠️ It does not stretch to a watcher, because a watcher takes no seat (→
	// Hello.Watch, Welcome.Watching) and the seats being full therefore says
	// nothing about whether one may join. What turns away the watcher over the
	// cap is CodeTooManyWatchers, declared below: the cap is the transport's
	// fact rather than this constant's, and the two sentences a player reads are
	// different advice.
	CodeRoomFull
	// CodeSquadRefused is a squad that did not pass the gate: Squad.Validate,
	// then Take (which is already the loadout check), then the format's size and
	// the level and stage rules. One code covers all of them, and that is a
	// decision rather than laziness — the client holds the same books and the
	// same validator, so it can say precisely what is wrong with a squad it
	// built, in the player's own language, without the server spelling it.
	CodeSquadRefused
	// CodeNotYourTurn is an act, a pass **or a draft decision** arriving from the
	// seat that is not being asked. The server knows whose turn it is — which is
	// also why Act carries no unit and why Decide carries no seat.
	//
	// ⚠️ **The draft reuses this rather than getting a code of its own**, and the
	// reason is the discipline at the top of this file: it is the same fact about
	// the same thing, and what a player does about it is the same either way —
	// nothing, the screen already says whose decision is due. Two codes for one
	// situation is worth less than one.
	CodeNotYourTurn
	// CodeIllegalAction is an act the prompt does not offer: a skill the unit
	// does not hold, one on cooldown, or an aim outside the cells the engine
	// listed. Act already refuses it, so this code is the engine's no travelling
	// back rather than a second reading of the rules.
	//
	// ⚠️ **It covers the draft's four legality refusals too, and that is a
	// decision rather than laziness** — the same decision CodeSquadRefused makes
	// for the four ways a squad can be turned away, for the same reason. A draft
	// decision of the wrong step, one naming a character out of the pool or
	// already taken, an illegal loadout and a refused arrangement are all
	// decisions the open prompt did not offer, and the client holds the pool,
	// cast.ChooseLoadout and placement.Squad.Validate itself — so it can say
	// precisely which, in the player's own language, where a code could only ever
	// say "one of four". A client that offered any of the four was wrong about
	// rules it holds, which is what this code's wording says.
	CodeIllegalAction
	// CodeUnknownMessage is a kind this peer does not know, which is what a
	// client one version ahead looks like. It is the answer Kind.UnmarshalJSON's
	// refusal turns into.
	CodeUnknownMessage
	// CodeSquadUnwanted is a squad brought to a room that **drafts**: the two
	// sides ban and pick here, so the side a client built at home is not the side
	// it will field. → Welcome.Drafts.
	//
	// ⚠️ **No existing code can say this, which is why it is a new one.** Every
	// other refusal about a squad is CodeSquadRefused, and that code means one
	// thing — the squad is not *legal* — which this squad may perfectly well be.
	// Answering it would send a player to check the levels, forms and skills of a
	// squad with nothing wrong with it, and its wording says in as many words to
	// fix the squad and join again; the fix here is to bring **none**. A refusal
	// that misdirects is worse than a refusal that is merely blunt.
	//
	// ⚠️ It is a refusal rather than a silent drop for the reason Welcome.Drafts
	// gives: a squad quietly ignored is a player watching their side fail to
	// appear with nothing saying why. And it is answerable at the *gate*,
	// unlike the draft's own refusals, because it is a fact about the hello.
	//
	// ⚠️ **It does not stretch to a squad a watcher brought, and the same
	// sentence is why.** A client that asked to watch (→ Hello.Watch) expects no
	// side of its own, so nothing fails to appear and a dropped squad costs it
	// nothing it came for — the reason this code exists simply is not present. And
	// answering it there would misdirect exactly as answering CodeSquadRefused
	// here would: the wording says the room drafts and to join again with no squad
	// chosen, which sends somebody who never wanted a side to fix something that
	// is not wrong. A watcher's squad is therefore ignored, by this code and by no
	// new one.
	CodeSquadUnwanted
	// CodeTooManyWatchers is a watcher turned away because the match it came to
	// see already has as many people watching as the transport carries. It is
	// the **transport's** refusal and not a room's: a room keeps no count of
	// watchers, no list of them and no cap — that is what makes its seats,
	// its roster and its result untouched by anybody watching (→ Hello.Watch) —
	// so the only thing that can answer this is whatever holds the connections.
	//
	// ⚠️ **CodeRoomFull cannot say it, and the reason is the wording rather than
	// the type.** Both books word that code as two players already having the
	// board and then advise waiting for their match to finish or opening a room
	// of your own — advice that is nonsense for somebody who wanted to watch
	// *this* match, and a refusal about **seats** says nothing at all to a client
	// that asked for none. A refusal that misdirects is worse than one that is
	// merely blunt, which is the argument CodeSquadUnwanted is here on.
	//
	// ⚠️ It is answered **after** a room has welcomed the watcher rather than
	// instead of the gate's own checks, which is that gate's discipline one layer
	// out: a peer wrong about two things is told about the earlier one, so a
	// watcher on a stale build or with the wrong password hears about that rather
	// than about a queue it was never going to join. The welcome such a
	// connection provoked is dropped rather than sent — a welcome followed by a
	// refusal would be two answers to one hello.
	CodeTooManyWatchers
	// CodeWatchingClosed is a watcher turned away because the room it came to
	// watch does not take watchers at all. Whether a room may be watched is a
	// **room's configuration** — one field on room.Config, chosen by the host
	// before anybody joins (→ cmd/hexarena-host's -watch) — so unlike the cap
	// above this is the room's own refusal and is answered at the gate.
	//
	// ⚠️ **CodeTooManyWatchers cannot say it, and reusing it would be the worse
	// kind of wrong answer.** Both books word that code as the match already
	// carrying as many watchers as it can and then advise waiting for one of
	// them to leave and pasting the code again — advice that is *false* here
	// rather than merely unhelpful, because nobody is watching and nobody ever
	// will be, so the reader would sit waiting for a queue that does not exist.
	// CodeRoomFull is no nearer for its own reason (→ CodeRoomFull): it is about
	// the two seats, and this client asked for none. What a player can actually
	// do is ask the host to open a room with watching turned on, which is what
	// this code's wording says and what neither of the others could.
	//
	// ⚠️ **It is refused BEFORE the seat check**, in the same place the welcome
	// would have been handed out, so a watcher told this is told it about the
	// room rather than about the two people already in it — and after the
	// version and the password, so a peer wrong about two things still hears
	// about the earlier one. → room.Room.Join, where the order is the answer.
	//
	// Declared last, which is the rule this enum shares with Kind and with
	// battle.Kind: a code serialises by name, so appending cannot reinterpret a
	// refusal a peer already knows how to word. ⚠️ **The comment moves with the
	// last constant** — left on CodeTooManyWatchers it would say something false
	// about this file.
	CodeWatchingClosed
)

func (Code) MarshalJSON

func (c Code) MarshalJSON() ([]byte, error)

MarshalJSON writes the code by name, so the format does not depend on the order these constants are declared in.

func (Code) Refuses

func (c Code) Refuses() bool

Refuses reports whether the code names an actual refusal, which is what a Refused has to carry and what Version.Check returns nothing of on a peer it accepts.

func (Code) String

func (c Code) String() string

func (*Code) UnmarshalJSON

func (c *Code) UnmarshalJSON(raw []byte) error

UnmarshalJSON reads a code written by name, and refuses one it does not know.

A refusal a peer cannot read is worse than no refusal: it would be worded from whatever constant happened to sit at zero, so a client would tell its player the room was fine and then go quiet.

type Decide added in v0.2.0

type Decide struct {
	DraftDecision
}

Decide is a client taking its draft decision. Client → server.

⚠️ **It carries no seat**, and that is the same rule Act is written under: the room knows which connection spoke, so a seat here would be a second statement of a fact one side already owns and the only thing it could add is a disagreement to resolve. It is also why this is not a DraftEntry with the seat left blank — a field a sender is asked not to fill in is a field somebody will fill in.

⚠️ **It is a request and not a record.** The room hands it to its own draft as a call, and what the draft records is the draft's own entry — so a field this message carries that its step has no use for is dropped on the way in rather than being written down. Compare Turn, which carries the decision **as recorded**.

⚠️ **There is deliberately no sequence number on it, and the step is what stands in for one.** A reader who knows the client's chooser will ask: that answer carries the turn it is for, because a buffered answer for a turn already spent is otherwise indistinguishable from a fresh one (→ CLAUDE.md, "A window is not closed by the fact that you have not opened it"). A draft has exactly one open decision, so the step tags a stale decision from a previous *stage* on its own — a ban arriving while a pick is due is refused by its own step. What it does not tell apart is a decision stale within one step, a second ban meant for the first ban slot, and that is the hazard Act already carries for a battle rather than a new one this message adds. → TODO.md.

func (Decide) Kind added in v0.2.0

func (Decide) Kind() Kind

Kind is KindDecide.

type Digest

type Digest struct {
	seed.Digest
}

Digest carries a seed.Digest across the wire in the form seed's own documentation names as the one that travels: the sixty-four lowercase hex characters of Digest.String.

⚠️ It is not a second digest and it derives nothing. It *holds* a seed.Digest, so comparing a peer's against this binary's is an equality of that one type and the compiler checks it — which is the property the room's gate rests on, and the reason the field is not a string. Wrapping rather than re-declaring is also why the value can only be built out of a real seed.Digest: there is no path here that produces one from anything else.

The wrapper exists purely for the encoding. seed.Digest is [32]byte and would otherwise ride as thirty-two numbers, which is a golden nobody can read and a diff nobody can review.

func (Digest) MarshalJSON

func (d Digest) MarshalJSON() ([]byte, error)

MarshalJSON writes the digest as hex, through the String seed already declares — so there is one statement anywhere of what a digest looks like written down.

func (*Digest) UnmarshalJSON

func (d *Digest) UnmarshalJSON(raw []byte) error

UnmarshalJSON reads a digest back out of those hex characters.

This is a decoding of the declared form and not a second derivation of the digest: nothing here reads the data, and a value that arrives malformed is an error rather than a zero digest, because two peers agreeing on a digest of nothing is the one outcome this gate must never produce.

type DraftDecision added in v0.2.0

type DraftDecision struct {
	// Step is which of the five things this decision is. → DraftSteps, which is
	// the list, and Valid, which is derived from it.
	Step DraftStep `json:"step"`
	// Character is the id banned or picked.
	//
	// ⚠️ **Absent on a StepBan is the skip**, which is why this is omitempty
	// rather than always written: a ban that names nobody is a ban slot spent on
	// nobody, there is no third state, and the absence *is* the decision. Absent
	// on a loadout and a timeout because neither names a character — a loadout's
	// is the pick's, one decision earlier.
	Character string `json:"character,omitempty"`
	// Stage is the form a loadout **named**, and its absence is a real answer
	// rather than a missing one: the empty string is progression.Furthest, "the
	// furthest the level cap reaches", which is what a line that does not fork
	// means. A line that forks has no such thing and must name an arm.
	//
	// ⚠️ It is what was named and never what it resolved to. The resolution is
	// the mirror's to compute, from this.
	Stage string `json:"stage,omitempty"`
	// Skills and Passives are the loadout as it was named, before
	// cast.ChooseLoadout was asked about it. Empty on every other step.
	//
	// ⚠️ An **absent** list and an **empty** one are one decision here, which is
	// what omitempty makes them: cast.ChooseLoadout reads neither as a request
	// for anything, so a peer that sent `[]` gets back nothing and has lost
	// nothing. TestAnEmptyLoadoutListTravelsAsAnAbsentOne measures that rather
	// than leaving it to be assumed.
	Skills   []string `json:"skills,omitempty"`
	Passives []string `json:"passives,omitempty"`
	// Slots is one side's whole arrangement: the cell each of its picks stands
	// on, in pick order. Empty on every other step.
	//
	// ⚠️ It is one side's **whole** arrangement rather than one cell, because the
	// phase is simultaneous and secret — a cell at a time would need the same
	// buffer and would additionally hand a peer a partial arrangement to be told
	// about.
	Slots []hex.Offset `json:"slots,omitempty"`
}

DraftDecision is one draft decision as it was taken, step-tagged, with the fields the other steps do not use left empty.

⚠️ **One shape with a Step rather than five shapes, and the reason is not economy.** A ban, a skip, a pick, a loadout, an arrangement and a timeout are the six things one record holds, and a draft's record is a single sequence — five bodies against one record would be two different answers to one question, and the switch that turned one into the other would be a second declaration of the draft's own sequence. The same argument keeps a `Skipped` flag off this struct: a ban that names nobody is the skip, so a flag beside Character would be a second statement of one fact and two fields that could disagree.

⚠️ **Nothing derived is on it.** The remaining pool, whose turn it is, both sides' picks and the form a loadout *resolved* to are all computed by a mirror from these decisions, exactly as a battle's state is computed from its decisions. A field holding one of them would be the one place two peers could come to disagree.

type DraftEntry added in v0.2.0

type DraftEntry struct {
	// Seat is who decided.
	Seat Seat `json:"seat"`
	DraftDecision
}

DraftEntry is one decision as the draft recorded it: who took it, and what it was.

The seat is a field of its own and the decision is embedded, so this serialises flat and reads as one struct — and, more to the point, the six facts a decision is are declared exactly once, in DraftDecision, for both directions and for internal/draft's record — which holds a run of *these* rather than of a shape of its own. → the file comment, and the ⚠️ there about the alias this sentence used to claim.

⚠️ On a StepTimeout the seat is the one whose allowance ran out, which is the seat that was being asked — and during the arrange phase that is any seat that had not arranged, since both are being asked at once.

type DraftStep added in v0.2.0

type DraftStep string

DraftStep is which kind of decision a draft decision is, and it doubles as the vocabulary of what a draft's record can hold.

It is a named string rather than an iota with a table of names, which is the cheaper end of the rule Kind and Code live under: a string type has no declaration order for an insertion to reinterpret, so it needs no MarshalJSON, no names table and no count to be held against. Nothing dispatches on it by index. → Seat, which is a string for the same reason.

The zero DraftStep is not a step: an absent step is not a decision this protocol has, and DraftStep.Valid is the question to ask.

const (
	// StepBan is a side taking a character out of the pool for the match. It is
	// optional, and a ban that names **no** character is the skip — see
	// DraftDecision.Character, where that absence is the whole of how a skip
	// travels.
	StepBan DraftStep = "ban"
	// StepPick is a side taking a character for itself, which is the first of the
	// two decisions a pick is made of. The character leaves the pool here.
	StepPick DraftStep = "pick"
	// StepLoadout is the second: the form, four skills and one trait the
	// character just picked will field.
	StepLoadout DraftStep = "loadout"
	// StepArrange is a side putting its picks on its own 3x3 formation, which is
	// the phase that runs once picking closes — privately and simultaneously.
	//
	// ⚠️ **Two of these arrive in one Drafted and neither arrives alone**, which
	// is the one place this vocabulary is not one message per decision as it is
	// taken: a recorded decision is public the moment it is sent, so sending the
	// first arrangement on its own would show it to the other player. →
	// draft.Draft.Arrange.
	StepArrange DraftStep = "arrange"
	// StepTimeout is not a decision anybody made: it is an allowance having run
	// out, which cancels the whole draft. It travels because it is one of the
	// things a draft's record holds, and a second vocabulary beside this one
	// would be two ways to say one idea.
	StepTimeout DraftStep = "timeout"
)

func DraftSteps added in v0.2.0

func DraftSteps() []DraftStep

DraftSteps is every step a draft decision may name, in the order a draft reaches them.

It exists so a caller can **walk** the vocabulary rather than range over a table of its own and ask it whether it holds what it holds — the shape KindCount and CodeCount take for the two enums that do have a declaration order. What it buys here is that draft.Draft.Apply's switch can be held total against it, so a sixth step is a red test rather than a decision a mirror silently drops.

func (DraftStep) Valid added in v0.2.0

func (s DraftStep) Valid() bool

Valid reports whether the step is one a draft decision may name. It is derived from DraftSteps rather than written as a switch, so the list and the gate cannot come to disagree.

type Drafted added in v0.2.0

type Drafted struct {
	// Decisions is the run of recorded decisions this message carries, in record
	// order. A Drafted carrying none is a room saying nothing happened, so a
	// room must not send one.
	Decisions []DraftEntry `json:"decisions"`
}

Drafted is what a draft recorded, in the order it recorded it. Server → client, and it is the draft's twin of Turn.

⚠️ **It is a batch rather than one decision a message, for two reasons and each is sufficient.** The arrange phase records **two** entries at once by design — both arrangements or neither, because an entry is public the moment it is sent — so a message carrying one could not express the phase at all. And a spectator joining a draft in progress is a consumer whose cursor is nought, which is the whole record in one message; a per-decision message would make catching up a count of messages rather than a read.

⚠️ **There is no digest on it, and this is where that question gets asked.** A reader who knows Turn will look for one: Turn carries the digest of the events its decision produced, which is what makes a mirror a *check* rather than a hope, because a battle's state is a large computation that can drift silently. A draft's state is not that. It is a pure function of the decisions **and the pool**, the pool is the cast minus every character held back, and the data digest already gates that at the join — a peer whose cast is not this cast is refused with CodeDataMismatch before it is seated at all. So a per-decision digest could catch nothing the join does not already refuse, and it would be a second reading of the same fact taken once a turn.

func (Drafted) Kind added in v0.2.0

func (Drafted) Kind() Kind

Kind is KindDrafted.

type Envelope

type Envelope struct {
	Kind Kind            `json:"kind"`
	Body json.RawMessage `json:"body,omitempty"`
}

Envelope is what actually crosses the connection: a named kind and the body, still raw.

One connection carries all ten, so the reader has to know what it is holding before it can decode it — which is the same discriminant-plus-payload shape battle.Event takes for the same reason, one line at a time from a single stream. The body stays json.RawMessage here so that decoding is one pass over the bytes and an unknown kind never reaches a struct.

func (*Envelope) UnmarshalJSON

func (e *Envelope) UnmarshalJSON(raw []byte) error

UnmarshalJSON reads an envelope, and it exists for one case that the field's own decoder cannot see: an envelope that names **no** kind at all.

Kind.UnmarshalJSON refuses a name it does not know, but it is never called for a field that is not there — so `{"body":{}}` would leave the kind at its zero value and every unlabelled message in the protocol would read as a hello. That is the trap hex.SideNone exists to avoid, and the two cases take opposite answers on purpose: a side genuinely has a "nobody" (a draw has no winner), so it is represented, while an envelope with no kind is not a message this format has — nothing sends one — so it is refused rather than given a name. Which also keeps the enum at the messages the design record pins and no others.

type EventDigest

type EventDigest [32]byte

EventDigest is the fingerprint of a run of events — in practice the events one turn produced, which is what a Turn carries.

It is a **different type** from the data digest on purpose, and not because two hashes want two names. The two answer different questions and confusing them would be a check that passed while measuring nothing: the data digest asks "will these two peers simulate the same battle" once, at the gate, and this one asks "did they, this turn" every turn. Sharing seed.Digest between them would make comparing a data digest to an event digest compile.

func DigestEvents

func DigestEvents(events []battle.Event) (EventDigest, error)

DigestEvents is the fingerprint of a run of events, and it lives **here** rather than in either peer because both of them have to compute it identically — two implementations of it is the drift this repository bans everywhere else, and the one place it would show up is a divergence report that was itself the divergence.

Each event is **framed** the way seed.digest frames a file: its byte length as a fixed-width big-endian integer, then its bytes. The bytes are what json.Marshal writes off battle.Event's own tags, so the shape of an event is still declared in exactly one place — a field added there enters this digest with no edit here, which is the property TestTheEventDigestReadsEveryFieldOfAnEvent holds by walking the struct rather than by naming fields.

Two things about the framing were decided rather than copied, and this is the second user of the idea seed introduced, so both are written down:

  • **The name half of seed's framing has no analogue here and is left out.** There, the name catches a *rename* — the same bytes read under another file name — and does nearly all the work, because a file's name is not in the file. An event's identity *is* in its bytes: `kind` is a field, and it is the first thing marshalled. So a name prefix here would be a second copy of something already inside the frame, which is the one kind of redundancy this repository consistently refuses.
  • **The length half is kept, and its justification is stronger here than it was there** — though it still has no test that isolates it, and that is worth saying rather than implying. A stream of marshalled events is self-delimiting *because of a property of the encoder*: every event begins `{"kind":"` and json.Marshal escapes every quote inside a string, so no free-text Note can forge that sequence and no two different runs of events can concatenate to the same bytes. Which means the collision seed could write down (a boundary moved across a copy of the next file's own name) cannot be built here at all. The length is what makes the framing unambiguous without resting on the escaping, for eight bytes an event.

⚠️ Not shared with seed.digest, deliberately. The two framings are different — that one walks an fs.FS and prefixes a name, this one walks a slice and prefixes nothing — so a shared helper would be the union of both with each caller passing a piece it does not use, and it would have to live in a third package that both internal/seed and internal/wire import, since internal/core may not. What is genuinely common is sha256 plus a big-endian length, and both of those are already the standard library. Restating six lines is cheaper than a package, and the difference between the two framings is a fact worth having visible at both sites.

An error rather than a swallowed one for the reason seed's digest returns one: a partial digest is worse than none, because two peers that both skipped the same unencodable event would agree and carry on.

func (EventDigest) MarshalJSON

func (d EventDigest) MarshalJSON() ([]byte, error)

MarshalJSON writes the digest as hex rather than as thirty-two numbers.

func (EventDigest) Short

func (d EventDigest) Short() string

Short is the first twelve hex characters, for a person reading two screens side by side. ⚠️ Never compare on this, for the reason seed.Digest.Short says: forty-eight bits is plenty to tell two turns apart at a glance and nowhere near enough to be the check that decides whether two peers are still fighting the same battle.

func (EventDigest) String

func (d EventDigest) String() string

String is the whole digest, sixty-four lowercase hex characters, which is the form that travels and the form a divergence gets reported in.

func (*EventDigest) UnmarshalJSON

func (d *EventDigest) UnmarshalJSON(raw []byte) error

UnmarshalJSON reads it back, and a malformed one is an error rather than a zero digest: two peers agreeing on the digest of nothing is the failure this check exists to catch.

type Format

type Format int

Format is the room's size: how many units a side fields.

⚠️ Its value **is** that number, which is what makes it the one enum here that is not written by name. A kind and a code serialise by name because their values are positions in a declaration and inserting a constant would reinterpret every message already written; three is three whichever order these two lines are in, so there is nothing for a rename or an insertion to break. A `Format` of 4 is refused rather than misread.

const (
	// Format3v3 is three units a side.
	Format3v3 Format = 3
	// Format5v5 is five units a side, and a host will open one.
	//
	// ⚠️ **This comment said the shipped balance was read at five a side, and that
	// was never true.** Every figure in the repository was read at three or fewer:
	// `roster.json` has been 3v3 since it stopped being a mirror, the screened
	// formation was priced on it, a spar is a duel and the five shipped squads are
	// three units each. The board nobody had read was this one, and it has now been
	// read — → `docs/balance.md` § *Five a side, read at last*.
	//
	// It was held back for one measured reason, and that reason is gone: a summon
	// lives in the gap between what a side FIELDS and what the board ADMITS, and
	// one constant was doing both jobs, so at this format there was no gap and
	// every summoning skill was a dead slot. The constant is now two —
	// `hex.MaxSquadSize` against `hex.BoardSlots` — and the readings at the wider
	// board are in `docs/balance.md` § *Five a side, read at last*. → `ENG-013`.
	Format5v5 Format = 5
)

func (Format) String

func (f Format) String() string

func (Format) Units

func (f Format) Units() int

Units is how many units a side fields, which is the format's own value.

func (Format) Valid

func (f Format) Valid() bool

Valid reports whether the format is one the room offers.

type Hello

type Hello struct {
	Version
	// Squad is the placement this player brings, by reference.
	Squad placement.Squad `json:"squad"`
	// Name is what the other player sees. It is the one free-text field in the
	// protocol and it is **not** prose in the sense the record bans: nothing
	// words it, nothing branches on it, and it is the player's own writing
	// rather than the server's.
	Name string `json:"name,omitempty"`
	// Password is the room's password, or empty for a room with none.
	Password Password `json:"password,omitempty"`
	// Watch is this client asking to **watch** the match rather than play it. A
	// watcher takes no seat, so what it asks for is to be sent the match rather
	// than to be asked for a decision in it; the room answers by welcoming it
	// with no seat at all (→ Welcome.Watching).
	//
	// ⚠️ **The joiner is what says which it means, and that is the whole reason
	// this field exists.** A room's code is twelve characters and the twelve a
	// watcher pastes are the same twelve a player pastes, so either the room
	// hands out a second kind of code or the joiner says which it means. The
	// second is cheaper — one flag against a second code space, a second thing
	// for a host to print and a second thing to mistype — and it is a change to
	// what a hello *says* rather than a change to what a code *is*.
	//
	// ⚠️ **A watcher's squad is ignored, and the asymmetry with a room that
	// drafts is deliberate rather than an oversight.** A squad brought to a room
	// that drafts is refused (CodeSquadUnwanted), because a squad quietly dropped
	// would be a player watching the side they spent an evening building fail to
	// appear with nothing saying why. That argument does not reach a watcher at
	// all: a watcher expects **no side of its own**, so there is nothing that
	// fails to appear and nothing to misread. So this needs no refusal — not
	// CodeSquadUnwanted, whose wording says in as many words that the room drafts
	// and to join again with no squad chosen, which would send a watcher to fix
	// something that is not wrong, and not a code of its own either. Nothing here
	// enforces that; a hello is a shape and the room is what decides.
	//
	// It carries no omitempty, for the reason Welcome.Drafts does not: a client
	// that means to play writes `false` rather than nothing, so what a joiner
	// asked for reads whole in a log and in the golden.
	Watch bool `json:"watch"`
	// Token is a seat this client already had, shown to take it back after the
	// socket between them closed.
	//
	// ⚠️ **A token is checked BEFORE the room is asked whether it is full**,
	// because a rejoining client's seat is exactly what makes it full — that is
	// the whole shape of a rejoin, and a gate that asked about space first would
	// refuse every rejoin that mattered. → room.Room.Join.
	//
	// An empty token is an ordinary join and is not a failure: a client that
	// never had a seat has nothing to show, and a client whose token no longer
	// matches anything is told the room is full, which is true.
	Token SeatToken `json:"token,omitempty"`
}

Hello is the first thing a client says. Client → server.

It carries the three version numbers inline (see Version), the squad the player built on their own machine, the room's password, a name for the other player to read, and whether this client means to watch rather than play.

The squad is a placement.Squad and not a resolved roster, which is the whole reason a client can be trusted with it: a Placement is a *reference* — character, level, stage, four skills, one trait, a slot — and carries no stat line at all, so an inflated one is unrepresentable rather than caught. The server resolves it with Squad.Take, which is already the legality check.

func (Hello) Kind

func (Hello) Kind() Kind

Kind is KindHello.

type Kind

type Kind uint8

Kind names which of the ten messages an envelope carries.

Four go from a client to a server and six come back. There are deliberately no others: see the note on Turn for the series-standing message that is missing on purpose, the note on Closed for why the one server-side ending message is not one kind per way a match can end, and the note on Decide for why a whole ban-and-pick is two kinds rather than five.

⚠️ **Declaration order does not group by direction and cannot be made to.** The first eight read client-then-server because that is the order they were written in; the draft's two append after them, one of each direction, because appending is the rule this enum is held to — see KindDrafted. So read a kind's own comment for which way it travels, never its position.

const (
	// KindHello is the first thing a client says: the three version numbers, the
	// squad it brings, the room's password and a name to show the other player.
	// It is the only message with a gate in front of it — see Version.Check.
	KindHello Kind = iota
	// KindAct is a client spending its turn. A skill and an aim, and nothing
	// else; see Act for why it names no unit.
	KindAct
	// KindPass is a client giving its turn up. It carries nothing at all; see
	// Pass, which is where the reason would have gone and why it does not.
	KindPass
	// KindWelcome is the room accepting a client: the room's configuration and
	// which of the two seats this client took.
	KindWelcome
	// KindRefused is the room turning a client away, as a Code and nothing else.
	KindRefused
	// KindStart opens a battle of the series: the seed, the roster both peers
	// build their engine from, which side this client plays and which battle
	// this is.
	KindStart
	// KindTurn is one resolved turn: the decision that was taken and the digest
	// of the events it produced, which is what makes a divergence loud on the
	// turn it happens rather than a board that quietly drifts.
	KindTurn
	// KindClosed is the room saying the match is over for a reason the board
	// cannot show — today a peer that went away, as a Closure and nothing else.
	// See Closed for why an ending a client can compute for itself gets no
	// message at all.
	KindClosed
	// KindDecide is a client taking one decision of the ban-and-pick: a ban, a
	// skip, a pick, a loadout or an arrangement, tagged with which. See Decide
	// for why it is one kind and not five, and why it names no seat.
	KindDecide
	// KindDrafted is the room saying what the draft recorded, in the order it
	// recorded it. A batch rather than one decision a message; see Drafted, which
	// is also where the digest a reader will look for is accounted for.
	//
	// Declared last, which is the rule this enum shares with battle.Kind: a kind
	// serialises by name, so appending cannot reinterpret anything already
	// written, while slotting one in beside KindAct would move KindCount and
	// every table built from declaration order. ⚠️ That is why the two draft
	// kinds are here rather than beside the messages they belong with, and why
	// **this comment has to move with the last constant** — left on a kind that
	// is no longer last it would make the file say something false about itself.
	KindDrafted
)

func (Kind) MarshalJSON

func (k Kind) MarshalJSON() ([]byte, error)

MarshalJSON writes the kind by name, so the format does not depend on the order these constants are declared in.

func (Kind) String

func (k Kind) String() string

func (*Kind) UnmarshalJSON

func (k *Kind) UnmarshalJSON(raw []byte) error

UnmarshalJSON reads a kind written by name, and refuses one it does not know.

This is where an unknown message becomes a clean refusal rather than a parse error or a zero value: a peer one version ahead sends a kind this one has never heard of, and the answer is a Refused carrying CodeUnknownMessage. A zero value would have been the worst of the three — the connection would have carried on, reading every unknown message as a hello.

type Pass

type Pass struct{}

Pass is a client giving its turn up. Client → server. **It carries nothing at all**, and the empty struct is the point rather than an oversight.

⚠️ There is no reason field. A passed turn's wording lives on battle.Decision, and battle.NoActionReason is this repository's single declaration of it — a client that sent a reason would be a second one, and two callers wording the same choice differently is precisely what made a replay diverge from the log it was replaying once already (→ CLAUDE.md § Mistakes already made here, "One source for a recorded string"). The server records the reason because the server is what writes the log.

It is a struct rather than an alias for nothing so that it satisfies Body and travels as a body-less envelope, which is the one kind Decode accepts empty.

func (Pass) Kind

func (Pass) Kind() Kind

Kind is KindPass.

type Password

type Password string

Password is a room's password, and the design record says plainly what it is **not**: it is not security. This is a plain WebSocket on a LAN, and the password keeps strangers in the house off the board rather than keeping an attacker out.

Two things are owed to it regardless of that, and both are here:

  • It is compared in **constant time** (Password.Equal), so the comparison cannot be timed.
  • It is **never printed**. String and GoString both redact it, which is what makes a `%v` or a `%+v` of any struct holding one safe — fmt calls a field's own String method — and TestARoomPasswordIsNeverPrinted measures exactly that over every message body by reflection.

⚠️ What the redaction cannot cover: the password rides in a hello in the clear, so a peer that logs the raw envelope bytes logs the password. That is the room's discipline to keep, and it is the price of the design record's own decision that a self-signed certificate implying security would be worse than saying there is none.

func (Password) Equal

func (p Password) Equal(other Password) bool

Equal reports whether two passwords match, in constant time.

func (Password) GoString

func (p Password) GoString() string

GoString redacts under %#v as well, which is the other verb a debug line reaches for.

func (Password) Set

func (p Password) Set() bool

Set reports whether there is a password at all. A room with none accepts any hello that gets past the version gate.

func (Password) String

func (p Password) String() string

String is the redaction, and it says the one thing about a password that is safe to say: whether there is one.

type Refused

type Refused struct {
	Code Code `json:"code"`
}

Refused is the room turning a client away: a Code and nothing else. Server → client.

Nothing accompanies the code — no sentence, no field naming what was wrong with the squad, no number. The client holds the same books, the same validator and both language books, so it can say more about its own squad than the server could, in the language the player reads.

func (Refused) Kind

func (Refused) Kind() Kind

Kind is KindRefused.

type RoomCode

type RoomCode string

RoomCode is the twelve characters a player pastes to join a room, and it **carries both the address and the room**: base32 of a four-byte address, a two-byte port and a one-byte room. So pasting the code is enough to connect *and* enough to say which of the rooms behind that address is meant, and nobody has to read an IP down a phone.

It is not a secret and not a name. It is an address in a form a person can retype, which is the whole of it — the password beside it is what keeps strangers in the house off the board, and even that is not security.

func EncodeRoom

func EncodeRoom(at netip.AddrPort, room uint8) (RoomCode, error)

EncodeRoom is the code for one room behind one address.

It refuses anything that is not IPv4. That is a real limit rather than an oversight: sixteen bytes of IPv6 plus a port and a room is base32 of nineteen bytes, which is thirty-one characters and no longer a code anybody retypes. The premise is one LAN, and a LAN hands out v4. An address that arrived as a v4-mapped v6 (::ffff:a.b.c.d) is unwrapped rather than refused, because that is what a listener commonly reports for a perfectly ordinary v4 socket.

Why the room is a byte of the code, rather than a port per room

One process, many rooms, **one listener**. The address and the port therefore name the *process*, and without the seventh byte a code would name the process rather than the room — pasting one would be a coin toss between the rooms running in it. The other way out was a listener per room, and it is the more expensive answer for reasons that have nothing to do with the wire: a port is a finite OS resource that wants a firewall hole, one leaks per crashed room, and it conflates a **room** (an application idea) with a **listener** (an OS one), so a registry keyed by code would be shadowed by a second registry keyed by port — and socket lifetime would become room lifetime, in the one component that has no I/O precisely so that it can be tested. A port per "room" is what appears where a room is a whole *process* (Quake, CS, an Agones fleet), which is the opposite architecture to this one. What it cost is written down: ten characters became twelve. → README.md § *A room, and getting into one*.

The room is a uint8 because that **is** the bound: there is no out-of-range room to refuse, which is a check that cannot be forgotten rather than one written correctly.

func (RoomCode) AddrPort

func (c RoomCode) AddrPort() (netip.AddrPort, error)

AddrPort is the address half of a code, for the caller that is about to connect and does not care yet which of the rooms behind it is meant. Every refusal is Decode's — this adds none of its own and drops none.

func (RoomCode) Decode

func (c RoomCode) Decode() (netip.AddrPort, uint8, error)

Decode is everything a code carries: the address to connect to, and which of the rooms behind that address is meant.

The code is upper-cased before it is decoded, so a player who typed it in lower case is not told their code is wrong: the alphabet is upper-case only, so the fold is total and loses nothing. Anything else — a length that is not twelve, or a character outside A–Z and 2–7 — is an error, because a code that decoded to *some* address would send the player at whatever machine happened to be there.

⚠️ A non-canonical code is refused, and that is about a map key

Twelve characters carry sixty bits and seven bytes are fifty-six, so **four bits are spare** and sixteen distinct strings decode to any one room's bytes. encoding/base32 has no Strict() — unlike encoding/base64 — so it simply ignores the trailing bits, and this was a hole at six bytes too, where two spare bits made four variants.

It matters because the registry keys its map on the **string**. A joiner who pasted one of the other fifteen would look up a key that is not in the map and be told the room is unknown while the room sat right there — the worst shape a bug can have, a correct-looking refusal. So a code is decoded, re-encoded, and refused when the two differ: a variant becomes a clear refusal that names the code which does work, and the canonical string is a sound key.

type Seat

type Seat string

Seat is which of a room's two places a client took, and it holds for the whole match.

⚠️ A seat is not a side. A match fights **both ways round**, because which side you get is worth up to sixty points and only fighting from both ends cancels it, so the side a client plays changes between battles and arrives on Start; the seat does not change at all and arrives once, on Welcome. Two facts, two messages, and a client that read one for the other would draw the wrong half of the board from the second battle on.

It is a named string rather than an iota with a table of names, and that is the cheaper end of the same rule: a string type cannot be reinterpreted by an insertion because it has no declaration order to reinterpret, so it needs no MarshalJSON, no names table and no count to be held against. Kind and Code cannot be strings — they are dispatched on and walked by index — and this is neither.

const (
	// SeatHost is the client that opened the room. It is also the one holding
	// the process, which is a fact about the network and not about the game:
	// nothing in the engine knows or cares which peer is which.
	SeatHost Seat = "host"
	// SeatGuest is the client that joined with the room's code.
	SeatGuest Seat = "guest"
)

func (Seat) Valid

func (s Seat) Valid() bool

Valid reports whether the seat is one a room hands out. The zero value is not: an absent seat means what it says rather than quietly meaning the host.

type SeatToken added in v0.2.0

type SeatToken string

SeatToken is what a client shows to take back the seat it had, and it is the one secret in this protocol that is not a password.

⚠️ **It is a capability, not a name.** Anyone holding it is that seat, so a room hands one only to the connection it just seated, and a client keeps it in memory and never writes it anywhere. It is unguessable rather than unforgeable: there is no signature and no expiry on the token itself — the window a seat is held open for is what bounds it, and that lives in the transport.

It is redacted by String and GoString, for wire.Password's reason: a seat token is worth exactly as much as the password that got the seat, and a debug line that printed one is a debug line that hands a match away.

func NewSeatToken added in v0.2.0

func NewSeatToken() (SeatToken, error)

NewSeatToken makes one, from the operating system's randomness.

⚠️ **It lives here rather than in the room, and that is what keeps the room a state machine.** internal/room reads no clock and draws no randomness — which is what lets a match be driven one message at a time in a test — so the room takes a source (room.Deps.Tokens) and this is the one every real caller hands it. A test hands it a counter.

A failure is returned rather than papered over with a weaker source: a room that cannot make a token should say so and seat nobody, because the alternative is a seat whose rejoin quietly does not work and a client that finds out by losing a match.

func (SeatToken) Equal added in v0.2.0

func (t SeatToken) Equal(other SeatToken) bool

Equal reports whether two tokens match, in constant time. → Password.Equal, which this is the same decision as: a comparison that returns early tells a guesser how much of a guess was right.

func (SeatToken) GoString added in v0.2.0

func (t SeatToken) GoString() string

GoString redacts under %#v as well.

func (SeatToken) Set added in v0.2.0

func (t SeatToken) Set() bool

Set reports whether a client is showing a token at all. An empty one is an ordinary join rather than a bad rejoin, which is why nothing refuses it.

func (SeatToken) String added in v0.2.0

func (t SeatToken) String() string

String is the redaction, and it says the one thing about a token that is safe to say: whether there is one.

type Start

type Start struct {
	Seed uint64 `json:"seed"`
	// Roster is every unit of both sides, resolved, **in the order the battle
	// enlists them** — which is exactly what battle.Log.Roster is, and it is one
	// slice rather than two fields for a reason that is easy to get wrong.
	//
	// ⚠️ The order is load-bearing. atb.Queue.Add assigns seq off a counter in
	// the order battle.New is handed its roster, and seq is the last tie-break
	// in the turn order — so *the caller's slice order decides which side wins a
	// speed tie*, and that is worth up to sixty points in a mirror. Two fields,
	// ally and enemy, would be a second statement of an order the slice already
	// holds, and the peer would have to re-derive the enlistment by concatenating
	// them in a convention written down nowhere.
	Roster []battle.Roster `json:"roster"`
	// Side is the half of the board this client plays, and it changes between
	// battles: a match is fought both ways round. Compare Welcome.Seat, which
	// does not.
	Side hex.Side `json:"side"`
	// Battle is which battle of the series this is, counting from one.
	Battle int `json:"battle"`
}

Start opens one battle of the series. Server → client, once per battle.

This is everything a mirror needs to build its own *battle.Battle: the seed its rolls come from and the roster it was composed with. Nothing else about the battle ever crosses — no board, no health, no statuses, no queue — because the client computes the state by computing the battle.

func (Start) Kind

func (Start) Kind() Kind

Kind is KindStart.

type Turn

type Turn struct {
	// Decision is the action as it was taken, in the same form the log records
	// and Replay reads.
	Decision battle.Decision `json:"decision"`
	// Events is the digest of the events this turn produced on the server, in
	// the order it produced them.
	Events EventDigest `json:"events"`
}

Turn is one resolved turn. Server → client, every turn of the battle including the ones the client itself asked for.

The decision is the whole of what the mirror applies: Replay takes a script of a single decision with a nil fallback, walks through whatever is forced after it, and hands back the prompt it stopped on. The digest is what makes the mirror a *check* rather than a hope — the client compares it against the digest of the events its own battle produced, so a divergence is loud on the turn it happens, with two digests to compare, rather than a board that quietly drifts.

⚠️ There is deliberately **no series-standing message**, and a reader will ask where it went. The client is a mirror: it learns the outcome of each battle from its own Ended event, and it already knows the series length from Welcome.Battles. A standing message would be a second declaration of a fact the client computes — and, worse, the one place two peers could disagree about who is winning while both of their battles agreed.

func (Turn) Kind

func (Turn) Kind() Kind

Kind is KindTurn.

type Version

type Version struct {
	// Protocol answers "can these two talk at all". On a mismatch: refuse.
	Protocol int `json:"protocol"`
	// Build answers "what does the human need to update", and it is **printed
	// and never acted on**. Nothing in this package branches on it, and
	// TestTheThreeVersionNumbersAreActedOnDifferently asserts that by joining
	// two peers whose builds disagree. It is a free-form string because it is
	// for a person: a commit, a tag, whatever the binary knows about itself.
	Build string `json:"build"`
	// Data answers "will these two simulate the same battle", and it is the one
	// a version string cannot stand in for: editing a power in skills.json
	// changes every battle without moving a semver by one character. On a
	// mismatch: refuse at the gate.
	Data Digest `json:"data"`
}

Version is the three numbers a peer announces, and they answer three different questions — which is why there are three of them and not one. → README.md § Three version numbers, because there are three questions.

It is embedded in Hello rather than nested inside it, so the three ride at the top level of a hello's body: they are the first thing a reader of the format should see, and a peer that cannot decode the rest of a hello can still be told which of the three it got wrong.

func Local

func Local(build string) (Version, error)

Local is the version this binary announces: the protocol constant above, the build string the caller was handed, and the digest of the data it embeds.

The build string is a parameter because wire has no way to know it — a version is stamped at build time and read by the binary's own main — and inventing one here would be this package guessing at something it is not the source of.

func (Version) Check

func (v Version) Check(against Version) Code

Check reports how this binary answers a peer announcing itself as v, and CodeNone means join. It is one function rather than three checks at three call sites, because the *order* of the two refusals is part of the answer.

⚠️ Protocol is checked before the data. A peer that cannot speak the protocol must not be told its data is wrong: it may not even be able to read the refusal, the digest it would be arguing about is a field this version of the format may not have in the same place, and the update it actually needs is the binary. TestTheThreeVersionNumbersAreActedOnDifferently pins the order with a peer that is wrong about both.

Build is deliberately absent from the body of this function. It is the only one of the three with nothing to decide.

func (Version) Report

func (v Version) Report(program string) string

Report is the three numbers written out for a person to read to a friend and for a script to cut a field out of, and it is what both binaries answer `-version` with:

hexarena-host v0.1.0
  protocol 1
  data     9034c8522586

⚠️ **One function rather than one per binary, and that is the whole reason it is here.** These three numbers are what two people compare when a room refuses one of them, so two spellings of the output would be two people comparing two different things — the same argument that moved BuildOf into this package. The first line is what the binary *is*; the two indented ones are the numbers a gate actually turns on, in the order Check tests them.

⚠️ **The labels stay in English in every language**, for the reason i18n.JoinVersion's do: `protocol` and `data` are what cmd/hexarena-host prints on its banner and what both version refusals tell a player to read, so a translated copy on one end would break the one instruction those refusals give. Being a wording with nothing to translate is also why it can live here rather than in internal/i18n, which is what keeps cmd/hexarena-tui holding no sentence of its own — → its TestNoScreenHoldsItsOwnWording.

⚠️ **The digest is the short form**, so that all three places a person can read this number — this report, the host's banner and the client's join screen — print the same twelve characters. The full sixty-four are what the wire carries and what Check compares; nobody reads those aloud.

type Welcome

type Welcome struct {
	// Format is how many units a side.
	Format Format `json:"format"`
	// Battles is the series length, and **bo1 is not a special case — it is
	// N = 1**. The room offers 1 or 3; 2 is deliberately not offered, because
	// only an even series cancels the side advantage and only an even series has
	// to invent a rule for a 1–1.
	Battles int `json:"battles"`
	// Allowance is how long a player has to answer one prompt, **in seconds**.
	//
	// ⚠️ Seconds as an int, deliberately not a time.Duration: a Duration
	// JSON-encodes as a count of nanoseconds, which is unreadable in a golden
	// and unreadable to anything that is not Go. And the allowance is **room
	// configuration**, not part of the battle — what enters the engine when it
	// runs out is a Pass, never a timestamp, never a duration, never a reading
	// of a clock. That is why it sits here beside the format and why no
	// battle-carrying message holds a clock reading at all.
	Allowance int `json:"allowance"`
	// Budget is the **chess clock**: how many seconds this client has for the
	// whole match, counted only while the room is waiting on it. Nought is no
	// budget, which is every room that has not asked for one.
	//
	// ⚠️ **It is here for the same reason TurnCap is, and the reason is not
	// symmetry.** A client that did not know its budget would watch a per-turn
	// countdown reach zero on a turn it had ninety seconds for, having quietly
	// run out of clock two turns earlier — a match decided by a number nothing on
	// its screen could show. The allowance tells a client how long *this* turn
	// is; this tells it how long the rest of them are.
	//
	// ⚠️ **It is the same number for both seats and is not a remaining count.** A
	// welcome is sent once, at the join, so a figure that counted down would be
	// stale the moment it arrived; what each side has *left* is the client's own
	// arithmetic over the turns it has spent, exactly as the per-turn countdown
	// is. → room.Config.Budget, where the rule is, and internal/socket, which
	// enforces it.
	Budget int `json:"budget,omitempty"`
	// TurnCap is how many turns one battle may open before the room stops
	// asking, so a runaway cannot hold two people at a board for ever.
	//
	// ⚠️ It is here for the reason the allowance is, and the argument is the one
	// written above: a cap is **room configuration**, not part of the battle.
	// The allowance is here so a client can count down; the cap is here so a
	// client can **stop on the same turn**. Without it a capped battle is
	// invisible to a mirror — the engine emits no Ended at a cap, and it must
	// not, because a cap is somebody deciding to stop rather than a way a
	// battle can end — so the client would sit holding an open prompt on a
	// battle the room had already stopped asking about.
	//
	// That is sufficient with no new message and no Ended: the client is a
	// mirror, so given the cap it reaches the cap on the same turn by the same
	// arithmetic. Two peers agree because they compute the same thing from the
	// same configuration, which is the mirror contract itself. ⚠️ Skipped turns
	// count towards it — a turn is a turn — so a client counting only the turns
	// that arrive on a Turn would sit behind the cap for a whole battle.
	//
	// ⚠️ Three alternatives were considered and refused. → README.md § PvP over
	// a LAN: a constant both peers read (the host loses the setting, and a
	// version skew then desyncs silently where a config field is checked at the
	// handshake), a "battle was capped" message (a protocol bump *and* a second
	// declaration of how a battle ends), and letting the engine emit Ended at
	// the cap (which would make every renderer and --verify learn a room's
	// policy).
	TurnCap int `json:"turn_cap"`
	// Drafts says the two sides ban and pick before they fight, rather than each
	// bringing a squad it built at home.
	//
	// ⚠️ **It is here so a client knows not to bring a squad**, and that changes
	// what Hello.Squad means in such a room: it becomes **unwanted** rather than
	// silently ignored, which is what CodeSquadUnwanted is for. A squad quietly
	// dropped would be a player watching the side they spent an evening building
	// fail to appear, with nothing anywhere saying why.
	//
	// ⚠️ **The ordering is the awkward half, and it is a room's problem rather
	// than this field's.** A hello is the first thing a client says, so it is
	// sent *before* this welcome arrives and a client cannot read this and then
	// decide. So a room that drafts refuses the squad and the client joins again
	// with none; this flag is what makes the second attempt informed rather than
	// a guess, and it is what a client reads to know a draft is coming at all.
	//
	// It carries no omitempty, like every field above it: a room that does not
	// draft writes `false` rather than nothing, so the configuration a match runs
	// under reads whole in a log and in the golden.
	Drafts bool `json:"drafts"`
	// Seat is which of the room's two places this client took, for the match —
	// and **an empty seat is the room's answer to Hello.Watch**: a welcome that
	// names no seat is the room saying this client watches.
	//
	// ⚠️ **There is deliberately no second field saying so.** Seat's own zero
	// value already means "no seat" rather than quietly meaning the host, so a
	// boolean beside it would be a second statement of a fact this field already
	// owns, and the only thing it could add is a disagreement to resolve — the
	// reason Act carries no unit and Pass carries no reason. Welcome.Watching is
	// the reading, derived here once.
	//
	// ⚠️ A watcher is **not a third seat**, and that is a decision about who wins
	// rather than about tidiness: the order the two seats are visited in reaches
	// the roster and the roster's order decides which side wins a speed tie, so a
	// watcher threaded through the same places as the players changes the battle
	// it came to watch. → internal/room/series.go, seatCount.
	Seat Seat `json:"seat"`
	// Token is what this client shows to take this seat back after the socket
	// between them closes. It is empty for a watcher, which holds no seat, and
	// empty from a room whose caller supplied no way to make one — a rejoin is
	// then simply unavailable rather than broken. → Hello.Token, and
	// room.Deps.Tokens.
	//
	// ⚠️ **A rejoin re-sends the SAME welcome and therefore the same token.** The
	// seat did not change, so neither does the capability for it; issuing a fresh
	// one would leave a client that reconnected twice holding a token for a seat
	// it still has under a name the room has forgotten.
	Token SeatToken `json:"token,omitempty"`
}

Welcome is the room accepting a client: the configuration the whole match runs under, and which seat this client took. Server → client.

func (Welcome) Kind

func (Welcome) Kind() Kind

Kind is KindWelcome.

func (Welcome) Watching added in v0.2.0

func (w Welcome) Watching() bool

Watching reports whether this welcome seats a watcher rather than a player, which is exactly the absence of a seat.

⚠️ **It is derived and never stored, and the derivation is the point.** The room, the transport and the screen each have to ask this question, and three callers writing the condition out are three places for it to be written differently — one of them eventually as `Seat != SeatHost`, which is the same answer today and stops being one the moment anything else can sit down. So it is read off Seat.Valid, which is already this package's one declaration of what a seat may be. That is the shape CodeCount and KindCount take for their enums and the shape DraftSteps takes for DraftStep.Valid: one declaration, and everything else asks it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL