Snapshot for release 2026.10.21.3 (internal 24a7b4f)

This commit is contained in:
Tom Bohar 2026-10-21 21:03:48 -04:00
commit 10c58b53b6
47 changed files with 2032 additions and 649 deletions

View file

@ -128,7 +128,7 @@ public partial class BuffManager
if (IsAwaitingCastResolution()) return "the server hasn't finished the last cast";
itemsOnly = true;
}
if (vital != OneTouchVital.Health && (DateTime.Now - _lastCastAttempt).TotalMilliseconds < _settings.SpellCastIntervalMs)
if (vital != OneTouchVital.Health && (RynthClock.Now - _lastCastAttempt).TotalMilliseconds < _settings.SpellCastIntervalMs)
return "inside the spell interval";
bool pacerAllows;

View file

@ -17,9 +17,9 @@ public partial class BuffManager
private bool TryScriptHeal(int healLine, bool inCombat)
{
// AC just said "You're too busy!": the same pacing as a Heal Self (AttemptVitalCast).
if (DateTime.Now < _busyBackoffUntil && (DateTime.Now - _lastCastAttempt).TotalMilliseconds < BusyHealRetryMs)
if (RynthClock.Now < _busyBackoffUntil && (RynthClock.Now - _lastCastAttempt).TotalMilliseconds < BusyHealRetryMs)
{
_vitalWhy = $"AC too busy, waiting {(_busyBackoffUntil - DateTime.Now).TotalMilliseconds:0} ms";
_vitalWhy = $"AC too busy, waiting {(_busyBackoffUntil - RynthClock.Now).TotalMilliseconds:0} ms";
_healWaitKind = "too-busy backoff";
return true;
}

View file

@ -190,7 +190,7 @@ public partial class BuffManager : IDisposable
private readonly Dictionary<int, DateTime> _noComponentsUntil = new();
private const double NoComponentsLevelSec = 600.0;
private bool LevelLacksComponents(int spellId)
=> _noComponentsUntil.TryGetValue(spellId, out DateTime until) && DateTime.Now < until;
=> _noComponentsUntil.TryGetValue(spellId, out DateTime until) && RynthClock.Now < until;
// Per-family SILENT no-show counter. Distinct from _buffFailCooldownUntil
// (which catches chat-explicit hard rejects). This catches the /god case:
@ -283,7 +283,7 @@ public partial class BuffManager : IDisposable
private readonly CastTracker _cast;
/// <summary>Clock for the cast-safety timing (give-up, server wait, held-cast nudge, stance
/// settle). The host tests replace it; everything else here reads DateTime.Now.</summary>
/// settle). The host tests replace it; everything else here reads RynthClock.Now.</summary>
internal Func<DateTime> Clock { get => _cast.Clock; set => _cast.Clock = value; }
private DateTime Now => _cast.Now;
@ -380,8 +380,8 @@ public partial class BuffManager : IDisposable
/// not usable). Cached for a second: the arbiter asks every tick.</summary>
private int TopStaminaToManaId()
{
if ((DateTime.Now - _topS2MAt).TotalMilliseconds < 1000) return _topS2MId;
_topS2MAt = DateTime.Now;
if ((RynthClock.Now - _topS2MAt).TotalMilliseconds < 1000) return _topS2MId;
_topS2MAt = RynthClock.Now;
_topS2MId = IsSkillUsable(AcSkillType.LifeMagic)
? _spellManager.GetDynamicSelfBuffId("Stamina to Mana Self", AcSkillType.LifeMagic, LevelLacksComponents)
: 0;
@ -432,7 +432,7 @@ public partial class BuffManager : IDisposable
if (id == 0 || !StaminaAllowsStaminaToMana()) return false;
int family = SpellTableStub.GetById(id)?.Family ?? 0;
return !(family != 0 && _buffFailCooldownUntil.TryGetValue(family, out DateTime until)
&& (until - DateTime.Now).TotalSeconds > LowManaHealRestSec);
&& (until - RynthClock.Now).TotalSeconds > LowManaHealRestSec);
}
/// <summary>Stamina lets Stamina to Mana go: over 15%, or a stamina kit or listed stamina potion
@ -461,7 +461,7 @@ public partial class BuffManager : IDisposable
spellName = id != 0 ? SpellTableStub.GetById(id)?.Name ?? "Stamina to Mana" : "Stamina to Mana";
if (id == 0 || _vitals.MaxMana == 0) return false;
if (cost > 0) return _vitals.CurrentMana < cost && AffordableVitalId("Stamina to Mana Self") == 0;
return (DateTime.Now - _lastManaRefusalAt).TotalMilliseconds < ManaRefusalMemoryMs;
return (RynthClock.Now - _lastManaRefusalAt).TotalMilliseconds < ManaRefusalMemoryMs;
}
/// <summary>The highest level of a vital spell whose known cost current mana can pay (a level
@ -483,7 +483,7 @@ public partial class BuffManager : IDisposable
internal bool WantsManaNow()
{
if (!_settings.IsMacroRunning || _vitals.MaxMana == 0) return false;
if (DateTime.Now < _manaUnavailableUntil) return false;
if (RynthClock.Now < _manaUnavailableUntil) return false;
if (!InCombatNow() || !FightsWithMagic()) return false;
return ManaUnderLine(true, out _) && ManaRefillPossible();
}
@ -549,7 +549,7 @@ public partial class BuffManager : IDisposable
_sameManaCasts++;
if (_sameManaCasts == StuckManaCasts)
{
_stuckManaSince = DateTime.Now;
_stuckManaSince = RynthClock.Now;
_host.Log($"[RynthAi] Vitals: the mana reading has not moved over {StuckManaCasts + 1} buff casts ({cur}/{_vitals.MaxMana}); buffs wait for a fresh reading (up to {StuckManaHoldSec:0} s).");
}
}
@ -563,7 +563,7 @@ public partial class BuffManager : IDisposable
{
if (_sameManaCasts < StuckManaCasts) return false;
if (_vitals.CurrentMana != _lastBuffCastMana
|| (DateTime.Now - _stuckManaSince).TotalSeconds >= StuckManaHoldSec)
|| (RynthClock.Now - _stuckManaSince).TotalSeconds >= StuckManaHoldSec)
{
_host.Log($"[RynthAi] Vitals: mana reading {(_vitals.CurrentMana != _lastBuffCastMana ? "moved" : "still the same after " + StuckManaHoldSec.ToString("0") + " s")}: {_lastBuffCastMana} -> {_vitals.CurrentMana}/{_vitals.MaxMana}; buffs go on.");
_sameManaCasts = 0;
@ -598,28 +598,28 @@ public partial class BuffManager : IDisposable
// rebuff ran mana under Stamina to Mana's own cost (2026-10-15): wait for it instead, up to
// ReserveWaitMaxSec. With no Stamina to Mana at all nothing refills: the buff goes.
if (TopStaminaToManaId() == 0) return false;
if (_reserveWaitSince == DateTime.MinValue) _reserveWaitSince = DateTime.Now;
if ((DateTime.Now - _reserveWaitSince).TotalSeconds >= ReserveWaitMaxSec)
if (_reserveWaitSince == DateTime.MinValue) _reserveWaitSince = RynthClock.Now;
if ((RynthClock.Now - _reserveWaitSince).TotalSeconds >= ReserveWaitMaxSec)
{
if ((DateTime.Now - _reserveOverLoggedAt).TotalSeconds >= 30)
if ((RynthClock.Now - _reserveOverLoggedAt).TotalSeconds >= 30)
{
_reserveOverLoggedAt = DateTime.Now;
_reserveOverLoggedAt = RynthClock.Now;
_host.Log($"[RynthAi] Vitals: {buffName} goes under the mana reserve ({cur}/{_vitals.MaxMana}, reserve {ManaReserve()}): Stamina to Mana could not go for {ReserveWaitMaxSec:0} s ({Why(_vitalWhy)}).");
}
return false;
}
LastBuffSkipReason = $"mana {cur}/{_vitals.MaxMana}: {buffName} would leave it under the reserve ({ManaReserve()}); waiting for Stamina to Mana";
if ((DateTime.Now - _buffManaWaitLoggedAt).TotalSeconds >= 30)
if ((RynthClock.Now - _buffManaWaitLoggedAt).TotalSeconds >= 30)
{
_buffManaWaitLoggedAt = DateTime.Now;
_buffManaWaitLoggedAt = RynthClock.Now;
_host.Log($"[RynthAi] Vitals: buffing waits: {LastBuffSkipReason} (Stamina to Mana: {Why(_vitalWhy)})");
}
return true;
}
LastBuffSkipReason = $"mana {cur}/{_vitals.MaxMana} is under {buffName}'s cost ({cost}); waiting for regen";
if ((DateTime.Now - _buffManaWaitLoggedAt).TotalSeconds >= 30)
if ((RynthClock.Now - _buffManaWaitLoggedAt).TotalSeconds >= 30)
{
_buffManaWaitLoggedAt = DateTime.Now;
_buffManaWaitLoggedAt = RynthClock.Now;
_host.Log($"[RynthAi] Vitals: buffing waits: {LastBuffSkipReason} (Stamina to Mana: {Why(_vitalWhy)})");
}
return true;
@ -940,7 +940,7 @@ public partial class BuffManager : IDisposable
DateTime expiresAt = new DateTime(long.Parse(p[3]));
int level = int.Parse(p[4]);
string name = p[5];
if (expiresAt > DateTime.Now)
if (expiresAt > RynthClock.Now)
{
int family = new SpellInfo(0, name).Family;
_itemSpellTimers[family] = new ItemSpellRecord
@ -965,7 +965,7 @@ public partial class BuffManager : IDisposable
int level = int.Parse(p[offset + 2]);
string name = p[offset + 3];
int family = new SpellInfo(0, name).Family;
if (expiration > DateTime.Now)
if (expiration > RynthClock.Now)
_ramBuffTimers[family] = new RamTimerInfo { Expiration = expiration, SpellLevel = level, SpellName = name };
}
}
@ -1070,7 +1070,7 @@ public partial class BuffManager : IDisposable
internal bool WantsHealNow()
{
if (!_settings.IsMacroRunning || _vitals.MaxHealth == 0) return false;
if (DateTime.Now < _healUnavailableUntil) return false;
if (RynthClock.Now < _healUnavailableUntil) return false;
return HealthUnderAnyLine(_vitals.HealthPct, _vitals.StaminaPct);
}
@ -1133,7 +1133,7 @@ public partial class BuffManager : IDisposable
{
if (_pendingSpellId != 0 && _pendingSpellId == _pendingVitalSpellId && _pendingVitalLabel.Length > 0)
return _pendingVitalLabel;
if (_kitUsedAt != DateTime.MinValue && (DateTime.Now - _kitUsedAt).TotalMilliseconds < KitResultTimeoutMs)
if (_kitUsedAt != DateTime.MinValue && (RynthClock.Now - _kitUsedAt).TotalMilliseconds < KitResultTimeoutMs)
return _kitIsStamina ? LabelStamina : LabelHealing;
if (_isHealingSelf || WantsHealNow()) return LabelHealing;
if (_pendingSpellId != 0) return LabelBuffing;
@ -1235,7 +1235,7 @@ public partial class BuffManager : IDisposable
/// <summary>A heal (kit or spell) sent earlier hasn't resolved yet.</summary>
private bool HealInFlight() =>
(_pendingSpellId != 0 && _pendingSpellId == _pendingVitalSpellId && _pendingVitalLabel == LabelHealing)
|| (_kitUsedAt != DateTime.MinValue && !_kitIsStamina && (DateTime.Now - _kitUsedAt).TotalMilliseconds < KitResultTimeoutMs);
|| (_kitUsedAt != DateTime.MinValue && !_kitIsStamina && (RynthClock.Now - _kitUsedAt).TotalMilliseconds < KitResultTimeoutMs);
public void OnHeartbeat()
{
@ -1255,7 +1255,7 @@ public partial class BuffManager : IDisposable
if (track)
{
string hold = _healHold;
if (hold.Length == 0 && DateTime.Now < _healUnavailableUntil) hold = "heal backoff (nothing could heal)";
if (hold.Length == 0 && RynthClock.Now < _healUnavailableUntil) hold = "heal backoff (nothing could heal)";
_healLatency.EndTick(Now, hold, _healHoldDetail, ArbiterActivity);
}
}
@ -1276,7 +1276,7 @@ public partial class BuffManager : IDisposable
// user toggled the macro off mid-experiment, we still want to capture and log them.
// Drain any pending diagnostics whose 2s post-cast window has elapsed.
while (_pendingDiagnostics.Count > 0 &&
(DateTime.Now - _pendingDiagnostics.Peek().CastedAt).TotalSeconds >= 2.0)
(RynthClock.Now - _pendingDiagnostics.Peek().CastedAt).TotalSeconds >= 2.0)
{
var diag = _pendingDiagnostics.Dequeue();
LogPostCastDiff(diag);
@ -1315,13 +1315,13 @@ public partial class BuffManager : IDisposable
bool buffsHeldForRefresh = false;
if (!_liveBuffsRefreshed)
{
if ((DateTime.Now - _lastLiveRefreshAttempt).TotalMilliseconds > 1000)
if ((RynthClock.Now - _lastLiveRefreshAttempt).TotalMilliseconds > 1000)
{
_lastLiveRefreshAttempt = DateTime.Now;
_lastLiveRefreshAttempt = RynthClock.Now;
int n = RefreshFromLiveMemory();
if (n >= 0)
{
if (_loginRefreshStartAt == DateTime.MinValue) _loginRefreshStartAt = DateTime.Now;
if (_loginRefreshStartAt == DateTime.MinValue) _loginRefreshStartAt = RynthClock.Now;
// Only trust the snapshot once the registry stops growing
// (two equal 1s reads), so we don't open the gate on a
// half-streamed set and rebuff buffs that are still landing.
@ -1329,7 +1329,7 @@ public partial class BuffManager : IDisposable
// its registry is complete: the first read is trusted (CarriedOverSession), unless
// it is empty (a read that found nothing yet must not wipe every timer).
bool stable = (n == _lastLoginRefreshCount);
bool timedOut = (DateTime.Now - _loginRefreshStartAt).TotalMilliseconds > LoginRefreshMaxWaitMs;
bool timedOut = (RynthClock.Now - _loginRefreshStartAt).TotalMilliseconds > LoginRefreshMaxWaitMs;
bool carried = CarriedOverSession && n > 0;
_lastLoginRefreshCount = n;
if (stable || timedOut || carried)
@ -1358,9 +1358,9 @@ public partial class BuffManager : IDisposable
// expire normally — causing NeedsAnyBuff() to return false while the char
// is completely unbuffed. Re-read from live AC memory every 30s to detect
// this gap and clear stale timers so rebuffing resumes promptly.
if ((DateTime.Now - _lastPeriodicRefreshAt).TotalMilliseconds > PeriodicRefreshIntervalMs)
if ((RynthClock.Now - _lastPeriodicRefreshAt).TotalMilliseconds > PeriodicRefreshIntervalMs)
{
_lastPeriodicRefreshAt = DateTime.Now;
_lastPeriodicRefreshAt = RynthClock.Now;
int n = RefreshFromLiveMemory();
if (n >= 0)
_host.Log($"[BuffDiag] periodic sync: {n} active enchantment(s) in RAM timers.");
@ -1377,7 +1377,7 @@ public partial class BuffManager : IDisposable
// CheckVitals heal now. A late confirmation still lands through the enchantment events;
// at worst a buff is recast later (2026-10-04).
if (_pendingSpellId != 0 && _pendingSpellId != _pendingVitalSpellId && WantsHealNow()
&& (DateTime.Now - _lastCastAttempt).TotalMilliseconds >= HealInterruptMinMs
&& (RynthClock.Now - _lastCastAttempt).TotalMilliseconds >= HealInterruptMinMs
&& CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s)) && !BusyHoldsHeal())
{
_host.Log($"[BuffDiag] health {_vitals.HealthPct}% under a heal line: released pending buff id={_pendingSpellId} to heal first.");
@ -1421,14 +1421,14 @@ public partial class BuffManager : IDisposable
// SELF-BUFF: confirm against the live registry once the cast has
// settled. (OnEnchantmentAdded usually clears pending faster; this
// poll is the authoritative fallback when the hook doesn't fire.)
double sinceCastMs = (DateTime.Now - _lastCastAttempt).TotalMilliseconds;
double sinceCastMs = (RynthClock.Now - _lastCastAttempt).TotalMilliseconds;
if (sinceCastMs > SelfBuffConfirmMs
&& (DateTime.Now - _lastSelfBuffPollAt).TotalMilliseconds > 250)
&& (RynthClock.Now - _lastSelfBuffPollAt).TotalMilliseconds > 250)
{
_lastSelfBuffPollAt = DateTime.Now;
_lastSelfBuffPollAt = RynthClock.Now;
RefreshFromLiveMemory();
bool active = _ramBuffTimers.TryGetValue(pendingSpell.Family, out RamTimerInfo? st)
&& st.Expiration > DateTime.Now;
&& st.Expiration > RynthClock.Now;
// A top-off (auto batch), Force Rebuff or tier upgrade casts over a
// buff that is still on, so "active" is true at the first poll
// whatever happened: a fizzle counted as landed, the buff wasn't
@ -1495,7 +1495,7 @@ public partial class BuffManager : IDisposable
bool parked = false;
if (noShowCount >= SilentNoShowThreshold)
{
_buffFailCooldownUntil[fam] = DateTime.Now + SilentNoShowCooldown;
_buffFailCooldownUntil[fam] = RynthClock.Now + SilentNoShowCooldown;
parked = true;
}
@ -1561,7 +1561,7 @@ public partial class BuffManager : IDisposable
_silentNoShowCounts[fam] = noShowCount;
if (noShowCount >= SilentNoShowThreshold)
{
_buffFailCooldownUntil[fam] = DateTime.Now + SilentNoShowCooldown;
_buffFailCooldownUntil[fam] = RynthClock.Now + SilentNoShowCooldown;
parked = true;
}
}
@ -1583,7 +1583,7 @@ public partial class BuffManager : IDisposable
// A due recovery retry (BuffManager.RecoveryRetry.cs) gets past Spell Interval, for the vitals
// step only: the buffs after it still wait (intervalHeld below). A stale episode ends first.
ExpireRecoveryEpisode();
bool intervalHeld = (DateTime.Now - _lastCastAttempt).TotalMilliseconds < _settings.SpellCastIntervalMs;
bool intervalHeld = (RynthClock.Now - _lastCastAttempt).TotalMilliseconds < _settings.SpellCastIntervalMs;
if (intervalHeld && !RecoveryRetryDue())
{
Hold("cast interval");
@ -1698,9 +1698,9 @@ public partial class BuffManager : IDisposable
return;
}
LastBuffSkipReason = $"mana {_vitals.ManaPct}% under Get Mana At {manaFloor}%";
if ((DateTime.Now - _lastManaFloorLogAt).TotalSeconds >= 30)
if ((RynthClock.Now - _lastManaFloorLogAt).TotalSeconds >= 30)
{
_lastManaFloorLogAt = DateTime.Now;
_lastManaFloorLogAt = RynthClock.Now;
_host.Log($"[RynthAi] Vitals: buffing waits: mana {_vitals.ManaPct}% is under Get Mana At {manaFloor}%, stamina {_vitals.StaminaPct}%, and nothing refilled it (Stamina to Mana / stamina / potion: {Why(_vitalWhy)})");
}
return;
@ -1720,15 +1720,15 @@ public partial class BuffManager : IDisposable
return;
}
if (DateTime.Now < _busyBackoffUntil)
if (RynthClock.Now < _busyBackoffUntil)
{
LastBuffSkipReason = $"too-busy backoff ({(_busyBackoffUntil - DateTime.Now).TotalMilliseconds:0}ms left, streak={_busyRefusalStreak})";
LastBuffSkipReason = $"too-busy backoff ({(_busyBackoffUntil - RynthClock.Now).TotalMilliseconds:0}ms left, streak={_busyRefusalStreak})";
return;
}
if (DateTime.Now < _lowManaPauseUntil)
if (RynthClock.Now < _lowManaPauseUntil)
{
LastBuffSkipReason = $"not enough mana ({(_lowManaPauseUntil - DateTime.Now).TotalMilliseconds:0}ms left)";
LastBuffSkipReason = $"not enough mana ({(_lowManaPauseUntil - RynthClock.Now).TotalMilliseconds:0}ms left)";
return;
}
@ -1816,7 +1816,7 @@ public partial class BuffManager : IDisposable
// Give the refresh time to reach the registry before judging. A cast
// issued seconds ago legitimately still reads its old timer.
if (!_castIssuedAtByFamily.TryGetValue(family, out DateTime castAt)
|| (DateTime.Now - castAt).TotalMilliseconds < AuditSettleMs)
|| (RynthClock.Now - castAt).TotalMilliseconds < AuditSettleMs)
continue;
// The expiry moved forward, so the cast DID land — this family is
@ -1842,7 +1842,7 @@ public partial class BuffManager : IDisposable
}
_unsatisfiedStrikes.Remove(family);
_buffFailCooldownUntil[family] = DateTime.Now + SilentNoShowCooldown;
_buffFailCooldownUntil[family] = RynthClock.Now + SilentNoShowCooldown;
// Spell out the stored timer: the two causes that produce this look
// identical from the outside. Either a lower-tier enchantment is
@ -1851,7 +1851,7 @@ public partial class BuffManager : IDisposable
// it is "due for recast" the instant it lands. The numbers below
// separate them at a glance.
string stored = _ramBuffTimers.TryGetValue(family, out RamTimerInfo? t)
? $"stored='{t.SpellName}' lvl={t.SpellLevel} remainSec={(t.IsPermanent ? "permanent" : (t.Expiration - DateTime.Now).TotalSeconds.ToString("F0"))}"
? $"stored='{t.SpellName}' lvl={t.SpellLevel} remainSec={(t.IsPermanent ? "permanent" : (t.Expiration - RynthClock.Now).TotalSeconds.ToString("F0"))}"
: "no timer entry";
_host.Log($"[BuffDiag] batch audit: '{name}' (id={spellId}, fam={family}) lands but never reads active after {UnsatisfiedStrikeThreshold} batches — " +
$"parking {SilentNoShowCooldown.TotalMinutes:0}min so it can't drive continuous rebuff cycles. " +
@ -1935,7 +1935,7 @@ public partial class BuffManager : IDisposable
_isHealingSelf = true;
return true;
}
_healUnavailableUntil = DateTime.Now.AddMilliseconds(HealUnavailableMs);
_healUnavailableUntil = RynthClock.Now.AddMilliseconds(HealUnavailableMs);
Hold("nothing could heal", $"kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(potionWhy)}");
LogNoHeal($"health {curHealthPct}% < {(inCombat ? "Heal At" : "Top Off HP")} {hpThreshold}% but nothing healed: " +
$"kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(potionWhy)}");
@ -1949,7 +1949,7 @@ public partial class BuffManager : IDisposable
// (e.g. an emergency line above Heal At whose kit failed), back off so WantsHealNow
// doesn't hold the tick for a heal that can't happen.
if (HealthUnderAnyLine(curHealthPct, curStamPct))
_healUnavailableUntil = DateTime.Now.AddMilliseconds(HealUnavailableMs);
_healUnavailableUntil = RynthClock.Now.AddMilliseconds(HealUnavailableMs);
// Mana: under Get Mana At / Top Off Mana, or (a caster) under the reserve kept for Stamina
// to Mana (ManaUnderLine; see "Mana reserve" at the top).
@ -1978,7 +1978,7 @@ public partial class BuffManager : IDisposable
return true;
}
// Nothing can refill it (no Stamina to Mana, parked, no potion): don't hold the bot for it.
if (inCombat) _manaUnavailableUntil = DateTime.Now.AddMilliseconds(ManaUnavailableMs);
if (inCombat) _manaUnavailableUntil = RynthClock.Now.AddMilliseconds(ManaUnavailableMs);
}
else _manaStarvedLogged = false;
// Stamina kits first, like healing kits for health: Lucy carried Greater Stamina Kits
@ -2067,7 +2067,7 @@ public partial class BuffManager : IDisposable
{
bool potionFirst = CurrentCombatMode != CombatMode.Magic;
bool potionJustDrunk = potionFirst && _settings.UsePotions
&& (DateTime.Now - _lastPotionAt).TotalMilliseconds < 2500
&& (RynthClock.Now - _lastPotionAt).TotalMilliseconds < 2500
&& HasListedPotion("StaminaPotion", "Stamina");
return !potionJustDrunk
&& (AttemptStaminaKitUse()
@ -2147,13 +2147,13 @@ public partial class BuffManager : IDisposable
{
int emergencyAt = _settings.EmergencyHealAt;
if (emergencyAt <= 0 || _vitals.HealthPct > emergencyAt) return;
if ((DateTime.Now - _lastPendingEmergencyHealAt).TotalMilliseconds < 2500) return;
if ((RynthClock.Now - _lastPendingEmergencyHealAt).TotalMilliseconds < 2500) return;
if (IsAwaitingCastResolution() || BusyHoldsHeal() || KitPending()) return;
if (!CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s))) return;
if (!ActionPacer.MayStart(_host, "Buff", HealNeed.Emergency, out _)) return;
if (AttemptHealthKitUse() || AttemptPotion("HealthPotion"))
{
_lastPendingEmergencyHealAt = DateTime.Now;
_lastPendingEmergencyHealAt = RynthClock.Now;
_isHealingSelf = true;
}
}
@ -2176,8 +2176,8 @@ public partial class BuffManager : IDisposable
/// </summary>
private void LogNoHeal(string line)
{
if ((DateTime.Now - _lastNoHealLogAt).TotalSeconds < 10) return;
_lastNoHealLogAt = DateTime.Now;
if ((RynthClock.Now - _lastNoHealLogAt).TotalSeconds < 10) return;
_lastNoHealLogAt = RynthClock.Now;
_host.Log("[RynthAi] Vitals: " + line);
}
@ -2188,12 +2188,12 @@ public partial class BuffManager : IDisposable
// gesture from finishing (Drakkon, 2026-10-05: Stamina to Mana every 0.4 s until he was
// moved). Mana and stamina wait out the backoff; a heal still retries, but no faster
// than BusyHealRetryMs. Waiting counts as handled, so no potion is drunk meanwhile.
if (DateTime.Now < _busyBackoffUntil)
if (RynthClock.Now < _busyBackoffUntil)
{
bool healthSpell = baseName is "Heal Self" or "Stamina to Health Self";
if (!healthSpell || (DateTime.Now - _lastCastAttempt).TotalMilliseconds < BusyHealRetryMs)
if (!healthSpell || (RynthClock.Now - _lastCastAttempt).TotalMilliseconds < BusyHealRetryMs)
{
_vitalWhy = $"AC too busy, waiting {(_busyBackoffUntil - DateTime.Now).TotalMilliseconds:0} ms";
_vitalWhy = $"AC too busy, waiting {(_busyBackoffUntil - RynthClock.Now).TotalMilliseconds:0} ms";
_healWaitKind = "too-busy backoff";
return true;
}
@ -2212,9 +2212,9 @@ public partial class BuffManager : IDisposable
if (spellId == 0 && baseName is "Heal Self" or "Stamina to Health Self")
{
spellId = _spellManager.GetSelfSpellIdAboveAllowedTier(baseName, AcSkillType.LifeMagic);
if (spellId != 0 && (DateTime.Now - _lastAboveTierLog).TotalSeconds >= 30)
if (spellId != 0 && (RynthClock.Now - _lastAboveTierLog).TotalSeconds >= 30)
{
_lastAboveTierLog = DateTime.Now;
_lastAboveTierLog = RynthClock.Now;
_host.Log($"[RynthAi] Vitals: no '{baseName}' at the tiers Life Magic allows now; " +
$"trying {SpellTableStub.GetById(spellId)?.Name ?? spellId.ToString()} (may fizzle).");
}
@ -2255,12 +2255,12 @@ public partial class BuffManager : IDisposable
int family = SpellTableStub.GetById(spellId)?.Family ?? 0;
if (family != 0
&& _buffFailCooldownUntil.TryGetValue(family, out DateTime coolUntil)
&& DateTime.Now < coolUntil)
return VitalNo($"parked for {(coolUntil - DateTime.Now).TotalSeconds:0} s more after a refusal or no-show");
&& RynthClock.Now < coolUntil)
return VitalNo($"parked for {(coolUntil - RynthClock.Now).TotalSeconds:0} s more after a refusal or no-show");
// A recovery vital retried after a mana refusal: its retry gap and the per-second ceiling.
if (IsRecoveryVital(what) && RecoveryRetryHolds(family) is { Length: > 0 } recoveryWhy)
return VitalNo(recoveryWhy);
if (CurrentCombatMode != CombatMode.Magic && DateTime.Now < _vitalSwapBlockedUntil)
if (CurrentCombatMode != CombatMode.Magic && RynthClock.Now < _vitalSwapBlockedUntil)
return VitalNo("wand swap blocked, retrying shortly");
bool urgentHeal = label == LabelHealing && (_oneTouchHealthScope || HealIsUrgent(_vitals.HealthPct, _vitals.StaminaPct));
if (!EnsureMagicMode(urgentHeal: urgentHeal))
@ -2268,7 +2268,7 @@ public partial class BuffManager : IDisposable
if (!_magicModeBlocked) { _healWaitKind = "wand swap / Magic stance"; return true; } // a swap step is in flight: yield the tick
// The switch can't complete now (no room to put the bow away, the wand won't
// wield): not handled, so the kit/potion after this gets its turn.
_vitalSwapBlockedUntil = DateTime.Now.AddSeconds(VitalSwapBlockedRetrySec);
_vitalSwapBlockedUntil = RynthClock.Now.AddSeconds(VitalSwapBlockedRetrySec);
return VitalNo("couldn't switch to Magic mode");
}
// A locally rejected cast sends nothing, so no chat or registry change will
@ -2280,7 +2280,7 @@ public partial class BuffManager : IDisposable
_pendingVitalBase = what;
bool castOk = _host.CastSpellFor(targetId, spellId, "Buff",
SpellTableStub.GetById(spellId)?.Name ?? what);
_lastCastAttempt = DateTime.Now;
_lastCastAttempt = RynthClock.Now;
if (!castOk)
{
_pendingSpellId = 0;
@ -2288,7 +2288,7 @@ public partial class BuffManager : IDisposable
}
sent = true;
_vitalActionsSent++;
_lastVitalCastAt = DateTime.Now;
_lastVitalCastAt = RynthClock.Now;
if (IsRecoveryVital(what)) NoteRecoveryAttempt();
NoteCastIssued(spellId);
if (_pendingVitalLabel == LabelMana) _manaStarvedLogged = false; // the next starved spell logs again
@ -2334,7 +2334,7 @@ public partial class BuffManager : IDisposable
private bool AttemptPotion(bool listedOnly, params string[] types)
{
if (!_settings.UsePotions || _worldObjectCache == null) return VitalNo("Use Potions is off");
if ((DateTime.Now - _lastPotionAt).TotalMilliseconds < 2500) return VitalNo("one drunk under 2.5 s ago");
if ((RynthClock.Now - _lastPotionAt).TotalMilliseconds < 2500) return VitalNo("one drunk under 2.5 s ago");
foreach (var rule in _settings.ConsumableRules)
{
if (Array.FindIndex(types, t => t.Equals(rule.Type, StringComparison.OrdinalIgnoreCase)) < 0) continue;
@ -2344,9 +2344,9 @@ public partial class BuffManager : IDisposable
if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy);
_host.Log($"[RynthAi] Vitals: drinking {rule.Name} ({rule.Type})" + (potion.Id != rule.Id ? " from a new stack." : "."));
_host.UseFor(unchecked((uint)potion.Id), "Buff", $"vitals: drink {rule.Name} ({rule.Type}) from the Items list");
_lastPotionAt = DateTime.Now;
_lastPotionAt = RynthClock.Now;
_vitalActionsSent++;
_lastCastAttempt = DateTime.Now;
_lastCastAttempt = RynthClock.Now;
if (IsHealthPotionType(types)) NoteHealSent(rule.Name);
return true;
}
@ -2361,9 +2361,9 @@ public partial class BuffManager : IDisposable
if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy);
_host.Log($"[RynthAi] Vitals: using {wo.Name} from the pack ({kind}).");
_host.UseFor(unchecked((uint)wo.Id), "Buff", $"vitals: {kind} potion from the pack");
_lastPotionAt = DateTime.Now;
_lastPotionAt = RynthClock.Now;
_vitalActionsSent++;
_lastCastAttempt = DateTime.Now;
_lastCastAttempt = RynthClock.Now;
if (IsHealthPotionType(types)) NoteHealSent(wo.Name ?? "health potion");
return true;
}
@ -2390,8 +2390,8 @@ public partial class BuffManager : IDisposable
private void TryUseBuffItems()
{
if (!_settings.UseBuffItems || _worldObjectCache == null || !_host.HasReadPlayerEnchantments) return;
if ((DateTime.Now - _lastBuffItemCheck).TotalMilliseconds < 3000) return;
_lastBuffItemCheck = DateTime.Now;
if ((RynthClock.Now - _lastBuffItemCheck).TotalMilliseconds < 3000) return;
_lastBuffItemCheck = RynthClock.Now;
if (!_host.CanCastNow) return;
var active = new HashSet<uint>();
@ -2408,13 +2408,13 @@ public partial class BuffManager : IDisposable
bool on = false;
foreach (uint s in spells) if (active.Contains(s)) { on = true; break; }
if (on) break;
if (_buffItemUsedAt.TryGetValue(name, out DateTime at) && (DateTime.Now - at).TotalSeconds < 15) break;
_buffItemUsedAt[name] = DateTime.Now;
if (_buffItemUsedAt.TryGetValue(name, out DateTime at) && (RynthClock.Now - at).TotalSeconds < 15) break;
_buffItemUsedAt[name] = RynthClock.Now;
// The same buff from the other Benediction counts as done too.
foreach (var (other, os) in BuffItems) if (os == spells || os[0] == spells[0]) _buffItemUsedAt[other] = DateTime.Now;
foreach (var (other, os) in BuffItems) if (os == spells || os[0] == spells[0]) _buffItemUsedAt[other] = RynthClock.Now;
_host.Log($"[RynthAi] Buff item: using {wo.Name} (its buff isn't on).");
_host.UseFor(unchecked((uint)wo.Id), "Buff", $"buff item: the buff of {wo.Name} is not on");
_lastCastAttempt = DateTime.Now;
_lastCastAttempt = RynthClock.Now;
return;
}
}
@ -2433,8 +2433,8 @@ public partial class BuffManager : IDisposable
{
int want = _settings.MakeRationsBelow;
if (want <= 0 || _worldObjectCache == null || !_host.HasUseObjectOn) return;
if (DateTime.Now < _rationRestUntil) return;
if ((DateTime.Now - _lastRationAttempt).TotalSeconds < 6) return;
if (RynthClock.Now < _rationRestUntil) return;
if ((RynthClock.Now - _lastRationAttempt).TotalSeconds < 6) return;
if (_combatManager?.HasCloseThreat(Math.Max(1, _settings.MonsterRange)) == true) return;
if (!_host.CanCastNow) return;
@ -2462,13 +2462,13 @@ public partial class BuffManager : IDisposable
{
_rationTries = 0;
_rationCountBefore = -1;
_rationRestUntil = DateTime.Now.AddMinutes(10);
_rationRestUntil = RynthClock.Now.AddMinutes(10);
_host.WriteToChat("[RynthAi] Couldn't cook field rations (3 tries). Is your Cooking high enough? Trying again in 10 minutes.", 2);
return;
}
_rationCountBefore = have;
_lastRationAttempt = DateTime.Now;
_lastCastAttempt = DateTime.Now;
_lastRationAttempt = RynthClock.Now;
_lastCastAttempt = RynthClock.Now;
_host.Log($"[RynthAi] Rations: {have} left (< {want}), cooking with the Cooking Pot.");
_host.UseOnFor(unchecked((uint)pot), unchecked((uint)dried), "Buff", $"rations: {have} left, cooking more");
}
@ -2504,7 +2504,7 @@ public partial class BuffManager : IDisposable
// around a teleport) leaves no pacing state, so the next tick asks again.
if (_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the healing kit"))
{
_lastCastAttempt = DateTime.Now;
_lastCastAttempt = RynthClock.Now;
_healWaitKind = "peace mode for the kit";
}
return true; // use the kit next tick, once in peace mode
@ -2515,7 +2515,7 @@ public partial class BuffManager : IDisposable
if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy);
if (fromPack) _host.Log($"[RynthAi] Vitals: using {kit.Name} from the pack.");
_host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: healing kit on yourself");
_lastCastAttempt = DateTime.Now;
_lastCastAttempt = RynthClock.Now;
MarkKitUsed();
NoteHealSent(kit.Name ?? "healing kit");
return true;
@ -2538,7 +2538,7 @@ public partial class BuffManager : IDisposable
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode)
{
if (_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the stamina kit"))
_lastCastAttempt = DateTime.Now;
_lastCastAttempt = RynthClock.Now;
return true; // use the kit next tick, once in peace mode
}
uint playerId = _host.GetPlayerId();
@ -2547,7 +2547,7 @@ public partial class BuffManager : IDisposable
_host.Log($"[RynthAi] Vitals: using {kit.Name} from the pack.");
_host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: stamina kit on yourself");
_vitalActionsSent++;
_lastCastAttempt = DateTime.Now;
_lastCastAttempt = RynthClock.Now;
MarkKitUsed(stamina: true);
return true;
}
@ -2580,7 +2580,7 @@ public partial class BuffManager : IDisposable
internal void MarkKitUsed(bool stamina = false) // internal for the host tests (VitalsTests)
{
_kitUsedAt = DateTime.Now;
_kitUsedAt = RynthClock.Now;
_kitLandedAt = DateTime.MinValue;
_kitIsStamina = stamina;
_kitSeqAtUse = UseDoneSeqNow();
@ -2596,7 +2596,7 @@ public partial class BuffManager : IDisposable
KitRefused($"UseDone error 0x{err:X}");
return false;
}
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
bool done = _kitLandedAt != DateTime.MinValue
? (now - _kitLandedAt).TotalMilliseconds >= KitLandGraceMs
: (now - _kitUsedAt).TotalMilliseconds >= KitResultTimeoutMs;
@ -2608,9 +2608,9 @@ public partial class BuffManager : IDisposable
private void KitRefused(string why)
{
if (_kitUsedAt == DateTime.MinValue || _kitLandedAt != DateTime.MinValue) return;
double ms = (DateTime.Now - _kitUsedAt).TotalMilliseconds;
double ms = (RynthClock.Now - _kitUsedAt).TotalMilliseconds;
_kitUsedAt = DateTime.MinValue;
_kitRefusedAt = DateTime.Now;
_kitRefusedAt = RynthClock.Now;
KitRefusals++;
_host.Log($"[RynthAi] Vitals: the {(_kitIsStamina ? "stamina" : "healing")} kit was refused {ms:0} ms after use ({why}): " +
$"no result will come, vitals carry on (next kit in {KitRetryAfterRefusalMs:0} ms).");
@ -2619,7 +2619,7 @@ public partial class BuffManager : IDisposable
/// <summary>True (with why) while a kit must wait after its last refusal.</summary>
private bool KitRetryWait(out string why)
{
double since = (DateTime.Now - _kitRefusedAt).TotalMilliseconds;
double since = (RynthClock.Now - _kitRefusedAt).TotalMilliseconds;
if (since < KitRetryAfterRefusalMs)
{
why = $"kit refused {since:0} ms ago, retrying shortly";
@ -2685,9 +2685,9 @@ public partial class BuffManager : IDisposable
double chance = 1.0 - 1.0 / (1.0 + Math.Exp(0.03 * (skill - difficulty)));
int pct = (int)Math.Floor(Math.Clamp(chance, 0, 1) * 100);
bool ok = pct >= minPct;
if (!ok && (DateTime.Now - _lastKitChanceLog).TotalSeconds >= 10)
if (!ok && (RynthClock.Now - _lastKitChanceLog).TotalSeconds >= 10)
{
_lastKitChanceLog = DateTime.Now;
_lastKitChanceLog = RynthClock.Now;
_host.Log($"[RynthAi] Vitals: {kitName} would work {pct}% of the time on {missing} missing (skill {skill} vs {difficulty}), under {minPct}%: using the spell.");
}
return ok;
@ -2747,7 +2747,7 @@ public partial class BuffManager : IDisposable
// batch starts → clears cooldown → cast again → silent no-show → re-park).
private bool AnyBuffBelowThreshold(List<string> desiredBuffs, int thresholdSec)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
foreach (string buffBaseName in desiredBuffs)
{
AcSkillType castSkill = SkillFor(buffBaseName);
@ -2773,7 +2773,7 @@ public partial class BuffManager : IDisposable
int cut = line.IndexOf(" — ", StringComparison.Ordinal);
string reason = cut >= 0 ? line.Substring(cut, Math.Min(18, line.Length - cut)) : line;
string key = buff + "|" + reason;
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (_diagSkipLoggedAt.TryGetValue(key, out DateTime at) && (now - at).TotalSeconds < 60) return;
_diagSkipLoggedAt[key] = now;
_host.Log(line);
@ -2838,10 +2838,10 @@ public partial class BuffManager : IDisposable
int buffFamily = SpellTableStub.GetById(spellId)?.Family ?? 0;
if (buffFamily != 0
&& _buffFailCooldownUntil.TryGetValue(buffFamily, out DateTime coolUntil)
&& DateTime.Now < coolUntil)
&& RynthClock.Now < coolUntil)
{
LastBuffSkipReason = $"fail-cooldown: {buffBaseName} (fam={buffFamily}, {(coolUntil - DateTime.Now).TotalSeconds:0}s)";
if (diagnose) DiagSkip(buffBaseName, $"[FR] skip '{buffBaseName}' (id={spellId}) — hard-fail cooldown {(coolUntil - DateTime.Now).TotalSeconds:0}s");
LastBuffSkipReason = $"fail-cooldown: {buffBaseName} (fam={buffFamily}, {(coolUntil - RynthClock.Now).TotalSeconds:0}s)";
if (diagnose) DiagSkip(buffBaseName, $"[FR] skip '{buffBaseName}' (id={spellId}) — hard-fail cooldown {(coolUntil - RynthClock.Now).TotalSeconds:0}s");
continue;
}
@ -2856,7 +2856,7 @@ public partial class BuffManager : IDisposable
// -> combat runs. Buffing stays top priority; only the impossible
// family is shelved, time-boxed, and auto-retried.
if (buffFamily != 0)
_buffFailCooldownUntil[buffFamily] = DateTime.Now.AddSeconds(BuffFailCooldownSec);
_buffFailCooldownUntil[buffFamily] = RynthClock.Now.AddSeconds(BuffFailCooldownSec);
LastBuffSkipReason = $"wand-swap exhausted: {buffBaseName} (fam={buffFamily})";
_host.Log($"[WieldGate] wand-swap exhausted for '{buffBaseName}' (fam={buffFamily}) — parking {BuffFailCooldownSec:0}s, fighting unbuffed");
continue;
@ -2891,7 +2891,7 @@ public partial class BuffManager : IDisposable
if (buffFamily != 0)
{
_lastCastSpellIdByFamily[buffFamily] = spellId;
_castIssuedAtByFamily[buffFamily] = DateTime.Now;
_castIssuedAtByFamily[buffFamily] = RynthClock.Now;
_expiryAtCastByFamily[buffFamily] = CurrentExpiryFor(buffFamily);
}
@ -2917,7 +2917,7 @@ public partial class BuffManager : IDisposable
_host.Log($"[BuffChain] '{spellInfo?.Name ?? buffBaseName}' goes without waiting for the animation: {_fastChainWhy}");
int seqAtSend = UseDoneSeqNow();
bool castOk = _host.CastSpellFor((uint)_host.GetPlayerId(), spellId, "Buff", spellInfo?.Name ?? buffBaseName);
_lastCastAttempt = DateTime.Now;
_lastCastAttempt = RynthClock.Now;
if (castOk)
{
NoteCastIssued(spellId);
@ -2992,7 +2992,7 @@ public partial class BuffManager : IDisposable
{
int level = GetSpellLevel(spellInfo);
double duration = GetCustomSpellDuration(level);
var now = DateTime.Now;
var now = RynthClock.Now;
_itemSpellTimers[spellInfo.Family] = new ItemSpellRecord
{
CastAt = now,
@ -3015,7 +3015,7 @@ public partial class BuffManager : IDisposable
{
var diag = new CastDiagnostic
{
CastedAt = DateTime.Now,
CastedAt = RynthClock.Now,
SpellName = spellInfo.Name,
SpellId = spellInfo.Id,
SpellFamily = spellInfo.Family,
@ -3205,12 +3205,12 @@ public partial class BuffManager : IDisposable
LogArmorRecast(targetSpell, $"tier-upgrade recordedLvl={itemTimer.SpellLevel} < targetLvl={targetLevel} (recorded='{itemTimer.SpellName}')");
return false;
}
if (DateTime.Now < itemTimer.ExpiresAt.AddSeconds(-rebufferSec))
if (RynthClock.Now < itemTimer.ExpiresAt.AddSeconds(-rebufferSec))
{
_lastArmorRecastReason.Remove(targetSpell.Family); // clear so next recast re-logs
return true;
}
double remainSec = (itemTimer.ExpiresAt - DateTime.Now).TotalSeconds;
double remainSec = (itemTimer.ExpiresAt - RynthClock.Now).TotalSeconds;
LogArmorRecast(targetSpell, $"expiry-window remainSec={remainSec:F0} threshold={rebufferSec} (recorded='{itemTimer.SpellName}' lvl={itemTimer.SpellLevel} expiresAt={itemTimer.ExpiresAt:HH:mm:ss})");
}
else
@ -3247,7 +3247,7 @@ public partial class BuffManager : IDisposable
LogPlayerRecast(targetSpell, $"tier-upgrade storedLvl={timer.SpellLevel} < effTarget={effectiveTarget} (nominal={targetLevel}, achievedCap={(_familyAchievedTier.TryGetValue(targetSpell.Family, out int a2) ? a2 : -1)}, stored='{timer.SpellName}')");
return false;
}
if (DateTime.Now < timer.Expiration.AddSeconds(-rebufferSec))
if (RynthClock.Now < timer.Expiration.AddSeconds(-rebufferSec))
{
_lastArmorRecastReason.Remove(targetSpell.Family);
return true;
@ -3261,7 +3261,7 @@ public partial class BuffManager : IDisposable
_lastArmorRecastReason.Remove(targetSpell.Family);
return true;
}
double remainSec = (timer.Expiration - DateTime.Now).TotalSeconds;
double remainSec = (timer.Expiration - RynthClock.Now).TotalSeconds;
LogPlayerRecast(targetSpell, $"expiry-window remainSec={remainSec:F0} threshold={rebufferSec} storedLvl={timer.SpellLevel} exp={timer.Expiration:HH:mm:ss} (stored='{timer.SpellName}')");
}
else if (timer != null)
@ -3326,7 +3326,7 @@ public partial class BuffManager : IDisposable
/// <summary>True while upgrades of <paramref name="family"/> are parked after repeated silent no-shows.</summary>
private bool UpgradeParked(int family)
=> family != 0 && _upgradeParkedUntil.TryGetValue(family, out DateTime until) && DateTime.Now < until;
=> family != 0 && _upgradeParkedUntil.TryGetValue(family, out DateTime until) && RynthClock.Now < until;
/// <summary>
/// The pending upgrade <paramref name="spellId"/> was a silent no-show (nothing showed in the
@ -3342,7 +3342,7 @@ public partial class BuffManager : IDisposable
if (count >= UpgradeNoShowThreshold)
{
_upgradeNoShowCounts.Remove(family);
_upgradeParkedUntil[family] = DateTime.Now + UpgradeParkCooldown;
_upgradeParkedUntil[family] = RynthClock.Now + UpgradeParkCooldown;
_host.Log($"[Buff] upgrade of family {family} ({SpellTableStub.GetById(spellId)?.Name}) never showed {count} times in a row: upgrades of it parked {UpgradeParkCooldown.TotalMinutes:0}min " +
"(the level it was cast over still refreshes as a normal cast; the family is not blacklisted).");
}
@ -3386,9 +3386,9 @@ public partial class BuffManager : IDisposable
if (_isForceRebuffing && _forceRebuffCastFamilies.Contains(family)) on = CastLevelThisRun(family);
else if (_ramBuffTimers.TryGetValue(family, out RamTimerInfo? t)
&& !(t.IsPermanent && _settings.CastBuffsOverItemBuffs)
&& (t.IsPermanent || t.Expiration > DateTime.Now))
&& (t.IsPermanent || t.Expiration > RynthClock.Now))
on = t.SpellLevel;
else if (_itemSpellTimers.TryGetValue(family, out ItemSpellRecord? it) && it.ExpiresAt > DateTime.Now)
else if (_itemSpellTimers.TryGetValue(family, out ItemSpellRecord? it) && it.ExpiresAt > RynthClock.Now)
on = it.SpellLevel;
return on > 0 && on < newLevel ? on : 0;
}
@ -3401,7 +3401,7 @@ public partial class BuffManager : IDisposable
{
if (!_familyLiveEntries.TryGetValue(family, out var entries)) return false;
bool ignorePermanent = _settings.CastBuffsOverItemBuffs;
DateTime due = DateTime.Now.AddSeconds(rebufferSec);
DateTime due = RynthClock.Now.AddSeconds(rebufferSec);
foreach (var (level, expiration, permanent) in entries)
if (level >= minLevel && expiration > due && !(permanent && ignorePermanent))
return true;
@ -3561,7 +3561,7 @@ public partial class BuffManager : IDisposable
var preservedItemTimers = new Dictionary<int, RamTimerInfo>();
foreach (var kvp in _ramBuffTimers)
{
if (kvp.Value.Expiration > DateTime.Now && IsItemEnchantment(kvp.Value.SpellName))
if (kvp.Value.Expiration > RynthClock.Now && IsItemEnchantment(kvp.Value.SpellName))
preservedItemTimers[kvp.Key] = kvp.Value;
}
@ -3597,7 +3597,7 @@ public partial class BuffManager : IDisposable
int level = GetSpellLevel(spellInfo);
var candidate = new RamTimerInfo
{
Expiration = isPermanent ? PermanentSentinel : DateTime.Now.AddSeconds(remainingSeconds),
Expiration = isPermanent ? PermanentSentinel : RynthClock.Now.AddSeconds(remainingSeconds),
SpellLevel = level,
SpellName = spellInfo.Name,
IsPermanent = isPermanent,
@ -3733,7 +3733,7 @@ public partial class BuffManager : IDisposable
{
ObjectId = objectId,
ObjectName = item.Name,
Expiration = DateTime.Now.AddSeconds(remainingSeconds),
Expiration = RynthClock.Now.AddSeconds(remainingSeconds),
SpellLevel = GetSpellLevel(spellInfo),
SpellName = spellInfo.Name,
};
@ -3760,7 +3760,7 @@ public partial class BuffManager : IDisposable
{
int family = new SpellInfo(0, spellBaseName).Family;
long key = ((long)objectId << 32) | (uint)family;
return _itemBuffTimers.TryGetValue(key, out var info) && info.Expiration > DateTime.Now;
return _itemBuffTimers.TryGetValue(key, out var info) && info.Expiration > RynthClock.Now;
}
public void PrintBuffDebug()
@ -3803,7 +3803,7 @@ public partial class BuffManager : IDisposable
{
var info = kvp.Value;
double total = GetCustomSpellDuration(info.SpellLevel);
TimeSpan left = info.Expiration - DateTime.Now;
TimeSpan left = info.Expiration - RynthClock.Now;
double passed = total - left.TotalSeconds;
_host.WriteToChat(
$"[RynthAi] {info.SpellName} (Lvl {info.SpellLevel}): {Math.Round(passed / 60, 1)}m passed, " +
@ -3848,9 +3848,9 @@ public partial class BuffManager : IDisposable
int level = info != null ? GetSpellLevel(info) : 0;
string activeTimer = "no timer";
if (info != null && _ramBuffTimers.TryGetValue(info.Family, out RamTimerInfo? timer))
activeTimer = $"timer T{timer.SpellLevel}, {Math.Round((timer.Expiration - DateTime.Now).TotalMinutes, 1)}m left";
activeTimer = $"timer T{timer.SpellLevel}, {Math.Round((timer.Expiration - RynthClock.Now).TotalMinutes, 1)}m left";
else if (info != null && _itemSpellTimers.TryGetValue(info.Family, out ItemSpellRecord? itemTimer))
activeTimer = $"item T{itemTimer.SpellLevel}, {Math.Round((itemTimer.ExpiresAt - DateTime.Now).TotalMinutes, 1)}m left";
activeTimer = $"item T{itemTimer.SpellLevel}, {Math.Round((itemTimer.ExpiresAt - RynthClock.Now).TotalMinutes, 1)}m left";
_host.WriteToChat($"[RynthAi] {baseName} → {info?.Name ?? "?"} (T{level}, {activeTimer})", 1);
}
@ -3872,8 +3872,8 @@ public partial class BuffManager : IDisposable
foreach (var kvp in _itemSpellTimers)
{
var info = kvp.Value;
TimeSpan left = info.ExpiresAt - DateTime.Now;
TimeSpan spent = DateTime.Now - info.CastAt;
TimeSpan left = info.ExpiresAt - RynthClock.Now;
TimeSpan spent = RynthClock.Now - info.CastAt;
double totalMin = (info.ExpiresAt - info.CastAt).TotalMinutes;
if (left.TotalSeconds <= 0)
_host.WriteToChat($"[RynthAi] {info.SpellName} (Lvl {info.SpellLevel}): EXPIRED", 1);
@ -4062,7 +4062,7 @@ public partial class BuffManager : IDisposable
// pass the caller just made.
private void LogFilterSkips()
{
var now = DateTime.Now;
var now = RynthClock.Now;
string summary = _filterSummary;
if (summary.Length == 0) return;
if (summary != _filterSkipLoggedSummary || (now - _filterSkipLoggedAt).TotalSeconds >= FilterSkipLogMinSec)
@ -4238,7 +4238,7 @@ public partial class BuffManager : IDisposable
// But only trust it if the just-added buff actually shows up there yet.
if (RefreshFromLiveMemory() >= 0 &&
_ramBuffTimers.TryGetValue(spellInfo.Family, out RamTimerInfo? liveTimer) &&
liveTimer.Expiration > DateTime.Now)
liveTimer.Expiration > RynthClock.Now)
{
return;
}
@ -4304,7 +4304,7 @@ public partial class BuffManager : IDisposable
// A kit on yourself finished (see KitPending). After the speech filter: "heal yourself" in a tell is not one.
if (_kitUsedAt != DateTime.MinValue && _kitLandedAt == DateTime.MinValue && IsKitResultLine(lower))
_kitLandedAt = DateTime.Now;
_kitLandedAt = RynthClock.Now;
// Real failure phrases. Note: bare "component" was removed — it false-matches
// the "consumed the following components" line, which fires for both success
@ -4327,7 +4327,7 @@ public partial class BuffManager : IDisposable
// A kit in flight with no result yet: this is its refusal (see KitRefused). Our bot
// sends nothing else while a kit is pending (CheckVitals returns at KitPending).
if (_kitUsedAt != DateTime.MinValue && _kitLandedAt == DateTime.MinValue
&& (DateTime.Now - _kitUsedAt).TotalMilliseconds <= KitRefusalWindowMs)
&& (RynthClock.Now - _kitUsedAt).TotalMilliseconds <= KitRefusalWindowMs)
KitRefused("You're too busy!");
// A refusal, never "done" (2026-10-05). When the pending cast's incantation has come,
// the server is running it and this refused something else (a loot use, a kit): the
@ -4360,7 +4360,7 @@ public partial class BuffManager : IDisposable
// on the 400ms tick. Cleared by NoteCastAccepted on the next success.
_busyRefusalStreak++;
double backoffMs = Math.Min(BusyBackoffBaseMs * Math.Pow(2, _busyRefusalStreak - 1), BusyBackoffMaxMs);
_busyBackoffUntil = DateTime.Now.AddMilliseconds(backoffMs);
_busyBackoffUntil = RynthClock.Now.AddMilliseconds(backoffMs);
if (_busyRefusalStreak == 1 || _busyRefusalStreak % 5 == 0)
_host.Log($"[BuffChat] too-busy streak={_busyRefusalStreak} — backing off {backoffMs:0}ms before the next cast attempt.");
@ -4406,7 +4406,7 @@ public partial class BuffManager : IDisposable
if (pendingSpell != null && noCompsVital)
{
// A vital spell: pass over this level only; the next lower one goes next.
_noComponentsUntil[_pendingSpellId] = DateTime.Now.AddSeconds(NoComponentsLevelSec);
_noComponentsUntil[_pendingSpellId] = RynthClock.Now.AddSeconds(NoComponentsLevelSec);
_host.WriteToChat($"[RynthAi] No components for {pendingSpell.Name}: using a lower level for {NoComponentsLevelSec / 60:0} min.", 2);
}
else if (pendingSpell != null)
@ -4417,7 +4417,7 @@ public partial class BuffManager : IDisposable
SaveBuffTimers();
}
_buffFailCooldownUntil[pendingSpell.Family] =
DateTime.Now.AddSeconds(BuffFailCooldownSec);
RynthClock.Now.AddSeconds(BuffFailCooldownSec);
// AC's refusal doesn't name the spell and vital casts print no
// "Casting:" line, so say which one. The server's text is not
// echoed: this line comes back through this handler, and it must
@ -4445,7 +4445,7 @@ public partial class BuffManager : IDisposable
if (lower.Contains("enough mana"))
{
_cast.Result(null, "not enough mana", atStart: true);
_lastManaRefusalAt = DateTime.Now; // a combat cast's refusal too: ManaStarved with costs unknown
_lastManaRefusalAt = RynthClock.Now; // a combat cast's refusal too: ManaStarved with costs unknown
if (_pendingSpellId == 0) return;
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
// A recovery vital tries again soon for a better Mana Conversion roll (RecoveryRetry).
@ -4453,7 +4453,7 @@ public partial class BuffManager : IDisposable
{
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} - not enough mana; retrying in {RecoveryRetryMs} ms, buffs {LowManaBuffPauseMs / 1000:0}s.");
_pendingSpellId = 0;
_lowManaPauseUntil = DateTime.Now.AddMilliseconds(LowManaBuffPauseMs);
_lowManaPauseUntil = RynthClock.Now.AddMilliseconds(LowManaBuffPauseMs);
_onCastResolved?.Invoke("not enough mana");
return;
}
@ -4472,12 +4472,12 @@ public partial class BuffManager : IDisposable
// mana regenerates to its cost while attacks wait (the mana reserve), then it goes.
bool vitalSpell = _pendingSpellId == _pendingVitalSpellId;
restSec = vitalSpell ? LowManaHealRestSec : LowManaFamilyRestSec;
_buffFailCooldownUntil[pendingSpell.Family] = DateTime.Now.AddSeconds(restSec);
_buffFailCooldownUntil[pendingSpell.Family] = RynthClock.Now.AddSeconds(restSec);
}
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} - not enough mana; resting the family {restSec:0}s, buffs {LowManaBuffPauseMs / 1000:0}s.");
EndPendingUpgrade(_pendingSpellId, "not enough mana");
_pendingSpellId = 0;
_lowManaPauseUntil = DateTime.Now.AddMilliseconds(LowManaBuffPauseMs);
_lowManaPauseUntil = RynthClock.Now.AddMilliseconds(LowManaBuffPauseMs);
_onCastResolved?.Invoke("not enough mana");
return;
}
@ -4828,7 +4828,7 @@ public partial class BuffManager : IDisposable
/// (CastTracker.GiveUpAt), else <paramref name="fallbackMs"/> from the send.</summary>
private bool PendingGiveUpReached(double fallbackMs) =>
_cast.GiveUpReached(_pendingSpellId, fallbackMs)
?? (DateTime.Now - _lastCastAttempt).TotalMilliseconds > fallbackMs;
?? (RynthClock.Now - _lastCastAttempt).TotalMilliseconds > fallbackMs;
private string GiveUpWhy(double fallbackMs)
{
@ -4867,7 +4867,7 @@ public partial class BuffManager : IDisposable
_host.SetAutoRunBy("Buff/Nudge", false);
CastNudges++;
if (urgent) UrgentNudges++;
DateTime hold = DateTime.Now.AddMilliseconds(NudgeHoldMs);
DateTime hold = RynthClock.Now.AddMilliseconds(NudgeHoldMs);
if (_busyBackoffUntil < hold) _busyBackoffUntil = hold;
string why = urgent
? (held != null && IsHealCast(held.SpellId) ? "it is a heal" : $"health {_vitals.HealthPct}% is under a heal line") +
@ -4902,7 +4902,7 @@ public partial class BuffManager : IDisposable
int level = GetSpellLevel(spellInfo);
_ramBuffTimers[spellInfo.Family] = new RamTimerInfo
{
Expiration = DateTime.Now.AddSeconds(durationSeconds),
Expiration = RynthClock.Now.AddSeconds(durationSeconds),
SpellLevel = level,
SpellName = spellInfo.Name,
};
@ -5114,12 +5114,12 @@ public partial class BuffManager : IDisposable
// _lastBuffStanceAttempt), while buffing held the bot.
int noWandShift = Math.Min(_buffStanceConsecutiveFails, 5);
int noWandGateMs = Math.Min(1000 << noWandShift, 30000);
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs
if ((RynthClock.Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "no wand: Magic mode bare-handed"))
{
NoteStanceRequest();
_lastBuffStanceAttempt = DateTime.Now;
_lastCastAttempt = DateTime.Now;
_lastBuffStanceAttempt = RynthClock.Now;
_lastCastAttempt = RynthClock.Now;
if (_buffStanceConsecutiveFails < 6) _buffStanceConsecutiveFails++;
if (_buffStanceConsecutiveFails > 1)
_host.Log($"[BuffStance] no wand: ChangeCombatMode(Magic) retry #{_buffStanceConsecutiveFails} (next retry in {noWandGateMs / 1000}s)");
@ -5167,7 +5167,7 @@ public partial class BuffManager : IDisposable
// before retrying. Mirrors the no-chat-timeout pattern used for
// spell casts at the top of OnHeartbeat. Checked BEFORE the shared
// swap gate so a denied attempt never claims the cross-subsystem slot.
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (now < _wieldCooldownUntil)
return false;
@ -5302,10 +5302,10 @@ public partial class BuffManager : IDisposable
// the clock restarts, so the refusals that follow are not counted as a wedged stance.
if (_buffStanceStuckSince != DateTime.MinValue && ActionPacer.LastEngineRefusalMs > _buffStanceStuckStartMs)
{
_buffStanceStuckSince = DateTime.Now;
_buffStanceStuckSince = RynthClock.Now;
_buffStanceStuckStartMs = ActionPacer.NowMs();
}
double stuckMs = _buffStanceStuckSince == DateTime.MinValue ? 0 : (DateTime.Now - _buffStanceStuckSince).TotalMilliseconds;
double stuckMs = _buffStanceStuckSince == DateTime.MinValue ? 0 : (RynthClock.Now - _buffStanceStuckSince).TotalMilliseconds;
// Capped re-equip recovery (mirrors CombatManager): handles the rare
// stale "wielded reads true" by resyncing the wield once or twice.
@ -5313,15 +5313,15 @@ public partial class BuffManager : IDisposable
// and unbounded re-equip jams the item-action queue permanently.
if (_buffStanceReEquips < BuffStanceReEquipMax
&& stuckMs > BuffStanceStuckRecoverMs
&& (DateTime.Now - _buffStanceLastRecoverAt).TotalMilliseconds > BuffStanceStuckRecoverMs
&& (RynthClock.Now - _buffStanceLastRecoverAt).TotalMilliseconds > BuffStanceStuckRecoverMs
&& (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("buff-stance-recovery")))
{
_buffStanceLastRecoverAt = DateTime.Now;
_buffStanceLastRecoverAt = RynthClock.Now;
_buffStanceReEquips++;
_host.Log($"[BuffStance] STUCK {stuckMs:0}ms (wielded, mode={CurrentCombatMode}≠Magic) — re-equip attempt {_buffStanceReEquips}/{BuffStanceReEquipMax} 0x{(uint)wandId:X8}");
_host.UseFor((uint)wandId, "Buff", "buffing: stance stuck, wield the wand again");
NoteStanceRequest();
_lastCastAttempt = DateTime.Now;
_lastCastAttempt = RynthClock.Now;
return false;
}
// Past the cap and clearly wedged: warn ONCE so a multi-hour silent
@ -5341,13 +5341,13 @@ public partial class BuffManager : IDisposable
if (shift > 5) shift = 5;
int gateMs = 1000 << shift; // 1s, 2s, 4s, 8s, 16s, 32s
if (gateMs > 30000) gateMs = 30000; // cap at 30s
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs
if ((RynthClock.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode"))
{
if (_buffStanceStuckSince == DateTime.MinValue) { _buffStanceStuckSince = DateTime.Now; _buffStanceStuckStartMs = ActionPacer.NowMs(); }
if (_buffStanceStuckSince == DateTime.MinValue) { _buffStanceStuckSince = RynthClock.Now; _buffStanceStuckStartMs = ActionPacer.NowMs(); }
NoteStanceRequest();
_lastBuffStanceAttempt = DateTime.Now;
_lastCastAttempt = DateTime.Now;
_lastBuffStanceAttempt = RynthClock.Now;
_lastCastAttempt = RynthClock.Now;
if (_buffStanceConsecutiveFails < 6) _buffStanceConsecutiveFails++;
// Visible retry line (throttled by the backoff itself): the
// 2026-06-12 coma produced ZERO log output from this path.
@ -5490,7 +5490,7 @@ public partial class BuffManager : IDisposable
{
if (_wandSkipUntil.TryGetValue(wo.Id, out DateTime until))
{
if (DateTime.Now < until) return true;
if (RynthClock.Now < until) return true;
_wandSkipUntil.Remove(wo.Id);
_wandWieldFails.Remove(wo.Id);
}
@ -5503,13 +5503,13 @@ public partial class BuffManager : IDisposable
_wandIdAsked.TryGetValue(wo.Id, out var asked);
if (asked.Count < WandIdMaxAsks)
{
if ((DateTime.Now - asked.At).TotalSeconds >= WandIdRetrySec)
if ((RynthClock.Now - asked.At).TotalSeconds >= WandIdRetrySec)
{
// Counted only when the engine took it: a refused ask (a death or a portal) is not one of the
// WandIdMaxAsks, and the wand is held back and asked about again.
if (_host.RequestId(uid))
{
_wandIdAsked[wo.Id] = (asked.Count + 1, DateTime.Now);
_wandIdAsked[wo.Id] = (asked.Count + 1, RynthClock.Now);
_host.Log($"[WieldGate] identifying 0x{uid:X8} '{wo.Name}' before using it to buff (its wield requirement isn't known yet)");
}
}
@ -5543,7 +5543,7 @@ public partial class BuffManager : IDisposable
bool tooLow = _host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out _, out uint wErr, out _, out uint wObj)
&& wObj == unchecked((uint)wandId) && wErr != 0 && wErr != 0x1D;
if (n < WandWieldFailMax && !tooLow) return;
_wandSkipUntil[wandId] = DateTime.Now.AddMinutes(WandSkipMin);
_wandSkipUntil[wandId] = RynthClock.Now.AddMinutes(WandSkipMin);
_wandWieldFails.Remove(wandId);
string name = _worldObjectCache?[wandId]?.Name ?? "?";
_host.Log($"[WieldGate] 0x{(uint)wandId:X8} '{name}' didn't wield after {n} tries: left out of buffing for {WandSkipMin:0} min");

View file

@ -53,9 +53,9 @@ internal static class CastGateWatchdog
return true; // already declared stuck; stay open until the engine gate recovers
if (_closedSince == DateTime.MinValue)
_closedSince = DateTime.Now;
_closedSince = RynthClock.Now;
if ((DateTime.Now - _closedSince).TotalMilliseconds > StuckMs)
if ((RynthClock.Now - _closedSince).TotalMilliseconds > StuckMs)
{
_overriding = true;
log?.Invoke($"[CastGate] CanCastNow stuck false >{StuckMs:F0}ms — overriding gate open " +

View file

@ -63,7 +63,7 @@ internal sealed class CastTracker
public CastTracker(Action<string> log) => _log = log;
public Func<DateTime> Clock = () => DateTime.Now;
public Func<DateTime> Clock = () => RynthClock.Now;
public DateTime Now => Clock();
/// <summary>The last cast sent.</summary>

View file

@ -57,7 +57,7 @@ public partial class CombatManager
/// one being wielded). Ammo crafting waits: it would otherwise equip ammo for the launcher
/// being swapped away from, or start a craft in the middle of the swap.
/// </summary>
public bool AmmoSwapInProgress => _ammoFollowUpFor != 0 && DateTime.Now < _ammoFollowUpUntil;
public bool AmmoSwapInProgress => _ammoFollowUpFor != 0 && RynthClock.Now < _ammoFollowUpUntil;
private void ResetAmmoState()
{
@ -192,7 +192,7 @@ public partial class CombatManager
int lt = LauncherTypeOf(_worldFilter[launcherId]);
if (lt == 0) return AmmoPrep.Ready;
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
var pack = PackAmmo();
var wielded = pack.FirstOrDefault(a => a.Wielded);
if (wielded != null && MissileAmmo.Fits(lt, wielded.AmmoType))
@ -287,7 +287,7 @@ public partial class CombatManager
private bool AmmoFollowUp(int launcherId, WorldObject target, MonsterRule? rule)
{
if (_ammoFollowUpFor == 0) return false;
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (_ammoFollowUpFor != launcherId || now >= _ammoFollowUpUntil) { EndAmmoFollowUp(); return false; }
var wo = _worldFilter[launcherId];
int lt = LauncherTypeOf(wo);

View file

@ -25,7 +25,7 @@ namespace RynthCore.Plugin.RynthAi;
public partial class CombatManager
{
/// <summary>Clock for the throttle and the projectile watch; tests replace it.</summary>
internal Func<DateTime> EnvClock { get; set; } = () => DateTime.Now;
internal Func<DateTime> EnvClock { get; set; } = () => RynthClock.Now;
internal EnvironmentImpactThrottle EnvThrottle { get; } = new();

View file

@ -14,7 +14,7 @@ namespace RynthCore.Plugin.RynthAi;
public partial class CombatManager
{
/// <summary>Clock for the kite state machine; tests replace it.</summary>
internal Func<DateTime> KiteClock { get; set; } = () => DateTime.Now;
internal Func<DateTime> KiteClock { get; set; } = () => RynthClock.Now;
// Face-away + autorun cadence (mirrors EnvironmentApproach).
private const double KiteTurnRefreshMs = 300;

View file

@ -114,7 +114,7 @@ public partial class CombatManager
/// <see cref="OffhandReadMs"/>, always live while an off-hand action is in flight.</summary>
internal int OffhandInSlot(bool fresh = false)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (!fresh && OffhandTracker.PendingId == 0 && _offDequipPendingId == 0
&& (now - _offSlotReadAt).TotalMilliseconds < OffhandReadMs)
return _offSlotId;
@ -259,11 +259,11 @@ public partial class CombatManager
if (OffhandRules.OffhandAllowed(kind, offWo != null && IsShieldItem(offWo))) return false;
string why;
if (mode == OffhandMode.None) why = "Offhand is None, so it stays";
else if (DateTime.Now < _offDequipRestUntil) why = "it didn't come off; resting";
else if (RynthClock.Now < _offDequipRestUntil) why = "it didn't come off; resting";
else return false;
if ((DateTime.Now - _lastOffHoldLogAt).TotalSeconds > 10)
if ((RynthClock.Now - _lastOffHoldLogAt).TotalSeconds > 10)
{
_lastOffHoldLogAt = DateTime.Now;
_lastOffHoldLogAt = RynthClock.Now;
_host.Log($"[EquipDiag] not wielding 0x{(uint)mainId:X8} '{WeaponName(mainId)}' ({OffhandRules.KindLabel(kind)}): 0x{(uint)off:X8} '{offWo?.Name ?? "?"}' is in the off hand and {why} — the server refuses it otherwise");
}
return true;
@ -291,7 +291,7 @@ public partial class CombatManager
/// <summary>Put <paramref name="offId"/> (in the off hand) into an open pack: one move in flight, capped.</summary>
private OffPrep DequipOffhand(int offId, string why, bool gateHeld = false)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (_offDequipPendingId != offId) _offDequipTries = 0;
if (_offDequipPendingId == offId && (now - _offDequipAt).TotalMilliseconds < OffDequipResolveMs)
return OffPrep.Busy;
@ -332,7 +332,7 @@ public partial class CombatManager
/// </summary>
private bool OffhandFollowUp(WorldObject target, MonsterRule? rule, int mainId)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
FoldServerAnswer(OffhandTracker, now);
var plan = OffhandPlanFor(target, rule, mainId);
int off = OffhandInSlot();

View file

@ -83,8 +83,8 @@ public partial class CombatManager
{
if (_spellManager == null || !_spellManager.IsKnownSpellId((int)spell)) return $"spell {spell} isn't known";
// A script spell the server refused outright (no components): parked like a vital level.
if (_scriptParkedUntil.TryGetValue((int)spell, out DateTime parked) && DateTime.Now < parked)
return $"spell {spell} was refused by the server, parked for {(parked - DateTime.Now).TotalSeconds:0} s more";
if (_scriptParkedUntil.TryGetValue((int)spell, out DateTime parked) && RynthClock.Now < parked)
return $"spell {spell} was refused by the server, parked for {(parked - RynthClock.Now).TotalSeconds:0} s more";
uint player = _playerId != 0 ? _playerId : _host.GetPlayerId();
if (castTarget == player) return null;
// Monster rule Priority 0 = IGNORE: not a target for a script either, even one attacking us.
@ -140,9 +140,9 @@ public partial class CombatManager
StartCastChatTrace(spellId, unchecked((int)castTarget)); // the server's answers, logged as for RynthAi's own casts
SessionAttackCasts++;
CastsSinceLastKill++;
_lastSpellCast = DateTime.Now;
_lastSpellCast = RynthClock.Now;
_scriptCastSpellId = spellId;
_scriptCastAt = DateTime.Now;
_scriptCastAt = RynthClock.Now;
_scriptCastSent = ActionPacer.CastsSent; // includes this cast: any later send changes it
bool atFight = castTarget == unchecked((uint)activeTargetId);
bool judged = atFight && !area && !noJudge;
@ -153,7 +153,7 @@ public partial class CombatManager
// What the NO DAMAGE report names as the last cast (ReportNoDamageCasts).
_lastOffensiveCastLine = $"script id={spellId} '{name}' target=0x{castTarget:X8}";
_pendingOffensiveSpellId = spellId;
_pendingOffensiveCastAt = DateTime.Now;
_pendingOffensiveCastAt = RynthClock.Now;
_pendingOffensiveTargetId = activeTargetId;
NoteOffensiveSeq();
}
@ -269,14 +269,14 @@ public partial class CombatManager
internal const double ScriptRefusalWindowMs = 2_000.0;
/// <summary>Host tests: true while <paramref name="spellId"/> is parked after a refusal.</summary>
internal bool ScriptSpellParked(int spellId) => _scriptParkedUntil.TryGetValue(spellId, out DateTime u) && DateTime.Now < u;
internal bool ScriptSpellParked(int spellId) => _scriptParkedUntil.TryGetValue(spellId, out DateTime u) && RynthClock.Now < u;
/// <summary>A chat line: park the script's last spell on a hard refusal (missing components, unknown spell).</summary>
private void NoteScriptCastRefusal(string text)
{
if (_scriptCastSpellId == 0) return;
if (ActionPacer.CastsSent != _scriptCastSent
|| (DateTime.Now - _scriptCastAt).TotalMilliseconds > ScriptRefusalWindowMs) { _scriptCastSpellId = 0; return; }
|| (RynthClock.Now - _scriptCastAt).TotalMilliseconds > ScriptRefusalWindowMs) { _scriptCastSpellId = 0; return; }
string lo = text.ToLowerInvariant();
string? own = SpellTableStub.GetById(_scriptCastSpellId)?.Name;
if (own != null && lo.Contains("ou cast " + own.ToLowerInvariant())) { _scriptCastSpellId = 0; return; } // it landed
@ -284,7 +284,7 @@ public partial class CombatManager
|| lo.Contains("have all the components for this spell"))) return;
int spell = _scriptCastSpellId;
_scriptCastSpellId = 0;
_scriptParkedUntil[spell] = DateTime.Now.AddSeconds(ScriptParkSec);
_scriptParkedUntil[spell] = RynthClock.Now.AddSeconds(ScriptParkSec);
_host.Log($"[CombatCast] script spell id={spell} '{SpellTableStub.GetById(spell)?.Name}' refused: '{text.Trim()}'. " +
$"Rejected for {ScriptParkSec / 60:0} min (RynthAi chooses instead while the script asks for it).");
}

View file

@ -237,7 +237,7 @@ public partial class CombatManager : IDisposable
// counting it as an attack (no attack interval starts, so the wall goes once settled).
private bool _wallFaceHeld;
/// <summary>Tests: the clock the wall facing reads.</summary>
internal Func<DateTime> WallClock { get; set; } = () => DateTime.Now;
internal Func<DateTime> WallClock { get; set; } = () => RynthClock.Now;
// ── Magic cast cadence guard ────────────────────────────────────────────
// Don't issue the next combat cast until the previous one's server windup
@ -676,7 +676,7 @@ public partial class CombatManager : IDisposable
private DateTime _lockedLastSeenInScan = DateTime.MinValue;
/// <summary>Tests: the clock target selection reads (scan grace, in-flight hold).</summary>
internal Func<DateTime> TargetClock { get; set; } = () => DateTime.Now;
internal Func<DateTime> TargetClock { get; set; } = () => RynthClock.Now;
public struct ScannedTarget
{
@ -903,9 +903,9 @@ public partial class CombatManager : IDisposable
/// </summary>
public void ScanNearbyTargets()
{
if ((DateTime.Now - _lastScanTime).TotalMilliseconds < SCAN_INTERVAL_MS)
if ((RynthClock.Now - _lastScanTime).TotalMilliseconds < SCAN_INTERVAL_MS)
return;
_lastScanTime = DateTime.Now;
_lastScanTime = RynthClock.Now;
// Raycast just became ready (warmup→ready edge, flagged on the bg
// thread): one-time clean slate. Whatever got blacklisted or had its
@ -929,7 +929,7 @@ public partial class CombatManager : IDisposable
// cleared lazily). Allocation-free: scratch list is reused.
if (_recentlyKilled.Count > 0)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
_killPruneScratch.Clear();
foreach (var kv in _recentlyKilled)
if (now >= kv.Value) // Value = expiry time
@ -1456,7 +1456,7 @@ public partial class CombatManager : IDisposable
if (_damageStore == null) return;
try { LearnFromCombatChat(text); } catch { }
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
bool critLine = text.IndexOf("critical", StringComparison.OrdinalIgnoreCase) >= 0;
if (critLine) _lastCritChatAt = now;
@ -1484,6 +1484,15 @@ public partial class CombatManager : IDisposable
_host.Log($"[DmgDbg] amt={amount} crit={crit} victim='{victim}' id=0x{(uint)victimId:X8} fight={(onFight ? 1 : onLastFight ? 2 : 0)} mode={CurrentCombatMode} text='{text}'");
}
// A hit on the fight target is damage for the no-damage judge and the no-progress timer,
// as a hit on any other monster is (CreditHitToOther). The server sends health only for
// the client's selection: once the player selects something else (a corpse, themselves,
// an item), the fight target's health stops coming, and this line is the only sign a war
// spell landed. Without it, three casts that hit after the player clicked a corpse were
// "no damage": the live monster was blacklisted and combat stopped (2026-10-21, Conquest).
if (onFight && amount > 0)
ReportDamageOnTarget(_fightTargetId);
if (!onFight && !onLastFight)
{
CreditHitToOther(victimId, victim, amount, crit);
@ -1751,7 +1760,7 @@ public partial class CombatManager : IDisposable
{
NoteDebuffLanded();
_waitingForDebuffResult = false;
_lastSpellCast = DateTime.Now;
_lastSpellCast = RynthClock.Now;
return;
}
@ -1794,7 +1803,7 @@ public partial class CombatManager : IDisposable
_host.WriteToChat($"[RynthAi] {what}: {_pendingDebuffKey} — recasting", 2);
}
_waitingForDebuffResult = false;
_lastSpellCast = DateTime.Now;
_lastSpellCast = RynthClock.Now;
}
/// <summary>
@ -1806,7 +1815,7 @@ public partial class CombatManager : IDisposable
private void NoteDebuffLanded()
{
int seconds = SpellDatabase.DurationSeconds(_pendingDebuffSpellId);
_debuffs.Landed(_pendingDebuffTargetId, _pendingDebuffKey ?? "", seconds, DateTime.Now);
_debuffs.Landed(_pendingDebuffTargetId, _pendingDebuffKey ?? "", seconds, RynthClock.Now);
if (seconds > 0)
_host.Log($"[CombatCast] debuff {_pendingDebuffKey} on 0x{(uint)_pendingDebuffTargetId:X8}: lasts {seconds} s, renewed in {seconds - DebuffTimers.Lead(seconds):0} s");
}
@ -1926,7 +1935,7 @@ public partial class CombatManager : IDisposable
/// <summary>True while a back-away is holding combat (jump or settle).</summary>
public bool BackAwayActive =>
_backAwayUntil != DateTime.MinValue && DateTime.Now < _backAwayUntil;
_backAwayUntil != DateTime.MinValue && RynthClock.Now < _backAwayUntil;
/// <summary>
/// Backs the character away from <paramref name="objectId"/> when it is within the danger radius:
@ -1967,7 +1976,7 @@ public partial class CombatManager : IDisposable
int hold = Math.Clamp(holdMs, BackAwayMinHoldMs, BackAwayMaxHoldMs);
_backAwayJumpStarted = false;
// Hold combat long enough for turn + charge + land + one re-engage tick.
_backAwayUntil = DateTime.Now.AddMilliseconds(hold + BackAwaySettleMs);
_backAwayUntil = RynthClock.Now.AddMilliseconds(hold + BackAwaySettleMs);
// Stop the bound melee/missile attack so the jump isn't eaten by the swing servo.
try
@ -1996,7 +2005,7 @@ public partial class CombatManager : IDisposable
private bool TickBackAway()
{
if (_backAwayUntil == DateTime.MinValue) return false;
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
bool jumperBusy = JumpBusy?.Invoke() == true;
// Jump never started / failed: clear early.
@ -2033,7 +2042,7 @@ public partial class CombatManager : IDisposable
_consecutiveCastMisses = 0;
_blacklistManager.ClearFailure(targetId);
if (targetId == activeTargetId || targetId == _lockedTargetId)
_lastDamageDealtAt = DateTime.Now;
_lastDamageDealtAt = RynthClock.Now;
}
/// <summary>
@ -2064,7 +2073,7 @@ public partial class CombatManager : IDisposable
private void NoteSwingEvidence(string kind)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
_lastSwingEvidenceAt = now;
_lastSwingEvidenceKind = kind;
_attacksSinceEvidence = 0;
@ -2099,7 +2108,7 @@ public partial class CombatManager : IDisposable
_host.CancelAttack();
if (!log) return;
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if ((now - _lastRebindLogAt).TotalMilliseconds < 2000) { _rebindLogSuppressed++; return; }
string more = _rebindLogSuppressed > 0 ? $" (+{_rebindLogSuppressed} more since last line)" : "";
_rebindLogSuppressed = 0;
@ -2197,7 +2206,7 @@ public partial class CombatManager : IDisposable
private void ReportNoDamageCasts(int tid)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if ((now - _lastNoDamageReportAt).TotalMilliseconds < NoDamageReportGapMs) return;
_lastNoDamageReportAt = now;
try
@ -2226,7 +2235,7 @@ public partial class CombatManager : IDisposable
if (tid == 0 || tid != _lockedTargetId || _targetLockedAt == DateTime.MinValue) return false;
if (_lastSwingEvidenceAt >= _targetLockedAt) return false;
if (_lockSpot == null || TargetSpot(tid) is not GhostSpot now || now.MovedFrom(_lockSpot.Value)) return false;
silentMs = ServerSilentMs(tid, DateTime.Now);
silentMs = ServerSilentMs(tid, RynthClock.Now);
return silentMs < 0 || silentMs >= GhostCheck.NoUpdateMs;
}
@ -2234,7 +2243,7 @@ public partial class CombatManager : IDisposable
{
if (_pendingJudgeCastAt == DateTime.MinValue) return;
if (RaycastWarmingUp) { _pendingJudgeCastAt = DateTime.MinValue; return; }
if ((DateTime.Now - _pendingJudgeCastAt).TotalMilliseconds < _settings.BlacklistCastSettleMs)
if ((RynthClock.Now - _pendingJudgeCastAt).TotalMilliseconds < _settings.BlacklistCastSettleMs)
return; // not settled yet — give the damage/health packet time
int tid = _pendingJudgeTargetId;
@ -2283,7 +2292,7 @@ public partial class CombatManager : IDisposable
if (_pendingOffensiveTargetId == 0) return;
if (_pendingOffensiveCastAt == DateTime.MinValue) return;
ObserveOffensiveAnswer();
if ((DateTime.Now - _pendingOffensiveCastAt).TotalMilliseconds < OffensiveRefusalWindowMs)
if ((RynthClock.Now - _pendingOffensiveCastAt).TotalMilliseconds < OffensiveRefusalWindowMs)
return;
// A refusal is not a cast (in a client log, three healthy targets were blacklisted 'after 3
@ -2336,7 +2345,7 @@ public partial class CombatManager : IDisposable
// in-flight hold (Target Lock off, AttackInFlightAtLocked) tracks the most
// recent cast. Stamping only on change would end the hold mid-fight while
// still casting at the same mob — the in-flight abandonment it exists to stop.
_lastAttackedAt = TargetClock(); // DateTime.Now outside tests
_lastAttackedAt = TargetClock(); // RynthClock.Now outside tests
JudgePendingCast(); // verdict on the prior attack if its settle window elapsed
@ -2345,7 +2354,7 @@ public partial class CombatManager : IDisposable
// clears _pendingJudgeCastAt on settle, so the next attack re-arms here.
if (_pendingJudgeCastAt != DateTime.MinValue) return;
_pendingJudgeCastAt = DateTime.Now;
_pendingJudgeCastAt = RynthClock.Now;
_pendingJudgeTargetId = targetId;
_damageSincePendingCast = false;
}
@ -2422,7 +2431,7 @@ public partial class CombatManager : IDisposable
int swapId = activeTargetId;
if (swapId == 0) return;
_recentlyKilled[swapId] = DateTime.Now.AddMilliseconds(PREDICTED_SWAP_SUPPRESS_MS);
_recentlyKilled[swapId] = RynthClock.Now.AddMilliseconds(PREDICTED_SWAP_SUPPRESS_MS);
ForgetScanned(swapId);
_predictedSwapAt[swapId] = TargetClock(); // fought again later = it didn't die (PredictionFailed)
// Queue this predicted one-shot so it's CREDITED when its death confirms —
@ -2431,12 +2440,12 @@ public partial class CombatManager : IDisposable
string pkName = _worldFilter[swapId]?.Name ?? _fightTargetName;
if (_fightTargetWcid != 0 && _fightCastCount > 0 && !string.IsNullOrEmpty(pkName))
{
DateTime nowSwap = DateTime.Now;
DateTime nowSwap = RynthClock.Now;
_predictedKillPending.RemoveAll(p => p.Expiry < nowSwap);
_predictedKillPending.Add(new PendingKill(
pkName, _fightTargetWcid, _fightCastCount,
_lastCastWeaponId, _lastCastElement, _lastCastTier, _fightDamage,
DateTime.Now.AddSeconds(5), _fightStartedAt, _fightSummon, swapId));
RynthClock.Now.AddSeconds(5), _fightStartedAt, _fightSummon, swapId));
}
_host.Log($"[RynthAi] Predicted kill shot 0x{swapId:X8} '{_worldFilter[swapId]?.Name}' (cast#{_fightCastCount} hp~{_fightTargetMaxHp:0} dealt~{_fightDamage:0}) — confirmed accepted, swapping to next target.");
// The pending-offensive judge state belongs to the mob being dropped —
@ -2471,7 +2480,7 @@ public partial class CombatManager : IDisposable
// the fight state has already been cleared/advanced by the time the corpse's
// KillerNotification lands. Three tiers, most-specific first.
if (_damageStore == null) return;
DateTime nowKill = DateTime.Now;
DateTime nowKill = RynthClock.Now;
_predictedKillPending.RemoveAll(p => p.Expiry < nowKill);
bool recorded = false;
@ -2640,7 +2649,7 @@ public partial class CombatManager : IDisposable
if (id == 0) return;
var pk = new PendingKill(_lastFightName, _lastFightWcid, _lastFightCount > 0 ? _lastFightCount : 1,
_lastFightWeaponId, _lastFightElement, _lastFightTier, 0,
DateTime.Now.AddMilliseconds(RecentFightTtlMs));
RynthClock.Now.AddMilliseconds(RecentFightTtlMs));
for (int i = _recentFights.Count - 1; i >= 0; i--)
if (_recentFights[i].Id == id) _recentFights.RemoveAt(i);
_recentFights.Add((id, pk));
@ -2728,7 +2737,7 @@ public partial class CombatManager : IDisposable
_fightStartedAt = default;
_fightSummon = null;
if (targetId == 0) return;
_fightStartedAt = DateTime.Now;
_fightStartedAt = RynthClock.Now;
_fightSummon = SummonOut?.Invoke();
_fightTargetName = _worldFilter[targetId]?.Name ?? "";
if (_host.HasGetObjectWcid && _host.TryGetObjectWcid((uint)targetId, out uint wcid))
@ -3029,7 +3038,7 @@ public partial class CombatManager : IDisposable
// attacks again, target or not — see ContinueStallRewield.
if (_stallRewieldId != 0 && ContinueStallRewield())
{
_stallWatch.Hold(DateTime.Now);
_stallWatch.Hold(RynthClock.Now);
return true;
}
@ -3085,7 +3094,7 @@ public partial class CombatManager : IDisposable
// refused/fizzled/resisted cast still cancels the arm in HandleChatForDebuffs.
if (activeTargetId == 0 || _predictArmTargetId != activeTargetId)
_predictKillSwapArmed = false; // target already advanced/dropped — stale arm
else if ((DateTime.Now - _predictArmCastAt).TotalMilliseconds >= OffensiveRefusalWindowMs)
else if ((RynthClock.Now - _predictArmCastAt).TotalMilliseconds >= OffensiveRefusalWindowMs)
{
// ⚠ Do NOT drop the target while the cast gesture is still
// animating. A high-tier cast (Force Arc VII) winds up ~2s,
@ -3098,7 +3107,7 @@ public partial class CombatManager : IDisposable
// damage and the predicted swap is correct. Bounded by a
// timeout so a missing/forever gesture can't arm-lock combat.
bool released = _predictSwapGestureSeen && (!_host.HasGetCastBusyState || _host.CanCastNow);
bool timedOut = (DateTime.Now - _predictArmCastAt).TotalMilliseconds >= PredictKillSwapMaxWaitMs;
bool timedOut = (RynthClock.Now - _predictArmCastAt).TotalMilliseconds >= PredictKillSwapMaxWaitMs;
if (released || timedOut)
ExecuteDeferredKillSwap();
}
@ -3159,7 +3168,7 @@ public partial class CombatManager : IDisposable
bool peaceHeld = false;
if (_settings.PeaceModeWhenIdle && CurrentCombatMode != CombatMode.NonCombat
&& _scannedTargets.Count == 0 && BusyCount == 0
&& DateTime.Now >= _navMagicWantedUntil) // a nav recall wants Magic mode
&& RynthClock.Now >= _navMagicWantedUntil) // a nav recall wants Magic mode
{
try { peaceHeld = HoldIdlePeace?.Invoke() == true; } catch { peaceHeld = false; }
if (peaceHeld && !_idlePeaceHeldLogged)
@ -3171,7 +3180,7 @@ public partial class CombatManager : IDisposable
if (!peaceHeld) _idlePeaceHeldLogged = false;
if (!peaceHeld && _settings.PeaceModeWhenIdle && CurrentCombatMode != CombatMode.NonCombat
&& _scannedTargets.Count == 0 && BusyCount == 0
&& DateTime.Now >= _navMagicWantedUntil) // a nav recall wants Magic mode
&& RynthClock.Now >= _navMagicWantedUntil) // a nav recall wants Magic mode
{
// Defer idle peace-swap while a cast at the just-dropped target is still
// resolving: ChangeCombatMode truncates the in-flight gesture → strands
@ -3180,10 +3189,10 @@ public partial class CombatManager : IDisposable
// 4 after that up to 15 s. An unbounded ChangeCombatMode stream is the
// 2026-05-25 stance-spam crash class; this used to retry every 500 ms forever.
double peaceDelayMs = Math.Min(15_000, 500 * Math.Pow(2, Math.Min(5, _idlePeaceAttempts / 4)));
if ((DateTime.Now - _lastPeaceAttempt).TotalMilliseconds > peaceDelayMs && !IsCastInFlight()
if ((RynthClock.Now - _lastPeaceAttempt).TotalMilliseconds > peaceDelayMs && !IsCastInFlight()
&& _host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "idle: no target (Peace Mode When Idle)"))
{
_lastPeaceAttempt = DateTime.Now;
_lastPeaceAttempt = RynthClock.Now;
_idlePeaceAttempts++;
if (_idlePeaceAttempts == 16)
_host.Log($"[EquipDiag] WARNING: {_idlePeaceAttempts} idle peace-mode requests without reaching peace (mode={CurrentCombatMode}) — backing off to {Math.Min(15_000, 500 * Math.Pow(2, Math.Min(5, _idlePeaceAttempts / 4))) / 1000:0.#}s retries.");
@ -3203,9 +3212,9 @@ public partial class CombatManager : IDisposable
// Give it a grace period before dropping — one bad LOS result or scan gap shouldn't
// hand control to navigation mid-fight.
if (_targetLostScanTime == DateTime.MinValue)
_targetLostScanTime = DateTime.Now;
_targetLostScanTime = RynthClock.Now;
if ((DateTime.Now - _targetLostScanTime).TotalMilliseconds > TARGET_SCAN_GRACE_MS)
if ((RynthClock.Now - _targetLostScanTime).TotalMilliseconds > TARGET_SCAN_GRACE_MS)
DropTarget("scan grace expired");
return true;
}
@ -3241,7 +3250,7 @@ public partial class CombatManager : IDisposable
if (noProgressTimeoutSec > 0 && _targetLockedAt != DateTime.MinValue && !RaycastWarmingUp)
{
DateTime refTime = _lastDamageDealtAt != DateTime.MinValue ? _lastDamageDealtAt : _targetLockedAt;
if ((DateTime.Now - refTime).TotalSeconds > noProgressTimeoutSec)
if ((RynthClock.Now - refTime).TotalSeconds > noProgressTimeoutSec)
{
_host.WriteToChat($"[RynthAi] No progress on {targetObj.Name} after {noProgressTimeoutSec}s — blacklisting", 2);
_blacklistManager.TimeoutSeconds = _settings.BlacklistTimeoutSec;
@ -3331,7 +3340,7 @@ public partial class CombatManager : IDisposable
double attackCmdIntervalMs = AttackIntervalMs(CurrentCombatMode, _settings.AttackSpellIntervalMs,
hasServerGates: _host.HasUseDoneSeq && _host.HasGetCastBusyState,
newTarget: activeTargetId != _lastAttackCmdTargetId);
if ((DateTime.Now - lastAttackCmd).TotalMilliseconds < attackCmdIntervalMs)
if ((RynthClock.Now - lastAttackCmd).TotalMilliseconds < attackCmdIntervalMs)
_tickWait = CombatLatencyTracker.Wait.Interval;
else
{
@ -3409,13 +3418,13 @@ public partial class CombatManager : IDisposable
{
ClearCombatTurnMotions();
_facingTarget = false;
_faceSettledAt = DateTime.Now;
_faceSettledAt = RynthClock.Now;
LastCombatSkipReason = "face-settle-release"; // D4 record-only
_tickWait = CombatLatencyTracker.Wait.Face;
return true; // settle tick
}
if (CurrentCombatMode == CombatMode.Magic
&& (DateTime.Now - _faceSettledAt).TotalMilliseconds < FACE_SETTLE_MS)
&& (RynthClock.Now - _faceSettledAt).TotalMilliseconds < FACE_SETTLE_MS)
{
LastCombatSkipReason = "face-settle-wait"; // D4 record-only
_tickWait = CombatLatencyTracker.Wait.Face;
@ -3438,9 +3447,9 @@ public partial class CombatManager : IDisposable
if (!_facingTarget)
{
_facingTarget = true;
_faceStartTime = DateTime.Now;
_faceStartTime = RynthClock.Now;
}
if ((DateTime.Now - _faceStartTime).TotalMilliseconds < FACE_TIMEOUT_MS)
if ((RynthClock.Now - _faceStartTime).TotalMilliseconds < FACE_TIMEOUT_MS)
{
_tickWait = CombatLatencyTracker.Wait.Face;
return true; // not facing yet, keep waiting
@ -3462,7 +3471,7 @@ public partial class CombatManager : IDisposable
// Don't attack in missile mode without ammo
if (CurrentCombatMode == CombatMode.Missile && !HasWieldedAmmo())
{
_lastMissileNoAmmoAt = DateTime.Now; // waiting on ammo is not a stall
_lastMissileNoAmmoAt = RynthClock.Now; // waiting on ammo is not a stall
LastCombatSkipReason = "no-ammo"; // D4 record-only
return true;
}
@ -3490,8 +3499,8 @@ public partial class CombatManager : IDisposable
// cast and AC paces the swing animation itself.
if (!CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s)))
{
if ((DateTime.Now - lastAttackCmd).TotalMilliseconds > 5000)
_host.Log($"[CombatCast] CanCastNow=false — gesture gate blocking cast (last attack {(DateTime.Now - lastAttackCmd).TotalMilliseconds:0}ms ago, target=0x{activeTargetId:X8})");
if ((RynthClock.Now - lastAttackCmd).TotalMilliseconds > 5000)
_host.Log($"[CombatCast] CanCastNow=false — gesture gate blocking cast (last attack {(RynthClock.Now - lastAttackCmd).TotalMilliseconds:0}ms ago, target=0x{activeTargetId:X8})");
LastCombatSkipReason = "cast-gate"; // D4 record-only (CanCastNow=false)
_tickWait = CombatLatencyTracker.Wait.Cast;
return true;
@ -3578,11 +3587,11 @@ public partial class CombatManager : IDisposable
_savedWeaponId = 0;
_returnToPhysicalCombat = true;
_host.UseFor((uint)wandId, "Combat", "wield the wand to cast");
_lastEquipTime = DateTime.Now; // gate AttackWithMagic until wand is wielded
_lastEquipTime = RynthClock.Now; // gate AttackWithMagic until wand is wielded
// Held by the pacing until the wield is answered; the wielded branch of
// EquipWeaponAndSetStance sends it then (2026-10-06).
_host.ChangeCombatModeFor(CombatMode.Magic, "Combat", "debuff: Magic mode after the wand");
lastAttackCmd = DateTime.Now;
lastAttackCmd = RynthClock.Now;
_lastAttackCmdTargetId = activeTargetId;
return true;
}
@ -3606,7 +3615,7 @@ public partial class CombatManager : IDisposable
bool magicMode = CurrentCombatMode == CombatMode.Magic && _spellManager != null;
if (!_lastCastWasRing && (!magicMode || _offensiveCastThisCycle) && physicalSent)
RecordOffensiveCast(activeTargetId);
lastAttackCmd = DateTime.Now;
lastAttackCmd = RynthClock.Now;
_lastAttackCmdTargetId = activeTargetId;
// A rebind sent only the CancelAttack: the attack follows as soon as the cancel can
// have landed, not a whole interval later ("lock->attack 1750 ms (interval 1671)").
@ -3630,7 +3639,7 @@ public partial class CombatManager : IDisposable
_predictSwapGestureSeen = false; // must observe the cast windup before swapping
// AttackWithMagic just set these for the cast that predicted the kill.
_predictArmTargetId = _pendingOffensiveTargetId != 0 ? _pendingOffensiveTargetId : activeTargetId;
_predictArmCastAt = _pendingOffensiveCastAt != DateTime.MinValue ? _pendingOffensiveCastAt : DateTime.Now;
_predictArmCastAt = _pendingOffensiveCastAt != DateTime.MinValue ? _pendingOffensiveCastAt : RynthClock.Now;
}
}
}
@ -3648,7 +3657,7 @@ public partial class CombatManager : IDisposable
{
long msSinceAttack = lastAttackCmd == DateTime.MinValue
? -1
: (long)(DateTime.Now - lastAttackCmd).TotalMilliseconds;
: (long)(RynthClock.Now - lastAttackCmd).TotalMilliseconds;
string attackBucket = msSinceAttack < 0 ? "never"
: msSinceAttack < 3000 ? "recent"
: msSinceAttack < 10_000 ? "stale"
@ -3674,7 +3683,7 @@ public partial class CombatManager : IDisposable
/// </summary>
private bool RunStallWatchdog(WorldObject targetObj, double currentDist)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
int mode = CurrentCombatMode;
bool physical = mode == CombatMode.Melee || mode == CombatMode.Missile;
bool toggling = _stallToggleAt != DateTime.MinValue
@ -3826,7 +3835,7 @@ public partial class CombatManager : IDisposable
uint pid = _playerId != 0 ? _playerId : _host.GetPlayerId();
uint lb = pid != 0 && _host.TryGetObjectPosition(pid, out uint pc, out _, out _, out _) ? pc >> 16 : 0;
GhostSpot spot = TargetSpot(id) ?? new GhostSpot(double.NaN, double.NaN, double.NaN);
Ghosts.Mark(id, name ?? "", spot, lb, DateTime.Now);
Ghosts.Mark(id, name ?? "", spot, lb, RynthClock.Now);
_blacklistManager.ClearFailure(id);
string silent = silentMs < 0 ? "nothing from the server about it since it was first seen" : $"nothing from the server about it for {silentMs / 1000:0}s";
_host.Log($"[Ghost] 0x{id:X8} '{name}' is a ghost: {why}, {silent}, it hasn't moved [{DescribeTargetPos(id)}]. " +
@ -3847,10 +3856,10 @@ public partial class CombatManager : IDisposable
}
/// <summary>The server sent an update for <paramref name="objectId"/> (RynthAiPlugin.OnUpdateObject).</summary>
public void OnServerObjectUpdate(uint objectId) => Ghosts.NoteServerUpdate((int)objectId, DateTime.Now);
public void OnServerObjectUpdate(uint objectId) => Ghosts.NoteServerUpdate((int)objectId, RynthClock.Now);
/// <summary>The server created <paramref name="objectId"/> (RynthAiPlugin.OnCreateObject).</summary>
public void OnObjectCreated(uint objectId) => Ghosts.NoteServerUpdate((int)objectId, DateTime.Now, "the server created it again");
public void OnObjectCreated(uint objectId) => Ghosts.NoteServerUpdate((int)objectId, RynthClock.Now, "the server created it again");
/// <summary>
/// Samples the swing animation and the character's position every stall-watch tick and says
@ -3918,7 +3927,7 @@ public partial class CombatManager : IDisposable
public int AttackRebinds => _attackRebinds;
public string LastSwingEvidenceDescription => _lastSwingEvidenceAt == DateTime.MinValue
? "never"
: $"{_lastSwingEvidenceKind} {(DateTime.Now - _lastSwingEvidenceAt).TotalSeconds:0.0}s ago";
: $"{_lastSwingEvidenceKind} {(RynthClock.Now - _lastSwingEvidenceAt).TotalSeconds:0.0}s ago";
private string LastStallStepName => _lastStallStep switch
{
CombatStallWatchdog.StallAction.Reissue => "1 (re-issue)",
@ -3978,7 +3987,7 @@ public partial class CombatManager : IDisposable
_host.Log($"{head} re-wield: 0x{wid:X8} '{wo.Name}' -> pack 0x{pack:X8}, then wield it again");
}
_stallRewieldId = wid;
_stallRewieldAt = DateTime.Now;
_stallRewieldAt = RynthClock.Now;
_stallRewieldCheckAt = DateTime.MinValue;
}
@ -3990,7 +3999,7 @@ public partial class CombatManager : IDisposable
/// </summary>
private bool ContinueStallRewield()
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
int mode = CurrentCombatMode;
if (mode == CombatMode.Magic)
{
@ -4045,7 +4054,7 @@ public partial class CombatManager : IDisposable
/// first declared (once per episode).</summary>
private void LogStallSnapshot(WorldObject targetObj, double dist, double stalledMs)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
string Ago(DateTime t) => t == DateTime.MinValue ? "never" : $"{(now - t).TotalMilliseconds:0}ms ago";
int tid = activeTargetId;
@ -4306,13 +4315,13 @@ public partial class CombatManager : IDisposable
// [CombatLatency]: time this engagement from the lock to its first attack.
double lockMs = Environment.TickCount64;
double sinceKillMs = _lastKillAt == DateTime.MinValue ? double.MaxValue : (DateTime.Now - _lastKillAt).TotalMilliseconds;
double sinceKillMs = _lastKillAt == DateTime.MinValue ? double.MaxValue : (RynthClock.Now - _lastKillAt).TotalMilliseconds;
_latency.OnLock(bestId, lockMs, sinceKillMs <= 2000 ? lockMs - sinceKillMs : double.NaN);
activeTargetId = bestId;
_lockedTargetId = bestId;
_lockedPriority = bestPriority;
_targetLockedAt = DateTime.Now;
_targetLockedAt = RynthClock.Now;
_lockSpot = TargetSpot(bestId);
_lastDamageDealtAt = DateTime.MinValue;
_lockedLastSeen = best; // it was in this tick's scan: the grace covers a blink next tick
@ -4456,7 +4465,7 @@ public partial class CombatManager : IDisposable
{
var rules = _settings.MonsterRules;
if (!ReferenceEquals(rules, _priorityCacheRules)) { _priorityCache.Clear(); _priorityCacheRules = rules; }
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (_priorityCache.TryGetValue(id, out var hit) && (now - hit.At).TotalMilliseconds < PriorityCacheMs)
return hit.Priority;
if (_priorityCache.Count > 512) _priorityCache.Clear();
@ -4495,7 +4504,7 @@ public partial class CombatManager : IDisposable
{
// The equip path and the spell path both ask every tick; the answer only moves when
// the target, the rule, the list or the hand does, so reuse it for a quarter second.
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
int hand = InHandWeaponId();
var list = _settings.ItemRules;
if (_planCache is { } pc && pc.TargetId == target.Id && ReferenceEquals(pc.Rule, rule) && ReferenceEquals(pc.List, list)
@ -4685,7 +4694,7 @@ public partial class CombatManager : IDisposable
// Not within NotCarriedGraceMs of a wield or move of ours: mid-swap a weapon is
// briefly in neither hand nor the pack walk. Drakkon's Acid Hand Wraps were dropped
// from the choice that way on 2026-10-17 and he fought bare-handed.
if ((DateTime.Now - _lastEquipTime).TotalMilliseconds >= NotCarriedGraceMs)
if ((RynthClock.Now - _lastEquipTime).TotalMilliseconds >= NotCarriedGraceMs)
{
if (_notCarriedNoted.Add(r.Id))
_host.Log($"[EquipDiag] listed weapon 0x{(uint)r.Id:X8} '{wo.Name}' isn't in your pack (sold, dropped or traded?): skipped");
@ -4727,7 +4736,7 @@ public partial class CombatManager : IDisposable
internal int InHandWeaponId(bool fresh = false)
{
if (InHandOverride != null) return InHandOverride();
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (!fresh && (now - _inHandReadAt).TotalMilliseconds < InHandReadMs) return _inHandId;
_inHandReadAt = now;
int found = 0;
@ -4813,7 +4822,7 @@ public partial class CombatManager : IDisposable
if (!_settings.RearmAfterVitals || _fightMainId == 0) return false;
DateTime vital = LastVitalCastAt?.Invoke() ?? DateTime.MinValue;
if (vital == DateTime.MinValue || vital <= _rearmedFor) return false;
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if ((now - vital).TotalMilliseconds < RearmSettleMs) return false; // another vitals spell may follow
bool buffing;
try { buffing = BuffingWantsTick?.Invoke() == true; } catch { buffing = true; }
@ -5007,7 +5016,7 @@ public partial class CombatManager : IDisposable
internal bool SkillTooLowFor(int id)
{
if (!_skillTooLowUntil.TryGetValue(id, out DateTime until)) return false;
if (DateTime.Now < until) return true;
if (RynthClock.Now < until) return true;
_skillTooLowUntil.Remove(id);
return false;
}
@ -5016,7 +5025,7 @@ public partial class CombatManager : IDisposable
{
if (id == 0) return;
bool first = !_skillTooLowUntil.ContainsKey(id);
_skillTooLowUntil[id] = DateTime.Now.AddMinutes(SkillTooLowSkipMin);
_skillTooLowUntil[id] = RynthClock.Now.AddMinutes(SkillTooLowSkipMin);
_planCache = null;
if (first)
{
@ -5032,7 +5041,7 @@ public partial class CombatManager : IDisposable
/// </summary>
private WeaponSwapTracker.Step SwapStep(int chosenId, int inHandId)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
FoldServerAnswer(SwapTracker, now);
var step = SwapTracker.Next(chosenId, inHandId, now, WeaponName, forKey: activeTargetId);
if (SwapTracker.Notice != null)
@ -5046,9 +5055,9 @@ public partial class CombatManager : IDisposable
NoteSkillTooLow(gaveUp, "it never reached your hand (the client refused the wield)");
}
SwapTracker.GaveUpId = null;
if (step == WeaponSwapTracker.Step.Hold && (DateTime.Now - _lastSwapHoldLogAt).TotalSeconds > 10)
if (step == WeaponSwapTracker.Step.Hold && (RynthClock.Now - _lastSwapHoldLogAt).TotalSeconds > 10)
{
_lastSwapHoldLogAt = DateTime.Now;
_lastSwapHoldLogAt = RynthClock.Now;
_host.Log($"[EquipDiag] keeping 0x{(uint)inHandId:X8} '{WeaponName(inHandId)}' instead of 0x{(uint)chosenId:X8} '{WeaponName(chosenId)}' ({SwapTracker.HoldReason})");
}
return step;
@ -5075,7 +5084,7 @@ public partial class CombatManager : IDisposable
int settleMs = _settings.WeaponSwapSettleMs;
if (settleMs > 0 && _lockWasSwitch && _lockedTargetId == target.Id && _targetLockedAt != DateTime.MinValue)
{
double lockedMs = (DateTime.Now - _targetLockedAt).TotalMilliseconds;
double lockedMs = (RynthClock.Now - _targetLockedAt).TotalMilliseconds;
if (lockedMs >= 0 && lockedMs < settleMs)
{
settling = true;
@ -5115,7 +5124,7 @@ public partial class CombatManager : IDisposable
private void LogSwapDefer(int chosenId, int inHand, string why)
{
var key = (chosenId, inHand, why.StartsWith("target switched", StringComparison.Ordinal));
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (key == _lastSwapDeferLogged && (now - _lastSwapDeferLogAt).TotalSeconds < 10) return;
_lastSwapDeferLogged = key;
_lastSwapDeferLogAt = now;
@ -5136,7 +5145,7 @@ public partial class CombatManager : IDisposable
/// holds further swaps until it lands, is refused, or times out.</summary>
private void MarkWieldSent(int weaponId, int inHandId)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (_host.HasGetLastUseDone && _host.TryGetLastUseDone(out int uSeq, out _)) _swapUseDoneSeq = uSeq;
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out _, out _, out _)) _swapWeenieSeq = wSeq;
SwapTracker.Sent(weaponId, inHandId, now);
@ -5247,7 +5256,7 @@ public partial class CombatManager : IDisposable
default: return false;
}
}
if (inHand == 0 || inHand == weaponId) { SwapTracker.Confirmed(weaponId, DateTime.Now); if (inHand == weaponId) _equippedWeaponId = weaponId; return false; }
if (inHand == 0 || inHand == weaponId) { SwapTracker.Confirmed(weaponId, RynthClock.Now); if (inHand == weaponId) _equippedWeaponId = weaponId; return false; }
if (WeaponKind(inHand) != desiredMode) return false; // a cross-kind case; the branches below handle it
_equippedWeaponId = inHand;
@ -5286,10 +5295,10 @@ public partial class CombatManager : IDisposable
ResetStanceFlipBackoff();
return true;
}
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
if ((RynthClock.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
&& _host.ChangeCombatModeFor(CombatMode.Melee, "Combat", "stance"))
{
lastStanceAttempt = DateTime.Now;
lastStanceAttempt = RynthClock.Now;
NoteStanceFlipSent();
}
return false;
@ -5318,9 +5327,9 @@ public partial class CombatManager : IDisposable
}
if (targetWeaponId == 0)
{
if ((DateTime.Now - _lastEquipDiagAt).TotalSeconds > 5)
if ((RynthClock.Now - _lastEquipDiagAt).TotalSeconds > 5)
{
_lastEquipDiagAt = DateTime.Now;
_lastEquipDiagAt = RynthClock.Now;
_host.Log($"[EquipDiag] no weapon found (source=none, desired='{desired}', ItemRules={_settings.ItemRules.Count}, MonsterRule='{rule?.Name ?? "null"}', {CanMagicDiag()}) - proceeding unarmed");
}
return EnsureUnarmedStance();
@ -5329,9 +5338,9 @@ public partial class CombatManager : IDisposable
var weaponObj = _worldFilter[targetWeaponId];
if (weaponObj == null)
{
if ((DateTime.Now - _lastEquipDiagAt).TotalSeconds > 5)
if ((RynthClock.Now - _lastEquipDiagAt).TotalSeconds > 5)
{
_lastEquipDiagAt = DateTime.Now;
_lastEquipDiagAt = RynthClock.Now;
_host.Log($"[EquipDiag] weapon 0x{targetWeaponId:X8} not in WorldFilter (source={weaponSource}) — proceeding unarmed");
}
return EnsureUnarmedStance();
@ -5417,7 +5426,7 @@ public partial class CombatManager : IDisposable
: CombatMode.Melee;
_chosenWeaponMode = desiredMode;
bool diagNow = (DateTime.Now - _lastEquipDiagAt).TotalSeconds > 5;
bool diagNow = (RynthClock.Now - _lastEquipDiagAt).TotalSeconds > 5;
// Use CurrentWieldedLocation (stype=10) — has an InqInt fallback that works even
// when the phys-obj offset probe hasn't fired yet (unlike TryGetObjectWielderInfo).
@ -5450,7 +5459,7 @@ public partial class CombatManager : IDisposable
// diagnostic history that was needed to investigate other issues.
if (diagNow)
{
_lastEquipDiagAt = DateTime.Now;
_lastEquipDiagAt = RynthClock.Now;
_host.Log($"[EquipDiag] wielded via wielder-info fallback (CurrentWieldedLocation read 0) 0x{targetWeaponId:X8} '{weaponObj.Name}'");
}
}
@ -5461,7 +5470,7 @@ public partial class CombatManager : IDisposable
// Just swapped to this launcher: wield its ammo (one in flight, confirmed, capped).
if (desiredMode == CombatMode.Missile && AmmoFollowUp(targetWeaponId, target, rule))
{
_lastMissileNoAmmoAt = DateTime.Now; // waiting on ammo is not a stall
_lastMissileNoAmmoAt = RynthClock.Now; // waiting on ammo is not a stall
LastCombatSkipReason = "no-ammo";
return false;
}
@ -5472,7 +5481,7 @@ public partial class CombatManager : IDisposable
// Waiting on ammo is not a stall. The attack block's stamp is never reached
// from here (Think returns on false), so the stall watchdog's no-ammo
// exemption never applied and it ran its whole ladder on an empty quiver.
_lastMissileNoAmmoAt = DateTime.Now;
_lastMissileNoAmmoAt = RynthClock.Now;
LastCombatSkipReason = "no-ammo"; // D4 record-only
return false;
}
@ -5481,7 +5490,7 @@ public partial class CombatManager : IDisposable
// Clear the gate here (not only on reaching the stance) so a slow stance
// flip doesn't leave a stale pending-wield behind it.
ResetCombatWandWieldGate();
SwapTracker.Confirmed(targetWeaponId, DateTime.Now);
SwapTracker.Confirmed(targetWeaponId, RynthClock.Now);
if (CurrentCombatMode == desiredMode)
{
@ -5502,28 +5511,28 @@ public partial class CombatManager : IDisposable
// A refusal newer than the clock's start: the request that started it was dropped (a teleport), so restart the clock.
if (_stanceStuckSince != DateTime.MinValue && ActionPacer.LastEngineRefusalMs > _stanceStuckStartMs)
{
_stanceStuckSince = DateTime.Now;
_stanceStuckSince = RynthClock.Now;
_stanceStuckStartMs = ActionPacer.NowMs();
}
double stuckMs = _stanceStuckSince == DateTime.MinValue ? 0 : (DateTime.Now - _stanceStuckSince).TotalMilliseconds;
double stuckMs = _stanceStuckSince == DateTime.MinValue ? 0 : (RynthClock.Now - _stanceStuckSince).TotalMilliseconds;
// RE-EQUIP recovery — only for the first couple of attempts in an
// episode (handles a stale "wielded reads true" on a wand that
// actually isn't wielded). Capped: UseObject on a genuinely wielded
// wand is a MOVE to AC, and unbounded re-equip jams the item queue.
if (_stanceReEquipAttempts < StanceReEquipMaxAttempts
&& stuckMs > StanceStuckRecoverMs
&& (DateTime.Now - _lastStanceRecoverAt).TotalMilliseconds > StanceStuckRecoverMs
&& (RynthClock.Now - _lastStanceRecoverAt).TotalMilliseconds > StanceStuckRecoverMs
// Recovery equips like any other path — must hold the swap gate or
// it can collide with a buff wand-equip inside the ±3s window.
// On refusal the && short-circuits: fall through to the throttled
// ChangeCombatMode below and retry next tick.
&& (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("stance-recovery")))
{
_lastStanceRecoverAt = DateTime.Now;
_lastStanceRecoverAt = RynthClock.Now;
_stanceReEquipAttempts++;
_host.Log($"[EquipDiag] STANCE STUCK {stuckMs:0}ms mode={CurrentCombatMode}≠{desiredMode} (wielded reads true) — re-equip attempt {_stanceReEquipAttempts}/{StanceReEquipMaxAttempts} 0x{targetWeaponId:X8}");
_host.UseFor((uint)targetWeaponId, "Combat", "stance stuck: equip again");
_lastEquipTime = DateTime.Now;
_lastEquipTime = RynthClock.Now;
lastStanceAttempt = DateTime.MinValue; // let ChangeCombatMode re-fire next tick
return false;
}
@ -5538,17 +5547,17 @@ public partial class CombatManager : IDisposable
_host.WriteToChat($"[RynthAi] Stance wedged: wand wielded but AC won't enter {(desiredMode == CombatMode.Magic ? "Magic" : "combat")} mode after {stuckMs / 1000:0}s. Re-equip stopped (was jamming item actions). Try /ra clearbusy, or relog if it persists.", 2);
}
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
if ((RynthClock.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
&& _host.ChangeCombatModeFor(desiredMode, "Combat", "stance"))
{
if (_stanceStuckSince == DateTime.MinValue) { _stanceStuckSince = DateTime.Now; _stanceStuckStartMs = ActionPacer.NowMs(); }
if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=true mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource}) — sending ChangeCombatMode"); }
lastStanceAttempt = DateTime.Now;
if (_stanceStuckSince == DateTime.MinValue) { _stanceStuckSince = RynthClock.Now; _stanceStuckStartMs = ActionPacer.NowMs(); }
if (diagNow) { _lastEquipDiagAt = RynthClock.Now; _host.Log($"[EquipDiag] wielded=true mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource}) — sending ChangeCombatMode"); }
lastStanceAttempt = RynthClock.Now;
NoteStanceFlipSent();
}
else if (diagNow)
{
_lastEquipDiagAt = DateTime.Now;
_lastEquipDiagAt = RynthClock.Now;
_host.Log($"[EquipDiag] wielded=true mode={CurrentCombatMode}≠{desiredMode} throttled (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}') — waiting for mode change");
}
return false;
@ -5589,10 +5598,10 @@ public partial class CombatManager : IDisposable
// mode bare-handed (throttled) and send no wield.
if (!allowWield)
{
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
if ((RynthClock.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
&& _host.ChangeCombatModeFor(desiredMode, "Combat", "stance"))
{
lastStanceAttempt = DateTime.Now;
lastStanceAttempt = RynthClock.Now;
NoteStanceFlipSent();
}
return false;
@ -5628,11 +5637,11 @@ public partial class CombatManager : IDisposable
// which has always sent both.
// A weapon still in hand: the wand's use swaps it and the server then puts us in Magic.
if (FindWieldedNonWandWeapon(targetWeaponId) == 0
&& (DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
&& (RynthClock.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
&& _host.ChangeCombatModeFor(desiredMode, "Combat", "stance"))
{
if (diagNow) _host.Log($"[EquipDiag] hand clear — ChangeCombatMode({desiredMode}) alongside wand equip (mode={CurrentCombatMode})");
lastStanceAttempt = DateTime.Now;
lastStanceAttempt = RynthClock.Now;
NoteStanceFlipSent();
}
@ -5642,7 +5651,7 @@ public partial class CombatManager : IDisposable
// item MOVE to AC, and a continuous stream of them keeps the item-action
// queue jammed so the wield never resolves. Issue one, wait for it,
// cool down, cap.
DateTime wnow = DateTime.Now;
DateTime wnow = RynthClock.Now;
if (wnow < _wandWieldCooldownUntil)
return false;
@ -5671,7 +5680,7 @@ public partial class CombatManager : IDisposable
return false;
}
if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] hand clear — UseObject(0x{targetWeaponId:X8} '{weaponObj.Name}') wand equip"); }
if (diagNow) { _lastEquipDiagAt = RynthClock.Now; _host.Log($"[EquipDiag] hand clear — UseObject(0x{targetWeaponId:X8} '{weaponObj.Name}') wand equip"); }
_host.UseFor((uint)targetWeaponId, "Combat", "equip the wand");
MarkWieldSent(targetWeaponId, inHand);
_wandPendingWieldId = targetWeaponId;
@ -5689,28 +5698,28 @@ public partial class CombatManager : IDisposable
// mode change on top of an unanswered action. With the pacing on, the mode change waits
// for the wield's answer (and once the weapon reads wielded, the wielded branch above
// sends it); off, both still go in this tick, as before.
if (allowWield && (DateTime.Now - _lastEquipTime).TotalMilliseconds > 2000
if (allowWield && (RynthClock.Now - _lastEquipTime).TotalMilliseconds > 2000
&& ClearOffhandFor(targetWeaponId, _curOffhandMode) == OffPrep.Ready // a shield off before a two-hander / launcher
&& (desiredMode != CombatMode.Missile || PrepareAmmoFor(targetWeaponId) == AmmoPrep.Ready)
&& (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("combat-equip")))
{
if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=FALSE UseObject(0x{targetWeaponId:X8} '{weaponObj.Name}') — equip attempt"); }
if (diagNow) { _lastEquipDiagAt = RynthClock.Now; _host.Log($"[EquipDiag] wielded=FALSE UseObject(0x{targetWeaponId:X8} '{weaponObj.Name}') — equip attempt"); }
_host.UseFor((uint)targetWeaponId, "Combat", "equip the weapon");
MarkWieldSent(targetWeaponId, inHand);
_lastEquipTime = DateTime.Now;
_lastEquipTime = RynthClock.Now;
}
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs())
if ((RynthClock.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs())
{
// A launcher swap: no Missile request until the launcher and its ammo are on (the
// wielded branch above sends it then). See LauncherSwapHoldsStance.
if (desiredMode == CombatMode.Missile && LauncherSwapHoldsStance(targetWeaponId))
{
if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] stance held: 0x{targetWeaponId:X8} '{weaponObj.Name}' or its ammo isn't on yet (mode={CurrentCombatMode})"); }
if (diagNow) { _lastEquipDiagAt = RynthClock.Now; _host.Log($"[EquipDiag] stance held: 0x{targetWeaponId:X8} '{weaponObj.Name}' or its ammo isn't on yet (mode={CurrentCombatMode})"); }
}
else if (_host.ChangeCombatModeFor(desiredMode, "Combat", "stance"))
{
if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=FALSE mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource} class={weaponObj.ObjectClass}) — ChangeCombatMode"); }
lastStanceAttempt = DateTime.Now;
if (diagNow) { _lastEquipDiagAt = RynthClock.Now; _host.Log($"[EquipDiag] wielded=FALSE mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource} class={weaponObj.ObjectClass}) — ChangeCombatMode"); }
lastStanceAttempt = RynthClock.Now;
NoteStanceFlipSent();
}
}
@ -5724,7 +5733,7 @@ public partial class CombatManager : IDisposable
private bool EnsureHandClearForWand(int wandId, bool diagNow)
{
int bowId = FindWieldedNonWandWeapon(wandId);
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (bowId != 0 && !_combatDirectWandSwapFailed && IsWieldedLive(bowId))
{
if (_combatDirectSwapSince == DateTime.MinValue) _combatDirectSwapSince = now;
@ -5827,7 +5836,7 @@ public partial class CombatManager : IDisposable
public bool EnsureMagicReady()
{
_navMagicWantedUntil = DateTime.Now.AddMilliseconds(2000);
_navMagicWantedUntil = RynthClock.Now.AddMilliseconds(2000);
int wandId = FindWandInItems();
// No target here: the global off-hand setting. With Offhand None and a shield on, the
// wand can't be wielded (the server refuses a caster beside it): cast bare-handed.
@ -5841,10 +5850,10 @@ public partial class CombatManager : IDisposable
// for good, even in Magic mode, so a Recall waypoint never cast and sat
// out the whole portal timeout.
if (CurrentCombatMode == CombatMode.Magic) { ResetStanceFlipBackoff(); return true; }
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
if ((RynthClock.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Combat", "stance"))
{
lastStanceAttempt = DateTime.Now;
lastStanceAttempt = RynthClock.Now;
NoteStanceFlipSent();
}
return false;
@ -5860,10 +5869,10 @@ public partial class CombatManager : IDisposable
if (alreadyWielded)
{
if (CurrentCombatMode == CombatMode.Magic) { ResetWandSwapState(); ResetStanceFlipBackoff(); return true; }
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
if ((RynthClock.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Combat", "stance"))
{
lastStanceAttempt = DateTime.Now;
lastStanceAttempt = RynthClock.Now;
NoteStanceFlipSent();
}
return false;
@ -5886,10 +5895,10 @@ public partial class CombatManager : IDisposable
}
if (!EnsureHandClearForWand(wandId, diagNow: true))
return false;
if ((DateTime.Now - _lastEquipTime).TotalMilliseconds > 2000)
if ((RynthClock.Now - _lastEquipTime).TotalMilliseconds > 2000)
{
_host.UseFor((uint)wandId, "Combat", "equip the wand");
_lastEquipTime = DateTime.Now;
_lastEquipTime = RynthClock.Now;
}
return false;
}
@ -5964,7 +5973,7 @@ public partial class CombatManager : IDisposable
private void LogLosDebug(WorldObject wo, bool blocked, in TargetingFSM.LosDetail det)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (_losDebugLast.TryGetValue(wo.Id, out var last))
{
double ms = (now - last.At).TotalMilliseconds;
@ -6084,7 +6093,7 @@ public partial class CombatManager : IDisposable
private bool HoldForPointBlankFacing(double currentDist, bool force = false)
{
if (CurrentCombatMode != CombatMode.Missile || !_host.HasTurnToHeading) return false;
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
int tid = activeTargetId;
if (_pointBlankFacing.Settling(now, tid)) return true;
if (!TryGetHeadingTo(tid, out double desiredDeg, out double error)) return false;
@ -6154,7 +6163,7 @@ public partial class CombatManager : IDisposable
_awaitingCastResolution = false;
return false;
}
if (DateTime.Now >= _castResolutionDeadline)
if (RynthClock.Now >= _castResolutionDeadline)
{
_awaitingCastResolution = false;
return false;
@ -6174,7 +6183,7 @@ public partial class CombatManager : IDisposable
{
_attackedThisTick = true; // [CombatLatency]: a debuff or attack cast went out
_awaitingCastResolution = true;
_castResolutionDeadline = DateTime.Now.AddMilliseconds(CAST_RESOLUTION_TIMEOUT_MS);
_castResolutionDeadline = RynthClock.Now.AddMilliseconds(CAST_RESOLUTION_TIMEOUT_MS);
_useDoneSeqAtCast = _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
}
@ -6442,9 +6451,9 @@ public partial class CombatManager : IDisposable
// Don't cast while a weapon equip is in progress — the wand may not be registered
// as wielded yet. _lastEquipTime is set whenever UseObject is called for a wand swap.
if ((DateTime.Now - _lastEquipTime).TotalMilliseconds < 3000)
if ((RynthClock.Now - _lastEquipTime).TotalMilliseconds < 3000)
{
_host.Log($"[CombatCast] equip-gate: wand equip in progress ({(DateTime.Now - _lastEquipTime).TotalMilliseconds:0}ms < 3000ms), skipping cast");
_host.Log($"[CombatCast] equip-gate: wand equip in progress ({(RynthClock.Now - _lastEquipTime).TotalMilliseconds:0}ms < 3000ms), skipping cast");
LastCombatSkipReason = "equip-gate"; // D4 record-only
return;
}
@ -6455,7 +6464,7 @@ public partial class CombatManager : IDisposable
if (_waitingForDebuffResult)
{
if ((DateTime.Now - _pendingDebuffCastTime).TotalMilliseconds > DEBUFF_RESULT_TIMEOUT_MS)
if ((RynthClock.Now - _pendingDebuffCastTime).TotalMilliseconds > DEBUFF_RESULT_TIMEOUT_MS)
{
NoteDebuffLanded();
_waitingForDebuffResult = false;
@ -6469,7 +6478,7 @@ public partial class CombatManager : IDisposable
if (activeTargetId != _lastDebuffTargetId)
{
_debuffs.NewTarget(DateTime.Now);
_debuffs.NewTarget(RynthClock.Now);
_lastDebuffTargetId = activeTargetId;
}
@ -6479,7 +6488,7 @@ public partial class CombatManager : IDisposable
if (rule != null)
{
var pendingDebuffs = BuildDebuffList(rule, element);
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
foreach (var debuffKey in pendingDebuffs)
{
if (_debuffs.IsOn(activeTargetId, debuffKey, now)) continue;
@ -6502,14 +6511,14 @@ public partial class CombatManager : IDisposable
_host.CastSpellFor((uint)activeTargetId, spellId, "Combat", SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}");
MarkCombatCastIssued();
StartCastChatTrace(spellId, activeTargetId);
_lastSpellCast = DateTime.Now;
_lastSpellCast = RynthClock.Now;
_lastCastWasRing = false;
_pendingDebuffKey = debuffKey;
_pendingDebuffTargetId = activeTargetId;
_pendingDebuffSpellId = spellId;
_pendingDebuffTier = castTier;
_waitingForDebuffResult = true;
_pendingDebuffCastTime = DateTime.Now;
_pendingDebuffCastTime = RynthClock.Now;
_host.WriteToChat($"[RynthAi] {(renewal ? "Renewing" : "Casting")}: {debuffKey} (T{castTier}) on {target.Name}", 5);
}
catch { }
@ -6578,7 +6587,7 @@ public partial class CombatManager : IDisposable
StartCastChatTrace(offensiveSpellId, activeTargetId);
SessionAttackCasts++; // D6: offensive attack-cast tally for the casts-per-kill signal
CastsSinceLastKill++; // reset in OnKillNotification when a kill lands
_lastSpellCast = DateTime.Now;
_lastSpellCast = RynthClock.Now;
_lastCastWasRing = multiTarget; // walls too: area casts (2026-10-08)
_wallFaceAt = DateTime.MinValue; // the next wall checks its facing afresh
// _offensiveCastThisCycle is NOT set here anymore — a cast
@ -6587,7 +6596,7 @@ public partial class CombatManager : IDisposable
// RecordOffensiveCast trigger moved to the chat-confirmation
// path so only chat-confirmed casts queue a judgement.
_pendingOffensiveSpellId = offensiveSpellId;
_pendingOffensiveCastAt = DateTime.Now;
_pendingOffensiveCastAt = RynthClock.Now;
_pendingOffensiveTargetId = activeTargetId;
NoteOffensiveSeq();
// Environment-impact throttle: follow this cast's projectiles (rings and walls
@ -6643,15 +6652,15 @@ public partial class CombatManager : IDisposable
bool snapWarm = _spellManager?.IsKnownSnapshotWarm == true;
// Chat at most every 30 s (it used to go out every attack cycle; sustained chat is
// the AddTextToScroll crash path). The file log keeps every occurrence.
if ((DateTime.Now - _lastNoSpellChatAt).TotalMilliseconds >= NoSpellChatIntervalMs)
if ((RynthClock.Now - _lastNoSpellChatAt).TotalMilliseconds >= NoSpellChatIntervalMs)
{
_lastNoSpellChatAt = DateTime.Now;
_lastNoSpellChatAt = RynthClock.Now;
_host.WriteToChat($"[RynthAi] No spell found: elem={element} warTier={warTier} voidTier={voidTier} snapshotWarm={snapWarm} pid={_playerId}", 2);
}
_host.Log($"[CombatCast] no offensive spell: elem={element} warTier={warTier} voidTier={voidTier} snapshotWarm={snapWarm} rule={rule?.Name ?? "null"} target='{target.Name}'" +
(_lastShapeArcGaveWay ? " (arc blocked, and no other shape or bolt known: no arc cast into the obstacle)" : ""));
LastCombatSkipReason = "no-offensive-spell"; // D4 record-only (FindBestShapedSpell==0)
_lastSpellCast = DateTime.Now;
_lastSpellCast = RynthClock.Now;
}
}
@ -6704,7 +6713,7 @@ public partial class CombatManager : IDisposable
private bool HasPendingDebuffs(MonsterRule rule, string element)
{
if (rule == null) return false;
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
foreach (var debuffKey in BuildDebuffList(rule, element))
if (!_debuffs.IsOn(activeTargetId, debuffKey, now)) return true;
return false;
@ -6897,8 +6906,8 @@ public partial class CombatManager : IDisposable
private void EnsureInventoryNameCache()
{
if ((DateTime.Now - _invNamesBuiltAt).TotalMilliseconds < InvNameCacheMs) return;
_invNamesBuiltAt = DateTime.Now;
if ((RynthClock.Now - _invNamesBuiltAt).TotalMilliseconds < InvNameCacheMs) return;
_invNamesBuiltAt = RynthClock.Now;
_invNamesLower.Clear();
_compSkipLogged.Clear();
foreach (var wo in _worldFilter.GetInventory())
@ -7379,7 +7388,7 @@ public partial class CombatManager : IDisposable
// Reached from every element probe (CanCastElement inside GetPreferredElement) as well
// as the cast itself, several times per attack cycle while a pack stands in ring range:
// say it (chat + file log) once per element per NoSpellChatIntervalMs.
DateTime nowRing = DateTime.Now;
DateTime nowRing = RynthClock.Now;
if (!_ringMissingChatAt.TryGetValue(element, out DateTime lastRing)
|| (nowRing - lastRing).TotalMilliseconds >= NoSpellChatIntervalMs)
{

View file

@ -314,8 +314,8 @@ public class FellowshipTracker : IDisposable
private void RefreshIfNeeded()
{
if ((DateTime.Now - _lastRefresh).TotalMilliseconds < REFRESH_INTERVAL_MS) return;
_lastRefresh = DateTime.Now;
if ((RynthClock.Now - _lastRefresh).TotalMilliseconds < REFRESH_INTERVAL_MS) return;
_lastRefresh = RynthClock.Now;
var members = new Dictionary<int, string>();
var levels = new Dictionary<int, int>();
try

View file

@ -37,6 +37,19 @@ public class MissileCraftingManager
/// could equip ammo for the launcher being swapped away from, or start a craft mid-swap.
/// </summary>
public Func<bool>? HoldWhile { get; set; }
/// <summary>
/// Set by the plugin (RynthAiPlugin.FightIsOn): true while a fight is on. Crafting holds combat
/// (Peace mode, up to CRAFT_TIMEOUT_MS a step), so in a fight it does only what the fight needs:
/// with ammo in the pack, that ammo is wielded at once and better ammo is not crafted, and a
/// craft under way stops as soon as there is ammo to shoot (carried before it, or one combine
/// made) and wields it. With no ammo at all it still makes the first combine: combat keeps an
/// empty launcher (it doesn't swap to melee or a wand for want of ammo), so without the craft
/// the bot could not fight back at all.
/// </summary>
public Func<bool>? FightIsOn { get; set; }
// The craft under way is better ammo than ammo already carried (an upgrade, not a need).
private bool _craftIsUpgrade;
public void SetCharacterSkills(CharacterSkills skills) => _charSkills = skills;
public enum CraftState { Idle, Evaluating, Combining, EquippingAmmo }
@ -114,7 +127,7 @@ public class MissileCraftingManager
string reason = $"Stopped by an error ({ex.GetType().Name}: {ex.Message}); trying again in a minute";
if (State == CraftState.Idle) ChatLog(reason); // Reset only speaks for a craft in progress
Reset(reason);
_lastAmmoCheck = DateTime.Now.AddMilliseconds(ERROR_BACKOFF_MS - AMMO_CHECK_INTERVAL_MS);
_lastAmmoCheck = RynthClock.Now.AddMilliseconds(ERROR_BACKOFF_MS - AMMO_CHECK_INTERVAL_MS);
}
}
@ -151,9 +164,9 @@ public class MissileCraftingManager
private void ProcessIdle()
{
if ((DateTime.Now - _lastAmmoCheck).TotalMilliseconds < AMMO_CHECK_INTERVAL_MS) return;
if ((RynthClock.Now - _lastAmmoCheck).TotalMilliseconds < AMMO_CHECK_INTERVAL_MS) return;
if (HoldWhile?.Invoke() == true) return;
_lastAmmoCheck = DateTime.Now;
_lastAmmoCheck = RynthClock.Now;
var inv = GetInventory(forceRefresh: true);
if (!TryGetWieldedMissileCategory(inv, out WeaponCategory category, out WorldObject? launcher))
@ -196,7 +209,19 @@ public class MissileCraftingManager
}
if (bestCraftable != null && bestCraftable.Rank > bestExistingPriority)
{ StartCrafting(bestCraftable, inv); return; }
{
// In a fight, better ammo waits: the carried ammo goes on now (no Peace mode, no combine).
if (bestExistingAmmo != null && InFight())
{
_host.Log($"[RynthAi] MissileCraft: a fight is on - wielding '{bestExistingAmmo.Name}' now instead of crafting {bestCraftable.OutputName}.");
ChatLog($"In a fight: wielding {bestExistingAmmo.Name} now instead of crafting {bestCraftable.OutputName}");
}
else
{
StartCrafting(bestCraftable, inv, upgrade: bestExistingAmmo != null);
return;
}
}
if (bestExistingAmmo != null)
{
@ -229,15 +254,16 @@ public class MissileCraftingManager
Reset("No ammo and no bundles available");
}
private void StartCrafting(AmmoRecipe recipe, List<WorldObject> inv)
private void StartCrafting(AmmoRecipe recipe, List<WorldObject> inv, bool upgrade = false)
{
_craftIsUpgrade = upgrade;
_currentRecipe = recipe;
_pendingBundlePairs.Clear();
_combinesCompleted = 0;
_allCombinesDone = false;
_peaceSent = false;
_peaceAskedAt = DateTime.Now; // the wait for the stance counts from the first ask
_peaceAskedAt = RynthClock.Now; // the wait for the stance counts from the first ask
TryPeaceForCrafting();
var headItems = inv.Where(i => recipe.IsHead(i.Name)).ToList();
@ -291,6 +317,21 @@ public class MissileCraftingManager
private void ProcessCombining()
{
// In a fight, with ammo to shoot (carried before the craft, or a combine already made):
// stop holding combat and wield the best ammo carried now.
if (!_allCombinesDone && (_craftIsUpgrade || _combinesCompleted > 0) && InFight())
{
string making = _currentRecipe?.OutputName ?? "ammo";
_host.Log($"[RynthAi] MissileCraft: a fight is on - {making} stopped after {_combinesCompleted} combine(s); wielding the ammo carried.");
ChatLog($"In a fight: stopped crafting {making} after {_combinesCompleted} combine(s), wielding the ammo carried");
_pendingBundlePairs.Clear();
_currentRecipe = null;
_craftIsUpgrade = false;
_equipTargetId = 0; // the best carried
SetState(CraftState.EquippingAmmo);
return;
}
if (_allCombinesDone)
{
StatusMessage = $"Equipping {_currentRecipe!.OutputName}...";
@ -299,7 +340,7 @@ public class MissileCraftingManager
return;
}
if ((DateTime.Now - _phaseStart).TotalMilliseconds > CRAFT_TIMEOUT_MS)
if ((RynthClock.Now - _phaseStart).TotalMilliseconds > CRAFT_TIMEOUT_MS)
{
if (_combinesCompleted > 0)
{
@ -317,21 +358,21 @@ public class MissileCraftingManager
if (!_peaceSent)
{
TryPeaceForCrafting();
if (!_peaceSent && (DateTime.Now - _peaceAskedAt).TotalMilliseconds < PeaceWaitMaxMs) return; // still asking, inside the ceiling
if (!_peaceSent && (RynthClock.Now - _peaceAskedAt).TotalMilliseconds < PeaceWaitMaxMs) return; // still asking, inside the ceiling
}
if ((DateTime.Now - _lastApplyAttempt).TotalMilliseconds >= APPLY_RETRY_MS)
if ((RynthClock.Now - _lastApplyAttempt).TotalMilliseconds >= APPLY_RETRY_MS)
{
try
{
if (!_host.UseOnFor((uint)_headBundleId, (uint)_shaftBundleId, "Crafting", "missile crafting: heads on shafts"))
{
ChatLog($"UseObjectOn returned false for 0x{_headBundleId:X8} -> 0x{_shaftBundleId:X8}");
_lastApplyAttempt = DateTime.Now;
_lastApplyAttempt = RynthClock.Now;
return;
}
_lastApplyAttempt = DateTime.Now;
_lastApplyAttempt = RynthClock.Now;
StatusMessage = $"Combining -> {_currentRecipe!.OutputName} ({_combinesCompleted + 1}/{_totalCombines})...";
}
catch (Exception ex)
@ -347,7 +388,7 @@ public class MissileCraftingManager
private void ProcessEquippingAmmo()
{
if ((DateTime.Now - _phaseStart).TotalMilliseconds < EQUIP_DELAY_MS) return;
if ((RynthClock.Now - _phaseStart).TotalMilliseconds < EQUIP_DELAY_MS) return;
try
{
@ -371,7 +412,7 @@ public class MissileCraftingManager
_host.Log($"[RynthAi] MissileCraft: {why} (0x{targetId:X8})");
Reset(why);
_equipRepeats = 0;
_lastAmmoCheck = DateTime.Now.AddMilliseconds(EQUIP_IGNORED_BACKOFF_MS - AMMO_CHECK_INTERVAL_MS);
_lastAmmoCheck = RynthClock.Now.AddMilliseconds(EQUIP_IGNORED_BACKOFF_MS - AMMO_CHECK_INTERVAL_MS);
return;
}
@ -381,7 +422,7 @@ public class MissileCraftingManager
}
else
{
if ((DateTime.Now - _phaseStart).TotalMilliseconds < CRAFT_TIMEOUT_MS)
if ((RynthClock.Now - _phaseStart).TotalMilliseconds < CRAFT_TIMEOUT_MS)
{
StatusMessage = $"Waiting for {_currentRecipe?.OutputName ?? GetCategoryLabel(_lastWeaponCategory)} to appear...";
return;
@ -473,17 +514,29 @@ public class MissileCraftingManager
private bool IsPlayerWielded(WorldObject item)
{
// Found inside a pack by the direct scan: AC's container lists never hold worn gear. A
// launcher put away after a swap keeps its old wielder and slot in the client's object
// description, so the slot alone said a stowed bow was in hand while a crossbow was, and
// arrows were wielded at it every 5 s (Silentkelpie, 2026-10-15).
if (item.DirectContainerId != 0)
return false;
// The server's word (the engine's EquipmentTracker, API v87) when the engine has it. The
// client's own fields go stale both ways: a launcher put away after a swap keeps its old
// wielder and slot, so the slot alone said a stowed bow was in hand while a crossbow was, and
// arrows were wielded at it every 5 s (Silentkelpie, 2026-10-15); gear wielded after login
// reads slot 0.
if (EquippedState.IsWielded(_host, item.Id) is bool tracked)
return tracked;
uint playerId = _host.GetPlayerId();
if (playerId == 0)
return false;
// Found inside a side pack by the direct scan (or in the main pack with its container field
// set and no wielder): not in hand, whatever the stale record says. A parent of the player
// says nothing: the engine lists what the player wields in the player's own contents too
// (ScanByContainerId matches the wielder as well as the container). Taking every item the
// scan filed under a container as "not in hand" (2026-10-19) hid the bow in hand as well,
// so crafting saw no launcher and never started, with nothing in chat (2026-10-21).
if (item.DirectContainerId != 0 && item.DirectContainerId != unchecked((int)playerId))
return false;
if (_objectCache?.InPackWalk(item.Id) == true)
return false;
if (item.WieldedLocation > 0)
return item.Wielder == 0 || item.Wielder == unchecked((int)playerId);
@ -499,7 +552,7 @@ public class MissileCraftingManager
/// </summary>
private bool NoteEquipSent(int targetId)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (targetId == _lastEquipSentId && (now - _lastEquipSentAt).TotalMilliseconds < EQUIP_REPEAT_WINDOW_MS)
_equipRepeats++;
else
@ -561,7 +614,7 @@ public class MissileCraftingManager
private void SetState(CraftState newState)
{
State = newState;
_phaseStart = DateTime.Now;
_phaseStart = RynthClock.Now;
}
private void Reset(string reason)
@ -578,9 +631,17 @@ public class MissileCraftingManager
_allCombinesDone = false;
_combinesCompleted = 0;
_totalCombines = 0;
_craftIsUpgrade = false;
_pendingBundlePairs.Clear();
}
/// <summary>The plugin says a fight is on (<see cref="FightIsOn"/>); a throwing check is no fight.</summary>
private bool InFight()
{
try { return FightIsOn?.Invoke() == true; }
catch { return false; }
}
private void ChatLog(string msg)
{
try { _host.WriteToChat($"[RynthAi Craft] {msg}", 1); } catch { }

View file

@ -29,7 +29,7 @@ internal sealed class WeaponElementTracker
public WeaponElementTracker(RynthCoreHost host, Func<DateTime>? now = null)
{
_host = host;
_now = now ?? (() => DateTime.Now);
_now = now ?? (() => RynthClock.Now);
}
/// <summary>What is known about <paramref name="id"/>'s element right now.</summary>

View file

@ -169,7 +169,7 @@ public class WorldObjectCache
lock (_gate)
{
_playerId = playerId;
_loginTime = DateTime.Now;
_loginTime = RynthClock.Now;
_deletedWhilePending.Clear();
// Remove self if mistakenly added as creature before login completed
if (playerId == 0) return;
@ -402,9 +402,9 @@ public class WorldObjectCache
// Same cadence also re-queues uids parked in _slowRetry (their fast-retry burst
// exhausted in <10 ms before AC could populate their weenie), giving them a
// fresh 8-tick attempt each pass.
if ((DateTime.Now - _lastReclassifyTime).TotalSeconds >= ReclassifyIntervalSec)
if ((RynthClock.Now - _lastReclassifyTime).TotalSeconds >= ReclassifyIntervalSec)
{
_lastReclassifyTime = DateTime.Now;
_lastReclassifyTime = RynthClock.Now;
FlushSlowRetry();
ReclassifyUnknownDynamics();
lock (_gate) _diag.Flush("2 s");
@ -413,10 +413,10 @@ public class WorldObjectCache
// Full container scan disabled — causes delayed crash when 160+ items in cache
// trigger bulk property queries. MissileCraftingManager does its own lightweight scan.
if (false && _inventoryDirty && _playerId != 0 && _host.HasGetContainerContents
&& (DateTime.Now - _loginTime).TotalMilliseconds >= 5000
&& (DateTime.Now - _lastScanAttempt).TotalMilliseconds >= ScanCooldownMs)
&& (RynthClock.Now - _loginTime).TotalMilliseconds >= 5000
&& (RynthClock.Now - _lastScanAttempt).TotalMilliseconds >= ScanCooldownMs)
{
_lastScanAttempt = DateTime.Now;
_lastScanAttempt = RynthClock.Now;
int found = ScanFullInventory();
// Only clear dirty once scan actually discovers items (hooks ready)
if (found > 0 || _initialScanDone)
@ -1390,7 +1390,7 @@ public class WorldObjectCache
// snapshot copy so the caller never iterates the live list a later call will clear.
lock (_gate)
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (!_host.HasGetContainerContents)
{
@ -1601,8 +1601,8 @@ public class WorldObjectCache
/// <summary>A chat warning that a full pack blocks something, at most once every 5 minutes.</summary>
public static void WarnPackFull(RynthCoreHost host, string what)
{
if ((DateTime.Now - _packFullWarnedAt).TotalMinutes < 5) return;
_packFullWarnedAt = DateTime.Now;
if ((RynthClock.Now - _packFullWarnedAt).TotalMinutes < 5) return;
_packFullWarnedAt = RynthClock.Now;
host.WriteToChat($"[RynthAi] Pack full: {what}. Free a slot (salvage, sell or drop); looting keeps {LootReserveFreeSlots} slots free.", 2);
}

View file

@ -761,7 +761,7 @@ internal static class RynthLog
string topFrame = ex.StackTrace?.Split('\n')[0].Trim() ?? string.Empty;
string signature = $"{where}|{ex.GetType().FullName}|{topFrame}";
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now; // an interval (the burst window), not the time of day
if (ExceptionSignatures.TryGetValue(signature, out var seen))
{

View file

@ -0,0 +1,258 @@
using System;
namespace RynthCore.Plugin.RynthAi;
/// <summary>The steps of <see cref="RynthAiPlugin.OnTick"/> that each run under their own guard (<see cref="TickGuard"/>).</summary>
internal enum TickStep
{
// Every tick, in world or not.
MetaCommands,
DataWriteProblems,
CombatHook,
DelayedCommands,
GameInput,
EngineCommands,
PropertyDump,
PackSetup,
SettingsPush,
WorldCache,
DifficultyTier,
PendingStops,
CreatureSave,
AutoSave,
MapBake,
WatchedFiles,
QuestTracker,
LocalFeatures,
GiveQueue,
Jumper,
// In world.
VTankYield,
VitalsRead,
DeathCheck,
LowComponents,
Pacing,
DeathHold,
DeathRecall,
HazardEscape,
BusyTimeout,
BuffsAndVitals,
ReloadBlocker,
PatrolReroute,
AutoVendor,
AutoTrade,
WeaponElements,
CramStack,
InventoryStatus,
CombatTelemetry,
Salvage,
ManaStones,
Pets,
MissileCrafting,
Combat,
Looting,
Navigation,
MtLoot,
Meta,
}
/// <summary>
/// Keeps one OnTick step's exception from stopping the rest of the tick (structural audit
/// 2026-10-21, finding 4). OnTick had one try/catch round the whole tick, so a step that threw
/// every tick (bad spell data, a null after a reload) skipped everything after it, healing and
/// combat included, and all that showed was one log line every 10 s: "the bot just stood there".
/// Each step now runs in its own guard:
/// <list type="bullet">
/// <item>A fault is logged at most once every <see cref="LogEveryMs"/> per step, through
/// <see cref="RynthLog.Exception"/> (the summary line; the stack in exceptions_*.txt under its own
/// de-duplication), with the count since the last line. The rest of the tick runs.</item>
/// <item>A step that failed <see cref="TripAfter"/> calls in a row over at least
/// <see cref="TripAfterMs"/> is switched off, with a chat line, and tried again every
/// <see cref="RetryMs"/>; chat says when it works again.</item>
/// <item>Essential steps (healing and buffs, combat, movement and the keys, the death and hazard
/// holds, the busy watchdog, ...) are never switched off: one chat line says they keep failing,
/// and they are tried every tick, as before.</item>
/// </list>
/// Nothing changes while nothing throws. Pump thread only.
/// </summary>
internal sealed class TickGuard
{
internal const int TripAfter = 30;
internal const long TripAfterMs = 5_000;
internal const long RetryMs = 60_000;
internal const long LogEveryMs = 10_000;
private readonly record struct StepInfo(string Name, LogCat Cat, bool Essential);
// Indexed by TickStep.
private static readonly StepInfo[] Steps = BuildSteps();
private static StepInfo[] BuildSteps()
{
var s = new StepInfo[Enum.GetValues<TickStep>().Length];
void Add(TickStep step, string name, LogCat cat, bool essential = false) => s[(int)step] = new(name, cat, essential);
Add(TickStep.MetaCommands, "meta edits", LogCat.Meta);
Add(TickStep.DataWriteProblems, "save problem report", LogCat.General);
Add(TickStep.CombatHook, "script hook cast results", LogCat.Combat);
Add(TickStep.DelayedCommands, "delayed commands", LogCat.Commands);
Add(TickStep.GameInput, "held keys", LogCat.Commands, essential: true);
Add(TickStep.EngineCommands, "engine commands", LogCat.Commands);
Add(TickStep.PropertyDump, "property dump", LogCat.Commands);
Add(TickStep.PackSetup, "pack setup", LogCat.Inventory);
Add(TickStep.SettingsPush, "settings to the engine", LogCat.UI);
Add(TickStep.WorldCache, "world object cache", LogCat.WorldCache, essential: true);
Add(TickStep.DifficultyTier, "difficulty tier", LogCat.Combat);
Add(TickStep.PendingStops, "held stops", LogCat.Navigation, essential: true);
Add(TickStep.CreatureSave, "creature data save", LogCat.Combat);
Add(TickStep.AutoSave, "settings autosave", LogCat.UI);
Add(TickStep.MapBake, "dungeon map bake", LogCat.Navigation);
Add(TickStep.WatchedFiles, "monster and nav files", LogCat.UI);
Add(TickStep.QuestTracker, "quest tracker", LogCat.Quests);
Add(TickStep.LocalFeatures, "HUDs and panels", LogCat.Huds);
Add(TickStep.GiveQueue, "give queue", LogCat.Inventory);
Add(TickStep.Jumper, "jumper", LogCat.Jumper, essential: true);
Add(TickStep.VTankYield, "VTank yield", LogCat.General, essential: true);
Add(TickStep.VitalsRead, "vitals read", LogCat.Buffing, essential: true);
Add(TickStep.DeathCheck, "death check", LogCat.General, essential: true);
Add(TickStep.LowComponents, "low components check", LogCat.Buffing);
Add(TickStep.Pacing, "action pacing", LogCat.General, essential: true);
Add(TickStep.DeathHold, "death hold", LogCat.General, essential: true);
Add(TickStep.DeathRecall, "recall on death", LogCat.General, essential: true);
Add(TickStep.HazardEscape, "hazard escape", LogCat.Navigation, essential: true);
Add(TickStep.BusyTimeout, "busy watchdog", LogCat.General, essential: true);
Add(TickStep.BuffsAndVitals, "healing and buffs", LogCat.Buffing, essential: true);
Add(TickStep.ReloadBlocker, "reload blocker", LogCat.General);
Add(TickStep.PatrolReroute, "patrol reroute", LogCat.Navigation);
Add(TickStep.AutoVendor, "AutoVendor", LogCat.Vendor);
Add(TickStep.AutoTrade, "AutoTrade", LogCat.Vendor);
Add(TickStep.WeaponElements, "weapon elements", LogCat.Combat);
Add(TickStep.CramStack, "AutoCram/AutoStack", LogCat.Inventory);
Add(TickStep.InventoryStatus, "inventory status", LogCat.Inventory);
Add(TickStep.CombatTelemetry, "combat telemetry", LogCat.Combat);
Add(TickStep.Salvage, "salvage", LogCat.Salvage);
Add(TickStep.ManaStones, "mana stones", LogCat.ManaStones);
Add(TickStep.Pets, "pets", LogCat.Pets);
Add(TickStep.MissileCrafting, "missile crafting", LogCat.Crafting);
Add(TickStep.Combat, "combat", LogCat.Combat, essential: true);
Add(TickStep.Looting, "looting", LogCat.Looting);
Add(TickStep.Navigation, "navigation", LogCat.Navigation, essential: true);
Add(TickStep.MtLoot, "/mt loot", LogCat.Looting);
Add(TickStep.Meta, "meta", LogCat.Meta);
return s;
}
private sealed class State
{
public int InARow;
public long FirstFailAt;
public long LastLogAt = long.MinValue / 2;
public int SinceLog;
public long Failures;
public long Runs;
public bool Off;
public long RetryAt;
public bool Warned;
}
private readonly State[] _state;
private readonly Action<string> _log;
private readonly Action<string> _chat;
/// <summary>Clock (ms, monotonic); tests replace it.</summary>
internal Func<long> Clock { get; set; } = static () => Environment.TickCount64;
public TickGuard(Action<string> log, Action<string> chat)
{
_log = log;
_chat = chat;
_state = new State[Steps.Length];
for (int i = 0; i < _state.Length; i++) _state[i] = new State();
}
internal static string NameOf(TickStep step) => Steps[(int)step].Name;
internal static bool IsEssential(TickStep step) => Steps[(int)step].Essential;
/// <summary>False while the step is switched off and its retry is not due.</summary>
public bool MayRun(TickStep step)
{
State st = _state[(int)step];
return !st.Off || Clock() >= st.RetryAt;
}
/// <summary>The step ran through.</summary>
public void Succeeded(TickStep step)
{
State st = _state[(int)step];
st.Runs++;
if (st.Off)
{
st.Off = false;
Say($"[RynthAi] {NameOf(step)} works again (it was off after failing every tick).");
}
else if (st.Warned)
{
_log($"[RynthAi] Tick step '{NameOf(step)}' runs through again after {st.InARow} failure(s) in a row.");
}
st.InARow = 0;
st.Warned = false;
}
/// <summary>The step threw: log (throttled), and switch it off once it keeps failing.</summary>
public void Failed(TickStep step, Exception ex)
{
StepInfo info = Steps[(int)step];
State st = _state[(int)step];
long now = Clock();
st.Runs++;
st.Failures++;
st.SinceLog++;
if (st.InARow++ == 0) st.FirstFailAt = now;
if (now - st.LastLogAt >= LogEveryMs)
{
st.LastLogAt = now;
// The summary line goes to the engine log; the stack to exceptions_*.txt (de-duplicated there).
RynthLog.Exception(info.Cat, ex, "tick step " + info.Name);
if (st.SinceLog > 1)
_log($"[RynthAi] Tick step '{info.Name}' failed {st.SinceLog} time(s) since its last line ({st.InARow} in a row); the rest of the tick still runs.");
st.SinceLog = 0;
}
if (st.Off)
{
// A retry that failed: off for another RetryMs, quietly (the log line above still counts it).
st.RetryAt = now + RetryMs;
return;
}
bool keepsFailing = st.InARow >= TripAfter && now - st.FirstFailAt >= TripAfterMs;
if (!keepsFailing || st.Warned) return;
st.Warned = true;
string what = $"{ex.GetType().Name}: {ex.Message}";
if (info.Essential)
{
Say($"[RynthAi] {info.Name} keeps failing ({what}); it is tried every tick, the rest of the bot keeps running. See the log.");
}
else
{
st.Off = true;
st.RetryAt = now + RetryMs;
Say($"[RynthAi] {info.Name} is off: it failed every tick for {(now - st.FirstFailAt) / 1000} s ({what}). The rest of the bot keeps running; it is tried again every {RetryMs / 1000} s.");
}
}
private void Say(string line)
{
_log(line);
try { _chat(line); } catch { /* chat gone during unload */ }
}
// ── Diagnostics and tests ─────────────────────────────────────────────
internal bool IsOff(TickStep step) => _state[(int)step].Off;
internal long Failures(TickStep step) => _state[(int)step].Failures;
internal long Runs(TickStep step) => _state[(int)step].Runs;
internal int FailuresInARow(TickStep step) => _state[(int)step].InARow;
}

View file

@ -3455,7 +3455,7 @@ internal sealed partial class LegacyDashboardRenderer
sb.Append("\"actionChildren\":"); AppendMetaRuleArray(sb, r.ActionChildren ?? new List<MetaRule>()); sb.Append(',');
sb.Append("\"enabled\":").Append(r.Enabled ? "true" : "false").Append(',');
if (!string.IsNullOrEmpty(r.Name)) { sb.Append("\"name\":\""); AppendEscaped(sb, r.Name); sb.Append("\","); }
long ms = r.LastFiredAt == DateTime.MinValue ? 99999L : (long)(DateTime.Now - r.LastFiredAt).TotalMilliseconds;
long ms = r.LastFiredAt == DateTime.MinValue ? 99999L : (long)(RynthClock.Now - r.LastFiredAt).TotalMilliseconds;
sb.Append("\"lastFiredMs\":").Append(ms.ToString(System.Globalization.CultureInfo.InvariantCulture));
sb.Append('}');
}

View file

@ -139,7 +139,7 @@ internal sealed class LegacyMetaUi
ImGuiInputTextFlags.AllowTabInput);
if (!string.IsNullOrEmpty(_sourceApplyMessage) &&
(DateTime.Now - _sourceApplyTime).TotalSeconds < 4)
(RynthClock.Now - _sourceApplyTime).TotalSeconds < 4)
{
SafeImGui.TextColored(new Vector4(0, 1, 0.4f, 1f), _sourceApplyMessage);
ImGui.SameLine();
@ -174,7 +174,7 @@ internal sealed class LegacyMetaUi
{
_sourceApplyMessage = $"Error: {ex.Message}";
}
_sourceApplyTime = DateTime.Now;
_sourceApplyTime = RynthClock.Now;
}
ImGui.SameLine();
@ -182,7 +182,7 @@ internal sealed class LegacyMetaUi
{
_sourceText = AfFileWriter.SaveToString(_settings.MetaRules, _settings.EmbeddedNavs);
_sourceApplyMessage = "Reverted to current rules.";
_sourceApplyTime = DateTime.Now;
_sourceApplyTime = RynthClock.Now;
}
RenderMetaEditorPopup();
@ -210,7 +210,7 @@ internal sealed class LegacyMetaUi
bool anyFired = false;
foreach (var r in stateRules)
{
if ((DateTime.Now - r.LastFiredAt).TotalMilliseconds < 1500)
if ((RynthClock.Now - r.LastFiredAt).TotalMilliseconds < 1500)
{
anyFired = true;
break;
@ -245,7 +245,7 @@ internal sealed class LegacyMetaUi
ImGui.TableNextRow();
double fadeMs = (DateTime.Now - rule.LastFiredAt).TotalMilliseconds;
double fadeMs = (RynthClock.Now - rule.LastFiredAt).TotalMilliseconds;
bool isFlashing = fadeMs < 1500;
if (isFlashing)
{
@ -1078,7 +1078,7 @@ internal sealed class LegacyMetaUi
_openSavePopup = true;
// Status message
if (!string.IsNullOrEmpty(_statusMessage) && (DateTime.Now - _statusTime).TotalSeconds < 5)
if (!string.IsNullOrEmpty(_statusMessage) && (RynthClock.Now - _statusTime).TotalSeconds < 5)
SafeImGui.TextColored(new Vector4(0, 1, 0, 1), _statusMessage);
// Save popup
@ -1158,7 +1158,7 @@ internal sealed class LegacyMetaUi
_settings.CurrentState = "Default";
_settings.ForceStateReset = true;
_statusMessage = "Macro cleared.";
_statusTime = DateTime.Now;
_statusTime = RynthClock.Now;
return true;
}
@ -1174,7 +1174,7 @@ internal sealed class LegacyMetaUi
else
{
_statusMessage = "Unsupported file type";
_statusTime = DateTime.Now;
_statusTime = RynthClock.Now;
return false;
}
@ -1186,7 +1186,7 @@ internal sealed class LegacyMetaUi
_statusMessage = loaded.Warnings.Count > 0
? $"No rules parsed — {loaded.Warnings.Count} warning(s): {loaded.Warnings[0]}"
: "No rules found (profile?)";
_statusTime = DateTime.Now;
_statusTime = RynthClock.Now;
return false;
}
@ -1207,13 +1207,13 @@ internal sealed class LegacyMetaUi
_statusMessage = loaded.Warnings.Count == 0
? $"Loaded {loaded.Rules.Count} rules / {stateCount} states / {loaded.EmbeddedNavs.Count} navs from {name}"
: $"Loaded {loaded.Rules.Count} rules / {stateCount} states from {name} — {loaded.Warnings.Count} warning(s): {loaded.Warnings[0]}";
_statusTime = DateTime.Now;
_statusTime = RynthClock.Now;
return true;
}
catch (Exception ex)
{
_statusMessage = $"Load error: {ex.Message}";
_statusTime = DateTime.Now;
_statusTime = RynthClock.Now;
return false;
}
}
@ -1247,7 +1247,7 @@ internal sealed class LegacyMetaUi
path = Path.ChangeExtension(path, ".af");
_settings.CurrentMetaPath = path;
_statusMessage = $"Converted .met → {Path.GetFileName(path)} for editing (original .met left untouched)";
_statusTime = DateTime.Now;
_statusTime = RynthClock.Now;
}
lock (_settings.MetaRulesLock)
@ -1264,7 +1264,7 @@ internal sealed class LegacyMetaUi
if (string.IsNullOrWhiteSpace(_saveName))
{
_statusMessage = "Enter a file name";
_statusTime = DateTime.Now;
_statusTime = RynthClock.Now;
return;
}
@ -1277,18 +1277,18 @@ internal sealed class LegacyMetaUi
if (!saved)
{
_statusMessage = $"Couldn't save {filePath}: {why}";
_statusTime = DateTime.Now;
_statusTime = RynthClock.Now;
return;
}
_statusMessage = $"Saved to {_saveName}.af";
_statusTime = DateTime.Now;
_statusTime = RynthClock.Now;
RefreshMacroFileList();
}
catch (Exception ex)
{
_statusMessage = $"Save error: {ex.Message}";
_statusTime = DateTime.Now;
_statusTime = RynthClock.Now;
}
}
}

View file

@ -42,7 +42,7 @@ internal sealed class RynthChatUi
lock (_lock)
{
_lines.Add(new ChatLine(text, chatType, DateTime.Now));
_lines.Add(new ChatLine(text, chatType, RynthClock.Now));
int max = Math.Max(50, _settings.ChatMaxLines);
int overflow = _lines.Count - max;

View file

@ -79,13 +79,13 @@ public sealed class InventoryManager
public void RunManual(bool cram, bool stack)
{
if (cram) _manualCramUntil = DateTime.Now.AddSeconds(60);
if (stack) _manualStackUntil = DateTime.Now.AddSeconds(60);
if (cram) _manualCramUntil = RynthClock.Now.AddSeconds(60);
if (stack) _manualStackUntil = RynthClock.Now.AddSeconds(60);
_nextInventoryActionTime = DateTime.MinValue;
}
private bool ManualCram => DateTime.Now < _manualCramUntil;
private bool ManualStack => DateTime.Now < _manualStackUntil;
private bool ManualCram => RynthClock.Now < _manualCramUntil;
private bool ManualStack => RynthClock.Now < _manualStackUntil;
public void OnHeartbeat(int busyCount)
{
@ -97,13 +97,13 @@ public sealed class InventoryManager
// that haven't been touched in BackoffMaxIdleMs are dropped so they don't
// accumulate across a multi-hour session; live backoff state persists so a
// genuinely-unmovable item stays backed off.
if ((DateTime.Now - _lastBackoffPrune).TotalMilliseconds >= BackoffPruneIntervalMs)
if ((RynthClock.Now - _lastBackoffPrune).TotalMilliseconds >= BackoffPruneIntervalMs)
{
PruneBackoff();
_lastBackoffPrune = DateTime.Now;
_lastBackoffPrune = RynthClock.Now;
}
if (DateTime.Now < _nextInventoryActionTime) return;
if (RynthClock.Now < _nextInventoryActionTime) return;
// Snapshot inventory once per tick — both passes use the same list.
var inv = _cache.GetDirectInventory(forceRefresh: true).ToList();
@ -115,19 +115,19 @@ public sealed class InventoryManager
// each other if AutoStack keeps finding new partial pairs every tick.
if (ProcessAutoCram(inv, (int)playerId))
{
_nextInventoryActionTime = DateTime.Now.AddMilliseconds(500);
_nextInventoryActionTime = RynthClock.Now.AddMilliseconds(500);
return;
}
if (ProcessAutoStack(inv, (int)playerId))
{
_nextInventoryActionTime = DateTime.Now.AddMilliseconds(500);
_nextInventoryActionTime = RynthClock.Now.AddMilliseconds(500);
return;
}
// Nothing to do — back off re-scan for a bit, and end a manual run.
_manualCramUntil = _manualStackUntil = DateTime.MinValue;
_nextInventoryActionTime = DateTime.Now.AddMilliseconds(2000);
_nextInventoryActionTime = RynthClock.Now.AddMilliseconds(2000);
}
// ── AutoCram ──────────────────────────────────────────────────────────
@ -154,7 +154,7 @@ public sealed class InventoryManager
_cramBackoff.Remove(item.Id);
continue;
}
if ((DateTime.Now - cp.EnqueuedAt).TotalMilliseconds < MoveConfirmGraceMs)
if ((RynthClock.Now - cp.EnqueuedAt).TotalMilliseconds < MoveConfirmGraceMs)
continue; // still in flight — don't re-enqueue or blacklist
_cramPending.Remove(item.Id);
RegisterFailure(_cramBackoff, item.Id);
@ -162,7 +162,7 @@ public sealed class InventoryManager
continue;
}
// Backed-off after a confirmed failure: skip until NextRetry.
if (_cramBackoff.TryGetValue(item.Id, out var cb) && DateTime.Now < cb.NextRetry)
if (_cramBackoff.TryGetValue(item.Id, out var cb) && RynthClock.Now < cb.NextRetry)
continue;
// Skip items the user has registered in the RynthAi Weapons tab —
// those are weapons they want to keep accessible at the top level.
@ -227,7 +227,7 @@ public sealed class InventoryManager
// Enqueue accepted — record as PENDING and confirm on a later snapshot (do
// NOT blacklist; success and a deferred-but-pending move look identical here).
_cramPending[item.Id] = new Pending { EnqueuedAt = DateTime.Now, FromContainer = playerId };
_cramPending[item.Id] = new Pending { EnqueuedAt = RynthClock.Now, FromContainer = playerId };
return true; // one action per tick
}
@ -320,14 +320,14 @@ public sealed class InventoryManager
_stackBackoff.Remove(key);
continue; // this pair resolved — try another
}
if ((DateTime.Now - sp.EnqueuedAt).TotalMilliseconds < MoveConfirmGraceMs)
if ((RynthClock.Now - sp.EnqueuedAt).TotalMilliseconds < MoveConfirmGraceMs)
continue; // still in flight — skip this pair this tick
_stackPending.Remove(key);
RegisterFailure(_stackBackoff, key);
_host.Log($"[RynthAi] AutoStack: CONFIRMED merge failure {key} (source survived after {MoveConfirmGraceMs:0}ms) — backing off");
continue;
}
if (_stackBackoff.TryGetValue(key, out var sb) && DateTime.Now < sb.NextRetry)
if (_stackBackoff.TryGetValue(key, out var sb) && RynthClock.Now < sb.NextRetry)
continue; // backed off — try another pair
chosenTarget = parts[ti];
chosenSource = parts[si];
@ -356,7 +356,7 @@ public sealed class InventoryManager
// Enqueue accepted — record PENDING, confirm on a later snapshot. Do NOT
// add the pair-key on success (the old bug that poisoned good merges and
// starved multi-partial consolidation).
_stackPending[pairKey] = new Pending { EnqueuedAt = DateTime.Now, FromContainer = playerId, TargetCount = target.Count, SourceCount = source.Count };
_stackPending[pairKey] = new Pending { EnqueuedAt = RynthClock.Now, FromContainer = playerId, TargetCount = target.Count, SourceCount = source.Count };
return true; // one action per tick
}
@ -374,21 +374,21 @@ public sealed class InventoryManager
map[key] = b;
}
b.Attempts++;
b.LastTouched = DateTime.Now;
b.LastTouched = RynthClock.Now;
int shift = b.Attempts - 1;
if (shift > 6) shift = 6; // cap the shift so the multiply can't overflow
double delay = BackoffBaseMs * (1 << shift); // 5s,10s,20s,40s,80s,160s,320s→capped
if (delay > BackoffMaxMs) delay = BackoffMaxMs;
// Past the attempt budget, park far out (still age-pruned) instead of looping.
if (b.Attempts >= MaxAttemptsBudget) delay = BackoffMaxMs;
b.NextRetry = DateTime.Now.AddMilliseconds(delay);
b.NextRetry = RynthClock.Now.AddMilliseconds(delay);
}
// Age-prune dead/idle entries so the maps don't grow unbounded across a long
// session (the wholesale clear used to be the de-facto bound).
private void PruneBackoff()
{
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
PruneMap(_cramBackoff, b => b.LastTouched, now);
PruneMap(_stackBackoff, b => b.LastTouched, now);
PruneMap(_cramPending, p => p.EnqueuedAt, now);

View file

@ -126,6 +126,16 @@ internal sealed class ManaStoneManager
/// </summary>
public Func<WorldObject, bool>? IsLootKept { get; set; }
/// <summary>
/// Set by the plugin (RynthAiPlugin.FightIsOn): true while a fight is on. Draining loot into an
/// empty stone is optional work and waits for it to end: every UseObjectOn cancels the move-to
/// chains and bumps the busy count, and between melee swings it held the next swing (a swing
/// repeat is not a paced action). Refilling worn gear that runs low still goes ahead: armor
/// with no mana drops its spells mid-fight.
/// </summary>
public Func<bool>? FightIsOn { get; set; }
private bool _drainHeldForFight;
// Items the looter picked up as "ManaTap" (looted only to be drained), with the
// time each was recorded. Draining destroys the item, so these are the ONLY tap
// targets: gear, quest items, bought items and loot kept by a rule are never in
@ -538,7 +548,9 @@ internal sealed class ManaStoneManager
// can loop forever on items like wielded weapons that AC won't
// refill via stone — that loop blacklists stones one by one and
// starves the drain path entirely.
int stoneId = _settings.EnableManaTapping ? FindEmptyStone() : 0;
// Not in a fight (FightIsOn): the drain waits for it to end.
bool drainWaits = DrainWaitsForFight();
int stoneId = _settings.EnableManaTapping && !drainWaits ? FindEmptyStone() : 0;
int targetId = stoneId != 0 ? FindTapTarget(threshold) : 0;
if (stoneId != 0 && targetId != 0)
@ -571,6 +583,28 @@ internal sealed class ManaStoneManager
}
}
/// <summary>
/// <see cref="FightIsOn"/> says a fight is on: drains wait. One log line per fight while an
/// item looted to tap is waiting.
/// </summary>
private bool DrainWaitsForFight()
{
bool fight;
try { fight = FightIsOn?.Invoke() == true; }
catch { fight = false; }
if (!fight)
{
_drainHeldForFight = false;
return false;
}
if (!_drainHeldForFight && _lootedForTap.Count > 0)
{
_drainHeldForFight = true;
_host.Log("[RynthAi] ManaStone: a fight is on - draining loot into a stone waits for it to end.");
}
return true;
}
private void IssueTapItem(int stoneId, int itemId)
{
_tapChatLogged = 0;
@ -683,6 +717,9 @@ internal sealed class ManaStoneManager
if (_state == TapState.TappingItem) return true;
if (_lootedForTap.Count == 0) return false;
if (!_settings.EnableManaTapping || !_settings.IsMacroRunning || !_host.HasUseObjectOn) return false;
// The drain waits for the fight to end, so it holds nothing meanwhile. No second item is
// looted to tap: FreeEmptyStoneSlots is 0 while this one waits.
if (DrainWaitsForFight()) return false;
long now = NowMs;
if (now - _holdLootAt < HoldCheckMs) return _holdLoot;
_holdLootAt = now;

View file

@ -2761,7 +2761,7 @@ internal sealed partial class ExpressionEngine
return false;
}
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
if (!IsCastWielded(wandId))
{

View file

@ -31,16 +31,16 @@ internal sealed class MetaManager
// ── State tracking ───────────────────────────────────────────────────────
private string _lastState = "";
private DateTime _stateStartTime = DateTime.Now;
private DateTime _stateStartTime = RynthClock.Now;
/// <summary>Wall clock for seconds-in-state, the watchdog and the chat window. Tests swap it
/// for a fake clock; the plugin never changes it.</summary>
internal Func<DateTime> Clock { get; set; } = static () => DateTime.Now;
internal Func<DateTime> Clock { get; set; } = static () => RynthClock.Now;
private bool _lastMacroRunning;
// PSecsInStateGE's clock: seconds spent in the current state. Restarts when the meta moves to
// a different state or a meta is loaded; keeps running over a macro stop/start and a SetState
// to the same state; pauses while the state has Called another and resumes on the Return.
private DateTime _statePStartTime = DateTime.Now;
private DateTime _statePStartTime = RynthClock.Now;
// Seconds the calling state had on its P clock, one entry per _stateStack entry (null when the
// Return goes to a different state than the one that called).
private readonly Stack<double?> _statePPaused = new();

View file

@ -63,7 +63,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
/// </summary>
private void BlacklistTarget(int targetId)
{
DateTime expirationTime = DateTime.Now.AddSeconds(TimeoutSeconds);
DateTime expirationTime = RynthClock.Now.AddSeconds(TimeoutSeconds);
_blacklistExpirations[targetId] = expirationTime;
int fc = _failureCounts.TryGetValue(targetId, out var c) ? c : 0;
@ -82,7 +82,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
return false; // Target not in blacklist
// Check if blacklist timeout has expired
if (DateTime.Now >= expiration)
if (RynthClock.Now >= expiration)
{
// Timeout expired - remove from blacklist and allow re-evaluation
_blacklistExpirations.Remove(targetId);
@ -138,7 +138,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
foreach (var kvp in _blacklistExpirations)
{
if (DateTime.Now < kvp.Value)
if (RynthClock.Now < kvp.Value)
{
count++;
}

View file

@ -1807,7 +1807,7 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra ghost: select the monster that never takes a swing first.");
return;
}
double silent = _combatManager.ServerSilentMs((int)sel, DateTime.Now);
double silent = _combatManager.ServerSilentMs((int)sel, RynthClock.Now);
_combatManager.MarkGhost((int)sel, wo.Name, silent, "marked by /ra ghost");
ChatLine($"[RynthAi] 0x{sel:X8} '{wo.Name}' marked as a ghost" + (canRemove ? " and sent for removal from the client (see the log)." : " (this engine can't remove it from the client; it is skipped)."));
return;
@ -1842,7 +1842,7 @@ public sealed partial class RynthAiPlugin
return;
}
ChatLine($"[RynthAi] {ghosts.Count} ghost(s) skipped by combat (the client draws them, the server doesn't have them):");
DateTime now = DateTime.Now;
DateTime now = RynthClock.Now;
foreach (var g in ghosts.All)
{
double silent = _combatManager.ServerSilentMs(g.Id, now);
@ -1858,7 +1858,7 @@ public sealed partial class RynthAiPlugin
if (_combatManager == null) { ChatLine("[RynthAi] Combat manager not ready."); return; }
var s = _combatManager.GetStateSnapshot();
var now = DateTime.Now;
var now = RynthClock.Now;
double sinceAttackS = s.LastAttackCmd == DateTime.MinValue ? -1 : (now - s.LastAttackCmd).TotalSeconds;
double sinceLostS = s.TargetLostScanTime == DateTime.MinValue ? -1 : (now - s.TargetLostScanTime).TotalSeconds;
double sinceStanceS = s.LastStanceAttempt == DateTime.MinValue ? -1 : (now - s.LastStanceAttempt).TotalSeconds;

View file

@ -0,0 +1,37 @@
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
// Item chores and fights (structural audit 2026-10-21, finding 3): missile crafting held combat with
// no danger check, and mana tapping and AutoCram/AutoStack acted between swings (their only gate was
// the busy count, and a swing repeat is not a paced action). They now all wait on one signal,
// FightIsOn, the one salvage already used.
public sealed partial class RynthAiPlugin
{
/// <summary>
/// A fight is on: a monster within Monster Range or on top of us, or the target combat is locked
/// on (CombatManager.HasEngageableTarget, the arbiter's Combat input, and IsUnderCloseAttack).
/// Optional item work waits for it to end: salvage, AutoCram/AutoStack, draining loot into mana
/// stones, reading scrolls, and missile crafting's optional crafts (MissileCraftingManager).
/// Only with the macro on: the target scan stops with the macro, and its last picture must not
/// hold a /ub autocram or a salvage the player asks for.
/// </summary>
internal bool FightIsOn(LegacyUiSettings? s = null)
{
s ??= _dashboard?.Settings;
if (s == null || !s.IsMacroRunning || !s.EnableCombat) return false;
var combat = _combatManager;
return combat != null && (combat.HasEngageableTarget || combat.IsUnderCloseAttack);
}
/// <summary>
/// AutoCram / AutoStack, one tick: not while a corpse is open or claimed, and not in a fight (a
/// pack move went out between melee swings). The manager itself waits for the busy count.
/// </summary>
private void TickCramStack(LegacyUiSettings settings)
{
if (_inventoryManager == null || _openedContainerId != 0 || _targetCorpseId != 0) return;
if (FightIsOn(settings)) return;
Guard(TickStep.CramStack, () => _inventoryManager?.OnHeartbeat(PacedBusy));
}
}

View file

@ -38,8 +38,7 @@ public sealed partial class RynthAiPlugin
{
if (!s.IsMacroRunning) return false;
if (_activity is BotActivity.Combat or BotActivity.Buffing or BotActivity.Looting or BotActivity.Salvaging) return false;
var combat = _combatManager;
if (combat != null && (combat.HasEngageableTarget || combat.IsUnderCloseAttack)) return false;
if (FightIsOn(s)) return false;
if (_openedContainerId != 0 || _targetCorpseId != 0) return false;
if (_buffManager != null && _buffManager.PendingSpellId != 0) return false;
if (_salvageManager?.IsBusy == true) return false;

View file

@ -169,7 +169,7 @@ public sealed partial class RynthAiPlugin
try
{
string folder = PropertyDump.Folder;
string path = Path.Combine(folder, PropertyDump.FileName(data.Name.Length > 0 ? data.Name : $"0x{data.Id:X8}", DateTime.Now));
string path = Path.Combine(folder, PropertyDump.FileName(data.Name.Length > 0 ? data.Name : $"0x{data.Id:X8}", RynthClock.Now));
if (DataWriteGuard.TrySave("Property dump", path, () =>
{
Directory.CreateDirectory(folder);

View file

@ -0,0 +1,51 @@
using System;
namespace RynthCore.Plugin.RynthAi;
// Each OnTick step runs under its own guard (Diagnostics/TickGuard.cs): one that throws every tick
// is logged and, unless it is essential, switched off for a while; the rest of the tick still runs,
// healing and combat above all (structural audit 2026-10-21, finding 4).
public sealed partial class RynthAiPlugin
{
private TickGuard? _tickGuard;
/// <summary>The steps' fault counters (internal for the host tests).</summary>
internal TickGuard TickGuards => _tickGuard ??= new TickGuard(m => Host.Log(m), m => Host.WriteToChat(m, 2));
/// <summary>Runs one OnTick step: an exception is logged and counted, and the tick goes on.</summary>
private void Guard(TickStep step, Action run)
{
TickGuard g = TickGuards;
if (!g.MayRun(step)) return;
try
{
run();
g.Succeeded(step);
}
catch (Exception ex) { g.Failed(step, ex); }
}
/// <summary>
/// Runs one OnTick step that answers "hold the rest of the tick". A fault, or the step switched
/// off, answers <paramref name="whenFaulted"/> (false: the tick goes on).
/// </summary>
private bool GuardHold(TickStep step, Func<bool> run, bool whenFaulted = false)
{
TickGuard g = TickGuards;
if (!g.MayRun(step)) return whenFaulted;
try
{
bool hold = run();
g.Succeeded(step);
return hold;
}
catch (Exception ex)
{
g.Failed(step, ex);
return whenFaulted;
}
}
/// <summary>The meta's tick, in every hold and at the end of the tick, under one guard.</summary>
private void ThinkMeta() => Guard(TickStep.Meta, () => _metaManager?.Think());
}

View file

@ -553,7 +553,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (_dashboard is null)
return;
_loginCompletedAt = DateTime.Now;
_loginCompletedAt = RynthClock.Now;
_loginComplete = true;
_killClock.SessionStarted();
_dashboard.OnLoginComplete();
@ -769,6 +769,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_missileCraftingManager.SetObjectCache(_objectCache!);
_missileCraftingManager.SetCharacterSkills(_charSkills);
_missileCraftingManager.HoldWhile = () => _combatManager?.AmmoSwapInProgress == true;
_missileCraftingManager.FightIsOn = () => FightIsOn(); // optional crafts wait for the fight (RynthAiPlugin.Chores.cs)
_dashboard.SetMissileCraftingManager(_missileCraftingManager);
_fellowshipTracker?.Dispose();
@ -799,6 +800,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_manaStoneManager = new ManaStoneManager(Host, _dashboard.Settings, _objectCache);
LegacyUi.NavPoint.SpellNameLookup = id => SpellTableStub.GetById(id)?.Name; // recall steps by name
_manaStoneManager.IsLootKept = IsKeptByLootProfile;
_manaStoneManager.FightIsOn = () => FightIsOn(); // drains wait for the fight (RynthAiPlugin.Chores.cs)
_petManager = new PetManager(Host, _dashboard.Settings, _objectCache, _combatManager, _charSkills);
_combatManager.SummonOut = () => _petManager?.CurrentSummon();
}
@ -1443,14 +1445,17 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
bool diag = ++_tickDiag <= 3;
try
{
_dashboard?.DrainMetaCommands(); // apply queued meta edits on this (plugin-tick) thread
if (_loginComplete) PostDataWriteProblems(); // a save that failed / folder not writable: say so in chat
CombatHook.ObserveUseDone(); // ctx.last.err: the answer to the hook's last cast
TickDelayedCommands(); // /ub delay
GameInput.Pump(); // release keys held for /mt movement | jump | strafe
DrainEngineCommands(); // fellowship command buttons (RynthCore's Fellowship section)
TickPropertyDump(); // /ub propertydump: waits for the ID, chat in chunks
if (_loginComplete) _dashboard?.TickPackSetup(_objectCache, _playerId); // new/copied profile items
// Each step below runs under its own guard (RynthAiPlugin.TickGuard.cs): one that throws
// is logged and the rest of the tick still runs. The try/catch round the whole tick only
// catches what sits between the steps.
Guard(TickStep.MetaCommands, () => _dashboard?.DrainMetaCommands()); // apply queued meta edits on this (plugin-tick) thread
if (_loginComplete) Guard(TickStep.DataWriteProblems, PostDataWriteProblems); // a save that failed / folder not writable: say so in chat
Guard(TickStep.CombatHook, CombatHook.ObserveUseDone); // ctx.last.err: the answer to the hook's last cast
Guard(TickStep.DelayedCommands, TickDelayedCommands); // /ub delay
Guard(TickStep.GameInput, GameInput.Pump); // release keys held for /mt movement | jump | strafe
Guard(TickStep.EngineCommands, DrainEngineCommands); // fellowship command buttons (RynthCore's Fellowship section)
Guard(TickStep.PropertyDump, () => TickPropertyDump()); // /ub propertydump: waits for the ID, chat in chunks
if (_loginComplete) Guard(TickStep.PackSetup, () => _dashboard?.TickPackSetup(_objectCache, _playerId)); // new/copied profile items
// /ra pause <sec>: restart the macro once the window elapses. Cleared by
// an explicit /ra start or /ra stop, so a manual decision always wins.
@ -1487,66 +1492,26 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
catch (Exception ex) { Host.Log($"[RynthAi] forwarded remote command '{fwd.action}' failed: {ex.Message}"); }
}
// ── Push settings to engine each tick ──────────────────────
// RynthAi has no render hook (it draws nothing itself). OnTick runs
// unconditionally via PluginManager.TickAll, including in
// Decal-coexistence mode. Push the suppression toggles here so the
// settings panel controls the radar/powerbar.
// (Renamed local to `pushSettings` to avoid collision with the
// `settings` local declared further down in OnTick.)
var pushSettings = _dashboard?.Settings;
if (diag)
Host.Log($"[RynthAi] OnTick: settings push entry — settings null? {pushSettings == null}, HasSetRadarSuppressed={Host.HasSetRadarSuppressed}");
if (pushSettings != null)
{
if (diag)
Host.Log($"[RynthAi] OnTick: pushSettings.SuppressRetailRadar={pushSettings.SuppressRetailRadar}, SuppressRetailPowerbar={pushSettings.SuppressRetailPowerbar}");
Host.SetFpsLimit(pushSettings.EnableFPSLimit, pushSettings.TargetFPSFocused, pushSettings.TargetFPSBackground);
// "Hide UI" (remote): blank the vanilla AC radar/powerbar too. The RynthAi Avalonia
// panels are separate windows already excluded by the stream's PrintWindow capture.
// NOTE: retail chat suppression is intentionally NOT handled here — it is owned by
// the RynthChat plugin (engine-side ChatHooks, driven from RynthChatPanel's gear menu).
// RynthAi pushing it every tick clobbered that toggle, so it lives solely in RynthChat now.
bool hideUi = _hideUi;
if (Host.HasSetRadarSuppressed)
Host.SetRadarSuppressed(hideUi || pushSettings.SuppressRetailRadar);
if (Host.HasSetPowerbarSuppressed)
Host.SetPowerbarSuppressed(hideUi || pushSettings.SuppressRetailPowerbar);
Guard(TickStep.SettingsPush, () => PushSettingsToEngine(diag));
// Fellowship-follow: publish the leader's object id so the nav
// engine can steer toward their live position. 0 = idle (not in a
// fellowship, or we ARE the leader — a leader shouldn't follow itself).
if (pushSettings.FollowMode && pushSettings.FollowNamedTargetId != 0)
{
pushSettings.FollowTargetId = pushSettings.FollowNamedTargetId;
}
else if (pushSettings.FollowMode && _fellowshipTracker != null)
{
int leader = _fellowshipTracker.LeaderId;
pushSettings.FollowTargetId =
(leader != 0 && !_fellowshipTracker.IsLeader) ? unchecked((uint)leader) : 0u;
}
else
{
pushSettings.FollowTargetId = 0;
}
}
_objectCache?.Tick();
Guard(TickStep.WorldCache, () => _objectCache?.Tick());
if (diag) Host.Log("[RynthAi] OnTick: after cache tick");
if (_loginComplete) TickDifficultyTier();
if (_loginComplete) Guard(TickStep.DifficultyTier, TickDifficultyTier);
// A stop the action pacing held (nothing of ours moving, a server action unanswered)
// goes out as soon as the server has answered: a stop is never dropped (2026-10-12).
if (_loginComplete) RynthCore.Plugin.Shared.MoveAudit.FlushPendingStops(Host, "once the server answered");
if (_loginComplete) Guard(TickStep.PendingStops, () => RynthCore.Plugin.Shared.MoveAudit.FlushPendingStops(Host, "once the server answered"));
// Periodically flush the creature profile store (~ every 5 seconds at 60Hz).
if (++_creatureSaveTickCounter >= 300)
{
_creatureSaveTickCounter = 0;
_creatureStore?.SaveIfDirty();
_damageStore?.SaveIfDirty();
Guard(TickStep.CreatureSave, () =>
{
_creatureStore?.SaveIfDirty();
_damageStore?.SaveIfDirty();
});
}
// Deferred per-character settings load. OnLoginComplete tries
@ -1602,7 +1567,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (++_settingsSaveTickCounter >= 120)
{
_settingsSaveTickCounter = 0;
_dashboard?.TickAutoSave();
Guard(TickStep.AutoSave, () => _dashboard?.TickAutoSave());
}
// Dungeon floor plans on disk for DrakRemote (StatusAgent /map), whether or not a
// map panel is open: one pose read about twice a second; the bake itself runs once
@ -1610,20 +1575,23 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (_loginComplete && ++_mapBakeTickCounter >= 30)
{
_mapBakeTickCounter = 0;
_dashboard?.TickDungeonMapBake();
Guard(TickStep.MapBake, () => _dashboard?.TickDungeonMapBake());
}
// Pick up an external Monster Editor save (monsters.json watcher). This used
// to run only inside the legacy dashboard's Render(), which the engine no
// longer calls, so edits waited for the next login. A flag check when idle.
_dashboard?.TickMonsterReload();
// A nav saved into NavProfiles from outside (RynthNav's "save as nav route"): list it.
_dashboard?.TickNavFolder();
_questTracker?.Tick();
TickLocalFeatures();
Guard(TickStep.WatchedFiles, () =>
{
// Pick up an external Monster Editor save (monsters.json watcher). This used
// to run only inside the legacy dashboard's Render(), which the engine no
// longer calls, so edits waited for the next login. A flag check when idle.
_dashboard?.TickMonsterReload();
// A nav saved into NavProfiles from outside (RynthNav's "save as nav route"): list it.
_dashboard?.TickNavFolder();
});
Guard(TickStep.QuestTracker, () => _questTracker?.Tick());
Guard(TickStep.LocalFeatures, TickLocalFeatures);
if (diag) Host.Log("[RynthAi] OnTick: after quest tracker");
DrainGiveQueue();
Guard(TickStep.GiveQueue, DrainGiveQueue);
if (diag) Host.Log("[RynthAi] OnTick: after drain give queue");
_jumper?.Tick();
Guard(TickStep.Jumper, () => _jumper?.Tick());
if (diag) Host.Log("[RynthAi] OnTick: after jumper tick");
// ── Affirmative in-world gate ────────────────────────────────
@ -1669,65 +1637,51 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (diag) Host.Log("[RynthAi] OnTick: entering loginComplete block");
// One bot per client (Decal bridge): VTank's macro started -> ours stops, before
// anything below can move, attack, cast or buff this tick.
if (_dashboard?.Settings is { } yieldSettings) TickVTankYield(yieldSettings);
// Player vitals: AC sends none of its own health through OnUpdateHealth (that is the
// 0x01C0 health-of-a-target message), so this read is how the bot learns health
// dropped. It ran every 30th tick: ~1 s at a background client's 30 fps, 1.5-3 s on a
// slower or busier PC, added to every heal at random (2026-10-05, "heals sometimes
// late"). The engine's snapshot is a locked struct copy kept current by its vitals
// hook, so read it every VitalsPollMs instead.
long vitalsNow = Environment.TickCount64;
if (vitalsNow - _lastVitalsPollAt >= VitalsPollMs)
{
_lastVitalsPollAt = vitalsNow;
if (Host.HasGetPlayerVitals &&
Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out uint st, out uint maxSt, out uint mp, out uint maxMp))
{
_vitals.CurrentHealth = hp;
_vitals.MaxHealth = maxHp;
_vitals.CurrentStamina = st;
_vitals.MaxStamina = maxSt;
_vitals.CurrentMana = mp;
// A big move in the max-mana reading (a death, buffs landing or dropping) is logged:
// the floor and the reserve judge mana by it (2026-10-15).
if (_vitals.MaxMana > 0 && maxMp > 0
&& Math.Abs((long)maxMp - _vitals.MaxMana) * 100 >= 15L * _vitals.MaxMana)
Host.Log($"[RynthAi] Vitals: max mana reading {_vitals.MaxMana} -> {maxMp} (mana {mp}).");
_vitals.MaxMana = maxMp;
}
}
if (_dashboard?.Settings is { } yieldSettings) Guard(TickStep.VTankYield, () => TickVTankYield(yieldSettings));
Guard(TickStep.VitalsRead, PollPlayerVitals);
if (_dashboard?.Settings is { } safetySettings)
{
CheckPlayerDeath(safetySettings);
CheckLowComponents(safetySettings);
Guard(TickStep.DeathCheck, () => CheckPlayerDeath(safetySettings));
Guard(TickStep.LowComponents, () => CheckLowComponents(safetySettings));
}
// Dead or on the way back from a death: do nothing (HoldForDeath). The
// finally below still submits the nav markers.
RynthCore.Plugin.Shared.ActionPacer.NoteFrame();
// Stuck Cast Break, once per tick: the breaker runs for every subsystem's casts.
if (_dashboard?.Settings is { } paceSettings)
Guard(TickStep.Pacing, () =>
{
RynthCore.Plugin.Shared.ActionPacer.StuckCastMs = Math.Max(0, paceSettings.StuckCastBreakMs);
NoteMacroForPacer(paceSettings.IsMacroRunning);
}
NotePortalForPacer();
if (HoldForDeath())
RynthCore.Plugin.Shared.ActionPacer.NoteFrame();
// Stuck Cast Break, once per tick: the breaker runs for every subsystem's casts.
if (_dashboard?.Settings is { } paceSettings)
{
RynthCore.Plugin.Shared.ActionPacer.StuckCastMs = Math.Max(0, paceSettings.StuckCastBreakMs);
NoteMacroForPacer(paceSettings.IsMacroRunning);
}
NotePortalForPacer();
});
// A hold whose check throws holds nothing: the tick goes on (healing, combat).
if (GuardHold(TickStep.DeathHold, HoldForDeath))
return;
// Recall On Death in progress: nothing else until it lands or gives up.
if (TickDeathRecall())
if (GuardHold(TickStep.DeathRecall, TickDeathRecall))
return;
// Standing in acid or lava: nothing but getting out (RynthAiPlugin.HazardEscape.cs).
RecordHazardTrail();
if (HoldForHazardEscape())
if (GuardHold(TickStep.HazardEscape, () =>
{
RecordHazardTrail();
return HoldForHazardEscape();
}))
return;
if (diag) Host.Log("[RynthAi] OnTick: before CheckBusyTimeout");
CheckBusyTimeout();
Guard(TickStep.BusyTimeout, CheckBusyTimeout);
if (diag) Host.Log("[RynthAi] OnTick: before buffManager");
_buffManager?.OnHeartbeat();
// Healing and buffs: essential, never switched off by its guard (TickGuard).
Guard(TickStep.BuffsAndVitals, () => _buffManager?.OnHeartbeat());
if (diag) Host.Log("[RynthAi] OnTick: after buffManager");
NoteCarriedOverSessionReady();
UpdateReloadBlocker();
Guard(TickStep.ReloadBlocker, () =>
{
NoteCarriedOverSessionReady();
UpdateReloadBlocker();
});
var settings = _dashboard?.Settings;
if (settings == null)
@ -1775,17 +1729,20 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_macroWasRunning = settings.IsMacroRunning;
_killClock.ObserveMacro(settings.IsMacroRunning); // a start counts even if nothing reads the clock meanwhile
if (_patrolOnLoginPending && _raycast?.GeometryLoader?.CellDat?.IsLoaded == true)
Guard(TickStep.PatrolReroute, () =>
{
_patrolOnLoginPending = false;
HandleDungeonNavPatrol();
}
if (_patrolOnLoginPending && _raycast?.GeometryLoader?.CellDat?.IsLoaded == true)
{
_patrolOnLoginPending = false;
HandleDungeonNavPatrol();
}
// Reroute the active dungeon patrol around any lava/acid hotspot sighted
// since the route was built — treats the hotspot as a wall instead of
// looping through it — or with the Dungeon Patrol settings changed since.
// Cheap no-op unless a new hazard cell was registered or a setting changed.
TickDunPatrolHazardReroute();
// Reroute the active dungeon patrol around any lava/acid hotspot sighted
// since the route was built — treats the hotspot as a wall instead of
// looping through it — or with the Dungeon Patrol settings changed since.
// Cheap no-op unless a new hazard cell was registered or a setting changed.
TickDunPatrolHazardReroute();
});
// ── Activity arbiter — STEP 5: AUTHORITATIVE, full stop ──
// The arbiter is the SOLE writer of every BotAction string, and
@ -1839,19 +1796,19 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
else
{
if (_buffingHeldSince == DateTime.MinValue)
_buffingHeldSince = DateTime.Now;
_buffingHeldSince = RynthClock.Now;
double heldMs = (DateTime.Now - _buffingHeldSince).TotalMilliseconds;
double heldMs = (RynthClock.Now - _buffingHeldSince).TotalMilliseconds;
// A coma is buffing that has STOPPED casting, not a long cycle: a full
// rebuff with Stamina to Mana refills runs past 5 min, and yielding a tick
// every 10 s then handed Combat the tick mid-cycle, which drew the weapon
// and changed stance between buffs (10-02 18:47, "pulls a weapon out and
// fights mid buff cycle"). Only when nothing was cast for BuffComaIdleMs.
double idleMs = (DateTime.Now - _buffManager!.LastCastAttemptAt).TotalMilliseconds;
double idleMs = (RynthClock.Now - _buffManager!.LastCastAttemptAt).TotalMilliseconds;
if (heldMs > BuffComaThresholdMs && idleMs > BuffComaIdleMs
&& (DateTime.Now - _lastBuffComaBypassAt).TotalMilliseconds > BuffComaBypassEveryMs)
&& (RynthClock.Now - _lastBuffComaBypassAt).TotalMilliseconds > BuffComaBypassEveryMs)
{
_lastBuffComaBypassAt = DateTime.Now;
_lastBuffComaBypassAt = RynthClock.Now;
wantBuff = false; // yield ONE tick so stance recovery can run
if (!_buffComaWarned)
{
@ -1964,39 +1921,33 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// inventory — UB takes VTank's Navigation + ItemUse locks the same way.
// Bounded by AutoVendor's own 60 s bail timer.
var autoVendor = _autoVendor;
if (autoVendor != null)
if (autoVendor != null
&& GuardHold(TickStep.AutoVendor, () => { autoVendor.Tick(_busyCount); return autoVendor.HoldsBot; }))
{
autoVendor.Tick(_busyCount);
if (autoVendor.HoldsBot)
{
if (settings.IsMacroRunning)
StopNavFor(BotActivity.Idle);
KeepThreatScanFresh(settings);
FreezeCorpseTimeout(CorpseNowMs); // a claimed corpse must not time out while held
_metaManager?.Think();
return;
}
if (settings.IsMacroRunning)
StopNavFor(BotActivity.Idle);
KeepThreatScanFresh(settings);
FreezeCorpseTimeout(CorpseNowMs); // a claimed corpse must not time out while held
ThinkMeta();
return;
}
// ── AutoTrade (UtilityBelt-style) ────────────────────────────────
// Same hold as AutoVendor while it fills a trade window: UB takes VTank's
// Navigation + ItemUse locks. Bounded by AutoTrade's own 10 s bail timer.
var autoTrade = _autoTrade;
if (autoTrade != null)
if (autoTrade != null
&& GuardHold(TickStep.AutoTrade, () => { autoTrade.Tick(_busyCount); return autoTrade.HoldsBot; }))
{
autoTrade.Tick(_busyCount);
if (autoTrade.HoldsBot)
{
if (settings.IsMacroRunning)
StopNavFor(BotActivity.Idle);
KeepThreatScanFresh(settings);
FreezeCorpseTimeout(CorpseNowMs); // a claimed corpse must not time out while held
_metaManager?.Think();
return;
}
if (settings.IsMacroRunning)
StopNavFor(BotActivity.Idle);
KeepThreatScanFresh(settings);
FreezeCorpseTimeout(CorpseNowMs); // a claimed corpse must not time out while held
ThinkMeta();
return;
}
TickWeaponElements();
Guard(TickStep.WeaponElements, TickWeaponElements);
// ── Priority 1: Buffing ───────────────────────────────────────────
// Blocks combat, looting, and navigation entirely. The coma
@ -2007,40 +1958,30 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
StopNavFor(BotActivity.Buffing);
KeepThreatScanFresh(settings);
FreezeCorpseTimeout(CorpseNowMs); // a claimed corpse must not time out while held
_metaManager?.Think();
ThinkMeta();
return;
}
// AutoCram / AutoStack — only while idle (not looting a corpse, not crafting).
// AutoCram / AutoStack — only while idle (not looting a corpse, not crafting, not
// in a fight: RynthAiPlugin.Chores.cs).
// Gated on busy count inside the manager so it won't move items mid-cast.
// Skip InventoryManager for a short settle window after login.
// Its first call does a forced GetDirectInventory which walks every
// container via native calls — when the cache is still classifying
// hundreds of pending CreateObjects (RL hot-reload, fresh login),
// the concurrent native walk has been causing intermittent crashes.
bool inventorySettled = (DateTime.Now - _loginCompletedAt).TotalMilliseconds > 3000;
if (inventorySettled
&& _inventoryManager != null
&& _openedContainerId == 0
&& _targetCorpseId == 0)
{
_inventoryManager.OnHeartbeat(PacedBusy);
}
bool inventorySettled = (RynthClock.Now - _loginCompletedAt).TotalMilliseconds > 3000;
if (inventorySettled)
TickCramStack(settings);
// Status feed: main-pack empty slots (cache-based, off-thread-safe). Throttled to
// ~3s — it walks direct inventory, no need every tick. Mirrors VTankLootEvaluator
// .GetMainPackEmptySlots so the phone shows when a box is about to run out of room.
if (inventorySettled && _objectCache != null && _playerId != 0
&& (DateTime.Now - _lastFreeSlotsPushAt).TotalMilliseconds > 3000)
&& (RynthClock.Now - _lastFreeSlotsPushAt).TotalMilliseconds > 3000)
{
_lastFreeSlotsPushAt = DateTime.Now;
ScanInventoryStatus(out int freeSlots, out int scarabs, out int tapers, out var scarabsByType, out var equipment);
_dashboard?.SetFreeSlots(freeSlots);
_dashboard?.SetComponentCounts(scarabs, tapers, scarabsByType);
_dashboard?.SetEquipment(AppraiseEquipment(equipment));
// Remote full-inventory snapshot (P1) — same 3s gate, reuses the cached walk.
ScanInventoryForRemote();
_lastFreeSlotsPushAt = RynthClock.Now;
Guard(TickStep.InventoryStatus, PushInventoryStatus);
}
// D2/D6 combat telemetry: three-tier target counts + offensive attack-cast/kill
@ -2048,33 +1989,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// live mobs" or "animates but 0 damage" wedge is diagnosable from the feed/log
// instead of guesswork. Independent of the inventory gate above — useful pre-settle.
if (_combatManager != null
&& (DateTime.Now - _lastCombatTelemetryAt).TotalMilliseconds > 3000)
&& (RynthClock.Now - _lastCombatTelemetryAt).TotalMilliseconds > 3000)
{
_lastCombatTelemetryAt = DateTime.Now;
int sTotal = _combatManager.LastScanTotalMonsters;
int sRing = _combatManager.LastScanInRing;
int sPoss = _combatManager.LastScanPossible;
int sLos = _combatManager.LastScanLosBlocked;
int atkCasts = _combatManager.SessionAttackCasts;
int sinceKill = _combatManager.CastsSinceLastKill;
_dashboard?.SetScanCounts(sTotal, sRing, sPoss, sLos);
_dashboard?.SetCastStats(atkCasts, sinceKill);
// Log only when there's something to see, and only when the picture changed,
// so a healthy idle bot never spams the per-client log. sinceKill is in the key
// so active combat shows periodic progress while a stalled-with-mobs wedge logs
// its snapshot once and then stays quiet. (-1 = no scan yet → OR is negative → skip.)
if ((sTotal | sRing | sPoss | sLos | atkCasts | sinceKill) > 0)
{
int sig = ((sTotal & 0x3FF) << 20) ^ ((sRing & 0x3FF) << 10) ^ (sPoss & 0x3FF)
^ (sLos << 6) ^ (sinceKill << 1);
if (sig != _lastCombatTelemetrySig)
{
_lastCombatTelemetrySig = sig;
Host.Log($"[ScanTele] targets total={sTotal} ring={sRing} possible={sPoss} " +
$"losBlk={sLos} | atkCasts={atkCasts} sinceKill={sinceKill}");
}
}
_lastCombatTelemetryAt = RynthClock.Now;
Guard(TickStep.CombatTelemetry, PushCombatTelemetry);
}
if (diag) Host.Log("[RynthAi] OnTick: before salvageManager");
@ -2085,11 +2003,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// combine-sweeps next to a mob attacking it: the legacy
// 'Salvaging' string blocks CombatManager.canRun and the
// arbiter doesn't override it (Salvaging isn't arbiter-
// authoritative yet). HasEngageableTarget = actively engaged OR
// a scanned mob within MonsterRange — the same predicate the
// arbiter uses for Combat-vs-Nav (pure, no side effects;
// reflects last tick's scan, which is fine to yield on).
bool combatThreat = settings.EnableCombat && _combatManager?.HasEngageableTarget == true;
// authoritative yet). FightIsOn = actively engaged OR a scanned
// mob within MonsterRange (or on top of us) — the same predicate
// the arbiter uses for Combat-vs-Nav (pure, no side effects;
// reflects last tick's scan, which is fine to yield on), and the
// one every item chore waits on (RynthAiPlugin.Chores.cs).
bool combatThreat = FightIsOn(settings);
// Same settle gate as InventoryManager: BeginCombineSalvage walks
// GetDirectInventory which races with cache classification during
@ -2097,7 +2016,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// combine work while a threat is up so it doesn't contend with
// combat over SelectItem; it resumes the moment the threat clears.
if (inventorySettled && !combatThreat)
_salvageManager?.OnTick(PacedBusy);
Guard(TickStep.Salvage, () => _salvageManager?.OnTick(PacedBusy));
if (diag) Host.Log("[RynthAi] OnTick: before manaStoneManager");
// STEP 4: the salvage gap-fill that used to pin/release
@ -2110,28 +2029,26 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// decision from scratch every tick.
// Mana stone tapping — runs after salvage, independent of looting state.
_manaStoneManager?.OnHeartbeat(PacedBusy);
_petManager?.OnHeartbeat(PacedBusy);
Guard(TickStep.ManaStones, () => _manaStoneManager?.OnHeartbeat(PacedBusy));
Guard(TickStep.Pets, () => _petManager?.OnHeartbeat(PacedBusy));
if (diag) Host.Log("[RynthAi] OnTick: before combatManager");
// Missile crafting runs before combat — blocks everything while active.
// Gated on the same settle window as InventoryManager: ProcessCrafting
// also does a forced GetDirectInventory walk which races with cache
// classification right after login/RL.
if (inventorySettled && _missileCraftingManager != null && settings.IsMacroRunning)
// classification right after login/RL. A fault holds nothing.
var crafting = _missileCraftingManager;
if (inventorySettled && crafting != null && settings.IsMacroRunning
&& GuardHold(TickStep.MissileCrafting, () => { crafting.ProcessCrafting(); return crafting.IsCrafting; }))
{
_missileCraftingManager.ProcessCrafting();
if (_missileCraftingManager.IsCrafting)
{
// Crafting can start in the middle of a nav leg (the ammo check runs
// whoever owns the tick). Without a stop, autorun stayed on and the
// bot ran blind on its last heading for the whole craft.
StopNavFor(BotActivity.Idle);
KeepThreatScanFresh(settings);
FreezeCorpseTimeout(CorpseNowMs); // a claimed corpse must not time out while held
_metaManager?.Think();
return; // Block combat, nav, looting until crafting finishes
}
// Crafting can start in the middle of a nav leg (the ammo check runs
// whoever owns the tick). Without a stop, autorun stayed on and the
// bot ran blind on its last heading for the whole craft.
StopNavFor(BotActivity.Idle);
KeepThreatScanFresh(settings);
FreezeCorpseTimeout(CorpseNowMs); // a claimed corpse must not time out while held
ThinkMeta();
return; // Block combat, nav, looting until crafting finishes
}
// Learn unknown spells (VTank ReadUnknownScrolls): reads a scroll only at a safe
@ -2141,7 +2058,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
StopNavFor(BotActivity.Idle);
KeepThreatScanFresh(settings);
FreezeCorpseTimeout(CorpseNowMs); // a claimed corpse must not time out while held
_metaManager?.Think();
ThinkMeta();
return;
}
@ -2175,34 +2092,38 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// costs nothing and is what keeps the decision honest.
if (_activity == BotActivity.Looting)
{
TickCorpseOpening();
_combatManager?.OnHeartbeat();
Guard(TickStep.Looting, TickCorpseOpening);
Guard(TickStep.Combat, () => _combatManager?.OnHeartbeat());
}
else
{
_combatManager?.OnHeartbeat();
// Combat: essential, never switched off by its guard (TickGuard).
Guard(TickStep.Combat, () => _combatManager?.OnHeartbeat());
if (diag) Host.Log("[RynthAi] OnTick: after combatManager.OnHeartbeat");
TickCorpseOpening();
Guard(TickStep.Looting, TickCorpseOpening);
}
if (diag) Host.Log("[RynthAi] OnTick: before nav");
if (navOwnsTick || navInPortal)
Guard(TickStep.Navigation, () =>
{
_navStopIssued = false;
_navStoppedFor = BotActivity.Idle;
if (navOwnsTick || navInPortal)
{
_navStopIssued = false;
_navStoppedFor = BotActivity.Idle;
bool doorBlocking = TickDoorInteraction();
if (!doorBlocking)
_navigationEngine?.Tick();
}
else
{
StopNavFor(_activity);
}
bool doorBlocking = TickDoorInteraction();
if (!doorBlocking)
_navigationEngine?.Tick();
}
else
{
StopNavFor(_activity);
}
});
TickPendingMtLoot();
_metaManager?.Think();
Guard(TickStep.MtLoot, TickPendingMtLoot);
ThinkMeta();
}
finally
@ -2237,6 +2158,125 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
private long _lastOwnCorpseTravelErrorLogAt = -100_000;
private long _lastTickErrorLogAt = -100_000;
/// <summary>
/// Push settings to the engine each tick. RynthAi has no render hook (it draws nothing
/// itself). OnTick runs unconditionally via PluginManager.TickAll, including in
/// Decal-coexistence mode. Push the suppression toggles here so the settings panel controls
/// the radar/powerbar.
/// </summary>
private void PushSettingsToEngine(bool diag)
{
var pushSettings = _dashboard?.Settings;
if (diag)
Host.Log($"[RynthAi] OnTick: settings push entry — settings null? {pushSettings == null}, HasSetRadarSuppressed={Host.HasSetRadarSuppressed}");
if (pushSettings == null) return;
if (diag)
Host.Log($"[RynthAi] OnTick: pushSettings.SuppressRetailRadar={pushSettings.SuppressRetailRadar}, SuppressRetailPowerbar={pushSettings.SuppressRetailPowerbar}");
Host.SetFpsLimit(pushSettings.EnableFPSLimit, pushSettings.TargetFPSFocused, pushSettings.TargetFPSBackground);
// "Hide UI" (remote): blank the vanilla AC radar/powerbar too. The RynthAi Avalonia
// panels are separate windows already excluded by the stream's PrintWindow capture.
// NOTE: retail chat suppression is intentionally NOT handled here — it is owned by
// the RynthChat plugin (engine-side ChatHooks, driven from RynthChatPanel's gear menu).
// RynthAi pushing it every tick clobbered that toggle, so it lives solely in RynthChat now.
bool hideUi = _hideUi;
if (Host.HasSetRadarSuppressed)
Host.SetRadarSuppressed(hideUi || pushSettings.SuppressRetailRadar);
if (Host.HasSetPowerbarSuppressed)
Host.SetPowerbarSuppressed(hideUi || pushSettings.SuppressRetailPowerbar);
// Fellowship-follow: publish the leader's object id so the nav
// engine can steer toward their live position. 0 = idle (not in a
// fellowship, or we ARE the leader — a leader shouldn't follow itself).
if (pushSettings.FollowMode && pushSettings.FollowNamedTargetId != 0)
{
pushSettings.FollowTargetId = pushSettings.FollowNamedTargetId;
}
else if (pushSettings.FollowMode && _fellowshipTracker != null)
{
int leader = _fellowshipTracker.LeaderId;
pushSettings.FollowTargetId =
(leader != 0 && !_fellowshipTracker.IsLeader) ? unchecked((uint)leader) : 0u;
}
else
{
pushSettings.FollowTargetId = 0;
}
}
/// <summary>
/// Player vitals: AC sends none of its own health through OnUpdateHealth (that is the
/// 0x01C0 health-of-a-target message), so this read is how the bot learns health
/// dropped. It ran every 30th tick: ~1 s at a background client's 30 fps, 1.5-3 s on a
/// slower or busier PC, added to every heal at random (2026-10-05, "heals sometimes
/// late"). The engine's snapshot is a locked struct copy kept current by its vitals
/// hook, so read it every VitalsPollMs instead.
/// </summary>
private void PollPlayerVitals()
{
long vitalsNow = Environment.TickCount64;
if (vitalsNow - _lastVitalsPollAt < VitalsPollMs) return;
_lastVitalsPollAt = vitalsNow;
if (Host.HasGetPlayerVitals &&
Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out uint st, out uint maxSt, out uint mp, out uint maxMp))
{
_vitals.CurrentHealth = hp;
_vitals.MaxHealth = maxHp;
_vitals.CurrentStamina = st;
_vitals.MaxStamina = maxSt;
_vitals.CurrentMana = mp;
// A big move in the max-mana reading (a death, buffs landing or dropping) is logged:
// the floor and the reserve judge mana by it (2026-10-15).
if (_vitals.MaxMana > 0 && maxMp > 0
&& Math.Abs((long)maxMp - _vitals.MaxMana) * 100 >= 15L * _vitals.MaxMana)
Host.Log($"[RynthAi] Vitals: max mana reading {_vitals.MaxMana} -> {maxMp} (mana {mp}).");
_vitals.MaxMana = maxMp;
}
}
/// <summary>Status feed: main-pack empty slots, components, equipment and the remote inventory snapshot.</summary>
private void PushInventoryStatus()
{
ScanInventoryStatus(out int freeSlots, out int scarabs, out int tapers, out var scarabsByType, out var equipment);
_dashboard?.SetFreeSlots(freeSlots);
_dashboard?.SetComponentCounts(scarabs, tapers, scarabsByType);
_dashboard?.SetEquipment(AppraiseEquipment(equipment));
// Remote full-inventory snapshot (P1) — same 3s gate, reuses the cached walk.
ScanInventoryForRemote();
}
/// <summary>Combat telemetry for the status feed, and a [ScanTele] line when the picture changed.</summary>
private void PushCombatTelemetry()
{
var cm = _combatManager;
if (cm == null) return;
int sTotal = cm.LastScanTotalMonsters;
int sRing = cm.LastScanInRing;
int sPoss = cm.LastScanPossible;
int sLos = cm.LastScanLosBlocked;
int atkCasts = cm.SessionAttackCasts;
int sinceKill = cm.CastsSinceLastKill;
_dashboard?.SetScanCounts(sTotal, sRing, sPoss, sLos);
_dashboard?.SetCastStats(atkCasts, sinceKill);
// Log only when there's something to see, and only when the picture changed,
// so a healthy idle bot never spams the per-client log. sinceKill is in the key
// so active combat shows periodic progress while a stalled-with-mobs wedge logs
// its snapshot once and then stays quiet. (-1 = no scan yet → OR is negative → skip.)
if ((sTotal | sRing | sPoss | sLos | atkCasts | sinceKill) > 0)
{
int sig = ((sTotal & 0x3FF) << 20) ^ ((sRing & 0x3FF) << 10) ^ (sPoss & 0x3FF)
^ (sLos << 6) ^ (sinceKill << 1);
if (sig != _lastCombatTelemetrySig)
{
_lastCombatTelemetrySig = sig;
Host.Log($"[ScanTele] targets total={sTotal} ring={sRing} possible={sPoss} " +
$"losBlk={sLos} | atkCasts={atkCasts} sinceKill={sinceKill}");
}
}
}
private bool _lootInspectMode = true; // always on; /ra lootcheck off to disable
/// <summary>Lets PluginExports log through this plugin's host (the base Log is protected).</summary>
@ -3079,7 +3119,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
foreach (var r in rules)
if (r.ElementSource != WeaponList.SourceSet && r.ElementSource.Length > 0 && _loggedWeaponElements.Add((r.Id, r.Element)))
Host.Log($"[RynthAi] weapon 0x{(uint)r.Id:X8} '{r.Name}': element {r.Element} (from {r.ElementSource})");
if ((DateTime.Now - _loginCompletedAt).TotalMilliseconds < 5000) return;
if ((RynthClock.Now - _loginCompletedAt).TotalMilliseconds < 5000) return;
if (_busyCount > 0 || (Host.HasIsPortaling && Host.IsPortaling())) return;
var ids = new List<int>(rules.Count);
foreach (var r in rules) if (r.Id != 0 && !WeaponList.IsShieldRule(r) && cache[r.Id] != null) ids.Add(r.Id); // shields have no element to identify

View file

@ -0,0 +1,27 @@
using System;
using System.Diagnostics;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// RynthAi's clock for timing: a local DateTime that moves forward at the real rate (Stopwatch) from
/// the wall clock's time when the plugin loaded, and never jumps.
///
/// DateTime.Now jumps when the clocks change: an hour back when daylight saving ends (Europe 25 Oct,
/// the US 1 Nov 2026), forward in spring, and by seconds when Windows corrects the time. Every
/// "(DateTime.Now - last) &lt; interval" check then went negative for the hour: no target scans, no
/// attacks, no buff or loot timeouts, and bane timers read an hour long (structural audit,
/// 2026-10-21). Intervals, timeouts and timestamps compared with each other use this clock.
///
/// DateTime.Now stays only where the time of day is shown or handed out as such: log lines and log
/// file names, backup file names, a meta's getdatetimelocal. Times saved to disk (bane timers) are
/// this clock's local time, read back after a restart against a fresh anchor, as before.
/// </summary>
internal static class RynthClock
{
private static readonly DateTime Anchor = DateTime.Now;
private static readonly long AnchorStamp = Stopwatch.GetTimestamp();
/// <summary>Local time that only moves forward with real time; use for intervals and timeouts.</summary>
public static DateTime Now => Anchor + Stopwatch.GetElapsedTime(AnchorStamp);
}

View file

@ -208,7 +208,7 @@ internal sealed class ChatTranslator : IDisposable
{
case JobKind.SendRaw:
Send(job.Prefix, job.Text);
AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.Out, job.Channel, string.Empty,
AddLog(new TranslateLogEntry(RynthClock.Now, TranslateDirection.Out, job.Channel, string.Empty,
job.Text, job.Text, string.Empty, string.Empty, "sent untranslated"));
break;
case JobKind.Inbound:
@ -274,7 +274,7 @@ internal sealed class ChatTranslator : IDisposable
{
if (!r.Ok)
{
AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.In, job.Channel, job.Speaker, job.Text,
AddLog(new TranslateLogEntry(RynthClock.Now, TranslateDirection.In, job.Channel, job.Speaker, job.Text,
string.Empty, job.Source, job.Target, r.Error));
ChatErrorThrottled(r.Error);
return;
@ -286,7 +286,7 @@ internal sealed class ChatTranslator : IDisposable
if (translated.Length == 0 || string.Equals(translated, job.Text, StringComparison.OrdinalIgnoreCase)) return;
Interlocked.Increment(ref _translated);
AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.In, job.Channel, job.Speaker, job.Text,
AddLog(new TranslateLogEntry(RynthClock.Now, TranslateDirection.In, job.Channel, job.Speaker, job.Text,
translated, r.DetectedSource, job.Target, string.Empty));
if (Settings.EchoToChat && job.Channel is { } ch)
@ -312,13 +312,13 @@ internal sealed class ChatTranslator : IDisposable
else
{
QueueEcho($"{EchoPrefix} Couldn't translate ({(r.Ok ? "empty result" : r.Error)}); message not sent.", ChatTypeSystem);
AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.Out, job.Channel, string.Empty, job.Text,
AddLog(new TranslateLogEntry(RynthClock.Now, TranslateDirection.Out, job.Channel, string.Empty, job.Text,
string.Empty, r.DetectedSource, job.Target, r.Ok ? "empty result" : r.Error));
return;
}
string sent = Send(job.Prefix, body);
AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.Out, job.Channel, string.Empty, job.Text,
AddLog(new TranslateLogEntry(RynthClock.Now, TranslateDirection.Out, job.Channel, string.Empty, job.Text,
sent, r.DetectedSource, job.Target, r.Ok ? string.Empty : r.Error));
if (r.Ok && Settings.EchoOutbound && job.Channel is { } ch)
@ -327,7 +327,7 @@ internal sealed class ChatTranslator : IDisposable
private void ApplyTest(Job job, TranslateResult r)
{
AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.Test, null, string.Empty, job.Text,
AddLog(new TranslateLogEntry(RynthClock.Now, TranslateDirection.Test, null, string.Empty, job.Text,
r.Ok ? r.Text : string.Empty, r.DetectedSource, job.Target, r.Error));
QueueEcho(r.Ok
? $"{EchoPrefix} Test ({(r.DetectedSource.Length > 0 ? r.DetectedSource : "?")} -> {job.Target}): {r.Text}"

View file

@ -189,7 +189,7 @@ public sealed partial class RynthAiPlugin
// /ub date[utc] [format]
private void UbDate(string format, bool utc)
{
DateTime t = utc ? DateTime.UtcNow : DateTime.Now;
DateTime t = utc ? DateTime.UtcNow : RynthClock.Now;
string s;
try { s = format.Length > 0 ? t.ToString(format, CultureInfo.InvariantCulture) : t.ToString(CultureInfo.InvariantCulture); }
catch (FormatException) { ChatLine($"[RynthAi] Bad date format: {format}"); return; }

View file

@ -50,6 +50,8 @@
<ItemGroup>
<!-- Fellowship reader (client memory, VirtualQuery-guarded), shared source with RynthAi. -->
<Compile Include="..\RynthCore.Plugin.RynthAi\Combat\FellowshipTracker.cs" Link="Shared\FellowshipTracker.cs" />
<!-- Its timing clock (RynthClock: intervals that don't jump when the clocks change, 2026-10-21). -->
<Compile Include="..\RynthCore.Plugin.RynthAi\RynthClock.cs" Link="Shared\RynthClock.cs" />
<!-- RynthAi's session stats ("RynthAi.Hub" SessionStats): the Character tab's session rates
count the same session as the Mini Remote's Session Stats. -->
<Compile Include="..\Shared\RynthAiHubApi.cs" Link="Shared\RynthAiHubApi.cs" />

View file

@ -22,6 +22,7 @@
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\BoundingVolume.cs" Link="Linked\BoundingVolume.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\BlacklistManager.cs" Link="Linked\BlacklistManager.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\RynthClock.cs" Link="Linked\RynthClock.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\DungeonLOS.cs" Link="Linked\DungeonLOS.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\GeometryLoader.cs" Link="Linked\GeometryLoader.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\LandblockStructs.cs" Link="Linked\LandblockStructs.cs" />

View file

@ -149,6 +149,8 @@ internal static class Program
ServerHubClientLookupTests.Register(runner);
UbMtSafetyTests.Register(runner);
DifficultyTierTests.Register(runner);
TickIsolationTests.Register(runner);
ChoresInFightTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -28,6 +28,100 @@ internal static class CastNoDamageTests
r.Add("no-damage casts: other monsters still get predicted kills; the memory lapses after 10 min", OthersStillPredicted);
r.Add("no-damage casts: the chat after a combat cast is logged, swings at us left out, capped, 4 s", CastChatTrace);
r.Add("no-damage casts (flight 63260): 3 magic casts landing nothing -> one short real sidestep, no cast meanwhile; a hit resets; 30 s apart", ResyncSidestep);
r.Add("no-damage casts (R-20261021 c788): a corpse selected mid-fight stops the target's health; its chat hits still count, it is not blacklisted", SelectionElsewhereChatHitsCount);
}
// ── A corpse selected during the fight (report R-20261021-191720-c788, Conquest) ─────────────
// "RynthAi interprets a corpse selection during combat as a target for attacks, and stops." The
// fight target never changed: the server sends health only for the client's selection, so once
// the player selected a corpse (or themselves) no health came for the monster, and a war spell's
// hit was seen only in chat, which the no-damage judge didn't count. Three casts that all hit
// were "no damage": the live monster was blacklisted, dropped, and combat stopped (the log:
// "3 casts with no damage - blacklisting" at a Curator taking 7,000 a cast).
private const uint Curator = 0x800F26CD, Marionette = 0x80168E96, Corpse = 0x802B29BD;
private const uint CuratorWcid = 40001, MarionetteWcid = 40002;
private const string CuratorHit = "You singe Curator of Torment for 7190 points with Incantation of Flame Bolt.";
private static CombatManager CorpseRig(LegacyUiSettings s)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true; // installs GetCurrentCombatMode
FakeHost.CombatModeValue = CombatMode.Magic;
FakeHost.Names[Player] = "Me";
FakeHost.Positions[Player] = (Lb | 0x0141, 96f, 96f, 0f);
FakeHost.PlayerPose = (Lb | 0x0141, 96f, 96f, 0f);
void Mob(uint id, string name, uint wcid, float north)
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (Lb | 0x0141, 96f, 96f + north, 0f);
FakeHost.ItemTypes[id] = 0x10;
FakeHost.Wcids[id] = wcid;
}
Mob(Curator, "Curator of Torment", CuratorWcid, 1.9f);
Mob(Marionette, "Tormented Marionette", MarionetteWcid, 3f);
FakeHost.Names[Corpse] = "Corpse of Qosmos, Guardian of Torment";
FakeHost.Positions[Corpse] = (Lb | 0x0141, 97f, 96f, 0f);
FakeHost.ItemTypes[Corpse] = 0x200; // a container
FakeHost.Bitfields[Corpse] = 0x00002000; // the corpse flag
FakeHost.NotAttackable.Add(Corpse);
s.MonsterRange = 20;
s.EnableRaycasting = false; // no raycast warm-up (it suspends the judge)
s.BlacklistAttempts = 3;
s.BlacklistCastSettleMs = 0; // each cast is judged at the next one
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, new[] { Curator, Marionette, Corpse });
var c = new CombatManager(host, s, cache);
c.SetPlayerId(Player);
c.SetDamageStores(null, new MonsterDamageStore());
c.EngageForTest(unchecked((int)Curator));
FakeHost.SelectedItem = Corpse; // the player clicks the corpse: no health for the Curator from here on
return c;
}
/// <summary>Five casts at the Curator, each followed by <paramref name="chat"/> (null: nothing), then one more cast
/// so the fifth is judged too.</summary>
private static void CastFive(CombatManager c, string? chat)
{
for (int i = 0; i < 5; i++)
{
c.RecordOffensiveCast(unchecked((int)Curator)); // judges the cast before it, opens this one's window
if (chat != null) c.HandleChatForDamage(chat, 7);
}
c.RecordOffensiveCast(unchecked((int)Curator));
}
private static void SelectionElsewhereChatHitsCount()
{
var c = CorpseRig(new LegacyUiSettings());
Check.Eq(FakeHost.SelectedItem, Corpse, "the rig: a corpse is selected");
CastFive(c, CuratorHit);
Check.Eq(unchecked((uint)c.activeTargetId), Curator, "five hits seen in chat: the Curator is still the fight target");
Check.False(FakeHost.Chat.Any(l => l.Contains("with no damage", StringComparison.Ordinal)), "no 'casts with no damage' blacklist");
Check.False(FakeHost.Logs.Any(l => l.Contains("[Blacklist] 0x800F26CD", StringComparison.Ordinal)), "the Curator was never blacklisted");
Check.False(FakeHost.Logs.Any(l => l.Contains("one short sidestep", StringComparison.Ordinal)), "no position re-sync sidestep either");
c.ScanNearbyTargets();
Check.True(c.ScannedTargets.Any(t => t.Id == unchecked((int)Curator)), "and it stays in the scan");
Check.False(c.ScannedTargets.Any(t => t.Id == unchecked((int)Corpse)), "the selected corpse is never a candidate");
// A critical hit has its prefix; it counts the same.
c.RecordOffensiveCast(unchecked((int)Curator));
c.HandleChatForDamage("Critical hit! You singe Curator of Torment for 11259 points with Incantation of Flame Bolt.", 7);
c.RecordOffensiveCast(unchecked((int)Curator));
Check.Eq(unchecked((uint)c.activeTargetId), Curator, "a critical hit line counts too");
// The judge still works: casts that land nothing, or hit only another monster, blacklist the target.
c = CorpseRig(new LegacyUiSettings());
CastFive(c, null);
Check.Eq(c.activeTargetId, 0, "no hit line at all: the Curator is blacklisted and dropped, as before");
Check.True(FakeHost.Chat.Any(l => l.Contains("3 casts with no damage", StringComparison.Ordinal)), "and chat says so");
c = CorpseRig(new LegacyUiSettings());
CastFive(c, "You singe Tormented Marionette for 4215 points with Incantation of Flame Bolt.");
Check.Eq(c.activeTargetId, 0, "hits only on another monster are not the Curator's");
c = CorpseRig(new LegacyUiSettings());
CastFive(c, "You singe Curator of Torment for 0 points with Incantation of Flame Bolt.");
Check.Eq(c.activeTargetId, 0, "a 0-point hit is no damage");
}
private sealed class Rig

View file

@ -0,0 +1,90 @@
using System;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Structural audit 2026-10-21, finding 3: item chores ignored fights. Missile crafting held combat
// with no danger check (MissileCraftingTests), mana tapping drained loot between swings
// (ManaStoneChoiceTests), and AutoCram/AutoStack moved items between swings: their only gate was
// the busy count, and a swing repeat is not a paced action. They all wait on one signal now,
// RynthAiPlugin.FightIsOn, the one salvage already used.
internal static class ChoresInFightTests
{
private const uint Player = TickIsolationTests.Player;
private const uint Gem = 0x80000F11, SidePack = 0x80000F12, Monster = 0x80000F13;
private const uint ItemTypeGem = 0x800, ItemTypeContainer = 0x200;
private const uint ItemsCapacityKey = 6;
public static void Register(Runner r)
{
r.Add("chores: a fight is a monster in Monster Range or on top of us; never with the macro or combat off", FightSignal);
r.Add("chores: AutoCram waits while a monster is on us, and crams once the fight is over", CramWaitsForFight);
}
private static CombatManager.ScannedTarget At(double yards) =>
new() { Id = unchecked((int)Monster), Distance = yards, Name = "Drudge Skulker" };
private static void FightSignal()
{
try
{
var bot = new TickIsolationTests.Bot(combat: true, heal: false);
bot.S.MonsterRange = 20;
var cm = (CombatManager)bot.Get("_combatManager")!;
Check.False(bot.P.FightIsOn(), "no monster: no fight");
cm.SetScannedTargetsForTests(new[] { At(15) });
Check.True(bot.P.FightIsOn(), "a monster inside Monster Range");
cm.SetScannedTargetsForTests(new[] { At(30) });
Check.False(bot.P.FightIsOn(), "only one past it: no fight");
bot.S.MonsterRange = 2;
cm.SetScannedTargetsForTests(new[] { At(4) });
Check.True(bot.P.FightIsOn(), "Monster Range 2, a monster 4 yd away: on top of us all the same");
bot.S.IsMacroRunning = false;
Check.False(bot.P.FightIsOn(), "macro off: the scan's last picture holds nothing");
bot.S.IsMacroRunning = true;
bot.S.EnableCombat = false;
Check.False(bot.P.FightIsOn(), "combat off: no fight");
}
finally { TickIsolationTests.Done(); }
}
private static void CramWaitsForFight()
{
try
{
var bot = new TickIsolationTests.Bot(combat: true, heal: false, arrange: () =>
{
FakeHost.Names[Gem] = "Black Opal";
FakeHost.ItemTypes[Gem] = ItemTypeGem;
FakeHost.Containers[Gem] = Player;
FakeHost.Names[SidePack] = "Backpack";
FakeHost.ItemTypes[SidePack] = ItemTypeContainer;
FakeHost.Ints[(SidePack, ItemsCapacityKey)] = 24;
FakeHost.Containers[SidePack] = Player;
});
_ = bot.Cache[unchecked((int)Gem)];
_ = bot.Cache[unchecked((int)SidePack)];
bot.S.EnableAutocram = true;
bot.S.MonsterRange = 20;
bot.Set("_inventoryManager", new InventoryManager(bot.Host, bot.S, bot.Cache));
var cm = (CombatManager)bot.Get("_combatManager")!;
cm.SetScannedTargetsForTests(new[] { At(2) });
for (int i = 0; i < 5; i++) bot.Call("TickCramStack", bot.S);
Check.Eq(FakeHost.Moves.Count, 0, "a monster on us: nothing is moved");
cm.SetScannedTargetsForTests(Array.Empty<CombatManager.ScannedTarget>());
bot.Call("TickCramStack", bot.S);
Check.True(FakeHost.Moves.Any(m => m.Id == Gem && m.Pack == SidePack),
"the fight is over: the gem goes into the side pack (moves: " + string.Join(",", FakeHost.Moves.Select(m => $"{m.Id:X8}->{m.Pack:X8}")) + ")");
}
finally { TickIsolationTests.Done(); }
}
}

View file

@ -175,7 +175,7 @@ internal static class LauncherSwapTests
{
const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic;
typeof(CombatManager).GetField("_lockedTargetId", F)!.SetValue(C, unchecked((int)target));
typeof(CombatManager).GetField("_targetLockedAt", F)!.SetValue(C, DateTime.Now);
typeof(CombatManager).GetField("_targetLockedAt", F)!.SetValue(C, RynthClock.Now);
typeof(CombatManager).GetField("_lockWasSwitch", F)!.SetValue(C, wasSwitch);
}

View file

@ -36,6 +36,8 @@ internal static class ManaStoneChoiceTests
r.Add("mana tapping: a drain that never completes keeps the item's place, tries the next stone, then gives up", FailedDrainKeepsPlace);
r.Add("mana tapping: only a stone in the client's pack is used or counted (not one on a corpse, not a stale id)", StoneMustBeInPack);
r.Add("mana tapping: a stone that failed two drains stays parked though it reads empty", FailedStoneStaysParked);
r.Add("mana tapping: in a fight the drain waits (holding no loot, taking no second item); after it, the drain goes", DrainWaitsForFight);
r.Add("mana stones: in a fight, worn gear that runs low is still refilled (armor without mana drops its spells)", RefillInFight);
}
private const uint ChargeA = 0x80400031, ChargeB = 0x80400032, ChargeC = 0x80400033;
@ -355,6 +357,33 @@ internal static class ManaStoneChoiceTests
// 2026-10-15: the pack filled with items looted to tap. A drain that never completed shelved
// its item for 5 minutes and the item stopped counting against the empty stones, so the looter
// took another in its place; and the looter went on opening corpses over the drain.
// Structural audit 2026-10-21, finding 3: a drain is optional work, and each UseObjectOn went out
// between melee swings (only the busy count gated it). It waits for the fight now.
private static void DrainWaitsForFight()
{
using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null) }, ringToDrain: true, maceMana: 5000);
bool fight = true;
rig.M.FightIsOn = () => fight;
rig.Run(3000);
Check.Eq(rig.OnRing.Count, 0, "a fight is on: no drain");
Check.False(rig.M.HoldsLootForDrain(), "the waiting drain doesn't hold the looter");
Check.Eq(rig.M.FreeEmptyStoneSlots(), 0, "and no second item is looted to tap meanwhile");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("ManaStone: a fight is on")), 1, "one log line for the fight");
fight = false;
rig.Run(1000);
Check.Eq(rig.OnRing.Count, 1, "the fight is over: the ring is drained");
Check.True(rig.M.HoldsLootForDrain(), "and the drain out holds the looter, as before");
}
private static void RefillInFight()
{
using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, 3000) }); // the mace reads 0 of 5000
rig.M.FightIsOn = () => true;
rig.Run(1000);
Check.Eq(rig.OnPlayer.Count, 1, "the charged stone goes on the player in the fight");
Check.Eq(rig.OnPlayer[0], StoneA, "stone A");
}
private static void OneTapItemAtATime()
{
using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null), (StoneB, null), (StoneC, null) }, maceMana: 5000);

View file

@ -19,6 +19,8 @@ internal static class MissileCraftingTests
{
private const uint Player = 0x50000C01;
private const uint Crossbow = 0x80000601, Bow = 0x80000602, Quarrels = 0x80000603, Arrows = 0x80000604;
private const uint Heads = 0x80000605, Shafts = 0x80000606, Made = 0x80000607;
private const uint StackSizeKey = 12;
private const int MissileSlot = 0x00400000, AmmoSlot = 0x00800000;
public static void Register(Runner r)
@ -27,6 +29,14 @@ internal static class MissileCraftingTests
r.Add("missile crafting: wielded quarrels are not taken for a bow launcher", AmmoNotLauncher);
r.Add("missile crafting: an ammo wield the server ignores backs off after 2 tries", IgnoredWieldBacksOff);
r.Add("missile crafting: a bow in hand with its arrows in the pack still gets them wielded", BowInHandArrowsInPack);
r.Add("missile crafting: in a fight the carried arrows go on at once, better ones are not crafted (no Peace, no combine)", FightWieldsCarried);
r.Add("missile crafting: a craft of better arrows stops when a fight starts, and the carried arrows go on", FightStopsUpgrade);
r.Add("missile crafting: out of arrows in a fight, one combine still goes (nothing else to shoot), then the arrows made go on", FightOutOfAmmoCraftsOnce);
// The engine's real container walk (2026-10-21): the player's own contents list the gear in hand.
r.Add("missile crafting: the walk lists the bow in hand under the player, and Deadly Prismatic Arrows are still made and wielded", WalkBowInHandCrafts);
r.Add("missile crafting: with the engine's tracker, a bow in hand whose client fields read blank is the launcher", WalkTrackerBowInHand);
r.Add("missile crafting: with the engine's tracker, a stowed bow listed first that still reads wielded is not the launcher", WalkTrackerStowedBowNotLauncher);
r.Add("missile crafting: a stowed bow in a side pack that still reads wielded is not the launcher (no tracker)", WalkSidePackBowNotLauncher);
}
/// <summary>Kelpie's state at 13:36: crossbow and quarrels in hand (slot 0), bow and arrows in the main pack.</summary>
@ -76,12 +86,274 @@ internal static class MissileCraftingTests
Check.True(FakeHost.Logs.Any(l => l.Contains("MissileCraft: no Arrow") && l.Contains("'Longbow'")), "the launcher it saw is logged");
}
// ── Fights (structural audit 2026-10-21, finding 3) ──────────────────────
// Crafting holds combat (Peace mode, up to 15 s a step) and had no danger check: the arrows run
// out mid-fight, which is when it starts. In a fight it now does only what the fight needs.
/// <summary>Longbow in hand, nothing in the ammo slot, the Infinite arrows (no recipe: rank 1) in the pack, and bundles for Greater Arrows.</summary>
private static MissileCraftingManager UpgradeRig(Func<bool> fight, bool carriedArrows = true) =>
Rig(crossbowInHand: false, extra: new[] { Heads, Shafts }, arrange: () =>
{
FakeHost.Containers.Remove(Bow);
FakeHost.Names[Bow] = "Longbow";
if (!carriedArrows) { FakeHost.Containers.Remove(Arrows); FakeHost.Names[Arrows] = "Infinite Deadly Prismatic Quarrel"; }
FakeHost.UseOnCalls = true;
FakeHost.CombatModeCalls = true;
FakeHost.CombatModeValue = CombatMode.Missile;
Bundle(Heads, "Bundle of Greater Arrowheads");
Bundle(Shafts, "Bundle of Arrowshafts");
}, fight: fight);
private static void Bundle(uint id, string name)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = 0x100;
FakeHost.Containers[id] = Player;
FakeHost.Ints[(id, StackSizeKey)] = 2;
}
private static void FightWieldsCarried()
{
// Out of a fight (the old behaviour): the better arrows are crafted.
var quiet = UpgradeRig(() => false);
Idle(quiet);
Step(quiet);
Check.Eq(quiet.State, MissileCraftingManager.CraftState.Combining, "no fight: Greater Arrows are crafted");
var cm = UpgradeRig(() => true);
Cycle(cm);
Check.Eq(FakeHost.Uses.LastOrDefault(), Arrows, "in a fight: the carried arrows are wielded");
Check.Eq(FakeHost.UsesOn.Count, 0, "no combine");
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no Peace mode");
Check.Eq(cm.State, MissileCraftingManager.CraftState.Idle, "and crafting let go");
Check.True(FakeHost.Chat.Any(l => l.Contains("In a fight: wielding Infinite Deadly Prismatic Arrow now instead of crafting Greater Arrow")), "chat says why");
}
private static void FightStopsUpgrade()
{
bool fight = false;
var cm = UpgradeRig(() => fight);
Idle(cm);
Step(cm); // evaluating: the craft starts
Step(cm); // the first combine goes out
Check.Eq(FakeHost.UsesOn.Count, 1, "the craft is under way");
Check.Eq(FakeHost.CombatModeRequests.LastOrDefault(), CombatMode.NonCombat, "in Peace mode");
fight = true;
Step(cm);
Check.Eq(cm.State, MissileCraftingManager.CraftState.EquippingAmmo, "a fight: the craft stops");
Step(cm);
Check.Eq(FakeHost.Uses.LastOrDefault(), Arrows, "the carried arrows go on");
Check.Eq(cm.State, MissileCraftingManager.CraftState.Idle, "crafting let go of the bot");
Check.Eq(FakeHost.UsesOn.Count, 1, "no second combine");
Check.True(FakeHost.Chat.Any(l => l.Contains("In a fight: stopped crafting Greater Arrow")), "chat says so");
}
private static void FightOutOfAmmoCraftsOnce()
{
var cm = UpgradeRig(() => true, carriedArrows: false);
Idle(cm);
Step(cm);
Step(cm);
Check.Eq(FakeHost.UsesOn.Count, 1, "no arrows at all: the first combine goes, fight or not");
// The server makes the arrows.
FakeHost.Names[Made] = "Greater Arrow";
FakeHost.ItemTypes[Made] = 0x100;
FakeHost.Containers[Made] = Player;
_ = _cache![unchecked((int)Made)];
cm.HandleChat("You make 2 Greater Arrows.");
Step(cm);
Check.Eq(cm.State, MissileCraftingManager.CraftState.EquippingAmmo, "arrows to shoot now: the second combine waits");
Step(cm);
Check.Eq(FakeHost.Uses.LastOrDefault(), Made, "the arrows made go on");
Check.Eq(FakeHost.UsesOn.Count, 1, "one combine in the fight");
}
/// <summary>One crafting tick, the phase clock moved past EQUIP_DELAY_MS (inside the 15 s timeout).</summary>
private static void Step(MissileCraftingManager cm)
{
PhaseStart.SetValue(cm, DateTime.Now.AddSeconds(-1));
ForceRescan();
cm.ProcessCrafting();
}
// ── The engine's real container walk ───────────────────────────────────
//
// 2026-10-21, a player: "it doesn't fletch arrows, even when the option is checked" (Deadly
// Prismatic). The engine's GetContainerContents(player) lists what the player wields as well as
// what the main pack holds (UpdateObjectInventoryHooks.ScanByContainerId matches the wielder too),
// so the walk filed the bow in hand under the player. Since 2026-10-19 crafting took any item the
// walk filed under a container as "not in hand", saw no launcher, and never started, with nothing
// in chat or the log. The rig above has no GetContainerContents, so its tests never met the walk.
private const uint SidePack = 0x80000610, WalkHeads = 0x80000611, WalkShafts = 0x80000612, WalkMade = 0x80000613;
private const uint ContainerType = 0x200; // ITEM_TYPE container: the walk opens it
/// <summary>The engine's walk as it is: wielded gear in the player's own contents, with no container.</summary>
private static MissileCraftingManager WalkRig(bool tracker, Action arrange, int fletching = 470)
{
PaceOff();
FakeHost.Reset();
RynthCore.Plugin.RynthAi.EquippedState.Invalidate();
FakeHost.WeaponCalls = true; // UseObject, GetCurrentCombatMode (peace: 1)
FakeHost.SalvageCalls = true; // GetObjectWielderInfo (answers from Wielded)
FakeHost.ContentsCalls = true; // GetContainerContents (Containers, then ContentsExtra)
FakeHost.UseOnCalls = true; // UseObjectOn (the head bundle on the shaft bundle)
FakeHost.EquippedCalls = tracker; // v87 GetWieldedItems (the engine's EquipmentTracker)
FakeHost.Names[Player] = "Archer";
FakeHost.Skills[(Player, 37)] = (fletching, 3); // Fletching, specialized
Item(Crossbow, "Fire Crossbow", MissileSlot);
Item(Bow, "Longbow", MissileSlot);
Item(Quarrels, "Deadly Prismatic Quarrel", AmmoSlot);
Item(Arrows, "Deadly Prismatic Arrow", AmmoSlot);
FakeHost.Names[WalkHeads] = "Bundle of Deadly Prismatic Arrowheads";
FakeHost.Names[WalkShafts] = "Bundle of Arrowshafts";
FakeHost.Ints[(WalkHeads, 12)] = 10; // StackCount
FakeHost.Ints[(WalkShafts, 12)] = 10;
FakeHost.Containers[WalkHeads] = Player;
FakeHost.Containers[WalkShafts] = Player;
arrange();
var host = FakeHost.Create(Player);
_cache = FakeHost.MakeCache(host, Player, new[] { Crossbow, Bow, Quarrels, Arrows, WalkHeads, WalkShafts, SidePack });
var cm = new MissileCraftingManager(host, new LegacyUiSettings { EnableMissileCrafting = true });
cm.SetObjectCache(_cache);
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
cm.SetCharacterSkills(skills);
return cm;
}
/// <summary>In hand as the client shows it: the record names the player, no container, and the
/// walk lists it in the player's contents. The tracker (when on) says so too.</summary>
private static void InHand(uint id, int slot, bool clientSlot = true, bool tracker = false)
{
if (clientSlot) FakeHost.Wielded[id] = unchecked((uint)slot);
FakeHost.Wielders[id] = Player;
if (!FakeHost.ContentsExtra.TryGetValue(Player, out var extra))
FakeHost.ContentsExtra[Player] = extra = new();
extra.Add(id);
if (tracker) FakeHost.Equipped[id] = unchecked((uint)slot);
}
/// <summary>One tick of whatever state crafting is in, its waits already over.</summary>
private static void WalkStep(MissileCraftingManager cm)
{
if (cm.State == MissileCraftingManager.CraftState.Idle) LastAmmoCheck.SetValue(cm, DateTime.MinValue);
else PhaseStart.SetValue(cm, DateTime.Now.AddSeconds(-1)); // past EQUIP_DELAY_MS, well inside the 15 s timeout
ForceRescan();
cm.ProcessCrafting();
}
/// <summary>The player's case: a Longbow wielded at login, the quiver empty, Deadly Prismatic bundles in the pack.</summary>
private static void WalkBowInHandCrafts()
{
var cm = WalkRig(tracker: false, arrange: () =>
{
InHand(Bow, MissileSlot);
FakeHost.Names.Remove(Crossbow); FakeHost.Names.Remove(Quarrels); FakeHost.Names.Remove(Arrows);
});
WalkStep(cm);
Check.Eq(cm.State, MissileCraftingManager.CraftState.Evaluating, "the empty quiver is seen");
Check.True(FakeHost.Logs.Any(l => l.Contains("MissileCraft: no Arrow") && l.Contains("'Longbow'")), "the bow in hand is the launcher");
WalkStep(cm);
Check.Eq(cm.State, MissileCraftingManager.CraftState.Combining, "Deadly Prismatic Arrows are made (Fletching 470)");
Check.True(FakeHost.Chat.Any(c => c.Contains("Crafting Deadly Prismatic Arrow x2")), "two combines planned: " + string.Join(" | ", FakeHost.Chat));
WalkStep(cm);
Check.Eq(FakeHost.UsesOn.Count, 1, "one combine sent");
Check.Eq(FakeHost.UsesOn[0], (WalkHeads, WalkShafts), "the head bundle on the shaft bundle");
cm.HandleChat("You make a bundle of deadly prismatic arrows.");
WalkStep(cm);
Check.Eq(FakeHost.UsesOn.Count, 2, "the second combine goes out after the first is confirmed");
cm.HandleChat("You make a bundle of deadly prismatic arrows.");
// The new arrows land in the main pack.
Item(WalkMade, "Deadly Prismatic Arrow", AmmoSlot);
FakeHost.Containers[WalkMade] = Player;
WalkStep(cm);
Check.Eq(cm.State, MissileCraftingManager.CraftState.EquippingAmmo, "both combines done: equip");
WalkStep(cm);
Check.Eq(FakeHost.Uses.LastOrDefault(), WalkMade, "UseObject(the new arrows)");
Check.Eq(cm.State, MissileCraftingManager.CraftState.Idle, "done");
}
/// <summary>The bow wielded after login: the client's slot and wielder record read blank; the tracker knows.</summary>
private static void WalkTrackerBowInHand()
{
var cm = WalkRig(tracker: true, arrange: () =>
{
FakeHost.ContentsExtra[Player] = new() { Bow }; // listed, but the record says nothing
FakeHost.Equipped[Bow] = MissileSlot; // the server's WieldObject
FakeHost.Names.Remove(Crossbow); FakeHost.Names.Remove(Quarrels); FakeHost.Names.Remove(Arrows);
});
WalkStep(cm);
Check.Eq(cm.State, MissileCraftingManager.CraftState.Evaluating, "the tracker's bow is the launcher");
WalkStep(cm);
WalkStep(cm);
Check.Eq(FakeHost.UsesOn.Count, 1, "the combine goes out");
}
/// <summary>
/// Silentkelpie's 2026-10-15 state on the real walk, with the tracker: crossbow and quarrels in
/// hand, the bow and arrows put into the main pack, the bow's record still naming the player and
/// the missile slot, and the bow listed before the crossbow. Only the tracker can tell them apart.
/// </summary>
private static void WalkTrackerStowedBowNotLauncher()
{
var cm = WalkRig(tracker: true, arrange: () =>
{
FakeHost.Containers[Bow] = Player; // in the main pack (listed first) ...
FakeHost.Wielded[Bow] = MissileSlot; // ... with the stale record
FakeHost.Wielders[Bow] = Player;
FakeHost.Containers[Arrows] = Player;
InHand(Crossbow, MissileSlot, clientSlot: false, tracker: true); // wielded after login: slot reads 0
InHand(Quarrels, AmmoSlot, clientSlot: false, tracker: true);
});
for (int i = 0; i < 3; i++) WalkStep(cm);
Check.Eq(cm.State, MissileCraftingManager.CraftState.Idle, "crossbow with quarrels on: nothing to do");
Check.Eq(FakeHost.Uses.Count, 0, "no arrow wield at the crossbow");
Check.Eq(FakeHost.UsesOn.Count, 0, "no combine");
Check.False(FakeHost.Logs.Any(l => l.Contains("MissileCraft: no")), "no evaluation logged");
}
/// <summary>
/// Without the tracker: the stowed bow sits in a side pack with its stale record (wielder and
/// missile slot), and the crossbow in hand can't be read (its record is blank, so the walk doesn't
/// list it). The stale bow is the only candidate and must not pass for the launcher.
/// </summary>
private static void WalkSidePackBowNotLauncher()
{
var cm = WalkRig(tracker: false, arrange: () =>
{
FakeHost.Names[SidePack] = "Backpack";
FakeHost.ItemTypes[SidePack] = ContainerType;
FakeHost.Containers[SidePack] = Player;
FakeHost.Containers[Bow] = SidePack;
FakeHost.Wielded[Bow] = MissileSlot; // stale
FakeHost.Wielders[Bow] = Player;
FakeHost.Containers[Arrows] = SidePack;
});
for (int i = 0; i < 3; i++) WalkStep(cm);
Check.Eq(cm.State, MissileCraftingManager.CraftState.Idle, "no launcher it can trust: nothing to do");
Check.Eq(FakeHost.Uses.Count, 0, "no arrow wield");
Check.False(FakeHost.Logs.Any(l => l.Contains("MissileCraft: no")), "no evaluation logged");
}
// ── The rig ─────────────────────────────────────────────────────────────
private static WorldObjectCache? _cache;
/// <param name="arrange">Changes to the fake world, made before the host and cache read it.</param>
private static MissileCraftingManager Rig(bool crossbowInHand, Action? arrange = null)
private static MissileCraftingManager Rig(bool crossbowInHand, Action? arrange = null, uint[]? extra = null, Func<bool>? fight = null)
{
PaceOff();
FakeHost.Reset();
@ -111,9 +383,10 @@ internal static class MissileCraftingTests
arrange?.Invoke();
var host = FakeHost.Create(Player);
_cache = FakeHost.MakeCache(host, Player, new[] { Crossbow, Bow, Quarrels, Arrows });
_cache = FakeHost.MakeCache(host, Player, new[] { Crossbow, Bow, Quarrels, Arrows }.Concat(extra ?? Array.Empty<uint>()));
var cm = new MissileCraftingManager(host, new LegacyUiSettings { EnableMissileCrafting = true });
cm.SetObjectCache(_cache);
cm.FightIsOn = fight;
return cm;
}
@ -164,10 +437,14 @@ internal static class MissileCraftingTests
}
}
/// <summary>GetDirectInventory re-serves a scan under 1 s old; the test can't wait on the wall clock.</summary>
private static void ForceRescan() =>
/// <summary>GetDirectInventory re-serves a scan under 1 s old; the test can't wait on the wall clock.
/// The tracker read is cached for 100 ms across hosts, so it is dropped too.</summary>
private static void ForceRescan()
{
typeof(WorldObjectCache).GetField("_lastDirectInventoryScan", BindingFlags.Instance | BindingFlags.NonPublic)!
.SetValue(_cache, DateTime.MinValue);
RynthCore.Plugin.RynthAi.EquippedState.Invalidate();
}
private static void PaceOff()
{

View file

@ -242,7 +242,7 @@ internal static class TargetingTests
public readonly CombatManager Combat;
public readonly LegacyUiSettings S;
private readonly WorldObjectCache _cache;
private DateTime _now = DateTime.Now;
private DateTime _now = RynthClock.Now; // the clock RynthAi times with
public Rig(int scheme, bool targetLock, Dictionary<uint, float>? health = null, int monsterRange = 20)
{

View file

@ -0,0 +1,320 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Structural audit 2026-10-21, finding 4: OnTick had one try/catch round the whole tick, so a step
// that threw every tick skipped everything after it, healing and combat included ("the bot just
// stood there and died"; one log line every 10 s). Each step now runs under its own guard
// (Diagnostics/TickGuard.cs). These drive the real OnTick with a step made to throw every tick
// (an object left half-built, as a null after a reload would) and check the rest still runs.
internal static class TickIsolationTests
{
internal const uint Player = 0x50000F01;
private const uint STypeLife = 33;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("tick isolation: a step before healing that throws every tick (quest tracker) doesn't stop the heal", HealDespiteEarlierFault);
r.Add("tick isolation: chores that throw every tick (mana stones, AutoCram) don't stop combat's heartbeat", CombatDespiteChoreFault);
r.Add("tick isolation: a chore failing every tick is switched off with one chat line, retried every 60 s, back on when it works", ChoreTripsAndRecovers);
r.Add("tick isolation: healing failing every tick is never switched off; one chat line, and combat still runs", HealingNeverTrips);
r.Add("tick guard: one log line per step per 10 s (with the count since), and nothing logged while nothing throws", GuardLogThrottle);
r.Add("tick guard: trips only after 30 failures in a row over 5 s; a success in between starts the count again", GuardTripNeedsAStreak);
}
// ── The rig: the real plugin, logged in, macro on (ChoresInFightTests uses it too) ──
internal sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S;
public readonly PlayerVitalsCache V;
public readonly WorldObjectCache Cache;
public readonly RynthCoreHost Host;
public long Now = 50_000_000;
/// <param name="arrange">The test's own objects and host options, before the host exists.</param>
public Bot(int healthPct = 100, bool combat = false, bool heal = true, Action? arrange = null)
{
PaceOff();
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
FakeHost.Names[Player] = "Isolation Tester";
FakeHost.Vitals = ((uint)healthPct, 100, 100, 100, 100, 100);
arrange?.Invoke();
Host = FakeHost.Create(Player);
RynthLog.Init(Host, Path.Combine(Program.TempRoot, "TickIsolationLogs"));
// No combat manager unless asked: the idle line applies, Heal At = Top Off HP = 60.
S = new LegacyUiSettings
{
IsMacroRunning = true, EnableCombat = combat, EnableLooting = false, EnableNavigation = false,
EnableBuffing = false, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0,
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false,
};
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
// As UseAtLoginTests: every empty collection/lock field of the dashboard gets an instance.
foreach (var f in typeof(LegacyDashboardRenderer).GetFields(Any))
{
if (f.GetValue(dash) != null || f.FieldType.IsValueType || f.FieldType == typeof(string)) continue;
bool fillable = f.FieldType == typeof(object)
|| (f.FieldType.Namespace?.StartsWith("System.Collections") == true && !f.FieldType.IsInterface && !f.FieldType.IsAbstract);
if (fillable && f.FieldType.GetConstructor(Type.EmptyTypes) != null)
f.SetValue(dash, Activator.CreateInstance(f.FieldType));
}
Set("_dashboard", dash);
Cache = new WorldObjectCache(Host);
Cache.SetPlayerId(Player);
Set("_objectCache", Cache);
Set("_playerId", Player);
Set("_loginComplete", true);
Set("_loginCompletedAt", DateTime.Now.AddSeconds(-10)); // past the inventory settle window
UseAudit.Reset("RynthAi", () => S.IsMacroRunning);
V = new PlayerVitalsCache();
Set("_vitals", V);
if (heal)
{
var skills = new CharacterSkills(Host);
skills.SetPlayerId(Player);
var sm = new SpellManager(Host, S);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
var b = new BuffManager(Host, S, sm, V);
b.SetCharacterSkills(skills);
b.MarkLiveBuffsReadyForTests();
Set("_buffManager", b);
}
if (combat)
Set("_combatManager", new CombatManager(Host, S, Cache));
P.TickGuards.Clock = () => Now;
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public object? Get(string f) => typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P);
public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
/// <summary>The plugin field's own type, built without its constructor: every call into it throws.</summary>
public object Broken(string field)
{
var type = typeof(RynthAiPlugin).GetField(field, Any)!.FieldType;
object o = RuntimeHelpers.GetUninitializedObject(type);
Set(field, o);
return o;
}
public void Ticks(int n, long msEach = 100)
{
for (int i = 0; i < n; i++)
{
Now += msEach;
P.OnTick();
}
}
public TickGuard G => P.TickGuards;
}
private static void PaceOff()
{
ActionPacer.Enabled = false;
ActionPacer.Reset();
ActionPacer.NowMs = () => Environment.TickCount64;
UseAudit.Reset("?", null);
UseAudit.NowMs = () => Environment.TickCount64;
MoveAudit.Reset();
MoveAudit.NowMs = () => Environment.TickCount64;
}
internal static void Done() => UseAudit.Reset("?", null);
private static int HealSelfCasts()
{
int cat = SpellTable.Named("Heal Self I").First().Category;
return FakeHost.Casts.Count(c => SpellTable.ById(c.SpellId)?.Category == cat);
}
/// <summary>The quest tracker left mid-refresh with no record table: its Tick throws every call.</summary>
private static void BreakQuestTracker(Bot bot)
{
object qt = bot.Broken("_questTracker");
qt.GetType().GetField("_refreshing", Any)!.SetValue(qt, true);
qt.GetType().GetField("_gotFirstQuest", Any)!.SetValue(qt, true);
}
private static string Steps(Bot bot) =>
string.Join(", ", Enum.GetValues<TickStep>().Where(s => bot.G.Failures(s) > 0).Select(s => $"{s}={bot.G.Failures(s)}"));
// ── The tests ────────────────────────────────────────────────────────────
private static void HealDespiteEarlierFault()
{
try
{
var bot = new Bot(healthPct: 40);
BreakQuestTracker(bot);
bot.Ticks(5);
Check.True(bot.G.Failures(TickStep.QuestTracker) >= 5, "the quest tracker threw every tick (" + Steps(bot) + ")");
Check.Eq(HealSelfCasts(), 1, "Heal Self went out anyway (before the guards the whole tick was skipped)");
Check.Eq(bot.G.Failures(TickStep.BuffsAndVitals), 0L, "healing itself ran through");
Check.True(bot.G.Runs(TickStep.Meta) >= 5, "and the tick ran on to its end every time");
Check.False(FakeHost.Logs.Any(l => l.Contains("OnTick exception")), "nothing reached the whole-tick catch");
Check.True(FakeHost.Logs.Any(l => l.Contains("tick step quest tracker error: NullReferenceException")), "the fault is logged by step name");
}
finally { Done(); }
}
private static void CombatDespiteChoreFault()
{
try
{
var bot = new Bot(combat: true, heal: false);
bot.Broken("_manaStoneManager");
bot.Broken("_inventoryManager");
bot.Ticks(10);
Check.True(bot.G.Failures(TickStep.ManaStones) >= 10, "mana stones threw every tick");
Check.True(bot.G.Failures(TickStep.CramStack) >= 10, "AutoCram/AutoStack threw every tick");
Check.Eq(bot.G.Runs(TickStep.Combat), 10L, "combat's heartbeat ran on every tick after them");
Check.Eq(bot.G.Failures(TickStep.Combat), 0L, "and ran through");
Check.True(FakeHost.Logs.Any(l => l.StartsWith("Combat: state enableCombat=True", StringComparison.Ordinal)), "the real heartbeat ran (its state line)");
Check.True(bot.G.Runs(TickStep.Meta) >= 10, "the tick ran to its end");
}
finally { Done(); }
}
private static void ChoreTripsAndRecovers()
{
try
{
var bot = new Bot(combat: true, heal: false);
bot.Broken("_manaStoneManager");
bot.Ticks(29);
Check.False(bot.G.IsOff(TickStep.ManaStones), "29 failures: still on");
bot.Ticks(30); // 59 in a row, 5.9 s
Check.True(bot.G.IsOff(TickStep.ManaStones), "failing every tick for 5 s: switched off");
Check.Eq(FakeHost.Chat.Count(l => l.Contains("mana stones is off")), 1, "one chat line says so");
Check.True(FakeHost.Chat.Any(l => l.Contains("mana stones is off") && l.Contains("NullReferenceException")), "with the error");
long failures = bot.G.Failures(TickStep.ManaStones);
long combatRuns = bot.G.Runs(TickStep.Combat);
bot.Ticks(100); // 10 s
Check.Eq(bot.G.Failures(TickStep.ManaStones), failures, "while off it isn't called");
Check.Eq(bot.G.Runs(TickStep.Combat), combatRuns + 100, "combat runs on every tick");
bot.Ticks(1, msEach: TickGuard.RetryMs); // the retry is due
Check.Eq(bot.G.Failures(TickStep.ManaStones), failures + 1, "tried again after 60 s");
Check.True(bot.G.IsOff(TickStep.ManaStones), "still broken: still off");
Check.Eq(FakeHost.Chat.Count(l => l.Contains("mana stones")), 1, "no second chat line for a failed retry");
bot.Set("_manaStoneManager", null); // a reload rebuilt it (here: none, so the call is a no-op)
bot.Ticks(1, msEach: TickGuard.RetryMs);
Check.False(bot.G.IsOff(TickStep.ManaStones), "the retry ran through: back on");
Check.True(FakeHost.Chat.Any(l => l.Contains("mana stones works again")), "and chat says so");
}
finally { Done(); }
}
private static void HealingNeverTrips()
{
try
{
var bot = new Bot(healthPct: 40, combat: true, heal: false);
bot.Broken("_buffManager");
bot.Ticks(100); // 10 s
Check.Eq(bot.G.Failures(TickStep.BuffsAndVitals), 100L, "healing and buffs failed on every tick");
Check.False(bot.G.IsOff(TickStep.BuffsAndVitals), "and are never switched off");
Check.Eq(FakeHost.Chat.Count(l => l.Contains("healing and buffs keeps failing")), 1, "one chat line says it keeps failing");
Check.Eq(bot.G.Runs(TickStep.Combat), 100L, "combat ran on every tick");
bot.Ticks(50);
Check.Eq(bot.G.Failures(TickStep.BuffsAndVitals), 150L, "still tried every tick");
Check.Eq(FakeHost.Chat.Count(l => l.Contains("healing and buffs")), 1, "and still one chat line");
}
finally { Done(); }
}
// ── TickGuard on its own ────────────────────────────────────────────────
private static (TickGuard G, List<string> Log, List<string> Chat, Func<long> Advance) Guard(long stepMs = 100)
{
FakeHost.Reset();
RynthLog.Init(FakeHost.Create(), Path.Combine(Program.TempRoot, "TickIsolationLogs"));
var log = new List<string>();
var chat = new List<string>();
long now = 1_000_000;
var g = new TickGuard(log.Add, chat.Add) { Clock = () => now };
return (g, log, chat, () => now += stepMs);
}
private static void GuardLogThrottle()
{
var (g, log, chat, advance) = Guard();
var ex = new InvalidOperationException("bad spell data");
for (int i = 0; i < 100; i++) { g.Failed(TickStep.Salvage, ex); advance(); } // one every 100 ms, the last at 9.9 s
int summaries = FakeHost.Logs.Count(l => l.Contains("tick step salvage error: InvalidOperationException: bad spell data"));
Check.Eq(summaries, 1, "100 failures inside 10 s: one summary line");
Check.Eq(log.Count(l => l.Contains("since its last line")), 0, "and no count line yet (the trip at 5 s has its own line)");
g.Failed(TickStep.Salvage, ex); // at 10 s
Check.Eq(FakeHost.Logs.Count(l => l.Contains("tick step salvage error")), 2, "the next one 10 s after the first");
Check.True(log.Any(l => l.Contains("'salvage' failed 100 time(s) since its last line (101 in a row)")), "with the count since the last line: " + string.Join(" | ", log));
int before = FakeHost.Logs.Count;
for (int i = 0; i < 50; i++) { g.Succeeded(TickStep.Combat); advance(); }
Check.Eq(FakeHost.Logs.Count, before, "a step that runs through logs nothing");
Check.Eq(g.Runs(TickStep.Combat), 50L, "but is counted");
Check.False(chat.Any(l => l.Contains("combat")), "and says nothing in chat");
}
private static void GuardTripNeedsAStreak()
{
var (g, _, chat, advance) = Guard(stepMs: 200);
var ex = new NullReferenceException();
// Fails on every other call: never a streak, never off.
for (int i = 0; i < 200; i++)
{
if (i % 2 == 0) g.Failed(TickStep.Pets, ex); else g.Succeeded(TickStep.Pets);
advance();
}
Check.False(g.IsOff(TickStep.Pets), "failing on every other tick: never switched off");
Check.Eq(chat.Count, 0, "no chat");
// One every 100 ms: 30 in a row is not yet 5 s of failing.
var (g2, _, chat2, advance2) = Guard(stepMs: 100);
for (int i = 0; i < 30; i++) { g2.Failed(TickStep.Pets, ex); advance2(); }
Check.False(g2.IsOff(TickStep.Pets), "30 in a row over 2.9 s: not yet");
for (int i = 0; i < 21; i++) { g2.Failed(TickStep.Pets, ex); advance2(); }
Check.True(g2.IsOff(TickStep.Pets), "51 in a row over 5 s: off");
Check.False(g2.MayRun(TickStep.Pets), "and not run");
Check.Eq(chat2.Count, 1, "one chat line");
// An essential step: warned once per streak, never off; a success ends the streak.
for (int i = 0; i < 60; i++) { g2.Failed(TickStep.Combat, ex); advance2(); }
Check.False(g2.IsOff(TickStep.Combat), "combat is never switched off");
Check.True(g2.MayRun(TickStep.Combat), "and always runs");
Check.Eq(chat2.Count(l => l.Contains("combat keeps failing")), 1, "one warning");
g2.Succeeded(TickStep.Combat);
Check.Eq(g2.FailuresInARow(TickStep.Combat), 0, "a success ends the streak");
for (int i = 0; i < 60; i++) { g2.Failed(TickStep.Combat, ex); advance2(); }
Check.Eq(chat2.Count(l => l.Contains("combat keeps failing")), 2, "a new streak warns again");
}
}

View file

@ -174,6 +174,23 @@ internal static class VTankHotkeyTests
Check.True(bot.LastChat.Contains("can't be attacked"), "an NPC: refused (" + bot.LastChat + ")");
Check.Eq(t.Combat.ForcedTargetId, 0, "no lock");
// A corpse selected mid-fight (R-20261021-191720-c788): never a target, and the fight goes on.
const uint Corpse = 0x80000505;
FakeHost.Names[Corpse] = "Corpse of Mob A";
FakeHost.ItemTypes[Corpse] = ItemTypeContainer;
FakeHost.Positions[Corpse] = (Lb | 0x1C, 96f, 97f, 0f);
FakeHost.Bitfields[Corpse] = 0x00002000; // the corpse flag
FakeHost.NotAttackable.Add(Corpse);
t.Cache.OnCreateObject(Corpse);
t.Cache.Tick();
Check.Eq(t.Pick((B, 3)), B, "fighting B");
FakeHost.SelectedItem = Corpse;
bot.P.OnSelectedTargetChange(Corpse, B);
bot.Ra("/ra targetlock");
Check.True(bot.LastChat.Contains("isn't a monster"), "a corpse: refused (" + bot.LastChat + ")");
Check.Eq(t.Combat.ForcedTargetId, 0, "no lock on the corpse");
Check.Eq(t.Pick((B, 3)), B, "the corpse selected: still fighting B");
t.Cache.OnUpdateHealth(A, 0f);
FakeHost.SelectedItem = A;
bot.Ra("/ra targetlock");

View file

@ -28,6 +28,7 @@
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthOracle\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthOracle\obj\**;..\..\Plugins\RynthCore.Plugin.RynthOracle\bin\**" Link="RynthOracle\%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Combat\FellowshipTracker.cs" Link="RynthOracle\Shared\FellowshipTracker.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\RynthClock.cs" Link="RynthOracle\Shared\RynthClock.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiHubApi.cs" Link="RynthOracle\Shared\RynthAiHubApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiSessionClient.cs" Link="RynthOracle\Shared\RynthAiSessionClient.cs" />
<!-- RynthCore's server list and the owner plugin's profile (as in the plugin's csproj). -->

View file

@ -48,12 +48,43 @@ internal static class Program
SharedCodeNamesNoServer(root);
NoServerCommands(root);
NoServerOnlyLinks(root);
RynthAiTimesWithItsClock(root);
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
Console.WriteLine(_failed == 0 ? "ALL BOUNDARY CHECKS PASSED." : $"{_failed} FAILED.");
return _failed == 0 ? 0 : 1;
}
/// <summary>
/// RynthAi times intervals with RynthClock, never DateTime.Now: the wall clock jumps an hour when
/// daylight saving ends, and every "now - last &lt; interval" check stalled for that hour (no target
/// scans or attacks; structural audit 2026-10-21). DateTime.Now stays only where the time of day is
/// shown: RynthLog's timestamps and file names, a backup file's name, a meta's getdatetimelocal.
/// </summary>
private static void RynthAiTimesWithItsClock(string root)
{
string dir = Path.Combine(root, "Plugins", "RynthCore.Plugin.RynthAi");
var found = new List<string>();
int files = 0;
foreach (string file in Directory.EnumerateFiles(dir, "*.cs", SearchOption.AllDirectories).Where(NotBuildOutput))
{
files++;
string rel = Rel(root, file);
if (rel.EndsWith("/Diagnostics/RynthLog.cs", StringComparison.Ordinal) || rel.EndsWith("/RynthClock.cs", StringComparison.Ordinal)) continue; // the log and the clock's own anchor
string[] lines = File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i].Trim();
if (!line.Contains("DateTime.Now", StringComparison.Ordinal) || line.StartsWith("//", StringComparison.Ordinal)) continue;
if (line.Contains("\"getdatetimelocal\"", StringComparison.Ordinal) || line.Contains("\".unreadable-\"", StringComparison.Ordinal)) continue;
found.Add($"{rel}:{i + 1}");
}
}
Check(files > 100, $"RynthAi's sources were found ({files})");
Check(found.Count == 0, "RynthAi times with RynthClock.Now, not DateTime.Now" +
(found.Count > 0 ? ": " + string.Join(", ", found.Take(10)) : ""));
}
/// <summary>No project here is a server plugin: they are RynthServers' (2026-10-21).</summary>
private static void NoServerPlugins(string root)
{