RynthServers/Tools/RynthILT.Tests/AttributeRaiserTests.cs

543 lines
34 KiB
C#

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");
}
}