CIG2 cheatsheet

Fast lookup for the API surface, pulled from source as of this writing. Everything here is either exported from package cig2 (github.com/PipGrylls/CIG2) or from github.com/PipGrylls/CIG2/web. For the why, see .claude/SPEC.md, docs/superpowers/specs/, and docs/getting-started-snap.md. For a worked example of every entry below, read games/highcardduel.

Building a game? Read docs/cig2-patterns.md first. This page tells you what exists; that one tells you which tool solves the problem you have, and which helpers not to write because the framework already ships them.

Visibility (visibility.go)

type Mode string"public" | "owner_only" | "concealed" | "face_down" | "hidden" — also ModePublic/ModeOwnerOnly/ModeConcealed/ModeFaceDown/ModeHidden
type Visibility struct{ Mode Mode; Owner PlayerID }Owner only meaningful for ModeOwnerOnly and ModeConcealed
Public() Visibilityeveryone sees real identity
OwnerOnly(owner PlayerID) Visibilityonly owner sees real identity; others see opaque but trackable (UUID kept)
Concealed(owner PlayerID) Visibilityowner sees real identity; others see the count only — no entries, no UUIDs. For a hand where tracking individual cards is itself a leak
FaceDown() Visibilityarrangement disclosed, identity not: one positional entry per card, no UUID. For a tableau column
Hidden() Visibilitynothing disclosed but the count; entries aren’t sent at all unless Revealed. For a shuffled deck

The disclosure ladder, most to least:

Modeidentitystable UUIDarrangement
Publicyesyesyes
OwnerOnly, to the owneryesyesyes
OwnerOnly, to a non-ownernoyesyes
Concealed, to the owneryesyesyes
FaceDownnonoyes
Concealed, to a non-ownernonono (count only, like Hidden for them)
Hiddennonono

Pick Concealed over OwnerOnly when opponents must not follow individual cards (which card left the hand, which one arrived); pick OwnerOnly when the client animates them and that tracking is acceptable.

Pick Hidden for a shuffled deck, FaceDown for a visible stack. FaceDown discloses the index of any card revealed in place, which is real order information — fine for a tableau the player can see anyway, wrong for a deck whose order is secret.

Effective visibility per card, per viewer (filter.go): Revealed is checked before the zone’s Mode, and overrides it. Order: Revealed → Hidden (dropped) → FaceDown (positional, empty) → Concealed + non-owner (dropped) → Concealed + owner (full) → OwnerOnly + non-owner (opaque) → OwnerOnly + owner (full) → Public (full) → unrecognised or zero-value mode (dropped, as Hidden: fail-closed).

Cards (card.go)

type PlayerID string
type CardPayload interface{ PayloadTag() string }your game-defined identity type implements this
RegisterPayload(gameName, tag string, ctor func() CardPayload)call from your package’s init(); gameName is the same string you pass to RegisterGame — tags are namespaced per-game, so two games can both use "playing_card"
PayloadTags() []stringevery registered (game, tag) key, sorted
type Card struct{ Payload CardPayload; /* unexported */ } — UUID() string, Revealed() boolframework envelope; Payload is what gets dropped when opaque. UUID and the sticky reveal flag are read-only (getters): NewCard/Session.NewCard set the UUID, Reveal() is the only way to reveal. The JSON (uuid, revealed) is unchanged
NewCard(uuid string, payload CardPayload) *Cardyou won’t normally call this directly — use Session.NewCard
(*Card) Reveal()one-way. Sets Revealed = true forever. Only call this when identity must survive re-entering a stricter zone than the one it’s currently visible from.
(*Card) Zone() CardHoldercurrent holder, or nil
(*Card) SetState(v any), (*Card) State() any, CardState[T any](c *Card) (T, bool)per-instance mutable state (damage, counters, “summoning sick”). Cleared to nil on every zone change; kept on in-zone moves (AddTop/Bottom/same-zone Move) and on a never-placed card’s first placement. Published exactly where the identity is (full card views only — never to a non-owner of OwnerOnly/Concealed, never from FaceDown/Hidden, everywhere once Revealed). Must marshal to JSON. Runtime-only: not in MarshalZone

Decoding a card can only ever turn Revealed on — an incoming false is ignored, never applied.

Zones (zone.go, cardzone.go, group.go, deck.go, hand.go, pile.go, display.go)

type Zone interface {
    ID() string
    Visibility() Visibility
    Children() []Zone
    ZoneTag() string
}
type CardHolder interface {
    Zone
    Cards() []*Card   // returns a COPY
    Count() int
    Add(c *Card)       // detaches c from wherever it was first
    Remove(c *Card) bool
}
TypeExtra methodsZoneTag()Typical visibility
*GroupAddChild(child Zone), RemoveChild(id string) bool"group"Public() — organizational only, holds no cards
*DeckDraw() (*Card, error) (index 0 = top), Shuffle(r *rand.Rand), AddTop(c *Card), Bottom(c *Card), PeekTop(n int) []*Card (top first, copy, no draw; clamps to size)"deck"usually Hidden()
*Hand—"hand"usually OwnerOnly(p)
*PileTop() (*Card, bool) (most recently added)"pile"usually Public()
*Display—"display"usually Public()

ErrEmptyDeck — returned by Draw() on an empty deck.

AddTop/Bottom on a card already in the deck move it there from wherever it currently sits, rather than no-opping the way plain Add (and therefore Move, which delegates to Add) does for a card the zone already holds. AddTop puts it where the next Draw takes it first; Bottom is its mirror — where Draw takes it last. Use these, not Move, to reposition a card within a deck it already occupies.

Every concrete zone type carries a compile-time assertion right next to its definition (var _ DeckZone = (*Deck)(nil)) — copy this pattern for any new zone type you define. It’s the direct fix for a real historical bug (an interface-signature drift that silently no-op’d card dealing).

Adding a new zone type:

type MyZone struct{ cardZone }
var _ MyZone = (*MyZone)(nil)                 // your interface, if any
var _ ZoneLoader = (*MyZone)(nil)
func NewMyZone(id string, vis Visibility) *MyZone {
    z := &MyZone{}
    z.init(z, id, vis)   // pass the OUTER type as self
    return z
}
func (z *MyZone) ZoneTag() string { return "my_zone" }
func init() { RegisterZone(Name, "my_zone", func() ZoneLoader { return NewMyZone("", Public()) }) }

RegisterZone(gameName, tag string, ctor func() ZoneLoader) / ZoneTags() []string — same generic registry pattern as payloads (registry.Registry[T]: New[T](), Register, New(tag), Has, Tags). Like RegisterPayload, gameName is your game’s own registered name, so your zone tags can never collide with another game’s. The five built-in zone types are registered by the framework under a reserved namespace and resolve for every game automatically — you never re-register them.

MarshalZone(z Zone) ([]byte, error) / UnmarshalZone(data []byte) (Zone, error) — unfiltered round-trip serialization (real identities, no visibility applied). For content loading and tests only. Never send MarshalZone’s output to a player — use Filter.

Session (session.go) — all of the below are actor-only

Call these only from Setup/HandleAction/CheckEnd. Calling from another goroutine races the session’s own state (a debug build with -tags cig2debug panics on the violation instead of silently corrupting state).

MethodSignature
IdentityID() string, Root() *Group, Rand() *rand/v2.Rand, Players() []PlayerID
ClockNow() time.Time — the session’s clock; override in tests with WithNow(func() time.Time). Does not affect Schedule/Rearm, which use real timers
Per-table stateSetState(v any), State() any; typed: StateOf[T](s) (T, bool), MustStateOf[T](s) T (panics with ErrStateType — for state your own Setup stored) — use this, never a field on your Game struct (a Game is a shared singleton across every session)
Per-player stateSetPlayerState(p PlayerID, v any), PlayerState(p PlayerID) any (typed: PlayerStateOf[T](s, p) (T, bool)) — one value per player, where SetState holds one for the table. No auto-redaction: GameState(s, viewer) already takes a viewer, so return s.PlayerState(viewer) is the whole filter
TurnsTurn() *TurnTracker, SetTurn(t *TurnTracker)
PhasesPhase() *PhaseMachine, SetPhase(m *PhaseMachine)
Zone factoriesNewGroup, NewDeck, NewHand, NewPile, NewDisplay — all (id string, vis Visibility) *T
CardsNewCard(payload CardPayload) *Card
Bulk cardsAddCopies(h CardHolder, specs ...CardSpec) int — see below
LookupFindZone(id string) (Zone, bool), FindZoneAs[T Zone](s, id) (T, error) (wraps ErrZoneNotFound / ErrZoneType, names the ID and both types; T may be an interface like CardHolder; MustFindZoneAs panics — only for zones your Setup built, never an ID from client data), FindCard(uuid string) (*Card, bool) — FindCard is O(1), the live-instance resolver: a moved card is found (same *Card, new Zone(), fresh state after a zone change), a Removed one is found with Zone() == nil, a Destroyed one is never found again. Also finds cards placed without Session.NewCard (board search on a miss, then indexed)
Enumerate cardsWalkCards(fn func(c *Card, zone CardHolder) bool) (false stops), Cards() []*Card — every card on the board, deterministic: zones depth-first in tree order, each zone index 0 first. Don’t mutate inside WalkCards; Cards() is a snapshot slice, safe to mutate from
MoveMove(c *Card, dst CardHolder) error
Move allMoveAll(from, to CardHolder) (int, error) — every card, in order (from’s index 0 lands first); same semantics as Move per card; returns the count; from == to is a no-op
DestroyDestroy(c *Card) error — removes from its zone and the card index, so it can never reappear in any future Filter output. Errors only on nil; a card with no zone is fine
Remove zonesRemoveZone(id string) error — removes a zone and its whole subtree from the index, unlinking it from its parent. Refuses, unchanged, if any zone in the subtree still holds a card (sweep cards out first); removing the root is always an error
TimersSchedule(after, player, action) (cancel func()), Rearm(key string, after, player, action) (cancel func()) — see below
DecisionsAsk(q Question) (id string, err error), CancelAsk(id string) bool, Pending() []Decision — see below
SettleSetSettle(steps ...SettleStep) — type SettleStep func(s *Session) (changed bool). Rerun to a fixpoint after every successful step (action, timer, resolved Ask) before CheckEnd, and once after Setup. Stops the moment the phase machine halts. Capped at SettlePassLimit (100) passes → ErrSettleRunaway as an error frame to everyone (after Setup: Start fails)
Settle mid-actionSettleNow() error — the same fixpoint, synchronously, inside HandleAction, between two steps of one action. Returns (doesn’t broadcast) ErrSettleRunaway; ErrSettleReentrant from inside a settle; ErrNotOnActor off the actor, checked in every build. The post-action settle still runs

NewSession(id string, game Game, players []PlayerID, opts ...SessionOption) *Session — does not start the actor; call Start().

Options: WithRand(r *rand/v2.Rand) (deterministic shuffles in tests), WithNow(now func() time.Time) (deterministic elapsed time in tests), WithAckTimeout(d time.Duration) (default 5s: a seat that hasn’t sent "ack" by then is marked disconnected and sent no more snapshots; d <= 0 disables), WithAckTimeoutHandler(func(seat PlayerID)) (runs on the actor for each dropped seat; default: one slog Warn record via WithLogger), WithConfig(v any), WithSeed(seed int64) (seed the RNG and record it: (*Session) Seed() (int64, bool), any goroutine; WithRand leaves it unknown; last of the two wins. A seed predicts every hidden card — keep it from players while the game runs). With neither, the RNG is ChaCha8 seeded from crypto/rand (WithRand(nil) keeps it). WithPanicHandler(func(*PanicError)) receives every recovered panic (default: one slog Error record with the stack, via WithLogger) — see “Panics” below. WithContext(ctx) ties the session’s lifetime to ctx (cancel → stop, Err stays nil). WithLogger(*slog.Logger) (default slog.Default(), read per record): panics, ack-timeout drops, failed sends, settle runaways and mutating rejections, with session/seat/action/id attributes. WithPanicRejection(bool) (default on): off skips the per-action state fingerprint (20–32% of an action) and makes every HandleAction panic fail the table — recommended for heavy games. WithStrictRejections(bool) fails the session when HandleAction rejects an action but changed game state (ErrRejectionMutated; default on under -tags cig2debug and in cig2test, off otherwise).

Session.Do — the one exception to “actor-only”

(*Session) Do(fn func())

Runs fn on the actor goroutine and blocks until it finishes — the actor model’s “ask”. Unlike everything else in this section, call it from any goroutine: a lobby needing a consistent multi-field read, an admin endpoint, or a test staging a precondition no legal action sequence reaches. Game code already on the actor (Setup/HandleAction/CheckEnd) never needs it. Never deadlocks — runs fn inline when the caller is already the actor, and inline before Start/after Stop too, since there’s no actor to hand off to either way. Once Start has returned, the actor owns the session, so a Do straight after Start — even from the same goroutine — runs on the actor, after the opening broadcast. fn blocks the actor for its duration, so keep it short, and never call Do from inside fn. A nil fn is a no-op.

Session.Ask — server-initiated decisions (decision.go)

id, err := s.Ask(cig2.Question{
    Seat:      p,
    Kind:      "keep-one",                 // game's discriminator, required
    Prompt:    peekedIdentities,           // any JSON; seat-only
    Choices:   uuids,                      // allowed answers, required, unique
    Min: 1, Max: 1,                        // both 0 = exactly one
    Timeout:   30 * time.Second,           // REQUIRED; cig2.NoDeadline to wait forever
    Default:   cig2.AnswerWith(uuids[0]),  // required with a Timeout; runs at expiry
    Validate:  nil,                        // optional extra check on player answers
    OnResolve: func(s *cig2.Session, r cig2.Resolution) { /* r.Answer, r.Reason */ },
})

Kind-agnostic: the framework shows the seat Kind/Prompt/Choices, validates the reply (in Choices, no repeats, Min..Max picked, then Validate), and calls OnResolve once — Reason is ResolvedByAnswer or ResolvedByDeadline — followed by CheckEnd and a broadcast, exactly like an action. A rejected answer goes to the seat as an error frame; the decision stays pending. Answers arrive as the reserved "cig2.answer" action and never reach HandleAction.

  • Never hangs the table. Timeout is mandatory; NoDeadline must be asked for by name. Expiry answers with Default (trusted, not validated). Expiry uses a real timer, like Rearm; WithNow only changes the Deadline shown.
  • Hidden by default. Other players’ snapshots carry only {id, seat, deadline} — never kind, prompt or choices (choices are often UUIDs of cards only the seat peeked).
  • CancelAsk(id) bool withdraws without calling OnResolve. Game end drops every pending decision the same way. Ask after the game ends errors.
  • Several may be pending at once, for one seat or many (simultaneous mulligans); each resolves independently.
  • Pending() []Decision (copies, oldest first) — from tests or an admin endpoint read it via s.Do(func() { ds = s.Pending() }).

TurnTracker (turn.go)

NewTurnTracker(order []PlayerID) *TurnTracker
(*TurnTracker) Current() PlayerID
(*TurnTracker) Advance() PlayerID
(*TurnTracker) IsCurrent(p PlayerID) bool
(*TurnTracker) Order() []PlayerID
(*TurnTracker) SetCurrent(p PlayerID) bool         // false + no-op if p isn't in the seating order

Optional — hand-roll your own turn state via SetState if round-robin doesn’t fit. SetCurrent is for what round-robin can’t express — an extra turn, or forcing a specific player to act — and a subsequent Advance continues round-robin from the new position. It’s the only home for “who acts”: PhaseMachine takes no actor argument (see below).

PhaseMachine (phase.go)

type PhaseID string
NewPhaseMachine(phases []PhaseID) *PhaseMachine
NewPhaseMachineWithPrelude(prelude, round []PhaseID) *PhaseMachine // round 1 = prelude+round; every later round = round
(*PhaseMachine) Prelude() []PhaseID              // copy; round-1-only opening phases
(*PhaseMachine) Current() PhaseID
(*PhaseMachine) Round() int                        // counts from 1; 0 if no phases
(*PhaseMachine) IsPhase(p PhaseID) bool
(*PhaseMachine) Order() []PhaseID                  // copy; the declared default, fixed at construction (never includes the prelude)
(*PhaseMachine) Sequence() []PhaseID               // copy; what THIS round is actually running
(*PhaseMachine) AtEnd() bool                       // true iff Current is the last phase of Sequence
(*PhaseMachine) Advance() PhaseID                  // moves within the round only; see warning below
(*PhaseMachine) NewRound(phases ...PhaseID)        // no args: declared order. args: exactly those phases, one round. no-op if the result would be empty
(*PhaseMachine) Goto(p PhaseID) bool                // move within Sequence; false if p isn't in it, or halted
(*PhaseMachine) Remaining() []PhaseID              // copy; phases after Current — SetRemaining's inverse
(*PhaseMachine) SetRemaining(phases ...PhaseID)    // replace the tail after Current; Round/Current untouched
(*PhaseMachine) Halt(final PhaseID)                // sticky, one-way; freezes Current/Round; see warning below
(*PhaseMachine) Halted() bool
(*PhaseMachine) OnEnter(p PhaseID, fn func(*Session))          // entry logic; runs in the next settle; nil removes
(*PhaseMachine) NeedsInput(p PhaseID, fn func(*Session) bool) // false = auto-advance past p; no predicate = needs input
(*PhaseMachine) OnRoundEnd(fn func(*Session))               // replaces auto-advance's default NewRound() at the round's end

Tracks position in a phase order you declare (Order), plus what the current round is actually running (Sequence — a copy of Order unless replaced per-round by NewRound or from the current phase onward by SetRemaining), plus how many times a new round has begun (Round). It has no per-phase action gate — gating is your own switch s.Phase().Current() in HandleAction. It does have optional entry hooks (below). There are no skip/insert/remove sequence editors either: compute the list you want with ordinary slice code (Order()/Sequence() plus a without you write in your own game code — the framework doesn’t ship one) and hand it to NewRound or SetRemaining.

NewRound is the only method that increments Round. Advance parks at the last phase of the sequence rather than wrapping — it is a no-op there, returning that same phase, and Round never moves under it. A game that drives Advance at the round boundary but never calls NewRound sits on its last phase forever; the fix is always if m.AtEnd() { m.NewRound() } else { m.Advance() }, not a bigger Advance.

Opening phases that must not replay go in a prelude. A bare NewRound() restores the declared order, so a draft or mulligan declared in NewPhaseMachine’s order replays every round — a real silent-skipped-turn bug. Use NewPhaseMachineWithPrelude([]PhaseID{"draft"}, []PhaseID{"play", "score"}): round 1 runs draft, play, score, every later round play, score.

NewRound refuses to begin a round that would run no phases. Calling it with no arguments on a machine whose declared order is empty (including one only ever driven by NewRound(phases...), once its custom sequence has run its course) is a complete no-op — sequence, position, and round are all left exactly as they were. Beginning a round with nothing in it would otherwise leave the machine silently dead: no Current, AtEnd never true, Advance a permanent no-op. This is also what keeps Round at 0 meaning exactly “this sequence has never had phases,” not “this sequence currently has none.”

Compute SetRemaining’s argument from Remaining(), not Sequence()/slices.Index. slices.Index finds the first occurrence of the current phase; SetRemaining splices at the machine’s actual position. They differ whenever the sequence repeats a phase, silently duplicating the tail. m.SetRemaining(without(m.Remaining(), "end")...) is always correct.

Halt’s terminal label must not appear in the declared order. The framework never interprets a PhaseID, so it cannot check this for you: halting to a label that’s also a declared phase leaves IsPhase reporting true for it after the game is already decided, which is how a finished game’s phase switch ends up taking a live branch. Pick a label — e.g. "game_over" — that isn’t one of your real phases. Halt is sticky and one-way (first call wins, no un-halt); after it, Current/Halted/Round freeze and Advance/Goto/NewRound/SetRemaining are all no-ops.

Publishes as snapshot.phase / snapshot.round (and data-phase / data-round in the browser toolkit) only if you call SetPhase. Don’t also mirror Current() into your own GameState — the snapshot reads the machine directly at broadcast time, so a hand-kept copy adds nothing and can go stale mid-action.

Entry hooks and auto-advance (opt-in, per phase). OnEnter(p, fn) runs fn each time the machine lands on p — construction (first phase), Advance, NewRound, Goto (even to the current phase). The machine has no Session, so hooks run during the session’s next settle (after every successful action and after Setup, before CheckEnd and the broadcast) — never call your enterX() by hand after Advance again. NeedsInput(p, fn) returning false makes settle auto-advance past p (Advance, or at the round’s end OnRoundEnd/NewRound()), one phase per settle pass with your settle steps in between, stopping at the first phase that needs input. A phase with no predicate needs input. Only the machine installed with SetPhase runs hooks. A ring where no phase ever needs input trips SettlePassLimit.

A sub-ring (e.g. cribbage’s three counts within the show) is a second PhaseMachine held by the game, not nesting inside one machine — there is no framework support for nested phases.

Clock (clock.go)

var c Clock                                        // zero value is a valid, stopped stopwatch
(*Clock) Start(now time.Time)                      // no-op if already running
(*Clock) Stop(now time.Time) time.Duration         // returns that interval; no-op if stopped
(*Clock) Running() bool
(*Clock) Elapsed(now time.Time) time.Duration      // includes the in-progress interval
(*Clock) Adjust(delta time.Duration)               // may go negative — see below

Measures elapsed running time, nothing else. now is always yours to supply (like Deck.Shuffle’s *rand.Rand) — testable without sleeping.

Adjust deliberately does not floor at zero. A player who consistently beats their increment legitimately ends up negative; clamping would break a real chess clock. No Session field and no wire representation — a game may hold many, so publishing them is your GameState’s job.

Countdown and count-up are both your arithmetic on top of Elapsed; Clock owns no budget. Both shipped consumers wrote the same one-liner:

remaining := bank - clock.Elapsed(s.Now())   // countdown
elapsed   := clock.Elapsed(s.Now())          // count-up

If you credit an increment, read Clock’s doc comment first. Every actor transition must close its outgoing stint (Stop + Adjust) before any Start, including transitions your phase machine performs implicitly inside one HandleAction — a real consumer dropped the credit twice, silently, by keying off “which phase am I in” instead. Test with a non-zero increment: at zero, Adjust is a no-op and the whole path is invisible.

Collector[T] (collector.go)

NewCollector[T any](expected []PlayerID) *Collector[T]
(*Collector[T]) Submit(p PlayerID, v T) (complete bool)
(*Collector[T]) Complete() bool
(*Collector[T]) Values() map[PlayerID]T            // copy; random range order
(*Collector[T]) All() iter.Seq2[PlayerID, T]       // declared order, then extras sorted
(*Collector[T]) Pending() []PlayerID               // copy, declared order
(*Collector[T]) Expected() []PlayerID              // copy

For simultaneous “everyone commits, then it resolves together” rounds. Build a fresh one per round. T is struct{} when you only need the completion signal (both players discarded), or a real payload when resolution needs the committed values (blind picks that swap).

Resolve inside the same HandleAction whose Submit returned true — the framework’s automatic post-action broadcast then carries the already-resolved state, so no leak window opens and no “defer the broadcast” mechanism exists or is needed.

Gotchas: Submit overwrites a resubmission (enforce “no changing your mind” yourself via Pending); it does not roll back if HandleAction later returns an error, so submit only after validating; and never publish Values() before Complete() — publish Pending() for a waiting-on display. Resolve with for p, v := range c.All(), never by ranging Values() while drawing from s.Rand(): map order differs every run, so a seeded replay diverges.

Session.Rearm vs Session.Schedule (lifecycle.go)

Schedule(after time.Duration, player PlayerID, action Action) (cancel func())
Rearm(key string, after time.Duration, player PlayerID, action Action) (cancel func())

Both deliver an Action to HandleAction after a delay, on the actor goroutine, attributed to that player and tagged action.Origin == cig2.OriginTimer. A client can POST the same name, so a timer-only action checks action.FromTimer() and rejects a player who sends it — Origin is json:"-", set only by the framework (the player path forces OriginPlayer). Tests fire one with (*Session) ApplyTimer(p, action) error (the exact timer path, synchronously; server-side only — never wire it to client input) or cig2test’s tbl.Fire(p, name, data).

Schedule’s cancel is not airtight — a timer that already fired can still win the race to deliver. Rearm fixes the consequence rather than the race: each armed timer carries an epoch for its key, and a superseded delivery is dropped before your game sees it. Re-arming the same key replaces what was there, so a per-turn timer needs no explicit cancel — the next turn’s Rearm supersedes it.

Keys are yours: "turn-timer", "idle:"+player, "clock:"+player. Compose with Clock for a proactive budget timeout: s.Rearm("clock:"+p, budget-clock.Elapsed(now), p, timeoutAction).

Building card collections (assembly.go, weighted.go)

type CardSpec struct { Payload CardPayload; Copies int }
(*Session) AddCopies(h CardHolder, specs ...CardSpec) int

type Weighted[T any] struct { Value T; Weight int }
PickWeighted[T any](r *rand.Rand, candidates []Weighted[T]) (T, bool)

Weighted piles are built, not drawn. Expanding copies into a deck and shuffling is weighted sampling, with an order that’s fixed and seed-reproducible:

s.AddCopies(deck, specs...)
deck.Shuffle(s.Rand())          // AddCopies never shuffles — seeding stays visible

There is deliberately no Deck.DrawWeighted: weighting an already-shuffled deck randomizes twice, after which neither deck order nor Count() describes what comes out next.

PickWeighted covers what that can’t — sampling with replacement from something that isn’t a deck (generating a card, a loot table, weighted AI moves). Weights <= 0 are never picked, so excluding a candidate means zeroing its weight rather than rebuilding the slice. T can be *Card: pick over deck.Cards() then Move/Destroy the winner for a weighted draw you opted into explicitly.

Copies from one CardSpec share its payload pointer — correct, since a payload is immutable identity, but don’t mutate a payload after handing it over.

The Game interface & registration (game.go)

type Game interface {
    Setup(s *Session, players []PlayerID, config any) error
    HandleAction(s *Session, player PlayerID, action Action) error
    CheckEnd(s *Session) (over bool, result Result)
}
RegisterGame(name string, g Game)   // call from init()
LookupGame(name string) (Game, bool)
GameNames() []string

config is whatever WithConfig supplied at construction, or nil:

s := cig2.NewSession(id, game, players, cig2.WithConfig(myRules))

There is no Session.Config() — config arrives in Setup and nowhere else. A game needing it later folds it into SetState, so per-table data lives in exactly one place. Never store config on the Game value: a Game is registered once and shared by every session.

Decode it with DecodeConfig[T any](config any) (T, error): accepts nil (→ defaults), T, *T, and json.RawMessage/[]byte (strict: unknown keys, wrong JSON types and trailing data are errors; empty/null → defaults). Optional hooks on *T: SetDefaults() (ConfigDefaulter, applied under the JSON and for nil) and Validate() error (ConfigValidator). Every error wraps ErrBadConfig; return it from Setup and host answers 400 on create/reset (a rejected create leaves no table; a rejected reset keeps the old game).

A Game value is registered once and shared by every concurrent session — it must be stateless. HandleAction returning an error rejects the action; only the submitting player is told (errorMessage frame), the board is unchanged for everyone else.

Optionally, to tell each player (and automated agents) what they may do now:

type ActionHinter interface {
    LegalActions(s *Session, viewer PlayerID) []ActionHint // nil omits; []ActionHint{} sends "legal": []
}
type ActionHint struct {
    Name  string `json:"action"`          // same shape as the inbound envelope:
    Data  any    `json:"data,omitempty"`  // an agent can POST a hint verbatim
    Label string `json:"label,omitempty"`
}

Published as snapshot.legal (decoded Data is json.RawMessage). Hints, not rules: the framework never enforces them — HandleAction still judges — and the game is the filter, so never hint what the viewer may not know. Pending Ask decisions are not repeated in legal; they’re in snapshot.decisions (seat-only ask), answered with "cig2.answer". highcardduel implements it.

Optionally, to publish state that is neither a card nor a zone:

type StatefulGame interface {
    GameState(s *Session, viewer PlayerID) any   // nil omits the field
}

Arrives on the wire as Snapshot.GameState json.RawMessage ("game_state"), decoded by the client into its own type — no registry. Runs on the actor goroutine, once per player per broadcast.

SetState is where you keep it; GameState is what you show — the same split as the zone tree and Filter:

stored inshown via
Cardsthe zone treeFilter(tree, viewer)
Everything elseSession.SetStateGameState(s, viewer)

The viewer argument is mandatory and the framework never inspects what you return. Whatever you return, that viewer sees.

Static content (content/)

content.Load[T](fsys, path, opts...) (T, error) / content.MustLoad[T](...) decode one JSON file into T, then run (*T).Validate() error if present (content.Validator). Strict: an unknown key or data after the top-level value is an error naming the file and key; content.AllowUnknownFields() opts out per call.

Serving a browser (sse/, action.go)

conn := cig2.NewChanConn(16)          // Send never blocks; evicts the oldest when full
_ = conn.Dropped()                    // uint64 — frames discarded so far
_ = conn.Messages()                   // <-chan []byte — frames to write out
_ = conn.Closed()                     // <-chan struct{} — closed on Close

sse.Stream(w, r, conn)                // runs until close / cancel / write error
sse.Stream(w, r, conn, sse.WithKeepalive(30*time.Second))
sse.Stream(w, r, conn, sse.WithWriteTimeout(10*time.Second)) // per-write deadline (default 30s); clears the server's WriteTimeout for the stream

ChanConn is production-capable, not a test helper: Send never blocks, so a slow browser cannot stall the session’s actor goroutine. When the buffer is full it evicts the oldest frame, so a lagging client always ends on the newest snapshot — safe only because CIG2 sends full snapshots. Dropped() counts evictions; a rising count means a slow client or a buffer too small. sse.Stream delivers frames still buffered when the source closes before its farewell.

sse.Stream returns nil for every ordinary disconnect (source closed, request cancelled, write failed). Its only error is a ResponseWriter that is not an http.Flusher, which is a server wiring mistake. sse imports net/http but not cig2, so the core stays HTTP-free; *cig2.ChanConn satisfies sse.Source structurally.

Each frame must be a single line — Stream writes it as one data: field.

A Source that also implements sse.Farewell (CloseReason() string) gets one last frame when it closes with a non-empty reason — event: close / data: {"reason":"…"} (sse.CloseEvent) — so the client can tell a deliberate close from a network drop. onmessage never sees it.

The whole hosting shell (host/, opt-in)

cfg := host.Config{Game: "my-game", Seats: []cig2.PlayerID{"p1", "p2"},
    Auth: host.Auth{PasswordEnv: "APP_PASSWORD"}, Static: pageFS} // ErrNoPassword if unset: fails closed
host.Flags(flag.CommandLine, &cfg) // -addr -password-env -allow-open -sync-actions -insecure-seats -expose-seeds -allow-delete -invites -idle-ttl
flag.Parse()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
err := host.Run(ctx, cfg) // serves until ctx ends; graceful shutdown with "shutdown" farewells

// by hand, when Run's shape doesn't fit:
reg, err := host.NewRegistry("my-game", seats, opts...)
(&host.Server{Registry: reg}).Mount(mux) // CSRF-protected routes + /cig2/
gated, err := host.Auth{PasswordEnv: "APP_PASSWORD"}.Wrap(mux)
// then your own http.Server — set ReadHeaderTimeout, RegisterOnShutdown(reg.Close)
Routes (Mount)GET /events, POST /action, POST /reset (table host.DefaultTable); GET /t/{table}/events, POST /t/{table}/action, POST /t/{table}/reset; GET /state + GET /t/{table}/state?player= (the seat’s current snapshot JSON — same filter as a broadcast, for polling); GET /tables ({"game","tables":[{"id","seats"}]}); POST /claim, POST /release (+ /t/{table}/…; 404 with InsecureSeats); POST /create (201, 409 if it exists). reset and create take an optional {"config": <JSON>, "seed": <int64>} body: a "config" key → cig2.WithConfig(json.RawMessage) for Setup to decode, kept across resets ("config": null → back to base; no key → unchanged); "seed" → cig2.WithSeed for this game only (replay). Every game is seeded (random seeds are < 2^53, JSON-safe — a 53-bit space a determined player could search offline; cig2.WithRand(nil) in the registry/table options gives each game the crypto-seeded default instead, with no seed to report); the seed appears in create/reset responses and /tables only with ExposeSeeds; GET /cig2/… toolkit assets. Seat = ?player= (what transport-sse.js sends)
host.Run(ctx, host.Config) error; host.NewHandler(cfg) (http.Handler, *Registry, error); host.Flags(fs, *Config)Config{Addr, Game, Seats, Options, Registry func(*Registry), Auth, Server, Static fs.FS, StaticPath, Routes func(*http.ServeMux, *Registry), Logger, ReadHeaderTimeout (10s, always set), IdleTimeout (2m), WriteTimeout (30s; streams clear their own), ShutdownTimeout (5s), Ready func(net.Addr)}. Routes are CSRF-protected like host’s routes, and a GET /{$} registered there wins over Static for / (the lobby pattern). NewHandler = the same surface without listening (tests); it starts the default table unless the registry is explicit, and a named-but-unset PasswordEnv always fails — for “open locally, password in prod” use Auth{AllowOpen: true} in code and -password-env NAME in prod, and never -allow-open behind a same-host reverse proxy
host.Auth{Password, PasswordEnv, Realm, AllowOpen, Logger}.Wrap(h) (http.Handler, error) (Logf deprecated)Basic Auth, any username, constant-time compare of SHA-256 digests. Password wins over PasswordEnv. No password → ErrNoPassword (fails closed) — unless AllowOpen: then it logs a loud warning and serves loopback clients only (others 403). Dev harnesses only; never behind a reverse proxy
host.NewTable(id, game string, seats []cig2.PlayerID, opts ...cig2.SessionOption) (*Table, error)Reset() error (keeps the table’s config), ResetWith(opts ...cig2.SessionOption) error (replace per-table options; none = back to base), ResetSeed(seed int64) error (this game from seed, config kept), Seed() (int64, bool), Claim(p, conn) (*cig2.Session, error), Release(conn), Submit(p, raw) error, Apply(p, action) error, ClaimSeat(p) (token, error), CheckSeat(p, token) bool, ReleaseSeat(p, token) error, Session(), Seated(p) bool, Seats(), ID(), Close()
Config.Server.Invites / -invites; Server{InviteTTL (48h), GrantTTL (7d), PlayURL func(table, seat) string}one-time seat links. GET /cig2/lobby is the host’s built-in lobby (/ redirects there if the game has no page). POST [/t/{id}]/invite?player= returns {table, seat, path, expires, recovery}; POST …/invite/revoke. Both are host only. GET …/join?invite= is the public page and spends nothing. POST …/join/redeem?invite= returns {table, seat, token, claim, play} and sets the grant cookie. GET …/seats returns {host, seats:[{seat, claimed, connected, invited, invite_expires}]}. With Invites on, host’s own reset, create, claim and delete are host only too (a guest plays their seat, nothing else). None of the invite routes is mounted with Invites off. NewHandler adds host.InvitePublicRoutes to Auth.Public
t.Invite(seat, ttl) (code, expires, err); t.Redeem(code) (seat, token, err); t.RevokeInvite(seat); t.InviteFor(code); t.SeatInfo(); t.ReissueSeat(seat) (token, err)an invite reserves an unclaimed seat (ClaimSeat → ErrSeatTaken). On a claimed seat it is a recovery link: redeeming it issues a fresh token and displaces the old holder. Only code hashes are kept, and the token is issued at redeem. Invites survive Reset, and a restart with -data-dir. Errors: ErrBadInvite (404), ErrInviteExpired (410, and the code is spent), ErrNoInvite
host.CredentialOf(r) → ViaPassword/ViaGrant/ViaPublic/ViaOpen/ViaNone; host.IsHost(r); host.HostOnly(h); host.Grant(w, r, ttl)how the request passed the gate. IsHost is password or open dev gate. HostOnly returns 403 for guests: wrap your own lobby routes. Grant grants via the request’s own gate, so no Auth value is needed; ErrNoPassword on an open gate, ErrNoGate outside one
reg.SetIdleTTL(d); Config.IdleTTL; -idle-ttl 24hdeletes tables with no stream, action or reset for d; never the default table
/cig2/invite.js: tablePaths(), playURL(table, seat), isHost(table), adoptSeat({claim, seat, token}), redeemInvite(url), <cig2-invite table exclude refresh>; transport-sse.js: seatTokenKey, storeSeatTokenthe browser half: endpoints from ?table=&player=, storing a handed-over token, the host’s seat panel
host.Auth{..., Public, GrantSecret}; host.PublicRoutes(patterns...); auth.Grant(w, r, ttl) errorinvite links without the password: Public (nil = nothing public; build it with PublicRoutes("GET /join", "POST /join/redeem"), ServeMux patterns) skips the password for those routes, still CSRF-protected, and never widens AllowOpen. Grant, called after spending a one-time code, sets a signed HttpOnly SameSite=Lax cookie the gate accepts until ttl. It equals the password (every route); seat tokens still pick the seat. It ends on a password change, and on restart unless GrantSecret (≥32 bytes) is set. No password → ErrNoPassword; ttl ≤ 0 → ErrBadGrantTTL
host.Auth.Validate() errorthe gate’s fail-closed rules, shared by Wrap, NewHandler and Run: a named-but-unset PasswordEnv is ErrNoPassword even with AllowOpen; no password at all is ErrNoPassword unless AllowOpen (which therefore opens only with no Password/PasswordEnv)
*host.RegistrySetLogger(*slog.Logger), a table’s Setup runs outside the registry lock (a slow start blocks nobody; concurrent Table(id) waits for it, Create(id) gets ErrTableExists), after Close → ErrRegistryClosed (503) (tables, sessions and lifecycle records — “table created”, “game started”, “seat displaced”, “table deleted”, “table failed”, “registry closed” — with a table attribute; Server.Mount calls it with Server.Logger; never logs seeds), Table(id) (*Table, error), Create(id, opts ...cig2.SessionOption) (*Table, error) (per-table options on top of the registry’s, kept across resets; ErrTableExists), CreateSeed(id, seed, opts...) (first game from seed only), Lookup(id) (*Table, bool), Game() string, SetExplicit(bool) (explicit mode: no table is created on first use — ErrUnknownTable, served as 404 — only Create/POST create start one) (get-or-create, up to DefaultMaxTables=64 → ErrTooManyTables), SetMaxTables(n), Tables() []string, Delete(id) error (close the table — streams get the "deleted" farewell — and forget it: Lookup false, the ID re-creatable; ErrUnknownTable; a held *Table can’t Reset back to life), Close() (returns once every session’s actor has exited; Delete and Table.Close wait too)
host.Server{Registry, Keepalive, Buffer, SyncActions, InsecureSeats, ExposeSeeds, AllowDelete, TrustedOrigins, InsecureAllowCrossOrigin, Logger} (SeatTokens deprecated, ignored)Mount(mux), or the handlers alone: Events(), Action(), Reset(), State(), List(), Claim(), Release(), Delete() — wrap those in Protect(h). CSRF: every mounted route refuses unsafe-method requests a browser marks cross-site (Sec-Fetch-Site, or an Origin ≠ Host) with 403, unless the origin is in TrustedOrigins (bad entry panics at Mount); no-header clients (curl, agents) and GETs pass; InsecureAllowCrossOrigin turns it off. A 500 body is always generic ("internal error"; the error is logged). AllowDelete: POST /t/{table}/delete → Registry.Delete (200 {"status":"deleted","table"}, 404 unknown; 404 for everything with it off; no un-prefixed /delete — use /t/default/delete). Seat tokens are on by default (InsecureSeats turns them off): POST claim?player= issues a token (409 if held; survives reset; POST release?player=&token= frees it), then every events/action/state for that seat needs ?token= or the X-CIG2-Seat-Token header (403). SyncActions: POST action waits for the outcome — 200 {"ok":true,"id"}, 422 rejection, 409 game over, 400 malformed, 500 settle runaway or a panic ("internal error"; a failed table says so) — instead of 202. A table whose session failed (Table.Err()) answers 500 on events/state/action until reset

Mount owns its paths. /events, /action, /reset, /state, /tables, /create, /claim, /release, /cig2/ and everything under /t/ belong to it. A game route on the same mux that overlaps one of them (your own POST /reset) makes http.ServeMux panic at startup. Give your routes other names, or mount host under a prefix on its own mux:

play := http.NewServeMux()
srv.Mount(play)
mux.Handle("/play/", http.StripPrefix("/play", play)) // /play/events, /play/t/x/state, /play/cig2/…
mux.HandleFunc("POST /reset", myOwnReset)              // free again

Then point the page at /play/events, /play/action (and /play/claim). Claiming a seat displaces its previous stream; Reset closes every stream on the old session so browsers’ EventSource reconnects to the new one. Every close host chooses ends with a farewell frame, event: close with {"reason": host.CloseReset | host.CloseDisplaced | host.CloseShutdown | host.CloseDeleted | host.CloseFailed} ("reset", "displaced", "shutdown", "deleted", "failed" — a panic failed the session), which SSETransport turns into status. Table.Close/Registry.Close end the streams with "shutdown"; wire httpServer.RegisterOnShutdown(reg.Close), or Shutdown waits out its whole deadline on streams that never go idle. The app password is the only gate — anyone with it can play any seat and reset any table; Auth.Grant hands that same access to an invited guest without telling them the password. The core never imports host; skip it for anything else (WebSockets, accounts, a lobby).

Standard 52-card deck (deck52/)

Opt-in; the framework never imports it. Not for a game with a non-standard deck.

deck52.StandardDeck() []*deck52.PlayingCard   // 52, fixed order, ace-low 1..13
deck52.Register(gameName string)              // registers the payload
deck52.PayloadOf(c *cig2.Card) (*PlayingCard, error)
deck52.Suits() []Suit                         // copy
(Suit) IsRed() bool
deck52.Clubs / Diamonds / Hearts / Spades
deck52.Ace / Jack / Queen / King              // 1 / 11 / 12 / 13

The line is properties of a French-suited deck, not rules of games played with one: IsRed belongs here, a pip value does not (cribbage counts face cards as ten, blackjack disagrees) — write that as a function in your own package. Ranks are ace-low 1..13; a game wanting ace-high defines its own payload, as games/highcardduel does with 2..14.

Testing a game (cig2test/, Session.Apply)

Framework-level test tooling: fuzz targets with seeds in testdata/fuzz/ (go test -run='^$' -fuzz='^FuzzInboundFrame$' -fuzztime=1m .), golden per-seat snapshots (go test ./games/highcardduel -run TestGoldenSnapshots -update -count=1 — always -count=1, or the cache replays a stale pass), benchmarks (go test -run='^$' -bench=. ., baselines in docs/benchmarks.md). cig2.Version is the release ("v0.1.2").

Golden helpers: g := cig2test.NewGolden() (one per scripted game); g.Render(t, step, seats...) []byte — every frame per seat as indented JSON, card UUIDs renamed c1, c2, … deterministically (seats in the given order, keys sorted) and replaced everywhere, including bare strings in hint data or game state and map keys, and any other string shaped like a minted UUID (32 lowercase hex — e.g. a hidden card a game names in its state), named after the "uuid"-key cards; cig2test.CheckGolden(t, path, got, update bool) — compare, or write with your own -update flag; cig2test.AssertNoHiddenLeaks(t, step) — from the typed ZoneViews: no identity (payload, tag, state) on an unrevealed card the seat can’t see, no entries in Hidden or another seat’s Concealed zones, no UUIDs in FaceDown.

Settle and phase hooks run only inside a live session’s actor, so calling HandleAction directly does not test your rules. Use the harness:

tbl := cig2test.Start(t, mygame.Name, []cig2.PlayerID{"p1", "p2"}, opts...) // real session, acked conns, stopped at cleanup
open := tbl.Opening.Snapshot("p2")             // what p2 saw at the start
step := tbl.Act("p1", "play", payload)         // data marshalled to JSON; nil for none
step.Err                                        // rejection | cig2.ErrGameOver | settle runaway | nil
step.Snapshot("p2")                             // p2's snapshot from this action (fails the test if none)
step.Snapshots / step.Errors / step.Frames      // per seat, in order; Frames are the raw wire bytes
tbl.Answer("p1", decisionID, "choice")          // answer an Ask through the real cig2.answer path
tbl.Apply("p1", cig2.Action{...})               // a ready-made action
tbl.Fire("p1", "timeout", nil)                 // through the timer path: Origin == OriginTimer
tbl.Last("p1")                                  // latest snapshot across all steps
tbl.Session().Do(func() { /* read or stage state */ }) // read into locals; NEVER t.Fatal inside (actor goroutine)

Each Act runs through (*Session) Apply(p PlayerID, a Action) error: the exact inbound path (ack, game-over gate, answer routing, HandleAction, settle, CheckEnd, broadcast), synchronously on the actor. When it returns, every frame the action produced is buffered. Apply is callable from any goroutine between Start and Stop; outside tests use Submit. Frames from timers that fire between steps are dropped from the next Step.

Scripted tests with raw sessions: ack or disable the timeout. cig2test.Start acks every seat, and fails the test if the handshake timeout drops one anyway. A raw NewSession + Start in a test does not ack: after 5s every seat is dropped and gets no more snapshots, so a long script reads stale frames that look like nondeterminism. Call cig2test.AckAll(t, s) right after Start, or pass cig2.WithAckTimeout(0). A drop logs a Warn naming the seat; s.Connected(p) reports it.

Every cig2test table checks rejections strictly: a step whose action was rejected but changed game state fails the session (step.Err → cig2.ErrRejectionMutated) and the test. Opt out with cig2.WithStrictRejections(false) in Start’s options. Outside cig2test it is on under -tags cig2debug and off in release builds unless WithStrictRejections(true).

Wire protocol (action.go, view.go)

type Action struct {
    Name string          `json:"action"`
    Data json.RawMessage `json:"data,omitempty"`
    ID   string          `json:"id,omitempty"` // optional correlation id: echoed as "id" on its error frames, "ack_id" once accepted
    Origin Origin        `json:"-"`            // OriginPlayer (zero) | OriginTimer — set by the framework, never from JSON; a.FromTimer()
}

Inbound envelope: {"action": "...", "data": {...}}. Names starting with cig2. (cig2.ReservedPrefix) belong to the framework: a player frame using one other than cig2.answer is rejected with ErrReservedAction before the game sees it. The reserved action name "ack" is consumed by the framework itself (join handshake) and never reaches HandleAction; so is "cig2.answer" (AnswerAction), which answers a pending decision: {"action":"cig2.answer","data":{"id":"<decision id>","choices":["..."]}}.

type CardView struct {
    UUID     string      `json:"uuid"`
    Revealed bool        `json:"revealed"`
    Tag      string      `json:"payload_tag,omitempty"`
    Payload  CardPayload `json:"payload,omitempty"`
    State    any         `json:"state,omitempty"` // Card.SetState; only where Payload is. Decodes as json.RawMessage
}
type ZoneView struct {
    ID       string     `json:"id"`
    Tag      string     `json:"tag"`
    Mode     Mode       `json:"mode"`
    Owner    PlayerID   `json:"owner,omitempty"`
    Count    int        `json:"count"`   // ALWAYS the true count
    Cards    []CardView `json:"cards,omitempty"`  // may hold FEWER entries than Count
    Children []ZoneView `json:"children,omitempty"`
}
type Result struct {
    Winners []PlayerID `json:"winners,omitempty"`
    Reason  string     `json:"reason,omitempty"`
}
type Snapshot struct {
    Type      string          `json:"type"`      // "snapshot"
    Session   string          `json:"session"`
    You       PlayerID        `json:"you"`       // the ONLY source of "who is viewing"
    Root      ZoneView        `json:"root"`
    Turn      PlayerID        `json:"turn,omitempty"`
    Phase     PhaseID         `json:"phase,omitempty"`  // only if SetPhase was called
    Round     int             `json:"round,omitempty"`  // counts from 1
    Over      bool            `json:"over"`
    Result    *Result         `json:"result,omitempty"`
    GameState json.RawMessage `json:"game_state,omitempty"`
    Decisions []DecisionView  `json:"decisions,omitempty"` // see Session.Ask
    Legal     []ActionHint    `json:"legal,omitzero"`    // ActionHinter; absent = no hints, [] = nothing legal
    AckID     string          `json:"ack_id,omitempty"`   // latest accepted action id from this seat
}
type DecisionView struct {
    ID       string     `json:"id"`
    Seat     PlayerID   `json:"seat"`
    Deadline *time.Time `json:"deadline,omitempty"` // session clock; absent for NoDeadline
    Ask      *AskView   `json:"ask,omitempty"`      // ONLY in the seat's own snapshot
}
type AskView struct {
    Kind    string          `json:"kind"`
    Prompt  json.RawMessage `json:"prompt,omitempty"`
    Choices []string        `json:"choices"`
    Min     int             `json:"min"`
    Max     int             `json:"max"`
}

Error frame (outbound, to one player only): {"type":"error","message":"...","id":"..."} — id echoes the causing action’s id when it had one (recovered even from a frame whose other fields are mistyped). An action after game over is ignored silently unless it carries an id, in which case it gets an ErrGameOver error frame. snapshot.ack_id is the id of the seat’s latest accepted action that carried one.

Looking things up in a received view — (ZoneView) Find(uuid string) (CardView, bool) (a card anywhere in the subtree, by UUID, the per-instance ID; finds only what the viewer was sent, so never a face-down card in a Hidden/FaceDown/non-owned Concealed zone; an OwnerOnly card seen by a non-owner comes back opaque) and (ZoneView) FindZone(id string) (ZoneView, bool). Use these in tests and Go clients instead of a hand-written tree walk.

Filter(z Zone, viewer PlayerID) ZoneView — the pure function that produces what one player is allowed to see. Recomputed fresh on every broadcast; full snapshots, never diffs.

Session lifecycle (lifecycle.go)

MethodNotes
Attach(p PlayerID, conn Conn) errorpre-Start() only
TokenFor(p PlayerID) (string, bool)reconnect token, available any time
Start() errorruns Setup, launches the actor goroutine, broadcasts. Idempotent — repeat calls return an error without re-running Setup
Submit(p PlayerID, raw []byte)call from a reader goroutine; only ever sends on a channel; copies raw, so the caller may reuse its buffer once it returns
Stop()idempotent; returns at once (callable from the actor)
Wait()blocks until the actor has exited and its timers are stopped — after Stop, a failing panic or a cancelled WithContext. Returns at once if never started; panics if called from the actor. s.Stop(); s.Wait() leaves no goroutines
(Goexit guard)if a callback or Do closure calls runtime.Goexit on the actor — t.Fatal/t.FailNow in a test — the session fails with ErrActorExited (Callback "Goexit") instead of hanging later calls; assert on the test goroutine, after Do returns
Err() errornil while healthy; after a panic failed the session, wraps ErrSessionFailed and the *PanicError. Any goroutine
Done() <-chan struct{}closed when the session stops (Stop, or a failing panic — Err is set first)
Reconnect(token string, conn Conn) (PlayerID, error)no deadline — a player may rejoin any time the session is alive; sends a fresh snapshot on success
Disconnect(p PlayerID) errormarks dropped; session keeps running
Connected(p PlayerID) boolwhether p is sent snapshots: false after Disconnect, after the ack timeout dropped an unacked seat, or for an unknown seat; an ack or Reconnect restores it. Any goroutine (runs via Do)
SnapshotFor(p PlayerID) ([]byte, error)p’s current snapshot, marshalled exactly as a broadcast would send it; sends nothing. Any goroutine (runs via Do)
DoContext(ctx, fn) error, ApplyContext(ctx, p, a) error, SnapshotForContext(ctx, p)bound the wait for the actor: if ctx is done before the actor takes the work → ctx.Err(), never run; once taken it runs to completion. host passes the request context
Schedule(after time.Duration, player PlayerID, action Action) (cancel func())delivers action on the actor goroutine after the delay, attributed to player, tagged OriginTimer. Fires once; never after Stop; dropped once the game is over. Timers are time.AfterFunc (no goroutine while armed) feeding a non-blocking mailbox. Cancel is airtight on the actor (from HandleAction): a delivery already queued is dropped. Cancel schedules that stop being relevant — an uncancelled timer keeps its action alive until it fires

Conn — Send(msg []byte) error, Close() error. For SSE don’t write an adapter: ChanConn + sse.Stream, or the whole host package (as cmd/cig2-demo uses). ChanConn (NewChanConn(buffer int) *ChanConn, .Messages() <-chan []byte) is the in-memory Conn used to drive sessions in tests over real goroutines/channels.

Panics

Every actor step (and Setup) runs under recover. A panic in HandleAction with the board provably unchanged (deep fingerprint of all game state, equal before and after) is a rejected action: error frame "internal error" + action id to the seat, Apply → *PanicError{Rejected: true}, play goes on. Any other panic fails the session: same frame to the acting seat, Err() → ErrSessionFailed, Done() closes, nothing more runs (Start returns the failure for Setup; a Do closure’s panic is re-raised on Do’s caller as the *PanicError). PanicError{Callback, Seat, ActionID, Value, Stack, Rejected}; cig2.InternalErrorMessage is the only text a client sees. A snapshot whose game-supplied data cannot be marshalled (a func value such as c.UUID in hint Data/GameState/an Ask prompt) is logged at Error as a *SnapshotError{Callback, Seat, Err} and the seat gets SnapshotErrorMessage instead of its view. Cost: one fingerprint per HandleAction (≈ one snapshot’s marshal).

Ground rules, fast

  • No package-level mutable game state. Ever. SetState/State on the session is where per-table data lives.
  • Actor-only methods panic (debug build) or race (release build) if called off the actor goroutine. Only Setup/HandleAction/CheckEnd are the actor goroutine.
  • A card lives in exactly one zone. Add detaches it from wherever it was first — this is enforced by the shared cardZone base, not by each zone type individually.
  • Reveal() is one-way and sticky across every future zone. Don’t call it unless identity must survive re-entering a stricter zone. Calling it when you don’t need to is the single most common way to leak information in a new game (see docs/getting-started-snap.md §5 for a worked example).
  • Moving a card does not carry its visibility with it — only the sticky Revealed flag travels. A face-up card moving into a Hidden zone without a fresh Reveal() vanishes from the wire entirely (Filter drops it from Cards, leaving only a count), and no build, vet, or domain-level test will notice. Destination Public → no Reveal() needed; OwnerOnly → needed if non-owners must see it; Hidden → always needed. See docs/getting-started-snap.md §5.1.
  • Every concrete zone type gets a compile-time interface assertion right next to its definition.
  • Adding a game never touches framework code. Self-register in init(); put per-table state in SetState, never on the Game struct.
  • Full snapshots, not diffs. Don’t build incremental patching without a measured need.

Browser toolkit (web/)

Zero dependencies, no build step, no shadow DOM. See web/AGENTS.md for the full authoring guide — this is the lookup table.

Elements (web/cig2.js)

ElementClassKey members
<cig2-table>Cig2Tablesnapshot (get/set — triggers render), viewer (get, from snapshot.you), zoneView(id), claimCard(uuid), render(), transport (get/set), send(action) (→ false if dropped: no transport, or stale under the guard — fires cig2-dropped; else the transport’s result), statusBanner/staleGuard (get/set the attributes), isLive (open/game-over and a snapshot since the last drop), whenLive(fn) (wrapper: calls fn only while live, drops otherwise — never queues), connectedCallback/disconnectedCallback (wires click-delegation and the guard once / closes transport)
<cig2-zone zone="ID">Cig2Zoneupdate(table) — bind one zone by ID, render into a child <cig2-cards>
<cig2-board>Cig2BoardsyncStructure(table) — mirrors the whole tree as nested zones; structure only, never renders a card
<cig2-card>Cig2Cardnever author by hand — produced by zones
<cig2-table status-banner>opt-in default status banner (table.statusBanner = true too): a <cig2-status> saying why the board is not live, a transport.reconnect() button in terminal states, and — while data-stale — [data-cig2-action] controls disabled and their clicks dropped. Cleared only by a fresh snapshot; never re-enables a control the page disabled
<cig2-table stale-guard>the stale guard without the banner (the banner implies it). While data-stale: a capture-phase block of click/dblclick/submit/change/Enter-Space keydown/pointer-mouse-touch down/up anywhere inside the table (STALE_GUARDED_EVENTS; activations also preventDefault), [data-cig2-action] disabled, send() dropped. [data-cig2-live] opts a subtree out. Blocked activations fire cig2-dropped {reason:'stale', event, target}
<cig2-status>Cig2Statusproduced by the banner — never author by hand

No seat attribute anywhere — the viewer always comes from Snapshot.you.

Pick one style per table — don’t combine <cig2-board> with a hand-placed <cig2-zone> for a zone ID it would also mirror; both would bind the same card UUID and fight over Cig2Table’s reuse pool (a console.warn fires if this happens, but the render outcome is still ambiguous — don’t rely on it).

The styling vocabulary — this is all of it

On a zoneOn a card
data-zone (id)data-uuid
data-tagdata-opaque (present when no identity)
data-modedata-revealed
data-ownerdata-tag (= payload_tag)
data-countone attribute per payload field (data-rank, data-suit, …)
data-relation (mine | theirs | shared, derived from Snapshot.you)data-placeholder (unkeyed, anonymous — a card the server withheld)
data-missing (zone absent from this viewer’s snapshot)

On <cig2-table>: data-you, data-session, data-over, data-turn, data-phase, data-round, and connection state — data-status (a transport status), data-status-reason (reset/displaced/shutdown, or the HTTP code of a terminal state) and data-stale (the board is not live: set on any status but open/game-over, cleared by the next snapshot). These are always set; only the banner and its styling are opt-in.

Pure view functions (web/render.js) — no DOM, no imports, no state

cardPayload(cardView) -> object | null
cardDataset(cardView) -> { [attr]: string }      // COMPLETE set; strip-then-write
relationFor(owner, viewer) -> 'mine' | 'theirs' | 'shared'
zoneDataset(zoneView, viewer) -> { [attr]: string }
placeholderCount(zoneView) -> number              // count - cards.length, never negative
indexZones(rootZoneView) -> Map<id, zoneView>
isLive(status) -> boolean                         // 'open' | 'game-over'
statusBanner(status, detail) -> { text, retry }   // the banner's words; retry = button label | null

Transport contract

{ subscribe(sink), send(action), close() }
// sink = { message(frameObject), status(status, detail) }

web/transport-sse.js default export SSETransport, constructed with { events, action, seat } (+ claim — defaults to events with “events” → “claim”, false turns claiming off; release, storage, retryBase). It claims a seat token by default (host enforces them); a 404 claim means no tokens. Any object implementing the three methods above drops in as table.transport = ....

SSETransport statusmeansleaves by
connectingbefore the first openopen
openstream livedrop, farewell, game over
reconnectingdropped; detail.reason reset (reconnects at once) or shutdownopen
game-overfinal board (snapshot.over); stream still livethe reset farewell
displaced ⛔another tab/client took the seat (never auto-retried)reconnect()
seat-taken ⛔claim 409reconnect()
forbidden ⛔stream 401/403 (after one re-claim with tokens)reconnect()
not-found ⛔stream 404 — unknown table or seat; or the "deleted" farewell (detail.reason)reconnect()
failed ⛔the "failed" farewell — a panic stopped the table; it stays down until resetreconnect()
closed ⛔close()reconnect()

⛔ = terminal (transport.terminal): no retries. Members: status, statusDetail ({reason?, http?}), terminal, onStatus(cb) → unsubscribe (called at once with the current status), reconnect(). EventSource hides HTTP codes, so when the browser gives up (or fails 3× running) the transport probes the stream URL once to classify it; network errors, 5xx and 200 retry with backoff (retryBase ms, doubling to 15s). Exports STATUSES, TERMINAL.

Card appearance, three layers, in order

  1. CSS off the data-* attributes alone (no JS).
  2. <template data-cig2-card="tag"> with data-cig2-field="x" slots — toolkit clones and fills it.
  3. registerCard(tag, (el, payload) => {...}) — never called for an opaque card.

Actions & errors

data-cig2-action="name" (+ optional data-cig2-data='{"json":true}') on any element inside <cig2-table> → table.send({action, data}). The toolkit never validates — a rejected action comes back as a bubbling cig2-error DOM event (detail = the error frame), and the current snapshot is left untouched.

Go embedding

import "github.com/PipGrylls/CIG2/web"
mux.Handle("/cig2/", http.StripPrefix("/cig2/", http.FileServerFS(web.FS)))

web.FS embeds exactly cig2.js, render.js, transport-sse.js, cig2.css — never the dev files (render.test.js, harness.html, package.json, AGENTS.md).

Commands, fast

go build ./... && go vet ./... && gofmt -l .
go test ./...
go test -race ./...
node --test 'web/*.test.js'      # quoted glob — bare `web/` fails on Node 25
python3 -m http.server <port> --directory web   # then open /harness.html

v0.2.0 additions

Persistence (journal.go, replay.go, journal/)

cig2.WithJournal(j cig2.Journal)record every step, write-ahead, with a state digest
cig2.WithReplay(records)rebuild from a journal at Start; ErrJournalDiverged [E101], ErrNotReplayable [E102]
cig2.WithUnjournaledDo(cig2.UnjournaledDoTaint)a mutating Do taints instead of failing [E103]; Session.Tainted()
cig2.WithIDSeed(seed)reproducible card UUIDs and decision IDs, tests only
cig2.GameVersioned{ GameVersion() string }names your rules version in every journal
journal.NewMem(), journal.Open(dir, journal.SyncEveryStep)in-memory journal; file store (Create, Reopen, Read, Tables, SaveMeta, Delete)
host.Config.DataDir / -data-dir, Registry.SetStore, Registry.Restoretables survive restarts
cig2test.Table.Journal(), .SkipReplayCheck()every table replays its journal at cleanup [E507]

On a journaled session, every s.Now() within one step returns the same instant (UTC, no monotonic reading).

Inspector (inspect.go, host/inspector.go)

Session.Inspect() cig2.Inspectionthe full unfiltered state; never send it to a player
cig2.Inspectable{ Inspect(s) any }curate the state the inspector shows
Session.AdminApply(by, p, a), AdminFire(by, p, a), AdminCancelDecision(by, id)journaled operator steps (Record.By, RecordAdmin)
host.Config.Inspector / -inspector-addr -inspector-password-env -inspector-writesits own listener, loopback default; fails closed [E402]
host.Inspector{Registry, Password | Authorize, AllowWrites}.Handler()mount it yourself
host.ScratchReplay(game, seats, records)the table at any step, without touching the live one

Identity, lobby, matchmaking (host/identity.go, host/lobby.go, spectate.go)

host.Identity{Store, Secret, AllowGuests, TrustedProxy}principals from API keys, a trusted proxy, guest cookies; Attach, Mount, IssueAPIKey, InspectorAuthorize
host.PrincipalFrom(ctx)the request’s principal (ID == "" is anonymous)
Table.BindPrincipal(seat, id), SeatHeldBy, SeatOfa seat that follows its player, no token needed
host.Lobby{Identity, Games, Store, Matcher, Bots, BotWait, AllowSpectators} / Config.Lobby / -lobby -bot-wait/lobby/… and /match/… routes; Start, Close; the flags add guest sign-in if the program set no Identity
host.FIFOMatcher{Widen}, host.RandomBots{}the default matcher; bots for any game with hints
host.OpenIdentityStore(path), host.NewMemIdentityStore()principals, key hashes, results, lobby tables
cig2.SeatPolicy{ SeatRange(config) SeatRange }variable seat counts
Session.Watch(conn), cig2.SpectatorStaterspectators: public information only; game state only if the game opts in
cig2.WithOnGameOver(func(Result)), Registry.CreateSeated

Wire contract and descriptions (schema/, contract/, describe.go)

schema.For[T]() schema.SchemaJSON Schema for a Go type, as encoding/json encodes it
cig2.GameDescriber{ Describe(config) GameDescription }rules, seats, per-action schemas → GET /describe
GET /schema, GET /openapi.jsonthe generated contract; regenerate with go generate ./contract
host.Server.Routes(), host.AllRoutes()the route tables both Mount and the OpenAPI come from

Agent tooling

cig2test.Explore(t, name, seats, opts…)automated play-testing; Games, MaxSteps, MayNotEnd, Seed, WithGameConfig [E501–E506]
go run github.com/PipGrylls/CIG2/tools/cmd/cig context [topic]version-matched guidance; errors CODE; schema
… cig check ./...wallclock, globalrand, maprand, zerovisibility, pkgstate, actoronly, uuidorder, fatalinactor
… cig new <module>; … cig new -package-only <import path> [dir]an agent-ready game template; -package-only writes just the package and tests into an existing module
… cig inspect tables | board T | as T SEAT | timeline T | step T SEQthe inspector from a terminal