fix(bridge): make the market sweep notice a vendor running out of gold

`BridgeMarket.Signature()` diffs shop name, owner, map, coordinates and the
item/price list -- the things a LISTING is made of. Protocol 5 added a `fees`
block to the frame and the change detector never learned about it.

So a vendor quietly running down its gold altered nothing the sweep compared,
emitted no frame, and `uo.vendor.expiring` -- the notification whose entire
subject is a vendor running out of gold -- could fire only by coincidence: when
somebody happened to reprice an item on a shop that was already broke. Proved on
the engagement Phase 11b live rig by setting a vendor's held gold to zero and
watching no frame follow.

The signature carries the DERIVED values, `exempt` and `periodsRemaining`, not
the raw ones. An integer division moves only when the shard's own answer to "is
this vendor in danger" moves; `HoldGold` changes on every sale and `NextPayTime`
on every tick, and keying on either would re-emit a fat listing frame for a shop
whose listings had not changed.

Emit CADENCE, not frame shape: no field added, PROTOCOL_VERSION untouched, and
`overlay.toml` unchanged. The general form is worth carrying forward -- a
sweep-based kind has a change detector, and a field added to the frame but not to
the detector ships correct and arrives never.

Also adds `tools/scaffolding/BridgeRigDriver.cs`: the shard driven from outside
the game over a polled command file. A walk asserts what happened BETWEEN two
steps, so the steps have to be separated by the observer rather than by a
hard-coded delay -- and ServUO's console takes a fixed verb set, so `[p5probe`
cannot be typed at a headless shard at all. Never deployed; `deploy.ps1` copies
only `overlay/`. The README gains the two ServUO facts the walk cost a rebuild
each to learn: a condemned house cannot be refreshed, and only a clean shutdown
emits.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-01 07:12:46 -05:00
parent a144c12c46
commit 1dd490b483
3 changed files with 552 additions and 0 deletions

View File

@@ -456,6 +456,20 @@ namespace Server.Custom.Bridge
sb.Append(vendor.Map == null ? "" : vendor.Map.Name).Append('|');
sb.Append(vendor.X).Append(',').Append(vendor.Y).Append('|');
// The FEE STATE, and it belongs here for a reason found on a live rig: a vendor
// quietly running out of gold changes none of the fields above, so without this the
// sweep sees no change, emits nothing, and `uo.vendor.expiring` -- the warning whose
// entire subject is a vendor running out of gold -- can only fire by coincidence,
// when somebody happens to reprice an item on a shop that is already broke.
//
// The DERIVED values, not the raw ones. `periodsRemaining` is an integer division, so
// it moves only when the shard's own answer to "is this vendor in danger" moves --
// near-zero extra frame volume -- while `HoldGold` changes on every sale and
// `NextPayTime` on every tick, which would re-emit a fat listing frame for a shop
// whose listings did not change. Protocol-neutral: the fields already ship in
// `AppendFees`, and this changes only WHEN a frame is sent.
AppendFeeSignature(sb, vendor);
var limit = Math.Min(_items.Count, BridgeConfig.MarketMaxListings);
sb.Append(_items.Count).Append('|');
@@ -624,6 +638,27 @@ namespace Server.Custom.Bridge
/// projection does. Unlike a dynamic-decay house, though, there is no randomness in it:
/// given the current funds it is the exact tick the vendor is destroyed on.
/// </summary>
/// <summary>
/// The fee state as the change-detector sees it: exempt, and how many pay ticks the
/// vendor survives. Kept beside `AppendFees` so the two cannot drift -- a fee field
/// that becomes decision-relevant has to be added in both places, and this comment is
/// where the next person is told so.
/// </summary>
private static void AppendFeeSignature(StringBuilder sb, PlayerVendor vendor)
{
if (vendor == null || vendor.IsCommission)
{
sb.Append("exempt|");
return;
}
int charge = BaseHouse.NewVendorSystem ? vendor.ChargePerRealWorldDay : vendor.ChargePerDay;
int funds = BaseHouse.NewVendorSystem ? vendor.HoldGold : vendor.BankAccount + vendor.HoldGold;
// Mirrors AppendFees: a free vendor never runs out, and reports no periods at all.
sb.Append(charge > 0 ? (funds / charge).ToString() : "free").Append('|');
}
private static void AppendFees(StringBuilder sb, PlayerVendor vendor)
{
sb.Append(",\"fees\":{");

View File

@@ -0,0 +1,486 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Server.Accounting;
using Server.Commands;
using Server.Engines.CityLoyalty;
using Server.Mobiles;
using Server.Multis;
namespace Server.Custom
{
/// <summary>
/// Drives the shard from OUTSIDE the game, one verb per line in a file the driver polls.
///
/// Every other probe here runs a fixed script at boot or from `[command`, and both are the
/// wrong shape for an acceptance walk: a walk asserts what happened BETWEEN two steps
/// ("one mail, then nothing for a day"), so the steps have to be separated by the observer
/// rather than by a hard-coded delay -- and ServUO's console reads a fixed verb set
/// (`Scripts/Misc/ConsoleCommands.cs`), so `[p5probe` cannot be typed at a headless shard
/// at all. A file is the one channel a headless shard already has.
///
/// Write one or more lines to `Config/rigcmd.txt`; the driver runs them on the Core thread
/// within a second, prints `[RigDriver]` lines, and TRUNCATES the file so the next write is
/// the next command. Output is console-only: nothing here emits, and everything observed
/// travels the real bridge.
///
/// Verbs:
/// decaylist houses that CAN decay, with owner account and stage
/// decay &lt;serial|any&gt; &lt;stage&gt; force a decay stage (LikeNew|Slightly|Somewhat|
/// Fairly|Greatly|IDOC|Collapsed)
/// vendorlist player vendors, with owner account and next pay time
/// vendorfunds &lt;serial&gt; &lt;gold&gt; set a vendor's held gold (drives periodsRemaining)
/// citylist cities, governors and election phases
/// governor &lt;city&gt; &lt;mobile|none&gt; seat a governor (a mobile serial, or a player's name)
/// election &lt;city&gt; force a new election into its nomination window
/// activate &lt;account&gt; clear an account's inactivity, so its houses stop
/// being Condemned and CAN be refreshed
/// password &lt;account&gt; &lt;pw&gt; set a game account's password (for a login probe)
/// save a world save
/// shutdown a CLEAN shutdown, so the bridge emits server.shutdown
///
/// Test scaffolding. Never deployed; `deploy.ps1` copies only `overlay/`.
/// </summary>
public static class BridgeRigDriver
{
private static string _path;
private static DateTime _lastWrite = DateTime.MinValue;
public static void Initialize()
{
if (!Config.Get("Bridge.RigDriverEnabled", false))
return;
_path = Path.Combine(Core.BaseDirectory, "Config", "rigcmd.txt");
CommandSystem.Register("rigdriver", AccessLevel.Administrator, e => Poll());
Console.WriteLine("[RigDriver] watching {0}", _path);
Timer.DelayCall(TimeSpan.FromSeconds(2.0), TimeSpan.FromSeconds(1.0), Poll);
}
// ---- the poll ----
private static void Poll()
{
try
{
if (!File.Exists(_path))
return;
// Written-and-not-finished is a real case: the observer writes with a shell
// redirect while this timer fires. An empty file is nothing to do, and the
// timestamp guard keeps a slow write from being run twice.
var stamp = File.GetLastWriteTimeUtc(_path);
if (stamp <= _lastWrite)
return;
var lines = File.ReadAllLines(_path);
if (lines.Length == 0)
return;
_lastWrite = stamp;
File.WriteAllText(_path, String.Empty);
foreach (var line in lines)
{
var trimmed = (line ?? String.Empty).Trim();
if (trimmed.Length == 0 || trimmed.StartsWith("#"))
continue;
try
{
Run(trimmed);
}
catch (Exception ex)
{
Say("\"" + trimmed + "\" threw: " + ex.Message);
}
}
Say("done");
}
catch (IOException)
{
// The writer still holds it. Next tick.
}
catch (Exception ex)
{
Say("poll threw: " + ex.Message);
}
}
private static void Say(string line)
{
Console.WriteLine("[RigDriver] " + line);
}
private static void Run(string line)
{
var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var verb = parts[0].ToLowerInvariant();
switch (verb)
{
case "decaylist": DecayList(); break;
case "decay": Decay(Arg(parts, 1), Arg(parts, 2)); break;
case "vendorlist": VendorList(); break;
case "vendorfunds": VendorFunds(Arg(parts, 1), Arg(parts, 2)); break;
case "citylist": CityList(); break;
case "governor": Governor(Arg(parts, 1), Arg(parts, 2)); break;
case "election": Election(Arg(parts, 1)); break;
case "activate": Activate(Arg(parts, 1)); break;
case "password": Password(Arg(parts, 1), Arg(parts, 2)); break;
case "save": Say("saving"); Misc.AutoSave.Save(); break;
// A clean shutdown, which is the only kind that EMITS. `Stop-Process` drops the
// socket and the shard says nothing, so a killed shard is indistinguishable from
// a wedged one -- and `uo.server.down` never fires. Core.Kill runs
// EventSink.Shutdown, which is what BridgeBoot listens on.
case "shutdown": Say("shutting down"); Timer.DelayCall(TimeSpan.Zero, () => Core.Kill(false)); break;
default: Say("unknown verb \"" + verb + "\""); break;
}
}
private static string Arg(string[] parts, int i)
{
return i < parts.Length ? parts[i] : null;
}
// ---- houses ----
/// <summary>
/// `CanDecay` is the filter, and getting it wrong is silent: an AutoRefresh house --
/// and the owner's newest house is always AutoRefresh -- has a DecayLevel getter that
/// calls ResetDynamicDecay(), so a forced stage is wiped before the sweep reads it and
/// NOTHING is emitted. That looks exactly like a broken emitter.
/// </summary>
private static IEnumerable<BaseHouse> Decayable()
{
return BaseHouse.AllHouses
.Where(h => h != null && !h.Deleted && h.Owner != null && h.CanDecay);
}
private static void DecayList()
{
foreach (var h in Decayable())
{
var acct = h.Owner.Account == null ? "-" : h.Owner.Account.Username;
Say(String.Format(
"house 0x{0:X} owner={1} acct={2} name=\"{3}\" region={4} type={5} level={6}",
h.Serial.Value, h.Owner.Name, acct, HouseName(h), RegionName(h),
h.DecayType, h.DecayLevel));
}
Say("decayable=" + Decayable().Count());
}
private static string HouseName(BaseHouse h)
{
return h.Sign != null && h.Sign.Name != null ? h.Sign.Name : String.Empty;
}
private static string RegionName(BaseHouse h)
{
var r = Region.Find(h.Location, h.Map);
return r == null ? "-" : r.Name ?? "-";
}
private static void Decay(string which, string stage)
{
DecayLevel level;
if (!TryParseStage(stage, out level))
{
Say("unknown stage \"" + stage + "\"");
return;
}
BaseHouse house = null;
if (String.IsNullOrEmpty(which) || which == "any")
house = Decayable().FirstOrDefault();
else
{
var serial = ParseSerial(which);
house = Decayable().FirstOrDefault(h => h.Serial.Value == serial);
}
if (house == null)
{
Say("no decayable house matched \"" + which + "\"");
return;
}
var from = house.DecayLevel;
// A refresh is what a player does at the sign, and it is NOT SetDynamicDecay: the
// level is derived from LastRefreshed, so a "LikeNew" that only rewrote the dynamic
// stage would be undone by the next read.
if (level == DecayLevel.LikeNew)
house.RefreshDecay();
else
house.SetDynamicDecay(level);
Say(String.Format(
"house 0x{0:X} {1} -> {2} (now {3})",
house.Serial.Value, from, level, house.DecayLevel));
}
private static bool TryParseStage(string s, out DecayLevel level)
{
level = DecayLevel.Ageless;
if (String.IsNullOrEmpty(s))
return false;
foreach (DecayLevel candidate in Enum.GetValues(typeof(DecayLevel)))
{
if (String.Equals(candidate.ToString(), s, StringComparison.OrdinalIgnoreCase))
{
level = candidate;
return true;
}
}
return false;
}
private static int ParseSerial(string s)
{
var text = s.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? s.Substring(2) : s;
int parsed;
if (Int32.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out parsed))
return parsed;
return Int32.TryParse(s, out parsed) ? parsed : 0;
}
// ---- vendors ----
private static IEnumerable<PlayerVendor> Vendors()
{
return World.Mobiles.Values.OfType<PlayerVendor>().Where(v => !v.Deleted);
}
private static void VendorList()
{
Say("NewVendorSystem=" + BaseHouse.NewVendorSystem);
foreach (var v in Vendors())
{
var owner = v.Owner;
var acct = owner == null || owner.Account == null ? "-" : owner.Account.Username;
Say(String.Format(
"vendor 0x{0:X} shop=\"{1}\" owner={2} acct={3} hold={4} charge={5} nextPay={6}",
v.Serial.Value, v.ShopName, owner == null ? "-" : owner.Name, acct,
v.HoldGold, v.ChargePerDay, v.NextPayTime.ToUniversalTime().ToString("o")));
}
Say("vendors=" + Vendors().Count());
}
/// <summary>
/// Set a vendor's held gold, which is the only knob that walks it toward dismissal
/// without waiting a pay period -- `NextPayTime` has a private setter, and a period is
/// a real day on the new vendor system and a UO day (~2 real hours) on the old one.
/// The emitter computes `periodsRemaining` as funds / chargePerPeriod, so this moves
/// exactly the field the threshold tracker watches.
/// </summary>
private static void VendorFunds(string which, string gold)
{
var serial = ParseSerial(which ?? String.Empty);
var vendor = Vendors().FirstOrDefault(v => v.Serial.Value == serial);
if (vendor == null)
{
Say("no vendor matched \"" + which + "\"");
return;
}
int funds;
if (!Int32.TryParse(gold, out funds))
{
Say("bad gold \"" + gold + "\"");
return;
}
// Both, because the old vendor system spends BankAccount + HoldGold and the new one
// spends HoldGold alone -- setting one would leave the other paying the charge.
vendor.HoldGold = funds;
vendor.BankAccount = 0;
var charge = BaseHouse.NewVendorSystem ? vendor.ChargePerRealWorldDay : vendor.ChargePerDay;
Say(String.Format(
"vendor 0x{0:X} hold={1} bank=0 charge={2} periodsRemaining={3}",
vendor.Serial.Value, vendor.HoldGold, charge, charge > 0 ? funds / charge : -1));
}
// ---- accounts ----
/// <summary>
/// Mark an account as having just logged in.
///
/// This is the ONLY way to walk a decaying house back out of danger on a seeded
/// world, and the reason is ServUO's, not the rig's: every house that CAN decay here
/// is `DecayType.Condemned` (the seeder backdates accounts past
/// `Account.InactiveDuration` precisely to make them decay), and
/// `BaseHouse.RefreshDecay()` returns false immediately for a Condemned house. A
/// condemned house is not refreshable by anyone; it is rescued by its OWNER LOGGING
/// IN, which is what this reproduces.
///
/// What the shard then reports depends on how many houses the owner has:
/// `AutoRefresh` (their newest) stops decaying and reads **Ageless**, while an older
/// `ManualRefresh` one is back on the clock and reads **LikeNew**. Both are "out of
/// danger", and a mapper that reads only one of them misses most rescues.
/// </summary>
private static void Activate(string username)
{
var acct = Accounts.GetAccount(username) as Account;
if (acct == null)
{
Say("no account \"" + username + "\"");
return;
}
acct.LastLogin = DateTime.UtcNow;
Say(String.Format("account {0} lastLogin=now inactive={1}", acct.Username, acct.Inactive));
foreach (var h in BaseHouse.AllHouses)
{
if (h == null || h.Deleted || h.Owner == null || h.Owner.Account != acct)
continue;
Say(String.Format(
" house 0x{0:X} type={1} level={2}", h.Serial.Value, h.DecayType, h.DecayLevel));
}
}
/// <summary>
/// Set a game account's password, so a login can be driven over a real socket.
///
/// The socket is not optional for the ACCEPTED half: ServUO's own AccountHandler calls
/// `acct.HasAccess(e.State)` before it ever checks the password, and a null NetState
/// fails that -- so an in-process probe reports "access denied" for a correct password
/// and can never produce `accepted:true`.
/// </summary>
private static void Password(string username, string pw)
{
var acct = Accounts.GetAccount(username) as Account;
if (acct == null)
{
Say("no account \"" + username + "\"");
return;
}
if (String.IsNullOrEmpty(pw))
{
Say("refusing to set an empty password");
return;
}
acct.SetPassword(pw);
Say("account " + acct.Username + " password set");
}
// ---- cities ----
private static void CityList()
{
Say("CityLoyaltySystem.Enabled=" + CityLoyaltySystem.Enabled);
foreach (var city in CityLoyaltySystem.Cities)
{
if (city == null)
continue;
var e = city.Election;
Say(String.Format(
"city={0} governor={1} elect={2} election={3} candidates={4} autoPick={5}",
city.City,
city.Governor == null ? "-" : city.Governor.Name + "/0x" + city.Governor.Serial.Value.ToString("X"),
city.GovernorElect == null ? "-" : city.GovernorElect.Name,
e == null ? "-" : (e.CanNominate() ? "nominate" : e.CanVote() ? "vote" : e.Ongoing ? "pending" : "none"),
e == null || e.Candidates == null ? 0 : e.Candidates.Count,
e == null ? "-" : e.AutoPickGovernor.ToUniversalTime().ToString("o")));
}
}
private static CityLoyaltySystem FindCity(string name)
{
return CityLoyaltySystem.Cities.FirstOrDefault(
c => c != null && String.Equals(c.City.ToString(), name, StringComparison.OrdinalIgnoreCase));
}
private static void Governor(string cityName, string who)
{
var city = FindCity(cityName);
if (city == null)
{
Say("no city \"" + cityName + "\"");
return;
}
if (String.Equals(who, "none", StringComparison.OrdinalIgnoreCase))
{
city.Governor = null;
Say("city=" + city.City + " governor cleared");
return;
}
var mob = FindMobile(who);
if (mob == null)
{
Say("no player matched \"" + who + "\"");
return;
}
city.Governor = mob;
var acct = mob.Account == null ? "-" : mob.Account.Username;
Say(String.Format(
"city={0} governor={1} 0x{2:X} acct={3}",
city.City, mob.Name, mob.Serial.Value, acct));
}
private static Mobile FindMobile(string who)
{
var serial = ParseSerial(who);
if (serial != 0)
{
var bySerial = World.FindMobile(serial);
if (bySerial != null)
return bySerial;
}
return World.Mobiles.Values.OfType<PlayerMobile>()
.FirstOrDefault(m => !m.Deleted && String.Equals(m.Name, who, StringComparison.OrdinalIgnoreCase));
}
private static void Election(string cityName)
{
var city = FindCity(cityName);
if (city == null)
{
Say("no city \"" + cityName + "\"");
return;
}
if (city.Election == null)
{
Say("city=" + city.City + " has no election object");
return;
}
city.Election.StartNewElection();
Say(String.Format(
"city={0} election restarted; autoPick={1} nominate={2}",
city.City,
city.Election.AutoPickGovernor.ToUniversalTime().ToString("o"),
city.Election.CanNominate()));
}
}
}

View File

@@ -14,6 +14,7 @@ These two scripts produced the measured budget in [PLAN.md](https://gitea.whitlo
| `BridgeCrierProbe.cs` | `Scripts/Custom/BridgeCrierProbe.cs` | Logs the global town-crier entry list every 3s so `towncrier.add` / `remove` can be seen landing in game state. Flag: `CrierProbeOnStart`. |
| `BridgeVendorSaleProbe.cs` | `Scripts/Custom/BridgeVendorSaleProbe.cs` | Fires `PlayerVendorSale` (Phase 7) with real seeded-vendor data so `vendor.sale` can be verified without a live buy. Requires the Phase 7 patches applied. Flag: `VendorSaleProbeOnStart`. |
| `BridgeDemoDress.cs` | `Scripts/Custom/BridgeDemoDress.cs` | Renames a seeded world so it is presentable in a screenshot: shop signs, vendor and character names, house signs. Also stages a few condemned houses back into IDOC, and sets a known password on `seed_000` so a character can be logged in. Flags: `DemoDressOnStart`, `DemoDressPassword`. In game: `[demodress`. |
| `BridgeRigDriver.cs` | `Scripts/Custom/BridgeRigDriver.cs` | Drives the shard from OUTSIDE the game, one verb per line in `Config/rigcmd.txt`, which the driver polls and truncates. Written for the engagement Phase 11b acceptance walk, where each step's assertion is what happened BETWEEN two steps, so the steps have to be separated by the observer rather than by a hard-coded delay -- and ServUO's console takes a fixed verb set (`Scripts/Misc/ConsoleCommands.cs`), so `[p5probe` cannot be typed at a headless shard at all. Verbs: `decaylist`, `decay`, `vendorlist`, `vendorfunds`, `citylist`, `governor`, `election`, `activate`, `password`, `save`, `shutdown`. Flag: `RigDriverEnabled`. **Sets passwords and mutates the world.** |
| `BridgeProtocol5Probe.cs` | `Scripts/Custom/BridgeProtocol5Probe.cs` | Drives all three Protocol 5 enrichments so their frames can be observed: walks one house Fairly -> Greatly -> IDOC (the PAIR is the assertion -- `estimatedCollapse` must appear only on the IDOC frame), reports each player vendor's fee state straight off the `PlayerVendor` so the emitted `fees` block can be checked against the shard's own numbers, and fires `EventSink.AccountLogin`. Flags: `Protocol5ProbeOnStart`, `Protocol5ProbeAccount`, `Protocol5ProbePassword`. In game: `[p5probe`. **Sets a password on the named account.** |
## Deploy overwrites Bridge.cfg
@@ -139,3 +140,33 @@ reports `Ageless`, so a forced `SetDynamicDecay` is wiped on the very next read,
change, and **nothing is emitted at all**. That looks exactly like a broken emitter. Filter on
`house.CanDecay`, and expect a seeded world to have only one or two houses that qualify -- both
probably already at IDOC, so the walk has to put one back down first.
## A decaying house cannot be refreshed — only its owner coming back rescues it
`BaseHouse.RefreshDecay()` returns `false` immediately when `DecayType == Condemned`, and on a
seeded world **every house that can decay is Condemned** — the seeder backdates 18 accounts past
`Account.InactiveDuration` precisely to make them decay. So `SetDynamicDecay(DecayLevel.LikeNew)`
is wiped by the next read and `RefreshDecay()` does nothing: the sweep sees no change and emits
nothing, which looks exactly like a broken emitter for the second time on the same page.
The rescue is the OWNER LOGGING IN (`BridgeRigDriver`'s `activate <account>` reproduces it by
setting `LastLogin`). What the shard then reports depends on how many houses that owner has:
| the house | `DecayType` after the login | `DecayLevel` reads |
|---|---|---|
| their newest | `AutoRefresh` | **`Ageless`** — off the decay clock entirely |
| any older one | `ManualRefresh` | **`LikeNew`** — back on the clock, at the top |
Both are "out of danger", and the newest-house case is the common one. A consumer that watches only
for `LikeNew` misses most rescues — which is what the engagement mapper did until this walk.
## The console takes a fixed verb set, so `[commands` cannot be typed at a headless shard
`Scripts/Misc/ConsoleCommands.cs` handles `save`, `shutdown`, `restart`, `online`, `kick` and a
handful more; it does **not** dispatch arbitrary `[commands`. Every other probe here therefore runs
either at boot or from an in-game client, and neither works for a walk driven from a script. That is
what `BridgeRigDriver` and its `rigcmd.txt` are for.
Also: only a CLEAN shutdown emits. `Stop-Process` drops the socket and the shard says nothing, so a
killed shard is indistinguishable from a wedged one and `server.shutdown` never reaches the sidecar —
use the driver's `shutdown` verb (`Core.Kill`) when the shutdown itself is what is being tested.