Welcome back to Technical Tuesday, the counterpart to Feature Friday where we pull back the curtain on how the thing actually works, and occasionally how badly it nearly didn't.
Last week was the engine loop. This week is the thing the loop exists for: a few hundred AI merchants who read the world, form opinions about it, and act on them. What actually is one of these merchants, in code? And how does a pile of if-statements end up looking, from the dock, like somebody with a plan? Fair warning. Some of this code I'm happy with, some of it I'd write completely differently today, and I'll point at both.
Quick Sidenote:
A lot of what you will read here is still Work in Progress and a lot of it is....not perfect. Things like the budget per tick being ~3 Merchants and the "every behavior fires, regardless of what the previous behaviors did" are all on my todo list and should be understood partially as a sort of warning of what NOT to fall into. These Technical Tuesdays are an exploration on how Argosy works, not as gospel about how to do it perfectly.
I am only human after all :)
A merchant is a list of small opinions
The whole AI hangs off one interface:
public interface IAiBehaviour
{
float Priority { get; }
bool IsUrgent => false;
bool IsTriggered(AiContext context);
void Respond(AiContext context, List output);
}
IsTriggered asks "does this apply to me right now?". Respond says what to do about it. Neither is allowed to touch the world. Respond gets handed a list, adds to it, and that list eventually goes into the engine's command queue. Same queue your clicks go into.
Running from a pirate is this:
public void Respond(AiContext context, List output)
{
foreach ((Ship ship, Position evasionTarget) in _threatBuffer)
output.Add(new MoveToPositionCommand(context.PlayerId, ship.Id, evasionTarget));
}
That's it. That's the behaviour.
Deciding whether to run is about thirty lines. Working out where to run to takes another hundred, because on a map that's mostly land, "away from the pirate" is very often "into Denmark". So it steers 70% directly away and 30% sideways, then keeps trying shorter and shorter hops until it finds open water. Most of the AI looks like this. A short opinion, buried in a pile of code that deals with the world being awkward about it.
There are 58 of these. Every merchant gets its own copy of all of them.
Eight always run, fifty wait their turn
Running all 58 for every merchant every tick would be wildly too expensive, so they're split in two at startup and sorted by priority within each half.
The urgent eight are the ones where a delay would look broken. Running from a pirate, dodging a storm, fighting, limping to a shipyard. Everything else can wait, so it waits. A merchant's routine turn comes round every 12 to 24 sim-hours, offset per merchant so they don't all wake up together.
That offset drifts back into sync over time, though, so there's a hard cap sitting on top of it: three merchants per pass get to run the routine fifty. Lose the race and you keep your place in the queue, you just go next time.
Three sounds brutal. It isn't, because a pass happens every tick. The engine ticks every 16ms and the AI runs once per tick, so those three slots come round about 62 times a second. Call it 187 routine turns per second. At normal speed the clock runs at 1000×, which means a merchant wanting its turn every 12 to 24 sim-hours needs one roughly once a minute of real time. Eight hundred merchants works out at about 12 a second, against a ceiling of 187. The cap is a spike flattener. At that size it never actually bites. Worth being clear about what it doesn't touch, because this is easy to read the wrong way. All 800 merchants run their eight urgent behaviours on every single pass, and trading is one of them. Nothing about buying, selling or setting a course is waiting for a slot. What gets rationed is the slow half: guild politics, factories, share dealing.
Nobody wins an argument
This is the bit that surprises people who've built behaviour trees. There's no selection step. Every behaviour that triggers gets to respond, and they all pile into the same list. Nothing anywhere clears or edits it.
So what happens when two behaviours want the same ship in two different places? Both commands go in, both get processed in order, last one wins. For destinations that's mostly fine, since a redundant move order costs nothing.
Money is where it bites. A merchant with 40,000 gold whose "buy a ship" and "build a factory" behaviours both fire has just queued two purchases against one balance. The engine checks each command as it processes it, so the first goes through, the balance drops, the second gets refused. Which is what the priority numbers are actually for. They decide who reaches the gold first. Selling a ship sits at 101, praying about it sits at 19, and that's the right way round for a company that's dying.
The AI deliberately doesn't check any of this up front. It's constantly emitting plans like "sell this cargo, then buy new cargo with the money", where step two only makes sense after step one has already happened. Check early and you quietly bin the profitable half of every plan.
The one that does the trading
One behaviour out of the 58 is responsible for basically all the trade you see on the map. Every AI ship that docks goes through it. Sell, then buy, then pick somewhere to sail, and each stage is allowed to fail into the next.
Three things in there cost me something to learn.
The first is that the price moves while you trade. Buying pushes the ask up, selling pushes the bid down, so a route that looks great at listed prices can lose money by the time both ends have actually executed. The AI now assumes it'll pay about 12% more than quoted and get about 15% less. Before that assumption went in, a full-scale test had the entire AI population losing something like 657,000 gold a week while every individual deal, on paper, looked fine.
The second is that everybody reads the same numbers. Which sounds harmless right up until you notice it means they all pick the same best town, the first arrivals crush the price, and everyone behind them sells into a market they collectively ruined. The fix is a small permanent bias, plus or minus 5%, that each merchant holds about each city. One's always a bit optimistic about Riga, another's a bit down on it. Costs one multiply. Difference between a fleet and a stampede.
The third is that curiosity has to fade. A loaded ship will sometimes ditch its best route and sail somewhere it's never been, which is how the AI fills in its map. That used to be a flat 40% chance, so a merchant that had already visited every port on the map was still binning four in ten profitable voyages. Forever. It now scales with how much of the map that particular merchant hasn't seen.
The day it fell over
Which brings me to a bug report that read, in full: "2801 AI are slow".
Their save had 2,801 players, 5,618 ships, 400 cities. Profiling it gave this, processor time added up across all threads for a single AI pass:
AssignIdleShipBehaviour.Respond 245.6 ms
AvoidStormBehaviour.IsTriggered 6.5 ms
AiMemory.ObservePort 11.0 ms
StrategyManager.Update 1.2 ms
The AI was costing about 92ms a pass. The entire rest of the simulation was costing 13ms. And 2,717 of the 2,800 merchants were running that trading behaviour every single tick, with roughly 98% of those runs producing no decision at all.
Nothing was broken, incidentally. That's the design above, working exactly as written. The trading behaviour is urgent, so it runs constantly. A ship sitting in port with nothing worth selling, nothing worth buying and nowhere worth going stays idle. So it got spotted as idle again on the next tick. And rebuilt the whole price table. And re-scored every reachable city. To reach the same conclusion it had reached 16 milliseconds earlier.
Two changes, both moved up into the cheap eligibility check so the expensive setup never gets reached at all:
A ship whose evaluation produced nothing gets parked for six sim-hours or so. A ship that actually did something never gets parked. The pause is tied to the port it was set at, so turning up somewhere new is always looked at straight away.
Ships still serving their minimum 24-hour harbour stay stopped counting as idle. That check already existed. It just ran after the expensive part had been paid for.
AI pass mean 91.9 ms → 21.9 ms
Respond calls 2 717 → 538
Good result. Also a workaround, and I'd rather say that than not. The real problem is that the AI polls: it asks "anything to do?" over and over instead of being told when something changed, and a cooldown makes polling cheaper without making it right. The giveaway is that arriving in a new port has to be special-cased to punch back through the cooldown. If a ship simply woke up when its port's prices moved, none of this would need to exist. That's a much bigger change than I was willing to make with a player sat there waiting.
And then it got worse.
The fix made a second, older bug visible all the time. Another player reported ships "trying to leave but instantly snapping back into town", in a port holding 40-odd ships. Frames off their clip show a sprite flickering between the city icon and just offshore, over and over.
Here's why. A departing ship keeps its record of which city it's in until it has physically cleared the harbour. So any behaviour hunting for "the nearest city" during that window finds the port it's currently leaving. A damaged ship leaving a shipyard decided the nearest shipyard was the one behind it. A ship leaving a healthy town for a plagued one decided the nearest safe town was the one behind it.

Both of those predated the performance work by a long way. What changed is that the fix got far more ships actually out of port, and only a departing ship can do this. Fix one thing, promote a rare bug to a permanent one.
It also meant going back and correcting my own commit message. That performance fix had proudly reported "3.5x more commands issued" as evidence it improved behaviour too. Most of those extra commands turned out to be this exact loop: dispatch, divert back, dispatch again. With the loop fixed, the same save issues fewer commands than it did before. A number going up isn't the same as a thing getting better, and I'd written it down like it was.
Where the personality comes from
None of this explains why merchants feel different from each other, though. The behaviours are identical for everyone. What differs is the numbers they read.
Every behaviour asks a shared settings object for its thresholds. How much cash to hold back, the smallest profit worth chasing, how battered a hull gets before it diverts to a yard, how much of the fleet should be armed. There are nearly sixty of these, and they're different for every merchant in the world.
Personality gets rolled once from the merchant's ID and never changes after. A Miser holds more cash back, wants a bigger margin, arms almost nothing. An Adventurer runs lean on cash, tolerates a battered hull, and keeps 60% of its fleet as armed escorts.
Life stage gets recomputed constantly from three numbers, and it's the closest thing the AI has to a survival instinct:
if (shipCount >= 8 && treasury >= 200_000 && factoryCount >= 3) return LifeStage.Dominant;
if ((shipCount >= 5 && treasury >= 80_000) || factoryCount >= 1) return LifeStage.Established;
if (shipCount >= 3 && treasury >= 30_000) return LifeStage.Growing;
if (shipCount >= 1 && treasury >= 5_000) return LifeStage.Establishing;
return LifeStage.Survival;
It's applied last, after personality and after goals, so it can't be argued away. A merchant in Survival has every expansion threshold shoved out of reach and its fleet capped at two ships. It never decides to stop expanding. It just can't clear its own bar any more. An ambitious personality inside a failing company ends up reading as somebody who stopped dreaming and started grinding, which is roughly what I was after.
Goals sit in between. Seven of them, reviewed every 90 sim-days, filtered by what the life stage allows, then scored on how badly the personality wants each one times how realistic it currently is. A goal that isn't working decays, and dropping one puts it on a 60-day cooldown so nobody flip-flops. Two things I'm not proud of here.
The code that combines all this is bad. One long method, about thirty local variables, sixteen of them threaded through a helper as ref parameters, then all sixteen copied out again to work out a blended version for the secondary goal:
private static void ApplyGoalModifiers(
GoalType goal,
ref float cashReserveRatio,
ref float minAcceptableProfit,
ref long expansionThreshold,
ref int maxFleetSize,
// ...twelve more
It works. It's well covered by tests. It's also horrible to change, and every new threshold means touching that signature in three places. This is what a system looks like when it grows a field at a time and nobody ever stops to restructure it.
The other thing is that some of this is guesswork in a lab coat. Working out whether a merchant is making progress on a wealth goal is easy, you check whether the money went up. Political ambition turned out to be much harder, and the code says so out loud:
GoalType.PoliticalAscent => 0.7, // political progress is hard to measure numerically
That 0.7 is there so political merchants don't quit their goal out of frustration. It measures nothing. And it has company: a lot of the economy's constants came out of a tuning search that runs for six hours, trying combinations until the simulation stops doing something stupid. Others, like the table saying a Merchant wants a trade empire 1.3 times as much as average, I wrote down by hand and nudged until the world looked right. Both are fine ways to land on a number. Neither is a derivation, and the decimal places shouldn't get to imply otherwise.
So, Novgorod
Put it together.
A merchant's ID hashes out to an opportunistic, ambitious trader. Six ships and 90,000 gold puts it in the Established bracket, which unlocks trade expansion as a goal, which its personality happens to like the look of. Between them they set its minimum acceptable profit at about 10 gold a unit and tell it to keep 22% of its money back.
One of its ships docks at Reval with an empty hold. Nothing to sell, so it looks at what Reval's got going. Salt, cheap. It remembers being in Novgorod eleven days ago, where salt was selling well. It assumes it'll pay a bit more and get a bit less than those remembered numbers, checks that still clears its 10 gold floor, and fills the hold to 80% or until the cash reserve stops it. Then it scores every port it can reach on profit over distance, applies its own private optimism about Novgorod, and off it goes.
Nowhere in any of that did anything decide to sail to Novgorod. It fell out of a hash, a handful of thresholds, a memory of a price, and a division.
No idea what I'll write about next week... If you have ideas or wished, please let me know in the comments or via Discord!
Join the Discord: discord.gg/CUSVEaEH2f
