ByteTerrace/Puck / .claude/skills/puck-world
puck-world
VerifiedMaps Puck.World: .puck worlds, rules, grants, console verbs, extensions, the live MCP World. Use to run or verify a World change (stdin script, stale binary, headless run) or debug a refusal.
references/session-lifecycle.md
View on GitHub# Session lifecycle — join, leave, and reconnect
Local-seat and peer join/leave, and the park-with-grace reconnect primitive
layered onto them. Read this before
touching `WorldPopulation.Entry`'s occupancy fields, `WorldServer.ApplySession`,
or the `$parked:` reserved rule channel.
## Contents
- The two join/leave doors
- Park-with-grace
- Body-resume (seats and verified peers)
- The `$parked:<bodyRef>` reserved rule channel
- Read-back: `world.parked`
- Authoring reconnect policy over the primitive
- Verification gotchas specific to this primitive
## The two join/leave doors
- **Local seats** (`WorldPopulation.LocalSeatCount`, the document's authored `bodies.localSeats`, at most `WorldBodiesLimits.LocalSeatCount` = 4; indices `0..LocalSeatCount-1`):
`SessionRequest.Join`/`Leave` → `WorldServer.ApplySession`, applied
SYNCHRONOUSLY (loopback delivers inline, no tick gating) →
`WorldPopulation.ActivateSeat`/`DeactivateSeat`. `player.join`/`player.leave`
are the console verbs; `PlayerRoster.JoinActive`/`Leave` are the client-side
callers. A seat's `IdentityName` (a `WorldIdentity.Name`) is the durable
identity a re-Join is matched against — see below.
- **Peers** (indices `LocalSeatCount..Capacity-1`; a zero-seat world admits peer 0): `WorldServer.TryAdmitPeerConnection`/
`DisconnectPeerConnection` → the ordered-domain `WorldServerEvent.PeerAdmitted`/
`PeerDisconnected` → `ApplyServerEvent` → `WorldPopulation.ApplyPeerAdmitted`/
`ApplyPeerDisconnected`. `Server.WorldPeerHost`'s Hello door is the one live
caller, and the admission door's verified attestation identity
(`identityDomain`/`identitySubject`) is what a reconnecting peer is matched
against for body-resume (below).
**The `bodies.networkPlayers` cap counts remote humans only (the owner's
ruling).** Companions are not networked players: a census bot, an inhabitant
and an authority-transferred autonomous traveler (the debug world's companion,
body 42, following the player through a painting) never spend the cap, so an
instance with `networkPlayers: 0` still admits them. Every body the peer door
admits (`TryAdmitRemotePeerAt`: a connection or a human's transfer) is a remote
human and checks `CountRemoteHumans() >= m_remoteCap`; a parked human still
counts.
The receiving instance decides who is a human from what it hands out, never from
a sender's claim (a federation sender's signature proves who speaks, not that it
is honest). A traveler lands as a human
(`WorldTransferReservationMember.LandsHuman`) when it carries the Live source,
whatever the sender says, or the sender states `RemoteHuman`: a claim can add a
human and never exempt one. A human lands through the peer door with its carried
control source, so a human set Idle before it left still counts and stays a
human. Every other traveler lands autonomous: authored by the destination, with
no Drive grant, and `IsLiveTransferredPrincipal` refuses everything its sender
forwards for it, so it gives an outside party nothing to drive. Reserve checks
the cap over the admitted humans plus every human a live lease holds
(`NetworkPlayersRefusal`), so a reservation never binds a human its commit must
refuse. The sender classifies from its own population: a seat or an admitted
remote human travels as a human, and anything else (a companion its addon
drives, a census bot) crosses autonomous, its Live source sent as Idle since its
driver stays behind. The census ceiling (`SimulatedCeiling`) is the free peer
slots, not the cap. Replay (`ApplyPeerAdmitted`) and checkpoint restore
re-apply recorded admissions and check no cap.
## Park-with-grace
When the compiled `definition.PopulationReconnectGraceTicks` (a
`CompiledTickDuration` derived from the authored
`bodies.reconnectGraceSeconds` field at the world's own simulation rate;
default 3.0 s = 90 ticks at the unauthored 30 Hz) is `IsZero`, both doors'
leave/disconnect path tears down immediately: it nulls `Entry.Body` and clears
`Entry.Active` (and, for a peer, `Entry.IsRemoteHuman`). Any other grace parks
the body instead (`IsNever`, a positive authored grace compiled at simulation
rate 0, parks it forever and never sweeps it) — the same call:
1. Sets `Entry.Parked = true` and `Entry.ParkedUntilTick = tick +` the
compiled grace's tick count (`WorldPopulation`'s own cache of
`WorldDefinition.PopulationReconnectGraceTicks`, recompiled on any Rebuild)
(`tick` is `WorldServer.NextInputTick` at the synchronous call site, or the
`Step`-local `tick` inside the tick loop — both name the same instant).
2. Leaves `Entry.Body`, `Entry.Active`, and (for a peer) `Entry.IsRemoteHuman`
UNTOUCHED — the retained body keeps its pose and durable state, stays in the
sim/collider set (still advanced by `AdvanceSeats`/`AdvanceSimulated`, still
collidable, still a valid `$distance:`/`$argmax:` target), and
**`WorldPopulation.IsHumanOccupied` keeps reading `true` through the whole
grace window BY CONSTRUCTION** — it is defined purely in terms of
`IsActive`/`IsAdmittedPeer`, which a park deliberately never flips. This is
the owner's occupancy ruling: a parked body stays targetable and its
CC/contribution pool keeps running offline; only the eventual teardown below
removes it from the pool.
`WorldPopulation.ReclaimExpiredParks(tick)` — swept every `Step`, right beside
`WorldGrants.ReclaimExpiredEscrows` (same tick-driven, no-wall-clock,
replay-deterministic shape `OwnershipEscrow.DeadlineTick` already established)
— tears down every entry where `Active && Parked && tick >= ParkedUntilTick`:
drops the body, clears `Active`/`Parked`/`IsRemoteHuman`. It never touches the
grant table — by the time a park expires, its generation holds nothing.
**The park defers the BODY only; a peer's AUTHORITY follows the CONNECTION.**
`ApplyServerEvent`'s `PeerDisconnected` case revokes `RevokedGrants`
unconditionally, whether or not the entry parked: while disconnected nothing
can exercise the rows, yet an `Exclusive` subject the generation reserved would
refuse every live acquirer — for the whole grace window, and forever at rate 0,
where the compiled grace is `Never` and `ReclaimExpiredParks` never runs at
all. A verified-identity reconnect that resumes the parked body re-mints its
admission templates through the ordinary `PeerAdmitted` event (below), so what
does not survive the gap is exactly a live acquisition beyond the templates.
The release rides `ApplyServerEvent`, the same door a replay re-drives the
recorded event through, so a re-drive reproduces it at the identical tick with
no separate tape entry. A checkpoint restore releases a restored park's rows
the same way, at `WorldServer.RestoreCheckpoint` itself — a restored parked
generation's connection did not survive the restore, so its rows and exclusive
reservations go before the first step. A local seat's park leaves its rows
entirely alone (the one participant whose table survives intact to a resume).
Proved by `tests/Puck.World.Server.Tests/ParkedGrantReleaseLawTests.cs`: a disconnect
releases an exclusively-held subject to a rival immediately (positive grace,
authored-zero grace, and rate 0 alike) while the body stays parked; a local
seat's rows survive park and resume — and the same restore untouched; a
restored park's rows go at the restore itself; a resume-shaped `PeerAdmitted`
event unparks the retained body and re-mints the fresh connection's rows.
Park state is **population state, not a mutation** — it carries no
`WorldMutation` ordinal and is never journaled. It IS replay-deterministic on its own
terms: `ParkedUntilTick` is a pure function of the tick the disconnect landed
on (itself replay-reproduced) plus the document-authored `reconnectGraceSeconds`,
so `ReclaimExpiredParks` fires identically on replay with no separate tape
entry, the same way `ReclaimExpiredEscrows`'s mutation-shaped reclaim needs
none.
## Body-resume (seats and verified peers)
A re-Join to a seat that `WorldPopulation.IsSeatParked` reports parked tries
`TryResumeParkedSeat` BEFORE falling back to `ActivateSeat`'s fresh-spawn path.
**The match rule:** the incoming `SessionRequest.Join.IdentityName`'s resolved
`WorldIdentity.Id` must equal the parked body's OWN retained
`WorldBody.Profile.Id` — read directly off the body the park never dropped, so
there is no separate "remembered identity" field to keep in sync. Both
`null` (an anonymous seat) counts as a match too. On a match: clears `Parked`,
leaves pose/durable state exactly as parked (no `ResetDurableState` — that
fires only on an ACTUAL id change, and this is the same id), and re-seats the
color if the caller resolved a different `WorldIdentity` object for the same
id (a profile reload between park and resume). On a mismatch: the parked body
is left completely untouched (so a later, correctly-identified re-Join can
still recover it before grace expires) and `WorldServer.ApplySession`'s `Join`
case refuses the request by name, distinct from an authority denial.
**Peer body-resume matches on the VERIFIED admission identity.** An ordinary
connect (never a transfer commit) whose door verdict's
(`identityDomain`, `identitySubject`) pair matches a parked peer resumes that
SAME retained body and generation in place
(`WorldPopulation.TryResumeParkedPeer`, called from
`WorldGrants.TryAdmitVerifiedParticipant`), then re-dispatches the ordinary
`PeerAdmitted` event carrying the fresh connection's minted admission
templates — which is also what unparks and re-mints a replayed resume
(`ApplyPeerAdmitted`'s generation-guarded unpark). An unverified or
non-matching reconnect claims a fresh slot via `TryAdmitRemotePeer`'s
`HighestFreeSlot`, which SKIPS a still-parked slot (its `Active` stays true)
without ever reusing it.
## The `$parked:<bodyRef>` reserved rule channel
`WorldRuleFacts.ParkedPrefix` (`WorldRuleFacts.cs`, alongside `$tick`/`$population`/
`$region:`/`$machine:`/`$reduce:`/`$argmax:`/`$argmin:`/`$distance:`/`$los:`).
`<bodyRef>` is the SAME single-body-reference grammar `$distance:`/`$los:`
spend one half of theirs on — `body:<n>` (a literal 0-based index) or
`argmax:<row>`/`argmin:<row>` (an entity-addressable extremum) — so it
composes with both directly in one `all` gate:
`$parked:argmax:threat >= 1` asks "is the highest-threat body currently
parked", and it can sit beside a `$distance:`/`$los:` conjunct naming the same
body reference. **Value semantics:** the remaining grace ticks
(`ParkedUntilTick - tick`, floored at 0) — NOT 1/0 — so a gate can also ask
"parked with less than N ticks of grace left" for a reconnect-policy rule.
A body that is not parked, or a reference that resolves to no live body at
all, reads `0` (the ordinary "absent/inapplicable reads as the neutral falsy
value" convention `$region:`/`$machine:` already set — NOT the inverted
`NoBodyDistance` sentinel (`WorldRuleHost`) `$distance:` uses, since `0` is the correct
"never gate open on a body that was never parked" answer here).
`WorldRuleHost.Read(ParkedOperand)` over `WorldPopulation.ParkedRemainingTicks` is
the runtime read; `WorldFactsCompiler`'s `ResolveOperand` is the compile-time
parse (`WorldRuleRefusal.ParkedChannelMalformed` on a bad spelling).
## Read-back: `world.parked`
`WorldPopulationCommandModule`'s `world.parked` (Immediate, no-arg) lists
every currently-parked entity: `body:<n> remaining=<ticks> deadline=<tick>
[profile=<name>] pos=(x, z) yaw=d°`. Empty when nothing is parked. This is the
`$parked:` channel's own read-back, and the cheapest way to prove a park
retained pose/state without fighting `body.where`'s `PlayerRoster.IsJoined`
gate (see the gotcha below).
## Authoring reconnect POLICY over the primitive — "everything else is rules"
Everything past park-with-grace/body-resume/`$parked:` above is an ordinary
authored `WorldRule` — no further engine surface exists or is needed.
Three rule shapes cover a reconnect policy: a CC countdown (`stunRemaining`, a plain
`Level`-mode decrement rule) keeps ticking through a park because rule
evaluation never consults occupancy (see "Park-with-grace" above); a
periodic-attack rule gated on `$argmax:threat` resolving to the PARKED body
proves a parked body stays a valid effect target through the whole grace
window; and a `$parked:body:<n>` threshold gate (`Edge` mode, paired with
its own clear-on-resume `Edge` rule) demonstrates a rule reacting to the
LIVE remaining-grace value, not just its parked/unparked boolean. Nothing
here is a new predicate, effect, or reserved channel — it is the SAME
substrate the quarantined arena district's targeting and attack rules
already exercise, aimed at `$parked:` instead of `$distance:`/`$argmax:`
alone. `reconnectGraceSeconds: 0` is the standing break-once control: the
SAME document with that one field zeroed tears the body down immediately on
`player.leave`, with `world.parked` staying empty the whole time — proving
the grace window (not merely the leave itself) is what the rules above ride.
## Verification gotchas specific to this primitive
- **`player.leave` clears the CLIENT roster slot regardless of server-side
park.** `PlayerRoster.Leave` sets `m_slots[slot] = null` unconditionally, so
`body.where <n>`/`body.channels <n>`/etc. (which gate on
`PlayerRoster.IsJoined`) report "not joined" for a parked seat even though
the SERVER still holds its body. Use `world.parked` to read a parked body's
pose/state; use `body.where` only AFTER a resuming re-Join (which
re-populates the client slot via `PlayerRoster.Fill`).
- **Player 1 (slot 0) never leaves** (`PlayerRoster.Leave` refuses `slot <= 0`)
— pick slot 2..4 for any leave/park/resume script.
- **No shipped world authors identities** — profiles come from the owned-worlds
catalog (`identity.create`, loaded at boot from `--state-dir`).
`player.join <profile> <slot>` refuses BY NAME
("profile '<x>' is already in use") the instant `<profile>` is active
ANYWHERE else — this fires regardless of park state, so testing a
MISMATCHED-identity resume needs an identity that is not currently active
elsewhere (free a second seat first, or add a spare identity to the
document).
- **Grace-expiry teardown is population-internal, not a mutation** — `world.status`'s
`dirty`/journal length does not move when `ReclaimExpiredParks` fires.
- Default `reconnectGraceSeconds` (3.0, which is 90 ticks at the unauthored 30 Hz) is small enough that `world.wait 91`
after a leave reliably crosses the deadline in a scripted verification run;
`world.wait <2` plus `world.parked` reads the remaining-ticks countdown
mid-window.
- A composed document may name a command a leaner boot shape (e.g. headless)
never registers. `WorldSeatBindings`'s recompose SKIPS a page (or a mixed
page's offending entries only, keeping its registered/resolvable rows)
whose commands are not in the registered vocabulary, keyed on
`WorldAffordances.IsCommandRegistered` (a registration FACT, never a
headless boolean) and narrated ONCE per skipped page instead of once per
entry. A genuine vocabulary mistake surviving the skip (bindability, value
kind) still rejects the whole recompose. Windowed boot registers every
command, so the skip predicate is always false there.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the work | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixes | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation code | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |