Refactor action handling and update UI elements
Browse files- Changed action "strike" to "attack" in tick.py and updated related validation logic.
- Updated UI text in card_observe.html to reflect new features and improved descriptions.
- Modified e2e tests to check for visibility of updated UI elements.
- Adjusted action hints in test_action_pipeline.py to include "attack" instead of "strike".
- Removed deprecated health URL in test_api_server.py.
- Added new tests for country systems in test_country_systems.py to ensure proper functionality of two-country demo.
- Updated gradio app tests to reflect changes in error handling.
- Increased NPC count in living village smoke test to 16.
- Cleaned up observability perception tests by removing unused overseer context checks.
- Updated OpenAI connector tests to use "attack" instead of "strike" in tool calls.
- Adjusted player MCP tests to use "use" actions instead of deprecated actions like "build" and "gather".
- Refined survival loop tests to ensure LLM sees all public primitive tools and removed role gating for survival tools.
Files changed (50)
- config/game.llm.local.json+1-1
- config/game.local.json+1-1
- config/game.modal.a10.local.json+1-1
- config/game.modal.b200.local.json+1-1
- config/game.modal.local.json+1-1
- config/game.modal.t4.local.json+1-1
- config/model_profiles.jsonAdded+14
- frontend/src/App.tsx-23
- frontend/src/api.ts-51
- frontend/src/components/AgentPanel.tsx+4-8
- frontend/src/components/ChaosDock.tsxDeleted-107
- frontend/src/components/GameOverOverlay.tsx+30-30
- frontend/src/components/OverseerPanel.tsxDeleted-77
- frontend/src/components/ScoreboardHeader.tsx+67-41
- frontend/src/components/SimulationControls.tsx+1-7
- frontend/src/components/modelStatus.ts+1-1
- frontend/src/eventDecor.ts+30-23
- frontend/src/hooks/useWorldSimulation.ts+5-154
- frontend/src/scene/NpcLabelButton.tsx+8-5
- frontend/src/scene/WorldView.tsx+56-1
- frontend/src/styles.css+98-311
- frontend/src/types.ts+49-29
- goal.mdAdded+783
- scripts/headless_sim.py+4-4
- scripts/selfplay_sim.pyAdded+299
- src/god_simulator/api/gradio_app.py+86-27
- src/god_simulator/api/mcp_server.py+53-33
- src/god_simulator/api/players.py+76-15
- src/god_simulator/api/public_ui.py+93-4
- src/god_simulator/api/runtime.py+268-182
- src/god_simulator/api/server.py+4-35
- src/god_simulator/domain.py+47
- src/god_simulator/observability.py+3-1
- src/god_simulator/rendering/scene_contract.py+52-13
- src/god_simulator/simulation/actions/builtin.py+6-14
- src/god_simulator/simulation/actions/hints.py+11-11
- src/god_simulator/simulation/autopilot.py+1-1
- src/god_simulator/simulation/connectors/base.py+9-2
- src/god_simulator/simulation/connectors/openai_compatible.py+251-113
- src/god_simulator/simulation/connectors/routing.py+19-1
- src/god_simulator/simulation/spawning.py+86-55
- src/god_simulator/simulation/survival.py+627-60
- src/god_simulator/simulation/tick.py+26-10
- src/god_simulator/ui/card_observe.html+5-5
- tests/e2e/god-simulator-scene.spec.ts+1-1
- tests/test_action_pipeline.py+1-1
- tests/test_api_server.py-1
- tests/test_country_systems.pyAdded+267
- tests/test_gradio_app.py+1-2
- tests/test_living_village_smoke.py+1-1
6 unmodified lines789101112136 unmodified lines"survival": true},"npcs": {"count": 0},"simulation": {"tick_ms": 5006 unmodified lines789101112136 unmodified lines"survival": true},"npcs": {"count": 6},"simulation": {"tick_ms": 500
6 unmodified lines789101112136 unmodified lines"survival": true},"npcs": {"count": 0},"simulation": {"tick_ms": 5006 unmodified lines789101112136 unmodified lines"survival": true},"npcs": {"count": 6},"simulation": {"tick_ms": 500
6 unmodified lines789101112136 unmodified lines"survival": true},"npcs": {"count": 0},"simulation": {"tick_ms": 5006 unmodified lines789101112136 unmodified lines"survival": true},"npcs": {"count": 6},"simulation": {"tick_ms": 500
6 unmodified lines789101112136 unmodified lines"survival": true},"npcs": {"count": 0},"simulation": {"tick_ms": 5006 unmodified lines789101112136 unmodified lines"survival": true},"npcs": {"count": 6},"simulation": {"tick_ms": 500
6 unmodified lines789101112136 unmodified lines"survival": true},"npcs": {"count": 0},"simulation": {"tick_ms": 5006 unmodified lines789101112136 unmodified lines"survival": true},"npcs": {"count": 6},"simulation": {"tick_ms": 500
6 unmodified lines789101112136 unmodified lines"survival": true},"npcs": {"count": 0},"simulation": {"tick_ms": 5006 unmodified lines789101112136 unmodified lines"survival": true},"npcs": {"count": 6},"simulation": {"tick_ms": 500
1234567891011121314{ "profiles": [ { "id": "default", "label": "Default NPC model", "connector_id": null }, { "id": "qwen", "label": "Qwen country connector", "connector_id": "qwen" } ]}1234567814 unmodified lines2324252627282930313233343536373839404 unmodified lines4546474849505152535455565758596061626364656667import { AgentPanel } from "./components/AgentPanel";import { ChaosDock } from "./components/ChaosDock";import { EventFeedPanel } from "./components/EventFeedPanel";import { GameOverOverlay } from "./components/GameOverOverlay";import { OverseerPanel } from "./components/OverseerPanel";import { ScoreboardHeader } from "./components/ScoreboardHeader";import { SimulationControls } from "./components/SimulationControls";import { StatusToasts } from "./components/StatusToasts";14 unmodified lines<ScoreboardHeadersnapshot={simulation.snapshot}isGodPending={simulation.isGodPending}isWaitingForTick={simulation.isWaitingForTick}/><OverseerPanel snapshot={simulation.snapshot} log={simulation.overseerLog} /><EventFeedPanel events={simulation.eventHistory} /><SimulationControlshasSnapshot={simulation.snapshot !== null}isAutoTicking={simulation.isAutoTicking}isGodPending={simulation.isGodPending}isWaitingForTick={simulation.isWaitingForTick}isWorldCommandPending={simulation.isWorldCommandPending}onStep={() => {4 unmodified lines}}/><ChaosDocksnapshot={simulation.snapshot}pendingChaosAction={simulation.pendingChaosAction}chaosMessage={simulation.chaosMessage}godCommand={simulation.godCommand}godMessage={simulation.godMessage}isGodPending={simulation.isGodPending}isWaitingForTick={simulation.isWaitingForTick}onChaosAction={(action) => {void simulation.runChaosAction(action);}}onCommandChange={simulation.setGodCommand}onSubmitCommand={(event) => {void simulation.runGodCommand(event);}}/><AgentPanelentity={simulation.selectedEntity}beast={simulation.selectedBeast}12345614 unmodified lines21222324252627282930313233344 unmodified lines394041424344import { AgentPanel } from "./components/AgentPanel";import { EventFeedPanel } from "./components/EventFeedPanel";import { GameOverOverlay } from "./components/GameOverOverlay";import { ScoreboardHeader } from "./components/ScoreboardHeader";import { SimulationControls } from "./components/SimulationControls";import { StatusToasts } from "./components/StatusToasts";14 unmodified lines<ScoreboardHeadersnapshot={simulation.snapshot}isWaitingForTick={simulation.isWaitingForTick}/><EventFeedPanel events={simulation.eventHistory} /><SimulationControlshasSnapshot={simulation.snapshot !== null}isAutoTicking={simulation.isAutoTicking}isWaitingForTick={simulation.isWaitingForTick}isWorldCommandPending={simulation.isWorldCommandPending}onStep={() => {4 unmodified lines}}/><AgentPanelentity={simulation.selectedEntity}beast={simulation.selectedBeast}
40 unmodified lines41424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939440 unmodified linesthrow new ApiResponseError(`World tick failed: ${response.status}`, response.status);}}export type GodCommandResult = {source?: string;queued?: boolean;applies_on_tick?: number;summary: string;applied: string[];snapshot?: WorldSnapshot;};export async function sendGodCommand(command: string): Promise<GodCommandResult> {const response = await fetch(`${API_BASE}/god-command`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ command }),});if (!response.ok) {throw new ApiResponseError(`God command failed: ${response.status}`, response.status);}return (await response.json()) as GodCommandResult;}export type ChaosActionResult = {action: string;queued?: boolean;applies_on_tick?: number;applied: string[];summary: string;snapshot?: WorldSnapshot;};export async function sendChaosAction(action: string): Promise<ChaosActionResult> {const response = await fetch(`${API_BASE}/chaos`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ action }),});if (!response.ok) {let message = `Chaos action failed: ${response.status}`;try {const body = (await response.json()) as { message?: string };if (body.message) {message = body.message;}} catch {// keep the generic message}throw new ApiResponseError(message, response.status);}return (await response.json()) as ChaosActionResult;}40 unmodified lines41424340 unmodified linesthrow new ApiResponseError(`World tick failed: ${response.status}`, response.status);}}
33 unmodified lines34353637383940147 unmodified lines18818919019119219319419519619719819915 unmodified lines21521621721821922022133 unmodified lines}const selectedName = entity?.label ?? "No NPC";const selectedRole = entity?.role ?? "world";return (<aside className="agentPanel" aria-label="Selected NPC">147 unmodified lines<><AgentReadout entity={entity} /><SurvivalReadout entity={entity} />{entity.state.god_directive ? (<div className="directiveBanner"><span>Directive</span><p>{entity.state.god_directive}</p></div>) : null}<RelationshipList entity={entity} /><MemoryList entity={entity} /></>15 unmodified lines}const inventoryLabel = inventory? `food ${inventory.food} / herbs ${inventory.herbs} / wood ${inventory.wood} / wpn ${inventory.weapon}`: "-";return (33 unmodified lines343536373839404142147 unmodified lines19019119219319419515 unmodified lines21121221321421521621733 unmodified lines}const selectedName = entity?.label ?? "No NPC";const selectedRole = entity? [entity.country_id, entity.special_status ?? entity.role].filter(Boolean).join(" / "): "world";return (<aside className="agentPanel" aria-label="Selected NPC">147 unmodified lines<><AgentReadout entity={entity} /><SurvivalReadout entity={entity} /><RelationshipList entity={entity} /><MemoryList entity={entity} /></>15 unmodified lines}const inventoryLabel = inventory? `food ${inventory.food} / herbs ${inventory.herbs} / wood ${inventory.wood} / coins ${inventory.coins} / wpn ${inventory.weapon}`: "-";return (
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107import { LoaderCircle, Send } from "lucide-react";import type { FormEvent } from "react";
import type { ChaosToolSnapshot, WorldSnapshot } from "../types";
const CHAOS_ICONS: Record<string, string> = { spawn_beast: "🐺", beast_pack: "🐺×3", famine: "🌾", maniac: "🔪",};
const FALLBACK_TOOLS: ChaosToolSnapshot[] = [ { action: "spawn_beast", label: "Spawn Beast", cooldown_ticks: 20, remaining_ticks: 0 }, { action: "beast_pack", label: "Beast Pack", cooldown_ticks: 80, remaining_ticks: 0 }, { action: "famine", label: "Famine", cooldown_ticks: 120, remaining_ticks: 0 }, { action: "maniac", label: "Maniac", cooldown_ticks: 100, remaining_ticks: 0 },];
type ChaosDockProps = { snapshot: WorldSnapshot | null; pendingChaosAction: string | null; chaosMessage: string | null; godCommand: string; godMessage: string | null; isGodPending: boolean; isWaitingForTick: boolean; onChaosAction: (action: string) => void; onCommandChange: (command: string) => void; onSubmitCommand: (event: FormEvent<HTMLFormElement>) => void;};
export function ChaosDock({ snapshot, pendingChaosAction, chaosMessage, godCommand, godMessage, isGodPending, isWaitingForTick, onChaosAction, onCommandChange, onSubmitCommand,}: ChaosDockProps) { const tools = snapshot?.simulation.chaos_tools ?? FALLBACK_TOOLS; const message = chaosMessage ?? godMessage;
return ( <section className="chaosDock" aria-label="God console"> <div className="chaosHeader"> <span className="chaosTitle">🔥 GOD OF CHAOS</span> <span className="chaosSubtitle">unleash havoc on the village</span> </div>
<div className="chaosButtons"> {tools.map((tool) => { const isPending = pendingChaosAction === tool.action; const onCooldown = tool.remaining_ticks > 0; const disabled = onCooldown || pendingChaosAction !== null || !snapshot; return ( <button key={tool.action} type="button" className={`chaosButton ${onCooldown ? "onCooldown" : ""}`} disabled={disabled} title={ onCooldown ? `${tool.label}: ready in ${tool.remaining_ticks} ticks` : `${tool.label} (cooldown ${tool.cooldown_ticks} ticks)` } onClick={() => onChaosAction(tool.action)} > {isPending ? ( <LoaderCircle className="spinIcon" size={16} /> ) : ( <span className="chaosIcon">{CHAOS_ICONS[tool.action] ?? "✦"}</span> )} <span className="chaosLabel">{tool.label}</span> {onCooldown ? ( <span className="chaosCooldown">{tool.remaining_ticks}</span> ) : null} </button> ); })} </div>
<form className="chaosCommandRow" onSubmit={onSubmitCommand}> <input value={godCommand} onChange={(event) => onCommandChange(event.target.value)} placeholder="Freeform command: 'a plague rumor spreads in the north'..." disabled={isGodPending} /> <button type="submit" aria-label="Run god command" title="Run freeform god command" disabled={!godCommand.trim() || isGodPending || isWaitingForTick} > {isGodPending ? <LoaderCircle className="spinIcon" size={16} /> : <Send size={15} />} </button> </form>
{message ? <p className="chaosMessage">{message}</p> : null} </section> );}9 unmodified lines1011121314151617181920212223242526272 unmodified lines3031323334353637383940414243444546474849505152539 unmodified lines63646566676869707172737475767778798081828384858687888990919293949514 unmodified lines1101111121131141151161171181191201219 unmodified linesconst RESULT_COPY: Record<string, { title: string; subtitle: string; tone: string }> = {win_population: {title: "🏆 THE VILLAGE PREVAILS",subtitle: "The Overseer raised a thriving generation — population goal reached.",tone: "win",},win_survival: {title: "🏆 THE VILLAGE ENDURES",subtitle: "Through famine and fangs, the village outlasted the chaos.",tone: "win",},lose: {title: "💀 THE VILLAGE HAS FALLEN",subtitle: "Chaos reigns. No villager drew breath at the end.",tone: "lose",},};2 unmodified linesconst [isDismissed, setIsDismissed] = useState(false);const status = snapshot.simulation.game_status ?? "running";const copy = RESULT_COPY[status];const stats = snapshot.simulation.stats;const scoreboard = snapshot.simulation.scoreboard;const totalDeaths = Object.values(stats?.deaths_by_cause ?? {}).reduce((sum, count) => sum + count,0,);const betrayals = useMemo(() => events.filter((event) => event.type === "steal" || event.type === "npc_attack").length,[events],);const storyEvents = useMemo(() =>events.filter((event) =>["npc_born", "npc_died", "build_completed", "house_destroyed", "beast_killed", "chaos_event", "game_over"].includes(event.type,),).slice(-14),[events],9 unmodified lines<h1>{copy.title}</h1><p className="gameOverSubtitle">{copy.subtitle}</p><div className="gameOverScore"><span className="scoreOverseerText">🧠 Overseer {scoreboard?.overseer ?? 0}</span><span className="scoreDivider">—</span><span className="scoreChaosText">{scoreboard?.chaos ?? 0} Chaos 🔥</span></div><div className="gameOverStats"><Stat icon="👶" label="Births" value={stats?.total_births ?? 0} /><Stat icon="💀" label="Deaths" value={totalDeaths} /><Stat icon="🏠" label="Houses built" value={stats?.houses_built ?? 0} /><Stat icon="⚔️" label="Beasts slain" value={stats?.beasts_killed ?? 0} /><Stat icon="🕵️" label="Betrayals" value={betrayals} /><Stat icon="👥" label="Peak population" value={snapshot.simulation.peak_population ?? 0} /></div>{Object.keys(stats?.deaths_by_cause ?? {}).length > 0 ? (<p className="gameOverCauses">Causes of death:{" "}{Object.entries(stats?.deaths_by_cause ?? {}).map(([cause, count]) => `${cause.replaceAll("_", " ")} ×${count}`).join(", ")}</p>) : null}{storyEvents.length > 0 ? (<div className="gameOverStory"><h2>The village's story</h2><div className="gameOverStoryList">{storyEvents.map((event, index) => (<div className={`eventLine ${severityClass(event.severity)}`} key={index}>14 unmodified lines);}function Stat({ icon, label, value }: { icon: string; label: string; value: number }) {return (<div className="gameOverStat"><span className="gameOverStatValue">{icon} {value}</span><span className="gameOverStatLabel">{label}</span></div>);9 unmodified lines1011121314151617181920212223242526272 unmodified lines303132333435363738394041424344454647484950515253545556575859609 unmodified lines7071727374757677787980818283848586878889909192939495969714 unmodified lines1121131141151161171181191201219 unmodified linesconst RESULT_COPY: Record<string, { title: string; subtitle: string; tone: string }> = {win_population: {title: "THE WORLD PREVAILS",subtitle: "The countries reached the population goal.",tone: "win",},win_survival: {title: "THE WORLD ENDURES",subtitle: "The countries survived the pressure of the world.",tone: "win",},lose: {title: "THE WORLD HAS FALLEN",subtitle: "No citizen drew breath at the end.",tone: "lose",},};2 unmodified linesconst [isDismissed, setIsDismissed] = useState(false);const status = snapshot.simulation.game_status ?? "running";const copy = RESULT_COPY[status];const stats = snapshot.simulation.stats;const totalDeaths = Object.values(stats?.deaths_by_cause ?? {}).reduce((sum, count) => sum + count,0,);const betrayals = useMemo(() => events.filter((event) => event.type === "steal" || event.type === "treasury_stolen").length,[events],);const storyEvents = useMemo(() =>events.filter((event) =>["npc_born","npc_died","build_completed","house_destroyed","beast_killed","election_completed","policy_updated","cannon_crafted","cannon_fired","game_over",].includes(event.type),).slice(-14),[events],9 unmodified lines<h1>{copy.title}</h1><p className="gameOverSubtitle">{copy.subtitle}</p><div className="gameOverStats"><Stat label="Countries" value={snapshot.countries?.length ?? 0} /><Stat label="Births" value={stats?.total_births ?? 0} /><Stat label="Deaths" value={totalDeaths} /><Stat label="Houses built" value={stats?.houses_built ?? 0} /><Stat label="Beasts slain" value={stats?.beasts_killed ?? 0} /><Stat label="Treasury raids" value={betrayals} /><Stat label="Peak population" value={snapshot.simulation.peak_population ?? 0} /></div>{Object.keys(stats?.deaths_by_cause ?? {}).length > 0 ? (<p className="gameOverCauses">Causes of death:{" "}{Object.entries(stats?.deaths_by_cause ?? {}).map(([cause, count]) => `${cause.replaceAll("_", " ")} x${count}`).join(", ")}</p>) : null}{storyEvents.length > 0 ? (<div className="gameOverStory"><h2>The world's story</h2><div className="gameOverStoryList">{storyEvents.map((event, index) => (<div className={`eventLine ${severityClass(event.severity)}`} key={index}>14 unmodified lines);}function Stat({ label, value }: { label: string; value: number }) {return (<div className="gameOverStat"><span className="gameOverStatValue">{value}</span><span className="gameOverStatLabel">{label}</span></div>);
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import { useEffect, useRef } from "react";
import type { OverseerLogEntry } from "../hooks/useWorldSimulation";import type { WorldSnapshot } from "../types";
type OverseerPanelProps = { snapshot: WorldSnapshot | null; log: OverseerLogEntry[];};
export function OverseerPanel({ snapshot, log }: OverseerPanelProps) { const overseer = snapshot?.simulation.overseer; const mode = overseer?.mode ?? "off"; const listRef = useRef<HTMLDivElement>(null);
useEffect(() => { const list = listRef.current; if (list) { list.scrollTop = list.scrollHeight; } }, [log]);
return ( <aside className="overseerPanel" aria-label="Overseer log"> <div className="sidePanelHeader"> <span className="sidePanelTitle">🧠 Overseer</span> <span className={`overseerMode overseerMode-${mode}`}>{mode.toUpperCase()}</span> </div>
{overseer?.priority_alert ? ( <div className="overseerAlert">⚠ {overseer.priority_alert}</div> ) : null}
<div className="overseerLog" ref={listRef}> {log.length === 0 ? ( <p className="eventEmpty"> {mode === "off" ? "The Overseer is dormant." : "Awaiting the Overseer's first assessment..."} </p> ) : ( log.map((entry) => <OverseerLogItem key={entry.tick} entry={entry} />) )} </div> </aside> );}
function OverseerLogItem({ entry }: { entry: OverseerLogEntry }) { return ( <div className="overseerEntry"> <div className="overseerEntryHead"> <span className="overseerEntryTick">T{entry.tick}</span> {entry.priorityAlert ? ( <span className="overseerEntryAlert">{entry.priorityAlert}</span> ) : null} </div> {entry.thoughts ? <p className="overseerThought">{entry.thoughts}</p> : null} {entry.directives.length > 0 ? ( <ul className="overseerDirectives"> {entry.directives.map((directive, index) => ( <li key={`${entry.tick}-${index}`} className={directive.applied === false ? "directiveSkipped" : ""} > <span className="directiveTarget">{directive.npc_id ?? "?"}</span> <span className="directiveText">{directive.directive ?? ""}</span> {directive.applied === false ? ( <span className="directiveBadge">advisory</span> ) : null} </li> ))} </ul> ) : null} </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737419 unmodified lines949596import type { WorldSnapshot } from "../types";import { formatModelStatus, modelStatusClass, shortModelLabel } from "./modelStatus";import { TooltipLabel } from "./TooltipLabel";const WIN_POPULATION = 12;const WIN_SURVIVAL_TICKS = 600;type ScoreboardHeaderProps = {snapshot: WorldSnapshot | null;isGodPending: boolean;isWaitingForTick: boolean;};export function ScoreboardHeader({snapshot,isGodPending,isWaitingForTick,}: ScoreboardHeaderProps) {const simulation = snapshot?.simulation;const overseerScore = simulation?.scoreboard?.overseer ?? 0;const chaosScore = simulation?.scoreboard?.chaos ?? 0;const population = simulation?.population ?? snapshot?.entities.length ?? 0;const tick = snapshot?.tick ?? 0;const populationProgress = Math.min(1, population / WIN_POPULATION);const survivalProgress = Math.min(1, tick / WIN_SURVIVAL_TICKS);const famineUntil = simulation?.famine_until ?? -1;const isFamineActive = famineUntil >= 0 && tick <= famineUntil;const activityLabel = isGodPending? "god console...": isWaitingForTick? "simulating...": (simulation?.last_tick_source ?? "idle");return (<header className="scoreboard" aria-label="Simulation status"><div className="scoreDuel"><div className="scoreSide scoreOverseer"><span className="scoreName">🧠 OVERSEER</span><span className="scoreValue">{overseerScore}</span></div><div className="scoreVs">vs</div><div className="scoreSide scoreChaos"><span className="scoreValue">{chaosScore}</span><span className="scoreName">CHAOS 🔥</span></div></div><div className="scoreMeta"><span className="scoreTick" title="Current simulation tick">⏱ Tick {tick}</span>{isFamineActive ? (<span className="famineBadge" title={`Food nodes halved until tick ${famineUntil}`}>🌾 FAMINE ({famineUntil - tick})</span>) : null}<span className="scoreActivity">{activityLabel}</span></div><div className="winProgress" title={`Win: ${WIN_POPULATION} villagers, or survive ${WIN_SURVIVAL_TICKS} ticks`}><div className="winRow"><span className="winLabel">👥 Population {population}/{WIN_POPULATION}</span><div className="winBar"><divclassName="winFill winFillPopulation"style={{ width: `${populationProgress * 100}%` }}/></div></div><div className="winRow"><span className="winLabel">🛡 Survival {Math.min(tick, WIN_SURVIVAL_TICKS)}/{WIN_SURVIVAL_TICKS}</span><div className="winBar"><divclassName="winFill winFillSurvival"19 unmodified lines</header>);}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606119 unmodified lines81828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122import type { CountrySnapshot, WorldSnapshot } from "../types";import { formatModelStatus, modelStatusClass, shortModelLabel } from "./modelStatus";import { TooltipLabel } from "./TooltipLabel";const WIN_SURVIVAL_TICKS = 600;type ScoreboardHeaderProps = {snapshot: WorldSnapshot | null;isWaitingForTick: boolean;};export function ScoreboardHeader({ snapshot, isWaitingForTick }: ScoreboardHeaderProps) {const simulation = snapshot?.simulation;const countries = snapshot?.countries ?? [];const population = simulation?.population ?? snapshot?.entities.length ?? 0;const tick = snapshot?.tick ?? 0;const survivalProgress = Math.min(1, tick / WIN_SURVIVAL_TICKS);const famineUntil = simulation?.famine_until ?? -1;const isFamineActive = famineUntil >= 0 && tick <= famineUntil;const activityLabel = isWaitingForTick? "simulating...": (simulation?.last_tick_source ?? "idle");return (<header className="scoreboard" aria-label="Simulation status"><div className="scoreMeta"><span className="scoreTick" title="Current simulation tick">Tick {tick}</span><span className="scoreActivity">{activityLabel}</span><span className="scoreTick">Population {population}</span>{isFamineActive ? (<span className="famineBadge" title={`Food nodes halved until tick ${famineUntil}`}>FAMINE ({famineUntil - tick})</span>) : null}</div><div className="countryGrid" aria-label="Countries">{countries.length > 0 ? (countries.map((country) => (<CountryCardkey={country.id}country={country}tick={tick}rulerName={snapshot?.entities.find((entity) => entity.id === country.ruler_id)?.label ?? null}/>))) : (<div className="countryCard countryCardEmpty">Countries are loading</div>)}</div><div className="winProgress" title={`Survival goal: ${WIN_SURVIVAL_TICKS} ticks`}><div className="winRow"><span className="winLabel">Survival {Math.min(tick, WIN_SURVIVAL_TICKS)}/{WIN_SURVIVAL_TICKS}</span><div className="winBar"><divclassName="winFill winFillSurvival"19 unmodified lines</header>);}type CountryCardProps = {country: CountrySnapshot;rulerName: string | null;tick: number;};function CountryCard({ country, rulerName, tick }: CountryCardProps) {const treasury = country.treasury?.resources ?? {};const election = country.next_election_tick <= tick? "election active": `election T${country.next_election_tick}`;const cannon = country.cannon? country.cannon.operator_id? `cannon: ${country.cannon.operator_id}`: "cannon: no operator": "no cannon";return (<section className="countryCard" style={{ borderColor: country.color }}><div className="countryHead"><span className="countryBadge" style={{ background: country.color }}>{country.badge}</span><strong>{country.name}</strong><span>{country.citizen_ids.length} citizens</span></div><p className="countryPolicy" title={country.policy}>{country.policy}</p><div className="countryFacts"><span>Ruler: {rulerName ?? country.ruler_id ?? "none"}</span><span>{election}</span><span>treasury F{treasury.food ?? 0} H{treasury.herbs ?? 0} W{treasury.wood ?? 0} C{treasury.coins ?? 0}</span><span>{cannon}</span></div></section>);}
2 unmodified lines34567893 unmodified lines13141516171819202122232425262728292 unmodified linestype SimulationControlsProps = {hasSnapshot: boolean;isAutoTicking: boolean;isGodPending: boolean;isWaitingForTick: boolean;isWorldCommandPending: boolean;onStep: () => void;3 unmodified linesexport function SimulationControls({hasSnapshot,isAutoTicking,isGodPending,isWaitingForTick,isWorldCommandPending,onStep,onToggleAutoTick,}: SimulationControlsProps) {const stepLabel = isGodPending? "God command in progress": isWaitingForTick? "Waiting for tick result": "Advance one tick";const autoLabel = isAutoTicking ? "Pause continuous ticks" : "Run continuous ticks";return (2 unmodified lines3456783 unmodified lines1213141516171819202122232 unmodified linestype SimulationControlsProps = {hasSnapshot: boolean;isAutoTicking: boolean;isWaitingForTick: boolean;isWorldCommandPending: boolean;onStep: () => void;3 unmodified linesexport function SimulationControls({hasSnapshot,isAutoTicking,isWaitingForTick,isWorldCommandPending,onStep,onToggleAutoTick,}: SimulationControlsProps) {const stepLabel = isWaitingForTick ? "Waiting for tick result" : "Advance one tick";const autoLabel = isAutoTicking ? "Pause continuous ticks" : "Run continuous ticks";return (
12345export function shortModelLabel(label: string): string {return label === "God Console" ? "God" : "NPC";}export function formatModelStatus(status: string): string {12345export function shortModelLabel(label: string): string {return label;}export function formatModelStatus(status: string): string {
1234567891011121314151617181920212223242526272829303132import type { GameLogEventSnapshot } from "./types";const EVENT_ICONS: Record<string, string> = {beast_spawned: "🐺",beast_attack: "🐺",beast_killed: "⚔️",beast_retreat: "🏃",npc_attack: "🗡️",npc_died: "💀",npc_born: "👶",build_started: "🚧",build_completed: "🏠",house_damaged: "🏚️",house_destroyed: "💥",gather: "🌾",transfer: "🤝",steal: "🕵️",heal: "💊",consume: "🍖",help_request: "🆘",directive_issued: "📜",directive_completed: "✅",chaos_event: "🔥",overseer_skipped: "🌫️",game_over: "🏁",};export function eventIcon(type: string): string {return EVENT_ICONS[type] ?? "•";}export function severityClass(severity: string): string {123456789101112131415161718192021222324252627282930313233343536373839import type { GameLogEventSnapshot } from "./types";const EVENT_ICONS: Record<string, string> = {beast_spawned: "B",beast_attack: "B",beast_killed: "A",beast_retreat: "B",npc_attack: "A",npc_died: "X",npc_born: "+",build_started: "H",build_completed: "H",house_damaged: "H",house_destroyed: "H",gather: "G",transfer: "T",steal: "S",heal: "H",consume: "F",help_request: "!",directive_issued: "D",directive_completed: "D",election_started: "E",vote_cast: "V",election_completed: "E",policy_updated: "P",treasury_deposit: "T",treasury_stolen: "T",cannon_crafted: "C",cannon_operator_assigned: "C",cannon_fired: "C",game_over: "END",};export function eventIcon(type: string): string {return EVENT_ICONS[type] ?? "-";}export function severityClass(severity: string): string {
123456789101112131415161718192021222324252627282930313233343536373839403 unmodified lines4445464748495020 unmodified lines717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815923 unmodified lines18318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922025 unmodified lines24624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028159 unmodified lines3413423433443453463473483493503517 unmodified lines3593603613623633643655 unmodified lines3713723733743753763772 unmodified lines3803813823833843853869 unmodified lines396397398399400401402import type { FormEvent } from "react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {ApiResponseError,fetchWorldSnapshot,sendChaosAction,sendGodCommand,tickWorld,} from "../api";import type {GameLogEventSnapshot,OverseerDirectiveSnapshot,WorldSnapshot,} from "../types";export type OverseerLogEntry = {tick: number;thoughts: string | null;priorityAlert: string | null;directives: OverseerDirectiveSnapshot[];};export function useWorldSimulation() {const [snapshot, setSnapshot] = useState<WorldSnapshot | null>(null);const [isTickPending, setIsTickPending] = useState(false);const [isGodPending, setIsGodPending] = useState(false);const [isAutoTicking, setIsAutoTicking] = useState(false);const [godCommand, setGodCommand] = useState("");const [godMessage, setGodMessage] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);const [selectedId, setSelectedId] = useState<string | null>(null);const [pendingChaosAction, setPendingChaosAction] = useState<string | null>(null);const [chaosMessage, setChaosMessage] = useState<string | null>(null);const isTickingRef = useRef(false);const eventHistory = useEventHistory(snapshot);const overseerLog = useOverseerLog(snapshot);const refresh = useCallback(async () => {const nextSnapshot = await fetchWorldSnapshot();3 unmodified linesconst isServerTickPending = snapshot?.simulation.tick_in_progress ?? false;const isWaitingForTick = isTickPending || isServerTickPending;const isWorldCommandPending = isWaitingForTick || isGodPending;const step = useCallback(async () => {if (isTickingRef.current || snapshot?.simulation.tick_in_progress) {20 unmodified lines}}, [refresh, snapshot?.simulation.tick_in_progress]);const runGodCommand = useCallback(async (event: FormEvent<HTMLFormElement>) => {event.preventDefault();const command = godCommand.trim();if (!command || isGodPending || isWaitingForTick) {return;}setIsGodPending(true);setIsAutoTicking(false);setError(null);setGodMessage(null);try {const result = await sendGodCommand(command);if (result.snapshot) {setSnapshot(result.snapshot);}setGodCommand("");setGodMessage(result.summary || result.applied[0] || "Command queued for the next tick");} catch (nextError) {setError(nextError instanceof Error ? nextError.message : "God command failed");} finally {setIsGodPending(false);}},[godCommand, isGodPending, isWaitingForTick],);const runChaosAction = useCallback(async (action: string) => {if (pendingChaosAction) {return;}setPendingChaosAction(action);setChaosMessage(null);try {for (let attempt = 0; ; attempt += 1) {try {const result = await sendChaosAction(action);if (result.snapshot) {setSnapshot(result.snapshot);}setChaosMessage(result.summary || "Chaos action queued for the next tick");return;} catch (nextError) {const message =nextError instanceof Error ? nextError.message : "Chaos action failed";const isTickBusy =nextError instanceof ApiResponseError &&nextError.status === 409 &&message.includes("tick is running");if (isTickBusy && attempt < 20) {await delay(500);continue;}setChaosMessage(message);return;}}} finally {setPendingChaosAction(null);}},[pendingChaosAction],);useInitialSnapshot(setSnapshot, setSelectedId, setError);useSelectedEntityFallback(snapshot, setSelectedId);useServerTickPolling(isServerTickPending, refresh, setError);useIdleSnapshotPolling({isIdle:snapshot !== null &&!isAutoTicking &&!isWaitingForTick &&!isGodPending &&pendingChaosAction === null,refresh,setError,});useAutoTicks({currentTick: snapshot?.tick ?? null,isAutoTicking,isGodPending,isWaitingForTick,hasSnapshot: snapshot !== null,step,23 unmodified lines);return {chaosMessage,error,eventHistory,godCommand,godMessage,isAutoTicking,isGodPending,isWaitingForTick,isWorldCommandPending,overseerLog,pendingChaosAction,selectedBeast,selectedEntity,selectedHouse,selectedResource,selectedId,setGodCommand,setIsAutoTicking,setSelectedId,snapshot,runChaosAction,runGodCommand,step,};}function delay(ms: number): Promise<void> {return new Promise((resolve) => {window.setTimeout(resolve, ms);});}function useEventHistory(snapshot: WorldSnapshot | null): GameLogEventSnapshot[] {const seenKeysRef = useRef<Set<string>>(new Set());const [history, setHistory] = useState<GameLogEventSnapshot[]>([]);25 unmodified linesreturn history;}function useOverseerLog(snapshot: WorldSnapshot | null): OverseerLogEntry[] {const seenTicksRef = useRef<Set<number>>(new Set());const [log, setLog] = useState<OverseerLogEntry[]>([]);useEffect(() => {const overseer = snapshot?.simulation.overseer;if (!overseer || overseer.last_tick === null) {return;}const lastTick = overseer.last_tick;if (seenTicksRef.current.has(lastTick)) {return;}seenTicksRef.current.add(lastTick);setLog((current) =>[...current,{tick: lastTick,thoughts: overseer.thoughts,priorityAlert: overseer.priority_alert,directives: overseer.directives,},].slice(-40),);}, [snapshot]);return log;}function useInitialSnapshot(setSnapshot: (snapshot: WorldSnapshot) => void,setSelectedId: (id: string | null) => void,59 unmodified linessetError: (error: string | null) => void;};// While the view is idle (not auto-ticking, no tick/god/chaos command in// flight) nothing else refetches the snapshot, so out-of-band world changes —// most notably a player joining over MCP, whose character is spawned into the// world on its first tool call — would only appear on a full page reload.// Poll at a relaxed cadence to surface those changes live.function useIdleSnapshotPolling(options: IdleSnapshotPollingOptions) {const { isIdle, refresh, setError } = options;useEffect(() => {7 unmodified linestype AutoTickOptions = {currentTick: number | null;isAutoTicking: boolean;isGodPending: boolean;isWaitingForTick: boolean;hasSnapshot: boolean;step: () => Promise<void>;5 unmodified linesconst {currentTick,isAutoTicking,isGodPending,isWaitingForTick,hasSnapshot,step,2 unmodified lines} = options;useEffect(() => {if (!isAutoTicking || !hasSnapshot || isWaitingForTick || isGodPending) {return undefined;}9 unmodified linescurrentTick,hasSnapshot,isAutoTicking,isGodPending,isWaitingForTick,setError,setIsAutoTicking,123456789101112131415163 unmodified lines2021222324252620 unmodified lines474849505152535455565758596061626323 unmodified lines8788899091929394959697989910010110210310410510610710810925 unmodified lines13513613713813914059 unmodified lines2002012022032042057 unmodified lines2132142152162172185 unmodified lines2242252262272282292 unmodified lines2322332342352362372389 unmodified lines248249250251252253import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { ApiResponseError, fetchWorldSnapshot, tickWorld } from "../api";import type { GameLogEventSnapshot, WorldSnapshot } from "../types";export function useWorldSimulation() {const [snapshot, setSnapshot] = useState<WorldSnapshot | null>(null);const [isTickPending, setIsTickPending] = useState(false);const [isAutoTicking, setIsAutoTicking] = useState(false);const [error, setError] = useState<string | null>(null);const [selectedId, setSelectedId] = useState<string | null>(null);const isTickingRef = useRef(false);const eventHistory = useEventHistory(snapshot);const refresh = useCallback(async () => {const nextSnapshot = await fetchWorldSnapshot();3 unmodified linesconst isServerTickPending = snapshot?.simulation.tick_in_progress ?? false;const isWaitingForTick = isTickPending || isServerTickPending;const isWorldCommandPending = isWaitingForTick;const step = useCallback(async () => {if (isTickingRef.current || snapshot?.simulation.tick_in_progress) {20 unmodified lines}}, [refresh, snapshot?.simulation.tick_in_progress]);useInitialSnapshot(setSnapshot, setSelectedId, setError);useSelectedEntityFallback(snapshot, setSelectedId);useServerTickPolling(isServerTickPending, refresh, setError);useIdleSnapshotPolling({isIdle: snapshot !== null && !isAutoTicking && !isWaitingForTick,refresh,setError,});useAutoTicks({currentTick: snapshot?.tick ?? null,isAutoTicking,isWaitingForTick,hasSnapshot: snapshot !== null,step,23 unmodified lines);return {error,eventHistory,isAutoTicking,isWaitingForTick,isWorldCommandPending,selectedBeast,selectedEntity,selectedHouse,selectedResource,selectedId,setIsAutoTicking,setSelectedId,snapshot,step,};}function useEventHistory(snapshot: WorldSnapshot | null): GameLogEventSnapshot[] {const seenKeysRef = useRef<Set<string>>(new Set());const [history, setHistory] = useState<GameLogEventSnapshot[]>([]);25 unmodified linesreturn history;}function useInitialSnapshot(setSnapshot: (snapshot: WorldSnapshot) => void,setSelectedId: (id: string | null) => void,59 unmodified linessetError: (error: string | null) => void;};function useIdleSnapshotPolling(options: IdleSnapshotPollingOptions) {const { isIdle, refresh, setError } = options;useEffect(() => {7 unmodified linestype AutoTickOptions = {currentTick: number | null;isAutoTicking: boolean;isWaitingForTick: boolean;hasSnapshot: boolean;step: () => Promise<void>;5 unmodified linesconst {currentTick,isAutoTicking,isWaitingForTick,hasSnapshot,step,2 unmodified lines} = options;useEffect(() => {if (!isAutoTicking || !hasSnapshot || isWaitingForTick) {return undefined;}9 unmodified linescurrentTick,hasSnapshot,isAutoTicking,isWaitingForTick,setError,setIsAutoTicking,
17 unmodified lines1819202122231 unmodified line2526272829303132333435363738394041424344454617 unmodified linesage !== undefined && maxAge !== undefined && maxAge > 0? Math.min(1, age / maxAge): null;return (<button1 unmodified lineclassName={`npcCard ${isAlive ? "" : "npcCardDead"}`}style={{ borderColor: meta.color }}onClick={(event) => {// Keep the click out of the r3f event container, where it would// raycast into empty space and fire onPointerMissed (deselect).event.stopPropagation();onSelect();}}aria-label={`Select ${entity.label}`}title={`${entity.label} — ${meta.label}, ${entity.state.intention}`}><span className="npcCardName"><span className="npcCardIcon" style={{ color: meta.color }} aria-hidden="true">{isAlive ? meta.icon : "💀"}</span><strong>{entity.label}</strong></span><span className="npcCardRole" style={{ color: meta.color }}>{meta.label}</span>{isAlive ? (<>17 unmodified lines18192021222324251 unmodified line272829303132333435363738394041424344454647484917 unmodified linesage !== undefined && maxAge !== undefined && maxAge > 0? Math.min(1, age / maxAge): null;const countryBadge = (entity.country_id ?? "?").slice(0, 1).toUpperCase();const statusLabel = entity.special_status ?? meta.label;return (<button1 unmodified lineclassName={`npcCard ${isAlive ? "" : "npcCardDead"}`}style={{ borderColor: meta.color }}onClick={(event) => {event.stopPropagation();onSelect();}}aria-label={`Select ${entity.label}`}title={`${entity.label} - ${entity.country_id ?? "no country"}, ${entity.state.intention}`}><span className="npcCardName"><span className="npcCardIcon" style={{ color: meta.color }} aria-hidden="true">{isAlive ? meta.icon : "x"}</span><span className="npcCountryBadge" aria-label={`Country ${entity.country_id ?? "unknown"}`}>{countryBadge}</span><strong>{entity.label}</strong></span><span className="npcCardRole" style={{ color: meta.color }}>{statusLabel}</span>{isAlive ? (<>
3 unmodified lines4567891049 unmodified lines60616263646520 unmodified lines8687888990913 unmodified linesimport { Color, Matrix4 } from "three";import type { InstancedMesh } from "three";import type { HouseSnapshot, WorldSnapshot } from "../types";import { BeastActor } from "./BeastActor";import { NpcActor } from "./NpcActor";import { ResourceActor } from "./ResourceActor";49 unmodified linesonSelect={() => onSelectEntity(house.id)}/>))}{(snapshot.resource_nodes ?? []).map((node) => (<ResourceActorkey={node.id}20 unmodified lines);}// Stepped slabs read as voxels where a smooth cone would not.const ROOF_STEPS: Array<{ size: number; y: number }> = [{ size: 3.9, y: 2.175 },3 unmodified lines4567891049 unmodified lines60616263646566676820 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451463 unmodified linesimport { Color, Matrix4 } from "three";import type { InstancedMesh } from "three";import type { CannonSnapshot, CountrySnapshot, HouseSnapshot, TreasurySnapshot, WorldSnapshot } from "../types";import { BeastActor } from "./BeastActor";import { NpcActor } from "./NpcActor";import { ResourceActor } from "./ResourceActor";49 unmodified linesonSelect={() => onSelectEntity(house.id)}/>))}{(snapshot.countries ?? []).map((country) => (<CountryAssets key={country.id} country={country} />))}{(snapshot.resource_nodes ?? []).map((node) => (<ResourceActorkey={node.id}20 unmodified lines);}function CountryAssets({ country }: { country: CountrySnapshot }) {return (<>{country.treasury ? <TreasuryMarker treasury={country.treasury} country={country} /> : null}{country.cannon ? <CannonMarker cannon={country.cannon} country={country} /> : null}</>);}function TreasuryMarker({ treasury, country }: { treasury: TreasurySnapshot; country: CountrySnapshot }) {const resources = treasury.resources;return (<group position={[treasury.position.x, treasury.position.y, treasury.position.z]}><mesh castShadow receiveShadow position={[0, 0.45, 0]}><boxGeometry args={[2.1, 0.9, 2.1]} /><meshStandardMaterial color={country.color} roughness={0.8} metalness={0.05} /></mesh><mesh castShadow receiveShadow position={[0, 1.05, 0]}><boxGeometry args={[1.45, 0.35, 1.45]} /><meshStandardMaterial color="#f4d36a" roughness={0.65} metalness={0.15} /></mesh><Html center distanceFactor={28} position={[0, 1.95, 0]} className="npcLabel" zIndexRange={[6, 0]}><div className="resourceTag treasuryTag"><span>{country.badge} Treasury</span><span>W{resources.wood ?? 0} C{resources.coins ?? 0}</span></div></Html></group>);}function CannonMarker({ cannon, country }: { cannon: CannonSnapshot; country: CountrySnapshot }) {return (<group position={[cannon.position.x, cannon.position.y, cannon.position.z]} rotation={[0, Math.PI / 4, 0]}><mesh castShadow receiveShadow position={[0, 0.45, 0]}><cylinderGeometry args={[0.28, 0.38, 2.1, 18]} /><meshStandardMaterial color="#2e3338" roughness={0.75} metalness={0.35} /></mesh><mesh castShadow receiveShadow position={[0, 0.18, -0.6]}><boxGeometry args={[1.6, 0.28, 1.15]} /><meshStandardMaterial color={country.color} roughness={0.82} /></mesh><Html center distanceFactor={28} position={[0, 1.35, 0]} className="npcLabel" zIndexRange={[6, 0]}><div className="resourceTag cannonTag"><span>{country.badge} Cannon</span><span>{cannon.operator_id ? "armed" : "no operator"}</span></div></Html></group>);}// Stepped slabs read as voxels where a smooth cone would not.const ROOF_STEPS: Array<{ size: number; y: number }> = [{ size: 3.9, y: 2.175 },
41 unmodified lines42434445464748495032 unmodified lines83848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231243 unmodified lines12812913013113213319 unmodified lines153154155156157158197 unmodified lines35635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647716 unmodified lines49449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364438 unmodified lines683684685686687688689690691692366 unmodified lines10591060106110621063106498 unmodified lines11631164116511661167116868 unmodified lines1237123812391240124112421243124412451246124712481249125074 unmodified lines13251326132713281329133013311332133313345 unmodified lines13401341134213431344134513461347134813494 unmodified lines135413551356135713581359136013611362136341 unmodified lines/* ---------------------------------------------------------------- panels */.scoreboard,.overseerPanel,.eventFeed,.chaosDock,.controls,.agentPanel,.errorToast,32 unmodified linesgap: 10px;}.scoreOverseer {justify-content: flex-start;}.scoreChaos {justify-content: flex-end;}.scoreName {font-size: 13px;font-weight: 800;letter-spacing: 0.06em;}.scoreOverseer .scoreName {color: #9fd1ff;}.scoreChaos .scoreName {color: #ffab8a;}.scoreValue {font-size: 24px;font-weight: 800;line-height: 1;}.scoreOverseer .scoreValue {color: #cfe7ff;}.scoreChaos .scoreValue {color: #ffd2c2;}.scoreVs {color: rgb(245 247 240 / 55%);font-size: 12px;3 unmodified lines.scoreMeta {display: flex;justify-content: space-between;gap: 10px;color: rgb(245 247 240 / 78%);19 unmodified linesanimation: faminePulse 1.6s ease-in-out infinite;}@keyframes faminePulse {0%,100% {197 unmodified linesborder-left-color: rgb(255 255 255 / 18%);}/* --------------------------------------------------------- overseer panel */.overseerPanel {position: absolute;top: 14px;left: 14px;z-index: 30;width: min(316px, calc(100vw - 28px));max-height: calc(100svh - 420px);min-height: 180px;display: flex;flex-direction: column;border-radius: 10px;overflow: hidden;}.overseerMode {padding: 3px 8px;border-radius: 5px;font-size: 10px;font-weight: 800;letter-spacing: 0.08em;}.overseerMode-off {background: rgb(255 255 255 / 10%);color: rgb(245 247 240 / 60%);}.overseerMode-advisor {background: rgb(240 195 78 / 18%);color: #ffeebc;}.overseerMode-autopilot {background: rgb(91 150 240 / 22%);color: #cfe7ff;}.overseerAlert {margin: 8px 10px 0;padding: 7px 10px;border: 1px solid rgb(240 195 78 / 45%);border-radius: 7px;background: rgb(240 195 78 / 12%);color: #ffeebc;font-size: 12px;font-weight: 700;}.overseerLog {flex: 1;min-height: 0;overflow-y: auto;padding: 8px 10px 10px;display: grid;gap: 8px;align-content: start;scrollbar-width: thin;}.overseerEntry {display: grid;gap: 5px;padding: 8px 10px;border: 1px solid rgb(159 209 255 / 14%);border-radius: 8px;background: rgb(91 150 240 / 7%);}.overseerEntryHead {display: flex;align-items: center;gap: 8px;}.overseerEntryTick {color: #9fd1ff;font-size: 10px;font-weight: 800;font-variant-numeric: tabular-nums;}.overseerEntryAlert {color: #ffeebc;font-size: 10px;font-weight: 700;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}.overseerThought {margin: 0;color: rgb(245 247 240 / 90%);font-size: 12px;font-style: italic;line-height: 1.4;}.overseerDirectives {margin: 0;padding: 0;display: grid;gap: 3px;list-style: none;}.overseerDirectives li {display: flex;align-items: baseline;gap: 6px;font-size: 11px;line-height: 1.35;}.directiveTarget {flex-shrink: 0;color: #9fd1ff;16 unmodified linesfont-weight: 700;}.directiveSkipped .directiveText {color: rgb(245 247 240 / 55%);}/* ------------------------------------------------------------- chaos dock */.chaosDock {position: absolute;bottom: 18px;left: 50%;z-index: 35;width: min(520px, calc(100vw - 28px));display: grid;gap: 8px;padding: 10px 12px 11px;border-color: rgb(240 106 78 / 35%);border-radius: 10px;transform: translateX(-50%);}.chaosHeader {display: flex;align-items: baseline;gap: 10px;}.chaosTitle {color: #ffab8a;font-size: 13px;font-weight: 800;letter-spacing: 0.06em;}.chaosSubtitle {color: rgb(245 247 240 / 50%);font-size: 11px;}.chaosButtons {display: grid;grid-template-columns: repeat(4, 1fr);gap: 7px;}.chaosButton {position: relative;display: grid;justify-items: center;gap: 3px;padding: 8px 4px 7px;border: 1px solid rgb(240 106 78 / 40%);border-radius: 8px;background: rgb(240 106 78 / 12%);color: #ffd3c8;cursor: pointer;transition: background 120ms ease;}.chaosButton:hover:not(:disabled) {background: rgb(240 106 78 / 26%);}.chaosButton:disabled {cursor: not-allowed;opacity: 0.55;}.chaosButton.onCooldown {border-style: dashed;}.chaosIcon {font-size: 16px;line-height: 1;}.chaosLabel {font-size: 10px;font-weight: 700;white-space: nowrap;}.chaosCooldown {position: absolute;top: -7px;right: -5px;min-width: 20px;padding: 2px 5px;border-radius: 9px;background: #3a2420;border: 1px solid rgb(240 106 78 / 55%);color: #ffab8a;font-size: 10px;font-weight: 800;text-align: center;}.chaosCommandRow {display: grid;grid-template-columns: minmax(0, 1fr) 36px;gap: 7px;}.chaosCommandRow input,.chaosCommandRow button {height: 34px;border: 1px solid rgb(255 255 255 / 14%);border-radius: 7px;color: #fffce9;background: rgb(255 255 255 / 10%);}.chaosCommandRow input {min-width: 0;padding: 0 11px;font: inherit;font-size: 12px;}.chaosCommandRow input::placeholder {color: rgb(245 247 240 / 42%);}.chaosCommandRow button {display: grid;place-items: center;cursor: pointer;}.chaosCommandRow button:disabled {cursor: wait;opacity: 0.68;}.chaosCommandRow button:hover:not(:disabled) {background: rgb(255 255 255 / 18%);}.chaosMessage {margin: 0;color: rgb(245 247 240 / 76%);font-size: 11px;line-height: 1.35;}/* --------------------------------------------------------------- controls */.controls {38 unmodified lines}.controls button:focus-visible,.npcLabel button:focus-visible,.chaosCommandRow input:focus-visible,.chaosCommandRow button:focus-visible,.chaosButton:focus-visible {outline: 2px solid #f8df6b;outline-offset: 2px;}366 unmodified linesline-height: 1;}.npcCardRole {font-size: 9px;font-weight: 700;98 unmodified linesfont-weight: 700;}/* -------------------------------------------------------- game over overlay */.gameOverOverlay {68 unmodified linesfont-weight: 800;}.scoreOverseerText {color: #9fd1ff;}.scoreChaosText {color: #ffab8a;}.scoreDivider {color: rgb(245 247 240 / 40%);}74 unmodified lines/* ---------------------------------------------------------------- responsive */@media (max-width: 1180px) {.overseerPanel {width: min(262px, calc(100vw - 28px));}.eventFeed {width: min(262px, calc(100vw - 28px));}5 unmodified lineswidth: min(400px, calc(100vw - 16px));}.overseerPanel {display: none;}.eventFeed {top: auto;bottom: 200px;4 unmodified linesdisplay: none;}.chaosDock {width: calc(100vw - 16px);}.controls {right: 8px;bottom: 200px;41 unmodified lines4243444546474832 unmodified lines8182838485868788899091929394959697983 unmodified lines10210310410510610710819 unmodified lines128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215197 unmodified lines41341441541641741816 unmodified lines43543643743843944038 unmodified lines479480481482483484485366 unmodified lines85285385485585685785885986086186286386498 unmodified lines96396496596696796896997097197297397497568 unmodified lines10441045104610471048104974 unmodified lines1124112511261127112811295 unmodified lines1135113611371138113911404 unmodified lines11451146114711481149115041 unmodified lines/* ---------------------------------------------------------------- panels */.scoreboard,.eventFeed,.controls,.agentPanel,.errorToast,32 unmodified linesgap: 10px;}.scoreName {font-size: 13px;font-weight: 800;letter-spacing: 0.06em;}.scoreValue {font-size: 24px;font-weight: 800;line-height: 1;}.scoreVs {color: rgb(245 247 240 / 55%);font-size: 12px;3 unmodified lines.scoreMeta {display: flex;flex-wrap: wrap;justify-content: space-between;gap: 10px;color: rgb(245 247 240 / 78%);19 unmodified linesanimation: faminePulse 1.6s ease-in-out infinite;}.countryGrid {display: grid;grid-template-columns: repeat(2, minmax(0, 1fr));gap: 8px;}.countryCard {display: grid;gap: 5px;min-width: 0;padding: 8px 9px;border: 1px solid rgb(255 255 255 / 22%);border-radius: 8px;background: rgb(255 255 255 / 7%);}.countryCardEmpty {grid-column: 1 / -1;color: rgb(245 247 240 / 60%);font-size: 12px;}.countryHead {display: grid;grid-template-columns: auto minmax(0, 1fr) auto;align-items: center;gap: 6px;font-size: 11px;}.countryHead strong {min-width: 0;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}.countryHead span:last-child {color: rgb(245 247 240 / 58%);font-size: 10px;}.countryBadge,.npcCountryBadge {display: inline-grid;place-items: center;width: 18px;height: 18px;border-radius: 5px;color: #101813;font-size: 11px;font-weight: 900;line-height: 1;}.countryPolicy {margin: 0;min-height: 2.5em;color: rgb(245 247 240 / 82%);font-size: 11px;line-height: 1.25;overflow: hidden;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 2;}.countryFacts {display: grid;grid-template-columns: repeat(2, minmax(0, 1fr));gap: 3px 8px;color: rgb(245 247 240 / 62%);font-size: 10px;}.countryFacts span {min-width: 0;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}@keyframes faminePulse {0%,100% {197 unmodified linesborder-left-color: rgb(255 255 255 / 18%);}.directiveTarget {flex-shrink: 0;color: #9fd1ff;16 unmodified linesfont-weight: 700;}/* --------------------------------------------------------------- controls */.controls {38 unmodified lines}.controls button:focus-visible,.npcLabel button:focus-visible {outline: 2px solid #f8df6b;outline-offset: 2px;}366 unmodified linesline-height: 1;}.npcCountryBadge {width: 16px;height: 16px;background: #f7d96c;font-size: 10px;}.npcCardRole {font-size: 9px;font-weight: 700;98 unmodified linesfont-weight: 700;}.treasuryTag,.cannonTag {border-color: rgb(244 211 106 / 45%);background: rgb(15 24 20 / 88%);text-align: center;}/* -------------------------------------------------------- game over overlay */.gameOverOverlay {68 unmodified linesfont-weight: 800;}.scoreDivider {color: rgb(245 247 240 / 40%);}74 unmodified lines/* ---------------------------------------------------------------- responsive */@media (max-width: 1180px) {.eventFeed {width: min(262px, calc(100vw - 28px));}5 unmodified lineswidth: min(400px, calc(100vw - 16px));}.eventFeed {top: auto;bottom: 200px;4 unmodified linesdisplay: none;}.controls {right: 8px;bottom: 200px;
21 unmodified lines2223242526271 unmodified line29303132333448 unmodified lines83848586878889909192939436 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521531541551568 unmodified lines1651661671681691701711721731741751761774 unmodified lines18218318418518618718818919019119219319421 unmodified linesherbs: number;wood: number;weapon: number;};export type EntitySnapshot = {1 unmodified linekind: "npc";label: string;role: string;position: Vec3;state: {intention: string;48 unmodified linesexport type ResourceNodeSnapshot = {id: string;type: "food" | "herbs" | "wood" | "weapon" | string;position: Vec3;amount: number;max_amount?: number;};export type BeastSnapshot = {id: string;position: Vec3;36 unmodified linespopulation?: number;population_cap?: number;peak_population?: number;scoreboard?: {overseer: number;chaos: number;};stats?: GameStatsSnapshot;famine_until?: number;chaos_tools?: ChaosToolSnapshot[];overseer?: {mode: "off" | "advisor" | "autopilot" | string;cycle_ticks: number;last_tick: number | null;status: string;thoughts: string | null;priority_alert: string | null;directives: OverseerDirectiveSnapshot[];};models?: ModelStatusSnapshot[];};terrain: TerrainSnapshot;entities: EntitySnapshot[];resource_nodes?: ResourceNodeSnapshot[];beasts?: BeastSnapshot[];houses?: HouseSnapshot[];8 unmodified linesbeasts_killed: number;};export type ChaosToolSnapshot = {action: string;label: string;cooldown_ticks: number;remaining_ticks: number;};export type GameLogEventSnapshot = {tick: number;type: string;4 unmodified linesseverity: "good" | "neutral" | "warning" | "danger" | string;};export type OverseerDirectiveSnapshot = {npc_id?: string;directive?: string;applied?: boolean;action?: string | null;};export type ModelStatusSnapshot = {id: string;label: string;21 unmodified lines222324252627281 unmodified line303132333435363748 unmodified lines868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914036 unmodified lines1771781791801811821831841851861871881891908 unmodified lines1992002012022032044 unmodified lines20921021121221321421 unmodified linesherbs: number;wood: number;weapon: number;coins: number;};export type EntitySnapshot = {1 unmodified linekind: "npc";label: string;role: string;country_id?: string | null;special_status?: string | null;position: Vec3;state: {intention: string;48 unmodified linesexport type ResourceNodeSnapshot = {id: string;type: "food" | "herbs" | "wood" | "weapon" | "coins" | string;position: Vec3;amount: number;max_amount?: number;};export type TreasurySnapshot = {id: string;position: Vec3;resources: {food?: number;herbs?: number;wood?: number;coins?: number;[key: string]: number | undefined;};};export type CannonSnapshot = {id: string;position: Vec3;operator_id: string | null;cooldown_until_tick: number;damage: number;radius: number;};export type CountrySnapshot = {id: string;name: string;color: string;badge: string;citizen_ids: string[];ruler_id: string | null;policy: string;next_election_tick: number;treasury: TreasurySnapshot | null;cannon: CannonSnapshot | null;};export type ElectionSnapshot = {country_id: string;start_tick: number;end_tick: number;candidate_ids: string[];votes: Record<string, string>;completed: boolean;};export type BeastSnapshot = {id: string;position: Vec3;36 unmodified linespopulation?: number;population_cap?: number;peak_population?: number;stats?: GameStatsSnapshot;famine_until?: number;models?: ModelStatusSnapshot[];};terrain: TerrainSnapshot;entities: EntitySnapshot[];countries?: CountrySnapshot[];elections?: ElectionSnapshot[];resource_nodes?: ResourceNodeSnapshot[];beasts?: BeastSnapshot[];houses?: HouseSnapshot[];8 unmodified linesbeasts_killed: number;};export type GameLogEventSnapshot = {tick: number;type: string;4 unmodified linesseverity: "good" | "neutral" | "warning" | "danger" | string;};export type ModelStatusSnapshot = {id: string;label: string;
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783# target.md — краткая цель для Codex / Claude Code
## 0. Режим работы агента
Прочитай этот документ и реализуй задачу шаг за шагом. Не пытайся угадать архитектуру: сначала найди реальные файлы проекта, затем вноси минимальные изменения.
Главный принцип: после каждого крупного блока запускай игру, смотри `logs/run_*/ledger.jsonl`, проверяй, как реально живут жители, и исправляй баги поведения. Зелёные тесты недостаточны: в демо жители должны жить, голосовать, копить ресурсы, взаимодействовать со странами и действовать через MCP.
---
## 1. Финальная цель
Сделать hackathon MVP игры:
- единый живой мир;- две страны/фракции;- NPC-жители внутри стран;- внешний пользователь подключает своего агента через MCP как обычного жителя;- публичных God Console, Chaos и Overseer больше нет;- все публичные действия идут только через единый MCP-контракт;- роли NPC не ограничивают доступные действия, а только влияют на контекст и стиль поведения;- каждые N тиков проходят выборы;- во время выборов появляется дополнительное действие `vote`;- правитель задаёт текстовую политику страны;- политика попадает в контекст NPC;- у страны есть физическая казна;- жители могут пополнять казну и воровать у другой страны;- страна может скрафтить пушку;- у пушки есть оператор;- оператор может стрелять по координатам;- всё работает через текущий Gradio-интерфейс;- админ может смотреть логи общения с моделями в читаемом виде.
---
## 2. Что обязательно выпилить / выключить
### 2.1. Overseer
В финальном режиме Overseer не нужен.
Нужно:
- выключить Overseer в runtime;- убрать его из tick loop;- убрать Overseer directives из perception;- убрать панель мыслей Overseer из Gradio;- новые логи не должны содержать активные `overseer_request` / `overseer_response`.- удалить
Если полное удаление файлов рискованно — не удаляй физически, а выключи через config/env.
### 2.2. God Console / Chaos
Публичной консоли бога быть не должно.
Нужно:
- убрать God Console из Gradio;- убрать Chaos framing из текстов;- отключить публичные god/chaos endpoints или сделать их admin-only;- пользователь может только: - наблюдать за миром; - создать персонажа; - подключить своего агента через MCP; - проверить статус персонажа.
---
## 3. Главный продуктовый сценарий
Пользователь открывает Gradio-интерфейс и видит:
1. **Observe the world** Наблюдать за миром двух AI-стран.
2. **Connect your agent** Создать персонажа в выбранной стране и получить MCP token/URL.
3. **Check your character** Проверить статус персонажа по токену.
4. **Admin logs / Admin panel** Только для админа по `ADMIN_TOKEN`.
В мире должны быть видны:
- две страны;- бейдж страны у NPC;- роль NPC;- текущий правитель страны;- текущая политика страны;- казна страны;- пушка страны, если построена;- ближайшие события.
---
## 4. MCP — единственный публичный способ действия
Все NPC и внешние агенты должны использовать один и тот же набор инструментов. Нельзя делать отдельные “магические” действия, которые обходят validator или напрямую меняют world state.
Инструменты доступны всем живым NPC и внешним агентам, если действие физически возможно. Роль не должна запрещать базовые действия.
Исключение: в день выборов появляется дополнительный инструмент `vote`.
---
## 5. Единый MCP-контракт
Оставь контракт в таком стиле. Это единственный публичный набор базовых действий.
```pythonACTION_TOOLS: dict[str, dict[str, Any]] = { "move": { "description": ( "Walk toward a destination position (x and z) this tick. To flee, " "move toward coordinates away from the threat." ), "inputSchema": _obj( { "x": {"type": "number", "description": "Destination X coordinate."}, "z": {"type": "number", "description": "Destination Z coordinate."}, } ), }, "speak": { "description": ( "Say a message. With target_npc_id it is direct speech to that NPC; " "without one it is a shout heard by everyone nearby." ), "inputSchema": _obj( { "message": {"type": "string", "description": "What to say."}, "target_npc_id": {"type": "string", "description": "Who to speak to (optional)."}, }, required=["message"], ), }, "attack": { "description": ( "Attack a valid nearby threat or hostile target. Give target_entity_id " "to choose a specific target, or omit it to attack the nearest valid threat. " "The engine resolves approach, range and damage." ), "inputSchema": _obj( {"target_entity_id": {"type": "string", "description": "Id of the target to attack."}} ), }, "use": { "description": ( "Use something in the world: eat food, heal with herbs, gather from a resource node, " "build or repair a house, use treasury, craft an object, or use a cannon. " "The exact effect depends on target/use_type/params and is validated by the engine." ), "inputSchema": _obj( { "resource_type": { "type": "string", "enum": ["food", "herbs", "wood", "coins"], "description": "Optional resource type for consuming, crafting or treasury actions.", }, "resource_id": {"type": "string", "description": "Resource node id, if using/gathering a resource."}, "target_entity_id": {"type": "string", "description": "World object/entity id to use."}, "use_type": { "type": "string", "description": "Use mode, e.g. eat, heal, gather, build, repair, craft, fire.", }, "params": { "type": "object", "description": "Additional structured parameters for the selected use_type.", }, } ), }, "transfer": { "description": ( "Give a resource to a nearby NPC, treasury, storage or object. " "Set take=true to steal/take from a valid nearby target if rules allow it." ), "inputSchema": _obj( { "target_npc_id": {"type": "string", "description": "The other NPC, if target is a character."}, "target_entity_id": {"type": "string", "description": "Treasury/storage/object target id."}, "resource_type": { "type": "string", "enum": ["food", "herbs", "wood", "weapon", "coins"], }, "amount": {"type": "integer", "minimum": 1, "maximum": 20}, "take": {"type": "boolean", "description": "Steal/take instead of give."}, }, required=["resource_type", "amount"], ), },}```
### 5.1. Что делать с build/gather
Если в проекте уже есть отдельные `build` и `gather`, не обязательно ломать их сразу. Но публично и логически они должны быть приведены к `use`.
- `gather(resource_id)` → `use(resource_id=..., use_type="gather")`- `build()` → `use(use_type="build")`- `repair()` → `use(use_type="repair")`
Не добавляй отдельные новые MCP tools для каждой механики. Новые игровые механики должны проходить через `use` или `transfer`.
### 5.2. Единственное исключение — vote
Во время выборов можно добавлять временный инструмент:
```python"vote": { "description": ( "Vote for a ruler candidate during an active election. " "Use candidate_id from the current election candidate list." ), "inputSchema": _obj( { "candidate_id": { "type": "string", "description": "NPC id of the candidate." } }, required=["candidate_id"], ),}```
`vote` доступен только во время election window. В обычные тики его не должно быть в available tools.
---
## 6. Роли NPC
Сейчас классовая система ограничивает выбор действий. Это нужно убрать.
Роль должна быть только контекстом:
- Guard чаще защищает и атакует угрозы;- Builder чаще строит и чинит;- Gatherer чаще собирает ресурсы;- Ruler чаще думает о политике страны;- Cannon operator чаще управляет пушкой.
Но базовые MCP tools не должны блокироваться ролью.
Validator запрещает действие только по реальным причинам:
- NPC мёртв;- цель мертва;- цель далеко;- нет ресурса;- нет объекта;- не хватает казны;- не идёт голосование;- NPC не ruler для смены политики;- NPC не cannon operator для выстрела;- cooldown;- действие нарушает физику/правила мира.
---
## 7. Две страны
Добавить в world state две страны:
- `nemotron`;- `qwen`.
У каждой страны:
- id;- name;- color/badge;- citizens;- ruler_id;- policy;- treasury;- cannon, если построена;- next_election_tick.
У каждого NPC:
- `country_id`;- role;- optional special status: `ruler`, `cannon_operator`;- optional `model_profile_id`.
Perception каждого NPC должен содержать:
- свою страну;- страну видимых NPC;- текущего правителя своей страны;- текущую политику своей страны;- состояние казны;- состояние пушки;- ближайшие события.
---
## 8. Выборы
Выборы должны быть настраиваемыми через `.env`.
```envELECTION_INTERVAL_TICKS=50ELECTION_DURATION_TICKS=10```
Если таких env нет — добавить.
### Как должны работать выборы
1. Каждые `ELECTION_INTERVAL_TICKS` начинается election window.2. Для каждой страны формируется список кандидатов из живых граждан.3. В perception добавляется: - что идут выборы; - список кандидатов; - краткое описание каждого кандидата; - что он делал; - что говорил; - значимые события.4. В available tools временно появляется `vote`.5. Каждый житель страны может проголосовать.6. Если NPC не проголосовал через модель — fallback должен проголосовать сам.7. Победитель становится ruler.8. Новый ruler задаёт policy страны через LLM или fallback.9. Policy сохраняется в CountryState и попадает в prompt граждан.
Важно: во время выборов NPC должен понимать, что сейчас политическая фаза, а не обычный survival tick.
---
## 9. Политика страны
Policy — короткое текстовое указание от правителя.
Примеры:
```textProtect the treasury, gather wood and avoid reckless war.```
```textSteal coins from the other country and prepare to build a cannon.```
```textTrade peacefully, help weak citizens and attack only if threatened.```
Policy не должна напрямую менять мир. Она должна попадать в perception/prompt и влиять на выбор действий модели.
---
## 10. Казна
У каждой страны должна быть физическая казна на карте.
Казна хранит:
- food;- herbs;- wood;- coins.
Действия:
- свой гражданин может положить ресурс в казну через `transfer`;- свой гражданин может взять ресурс, если правила позволяют;- гражданин другой страны может украсть ресурс через `transfer(take=true)`, если он рядом с казной;- все treasury events должны попадать в ledger/engine events.
---
## 11. Пушка и крафт
Пушка — killer feature, но реализация должна быть простой.
### Условия крафта
Через `.env`:
```envCANNON_MIN_POPULATION=6CANNON_TREASURY_COST=20CANNON_WOOD_COST=15CANNON_HP_TAX_PER_CITIZEN=5CANNON_DAMAGE=35CANNON_RADIUS=5CANNON_COOLDOWN_TICKS=20```
Пушка крафтится через:
```textuse(use_type="craft", params={"recipe_id": "cannon"})```
Условия:
- инициатор — ruler;- населения достаточно;- в казне достаточно ресурсов;- пушка ещё не построена;- HP tax не должен сразу уничтожить страну.
### Оператор
Ruler назначает оператора через:
```textuse(use_type="assign_cannon_operator", params={"npc_id": "..."})```
### Выстрел
Оператор стреляет через:
```textuse(use_type="fire", target_entity_id="cannon_id", params={"x": 10, "z": -5})```
Эффект:
- проверка operator;- проверка cooldown;- area damage по живым целям в радиусе;- friendly fire допустим, чтобы у решения была цена;- событие пишется в ledger и отображается в UI.
---
## 12. Внешний MCP-персонаж
Пользователь через Gradio создаёт персонажа:
- name;- icon;- country.
Получает:
- token;- MCP URL;- character id;- список tools.
Ограничения:
- максимум 1 world-changing action per tick;- observe можно чаще, но с rate limit;- если персонаж умер — write actions возвращают ошибку;- invalid token — auth error;- внешний агент не может менять модель;- внешний агент не может вызывать God Console;- внешний агент действует теми же tools, что и NPC.
---
## 13. Admin model switching
Админ может переключить модель любого NPC из списка в JSON config.
Не-админ не может.
Добавить или использовать:
```envADMIN_TOKEN=dev-admin-tokenMODEL_PROFILES_PATH=config/model_profiles.json```
Минимальные endpoints:
```textGET /admin/modelsPOST /admin/npcs/{npc_id}/model```
Защита:
```textX-Admin-Token: <ADMIN_TOKEN>```
В ledger должно быть видно, какой model profile использовался для NPC request.
---
## 14. Admin Model Logs Page
Сделать админ-страницу/вкладку в Gradio для просмотра общения с моделями.
### Backend
Добавить endpoints:
```textGET /admin/logs/runsGET /admin/logs/runs/current/records?since_line=0&limit=200GET /admin/logs/runs/{run_id}/records?phase=&npc_id=&tick_from=&tick_to=&limit=```
SSE optional. Если не успевает — polling.
Читать именно:
```textlogs/run_<UTC timestamp>/ledger.jsonl```
Читать построчно, не грузить весь файл.
Возвращать нормализованный формат:
```json{ "line": 123, "tick": 45, "phase": "npc_response", "npc_id": "npc_7", "model": "nemotron3-nano-4b-fp8", "summary": "NPC used transfer to deposit wood; validator accepted", "record": {}}```
### Frontend / Gradio
Добавить вкладку:
```textAdmin Logs```
Показывать:
- список runs;- фильтр phase;- фильтр npc_id;- tick range;- accepted/repaired/rejected/fallback;- live polling каждые 1–2 секунды;- prompt payload pretty JSON;- raw model output;- parsed action;- validator verdict;- fallback reason;- engine events.
Если старые логи содержат Overseer — можно показывать как legacy. Новый режим не должен создавать новые Overseer records.
---
## 15. Gradio integration
Всё должно работать через текущий Gradio-интерфейс.
Нужно обновить:
- landing text;- Observe screen;- Connect Agent;- Check Character;- Admin Logs;- Admin model switch, если успеешь;- country panels;- NPC badges;- treasury/cannon display.
Не делай отдельный несовместимый UI, если основной демо-интерфейс — Gradio.
---
## 16. Приоритет реализации
### P0 — сначала
1. Найти реальные файлы tick/perception/validator/MCP/Gradio/ledger.2. Выключить Overseer.3. Выключить публичную God Console/Chaos.4. Зафиксировать MCP tools.5. Убрать role-based action blocking.6. Проверить, что игра запускается.
### P1 — ядро нового демо
7. Добавить две страны и `country_id`.8. Добавить country info в perception.9. Добавить country badges в Gradio.10. Добавить выборы через env.11. Добавить `vote` только во время election window.12. Добавить ruler.13. Добавить policy и передачу policy в prompt.
### P2 — экономика и конфликт
14. Добавить физическую казну.15. Реализовать deposit/steal через `transfer`.16. Добавить treasury events в ledger/UI.17. Добавить простую пушку.18. Реализовать craft через `use`.19. Реализовать assign operator через `use`.20. Реализовать fire через `use`.
### P3 — админка
21. Добавить admin model switching.22. Добавить admin logs backend.23. Добавить Admin Logs вкладку в Gradio.24. Добавить live polling логов.
### P4 — self-play и полировка
25. Запустить игру.26. Прогнать минимум 100–200 ticks.27. Проанализировать ledger.28. Исправить баги поведения.29. Повторить прогон.30. Подготовить короткий финальный отчёт.
---
## 17. Обязательный self-play workflow
После реализации каждого крупного блока:
1. Запусти тесты.2. Запусти headless simulation.3. Запусти Gradio/server.4. Прогони 100–200 ticks.5. Найди latest `logs/run_*/ledger.jsonl`.6. Проверь: - NPC понимают свою страну; - NPC видят страну других; - роли не блокируют базовые tools; - во время выборов появляется `vote`; - жители голосуют; - ruler назначается; - policy попадает в prompt; - жители используют treasury; - враги могут воровать; - пушка достижима в demo config; - dead NPC не появляются как targets; - Overseer/God Console не активны; - MCP-персонаж может действовать; - accepted/repaired/rejected/fallback не деградировали.
Если поведение плохое — исправь prompt/perception/validator/balance и прогони снова.
---
## 18. Тесты
Добавить или обновить тесты:
- existing tests pass;- Overseer disabled in final mode;- public God Console disabled;- MCP tools schema valid;- roles do not block base tools;- vote appears only during election;- country_id in NPC perception;- visible NPCs include country;- election starts by env interval;- fallback vote works;- ruler assigned;- policy appears in perception;- treasury deposit works;- treasury steal works;- cannon craft rejects too early;- cannon craft succeeds when requirements met;- cannon fire damages area;- dead MCP character cannot act;- admin token required for admin endpoints;- admin logs read ledger by line.
Команды:
```bashpython -m pytest -qpython scripts/headless_sim.pynpm run typecheck```
Если используется Windows venv:
```bash.venv\Scripts\python.exe -m pytest -q.venv\Scripts\python.exe scripts\headless_sim.py```
---
## 19. Definition of Done
Готово, если:
- Gradio запускается;- публичного Overseer/God Console больше нет;- есть две страны;- NPC имеют country badges;- MCP tools единые;- роли не блокируют базовые действия;- выборы идут по env interval;- `vote` доступен только во время выборов;- ruler задаёт policy;- policy попадает в context NPC;- treasury физически существует и используется;- cannon можно скрафтить и выстрелить;- external MCP character работает;- admin model switching работает;- admin logs page читает ledger;- Codex сам прогнал игру и исправил найденные проблемы;- тесты зелёные.
---
## 20. Финальный отчёт агента
В конце напиши:
```textImplemented:- ...
Validation:- pytest: ...- headless_sim: ...- gradio/server: ...- latest ledger: ...- ticks simulated: ...
Observed behavior:- countries: ...- elections: ...- policies: ...- treasury: ...- cannon: ...- MCP character: ...
Known limitations:- ...```
---
## 21. Verification status (audit 2026-06-14, Claude)
Проверено по коду / тестам / ledger. Статусы: `[x] VERIFIED` `[~] PARTIAL` `[!] BROKEN` `[ ] NOT IMPLEMENTED`.
Self-play ledger: `logs/run_20260614T104917Z/ledger.jsonl` (200 тиков, routing Nemotron+Qwen, offline LLM-shaped completer гоняет тот же pipeline). Headless: `scripts/headless_sim.py` (300 тиков, deterministic). Tests: `pytest -q` → **116 passed**; `tests/test_country_systems.py` (7 новых). Frontend: `npm run typecheck` → clean.
- [x] VERIFIED — Нет активных Overseer/God Console/Chaos в runtime. `api/runtime.py` tick() зовёт `plan_world_tick` без overseer; `overseer_mode="off"` (`spawning.py:81`); нет `/chaos`,`/god` роутов (`api/gradio_app.py`,`api/server.py`); фронт без Chaos/Overseer (ChaosDock/OverseerPanel удалены).- [x] VERIFIED — Публичные действия только через MCP. `api/mcp_server.py` `assert set(ACTION_TOOLS)==set(PLAYER_ACTIONS)`; всё идёт через `runtime.player_act`→`queue_action`.- [x] VERIFIED — Единые tools `move/speak/attack/use/transfer`. `mcp_server.py:51`, `players.py:38`.- [x] VERIFIED — `vote` только во время выборов. `mcp_server` VOTE_TOOL за `player_vote_available`; коннектор добавляет `vote` лишь при `active_election_for_npc` (`openai_compatible.py:558`). Тест `test_vote_tool_only_during_election`.- [x] VERIFIED — Роли не блокируют действия. Промпт «Your role is context, not a tool restriction»; `allowed=PRIMITIVE_TOOL_IDS` для всех; players `unrestricted_actions=True`.- [x] VERIFIED — Две страны, одна на Qwen. `spawning.py` Nemotron+Qwen; Qwen NPC `connector_id="qwen"`→ qwen secondary connector (`game.modal.local.json`, model `qwen3.6-27b-h100-fp8`). Ledger: модели per-country (nemotron3-nano 534 / qwen3.6-27b 466). Тест `test_demo_config_spawns_two_populated_countries`.- [x] VERIFIED — NPC знают свою/чужую страну, правителя, policy, казну, мир. `_build_survival_messages` (`country`+`world_countries`), `build_perception` + rival lines. Тест `test_survival_prompt_exposes_rival_countries`.- [x] VERIFIED — LLM-жители реально играют (action/speak/move/vote/transfer). Self-play ledger: 1914 npc_request/response; actions use 724 / move 829 / transfer 179 / speak 94 / vote 27; engine events gather/treasury_deposit/vote_cast/cannon_*. (Modal-эндпоинты настроены; live-прогон не делал из-за latency, harness гоняет идентичный pipeline routing→ledger.)- [x] VERIFIED — Ledger содержит npc_id, model/model_profile, request, raw response, parsed action, validator verdict, fallback reason, engine events. `connectors/openai_compatible.py` `_npc_request_entry`/`_npc_response_entry`; verdict реконсилится в `tick.py:_publish_plan_ledger_entries`.- [x] VERIFIED — Для каждого жителя видно модель. npc_request несёт `model`+`model_profile`+`connector_id`; admin-нормализатор отдаёт `model` per NPC (qwen-001→qwen3.6-27b).- [x] VERIFIED — Fallback явно виден. `npc_fallback` с `reason` (45 записей «model output was unusable»). Тест `test_unusable_model_output_is_logged_as_fallback`.- [~] PARTIAL — Внешняя MCP-модель играет по тем же правилам. `players.py` гонит queued action через тот же survival pipeline (`unrestricted_actions`, `vote` gated, dead→error); покрыто `tests/test_players_mcp.py`. Не гонял живого внешнего агента end-to-end в этой сессии.- [x] VERIFIED — Выборы настоящие. `_run_election_system`/`_start_election`/`_finish_election`/`_fallback_vote`/`_set_country_policy`. Self-play: election_started/completed 5, vote_cast 25, policy_updated 5.- [x] VERIFIED — Казна и пушка не декоративны. transfer меняет ресурсы (deposit/steal — тесты `test_treasury_*`), пушка craft/assign/fire меняет HP и убивает. Self-play: treasury_deposit 71, cannon_crafted 2, cannon_operator_assigned 2, cannon_fired 10.- [x] VERIFIED — Gradio demo без God/Overseer. `api/public_ui.py`: Observe / Connect your agent / Country, без chaos/god framing.- [x] VERIFIED — Admin logs читают `ledger.jsonl` построчно и показывают LLM/fallback. `runtime.admin_log_records` (line-by-line, фильтры phase/npc_id/tick); smoke: модели per-country + fallback summaries.
### Баги, найденные и исправленные в этой сессии1. `RoutingWorldSimulator.propose_tick` терял `ledger_entries` → при Qwen-роутинге LLM-вызовы не попадали в ledger/admin. Fix: `connectors/routing.py` (мерж entries по owner).2. `npcs.count: 0` во всех survival-конфигах → пустой demo-мир. Fix: `config/game*.json` count=6 (12 жителей).3. В ledger не было видно модель жителя. Fix: `model_profile`/`connector_id`/`country_id` в `_npc_request_entry` + `_stamp_model_attribution`.4. `_optional_known_entity_id` знал только beast-id → `target_entity_id` казны/пушки обнулялся, deposit/steal через LLM деградировали. Fix: распознаём treasury/cannon/house id.5. `transfer(take=true)` к казне уходил в NPC-steal вместо казны. Fix: `_verb_for_action` — transfer к treasury всегда идёт в treasury-handler (он чтит `take`).6. Perception без чужих стран и без своей позиции → нельзя воровать/навигировать. Fix: `world_countries` + `own_state.position` + rival lines в `build_perception`.7. При сбое/непарсимом ответе модели verdict в `npc_response` реконсилился к «accepted» дет-фолбэка → фолбэк маскировался. Fix: `tick.py:_publish_plan_ledger_entries` реконсилит только `pending`; явный `rejected`+reason сохраняется (self-play теперь показывает rejected 48).
### Real-endpoint smoke (честно)2-тиковый прогон на реальных Modal-эндпоинтах (`logs/run_20260614T110045Z`): tick'и прошли (status 200), но `/v1/chat/completions` не ответил в окне сессии (health=200, но генерация холодная/недоступна) → все NPC ушли в deterministic fallback, что корректно залогировано (24 `npc_fallback`). Это инфра, не код: ID моделей и routing верные, offline LLM-shaped self-play гоняет идентичный pipeline и подтверждает поведение.43 unmodified lines4445464748495021 unmodified lines72737475767778798021 unmodified lines10210310410510610710843 unmodified lines)min_population = world.populationrole_violations: list[str] = []tick_durations: list[float] = []overseer = scripted_overseer_controller() if args.mock_overseer else Noneall_debug: list[dict[str, object]] = []21 unmodified linesif npc is None:continueif npc.role == "guard" and action == "gather":role_violations.append(f"tick {world.tick}: guard {npc.id} gathered")if npc.role == "builder" and action == "attack":role_violations.append(f"tick {world.tick}: builder {npc.id} attacked")new_events = world.event_log[before_events:]event_text = "; ".join(21 unmodified linesassert counts["npc_born"] >= 1, "expected at least one reproduction"assert guard_engagements, "expected at least one guard attack against a beast"assert min_population >= 0, "population went negative"assert not role_violations, "\n".join(role_violations)assert all(duration < 0.25 for duration in tick_durations), "tick exceeded time budget"if args.mock_overseer:43 unmodified lines4445464748495021 unmodified lines72737475767778798021 unmodified lines10210310410510610710843 unmodified lines)min_population = world.populationcross_role_actions: list[str] = []tick_durations: list[float] = []overseer = scripted_overseer_controller() if args.mock_overseer else Noneall_debug: list[dict[str, object]] = []21 unmodified linesif npc is None:continueif npc.role == "guard" and action == "gather":cross_role_actions.append(f"tick {world.tick}: guard {npc.id} gathered")if npc.role == "builder" and action == "attack":cross_role_actions.append(f"tick {world.tick}: builder {npc.id} attacked")new_events = world.event_log[before_events:]event_text = "; ".join(21 unmodified linesassert counts["npc_born"] >= 1, "expected at least one reproduction"assert guard_engagements, "expected at least one guard attack against a beast"assert min_population >= 0, "population went negative"assert cross_role_actions, "expected at least one role-flexible action"assert all(duration < 0.25 for duration in tick_durations), "tick exceeded time budget"if args.mock_overseer:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299"""LLM-shaped self-play harness.
Drives the *real* runtime pipeline (RoutingWorldSimulator -> OpenAICompatibleconnectors -> ledger) but injects a deterministic, behaviour-rich "model"instead of calling a remote endpoint. This makes a full 100-300 tick self-playreproducible offline while still exercising:
* per-NPC npc_request / npc_response ledger records with model attribution;* the Qwen secondary connector routing (qwen-* NPCs) vs the default connector (nemotron NPCs), each logged with its own model/model_profile;* the fallback path (a few "unusable" model outputs) being explicitly logged;* elections + vote, treasury deposit/steal via transfer, cannon craft via use, speak, gather, eat/heal — the full action surface.
Usage: .venv\\Scripts\\python.exe scripts\\selfplay_sim.py --ticks 150"""
from __future__ import annotations
import argparseimport jsonfrom collections import Counterfrom pathlib import Pathimport sys
REPO_ROOT = Path(__file__).resolve().parents[1]SRC_ROOT = REPO_ROOT / "src"if str(SRC_ROOT) not in sys.path: sys.path.insert(0, str(SRC_ROOT))
from god_simulator.api.runtime import GameRuntime # noqa: E402from god_simulator.config import load_game_config # noqa: E402from god_simulator.simulation.connectors.deterministic import ( # noqa: E402 DeterministicWorldSimulator,)from god_simulator.simulation.connectors.openai_compatible import ( # noqa: E402 OpenAICompatibleWorldSimulator,)from god_simulator.simulation.connectors.routing import RoutingWorldSimulator # noqa: E402from god_simulator.simulation.spawning import create_world # noqa: E402
def _tool_response(name: str, arguments: dict[str, object]) -> dict[str, object]: return { "choices": [ { "message": { "role": "assistant", "content": "", "tool_calls": [ { "id": "call_0", "type": "function", "function": { "name": name, "arguments": json.dumps(arguments), }, } ], } } ] }
def _unusable_response() -> dict[str, object]: # Neither tool calls nor JSON content -> connector logs a fallback explicitly. return {"choices": [{"message": {"role": "assistant", "content": ""}}]}
def make_fake_completer(): """Return a thread-safe completer that decides one action from the prompt."""
def complete(request: dict[str, object]) -> dict[str, object]: messages = request.get("messages") or [] user = next((m for m in reversed(messages) if m.get("role") == "user"), None) if user is None: return _unusable_response() payload = json.loads(user["content"])
npc_id = payload["npc_id"] tick = int(payload.get("tick", 0)) allowed = set(payload.get("allowed_actions") or []) own = payload.get("own_state") or {} inv = own.get("inventory") or {} country = payload.get("country") or {} threats = payload.get("nearby_threats") or [] allies = payload.get("nearby_allies") or [] resources = payload.get("reachable_resources") or [] seed = (hash(npc_id) ^ (tick * 2654435761)) & 0xFFFFFFFF
# Rarely emit an unusable output so the fallback path is visibly logged. if seed % 41 == 0: return _unusable_response()
# --- elections: vote when the window is open and we have not voted --- election = country.get("election") if isinstance(country, dict) else None if "vote" in allowed and isinstance(election, dict) and not election.get("already_voted"): candidates = election.get("candidate_ids") or [] if candidates: choice = candidates[seed % len(candidates)] return _tool_response("vote", {"candidate_id": choice})
is_ruler = isinstance(country, dict) and country.get("ruler_id") == npc_id treasury = country.get("treasury") if isinstance(country, dict) else {} treasury = treasury if isinstance(treasury, dict) else {} cannon = country.get("cannon") if isinstance(country, dict) else None treasury_id = country.get("treasury_id") if isinstance(country, dict) else None treasury_pos = country.get("treasury_position") if isinstance(country, dict) else None
# --- ruler drives the cannon programme --- if is_ruler: if cannon is None and treasury.get("coins", 0) >= 20 and treasury.get("wood", 0) >= 15: return _tool_response("use", {"use_type": "craft", "params": {"recipe_id": "cannon"}}) if isinstance(cannon, dict) and not cannon.get("operator_id"): return _tool_response( "use", {"use_type": "assign_cannon_operator", "params": {"npc_id": npc_id}}, ) if isinstance(cannon, dict) and cannon.get("operator_id") == npc_id: if tick >= int(cannon.get("cooldown_until_tick", 0)): # Fire toward the rival country (mirror image across x=0). enemy_x = -float((treasury_pos or {}).get("x", 0.0) or 0.0) return _tool_response( "use", { "use_type": "fire", "target_entity_id": cannon.get("id"), "params": {"x": enemy_x, "z": 0.0}, }, )
# --- survival upkeep --- if own.get("hunger", 0) >= 45 and inv.get("food", 0) > 0: return _tool_response("use", {"use_type": "eat", "resource_type": "food"}) if own.get("health", 100) < 55 and inv.get("herbs", 0) > 0: return _tool_response("use", {"use_type": "heal", "resource_type": "herbs"})
# --- guards engage live threats --- if threats and own.get("role") == "guard": return _tool_response("attack", {"target_entity_id": threats[0]["id"]})
world_countries = payload.get("world_countries") or [] rival = next( (c for c in world_countries if isinstance(c, dict) and not c.get("is_own")), None ) own_pos = own.get("position") or {}
# --- raid the rival treasury for coins when close enough --- if rival and rival.get("treasury_position") and (rival.get("treasury", {}).get("coins", 0) > 0): rpos = rival["treasury_position"] dist = abs(float(rpos.get("x", 0)) - float(own_pos.get("x", 0))) + abs( float(rpos.get("z", 0)) - float(own_pos.get("z", 0)) ) if dist <= 6 and seed % 3 == 0: return _tool_response( "transfer", { "target_entity_id": rival["treasury_id"], "resource_type": "coins", "amount": 2, "take": True, }, ) if seed % 13 == 0: # March toward the rival treasury to attempt a raid later. return _tool_response("move", {"x": float(rpos.get("x", 0)), "z": float(rpos.get("z", 0))})
# --- periodically deposit surplus into the home treasury --- if treasury_id and seed % 6 == 0: for res in ("wood", "food", "herbs"): if inv.get(res, 0) > 0: return _tool_response( "transfer", {"target_entity_id": treasury_id, "resource_type": res, "amount": 1}, )
# --- occasionally chat with a nearby ally --- if allies and seed % 9 == 0: partner = allies[0] return _tool_response( "speak", {"message": f"How is the {partner.get('role', 'work')} going?", "target_npc_id": partner["id"]}, )
# --- default: gather the nearest reachable resource, else wander --- if resources: node = resources[0] return _tool_response("use", {"use_type": "gather", "resource_id": node["id"]})
pos = own.get("position") or {} x = float(pos.get("x", 0.0)) + ((seed % 7) - 3) z = float(pos.get("z", 0.0)) + ((seed % 5) - 2) return _tool_response("move", {"x": x, "z": z})
return complete
def build_runtime(config_path: Path) -> GameRuntime: config = load_game_config(config_path) world = create_world(config) completer = make_fake_completer() deterministic = DeterministicWorldSimulator()
routes = { connector_id: OpenAICompatibleWorldSimulator( connector_cfg, fallback=deterministic, connector_id_filter=connector_id, chat_completer=completer, ) for connector_id, connector_cfg in config.secondary_connectors.items() if connector_cfg.type == "openai_compatible" } default = OpenAICompatibleWorldSimulator( config.connector, fallback=deterministic, connector_id_filter=None, chat_completer=completer, ) simulator = RoutingWorldSimulator(routes=routes, default=default) return GameRuntime(world=world, simulator=simulator, config=config)
def main() -> None: parser = argparse.ArgumentParser(description="Offline LLM-shaped self-play.") parser.add_argument("--ticks", type=int, default=150) parser.add_argument("--config", type=Path, default=REPO_ROOT / "config" / "game.modal.local.json") args = parser.parse_args()
runtime = build_runtime(args.config) print(f"SELFPLAY start config={args.config.name} ticks={args.ticks} simulator={runtime.simulator_name}")
for _ in range(args.ticks): status, _payload = runtime.tick() if int(status) != 200: print(f"tick failed: {status}") break
ledger_path = runtime._ledger.ledger_path # noqa: SLF001 - harness introspection print(f"SELFPLAY done. ledger={ledger_path}") _summarize(ledger_path)
def _summarize(ledger_path: Path) -> None: phases: Counter[str] = Counter() models_by_npc: dict[str, set[str]] = {} verdicts: Counter[str] = Counter() event_types: Counter[str] = Counter() actions: Counter[str] = Counter() fallback_reasons: Counter[str] = Counter()
with ledger_path.open("r", encoding="utf-8") as handle: for line in handle: if not line.strip(): continue rec = json.loads(line) phase = rec.get("phase", "?") phases[phase] += 1 if phase == "npc_request": models_by_npc.setdefault(str(rec.get("npc_id")), set()).add( f"{rec.get('model_profile')}::{rec.get('model')}" ) if phase == "npc_response": verdict = rec.get("validator_verdict") or {} verdicts[str(verdict.get("status"))] += 1 parsed = rec.get("parsed_action") or {} if isinstance(parsed, dict) and parsed.get("action"): actions[str(parsed["action"])] += 1 if phase == "npc_fallback": fallback_reasons[str(rec.get("reason"))] += 1 if phase == "engine_events": for event in rec.get("events") or []: event_types[str(event.get("type"))] += 1
print("\n== ledger phases ==") for phase, count in phases.most_common(): print(f" {phase}: {count}") print("\n== model per NPC (from npc_request) ==") for npc_id in sorted(models_by_npc): print(f" {npc_id}: {sorted(models_by_npc[npc_id])}") print("\n== validator verdicts (npc_response) ==") for status, count in verdicts.most_common(): print(f" {status}: {count}") print("\n== parsed LLM actions ==") for action, count in actions.most_common(): print(f" {action}: {count}") print("\n== fallback reasons ==") for reason, count in fallback_reasons.most_common(): print(f" {reason}: {count}") print("\n== engine event types ==") for event_type, count in event_types.most_common(): print(f" {event_type}: {count}")
if __name__ == "__main__": main()123456789101111 unmodified lines232425262728293031323334353637383916 unmodified lines56575859606120 unmodified lines82838485868788899091929394959697989910010110210310418 unmodified lines1231241251261271282 unmodified lines13113213313413513613713813914014114214341 unmodified lines185186187188189190from __future__ import annotationsfrom http import HTTPStatusfrom pathlib import Pathfrom typing import Anyimport gradio as grfrom fastapi import HTTPException, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import (FileResponse,11 unmodified linesfrom god_simulator.simulation.spawning import create_worldclass GodCommandRequest(BaseModel):command: strclass ChaosActionRequest(BaseModel):action: strclass CreatePlayerRequest(BaseModel):name: stricon: str = ""def create_gradio_app(16 unmodified linesregister_api_routes(app, runtime)register_gradio_api(app, runtime)register_player_routes(app, runtime)register_mcp_routes(app, runtime)mount_public_ui(app, runtime)# The SPA catch-all must be registered last so it does not shadow the API,20 unmodified linesstatus, payload = runtime.tick()return JSONResponse(status_code=int(status), content=payload)@app.post("/god-command")def god_command(request: GodCommandRequest) -> JSONResponse:status, payload = runtime.god_command(request.command)return JSONResponse(status_code=int(status), content=payload)@app.post("/chaos")def chaos(request: ChaosActionRequest) -> JSONResponse:status, payload = runtime.chaos_action(request.action)return JSONResponse(status_code=int(status), content=payload)def register_player_routes(app: gr.Server, runtime: GameRuntime) -> None:"""REST mirror of the MCP player tools (handy for the UI and plain clients)."""@app.post("/players")def create_player(request: CreatePlayerRequest) -> JSONResponse:status, payload = runtime.create_player(name=request.name, icon=request.icon)return JSONResponse(status_code=int(status), content=payload)@app.get("/players/{token}")18 unmodified linesreturn JSONResponse(status_code=int(status), content=result)def register_gradio_api(app: gr.Server, runtime: GameRuntime) -> None:@app.api(name="tick", concurrency_limit=1) # type: ignore[untyped-decorator]def tick_api() -> dict[str, Any]:2 unmodified linesraise HTTPException(status_code=int(status), detail=payload)return payload@app.api(name="god_command", concurrency_limit=1) # type: ignore[untyped-decorator]def god_command_api(command: str) -> dict[str, Any]:status, payload = runtime.god_command(command)if status != HTTPStatus.OK:raise HTTPException(status_code=int(status), detail=payload)return payloaddef register_static_routes(app: gr.Server, static_dir: Path) -> None:static_dir = static_dir.resolve()41 unmodified linesreturn value is not None and value.lower() in ("1", "true", "yes")def _is_within(parent: Path, child: Path) -> bool:try:child.relative_to(parent)12345678910111211 unmodified lines242526272829303132333435363716 unmodified lines5455565758596020 unmodified lines818283848586878889909192939495969718 unmodified lines1161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871882 unmodified lines19119219319419519641 unmodified lines238239240241242243244245246247248249from __future__ import annotationsimport osfrom http import HTTPStatusfrom pathlib import Pathfrom typing import Anyimport gradio as grfrom fastapi import Header, HTTPException, Query, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import (FileResponse,11 unmodified linesfrom god_simulator.simulation.spawning import create_worldclass CreatePlayerRequest(BaseModel):name: stricon: str = ""country: str = "nemotron"class AdminModelRequest(BaseModel):profile_id: strdef create_gradio_app(16 unmodified linesregister_api_routes(app, runtime)register_gradio_api(app, runtime)register_player_routes(app, runtime)register_admin_routes(app, runtime)register_mcp_routes(app, runtime)mount_public_ui(app, runtime)# The SPA catch-all must be registered last so it does not shadow the API,20 unmodified linesstatus, payload = runtime.tick()return JSONResponse(status_code=int(status), content=payload)def register_player_routes(app: gr.Server, runtime: GameRuntime) -> None:"""REST mirror of the MCP player tools (handy for the UI and plain clients)."""@app.post("/players")def create_player(request: CreatePlayerRequest) -> JSONResponse:status, payload = runtime.create_player(name=request.name,icon=request.icon,country_id=request.country,)return JSONResponse(status_code=int(status), content=payload)@app.get("/players/{token}")18 unmodified linesreturn JSONResponse(status_code=int(status), content=result)def register_admin_routes(app: gr.Server, runtime: GameRuntime) -> None:@app.get("/admin/logs/runs")def admin_logs_runs(x_admin_token: str | None = Header(default=None)) -> dict[str, Any]:_require_admin(x_admin_token)return runtime.admin_logs_runs()@app.get("/admin/logs/runs/current/records")def admin_current_log_records(x_admin_token: str | None = Header(default=None),since_line: int = Query(default=0, ge=0),limit: int = Query(default=200, ge=1, le=1000),phase: str | None = None,npc_id: str | None = None,tick_from: int | None = None,tick_to: int | None = None,) -> JSONResponse:_require_admin(x_admin_token)status, payload = runtime.admin_log_records(run_id="current",since_line=since_line,limit=limit,phase=phase,npc_id=npc_id,tick_from=tick_from,tick_to=tick_to,)return JSONResponse(status_code=int(status), content=payload)@app.get("/admin/logs/runs/{run_id}/records")def admin_log_records(run_id: str,x_admin_token: str | None = Header(default=None),since_line: int = Query(default=0, ge=0),limit: int = Query(default=200, ge=1, le=1000),phase: str | None = None,npc_id: str | None = None,tick_from: int | None = None,tick_to: int | None = None,) -> JSONResponse:_require_admin(x_admin_token)status, payload = runtime.admin_log_records(run_id=run_id,since_line=since_line,limit=limit,phase=phase,npc_id=npc_id,tick_from=tick_from,tick_to=tick_to,)return JSONResponse(status_code=int(status), content=payload)@app.get("/admin/models")def admin_models(x_admin_token: str | None = Header(default=None)) -> dict[str, Any]:_require_admin(x_admin_token)return runtime.admin_models()@app.post("/admin/npcs/{npc_id}/model")def admin_set_npc_model(npc_id: str,request: AdminModelRequest,x_admin_token: str | None = Header(default=None),) -> JSONResponse:_require_admin(x_admin_token)status, payload = runtime.admin_set_npc_model(npc_id, request.profile_id)return JSONResponse(status_code=int(status), content=payload)def register_gradio_api(app: gr.Server, runtime: GameRuntime) -> None:@app.api(name="tick", concurrency_limit=1) # type: ignore[untyped-decorator]def tick_api() -> dict[str, Any]:2 unmodified linesraise HTTPException(status_code=int(status), detail=payload)return payloaddef register_static_routes(app: gr.Server, static_dir: Path) -> None:static_dir = static_dir.resolve()41 unmodified linesreturn value is not None and value.lower() in ("1", "true", "yes")def _require_admin(token: str | None) -> None:expected = os.getenv("ADMIN_TOKEN", "dev-admin-token")if not token or token != expected:raise HTTPException(status_code=403, detail={"error": "admin_token_required"})def _is_within(parent: Path, child: Path) -> bool:try:child.relative_to(parent)
5 unmodified lines67891011121361 unmodified lines757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331 unmodified line13513613713813914014186 unmodified lines22822923023123223323418 unmodified lines2532542552562572582595 unmodified lines* ``observe`` - look at the world from the character's point of view.* ``whoami`` - report the character's status (alive/dead, stats).* ``move`` / ``speak`` / ``attack`` / ``use`` / ``transfer`` / ``build`` /``gather`` - queue that action for the next simulation tick.The token is embedded in the URL, so the agent only has to point its MCP clientat the URL it was given when creating the character. The character is spawned61 unmodified lines},"attack": {"description": ("Attack a beast. Give target_entity_id to choose a specific beast, or ""omit it to attack the nearest one. The engine resolves approach, ""range and damage."),"inputSchema": _obj({"target_entity_id": {"type": "string", "description": "Id of the beast to attack."}}),},"use": {"description": ("Use something: eat food (resource_type=food), heal with herbs ""(resource_type=herbs), or gather from a resource node (resource_id)."),"inputSchema": _obj({"resource_type": {"type": "string","enum": ["food", "herbs"],"description": "Consume from your inventory: food to eat, herbs to heal.",},"resource_id": {"type": "string", "description": "Gather from this nearby node."},}),},"transfer": {"description": ("Give a resource to a nearby NPC (target_npc_id). Set take=true to ""steal from them instead."),"inputSchema": _obj({"target_npc_id": {"type": "string", "description": "The other NPC."},"resource_type": {"type": "string","enum": ["food", "herbs", "wood", "weapon"],},"amount": {"type": "integer", "minimum": 1, "maximum": 5},"take": {"type": "boolean", "description": "Steal instead of give."},},required=["target_npc_id"],),},"build": {"description": "Raise a new house or repair one nearby. Requires wood in your inventory.","inputSchema": _obj({}),},"gather": {"description": ("Collect one unit from a nearby resource node. Give resource_id to ""target a specific node, or omit it for the nearest one."),"inputSchema": _obj({"resource_id": {"type": "string", "description": "The resource node to gather from."}}),},}1 unmodified line# Sanity: keep the action tools in lock-step with the player action surface.assert set(ACTION_TOOLS) == set(PLAYER_ACTIONS)TOOLS: list[dict[str, Any]] = [{"name": "observe","description": (86 unmodified linesreturn _result_obj(request_id, {})if method == "tools/list":return _result_obj(request_id, {"tools": TOOLS})if method == "tools/call":if not isinstance(params, dict):18 unmodified linesstatus, payload = runtime.player_observe(token)elif name == "whoami":status, payload = runtime.player_status(token)elif name in ACTION_TOOLS:status, payload = runtime.player_act(token, {**arguments, "action": name})else:return _error_obj(request_id, -32602, f"Unknown tool: {name}")5 unmodified lines6789101112131461 unmodified lines7677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331 unmodified line13513613713813914014114214314414514614714814915015115215315415515615715886 unmodified lines24524624724824925025125225325418 unmodified lines2732742752762772782795 unmodified lines* ``observe`` - look at the world from the character's point of view.* ``whoami`` - report the character's status (alive/dead, stats).* ``move`` / ``speak`` / ``attack`` / ``use`` / ``transfer`` - queue thataction for the next simulation tick. Build/gather/repair/craft/fire arerepresented by ``use_type`` on ``use``.The token is embedded in the URL, so the agent only has to point its MCP clientat the URL it was given when creating the character. The character is spawned61 unmodified lines},"attack": {"description": ("Attack a valid nearby threat or hostile target. Give target_entity_id ""to choose a specific target, or omit it to attack the nearest valid ""threat. The engine resolves approach, range and damage."),"inputSchema": _obj({"target_entity_id": {"type": "string", "description": "Id of the target to attack."}}),},"use": {"description": ("Use something in the world: eat food, heal with herbs, gather from a ""resource node, build or repair a house, use treasury, craft an object, ""or use a cannon. The exact effect depends on target/use_type/params ""and is validated by the engine."),"inputSchema": _obj({"resource_type": {"type": "string","enum": ["food", "herbs", "wood", "coins"],"description": "Optional resource type for consuming, crafting or treasury actions.",},"resource_id": {"type": "string", "description": "Gather from this nearby node."},"target_entity_id": {"type": "string", "description": "World object/entity id to use."},"use_type": {"type": "string","description": "Use mode, e.g. eat, heal, gather, build, repair, craft, fire.",},"params": {"type": "object","description": "Additional structured parameters for the selected use_type.",},}),},"transfer": {"description": ("Give a resource to a nearby NPC, treasury, storage or object. Set ""take=true to steal/take from a valid nearby target if rules allow it."),"inputSchema": _obj({"target_npc_id": {"type": "string", "description": "The other NPC, if target is a character."},"target_entity_id": {"type": "string", "description": "Treasury/storage/object target id."},"resource_type": {"type": "string","enum": ["food", "herbs", "wood", "weapon", "coins"],},"amount": {"type": "integer", "minimum": 1, "maximum": 20},"take": {"type": "boolean", "description": "Steal/take instead of give."},},required=["resource_type", "amount"],),},}1 unmodified line# Sanity: keep the action tools in lock-step with the player action surface.assert set(ACTION_TOOLS) == set(PLAYER_ACTIONS)VOTE_TOOL: dict[str, Any] = {"name": "vote","description": ("Vote for a ruler candidate during an active election. Use candidate_id ""from the current election candidate list."),"inputSchema": _obj({"candidate_id": {"type": "string","description": "NPC id of the candidate.",}},required=["candidate_id"],),}BASE_TOOLS: list[dict[str, Any]] = [{"name": "observe","description": (86 unmodified linesreturn _result_obj(request_id, {})if method == "tools/list":tools = list(BASE_TOOLS)if runtime.player_vote_available(token):tools.append(VOTE_TOOL)return _result_obj(request_id, {"tools": tools})if method == "tools/call":if not isinstance(params, dict):18 unmodified linesstatus, payload = runtime.player_observe(token)elif name == "whoami":status, payload = runtime.player_status(token)elif name in ACTION_TOOLS or (name == "vote" and runtime.player_vote_available(token)):status, payload = runtime.player_act(token, {**arguments, "action": name})else:return _error_obj(request_id, -32602, f"Unknown tool: {name}")
34 unmodified lines35363738394041424344454647484910 unmodified lines60616263646520 unmodified lines8687888990918 unmodified lines10010110210310410551 unmodified lines15715815916016116216324 unmodified lines1881891901911921937 unmodified lines20120220320420520610 unmodified lines21721821922022122222322422522622722828 unmodified lines2572582592602612622632642656 unmodified lines2722732742752762772782798 unmodified lines2882892902912922932942952962978 unmodified lines3063073083093103116 unmodified lines31831932032132232310 unmodified lines33433533633733833953 unmodified lines39339439539639739816 unmodified lines41541641741841942034 unmodified lines# external agent may request any of these actions. The survival resolver still# repairs physically impossible requests (no target, empty inventory,# out-of-range) but never blocks an action by role.PLAYER_ACTIONS: tuple[str, ...] = ("move","speak","attack","use","transfer","build","gather",)class PlayerError(Exception):10 unmodified linestoken: strname: stricon: strnpc_id: strcreated_tick: intspawned: bool = False20 unmodified lines*,name: str,icon: str,created_tick: int,) -> PlayerCharacter:clean_name = (name or "").strip()8 unmodified linestoken=token,name=clean_name,icon=(icon or "").strip()[:4],npc_id=f"player-{self._counter:03d}-{token[:6]}",created_tick=created_tick,)51 unmodified lines) -> Npc:npc = self.require_alive(character, world)action = str(payload.get("action", "idle")).strip().lower()if action not in PLAYER_ACTIONS:raise PlayerError("unknown_action",f"Unknown action '{action}'. Valid actions: {', '.join(PLAYER_ACTIONS)}.",24 unmodified lines"name": character.name,"icon": character.icon,"npc_id": character.npc_id,"spawned": character.spawned,"alive": alive,"death_cause": character.death_cause,7 unmodified lines"tick": world.tick,"game_status": world.game_status,"self": self._self_payload(npc),"perception_text": build_perception(npc, world),"nearby_npcs": self._nearby_npcs(npc, world),"nearby_beasts": self._nearby_beasts(npc, world),10 unmodified linesreturn next((npc for npc in world.npcs if npc.id == character.npc_id), None)def _build_npc(self, character: PlayerCharacter, world: WorldState) -> Npc:position = self._spawn_position(world)npc = Npc(id=character.npc_id,name=character.display_name,role=PLAYER_ROLE,position=position,health=100,attack_damage=12,personality="player",28 unmodified linesother.relationships.setdefault(npc.id, 0.45)return npcdef _spawn_position(self, world: WorldState) -> Vec3:half_width = world.terrain.width / 2half_depth = world.terrain.depth / 2# Spawn near the map centre, fanned out so multiple players do not# stack on the exact same tile.spawned_players = sum(1 for npc in world.npcs if npc.is_player)6 unmodified lines(0.0, -BLOCK_SIZE * 2),]offset_x, offset_z = ring[spawned_players % len(ring)]x = _clamp(offset_x, -half_width + BLOCK_SIZE, half_width - BLOCK_SIZE)z = _clamp(offset_z, -half_depth + BLOCK_SIZE, half_depth - BLOCK_SIZE)return Vec3(x=round(x, 3), y=0.0, z=round(z, 3))def _directive_from_payload(self, npc: Npc, payload: dict[str, Any]) -> NpcDirective:8 unmodified linesnpc_id=npc.id,action=action,target=target,target_npc_id=_opt_str(payload.get("target_npc_id")),target_entity_id=_opt_str(payload.get("target_entity_id")),resource_id=_opt_str(payload.get("resource_id")),resource_type=_opt_str(payload.get("resource_type")),amount=_opt_int(payload.get("amount")),communication_intent=_opt_str(payload.get("communication_intent")),message=_opt_str(payload.get("message")),8 unmodified lines"npc_id": npc.id,"name": npc.name,"role": npc.role,"position": {"x": npc.position.x, "z": npc.position.z},"health": npc.health,"hunger": round(npc.hunger, 1),6 unmodified lines"herbs": npc.inventory_herbs,"wood": npc.inventory_wood,"weapon": npc.inventory_weapon,},}10 unmodified lines"id": other.id,"name": other.name,"role": other.role,"distance_tiles": round(distance / BLOCK_SIZE, 1),"trust": round(npc.relationships.get(other.id, 0.0), 2),"is_player": other.is_player,53 unmodified lineshouses.sort(key=lambda item: item["distance_tiles"])return housesdef _mark_dead(self, character: PlayerCharacter, world: WorldState, npc: Npc | None) -> None:character.spawned = Trueif character.death_cause is not None:16 unmodified linesreturn Nonedef _clamp(value: float, minimum: float, maximum: float) -> float:return min(max(value, minimum), maximum)34 unmodified lines353637383940414210 unmodified lines5354555657585920 unmodified lines808182838485868 unmodified lines959697989910010151 unmodified lines15315415515615715815916016124 unmodified lines1861871881891901911927 unmodified lines20020120220320420520610 unmodified lines21721821922022122222322422522622722822928 unmodified lines2582592602612622632642652662672686 unmodified lines2752762772782792802812828 unmodified lines2912922932942952962972982993003013028 unmodified lines3113123133143153163173186 unmodified lines32532632732832933033110 unmodified lines34234334434534634734853 unmodified lines40240340440540640740840941041141241341441541641741841942042142242342442542642742842943016 unmodified lines44744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048134 unmodified lines# external agent may request any of these actions. The survival resolver still# repairs physically impossible requests (no target, empty inventory,# out-of-range) but never blocks an action by role.PLAYER_ACTIONS: tuple[str, ...] = ("move", "speak", "attack", "use", "transfer")VOTE_ACTION = "vote"class PlayerError(Exception):10 unmodified linestoken: strname: stricon: strcountry_id: strnpc_id: strcreated_tick: intspawned: bool = False20 unmodified lines*,name: str,icon: str,country_id: str = "nemotron",created_tick: int,) -> PlayerCharacter:clean_name = (name or "").strip()8 unmodified linestoken=token,name=clean_name,icon=(icon or "").strip()[:4],country_id=country_id if country_id in {"nemotron", "qwen"} else "nemotron",npc_id=f"player-{self._counter:03d}-{token[:6]}",created_tick=created_tick,)51 unmodified lines) -> Npc:npc = self.require_alive(character, world)action = str(payload.get("action", "idle")).strip().lower()if action == VOTE_ACTION and not _vote_available(npc, world):raise PlayerError("vote_unavailable", "Vote is only available during your country's election.")if action not in PLAYER_ACTIONS and action != VOTE_ACTION:raise PlayerError("unknown_action",f"Unknown action '{action}'. Valid actions: {', '.join(PLAYER_ACTIONS)}.",24 unmodified lines"name": character.name,"icon": character.icon,"npc_id": character.npc_id,"country_id": character.country_id,"spawned": character.spawned,"alive": alive,"death_cause": character.death_cause,7 unmodified lines"tick": world.tick,"game_status": world.game_status,"self": self._self_payload(npc),"country": self._country_payload(npc, world),"perception_text": build_perception(npc, world),"nearby_npcs": self._nearby_npcs(npc, world),"nearby_beasts": self._nearby_beasts(npc, world),10 unmodified linesreturn next((npc for npc in world.npcs if npc.id == character.npc_id), None)def _build_npc(self, character: PlayerCharacter, world: WorldState) -> Npc:position = self._spawn_position(world, character.country_id)npc = Npc(id=character.npc_id,name=character.display_name,role=PLAYER_ROLE,position=position,country_id=character.country_id,health=100,attack_damage=12,personality="player",28 unmodified linesother.relationships.setdefault(npc.id, 0.45)return npcdef _spawn_position(self, world: WorldState, country_id: str) -> Vec3:half_width = world.terrain.width / 2half_depth = world.terrain.depth / 2country = next((item for item in world.countries if item.id == country_id), None)anchor = country.treasury.position if country and country.treasury else Vec3(0.0, 0.0, 0.0)# Spawn near the map centre, fanned out so multiple players do not# stack on the exact same tile.spawned_players = sum(1 for npc in world.npcs if npc.is_player)6 unmodified lines(0.0, -BLOCK_SIZE * 2),]offset_x, offset_z = ring[spawned_players % len(ring)]x = _clamp(anchor.x + offset_x, -half_width + BLOCK_SIZE, half_width - BLOCK_SIZE)z = _clamp(anchor.z + offset_z, -half_depth + BLOCK_SIZE, half_depth - BLOCK_SIZE)return Vec3(x=round(x, 3), y=0.0, z=round(z, 3))def _directive_from_payload(self, npc: Npc, payload: dict[str, Any]) -> NpcDirective:8 unmodified linesnpc_id=npc.id,action=action,target=target,target_npc_id=_opt_str(payload.get("target_npc_id") or payload.get("candidate_id")),target_entity_id=_opt_str(payload.get("target_entity_id")),resource_id=_opt_str(payload.get("resource_id")),resource_type=_opt_str(payload.get("resource_type")),use_type=_opt_str(payload.get("use_type")),params=payload.get("params") if isinstance(payload.get("params"), dict) else None,amount=_opt_int(payload.get("amount")),communication_intent=_opt_str(payload.get("communication_intent")),message=_opt_str(payload.get("message")),8 unmodified lines"npc_id": npc.id,"name": npc.name,"role": npc.role,"country_id": npc.country_id,"special_status": npc.special_status,"position": {"x": npc.position.x, "z": npc.position.z},"health": npc.health,"hunger": round(npc.hunger, 1),6 unmodified lines"herbs": npc.inventory_herbs,"wood": npc.inventory_wood,"weapon": npc.inventory_weapon,"coins": npc.inventory_coins,},}10 unmodified lines"id": other.id,"name": other.name,"role": other.role,"country_id": other.country_id,"distance_tiles": round(distance / BLOCK_SIZE, 1),"trust": round(npc.relationships.get(other.id, 0.0), 2),"is_player": other.is_player,53 unmodified lineshouses.sort(key=lambda item: item["distance_tiles"])return housesdef _country_payload(self, npc: Npc, world: WorldState) -> dict[str, Any] | None:if npc.country_id is None:return Nonecountry = next((item for item in world.countries if item.id == npc.country_id), None)if country is None:return Noneelection = _active_election_payload(npc, world)return {"id": country.id,"name": country.name,"badge": country.badge,"ruler_id": country.ruler_id,"policy": country.policy,"treasury": dict(country.treasury.resources) if country.treasury else {},"treasury_id": country.treasury.id if country.treasury else None,"treasury_position": Noneif country.treasury is Noneelse {"x": country.treasury.position.x, "z": country.treasury.position.z},"cannon_id": country.cannon.id if country.cannon else None,"next_election_tick": country.next_election_tick,"election": election,}def _mark_dead(self, character: PlayerCharacter, world: WorldState, npc: Npc | None) -> None:character.spawned = Trueif character.death_cause is not None:16 unmodified linesreturn Nonedef _vote_available(npc: Npc, world: WorldState) -> bool:if npc.country_id is None:return Falsefor election in world.elections:if election.country_id != npc.country_id or election.completed:continueif election.start_tick <= world.tick <= election.end_tick and npc.id not in election.votes:return Truereturn Falsedef _active_election_payload(npc: Npc, world: WorldState) -> dict[str, Any] | None:if npc.country_id is None:return Nonefor election in world.elections:if election.country_id != npc.country_id or election.completed:continueif election.start_tick <= world.tick <= election.end_tick:return {"country_id": election.country_id,"start_tick": election.start_tick,"end_tick": election.end_tick,"candidate_ids": list(election.candidate_ids),"votes": dict(election.votes),"has_voted": npc.id in election.votes,}return Nonedef _clamp(value: float, minimum: float, maximum: float) -> float:return min(max(value, minimum), maximum)
13 unmodified lines14151617181974 unmodified lines94959697989933 unmodified lines1331341351361371381391401411421435 unmodified lines14915015115215315415515615715815916042 unmodified lines20320420520620720820921021121213 unmodified lines22622722822923023123213 unmodified linesfrom __future__ import annotationsimport jsonfrom http import HTTPStatusfrom pathlib import Pathfrom typing import Any74 unmodified linesallow_custom_value=True,scale=1,)create_submit = gr.Button("✨ Create character & get MCP token",elem_id="gs-btn-create",33 unmodified lines)status_out = gr.Markdown()gr.HTML(_GROUND_FOOTER_HTML)create_submit.click(_make_create_handler(runtime),inputs=[name_box, icon_box],outputs=[create_status, token_group, token_box, mcp_url_box, config_box],api_name="create_character",)5 unmodified linesapi_name="check_status",)return blocksdef _make_create_handler(runtime: GameRuntime) -> Any:def create(name: str, icon: str, request: gr.Request) -> tuple[Any, ...]:status, payload = runtime.create_player(name=name, icon=icon)if status != HTTPStatus.OK:message = payload.get("message", "Could not create character.")return (42 unmodified linesreturn checkdef _format_status(payload: dict[str, Any]) -> str:icon = payload.get("icon", "")name = payload.get("name", "?")lines = [f"### {icon} {name}"]if not payload.get("spawned"):lines.append("⏳ Not in the world yet — call `observe` or `act` over MCP to join.")return "\n\n".join(lines)13 unmodified lines)lines.append(f"- Inventory — food: {inv.get('food', 0)}, herbs: {inv.get('herbs', 0)}, "f"wood: {inv.get('wood', 0)}, weapon: {inv.get('weapon', 0)}")lines.append(f"- Doing: {me.get('intention', '—')} (tick {payload.get('tick')})")return "\n".join(lines)13 unmodified lines1415161718192074 unmodified lines959697989910010110210310410510633 unmodified lines1401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851865 unmodified lines19219319419519619719819920020120220320420520620720820921021121221321421521621721842 unmodified lines26126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930013 unmodified lines31431531631731831932032113 unmodified linesfrom __future__ import annotationsimport jsonimport osfrom http import HTTPStatusfrom pathlib import Pathfrom typing import Any74 unmodified linesallow_custom_value=True,scale=1,)country_box = gr.Dropdown(label="Country",choices=[("Nemotron", "nemotron"), ("Qwen", "qwen")],value="nemotron",scale=1,)create_submit = gr.Button("✨ Create character & get MCP token",elem_id="gs-btn-create",33 unmodified lines)status_out = gr.Markdown()with gr.Group(elem_classes="gs-card"):gr.HTML("""<div class="gs-card-head sky"><div class="gs-tile sky">LOGS</div><h2>Admin Logs</h2></div><div class="gs-card-body"><p class="gs-lede">Read model, validator and engine records from ledger.jsonl. Requires ADMIN_TOKEN.</p></div>""")with gr.Column(elem_classes="gs-card-inputs"):with gr.Row(elem_classes="status-row"):admin_token = gr.Textbox(label="Admin token",placeholder="ADMIN_TOKEN",max_lines=1,type="password",scale=2,)admin_run = gr.Textbox(label="Run id",value="current",max_lines=1,scale=1,)with gr.Row(elem_classes="status-row"):admin_phase = gr.Textbox(label="phase", max_lines=1)admin_npc = gr.Textbox(label="npc_id", max_lines=1)admin_tick_from = gr.Number(label="tick from", precision=0)admin_tick_to = gr.Number(label="tick to", precision=0)admin_limit = gr.Number(label="limit", value=100, precision=0)admin_btn = gr.Button("Load ledger records")admin_out = gr.JSON(label="Ledger records")gr.HTML(_GROUND_FOOTER_HTML)create_submit.click(_make_create_handler(runtime),inputs=[name_box, icon_box, country_box],outputs=[create_status, token_group, token_box, mcp_url_box, config_box],api_name="create_character",)5 unmodified linesapi_name="check_status",)admin_btn.click(_make_admin_logs_handler(runtime),inputs=[admin_token,admin_run,admin_phase,admin_npc,admin_tick_from,admin_tick_to,admin_limit,],outputs=[admin_out],api_name="admin_logs",)return blocksdef _make_create_handler(runtime: GameRuntime) -> Any:def create(name: str, icon: str, country: str, request: gr.Request) -> tuple[Any, ...]:status, payload = runtime.create_player(name=name, icon=icon, country_id=country)if status != HTTPStatus.OK:message = payload.get("message", "Could not create character.")return (42 unmodified linesreturn checkdef _make_admin_logs_handler(runtime: GameRuntime) -> Any:def load(token: str,run_id: str,phase: str,npc_id: str,tick_from: float | None,tick_to: float | None,limit: float | None,) -> dict[str, Any]:if token != os.getenv("ADMIN_TOKEN", "dev-admin-token"):return {"error": "admin_token_required"}status, payload = runtime.admin_log_records(run_id=(run_id or "current").strip() or "current",phase=(phase or "").strip() or None,npc_id=(npc_id or "").strip() or None,tick_from=int(tick_from) if tick_from is not None else None,tick_to=int(tick_to) if tick_to is not None else None,limit=int(limit) if limit is not None else 100,)if status != HTTPStatus.OK:return payloadruns = runtime.admin_logs_runs()return {**payload, **runs}return loaddef _format_status(payload: dict[str, Any]) -> str:icon = payload.get("icon", "")name = payload.get("name", "?")lines = [f"### {icon} {name}"]if payload.get("country_id"):lines.append(f"Country: `{payload['country_id']}`")if not payload.get("spawned"):lines.append("⏳ Not in the world yet — call `observe` or `act` over MCP to join.")return "\n\n".join(lines)13 unmodified lines)lines.append(f"- Inventory — food: {inv.get('food', 0)}, herbs: {inv.get('herbs', 0)}, "f"wood: {inv.get('wood', 0)}, weapon: {inv.get('weapon', 0)}, "f"coins: {inv.get('coins', 0)}")lines.append(f"- Doing: {me.get('intention', '—')} (tick {payload.get('tick')})")return "\n".join(lines)
1234567894 unmodified lines14151617181920212223242526272829303132333 unmodified lines37383940414243444546474849505152535455565726 unmodified lines84858687888990919211 unmodified lines1041051061071081091101111121131141151161171181191201211221236 unmodified lines1301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192201 unmodified line22222322422522622722822923023123223338 unmodified lines2722732742752762776 unmodified lines2842852862872882892902912921 unmodified line2942952962972982993003013023033043053063072 unmodified lines31031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635716 unmodified lines374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417182 unmodified lines600601602603604605606607608609from __future__ import annotationsimport timefrom copy import deepcopyfrom dataclasses import asdict, dataclass, fieldfrom http import HTTPStatusfrom threading import Lock, Threadfrom typing import Any, Protocolfrom urllib.error import HTTPError, URLError4 unmodified linesPlayerError,PlayerManager,)from god_simulator.config import ConnectorConfig, GameConfigfrom god_simulator.domain import WorldStatefrom god_simulator.rendering.scene_contract import to_scene_snapshotfrom god_simulator.simulation.chaos import (CHAOS_COOLDOWNS,CHAOS_TOOL_LABELS,apply_chaos_action,)from god_simulator.simulation.connectors.base import TickPlan, WorldSimulatorfrom god_simulator.simulation.connectors.factory import create_world_simulatorfrom god_simulator.simulation.god_console import GodConsole, apply_god_command_planfrom god_simulator.simulation.god_console import GodCommandPlanfrom god_simulator.simulation.directives import expire_directivesfrom god_simulator.simulation.overseer import OverseerController, create_overseerfrom god_simulator.simulation.tick import apply_tick_plan, plan_world_tick3 unmodified lines*,world: WorldState,simulator: WorldSimulator,god_console: GodConsole | None = None,modal_health_warmer: HealthWarmer | None = None,overseer: OverseerController | None = None,players: PlayerManager | None = None,) -> None:self._world = worldself._simulator = simulatorself._god_console = god_consoleself._modal_health_warmer = modal_health_warmerself._overseer = overseerself._players = players or PlayerManager()self._lock = Lock()self._tick_status = TickStatus()self._god_status = GodCommandStatus()self._chaos_status = ChaosStatus()self._pending_commands: list[PendingCommand] = []@property26 unmodified linestick_in_progress=self._tick_status.in_progress,pending_tick=self._tick_status.pending_tick,)payload["simulation"]["chaos_tools"] = chaos_tools_payload(self._chaos_status, self._world.tick)if self._modal_health_warmer is not None:payload["simulation"]["models"] = self._modal_health_warmer.statuses()return payload11 unmodified linesnpc_order=[npc.id for npc in planning_world.living_npcs()],)set_active_tick_buffer(buffer)prepared_commands: list[PreparedCommand] = []try:prepared_commands = self._prepare_pending_commands(planning_world,pending_commands,next_tick=next_tick,)expire_directives(planning_world, tick=next_tick)planned_tick, plan = plan_world_tick(planning_world,self._simulator,next_tick,overseer=self._overseer,)except Exception as exc:with self._lock:6 unmodified lines"message": str(exc),}with self._lock:plan = self._override_player_directives(planning_world, plan)apply_tick_plan(self._world, planned_tick, plan)append_record({"tick": planned_tick,"phase": "engine_events","events": [eventfor event in self._world.to_dict()["event_log"][before_events:]],})self._tick_status.in_progress = Falseself._tick_status.pending_tick = Nonepayload = self._world.to_dict()payload["simulation"] = tick_status_payload(self._tick_status)self._ledger.flush_tick(buffer)set_active_tick_buffer(None)return HTTPStatus.OK, payloaddef god_command(self, command: str) -> tuple[HTTPStatus, dict[str, Any]]:if self._god_console is None:return HTTPStatus.BAD_REQUEST, {"error": "god_console_unavailable"}if not command.strip():return HTTPStatus.BAD_REQUEST, {"error": "invalid_request","message": "Expected non-empty 'command'.",}with self._lock:self._pending_commands.append(PendingCommand(kind="god_console", raw_input=command.strip()))applies_on_tick = self._queued_command_tick()return HTTPStatus.OK, {"source": plan.source,"summary": plan.summary,"applied": applied,"snapshot": to_scene_snapshot(self._world,tick_in_progress=self._tick_status.in_progress,pending_tick=self._tick_status.pending_tick,),}def chaos_action(self, action: str) -> tuple[HTTPStatus, dict[str, Any]]:if action not in CHAOS_COOLDOWNS:return HTTPStatus.BAD_REQUEST, {"error": "unknown_chaos_action","message": f"Unknown chaos action: {action}","actions": sorted(CHAOS_COOLDOWNS),}with self._lock:last_used = self._chaos_status.last_used.get(action)if last_used is not None:remaining = last_used + CHAOS_COOLDOWNS[action] - self._world.tickif remaining > 0:return HTTPStatus.CONFLICT, {"error": "chaos_on_cooldown","message": (f"{CHAOS_TOOL_LABELS[action]} ready in {remaining} ticks."),"remaining_ticks": remaining,}applied = apply_chaos_action(self._world, action)if applied:self._chaos_status.last_used[action] = self._world.ticksnapshot = to_scene_snapshot(self._world,tick_in_progress=self._tick_status.in_progress,pending_tick=self._tick_status.pending_tick,)snapshot["simulation"]["chaos_tools"] = chaos_tools_payload(self._chaos_status, self._world.tick)return HTTPStatus.OK, {"action": action,"queued": True,"applies_on_tick": applies_on_tick,"applied": [],"summary": f"{CHAOS_TOOL_LABELS[action]} queued for tick {applies_on_tick}.",}# -- player characters (external agents over MCP) ---------------------- #def create_player(1 unmodified line*,name: str,icon: str,) -> tuple[HTTPStatus, dict[str, Any]]:with self._lock:try:character = self._players.create(name=name,icon=icon,created_tick=self._world.tick,)except PlayerError as exc:38 unmodified lines"observation": observation,}def _override_player_directives(self, world: WorldState, plan: TickPlan) -> TickPlan:"""Replace planner directives for player-owned NPCs with their queued actions."""player_ids = self._players.player_npc_ids6 unmodified linesdirective = self._players.take_directive(character, world)if directive is not None:directives.append(directive)return TickPlan(source=plan.source, directives=directives, overseer=plan.overseer)def _begin_tick(self) -> tuple[WorldState | None, int | None, dict[str, Any] | None]:with self._lock:if self._tick_status.in_progress:return None, None, None, {1 unmodified line"tick": self._world.tick,**tick_status_payload(self._tick_status),}if self._god_status.in_progress:return None, None, None, {"error": "god_command_in_progress","message": "A god command is already modifying the world.","tick": self._world.tick,**tick_status_payload(self._tick_status),}next_tick = self._world.tick + 1planning_world = deepcopy(self._world)pending_commands = list(self._pending_commands)2 unmodified linesself._tick_status.pending_tick = next_tickreturn planning_world, next_tick, pending_commands, Nonedef _begin_god_command(self) -> tuple[WorldState | None, dict[str, Any] | None]:with self._lock:if self._tick_status.in_progress:return None, {"error": "tick_in_progress","message": "God commands are disabled while a tick is running.",**tick_status_payload(self._tick_status),}if self._god_status.in_progress:return None, {"error": "god_command_in_progress","message": "Another god command is already running.",**tick_status_payload(self._tick_status),}self._god_status.in_progress = Truereturn deepcopy(self._world), Nonedef create_game_runtime(*, world: WorldState, config: GameConfig) -> GameRuntime:simulator = create_world_simulator(config)overseer = create_overseer(config)god_console_config = config.god_console or config.connectorgod_console = (GodConsole(god_console_config)if god_console_config.type == "openai_compatible"else None)return GameRuntime(world=world,simulator=simulator,god_console=god_console,modal_health_warmer=ModalHealthWarmer(modal_health_targets(config)),overseer=overseer,)def _character_summary(character: PlayerCharacter) -> dict[str, Any]:return {"token": character.token,"name": character.name,"icon": character.icon,"npc_id": character.npc_id,}16 unmodified linespending_tick: int | None = None@dataclass(slots=True)class GodCommandStatus:in_progress: bool = False@dataclass(frozen=True, slots=True)class PendingCommand:kind: strraw_input: str@dataclass(frozen=True, slots=True)class PreparedCommand:pending: PendingCommandgod_plan: GodCommandPlan | None = None@dataclass(slots=True)class ChaosStatus:last_used: dict[str, int] = field(default_factory=dict)def chaos_tools_payload(chaos_status: ChaosStatus, tick: int) -> list[dict[str, Any]]:tools: list[dict[str, Any]] = []for action, cooldown in CHAOS_COOLDOWNS.items():last_used = chaos_status.last_used.get(action)remaining = 0 if last_used is None else max(0, last_used + cooldown - tick)tools.append({"action": action,"label": CHAOS_TOOL_LABELS[action],"cooldown_ticks": cooldown,"remaining_ticks": remaining,})return toolsdef tick_status_payload(tick_status: TickStatus) -> dict[str, Any]:return {"tick_in_progress": tick_status.in_progress,182 unmodified linestargets: list[ModalHealthTarget] = []connector_targets: list[tuple[str, str, ConnectorConfig | None]] = [("npc_model", "NPC model", config.connector),("god_console", "God Console", config.god_console),]if config.overseer.mode != "off":connector_targets.append(("overseer", "Overseer", config.overseer.connector))for target_id, label, connector in connector_targets:if connector is None:continue1234567891011124 unmodified lines171819202122232425262728293 unmodified lines3334353637383940414243444546474849505126 unmodified lines78798081828311 unmodified lines95969798991001011021031041051061076 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421 unmodified line14414514614714814915015115215315415515615738 unmodified lines1961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663676 unmodified lines3743753763773783793803813823833843853863873883891 unmodified line3913923933943953962 unmodified lines39940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747816 unmodified lines495496497498499500501502503504505506182 unmodified lines689690691692693694695from __future__ import annotationsimport jsonimport osimport timefrom copy import deepcopyfrom dataclasses import dataclassfrom http import HTTPStatusfrom pathlib import Pathfrom threading import Lock, Threadfrom typing import Any, Protocolfrom urllib.error import HTTPError, URLError4 unmodified linesPlayerError,PlayerManager,)from god_simulator.observability import RunLedger, append_record, set_active_tick_bufferfrom god_simulator.config import ConnectorConfig, GameConfigfrom god_simulator.domain import WorldLogEvent, WorldStatefrom god_simulator.rendering.scene_contract import to_scene_snapshotfrom god_simulator.simulation.connectors.base import TickPlan, WorldSimulatorfrom god_simulator.simulation.connectors.factory import create_world_simulatorfrom god_simulator.simulation.directives import expire_directivesfrom god_simulator.simulation.tick import apply_tick_plan, plan_world_tick3 unmodified lines*,world: WorldState,simulator: WorldSimulator,modal_health_warmer: HealthWarmer | None = None,players: PlayerManager | None = None,ledger: RunLedger | None = None,config: GameConfig | None = None,) -> None:self._world = worldself._simulator = simulatorself._modal_health_warmer = modal_health_warmerself._players = players or PlayerManager()self._ledger = ledger or RunLedger()self._config = configself._lock = Lock()self._tick_status = TickStatus()self._pending_commands: list[PendingCommand] = []@property26 unmodified linestick_in_progress=self._tick_status.in_progress,pending_tick=self._tick_status.pending_tick,)if self._modal_health_warmer is not None:payload["simulation"]["models"] = self._modal_health_warmer.statuses()return payload11 unmodified linesnpc_order=[npc.id for npc in planning_world.living_npcs()],)set_active_tick_buffer(buffer)try:expire_directives(planning_world, tick=next_tick)planned_tick, plan = plan_world_tick(planning_world,self._simulator,next_tick,)except Exception as exc:with self._lock:6 unmodified lines"message": str(exc),}try:with self._lock:before_events = len(self._world.event_log)plan = self._override_player_directives(planning_world, plan)apply_tick_plan(self._world, planned_tick, plan)append_record({"tick": planned_tick,"phase": "engine_events","events": [eventfor event in self._world.to_dict()["event_log"][before_events:]],})self._tick_status.in_progress = Falseself._tick_status.pending_tick = Nonepayload = self._world.to_dict()payload["simulation"] = tick_status_payload(self._tick_status)self._ledger.flush_tick(buffer)return HTTPStatus.OK, payloadfinally:set_active_tick_buffer(None)# -- player characters (external agents over MCP) ---------------------- #def create_player(1 unmodified line*,name: str,icon: str,country_id: str = "nemotron",) -> tuple[HTTPStatus, dict[str, Any]]:with self._lock:try:character = self._players.create(name=name,icon=icon,country_id=country_id,created_tick=self._world.tick,)except PlayerError as exc:38 unmodified lines"observation": observation,}def player_vote_available(self, token: str) -> bool:with self._lock:try:character = self._players.get(token)except PlayerError:return Falsefor election in self._world.elections:if election.country_id != character.country_id or election.completed:continueif election.start_tick <= self._world.tick <= election.end_tick:return Truereturn False# -- admin ------------------------------------------------------------- #def admin_logs_runs(self) -> dict[str, Any]:root = self._ledger.run_dir.parentruns: list[dict[str, Any]] = []for run_dir in sorted(root.glob("run_*"), key=lambda item: item.name, reverse=True):if not run_dir.is_dir():continueledger_path = run_dir / "ledger.jsonl"runs.append({"run_id": run_dir.name,"current": run_dir == self._ledger.run_dir,"ledger_path": str(ledger_path),"exists": ledger_path.is_file(),"size_bytes": ledger_path.stat().st_size if ledger_path.is_file() else 0,})return {"runs": runs}def admin_log_records(self,*,run_id: str | None = None,since_line: int = 0,limit: int = 200,phase: str | None = None,npc_id: str | None = None,tick_from: int | None = None,tick_to: int | None = None,) -> tuple[HTTPStatus, dict[str, Any]]:run_dir = self._ledger.run_dir if run_id in (None, "current") else self._run_dir(run_id)if run_dir is None:return HTTPStatus.NOT_FOUND, {"error": "run_not_found", "message": "Unknown ledger run."}ledger_path = run_dir / "ledger.jsonl"if not ledger_path.is_file():return HTTPStatus.NOT_FOUND, {"error": "ledger_not_found", "message": "Run has no ledger.jsonl."}records: list[dict[str, Any]] = []next_line = max(0, since_line)limit = max(1, min(limit, 1000))with ledger_path.open("r", encoding="utf-8") as ledger_file:for line_no, line in enumerate(ledger_file):next_line = line_no + 1if line_no < since_line:continuetry:record = json.loads(line)except json.JSONDecodeError:continueif not _record_matches(record,phase=phase,npc_id=npc_id,tick_from=tick_from,tick_to=tick_to,):continuerecords.append(_normalize_log_record(line_no, record))if len(records) >= limit:breakreturn HTTPStatus.OK, {"run_id": run_dir.name,"ledger_path": str(ledger_path),"next_line": next_line,"records": records,}def admin_models(self) -> dict[str, Any]:return {"profiles": self._model_profiles(),"npcs": [{"id": npc.id,"name": npc.name,"country_id": npc.country_id,"model_profile_id": npc.model_profile_id,"connector_id": npc.connector_id,}for npc in self._world.npcs],}def admin_set_npc_model(self, npc_id: str, profile_id: str) -> tuple[HTTPStatus, dict[str, Any]]:profiles = {profile["id"]: profile for profile in self._model_profiles()}if profile_id not in profiles:return HTTPStatus.BAD_REQUEST, {"error": "unknown_profile", "message": "Unknown model profile."}profile = profiles[profile_id]connector_id = profile.get("connector_id")with self._lock:npc = next((candidate for candidate in self._world.npcs if candidate.id == npc_id), None)if npc is None:return HTTPStatus.NOT_FOUND, {"error": "npc_not_found", "message": "Unknown NPC."}npc.model_profile_id = profile_idnpc.connector_id = connector_id if isinstance(connector_id, str) and connector_id else Noneself._world.event_log.append(WorldLogEvent(tick=self._world.tick,type="model_profile_changed",summary=f"{npc.name} model profile set to {profile_id}",severity="neutral",actor_id=npc.id,))self._ledger.write_records([{"tick": self._world.tick,"phase": "admin_model_switch","npc_id": npc_id,"model_profile_id": profile_id,"connector_id": connector_id,}])return HTTPStatus.OK, {"npc_id": npc_id, "profile": profile}def _run_dir(self, run_id: str | None) -> Path | None:if not run_id or "/" in run_id or "\\" in run_id or not run_id.startswith("run_"):return Nonerun_dir = self._ledger.run_dir.parent / run_idif not run_dir.is_dir():return Nonereturn run_dirdef _model_profiles(self) -> list[dict[str, Any]]:profiles: dict[str, dict[str, Any]] = {"default": {"id": "default","label": "Default NPC model","connector_id": None,"model": self._config.connector.model if self._config else None,}}if self._config is not None:for connector_id, connector in self._config.secondary_connectors.items():profiles[connector_id] = {"id": connector_id,"label": connector_id,"connector_id": connector_id,"model": connector.model,"type": connector.type,}profiles_path = Path(os.getenv("MODEL_PROFILES_PATH", "config/model_profiles.json"))if profiles_path.is_file():try:raw = json.loads(profiles_path.read_text(encoding="utf-8"))except json.JSONDecodeError:raw = {}for item in raw.get("profiles", []) if isinstance(raw, dict) else []:if isinstance(item, dict) and isinstance(item.get("id"), str):profiles[item["id"]] = dict(item)return list(profiles.values())def _override_player_directives(self, world: WorldState, plan: TickPlan) -> TickPlan:"""Replace planner directives for player-owned NPCs with their queued actions."""player_ids = self._players.player_npc_ids6 unmodified linesdirective = self._players.take_directive(character, world)if directive is not None:directives.append(directive)return TickPlan(source=plan.source,directives=directives,overseer=plan.overseer,ledger_entries=plan.ledger_entries,)def _begin_tick(self,) -> tuple[WorldState | None, int | None, list[PendingCommand] | None, dict[str, Any] | None]:with self._lock:if self._tick_status.in_progress:return None, None, None, {1 unmodified line"tick": self._world.tick,**tick_status_payload(self._tick_status),}next_tick = self._world.tick + 1planning_world = deepcopy(self._world)pending_commands = list(self._pending_commands)2 unmodified linesself._tick_status.pending_tick = next_tickreturn planning_world, next_tick, pending_commands, Nonedef create_game_runtime(*, world: WorldState, config: GameConfig) -> GameRuntime:simulator = create_world_simulator(config)return GameRuntime(world=world,simulator=simulator,modal_health_warmer=ModalHealthWarmer(modal_health_targets(config)),config=config,)def _record_matches(record: dict[str, Any],*,phase: str | None,npc_id: str | None,tick_from: int | None,tick_to: int | None,) -> bool:if phase and record.get("phase") != phase:return Falseif npc_id and record.get("npc_id") != npc_id:return Falsetick = record.get("tick")if tick_from is not None and isinstance(tick, int) and tick < tick_from:return Falseif tick_to is not None and isinstance(tick, int) and tick > tick_to:return Falsereturn Truedef _normalize_log_record(line: int, record: dict[str, Any]) -> dict[str, Any]:return {"line": line,"tick": record.get("tick"),"phase": record.get("phase"),"npc_id": record.get("npc_id"),"model": _record_model(record),"summary": _record_summary(record),"record": record,}def _record_model(record: dict[str, Any]) -> str | None:model = record.get("model")if isinstance(model, str):return modelrequest = record.get("request")if isinstance(request, dict) and isinstance(request.get("model"), str):return request["model"]return Nonedef _record_summary(record: dict[str, Any]) -> str:summary = record.get("summary")if isinstance(summary, str) and summary:return summaryphase = str(record.get("phase") or "record")parsed = record.get("parsed_action") or record.get("action")verdict = record.get("validator") or record.get("verdict") or record.get("reason")parts = [phase]if parsed:parts.append(f"action={parsed}")if verdict:parts.append(str(verdict))return "; ".join(parts)def _character_summary(character: PlayerCharacter) -> dict[str, Any]:return {"token": character.token,"name": character.name,"icon": character.icon,"country_id": character.country_id,"npc_id": character.npc_id,}16 unmodified linespending_tick: int | None = None@dataclass(frozen=True, slots=True)class PendingCommand:kind: strraw_input: strdef tick_status_payload(tick_status: TickStatus) -> dict[str, Any]:return {"tick_in_progress": tick_status.in_progress,182 unmodified linestargets: list[ModalHealthTarget] = []connector_targets: list[tuple[str, str, ConnectorConfig | None]] = [("npc_model", "NPC model", config.connector),]for target_id, label, connector in connector_targets:if connector is None:continue
30 unmodified lines313233343536373816 unmodified lines555657585960611 unmodified line636465666768697071727374757677787935 unmodified lines11511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714830 unmodified linesfrom god_simulator.config import GameConfigfrom god_simulator.domain import WorldStatefrom god_simulator.simulation.connectors.base import WorldSimulatorfrom god_simulator.simulation.god_console import GodConsolefrom god_simulator.simulation.overseer import OverseerController__all__ = ["_ModalHealthTarget",16 unmodified linesprint(f"World simulator connector: {runtime.simulator_name}")print("Available endpoints: GET /health, GET /state, GET /scene/state, ""POST /tick, POST /god-command, POST /chaos")server.serve_forever()1 unmodified linedef _build_handler(world: WorldState,simulator: WorldSimulator,god_console: GodConsole | None = None,modal_health_warmer: _HealthWarmer | None = None,overseer: OverseerController | None = None,) -> type[BaseHTTPRequestHandler]:return build_handler(GameRuntime(world=world,simulator=simulator,god_console=god_console,modal_health_warmer=modal_health_warmer,overseer=overseer,))35 unmodified linesself._send_json(payload, status=status)returnif self.path == "/god-command":try:command = self._read_json_field("command")except ValueError as exc:self._send_json({"error": "invalid_request", "message": str(exc)},status=HTTPStatus.BAD_REQUEST,)returnstatus, payload = runtime.god_command(command)self._send_json(payload, status=status)returnif self.path == "/chaos":try:action = self._read_json_field("action")except ValueError as exc:self._send_json({"error": "invalid_request", "message": str(exc)},status=HTTPStatus.BAD_REQUEST,)returnstatus, payload = runtime.chaos_action(action)self._send_json(payload, status=status)returnself._send_json({"error": "not_found", "path": self.path},status=HTTPStatus.NOT_FOUND,30 unmodified lines31323334353616 unmodified lines535455565758591 unmodified line6162636465666768697071727374757635 unmodified lines11211311411511611730 unmodified linesfrom god_simulator.config import GameConfigfrom god_simulator.domain import WorldStatefrom god_simulator.simulation.connectors.base import WorldSimulator__all__ = ["_ModalHealthTarget",16 unmodified linesprint(f"World simulator connector: {runtime.simulator_name}")print("Available endpoints: GET /health, GET /state, GET /scene/state, ""POST /tick")server.serve_forever()1 unmodified linedef _build_handler(world: WorldState,simulator: WorldSimulator,god_console: object | None = None,modal_health_warmer: _HealthWarmer | None = None,overseer: object | None = None,) -> type[BaseHTTPRequestHandler]:_ = god_console, overseerreturn build_handler(GameRuntime(world=world,simulator=simulator,modal_health_warmer=modal_health_warmer,))35 unmodified linesself._send_json(payload, status=status)returnself._send_json({"error": "not_found", "path": self.path},status=HTTPStatus.NOT_FOUND,
138 unmodified lines1391401411421431448 unmodified lines15315415515615715838 unmodified lines19719819920020120236 unmodified lines239240241242243244138 unmodified linesinventory_herbs: int = 0inventory_wood: int = 0inventory_weapon: int = 0help_target_id: str | None = None# Whom the NPC is currently engaging (talk/attack/trade); drives facing in the renderer.focus_target_id: str | None = None8 unmodified lines# by the built-in deterministic/LLM planner.is_player: bool = Falseplayer_owner: str | None = None# When true, the engine does not role-gate this NPC's actions: it may take# any action regardless of role. Player NPCs set this, but it can also be# given to special non-player NPCs.38 unmodified linesoccupant_ids: list[str] = field(default_factory=list)@dataclass(slots=True)class WorldLogEvent:tick: int36 unmodified lineshouses: list[House] = field(default_factory=list)active_events: list[WorldEvent] = field(default_factory=list)event_log: list[WorldLogEvent] = field(default_factory=list)game_status: GameStatus = "running"population: int = 0population_cap: int = 12138 unmodified lines1391401411421431441458 unmodified lines15415515615715815916016116238 unmodified lines20120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624736 unmodified lines284285286287288289290291138 unmodified linesinventory_herbs: int = 0inventory_wood: int = 0inventory_weapon: int = 0inventory_coins: int = 0help_target_id: str | None = None# Whom the NPC is currently engaging (talk/attack/trade); drives facing in the renderer.focus_target_id: str | None = None8 unmodified lines# by the built-in deterministic/LLM planner.is_player: bool = Falseplayer_owner: str | None = Nonecountry_id: str | None = Nonespecial_status: str | None = Nonemodel_profile_id: str | None = None# When true, the engine does not role-gate this NPC's actions: it may take# any action regardless of role. Player NPCs set this, but it can also be# given to special non-player NPCs.38 unmodified linesoccupant_ids: list[str] = field(default_factory=list)@dataclass(slots=True)class TreasuryState:id: strposition: Vec3resources: dict[str, int] = field(default_factory=dict)@dataclass(slots=True)class CannonState:id: strposition: Vec3operator_id: str | None = Nonecooldown_until_tick: int = 0damage: int = 35radius: int = 5@dataclass(slots=True)class CountryState:id: strname: strcolor: strbadge: strcitizen_ids: list[str] = field(default_factory=list)ruler_id: str | None = Nonepolicy: str = "Gather resources, protect citizens, and avoid reckless war."treasury: TreasuryState | None = Nonecannon: CannonState | None = Nonenext_election_tick: int = 50@dataclass(slots=True)class ElectionState:country_id: strstart_tick: intend_tick: intcandidate_ids: list[str]votes: dict[str, str] = field(default_factory=dict)completed: bool = False@dataclass(slots=True)class WorldLogEvent:tick: int36 unmodified lineshouses: list[House] = field(default_factory=list)active_events: list[WorldEvent] = field(default_factory=list)event_log: list[WorldLogEvent] = field(default_factory=list)countries: list[CountryState] = field(default_factory=list)elections: list[ElectionState] = field(default_factory=list)game_status: GameStatus = "running"population: int = 0population_cap: int = 12
31 unmodified lines3233343536373831 unmodified linesreturn TickLedgerBuffer(tick=tick, npc_order=npc_order)def flush_tick(self, buffer: TickLedgerBuffer) -> None:records = buffer.sorted_records()if not records:returnwith self._lock:31 unmodified lines32333435363738394031 unmodified linesreturn TickLedgerBuffer(tick=tick, npc_order=npc_order)def flush_tick(self, buffer: TickLedgerBuffer) -> None:self.write_records(buffer.sorted_records())def write_records(self, records: list[dict[str, Any]]) -> None:if not records:returnwith self._lock:
22 unmodified lines232425262728293031321 unmodified line34353637383940414243444546474813 unmodified lines62636465666722 unmodified lines90919293949530 unmodified lines12612712812913013122 unmodified lines"population": world.population,"population_cap": world.population_cap,"peak_population": world.peak_population,"scoreboard": {"overseer": world.overseer_score,"chaos": world.chaos_score,},"stats": {"total_births": world.total_births,"deaths_by_cause": dict(world.deaths_by_cause),1 unmodified line"beasts_killed": world.beasts_killed,},"famine_until": world.famine_until,"overseer": {"mode": world.overseer_mode,"cycle_ticks": world.overseer_cycle_ticks,"last_tick": world.overseer_last_tick,"status": world.overseer_status,"thoughts": world.overseer_last_thoughts,"priority_alert": world.overseer_priority_alert,"directives": list(world.overseer_last_directives),},},"terrain": {"kind": world.terrain.kind,13 unmodified lines"kind": "npc","label": npc.name,"role": npc.role,"position": {"x": npc.position.x,"y": npc.position.y,22 unmodified lines"herbs": npc.inventory_herbs,"wood": npc.inventory_wood,"weapon": npc.inventory_weapon,},"memory_count": len(npc.memory),"memory_summary": npc.memory_summary,30 unmodified lines}for npc in world.npcs],"resource_nodes": [{"id": node.id,22 unmodified lines2324252627281 unmodified line30313233343513 unmodified lines495051525354555622 unmodified lines7980818283848530 unmodified lines11611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917022 unmodified lines"population": world.population,"population_cap": world.population_cap,"peak_population": world.peak_population,"stats": {"total_births": world.total_births,"deaths_by_cause": dict(world.deaths_by_cause),1 unmodified line"beasts_killed": world.beasts_killed,},"famine_until": world.famine_until,},"terrain": {"kind": world.terrain.kind,13 unmodified lines"kind": "npc","label": npc.name,"role": npc.role,"country_id": npc.country_id,"special_status": npc.special_status,"position": {"x": npc.position.x,"y": npc.position.y,22 unmodified lines"herbs": npc.inventory_herbs,"wood": npc.inventory_wood,"weapon": npc.inventory_weapon,"coins": npc.inventory_coins,},"memory_count": len(npc.memory),"memory_summary": npc.memory_summary,30 unmodified lines}for npc in world.npcs],"countries": [{"id": country.id,"name": country.name,"color": country.color,"badge": country.badge,"citizen_ids": list(country.citizen_ids),"ruler_id": country.ruler_id,"policy": country.policy,"next_election_tick": country.next_election_tick,"treasury": Noneif country.treasury is Noneelse {"id": country.treasury.id,"position": {"x": country.treasury.position.x,"y": country.treasury.position.y,"z": country.treasury.position.z,},"resources": dict(country.treasury.resources),},"cannon": Noneif country.cannon is Noneelse {"id": country.cannon.id,"position": {"x": country.cannon.position.x,"y": country.cannon.position.y,"z": country.cannon.position.z,},"operator_id": country.cannon.operator_id,"cooldown_until_tick": country.cannon.cooldown_until_tick,"damage": country.cannon.damage,"radius": country.cannon.radius,},}for country in world.countries],"elections": [{"country_id": election.country_id,"start_tick": election.start_tick,"end_tick": election.end_tick,"candidate_ids": list(election.candidate_ids),"votes": dict(election.votes),"completed": election.completed,}for election in world.elections[-10:]],"resource_nodes": [{"id": node.id,
1 unmodified line234567814 unmodified lines23242526272829303132333435363738394041424 unmodified lines474849505152535455565758591 unmodified linefrom god_simulator.simulation.actions.schemas import ActionDefinition# The whole action surface: six parameterized primitives. Behavioral flavor# (fleeing, pleading, threatening, stealing, healing...) is expressed through# parameters and free-text intent, not through dedicated action ids.BUILTIN_ACTIONS: dict[str, ActionDefinition] = {14 unmodified lines),required_params=("message",),),"strike": ActionDefinition(id="strike",category="combat",description_for_model=("Attack a nearby NPC or beast. The engine resolves movement, damage, and death."),required_params=("target_id",),),"use": ActionDefinition(id="use",category="resource",description_for_model=("Use something: gather from a resource node (resource_id), eat food ""(item=food), or heal with herbs (item=herbs)."),),"transfer": ActionDefinition(4 unmodified lines),required_params=("target_id",),),"idle": ActionDefinition(id="idle",category="passive",description_for_model=("Do nothing this tick: wait, observe, or hold position defensively."),),}PRIMITIVE_ACTION_IDS: tuple[str, ...] = tuple(BUILTIN_ACTIONS)1 unmodified line234567814 unmodified lines232425262728293031323334353637383940414 unmodified lines4647484950511 unmodified linefrom god_simulator.simulation.actions.schemas import ActionDefinition# The whole public action surface: five parameterized primitives. Behavioral flavor# (fleeing, pleading, threatening, stealing, healing...) is expressed through# parameters and free-text intent, not through dedicated action ids.BUILTIN_ACTIONS: dict[str, ActionDefinition] = {14 unmodified lines),required_params=("message",),),"attack": ActionDefinition(id="attack",category="combat",description_for_model=("Attack a valid nearby threat or hostile target. The engine resolves approach, range, damage, and death."),),"use": ActionDefinition(id="use",category="resource",description_for_model=("Use something: gather from a resource node, eat food, heal with herbs, ""build/repair/craft an object, or operate a world object."),),"transfer": ActionDefinition(4 unmodified lines),required_params=("target_id",),),}PRIMITIVE_ACTION_IDS: tuple[str, ...] = tuple(BUILTIN_ACTIONS)
34 unmodified lines3536373839404142434445464748495051525354554 unmodified lines606162636465662 unmodified lines6970717273747576771 unmodified line798081828384855 unmodified lines91929394959697989910010110210334 unmodified linesmatch goal.goal_type:case "survive" | "call_for_help":suggested: list[ActionKind] = ["move", "speak", "idle"]if _goal_target_in_range(world, npc, goal):suggested.insert(1, "strike")return ActionHints(suggested_actions=suggested,reason=("A threat is nearby: moving away, calling for help, pleading, ""defending, or striking back are the most plausible responses"),)case "pursue_and_attack_target":if _goal_target_in_range(world, npc, goal):return ActionHints(suggested_actions=["strike", "speak"],reason="The hostile directive target is within striking range",)return ActionHints(4 unmodified linescase "retaliate":if _goal_target_in_range(world, npc, goal):return ActionHints(suggested_actions=["strike", "speak", "move"],reason="The recent attacker is within reach",)return ActionHints(2 unmodified lines)case "help_or_defend":helping: list[ActionKind] = ["speak", "idle", "move"]if _goal_target_in_range(world, npc, goal):helping.insert(0, "strike")return ActionHints(suggested_actions=helping,reason="Someone nearby is being harmed; helping or defending is most plausible",1 unmodified linecase "respond_to_event" | "investigate":return ActionHints(suggested_actions=["move", "idle", "speak"],reason="Something suspicious happened; investigating or watching is most plausible",)5 unmodified linescase "routine_life":return ActionHints(suggested_actions=["move", "speak", "use", "transfer", "idle"],reason="Nothing urgent is happening; everyday activity is most plausible",)return ActionHints(suggested_actions=["idle"],reason="Unknown goal; observing is the safest default",)34 unmodified lines3536373839404142434445464748495051525354554 unmodified lines606162636465662 unmodified lines6970717273747576771 unmodified line798081828384855 unmodified lines91929394959697989910010110210334 unmodified linesmatch goal.goal_type:case "survive" | "call_for_help":suggested: list[ActionKind] = ["move", "speak"]if _goal_target_in_range(world, npc, goal):suggested.insert(1, "attack")return ActionHints(suggested_actions=suggested,reason=("A threat is nearby: moving away, calling for help, pleading, ""defending, or attacking back are the most plausible responses"),)case "pursue_and_attack_target":if _goal_target_in_range(world, npc, goal):return ActionHints(suggested_actions=["attack", "speak"],reason="The hostile directive target is within striking range",)return ActionHints(4 unmodified linescase "retaliate":if _goal_target_in_range(world, npc, goal):return ActionHints(suggested_actions=["attack", "speak", "move"],reason="The recent attacker is within reach",)return ActionHints(2 unmodified lines)case "help_or_defend":helping: list[ActionKind] = ["speak", "move"]if _goal_target_in_range(world, npc, goal):helping.insert(0, "attack")return ActionHints(suggested_actions=helping,reason="Someone nearby is being harmed; helping or defending is most plausible",1 unmodified linecase "respond_to_event" | "investigate":return ActionHints(suggested_actions=["move", "speak"],reason="Something suspicious happened; investigating or watching is most plausible",)5 unmodified linescase "routine_life":return ActionHints(suggested_actions=["move", "speak", "use", "transfer"],reason="Nothing urgent is happening; everyday activity is most plausible",)return ActionHints(suggested_actions=["move", "speak"],reason="Unknown goal; cautious observation and communication are the safest defaults",)
100 unmodified lines101102103104105106107100 unmodified linesif distance_between(npc, target) <= ATTACK_RADIUS:return NpcDirective(npc_id=npc.id,action="strike",target_npc_id=target.id,message=directive.message,memory=memory,100 unmodified lines101102103104105106107100 unmodified linesif distance_between(npc, target) <= ATTACK_RADIUS:return NpcDirective(npc_id=npc.id,action="attack",target_npc_id=target.id,message=directive.message,memory=memory,
4 unmodified lines56789101112131416 unmodified lines3132333435367 unmodified lines44454647484912 unmodified lines6263646566674 unmodified linesfrom god_simulator.domain import Vec3, WorldState# The public action surface: every NPC decision is one of these six primitives.# Legacy action names (walk, talk, attack, flee, ...) are accepted as raw# strings at parse/validation boundaries and normalized to primitives there.PrimitiveActionKind: TypeAlias = Literal["move", "speak", "strike", "use", "transfer", "idle"]# Survival worlds keep a richer role-gated action surface that resolves inside# the survival engine (simulation/survival.py) instead of the primitive executor.SurvivalActionKind: TypeAlias = Literal[16 unmodified lines"flee","defend","attack",]ActionKind: TypeAlias = PrimitiveActionKind | SurvivalActionKind7 unmodified linestarget_entity_id: str | None = Noneresource_id: str | None = Noneresource_type: str | None = Noneamount: int | None = Nonecommunication_intent: str | None = Nonemessage: str | None = None12 unmodified linestarget_entity_id: str | None = Noneresource_id: str | None = Noneresource_type: str | None = Noneamount: int | None = Nonecommunication_intent: str | None = Nonemessage: str | None = None4 unmodified lines56789101112131416 unmodified lines3132333435363738397 unmodified lines474849505152535412 unmodified lines67686970717273744 unmodified linesfrom god_simulator.domain import Vec3, WorldState# The public action surface: every NPC decision is one of these primitives.# Legacy action names (walk, talk, attack, flee, ...) are accepted as raw# strings at parse/validation boundaries and normalized to primitives there.PrimitiveActionKind: TypeAlias = Literal["move", "speak", "attack", "use", "transfer", "vote"]# Survival worlds keep a richer role-gated action surface that resolves inside# the survival engine (simulation/survival.py) instead of the primitive executor.SurvivalActionKind: TypeAlias = Literal[16 unmodified lines"flee","defend","attack","vote","strike","idle",]ActionKind: TypeAlias = PrimitiveActionKind | SurvivalActionKind7 unmodified linestarget_entity_id: str | None = Noneresource_id: str | None = Noneresource_type: str | None = Noneuse_type: str | None = Noneparams: dict[str, Any] | None = Noneamount: int | None = Nonecommunication_intent: str | None = Nonemessage: str | None = None12 unmodified linestarget_entity_id: str | None = Noneresource_id: str | None = Noneresource_type: str | None = Noneuse_type: str | None = Noneparams: dict[str, Any] | None = Noneamount: int | None = Nonecommunication_intent: str | None = Nonemessage: str | None = None
36 unmodified lines37383940414223 unmodified lines66676869707172737475767778798081828384858633 unmodified lines12012112212312412512612712812913013113213313413513613713813914014113 unmodified lines1551561571581591601611621631641 unmodified line1661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092106 unmodified lines2172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522531 unmodified line25525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428581 unmodified lines3673683693703713721 unmodified line3743753763773783793806 unmodified lines38738838939039139228 unmodified lines421422423424425426427125 unmodified lines55355455555655755855956056156266 unmodified lines6296306316326336346356366376386396406412 unmodified lines64464564664764864965039 unmodified lines6906916926936946958 unmodified lines70470570670770870971071171211 unmodified lines7247257267277287298 unmodified lines73873974074174274374474574674774874975075175275375475575651 unmodified lines8088098108118128133 unmodified lines817818819820821822823824825826827828100 unmodified lines9299309319329339341 unmodified line93693793893994094194294394494583 unmodified lines10291030103110321033103445 unmodified lines1080108110821083108410851086108716 unmodified lines11041105110611071108110911104 unmodified lines11151116111711181119112011 unmodified lines1132113311341135113611378 unmodified lines1146114711481149115011511152115332 unmodified lines118611871188118911901191119211937 unmodified lines12011202120312041205120612071 unmodified line120912101211121212131214121540 unmodified lines125612571258125912601261126236 unmodified linesfrom god_simulator.simulation.perception import CitizenPerceptionfrom god_simulator.simulation.roles import normalize_rolefrom god_simulator.simulation.survival import (is_survival_world,allowed_actions_for_npc,suggested_actions_for_npc,23 unmodified lines"parameters": {"type": "object","properties": {"target_id": {"type": "string","description": "Optional visible NPC, beast, or resource node id.",},"target_x": {"type": "number","description": "Optional desired x coordinate.",},"target_z": {"type": "number","description": "Optional desired z coordinate.",},"away": {"type": "boolean","description": "Move away from the target/threat instead of toward it.",},},"required": [],33 unmodified lines},},},"strike": {"type": "function","function": {"name": "strike","description": ("Attack a nearby NPC or beast. The engine resolves movement, damage, and death."),"parameters": {"type": "object","properties": {"target_id": {"type": "string","description": "Visible NPC or beast id to attack.",}},"required": ["target_id"],"additionalProperties": False,},},13 unmodified lines"type": "string","description": "Nearby resource node id to gather from.",},"item": {"type": "string","enum": ["food", "herbs"],"description": "Inventory item to consume.",},},"required": [],1 unmodified line},},},"go_home": {"type": "function","function": {"name": "go_home","description": "Move into the nearest completed house to regain safety.","parameters": {"type": "object","properties": {},"required": [],"additionalProperties": False,},},},"patrol": {"type": "function","function": {"name": "patrol","description": "Guard action: patrol between village houses and intercept threats.","parameters": {"type": "object","properties": {},"required": [],"additionalProperties": False,},},},"build": {"type": "function","function": {"name": "build","description": "Builder action: spend wood to start or continue building a house.","parameters": {"type": "object","properties": {},"required": [],"additionalProperties": False,},},},"transfer": {"type": "function","function": {6 unmodified lines"properties": {"target_id": {"type": "string","description": "Nearby NPC id.",},"resource_type": {"type": "string","enum": ["food", "herbs", "wood", "weapon"],},"amount": {"type": "integer", "minimum": 1, "maximum": 5},"take": {"type": "boolean","description": "Steal from the target instead of giving.",},},"required": ["target_id"],"additionalProperties": False,},},},"idle": {"type": "function","function": {"name": "idle","description": "Do nothing this tick: wait, observe, or hold position defensively.","parameters": {"type": "object","properties": {"intent": {"type": "string","description": "Optional flavor, e.g. observe or defend.",}},"required": [],"additionalProperties": False,},},1 unmodified line}PRIMITIVE_TOOL_IDS = ("move", "speak", "strike", "use", "transfer", "idle")def primitive_tools() -> list[dict[str, Any]]:return [TOOL_DEFINITIONS[tool_id] for tool_id in PRIMITIVE_TOOL_IDS]def survival_tools_for_role(role: str) -> list[dict[str, Any]]:"""Primitives plus role-gated survival extras (GAME_DESIGN role whitelists).Builders never see strike, only guards see patrol, only builders see build;everyone can go_home. The engine still re-validates every request.Pass role="unrestricted" to expose every tool."""tool_ids = list(PRIMITIVE_TOOL_IDS) + ["go_home"]if role == "unrestricted":tool_ids += ["patrol", "build"]return [TOOL_DEFINITIONS[tool_id] for tool_id in dict.fromkeys(tool_ids)]normalized = normalize_role(role)if normalized == "guard":tool_ids.append("patrol")if normalized == "builder":tool_ids = [tool_id for tool_id in tool_ids if tool_id != "strike"]tool_ids.append("build")return [TOOL_DEFINITIONS[tool_id] for tool_id in tool_ids]_UNSET = object() # sentinel: handle all NPCs (backward-compatible default)81 unmodified linesassert self._config.model is not Nonedirectives: list[NpcDirective] = []if self._connector_id_filter is _UNSET:living_npcs = [npc for npc in world.npcs if is_alive(npc)]else:1 unmodified linenpc for npc in world.npcsif is_alive(npc) and npc.connector_id == self._connector_id_filter]directives.extend(self._call_model_for_npcs(world, next_tick, living_npcs))missing_npcs = _missing_npcs(living_npcs, directives)if missing_npcs:6 unmodified linesdirectives.extend(result.directives)ledger_entries.extend(result.ledger_entries)return TickPlan(source=self.name,directives=_dedupe_directives(directives),28 unmodified linesworld: WorldState,next_tick: int,npc: Npc,) -> list[NpcDirective]:assert self._config.model is not Nonellm_compact_memory(npc, self._chat_completer, self._config.model)request = self._build_request(world, next_tick, npc)125 unmodified linesif is_survival_world(world):survival_goal = select_survival_goal(npc, world)suggested = suggested_actions_for_npc(npc, survival_goal)messages = _build_survival_messages(world, next_tick, npc, survival_goal, suggested)role_key = "unrestricted" if npc.unrestricted_actions else npc.roletools = survival_tools_for_role(role_key)else:perception, goal = refresh_citizen_motivation(world, npc)hints = build_action_hints(world, npc, perception, goal)66 unmodified lines"do not invent npc ids",f"move covers at most {MAX_WALK_DISTANCE:g} world units per tick",f"speak requires target distance <= {TALK_RADIUS:g} world units",f"strike requires target distance <= {ATTACK_RADIUS:g} world units",f"each NPC can see only visible_npcs within {VISIBLE_RADIUS:g} world units","visible_npcs is the full set of other NPCs you can currently observe","do not target dead NPCs","your current health and recent observations should affect your decision","treat current_goal as the strongest behavioral priority","treat god_directive as strong input, already interpreted by current_goal","your personality should shape action choice and tone","message must be direct speech, not narration about yourself","the simulation will report what happened after your action",2 unmodified lines"the engine resolves damage and death"),("out-of-range speak or strike is automatically converted ""into movement toward the target"),],39 unmodified lines"own_state": {"name": npc.name,"role": npc.role,"health": round(npc.health),"hunger": round(npc.hunger),"fear": round(npc.fear),8 unmodified lines"herbs": npc.inventory_herbs,"wood": npc.inventory_wood,"weapon": npc.inventory_weapon,},},"goal": goal,"active_directive": active_directive_payload(npc, tick=next_tick),"nearby_threats": _survival_nearby_threats(world, npc),"nearby_allies": _survival_nearby_allies(world, npc),11 unmodified lines"content": (f"You are {npc.name}, a {npc.role}. Call exactly one tool for the next tick. ""Use only allowed_actions and visible ids from the payload. Do not invent ids. ""Do not write prose. The engine validates and applies effects."),},8 unmodified linesif role == "guard":return ["Protect living villagers and houses from live threats.","Attack only visible beasts or hostile live NPCs.","Patrol when no threat is reachable.","Never gather resources.",]if role == "builder":return ["Build or gather wood when work is safe.","Go home or flee from live threats.","Share or ask for supplies only with live nearby allies.","Never attack.",]return ["Gather reachable food, herbs, wood, or weapons when safe.","Eat or heal before routine work when urgent.","Flee or call for help from live threats.","Transfer supplies only to live nearby allies.",51 unmodified lines"id": other.id,"name": other.name,"role": other.role,"distance": round(distance, 2),"trust": round(npc.relationships.get(other.id, 0.0), 2),"hp": round(other.health),3 unmodified lines"herbs": other.inventory_herbs,"wood": other.inventory_wood,"weapon": other.inventory_weapon,},})return sorted(allies, key=lambda item: (item["distance"], item["id"]))[:5]def _survival_reachable_resources(world: WorldState, npc: Npc) -> list[dict[str, Any]]:resources: list[dict[str, Any]] = []for node in world.resource_nodes:100 unmodified lines}def _npc_request_entry(*,npc: Npc,1 unmodified linemodel: str,allowed_actions: list[str],) -> dict[str, Any]:return {"phase": "npc_request","npc_id": npc.id,"model": model,"allowed_actions": allowed_actions,"messages": request.get("messages"),"request": request,83 unmodified linesif not isinstance(function, dict):continuetool_name = function.get("name")if tool_name not in TOOL_DEFINITIONS:continuetry:45 unmodified linespayload: dict[str, Any] = {"npc_id": resolved_npc_id, "action": action}if len(tokens) > 1 and action in {"use", "move"}:payload["resource_id"] = tokens[1]if len(tokens) > 1 and action in {"transfer", "speak", "strike"}:payload["target_id"] = tokens[1]return _actions_to_plan([payload], world, source=source)16 unmodified linescontinuetarget = _target_from_action(action, half_width=half_width, half_depth=half_depth)raw_target_id = action.get("target_id") or action.get("target_npc_id")target_npc_id = _optional_known_npc_id(raw_target_id, world)target_entity_id = (None if target_npc_id else _optional_known_entity_id(raw_target_id, world)4 unmodified linesresource_type = _optional_resource_type(action.get("resource_type") or action.get("item"))amount = _optional_amount(action.get("amount"))communication_intent = _optional_communication_intent(action.get("intent"))message = _optional_short_text(action.get("message"), limit=140)11 unmodified linestarget_entity_id=target_entity_id,resource_id=resource_id,resource_type=resource_type,amount=amount,communication_intent=communication_intent,message=message,8 unmodified linesdef _action_kind(raw: object) -> ActionKind | None:if raw in ("move", "speak", "strike", "use", "transfer", "idle"):return rawif raw in (# Survival actions: resolved by the survival engine in survival worlds;# the autopilot replaces them with a primitive in social worlds.32 unmodified linesdef _optional_known_entity_id(raw: object, world: WorldState) -> str | None:if not isinstance(raw, str):return Nonebeast_ids = {beast.id for beast in world.beasts}if raw in beast_ids:return rawreturn None7 unmodified linesdef _optional_resource_type(raw: object) -> str | None:if raw in {"food", "herbs", "wood", "weapon"}:return rawreturn None1 unmodified linedef _optional_amount(raw: object) -> int | None:if isinstance(raw, bool) or not isinstance(raw, int):return Nonereturn max(1, min(5, raw))def _optional_communication_intent(raw: object) -> str | None:40 unmodified lineshalf_width: float,half_depth: float,) -> Vec3 | None:if "target_x" in action or "target_z" in action:x = action.get("target_x")z = action.get("target_z")else:36 unmodified lines3738394041424323 unmodified lines6768697071727374757677787933 unmodified lines11311411511611711811912012112212312412512612712812913013113213313413513613 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711 unmodified line1731741751761771786 unmodified lines1851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312321 unmodified line23423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228381 unmodified lines3653663673683693703711 unmodified line3733743753763773783793803813826 unmodified lines38939039139239339439539639739839928 unmodified lines428429430431432433434125 unmodified lines56056156256356456556656756856957057157257357457557657757857958066 unmodified lines6476486496506516526536546556566576586592 unmodified lines66266366466566666766839 unmodified lines7087097107117127137148 unmodified lines72372472572672772872973073173273373411 unmodified lines7467477487497507517528 unmodified lines76176276376476576676776876977077177277377477577677777877951 unmodified lines8318328338348358368373 unmodified lines841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921100 unmodified lines102210231024102510261027102810291030103110321033103410351036103710381039104010411 unmodified line104310441045104610471048104910501051105210531054105510561057105883 unmodified lines1142114311441145114611471148114945 unmodified lines1195119611971198119912001201120216 unmodified lines1219122012211222122312241225122612271228122912304 unmodified lines1235123612371238123912401241124211 unmodified lines125412551256125712581259126012618 unmodified lines127012711272127312741275127612771278127932 unmodified lines131213131314131513161317131813191320132113221323132413251326132713287 unmodified lines13361337133813391340134113421 unmodified line134413451346134713481349135040 unmodified lines139113921393139413951396139713981399140036 unmodified linesfrom god_simulator.simulation.perception import CitizenPerceptionfrom god_simulator.simulation.roles import normalize_rolefrom god_simulator.simulation.survival import (active_election_for_npc,is_survival_world,allowed_actions_for_npc,suggested_actions_for_npc,23 unmodified lines"parameters": {"type": "object","properties": {"x": {"type": "number","description": "Destination X coordinate.",},"z": {"type": "number","description": "Destination Z coordinate.",},},"required": [],33 unmodified lines},},},"attack": {"type": "function","function": {"name": "attack","description": ("Attack a valid nearby threat or hostile target. Give target_entity_id ""to choose a specific target, or omit it to attack the nearest valid threat. ""The engine resolves approach, range and damage."),"parameters": {"type": "object","properties": {"target_entity_id": {"type": "string","description": "Visible NPC, beast, or object id to attack.",}},"required": [],"additionalProperties": False,},},13 unmodified lines"type": "string","description": "Nearby resource node id to gather from.",},"target_entity_id": {"type": "string","description": "World object/entity id to use.",},"resource_type": {"type": "string","enum": ["food", "herbs", "wood", "coins"],"description": "Optional resource type for consuming, crafting or treasury actions.",},"use_type": {"type": "string","description": "Use mode, e.g. eat, heal, gather, build, repair, craft, fire.",},"params": {"type": "object","description": "Additional structured parameters for the selected use_type.",},},"required": [],1 unmodified line},},},"transfer": {"type": "function","function": {6 unmodified lines"properties": {"target_id": {"type": "string","description": "Nearby NPC, treasury, storage, or object target id.",},"target_npc_id": {"type": "string","description": "Nearby NPC id, if target is a character.",},"target_entity_id": {"type": "string","description": "Treasury/storage/object target id.",},"resource_type": {"type": "string","enum": ["food", "herbs", "wood", "weapon", "coins"],},"amount": {"type": "integer", "minimum": 1, "maximum": 20},"take": {"type": "boolean","description": "Steal/take instead of give.",},},"required": ["resource_type", "amount"],"additionalProperties": False,},},},"vote": {"type": "function","function": {"name": "vote","description": ("Vote for a ruler candidate during an active election. Use candidate_id ""from the current election candidate list."),"parameters": {"type": "object","properties": {"candidate_id": {"type": "string","description": "NPC id of the candidate.",}},"required": ["candidate_id"],"additionalProperties": False,},},1 unmodified line}PRIMITIVE_TOOL_IDS = ("move", "speak", "attack", "use", "transfer")def primitive_tools() -> list[dict[str, Any]]:return [TOOL_DEFINITIONS[tool_id] for tool_id in PRIMITIVE_TOOL_IDS]def _public_action_suggestions(actions: Sequence[str]) -> list[str]:mapped: list[str] = []for action in actions:if action in {"attack", "strike"}:public = "attack"elif action in {"gather", "consume", "eat", "heal", "build", "repair", "craft"}:public = "use"elif action in {"move","move_to","move_to_resource","go_home","patrol","flee","wander","find_food","find_herbs",}:public = "move"elif action in {"communicate", "talk", "speak", "request_trade", "trade"}:public = "speak"elif action in {"transfer", "steal"}:public = "transfer"else:continueif public not in mapped:mapped.append(public)return mapped or ["move", "speak", "use", "transfer"]def survival_tools_for_role(role: str) -> list[dict[str, Any]]:"""Return the unified public tool surface for every role.Roles now shape prompt context and suggestions only. They do not removebase tools from the LLM-facing contract."""return primitive_tools()_UNSET = object() # sentinel: handle all NPCs (backward-compatible default)81 unmodified linesassert self._config.model is not Nonedirectives: list[NpcDirective] = []ledger_entries: list[dict[str, Any]] = []if self._connector_id_filter is _UNSET:living_npcs = [npc for npc in world.npcs if is_alive(npc)]else:1 unmodified linenpc for npc in world.npcsif is_alive(npc) and npc.connector_id == self._connector_id_filter]npc_by_id = {npc.id: npc for npc in living_npcs}for result in self._call_model_for_npcs(world, next_tick, living_npcs):directives.extend(result.directives)ledger_entries.extend(result.ledger_entries)missing_npcs = _missing_npcs(living_npcs, directives)if missing_npcs:6 unmodified linesdirectives.extend(result.directives)ledger_entries.extend(result.ledger_entries)# Stamp model attribution on every entry (response/fallback as well as# request) so the admin log can show which model drove each NPC.for entry in ledger_entries:_stamp_model_attribution(entry, npc_by_id.get(str(entry.get("npc_id"))), self._config.model)return TickPlan(source=self.name,directives=_dedupe_directives(directives),28 unmodified linesworld: WorldState,next_tick: int,npc: Npc,) -> NpcCallResult:assert self._config.model is not Nonellm_compact_memory(npc, self._chat_completer, self._config.model)request = self._build_request(world, next_tick, npc)125 unmodified linesif is_survival_world(world):survival_goal = select_survival_goal(npc, world)allowed = list(PRIMITIVE_TOOL_IDS)if active_election_for_npc(world, npc, tick=next_tick) is not None:allowed.append("vote")suggested = _public_action_suggestions(suggested_actions_for_npc(npc, survival_goal))if "vote" in allowed and "vote" not in suggested:suggested.insert(0, "vote")messages = _build_survival_messages(world,next_tick,npc,survival_goal,suggested,allowed_actions=allowed,)tools = [TOOL_DEFINITIONS[tool_id] for tool_id in allowed]else:perception, goal = refresh_citizen_motivation(world, npc)hints = build_action_hints(world, npc, perception, goal)66 unmodified lines"do not invent npc ids",f"move covers at most {MAX_WALK_DISTANCE:g} world units per tick",f"speak requires target distance <= {TALK_RADIUS:g} world units",f"attack requires target distance <= {ATTACK_RADIUS:g} world units",f"each NPC can see only visible_npcs within {VISIBLE_RADIUS:g} world units","visible_npcs is the full set of other NPCs you can currently observe","do not target dead NPCs","your current health and recent observations should affect your decision","treat current_goal as the strongest behavioral priority","treat current policy/directive context as behavioral input only","your personality should shape action choice and tone","message must be direct speech, not narration about yourself","the simulation will report what happened after your action",2 unmodified lines"the engine resolves damage and death"),("out-of-range speak or attack is automatically converted ""into movement toward the target"),],39 unmodified lines"own_state": {"name": npc.name,"role": npc.role,"position": {"x": npc.position.x, "z": npc.position.z},"health": round(npc.health),"hunger": round(npc.hunger),"fear": round(npc.fear),8 unmodified lines"herbs": npc.inventory_herbs,"wood": npc.inventory_wood,"weapon": npc.inventory_weapon,"coins": npc.inventory_coins,},},"goal": goal,"country": _country_payload(world, npc),"world_countries": _world_countries_payload(world, npc),"active_directive": active_directive_payload(npc, tick=next_tick),"nearby_threats": _survival_nearby_threats(world, npc),"nearby_allies": _survival_nearby_allies(world, npc),11 unmodified lines"content": (f"You are {npc.name}, a {npc.role}. Call exactly one tool for the next tick. ""Use only allowed_actions and visible ids from the payload. Do not invent ids. ""Your role is context, not a tool restriction. ""Do not write prose. The engine validates and applies effects."),},8 unmodified linesif role == "guard":return ["Protect living villagers and houses from live threats.","You tend to attack visible beasts or hostile live NPCs.","When no threat is reachable, you tend to move through patrol routes.","You can still use, speak, move or transfer when the situation calls for it.",]if role == "builder":return ["You tend to build, repair, and gather wood when work is safe.","You tend to seek shelter or flee from live threats.","Share or ask for supplies only with live nearby allies.","You can still use the same base tools as everyone else.",]return ["You tend to gather reachable food, herbs, wood, or weapons when safe.","Eat or heal before routine work when urgent.","Flee or call for help from live threats.","Transfer supplies only to live nearby allies.",51 unmodified lines"id": other.id,"name": other.name,"role": other.role,"country_id": other.country_id,"distance": round(distance, 2),"trust": round(npc.relationships.get(other.id, 0.0), 2),"hp": round(other.health),3 unmodified lines"herbs": other.inventory_herbs,"wood": other.inventory_wood,"weapon": other.inventory_weapon,"coins": other.inventory_coins,},})return sorted(allies, key=lambda item: (item["distance"], item["id"]))[:5]def _country_payload(world: WorldState, npc: Npc) -> dict[str, Any] | None:if npc.country_id is None:return Nonecountry = next((item for item in world.countries if item.id == npc.country_id), None)if country is None:return Noneelection = active_election_for_npc(world, npc)return {"id": country.id,"name": country.name,"badge": country.badge,"ruler_id": country.ruler_id,"policy": country.policy,"treasury": dict(country.treasury.resources) if country.treasury else {},"treasury_id": country.treasury.id if country.treasury else None,"treasury_position": Noneif country.treasury is Noneelse {"x": country.treasury.position.x, "z": country.treasury.position.z},"cannon": Noneif country.cannon is Noneelse {"id": country.cannon.id,"position": {"x": country.cannon.position.x, "z": country.cannon.position.z},"operator_id": country.cannon.operator_id,"cooldown_until_tick": country.cannon.cooldown_until_tick,},"next_election_tick": country.next_election_tick,"election": Noneif election is Noneelse {"start_tick": election.start_tick,"end_tick": election.end_tick,"candidate_ids": list(election.candidate_ids),"already_voted": npc.id in election.votes,},}def _world_countries_payload(world: WorldState, npc: Npc) -> list[dict[str, Any]]:"""Public info on every country so an NPC knows the rival, its ruler/policy,and where the rival treasury/cannon is (needed to steal or strike)."""overview: list[dict[str, Any]] = []for country in world.countries:ruler = next((c for c in world.npcs if c.id == country.ruler_id), None)treasury_pos = (Noneif country.treasury is Noneelse {"x": country.treasury.position.x, "z": country.treasury.position.z})overview.append({"id": country.id,"name": country.name,"is_own": country.id == npc.country_id,"ruler_id": country.ruler_id,"ruler_name": ruler.name if ruler else None,"policy": country.policy,"population": len(country.citizen_ids),"treasury_id": country.treasury.id if country.treasury else None,"treasury_position": treasury_pos,# The rival's stored resources are public knowledge worth stealing."treasury": dict(country.treasury.resources) if country.treasury else {},"cannon_id": country.cannon.id if country.cannon else None,})return overviewdef _survival_reachable_resources(world: WorldState, npc: Npc) -> list[dict[str, Any]]:resources: list[dict[str, Any]] = []for node in world.resource_nodes:100 unmodified lines}def _stamp_model_attribution(entry: dict[str, Any],npc: Npc | None,model: str | None,) -> None:"""Ensure a ledger entry says which model/profile is driving the NPC."""if npc is None:returnentry.setdefault("model", model or "")entry.setdefault("model_profile", npc.model_profile_id or npc.connector_id or "default")entry.setdefault("connector_id", npc.connector_id)entry.setdefault("country_id", npc.country_id)def _npc_request_entry(*,npc: Npc,1 unmodified linemodel: str,allowed_actions: list[str],) -> dict[str, Any]:# `model_profile`/`connector_id` make it explicit, per NPC, which model is# driving it (e.g. the Qwen country connector vs the default model). This is# what the admin log surfaces so a viewer can see "npc-007 -> qwen".return {"phase": "npc_request","npc_id": npc.id,"model": model,"model_profile": npc.model_profile_id or npc.connector_id or "default","connector_id": npc.connector_id,"country_id": npc.country_id,"allowed_actions": allowed_actions,"messages": request.get("messages"),"request": request,83 unmodified linesif not isinstance(function, dict):continuetool_name = function.get("name")if tool_name == "strike":tool_name = "attack"if tool_name not in TOOL_DEFINITIONS:continuetry:45 unmodified linespayload: dict[str, Any] = {"npc_id": resolved_npc_id, "action": action}if len(tokens) > 1 and action in {"use", "move"}:payload["resource_id"] = tokens[1]if len(tokens) > 1 and action in {"transfer", "speak", "attack", "strike"}:payload["target_id"] = tokens[1]return _actions_to_plan([payload], world, source=source)16 unmodified linescontinuetarget = _target_from_action(action, half_width=half_width, half_depth=half_depth)raw_target_id = (action.get("target_id")or action.get("target_npc_id")or action.get("target_entity_id")or action.get("candidate_id"))target_npc_id = _optional_known_npc_id(raw_target_id, world)target_entity_id = (None if target_npc_id else _optional_known_entity_id(raw_target_id, world)4 unmodified linesresource_type = _optional_resource_type(action.get("resource_type") or action.get("item"))use_type = _optional_short_text(action.get("use_type"), limit=40)params = action.get("params") if isinstance(action.get("params"), dict) else Noneamount = _optional_amount(action.get("amount"))communication_intent = _optional_communication_intent(action.get("intent"))message = _optional_short_text(action.get("message"), limit=140)11 unmodified linestarget_entity_id=target_entity_id,resource_id=resource_id,resource_type=resource_type,use_type=use_type,params=params,amount=amount,communication_intent=communication_intent,message=message,8 unmodified linesdef _action_kind(raw: object) -> ActionKind | None:if raw in ("move", "speak", "attack", "use", "transfer", "vote", "idle"):return cast(ActionKind, raw)if raw == "strike":return "attack"if raw in (# Survival actions: resolved by the survival engine in survival worlds;# the autopilot replaces them with a primitive in social worlds.32 unmodified linesdef _optional_known_entity_id(raw: object, world: WorldState) -> str | None:if not isinstance(raw, str):return Noneif raw in {beast.id for beast in world.beasts}:return raw# Treasuries and cannons are engine objects an NPC can target with# transfer/use (deposit, steal, fire). Without these the engine would null# the target and silently degrade a treasury deposit into an NPC transfer.for country in world.countries:if country.treasury is not None and raw == country.treasury.id:return rawif country.cannon is not None and raw == country.cannon.id:return rawif raw in {house.id for house in world.houses}:return rawreturn None7 unmodified linesdef _optional_resource_type(raw: object) -> str | None:if raw in {"food", "herbs", "wood", "weapon", "coins"}:return rawreturn None1 unmodified linedef _optional_amount(raw: object) -> int | None:if isinstance(raw, bool) or not isinstance(raw, int):return Nonereturn max(1, min(20, raw))def _optional_communication_intent(raw: object) -> str | None:40 unmodified lineshalf_width: float,half_depth: float,) -> Vec3 | None:if "x" in action or "z" in action:x = action.get("x")z = action.get("z")elif "target_x" in action or "target_z" in action:x = action.get("target_x")z = action.get("target_z")else:
12345621 unmodified lines28293031323310 unmodified lines4445464748495051525354556 unmodified lines62636465from __future__ import annotationsfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom god_simulator.domain import WorldStatefrom god_simulator.simulation.connectors.base import NpcDirective, TickPlan, WorldSimulator21 unmodified linesrouted_ids = {npc.id for npc in world.npcs if npc.connector_id in self._routes}all_directives: list[NpcDirective] = []source_parts: list[str] = []# Run all route simulators and the default simulator in parallel.10 unmodified linesfor connector_id, sim in self._routes.items():plan = results[connector_id]filtered = [d for d in plan.directives if npc_connector.get(d.npc_id) == connector_id]if filtered:all_directives.extend(filtered)source_parts.append(plan.source)default_plan = results["__default__"]filtered_default = [d for d in default_plan.directives if d.npc_id not in routed_ids]if filtered_default:all_directives.extend(filtered_default)source_parts.append(default_plan.source)6 unmodified linesunique.append(d)source = "+".join(dict.fromkeys(source_parts)) or self.namereturn TickPlan(source=source, directives=unique)123456721 unmodified lines293031323334353637383910 unmodified lines5051525354555657585960616263646566676869707172736 unmodified lines80818283from __future__ import annotationsfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom typing import Anyfrom god_simulator.domain import WorldStatefrom god_simulator.simulation.connectors.base import NpcDirective, TickPlan, WorldSimulator21 unmodified linesrouted_ids = {npc.id for npc in world.npcs if npc.connector_id in self._routes}all_directives: list[NpcDirective] = []# Ledger entries (npc_request/npc_response/npc_fallback) must survive the# merge: the admin log and the goal's "every LLM call is recorded"# requirement depend on them. They are filtered by the same ownership# rule as the directives so each NPC is logged exactly once.all_ledger_entries: list[dict[str, Any]] = []source_parts: list[str] = []# Run all route simulators and the default simulator in parallel.10 unmodified linesfor connector_id, sim in self._routes.items():plan = results[connector_id]filtered = [d for d in plan.directives if npc_connector.get(d.npc_id) == connector_id]owned_entries = [entryfor entry in plan.ledger_entriesif npc_connector.get(str(entry.get("npc_id"))) == connector_id]all_ledger_entries.extend(owned_entries)if filtered:all_directives.extend(filtered)source_parts.append(plan.source)default_plan = results["__default__"]filtered_default = [d for d in default_plan.directives if d.npc_id not in routed_ids]default_entries = [entryfor entry in default_plan.ledger_entriesif entry.get("npc_id") is None or entry.get("npc_id") not in routed_ids]all_ledger_entries.extend(default_entries)if filtered_default:all_directives.extend(filtered_default)source_parts.append(default_plan.source)6 unmodified linesunique.append(d)source = "+".join(dict.fromkeys(source_parts)) or self.namereturn TickPlan(source=source, directives=unique, ledger_entries=all_ledger_entries)
4 unmodified lines5678910111213141526 unmodified lines4243444546474849505152532 unmodified lines565758596061626364656667686970717273741 unmodified line767778798081828384858687888922 unmodified lines11211311411511611776 unmodified lines1941951961971981992002012022032042052062072082098 unmodified lines2182192202212222232242252262275 unmodified lines2332342352362372382392402412424 unmodified lines2472482492502512522532542552562572582592602612622632642654 unmodified lines2702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043054 unmodified linesfrom god_simulator.config import GameConfigfrom god_simulator.domain import (Beast,House,MemoryEntry,Npc,ResourceNode,Terrain,Vec3,WorldState,)26 unmodified lines_ROLES = ["gatherer", "gatherer", "gatherer", "guard", "guard", "builder"]_QWEN_NAMES = ["Kira", "Lena", "Mira", "Niko", "Oleg", "Pavel"]_BARB_NAMES = ["Borg", "Drak", "Hrag", "Krull", "Morg", "Ravn","Skur", "Thax", "Vrex", "Wulf", "Xorn", "Yrag","Zark", "Brox", "Crag", "Dusk",]def create_world(config: GameConfig) -> WorldState:rng = random.Random(config.world.seed)2 unmodified lineswidth=config.world.width,depth=config.world.depth,)village_npcs = [_spawn_npc(index=index, config=config, rng=rng) for index in range(config.npcs.count)]qwen_npcs = _spawn_qwen_npcs(config) if config.world.survival else []barbarians = _spawn_barbarians(config) if config.world.survival else []houses = _spawn_houses(config)if config.world.survival:_seed_survival_relationships(village_npcs + qwen_npcs)_assign_starting_homes(village_npcs + qwen_npcs, houses)_initialize_importance(village_npcs + qwen_npcs + barbarians)all_npcs = village_npcs + qwen_npcs + barbarianspopulation = sum(1 for npc in all_npcs if npc.health > 0)return WorldState(tick=0,seed=config.world.seed,terrain=terrain,1 unmodified lineresource_nodes=_spawn_resource_nodes(config),beasts=_spawn_beasts(config),houses=houses,population=population,peak_population=population,overseer_mode=config.overseer.mode,overseer_cycle_ticks=config.overseer.cycle_ticks,)def _spawn_npc(*, index: int, config: GameConfig, rng: random.Random) -> Npc:half_width = config.world.width / 2half_depth = config.world.depth / 222 unmodified linesname=name,role=role,position=Vec3(x=x, y=0.0, z=z),attack_damage=rng.randint(5, 15),memory=[MemoryEntry(tick=0, text=f"{name} arrived as a {role}.")],age=60 if config.world.survival else 0,76 unmodified linesif not config.world.survival:return []village_x = -(config.world.width / 2 * 2 / 3)return [House(id="house_001",position=Vec3(x=village_x, y=0.0, z=0.0),hp=60.0,max_hp=60.0,state="completed",build_progress=10,capacity=3,)]8 unmodified linesdef _assign_starting_homes(npcs: list[Npc], houses: list[House]) -> None:if not houses:returnhome = houses[0]for npc in npcs:npc.home_house_id = home.idhome.occupant_ids = [npc.id for npc in npcs[: home.capacity]]def _initialize_importance(npcs: list[Npc]) -> None:5 unmodified linesnpc.importance = round(1.0 + 2.0 * (1 / role_count), 3)def _spawn_qwen_npcs(config: GameConfig) -> list[Npc]:half_width = config.world.width / 2village_x = -(half_width * 2 / 3)# Cluster around the house (which sits at village_x, z=0)offsets = [(0.0, 0.0),(BLOCK_SIZE, 0.0),4 unmodified lines]npcs = []inv_rng = random.Random(f"{config.world.seed}:qwen_inventory")for i, (dx, dz) in enumerate(offsets):name = _QWEN_NAMES[i]npc = Npc(id=f"qwen-{i + 1:03d}",name=name,role="gatherer",position=Vec3(x=round(village_x + dx, 3), y=0.0, z=round(dz, 3)),attack_damage=inv_rng.randint(5, 12),memory=[MemoryEntry(tick=0, text=f"{name} joined the village as a free spirit.")],age=25,max_age=550,unrestricted_actions=True,connector_id="qwen",personality="curious and resourceful",hunger=15.0,safety=60.0,4 unmodified linesreturn npcsdef _spawn_barbarians(config: GameConfig) -> list[Npc]:half_width = config.world.width / 2half_depth = config.world.depth / 2barb_x = half_width * 2 / 3npcs = []inv_rng = random.Random(f"{config.world.seed}:barb_inventory")for i in range(16):col = i % 4row = i // 4dx = (col - 1.5) * BLOCK_SIZEdz = (row - 1.5) * (half_depth / 2)name = _BARB_NAMES[i]npc = Npc(id=f"barb-{i + 1:03d}",name=name,role="guard",position=Vec3(x=round(barb_x + dx, 3), y=0.0, z=round(dz, 3)),attack_damage=inv_rng.randint(12, 20),memory=[MemoryEntry(tick=0, text=f"{name} is a barbarian warrior on the warpath.")],age=30,max_age=350,connector_id=None,personality="aggressive barbarian",hunger=35.0,safety=0.0,inventory_food=inv_rng.randint(0, 1),inventory_weapon=1,)npcs.append(npc)return npcsdef _random_max_age(seed: int, index: int) -> int:4 unmodified lines56789101112131415161726 unmodified lines4445464748492 unmodified lines5253545556575859606162636465666768697071721 unmodified line74757677787980818283848586878889909122 unmodified lines11411511611711811912076 unmodified lines1971981992002012022032042052062072082092102112122132142152162172182192202212228 unmodified lines2312322332342352362372382392402412425 unmodified lines2482492502512522532542552564 unmodified lines2612622632642652662672682692702712722732742752762772782792802814 unmodified lines2862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353364 unmodified linesfrom god_simulator.config import GameConfigfrom god_simulator.domain import (Beast,CountryState,House,MemoryEntry,Npc,ResourceNode,Terrain,TreasuryState,Vec3,WorldState,)26 unmodified lines_ROLES = ["gatherer", "gatherer", "gatherer", "guard", "guard", "builder"]_QWEN_NAMES = ["Kira", "Lena", "Mira", "Niko", "Oleg", "Pavel"]def create_world(config: GameConfig) -> WorldState:rng = random.Random(config.world.seed)2 unmodified lineswidth=config.world.width,depth=config.world.depth,)village_npcs = [_spawn_npc(index=index, config=config, rng=rng, country_id="nemotron")for index in range(config.npcs.count)]qwen_npcs = _spawn_qwen_npcs(config, count=config.npcs.count) if config.world.survival else []houses = _spawn_houses(config)if config.world.survival:_seed_survival_relationships(village_npcs + qwen_npcs)_assign_starting_homes(village_npcs + qwen_npcs, houses)_initialize_importance(village_npcs + qwen_npcs)all_npcs = village_npcs + qwen_npcspopulation = sum(1 for npc in all_npcs if npc.health > 0)world = WorldState(tick=0,seed=config.world.seed,terrain=terrain,1 unmodified lineresource_nodes=_spawn_resource_nodes(config),beasts=_spawn_beasts(config),houses=houses,countries=_spawn_countries(config, all_npcs),population=population,population_cap=max(24, population + 8),peak_population=population,overseer_mode="off",overseer_cycle_ticks=0,)_assign_initial_rulers(world)return worlddef _spawn_npc(*, index: int, config: GameConfig, rng: random.Random, country_id: str) -> Npc:half_width = config.world.width / 2half_depth = config.world.depth / 222 unmodified linesname=name,role=role,position=Vec3(x=x, y=0.0, z=z),country_id=country_id,attack_damage=rng.randint(5, 15),memory=[MemoryEntry(tick=0, text=f"{name} arrived as a {role}.")],age=60 if config.world.survival else 0,76 unmodified linesif not config.world.survival:return []village_x = -(config.world.width / 2 * 2 / 3)qwen_x = config.world.width / 2 * 2 / 3return [House(id="house_nemotron_001",position=Vec3(x=village_x, y=0.0, z=0.0),hp=60.0,max_hp=60.0,state="completed",build_progress=10,capacity=3,),House(id="house_qwen_001",position=Vec3(x=qwen_x, y=0.0, z=0.0),hp=60.0,max_hp=60.0,state="completed",build_progress=10,capacity=3,),]8 unmodified linesdef _assign_starting_homes(npcs: list[Npc], houses: list[House]) -> None:if not houses:returnfor npc in npcs:home = min(houses, key=lambda house: abs(house.position.x - npc.position.x))npc.home_house_id = home.idfor house in houses:citizens = [npc.id for npc in npcs if npc.home_house_id == house.id]house.occupant_ids = citizens[: house.capacity]def _initialize_importance(npcs: list[Npc]) -> None:5 unmodified linesnpc.importance = round(1.0 + 2.0 * (1 / role_count), 3)def _spawn_qwen_npcs(config: GameConfig, *, count: int) -> list[Npc]:half_width = config.world.width / 2qwen_x = half_width * 2 / 3offsets = [(0.0, 0.0),(BLOCK_SIZE, 0.0),4 unmodified lines]npcs = []inv_rng = random.Random(f"{config.world.seed}:qwen_inventory")for i in range(count):dx, dz = offsets[i % len(offsets)]name = _QWEN_NAMES[i % len(_QWEN_NAMES)]npc = Npc(id=f"qwen-{i + 1:03d}",name=name,role="gatherer",position=Vec3(x=round(qwen_x + dx, 3), y=0.0, z=round(dz, 3)),attack_damage=inv_rng.randint(5, 12),memory=[MemoryEntry(tick=0, text=f"{name} joined Qwen as a free spirit.")],age=25,max_age=550,unrestricted_actions=True,connector_id="qwen",country_id="qwen",personality="curious and resourceful",hunger=15.0,safety=60.0,4 unmodified linesreturn npcsdef _spawn_countries(config: GameConfig, npcs: list[Npc]) -> list[CountryState]:if not config.world.survival:return []half_width = config.world.width / 2nemotron_x = -(half_width * 2 / 3)qwen_x = half_width * 2 / 3citizens_by_country = {"nemotron": [npc.id for npc in npcs if npc.country_id == "nemotron"],"qwen": [npc.id for npc in npcs if npc.country_id == "qwen"],}return [CountryState(id="nemotron",name="Nemotron",color="#4f8cff",badge="N",citizen_ids=citizens_by_country["nemotron"],treasury=TreasuryState(id="treasury_nemotron",position=Vec3(x=nemotron_x, y=0.0, z=BLOCK_SIZE * 1.5),resources={"food": 2, "herbs": 1, "wood": 20, "coins": 25},),),CountryState(id="qwen",name="Qwen",color="#d86bff",badge="Q",citizen_ids=citizens_by_country["qwen"],treasury=TreasuryState(id="treasury_qwen",position=Vec3(x=qwen_x, y=0.0, z=BLOCK_SIZE * 1.5),resources={"food": 2, "herbs": 1, "wood": 20, "coins": 25},),),]def _assign_initial_rulers(world: WorldState) -> None:for country in world.countries:ruler = next((npc for npc in world.living_npcs() if npc.id in country.citizen_ids), None)if ruler is None:continuecountry.ruler_id = ruler.idruler.special_status = "ruler"def _random_max_age(seed: int, index: int) -> int:
11 unmodified lines12131415161718192021222324252612 unmodified lines39404142434445464766 unmodified lines11411511611711811912 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715818 unmodified lines177178179180181182170 unmodified lines35335435535635735826 unmodified lines385386387388389390391178 unmodified lines570571572573574575247 unmodified lines823824825826827828829830831832833834835836837236 unmodified lines1074107510761077107810794 unmodified lines1084108510861087108810891090109110921093109410951096231 unmodified lines132813291330133113321333133478 unmodified lines141314141415141614171418141918 unmodified lines143814391440144114421443144414451446144714481449145014511452145341 unmodified lines14951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415255 unmodified lines15311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155722 unmodified lines15801581158215831584158515861587158815899 unmodified lines159916001601160216031604160516061607160895 unmodified lines1704170517061707170817091710171173 unmodified lines17851786178717881789179086 unmodified lines187718781879188018811882102 unmodified lines198519861987198819891990199119921993188 unmodified lines218221832184218521862187218821892190113 unmodified lines230423052306230723082309155 unmodified lines24652466246724682469247024712472247324742475247624772478247942 unmodified lines2522252325242525252625275 unmodified lines2533253425352536253725385 unmodified lines254425452546254725482549245 unmodified lines2795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822128 unmodified lines29512952295329542955295611 unmodified linesfrom __future__ import annotationsimport mathimport randomfrom god_simulator.domain import (Beast,House,MemoryEntry,MemoryEpisode,Npc,ResourceNode,Vec3,WorldEvent,WorldLogEvent,12 unmodified lines)from god_simulator.simulation.memory import rememberfrom god_simulator.simulation.roles import (action_allowed_for_role,canonical_action,filter_actions_for_role,normalize_role,)66 unmodified lines# Minimum surplus food before an NPC is willing to share with a needier neighbor.SHARE_FOOD_SURPLUS = 2# Goal -> allowed survival effect verbs (engine-side: the deterministic role# planner chooses from these sets, and role whitelists filter them per NPC).GOAL_ACTIONS: dict[str, list[str]] = {12 unmodified lines"dead": [],}# Goal -> ranked LLM-facing suggestions, best first: the six primitives plus the# role-gated survival extras (go_home, patrol, build). These are hints; the# engine role-gates and repairs every request at validation time.GOAL_SUGGESTED_ACTIONS: dict[str, list[str]] = {"engage_threat": ["strike", "patrol", "speak", "move"],"survive_threat_fight": ["strike", "go_home", "speak", "move", "idle"],"survive_threat_flee": ["move", "go_home", "speak", "idle"],"help_ally": ["strike", "idle", "speak"],"heal_self": ["use"],"eat_food": ["use"],"find_food": ["move", "use", "speak", "transfer"],"find_herbs": ["move", "use", "speak"],"obey_directive": ["speak", "move", "strike", "go_home", "build", "patrol", "idle"],"settle": ["go_home", "use", "speak", "transfer"],"work": ["use", "move", "build", "patrol", "transfer", "speak"],"routine_life": ["use", "move", "transfer", "speak", "go_home", "build", "patrol"],"dead": [],}PRIMITIVE_SURVIVAL_ACTIONS = frozenset({"move", "speak", "strike", "use", "transfer", "idle"})# Internal effect verbs the resolver knows how to execute. Primitives are18 unmodified lines"go_home","patrol","build",})170 unmodified linesdef build_perception(npc: Npc, world: WorldState) -> str:lines: list[str] = []for beast in sorted(world.beasts, key=lambda item: vec_distance(npc.position, item.position)):if beast.state == "dead":26 unmodified linesfor other in sorted(npcs_in_radius(world, npc.position, PERCEPTION_NPC_RADIUS, exclude_id=npc.id), key=lambda item: item.id):trust = npc.relationships.get(other.id, 0.0)label = _relationship_label(trust)inventory = [f"{label} trust={trust:.1f}"]if other.inventory_food:inventory.append(f"food={other.inventory_food}")if other.inventory_weapon:178 unmodified lines)def apply_world_systems(world: WorldState) -> None:"""Run deterministic environment systems before NPC decisions."""# Local import: chaos.py reuses survival helpers at module level.247 unmodified linesdef apply_post_survival_tick(world: WorldState, next_tick: int) -> None:"""Run deterministic end-of-tick systems after NPC actions resolve."""_refresh_house_occupants(world)for npc in list(world.npcs):if is_alive(npc):_maybe_reproduce(world, npc, next_tick)_refresh_house_occupants(world)if next_tick % 10 == 0:_recompute_importance(world)_update_population_and_status(world, next_tick)def _apply_beast_system(world: WorldState) -> None:half_width = world.terrain.width / 2half_depth = world.terrain.depth / 2236 unmodified lines("herbs", npc.inventory_herbs),("wood", npc.inventory_wood),("weapon", npc.inventory_weapon),):if amount <= 0:continue4 unmodified linesresource_type=resource_type,position=npc.position,amount=amount,max_amount=max(amount, {"food": 5, "herbs": 4, "wood": 6, "weapon": 2}[resource_type]),))npc.inventory_food = 0npc.inventory_herbs = 0npc.inventory_wood = 0npc.inventory_weapon = 0def _purge_dead_npc_references(world: WorldState, dead: Npc) -> None:231 unmodified linesreturnif population <= 0:world.game_status = "lose"elif population >= 12:world.game_status = "win_population"elif next_tick >= 600:world.game_status = "win_survival"78 unmodified linesdef allowed_actions_for_npc(world: WorldState, npc: Npc, goal: str) -> list[str]:allowed = filter_actions_for_role(allowed_actions_for_goal(goal), npc.role)if goal == "survive_threat_flee":allowed = [action for action in allowed if action != "transfer"]if "gather" in allowed and not _has_gatherable_resource_for_goal(world, npc, goal):18 unmodified linesdef suggested_actions_for_npc(npc: Npc, goal: str) -> list[str]:"""Role-gated, ranked LLM suggestions: primitives plus survival extras."""role = normalize_role(npc.role)suggested = suggested_actions_for_goal(goal)if role != "builder":suggested = [action for action in suggested if action != "build"]if role != "guard":suggested = [action for action in suggested if action != "patrol"]if role == "builder":suggested = [action for action in suggested if action != "strike"]return suggested or ["idle"]def _beast_threatens_village(world: WorldState) -> bool:41 unmodified linesif action not in VALID_SURVIVAL_VERBS:return "idle"resource_type = _resource_type_for_validation(world, npc, directive, action)self_defense = (action == "attack"and nearest_beast_distance(world, npc) <= NPC_MELEE_REACHand normalize_role(npc.role) == "gatherer")# Unrestricted NPCs (e.g. external agents over MCP) are intentionally not# role-gated: they may request any action. Physical-possibility checks below# still apply, but role whitelists do not.if not npc.unrestricted_actions and not action_allowed_for_role(npc.role,action,resource_type=resource_type,self_defense=self_defense,):return _role_fallback_action(world, npc)if action == "gather":node = _resource_from_directive(world, directive, npc, max_dist=GATHER_RADIUS)if node is None or node.amount <= 0:return "move_to_resource"if (not npc.unrestricted_actionsand normalize_role(npc.role) == "builder"and node.resource_type != "wood"):return "move_to_resource"return "gather"if action == "consume":return "consume" if npc.inventory_food > 0 else "find_food"5 unmodified linesreturn "defend"return "attack" # apply_action_effects approaches when out of melee reachif action == "build":if not npc.unrestricted_actions and normalize_role(npc.role) != "builder":return _role_fallback_action(world, npc)if npc.build_target_house_id:house = _house_by_id(world, npc.build_target_house_id)if house is not None and house.state == "under_construction":return "build"return "build" if npc.inventory_wood >= 5 else "move_to_resource"if action == "go_home":return "go_home" if nearest_house(world, npc.position) is not None else "move_to"if action == "patrol":return "patrol" if normalize_role(npc.role) == "guard" else _role_fallback_action(world, npc)if action == "steal":partner = _target_npc_from_directive(world, npc, directive, max_dist=TRADE_RADIUS)if partner is None:partner = nearest_alive_npc(world, npc, max_dist=TRADE_RADIUS, require_food=True)return "steal" if partner is not None else "move_to_resource"if action == "transfer":partner = _target_npc_from_directive(world, npc, directive, max_dist=TRADE_RADIUS)if partner is None:partner = nearest_alive_npc(world, npc, max_dist=TRADE_RADIUS)return "transfer" if partner is not None else "communicate"return action22 unmodified linesif action == "speak":return "communicate"if action == "strike":return "attack"if action == "use":if directive is not None and directive.resource_id:return "gather"resource_type = directive.resource_type if directive is not None else None9 unmodified linesreturn "gather"if action == "transfer":if directive is not None and directive.take:return "steal"return "transfer"return "idle"95 unmodified linesif action == "gather":node = _resource_from_directive(world, directive, npc, max_dist=GATHER_RADIUS)if node is not None and node.amount > 0:if normalize_role(npc.role) == "builder" and node.resource_type != "wood":return "searching for wood"node.amount -= 1_add_to_inventory(npc, node.resource_type)add_episode(73 unmodified linesif action == "build":return _apply_build(npc, world)if action == "flee":beast = _beast_from_directive(world, npc, directive)if beast is not None:86 unmodified linesreturn "charging the beast"if action == "transfer":# Share food from whoever has a surplus with the neediest nearby neighbour,# so food flows from haves to have-nots instead of people starving alone.partner = _transfer_partner(world, npc, directive)102 unmodified linesif action == "defend":return "defending"return "idle"def _apply_communicate(npc: Npc,world: WorldState,188 unmodified linesdef _apply_build(npc: Npc, world: WorldState) -> str:if not npc.unrestricted_actions and normalize_role(npc.role) != "builder":return "cannot build"half_width = world.terrain.width / 2half_depth = world.terrain.depth / 2active_house = _house_by_id(world, npc.build_target_house_id or "")113 unmodified linesreturn f"building {house.id}"def _patrol_target(world: WorldState, npc: Npc) -> Vec3 | None:threat = _nearest_village_threat(world, npc)if threat is not None:155 unmodified linesreturn _neediest_food_neighbor(world, npc)def _resource_type_from_directive(directive: NpcDirective | None, *, default: str) -> str:if directive is not None and directive.resource_type in {"food", "herbs", "wood", "weapon"}:return directive.resource_typereturn defaultdef _amount_from_directive(directive: NpcDirective | None, *, default: int) -> int:if directive is not None and directive.amount is not None:return max(1, min(5, directive.amount))return default42 unmodified linesnpc.inventory_wood += amountelif resource_type == "weapon":npc.inventory_weapon += amountdef _remove_from_inventory(npc: Npc, resource_type: str, amount: int) -> None:5 unmodified linesnpc.inventory_wood = max(0, npc.inventory_wood - amount)elif resource_type == "weapon":npc.inventory_weapon = max(0, npc.inventory_weapon - amount)def _inventory_amount(npc: Npc, resource_type: str) -> int:5 unmodified linesreturn npc.inventory_woodif resource_type == "weapon":return npc.inventory_weaponreturn 0245 unmodified lines*,target: Vec3 | None = None,target_npc_id: str | None = None,resource_id: str | None = None,resource_type: str | None = None,amount: int | None = None,communication_intent: str | None = None,message: str | None = None,away: bool = False,) -> NpcDirective:return NpcDirective(npc_id=npc.id,action=action, # type: ignore[arg-type]target=target,target_npc_id=target_npc_id,resource_id=resource_id,resource_type=resource_type,amount=amount,communication_intent=communication_intent,message=message,away=away,intent=f"survival:{goal}",)role = normalize_role(npc.role)if goal == "obey_directive":text = (npc.god_directive or "").lower()128 unmodified lines# routine_life/work fallback: socialise, share, forage, or wander -- and spread out.neighbor = nearest_alive_npc(world, npc, max_dist=TALK_RADIUS)phase = (next_tick + index) % 4if (neighbor is not Noneand npc.inventory_food >= SHARE_FOOD_SURPLUS11 unmodified lines121314151617181920212223242526272829303112 unmodified lines4445464748495066 unmodified lines11711811912012112212312412512612712812913013113212 unmodified lines14514614714814915015115215315415515615715815916016116216316416516616716816917018 unmodified lines189190191192193194195196197198170 unmodified lines36937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941026 unmodified lines437438439440441442443444178 unmodified lines623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666247 unmodified lines914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041236 unmodified lines12781279128012811282128312844 unmodified lines12891290129112921293129412951296129712981299130013011302130313041305231 unmodified lines153715381539154015411542154378 unmodified lines162216231624162516261627162818 unmodified lines16471648164916501651165216531654165541 unmodified lines16971698169917001701170217031704170517065 unmodified lines17121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175022 unmodified lines17731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617979 unmodified lines18071808180918101811181218131814181518161817181818191820182118221823182495 unmodified lines19201921192219231924192573 unmodified lines19992000200120022003200420052006200720082009201020112012201386 unmodified lines210021012102210321042105210621072108102 unmodified lines2211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241188 unmodified lines243024312432243324342435113 unmodified lines254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695155 unmodified lines28512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293742 unmodified lines298029812982298329842985298629875 unmodified lines299329942995299629972998299930005 unmodified lines30063007300830093010301130123013245 unmodified lines32593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371128 unmodified lines35003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352311 unmodified linesfrom __future__ import annotationsimport mathimport osimport randomfrom god_simulator.domain import (Beast,CannonState,CountryState,ElectionState,House,MemoryEntry,MemoryEpisode,Npc,ResourceNode,TreasuryState,Vec3,WorldEvent,WorldLogEvent,12 unmodified lines)from god_simulator.simulation.memory import rememberfrom god_simulator.simulation.roles import (canonical_action,normalize_role,)66 unmodified lines# Minimum surplus food before an NPC is willing to share with a needier neighbor.SHARE_FOOD_SURPLUS = 2DEFAULT_ELECTION_INTERVAL_TICKS = 50DEFAULT_ELECTION_DURATION_TICKS = 10DEFAULT_CANNON_MIN_POPULATION = 6DEFAULT_CANNON_TREASURY_COST = 20DEFAULT_CANNON_WOOD_COST = 15DEFAULT_CANNON_HP_TAX_PER_CITIZEN = 5DEFAULT_CANNON_DAMAGE = 35DEFAULT_CANNON_RADIUS = 5DEFAULT_CANNON_COOLDOWN_TICKS = 20# Goal -> allowed survival effect verbs (engine-side: the deterministic role# planner chooses from these sets, and role whitelists filter them per NPC).GOAL_ACTIONS: dict[str, list[str]] = {12 unmodified lines"dead": [],}# Goal -> ranked LLM-facing suggestions, best first. These are public tools;# internal survival verbs such as gather/build/go_home map through use/move.GOAL_SUGGESTED_ACTIONS: dict[str, list[str]] = {"engage_threat": ["attack", "move", "speak"],"survive_threat_fight": ["attack", "move", "speak"],"survive_threat_flee": ["move", "speak"],"help_ally": ["attack", "speak"],"heal_self": ["use"],"eat_food": ["use"],"find_food": ["move", "use", "speak", "transfer"],"find_herbs": ["move", "use", "speak"],"obey_directive": ["speak", "move", "attack", "use", "transfer"],"settle": ["move", "use", "speak", "transfer"],"work": ["use", "move", "transfer", "speak"],"routine_life": ["use", "move", "transfer", "speak"],"dead": [],}PRIMITIVE_SURVIVAL_ACTIONS = frozenset({"move", "speak", "attack", "use", "transfer", "vote"})# Internal effect verbs the resolver knows how to execute. Primitives are18 unmodified lines"go_home","patrol","build","craft","assign_cannon_operator","fire","vote",})170 unmodified linesdef build_perception(npc: Npc, world: WorldState) -> str:lines: list[str] = []country = country_for_npc(world, npc)if country is not None:ruler = _npc_by_id(world, country.ruler_id or "")treasury = country.treasury.resources if country.treasury is not None else {}lines.append(f"- your country is {country.name} [{country.badge}], ruler="f"{ruler.name if ruler else country.ruler_id or 'none'}")lines.append(f"- country policy: {country.policy}")lines.append("- treasury "+ " ".join(f"{key}={value}" for key, value in sorted(treasury.items())))if country.cannon is not None:operator = _npc_by_id(world, country.cannon.operator_id or "")lines.append(f"- cannon {country.cannon.id} operator="f"{operator.name if operator else country.cannon.operator_id or 'none'}")election = active_election_for_country(world, country.id)if election is not None:lines.append(f"- election active until tick {election.end_tick}; candidates: "+ ", ".join(election.candidate_ids))for rival in world.countries:if rival.id == country.id:continuerival_ruler = _npc_by_id(world, rival.ruler_id or "")rival_treasury = rival.treasury.resources if rival.treasury is not None else {}lines.append(f"- rival country {rival.name} [{rival.badge}] ruler="f"{rival_ruler.name if rival_ruler else rival.ruler_id or 'none'}; "f"treasury {rival.treasury.id if rival.treasury else 'none'} "+ " ".join(f"{key}={value}" for key, value in sorted(rival_treasury.items())))for beast in sorted(world.beasts, key=lambda item: vec_distance(npc.position, item.position)):if beast.state == "dead":26 unmodified linesfor other in sorted(npcs_in_radius(world, npc.position, PERCEPTION_NPC_RADIUS, exclude_id=npc.id), key=lambda item: item.id):trust = npc.relationships.get(other.id, 0.0)label = _relationship_label(trust)country_label = other.country_id or "no-country"inventory = [f"{label} trust={trust:.1f}", f"country={country_label}"]if other.inventory_food:inventory.append(f"food={other.inventory_food}")if other.inventory_weapon:178 unmodified lines)def country_for_npc(world: WorldState, npc: Npc) -> CountryState | None:if npc.country_id is None:return Nonereturn next((country for country in world.countries if country.id == npc.country_id), None)def active_election_for_country(world: WorldState,country_id: str,*,tick: int | None = None,) -> ElectionState | None:current_tick = world.tick if tick is None else tickfor election in world.elections:if election.country_id != country_id or election.completed:continueif election.start_tick <= current_tick <= election.end_tick:return electionreturn Nonedef active_election_for_npc(world: WorldState, npc: Npc, *, tick: int | None = None) -> ElectionState | None:if npc.country_id is None:return Nonereturn active_election_for_country(world, npc.country_id, tick=tick)def _env_int(name: str, default: int) -> int:raw = os.getenv(name)if raw is None:return defaulttry:value = int(raw)except ValueError:return defaultreturn value if value > 0 else defaultdef apply_world_systems(world: WorldState) -> None:"""Run deterministic environment systems before NPC decisions."""# Local import: chaos.py reuses survival helpers at module level.247 unmodified linesdef apply_post_survival_tick(world: WorldState, next_tick: int) -> None:"""Run deterministic end-of-tick systems after NPC actions resolve."""_refresh_house_occupants(world)_refresh_country_citizens(world, next_tick)_run_election_system(world, next_tick)for npc in list(world.npcs):if is_alive(npc):_maybe_reproduce(world, npc, next_tick)_refresh_house_occupants(world)_refresh_country_citizens(world, next_tick)if next_tick % 10 == 0:_recompute_importance(world)_update_population_and_status(world, next_tick)def _refresh_country_citizens(world: WorldState, next_tick: int) -> None:living_ids = {npc.id for npc in world.living_npcs()}for country in world.countries:country.citizen_ids = [npc.idfor npc in world.npcsif npc.country_id == country.id and npc.id in living_ids]if country.ruler_id not in living_ids or country.ruler_id not in country.citizen_ids:country.ruler_id = country.citizen_ids[0] if country.citizen_ids else Nonefor npc in world.npcs:if npc.country_id != country.id:continuenpc.special_status = "ruler" if npc.id == country.ruler_id else ("cannon_operator" if country.cannon and country.cannon.operator_id == npc.id else None)def _run_election_system(world: WorldState, next_tick: int) -> None:for country in world.countries:active = active_election_for_country(world, country.id, tick=next_tick)if active is None and country.citizen_ids and next_tick >= country.next_election_tick:_start_election(world, country, next_tick)active = active_election_for_country(world, country.id, tick=next_tick)if active is not None and next_tick >= active.end_tick:_finish_election(world, country, active, next_tick)def _start_election(world: WorldState, country: CountryState, tick: int) -> None:duration = _env_int("ELECTION_DURATION_TICKS", DEFAULT_ELECTION_DURATION_TICKS)candidate_ids = list(country.citizen_ids)election = ElectionState(country_id=country.id,start_tick=tick,end_tick=tick + duration,candidate_ids=candidate_ids,)world.elections.append(election)_log_event(world,"election_started",f"{country.name} election started with {len(candidate_ids)} candidates",severity="neutral",object_id=country.id,tick=tick,)def _finish_election(world: WorldState,country: CountryState,election: ElectionState,tick: int,) -> None:for npc_id in country.citizen_ids:if npc_id in election.votes:continueelection.votes[npc_id] = _fallback_vote(world, election, voter_id=npc_id)counts: dict[str, int] = {}for candidate_id in election.votes.values():if candidate_id in election.candidate_ids:counts[candidate_id] = counts.get(candidate_id, 0) + 1if counts:winner_id = min(counts, key=lambda candidate_id: (-counts[candidate_id], candidate_id))country.ruler_id = winner_id_set_country_policy(world, country, tick)election.completed = Truecountry.next_election_tick = tick + _env_int("ELECTION_INTERVAL_TICKS",DEFAULT_ELECTION_INTERVAL_TICKS,)_refresh_country_citizens(world, tick)_log_event(world,"election_completed",f"{country.name} elected {country.ruler_id} with {len(election.votes)} votes",severity="good",target_id=country.ruler_id,object_id=country.id,tick=tick,)def _fallback_vote(world: WorldState, election: ElectionState, *, voter_id: str) -> str:if not election.candidate_ids:return voter_idrng = random.Random(f"{world.seed}:{election.country_id}:{election.start_tick}:{voter_id}")return rng.choice(election.candidate_ids)def _set_country_policy(world: WorldState, country: CountryState, tick: int) -> None:treasury = country.treasury.resources if country.treasury else {}wood = treasury.get("wood", 0)coins = treasury.get("coins", 0)if wood >= DEFAULT_CANNON_WOOD_COST and coins >= DEFAULT_CANNON_TREASURY_COST:country.policy = "Craft a cannon, protect the treasury, and attack only clear threats."elif coins < 8:country.policy = "Gather coins and wood, defend citizens, and avoid reckless fights."else:country.policy = "Gather resources, help weak citizens, and watch the other country."_log_event(world,"policy_updated",f"{country.name} policy: {country.policy}",severity="neutral",actor_id=country.ruler_id,object_id=country.id,tick=tick,)def _apply_beast_system(world: WorldState) -> None:half_width = world.terrain.width / 2half_depth = world.terrain.depth / 2236 unmodified lines("herbs", npc.inventory_herbs),("wood", npc.inventory_wood),("weapon", npc.inventory_weapon),("coins", npc.inventory_coins),):if amount <= 0:continue4 unmodified linesresource_type=resource_type,position=npc.position,amount=amount,max_amount=max(amount,{"food": 5, "herbs": 4, "wood": 6, "weapon": 2, "coins": 10}[resource_type],),))npc.inventory_food = 0npc.inventory_herbs = 0npc.inventory_wood = 0npc.inventory_weapon = 0npc.inventory_coins = 0def _purge_dead_npc_references(world: WorldState, dead: Npc) -> None:231 unmodified linesreturnif population <= 0:world.game_status = "lose"elif population >= world.population_cap:world.game_status = "win_population"elif next_tick >= 600:world.game_status = "win_survival"78 unmodified linesdef allowed_actions_for_npc(world: WorldState, npc: Npc, goal: str) -> list[str]:allowed = allowed_actions_for_goal(goal)if goal == "survive_threat_flee":allowed = [action for action in allowed if action != "transfer"]if "gather" in allowed and not _has_gatherable_resource_for_goal(world, npc, goal):18 unmodified linesdef suggested_actions_for_npc(npc: Npc, goal: str) -> list[str]:"""Ranked LLM suggestions. Roles influence planning context, not tool access."""suggested = suggested_actions_for_goal(goal)return suggested or ["move", "speak"]def _beast_threatens_village(world: WorldState) -> bool:41 unmodified linesif action not in VALID_SURVIVAL_VERBS:return "idle"resource_type = _resource_type_for_validation(world, npc, directive, action)if action == "gather":node = _resource_from_directive(world, directive, npc, max_dist=GATHER_RADIUS)if node is None or node.amount <= 0:return "move_to_resource"return "gather"if action == "consume":return "consume" if npc.inventory_food > 0 else "find_food"5 unmodified linesreturn "defend"return "attack" # apply_action_effects approaches when out of melee reachif action == "build":if npc.build_target_house_id:house = _house_by_id(world, npc.build_target_house_id)if house is not None and house.state == "under_construction":return "build"return "build" if npc.inventory_wood >= 5 else "move_to_resource"if action == "craft":return "craft" if _can_craft_cannon(world, npc) else "idle"if action == "assign_cannon_operator":return "assign_cannon_operator" if _can_assign_cannon_operator(world, npc, directive) else "idle"if action == "fire":return "fire" if _can_fire_cannon(world, npc, directive) else "idle"if action == "go_home":return "go_home" if nearest_house(world, npc.position) is not None else "move_to"if action == "patrol":return "patrol"if action == "steal":partner = _target_npc_from_directive(world, npc, directive, max_dist=TRADE_RADIUS)if partner is None:partner = nearest_alive_npc(world, npc, max_dist=TRADE_RADIUS, require_food=True)return "steal" if partner is not None else "move_to_resource"if action == "transfer":if _treasury_from_directive(world, directive) is not None:return "transfer"partner = _target_npc_from_directive(world, npc, directive, max_dist=TRADE_RADIUS)if partner is None:partner = nearest_alive_npc(world, npc, max_dist=TRADE_RADIUS)return "transfer" if partner is not None else "communicate"if action == "vote":election = active_election_for_npc(world, npc)candidate_id = directive.target_npc_id if directive is not None else Noneif election is None or candidate_id not in election.candidate_ids:return "idle"return "vote"return action22 unmodified linesif action == "speak":return "communicate"if action in {"attack", "strike"}:return "attack"if action == "use":use_type = (directive.use_type or "").lower() if directive is not None else ""if use_type in {"eat", "consume"}:return "consume"if use_type == "heal":return "heal"if use_type == "gather":return "gather"if use_type in {"build", "repair"}:return "build"if use_type == "craft":return "craft"if use_type == "assign_cannon_operator":return "assign_cannon_operator"if use_type == "fire":return "fire"if directive is not None and directive.resource_id:return "gather"resource_type = directive.resource_type if directive is not None else None9 unmodified linesreturn "gather"if action == "transfer":# A transfer aimed at a treasury always resolves through the treasury# handler, which honors `take` (steal from a rival) vs deposit. Routing# take->NPC-steal here would bypass treasury raids entirely.if _treasury_from_directive(world, directive) is not None:return "transfer"if directive is not None and directive.take:return "steal"return "transfer"if action == "vote":return "vote"return "idle"95 unmodified linesif action == "gather":node = _resource_from_directive(world, directive, npc, max_dist=GATHER_RADIUS)if node is not None and node.amount > 0:node.amount -= 1_add_to_inventory(npc, node.resource_type)add_episode(73 unmodified linesif action == "build":return _apply_build(npc, world)if action == "craft":return _apply_craft(npc, world, directive)if action == "assign_cannon_operator":return _apply_assign_cannon_operator(npc, world, directive)if action == "fire":return _apply_fire_cannon(npc, world, directive)if action == "flee":beast = _beast_from_directive(world, npc, directive)if beast is not None:86 unmodified linesreturn "charging the beast"if action == "transfer":treasury = _treasury_from_directive(world, directive)if treasury is not None:return _apply_treasury_transfer(npc, world, treasury, directive)# Share food from whoever has a surplus with the neediest nearby neighbour,# so food flows from haves to have-nots instead of people starving alone.partner = _transfer_partner(world, npc, directive)102 unmodified linesif action == "defend":return "defending"if action == "vote":return _apply_vote(npc, world, directive)return "idle"def _apply_vote(npc: Npc, world: WorldState, directive: NpcDirective | None) -> str:election = active_election_for_npc(world, npc)candidate_id = directive.target_npc_id if directive is not None else Noneif election is None or candidate_id not in election.candidate_ids:return "unable to vote"election.votes[npc.id] = candidate_idcandidate = _npc_by_id(world, candidate_id)candidate_name = candidate.name if candidate is not None else candidate_id_log_event(world,"vote_cast",f"{npc.name} voted for {candidate_name}",actor_id=npc.id,target_id=candidate_id,object_id=election.country_id,)return f"voting for {candidate_name}"def _apply_communicate(npc: Npc,world: WorldState,188 unmodified linesdef _apply_build(npc: Npc, world: WorldState) -> str:half_width = world.terrain.width / 2half_depth = world.terrain.depth / 2active_house = _house_by_id(world, npc.build_target_house_id or "")113 unmodified linesreturn f"building {house.id}"def _can_craft_cannon(world: WorldState, npc: Npc) -> bool:country = country_for_npc(world, npc)if country is None or country.ruler_id != npc.id or country.cannon is not None:return Falseif len(country.citizen_ids) < _env_int("CANNON_MIN_POPULATION", DEFAULT_CANNON_MIN_POPULATION):return Falsetreasury = country.treasury.resources if country.treasury else {}return (treasury.get("coins", 0) >= _env_int("CANNON_TREASURY_COST", DEFAULT_CANNON_TREASURY_COST)and treasury.get("wood", 0) >= _env_int("CANNON_WOOD_COST", DEFAULT_CANNON_WOOD_COST))def _can_assign_cannon_operator(world: WorldState,npc: Npc,directive: NpcDirective | None,) -> bool:country = country_for_npc(world, npc)target_id = _param_str(directive, "npc_id") or (directive.target_npc_id if directive else None)target = _npc_by_id(world, target_id or "")return (country is not Noneand country.ruler_id == npc.idand country.cannon is not Noneand target is not Noneand target.country_id == country.id)def _can_fire_cannon(world: WorldState, npc: Npc, directive: NpcDirective | None) -> bool:country = country_for_npc(world, npc)if country is None or country.cannon is None:return Falsereturn country.cannon.operator_id == npc.id and world.tick >= country.cannon.cooldown_until_tickdef _apply_craft(npc: Npc, world: WorldState, directive: NpcDirective | None) -> str:if _param_str(directive, "recipe_id") not in {None, "cannon"}:return "unknown recipe"if not _can_craft_cannon(world, npc):return "cannot craft cannon yet"country = country_for_npc(world, npc)assert country is not None and country.treasury is not Nonetreasury = country.treasury.resourcescoin_cost = _env_int("CANNON_TREASURY_COST", DEFAULT_CANNON_TREASURY_COST)wood_cost = _env_int("CANNON_WOOD_COST", DEFAULT_CANNON_WOOD_COST)hp_tax = _env_int("CANNON_HP_TAX_PER_CITIZEN", DEFAULT_CANNON_HP_TAX_PER_CITIZEN)treasury["coins"] = treasury.get("coins", 0) - coin_costtreasury["wood"] = treasury.get("wood", 0) - wood_costfor citizen in world.living_npcs():if citizen.country_id == country.id:citizen.health = max(1, citizen.health - hp_tax)country.cannon = CannonState(id=f"cannon_{country.id}",position=country.treasury.position,damage=_env_int("CANNON_DAMAGE", DEFAULT_CANNON_DAMAGE),radius=_env_int("CANNON_RADIUS", DEFAULT_CANNON_RADIUS),)_log_event(world,"cannon_crafted",f"{country.name} crafted {country.cannon.id}",severity="good",actor_id=npc.id,object_id=country.cannon.id,)return f"crafting {country.cannon.id}"def _apply_assign_cannon_operator(npc: Npc,world: WorldState,directive: NpcDirective | None,) -> str:if not _can_assign_cannon_operator(world, npc, directive):return "cannot assign cannon operator"country = country_for_npc(world, npc)assert country is not None and country.cannon is not Nonetarget_id = _param_str(directive, "npc_id") or directive.target_npc_idcountry.cannon.operator_id = target_id_refresh_country_citizens(world, world.tick)_log_event(world,"cannon_operator_assigned",f"{country.name} assigned {target_id} to {country.cannon.id}",severity="good",actor_id=npc.id,target_id=target_id,object_id=country.cannon.id,)return f"assigning cannon operator {target_id}"def _apply_fire_cannon(npc: Npc, world: WorldState, directive: NpcDirective | None) -> str:if not _can_fire_cannon(world, npc, directive):return "cannot fire cannon"country = country_for_npc(world, npc)assert country is not None and country.cannon is not Nonex = _param_float(directive, "x")z = _param_float(directive, "z")if x is None or z is None:return "missing cannon target"target = Vec3(x=x, y=0.0, z=z)damaged: list[str] = []for target_npc in list(world.living_npcs()):if vec_distance(target_npc.position, target) > country.cannon.radius:continuetarget_npc.health -= country.cannon.damagedamaged.append(target_npc.id)if target_npc.health <= 0:_kill_npc(world, target_npc, cause="cannon", actor_id=npc.id)cooldown = _env_int("CANNON_COOLDOWN_TICKS", DEFAULT_CANNON_COOLDOWN_TICKS)country.cannon.cooldown_until_tick = world.tick + cooldown_log_event(world,"cannon_fired",f"{npc.name} fired {country.cannon.id} at ({x:g}, {z:g}) hitting {len(damaged)} targets",severity="danger" if damaged else "warning",actor_id=npc.id,object_id=country.cannon.id,)return f"firing cannon at {x:g}, {z:g}"def _param_str(directive: NpcDirective | None, key: str) -> str | None:if directive is None or not isinstance(directive.params, dict):return Nonevalue = directive.params.get(key)return value if isinstance(value, str) else Nonedef _param_float(directive: NpcDirective | None, key: str) -> float | None:if directive is None or not isinstance(directive.params, dict):return Nonevalue = directive.params.get(key)if isinstance(value, int | float) and not isinstance(value, bool):return float(value)return Nonedef _patrol_target(world: WorldState, npc: Npc) -> Vec3 | None:threat = _nearest_village_threat(world, npc)if threat is not None:155 unmodified linesreturn _neediest_food_neighbor(world, npc)def _treasury_from_directive(world: WorldState,directive: NpcDirective | None,) -> tuple[CountryState, TreasuryState] | None:target_id = directive.target_entity_id if directive is not None else Noneif target_id is None:return Nonefor country in world.countries:if country.treasury is not None and country.treasury.id == target_id:return country, country.treasuryreturn Nonedef _apply_treasury_transfer(npc: Npc,world: WorldState,treasury_ref: tuple[CountryState, TreasuryState],directive: NpcDirective | None,) -> str:country, treasury = treasury_refresource_type = _resource_type_from_directive(directive, default="coins")amount = _amount_from_directive(directive, default=1)take = bool(directive and directive.take)position = treasury.positionresources = treasury.resourcesif vec_distance(npc.position, position) > TRADE_RADIUS:npc.position = move_toward(npc.position,position,NPC_MOVE_STEP,half_width=world.terrain.width / 2,half_depth=world.terrain.depth / 2,)return "approaching treasury"if take:if npc.country_id == country.id:return "guarding own treasury"available = resources.get(resource_type, 0)if available <= 0:return "found empty treasury"moved = min(amount, available)resources[resource_type] = available - moved_add_to_inventory_amount(npc, resource_type, moved)_log_event(world,"treasury_stolen",f"{npc.name} stole {moved} {resource_type} from {country.name}",severity="warning",actor_id=npc.id,object_id=treasury.id,)return f"stealing {resource_type} from {country.name}"if npc.country_id != country.id:return "refusing to fund foreign treasury"available = _inventory_amount(npc, resource_type)if available <= 0:return f"no {resource_type} to deposit"moved = min(amount, available)_remove_from_inventory(npc, resource_type, moved)resources[resource_type] = resources.get(resource_type, 0) + movednpc.resources_transferred += moved_log_event(world,"treasury_deposit",f"{npc.name} deposited {moved} {resource_type} into {country.name} treasury",severity="good",actor_id=npc.id,object_id=treasury.id,)return f"depositing {resource_type} into {country.name} treasury"def _resource_type_from_directive(directive: NpcDirective | None, *, default: str) -> str:if directive is not None and directive.resource_type in {"food", "herbs", "wood", "weapon", "coins"}:return directive.resource_typereturn defaultdef _amount_from_directive(directive: NpcDirective | None, *, default: int) -> int:if directive is not None and directive.amount is not None:return max(1, min(20, directive.amount))return default42 unmodified linesnpc.inventory_wood += amountelif resource_type == "weapon":npc.inventory_weapon += amountelif resource_type == "coins":npc.inventory_coins += amountdef _remove_from_inventory(npc: Npc, resource_type: str, amount: int) -> None:5 unmodified linesnpc.inventory_wood = max(0, npc.inventory_wood - amount)elif resource_type == "weapon":npc.inventory_weapon = max(0, npc.inventory_weapon - amount)elif resource_type == "coins":npc.inventory_coins = max(0, npc.inventory_coins - amount)def _inventory_amount(npc: Npc, resource_type: str) -> int:5 unmodified linesreturn npc.inventory_woodif resource_type == "weapon":return npc.inventory_weaponif resource_type == "coins":return npc.inventory_coinsreturn 0245 unmodified lines*,target: Vec3 | None = None,target_npc_id: str | None = None,target_entity_id: str | None = None,resource_id: str | None = None,resource_type: str | None = None,amount: int | None = None,communication_intent: str | None = None,message: str | None = None,params: dict[str, object] | None = None,away: bool = False,) -> NpcDirective:public_action = actionpublic_use_type: str | None = Nonepublic_take = Falseif action in {"strike", "attack"}:public_action = "attack"elif action in {"gather", "consume", "eat", "heal", "build", "repair"}:public_action = "use"public_use_type = {"consume": "eat","eat": "eat","heal": "heal","gather": "gather","build": "build","repair": "repair",}[action]if action in {"consume", "eat"} and resource_type is None:resource_type = "food"if action == "heal" and resource_type is None:resource_type = "herbs"elif action in {"craft", "assign_cannon_operator", "fire"}:public_action = "use"public_use_type = actionelif action in {"communicate", "trade", "request_trade"}:public_action = "speak"elif action == "steal":public_action = "transfer"public_take = Trueelif action in {"go_home","patrol","flee","move_to_resource","move_to","find_food","find_herbs","wander",}:public_action = "move"if action == "go_home" and target is None:home = nearest_house(world, npc.position)target = home.position if home is not None else Noneelif action == "patrol" and target is None:target = _patrol_target(world, npc)away = away or action == "flee"return NpcDirective(npc_id=npc.id,action=public_action, # type: ignore[arg-type]target=target,target_npc_id=target_npc_id,target_entity_id=target_entity_id,resource_id=resource_id,resource_type=resource_type,use_type=public_use_type,params=params,amount=amount,communication_intent=communication_intent,message=message,away=away,take=public_take,intent=f"survival:{goal}",)role = normalize_role(npc.role)election = active_election_for_npc(world, npc, tick=next_tick)if election is not None and npc.id not in election.votes and election.candidate_ids:candidate_id = _fallback_vote(world, election, voter_id=npc.id)return directive("vote", target_npc_id=candidate_id)country = country_for_npc(world, npc)if country is not None and country.ruler_id == npc.id:if country.cannon is None and _can_craft_cannon(world, npc):return directive("craft", params={"recipe_id": "cannon"})if country.cannon is not None and country.cannon.operator_id is None:operator = next((citizenfor citizen in world.living_npcs()if citizen.country_id == country.id and citizen.id != npc.id),npc,)return directive("assign_cannon_operator", params={"npc_id": operator.id})if (country is not Noneand country.cannon is not Noneand country.cannon.operator_id == npc.idand next_tick >= country.cannon.cooldown_until_tick):target = next((other for other in world.living_npcs() if other.country_id != country.id),None,)if target is not None:return directive("fire",target=country.cannon.position,target_npc_id=target.id,params={"x": target.position.x, "z": target.position.z},)if goal == "obey_directive":text = (npc.god_directive or "").lower()128 unmodified lines# routine_life/work fallback: socialise, share, forage, or wander -- and spread out.neighbor = nearest_alive_npc(world, npc, max_dist=TALK_RADIUS)phase = (next_tick + index) % 4country = country_for_npc(world, npc)if country is not None and country.treasury is not None and phase == 2:if npc.inventory_coins > 0:return directive("transfer",target=country.treasury.position,target_entity_id=country.treasury.id,resource_type="coins",amount=1,)if npc.inventory_wood > 0:return directive("transfer",target=country.treasury.position,target_entity_id=country.treasury.id,resource_type="wood",amount=1,)if (neighbor is not Noneand npc.inventory_food >= SHARE_FOOD_SURPLUS
153 unmodified lines15415515615715815916080 unmodified lines241242243244245246247248249250251252253254255256257258259260261262263264265266592 unmodified lines859860861862863864865866867868153 unmodified lines)case "speak":resolution = _apply_speak(npc, directive, npcs_by_id, next_tick)case "strike":resolution = _apply_strike(npc, directive, npcs_by_id, world, next_tick)case "idle":resolution = _apply_idle(npc, directive)80 unmodified linesresolved = idle_directive(directive, memory=None, intent="actor_dead")return _validation_result(directive, resolved, valid=False, reason="actor dead")perception, goal = refresh_citizen_motivation(world, npc)if directive.action not in PRIMITIVE_ACTION_IDS:fallback = autopilot_directive(world, npc, directive, perception, goal)return _validation_result(directive,fallback,valid=False,reason=f"unknown action {directive.action!r} replaced by autopilot",)match directive.action:case "idle":return _validation_result(directive, directive, valid=True, reason="idle accepted")case "move":return _validate_move(world, npc, directive, perception, goal)case "speak":return _validate_speak(world, npc, directive)case "strike":return _validate_strike(world, npc, directive)case _:# use/transfer have no effects outside survival worlds.resolved = idle_directive(592 unmodified linesfor entry in entries:record = dict(entry)if record.get("phase") == "npc_response":npc_id = str(record.get("npc_id") or "")verdict = verdicts.get(npc_id)if verdict is not None:record["validator_verdict"] = verdictappend_record(record)153 unmodified lines15415515615715815916080 unmodified lines241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275592 unmodified lines868869870871872873874875876877878879880881882883884153 unmodified lines)case "speak":resolution = _apply_speak(npc, directive, npcs_by_id, next_tick)case "attack" | "strike":resolution = _apply_strike(npc, directive, npcs_by_id, world, next_tick)case "idle":resolution = _apply_idle(npc, directive)80 unmodified linesresolved = idle_directive(directive, memory=None, intent="actor_dead")return _validation_result(directive, resolved, valid=False, reason="actor dead")original_directive = directiveif directive.action == "idle":return _validation_result(directive, directive, valid=True, reason="idle accepted")if directive.action == "strike":directive = replace(directive, action="attack")perception, goal = refresh_citizen_motivation(world, npc)if directive.action not in PRIMITIVE_ACTION_IDS:fallback = autopilot_directive(world, npc, directive, perception, goal)return _validation_result(original_directive,fallback,valid=False,reason=f"unknown action {directive.action!r} replaced by autopilot",)match directive.action:case "move":return _validate_move(world, npc, directive, perception, goal)case "speak":return _validate_speak(world, npc, directive)case "attack" | "strike":validation = _validate_strike(world, npc, directive)if original_directive.action != directive.action:return replace(validation, original_action=str(original_directive.action))return validationcase _:# use/transfer have no effects outside survival worlds.resolved = idle_directive(592 unmodified linesfor entry in entries:record = dict(entry)if record.get("phase") == "npc_response":# Only a genuine model response (verdict still "pending") is# reconciled with the engine's accept/repair/reject verdict. A# response whose verdict is already "rejected" (model call failed /# output unusable / NPC omitted) keeps that explicit reason so a# fallback is never masked as "accepted" by the deterministic fill.current = record.get("validator_verdict")current_status = current.get("status") if isinstance(current, dict) else Noneif current_status in (None, "pending"):verdict = verdicts.get(str(record.get("npc_id") or ""))if verdict is not None:record["validator_verdict"] = verdictappend_record(record)
123456789101112<div class="gs-card-head sky"><div class="gs-tile sky">🌍</div><h2>Observe the world</h2></div><div class="gs-card-body"><p class="gs-lede">Step into the live 3D view and watch the simulation unfold in real time — characters gather, build, fight and fall.</p><ul class="gs-feats"><li><span class="gs-pip"></span>🌐 Live 3D map</li><li><span class="gs-pip"></span>⚔️ Watch the Overseer vs. Chaos play out</li><li><span class="gs-pip"></span>🗺️ No setup required</li></ul></div>123456789101112<div class="gs-card-head sky"><div class="gs-tile sky">WORLD</div><h2>Observe the world</h2></div><div class="gs-card-body"><p class="gs-lede">Watch two AI countries live in the same world: citizens gather, vote, build, raid treasuries and operate cannons.</p><ul class="gs-feats"><li><span class="gs-pip"></span>Live 3D map</li><li><span class="gs-pip"></span>Countries, rulers, policies and elections</li><li><span class="gs-pip"></span>No setup required</li></ul></div>
7 unmodified lines8910111213147 unmodified linesconst canvas = page.locator("canvas").first();await expect(canvas).toBeVisible();await expect(page.getByLabel("Simulation status")).toBeVisible();await expect(page.getByLabel("God console")).toBeVisible();await expect(page.getByLabel("Ada memories")).toBeVisible();await page.keyboard.down("w");7 unmodified lines8910111213147 unmodified linesconst canvas = page.locator("canvas").first();await expect(canvas).toBeVisible();await expect(page.getByLabel("Simulation status")).toBeVisible();await expect(page.getByLabel("Countries")).toBeVisible();await expect(page.getByLabel("Ada memories")).toBeVisible();await page.keyboard.down("w");
241 unmodified lines242243244245246247248241 unmodified linesassert cora.mode == "threatened"assert boris_goal is not None and boris_goal.goal_type == "survive"assert cora_goal is not None and cora_goal.goal_type == "survive"assert {"move", "speak", "strike"}.issubset(set(boris_hints.suggested_actions))assert cora_hints.suggested_actions[0] == "move"241 unmodified lines242243244245246247248241 unmodified linesassert cora.mode == "threatened"assert boris_goal is not None and boris_goal.goal_type == "survive"assert cora_goal is not None and cora_goal.goal_type == "survive"assert {"move", "speak", "attack"}.issubset(set(boris_hints.suggested_actions))assert cora_hints.suggested_actions[0] == "move"
154 unmodified lines155156157158159160161154 unmodified linesassert _modal_health_urls(config) == ["https://workspace--npc-serve.modal.run/health","https://workspace--god-serve.modal.run/health",]config = _config(154 unmodified lines155156157158159160154 unmodified linesassert _modal_health_urls(config) == ["https://workspace--npc-serve.modal.run/health",]config = _config(
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267"""Regression tests for the two-country demo systems and the LLM ledger.
These pin the fixes audited against goal.md:* demo configs spawn two populated countries (Nemotron + Qwen);* the routing simulator preserves per-NPC LLM ledger entries and records which model/model_profile drives each NPC (Qwen vs default);* treasury deposit and cross-country steal both resolve through `transfer`;* perception exposes rival countries (so an agent can steal/strike);* `vote` appears only during an election window;* an unusable model output is logged as an explicit fallback."""
from __future__ import annotations
import jsonfrom pathlib import Pathfrom typing import Any
from god_simulator.config import ( ConnectorConfig, GameConfig, NpcConfig, ServerConfig, SimulationConfig, WorldConfig, load_game_config,)from god_simulator.domain import ElectionStatefrom god_simulator.simulation.connectors.base import NpcDirectivefrom god_simulator.simulation.connectors.deterministic import DeterministicWorldSimulatorfrom god_simulator.simulation.connectors.openai_compatible import ( OpenAICompatibleWorldSimulator,)from god_simulator.simulation.connectors.routing import RoutingWorldSimulatorfrom god_simulator.simulation.spawning import create_worldfrom god_simulator.simulation.survival import ( apply_action_effects, validate_survival_action,)
def _survival_config(*, npc_count: int = 6) -> GameConfig: return GameConfig( world=WorldConfig(width=240, depth=80, terrain="plain_green", seed=42, survival=True), npcs=NpcConfig(count=npc_count), simulation=SimulationConfig(tick_ms=500), server=ServerConfig(host="127.0.0.1", port=8000), )
def _move_completer(request: dict[str, Any]) -> dict[str, Any]: """A minimal valid model: always returns one `move` tool call.""" return { "choices": [ { "message": { "role": "assistant", "tool_calls": [ { "type": "function", "function": {"name": "move", "arguments": json.dumps({})}, } ], } } ] }
# --------------------------------------------------------------------------- ## Two populated countries# --------------------------------------------------------------------------- #def test_demo_config_spawns_two_populated_countries() -> None: config = load_game_config(Path("config/game.modal.local.json")) world = create_world(config)
assert world.population == 12 assert {c.id for c in world.countries} == {"nemotron", "qwen"} by_id = {c.id: c for c in world.countries} assert len(by_id["nemotron"].citizen_ids) == 6 assert len(by_id["qwen"].citizen_ids) == 6 assert by_id["nemotron"].ruler_id is not None assert by_id["qwen"].ruler_id is not None # The Qwen country routes its NPCs to the Qwen connector. qwen_npcs = [n for n in world.npcs if n.country_id == "qwen"] assert qwen_npcs and all(n.connector_id == "qwen" for n in qwen_npcs) nemotron_npcs = [n for n in world.npcs if n.country_id == "nemotron"] assert nemotron_npcs and all(n.connector_id is None for n in nemotron_npcs)
# --------------------------------------------------------------------------- ## Routing preserves LLM ledger entries + records the model per NPC# --------------------------------------------------------------------------- #def test_routing_preserves_ledger_entries_with_model_per_npc() -> None: world = create_world(_survival_config()) deterministic = DeterministicWorldSimulator() default = OpenAICompatibleWorldSimulator( ConnectorConfig(type="openai_compatible", base_url="http://nemo.local/v1", model="nemotron-test"), fallback=deterministic, connector_id_filter=None, chat_completer=_move_completer, ) qwen = OpenAICompatibleWorldSimulator( ConnectorConfig(type="openai_compatible", base_url="http://qwen.local/v1", model="qwen-test"), fallback=deterministic, connector_id_filter="qwen", chat_completer=_move_completer, ) router = RoutingWorldSimulator(routes={"qwen": qwen}, default=default)
plan = router.propose_tick(world, 1) requests = { entry["npc_id"]: entry for entry in plan.ledger_entries if entry.get("phase") == "npc_request" } # Every living NPC of both countries produced a logged request. assert {n.id for n in world.living_npcs()} <= set(requests)
nemo = requests["npc-001"] assert nemo["model"] == "nemotron-test" assert nemo["model_profile"] == "default" assert nemo["connector_id"] is None
qwen_entry = requests["qwen-001"] assert qwen_entry["model"] == "qwen-test" assert qwen_entry["model_profile"] == "qwen" assert qwen_entry["connector_id"] == "qwen"
# Each NPC also has a paired response carrying its validator verdict. responses = [e for e in plan.ledger_entries if e.get("phase") == "npc_response"] assert {e["npc_id"] for e in responses} >= {"npc-001", "qwen-001"}
# --------------------------------------------------------------------------- ## Treasury deposit + cross-country steal through `transfer`# --------------------------------------------------------------------------- #def test_treasury_deposit_via_transfer() -> None: world = create_world(_survival_config()) country = next(c for c in world.countries if c.id == "qwen") assert country.treasury is not None citizen = next(n for n in world.npcs if n.country_id == "qwen") citizen.position = country.treasury.position citizen.inventory_wood = 4 before = country.treasury.resources.get("wood", 0)
directive = NpcDirective( npc_id=citizen.id, action="transfer", target_entity_id=country.treasury.id, resource_type="wood", amount=2, ) verb = validate_survival_action(citizen, directive.action, world, directive) apply_action_effects(citizen, verb, world, directive=directive)
assert country.treasury.resources["wood"] == before + 2 assert citizen.inventory_wood == 2 assert any(e.type == "treasury_deposit" for e in world.event_log)
def test_treasury_steal_via_transfer_take() -> None: world = create_world(_survival_config()) rival = next(c for c in world.countries if c.id == "nemotron") assert rival.treasury is not None thief = next(n for n in world.npcs if n.country_id == "qwen") thief.position = rival.treasury.position before = rival.treasury.resources.get("coins", 0) assert before > 0
directive = NpcDirective( npc_id=thief.id, action="transfer", target_entity_id=rival.treasury.id, resource_type="coins", amount=3, take=True, ) verb = validate_survival_action(thief, directive.action, world, directive) summary = apply_action_effects(thief, verb, world, directive=directive)
assert "stealing" in summary.lower() assert rival.treasury.resources["coins"] == before - 3 assert thief.inventory_coins == 3 assert any(e.type == "treasury_stolen" for e in world.event_log)
# --------------------------------------------------------------------------- ## Perception exposes rival countries + own position# --------------------------------------------------------------------------- #def test_survival_prompt_exposes_rival_countries() -> None: captured: list[dict[str, Any]] = []
def completer(request: dict[str, Any]) -> dict[str, Any]: captured.append(json.loads(request["messages"][1]["content"])) return _move_completer(request)
world = create_world(_survival_config()) simulator = OpenAICompatibleWorldSimulator( ConnectorConfig(type="openai_compatible", base_url="http://nemo.local/v1", model="t"), fallback=DeterministicWorldSimulator(), connector_id_filter=None, chat_completer=completer, ) simulator.propose_tick(world, 1)
assert captured payload = captured[0] assert "position" in payload["own_state"] overview = payload["world_countries"] assert {c["id"] for c in overview} == {"nemotron", "qwen"} own = next(c for c in overview if c["is_own"]) rival = next(c for c in overview if not c["is_own"]) assert own["id"] == "nemotron" assert rival["id"] == "qwen" assert rival["treasury_id"] == "treasury_qwen" assert "coins" in rival["treasury"]
# --------------------------------------------------------------------------- ## vote appears only during an election window# --------------------------------------------------------------------------- #def test_vote_tool_only_during_election() -> None: world = create_world(_survival_config()) simulator = OpenAICompatibleWorldSimulator( ConnectorConfig(type="openai_compatible", base_url="http://nemo.local/v1", model="t"), fallback=DeterministicWorldSimulator(), connector_id_filter=None, chat_completer=_move_completer, ) npc = next(n for n in world.npcs if n.country_id == "nemotron")
request = simulator._build_request(world, 5, npc) # noqa: SLF001 assert "vote" not in [t["function"]["name"] for t in request["tools"]]
world.elections.append( ElectionState( country_id="nemotron", start_tick=4, end_tick=14, candidate_ids=[n.id for n in world.npcs if n.country_id == "nemotron"], ) ) request = simulator._build_request(world, 5, npc) # noqa: SLF001 assert "vote" in [t["function"]["name"] for t in request["tools"]]
# --------------------------------------------------------------------------- ## Unusable model output is logged as an explicit fallback# --------------------------------------------------------------------------- #def test_unusable_model_output_is_logged_as_fallback() -> None: def empty_completer(_: dict[str, Any]) -> dict[str, Any]: # Neither tool calls nor JSON content -> connector must fall back. return {"choices": [{"message": {"role": "assistant", "content": ""}}]}
world = create_world(_survival_config(npc_count=2)) simulator = OpenAICompatibleWorldSimulator( ConnectorConfig(type="openai_compatible", base_url="http://nemo.local/v1", model="t"), fallback=DeterministicWorldSimulator(), connector_id_filter=None, chat_completer=empty_completer, )
plan = simulator.propose_tick(world, 1) fallbacks = [e for e in plan.ledger_entries if e.get("phase") == "npc_fallback"] assert fallbacks assert all(e.get("reason") for e in fallbacks) rejected = [ e for e in plan.ledger_entries if e.get("phase") == "npc_response" and isinstance(e.get("validator_verdict"), dict) and e["validator_verdict"].get("status") == "rejected" ] assert rejected60 unmodified lines616263646566676860 unmodified linesassert snapshot.json()["simulation"]["models"] == []god_command = client.post("/god-command", json={"command": "make Ada happy"})assert god_command.status_code == 400assert god_command.json()["error"] == "god_console_unavailable"def _write_config(tmp_path: Path) -> Path:60 unmodified lines6162636465666760 unmodified linesassert snapshot.json()["simulation"]["models"] == []god_command = client.post("/god-command", json={"command": "make Ada happy"})assert god_command.status_code == 404def _write_config(tmp_path: Path) -> Path:
15 unmodified lines1617181920212215 unmodified lines)start_positions = {npc.id: (npc.position.x, npc.position.z) for npc in world.npcs}assert len(world.npcs) == 8assert world.resource_nodesassert world.beasts15 unmodified lines1617181920212215 unmodified lines)start_positions = {npc.id: (npc.position.x, npc.position.z) for npc in world.npcs}assert len(world.npcs) == 16assert world.resource_nodesassert world.beasts