RynthAi: no false "never reached your hand" weapon ban #21

Open
AwfulWaffle wants to merge 2 commits from AwfulWaffle/RynthSuite:wield-ban-false-positive into main
5 changed files with 373 additions and 3 deletions

View file

@ -1336,6 +1336,15 @@ public partial class CombatManager : IDisposable
_inHandId = 0;
_inHandReadAt = DateTime.MinValue;
}
// A login or relog (the same character too): every "never reached your hand" ban ends. Those
// are guesses from a missing answer; the server's own "skill too low" bans stay.
if (_neverReachedBans.Count > 0)
{
foreach (int id in _neverReachedBans) _skillTooLowUntil.Remove(id);
_host.Log($"[EquipDiag] relog: {_neverReachedBans.Count} weapon(s) left out as 'never reached your hand' are back in the weapon choice");
_neverReachedBans.Clear();
_planCache = null;
}
_playerId = playerId;
_monsterMatchEval = new MonsterMatchEvaluator(_worldFilter, playerId);
}
@ -4546,6 +4555,7 @@ public partial class CombatManager : IDisposable
public void OnHeartbeat()
{
NoteSwapPortal();
NoteSwapWieldsSeen();
// The hands swap's steps (weapons back, or the fight's weapons) go before the gates; the macro stopping ends it (freeing the gate).
TickRearmSwap();
@ -5833,6 +5843,10 @@ public partial class CombatManager : IDisposable
/// skill raise may let it in later).</summary>
internal const double SkillTooLowSkipMin = 30;
private readonly Dictionary<int, DateTime> _skillTooLowUntil = new();
// The entries of _skillTooLowUntil put there because a wield "never reached your hand" (no
// server answer). A relog clears these; a real "skill too low" from the server stays.
private readonly HashSet<int> _neverReachedBans = new();
internal const string NeverReachedWhy = "it never reached your hand (the client refused the wield)";
/// <summary>
/// True while <paramref name="id"/> sits out a SkillTooLow refusal. Drakkon (2026-10-16) was
@ -5844,14 +5858,18 @@ public partial class CombatManager : IDisposable
if (!_skillTooLowUntil.TryGetValue(id, out DateTime until)) return false;
if (RynthClock.Now < until) return true;
_skillTooLowUntil.Remove(id);
_neverReachedBans.Remove(id);
return false;
}
private void NoteSkillTooLow(int id, string? why = null)
private void NoteSkillTooLow(int id, string? why = null, bool neverReached = false)
{
if (id == 0) return;
bool first = !_skillTooLowUntil.ContainsKey(id);
_skillTooLowUntil[id] = RynthClock.Now.AddMinutes(SkillTooLowSkipMin);
// The server's own "skill too low" outranks a "never reached your hand" on the same weapon.
if (!neverReached) _neverReachedBans.Remove(id);
else if (first) _neverReachedBans.Add(id);
_planCache = null;
if (first)
{
@ -5877,8 +5895,8 @@ public partial class CombatManager : IDisposable
// The server's own list (v87) says it never reached the hand: the wield can't work
// (the client refused it unasked). Out of the choice like a "skill too low" answer,
// not retried every 2 minutes with the off hand taken off each time (the Tetsubo, 2026-10-18).
if (SwapTracker.GaveUpId is int gaveUp && EquippedState.TryGet(_host, out _))
NoteSkillTooLow(gaveUp, "it never reached your hand (the client refused the wield)");
if (SwapTracker.GaveUpId is int gaveUp && NeverReachedHand(gaveUp))
NoteSkillTooLow(gaveUp, NeverReachedWhy, neverReached: true);
}
SwapTracker.GaveUpId = null;
if (step == WeaponSwapTracker.Step.Hold && (RynthClock.Now - _lastSwapHoldLogAt).TotalSeconds > 10)
@ -5891,6 +5909,40 @@ public partial class CombatManager : IDisposable
private DateTime _lastSwapHoldLogAt = DateTime.MinValue;
/// <summary>
/// True only when the engine's equipment list can be read, does not hold
/// <paramref name="id"/> now, and the swap tracker never saw it there while its wields were
/// under way (<see cref="NoteSwapWieldsSeen"/>). A readable list alone used to be enough,
/// so a weapon that did reach the hand, and that buffing then swapped out for a wand before
/// combat looked, was banned for 30 min.
/// </summary>
private bool NeverReachedHand(int id)
{
if (SwapTracker.WasSeenWielded(id)) return false;
EquippedState.Invalidate();
return EquippedState.TryGet(_host, out var map) && !map.ContainsKey(id);
}
/// <summary>
/// While a combat wield is in flight or has recent tries counted, read the engine's equipment
/// list (API v87, the server's own wield messages) and tell the swap tracker about every item
/// in a main-hand slot (the slots <see cref="InHandWeaponId"/> reads; a weapon sitting in the
/// shield slot is not the wield combat asked for). Called every tick by the plugin ahead of its
/// buffing hold, because the buffing hold skips <see cref="OnHeartbeat"/>, and from OnHeartbeat
/// itself. No game command.
/// </summary>
internal void NoteSwapWieldsSeen()
{
try
{
if (!SwapTracker.HasAttemptsAt(RynthClock.Now)) return;
if (!EquippedState.TryGet(_host, out var map)) return;
foreach (var kv in map)
if ((kv.Value & MainHandSlots) != 0) SwapTracker.SeenWielded(kv.Key);
}
catch { /* a failed read must never stop the tick */ }
}
/// <summary>
/// Why a swap the tracker allows should not start now (null = start it). Settling: the
/// target was switched to (it replaced another live target) under WeaponSwapSettleMs ago;

View file

@ -61,9 +61,44 @@ internal sealed class WeaponSwapTracker
private int _lastFrom, _lastTo;
private DateTime _lastLandedAt = DateTime.MinValue;
private int _askKey, _pendingKey, _lastKey; // the fight (target id) each swap was for; 0 = unknown
// Weapons seen in a wielded slot (the engine's equipment list) during their current run of
// wields. A new run (the first send after the count was cleared) forgets the sighting, so a
// weapon that later stops reaching the hand is given up on again.
private readonly HashSet<int> _seenWielded = new();
private DateTime _lastSentAt = DateTime.MinValue;
/// <summary>How long after the last send counted tries keep the equipment list sampled.</summary>
public double AttemptWatchMs { get; set; } = 120_000;
/// <summary>The weapon a swap is in flight for (0 = none).</summary>
public int PendingId => _pendingId;
/// <summary>
/// True while a wield is in flight, or tries are counted and the last send was under
/// <see cref="AttemptWatchMs"/> before <paramref name="now"/>: the equipment list is worth
/// sampling. A stale count left behind does not keep the sampler reading every tick.
/// </summary>
public bool HasAttemptsAt(DateTime now) =>
_pendingId != 0 || (_tries.Count > 0 && (now - _lastSentAt).TotalMilliseconds < AttemptWatchMs);
/// <summary>True when <paramref name="id"/> was seen wielded while its wields were under way (see <see cref="SeenWielded"/>).</summary>
public bool WasSeenWielded(int id) => _seenWielded.Contains(id);
/// <summary>
/// <paramref name="id"/> is in a wielded slot per the engine's equipment list, sampled every
/// tick while a wield is under way. When it has a wield in flight or tries counted, the wield
/// worked: its try count starts over and it is remembered as seen, so it is never taken for a
/// weapon that "never reached your hand". The swap in flight is left alone (combat lands it
/// when it sees the weapon in hand itself), so a stale hand read can never send a second
/// UseObject that would take the weapon off again. A weapon reached the hand
/// twice, buffing swapped it out to a wand each time before combat looked again, and each of
/// those wields counted as a failed try until it was banned for 30 min.
/// </summary>
public void SeenWielded(int id)
{
if (id == 0 || (_pendingId != id && !_tries.ContainsKey(id))) return;
_seenWielded.Add(id);
_tries.Remove(id);
_busyRefunds.Remove(id);
}
/// <summary>Wields sent for <paramref name="id"/> since it was last in hand.</summary>
public int TriesFor(int id) => _tries.TryGetValue(id, out int t) ? t : 0;
/// <summary>Why the last Hold happened, for the log ("" = none).</summary>
@ -140,6 +175,9 @@ internal sealed class WeaponSwapTracker
_pendingId = id;
_pendingFrom = fromId;
_pendingAt = now;
_lastSentAt = now;
// A fresh run of wields: an earlier sighting says nothing about this one.
if (!_tries.ContainsKey(id)) _seenWielded.Remove(id);
_tries[id] = (_tries.TryGetValue(id, out int t) ? t : 0) + 1;
}
@ -179,6 +217,7 @@ internal sealed class WeaponSwapTracker
_tries.Clear();
_busyRefunds.Clear();
_restUntil.Clear();
_seenWielded.Clear();
_busyUntil = DateTime.MinValue;
}
@ -196,9 +235,11 @@ internal sealed class WeaponSwapTracker
_busyRefunds.Clear();
_busyUntil = DateTime.MinValue;
_restUntil.Clear();
_seenWielded.Clear();
_landed.Clear();
_lastFrom = _lastTo = 0;
_lastLandedAt = DateTime.MinValue;
_lastSentAt = DateTime.MinValue;
_askKey = _pendingKey = _lastKey = 0;
HoldReason = "";
Notice = null;

View file

@ -1739,6 +1739,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// Healing and buffs: essential, never switched off by its guard (TickGuard).
Guard(TickStep.BuffsAndVitals, () => _buffManager?.OnHeartbeat());
if (diag) Host.Log("[RynthAi] OnTick: after buffManager");
// Combat's wields in flight, checked against the equipment list every tick, ahead of
// the buffing hold below (which skips combat's heartbeat): a weapon that reached the
// hand and was swapped out for a wand by buffing is not a failed wield.
// Reads only, and catches its own faults.
_combatManager?.NoteSwapWieldsSeen();
Guard(TickStep.ReloadBlocker, () =>
{
NoteCarriedOverSessionReady();

View file

@ -191,6 +191,7 @@ internal static class Program
CommandReplyTests.Register(runner);
MonsterStatsTests.Register(runner);
MetaSaveTests.Register(runner);
WieldBanTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -0,0 +1,271 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The false "it never reached your hand" ban: combat's wield of a weapon
// landed twice, buffing swapped it out for a wand each time before combat looked again, each of
// those wields counted as a failed try, and after the third the weapon was left out of the
// choice for 30 min ("no weapon found ... proceeding unarmed" 115 times). The engine's
// equipment list (FakeHost.Equipped, API v87) plays the server's wield messages here.
internal static class WieldBanTests
{
private const uint Player = 0x50000C01;
private const uint Blade = 0x800484AA, Wand = 0x80048401, Nodachi = 0x80048402;
private const uint MeleeSlot = 0x00100000, HeldSlot = 0x01000000;
private const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic;
public static void Register(Runner r)
{
r.Add("wield ban: a weapon seen wielded between combat's looks is not banned, its tries start over", SeenWieldedNotBanned);
r.Add("wield ban: no ban while the equipment list shows the weapon at the give-up", ListShowsItAtGiveUp);
r.Add("wield ban: a relog ends 'never reached your hand' bans, not 'skill too low' ones", RelogClearsNeverReached);
r.Add("wield ban: a wield that never shows in the list is still banned", NeverShownStillBanned);
r.Add("wield ban: one sighting, then three wields never seen: banned (a new run forgets the sighting)", SeenOnceThenNeverBanned);
r.Add("wield ban: a weapon in the shield slot is not a main-hand sighting, it still rests", ShieldSlotNotASighting);
r.Add("wield ban: the plugin's sampler call alone resets the tries (no heartbeat)", DirectSamplerResetsTries);
r.Add("wield ban: RynthAiPlugin's tick samples wields before the buffing hold returns", PluginSamplesBeforeBuffHold);
r.Add("wield ban: a stale try count stops the equipment list sampling", StaleCountStopsSampling);
}
private sealed class Rig
{
public readonly CombatManager C;
private readonly MethodInfo _send = typeof(CombatManager).GetMethod("MarkWieldSent", F)!;
private readonly MethodInfo _step = typeof(CombatManager).GetMethod("SwapStep", F)!;
public Rig(bool equipped = true, bool weenieErrors = false)
{
FakeHost.Reset();
FakeHost.EquippedCalls = equipped;
FakeHost.WeenieErrorCalls = weenieErrors;
FakeHost.Names[Blade] = "Test Blade";
FakeHost.Names[Wand] = "Fire Wand";
FakeHost.Names[Nodachi] = "Nodachi";
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, new[] { Blade, Wand, Nodachi });
C = new CombatManager(host, new LegacyUiSettings(), cache);
C.SetPlayerId(Player);
C.SwapTracker.ResolveMs = 0; // each look after a send resolves it (no real 2.5 s waits)
Hold(Wand, HeldSlot);
}
/// <summary>What the server says is wielded now: only <paramref name="id"/>.</summary>
public void Hold(uint id, uint slot)
{
FakeHost.Equipped.Clear();
FakeHost.Equipped[id] = slot;
EquippedState.Invalidate();
}
public void Send(uint id, uint from) => _send.Invoke(C, new object[] { unchecked((int)id), unchecked((int)from) });
public WeaponSwapTracker.Step Step(uint id, uint inHand) =>
(WeaponSwapTracker.Step)_step.Invoke(C, new object[] { unchecked((int)id), unchecked((int)inHand) })!;
public bool Banned(uint id) => C.SkillTooLowFor(unchecked((int)id));
public int Tries(uint id) => C.SwapTracker.TriesFor(unchecked((int)id));
}
private static bool NeverReachedLogged() => FakeHost.Logs.Any(l => l.Contains("never reached your hand"));
/// <summary>A weapon that lands, is swapped out for a wand by buffing, and lands again is never banned: the same sequence three times over.</summary>
private static void SeenWieldedNotBanned()
{
var rig = new Rig();
try
{
for (int i = 1; i <= 3; i++)
{
rig.Send(Blade, Wand); // combat sends the wield
rig.Hold(Blade, MeleeSlot); // the server wields it
rig.C.OnHeartbeat(); // a tick samples the equipment list
Check.Eq(rig.Tries(Blade), 0, $"wield {i}: seen in hand, its try count starts over");
rig.Hold(Wand, HeldSlot); // buffing swaps it out for the wand
rig.Step(Blade, Wand); // combat looks: the wand is in hand
}
Check.False(rig.Banned(Blade), "three wields that landed: not left out of the weapon choice");
Check.False(NeverReachedLogged(), "no 'never reached your hand' line");
}
finally { EquippedState.Invalidate(); }
}
/// <summary>The give-up itself reads the list, and a list holding the weapon is no ban.</summary>
private static void ListShowsItAtGiveUp()
{
var rig = new Rig();
try
{
for (int i = 1; i <= 3; i++)
{
rig.Send(Blade, Wand);
// No tick samples between the wields here. At the third look the server's list
// holds the weapon (the hand read combat passed in is stale).
if (i == 3) { FakeHost.Equipped[Blade] = MeleeSlot; EquippedState.Invalidate(); }
rig.Step(Blade, Wand);
}
Check.False(rig.Banned(Blade), "the list shows it wielded at the give-up: not banned");
Check.False(NeverReachedLogged(), "no 'never reached your hand' line");
// Control: no equipment list from the engine, nothing is known: no ban either way.
var blind = new Rig(equipped: false);
for (int i = 1; i <= 3; i++) { blind.Send(Blade, Wand); blind.Step(Blade, Wand); }
Check.False(blind.Banned(Blade), "no equipment list: no 'never reached' ban");
}
finally { EquippedState.Invalidate(); }
}
/// <summary>SetPlayerId (a login or relog) ends 'never reached' bans only.</summary>
private static void RelogClearsNeverReached()
{
var rig = new Rig(weenieErrors: true);
try
{
// The blade: three wields that never show in the list -> 'never reached your hand'.
for (int i = 1; i <= 3; i++) { rig.Send(Blade, Wand); rig.C.OnHeartbeat(); rig.Step(Blade, Wand); }
Check.True(rig.Banned(Blade), "setup: the blade left out as 'never reached your hand'");
// Nodachi: the server answers 'skill too low'.
rig.Send(Nodachi, Wand);
FakeHost.WeenieError(CombatManager.SkillTooLowErr, 0x00A0, Nodachi);
rig.Step(Nodachi, Wand);
Check.True(rig.Banned(Nodachi), "setup: Nodachi left out as 'skill too low'");
rig.C.SetPlayerId(Player); // the same character logs in again
Check.False(rig.Banned(Blade), "relog: the 'never reached your hand' ban is over");
Check.True(rig.Banned(Nodachi), "relog: the server's 'skill too low' ban stays");
}
finally { EquippedState.Invalidate(); }
}
/// <summary>A wield the client or server truly refuses (never in the list) still bans.</summary>
private static void NeverShownStillBanned()
{
var rig = new Rig();
try
{
for (int i = 1; i <= 3; i++)
{
rig.Send(Blade, Wand);
rig.C.OnHeartbeat(); // ticks sample: only the wand, every time
Check.Eq(rig.Tries(Blade), i, $"wield {i}: never seen, the try counts");
rig.Step(Blade, Wand);
}
Check.True(rig.Banned(Blade), "three wields never seen in the list: left out of the weapon choice");
Check.True(NeverReachedLogged(), "logged as 'never reached your hand'");
}
finally { EquippedState.Invalidate(); }
}
/// <summary>
/// A sighting counts for its own run of wields only. The weapon lands once (buffing
/// swaps it out), then stops reaching the hand: three unseen wields still end in the ban,
/// instead of three wields and an off-hand clear every 2 min forever.
/// </summary>
private static void SeenOnceThenNeverBanned()
{
var rig = new Rig();
try
{
rig.Send(Blade, Wand);
rig.Hold(Blade, MeleeSlot);
rig.C.OnHeartbeat();
Check.Eq(rig.Tries(Blade), 0, "the landed wield: seen, the count starts over");
rig.Hold(Wand, HeldSlot);
rig.Step(Blade, Wand);
for (int i = 1; i <= 3; i++)
{
rig.Send(Blade, Wand);
rig.C.OnHeartbeat(); // only the wand, every time
rig.Step(Blade, Wand);
}
Check.True(rig.Banned(Blade), "three later wields never seen: left out of the weapon choice");
Check.True(NeverReachedLogged(), "logged as 'never reached your hand'");
}
finally { EquippedState.Invalidate(); }
}
/// <summary>
/// Only main-hand slots count (as InHandWeaponId reads them). A weapon chosen while it
/// sits in the shield slot is not a landed wield: its tries count, and after three it rests
/// instead of being sent again every 2.5 s.
/// </summary>
private static void ShieldSlotNotASighting()
{
var rig = new Rig();
try
{
FakeHost.Equipped[Blade] = 0x00200000; // the shield (off-hand) slot, next to the wand
EquippedState.Invalidate();
var last = WeaponSwapTracker.Step.Swap;
for (int i = 1; i <= 3; i++)
{
rig.Send(Blade, Wand);
rig.C.OnHeartbeat();
Check.Eq(rig.Tries(Blade), i, $"wield {i}: the shield slot is no sighting, the try counts");
last = rig.Step(Blade, Wand);
}
Check.Eq(last, WeaponSwapTracker.Step.Hold, "after three tries: rested, not sent again");
Check.Eq(rig.Step(Blade, Wand), WeaponSwapTracker.Step.Hold, "still resting on the next look");
}
finally { EquippedState.Invalidate(); }
}
/// <summary>The sampler the plugin calls every tick works without combat's heartbeat.</summary>
private static void DirectSamplerResetsTries()
{
var rig = new Rig();
try
{
rig.Send(Blade, Wand);
Check.Eq(rig.Tries(Blade), 1, "setup: one wield sent");
rig.Hold(Blade, MeleeSlot);
rig.C.NoteSwapWieldsSeen();
Check.Eq(rig.Tries(Blade), 0, "the sampler alone sees it in hand: the count starts over");
}
finally { EquippedState.Invalidate(); }
}
/// <summary>
/// Source pin. The buffing hold returns from OnTick before combat's heartbeat runs,
/// so the plugin's own sampler call must come after the buff step and before that hold.
/// </summary>
private static void PluginSamplesBeforeBuffHold()
{
string? root = AppContext.BaseDirectory;
while (root != null && !Directory.Exists(Path.Combine(root, "Plugins"))) root = Path.GetDirectoryName(root);
Check.True(root != null, "found the repo (a Plugins folder above the test output)");
if (root == null) return;
string src = File.ReadAllText(Path.Combine(root, "Plugins", "RynthCore.Plugin.RynthAi", "RynthAiPlugin.cs"));
int buffStep = src.IndexOf("Guard(TickStep.BuffsAndVitals, () => _buffManager?.OnHeartbeat());", StringComparison.Ordinal);
int sample = src.IndexOf("_combatManager?.NoteSwapWieldsSeen();", StringComparison.Ordinal);
int buffHold = src.IndexOf("if (settings.IsMacroRunning && _activity == BotActivity.Buffing)", StringComparison.Ordinal);
Check.True(buffStep >= 0, "the buff step is in OnTick");
Check.True(buffHold >= 0, "the buffing hold is in OnTick");
Check.True(sample >= 0, "OnTick calls NoteSwapWieldsSeen");
Check.True(sample > buffStep && sample < buffHold, "after the buff step and before the buffing hold's return");
int holdReturn = buffHold >= 0 ? src.IndexOf("return;", buffHold, StringComparison.Ordinal) : -1;
Check.True(holdReturn > buffHold, "the buffing hold returns early (what makes the call's place matter)");
}
/// <summary>A try count left behind with no send for 2 min no longer keeps the sampler reading every tick.</summary>
private static void StaleCountStopsSampling()
{
var tr = new WeaponSwapTracker();
var t = new DateTime(2026, 11, 2, 12, 0, 0);
tr.Sent(5, 1, t);
tr.Next(5, 1, t.AddSeconds(3)); // not seen in 2.5 s: the try stays counted
Check.Eq(tr.PendingId, 0, "setup: nothing in flight");
Check.Eq(tr.TriesFor(5), 1, "setup: one try counted");
var at = typeof(WeaponSwapTracker).GetMethod("HasAttemptsAt", BindingFlags.Instance | BindingFlags.Public);
Check.True(at != null, "the tracker answers 'worth sampling?' for a given time");
if (at == null) return;
Check.True((bool)at.Invoke(tr, new object[] { t.AddSeconds(10) })!, "10 s after the send: sampled");
Check.False((bool)at.Invoke(tr, new object[] { t.AddMinutes(3) })!, "3 min after the last send: not sampled");
tr.Sent(5, 1, t.AddMinutes(3));
Check.True((bool)at.Invoke(tr, new object[] { t.AddMinutes(3) })!, "a new send: sampled again");
}
}