{"slug": "the-master-s-shadow", "title": "The Master's Shadow", "summary": "Master Malacor in 'The Master's Shadow' is a rule-bound autonomous AI using Ant-Colony Optimisation (ACO) to pursue players, with deterministic behavior governed by pheromone-based pathfinding and dynamic strategies based on player actions and trace levels.", "body_md": "**The Master AI — Ant-Colony Optimisation**\n\nMaster Malacor is **not** a game-over timer or an omniscient threat. He is a rule-bound autonomous agent running on the same deterministic Clockwork Dark engine as the player, subject to the **same world friction**: every action is a legal engine call (`move_to_node`\n\n, `resolve_skill_check`\n\n, `craft_item`\n\n, forage/rest), governed so he cannot cheat or hallucinate outcomes. He spends Food, Energy and Mana, is slowed by hazardous nodes, and can be outlasted if he burns resources recklessly. His edge is **better starting knowledge and stats**; the player’s counter is that this knowledge is *imperfect and corruptible*.\n\n**The ACO model**\n\nAnt-Colony Optimisation (ACO) is a swarm metaheuristic: artificial ants lay **pheromone** on good paths, pheromone **evaporates** to allow adaptation, and each next-step choice combines pheromone (τ, weight `alpha`\n\n) with a heuristic (η, weight `beta`\n\n) via seeded roulette-wheel selection. ACO gives the Master and crowds a *memory of good routes* that A* alone lacks, and adapts naturally to changing traps, trace and reputation.\n\n**Hex adaptation:** pheromone is stored per **directed edge** between cube-coordinate hexes (the 6 neighbours). Heuristic η = `1 / movement_cost`\n\n, where `movement_cost`\n\nalready folds in terrain, traps, trace and reputation. All random choices are seeded with `game_seed + state_hash`\n\n, so ACO is fully deterministic. See [World & Flow Fields](https://github.com/nihilistau/the-masters-shadow/blob/master/design/okf/world-and-flowfields.md) for the hybrid: ACO is the strategic layer that emits a temporary flow field, blended (weight ~0.7) with the global flow field; flow fields + local steering handle cheap real-time crowd movement.\n\n**Recommended parameters (per context):**\n\n**Context** |\n**ants** |\n**iters** |\n**alpha** |\n**beta** |\n**evap** |\n**Q** |\n| Master Bloodhound pursuit |\n15 |\n25 |\n1.2 |\n2.5 |\n0.08 |\n1.0 |\n| Master Architect planning |\n25 |\n40 |\n1.0 |\n2.0 |\n0.12 |\n0.8 |\n| Loyalist patrol swarms |\n10 |\n15 |\n0.8 |\n3.0 |\n0.15 |\n0.6 |\n| Rebel groups |\n12 |\n20 |\n1.0 |\n1.8 |\n0.10 |\n0.7 |\n| Monster swarms |\n8 |\n12 |\n1.5 |\n1.5 |\n0.20 |\n0.5 |\n\n**Tracking vectors**\n\nThe Master maintains an internal world model from state flags, imperfect and degrading with time/distance:\n\n-\n**Sympathy Trace** (primary). Black spells (*Drain Life*, *Shadow Step*, *Bind*, *Summon Familiar*), heavy Black ingredients (*Nightshade*, *Mandrake Root*, *Sympathy Ash*) and failed Black alchemy add trace. Trace decays ~1–3 per node moved (faster with White magic, rain, Shimmering Lake). Bands drive behaviour:\n\n**Trace** |\n**Master behaviour** |\n**Player-visible** |\n**Counters** |\n| Low (0–20) |\nNormal patrol / Architect |\nnone |\n— |\n| Med (21–50) |\nBloodhound chance ↑ |\nraven cries, scorched nodes |\nGrey masking, Decoy, weather |\n| High (51–80) |\nLocks onto path, faster |\ndead NPCs, stripped nodes on trail |\nWhite trace-purge, false trails |\n| Critical (81+) |\nAggressive pursuit, trackers |\nprojection appears, Loyalists converge |\nShadow Cloak + high Grey, sabotage |\n\n-\n**Last-known position + path history** (from Raven Familiar, Loyalist Trackers, direct sight). Grey magic — *Invisibility*, *Muffle*, *Decoy*, high *Concealment*, *Shadow Cloak* — breaks or falsifies it.\n\n-\n**Reputation & world flags** (secondary): Loyalist reputation drives patrol/trap density; bribed NPCs may feed him false intel; helping/harming key characters sets persistent readable flags.\n\n**Pursuit strategies**\n\nThe Master switches mode dynamically on trace, resources, last-known position, and predicted intent:\n\n**Bloodhound (reactive).** Trigger: medium+ trace, recent sighting, or obvious Black magic. Runs the player’s exact recent path, spends Mana on *Haste*, strips resources behind them, prioritises closing distance. Countered by *Haste*, false trails, weather (Sudden Storm doubles all costs), or leading him into monster nodes.\n**Architect (predictive).** Trigger: low trace but the player is heading to a chokepoint (Boundary Gate, Rebel Encampment, Smuggler’s Cove) or is patterned. Diverges *ahead*, lays snares, bribes guards (Gorn, Vex, Captain Thorne), sets ambushes. Countered by breaking patterns, varying routes, counter-intel (*Divination Mirror*), or sabotaging his forward assets.\n**Opportunistic / Idle.** Casts about the strongest scent when neither loud nor cleanly predictable; Idle covers forage/rest.\n\nHe can switch mid-chase if trace spikes or he loses the trail.\n\n**Learning: memory decay & protection**\n\nThe Master keeps a **separate pheromone map of the player** (observed spell chains, escape routes, alchemy habits, trap responses) that steers strategy, trap placement and spell priority. It is a **learning but fallible** memory that decays under pressure, so the player must keep adapting.\n\n**Decay** `base_rate = 0.06`\n\n(slower than player-side magical pheromone; he is disciplined). Multipliers: Ritual Clock `1.0 + stage*0.35`\n\n; player trace `1.0 + trace/120`\n\n; low Mana ×1.3; recent failed counter ×1.2; heavy recent Grey ×1.4; strong Water-Spirit reputation ×1.15; time-since-observed up to ×1.8. Capped at 0.28; floor 0.005.\n**Protection** (else Grey trivialises him): Ritual-Clock *hardening* (`1.0 − stage*0.12`\n\n, up to ~36% slower late), extra ×0.7 on recently-used patterns, importance weighting, resource-based resilience (stronger >60% Mana), and active tools — *Trace-Burn*, *Clarity Projection*, *Pheromone Anchor*, surveillance agents. Targeted *Memory Fog* he may *detect and reinforce against*, a cat-and-mouse mini-game.\n**Player disruptor — Memory Fog (Grey).** Applies a decay boost `0.18 + grey_level*0.03`\n\n(×1.5 targeted) to his player-model over 4–8 nodes (10–12 with alchemy); ~+0.5 clock at stage ≥2; recent-use penalty ×0.5 within 8 turns to stop spam.\n\nNet arc: **early** memory strong and teaching; **mid** older observations erode, he can be re-fooled; **late** desperation (clock) both accelerates his forgetting *and* hardens his prized recent counters, so he grows more brute-force and predictable — windows for skilled play.\n\n**The unified ACO loop (player + Master)**\n\nACO also drives **spell-sequence selection** for both sides. Each “ant” runs a short simulated cast chain (≤4 spells); transition probability `P = τ^alpha · η^beta · clock_pressure^gamma · reputation_mod^delta`\n\n, normalised (uniform fallback if none viable). The heuristic scores Mana efficiency, trace delta (heavy penalty for Black when trace >60–70; small reward for controlled Black when low), affinity match, alchemy synergy (potions as temporary pheromone boosters), and tactical context (near-traps favours *Haste/Shadow Step/Decoy*; low health favours *Mend/Ward*; density favours *Bind/Sleep*). Successful chains deposit pheromone, so tactics that work become reliable — but also predictable.\n\n**Ritual-Clock tuning** ramps parameters by stage: alpha 1.0→1.5, beta 2.5→3.5, evaporation 0.10→0.30, with rising Black penalty and survival bias. The **Master’s** loop uses higher alpha (1.4–1.6, leans on learned patterns), aggressive elitist reinforcement, and grows more efficient and less exploratory as the clock advances.\n\n**Phase carry-over.** [Phase 1](https://github.com/nihilistau/the-masters-shadow/blob/master/design/okf/phases.md) choices seed Phase 2 pheromone: reputation flags become initial pheromone biases; Grey progress → stronger stealth-pair pheromone and better decoys; heavy Black → higher starting trace; ritual sabotage → lower starting clock and persistent low-cost corridors.\n\n**In the build**\n\nThe design is realised, though the shipped C++ core is a **deliberately lean, deterministic subset** of the sprawling design above — not the full multi-map ACO/LLM stack.\n\n`src/ai/master_ai.hpp`\n\n/ `master_ai.cpp`\n\n— `MasterBrain`\n\n. A single scent (pheromone) map `unordered_map<Hex,float>`\n\nwith `observe_player`\n\n(deposit `kDeposit=1.0`\n\non sighting), `decay`\n\n(evaporation `kEvap=0.15`\n\n, prune <0.02), and `strongest_scent`\n\nwith a deterministic hex-order tiebreak. `decide()`\n\nimplements the strategy FSM: forage if `food<25`\n\nor `energy<30`\n\n; else **Bloodhound** if `trace≥50`\n\nor seen within 1 turn, **Architect** (interception via `a_star`\n\n3 hexes ahead toward the gate) if `trace<30`\n\nwith a fix, else **Opportunistic** on strongest scent — then steps via a flow field to the goal. `poison_scent(h, amt, steal_fix)`\n\nis the Nyxari false-trail hook that can steal his fix.\n`MasterStrategy`\n\nenum lives in `src/core/types.hpp`\n\n: `Idle, Opportunistic, Bloodhound, Architect`\n\n.\n`src/ai/pursuit_sim.cpp`\n\n— `simulate_pursuit`\n\nproves the Master is rule-bound and can *win or lose*: a seeded headless chase (greedy player vs a Master `IAgent`\n\n), used by tests and balance sweeps.\n`agent_engine/master_agent.py`\n\n— the pluggable external-agent bridge. The Master can be driven by an LLM via **LM Studio** (`lmstudio_client.py`\n\n, OpenAI-style tool calling, `/no_think`\n\n), choosing among only *legal* moves through a single `act(action, index, say)`\n\ntool — he still cannot cheat. It uses a **loaded-only** model (never force-loads) and falls back to a deterministic bloodhound `heuristic()`\n\nwhen no model is resident, the call fails, or `MS_AGENT_HEURISTIC=1`\n\n. This is the “CosySim” agent seam referenced in project history.\n\n**Note:** sources differ on decay/trace constants vs. the build. Design docs specify player-model decay `base=0.06`\n\n, evaporation ~0.08–0.30, and trace bands with a slow 1–3/node fade; the shipped `MasterBrain`\n\nuses a single scent map with fixed `kEvap=0.15`\n\n, `kDeposit=1.0`\n\n, and integer thresholds `kTraceBloodhound=50`\n\n/ `kTraceArchitect=30`\n\n. The **build values are canonical for the current implementation**; the finer per-mille/per-affinity model and the separate player-model pheromone map are **design-only / not yet in the C++ core**.\n\n**Note:** the design describes multiple pheromone maps, full ACO spell-sequence search, and Phase-3 action scoring (stabilize_flow / pressure_bond / deploy_distortion / counter_disruption). The GDD claims these; the current C++ `MasterBrain`\n\nimplements **movement/pursuit ACO only** — spell-chain ACO and the multi-map planner remain design-level.\n\n**World, Flow Fields & Crowd Simulation**\n\nPhase 2 (The Forest Pursuit) and Phase 3 (The Ritual Apex) play out on a **procedural hex-grid forest** governed by **flow fields**. The same map, movement costs, and pathfinding serve the player, the Master, faction warbands, and monsters — everything is deterministic given seed plus state, honoring the Clockwork Dark philosophy. See [Phases](https://github.com/nihilistau/the-masters-shadow/blob/master/design/okf/phases.md), [Master AI](https://github.com/nihilistau/the-masters-shadow/blob/master/design/okf/master-ai.md), and [Factions](https://github.com/nihilistau/the-masters-shadow/blob/master/design/okf/factions.md).\n\n**Hex Coordinate System**\n\nAll spatial logic uses **cube coordinates** `(q, r, s)`\n\nwith the invariant `q + r + s = 0`\n\n(stored as axial `q, r`\n\n; sparse `unordered_map<Hex, Tile>`\n\n). This makes the six neighbors, distance, and A* heuristics clean:\n\n**Distance** = `max(|Δq|, |Δr|, |Δs|)`\n\n— admissible and consistent, so A* is optimal.\n**Neighbors** = the 6 cube deltas (vs. 4/8 on square grids), giving smoother turns, better packing, and no diagonal-vs-cardinal cost inconsistency.\n- Deterministic tie-breaking uses\n`hex_key()`\n\n(a stable packing of q,r) so priority-queue order is reproducible.\n\n**Terrain & Movement Cost**\n\nEach `Tile`\n\ncarries a `Terrain`\n\n, an optional special-location `node`\n\n, a `trap`\n\ntier, a float `distortion`\n\n, and fog-of-war flags (`discovered`\n\n, `visible`\n\n). Movement cost entering a hex = **terrain base cost + distortion + trap penalty** (`3 × trap tier`\n\n). Water is costly, not blocking — nothing is truly impassable, only expensive.\n\nTerrain base costs (per-mille integers, `X/1000`\n\n, so the sim stays byte-stable):\n\n**Terrain** |\n**cost** |\n**Terrain** |\n**cost** |\n| Path |\n0.70 |\nDeep Woods |\n1.60 |\n| Grass / Clearing |\n1.00 |\nRock |\n1.80 |\n| Forest |\n1.20 |\nSwamp |\n2.00 |\n| Ritual |\n1.30 |\nWater |\n3.00 |\n\n**Note:** the pathfinding design docs described costs as `base 1.0 + terrain modifier`\n\n(e.g. “Deep Woods 1.5, Spore Caves 2.0”); the build instead uses **absolute** per-terrain costs (above). Spore Caves is a *node type* placed onto Swamp terrain (2.0), not a distinct terrain.\n\n**Procedural Forest Generation**\n\n`generate_forest(seed, radius=6)`\n\nbuilds a hex disc deterministically:\n\n**Terrain** — two layers of **fractal value noise** (fBm, 4 octaves) drive an *elevation* field and a *moisture* field; a `classify()`\n\nthreshold table maps them: elevation > 0.74 → Rock, > 0.60 → Deep Woods, low elevation + high moisture → Water/Swamp, very low → Grass, else Forest.\n**Endpoints** — the **start** clearing sits on the west edge `(-radius+1, 0)`\n\n; the **Boundary Gate** (the winnable exit) on the east edge `(radius-1, 0)`\n\n, set to Ritual terrain.\n**Node placement** — candidate hexes (excluding a 2-hex radius around start/gate) are sorted for a stable base order, then **Fisher-Yates shuffled with the seeded RNG**, and greedily placed with a **minimum spacing of 2 hexes**. Some node types stamp their terrain (Lake/Spring → Water, Ritual Scar → Ritual, Spore Caves → Swamp, High Ground → Rock).\n**Reveal** — hexes within distance 2 of start begin `discovered`\n\n.\n\n**Node types** (18): FairyRing, WhisperingWell, GoblinMarket, TrollBridge, RebelCamp, LoyalistOutpost, AncientShrine, ShimmeringLake, SporeCaves, AbandonedMill, SmugglersCove, BoundaryGate, plus the **six high-value contested nodes** — **Ley Line Nexus, Fae-Touched Grove, Corrupted Ritual Scar, Water Spirit Spring, Hidden Rebel Cache, High Ground Overlook** — which offer strong rewards but draw agents, backlash, and flow distortion.\n\nThe design canon frames this as a **hybrid PCG pipeline** (Curious Expedition 2-inspired): Noise for organic terrain, plus WFC/template-and-prefab structure for special nodes and a guaranteed start→Gate route, then **state-driven post-processing** (high trace spawns more hazards; high Rebel reputation adds friendly nodes/hidden routes; advanced Ritual Clock fortifies chokepoints). The survey considered BSP, cellular automata, drunkard’s walk, DLA, Voronoi, and WFC before settling on Noise+templates.\n\n**Note:** WFC and full state-driven node re-weighting are **design canon but not in the current build** — the build uses fBm noise + seeded shuffle + spacing. Terrain classification and node roster *are* implemented.\n\n**Hex Pathfinding (A*)**\n\n`a_star(map, start, goal)`\n\nis standard A* on the hex grid: heuristic = true hex distance, cost = `HexMap::movement_cost`\n\n, deterministic tie-breaking, returns the inclusive path or empty if unreachable. The player’s greedy escape and the Master’s precise approach both call it, so both feel the same world friction (traps, distortion, terrain). Design notes call out optional variants (Dijkstra for influence maps, greedy-weighted heuristic for Bloodhound haste, hierarchical/JPS for very large maps) — the build ships plain A* plus the flow field below.\n\n**Flow Fields**\n\nA **flow field** is a Dijkstra flood-fill outward from one or more goals: for every reachable hex it stores the **best next neighbor** toward the goal and the accumulated `cost`\n\n. `build_flow_field(map, goal)`\n\n(or a vector of goals) drives crowd/warband movement and the Master’s coordinated pursuit — far cheaper than per-agent A* when many agents share few goals, and agents naturally spread out and route around cost. Multi-goal builds seed every goal at cost 0, enabling attraction (toward the player’s last-known position or a chokepoint).\n\n**Blended attraction + repulsion** (design canon): compute an attraction field and a repulsion field (from traps, high-trace zones, hostile reputation, player decoys), convert each to a direction vector, and blend `attr × 1.0 − rep × 0.6`\n\n, snapping to the best legal neighbor. This is the mechanism behind *Decoy*/*Illusion* pulling crowds and Grey magic (*Invisibility*, *Muffle*) letting the player slip between flow lines.\n\n**Note:** the build implements single- and multi-goal **attraction** flow fields; **repulsion blending** and per-agent Boids steering weights are design-only so far.\n\n**Flow Distortion & Falloff Curves**\n\nBoth player and Master can **distort** the field — raising movement cost in an area to deny it. `apply_distortion(map, center, strength, radius, type)`\n\nadds a falloff-scaled value to each tile’s `distortion`\n\nwithin the radius. Four **falloff curves** (`Falloff`\n\nenum):\n\n**Quadratic** — `strength / (1 + dist² / radius²)`\n\n: smooth, long tail.\n**Gaussian** — `strength · exp(−dist² / (2σ²))`\n\n, `σ = radius/2`\n\n: soft bell.\n**Exponential** — `strength · exp(−2·(dist/radius))`\n\n: sharp decay.\n**Stepped** — banded: full strength inside 34% of radius, ×0.5 to 67%, ×0.2 to the edge, 0 beyond.\n\nDesign canon adds **dynamic falloff modifiers** — the curve/strength responds to lineage (e.g. **Nyxari, “The Veiled”** excel at misdirection and flow control), Trace Parasite, Ritual Clock stage, and whether the Master is actively contesting. In **Phase 3** the fields become violently chaotic. The Master’s ACO planner weighs `flow_denial`\n\nagainst `contest_resources`\n\nand `direct_pursuit`\n\n. See [Master AI](https://github.com/nihilistau/the-masters-shadow/blob/master/design/okf/master-ai.md).\n\n**Crowd & Warband Simulation**\n\nFaction **warbands** are mobile forces on the hex grid (`FactionWarSim`\n\n). Each turn a band finds its **nearest hostile enemy**, builds a flow field to it, and steps one hex along it; adjacent hostile bands then **clash** — resolution is `d20 + strength/8`\n\nper side, loser takes `3 + |Δroll|`\n\ndamage; a band at strength 0 is routed. Survivors hold **territory** (hex → controlling faction). The war axis is **Rebels vs Loyalists**, with **Trolls and Goblins hostile to Loyalists** for a clean three-way; Fae/Villagers stay out. The player can `reinforce`\n\na faction (capped at strength 60), tipping the balance. See [Factions](https://github.com/nihilistau/the-masters-shadow/blob/master/design/okf/factions.md).\n\nThe full design vision layers **Boids-style local steering** (separation / alignment / cohesion + obstacle avoidance) on the global flow field, with **per-faction weight templates** — Loyalists: high alignment/goal-focus (patrols); Rebels: high cohesion, avoid high-trace; Monsters: loose, drawn to player trace; Master’s trackers: very goal-driven, trap-smart. The GDD also describes a lightweight **movement physics layer** (velocity, mass, flow forces) where Trace Parasite raises effective mass. These steering/physics layers are **design-only**; the build’s warband sim uses flow-field marching + deterministic clash resolution.\n\n**In the build**\n\n**Terrain table** — `data/world/terrain.md`\n\n(`cost_milli`\n\n, `encounter_base`\n\n, per-mille ints), injected into `ms_core`\n\nvia `content_tables.cpp`\n\n→ `game_tables().terrain`\n\n, consumed by `src/world/hexmap.cpp`\n\n(`terrain_base_cost`\n\n, `movement_cost`\n\n).\n**Hex map & coords** — `src/world/hexmap.hpp/.cpp`\n\n, `src/core/hex.*`\n\n(distance, neighbors, `hex_key`\n\n).\n**Procedural gen** — `src/world/forestgen.hpp/.cpp`\n\n(fBm noise, node roster, seeded placement).\n**Pathfinding** — `src/world/pathfind.hpp/.cpp`\n\n(A*).\n**Flow fields & distortion** — `src/world/flowfield.hpp/.cpp`\n\n(Dijkstra field, `Falloff`\n\ncurves, `apply_distortion`\n\n).\n**Warband crowd sim** — `src/world/faction_war.hpp/.cpp`\n\n.\n**Headless pursuit** — `src/ai/pursuit_sim.cpp`\n\ndrives a greedy player vs. a Master `IAgent`\n\non a generated forest (Bloodhound “haste” = a second step when the Master has a fresh fix and mana), proving the rule-bound Master can win *or* lose; used by tests and `--balance`\n\n.", "url": "https://wpnews.pro/news/the-master-s-shadow", "canonical_source": "https://discuss.huggingface.co/t/the-masters-shadow/177573#post_6", "published_at": "2026-07-08 13:26:23+00:00", "updated_at": "2026-07-08 13:40:52.064721+00:00", "lang": "en", "topics": ["artificial-intelligence", "machine-learning", "ai-agents"], "entities": ["Master Malacor", "Clockwork Dark", "Ant-Colony Optimisation", "Bloodhound", "Architect", "Loyalist", "Rebel", "Monster"], "alternates": {"html": "https://wpnews.pro/news/the-master-s-shadow", "markdown": "https://wpnews.pro/news/the-master-s-shadow.md", "text": "https://wpnews.pro/news/the-master-s-shadow.txt", "jsonld": "https://wpnews.pro/news/the-master-s-shadow.jsonld"}}