CIG2 Patterns
Recipes for the things games keep needing. Written for an agent or author building a game on CIG2 who is about to write a helper the framework already ships.
The code here is indicative, not runnable. Signatures are real; bodies are
often elided. For the exact surface see docs/cig2-cheatsheet.md or go doc.
This document exists because reinvention has actually happened, repeatedly, and was only caught later by a ledger:
- Three demo servers independently wrote the same ~35-line SSE
Connadapter, down to the same struct fields. - Two games independently wrote the same
card.Payloadtype-assert helper — one factored it, one inlined five copies. - Two games independently reinvented a
func() time.Timeseam and both lost test determinism. - Two integration suites wrote a byte-identical recursive
ZoneViewwalker.
None of those authors were careless. They just didn’t know the tool was there.
The wheel index
Scan this first. If your symptom is here, stop and read that section.
| You’re about to write | Use instead | § |
|---|---|---|
A switch gameName anywhere in the framework | RegisterGame in init() | 1 |
A package-level var currentPlayer / var board | Session.SetState | 2 |
s.State().(*tableState), or z, _ := s.FindZone(id); h := z.(*cig2.Hand) | cig2.MustStateOf / StateOf, cig2.MustFindZoneAs / FindZoneAs | 2 |
A switch c := config.(type) over your struct and json.RawMessage in Setup | cig2.DecodeConfig[T] | 1 |
| Your own “who can see this card” check | Zone Visibility + sticky Card.Reveal | 3 |
A round-robin players[(i+1)%len] | TurnTracker | 4 |
A phase string enum + a gameOver bool beside it | PhaseMachine + Halt | 5 |
map[PlayerID]choice + a “have they all submitted yet” count | Collector[T] | 6 |
lastActionAt time.Time + manual subtraction | Clock | 7 |
| A timer plus bookkeeping to stop a stale one firing | Session.Rearm | 8 |
| A nonce or secret in a scheduled action’s data so clients can’t forge it, or re-checking state to guess whether a timer sent it | action.FromTimer() | 8 |
A rollback() after a rejected action, or “undo the move if the target is invalid” | validate everything, then mutate | 24 |
time.Now() inside HandleAction | Session.Now() | 7 |
A Suit/Rank type for a standard deck | deck52 | 9 |
card.Payload.(*deck52.PlayingCard) with an ok check | deck52.PayloadOf | 9 |
| A loop appending N copies of a card | Session.AddCopies | 10 |
| Your own weighted random pick | PickWeighted | 10 |
json.Unmarshal + hand-rolled validation of a content file | content.Load | 11 |
An SSE adapter implementing Conn | ChanConn + sse.Stream | 12 |
A demo main.go with a table struct, token map, reset handler and password check | host.Run (+ host.Flags) | 12 |
A SeatTokenTransport / claimToken() with localStorage caching | new SSETransport({events, action, seat}) — it claims by default | 12 |
Your own /reset or /state route next to Server.Mount (panics at startup) | a different name, or Mount on a sub-mux under a prefix | 12 |
A “connection lost” banner, an onerror → “reconnecting…” label, or location.reload() after a reset | <cig2-table status-banner>, transport.onStatus | 12 |
if (table.hasAttribute('data-stale')) return; at the top of your click/submit handlers | the stale guard (status-banner or stale-guard); table.whenLive(fn) outside the table | 12 |
A tables map or “game started” flag in your server to decide lobby vs board | Registry.Lookup + Registry.Delete (explicit mode) | 12 |
| A per-player field you filter by hand before sending | StatefulGame.GameState | 13 |
A sync.Mutex or channel to read session state from an HTTP handler | Session.Do | 15 |
A time.Sleep after Stop “to let the goroutine finish”, or a per-session log.Printf wrapper | s.Wait(); cig2.WithLogger / host.Server{Logger} | 15 |
Moveing a card within a deck it already occupies (silently no-ops) | Deck.AddTop / Deck.Bottom | 16 |
for _, c := range z.Cards() { s.Move(c, dst) } | Session.MoveAll | 17 |
A pending map[PlayerID]*choice + a catch-all “choose” action + your own timeout | Session.Ask | 18 |
A checkStateBasedActions() call pasted after every mutation, or a for changed { ... } loop in HandleAction | Session.SetSettle | 19 |
enterX(s) called by hand after every Advance | PhaseMachine.OnEnter / NeedsInput | 5 |
A firstRound bool to skip a one-off opening phase on later rounds | NewPhaseMachineWithPrelude | 5 |
A map[uuid]*status side-table cleared on zone exit | Card.SetState / CardState[T] | 20 |
for uuid, st := range myStatusTable to find cards with some state | Session.WalkCards + CardState[T] | 20 |
A *Card field in card state pointing at another card | UUID in state + Session.FindCard | 21 |
| A bot that guesses action names, or a hand-written “what can I do now” endpoint | ActionHinter → snapshot.legal; docs/agent-play.md | 22 |
A recursive findCard(view, uuid) / zoneByID helper over a snapshot | ZoneView.Find / ZoneView.FindZone | 14 |
A test harness that starts a session, attaches fake conns and waits for frames — or HandleAction called directly in a test | cig2test | 14 |
An ackBothPlayers(t, s) loop after Start in a raw-session test | cig2test.AckAll or cig2.WithAckTimeout(0) | 14 |
| A hand-rolled golden helper with a UUID rename, or your own “no hidden payloads” frame walk | cig2test.NewGolden / CheckGolden / AssertNoHiddenLeaks | 14 |
A defer recover() in HandleAction, or a supervisor that restarts the process when a game panics | nothing — the actor recovers; see what it does | 23 |
1. A game registers itself
Adding a game must never require editing framework code. If you find yourself opening a framework file to add a case, that is the bug.
package hearts
import "github.com/PipGrylls/CIG2"
const Name = "hearts"
type Game struct{}
// Compile-time proof this still satisfies the interfaces. Keep these:
// a signature drift that silently stopped satisfying an interface is the
// exact bug that made the predecessor project unable to deal cards.
var _ cig2.Game = (*Game)(nil)
var _ cig2.StatefulGame = (*Game)(nil)
func init() { cig2.RegisterGame(Name, &Game{}) }
func (g *Game) Setup(s *cig2.Session, players []cig2.PlayerID, config any) error
func (g *Game) HandleAction(s *cig2.Session, player cig2.PlayerID, action cig2.Action) error
func (g *Game) CheckEnd(s *cig2.Session) (bool, cig2.Result)A Game value is registered once and shared by every session. It must be
stateless — never store per-table data on it. config is whatever a lobby
passed to WithConfig (host passes a create/reset body’s "config" as
json.RawMessage); decode it with cig2.DecodeConfig[T] rather than a type
switch, and fold it into your table state in Setup:
type Config struct {
Decks int `json:"decks"`
}
func (c *Config) SetDefaults() { c.Decks = 1 } // optional: for nil and missing keys
func (c *Config) Validate() error { /* optional: range checks */ return nil }
cfg, err := cig2.DecodeConfig[Config](config) // nil, Config, *Config or JSON
if err != nil {
return err // wraps cig2.ErrBadConfig: host answers 400, not 500
}JSON is decoded strictly: an unknown key or a wrong type is an error, so a
typo in a lobby’s house rules fails the create instead of silently playing
the default game. games/highcardduel is the reference.
2. Per-table state
All mutable state lives on the session, reachable only from the actor goroutine. There are no package-level game variables, and no mutexes — if you reach for one, the actor boundary has been broken somewhere.
type tableState struct {
Hands map[cig2.PlayerID]*cig2.Hand
Pile *cig2.Pile
Score map[cig2.PlayerID]int
}
// in Setup
s.SetState(&tableState{ /* ... */ })
// anywhere on the actor goroutine
st := cig2.MustStateOf[*tableState](s)Read it back with the typed helpers rather than a bare type assertion:
cig2.MustStateOf[T](s) for state your own Setup stored (a miss is a bug in
your game; the panic is contained and fails the table with a stack), or
cig2.StateOf[T](s) (T, bool) when it may legitimately be absent. Zones the
same way: cig2.MustFindZoneAs[*cig2.Hand](s, "hand-p1") for zones you built,
cig2.FindZoneAs[T](s, id) (T, error) — a rejection — when the ID came from a
client’s action data. The errors name the ID and both types.
For state scoped to one player rather than the table, s.SetPlayerState(p, v)
and s.PlayerState(p) (typed: cig2.PlayerStateOf[T](s, p)).
Setup, HandleAction, CheckEnd, and GameState all run on the session’s
single goroutine, so none of this needs locking.
3. Hidden information
Never write your own visibility check. Zones carry a mode; cards carry a sticky reveal flag; the framework computes the per-viewer filter on every broadcast.
deck := s.NewDeck("deck", cig2.Hidden()) // nobody sees identities
hand := s.NewHand("hand-"+string(p), cig2.OwnerOnly(p)) // only p sees theirs
disc := s.NewPile("discard", cig2.Public()) // everyone sees
face := s.NewDisplay("board", cig2.FaceDown()) // present but unidentified
secret := s.NewHand("secret-"+string(p), cig2.Concealed(p)) // p sees theirs; others: count only
s.Root().AddChild(deck)To turn a card face up permanently:
c.Reveal() // sticky and one-way; survives every later move, whatever the zoneAn opaque card still carries its real UUID on the wire, so a client can animate
“the same physical card” moving between zones without learning what it is.
That UUID is itself information — an opponent can follow one physical card in
and out of an OwnerOnly hand. When that matters, use Concealed: non-owners
get the count and nothing else.
Do not hand-filter card lists before returning them. Filter runs per
viewer at broadcast time from the authoritative tree.
4. Turn order
s.SetTurn(cig2.NewTurnTracker(players))
if !s.Turn().IsCurrent(player) {
return fmt.Errorf("hearts: not %s's turn", player)
}
next := s.Turn().Advance()The tracker reports whose turn it is; it does not enforce anything. Gating is the game’s job, as above.
Extra turns and forced actors use SetCurrent, not a second source of
truth:
// grant another turn: simply don't advance
if st.extraTurns[s.Turn().Current()] > 0 {
st.extraTurns[s.Turn().Current()]--
} else {
s.Turn().Advance()
}
// force a specific player to act
s.Turn().SetCurrent(target)PhaseMachine deliberately takes no actor argument — “who acts” lives here
and only here.
5. Phases
PhaseMachine tracks position in a declared phase order and how many rounds
have begun. It never interprets a PhaseID.
s.SetPhase(cig2.NewPhaseMachine([]cig2.PhaseID{"deal", "bid", "play", "score"}))
if s.Phase().IsPhase("bid") { /* ... */ }
s.Phase().Advance() // moves within the round; parks at the last phaseRound boundaries
NewRound is the only method that increments Round. Advance parks at
the last phase rather than wrapping.
if s.Phase().AtEnd() {
s.Phase().NewRound() // back to the declared order, round + 1
} else {
s.Phase().Advance()
}A game that never calls NewRound sits on its last phase forever.
Game over — don’t add a bool
The temptation is a gameOver bool beside the machine. Use the terminal phase:
s.Phase().Halt("game_over") // sticky, one-way; freezes the machine
func (g *Game) CheckEnd(s *cig2.Session) (bool, cig2.Result) {
if !s.Phase().Halted() {
return false, cig2.Result{}
}
return true, cig2.Result{Winners: []cig2.PlayerID{st.winner}}
}Halt’s label must not appear in the declared order, or IsPhase reports
true for it after the game is decided and a phase switch takes a live branch
on a finished game.
A round with a different shape
One variadic covers “start at a later phase”, “skip a phase this round”, and “run a different order for one round” — a machine tracking position in a sequence cannot tell them apart.
s.Phase().NewRound("upkeep", "main", "end") // no "draw" this roundCustom sequences last one round; the next bare NewRound() restores the
declared order.
Opening phases that happen once — a draft, a mulligan — go in a prelude,
not the declared order, or every bare NewRound() replays them:
s.SetPhase(cig2.NewPhaseMachineWithPrelude(
[]cig2.PhaseID{"draft"}, // round 1 only
[]cig2.PhaseID{"play", "score"}, // every round
))To drop a phase that has not happened yet, mid-round:
// "skip your end step this turn"
s.Phase().SetRemaining(without(s.Phase().Remaining(), "end")...)Read the tail through Remaining(), never by searching Sequence() for the
current phase — with a repeated phase those differ and the tail duplicates.
without is your own five-line slice filter; the framework ships no sequence
editors, because “here is the sequence for this round” is a tool and “skip this
step” is one game’s feature.
Deferred effects are game policy
“On the target’s next turn they skip untap” is deliberately not a framework feature — which player, how many turns, whether it stacks, whether it survives an extra turn all differ per game.
// when the effect resolves — ordinary game state
st.skip[target] = append(st.skip[target], "untap")
// at the round boundary
seq := s.Phase().Order()
if skips := st.skip[p]; len(skips) > 0 {
seq = without(seq, skips...)
delete(st.skip, p)
}
s.Phase().NewRound(seq...)Entry logic and phases that play themselves
Don’t call enterDraw(s) by hand after every Advance — one path always
forgets. Register it:
m := cig2.NewPhaseMachine([]cig2.PhaseID{"untap", "draw", "main", "cleanup"})
m.OnEnter("untap", untapAll) // func(s *cig2.Session)
m.OnEnter("draw", drawOne)
m.NeedsInput("untap", func(*cig2.Session) bool { return false })
m.NeedsInput("draw", func(*cig2.Session) bool { return false })
m.NeedsInput("cleanup", func(s *cig2.Session) bool { return mustDiscard(s) })
m.OnRoundEnd(func(s *cig2.Session) { s.Turn().Advance(); s.Phase().NewRound() })
s.SetPhase(m)Hooks run in the settle after the action (and after Setup), before
CheckEnd and the broadcast, so nobody ever sees a phase whose entry logic
hasn’t happened. Phases whose NeedsInput says false are passed through one
per settle pass — with your settle steps (§19) in between, so a loss
condition halts the game before the machine runs on. A phase with no
predicate waits for input, so adding hooks never skips a phase by surprise.
A phase that is itself a short ring
Don’t ask for nesting — compose a second machine, held by your own state:
type showState struct{ round *cig2.PhaseMachine }
st.show.round = cig2.NewPhaseMachine([]cig2.PhaseID{"non_dealer", "dealer", "crib"})
if st.show.round.AtEnd() {
s.Phase().Advance() // inner ring done, move the outer one
} else {
st.show.round.Advance()
}6. Simultaneous commit-then-reveal
Everyone commits secretly, then it resolves together — a blind bid, a simultaneous draft pick, a pair of face-down discards.
st.picks = cig2.NewCollector[Choice](s.Players())
// in HandleAction
if st.picks.Submit(player, choice) {
// every expected player is in. Reveal and resolve HERE, before returning.
for p, c := range st.picks.All() { /* ... */ } // declared order
}Resolve with All(), not by ranging over Values(): Values() is a map, Go
randomizes map order on every range, and a resolution that draws from
s.Rand() once per player would then consume the RNG in a different order
each run — a seeded replay (WithSeed) diverges. The same goes for any map
you range while drawing randomness, logging or breaking ties: range a sorted
key slice or a declared-order slice instead.
Build a fresh Collector per round — there is no Reset, the same way you
build a fresh Deck rather than emptying one. A ruleset may run several at
once, which is why a Session never holds one.
You do not need to suppress broadcasts. Resolve inside the same
HandleAction whose Submit returned true and the framework’s ordinary
post-action broadcast already carries the resolved state. Apply no visible
effect before that and no player ever sees a half-committed board.
7. Clocks
Clock is a plain stopwatch value — zero value useful, caller-supplied time.
It owns no budget, no increment, and no notion of whose turn it is, so it
composes into countdown, count-up, Fischer increment, or clock-as-score.
// Note the pointer. Clock's methods have pointer receivers and map elements
// are not addressable, so map[PlayerID]cig2.Clock will not compile at the
// first .Start(). A struct field can be a plain cig2.Clock.
type tableState struct {
clocks map[cig2.PlayerID]*cig2.Clock
budget time.Duration
}
now := s.Now() // NOT time.Now() — see below
st.clocks[player].Start(now)
// ...later
st.clocks[player].Stop(now)
remaining := st.budget - st.clocks[player].Elapsed(now)There is no singleton clock on Session, deliberately: a game runs as many as
it needs. That is what lets two players’ clocks run independently through a
simultaneous discard phase, with no framework change.
Read time through s.Now(), never time.Now() directly. It defaults to
time.Now and a test replaces it wholesale with cig2.WithNow(...), which is
the difference between asserting an exact elapsed value and asserting > 0.
Now does not cache: capture it once per action and pass that value to every
clock you touch.
The stint invariant — this one shipped a silent bug
A stint is one unbroken run of Running() time.
Every transition must close the outgoing stint with exactly one
Stop+Adjustbefore anyStartopens the next — including transitions your phase machine performs implicitly, mid-HandleAction.
Key your clock logic off “did this stint end”, not “which phase am I in”.
A real game got this wrong twice: once where whether a player got their
increment depended on whose discard arrived second, and once across a redeal
where Start on an already-running clock was a silent no-op. No error, no
failing test, no wrong winner — just quietly wrong remaining time.
Any game crediting an increment needs at least one test with a non-zero
increment. At zero, Adjust(-increment) is a no-op and the entire path is
unreachable — which is exactly how that bug survived a full test suite.
8. Repeating timers
For a one-shot delay, s.Schedule(after, player, action). For anything that
re-arms — a per-turn timeout, an idle timer, a chess clock — use Rearm and
write no staleness bookkeeping at all:
// re-arming each turn needs no explicit cancel: the next Rearm supersedes
s.Rearm("turn-timer", remaining, current, cig2.Action{Name: "timeout"})
// only needed to stop without re-arming
cancel := s.Rearm("idle:"+string(p), 30*time.Second, p, timeoutAction)
cancel()Each armed timer carries an epoch for its key, and a delivery whose epoch was superseded is dropped before your game sees it. Keys are an opaque namespace you choose.
Timer-only actions
A timer delivers an ordinary Action to HandleAction, and a client can POST
the same name. Don’t defend with nonces or by re-checking state to guess who
sent it: the framework tags every action with where it came from, and that tag
never comes from the wire.
case "timeout":
if !action.FromTimer() { // action.Origin == cig2.OriginTimer
return errors.New("timeout is not a player action")
}Everything a player sends — wire frames, Submit, Apply — arrives as
OriginPlayer, whatever the caller set. Test a timer-only action with
tbl.Fire("p1", "timeout", nil) (cig2test) or s.ApplyTimer(p, action),
which run the real timer path without waiting. Names starting with cig2.
belong to the framework; don’t use them for your own actions.
9. Standard 52-card decks
Opt-in; the framework never imports it. A game with non-standard cards simply doesn’t use it.
import "github.com/PipGrylls/CIG2/deck52"
func init() {
cig2.RegisterGame(Name, &Game{})
deck52.Register(Name) // registers the playing_card payload
}
for _, pc := range deck52.StandardDeck() {
deck.Add(s.NewCard(pc))
}Getting back to the payload has a helper — do not write the assert yourself:
pc, err := deck52.PayloadOf(c)
if err != nil {
return err // error names the card UUID and the type actually found
}deck52 holds properties of a French-suited deck (Suit.IsRed), never rules
of a game played with one — cribbage counts face cards as ten and blackjack
disagrees, so pip value stays in the game.
10. Weighted content
Two different problems, deliberately kept apart.
Building a pile with a fixed distribution — expand copies, then shuffle:
n := s.AddCopies(deck,
cig2.CardSpec{Payload: common, Copies: 12},
cig2.CardSpec{Payload: rare, Copies: 3},
cig2.CardSpec{Payload: mythic, Copies: 1},
)
deck.Shuffle(s.Rand())That gives exactly a 12:3:1 draw distribution with an order reproducible from a
seed. This is why there is no weighted draw on Deck: it would randomise
twice, and neither deck order nor Count() would describe what comes out.
Every copy from one CardSpec shares that payload pointer. Never mutate a
payload afterwards — every copy changes at once.
Sampling with replacement from something that isn’t a deck — a random event, an encounter table:
event, ok := cig2.PickWeighted(s.Rand(), []cig2.Weighted[Event]{
{Value: calm, Weight: 5},
{Value: storm, Weight: 2},
})Weights are integers; only ratios matter; weight <= 0 is never picked; the
input is never mutated.
11. Declarative content
For card tables shipped as embedded JSON, so a designer edits data rather than Go.
//go:embed content/cards.json
var contentFS embed.FS
type CardDef struct {
ID string `json:"id"`
Cost int `json:"cost"`
}
type CardTable struct{ Cards []CardDef `json:"cards"` }
// optional self-validation — the framework never learns what a card is
func (t *CardTable) Validate() error {
seen := map[string]bool{}
for _, c := range t.Cards {
if seen[c.ID] {
return fmt.Errorf("duplicate card id %q", c.ID)
}
seen[c.ID] = true
}
return nil
}
var Cards = content.MustLoad[CardTable](contentFS, "content/cards.json")Decoding is strict: a key that matches no field of your type ("cots" for
"cost") or anything after the top-level value fails the load, naming the file
and the key. Pass content.AllowUnknownFields() for a file that legitimately
carries extra keys.
Cross-file consistency (a template referencing an effect ID from another file)
composes trivially: Load each file, then run your own domain check across the
results.
12. Transport
This is the most-reinvented thing in the codebase. Do not write a Conn
adapter.
conn := cig2.NewChanConn(16)
if err := session.Attach(player, conn); err != nil { /* ... */ }
defer conn.Close()
// the whole SSE handler
if err := sse.Stream(w, r, conn); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}ChanConn is production-capable, not a test double: its Send is non-blocking,
so a slow or dead browser can never block the session’s actor goroutine. Frames
may be dropped under backpressure, which is safe because CIG2 sends full
snapshots, never diffs — the next one is complete.
*cig2.ChanConn satisfies sse.Source structurally; neither package imports
the other. The browser half ships in web/transport-sse.js.
And don’t write the rest of the server either. The table and seat-token
bookkeeping, reset, action POST, password gate, cross-origin protection,
timeouts and graceful shutdown that every game’s main used to repeat are
host.Run:
//go:embed static
var staticFS embed.FS
func main() {
static, _ := fs.Sub(staticFS, "static")
cfg := host.Config{
Game: mygame.Name,
Seats: []cig2.PlayerID{"p1", "p2"},
Auth: host.Auth{PasswordEnv: "APP_PASSWORD"},
Static: static, // your page at /
}
host.Flags(flag.CommandLine, &cfg) // -addr, -password-env, -sync-actions, ...
flag.Parse()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := host.Run(ctx, cfg); err != nil {
log.Fatal(err)
}
}cmd/cig2-demo is exactly this. For tests, host.NewHandler(cfg) builds the
same surface without listening. Compose by hand —
(&host.Server{Registry: reg}).Mount(mux) behind host.Auth{...}.Wrap — only
when you need a shape Run does not give; then set ReadHeaderTimeout
yourself and register reg.Close with RegisterOnShutdown.
Secure by default. Seat tokens are on (Server.InsecureSeats turns them
off for a trusted local playtest), so the app password alone no longer lets
one player watch another’s seat. Unsafe-method requests that a browser marks
cross-site are refused (Server.TrustedOrigins admits named origins), because
Basic Auth credentials ride along on another site’s form POST. The same
protection covers your own Config.Routes. A 500’s body is generic; the error
goes to the log.
Invite links instead of sharing the password. One player signs in with the app password and sends one-time seat links. A guest who opens one plays without being asked for the password. Turn it on and the framework does the rest:
cfg.Server.Invites = true // or -invitesThe host goes to /cig2/lobby (where / redirects until the game has its
own page), starts a game, takes a seat, and copies a link for each other
seat. The link opens a public join page. “Take the seat” redeems the link,
sets a grant cookie that passes the password gate, stores the seat token
where SSETransport looks, and sends the guest to /?table=ID&player=SEAT.
For that last step, the board page reads the table and seat from the address:
import SSETransport from '/cig2/transport-sse.js';
import { tablePaths } from '/cig2/invite.js'; // also defines <cig2-invite>
const p = tablePaths();
table.transport = new SSETransport({ events: p.events, action: p.action, seat: p.seat });To make links from the board itself, add <cig2-invite table="ID" exclude="p1"></cig2-invite> for the host.
What the framework guarantees:
- Making a link reserves the seat, so nobody can take it first.
- A link works once, and opening the page doesn’t spend it.
- A grant is not the password: the invite routes, plus host’s own reset,
create, claim and delete, are
HostOnly. A guest plays but can’t start, reset or delete games, or make links.isHost()lets a page hide those controls. - A link for a seat that is already taken is a recovery link. It moves the seat to whoever opens it, which covers a second device or cleared storage.
Wrap your own host-only routes the same way:
mux.Handle("POST /start", host.HostOnly(startHandler))Open locally, password in production. Don’t name the password variable in
code — a named PasswordEnv that is unset always fails, even with
AllowOpen, so that a production deploy missing its password refuses to start
rather than coming up open:
cfg.Auth = host.Auth{AllowOpen: true} // `go run`: no password, loopback clients only
host.Flags(flag.CommandLine, &cfg) // production: -password-env CARDS_APP_PASSWORDPut -password-env NAME in the production command line (the systemd unit, the
Dockerfile). Never serve with -allow-open and no password behind a
reverse proxy on the same host (Caddy, nginx): every request then arrives from
loopback, and the server is open to anyone who can reach the proxy.
A lobby, or any index of your own. Register GET /{$} in Config.Routes;
it wins over Config.Static for exactly /, while Static still serves your
scripts and styles:
cfg.Routes = func(mux *http.ServeMux, reg *host.Registry) {
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
if _, ok := reg.Lookup(tableFor(r)); ok {
serveFile(w, r, "board.html")
return
}
serveFile(w, r, "lobby.html")
})
mux.HandleFunc("POST /start", startTable) // CSRF-protected like host's routes
}With reg.SetExplicit(true) (via Config.Registry) the lobby creates tables
and Registry.Delete ends them; see “Tables that end” below.
It is optional by design: the core never imports it, and a server with a
different shape wires cig2.Session directly.
The browser side needs nothing: new SSETransport({events, action, seat})
claims the seat (the claim endpoint defaults from events), caches, sends and
re-claims the token itself (see web/AGENTS.md). Don’t write a token
transport.
Mount owns /events, /action, /reset, /state, /tables, /create,
/claim, /release, /cig2/ and /t/…: registering a game route with one
of those names on the same mux panics http.ServeMux at startup (three demos
hit this). Rename yours, or mount host under a prefix —
mux.Handle("/play/", http.StripPrefix("/play", hostMux)).
Connection status
A stream that drops with no new snapshot — a server restart, a reset, a second tab taking the seat — leaves a board that looks live and isn’t. Don’t hand-roll the cue:
<cig2-table id="table" status-banner> … </cig2-table>That one attribute shows why the board is not live (reconnecting, the table
was reset, the server is restarting, opened in another tab, refused, no such
table), greys the board out and disables its data-cig2-action controls until
a fresh snapshot arrives, and offers a reconnect button when the transport has
stopped for good. Without it, data-status, data-status-reason and
data-stale are still on the table for your own CSS, and
transport.onStatus((status, detail) => …) / transport.status drive any
custom UI.
The states come from SSETransport (connecting, open, reconnecting,
game-over, and the terminal displaced, seat-taken, forbidden,
not-found, closed). host makes them precise: every stream it closes on
purpose ends with a farewell frame naming the reason, so a reset reconnects
at once and a displaced tab stops instead of stealing the seat back. Wire
httpServer.RegisterOnShutdown(reg.Close) so a restart says so too.
The banner brings the stale guard (or use stale-guard alone): while
stale, input is blocked board-wide in the capture phase — delegated
handlers, onclick, onsubmit, card and zone clicks — so handlers need no
data-stale checks of their own. table.send() is dropped (returns
false, fires cig2-dropped), never queued. Mark anything that must stay
usable (a debug panel, a reset button) data-cig2-live, and wrap handlers
that live outside the table with table.whenLive(fn).
Tables that end
A game with a lobby decides “lobby or board?” by whether the table exists —
reg.Lookup(id) — so a finished table must be able to stop existing.
reg.Delete(id) closes it, ends its streams with a "deleted" farewell (the
transport goes terminal not-found, banner “This table was closed.”) and
frees the ID for Create. Use it with SetExplicit(true): in
create-on-first-use mode any later request for the ID starts a fresh table.
Over HTTP it is POST /t/{table}/delete, only with
host.Server{AllowDelete: true}. Don’t keep your own table map beside the
registry.
13. Per-player views
For state that is neither a card nor a zone — a score, a house rule, a bid. Optional: skip the interface and your snapshots are unchanged.
func (g *Game) GameState(s *cig2.Session, viewer cig2.PlayerID) any {
st := cig2.MustStateOf[*tableState](s)
return stateView{
Scores: st.Scores,
MyBid: st.Bids[viewer], // the game IS the filter here
}
}The framework never inspects what you return — whatever you return, that viewer
sees. Return nil to omit the field.
Do not mirror framework state into it. Snapshot already carries Turn,
Phase, Round, Over, and Result, all read live at broadcast time:
// Wrong: a hand-maintained copy that goes stale mid-action.
st.View.Phase = string(s.Phase().Current())
// Right: nothing. The snapshot fills it from the machine.14. Integration tests
Unit tests of the pieces are not enough — the predecessor’s card-dealing bug shipped because nothing ever played a full game and checked what each player received. Drive a real session over real channels and assert on wire bytes.
s := cig2.NewSession("t1", &Game{}, []cig2.PlayerID{"p1", "p2"},
cig2.WithRand(rand.New(rand.NewPCG(1, 2))), // deterministic deal
cig2.WithNow(func() time.Time { return fixed }), // deterministic clocks
)
c1 := cig2.NewChanConn(16)
s.Attach("p1", c1)
s.Start()
cig2test.AckAll(t, s) // or cig2.WithAckTimeout(0) above — see below
raw := <-c1.Messages()
snap, err := cig2.UnmarshalSnapshot(raw, Name)
// assert p1 sees their own hand and NOT p2's
hand, _ := snap.Root.FindZone("hand-p2") // no hand-written tree walk
if c, ok := snap.Root.Find(dealtUUID); ok && c.Payload != nil { /* leak! */ }Assert the negative case explicitly: that a player’s view of an opponent’s
OwnerOnly hand carries counts but no identities. A leak test that only checks
what a player can see proves nothing.
Scripted tests with raw sessions: ack or disable the timeout. A session
waits 5s for every seat to send the join-handshake "ack", then marks each
seat that hasn’t acked as disconnected, and a disconnected seat is sent no
more snapshots. A raw session in a test (Start without cig2test) never
acks unless you do it. Its script runs fine for five seconds, then reads stale
frames, which looks like nondeterminism even with a fixed seed. One game lost
a day to this before writing its own ackBothPlayers(t, s). That helper is
the recipe, and it now ships as cig2test.AckAll(t, s); call it right after
Start. Alternatively, pass cig2.WithAckTimeout(0) to disable the timeout
for that session. cig2test.Start acks every seat already, and it fails the
test if one is dropped anyway. A dropped seat is never silent: the session
logs a Warn record naming the seat and the timeout, and
s.Connected(p) reports false. cig2.WithAckTimeoutHandler(fn) replaces
that Warn. The host uses it to log unclaimed seats at Debug, since those
never ack.
For rule-by-rule tests, don’t hand-roll a harness around a started session
(one game did), and don’t call HandleAction directly — since the settle loop
and phase hooks run only inside the actor, that skips half your rules. Use
cig2test, which applies each action synchronously through the real path
and returns what every seat was sent:
tbl := cig2test.Start(t, mygame.Name, []cig2.PlayerID{"p1", "p2"})
step := tbl.Act("p1", "play", map[string]string{"card": uuid})
if step.Err != nil { t.Fatal(step.Err) }
if c, ok := step.Snapshot("p2").Root.Find(uuid); ok && c.Payload != nil { /* leak */ }
step = tbl.Answer("p1", step.Snapshot("p1").Decisions[0].ID, "keep")Fuzzing, golden snapshots, benchmarks
The framework ships three more kinds of test, worth copying into a game:
Fuzz targets (
fuzz_test.goand its siblings) assert invariants on arbitrary input — every frame a client can send reaches the game asOriginPlayer, decoded configs round-trip, a reset body is never a 500. Their seeds (f.Addplustestdata/fuzz/) run under plaingo test; fuzz one withgo test -run='^$' -fuzz='^FuzzX$' -fuzztime=1m ./pkg, and commit any failing input it writes totestdata/fuzz/along with the fix. CI fuzzes each target for a fixed execution count (-fuzztime=Nx, never a duration — a duration can trip a Go toolchain race at the deadline).Golden snapshots pin every frame each seat receives across a scripted, seeded game. Use cig2test’s helpers rather than writing your own (
games/highcardduel/golden_test.gois the reference):var update = flag.Bool("update", false, "rewrite testdata/golden") g := cig2test.NewGolden() // one per game, so a card keeps its name for i, s := range steps { cig2test.AssertNoHiddenLeaks(t, s.step) path := fmt.Sprintf("testdata/golden/%02d-%s.json", i, s.name) cig2test.CheckGolden(t, path, g.Render(t, s.step, "p1", "p2"), *update) }Renderrenames card UUIDs (random per run) to c1, c2, … in a fixed order — seats as given, keys sorted — and replaces them everywhere, including bare UUID strings in hint data and game state and map keys.AssertNoHiddenLeakschecks each seat’s typed views: no identity on an unrevealed card the seat can’t see, no entries in Hidden (or someone else’s Concealed) zones, no UUIDs in FaceDown ones. Rewrite withgo test -run TestGolden -update -count=1— always-count=1, or the test cache can replay an old pass without writing anything — only for a deliberate wire change, and review the diff: it shows exactly what each player can now see.Seeded replays are byte-identical — the framework’s contract, pinned by
determinism_test.go(50 fresh runs per mode, through shuffles, reshuffles, an RNG-built deck, aCollectorround,Fired and real timers): the sameWithSeed, game and action script produce the same frames onceRenderhas renamed UUIDs. Card UUIDs are not seeded — they come fromcrypto/randand never touch the session RNG, so they cannot shift a shuffle, but they differ every run: compare rendered frames, never raw ones, and never order anything by UUID (a sort by UUID, or ranging amapkeyed by UUID, is a different order every run). If a seeded replay of your game diverges, look for amapranged while drawing froms.Rand()(Collector.Valuesincluded — useAll), a real timer racing a scripted action (deliver timers withtbl.Fire), or RNG drawn outside the actor.Benchmarks (
benchmarks_test.go) cover the action hot path; the baselines are indocs/benchmarks.md.
15. Reading session state from outside
You’re building a lobby endpoint, an admin page, or a test that needs to stage a precondition no legal action sequence reaches — and every other way to touch session state is actor-only. Reaching for a mutex here is exactly the actor-boundary violation this framework exists to avoid.
var playerCount int
s.Do(func() {
playerCount = len(s.Players())
})
// playerCount is safe to read here — Do already waited for fn to finishDo runs fn on the actor goroutine and blocks until it returns, so fn
sees a consistent snapshot of whatever it touches and nothing races it —
that’s what -race on TestDoRunsOnTheActorAndWaits proves. It never
deadlocks: called from the actor goroutine itself (inside Setup,
HandleAction, or CheckEnd) it runs fn inline rather than queueing onto
a channel only that same goroutine reads; called before Start or after
Stop it also runs inline, since there is no actor to hand off to either
way.
// A test staging a precondition:
s.Do(func() {
st := cig2.MustStateOf[*tableState](s)
st.round = 9 // jump straight to the state under test
})Keep fn short — it blocks the actor for its whole duration, delaying
every other player’s action. Read or write what you need and return; don’t
call Do again from inside fn, and don’t call a Session method that
itself blocks.
In tests, never assert inside fn. t.Fatal, t.FailNow (and
require.*) must run on the test’s own goroutine; inside Do — or any game
callback — they run on the actor and call runtime.Goexit there, which kills
the actor instead of failing the test. Read into locals, assert afterwards:
// wrong: t.Fatalf on the actor goroutine
s.Do(func() {
if cig2.MustStateOf[*tableState](s).round != 2 { t.Fatalf("wrong round") }
})
// right
var round int
s.Do(func() { round = cig2.MustStateOf[*tableState](s).round })
if round != 2 { t.Fatalf("round = %d, want 2", round) }(t.Errorf is safe anywhere; it only marks the test failed. If a Goexit
does happen on the actor, the session fails with cig2.ErrActorExited, so
the next call errors rather than the test hanging.)
From an HTTP handler, bound the wait with the request’s context:
s.DoContext(r.Context(), fn) (and ApplyContext, SnapshotForContext)
return ctx.Err() without running fn if the client gives up while the actor
is busy; once the actor has taken fn it runs to completion.
Session lifetime
s.Stop() returns at once (it is safe from the actor — a failing session
stops itself); s.Wait() blocks until the actor has exited and its timers are
stopped. Shut a session down with both, and it holds no goroutines afterwards.
To tie a session to something else’s lifetime, cig2.WithContext(ctx):
cancelling ctx stops it. Under host, Registry.Close (wired to
http.Server.RegisterOnShutdown) stops and waits for every table and sends
the "shutdown" farewell — prefer it over a context for a server’s own
sessions.
Logging goes through log/slog: cig2.WithLogger(l) per session,
host.Server{Logger: l} for a whole server (tables pass it to their
sessions with a table attribute). Don’t wrap game code in your own
logging of panics — the default panic handler already logs the callback,
seat, action, value and stack.
16. Move a card within its own deck
Move delegates to the destination’s Add, and Add returns early for a
card the zone already holds — so s.Move(c, deckItsAlreadyIn) silently
does nothing. Use the deck’s own repositioning methods instead:
deck.AddTop(c) // wherever c currently sits, move it to the top (next Draw)
deck.Bottom(c) // move it to the bottom (last Draw)Both detach c from its current position first, so this is the correct way
to send a peeked card back to the top or bottom of the deck it came from —
Move cannot express it.
17. Move a whole zone
Sweeping a zone — discard back into the deck, a trick to the winner’s pile, a hand into a graveyard — is one call:
n, err := s.MoveAll(discard, deck) // order kept: discard[0] lands first
deck.Shuffle(s.Rand())Each card goes through the destination’s Add, so visibility follows the
destination and a card’s sticky Revealed goes with it — a revealed card
swept into a Hidden deck is still visible to everyone. Don’t reuse revealed
cards in a fresh secret deck (see the anti-patterns).
18. Asking one player a question
Mid-resolution pauses — choose a target, keep one of the top three, mulligan
or keep, order your triggers — are all the same shape: the server asks one
seat, waits, validates, continues. Don’t build a pending map, a catch-all
action and a timeout by hand; use Session.Ask:
top := deck.PeekTop(3)
_, err := s.Ask(cig2.Question{
Seat: p, Kind: "keep-one",
Prompt: identitiesOf(top), // seat-only: safe to show what they peeked
Choices: uuidsOf(top),
Timeout: 30 * time.Second,
Default: cig2.AnswerWith(top[0].UUID()),
OnResolve: func(s *cig2.Session, r cig2.Resolution) {
for _, c := range top {
if c.UUID() == r.Answer[0] {
_ = s.Move(c, hand)
} else {
deck.Bottom(c)
}
}
},
})- A Timeout is mandatory — a disconnected player must never hang the
table.
cig2.NoDeadlineexists, but you must write it. - Keep continuation state in the closure, not on the
Gamevalue — the closure lives on the session, theGameis shared by every table. - Don’t re-check validity in
OnResolve. The framework has already enforcedChoices/Min/Max, andValidatefor anything else. (It does not validateDefault’s answer — that one is yours.) - Opponents see only that the seat is deciding and until when. If the
table should also see what is being decided, publish it through
GameState. - Pair with
Concealedwhen even the kept card’s UUID must not be trackable by opponents.
19. State that settles itself
State-based checks — “a creature with lethal damage dies”, “a player at 0 life loses”, “an empty hand refills” — must run after every change, including changes made by other checks. Don’t paste the call after each mutation, and don’t hand-roll the loop:
s.SetSettle( // in Setup; order is the order each pass runs them
lethalDamage, // func(s *cig2.Session) (changed bool)
lossCondition, // may s.Phase().Halt("game_over") — settling stops there
)The framework reruns every step until a full pass changes nothing, after each
successful action, scheduled action and resolved Ask, before CheckEnd
and the broadcast — and once after Setup. A halt stops it immediately, so a
decided game runs no further step.
Report changed honestly. A step that always returns true never settles; at
SettlePassLimit passes the framework gives up and sends everyone an
ErrSettleRunaway error frame (and fails Start if it happened after
Setup). That is a bug in the game, surfaced loudly rather than spinning the
actor forever.
When one action must resolve checks between two of its own steps — deal
damage, let lethal creatures die, then count the survivors — call
s.SettleNow() in the middle of HandleAction. Same fixpoint, same halt and
pass limit; return its error to reject the action on a runaway. The
post-action settle still runs afterwards (a no-op if nothing changed since).
Don’t call it from a settle step or phase hook: that’s ErrSettleReentrant,
and the running settle reruns every step anyway.
20. State on one card in play
Damage marked, counters, “tapped”, “summoning sick”: state that belongs to one
card while it is in play, not to its identity. Don’t mutate the payload
(it’s immutable identity) and don’t keep a map[uuid]*status side-table you
must remember to clear on every zone exit and to redact by hand:
c.SetState(&Status{Damage: 2})
if st, ok := cig2.CardState[*Status](c); ok && st.Damage >= toughness { ... }- Fresh on every zone change. Entering a different zone clears it, so a
creature that dies and returns has no damage. Repositioning within a zone
(
AddTop,Bottom) keeps it. - Redacted like identity. Whoever sees the card sees its state; nobody
else does — not an
OwnerOnlynon-owner, notFaceDown/Hidden, not aConcealednon-owner. So never put in it what the card’s viewers may not know. - Clients receive it as
card.state; Go clients getjson.RawMessagefromUnmarshalSnapshot. - To act on every card with some state, iterate the board, not a side-table:
s.WalkCards(func(c *cig2.Card, z cig2.CardHolder) bool { ... }), orfor _, c := range s.Cards()when the loop moves cards.
21. References between cards
An aura attached to a creature, a token tracking its creator, “the card
exiled by this one”: a card that points at another. Store the referent’s
UUID in card state, never a *Card, and resolve it every time with
FindCard:
type Attached struct{ To, Zone string } // host UUID, and where it was when attached
aura.SetState(&Attached{To: host.UUID(), Zone: "battlefield"})
// later — treat anything but "found, still where I attached it" as stale
ref, _ := cig2.CardState[*Attached](aura)
host, ok := s.FindCard(ref.To)
if !ok || host.Zone() == nil || host.Zone().ID() != ref.Zone {
// destroyed, or left the zone: the attachment falls off
}What a referent looks like after things happen to it:
| It was… | FindCard | |
|---|---|---|
| moved within its zone | found | same state |
| moved to another zone | found, new Zone() | state fresh (nil) — a new object |
Removed from every zone | found, Zone() == nil | |
Destroyed | not found, ever |
A pointer would survive all four and keep a destroyed card alive; a UUID makes
“stale” an explicit check. A settle step (§19) is the natural place to sweep
dangling references.
22. Making a game playable by agents
Automated playtesters drive games over host’s HTTP surface; the client side
is in docs/agent-play.md. On the game side, two things make an agent’s life
easy, and neither is a new protocol:
var _ cig2.ActionHinter = (*Game)(nil)
func (g *Game) LegalActions(s *cig2.Session, viewer cig2.PlayerID) []cig2.ActionHint {
if !myTurn(s, viewer) {
return []cig2.ActionHint{} // "nothing now" — not nil
}
return []cig2.ActionHint{{Name: "play", Data: playData{Card: c.UUID()}, Label: "Play the 7♣"}}
}- Hint in the envelope’s own shape, so the agent sends a hint straight back. Only hint what the viewer may see — the game is the filter.
- Use
Session.Askfor mid-action choices; agents readdecisions[].ask. - Take house rules through
Setup’sconfig(ajson.RawMessagewhen it came fromPOST create/reset) so playtest can vary them per table.
On the server: host.Server{SyncActions: true} (seat tokens are on by default), and
Registry.SetExplicit(true) when tables carry per-table config.
23. When game code panics
You don’t handle panics; the framework does. Every unit of actor work runs
under recover, so one table’s bug never takes the process (and every other
table) down. What happens next depends on whether the board can be trusted:
HandleActionpanicked and the board is provably unchanged (a deep fingerprint of the session’s game state is identical before and after): the action is rejected. The seat gets an error frame reading"internal error"with its actionid,Applyreturns a*cig2.PanicErrorwithRejectedset, and play carries on.- Anything else —
HandleActionafter it changed something, or a panic in a settle step, phase hook,CheckEnd,GameState,LegalActions, anAskcallback, aDoclosure orSetup— the session fails:s.Err()wrapscig2.ErrSessionFailed,s.Done()closes, nothing more runs. host ends the streams with a"failed"farewell (the banner says the table hit an internal error) and answers500until someone resets the table.
The value and stack go to cig2.WithPanicHandler (default: an Error record
on the session’s slog logger), never onto the wire, so a panic message that
names a hidden card leaks nothing. To keep the “rejected” outcome available,
validate before you mutate — the same order that makes a returned error safe.
The “provably unchanged” proof costs a fingerprint of all game state before
every action (20–32% of a full action in docs/benchmarks.md).
cig2.WithPanicRejection(false) drops it: every HandleAction panic then
fails the table, like a panic anywhere else, and release builds pay nothing
per action. Recommended for heavy games — large state, many actions — where a
panic is a bug to fix, not an event to survive. Strict rejection checking
(debug builds, cig2test) still works either way.
24. Rejections leave no trace
Returning an error from HandleAction tells the sender “nothing happened” and
broadcasts nothing. So a rejection must leave the board exactly as it found
it — anything it changed is invisible to every other seat until some later
action happens to broadcast it. Validate everything first, then mutate:
// wrong: the cards have moved by the time the second check fails
for _, id := range picked { s.Move(card(id), crib) }
if len(picked) != 2 { return errors.New("discard exactly two") }
// right: every check, then every change
if len(picked) != 2 { return errors.New("discard exactly two") }
cards, err := resolve(s, picked) // look up, don't move
if err != nil { return err }
for _, c := range cards { _ = s.Move(c, crib) }This is checked, not just asked. With strict rejection checking the session
compares a fingerprint of all game state before and after every rejected
action, and a rejection that changed anything fails the table
(cig2.ErrRejectionMutated). It is on under -tags cig2debug and in every
cig2test table, where it also fails the test; release builds turn it on
with cig2.WithStrictRejections(true). If one step genuinely must mutate and
then discover a problem (a settle runaway from SettleNow), the table has a
bug either way, and failing it is the honest outcome.
“All game state” includes the timer bookkeeping (every Schedule/Rearm and
Rearm epoch), the RNG and clocks. So the usual offenders are side effects on
the error path rather than an obvious move-then-fail:
- a
deferthat runs after every action — re-arming a turn timer, bumping a counter — also runs on a rejection; - starting a clock, drawing from
s.Rand()or arming a timer before the last check.
Do follow-up work only on the success path, after every check.
Anti-patterns, collected
| Don’t | Because |
|---|---|
| A mutex around game state | The actor boundary is broken; fix the boundary |
| Package-level game vars | Sessions must be independent |
A switch gameName in the framework | Breaks the core promise; use RegisterGame |
Storing per-table data on the Game value | One Game is shared by every session |
Mirroring Phase/Turn/Round into GameState | Already on the snapshot, read live |
A gameOver bool beside a phase machine | Halt |
| Hand-filtering cards before sending | Filter runs per viewer already |
| Un-revealing a card | Revealed is one-way by design |
| Diffing state to “optimise” the wire | Full snapshots are deliberate |
time.Now() in HandleAction | Kills test determinism; use s.Now() |
Ranging a map (or Collector.Values) while drawing from s.Rand() | Map order differs every run, so a seeded replay diverges; range Collector.All or a sorted slice |
| Sorting or keying order by card UUID | UUIDs are random per run, even under WithSeed; order by position or a game field |
| Keying clock logic off the current phase | Key off “did this stint end” |
| Testing an increment-crediting clock at increment 0 | The credit path is unreachable there |
| Reusing a revealed card in a fresh hidden deck | Revealed is sticky and leaks it forever |
An Ask with no real deadline “because players are always there” | A dropped connection hangs the table; NoDeadline only when a human arbiter exists |
A settle step that returns true unconditionally | It never settles; ErrSettleRunaway after 100 passes |
| Mutating a payload to track damage or counters | Payloads are identity; use Card.SetState |
A scripted test on a raw session that never sends "ack" | After 5s every seat is dropped and gets no more snapshots; the test reads stale frames that look nondeterministic. Use cig2test.AckAll(t, s) or cig2.WithAckTimeout(0) |
Calling HandleAction directly in a unit test | Settle, phase hooks and CheckEnd never run; use cig2test |
Holding a *Card to reference another card | It outlives Destroy and zone changes; store the UUID, resolve with FindCard |
Auto-reconnecting a stream closed as displaced | The two tabs take the seat from each other forever; SSETransport stops and waits for reconnect() |
| Leaving an interactive board up after the stream drops | Players act on stale state with no cue; status-banner |
| Queuing actions made on a stale board to send after reconnecting | They land on a board the player never saw; the guard drops them on purpose |
recover() inside game code | It swallows a half-applied mutation and play continues on an inconsistent board; the framework already recovers and decides reject-or-fail from the board itself |
panic as a way to reject an action | Return an error: it reaches the player with its text, a panic only says “internal error” |
Changing state, then returning an error from HandleAction | The sender is told nothing happened and nobody else is sent the change; strict rejection checking fails the table |
A defer g.afterAction(s) (re-arm, counters) in HandleAction | It runs on rejections too and changes state; do follow-up work on the success path only |
c.UUID (no parentheses) as a value in hint Data, GameState or an Ask prompt | It compiles and passes vet, then fails the snapshot marshal at runtime; write c.UUID() |
t.Fatal / t.FailNow inside s.Do or a game callback in a test | It runs runtime.Goexit on the actor, not the test goroutine; read into locals and assert after Do returns |
InsecureSeats or InsecureAllowCrossOrigin on a server other people can reach | Anyone with the password then watches every seat, or any site they visit acts for them |
Your own http.Server{} without ReadHeaderTimeout | Slow clients hold connections open; host.Run always sets it |
| Trusting an action’s name to mean a timer sent it | Clients can POST any name; check action.FromTimer() |
json.Unmarshal of a config or content file with unknown keys allowed | A typo silently becomes the default; DecodeConfig and content.Load are strict |
MustFindZoneAs on a zone ID from a client’s action data | A bad ID would fail the table; use FindZoneAs and return its error |
| Assigning a card’s UUID or revealed flag | Read-only by design: UUID()/Revealed(); Reveal() is the only way in |