Snapshot for release 2026.10.21.1 (internal 32a418d)

This commit is contained in:
Tom Bohar 2026-10-21 09:35:08 -04:00
commit 6fe5630e8c
202 changed files with 43765 additions and 0 deletions

View file

@ -0,0 +1,277 @@
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The Lugian-hammer aetheria rules (Hub/IltChunkClap.cs): Infinite Leaftide aetheria goes up to
// level 10, and aetheria carrying a C, CD or CDR rating is kept unless its keep switch is off.
// The cap covers levelled Coalesced Aetheria; an unlevelled one chunks, as in ub-IT. Corrupted
// weapons follow ub-IT's hard rules and its optional keep rules, and /clap needs a colour with its
// own trinket.
internal static class AetheriaChunkTests
{
public static void Register(Runner r)
{
r.Add("aetheria: the chunk cap runs to one past ILT's level 10", Cap);
r.Add("aetheria: C / CD / CDR ratings are kept by default, each with its own switch", Ratings);
r.Add("aetheria: rating level - at or above keeps, below chunks (Coalesced too)", RatingLevel);
r.Add("aetheria: the level cap applies to levelled Coalesced Aetheria; unlevelled Coalesced chunks (ub-IT)", CoalescedCap);
r.Add("aetheria: a failed read is not 'unlevelled': unreadable pieces are kept, levelled Coalesced keeps its cap", UnreadableAetheria);
r.Add("aetheria: never-chunk, tinker / imbue, item XP, ratings and the cap each keep a piece", AetheriaRules);
r.Add("chunk: kind by class and name; chunks and powder are clap material", Kinds);
r.Add("corrupted: ub-IT hard rules (workmanship, cleave 1, or 2 on two-handed non-thrust)", CorruptedHardRules);
r.Add("corrupted: ub-IT keep rules, all off by default", CorruptedKeepRules);
r.Add("corrupted: a failed read is kept; two-handed cleave 2 chunks and other cleave 2 does not", UnreadableCorrupted);
r.Add("chunk: busy blocks peace mode, not combat with chunk-in-combat on (ub-IT v2.0.1059)", BusyGate);
r.Add("chunk: a target that leaves the pack counts as chunked; still carried after 10 s times out", WaitOutcome);
r.Add("clap: the server's WCIDs, each colour paired with its trinket, Coalesced only unrevealed level 1-3", ClapPairs);
}
/// <summary>
/// Coalesced Aetheria has its level from loot (ACECustom 1-10, ratings at 6+); it used to skip
/// the cap, so a cap of 9 still chunked a level 10 Coalesced piece.
/// </summary>
private static void CoalescedCap()
{
Check.True(IltChunkClap.UnderChunkCap(8, 9), "level 8 under a cap of 9");
Check.False(IltChunkClap.UnderChunkCap(9, 9), "level 9 is not below 9");
Check.False(IltChunkClap.UnderChunkCap(10, 9), "a level 10 Coalesced piece is kept");
Check.True(IltChunkClap.UnderChunkCap(10, 11), "11 chunks every level");
Check.False(IltChunkClap.UnderChunkCap(0, 11), "revealed aetheria with no level read: never chunked");
Check.False(IltChunkClap.UnderChunkCap(9, 9, coalesced: true), "a levelled Coalesced piece keeps the cap");
Check.True(IltChunkClap.UnderChunkCap(0, 4, coalesced: true), "an unlevelled Coalesced piece chunks (it used to be kept forever)");
Check.True(IltChunkClap.UnderChunkCap(0, 1, coalesced: true), "even with the lowest cap");
}
private static readonly IltChunkClap.AetheriaFacts PlainCoalesced = new(
Coalesced: true, MaxLevel: 0, NeverChunk: false, ItemXp: 0, Tinkers: 0, Imbue: 0, Crit: 0, CritDamage: 0, CritDamageResist: 0);
private static void AetheriaRules()
{
var g = new IltGearState();
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced), null, "a plain unlevelled Coalesced piece chunks");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 3 }), null, "level 3 under the default cap of 4");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 4 }), "level at or above the cap", "level 4 at the default cap");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { NeverChunk = true }), "never-chunk flag", "bool 9030");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Tinkers = 1 }), "tinkered or imbued", "tinkered");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Imbue = 4 }), "tinkered or imbued", "imbued");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { ItemXp = 100 }), "has item XP", "levelled by use");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Crit = 2 }), "kept for its C / CD / CDR rating", "a C 2 piece is kept by default");
g.KeepAetheriaWithCrit = false;
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Crit = 2 }), null, "C switch off: a C 2 piece chunks");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Coalesced = false }), "no level read", "revealed aetheria needs a level");
}
/// <summary>
/// The rules read 0 for "the item has none" and for "the host could not read it". An unlevelled
/// Coalesced piece is chunked (ub-IT), but only when its level was truly read as none; a piece whose
/// properties could not be read is kept, whatever the numbers say.
/// </summary>
private static void UnreadableAetheria()
{
var g = new IltGearState();
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced), null, "read as unlevelled: chunks");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Unreadable = "no appraisal" }),
"item data unreadable (no appraisal)", "the same piece with failed reads: kept");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 2, Unreadable = "no item XP" }),
"item data unreadable (no item XP)", "a levelled piece with failed reads: kept");
Check.Eq(IltChunkClap.AetheriaSkip(new IltGearState { ChunkAetheriaUnderLevel = 1 }, PlainCoalesced), null, "unlevelled chunks at the lowest cap too");
// Levelled Coalesced pieces keep the cap.
var cap9 = new IltGearState { ChunkAetheriaUnderLevel = 9 };
Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 8 }), null, "levelled 8 under a cap of 9");
Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 9 }), "level at or above the cap", "levelled 9 at a cap of 9");
Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 10 }), "level at or above the cap", "levelled 10 over a cap of 9");
Check.Eq(IltChunkClap.AetheriaSkip(new IltGearState { ChunkAetheriaUnderLevel = 11 }, PlainCoalesced with { MaxLevel = 10 }), null, "cap 11 chunks every level");
}
private static void UnreadableCorrupted()
{
var g = new IltGearState();
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Unreadable = "no appraisal" }),
"item data unreadable (no appraisal)", "failed reads: kept (they would read as a plain weapon)");
var keepCb = new IltGearState { KeepCorruptedCrushingBlow = true };
Check.Eq(IltChunkClap.CorruptedSkip(keepCb, PlainSword with { Unreadable = "float properties" }),
"item data unreadable (float properties)", "a keep rule whose float cannot be read keeps the weapon");
var twoHanded = PlainSword with { WieldSkill = 41, Cleaving = 2 };
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded), null, "two-handed cleave 2 chunks");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 2 }), "cleave over the limit", "other cleave 2 is kept");
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { WieldSkill = 0, WeaponType = 11 }), null, "WeaponType two-handed counts");
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { AttackType = 2 }), "cleave over the limit", "two-handed thrust keeps the 1 limit");
}
private static void Kinds()
{
var gem = RynthCore.Loot.AcObjectClass.Gem;
Check.Eq(IltChunkClap.KindOf(gem, "Coalesced Aetheria"), IltChunkClap.ChunkKind.Aetheria, "Coalesced");
Check.Eq(IltChunkClap.KindOf(gem, "Blue Aetheria"), IltChunkClap.ChunkKind.Aetheria, "revealed sigil");
Check.Eq(IltChunkClap.KindOf(gem, "Red Aetheria Chunk"), IltChunkClap.ChunkKind.None, "chunk");
Check.Eq(IltChunkClap.KindOf(gem, "Aetheria Powder"), IltChunkClap.ChunkKind.None, "powder");
Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MeleeWeapon, "Corrupted Greatsword"), IltChunkClap.ChunkKind.Corrupted, "melee");
Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MissileWeapon, "Corrupted Bow"), IltChunkClap.ChunkKind.Corrupted, "missile");
Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.WandStaffOrb, "Corrupted Orb"), IltChunkClap.ChunkKind.None, "casters are not chunked (ub-IT)");
Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MeleeWeapon, "Greatsword"), IltChunkClap.ChunkKind.None, "not corrupted");
}
private static readonly IltChunkClap.CorruptedFacts PlainSword = new() { Workmanship = 6, AttackType = 4, WieldSkill = 45 };
private static void CorruptedHardRules()
{
var g = new IltGearState();
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword), null, "a plain corrupted sword chunks");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Workmanship = 0 }), "no workmanship", "workmanship 0");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Tinkers = 1 }), "tinkered or imbued", "tinkered");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Imbue = 1 }), "tinkered or imbued", "imbued");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { NeverChunk = true }), "never-chunk flag", "bool 9030");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 1 }), null, "one-handed cleave 1");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 2 }), "cleave over the limit", "one-handed cleave 2");
var twoHanded = PlainSword with { WieldSkill = 41, Cleaving = 2 };
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded), null, "two-handed cleave 2 chunks (it never did before)");
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { Cleaving = 3 }), "cleave over the limit", "two-handed cleave 3");
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { AttackType = 2 }), "cleave over the limit", "a two-handed thrust weapon keeps the 1 limit");
Check.Eq(IltChunkClap.MaxChunkCleave(0, 11, 4), 2, "WeaponType TwoHanded counts too");
Check.Eq(IltChunkClap.MaxChunkCleave(45, 0, 4), 1, "one-handed");
}
private static void CorruptedKeepRules()
{
var g = new IltGearState();
var loaded = PlainSword with
{
CritFrequency = 0.1, CritMultiplier = 1.5, IgnoreArmor = 0.2, Slayer = 5, AttackType = 160,
ElementalBonus = 10, MaxDamage = 400, Spells = new[] { 2072 },
};
Check.Eq(IltChunkClap.CorruptedSkip(g, loaded), null, "every keep rule is off by default");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedCrushingBlow = true }, loaded), "kept: Crushing Blow", "Crushing Blow");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedBitingStrike = true }, loaded), "kept: Biting Strike", "Biting Strike");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedArmorCleaving = true }, loaded), "kept: Armor Cleaving", "Armor Cleaving");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedAnySlayer = true }, loaded), "kept: slayer", "slayer");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMultiStrike = true }, loaded), "kept: multi-strike", "multi-strike 160");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMultiStrike = true }, PlainSword), null, "a single slash is not multi-strike");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedElementalBonus = true }, loaded), "kept: elemental bonus", "elemental");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMaxDamageAtLeast = 400 }, loaded), "kept: max damage", "max damage at the limit");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMaxDamageAtLeast = 401 }, loaded), null, "max damage under the limit");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedAnySpell = true }, loaded), "kept: has a spell", "any spell");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedSpellIds = "100, 2072" }, loaded), "kept: listed spell", "listed spell id");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedSpellIds = "100 200" }, loaded), null, "other spell ids");
Check.Eq(IltChunkClap.ParseSpellIds("1, 2;3 x -4 0").Count, 3, "positive ids only, any separator");
Check.Eq(IltChunkClap.ParseSpellIds(null).Count, 0, "no list");
}
/// <summary>
/// Silentkelpie 2026-10-18: a Coalesced piece was chunked (Red Aetheria Chunk arrived) with no
/// result line, and it was filed as skipped after 10 s instead of counted.
/// </summary>
private static void WaitOutcome()
{
Check.Eq(IltChunkClap.WaitOutcome(500, targetStillCarried: true), IltChunkClap.ChunkWait.Waiting, "still carried, within the wait");
Check.Eq(IltChunkClap.WaitOutcome(1_100, targetStillCarried: false), IltChunkClap.ChunkWait.Gone, "gone from the pack: chunked");
Check.Eq(IltChunkClap.WaitOutcome(12_000, targetStillCarried: false), IltChunkClap.ChunkWait.Gone, "gone beats the timeout");
Check.Eq(IltChunkClap.WaitOutcome(10_000, targetStillCarried: true), IltChunkClap.ChunkWait.TimedOut, "still carried at 10 s: timed out");
}
private static void BusyGate()
{
Check.True(IltChunkClap.AllowsChunkWhileBusy(isBusy: false, isPeace: true, chunkInCombat: false), "idle in peace");
Check.False(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: true, chunkInCombat: true), "busy in peace waits");
Check.True(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: false, chunkInCombat: true), "busy swinging with chunk-in-combat");
Check.False(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: false, chunkInCombat: false), "busy in combat without it");
}
/// <summary>
/// ACECustom /clap: red (Coalesced 42636 at 1-3, chunk 310147, powder 42644) with Empyrean
/// Trinkets (34276); blue (42635, 310149, 300019) with Falatacot (34277). 42635/42636 were taken
/// for chunks, and one side alone counted, so auto-clap sent /clap with nothing to pair.
/// </summary>
private static void ClapPairs()
{
const string Co = "Coalesced Aetheria";
Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 2), IltChunkClap.ClapPart.Red, "red Coalesced level 2");
Check.Eq(IltChunkClap.ClapPartOf(42635, Co, 3), IltChunkClap.ClapPart.Blue, "blue Coalesced level 3");
Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 0), IltChunkClap.ClapPart.Red, "level not read yet: the server decides");
Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 4), IltChunkClap.ClapPart.None, "level 4 Coalesced is not clapped");
Check.Eq(IltChunkClap.ClapPartOf(42636, "Aetheria", 1), IltChunkClap.ClapPart.None, "revealed aetheria is not clapped");
Check.Eq(IltChunkClap.ClapPartOf(42637, Co, 1), IltChunkClap.ClapPart.None, "yellow has no clap use");
Check.Eq(IltChunkClap.ClapPartOf(310147, "Red Aetheria Chunk", 0), IltChunkClap.ClapPart.Red, "red chunk");
Check.Eq(IltChunkClap.ClapPartOf(310149, "Blue Aetheria Chunk", 0), IltChunkClap.ClapPart.Blue, "blue chunk");
Check.Eq(IltChunkClap.ClapPartOf(310150, "Yellow Aetheria Chunk", 0), IltChunkClap.ClapPart.None, "yellow chunk");
Check.Eq(IltChunkClap.ClapPartOf(42644, "Aetheria Powder", 0), IltChunkClap.ClapPart.Red, "red powder");
Check.Eq(IltChunkClap.ClapPartOf(300019, "Aetheria Powder", 0), IltChunkClap.ClapPart.Blue, "blue powder");
Check.Eq(IltChunkClap.ClapPartOf(34276, "Ancient Empyrean Trinket", 0), IltChunkClap.ClapPart.Empyrean, "Empyrean trinket");
Check.Eq(IltChunkClap.ClapPartOf(34277, "Ancient Falatacot Trinket", 0), IltChunkClap.ClapPart.Falatacot, "Falatacot trinket");
Check.Eq(IltChunkClap.ClapPartOf(0, "Red Aetheria Chunk", 0), IltChunkClap.ClapPart.Red, "no WCID yet: the chunk name");
Check.Eq(IltChunkClap.ClapPartOf(0, Co, 1), IltChunkClap.ClapPart.None, "no WCID yet: a Coalesced piece's colour is unknown");
Check.Eq(IltChunkClap.ClapPartOf(273, "Pyreal", 0), IltChunkClap.ClapPart.None, "anything else");
var R = IltChunkClap.ClapPart.Red; var B = IltChunkClap.ClapPart.Blue;
var E = IltChunkClap.ClapPart.Empyrean; var F = IltChunkClap.ClapPart.Falatacot;
Check.True(IltChunkClap.CanClap(new[] { R, E }), "red + Empyrean");
Check.True(IltChunkClap.CanClap(new[] { B, F }), "blue + Falatacot");
Check.False(IltChunkClap.CanClap(new[] { R, F }), "red needs Empyrean, not Falatacot");
Check.False(IltChunkClap.CanClap(new[] { B, E }), "blue needs Falatacot, not Empyrean");
Check.False(IltChunkClap.CanClap(new[] { E, F }), "trinkets alone");
Check.False(IltChunkClap.CanClap(new[] { R, B }), "aetheria alone");
Check.False(IltChunkClap.CanClap(System.Array.Empty<IltChunkClap.ClapPart>()), "nothing carried");
}
private static void Cap()
{
Check.Eq(IltInventory.AetheriaMaxLevel, 10, "ILT max aetheria level");
Check.Eq(IltChunkClap.ClampUnderLevel(0), 1, "below 1 clamps to 1");
Check.Eq(IltChunkClap.ClampUnderLevel(7), 7, "7 (retail clamp was 6) is allowed");
Check.Eq(IltChunkClap.ClampUnderLevel(11), 11, "11 chunks every level");
Check.Eq(IltChunkClap.ClampUnderLevel(50), 11, "above 11 clamps to 11");
Check.Eq(new IltGearState().ChunkAetheriaUnderLevel, 4, "the default cap is unchanged");
}
private static void Ratings()
{
var g = new IltGearState();
Check.True(g.KeepAetheriaWithCrit && g.KeepAetheriaWithCritDamage && g.KeepAetheriaWithCritDamageResist, "all keep switches on by default");
Check.False(IltChunkClap.KeptForRatings(g, 0, 0, 0), "no rating: chunkable");
Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C kept");
Check.True(IltChunkClap.KeptForRatings(g, 0, 1, 0), "CD kept");
Check.True(IltChunkClap.KeptForRatings(g, 0, 0, 3), "CDR kept");
g.KeepAetheriaWithCrit = false;
Check.False(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C chunkable with its switch off");
Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 3), "CDR still keeps a C+CDR sigil");
g.KeepAetheriaWithCritDamage = false;
g.KeepAetheriaWithCritDamageResist = false;
Check.False(IltChunkClap.KeptForRatings(g, 3, 3, 3), "every switch off: ratings don't protect");
}
/// <summary>
/// The rating level: a C / CD / CDR rating at or above it keeps the piece, a lower one chunks
/// (if the level cap allows). The default of 1 keeps any rating, as before.
/// </summary>
private static void RatingLevel()
{
var g = new IltGearState();
Check.Eq(g.KeepAetheriaRatingAtLeast, 1, "default: any rating keeps");
Check.True(IltChunkClap.KeptForRatings(g, 1, 0, 0), "C 1 kept at the default");
g.KeepAetheriaRatingAtLeast = 2;
Check.False(IltChunkClap.KeptForRatings(g, 1, 0, 0), "C 1 below level 2: chunks");
Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C 2 at level 2: kept");
Check.True(IltChunkClap.KeptForRatings(g, 3, 0, 0), "C 3 above level 2: kept");
Check.True(IltChunkClap.KeptForRatings(g, 1, 0, 2), "CDR 2 keeps a C 1 + CDR 2 piece");
Check.False(IltChunkClap.KeptForRatings(g, 1, 1, 1), "every rating below the level: chunks");
g.KeepAetheriaWithCrit = false;
Check.False(IltChunkClap.KeptForRatings(g, 5, 0, 0), "a switch that is off ignores the level");
Check.Eq(IltChunkClap.ClampRatingLevel(0), 1, "below 1 clamps to 1");
Check.Eq(IltChunkClap.ClampRatingLevel(99), IltChunkClap.MaxRatingLevel, "clamped to the maximum");
var coalescedC1 = PlainCoalesced with { Crit = 1 };
var level2 = new IltGearState { KeepAetheriaRatingAtLeast = 2 };
Check.Eq(IltChunkClap.AetheriaSkip(level2, coalescedC1), null, "an unlevelled C 1 Coalesced piece chunks at rating level 2");
Check.Eq(IltChunkClap.AetheriaSkip(level2, PlainCoalesced with { Crit = 2 }), "kept for its C / CD / CDR rating", "a C 2 one is kept");
Check.Eq(IltChunkClap.AetheriaSkip(level2, coalescedC1 with { MaxLevel = 6 }), "level at or above the cap",
"a low rating does not override the level cap");
}
}

View file

@ -0,0 +1,543 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// Server Features gate + the infinite-attribute raiser (2026-10-06; RynthAi's ILT Hub, in RynthILT
// since 2026-10-13). The gate decides from RynthILT's server list (world-name patterns) and the
// character's "Treat this world as ILT" whether the ILT features ask the server at all; the raiser reads "/xp all" costs and spends unassigned XP with "/attr <abbr> 1"
// on the ticked stats, in the chosen order, never below the reserve.
internal static class AttributeRaiserTests
{
private const uint Player = 0x50000C01;
public static void Register(Runner r)
{
r.Add("server features: name patterns (exact, wildcards, case)", Patterns);
r.Add("server features: list parsing and the override", ListAndOverride);
r.Add("attr raiser: pick by mode (priority, round robin, cheapest)", PickModes);
r.Add("attr raiser: pick respects ticks, reserve and unknown costs", PickLimits);
r.Add("attr raiser: order repair and stat names from server lines", OrderAndNames);
r.Add("attr raiser: a run reads costs, raises in order, stops when nothing is affordable", FullRun);
r.Add("attr raiser: off when the world is not in the Server Features list", GatedOff);
r.Add("attr raiser: safety (stale costs, another stat's reply, gate off mid-run, held off)", Safety);
r.Add("attr raiser: by-hand +1 / +10 priced like UB, refused when unaffordable, costs read on tab open", ByHandPriced);
r.Add("aug planner: /aug pulled on tab open, totals, reset targets, copy texts", AugPlanner);
r.Add("aug refresh: banner alone does not end /aug; Current updates from level lines", AugRefreshWaitsForLevelLines);
r.Add("aug refresh: a probe that left Current empty retries /aug once; a click during the probe runs after it", AugProbeRetry);
r.Add("aug lines: separators in the level (4,300 / 4.300 / 4 300 / 4'300) and trailing notes read", AugLineValues);
r.Add("aug costs: UB's ILT model (tier starts at its S level) in closed form", AugCostModel);
r.Add("aug costs: per-server multipliers and rules, saved and reset", AugCostSettings);
}
/// <summary>UB Augs.cs GetCumulativeCost difference, level by level (the reference the closed form must match).</summary>
private static decimal UbLoop(IltAugCostRow r, double[] m, int cur, int tgt)
{
decimal step = r.Base * (decimal)r.LinearPercent / 100m, total = 0;
for (int i = cur + 1; i <= tgt; i++)
{
decimal b = r.Base + (i - 1) * step;
double mult = i < r.S1 ? m[0] : i < r.S2 ? m[1] : i < r.S3 ? m[2] : i < r.S4 ? m[3] : m[4];
total += b * (decimal)mult;
}
return total;
}
private static void AugCostModel()
{
var rows = IltAugCosts.DefaultRows().ToDictionary(x => x.Key);
var m = IltAugCosts.DefaultMultipliers;
var creature = rows["creature"];
Check.Eq(IltAugCosts.LumCost(creature, m, 2748, 2749), 750_000m + 2748 * 975_000m, "level 2749 (S1 - 1) is the last x1 level");
Check.Eq(IltAugCosts.LumCost(creature, m, 2749, 2750), (750_000m + 2749 * 975_000m) * 4, "level 2750 (S1) is the first x4 level");
Check.Eq(rows["specialization"].S2, 2500, "Specialization uses UB's 1750/2500/3000/3750");
Check.Eq(rows["summon"].S1, 1750, "Summon uses UB's 1750/2500/3000/3750");
Check.Eq(creature.Cap, 0, "no target cap by default (UB has none)");
foreach (var (key, cur, tgt) in new[] { ("creature", 0, 6000), ("item", 1200, 3600), ("specialization", 1700, 3800),
("duration", 999, 1001), ("summon", 3749, 3751), ("life", 10, 10) })
Check.Eq(IltAugCosts.LumCost(rows[key], m, cur, tgt), UbLoop(rows[key], m, cur, tgt), $"{key} {cur}->{tgt} matches UB's loop");
var odd = new double[] { 1.5, 2, 3.25, 10, 0 };
Check.Eq(IltAugCosts.LumCost(rows["war"], odd, 1500, 4000), UbLoop(rows["war"], odd, 1500, 4000), "custom multipliers match the loop");
Check.Eq(IltAugCosts.LumCost(creature, m, 50, 40), 0m, "a target below current costs nothing");
Check.True(IltAugCosts.LumCost(creature, m, 0, IltAugCosts.NoCapLimit) > 0, "the largest uncapped target is priced without overflow");
}
private static void AugCostSettings()
{
string file = IltAugCosts.FilePath;
if (File.Exists(file)) File.Delete(file);
var settings = new IltSettings();
var hub = NewHub("InfiniteLeaftide", settings, "aug-costs", out _);
var prog = hub.Progression;
prog.ApplyAugLines(new List<string> { "War: 1700" });
hub.State.Character.AugTargets["war"] = 1800;
string Snapshot()
{
var sb = new System.Text.StringBuilder();
prog.AppendSnapshotJson(sb);
return "{" + sb + "}";
}
System.Text.Json.JsonElement Aug(string json) => System.Text.Json.JsonDocument.Parse(json).RootElement.GetProperty("aug");
var before = Aug(Snapshot());
Check.False(before.GetProperty("cfg").GetProperty("custom").GetBoolean(), "a world starts on the defaults");
Check.Eq(before.GetProperty("cfg").GetProperty("mults").GetArrayLength(), 5, "five tier multipliers in the snapshot");
string lumBefore = before.GetProperty("totLum").GetString() ?? "";
prog.HandleRemote(new[] { "augmult", "1", "2" });
var after = Aug(Snapshot());
Check.True(after.GetProperty("cfg").GetProperty("custom").GetBoolean(), "an edit gives the world its own rules");
Check.Eq(after.GetProperty("cfg").GetProperty("mults")[1].GetDouble(), 2.0, "multiplier saved");
Check.True((after.GetProperty("totLum").GetString() ?? "") != lumBefore, "the plan re-prices with the new multiplier");
prog.HandleRemote(new[] { "augcfg", "war", "s1", "1800" });
prog.HandleRemote(new[] { "augcfg", "war", "base", "1m" });
prog.HandleRemote(new[] { "augcfg", "war", "s2", "100" });
var war = prog.AugCosts.For("InfiniteLeaftide").Augs.First(x => x.Key == "war");
Check.Eq(war.S1, 1800, "S1 edited");
Check.Eq(war.Base, 1_000_000L, "base accepts k/m/b suffixes");
Check.Eq(war.S2, 1800, "S2 can't go below S1");
Check.Eq(prog.AugCosts.For("Aelrynth").Multipliers[1], 4.0, "another world keeps the defaults");
var reloaded = new IltAugCosts();
Check.Eq(reloaded.For("infiniteleaftide").Multipliers[1], 2.0, "rules are saved per world (name ignores case)");
prog.HandleRemote(new[] { "augcfgreset" });
Check.False(prog.AugCosts.IsCustom("InfiniteLeaftide"), "reset drops the world's rules");
Check.Eq(new IltAugCosts().For("InfiniteLeaftide").Multipliers[1], 4.0, "and the reset is saved");
}
private static void ByHandPriced()
{
Check.Eq(IltAttributeRaiser.ProjectCost(1_000, 1), 1_000L, "one level costs the reported cost");
// 1000 * (1.077^10 - 1) / 0.077 = 14,281.7 (UB's EstimateMultiLevelCost).
Check.Eq(IltAttributeRaiser.ProjectCost(1_000, 10), 14_281L, "ten levels grow 7.7% each");
Check.Eq(IltAttributeRaiser.ProjectCost(0, 10), 0L, "unknown cost projects nothing");
Check.Eq(IltAttributeRaiser.ProjectCost(long.MaxValue / 2, 10), long.MaxValue, "saturates instead of overflowing");
var settings = new IltSettings();
var hub = NewHub("InfiniteLeaftide", settings, "attr-byhand", out _);
var raiser = hub.Progression.Attributes;
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 5_000;
// Levels already known (as after the login probe), so the tab doesn't queue /aug ahead of /xp all.
hub.Progression.ApplyAugLines(new List<string> { "Creature: 1" });
// Opening the tab (a snapshot poll) reads the costs once per login.
var sb = new System.Text.StringBuilder();
hub.Progression.AppendSnapshotJson(sb);
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "the first snapshot reads the costs");
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 1,000",
"[XP] Your XP cost for next 1 Strength level is: 4,000");
TickUntil(hub, () => false, 400);
int reads = FakeHost.ChatCommands.Count(x => x == "/xp all");
hub.Progression.AppendSnapshotJson(new System.Text.StringBuilder());
TickUntil(hub, () => false, 400);
Check.Eq(FakeHost.ChatCommands.Count(x => x == "/xp all"), reads, "later snapshots don't read again");
sb.Clear();
raiser.AppendJson(sb);
string json = sb.ToString();
System.Text.Json.JsonDocument.Parse("{" + json + "}").Dispose();
Check.True(json.Contains("\"key\":\"coo\"") && json.Contains("\"afford1\":true") && json.Contains("\"cost10\":\"~14.3K\""),
$"Coordination: +1 affordable, +10 projected (got {json})");
Check.True(json.Contains("\"updated\":\"") && !json.Contains("\"updated\":\"-\""), "the last-updated time is set");
// +10 Coordination (~14.3K of 5K) is refused; +1 Strength (4K of 5K) goes out.
raiser.RaiseManual("coo", 10);
var status = new System.Text.StringBuilder();
raiser.AppendJson(status);
Check.True(status.ToString().Contains("Not enough unassigned XP"), "an unaffordable +10 is refused with the reason");
raiser.RaiseManual("str", 1);
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr str 1")), "an affordable +1 is sent");
Check.False(FakeHost.ChatCommands.Contains("/attr coo 10"), "the refused +10 was never sent");
}
private static void AugPlanner()
{
var settings = new IltSettings();
var hub = NewHub("InfiniteLeaftide", settings, "aug-planner", out _);
var prog = hub.Progression;
prog.AppendSnapshotJson(new System.Text.StringBuilder());
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "opening the tab pulls /aug once");
prog.ApplyAugLines(new List<string> { "Creature: 100", "Specialize: 2", "Summon: 0" });
prog.HandleRemote(new[] { "augtarget", "creature", "110" });
var sb = new System.Text.StringBuilder();
prog.AppendSnapshotJson(sb);
string json = sb.ToString();
using (var doc = System.Text.Json.JsonDocument.Parse("{" + json + "}"))
{
var aug = doc.RootElement.GetProperty("aug");
Check.Eq(aug.GetProperty("totCur").GetInt64(), 102L, "totals: current");
Check.Eq(aug.GetProperty("totTgt").GetInt64(), 112L, "totals: target");
Check.Eq(aug.GetProperty("totInc").GetInt64(), 10L, "totals: increase");
Check.Eq(aug.GetProperty("totCoins").GetInt64(), 30L, "Creature costs 3 coins a level");
var creature = aug.GetProperty("rows").EnumerateArray().First(x => x.GetProperty("key").GetString() == "creature");
Check.Eq(creature.GetProperty("inc").GetInt32(), 10, "row: increase");
string discord = aug.GetProperty("copyDiscord").GetString() ?? "";
Check.True(discord.StartsWith("```", StringComparison.Ordinal) && discord.Contains("TOTALS:") && discord.Contains("Creature"),
"Discord copy is a code-block table with totals");
Check.True(discord.All(ch => ch < 128), "copy text is ASCII (the engine reads the snapshot as ANSI)");
string ingame = aug.GetProperty("copyIngame").GetString() ?? "";
Check.True(ingame.Contains("Crit: 100") && ingame.Contains("Spec: 2") && !ingame.Contains("Sum:"),
$"in-game copy lists current levels with short names (got '{ingame}')");
}
prog.HandleRemote(new[] { "augreset" });
Check.Eq(hub.State.Character.AugTargets["creature"], 100, "reset targets: back to current");
Check.Eq(hub.State.Character.AugTargets["summon"], 0, "reset targets: unloaded augs go to 0");
Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 1, "levels loaded: no second automatic /aug");
}
/// <summary>
/// Refresh current must not finish on the /aug banner alone (chat-hold lag used to leave Current at 0).
/// </summary>
private static void AugRefreshWaitsForLevelLines()
{
var settings = new IltSettings();
var hub = NewHub("InfiniteLeaftide", settings, "aug-refresh-idle", out _);
var prog = hub.Progression;
// Seed so EnsureAugs does not queue its own /aug ahead of our Refresh.
prog.ApplyAugLines(new List<string> { "Creature: 1" });
prog.HandleRemote(new[] { "augload" });
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "Refresh current sends /aug");
Reply(hub, "---------------------------", "Advanced Augmentation Levels:");
// Longer than IdleEndMs (2s): without ArmsIdle this used to ApplyAugLines([]) and clear the status.
var until = DateTime.UtcNow.AddMilliseconds(2500);
while (DateTime.UtcNow < until) { hub.Tick(); Thread.Sleep(25); }
Check.True(FakeHost.ChatCommands.Count(x => x == "/aug") == 1, "still waiting on the same /aug (banner did not end it)");
Reply(hub, "Creature:4,300", "Item:100", "Specialize: 2");
Check.True(TickUntil(hub, () =>
{
var sb = new System.Text.StringBuilder();
prog.AppendSnapshotJson(sb);
return sb.ToString().Contains("\"cur\":4300", StringComparison.Ordinal);
}), "Current updates once Creature:/Item: lines arrive");
}
// Silentkelpie (PR #12): the login probe could end on the banner alone (chat-hold backlog) and leave
// Current empty with nothing to retry it; a Refresh current click during the probe was dropped.
private static void AugProbeRetry()
{
var hub = NewHub("InfiniteLeaftide", new IltSettings(), "aug-probe-retry", out _);
var prog = hub.Progression;
// Probe reply: the banner and no level lines. The tap runs ApplyAugLines then AfterExternalAugCapture.
prog.ApplyAugLines(new List<string> { "---------------------------", "Advanced Augmentation Levels:" });
prog.AfterExternalAugCapture();
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "Current still empty: /aug is sent again");
prog.AfterExternalAugCapture(); // the retry is in flight, and was the one retry
prog.ApplyAugLines(new List<string> { "Advanced Augmentation Levels:" });
prog.AfterExternalAugCapture();
for (int i = 0; i < 20; i++) { hub.Tick(); Thread.Sleep(25); }
Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 1, "only one retry");
Reply(hub, "Creature:4,300", "Item:100");
Check.True(TickUntil(hub, () =>
{
var sb = new System.Text.StringBuilder();
prog.AppendSnapshotJson(sb);
return sb.ToString().Contains("\"cur\":4300", StringComparison.Ordinal);
}), "the retry's level lines fill Current");
// A probe with levels needs no retry.
var hub2 = NewHub("InfiniteLeaftide", new IltSettings(), "aug-probe-ok", out _);
hub2.Progression.ApplyAugLines(new List<string> { "Creature: 12" });
hub2.Progression.AfterExternalAugCapture();
for (int i = 0; i < 20; i++) { hub2.Tick(); Thread.Sleep(25); }
Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 0, "levels present: no retry");
}
private static void AugLineValues()
{
Check.True(IltParse.AugLine.IsMatch("Creature:4,300") && IltParse.AugLine.IsMatch("Creature: 4.300")
&& IltParse.AugLine.IsMatch("Creature: 4 300") && IltParse.AugLine.IsMatch("Creature: 4'300"), "the regex matches each grouping");
Check.False(IltParse.AugLine.IsMatch("Creature: none") || IltParse.AugLine.IsMatch("Advanced Augmentation Levels:"), "and not a line with no number");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature:4,300").Groups[2].Value), 4300L, "comma");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4.300").Groups[2].Value), 4300L, "period");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4 300").Groups[2].Value), 4300L, "space");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4'300").Groups[2].Value), 4300L, "apostrophe");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 1,234,567").Groups[2].Value), 1234567L, "two groups");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Duration: 5 (adds 3)").Groups[2].Value), 5L, "a trailing note");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Specialize: 2").Groups[2].Value), 2L, "plain");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Item: 2750").Groups[2].Value), 2750L, "no separator");
Check.Eq(IltParse.ParseAugValue(""), 0L, "empty");
var hub = NewHub("InfiniteLeaftide", new IltSettings(), "aug-values", out _);
hub.Progression.ApplyAugLines(new List<string> { "Creature: 2 750", "Item: 1.200", "Life: 300" });
var sb = new System.Text.StringBuilder();
hub.Progression.AppendSnapshotJson(sb);
string snap = sb.ToString();
Check.True(snap.Contains("\"cur\":2750", StringComparison.Ordinal) && snap.Contains("\"cur\":1200", StringComparison.Ordinal)
&& snap.Contains("\"cur\":300", StringComparison.Ordinal), "the planner takes the grouped levels whole");
}
private static void Patterns()
{
Check.True(ServerFeatureGate.Matches("InfiniteLeaftide", "InfiniteLeaftide"), "exact");
Check.True(ServerFeatureGate.Matches("infiniteleaftide", "InfiniteLeaftide"), "exact ignores case");
Check.False(ServerFeatureGate.Matches("InfiniteLeaftide2", "InfiniteLeaftide"), "exact means the whole name");
Check.True(ServerFeatureGate.Matches("Leaftide Test", "*Leaftide*"), "contains");
Check.True(ServerFeatureGate.Matches("MyLeaftide", "*tide"), "ends with");
Check.True(ServerFeatureGate.Matches("Leaftide-PTR", "Leaf*"), "starts with");
Check.True(ServerFeatureGate.Matches("Aelrynth Infinite", "Ael*Inf*"), "two wildcards");
Check.False(ServerFeatureGate.Matches("Aelrynth", "*Leaftide*"), "no match");
Check.False(ServerFeatureGate.Matches("ab", "a*bb"), "the end part must fit after the start");
Check.True(ServerFeatureGate.NameMatches("Aelrynth", new[] { "", "InfiniteLeaftide", "aelrynth" }, out string m) && m == "aelrynth",
"NameMatches reports the pattern that matched");
Check.False(ServerFeatureGate.NameMatches("", ServerFeatureGate.DefaultServerNames, out _), "an unknown world never matches");
}
private static void ListAndOverride()
{
var list = ServerFeatureGate.ParseList(" InfiniteLeaftide , *Leaftide*;Aelrynth,,aelrynth ");
Check.Eq(string.Join("|", list), "InfiniteLeaftide|*Leaftide*|Aelrynth", "trimmed, split on , and ;, de-duplicated ignoring case");
Check.Eq(ServerFeatureGate.FormatList(list), "InfiniteLeaftide, *Leaftide*, Aelrynth", "formatted back for the text box");
var s = new IltSettings();
Check.True(s.ServerNames.Contains("InfiniteLeaftide"), "fresh settings start with the defaults");
Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s, forceOn: false), "the default list covers InfiniteLeaftide");
Check.False(ServerFeatureGate.IsEnabled("Aelrynth", s, forceOn: false), "another world is off by default");
Check.True(ServerFeatureGate.IsEnabled("Aelrynth", s, forceOn: true), "the character's override turns it on anywhere");
s.ServerNames = new List<string> { "Aelrynth" };
Check.True(ServerFeatureGate.IsEnabled("aelrynth", s, forceOn: false), "a world added to the list is on");
Check.False(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s, forceOn: false), "a world removed from the list is off");
Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", null, forceOn: false), "no settings yet: the defaults apply");
s.ServerNames = new List<string>();
Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s, forceOn: false), "an emptied list falls back to the defaults");
}
private static readonly string[] Order = { "coo", "qui", "str", "end", "foc", "sel", "hea", "sta", "man" };
private static void PickModes()
{
var cost = new Dictionary<string, long> { ["coo"] = 500, ["qui"] = 300, ["str"] = 100 };
var ticked = new HashSet<string> { "coo", "qui", "str" };
int rr = 0;
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, ticked, cost, 1000, ref rr), "coo",
"priority: the first affordable stat in the order");
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, ticked, cost, 400, ref rr), "qui",
"priority: skips a stat it can't afford");
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, ticked, cost, 1000, ref rr), "str",
"cheapest: the lowest next-level cost");
var tie = new Dictionary<string, long> { ["coo"] = 100, ["str"] = 100 };
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, ticked, tie, 1000, ref rr), "coo",
"cheapest: a tie goes to the higher-priority stat");
rr = 0;
var picks = new List<string?>();
for (int i = 0; i < 4; i++) picks.Add(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 1000, ref rr));
Check.Eq(string.Join(",", picks), "coo,qui,str,coo", "round robin: one each in order, then around again");
rr = 0;
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 400, ref rr), "qui",
"round robin: an unaffordable stat is passed over");
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 400, ref rr), "str",
"round robin: carries on from the last pick");
}
private static void PickLimits()
{
var cost = new Dictionary<string, long> { ["coo"] = 500, ["qui"] = 300 };
int rr = 0;
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string>(), cost, 10_000, ref rr),
"nothing ticked: nothing raised");
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string> { "qui" }, cost, 10_000, ref rr), "qui",
"an unticked stat is never spent on, even at the top of the order");
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string> { "coo", "qui" }, cost, 0, ref rr),
"no budget (XP at or below the reserve): nothing raised");
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string> { "str" }, cost, 10_000, ref rr),
"a stat whose cost wasn't read is not raised blind");
var zero = new Dictionary<string, long> { ["coo"] = 0 };
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, new HashSet<string> { "coo" }, zero, 10_000, ref rr),
"a zero cost (unparsed) is not raised");
}
private static void OrderAndNames()
{
var repaired = IltAttributeRaiser.RepairOrder(new List<string> { "sel", "bogus", "Self", "Strength", "hea" });
Check.Eq(string.Join(",", repaired), "sel,str,hea,coo,qui,end,foc,sta,man",
"saved order kept, duplicates/junk dropped, missing stats appended in the default order");
Check.Eq(IltAttributeRaiser.RepairOrder(null).Count, 9, "a missing order becomes the default");
Check.Eq(string.Join(",", IltAttributeRaiser.RepairSelection(new List<string> { "Coordination", "coo", "x" })), "coo",
"selection: names map to abbreviations, duplicates and junk dropped");
Check.Eq(IltAttributeRaiser.Find("MaxHealth")?.Abbr, "hea", "cost line 'MaxHealth'");
Check.Eq(IltAttributeRaiser.Find("Maximum Stamina")?.Abbr, "sta", "'Maximum Stamina'");
Check.Eq(IltAttributeRaiser.Find("Self")?.Abbr, "sel", "Self");
Check.Eq(IltAttributeRaiser.Find("qui")?.Abbr, "qui", "abbreviation");
Check.Null(IltAttributeRaiser.Find("Luck"), "unknown names are rejected");
var cost = IltParse.XpCost.Match("[XP] Your XP cost for next 1 Coordination level is: 12,345,678");
Check.True(cost.Success && cost.Groups[1].Value == "Coordination" && IltParse.ParseLeadingLong(cost.Groups[2].Value) == 12_345_678,
"the /xp all cost line parses");
var raised = IltParse.AttrRaised.Match("[ATTR] Quickness attribute raised by 1, costing 9,876!");
Check.True(raised.Success && raised.Groups[1].Value == "Quickness" && raised.Groups[2].Value == "1"
&& IltParse.ParseLeadingLong(raised.Groups[3].Value) == 9876, "the /attr success line parses");
}
// ── The loop on the fake host ─────────────────────────────────────────────
private static IltHubController NewHub(string world, IltSettings settings, string folder, out RynthCoreHost host)
{
FakeHost.Reset();
FakeHost.WorldName = world;
host = FakeHost.Create(Player);
string dir = Path.Combine(Program.TempRoot, folder);
Directory.CreateDirectory(dir);
// No RynthAi here (the fake host has no GetPluginInterface): RynthILT runs on its own.
return new IltHubController(host, dir, settings, new RynthAiClient(host));
}
/// <summary>Ticks the hub until <paramref name="done"/> or the timeout (the chat queue spaces sends by real time).</summary>
private static bool TickUntil(IltHubController hub, Func<bool> done, int timeoutMs = 6000)
{
var until = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (DateTime.UtcNow < until)
{
hub.Tick();
if (done()) return true;
Thread.Sleep(25);
}
return false;
}
private static void Reply(IltHubController hub, params string[] lines)
{
foreach (string l in lines) hub.OnChat(l);
}
private static void FullRun()
{
var settings = new IltSettings();
var hub = NewHub("InfiniteLeaftide", settings, "attr-run", out _);
var c = hub.State.Character;
c.AttrRaiseStats = new List<string> { "coo", "qui" };
c.AttrRaiseMode = (int)IltAttributeRaiser.Mode.Priority;
c.AttrKeepXp = 200;
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 2_500;
var raiser = hub.Progression.Attributes;
Check.Null(raiser.Blocker(), "an ILT world with /xp not reported off: the raiser can run");
raiser.Start(auto: false);
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "a run starts by reading the costs");
Reply(hub, "[XP] Your XP cost for next 1 Strength level is: 50",
"[XP] Your XP cost for next 1 Coordination level is: 1,000",
"[XP] Your XP cost for next 1 Quickness level is: 1,200");
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr coo 1")),
"priority: Coordination first (Strength is cheaper but not ticked)");
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 1_500;
Reply(hub, "[ATTR] Coordination attribute raised by 1, costing 1,000!");
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Count(x => x == "/xp all") >= 2), "costs are read again after each raise");
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 2,000",
"[XP] Your XP cost for next 1 Quickness level is: 1,200");
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr qui 1")),
"Coordination now costs more than the spendable 1,300: Quickness next");
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 300;
Reply(hub, "[ATTR] Quickness attribute raised by 1, costing 1,200!");
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Count(x => x == "/xp all") >= 3), "third cost read");
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 2,000",
"[XP] Your XP cost for next 1 Quickness level is: 1,500");
Check.True(TickUntil(hub, () => !raiser.Running), "nothing affordable above the reserve: the run ends");
Check.Eq(FakeHost.ChatCommands.Count(x => x.StartsWith("/attr", StringComparison.Ordinal)), 2, "exactly two raises sent");
string summary = FakeHost.Chat.LastOrDefault(x => x.Contains("Attribute raise")) ?? "";
Check.True(summary.Contains("Coordination +1") && summary.Contains("Quickness +1") && summary.Contains("2.2K"),
$"the run reports what it raised and spent (got '{summary}')");
var sb = new System.Text.StringBuilder();
raiser.AppendJson(sb);
string json = sb.ToString();
Check.True(json.StartsWith("\"attr\":{\"off\":false", StringComparison.Ordinal), "the Progression snapshot carries the raiser");
Check.True(json.Contains("\"key\":\"coo\"") && json.Contains("\"cost\":\"2.0K\""), "rows carry the last read costs");
System.Text.Json.JsonDocument.Parse("{" + json + "}").Dispose(); // throws if the JSON is malformed
// Panel commands: order, ticks, mode, reserve, a manual +10.
raiser.HandleRemote("attrmove", new[] { "attrmove", "qui", "up" });
Check.Eq(c.AttrOrder[0], "qui", "attrmove up");
raiser.HandleRemote("attron", new[] { "attron", "str", "on" });
Check.True(c.AttrRaiseStats.Contains("str"), "attron");
raiser.HandleRemote("attrmode", new[] { "attrmode", "2" });
Check.Eq(c.AttrRaiseMode, 2, "attrmode");
raiser.HandleRemote("attrkeep", new[] { "attrkeep", "1.5b" });
Check.Eq(c.AttrKeepXp, 1_500_000_000L, "attrkeep takes k/m/b suffixes");
raiser.HandleRemote("attrraise", new[] { "attrraise", "foc", "10" });
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr foc 10")), "a manual +10 sends /attr foc 10");
}
private static void Safety()
{
var settings = new IltSettings();
var hub = NewHub("InfiniteLeaftide", settings, "attr-safety", out _);
var c = hub.State.Character;
var raiser = hub.Progression.Attributes;
c.AttrRaiseStats = new List<string> { "coo", "qui" };
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 10_000;
// A cost seen earlier (passively, here by a hand-typed /xp all) is not trusted by a run:
// only the costs in the run's own read count.
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 100");
raiser.Start(auto: false);
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "run reads costs");
Reply(hub, "[XP] Your XP cost for next 1 Quickness level is: 500"); // Coordination missing this time
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Any(x => x.StartsWith("/attr", StringComparison.Ordinal))), "a raise is sent");
Check.Eq(FakeHost.ChatCommands.First(x => x.StartsWith("/attr", StringComparison.Ordinal)), "/attr qui 1",
"Coordination's older cost is not used when this read left it out");
// A reply about another stat (some other /attr sender) is not taken as our success.
Reply(hub, "[ATTR] Strength attribute raised by 1, costing 50!");
Check.True(TickUntil(hub, () => !raiser.Running), "a reply about another stat ends the run");
Check.Eq(FakeHost.ChatCommands.Count(x => x.StartsWith("/attr", StringComparison.Ordinal)), 1, "and nothing more is raised");
Check.False(FakeHost.Chat.Any(x => x.Contains("Attribute raise")), "and no raise is reported");
// The world leaves Server Features mid-run: the next step stops.
FakeHost.ChatCommands.Clear();
raiser.Start(auto: false);
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "second run reads costs");
settings.ServerNames = new List<string> { "SomewhereElse" };
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 100");
Check.True(TickUntil(hub, () => !raiser.Running), "the run stops once the world is off");
Check.False(FakeHost.ChatCommands.Any(x => x.StartsWith("/attr", StringComparison.Ordinal)), "no raise after the gate closed");
settings.ServerNames = new List<string>(ServerFeatureGate.DefaultServerNames);
// Another XP spender running: neither Raise now nor +N starts.
bool spending = true;
raiser.HoldOff = () => spending;
FakeHost.ChatCommands.Clear();
raiser.Start(auto: false);
raiser.RaiseManual("coo", 1);
TickUntil(hub, () => false, 600);
Check.False(raiser.Running, "held off: Raise now doesn't start");
Check.False(FakeHost.ChatCommands.Any(), "held off: nothing is sent");
}
private static void GatedOff()
{
var settings = new IltSettings();
var hub = NewHub("Aelrynth", settings, "attr-gated", out _);
var raiser = hub.Progression.Attributes;
hub.State.Character.AttrRaiseStats = new List<string> { "coo" };
Check.NotNull(raiser.Blocker(), "a world not in the list: blocked");
raiser.Start(auto: false);
TickUntil(hub, () => false, 600);
Check.False(FakeHost.ChatCommands.Any(), "nothing is sent off a feature world");
settings.ServerNames.Add("Aelrynth");
Check.Null(raiser.Blocker(), "adding the world to the server list unblocks it");
settings.ServerNames.Remove("Aelrynth");
hub.State.ForceLeaftideFeatures = true;
Check.Null(raiser.Blocker(), "so does the character's override");
}
}

View file

@ -0,0 +1,146 @@
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// Banking tab (IltBankCommands): the deposit / withdraw commands match ACECustom's /bank handler
// (upstream 2026-10-11), and only the bank's own reply lines count as a deposit / withdraw result.
internal static class BankCommandTests
{
public static void Register(Runner r)
{
r.Add("bank: deposit commands (everything, one kind, luminance tokens)", Deposits);
r.Add("bank: withdraw commands, trade notes by denomination and count", Withdrawals);
r.Add("bank: withdraw input is checked before anything is sent", WithdrawRefusals);
r.Add("bank: reply lines are recognised, balance and chat lines are not", Replies);
r.Add("bank: one item table matches ACECustom's handler (deposit / withdraw / transfer)", ItemTable);
r.Add("bank: transfer commands, trade notes by denomination, quoted names", Transfers);
r.Add("bank: transfer replies (notes' equivalent, bound prestige coins) are recognised", TransferReplies);
r.Add("bank: only the balance dump is backstop-eaten, and only just after a quiet refresh", LeakedDump);
}
private static int TransferIndex(string code) =>
System.Array.FindIndex(IltBankCommands.Transfers, t => t.Code == code);
private static void ItemTable()
{
string Codes(System.Collections.Generic.IEnumerable<string> codes) => string.Join(",", codes);
// ACECustom HandleBank (upstream 976606695): deposit everything; withdraw all but peas and
// luminance tokens; transfer all but those and the bound prestige coins.
Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Deposits, d => d.Args)), ",p,ps,l,lum,k,mk,e,we,pc,n", "deposits");
Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Withdrawals, w => w.Code)), "p,l,k,mk,e,we,pc,n", "withdrawals");
Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Transfers, t => t.Code)), "p,l,k,mk,e,we,n", "transfers");
Check.Eq(TransferIndex("pc"), -1, "prestige coins are bound: never offered for transfer");
Check.Eq(TransferIndex("ps"), -1, "pyreal peas: deposit only");
Check.Eq(IltBanking.Currencies.Length, IltBankCommands.Transfers.Length, "the transfer form uses the table");
Check.Eq(IltBanking.Currencies[0].Code, "p", "saved transfer index 0 is still pyreals");
Check.Eq(IltBanking.Currencies[5].Code, "we", "saved transfer indexes 0-5 keep their currency");
}
private static void Transfers()
{
int mmd = System.Array.FindIndex(IltBankCommands.NoteDenominations, n => n.Code == "mmd");
Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 250_000, -1, "Bob", out _), "/bank t p 250000 Bob", "pyreals");
Check.Eq(IltBankCommands.Transfer(TransferIndex("mk"), 3, -1, " Bob ", out _), "/bank t mk 3 Bob", "name trimmed");
Check.Eq(IltBankCommands.Transfer(TransferIndex("l"), 10, -1, "Some Name", out _), "/bank t l 10 \"Some Name\"",
"a name with a space is quoted (the server reads one argument)");
Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), 4, mmd, "Bob", out _), "/bank t n mmd 4 Bob", "four 250K notes");
Check.True(IltBankCommands.IsNoteTransfer(TransferIndex("n")), "notes transfer by denomination");
Check.False(IltBankCommands.IsNoteTransfer(TransferIndex("p")), "pyreals don't");
Check.Eq(IltBankCommands.NoteValue(mmd, 4), 1_000_000L, "4 x 250K");
Check.Eq(IltBankCommands.Transfer(-1, 10, -1, "Bob", out string e1), "", "no currency refused");
Check.Eq(e1, "Pick a currency.", "why");
Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 0, -1, "Bob", out _), "", "zero refused");
Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 10, -1, " ", out string e2), "", "no recipient refused");
Check.Eq(e2, "Enter a recipient.", "why");
Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 10, -1, "Bob\" x", out _), "", "a quote can't break out of the name");
Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), 4, 99, "Bob", out _), "", "bad denomination refused");
Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), IltBankCommands.MaxNoteCount + 1, mmd, "Bob", out _), "", "too many notes refused");
}
private static void TransferReplies()
{
Check.True(IltBankCommands.IsTransferReply("Transferred 1,000,000 Pyreals to Bob"), "result");
Check.True(IltBankCommands.IsTransferReply("(Equivalent to 4x MMD notes)"), "trade-note equivalent");
Check.True(IltBankCommands.IsTransferReply("[BANK] Prestige Coins are bound to you and cannot be transferred."), "bound coins");
Check.True(IltBankCommands.IsTransferReply("[Transfer] This command may only be run once every 5 seconds."), "throttled");
Check.True(IltBankCommands.IsTransferReply("Invalid denomination. Use: i(100), v(500)"), "bad denomination");
Check.False(IltBankCommands.IsTransferReply("[BANK] Pyreals: 1,000"), "a balance line is not");
Check.False(IltBankCommands.IsTransferReply("Bob tells you, \"Transferred 5\""), "a tell is not");
}
private static int DepositIndex(string args) =>
System.Array.FindIndex(IltBankCommands.Deposits, d => d.Args == args);
private static int WithdrawIndex(string code) =>
System.Array.FindIndex(IltBankCommands.Withdrawals, w => w.Code == code);
private static void Deposits()
{
Check.Eq(IltBankCommands.Deposit(0), "/b d", "Everything is a plain deposit");
Check.Eq(IltBankCommands.Deposit(DepositIndex("p")), "/b d p", "pyreals");
Check.Eq(IltBankCommands.Deposit(DepositIndex("pc")), "/b d pc", "prestige coins");
Check.Eq(IltBankCommands.Deposit(DepositIndex("lum")), "/b lum", "luminance tokens use /b lum");
Check.Eq(IltBankCommands.Deposit(-1), "", "unknown index sends nothing");
Check.Eq(IltBankCommands.Deposit(IltBankCommands.Deposits.Length), "", "past the end sends nothing");
}
private static void Withdrawals()
{
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("p"), 1_500_000, 0, out _), "/b w p 1500000", "pyreals");
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("pc"), 3, 0, out _), "/b w pc 3", "prestige coins");
int mmd = System.Array.FindIndex(IltBankCommands.NoteDenominations, n => n.Code == "mmd");
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), 5, mmd, out _), "/b w n mmd 5", "five 250K notes");
}
private static void WithdrawRefusals()
{
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("p"), 0, 0, out string e1), "", "zero refused");
Check.True(e1.Length > 0, "zero says why");
Check.Eq(IltBankCommands.Withdraw(-1, 10, 0, out _), "", "no currency refused");
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), 10, 99, out _), "", "bad denomination refused");
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), IltBankCommands.MaxNoteCount + 1, 0, out string e2), "",
"more notes than the server allows refused");
Check.True(e2.Contains("50,000"), "says the limit");
}
private static void Replies()
{
Check.True(IltBankCommands.IsActionReply("Deposited 12,345 pyreals"), "deposit");
Check.True(IltBankCommands.IsActionReply("No pyreal peas found to deposit"), "nothing to deposit");
Check.True(IltBankCommands.IsActionReply("Withdrew 2 prestige coins"), "withdraw");
Check.True(IltBankCommands.IsActionReply("Starting Banked Lum: 5B (5,000,000,000)"), "token deposit start");
Check.True(IltBankCommands.IsActionReply("[Withdraw] This command may only be run once every 5 seconds."), "throttled");
Check.True(IltBankCommands.IsActionReply("You don't have enough luminance banked. Need 10 but only have 5."), "short");
Check.False(IltBankCommands.IsActionReply("[BANK] Pyreals: 1,000"), "a balance line is not an action reply");
Check.False(IltBankCommands.IsActionReply("No one is near."), "other 'No ...' lines are not");
Check.False(IltBankCommands.IsActionReply("Bob tells you, \"Deposited 5 pyreals\""), "a tell is not");
Check.False(IltBankCommands.IsActionReply(""), "empty");
}
/// <summary>
/// SilentKelpie's backstop for a quiet refresh whose reply leaked into chat, narrowed: the dump's
/// header and "Label: N" lines only, never errors, bound-coin notes or Transferred / Received lines,
/// and never a balance read outside the window after a quiet refresh (a macro's or plugin's /bank).
/// </summary>
private static void LeakedDump()
{
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Your balances are:"), "header");
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Pyreals: 1,000"), "pyreals");
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Luminance: 2,500,000"), "luminance");
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Weakly Enlightened Coins: 3"), "weakly enlightened coins");
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Prestige Coins: 2 (bound to you and cannot be traded)"), "prestige coins");
Check.False(IltBanking.IsBalanceDumpLine("[BANK] Too many parameters"), "an error");
Check.False(IltBanking.IsBalanceDumpLine("[BANK] Prestige Coins are bound to you and cannot be transferred."), "the bound-coin note");
Check.False(IltBanking.IsBalanceDumpLine("Transferred 1,000,000 Pyreals to Bob"), "a transfer reply");
Check.False(IltBanking.IsBalanceDumpLine("Received 5 Pyreals from Bob"), "a received line");
Check.False(IltBanking.IsBalanceDumpLine("Bob tells you, \"[BANK] Pyreals: 5\""), "a tell quoting a dump");
const long Win = IltBanking.QuietBalanceWindowMs;
Check.True(IltBanking.EatLeakedDump(true, 1_000, 1_000 + Win), "a dump line inside the window is eaten");
Check.False(IltBanking.EatLeakedDump(true, 1_000 + Win + 1, 1_000 + Win), "after the window it shows (a macro's /bank)");
Check.False(IltBanking.EatLeakedDump(true, 1_000, 0), "no quiet refresh out: it shows (typed /bank, loud refresh, other plugins)");
Check.False(IltBanking.EatLeakedDump(false, 1_000, 1_000 + Win), "a non-dump [BANK] line inside the window still shows");
}
}

View file

@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The Banking tab's every-character table (Hub/IltBankRoster.cs): SilentKelpie's Banking tab, in
// RynthInventory's window until 2026-10-21 (its tests came with it, adapted: the roster is RynthILT's own
// characters now, without Global Inventory's "not read yet" rows) and RynthILT's own tab since.
internal static class BankRosterTests
{
public static void Register(Runner r)
{
r.Add("bank roster: you first, then by name; the totals add every read balance", Roster);
r.Add("bank roster: the Banking tab lists every character RynthILT has run on this server", FromSavedCharacters);
}
private static IltBankState Bank(long py, long lum, long lk, long mk, long ec, long wec, long pc, DateTime updated) => new()
{
Pyreals = py, Luminance = lum, LegendaryKeys = lk, MythicalKeys = mk,
EnlightenedCoins = ec, WeaklyEnlightenedCoins = wec, PrestigeCoins = pc, LastUpdated = updated,
};
private static void Roster()
{
DateTime t = new(2026, 10, 3, 11, 0, 0, DateTimeKind.Local);
var rows = new List<IltBankExport.Row>
{
new("Willow", false, Bank(1, 1, 0, 0, 0, 0, 0, t.AddDays(-1))),
new("Buffy", true, Bank(100, 2000, 1, 0, 3, 0, 0, t)),
new("Ghost", false, Bank(50, 0, 2, 1, 0, 4, 5, t.AddDays(-2))),
new("buffy", false, Bank(999, 999, 9, 9, 9, 9, 9, t.AddDays(-9))), // a stale saved copy of you
new("Never", false, Bank(7, 7, 7, 7, 7, 7, 7, DateTime.MinValue)), // never read: not in the totals
};
IltBankRosterRow[] roster = IltBankRoster.Build(rows);
Check.Eq(string.Join(",", roster.Select(r => r.Name)), "Buffy,Ghost,Never,Willow", "you first, then by name; your saved copy doesn't replace you");
Check.True(roster[0].Current && roster[0].Pyreals == 100, "your live balance");
IltBankRosterRow total = IltBankRoster.Totals(roster);
Check.True(total.Name == "Total" && total.Pyreals == 151 && total.Luminance == 2001 && total.LegendaryKeys == 3 && total.MythicalKeys == 1
&& total.EnlightenedCoins == 3 && total.WeaklyEnlightenedCoins == 4 && total.PrestigeCoins == 5,
"totals add every balance read (a never-read one isn't counted)");
Check.Eq(string.Join(",", IltBankRoster.Others(roster)), "Ghost,Never,Willow", "the transfer form's picker: your other characters");
Check.Eq(IltBankRoster.Build(new List<IltBankExport.Row>()).Length, 0, "nothing: an empty roster");
Check.Eq(IltBankRoster.Age(DateTime.MinValue, t), "-", "never read");
Check.Eq(IltBankRoster.Age(t.AddMinutes(-5), t), "5m ago", "minutes");
Check.Eq(IltBankRoster.Age(t.AddHours(-3), t), "3h ago", "hours");
Check.Eq(IltBankRoster.Age(t.AddDays(-2), t), "2d ago", "days");
}
private static void FromSavedCharacters()
{
FakeHost.Reset();
FakeAiHub.Reset();
FakeHost.WorldName = "InfiniteLeaftide";
var host = FakeHost.Create(0x50000D41);
string world = Path.Combine(Program.TempRoot, "roster-world");
if (Directory.Exists(world)) Directory.Delete(world, recursive: true);
// Two other characters RynthILT has run here (their saved hub.json), one that never banked.
foreach ((string name, long py, bool banked) in new[] { ("Ghost", 50L, true), ("Willow", 7L, true), ("Nobank", 0L, false) })
{
string dir = Path.Combine(world, name);
Directory.CreateDirectory(dir);
var state = new IltHubState();
state.Bank.Pyreals = py;
if (banked) state.Bank.LastUpdated = DateTime.Now.AddHours(-2);
File.WriteAllText(Path.Combine(dir, IltHubStore.StateFile), JsonSerializer.Serialize(state, IltHubJsonContext.Default.IltHubState));
}
string me = Path.Combine(world, "Buffy");
Directory.CreateDirectory(me);
var hub = new IltHubController(host, me, new IltSettings(), new RynthAiClient(host));
hub.OnLoginComplete("Buffy", forceFromMigration: false);
hub.State.Bank.Pyreals = 100;
hub.State.Bank.LastUpdated = DateTime.Now;
hub.Tick();
Check.Eq(hub.Banking.Roster.Length, 0, "nothing is read while the table isn't on screen");
hub.Banking.MarkRosterWatched();
hub.Tick();
IltBankRosterRow[] roster = hub.Banking.Roster;
Check.Eq(string.Join(",", roster.Select(r => r.Name)), "Buffy,Ghost,Willow", "you and the characters with a saved balance");
Check.True(roster[0].Current && roster[0].Pyreals == 100 && roster[1].Pyreals == 50, "live and saved balances");
Check.Eq(IltBankRoster.Totals(roster).Pyreals, 157L, "the total");
}
}

View file

@ -0,0 +1,252 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthILT.Bounty;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The RynthILT review of SilentKelpie's tracker (2026-10-09). Two promises, checked here on a
// fake clock:
// * rate: at most one "/bounty list" per MinRefreshSeconds (5 s floor, whatever asks: kills,
// award lines every kill, Refresh spam, opening and closing the window), and none while the
// window is closed;
// * hidden chat: only the reply to the tracker's own read is eaten. A /bounty the player types
// is shown, also when it overlaps a read of ours, and our own command coming back through the
// engine's chat bar dispatcher is not mistaken for the player's.
internal static class BountyReviewTests
{
public static void Register(Runner r)
{
r.Add("review: awards on every kill never read more than once per MinRefreshSeconds", AwardsEveryKill);
r.Add("review: Refresh spam and window open/close keep the 5 s floor", RefreshSpamAndToggling);
r.Add("review: a long mixed session: every read 5 s apart and only while the window is open", MixedSession);
r.Add("review: a /bounty list the player types is shown and stands in for the next read", TypedListShown);
r.Add("review: a /bounty the player types during our read: the rest of that read is shown", TypedDuringCapture);
r.Add("review: our own /bounty list coming back through the chat bar is not the player's", OwnEcho);
r.Add("review: command matching and long lines", Matching);
}
private const string Header = "Bounties:";
private const string Line = " Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills.";
private const string Footer = "Bounty: type /bounty to see the bounties where you stand.";
private sealed class Rig
{
public long Ms = 1_000_000;
public readonly List<long> SentAt = new();
public readonly List<bool> SentWhileOpen = new();
public BountyTracker T = null!;
public bool Open;
private long _lastPollMs;
public void Step(long ms)
{
for (long e = 0; e < ms; e += 250)
{
Ms += 250;
if (Open && Ms - _lastPollMs >= 1000) { T.BuildJson(); _lastPollMs = Ms; }
T.Tick();
}
}
/// <summary>The server answers our read at once (header, a line, footer).</summary>
public void Reply()
{
T.OnChat(Header);
T.OnChat(Line);
T.OnChat(Footer);
}
}
private static Rig New(int minRefreshSeconds = 5)
{
var rig = new Rig();
rig.T = new BountyTracker(cmd =>
{
if (cmd != BountyTracker.ListCommand) return;
rig.SentAt.Add(rig.Ms);
rig.SentWhileOpen.Add(rig.T.WindowOpen);
}, _ => { }, _ => { }, string.Empty, () => rig.Ms);
rig.T.Command($"set minrefreshseconds {minRefreshSeconds}");
return rig;
}
private static long MinGap(List<long> at)
{
long min = long.MaxValue;
for (int i = 1; i < at.Count; i++) min = Math.Min(min, at[i] - at[i - 1]);
return min;
}
private static void AwardsEveryKill()
{
var rig = New(minRefreshSeconds: 10);
rig.Open = true;
// A 1-kill bounty with no cooldown: every kill prints an award, for two minutes.
for (int s = 0; s < 120; s++)
{
rig.T.OnKill();
rig.T.OnChat("Bounty complete! +1 Ascension Coin gained.");
rig.T.OnChat("Next bounty requires 1 kill.");
rig.Step(1000);
if (rig.T.Reading) rig.Reply();
}
Check.True(rig.SentAt.Count >= 2, $"it still reads ({rig.SentAt.Count} reads)");
Check.True(rig.SentAt.Count <= 13, $"at most one read per 10 s over 120 s ({rig.SentAt.Count} reads)");
Check.True(MinGap(rig.SentAt) >= 10_000, $"reads at least MinRefreshSeconds apart (min gap {MinGap(rig.SentAt)} ms)");
}
private static void RefreshSpamAndToggling()
{
var rig = New(minRefreshSeconds: 30);
rig.Open = true;
rig.Step(500);
rig.Reply();
Check.Eq(rig.SentAt.Count, 1, "opening reads once");
// Refresh clicked every half second for 20 s: manual reads keep the 5 s floor.
for (int i = 0; i < 40; i++)
{
rig.T.Command("refresh");
rig.Step(500);
if (rig.T.Reading) rig.Reply();
}
Check.True(rig.SentAt.Count <= 5, $"20 s of Refresh spam: at most 4 more reads ({rig.SentAt.Count} in all)");
Check.True(MinGap(rig.SentAt) >= 5_000, $"manual reads at least 5 s apart (min gap {MinGap(rig.SentAt)} ms)");
// Kills while closed, then the window toggled open and shut every 4 s for a minute.
int before = rig.SentAt.Count;
for (int i = 0; i < 15; i++)
{
rig.Open = false;
rig.T.OnKill();
rig.Step(4000);
rig.Open = true;
rig.Step(1000);
if (rig.T.Reading) rig.Reply();
}
Check.True(rig.SentAt.Count - before <= 3, $"open/close every 5 s for 75 s with MinRefreshSeconds 30: at most 3 reads ({rig.SentAt.Count - before})");
Check.True(MinGap(rig.SentAt) >= 5_000, "and never two within 5 s");
Check.True(rig.SentWhileOpen.All(o => o), "every read went out with the window open");
}
private static void MixedSession()
{
var rig = New(minRefreshSeconds: 5);
var rnd = new Random(20261009);
for (int s = 0; s < 1800; s++) // 30 minutes
{
if (s % 120 == 0) rig.Open = !rig.Open;
int roll = rnd.Next(100);
if (roll < 30) rig.T.OnKill();
else if (roll < 35) rig.T.OnChat("Bounty complete! +1 Ascension Coin gained.");
else if (roll < 37) rig.T.Command("refresh");
else if (roll < 38) rig.T.OnChat("Bounty unlocked: Ascension Coin - 1 kill required.");
rig.Step(1000);
if (rig.T.Reading && rnd.Next(4) != 0) rig.Reply(); // now and then the server says nothing
}
Check.True(rig.SentAt.Count > 10, $"reads happened ({rig.SentAt.Count})");
Check.True(MinGap(rig.SentAt) >= 5_000, $"every read at least 5 s after the last (min gap {MinGap(rig.SentAt)} ms)");
Check.True(rig.SentWhileOpen.All(o => o), "every read went out with the window open");
}
private static void TypedListShown()
{
var rig = New(minRefreshSeconds: 5);
rig.Open = true;
rig.Step(500);
rig.Reply();
Check.Eq(rig.SentAt.Count, 1, "first read");
rig.Step(10_000);
// The player types /bounty list: the reply is shown (nothing eaten) and still applied.
rig.T.NoteTypedCommand("/bounty list");
Check.True(rig.T.Reading, "the typed list is captured (shown)");
Check.False(rig.T.OnChat(Header), "typed reply: the header stays in chat");
Check.False(rig.T.OnChat(" Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills."), "typed reply: the lines stay in chat");
Check.False(rig.T.OnChat(Footer), "typed reply: the footer stays in chat");
Check.False(rig.T.Reading, "and the footer ends it");
Check.Eq(rig.T.State.Entries.Count, 1, "the typed reply fills the list");
// It counts as the latest read: a kill right after waits the full interval.
rig.T.OnKill();
rig.Step(4000);
Check.Eq(rig.SentAt.Count, 1, "no read of ours on top of the player's");
rig.Step(2000);
Check.Eq(rig.SentAt.Count, 2, "the kill's read comes MinRefreshSeconds after the typed one");
Check.True(rig.T.OnChat(Header) && rig.T.OnChat(Line) && rig.T.OnChat(Footer), "our own read is eaten again");
// "/bounty" (where you stand) output is never eaten.
rig.T.NoteTypedCommand("/bounty");
Check.False(rig.T.OnChat("Bounty: 1 Ascension Coin - 0 of 1 kills."), "a /bounty line stays in chat");
Check.False(rig.T.OnChat("Bounty: there is no bounty here."), "'no bounty here' stays in chat");
}
private static void TypedDuringCapture()
{
var rig = New(minRefreshSeconds: 5);
rig.Open = true;
rig.Step(500);
Check.Eq(rig.SentAt.Count, 1, "our read went out");
rig.T.NoteTypedCommand(BountyTracker.ListCommand); // our own echo first (consumed)
Check.True(rig.T.OnChat(Header), "our reply's header is eaten");
// The player types /bounty list while our reply is still coming in.
rig.Step(250);
rig.T.NoteTypedCommand("/bounty list");
Check.False(rig.T.OnChat(Line), "after the player asked, reward lines are shown");
Check.False(rig.T.OnChat(Footer), "and so is the footer");
Check.False(rig.T.OnChat(Header), "the player's own reply: header shown");
Check.False(rig.T.OnChat(Line), "the player's own reply: line shown");
Check.False(rig.T.OnChat(Footer), "the player's own reply: footer shown");
Check.False(rig.T.OnChat("Bounty complete! +1 Ascension Coin gained."), "award lines are never eaten");
// On a server without /bounty, the player's typed /bounty during our read: the refusal shows.
var rig2 = New();
rig2.Open = true;
rig2.Step(500);
rig2.T.NoteTypedCommand("/bounty");
Check.False(rig2.T.OnChat("Unknown command: bounty"), "the refusal of the player's own /bounty stays in chat");
}
private static void OwnEcho()
{
var rig = New(minRefreshSeconds: 5);
rig.Open = true;
rig.Step(500);
Check.Eq(rig.SentAt.Count, 1, "our read went out");
rig.Step(250);
rig.T.NoteTypedCommand("/bounty list"); // the engine's dispatcher passing our own line back
Check.True(rig.T.OnChat(Header), "our echo is recognised: the reply is still eaten");
Check.True(rig.T.OnChat(Line), "reward lines eaten");
Check.True(rig.T.OnChat(Footer), "footer eaten");
// An echo that comes too late is taken for the player's: that read is shown, never eaten wrongly.
rig.Step(10_000);
Check.Eq(rig.SentAt.Count, 1, "no new read yet (nothing asked)");
rig.T.Command("refresh");
rig.Step(500);
Check.Eq(rig.SentAt.Count, 2, "refresh reads");
rig.Step(3000);
rig.T.NoteTypedCommand("/bounty list");
Check.False(rig.T.OnChat(Header), "a late echo errs on the shown side");
}
private static void Matching()
{
Check.True(BountyTracker.IsBountyCommand("/bounty"), "/bounty");
Check.True(BountyTracker.IsBountyCommand("/bounty list"), "/bounty list");
Check.True(BountyTracker.IsBountyCommand("@Bounty all"), "@bounty all");
Check.False(BountyTracker.IsBountyCommand("/bountyhunter"), "a longer command is not /bounty");
Check.False(BountyTracker.IsBountyCommand("/b hello"), "chat");
Check.True(BountyTracker.IsListCommand("/bounty list") && BountyTracker.IsListCommand("/BOUNTY ALL"), "list commands");
Check.False(BountyTracker.IsListCommand("/bounty") || BountyTracker.IsListCommand("/bounty list now"), "not list commands");
var rig = New();
rig.Open = true;
rig.Step(500);
string longLine = " Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills." + new string(' ', 600) + "x";
Check.False(rig.T.OnChat(longLine), "a line over 512 characters is never eaten or parsed");
}
}

View file

@ -0,0 +1,388 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using RynthCore.Plugin.RynthILT.Bounty;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// ACECustom bounty tracker (2026-10-09). The server keeps the kill counts (BountyProgress is a
// server-only property), so the engine's Bounties window has RynthILT read "/bounty list" quietly
// and parse it. The line formats below are copied from ACECustom BountyManager (ShowAllBounties /
// ShowBounty / Award / NextBountyLine). The tracker runs on a fake clock; the engine's 1 s poll
// of RynthPluginGetBountiesJson is simulated by calling BuildJson.
internal static class BountyTests
{
public static void Register(Runner r)
{
r.Add("bounty: /bounty list lines (counting, cooldown, QB, layers, commas)", ListLines);
r.Add("bounty: /bounty lines, waits and chat events", HereLinesAndEvents);
r.Add("bounty: a full read replaces the list, a partial one updates it", ApplyListRules);
r.Add("bounty: kills and awards stamp the row; an ended cooldown shows 0 kills; state survives a relog", ChangesAndCooldown);
r.Add("bounty: /bounty updates only the one reward it can mean", HereMatching);
r.Add("bounty: an open window reads the list quietly, kills and awards re-read it", WindowReadsAndKills);
r.Add("bounty: closed window sends nothing; unknown command stops reads; no reply times out", ClosedAndUnsupported);
r.Add("bounty: the window's JSON (options, QB filter, closest first) parses in the engine", BridgeJson);
}
// ── Parsing ────────────────────────────────────────────────────────────────
private static void ListLines()
{
Check.True(BountyParse.TryParseListLine(" Lugian Mines: 1 Ascension Coin every 100 kills (at most every 5 min) - you: 34 of 100 kills.", out var a),
"counting line parses (leading indentation)");
Check.Eq(a.Where, "Lugian Mines", "area");
Check.Eq(a.Amount, 1L, "amount");
Check.Eq(a.Item, "Ascension Coin", "item");
Check.Eq(a.KillsRequired, 100, "kills per award");
Check.Eq(a.CooldownSeconds, 300, "cooldown");
Check.Eq(a.Status.Status, BountyStatus.Counting, "status");
Check.Eq(a.Status.Kills, 34, "kills so far");
Check.True(BountyParse.TryParseListLine("All zones: 3 Pyreal Nugget every 1,000 kills (at most every 2 min 30 sec) - you: unlocks in 1 hr 15 sec, then 1,000 kills required.", out var b),
"cooldown line parses");
Check.Eq(b.Where, "All zones", "all-zones area");
Check.Eq(b.KillsRequired, 1000, "N0 kills");
Check.Eq(b.CooldownSeconds, 150, "2 min 30 sec");
Check.Eq(b.Status.Status, BountyStatus.Cooldown, "cooldown status");
Check.Eq(b.Status.WaitSeconds, 3615, "1 hr 15 sec");
Check.Eq(b.Status.KillsRequired, 1000, "kills after the cooldown");
Check.True(BountyParse.TryParseListLine("Valley of Death: 1,500 Trade Note - Large every 1 kill - you: needs 5,000 QB (you have 3,210).", out var c),
"QB line with no cooldown and a hyphenated item parses");
Check.Eq(c.Amount, 1500L, "N0 amount");
Check.Eq(c.Item, "Trade Note - Large", "item keeps its own ' - '");
Check.Eq(c.KillsRequired, 1, "one kill");
Check.Eq(c.CooldownSeconds, 0, "no cooldown");
Check.Eq(c.Status.Status, BountyStatus.NeedsQb, "QB status");
Check.Eq(c.Status.QbRequired, 5000L, "QB needed");
Check.Eq(c.Status.QbHave, 3210L, "QB had");
Check.True(BountyParse.TryParseListLine("Halls of Metos: Lower (layer 2): 2 Ascension Coin every 50 kills - you: 0 of 50 kills.", out var d),
"an area with ': ' and a layer parses");
Check.Eq(d.Where, "Halls of Metos: Lower (layer 2)", "area keeps its colon and layer");
Check.False(BountyParse.TryParseListLine("Bounties:", out _), "the header is not a reward");
Check.False(BountyParse.TryParseListLine("Bounty: type /bounty to see the bounties where you stand.", out _), "the footer is not a reward");
Check.False(BountyParse.TryParseListLine("Bob says, \"Lugian Mines: 1 coin every 100 kills\"", out _), "chat talk is not a reward");
Check.True(BountyParse.IsListTerminator("Bounty: type /bounty to see the bounties where you stand."), "footer ends the reply");
Check.True(BountyParse.IsListTerminator("Bounty: there are no bounties anywhere right now."), "'none anywhere' ends the reply");
Check.True(BountyParse.IsNoBountiesAnywhere("Bounty: there are no bounties anywhere right now."), "'none anywhere' is recognised");
Check.False(BountyParse.IsListTerminator("Bounty: there is no bounty here."), "/bounty's 'none here' is not the list's end");
Check.True(BountyParse.IsUnknownCommand("Unknown command: bounty"), "ACE's unknown-command reply is recognised");
Check.False(BountyParse.IsUnknownCommand("Unknown command: bank"), "another command's reply is not ours");
}
private static void HereLinesAndEvents()
{
Check.True(BountyParse.TryParseHereLine("Bounty: 1 Ascension Coin - 12 of 100 kills.", out var h1), "plain /bounty line");
Check.Eq(h1.Scope, "", "no scope");
Check.Eq(h1.Status.Kills, 12, "kills");
Check.True(BountyParse.TryParseHereLine("Bounty (all zones): 3 Pyreal Nugget - unlocks in 45 sec, then 1 kill required.", out var h2), "all-zones /bounty line");
Check.Eq(h2.Scope, "all zones", "all-zones scope");
Check.Eq(h2.Status.WaitSeconds, 45, "45 sec");
Check.True(BountyParse.TryParseHereLine("Bounty (Thaelaryn Island): 1 Ascension Coin - needs 500 QB (you have 20).", out var h3), "region /bounty line");
Check.Eq(h3.Scope, "Thaelaryn Island", "region scope");
Check.False(BountyParse.TryParseHereLine("Bounty: there is no bounty here.", out _), "'none here' is not a reward");
Check.False(BountyParse.TryParseHereLine("Bounty: +1 Ascension Coin will follow in a moment.", out _), "held notice is not a reward");
Check.Eq(BountyParse.ParseWaitSeconds("5 min"), 300, "5 min");
Check.Eq(BountyParse.ParseWaitSeconds("2 hr 3 min 4 sec"), 7384, "hr min sec");
Check.Eq(BountyParse.ParseWaitSeconds("soon"), 0, "unparseable wait");
Check.True(BountyParse.TryParseEvent("Bounty unlocked: Ascension Coin - 100 kills required.", out var k1, out string item1, out int n1, out _)
&& k1 == BountyEventKind.Unlocked && item1 == "Ascension Coin" && n1 == 100, "unlock event");
Check.True(BountyParse.TryParseEvent("Bounty complete! +3 Pyreal Nuggets gained.", out var k2, out string item2, out _, out _)
&& k2 == BountyEventKind.Complete && item2 == "Pyreal Nuggets", "award event");
Check.True(BountyParse.TryParseEvent("Next bounty unlocks in 2 min 30 sec - 1 kill required.", out var k3, out _, out int n3, out int w3)
&& k3 == BountyEventKind.NextCooldown && n3 == 1 && w3 == 150, "next-cooldown event");
Check.True(BountyParse.TryParseEvent("Next bounty requires 1,000 kills.", out var k4, out _, out int n4, out _)
&& k4 == BountyEventKind.NextReady && n4 == 1000, "next-ready event");
Check.True(BountyParse.TryParseEvent("Bounty: Your inventory is full. +1 Ascension Coin gained (3 total). They're safe until you make room.", out var k5, out _, out _, out _)
&& k5 == BountyEventKind.Held, "held event");
Check.False(BountyParse.TryParseEvent("Bounty: there is no bounty here.", out _, out _, out _, out _), "'none here' is not an event");
Check.False(BountyParse.TryParseEvent("Bounty: 1 Ascension Coin - 12 of 100 kills.", out _, out _, out _, out _), "a status line is not an event");
Check.False(BountyParse.TryParseEvent("Bounty: type /bounty to see the bounties where you stand.", out _, out _, out _, out _), "the footer is not an event");
}
// ── Applying reads ─────────────────────────────────────────────────────────
private static BountyListLine L(string line)
{
Check.True(BountyParse.TryParseListLine(line, out var l), "fixture parses: " + line);
return l;
}
private static void ApplyListRules()
{
var t = New(out _, out _, out _);
var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc);
t.ApplyList(new[]
{
L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."),
L("All zones: 3 Pyreal Nugget every 50 kills - you: 0 of 50 kills."),
}, complete: true, noneAnywhere: false, t0);
Check.Eq(t.State.Entries.Count, 2, "full read: two rewards");
Check.Eq(t.State.ListedUtc, t0, "read time stamped");
// A partial reply (no footer) only updates what it names; the other rows stay.
t.ApplyList(new[] { L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 11 of 100 kills.") },
complete: false, noneAnywhere: false, t0.AddSeconds(5));
Check.Eq(t.State.Entries.Count, 2, "partial read keeps the other row");
Check.Eq(t.State.Entries[0].Kills, 11, "partial read updates the named row in place");
// A full read drops areas that are gone and keeps the server's order.
t.ApplyList(new[]
{
L("Thaelaryn Island: 1 Ascension Coin every 20 kills - you: 4 of 20 kills."),
L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 12 of 100 kills."),
}, complete: true, noneAnywhere: false, t0.AddSeconds(10));
Check.Eq(string.Join(",", t.State.Entries.Select(e => e.Where)), "Thaelaryn Island,Lugian Mines", "server order, removed area gone");
t.ApplyList(Array.Empty<BountyListLine>(), complete: true, noneAnywhere: true, t0.AddSeconds(20));
Check.Eq(t.State.Entries.Count, 0, "'none anywhere' empties the list");
Check.True(t.State.NoneAnywhere, "and says so");
}
private static void ChangesAndCooldown()
{
string file = Path.Combine(Program.TempRoot, "bounty-changes", BountyTracker.FileName);
var t = New(out _, out _, out _, file);
var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc);
const string Head = "Lugian Mines: 1 Ascension Coin every 3 kills (at most every 5 min) - you: ";
t.ApplyList(new[] { L(Head + "1 of 3 kills.") }, true, false, t0);
Check.Eq(t.State.Entries[0].ChangedUtc, default(DateTime), "first sighting is not a change");
t.ApplyList(new[] { L(Head + "2 of 3 kills.") }, true, false, t0.AddSeconds(10));
Check.Eq(t.State.Entries[0].ChangedUtc, t0.AddSeconds(10), "a new kill stamps the row");
t.ApplyList(new[] { L(Head + "unlocks in 5 min, then 3 kills required.") }, true, false, t0.AddSeconds(20));
var e = t.State.Entries[0];
Check.Eq(e.ChangedUtc, t0.AddSeconds(20), "the award stamps the row");
Check.Eq(e.UnlockAtUtc, t0.AddSeconds(320), "unlock time = read time + wait");
Check.Eq(BountyTracker.Effective(e, t0.AddSeconds(100)).Status, BountyStatus.Cooldown, "still cooling down");
var after = BountyTracker.Effective(e, t0.AddSeconds(321));
Check.True(after.Status == BountyStatus.Counting && after.Kills == 0, "after the cooldown: 0 of N kills");
Check.True(BountyTracker.Describe(e, t0.AddSeconds(100)).Contains("unlocks in 3 min 40 sec"), "chat text counts the cooldown down");
// The state survives a relog (the window fills right after login).
t.Command("set hideqblocked 1");
t.Save();
var loaded = New(out _, out _, out _, file);
Check.Eq(loaded.State.Entries.Count, 1, "entries saved per character");
Check.Eq(loaded.State.Entries[0].UnlockAtUtc, t0.AddSeconds(320), "unlock time saved");
Check.True(loaded.State.HideQbLocked, "options saved");
}
private static void HereMatching()
{
var t = New(out _, out _, out _);
var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc);
t.ApplyList(new[]
{
L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."),
L("Halls of Metos: 1 Ascension Coin every 100 kills - you: 50 of 100 kills."),
L("Thaelaryn Island: 2 Ascension Coin every 20 kills - you: 4 of 20 kills."),
L("All zones: 1 Ascension Coin every 100 kills - you: 0 of 100 kills."),
}, true, false, t0);
Check.True(BountyParse.TryParseHereLine("Bounty (Thaelaryn Island): 2 Ascension Coin - 5 of 20 kills.", out var region), "fixture");
Check.True(t.ApplyHere(region, t0.AddSeconds(5)), "a region line names its area");
Check.Eq(t.State.Entries[2].Kills, 5, "region row updated");
Check.True(BountyParse.TryParseHereLine("Bounty (all zones): 1 Ascension Coin - 1 of 100 kills.", out var zones), "fixture");
Check.True(t.ApplyHere(zones, t0.AddSeconds(6)), "an all-zones line names its area");
Check.Eq(t.State.Entries[3].Kills, 1, "all-zones row updated");
Check.True(BountyParse.TryParseHereLine("Bounty: 1 Ascension Coin - 11 of 100 kills.", out var plain), "fixture");
Check.False(t.ApplyHere(plain, t0.AddSeconds(7)), "two dungeons pay the same reward: left alone");
Check.Eq(t.State.Entries[0].Kills, 10, "first dungeon untouched");
Check.Eq(t.State.Entries[1].Kills, 50, "second dungeon untouched");
}
// ── The read loop ──────────────────────────────────────────────────────────
private const string ListReplyCounting = " Lugian Mines: 1 Ascension Coin every 100 kills - you: 34 of 100 kills.";
private const string Footer = "Bounty: type /bounty to see the bounties where you stand.";
private static void WindowReadsAndKills()
{
var t = New(out var clock, out var sent, out _);
t.Command("set minrefreshseconds 5");
Run(t, clock, 500, windowOpen: true);
Check.Eq(Reads(sent), 1, "opening the window reads /bounty list");
Check.True(t.Reading, "a read is in progress");
Check.True(t.OnChat("Bounties:"), "the header is hidden from chat");
Check.True(t.OnChat(ListReplyCounting), "reward lines are hidden from chat");
Check.True(t.OnChat(Footer), "the footer is hidden and ends the read");
Check.False(t.Reading, "the read is over");
Check.Eq(t.State.Entries.Count, 1, "the read fills the list");
Check.Eq(t.State.Entries[0].Kills, 34, "with the player's kills");
// A kill re-reads after the debounce, but not sooner than MinRefreshSeconds after the last read.
t.OnKill();
Run(t, clock, 3000, windowOpen: true);
Check.Eq(Reads(sent), 1, "no re-read inside MinRefreshSeconds");
Run(t, clock, 3000, windowOpen: true);
Check.Eq(Reads(sent), 2, "a kill re-reads the list");
t.OnChat("Bounties:");
t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills - you: 35 of 100 kills.");
t.OnChat(Footer);
Check.Eq(t.State.Entries[0].Kills, 35, "the kill shows up");
Check.True(t.State.Entries[0].ChangedUtc != default, "and the row is highlighted");
// Award lines are shown to the player and also trigger a read, once MinRefreshSeconds
// have passed since the last one (review 2026-10-09: awards used to skip the interval).
Check.False(t.OnChat("Bounty complete! +1 Ascension Coin gained."), "award lines stay in chat");
Check.Eq(t.State.LastEvent, "Bounty complete! +1 Ascension Coin gained.", "the window shows the last event");
Run(t, clock, 2000, windowOpen: true);
Check.Eq(Reads(sent), 2, "the award's re-read waits for MinRefreshSeconds");
Run(t, clock, 3000, windowOpen: true);
Check.Eq(Reads(sent), 3, "an award re-reads the list");
// A reply whose footer never comes ends after a quiet moment, as a partial update.
t.OnChat("Bounties:");
t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills (at most every 5 min) - you: unlocks in 5 min, then 100 kills required.");
Run(t, clock, 2000, windowOpen: true);
Check.False(t.Reading, "a reply without its footer still ends");
Check.Eq(t.State.Entries[0].Status, (int)BountyStatus.Cooldown, "and is applied");
// Lines the player asks for themselves are not hidden but still update the list.
Check.False(t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills - you: 0 of 100 kills."), "a typed /bounty list line stays in chat");
Check.Eq(t.State.Entries[0].Status, (int)BountyStatus.Counting, "and updates the row");
// Closing the window (the engine stops polling; 3 s grace) stops the reads.
Run(t, clock, 5000, windowOpen: false);
int before = Reads(sent);
t.OnKill();
Run(t, clock, 20000, windowOpen: false);
Check.Eq(Reads(sent), before, "no reads once the window is closed");
}
private static void ClosedAndUnsupported()
{
var t = New(out var clock, out var sent, out var chat);
t.Command("set minrefreshseconds 5");
t.OnKill();
Run(t, clock, 10000, windowOpen: false);
Check.Eq(Reads(sent), 0, "closed window: kills send nothing");
Run(t, clock, 500, windowOpen: true);
Check.Eq(Reads(sent), 1, "opening the window reads the list");
Check.True(t.OnChat("Unknown command: bounty"), "the unknown-command reply to our read is hidden");
Check.True(t.Unsupported, "'Unknown command: bounty' marks the server unsupported");
t.OnKill();
Run(t, clock, 10 * 60_000, windowOpen: true);
Check.Eq(Reads(sent), 1, "no automatic reads on an unsupported server, periodic included");
t.HandleChatCommand(new[] { "/ilt", "bountys", "refresh" });
Check.False(t.Unsupported, "a manual refresh tries again");
Run(t, clock, 500, windowOpen: true);
Check.Eq(Reads(sent), 2, "and reads the list");
Check.True(chat.Any(c => c.Contains("Reading /bounty list")), "the command answers in chat");
Run(t, clock, 11000, windowOpen: true);
Check.False(t.Reading, "no reply: the read is abandoned");
Check.True(t.BuildJson().Contains("no reply to /bounty list"), "and the window says so");
// With the window closed a manual refresh sends nothing (review 2026-10-09: reads only
// while the window is open); the next open reads.
Run(t, clock, 5000, windowOpen: false);
Check.True(t.Command("refresh").Contains("window is open"), "a closed-window refresh says why it waits");
Check.Eq(Reads(sent), 2, "a closed-window refresh sends nothing");
Run(t, clock, 500, windowOpen: true);
Check.Eq(Reads(sent), 3, "the next open reads");
chat.Clear();
t.HandleChatCommand(new[] { "/ilt", "bounty" });
Check.True(chat.Any(c => c.Contains("/rc bounties")), "'/ilt bounty' points at the window");
}
private static void BridgeJson()
{
var t = New(out _, out _, out _);
var now = DateTime.UtcNow;
t.ApplyList(new[]
{
L("Valley of Death: 1,500 Trade Note - Large every 1 kill - you: needs 5,000 QB (you have 3,210)."),
L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."),
L("Thaelaryn Island: 2 Ascension Coin every 20 kills (at most every 5 min) - you: unlocks in 2 min, then 20 kills required."),
L("Halls of Metos: 1 Ascension Coin every 10 kills - you: 9 of 10 kills."),
}, true, false, now);
Check.Eq(t.Command("set minrefreshseconds 1"), "", "option accepted");
Check.Eq(t.State.MinRefreshSeconds, BountyTracker.MinRefreshFloorSeconds, "MinRefreshSeconds is clamped to the floor");
t.Command("set periodicminutes 999");
Check.Eq(t.State.PeriodicRefreshMinutes, BountyTracker.PeriodicCeilingMinutes, "PeriodicRefreshMinutes is clamped");
Check.True(t.Command("set nonsense 1").Contains("unknown"), "unknown option is reported");
using (var doc = JsonDocument.Parse(t.BuildJson()))
{
var root = doc.RootElement;
Check.Eq(root.GetProperty("rows").GetArrayLength(), 4, "all rows by default");
Check.Eq(root.GetProperty("rows")[0].GetProperty("where").GetString(), "Valley of Death", "server order by default");
Check.Eq(root.GetProperty("minRefreshSeconds").GetInt32(), 5, "camelCase option names");
}
t.Command("set hideqblocked 1");
t.Command("set sortbyprogress on");
string json = t.BuildJson();
using (var doc = JsonDocument.Parse(json))
{
var rows = doc.RootElement.GetProperty("rows");
Check.Eq(rows.GetArrayLength(), 3, "QB-locked row hidden");
Check.Eq(doc.RootElement.GetProperty("hiddenCount").GetInt32(), 1, "and counted");
Check.Eq(rows[0].GetProperty("where").GetString(), "Halls of Metos", "closest first: 9 of 10");
Check.Eq(rows[2].GetProperty("where").GetString(), "Thaelaryn Island", "cooldowns after counting rows");
}
#if ENGINE_BOUNTIES
var snap = RynthCore.Engine.UI.Data.BountiesSnapshot.Parse(json);
Check.NotNull(snap, "the engine parses the plugin's JSON");
Check.True(snap!.HideQbLocked && snap.SortByProgress, "engine sees the options");
Check.Eq(snap.MinRefreshSeconds, 5, "engine sees MinRefreshSeconds");
Check.Eq(snap.HiddenCount, 1, "engine sees the hidden count");
Check.Eq(snap.Rows.Count, 3, "engine sees the rows");
var cd = snap.Rows.Single(r => r.Where == "Thaelaryn Island");
Check.Eq(cd.Status, (int)RynthCore.Engine.UI.Data.BountyRowStatus.Cooldown, "engine status enum matches the plugin's");
Check.True(cd.UnlockInSec > 100 && cd.UnlockInSec <= 120, $"cooldown seconds left ({cd.UnlockInSec})");
Check.Eq(cd.CooldownSeconds, 300, "cooldown length");
var halls = snap.Rows[0];
Check.True(halls.Kills == 9 && halls.KillsRequired == 10 && halls.Amount == 1 && halls.Item == "Ascension Coin", "row fields");
#endif
}
// ── Helpers ────────────────────────────────────────────────────────────────
private sealed class Clock { public long Ms = 1_000_000; }
private static BountyTracker New(out Clock clock, out List<string> sent, out List<string> chat, string file = "")
{
var c = new Clock();
var s = new List<string>();
var ch = new List<string>();
if (file.Length > 0) Directory.CreateDirectory(Path.GetDirectoryName(file)!);
var t = new BountyTracker(s.Add, ch.Add, _ => { }, file, () => c.Ms);
clock = c;
sent = s;
chat = ch;
return t;
}
private static int Reads(List<string> sent) => sent.Count(x => x == BountyTracker.ListCommand);
/// <summary>Advances the clock in 250 ms steps, ticking; with the window open the engine polls every second.</summary>
private static void Run(BountyTracker t, Clock clock, long ms, bool windowOpen)
{
for (long elapsed = 0; elapsed < ms; elapsed += 250)
{
clock.Ms += 250;
if (windowOpen && elapsed % 1000 == 0) t.BuildJson();
t.Tick();
}
}
}

View file

@ -0,0 +1,379 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using RynthCore.Plugin.RynthILT;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The pet breeding tracker (IltBreedingRules / IltBreedingEssence / IltBreedingSupplies / IltPetBreeding):
// the server's rules and where each value came from, the parsers for ACECustom's appraisal block,
// chat and "@breed-debug" (formats copied from PetDevice_Breeding.cs / PetDevice_Maturity.cs), each
// breeding gate, the pair planner's odds, the supply refusals, and the JSON RynthOracle reads.
internal static class BreedingTests
{
public static void Register(Runner r)
{
r.Add("breeding: tier table has one WCID per tier in every family, no repeats", TierTable);
r.Add("breeding: rules come from the server, else the ILT profile, else ACE", RuleSources);
r.Add("breeding: stat mutation odds follow ACE's decay, floor and incense cap", MutationOdds);
r.Add("breeding: appraisal text gives the stud's charges, refill window and growth", AppraisalParse);
r.Add("breeding: chat lines give charges, the guardian, growth stages and events", ChatParse);
r.Add("breeding: @breed-debug reply is captured whole or line by line and parsed", DebugParse);
r.Add("breeding: each gate (charges, rest, growth, neutered, shiny, bond, tier, ID)", Gates);
r.Add("breeding: pair planner blocks wrong sexes and ranges the inherited mutations", Planner);
r.Add("breeding: supplies are refused where the server would refuse them", Supplies);
r.Add("breeding: reader JSON round-trips through RynthOracle's view", ReaderJson);
r.Add("breeding: saved state survives the hub.json source-generated serializer", StateJson);
r.Add("breeding: RynthILT.Data v2 keeps v1 readers working", DataApiVersion);
}
private static IltBreedingRules Rules() => new(new IltBreedingState());
/// <summary>A healthy adult essence's facts (tier 150, bond 120, appraised).</summary>
private static BreedEssenceFacts Facts(int id, bool male, uint wcid = 48946) => new()
{
Id = id,
Name = (male ? "Stud " : "Dam ") + id,
Wcid = wcid,
HasId = true,
Bond = 120,
MaleOverride = male,
};
private static void TierTable()
{
var seen = new HashSet<uint>();
foreach (uint[] row in IltBreedingEssence.Families)
{
Check.Eq(row.Length, IltBreedingEssence.Tiers.Length, "row " + row[0]);
foreach (uint w in row) Check.True(seen.Add(w), "WCID " + w + " appears once");
}
Check.Eq(IltBreedingEssence.Families.Length, 36, "36 combat pet families");
Check.Eq(IltBreedingEssence.TierOf(48942), 50, "first fire skeleton is tier 50");
Check.Eq(IltBreedingEssence.TierOf(49212), 200, "an out-of-run WCID keeps its slot (tier 200)");
Check.Eq(IltBreedingEssence.TierOf(787801072), 300, "the last tier-300 essence");
Check.Eq(IltBreedingEssence.TierOf(12345, 125), 125, "unknown WCID: a tier-valued level requirement");
Check.Eq(IltBreedingEssence.TierOf(12345, 126), 0, "unknown WCID, odd level: unknown tier");
Check.True(IltBreedingEssence.IsCombatEssence(49551), "range end is included");
}
private static void RuleSources()
{
IltBreedingRules r = Rules();
Check.Eq(r.Value(IltBreedingRules.MinTier).Source, BreedRuleSource.AceDefault, "min tier: ACE default");
Check.Eq(r.GetInt(IltBreedingRules.MinTier), 100, "min tier 100");
Check.Eq(r.Value(IltBreedingRules.MutationDecay).Source, BreedRuleSource.IltProfile, "decay: ILT profile");
Check.Near(r.Get(IltBreedingRules.MutationDecay), 0.1, 1e-9, "ILT decay 0.1");
Check.Near(r.Get(IltBreedingRules.GuardianEnabled), 1, 1e-9, "ILT runs the mating guardian");
DateTime t = new(2026, 10, 15, 12, 0, 0, DateTimeKind.Utc);
Check.True(r.Learn(IltBreedingRules.MaleCharges, 12, t), "a new value is a change");
Check.False(r.Learn(IltBreedingRules.MaleCharges, 12, t), "the same value again isn't");
Check.Eq(r.Value(IltBreedingRules.MaleCharges).Source, BreedRuleSource.Server, "learned: seen on server");
Check.Eq(r.GetInt(IltBreedingRules.MaleCharges), 12, "learned value wins");
Check.False(r.Learn("not_a_rule", 1, t), "unknown keys are ignored");
Check.Eq(r.RoomText(), "landblock 0x0106 variant 2", "Seedy Motel room");
IltBreedingRules frozen = r.Frozen();
r.Learn(IltBreedingRules.MaleCharges, 8, t);
Check.Eq(frozen.GetInt(IltBreedingRules.MaleCharges), 12, "a frozen copy doesn't follow later learning");
Check.Eq(r.StageName(2), "Whelp", "default stage names");
Check.True(r.LearnStageName(2, "Pup"), "a server's own stage name");
Check.Eq(r.StageName(2), "Pup", "seen name wins");
for (int i = 0; i < IltBreedingRules.MaxEvents + 5; i++) r.AddEvent("x", "e" + i, t);
Check.Eq(r.State.Log.Count, IltBreedingRules.MaxEvents, "event log is capped");
Check.Eq(r.State.Log[^1].Text, "e" + (IltBreedingRules.MaxEvents + 4), "newest kept last");
}
private static void MutationOdds()
{
IltBreedingRules r = Rules();
Check.Near(r.StatMutationChance(0, 0), 0.05, 1e-9, "base 5%");
Check.Near(r.StatMutationChance(4, 0), 0.05 / 1.4, 1e-9, "decay 0.1 x 4 mutations");
Check.Near(r.StatMutationChance(0, 0.10), 0.15, 1e-9, "exquisite incense adds 10%");
Check.Near(r.CombinedIncense(0.4, 0.3), 0.5, 1e-9, "both parents' incense capped at 50%");
r.Learn(IltBreedingRules.MutationDecay, 10, DateTime.UtcNow);
Check.Near(r.StatMutationChance(4, 0), 0.02, 1e-9, "never below the 2% floor");
}
private static void AppraisalParse()
{
double now = 1_800_000_000;
double lastRefill = now - (20 * 3600 + 50 * 60);
string desc = "A fire skeleton essence.\nSex: Male (9/12 breeding charges today) - refills in 3h 10m\nBond: Unbound (imprints on first summon)";
var seen = IltBreedingRules.FromAppraisal(desc, lastRefill, now);
Check.True(seen.Contains((IltBreedingRules.MaleCharges, 12)), "max charges from the stud line");
Check.True(seen.Contains((IltBreedingRules.MaleRefillHours, 24)), "refill window from the countdown");
string growth = "Sex: Female (ready to breed)\nGrowth: Whelp 2/5 - 75 kills to Juvenile, 195 to Adult";
Check.True(IltBreedingRules.FromAppraisal(growth, 0, now).Contains((IltBreedingRules.MaturityStages, 5)), "stage count");
Check.True(IltBreedingRules.TryParseGrowth(growth, out string name, out int stage, out int stages, out int toNext, out string next, out int toAdult), "growth line");
Check.Eq(name, "Whelp", "stage name");
Check.Eq(stage, 2, "stage");
Check.Eq(stages, 5, "stages");
Check.Eq(toNext, 75, "to next");
Check.Eq(next, "Juvenile", "next stage");
Check.Eq(toAdult, 195, "to adult");
Check.True(IltBreedingRules.TryParseGrowth("Growth: Young Adult 5/5 - 60 kills to Adult", out name, out stage, out _, out toNext, out next, out toAdult), "last stage");
Check.Eq(name, "Young Adult", "two-word stage name");
Check.Eq(next, "Adult", "last stage leads to Adult");
Check.Eq(toAdult, 60, "last stage: to adult = to next");
Check.False(IltBreedingRules.TryParseGrowth("Growth: Adult", out _, out _, out _, out _, out _, out _), "an adult has no countdown");
}
private static void ChatParse()
{
var a = IltBreedingRules.FromChat("[Breeding] Fire Skeleton Essence spent a breeding charge: 7/12 left today.");
Check.True(a.Contains((IltBreedingRules.MaleCharges, 12)), "charge line gives the max");
var g = IltBreedingRules.FromChat("The union stirs something... Mating Spirit rises before A and B! Only the two parents can harm it. They have 120s to bring it down together.");
Check.True(g.Contains((IltBreedingRules.GuardianEnabled, 1)), "guardian on");
Check.True(g.Contains((IltBreedingRules.GuardianSeconds, 120)), "guardian timer");
var d = IltBreedingRules.FromChat("[Breeding] Your pet performs the courtship dance, waiting for a partner... (Your partner must have their pet summoned in the same room and *dance* within 5 seconds).");
Check.True(d.Contains((IltBreedingRules.DanceWindow, 5)), "dance window");
Check.Eq(IltBreedingRules.FromChat("You say, \"hello\"").Count, 0, "ordinary chat says nothing");
Check.True(IltBreedingRules.TryParseGrownInto("Pup has grown into a Whelp! Its body swells with new strength. (2/5)", out int stage, out string name), "growth line");
Check.Eq(stage, 2, "stage number");
Check.Eq(name, "Whelp", "stage name");
Check.Eq(IltPetBreeding.EventKind("The mating ritual has begun between A and B..."), "ritual", "ritual");
Check.Eq(IltPetBreeding.EventKind("Congratulations! A baby pet has been born: Pup! Placed in Bob's inventory."), "birth", "birth");
Check.Eq(IltPetBreeding.EventKind("A baby pet has been born: Pup! Bob's packs are full, so the baby has been tucked away"), "birth", "deferred birth");
Check.Eq(IltPetBreeding.EventKind("Pup has reached adulthood! It stands at its full size"), "adult", "adulthood");
Check.Eq(IltPetBreeding.EventKind("Pup has imprinted on you. It is now bound to this character"), "imprint", "imprint");
Check.Eq(IltPetBreeding.EventKind("[Breeding] The spectral guardian dissolves back into the ether..."), "guardian", "guardian lost");
Check.Eq(IltPetBreeding.EventKind("Bob tells you, \"breed?\""), null, "not a breeding line");
}
private const string DebugReply =
"=== PET BREEDING DIAGNOSTICS ===\n" +
"Breeding System Enabled: True\n" +
"Your Location: Landblock=0x0106, Cell=0x01060186, Variant=2\n" +
"Allowed Target: whole landblock 0x106, Variant=2 => Location Match: VALID (Room OK)\n" +
"Your Active Pet: Fire Skeleton (WCID 48900) | Device: Fire Skeleton Essence\n" +
" Sex: Male (9/10 charges)\n" +
"Eligible breeding partners nearby: 1\n" +
"================================\n";
private static void DebugParse()
{
Check.True(IltBreedingRules.IsDebugLine(DebugReply.TrimEnd('\n')), "whole message is a reply line");
Check.True(IltBreedingRules.IsDebugEnd(DebugReply.TrimEnd('\n')), "whole message ends the reply");
Check.True(IltBreedingRules.IsDebugEnd("================================"), "rule line alone ends it");
Check.False(IltBreedingRules.IsDebugEnd("=== PET BREEDING DIAGNOSTICS ==="), "the header doesn't");
Check.False(IltBreedingRules.IsDebugLine("Bob says, \"hi\""), "chat isn't");
BreedDebugInfo whole = IltBreedingRules.ParseDebug(new[] { DebugReply });
BreedDebugInfo split = IltBreedingRules.ParseDebug(DebugReply.Split('\n'));
foreach (BreedDebugInfo d in new[] { whole, split })
{
Check.Eq(d.Enabled, (bool?)true, "enabled");
Check.Eq(d.AllowedLandblock, 0x106u, "landblock");
Check.Eq(d.AllowedVariant, 2, "variant");
Check.Eq(d.AllowedKind, "whole landblock", "kind");
Check.Eq(d.LocationOk, (bool?)true, "in the room");
Check.Eq(d.Partners, 1, "partners");
Check.Eq(d.PetSex, "Male (9/10 charges)", "pet sex line");
}
var rules = IltBreedingRules.FromChat(DebugReply);
Check.True(rules.Contains((IltBreedingRules.Landblock, 0x106)), "room landblock learned");
Check.True(rules.Contains((IltBreedingRules.Variant, 2)), "room variant learned");
}
private static void Gates()
{
IltBreedingRules r = Rules();
double now = 1_800_000_000;
BreedEssence full = IltBreedingEssence.Evaluate(Facts(1, true), r, now);
Check.True(full.Ready, "a stud that never bred is full");
Check.Eq(full.Charges, 10, "10 charges");
Check.Eq(full.Tier, 125, "48946 is tier 125");
var spent = Facts(2, true);
spent.MaleCharges = 0;
spent.MaleRefreshUnix = now - 2 * 3600;
BreedEssence noCharge = IltBreedingEssence.Evaluate(spent, r, now);
Check.Eq(noCharge.Gate, BreedGate.NoCharges, "no charges");
Check.Near(noCharge.ReadyAtUnix, now + 22 * 3600, 1, "refills 24h after the last refill");
spent.MaleRefreshUnix = now - 25 * 3600;
Check.True(IltBreedingEssence.Evaluate(spent, r, now).Ready, "refilled once the window passed (the server refills on read)");
var dam = Facts(3, false);
dam.NextBreedUnix = now + 3600 + 300;
BreedEssence resting = IltBreedingEssence.Evaluate(dam, r, now);
Check.Eq(resting.Gate, BreedGate.Resting, "resting dam");
Check.Eq(resting.Status, "Rest 1h 05m", "rest countdown");
var neut = Facts(4, false);
neut.Neutered = true;
Check.Eq(IltBreedingEssence.Evaluate(neut, r, now).Gate, BreedGate.Neutered, "neutered");
var shiny = Facts(5, true);
shiny.LongDesc = "Sex: Male (shiny - cannot breed)";
Check.Eq(IltBreedingEssence.Evaluate(shiny, r, now).Gate, BreedGate.Shiny, "shiny");
var baby = Facts(6, false);
baby.JuvenileFlag = true;
baby.MaturityKills = 130;
BreedEssence growing = IltBreedingEssence.Evaluate(baby, r, now);
Check.Eq(growing.Gate, BreedGate.Growing, "juvenile");
Check.Eq(growing.Stage, 3, "130 kills of 300 over 5 stages: stage 3");
Check.Eq(growing.StageName, "Juvenile", "stage 3 name");
Check.Eq(growing.KillsToNext, 50, "50 kills to stage 4");
var weak = Facts(7, true);
weak.Bond = 40;
Check.Eq(IltBreedingEssence.Evaluate(weak, r, now).Gate, BreedGate.LowBond, "bond under 100");
BreedEssence low = IltBreedingEssence.Evaluate(Facts(8, true, 48944), r, now);
Check.Eq(low.Gate, BreedGate.LowTier, "tier 80 is under the minimum");
var unread = Facts(9, true);
unread.HasId = false;
Check.Eq(IltBreedingEssence.Evaluate(unread, r, now).Gate, BreedGate.NeedsId, "not appraised yet");
var boosted = Facts(10, false);
boosted.Incense = 0.05;
boosted.Catalyst = true;
BreedEssence b = IltBreedingEssence.Evaluate(boosted, r, now);
Check.Eq(string.Join("|", b.Boosters), "Refined incense +5%|Chromatic Catalyst", "boosters listed");
}
private static void Planner()
{
IltBreedingRules r = Rules();
double now = 1_800_000_000;
var sf = Facts(1, true);
sf.MutDamage = 2;
sf.MutCrit = 1;
sf.Incense = 0.10;
var df = Facts(2, false);
df.MutDamage = 0;
df.MutCrit = 3;
BreedEssence stud = IltBreedingEssence.Evaluate(sf, r, now), dam = IltBreedingEssence.Evaluate(df, r, now);
BreedPairPlan p = IltBreedingPlanner.Plan(stud, dam, r);
Check.True(p.CanBreed, "both ready");
Check.Eq(p.InheritMin, 1, "lower lines: damage 0 + crit 1");
Check.Eq(p.InheritMax, 5, "higher lines: damage 2 + crit 3");
Check.Near(p.ChanceBest, 0.15 / 1.1, 1e-9, "best: 1 mutation, incense 10%");
Check.Near(p.ChanceWorst, 0.15 / 1.5, 1e-9, "worst: 5 mutations");
Check.Near(p.PotencyChance, 0.03, 1e-9, "potency 3%");
BreedPairPlan wrong = IltBreedingPlanner.Plan(dam, stud, r);
Check.False(wrong.CanBreed, "swapped sexes");
Check.True(wrong.Blockers.Any(b => b.Contains("must be male")), "says the stud must be male");
}
private static void Supplies()
{
IltBreedingRules r = Rules();
double now = 1_800_000_000;
BreedSupplyDef lesser = IltBreedingSupplies.Find(IltBreedingSupplies.LesserIncense)!;
BreedSupplyDef exquisite = IltBreedingSupplies.Find(IltBreedingSupplies.ExquisiteIncense)!;
BreedSupplyDef draught = IltBreedingSupplies.Find(IltBreedingSupplies.Draught)!;
BreedSupplyDef offering = IltBreedingSupplies.Find(IltBreedingSupplies.Offering)!;
BreedSupplyDef neuter = IltBreedingSupplies.Find(IltBreedingSupplies.NeuteringKit)!;
var f = Facts(1, false);
f.Incense = 0.05;
BreedEssence primed = IltBreedingEssence.Evaluate(f, r, now);
Check.NotNull(IltBreedingSupplies.RefuseReason(lesser, primed, r), "weaker incense refused");
Check.Null(IltBreedingSupplies.RefuseReason(exquisite, primed, r), "stronger incense taken");
Check.True(IltBreedingSupplies.Warning(exquisite, primed).Contains("+5%"), "and warns the +5% is lost");
var n = Facts(2, false);
n.Neutered = true;
Check.NotNull(IltBreedingSupplies.RefuseReason(lesser, IltBreedingEssence.Evaluate(n, r, now), r), "no incense on a neutered essence");
BreedEssence adult = IltBreedingEssence.Evaluate(Facts(3, true), r, now);
Check.NotNull(IltBreedingSupplies.RefuseReason(draught, adult, r), "draught: juveniles only");
var j = Facts(4, true);
j.JuvenileFlag = true;
j.MaturityKills = 0;
Check.Null(IltBreedingSupplies.RefuseReason(draught, IltBreedingEssence.Evaluate(j, r, now), r), "draught on a juvenile");
j.MaturityXpMult = 2.0;
Check.NotNull(IltBreedingSupplies.RefuseReason(draught, IltBreedingEssence.Evaluate(j, r, now), r), "not twice");
Check.Null(IltBreedingSupplies.RefuseReason(offering, adult, r), "offering with the guardian on");
r.Learn(IltBreedingRules.GuardianEnabled, 0, DateTime.UtcNow);
Check.NotNull(IltBreedingSupplies.RefuseReason(offering, adult, r), "offering refused with the guardian off");
Check.NotNull(IltBreedingSupplies.RefuseReason(neuter, adult, r), "the neutering kit is never used from here");
Check.Eq(IltBreedingSupplies.PriceText(1_250_000), "1.25M", "price text");
}
private static void ReaderJson()
{
IltBreedingRules r = Rules();
double now = 1_800_000_000;
var stud = IltBreedingEssence.Evaluate(Facts(11, true), r, now);
var dam = IltBreedingEssence.Evaluate(Facts(12, false), r, now);
var events = new[] { new IltBreedingEvent { Utc = new DateTime(2026, 10, 15, 20, 0, 0, DateTimeKind.Utc), Kind = "birth", Text = "A \"baby\" was born" } };
var supplies = IltBreedingSupplies.All.Select(s => (s, s.Key == IltBreedingSupplies.RefinedIncense ? 2L : 0L)).ToList();
var snap = new BreedingSnapshot(new[] { stud, dam }, supplies, r.All(), events,
IltBreedingRules.ParseDebug(new[] { DebugReply }), DateTime.UtcNow, IltTri.On, IltTri.On, IltTri.On,
r.RoomText(), 5, "hello", now, true, r.Frozen());
string json = IltPetBreeding.BuildJson(snap, r, "InfiniteLeaftide");
using (JsonDocument.Parse(json)) { } // well-formed
IltBreedingView v = IltBreedingView.Parse(json);
Check.True(v.Loaded && v.Available, "loaded");
Check.Eq(v.Enabled, "on", "enabled");
Check.Eq(v.Room, "landblock 0x0106 variant 2", "room");
Check.Eq(v.FreeSlots, 5, "free slots");
Check.Eq(v.Essences.Count, 2, "two essences");
Check.True(v.Essences[0].Male && v.Essences[0].Ready, "stud row");
Check.Eq(v.Pairs.Count, 1, "one ready pairing");
Check.Near(v.Pairs[0].ChanceBest, 0.05, 1e-6, "pair odds");
IltBreedSupplyRow refined = v.Supplies.First(s => s.Key == IltBreedingSupplies.RefinedIncense);
Check.Eq(refined.Count, 2L, "supply count");
Check.Eq(refined.Targets.Count, 2, "both essences can take it");
Check.Eq(v.Supplies.First(s => s.Key == IltBreedingSupplies.LesserIncense).Targets.Count, 0, "none carried: no targets");
Check.Eq(v.Rules.Count, IltBreedingRules.Defs.Length, "every rule");
Check.Eq(v.Events[0].Text, "A \"baby\" was born", "quotes escaped and read back");
Check.Eq(v.Debug?.Match, "valid", "diagnostics");
Check.Eq(IltBreedingView.ApplyVerb(" incense2 ", 12), "apply incense2 12", "apply verb");
}
private static void StateJson()
{
var state = new IltHubState();
var rules = new IltBreedingRules(state.Pet.Breeding);
rules.Learn(IltBreedingRules.MaleCharges, 12, new DateTime(2026, 10, 15, 0, 0, 0, DateTimeKind.Utc));
rules.LearnStageName(1, "Hatchling");
rules.AddEvent("birth", "born", DateTime.UtcNow);
string json = JsonSerializer.Serialize(state, IltHubJsonContext.Default.IltHubState);
IltHubState back = JsonSerializer.Deserialize(json, IltHubJsonContext.Default.IltHubState)!;
var again = new IltBreedingRules(back.Pet.Breeding);
Check.Eq(again.GetInt(IltBreedingRules.MaleCharges), 12, "learned rule saved");
Check.Eq(again.StageName(1), "Hatchling", "stage name saved");
Check.Eq(back.Pet.Breeding.Log.Count, 1, "event saved");
IltHubState old = JsonSerializer.Deserialize("{\"Pet\":{\"PetLog\":[\"a\"]}}", IltHubJsonContext.Default.IltHubState)!;
Check.NotNull(old.Pet.Breeding, "a hub.json from before the tracker gets an empty breeding state");
}
private static unsafe void DataApiVersion()
{
// Version 3 (the Temple guardians) appends after the breeding pair; a v2 reader sees the same breeding layout.
Check.Eq(RynthIltDataApiV1.InterfaceVersion, 3u, "version 3");
Check.True(RynthIltDataApiV1.V1Size < RynthIltDataApiV1.V2Size && RynthIltDataApiV1.V2Size < (uint)sizeof(RynthIltDataApiV1),
"v2 appends to v1, v3 to v2");
Check.Eq(RynthIltDataApiV1.V1Size, (uint)(8 + 4 * sizeof(IntPtr)), "v1 = two uints and four function pointers");
Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1) != IntPtr.Zero, "v1 readers still get the table");
Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 2) != IntPtr.Zero, "v2 readers too");
Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 3) != IntPtr.Zero, "v3 readers too");
Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 4) == IntPtr.Zero, "a future version isn't claimed");
var t = (RynthIltDataApiV1*)DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1);
Check.True(t->GetPetBreedingJson != null && t->PetBreedingCommand != null, "breeding functions filled");
Check.Eq(RynthIltHub.SectionPetBreeding, "pets-breeding", "section id");
}
}

View file

@ -0,0 +1,173 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The chunk rules end to end: a fake inventory with the Lugian Aetheria Hammer and one candidate,
// IltChunkClap.Tick, and whether the hammer was used on the candidate. These cover what the pure
// rule tests (AetheriaChunkTests) cannot: the properties as RynthILT reads them from the host, an
// item that is not appraised, and a host that cannot tell whether an appraisal arrived. The hammer
// destroys what it is used on, so "used on it" is the thing to get right.
internal static class ChunkTargetTests
{
private const uint Player = 0x50000F01;
private const uint Hammer = 0x5000A001;
private const uint Item = 0x5000A002;
private const uint ItemTypeGem = 0x00000800;
private const uint ItemTypeMelee = 0x00000001;
private const uint ItemTypeMisc = 0x00000080;
public static void Register(Runner r)
{
r.Add("chunk (live path): unlevelled Coalesced chunks only when its level was truly read as none", UnlevelledVsUnreadable);
r.Add("chunk (live path): levelled Coalesced Aetheria obeys the cap; other aetheria needs a level", LevelledCap);
r.Add("chunk (live path): corrupted two-handed cleave 2 chunks, other corrupted cleave 2 does not", CorruptedCleave);
r.Add("chunk (live path): corrupted keep rules and the rating level are off by default and protect when on", KeepRulesLive);
r.Add("chunk (live path): a busy client in combat chunks with chunk-in-combat on, not off; peace waits for idle", CombatBusy);
}
/// <summary>One chunk pass on a fake pack. Returns the targets the hammer was used on.</summary>
private static List<uint> Pass(string folder, Action<IltGearState> settings, Action<uint> candidate,
uint itemType = ItemTypeGem, string name = "Coalesced Aetheria", bool appraised = true,
bool hostCanSayAppraised = true, bool busy = false, int combatMode = 1)
{
FakeHost.Reset();
FakeHost.WorldName = "InfiniteLeaftide";
FakeHost.ContentsCalls = true;
FakeHost.UseOnCalls = true;
FakeHost.WeaponCalls = hostCanSayAppraised; // installs HasAppraisalData / RequestId / combat mode
FakeHost.BusyCalls = true;
FakeHost.BusyStateValue = busy ? 1 : 0;
FakeHost.CombatModeValue = combatMode;
FakeHost.Names[Hammer] = "Lugian Aetheria Hammer"; FakeHost.ItemTypes[Hammer] = ItemTypeMisc; FakeHost.Containers[Hammer] = Player;
FakeHost.Names[Item] = name; FakeHost.ItemTypes[Item] = itemType; FakeHost.Containers[Item] = Player;
if (appraised) FakeHost.Appraised.Add(Item);
candidate(Item);
var host = FakeHost.Create(Player);
string dir = Path.Combine(Program.TempRoot, "chunk-" + folder);
Directory.CreateDirectory(dir);
var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host));
var g = hub.State.Gear;
g.AutoChunkAetheria = true;
g.AutoChunkCorrupted = true;
settings(g);
hub.Gear.ChunkClap.Tick(10_000);
return FakeHost.UsesOn.Where(u => u.Source == Hammer).Select(u => u.Target).ToList();
}
private static void Ints(uint id, params (uint Key, int Value)[] values)
{
foreach (var (k, v) in values) FakeHost.Ints[(id, k)] = v;
}
private static void UnlevelledVsUnreadable()
{
// Truly unlevelled: the appraisal arrived and the item has no level (int 319), no XP, no tinks.
Check.Eq(Pass("coal-unlevelled", _ => { }, _ => { }).Count, 1, "appraised, no level: chunked (ub-IT)");
// Even with the cap at its lowest.
Check.Eq(Pass("coal-unlevelled-cap1", g => g.ChunkAetheriaUnderLevel = 1, _ => { }).Count, 1, "cap 1 does not stop an unlevelled one");
// Not appraised yet: nothing is known, so it is asked for, not hammered.
var asked = Pass("coal-unappraised", _ => { }, _ => { }, appraised: false);
Check.Eq(asked.Count, 0, "not appraised: not chunked");
Check.True(FakeHost.IdRequests.Contains(Item), "its appraisal is requested");
// The host cannot say whether an appraisal arrived: a level of 0 might be a failed read.
Check.Eq(Pass("coal-unreadable", _ => { }, _ => { }, hostCanSayAppraised: false).Count, 0,
"host cannot confirm the appraisal: kept, not chunked");
// The same unconfirmable host with a read level still keeps (no half-trusted piece is hammered).
Check.Eq(Pass("coal-unreadable-lvl", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 2)), hostCanSayAppraised: false).Count, 0,
"host cannot confirm the appraisal: even a read level 2 is kept");
// A revealed (non-Coalesced) aetheria with no level is never chunked.
Check.Eq(Pass("rev-unlevelled", _ => { }, _ => { }, name: "Blue Aetheria").Count, 0, "revealed aetheria with no level: kept");
// Item XP, tinks or the never-chunk flag keep it.
Check.Eq(Pass("coal-xp", _ => { }, id => FakeHost.Quads[(id, IltInventory.QuadItemTotalXp)] = 500).Count, 0, "has item XP: kept");
Check.Eq(Pass("coal-tinked", _ => { }, id => Ints(id, (IltInventory.IntNumTimesTinkered, 1))).Count, 0, "tinkered: kept");
Check.Eq(Pass("coal-never", _ => { }, id => FakeHost.Bools[(id, IltInventory.BoolNeverChunk)] = true).Count, 0, "never-chunk flag: kept");
}
private static void LevelledCap()
{
Check.Eq(Pass("cap-l3", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 3))).Count, 1, "level 3 under the default cap of 4");
Check.Eq(Pass("cap-l4", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 4))).Count, 0, "level 4 at the default cap of 4: kept");
Check.Eq(Pass("cap9-l8", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 8))).Count, 1, "level 8 under a cap of 9");
Check.Eq(Pass("cap9-l9", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 9))).Count, 0, "level 9 at a cap of 9: kept");
Check.Eq(Pass("cap9-l10", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 10))).Count, 0, "level 10 over a cap of 9: kept");
Check.Eq(Pass("cap11-l10", g => g.ChunkAetheriaUnderLevel = 11, id => Ints(id, (IltInventory.IntItemMaxLevel, 10))).Count, 1, "cap 11 chunks every level");
Check.Eq(Pass("rev-l2", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 2)), name: "Blue Aetheria").Count, 1, "a levelled revealed piece under the cap");
}
private static void CorruptedCleave()
{
void Weapon(uint id, int cleave, int wieldSkill = 45, int weaponType = 0, int attackType = 4) =>
Ints(id, (IltInventory.IntItemWorkmanship, 6), (IltInventory.IntCleaving, cleave), (IltInventory.IntWieldSkillType, wieldSkill),
(IltInventory.IntWeaponType, weaponType), (IltInventory.IntAttackType, attackType));
Check.Eq(Pass("cor-1h-c1", _ => { }, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword").Count, 1, "one-handed cleave 1 chunks");
Check.Eq(Pass("cor-1h-c2", _ => { }, id => Weapon(id, 2), ItemTypeMelee, "Corrupted Sword").Count, 0, "one-handed cleave 2 is kept");
Check.Eq(Pass("cor-2h-c2", _ => { }, id => Weapon(id, 2, wieldSkill: 41), ItemTypeMelee, "Corrupted Greatsword").Count, 1, "two-handed cleave 2 chunks");
Check.Eq(Pass("cor-2h-c3", _ => { }, id => Weapon(id, 3, wieldSkill: 41), ItemTypeMelee, "Corrupted Greatsword").Count, 0, "two-handed cleave 3 is kept");
Check.Eq(Pass("cor-2h-thrust", _ => { }, id => Weapon(id, 2, wieldSkill: 41, attackType: 2), ItemTypeMelee, "Corrupted Spear").Count, 0, "two-handed thrust cleave 2 is kept");
Check.Eq(Pass("cor-nowork", _ => { }, id => Ints(id, (IltInventory.IntCleaving, 1)), ItemTypeMelee, "Corrupted Sword").Count, 0, "no workmanship read: kept");
Check.Eq(Pass("cor-unreadable", _ => { }, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword", hostCanSayAppraised: false).Count, 0,
"host cannot confirm the appraisal: kept");
Check.Eq(Pass("cor-off", g => g.AutoChunkCorrupted = false, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword").Count, 0, "auto-chunk corrupted off: not touched");
}
private static void KeepRulesLive()
{
var def = new IltGearState();
Check.True(!def.KeepCorruptedCrushingBlow && !def.KeepCorruptedBitingStrike && !def.KeepCorruptedArmorCleaving
&& !def.KeepCorruptedAnySlayer && !def.KeepCorruptedMultiStrike && !def.KeepCorruptedElementalBonus
&& !def.KeepCorruptedAnySpell && def.KeepCorruptedMaxDamageAtLeast == 0 && def.KeepCorruptedSpellIds == "",
"every corrupted keep rule is off by default");
Check.Eq(def.KeepAetheriaRatingAtLeast, 1, "the rating level defaults to 1 (any rating keeps, as before)");
void Loaded(uint id)
{
Ints(id, (IltInventory.IntItemWorkmanship, 6), (IltInventory.IntCleaving, 1), (IltInventory.IntAttackType, 160),
(IltInventory.IntSlayerCreatureType, 5), (IltInventory.IntElementalDamageBonus, 10), (IltInventory.IntDamage, 400));
FakeHost.Doubles[(id, IltInventory.FloatCriticalFrequency)] = 0.1;
FakeHost.Doubles[(id, IltInventory.FloatCriticalMultiplier)] = 1.5;
FakeHost.Doubles[(id, IltInventory.FloatIgnoreArmor)] = 0.2;
FakeHost.SpellIds[id] = new uint[] { 2072 };
}
int Run(string tag, Action<IltGearState> s) => Pass("keep-" + tag, s, Loaded, ItemTypeMelee, "Corrupted Sword").Count;
Check.Eq(Run("none", _ => { }), 1, "a loaded corrupted weapon chunks while every keep rule is off");
Check.Eq(Run("crush", g => g.KeepCorruptedCrushingBlow = true), 0, "Crushing Blow on: kept");
Check.Eq(Run("bite", g => g.KeepCorruptedBitingStrike = true), 0, "Biting Strike on: kept");
Check.Eq(Run("armor", g => g.KeepCorruptedArmorCleaving = true), 0, "Armor Cleaving on: kept");
Check.Eq(Run("slayer", g => g.KeepCorruptedAnySlayer = true), 0, "slayer on: kept");
Check.Eq(Run("multi", g => g.KeepCorruptedMultiStrike = true), 0, "multi-strike on: kept");
Check.Eq(Run("elem", g => g.KeepCorruptedElementalBonus = true), 0, "elemental bonus on: kept");
Check.Eq(Run("maxdmg", g => g.KeepCorruptedMaxDamageAtLeast = 400), 0, "max damage 400 on: kept");
Check.Eq(Run("maxdmg-hi", g => g.KeepCorruptedMaxDamageAtLeast = 401), 1, "max damage above the weapon's: chunks");
Check.Eq(Run("spell", g => g.KeepCorruptedAnySpell = true), 0, "any spell on: kept");
Check.Eq(Run("spellid", g => g.KeepCorruptedSpellIds = "2072"), 0, "a listed spell id: kept");
Check.Eq(Run("spellid-other", g => g.KeepCorruptedSpellIds = "100"), 1, "another spell id: chunks");
// The rating level on a live Coalesced piece with a C 1 rating.
void C1(uint id) => Ints(id, (IltInventory.IntGearCrit, 1));
Check.Eq(Pass("rate-default", _ => { }, C1).Count, 0, "C 1 is kept at the default rating level");
Check.Eq(Pass("rate-2", g => g.KeepAetheriaRatingAtLeast = 2, C1).Count, 1, "C 1 chunks once the rating level is 2");
Check.Eq(Pass("rate-2-c2", g => g.KeepAetheriaRatingAtLeast = 2, id => Ints(id, (IltInventory.IntGearCrit, 2))).Count, 0, "C 2 is kept at level 2");
Check.Eq(Pass("rate-2-off", g => { g.KeepAetheriaRatingAtLeast = 2; g.KeepAetheriaWithCrit = false; }, id => Ints(id, (IltInventory.IntGearCrit, 5))).Count, 1,
"the C switch off ignores the rating level");
}
private static void CombatBusy()
{
Check.Eq(Pass("busy-combat-on", g => g.ChunkInCombat = true, _ => { }, busy: true, combatMode: 2).Count, 1,
"busy in combat mode with chunk-in-combat on: chunks");
Check.Eq(Pass("busy-combat-off", g => g.ChunkInCombat = false, _ => { }, busy: true, combatMode: 2).Count, 0,
"busy in combat mode with chunk-in-combat off: waits");
Check.Eq(Pass("idle-combat-on", g => g.ChunkInCombat = true, _ => { }, busy: false, combatMode: 2).Count, 1,
"idle in combat mode with chunk-in-combat on: chunks");
Check.Eq(Pass("busy-peace", g => g.ChunkInCombat = true, _ => { }, busy: true, combatMode: 1).Count, 0,
"busy in peace mode waits for idle even with chunk-in-combat on");
Check.Eq(Pass("idle-peace", g => g.ChunkInCombat = false, _ => { }, busy: false, combatMode: 1).Count, 1,
"idle in peace mode chunks");
}
}

View file

@ -0,0 +1,36 @@
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// Lugian-hammer chunking (Hub/IltChunkClap.cs): only the Lugian Aetheria Hammer is the tool, and
// ILT's result lines name the item and the tool. Ported from SilentKelpie's fix (2026-10-15).
internal static class ChunkTests
{
public static void Register(Runner r)
{
r.Add("chunk: only the Lugian Aetheria Hammer is the tool, never a Lugian Hammer weapon", HammerOnly);
r.Add("chunk: ILT's result lines (item and tool named) end the wait; combat lines don't", ResultLines);
}
/// <summary>The Flaming Lugian Hammer (a loot weapon) matched " Lugian Hammer", chunked nothing,
/// and all 9 Coalesced Aetheria timed out into the skip list.</summary>
private static void HammerOnly()
{
Check.True(IltChunkClap.IsChunkHammer("Lugian Aetheria Hammer"), "the ILT tool");
Check.True(IltChunkClap.IsChunkHammer("lugian aetheria hammer"), "any case");
Check.False(IltChunkClap.IsChunkHammer("Flaming Lugian Hammer"), "a loot weapon is not the tool");
Check.False(IltChunkClap.IsChunkHammer("Lugian Hammer"), "nor the plain one");
Check.False(IltChunkClap.IsChunkHammer("Acid Lugian Hammer"), "nor any variant");
}
private static void ResultLines()
{
Check.Eq(IltChunkClap.ClassifyChat("You smash the Corrupted Sword with the Lugian Aetheria Hammer."), IltChunkClap.ChunkResult.Done, "ILT corrupted line");
Check.Eq(IltChunkClap.ClassifyChat("You smash the aetheria with the hammer."), IltChunkClap.ChunkResult.Done, "aetheria line");
Check.Eq(IltChunkClap.ClassifyChat("The aetheria is too powerful to chunk."), IltChunkClap.ChunkResult.Refused, "refused");
Check.Eq(IltChunkClap.ClassifyChat("You're too busy!"), IltChunkClap.ChunkResult.Busy, "busy");
Check.Eq(IltChunkClap.ClassifyChat("You smash Corrupted Shadow for 147 points of bludgeoning damage!"), IltChunkClap.ChunkResult.None,
"a combat line naming a corrupted monster is no result");
}
}

View file

@ -0,0 +1,152 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthILT;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// "RynthILT.Data" v1 (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs): the bank JSON RynthILT
// builds (Hub/IltBankExport.cs) read back by the shared reader, the bank verb lines a reader sends
// (IltBanking.RunVerb splits them), and the table itself. The charms JSON is MoveTests'
// CharmsReaderJson. No plugin in this tree reads the interface yet.
internal static class DataApiTests
{
public static void Register(Runner r)
{
r.Add("data: the bank JSON reads back whole: characters (current first), choices, notes, log", BankRoundTrip);
r.Add("data: the bank verb lines carry their fields in RunVerb's order", BankVerbs);
r.Add("data: bad bank JSON reads as nothing", BankBadJson);
r.Add("data: the Temple guardian JSON reads back whole (switches, answer, hand-in, rows)", GuardianRoundTrip);
// Last: Release() switches the table off for the rest of the process.
r.Add("data: the RynthILT.Data table: query, functions, release", DataTable);
}
private static void BankRoundTrip()
{
var me = new IltBankState { Pyreals = 1_500_000, Luminance = 42, PrestigeCoins = 3,
LastUpdated = new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc).ToLocalTime() };
var alt = new IltBankState { Pyreals = 7, LegendaryKeys = 2, LastUpdated = DateTime.Now };
var tx = new List<IltBankTransaction>();
for (int i = 0; i < IltBankExport.MaxTransactions + 5; i++)
tx.Add(new IltBankTransaction { Timestamp = new DateTime(2026, 10, 1).AddMinutes(i), Type = i % 2 == 0 ? "Sent" : "Received",
Currency = "Pyreals", Amount = i, OtherPlayer = "Bob \"the\" Builder" });
string json = IltBankExport.Build(true, 1, "InfiniteLeaftide", "Zed",
new[] { new IltBankExport.Row("Alt", false, alt), new IltBankExport.Row("Zed", true, me) },
"Deposited 5 Pyreals", tx);
Check.True(json.All(c => c >= 0x20 && c <= 0x7E), "plain printable ASCII");
IltBankView v = IltBankView.Parse(json);
Check.True(v.Loaded && v.Available, "loaded, ILT");
Check.Eq(v.Enabled, 1, "the server has /bank");
Check.Eq(v.World, "InfiniteLeaftide", "world");
Check.Eq(v.Character, "Zed", "character");
Check.Eq(v.Result, "Deposited 5 Pyreals", "last result");
Check.Eq(v.Characters.Count, 2, "both characters");
Check.True(v.Characters[0].Current && v.Characters[0].Name == "Zed", "the current character first");
Check.Eq(v.Characters[0].Pyreals, 1_500_000L, "pyreals");
Check.Eq(v.Characters[0].PrestigeCoins, 3L, "prestige coins");
Check.Eq(v.Characters[0].UpdatedUtc, new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc), "updated, in UTC");
Check.Eq(v.Characters[1].LegendaryKeys, 2L, "the other character's keys");
Check.Eq(v.Deposits.Count, IltBankCommands.Deposits.Length, "every deposit choice");
Check.Eq(v.Withdrawals.Count, IltBankCommands.Withdrawals.Length, "every withdraw choice");
Check.Eq(v.Transfers.Count, IltBankCommands.Transfers.Length, "every transfer choice");
Check.True(v.Transfers.Single(t => t.Notes).Label == "Trade notes", "only trade notes count notes");
Check.Eq(v.Notes.Count, IltBankCommands.NoteDenominations.Length, "every note denomination");
Check.Eq(v.Notes[^1].Value, 250_000L, "MMD is 250K");
Check.Eq(v.Transactions.Count, IltBankExport.MaxTransactions, "the log is capped");
Check.Eq(v.Transactions[0].Amount, (long)(IltBankExport.MaxTransactions + 4), "newest first");
Check.Eq(v.Transactions[0].Player, "Bob \"the\" Builder", "quotes in a name survive");
}
private static void BankVerbs()
{
Check.Eq(IltBankView.RefreshVerb(), "refresh", "refresh");
Check.Eq(IltBankView.DepositVerb(3), "deposit 3", "deposit");
Check.Eq(IltBankView.WithdrawVerb(7, 4, 9), "withdraw 7 4 9", "withdraw: index, amount, note");
Check.Eq(IltBankView.TransferVerb(6, 2, 9, " Some Name "), "transfer 6 2 9 Some Name", "transfer: the name last, trimmed");
foreach (string verb in new[] { IltBankView.RefreshVerb(), IltBankView.DepositVerb(0), IltBankView.WithdrawVerb(0, 1, -1),
IltBankView.TransferVerb(0, 1, -1, "Bob") })
Check.True(verb.All(c => c >= 0x20 && c <= 0x7E), "ASCII verb (DataInterface refuses anything else): " + verb);
}
private static void BankBadJson()
{
Check.True(ReferenceEquals(IltBankView.Parse(null), IltBankView.None), "null");
Check.True(ReferenceEquals(IltBankView.Parse("{not json"), IltBankView.None), "broken");
Check.True(ReferenceEquals(IltBankView.Parse("[1,2]"), IltBankView.None), "not an object");
IltBankView empty = IltBankView.Parse("{}");
Check.True(empty.Loaded && !empty.Available && empty.Enabled == -1 && empty.Characters.Count == 0, "missing fields read as nothing known");
}
/// <summary>
/// Version 3: the guardian JSON RynthILT builds (IltGuardian.BuildJson) read back by the reader
/// RynthOracle's Quests tab uses, quotes and all.
/// </summary>
private static void GuardianRoundTrip()
{
var rows = new[]
{
new IltTempleAttrStatus("Strength", "Fiun \"Big\" Strongarm", 3, "Ready", "", true, true),
new IltTempleAttrStatus("Focus", "Fiun Thinker", 1, "Cooldown", "in 5h 2m", false, false),
};
string json = IltGuardian.BuildJson("InfiniteLeaftide", chat: true, auto: false, buy: true, cooldownHours: 20,
answer: "Pyreal", npc: "Guardian of Attribute Enlightenment", answerAgeSec: 42, heard: "What is \"coin\"?",
running: true, status: "handing Pyreal to Guardian...", syncedUtc: new DateTime(2026, 10, 18, 19, 5, 0, DateTimeKind.Utc), rows);
Check.True(json.All(c => c >= 0x20 && c <= 0x7E), "plain printable ASCII");
IltGuardianView v = IltGuardianView.Parse(json);
Check.True(v.Loaded && v.Available && v.World == "InfiniteLeaftide", "loaded, the world");
Check.True(v.Chat && !v.Auto && v.Buy && v.CooldownHours == 20, "the switches");
Check.True(v.Answer == "Pyreal" && v.Npc == "Guardian of Attribute Enlightenment" && v.AnswerAgeSec == 42 && v.Heard == "What is \"coin\"?",
"the last answer");
Check.True(v.Running && v.Status.StartsWith("handing Pyreal"), "the hand-in");
Check.Eq(v.SyncedUtc, new DateTime(2026, 10, 18, 19, 5, 0, DateTimeKind.Utc), "the /qb read time");
Check.Eq(v.Rows.Count, 2, "both rows");
Check.True(v.Rows[0].Npc == "Fiun \"Big\" Strongarm" && v.Rows[0].Count == 3 && v.Rows[0].Ready && v.Rows[0].Exact, "an exact, ready row");
Check.True(v.Rows[1].Eta == "in 5h 2m" && !v.Rows[1].Ready && !v.Rows[1].Exact, "an estimated row on cooldown");
IltGuardianView none = IltGuardianView.Parse(IltGuardian.BuildJson("x", false, false, false, 1, "", "", -1, "", false, "idle",
DateTime.MinValue, Array.Empty<IltTempleAttrStatus>()));
Check.True(none.Answer.Length == 0 && none.AnswerAgeSec == -1 && none.SyncedUtc == DateTime.MinValue && none.Rows.Count == 0,
"no answer, no /qb read, no rows");
}
private static unsafe void DataTable()
{
Check.Eq(DataInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not ours");
Check.Eq(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 4), IntPtr.Zero, "a newer version than we have: none");
var t = (RynthIltDataApiV1*)DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1);
Check.True(t != null, "v1 is served");
Check.Eq(t->Version, 3u, "Version 3 (v1 and v2 readers take it: it starts with their tables)");
Check.Eq(t->StructSize, (uint)sizeof(RynthIltDataApiV1), "StructSize");
Check.Eq(sizeof(RynthIltDataApiV1), 8 + 8 * IntPtr.Size, "header + 8 functions (v1's 4, the breeding pair, the guardian pair)");
Check.Eq(RynthIltDataApiV1.V1Size, (uint)(8 + 4 * IntPtr.Size), "a v1 table ends before the breeding pair");
Check.Eq(RynthIltDataApiV1.V2Size, (uint)(8 + 6 * IntPtr.Size), "a v2 table ends before the guardian pair (readers still see breeding on it)");
Check.True(t->GetCharmsJson != null && t->GetBankJson != null && t->ToggleCharm != null && t->BankCommand != null
&& t->GetPetBreedingJson != null && t->PetBreedingCommand != null
&& t->GetGuardianJson != null && t->GuardianCommand != null, "every function is filled in");
Check.Eq((IntPtr)t, DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1), "the same table each time");
// No plugin instance here (not logged in): nothing to report, every action refused.
byte* buf = stackalloc byte[64];
Check.Eq(t->GetCharmsJson(buf, 64), 0, "no charms before login");
Check.Eq(t->GetBankJson(buf, 64), 0, "no bank before login");
Check.Eq(t->ToggleCharm(1234), 0, "no toggle before login");
byte* verb = stackalloc byte[] { (byte)'r', (byte)'e', (byte)'f', (byte)'r', (byte)'e', (byte)'s', (byte)'h', 0 };
Check.Eq(t->BankCommand(verb), 0, "no bank command before login");
Check.Eq(t->GetPetBreedingJson(buf, 64), 0, "no breeding JSON before login");
Check.Eq(t->PetBreedingCommand(verb), 0, "no breeding command before login");
Check.Eq(t->GetGuardianJson(buf, 64), 0, "no guardian JSON before login");
Check.Eq(t->GuardianCommand(verb), 0, "no guardian command before login");
DataInterface.Release();
Check.Eq(t->Version, 0u, "Release zeroes Version (readers re-query)");
Check.Eq(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1), IntPtr.Zero, "and nothing is served after shutdown");
Check.Eq(t->GetBankJson(buf, 64), 0, "the old table stays callable and answers nothing");
}
}

View file

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.Shared;
namespace RynthILT.Tests;
/// <summary>
/// A stand-in for RynthAi's "RynthAi.Hub" table (Plugins/Shared/RynthAiHubApi.cs), so the tests can
/// check what RynthILT asks of RynthAi (RynthAiClient.UseTableForTests takes it). Only the functions
/// the moved features use answer anything; the rest are absent (null), as an old RynthAi's would be.
/// Reset() before each test that uses it.
/// </summary>
internal static unsafe class FakeAiHub
{
/// <summary>BackAwayFrom calls (object, radius, hold), and what it answers.</summary>
public static readonly List<(uint Id, float Radius, int HoldMs)> BackAways = new();
public static int BackAwayResult = RynthAiHub.BackAwayStarted;
/// <summary>SetPlayerCounter: the last value reported per counter id.</summary>
public static readonly Dictionary<uint, long> Counters = new();
/// <summary>SessionStats: the shared session's start (0 = no session: SessionStats answers 0).</summary>
public static long SessionStartTicks;
private static RynthAiHubApiV1* _table;
public static void Reset()
{
BackAways.Clear();
BackAwayResult = RynthAiHub.BackAwayStarted;
Counters.Clear();
SessionStartTicks = 0;
}
public static IntPtr Table
{
get
{
if (_table == null)
{
var t = (RynthAiHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiHubApiV1));
t->StructSize = (uint)sizeof(RynthAiHubApiV1);
t->BackAwayFrom = &BackAwayFrom;
t->SetPlayerCounter = &SetPlayerCounter;
t->SessionStats = &SessionStats;
t->Version = RynthAiHubApiV1.InterfaceVersion;
_table = t;
}
return (IntPtr)_table;
}
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SessionStats(SessionStatsV1* s)
{
if (SessionStartTicks == 0 || s == null) return 0;
*s = default;
s->StartUtcTicks = SessionStartTicks;
s->SessionSeconds = 60;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetPlayerCounter(uint id, long value)
{
Counters[id] = value;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int BackAwayFrom(uint id, float radius, int holdMs)
{
BackAways.Add((id, radius, holdMs));
return BackAwayResult;
}
}

View file

@ -0,0 +1,215 @@
using System;
using System.Text;
using System.Text.Json;
using RynthCore.Plugin.RynthILT;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// Leaftide feature list (IltFeatureCatalog): every feature the player asked RynthILT to cover is
// listed and the states follow the server bits. Also the NUL-terminated copy RynthILT's interfaces
// ("RynthServer.Profile", "RynthILT.Data") hand their JSON out with.
internal static class FeatureCatalogTests
{
public static void Register(Runner r)
{
r.Add("features: banking, guardian, attributes, augs, paragon x3, split arrows, T11 and fellowship are listed", Listed);
r.Add("features: state follows the server bit on ILT, built-ins are on, nothing is known off ILT", States);
r.Add("features: profile JSON is valid ASCII with features and the fellowship rules", ProfileJson);
r.Add("features: the interface copies the JSON only when it fits, NUL-terminated", InterfaceWrite);
r.Add("features: the /qb list rides the profile JSON on ILT worlds only", QuestBonusJson);
r.Add("features: the RynthILT.Server table: query, filled in, release", ServerTable);
r.Add("features: the ILT profile is on with the world; a refusal in chat turns a feature off", ProfileOnWithTheWorld);
r.Add("features: probed features read checking; options ILT runs off are off until chat shows them", ProbedAndOffInIlt);
r.Add("features: charms are on with the ILT world unless refused; rows describe themselves", Charms);
}
/// <summary>ACECustom options Infinite Leaftide runs with off (ServerConfig defaults, PROD_DEPLOY_PLAN.md).</summary>
private static readonly string[] OffInIlt = { "pet_strain", "pet_refill", "defense_scaling" };
/// <summary>Features the login probe (or the /myquests tracker) answers.</summary>
private static readonly string[] Probed =
{
"bank", "attributes", "augmentations", "enlightenment", "clap", "pets", "shinies",
"fellowship_blackjack", "quests", "quest_bonus", "powerball", "blackjack",
};
private static void ProfileOnWithTheWorld()
{
// The features the player asked about, plus the pet switches prod runs on (bond, potency).
foreach (string key in new[] { "bank_notes", "t11", "t11_craft_gate", "split_arrows", "charms", "pet_breeding",
"pet_maturity", "pet_bond", "pet_potency", "monster_capture", "universal_mastery",
"missile_power", "t11_hit_gate", "fship" })
{
IltFeatureInfo f = IltFeatureCatalog.Find(key)!;
Check.Eq(f.Known, IltKnown.Profile, key + " is on in the ILT profile");
Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown), IltTri.On, key + " on with the ILT world");
Check.Eq(IltFeatureCatalog.StateOf(f, false, _ => IltTri.On), IltTri.Unknown, key + " unknown off ILT");
}
IltFeatureInfo mastery = IltFeatureCatalog.Find("universal_mastery")!;
Check.Eq(IltFeatureCatalog.StateOf(mastery, true, k => k == IltFeature.UniversalMastery ? IltTri.Off : IltTri.Unknown),
IltTri.Off, "a refusal in chat turns a profile feature off");
Check.Null(IltFeatureCatalog.Find("fellowship_additive"), "upstream ACE's additive fellowship option isn't an ILT feature");
}
private static void ProbedAndOffInIlt()
{
foreach (string key in Probed)
{
IltFeatureInfo f = IltFeatureCatalog.Find(key)!;
Check.Eq(f.Known, IltKnown.Checked, key + " is answered by the login probe");
Check.Eq(IltFeatureCatalog.StateText(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown)), "checking", key + " reads 'checking' until then");
}
foreach (string key in OffInIlt)
{
IltFeatureInfo f = IltFeatureCatalog.Find(key)!;
Check.Eq(f.Known, IltKnown.ProfileOff, key + " is off in the ILT profile");
Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown), IltTri.Off, key + " off with the ILT world");
Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.On), IltTri.On, key + " on once the server shows it");
Check.True(IltFeatureCatalog.Describe(key).Tooltip.Contains("Off in ILT"), key + "'s tooltip says it's off in ILT");
}
// ACECustom's three refill messages (PetDevice.TryApplyPyrealAutoRefillBeforeSummon) prove the refill is on.
Check.True(IltServerOptions.IsPyrealRefillLine("You restore one charge on your summoning essence at no cost."), "free refill");
Check.True(IltServerOptions.IsPyrealRefillLine("You spend 1,000 pyreals to restore one charge on your summoning essence."), "paid refill");
Check.True(IltServerOptions.IsPyrealRefillLine("You need 1,000 pyreals to auto-replenish your summoning essence. You do not have enough pyreals."), "refill too dear");
Check.False(IltServerOptions.IsPyrealRefillLine("Your summoning essence is empty."), "an empty essence says nothing about the refill");
}
private static void Charms()
{
Check.Eq(IltFeatureCatalog.CharmStateOf(true, IltTri.Unknown), IltTri.On, "a charm is on with the ILT world");
Check.Eq(IltFeatureCatalog.CharmStateOf(true, IltTri.Off), IltTri.Off, "a refused charm is off");
Check.Eq(IltFeatureCatalog.CharmStateOf(false, IltTri.On), IltTri.Unknown, "nothing is claimed off ILT");
var (label, group, tooltip) = IltFeatureCatalog.Describe(IltFeature.Charm("Mana Barrier"));
Check.Eq(label, "Mana Barrier", "a charm row shows the charm's name");
Check.Eq(group, IltFeatureCatalog.GroupCharms, "charms have their own section");
Check.True(tooltip.Contains("Mana absorbs"), "the tooltip carries the charm's effect");
Check.Eq(IltFeatureCatalog.Describe("something_new").Group, IltFeatureCatalog.GroupOther, "an unknown bit goes to Other");
}
private static readonly string[] Requested =
{
"bank", "guardian", "attributes", "augmentations", "paragon_armor", "paragon_weapons",
"paragon_jewelry", "split_arrows", "t11", "fellowship_large", "zone_share", "fellowship_blackjack",
};
private static void Listed()
{
foreach (string key in Requested)
Check.NotNull(IltFeatureCatalog.Find(key), "listed: " + key);
Check.Null(IltFeatureCatalog.Find("no_such_feature"), "an unknown key is not found");
var seen = new System.Collections.Generic.HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (IltFeatureInfo f in IltFeatureCatalog.All)
{
Check.True(seen.Add(f.Key), "keys are unique: " + f.Key);
Check.True(Array.IndexOf(IltFeatureCatalog.Groups, f.Group) >= 0, $"{f.Key} is in a known section ({f.Group})");
Check.True(f.Label.Length > 0 && f.Where.Length > 0 && f.Description.Length > 0, f.Key + " has a label, a place and a description");
}
}
private static void States()
{
IltFeatureInfo bank = IltFeatureCatalog.Find("bank")!;
IltFeatureInfo guardian = IltFeatureCatalog.Find("guardian")!;
Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.On), IltTri.On, "bank on when the server answers /bank");
Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.Off), IltTri.Off, "bank off when the server says so");
Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.Unknown), IltTri.Unknown, "bank unknown before the check");
Check.Eq(IltFeatureCatalog.StateOf(guardian, true, _ => IltTri.Off), IltTri.On, "a built-in feature is on with the ILT world");
Check.Eq(IltFeatureCatalog.StateOf(guardian, false, _ => IltTri.On), IltTri.Unknown, "nothing is claimed off ILT");
Check.Eq(IltFeatureCatalog.StateText(IltTri.Unknown), "checking", "unknown reads 'checking'");
Check.Eq(IltFeatureCatalog.FellowshipMax(true), 29, "ILT fellowships hold 29");
Check.Eq(IltFeatureCatalog.FellowshipMax(false), 9, "retail fellowships hold 9");
}
private static void ProfileJson()
{
string json = IltFeatureCatalog.BuildProfileJson(true, "Infinite \"Leaftide\"", false, "probe",
new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc),
key => key == IltFeature.FBlackjack ? IltTri.Off : IltTri.On);
bool ascii = true;
foreach (char c in json) if (c < 0x20 || c > 0x7E) ascii = false;
Check.True(ascii, "plain printable ASCII");
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
Check.True(root.GetProperty("ilt").GetBoolean(), "ilt");
Check.Eq(root.GetProperty("world").GetString(), "Infinite \"Leaftide\"", "quotes in the world name survive");
Check.Eq(root.GetProperty("checked").GetString(), "2026-10-13T21:25:37Z", "checked time in UTC");
Check.Eq(root.GetProperty("features").GetArrayLength(), IltFeatureCatalog.All.Length, "every feature in the JSON");
JsonElement fel = root.GetProperty("fellowship");
Check.Eq(fel.GetProperty("maxMembers").GetInt32(), 29, "fellowship size");
Check.Eq(fel.GetProperty("zoneShare").GetInt32(), 1, "Zone Share on (built in)");
Check.Eq(fel.GetProperty("blackjack").GetInt32(), 0, "Fellowship Blackjack off (server bit)");
string off = IltFeatureCatalog.BuildProfileJson(false, "", false, "", DateTime.MinValue, _ => IltTri.On);
using JsonDocument d2 = JsonDocument.Parse(off);
Check.Eq(d2.RootElement.GetProperty("fellowship").GetProperty("maxMembers").GetInt32(), 9, "off ILT: retail size");
Check.Eq(d2.RootElement.GetProperty("checked").GetString(), "", "never checked: empty time");
}
private static void QuestBonusJson()
{
var qb = new IltQuestBonusInfo(false, 2, 41, "2 completed, 1 incomplete",
new[] { "flag\"one", "flagTwo" }, new[] { "flagThree" });
string json = IltFeatureCatalog.BuildProfileJson(true, "Infinite Leaftide", false, "probe", DateTime.MinValue, _ => IltTri.On, qb);
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement q = doc.RootElement.GetProperty("questBonus");
Check.False(q.GetProperty("disabled").GetBoolean(), "enabled");
Check.Eq(q.GetProperty("generation").GetInt32(), 2, "generation");
Check.Eq(q.GetProperty("count").GetInt64(), 41L, "count");
Check.Eq(q.GetProperty("status").GetString(), "2 completed, 1 incomplete", "status");
Check.Eq(q.GetProperty("completed").GetArrayLength(), 2, "completed flags");
Check.Eq(q.GetProperty("completed")[0].GetString(), "flag\"one", "quotes in a flag survive");
Check.Eq(q.GetProperty("incomplete")[0].GetString(), "flagThree", "incomplete flags");
Check.True(doc.RootElement.TryGetProperty("fellowship", out _), "the fellowship rules are still there");
string off = IltFeatureCatalog.BuildProfileJson(false, "", false, "", DateTime.MinValue, _ => IltTri.On, qb);
using JsonDocument d2 = JsonDocument.Parse(off);
Check.False(d2.RootElement.TryGetProperty("questBonus", out _), "off ILT: no /qb list");
}
private static unsafe void ServerTable()
{
Check.Eq(ServerInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not ours");
Check.Eq(ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none");
var t = (RynthIltServerApiV1*)ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 1);
Check.True(t != null && t->Version == 1 && t->StructSize == (uint)sizeof(RynthIltServerApiV1) && t->GetProfileJson != null,
"v1 is served and filled in");
// Before login the profile is the not-ILT default; the copy is NUL-terminated and valid JSON.
byte* buf = stackalloc byte[262144];
int n = t->GetProfileJson(buf, 262144);
Check.True(n > 0 && n < 262144 && buf[n] == 0, "the default profile fits and is NUL-terminated");
using JsonDocument doc = JsonDocument.Parse(Encoding.UTF8.GetString(buf, n));
Check.False(doc.RootElement.GetProperty("ilt").GetBoolean(), "not an ILT world before login");
Check.Eq(t->GetProfileJson(buf, 8), n, "too small: the length comes back");
ServerInterface.Release();
Check.Eq(t->Version, 0u, "Release zeroes Version (readers re-query)");
Check.Eq(t->GetProfileJson(buf, 64), 0, "answers 0 after release");
Check.Eq(ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 1), IntPtr.Zero, "not served after release");
}
private static unsafe void InterfaceWrite()
{
const string json = "{\"ilt\":true}";
byte* small = stackalloc byte[4];
small[0] = 0x55;
Check.Eq(ProfileInterface.Write(json, small, 4), json.Length, "too small: the length is returned");
Check.Eq(small[0], (byte)0x55, "too small: nothing written");
byte* exact = stackalloc byte[json.Length];
Check.Eq(ProfileInterface.Write(json, exact, json.Length), json.Length, "no room for the NUL: too small");
byte* big = stackalloc byte[64];
int n = ProfileInterface.Write(json, big, 64);
Check.Eq(n, json.Length, "fits: the length without the NUL");
Check.Eq(big[n], (byte)0, "NUL-terminated");
Check.Eq(Encoding.UTF8.GetString(big, n), json, "the JSON copied whole");
}
}

View file

@ -0,0 +1,97 @@
using System;
using System.Linq;
using RynthCore.Plugin.RynthILT.IltFellowship;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// ILT's fellowship commands (IltFellowship/IltFellowshipCommands.cs, ACECustom /fship) and the
// "servercommands" format they are kept in (Plugins/Shared/ServerCommandShare.cs), checked together.
internal static class FellowshipCommandTests
{
public static void Register(Runner r)
{
r.Add("ilt fellowship: the /fship list round-trips through the servercommands format", RoundTrip);
r.Add("ilt fellowship: chat lines quote multi-word names and need a name for create", Compose);
r.Add("ilt fellowship: bad commands and payloads are dropped", Rejects);
r.Add("ilt fellowship: RynthCore's verdict decides, else the world name", Active);
}
private static void RoundTrip()
{
ServerCommandSet? set = ServerCommandShare.Parse(IltFellowshipCommands.Payload(active: true));
Check.True(set != null, "parsed");
Check.Eq(set!.Section, "fellowship", "section");
Check.Eq(set.ServerId, "ilt", "server id");
Check.Eq(set.ServerName, "Infinite Leaftide", "server name");
Check.Eq(set.Commands.Count, IltFellowshipCommands.Commands.Count, "every command survives");
for (int i = 0; i < set.Commands.Count; i++)
Check.Eq(set.Commands[i], IltFellowshipCommands.Commands[i], "command " + i);
Check.True(set.Commands.All(c => c.Command.StartsWith("/fship", StringComparison.Ordinal)), "all /fship");
ServerCommandSet? off = ServerCommandShare.Parse(IltFellowshipCommands.Payload(active: false));
Check.True(off != null, "the clear parses");
Check.Eq(off!.Commands.Count, 0, "the clear has no commands");
}
private static void Compose()
{
ServerCommand create = Find("Create"), invite = Find("Invite"), dismiss = Find("Dismiss"), list = Find("List nearby");
Check.True(ServerCommandShare.Compose(create, "") == null, "create needs a name");
Check.True(ServerCommandShare.Compose(create, " ") == null, "blank is no name");
Check.Eq(ServerCommandShare.Compose(create, "Leaf"), "/fship create Leaf", "one word");
Check.Eq(ServerCommandShare.Compose(create, " Leaf Hunters "), "/fship create \"Leaf Hunters\"", "quoted, spaces collapsed");
Check.Eq(ServerCommandShare.Compose(invite, ""), "/fship add", "no name: the selected player");
Check.Eq(ServerCommandShare.Compose(invite, "Raw Cigam"), "/fship add \"Raw Cigam\"", "multi-word player");
Check.Eq(ServerCommandShare.Compose(dismiss, "Bo\"b\t"), "/fship remove Bob", "quotes and control characters dropped");
Check.Eq(ServerCommandShare.Compose(list, "ignored"), "/fship list", "no argument taken");
Check.True(dismiss.Confirm && Find("Disband").Confirm && Find("Leave").Confirm && Find("Invite landblock").Confirm, "risky ones ask");
Check.False(invite.Confirm || list.Confirm || create.Confirm, "the rest don't");
string longName = new string('x', 200);
Check.Eq(ServerCommandShare.CleanArgument(longName).Length, ServerCommandShare.MaxArgument, "argument capped");
}
private static void Rejects()
{
Check.True(ServerCommandShare.Parse(null) == null, "null");
Check.True(ServerCommandShare.Parse("") == null, "empty");
Check.True(ServerCommandShare.Parse("C\tX\t/fship\t\t\n") == null, "no S line");
Check.True(ServerCommandShare.Parse("S\t\tilt\tILT\n") == null, "no section");
string payload = "S\tfellowship\tilt\tILT\n" +
"C\tNo slash\tfship list\t\t\n" +
"C\tSpace\t/ fship\t\t\n" +
"C\tQuote\t/fship add \"x\"\t\t\n" +
"C\t\t/fship list\t\tno label\n" +
"C\tLong\t/" + new string('a', ServerCommandShare.MaxCommand + 5) + "\t\t\n" +
"C\tShort\t/fship\t\n" +
"C\tGood\t/fship list\tzqA\ttip\n";
ServerCommandSet? set = ServerCommandShare.Parse(payload);
Check.True(set != null, "parsed");
Check.Eq(set!.Commands.Count, 1, "only the good command");
Check.Eq(set.Commands[0].Flags, "A", "unknown flags dropped");
var many = Enumerable.Range(0, 40).Select(i => new ServerCommand("B" + i, "/fship list", "", ""));
string built = ServerCommandShare.Build(new ServerCommandSet("fellowship", "ilt", "ILT", many.ToList()));
Check.Eq(ServerCommandShare.Parse(built)!.Commands.Count, ServerCommandShare.MaxCommands, "capped");
string tabbed = ServerCommandShare.Build(new ServerCommandSet("fellowship", "ilt", "ILT",
new[] { new ServerCommand("A\tB", "/fship list", "", "line one\nline two") }));
ServerCommand c = ServerCommandShare.Parse(tabbed)!.Commands[0];
Check.Eq(c.Label, "A B", "tab in a field becomes a space");
Check.Eq(c.Tooltip, "line one line two", "newline in a field becomes a space");
}
private static void Active()
{
Check.True(IltFellowshipCommands.IsActive(true, "Coldeve"), "RynthCore says ILT");
Check.False(IltFellowshipCommands.IsActive(false, "InfiniteLeaftide"), "RynthCore says not ILT");
Check.True(IltFellowshipCommands.IsActive(null, "InfiniteLeaftide"), "no verdict yet: the world name");
Check.False(IltFellowshipCommands.IsActive(null, "Coldeve"), "no verdict, another world");
Check.False(IltFellowshipCommands.IsActive(null, null), "nothing known");
}
private static ServerCommand Find(string label) =>
IltFellowshipCommands.Commands.First(c => c.Label == label);
}

View file

@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthILT.IltSettingsView;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// RynthILT's copy of the ILT settings (IltSettingsView/IltSettingsModel.cs): RynthCore's server
// list (plugin API v86, GetServerStateJson: verdict, override, reason), the Hub's feature read, the
// engine verdict the Hub follows (IltEngineVerdict), and the RynthCore commands the view sends.
internal static class IltSettingsTests
{
public static void Register(Runner r)
{
r.Add("ilt settings: RynthCore's server list gives the ILT verdict, override and reason", ServerList);
r.Add("ilt settings: a list without ILT, or no list at all, reads as such", NoIlt);
r.Add("ilt settings: the Hub's feature read is published whole", FeatureRead);
r.Add("ilt settings: the Hub follows RynthCore's ILT verdict once one arrives", EngineVerdict);
r.Add("ilt settings: override and world-name commands are checked before sending", Commands);
r.Add("ilt settings: logout clears the copy", ClearOnLogout);
}
// GetServerStateJson as RynthCore writes it (UI/Sections/ServerStateJson.cs, schema 1).
private const string State =
"{\"schema\":1,\"revision\":3,\"host\":\"infiniteleaftide.online\",\"world\":\"InfiniteLeaftide\",\"pick\":\"auto\"," +
"\"active\":\"ilt\",\"activeName\":\"Infinite Leaftide\",\"activePlugin\":\"RynthILT\",\"servers\":[" +
"{\"id\":\"ilt\",\"name\":\"Infinite Leaftide\",\"active\":true,\"detected\":false,\"force\":\"on\",\"builtIn\":true," +
"\"plugin\":\"RynthILT\",\"reason\":\"forced on for this character\"}," +
"{\"id\":\"aelrynth\",\"name\":\"Aelrynth\",\"active\":false,\"detected\":false,\"force\":\"auto\",\"builtIn\":true," +
"\"plugin\":\"\",\"reason\":\"not detected\"}]}";
private const string NoIltState =
"{\"schema\":1,\"revision\":1,\"active\":\"\",\"servers\":[" +
"{\"id\":\"aelrynth\",\"name\":\"Aelrynth\",\"active\":true,\"detected\":true,\"force\":\"auto\"}]}";
private static void ServerList()
{
IltEngineView? v = IltSettingsModel.FromServerState(EngineServerState.Parse(State));
Check.True(v?.Server != null, "the ILT server is there");
Check.Eq(v!.Server!.Name, "Infinite Leaftide", "name");
Check.True(v.Server.Active, "active");
Check.False(v.Server.Detected, "not detected (forced)");
Check.Eq(v.Server.Force, "on", "override");
Check.Eq(v.Server.Reason, "forced on for this character", "reason");
IltEngineView? odd = IltSettingsModel.FromServerState(EngineServerState.Parse(
"{\"schema\":1,\"servers\":[{\"id\":\"ILT\",\"force\":\"WEIRD\"}]}"));
Check.True(odd?.Server != null, "the id ignores case");
Check.Eq(odd!.Server!.Force, "auto", "an unknown override shows as auto");
Check.Eq(odd.Server.Name, "Infinite Leaftide", "a missing name gets the server's");
Check.False(odd.Server.Active, "a missing flag is off");
}
private static void NoIlt()
{
IltEngineView? none = IltSettingsModel.FromServerState(EngineServerState.Parse(NoIltState));
Check.True(none != null && none.Server == null, "a list without ILT says so (not 'waiting')");
Check.True(IltSettingsModel.FromServerState(null) == null, "no list: nothing");
Check.True(EngineServerState.Parse("") == null && EngineServerState.Parse("{\"schema\":2}") == null, "empty or another schema: no list");
var model = new IltSettingsModel();
model.ApplyServerState(EngineServerState.Parse(State));
model.ApplyServerState(null);
Check.True(model.Engine?.Server?.Active == true, "no answer keeps the last list");
}
private static void FeatureRead()
{
var model = new IltSettingsModel();
var read = new IltFeatureView("Infinite Leaftide", "probe", "12:00:00", Checking: true, IltLike: true,
new[] { new KeyValuePair<string, int>("bank", 1) });
model.PublishFeatures(read);
Check.True(ReferenceEquals(model.Features, read), "published as is");
model.PublishFeatures(null);
Check.True(model.Features == null, "cleared while there is no Hub");
Check.Eq(IltSettingsModel.StateText(1), "on", "1 is on");
Check.Eq(IltSettingsModel.StateText(0), "off", "0 is off (not unknown)");
Check.Eq(IltSettingsModel.StateText(-1), "unknown", "-1 is unknown");
}
private static void EngineVerdict()
{
var model = new IltSettingsModel();
try
{
IltEngineVerdict.Attach(model);
Check.False(IltEngineVerdict.Pushed, "nothing sent yet");
Check.True(IltEngineVerdict.Active == null, "no verdict: RynthILT's own list decides");
model.ApplyServerState(EngineServerState.Parse(State));
Check.True(IltEngineVerdict.Pushed, "sent");
Check.True(IltEngineVerdict.Active == true, "RynthCore says ILT");
model.ApplyServerState(EngineServerState.Parse(NoIltState));
Check.True(IltEngineVerdict.Pushed && IltEngineVerdict.Active == null, "a list without ILT gives no ILT verdict");
model.Clear();
Check.False(IltEngineVerdict.Pushed, "logout forgets it");
}
finally { IltEngineVerdict.Attach(null); }
Check.True(IltEngineVerdict.Active == null, "detached");
}
private static void Commands()
{
Check.Eq(IltSettingsModel.ForceCommand("on"), "/rc server ilt on", "on");
Check.Eq(IltSettingsModel.ForceCommand("auto"), "/rc server ilt auto", "auto");
Check.Eq(IltSettingsModel.ForceCommand("maybe"), "", "unknown mode sends nothing");
Check.Eq(IltSettingsModel.NamesListCommand, "/rc server names ilt", "the names are listed by RynthCore");
Check.Eq(IltSettingsModel.NamesCommand(true, " *Frost* ", out _), "/rc server names ilt add *Frost*", "add, trimmed");
Check.Eq(IltSettingsModel.NamesCommand(false, "Infinite Leaftide", out _), "/rc server names ilt remove Infinite Leaftide", "remove");
Check.Eq(IltSettingsModel.NamesCommand(true, "", out string e1), "", "empty refused");
Check.True(e1.Length > 0, "with a reason");
Check.Eq(IltSettingsModel.NamesCommand(true, new string('a', IltSettingsModel.MaxPattern + 1), out _), "", "too long refused");
Check.Eq(IltSettingsModel.NamesCommand(true, "x\n/rc reload", out _), "", "a line break can't start a second command");
Check.Eq(IltSettingsModel.NamesCommand(true, "a/b", out _), "", "no '/'");
}
private static void ClearOnLogout()
{
var model = new IltSettingsModel();
model.ApplyServerState(EngineServerState.Parse(State));
model.PublishFeatures(new IltFeatureView("w", "", "", false, true, Array.Empty<KeyValuePair<string, int>>()));
Check.True(model.Engine != null && model.Features != null, "both copies");
model.Clear();
Check.True(model.Engine == null && model.Features == null, "cleared");
}
}

View file

@ -0,0 +1,615 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using RynthCore.Loot;
using RynthCore.Plugin.RynthILT;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The ILT Hub's move out of RynthAi into RynthILT (2026-10-13): the saved data carried over from
// RynthAi's folders (copied, never moved), the RynthILT.Hub interface table RynthAi's Mini Remote
// reads, which "/ra" verbs RynthILT takes from RynthAi, and the host-backed object view that
// replaced RynthAi's WorldObjectCache.
internal static class MoveTests
{
public static void Register(Runner r)
{
r.Add("move: a character's RynthAi ILT Hub files are copied, the RynthAi copies left alone", MigratesCharacter);
r.Add("move: migration never overwrites RynthILT's files and runs once", MigrationIdempotent);
r.Add("move: the pre-per-server ACEmulator folder is found too", MigratesFromAceEmulatorFolder);
r.Add("move: shared Hub profiles and aug costs are copied once", MigratesShared);
r.Add("move: a migration copy that fails is reported (log + chat) and the shared ones retried", MigrationFailuresReported);
r.Add("move: a failed Hub save is reported once and retried", StoreSaveFailureReported);
r.Add("move: an unfinished copy blocks the character's Hub writes until the retry copies the original", PendingMigrationNeverShadowed);
r.Add("move: an old ilt-hub.json loads into RynthILT's state (ILT parts kept)", LegacyStateLoads);
r.Add("move: RynthAi's \"/ra\" verbs RynthILT takes (and the ones it leaves)", VerbRouting);
r.Add("move: item classes from the client's item type (the gear tools' checks)", Classification);
r.Add("move: the interface structs have the agreed layout", InterfaceLayout);
r.Add("move: server-list status lines", DescribeLines);
r.Add("move: off ILT nothing is sent, no tab or section shows; on ILT the login probe runs", DormantOffIlt);
r.Add("move: the charms JSON for RynthILT.Data readers carries the Guardian Hands", CharmsReaderJson);
r.Add("move: Character redirects to RynthOracle; Charms and Banking stay RynthILT's tabs", MovedSections);
r.Add("sections: RynthILT's manifest (rates, /fship, /qb, and the ILT tabs it shows) is valid schema-1 JSON the engine places", SectionsManifest);
// Last: Release() switches the table off for the rest of the process.
r.Add("move: the RynthILT.Hub table: query, functions, release", HubTable);
}
private static string Root(string name)
{
string dir = Path.Combine(Program.TempRoot, "move-" + name);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
IltMigration.LegacyProfilesBase = Path.Combine(dir, "RynthAi", "SettingsProfiles");
IltMigration.LegacySharedRoot = Path.Combine(dir, "RynthAi");
return dir;
}
private const string LegacyHubJson = """
{
"SchemaVersion": 1,
"ForceLeaftideFeatures": false,
"UbSidecarsImported": true,
"Bank": { "Pyreals": 1234567, "Luminance": 89, "EnlightenedCoins": 42, "AutoRefreshSeconds": 300 },
"Pet": { "HealingEnabled": true, "HealPetName": "Healing Buddy", "PetLog": ["Fire Banshee"], "ShinyLog": [] },
"Character": {
"QuestFilter": "temple", "QbFilter": "wait", "QuestFavorites": ["foo"],
"AttrOrder": ["qui","coo","str","end","foc","sel","hea","sta","man"], "AttrRaiseStats": ["qui"],
"AugTargets": { "war": 1800 }
},
"Gear": { "AutoClap": true, "LastUsdPath": "C:\\vt\\x.usd", "LastEquipProfile": "Melee" },
"Guardian": { "AutoHandIn": true, "TurnInCounts": { "Strength": 3 } }
}
""";
private static string MakeLegacyChar(string world, string charName, bool withProfile = true)
{
string dir = Path.Combine(IltMigration.LegacyProfilesBase, IltMigration.RynthAiSafeName(world), IltMigration.RynthAiSafeName(charName));
Directory.CreateDirectory(Path.Combine(dir, "ilt-hub-profiles"));
File.WriteAllText(Path.Combine(dir, "ilt-hub.json"), LegacyHubJson);
File.WriteAllText(Path.Combine(dir, "ilt-hub-transactions.json"), "[{\"Type\":\"Received\",\"Currency\":\"Pyreals\",\"Amount\":5}]");
File.WriteAllText(Path.Combine(dir, "ilt-hub-profiles", "farm.json"), "{\"SchemaVersion\":1}");
if (withProfile)
{
File.WriteAllText(Path.Combine(dir, "active_profile.txt"), "Melee");
File.WriteAllText(Path.Combine(dir, "Melee.json"),
"{\"MetaDebug\":false,\"FeatureServerNames\":[\"InfiniteLeaftide\",\"*Leaftide*\",\"MyShard\"],\"ForceServerFeatures\":true}");
File.WriteAllText(Path.Combine(dir, "Default.json"), "{\"FeatureServerNames\":[\"Unused\"]}");
}
return dir;
}
private static void MigratesCharacter()
{
string root = Root("char");
string legacy = MakeLegacyChar("Infinite Leaftide", "Sir Tester");
string before = File.ReadAllText(Path.Combine(legacy, "ilt-hub.json"));
var settings = new IltSettings();
string dest = Path.Combine(root, "RynthILT", "Infinite Leaftide", "Sir Tester");
var done = IltMigration.MigrateCharacter(dest, "Infinite Leaftide", "Sir Tester", settings, out bool force);
Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "ilt-hub.json -> hub.json");
Check.Eq(File.ReadAllText(Path.Combine(dest, IltHubStore.StateFile)), before, "copied byte for byte");
Check.True(File.Exists(Path.Combine(dest, IltHubStore.TransactionsFile)), "transactions copied");
Check.True(File.Exists(Path.Combine(dest, IltHubStore.ProfilesFolder, "farm.json")), "per-character Hub profiles copied");
Check.True(File.Exists(Path.Combine(legacy, "ilt-hub.json")) && File.Exists(Path.Combine(legacy, "ilt-hub-transactions.json")),
"RynthAi's files are still there (copy, not move)");
Check.True(settings.ServerNames.Contains("MyShard"), "the active profile's server names are added");
Check.False(settings.ServerNames.Contains("Unused"), "only the ACTIVE profile is read");
Check.Eq(settings.ServerNames.Count(n => n.Equals("InfiniteLeaftide", StringComparison.OrdinalIgnoreCase)), 1, "no duplicates");
Check.True(force, "\"Force enable\" carries over as Treat this world as ILT");
Check.True(done.Count >= 4, "the log line lists what was carried over: " + string.Join(", ", done));
}
private static void MigrationIdempotent()
{
string root = Root("idem");
string legacy = MakeLegacyChar("InfiniteLeaftide", "Again", withProfile: false);
string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Again");
Directory.CreateDirectory(dest);
File.WriteAllText(Path.Combine(dest, IltHubStore.TransactionsFile), "[]"); // RynthILT already has one
var settings = new IltSettings();
IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Again", settings, out bool force);
Check.Eq(File.ReadAllText(Path.Combine(dest, IltHubStore.TransactionsFile)), "[]", "an existing RynthILT file is never overwritten");
Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "the missing hub.json is still copied");
Check.False(force, "no profile, no override");
File.WriteAllText(Path.Combine(legacy, "ilt-hub.json"), "{\"Bank\":{\"Pyreals\":1}}");
var second = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Again", settings, out _);
Check.Eq(second.Count, 0, "once hub.json exists the character is never migrated again");
Check.False(File.ReadAllText(Path.Combine(dest, IltHubStore.StateFile)).Contains("\"Pyreals\":1}"), "later RynthAi edits don't overwrite RynthILT's state");
var none = IltMigration.MigrateCharacter(Path.Combine(root, "RynthILT", "X", "Nobody"), "X", "Nobody", settings, out _);
Check.Eq(none.Count, 0, "a character RynthAi never saw: nothing to do");
Check.False(Directory.Exists(Path.Combine(root, "RynthILT", "X", "Nobody")), "and no folder is made for it");
}
private static void MigratesFromAceEmulatorFolder()
{
string root = Root("ace");
MakeLegacyChar("ACEmulator", "Old Timer", withProfile: false);
var settings = new IltSettings();
string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Old Timer");
Check.NotNull(IltMigration.FindLegacyCharFolder("InfiniteLeaftide", "Old Timer"), "the world folder is missing, ACEmulator\\<char> is used");
IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Old Timer", settings, out _);
Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "copied from the ACEmulator folder");
Check.Eq(IltMigration.RynthAiSafeName("Sir O'Neil-Smith"), "Sir_O'Neil-Smith", "RynthAi's folder names keep ' and - only");
}
private static void MigratesShared()
{
string root = Root("shared");
Directory.CreateDirectory(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles"));
File.WriteAllText(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles", "team.json"), "{}");
File.WriteAllText(Path.Combine(IltMigration.LegacySharedRoot, "ilt-aug-costs.json"), "{\"x\":1}");
var settings = new IltSettings();
string dest = Path.Combine(root, "RynthILT");
var done = IltMigration.MigrateShared(settings, dest);
Check.True(File.Exists(Path.Combine(dest, "Profiles", "team.json")), "shared profiles copied");
Check.True(File.Exists(Path.Combine(dest, "ilt-aug-costs.json")), "aug costs copied");
Check.True(settings.SharedFilesMigrated, "marked done in the settings");
Check.Eq(done.Count, 2, "both reported");
File.Delete(Path.Combine(dest, "ilt-aug-costs.json"));
Check.Eq(IltMigration.MigrateShared(settings, dest).Count, 0, "once only");
Check.False(File.Exists(Path.Combine(dest, "ilt-aug-costs.json")), "a file deleted afterwards isn't brought back");
}
// A copy that fails (here: the RynthAi file held open by another program) is never silent: it
// is logged and queued for chat with the reason, the rest still copies, and the shared files
// aren't marked done so the next login tries again.
private static void MigrationFailuresReported()
{
string root = Root("fail");
DataWriteGuard.Reset();
string legacy = MakeLegacyChar("InfiniteLeaftide", "Locked Out");
string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Locked Out");
var settings = new IltSettings();
List<string> done;
using (new FileStream(Path.Combine(legacy, "ilt-hub-transactions.json"), FileMode.Open, FileAccess.Read, FileShare.None))
done = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Locked Out", settings, out _);
Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "the other files are still copied");
Check.False(File.Exists(Path.Combine(dest, IltHubStore.TransactionsFile)), "the held file isn't");
Check.True(done.Any(l => l.Contains("NOT copied") && l.Contains(legacy)), "the log line says so and where the originals are: " + string.Join(", ", done));
Check.Eq(DataWriteGuard.PendingCount, 1, "one chat line queued (shown on ILT)");
var lines = new List<string>();
DataWriteGuard.DrainChat(lines.Add);
Check.True(lines.Count == 1 && lines[0].StartsWith("[RynthILT]", StringComparison.Ordinal)
&& lines[0].Contains("ilt-hub-transactions.json") && lines[0].Contains("another program"),
"it names the file and the reason: " + string.Join(" | ", lines));
DataWriteGuard.Reset();
Directory.CreateDirectory(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles"));
File.WriteAllText(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles", "team.json"), "{}");
string aug = Path.Combine(IltMigration.LegacySharedRoot, "ilt-aug-costs.json");
File.WriteAllText(aug, "{\"x\":1}");
string sharedDest = Path.Combine(root, "RynthILT");
using (new FileStream(aug, FileMode.Open, FileAccess.Read, FileShare.None))
done = IltMigration.MigrateShared(settings, sharedDest);
Check.False(settings.SharedFilesMigrated, "a failed shared copy isn't marked done");
Check.True(done.Any(l => l.Contains("NOT copied")), "and is reported: " + string.Join(", ", done));
Check.True(DataWriteGuard.PendingCount >= 1, "in chat too");
done = IltMigration.MigrateShared(settings, sharedDest);
Check.True(File.Exists(Path.Combine(sharedDest, "ilt-aug-costs.json")), "the next login copies it");
Check.True(settings.SharedFilesMigrated, "then it is marked done");
Check.Eq(done.Count, 1, "only the missing file is copied the second time: " + string.Join(", ", done));
DataWriteGuard.Reset();
}
// A character whose ilt-hub.json couldn't be copied (held open by another program): the Hub
// runs from the RynthAi original read-only (or the defaults), writes no hub.json, bank log or
// per-character profile there, the pending mark survives a restart, and the next attempt copies
// the original byte for byte - never shadowed by a fresh file.
private static void PendingMigrationNeverShadowed()
{
string root = Root("pending");
DataWriteGuard.Reset();
string legacy = MakeLegacyChar("InfiniteLeaftide", "Held Open");
string legacyHub = Path.Combine(legacy, "ilt-hub.json");
string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Held Open");
string hubJson = Path.Combine(dest, IltHubStore.StateFile);
var settings = new IltSettings();
// Held open by another program: neither copied nor readable.
using (var held = new FileStream(legacyHub, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
var done = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Held Open", settings, out _);
Check.False(File.Exists(hubJson), "the held ilt-hub.json isn't copied");
Check.True(IltMigration.IsPending(settings, dest), "the character is marked pending");
Check.True(done.Any(l => l.Contains("NOT copied")), "and the log says so: " + string.Join(", ", done));
var store = new IltHubStore(default, dest)
{
WritesBlocked = () => IltMigration.IsPending(settings, dest),
LegacyFolder = legacy,
};
IltHubState state = store.LoadState();
Check.Eq(state.Bank.Pyreals, 0L, "unreadable: the Hub runs from the defaults");
state.Bank.Pyreals = 1;
store.SaveStateIfDirty(state);
Check.False(File.Exists(hubJson), "no hub.json is written while the copy is unfinished");
Check.False(store.SaveProfile(state, "mine", shared: false, out string why), "nor a per-character profile");
Check.True(why.Contains("RynthAi"), "with the reason: " + why);
Check.True(store.SaveProfile(state, "team-" + Guid.NewGuid().ToString("N"), shared: true, out _), "shared profiles still save");
// A second login while still held: still pending, still nothing written.
IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Held Open", settings, out _);
Check.True(IltMigration.IsPending(settings, dest) && !File.Exists(hubJson), "still pending, still no hub.json");
}
// Readable again but not yet retried: a Hub started now reads the original, still writes nothing.
var readOnly = new IltHubStore(default, dest)
{
WritesBlocked = () => IltMigration.IsPending(settings, dest),
LegacyFolder = legacy,
};
IltHubState fromLegacy = readOnly.LoadState();
Check.Eq(fromLegacy.Bank.Pyreals, 1234567L, "the Hub runs from the RynthAi original, read only");
fromLegacy.Bank.Pyreals = 2;
readOnly.SaveStateIfDirty(fromLegacy);
Check.False(File.Exists(hubJson), "and still writes no hub.json");
// The mark is in settings.json, so a client restart still knows the copy is unfinished.
IltSettingsStore.Save(settings);
IltSettings reloaded = IltSettingsStore.Load();
Check.True(IltMigration.IsPending(reloaded, dest), "pending survives a restart");
var finished = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Held Open", reloaded, out bool force);
Check.True(File.Exists(hubJson), "the next attempt copies it");
Check.Eq(File.ReadAllText(hubJson), File.ReadAllText(legacyHub), "byte for byte: the original, not a fresh file");
Check.False(IltMigration.IsPending(reloaded, dest), "no longer pending");
Check.True(force, "the profile's Force enable still carries over on the retry");
Check.True(finished.Any(l => l.Contains("complete")), "the log says it finished: " + string.Join(", ", finished));
var after = new IltHubStore(default, dest) { WritesBlocked = () => IltMigration.IsPending(reloaded, dest) };
IltHubState loaded = after.LoadState();
Check.Eq(loaded.Bank.Pyreals, 1234567L, "the restarted Hub loads the copied file");
loaded.Bank.Pyreals = 7;
after.SaveStateIfDirty(loaded);
Check.True(File.ReadAllText(hubJson).Contains("\"Pyreals\": 7"), "and saves normally from then on");
File.Delete(Path.Combine(IltSettingsStore.Folder, IltSettingsStore.FileName));
DataWriteGuard.Reset();
}
// RynthILT's own saves report a failure (DataWriteGuard) and try again on the next save.
private static void StoreSaveFailureReported()
{
string root = Root("storefail");
DataWriteGuard.Reset();
string blocker = Path.Combine(root, "NotAFolder");
File.WriteAllText(blocker, "a file where the character folder should be");
var store = new IltHubStore(default, blocker);
var state = new IltHubState();
store.SaveStateIfDirty(state);
Check.Eq(DataWriteGuard.PendingCount, 1, "the failed Hub save is queued for chat");
store.SaveStateIfDirty(state);
Check.Eq(DataWriteGuard.PendingCount, 1, "once per folder, not every retry");
File.Delete(blocker);
store.SaveStateIfDirty(state);
Check.True(File.Exists(Path.Combine(blocker, IltHubStore.StateFile)), "the next save retries and works");
DataWriteGuard.Reset();
}
private static void LegacyStateLoads()
{
string root = Root("state");
string dir = Path.Combine(root, "char");
Directory.CreateDirectory(dir);
File.WriteAllText(Path.Combine(dir, IltHubStore.StateFile), LegacyHubJson);
var store = new IltHubStore(default, dir);
var s = store.LoadState();
Check.Eq(s.Bank.Pyreals, 1234567L, "bank balances");
Check.Eq(s.Bank.AutoRefreshSeconds, 300, "bank settings");
Check.Eq(s.Pet.PetLog.FirstOrDefault(), "Fire Banshee", "the /pets log (an ILT part of the Pet section)");
Check.Eq(s.Character.QbFilter, "wait", "the /qb filter");
Check.Eq(s.Character.AttrOrder.FirstOrDefault(), "qui", "the attribute raiser's order");
Check.Eq(s.Character.AugTargets["war"], 1800, "aug targets");
Check.True(s.Gear.AutoClap && s.Gear.LastEquipProfile == "Melee", "gear settings");
Check.True(s.Guardian.AutoHandIn && s.Guardian.TurnInCounts["Strength"] == 3, "guardian settings");
Check.True(s.UbSidecarsImported, "the UB import isn't redone");
store.SaveStateIfDirty(s);
string saved = File.ReadAllText(Path.Combine(dir, IltHubStore.StateFile));
Check.False(saved.Contains("HealPetName"), "the Pets tab's settings (RynthAi's now) aren't written back here");
Check.False(saved.Contains("QuestFavorites"), "nor the Quests tab's");
}
private static void VerbRouting()
{
static bool Takes(string line) => RynthILTPlugin.IsIltVerb(line.Split(' ', StringSplitOptions.RemoveEmptyEntries));
Check.True(Takes("hub bank"), "hub bank");
Check.True(Takes("hub attr run"), "hub attr run");
Check.True(Takes("hub refresh"), "hub refresh");
Check.True(Takes("hub help"), "hub help (RynthILT prints the whole list)");
Check.True(Takes("hub open banking show"), "hub open <ILT tab>");
Check.True(Takes("hub open guardian"), "hub open guardian (the engine panel)");
Check.True(Takes("hub open bounties"), "hub open bounties");
Check.False(Takes("hub open pets"), "hub open pets is RynthAi's");
Check.False(Takes("hub open quests hide"), "hub open quests is RynthAi's");
Check.True(Takes("hub tab gear"), "hub tab <ILT tab>");
Check.False(Takes("hub tab quests"), "hub tab quests is RynthAi's");
Check.False(Takes("hub tab remote"), "the Remote tab is RynthAi's");
Check.False(Takes("hub"), "bare /ra hub toggles RynthAi's Mini Remote");
Check.True(Takes("guardian handin"), "guardian");
Check.True(Takes("bounty show") && Takes("bounties") && Takes("bountys"), "bounty, bounties, bountys");
Check.True(Takes("rates reset"), "rates reset (the Mini Remote's Reset XP)");
Check.False(Takes("quests refresh"), "/ra quests is RynthAi's");
Check.False(Takes("pets show"), "/ra pets is RynthAi's");
Check.False(Takes("start"), "anything else is RynthAi's");
// The VTank hotkey verbs (RynthAi 2026-10-13, RynthAiPlugin.VTankHotkeys.cs) stay RynthAi's.
foreach (string vt in new[] { "vtkeys", "targetlock", "recharge", "lootthis", "meleelow", "navprio", "lootprio", "navlootprio", "setmetastate Default", "testitem", "propertydump" })
Check.False(Takes(vt), $"{vt} is RynthAi's (VTank hotkeys)");
}
private static void Classification()
{
Check.Eq(IltObjects.ClassifyByItemType(0x00000800), AcObjectClass.Gem, "gem (aetheria)");
Check.Eq(IltObjects.ClassifyByItemType(0x00000001), AcObjectClass.MeleeWeapon, "melee weapon");
Check.Eq(IltObjects.ClassifyByItemType(0x00000100), AcObjectClass.MissileWeapon, "missile weapon");
Check.Eq(IltObjects.ClassifyByItemType(0x00008000), AcObjectClass.WandStaffOrb, "caster");
Check.Eq(IltObjects.ClassifyByItemType(0x40000000), AcObjectClass.Salvage, "salvage (white quartz)");
Check.Eq(IltObjects.ClassifyByItemType(0x00001000), AcObjectClass.SpellComponent, "spell component");
Check.Eq(IltObjects.ClassifyByItemType(0x00000200), AcObjectClass.Container, "pack");
Check.Eq(IltObjects.ClassifyByItemType(0x00000010), AcObjectClass.Monster, "creature");
Check.Eq(IltObjects.ClassifyByItemType(0x00000002 | 0x00000004), AcObjectClass.Armor, "armor wins over clothing");
Check.Eq(IltObjects.ClassifyByItemType(0), AcObjectClass.Unknown, "no type yet");
}
private static unsafe void InterfaceLayout()
{
Check.Eq(sizeof(ServerHubTabV1), 24 + 32 + 4 + 4 + 4, "ServerHubTabV1: id, label, width, height, flags");
Check.Eq((int)Marshal.OffsetOf<ServerHubTabV1>(nameof(ServerHubTabV1.Flags)), 64, "ServerHubTabV1.Flags offset");
// RynthILT.Hub grew on 2026-10-20 (append-only): readers accept any table at least BaseStructSize
// long (the first release's 9 functions) and check the appended ones with Has.
Check.Eq((int)RynthServerHubApiV1.BaseStructSize, 8 + 9 * IntPtr.Size, "RynthServerHubApiV1.BaseStructSize: the first release's 9 functions");
Check.Eq(RynthServerHubApiV1.AllowSummonOnEmptyOffset, 8 + 9 * IntPtr.Size, "AllowSummonOnEmpty right after Command");
Check.Eq((int)Marshal.OffsetOf<RynthServerHubApiV1>(nameof(RynthServerHubApiV1.AllowSummonOnEmpty)), RynthServerHubApiV1.AllowSummonOnEmptyOffset,
"AllowSummonOnEmptyOffset is where the field really is");
Check.Eq((int)Marshal.OffsetOf<RynthServerHubApiV1>(nameof(RynthServerHubApiV1.GetSubTabs)), RynthServerHubApiV1.GetSubTabsOffset,
"GetSubTabsOffset is where the field really is");
Check.Eq((int)Marshal.OffsetOf<RynthServerHubApiV1>(nameof(RynthServerHubApiV1.GetSetting)), RynthServerHubApiV1.GetSettingOffset,
"GetSettingOffset is where the field really is");
Check.Eq((int)Marshal.OffsetOf<RynthServerHubApiV1>(nameof(RynthServerHubApiV1.SetSetting)), RynthServerHubApiV1.SetSettingOffset,
"SetSettingOffset is where the field really is");
// SessionStatsMore was appended (2026-10-13); readers accept any table at least
// BaseStructSize long, so an older RynthAi still connects.
// VaultedDungeonsEnabled was appended (2026-10-18): the Vaulted Dungeons master switch.
// BackAwayFrom was appended (2026-10-20): the generic back-away RynthILT's Handler ring evade asks for.
// SetPlayerCounter too (2026-10-20): the T11 wield counters RynthILT reads from /aug.
Check.Eq(sizeof(RynthAiHubApiV1), 8 + 14 * IntPtr.Size, "RynthAiHubApiV1: header + 14 functions");
Check.Eq((int)Marshal.OffsetOf<RynthAiHubApiV1>(nameof(RynthAiHubApiV1.SetPlayerCounter)), RynthAiHubApiV1.SetPlayerCounterOffset,
"SetPlayerCounterOffset is where the field really is");
Check.Eq((int)Marshal.OffsetOf<RynthAiHubApiV1>(nameof(RynthAiHubApiV1.BackAwayFrom)), RynthAiHubApiV1.BackAwayFromOffset,
"BackAwayFromOffset is where the field really is");
Check.Eq((int)RynthAiHubApiV1.BaseStructSize, 8 + 10 * IntPtr.Size, "RynthAiHubApiV1.BaseStructSize: the first release's 10 functions");
Check.Eq(RynthAiHubApiV1.SessionStatsMoreOffset, (int)RynthAiHubApiV1.BaseStructSize, "SessionStatsMore right after the base table");
Check.Eq(RynthAiHubApiV1.VaultedDungeonsEnabledOffset, 8 + 11 * IntPtr.Size, "VaultedDungeonsEnabled right after SessionStatsMore");
Check.Eq((int)Marshal.OffsetOf<RynthAiHubApiV1>(nameof(RynthAiHubApiV1.VaultedDungeonsEnabled)), RynthAiHubApiV1.VaultedDungeonsEnabledOffset,
"VaultedDungeonsEnabledOffset is where the field really is");
Check.Eq(sizeof(QuestFlagV1), 24, "QuestFlagV1");
Check.Eq(sizeof(QuestStatusV1), 16, "QuestStatusV1");
Check.Eq(RynthIltHub.InterfaceName, "RynthILT.Hub", "interface name");
// The hub split into the neutral RynthServer.Hub (RynthServerHubApi.cs) on 2026-10-21: the ids are
// the wire format and kept their values.
Check.Eq(RynthServerHubApiV1.InterfaceName, "RynthServer.Hub", "the neutral interface name");
Check.Eq(string.Join(",", RynthServerHub.SectionRemoteBank, RynthServerHub.SectionRemoteGuardian, RynthServerHub.SectionRemoteStats,
RynthServerHub.SectionRemoteOptions, RynthServerHub.SectionPetCharms, RynthServerHub.SectionPetCapture,
RynthServerHub.SectionPetLogs, RynthServerHub.SectionServerStatus, RynthServerHub.SectionServerMenu),
"remote-bank,remote-guardian,remote-stats,remote-options,pets-charms,pets-capture,pets-logs,ilt-status,server-menu",
"section ids unchanged");
Check.Eq(string.Join(",", RynthServerHub.TabParentPets, RynthServerHub.TextSessionReport, RynthServerHub.TextServerId,
RynthServerHub.FeatureQuests, RynthServerHub.SettingVaultedDungeons),
"pets,session-report,server-id,quests,vaulted-dungeons", "tab, text, feature and setting ids unchanged");
Check.Eq((RynthServerHub.TabShown, RynthServerHub.TabAvailable), (1u, 2u), "tab flags unchanged");
Check.Eq(RynthAiHubApiV1.InterfaceName, "RynthAi.Hub", "RynthAi's interface name");
}
private static void DescribeLines()
{
var s = new IltSettings();
Check.True(ServerFeatureGate.Describe("InfiniteLeaftide", s, false).Contains("ON - matches 'InfiniteLeaftide'"), "on by name");
Check.True(ServerFeatureGate.Describe("Aelrynth", s, true).Contains("Treat this world as ILT"), "on by the override");
Check.True(ServerFeatureGate.Describe("Aelrynth", s, false).Contains("OFF"), "off");
Check.True(ServerFeatureGate.Describe("", s, false).Contains("not logged in"), "before login");
}
private static IltHubController NewHub(string world, string folder)
{
RynthCore.RynthAiHostTests.Fakes.FakeHost.Reset();
RynthCore.RynthAiHostTests.Fakes.FakeHost.WorldName = world;
var host = RynthCore.RynthAiHostTests.Fakes.FakeHost.Create(0x50000F01);
string dir = Path.Combine(Program.TempRoot, "move-" + folder);
Directory.CreateDirectory(dir);
return new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host));
}
private static void TickFor(IltHubController hub, int ms)
{
var until = DateTime.UtcNow.AddMilliseconds(ms);
while (DateTime.UtcNow < until) { hub.Tick(); System.Threading.Thread.Sleep(50); }
}
/// <summary>
/// The charms JSON behind "RynthILT.Data" is valid JSON; on ILT it has a "hands" array (empty
/// with no hand carried) that the shared reader parses, off ILT it has none and still parses.
/// </summary>
private static void CharmsReaderJson()
{
var on = NewHub("InfiniteLeaftide", "charms-on");
string json = on.CharmsTab.BuildReaderJson();
using (var doc = System.Text.Json.JsonDocument.Parse(json))
Check.True(doc.RootElement.TryGetProperty("hands", out var hands) && hands.GetArrayLength() == 0,
"on ILT: an empty hands array with no Guardian Hand carried");
Check.True(json.All(c => c < 128), "ASCII only");
var view = IltCharmsView.Parse(json);
Check.True(view.Loaded && view.Hands.Count == 0, "the shared reader takes it");
var withHands = IltCharmsView.Parse("{\"available\":true,\"charms\":[],\"hands\":[" +
"{\"id\":1234,\"name\":\"Guardian Hand\",\"active\":\"on\",\"server\":\"off\"},{\"id\":0,\"name\":\"no id\"}]}");
Check.Eq(withHands.Hands.Count, 1, "a hand without an id is skipped (nothing to toggle)");
Check.True(withHands.Hands[0] == new IltHandRow(1234, "Guardian Hand", "on", "off"), "id, name, active, server");
var off = NewHub("Aeshnidae", "charms-off");
string offJson = off.CharmsTab.BuildReaderJson();
using (var doc = System.Text.Json.JsonDocument.Parse(offJson))
Check.False(doc.RootElement.TryGetProperty("hands", out _), "off ILT: no hands");
Check.True(IltCharmsView.Parse(offJson).Hands.Count == 0, "and the reader shows none");
}
/// <summary>The Character tab moved out (2026-10-13); every other ILT tab is still RynthILT's.</summary>
private static void MovedSections()
{
Check.Eq(IltSections.MovedCommand(IltSection.Character), IltSections.OracleCharacterCommand, "Character -> RynthOracle Character");
foreach (var kept in new[] { IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games })
{
Check.True(IltSections.MovedCommand(kept) == null, $"{IltSections.Label(kept)} is still RynthILT's");
Check.True(IltSections.IsTab(kept), $"{IltSections.Label(kept)} is a Mini Remote tab");
}
Check.True(IltSections.MovedCommand(IltSection.VaultedDungeons) == null && IltSections.IsTab(IltSection.VaultedDungeons),
"Vaulted Dungeons is a RynthILT tab (shown only with the master switch, VaultedDungeonsTests)");
Check.True(IltSections.Tabs.SequenceEqual(new[] { IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, IltSection.VaultedDungeons }),
"the tab list is Banking, Gear, Charms, Games, Vaulted Dungeons");
Check.False(IltSections.IsTab(IltSection.Character) || IltSections.IsTab(IltSection.Guardian), "Character and the Guardian aren't tabs");
Check.True(IltSections.TryParse("char", out IltSection c) && c == IltSection.Character, "old Character names still parse (for the redirect)");
Check.Eq(IltSections.OracleCharacterCommand, "/ro character", "Oracle command");
}
/// <summary>
/// RynthILT's RynthPluginGetSectionsJson: schema 1 (UI/Sections/SectionManifest.cs in RynthCore),
/// every view an ILT one, each surface one RenderEmbed answers.
/// </summary>
private static void SectionsManifest()
{
// No Hub (before the character's name is known): the always-there views only.
string bare = IltSectionsManifest.Build(IltSectionsManifest.TabsOf(null));
using var doc = System.Text.Json.JsonDocument.Parse(bare);
var root = doc.RootElement;
Check.Eq(root.GetProperty("version").GetInt32(), 1, "schema 1");
var sections = root.GetProperty("sections");
Check.Eq(sections.GetArrayLength(), 2, "two sections of RynthILT's own");
Check.Eq(sections[0].GetProperty("id").GetString(), "quests", "a Quests section (the /qb list)");
Check.Eq(sections[1].GetProperty("id").GetString(), "games", "and Games (moved from RynthAi with the tabs)");
var surfaces = new System.Collections.Generic.List<string>();
foreach (var c in root.GetProperty("contributions").EnumerateArray())
{
Check.Eq(c.GetProperty("server").GetString(), "ilt", "an Infinite Leaftide view");
surfaces.Add(c.GetProperty("surface").GetString() ?? "");
}
Check.True(surfaces.SequenceEqual(new[] { RynthILTPlugin.RatesSurface, RynthILTPlugin.FellowshipSurface, RynthILTPlugin.QuestBonusSurface,
RynthILTPlugin.DynamicStampsSurface }),
"rates, fellowship, quest bonus, Dynamic Stamps (from RynthOracle 2026-10-21): " + string.Join(",", surfaces));
Check.True(surfaces.All(s => s.StartsWith("section:ilt-", StringComparison.Ordinal) && s.Length <= 64), "short section:ilt-* surfaces");
Check.True(bare.All(ch => ch < 128), "ASCII only");
// The Mini Remote ILT tabs the Hub shows (RynthAi listed them until 2026-10-20): Gear not reported yet,
// Games hidden, Charms and Banking shown.
var tabs = new[]
{
new IltSectionsManifest.Tab("banking", 560, 520, Shown: true, Available: true),
new IltSectionsManifest.Tab("gear", 560, 520, Shown: true, Available: false),
new IltSectionsManifest.Tab("charms", 560, 520, Shown: true, Available: true),
new IltSectionsManifest.Tab("games", 520, 440, Shown: false, Available: false),
new IltSectionsManifest.Tab("character", 520, 440, Shown: true, Available: true),
};
string json = IltSectionsManifest.Build(tabs);
var m = RynthCore.Engine.UI.Sections.SectionManifestParser.Parse("RynthILT", json, out string error);
Check.Eq(error, string.Empty, "the engine's parser takes it");
Check.Eq(m.Contributions.Length, 7, "rates, fellowship, /qb, Dynamic Stamps, Banking, Gear, Charms");
var stamps = m.Contributions.Single(c => c.Surface == RynthILTPlugin.DynamicStampsSurface);
Check.True(stamps.Section == "quests" && stamps.Primary && stamps.Server == "ilt" && stamps.Label == "Dynamic Stamps",
"Dynamic Stamps: a page of RynthILT's Quests section, on ILT only");
var gear = m.Contributions.Single(c => c.Surface == "section:gear");
Check.True(gear.Section == "inventory" && !gear.Enabled && gear.Note.Length > 0, "Gear in Inventory, disabled with a note until reported");
Check.True(m.Contributions.Any(c => c.Surface == "section:charms" && c.Enabled) && m.Contributions.Any(c => c.Surface == "section:banking" && c.Enabled),
"Charms and Banking stay RynthILT's tabs");
Check.False(m.Contributions.Any(c => c.Surface == "section:games"), "a hidden tab isn't listed");
Check.False(m.Contributions.Any(c => c.Surface == "section:character"), "Character moved out: never placed");
var iltOn = new RynthCore.Engine.UI.Sections.ServerState("ilt", "Infinite Leaftide", true, true, RynthCore.Engine.UI.Sections.ServerForce.Auto, true, "");
var on = RynthCore.Engine.UI.Sections.SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn });
Check.True(on.Single(v => v.Id == "inventory").Panes.Any(p => p.Title == "Charms" && p.Contribution?.Plugin == "RynthILT"),
"on ILT the engine shows RynthILT's Charms in Inventory (drawn by RynthILT)");
var off = RynthCore.Engine.UI.Sections.SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn with { Active = false } });
Check.False(off.Single(v => v.Id == "inventory").Panes.Any(p => p.Title == "Charms"), "off ILT: none");
Check.True(IltSectionsManifest.TryTabOf("section:banking", out IltSection bank) && bank == IltSection.Banking, "section:banking draws Banking");
Check.False(IltSectionsManifest.TryTabOf("section:bank", out _), "only the tab's own id");
Check.False(IltSectionsManifest.TryTabOf("section:pets", out _), "pets is RynthAi's");
Check.False(IltSectionsManifest.TryTabOf("section:ilt-rates", out _), "not a tab");
Check.True(RynthILTPlugin.IsParsedRemoteAction("servermenu") && RynthILTPlugin.IsParsedRemoteAction("ServerMenu")
&& !RynthILTPlugin.IsParsedRemoteAction("prog"), "RynthCore's servermenu push is answered, never queued as a verb");
}
private static void DormantOffIlt()
{
var off = NewHub("Aeshnidae", "dormant");
off.OnLoginComplete("Tester", forceFromMigration: false);
foreach (string line in new[] { "Your Pet Log:", "[BANK] Pyreals: 5", "Guardian of Strength tells you, \"x\"" }) off.OnChat(line);
TickFor(off, 6800); // past the 6 s login delay
Check.Eq(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Count, 0, "off ILT: no probe, no command at all");
Check.False(off.Options.IsIltLikeWorld, "not an ILT world");
foreach (var s in IltSections.Tabs) Check.False(off.TabShown(s), $"no {IltSections.Label(s)} tab");
Check.False(off.RenderSection(RynthServerHub.SectionRemoteBank) || off.RenderSection(RynthIltHub.SectionQuestBonus)
|| off.RenderSection(RynthServerHub.SectionPetLogs) || off.RenderSection(RynthServerHub.SectionRemoteGuardian)
|| off.RenderSection(RynthServerHub.SectionServerMenu), "no ILT section draws (checked before any ImGui call)");
Check.True(off.BuildProgressionJson().StartsWith("{\"available\":false"), "Progression: not available");
off.OnLogout();
var on = NewHub("InfiniteLeaftide", "awake");
on.OnLoginComplete("Tester", forceFromMigration: false);
TickFor(on, 6800);
Check.True(on.Options.IsIltLikeWorld, "InfiniteLeaftide is ILT");
Check.True(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Count > 0, "on ILT the login probe asks the server");
Check.False(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Any(c => c.Contains("/ilt features", StringComparison.OrdinalIgnoreCase)),
"the server is never asked for a feature list (the ILT profile is Rynth-side)");
// Character moved out of the Mini Remote (RynthOracle's Character tab, Session Stats);
// Charms and Banking are Infinite Leaftide's own screens and stay RynthILT's tabs.
Check.False(on.TabShown(IltSection.Character), "Character is no Mini Remote tab any more");
Check.Eq(on.TabShown(IltSection.Gear), on.Available, "Gear shows once the server features are known");
Check.Eq(on.TabShown(IltSection.Charms), on.Available, "Charms too");
on.OnLogout();
var forced = NewHub("Aeshnidae", "forced");
forced.OnLoginComplete("Tester", forceFromMigration: true);
Check.True(forced.Options.IsIltLikeWorld, "a migrated \"Force enable\" makes the world ILT for this character");
forced.OnLogout();
}
private static unsafe void HubTable()
{
Check.Eq(HubInterface.Query("RynthAi.Hub", 1), IntPtr.Zero, "another interface's name: not ours");
Check.Eq(HubInterface.Query(RynthIltHub.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none");
var t = (RynthServerHubApiV1*)HubInterface.Query(RynthIltHub.InterfaceName, 1);
Check.True(t != null, "v1 is served");
Check.Eq(t->Version, 1u, "Version 1");
Check.Eq(t->StructSize, (uint)sizeof(RynthServerHubApiV1), "StructSize");
Check.True(t->IsServerWorld != null && t->GetFeature != null && t->GetRates != null && t->GetForceServer != null && t->SetForceServer != null
&& t->GetTabs != null && t->RenderTab != null && t->RenderSection != null && t->Command != null
&& t->AllowSummonOnEmpty != null && t->GetSubTabs != null && t->GetSetting != null && t->SetSetting != null,
"every function is filled in");
Check.True(RynthServerHubApiV1.Has(t, RynthServerHubApiV1.GetSubTabsOffset), "the appended functions are inside StructSize");
Check.Eq((IntPtr)t, HubInterface.Query(RynthIltHub.InterfaceName, 1), "the same table each time");
Check.Eq((IntPtr)t, HubInterface.Query(RynthServerHubApiV1.InterfaceName, 1),
"and under the server-neutral name RynthAi asks the active server's owner for (RynthServer.Hub)");
// No plugin instance here (not logged in): every function answers "nothing".
Check.Eq(t->IsServerWorld(), 0, "not ILT before login");
byte* key = stackalloc byte[] { (byte)'b', (byte)'a', (byte)'n', (byte)'k', 0 };
Check.Eq(t->GetFeature(key), -1, "feature unknown before login");
Check.Eq(t->GetTabs(null, 0), 0, "no tabs before login");
Check.Eq(t->Command(key), 0, "no command taken before login");
Check.Eq(t->AllowSummonOnEmpty(), 0, "no summon from empty before login");
byte* pets = stackalloc byte[] { (byte)'p', (byte)'e', (byte)'t', (byte)'s', 0 };
Check.Eq(t->GetSubTabs(pets, null, 0), 0, "no Pets sub-tabs before login");
Check.Eq(t->GetSetting(pets), -1, "no setting offered before login");
Check.Eq(t->SetSetting(pets, 1), 0, "and none taken");
HubInterface.Release();
Check.Eq(t->Version, 0u, "Release zeroes Version (callers re-query)");
Check.Eq(HubInterface.Query(RynthIltHub.InterfaceName, 1), IntPtr.Zero, "and nothing is served after shutdown");
Check.Eq(t->IsServerWorld(), 0, "the old table stays callable and answers nothing");
}
}

View file

@ -0,0 +1,189 @@
using System;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// ACECustom's parts of RynthAi's Pets tab moved to RynthILT on 2026-10-20 (Hub/IltPetAutomation.cs):
// the pet charms, the summon-from-empty refill gate RynthAi's PetManager asks through RynthILT.Hub,
// siphon-lens auto-capture and the Breeding sub-tab offer. Their settings are copied once from the
// character's RynthAi miniremote.json (IltMigration.ImportRynthAiSettings).
internal static class PetAutomationTests
{
private const uint Player = 0x50000A01;
private const uint Lens = 0x80000A02;
private const uint Mob = 0x80000A03;
private const uint Charm = 0x80000A04;
private const uint Lb = 0xA9B40000;
public static void Register(Runner r)
{
r.Add("pets (RynthILT): summon from empty needs the opt-in, an active refill charm and the server's word; never off ILT", RefillGate);
r.Add("pets (RynthILT): auto-capture uses the lens on a weak creature in range only, and only when switched on", Capture);
r.Add("pets (RynthILT): the Breeding sub-tab is offered on ILT unless the server reports breeding off", BreedingSubTab);
r.Add("pets (RynthILT): off ILT the Pets sections draw nothing and nothing ticks", DormantOffIlt);
r.Add("migration: the Pets tab's ACECustom options come over from RynthAi's miniremote.json once", ImportsPetSettings);
}
private static IltHubController NewHub(string world, string folder, Action? setup = null)
{
FakeHost.Reset();
FakeHost.WorldName = world;
FakeHost.ContentsCalls = true;
FakeHost.WeaponCalls = true; // UseObject, RequestId, appraisal state
FakeHost.LiveObjectsCalls = true;
FakeHost.Names[Player] = "Petter";
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
setup?.Invoke();
var host = FakeHost.Create(Player);
string dir = Path.Combine(Program.TempRoot, "pets-" + folder);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host));
hub.OnLoginComplete("Petter", forceFromMigration: false);
return hub;
}
private static void Carry(uint id, string name, uint wcid)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = 0x80; // misc
FakeHost.Containers[id] = Player;
FakeHost.Wcids[id] = wcid;
}
private static void RefillGate()
{
var hub = NewHub("InfiniteLeaftide", "refill", () => FakeHost.Bools[(Player, IltInventory.BoolPyrealRefillActive)] = true);
var pets = hub.PetAutomation;
Check.False(pets.ComputeAllowSummonOnEmpty(), "not opted in: no summon from empty");
hub.State.Pet.RefillFromEmpty = true;
Check.True(pets.ComputeAllowSummonOnEmpty(), "opted in, and the server stamped the refill bool (active and confirmed)");
var charmOnly = NewHub("InfiniteLeaftide", "refill-charm", () =>
{
Carry(Charm, "Summon Essence Refill Charm", IltInventory.WcidSummonRefillCharm);
FakeHost.Strings[(Charm, IltInventory.StrUse)] = "Toggles the refill. Status: ON";
});
charmOnly.State.Pet.RefillFromEmpty = true;
Check.True(charmOnly.PetAutomation.RefillCharmActive(), "the carried charm reads ON");
Check.False(charmOnly.PetAutomation.ComputeAllowSummonOnEmpty(), "but the server hasn't confirmed pet_refill: never spend");
charmOnly.Options.Set(IltFeature.PetRefill, IltTri.On);
Check.True(charmOnly.PetAutomation.ComputeAllowSummonOnEmpty(), "confirmed: summon from empty");
charmOnly.Tick();
Check.True(charmOnly.PetAutomation.AllowSummonOnEmpty, "the tick caches it for RynthAi (RynthILT.Hub AllowSummonOnEmpty)");
var off = NewHub("Aeshnidae", "refill-off", () => FakeHost.Bools[(Player, IltInventory.BoolPyrealRefillActive)] = true);
off.State.Pet.RefillFromEmpty = true;
Check.False(off.PetAutomation.ComputeAllowSummonOnEmpty(), "off ILT: never");
off.Tick();
Check.False(off.PetAutomation.AllowSummonOnEmpty, "and nothing cached for RynthAi");
}
private static void Capture()
{
var hub = NewHub("InfiniteLeaftide", "capture", () =>
{
Carry(Lens, "Flawed Siphon Lens", PetCaptureRules.Lenses[0].Wcid);
FakeHost.Names[Mob] = "Drudge Skulker";
FakeHost.ItemTypes[Mob] = 0x10; // creature
FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f); // 3 m
FakeHost.TargetVitals[Mob] = (100, 100);
});
var pets = hub.PetAutomation;
long now = Environment.TickCount64; // the chat replies time their back-off on the real clock
pets.TickCapture(now);
Check.Eq(FakeHost.Uses.Count, 0, "switched off: no lens used");
Check.Eq(pets.CaptureStatus, "off", "status off");
hub.State.Pet.AutoCapture = true;
pets.TickCapture(now);
Check.Eq(FakeHost.Uses.Count, 0, "a full-health creature: no lens");
Check.True(pets.CaptureStatus.Contains("Drudge Skulker") && pets.CaptureStatus.Contains("need"), "it says what it waits for");
FakeHost.TargetVitals[Mob] = (15, 100);
pets.TickCapture(now + 1000);
Check.Eq(FakeHost.Uses.Count, 1, "15%: the lens is used");
Check.Eq(FakeHost.Uses[0], Lens, "the chosen lens");
pets.TickCapture(now + 1500);
Check.Eq(FakeHost.Uses.Count, 1, "the cooldown holds the next use back");
pets.OnChat("The creature is too strong to be siphoned.");
Check.True(pets.CaptureStatus.StartsWith("refused"), "a refusal is noted");
FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 110f, 0f); // 14 m
pets.TickCapture(now + 60_000);
Check.Eq(FakeHost.Uses.Count, 1, "out of range: no lens");
hub.Options.Set(RynthIltHub.FeatureMonsterCapture, IltTri.Off);
FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f);
pets.TickCapture(now + 120_000);
Check.Eq(FakeHost.Uses.Count, 1, "the server reports monster capture off: no lens");
Check.True(pets.CaptureStatus.Contains("disabled"), "and says so");
}
private static void BreedingSubTab()
{
var on = NewHub("InfiniteLeaftide", "breed-on");
var tabs = on.SubTabs(RynthServerHub.TabParentPets);
Check.Eq(tabs.Length, 1, "one Pets sub-tab on ILT");
Check.Eq(tabs[0].Id, RynthIltHub.SectionPetBreeding, "Breeding, drawn as the pets-breeding section");
Check.Eq(on.SubTabs("crafting").Length, 0, "nothing for another tab");
on.Options.Set(RynthIltHub.FeaturePetBreeding, IltTri.Off);
Check.Eq(on.SubTabs(RynthServerHub.TabParentPets).Length, 0, "the server reports breeding off: none");
var off = NewHub("Aeshnidae", "breed-off");
Check.Eq(off.SubTabs(RynthServerHub.TabParentPets).Length, 0, "off ILT: none");
}
private static void DormantOffIlt()
{
var off = NewHub("Aeshnidae", "dormant", () =>
{
Carry(Lens, "Flawed Siphon Lens", PetCaptureRules.Lenses[0].Wcid);
FakeHost.Names[Mob] = "Drudge Skulker";
FakeHost.ItemTypes[Mob] = 0x10;
FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f);
FakeHost.TargetVitals[Mob] = (1, 100);
});
off.State.Pet.AutoCapture = true;
for (int i = 0; i < 5; i++) { off.Tick(); System.Threading.Thread.Sleep(60); }
Check.Eq(FakeHost.Uses.Count, 0, "off ILT the capture never ticks (no lens used)");
Check.False(off.RenderSection(RynthServerHub.SectionPetCharms) || off.RenderSection(RynthServerHub.SectionPetCapture),
"the Pets sections draw nothing (checked before any ImGui call)");
}
private static void ImportsPetSettings()
{
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Petter");
Directory.CreateDirectory(legacy);
File.WriteAllText(Path.Combine(legacy, "Default.json"), "{}");
File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyMiniRemoteFile),
"{ \"Pet\": { \"HealingEnabled\": true, \"UsePyrealRefillPath\": true, \"AutoCaptureEnabled\": true, \"CaptureLensIndex\": 3 } }");
var state = new IltHubState();
Check.False(state.Pet.RefillFromEmpty || state.Pet.AutoCapture, "RynthILT's defaults: both off");
var lines = IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Petter");
Check.True(state.RynthAiSettingsImported, "marked done");
Check.True(state.Pet.RefillFromEmpty, "summon from empty came over");
Check.True(state.Pet.AutoCapture, "auto-capture came over");
Check.Eq(state.Pet.CaptureLens, 3, "the lens came over");
Check.True(lines.Any(l => l.Contains("auto-capture on")), "and the log line says so");
state.Pet.AutoCapture = false; // changed in RynthILT afterwards
Check.Eq(IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Petter").Count, 0, "the second login does nothing");
Check.False(state.Pet.AutoCapture, "RynthILT's own change stays");
var fresh = new IltHubState();
IltMigration.ImportRynthAiSettings(fresh, "InfiniteLeaftide", "Nobody");
Check.True(fresh.RynthAiSettingsImported && !fresh.Pet.AutoCapture && !fresh.Pet.RefillFromEmpty,
"a character without RynthAi files keeps the defaults (and is marked done)");
File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyMiniRemoteFile), "{ broken");
var broken = new IltHubState();
IltMigration.ImportRynthAiSettings(broken, "InfiniteLeaftide", "Petter");
Check.True(broken.RynthAiSettingsImported && !broken.Pet.AutoCapture, "an unreadable miniremote.json: defaults, no exception");
}
}

View file

@ -0,0 +1,109 @@
// ACECustom MonsterCapture health / range / lens table — matches Source/ACE.Server/Entity/MonsterCapture.cs.
// Moved from RynthCore.RynthAiTests with the rules (RynthILT's IltPetCaptureRules since 2026-10-20).
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
internal static class PetCaptureRulesTests
{
public static void Register(Runner r)
{
r.Add("pet capture: health gate matches ACECustom (≤20% or under 20 HP)", HealthGate);
r.Add("pet capture: Asheron's Lens bypasses the health gate", AsheronsBypass);
r.Add("pet capture: range is 5 m; dead creatures are never capturable", RangeAndDead);
r.Add("pet capture: lens WCIDs match PetGuideController", LensWcids);
r.Add("pet capture: a creature is left alone after 5 tries with no capture, then retried after the block", ThrottlePerTarget);
r.Add("pet capture: 15 lens uses with no capture anywhere trip the backstop; a success resets it", ThrottleBackstop);
}
private static void HealthGate()
{
// Full health — refuse.
Check.False(PetCaptureRules.IsWeakEnough(100, 100), "100/100 too strong");
Check.False(PetCaptureRules.IsWeakEnough(21, 100), "21% and ≥20 HP too strong");
// Fraction gate.
Check.True(PetCaptureRules.IsWeakEnough(20, 100), "20% exactly is allowed");
Check.True(PetCaptureRules.IsWeakEnough(1, 100), "1% allowed");
// Absolute HP gate (high % but under 20 HP).
Check.True(PetCaptureRules.IsWeakEnough(15, 50), "15/50 = 30% but under 20 HP");
Check.True(PetCaptureRules.IsWeakEnough(19, 19), "19/19 under 20 HP");
// Ratio-only path (no absolute HP): only the fraction half.
Check.True(PetCaptureRules.IsWeakEnoughRatio(0.20f), "ratio 0.20");
Check.False(PetCaptureRules.IsWeakEnoughRatio(0.21f), "ratio 0.21");
Check.False(PetCaptureRules.IsWeakEnoughRatio(0f), "ratio 0 = dead");
Check.False(PetCaptureRules.IsWeakEnough(0, 100), "0 current = dead");
}
private static void AsheronsBypass()
{
var asheron = PetCaptureRules.LensAt(4);
Check.Eq(asheron.Wcid, 78780012u, "Asheron's WCID");
Check.True(asheron.BypassesHealthGate, "bypasses health");
Check.True(PetCaptureRules.CanAttempt(asheron, 100, 100), "full health ok for Asheron's");
Check.False(PetCaptureRules.CanAttempt(asheron, 0, 100), "still not when dead");
var flawed = PetCaptureRules.LensAt(0);
Check.False(PetCaptureRules.CanAttempt(flawed, 100, 100), "Flawed refuses full health");
Check.True(PetCaptureRules.CanAttempt(flawed, 10, 100), "Flawed at 10%");
}
private static void RangeAndDead()
{
Check.Eq(PetCaptureRules.CaptureRangeM, 5.0f, "5 m range");
Check.True(PetCaptureRules.InRange(0), "at feet");
Check.True(PetCaptureRules.InRange(5.0), "at 5 m");
Check.False(PetCaptureRules.InRange(5.01), "past 5 m");
Check.False(PetCaptureRules.InRange(-1), "unknown distance");
}
private static void LensWcids()
{
Check.Eq(PetCaptureRules.Lenses.Length, 5, "five selectable lenses");
Check.Eq(PetCaptureRules.LensAt(0).Wcid, 78780001u, "Flawed");
Check.Eq(PetCaptureRules.LensAt(1).Wcid, 78780002u, "Pristine");
Check.Eq(PetCaptureRules.LensAt(2).Wcid, 78780003u, "Perfect");
Check.Eq(PetCaptureRules.LensAt(3).Wcid, 78780010u, "Resonance");
Check.Eq(PetCaptureRules.LensAt(4).Wcid, 78780012u, "Asheron's");
Check.Eq(PetCaptureRules.LensNames.Length, PetCaptureRules.Lenses.Length, "combo labels match");
}
private static void ThrottlePerTarget()
{
var t = new PetCaptureThrottle();
long now = 1000;
for (int i = 0; i < PetCaptureThrottle.MaxTriesPerTarget; i++)
{
Check.True(t.MayAttempt(7, now), $"try {i + 1} allowed");
t.RecordAttempt(7, now);
now += 2500;
}
Check.False(t.MayAttempt(7, now), "5 tries used: blocked");
Check.True(t.BlockedSecondsLeft(7, now) > 0, "block time left reported");
Check.True(t.MayAttempt(8, now), "another creature is not blocked");
Check.False(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs - 3000), "still blocked just before the block ends");
Check.True(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 1), "block served: tries again");
t.RecordAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 1);
Check.True(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 2), "a fresh set of tries after the block");
}
private static void ThrottleBackstop()
{
var t = new PetCaptureThrottle();
long now = 0;
for (int i = 0; i < PetCaptureThrottle.MaxTriesWithoutSuccess; i++)
{
Check.False(t.Exhausted, $"not exhausted before use {i + 1}");
t.RecordAttempt(100 + i, now); // a new creature each time: per-target never trips
now += 2500;
}
Check.True(t.Exhausted, "15 uses over many creatures, no capture: exhausted");
Check.False(t.MayAttempt(999, now), "nothing more is allowed");
t.RecordSuccess();
Check.False(t.Exhausted, "a capture reply resets the backstop");
Check.True(t.MayAttempt(100, now), "and the per-target blocks");
}
}

View file

@ -0,0 +1,98 @@
using System;
using System.Linq;
using System.Text.Json;
using RynthCore.Plugin.RynthILT;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// RynthILT's "RynthServer.Profile" (ProfileInterface.cs): the same interface and JSON the server
// plugins serve, for "ilt", carrying Infinite Leaftide's tinkering salvage (Hub/IltSalvage.cs).
// The JSON is read back with the shared reader RynthAi's Crafting tab uses (EngineServerState.cs:
// ServerSalvageView.ParseList), so the rows it plans with are the ones checked here. 2026-10-15.
internal static unsafe class ProfileTests
{
public static void Register(Runner r)
{
r.Add("profile: RynthILT serves RynthServer.Profile for ilt", Interface);
r.Add("profile: ILT's salvage reaches the Crafting tab's reader (Leather after the cap, jewelry stack)", Salvage);
r.Add("profile: ILT's trinkets reach the Crafting tab's reader (RynthAi's TinkerCatalog rule until 2026-10-20)", Trinkets);
}
private static void Interface()
{
Check.Eq(ProfileInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not this table");
Check.Eq(ProfileInterface.Query(RynthServerProfileApiV1.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none");
var t = (RynthServerProfileApiV1*)ProfileInterface.Query(RynthServerProfileApiV1.InterfaceName, 1);
Check.True(t != null, "the table");
Check.Eq(t->Version, RynthServerProfileApiV1.InterfaceVersion, "version");
Check.Eq(t->StructSize, (uint)sizeof(RynthServerProfileApiV1), "struct size");
Check.True(t->GetProfileJson != null, "GetProfileJson");
string json = ProfileInterface.CurrentJson(true, "InfiniteLeaftide");
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
Check.Eq(root.GetProperty("schema").GetInt32(), RynthServerProfile.Schema, "schema");
Check.Eq(root.GetProperty("id").GetString(), "ilt", "the engine's ILT id");
Check.Eq(root.GetProperty("name").GetString(), "Infinite Leaftide", "name");
Check.Eq(root.GetProperty("plugin").GetString(), "RynthILT", "plugin");
Check.True(root.GetProperty("active").GetBoolean(), "active");
Check.Eq(root.GetProperty("world").GetString(), "InfiniteLeaftide", "world");
Check.Eq(root.GetProperty("hosts")[0].GetString(), "infiniteleaftide.online", "hosts from the csproj");
Check.Eq(ProfileInterface.CurrentJson(true, "InfiniteLeaftide"), json, "unchanged state: the same JSON");
Check.False(JsonDocument.Parse(ProfileInterface.CurrentJson(false, null)).RootElement.GetProperty("active").GetBoolean(),
"before the Hub is up: not active");
}
private static void Trinkets()
{
var rule = ServerTrinketRule.Parse(ProfileInterface.CurrentJson(true, "InfiniteLeaftide"));
Check.True(rule != ServerTrinketRule.None, "the profile carries a trinket rule");
foreach (string t in new[] { "Ornate Compass", "Tinker's Goggles", "Jade Scarab", "Pocket Watch", "Puzzle Box", "Spinning Top" })
Check.True(rule.IsTrinket(t), t + " is a trinket");
foreach (string j in new[] { "Yellow Topaz Ring", "Gold Necklace", "Silver Bracelet" })
Check.False(rule.IsTrinket(j), j + " is Jewelry");
}
private static void Salvage()
{
var rows = ServerSalvageView.ParseList(ProfileInterface.CurrentJson(true, "InfiniteLeaftide"));
Check.Eq(rows.Count, IltSalvage.Rows.Length, "every row arrives");
for (int i = 0; i < rows.Count; i++)
{
var a = IltSalvage.Rows[i];
var b = rows[i];
bool same = a.Bench == b.Bench && a.Material == b.Material && a.Kind == b.Kind && a.Effect == b.Effect
&& a.UsesTinkSlot == b.UsesTinkSlot && a.NameMatch == b.NameMatch && a.AppliedInt == b.AppliedInt
&& a.Prepared == b.Prepared && a.Order == b.Order && a.AfterCap == b.AfterCap
&& a.StackGroup == b.StackGroup && a.StackCap == b.StackCap;
Check.True(same, $"row {i} ({a.Bench} {a.Material}) round-trips");
}
const int Leather = 52, Steel = 64, Serpentine = 71, Silver = 63, Diamond = 20, BlackGarnet = 15;
foreach (string bench in new[] { "melee", "missile", "caster" })
{
var leather = rows.Single(r => r.Bench == bench && r.Material == Leather);
Check.True(leather.AfterCap, bench + " Leather: after the cap");
Check.False(leather.UsesTinkSlot, bench + " Leather: no tink slot");
Check.Eq(leather.Kind, "once", bench + " Leather: once");
Check.Eq(leather.Order, 995, bench + " Leather: last");
}
Check.Eq(rows.Count(r => r.AfterCap), 3, "only the weapon Leathers wait for the cap");
var stack = rows.Where(r => r.StackGroup.Length > 0).ToList();
Check.Eq(string.Join(",", stack.Select(r => r.Bench + ":" + r.Material)), $"jewelry:{Serpentine},jewelry:{Steel}", "Serpentine + Steel stack");
Check.True(stack.All(r => r.StackGroup == "jewelry-stack" && r.StackCap == 10 && r.Kind == "tink" && !r.UsesTinkSlot),
"one group, cap 10, repeatable, no tink slot");
Check.Eq(rows.Single(r => r.Bench == "jewelry" && r.Material == Silver).AppliedInt, 374, "jewelry Silver flag int");
var diamond = rows.Single(r => r.Bench == "trinkets" && r.Material == Diamond);
Check.True(diamond.Prepared && diamond.AppliedInt == 384 && diamond.Order == 10, "trinket Diamond: prepared, flag 384, first");
Check.Eq(rows.Count(r => r.Prepared), 4, "the four trinket tiers are prepared");
Check.True(rows.Where(r => r.Material == BlackGarnet).All(r => r.NameMatch == "Abyssal" && r.UsesTinkSlot),
"Abyssal-Touched Gems by bag name, using a tink slot");
Check.False(rows.Any(r => r.Bench is "armor" or "items"), "no armor or item rows");
}
}

View file

@ -0,0 +1,64 @@
using System;
using System.IO;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// Offline tests for the RynthILT plugin: the ACECustom bounty tracker (parsing, merging, the
// quiet /bounty list read loop on a fake clock, persistence, the bridge JSON) and the ILT Hub
// (attribute raiser, aug costs, bank commands, sigil chain, and the move out of RynthAi: data
// migration, the RynthILT.Hub table, verb routing, the object view) and its RynthServer.Profile
// (ILT's tinkering salvage). Each test prints PASS / FAIL.
//
// Run: dotnet run -c Release (all tests)
// dotnet run -c Release -- window (tests whose name contains "window")
internal static class Program
{
/// <summary>Scratch folder next to the exe for files tests write. Emptied at start.</summary>
public static string TempRoot { get; } = Path.Combine(AppContext.BaseDirectory, "scratch");
private static int Main(string[] args)
{
if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true);
Directory.CreateDirectory(TempRoot);
// SAFETY: every file the ILT Hub would write under %APPDATA%\RynthCore\RynthILT or read from
// the RynthAi folder points at the scratch folder before any test runs.
RynthCore.Plugin.RynthILT.Hub.IltAugCosts.FilePath = Path.Combine(TempRoot, "ilt-aug-costs.json");
RynthCore.Plugin.RynthILT.Hub.IltHubStore.SharedRoot = Path.Combine(TempRoot, "RynthILT");
RynthCore.Plugin.RynthILT.Hub.IltSettingsStore.Folder = Path.Combine(TempRoot, "RynthILT");
RynthCore.Plugin.RynthILT.Hub.IltMigration.LegacyProfilesBase = Path.Combine(TempRoot, "RynthAi", "SettingsProfiles");
RynthCore.Plugin.RynthILT.Hub.IltMigration.LegacySharedRoot = Path.Combine(TempRoot, "RynthAi");
RynthCore.Plugin.RynthILT.RynthLog.Init(default, Path.Combine(TempRoot, "Logs"));
RynthCore.Plugin.Shared.DataWriteGuard.PluginName = "RynthILT"; // as RynthILTPlugin.Initialize sets it
var runner = new Runner();
BountyTests.Register(runner);
BountyReviewTests.Register(runner);
AttributeRaiserTests.Register(runner);
SigilChainTests.Register(runner);
BankCommandTests.Register(runner);
MoveTests.Register(runner);
ChunkTests.Register(runner);
ProfileTests.Register(runner);
FeatureCatalogTests.Register(runner);
IltSettingsTests.Register(runner);
FellowshipCommandTests.Register(runner);
AetheriaChunkTests.Register(runner);
ChunkTargetTests.Register(runner);
RingChainTests.Register(runner);
VaultedDungeonsTests.Register(runner);
PetCaptureRulesTests.Register(runner);
PetAutomationTests.Register(runner);
RingEvadeTests.Register(runner);
VaultedSwitchTests.Register(runner);
T11Tests.Register(runner);
RemoteTabTests.Register(runner);
StampTests.Register(runner);
BankRosterTests.Register(runner);
// Before DataApiTests: its last test releases the RynthILT.Data table, which the breeding version test queries.
BreedingTests.Register(runner);
DataApiTests.Register(runner);
return runner.Run("RynthILT tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -0,0 +1,94 @@
using System;
using System.IO;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The ILT parts of RynthAi's Remote tab moved to RynthILT on 2026-10-20: the coin / pyreal lines under
// RynthAi's Stats ("remote-stats"), the session report's tail (GetText "session-report"), the Bank and
// Guardian sections' switches (RynthILT's own now, drawn in RynthAi's Options popup, "remote-options"),
// and the coin session restarting with RynthAi's shared session instead of RynthAi sending "rates reset".
internal static class RemoteTabTests
{
public static void Register(Runner r)
{
r.Add("remote tab (RynthILT): its texts for RynthAi (server id, the session report's coins) and none off ILT", Texts);
r.Add("remote tab (RynthILT): Bank / Guardian follow RynthILT's own switches; the stats and options draw nothing off ILT", Switches);
r.Add("remote tab (RynthILT): the coins start over when RynthAi's shared session restarts", FollowsSession);
r.Add("migration: RynthAi's huds.json Bank / Guardian switches come over once", ImportsSwitches);
}
private static IltHubController NewHub(string world, string folder)
{
FakeHost.Reset();
FakeAiHub.Reset();
FakeHost.WorldName = world;
var host = FakeHost.Create(0x50000D21);
var ai = new RynthAiClient(host);
ai.UseTableForTests(FakeAiHub.Table);
string dir = Path.Combine(Program.TempRoot, "remote-" + folder);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
var hub = new IltHubController(host, dir, new IltSettings(), ai);
hub.OnLoginComplete("Remoter", forceFromMigration: false);
return hub;
}
private static void Texts()
{
var on = NewHub("InfiniteLeaftide", "texts-on");
Check.Eq(on.GetText(RynthServerHub.TextServerId), "ilt", "its tabs belong to RynthCore's 'ilt'");
string tail = on.GetText(RynthServerHub.TextSessionReport);
Check.True(tail.StartsWith(", Coins ") && tail.Contains("/h, Pyr "), "the session report's tail: coins and pyreals per hour");
Check.Eq(on.GetText("no-such-text"), string.Empty, "an unknown id: nothing");
var off = NewHub("Aeshnidae", "texts-off");
Check.Eq(off.GetText(RynthServerHub.TextSessionReport), string.Empty, "off ILT: no coins in RynthAi's report");
}
private static void Switches()
{
var on = NewHub("InfiniteLeaftide", "switches");
Check.True(on.State.Remote.ShowBank && on.State.Remote.ShowGuardian, "both on by default");
on.State.Remote.ShowBank = false;
on.State.Remote.ShowGuardian = false;
Check.False(on.RenderSection(RynthServerHub.SectionRemoteBank), "Bank switched off: nothing drawn");
Check.False(on.RenderSection(RynthServerHub.SectionRemoteGuardian), "Guardian switched off: nothing drawn");
var off = NewHub("Aeshnidae", "switches-off");
Check.False(off.RenderSection(RynthServerHub.SectionRemoteStats) || off.RenderSection(RynthServerHub.SectionRemoteOptions)
|| off.RenderSection(RynthServerHub.SectionRemoteBank) || off.RenderSection(RynthServerHub.SectionRemoteGuardian),
"off ILT: none of the Remote tab's ILT parts draws (checked before any ImGui call)");
}
private static void FollowsSession()
{
var hub = NewHub("InfiniteLeaftide", "session");
long t1 = DateTime.UtcNow.AddMinutes(-10).Ticks;
FakeAiHub.SessionStartTicks = t1;
long now = Environment.TickCount64;
hub.Rates.Tick(now);
DateTime first = hub.Rates.SessionStartUtc;
System.Threading.Thread.Sleep(30);
hub.Rates.Tick(now + 100);
Check.Eq(hub.Rates.SessionStartUtc, first, "the same shared session: no restart");
FakeAiHub.SessionStartTicks = DateTime.UtcNow.Ticks; // RynthAi's Reset XP
hub.Rates.Tick(now + 200);
Check.True(hub.Rates.SessionStartUtc > first, "RynthAi's session restarted: the coins start over too");
}
private static void ImportsSwitches()
{
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Remoter");
Directory.CreateDirectory(legacy);
File.WriteAllText(Path.Combine(legacy, "Default.json"), "{}");
File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyHudsFile), "{ \"ShowMiniRemote\": true, \"MiniShowBank\": false }");
var state = new IltHubState();
IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Remoter");
Check.False(state.Remote.ShowBank, "Bank was hidden in RynthAi: hidden here");
Check.True(state.Remote.ShowGuardian, "Guardian wasn't in the file: the default (shown)");
}
}

View file

@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The Rings inscription chain's pure parts (Hub/IltRingChain.cs, SilentKelpie's RynthAi
// Crafting > Rings moved to RynthILT): ingredient names, the craft queue and the scroll pairing.
internal static class RingChainTests
{
public static void Register(Runner r)
{
r.Add("rings: ingredients match by name, with alternates and an exclude", Ingredients);
r.Add("rings: the queue runs every Step 1, then Step 2, then the glyphs, capped per recipe", Queue);
r.Add("rings: scrolls are known by their glyph and paired with targets the UB-IT way", Scrolls);
r.Add("rings: the recipe list holds the three steps and eight glyphs", RecipeList);
}
private static IltRingRecipe Recipe(string id) => IltRingChain.Recipes.Single(r => r.Id == id);
private static void Ingredients()
{
var step1 = Recipe("ring2_step1_quill_trophy");
Check.True(IltRingChain.Matches("Quill of Infliction", step1.Tool), "the quill");
Check.True(IltRingChain.Matches("infliction quill", step1.Tool), "an alternate name, any case");
Check.False(IltRingChain.Matches("Enlightened Quill of Infliction", step1.Tool), "the enlightened quill is Step 2's, not Step 1's");
Check.True(IltRingChain.Matches("Empyrean Trophy", step1.Target), "a trophy");
Check.False(IltRingChain.Matches("Trophy Scroll", step1.Target), "plain 'Trophy' isn't enough (scrolls carry the word)");
Check.False(IltRingChain.Matches(null, step1.Tool), "no name");
Check.False(IltRingChain.Matches("", step1.Tool), "empty name");
var step2 = Recipe("ring2_step2_ink");
Check.True(IltRingChain.Matches("Enlightened Quill of Infliction", step2.Tool), "Step 2 takes Step 1's quill");
Check.False(IltRingChain.Matches("Enlightened Infliction Quill of Partition", step2.Tool), "but not the partition quill");
var flame = Recipe("ring2_glyph_flame");
Check.True(IltRingChain.Matches("Enlightened Infliction Quill of Partition", flame.Tool), "Step 3 takes the partition quill");
Check.True(IltRingChain.Matches("Glyph of Flame", flame.Target), "the full glyph name");
Check.False(IltRingChain.Matches("Glyph of Frost", flame.Target), "another glyph is not");
}
private static void Queue()
{
var runs = new Dictionary<string, int>
{
["ring2_glyph_frost"] = 1,
["ring2_step2_ink"] = 2,
["ring2_step1_quill_trophy"] = 2,
["ring2_glyph_bludgeoning"] = 1,
};
List<IltRingRecipe> q = IltRingChain.Expand(id => runs.TryGetValue(id, out int n) ? n : 0);
Check.Eq(string.Join(",", q.Select(r => r.Id)),
"ring2_step1_quill_trophy,ring2_step1_quill_trophy,ring2_step2_ink,ring2_step2_ink,ring2_glyph_bludgeoning,ring2_glyph_frost",
"tier order, then the definition order within a tier");
Check.Eq(IltRingChain.Expand(_ => 0).Count, 0, "nothing queued");
Check.Eq(IltRingChain.Expand(id => id == "ring2_step2_ink" ? -5 : 0).Count, 0, "negative runs count as none");
Check.Eq(IltRingChain.Expand(id => id == "ring2_step2_ink" ? 500 : 0).Count, IltRingChain.MaxRuns, "capped at MaxRuns");
}
private static void Scrolls()
{
Check.True(IltRingChain.IsInscriptionScroll("Inscription of Halo of Frost"), "an inscription scroll");
Check.False(IltRingChain.IsInscriptionScroll("Scroll of Frost Bolt"), "a spell scroll is not");
Check.False(IltRingChain.IsInscriptionScroll(null), "no name");
Check.Eq(IltRingChain.GlyphOf("Inscription of Halo of Frost")?.Id, "ring2_glyph_frost", "known by its scroll name");
Check.Eq(IltRingChain.GlyphOf("Inscription of Cassius' Ring of Fire")?.Id, "ring2_glyph_flame", "apostrophes too");
Check.True(IltRingChain.GlyphOf("Inscription of Something New") == null, "an unknown scroll has no glyph");
var scrolls = new[]
{
(Id: 50, Name: "Inscription of Something New"),
(Id: 40, Name: "Inscription of Halo of Frost"),
(Id: 30, Name: "Inscription of Tectonic Rifts"),
(Id: 20, Name: "Inscription of Halo of Frost"),
};
var pairs = IltRingChain.PairScrolls(scrolls, new[] { 900, 700, 800, 700 });
// Scrolls by glyph id (bludgeoning < frost; unknown last), then by id; targets by id, once each.
Check.Eq(string.Join(" ", pairs.Select(p => p.Scroll + ">" + p.Target)), "30>700 20>800 40>900", "pairing order");
Check.Eq(IltRingChain.PairScrolls(scrolls.Take(1), new[] { 1, 2, 3 }).Count, 1, "one scroll per target, no more pairs than scrolls");
Check.Eq(IltRingChain.PairScrolls(scrolls, Array.Empty<int>()).Count, 0, "no targets, no pairs");
}
private static void RecipeList()
{
Check.Eq(IltRingChain.Recipes.Length, 10, "Step 1, Step 2 and eight glyphs");
Check.Eq(IltRingChain.Recipes.Count(r => r.Tier == 3), 8, "eight glyphs");
Check.True(IltRingChain.Recipes.Select(r => r.Id).Distinct().Count() == IltRingChain.Recipes.Length, "ids are unique");
foreach (var r in IltRingChain.Recipes.Where(r => r.Tier == 3))
Check.True(r.ScrollMarkers.Length > 0, r.Id + " knows its scroll's name");
}
}

View file

@ -0,0 +1,134 @@
using System;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The Empyrean Handler's lethal ring (Hub/IltRingEvade.cs), RynthAi's CombatManager's until 2026-10-20
// (Silentkelpie's PR 12). The line "The handler briefly channels infused Empyrean hatred to release a
// lethal ring." on an ILT world, with a Handler near, makes RynthILT ask RynthAi to back away from it
// (RynthAi.Hub BackAwayFrom, 12 yards, a 750 ms jump). The setting (on by default) is RynthILT's now,
// copied once from the RynthAi profile.
internal static class RingEvadeTests
{
private const uint Player = 0x50000B01;
private const uint Handler = 0x80000B02;
private const uint Lb = 0xA9B40000;
private const string RingLine = "The handler briefly channels infused Empyrean hatred to release a lethal ring.";
public static void Register(Runner r)
{
r.Add("ring evade (RynthILT): the Handler's line, and not a player's copy of it", ChannelLine);
r.Add("ring evade (RynthILT): on ILT with a Handler near, RynthAi is asked to back away (once per cooldown)", AsksRynthAi);
r.Add("ring evade (RynthILT): not with the setting off, no Handler near, off ILT, or without RynthAi", NotThese);
r.Add("migration: the RynthAi profile's Handler ring evade comes over once (on by default)", ImportsSetting);
}
private static IltHubController NewHub(string world, string folder, bool handler = true, bool withAi = true, string handlerName = "Empyrean Handler")
{
FakeHost.Reset();
FakeAiHub.Reset();
FakeHost.WorldName = world;
FakeHost.ContentsCalls = true;
FakeHost.LiveObjectsCalls = true;
FakeHost.Names[Player] = "Evader";
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
if (handler)
{
FakeHost.Names[Handler] = handlerName;
FakeHost.ItemTypes[Handler] = 0x10;
FakeHost.Positions[Handler] = (Lb | 0x1C, 96f, 101f, 0f);
}
var host = FakeHost.Create(Player);
var ai = new RynthAiClient(host);
if (withAi) ai.UseTableForTests(FakeAiHub.Table);
string dir = Path.Combine(Program.TempRoot, "ring-" + folder);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
var hub = new IltHubController(host, dir, new IltSettings(), ai);
hub.OnLoginComplete("Evader", forceFromMigration: false);
return hub;
}
private static void ChannelLine()
{
Check.True(IltRingEvade.IsChannelLine(RingLine, ChatSource.Emote), "the Handler's emote");
Check.True(IltRingEvade.IsChannelLine("handler briefly channels infused Empyrean hatred to release a lethal ring.", 0x00),
"mid-line on a system line (a client that strips 'The ')");
Check.False(IltRingEvade.IsChannelLine("Someone says, \"" + RingLine + "\"", ChatSource.Speech), "a player saying it");
Check.False(IltRingEvade.IsChannelLine("Bob tells you, \"" + RingLine + "\"", 0x00), "a tell repeating it");
Check.False(IltRingEvade.IsChannelLine("The handler waves.", ChatSource.Emote), "another Handler emote");
}
private static void AsksRynthAi()
{
var hub = NewHub("InfiniteLeaftide", "asks");
hub.OnChat(RingLine, ChatSource.Emote);
Check.Eq(FakeAiHub.BackAways.Count, 1, "one back-away request");
var (id, radius, hold) = FakeAiHub.BackAways[0];
Check.Eq(id, Handler, "away from the Handler");
Check.Eq(radius, IltRingEvade.DangerYards, "12 yards (RynthAi widens it to Ring Range)");
Check.Eq(hold, IltRingEvade.JumpHoldMs, "a 750 ms jump");
Check.True(hub.RingEvade.LastOutcome.Contains("backs away"), "logged");
hub.OnChat(RingLine, ChatSource.Emote);
Check.Eq(FakeAiHub.BackAways.Count, 1, "a second line inside the cooldown asks nothing");
var outside = NewHub("InfiniteLeaftide", "outside");
FakeAiHub.BackAwayResult = RynthAiHub.BackAwayOutside;
outside.OnChat(RingLine, ChatSource.Emote);
Check.Eq(FakeAiHub.BackAways.Count, 1, "RynthAi decides the radius");
Check.True(outside.RingEvade.LastOutcome.Contains("outside"), "and its answer is logged");
var notFighting = NewHub("InfiniteLeaftide", "notnow");
FakeAiHub.BackAwayResult = RynthAiHub.BackAwayNotNow;
notFighting.OnChat(RingLine, ChatSource.Emote);
Check.True(notFighting.RingEvade.LastOutcome.Contains("isn't fighting"), "RynthAi not fighting: it says so");
}
private static void NotThese()
{
var off = NewHub("InfiniteLeaftide", "setting-off");
off.State.Combat.HandlerRingEvade = false;
off.OnChat(RingLine, ChatSource.Emote);
Check.Eq(FakeAiHub.BackAways.Count, 0, "setting off: nothing asked");
var none = NewHub("InfiniteLeaftide", "none", handlerName: "Drudge Skulker");
none.OnChat(RingLine, ChatSource.Emote);
Check.Eq(FakeAiHub.BackAways.Count, 0, "no Empyrean Handler near: nothing asked");
var said = NewHub("InfiniteLeaftide", "said");
said.OnChat("Someone says, \"" + RingLine + "\"", ChatSource.Speech);
Check.Eq(FakeAiHub.BackAways.Count, 0, "a player's copy: nothing asked");
var retail = NewHub("Aeshnidae", "retail");
retail.OnChat(RingLine, ChatSource.Emote);
Check.Eq(FakeAiHub.BackAways.Count, 0, "off ILT: nothing asked");
var noAi = NewHub("InfiniteLeaftide", "noai", withAi: false);
noAi.OnChat(RingLine, ChatSource.Emote);
Check.True(noAi.RingEvade.LastOutcome.Contains("RynthAi"), "without RynthAi: said in the log, no crash");
}
private static void ImportsSetting()
{
Check.True(new IltHubState().Combat.HandlerRingEvade, "on by default");
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Evader");
Directory.CreateDirectory(legacy);
File.WriteAllText(Path.Combine(legacy, "active_profile.txt"), "Farm");
File.WriteAllText(Path.Combine(legacy, "Farm.json"), "{ \"HandlerRingEvade\": false, \"MonsterRange\": 30 }");
var state = new IltHubState();
IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Evader");
Check.False(state.Combat.HandlerRingEvade, "the active profile had it off: off here too");
string legacy2 = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Oldie");
Directory.CreateDirectory(legacy2);
File.WriteAllText(Path.Combine(legacy2, "Default.json"), "{ \"MonsterRange\": 30 }");
var old = new IltHubState();
IltMigration.ImportRynthAiSettings(old, "InfiniteLeaftide", "Oldie");
Check.True(old.Combat.HandlerRingEvade, "a profile from before the setting: on (the default)");
}
}

View file

@ -0,0 +1,71 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Tests for the RynthILT plugin: the ACECustom bounty tracker (Bounty/, ported from SilentKelpie's
rynth/RynthSuite PR #11 with his BountyTests) and the ILT Hub moved out of RynthAi 2026-10-13
(the attribute raiser and aug costs, bank commands and the sigil chain, which ran in
RynthCore.RynthAiHostTests before, plus the move itself: data migration, the RynthILT.Hub
interface table, which "/ra" verbs RynthILT takes, the host-backed object view).
Like RynthCore.RynthAiHostTests this references the plugin project itself, so it is a
net10.0-windows x86 exe and needs the x86 .NET runtime (C:\Program Files (x86)\dotnet). The
plugin grants InternalsVisibleTo to this assembly name. The fake engine host is the RynthAi
host tests' FakeHost (linked; RYNTHILT_TESTS leaves out its RynthAi-only helpers). File tests
use a scratch folder next to the exe, never %APPDATA%\RynthCore or C:\Games.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail; an argument filters by test name)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>RynthILT.Tests</RootNamespace>
<AssemblyName>RynthILT.Tests</AssemblyName>
<Platforms>x86</Platforms>
<DefineConstants>$(DefineConstants);RYNTHILT_TESTS</DefineConstants>
<NoWarn>$(NoWarn);CS1591</NoWarn>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Plugins\RynthCore.Plugin.RynthILT\RynthCore.Plugin.RynthILT.csproj" />
</ItemGroup>
<ItemGroup>
<!-- The RynthAi test tools' check/runner harness and fake engine host (no plugin code in them). -->
<Compile Include="$(RynthSuiteRoot)Tools\RynthCore.RynthAiTests\Harness\Check.cs" Link="Harness\Check.cs" />
<Compile Include="$(RynthSuiteRoot)Tools\RynthCore.RynthAiTests\Harness\Runner.cs" Link="Harness\Runner.cs" />
<Compile Include="$(RynthSuiteRoot)Tools\RynthCore.RynthAiHostTests\Fakes\FakeHost.cs" Link="Fakes\FakeHost.cs" />
<!-- The shared reader RynthAi's Crafting tab uses on RynthILT's RynthServer.Profile JSON (ProfileTests),
Plugins\Shared\EngineServerState.cs, comes with the plugin now (it reads RynthCore's server list). -->
</ItemGroup>
<!-- The engine's Bounties snapshot reader (self-contained DTOs), so BountyTests checks the plugin's
JSON against the engine's own reader. Optional, so this builds before the engine side is
merged: without the file the round-trip check is compiled out (ENGINE_BOUNTIES). -->
<PropertyGroup Condition="Exists('..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\BountiesSnapshotJson.cs')">
<DefineConstants>$(DefineConstants);ENGINE_BOUNTIES</DefineConstants>
</PropertyGroup>
<ItemGroup Condition="Exists('..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\BountiesSnapshotJson.cs')">
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\BountiesSnapshotJson.cs" Link="Engine\BountiesSnapshotJson.cs" />
</ItemGroup>
<!-- The engine's Mini Remote sections manifest parser and catalog (pure; the RynthAi host tests link the same
files), so the sections test checks RynthILT's RynthPluginGetSectionsJson against the engine's reader. -->
<ItemGroup>
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Sections\ServerForce.cs" Link="Engine\ServerForce.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Sections\SectionManifest.cs" Link="Engine\SectionManifest.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Sections\SectionCatalog.cs" Link="Engine\SectionCatalog.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Compatibility\IltDetect.cs" Link="Engine\IltDetect.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Compatibility\AelrynthWire.cs" Link="Engine\AelrynthWire.cs" />
</ItemGroup>
<!-- The engine supplies cimgui; never copy ImGui.NET's own next to the test exe either. -->
<Target Name="RemoveBundledImGuiNative" AfterTargets="Build">
<Delete Files="$(OutputPath)cimgui.dll" Condition="Exists('$(OutputPath)cimgui.dll')" />
</Target>
</Project>

View file

@ -0,0 +1,83 @@
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// Enlightenment 301-325 sigil craft chain (2026-10-07). Each target level T costs T - 5 sigils and
// T x 2B luminance (ACECustom tier 5). Sigil = Lifeblood Elixir + Ascension Coin; Ascension Coin =
// E-coin + Ancient Yalani Trinket; Elixir = Lifebloom Resin + Necrolytic Extract; Resin = Life
// Splitter + Plant. Stock is used from the top of the chain down.
internal static class SigilChainTests
{
public static void Register(Runner r)
{
r.Add("sigil chain: 301-325 tier rates and sigil counts", TierRates);
r.Add("sigil chain: shortfall uses stock top-down", ShortfallTopDown);
r.Add("sigil chain: fulfillable count and shared e-coin pool", FulfillableAndCoins);
r.Add("sigil chain: item names (plural stacks, Plant exact)", Names);
}
private static void TierRates()
{
var t301 = IltProgression.EnlStepCost(301);
Check.Eq(t301.Item, "Enlightenment Sigils", "301 takes sigils");
Check.Eq(t301.Count, 296, "301 takes T - 5 sigils");
Check.Eq(t301.Lum, 301 * 2_000_000_000m, "301 costs T x 2B luminance (no step multiplier yet)");
Check.Eq(IltProgression.EnlStepCost(325).Lum, 325 * 2_000_000_000m, "325 still has no step multiplier");
Check.Eq(IltProgression.EnlStepCost(326).Item, "Enlightenment Crests", "326 moves to crests");
Check.Eq(IltSigilChain.SigilsForRange(300, 302), 296L + 297L, "range 300 -> 302 sums both levels");
Check.Eq(IltSigilChain.SigilsForRange(324, 330), 320L, "range clamps at 325");
Check.Eq(IltSigilChain.SigilsForRange(200, 300), 0L, "no sigils below 301");
}
private static void ShortfallTopDown()
{
var empty = IltSigilChain.Shortfall(10, new IltSigilStock());
Check.Eq(empty.CoinsShort, 10L, "empty pack: one e-coin per sigil");
Check.Eq(empty.PlantsShort, 10L, "empty pack: one plant per sigil");
Check.True(!empty.Covered, "empty pack is not covered");
var stock = new IltSigilStock
{
Sigils = 2, AscensionCoins = 3, LifebloodElixirs = 1, LifebloomResins = 4,
EnlightenedCoins = 100, YalaniTrinkets = 1, NecrolyticExtracts = 2, LifeSplitters = 0, Plants = 5,
};
var s = IltSigilChain.Shortfall(10, stock);
Check.Eq(s.SigilsToCraft, 8L, "2 finished sigils used first");
Check.Eq(s.AscensionToCraft, 5L, "3 Ascension Coins on hand");
Check.Eq(s.ElixirsToCraft, 7L, "1 Elixir on hand");
Check.Eq(s.CoinsShort, 0L, "100 e-coins cover 5 crafts");
Check.Eq(s.TrinketsShort, 4L, "1 trinket on hand");
Check.Eq(s.ExtractsShort, 5L, "2 extracts on hand");
Check.Eq(s.ResinsToCraft, 3L, "4 resins on hand");
Check.Eq(s.SplittersShort, 3L, "no splitters");
Check.Eq(s.PlantsShort, 0L, "5 plants cover 3 resins");
Check.True(IltSigilChain.Shortfall(5, new IltSigilStock { Sigils = 9 }).Covered, "finished sigils cover the demand");
}
private static void FulfillableAndCoins()
{
var stock = new IltSigilStock
{
Sigils = 1, AscensionCoins = 1, EnlightenedCoins = 10, YalaniTrinkets = 2,
LifebloomResins = 1, LifeSplitters = 10, Plants = 10, NecrolyticExtracts = 4,
};
Check.Eq(IltSigilChain.Fulfillable(stock), 4L, "1 finished + min(3 coins, 4 elixirs)");
IltSigilChain.EcoinDemand(50, 30, 2, 20, out long fromCoins, out long still, out long need);
Check.Eq(fromCoins, 1L, "20 coins left after Ascension crafts make 1 token");
Check.Eq(still, 1L, "one token still short");
Check.Eq(need, 20L, "one more token's worth of coins");
IltSigilChain.EcoinDemand(10, 25, 0, 20, out _, out _, out need);
Check.Eq(need, 15L, "Ascension crafts alone exceed the pool");
}
private static void Names()
{
Check.True(IltSigilChain.NameIs("Ascension Coins", IltSigilChain.AscensionCoin), "plural stack name");
Check.True(IltSigilChain.NameIs(" plant ", IltSigilChain.Plant), "case and spaces ignored");
Check.True(!IltSigilChain.NameIs("Plant Fiber", IltSigilChain.Plant), "Plant must be the whole name");
Check.True(!IltSigilChain.NameIs("Lifebloom Resin", IltSigilChain.LifebloodElixir), "Lifebloom is not Lifeblood");
}
}

View file

@ -0,0 +1,258 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthILT;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.RynthOracle.Data;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// Infinite Leaftide's Dynamic Stamps (Hub/IltDynamicStampList.cs, Hub/IltDynamicStamps.cs): SilentKelpie's
// (RynthSuite PR 12), rows of RynthOracle's Quests list until 2026-10-21 and RynthILT's own page since.
// The list and its matching rules (the tests that came with it from RynthOracle.Tests), the page's
// filters, where its flags come from, and what its buttons send (RynthNav, RynthAi's /ub give).
internal static class StampTests
{
public static void Register(Runner r)
{
r.Add("stamps: the shipped list (243 stamps in 17 areas) and how a stamp is matched", ShippedList);
r.Add("stamps: the loader skips bad and repeated rows", Loader);
r.Add("stamps: the page's filters (area, missing / had, search)", Filters);
r.Add("stamps: flags come from any /myquests reply; only RynthILT's own reply is hidden", Flags);
r.Add("stamps: off ILT the page is dormant (no flags read)", Dormant);
r.Add("stamps: Go / Route / Arrow ask RynthNav; Chat prints the stamp", Nav);
r.Add("stamps: Give Parchment needs RynthAi, sends /ub give 1, then reads the flags again", Give);
r.Add("stamps: a Parchment in the packs is found while the page is on screen", Parchment);
}
private const uint Player = 0x50000D31;
private static readonly long Yesterday = DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds();
private static IltHubController NewHub(string world, string folder, bool withAi = false)
{
FakeHost.Reset();
FakeAiHub.Reset();
FakeHost.WorldName = world;
FakeHost.PluginCommandCalls = true;
FakeHost.ContentsCalls = true;
FakeHost.Containers[0x7000A001] = Player;
FakeHost.Names[0x7000A001] = "Pyreal";
var host = FakeHost.Create(Player);
var ai = new RynthAiClient(host);
if (withAi) ai.UseTableForTests(FakeAiHub.Table);
string dir = Path.Combine(Program.TempRoot, "stamps-" + folder);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
var hub = new IltHubController(host, dir, new IltSettings(), ai);
hub.OnLoginComplete("Stamper", forceFromMigration: false);
return hub;
}
private static void ShippedList()
{
var all = DynamicStampList.All;
Check.Eq(all.Count, 243, "243 stamps from the ExtraDyn sheet");
Check.True(DynamicStampList.Areas.Count == 17 && DynamicStampList.Areas[0] == "Facility Hub" && DynamicStampList.Areas[^1] == "Candeth Keep",
"areas: " + string.Join(",", DynamicStampList.Areas));
Check.True(all.All(s => s.Stamp.StartsWith("dynamic_") && s.Stamp == s.Stamp.ToLowerInvariant()), "every stamp is a lower-case dynamic_ flag");
Check.Eq(all.Select(s => s.Stamp).Distinct().Count(), all.Count, "no stamp listed twice");
Check.True(all.All(s => s.Label.Length > 0), "every row names an NPC or a place");
DynamicStamp felscuda = all.First(s => s.Npc == "Felscuda");
Check.True(felscuda.Stamp == "dynamic_1_&9jiytb!" && felscuda.Place == "Folthid Cellar" && felscuda.Reward == "Healing Rabbit Pie"
&& felscuda.Note == "8.8S, 53.1E", $"Felscuda row: {felscuda.Place} / {felscuda.Reward} / {felscuda.Note}");
// /myquests keys flags as \S+ lower case, so the stamps' ! & # ^ $ survive.
var f = new QuestFlagStore();
long t = 900_000;
f.OnChatLine($"Dynamic_1_&9jiyTB! - 1 solves ({Yesterday})\"Dynamic\" 1 0", t);
f.OnChatLine($"Dynamic_1_ANND! - 1 solves ({Yesterday})\"Dynamic\" 1 0", t + 1); // the sheet lost the closing !
f.OnChatLine($"Dynamic_1_ZZZnewNPC! - 1 solves ({Yesterday})\"Dynamic\" 1 0", t + 2); // not on the sheet
f.OnChatLine($"rtwcompleted_1013 - 1 solves ({Yesterday})\"RTW\" -1 72000", t + 3);
f.Tick(t + 5_000);
Check.True(felscuda.Have(f), "Felscuda's stamp read from /myquests");
DynamicStamp annd = all.First(s => s.Stamp == "dynamic_1_annd");
Check.True(annd.Have(f) && annd.MatchedFlag(f) == "dynamic_1_annd!", "a stamp the sheet lost its ! on still matches");
Check.False(all.First(s => s.Npc == "Raxanza Folthid").Have(f), "an NPC not done is missing");
List<string> extra = DynamicStampList.Unlisted(f);
Check.True(extra.Count == 1 && extra[0] == "dynamic_1_zzznewnpc!", "unlisted: only the stamp the sheet doesn't have: " + string.Join(",", extra));
DynamicStamp shortStamp = all.First(s => s.Stamp == "dynamic_1_s");
var sf = new QuestFlagStore();
sf.OnChatLine($"Dynamic_1_SomethingElse! - 1 solves ({Yesterday})\"Dynamic\" 1 0", t);
sf.Tick(t + 5_000);
Check.False(shortStamp.Have(sf), "a cut-short stem under 14 characters isn't matched by prefix");
// RynthNav targets, best first (RynthNav takes the first on its map).
Check.Eq(string.Join(" | ", felscuda.NavCandidates()), "8.8S, 53.1E | Folthid Cellar | Felscuda | Facility Hub", "Felscuda nav");
var gerent = new DynamicStamp { Area = "Graveyard", Place = "Gerent's Compound at 87.2S, 17.5W", Npc = "Gerent" };
Check.Eq(string.Join(" | ", gerent.NavCandidates()), "87.2S, 17.5W | Gerent's Compound | Gerent | Graveyard", "coordinates inside the place, 'at' dropped");
var lost = new DynamicStamp { Area = "Odd Stamps", Place = "Lost Wish Cottages (Arwic) 42.6n 62.4e", Npc = "Bob" };
Check.Eq(string.Join(" | ", lost.NavCandidates()), "42.6N, 62.4E | Lost Wish Cottages (Arwic) | Lost Wish Cottages | Arwic",
"lower-case n/e, a bracketed town, no grouping area, a 3-letter NPC left out");
var mhoire = new DynamicStamp { Area = "Looking Around", Place = "Mhoire Castle - Great Hall" };
Check.Eq(string.Join(" | ", mhoire.NavCandidates()), "Mhoire Castle - Great Hall | Mhoire Castle | Great Hall", "a place's parts");
Check.True(all.Count(s => s.NavCandidates().Count > 0) >= 200, "most stamps have somewhere to go: " + all.Count(s => s.NavCandidates().Count > 0));
}
private static void Loader()
{
var stamps = DynamicStampList.Parse(new StringReader(
"Area,Place,Npc,Reward,Stamp,Note\n"
+ "\"A\",\"P\",\"Npc1\",\"R\",\"Dynamic_1_Abc!\",\"8.8S, 53.1E\"\n"
+ "\"A\",\"P\",\"Dup\",\"R\",\"dynamic_1_abc!\",\"\"\n" // the same stamp again: skipped
+ "\"A\",\"P\",\"NotDyn\",\"R\",\"something_else\",\"\"\n" // not a dynamic_ flag: skipped
+ "\"A\",\"P\",\"Short\"\n" // no stamp column: skipped
+ "\n"
+ "\"B\",\"\",\"\",\"\",\"Dynamic_2_x\",\"\"\n"));
Check.True(stamps.Count == 2 && stamps[0].Stamp == "dynamic_1_abc!" && stamps[1].Stamp == "dynamic_2_x",
"bad and repeated rows skipped, the rest kept: " + string.Join(",", stamps.Select(s => s.Stamp)));
Check.True(stamps[0].Npc == "Npc1" && stamps[0].Note == "8.8S, 53.1E" && stamps[1].Label == "", "fields read, a missing NPC and place leave an empty label");
Check.Eq(DynamicStampList.Parse(new StringReader("")).Count, 0, "an empty file is an empty list");
}
private static void Filters()
{
var f = new QuestFlagStore();
f.OnChatLine($"Dynamic_1_&9jiyTB! - 1 solves ({Yesterday})\"Dynamic\" 1 0", 0);
f.Tick(5_000);
List<DynamicStampText.Row> rows = DynamicStampText.Rows(DynamicStampList.All, f);
Check.Eq(rows.Count, 243, "a row per listed stamp");
Check.Eq(rows.Count(r => r.Have), 1, "one had");
Check.Eq(DynamicStampText.Filter(rows, "", null, DynamicStampText.Show.All).Count, 243, "no filter: everything");
Check.Eq(DynamicStampText.Filter(rows, "", null, DynamicStampText.Show.Have).Single().Stamp.Npc, "Felscuda", "Had: Felscuda's");
Check.Eq(DynamicStampText.Filter(rows, "", null, DynamicStampText.Show.Missing).Count, 242, "Missing: the rest");
string area = DynamicStampList.Areas[0];
int inArea = DynamicStampList.All.Count(s => s.Area == area);
Check.Eq(DynamicStampText.Filter(rows, null, area, DynamicStampText.Show.All).Count, inArea, "the area picker narrows to " + area);
Check.Eq(DynamicStampText.Filter(rows, "felscuda rabbit", null, DynamicStampText.Show.All).Single().Stamp.Npc, "Felscuda",
"every search word, in the NPC and the reward, any case");
Check.Eq(DynamicStampText.Filter(rows, "felscuda nothinglikethis", null, DynamicStampText.Show.All).Count, 0, "a word nowhere: nothing");
}
private static void Flags()
{
IltHubController hub = NewHub("InfiniteLeaftide", "flags");
IltDynamicStamps stamps = hub.DynamicStamps;
long now = IltHubContext.NowMs;
// A reply another plugin (or the player) asked for: read, and shown.
bool eaten = hub.OnChat($"Dynamic_1_&9jiyTB! - 1 solves ({Yesterday})\"Dynamic\" 1 0");
Check.False(eaten, "a reply RynthILT didn't ask for shows in chat");
stamps.Tick(now + 5_000);
Check.True(stamps.Flags.TryGet("dynamic_1_&9jiytb!", out _), "the flag is read from it");
// Its own request: the reply is hidden.
hub.Tick();
stamps.RequestFlags();
Check.True(FakeHost.ChatCommands.Contains("/myquests"), "Read quest flags sends /myquests");
stamps.NoteTypedMyQuests(); // the engine's dispatcher hands it back through the chat bar
Check.True(stamps.Flags.AwaitingOurs, "waiting for its own reply");
Check.True(hub.OnChat($"Dynamic_1_ANND! - 1 solves ({Yesterday})\"Dynamic\" 1 0"), "its own reply is hidden");
stamps.Tick(IltHubContext.NowMs + 5_000);
Check.False(stamps.Flags.AwaitingOurs, "done waiting once the reply went quiet");
Check.True(stamps.Flags.TryGet("dynamic_1_annd!", out _), "and read");
// The page's snapshot follows the flags while it is on screen.
stamps.MarkWatched();
stamps.Tick(IltHubContext.NowMs);
IltDynamicStamps.Snapshot s = stamps.Current;
Check.True(s.Built && s.Rows.Count == 243, "the snapshot lists every stamp");
Check.Eq(s.Have, 1, "one listed stamp had (the other read reply replaced the first)");
Check.True(s.LastReadUtc != DateTime.MinValue, "when the flags were read");
hub.OnLogout();
Check.False(stamps.Current.Built || stamps.Flags.Flags.Count > 0, "logout forgets the flags and the snapshot");
}
private static void Dormant()
{
IltHubController hub = NewHub("Aeshnidae", "dormant");
hub.OnChat($"Dynamic_1_&9jiyTB! - 1 solves ({Yesterday})\"Dynamic\" 1 0");
hub.DynamicStamps.Tick(IltHubContext.NowMs + 5_000);
Check.Eq(hub.DynamicStamps.Flags.Flags.Count, 0, "off ILT no chat reaches the page");
Check.False(hub.Options.IsIltLikeWorld, "(not an ILT world)");
}
private static void Nav()
{
IltHubController hub = NewHub("InfiniteLeaftide", "nav");
IltDynamicStamps stamps = hub.DynamicStamps;
DynamicStamp felscuda = DynamicStampList.All.First(s => s.Npc == "Felscuda");
Check.Eq(DynamicStampText.NavLine("route", felscuda), "route 8.8S, 53.1E || Folthid Cellar || Felscuda || Facility Hub", "the RynthNav line");
Check.Eq(DynamicStampText.NavLine("go", new DynamicStamp { Stamp = "dynamic_x" }), "", "nowhere to go: no line");
stamps.Nav("route", felscuda);
stamps.Nav("go", felscuda);
stamps.Nav("arrow", felscuda);
Check.Eq(FakeHost.PluginCommands.Count, 3, "three RynthNav commands");
Check.True(FakeHost.PluginCommands.All(c => c.Plugin == "RynthNav" && c.Action == "rnav"), "to RynthNav's rnav");
Check.True(FakeHost.PluginCommands[1].Value.StartsWith("go 8.8S, 53.1E || "), "go with every candidate");
Check.True(stamps.Status.Contains("arrow"), "the status says what happened: " + stamps.Status);
FakeHost.PluginCommandDelivered = false;
stamps.Nav("go", felscuda);
Check.True(stamps.Status.Contains("RynthNav isn't loaded"), "without RynthNav: said so");
FakeHost.Chat.Clear();
stamps.Print(felscuda);
Check.True(FakeHost.Chat.Count >= 2 && FakeHost.Chat[0].Contains("Felscuda") && FakeHost.Chat[0].Contains("missing")
&& FakeHost.Chat[1].Contains("Folthid Cellar") && FakeHost.Chat[1].Contains("Healing Rabbit Pie"),
"Chat prints the stamp, its status, place and reward: " + string.Join(" | ", FakeHost.Chat));
}
private static void Give()
{
// Without RynthAi: the reason, nothing sent.
Check.True(DynamicStampText.GiveUnavailableReason(false, false)!.Contains("Needs RynthAi"), "no RynthAi: says it needs it");
Check.True(DynamicStampText.GiveUnavailableReason(true, true)!.Contains("Unrecognized /ub command"), "rejected: says why");
Check.Null(DynamicStampText.GiveUnavailableReason(true, false), "RynthAi there: Give works");
Check.Eq(DynamicStampText.GiveCommand("Parchment\nof /quit", "Felscuda"), "/ub give 1 Parchmentof /quit to Felscuda",
"control characters are stripped from the command");
Check.True(DynamicStampText.IsGiveRejection("[RynthAi] Unrecognized /ub command.") && !DynamicStampText.IsGiveRejection("[RynthAi] ok"),
"RynthAi's rejection line");
DynamicStamp felscuda = DynamicStampList.All.First(s => s.Npc == "Felscuda");
IltHubController none = NewHub("InfiniteLeaftide", "give-none");
none.DynamicStamps.Give(felscuda, "Parchment of Learning");
Check.False(FakeHost.ChatCommands.Any(c => c.StartsWith("/ub give")), "without RynthAi nothing is sent");
IltHubController hub = NewHub("InfiniteLeaftide", "give", withAi: true);
IltDynamicStamps stamps = hub.DynamicStamps;
stamps.Give(felscuda, "Parchment of Learning");
Check.True(FakeHost.ChatCommands.Contains("/ub give 1 Parchment of Learning to Felscuda"), "Give sends /ub give 1: " + string.Join("|", FakeHost.ChatCommands));
Check.True(stamps.Status.Contains("Giving Parchment of Learning to Felscuda"), "and says so");
// The stamp is a quest flag: /myquests is read again once the NPC had time to answer.
stamps.Tick(IltHubContext.NowMs + 1_000);
Check.False(FakeHost.ChatCommands.Contains("/myquests"), "not straight away");
stamps.Tick(IltHubContext.NowMs + IltDynamicStamps.HandInRefreshMs + 1_000);
Check.True(FakeHost.ChatCommands.Contains("/myquests"), "a /myquests after the hand-in");
// The loaded RynthAi answers "Unrecognized /ub command": Give turns itself off.
hub.OnChat("[RynthAi] Unrecognized /ub command.");
stamps.Rebuild();
Check.True(stamps.Current.GiveReason != null && stamps.Current.GiveReason.Contains("Unrecognized"), "rejected right after the send: Give is off");
int sends = FakeHost.ChatCommands.Count(c => c.StartsWith("/ub give"));
stamps.Give(felscuda, "Parchment of Learning");
Check.Eq(FakeHost.ChatCommands.Count(c => c.StartsWith("/ub give")), sends, "no further /ub give goes out");
}
private static void Parchment()
{
IltHubController hub = NewHub("InfiniteLeaftide", "parchment", withAi: true);
IltDynamicStamps stamps = hub.DynamicStamps;
stamps.Tick(IltHubContext.NowMs);
Check.False(stamps.Current.Built, "nothing is built while the page isn't on screen");
stamps.MarkWatched();
stamps.Tick(IltHubContext.NowMs);
Check.True(stamps.Current.Built && stamps.Current.Parchment == null, "on screen: built; no Parchment carried");
Check.Null(stamps.Current.GiveReason, "RynthAi is there: Give would work");
FakeHost.Containers[0x7000A002] = Player;
FakeHost.Names[0x7000A002] = "Parchment of Learning";
stamps.Tick(IltHubContext.NowMs + 2_000);
Check.Eq(stamps.Current.Parchment, "Parchment of Learning", "a Parchment in the main pack is found");
}
}

View file

@ -0,0 +1,113 @@
using System;
using System.IO;
using System.Linq;
using RynthCore.Loot.T11;
using RynthCore.Plugin.RynthILT;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// T11 (ACECustom tier 11+ gear) moved from RynthAi on 2026-10-20 (Hub/IltT11.cs): RynthILT reads the
// "/aug" reply's wield counters, applies its item-aug override and reports them to RynthAi's loot rules
// (RynthAi.Hub SetPlayerCounter); "/ilt t11" (and RynthAi's "/ra t11", passed on) shows and sets them.
internal static class T11Tests
{
private const uint Player = 0x50000E01;
public static void Register(Runner r)
{
r.Add("t11 (RynthILT): the /aug reply's counters go to RynthAi, with the item-aug override applied", ReportsCounters);
r.Add("t11 (RynthILT): /ilt t11 and /ra t11 are RynthILT's verbs; augs sets the override", Commands);
r.Add("t11 (RynthILT): off ILT nothing is read or reported", DormantOffIlt);
r.Add("migration: the RynthAi profile's T11 item-aug override comes over once", ImportsOverride);
}
private static IltHubController NewHub(string world, string folder)
{
FakeHost.Reset();
FakeAiHub.Reset();
FakeHost.WorldName = world;
var host = FakeHost.Create(Player);
var ai = new RynthAiClient(host);
ai.UseTableForTests(FakeAiHub.Table);
string dir = Path.Combine(Program.TempRoot, "t11-" + folder);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
var hub = new IltHubController(host, dir, new IltSettings(), ai);
hub.OnLoginComplete("Augger", forceFromMigration: false);
return hub;
}
private static void ReportsCounters()
{
var hub = NewHub("InfiniteLeaftide", "report");
hub.T11.Tick(Environment.TickCount64);
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], -1L, "unknown before /aug (reported as -1)");
Check.Eq(hub.T11.LastReported, T11Catalog.CounterNames.Length, "every counter is reported");
hub.OnChat("Advanced Augmentation Levels:");
hub.OnChat("Item:2,400");
hub.OnChat("Triune Weave: 5 (adds 5 to your aug counts)");
hub.T11.Tick(Environment.TickCount64);
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2400L, "Item: 2,400 reported");
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.TriuneWeave], 5L, "Triune Weave: 5 reported");
hub.State.T11.ItemAugsOverride = 2500;
hub.T11.Tick(Environment.TickCount64);
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2500L, "the override replaces /aug's item count");
hub.State.T11.ItemAugsOverride = -1;
hub.T11.Tick(Environment.TickCount64);
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2400L, "auto again: /aug's count");
hub.OnLogout();
hub.T11.Tick(Environment.TickCount64);
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], -1L, "after logout: unknown again");
}
private static void Commands()
{
Check.True(RynthILTPlugin.IsIltVerb(new[] { "t11" }), "/ra t11 is RynthILT's (RynthAi passes it on)");
Check.True(RynthILTPlugin.IsIltVerb(new[] { "t11", "augs", "5" }), "with its arguments");
Check.True(RynthILTPlugin.IsIltVerb(new[] { "ub", "qblist" }) && RynthILTPlugin.IsIltVerb(new[] { "ub", "augs" }),
"ub-IT's /ub qblist and /ub augs (ACECustom commands RynthAi passes on) are RynthILT's");
Check.False(RynthILTPlugin.IsIltVerb(new[] { "ub", "wear" }) || RynthILTPlugin.IsIltVerb(new[] { "ub" }), "no other /ub verb");
var hub = NewHub("InfiniteLeaftide", "cmd");
FakeHost.Chat.Clear();
hub.T11.HandleCommand(new[] { "augs", "3,000" });
Check.Eq(hub.State.T11.ItemAugsOverride, 3000, "augs 3,000 fixes the override");
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 3000L, "and reports it at once");
hub.T11.HandleCommand(new[] { "augs", "auto" });
Check.Eq(hub.State.T11.ItemAugsOverride, -1, "augs auto clears it");
FakeHost.Chat.Clear();
hub.T11.HandleCommand(Array.Empty<string>());
Check.True(FakeHost.Chat.Any(l => l.Contains("=== T11 loot")), "no argument: the status");
Check.True(FakeHost.Chat.Any(l => l.Contains("Item Augmentations") || l.Contains("unknown")), "lists the counters");
FakeHost.Chat.Clear();
hub.T11.HandleCommand(new[] { "augs", "-5" });
Check.True(FakeHost.Chat.Any(l => l.Contains("Usage")), "a bad count: usage");
}
private static void DormantOffIlt()
{
var off = NewHub("Aeshnidae", "off");
off.OnChat("Advanced Augmentation Levels:");
off.OnChat("Item:2,400");
for (int i = 0; i < 3; i++) off.Tick();
Check.Eq(FakeAiHub.Counters.Count, 0, "off ILT: no counter is reported to RynthAi");
Check.True(off.T11.Player.Get(T11Counter.ItemAugmentations) == null, "nor read");
}
private static void ImportsOverride()
{
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Augger");
Directory.CreateDirectory(legacy);
File.WriteAllText(Path.Combine(legacy, "Default.json"), "{ \"T11ItemAugsOverride\": 2750 }");
var state = new IltHubState();
Check.Eq(state.T11.ItemAugsOverride, -1, "automatic by default");
IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Augger");
Check.Eq(state.T11.ItemAugsOverride, 2750, "the RynthAi profile's override came over");
}
}

View file

@ -0,0 +1,527 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The Vaulted Dungeons keeper (Hub/IltVaultedDungeons.cs, Silentkelpie's, taken in with the owner's
// safety rules): ILT only, a master switch (RynthAi's setting, off by default) that gates everything,
// no resume of Active from the saved file, a recall that waits out combat / buffing, /rc quit once per
// activation and never while gated, and a no-kill timer that restarts on kills and captures.
// The clock, the master switch, RynthAi's activity and the gem use are the module's test seams.
internal static class VaultedDungeonsTests
{
private const uint Player = 0x50000C01;
private const uint Quarry = 0x01F7; // dungeon 1: Tyrant's Quarry
private const uint Elsewhere = 0x0001;
private const string Luminance = "You've banked 1,234 Luminance.";
public static void Register(Runner r)
{
r.Add("vaulted: not an ILT world -> inert (no tick work, no recall, no quit, a 'not available' reply)", NotIlt);
r.Add("vaulted: master off -> inert even with a saved Active, Auto Start and Kill Client", MasterOff);
r.Add("vaulted: master on + explicit start -> recalls at 1 s then every 5 s outside, stops inside; a saved Active is not resumed", ExplicitStartRecalls);
r.Add("vaulted: Auto Start On Arrival is honoured only with the master on", AutoStart);
r.Add("vaulted: Kill Client fires once per activation and restarts on luminance, a killing blow and a capture", QuitOnceAndResets);
r.Add("vaulted: Kill Client is never sent once the master goes off, even between the timer and the send", QuitNeverWhenGated);
r.Add("vaulted: a busy bot (combat, buffing, server wait, client busy) defers the recall; the warning keeps its cadence", BusyDefers);
r.Add("vaulted: turning the master off mid-run stops it at once and says so once; turning it on starts Off", MasterOffMidRun);
r.Add("vaulted: the tab and /ra hub open vaulted follow ILT + the master; settings file format kept", TabAndFile);
r.Add("vaulted: capture lines are the Pets tab's own success replies", CaptureLines);
r.Add("vaulted: settings go through the source-generated JSON context (NativeAOT has no reflection serializer)", SourceGeneratedContext);
}
// ── Rig ──────────────────────────────────────────────────────────────────
private sealed class Rig
{
public IltHubController Hub = null!;
public IltVaultedDungeons V = null!;
public string Dir = "";
public long T = 1_000_000;
public bool Master;
public RynthAiActivity? Act = RynthAiActivity.None;
public int MasterCalls, AllowCalls = int.MaxValue;
public readonly List<string> GemsUsed = new();
public bool HasGem = true;
public int Quits => FakeHost.ChatCommands.Count(c => c == "/rc quit");
public int ChatCount(string part) => FakeHost.Chat.Count(c => c.Contains(part, StringComparison.OrdinalIgnoreCase));
public void Step(long ms) { T += ms; V.Tick(T); }
public void Inside() => FakeHost.PlayerPose = ((Quarry << 16) | 0x0100u, 0, 0, 0);
public void Outside() => FakeHost.PlayerPose = ((Elsewhere << 16) | 0x0100u, 0, 0, 0);
public string SettingsFile => Path.Combine(Dir, "VaultedDungeons", "settings.json");
public void WriteSettings(string json)
{
Directory.CreateDirectory(Path.GetDirectoryName(SettingsFile)!);
File.WriteAllText(SettingsFile, json);
}
}
private static Rig NewRig(string world, string folder, bool master, bool busyCalls = false)
{
FakeHost.Reset();
FakeHost.WorldName = world;
FakeHost.BusyCalls = busyCalls;
var host = FakeHost.Create(Player);
var rig = new Rig { Master = master, Dir = Path.Combine(Program.TempRoot, folder) };
Directory.CreateDirectory(rig.Dir);
rig.Hub = new IltHubController(host, rig.Dir, new IltSettings(), new RynthAiClient(host));
rig.V = rig.Hub.VaultedDungeons;
rig.V.Clock = () => rig.T;
rig.V.MasterEnabled = () => { rig.MasterCalls++; return rig.Master && rig.MasterCalls <= rig.AllowCalls; };
rig.V.Activity = () => rig.Act;
rig.V.UseGem = name => { if (!rig.HasGem) return false; rig.GemsUsed.Add(name); return true; };
rig.Outside();
return rig;
}
/// <summary>Dungeon 1 (Tyrant's Quarry), the primary gem, the given extras. "active": true is on disk to prove it is ignored.</summary>
private static string Settings(string extras = "")
=> "{ \"active\": true, \"dungeon\": 1, \"gem\": 1" + (extras.Length > 0 ? ", " + extras : "") + " }";
// ── ILT only ─────────────────────────────────────────────────────────────
private static void NotIlt()
{
var rig = NewRig("Aelrynth", "vd-notilt", master: true);
rig.WriteSettings(Settings("\"autoStart\": true, \"quit\": true, \"quitMinutes\": 1"));
string before = File.ReadAllText(rig.SettingsFile);
rig.Outside();
for (int i = 0; i < 20; i++) rig.Step(1000);
rig.Inside();
for (int i = 0; i < 10; i++) rig.Step(30_000);
Check.False(rig.V.IsActive, "not running on another world, though the master is on and Auto Start was saved");
Check.Eq(rig.GemsUsed.Count, 0, "no recall gem");
Check.Eq(rig.Quits, 0, "no /rc quit");
Check.Eq(FakeHost.ChatCommands.Count, 0, "no command of any kind (no /vt, /ub or /rc)");
Check.Eq(rig.ChatCount("[Vaulted Dungeons]"), 0, "and not a word in chat");
Check.Eq(File.ReadAllText(rig.SettingsFile), before, "the settings file wasn't even read or rewritten");
rig.V.HandleCommand(new[] { "on" });
Check.False(rig.V.IsActive, "/ilt vaulted on is refused");
Check.Eq(rig.ChatCount("Not available on this server"), 1, "with the 'not available on this server' reply");
FakeHost.Chat.Clear();
rig.V.HandleCommand(new[] { "status" });
Check.Eq(rig.ChatCount("Not available on this server"), 1, "status says the same");
Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "no tab");
Check.False(rig.Hub.SectionAvailable(IltSection.VaultedDungeons), "not available");
// The controller doesn't tick it either (and the module would refuse anyway).
rig.Hub.Tick();
Check.Eq(rig.GemsUsed.Count, 0, "the controller's tick does nothing here");
}
// ── Master switch ────────────────────────────────────────────────────────
private static void MasterOff()
{
var rig = NewRig("InfiniteLeaftide", "vd-masteroff", master: false);
rig.WriteSettings(Settings("\"autoStart\": true, \"quit\": true, \"quitMinutes\": 1, \"disableMeta\": true"));
string before = File.ReadAllText(rig.SettingsFile);
rig.Outside();
for (int i = 0; i < 20; i++) rig.Step(1000);
rig.Inside();
for (int i = 0; i < 10; i++) rig.Step(30_000); // five minutes inside: a one-minute Kill Client would have fired
Check.False(rig.V.IsActive, "off: a saved Active and Auto Start start nothing");
Check.Eq(rig.GemsUsed.Count, 0, "no recall gem");
Check.Eq(rig.Quits, 0, "no /rc quit");
Check.Eq(FakeHost.ChatCommands.Count, 0, "no arrival commands (/vt opt set ...) either");
Check.Eq(rig.ChatCount("[Vaulted Dungeons]"), 0, "silent");
Check.Eq(File.ReadAllText(rig.SettingsFile), before, "settings untouched");
Check.True(rig.Hub.Options.IsIltLikeWorld, "(it is an ILT world: the master switch is what holds it)");
Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "the tab is hidden");
Check.False(rig.Hub.SectionAvailable(IltSection.VaultedDungeons), "and not available");
rig.V.HandleCommand(new[] { "on" });
Check.False(rig.V.IsActive, "/ilt vaulted on is refused");
Check.Eq(rig.ChatCount("Settings > Navigation"), 1, "and says where the switch is");
rig.V.HandleCommand(new[] { "toggle" });
Check.False(rig.V.IsActive, "toggle too");
// Through the controller, the real wiring: nothing either.
for (int i = 0; i < 5; i++) rig.Hub.Tick();
Check.Eq(rig.GemsUsed.Count, 0, "the controller's tick does nothing while off");
// The lines that restart the timer are ignored too (nothing is running).
rig.V.OnChat(Luminance);
rig.V.OnKillNotification();
Check.Eq(rig.Quits, 0, "still nothing");
}
// ── Recalls ──────────────────────────────────────────────────────────────
private static void ExplicitStartRecalls()
{
var rig = NewRig("InfiniteLeaftide", "vd-recall", master: true);
rig.WriteSettings(Settings()); // "active": true on disk: ignored
rig.Outside();
rig.Step(0);
Check.False(rig.V.IsActive, "a saved Active is not resumed after login");
for (int i = 0; i < 10; i++) rig.Step(1000);
Check.Eq(rig.GemsUsed.Count, 0, "so nothing is recalled until the player starts it");
rig.V.HandleCommand(new[] { "on" });
Check.True(rig.V.IsActive, "an explicit start");
rig.Step(0); // first tick outside: the clock starts
rig.Step(500);
Check.Eq(rig.GemsUsed.Count, 0, "0.5 s out: too early");
rig.Step(500); // 1 s
Check.Eq(rig.GemsUsed.Count, 1, "the first recall comes 1 s after leaving");
Check.Eq(rig.GemsUsed[0], "Primary Portal Recall Gem", "the chosen gem");
rig.Step(4000);
Check.Eq(rig.GemsUsed.Count, 1, "4 s later: not yet");
rig.Step(1000); // 5 s since the last use
Check.Eq(rig.GemsUsed.Count, 2, "then every 5 s");
rig.Step(5000);
Check.Eq(rig.GemsUsed.Count, 3, "again");
rig.Inside();
rig.Step(1000);
for (int i = 0; i < 12; i++) rig.Step(1000);
Check.Eq(rig.GemsUsed.Count, 3, "inside the dungeon: no more gems");
FakeHost.Portaling = true;
rig.Outside();
rig.Step(10_000);
Check.Eq(rig.GemsUsed.Count, 3, "portal space: nothing used");
FakeHost.Portaling = false;
rig.Step(0);
rig.Step(1000);
Check.Eq(rig.GemsUsed.Count, 4, "out again: 1 s, then a recall");
rig.HasGem = false;
rig.Step(5000);
Check.Eq(rig.GemsUsed.Count, 4, "no gem in the pack: none used");
Check.True(rig.ChatCount("No Primary Portal Recall Gem") >= 1, "and it says so");
}
private static void AutoStart()
{
// Master on: arriving in the chosen dungeon switches it on, and the arrival commands go out.
var on = NewRig("InfiniteLeaftide", "vd-auto-on", master: true);
on.WriteSettings(Settings("\"autoStart\": true, \"disableMeta\": true"));
on.Inside();
on.Step(0);
Check.True(on.V.IsActive, "Auto Start On Arrival switches the keeper on (master on)");
Check.True(FakeHost.ChatCommands.Contains("/vt opt set EnableMeta False"), "and runs the arrival commands");
// Auto Start off, master on: a relog inside does not resume a saved Active.
var manual = NewRig("InfiniteLeaftide", "vd-auto-off", master: true);
manual.WriteSettings(Settings("\"disableMeta\": true"));
manual.Inside();
manual.Step(0);
Check.False(manual.V.IsActive, "no Auto Start: not resumed");
Check.Eq(FakeHost.ChatCommands.Count, 0, "and the arrival commands wait for an Active keeper");
// Master off, Auto Start saved: nothing; then the master comes on while inside.
var gated = NewRig("InfiniteLeaftide", "vd-auto-gated", master: false);
gated.WriteSettings(Settings("\"autoStart\": true"));
gated.Inside();
gated.Step(0);
Check.False(gated.V.IsActive, "master off: Auto Start does nothing");
gated.Master = true;
gated.Step(1000);
Check.True(gated.V.IsActive, "with the master on, Auto Start (the player's own saved choice) applies");
}
// ── Kill Client ──────────────────────────────────────────────────────────
private static Rig QuitRig(string folder, int minutes = 2)
{
var rig = NewRig("InfiniteLeaftide", folder, master: true);
rig.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": " + minutes));
rig.Inside();
rig.Step(0);
rig.V.HandleCommand(new[] { "on" });
rig.Step(0); // inside: the no-kill clock starts here
return rig;
}
private static void QuitOnceAndResets()
{
// Luminance line.
var rig = QuitRig("vd-quit-lum");
rig.Step(119_000);
Check.Eq(rig.Quits, 0, "just under 2 minutes: no quit");
rig.V.OnChat(Luminance);
rig.Step(119_000);
Check.Eq(rig.Quits, 0, "the luminance line restarted the timer");
rig.Step(2_000);
Check.Eq(rig.Quits, 1, "2 minutes after the last kill: /rc quit");
for (int i = 0; i < 10; i++) rig.Step(60_000);
Check.Eq(rig.Quits, 1, "and only once");
// A kill after the quit went out doesn't arm a second one (once per activation).
rig.V.OnChat(Luminance);
for (int i = 0; i < 10; i++) rig.Step(60_000);
Check.Eq(rig.Quits, 1, "still once");
// The player's own killing blow.
rig = QuitRig("vd-quit-kill");
rig.Step(110_000);
rig.V.OnKillNotification();
rig.Step(110_000);
Check.Eq(rig.Quits, 0, "a killing blow restarted the timer");
rig.Step(15_000);
Check.Eq(rig.Quits, 1, "and it fires after the next idle stretch");
// A pet capture.
rig = QuitRig("vd-quit-capture");
rig.Step(110_000);
rig.V.OnChat("You have successfully siphoned the essence of the Olthoi Warrior.");
rig.Step(110_000);
Check.Eq(rig.Quits, 0, "a capture restarted the timer");
rig.V.OnChat("The echo resonates perfectly.");
rig.Step(110_000);
Check.Eq(rig.Quits, 0, "so does the other success reply");
rig.Step(15_000);
Check.Eq(rig.Quits, 1, "then it fires");
// Lines that are not kills don't restart it.
rig = QuitRig("vd-quit-noise");
rig.Step(110_000);
rig.V.OnChat("You hit the Olthoi Warrior for 50 points of damage.");
rig.V.OnChat("The essence is not ready yet.");
rig.V.OnChat("Bob says, \"You've banked 5 Luminance.\""); // a player's chat, not the system line
rig.Step(15_000);
Check.Eq(rig.Quits, 1, "damage lines, a refused capture and someone else's chat don't count");
// The minutes are the player's setting: 1 minute here.
rig = QuitRig("vd-quit-1m", minutes: 1);
rig.Step(59_000);
Check.Eq(rig.Quits, 0, "1 minute setting: not yet");
rig.Step(2_000);
Check.Eq(rig.Quits, 1, "fires at 1 minute");
// Off -> on again is a new activation: one more quit may be sent.
rig.V.HandleCommand(new[] { "off" });
rig.V.HandleCommand(new[] { "on" });
rig.Step(0);
rig.Step(61_000);
Check.Eq(rig.Quits, 2, "a new activation gets its own single quit");
}
private static void QuitNeverWhenGated()
{
// The master goes off, the timer would have fired: nothing is sent, and it stopped.
var rig = QuitRig("vd-quit-gated");
rig.Step(100_000);
rig.Master = false;
rig.Step(30_000);
Check.Eq(rig.Quits, 0, "master off before the timer: no /rc quit");
Check.False(rig.V.IsActive, "and the keeper is off");
rig.Step(600_000);
Check.Eq(rig.Quits, 0, "ever");
// The master goes off between the timer firing and the send (asked again right before sending).
rig = QuitRig("vd-quit-race");
rig.Step(100_000);
rig.AllowCalls = rig.MasterCalls + 1; // true at the top of the next tick, false when it re-checks
rig.Step(21_000); // the timer fires in this tick
Check.Eq(rig.Quits, 0, "master off between the timer firing and the send: not sent");
Check.False(rig.V.IsActive, "the keeper stopped");
Check.Eq(rig.ChatCount("Stopped"), 1, "said once");
// Not an ILT world any more (the world name changes): same.
rig = QuitRig("vd-quit-world");
rig.Step(100_000);
FakeHost.WorldName = "Aelrynth";
rig.Step(30_000);
Check.Eq(rig.Quits, 0, "world no longer ILT: no /rc quit");
Check.False(rig.V.IsActive, "stopped");
// Not Active: the timer has nothing to do (the player turned it off).
rig = QuitRig("vd-quit-off");
rig.V.HandleCommand(new[] { "off" });
for (int i = 0; i < 10; i++) rig.Step(60_000);
Check.Eq(rig.Quits, 0, "Off: no quit");
}
// ── Combat / buff guard ──────────────────────────────────────────────────
private static void BusyDefers()
{
var rig = NewRig("InfiniteLeaftide", "vd-busy", master: true, busyCalls: true);
rig.WriteSettings(Settings());
rig.Outside();
rig.Step(0);
rig.V.HandleCommand(new[] { "on" });
rig.Act = RynthAiActivity.MacroRunning | RynthAiActivity.Combat;
rig.Step(0);
rig.Step(1000);
rig.Step(4000);
Check.Eq(rig.GemsUsed.Count, 0, "in combat: the recall is deferred");
Check.Eq(rig.ChatCount("Waiting to use the Primary Portal Recall Gem"), 1, "and says why, once");
rig.Step(20_000);
Check.Eq(rig.ChatCount("Waiting to use"), 1, "no repeat inside the 30 s warning cadence");
rig.Step(10_000);
Check.Eq(rig.ChatCount("Waiting to use"), 2, "the warning comes again after 30 s");
Check.Eq(rig.GemsUsed.Count, 0, "still nothing used");
rig.Act = RynthAiActivity.MacroRunning; // clear
rig.Step(100);
Check.Eq(rig.GemsUsed.Count, 1, "the first clear tick recalls (it was due all along)");
// Buffing, the server wait, looting, salvaging, crafting and RynthAi not answering all defer too.
foreach (RynthAiActivity? busy in new RynthAiActivity?[]
{ RynthAiActivity.Buffing, RynthAiActivity.ServerAction, RynthAiActivity.Looting, RynthAiActivity.Salvaging, RynthAiActivity.Crafting, null })
{
int before = rig.GemsUsed.Count;
rig.Act = busy;
rig.Step(6000);
Check.Eq(rig.GemsUsed.Count, before, $"busy ({(busy.HasValue ? busy.Value.ToString() : "RynthAi not ready")}): deferred");
rig.Act = RynthAiActivity.None;
rig.Step(100);
Check.Eq(rig.GemsUsed.Count, before + 1, "and used once it is clear");
}
// The client's own busy hourglass.
FakeHost.BusyStateValue = 1;
int n = rig.GemsUsed.Count;
rig.Step(6000);
Check.Eq(rig.GemsUsed.Count, n, "the client is busy: deferred");
FakeHost.BusyStateValue = 0;
rig.Step(100);
Check.Eq(rig.GemsUsed.Count, n + 1, "used when it clears");
// Busy never blocks the Kill Client (it is not a game action that can be lost).
var q = NewRig("InfiniteLeaftide", "vd-busy-quit", master: true);
q.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": 1"));
q.Inside();
q.Step(0);
q.V.HandleCommand(new[] { "on" });
q.Step(0);
q.Act = RynthAiActivity.Combat;
q.Step(61_000);
Check.Eq(q.Quits, 1, "a busy bot still gets its Kill Client");
}
// ── Master off mid-run ───────────────────────────────────────────────────
private static void MasterOffMidRun()
{
var rig = NewRig("InfiniteLeaftide", "vd-midrun", master: true);
rig.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": 1"));
rig.Outside();
rig.Step(0);
rig.V.HandleCommand(new[] { "on" });
rig.Step(0);
rig.Step(1000);
Check.Eq(rig.GemsUsed.Count, 1, "running: a recall went out");
rig.Master = false;
rig.Step(10);
Check.False(rig.V.IsActive, "the master went off: stopped on that very tick");
Check.Eq(rig.ChatCount("Stopped"), 1, "and it said so");
for (int i = 0; i < 20; i++) rig.Step(5000);
Check.Eq(rig.GemsUsed.Count, 1, "no more recalls");
Check.Eq(rig.ChatCount("Stopped"), 1, "and the notice wasn't repeated");
Check.Eq(rig.Quits, 0, "no quit");
rig.Master = true;
rig.Step(10);
Check.False(rig.V.IsActive, "turned back on: it starts Off, nothing resumes by itself");
rig.Step(10_000);
Check.Eq(rig.GemsUsed.Count, 1, "nothing recalled");
rig.V.HandleCommand(new[] { "on" });
rig.Step(0);
rig.Step(1000);
Check.Eq(rig.GemsUsed.Count, 2, "until the player starts it again");
// The Mini Remote button path (posted to the pump) re-checks the switch as well.
rig.V.HandleCommand(new[] { "off" });
rig.Master = false;
rig.Hub.Context.Post(() => rig.V.HandleCommand(new[] { "on" }));
rig.Hub.Tick();
Check.False(rig.V.IsActive, "an On click that lands after the switch went off is refused");
}
// ── Tab, commands, file ──────────────────────────────────────────────────
private static void TabAndFile()
{
var rig = NewRig("InfiniteLeaftide", "vd-tab", master: true);
Check.True(rig.Hub.TabShown(IltSection.VaultedDungeons), "ILT + master on: the tab is shown");
Check.True(IltSections.Tabs.Contains(IltSection.VaultedDungeons), "it is one of the tab-bar tabs");
Check.True(IltSections.IsTab(IltSection.VaultedDungeons), "a Mini Remote tab");
Check.Eq(IltSections.TabId(IltSection.VaultedDungeons), "vaulted", "tab id");
Check.True(IltSections.TryParse("vaulted", out var s) && s == IltSection.VaultedDungeons, "/ra hub open vaulted parses");
Check.True(IltSections.TryParse("vaulted-dungeons", out s) && s == IltSection.VaultedDungeons, "and the long names");
Check.True(RynthCore.Plugin.RynthILT.RynthILTPlugin.IsIltVerb(new[] { "hub", "open", "vaulted" }), "RynthILT takes '/ra hub open vaulted'");
rig.Master = false;
Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "master off: hidden");
// The file: the format Silentkelpie's keeper wrote, kept. A start is saved.
rig = NewRig("InfiniteLeaftide", "vd-file", master: true);
rig.WriteSettings("""{ "dungeon": 3, "gem": 2, "quit": true, "quitMinutes": 7, "autoStart": false, "attackPower": 0.5 }""");
rig.V.HandleCommand(new[] { "status" });
Check.Eq(rig.ChatCount("dungeon=Wailing Cells, gem=Secondary Portal Recall Gem, kill-client=7m"), 1, "dungeon list and gem names as upstream");
rig.V.HandleCommand(new[] { "on" });
rig.Step(0);
string saved = File.ReadAllText(rig.SettingsFile);
Check.True(saved.Contains("\"active\": true") && saved.Contains("\"quitMinutes\": 7") && saved.Contains("\"dungeon\": 3"),
"saved in the same camelCase layout");
// A new session (relog) reads it back with Active Off.
var again = NewRig("InfiniteLeaftide", "vd-file", master: true);
FakeHost.Chat.Clear();
again.V.HandleCommand(new[] { "status" });
Check.True(again.ChatCount("Off — dungeon=Wailing Cells") == 1 && !again.V.IsActive, "the next session starts Off, with the same choices");
}
// The NativeAOT build (what ships) turns reflection-based System.Text.Json off, so the keeper's
// settings must use IltVaultedDungeonsJsonContext. This project runs on the normal runtime where
// reflection would still work, so assert the generated metadata exists and that the file layout
// is what the context (not an options object) produces.
private static void SourceGeneratedContext()
{
var ctx = IltVaultedDungeonsJsonContext.Default;
Check.True(ctx.Cfg != null, "the context has metadata for the settings type (IltVaultedDungeonsJsonContext.Default.Cfg)");
Check.True(ctx.GetTypeInfo(typeof(IltVaultedDungeons.Cfg)) != null, "and resolves it by type");
var cfg = new IltVaultedDungeons.Cfg
{
Active = true, Dungeon = 3, Gem = 2, Quit = true, QuitMinutes = 7, ShowInDungeon = true,
AutoStart = true, DisableMeta = true, DisableNav = false, RepeatAttack = true, SetPower = true, AttackPower = 0.5f,
};
string json = System.Text.Json.JsonSerializer.Serialize(cfg, ctx.Cfg);
Check.True(json.Contains("\"active\": true") && json.Contains("\"quitMinutes\": 7") && json.Contains("\"attackPower\": 0.5"),
"serializes indented with camelCase names");
Check.True(json.Contains("\n"), "indented");
var back = System.Text.Json.JsonSerializer.Deserialize(json, ctx.Cfg);
Check.True(back != null, "round-trips");
Check.True(back!.Active && back.Dungeon == 3 && back.Gem == 2 && back.Quit && back.QuitMinutes == 7 && back.ShowInDungeon
&& back.AutoStart && back.DisableMeta && !back.DisableNav && back.RepeatAttack && back.SetPower && back.AttackPower == 0.5f,
"every field survives");
// The shape of the file Silentkelpie's keeper wrote (camelCase, partial) still reads.
var upstream = System.Text.Json.JsonSerializer.Deserialize(
"""{ "dungeon": 2, "gem": 1, "quit": true, "quitMinutes": 5 }""", ctx.Cfg);
Check.True(upstream != null && upstream.Dungeon == 2 && upstream.Gem == 1 && upstream.Quit && upstream.QuitMinutes == 5 && !upstream.Active,
"a partial upstream file reads, missing fields keep their defaults");
bool threw = false;
try { System.Text.Json.JsonSerializer.Deserialize("{ not json", ctx.Cfg); } catch (System.Text.Json.JsonException) { threw = true; }
Check.True(threw, "a corrupt file still throws, which the keeper's bad-file copy relies on");
}
private static void CaptureLines()
{
Check.True(PetCaptureLines.IsSuccess("You have successfully siphoned the essence."), "siphoned");
Check.True(PetCaptureLines.IsSuccess("The echo resonates perfectly."), "echo");
Check.True(PetCaptureLines.IsSuccess("The essence is captured!"), "captured");
Check.False(PetCaptureLines.IsSuccess("The creature is too strong to be siphoned."), "a refusal is not a success");
Check.False(PetCaptureLines.IsSuccess("siphon failed"), "nor a failure");
Check.False(PetCaptureLines.IsSuccess(""), "empty");
}
}

View file

@ -0,0 +1,64 @@
using System;
using System.IO;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The Vaulted Dungeons keeper's master switch moved from RynthAi's profile to RynthILT on 2026-10-20
// (IltHubState.VaultedDungeonsEnabled, the ILT settings view). RynthAi mirrors it into the engine's
// Settings > Navigation row through RynthILT.Hub GetSetting / SetSetting, which offer it on ILT only.
internal static class VaultedSwitchTests
{
public static void Register(Runner r)
{
r.Add("vaulted switch: RynthILT's own (off by default), what the keeper reads, offered to the engine row on ILT only", OwnSwitch);
r.Add("migration: the RynthAi profile's Vaulted Dungeons switch comes over once", ImportsSwitch);
}
private static IltHubController NewHub(string world, string folder)
{
FakeHost.Reset();
FakeHost.WorldName = world;
var host = FakeHost.Create(0x50000C01);
string dir = Path.Combine(Program.TempRoot, "vswitch-" + folder);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host));
hub.OnLoginComplete("Vaulter", forceFromMigration: false);
return hub;
}
private static void OwnSwitch()
{
var hub = NewHub("InfiniteLeaftide", "own");
Check.False(hub.State.VaultedDungeonsEnabled, "off by default");
Check.False(hub.VaultedDungeons.MasterEnabled(), "the keeper reads RynthILT's own switch (no RynthAi needed)");
Check.False(hub.SectionAvailable(IltSection.VaultedDungeons), "no tab while off");
Check.Eq(hub.GetSetting(RynthServerHub.SettingVaultedDungeons), 0, "offered to the engine row: off");
Check.True(hub.SetSetting(RynthServerHub.SettingVaultedDungeons, 1), "the engine row (through RynthAi) sets it");
Check.True(hub.State.VaultedDungeonsEnabled && hub.VaultedDungeons.MasterEnabled(), "on");
Check.True(hub.SectionAvailable(IltSection.VaultedDungeons), "the tab shows on ILT");
Check.Eq(hub.GetSetting("no-such-setting"), -1, "an unknown key isn't offered");
Check.False(hub.SetSetting("no-such-setting", 1), "nor taken");
var off = NewHub("Aeshnidae", "off");
Check.Eq(off.GetSetting(RynthServerHub.SettingVaultedDungeons), -1, "off ILT: not offered (the engine row hides)");
}
private static void ImportsSwitch()
{
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Vaulter");
Directory.CreateDirectory(legacy);
File.WriteAllText(Path.Combine(legacy, "Default.json"), "{ \"EnableVaultedDungeons\": true }");
var state = new IltHubState();
var lines = IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Vaulter");
Check.True(state.VaultedDungeonsEnabled, "on in the RynthAi profile: on here");
Check.True(lines.Exists(l => l.Contains("Vaulted Dungeons master switch on")), "logged");
state.VaultedDungeonsEnabled = false;
IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Vaulter");
Check.False(state.VaultedDungeonsEnabled, "copied once: RynthILT's later change stays");
}
}