diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 9484370..f3a525f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -126,9 +126,10 @@ public class BuffManager : IDisposable // a buff bot's level 8 expiring over our own fresh VI (2026-10-05). Permanent marks an // item-granted entry (no expiry), which CastBuffsOverItemBuffs leaves out. private readonly Dictionary> _familyLiveEntries = new(); - // Highest tier this session has CAST per family (nominal level). The achieved-tier cap - // applies only once the target tier has been tried, so a family deliberately cast low - // first (the tier-7 creature bootstrap before 8s) still upgrades. + // Highest tier CONFIRMED per family since load (nominal level; written on the cast's + // confirmation, so a fizzled or refused try doesn't count). The achieved-tier cap applies + // only once the target tier has gone through, so a family deliberately cast low first (the + // tier-7 creature bootstrap before 8s) still upgrades, and a failed upgrade is retried. private readonly Dictionary _familyAttemptedTier = new(); /// Keyed by (objectId, spellFamily) packed as long. private readonly Dictionary _itemBuffTimers = new(); @@ -144,6 +145,13 @@ public class BuffManager : IDisposable // Force Rebuff cycle tracking — when set, IsBuffActive consults this instead // of the live timer dicts so FR re-casts every spell to align all timers. private readonly HashSet _forceRebuffCastFamilies = new(); + // The level each family CONFIRMED at in this run (the highest), written only where the family + // joins _forceRebuffCastFamilies; an upgrade that fizzles or is refused leaves it alone. + private readonly Dictionary _runConfirmedLevelByFamily = new(); + // The buff cast in flight that is an upgrade (a lower level of its family was on), 0 = none. + // A failed upgrade is not counted or rested; it is cast again at the next opportunity, paced + // like any cast. + private int _pendingUpgradeSpellId; // Per-family diagnostic throttle — last reason string we logged. Suppresses // dup spam when IsBuffActive is polled every tick by NeedsAnyBuff + CheckAndCastSelfBuffs. @@ -862,7 +870,7 @@ public class BuffManager : IDisposable { _isForceRebuffing = true; _isAutoBatchRebuff = false; - _forceRebuffCastFamilies.Clear(); + ClearRunFamilies(); _buffFailCooldownUntil.Clear(); // explicit recast-all must not be blocked by stale cooldowns _silentNoShowCounts.Clear(); // give parked families a fresh shot on FR too _unsatisfiedStrikes.Clear(); // ditto for the post-batch satisfaction audit @@ -1283,12 +1291,23 @@ public class BuffManager : IDisposable && expiryThen > issuedAt // it was on when we cast && st!.Expiration <= expiryThen.AddSeconds(2)) // and hasn't been refreshed active = false; + // An upgrade is cast over its own lower level, so the family is "on" whatever + // happened, at the give-up as well: it landed only when the entry MOVED (a later + // expiry, or the pending level or higher; an Incantation landing a level low shows + // a lower level, so for one it is the expiry that moves). Unmoved: a no-show. + if (active && _pendingSpellId == _pendingUpgradeSpellId) + { + bool later = _expiryAtCastByFamily.TryGetValue(pendingSpell.Family, out DateTime upThen) + && st!.Expiration > upThen.AddSeconds(2); + bool higher = st!.SpellLevel >= GetSpellLevel(pendingSpell); + active = later || higher; + } if (active) { // During an auto-batch / force-rebuff, IsBuffActive gates on // _forceRebuffCastFamilies (not timers), so the family MUST be // marked cast here or the batch respins this buff forever. - if (_isForceRebuffing) _forceRebuffCastFamilies.Add(pendingSpell.Family); + NoteBuffConfirmed(pendingSpell); _cast.Confirmed(_pendingSpellId, "confirmed in the enchantment registry"); _pendingSpellId = 0; // landed — registry confirms it; advance NoteCastAccepted(); // it went through — end any too-busy backoff @@ -1300,27 +1319,39 @@ public class BuffManager : IDisposable // A WARM snapshot already excludes unknown tiers, so a no-show // is lag/fizzle → retry (NO blacklist). A COLD snapshot has no // other tier-down signal → blacklist this id to drop a tier. - bool cold = !_spellManager.IsKnownSnapshotWarm; - if (cold) _spellManager.MarkSpellUnresolvable(_pendingSpellId); - - // Per-family silent-no-show bookkeeping (the /god loop break). - // Increment regardless of warmth — even the "warm → retry" path - // needs an upper bound, otherwise a buff whose family is in the - // dynamic list but can never actually land loops forever. + // An upgrade's no-show ends that attempt and nothing else: no strike, no 30 min park, + // no blacklist (any of them would delay the next try and the lower level it was cast + // over). Read before EndPendingUpgrade clears the pending upgrade. + bool isUpgrade = _pendingSpellId == _pendingUpgradeSpellId; int fam = pendingSpell.Family; - int noShowCount = _silentNoShowCounts.TryGetValue(fam, out int prev) ? prev + 1 : 1; - _silentNoShowCounts[fam] = noShowCount; - bool parked = false; - if (noShowCount >= SilentNoShowThreshold) + if (isUpgrade) { - _buffFailCooldownUntil[fam] = DateTime.Now + SilentNoShowCooldown; - parked = true; + _host.Log($"[BuffDiag] upgrade '{pendingSpell.Name}' (id={_pendingSpellId}, fam={fam}) not in the live registry after {sinceCastMs:0}ms (the lower level is unchanged): no strike, tried again."); } + else + { + bool cold = !_spellManager.IsKnownSnapshotWarm; + if (cold) _spellManager.MarkSpellUnresolvable(_pendingSpellId); - _host.Log($"[BuffDiag] self-buff '{pendingSpell.Name}' (id={_pendingSpellId}, fam={fam}) absent from live registry after {sinceCastMs:0}ms — " + - (cold ? "cold snapshot → blacklisted, tier-down." : "warm snapshot → retry (lag/fizzle).") + - $" noShows={noShowCount}/{SilentNoShowThreshold}" + - (parked ? $" — family parked {SilentNoShowCooldown.TotalMinutes:0}min." : "")); + // Per-family silent-no-show bookkeeping (the /god loop break). + // Increment regardless of warmth — even the "warm → retry" path + // needs an upper bound, otherwise a buff whose family is in the + // dynamic list but can never actually land loops forever. + int noShowCount = _silentNoShowCounts.TryGetValue(fam, out int prev) ? prev + 1 : 1; + _silentNoShowCounts[fam] = noShowCount; + bool parked = false; + if (noShowCount >= SilentNoShowThreshold) + { + _buffFailCooldownUntil[fam] = DateTime.Now + SilentNoShowCooldown; + parked = true; + } + + _host.Log($"[BuffDiag] self-buff '{pendingSpell.Name}' (id={_pendingSpellId}, fam={fam}) absent from live registry after {sinceCastMs:0}ms — " + + (cold ? "cold snapshot → blacklisted, tier-down." : "warm snapshot → retry (lag/fizzle).") + + $" noShows={noShowCount}/{SilentNoShowThreshold}" + + (parked ? $" — family parked {SilentNoShowCooldown.TotalMinutes:0}min." : "")); + } + EndPendingUpgrade(_pendingSpellId, "no-show"); _pendingSpellId = 0; _onCastResolved?.Invoke("self-buff no-show (registry)"); } @@ -1340,8 +1371,10 @@ public class BuffManager : IDisposable { int stuckId = _pendingSpellId; var stuck = SpellTableStub.GetById(stuckId); + // An upgrade: no strike, park or blacklist, as on the self-buff path. + bool isUpgrade = stuckId == _pendingUpgradeSpellId; bool confirmedKnown = _spellManager.IsKnownSnapshotWarm && _spellManager.IsKnownSpellId(stuckId); - if (!confirmedKnown) + if (!confirmedKnown && !isUpgrade) _spellManager.MarkSpellUnresolvable(stuckId); // 2026-05-25 — per-family silent-no-show bookkeeping on the @@ -1367,7 +1400,7 @@ public class BuffManager : IDisposable // there's no armor to bind to. int fam = stuck?.Family ?? 0; bool parked = false; - if (fam != 0) + if (fam != 0 && !isUpgrade) { int noShowCount = _silentNoShowCounts.TryGetValue(fam, out int prev) ? prev + 1 : 1; _silentNoShowCounts[fam] = noShowCount; @@ -1380,9 +1413,10 @@ public class BuffManager : IDisposable _host.Log($"[BuffChat] NO-CHAT TIMEOUT (armor) pending={stuckId} ('{stuck?.Name}') — no chat in " + $"{NoChatResolveTimeoutMs:0}ms. confirmedKnown={confirmedKnown}. " + - (confirmedKnown ? "Lag/busy — NOT blacklisted." : "Blacklisted → tier-down.") + - (fam != 0 ? $" noShows={_silentNoShowCounts[fam]}/{SilentNoShowThreshold}" : "") + + (isUpgrade ? "An upgrade: no strike, tried again." : confirmedKnown ? "Lag/busy — NOT blacklisted." : "Blacklisted → tier-down.") + + (fam != 0 && !isUpgrade ? $" noShows={_silentNoShowCounts[fam]}/{SilentNoShowThreshold}" : "") + (parked ? $" — family parked {SilentNoShowCooldown.TotalMinutes:0}min." : "")); + EndPendingUpgrade(_pendingSpellId, "no-chat timeout"); _pendingSpellId = 0; _onCastResolved?.Invoke("no-chat timeout (armor)"); } @@ -1552,7 +1586,7 @@ public class BuffManager : IDisposable // every family would read "active"), and the set must still be // populated — it is what the audit iterates. AuditBatchSatisfied(); - _forceRebuffCastFamilies.Clear(); + ClearRunFamilies(); _chain.PassEnd("complete", s => _host.Log(s)); _host.WriteToChat(wasAutoBatch ? "[RynthAi] Rebuff complete." : "[RynthAi] Force Rebuff Complete.", 1); } @@ -2472,7 +2506,7 @@ public class BuffManager : IDisposable // cooldowns are short-lived (120s) so they expire on their own. _isForceRebuffing = true; _isAutoBatchRebuff = true; - _forceRebuffCastFamilies.Clear(); + ClearRunFamilies(); _chain.PassStart(); LogFilterSkips(); } @@ -2555,6 +2589,11 @@ public class BuffManager : IDisposable if (BuffWaitsForMana(spellId, buffBaseName)) return true; + // An upgrade replaces this family's active lower level (read before the cast is recorded). + var spellInfo = SpellTableStub.GetById(spellId); + int upgradeTo = spellInfo == null ? 0 : IsItemEnchantment(spellInfo.Name) ? GetSpellLevel(spellInfo) : EffectiveTargetLevel(spellInfo); + int upgradeFrom = spellInfo != null && buffFamily != 0 ? ActiveLevelBelow(buffFamily, upgradeTo) : 0; + _pendingSpellId = spellId; if (buffFamily != 0) { @@ -2563,9 +2602,13 @@ public class BuffManager : IDisposable _expiryAtCastByFamily[buffFamily] = CurrentExpiryFor(buffFamily); } - var spellInfo = SpellTableStub.GetById(spellId); if (spellInfo != null) _host.WriteToChat($"[RynthAi] Casting: {spellInfo.Name}", 5); + if (upgradeFrom > 0 && spellInfo != null) + { + BuffUpgrades++; + _host.Log($"[Buff] upgrade: {buffBaseName} level {upgradeFrom} -> {upgradeTo} ({spellInfo.Name}){(_isForceRebuffing ? " in this buff run" : "")}"); + } // NOTE: timers are recorded ONLY on chat confirmation ("you cast X"), // never optimistically here. An optimistic item-timer at cast time // left a phantom 1h "active" buff whenever a cast silently failed @@ -2588,16 +2631,12 @@ public class BuffManager : IDisposable { _chain.ClientRefused(spellId, spellInfo?.Name ?? buffBaseName, fast, s => _host.Log(s)); } - if (castOk && buffFamily != 0 && spellInfo != null) - { - // Highest tier cast per family this session: IsBuffActive's landed-tier cap only - // applies once the target tier has been tried. - int castLevel = GetSpellLevel(spellInfo); - if (!_familyAttemptedTier.TryGetValue(buffFamily, out int prevAttempt) || castLevel > prevAttempt) - _familyAttemptedTier[buffFamily] = castLevel; - } + // An upgrade in flight (its registry check and no-show handling differ; EndPendingUpgrade + // ends it on a failure). + _pendingUpgradeSpellId = upgradeFrom > 0 ? spellId : 0; if (!castOk) { + EndPendingUpgrade(spellId, "the client refused it"); // retried after SpellCastIntervalMs (_lastCastAttempt is set above) // Local CastSpell rejected — packet never went out, so no chat // will ever arrive. Clear the gate immediately so the cycle // doesn't hang on this spell. (No timer to undo — we no longer @@ -2611,6 +2650,9 @@ public class BuffManager : IDisposable return false; } + /// Casts that replaced an active buff of the same family at a lower level (tests, status). + internal int BuffUpgrades { get; private set; } + private int FindBestSpellId(string baseName, AcSkillType skill) => _spellManager.GetDynamicSelfBuffId(baseName, skill); @@ -2830,7 +2872,11 @@ public class BuffManager : IDisposable // to their own timers. if (_isForceRebuffing) { - if (_forceRebuffCastFamilies.Contains(targetSpell.Family)) return true; + // Cast this run: done, unless a strictly higher level is castable now than the one this + // run cast (the priority buffs landed and raised the skill, or a higher spell was + // learned). Never lower: a skill that dropped leaves the run's cast alone. + if (_forceRebuffCastFamilies.Contains(targetSpell.Family)) + return !(CastLevelThisRun(targetSpell.Family) is int ran && ran > 0 && GetSpellLevel(targetSpell) > ran); if (!_isAutoBatchRebuff) return false; rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining); } @@ -2893,11 +2939,7 @@ public class BuffManager : IDisposable // skill reaches 8) landed at exactly what was cast; capping it there kept those // three at 7 while everything after them went to 8. No attempt recorded (fresh // login) keeps the cap, so a relog doesn't recast every capped Incantation. - int effectiveTarget = targetLevel; - bool triedLowerOnly = _familyAttemptedTier.TryGetValue(targetSpell.Family, out int attempted) && attempted < targetLevel; - if (!triedLowerOnly - && _familyAchievedTier.TryGetValue(targetSpell.Family, out int achieved) && achieved < effectiveTarget) - effectiveTarget = achieved; + int effectiveTarget = EffectiveTargetLevel(targetSpell); if (timer.SpellLevel < effectiveTarget) { @@ -2935,6 +2977,80 @@ public class BuffManager : IDisposable return false; } + /// The level this force/batch run CONFIRMED at, 0 = none confirmed. + private int CastLevelThisRun(int family) + => _runConfirmedLevelByFamily.TryGetValue(family, out int level) ? level : 0; + + private void ClearRunFamilies() + { + _forceRebuffCastFamilies.Clear(); + _runConfirmedLevelByFamily.Clear(); + } + + /// + /// A buff cast went through (chat, enchantment event or registry): the highest level confirmed + /// per family since load (the landed-tier cap's "tried" mark, so a failed upgrade is retried), + /// and in a force/batch run the family is done at that level. + /// + private void NoteBuffConfirmed(SpellInfo spell) + { + int level = GetSpellLevel(spell); + if (!_familyAttemptedTier.TryGetValue(spell.Family, out int prev) || level > prev) + _familyAttemptedTier[spell.Family] = level; + // The pending upgrade (or better) landed. + if (_pendingUpgradeSpellId != 0 && SpellTableStub.GetById(_pendingUpgradeSpellId) is { } up + && up.Family == spell.Family && level >= GetSpellLevel(up)) + _pendingUpgradeSpellId = 0; + if (!_isForceRebuffing) return; + _forceRebuffCastFamilies.Add(spell.Family); + if (!_runConfirmedLevelByFamily.TryGetValue(spell.Family, out int ran) || level > ran) + _runConfirmedLevelByFamily[spell.Family] = level; + } + + /// + /// The pending upgrade cast did not take (fizzle, refusal, no mana, + /// no-show): it is no longer pending, and it is cast again at the next opportunity. No try cap, + /// and no rest after a fizzle, a client refusal or a no-show; a server mana or component refusal + /// still rests the family as it does for any buff. + /// + private void EndPendingUpgrade(int spellId, string why) + { + if (spellId == 0 || spellId != _pendingUpgradeSpellId) return; + _pendingUpgradeSpellId = 0; + _host.Log($"[Buff] upgrade to {SpellTableStub.GetById(spellId)?.Name ?? spellId.ToString()} did not take ({why}); cast again at the next opportunity."); + } + /// + /// The level IsBuffActive holds a player buff to: the target spell's level, capped at the + /// highest level that family has landed at, once the target level has been confirmed and + /// saw it land lower (Incantations that land skill-capped). + /// + private int EffectiveTargetLevel(SpellInfo targetSpell) + { + int targetLevel = GetSpellLevel(targetSpell); + bool triedLowerOnly = _familyAttemptedTier.TryGetValue(targetSpell.Family, out int attempted) && attempted < targetLevel; + if (!triedLowerOnly && _familyAchievedTier.TryGetValue(targetSpell.Family, out int achieved) && achieved < targetLevel) + return achieved; + return targetLevel; + } + + /// + /// The level of that is on now (this run's confirmed cast during a + /// force/batch run, else a live timer or an item spell with time left), when it is below + /// ; 0 otherwise. A cast that replaces it is an upgrade. + /// + private int ActiveLevelBelow(int family, int newLevel) + { + int on = 0; + 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)) + on = t.SpellLevel; + else if (_itemSpellTimers.TryGetValue(family, out ItemSpellRecord? it) && it.ExpiresAt > DateTime.Now) + on = it.SpellLevel; + return on > 0 && on < newLevel ? on : 0; + } + /// True when the last live read holds an entry in at /// or above with more than left /// (a permanent one counts unless CastBuffsOverItemBuffs is on: then only our timed @@ -3715,7 +3831,7 @@ public class BuffManager : IDisposable // same pump tick, and that chat handler only marks the force-rebuff family // while _pendingSpellId is still set. Clearing pending here without marking // it would make an auto-batch respin this buff forever. - if (_isForceRebuffing) _forceRebuffCastFamilies.Add(pendingSpell.Family); + NoteBuffConfirmed(pendingSpell); _cast.Confirmed(_pendingSpellId, "enchantment landed"); _pendingSpellId = 0; NoteCastAccepted(); @@ -3773,6 +3889,9 @@ public class BuffManager : IDisposable { string lower = text.ToLowerInvariant(); + // A scroll read that taught a spell (ACE: "The scroll is destroyed."): read the spellbook on + // the next buff check, so a newly learned higher level is cast (an upgrade) at once. + if (text.Trim() == "The scroll is destroyed.") _spellManager.InvalidateKnownSpells(); // Diagnostic: log every chat seen while waiting on a cast confirmation, // so we can see what AC is actually emitting and adjust our matchers. @@ -3924,6 +4043,7 @@ public class BuffManager : IDisposable } _host.Log($"[BuffChat] CLEARED+COOLED pending={_pendingSpellId} ({BuffFailCooldownSec:0}s) — hard rejection in '{text}'"); } + EndPendingUpgrade(_pendingSpellId, "refused"); _pendingSpellId = 0; _onCastResolved?.Invoke("hard-reject"); return; @@ -3961,6 +4081,7 @@ public class BuffManager : IDisposable _buffFailCooldownUntil[pendingSpell.Family] = DateTime.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); _onCastResolved?.Invoke("not enough mana"); @@ -3985,6 +4106,7 @@ public class BuffManager : IDisposable _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} via soft-fail in '{text}'"); } _lastCastAttempt = DateTime.MinValue; + EndPendingUpgrade(_pendingSpellId, "fizzled"); _pendingSpellId = 0; _onCastResolved?.Invoke("soft-fail"); return; @@ -4036,6 +4158,21 @@ public class BuffManager : IDisposable return; } + // A result naming a LOWER level of the pending family, or naming an earlier cast of ours + // (the cast tracker matched it to another send), is a late line: recorded for that spell, + // and the pending cast keeps waiting for its own result. An Incantation's line names the + // Incantation (BuffTests "You cast Incantation of Strength Self"), so a pending one is not + // exempt; one that never reports is judged by the registry poll at its give-up. + if (pendingInfo != null && spellInfo != null && spellInfo.Family == pendingInfo.Family + && (GetSpellLevel(spellInfo) < GetSpellLevel(pendingInfo) + || (tracked != null && tracked.SpellId != _pendingSpellId))) + { + if (IsItemEnchantment(spellInfo.Name)) RecordItemSpellCast(spellInfo); + else RecordSpellTimer(spellInfo); + _host.Log($"[BuffChat] result for '{spellInfo.Name}' is a lower level than pending={_pendingSpellId} ('{pendingInfo.Name}') - a late line, recorded; pending kept."); + return; + } + if (spellInfo != null) { _buffFailCooldownUntil.Remove(spellInfo.Family); // it cast — clear any stale hard-fail cooldown @@ -4055,11 +4192,8 @@ public class BuffManager : IDisposable if (_pendingSpellId != 0) { - if (_isForceRebuffing) - { - var ps = SpellTableStub.GetById(_pendingSpellId); - if (ps != null) _forceRebuffCastFamilies.Add(ps.Family); - } + var ps = SpellTableStub.GetById(_pendingSpellId); + if (ps != null) NoteBuffConfirmed(ps); _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} via ou-cast match name='{spellName}' resolvedId={spellId}"); } _pendingSpellId = 0; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs index ba6b58a..bda1386 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs @@ -330,6 +330,9 @@ public class SpellManager /// public bool IsKnownSpellId(int id) => _knownSpellIds.Contains(id); + /// The next RefreshKnownSpells reads the spellbook at once (a spell was just learned). + public void InvalidateKnownSpells() => _lastKnownRefreshUtc = DateTime.MinValue; + /// /// Refresh the known-spell inventory from the engine's main-thread /// spellbook snapshot (host ReadKnownSpells). Throttled. Safe no-op if the diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs index cf1281b..8414bac 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs @@ -77,6 +77,23 @@ internal static class BuffTests r.Add("buff timers: tier-8 weapon auras last 90 minutes", TierEightAuras); // was a known failure; fixed by 9a317a8 r.Add("buff chat: another player's speech can't record a buff timer", SpeechIsNotACast); // was a known failure; fixed by 0e384d2 r.Add("buff school: Armor Tinkering Expertise is a Creature Enchantment spell", ArmorTinkeringSchool); // was a known failure + r.Add("buff upgrade: in a force run, the priority buffs go first, then the families cast before the skill rose are recast a level higher", UpgradeInRun); + r.Add("buff upgrade: the next pass recasts every buff a level higher once the skill allows it; equal level or a lower skill casts nothing", UpgradeNextPass); + r.Add("buff upgrade: a higher level learned from a scroll is cast at once (the spellbook is read again)", UpgradeAfterScroll); + r.Add("buff upgrade: an in-run upgrade that fizzles is cast again; one that always fizzles keeps being cast", UpgradeFizzleRetried); + r.Add("buff upgrade: an upgrade failing on a next pass is cast again every time, with no rest, until it lands", UpgradeFizzleNextPass); + r.Add("buff upgrade: an Incantation landing a level low is not logged or counted as an upgrade when refreshed", IncantationRefreshNotUpgrade); + r.Add("buff upgrade: 'too busy' refusals of an upgrade: it is sent again and lands", UpgradeBusyNotATry); + r.Add("buff upgrade: a late line for the lower level does not confirm the pending upgrade", UpgradeLateLowerLine); + r.Add("buff upgrade: the upgrade line names the level the upgrade is counted at (an Incantation's capped level)", UpgradeLineEffectiveLevel); + r.Add("buff upgrade: through the heartbeat, an always-fizzling upgrade is sent once per answered beat, never unanswered", UpgradeCapViaHeartbeat); + r.Add("buff upgrade: a client-refused upgrade is retried once per SpellCastIntervalMs, not every heartbeat", UpgradeClientRefusalPaced); + r.Add("buff upgrade: an upgrade the registry never shows (still the lower level) is a no-show, not a landing", UpgradeNoShowIsATry); + r.Add("buff upgrade: a late line for the level below a pending Incantation leaves it pending", UpgradeIncantationLateLine); + r.Add("buff upgrade: a late line the cast tracker credits to an earlier send does not confirm the pending cast", UpgradeLateLineFromEarlierSend); + r.Add("buff upgrade: two upgrade no-shows do not park the family; its lower level running low is recast", UpgradeNoShowsDoNotPark); + r.Add("buff upgrade: two item spell upgrades with no chat do not park the family; its lower level running low is recast", UpgradeArmorNoChatDoesNotPark); + r.Add("buff upgrade: an upgrade that would leave mana under the reserve waits for Stamina to Mana, then goes", UpgradeWaitsForManaReserve); } // ── Rig ─────────────────────────────────────────────────────────────────── @@ -135,6 +152,8 @@ internal static class BuffTests public readonly BuffManager B; public readonly SpellManager Sm; public readonly RynthCoreHost Host; + /// The vitals BuffManager reads (all zero unless a test sets them). + public readonly PlayerVitalsCache V = new(); /// Call FakeHost.Reset(), set skills and the spellbook first. public BuffRig() @@ -143,7 +162,7 @@ internal static class BuffTests Host = host; var skills = Skills(host); Sm = NewSpells(host, S, skills); - B = new BuffManager(host, S, Sm, new PlayerVitalsCache()); + B = new BuffManager(host, S, Sm, V); B.SetCharacterSkills(skills); FakeHost.ServerTime = 100_000; } @@ -845,6 +864,678 @@ internal static class BuffTests rig.B.OnChatWindowText($"You cast Aura of {aura} Self VI on Rune Sword", 7); } + // -- Level upgrades: when a higher level of a buff becomes castable (Creature Enchantment Mastery, + // Focus and Willpower raise the skill), the buff is recast at it ----------------------------- + + /// Every spell known; Creature, Life and Item Magic at ; Magic stance; no items listed. + private static BuffRig UpgradeRig(int buffed) + { + FakeHost.Reset(); + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeCreature)] = (buffed, 2); + FakeHost.Skills[(Player, STypeLife)] = (buffed, 2); + FakeHost.Skills[(Player, STypeItem)] = (buffed, 2); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + var rig = new BuffRig(); + rig.B.SetWorldObjectCache(FakeHost.MakeCache(rig.Host, Player, Array.Empty())); + return rig; + } + + private static int LevelOf(int id) => SpellTableStub.GetById(id) is { } s ? BuffManager.GetSpellLevel(s) : 0; + private static int FamilyOf(int id) => SpellTableStub.GetById(id)?.Family ?? 0; + private static int FamilyOfBuff(string anyTierName) => FamilyOf(Id(anyTierName)); + + /// Runs the buff step to the end (confirming each cast by chat), calling + /// after each cast with the casts so far. + private static List RunBuffs(BuffRig rig, Action>? afterCast = null, int max = 200) + { + var ids = new List(); + for (int i = 0; i < max; i++) + { + int before = FakeHost.Casts.Count; + CastSelfBuffs.Invoke(rig.B, null); + if (FakeHost.Casts.Count == before) break; + int id = FakeHost.Casts.Last().SpellId; + ids.Add(id); + string name = NameOf(id); + rig.B.OnChatWindowText($"You cast {name} on {(BuffManager.IsItemEnchantment(name) ? "Rune Robe" : "yourself")}", 7); + afterCast?.Invoke(ids); + } + return ids; + } + + private static string Show(IEnumerable ids) => string.Join(", ", ids.Select(NameOf)); + + /// The run's end as OnHeartbeat does it when CheckAndCastSelfBuffs has nothing left + /// (flag off first, the audit, then the family set cleared). + private static void EndRun(BuffRig rig) + { + const BindingFlags F = BindingFlags.NonPublic | BindingFlags.Instance; + if (!(bool)typeof(BuffManager).GetField("_isForceRebuffing", F)!.GetValue(rig.B)!) return; + typeof(BuffManager).GetField("_isForceRebuffing", F)!.SetValue(rig.B, false); + typeof(BuffManager).GetField("_isAutoBatchRebuff", F)!.SetValue(rig.B, false); + typeof(BuffManager).GetMethod("AuditBatchSatisfied", F)!.Invoke(rig.B, null); + typeof(BuffManager).GetMethod("ClearRunFamilies", F)!.Invoke(rig.B, null); + } + + /// A fake BuffManager clock (the cast tracker's send and give-up times). + private static Action FakeClock(BuffRig rig) + { + DateTime t0 = new DateTime(2026, 10, 10, 12, 0, 0), now = t0; + rig.B.Clock = () => now; + return s => now = t0.AddSeconds(s); + } + + /// CEM sends of a cast list, as levels ("6,7,7"). + private static string CemLevels(IEnumerable sent) => + string.Join(",", sent.Where(id => FamilyOf(id) == FamilyOfBuff("Creature Enchantment Mastery Self VI")).Select(LevelOf)); + + private static void UpgradeInRun() + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"), focus = FamilyOfBuff("Focus Self VI"), will = FamilyOfBuff("Willpower Self VI"); + var rig = UpgradeRig(300); // tier 6 + rig.Live(("Strength Self I", 3000)); // a registry read, nothing of ours on + rig.B.ForceFullRebuff(); + // Creature Enchantment Mastery, Focus and Willpower land and lift Creature Magic to tier 7. + var cast = RunBuffs(rig, ids => { if (ids.Count == 3) FakeHost.Skills[(Player, STypeCreature)] = (340, 2); }); + Check.True(cast.Count > 7, "the run casts the suite: " + Show(cast)); + Check.Eq(string.Join(",", cast.Take(3).Select(FamilyOf)), $"{cem},{focus},{will}", "the priority buffs first: " + Show(cast.Take(3))); + Check.True(cast.Take(3).All(id => LevelOf(id) == 6), "at the level the skill allowed then (6)"); + Check.Eq(string.Join(",", cast.Skip(3).Take(3).Select(FamilyOf)), $"{cem},{focus},{will}", "then the same three again: " + Show(cast.Skip(3).Take(3))); + Check.True(cast.Skip(3).Take(3).All(id => LevelOf(id) == 7), "a level higher (7)"); + Check.Eq(rig.B.BuffUpgrades, 3, "three upgrades"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Buff] upgrade:")), 3, "one line each"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[Buff] upgrade: Creature Enchantment Mastery level 6 -> 7")), "the line names the levels"); + // After the head: every cast is at its school's level now (Creature 7; Life and Item still 6). + var under = cast.Skip(6).Where(id => LevelOf(id) < (BuffManager.SkillForBuff(NameOf(id)) == AcSkillType.CreatureEnchantment ? 7 : 6)).ToList(); + Check.Eq(under.Count, 0, "nothing after the head under its school's level: " + Show(under)); + Check.Eq(cast.Distinct().Count(), cast.Count, "nothing is cast twice at the same level (no churn)"); + + // The skill falls back (a buff ran out) during the run: nothing is cast a level lower. + var down = UpgradeRig(300); + down.Live(("Strength Self I", 3000)); + down.B.ForceFullRebuff(); + var dcast = RunBuffs(down, ids => { if (ids.Count == 3) FakeHost.Skills[(Player, STypeCreature)] = (250, 2); }); + Check.False(dcast.Skip(3).Any(id => FamilyOf(id) == cem || FamilyOf(id) == focus || FamilyOf(id) == will), "no downgrade of the head: " + Show(dcast)); + Check.Eq(down.B.BuffUpgrades, 0, "no upgrades"); + } + + private static void UpgradeNextPass() + { + var rig = UpgradeRig(300); + rig.Live(("Strength Self I", 3000)); + rig.B.ForceFullRebuff(); + var first = RunBuffs(rig); + EndRun(rig); + Check.True(first.Count > 7 && first.All(id => LevelOf(id) <= 6), "the run at tier 6: " + Show(first)); + Check.Eq(RunBuffs(rig).Count, 0, "the same skill: nothing more (equal level is no upgrade)"); + EndRun(rig); + + FakeHost.Skills[(Player, STypeCreature)] = (340, 2); // Creature Magic now allows 7 + var next = RunBuffs(rig); + EndRun(rig); + Check.True(next.Count > 0, "the next pass recasts"); + Check.True(next.All(id => LevelOf(id) == 7), "every recast is a level higher: " + Show(next)); + Check.True(next.Select(FamilyOf).Contains(FamilyOfBuff("Creature Enchantment Mastery Self VI")) && next.Select(FamilyOf).Contains(FamilyOfBuff("Focus Self VI")) + && next.Select(FamilyOf).Contains(FamilyOfBuff("Willpower Self VI")), "including Creature Enchantment Mastery, Focus and Willpower"); + Check.Eq(rig.B.BuffUpgrades, next.Count, "each one an upgrade"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Buff] upgrade:")), next.Count, "one line each"); + Check.Eq(RunBuffs(rig).Count, 0, "then nothing (no churn)"); + EndRun(rig); + + // One buff runs low: recast at the same level, which is not an upgrade. + var onNow = first.Concat(next).GroupBy(FamilyOf).Select(g => g.Last()).Where(id => !BuffManager.IsItemEnchantment(NameOf(id))).ToList(); + int low = next.First(id => FamilyOf(id) == FamilyOfBuff("Focus Self VI")); + rig.Live(onNow.Select(id => (NameOf(id), id == low ? 200.0 : 3000.0)).ToArray()); + int upgradesBefore = rig.B.BuffUpgrades; + var refresh = RunBuffs(rig); + Check.True(refresh.Contains(low), "the low one is recast: " + Show(refresh) + " (last skip: " + rig.B.LastBuffSkipReason + ")"); + Check.Eq(rig.B.BuffUpgrades, upgradesBefore, "at the same level: not an upgrade, no line"); + EndRun(rig); + + FakeHost.Skills[(Player, STypeCreature)] = (250, 2); // the skill drops (tier 5) + Check.Eq(RunBuffs(rig).Count, 0, "a lower skill: nothing is recast lower"); + } + + // The upgrade path sits after the mana reserve hold (BuffWaitsForMana): a higher level that + // would leave mana under the reserve is not sent, counted or logged as an upgrade; Stamina to + // Mana goes instead, and the upgrade goes once mana is back. + private static void UpgradeWaitsForManaReserve() + { + var rig = UpgradeRig(300); // tier 6 + BuffManager.ManaCostOverride = id => LevelOf(id) * 10; // level x 10 (FakeHost.Reset sets 0) + rig.S.GetManaAt = 20; rig.S.TopOffMana = 20; + rig.V.MaxHealth = 400; rig.V.CurrentHealth = 400; + rig.V.MaxStamina = 383; rig.V.CurrentStamina = 289; + rig.V.MaxMana = 383; rig.V.CurrentMana = 300; + rig.Live(("Strength Self I", 3000)); + rig.B.ForceFullRebuff(); + var first = RunBuffs(rig); + EndRun(rig); + Check.True(first.Count > 7 && first.All(id => LevelOf(id) <= 6), "300/383: the run at tier 6: " + Show(first)); + + FakeHost.Skills[(Player, STypeCreature)] = (340, 2); // Creature Magic now allows 7 + int reserve = rig.B.ManaReserve(); + Check.True(reserve > 0, $"a reserve ({reserve})"); + rig.V.CurrentMana = (uint)(reserve + 30); // a level VII (70) would leave it under the reserve + int upgradesBefore = rig.B.BuffUpgrades, castsBefore = FakeHost.Casts.Count; + CastSelfBuffs.Invoke(rig.B, null); + Check.Eq(FakeHost.Casts.Count, castsBefore + 1, "one cast"); + int held = FakeHost.Casts.Last().SpellId; + Check.Eq(FamilyOf(held), FamilyOfBuff("Stamina to Mana Self I"), $"it is Stamina to Mana, not the upgrade ({NameOf(held)})"); + Check.Eq(rig.B.BuffUpgrades, upgradesBefore, "the held upgrade is not counted"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Buff] upgrade:")), 0, "and not logged"); + + rig.B.OnChatWindowText($"You cast {NameOf(held)} on yourself", 7); + rig.V.CurrentMana = 300; + var next = RunBuffs(rig); + EndRun(rig); + Check.True(next.Count > 0 && next.All(id => LevelOf(id) == 7), "mana back: the upgrades go at 7: " + Show(next)); + Check.Eq(rig.B.BuffUpgrades, upgradesBefore + next.Count, "each one an upgrade"); + } + + private static void UpgradeAfterScroll() + { + FakeHost.Reset(); + int cemFam = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + int seven = SpellTable.Rows.Select(r => r.Id).First(id => FamilyOf(id) == cemFam && LevelOf(id) == 7 && NameOf(id).IndexOf("Other", StringComparison.Ordinal) < 0); + Know("Creature Enchantment Mastery Self VI"); + FakeHost.Skills[(Player, STypeCreature)] = (340, 2); // tier 7, but only VI is known + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + var rig = new BuffRig(); + rig.B.SetWorldObjectCache(FakeHost.MakeCache(rig.Host, Player, Array.Empty())); + rig.Live(("Strength Self I", 3000)); + var first = RunBuffs(rig); + Check.Eq(Show(first), "Creature Enchantment Mastery Self VI", "only VI is known: VI"); + EndRun(rig); + FakeHost.Spellbook.Add((uint)seven); // the scroll's spell is now in the spellbook + Check.Eq(RunBuffs(rig).Count, 0, "before the learn line: the spellbook is not read again yet (3 s throttle)"); + rig.B.OnChatWindowText("The scroll is destroyed.", 0); + var after = RunBuffs(rig); + Check.Eq(Show(after), NameOf(seven), "the learned level is cast at once"); + Check.Eq(rig.B.BuffUpgrades, 1, "an upgrade"); + } + + /// A force run where the cast numbered (1-based) in fizzles; + /// Creature Magic rises to tier 7 after the third cast. Returns every cast sent and the confirmed ones. + private static (List Sent, List Confirmed) RunWithFizzles(BuffRig rig, Func fizzle, int max = 300) + { + var sent = new List(); var confirmed = new List(); + for (int i = 0; i < max; i++) + { + int before = FakeHost.Casts.Count; + CastSelfBuffs.Invoke(rig.B, null); + if (FakeHost.Casts.Count == before) break; + int id = FakeHost.Casts.Last().SpellId; + sent.Add(id); + if (fizzle(sent.Count, id)) { rig.B.OnChatWindowText("Your spell fizzled.", 7); continue; } + confirmed.Add(id); + string name = NameOf(id); + rig.B.OnChatWindowText($"You cast {name} on {(BuffManager.IsItemEnchantment(name) ? "Rune Robe" : "yourself")}", 7); + if (sent.Count == 3) FakeHost.Skills[(Player, STypeCreature)] = (340, 2); + } + return (sent, confirmed); + } + + // The upgrade's issue was taken as done, so a fizzled upgrade was never retried. + private static void UpgradeFizzleRetried() + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var rig = UpgradeRig(300); + rig.Live(("Strength Self I", 3000)); + rig.B.ForceFullRebuff(); + var (sent, _) = RunWithFizzles(rig, (n, _) => n == 4); // the first upgrade (CEM 7) fizzles + var cemLevels = sent.Where(id => FamilyOf(id) == cem).Select(LevelOf).ToList(); + Check.Eq(string.Join(",", cemLevels), "6,7,7", "CEM 6, CEM 7 (fizzled), CEM 7 again in the same run: " + Show(sent.Take(8))); + + // CEM 7 always fizzles: it is cast again every time, with no limit and no rest, and + // nothing else gets ahead of it (it heads the list). + var all = UpgradeRig(300); + all.Live(("Strength Self I", 3000)); + all.B.ForceFullRebuff(); + var (sent2, _) = RunWithFizzles(all, (n, id) => n > 3 && FamilyOf(id) == cem && LevelOf(id) == 7, 40); + Check.Eq(sent2.Count, 40, "the run goes on"); + Check.Eq(sent2.Skip(3).Count(id => FamilyOf(id) == cem && LevelOf(id) == 7), 37, "every send after the first three is CEM 7 again: " + Show(sent2.Take(8))); + } + + // A failed upgrade on a next pass is cast again at once each time, at any time (no rest), and + // stops once it lands. + private static void UpgradeFizzleNextPass() + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var rig = UpgradeRig(300); + var at = FakeClock(rig); + at(0); + rig.Live(("Strength Self I", 3000)); + rig.B.ForceFullRebuff(); + RunBuffs(rig); + EndRun(rig); + FakeHost.Skills[(Player, STypeCreature)] = (340, 2); // Creature Magic now allows 7 + bool FizzleCem7(int n, int id) => FamilyOf(id) == cem && LevelOf(id) == 7; + var (sent, _) = RunWithFizzles(rig, FizzleCem7, 20); + Check.Eq(sent.Count(id => FamilyOf(id) == cem && LevelOf(id) == 7), 20, "CEM 7 sent again after every fizzle: " + Show(sent.Take(6))); + Check.False(FakeHost.Logs.Any(l => l.Contains("no upgrade of it for")), "no rest"); + at(30); + var (later, _) = RunWithFizzles(rig, FizzleCem7, 5); + Check.Eq(CemLevels(later), "7,7,7,7,7", "30 s later: still tried every time"); + at(31); + var (landed, _) = RunWithFizzles(rig, (n, id) => false, 60); + EndRun(rig); + Check.Eq(landed.Count(id => FamilyOf(id) == cem), 1, "it lands, once"); + Check.Eq(RunWithFizzles(rig, (n, id) => false, 60).Sent.Count, 0, "then nothing (no churn)"); + } + + // "You're too busy!" for an upgrade is not a failed try. + private static void UpgradeBusyNotATry() + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var rig = UpgradeRig(300); + rig.Live(("Strength Self I", 3000)); + rig.B.ForceFullRebuff(); + var backoff = typeof(BuffManager).GetField("_busyBackoffUntil", BindingFlags.NonPublic | BindingFlags.Instance)!; + int busy = 0; + var sent = new List(); + for (int i = 0; i < 200; i++) + { + int before = FakeHost.Casts.Count; + CastSelfBuffs.Invoke(rig.B, null); + if (FakeHost.Casts.Count == before) break; + int id = FakeHost.Casts.Last().SpellId; + sent.Add(id); + if (FamilyOf(id) == cem && LevelOf(id) == 7 && busy < 2) + { + busy++; + rig.B.OnChatWindowText("You're too busy!", 0); + backoff.SetValue(rig.B, DateTime.MinValue); // the backoff runs on the real clock; not what is tested + continue; + } + rig.B.OnChatWindowText($"You cast {NameOf(id)} on {(BuffManager.IsItemEnchantment(NameOf(id)) ? "Rune Robe" : "yourself")}", 7); + if (sent.Count == 3) FakeHost.Skills[(Player, STypeCreature)] = (340, 2); + } + Check.Eq(busy, 2, "two refusals"); + Check.Eq(CemLevels(sent), "6,7,7,7", "CEM 6, two refused 7s, then 7 lands: " + Show(sent)); + Check.Eq(rig.B.BuffUpgrades, 3 + 2, "the upgrade line counts sends (CEM 3 times, Focus, Willpower)"); + } + + // A late "You cast ... VI" while VII is pending is the lower cast's line. + private static void UpgradeLateLowerLine() + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var rig = UpgradeRig(300); + rig.Live(("Strength Self I", 3000)); + rig.B.ForceFullRebuff(); + var sent = new List(); + bool late = false; + for (int i = 0; i < 200; i++) + { + int before = FakeHost.Casts.Count; + CastSelfBuffs.Invoke(rig.B, null); + if (FakeHost.Casts.Count == before) break; + int id = FakeHost.Casts.Last().SpellId; + sent.Add(id); + if (FamilyOf(id) == cem && LevelOf(id) == 7 && !late) + { + late = true; + rig.B.OnChatWindowText("You cast Creature Enchantment Mastery Self VI on yourself", 7); // the earlier cast's line + Check.Eq(rig.B.PendingSpellId, id, "the VI line leaves VII pending"); + rig.B.OnChatWindowText("Your spell fizzled.", 7); // VII's own result + continue; + } + rig.B.OnChatWindowText($"You cast {NameOf(id)} on {(BuffManager.IsItemEnchantment(NameOf(id)) ? "Rune Robe" : "yourself")}", 7); + if (sent.Count == 3) FakeHost.Skills[(Player, STypeCreature)] = (340, 2); + } + Check.Eq(CemLevels(sent), "6,7,7", "CEM 6, CEM 7 (late VI line, then its fizzle), CEM 7 again: " + Show(sent)); + } + + // The line printed "6 -> 8" for an Incantation counted as an upgrade to its capped 7. + private static void UpgradeLineEffectiveLevel() + { + FakeHost.Reset(); + Know("Incantation of Strength Self"); + FakeHost.Skills[(Player, STypeCreature)] = (500, 2); // tier 8 + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + var rig = new BuffRig(); + rig.B.SetWorldObjectCache(FakeHost.MakeCache(rig.Host, Player, Array.Empty())); + rig.Live(("Armor Self I", 3000)); + RunBuffs(rig); + EndRun(rig); + rig.Live(("Might of the Lugians", 3000)); // it landed as 7 (the cap) + Check.Eq(RunBuffs(rig).Count, 0, "at its cap: not recast"); + EndRun(rig); + rig.Live(("Strength Self VI", 3000)); // ours is gone, someone's VI is on + var up = RunBuffs(rig); + EndRun(rig); + Check.Eq(Show(up), "Incantation of Strength Self", "recast to reach the cap again"); + var line = FakeHost.Logs.LastOrDefault(l => l.Contains("[Buff] upgrade:")) ?? ""; + Check.True(line.Contains("level 6 -> 7 (Incantation of Strength Self)"), "the line says 6 -> 7, the level counted: " + line); + } + + private static T Fld(BuffManager b, string name) => (T)typeof(BuffManager).GetField(name, BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(b)!; + private static void SetFld(BuffManager b, string name, object v) => typeof(BuffManager).GetField(name, BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(b, v); + + private static int AttemptedOf(BuffRig rig, int family) => Fld>(rig.B, "_familyAttemptedTier").TryGetValue(family, out int n) ? n : 0; + + /// The macro's path: heartbeats on a fake clock, the buff step running itself. + private sealed class BeatRig + { + public readonly BuffRig R; + private readonly Action _at; + private double _t; + public BeatRig(int buffed) + { + R = UpgradeRig(buffed); + R.S.IsMacroRunning = true; + R.S.SpellCastIntervalMs = 0; + _at = FakeClock(R); + _at(0); + R.B.MarkLiveBuffsReadyForTests(); + } + public void Tick(double s) { _t += s; _at(_t); } + /// Up to beats of 3 s, confirming every cast by chat except + /// the first one picks, which is returned unanswered (0 = none). + public int Beats(int n, Func hold) + { + for (int i = 0; i < n; i++) + { + Tick(3); + int before = FakeHost.Casts.Count; + R.B.OnHeartbeat(); + if (FakeHost.Casts.Count == before) continue; + int id = FakeHost.Casts.Last().SpellId; + if (hold(id)) return id; + R.B.OnChatWindowText($"You cast {NameOf(id)} on {(BuffManager.IsItemEnchantment(NameOf(id)) ? "Rune Robe" : "yourself")}", 7); + } + return 0; + } + /// A force run at the rig's skill, to its end, through the heartbeat. + public void FirstRun() + { + R.Live(("Strength Self I", 3000)); + R.B.ForceFullRebuff(); + Beats(150, _ => false); + Check.False(R.B.GetStateSnapshot().IsForceRebuffing, "the first run ends"); + } + /// The pending cast's settle and give-up are read on the real clock too: put the send in the past. + public void SendLongAgo(double seconds) + { + SetFld(R.B, "_lastCastAttempt", DateTime.Now.AddSeconds(-seconds)); + SetFld(R.B, "_lastSelfBuffPollAt", DateTime.MinValue); + } + } + + /// A pass after a run at tier 6 with Creature Magic now at 7, stopped with CEM 7 sent and pending. + private static (BuffRig Rig, int Seven) PendingCem7(Action? setup = null) + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var rig = UpgradeRig(300); + setup?.Invoke(rig); + rig.Live(("Strength Self I", 3000)); + rig.B.ForceFullRebuff(); + var first = RunBuffs(rig); + EndRun(rig); + FakeHost.Skills[(Player, STypeCreature)] = (340, 2); + rig.Live(first.GroupBy(FamilyOf).Select(g => g.Last()).Where(id => !BuffManager.IsItemEnchantment(NameOf(id))).Select(id => (NameOf(id), 3000.0)).ToArray()); + for (int i = 0; i < 100; i++) + { + int before = FakeHost.Casts.Count; + CastSelfBuffs.Invoke(rig.B, null); + if (FakeHost.Casts.Count == before) break; + int id = FakeHost.Casts.Last().SpellId; + if (FamilyOf(id) == cem && LevelOf(id) == 7) return (rig, id); + rig.B.OnChatWindowText($"You cast {NameOf(id)} on {(BuffManager.IsItemEnchantment(NameOf(id)) ? "Rune Robe" : "yourself")}", 7); + } + return (rig, 0); + } + + // The registry still holding VI at the give-up was taken as VII landing. + // registryAtGiveUp: what the registry holds when the poll judges the pending CEM 7. + private static (BeatRig H, int Seven) NoShowCase((string, double)[] registryAtGiveUp) + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var h = new BeatRig(300); + h.FirstRun(); + FakeHost.Skills[(Player, STypeCreature)] = (340, 2); + h.R.Live(("Creature Enchantment Mastery Self VI", 3000), ("Focus Self VI", 3000), ("Willpower Self VI", 3000)); + int seven = h.Beats(60, id => FamilyOf(id) == cem && LevelOf(id) == 7); + Check.True(seven != 0 && h.R.B.PendingSpellId == seven, "CEM 7 is sent over the live VI and waits"); + h.R.Live(registryAtGiveUp); + h.SendLongAgo(3); // no chat + h.Tick(3); + h.R.B.OnHeartbeat(); + return (h, seven); + } + + private static void UpgradeNoShowIsATry() + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var others = new[] { ("Focus Self VI", 3000.0), ("Willpower Self VI", 3000.0) }; + + var (h, seven) = NoShowCase(others.Prepend(("Creature Enchantment Mastery Self VI", 3000.0)).ToArray()); + Check.True(FakeHost.Logs.Any(l => l.Contains("not in the live registry") && l.Contains("no strike, tried again")), "VI unmoved: a no-show"); + Check.True(AttemptedOf(h.R, cem) < 7, $"VII is not taken as landed (attempted {AttemptedOf(h.R, cem)})"); + Check.Eq(FakeHost.Casts.Count(c => c.SpellId == seven), 2, "given up, and VII is sent again (the same beat)"); + + // The entry moved: VII at the same expiry (a higher level) ... + (h, seven) = NoShowCase(others.Prepend(("Adja's Blessing", 3000.0)).ToArray()); + Check.Eq(AttemptedOf(h.R, cem), 7, "VII in the registry: landed"); + Check.Eq(FakeHost.Casts.Count(c => c.SpellId == seven), 1, "not sent again"); + + // ... or the same level with a later expiry (an Incantation landing low shows this way). + (h, seven) = NoShowCase(others.Prepend(("Creature Enchantment Mastery Self VI", 3600.0)).ToArray()); + Check.Eq(AttemptedOf(h.R, cem), 7, "a later expiry: landed"); + Check.Eq(FakeHost.Casts.Count(c => c.SpellId == seven), 1, "not sent again"); + } + // A pending Incantation took a late VII line as its own result. + private static void UpgradeIncantationLateLine() + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var rig = UpgradeRig(340); + rig.Live(("Strength Self I", 3000)); + rig.B.ForceFullRebuff(); + var first = RunBuffs(rig); + EndRun(rig); + var on = first.GroupBy(FamilyOf).Select(g => g.Last()).Where(id => !BuffManager.IsItemEnchantment(NameOf(id))).ToList(); + FakeHost.Skills[(Player, STypeCreature)] = (500, 2); + rig.Live(on.Select(id => (NameOf(id), 3000.0)).ToArray()); + int inc = 0; + for (int i = 0; i < 100 && inc == 0; i++) + { + int before = FakeHost.Casts.Count; + CastSelfBuffs.Invoke(rig.B, null); + if (FakeHost.Casts.Count == before) break; + int id = FakeHost.Casts.Last().SpellId; + if (FamilyOf(id) == cem && LevelOf(id) == 8) { inc = id; break; } + rig.B.OnChatWindowText($"You cast {NameOf(id)} on {(BuffManager.IsItemEnchantment(NameOf(id)) ? "Rune Robe" : "yourself")}", 7); + } + Check.True(inc != 0, "the CEM Incantation is sent over VII"); + rig.B.OnChatWindowText($"You cast {NameOf(on.First(id => FamilyOf(id) == cem))} on yourself", 7); // the VII cast's late line + Check.Eq(rig.B.PendingSpellId, inc, "the late VII line leaves the Incantation pending"); + Check.True(AttemptedOf(rig, cem) < 8, "and not taken as landed"); + rig.B.OnChatWindowText("Your spell fizzled.", 7); + Check.Eq(rig.B.PendingSpellId, 0, "its own fizzle ends it"); + int sentBefore = FakeHost.Casts.Count; + CastSelfBuffs.Invoke(rig.B, null); + Check.True(FakeHost.Casts.Count > sentBefore && FakeHost.Casts.Last().SpellId == inc, "and it is cast again"); + } + + // An Incantation heard (open on the server) and given up; the + // skill drops; VII goes out; then the Incantation's own line arrives. It names a HIGHER level than + // the pending VII, so only the tracker (it credits the line to the open Incantation) says it is late. + private static void UpgradeLateLineFromEarlierSend() + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var h = new BeatRig(340); + h.FirstRun(); + FakeHost.Skills[(Player, STypeCreature)] = (500, 2); + h.R.Live(("Adja's Blessing", 200), ("Inner Calm", 3000), ("Mind Blossom", 3000)); // CEM VII running low + int inc = h.Beats(60, id => FamilyOf(id) == cem); + Check.True(inc != 0 && LevelOf(inc) == 8, "the CEM Incantation is sent: " + NameOf(inc)); + h.R.B.OnChatWindowText("You say, \"Puish Zharil\"", 17); // its incantation: the server runs it + FakeHost.Skills[(Player, STypeCreature)] = (340, 2); // the skill drops + for (int i = 0; i < 6 && h.R.B.PendingSpellId == inc; i++) + { + h.SendLongAgo(6); + h.Tick(3); + h.R.B.OnHeartbeat(); // no result: given up, VII goes out + } + int seven = h.R.B.PendingSpellId; + Check.True(seven != 0 && FamilyOf(seven) == cem && LevelOf(seven) == 7, "given up; VII is pending: " + NameOf(seven)); + h.R.B.OnChatWindowText($"You cast {NameOf(inc)} on yourself", 7); // the Incantation's late line + Check.Eq(h.R.B.PendingSpellId, seven, "VII still waits for its own result"); + } + + /// Lets the pending reach its give-up unanswered twice (it is resent + /// in between); returns the give-ups done. Every other cast is confirmed. + private static int FailTwice(BeatRig h, int id) + { + int gaveUp = 0; + for (int k = 0; k < 20 && gaveUp < 2; k++) + { + if (h.R.B.PendingSpellId != id) { if (h.Beats(40, x => x == id) == 0) break; continue; } + h.SendLongAgo(6); + h.Tick(6); + h.R.B.OnHeartbeat(); + if (h.R.B.PendingSpellId != id || FakeHost.Casts.Count(c => c.SpellId == id) > gaveUp + 1) gaveUp++; + } + // The last give-up's beat may have sent the next cast: answer it, as Beats does. + int next = h.R.B.PendingSpellId; + if (next != 0 && next != id) + h.R.B.OnChatWindowText($"You cast {NameOf(next)} on {(BuffManager.IsItemEnchantment(NameOf(next)) ? "Rune Robe" : "yourself")}", 7); + return gaveUp; + } + + private static bool Parked(BuffRig rig, int family) => Fld>(rig.B, "_buffFailCooldownUntil").ContainsKey(family); + + // The no-show strikes parked the family 30 min after two upgrade no-shows, so the + // lower level it was cast over was not recast when it ran low. + private static void UpgradeNoShowsDoNotPark() + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var h = new BeatRig(300); + h.FirstRun(); + // The registry holds the first run's player buffs (so a batch is the few upgrades, not the suite). + var six = FakeHost.Casts.Select(c => c.SpellId).Where(id => !BuffManager.IsItemEnchantment(NameOf(id))).Distinct().ToList(); + (string, double)[] Registry(double cemLeft) => six.Select(id => (NameOf(id), FamilyOf(id) == cem ? cemLeft : 3000.0)).ToArray(); + FakeHost.Skills[(Player, STypeCreature)] = (340, 2); + h.R.Live(Registry(3000)); + int seven = h.Beats(60, id => FamilyOf(id) == cem && LevelOf(id) == 7); + Check.True(seven != 0, "CEM 7 is sent over the live VI"); + Check.Eq(FailTwice(h, seven), 2, "two no-shows"); + Check.False(Parked(h.R, cem), "the family is not parked"); + h.R.Live(Registry(100)); // VI running low + // No limit: CEM is still being cast (already resent, or on a later beat). A 30 min park (the + // bug) runs on the real clock and would hold it throughout. + Check.True(FamilyOf(h.R.B.PendingSpellId) == cem || h.Beats(150, id => FamilyOf(id) == cem) != 0, "CEM is still being cast"); + Check.False(Parked(h.R, cem), "never parked"); } + + // The item spell (armor) twin of the test above. + private static void UpgradeArmorNoChatDoesNotPark() + { + var h = new BeatRig(300); + h.FirstRun(); + FakeHost.Skills[(Player, STypeItem)] = (340, 2); + int item7 = h.Beats(80, id => BuffManager.IsItemEnchantment(NameOf(id)) && LevelOf(id) == 7); + Check.True(item7 != 0, "an item spell is upgraded to 7: " + NameOf(item7)); + int fam = FamilyOf(item7); + Check.Eq(FailTwice(h, item7), 2, "two no-chat give-ups"); + Check.False(Parked(h.R, fam), "the family is not parked"); + // Its VI record runs low. + object rec = ((System.Collections.IDictionary)Fld(h.R.B, "_itemSpellTimers"))[fam]!; + rec.GetType().GetField("ExpiresAt")!.SetValue(rec, DateTime.Now.AddSeconds(100)); + Check.True(h.Beats(40, id => FamilyOf(id) == fam) != 0, "running low: recast"); + } + + // No limit and no rest, through OnHeartbeat: an always-fizzling CEM 7 is sent on + // every beat (one per answer), the late VI line confirms nothing, and nothing goes out unanswered. + private static void UpgradeCapViaHeartbeat() + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var h = new BeatRig(300); + h.FirstRun(); + var six = FakeHost.Casts.Select(c => c.SpellId).Where(id => !BuffManager.IsItemEnchantment(NameOf(id))).Distinct().ToList(); + FakeHost.Skills[(Player, STypeCreature)] = (340, 2); + h.R.Live(six.Select(id => (NameOf(id), 3000.0)).ToArray()); + int seven = h.Beats(60, id => FamilyOf(id) == cem && LevelOf(id) == 7); + Check.True(seven != 0, "CEM 7 is sent"); + h.R.B.OnChatWindowText("You cast Creature Enchantment Mastery Self VI on yourself", 7); // a late VI line + Check.Eq(h.R.B.PendingSpellId, seven, "the late VI line confirms nothing"); + h.R.B.OnChatWindowText("Your spell fizzled.", 7); + int sends = 1; + for (int i = 0; i < 20; i++) + { + h.Tick(3); + int before = FakeHost.Casts.Count; + h.R.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count - before, 1, $"beat {i}: one send"); + Check.Eq(FakeHost.Casts.Last().SpellId, seven, $"beat {i}: CEM 7 again"); + sends++; + h.R.B.OnChatWindowText("Your spell fizzled.", 7); + } + Check.Eq(sends, 21, "21 sends in 21 answered beats"); + // Unanswered: nothing more goes out while it waits. + int held = FakeHost.Casts.Count; + h.Tick(3); + h.R.B.OnHeartbeat(); // sends CEM 7 + for (int i = 0; i < 10; i++) { h.Tick(0.1); h.R.B.OnHeartbeat(); } + Check.Eq(FakeHost.Casts.Count - held, 1, "unanswered: one send, then it waits"); + } + + // With no limit, a cast the client refuses (nothing goes out, no answer comes) + // must still wait SpellCastIntervalMs between attempts, not re-send on every heartbeat. + private static void UpgradeClientRefusalPaced() + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var h = new BeatRig(300); + h.FirstRun(); + var six = FakeHost.Casts.Select(c => c.SpellId).Where(id => !BuffManager.IsItemEnchantment(NameOf(id))).Distinct().ToList(); + FakeHost.Skills[(Player, STypeCreature)] = (340, 2); + h.R.Live(six.Select(id => (NameOf(id), 3000.0)).ToArray()); + h.R.S.SpellCastIntervalMs = 600_000; // the interval runs on the real clock: shut for this test + try + { + FakeHost.CastRefused = true; + h.SendLongAgo(700); // an interval has passed + for (int i = 0; i < 30; i++) { h.Tick(0.1); h.R.B.OnHeartbeat(); } + Check.Eq(FakeHost.CastsRefused, 1, "30 heartbeats inside one interval: one refused attempt"); + Check.Eq(h.R.B.PendingSpellId, 0, "nothing pending"); + h.SendLongAgo(700); // the next interval + h.Tick(0.1); + h.R.B.OnHeartbeat(); + Check.Eq(FakeHost.CastsRefused, 2, "the next interval: tried again"); + Check.True(FakeHost.Logs.Count(l => l.Contains("did not take (the client refused it)")) >= 2 && FakeHost.Logs.Any(l => l.Contains("Adja's Blessing")), "the refused cast was the CEM upgrade"); + } + finally { FakeHost.CastRefused = false; } + } + + // "Incantation of Strength Self" lands as Strength Self VI here; refreshing it is + // not an upgrade. + private static void IncantationRefreshNotUpgrade() + { + FakeHost.Reset(); + Know("Incantation of Strength Self"); + FakeHost.Skills[(Player, STypeCreature)] = (500, 2); // tier 8 + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + var rig = new BuffRig(); + rig.B.SetWorldObjectCache(FakeHost.MakeCache(rig.Host, Player, Array.Empty())); + rig.Live(("Armor Self I", 3000) /* a registry read with no Strength on */); + var first = RunBuffs(rig); + EndRun(rig); + Check.Eq(Show(first), "Incantation of Strength Self", "the Incantation is cast and confirmed"); + rig.Live(("Strength Self VI", 3000)); // it landed as VI + Check.Eq(RunBuffs(rig).Count, 0, "landed a level low: not recast (the cap)"); + EndRun(rig); + rig.Live(("Strength Self VI", 200)); // running low + var refresh = RunBuffs(rig); + EndRun(rig); + Check.Eq(Show(refresh), "Incantation of Strength Self", "refreshed"); + Check.Eq(rig.B.BuffUpgrades, 0, "not an upgrade"); + Check.False(FakeHost.Logs.Any(l => l.Contains("[Buff] upgrade:")), "no upgrade line"); + } + private static void PriorityOrder() { var rig = SuiteRig(MeleeItem, WandItem);