Something went wrong. Try again.
A Social Deduction / Deception Game
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214// PDS writes (PLAN §8, server-write path). The server holds each player's OAuth session and writes// records on their behalf:// • writeGameDeclaration — the host's town.deception.game record (the canonical game id);// • writeResults — one signed town.deception.game.result per player at round end.// Results are signed by the server's own key (badge.blue inline attestation, bound to the player's// repo) so a player can't forge or doctor their own history.
import type { Agent } from '@atproto/api'import type { Action } from '../../engine/actions.js'import type { Did } from '../../engine/types.js'import { getSigner } from './signing.js'import { inlineSign } from './attestation.js'import { agentForDid, hasSession } from './oauth.js'import { SPRITE_NSID, getSpriteRecord, fetchBlob, invalidateSprite } from './atproto.js'import type { Room, LogEntry } from './rooms.js'import type { GameDeclaration } from '../../engine/lobby.js'
const GAME_NSID = 'town.deception.game'const RESULT_NSID = 'town.deception.game.result'
// The deduction win record (DEDUCTION.md). A single self-keyed actor.rpg.stat per player tallies// wins across all deduction games; the rkey scopes it to this mode within the town namespace.const STAT_NSID = 'actor.rpg.stat'const DEDUCTION_STAT_RKEY = 'deception.town'
/** * Tally a deduction win in the player's own repo. Read their actor.rpg.stat/deception.town record, * increment `wins`, write it back (putRecord — there's exactly one stat record, so we overwrite it). * Best-effort: a player who never authed through us has no session and just gets no stat. A missing * record (first win) starts the count at 0. */export async function recordDeductionWin(did: Did): Promise<void> { if (!(await hasSession(did))) return try { const agent = await agentForDid(did) let wins = 0 try { const res = await agent.com.atproto.repo.getRecord({ repo: did, collection: STAT_NSID, rkey: DEDUCTION_STAT_RKEY }) const cur = (res.data.value as { wins?: unknown }).wins if (typeof cur === 'number' && Number.isFinite(cur)) wins = cur } catch { /* no existing stat — first win, count from 0 */ } const record = { $type: STAT_NSID, wins: wins + 1 } await agent.com.atproto.repo.putRecord({ repo: did, collection: STAT_NSID, rkey: DEDUCTION_STAT_RKEY, record }) } catch (err) { console.warn(`[persist] deduction win write failed for ${did}:`, err instanceof Error ? err.message : err) }}
/** A blob reference as it appears in / is written back to a record's JSON. */interface BlobRef { $type?: 'blob' ref?: { $link?: string } mimeType?: string}
/** * Clone the default actor (sourceDid's actor.rpg.sprite/self) into `did`'s repo as their own * self-keyed sprite. A blob can't be referenced across repos, so we re-upload the sheet: read the * source record, pull its spriteSheet blob from the source PDS, upload those bytes to the player's PDS * (yielding a fresh blob ref bound to their repo), then putRecord the cloned record with that ref. * Returns the new record's AT-URI. putRecord (not createRecord) so re-running just overwrites `self`. */export async function copyDefaultSprite(agent: Agent, did: Did, sourceDid: Did): Promise<string> { const source = await getSpriteRecord(sourceDid) if (!source) throw new Error(`default sprite source ${sourceDid} has no ${SPRITE_NSID}/self record`) const sheet = source.spriteSheet as BlobRef | undefined const cid = sheet?.ref?.$link if (!cid) throw new Error(`default sprite source ${sourceDid} has no spriteSheet blob`)
const bytes = await fetchBlob(sourceDid, cid) const upload = await agent.com.atproto.repo.uploadBlob(bytes, { encoding: sheet?.mimeType || 'image/png', })
// Clone every field of the source record, swapping in the freshly-uploaded (repo-local) blob. const record: Record<string, unknown> = { ...source, $type: SPRITE_NSID, spriteSheet: upload.data.blob } const res = await agent.com.atproto.repo.putRecord({ repo: did, collection: SPRITE_NSID, rkey: 'self', record, }) invalidateSprite(did) return res.data.uri}
/** Write the host's town.deception.game record; returns its AT-URI (the canonical game id). */export async function writeGameDeclaration( agent: Agent, hostDid: Did, decl: GameDeclaration,): Promise<string> { const record: Record<string, unknown> = { $type: GAME_NSID, players: decl.players, roundDurationSec: decl.roundDurationSec, resourceCount: decl.resourceCount, createdAt: new Date().toISOString(), } if (decl.code) record.code = decl.code // decl.mapUri is the game's world.tilemap.map (station markers carry resource AT-URIs directly). if (decl.mapUri) record.map = decl.mapUri const res = await agent.com.atproto.repo.createRecord({ repo: hostDid, collection: GAME_NSID, record }) return res.data.uri}
/** * Build, sign, and write each connected player's result to their own PDS. Best-effort and * independent: one player's PDS being down (or that player never having authed through us) doesn't * block the others. */export async function writeResults(room: Room): Promise<void> { if (!room.gameUri) { console.warn(`[persist] room ${room.code} ended without a game AT-URI; skipping result writes`) return } const signer = await getSigner() const createdAt = new Date().toISOString() const state = room.state const outcome = state.outcome ?? 'aborted' const roster = room.decl.players.map((did) => { const handle = state.players[did]?.handle return handle ? { did, handle } : { did } }) const config = { resourceCount: room.decl.resourceCount, roundDurationSec: room.decl.roundDurationSec, targets: Object.entries(state.config.targets).map(([resourceId, target]) => ({ resourceId, target })), }
await Promise.allSettled( Object.values(state.players).map(async (player) => { // Only players who authed through us have a session we can write with. if (!(await hasSession(player.did))) return const role = player.role if (!role) return // never assigned (round voided before start) — nothing to attest
const payload: Record<string, unknown> = { $type: RESULT_NSID, game: room.gameUri, role, status: player.status, outcome, roster, config, actions: playerLog(room.entries(), player.did), createdAt, } if (room.code) payload.code = room.code
// Sign the payload bound to THIS player's repo, then embed the attestation. const entry = await inlineSign(payload, player.did, signer, createdAt) const record = { ...payload, signatures: [entry] }
try { const agent = await agentForDid(player.did) await agent.com.atproto.repo.createRecord({ repo: player.did, collection: RESULT_NSID, record }) } catch (err) { console.warn(`[persist] result write failed for ${player.did}:`, err instanceof Error ? err.message : err) } }), )}
/** Project the global action log down to what one player did, in the result's logEntry shape. */function playerLog(entries: readonly LogEntry[], did: Did): Array<Record<string, unknown>> { const out: Array<Record<string, unknown>> = [] for (const e of entries) { const a = e.action const mine = attributableTo(a, did) if (!mine) continue const item: Record<string, unknown> = { serverTime: e.serverTime, type: a.type } if ('stationId' in a && a.stationId) item.station = a.stationId const detail = detailOf(a) if (detail) item.detail = detail out.push(item) } return out}
/** Whether an action is part of `did`'s personal log (things they did / that resolved for them). */function attributableTo(a: Action, did: Did): boolean { switch (a.type) { case 'playerJoined': case 'actionStarted': case 'actionCancelled': case 'actionResolved': case 'itemDropped': case 'debrisInspected': return a.did === did case 'voteCast': return a.voterDid === did default: return false // movement, ticks, and global resolutions aren't part of a personal log }}
function detailOf(a: Action): string | null { switch (a.type) { case 'actionStarted': return a.kind case 'actionResolved': return a.rng?.sabotageTriggered ? 'sabotage-triggered' : null case 'voteCast': return a.targetDid case 'debrisInspected': return a.debrisId default: return null }}