Changelog

Changes that a game or server built on CIG2 may need to act on. Each entry says what changed and, under Migrate, what to do about it.

Upgrading from v0.3.0 to v0.3.1

v0.3.1 closes a gap that rhetoric found on its first day on v0.3.0. Take it with go get github.com/PipGrylls/CIG2@v0.3.1; the cig tool is tagged tools/v0.3.1.

Fixed: with invites on, a guest could reset, create or delete tables. v0.3.0 kept the invite routes host only, but host’s own POST reset, create, claim and t/{table}/delete still let any grant holder through. A guest could press a board’s “New deal” and wipe the game. With Server.Invites on, those routes are now host only too (403 for a guest). A guest plays the seat they were given and nothing else; seats are handed out by the host’s links, not claimed. Without Invites nothing changes: everyone through the gate holds the password.

New: pages can tell whether the viewer is the host. GET seats answers "host": true|false, and /cig2/invite.js exports isHost(table). Use it to hide host-only controls (new game, leave, reset) from guests. <cig2-invite> now hides itself for guests, refreshes at once when its table or exclude attribute changes, and waits quietly for a table that hasn’t started yet instead of showing an error.

Migrate: if guests used your board’s reset button, only the host can press it now. Hide it with isHost(). Your own host-only routes still need host.HostOnly.

Upgrading from v0.2.2 to v0.3.0

v0.3.0 builds invite links into the framework. cig2-test, rhetoric and sticker-card each hand-rolled the same lobby on v0.2.2; this is that lobby, done once, with the gaps all three hit fixed. Take it with go get github.com/PipGrylls/CIG2@v0.3.0; the cig tool is tagged tools/v0.3.0.

The flow. The host signs in with the app password, starts a game, takes a seat and makes a one-time link for each other seat. Whoever opens a link presses “Take the seat” and plays, without ever being asked for the password.

Turn it on with -invites (host.Config.Server.Invites). Then:

  • GET /cig2/lobby is a built-in lobby page for the host: start a game, see every table’s seats (free, invited, taken, connected), and make, copy or revoke links. GET / redirects there until the game serves its own page.
  • POST invite?player= (and /t/{table}/invite) makes a link ({table, seat, path, expires, recovery}). POST invite/revoke?player= cancels it. Both are host only.
  • GET join?invite= is the page the link opens. It is public, and opening it spends nothing, so a chat app’s link preview can’t use the link up.
  • POST join/redeem?invite= spends the code. It sets the guest’s grant cookie and answers {table, seat, token, claim, play}.
  • GET seats lists every seat’s state, for players too.

NewHandler makes the join routes public by itself (host.InvitePublicRoutes).

On a table (host.Table):

  • Invite(seat, ttl) makes a link. On an unclaimed seat it reserves the seat: ClaimSeat refuses it until the link is redeemed, revoked or expires. On a claimed seat it is a recovery link: the current holder plays on until the link is redeemed, then the new browser gets a fresh token and the old one is displaced. That covers a second device, cleared browser storage, and handing over a solo game.
  • Redeem(code) spends a code. RevokeInvite(seat) cancels one. InviteFor(code) looks a code up without spending it. SeatInfo() lists every seat’s state. ReissueSeat(seat) gives a seat a fresh token from code.
  • The table keeps only hashes of codes and issues the seat token at redeem time. No plaintext token waits on the server any more.
  • Invites survive Reset, and with -data-dir they survive a restart.
  • Links last 48h (Server.InviteTTL). A guest’s grant lasts 7 days (Server.GrantTTL). A guest lands on Server.PlayURL, by default /?player=p2, or /?table=ID&player=p2 for tables other than the default.

A grant is no longer the password. The gate records how each request got in: host.CredentialOf(r) returns ViaPassword, ViaGrant, ViaPublic, ViaOpen or ViaNone. host.IsHost(r) is true for the password, or for an open development gate. host.HostOnly(h) answers 403 to everyone else, so use it on your own lobby routes: an invited guest can play but can’t start games or make invites. host.Grant(w, r, ttl) grants through the gate that let r in, so a handler no longer needs the Auth value passed to it.

Browser toolkit: /cig2/invite.js exports:

  • tablePaths(), which reads ?table= and ?player= and returns that table’s events, action, claim and seats paths, so one page serves every table.
  • adoptSeat() and redeemInvite(), which store a handed-over token where SSETransport looks.
  • <cig2-invite table="...">, the host’s seat panel, for a game’s own board page.

transport-sse.js also exports seatTokenKey and storeSeatToken. Pages no longer need to know the storage key’s format.

Also new: Registry.SetIdleTTL(d) (-idle-ttl 24h, Config.IdleTTL) deletes tables nobody has used for d. The default table is never deleted.

Migrate: nothing breaks. The invite routes are mounted only with Invites on, so a game’s own /join, /invite and /seats routes keep working. To move a hand-rolled v0.2.2 lobby onto the framework:

  1. Delete your invite store, /invite, /join, /join/redeem and join page, and your own Auth.Public entries for them.
  2. Turn on Config.Server.Invites (or -invites).
  3. On the board page, take the paths from tablePaths() and put <cig2-invite table="..."> where the host makes links. Or send the host to /cig2/lobby.
  4. Wrap your own host-only routes (starting a game) in host.HostOnly.
  5. If your board isn’t at /?table=&player=, set Server.PlayURL.

Table.ClaimSeat now also refuses a seat reserved by an invite, with ErrSeatTaken.

Upgrading from v0.2.1 to v0.2.2

v0.2.2 lets an invite link stand in for the app password. Take it with go get github.com/PipGrylls/CIG2@v0.2.2; the cig tool is tagged tools/v0.2.2.

New: invite links that work without the app password. The flow: one player logs in with the password and sends one-time seat links; whoever opens a link plays without ever being asked for the password. Two additions to host.Auth make that possible:

  • Auth.Public func(*http.Request) bool lets matching requests through the password gate, so the invite page and its redeem endpoint load before the guest holds any credential. Build it with host.PublicRoutes("GET /join", "POST /join/redeem", "GET /invite.js") (http.ServeMux patterns). Nil, the default, means nothing is public. Public routes still pass the cross-origin (CSRF) protection, and Public does not widen an AllowOpen gate.
  • Auth.Grant(w, r, ttl) sets a signed cookie (HttpOnly, SameSite=Lax, Secure over HTTPS) that the gate accepts in place of the password until ttl passes. Call it from the redeem handler after spending the code. EventSource and fetch send the cookie on their own, so the toolkit is unchanged. A grant ends when the password changes, and when the server restarts unless you set Auth.GrantSecret (32 bytes or more; rotating it revokes every grant).

A grant is the password’s equal: it opens every route the gate guards. Seat tokens still decide which seat a browser plays, so hand the guest its seat token in the redeem response, as before.

Migrate: nothing. A game that told invitees the password can move to Public plus Grant:

cfg.Auth.Public = host.PublicRoutes("GET /join", "POST /join/redeem")
// in POST /join/redeem, after spending the one-time code:
if err := cfg.Auth.Grant(w, r, 24*time.Hour); err != nil { ... }

Upgrading from v0.2.0 to v0.2.1

v0.2.1 fixes the bugs and rough edges the first consumer games found in v0.2.0. Take it with go get github.com/PipGrylls/CIG2@v0.2.1; the cig tool is tagged tools/v0.2.1.

Fixed: a configured table could not replay its journal. With any cig2.WithConfig value other than json.RawMessage (a config struct, a pointer to one, even Config{}), replay failed at the start record with [CIG2-E101], and cig2test.Start reported [CIG2-E507] at cleanup. The state digest hashed the config’s Go value, which is the game’s struct when live but the recorded JSON on replay. It now hashes the config’s JSON encoding. A []byte config was also recorded as a base64 string, so replay handed Setup a JSON string; it is now recorded as the JSON it contains, the way DecodeConfig reads it.

Migrate: nothing, unless you added Table.SkipReplayCheck or dropped WithConfig from tests to work around this; you can remove the workaround. Journals that v0.2.0 wrote for configured tables never replayed, and still won’t: their recorded digests use the old encoding.

PhaseMachine’s read-only methods are nil-safe. Session.Phase() is nil for a game without a phase machine, so a hint guard copied from another game, if s.Phase().Halted(), panicked every table at its first snapshot ([CIG2-E206]). Current, Round, IsPhase, Halted, AtEnd, Order, Sequence, Prelude and Remaining now answer “no phase” on nil. Methods that change the machine still panic on nil.

Explore: MayNotEnd, a higher step bound, and no shrinking of endless games.

  • cig2test.MayNotEnd() is for games random play need not finish (a solitaire that can cycle its stock, a game where passing is always legal): a game still running at MaxSteps counts as passed, with every step still checked.
  • The default MaxSteps is now 5000, up from 500. A game that ends sooner never pays for the higher bound, and long games such as cribbage no longer fail with a false [CIG2-E505].
  • An [CIG2-E505] failure is no longer shrunk. Shrinking replayed up to MaxSteps actions per attempt, which made a failing Explore take minutes, and a game that never ends has no short reproducer anyway. The report gives the seed instead.

Migrate: nothing. If you set MaxSteps only to get past the old default, you can drop it. A solitaire that skipped Explore can now run it with MayNotEnd().

host.Flags adds -lobby and -bot-wait. -lobby serves the lobby and matchmaking. Unless the program set Config.Identity itself, it also sets up guest sign-in, with an in-memory store and a fresh secret per process. -bot-wait 5s fills a lonely ticket’s seats with RandomBots after that wait, and implies -lobby.

cig new -package-only <import path> [dir] writes only the game package and its tests into a directory of an existing module, such as a repository of several games. It checks the import path against the enclosing go.mod.

cig inspect reads its flags anywhere. cig inspect board t1 -addr host:8081 now works as well as putting -addr first, and an address without a scheme (localhost:8081) is no longer read as URL scheme localhost.

Docs: the persistence guide notes that under Go’s JSON v2, json.RawMessage is an alias for jsontext.Value, so %T prints the latter.

Upgrading from v0.1.2 to v0.2.0

v0.2.0 adds persistence, the inspector, identity, the lobby and matchmaking, a generated wire contract, and an agent-first toolchain. Most of it is opt-in, and the wire format of snapshots and actions is unchanged. The steps below are the ones that can affect an existing game or server. Each step compiles and tests on its own, so commit after each.

1. Take the release.

go get github.com/PipGrylls/CIG2@v0.2.0

The cig tool lives in a nested module tagged tools/v0.2.0: go run github.com/PipGrylls/CIG2/tools/cmd/cig@v0.2.0 context. Run from inside your module, it picks the CIG2 version your go.mod requires.

2. Run your tests; the new replay check may find nondeterminism. Every cig2test.Start table now replays its own journal when the test ends, and fails with [CIG2-E507] if any step comes out differently. That is the property a host needs to restore your tables after a restart, so treat a failure as a real bug. The usual causes, all reported by cig check, are:

time.Now()                          // → s.Now()
rand.IntN(n)                        // → s.Rand().IntN(n)
for p, v := range m { s.Rand()… }   // → range over sorted keys, or Collector.All
counter++ // a package variable     // → state in s.SetState

A test that stages state through Session.Do still passes. Its replay check is skipped with a log line, because no journal can replay that change. tbl.SkipReplayCheck() opts a deliberately nondeterministic test out.

3. Give every zone a visibility mode. A zone with no mode (Visibility{}) or an unknown one now shows players its count only. It used to show opaque entries carrying UUIDs. cig check (zerovisibility) finds these.

4. Session.Now is one instant per step on journaled sessions. Every table a host serves is now journaled: in memory, or on disk with -data-dir. On those tables every s.Now() within one step returns the same instant, in UTC, with no monotonic reading. A game that timed work inside a single step with two Now calls now measures zero. Measure across steps instead.

5. Change state through steps, not Session.Do. On a table with -data-dir, a Session.Do that changes game state fails the table with [CIG2-E103], because the journal could not restore it. On in-memory host tables it only marks the history as not replayable. Server code that mutated tables through Do (a lobby assigning seats by hand, say) should apply an action, or use Session.AdminApply, which is journaled.

6. Match errors with errors.Is, not by text. Developer-facing errors now end in a code, such as cig2: settle did not converge [CIG2-E202]. cig context errors E202 explains each one. Player-facing messages (“the game is over”, a game’s own rejections) are unchanged.

7. Persisted tables need JSON configs and recorded randomness. With -data-dir, a table’s config must marshal to JSON. Replay hands it to Setup as json.RawMessage, which cig2.DecodeConfig already handles. A table built with cig2.WithRand keeps its history but cannot be restored; use cig2.WithSeed, or nothing (the default source is recorded).

8. Optional: describe your game and let agents in. None of these is required, and each is a small addition:

  • cig2.GameDescriber: rules plus JSON Schema from schema.For[T](), served at GET /describe.
  • cig2.SeatPolicy: variable seat counts, for the lobby.
  • cig2test.Explore(t, Name, seats): one line of automated play-testing.

9. Check. go build ./... && go vet ./... && go test ./..., then go run github.com/PipGrylls/CIG2/tools/cmd/cig check ./....

Upgrading from 2c577fe to v0.1.0

Games pinned at 2c577fe upgrade once, in this order. Each step compiles and tests on its own, so commit after each. The release notes below (P10–P16) give the reasoning; this is the checklist.

Going straight to the latest patch (recommended — v0.1.2 at the time of writing): go get github.com/PipGrylls/CIG2@latest in step 1, follow the same steps, then read the v0.1.1 and v0.1.2 notes — one behaviour change for servers that call Auth.Wrap directly, and moving t.Fatal out of Do closures in tests.

1. Take the release.

go get github.com/PipGrylls/CIG2@v0.1.0   # mixed-case path, exactly as written

2. Card fields are getters (P13). The compiler finds most uses; go vet finds the ones it can’t (a method value passed to fmt).

// before                                  // after
if c.Revealed { ... }                       if c.Revealed() { ... }
ref := Ref{Card: c.UUID}                    ref := Ref{Card: c.UUID()}
fmt.Errorf("card %s", c.UUID)               fmt.Errorf("card %s", c.UUID())   // vet catches the old form

Warning — the compiler and vet both miss one case. c.UUID used as a value inside map[string]any, []any or an any field — a hint’s Data, a GameState map, an Ask prompt — still compiles and passes vet, because a method value is a perfectly good any. It fails only at runtime, when the snapshot is marshalled (“json: unsupported type: func() string”); the seat then gets an error frame instead of its view, and the server logs which callback supplied it (cig2.SnapshotError). Find every such use before upgrading:

grep -rnE '\.(UUID|Revealed)\b([^(]|$)' --include='*.go' .

and add the () wherever the receiver is a *cig2.Card (CardView’s fields are unchanged and need none).

Code that assigned either field must stop: build cards with s.NewCard(payload), reveal with c.Reveal(). Snapshot CardViews are unchanged.

3. Typed state and zones (P12). Optional but recommended; behaviour is the same.

// before
st := s.State().(*tableState)
z, _ := s.FindZone("hand-" + string(p)); hand := z.(*cig2.Hand)
// after — your own Setup's values: a miss is a game bug and fails the table
st := cig2.MustStateOf[*tableState](s)
hand := cig2.MustFindZoneAs[*cig2.Hand](s, "hand-"+string(p))
// a zone ID from a client's action data: an error, i.e. a rejection
pile, err := cig2.FindZoneAs[*cig2.Pile](s, data.Zone)
if err != nil { return err }

4. Config through DecodeConfig (P12).

// before
var cfg Config
switch c := config.(type) {
case Config: cfg = c
case json.RawMessage: if err := json.Unmarshal(c, &cfg); err != nil { return err }
}
// after
cfg, err := cig2.DecodeConfig[Config](config) // nil, Config, *Config or JSON
if err != nil { return err }                   // ErrBadConfig: host answers 400

Decoding is strict: a key your struct lacks is now an error. Defaults go in func (c *Config) SetDefaults(), range checks in Validate() error.

5. Validate, then mutate (P11). Under -tags cig2debug and in every cig2test table, a HandleAction that changes any game state and then returns an error fails the table and the test. “Any” is wide: the check fingerprints everything reachable from the session — the board, card and player state, the turn and phase machines, pending decisions, the RNG, and the timer bookkeeping (every Schedule/Rearm call and every Rearm epoch). The trial upgrades found the offenders were rarely an obvious move-then-fail; they were side effects that run on the error path too:

  • Deferred bookkeeping. A defer that runs after every action — re-arming a turn timer, advancing a counter — also runs when the action is rejected. Rearm bumps an epoch, so the rejection has changed state (cribbage’s deferred afterAction).
  • Starting things before validating. Starting a clock, drawing from the RNG, or arming a timer before the last check (klondike started its clock first).
// before
func (g *Game) HandleAction(s *cig2.Session, p cig2.PlayerID, a cig2.Action) (err error) {
    defer g.afterAction(s) // re-arms the turn timer — even on a rejection
    st := cig2.MustStateOf[*state](s)
    st.clock.Start(s.Now()) // a change before validation
    if !legal(st, a) { return errNotLegal }
    ...
}
// after: validate first; do follow-up work only on success
func (g *Game) HandleAction(s *cig2.Session, p cig2.PlayerID, a cig2.Action) error {
    st := cig2.MustStateOf[*state](s)
    if !legal(st, a) { return errNotLegal }
    st.clock.Start(s.Now())
    ...
    g.afterAction(s)
    return nil
}

The same goes for any rule that moves cards and then discovers a problem: look everything up and check it first, then move.

6. Timer-only actions check their origin (P11). Clients can POST any action name; only the framework can set Origin.

// before: a nonce in the scheduled action's data, or re-checking state
case "timeout":
    if data.Nonce != st.timerNonce { return errStale }
// after
case "timeout":
    if !action.FromTimer() { return errors.New("timeout is not a player action") }

Delete the nonce layer (sticker-card’s timers.go). In tests, fire timer actions with tbl.Fire(p, "timeout", nil) (cig2test) or s.ApplyTimer(p, action); Apply always means a player. Rename any action of your own that starts with cig2..

7. Content files are strict (P12). content.Load/MustLoad reject unknown keys, and a bad file now fails at startup. Fix the keys, or pass content.AllowUnknownFields() for a file that carries extras on purpose.

8. Panics and logging (P10, P13). Remove any recover() from game code — the framework recovers, then rejects the action (board unchanged) or fails the table. The default panic handler and every framework record go through log/slog; route them with slog.SetDefault, cig2.WithLogger, or host.Config{Logger}. If you recover() around s.Do, the value is now a *cig2.PanicError (read .Value).

9. Replace your server’s main with host.Run (P13, P14).

// before: ~70 lines of NewRegistry, Mount, Auth.Wrap, http.Server,
// signal.NotifyContext, RegisterOnShutdown, Shutdown, plus the page as a
// Go string
// after
//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}
    host.Flags(flag.CommandLine, &cfg)
    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) }
}

Move the page into static/index.html. cmd/cig2-demo is the reference. Replace time.Sleep after Stop with Wait.

For “open locally, password in production”, don’t put PasswordEnv in code — a named variable that is unset always fails, even with AllowOpen. Set Auth: host.Auth{AllowOpen: true} and pass -password-env NAME in the production command line (systemd unit, Dockerfile). Never serve with -allow-open and no password behind a same-host reverse proxy (Caddy, nginx): every request then looks like loopback. A lobby or other routes of your own go in Config.Routes (a GET /{$} index wins over Static for /); they get the same CSRF protection as host’s routes.

Heavy games (large state, many actions): consider cig2.WithPanicRejection(false) in Config.Options. It drops the per-action state fingerprint — 20–32% off a full action in the benchmarks — at the cost of every HandleAction panic failing the table instead of sometimes being a rejection.

10. Seat tokens and cross-origin protection are on (P14). Pages using SSETransport need no change — it claims automatically. Anything else (agents, scripts) must POST /claim?player= and send the token, preferably as the X-CIG2-Seat-Token header:

# before
curl "$B/state?player=p1"
# after
T=$(curl -s -X POST "$B/claim?player=p1" | jq -r .token)
curl -H "X-CIG2-Seat-Token: $T" "$B/state?player=p1"

Drop SeatTokens: true and -seat-tokens (the default now); use InsecureSeats / -insecure-seats only for a trusted local playtest. A page served from another origin that POSTs to the server needs that origin in host.Server{TrustedOrigins}.

11. Browser code. Handle the new terminal status failed if you switch over transport statuses (the stock banner already does), and expect a "failed" farewell from a table whose game panicked.

12. Tests. Test servers that open streams without tokens set InsecureSeats: true (or claim first). A cig2test step that rejects after mutating now fails the test; fix the game (step 5) rather than opting out with cig2.WithStrictRejections(false). Consider a golden-snapshot test like games/highcardduel/golden_test.go.

13. Check.

go vet ./... && go test ./... && go test -tags cig2debug ./... && go test -race ./...
go run honnef.co/go/tools/cmd/staticcheck@v0.8.1 ./...

v0.3.1 — 2026-11-19

With invites on, reset, create, claim and delete are host only; GET seats reports host, isHost() in /cig2/invite.js. See “Upgrading from v0.3.0 to v0.3.1” at the top of this file.

v0.3.0 — 2026-11-19

Invite links built in: Server.Invites (-invites) with a built-in lobby at /cig2/lobby, Table.Invite/Redeem/RevokeInvite/ReissueSeat with recovery links, host.HostOnly/IsHost/CredentialOf/Grant, /cig2/invite.js, and Registry.SetIdleTTL. See “Upgrading from v0.2.2 to v0.3.0” at the top of this file.

v0.2.2 — 2026-11-18

Invite links: host.Auth.Public, host.PublicRoutes and host.Auth.Grant let a one-time link stand in for the app password. See “Upgrading from v0.2.1 to v0.2.2” at the top of this file.

v0.2.1 — 2026-11-16

Fixes from the first consumer games built on v0.2.0: replay of configured tables, a nil-safe PhaseMachine, Explore’s MayNotEnd and step bound, -lobby/-bot-wait flags, cig new -package-only, and cig inspect flag order. See “Upgrading from v0.2.0 to v0.2.1” at the top of this file.

v0.2.0 — 2026-11-14

Four workstreams from the “Django of card games” review (design specs: docs/superpowers/specs/2026-11-14-*), plus a schema-first wire contract. The upgrade guide at the top of this file lists what an existing game must do.

Persistence: an event-sourced journal

  • Every step can be journaled (cig2.WithJournal): actions, decision answers, timer deliveries, decision expiries and admin operations. Each record is written before the step is broadcast, and carries a portable digest of the state after the step.
  • cig2.WithReplay(records) rebuilds a session through the real step functions, checking the digest at every step. Timers still pending are re-armed for their remaining time. A divergence is an error (ErrJournalDiverged), never silent.
  • Card UUIDs and decision IDs come from a per-session ID stream keyed by recorded crypto entropy, so a replay reproduces them. A seat’s reconnect token, which is a secret, still comes from crypto/rand.
  • The journal package: Mem, and a FileStore that frames each record with a length and a CRC, truncates a torn tail on open, refuses corruption anywhere else, takes an exclusive lock, and keeps per-table metadata.
  • host keeps tables across a restart: Config.DataDir / -data-dir, Registry.SetStore / Restore. Seat tokens are kept only as SHA-256 hashes, in memory and on disk, and keep working after a restart.
  • cig2test tables replay their own journal at cleanup ([CIG2-E507]).

Inspector

  • Session.Inspect returns the full, unfiltered state (cig2.Inspection):
    • every card in every zone, with its zone’s visibility
    • the seats’ connection state
    • the phase machine’s position
    • pending decisions and timers
    • how the session failed, including the panic value and stack
  • host.Inspector is an admin and debugger on its own listener (Config.Inspector, -inspector-addr), loopback by default. It fails closed without credentials and refuses the app password. It has:
    • the board, and “view as seat”
    • the timeline, and the table as it was at any step, replayed into a scratch session
    • a live watch stream
    • its own OpenAPI document
  • Write actions (-inspector-writes) are journaled with the operator’s name: reset, act as a seat (Session.AdminApply), fire a timer (AdminFire), cancel a decision (AdminCancelDecision).
  • Every host table now keeps a journal, in memory when there is no data directory, so the timeline always works.

Identity, lobby and matchmaking

  • host.Identity: principals (human or agent; player, host or admin) from three sources:

    • API keys, stored as hashes
    • a trusted reverse proxy’s headers, honoured only from its addresses
    • signed guest cookies

    Bad credentials get a 401, never anonymous play. Sign-ins are throttled. No passwords are stored. Seats bind to principals (Table.BindPrincipal), so a seat follows its player without a token.

  • host.Lobby (Config.Lobby):

    • tables across every registered game, public or invite-only
    • an open → playing → finished → rematch lifecycle
    • play routes keyed by identity
    • spectating, public information only (Session.Watch; a game opts game state in with SpectatorStater)
    • FIFO matchmaking that widens to the game’s minimum (Matcher)
    • bot fill (BotProvider; RandomBots plays any game that gives hints)
    • match history per principal
    • persistence of lobby tables
  • Smaller additions: cig2.SeatPolicy, cig2.WithOnGameOver, Registry.CreateSeated.

A schema-first wire contract

  • contract/cig2.schema.json (JSON Schema 2020-12) and contract/openapi.json are generated from the Go types the server marshals (go generate ./contract), served at GET /schema and GET /openapi.json, checked fresh by go test, and gated in CI: a change that breaks existing clients needs a Migrate entry here.
  • The schema package: a stdlib-only generator (schema.For[T]()) that follows encoding/json, a subset validator, and a direction-aware compatibility checker.
  • host.Server.Routes: one route table drives both Mount and the OpenAPI document. The ad-hoc JSON bodies became named types (TableStatus, ClaimResponse, …), with the same JSON as before.
  • cig2.GameDescriber (GET /describe): rules, seats, and per-action schemas. High Card Duel describes itself.
  • Renames: cig2.ErrorFrame and cig2.AnswerData are exported, and Mode lists its values in the schema.

Agent-first developer experience

  • agentdocs: version-matched guidance inside the module.

  • Stable error codes ([CIG2-Exxx]) on developer-facing errors.

  • cig2test.Explore: automated play-testing that fails on:

    • leaks of hidden UUIDs or identities in game-authored data
    • hints the game rejects
    • deadlocks and games that never end
    • failed sessions
    • nondeterminism

    It shrinks a failure and prints a test that reproduces it. cig2.WithIDSeed makes UUIDs reproducible, for tests only.

  • The tools module and its cig command:

    • cig context (guidance)
    • cig check (eight analyzers for the framework’s rules)
    • cig new (an agent-ready template that passes its own checks)
    • cig inspect (an inspector client)
  • A Claude Code plugin (.claude-plugin/), the agent eval loop (eval/), and a root AGENTS.md.

Also in this release

A determinism audit (P19), prompted by a seeded sticker-card match that diverged between runs. Verdict: the framework is deterministic under a fixed seed. It never draws from the session RNG itself, card UUIDs come from crypto/rand and never touch it, nothing in it orders by UUID, and every map it ranges is either sorted first or doesn’t affect output. determinism_test.go now pins the contract. It runs 50 fresh sessions per mode (WithSeed, WithRand) through shuffles, reshuffles, an RNG-built deck, a Collector round, a Fired timer and a real timer, and checks the frames are byte-identical after UUID renaming.

  • Collector.All() iter.Seq2[PlayerID, T] (new): submissions in declared order, then any extras sorted by ID. Ranging Values() (a map) while drawing from s.Rand() consumes the RNG in a random order each run and breaks seeded replay; a test pins that hazard.
  • cig2test.Golden renames bare UUIDs it never saw under a "uuid" key: any string shaped like a minted UUID (32 lowercase hex), e.g. a hidden card a game names in its state. They used to stay raw, so rendered frames differed every run. Such names are assigned after the "uuid"-key cards, so existing golden files keep their names.

Migrate: if you resolve a Collector by ranging Values() and draw randomness, log or break ties inside the loop, switch to All(). Re-render golden files (-update -count=1) only if a 32-hex string in your frames used to stay raw; the diff should show it renamed and nothing else.

WithSeed does not seed UUIDs, deliberately. UUIDs never affect the deal, and renaming makes frames comparable. Seeded UUIDs would also tie a card’s on-the-wire name to the seed and to the order cards were created. If byte-identical raw frames are ever needed, use a separate stream derived from the seed, never s.Rand(), so adding a card can’t shift a shuffle.

The join-handshake timeout is now loud and test-friendly (P20). sticker-card’s “nondeterminism” turned out to come from its raw test sessions never sending "ack". After the 5s handshake timeout, both seats were silently marked disconnected and sent no more snapshots, so the script read stale frames.

  • A dropped seat is reported. By default the session logs one Warn record per seat dropped at the timeout (seat, timeout and a hint). WithAckTimeoutHandler(func(seat PlayerID)) (new) replaces the Warn. host uses it to log unclaimed seats at Debug, since a placeholder seat never acks.
  • (*Session) Connected(p) bool (new, any goroutine) reports whether a seat is being sent snapshots.
  • WithAckTimeout(d) with d <= 0 disables the timeout. It used to fire at once and drop every seat. The default stays 5s.
  • cig2test.AckAll(t, s) (new) acks every seat of a raw session. cig2test.Start already acked every seat, and now also fails the test if the timeout drops one anyway.

Migrate: in a test that starts a session without cig2test.Start, replace your own ack loop (e.g. ackBothPlayers(t, s)) with cig2test.AckAll(t, s) right after Start, or pass cig2.WithAckTimeout(0). If you passed WithAckTimeout(0) expecting an instant timeout, use a small positive duration instead.

Fixes from a Go code review:

  • An unrecognised or zero-value visibility mode now drops cards, as Hidden. It used to emit one opaque entry per card, each carrying a UUID. A deck built with Visibility{} by mistake therefore let viewers correlate cards and reconstruct its order. Revealed cards still show.
  • Table.Reset no longer holds the table lock during the game’s Setup. A slow or hung Setup on reset used to stall every Submit, Claim and State on that table, and block Close, Registry.Delete and graceful shutdown. A Delete during the reset now wins: the reset returns ErrUnknownTable and its new session is stopped.
  • A rejection that wraps a *PanicError is sent as "internal error". The check was a bare type assertion, so a game returning fmt.Errorf("…: %w", panicErr) put the panic text on the wire.
  • sse.Stream no longer commits a 200 before checking the writer can flush. On a non-flushable writer it now returns its error with nothing written, so Server.Events sends a clean 500 instead of appending to an event stream.
  • Reconnect tokens are compared in constant time, like seat tokens and the app password.
  • Deck.InsertRandom moves the card it is given. For a card already in the deck it used to leave that card in place and splice the bottom card to the random index instead. A nil card is now ignored, as with Add; on an empty deck it used to panic.
  • A decision cancelled by its own Validate never resolves. OnResolve used to run anyway. The answer is now rejected as unknown, and every seat gets a fresh snapshot without the decision.

Migrate: a zone that shows count with no cards to non-revealed viewers has no Mode set. Give it one (Public(), Hidden(), …).

v0.1.2 — 2026-10-17

Golden-snapshot helpers in cig2test, from game feedback: CIG2-Test had hand-rolled them four times, and sticker-card was about to.

cig2test.NewGolden() / (*Golden).Render(t, step, seats...). Renders every frame each seat received as indented JSON with card UUIDs renamed c1, c2, …. Renaming is two-pass — names come from every "uuid" field, then every string equal to a known UUID is replaced anywhere, so bare UUIDs in hint data, game state and map keys no longer leak into golden files — and deterministic: seats walk in the order given and object keys sorted, so names never depend on Go’s map iteration order. One Golden per scripted game keeps a card’s name from step to step.

cig2test.CheckGolden(t, path, got, update) compares against a golden file or rewrites it under the test’s own -update flag. Run -update with -count=1: otherwise the test cache can replay an earlier pass and write nothing.

cig2test.AssertNoHiddenLeaks(t, step) checks every snapshot in a step from the typed ZoneViews: no identity (payload, payload tag, card state) on an unrevealed card in a zone the seat can’t see into, no card entries in Hidden zones or another seat’s Concealed zone, and no UUIDs in FaceDown zones.

games/highcardduel now uses them; its golden files are unchanged byte-for-byte.

Migrate: optional. Replace hand-rolled golden helpers (UUID renaming, leak walks) with these; keep your own -update flag and pass it to CheckGolden.

v0.1.1 — 2026-10-13

A patch from the game migrations. Drop-in for v0.1.0 except for the one behaviour change below.

host.Auth.Wrap fails closed for a named-but-unset PasswordEnv. The rule (“a PasswordEnv that names an unset variable is ErrNoPassword, even with AllowOpen”) was enforced only by host.NewHandler/host.Run, so Auth{PasswordEnv: "X", AllowOpen: true}.Wrap(h) with X unset served loopback-open. The rules now live in the new Auth.Validate() error, which Wrap calls first and NewHandler relies on; every path refuses identically.

Migrate: if you call Auth.Wrap yourself (a server that can’t use host.Run), AllowOpen now opens the gate only when neither Password nor PasswordEnv is set. Delete any hand-copied pre-check — Wrap, or Auth.Validate at startup, does it. For “open locally, password in production”, leave PasswordEnv empty in code and pass the variable’s name at deploy time (upgrade step 9).

A Goexit on the actor fails the session instead of hanging. t.Fatal or t.FailNow inside Session.Do (or a game callback) calls runtime.Goexit on the actor goroutine, which recover cannot catch: the actor died silently and every later call hung. Now the session fails with cig2.ErrActorExited (a *PanicError with Callback "Goexit"), later calls such as Apply return the failure, and Wait returns. Apply and ApplyTimer also refuse to run on a session that failed while they were queued. The rule is documented in cig2test, patterns §15 and the cheatsheet: read values out of Do into locals and assert on the test goroutine.

Migrate: move any t.Fatal/t.FailNow out of Do closures and game callbacks in your tests (t.Errorf there is fine).

v0.1.0 — 2026-10-11

The first tagged release: the architectural review series (P10–P16) on top of 2c577fe. The upgrade guide above is the short version of what follows.

P10 — Safety

Panics in game code are recovered. Before, a panic in any game callback ran on the session’s actor goroutine and killed the whole process — every table. Now every unit of actor work (actions, timers, decision deadlines, Do closures, reconnects, broadcasts) and Setup run under recover:

  • A panic in HandleAction with the board provably unchanged (a deep fingerprint of all game state is identical before and after) is a rejected action: the seat gets an error frame reading "internal error" with the action id, Apply returns a *cig2.PanicError with Rejected set, and play carries on.
  • Any other panic fails the session: the acting seat gets the same frame, Session.Err() wraps cig2.ErrSessionFailed, Session.Done() closes, and nothing more runs. Start returns the failure for a panic in Setup.
  • The value and stack go to cig2.WithPanicHandler (default log.Printf), never to the wire.
  • host ends a failed table’s streams with the new "failed" farewell (host.CloseFailed) and answers 500 with generic text on events, state and action until the table is reset; Table.Err() reports it. With SyncActions, a panic is 500 ("internal error", or the failed-table text).
  • SSETransport has a new terminal status, failed, and statusBanner explains it.

Migrate:

  • Session.Do: a panic in the closure is now re-raised on the caller as a *cig2.PanicError, after the session has failed. Code that recover()s around Do and inspects the value should read pe.Value.
  • Session.Apply and host’s SyncActions can now return a panic outcome; a client that treated every non-422 failure as fatal needs no change.
  • Code that switches over STATUSES (or data-status) exhaustively should handle failed.
  • Remove any recover() from game code. It hides a half-applied mutation from the framework, which would otherwise fail the table.
  • Each HandleAction now pays for one fingerprint of the game state (about the cost of one snapshot’s marshal: ~0.1 ms for 52 cards on the arm64 Raspberry Pi it was measured on).

ChanConn keeps the newest frame. A full buffer used to drop the newest frame, which could leave a lagging client on a stale snapshot. It now evicts the oldest, and ChanConn.Dropped() counts discarded frames. sse.Stream now writes frames still buffered when its source closes before the farewell frame.

Migrate: a test that overfills a ChanConn and expects the first frames to survive should expect the last ones. Size buffers as before.

The default RNG is secure. Without WithSeed/WithRand, a session’s RNG was a PCG seeded from time.Now. It is now ChaCha8 seeded with 256 bits from crypto/rand; WithRand(nil) keeps that default. WithSeed and WithRand are unchanged and still deterministic.

host still seeds every game for replay, from a 53-bit space (JSON-safe) into a PCG — searchable offline by a determined player. Migrate (optional): a game where that matters more than replay passes cig2.WithRand(nil) in its registry or table options; Table.Seed then reports none, and a one-off {"seed": n} still applies.

P11 — Action origin & atomic rejections

Timer actions can’t be forged. Schedule/Rearm deliver an ordinary Action, and a client could POST the same name. Every action now carries Action.Origin — cig2.OriginPlayer (the zero value) or cig2.OriginTimer — tagged json:"-". The player path (wire frames, Submit, Apply) forces OriginPlayer whatever the caller set; the timer path sets OriginTimer. action.FromTimer() is the check. Session.ApplyTimer(p, action) runs the timer path synchronously for tests (cig2test: Table.Fire); it is server-side only.

Player frames named cig2.… (cig2.ReservedPrefix) other than cig2.answer are now rejected with cig2.ErrReservedAction before the game sees them.

Migrate:

  • Make every timer-only action check action.FromTimer() first and reject otherwise. Remove nonce layers built for this (sticker-card’s timers.go) and “did a timer send this?” state re-checks (cribbage).
  • Rename any game action starting with cig2..
  • Session.Apply with Origin: OriginTimer no longer reaches the game as a timer; use ApplyTimer (or Fire) in tests that drive timer actions.

Rejections are checked for side effects. The Game contract always said a rejected action leaves the board unchanged; now it is enforced where it costs nothing. With strict rejection checking, a HandleAction that returns an error after changing any game state (by the P10 fingerprint) fails the session: Session.Err() wraps ErrSessionFailed and cig2.ErrRejectionMutated, and the acting seat gets the generic error frame. It is on under -tags cig2debug and in every cig2test table (where it also fails the test), and off in release builds unless cig2.WithStrictRejections(true).

Migrate:

  • Validate everything before mutating anything in HandleAction (patterns §24). Watch for side effects on the error path — a deferred re-arm or counter, a clock started before validation (see upgrade step 5).
  • A test that deliberately rejects after a change can pass cig2.WithStrictRejections(false) to cig2test.Start (last option wins).
  • Returning SettleNow’s ErrSettleRunaway from HandleAction still rejects the action, but whatever the settle changed stays changed, so under strict checking it fails the table — correct for a runaway, which is a game bug.

P12 — Typed helpers

Typed accessors. cig2.StateOf[T](s) (T, bool), cig2.PlayerStateOf[T](s, p) (T, bool) and cig2.FindZoneAs[T Zone](s, id) (T, error) replace bare s.State().(*T) and zone.(*cig2.Hand) assertions. FindZoneAs errors wrap ErrZoneNotFound / ErrZoneType and name the ID and both types. MustStateOf and MustFindZoneAs panic with the same message; use them only for values your own Setup created (P10 turns the panic into a failed table with a stack), and the error forms for anything a client addresses.

Migrate (optional, recommended): replace casts with the helpers — games/highcardduel is the reference. No behaviour changes for existing code.

DecodeConfig[T](config). One way to read Setup’s config: nil → defaults, T, *T, or json.RawMessage/[]byte decoded strictly. Optional SetDefaults() and Validate() error on *T. Errors wrap ErrBadConfig, which host now answers with 400 (was 500) on create and reset.

Migrate: replace switch config.(type) blocks (cribbage game.go:54-66, rhetoric game.go:59-71) with DecodeConfig. Strict decoding means a config with a key your struct lacks — previously ignored — is now rejected; add the field, or accept it explicitly.

highcardduel gained an optional Config{Decks} (default 1); the classic game is unchanged.

content.Load is strict. It now rejects unknown JSON keys and data after the top-level value, naming the file and key. Load/MustLoad take variadic options; content.AllowUnknownFields() restores the old leniency.

Migrate: run your content through the new loader. A file with stray or misspelt keys (check sticker-card’s content) now fails to load — fix the keys, or pass content.AllowUnknownFields() for files that carry extra keys on purpose. Since most games MustLoad in init(), a bad file now fails at startup.

P13 — Lifecycle & observability

Context. cig2.WithContext(ctx) ties a session’s lifetime to ctx: cancelling it stops the session (Err stays nil). DoContext, ApplyContext and SnapshotForContext bound a caller’s wait for the actor — if ctx is done before the actor takes the work, they return ctx.Err() and it never runs. host’s sync actions and state handler pass the request context (a client that gives up gets 503; its action was never applied).

Wait. Stop still returns at once (it must work from the actor); Session.Wait() blocks until the actor has exited and its timers are stopped. host’s Table.Close, Registry.Delete and Registry.Close now wait.

Timers. Schedule, Rearm and Ask deadlines are time.AfterFunc timers feeding a non-blocking mailbox instead of one goroutine each; pending timers stop with the actor. Schedule’s cancel is now airtight when called on the actor (an already-queued delivery is dropped).

Logging. cig2.WithLogger(*slog.Logger) (default slog.Default()): panics, failed sends, settle runaways and mutating rejections, with session/seat/action/id attributes. PanicError gains Action. host: Server.Logger and Registry.SetLogger — tables, sessions (tagged table) and lifecycle events; streams log their end with dropped-frame counts. Seeds are never logged.

Card fields. Card.UUID and Card.Revealed are now read-only: Card.UUID() and Card.Revealed(). The JSON wire format is unchanged.

Goroutine IDs were reviewed for removal and kept, confined to “is the caller the actor?” checks (see actorgid.go for why).

Migrate:

  • card.UUID → card.UUID(), card.Revealed → card.Revealed(). The compiler finds every use, but run go vet: a method value passed to fmt (fmt.Sprintf("%s", c.UUID)) compiles and is only caught by vet. Code that assigned either field must stop: build cards with Session.NewCard, reveal with Reveal(). CardView (snapshots) is unchanged.
  • The default panic handler logs through slog instead of log.Printf; configure output with slog.SetDefault, cig2.WithLogger or host.Server{Logger}.
  • Replace time.Sleep after Stop with Wait. Tests that counted goroutines per armed timer should expect none.
  • Optional: pass r.Context() through DoContext/ApplyContext in your own handlers.

P14 — Host hardening & host.Run

Seat tokens are on by default. host.Server enforces them unless the new InsecureSeats is set; SeatTokens is deprecated and ignored. Before, anyone holding the app password could open any seat’s stream and see its hidden cards. SSETransport claims automatically: claim defaults to the events endpoint with “events” replaced by “claim”; claim: false opts out.

Cross-origin (CSRF) protection, on by default. Every route Mount registers is wrapped in http.CrossOriginProtection (Server.Protect): unsafe-method requests a browser marks cross-site get 403. Server.TrustedOrigins admits named origins; InsecureAllowCrossOrigin turns it off. Clients that send no Origin/Sec-Fetch-Site (curl, agents) are unaffected.

Registry lock. A table’s Setup no longer runs under the registry lock, so a slow start blocks no other table; concurrent Table(id) calls share one start. Registry.Close no longer holds the lock while waiting; afterwards Table/Create return ErrRegistryClosed (503).

HTTP hygiene. sse.Stream uses http.NewResponseController: it flushes through middleware that offers Unwrap, survives a server WriteTimeout, and sets a per-write deadline (sse.WithWriteTimeout, default 30s). A 500’s body is a generic "internal error" (the error is logged); the unknown-seat 404 no longer lists the seats. Auth.Logger (slog) replaces Auth.Logf (deprecated). ?token= in URLs lands in access logs; clients should prefer the X-CIG2-Seat-Token header (EventSource cannot). host.Registry keeps its name (reasons on the type).

host.Run. host.Run(ctx, host.Config{...}) replaces a game’s main: registry, gate, server options, a static page fs.FS, extra routes, slog, ReadHeaderTimeout (always), IdleTimeout, WriteTimeout, graceful shutdown with farewells. host.NewHandler is the same without listening; host.Flags binds the standard flags. cig2-demo is migrated, with its page embedded from static/index.html.

Migrate:

  • Pages using SSETransport need nothing. Other clients must POST /claim?player= and send the token, or the server must set InsecureSeats: true (trusted local playtests only). Agents: send the token as the X-CIG2-Seat-Token header.
  • Drop SeatTokens: true (it is the default), and -seat-tokens from scripts (cig2-demo still accepts it as a no-op).
  • A page on another origin that POSTs to the server needs its origin in Server.TrustedOrigins.
  • Tests that open streams without a token: claim first, or set InsecureSeats: true on the test server.
  • Replace each game’s main with host.Run (see cmd/cig2-demo); move the page into an embedded static/ directory. Auth.Logf → Auth.Logger.
  • Clients that parsed the unknown-seat 404 for the seat list must use GET /tables.

P15 — Tooling & release prep

Fuzzing. Native fuzz targets with seed corpora in testdata/fuzz/, run by plain go test: FuzzInboundFrame (no frame can reach the game as a timer, as ack or as a reserved name; replies are one line of JSON), FuzzUnmarshalSnapshot and FuzzDecodeConfig (round trips, strictness), content.FuzzLoad, sse.FuzzStreamFrames (frames and farewell come back exactly) and host.FuzzResetBody (never a 500). CI fuzzes each for a fixed number of executions (count-based, see P16).

Benchmarks for the action hot path, with a Raspberry Pi 4 baseline in docs/benchmarks.md.

Golden snapshots of every frame each seat receives in a scripted highcardduel game; -update rewrites them.

CI adds staticcheck (clean, no suppressions), govulncheck on the latest stable Go, and the fuzz matrix.

cig2.Version is "v0.1.0", kept in step with this file by a test.

Migrate: nothing required. Copy the golden-snapshot test pattern into your game.

P16 — Pre-release fixes from the game upgrade reviews

Found by trial-upgrading both game repositories to the P15 release candidate.

cig2.WithPanicRejection(false) drops the per-action state fingerprint behind P10’s “provably unchanged” proof. With strict checking also off (a release build), an action pays nothing extra — 20–32% off a full action in docs/benchmarks.md — and every HandleAction panic fails the table. The default is unchanged; it is recommended for heavy games.

Loud snapshot failures. Game-supplied data that cannot be marshalled (typically c.UUID without parentheses stored in a hint’s Data or a GameState map, which compiles and passes vet) used to reach the seat as a raw JSON error, with nothing logged. Now it is logged at Error as a *cig2.SnapshotError naming the callback and seat, and the seat gets the generic cig2.SnapshotErrorMessage.

host.Run protects game routes. Routes added through Config.Routes (a lobby’s POST /start) are now behind the same CSRF protection as host’s own; a game’s GET /{$} index coexists with Config.Static (tested).

Docs. The “open locally, password in production” pattern (Auth{AllowOpen: true} plus -password-env NAME; never -allow-open behind a same-host reverse proxy). The upgrade guide’s strict-rejection step now describes the real offenders (deferred bookkeeping on the error path, a clock started before validation), and step 2 warns about c.UUID values inside any.

Session.Submit copies its frame. It used to hand the caller’s slice to the actor, so a caller reusing its buffer (a pooled reader, a WebSocket frame buffer, the fuzzer) changed bytes the actor was decoding — a data race that CI’s fuzz run surfaced as encoding/json panicking (“data changing underfoot”). Submit now copies at the boundary: the caller may reuse the slice as soon as Submit returns. Covered by a deterministic regression test.

CI fuzzing is count-based. The fuzz job used -fuzztime=10s; at that deadline Go’s fuzz coordinator can report its own shutdown as “context deadline exceeded” with no failing input (a toolchain race, golang/go#75804, reported fixed in Go 1.27; CI’s fuzz job runs the go.mod toolchain). It now runs a fixed execution count per target (-fuzztime=Nx, no deadline context at all), with minimization off so a real crasher is written at once, a hard timeout, and the failing input uploaded as an artifact. TestCIFuzzesEveryTarget enforces both coverage and the count form. No slow inputs were found: DecodeConfig’s worst case at the 64 KiB body cap is about 12 ms.

Migrate: covered by the upgrade guide above (steps 2, 5 and 9).

Known divergence: module path casing

The module path is github.com/PipGrylls/CIG2, mixed case, where Go convention is all lower case. It stays as is: changing it would break every import in every game for no functional gain. Write it exactly as above.