A Social Deduction / Deception Game
47 kB 733 lines
Markdown
at main

Sabotage Town — Build Plan #

Working title: Sabotage Town (spelling corrected throughout: sabotage, saboteur, sabotaged). The domain / repo stays deception.town; the in-game name is "Sabotage Town".

A real-time, hidden-role multiplayer game built on ATProto identity. Workers race to collect resources; one hidden saboteur tries to stop them. Closest cousins: Among Us (social deduction

  • meetings/voting) crossed with a co-op resource-collection sim.

1. Game design (canonical rules) #

1.1 Identity & entry #

  • Players sign in with their ATProto / Bluesky account (OAuth — already implemented).
  • On login we connect their actor.rpg.sprite/self record (already being read in Home.tsx) and use it to render their in-game character (48×48 sheet, same layout as rpg-actor.png).
  • Players enter a game via a 4-character alphanumeric join code (lobby → game room).

1.2 Roles #

  • 4–10 players per game. Exactly 1 saboteur; everyone else is a worker. Assigned at round start, hidden. (No multi-saboteur in v1; revisit if lobbies grow.)
  • Because there is always exactly one saboteur, the round cannot continue without them — see reconnect handling in §3.6.

1.3 Win conditions & the round #

  • A round lasts 10 minutes (configurable).

  • Workers must collect a target amount of each of N resources (N = 4 for the first game; configurable).

  • Saboteur must prevent the workers from hitting those targets.

  • At round end exactly one outcome resolves:

    1. Workers win — every resource met its target.
    2. Saboteur wins — targets NOT met and the saboteur was never caught (kicked).
    3. No one wins — targets NOT met but the saboteur was caught (kicked) earlier.
  • Voting never pauses the world. Time keeps running during a vote, so calling/attending a meeting has a real opportunity cost — workers who stop to vote aren't collecting. Voting is not free.

    Note: hitting the resource targets ends the round as a worker win regardless of whether the saboteur was caught. Catching the saboteur does not by itself win the round — workers still need the resources; catching only downgrades a saboteur win into "no one wins".

  • The saboteur's identity is always revealed on the end screen, every game.

  • Targets met on the same tick the clock reaches 0 → worker win (ties go to workers).

1.4 Map & stations #

  • One resource station per resource (4 to start).
  • The number of worker slots per station scales with player count (formula of player count — see §2). Slots = how many players can use that station concurrently.
  • Each station slot has its own cooldown between uses (cooldown is per-slot, NOT per-station).
  • Station state is per-station, not per-slot. Sabotaging or breaking a station applies to all of its slots at once — there is no "sabotage one slot." A 3-slot station that gets sabotaged is sabotaged for everyone.
  • Design intent (pacing): because state is station-wide and targets scale with players, it is NOT viable to swarm one resource to completion and then move on. Workers must divide and conquer across stations in parallel. Resource targets (§2) are tuned to enforce this.
  • Plus three special station types (below).

1.5 Resource station — states #

Each resource station is in one of three states:

State Visible on access? Allowed actions
Working yes all actions
Broken yes (obvious when accessed) repair only (collect & inspect disabled)
Sabotaged no — looks Working; only revealed by Inspect all actions, but collections may fail

State transition rules:

  • Sabotaged is armed with a hidden countdown: after some future number of collections the sabotage "triggers" and the station flips to Broken.
  • While sabotaged, every (real) collection rolls a die whose chance rises with both the number of collections since sabotage and the time elapsed since sabotage (expected trigger ~3–4 collections later). On a hit: the collection fails (no resource granted) and the station becomes Broken — but it still consumes the full Timer-1 duration.
  • Repairing a station always returns it to Working and clears any sabotage — even if the repairer never knew it was sabotaged.

Information rules (what Inspect does and doesn't tell you):

  • Inspect reveals only the fact that a station is Sabotaged — never the timing (how many collections in, or how close the trigger is). That countdown never leaves the server, even for someone who has inspected.
  • The saboteur has free knowledge of their own actions — they know which stations they sabotaged. They may still Inspect, but it only tells them what they already know; it's purely a way to look like a worker. (Other players learn a station is sabotaged only by inspecting.)
  • Repair tells you nothing about the past — only that the station is Working now. Repairing a Sabotaged station is indistinguishable from repairing a Working one (in both, you simply know the next collection will succeed). Broken is the exception — it's plainly visible (knowing it requires interacting, but that's free), so you do know when you've repaired a Broken station.
  • Fake/Pretend Collect never rolls the break die and never advances the sabotage counter — a saboteur can mime a collect for cover (a real repair is usually followed by a real collect) without risking tripping the trap they just set with Fake Repair.

1.6 Worker actions (at a resource station) #

  1. Do nothing — close the menu, no timer.
  2. Collect — Timer 1 — gain 1 of that resource to carry.
  3. Repair — Timer 2 — station → Working (clears broken/sabotaged).
  4. Inspect — Timer 3 — reveals the station's true state (working vs sabotaged).

1.7 Saboteur actions #

The saboteur has all 4 worker actions plus four extra:

  1. Pretend to Collect — Timer 1 — gain a fake resource to carry.
  2. Break immediately — Timer 1 — station → Broken.
  3. Fake Repair — Timer 2 — looks like a Repair but never clears sabotage:
    • on a Broken station → re-sabotages it (→ Sabotaged, with 1–3 collections of grace),
    • on a Sabotaged station → leaves the trap intact (mechanically a no-op) — offered as repair cover, since a real Repair would destroy the saboteur's own trap,
    • on a Working station → no-op, so it's omitted from the menu for clarity.
  4. Sabotage — Timer 3 — station → Sabotaged.

Action cover (the heart of the bluff). The game rests on a saboteur being able to claim a plausible worker activity — "I was just inspecting." Because the activity kind is hidden from observers (they see only the station, the timer duration, and the before/after state), every saboteur action mirrors a worker action at the same timer tier and produces an indistinguishable outside view:

Tier Worker activity Saboteur cover Why it's indistinguishable
T1 Collect Pretend Collect both end with you carrying a resource (fake looks real) — but only a real collect cools the slot, so it's not a perfect mirror (see the proof loop)
T1 Collect that hits the dice on a sabotaged station (→ Broken, no resource) Break immediately both: a Timer-1 action, station looks fine during, then Broken, no resource gained
T2 Repair (Broken → Working) Fake Repair on Broken both turn a Broken station into a working-looking one after Timer-2
T3 Inspect (no visible change) Sabotage both: a Timer-3 action that leaves the station still looking Working

So the saboteur always has a believable answer for what they were doing, and a worker can never tell a sabotage apart from an inspect, a break apart from an unlucky collect, etc., from the outside alone — only by watching patterns over time.

Slot cooldown supports this too. Cooldown is collect-only (only a real Collect depletes a slot; other activities ignore it) and secret — per-slot occupancy and collectCooldownUntil are never projected; which slot someone occupies is hidden. On interaction you're simply told whether you can collect: "Collect wood" or, when every slot is busy/regenerating, "No woods" (which never reveals busy vs cooling). The only knob is the cooldown duration (slotCooldownMs).

Pretend Collect is deliberately a weak, leaky cover. It requires a collectable slot (you can't fake a collect where a real one is impossible — that'd be a crude tell), but it does not consume the cooldown. Two consequences:

  • Low reward — it doesn't deplete the slot, so it never denies workers or slows them. The saboteur's real win condition is sabotage/breaking, not fake-collecting; collection targets are tuned to be reachable by the worker team even with some voting rounds and some repairs.
  • A tell — because a real collect cools the slot and a fake one doesn't, a careful observer who tracks a slot's availability can catch a fake collect (the slot stays collectable when a real one would read "No woods").

So real Collect is the strong cover for a saboteur (it survives the check and actually ties up a slot), at the modest price of helping the workers a little — exactly the kind of "sometimes play like a worker" pressure we want.

Proving a saboteur — costly, private, self-defeating. A single snapshot is perfect cover, but a suspicious player can prove to themselves that someone took a saboteur-only action by observing a station before and after the suspect acts:

  • Sabotage (Working → Sabotaged): Inspect first to confirm it's genuinely Working (not already secretly sabotaged), watch the suspect's Timer-3 action, then Inspect again. A Working→Sabotaged flip is only possible via Sabotage. Crucially your view goes stale after they act — a freshly sabotaged station still reads Working to you until you re-Inspect — so the second look is genuinely required.
  • Fake Repair (Broken → still Sabotaged): Broken is public, so "before" is free; after the "repair", Inspect — a real repair reads Working, a fake one reads Sabotaged.
  • Fake Collect: two tells. The slot it "collected" from never cools (a real collect would), so a careful observer can catch it; and the saboteur is left holding a fake — drop it and the debris Inspects as fake (evidence a worker's drop never leaves), its only clean disposal a pointless fake deposit. Being low-reward as well (no slot denial), it's rarely worth it over a real collect.

Three properties make this the heart of the game:

  1. Costly — each Inspect is a Timer-3 you're not spending collecting; before/after is two of them plus the attention to watch. You can't audit everyone.
  2. Private (he-said/she-said) — what you learn is per-viewer knowledge: a station you've caught as Sabotaged still reads Working to everyone who hasn't paid the same cost, and a vote never reveals roles. You can accuse, but you cannot show your proof.
  3. Self-defeating — the proof requires the saboteur to actually perform a fake while watched, so a saboteur who senses they're being watched is pushed to play honestly (really collect, really repair) to pass the before/after check. That pressure — not any extra accounting — is what stops fakes from being free, and the reason a saboteur sometimes behaves like a worker.

(Considered and not adopted: a per-player contribution audit, and a saboteur ability rate-limit — the costly/private/self-defeating observation loop above is preferred.)

Worked example — a viable saboteur arc. The mechanics are meant to compose into a narrative, not a checklist. One strong line of play:

  1. Early — damage + misdirect. Mix cheap Break immediately (Timer-1), Sabotage, and Fake Repair to do real damage and engineer the appearance that another player is the saboteur (be seen near stations that then fail; let the breaks land where a specific worker was).
  2. Frame & vote. Steer a meeting to vote off that innocent worker. The vote never reveals roles, so the room can't tell they got it wrong — and the workers have now lost a contributor.
  3. Go quiet & look clean. For a while, play for real — genuine Collect/Repair that pass any before/after Inspect. The sabotage "stops", so the group concludes the saboteur is gone and relaxes their watching (the proof loop is costly, so they stop paying for it).
  4. Coast on fakes. Once unwatched, Fake Collect / Fake Deposit the rest of the game: look busy, contribute nothing. The tells (uncooled slot, the fake you hold) don't matter when nobody is checking.

The arithmetic is the point, and it's a balance target: a full worker team should be able to hit the resource goals despite a couple of voting rounds and repairing some broken equipment — but losing one worker (the framed vote) + one permanent non-contributor (the saboteur) + the early sabotage damage should tip them into a loss. resourceTarget in balance() must be tuned to that knife-edge: comfortably reachable by N honest workers, not reachable by N−2 effective ones.

1.8 Carrying / depositing / dropping #

  • When a player is carrying a resource (real or fake) they can ONLY:
    1. Deposit it, or
    2. Drop it. (No other actions while carrying.)
  • Deposit station — Timer 1: a worker depositing a real resource adds +1 to that resource's collected total. A saboteur carrying a fake resource can fake deposit — it looks the same but does not count.
  • Drop: places debris on the map. Anyone can take a free action to inspect debris and learn whether it held a real or fake resource. Debris disappears after a timer and is not attributable to any player except by carefully watching positions.

1.9 Special stations #

  1. Deposit station(s) — see 1.8.
  2. Score board — one per level. Anyone may spend a Timer 3 action to read the current collected counts of all resources.
  3. Meeting square — one per level. Anyone may come here to instantly start a voting round to remove a player.

1.10 Voting #

  • A voting round has a timer.
  • Before the timer expires, a majority of players still in the game must agree on one player to kick.
  • If a majority is reached early, the vote ends early.
  • The kicked player's role is never revealed.
  • Kicked players become spectators (see Visibility).

1.11 Visibility / spectating #

The deduction in this game comes from watching behavior, not from fog of war. Almost everything observable about a player is public; the only truly hidden bits are authenticity (real vs fake) and roles.

  • Public information (server may share with anyone who can see that part of the map):
    • Every player's position and movement.
    • How long a player spends at a station (dwell time / that they're mid-action there).
    • What a player is carrying (that they hold a resource, and which resource type).
    • When and where a player drops something (the drop event + the debris location).
  • A live player's client normally only renders the area around their character — this is a rendering/UX choice, not an information restriction.
  • Spectators (kicked players, or non-players who joined to watch) can see everything by zooming out and panning the full board. Same underlying public data, no camera clamp.
  • Hidden information the server must NOT leak to anyone who hasn't earned it:
    • Who the saboteur is (roles, until/if revealed post-game).
    • A station's Sabotaged state — it renders as Working to everyone until someone Inspects it.
    • Whether a carried item is real or fake — you can see that someone carries a resource, not its authenticity.
    • The contents of debris (real vs fake) until someone Inspects that debris.

2. Timers, counters & tunables (placeholders — for balancing) #

All values are server-side constants in one config module so they're easy to tune.

TIMER_1 (collect / pretend / break / deposit) = ~2s
TIMER_2 (repair / fake repair)                = ~5s
TIMER_3 (inspect / sabotage / scoreboard)     = ~8s
SLOT_COOLDOWN                                  = ~3s
ROUND_DURATION                                 = 600s (configurable)
RESOURCE_COUNT (N)                             = 4
RESOURCE_TARGET(players)  = formula of player count — paces the round; tuned so swarming one
                            station is not viable (must divide & conquer). TBD curve.
SABOTAGE_DICE_RAMP   = collection k after sabotage fails with P(k); ~0,.15,.35,.6,1.0
FAKE_REPAIR_EXTRA_COLLECTIONS = 1–3
DEBRIS_TTL           = ~15s
VOTE_DURATION        = ~45s
SABOTEUR_GRACE       = 45s  — saboteur gone this long mid-round → round aborts (§3.6). Lives in
                            balance() as `saboteurGraceMs`; SERVER-ONLY (never projected — the
                            grace deadline would identify the saboteur).
STATION_SLOTS(players)    = formula of player count (concurrent users per station). TBD curve.
                            Cooldown is per-slot; sabotage/break state is per-station (all slots).
MIN_PLAYERS / MAX_PLAYERS = 4 / 10

3. Technical architecture #

3.1 Stack (existing) #

  • Client: Vite + React 18 + Tailwind 4; PixiJS 8 for the game canvas.
  • Server: Hono on @hono/node-server.
  • Identity: @atproto/oauth-client-browser + @atproto/api.
  • Map: Tiled (farm.tmx → farm.json + farm.png), already loaded by farm-test.ts.

3.2 Authority model #

Server-authoritative. All game logic (timers, dice, state transitions, voting, win checks) runs on the server. Clients send intents; the server validates, mutates state, and pushes per-player filtered snapshots/deltas. This is mandatory because the game has hidden state (saboteur identity, sabotaged stations, fake items, debris contents) that must never be sent to clients that shouldn't see it. Never trust the client for anything hidden.

3.3 Realtime transport #

  • WebSockets (add @hono/node-ws, or run a ws server alongside Hono).
  • Server game tick ~10–15 Hz drives timers, cooldowns, dice rolls, vote countdown, and the round clock.
  • Movement: server-authoritative positions (positions matter for debris attribution and social deduction). Given the slow pace, send client move intents and broadcast authoritative positions; light client-side interpolation for smoothness. Optional client prediction later.

3.4 Rooms / lobby #

  • A Room = one game keyed by its 4-char join code. Lifecycle: lobby → in-round → (voting overlay) → ended.
  • Room registry in server memory (single process) — an intended constraint, not a stopgap. Games are short and the authoritative GameState lives in process memory, so all sockets for a game must hit the same instance; OAuth sessions are likewise in-memory (oauth.ts, lost on restart). Scale-out (a shared session/room store + sticky routing) is out of scope. A room is disposed when it ends — once writeResults finishes the §8 fan-out the registry drops it (its tick loop, state, and event backlog are freed), and a deleted town.deception.game record observed on Jetstream tears its room down too.

3.5 Filtered views #

Core server responsibility: given the full authoritative state, produce a viewer-specific snapshot per recipient. The redaction surface is narrow (per §1.11): positions, dwell time, carried-resource type, and drop/debris locations are public to everyone. Only four things are redacted, and identically for live players and spectators alike:

  1. roles (saboteur identity),
  2. station Sabotaged flag → reported as Working until that viewer has Inspected it,
  3. carried-item authenticity (real/fake) → reported only as "carrying resource X",
  4. debris authenticity (real/fake) → until that viewer has Inspected that debris.

Note inspection results are per-viewer knowledge (who has learned a given station/debris is sabotaged/fake), so redaction is keyed on (viewer, target). Spectators don't automatically know authenticity either — they watch behavior like everyone else. Implement as a single projectStateFor(viewer) function so all redaction lives in one place.

Implemented as selectors.projectFor(state, viewer) with projectActionToWire(action, viewer) applying the identical redaction to streamed events. viewer === null is the non-logged-in spectator: they receive positions + movement, station dwell time (active.{stationId,startedAt, endsAt} with the activity kind hidden), what each player carries (resource type; authentic hidden), debris locations, and the live vote with every ballot (who is voting for whom) — and at phase === 'ended' the post-roundEnded snapshot reveals who won, who lost, and who the saboteur was. Exactly the watch-the-game surface; nothing role/authenticity-bearing leaks early.

3.6 Disconnect / reconnect #

  • Workers that disconnect → server holds their slot, role, position, and carried item; they resume as the same player on reconnect. Their avatar idles in place while gone (still collidable/visible — disappearing would leak info).
  • The saboteur disconnecting is special: the round can't continue without them, so start a grace timer. If they reconnect within it, resume as normal. If the grace timer expires, end the round (outcome: aborted — no win assigned; see §6).
    • Implemented. The reducer arms state.saboteurGraceEndsAt = now + saboteurGraceMs on the saboteur's playerDisconnected (round phase only) and clears it on their playerReconnected. pendingResolutions surfaces a grace item once it lapses; the server resolves it to roundEnded{ outcome: 'aborted' }. A kicked saboteur never triggers it (no disconnect fires for a non-alive player). The deadline is never projected — it would out the saboteur.
  • Reconnect = re-auth via existing OAuth session, re-bind socket to the same player by DID. A worker's disconnect just flips status to disconnected (slot/role/carry held); their avatar idles in place.

3.7 State as a reducer + event log (Redux-style) #

Model the authoritative game state as a single reducer over a stream of dispatched actions (events) — Redux / event-sourcing style. nextState = reduce(state, action). Every mutation — movement, action start/resolve, sabotage, deposit, drop, vote, kick, tick, round end — is an action object, and nothing mutates state except the reducer.

Why this pattern fits this game specifically:

  • The per-player action log is free. A thin logging middleware sees every dispatched action; tag each with the acting player's DID and you have the §8 action log as a byproduct, not a separate bookkeeping system to keep in sync.
  • Deterministic replay → trivial reconnect (replay log or ship a snapshot) and the signed end-of-round record can be derived from the event log.
  • Filtered views (§3.5) become pure selectors over state, keyed by viewer — no extra plumbing.
  • Testable: pure reducer + scripted action sequences = fast unit tests of the rules.

Determinism caveat — keep the reducer pure by baking side-effects into the action data:

  • Randomness can be truly random. Roll the dice outside the reducer (sabotage dice, role/spawn assignment) and record the result in the action itself. The reducer just applies the recorded outcome, so replaying the log reproduces the exact game — no seeded RNG needed.
  • Every action carries a serverTime. That timestamp is the authoritative clock; the reducer reads time from the action, never from the wall clock. This makes the log replayable to any point in time — fast-forward by feeding actions up to a target serverTime.
  • A tick action advances the current time (and resolves anything whose timer has elapsed: in-progress actions, slot cooldowns, debris TTL, vote/round expiry). Tick is the heartbeat that drives time-based transitions through the same reducer path as everything else.
  • Network sends, PDS writes, and the real timer loop live outside the reducer (middleware).

The per-player log captured this way (action start/resolve, deposits, drops, votes, kicks, role, outcome) is exactly the payload written to each player's PDS at round end (§8).


4. Data model (server, authoritative) #

Room
  code: string(4)            roundEndsAt, durationMs, config
  phase: 'lobby'|'round'|'ended'
  vote?: Vote                resources: ResourceTotals (collected + targets)
  players: Player[]          stations: Station[]
  debris: Debris[]

Player
  did, handle, spriteRef     role: 'worker'|'saboteur'
  status: 'alive'|'kicked'|'spectator'
  pos: {x,y}, facing         carrying: null | {kind:'real'|'fake', resourceId}
  activeAction?: {type, startedAt, endsAt, stationId, slot}

Station (resource)
  id, resourceId, pos        slots: Slot[] (occupancy + cooldownUntil)  // cooldown per-slot
  state: 'working'|'broken'|'sabotaged'   // station-wide: applies to ALL slots at once
  collectionsSinceSabotage   sabotageArmed: bool   fakeRepairExtra: int
  knownSabotagedBy: Set<did> // per-viewer: who has Inspected & learned it's sabotaged

SpecialStation: kind 'deposit'|'scoreboard'|'meeting'  (pos, slots)

Debris  id, pos, kind:'real'|'fake', resourceId, expiresAt, inspectedBy[]

Vote  startedAt, endsAt, tallies: Map<targetDid, voterDid[]>, eligibleVoters

State machines to implement explicitly: Room phase, Station state, per-player Action (idle → in-progress(timer) → resolved), Vote.


5. Wire format #

Two halves over one WebSocket, both ATProto-lexicon-defined and DAG-CBOR framed. Namespace: town.deception.*.

  • Downstream (server→client): an XRPC subscription — town.deception.subscribeGame. The authoritative, per-viewer event stream (snapshot + projected reducer actions). Standard ATProto subscription framing.
  • Upstream (client→server): a backchannel of intent frames — a standalone lexicon town.deception.clientFrame. XRPC subscriptions are read-only, so we carry client intents as our own framed messages up the same socket.

This is a 1:1 fit with the event-sourced core (§3.7): the subscription is the dispatched-action log, projected per viewer; the backchannel is the untrusted intent feed the server validates into actions. (Pattern proven on a prior project.)

5.1 Framing (both directions) #

Reuse ATProto subscription framing: each message = two concatenated DAG-CBOR objects —

  • header { op: 1, t: "#event" } — op:1 normal / op:-1 error (body {error, message}); t names the union member;
  • body — DAG-CBOR of that member.

Both directions share this header/body convention so there's a single codec.

5.2 Downstream — town.deception.subscribeGame (type: subscription) #

  • parameters (connect-time): code (4-char join code, required); cursor (last seq seen, optional — for resume).
  • message union:
    • #snapshot — full filtered RoomState for this viewer. Sent first on connect, or on resume when the client's cursor predates the server's retained backlog. { seq, serverTime, state }.
    • #event — one projected reducer action. { seq, serverTime, action }, where action is a redacted dispatched action (§3.5). Streamed continuously after the snapshot.
    • errors (op:-1): FutureCursor, GameNotFound, Unauthorized.
  • Per-viewer projection: the server runs projectStateFor(viewer) (§3.5) over both the snapshot and every event, so roles / sabotaged flags / authenticity never cross the wire to someone who hasn't earned it. Two viewers of the same game receive different #event payloads for the same underlying action.
  • Resume/reconnect: client reconnects with cursor=lastSeq; server replays missed #events, or falls back to a fresh #snapshot. Directly serves §3.6 reconnect and the §3.7 replayable log.
  • The action schema lives in a shared town.deception.defs lexicon (the reducer's action union), referenced here and reused server-side — one source of truth for the event shapes.

5.3 Upstream — town.deception.clientFrame (standalone lexicon) #

A union of intent frames. These are requests, not facts: the server validates each against authoritative state, then (and only then) dispatches a trusted, serverTime- and RNG-stamped action onto the stream. Named defs:

  • #join { code } — identity comes from the OAuth-bound session, not the frame.
  • #move { dir | vec }
  • #interact { stationId } — open a station.
  • #chooseAction { stationId, actionType } — collect/repair/inspect/sabotage/pretend/break/…
  • #cancelAction {}
  • #deposit {} · #drop {}
  • #inspectDebris { debrisId }
  • #startMeeting {} · #castVote { targetDid }
  • #setView { mode: 'follow' | 'free' } — only if the server needs to know; otherwise client-local.
  • #ping {} — heartbeat.

5.4 Trust boundary — intent → action #

Upstream frames are untrusted intents; downstream events are authoritative facts; the server is the only place they connect:

  • #chooseAction{collect} → validate (slot free, cooldown elapsed, station not broken, hands empty) → dispatch actionStarted{ did, stationId, slot, type, serverTime, endsAt } → on a later tick, dispatch actionResolved{ …, rngResult, granted } (RNG outcome recorded in the action, §3.7). The client never asserts success — it only ever observes the resolved event.
  • #castVote → voteCast{ voterDid, targetDid } (+ voteEnded if majority reached).
  • Illegal/stale intents → op:-1 error frame (or silent drop). They never mutate state.

5.5 Auth binding #

The socket is bound to the player's DID via their OAuth session at connect; #join carries only the game code. That DID is the same one that tags the action log (§3.7) and addresses the end-of-round PDS write (§8). Spectators connect subscription-only (no meaningful backchannel beyond #setView/#ping).

5.6 Lexicon files #

Author under lexicons/town/deception/: subscribeGame.json, clientFrame.json, defs.json (action union + shared object types), and game/result.json (§8). Codegen TS types from these so client, server reducer, and persistence all share one schema. Add this in Phase 1.


6. Build milestones #

Phase 0 — Repo hygiene (quick, do first)

  • Fix the 2 TypeScript errors in farm-test.ts:121/130 (PixiJS 8 AnimatedSprite rejects (Texture|undefined)[] — assert/guard the cycle() frames).
  • Use Node ≥20 (.nvmrc already pins 22; current shell is on 18).
  • Sweep root-level Tiled junk (Test.tsx, Town Buildings.tsx, buildings 48.tsx, buildings_bigger.tsx, crops.tsx, farm.tsx, untitled.tiled-*) — these are tileset XML, not source; the live map assets live in client/public/.
  • Make the initial git commit (currently 0 commits).

Phase 1 — Lobby, rooms & wire format

  • Author the town.deception.* lexicons (§5.6: subscribeGame, clientFrame, defs) + TS codegen shared by client/server. Stand up the WebSocket with the DAG-CBOR framing (§5.1), the subscription stream, and the intent backchannel.
  • Server room registry. Create/join by 4-char code. Lobby UI listing players (with ATProto handle
    • sprite). Host can start; role assignment (1 saboteur).
  • Scaffold the reducer + action union (§3.7) so the lobby itself already flows through dispatch → event → projected #event frames end to end.

Phase 2 — World & movement (multiplayer)

  • Reuse farm-test.ts walker. Replace single-player with server-authoritative positions for all players; render each player's actor.rpg.sprite. Camera follows local player; full-board toggle.

Phase 3 — Resource stations & the action loop

  • Place stations from the Tiled map (object layer). Station slots + cooldown. Implement the worker action menu and Timer-1/2/3 actions with server-driven progress. Carry/deposit/drop + debris. Resource totals. Filtered station state (sabotaged hidden).

Phase 4 — Saboteur & sabotage mechanics

  • Saboteur-only actions, fake resources/fake deposit, sabotage arming + increasing-chance dice on collect, fake repair, break. Verify redaction (workers never see sabotaged/fake/role).

Phase 5 — Special stations & voting

  • Scoreboard, meeting square → voting round (timer, majority, early-end, no role reveal), kicked → spectator.

Phase 6 — Win resolution & end screen

  • Round clock; evaluate the three outcomes (ties → workers); end screen always reveals the saboteur. Handle the void/aborted round (saboteur abandoned, §3.6).

Phase 7 — Spectators, reconnect, polish, balancing

  • Spectator zoom/pan omniscient view; disconnect/reconnect (§3.6, incl. saboteur grace timer); tune the §2 tunables (slot/target formulas, dice ramp); sound/feedback.

Phase 8 — Persistence & history (see §8)

  • Define town.deception.game.result lexicon; capture the per-player action log (§3.7); decide & implement the badges.blue-style signing/write path (confirm OAuth write scope); fan-out writes to each PDS at round end; client history view.

7. Open questions / decisions #

Resolved #

  1. Voting does not pause the world. Time keeps running; meetings have an opportunity cost. ✔

  2. Full-board view. Position, dwell time, carried-resource type, and drops are all public. Live clients just render the local area; spectators zoom/pan to see everything. Only authenticity (real/fake) and roles are hidden. (See §1.11.) ✔

  3. Station slots = formula of player count; cooldown per-slot, sabotage/break per-station (all slots). ✔

  4. Resource targets = formula of player count, tuned to force divide-and-conquer. ✔

  5. Player count = 4–10, always exactly 1 saboteur. No multi-saboteur in v1. ✔

  6. Reconnect: workers resume as the same player; saboteur disconnect → grace timer, then end the round (see §3.6). ✔

  7. Post-round persistence: record of each player's action log posted to their PDS. OAuth provides DID + write scope; the server signs the payload with its own key so the log is verifiable and unforgeable; user keeps the attested copy (see §8). ✔

  8. Role reveal: saboteur always revealed on the end screen. ✔

  9. Tie timing: targets met on the final tick → worker win (ties to workers). ✔

  10. Void-round outcome when the saboteur abandons (§3.6): write an aborted record. The round ends roundEnded{ outcome: 'aborted' } and the normal §8 fan-out runs — each player gets a signed result with outcome: 'aborted' and their own log. (Not "no record": the abandoned game is still part of a player's history.) ✔

  11. PDS write path (§8.3): server-side write. The backend holds each player's OAuth session and writes on their behalf (persist.ts). Overrides the earlier client-write lean — see oauth.ts and the build memory. ✔

  12. Public result vs. private log split. The outcome + roster + saboteur reveal are public — every viewer (players AND non-logged-in spectators) learns them from the live stream at game end (the post-roundEnded snapshot reveals roles/authenticity). The detailed action log is private: each player's signed PDS record carries only their own actions (playerLog), signed and written to their repo. So results are for everyone; the granular log is yours alone. ✔

Still open #

  1. Sabotage dice ramp exact curve, and whether fake-repair re-arms with its own short fuse. (Balancing — stays TBD until playtesting.)
  2. STATION_SLOTS(players) and RESOURCE_TARGET(players) curves — need concrete formulas (also balancing/playtesting).

8. Post-round persistence (signed action-log records) #

At the end of a (non-void) round, each player gets a per-player game record in their own PDS — badges.blue style. Two roles combine:

  • OAuth establishes the player's DID (unique identity) and grants PDS write scope, so a record can be placed in their repo.
  • The server signs the log payload with its own signing key before it's written. This attestation is the trust anchor: anyone can verify the game server issued the log, so a user can't forge or doctor their own history. The user keeps a copy; the signature proves it's real.

Each user thereby builds a verifiable personal history of the games they've played.

What's in each record (per player):

  • Game id, join code, timestamp, round config (resources/targets/duration).
  • That player's role (revealed post-game) and final status (alive/kicked/spectator).
  • Their action log from §3.7 — timestamped list of what they did.
  • The round outcome (worker / saboteur / no-one) and roster (DIDs/handles).

Design work this implies:

  1. A custom lexicon, e.g. town.deception.game.result (record schema for the above, including the embedded server signature + the key/identity used to sign). Define it before Phase 6.
  2. Server signing identity — the server holds its own signing key; at round end it canonically serializes each player's log payload and signs it, embedding the signature in the record so it's independently verifiable. (Implemented: signing.ts (secp256k1) + attestation.ts.)
    • Key type & how verifiers resolve the public key. The signer is a secp256k1 keypair whose did:key IS the public key (the bytes are embedded in the identifier). The attestation's key/issuer fields carry that did:key, so verifying a signature needs no external lookup at all — a verifier decodes the public key straight from key and checks the ECDSA signature over the recomputed CID. The badge.blue / CID-First spec confirms this: it only requires key be a public-key reference (e.g. did:key:z…) and says nothing about, and does not need, DID documents or published key records.
    • What you still need is a TRUST ANCHOR, not key publication. did:key proves a key signed the record; it doesn't prove that key is deception.town's. So publish which did:key is the official server signer somewhere clients can pin it. Recommendation: write a record to a PDS (your instinct) — e.g. a town.deception.signer record in the service's own repo (or a well-known service DID) listing the current + previously-rotated signer did:keys. Prefer this over a did:web/DID-document approach: it's atproto-native, needs no extra DNS/web infra, rotates by appending, and matches how clients already read records. (A did:web document would also work but is heavier and off the data plane.)
    • Make the key stable first. Today signing.ts mints an ephemeral key per process unless SABOTAGE_SIGNING_KEY (hex secp256k1 secret) is set. Set it in prod so the did:key is durable and worth pinning; only then is the signer record meaningful.
  3. OAuth write scope — login must request PDS write scope (not just identity), since the record goes into the player's repo. Confirm the requested OAuth scope on the existing login flow covers repo write. Remaining sub-choice: does the server perform the write (needs access to the user's session/tokens) or does the browser client perform the write with its own OAuth session using the server-signed payload? The latter fits the current browser-only OAuth setup with less token-handling; the former matches "the server writes it." Pick one.
  4. Write fan-out at round end — one com.atproto.repo.putRecord (or createRecord) per player; handle partial failures (a player's PDS down) without blocking others.
  5. History view — a client screen that lists a user's past game.result records.

This becomes its own milestone — Phase 8: Persistence & history (after Phase 6 win resolution; Phase 7 polish can run in parallel).


---

## 9. NPCs (set dressing)

NPCs — cows, townspeople, shipmates — are pure ambiance: **no gameplay effect**, no role in
collection, sabotage, detection, or the win check. They exist to make the world feel alive.

The whole architecture hinges on one question: **do they affect player A\* routing?** Decision:
**NPCs are non-colliding** — they never alter the nav grid or how players path. That keeps them
entirely out of the authoritative engine and off the wire:

- **Per-client, not server-authoritative.** Each client animates its own NPCs from the map. If
  they drift apart between viewers it doesn't matter — they're decoration. *(This is only
  acceptable because they don't change routing — see the escalation rule.)*
- **Off the engine / off the wire.** NPCs are never actions, never in `GameState`, never projected.
  Zero bandwidth.
- **Placed as map markers, typed by a scenario catalog.** `tilemap.world`'s `markerNode` is built
  for this; tag a marker with `town.deception.npc` = a *type key* (`cow | townsperson | shipmate`),
  optionally `town.deception.npcWander` to override its leash radius. The type's **sprites and
  behaviour live in the scenario, not on the marker** — a `town.deception.npcs` record bound via
  `scenario.npcs` maps each key to a **distribution of `actor.rpg.sprite` URIs** (the client picks
  one per placed NPC, seeded by the marker, so a herd isn't uniform) plus its tunables (wander
  radius, speed, idle/spin/wander weights, idle/spin durations, yield radius, on-map size). The
  `npcsUri` rides the same server→client rails as `resourcesUri`; the client resolves everything
  (see `client/src/npc-import.ts`), and the engine never sees any of it.

**Behavior** (simple, tunable per NPC for "character"):
- States: **move → wait → emote**, on randomized timers.
- Tunables: wander radius / leash to its marker, move speed, idle min–max, emote set + frequency.
- **Yield to players** — an NPC near a player drifts aside, so you rarely see overlap. Cosmetic and
  one-directional: NPCs avoid players; **players never route around NPCs** (authoritative nav is
  untouched), so no authority is needed.
- NPCs may consult the client's nav grid only to avoid wandering into walls *themselves* — never to
  influence player movement.

**Interactions** (all **client-local**, instant, cosmetic — consistent with per-client NPCs):
- **Ambient** — random emoji in a bubble on a timer.
- **Proximity** — emote when a player passes (a townsperson waves 👋).
- **Player-initiated** — an affordance (e.g. tap the NPC when nearby) for a canned emoji response: a
  personal RPG-villager moment, seen only by the initiating player. It is **not** broadcast and has
  **no cover value** (others don't observe it), so it stays free of gameplay and netcode.

**Escalation rule (per the sync decision).** The day NPCs become **collidable obstacles that change
player A\* routing** — or otherwise touch gameplay — they stop being set dressing and must move to
**server-authoritative** simulation over a shared, *dynamic* nav grid, so routing is identical and
fair for everyone (and player-initiated emotes others should see would then need a sliver of shared
state). We deliberately keep NPCs non-colliding to stay in the cheap per-client regime.

---

## 10. Lobby & game declaration

A game is declared by a **`town.deception.game`** record written to a PDS (lexicon:
`lexicons/town/deception/game.json`). It fixes the **roster (DIDs)** and the round settings
(`roundDurationSec`, `resourceCount`, optional `map` AT-URI and human `code`). The game is
identified by that record's **AT-URI**.

**Access model** (the record is the source of truth; the wire layer enforces it):
- **Subscribe = open.** Anyone may subscribe to a game's live state by AT-URI, **without
  authenticating** — players, kicked players, and pure spectators alike.
- **Push = roster only.** Only the DIDs listed in `players` may push state up; a pusher proves its
  DID (ATProto auth) and is checked with `isPlayer(decl, did)`.
- **Roles are never in the record.** The saboteur is secret; the record only fixes *who may play*.

**Grace period & start (engine/lobby.ts, pure).** The game opens for a **grace period** before
everyone has joined — a live warmup world players can walk around in:
- `createLobby(...)` emits `gameCreated` (phase `lobby`) sized from the **roster** so the world
  exists immediately. Players connect over the grace window via `joinAction` (`playerJoined`).
- During grace players can **move** (movement isn't gated by phase), but **station activities are
  blocked** — the API layer rejects them with `not-in-round`. So the grace world is movement-only.
- `closeLobby(...)` ends grace: it **picks the saboteur from the players who actually connected**
  (`pickSaboteur` over the connected set, recorded RNG) and emits `roundStarted`, which **finalizes
  balance for the participant count** (its optional `config` replaces the roster-sized one).
- **Grace ends on an explicit host action, not a timer.** The host sends a `#start` intent; the
  server runs `closeLobby` (`Room.start`). There is deliberately **no automatic grace-expiry
  timer** that starts the round on its own — the host decides when everyone's ready. (If a timed
  auto-start is wanted later, schedule a `closeLobby` from the tick loop; the engine already
  supports it.)
- **Void rules** (`evaluateStart`): the only at-start void is **fewer than `MIN_PLAYERS` (4)
  connected** → `void: not-enough-players`. Picking the saboteur *after* grace means there is **no
  "saboteur absent" void** — the saboteur is always someone present. (The sole saboteur-
  disappearance path is the in-round abandon of §3.6, which ends the round as `aborted`.)
- `startGame(...)` remains a convenience for an instant, no-grace start (gameCreated → joins →
  roundStarted in one shot), also drawing the saboteur from the connected set.

**Wire requirement (deferred):** `roundStarted` carries the full roles map, so the streamed `#event`
for it **must be redacted per-viewer** — each player learns only their own role (others stay hidden
until game end, per §3.5).