Guidance for AI coding agents working in this repository.
CLAUDE.md and GEMINI.md are symlinks to this file.
Node.js >=22.23.4 (engines in package.json; CI builds on Node 24). Yarn 4 via Corepack (corepack enable; the version is pinned in packageManager).
yarn- install dependenciesyarn start- dev server at localhost:3000yarn build- production build tobuild/yarn test- Jest (viareact-scripts) in watch modeCI=true yarn test- run tests once, no watchCI=true yarn test src/App.test.tsx -t "name"- single file / single testyarn serve- build and serve production locallyyarn preview- build and serve throughwrangler devyarn deploy- build and deploy to Cloudflare
There is no lint script: CRA's ESLint (react-app, react-app/jest) runs inside start and build.
src/utils/*.test.ts pass. src/App.test.tsx is the untouched CRA template and fails: Jest cannot resolve react-router-dom v7, and the assertion looks for "learn react" text that no longer exists. That one failure is not caused by your change.
The site is hosted on Cloudflare as a Worker with static assets (wrangler.jsonc): Worker aimaf, assets from build/, custom domain https://aimaf.flopbut.pl. The workers.dev address is disabled.
Every push to main builds and runs yarn wrangler deploy (.github/workflows/deploy.yml), which needs the CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID repository secrets. The build runs with DISABLE_ESLINT_PLUGIN=true, so lint errors do not block the deploy. yarn deploy does the same from a machine logged in with wrangler login.
The site lives at the domain root; the public path comes from homepage in package.json. Routing uses HashRouter, so no SPA fallback is configured for assets.
aimaf.mov is stored in Git LFS (.gitattributes).
Client-only React 19 SPA (Create React App, TypeScript) that runs a Mafia social deduction game between LLM players. There is no backend: the browser calls OpenRouter directly through the ai SDK and @openrouter/ai-sdk-provider.
Direct fetch calls to OpenRouter (in Settings) use OPENROUTER_API_BASE_URL from src/constants.ts; do not hardcode the URL.
Routes (src/App.tsx): / is Home (the game), /settings is Settings (API key, model list, prompt editing).
One hook owns all game state and is the only orchestrator; Home just wires its return value into components.
GameStateisInitial → Started → Ended.GamePhasecyclesWelcome → Night → Actions → Day → Voting → Night ….nextPhase()advances the phase and runs the matchingrunNight/runActions/runDay/runVoting. The first call (fromWelcome) also starts the game. Auto-play is an effect that callsnextPhase()one second afterisLoadingdrops.- Agents are called strictly sequentially.
messagesRefmirrors themessagesstate and is updated synchronously inaddMessage, so each agent sees what the previous one just said within the same phase run. Read history from the ref, not from state, inside phase runners. - The phase runners pass the phase to
callAgentInternalexplicitly (phaseOverride), because thegamePhasestate captured by the callback is still the old one when they run. ChatAgentinstances are mutated in place (agent.isDead = true) and thensetAgents([...agents])forces the re-render.- Agents exist only in memory; a page reload loses them and the game.
ChatAgent wraps a ToolLoopAgent from the ai SDK, one per player.
- Tools are registered by role (
killfor Mafia/Don,checkfor Detective,savefor Doctor,votefor everyone) and all take{ playerName }. Theirexecuteonly returns an acknowledgement string, or an error if the current phase does not allow the tool. The real effect happens inuseChat: tool calls are extracted from the result steps, passed tohandleToolCall, and queued inNightActions/DayActions. - A tool takes effect only in its phase (
TOOL_PHASESinutils/toolPhases.ts:kill/check/savein Actions,votein Voting). A call in any other phase gets an error from the tool, andgeneratedrops it from the returnedtoolCalls, so it reaches neither the game nor the log. - Message visibility is decided in
ChatAgent.convertMessages, which builds each agent's own view of the shared log:mafia: truemessages are visible only to Mafia/Don,pm: trueonly to the agent inagentId. The agent's own messages becomeassistantturns, everything else becomesuserturns prefixed with[SYSTEM]:,[MODERATOR]:or[@Name]:. Any new kind of secret information must be flagged withmafiaorpm, otherwise every player sees it. fixNamespost-processes model output: strips the agent's own name from the start and puts@before every player name.- Prompt caching:
generatemarks up to three cache breakpoints (providerOptions.openrouter.cacheControl): the system prompt, the last message of the history, and the message the history ended on at this agent's previous turn. It relies on each agent's view of the log being append-only, so anything that reorders or rewrites earlier messages inconvertMessagesbreaks the cache. Anthropic models cache only with these markers; providers with automatic caching ignore them. - Usage:
collectUsagesums OpenRouter's per-step usage (providerMetadata.openrouter.usage) intoUsageData; it travels on the message next toexecutionTimeand is rendered byMessageHeader. MafiaPromptsbuilds the system prompt asroot + generalRules + role prompt + optional per-agent instructions. Defaults live inDEFAULT_PROMPTS; amafia_promptsentry in localStorage overrides them entirely. The prompt is built once in theChatAgentconstructor, so prompt edits affect only agents created afterwards.
RoleIcondraws the role glyph on a round badge in the agent's color; it is shown before the name in agent cards and in message headers. Do not use emoji for roles or statuses.- Never use an agent's raw color for text.
utils/colors.tscomputes WCAG contrast:readableNameColordarkens a color until it reaches 4.5:1 on the darkest message background,inkOnpicks dark or light ink for content drawn on top of the color.colors.test.tschecks the whole form palette against every bubble background, so update it when adding colors or backgrounds.
When the game has ended the header shows an Export button. utils/exportGame.ts builds one JSON document (format: "aimaf-game", version: 1): game result, every agent with role, model and full system prompt, per-agent and total usage, and the complete message log with its mafia / pm visibility flags, tool calls, timing, usage and reasoning. Bump version when the shape changes. reasoning is filled only when the provider returns reasoning parts, which the app requests when the Reasoning toggle in Settings is on.
NightActions.processActions- the kill target is the one with the most kill actions, a matchingsavecancels the kill, and a Detective check reports mafia only for theMafiarole, so the Don reads as not mafia.DayActions.processVotes- one vote per voter (a later vote replaces the earlier one); a tie eliminates nobody.gameStatus.ts- win conditions: mafia wins when alive mafia >= alive non-mafia, civilians win when no mafia are alive. Not evaluated until someone has died.
The Doctor prompt says the same player cannot be saved two nights in a row, but the code does not enforce it.
The UI requires at least 5 agents before the game can start (Home.tsx); the expected setup is Mafia, Don, Detective, Doctor, Civilian.
openrouter_api_key- OpenRouter API keyselected_models- models offered in the agent creation formmafia_prompts- edited prompt templatesreasoning_enabled-'true'when models are asked to reason (reasoning: { effort: 'low' });ChatAgentrebuilds its model when the value changes
For development, .env.development.local (git-ignored, see .env.example) can hold REACT_APP_OPENROUTER_API_KEY and REACT_APP_DEV_MODELS; src/devSeed.ts copies them into empty localStorage under yarn start only. Never put the key in .env under a REACT_APP_ name: CRA would embed it in the production bundle.
The key names are duplicated as constants in the files that use them (useChat.ts, Settings.tsx, AgentForm.tsx, AgentPanel.tsx, MafiaPrompts.ts); renaming one means updating all of them.