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,297 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthThreads.Threads;
using RynthCore.RynthAiTests.Harness;
namespace RynthThreads.Tests;
// The odds (Threads/PressInference.cs): rates, intervals and comparisons, on the first real presses
// and on made-up ones.
internal static class InferenceTests
{
public static void Register(Runner r)
{
r.Add("infer: the 4 real Lead Scarab presses (old JSON lines): rates, intervals, Affinity group", RealPresses);
r.Add("infer: with/without a component; 'more likely' only when clear; 'always' only at 10+", WithWithout);
r.Add("infer: Wilson intervals and the Fisher test", Statistics);
r.Add("infer: exact combinations of components", Combinations);
r.Add("infer: No components and All presses rows; incomplete presses left out", NoComponentsAndAll);
r.Add("infer: Affinity grouping and the split by material", AffinityGroup);
r.Add("infer: per-modifier view: overall, no components, each component (0% too)", ModifierView);
r.Add("infer: values by level, tags, results and modifiers per press", ReportDetails);
r.Add("infer: the sample press runs through the whole report", SampleReport);
}
/// <summary>The first 4 presses from presses.jsonl (2026-10-12, all Lead Scarab), exactly as written.</summary>
internal static readonly string[] RealLines =
{
"""{"v":1,"id":"ccbf1dd788704e08","time":"2026-10-12T23:44:32.8501639Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Radiant","description":"kills pay x1.84 luminance","numbers":[{"value":1.84,"kind":"mult","text":"x1.84"}]},{"name":"Amethyst Affinity","description":"10% of kills leave amethyst to salvage","numbers":[{"value":10,"kind":"pct","text":"10%"}]},{"name":"Precise","description":"monsters have \u002B27 critical strike rating, landing more critical hits","numbers":[{"value":27,"kind":"plus","text":"\u002B27"}]},{"name":"Guarded","description":"the boss has x1.91 health","numbers":[{"value":1.91,"kind":"mult","text":"x1.91"}]},{"name":"Savage","description":"monsters attack with \u002B35 damage rating, hitting harder","numbers":[{"value":35,"kind":"plus","text":"\u002B35"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Radiant - kills pay x1.84 luminance"," Amethyst Affinity - 10% of kills leave amethyst to salvage"," Precise - monsters have \u002B27 critical strike rating, landing more critical hits"," Guarded - the boss has x1.91 health"," Savage - monsters attack with \u002B35 damage rating, hitting harder","Level 175, 3 entries."],"extra":[]}""",
"""{"v":1,"id":"6613196a36424f8c","time":"2026-10-12T23:50:31.1229501Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Radiant","description":"kills pay x1.75 luminance","numbers":[{"value":1.75,"kind":"mult","text":"x1.75"}]},{"name":"Iron Affinity","description":"8% of kills leave iron to salvage","numbers":[{"value":8,"kind":"pct","text":"8%"}]},{"name":"Teeming","description":"67% more monsters","numbers":[{"value":67,"kind":"pct","text":"67%"}]},{"name":"Guarded","description":"the boss has x1.83 health","numbers":[{"value":1.83,"kind":"mult","text":"x1.83"}]},{"name":"Swift","description":"monsters move at x1.21 speed","numbers":[{"value":1.21,"kind":"mult","text":"x1.21"}]},{"name":"Shieldbreaker","description":"monsters ignore 54% of your shield","numbers":[{"value":54,"kind":"pct","text":"54%"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Radiant - kills pay x1.75 luminance"," Iron Affinity - 8% of kills leave iron to salvage"," Teeming - 67% more monsters"," Guarded - the boss has x1.83 health"," Swift - monsters move at x1.21 speed"," Shieldbreaker - monsters ignore 54% of your shield","Level 175, 3 entries."],"extra":[]}""",
"""{"v":1,"id":"1e960ea87fa64343","time":"2026-10-13T00:22:04.7703741Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Bounteous","description":"kills drop x1.51 loot","numbers":[{"value":1.51,"kind":"mult","text":"x1.51"}]},{"name":"Serpentine Affinity","description":"22% of kills leave serpentine to salvage","numbers":[{"value":22,"kind":"pct","text":"22%"}]},{"name":"Champions","description":"30% of the run\u0027s monsters are elites","numbers":[{"value":30,"kind":"pct","text":"30%"}]},{"name":"Guarded","description":"the boss has x2.18 health","numbers":[{"value":2.18,"kind":"mult","text":"x2.18"}]},{"name":"Enraged","description":"the boss attacks with \u002B54 damage rating, hitting harder","numbers":[{"value":54,"kind":"plus","text":"\u002B54"}]},{"name":"Precise","description":"monsters have \u002B19 critical strike rating, landing more critical hits","numbers":[{"value":19,"kind":"plus","text":"\u002B19"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Bounteous - kills drop x1.51 loot"," Serpentine Affinity - 22% of kills leave serpentine to salvage"," Champions - 30% of the run\u0027s monsters are elites"," Guarded - the boss has x2.18 health"," Enraged - the boss attacks with \u002B54 damage rating, hitting harder"," Precise - monsters have \u002B19 critical strike rating, landing more critical hits","Level 175, 3 entries."],"extra":[]}""",
"""{"v":1,"id":"f0bf2c2811904c52","time":"2026-10-13T00:34:08.9352276Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Enlightened","description":"kills pay x1.43 experience","numbers":[{"value":1.43,"kind":"mult","text":"x1.43"}]},{"name":"Obsidian Affinity","description":"7% of kills leave obsidian to salvage","numbers":[{"value":7,"kind":"pct","text":"7%"}]},{"name":"Shieldbreaker","description":"monsters ignore 51% of your shield","numbers":[{"value":51,"kind":"pct","text":"51%"}]},{"name":"Savage","description":"monsters attack with \u002B33 damage rating, hitting harder","numbers":[{"value":33,"kind":"plus","text":"\u002B33"}]},{"name":"Stalwart","description":"monsters have \u002B20 damage resist rating, taking less damage from you","numbers":[{"value":20,"kind":"plus","text":"\u002B20"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Enlightened - kills pay x1.43 experience"," Obsidian Affinity - 7% of kills leave obsidian to salvage"," Shieldbreaker - monsters ignore 51% of your shield"," Savage - monsters attack with \u002B33 damage rating, hitting harder"," Stalwart - monsters have \u002B20 damage resist rating, taking less damage from you","Level 175, 3 entries."],"extra":["[BANK] Debited 1 Trade Notes (250,000) (250,000 pyreals) from your bank."]}""",
};
internal static List<Press> Real() => RealLines.Select(l => PressStore.FromJson(l)!).ToList();
private static int _n;
/// <summary>A complete press with these components and modifiers ("Name" or "Name=x1.5 text").</summary>
internal static Press P(string components, string modifiers, int level = 100, bool complete = true, int? result = null, int? entries = null)
{
var p = new Press
{
Id = "t" + (++_n),
TimeUtc = new DateTime(2026, 10, 12, 19, 0, 0, DateTimeKind.Utc).AddSeconds(_n),
Character = "Tester",
Server = "DreamWeave",
Fragment = "Raw Fragment",
FragmentLevel = level,
Outcome = "Pressed. It holds.",
ComponentsSeen = true,
Components = PressParser.SplitComponents(components),
Complete = complete,
End = complete ? "done" : "timeout",
ResultLevel = result,
Entries = entries,
};
foreach (string m in modifiers.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
string[] parts = m.Split('=', 2);
string desc = parts.Length > 1 ? parts[1] : "something";
p.Modifiers.Add(new GemModifier { Name = parts[0], Description = desc, Numbers = PressParser.Numbers(desc) });
}
return p;
}
private static List<Press> Many(int count, string components, string modifiers) =>
Enumerable.Range(0, count).Select(_ => P(components, modifiers)).ToList();
private static Odds? Odd(GroupReport? g, string mod) => g?.Find(mod);
private static void RealPresses()
{
List<Press> presses = Real();
Check.True(presses.All(p => p != null && p.Usable), "all 4 old lines load as complete presses");
Check.Eq(string.Join(",", presses.Select(p => p.ComponentsText).Distinct()), "Lead Scarab", "all Lead Scarab");
ThreadsReport r = PressInference.Build(presses);
GroupReport? ls = r.Component("Lead Scarab");
Check.NotNull(ls, "Lead Scarab row");
if (ls == null) return;
Check.Eq(ls.Presses, 4, "4 presses");
Odds g = Odd(ls, "Guarded")!;
Check.Eq((g.Hits, g.N), (3, 4), "Guarded 3/4");
Check.Eq(PressInference.OddsText(g), "75% (3/4, 30-95%)", "Guarded text");
Check.Eq(g.Values, "x1.83 to x2.18", "Guarded values");
Odds rad = Odd(ls, "Radiant")!;
Check.Eq(PressInference.OddsText(rad), "50% (2/4, 15-85%)", "Radiant 2/4");
Check.Eq(PressInference.OddsText(Odd(ls, "Champions")!), "25% (1/4, 5-70%)", "Champions 1/4");
Odds aff = Odd(ls, PressInference.AffinityGroup)!;
Check.Eq((aff.Hits, aff.N), (4, 4), "Affinity group 4/4");
Check.Eq(PressInference.OddsText(aff), "100% (4/4, 51-100%)", "Affinity text");
Check.Eq(PressInference.SplitText(aff), "Amethyst 1, Iron 1, Obsidian 1, Serpentine 1", "split 1 each");
Check.Eq(aff.Values, "7% to 22%", "affinity values across materials");
Check.Null(Odd(ls, "Amethyst Affinity"), "materials are not rows of their own");
Check.Eq(ls.Odds[0].Modifier, PressInference.AffinityGroup, "sorted by rate: Affinity first");
Check.Eq(ls.Odds[1].Modifier, "Guarded", "then Guarded");
Check.Eq(PressInference.OtherText(g, ls.OtherLabel), "without: no data", "nothing without Lead Scarab");
Check.False(ls.Odds.Any(o => o.MoreLikely), "no 'more likely' with nothing to compare");
Check.Eq(r.All?.Presses, 4, "All presses row");
Check.Eq(r.Combinations.Count, 0, "no combinations");
Check.Null(r.NoComponents, "no No components row");
Check.Eq(PressInference.ModifiersText(ls), "5.5 modifiers per press (5-6)", "modifiers per press");
Check.Eq(PressInference.ResultsText(ls), "L185 -> 175, 3 entries: 4", "results");
Check.Eq(r.Modifier("Affinity")?.Overall.Hits, 4, "modifier view: Affinity 4/4");
Check.Null(r.Modifier("Iron Affinity"), "no Iron Affinity modifier entry");
Check.Eq(r.Modifiers.Count, 13, "13 modifiers (affinities as one)");
}
private static void WithWithout()
{
var presses = Many(5, "Red Taper", "Bounteous, Hardy");
presses.Add(P("Red Taper", "Teeming, Hardy"));
presses.AddRange(Many(3, "", "Hardy, Teeming"));
presses.AddRange(Many(3, "", "Savage, Teeming"));
ThreadsReport r = PressInference.Build(presses);
GroupReport red = r.Component("Red Taper")!;
Odds b = Odd(red, "Bounteous")!;
Check.Eq((b.Hits, b.N, b.OtherHits, b.OtherN), (5, 6, 0, 6), "Bounteous 5/6 with, 0/6 without");
Check.True(b.MoreLikely, "Bounteous more likely with Red Taper");
Check.Eq(PressInference.LikelyText(b, red), "more likely with Red Taper", "wording");
Check.Eq(PressInference.OtherText(b, red.OtherLabel), "without: 0% (0/6)", "without text");
Odds h = Odd(red, "Hardy")!;
Check.Eq((h.Hits, h.OtherHits), (6, 3), "Hardy 6/6 with, 3/6 without");
Check.False(h.MoreLikely, "Hardy 6/6 vs 3/6: not clear (p ~ 0.09)");
Check.Eq(red.Odds[0].Modifier, "Hardy", "sorted by rate: Hardy (100%) first");
// Few presses: nothing claimed.
r = PressInference.Build(Many(2, "Blue Taper", "Bounteous").Concat(Many(2, "", "Hardy")).ToList());
Check.False(Odd(r.Component("Blue Taper"), "Bounteous")!.MoreLikely, "2/2 vs 0/2: not claimed");
// 'always' only at 100% over 10 or more.
r = PressInference.Build(Many(9, "Green Taper", "Teeming").Concat(Many(9, "", "Hardy")).ToList());
GroupReport green = r.Component("Green Taper")!;
Check.Eq(PressInference.LikelyText(Odd(green, "Teeming")!, green), "more likely with Green Taper", "9/9: more likely, not always");
r = PressInference.Build(Many(10, "Green Taper", "Teeming").Concat(Many(10, "", "Hardy")).ToList());
green = r.Component("Green Taper")!;
Check.Eq(PressInference.LikelyText(Odd(green, "Teeming")!, green), "always with Green Taper so far", "10/10: always so far");
// The No components row is compared with presses that had components.
r = PressInference.Build(Many(6, "Red Taper", "Hardy").Concat(Many(6, "", "Teeming")).ToList());
Odds t = Odd(r.NoComponents, "Teeming")!;
Check.True(t.MoreLikely, "Teeming 6/6 plain vs 0/6 with components");
Check.Eq(PressInference.LikelyText(t, r.NoComponents!), "more likely with no components", "no-components wording");
}
private static void Statistics()
{
var (lo, hi) = PressInference.Wilson(3, 4);
Check.True(Math.Abs(lo - 0.3006) < 0.001 && Math.Abs(hi - 0.9544) < 0.001, $"3/4: 30.1-95.4% ({lo:0.0000}-{hi:0.0000})");
(lo, hi) = PressInference.Wilson(0, 5);
Check.True(lo == 0 && Math.Abs(hi - 0.4345) < 0.001, $"0/5: 0-43% ({hi:0.0000})");
(lo, hi) = PressInference.Wilson(0, 0);
Check.True(lo == 0 && hi == 1, "0/0: anything");
Check.True(Math.Abs(PressInference.FisherGreater(3, 3, 0, 3) - 0.05) < 1e-9, "3/3 vs 0/3: p = 1/20");
Check.True(Math.Abs(PressInference.FisherGreater(5, 6, 0, 6) - 7.0 / 924) < 1e-9, "5/6 vs 0/6: p = 7/924");
Check.True(Math.Abs(PressInference.FisherGreater(0, 4, 4, 4) - 1) < 1e-9, "0 hits: p = 1");
Check.Eq(PressInference.OddsText(new Odds { Hits = 30, N = 60 }), "50% (30/60)", "no interval from 50 presses");
Check.Eq(PressInference.OddsText(new Odds { Hits = 0, N = 0 }), "no data", "empty");
}
private static void Combinations()
{
var presses = Many(3, "Red Taper, Blue Taper", "Bounteous, Savage");
presses.AddRange(Many(2, "Red Taper", "Bounteous, Hardy"));
presses.Add(P("Blue Taper", "Savage, Hardy"));
presses.AddRange(Many(2, "", "Hardy, Teeming"));
ThreadsReport r = PressInference.Build(presses);
Check.Eq(r.Combinations.Count, 1, "one combination");
GroupReport? combo = r.Combination("Blue Taper + Red Taper");
Check.NotNull(combo, "named by its sorted components");
if (combo == null) return;
Check.Eq(combo.Presses, 3, "3 presses with exactly both");
Check.Eq(combo.Members.Count, 2, "two members");
Check.Eq(r.Component("Red Taper")!.Presses, 5, "component row counts every press with it");
Check.Eq(r.Component("Blue Taper")!.Presses, 4, "Blue Taper 4");
Odds s = Odd(combo, "Savage")!;
Check.Eq((s.Hits, s.N, s.OtherHits, s.OtherN), (3, 3, 1, 5), "Savage 3/3 in the combination, 1/5 in other presses");
Check.Eq(PressInference.OtherText(s, combo.OtherLabel), "other presses: 20% (1/5)", "comparison label");
Check.Eq(PressInference.Build(Many(2, "Blue Taper, Red Taper", "Hardy").Concat(Many(1, "Red Taper, Blue Taper", "Hardy")).ToList())
.Combination("Blue Taper + Red Taper")?.Presses, 3, "order of components doesn't matter");
}
private static void NoComponentsAndAll()
{
var presses = Many(4, "Red Taper", "Bounteous, Hardy");
presses.AddRange(Many(2, "", "Hardy, Teeming"));
presses.Add(P("", "Teeming"));
presses.Add(P("Red Taper", "Savage", complete: false));
presses.Add(P("", "")); // finished but no gem block: not usable
ThreadsReport r = PressInference.Build(presses);
Check.Eq((r.Total, r.Usable, r.Incomplete), (9, 7, 1), "totals");
Check.Eq(r.Component("Red Taper")!.Presses, 4, "incomplete press left out");
GroupReport? nc = r.NoComponents;
Check.NotNull(nc, "No components row");
if (nc == null) return;
Check.Eq((nc.Presses, nc.Kind), (3, GroupKind.NoComponents), "3 plain presses");
Odds t = Odd(nc, "Teeming")!;
Check.Eq((t.Hits, t.N, t.OtherHits, t.OtherN), (3, 3, 0, 4), "Teeming 3/3 plain, 0/4 with components");
Check.Eq(PressInference.OtherText(t, nc.OtherLabel), "with components: 0% (0/4)", "comparison label");
Check.Eq(nc.Odds[0].Modifier, "Teeming", "most common plain draw first");
GroupReport all = r.All!;
Check.Eq((all.Presses, all.Kind), (7, GroupKind.All), "All presses: every usable press");
Odds h = Odd(all, "Hardy")!;
Check.Eq((h.Hits, h.N), (6, 7), "Hardy 6/7 overall");
Check.False(h.Compared, "the baseline isn't compared");
Check.Eq(PressInference.OtherText(h, all.OtherLabel), "", "no comparison text");
Check.False(all.Odds.Any(o => o.MoreLikely), "never flagged");
}
private static void AffinityGroup()
{
Check.Eq(PressInference.Material("Green Garnet Affinity"), "Green Garnet", "two-word material");
Check.Eq(PressInference.Key("Tourmaline Affinity"), PressInference.AffinityGroup, "grouped");
Check.Null(PressInference.Material("Affinity"), "bare 'Affinity' is not a material");
Check.Eq(PressInference.Key("Guarded"), "Guarded", "others keep their name");
Check.Eq(PressInference.Display(PressInference.AffinityGroup), "Affinity (any)", "display name");
var presses = new List<Press>
{
P("Red Taper", "Iron Affinity=8% of kills leave iron to salvage, Hardy"),
P("Red Taper", "Iron Affinity=10% of kills leave iron to salvage, Teeming"),
P("Red Taper", "Amethyst Affinity=12% of kills leave amethyst to salvage, Gold Affinity=5% of kills leave gold to salvage"),
P("", "Hardy"),
};
ThreadsReport r = PressInference.Build(presses);
Odds a = Odd(r.Component("Red Taper"), PressInference.AffinityGroup)!;
Check.Eq((a.Hits, a.N, a.OtherHits, a.OtherN), (3, 3, 0, 1), "a press with two affinities counts once");
Check.Eq(PressInference.SplitText(a), "Iron 2, Amethyst 1, Gold 1", "split counts both, most first");
ModifierReport m = r.Modifier("Affinity")!;
Check.True(m.IsGroup, "modifier view: the group");
Check.Eq(m.Tag, "reward", "salvage: reward");
Check.Eq(m.Values, "8% to 12%", "values over every material (first affinity per press)");
}
private static void ModifierView()
{
var presses = Many(3, "Red Taper", "Bounteous, Hardy");
presses.AddRange(Many(2, "Blue Taper", "Hardy"));
presses.Add(P("Blue Taper, Red Taper", "Bounteous"));
presses.AddRange(Many(2, "", "Teeming, Bounteous"));
ThreadsReport r = PressInference.Build(presses);
ModifierReport b = r.Modifier("Bounteous")!;
Check.Eq((b.Overall.Hits, b.Overall.N), (6, 8), "overall 6/8");
Check.Eq((b.NoComponents?.Hits, b.NoComponents?.N, b.NoComponents?.OtherHits, b.NoComponents?.OtherN), ((int?)2, (int?)2, (int?)4, (int?)6), "no components 2/2 vs 4/6");
Check.Eq(string.Join(", ", b.ByGroup.Select(x => $"{x.Group.Name} {x.Odds.Hits}/{x.Odds.N}")),
"Red Taper 4/4, Blue Taper + Red Taper 1/1, Blue Taper 1/3", "each component and combination, likeliest first");
Odds teemingBlue = r.Modifier("Teeming")!.ByGroup.First(x => x.Group.Name == "Blue Taper").Odds;
Check.Eq((teemingBlue.Hits, teemingBlue.N, teemingBlue.OtherHits, teemingBlue.OtherN), (0, 3, 2, 5), "0% rows are kept, with their comparison");
}
private static void ReportDetails()
{
var presses = new List<Press>
{
P("Red Taper", "Bounteous=kills drop x1.38 loot, Hardy=monsters have x1.5 health", level: 185, result: 175, entries: 3),
P("Red Taper", "Bounteous=kills drop x1.52 loot", level: 185, result: 175, entries: 3),
P("Red Taper", "Bounteous=kills drop x1.20 loot", level: 120, result: 110, entries: 2),
P("Red Taper", "Hardy=monsters have x2 health", complete: false),
P("", "Hardy=monsters have x1.81 health, Teeming=75% more monsters", level: 120),
P("", "Teeming=60% more monsters", level: 120),
};
ThreadsReport r = PressInference.Build(presses);
GroupReport red = r.Component("Red Taper")!;
Check.Eq(PressInference.ResultsText(red), "L185 -> 175, 3 entries: 2; L120 -> 110, 2 entries: 1", "results, most common first");
Check.Eq(PressInference.ModifiersText(red), "1.33 modifiers per press (1-2)", "modifiers per press");
Check.Eq(Odd(red, "Bounteous")!.Values, "x1.2 to x1.52", "values with the component");
ModifierReport b = r.Modifier("Bounteous")!;
Check.Eq(b.Values, "x1.2 to x1.52", "value range");
Check.Eq(b.ByLevel.Count, 2, "two fragment levels");
Check.Eq(b.ByLevel[0].Level, 120, "lowest level first");
Check.Eq(b.ByLevel[1].Values, "x1.38 to x1.52", "level 185 range");
Check.Eq(b.Tag, "reward", "loot is a reward");
Check.Eq(r.Modifier("Hardy")!.Tag, "harder", "monster health is harder");
Check.Eq(PressInference.Tag("something odd"), "", "no tag when the text doesn't say");
ThreadsReport empty = PressInference.Build(new List<Press>());
Check.True(empty.Usable == 0 && empty.All == null && empty.Modifiers.Count == 0, "empty input");
}
private static void SampleReport()
{
Press p = new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0];
ThreadsReport r = PressInference.Build(new[] { p });
Check.Eq(r.Component("Red Taper")?.Presses, 1, "Red Taper counted");
Check.Eq(r.Modifiers.Count, 6, "six modifiers in the report");
Check.Eq(r.Modifier("Affinity")?.Tag, "reward", "salvage is a reward");
Check.Eq(PressInference.SplitText(r.Modifier("Affinity")!.Overall), "Tourmaline 1", "Tourmaline");
Check.Eq(r.Modifier("Enraged")?.Tag, "harder", "boss damage is harder");
Check.Eq(PressInference.OddsText(r.Component("Red Taper")!.Find("Hardy")!), "100% (1/1, 21-100%)", "one press: wide range");
}
}

View file

@ -0,0 +1,258 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthThreads.Threads;
using RynthCore.RynthAiTests.Harness;
namespace RynthThreads.Tests;
// The chat parser (Threads/PressParser.cs). The sample is real DreamWeave chat from 2026-10-12
// (timestamps removed: the plugin sees the text without them), with another player's line in it.
internal static class ParserTests
{
public static readonly string[] Sample =
{
"Using the Raw Fragment (Level 185) with the Fragment Press",
"Yorick is recalling to the marketplace.",
"Pressed. It holds.",
"Components selected: Red Taper",
"Remaining slots drawn at random.",
"The gem carries:",
" Bounteous - kills drop x1.38 loot",
" Tourmaline Affinity - 12% of kills leave tourmaline to salvage",
" Hardy - monsters have x1.81 health",
" Enraged - the boss attacks with +29 damage rating, hitting harder",
" Teeming - 75% more monsters",
" Savage - monsters attack with +20 damage rating, hitting harder",
"Level 190, 4 entries.",
};
public static void Register(Runner r)
{
r.Add("parse: the real sample, line by line, with another player's line in it", SampleLineByLine);
r.Add("parse: the sample as one message with newlines", SampleOneMessage);
r.Add("parse: several components (commas, 'and'), sorted", SeveralComponents);
r.Add("parse: no components (no line, 'none', 'No components ...')", NoComponents);
r.Add("parse: incomplete presses (timeout, next press, other Using line, logout)", Incomplete);
r.Add("parse: unknown and odd lines never throw and never become modifiers", UnknownLines);
r.Add("parse: numbers and their forms", NumberForms);
}
private static List<Press> FeedAll(PressParser parser, IEnumerable<string> lines, long now = 1000)
{
var done = new List<Press>();
foreach (string line in lines)
if (parser.Feed(line, now) is { } d) done.AddRange(d);
return done;
}
private static void SampleLineByLine()
{
var parser = new PressParser();
List<Press> done = FeedAll(parser, Sample);
Check.Eq(done.Count, 1, "one press");
if (done.Count != 1) return;
CheckSample(done[0]);
Check.False(parser.Busy, "parser idle after the Level line");
}
private static void SampleOneMessage()
{
var parser = new PressParser();
List<Press>? done = parser.Feed(string.Join("\n", Sample) + "\n", 1000);
Check.Eq(done?.Count ?? 0, 1, "one press from one message");
if (done is { Count: 1 }) CheckSample(done[0]);
// CRLF too.
done = new PressParser().Feed(string.Join("\r\n", Sample), 1000);
Check.Eq(done?[0].Modifiers.Count ?? -1, 6, "CRLF lines: 6 modifiers");
}
internal static void CheckSample(Press p)
{
Check.Eq(p.Fragment, "Raw Fragment", "fragment name");
Check.Eq(p.FragmentLevel, 185, "fragment level");
Check.Eq(p.Tool, "Fragment Press", "tool");
Check.Eq(p.Outcome, "Pressed. It holds.", "outcome");
Check.True(p.Held, "held");
Check.True(p.ComponentsSeen, "components line seen");
Check.Eq(string.Join("|", p.Components), "Red Taper", "components");
Check.Eq(p.RandomNote, "Remaining slots drawn at random.", "random note");
Check.Eq(p.ResultLevel, 190, "result level");
Check.Eq(p.Entries, 4, "entries (raw, not the modifier count)");
Check.True(p.Complete, "complete");
Check.Eq(p.End, "done", "end reason");
Check.Eq(p.Modifiers.Count, 6, "six modifiers");
Check.Eq(p.Raw.Count, 12, "12 own raw lines");
Check.Eq(string.Join("|", p.Extra), "Yorick is recalling to the marketplace.", "the foreign line is kept apart");
Check.False(p.Raw.Any(l => l.Contains("Yorick")), "no foreign line in Raw");
Check.Eq(p.Raw[5], " Bounteous - kills drop x1.38 loot", "raw lines kept as is (indent too)");
if (p.Modifiers.Count != 6) return;
(string Name, string Kinds, string Values, string Desc)[] want =
{
("Bounteous", "mult", "1.38", "kills drop x1.38 loot"),
("Tourmaline Affinity", "pct", "12", "12% of kills leave tourmaline to salvage"),
("Hardy", "mult", "1.81", "monsters have x1.81 health"),
("Enraged", "plus", "29", "the boss attacks with +29 damage rating, hitting harder"),
("Teeming", "pct", "75", "75% more monsters"),
("Savage", "plus", "20", "monsters attack with +20 damage rating, hitting harder"),
};
for (int i = 0; i < want.Length; i++)
{
GemModifier m = p.Modifiers[i];
Check.Eq(m.Name, want[i].Name, $"modifier {i} name");
Check.Eq(m.Description, want[i].Desc, $"{want[i].Name} description");
Check.Eq(string.Join(",", m.Numbers.Select(n => n.Kind)), want[i].Kinds, $"{want[i].Name} number kinds");
Check.Eq(string.Join(",", m.Numbers.Select(n => n.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))), want[i].Values, $"{want[i].Name} values");
}
Check.Eq(p.Modifiers[0].Numbers[0].Text, "x1.38", "text as written");
Check.Eq(p.Modifiers[3].Numbers[0].Text, "+29", "rating text");
}
private static string[] Press(string components, params string[] mods)
{
var lines = new List<string> { "Using the Raw Fragment (Level 100) with the Fragment Press", "Pressed. It holds." };
if (components != null) lines.Add(components);
lines.Add("Remaining slots drawn at random.");
lines.Add("The gem carries:");
lines.AddRange(mods.Select(m => " " + m));
lines.Add("Level 104, 2 entries.");
return lines.ToArray();
}
private static void SeveralComponents()
{
Press p = FeedAll(new PressParser(), Press("Components selected: Red Taper, Blue Taper, Pyreal", "Hardy - monsters have x1.5 health")).Single();
Check.Eq(string.Join("|", p.Components), "Blue Taper|Pyreal|Red Taper", "three, sorted");
p = FeedAll(new PressParser(), Press("Components selected: Red Taper and Yellow Taper.", "Hardy - x")).Single();
Check.Eq(string.Join("|", p.Components), "Red Taper|Yellow Taper", "'and' splits, trailing dot dropped");
p = FeedAll(new PressParser(), Press("Components selected: Red Taper, red taper", "Hardy - x")).Single();
Check.Eq(p.Components.Count, 1, "the same component twice counts once");
}
private static void NoComponents()
{
Press p = FeedAll(new PressParser(), Press(null!, "Teeming - 75% more monsters")).Single();
Check.False(p.ComponentsSeen, "no line: not seen");
Check.Eq(p.Components.Count, 0, "no line: none");
Check.True(p.Complete && p.Usable, "still complete and usable");
p = FeedAll(new PressParser(), Press("Components selected: none", "Teeming - 75% more monsters")).Single();
Check.True(p.ComponentsSeen && p.Components.Count == 0, "'none'");
p = FeedAll(new PressParser(), Press("No components selected.", "Teeming - 75% more monsters")).Single();
Check.True(p.ComponentsSeen && p.Components.Count == 0, "'No components selected.'");
Check.Eq(p.ComponentsText, "no components", "shown as 'no components'");
}
private static void Incomplete()
{
// Timeout: the Level line never comes.
var parser = new PressParser();
string[] lines = Sample.Take(Sample.Length - 1).ToArray();
Check.Eq(FeedAll(parser, lines, 1000).Count, 0, "nothing finished yet");
Check.Null(parser.Tick(1000 + PressParser.TimeoutMs - 1), "not before the timeout");
// Other chat doesn't keep it open.
parser.Feed("Someone says, \"hello\"", 1000 + PressParser.TimeoutMs - 1);
Press? t = parser.Tick(1000 + PressParser.TimeoutMs);
Check.NotNull(t, "timed out");
if (t != null)
{
Check.False(t.Complete, "incomplete");
Check.Eq(t.End, "timeout", "reason");
Check.Eq(t.Modifiers.Count, 6, "what was gathered is kept");
Check.Null(t.ResultLevel, "no result level");
Check.False(t.Usable, "not used by the inference");
}
// The next press starts before this one's Level line.
parser = new PressParser();
var done = FeedAll(parser, Sample.Take(4).Concat(Sample));
Check.Eq(done.Count, 2, "two presses");
if (done.Count == 2)
{
Check.True(!done[0].Complete && done[0].End == "next use", "first: incomplete, next use");
Check.Eq(done[0].Outcome, "Pressed. It holds.", "first kept its outcome");
Check.True(done[1].Complete && done[1].Modifiers.Count == 6, "second complete");
}
// Some other "Using ..." line ends it and starts nothing.
parser = new PressParser();
done = FeedAll(parser, Sample.Take(3).Append("Using the Mana Stone on the Robe of Ages"));
Check.Eq(done.Count, 1, "ended by another Using line");
Check.False(parser.Busy, "no new press from an unrelated Using line");
Check.Eq(done.Count == 1 ? done[0].End : "", "next use", "reason");
// Logout.
parser = new PressParser();
FeedAll(parser, Sample.Take(2));
Press? f = parser.Flush("logout");
Check.True(f != null && f.End == "logout" && !f.Complete, "flush at logout");
Check.Null(parser.Flush("logout"), "nothing left to flush");
}
private static void UnknownLines()
{
var parser = new PressParser();
string[] junk =
{
"", " ", "\n\n", "Level 190, 4 entries.", "Pressed. It holds.", " Hardy - monsters have x1.81 health",
new string('x', 5000), "Components selected:", "The gem carries:", "☃ éè ???", "Using", "Using the",
"with the Fragment Press", "1234567890123456789012345678901234567890", " - just a dash", "x%+",
};
int finished = 0;
foreach (string j in junk)
finished += parser.Feed(j, 1000)?.Count ?? 0;
Check.Eq(finished, 0, "nothing comes out of junk while idle");
Check.False(parser.Busy, "still idle");
Check.Null(parser.Feed(null, 1000), "null text");
// Inside a press: junk goes to Extra, chat-like dash lines don't become modifiers, a failed outcome is kept.
var lines = new List<string>
{
"Using the Woven Shard (Level 12) with the Fragment Press",
"Pressed. It cracks.",
"The gem carries:",
"Bob says, \"Hardy - is that good?\"",
"[Trade] Alice - selling tapers",
"☃☃☃",
" Strange Sigil - something we've never seen, 3 times",
" not a modifier line",
new string('y', 2000),
"Level 12, 1 entry.",
};
List<Press> done = FeedAll(parser, lines);
Check.Eq(done.Count, 1, "one press");
if (done.Count != 1) return;
Press p = done[0];
Check.Eq(p.Fragment, "Woven Shard", "other fragment name");
Check.Eq(p.FragmentLevel, 12, "its level");
Check.Eq(p.Outcome, "Pressed. It cracks.", "a failed outcome is kept as said");
Check.False(p.Held, "not held");
Check.Eq(p.Modifiers.Count, 1, "only the real modifier line");
Check.Eq(p.Modifiers.Count == 1 ? p.Modifiers[0].Name : "", "Strange Sigil", "unknown modifier name kept");
Check.Eq(p.Entries, 1, "'1 entry' singular");
Check.True(p.Extra.Count >= 4, "unfitting lines kept in Extra");
Check.True(p.Extra.All(l => l.Length <= 400), "long lines cut");
// A fragment without a level, and a press that isn't the Fragment Press.
done = FeedAll(new PressParser(), new[] { "Using the Odd Shard with the Fragment Press", "Level 3, 0 entries." });
Check.True(done.Count == 1 && done[0].FragmentLevel == null && done[0].Fragment == "Odd Shard", "no level in the name");
Check.True(done.Count == 1 && done[0].Complete && !done[0].Usable, "complete, but no modifiers: not usable");
done = FeedAll(new PressParser(), new[] { "Using the Pyreal Ingot with the Forge", "Level 3, 0 entries." });
Check.Eq(done.Count, 0, "not a Press: ignored");
}
private static void NumberForms()
{
string Forms(string s) => string.Join(" ", PressParser.Numbers(s).Select(n => n.Kind + ":" + n.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)));
Check.Eq(Forms("kills drop x1.38 loot"), "mult:1.38", "multiplier");
Check.Eq(Forms("12% of kills"), "pct:12", "percent");
Check.Eq(Forms("+29 damage rating"), "plus:29", "rating");
Check.Eq(Forms("attacks with +29."), "plus:29", "rating before a full stop");
Check.Eq(Forms("-5 damage rating"), "plus:-5", "negative rating");
Check.Eq(Forms("+12% more"), "pct:12", "signed percent is a percent");
Check.Eq(Forms("spawns 3 bosses in 10.5 seconds"), "num:3 num:10.5", "plain numbers");
Check.Eq(Forms("max5 and box2"), "", "digits glued to words aren't numbers");
Check.Eq(Forms("no numbers here"), "", "none");
}
}

View file

@ -0,0 +1,51 @@
using System;
using System.IO;
using RynthCore.RynthAiTests.Harness;
// The engine parser's only outside dependency: the registry's limits (the engine's values).
namespace RynthCore.Engine.UI.ScriptWindows
{
internal static class ScriptWindowRegistry
{
public const int MaxOpsPerWindow = 1500;
public const int MaxBytesPerWindow = 64 * 1024;
public const int MaxWindowsPerOwner = 32;
public const int MaxBytesPerSubmit = 256 * 1024;
}
}
namespace RynthThreads.Tests
{
// Offline tests for RynthThreads. Each test prints PASS / FAIL.
//
// Run: dotnet run -c Release (all tests)
// dotnet run -c Release -- infer (tests whose name contains "infer")
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);
var runner = new Runner();
ParserTests.Register(runner);
InferenceTests.Register(runner);
StoreTests.Register(runner);
WindowTests.Register(runner);
int rc = runner.Run("RynthThreads tests", args.Length > 0 ? args[0] : null);
try { Directory.Delete(TempRoot, recursive: true); } catch { }
return rc;
}
/// <summary>A fresh empty folder under the scratch root.</summary>
public static string NewFolder(string name)
{
string path = Path.Combine(TempRoot, name + "-" + Guid.NewGuid().ToString("N").Substring(0, 6));
Directory.CreateDirectory(path);
return path;
}
}
}

View file

@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline tests for the RynthThreads plugin (DreamWeave Fragment Press results): the chat parser
(the real sample with an interleaved line, several / no components, incomplete presses, odd
text), the inference rules on made-up presses (a forced modifier at n = 3 but not n = 1, n = 2,
the 90% rule, base rates, several components in one press), the shared presses.jsonl (JSON
round trip, following the file's growth, two writers appending at once) and that the window's
display list is accepted by the engine's own parser (RynthCore
src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs, from the sibling checkout).
The plugin is a NativeAOT x86 library, so its sources are compiled in here. Files go to a
scratch folder next to the exe, never %LOCALAPPDATA%.
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>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>RynthThreads.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
<!-- The engine parser's whitelists use ImGui.NET's enums. -->
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthThreads\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthThreads\obj\**;..\..\Plugins\RynthCore.Plugin.RynthThreads\bin\**" Link="RynthThreads\%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
<!-- The RynthAi test tools' check/runner harness (no plugin code in it). -->
<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" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,181 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using RynthCore.Plugin.RynthThreads.Threads;
using RynthCore.RynthAiTests.Harness;
namespace RynthThreads.Tests;
// The shared presses.jsonl (Threads/PressStore.cs).
internal static class StoreTests
{
public static void Register(Runner r)
{
r.Add("store: a press survives the JSON round trip", RoundTrip);
r.Add("store: another client's presses are read as the file grows; no doubles", FollowsGrowth);
r.Add("store: odd lines are skipped, a half-written line waits", OddLines);
r.Add("store: two writers appending at once lose nothing", ConcurrentAppends);
r.Add("store: CSV export", CsvExport);
}
private static Press Sample() => new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0];
private static void RoundTrip()
{
Press p = Sample();
p.Server = "DreamWeave";
p.Character = "Tester \"Quote\"";
string json = PressStore.ToJson(p);
Check.False(json.Contains('\n'), "one line");
Press? back = PressStore.FromJson(json);
Check.NotNull(back, "reads back");
if (back == null) return;
ParserTests.CheckSample(back);
Check.Eq(back.Id, p.Id, "id");
Check.Eq(back.Character, "Tester \"Quote\"", "character (escaped quotes)");
Check.Eq(back.Server, "DreamWeave", "server");
Check.Eq(back.TimeUtc, p.TimeUtc, "time");
Check.Eq(back.Modifiers[3].Numbers[0].Text, "+29", "number text");
// Missing fields and unknown ones (a later version) are fine.
Press? minimal = PressStore.FromJson("{\"id\":\"x1\",\"future\":[1,2],\"modifiers\":[{\"name\":\"Hardy\"},{\"description\":\"no name\"}]}");
Check.True(minimal != null && minimal.Id == "x1" && minimal.Modifiers.Count == 1 && minimal.FragmentLevel == null,
"minimal line reads, nameless modifier dropped");
Check.Null(PressStore.FromJson("not json"), "garbage");
Check.Null(PressStore.FromJson("[1,2]"), "not an object");
}
private static void FollowsGrowth()
{
string folder = Program.NewFolder("growth");
var a = new PressStore(folder);
var b = new PressStore(folder);
Check.Eq(b.Poll(), 0, "no file yet");
Check.Null(a.Record(Sample()), "client A writes");
Check.Eq(a.Poll(), 0, "A reading its own press back adds nothing");
Check.Eq(a.Presses.Count, 1, "A has it once");
Check.Eq(b.Poll(), 1, "client B sees it");
Check.Eq(b.Poll(), 0, "and only once");
Press second = Sample();
second.Components = new List<string> { "Blue Taper" };
a.Record(second);
b.Record(Sample());
Check.Eq(b.Poll(), 1, "B gets A's second press (its own is already there)");
Check.Eq(a.Poll(), 1, "A gets B's press");
Check.Eq(a.Presses.Count, 3, "A: 3");
Check.Eq(b.Presses.Count, 3, "B: 3");
// A fresh client reads them all.
var c = new PressStore(folder);
Check.Eq(c.Poll(), 3, "a new client loads everything");
int v = c.Version;
c.Poll();
Check.Eq(c.Version, v, "nothing new: unchanged");
}
private static void OddLines()
{
string folder = Program.NewFolder("odd");
var s = new PressStore(folder);
Directory.CreateDirectory(folder);
string good = PressStore.ToJson(Sample());
File.WriteAllText(s.FilePath, good + "\n\nnot json at all\n{\"broken\":\n" + good.Substring(0, 20));
Check.Eq(s.Poll(), 1, "the good line");
Check.Eq(s.BadLines, 2, "two bad lines counted");
// The half line gets finished (with a different id: a new press).
Press other = Sample();
string rest = PressStore.ToJson(other);
File.WriteAllText(s.FilePath, good + "\n\nnot json at all\n{\"broken\":\n" + rest + "\n");
Check.Eq(s.Poll(), 1, "the finished line is read");
Check.Eq(s.Presses.Count, 2, "two presses");
}
private static void ConcurrentAppends()
{
string folder = Program.NewFolder("concurrent");
const int perWriter = 250;
var writers = new[] { new PressStore(folder), new PressStore(folder) };
var errors = new int[2];
using var stop = new CancellationTokenSource();
// A third party holding the file now and then, as another client mid-write would.
var holder = new Thread(() =>
{
while (!stop.IsCancellationRequested)
{
try
{
using var fs = new FileStream(Path.Combine(folder, PressStore.FileName), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
Thread.Sleep(3);
}
catch (IOException) { }
Thread.Sleep(2);
}
});
holder.Start();
var threads = Enumerable.Range(0, 2).Select(w => new Thread(() =>
{
for (int i = 0; i < perWriter; i++)
{
Press p = Sample();
p.Character = "Writer" + w;
p.Components = new List<string> { "C" + i };
if (writers[w].Record(p) != null) errors[w]++;
}
})).ToList();
threads.ForEach(t => t.Start());
threads.ForEach(t => t.Join());
stop.Cancel();
holder.Join();
// Whatever found the file busy every time is written now.
foreach (PressStore w in writers)
for (int i = 0; i < 50 && w.FlushPending() > 0; i++) Thread.Sleep(10);
Check.Eq(writers[0].PendingCount + writers[1].PendingCount, 0, "nothing left pending");
string[] lines = File.ReadAllLines(Path.Combine(folder, PressStore.FileName), Encoding.UTF8)
.Where(l => l.Length > 0).ToArray();
Check.Eq(lines.Length, 2 * perWriter, "every press is one line");
List<Press?> read = lines.Select(PressStore.FromJson).ToList();
Check.True(read.All(p => p != null && p.Modifiers.Count == 6), "every line is a whole press");
Check.Eq(read.Select(p => p!.Id).Distinct().Count(), 2 * perWriter, "all ids distinct");
Check.Eq(read.Count(p => p!.Character == "Writer0"), perWriter, "writer 0's presses all there");
Check.Eq(read.Count(p => p!.Character == "Writer1"), perWriter, "writer 1's presses all there");
var reader = new PressStore(folder);
Check.Eq(reader.Poll(), 2 * perWriter, "a reader loads them all");
Check.Eq(reader.BadLines, 0, "no bad lines");
Console.WriteLine($" (appends that found the file busy every try and waited: {errors[0] + errors[1]})");
}
private static void CsvExport()
{
string folder = Program.NewFolder("csv");
var s = new PressStore(folder);
Press p = Sample();
p.Character = "Tester, Jr.";
s.Record(p);
Press q = Sample();
q.Components = new List<string> { "=cmd", "Red Taper" };
q.Complete = false;
q.End = "timeout";
s.Record(q);
string path = s.ExportCsv(new DateTime(2026, 10, 12, 19, 30, 0));
Check.True(File.Exists(path) && Path.GetDirectoryName(path) == folder, "written next to presses.jsonl");
Check.Eq(Path.GetFileName(path), "presses-20261012-193000.csv", "file name");
string[] rows = File.ReadAllLines(path);
Check.Eq(rows.Length, 3, "header + 2 rows");
Check.True(rows[0].StartsWith("time_utc,server,character,fragment,fragment_level"), "header");
Check.True(rows[1].Contains("\"Tester, Jr.\""), "comma value quoted");
Check.True(rows[1].Contains(",Raw Fragment,185,Pressed. It holds.,Red Taper,190,4,yes,6,"), "columns");
Check.True(rows[1].Contains("Bounteous: kills drop x1.38 loot | Tourmaline Affinity"), "modifiers joined");
Check.True(rows[2].Contains("'=cmd; Red Taper"), "a formula-looking cell is defused");
Check.True(rows[2].Contains("no (timeout)"), "incomplete marked");
}
}

View file

@ -0,0 +1,186 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using RynthCore.Engine.UI.ScriptWindows;
using RynthCore.Plugin.RynthThreads;
using RynthCore.Plugin.RynthThreads.Threads;
using RynthCore.Plugin.RynthThreads.Ui;
using RynthCore.Plugin.RynthThreads.Views;
using RynthCore.RynthAiTests.Harness;
namespace RynthThreads.Tests;
// The window's display list against the engine's own parser, the server check and /rthreads stats.
internal static class WindowTests
{
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Write")]
private static extern int Write(UiHost h);
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_submit")]
private static extern ref byte[] SubmitBuffer(UiHost h);
public static void Register(Runner r)
{
r.Add("window: every tab, headers open, parses in the engine (bar button set)", EveryTab);
r.Add("window: DreamWeave check and /rthreads stats lines", ServerAndStats);
r.Add("window: Components and Modifiers tab text for the 4 real presses", RealText);
}
private static List<Press> Data()
{
var presses = new List<Press>();
for (int i = 0; i < 3; i++) presses.Add(InferenceTests.P("Red Taper", "Bounteous=kills drop x1.38 loot, Hardy=monsters have x1.5 health", level: 185));
for (int i = 0; i < 4; i++) presses.Add(InferenceTests.P("", "Hardy=monsters have x1.81 health, Teeming=75% more monsters", level: 185));
presses.Add(InferenceTests.P("Blue Taper, Red Taper", "Bounteous=kills drop x1.4 loot", level: 120));
Press raw = new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0];
presses.Add(raw);
presses.Add(InferenceTests.P("Red Taper", "Hardy", complete: false));
return presses;
}
private static unsafe void EveryTab()
{
List<Press> presses = Data();
ThreadsReport report = PressInference.Build(presses);
var panel = new ThreadsPanel { Report = () => report, Presses = () => presses };
var host = new UiHost();
UiWindow w = host.Add(new UiWindow("RynthThreads/Main", "RynthThreads") { DefaultWidth = 440f, DefaultHeight = 480f, MinWidth = 320f, MinHeight = 220f });
void Pass()
{
w.Begin();
panel.Draw(w);
w.End();
}
void OpenAll(IEnumerable<string> ids)
{
foreach (string id in ids) w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvOpen, b: true));
}
void Click(string id) => w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvClicked));
string[] tabs = { "tab.c", "tab.m", "tab.p" };
foreach (string tab in tabs)
{
Pass();
Click(tab);
Pass();
OpenAll(report.Components.Select(c => "c:" + c.Name).Append("c:(none)").Append("c:(all)")
.Concat(report.Combinations.Select(c => "k:" + c.Name))
.Concat(report.Modifiers.Select(m => "m:" + m.Name))
.Concat(presses.Select(p => "p:" + p.Id)));
Pass();
int n = Write(host);
byte[] buf = SubmitBuffer(host);
int rc;
List<ParsedWindow> windows;
string error;
fixed (byte* p = buf) rc = DisplayListParser.Parse(p, n, 4000f, out _, out windows, out error);
Check.Eq(rc, 0, $"{tab}: the engine accepts the list ({error})");
if (rc != 0 || windows.Count != 1) continue;
Check.Eq(windows[0].Title, "RynthThreads", "title (the bar button's tooltip)");
Check.True((windows[0].Flags & WindowFlags.ShowInBar) != 0 && (windows[0].Flags & WindowFlags.BarButton) != 0, "bar button");
Check.True(windows[0].List!.OpCount > 20, $"{tab}: something drawn ({windows[0].List!.OpCount} ops)");
}
string body = System.Text.Encoding.UTF8.GetString(w.Body);
Check.True(body.Contains("Level 190, 4 entries."), "presses tab shows raw lines");
Check.True(body.Contains("Yorick is recalling"), "and the other lines kept beside them");
// Empty data still draws.
var empty = new ThreadsPanel();
w.Begin();
empty.Draw(w);
w.End();
Check.True(System.Text.Encoding.UTF8.GetString(w.Body).Contains("No presses yet"), "empty window explains itself");
}
private static void ServerAndStats()
{
Check.True(RynthThreadsPlugin.IsDreamWeave("DreamWeave"), "DreamWeave");
Check.True(RynthThreadsPlugin.IsDreamWeave("dreamweave PvE"), "any case, extra words");
Check.False(RynthThreadsPlugin.IsDreamWeave("Aelrynth"), "Aelrynth");
Check.False(RynthThreadsPlugin.IsDreamWeave(""), "empty");
Check.False(RynthThreadsPlugin.IsDreamWeave(null), "null");
List<string> lines = RynthThreadsPlugin.StatsLines(PressInference.Build(Data()), @"C:\x\presses.jsonl");
Check.True(lines[0].StartsWith("10 presses (9 complete, 1 incomplete)"), "totals line: " + lines[0]);
Check.True(lines.Any(l => l.StartsWith("Red Taper (5): Bounteous 100%+, Hardy 80%")), "Red Taper line");
Check.True(lines.Any(l => l == "Blue Taper (1): Bounteous 100%"), "Blue Taper line");
Check.True(lines.Any(l => l.StartsWith("No components (4): Hardy 100%")), "No components line");
Check.False(lines.Any(l => l.Contains("Affinity")), "the Affinity group is left out");
Check.True(lines.Contains("+ = more likely with it than without."), "legend");
Check.Eq(lines[^1], @"File: C:\x\presses.jsonl", "file named last");
Check.True(lines.Count <= 9, "short");
}
/// <summary>The window's text ops in order (headers as "== label", indented by Indent ops).</summary>
internal static List<string> TextOf(ReadOnlySpan<byte> b)
{
var lines = new List<string>();
int i = 0, indent = 0;
string Str(ReadOnlySpan<byte> s, int at) =>
System.Text.Encoding.UTF8.GetString(s.Slice(at + 2, s[at] | (s[at + 1] << 8)));
while (i + 4 <= b.Length)
{
byte code = b[i], flags = b[i + 1];
int len = b[i + 2] | (b[i + 3] << 8), at = i + 4;
if (code == UiFormat.OpEnd && len == 0) break;
string pad = new string(' ', indent * 2);
switch (code)
{
case UiFormat.OpText: case UiFormat.OpTextWrapped: case UiFormat.OpTextDisabled: case UiFormat.OpSeparatorText:
lines.Add(pad + Str(b, at)); break;
case UiFormat.OpBulletText: lines.Add(pad + "- " + Str(b, at)); break;
case UiFormat.OpTextColored: lines.Add(pad + Str(b, at + 4)); break;
case UiFormat.OpCollapsingHeader:
string h = Str(b, at + 4);
int cut = h.IndexOf("###", StringComparison.Ordinal);
lines.Add(pad + "== " + (cut >= 0 ? h.Substring(0, cut) : h)); break;
case UiFormat.OpIndent: indent++; break;
case UiFormat.OpUnindent: indent = Math.Max(0, indent - 1); break;
}
i = at + len + ((flags & UiFormat.OpHasBlock) != 0 ? 4 : 0);
}
return lines;
}
private static void RealText()
{
List<Press> presses = InferenceTests.Real();
ThreadsReport report = PressInference.Build(presses);
var panel = new ThreadsPanel { Report = () => report, Presses = () => presses };
var w = new UiWindow("RynthThreads/Main", "RynthThreads");
void Pass() { w.Begin(); panel.Draw(w); w.End(); }
void Open(string id) => w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvOpen, b: true));
Pass();
Open("c:(all)");
Open("c:Lead Scarab");
Pass();
List<string> comp = TextOf(w.Body);
Check.True(comp.Contains("== Lead Scarab (4 presses)"), "Lead Scarab header");
Check.True(comp.Any(l => l.Trim() == "- Guarded 75% (3/4, 30-95%); without: no data; x1.83 to x2.18"), "Guarded line");
Check.True(comp.Any(l => l.Trim() == "- Affinity (any) 100% (4/4, 51-100%); without: no data; 7% to 22%"), "Affinity line");
Check.True(comp.Any(l => l.Trim() == "Amethyst 1, Iron 1, Obsidian 1, Serpentine 1"), "split line");
Check.True(comp.Any(l => l.Trim() == "- Guarded 75% (3/4, 30-95%); x1.83 to x2.18"), "All presses: no comparison");
w.Dispatch(w.KeyOf("tab.m"), new UiEvent(UiFormat.EvClicked));
Pass();
Open("m:Affinity");
Open("m:Guarded");
Pass();
List<string> mods = TextOf(w.Body);
Check.True(mods.Contains("== Guarded 75% (3/4, 30-95%) [harder]") || mods.Contains("== Guarded 75% (3/4, 30-95%)"), "Guarded header");
Check.True(mods.Any(l => l.Trim() == "- Lead Scarab 75% (3/4, 30-95%); without: no data; x1.83 to x2.18"), "Guarded with Lead Scarab");
Check.True(mods.Any(l => l.Trim() == "- Amethyst: 25% (1/4, 5-70%)"), "Affinity by material");
if (Environment.GetEnvironmentVariable("RYNTHTHREADS_DUMP") == "1")
{
Console.WriteLine("---- Components tab ----");
foreach (string l in comp) Console.WriteLine(l);
Console.WriteLine("---- Modifiers tab ----");
foreach (string l in mods) Console.WriteLine(l);
}
}
}