## Phase 83: NPC Emergent Agency & Living World Evolution

**Purpose:** Make NPCs genuinely autonomous agents that form their own goals,
make multi-step plans, execute them over days and weeks of game time, cooperate
with other NPCs, and surprise the player with decisions that emerge from
personality + memory + world state. Simultaneously, make cities feel alive by
generating furnished building interiors, simulating urban growth and decay over
time, and modeling infrastructure systems that affect gameplay. This phase
transforms the Maya world from a stage set into a living ecosystem where the
player is one actor among thousands of autonomous agents.

**Reference Proposal:** `docs/proposals/LIVING_WORLD_NPC_SOTA_PROPOSAL.md`

**Scope:** Rust crates for the planning system, reflection engine, emergent goal
generator, multi-NPC cooperation, building interior generation, and
infrastructure simulation. TypeScript libraries for planning orchestration,
cooperation negotiation, urban evolution management, and voice-driven narrative
integration. Builds on Phase 81 cognitive core (SLM inference for planning),
Phase 79.24 (needs/personality/emotions/memory), Phase 79.25 (relationships),
Phase 79.26 (occupations), Phase 79.27 (city infrastructure), Phase 79.28
(economy), Phase 79.34 (information propagation).

**Technology:**

- **Rust crates** (in `libs/maya/engine-core/crates/`): `maya-npc-planning`
  (hierarchical goal/plan system), `maya-npc-reflection` (insight generation),
  `maya-npc-cooperation` (multi-agent coordination), `maya-interior-gen`
  (procedural building interiors), `maya-urban-evolution` (city growth/decay),
  `maya-infrastructure` (power/water/road systems)
- **TypeScript libraries** (in `libs/maya/`): `npc-agency-orchestrator`
  (planning prompt management), `npc-cooperation-negotiation` (NPC-NPC deal
  making), `urban-evolution-manager` (city change scheduling), `voice-narrative`
  (voice-driven emergent story)
- **Integration targets**: Phase 81 (SLM inference), Phase 79.24-36 (NPC life
  systems), Phase 79.27 (city infrastructure), Phase 82 (voice dialogue for
  narrative)

---

### 83.1 Autonomous Planning System — Multi-Horizon Goals (Rust + TypeScript)

Each Tier 0/1 NPC generates and maintains plans at four time horizons: long-term
goals (months/years), monthly plans, weekly plans, and daily schedules. Plans
are revised reactively when circumstances change. Inspired by Stanford
Generative Agents' planning architecture, adapted for real-time game
performance.

#### 83.1.1 Goal Generation

- [x] **83.1.1.1** Create `maya-npc-planning` Rust crate with hierarchical plan
      data structures, ECS components, and scheduling integration
- [x] **83.1.1.2** Implement long-term goal generation — on NPC creation, SLM
      generates 1-3 life goals from personality facets + values + life stage +
      occupation + culture. Examples: "Master blacksmithing" (high Craftsmanship
      value), "Accumulate wealth" (high Greed), "Avenge brother" (Revenge
      thought + high Bravery), "Start a family" (high Family value)
- [x] **83.1.1.3** Create goal persistence and tracking — goals stored as
      structured records: description, motivation (personality source), progress
      metric (0-100%), subgoals, deadline (if any), priority
- [x] **83.1.1.4** Implement goal priority scoring —
      `priority =     personality_alignment × emotional_urgency × feasibility × recency_of_     progress`
      — highest-priority goal drives monthly planning
- [x] **83.1.1.5** Create goal abandonment conditions — goal abandoned when:
      feasibility drops below threshold (workshop destroyed, ally died),
      personality drift makes goal irrelevant, or a higher-priority goal
      conflicts. Abandoned goals generate sadness/frustration thoughts.
- [x] **83.1.1.6** Implement goal completion consequences — completing a major
      goal generates strong positive memory, personality reinforcement
      (successful craftsman becomes more patient), and triggers new goal
      generation
- [x] **83.1.1.7** Create goal conflict resolution — when two goals conflict
      (e.g., "accumulate wealth" vs "help the poor"), NPC resolves based on
      personality weights. High internal conflict generates stress thoughts.
- [x] **83.1.1.8** Implement goal visibility to player — through conversation
      (Phase 82.5), NPCs reveal their goals when asked or when conversation
      naturally leads there ("I've always dreamed of opening my own shop")

#### 83.1.2 Hierarchical Planning

- [x] **83.1.2.1** Implement monthly plan generation — SLM decomposes current
      priority goal into monthly milestones: "This month: complete 3 masterwork
      swords, save 50 gold, approach merchant guild about membership"
- [x] **83.1.2.2** Create weekly plan generation — SLM decomposes monthly plan
      into weekly tasks considering: available resources, social calendar,
      weather forecast, known upcoming events, occupation schedule
- [x] **83.1.2.3** Implement daily schedule generation — each morning (or dawn
      game event), SLM generates hour-by-hour schedule: "6am wake, 6:30 forge,
      12pm lunch at tavern with [friend], 1pm buy steel from traveling merchant,
      2pm forge, 6pm home, 8pm tavern for socializing"
- [x] **83.1.2.4** Create schedule template library — common daily templates for
      each occupation (farmer, guard, merchant, etc.) that the SLM customizes
      rather than generating from scratch, reducing inference cost
- [x] **83.1.2.5** Implement plan caching — generated plans stored in NPC state.
      SLM is NOT queried every tick for planning. Plans persist until
      invalidated by events or time progression.
- [x] **83.1.2.6** Create Tier 2 schedule fallback — Tier 2 NPCs (personality NN
      only) follow pre-generated schedule templates without SLM customization,
      parameterized by occupation and personality archetype
- [x] **83.1.2.7** Implement plan execution tracking — as NPC completes planned
      activities, update progress. Missed activities logged with reason (was
      interrupted, path blocked, need was critical).
- [x] **83.1.2.8** Create opportunistic plan revision — when an unexpected
      opportunity arises (player offers quest, friend invites to event, merchant
      has rare item), SLM evaluates whether to revise current plan to seize
      opportunity vs stick to plan (personality-dependent: spontaneous NPCs
      revise more readily)

#### 83.1.3 Reactive Replanning

- [x] **83.1.3.1** Implement plan invalidation detection — trigger replanning
      when: workplace destroyed, critical resource unavailable, NPC injured,
      extreme weather, combat erupts, critical need spikes, social obligation
      arises
- [x] **83.1.3.2** Create emergency replanning — when plan is invalidated, SLM
      generates a replacement plan for the remainder of the current day,
      incorporating new circumstances. Priority: address the disruption first,
      then resume modified plan.
- [x] **83.1.3.3** Implement frustration accumulation — repeated plan failures
      generate negative thoughts ("Nothing is going right") that lower mood
      (Phase 79.24.3) and eventually trigger goal reassessment
- [x] **83.1.3.4** Create resilient planning — personality trait Perseverance
      determines how many plan failures before goal abandonment. High
      Perseverance NPCs try alternative approaches. Low Perseverance NPCs give
      up quickly.
- [x] **83.1.3.5** Implement player-caused disruption — when the player destroys
      an NPC's workplace, kills their friend, or otherwise disrupts their plans,
      the NPC's replanning explicitly incorporates the player as a causal agent,
      affecting relationship and future behavior toward the player

---

### 83.2 Reflection & Insight Generation (TypeScript + Rust)

Adapted from Stanford Generative Agents: NPCs periodically synthesize high-level
insights from accumulated experiences, building a hierarchical memory that moves
from raw observations to beliefs and worldviews.

#### 83.2.1 Reflection Engine

- [x] **83.2.1.1** Create `maya-npc-reflection` integration in both Rust
      (trigger detection, memory scoring) and TypeScript (SLM reflection
      prompts)
- [x] **83.2.1.2** Implement reflection trigger — track cumulative importance of
      new memories since last reflection. When sum exceeds configurable
      threshold (default 150), schedule reflection task.
- [x] **83.2.1.3** Create question generation — SLM generates 3-5 high-level
      questions about recent experiences: "What is my relationship with [NPC]?",
      "What pattern do I see in recent events?", "What have I learned about
      [topic]?"
- [x] **83.2.1.4** Implement memory retrieval for reflection — for each
      generated question, retrieve top-10 most relevant memories using the
      standard retrieval function (recency × importance × relevance)
- [x] **83.2.1.5** Create insight synthesis — SLM generates high-level insights
      from retrieved memories: "The player has been consistently helpful — I
      trust them", "The market prices have been rising — I should stockpile
      grain", "My neighbor has been acting suspicious — I should be cautious"
- [x] **83.2.1.6** Implement insight storage — insights stored back into memory
      stream at high importance (7-9), tagged as type:insight. These become
      retrievable for future decisions, creating a hierarchy: observations →
      insights → beliefs.
- [x] **83.2.1.7** Create belief formation — when multiple insights converge on
      the same topic, SLM synthesizes a belief: "I believe the player is
      trustworthy" or "I believe the kingdom is heading for war". Beliefs are
      highest-importance memories (9-10).
- [x] **83.2.1.8** Implement personality drift from reflection — strong insights
      and beliefs can slowly modify personality facets (configurable rate,
      default ±1 per reflection): traumatic insights increase Neuroticism,
      positive social insights increase Agreeableness, etc.
- [x] **83.2.1.9** Create reflection rate limiting — maximum one reflection per
      NPC per game-day, preventing excessive SLM usage on NPCs with many
      high-importance experiences
- [x] **83.2.1.10** Implement reflection quality evaluation — compare NPC
      insights against ground truth game state to verify insights are reasonable
      (NPC shouldn't believe "the kingdom is peaceful" during an active war)
- [x] **83.2.1.11** Create reflection visualization — debug panel showing NPC's
      reflection hierarchy: raw memories → insights → beliefs, with connections
      showing which memories produced which insights
- [x] **83.2.1.12** Implement cross-NPC insight sharing — NPCs who have deep
      conversations (Phase 79.31) can share insights, allowing beliefs to
      propagate through social networks beyond raw gossip

---

### 83.3 Emergent Goal Generation from Personality + Memory (TypeScript)

NPCs generate new goals dynamically based on the interaction of their
personality, emotional state, accumulated experiences, and world circumstances —
producing genuinely emergent narrative that isn't designer-authored.

#### 83.3.1 Dynamic Goal Engine

- [x] **83.3.1.1** Create `libs/maya/npc-agency-orchestrator/` TypeScript
      library with goal generation, evaluation, and lifecycle management
- [x] **83.3.1.2** Implement personality-driven goal templates — 30+ goal
      templates activated by personality/value combinations: high Greed + low
      Ethics → "steal from wealthy merchant", high Knowledge + discovered ruins
      → "explore and study ruins", Revenge thought + sufficient Bravery →
      "confront my brother's killer"
- [x] **83.3.1.3** Create circumstance-triggered goals — world events generate
      goal opportunities: famine → "hoard food" (selfish) or "organize food
      distribution" (altruistic), depending on personality; new ruler → "curry
      favor" (ambitious) or "resist tyranny" (freedom-loving)
- [x] **83.3.1.4** Implement need-driven emergency goals — when a need becomes
      critically low (hunger <10%, safety <10%), emergency goals override
      long-term plans: "find food immediately", "flee to safety", "find shelter"
- [x] **83.3.1.5** Create social-observation goals — observing other NPCs'
      success triggers envy-driven goals in NPCs with relevant personality:
      seeing wealthy merchant → "I want to be that successful" (high Ambition);
      seeing happy family → "I want a family too" (high Family value)
- [x] **83.3.1.6** Implement player-interaction goals — after significant player
      interactions (Phase 82.5 conversation, quest completion, betrayal), NPC
      may generate player-related goals: "repay the player's kindness", "avoid
      the player who threatened me", "seek the player's help with my problem"
- [x] **83.3.1.7** Create creative goals — NPCs with high Art or Craftsmanship
      values periodically generate creative goals: "compose a song about recent
      events", "create a masterwork sword", "paint the sunset from the tower"
- [x] **83.3.1.8** Implement leadership goals — NPCs with high Power value and
      sufficient Social standing may generate political goals: "become guild
      leader", "run for council seat", "organize resistance" (connects to Phase
      79.36)
- [x] **83.3.1.9** Create migration goals — NPCs in poor conditions (low job
      satisfaction, dangerous area, social isolation) may decide to relocate to
      another settlement, creating visible migration patterns
- [x] **83.3.1.10** Implement criminal goals — NPCs with low Responsibility +
      high need deficits may generate criminal goals: theft, smuggling,
      extortion. Crime type matches personality (clever → fraud, aggressive →
      robbery). Connects to Phase 79.29 justice system.
- [x] **83.3.1.11** Create romantic goals — NPCs with high Social need and
      compatible personality traits generate courtship goals toward specific
      NPCs, driving the Phase 79.25 romantic interaction chain
- [x] **83.3.1.12** Implement revenge goals — when an NPC is wronged (attacked,
      robbed, family member killed, betrayed), generate revenge goal with
      intensity proportional to wrong severity × Anger trait. May plan elaborate
      revenge over weeks of game time.
- [x] **83.3.1.13** Create goal coherence validation — verify generated goals
      don't contradict NPC's existing beliefs, personality, or physical
      capabilities. SLM self-checks: "Would this character really do this?"
- [x] **83.3.1.14** Implement emergent narrative logging — all goal generations,
      plan executions, and outcomes logged in a world narrative stream that
      designers can review to understand emergent stories
- [x] **83.3.1.15** Create emergent goal integration tests — verify that
      personality + circumstance combinations produce expected goal types, that
      goals lead to visible NPC behavior changes, and that the overall
      distribution of goals across a population feels natural

---

### 83.4 Multi-NPC Emergent Cooperation (TypeScript + Rust)

Groups of NPCs independently deciding to cooperate based on shared goals,
compatible personalities, and mutual trust. Produces emergent gangs, study
groups, trading partnerships, resistance movements, and expedition parties
without designer scripting.

#### 83.4.1 Cooperation Engine

- [x] **83.4.1.1** Create `maya-npc-cooperation` Rust crate for cooperation
      detection and group management, plus
      `libs/maya/npc-cooperation-     negotiation/` TypeScript library for
      SLM-driven negotiation
- [x] **83.4.1.2** Implement shared goal detection — periodically scan nearby
      NPC pairs/groups for compatible active goals: two NPCs both wanting to
      "explore the ruins", three merchants wanting to "organize trade route
      protection", five farmers wanting to "petition for lower taxes"
- [x] **83.4.1.3** Create cooperation proposal — when shared goal detected, the
      more Extroverted/dominant NPC initiates proposal via NPC-NPC conversation
      (Phase 79.31): "We both want to explore those ruins — we should go
      together."
- [x] **83.4.1.4** Implement cooperation acceptance model — receiving NPC
      evaluates proposal based on: trust in proposer (Phase 79.25 relationship),
      personality compatibility, risk assessment, and own goal priority. High
      Trust + high Agreeableness → likely accept. Low Trust → likely refuse.
- [x] **83.4.1.5** Create emergent group formation — accepted cooperation forms
      a temporary group with shared objective, coordinated planning, and role
      assignment based on skills/personality
- [x] **83.4.1.6** Implement group role assignment — SLM assigns roles based on
      capability: strongest member as guard, most knowledgeable as navigator,
      most charismatic as spokesperson, most cautious as lookout
- [x] **83.4.1.7** Create group plan coordination — group members generate
      synchronized daily schedules that include group activities (expedition
      departure, meeting times, shared work shifts)
- [x] **83.4.1.8** Implement group dissolution — groups dissolve when: objective
      complete, trust breaks (member betrayal), irreconcilable personality
      conflict, or circumstances make objective impossible
- [x] **83.4.1.9** Create gang formation — criminal NPCs with complementary
      skills (pickpocket + fence + lookout) form criminal organizations with
      territory, hierarchy, and coordinated operations
- [x] **83.4.1.10** Implement resistance formation — when NPC population
      satisfaction with governance drops below threshold (Phase 79.36) and
      sufficient NPCs have Freedom + Bravery values, resistance groups form
      organically through social network connections
- [x] **83.4.1.11** Create merchant coalition — merchants with shared route
      interests form trading companies, pooling resources for caravan protection
      and negotiating power
- [x] **83.4.1.12** Implement scholarly cooperation — NPCs with Knowledge values
      form study groups around discovered artifacts, ruins, or mysterious
      events, sharing insights and pooling research
- [x] **83.4.1.13** Create cooperation visualization — debug tool showing active
      cooperative groups, their objectives, member roles, and coordination state
- [x] **83.4.1.14** Implement cooperation integration tests — verify that
      expected cooperation patterns emerge from personality + circumstance
      combinations across 100+ NPC populations
- [x] **83.4.1.15** Create cooperation narrative hooks — when emergent groups
      form, log events that the quest system can detect and respond to (player
      discovers a resistance movement, player encounters an expedition party,
      player disrupts a criminal gang)

---

### 83.5 Procedural Building Interiors (Rust)

When a player enters any building, the interior is procedurally generated using
shape grammar for room layout and constraint-based furnishing. Interiors reflect
the building type, occupant personality, wealth, and occupation.

#### 83.5.1 Interior Generation Pipeline

- [x] **83.5.1.1** Create `maya-interior-gen` Rust crate with shape grammar
      engine, room subdivision, furniture placement, and decoration system
- [x] **83.5.1.2** Implement building footprint analysis — receive building
      shell geometry (walls, doors, windows from exterior generation), extract
      floor area, floor count, entrance positions, and window positions
- [x] **83.5.1.3** Create room subdivision engine using space partitioning —
      BSP-tree or shape grammar rules divide floor area into rooms based on
      building type: residential (bedroom, kitchen, living, storage), commercial
      (shop floor, back room, office), public (lobby, offices, conference,
      restroom), tavern (common room, kitchen, private rooms, cellar)
- [x] **83.5.1.4** Implement room type assignment — rooms assigned types based
      on building function, with constraints: kitchen near exterior wall
      (chimney), bedroom upstairs (privacy), shop floor near entrance
      (accessibility), storage in back (security)
- [x] **83.5.1.5** Create door and corridor placement — ensure all rooms are
      reachable, place internal doors at room boundaries, create corridors for
      multi-room floors, ensure door positions don't conflict with furniture
      placement zones
- [x] **83.5.1.6** Implement furniture placement using constraint solving — each
      room type has a furniture vocabulary (bedroom: bed, wardrobe, nightstand,
      chest; kitchen: hearth, table, shelves, water barrel). Placement
      constraints: bed against wall, table accessible from 3 sides, clear path
      from door to all functional items.
- [x] **83.5.1.7** Create wealth-driven quality scaling — NPC income (from Phase
      79.26 occupation) determines furniture quality (crude/standard/
      fine/ornate), repair state (pristine to damaged), and decoration density
      (bare walls to paintings and tapestries)
- [x] **83.5.1.8** Implement occupation-driven decoration — blacksmith home:
      small anvil, tool rack, metal samples. Scholar home: bookshelves, writing
      desk, ink stains, scroll cases. Guard home: weapon rack, armor stand,
      uniform. Merchant home: displayed samples, ledger book, strongbox.
- [x] **83.5.1.9** Create personality-driven personalization — messy personality
      (low Orderliness) → items on floor, unmade bed, scattered papers. Artistic
      personality → paintings, sculptures, decorative items. Devout → shrine,
      religious texts. Nature-loving → potted plants, pressed flowers.
- [x] **83.5.1.10** Implement interior persistence — once generated, interior
      layout and item positions saved to world state. NPC activities modify
      interior over time (food appears on table at meal time, bed is unmade
      after sleeping, items accumulate or are cleaned based on personality).
- [x] **83.5.1.11** Create interior damage system — combat or disasters inside
      buildings cause visible damage: broken furniture, scorch marks, collapsed
      walls. Damage persists and is repaired over time by owner NPC.
- [x] **83.5.1.12** Implement interior LOD — full detail when player is inside,
      simplified when visible through windows from outside, nothing generated
      for buildings player hasn't entered (generate on first entry, persist
      thereafter)
- [x] **83.5.1.13** Create multi-occupant interiors — shared buildings (taverns,
      barracks, tenements) have common areas reflecting aggregate use plus
      private spaces reflecting individual occupants
- [x] **83.5.1.14** Implement interior generation performance — target <200ms
      for a standard residential building (4-6 rooms), <500ms for a large
      commercial building (10-15 rooms), running on a background thread
- [x] **83.5.1.15** Create interior generation integration tests — verify
      furniture placement constraints, room connectivity, personality
      reflection, and visual quality for all building types

---

### 83.6 Urban Evolution — City Growth, Decay & Change (TypeScript + Rust)

Cities change visibly over gameplay time: new buildings constructed, abandoned
areas decay, prosperous districts expand, and disaster recovery transforms
neighborhoods.

#### 83.6.1 City Change Simulation

- [x] **83.6.1.1** Create `maya-urban-evolution` Rust crate for structural
      change simulation and `libs/maya/urban-evolution-manager/` TypeScript
      library for change scheduling and event management
- [x] **83.6.1.2** Implement construction system — new buildings appear through
      a visible multi-phase process: empty lot → foundation (dirt, stakes) →
      framework (timber/stone skeleton) → walls → roof → finishing (windows,
      doors, paint) → occupancy. Total duration: 5-30 game days depending on
      building size.
- [x] **83.6.1.3** Create construction crew NPC behavior — construction workers
      assigned to sites (from Phase 79.26 occupation system), visibly perform
      work actions (hammering, carrying materials, climbing scaffolding) during
      work hours. Progress advances only when workers are present.
- [x] **83.6.1.4** Implement construction demand model — new construction
      triggered by: population growth exceeding housing capacity, new business
      opportunities (trade route opens), government investment, or NPC
      entrepreneurship goals (Phase 83.3)
- [x] **83.6.1.5** Create building demolition — condemned buildings demolished
      before new construction. Demolition crew removes structure over 2-5 game
      days. Rubble hauled away. Empty lot ready for new construction.
- [x] **83.6.1.6** Implement gentrification dynamics — when a district's average
      wealth increases (wealthy NPCs moving in, luxury shops opening), adjacent
      low-wealth buildings are gradually replaced: old structures demolished →
      new higher-quality buildings → displaced residents move to cheaper
      districts
- [x] **83.6.1.7** Create decay system — abandoned buildings (owner died/left,
      business failed) deteriorate over time: first week: dusty, cobwebs. First
      month: broken windows, minor roof damage. First season: structural
      concerns, graffiti, squatters. First year: partial collapse, vegetation
      overgrowth.
- [x] **83.6.1.8** Implement repair and renovation — building owners commission
      repairs when damage exceeds threshold. Repair crews fix damage over 1-5
      game days. Renovation upgrades building quality when owner prospers.
- [x] **83.6.1.9** Create disaster recovery — after fire, war, or natural
      disaster: damaged zone enters cleanup phase (rubble removal) → rebuilding
      phase (construction from foundations) → recovery phase (new occupants).
      Recovery time depends on economic health and available labor.
- [x] **83.6.1.10** Implement seasonal visual changes — facades change with
      seasons: flower boxes in spring, open windows in summer, harvest
      decorations in autumn, snow accumulation in winter. Festival periods add
      banners and decorations.
- [x] **83.6.1.11** Create district evolution tracking — record district wealth
      index, population density, building quality distribution, and crime rate
      over time. Detectable trends drive NPC behavior (NPCs avoid declining
      areas, seek improving areas).
- [x] **83.6.1.12** Implement player impact on urban evolution — player actions
      affect city development: destroying buildings accelerates decay, investing
      gold triggers construction, completing quests improves district safety
      attracting new residents
- [x] **83.6.1.13** Create urban evolution timeline — time-lapse visualization
      showing city changes over game months, viewable from a city overlook or
      in-game map
- [x] **83.6.1.14** Implement urban evolution performance — all change
      simulation runs on background thread, <1ms per game-day tick for entire
      city, visual changes applied incrementally across frames
- [x] **83.6.1.15** Create urban evolution integration tests — simulate 1 game
      year of city evolution, verify construction completion, decay progression,
      gentrification patterns, and disaster recovery timelines

---

### 83.7 Infrastructure Systems — Power, Water, Roads (Rust)

Functional infrastructure that affects NPC daily life and gameplay. Power
outages darken streets, water shortages affect NPC needs, and road damage slows
traffic.

#### 83.7.1 Infrastructure Simulation

- [x] **83.7.1.1** Create `maya-infrastructure` Rust crate with network graph
      simulation for power, water, and road systems
- [x] **83.7.1.2** Implement power network — generators (windmill, waterwheel,
      coal furnace, magical source) connected to consumers (street lights,
      forges, water pumps, mechanical devices) via distribution lines. Power
      balance: total generation must meet demand.
- [x] **83.7.1.3** Create power outage mechanics — when generation < demand:
      non-essential consumers shed first (street lights → decorative → heating).
      Generator failure (fuel exhaustion, storm damage) cascades to connected
      consumers. Dark streets at night increase crime rate.
- [x] **83.7.1.4** Implement water network — sources (wells, rivers, aqueducts,
      cisterns) connected to consumers (households, farms, public fountains,
      breweries) via pipe/channel network. Water flow simulation: upstream
      damage affects downstream consumers.
- [x] **83.7.1.5** Create water shortage mechanics — drought or infrastructure
      damage reduces water supply. Affected NPCs cannot satisfy Hygiene need as
      easily, crops grow slower, fire response is hampered (no water pressure).
      NPC complaints and political pressure mount.
- [x] **83.7.1.6** Implement road quality system — road segments have condition
      rating (0-100) that degrades with traffic volume and weather (rain,
      freeze-thaw). Potholes develop, slowing traffic (Phase 79.27). Road repair
      crews restore condition over 1-3 game days per segment.
- [x] **83.7.1.7** Create infrastructure worker NPCs — specialized occupations
      (Phase 79.26): pump operators, lamplighters, road crews, aqueduct
      inspectors. They perform visible maintenance routines. If these NPCs
      die/leave, infrastructure degrades faster.
- [x] **83.7.1.8** Implement infrastructure investment — city governance (Phase
      79.36) allocates budget to infrastructure. Higher investment → better
      maintenance, capacity upgrades, new connections. Lower investment →
      accelerated degradation.
- [x] **83.7.1.9** Create sabotage mechanics — player or hostile NPCs can damage
      infrastructure (poison well, destroy bridge, sabotage generator) causing
      cascading effects on dependent systems and NPC life
- [x] **83.7.1.10** Implement infrastructure visualization — overlay map showing
      power network, water network, and road condition with color-coded status
      (green/yellow/red)
- [x] **83.7.1.11** Create infrastructure simulation performance — entire city
      infrastructure simulated in <0.5ms per game-hour tick, with event-driven
      updates for damage/repair between ticks
- [x] **83.7.1.12** Implement sewage/waste system — drainage networks connected
      to population centers. Overflow or damage increases disease spread risk in
      affected districts, lowers district desirability score, generates NPC
      complaints, and triggers political pressure for investment
- [x] **83.7.1.13** Create weather-driven infrastructure damage — storms damage
      roofs triggering repair waves, flooding damages low-lying district
      infrastructure and roads, drought strains water network capacity
      triggering construction of new wells/cisterns
- [x] **83.7.1.14** Implement infrastructure integration tests — simulate
      infrastructure scenarios: power outage → dark streets → crime spike, water
      shortage → crop failure → food price rise → unrest, sewage overflow →
      disease → hospital demand

---

### 83.8 NPC Lifecycle & Skill Progression (TypeScript + Rust)

Birth, aging, death, inheritance, and skill growth over time — the demographic
engine that makes the NPC population feel like a living society across
generations.

#### 83.8.1 Demographic Lifecycle

- [x] **83.8.1.1** Implement NPC aging system — NPCs age in game time with life
      stages (child, adolescent, adult, elder) affecting available occupations,
      physical capabilities, personality maturity, and social roles
- [x] **83.8.1.2** Create NPC birth — married NPC pairs with Family values may
      produce children. Children inherit personality facets from parents with
      random variation (±10 per facet). Children grow over game time.
- [x] **83.8.1.3** Implement NPC death — natural death at end of lifespan
      (modified by health, occupation danger, lifestyle), violent death from
      combat/crime/accident. Death triggers grief in connected NPCs, funeral
      events, and estate handling.
- [x] **83.8.1.4** Create inheritance system — on NPC death, property, wealth,
      and business ownership transfer to designated heir (spouse → eldest child
      → closest relative → faction). Contested inheritance generates conflict.
- [x] **83.8.1.5** Implement population demographics tracking — per-settlement
      birth rate, death rate, age distribution, migration balance. Visible
      population trends affect city evolution (Phase 83.6) and economy (Phase
      79.28).
- [x] **83.8.1.6** Create generational memory — children remember stories told
      by parents/elders about world history (Phase 79.33), creating cultural
      continuity. Family feuds and alliances persist across generations.

#### 83.8.2 Skill & Knowledge Progression

- [x] **83.8.2.1** Implement skill level system — each NPC has skill levels
      (0-100) for their occupation and secondary skills. Skills improve through
      practice: working at forge increases Blacksmithing, combat increases
      Martial skill. Rate modulated by personality (high Perseverance → faster).
- [x] **83.8.2.2** Create knowledge acquisition — NPCs learn new information
      through experience, conversation, and study. An NPC who studies at a
      library gains Knowledge. An NPC who travels to a new region gains
      Geographic knowledge. Knowledge feeds into planning and goal generation.
- [x] **83.8.2.3** Implement mentorship mechanics — master-apprentice
      relationships where experienced NPCs teach skills to younger ones.
      Teaching quality depends on master's skill level and Patience trait.
      Apprenticeship completion triggers career advancement.
- [x] **83.8.2.4** Create skill-driven goal evolution — as NPC gains skill, new
      goals become available: journeyman blacksmith can aspire to master,
      skilled merchant can aspire to guild leadership. Skill gates prevent
      unrealistic goal pursuit.
- [x] **83.8.2.5** Implement world history integration — NPC reflection (Phase
      83.2) can incorporate knowledge of Phase 79.33 world history: NPCs in
      areas with historical significance form beliefs about their heritage,
      cultural identity influences goal generation, and historical events inform
      NPC caution (settlement near historical battle site → NPCs value defense
      more)

---

### 83.9 Voice-Driven Emergent Narrative Integration (TypeScript)

Connects Phase 82 voice dialogue to emergent NPC agency: what players SAY to
NPCs has real consequences that ripple through the NPC agency systems, producing
emergent stories driven by player speech.

#### 83.9.1 Narrative Consequence Engine

- [x] **83.9.1.1** Create `libs/maya/voice-narrative/` TypeScript library with
      consequence detection, propagation, and narrative arc tracking
- [x] **83.9.1.2** Implement lie detection and propagation — when player tells
      an NPC a lie (detected by SLM analyzing player statement against known
      world state), the lie enters NPC's memory as believed truth. NPC may
      gossip the lie (Phase 79.34), spreading misinformation through the social
      network. Eventually, NPCs who know the truth may expose the lie.
- [x] **83.9.1.3** Create promise tracking — when player makes a promise to an
      NPC ("I'll bring you the medicine by tomorrow"), system tracks promise
      with deadline. NPC expects fulfillment. Kept promises → trust increase.
      Broken promises → trust decrease, NPC remembers and references in future
      conversations.
- [x] **83.9.1.4** Implement persuasion consequences — when player convinces an
      NPC to change behavior (Phase 82.6): change career (→ Phase 79.26
      occupation change), join a cause (→ faction alignment change), move to new
      location (→ migration), the NPC actually does it with visible consequences
- [x] **83.9.1.5** Create information gift consequences — telling an NPC
      valuable information (location of treasure, enemy plans, market
      opportunity) enters their memory and may change their goals (Phase 83.3):
      NPC may mount expedition, change defensive strategy, or adjust business
      plans
- [x] **83.9.1.6** Implement emotional impact — words have weight: comforting a
      grieving NPC reduces their sadness, insulting a proud NPC generates
      lasting resentment, encouraging a struggling NPC may prevent them from
      abandoning their goal
- [x] **83.9.1.7** Create rumor seeding — player can deliberately spread
      information through conversation, knowing it will propagate via gossip
      network. Strategic rumor-planting as a game mechanic (spread false
      intelligence about enemy movements, create market panics for profit)
- [x] **83.9.1.8** Implement reputation through word — NPCs who witness or hear
      about player's conversational behavior form opinions: "The player lies
      often" (detected broken promises spread), "The player is generous with
      information", "The player intimidated my friend"
- [x] **83.9.1.9** Create narrative arc detection — system identifies when a
      sequence of voice-driven events forms a coherent story arc (player
      recruited allies through conversation → trained them → led them against
      threat) and logs it as a notable world event
- [x] **83.9.1.10** Implement voice-narrative integration tests — scripted
      scenarios verifying: lie propagation through gossip network, promise
      tracking with deadline enforcement, persuasion-driven behavior change
      persistence, and emotional impact on NPC goal modification

---

### Phase 83 Summary — NPC Emergent Agency & Living World Evolution

**New Systems:**

| System Area                   | Section | Tasks   |
| ----------------------------- | ------- | ------- |
| Goal Generation               | 83.1.1  | 8       |
| Hierarchical Planning         | 83.1.2  | 8       |
| Reactive Replanning           | 83.1.3  | 5       |
| Reflection Engine             | 83.2.1  | 12      |
| Dynamic Goal Engine           | 83.3.1  | 15      |
| Cooperation Engine            | 83.4.1  | 15      |
| Interior Generation           | 83.5.1  | 15      |
| City Change Simulation        | 83.6.1  | 15      |
| Infrastructure Simulation     | 83.7.1  | 14      |
| Demographic Lifecycle         | 83.8.1  | 6       |
| Skill & Knowledge Progression | 83.8.2  | 5       |
| Narrative Consequence Engine  | 83.9.1  | 10      |
| **TOTAL Phase 83**            |         | **128** |

---

### Living World After Phase 83

| Capability         | Before Phase 83              | After Phase 83                                          |
| ------------------ | ---------------------------- | ------------------------------------------------------- |
| NPC goals          | Designer-authored quests     | Emergent goals from personality + memory                |
| NPC planning       | Daily schedule (Phase 79.24) | Multi-horizon: life goals → monthly → weekly → daily    |
| NPC reflection     | None                         | Stanford-class observation → insight → belief hierarchy |
| NPC cooperation    | Scripted teams               | Emergent gangs, study groups, coalitions, expeditions   |
| Building interiors | Empty shells or hand-built   | Procedural, personality-driven, persistent interiors    |
| City change        | Static environment           | Construction, gentrification, decay, disaster recovery  |
| Infrastructure     | Decorative                   | Functional power, water, roads affecting NPC life       |
| Voice consequences | Dialogue tree outcomes       | Real narrative ripples from every conversation          |
| Emergent narrative | None                         | Bottom-up stories from NPC agency + player voice        |

**Combined with Phase 81's cognitive core and Phase 82's voice system, Phase 83
makes the Maya world a place where NPCs have genuine inner lives with goals,
plans, memories, and beliefs — where cities grow and change around them — and
where the player's words create real consequences that ripple through a living
ecosystem of autonomous agents.**

---

### Complete System After Phases 81-83

| Dimension              | GTA 6          | Everything Else | **Oshun/Maya (81-83)**                                     |
| ---------------------- | -------------- | --------------- | ---------------------------------------------------------- |
| NPC count              | 10,000+        | ~200            | **10,000+ with cognitive LOD**                             |
| NPC cognition          | Lightweight NN | Scripted/BT     | **5-tier: statistical → NN → 2B SLM → 8B SLM → cloud LLM** |
| Voice interaction      | None           | None            | **Full natural language with any NPC**                     |
| Voice squad control    | None           | None            | **Full tactical voice control (R6/SOCOM class)**           |
| Emergent goals         | None           | None            | **Self-generated goals from personality + memory + world** |
| NPC memory             | None           | None            | **Episodic + semantic + reflective hierarchy**             |
| NPC cooperation        | None           | Scripted        | **Emergent gangs, coalitions, expeditions**                |
| Building interiors     | Hand-built     | Hand-built      | **Procedural, personality-driven, persistent**             |
| City evolution         | Static         | Static          | **Construction, decay, gentrification, disaster recovery** |
| Infrastructure         | Decorative     | Decorative      | **Functional power, water, roads**                         |
| Voice-driven narrative | None           | None            | **Words create real consequences in living world**         |
| Negotiation            | None           | Dialogue trees  | **Free-form voice persuasion, intimidation, deception**    |
