kikikita commited on
Commit
2fc6392
·
1 Parent(s): a3fd468

aboba improvement

Browse files
GAME_DESIGN.md CHANGED
@@ -338,4 +338,71 @@ Factions, economy/money, crafting beyond `build`, childhood/aging stages, social
338
  7. Reproduction never fires when any condition in §5 is false (property check)
339
  8. `game_status` transitions correctly on win/lose seeds
340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  `scripts/playtest_agent.py` runs the scheduled-chaos scenarios from §14 and produces `playtest_report.md` with: event timeline, population-over-time data, which causal chains occurred (beast→fear→help_request→guard response→trust change; hunger→gather/steal; build→reproduce), and a balance verdict.
 
338
  7. Reproduction never fires when any condition in §5 is false (property check)
339
  8. `game_status` transitions correctly on win/lose seeds
340
 
341
+ ---
342
+
343
+ ## ADDENDUM A: Observability & Perception
344
+
345
+ ### A1. Tick ledger
346
+
347
+ Every server run creates `logs/run_<UTC timestamp>/` containing:
348
+
349
+ - `ledger.jsonl`: one JSON object per record.
350
+ - `pretty.log`: one tail-friendly, truncated mirror line per record.
351
+
352
+ Within each tick, records are ordered:
353
+
354
+ 1. `god_command`, only when a queued God Console or chaos command is applied at tick start. It includes raw input, parsed interpretation, and applied effects.
355
+ 2. `overseer_request`, with the final prompt/messages, model name, and mode.
356
+ 3. `overseer_response`, with raw model output, parsed JSON, accepted/rejected directives, rejection reasons, and latency.
357
+ 4. For each NPC in stable living-NPC order: `npc_request`, then `npc_response`; if the LLM is skipped, `npc_fallback`.
358
+ 5. `engine_events`, containing every event applied during the tick.
359
+
360
+ No model interaction or deterministic fallback path may be silent.
361
+
362
+ ### A2. Queued God and chaos commands
363
+
364
+ God Console and chaos endpoint calls queue intent for the next tick. They do not mutate the world immediately. At tick start, the engine applies queued commands first, logs `god_command`, and only then builds Overseer and NPC model prompts.
365
+
366
+ ### A3. Clean model perception
367
+
368
+ `WorldState.living_npcs()` is the only source for live NPC target enumeration. Dead, corpse, or removed entities must never appear as valid targets for attack, talk, help, follow, flee-from, memory-threat resolution, directives, or Overseer summaries. Dead NPCs may remain only as renderable corpse entities and memory episodes.
369
+
370
+ NPC prompts are compact and truthful. They contain only:
371
+
372
+ - own state and current goal;
373
+ - live nearby threats;
374
+ - live nearby allies with trust;
375
+ - reachable non-empty resources;
376
+ - completed houses with free capacity;
377
+ - active directive with remaining TTL;
378
+ - top 5 relevant memories;
379
+ - allowed action names;
380
+ - 3 to 5 short behavior rules.
381
+
382
+ ### A4. Directives
383
+
384
+ Each directive has `ttl_ticks`, default 24. Expired directives are cleared and logged. Each NPC has at most one active directive; a new directive replaces the previous one. Threats and urgent survival needs may still preempt directives.
385
+
386
+ ### A5. Death consequences
387
+
388
+ On NPC death:
389
+
390
+ - witnesses within 10 world units receive a memory episode with `emotional_weight = 0.9`;
391
+ - if the killer is a beast, witnesses gain fear +30 and set that beast relationship to -1.0;
392
+ - if the killer is an NPC, witnesses reduce trust toward the killer by -0.5;
393
+ - inventory drops as lootable resource nodes at the death position;
394
+ - the dead NPC is purged from live target lists, house occupancy, beast targets, help/focus targets, active directives, and Overseer/NPC contexts during the same tick.
395
+
396
+ ### A6. Observation workflow
397
+
398
+ A playtest must run at least 100 ticks with live configured endpoints when reachable. The resulting ledger is inspected manually and summarized in `OBSERVATIONS.md` with:
399
+
400
+ - three full NPC request/response pairs and a judgment for each;
401
+ - one full Overseer request/response cycle and judgment;
402
+ - accepted, repaired, rejected, and fallback action percentages;
403
+ - top five concrete problems with ledger-line evidence;
404
+ - a second 100-tick rerun after fixes and a before/after acceptance-rate table.
405
+
406
+ If live endpoints are unreachable, record the exact error, run deterministic fallback, and mark live validation pending.
407
+
408
  `scripts/playtest_agent.py` runs the scheduled-chaos scenarios from §14 and produces `playtest_report.md` with: event timeline, population-over-time data, which causal chains occurred (beast→fear→help_request→guard response→trust change; hunger→gather/steal; build→reproduce), and a balance verdict.
OBSERVATIONS.md ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OBSERVATIONS
2
+ ## Live Validation
3
+ - Live HTTP server was started with `config/game.modal.local.json`.
4
+ - NPC model: `nemotron3-nano-4b-fp8`; Overseer model: `qwen3.6-27b-h100-fp8`; Overseer mode: `autopilot`.
5
+ - Before-fix live ledger: `logs\run_20260613T092650Z\ledger.jsonl`; 100 ticks; 2430 records.
6
+ - After-fix live ledger: `logs\run_20260613T142424Z\ledger.jsonl`; 100 ticks; 2414 records.
7
+ - Live endpoints were reachable. Cold-start latency was observed but no fallback run was needed.
8
+
9
+ ## Acceptance Rates
10
+ | Run | Total NPC decisions | Accepted | Repaired | Rejected | Fallback |
11
+ | --- | ---: | ---: | ---: | ---: | ---: |
12
+ | Before `run_20260613T092650Z` | 1134 | 79.19% (898) | 20.81% (236) | 0.00% (0) | 0.00% (0) |
13
+ | After `run_20260613T142424Z` | 1132 | 88.16% (998) | 11.84% (134) | 0.00% (0) | 0.00% (0) |
14
+
15
+ Repair rate fell from 20.81% to 11.84% after making active directives preempt non-critical resource goals and removing physically false `use` affordances when no resource was gatherable at the NPC position.
16
+
17
+ ## Ledger Coverage
18
+ Phase counts in the after-fix live run:
19
+
20
+ | Phase | Count |
21
+ | --- | ---: |
22
+ | `directive_expired` | 26 |
23
+ | `engine_events` | 100 |
24
+ | `npc_request` | 1132 |
25
+ | `npc_response` | 1132 |
26
+ | `overseer_request` | 12 |
27
+ | `overseer_response` | 12 |
28
+
29
+ ## NPC Request/Response Quotes
30
+ The following are full JSONL records copied from the after-fix ledger. Judgments follow each pair.
31
+
32
+ ### Pair 1: Ada Moves Toward Reachable Food, Accepted
33
+ `run_20260613T142424Z` line 1, request
34
+
35
+ ```json
36
+ {"allowed_actions": ["move", "transfer", "speak"], "messages": [{"content": "You are Ada, a gatherer. 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.", "role": "system"}, {"content": "{\"npc_id\": \"npc-001\", \"tick\": 1, \"own_state\": {\"name\": \"Ada\", \"role\": \"gatherer\", \"health\": 100, \"hunger\": 0, \"fear\": 0, \"safety\": 100, \"age\": 60, \"max_age\": 332, \"reproduction_cooldown\": 0, \"importance\": 1.333, \"goal\": \"work\", \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, \"goal\": \"work\", \"active_directive\": null, \"nearby_threats\": [], \"nearby_allies\": [{\"id\": \"npc-007\", \"name\": \"Gita\", \"role\": \"gatherer\", \"distance\": 0.0, \"trust\": 0.45, \"hp\": 100, \"hunger\": 28, \"inventory\": {\"food\": 1, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-003\", \"name\": \"Cora\", \"role\": \"gatherer\", \"distance\": 1.35, \"trust\": 0.45, \"hp\": 100, \"hunger\": 26, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-009\", \"name\": \"Ivan\", \"role\": \"gatherer\", \"distance\": 1.35, \"trust\": 0.45, \"hp\": 100, \"hunger\": 27, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-002\", \"name\": \"Boris\", \"role\": \"gatherer\", \"distance\": 1.44, \"trust\": 0.45, \"hp\": 100, \"hunger\": 20, \"inventory\": {\"food\": 1, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-008\", \"name\": \"Hana\", \"role\": \"gatherer\", \"distance\": 1.44, \"trust\": 0.45, \"hp\": 100, \"hunger\": 21, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}], \"reachable_resources\": [{\"id\": \"res_wood_3\", \"type\": \"wood\", \"amount\": 5, \"distance\": 10.66, \"position\": {\"x\": -9.697, \"z\": 4.421}}, {\"id\": \"res_herbs_2\", \"type\": \"herbs\", \"amount\": 2, \"distance\": 13.26, \"position\": {\"x\": -10.008, \"z\": 8.701}}, {\"id\": \"res_herbs_1\", \"type\": \"herbs\", \"amount\": 2, \"distance\": 19.72, \"position\": {\"x\": -6.117, \"z\": 18.747}}, {\"id\": \"res_food_4\", \"type\": \"food\", \"amount\": 3, \"distance\": 19.79, \"position\": {\"x\": 7.297, \"z\": 18.399}}], \"houses_with_free_capacity\": [], \"top_memories\": [], \"allowed_actions\": [\"move\", \"transfer\", \"speak\"], \"suggested_actions\": [\"move\", \"transfer\", \"speak\"], \"behavior_rules\": [\"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.\"]}", "role": "user"}], "model": "nemotron3-nano-4b-fp8", "npc_id": "npc-001", "phase": "npc_request", "request": {"extra_body": {"chat_template_kwargs": {"enable_thinking": false}}, "max_tokens": 1400, "messages": [{"content": "You are Ada, a gatherer. 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.", "role": "system"}, {"content": "{\"npc_id\": \"npc-001\", \"tick\": 1, \"own_state\": {\"name\": \"Ada\", \"role\": \"gatherer\", \"health\": 100, \"hunger\": 0, \"fear\": 0, \"safety\": 100, \"age\": 60, \"max_age\": 332, \"reproduction_cooldown\": 0, \"importance\": 1.333, \"goal\": \"work\", \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, \"goal\": \"work\", \"active_directive\": null, \"nearby_threats\": [], \"nearby_allies\": [{\"id\": \"npc-007\", \"name\": \"Gita\", \"role\": \"gatherer\", \"distance\": 0.0, \"trust\": 0.45, \"hp\": 100, \"hunger\": 28, \"inventory\": {\"food\": 1, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-003\", \"name\": \"Cora\", \"role\": \"gatherer\", \"distance\": 1.35, \"trust\": 0.45, \"hp\": 100, \"hunger\": 26, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-009\", \"name\": \"Ivan\", \"role\": \"gatherer\", \"distance\": 1.35, \"trust\": 0.45, \"hp\": 100, \"hunger\": 27, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-002\", \"name\": \"Boris\", \"role\": \"gatherer\", \"distance\": 1.44, \"trust\": 0.45, \"hp\": 100, \"hunger\": 20, \"inventory\": {\"food\": 1, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-008\", \"name\": \"Hana\", \"role\": \"gatherer\", \"distance\": 1.44, \"trust\": 0.45, \"hp\": 100, \"hunger\": 21, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}], \"reachable_resources\": [{\"id\": \"res_wood_3\", \"type\": \"wood\", \"amount\": 5, \"distance\": 10.66, \"position\": {\"x\": -9.697, \"z\": 4.421}}, {\"id\": \"res_herbs_2\", \"type\": \"herbs\", \"amount\": 2, \"distance\": 13.26, \"position\": {\"x\": -10.008, \"z\": 8.701}}, {\"id\": \"res_herbs_1\", \"type\": \"herbs\", \"amount\": 2, \"distance\": 19.72, \"position\": {\"x\": -6.117, \"z\": 18.747}}, {\"id\": \"res_food_4\", \"type\": \"food\", \"amount\": 3, \"distance\": 19.79, \"position\": {\"x\": 7.297, \"z\": 18.399}}], \"houses_with_free_capacity\": [], \"top_memories\": [], \"allowed_actions\": [\"move\", \"transfer\", \"speak\"], \"suggested_actions\": [\"move\", \"transfer\", \"speak\"], \"behavior_rules\": [\"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.\"]}", "role": "user"}], "model": "nemotron3-nano-4b-fp8", "temperature": 0.6, "tool_choice": "required", "tools": [{"function": {"description": "Move toward a position, NPC, beast, or resource node. Set away=true to move away from the target instead (flee).", "name": "move", "parameters": {"additionalProperties": false, "properties": {"away": {"description": "Move away from the target/threat instead of toward it.", "type": "boolean"}, "target_id": {"description": "Optional visible NPC, beast, or resource node id.", "type": "string"}, "target_x": {"description": "Optional desired x coordinate.", "type": "number"}, "target_z": {"description": "Optional desired z coordinate.", "type": "number"}}, "required": [], "type": "object"}}, "type": "function"}, {"function": {"description": "Give a resource to a nearby NPC, or set take=true to steal from them.", "name": "transfer", "parameters": {"additionalProperties": false, "properties": {"amount": {"maximum": 5, "minimum": 1, "type": "integer"}, "resource_type": {"enum": ["food", "herbs", "wood", "weapon"], "type": "string"}, "take": {"description": "Steal from the target instead of giving.", "type": "boolean"}, "target_id": {"description": "Nearby NPC id.", "type": "string"}}, "required": ["target_id"], "type": "object"}}, "type": "function"}, {"function": {"description": "Say one short message. With target_id it is direct speech; without a target it is a shout heard by everyone nearby (e.g. a call for help).", "name": "speak", "parameters": {"additionalProperties": false, "properties": {"intent": {"description": "Why you are speaking, e.g. help_request, warning, trade_request, social, plead, threaten.", "type": "string"}, "message": {"description": "The exact words said aloud.", "type": "string"}, "target_id": {"description": "Optional nearby NPC id to address directly.", "type": "string"}}, "required": ["message"], "type": "object"}}, "type": "function"}], "top_p": 0.95}, "tick": 1}
37
+ ```
38
+ `run_20260613T142424Z` line 2, response
39
+
40
+ ```json
41
+ {"latency_ms": 130978, "npc_id": "npc-001", "parsed_action": {"action": "move", "amount": null, "away": false, "communication_intent": null, "confidence": null, "conversation_assistant": "tool:move {\"target_id\": \"res_food_4\", \"target_x\": 7.297, \"target_z\": 18.399, \"away\": false}", "conversation_user": "{\"npc_id\": \"npc-001\", \"tick\": 1, \"own_state\": {\"name\": \"Ada\", \"role\": \"gatherer\", \"health\": 100, \"hunger\": 0, \"fear\": 0, \"safety\": 100, \"age\": 60, \"max_age\": 332, \"reproduction_cooldown\": 0, \"importance\": 1.333, \"goal\": \"work\", \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, \"goal\": \"work\", \"active_directive\": null, \"nearby_threats\": [], \"nearby_allies\": [{\"id\": \"npc-007\", \"name\": \"Gita\", \"role\": \"gatherer\", \"distance\": 0.0, \"trust\": 0.45, \"hp\": 100, \"hunger\": 28, \"inventory\": {\"food\": 1, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-003\", \"name\": \"Cora\", \"role\": \"gatherer\", \"distance\": 1.35, \"trust\": 0.45, \"hp\": 100, \"hunger\": 26, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-009\", \"name\": \"Ivan\", \"role\": \"gatherer\", \"distance\": 1.35, \"trust\": 0.45, \"hp\": 100, \"hunger\": 27, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-002\", \"name\": \"Boris\", \"role\": \"gatherer\", \"distance\": 1.44, \"trust\": 0.45, \"hp\": 100, \"hunger\": 20, \"inventory\": {\"food\": 1, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-008\", \"name\": \"Hana\", \"role\": \"gatherer\", \"distance\": 1.44, \"trust\": 0.45, \"hp\": 100, \"hunger\": 21, \"inventory\": {\"", "intent": null, "memory": null, "message": null, "npc_id": "npc-001", "resource_id": "res_food_4", "resource_type": null, "take": false, "target": {"x": 7.297, "y": 0.0, "z": 18.399}, "target_entity_id": null, "target_npc_id": null}, "phase": "npc_response", "raw_output": {"choices": [{"finish_reason": "tool_calls", "index": 0, "logprobs": null, "message": {"annotations": null, "audio": null, "content": "", "function_call": null, "reasoning": null, "reasoning_content": null, "refusal": null, "role": "assistant", "tool_calls": [{"function": {"arguments": "{\"target_id\": \"res_food_4\", \"target_x\": 7.297, \"target_z\": 18.399, \"away\": false}", "name": "move"}, "id": "chatcmpl-tool-bfc98e9f3a2bbd83", "type": "function"}]}, "stop_reason": null, "token_ids": null}], "created": 1781360776, "id": "chatcmpl-9f4e2b138bdf5d6d", "kv_transfer_params": null, "model": "nemotron3-nano-4b-fp8", "moderation": null, "object": "chat.completion", "prompt_logprobs": null, "prompt_token_ids": null, "service_tier": null, "system_fingerprint": null, "usage": {"completion_tokens": 51, "completion_tokens_details": null, "prompt_tokens": 1780, "prompt_tokens_details": null, "total_tokens": 1831}}, "tick": 1, "validator_verdict": {"reason": "accepted", "requested": "move", "requested_effect": "move_to_resource", "resolved": "move_to_resource", "status": "accepted"}}
42
+ ```
43
+ Judgment: prompt is clean and truthful: only live allies/resources are present, no dead targets, and `use` is absent because food is reachable but not at gather range. The model chose `move` toward `res_food_4`, and the validator accepted it.
44
+
45
+ ### Pair 2: Farid Builder Ambiguity, Repaired
46
+ `run_20260613T142424Z` line 32, request
47
+
48
+ ```json
49
+ {"allowed_actions": ["use", "move", "transfer", "speak", "build"], "messages": [{"content": "You are Farid, a builder. 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.", "role": "system"}, {"content": "{\"npc_id\": \"npc-006\", \"tick\": 2, \"own_state\": {\"name\": \"Farid\", \"role\": \"builder\", \"health\": 100, \"hunger\": 26, \"fear\": 0, \"safety\": 0, \"age\": 61, \"max_age\": 440, \"reproduction_cooldown\": 0, \"importance\": 3.0, \"goal\": \"work\", \"inventory\": {\"food\": 0, \"herbs\": 1, \"wood\": 5, \"weapon\": 0}}, \"goal\": \"work\", \"active_directive\": null, \"nearby_threats\": [], \"nearby_allies\": [{\"id\": \"npc-008\", \"name\": \"Hana\", \"role\": \"gatherer\", \"distance\": 2.24, \"trust\": 0.45, \"hp\": 100, \"hunger\": 22, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-003\", \"name\": \"Cora\", \"role\": \"gatherer\", \"distance\": 2.67, \"trust\": 0.45, \"hp\": 100, \"hunger\": 27, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-009\", \"name\": \"Ivan\", \"role\": \"gatherer\", \"distance\": 2.67, \"trust\": 0.45, \"hp\": 100, \"hunger\": 28, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-001\", \"name\": \"Ada\", \"role\": \"gatherer\", \"distance\": 5.45, \"trust\": 0.45, \"hp\": 100, \"hunger\": 1, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-007\", \"name\": \"Gita\", \"role\": \"gatherer\", \"distance\": 5.45, \"trust\": 0.45, \"hp\": 100, \"hunger\": 29, \"inventory\": {\"food\": 1, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}], \"reachable_resources\": [{\"id\": \"res_wood_3\", \"type\": \"wood\", \"amount\": 6, \"distance\": 5.75, \"position\": {\"x\": -9.697, \"z\": 4.421}}, {\"id\": \"res_herbs_2\", \"type\": \"herbs\", \"amount\": 3, \"distance\": 7.76, \"position\": {\"x\": -10.008, \"z\": 8.701}}, {\"id\": \"res_herbs_1\", \"type\": \"herbs\", \"amount\": 3, \"distance\": 15.08, \"position\": {\"x\": -6.117, \"z\": 18.747}}, {\"id\": \"res_food_4\", \"type\": \"food\", \"amount\": 4, \"distance\": 18.43, \"position\": {\"x\": 7.297, \"z\": 18.399}}], \"houses_with_free_capacity\": [], \"top_memories\": [], \"allowed_actions\": [\"use\", \"move\", \"transfer\", \"speak\", \"build\"], \"suggested_actions\": [\"use\", \"move\", \"build\", \"transfer\", \"speak\"], \"behavior_rules\": [\"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.\"]}", "role": "user"}], "model": "nemotron3-nano-4b-fp8", "npc_id": "npc-006", "phase": "npc_request", "request": {"extra_body": {"chat_template_kwargs": {"enable_thinking": false}}, "max_tokens": 1400, "messages": [{"content": "You are Farid, a builder. 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.", "role": "system"}, {"content": "{\"npc_id\": \"npc-006\", \"tick\": 2, \"own_state\": {\"name\": \"Farid\", \"role\": \"builder\", \"health\": 100, \"hunger\": 26, \"fear\": 0, \"safety\": 0, \"age\": 61, \"max_age\": 440, \"reproduction_cooldown\": 0, \"importance\": 3.0, \"goal\": \"work\", \"inventory\": {\"food\": 0, \"herbs\": 1, \"wood\": 5, \"weapon\": 0}}, \"goal\": \"work\", \"active_directive\": null, \"nearby_threats\": [], \"nearby_allies\": [{\"id\": \"npc-008\", \"name\": \"Hana\", \"role\": \"gatherer\", \"distance\": 2.24, \"trust\": 0.45, \"hp\": 100, \"hunger\": 22, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-003\", \"name\": \"Cora\", \"role\": \"gatherer\", \"distance\": 2.67, \"trust\": 0.45, \"hp\": 100, \"hunger\": 27, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-009\", \"name\": \"Ivan\", \"role\": \"gatherer\", \"distance\": 2.67, \"trust\": 0.45, \"hp\": 100, \"hunger\": 28, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-001\", \"name\": \"Ada\", \"role\": \"gatherer\", \"distance\": 5.45, \"trust\": 0.45, \"hp\": 100, \"hunger\": 1, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-007\", \"name\": \"Gita\", \"role\": \"gatherer\", \"distance\": 5.45, \"trust\": 0.45, \"hp\": 100, \"hunger\": 29, \"inventory\": {\"food\": 1, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}], \"reachable_resources\": [{\"id\": \"res_wood_3\", \"type\": \"wood\", \"amount\": 6, \"distance\": 5.75, \"position\": {\"x\": -9.697, \"z\": 4.421}}, {\"id\": \"res_herbs_2\", \"type\": \"herbs\", \"amount\": 3, \"distance\": 7.76, \"position\": {\"x\": -10.008, \"z\": 8.701}}, {\"id\": \"res_herbs_1\", \"type\": \"herbs\", \"amount\": 3, \"distance\": 15.08, \"position\": {\"x\": -6.117, \"z\": 18.747}}, {\"id\": \"res_food_4\", \"type\": \"food\", \"amount\": 4, \"distance\": 18.43, \"position\": {\"x\": 7.297, \"z\": 18.399}}], \"houses_with_free_capacity\": [], \"top_memories\": [], \"allowed_actions\": [\"use\", \"move\", \"transfer\", \"speak\", \"build\"], \"suggested_actions\": [\"use\", \"move\", \"build\", \"transfer\", \"speak\"], \"behavior_rules\": [\"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.\"]}", "role": "user"}], "model": "nemotron3-nano-4b-fp8", "temperature": 0.6, "tool_choice": "required", "tools": [{"function": {"description": "Use something: gather from a resource node (resource_id), eat food (item=food), or heal with herbs (item=herbs).", "name": "use", "parameters": {"additionalProperties": false, "properties": {"item": {"description": "Inventory item to consume.", "enum": ["food", "herbs"], "type": "string"}, "resource_id": {"description": "Nearby resource node id to gather from.", "type": "string"}}, "required": [], "type": "object"}}, "type": "function"}, {"function": {"description": "Move toward a position, NPC, beast, or resource node. Set away=true to move away from the target instead (flee).", "name": "move", "parameters": {"additionalProperties": false, "properties": {"away": {"description": "Move away from the target/threat instead of toward it.", "type": "boolean"}, "target_id": {"description": "Optional visible NPC, beast, or resource node id.", "type": "string"}, "target_x": {"description": "Optional desired x coordinate.", "type": "number"}, "target_z": {"description": "Optional desired z coordinate.", "type": "number"}}, "required": [], "type": "object"}}, "type": "function"}, {"function": {"description": "Give a resource to a nearby NPC, or set take=true to steal from them.", "name": "transfer", "parameters": {"additionalProperties": false, "properties": {"amount": {"maximum": 5, "minimum": 1, "type": "integer"}, "resource_type": {"enum": ["food", "herbs", "wood", "weapon"], "type": "string"}, "take": {"description": "Steal from the target instead of giving.", "type": "boolean"}, "target_id": {"description": "Nearby NPC id.", "type": "string"}}, "required": ["target_id"], "type": "object"}}, "type": "function"}, {"function": {"description": "Say one short message. With target_id it is direct speech; without a target it is a shout heard by everyone nearby (e.g. a call for help).", "name": "speak", "parameters": {"additionalProperties": false, "properties": {"intent": {"description": "Why you are speaking, e.g. help_request, warning, trade_request, social, plead, threaten.", "type": "string"}, "message": {"description": "The exact words said aloud.", "type": "string"}, "target_id": {"description": "Optional nearby NPC id to address directly.", "type": "string"}}, "required": ["message"], "type": "object"}}, "type": "function"}, {"function": {"description": "Builder action: spend wood to start or continue building a house.", "name": "build", "parameters": {"additionalProperties": false, "properties": {}, "required": [], "type": "object"}}, "type": "function"}], "top_p": 0.95}, "tick": 2}
50
+ ```
51
+ `run_20260613T142424Z` line 33, response
52
+
53
+ ```json
54
+ {"latency_ms": 889, "npc_id": "npc-006", "parsed_action": {"action": "use", "amount": null, "away": false, "communication_intent": null, "confidence": null, "conversation_assistant": "tool:use {\"resource_id\": \"res_wood_3\", \"item\": \"food\"}", "conversation_user": "{\"npc_id\": \"npc-006\", \"tick\": 2, \"own_state\": {\"name\": \"Farid\", \"role\": \"builder\", \"health\": 100, \"hunger\": 26, \"fear\": 0, \"safety\": 0, \"age\": 61, \"max_age\": 440, \"reproduction_cooldown\": 0, \"importance\": 3.0, \"goal\": \"work\", \"inventory\": {\"food\": 0, \"herbs\": 1, \"wood\": 5, \"weapon\": 0}}, \"goal\": \"work\", \"active_directive\": null, \"nearby_threats\": [], \"nearby_allies\": [{\"id\": \"npc-008\", \"name\": \"Hana\", \"role\": \"gatherer\", \"distance\": 2.24, \"trust\": 0.45, \"hp\": 100, \"hunger\": 22, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-003\", \"name\": \"Cora\", \"role\": \"gatherer\", \"distance\": 2.67, \"trust\": 0.45, \"hp\": 100, \"hunger\": 27, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-009\", \"name\": \"Ivan\", \"role\": \"gatherer\", \"distance\": 2.67, \"trust\": 0.45, \"hp\": 100, \"hunger\": 28, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-001\", \"name\": \"Ada\", \"role\": \"gatherer\", \"distance\": 5.45, \"trust\": 0.45, \"hp\": 100, \"hunger\": 1, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-007\", \"name\": \"Gita\", \"role\": \"gatherer\", \"distance\": 5.45, \"trust\": 0.45, \"hp\": 100, \"hunger\": 29, \"inventory\": {\"food", "intent": null, "memory": null, "message": null, "npc_id": "npc-006", "resource_id": "res_wood_3", "resource_type": "food", "take": false, "target": null, "target_entity_id": null, "target_npc_id": null}, "phase": "npc_response", "raw_output": {"choices": [{"finish_reason": "tool_calls", "index": 0, "logprobs": null, "message": {"annotations": null, "audio": null, "content": "", "function_call": null, "reasoning": null, "reasoning_content": null, "refusal": null, "role": "assistant", "tool_calls": [{"function": {"arguments": "{\"resource_id\": \"res_wood_3\", \"item\": \"food\"}", "name": "use"}, "id": "chatcmpl-tool-8ceb4a1a73504f19", "type": "function"}]}, "stop_reason": null, "token_ids": null}], "created": 1781360819, "id": "chatcmpl-a545b48c10f9e20c", "kv_transfer_params": null, "model": "nemotron3-nano-4b-fp8", "moderation": null, "object": "chat.completion", "prompt_logprobs": null, "prompt_token_ids": null, "service_tier": null, "system_fingerprint": null, "usage": {"completion_tokens": 29, "completion_tokens_details": null, "prompt_tokens": 1976, "prompt_tokens_details": null, "total_tokens": 2005}}, "tick": 2, "validator_verdict": {"reason": "engine validation repaired action", "requested": "use", "requested_effect": "gather", "resolved": "build", "status": "repaired"}}
55
+ ```
56
+ Judgment: prompt is mostly clean, but this exposes remaining ambiguity: a builder with enough wood sees both `use` and `build`. The model tried `use` with a wood resource; the engine repaired the effect to `build`. This is sensible but still counted as repaired.
57
+
58
+ ### Pair 3: Active Directive In Payload, Accepted
59
+ `run_20260613T142424Z` line 324, request
60
+
61
+ ```json
62
+ {"allowed_actions": ["move", "go_home", "speak", "idle"], "messages": [{"content": "You are Cora, a gatherer. 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.", "role": "system"}, {"content": "{\"npc_id\": \"npc-003\", \"tick\": 16, \"own_state\": {\"name\": \"Cora\", \"role\": \"gatherer\", \"health\": 100, \"hunger\": 38, \"fear\": 0, \"safety\": 4, \"age\": 75, \"max_age\": 462, \"reproduction_cooldown\": 0, \"importance\": 1.333, \"goal\": \"obey_directive\", \"inventory\": {\"food\": 2, \"herbs\": 4, \"wood\": 1, \"weapon\": 0}}, \"goal\": \"obey_directive\", \"active_directive\": {\"text\": \"go_home\", \"source\": \"overseer\", \"issued_tick\": 15, \"ttl_ticks\": 24, \"remaining_ttl\": 23}, \"nearby_threats\": [], \"nearby_allies\": [{\"id\": \"npc-007\", \"name\": \"Gita\", \"role\": \"gatherer\", \"distance\": 4.15, \"trust\": 0.45, \"hp\": 100, \"hunger\": 40, \"inventory\": {\"food\": 1, \"herbs\": 2, \"wood\": 4, \"weapon\": 0}}, {\"id\": \"npc-002\", \"name\": \"Boris\", \"role\": \"gatherer\", \"distance\": 5.74, \"trust\": 0.45, \"hp\": 100, \"hunger\": 5, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-006\", \"name\": \"Farid\", \"role\": \"builder\", \"distance\": 6.04, \"trust\": 0.45, \"hp\": 100, \"hunger\": 37, \"inventory\": {\"food\": 0, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-001\", \"name\": \"Ada\", \"role\": \"gatherer\", \"distance\": 10.2, \"trust\": 0.45, \"hp\": 100, \"hunger\": 2, \"inventory\": {\"food\": 3, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-004\", \"name\": \"Dima\", \"role\": \"guard\", \"distance\": 14.56, \"trust\": 0.45, \"hp\": 82, \"hunger\": 36, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 1}}], \"reachable_resources\": [{\"id\": \"res_herbs_1\", \"type\": \"herbs\", \"amount\": 1, \"distance\": 6.04, \"position\": {\"x\": -6.117, \"z\": 18.747}}, {\"id\": \"res_food_6\", \"type\": \"food\", \"amount\": 2, \"distance\": 9.68, \"position\": {\"x\": -5.673, \"z\": 3.182}}], \"houses_with_free_capacity\": [], \"top_memories\": [{\"age_ticks\": 13, \"kind\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"I gathered wood from res_wood_3\", \"weight\": 0.3, \"tags\": [\"wood\"]}, {\"age_ticks\": 9, \"kind\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"I gathered herbs from res_herbs_2\", \"weight\": 0.3, \"tags\": [\"herbs\"]}, {\"age_ticks\": 7, \"kind\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"I gathered herbs from res_herbs_1\", \"weight\": 0.3, \"tags\": [\"herbs\"]}, {\"age_ticks\": 6, \"kind\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"I gathered herbs from res_herbs_1\", \"weight\": 0.3, \"tags\": [\"herbs\"]}, {\"age_ticks\": 5, \"kind\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"I gathered herbs from res_herbs_1\", \"weight\": 0.3, \"tags\": [\"herbs\"]}], \"allowed_actions\": [\"move\", \"go_home\", \"speak\", \"idle\"], \"suggested_actions\": [\"speak\", \"move\", \"go_home\", \"idle\"], \"behavior_rules\": [\"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.\"]}", "role": "user"}], "model": "nemotron3-nano-4b-fp8", "npc_id": "npc-003", "phase": "npc_request", "request": {"extra_body": {"chat_template_kwargs": {"enable_thinking": false}}, "max_tokens": 1400, "messages": [{"content": "You are Cora, a gatherer. 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.", "role": "system"}, {"content": "{\"npc_id\": \"npc-003\", \"tick\": 16, \"own_state\": {\"name\": \"Cora\", \"role\": \"gatherer\", \"health\": 100, \"hunger\": 38, \"fear\": 0, \"safety\": 4, \"age\": 75, \"max_age\": 462, \"reproduction_cooldown\": 0, \"importance\": 1.333, \"goal\": \"obey_directive\", \"inventory\": {\"food\": 2, \"herbs\": 4, \"wood\": 1, \"weapon\": 0}}, \"goal\": \"obey_directive\", \"active_directive\": {\"text\": \"go_home\", \"source\": \"overseer\", \"issued_tick\": 15, \"ttl_ticks\": 24, \"remaining_ttl\": 23}, \"nearby_threats\": [], \"nearby_allies\": [{\"id\": \"npc-007\", \"name\": \"Gita\", \"role\": \"gatherer\", \"distance\": 4.15, \"trust\": 0.45, \"hp\": 100, \"hunger\": 40, \"inventory\": {\"food\": 1, \"herbs\": 2, \"wood\": 4, \"weapon\": 0}}, {\"id\": \"npc-002\", \"name\": \"Boris\", \"role\": \"gatherer\", \"distance\": 5.74, \"trust\": 0.45, \"hp\": 100, \"hunger\": 5, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-006\", \"name\": \"Farid\", \"role\": \"builder\", \"distance\": 6.04, \"trust\": 0.45, \"hp\": 100, \"hunger\": 37, \"inventory\": {\"food\": 0, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-001\", \"name\": \"Ada\", \"role\": \"gatherer\", \"distance\": 10.2, \"trust\": 0.45, \"hp\": 100, \"hunger\": 2, \"inventory\": {\"food\": 3, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-004\", \"name\": \"Dima\", \"role\": \"guard\", \"distance\": 14.56, \"trust\": 0.45, \"hp\": 82, \"hunger\": 36, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 1}}], \"reachable_resources\": [{\"id\": \"res_herbs_1\", \"type\": \"herbs\", \"amount\": 1, \"distance\": 6.04, \"position\": {\"x\": -6.117, \"z\": 18.747}}, {\"id\": \"res_food_6\", \"type\": \"food\", \"amount\": 2, \"distance\": 9.68, \"position\": {\"x\": -5.673, \"z\": 3.182}}], \"houses_with_free_capacity\": [], \"top_memories\": [{\"age_ticks\": 13, \"kind\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"I gathered wood from res_wood_3\", \"weight\": 0.3, \"tags\": [\"wood\"]}, {\"age_ticks\": 9, \"kind\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"I gathered herbs from res_herbs_2\", \"weight\": 0.3, \"tags\": [\"herbs\"]}, {\"age_ticks\": 7, \"kind\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"I gathered herbs from res_herbs_1\", \"weight\": 0.3, \"tags\": [\"herbs\"]}, {\"age_ticks\": 6, \"kind\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"I gathered herbs from res_herbs_1\", \"weight\": 0.3, \"tags\": [\"herbs\"]}, {\"age_ticks\": 5, \"kind\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"I gathered herbs from res_herbs_1\", \"weight\": 0.3, \"tags\": [\"herbs\"]}], \"allowed_actions\": [\"move\", \"go_home\", \"speak\", \"idle\"], \"suggested_actions\": [\"speak\", \"move\", \"go_home\", \"idle\"], \"behavior_rules\": [\"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.\"]}", "role": "user"}], "model": "nemotron3-nano-4b-fp8", "temperature": 0.6, "tool_choice": "required", "tools": [{"function": {"description": "Move toward a position, NPC, beast, or resource node. Set away=true to move away from the target instead (flee).", "name": "move", "parameters": {"additionalProperties": false, "properties": {"away": {"description": "Move away from the target/threat instead of toward it.", "type": "boolean"}, "target_id": {"description": "Optional visible NPC, beast, or resource node id.", "type": "string"}, "target_x": {"description": "Optional desired x coordinate.", "type": "number"}, "target_z": {"description": "Optional desired z coordinate.", "type": "number"}}, "required": [], "type": "object"}}, "type": "function"}, {"function": {"description": "Move into the nearest completed house to regain safety.", "name": "go_home", "parameters": {"additionalProperties": false, "properties": {}, "required": [], "type": "object"}}, "type": "function"}, {"function": {"description": "Say one short message. With target_id it is direct speech; without a target it is a shout heard by everyone nearby (e.g. a call for help).", "name": "speak", "parameters": {"additionalProperties": false, "properties": {"intent": {"description": "Why you are speaking, e.g. help_request, warning, trade_request, social, plead, threaten.", "type": "string"}, "message": {"description": "The exact words said aloud.", "type": "string"}, "target_id": {"description": "Optional nearby NPC id to address directly.", "type": "string"}}, "required": ["message"], "type": "object"}}, "type": "function"}, {"function": {"description": "Do nothing this tick: wait, observe, or hold position defensively.", "name": "idle", "parameters": {"additionalProperties": false, "properties": {"intent": {"description": "Optional flavor, e.g. observe or defend.", "type": "string"}}, "required": [], "type": "object"}}, "type": "function"}], "top_p": 0.95}, "tick": 16}
63
+ ```
64
+ `run_20260613T142424Z` line 325, response
65
+
66
+ ```json
67
+ {"latency_ms": 1375, "npc_id": "npc-003", "parsed_action": {"action": "move", "amount": null, "away": false, "communication_intent": null, "confidence": null, "conversation_assistant": "tool:move {\"target_id\": \"res_food_6\", \"target_x\": -5.673, \"target_z\": 3.182}", "conversation_user": "{\"npc_id\": \"npc-003\", \"tick\": 16, \"own_state\": {\"name\": \"Cora\", \"role\": \"gatherer\", \"health\": 100, \"hunger\": 38, \"fear\": 0, \"safety\": 4, \"age\": 75, \"max_age\": 462, \"reproduction_cooldown\": 0, \"importance\": 1.333, \"goal\": \"obey_directive\", \"inventory\": {\"food\": 2, \"herbs\": 4, \"wood\": 1, \"weapon\": 0}}, \"goal\": \"obey_directive\", \"active_directive\": {\"text\": \"go_home\", \"source\": \"overseer\", \"issued_tick\": 15, \"ttl_ticks\": 24, \"remaining_ttl\": 23}, \"nearby_threats\": [], \"nearby_allies\": [{\"id\": \"npc-007\", \"name\": \"Gita\", \"role\": \"gatherer\", \"distance\": 4.15, \"trust\": 0.45, \"hp\": 100, \"hunger\": 40, \"inventory\": {\"food\": 1, \"herbs\": 2, \"wood\": 4, \"weapon\": 0}}, {\"id\": \"npc-002\", \"name\": \"Boris\", \"role\": \"gatherer\", \"distance\": 5.74, \"trust\": 0.45, \"hp\": 100, \"hunger\": 5, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-006\", \"name\": \"Farid\", \"role\": \"builder\", \"distance\": 6.04, \"trust\": 0.45, \"hp\": 100, \"hunger\": 37, \"inventory\": {\"food\": 0, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-001\", \"name\": \"Ada\", \"role\": \"gatherer\", \"distance\": 10.2, \"trust\": 0.45, \"hp\": 100, \"hunger\": 2, \"inventory\": {\"food\": 3, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}}, {\"id\": \"npc-00", "intent": null, "memory": null, "message": null, "npc_id": "npc-003", "resource_id": "res_food_6", "resource_type": null, "take": false, "target": {"x": -5.673, "y": 0.0, "z": 3.182}, "target_entity_id": null, "target_npc_id": null}, "phase": "npc_response", "raw_output": {"choices": [{"finish_reason": "tool_calls", "index": 0, "logprobs": null, "message": {"annotations": null, "audio": null, "content": "", "function_call": null, "reasoning": null, "reasoning_content": null, "refusal": null, "role": "assistant", "tool_calls": [{"function": {"arguments": "{\"target_id\": \"res_food_6\", \"target_x\": -5.673, \"target_z\": 3.182}", "name": "move"}, "id": "chatcmpl-tool-9653fd610cbeb43e", "type": "function"}]}, "stop_reason": null, "token_ids": null}], "created": 1781360985, "id": "chatcmpl-b9d416d296635de6", "kv_transfer_params": null, "model": "nemotron3-nano-4b-fp8", "moderation": null, "object": "chat.completion", "prompt_logprobs": null, "prompt_token_ids": null, "service_tier": null, "system_fingerprint": null, "usage": {"completion_tokens": 45, "completion_tokens_details": null, "prompt_tokens": 1982, "prompt_tokens_details": null, "total_tokens": 2027}}, "tick": 16, "validator_verdict": {"reason": "accepted", "requested": "go_home", "requested_effect": "go_home", "resolved": "go_home", "status": "accepted"}}
68
+ ```
69
+ Judgment: this verifies the directive fix. The active directive remains visible with TTL, `goal` becomes `obey_directive`, and `go_home` is included in allowed actions. The selected movement was accepted.
70
+
71
+ ## Overseer Cycle Quote
72
+ `run_20260613T142424Z` line 318, overseer request
73
+
74
+ ```json
75
+ {"messages": [{"content": "You are the Overseer, protector of a small village in a deterministic survival simulation.\n\nRead the compact world context, recent event log, active beasts, houses, resources, and critical NPC stats. Your job is to help the village survive and grow against the God of Chaos.\n\nReturn strict JSON only:\n{\"thoughts\":\"short tactical reasoning\",\"directives\":[{\"npc_id\":\"npc-004\",\"directive\":\"attack beast_2\"}],\"priority_alert\":\"short alert\"}\n\nRules:\n- Issue at most 3 concrete directives.\n- Use only NPC ids from the context.\n- Directives must be short, specific, and feasible for the NPC role.\n- Protect scarce roles, especially the last builder and wounded guards.\n- Prefer: guards attack/defend/patrol, builders build or gather wood, gatherers gather/transfer/go home.\n- The engine validates all actions and consequences. You only command intent.\n- If no action is needed, return an empty directives array.\n", "role": "system"}, {"content": "{\"tick\": 15, \"next_tick\": 16, \"game_status\": \"running\", \"population\": 10, \"population_cap\": 12, \"roles\": {\"gatherer\": 6, \"guard\": 3, \"builder\": 1}, \"scoreboard\": {\"overseer\": 2, \"chaos\": 0}, \"npcs\": [{\"id\": \"npc-004\", \"name\": \"Dima\", \"role\": \"guard\", \"hp\": 82.0, \"hunger\": 36.0, \"safety\": 72.0, \"importance\": 1.667, \"goal\": \"work\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 1}, \"allowed_actions\": [\"transfer\", \"communicate\", \"patrol\"], \"position\": {\"x\": 0.0, \"z\": 0.0}}, {\"id\": \"npc-007\", \"name\": \"Gita\", \"role\": \"gatherer\", \"hp\": 100, \"hunger\": 40.0, \"safety\": 24.0, \"importance\": 1.333, \"goal\": \"work\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 1, \"herbs\": 2, \"wood\": 4, \"weapon\": 0}, \"allowed_actions\": [\"gather\", \"move_to_resource\", \"transfer\", \"communicate\"], \"position\": {\"x\": -5.833, \"z\": 8.788}}, {\"id\": \"npc-003\", \"name\": \"Cora\", \"role\": \"gatherer\", \"hp\": 100, \"hunger\": 38.0, \"safety\": 4.0, \"importance\": 1.333, \"goal\": \"work\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 2, \"herbs\": 4, \"wood\": 1, \"weapon\": 0}, \"allowed_actions\": [\"move_to_resource\", \"transfer\", \"communicate\"], \"position\": {\"x\": -6.988, \"z\": 12.775}}, {\"id\": \"npc-006\", \"name\": \"Farid\", \"role\": \"builder\", \"hp\": 100, \"hunger\": 37.0, \"safety\": 0.0, \"importance\": 3.0, \"goal\": \"obey_directive\", \"active_directive\": \"build house\", \"directive_remaining_ttl\": 16, \"inventory\": {\"food\": 0, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}, \"allowed_actions\": [\"flee\", \"go_home\", \"move_to_resource\", \"communicate\", \"build\", \"idle\"], \"position\": {\"x\": -6.117, \"z\": 18.747}}, {\"id\": \"npc-010\", \"name\": \"Juno\", \"role\": \"guard\", \"hp\": 100, \"hunger\": 35.0, \"safety\": 60.0, \"importance\": 2.167, \"goal\": \"work\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 1}, \"allowed_actions\": [\"transfer\", \"communicate\", \"patrol\"], \"position\": {\"x\": 0.0, \"z\": 0.0}}, {\"id\": \"npc-005\", \"name\": \"Elena\", \"role\": \"guard\", \"hp\": 100, \"hunger\": 33.0, \"safety\": 72.0, \"importance\": 1.667, \"goal\": \"work\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 1, \"herbs\": 0, \"wood\": 0, \"weapon\": 1}, \"allowed_actions\": [\"transfer\", \"communicate\", \"patrol\"], \"position\": {\"x\": 0.0, \"z\": 0.0}}, {\"id\": \"npc-008\", \"name\": \"Hana\", \"role\": \"gatherer\", \"hp\": 100, \"hunger\": 5.6, \"safety\": 96.0, \"importance\": 1.333, \"goal\": \"settle\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 0, \"herbs\": 1, \"wood\": 1, \"weapon\": 0}, \"allowed_actions\": [\"go_home\", \"communicate\", \"transfer\"], \"position\": {\"x\": 0.0, \"z\": 0.0}}, {\"id\": \"npc-002\", \"name\": \"Boris\", \"role\": \"gatherer\", \"hp\": 100, \"hunger\": 4.8, \"safety\": 0.0, \"importance\": 1.333, \"goal\": \"settle\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}, \"allowed_actions\": [\"go_home\", \"consume\", \"communicate\", \"transfer\"], \"position\": {\"x\": -2.071, \"z\": 15.737}}, {\"id\": \"npc-009\", \"name\": \"Ivan\", \"role\": \"gatherer\", \"hp\": 100, \"hunger\": 4.8, \"safety\": 60.0, \"importance\": 1.333, \"goal\": \"settle\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 0, \"herbs\": 2, \"wood\": 1, \"weapon\": 0}, \"allowed_actions\": [\"go_home\", \"communicate\", \"transfer\"], \"position\": {\"x\": 0.0, \"z\": 0.0}}, {\"id\": \"npc-001\", \"name\": \"Ada\", \"role\": \"gatherer\", \"hp\": 100, \"hunger\": 2.4, \"safety\": 4.0, \"importance\": 1.333, \"goal\": \"settle\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 3, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}, \"allowed_actions\": [\"go_home\", \"consume\", \"communicate\", \"transfer\"], \"position\": {\"x\": 1.192, \"z\": 6.689}}], \"houses\": [{\"id\": \"house_001\", \"state\": \"completed\", \"hp\": 60.0, \"capacity\": 3, \"occupants\": [\"npc-001\", \"npc-004\", \"npc-005\"], \"position\": {\"x\": 0.0, \"z\": 0.0}}, {\"id\": \"house_002\", \"state\": \"under_construction\", \"hp\": 60.0, \"capacity\": 3, \"occupants\": [], \"position\": {\"x\": -7.087, \"z\": 14.866}}], \"resources\": {\"food\": 21, \"herbs\": 1, \"wood\": 12, \"weapon\": 2}, \"beasts\": [], \"current_threats\": [], \"recent_events\": [{\"tick\": 8, \"type\": \"overseer_thoughts\", \"actor_id\": null, \"target_id\": null, \"summary\": \"The village is stable with no active beasts. The single builder, Farid, has sufficient wood (5) and is a high-priority asset. I must ensure he builds immediately to expand housing capacity before population cap or threats force evacuation. Guards are idle but safe; I will leave them to patrol/standby to avoid unnecessary risk. Gatherers are active and managing resources well.\", \"severity\": \"neutral\"}, {\"tick\": 8, \"type\": \"directive_issued\", \"actor_id\": \"overseer\", \"target_id\": \"npc-006\", \"summary\": \"Overseer applied npc-006: build house\", \"severity\": \"good\"}, {\"tick\": 8, \"type\": \"gather\", \"actor_id\": \"npc-001\", \"target_id\": null, \"summary\": \"Ada gathered food\", \"severity\": \"neutral\"}, {\"tick\": 8, \"type\": \"gather\", \"actor_id\": \"npc-002\", \"target_id\": null, \"summary\": \"Boris gathered food\", \"severity\": \"neutral\"}, {\"tick\": 8, \"type\": \"gather\", \"actor_id\": \"npc-007\", \"target_id\": null, \"summary\": \"Gita gathered wood\", \"severity\": \"neutral\"}, {\"tick\": 8, \"type\": \"consume\", \"actor_id\": \"npc-008\", \"target_id\": null, \"summary\": \"Hana ate food\", \"severity\": \"neutral\"}, {\"tick\": 8, \"type\": \"gather\", \"actor_id\": \"npc-009\", \"target_id\": null, \"summary\": \"Ivan gathered wood\", \"severity\": \"neutral\"}, {\"tick\": 9, \"type\": \"gather\", \"actor_id\": \"npc-001\", \"target_id\": null, \"summary\": \"Ada gathered food\", \"severity\": \"neutral\"}, {\"tick\": 9, \"type\": \"consume\", \"actor_id\": \"npc-002\", \"target_id\": null, \"summary\": \"Boris ate food\", \"severity\": \"neutral\"}, {\"tick\": 9, \"type\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"Cora gathered herbs\", \"severity\": \"neutral\"}, {\"tick\": 9, \"type\": \"consume\", \"actor_id\": \"npc-009\", \"target_id\": null, \"summary\": \"Ivan ate food\", \"severity\": \"neutral\"}, {\"tick\": 10, \"type\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"Cora gathered herbs\", \"severity\": \"neutral\"}, {\"tick\": 10, \"type\": \"gather\", \"actor_id\": \"npc-007\", \"target_id\": null, \"summary\": \"Gita gathered wood\", \"severity\": \"neutral\"}, {\"tick\": 11, \"type\": \"consume\", \"actor_id\": \"npc-001\", \"target_id\": null, \"summary\": \"Ada ate food\", \"severity\": \"neutral\"}, {\"tick\": 11, \"type\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"Cora gathered herbs\", \"severity\": \"neutral\"}, {\"tick\": 11, \"type\": \"gather\", \"actor_id\": \"npc-007\", \"target_id\": null, \"summary\": \"Gita gathered wood\", \"severity\": \"neutral\"}, {\"tick\": 12, \"type\": \"consume\", \"actor_id\": \"npc-001\", \"target_id\": null, \"summary\": \"Ada ate food\", \"severity\": \"neutral\"}, {\"tick\": 12, \"type\": \"gather\", \"actor_id\": \"npc-007\", \"target_id\": null, \"summary\": \"Gita gathered wood\", \"severity\": \"neutral\"}, {\"tick\": 13, \"type\": \"build_started\", \"actor_id\": \"npc-006\", \"target_id\": \"house_002\", \"summary\": \"Farid started house_002\", \"severity\": \"good\"}, {\"tick\": 14, \"type\": \"gather\", \"actor_id\": \"npc-007\", \"target_id\": null, \"summary\": \"Gita gathered herbs\", \"severity\": \"neutral\"}], \"mode\": \"autopilot\"}", "role": "user"}], "mode": "autopilot", "model": "qwen3.6-27b-h100-fp8", "phase": "overseer_request", "request": {"extra_body": {"chat_template_kwargs": {"enable_thinking": false}}, "max_tokens": 1200, "messages": [{"content": "You are the Overseer, protector of a small village in a deterministic survival simulation.\n\nRead the compact world context, recent event log, active beasts, houses, resources, and critical NPC stats. Your job is to help the village survive and grow against the God of Chaos.\n\nReturn strict JSON only:\n{\"thoughts\":\"short tactical reasoning\",\"directives\":[{\"npc_id\":\"npc-004\",\"directive\":\"attack beast_2\"}],\"priority_alert\":\"short alert\"}\n\nRules:\n- Issue at most 3 concrete directives.\n- Use only NPC ids from the context.\n- Directives must be short, specific, and feasible for the NPC role.\n- Protect scarce roles, especially the last builder and wounded guards.\n- Prefer: guards attack/defend/patrol, builders build or gather wood, gatherers gather/transfer/go home.\n- The engine validates all actions and consequences. You only command intent.\n- If no action is needed, return an empty directives array.\n", "role": "system"}, {"content": "{\"tick\": 15, \"next_tick\": 16, \"game_status\": \"running\", \"population\": 10, \"population_cap\": 12, \"roles\": {\"gatherer\": 6, \"guard\": 3, \"builder\": 1}, \"scoreboard\": {\"overseer\": 2, \"chaos\": 0}, \"npcs\": [{\"id\": \"npc-004\", \"name\": \"Dima\", \"role\": \"guard\", \"hp\": 82.0, \"hunger\": 36.0, \"safety\": 72.0, \"importance\": 1.667, \"goal\": \"work\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 1, \"herbs\": 1, \"wood\": 0, \"weapon\": 1}, \"allowed_actions\": [\"transfer\", \"communicate\", \"patrol\"], \"position\": {\"x\": 0.0, \"z\": 0.0}}, {\"id\": \"npc-007\", \"name\": \"Gita\", \"role\": \"gatherer\", \"hp\": 100, \"hunger\": 40.0, \"safety\": 24.0, \"importance\": 1.333, \"goal\": \"work\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 1, \"herbs\": 2, \"wood\": 4, \"weapon\": 0}, \"allowed_actions\": [\"gather\", \"move_to_resource\", \"transfer\", \"communicate\"], \"position\": {\"x\": -5.833, \"z\": 8.788}}, {\"id\": \"npc-003\", \"name\": \"Cora\", \"role\": \"gatherer\", \"hp\": 100, \"hunger\": 38.0, \"safety\": 4.0, \"importance\": 1.333, \"goal\": \"work\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 2, \"herbs\": 4, \"wood\": 1, \"weapon\": 0}, \"allowed_actions\": [\"move_to_resource\", \"transfer\", \"communicate\"], \"position\": {\"x\": -6.988, \"z\": 12.775}}, {\"id\": \"npc-006\", \"name\": \"Farid\", \"role\": \"builder\", \"hp\": 100, \"hunger\": 37.0, \"safety\": 0.0, \"importance\": 3.0, \"goal\": \"obey_directive\", \"active_directive\": \"build house\", \"directive_remaining_ttl\": 16, \"inventory\": {\"food\": 0, \"herbs\": 1, \"wood\": 0, \"weapon\": 0}, \"allowed_actions\": [\"flee\", \"go_home\", \"move_to_resource\", \"communicate\", \"build\", \"idle\"], \"position\": {\"x\": -6.117, \"z\": 18.747}}, {\"id\": \"npc-010\", \"name\": \"Juno\", \"role\": \"guard\", \"hp\": 100, \"hunger\": 35.0, \"safety\": 60.0, \"importance\": 2.167, \"goal\": \"work\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 1}, \"allowed_actions\": [\"transfer\", \"communicate\", \"patrol\"], \"position\": {\"x\": 0.0, \"z\": 0.0}}, {\"id\": \"npc-005\", \"name\": \"Elena\", \"role\": \"guard\", \"hp\": 100, \"hunger\": 33.0, \"safety\": 72.0, \"importance\": 1.667, \"goal\": \"work\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 1, \"herbs\": 0, \"wood\": 0, \"weapon\": 1}, \"allowed_actions\": [\"transfer\", \"communicate\", \"patrol\"], \"position\": {\"x\": 0.0, \"z\": 0.0}}, {\"id\": \"npc-008\", \"name\": \"Hana\", \"role\": \"gatherer\", \"hp\": 100, \"hunger\": 5.6, \"safety\": 96.0, \"importance\": 1.333, \"goal\": \"settle\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 0, \"herbs\": 1, \"wood\": 1, \"weapon\": 0}, \"allowed_actions\": [\"go_home\", \"communicate\", \"transfer\"], \"position\": {\"x\": 0.0, \"z\": 0.0}}, {\"id\": \"npc-002\", \"name\": \"Boris\", \"role\": \"gatherer\", \"hp\": 100, \"hunger\": 4.8, \"safety\": 0.0, \"importance\": 1.333, \"goal\": \"settle\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 2, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}, \"allowed_actions\": [\"go_home\", \"consume\", \"communicate\", \"transfer\"], \"position\": {\"x\": -2.071, \"z\": 15.737}}, {\"id\": \"npc-009\", \"name\": \"Ivan\", \"role\": \"gatherer\", \"hp\": 100, \"hunger\": 4.8, \"safety\": 60.0, \"importance\": 1.333, \"goal\": \"settle\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 0, \"herbs\": 2, \"wood\": 1, \"weapon\": 0}, \"allowed_actions\": [\"go_home\", \"communicate\", \"transfer\"], \"position\": {\"x\": 0.0, \"z\": 0.0}}, {\"id\": \"npc-001\", \"name\": \"Ada\", \"role\": \"gatherer\", \"hp\": 100, \"hunger\": 2.4, \"safety\": 4.0, \"importance\": 1.333, \"goal\": \"settle\", \"active_directive\": null, \"directive_remaining_ttl\": null, \"inventory\": {\"food\": 3, \"herbs\": 0, \"wood\": 0, \"weapon\": 0}, \"allowed_actions\": [\"go_home\", \"consume\", \"communicate\", \"transfer\"], \"position\": {\"x\": 1.192, \"z\": 6.689}}], \"houses\": [{\"id\": \"house_001\", \"state\": \"completed\", \"hp\": 60.0, \"capacity\": 3, \"occupants\": [\"npc-001\", \"npc-004\", \"npc-005\"], \"position\": {\"x\": 0.0, \"z\": 0.0}}, {\"id\": \"house_002\", \"state\": \"under_construction\", \"hp\": 60.0, \"capacity\": 3, \"occupants\": [], \"position\": {\"x\": -7.087, \"z\": 14.866}}], \"resources\": {\"food\": 21, \"herbs\": 1, \"wood\": 12, \"weapon\": 2}, \"beasts\": [], \"current_threats\": [], \"recent_events\": [{\"tick\": 8, \"type\": \"overseer_thoughts\", \"actor_id\": null, \"target_id\": null, \"summary\": \"The village is stable with no active beasts. The single builder, Farid, has sufficient wood (5) and is a high-priority asset. I must ensure he builds immediately to expand housing capacity before population cap or threats force evacuation. Guards are idle but safe; I will leave them to patrol/standby to avoid unnecessary risk. Gatherers are active and managing resources well.\", \"severity\": \"neutral\"}, {\"tick\": 8, \"type\": \"directive_issued\", \"actor_id\": \"overseer\", \"target_id\": \"npc-006\", \"summary\": \"Overseer applied npc-006: build house\", \"severity\": \"good\"}, {\"tick\": 8, \"type\": \"gather\", \"actor_id\": \"npc-001\", \"target_id\": null, \"summary\": \"Ada gathered food\", \"severity\": \"neutral\"}, {\"tick\": 8, \"type\": \"gather\", \"actor_id\": \"npc-002\", \"target_id\": null, \"summary\": \"Boris gathered food\", \"severity\": \"neutral\"}, {\"tick\": 8, \"type\": \"gather\", \"actor_id\": \"npc-007\", \"target_id\": null, \"summary\": \"Gita gathered wood\", \"severity\": \"neutral\"}, {\"tick\": 8, \"type\": \"consume\", \"actor_id\": \"npc-008\", \"target_id\": null, \"summary\": \"Hana ate food\", \"severity\": \"neutral\"}, {\"tick\": 8, \"type\": \"gather\", \"actor_id\": \"npc-009\", \"target_id\": null, \"summary\": \"Ivan gathered wood\", \"severity\": \"neutral\"}, {\"tick\": 9, \"type\": \"gather\", \"actor_id\": \"npc-001\", \"target_id\": null, \"summary\": \"Ada gathered food\", \"severity\": \"neutral\"}, {\"tick\": 9, \"type\": \"consume\", \"actor_id\": \"npc-002\", \"target_id\": null, \"summary\": \"Boris ate food\", \"severity\": \"neutral\"}, {\"tick\": 9, \"type\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"Cora gathered herbs\", \"severity\": \"neutral\"}, {\"tick\": 9, \"type\": \"consume\", \"actor_id\": \"npc-009\", \"target_id\": null, \"summary\": \"Ivan ate food\", \"severity\": \"neutral\"}, {\"tick\": 10, \"type\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"Cora gathered herbs\", \"severity\": \"neutral\"}, {\"tick\": 10, \"type\": \"gather\", \"actor_id\": \"npc-007\", \"target_id\": null, \"summary\": \"Gita gathered wood\", \"severity\": \"neutral\"}, {\"tick\": 11, \"type\": \"consume\", \"actor_id\": \"npc-001\", \"target_id\": null, \"summary\": \"Ada ate food\", \"severity\": \"neutral\"}, {\"tick\": 11, \"type\": \"gather\", \"actor_id\": \"npc-003\", \"target_id\": null, \"summary\": \"Cora gathered herbs\", \"severity\": \"neutral\"}, {\"tick\": 11, \"type\": \"gather\", \"actor_id\": \"npc-007\", \"target_id\": null, \"summary\": \"Gita gathered wood\", \"severity\": \"neutral\"}, {\"tick\": 12, \"type\": \"consume\", \"actor_id\": \"npc-001\", \"target_id\": null, \"summary\": \"Ada ate food\", \"severity\": \"neutral\"}, {\"tick\": 12, \"type\": \"gather\", \"actor_id\": \"npc-007\", \"target_id\": null, \"summary\": \"Gita gathered wood\", \"severity\": \"neutral\"}, {\"tick\": 13, \"type\": \"build_started\", \"actor_id\": \"npc-006\", \"target_id\": \"house_002\", \"summary\": \"Farid started house_002\", \"severity\": \"good\"}, {\"tick\": 14, \"type\": \"gather\", \"actor_id\": \"npc-007\", \"target_id\": null, \"summary\": \"Gita gathered herbs\", \"severity\": \"neutral\"}], \"mode\": \"autopilot\"}", "role": "user"}], "model": "qwen3.6-27b-h100-fp8", "temperature": 0.6, "top_p": 0.95}, "tick": 16}
76
+ ```
77
+ `run_20260613T142424Z` line 319, overseer response
78
+
79
+ ```json
80
+ {"accepted_directives": [{"action": "consume", "directive": "transfer food to npc-006", "npc_id": "npc-002"}, {"action": "go_home", "directive": "go_home", "npc_id": "npc-003"}, {"action": "move_to_resource", "directive": "gather wood", "npc_id": "npc-007"}], "latency_ms": 10140, "parsed_json": {"directives": [{"directive": "transfer food to npc-006", "npc_id": "npc-002"}, {"directive": "go_home", "npc_id": "npc-003"}, {"directive": "gather wood", "npc_id": "npc-007"}], "priority_alert": "Builder Farid has no food; Boris ordered to transfer food immediately.", "thoughts": "The village is in a stable phase with no active beasts. The critical asset, Builder Farid (npc-006), is currently constructing house_002 but has 0 safety and 0 food. He is vulnerable. Gatherer Gita (npc-007) has wood and herbs but is far from the builder. Gatherer Cora (npc-003) has low safety (4.0) and is far out. I need to ensure Farid survives the build process. Since he cannot gather, I must direct a nearby or capable gatherer to transfer resources to him or ensure he is protected. However, looking at positions, Gita is at (-5.8, 8.8) and Farid is at (-6.1, 18.7). They are not adjacent. Cora is at (-7.0, 12.8). No one is immediately next to Farid to transfer food. Farid has 'idle' and 'go_home' as allowed actions, but his goal is 'obey_directive' (build). If he starves, the build fails. I will instruct Gita to move towards the construction site or transfer if possible, but 'transfer' usually requires proximity. Let's look at allowed actions. Gita can 'move_to_resource'. This might not help Farid directly. Actually, Farid has 0 food. He will starve soon. The best immediate action is to get someone to bring him food. Gita has 1 food. Cora has 2 food. Boris has 2 food but is at (-2.0, 15.7) which is closer to Farid (-6.1, 18.7) than Gita. Boris can 'transfer'. Let's check if Boris is close enough. Distance Boris to Farid: sqrt((−2.07+6.11)^2 + (15.74−18.74)^2) ≈ sqrt(16.3 + 9) ≈ 5. Distance Gita to Farid: sqrt((−5.8+6.1)^2 + (8.8−18.7)^2) ≈ sqrt(0.09 + 98) ≈ 10. Boris is closer. I will order Boris to transfer food to Farid. Also, Cora has very low safety (4.0) and is far out; she should return to safety or gather more aggressively if safe. Given the 'settle' goal of many gatherers, they might be idle. I will prioritize feeding the builder."}, "phase": "overseer_response", "raw_output": "{\n\"thoughts\": \"The village is in a stable phase with no active beasts. The critical asset, Builder Farid (npc-006), is currently constructing house_002 but has 0 safety and 0 food. He is vulnerable. Gatherer Gita (npc-007) has wood and herbs but is far from the builder. Gatherer Cora (npc-003) has low safety (4.0) and is far out. I need to ensure Farid survives the build process. Since he cannot gather, I must direct a nearby or capable gatherer to transfer resources to him or ensure he is protected. However, looking at positions, Gita is at (-5.8, 8.8) and Farid is at (-6.1, 18.7). They are not adjacent. Cora is at (-7.0, 12.8). No one is immediately next to Farid to transfer food. Farid has 'idle' and 'go_home' as allowed actions, but his goal is 'obey_directive' (build). If he starves, the build fails. I will instruct Gita to move towards the construction site or transfer if possible, but 'transfer' usually requires proximity. Let's look at allowed actions. Gita can 'move_to_resource'. This might not help Farid directly. Actually, Farid has 0 food. He will starve soon. The best immediate action is to get someone to bring him food. Gita has 1 food. Cora has 2 food. Boris has 2 food but is at (-2.0, 15.7) which is closer to Farid (-6.1, 18.7) than Gita. Boris can 'transfer'. Let's check if Boris is close enough. Distance Boris to Farid: sqrt((−2.07+6.11)^2 + (15.74−18.74)^2) ≈ sqrt(16.3 + 9) ≈ 5. Distance Gita to Farid: sqrt((−5.8+6.1)^2 + (8.8−18.7)^2) ≈ sqrt(0.09 + 98) ≈ 10. Boris is closer. I will order Boris to transfer food to Farid. Also, Cora has very low safety (4.0) and is far out; she should return to safety or gather more aggressively if safe. Given the 'settle' goal of many gatherers, they might be idle. I will prioritize feeding the builder.\",\n\"directives\": [\n{\n\"npc_id\": \"npc-002\",\n\"directive\": \"transfer food to npc-006\"\n},\n{\n\"npc_id\": \"npc-003\",\n\"directive\": \"go_home\"\n},\n{\n\"npc_id\": \"npc-007\",\n\"directive\": \"gather wood\"\n}\n],\n\"priority_alert\": \"Builder Farid has no food; Boris ordered to transfer food immediately.\"\n}", "rejected_directives": [], "tick": 16}
81
+ ```
82
+ Judgment: overseer context contains only living NPCs, filtered house occupants, live beasts, role counts, and active directive TTL. The request was clean. The accepted directives were feasible and attached to live NPC ids.
83
+
84
+ ## Top Problems And Evidence
85
+ | # | Problem | Ledger Evidence | Fix / Status |
86
+ | ---: | --- | --- | --- |
87
+ | 1 | Active directives were present but did not reliably drive current goal/action affordances. | Before `run_20260613T092650Z` line 1284 had `go_home` directive while allowed actions were only move/speak/use; before count: 150 directive/goal mismatches and 78 directive-action missing cases. | Fixed by making non-critical active directives select `obey_directive` before find-food/find-herbs and by applying overseer metadata before NPC prompts. After counts: 24 mismatches, 4 missing action cases. Remaining mismatches are mostly urgent eat-food overriding directive. |
88
+ | 2 | `use` was offered when a resource was visible but not actually gatherable, causing repairs to `move_to_resource`. | Before `run_20260613T092650Z` line 4: NPC response `use` repaired from `gather` to `move_to_resource`. | Fixed by filtering `gather/use` out of allowed actions unless the target resource is within gather radius. Repairs fell from 236 to 134. |
89
+ | 3 | Builder tool semantics are still overloaded. | After `run_20260613T142424Z` lines 32-33: Farid had `build` and `use`; model chose `use` on wood, validator repaired to `build`. | Residual. Best next fix is to suppress `use` for builders with enough wood unless a specific nearby wood node is the intended target, or split gather/build more explicitly in tool names. |
90
+ | 4 | Prompt payload is clean but still larger than the target once schemas and nearby allies/resources are included. | After `run_20260613T142424Z` payload chars min/avg/max: 1447/2626.2/3316; line 2 reports 1780 prompt tokens including tool schemas. | Residual. Could cap allies/resources to fewer items or move role rules/tool schemas into shorter system text. |
91
+ | 5 | Live endpoint cold starts created long model latency. | After `run_20260613T142424Z` line 2 has `latency_ms: 130978`; tick 8 overseer cycle was also cold in the HTTP run. | Operational residual. Health warmup exists, but live validation still saw cold starts. Pre-warming both Modal endpoints before the first tick would make playtests less noisy. |
92
+
93
+ ## Before/After Notes
94
+ - No dead/corpse entities appeared in live NPC target payloads inspected; regression tests cover scripted deaths across 200 ticks.
95
+ - No live model parse rejections occurred in either 100-tick run.
96
+ - No deterministic fallback occurred during the live runs, because both Modal endpoints were reachable.
97
+ - Game reached `win_population` in both live runs; the after-fix run reached it at tick 48.
config/game.modal.local.json CHANGED
@@ -51,5 +51,26 @@
51
  "enable_thinking": false
52
  }
53
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  }
55
  }
 
51
  "enable_thinking": false
52
  }
53
  }
54
+ },
55
+ "overseer": {
56
+ "mode": "autopilot",
57
+ "cycle_ticks": 8,
58
+ "max_directives": 3,
59
+ "connector": {
60
+ "type": "openai_compatible",
61
+ "base_url_env": "GOD_CONSOLE_QWEN_BASE_URL",
62
+ "model_env": "GOD_CONSOLE_QWEN_MODEL",
63
+ "base_url": "https://georgij-sawin--god-simulator-qwen36-27b-h100-serve.modal.run/v1",
64
+ "model": "qwen3.6-27b-h100-fp8",
65
+ "timeout_seconds": 600,
66
+ "max_tokens": 1200,
67
+ "temperature": 0.6,
68
+ "top_p": 0.95,
69
+ "extra_body": {
70
+ "chat_template_kwargs": {
71
+ "enable_thinking": false
72
+ }
73
+ }
74
+ }
75
  }
76
  }
frontend/src/api.ts CHANGED
@@ -43,10 +43,12 @@ export async function tickWorld(): Promise<void> {
43
  }
44
 
45
  export type GodCommandResult = {
46
- source: string;
 
 
47
  summary: string;
48
  applied: string[];
49
- snapshot: WorldSnapshot;
50
  };
51
 
52
  export async function sendGodCommand(command: string): Promise<GodCommandResult> {
@@ -63,9 +65,11 @@ export async function sendGodCommand(command: string): Promise<GodCommandResult>
63
 
64
  export type ChaosActionResult = {
65
  action: string;
 
 
66
  applied: string[];
67
  summary: string;
68
- snapshot: WorldSnapshot;
69
  };
70
 
71
  export async function sendChaosAction(action: string): Promise<ChaosActionResult> {
 
43
  }
44
 
45
  export type GodCommandResult = {
46
+ source?: string;
47
+ queued?: boolean;
48
+ applies_on_tick?: number;
49
  summary: string;
50
  applied: string[];
51
+ snapshot?: WorldSnapshot;
52
  };
53
 
54
  export async function sendGodCommand(command: string): Promise<GodCommandResult> {
 
65
 
66
  export type ChaosActionResult = {
67
  action: string;
68
+ queued?: boolean;
69
+ applies_on_tick?: number;
70
  applied: string[];
71
  summary: string;
72
+ snapshot?: WorldSnapshot;
73
  };
74
 
75
  export async function sendChaosAction(action: string): Promise<ChaosActionResult> {
frontend/src/hooks/useWorldSimulation.ts CHANGED
@@ -85,9 +85,11 @@ export function useWorldSimulation() {
85
  setGodMessage(null);
86
  try {
87
  const result = await sendGodCommand(command);
88
- setSnapshot(result.snapshot);
 
 
89
  setGodCommand("");
90
- setGodMessage(result.applied[0] ?? result.summary);
91
  } catch (nextError) {
92
  setError(nextError instanceof Error ? nextError.message : "God command failed");
93
  } finally {
@@ -108,8 +110,10 @@ export function useWorldSimulation() {
108
  for (let attempt = 0; ; attempt += 1) {
109
  try {
110
  const result = await sendChaosAction(action);
111
- setSnapshot(result.snapshot);
112
- setChaosMessage(result.summary);
 
 
113
  return;
114
  } catch (nextError) {
115
  const message =
 
85
  setGodMessage(null);
86
  try {
87
  const result = await sendGodCommand(command);
88
+ if (result.snapshot) {
89
+ setSnapshot(result.snapshot);
90
+ }
91
  setGodCommand("");
92
+ setGodMessage(result.summary || result.applied[0] || "Command queued for the next tick");
93
  } catch (nextError) {
94
  setError(nextError instanceof Error ? nextError.message : "God command failed");
95
  } finally {
 
110
  for (let attempt = 0; ; attempt += 1) {
111
  try {
112
  const result = await sendChaosAction(action);
113
+ if (result.snapshot) {
114
+ setSnapshot(result.snapshot);
115
+ }
116
+ setChaosMessage(result.summary || "Chaos action queued for the next tick");
117
  return;
118
  } catch (nextError) {
119
  const message =
pyproject.toml CHANGED
@@ -43,6 +43,7 @@ strict = true
43
  mypy_path = "src"
44
 
45
  [tool.pytest.ini_options]
 
46
  testpaths = ["tests"]
47
  pythonpath = ["src"]
48
 
 
43
  mypy_path = "src"
44
 
45
  [tool.pytest.ini_options]
46
+ addopts = "--basetemp=tmp/pytest"
47
  testpaths = ["tests"]
48
  pythonpath = ["src"]
49
 
src/god_simulator/api/runtime.py CHANGED
@@ -2,7 +2,7 @@ from __future__ import annotations
2
 
3
  import time
4
  from copy import deepcopy
5
- from dataclasses import dataclass, field
6
  from http import HTTPStatus
7
  from threading import Lock, Thread
8
  from typing import Any, Protocol
@@ -11,6 +11,7 @@ from urllib.request import urlopen
11
 
12
  from god_simulator.config import ConnectorConfig, GameConfig
13
  from god_simulator.domain import WorldState
 
14
  from god_simulator.rendering.claw3d_contract import to_claw3d_snapshot
15
  from god_simulator.simulation.chaos import (
16
  CHAOS_COOLDOWNS,
@@ -20,6 +21,8 @@ from god_simulator.simulation.chaos import (
20
  from god_simulator.simulation.connectors.base import WorldSimulator
21
  from god_simulator.simulation.connectors.factory import create_world_simulator
22
  from god_simulator.simulation.god_console import GodConsole, apply_god_command_plan
 
 
23
  from god_simulator.simulation.overseer import OverseerController, create_overseer
24
  from god_simulator.simulation.tick import apply_tick_plan, plan_world_tick
25
 
@@ -33,16 +36,19 @@ class GameRuntime:
33
  god_console: GodConsole | None = None,
34
  modal_health_warmer: HealthWarmer | None = None,
35
  overseer: OverseerController | None = None,
 
36
  ) -> None:
37
  self._world = world
38
  self._simulator = simulator
39
  self._god_console = god_console
40
  self._modal_health_warmer = modal_health_warmer
41
  self._overseer = overseer
 
42
  self._lock = Lock()
43
  self._tick_status = TickStatus()
44
  self._god_status = GodCommandStatus()
45
  self._chaos_status = ChaosStatus()
 
46
 
47
  @property
48
  def simulator_name(self) -> str:
@@ -82,13 +88,27 @@ class GameRuntime:
82
  return payload
83
 
84
  def tick(self) -> tuple[HTTPStatus, dict[str, Any]]:
85
- planning_world, next_tick, conflict = self._begin_tick()
86
  if conflict is not None:
87
  return HTTPStatus.CONFLICT, conflict
88
  assert planning_world is not None
89
  assert next_tick is not None
 
 
 
 
 
 
 
 
90
 
91
  try:
 
 
 
 
 
 
92
  planned_tick, plan = plan_world_tick(
93
  planning_world,
94
  self._simulator,
@@ -99,18 +119,35 @@ class GameRuntime:
99
  with self._lock:
100
  self._tick_status.in_progress = False
101
  self._tick_status.pending_tick = None
 
 
102
  return HTTPStatus.INTERNAL_SERVER_ERROR, {
103
  "error": "tick_failed",
104
  "message": str(exc),
105
  }
106
 
107
  with self._lock:
 
 
 
108
  apply_tick_plan(self._world, planned_tick, plan)
 
 
 
 
 
 
 
 
 
 
109
  self._tick_status.in_progress = False
110
  self._tick_status.pending_tick = None
111
  payload = self._world.to_dict()
112
  payload["simulation"] = tick_status_payload(self._tick_status)
113
- return HTTPStatus.OK, payload
 
 
114
 
115
  def god_command(self, command: str) -> tuple[HTTPStatus, dict[str, Any]]:
116
  if self._god_console is None:
@@ -121,33 +158,16 @@ class GameRuntime:
121
  "message": "Expected non-empty 'command'.",
122
  }
123
 
124
- planning_world, conflict = self._begin_god_command()
125
- if conflict is not None:
126
- return HTTPStatus.CONFLICT, conflict
127
- assert planning_world is not None
128
-
129
- try:
130
- plan = self._god_console.propose(planning_world, command.strip())
131
- except Exception as exc:
132
- with self._lock:
133
- self._god_status.in_progress = False
134
- return HTTPStatus.INTERNAL_SERVER_ERROR, {
135
- "error": "god_command_failed",
136
- "message": str(exc),
137
- }
138
-
139
  with self._lock:
140
- applied = apply_god_command_plan(self._world, plan)
141
- self._god_status.in_progress = False
 
 
142
  return HTTPStatus.OK, {
143
- "source": plan.source,
144
- "summary": plan.summary,
145
- "applied": applied,
146
- "snapshot": to_claw3d_snapshot(
147
- self._world,
148
- tick_in_progress=self._tick_status.in_progress,
149
- pending_tick=self._tick_status.pending_tick,
150
- ),
151
  }
152
 
153
  def chaos_action(self, action: str) -> tuple[HTTPStatus, dict[str, Any]]:
@@ -159,13 +179,6 @@ class GameRuntime:
159
  }
160
 
161
  with self._lock:
162
- if self._tick_status.in_progress:
163
- return HTTPStatus.CONFLICT, {
164
- "error": "tick_in_progress",
165
- "message": "Chaos tools are disabled while a tick is running.",
166
- **tick_status_payload(self._tick_status),
167
- }
168
-
169
  last_used = self._chaos_status.last_used.get(action)
170
  if last_used is not None:
171
  remaining = last_used + CHAOS_COOLDOWNS[action] - self._world.tick
@@ -178,36 +191,115 @@ class GameRuntime:
178
  "remaining_ticks": remaining,
179
  }
180
 
181
- applied = apply_chaos_action(self._world, action)
182
- if applied:
183
- self._chaos_status.last_used[action] = self._world.tick
184
- snapshot = to_claw3d_snapshot(
185
- self._world,
186
- tick_in_progress=self._tick_status.in_progress,
187
- pending_tick=self._tick_status.pending_tick,
188
- )
189
- snapshot["simulation"]["chaos_tools"] = chaos_tools_payload(
190
- self._chaos_status, self._world.tick
191
- )
192
  return HTTPStatus.OK, {
193
  "action": action,
194
- "applied": applied,
195
- "summary": applied[0]
196
- if applied
197
- else f"{CHAOS_TOOL_LABELS[action]} had no effect.",
198
- "snapshot": snapshot,
199
  }
200
 
201
- def _begin_tick(self) -> tuple[WorldState | None, int | None, dict[str, Any] | None]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  with self._lock:
203
  if self._tick_status.in_progress:
204
- return None, None, {
205
  "error": "tick_in_progress",
206
  "tick": self._world.tick,
207
  **tick_status_payload(self._tick_status),
208
  }
209
  if self._god_status.in_progress:
210
- return None, None, {
211
  "error": "god_command_in_progress",
212
  "message": "A god command is already modifying the world.",
213
  "tick": self._world.tick,
@@ -216,9 +308,11 @@ class GameRuntime:
216
 
217
  next_tick = self._world.tick + 1
218
  planning_world = deepcopy(self._world)
 
 
219
  self._tick_status.in_progress = True
220
  self._tick_status.pending_tick = next_tick
221
- return planning_world, next_tick, None
222
 
223
  def _begin_god_command(self) -> tuple[WorldState | None, dict[str, Any] | None]:
224
  with self._lock:
@@ -268,6 +362,18 @@ class GodCommandStatus:
268
  in_progress: bool = False
269
 
270
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  @dataclass(slots=True)
272
  class ChaosStatus:
273
  last_used: dict[str, int] = field(default_factory=dict)
@@ -475,10 +581,13 @@ def modal_health_urls(config: GameConfig) -> list[str]:
475
 
476
  def modal_health_targets(config: GameConfig) -> list[ModalHealthTarget]:
477
  targets: list[ModalHealthTarget] = []
478
- for target_id, label, connector in (
479
  ("npc_model", "NPC model", config.connector),
480
  ("god_console", "God Console", config.god_console),
481
- ):
 
 
 
482
  if connector is None:
483
  continue
484
  health_url = modal_health_url(connector)
 
2
 
3
  import time
4
  from copy import deepcopy
5
+ from dataclasses import asdict, dataclass, field
6
  from http import HTTPStatus
7
  from threading import Lock, Thread
8
  from typing import Any, Protocol
 
11
 
12
  from god_simulator.config import ConnectorConfig, GameConfig
13
  from god_simulator.domain import WorldState
14
+ from god_simulator.observability import RunLedger, append_record, set_active_tick_buffer
15
  from god_simulator.rendering.claw3d_contract import to_claw3d_snapshot
16
  from god_simulator.simulation.chaos import (
17
  CHAOS_COOLDOWNS,
 
21
  from god_simulator.simulation.connectors.base import WorldSimulator
22
  from god_simulator.simulation.connectors.factory import create_world_simulator
23
  from god_simulator.simulation.god_console import GodConsole, apply_god_command_plan
24
+ from god_simulator.simulation.god_console import GodCommandPlan
25
+ from god_simulator.simulation.directives import expire_directives
26
  from god_simulator.simulation.overseer import OverseerController, create_overseer
27
  from god_simulator.simulation.tick import apply_tick_plan, plan_world_tick
28
 
 
36
  god_console: GodConsole | None = None,
37
  modal_health_warmer: HealthWarmer | None = None,
38
  overseer: OverseerController | None = None,
39
+ ledger: RunLedger | None = None,
40
  ) -> None:
41
  self._world = world
42
  self._simulator = simulator
43
  self._god_console = god_console
44
  self._modal_health_warmer = modal_health_warmer
45
  self._overseer = overseer
46
+ self._ledger = ledger or RunLedger()
47
  self._lock = Lock()
48
  self._tick_status = TickStatus()
49
  self._god_status = GodCommandStatus()
50
  self._chaos_status = ChaosStatus()
51
+ self._pending_commands: list[PendingCommand] = []
52
 
53
  @property
54
  def simulator_name(self) -> str:
 
88
  return payload
89
 
90
  def tick(self) -> tuple[HTTPStatus, dict[str, Any]]:
91
+ planning_world, next_tick, pending_commands, conflict = self._begin_tick()
92
  if conflict is not None:
93
  return HTTPStatus.CONFLICT, conflict
94
  assert planning_world is not None
95
  assert next_tick is not None
96
+ assert pending_commands is not None
97
+
98
+ buffer = self._ledger.start_tick(
99
+ next_tick,
100
+ npc_order=[npc.id for npc in planning_world.living_npcs()],
101
+ )
102
+ set_active_tick_buffer(buffer)
103
+ prepared_commands: list[PreparedCommand] = []
104
 
105
  try:
106
+ prepared_commands = self._prepare_pending_commands(
107
+ planning_world,
108
+ pending_commands,
109
+ next_tick=next_tick,
110
+ )
111
+ expire_directives(planning_world, tick=next_tick)
112
  planned_tick, plan = plan_world_tick(
113
  planning_world,
114
  self._simulator,
 
119
  with self._lock:
120
  self._tick_status.in_progress = False
121
  self._tick_status.pending_tick = None
122
+ self._pending_commands = [*pending_commands, *self._pending_commands]
123
+ set_active_tick_buffer(None)
124
  return HTTPStatus.INTERNAL_SERVER_ERROR, {
125
  "error": "tick_failed",
126
  "message": str(exc),
127
  }
128
 
129
  with self._lock:
130
+ before_events = len(self._world.event_log)
131
+ self._apply_prepared_commands(self._world, prepared_commands)
132
+ expire_directives(self._world, tick=planned_tick)
133
  apply_tick_plan(self._world, planned_tick, plan)
134
+ append_record(
135
+ {
136
+ "tick": planned_tick,
137
+ "phase": "engine_events",
138
+ "events": [
139
+ event
140
+ for event in self._world.to_dict()["event_log"][before_events:]
141
+ ],
142
+ }
143
+ )
144
  self._tick_status.in_progress = False
145
  self._tick_status.pending_tick = None
146
  payload = self._world.to_dict()
147
  payload["simulation"] = tick_status_payload(self._tick_status)
148
+ self._ledger.flush_tick(buffer)
149
+ set_active_tick_buffer(None)
150
+ return HTTPStatus.OK, payload
151
 
152
  def god_command(self, command: str) -> tuple[HTTPStatus, dict[str, Any]]:
153
  if self._god_console is None:
 
158
  "message": "Expected non-empty 'command'.",
159
  }
160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  with self._lock:
162
+ self._pending_commands.append(
163
+ PendingCommand(kind="god_console", raw_input=command.strip())
164
+ )
165
+ applies_on_tick = self._queued_command_tick()
166
  return HTTPStatus.OK, {
167
+ "queued": True,
168
+ "applies_on_tick": applies_on_tick,
169
+ "summary": f"God command queued for tick {applies_on_tick}.",
170
+ "applied": [],
 
 
 
 
171
  }
172
 
173
  def chaos_action(self, action: str) -> tuple[HTTPStatus, dict[str, Any]]:
 
179
  }
180
 
181
  with self._lock:
 
 
 
 
 
 
 
182
  last_used = self._chaos_status.last_used.get(action)
183
  if last_used is not None:
184
  remaining = last_used + CHAOS_COOLDOWNS[action] - self._world.tick
 
191
  "remaining_ticks": remaining,
192
  }
193
 
194
+ if any(command.kind == "chaos" and command.raw_input == action for command in self._pending_commands):
195
+ return HTTPStatus.CONFLICT, {
196
+ "error": "chaos_already_queued",
197
+ "message": f"{CHAOS_TOOL_LABELS[action]} is already queued.",
198
+ }
199
+ self._pending_commands.append(PendingCommand(kind="chaos", raw_input=action))
200
+ applies_on_tick = self._queued_command_tick()
 
 
 
 
201
  return HTTPStatus.OK, {
202
  "action": action,
203
+ "queued": True,
204
+ "applies_on_tick": applies_on_tick,
205
+ "applied": [],
206
+ "summary": f"{CHAOS_TOOL_LABELS[action]} queued for tick {applies_on_tick}.",
 
207
  }
208
 
209
+ def _prepare_pending_commands(
210
+ self,
211
+ world: WorldState,
212
+ pending_commands: list[PendingCommand],
213
+ *,
214
+ next_tick: int,
215
+ ) -> list[PreparedCommand]:
216
+ prepared: list[PreparedCommand] = []
217
+ for pending in pending_commands:
218
+ if pending.kind == "god_console":
219
+ if self._god_console is None:
220
+ append_record(
221
+ {
222
+ "tick": next_tick,
223
+ "phase": "god_command",
224
+ "kind": pending.kind,
225
+ "raw_input": pending.raw_input,
226
+ "parsed_interpretation": None,
227
+ "applied_effects": [],
228
+ "error": "god_console_unavailable",
229
+ }
230
+ )
231
+ continue
232
+ plan = self._god_console.propose(world, pending.raw_input)
233
+ applied = apply_god_command_plan(world, plan)
234
+ append_record(
235
+ {
236
+ "tick": next_tick,
237
+ "phase": "god_command",
238
+ "kind": pending.kind,
239
+ "raw_input": pending.raw_input,
240
+ "model_request": plan.request,
241
+ "raw_model_output": plan.raw_response,
242
+ "parsed_interpretation": {
243
+ "source": plan.source,
244
+ "summary": plan.summary,
245
+ "edits": [asdict(edit) for edit in plan.edits],
246
+ },
247
+ "applied_effects": applied,
248
+ "latency_ms": plan.latency_ms,
249
+ }
250
+ )
251
+ prepared.append(PreparedCommand(pending=pending, god_plan=plan))
252
+ continue
253
+
254
+ if pending.kind == "chaos":
255
+ applied = apply_chaos_action(world, pending.raw_input)
256
+ append_record(
257
+ {
258
+ "tick": next_tick,
259
+ "phase": "god_command",
260
+ "kind": pending.kind,
261
+ "raw_input": pending.raw_input,
262
+ "parsed_interpretation": {
263
+ "action": pending.raw_input,
264
+ "label": CHAOS_TOOL_LABELS.get(pending.raw_input),
265
+ },
266
+ "applied_effects": applied,
267
+ }
268
+ )
269
+ prepared.append(PreparedCommand(pending=pending))
270
+ return prepared
271
+
272
+ def _apply_prepared_commands(
273
+ self,
274
+ world: WorldState,
275
+ prepared_commands: list[PreparedCommand],
276
+ ) -> None:
277
+ for prepared in prepared_commands:
278
+ pending = prepared.pending
279
+ if pending.kind == "god_console" and prepared.god_plan is not None:
280
+ apply_god_command_plan(world, prepared.god_plan)
281
+ elif pending.kind == "chaos":
282
+ applied = apply_chaos_action(world, pending.raw_input)
283
+ if applied:
284
+ self._chaos_status.last_used[pending.raw_input] = world.tick + 1
285
+
286
+ def _queued_command_tick(self) -> int:
287
+ if self._tick_status.in_progress and self._tick_status.pending_tick is not None:
288
+ return self._tick_status.pending_tick + 1
289
+ return self._world.tick + 1
290
+
291
+ def _begin_tick(
292
+ self,
293
+ ) -> tuple[WorldState | None, int | None, list[PendingCommand] | None, dict[str, Any] | None]:
294
  with self._lock:
295
  if self._tick_status.in_progress:
296
+ return None, None, None, {
297
  "error": "tick_in_progress",
298
  "tick": self._world.tick,
299
  **tick_status_payload(self._tick_status),
300
  }
301
  if self._god_status.in_progress:
302
+ return None, None, None, {
303
  "error": "god_command_in_progress",
304
  "message": "A god command is already modifying the world.",
305
  "tick": self._world.tick,
 
308
 
309
  next_tick = self._world.tick + 1
310
  planning_world = deepcopy(self._world)
311
+ pending_commands = list(self._pending_commands)
312
+ self._pending_commands.clear()
313
  self._tick_status.in_progress = True
314
  self._tick_status.pending_tick = next_tick
315
+ return planning_world, next_tick, pending_commands, None
316
 
317
  def _begin_god_command(self) -> tuple[WorldState | None, dict[str, Any] | None]:
318
  with self._lock:
 
362
  in_progress: bool = False
363
 
364
 
365
+ @dataclass(frozen=True, slots=True)
366
+ class PendingCommand:
367
+ kind: str
368
+ raw_input: str
369
+
370
+
371
+ @dataclass(frozen=True, slots=True)
372
+ class PreparedCommand:
373
+ pending: PendingCommand
374
+ god_plan: GodCommandPlan | None = None
375
+
376
+
377
  @dataclass(slots=True)
378
  class ChaosStatus:
379
  last_used: dict[str, int] = field(default_factory=dict)
 
581
 
582
  def modal_health_targets(config: GameConfig) -> list[ModalHealthTarget]:
583
  targets: list[ModalHealthTarget] = []
584
+ connector_targets: list[tuple[str, str, ConnectorConfig | None]] = [
585
  ("npc_model", "NPC model", config.connector),
586
  ("god_console", "God Console", config.god_console),
587
+ ]
588
+ if config.overseer.mode != "off":
589
+ connector_targets.append(("overseer", "Overseer", config.overseer.connector))
590
+ for target_id, label, connector in connector_targets:
591
  if connector is None:
592
  continue
593
  health_url = modal_health_url(connector)
src/god_simulator/domain.py CHANGED
@@ -113,6 +113,9 @@ class Npc:
113
  attack_damage: int = 10
114
  personality: str = "neutral"
115
  god_directive: str | None = None
 
 
 
116
  intention: str = "idle"
117
  memory_summary: str | None = None
118
  memory: list[MemoryEntry] = field(default_factory=list)
@@ -246,6 +249,9 @@ class WorldState:
246
  overseer_last_directives: list[dict[str, Any]] = field(default_factory=list)
247
  overseer_status: str = "idle"
248
 
 
 
 
249
  def to_dict(self) -> dict[str, Any]:
250
  return asdict(self)
251
 
 
113
  attack_damage: int = 10
114
  personality: str = "neutral"
115
  god_directive: str | None = None
116
+ directive_source: str | None = None
117
+ directive_issued_tick: int | None = None
118
+ directive_ttl_ticks: int | None = None
119
  intention: str = "idle"
120
  memory_summary: str | None = None
121
  memory: list[MemoryEntry] = field(default_factory=list)
 
249
  overseer_last_directives: list[dict[str, Any]] = field(default_factory=list)
250
  overseer_status: str = "idle"
251
 
252
+ def living_npcs(self) -> list[Npc]:
253
+ return [npc for npc in self.npcs if npc.health > 0]
254
+
255
  def to_dict(self) -> dict[str, Any]:
256
  return asdict(self)
257
 
src/god_simulator/observability.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import asdict, is_dataclass
5
+ from datetime import UTC, datetime
6
+ from pathlib import Path
7
+ from threading import Lock
8
+ from typing import Any
9
+
10
+
11
+ _ACTIVE_TICK: TickLedgerBuffer | None = None
12
+ _ACTIVE_LOCK = Lock()
13
+
14
+
15
+ class RunLedger:
16
+ def __init__(self, root: Path = Path("logs")) -> None:
17
+ timestamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
18
+ run_dir = root / f"run_{timestamp}"
19
+ suffix = 1
20
+ while run_dir.exists():
21
+ run_dir = root / f"run_{timestamp}_{suffix:02d}"
22
+ suffix += 1
23
+ run_dir.mkdir(parents=True, exist_ok=False)
24
+ self.run_dir = run_dir
25
+ self.ledger_path = run_dir / "ledger.jsonl"
26
+ self.pretty_path = run_dir / "pretty.log"
27
+ self._jsonl = self.ledger_path.open("a", encoding="utf-8")
28
+ self._pretty = self.pretty_path.open("a", encoding="utf-8")
29
+ self._lock = Lock()
30
+
31
+ def start_tick(self, tick: int, *, npc_order: list[str]) -> TickLedgerBuffer:
32
+ return TickLedgerBuffer(tick=tick, npc_order=npc_order)
33
+
34
+ def flush_tick(self, buffer: TickLedgerBuffer) -> None:
35
+ records = buffer.sorted_records()
36
+ if not records:
37
+ return
38
+ with self._lock:
39
+ for record in records:
40
+ clean = {key: value for key, value in record.items() if not key.startswith("_")}
41
+ self._jsonl.write(json.dumps(_json_safe(clean), ensure_ascii=False, sort_keys=True))
42
+ self._jsonl.write("\n")
43
+ self._pretty.write(_pretty_line(clean))
44
+ self._pretty.write("\n")
45
+ self._jsonl.flush()
46
+ self._pretty.flush()
47
+
48
+
49
+ class TickLedgerBuffer:
50
+ def __init__(self, *, tick: int, npc_order: list[str]) -> None:
51
+ self.tick = tick
52
+ self._npc_order = {npc_id: index for index, npc_id in enumerate(npc_order)}
53
+ self._records: list[dict[str, Any]] = []
54
+ self._counter = 0
55
+ self._lock = Lock()
56
+
57
+ def append(self, record: dict[str, Any]) -> None:
58
+ with self._lock:
59
+ self._counter += 1
60
+ enriched = dict(record)
61
+ enriched.setdefault("tick", self.tick)
62
+ enriched["_insert_order"] = self._counter
63
+ enriched["_sort_order"] = self._sort_order(enriched)
64
+ self._records.append(enriched)
65
+
66
+ def sorted_records(self) -> list[dict[str, Any]]:
67
+ with self._lock:
68
+ return sorted(
69
+ (dict(record) for record in self._records),
70
+ key=lambda record: (record["_sort_order"], record["_insert_order"]),
71
+ )
72
+
73
+ def _sort_order(self, record: dict[str, Any]) -> float:
74
+ phase = record.get("phase")
75
+ if phase == "god_command":
76
+ return 0
77
+ if phase == "directive_expired":
78
+ return 0.5
79
+ if phase == "overseer_request":
80
+ return 1
81
+ if phase == "overseer_response":
82
+ return 2
83
+ if phase in {"npc_request", "npc_response", "npc_fallback"}:
84
+ npc_index = self._npc_order.get(str(record.get("npc_id")), 9999)
85
+ offset = {"npc_request": 0, "npc_response": 1, "npc_fallback": 2}[phase]
86
+ return 10 + (npc_index * 3) + offset
87
+ if phase == "engine_events":
88
+ return 99999
89
+ return 50000
90
+
91
+
92
+ def set_active_tick_buffer(buffer: TickLedgerBuffer | None) -> None:
93
+ global _ACTIVE_TICK
94
+ with _ACTIVE_LOCK:
95
+ _ACTIVE_TICK = buffer
96
+
97
+
98
+ def append_record(record: dict[str, Any]) -> None:
99
+ with _ACTIVE_LOCK:
100
+ buffer = _ACTIVE_TICK
101
+ if buffer is not None:
102
+ buffer.append(record)
103
+
104
+
105
+ def _json_safe(value: Any) -> Any:
106
+ if is_dataclass(value):
107
+ return _json_safe(asdict(value))
108
+ if isinstance(value, dict):
109
+ return {str(key): _json_safe(item) for key, item in value.items()}
110
+ if isinstance(value, list | tuple):
111
+ return [_json_safe(item) for item in value]
112
+ if isinstance(value, Path):
113
+ return str(value)
114
+ return value
115
+
116
+
117
+ def _pretty_line(record: dict[str, Any]) -> str:
118
+ tick = record.get("tick", "?")
119
+ phase = record.get("phase", "unknown")
120
+ npc = record.get("npc_id")
121
+ suffix = f" npc={npc}" if npc else ""
122
+ compact = json.dumps(_json_safe(record), ensure_ascii=False, sort_keys=True)
123
+ if len(compact) > 900:
124
+ compact = compact[:897] + "..."
125
+ return f"tick={tick} phase={phase}{suffix} {compact}"
src/god_simulator/simulation/actions/hints.py CHANGED
@@ -105,7 +105,7 @@ def _goal_target_in_range(world: WorldState, npc: Npc, goal: CitizenGoal) -> boo
105
  if goal.target_npc_id is None:
106
  return False
107
  target = next(
108
- (candidate for candidate in world.npcs if candidate.id == goal.target_npc_id),
109
  None,
110
  )
111
  if target is None or not is_alive(target):
 
105
  if goal.target_npc_id is None:
106
  return False
107
  target = next(
108
+ (candidate for candidate in world.living_npcs() if candidate.id == goal.target_npc_id),
109
  None,
110
  )
111
  if target is None or not is_alive(target):
src/god_simulator/simulation/autopilot.py CHANGED
@@ -176,4 +176,4 @@ def idle_directive(
176
 
177
 
178
  def _npc_by_id(world: WorldState, npc_id: str) -> Npc | None:
179
- return next((candidate for candidate in world.npcs if candidate.id == npc_id), None)
 
176
 
177
 
178
  def _npc_by_id(world: WorldState, npc_id: str) -> Npc | None:
179
+ return next((candidate for candidate in world.living_npcs() if candidate.id == npc_id), None)
src/god_simulator/simulation/chaos.py CHANGED
@@ -11,6 +11,7 @@ from __future__ import annotations
11
  import random
12
 
13
  from god_simulator.domain import Beast, WorldState
 
14
  from god_simulator.simulation.mechanics import is_alive
15
  from god_simulator.simulation.survival import (
16
  _log_event,
@@ -124,13 +125,19 @@ def end_famine_if_due(world: WorldState) -> None:
124
 
125
 
126
  def _apply_maniac(world: WorldState) -> list[str]:
127
- candidates = [npc for npc in world.npcs if is_alive(npc)]
128
  if not candidates:
129
  return []
130
 
131
  rng = random.Random(f"{world.seed}:{world.tick}:chaos_maniac")
132
  victim = rng.choice(candidates)
133
- victim.god_directive = MANIAC_DIRECTIVE
 
 
 
 
 
 
134
  victim.personality = "violent maniac"
135
  _log_event(
136
  world,
 
11
  import random
12
 
13
  from god_simulator.domain import Beast, WorldState
14
+ from god_simulator.simulation.directives import set_active_directive
15
  from god_simulator.simulation.mechanics import is_alive
16
  from god_simulator.simulation.survival import (
17
  _log_event,
 
125
 
126
 
127
  def _apply_maniac(world: WorldState) -> list[str]:
128
+ candidates = [npc for npc in world.living_npcs() if is_alive(npc)]
129
  if not candidates:
130
  return []
131
 
132
  rng = random.Random(f"{world.seed}:{world.tick}:chaos_maniac")
133
  victim = rng.choice(candidates)
134
+ set_active_directive(
135
+ victim,
136
+ MANIAC_DIRECTIVE,
137
+ source="chaos:maniac",
138
+ tick=world.tick,
139
+ ttl_ticks=60,
140
+ )
141
  victim.personality = "violent maniac"
142
  _log_event(
143
  world,
src/god_simulator/simulation/connectors/base.py CHANGED
@@ -1,6 +1,6 @@
1
  from __future__ import annotations
2
 
3
- from dataclasses import dataclass
4
  from typing import Any, Literal, Protocol, TypeAlias
5
 
6
  from god_simulator.domain import Vec3, WorldState
@@ -106,6 +106,7 @@ class TickPlan:
106
  source: str
107
  directives: list[NpcDirective]
108
  overseer: dict[str, Any] | None = None
 
109
 
110
 
111
  class WorldSimulator(Protocol):
 
1
  from __future__ import annotations
2
 
3
+ from dataclasses import dataclass, field
4
  from typing import Any, Literal, Protocol, TypeAlias
5
 
6
  from god_simulator.domain import Vec3, WorldState
 
106
  source: str
107
  directives: list[NpcDirective]
108
  overseer: dict[str, Any] | None = None
109
+ ledger_entries: list[dict[str, Any]] = field(default_factory=list)
110
 
111
 
112
  class WorldSimulator(Protocol):
src/god_simulator/simulation/connectors/deterministic.py CHANGED
@@ -4,7 +4,7 @@ import random
4
 
5
  from god_simulator.domain import Vec3, WorldState
6
  from god_simulator.simulation.connectors.base import NpcDirective, TickPlan
7
- from god_simulator.simulation.mechanics import BLOCK_SIZE, is_alive
8
  from god_simulator.simulation.survival import propose_survival_tick
9
 
10
 
@@ -15,16 +15,27 @@ class DeterministicWorldSimulator:
15
  # Survival worlds get the deterministic survival planner so the core
16
  # loop (flee/fight/gather/eat/heal) is visible without any LLM.
17
  if world.beasts or world.resource_nodes:
18
- return propose_survival_tick(world, next_tick)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  half_width = world.terrain.width / 2
21
  half_depth = world.terrain.depth / 2
22
  directives: list[NpcDirective] = []
23
 
24
- for npc in world.npcs:
25
- if not is_alive(npc):
26
- continue
27
-
28
  rng = random.Random(f"{world.seed}:{next_tick}:{npc.id}")
29
  dx = rng.choice([-BLOCK_SIZE, 0, BLOCK_SIZE])
30
  dz = rng.choice([-BLOCK_SIZE, 0, BLOCK_SIZE])
@@ -41,7 +52,19 @@ class DeterministicWorldSimulator:
41
  )
42
  )
43
 
44
- return TickPlan(source=self.name, directives=directives)
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
 
47
  def _clamp(value: float, minimum: float, maximum: float) -> float:
 
4
 
5
  from god_simulator.domain import Vec3, WorldState
6
  from god_simulator.simulation.connectors.base import NpcDirective, TickPlan
7
+ from god_simulator.simulation.mechanics import BLOCK_SIZE
8
  from god_simulator.simulation.survival import propose_survival_tick
9
 
10
 
 
15
  # Survival worlds get the deterministic survival planner so the core
16
  # loop (flee/fight/gather/eat/heal) is visible without any LLM.
17
  if world.beasts or world.resource_nodes:
18
+ plan = propose_survival_tick(world, next_tick)
19
+ return TickPlan(
20
+ source=plan.source,
21
+ directives=plan.directives,
22
+ overseer=plan.overseer,
23
+ ledger_entries=[
24
+ {
25
+ "phase": "npc_fallback",
26
+ "npc_id": directive.npc_id,
27
+ "reason": "deterministic survival planner",
28
+ "action": directive.action,
29
+ }
30
+ for directive in plan.directives
31
+ ],
32
+ )
33
 
34
  half_width = world.terrain.width / 2
35
  half_depth = world.terrain.depth / 2
36
  directives: list[NpcDirective] = []
37
 
38
+ for npc in world.living_npcs():
 
 
 
39
  rng = random.Random(f"{world.seed}:{next_tick}:{npc.id}")
40
  dx = rng.choice([-BLOCK_SIZE, 0, BLOCK_SIZE])
41
  dz = rng.choice([-BLOCK_SIZE, 0, BLOCK_SIZE])
 
52
  )
53
  )
54
 
55
+ return TickPlan(
56
+ source=self.name,
57
+ directives=directives,
58
+ ledger_entries=[
59
+ {
60
+ "phase": "npc_fallback",
61
+ "npc_id": directive.npc_id,
62
+ "reason": "deterministic simulator",
63
+ "action": directive.action,
64
+ }
65
+ for directive in directives
66
+ ],
67
+ )
68
 
69
 
70
  def _clamp(value: float, minimum: float, maximum: float) -> float:
src/god_simulator/simulation/connectors/openai_compatible.py CHANGED
@@ -2,15 +2,17 @@ from __future__ import annotations
2
 
3
  import json
4
  import os
 
5
  from collections.abc import Callable, Sequence
6
  from concurrent.futures import ThreadPoolExecutor
7
- from dataclasses import asdict, replace
8
  from typing import Any, cast
9
 
10
  from openai import OpenAI
11
 
12
  from god_simulator.config import ConnectorConfig
13
  from god_simulator.domain import Npc, Vec3, WorldState
 
14
  from god_simulator.simulation.actions import ActionHints, build_action_hints
15
  from god_simulator.simulation.autopilot import autopilot_directive
16
  from god_simulator.simulation.connectors.base import (
@@ -27,16 +29,16 @@ from god_simulator.simulation.mechanics import (
27
  MAX_WALK_DISTANCE,
28
  TALK_RADIUS,
29
  VISIBLE_RADIUS,
 
30
  is_alive,
 
31
  )
32
  from god_simulator.simulation.memory import recent_meaningful_memories
33
  from god_simulator.simulation.perception import CitizenPerception
34
  from god_simulator.simulation.roles import normalize_role
35
  from god_simulator.simulation.survival import (
36
- build_memory_summary,
37
- build_perception,
38
- build_relationships_summary,
39
  is_survival_world,
 
40
  suggested_actions_for_npc,
41
  survival_directive_for,
42
  )
@@ -44,6 +46,12 @@ from god_simulator.simulation.survival import select_goal as select_survival_goa
44
 
45
  ChatCompleter = Callable[[dict[str, Any]], dict[str, Any]]
46
 
 
 
 
 
 
 
47
  # One tool per primitive. Every NPC always sees all six; suggested_actions in
48
  # the payload are ranked hints, never restrictions.
49
  TOOL_DEFINITIONS: dict[str, dict[str, Any]] = {
@@ -270,6 +278,41 @@ def survival_tools_for_role(role: str) -> list[dict[str, Any]]:
270
  return [TOOL_DEFINITIONS[tool_id] for tool_id in tool_ids]
271
 
272
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
  class OpenAICompatibleWorldSimulator:
274
  name = "openai_compatible"
275
 
@@ -335,14 +378,27 @@ class OpenAICompatibleWorldSimulator:
335
  )
336
 
337
  source = self.name if fallback_fill_count == 0 else f"{self.name}+{self._fallback.name}"
338
- return TickPlan(source=source, directives=merged)
 
 
 
 
 
 
 
 
 
339
 
340
  def _call_model(self, world: WorldState, next_tick: int) -> TickPlan:
341
  assert self._config.model is not None
342
 
343
  directives: list[NpcDirective] = []
344
- living_npcs = [npc for npc in world.npcs if is_alive(npc)]
345
- directives.extend(self._call_model_for_npcs(world, next_tick, living_npcs))
 
 
 
 
346
 
347
  missing_npcs = _missing_npcs(living_npcs, directives)
348
  if missing_npcs:
@@ -350,16 +406,23 @@ class OpenAICompatibleWorldSimulator:
350
  f"Retrying {len(missing_npcs)} NPC(s) without LLM directives individually.",
351
  flush=True,
352
  )
353
- directives.extend(self._call_model_for_npcs(world, next_tick, missing_npcs))
354
-
355
- return TickPlan(source=self.name, directives=_dedupe_directives(directives))
 
 
 
 
 
 
 
356
 
357
  def _call_model_for_npcs(
358
  self,
359
  world: WorldState,
360
  next_tick: int,
361
  npcs: Sequence[Npc],
362
- ) -> list[NpcDirective]:
363
  if not npcs:
364
  return []
365
 
@@ -375,23 +438,46 @@ class OpenAICompatibleWorldSimulator:
375
  )
376
  )
377
 
378
- return [directive for npc_directives in results for directive in npc_directives]
379
 
380
  def _call_model_for_npc(
381
  self,
382
  world: WorldState,
383
  next_tick: int,
384
  npc: Npc,
385
- ) -> list[NpcDirective]:
386
  request = self._build_request(world, next_tick, npc)
 
 
 
 
 
 
387
  try:
 
388
  response = self._chat_completer(request)
 
389
  except Exception as exc:
390
  print(
391
  f"LLM connector failed for {npc.id}; deterministic fallback will fill it: {exc}",
392
  flush=True,
393
  )
394
- return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395
 
396
  try:
397
  batch_plan = _parse_model_response(response, world, source=self.name, npc_id=npc.id)
@@ -400,11 +486,31 @@ class OpenAICompatibleWorldSimulator:
400
  f"LLM connector returned unusable action for {npc.id}; using safe fallback: {exc}",
401
  flush=True,
402
  )
403
- return [
404
- _safe_fallback_directive(
405
  world, npc, next_tick, reason="model output was unusable"
406
  )
407
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
408
 
409
  directives = [
410
  directive
@@ -412,12 +518,32 @@ class OpenAICompatibleWorldSimulator:
412
  if directive.npc_id == npc.id
413
  ]
414
  if not directives:
415
- return [
416
- _safe_fallback_directive(world, npc, next_tick, reason="model omitted this NPC")
417
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  user_content = _latest_user_content(request)
419
  assistant_content = _assistant_turn_content(response)
420
- return [
421
  _with_conversation_turn(
422
  directive,
423
  user_content=user_content,
@@ -425,6 +551,19 @@ class OpenAICompatibleWorldSimulator:
425
  )
426
  for directive in directives
427
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
428
 
429
  def _build_request(
430
  self,
@@ -436,9 +575,22 @@ class OpenAICompatibleWorldSimulator:
436
 
437
  if is_survival_world(world):
438
  survival_goal = select_survival_goal(npc, world)
439
- suggested = suggested_actions_for_npc(npc, survival_goal)
440
- messages = _build_survival_messages(world, next_tick, npc, survival_goal, suggested)
441
- tools = survival_tools_for_role(npc.role)
 
 
 
 
 
 
 
 
 
 
 
 
 
442
  else:
443
  perception, goal = refresh_citizen_motivation(world, npc)
444
  hints = build_action_hints(world, npc, perception, goal)
@@ -562,13 +714,15 @@ def _build_survival_messages(
562
  npc: Npc,
563
  goal: str,
564
  suggested_actions: Sequence[str],
 
 
565
  ) -> list[dict[str, str]]:
566
  """Build a compact single-NPC survival prompt."""
567
- _ = next_tick
568
  payload = {
569
  "npc_id": npc.id,
570
- "tick": world.tick,
571
- "state": {
 
572
  "role": npc.role,
573
  "health": round(npc.health),
574
  "hunger": round(npc.hunger),
@@ -579,35 +733,23 @@ def _build_survival_messages(
579
  "reproduction_cooldown": npc.reproduction_cooldown,
580
  "importance": npc.importance,
581
  "goal": goal,
582
- },
583
- "status": {
584
- "health": round(npc.health),
585
- "hunger": round(npc.hunger),
586
- "fear": round(npc.fear),
587
- "safety": round(npc.safety),
588
- },
589
- "inventory": {
590
- "food": npc.inventory_food,
591
- "herbs": npc.inventory_herbs,
592
- "wood": npc.inventory_wood,
593
- "weapon": npc.inventory_weapon,
594
  },
595
  "goal": goal,
 
 
 
 
 
 
 
596
  "suggested_actions": list(suggested_actions),
597
- "role_rules": _role_rules_for_prompt(npc.role),
598
- "houses": [
599
- {
600
- "id": house.id,
601
- "state": house.state,
602
- "hp": round(house.hp),
603
- "position": {"x": house.position.x, "z": house.position.z},
604
- "occupants": list(house.occupant_ids),
605
- }
606
- for house in world.houses
607
- ],
608
- "perception": build_perception(npc, world),
609
- "memory": build_memory_summary(npc, last_n=3, current_tick=world.tick),
610
- "relationships": build_relationships_summary(npc, world),
611
  }
612
 
613
  return [
@@ -615,11 +757,10 @@ def _build_survival_messages(
615
  "role": "system",
616
  "content": (
617
  f"You are {npc.name}, a {npc.role}. Call exactly one tool for the next tick. "
618
- "suggested_actions are ranked hints; follow role_rules. Do not invent ids. "
619
- "Do not mutate world state; the engine validates and applies effects."
620
  ),
621
  },
622
- *npc.conversation_context.messages,
623
  {
624
  "role": "user",
625
  "content": json.dumps(payload, ensure_ascii=False),
@@ -630,17 +771,148 @@ def _build_survival_messages(
630
  def _role_rules_for_prompt(role: str) -> list[str]:
631
  if role == "guard":
632
  return [
633
- "You are a guard: attack, defend, and patrol threats near the village.",
634
- "Do not gather resources.",
 
 
635
  ]
636
  if role == "builder":
637
  return [
638
- "You are a builder: gather only wood and use build to construct houses.",
639
- "Do not attack.",
 
 
640
  ]
641
  return [
642
- "You are a gatherer: gather resources, transfer supplies, eat, heal, flee, and communicate.",
643
- "Do not choose attack unless the engine has specifically exposed it for self-defense.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
644
  ]
645
 
646
 
@@ -691,6 +963,58 @@ def _npc_context(
691
  }
692
 
693
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
694
  def _parse_model_response(
695
  response: dict[str, Any],
696
  world: WorldState,
@@ -783,7 +1107,7 @@ def _parse_text_content(
783
  if _action_kind(action) is None:
784
  raise ValueError("LLM text response did not start with a known action.")
785
 
786
- resolved_npc_id = npc_id or next((npc.id for npc in world.npcs if is_alive(npc)), None)
787
  if resolved_npc_id is None:
788
  return TickPlan(source=source, directives=[])
789
 
@@ -796,7 +1120,7 @@ def _parse_text_content(
796
 
797
 
798
  def _actions_to_plan(actions: Sequence[object], world: WorldState, *, source: str) -> TickPlan:
799
- known_npcs = {npc.id for npc in world.npcs if is_alive(npc)}
800
  half_width = world.terrain.width / 2
801
  half_depth = world.terrain.depth / 2
802
  directives: list[NpcDirective] = []
@@ -888,7 +1212,7 @@ def _action_kind(raw: object) -> ActionKind | None:
888
  def _optional_known_npc_id(raw: object, world: WorldState) -> str | None:
889
  if not isinstance(raw, str):
890
  return None
891
- if raw not in {npc.id for npc in world.npcs}:
892
  return None
893
  return raw
894
 
 
2
 
3
  import json
4
  import os
5
+ import time
6
  from collections.abc import Callable, Sequence
7
  from concurrent.futures import ThreadPoolExecutor
8
+ from dataclasses import asdict, dataclass, replace
9
  from typing import Any, cast
10
 
11
  from openai import OpenAI
12
 
13
  from god_simulator.config import ConnectorConfig
14
  from god_simulator.domain import Npc, Vec3, WorldState
15
+ from god_simulator.simulation.directives import active_directive_payload
16
  from god_simulator.simulation.actions import ActionHints, build_action_hints
17
  from god_simulator.simulation.autopilot import autopilot_directive
18
  from god_simulator.simulation.connectors.base import (
 
29
  MAX_WALK_DISTANCE,
30
  TALK_RADIUS,
31
  VISIBLE_RADIUS,
32
+ has_hostile_intent,
33
  is_alive,
34
+ vec_distance,
35
  )
36
  from god_simulator.simulation.memory import recent_meaningful_memories
37
  from god_simulator.simulation.perception import CitizenPerception
38
  from god_simulator.simulation.roles import normalize_role
39
  from god_simulator.simulation.survival import (
 
 
 
40
  is_survival_world,
41
+ allowed_actions_for_npc,
42
  suggested_actions_for_npc,
43
  survival_directive_for,
44
  )
 
46
 
47
  ChatCompleter = Callable[[dict[str, Any]], dict[str, Any]]
48
 
49
+
50
+ @dataclass(frozen=True, slots=True)
51
+ class NpcCallResult:
52
+ directives: list[NpcDirective]
53
+ ledger_entries: list[dict[str, Any]]
54
+
55
  # One tool per primitive. Every NPC always sees all six; suggested_actions in
56
  # the payload are ranked hints, never restrictions.
57
  TOOL_DEFINITIONS: dict[str, dict[str, Any]] = {
 
278
  return [TOOL_DEFINITIONS[tool_id] for tool_id in tool_ids]
279
 
280
 
281
+ SURVIVAL_VERB_TO_TOOL: dict[str, str] = {
282
+ "attack": "strike",
283
+ "build": "build",
284
+ "communicate": "speak",
285
+ "consume": "use",
286
+ "defend": "idle",
287
+ "find_food": "move",
288
+ "find_herbs": "move",
289
+ "flee": "move",
290
+ "gather": "use",
291
+ "go_home": "go_home",
292
+ "heal": "use",
293
+ "idle": "idle",
294
+ "move_to": "move",
295
+ "move_to_resource": "move",
296
+ "patrol": "patrol",
297
+ "steal": "transfer",
298
+ "transfer": "transfer",
299
+ "wander": "move",
300
+ }
301
+
302
+
303
+ def survival_tool_names_for_allowed_actions(allowed_actions: Sequence[str]) -> list[str]:
304
+ names: list[str] = []
305
+ for action in allowed_actions:
306
+ tool_name = SURVIVAL_VERB_TO_TOOL.get(action)
307
+ if tool_name is not None and tool_name not in names:
308
+ names.append(tool_name)
309
+ return names or ["idle"]
310
+
311
+
312
+ def survival_tools_for_allowed_actions(allowed_actions: Sequence[str]) -> list[dict[str, Any]]:
313
+ return [TOOL_DEFINITIONS[name] for name in survival_tool_names_for_allowed_actions(allowed_actions)]
314
+
315
+
316
  class OpenAICompatibleWorldSimulator:
317
  name = "openai_compatible"
318
 
 
378
  )
379
 
380
  source = self.name if fallback_fill_count == 0 else f"{self.name}+{self._fallback.name}"
381
+ fallback_entries = [
382
+ entry
383
+ for entry in fallback_plan.ledger_entries
384
+ if entry.get("npc_id") not in llm_npc_ids
385
+ ]
386
+ return TickPlan(
387
+ source=source,
388
+ directives=merged,
389
+ ledger_entries=[*llm_plan.ledger_entries, *fallback_entries],
390
+ )
391
 
392
  def _call_model(self, world: WorldState, next_tick: int) -> TickPlan:
393
  assert self._config.model is not None
394
 
395
  directives: list[NpcDirective] = []
396
+ ledger_entries: list[dict[str, Any]] = []
397
+ living_npcs = world.living_npcs()
398
+ initial_results = self._call_model_for_npcs(world, next_tick, living_npcs)
399
+ for result in initial_results:
400
+ directives.extend(result.directives)
401
+ ledger_entries.extend(result.ledger_entries)
402
 
403
  missing_npcs = _missing_npcs(living_npcs, directives)
404
  if missing_npcs:
 
406
  f"Retrying {len(missing_npcs)} NPC(s) without LLM directives individually.",
407
  flush=True,
408
  )
409
+ retry_results = self._call_model_for_npcs(world, next_tick, missing_npcs)
410
+ for result in retry_results:
411
+ directives.extend(result.directives)
412
+ ledger_entries.extend(result.ledger_entries)
413
+
414
+ return TickPlan(
415
+ source=self.name,
416
+ directives=_dedupe_directives(directives),
417
+ ledger_entries=ledger_entries,
418
+ )
419
 
420
  def _call_model_for_npcs(
421
  self,
422
  world: WorldState,
423
  next_tick: int,
424
  npcs: Sequence[Npc],
425
+ ) -> list[NpcCallResult]:
426
  if not npcs:
427
  return []
428
 
 
438
  )
439
  )
440
 
441
+ return list(results)
442
 
443
  def _call_model_for_npc(
444
  self,
445
  world: WorldState,
446
  next_tick: int,
447
  npc: Npc,
448
+ ) -> NpcCallResult:
449
  request = self._build_request(world, next_tick, npc)
450
+ request_entry = _npc_request_entry(
451
+ npc=npc,
452
+ request=request,
453
+ model=self._config.model or "",
454
+ allowed_actions=_request_tool_names(request),
455
+ )
456
  try:
457
+ started = time.perf_counter()
458
  response = self._chat_completer(request)
459
+ latency_ms = round((time.perf_counter() - started) * 1000)
460
  except Exception as exc:
461
  print(
462
  f"LLM connector failed for {npc.id}; deterministic fallback will fill it: {exc}",
463
  flush=True,
464
  )
465
+ return NpcCallResult(
466
+ directives=[],
467
+ ledger_entries=[
468
+ request_entry,
469
+ _npc_response_entry(
470
+ npc_id=npc.id,
471
+ raw_output=None,
472
+ parsed_action=None,
473
+ latency_ms=None,
474
+ validator_verdict={
475
+ "status": "rejected",
476
+ "reason": f"model call failed: {exc}",
477
+ },
478
+ ),
479
+ ],
480
+ )
481
 
482
  try:
483
  batch_plan = _parse_model_response(response, world, source=self.name, npc_id=npc.id)
 
486
  f"LLM connector returned unusable action for {npc.id}; using safe fallback: {exc}",
487
  flush=True,
488
  )
489
+ fallback = _safe_fallback_directive(
 
490
  world, npc, next_tick, reason="model output was unusable"
491
  )
492
+ return NpcCallResult(
493
+ directives=[fallback],
494
+ ledger_entries=[
495
+ request_entry,
496
+ _npc_response_entry(
497
+ npc_id=npc.id,
498
+ raw_output=response,
499
+ parsed_action=None,
500
+ latency_ms=latency_ms,
501
+ validator_verdict={
502
+ "status": "rejected",
503
+ "reason": f"model output was unusable: {exc}",
504
+ },
505
+ ),
506
+ {
507
+ "phase": "npc_fallback",
508
+ "npc_id": npc.id,
509
+ "reason": "model output was unusable",
510
+ "action": fallback.action,
511
+ },
512
+ ],
513
+ )
514
 
515
  directives = [
516
  directive
 
518
  if directive.npc_id == npc.id
519
  ]
520
  if not directives:
521
+ fallback = _safe_fallback_directive(world, npc, next_tick, reason="model omitted this NPC")
522
+ return NpcCallResult(
523
+ directives=[fallback],
524
+ ledger_entries=[
525
+ request_entry,
526
+ _npc_response_entry(
527
+ npc_id=npc.id,
528
+ raw_output=response,
529
+ parsed_action=None,
530
+ latency_ms=latency_ms,
531
+ validator_verdict={
532
+ "status": "rejected",
533
+ "reason": "model omitted this NPC",
534
+ },
535
+ ),
536
+ {
537
+ "phase": "npc_fallback",
538
+ "npc_id": npc.id,
539
+ "reason": "model omitted this NPC",
540
+ "action": fallback.action,
541
+ },
542
+ ],
543
+ )
544
  user_content = _latest_user_content(request)
545
  assistant_content = _assistant_turn_content(response)
546
+ resolved = [
547
  _with_conversation_turn(
548
  directive,
549
  user_content=user_content,
 
551
  )
552
  for directive in directives
553
  ]
554
+ return NpcCallResult(
555
+ directives=resolved,
556
+ ledger_entries=[
557
+ request_entry,
558
+ _npc_response_entry(
559
+ npc_id=npc.id,
560
+ raw_output=response,
561
+ parsed_action=asdict(resolved[0]) if resolved else None,
562
+ latency_ms=latency_ms,
563
+ validator_verdict={"status": "pending"},
564
+ ),
565
+ ],
566
+ )
567
 
568
  def _build_request(
569
  self,
 
575
 
576
  if is_survival_world(world):
577
  survival_goal = select_survival_goal(npc, world)
578
+ allowed_actions = allowed_actions_for_npc(world, npc, survival_goal)
579
+ allowed_tool_names = survival_tool_names_for_allowed_actions(allowed_actions)
580
+ suggested = [
581
+ action
582
+ for action in suggested_actions_for_npc(npc, survival_goal)
583
+ if action in allowed_tool_names
584
+ ] or allowed_tool_names
585
+ messages = _build_survival_messages(
586
+ world,
587
+ next_tick,
588
+ npc,
589
+ survival_goal,
590
+ suggested,
591
+ allowed_actions=allowed_tool_names,
592
+ )
593
+ tools = survival_tools_for_allowed_actions(allowed_actions)
594
  else:
595
  perception, goal = refresh_citizen_motivation(world, npc)
596
  hints = build_action_hints(world, npc, perception, goal)
 
714
  npc: Npc,
715
  goal: str,
716
  suggested_actions: Sequence[str],
717
+ *,
718
+ allowed_actions: Sequence[str],
719
  ) -> list[dict[str, str]]:
720
  """Build a compact single-NPC survival prompt."""
 
721
  payload = {
722
  "npc_id": npc.id,
723
+ "tick": next_tick,
724
+ "own_state": {
725
+ "name": npc.name,
726
  "role": npc.role,
727
  "health": round(npc.health),
728
  "hunger": round(npc.hunger),
 
733
  "reproduction_cooldown": npc.reproduction_cooldown,
734
  "importance": npc.importance,
735
  "goal": goal,
736
+ "inventory": {
737
+ "food": npc.inventory_food,
738
+ "herbs": npc.inventory_herbs,
739
+ "wood": npc.inventory_wood,
740
+ "weapon": npc.inventory_weapon,
741
+ },
 
 
 
 
 
 
742
  },
743
  "goal": goal,
744
+ "active_directive": active_directive_payload(npc, tick=next_tick),
745
+ "nearby_threats": _survival_nearby_threats(world, npc),
746
+ "nearby_allies": _survival_nearby_allies(world, npc),
747
+ "reachable_resources": _survival_reachable_resources(world, npc),
748
+ "houses_with_free_capacity": _survival_houses_with_capacity(world),
749
+ "top_memories": _top_memory_payload(npc, current_tick=next_tick),
750
+ "allowed_actions": list(allowed_actions),
751
  "suggested_actions": list(suggested_actions),
752
+ "behavior_rules": _role_rules_for_prompt(npc.role),
 
 
 
 
 
 
 
 
 
 
 
 
 
753
  }
754
 
755
  return [
 
757
  "role": "system",
758
  "content": (
759
  f"You are {npc.name}, a {npc.role}. Call exactly one tool for the next tick. "
760
+ "Use only allowed_actions and visible ids from the payload. Do not invent ids. "
761
+ "Do not write prose. The engine validates and applies effects."
762
  ),
763
  },
 
764
  {
765
  "role": "user",
766
  "content": json.dumps(payload, ensure_ascii=False),
 
771
  def _role_rules_for_prompt(role: str) -> list[str]:
772
  if role == "guard":
773
  return [
774
+ "Protect living villagers and houses from live threats.",
775
+ "Attack only visible beasts or hostile live NPCs.",
776
+ "Patrol when no threat is reachable.",
777
+ "Never gather resources.",
778
  ]
779
  if role == "builder":
780
  return [
781
+ "Build or gather wood when work is safe.",
782
+ "Go home or flee from live threats.",
783
+ "Share or ask for supplies only with live nearby allies.",
784
+ "Never attack.",
785
  ]
786
  return [
787
+ "Gather reachable food, herbs, wood, or weapons when safe.",
788
+ "Eat or heal before routine work when urgent.",
789
+ "Flee or call for help from live threats.",
790
+ "Transfer supplies only to live nearby allies.",
791
+ ]
792
+
793
+
794
+ def _survival_nearby_threats(world: WorldState, npc: Npc) -> list[dict[str, Any]]:
795
+ threats: list[dict[str, Any]] = []
796
+ for beast in world.beasts:
797
+ if beast.state == "dead":
798
+ continue
799
+ distance = vec_distance(npc.position, beast.position)
800
+ if distance <= VISIBLE_RADIUS:
801
+ threats.append(
802
+ {
803
+ "id": beast.id,
804
+ "kind": "beast",
805
+ "distance": round(distance, 2),
806
+ "hp": round(beast.health, 1),
807
+ "state": beast.state,
808
+ "can_attack": distance <= ATTACK_RADIUS,
809
+ "position": {"x": beast.position.x, "z": beast.position.z},
810
+ }
811
+ )
812
+
813
+ for other in world.living_npcs():
814
+ if other.id == npc.id or not has_hostile_intent(other):
815
+ continue
816
+ distance = vec_distance(npc.position, other.position)
817
+ if distance <= VISIBLE_RADIUS:
818
+ threats.append(
819
+ {
820
+ "id": other.id,
821
+ "kind": "npc",
822
+ "name": other.name,
823
+ "distance": round(distance, 2),
824
+ "role": other.role,
825
+ "can_attack": distance <= ATTACK_RADIUS,
826
+ "can_talk": distance <= TALK_RADIUS,
827
+ }
828
+ )
829
+ return sorted(threats, key=lambda item: (item["distance"], item["id"]))[:5]
830
+
831
+
832
+ def _survival_nearby_allies(world: WorldState, npc: Npc) -> list[dict[str, Any]]:
833
+ allies: list[dict[str, Any]] = []
834
+ for other in world.living_npcs():
835
+ if other.id == npc.id or has_hostile_intent(other):
836
+ continue
837
+ distance = vec_distance(npc.position, other.position)
838
+ if distance > VISIBLE_RADIUS:
839
+ continue
840
+ allies.append(
841
+ {
842
+ "id": other.id,
843
+ "name": other.name,
844
+ "role": other.role,
845
+ "distance": round(distance, 2),
846
+ "trust": round(npc.relationships.get(other.id, 0.0), 2),
847
+ "hp": round(other.health),
848
+ "hunger": round(other.hunger),
849
+ "inventory": {
850
+ "food": other.inventory_food,
851
+ "herbs": other.inventory_herbs,
852
+ "wood": other.inventory_wood,
853
+ "weapon": other.inventory_weapon,
854
+ },
855
+ }
856
+ )
857
+ return sorted(allies, key=lambda item: (item["distance"], item["id"]))[:5]
858
+
859
+
860
+ def _survival_reachable_resources(world: WorldState, npc: Npc) -> list[dict[str, Any]]:
861
+ resources: list[dict[str, Any]] = []
862
+ for node in world.resource_nodes:
863
+ if node.amount <= 0:
864
+ continue
865
+ distance = vec_distance(npc.position, node.position)
866
+ if distance > VISIBLE_RADIUS:
867
+ continue
868
+ resources.append(
869
+ {
870
+ "id": node.id,
871
+ "type": node.resource_type,
872
+ "amount": node.amount,
873
+ "distance": round(distance, 2),
874
+ "position": {"x": node.position.x, "z": node.position.z},
875
+ }
876
+ )
877
+ return sorted(resources, key=lambda item: (item["distance"], item["id"]))[:6]
878
+
879
+
880
+ def _survival_houses_with_capacity(world: WorldState) -> list[dict[str, Any]]:
881
+ houses: list[dict[str, Any]] = []
882
+ living_ids = {npc.id for npc in world.living_npcs()}
883
+ for house in world.houses:
884
+ occupants = [npc_id for npc_id in house.occupant_ids if npc_id in living_ids]
885
+ free = max(0, house.capacity - len(occupants))
886
+ if house.state != "completed" or house.hp <= 0 or free <= 0:
887
+ continue
888
+ houses.append(
889
+ {
890
+ "id": house.id,
891
+ "hp": round(house.hp),
892
+ "free_capacity": free,
893
+ "position": {"x": house.position.x, "z": house.position.z},
894
+ }
895
+ )
896
+ return houses[:5]
897
+
898
+
899
+ def _top_memory_payload(npc: Npc, *, current_tick: int) -> list[dict[str, Any]]:
900
+ episodes = sorted(
901
+ npc.structured_memory.episodes,
902
+ key=lambda episode: (episode.emotional_weight, episode.tick),
903
+ reverse=True,
904
+ )[:5]
905
+ return [
906
+ {
907
+ "age_ticks": max(0, current_tick - episode.tick),
908
+ "kind": episode.kind,
909
+ "actor_id": episode.actor_id,
910
+ "target_id": episode.target_id,
911
+ "summary": episode.summary,
912
+ "weight": episode.emotional_weight,
913
+ "tags": list(episode.tags),
914
+ }
915
+ for episode in sorted(episodes, key=lambda episode: episode.tick)
916
  ]
917
 
918
 
 
963
  }
964
 
965
 
966
+ def _npc_request_entry(
967
+ *,
968
+ npc: Npc,
969
+ request: dict[str, Any],
970
+ model: str,
971
+ allowed_actions: list[str],
972
+ ) -> dict[str, Any]:
973
+ return {
974
+ "phase": "npc_request",
975
+ "npc_id": npc.id,
976
+ "model": model,
977
+ "allowed_actions": allowed_actions,
978
+ "messages": request.get("messages"),
979
+ "request": request,
980
+ }
981
+
982
+
983
+ def _npc_response_entry(
984
+ *,
985
+ npc_id: str,
986
+ raw_output: dict[str, Any] | None,
987
+ parsed_action: dict[str, Any] | None,
988
+ validator_verdict: dict[str, Any],
989
+ latency_ms: int | None,
990
+ ) -> dict[str, Any]:
991
+ return {
992
+ "phase": "npc_response",
993
+ "npc_id": npc_id,
994
+ "raw_output": raw_output,
995
+ "parsed_action": parsed_action,
996
+ "validator_verdict": validator_verdict,
997
+ "latency_ms": latency_ms,
998
+ }
999
+
1000
+
1001
+ def _request_tool_names(request: dict[str, Any]) -> list[str]:
1002
+ tools = request.get("tools")
1003
+ if not isinstance(tools, list):
1004
+ return []
1005
+ names: list[str] = []
1006
+ for tool in tools:
1007
+ if not isinstance(tool, dict):
1008
+ continue
1009
+ function = tool.get("function")
1010
+ if not isinstance(function, dict):
1011
+ continue
1012
+ name = function.get("name")
1013
+ if isinstance(name, str):
1014
+ names.append(name)
1015
+ return names
1016
+
1017
+
1018
  def _parse_model_response(
1019
  response: dict[str, Any],
1020
  world: WorldState,
 
1107
  if _action_kind(action) is None:
1108
  raise ValueError("LLM text response did not start with a known action.")
1109
 
1110
+ resolved_npc_id = npc_id or next((npc.id for npc in world.living_npcs()), None)
1111
  if resolved_npc_id is None:
1112
  return TickPlan(source=source, directives=[])
1113
 
 
1120
 
1121
 
1122
  def _actions_to_plan(actions: Sequence[object], world: WorldState, *, source: str) -> TickPlan:
1123
+ known_npcs = {npc.id for npc in world.living_npcs()}
1124
  half_width = world.terrain.width / 2
1125
  half_depth = world.terrain.depth / 2
1126
  directives: list[NpcDirective] = []
 
1212
  def _optional_known_npc_id(raw: object, world: WorldState) -> str | None:
1213
  if not isinstance(raw, str):
1214
  return None
1215
+ if raw not in {npc.id for npc in world.living_npcs()}:
1216
  return None
1217
  return raw
1218
 
src/god_simulator/simulation/directives.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, cast
4
+
5
+ from god_simulator.domain import Npc, WorldLogEvent, WorldState
6
+ from god_simulator.observability import append_record
7
+ from god_simulator.simulation.mechanics import is_alive
8
+
9
+ DEFAULT_DIRECTIVE_TTL_TICKS = 24
10
+
11
+
12
+ def set_active_directive(
13
+ npc: Npc,
14
+ directive: str,
15
+ *,
16
+ source: str,
17
+ tick: int,
18
+ ttl_ticks: int = DEFAULT_DIRECTIVE_TTL_TICKS,
19
+ ) -> None:
20
+ npc.god_directive = directive
21
+ npc.directive_source = source
22
+ npc.directive_issued_tick = tick
23
+ npc.directive_ttl_ticks = ttl_ticks
24
+
25
+
26
+ def clear_active_directive(npc: Npc) -> None:
27
+ npc.god_directive = None
28
+ npc.directive_source = None
29
+ npc.directive_issued_tick = None
30
+ npc.directive_ttl_ticks = None
31
+
32
+
33
+ def directive_remaining_ttl(npc: Npc, *, tick: int) -> int | None:
34
+ if npc.god_directive is None:
35
+ return None
36
+ if npc.directive_issued_tick is None or npc.directive_ttl_ticks is None:
37
+ return DEFAULT_DIRECTIVE_TTL_TICKS
38
+ return max(0, npc.directive_issued_tick + npc.directive_ttl_ticks - tick)
39
+
40
+
41
+ def active_directive_payload(npc: Npc, *, tick: int) -> dict[str, Any] | None:
42
+ if npc.god_directive is None:
43
+ return None
44
+ return {
45
+ "text": npc.god_directive,
46
+ "source": npc.directive_source or "unknown",
47
+ "issued_tick": npc.directive_issued_tick,
48
+ "ttl_ticks": npc.directive_ttl_ticks or DEFAULT_DIRECTIVE_TTL_TICKS,
49
+ "remaining_ttl": directive_remaining_ttl(npc, tick=tick),
50
+ }
51
+
52
+
53
+ def expire_directives(world: WorldState, *, tick: int) -> list[dict[str, Any]]:
54
+ expired: list[dict[str, Any]] = []
55
+ for npc in world.living_npcs():
56
+ remaining = directive_remaining_ttl(npc, tick=tick)
57
+ if remaining is None or remaining > 0:
58
+ continue
59
+ record = {
60
+ "npc_id": npc.id,
61
+ "directive": npc.god_directive,
62
+ "source": npc.directive_source,
63
+ "issued_tick": npc.directive_issued_tick,
64
+ "ttl_ticks": npc.directive_ttl_ticks,
65
+ }
66
+ clear_active_directive(npc)
67
+ world.event_log.append(
68
+ WorldLogEvent(
69
+ tick=tick,
70
+ type="directive_expired",
71
+ actor_id="engine",
72
+ target_id=npc.id,
73
+ object_id=None,
74
+ summary=f"Directive expired for {npc.name}",
75
+ severity=cast(Any, "neutral"),
76
+ )
77
+ )
78
+ append_record({"tick": tick, "phase": "directive_expired", **record})
79
+ expired.append(record)
80
+
81
+ for npc in world.npcs:
82
+ if not is_alive(npc):
83
+ clear_active_directive(npc)
84
+ return expired
src/god_simulator/simulation/goals.py CHANGED
@@ -162,7 +162,7 @@ def _mode_for_goal(goal: CitizenGoal | None) -> CitizenMode:
162
 
163
 
164
  def _explicit_directive_target(world: WorldState, npc: Npc, directive: str) -> Npc | None:
165
- for candidate in world.npcs:
166
  if candidate.id == npc.id or not is_alive(candidate):
167
  continue
168
  if candidate.id.lower() in directive or candidate.name.lower() in directive:
@@ -189,7 +189,7 @@ def _directive_allows_any_target(directive: str) -> bool:
189
  def _nearest_living_target(world: WorldState, npc: Npc) -> Npc | None:
190
  candidates = [
191
  (distance_between(npc, candidate), candidate.id, candidate)
192
- for candidate in world.npcs
193
  if candidate.id != npc.id and is_alive(candidate)
194
  ]
195
  if not candidates:
@@ -219,7 +219,7 @@ def _attacker_from_observed_attack(
219
  continue
220
  if "attacked" not in lowered:
221
  continue
222
- for candidate in world.npcs:
223
  if candidate.id == npc.id:
224
  continue
225
  if candidate.name.lower() in lowered or candidate.id.lower() in lowered:
@@ -228,7 +228,7 @@ def _attacker_from_observed_attack(
228
 
229
 
230
  def _npc_by_id(world: WorldState, npc_id: str) -> Npc | None:
231
- return next((npc for npc in world.npcs if npc.id == npc_id), None)
232
 
233
 
234
  def _wants_to_call_for_help(npc: Npc) -> bool:
 
162
 
163
 
164
  def _explicit_directive_target(world: WorldState, npc: Npc, directive: str) -> Npc | None:
165
+ for candidate in world.living_npcs():
166
  if candidate.id == npc.id or not is_alive(candidate):
167
  continue
168
  if candidate.id.lower() in directive or candidate.name.lower() in directive:
 
189
  def _nearest_living_target(world: WorldState, npc: Npc) -> Npc | None:
190
  candidates = [
191
  (distance_between(npc, candidate), candidate.id, candidate)
192
+ for candidate in world.living_npcs()
193
  if candidate.id != npc.id and is_alive(candidate)
194
  ]
195
  if not candidates:
 
219
  continue
220
  if "attacked" not in lowered:
221
  continue
222
+ for candidate in world.living_npcs():
223
  if candidate.id == npc.id:
224
  continue
225
  if candidate.name.lower() in lowered or candidate.id.lower() in lowered:
 
228
 
229
 
230
  def _npc_by_id(world: WorldState, npc_id: str) -> Npc | None:
231
+ return next((npc for npc in world.living_npcs() if npc.id == npc_id), None)
232
 
233
 
234
  def _wants_to_call_for_help(npc: Npc) -> bool:
src/god_simulator/simulation/god_console.py CHANGED
@@ -2,6 +2,7 @@ from __future__ import annotations
2
 
3
  import json
4
  import os
 
5
  from collections.abc import Callable
6
  from dataclasses import dataclass
7
  from typing import Any, cast
@@ -10,6 +11,7 @@ from openai import OpenAI
10
 
11
  from god_simulator.config import ConnectorConfig
12
  from god_simulator.domain import Vec3, WorldEvent, WorldState
 
13
  from god_simulator.simulation.memory import recent_meaningful_memories, remember
14
 
15
  GodChatCompleter = Callable[[dict[str, Any]], dict[str, Any]]
@@ -180,6 +182,9 @@ class GodCommandPlan:
180
  source: str
181
  summary: str
182
  edits: list[GodEdit]
 
 
 
183
 
184
 
185
  class GodConsole:
@@ -220,8 +225,18 @@ class GodConsole:
220
  if self._config.extra_body:
221
  request["extra_body"] = self._config.extra_body
222
 
 
223
  response = self._chat_completer(request)
224
- return _parse_response(response)
 
 
 
 
 
 
 
 
 
225
 
226
  def _complete_with_openai(self, request: dict[str, Any]) -> dict[str, Any]:
227
  completion = self._client.chat.completions.create(**request)
@@ -280,7 +295,9 @@ def apply_god_command_plan(world: WorldState, plan: GodCommandPlan) -> list[str]
280
  if npc.health > 0 and npc.intention == "dead":
281
  npc.intention = "idle"
282
  if npc.health <= 0:
283
- npc.intention = "dead"
 
 
284
  applied.append(f"{npc.name} health set to {npc.health}.")
285
  case "set_npc_attack_damage":
286
  attack_damage = _int_arg(edit.arguments.get("attack_damage"))
@@ -298,7 +315,12 @@ def apply_god_command_plan(world: WorldState, plan: GodCommandPlan) -> list[str]
298
  directive = _short_text(edit.arguments.get("directive"), limit=240)
299
  if directive is None:
300
  continue
301
- npc.god_directive = directive
 
 
 
 
 
302
  remember(npc, world.tick, f"God directive: {directive}")
303
  applied.append(f"{npc.name} directive set.")
304
  case "add_npc_memory":
@@ -378,7 +400,7 @@ def _build_messages(world: WorldState, command: str) -> list[dict[str, str]]:
378
  for memory in recent_meaningful_memories(npc, limit=3)
379
  ],
380
  }
381
- for npc in world.npcs
382
  ],
383
  },
384
  ensure_ascii=False,
 
2
 
3
  import json
4
  import os
5
+ import time
6
  from collections.abc import Callable
7
  from dataclasses import dataclass
8
  from typing import Any, cast
 
11
 
12
  from god_simulator.config import ConnectorConfig
13
  from god_simulator.domain import Vec3, WorldEvent, WorldState
14
+ from god_simulator.simulation.directives import set_active_directive
15
  from god_simulator.simulation.memory import recent_meaningful_memories, remember
16
 
17
  GodChatCompleter = Callable[[dict[str, Any]], dict[str, Any]]
 
182
  source: str
183
  summary: str
184
  edits: list[GodEdit]
185
+ request: dict[str, Any] | None = None
186
+ raw_response: dict[str, Any] | None = None
187
+ latency_ms: int | None = None
188
 
189
 
190
  class GodConsole:
 
225
  if self._config.extra_body:
226
  request["extra_body"] = self._config.extra_body
227
 
228
+ started = time.perf_counter()
229
  response = self._chat_completer(request)
230
+ latency_ms = round((time.perf_counter() - started) * 1000)
231
+ parsed = _parse_response(response)
232
+ return GodCommandPlan(
233
+ source=parsed.source,
234
+ summary=parsed.summary,
235
+ edits=parsed.edits,
236
+ request=request,
237
+ raw_response=response,
238
+ latency_ms=latency_ms,
239
+ )
240
 
241
  def _complete_with_openai(self, request: dict[str, Any]) -> dict[str, Any]:
242
  completion = self._client.chat.completions.create(**request)
 
295
  if npc.health > 0 and npc.intention == "dead":
296
  npc.intention = "idle"
297
  if npc.health <= 0:
298
+ from god_simulator.simulation.survival import _kill_npc
299
+
300
+ _kill_npc(world, npc, cause="god", actor_id="god")
301
  applied.append(f"{npc.name} health set to {npc.health}.")
302
  case "set_npc_attack_damage":
303
  attack_damage = _int_arg(edit.arguments.get("attack_damage"))
 
315
  directive = _short_text(edit.arguments.get("directive"), limit=240)
316
  if directive is None:
317
  continue
318
+ set_active_directive(
319
+ npc,
320
+ directive,
321
+ source="god_console",
322
+ tick=world.tick,
323
+ )
324
  remember(npc, world.tick, f"God directive: {directive}")
325
  applied.append(f"{npc.name} directive set.")
326
  case "add_npc_memory":
 
400
  for memory in recent_meaningful_memories(npc, limit=3)
401
  ],
402
  }
403
+ for npc in world.living_npcs()
404
  ],
405
  },
406
  ensure_ascii=False,
src/god_simulator/simulation/overseer.py CHANGED
@@ -3,12 +3,15 @@ from __future__ import annotations
3
  from dataclasses import dataclass
4
  import json
5
  import os
 
6
  from pathlib import Path
7
  from typing import Any, Protocol, cast
8
 
9
  from god_simulator.config import ConnectorConfig, GameConfig, OverseerConfig
10
  from god_simulator.domain import Npc, WorldLogEvent, WorldState
 
11
  from god_simulator.simulation.connectors.base import NpcDirective, TickPlan
 
12
  from god_simulator.simulation.mechanics import is_alive, vec_distance
13
  from god_simulator.simulation.roles import normalize_role
14
  from god_simulator.simulation.survival import (
@@ -33,6 +36,9 @@ class OverseerDecision:
33
  thoughts: str
34
  directives: list[OverseerDirective]
35
  priority_alert: str
 
 
 
36
 
37
 
38
  class OverseerClient(Protocol):
@@ -79,18 +85,45 @@ class OpenAICompatibleOverseerClient:
79
  }
80
  if self._config.extra_body:
81
  request["extra_body"] = self._config.extra_body
 
 
 
 
 
 
 
 
 
 
82
  completion = client.chat.completions.create(**request)
 
83
  response = completion.model_dump()
84
  content = response["choices"][0]["message"].get("content")
85
  if not isinstance(content, str):
86
  raise RuntimeError("Overseer response did not contain text content.")
87
- return parse_overseer_decision(content)
 
 
 
 
 
 
 
 
88
 
89
 
90
  class ScriptedOverseerClient:
91
  """Deterministic fake used by headless tests."""
92
 
93
  def decide(self, context: dict[str, Any]) -> OverseerDecision:
 
 
 
 
 
 
 
 
94
  npcs = context.get("npcs", [])
95
  guard = _first_role(npcs, "guard")
96
  builder = _first_role(npcs, "builder")
@@ -109,10 +142,21 @@ class ScriptedOverseerClient:
109
  )
110
  if gatherer is not None:
111
  directives.append(OverseerDirective(npc_id=gatherer["id"], directive="go home"))
 
 
 
 
 
 
 
 
112
  return OverseerDecision(
113
  thoughts="Mock Overseer: test guard attack, invalid builder command, and shelter order.",
114
  directives=directives,
115
  priority_alert="Mock directive validation check",
 
 
 
116
  )
117
 
118
 
@@ -130,9 +174,24 @@ class OverseerController:
130
  return plan
131
 
132
  context = build_overseer_context(world, next_tick)
 
133
  try:
134
  decision = self.client.decide(context)
135
  except Exception as exc:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  metadata = {
137
  "mode": self.mode,
138
  "tick": next_tick,
@@ -146,14 +205,33 @@ class OverseerController:
146
  source=f"{plan.source}+overseer_skipped",
147
  directives=plan.directives,
148
  overseer=metadata,
 
149
  )
150
 
151
  raw_directives = decision.directives[: self.max_directives]
152
  issued: list[dict[str, Any]] = []
153
  converted: list[NpcDirective] = []
 
 
154
  if self.mode == "autopilot":
155
  for raw in raw_directives:
156
  directive = _directive_to_engine(world, raw)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  issued.append(
158
  {
159
  "npc_id": raw.npc_id,
@@ -165,7 +243,27 @@ class OverseerController:
165
  if directive is not None:
166
  converted.append(directive)
167
  else:
168
- issued = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
  metadata = {
171
  "mode": self.mode,
@@ -178,7 +276,12 @@ class OverseerController:
178
  "directives": issued,
179
  }
180
  if self.mode != "autopilot":
181
- return TickPlan(source=plan.source, directives=plan.directives, overseer=metadata)
 
 
 
 
 
182
 
183
  merged = {directive.npc_id: directive for directive in plan.directives}
184
  for directive in converted:
@@ -187,6 +290,7 @@ class OverseerController:
187
  source=f"{plan.source}+overseer",
188
  directives=list(merged.values()),
189
  overseer=metadata,
 
190
  )
191
 
192
 
@@ -222,7 +326,8 @@ def scripted_overseer_controller(
222
 
223
 
224
  def build_overseer_context(world: WorldState, next_tick: int) -> dict[str, Any]:
225
- alive = [npc for npc in world.npcs if is_alive(npc)]
 
226
  role_counts: dict[str, int] = {"gatherer": 0, "guard": 0, "builder": 0}
227
  for npc in alive:
228
  role_counts[normalize_role(npc.role)] += 1
@@ -257,6 +362,10 @@ def build_overseer_context(world: WorldState, next_tick: int) -> dict[str, Any]:
257
  "safety": round(npc.safety, 1),
258
  "importance": npc.importance,
259
  "goal": npc.survival_goal,
 
 
 
 
260
  "inventory": {
261
  "food": npc.inventory_food,
262
  "herbs": npc.inventory_herbs,
@@ -274,7 +383,7 @@ def build_overseer_context(world: WorldState, next_tick: int) -> dict[str, Any]:
274
  "state": house.state,
275
  "hp": round(house.hp, 1),
276
  "capacity": house.capacity,
277
- "occupants": list(house.occupant_ids),
278
  "position": {"x": house.position.x, "z": house.position.z},
279
  }
280
  for house in world.houses
@@ -328,6 +437,8 @@ def parse_overseer_decision(content: str) -> OverseerDecision:
328
  thoughts=thoughts or "",
329
  directives=directives,
330
  priority_alert=priority_alert or "",
 
 
331
  )
332
 
333
 
@@ -360,7 +471,7 @@ def apply_overseer_metadata(world: WorldState, metadata: dict[str, Any] | None)
360
  severity="neutral",
361
  )
362
 
363
- npcs_by_id = {npc.id: npc for npc in world.npcs}
364
  for directive in world.overseer_last_directives:
365
  if not isinstance(directive, dict):
366
  continue
@@ -371,7 +482,12 @@ def apply_overseer_metadata(world: WorldState, metadata: dict[str, Any] | None)
371
  continue
372
  npc = npcs_by_id.get(npc_id)
373
  if npc is not None and applied:
374
- npc.god_directive = text
 
 
 
 
 
375
  _append_log(
376
  world,
377
  "directive_issued",
@@ -391,7 +507,7 @@ def _client_from_config(config: OverseerConfig) -> OverseerClient | None:
391
 
392
 
393
  def _directive_to_engine(world: WorldState, raw: OverseerDirective) -> NpcDirective | None:
394
- npc = next((candidate for candidate in world.npcs if candidate.id == raw.npc_id), None)
395
  if npc is None or not is_alive(npc):
396
  return None
397
  text = raw.directive.lower()
@@ -454,7 +570,7 @@ def _current_threats(world: WorldState) -> list[dict[str, Any]]:
454
  if beast.state == "dead":
455
  continue
456
  nearest_npc = min(
457
- (npc for npc in world.npcs if is_alive(npc)),
458
  key=lambda npc: (vec_distance(beast.position, npc.position), npc.id),
459
  default=None,
460
  )
 
3
  from dataclasses import dataclass
4
  import json
5
  import os
6
+ import time
7
  from pathlib import Path
8
  from typing import Any, Protocol, cast
9
 
10
  from god_simulator.config import ConnectorConfig, GameConfig, OverseerConfig
11
  from god_simulator.domain import Npc, WorldLogEvent, WorldState
12
+ from god_simulator.observability import append_record
13
  from god_simulator.simulation.connectors.base import NpcDirective, TickPlan
14
+ from god_simulator.simulation.directives import set_active_directive
15
  from god_simulator.simulation.mechanics import is_alive, vec_distance
16
  from god_simulator.simulation.roles import normalize_role
17
  from god_simulator.simulation.survival import (
 
36
  thoughts: str
37
  directives: list[OverseerDirective]
38
  priority_alert: str
39
+ raw_output: str | None = None
40
+ parsed_json: dict[str, Any] | None = None
41
+ latency_ms: int | None = None
42
 
43
 
44
  class OverseerClient(Protocol):
 
85
  }
86
  if self._config.extra_body:
87
  request["extra_body"] = self._config.extra_body
88
+ append_record(
89
+ {
90
+ "phase": "overseer_request",
91
+ "model": self._config.model,
92
+ "mode": context.get("mode"),
93
+ "messages": request["messages"],
94
+ "request": request,
95
+ }
96
+ )
97
+ started = time.perf_counter()
98
  completion = client.chat.completions.create(**request)
99
+ latency_ms = round((time.perf_counter() - started) * 1000)
100
  response = completion.model_dump()
101
  content = response["choices"][0]["message"].get("content")
102
  if not isinstance(content, str):
103
  raise RuntimeError("Overseer response did not contain text content.")
104
+ decision = parse_overseer_decision(content)
105
+ return OverseerDecision(
106
+ thoughts=decision.thoughts,
107
+ directives=decision.directives,
108
+ priority_alert=decision.priority_alert,
109
+ raw_output=content,
110
+ parsed_json=decision.parsed_json,
111
+ latency_ms=latency_ms,
112
+ )
113
 
114
 
115
  class ScriptedOverseerClient:
116
  """Deterministic fake used by headless tests."""
117
 
118
  def decide(self, context: dict[str, Any]) -> OverseerDecision:
119
+ append_record(
120
+ {
121
+ "phase": "overseer_request",
122
+ "model": "scripted",
123
+ "mode": context.get("mode"),
124
+ "prompt": json.dumps(context, ensure_ascii=False),
125
+ }
126
+ )
127
  npcs = context.get("npcs", [])
128
  guard = _first_role(npcs, "guard")
129
  builder = _first_role(npcs, "builder")
 
142
  )
143
  if gatherer is not None:
144
  directives.append(OverseerDirective(npc_id=gatherer["id"], directive="go home"))
145
+ parsed = {
146
+ "thoughts": "Mock Overseer: test guard attack, invalid builder command, and shelter order.",
147
+ "directives": [
148
+ {"npc_id": directive.npc_id, "directive": directive.directive}
149
+ for directive in directives
150
+ ],
151
+ "priority_alert": "Mock directive validation check",
152
+ }
153
  return OverseerDecision(
154
  thoughts="Mock Overseer: test guard attack, invalid builder command, and shelter order.",
155
  directives=directives,
156
  priority_alert="Mock directive validation check",
157
+ raw_output=json.dumps(parsed, ensure_ascii=False),
158
+ parsed_json=parsed,
159
+ latency_ms=0,
160
  )
161
 
162
 
 
174
  return plan
175
 
176
  context = build_overseer_context(world, next_tick)
177
+ context["mode"] = self.mode
178
  try:
179
  decision = self.client.decide(context)
180
  except Exception as exc:
181
+ append_record(
182
+ {
183
+ "phase": "overseer_response",
184
+ "raw_output": None,
185
+ "parsed_json": None,
186
+ "accepted_directives": [],
187
+ "rejected_directives": [
188
+ {
189
+ "reason": str(exc),
190
+ }
191
+ ],
192
+ "latency_ms": None,
193
+ }
194
+ )
195
  metadata = {
196
  "mode": self.mode,
197
  "tick": next_tick,
 
205
  source=f"{plan.source}+overseer_skipped",
206
  directives=plan.directives,
207
  overseer=metadata,
208
+ ledger_entries=plan.ledger_entries,
209
  )
210
 
211
  raw_directives = decision.directives[: self.max_directives]
212
  issued: list[dict[str, Any]] = []
213
  converted: list[NpcDirective] = []
214
+ accepted: list[dict[str, Any]] = []
215
+ rejected: list[dict[str, Any]] = []
216
  if self.mode == "autopilot":
217
  for raw in raw_directives:
218
  directive = _directive_to_engine(world, raw)
219
+ if directive is None:
220
+ rejected.append(
221
+ {
222
+ "npc_id": raw.npc_id,
223
+ "directive": raw.directive,
224
+ "reason": "invalid or dead npc_id",
225
+ }
226
+ )
227
+ else:
228
+ accepted.append(
229
+ {
230
+ "npc_id": raw.npc_id,
231
+ "directive": raw.directive,
232
+ "action": directive.action,
233
+ }
234
+ )
235
  issued.append(
236
  {
237
  "npc_id": raw.npc_id,
 
243
  if directive is not None:
244
  converted.append(directive)
245
  else:
246
+ issued = [
247
+ {
248
+ "npc_id": raw.npc_id,
249
+ "directive": raw.directive,
250
+ "applied": False,
251
+ "action": None,
252
+ }
253
+ for raw in raw_directives
254
+ ]
255
+ accepted = issued
256
+
257
+ append_record(
258
+ {
259
+ "phase": "overseer_response",
260
+ "raw_output": decision.raw_output,
261
+ "parsed_json": decision.parsed_json,
262
+ "accepted_directives": accepted,
263
+ "rejected_directives": rejected,
264
+ "latency_ms": decision.latency_ms,
265
+ }
266
+ )
267
 
268
  metadata = {
269
  "mode": self.mode,
 
276
  "directives": issued,
277
  }
278
  if self.mode != "autopilot":
279
+ return TickPlan(
280
+ source=plan.source,
281
+ directives=plan.directives,
282
+ overseer=metadata,
283
+ ledger_entries=plan.ledger_entries,
284
+ )
285
 
286
  merged = {directive.npc_id: directive for directive in plan.directives}
287
  for directive in converted:
 
290
  source=f"{plan.source}+overseer",
291
  directives=list(merged.values()),
292
  overseer=metadata,
293
+ ledger_entries=plan.ledger_entries,
294
  )
295
 
296
 
 
326
 
327
 
328
  def build_overseer_context(world: WorldState, next_tick: int) -> dict[str, Any]:
329
+ alive = world.living_npcs()
330
+ living_ids = {npc.id for npc in alive}
331
  role_counts: dict[str, int] = {"gatherer": 0, "guard": 0, "builder": 0}
332
  for npc in alive:
333
  role_counts[normalize_role(npc.role)] += 1
 
362
  "safety": round(npc.safety, 1),
363
  "importance": npc.importance,
364
  "goal": npc.survival_goal,
365
+ "active_directive": npc.god_directive,
366
+ "directive_remaining_ttl": None
367
+ if npc.directive_issued_tick is None or npc.directive_ttl_ticks is None
368
+ else max(0, npc.directive_issued_tick + npc.directive_ttl_ticks - next_tick),
369
  "inventory": {
370
  "food": npc.inventory_food,
371
  "herbs": npc.inventory_herbs,
 
383
  "state": house.state,
384
  "hp": round(house.hp, 1),
385
  "capacity": house.capacity,
386
+ "occupants": [npc_id for npc_id in house.occupant_ids if npc_id in living_ids],
387
  "position": {"x": house.position.x, "z": house.position.z},
388
  }
389
  for house in world.houses
 
437
  thoughts=thoughts or "",
438
  directives=directives,
439
  priority_alert=priority_alert or "",
440
+ raw_output=content,
441
+ parsed_json=raw,
442
  )
443
 
444
 
 
471
  severity="neutral",
472
  )
473
 
474
+ npcs_by_id = {npc.id: npc for npc in world.living_npcs()}
475
  for directive in world.overseer_last_directives:
476
  if not isinstance(directive, dict):
477
  continue
 
482
  continue
483
  npc = npcs_by_id.get(npc_id)
484
  if npc is not None and applied:
485
+ set_active_directive(
486
+ npc,
487
+ text,
488
+ source="overseer",
489
+ tick=world.tick,
490
+ )
491
  _append_log(
492
  world,
493
  "directive_issued",
 
507
 
508
 
509
  def _directive_to_engine(world: WorldState, raw: OverseerDirective) -> NpcDirective | None:
510
+ npc = next((candidate for candidate in world.living_npcs() if candidate.id == raw.npc_id), None)
511
  if npc is None or not is_alive(npc):
512
  return None
513
  text = raw.directive.lower()
 
570
  if beast.state == "dead":
571
  continue
572
  nearest_npc = min(
573
+ world.living_npcs(),
574
  key=lambda npc: (vec_distance(beast.position, npc.position), npc.id),
575
  default=None,
576
  )
src/god_simulator/simulation/perception.py CHANGED
@@ -39,7 +39,7 @@ def build_perception(world: WorldState, npc: Npc) -> CitizenPerception:
39
  nearby_threats: list[dict[str, Any]] = []
40
  visible_targets: list[dict[str, Any]] = []
41
 
42
- for other in world.npcs:
43
  if other.id == npc.id:
44
  continue
45
 
@@ -50,8 +50,8 @@ def build_perception(world: WorldState, npc: Npc) -> CitizenPerception:
50
  active_threat = has_hostile_intent(other)
51
  memory_threat = other.id in memory_threat_ids
52
  threat = active_threat or memory_threat
53
- can_talk = is_alive(other) and distance <= TALK_RADIUS
54
- can_attack = is_alive(other) and distance <= ATTACK_RADIUS
55
  can_attack_you = threat and distance <= ATTACK_RADIUS
56
  citizen = {
57
  "id": other.id,
@@ -69,16 +69,15 @@ def build_perception(world: WorldState, npc: Npc) -> CitizenPerception:
69
  }
70
  nearby_citizens.append(citizen)
71
 
72
- if is_alive(other):
73
- visible_targets.append(
74
- {
75
- "id": other.id,
76
- "npc_id": other.id,
77
- "name": other.name,
78
- "distance": round(distance, 3),
79
- "can_talk": can_talk,
80
- "can_attack": can_attack,
81
- }
82
  )
83
 
84
  if threat:
@@ -139,7 +138,7 @@ def nearby_threat_npc(world: WorldState, perception: CitizenPerception) -> Npc |
139
  if not perception.nearby_threats:
140
  return None
141
  threat_id = perception.nearby_threats[0]["npc_id"]
142
- return next((npc for npc in world.npcs if npc.id == threat_id), None)
143
 
144
 
145
  def _memory_threat_ids(world: WorldState, npc: Npc) -> set[str]:
@@ -164,7 +163,7 @@ def _memory_threat_ids(world: WorldState, npc: Npc) -> set[str]:
164
 
165
  def _mentioned_npc(world: WorldState, text: str) -> Npc | None:
166
  lowered = text.lower()
167
- for npc in world.npcs:
168
  name = npc.name.lower()
169
  npc_id = npc.id.lower()
170
  if f"{name} attacked" in lowered or f"{npc_id} attacked" in lowered:
@@ -174,7 +173,7 @@ def _mentioned_npc(world: WorldState, text: str) -> Npc | None:
174
 
175
  matches = [
176
  (lowered.find(npc.name.lower()), npc)
177
- for npc in world.npcs
178
  if npc.name.lower() in lowered or npc.id.lower() in lowered
179
  ]
180
  if not matches:
 
39
  nearby_threats: list[dict[str, Any]] = []
40
  visible_targets: list[dict[str, Any]] = []
41
 
42
+ for other in world.living_npcs():
43
  if other.id == npc.id:
44
  continue
45
 
 
50
  active_threat = has_hostile_intent(other)
51
  memory_threat = other.id in memory_threat_ids
52
  threat = active_threat or memory_threat
53
+ can_talk = distance <= TALK_RADIUS
54
+ can_attack = distance <= ATTACK_RADIUS
55
  can_attack_you = threat and distance <= ATTACK_RADIUS
56
  citizen = {
57
  "id": other.id,
 
69
  }
70
  nearby_citizens.append(citizen)
71
 
72
+ visible_targets.append(
73
+ {
74
+ "id": other.id,
75
+ "npc_id": other.id,
76
+ "name": other.name,
77
+ "distance": round(distance, 3),
78
+ "can_talk": can_talk,
79
+ "can_attack": can_attack,
80
+ }
 
81
  )
82
 
83
  if threat:
 
138
  if not perception.nearby_threats:
139
  return None
140
  threat_id = perception.nearby_threats[0]["npc_id"]
141
+ return next((npc for npc in world.living_npcs() if npc.id == threat_id), None)
142
 
143
 
144
  def _memory_threat_ids(world: WorldState, npc: Npc) -> set[str]:
 
163
 
164
  def _mentioned_npc(world: WorldState, text: str) -> Npc | None:
165
  lowered = text.lower()
166
+ for npc in world.living_npcs():
167
  name = npc.name.lower()
168
  npc_id = npc.id.lower()
169
  if f"{name} attacked" in lowered or f"{npc_id} attacked" in lowered:
 
173
 
174
  matches = [
175
  (lowered.find(npc.name.lower()), npc)
176
+ for npc in world.living_npcs()
177
  if npc.name.lower() in lowered or npc.id.lower() in lowered
178
  ]
179
  if not matches:
src/god_simulator/simulation/survival.py CHANGED
@@ -27,6 +27,7 @@ from god_simulator.domain import (
27
  WorldState,
28
  )
29
  from god_simulator.simulation.connectors.base import NpcDirective, TickPlan
 
30
  from god_simulator.simulation.mechanics import (
31
  ATTACK_RADIUS,
32
  BLOCK_SIZE,
@@ -64,7 +65,7 @@ BEAST_THREAT_RADIUS = 8 * TILE
64
  VILLAGE_THREAT_RADIUS = 10 * TILE
65
  HOUSE_THREAT_RADIUS = 12 * TILE
66
  ALLY_RADIUS = 5 * TILE
67
- WITNESS_RADIUS = 5 * TILE
68
  FEAR_DECAY_RADIUS = 12 * TILE
69
  GATHER_RADIUS = 1.5 * TILE
70
  TRADE_RADIUS = 2 * TILE
@@ -79,6 +80,7 @@ HOUSE_MIN_DISTANCE = 4 * TILE
79
  # Fear dynamics.
80
  FEAR_ON_ATTACK = 60.0
81
  FEAR_ON_WITNESS = 20.0
 
82
  FEAR_DECAY = 2.0
83
  SAFETY_GAIN = 12.0
84
  SAFETY_DECAY = 8.0
@@ -122,6 +124,7 @@ GOAL_ACTIONS: dict[str, list[str]] = {
122
  "eat_food": ["consume"],
123
  "find_food": ["move_to_resource", "gather", "communicate", "steal"],
124
  "find_herbs": ["move_to_resource", "gather", "communicate"],
 
125
  "settle": ["go_home", "consume", "communicate", "transfer"],
126
  "work": ["gather", "move_to_resource", "transfer", "communicate", "build", "patrol"],
127
  "routine_life": ["gather", "move_to_resource", "transfer", "communicate", "go_home", "build", "patrol"],
@@ -140,6 +143,7 @@ GOAL_SUGGESTED_ACTIONS: dict[str, list[str]] = {
140
  "eat_food": ["use"],
141
  "find_food": ["move", "use", "speak", "transfer"],
142
  "find_herbs": ["move", "use", "speak"],
 
143
  "settle": ["go_home", "use", "speak", "transfer"],
144
  "work": ["use", "move", "build", "patrol", "transfer", "speak"],
145
  "routine_life": ["use", "move", "transfer", "speak", "go_home", "build", "patrol"],
@@ -326,10 +330,10 @@ def build_memory_summary(npc: Npc, *, last_n: int = 3, current_tick: int | None
326
 
327
 
328
  def build_relationships_summary(npc: Npc, world: WorldState | None = None) -> str:
329
- names = {other.id: other.name for other in world.npcs} if world is not None else {}
330
  ids = set(npc.relationships)
331
  if world is not None:
332
- ids.update(other.id for other in world.npcs if other.id != npc.id)
333
  ids.update(beast.id for beast in world.beasts)
334
 
335
  lines: list[str] = []
@@ -431,8 +435,8 @@ def find_nearest_alive_npc(
431
  ) -> Npc | None:
432
  candidates = [
433
  npc
434
- for npc in world.npcs
435
- if is_alive(npc) and npc.id != exclude_id
436
  ]
437
  if not candidates:
438
  return None
@@ -448,9 +452,8 @@ def nearest_alive_npc(
448
  ) -> Npc | None:
449
  candidates = [
450
  other
451
- for other in world.npcs
452
  if other.id != npc.id
453
- and is_alive(other)
454
  and vec_distance(npc.position, other.position) <= max_dist
455
  and (not require_food or other.inventory_food > 0)
456
  ]
@@ -468,9 +471,8 @@ def _nearest_role(
468
  ) -> Npc | None:
469
  candidates = [
470
  other
471
- for other in world.npcs
472
  if other.id != npc.id
473
- and is_alive(other)
474
  and normalize_role(other.role) == role
475
  and vec_distance(npc.position, other.position) <= max_dist
476
  ]
@@ -508,9 +510,8 @@ def npcs_in_radius(
508
  ) -> list[Npc]:
509
  return [
510
  npc
511
- for npc in world.npcs
512
- if is_alive(npc)
513
- and npc.id != exclude_id
514
  and vec_distance(position, npc.position) <= radius
515
  ]
516
 
@@ -518,13 +519,13 @@ def npcs_in_radius(
518
  def count_alive_npcs_in_radius(world: WorldState, position: Vec3, radius: float) -> int:
519
  return sum(
520
  1
521
- for npc in world.npcs
522
- if is_alive(npc) and vec_distance(position, npc.position) <= radius
523
  )
524
 
525
 
526
  def count_alive_population(world: WorldState) -> int:
527
- return sum(1 for npc in world.npcs if is_alive(npc))
528
 
529
 
530
  def completed_houses(world: WorldState) -> list[House]:
@@ -692,9 +693,8 @@ def _random_map_position(world: WorldState, rng: random.Random) -> Vec3:
692
  def _select_beast_target(world: WorldState, beast: Beast) -> Npc | None:
693
  candidates = [
694
  npc
695
- for npc in world.npcs
696
- if is_alive(npc)
697
- and not is_npc_inside_house(world, npc)
698
  ]
699
  if not candidates:
700
  return None
@@ -713,9 +713,7 @@ def _select_house_target(world: WorldState, beast: Beast) -> House | None:
713
  if not houses:
714
  return None
715
  occupied_ids = set()
716
- for npc in world.npcs:
717
- if not is_alive(npc):
718
- continue
719
  house = house_containing_npc(world, npc)
720
  if house is not None:
721
  occupied_ids.add(house.id)
@@ -793,9 +791,7 @@ def apply_survival_tick(world: WorldState) -> None:
793
 
794
  _refresh_house_occupants(world)
795
 
796
- for npc in world.npcs:
797
- if not is_alive(npc):
798
- continue
799
  npc.age += 1
800
  npc.reproduction_cooldown = max(0, npc.reproduction_cooldown - 1)
801
  npc.hunger = min(HUNGER_CAP, npc.hunger + HUNGER_RATE)
@@ -812,10 +808,7 @@ def apply_survival_tick(world: WorldState) -> None:
812
  _apply_beast_system(world)
813
  _refresh_house_occupants(world)
814
 
815
- for npc in world.npcs:
816
- if not is_alive(npc):
817
- npc.survival_goal = "dead"
818
- continue
819
  _update_safety(world, npc)
820
  if nearest_beast_distance(world, npc) > FEAR_DECAY_RADIUS:
821
  npc.fear = max(0.0, npc.fear - FEAR_DECAY)
@@ -1013,6 +1006,7 @@ def _kill_npc(world: WorldState, npc: Npc, *, cause: str, actor_id: str | None)
1013
  npc.health = min(npc.health, 0)
1014
  npc.intention = "dead"
1015
  npc.survival_goal = "dead"
 
1016
  world.deaths_by_cause[cause] = world.deaths_by_cause.get(cause, 0) + 1
1017
  if _chaos_points_active(world):
1018
  world.chaos_score += 3
@@ -1048,7 +1042,15 @@ def _kill_npc(world: WorldState, npc: Npc, *, cause: str, actor_id: str | None)
1048
  object_id=cause,
1049
  )
1050
  for witness in npcs_in_radius(world, npc.position, WITNESS_RADIUS, exclude_id=npc.id):
1051
- witness.fear = min(100.0, witness.fear + FEAR_ON_WITNESS)
 
 
 
 
 
 
 
 
1052
  add_episode(
1053
  witness,
1054
  world.tick,
@@ -1056,12 +1058,13 @@ def _kill_npc(world: WorldState, npc: Npc, *, cause: str, actor_id: str | None)
1056
  actor_id or npc.id,
1057
  f"{npc.name} died of {cause}",
1058
  target_id=npc.id,
1059
- subject_kind="npc",
1060
  perspective="witness",
1061
  tags=["danger", "death", cause],
1062
  weight=0.9,
1063
  )
1064
  remember(witness, world.tick, f"{npc.name} died of {cause}.")
 
1065
 
1066
 
1067
  def _drop_inventory(world: WorldState, npc: Npc) -> None:
@@ -1089,6 +1092,33 @@ def _drop_inventory(world: WorldState, npc: Npc) -> None:
1089
  npc.inventory_weapon = 0
1090
 
1091
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1092
  def _refresh_house_occupants(world: WorldState) -> None:
1093
  for house in world.houses:
1094
  if house.state != "completed" or house.hp <= 0:
@@ -1096,8 +1126,8 @@ def _refresh_house_occupants(world: WorldState) -> None:
1096
  continue
1097
  house.occupant_ids = [
1098
  npc.id
1099
- for npc in world.npcs
1100
- if is_alive(npc) and vec_distance(npc.position, house.position) <= HOUSE_RADIUS
1101
  ][: house.capacity]
1102
 
1103
 
@@ -1113,10 +1143,9 @@ def _update_safety(world: WorldState, npc: Npc) -> None:
1113
  for beast in world.beasts
1114
  ) or any(
1115
  other.id != npc.id
1116
- and is_alive(other)
1117
  and vec_distance(other.position, npc.position) <= 10 * TILE
1118
  and _has_hostile_directive_toward(other, npc)
1119
- for other in world.npcs
1120
  )
1121
  if not threat_near_house:
1122
  npc.safety = min(100.0, npc.safety + SAFETY_GAIN)
@@ -1154,7 +1183,7 @@ def _maybe_reproduce(world: WorldState, parent: Npc, next_tick: int) -> None:
1154
  home_house_id=house.id,
1155
  memory=[MemoryEntry(tick=next_tick, text=f"Born in {house.id} as a {role}.")],
1156
  )
1157
- for npc in world.npcs:
1158
  if npc.id == child.id:
1159
  continue
1160
  child.relationships[npc.id] = 0.45
@@ -1223,9 +1252,8 @@ def _house_has_threat(world: WorldState, house: House) -> bool:
1223
 
1224
  def _role_for_child(world: WorldState, parent: Npc) -> str:
1225
  counts = {role: 0 for role in ("gatherer", "guard", "builder")}
1226
- for npc in world.npcs:
1227
- if is_alive(npc):
1228
- counts[normalize_role(npc.role)] += 1
1229
  total = max(1, sum(counts.values()))
1230
  targets = {"gatherer": 3 / 6, "guard": 2 / 6, "builder": 1 / 6}
1231
  scarcity = {
@@ -1275,9 +1303,8 @@ def _child_name(index: int) -> str:
1275
 
1276
  def _recompute_importance(world: WorldState) -> None:
1277
  counts = {role: 0 for role in ("gatherer", "guard", "builder")}
1278
- for npc in world.npcs:
1279
- if is_alive(npc):
1280
- counts[normalize_role(npc.role)] += 1
1281
  for npc in world.npcs:
1282
  role_count = max(1, counts.get(normalize_role(npc.role), 1))
1283
  role_scarcity = 1 / role_count
@@ -1365,6 +1392,8 @@ def select_goal(npc: Npc, world: WorldState) -> str:
1365
  return "eat_food"
1366
  if npc.hunger >= EAT_GOAL_HUNGER and npc.inventory_food > 0:
1367
  return "eat_food"
 
 
1368
  if npc.hunger >= EAT_GOAL_HUNGER:
1369
  return "find_food"
1370
  if npc.health < FIND_HERBS_HEALTH and npc.inventory_herbs == 0:
@@ -1383,13 +1412,30 @@ def allowed_actions_for_goal(goal: str) -> list[str]:
1383
 
1384
 
1385
  def allowed_actions_for_npc(world: WorldState, npc: Npc, goal: str) -> list[str]:
1386
- _ = world
1387
  allowed = filter_actions_for_role(allowed_actions_for_goal(goal), npc.role)
1388
  if goal == "survive_threat_flee":
1389
  allowed = [action for action in allowed if action != "transfer"]
 
 
 
 
 
 
1390
  return allowed or ["idle"]
1391
 
1392
 
 
 
 
 
 
 
 
 
 
 
 
 
1393
  def suggested_actions_for_npc(npc: Npc, goal: str) -> list[str]:
1394
  """Role-gated, ranked LLM suggestions: primitives plus survival extras."""
1395
  role = normalize_role(npc.role)
@@ -1410,8 +1456,8 @@ def _beast_threatens_village(world: WorldState) -> bool:
1410
  for house in completed_houses(world):
1411
  if vec_distance(beast.position, house.position) <= VILLAGE_THREAT_RADIUS:
1412
  return True
1413
- for npc in world.npcs:
1414
- if is_alive(npc) and vec_distance(beast.position, npc.position) <= VILLAGE_THREAT_RADIUS:
1415
  return True
1416
  return False
1417
 
@@ -2212,9 +2258,8 @@ def _nearest_village_threat(world: WorldState, npc: Npc) -> Beast | None:
2212
  and (
2213
  any(vec_distance(beast.position, house.position) <= VILLAGE_THREAT_RADIUS for house in world.houses)
2214
  or any(
2215
- is_alive(other)
2216
- and vec_distance(beast.position, other.position) <= VILLAGE_THREAT_RADIUS
2217
- for other in world.npcs
2218
  )
2219
  )
2220
  ]
@@ -2485,9 +2530,8 @@ def _spread_resource(
2485
  def _neediest_food_neighbor(world: WorldState, npc: Npc) -> Npc | None:
2486
  candidates = [
2487
  other
2488
- for other in world.npcs
2489
  if other.id != npc.id
2490
- and is_alive(other)
2491
  and vec_distance(npc.position, other.position) <= TRADE_RADIUS
2492
  ]
2493
  if not candidates:
@@ -2508,7 +2552,7 @@ def _small_talk_line(npc: Npc, partner: Npc) -> str:
2508
 
2509
 
2510
  def _npc_by_id(world: WorldState, npc_id: str) -> Npc | None:
2511
- return next((candidate for candidate in world.npcs if candidate.id == npc_id), None)
2512
 
2513
 
2514
  def _adjust_relationship(npc: Npc, target_id: str, delta: float) -> None:
@@ -2575,9 +2619,7 @@ def survival_directive_for(world: WorldState, npc: Npc, next_tick: int) -> NpcDi
2575
  def propose_survival_tick(world: WorldState, next_tick: int) -> TickPlan:
2576
  """Deterministic survival plan: one survival action per living NPC."""
2577
  directives: list[NpcDirective] = []
2578
- for index, npc in enumerate(world.npcs):
2579
- if not is_alive(npc):
2580
- continue
2581
  goal = select_goal(npc, world)
2582
  directives.append(_plan_directive(world, npc, goal, next_tick, index))
2583
  return TickPlan(source="survival", directives=directives)
@@ -2599,6 +2641,7 @@ def apply_survival_plan(
2599
  if not is_alive(npc):
2600
  npc.intention = "dead"
2601
  continue
 
2602
  action = validate_survival_action(npc, directive.action, world, directive)
2603
  summary = apply_action_effects(
2604
  npc,
@@ -2622,8 +2665,14 @@ def apply_survival_plan(
2622
  "npc_id": npc.id,
2623
  "goal": npc.survival_goal,
2624
  "requested_action": directive.action,
 
2625
  "action": action,
2626
  "summary": summary,
 
 
 
 
 
2627
  }
2628
  )
2629
 
@@ -2634,6 +2683,37 @@ def apply_survival_plan(
2634
  return debug
2635
 
2636
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2637
  def _plan_directive(
2638
  world: WorldState,
2639
  npc: Npc,
@@ -2671,6 +2751,36 @@ def _plan_directive(
2671
 
2672
  role = normalize_role(npc.role)
2673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2674
  if goal == "engage_threat":
2675
  beast = _nearest_village_threat(world, npc)
2676
  if beast is not None:
@@ -2794,3 +2904,12 @@ def _plan_directive(
2794
  if node is not None and phase != 3:
2795
  return directive("move", target=node.position, resource_id=node.id)
2796
  return directive("move") # wander to disperse
 
 
 
 
 
 
 
 
 
 
27
  WorldState,
28
  )
29
  from god_simulator.simulation.connectors.base import NpcDirective, TickPlan
30
+ from god_simulator.simulation.directives import clear_active_directive
31
  from god_simulator.simulation.mechanics import (
32
  ATTACK_RADIUS,
33
  BLOCK_SIZE,
 
65
  VILLAGE_THREAT_RADIUS = 10 * TILE
66
  HOUSE_THREAT_RADIUS = 12 * TILE
67
  ALLY_RADIUS = 5 * TILE
68
+ WITNESS_RADIUS = 10.0
69
  FEAR_DECAY_RADIUS = 12 * TILE
70
  GATHER_RADIUS = 1.5 * TILE
71
  TRADE_RADIUS = 2 * TILE
 
80
  # Fear dynamics.
81
  FEAR_ON_ATTACK = 60.0
82
  FEAR_ON_WITNESS = 20.0
83
+ FEAR_ON_DEATH_BY_BEAST = 30.0
84
  FEAR_DECAY = 2.0
85
  SAFETY_GAIN = 12.0
86
  SAFETY_DECAY = 8.0
 
124
  "eat_food": ["consume"],
125
  "find_food": ["move_to_resource", "gather", "communicate", "steal"],
126
  "find_herbs": ["move_to_resource", "gather", "communicate"],
127
+ "obey_directive": ["attack", "defend", "flee", "go_home", "move_to_resource", "gather", "communicate", "build", "patrol", "idle"],
128
  "settle": ["go_home", "consume", "communicate", "transfer"],
129
  "work": ["gather", "move_to_resource", "transfer", "communicate", "build", "patrol"],
130
  "routine_life": ["gather", "move_to_resource", "transfer", "communicate", "go_home", "build", "patrol"],
 
143
  "eat_food": ["use"],
144
  "find_food": ["move", "use", "speak", "transfer"],
145
  "find_herbs": ["move", "use", "speak"],
146
+ "obey_directive": ["speak", "move", "strike", "go_home", "build", "patrol", "idle"],
147
  "settle": ["go_home", "use", "speak", "transfer"],
148
  "work": ["use", "move", "build", "patrol", "transfer", "speak"],
149
  "routine_life": ["use", "move", "transfer", "speak", "go_home", "build", "patrol"],
 
330
 
331
 
332
  def build_relationships_summary(npc: Npc, world: WorldState | None = None) -> str:
333
+ names = {other.id: other.name for other in world.living_npcs()} if world is not None else {}
334
  ids = set(npc.relationships)
335
  if world is not None:
336
+ ids.update(other.id for other in world.living_npcs() if other.id != npc.id)
337
  ids.update(beast.id for beast in world.beasts)
338
 
339
  lines: list[str] = []
 
435
  ) -> Npc | None:
436
  candidates = [
437
  npc
438
+ for npc in world.living_npcs()
439
+ if npc.id != exclude_id
440
  ]
441
  if not candidates:
442
  return None
 
452
  ) -> Npc | None:
453
  candidates = [
454
  other
455
+ for other in world.living_npcs()
456
  if other.id != npc.id
 
457
  and vec_distance(npc.position, other.position) <= max_dist
458
  and (not require_food or other.inventory_food > 0)
459
  ]
 
471
  ) -> Npc | None:
472
  candidates = [
473
  other
474
+ for other in world.living_npcs()
475
  if other.id != npc.id
 
476
  and normalize_role(other.role) == role
477
  and vec_distance(npc.position, other.position) <= max_dist
478
  ]
 
510
  ) -> list[Npc]:
511
  return [
512
  npc
513
+ for npc in world.living_npcs()
514
+ if npc.id != exclude_id
 
515
  and vec_distance(position, npc.position) <= radius
516
  ]
517
 
 
519
  def count_alive_npcs_in_radius(world: WorldState, position: Vec3, radius: float) -> int:
520
  return sum(
521
  1
522
+ for npc in world.living_npcs()
523
+ if vec_distance(position, npc.position) <= radius
524
  )
525
 
526
 
527
  def count_alive_population(world: WorldState) -> int:
528
+ return len(world.living_npcs())
529
 
530
 
531
  def completed_houses(world: WorldState) -> list[House]:
 
693
  def _select_beast_target(world: WorldState, beast: Beast) -> Npc | None:
694
  candidates = [
695
  npc
696
+ for npc in world.living_npcs()
697
+ if not is_npc_inside_house(world, npc)
 
698
  ]
699
  if not candidates:
700
  return None
 
713
  if not houses:
714
  return None
715
  occupied_ids = set()
716
+ for npc in world.living_npcs():
 
 
717
  house = house_containing_npc(world, npc)
718
  if house is not None:
719
  occupied_ids.add(house.id)
 
791
 
792
  _refresh_house_occupants(world)
793
 
794
+ for npc in list(world.living_npcs()):
 
 
795
  npc.age += 1
796
  npc.reproduction_cooldown = max(0, npc.reproduction_cooldown - 1)
797
  npc.hunger = min(HUNGER_CAP, npc.hunger + HUNGER_RATE)
 
808
  _apply_beast_system(world)
809
  _refresh_house_occupants(world)
810
 
811
+ for npc in world.living_npcs():
 
 
 
812
  _update_safety(world, npc)
813
  if nearest_beast_distance(world, npc) > FEAR_DECAY_RADIUS:
814
  npc.fear = max(0.0, npc.fear - FEAR_DECAY)
 
1006
  npc.health = min(npc.health, 0)
1007
  npc.intention = "dead"
1008
  npc.survival_goal = "dead"
1009
+ clear_active_directive(npc)
1010
  world.deaths_by_cause[cause] = world.deaths_by_cause.get(cause, 0) + 1
1011
  if _chaos_points_active(world):
1012
  world.chaos_score += 3
 
1042
  object_id=cause,
1043
  )
1044
  for witness in npcs_in_radius(world, npc.position, WITNESS_RADIUS, exclude_id=npc.id):
1045
+ actor_is_beast = bool(actor_id and actor_id.startswith("beast"))
1046
+ actor_is_npc = bool(actor_id and actor_id.startswith("npc"))
1047
+ if actor_is_beast:
1048
+ witness.fear = min(100.0, witness.fear + FEAR_ON_DEATH_BY_BEAST)
1049
+ witness.relationships[actor_id or "beast"] = -1.0
1050
+ else:
1051
+ witness.fear = min(100.0, witness.fear + FEAR_ON_WITNESS)
1052
+ if actor_is_npc and actor_id is not None:
1053
+ _adjust_relationship(witness, actor_id, -0.5)
1054
  add_episode(
1055
  witness,
1056
  world.tick,
 
1058
  actor_id or npc.id,
1059
  f"{npc.name} died of {cause}",
1060
  target_id=npc.id,
1061
+ subject_kind="beast" if actor_is_beast else "npc",
1062
  perspective="witness",
1063
  tags=["danger", "death", cause],
1064
  weight=0.9,
1065
  )
1066
  remember(witness, world.tick, f"{npc.name} died of {cause}.")
1067
+ _purge_dead_npc_references(world, npc)
1068
 
1069
 
1070
  def _drop_inventory(world: WorldState, npc: Npc) -> None:
 
1092
  npc.inventory_weapon = 0
1093
 
1094
 
1095
+ def _purge_dead_npc_references(world: WorldState, dead: Npc) -> None:
1096
+ for house in world.houses:
1097
+ house.occupant_ids = [npc_id for npc_id in house.occupant_ids if npc_id != dead.id]
1098
+ house.owner_ids = [npc_id for npc_id in house.owner_ids if npc_id != dead.id]
1099
+
1100
+ dead.focus_target_id = None
1101
+ dead.help_target_id = None
1102
+ dead.build_target_house_id = None
1103
+ dead.home_house_id = None
1104
+
1105
+ dead_name = dead.name.lower()
1106
+ dead_id = dead.id.lower()
1107
+ for npc in world.living_npcs():
1108
+ if npc.focus_target_id == dead.id:
1109
+ npc.focus_target_id = None
1110
+ if npc.help_target_id == dead.id:
1111
+ npc.help_target_id = None
1112
+ if npc.god_directive:
1113
+ lowered = npc.god_directive.lower()
1114
+ if dead_id in lowered or dead_name in lowered:
1115
+ clear_active_directive(npc)
1116
+
1117
+ for beast in world.beasts:
1118
+ if beast.target_npc_id == dead.id:
1119
+ beast.target_npc_id = None
1120
+
1121
+
1122
  def _refresh_house_occupants(world: WorldState) -> None:
1123
  for house in world.houses:
1124
  if house.state != "completed" or house.hp <= 0:
 
1126
  continue
1127
  house.occupant_ids = [
1128
  npc.id
1129
+ for npc in world.living_npcs()
1130
+ if vec_distance(npc.position, house.position) <= HOUSE_RADIUS
1131
  ][: house.capacity]
1132
 
1133
 
 
1143
  for beast in world.beasts
1144
  ) or any(
1145
  other.id != npc.id
 
1146
  and vec_distance(other.position, npc.position) <= 10 * TILE
1147
  and _has_hostile_directive_toward(other, npc)
1148
+ for other in world.living_npcs()
1149
  )
1150
  if not threat_near_house:
1151
  npc.safety = min(100.0, npc.safety + SAFETY_GAIN)
 
1183
  home_house_id=house.id,
1184
  memory=[MemoryEntry(tick=next_tick, text=f"Born in {house.id} as a {role}.")],
1185
  )
1186
+ for npc in world.living_npcs():
1187
  if npc.id == child.id:
1188
  continue
1189
  child.relationships[npc.id] = 0.45
 
1252
 
1253
  def _role_for_child(world: WorldState, parent: Npc) -> str:
1254
  counts = {role: 0 for role in ("gatherer", "guard", "builder")}
1255
+ for npc in world.living_npcs():
1256
+ counts[normalize_role(npc.role)] += 1
 
1257
  total = max(1, sum(counts.values()))
1258
  targets = {"gatherer": 3 / 6, "guard": 2 / 6, "builder": 1 / 6}
1259
  scarcity = {
 
1303
 
1304
  def _recompute_importance(world: WorldState) -> None:
1305
  counts = {role: 0 for role in ("gatherer", "guard", "builder")}
1306
+ for npc in world.living_npcs():
1307
+ counts[normalize_role(npc.role)] += 1
 
1308
  for npc in world.npcs:
1309
  role_count = max(1, counts.get(normalize_role(npc.role), 1))
1310
  role_scarcity = 1 / role_count
 
1392
  return "eat_food"
1393
  if npc.hunger >= EAT_GOAL_HUNGER and npc.inventory_food > 0:
1394
  return "eat_food"
1395
+ if npc.god_directive:
1396
+ return "obey_directive"
1397
  if npc.hunger >= EAT_GOAL_HUNGER:
1398
  return "find_food"
1399
  if npc.health < FIND_HERBS_HEALTH and npc.inventory_herbs == 0:
 
1412
 
1413
 
1414
  def allowed_actions_for_npc(world: WorldState, npc: Npc, goal: str) -> list[str]:
 
1415
  allowed = filter_actions_for_role(allowed_actions_for_goal(goal), npc.role)
1416
  if goal == "survive_threat_flee":
1417
  allowed = [action for action in allowed if action != "transfer"]
1418
+ if "gather" in allowed and not _has_gatherable_resource_for_goal(world, npc, goal):
1419
+ allowed = [action for action in allowed if action != "gather"]
1420
+ if "consume" in allowed and npc.inventory_food <= 0:
1421
+ allowed = [action for action in allowed if action != "consume"]
1422
+ if "heal" in allowed and npc.inventory_herbs <= 0:
1423
+ allowed = [action for action in allowed if action != "heal"]
1424
  return allowed or ["idle"]
1425
 
1426
 
1427
+ def _has_gatherable_resource_for_goal(world: WorldState, npc: Npc, goal: str) -> bool:
1428
+ resource_type: str | None = None
1429
+ if goal == "find_food":
1430
+ resource_type = "food"
1431
+ elif goal == "find_herbs":
1432
+ resource_type = "herbs"
1433
+ elif normalize_role(npc.role) == "builder":
1434
+ resource_type = "wood"
1435
+ node = nearest_resource_for_npc(world, npc, resource_type=resource_type)
1436
+ return node is not None and vec_distance(npc.position, node.position) <= GATHER_RADIUS
1437
+
1438
+
1439
  def suggested_actions_for_npc(npc: Npc, goal: str) -> list[str]:
1440
  """Role-gated, ranked LLM suggestions: primitives plus survival extras."""
1441
  role = normalize_role(npc.role)
 
1456
  for house in completed_houses(world):
1457
  if vec_distance(beast.position, house.position) <= VILLAGE_THREAT_RADIUS:
1458
  return True
1459
+ for npc in world.living_npcs():
1460
+ if vec_distance(beast.position, npc.position) <= VILLAGE_THREAT_RADIUS:
1461
  return True
1462
  return False
1463
 
 
2258
  and (
2259
  any(vec_distance(beast.position, house.position) <= VILLAGE_THREAT_RADIUS for house in world.houses)
2260
  or any(
2261
+ vec_distance(beast.position, other.position) <= VILLAGE_THREAT_RADIUS
2262
+ for other in world.living_npcs()
 
2263
  )
2264
  )
2265
  ]
 
2530
  def _neediest_food_neighbor(world: WorldState, npc: Npc) -> Npc | None:
2531
  candidates = [
2532
  other
2533
+ for other in world.living_npcs()
2534
  if other.id != npc.id
 
2535
  and vec_distance(npc.position, other.position) <= TRADE_RADIUS
2536
  ]
2537
  if not candidates:
 
2552
 
2553
 
2554
  def _npc_by_id(world: WorldState, npc_id: str) -> Npc | None:
2555
+ return next((candidate for candidate in world.living_npcs() if candidate.id == npc_id), None)
2556
 
2557
 
2558
  def _adjust_relationship(npc: Npc, target_id: str, delta: float) -> None:
 
2619
  def propose_survival_tick(world: WorldState, next_tick: int) -> TickPlan:
2620
  """Deterministic survival plan: one survival action per living NPC."""
2621
  directives: list[NpcDirective] = []
2622
+ for index, npc in enumerate(world.living_npcs()):
 
 
2623
  goal = select_goal(npc, world)
2624
  directives.append(_plan_directive(world, npc, goal, next_tick, index))
2625
  return TickPlan(source="survival", directives=directives)
 
2641
  if not is_alive(npc):
2642
  npc.intention = "dead"
2643
  continue
2644
+ requested_effect = _canonical_action(_verb_for_action(npc, directive.action, world, directive))
2645
  action = validate_survival_action(npc, directive.action, world, directive)
2646
  summary = apply_action_effects(
2647
  npc,
 
2665
  "npc_id": npc.id,
2666
  "goal": npc.survival_goal,
2667
  "requested_action": directive.action,
2668
+ "requested_effect": requested_effect,
2669
  "action": action,
2670
  "summary": summary,
2671
+ "validator_verdict": _survival_validator_verdict(
2672
+ requested_action=str(directive.action),
2673
+ requested_effect=requested_effect,
2674
+ resolved_action=action,
2675
+ ),
2676
  }
2677
  )
2678
 
 
2683
  return debug
2684
 
2685
 
2686
+ def _survival_validator_verdict(
2687
+ *,
2688
+ requested_action: str,
2689
+ requested_effect: str,
2690
+ resolved_action: str,
2691
+ ) -> dict[str, object]:
2692
+ if requested_effect == resolved_action:
2693
+ return {
2694
+ "status": "accepted",
2695
+ "requested": requested_action,
2696
+ "requested_effect": requested_effect,
2697
+ "resolved": resolved_action,
2698
+ "reason": "accepted",
2699
+ }
2700
+ if resolved_action == "idle" and requested_effect != "idle":
2701
+ return {
2702
+ "status": "rejected",
2703
+ "requested": requested_action,
2704
+ "requested_effect": requested_effect,
2705
+ "resolved": resolved_action,
2706
+ "reason": "invalid or impossible survival action",
2707
+ }
2708
+ return {
2709
+ "status": "repaired",
2710
+ "requested": requested_action,
2711
+ "requested_effect": requested_effect,
2712
+ "resolved": resolved_action,
2713
+ "reason": "engine validation repaired action",
2714
+ }
2715
+
2716
+
2717
  def _plan_directive(
2718
  world: WorldState,
2719
  npc: Npc,
 
2751
 
2752
  role = normalize_role(npc.role)
2753
 
2754
+ if goal == "obey_directive":
2755
+ text = (npc.god_directive or "").lower()
2756
+ target = _directive_named_target(world, npc, text)
2757
+ if any(word in text for word in ("attack", "kill", "fight", "hunt", "strike")):
2758
+ if target is not None:
2759
+ return directive("strike", target_npc_id=target.id)
2760
+ if "beast" in text or "monster" in text:
2761
+ beast = nearest_beast(world, npc.position)
2762
+ if beast is not None:
2763
+ return directive("strike", target=beast.position)
2764
+ return directive("strike")
2765
+ if any(word in text for word in ("home", "shelter", "hide", "safe")):
2766
+ return directive("go_home")
2767
+ if any(word in text for word in ("build", "repair", "house")):
2768
+ return directive("build")
2769
+ if any(word in text for word in ("wood", "food", "herb", "gather", "resource")):
2770
+ resource_type = "wood" if "wood" in text else "food" if "food" in text else "herbs" if "herb" in text else None
2771
+ node = _spread_resource(world, npc, index, resource_type=resource_type)
2772
+ if node is not None and vec_distance(npc.position, node.position) <= GATHER_RADIUS:
2773
+ return directive("use", resource_id=node.id, resource_type=resource_type)
2774
+ if node is not None:
2775
+ return directive("move", target=node.position, resource_id=node.id, resource_type=resource_type)
2776
+ if any(word in text for word in ("help", "warn", "talk", "speak", "tell")):
2777
+ partner = target or nearest_alive_npc(world, npc, max_dist=TALK_RADIUS)
2778
+ if partner is not None:
2779
+ return directive("speak", target_npc_id=partner.id, communication_intent="directive")
2780
+ if any(word in text for word in ("patrol", "guard", "watch")):
2781
+ return directive("patrol")
2782
+ return directive("idle")
2783
+
2784
  if goal == "engage_threat":
2785
  beast = _nearest_village_threat(world, npc)
2786
  if beast is not None:
 
2904
  if node is not None and phase != 3:
2905
  return directive("move", target=node.position, resource_id=node.id)
2906
  return directive("move") # wander to disperse
2907
+
2908
+
2909
+ def _directive_named_target(world: WorldState, npc: Npc, text: str) -> Npc | None:
2910
+ for other in world.living_npcs():
2911
+ if other.id == npc.id:
2912
+ continue
2913
+ if other.id.lower() in text or other.name.lower() in text:
2914
+ return other
2915
+ return None
src/god_simulator/simulation/tick.py CHANGED
@@ -2,9 +2,11 @@ from __future__ import annotations
2
 
3
  import math
4
  import random
 
5
  from dataclasses import asdict, replace
6
 
7
  from god_simulator.domain import CitizenGoal, Npc, Vec3, WorldState
 
8
  from god_simulator.simulation.actions import PRIMITIVE_ACTION_IDS
9
  from god_simulator.simulation.autopilot import (
10
  autopilot_directive,
@@ -22,6 +24,7 @@ from god_simulator.simulation.connectors.base import (
22
  WorldSimulator,
23
  )
24
  from god_simulator.simulation.connectors.deterministic import DeterministicWorldSimulator
 
25
  from god_simulator.simulation.goals import refresh_citizen_motivation
26
  from god_simulator.simulation.mechanics import (
27
  ATTACK_RADIUS,
@@ -51,7 +54,9 @@ def advance_world(
51
  overseer: OverseerController | None = None,
52
  ) -> WorldState:
53
  """Advance world state by asking the configured simulator for a tick plan."""
54
- next_tick, plan = plan_world_tick(world, simulator, overseer=overseer)
 
 
55
  apply_tick_plan(world, next_tick, plan)
56
  return world
57
 
@@ -65,10 +70,29 @@ def plan_world_tick(
65
  """Build a tick plan without mutating the supplied world state."""
66
  planned_tick = next_tick if next_tick is not None else world.tick + 1
67
  active_simulator = simulator or DeterministicWorldSimulator()
68
- plan = active_simulator.propose_tick(world, planned_tick)
69
- if overseer is not None:
70
- plan = overseer.augment_plan(world, planned_tick, plan)
71
- return planned_tick, plan
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
 
74
  def apply_tick_plan(world: WorldState, next_tick: int, plan: TickPlan) -> None:
@@ -83,6 +107,7 @@ def apply_tick_plan(world: WorldState, next_tick: int, plan: TickPlan) -> None:
83
  world.tick = next_tick
84
  apply_overseer_metadata(world, plan.overseer)
85
  debug = apply_survival_plan(world, next_tick, plan)
 
86
  apply_post_survival_tick(world, next_tick)
87
  world.last_tick_source = plan.source
88
  world.last_action_debug = debug
@@ -158,6 +183,7 @@ def apply_tick_plan(world: WorldState, next_tick: int, plan: TickPlan) -> None:
158
  apply_overseer_metadata(world, plan.overseer)
159
  world.last_tick_source = plan.source
160
  world.last_action_debug = [_trace_to_dict(trace) for trace in resolved_traces]
 
161
 
162
 
163
  def validate_tick_plan(
@@ -181,7 +207,15 @@ def validate_tick_plan(
181
  )
182
  resolved_directives.append(validation.directive)
183
 
184
- return TickPlan(source=plan.source, directives=resolved_directives, overseer=plan.overseer), traces
 
 
 
 
 
 
 
 
185
 
186
 
187
  def validate_directive(
@@ -396,7 +430,7 @@ def _move_intent(goal: CitizenGoal | None, target: Npc) -> str:
396
 
397
 
398
  def _npc_by_id(world: WorldState, npc_id: str) -> Npc | None:
399
- return next((candidate for candidate in world.npcs if candidate.id == npc_id), None)
400
 
401
 
402
  def _resolve_move_targets(
@@ -815,6 +849,54 @@ def _append_resolution_trace(
815
  )
816
 
817
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
818
  def _trace_to_dict(trace: ActionDebugTrace) -> dict[str, object]:
819
  return asdict(trace)
820
 
 
2
 
3
  import math
4
  import random
5
+ from copy import deepcopy
6
  from dataclasses import asdict, replace
7
 
8
  from god_simulator.domain import CitizenGoal, Npc, Vec3, WorldState
9
+ from god_simulator.observability import append_record
10
  from god_simulator.simulation.actions import PRIMITIVE_ACTION_IDS
11
  from god_simulator.simulation.autopilot import (
12
  autopilot_directive,
 
24
  WorldSimulator,
25
  )
26
  from god_simulator.simulation.connectors.deterministic import DeterministicWorldSimulator
27
+ from god_simulator.simulation.directives import expire_directives
28
  from god_simulator.simulation.goals import refresh_citizen_motivation
29
  from god_simulator.simulation.mechanics import (
30
  ATTACK_RADIUS,
 
54
  overseer: OverseerController | None = None,
55
  ) -> WorldState:
56
  """Advance world state by asking the configured simulator for a tick plan."""
57
+ planned_tick = world.tick + 1
58
+ expire_directives(world, tick=planned_tick)
59
+ next_tick, plan = plan_world_tick(world, simulator, next_tick=planned_tick, overseer=overseer)
60
  apply_tick_plan(world, next_tick, plan)
61
  return world
62
 
 
70
  """Build a tick plan without mutating the supplied world state."""
71
  planned_tick = next_tick if next_tick is not None else world.tick + 1
72
  active_simulator = simulator or DeterministicWorldSimulator()
73
+ if overseer is None:
74
+ return planned_tick, active_simulator.propose_tick(world, planned_tick)
75
+
76
+ prompt_world = deepcopy(world)
77
+ overseer_plan = overseer.augment_plan(
78
+ prompt_world,
79
+ planned_tick,
80
+ TickPlan(source="pre_npc", directives=[]),
81
+ )
82
+ apply_overseer_metadata(prompt_world, overseer_plan.overseer)
83
+ npc_plan = active_simulator.propose_tick(prompt_world, planned_tick)
84
+ merged = {directive.npc_id: directive for directive in npc_plan.directives}
85
+ for directive in overseer_plan.directives:
86
+ merged[directive.npc_id] = directive
87
+ return (
88
+ planned_tick,
89
+ TickPlan(
90
+ source=f"{npc_plan.source}+overseer" if overseer_plan.overseer else npc_plan.source,
91
+ directives=list(merged.values()),
92
+ overseer=overseer_plan.overseer,
93
+ ledger_entries=[*overseer_plan.ledger_entries, *npc_plan.ledger_entries],
94
+ ),
95
+ )
96
 
97
 
98
  def apply_tick_plan(world: WorldState, next_tick: int, plan: TickPlan) -> None:
 
107
  world.tick = next_tick
108
  apply_overseer_metadata(world, plan.overseer)
109
  debug = apply_survival_plan(world, next_tick, plan)
110
+ _publish_plan_ledger_entries(plan.ledger_entries, debug)
111
  apply_post_survival_tick(world, next_tick)
112
  world.last_tick_source = plan.source
113
  world.last_action_debug = debug
 
183
  apply_overseer_metadata(world, plan.overseer)
184
  world.last_tick_source = plan.source
185
  world.last_action_debug = [_trace_to_dict(trace) for trace in resolved_traces]
186
+ _publish_plan_ledger_entries(plan.ledger_entries, world.last_action_debug)
187
 
188
 
189
  def validate_tick_plan(
 
207
  )
208
  resolved_directives.append(validation.directive)
209
 
210
+ return (
211
+ TickPlan(
212
+ source=plan.source,
213
+ directives=resolved_directives,
214
+ overseer=plan.overseer,
215
+ ledger_entries=plan.ledger_entries,
216
+ ),
217
+ traces,
218
+ )
219
 
220
 
221
  def validate_directive(
 
430
 
431
 
432
  def _npc_by_id(world: WorldState, npc_id: str) -> Npc | None:
433
+ return next((candidate for candidate in world.living_npcs() if candidate.id == npc_id), None)
434
 
435
 
436
  def _resolve_move_targets(
 
849
  )
850
 
851
 
852
+ def _publish_plan_ledger_entries(
853
+ entries: list[dict[str, object]],
854
+ debug: list[dict[str, object]],
855
+ ) -> None:
856
+ if not entries:
857
+ return
858
+ verdicts = _validator_verdicts_by_npc(debug)
859
+ for entry in entries:
860
+ record = dict(entry)
861
+ if record.get("phase") == "npc_response":
862
+ npc_id = str(record.get("npc_id") or "")
863
+ verdict = verdicts.get(npc_id)
864
+ if verdict is not None:
865
+ record["validator_verdict"] = verdict
866
+ append_record(record)
867
+
868
+
869
+ def _validator_verdicts_by_npc(debug: list[dict[str, object]]) -> dict[str, dict[str, object]]:
870
+ verdicts: dict[str, dict[str, object]] = {}
871
+ for trace in debug:
872
+ npc_id = trace.get("npc_id")
873
+ if not isinstance(npc_id, str):
874
+ continue
875
+ verdict = trace.get("validator_verdict")
876
+ if isinstance(verdict, dict):
877
+ verdicts[npc_id] = dict(verdict)
878
+ continue
879
+ validation = trace.get("validation")
880
+ if isinstance(validation, dict):
881
+ valid = validation.get("valid")
882
+ original = validation.get("original_action")
883
+ resolved = validation.get("resolved_action")
884
+ reason = validation.get("reason")
885
+ if valid is True:
886
+ status = "accepted"
887
+ elif original != resolved:
888
+ status = "repaired"
889
+ else:
890
+ status = "rejected"
891
+ verdicts[npc_id] = {
892
+ "status": status,
893
+ "requested": original,
894
+ "resolved": resolved,
895
+ "reason": reason,
896
+ }
897
+ return verdicts
898
+
899
+
900
  def _trace_to_dict(trace: ActionDebugTrace) -> dict[str, object]:
901
  return asdict(trace)
902
 
tests/test_observability_perception.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from http import HTTPStatus
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from god_simulator.api.runtime import GameRuntime
9
+ from god_simulator.config import (
10
+ ConnectorConfig,
11
+ GameConfig,
12
+ NpcConfig,
13
+ ServerConfig,
14
+ SimulationConfig,
15
+ WorldConfig,
16
+ )
17
+ from god_simulator.domain import Beast, House, Npc, ResourceNode, Terrain, Vec3, WorldState
18
+ from god_simulator.observability import RunLedger
19
+ from god_simulator.simulation.connectors.deterministic import DeterministicWorldSimulator
20
+ from god_simulator.simulation.connectors.openai_compatible import OpenAICompatibleWorldSimulator
21
+ from god_simulator.simulation.directives import (
22
+ DEFAULT_DIRECTIVE_TTL_TICKS,
23
+ expire_directives,
24
+ set_active_directive,
25
+ )
26
+ from god_simulator.simulation.god_console import GodConsole
27
+ from god_simulator.simulation.overseer import build_overseer_context, scripted_overseer_controller
28
+ from god_simulator.simulation.spawning import create_world
29
+ from god_simulator.simulation.survival import _kill_npc
30
+ from god_simulator.simulation.tick import advance_world
31
+
32
+
33
+ def test_dead_npcs_never_appear_in_model_target_fields_over_scripted_deaths() -> None:
34
+ world = _survival_world(npc_count=8)
35
+ world.beasts.clear()
36
+ captured_payloads: list[dict[str, Any]] = []
37
+
38
+ def fake_chat_completer(request: dict[str, Any]) -> dict[str, Any]:
39
+ payload = json.loads(request["messages"][1]["content"])
40
+ captured_payloads.append(payload)
41
+ return _tool_response("idle", {"npc_id": payload["npc_id"]})
42
+
43
+ simulator = OpenAICompatibleWorldSimulator(
44
+ ConnectorConfig(
45
+ type="openai_compatible",
46
+ base_url="http://llm.local/v1",
47
+ model="test-model",
48
+ max_parallel_npc_calls=8,
49
+ ),
50
+ fallback=DeterministicWorldSimulator(),
51
+ chat_completer=fake_chat_completer,
52
+ )
53
+
54
+ for iteration in range(200):
55
+ if iteration in {3, 17, 41, 73} and len(world.living_npcs()) > 3:
56
+ victim = world.living_npcs()[-1]
57
+ victim.inventory_food = 1
58
+ world.houses[0].occupant_ids.append(victim.id)
59
+ world.beasts.append(Beast(f"beast_scripted_{iteration}", victim.position, target_npc_id=victim.id))
60
+ _kill_npc(world, victim, cause="scripted", actor_id="test")
61
+
62
+ captured_payloads.clear()
63
+ pre_tick_dead_ids = {npc.id for npc in world.npcs if npc.health <= 0}
64
+ advance_world(world, simulator)
65
+ dead_ids = {npc.id for npc in world.npcs if npc.health <= 0}
66
+ if not dead_ids:
67
+ continue
68
+
69
+ for payload in captured_payloads:
70
+ _assert_survival_payload_has_no_dead_targets(payload, world, pre_tick_dead_ids)
71
+ _assert_world_live_registries_have_no_dead_targets(world, dead_ids)
72
+ _assert_overseer_context_has_no_dead_targets(
73
+ build_overseer_context(world, world.tick + 1),
74
+ dead_ids,
75
+ )
76
+
77
+
78
+ def test_directive_ttl_expiry_and_replacement() -> None:
79
+ npc = _npc("npc-001", "Ada")
80
+ world = _world([npc])
81
+
82
+ set_active_directive(npc, "Gather food.", source="test", tick=0)
83
+ assert npc.directive_ttl_ticks == DEFAULT_DIRECTIVE_TTL_TICKS
84
+ expire_directives(world, tick=DEFAULT_DIRECTIVE_TTL_TICKS - 1)
85
+ assert npc.god_directive == "Gather food."
86
+
87
+ expire_directives(world, tick=DEFAULT_DIRECTIVE_TTL_TICKS)
88
+ assert npc.god_directive is None
89
+ assert world.event_log[-1].type == "directive_expired"
90
+
91
+ set_active_directive(npc, "First order.", source="test", tick=30, ttl_ticks=24)
92
+ set_active_directive(npc, "Replacement order.", source="test", tick=31, ttl_ticks=7)
93
+ assert npc.god_directive == "Replacement order."
94
+ assert npc.directive_issued_tick == 31
95
+ assert npc.directive_ttl_ticks == 7
96
+
97
+ expire_directives(world, tick=37)
98
+ assert npc.god_directive == "Replacement order."
99
+ expire_directives(world, tick=38)
100
+ assert npc.god_directive is None
101
+
102
+
103
+ def test_death_drops_loot_and_updates_witnesses_and_live_registries() -> None:
104
+ killer = _npc("npc-001", "Ada", x=0.0)
105
+ victim = _npc(
106
+ "npc-002",
107
+ "Boris",
108
+ x=1.0,
109
+ inventory_food=2,
110
+ inventory_herbs=1,
111
+ inventory_wood=3,
112
+ inventory_weapon=1,
113
+ )
114
+ witness = _npc("npc-003", "Cora", x=2.0)
115
+ house = House("house_1", Vec3(1.0, 0.0, 0.0), occupant_ids=[victim.id], owner_ids=[victim.id])
116
+ beast = Beast("beast_1", Vec3(0.0, 0.0, 0.0), target_npc_id=victim.id)
117
+ world = _world([killer, victim, witness], houses=[house], beasts=[beast], tick=7)
118
+ killer.focus_target_id = victim.id
119
+ witness.help_target_id = victim.id
120
+ set_active_directive(witness, "Help Boris.", source="test", tick=7)
121
+
122
+ _kill_npc(world, victim, cause="violence", actor_id=killer.id)
123
+
124
+ assert victim.health <= 0
125
+ assert {node.resource_type: node.amount for node in world.resource_nodes} == {
126
+ "food": 2,
127
+ "herbs": 1,
128
+ "wood": 3,
129
+ "weapon": 1,
130
+ }
131
+ assert witness.relationships[killer.id] == -0.5
132
+ assert witness.structured_memory.episodes[-1].emotional_weight == 0.9
133
+ assert victim.id not in house.occupant_ids
134
+ assert victim.id not in house.owner_ids
135
+ assert killer.focus_target_id is None
136
+ assert witness.help_target_id is None
137
+ assert witness.god_directive is None
138
+ assert beast.target_npc_id is None
139
+
140
+
141
+ def test_beast_kill_gives_witness_fear_and_beast_relationship() -> None:
142
+ victim = _npc("npc-001", "Ada", x=0.0)
143
+ witness = _npc("npc-002", "Boris", x=2.0, fear=10.0)
144
+ world = _world([victim, witness], tick=5)
145
+
146
+ _kill_npc(world, victim, cause="beast", actor_id="beast_1")
147
+
148
+ assert witness.fear == 40.0
149
+ assert witness.relationships["beast_1"] == -1.0
150
+ assert witness.structured_memory.episodes[-1].subject_kind == "beast"
151
+ assert witness.structured_memory.episodes[-1].emotional_weight == 0.9
152
+
153
+
154
+ def test_runtime_ledger_contains_all_required_phase_types_after_20_ticks() -> None:
155
+ world = create_world(_config(npc_count=4, survival=True))
156
+ ledger_root = Path("tmp") / "ledger_tests"
157
+ ledger_root.mkdir(parents=True, exist_ok=True)
158
+ ledger = RunLedger(root=ledger_root)
159
+ runtime = GameRuntime(
160
+ world=world,
161
+ simulator=_ledger_test_simulator(),
162
+ god_console=_ledger_test_god_console(),
163
+ overseer=scripted_overseer_controller(mode="autopilot", cycle_ticks=1),
164
+ ledger=ledger,
165
+ )
166
+
167
+ status, payload = runtime.god_command("Give the village a harmless omen.")
168
+ assert status == HTTPStatus.OK
169
+ assert payload["queued"] is True
170
+
171
+ for _ in range(20):
172
+ status, _ = runtime.tick()
173
+ assert status == HTTPStatus.OK
174
+
175
+ records = [
176
+ json.loads(line)
177
+ for line in ledger.ledger_path.read_text(encoding="utf-8").splitlines()
178
+ ]
179
+ phases = {record["phase"] for record in records}
180
+
181
+ assert {
182
+ "god_command",
183
+ "overseer_request",
184
+ "overseer_response",
185
+ "npc_request",
186
+ "npc_response",
187
+ "npc_fallback",
188
+ "engine_events",
189
+ }.issubset(phases)
190
+ assert ledger.pretty_path.read_text(encoding="utf-8").strip()
191
+
192
+
193
+ def _ledger_test_simulator() -> OpenAICompatibleWorldSimulator:
194
+ def fake_chat_completer(request: dict[str, Any]) -> dict[str, Any]:
195
+ payload = json.loads(request["messages"][1]["content"])
196
+ if payload["npc_id"] == "npc-001":
197
+ raise RuntimeError("scripted model outage")
198
+ return _tool_response("idle", {"npc_id": payload["npc_id"]})
199
+
200
+ return OpenAICompatibleWorldSimulator(
201
+ ConnectorConfig(
202
+ type="openai_compatible",
203
+ base_url="http://llm.local/v1",
204
+ model="test-model",
205
+ max_parallel_npc_calls=4,
206
+ ),
207
+ fallback=DeterministicWorldSimulator(),
208
+ chat_completer=fake_chat_completer,
209
+ )
210
+
211
+
212
+ def _ledger_test_god_console() -> GodConsole:
213
+ def fake_chat_completer(_: dict[str, Any]) -> dict[str, Any]:
214
+ return {
215
+ "choices": [
216
+ {
217
+ "message": {
218
+ "content": "The omen is recorded.",
219
+ "tool_calls": [],
220
+ }
221
+ }
222
+ ]
223
+ }
224
+
225
+ return GodConsole(
226
+ ConnectorConfig(
227
+ type="openai_compatible",
228
+ base_url="http://llm.local/v1",
229
+ model="god-test-model",
230
+ ),
231
+ chat_completer=fake_chat_completer,
232
+ )
233
+
234
+
235
+ def _assert_survival_payload_has_no_dead_targets(
236
+ payload: dict[str, Any],
237
+ world: WorldState,
238
+ dead_ids: set[str],
239
+ ) -> None:
240
+ assert payload["npc_id"] not in dead_ids
241
+ dead_names = {
242
+ npc.name.lower()
243
+ for npc in world.npcs
244
+ if npc.id in dead_ids
245
+ }
246
+ for field in ("nearby_threats", "nearby_allies"):
247
+ for item in payload[field]:
248
+ assert item.get("id") not in dead_ids
249
+ assert item.get("npc_id") not in dead_ids
250
+ for house in payload["houses_with_free_capacity"]:
251
+ assert not (set(house.get("occupants", [])) & dead_ids)
252
+ active_directive = payload.get("active_directive")
253
+ if active_directive:
254
+ text = str(active_directive.get("text", "")).lower()
255
+ assert not any(dead_id.lower() in text for dead_id in dead_ids)
256
+ assert not any(name in text for name in dead_names)
257
+
258
+ def _assert_world_live_registries_have_no_dead_targets(
259
+ world: WorldState,
260
+ dead_ids: set[str],
261
+ ) -> None:
262
+ for house in world.houses:
263
+ assert not (set(house.occupant_ids) & dead_ids)
264
+ assert not (set(house.owner_ids) & dead_ids)
265
+ for beast in world.beasts:
266
+ assert beast.target_npc_id not in dead_ids
267
+ for npc in world.living_npcs():
268
+ assert npc.focus_target_id not in dead_ids
269
+ assert npc.help_target_id not in dead_ids
270
+ if npc.god_directive:
271
+ lowered = npc.god_directive.lower()
272
+ dead_names = [
273
+ dead.name.lower()
274
+ for dead in world.npcs
275
+ if dead.id in dead_ids
276
+ ]
277
+ assert not any(dead_id.lower() in lowered for dead_id in dead_ids)
278
+ assert not any(name in lowered for name in dead_names)
279
+
280
+
281
+ def _assert_overseer_context_has_no_dead_targets(
282
+ context: dict[str, Any],
283
+ dead_ids: set[str],
284
+ ) -> None:
285
+ assert not ({npc["id"] for npc in context["npcs"]} & dead_ids)
286
+ for house in context["houses"]:
287
+ assert not (set(house["occupants"]) & dead_ids)
288
+ for beast in context["beasts"]:
289
+ assert beast["target_npc_id"] not in dead_ids
290
+ for threat in context["current_threats"]:
291
+ assert threat.get("npc_id") not in dead_ids
292
+ assert threat.get("target_npc_id") not in dead_ids
293
+
294
+
295
+ def _survival_world(*, npc_count: int) -> WorldState:
296
+ return create_world(_config(npc_count=npc_count, survival=True))
297
+
298
+
299
+ def _world(
300
+ npcs: list[Npc],
301
+ *,
302
+ houses: list[House] | None = None,
303
+ beasts: list[Beast] | None = None,
304
+ tick: int = 0,
305
+ ) -> WorldState:
306
+ return WorldState(
307
+ tick=tick,
308
+ seed=42,
309
+ terrain=Terrain(kind="plain_green", width=80, depth=80),
310
+ npcs=npcs,
311
+ houses=houses or [],
312
+ beasts=beasts or [],
313
+ )
314
+
315
+
316
+ def _npc(
317
+ npc_id: str,
318
+ name: str,
319
+ *,
320
+ x: float = 0.0,
321
+ z: float = 0.0,
322
+ **state: Any,
323
+ ) -> Npc:
324
+ return Npc(
325
+ id=npc_id,
326
+ name=name,
327
+ role=str(state.pop("role", "gatherer")),
328
+ position=Vec3(x=x, y=0.0, z=z),
329
+ **state,
330
+ )
331
+
332
+
333
+ def _config(*, npc_count: int, survival: bool) -> GameConfig:
334
+ return GameConfig(
335
+ world=WorldConfig(width=80, depth=80, terrain="plain_green", seed=42, survival=survival),
336
+ npcs=NpcConfig(count=npc_count),
337
+ simulation=SimulationConfig(tick_ms=500),
338
+ server=ServerConfig(host="127.0.0.1", port=8000),
339
+ connector=ConnectorConfig(type="deterministic"),
340
+ )
341
+
342
+
343
+ def _tool_response(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
344
+ return {
345
+ "choices": [
346
+ {
347
+ "message": {
348
+ "tool_calls": [
349
+ {
350
+ "type": "function",
351
+ "function": {
352
+ "name": name,
353
+ "arguments": json.dumps(arguments),
354
+ },
355
+ }
356
+ ]
357
+ }
358
+ }
359
+ ]
360
+ }
tests/test_survival_loop.py CHANGED
@@ -357,7 +357,8 @@ def test_llm_connector_drives_survival_actions() -> None:
357
  assert captured # the compact survival prompt was built and sent
358
  # Every captured prompt is the compact survival shape, not the social payload.
359
  assert all("suggested_actions" in payload and "goal" in payload for payload in captured)
360
- assert all("status" in payload and "inventory" in payload for payload in captured)
 
361
  assert "openai_compatible" in world.last_tick_source
362
 
363
 
 
357
  assert captured # the compact survival prompt was built and sent
358
  # Every captured prompt is the compact survival shape, not the social payload.
359
  assert all("suggested_actions" in payload and "goal" in payload for payload in captured)
360
+ assert all("own_state" in payload and "inventory" in payload["own_state"] for payload in captured)
361
+ assert all("allowed_actions" in payload and "behavior_rules" in payload for payload in captured)
362
  assert "openai_compatible" in world.last_tick_source
363
 
364