Something went wrong. Try again.
A Social Deduction / Deception Game
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322// Case generation (PURE) — DEDUCTION.md §5. Assembles a full `DeductionCase` from a suspect pool://// 1. Pick the 3 incriminating fragments + culprit via `buildOverlapMystery` (the rule-of-3 lattice).// 2. Fill a quota of non-incriminating NOISE clues (a random source, one of THEIR own traits as the// fragment, owned when questioned). Pure red herrings — they always resolve because the source// owns up. Adding a noise source can over-match the incriminating fragments (common items like// Simple Pants), so each candidate is screened: if it would land in all 3 fakes we escalate one// fragment's granularity to exclude it (title → "red Basic T-Shirt"), or swap the source out.// 3. STACK clues onto stations by depth (this file's new job). Non-incriminating clues are ordered// MORE-SUSPECTS-FIRST and dealt round-robin so stations stay depth-balanced; each of 3 host// stations then gets one incriminating clue appended as its DEEPEST slot (so every fake is gated// behind ≥1 ordinary clue, and a station that can hold a fake is never just "working").//// The over-match invariant (§5) — the 3 incriminating match sets, recomputed over the WHOLE cast,// intersect to exactly {culprit} with ≤2 per innocent — is a hard guarantee, asserted by `verifyCase`.
import { buildOverlapMystery, tokensOf, verifyRuleOfThree } from './construct.js'import type { EvidencePiece, StationCondition, StationVerb } from './evidence.js'import type { SuspectAttributes } from './types.js'
/** A station the case can stack clues on (or leave clue-less). The interview/meeting hub is NOT a slot * — it can't be inspected (§3.5), so the caller excludes it. */export interface StationSlot { id: string resource: string verb: StationVerb}
/** What the generator needs to know about the map: the inspectable stations. (Debris is gone — every * clue now lives on a station, so we no longer need a separate pool of debris resources.) */export interface MapInfo { stations: StationSlot[]}
export interface GenerateOptions { /** Target number of non-incriminating noise clues. Auto-bumped to keep stations populated and to * guarantee ≥3 clues for the 3 incriminating fakes to gate behind. */ noise?: number /** How many suspects to try as the culprit in `buildOverlapMystery`. */ culpritTries?: number}
/** A station with its (ordered, shallow→deep) clue stack and its SERVER-ONLY true `condition`. An empty * `clues` is a plain working station. */export interface CaseStation { id: string resource: string verb: StationVerb /** SERVER-ONLY truth — never projected (see `StationCondition`). */ condition: StationCondition /** Clues by depth, shallow→deep: slot 0 found first, deepest (incriminating, if any) found last. */ clues: EvidencePiece[]}
/** * A generated case. `stations` holds every inspectable station with its clue stack (empty = clean). * `culpritDid` and `incriminatingClueIds` are SERVER-ONLY truth (the win check) — the player must * deduce them from the grid, never receive them. */export interface DeductionCase { suspects: SuspectAttributes[] stations: CaseStation[] /** SERVER-ONLY: the saboteur. */ culpritDid: string /** SERVER-ONLY: the ids of the 3 incriminating (fake) clues — the clues the endgame solve selects. */ incriminatingClueIds: string[]}
/** Every clue across every station, flattened (handy for callers reasoning over all clues). */export function allClues(c: DeductionCase): EvidencePiece[] { return c.stations.flatMap((s) => s.clues)}
const DEFAULT_NOISE = 5
function shuffle<T>(arr: T[], rng: () => number): T[] { const out = arr.slice() for (let i = out.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)) ;[out[i], out[j]] = [out[j]!, out[i]!] } return out}
function pick<T>(arr: T[], rng: () => number): T { return arr[Math.floor(rng() * arr.length)]!}
/** How specific a token is: `both` (item+colour) beats `title`/`colour`. Used to escalate fragments. */function specificity(token: string): number { return token.split('#')[1] === 'both' ? 2 : 1}
/** * Find a TIGHTER token of the culprit's same-category item that still matches everyone in `mustKeep` * but excludes `excludeDid` — so we can swap an over-matched fragment (e.g. "a Basic T-Shirt", worn by * a noise suspect too) for a more specific one ("a red Basic T-Shirt") without dropping the fake's * core witnesses below 2. Returns the new token, or null if no tightening separates them. */export function escalateFragment( fragment: string, culprit: SuspectAttributes, byDid: Map<string, SuspectAttributes>, mustKeep: string[], excludeDid: string,): string | null { const cat = fragment.split('#')[0]! const excludeToks = tokensOf(byDid.get(excludeDid)!) const candidates = [...tokensOf(culprit)] .filter((t) => t.startsWith(`${cat}#`) && t !== fragment && specificity(t) > specificity(fragment)) .sort((a, b) => specificity(b) - specificity(a)) for (const cand of candidates) { if (excludeToks.has(cand)) continue // doesn't separate them if (mustKeep.every((d) => tokensOf(byDid.get(d)!).has(cand))) return cand } return null}
/** A clue before it's bound to a station slot/depth — just its identity, fragment, source and role. */interface Proto { id: string fragment: string trueSource: string incriminating: boolean}
/** * Build a full case from `suspects`. Returns null if the pool is too sparse to support the rule-of-3 * lattice, can't supply ≥3 non-incriminating clues to gate the fakes, or the map has <3 inspectable * stations (one per incriminating clue). Deterministic given `rng`. */export function generateCase( suspects: SuspectAttributes[], map: MapInfo, rng: () => number, opts: GenerateOptions = {},): DeductionCase | null { const S = map.stations.length if (S < 3) return null // need one host station per incriminating clue (each fake is the deepest there)
const core = buildOverlapMystery(suspects, rng, { culpritTries: opts.culpritTries }) if (!core || !verifyRuleOfThree(core)) return null
const byDid = new Map(suspects.map((s) => [s.did, s])) const culprit = byDid.get(core.culpritDid)!
// Mutable across escalation. fragments[i] keeps core.matchSets[i] as its protected core witnesses. const fragments: [string, string, string] = [...core.fragments] const cast = new Map<string, SuspectAttributes>(core.lineup.map((d) => [d, byDid.get(d)!]))
// Non-incriminating clues needed: ≥3 (one to gate each of the 3 fakes). Beyond that, more just makes // for fuller stations — and it's fine to leave some stations clean (working), so we don't force a // floor proportional to the map size. const targetNoise = opts.noise ?? DEFAULT_NOISE const neededNoise = Math.max(targetNoise, 3)
// --- step 2: noise clues (random source owns one of their own traits) ----- const noise: Proto[] = [] const fakeMatches = (did: string) => fragments.every((f) => tokensOf(byDid.get(did)!).has(f)) for (const src of shuffle(suspects.filter((s) => !cast.has(s.did)), rng)) { if (noise.length >= neededNoise) break const own = [...tokensOf(src)] if (own.length === 0) continue
// Screen for over-match: a source matching all 3 fakes would become a false culprit in the // intersection. Try to escalate one fake's granularity to exclude it; otherwise skip this source. if (fakeMatches(src.did)) { let fixed = false for (let i = 0; i < 3 && !fixed; i++) { const tighter = escalateFragment(fragments[i]!, culprit, byDid, core.matchSets[i]!, src.did) if (tighter) { fragments[i] = tighter fixed = true } } if (!fixed) continue // swap the suspect out — can't separate them }
cast.set(src.did, src) noise.push({ id: '', fragment: pick(own, rng), trueSource: src.did, incriminating: false }) } if (noise.length < 3) return null // can't gate 3 incriminating clues behind ordinary ones
// --- assemble protos, compute match sets over the FINAL cast -------------- const castDids = [...cast.keys()] const matchSetOf = (frag: string) => castDids.filter((d) => tokensOf(byDid.get(d)!).has(frag))
const incriminating: Proto[] = fragments.map((f, i) => ({ id: `c-inc-${i}`, fragment: f, trueSource: culprit.did, incriminating: true, })) noise.forEach((p, i) => (p.id = `c-noise-${i}`))
// --- step 3: stack clues onto stations ----------------------------------- // Randomly, within hard limits: no stack deeper than MAX_DEPTH clues (avoid 4+), each fake the deepest // slot of a distinct host station, gated behind ≥1 ordinary clue (so a fake is never the first clue). // It's fine to leave stations clean (working). Assignment order is random — the more-suspects-first // ordering is imposed per-stack afterwards, so randomness here doesn't fight the ordering rule. const MAX_DEPTH = 3 const order = shuffle(map.stations, rng) const hosts = order.slice(0, 3) const hostIds = new Set(hosts.map((s) => s.id)) const buckets = new Map<string, Proto[]>(order.map((s) => [s.id, []])) // Ordinary-clue capacity per station: a host reserves one slot for its (later) incriminating clue. const cap = new Map<string, number>(order.map((s) => [s.id, MAX_DEPTH - (hostIds.has(s.id) ? 1 : 0)]))
const pool = shuffle(noise, rng) let i = 0 // Guarantee every host has ≥1 ordinary clue to gate its fake (pool has ≥3 — checked above). for (const h of hosts) { buckets.get(h.id)!.push(pool[i++]!) cap.set(h.id, cap.get(h.id)! - 1) } // Scatter the rest randomly across any station with capacity left; drop any overflow (rare). for (; i < pool.length; i++) { const avail = order.filter((s) => cap.get(s.id)! > 0) if (avail.length === 0) break const s = pick(avail, rng) buckets.get(s.id)!.push(pool[i]!) cap.set(s.id, cap.get(s.id)! - 1) } // Cap each host with its incriminating clue (becomes the deepest slot). hosts.forEach((h, k) => buckets.get(h.id)!.push(incriminating[k]!))
const stations: CaseStation[] = order.map((slot) => { // Order each stack: ordinary clues by DESCENDING suspect count, the incriminating fake always last. const stack = buckets.get(slot.id)!.slice().sort((a, b) => { if (a.incriminating !== b.incriminating) return a.incriminating ? 1 : -1 return matchSetOf(b.fragment).length - matchSetOf(a.fragment).length }) const condition: StationCondition = stack.length <= 1 ? 'working' : rng() < 0.5 ? 'broken' : 'sabotaged' const clues: EvidencePiece[] = stack.map((proto, depth) => ({ id: proto.id, fragment: proto.fragment, resource: slot.resource, verb: slot.verb, stationId: slot.id, depth, matchSet: matchSetOf(proto.fragment), trueSource: proto.trueSource, incriminating: proto.incriminating, condition, })) return { id: slot.id, resource: slot.resource, verb: slot.verb, condition, clues } })
return { suspects: castDids.map((d) => byDid.get(d)!), stations, culpritDid: culprit.did, incriminatingClueIds: incriminating.map((p) => p.id), }}
/** * Re-derive and assert every §5 invariant from a finished case (no hidden state): the hard over-match * check, plus the new stacking rules — fakes are the deepest clue of a non-working station, gated behind * ≥1 ordinary clue, and ordinary clues run more-suspects-first. Returns the violated invariants; empty * means valid. */export function verifyCase(c: DeductionCase): string[] { const reasons: string[] = [] const byDid = new Map(c.suspects.map((s) => [s.did, s])) const toks = (did: string) => (byDid.has(did) ? tokensOf(byDid.get(did)!) : new Set<string>()) const clues = allClues(c)
const inc = clues.filter((e) => e.incriminating) if (inc.length !== 3) reasons.push(`expected 3 incriminating clues, found ${inc.length}`) const incIds = new Set(inc.map((e) => e.id)) if (c.incriminatingClueIds.length !== incIds.size || c.incriminatingClueIds.some((id) => !incIds.has(id))) { reasons.push('incriminatingClueIds does not match the incriminating clues on the map') }
// Over-match invariant: ∩ of the 3 fake match sets = {culprit}; every innocent in ≤2. const counts = new Map<string, number>() for (const piece of inc) { if (piece.matchSet.length < 2) reasons.push(`fake ${piece.id} matches <2 suspects`) for (const d of piece.matchSet) counts.set(d, (counts.get(d) ?? 0) + 1) } const inAll3 = [...counts].filter(([, n]) => n === 3).map(([d]) => d) if (inAll3.length !== 1 || inAll3[0] !== c.culpritDid) { reasons.push(`intersection of fakes = {${inAll3.join(', ')}}, expected {${c.culpritDid}}`) } for (const [d, n] of counts) if (d !== c.culpritDid && n > 2) reasons.push(`innocent ${d} matches ${n} fakes (>2)`)
for (const st of c.stations) { st.clues.forEach((p, i) => { if (p.depth !== i) reasons.push(`clue ${p.id}: depth ${p.depth} ≠ slot index ${i}`) if (p.stationId !== st.id) reasons.push(`clue ${p.id}: stationId ${p.stationId} ≠ ${st.id}`) if (p.condition !== st.condition) reasons.push(`clue ${p.id}: condition ${p.condition} ≠ station ${st.condition}`) if (!toks(p.trueSource).has(p.fragment)) reasons.push(`clue ${p.id}: fragment not in true source's attire`) if (p.incriminating && p.trueSource !== c.culpritDid) reasons.push(`incriminating ${p.id} not sourced to culprit`) })
// Incriminating placement: ≤1 per station, the DEEPEST slot, gated behind ≥1 clue, never on working. const here = st.clues.filter((p) => p.incriminating) if (here.length > 1) reasons.push(`station ${st.id}: ${here.length} incriminating clues (max 1)`) if (here.length === 1) { if (!st.clues[st.clues.length - 1]!.incriminating) reasons.push(`station ${st.id}: incriminating clue is not the deepest`) if (st.clues.length < 2) reasons.push(`station ${st.id}: incriminating clue is not gated behind an ordinary clue`) if (st.condition === 'working') reasons.push(`station ${st.id}: a working station holds incriminating evidence`) }
// Depth cap: no stack deeper than 3 clues (avoid 4+). if (st.clues.length > 3) reasons.push(`station ${st.id}: ${st.clues.length} clues (max 3)`)
// Condition ↔ depth: ≤1 clue ⟹ working; 2+ ⟹ broken/sabotaged. if (st.clues.length <= 1 && st.condition !== 'working') reasons.push(`station ${st.id}: ≤1 clue but condition ${st.condition}`) if (st.clues.length >= 2 && st.condition === 'working') reasons.push(`station ${st.id}: ${st.clues.length} clues but working`)
// Ordinary clues run more-suspects-first (non-strict — ties allowed). const ord = st.clues.filter((p) => !p.incriminating) for (let i = 1; i < ord.length; i++) { if (ord[i]!.matchSet.length > ord[i - 1]!.matchSet.length) reasons.push(`station ${st.id}: clues not ordered by descending suspects`) } }
return reasons}