diff --git a/CLAUDE.md b/CLAUDE.md
index 48cb46e..8794607 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -31,6 +31,9 @@ Datra/
│ ├── Models/ # DataModelInfo, PropertyInfo 등
│ └── DataContextSourceGenerator.cs # 메인 진입점 (ISourceGenerator)
│
+├── Datra.Lab/ # 밸런스 실험실 코어 (UI 없음): 손잡이 스키마, 갈래 컨텍스트, 시뮬레이터 계약, 봇 실행기
+├── Datra.Lab.Sample/ # 실험실용 장난감 게임 데이터 + 시뮬레이터 (웹 샘플·테스트 공용)
+├── Datra.Lab.Tests/ # 실험실 코어 테스트
├── Datra.Analyzers/ # Roslyn Analyzer
├── Datra.SampleData/ # 테스트용 샘플 데이터 모델
├── Datra.SampleData2/ # 멀티 컨텍스트 테스트용
diff --git a/Datra.Lab.Sample/Datra.Lab.Sample.csproj b/Datra.Lab.Sample/Datra.Lab.Sample.csproj
new file mode 100644
index 0000000..e01f0e8
--- /dev/null
+++ b/Datra.Lab.Sample/Datra.Lab.Sample.csproj
@@ -0,0 +1,31 @@
+
+
+
+ netstandard2.1
+ latest
+ enable
+ Datra.Lab.Sample
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Datra.Lab.Sample/DatraConfiguration.cs b/Datra.Lab.Sample/DatraConfiguration.cs
new file mode 100644
index 0000000..85748ed
--- /dev/null
+++ b/Datra.Lab.Sample/DatraConfiguration.cs
@@ -0,0 +1,7 @@
+using Datra.Attributes;
+
+[assembly: DatraConfiguration("Descent",
+ Namespace = "Datra.Lab.Sample.Generated",
+ EnableLocalization = false,
+ EmitPhysicalFiles = false
+)]
diff --git a/Datra.Lab.Sample/DescentData.cs b/Datra.Lab.Sample/DescentData.cs
new file mode 100644
index 0000000..02a02f9
--- /dev/null
+++ b/Datra.Lab.Sample/DescentData.cs
@@ -0,0 +1,71 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using Datra.Lab.Sample.Generated;
+using Datra.Lab.Sample.Models;
+
+namespace Datra.Lab.Sample
+{
+ ///
+ /// The toy game's data files (embedded in this assembly) and the few helpers that read
+ /// the loaded tables the way a game's own code would.
+ ///
+ public static class DescentData
+ {
+ private const string Prefix = "Descent/";
+
+ /// File name → YAML text, as shipped.
+ public static IReadOnlyDictionary Files()
+ {
+ var assembly = typeof(DescentData).GetTypeInfo().Assembly;
+ var files = new Dictionary(StringComparer.Ordinal);
+ foreach (var name in assembly.GetManifestResourceNames().Where(n => n.StartsWith(Prefix, StringComparison.Ordinal)))
+ {
+ using var stream = assembly.GetManifestResourceStream(name)!;
+ using var reader = new StreamReader(stream);
+ files[name.Substring(Prefix.Length)] = reader.ReadToEnd();
+ }
+ return files;
+ }
+
+ /// Write the data files into so a file provider can serve them.
+ public static string WriteTo(string directory)
+ {
+ Directory.CreateDirectory(directory);
+ foreach (var file in Files())
+ File.WriteAllText(Path.Combine(directory, file.Key), file.Value);
+ return directory;
+ }
+
+ /// Floors top to bottom, in file order.
+ public static IReadOnlyList FloorsInOrder(DescentContext data) =>
+ data.Floor.LoadedItems.Values.ToList();
+
+ /// The factor each floor's value multiplier grows by, on average.
+ public static double ValueGrowth(DescentContext data)
+ {
+ var floors = FloorsInOrder(data);
+ if (floors.Count < 2 || floors[0].ValueMultiplier <= 0) return 1;
+ return Math.Pow(floors[floors.Count - 1].ValueMultiplier / floors[0].ValueMultiplier, 1.0 / (floors.Count - 1));
+ }
+
+ ///
+ /// Re-slope the value multipliers to grow by per floor. Each
+ /// floor keeps its hand-tuned distance from the curve: only the slope changes.
+ ///
+ public static void SetValueGrowth(DescentContext data, double growth)
+ {
+ var current = ValueGrowth(data);
+ if (current <= 0 || growth <= 0) return;
+ var floors = FloorsInOrder(data);
+ for (var i = 0; i < floors.Count; i++)
+ {
+ var value = (float)(floors[i].ValueMultiplier * Math.Pow(growth / current, i));
+ ForkedData.Set(floors[i], f => f.ValueMultiplier, value);
+ }
+ }
+ }
+}
diff --git a/Datra.Lab.Sample/DescentLab.cs b/Datra.Lab.Sample/DescentLab.cs
new file mode 100644
index 0000000..6c18e66
--- /dev/null
+++ b/Datra.Lab.Sample/DescentLab.cs
@@ -0,0 +1,37 @@
+#nullable enable
+using Datra.Lab.Sample.Generated;
+
+namespace Datra.Lab.Sample
+{
+ /// The toy game's lab setup, shared by the web sample and the tests.
+ public static class DescentLab
+ {
+ ///
+ /// Policies, the policy parameter, the curve knob, the checks: everything the game adds
+ /// on top of its [Knob] attributes and its simulator.
+ ///
+ public static void Configure(LabOptions lab)
+ {
+ lab.Title = "Descent · balance lab";
+ lab.Bots = 40;
+
+ lab.Policy(DescentSim.Efficient, "Efficient", "Buys what gets it down soonest, saves otherwise");
+ lab.Policy(DescentSim.Cheap, "Cheapest first", "Buys whatever it can afford");
+ lab.Policy(DescentSim.RandomPick, "Random", "Picks among the upgrades that pay back");
+ lab.PolicyParam("shopSeconds", "Time between runs", @default: 8, min: 2, max: 30, step: 1, unit: "s");
+
+ // One knob over a whole column: an attribute cannot say "re-slope these five rows".
+ lab.Knobs(knobs => knobs.Add(
+ "Depth value growth",
+ read: DescentData.ValueGrowth,
+ write: DescentData.SetValueGrowth,
+ min: 1.4, max: 3, step: 0.05,
+ group: "Floors", unit: "×/floor",
+ hint: "How much more each floor pays than the one above",
+ id: "Floors.ValueGrowth"));
+
+ lab.Check("First purchase", bot => bot.FirstPurchaseSeconds, "<= 60", unit: "s");
+ lab.Check("Longest run", bot => bot.LongestTickSeconds("run"), "<= 90", unit: "s");
+ }
+ }
+}
diff --git a/Datra.Lab.Sample/DescentPhysics.cs b/Datra.Lab.Sample/DescentPhysics.cs
new file mode 100644
index 0000000..f630f16
--- /dev/null
+++ b/Datra.Lab.Sample/DescentPhysics.cs
@@ -0,0 +1,102 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Datra.Lab.Sample.Generated;
+using Datra.Lab.Sample.Models;
+
+namespace Datra.Lab.Sample
+{
+ /// What happened to one bottle on the stairs: the unit the physics cache stores.
+ public sealed class BottleOutcome
+ {
+ /// Steps the bottle survived.
+ public int Steps { get; set; }
+
+ /// It reached the bottom in one piece.
+ public bool Intact { get; set; }
+
+ /// It came to rest on the landing.
+ public bool StoppedOnLanding { get; set; }
+
+ /// How long the bottle was in play.
+ public double Seconds { get; set; }
+ }
+
+ ///
+ /// Stands in for a game's headless physics batch. A real game runs its engine overnight and
+ /// stores the outcomes; this fills the same kind of pools from a few lines of arithmetic so
+ /// the sample has something to draw from.
+ ///
+ public static class DescentPhysics
+ {
+ public const string Version = "toy-1";
+ public const int SamplesPerKey = 64;
+
+ /// The physics state a bottle is rolled in. Only inputs that change the outcome belong here.
+ public static PhysicsKey Key(string floor, int push, int wrap) =>
+ PhysicsKey.Of(("floor", floor), ("push", push), ("wrap", wrap));
+
+ /// Roll every state a bot can pass through and keep the outcomes.
+ public static InMemoryOutcomes Bake(DescentContext data)
+ {
+ var outcomes = new InMemoryOutcomes(Version);
+ var economy = data.Economy.Current ?? new EconomyData();
+ var upgrades = data.Upgrade.LoadedItems;
+ var push = upgrades["push"];
+ var wrap = upgrades["wrap"];
+ var floors = DescentData.FloorsInOrder(data);
+
+ for (var f = 0; f < floors.Count; f++)
+ {
+ for (var p = 0; p <= push.MaxLevel; p++)
+ {
+ for (var w = 0; w <= wrap.MaxLevel; w++)
+ {
+ // One fixed seed per state: baking twice gives the same pools.
+ var random = new SimRandom(1_000_003L * (f + 1) + 1_009L * p + w);
+ var pool = Enumerable.Range(0, SamplesPerKey)
+ .Select(_ => Roll(floors[f], p * push.Amount, w * wrap.Amount, economy.GlassToughness, random))
+ .ToList();
+ outcomes.Add(Key(floors[f].Id, p, w), pool);
+ }
+ }
+ }
+ return outcomes;
+ }
+
+ private static BottleOutcome Roll(FloorData floor, double reach, double padding, double toughness, SimRandom random)
+ {
+ // Each step is a chance to break. Pushing harder carries the bottle further before
+ // it slows down; wrap and tougher glass make every step kinder.
+ var breakChance = 0.20 / (toughness * (1 + padding));
+ var carry = 3.0 + reach * 4.0;
+ var steps = 0;
+ var stopped = false;
+
+ while (steps < floor.Steps)
+ {
+ if (random.Chance(breakChance)) break;
+ steps++;
+ if (steps == floor.LandingStep && random.Chance(0.55))
+ {
+ stopped = true;
+ break;
+ }
+ if (steps > carry && random.Chance(0.28))
+ {
+ stopped = true;
+ break;
+ }
+ }
+
+ return new BottleOutcome
+ {
+ Steps = steps,
+ Intact = steps >= floor.Steps,
+ StoppedOnLanding = stopped && steps == floor.LandingStep && floor.LandingStep > 0,
+ Seconds = 3.0 + steps * 0.8,
+ };
+ }
+ }
+}
diff --git a/Datra.Lab.Sample/DescentSim.cs b/Datra.Lab.Sample/DescentSim.cs
new file mode 100644
index 0000000..d510e1c
--- /dev/null
+++ b/Datra.Lab.Sample/DescentSim.cs
@@ -0,0 +1,180 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Datra.Lab.Sample.Generated;
+using Datra.Lab.Sample.Models;
+
+namespace Datra.Lab.Sample
+{
+ ///
+ /// One bot playing the toy game from the top floor to the platform.
+ ///
+ ///
+ /// The rules a balance tool has to get right are all here in a few lines:
+ ///
+ /// - The fare box is the wallet. Buying an upgrade takes coins out of the box, so every
+ /// purchase pushes the shutter back down.
+ /// - When the box holds the fare the shutter opens and the bot goes down. Whatever is
+ /// in the box stays there: every floor starts with an empty box.
+ /// - Account upgrades come along. Floor devices stay on the floor they were bought on.
+ ///
+ /// A real game would call its own earnings and shop code instead of the small
+ /// Earn and Cost methods below.
+ ///
+ public sealed class DescentSim : ISimulator
+ {
+ public const string Efficient = "efficient";
+ public const string Cheap = "cheap";
+ public const string RandomPick = "random";
+
+ public void Play(DescentContext data, SimRun run)
+ {
+ var economy = data.Economy.Current ?? new EconomyData();
+ var upgrades = data.Upgrade.LoadedItems.Values.ToList();
+ var floors = DescentData.FloorsInOrder(data);
+ var shopSeconds = run.Param("shopSeconds", 8);
+
+ var account = upgrades.Where(u => u.Scope == UpgradeScope.Account).ToDictionary(u => u.Id, _ => 0);
+ var markedIntact = false;
+
+ for (var f = 0; f < floors.Count && !run.OutOfTime; f++)
+ {
+ var floor = floors[f];
+ run.Stage(floor.Id, targetSeconds: floor.TargetMinutes * 60, label: floor.Id + " " + floor.Name);
+
+ // A new floor: an empty fare box and no devices installed yet.
+ var wallet = 0.0;
+ var devices = upgrades.Where(u => u.Scope == UpgradeScope.Floor).ToDictionary(u => u.Id, _ => 0);
+ int Level(UpgradeData u) => u.Scope == UpgradeScope.Account ? account[u.Id] : devices[u.Id];
+
+ double earnedHere = 0, playedHere = 0;
+ int bottlesHere = 0, landedHere = 0;
+
+ while (!run.OutOfTime)
+ {
+ // One run: every bottle in the line gets one stored physics outcome.
+ var key = DescentPhysics.Key(floor.Id, account["push"], account["wrap"]);
+ var bottles = economy.BottlesPerRun + account["queue"];
+ double earned = 0, seconds = 0;
+ for (var b = 0; b < bottles; b++)
+ {
+ var outcome = run.Outcome(key);
+ earned += Earn(economy, floor, outcome, devices, upgrades);
+ seconds += outcome.Seconds;
+ bottlesHere++;
+ if (outcome.StoppedOnLanding) landedHere++;
+ if (outcome.Intact && !markedIntact)
+ {
+ markedIntact = true;
+ run.Mark("first intact bottle");
+ }
+ }
+
+ wallet += earned;
+ earnedHere += earned;
+ playedHere += seconds + shopSeconds;
+ run.Tick(seconds, earned);
+ run.Progress(wallet / floor.Fare);
+
+ // The shutter opens as soon as the box holds the fare. The coins stay behind.
+ if (wallet >= floor.Fare) break;
+
+ run.Tick(shopSeconds, 0, "shop");
+ var rate = earnedHere / playedHere;
+ while (Pick(run, upgrades, Level, floor, floors, f, wallet, rate) is { } choice)
+ {
+ var cost = Cost(choice, Level(choice), floor);
+ wallet -= cost;
+ if (choice.Scope == UpgradeScope.Account) account[choice.Id]++;
+ else devices[choice.Id]++;
+ run.Purchase(choice.Id, cost,
+ group: choice.Scope == UpgradeScope.Account ? "Account" : "Floor device",
+ label: choice.Name + " Lv" + Level(choice));
+ run.Progress(wallet / floor.Fare);
+ }
+ }
+
+ if (bottlesHere > 0 && landedHere > bottlesHere * 0.25)
+ {
+ run.Explain(floor.Id, "More than a quarter of the bottles stop on the landing, which cuts their step count short.");
+ }
+ }
+ }
+
+ /// The game's pricing rule: what one bottle's outcome is worth.
+ public static double Earn(
+ EconomyData economy, FloorData floor, BottleOutcome outcome,
+ IReadOnlyDictionary devices, IReadOnlyList upgrades)
+ {
+ var carpet = upgrades.First(u => u.Id == "carpet");
+ var box = upgrades.First(u => u.Id == "box");
+ var steps = outcome.Steps * economy.StepValue * (1 + carpet.Amount * devices["carpet"]);
+ var bonus = outcome.Intact ? economy.IntactBonus * (1 + box.Amount * devices["box"]) : 0;
+ return (steps + bonus) * floor.ValueMultiplier;
+ }
+
+ /// The game's price rule. Floor devices cost more the deeper the floor.
+ public static double Cost(UpgradeData upgrade, int level, FloorData floor)
+ {
+ var price = upgrade.BaseCost * Math.Pow(upgrade.CostGrowth, level);
+ if (upgrade.Scope == UpgradeScope.Floor) price *= floor.ValueMultiplier;
+ return Math.Round(price);
+ }
+
+ /// What the bot buys next, or null when it would rather save for the fare.
+ private static UpgradeData? Pick(
+ SimRun run, List upgrades, Func level,
+ FloorData floor, IReadOnlyList floors, int floorIndex, double wallet, double rate)
+ {
+ var affordable = upgrades
+ .Where(u => level(u) < u.MaxLevel && Cost(u, level(u), floor) <= wallet)
+ .ToList();
+ if (affordable.Count == 0) return null;
+
+ switch (run.Policy)
+ {
+ case Cheap:
+ // Buys whatever is cheapest as soon as it can. Finite: levels run out.
+ return affordable.OrderBy(u => Cost(u, level(u), floor)).First();
+
+ case RandomPick:
+ {
+ var worth = affordable.Where(u => PaysBack(u, level(u), floor, floors, floorIndex, wallet, rate)).ToList();
+ return worth.Count > 0 && run.Random.Chance(0.6) ? run.Random.Pick(worth) : null;
+ }
+
+ default:
+ // Most extra earnings per coin, among the upgrades that get the bot down sooner.
+ return affordable
+ .Where(u => PaysBack(u, level(u), floor, floors, floorIndex, wallet, rate))
+ .OrderByDescending(u => u.Amount / Cost(u, level(u), floor))
+ .FirstOrDefault();
+ }
+ }
+
+ ///
+ /// Spending sets the fare box back. It is worth it when the faster earning makes up the
+ /// cost before the coins would have been needed: on this floor for a device, over the
+ /// rest of the game for an account upgrade.
+ ///
+ private static bool PaysBack(
+ UpgradeData upgrade, int level, FloorData floor, IReadOnlyList floors, int floorIndex,
+ double wallet, double rate)
+ {
+ if (rate <= 0) return false;
+ var cost = Cost(upgrade, level, floor);
+ var toGo = floor.Fare - wallet;
+ if (upgrade.Scope == UpgradeScope.Account)
+ {
+ // Later floors pay more per second, so their fares take less time than the coins suggest.
+ for (var i = floorIndex + 1; i < floors.Count; i++)
+ toGo += floors[i].Fare * floor.ValueMultiplier / floors[i].ValueMultiplier;
+ }
+
+ var without = toGo / rate;
+ var with = (toGo + cost) / (rate * (1 + upgrade.Amount));
+ return with < without;
+ }
+ }
+}
diff --git a/Datra.Lab.Sample/Models/EconomyData.cs b/Datra.Lab.Sample/Models/EconomyData.cs
new file mode 100644
index 0000000..bb8d57e
--- /dev/null
+++ b/Datra.Lab.Sample/Models/EconomyData.cs
@@ -0,0 +1,24 @@
+using Datra.Attributes;
+
+namespace Datra.Lab.Sample.Models
+{
+ /// The pricing rules of the toy game.
+ [SingleData("Economy.yaml", Format = DataFormat.Yaml)]
+ public partial class EconomyData
+ {
+ /// Coins for every step a bottle survives.
+ [Knob("Step value", Group = "Rewards", Unit = "coins/step", Min = 1, Max = 15, Step = 0.5)]
+ public float StepValue { get; set; } = 5f;
+
+ /// Coins for a bottle that reaches the bottom in one piece.
+ [Knob("Intact bonus", Group = "Rewards", Unit = "coins", Min = 0, Max = 200, Step = 5)]
+ public float IntactBonus { get; set; } = 40f;
+
+ /// Bottles in the line at the start of the game.
+ public int BottlesPerRun { get; set; } = 3;
+
+ /// How easily glass breaks. Decides the stored outcomes, so it is a physics knob.
+ [Knob("Glass toughness", Group = "Rewards", Unit = "×", Min = 0.5, Max = 2, Step = 0.05, Layer = KnobLayer.Physics)]
+ public float GlassToughness { get; set; } = 1f;
+ }
+}
diff --git a/Datra.Lab.Sample/Models/FloorData.cs b/Datra.Lab.Sample/Models/FloorData.cs
new file mode 100644
index 0000000..07f70f4
--- /dev/null
+++ b/Datra.Lab.Sample/Models/FloorData.cs
@@ -0,0 +1,33 @@
+using Datra.Attributes;
+using Datra.Interfaces;
+
+namespace Datra.Lab.Sample.Models
+{
+ ///
+ /// One floor of the toy game. The player fills the fare box to open the shutter and go down.
+ ///
+ [TableData("Floors.yaml", Format = DataFormat.Yaml)]
+ public partial class FloorData : ITableData
+ {
+ public string Id { get; set; } = string.Empty;
+
+ public string Name { get; set; } = string.Empty;
+
+ /// Coins the fare box must hold before the shutter opens.
+ [Knob("Fare", Group = "Floors", Unit = "coins", EachRow = true,
+ Hint = "Coins the fare box must hold before the shutter opens")]
+ public int Fare { get; set; }
+
+ /// Everything earned on this floor is multiplied by this.
+ public float ValueMultiplier { get; set; } = 1f;
+
+ /// How long the floor is meant to take.
+ public float TargetMinutes { get; set; }
+
+ /// Number of steps on the staircase.
+ public int Steps { get; set; }
+
+ /// The step that is a landing, where bottles tend to stop. Zero for none.
+ public int LandingStep { get; set; }
+ }
+}
diff --git a/Datra.Lab.Sample/Models/UpgradeData.cs b/Datra.Lab.Sample/Models/UpgradeData.cs
new file mode 100644
index 0000000..ca50225
--- /dev/null
+++ b/Datra.Lab.Sample/Models/UpgradeData.cs
@@ -0,0 +1,45 @@
+using Datra.Attributes;
+using Datra.Interfaces;
+
+namespace Datra.Lab.Sample.Models
+{
+ public enum UpgradeScope
+ {
+ /// Kept for the whole game.
+ Account,
+
+ /// A device installed on one floor: bought again on every floor.
+ Floor
+ }
+
+ /// Something the bot can buy with coins from the fare box.
+ [TableData("Upgrades.yaml", Format = DataFormat.Yaml)]
+ public partial class UpgradeData : ITableData
+ {
+ public string Id { get; set; } = string.Empty;
+
+ public string Name { get; set; } = string.Empty;
+
+ public UpgradeScope Scope { get; set; }
+
+ /// Price of the first level.
+ [Knob("Upgrade prices", Group = "Upgrades", Unit = "×", Min = 0.25, Max = 3, Step = 0.05, Apply = KnobApply.Scale,
+ Hint = "Multiplies the first-level price of every upgrade")]
+ public float BaseCost { get; set; }
+
+ /// Each level costs this many times the one before.
+ public float CostGrowth { get; set; } = 1.5f;
+
+ public int MaxLevel { get; set; } = 5;
+
+ ///
+ /// Gain per level, as a fraction. For the economy upgrades this is the rule the game
+ /// applies; for the physics ones it is only what the bot expects when it shops.
+ ///
+ [Knob("Carpet value per level", Group = "Upgrades", Unit = "×/level", Min = 0, Max = 1, Step = 0.01, Row = "carpet",
+ Hint = "Extra step value per carpet level, on the floor it is laid on")]
+ [Knob("Push: steps per level", Group = "Upgrades", Unit = "steps/level", Min = 0, Max = 1, Step = 0.01, Row = "push",
+ Layer = KnobLayer.Physics, Hint = "How much further a harder push carries a bottle")]
+ public float Amount { get; set; }
+ }
+}
diff --git a/Datra.Lab.Sample/Resources/Economy.yaml b/Datra.Lab.Sample/Resources/Economy.yaml
new file mode 100644
index 0000000..37c2200
--- /dev/null
+++ b/Datra.Lab.Sample/Resources/Economy.yaml
@@ -0,0 +1,5 @@
+# Pricing rules of the toy game.
+StepValue: 5
+IntactBonus: 40
+BottlesPerRun: 3
+GlassToughness: 1
diff --git a/Datra.Lab.Sample/Resources/Floors.yaml b/Datra.Lab.Sample/Resources/Floors.yaml
new file mode 100644
index 0000000..5fab42a
--- /dev/null
+++ b/Datra.Lab.Sample/Resources/Floors.yaml
@@ -0,0 +1,41 @@
+# Floors of the toy game the lab sample tunes. Fill the fare box to go down one floor.
+- Id: B1
+ Name: Ticket hall
+ Fare: 280
+ ValueMultiplier: 1
+ TargetMinutes: 4
+ Steps: 8
+ LandingStep: 0
+
+- Id: B2
+ Name: Concourse
+ Fare: 600
+ ValueMultiplier: 2.2
+ TargetMinutes: 5
+ Steps: 10
+ LandingStep: 0
+
+# The landing halfway down is where bottles like to stop.
+- Id: B3
+ Name: Transfer
+ Fare: 2000
+ ValueMultiplier: 4.5
+ TargetMinutes: 6
+ Steps: 12
+ LandingStep: 6
+
+- Id: B4
+ Name: Mezzanine
+ Fare: 9500
+ ValueMultiplier: 9
+ TargetMinutes: 7
+ Steps: 12
+ LandingStep: 0
+
+- Id: B5
+ Name: Platform
+ Fare: 32000
+ ValueMultiplier: 18
+ TargetMinutes: 8
+ Steps: 14
+ LandingStep: 0
diff --git a/Datra.Lab.Sample/Resources/Upgrades.yaml b/Datra.Lab.Sample/Resources/Upgrades.yaml
new file mode 100644
index 0000000..1f92f84
--- /dev/null
+++ b/Datra.Lab.Sample/Resources/Upgrades.yaml
@@ -0,0 +1,40 @@
+# Account upgrades stay for the whole game. Floor devices are bought again on every floor.
+- Id: push
+ Name: Push power
+ Scope: Account
+ BaseCost: 120
+ CostGrowth: 2.1
+ MaxLevel: 5
+ Amount: 0.35
+
+- Id: wrap
+ Name: Bubble wrap
+ Scope: Account
+ BaseCost: 260
+ CostGrowth: 2.6
+ MaxLevel: 3
+ Amount: 0.2
+
+- Id: queue
+ Name: Longer line
+ Scope: Account
+ BaseCost: 400
+ CostGrowth: 3.2
+ MaxLevel: 3
+ Amount: 0.33
+
+- Id: carpet
+ Name: Carpet
+ Scope: Floor
+ BaseCost: 90
+ CostGrowth: 1.9
+ MaxLevel: 4
+ Amount: 0.25
+
+- Id: box
+ Name: Catch box
+ Scope: Floor
+ BaseCost: 150
+ CostGrowth: 2.2
+ MaxLevel: 3
+ Amount: 0.5
diff --git a/Datra.Lab.Tests/BotRunnerTests.cs b/Datra.Lab.Tests/BotRunnerTests.cs
new file mode 100644
index 0000000..883ccd6
--- /dev/null
+++ b/Datra.Lab.Tests/BotRunnerTests.cs
@@ -0,0 +1,183 @@
+using Datra.Lab.Sample;
+using Datra.Lab.Sample.Generated;
+using Xunit;
+
+namespace Datra.Lab.Tests;
+
+public class BotRunnerTests
+{
+ /// The result as JSON, minus the wall-clock time — the one part allowed to differ.
+ private static string Fingerprint(LabResult result)
+ {
+ var timing = result.Timing;
+ result.Timing = null;
+ try { return LabJson.Serialize(result); }
+ finally { result.Timing = timing; }
+ }
+
+ [Fact]
+ public async Task Same_seed_gives_the_same_result()
+ {
+ using var lab = new DescentFixture();
+ var scenario = new Scenario { Seed = 7, Bots = 24, Changes = { ["EconomyData.StepValue"] = 8 } };
+
+ var first = await lab.Engine.RunAsync(scenario);
+ var second = await lab.Engine.RunAsync(scenario);
+
+ Assert.Equal(Fingerprint(first), Fingerprint(second));
+ Assert.Equal(24, first.Finished);
+ }
+
+ [Fact]
+ public async Task Result_does_not_depend_on_how_many_threads_ran_the_bots()
+ {
+ using var serial = new DescentFixture(o => o.MaxParallelism = 1);
+ using var parallel = new DescentFixture(o => o.MaxParallelism = 8);
+ var scenario = new Scenario { Seed = 3, Bots = 32 };
+
+ var one = await serial.Engine.RunAsync(scenario);
+ var many = await parallel.Engine.RunAsync(scenario);
+
+ Assert.Equal(Fingerprint(one), Fingerprint(many));
+ }
+
+ [Fact]
+ public async Task A_different_seed_gives_a_different_result()
+ {
+ using var lab = new DescentFixture();
+
+ var a = await lab.Engine.RunAsync(new Scenario { Seed = 1 });
+ var b = await lab.Engine.RunAsync(new Scenario { Seed = 2 });
+
+ Assert.NotEqual(a.Total!.Median, b.Total!.Median);
+ }
+
+ [Fact]
+ public async Task Each_bot_replays_exactly_from_its_own_seed()
+ {
+ using var lab = new DescentFixture();
+ var data = await lab.Engine.ForkAsync();
+ var outcomes = DescentPhysics.Bake(data);
+ var settings = new RunSettings { Bots = 12, Seed = 5, Policy = DescentSim.Efficient };
+
+ var batch = BotRunner.Run(new DescentSim(), data, settings, outcomes);
+ var alone = BotRunner.RunOne(new DescentSim(), data, settings, 9, outcomes);
+
+ Assert.Equal(SimRandom.Derive(5, 9), batch[9].Seed);
+ Assert.Equal(batch[9].Seed, alone.Seed);
+ Assert.Equal(batch[9].TotalSeconds, alone.TotalSeconds);
+ Assert.Equal(batch[9].Purchases.Select(p => (p.Time, p.Id)), alone.Purchases.Select(p => (p.Time, p.Id)));
+ Assert.Equal(batch[9].Ticks.Select(t => t.Earned), alone.Ticks.Select(t => t.Earned));
+ Assert.Equal(Enumerable.Range(0, 12), batch.Select(r => r.Bot));
+ Assert.Equal(12, batch.Select(r => r.Seed).Distinct().Count());
+ }
+
+ [Fact]
+ public async Task Bots_share_luck_across_scenarios_so_a_knob_is_the_only_difference()
+ {
+ using var lab = new DescentFixture();
+ var data = await lab.Engine.ForkAsync();
+ var outcomes = DescentPhysics.Bake(data);
+ var settings = new RunSettings { Bots = 6, Seed = 11, Policy = DescentSim.Cheap };
+
+ var a = BotRunner.Run(new DescentSim(), data, settings, outcomes);
+ var b = BotRunner.Run(new DescentSim(), data, settings, outcomes);
+
+ Assert.Equal(a.Select(r => r.Seed), b.Select(r => r.Seed));
+ Assert.Equal(a.Select(r => r.TotalEarned), b.Select(r => r.TotalEarned));
+ }
+
+ [Fact]
+ public async Task Policy_and_policy_parameters_reach_the_simulator()
+ {
+ using var lab = new DescentFixture();
+
+ var quick = await lab.Engine.RunAsync(new Scenario { PolicyParams = { ["shopSeconds"] = 2 } });
+ var slow = await lab.Engine.RunAsync(new Scenario { PolicyParams = { ["shopSeconds"] = 30 } });
+ var cheap = await lab.Engine.RunAsync(new Scenario { Policy = DescentSim.Cheap });
+
+ Assert.True(quick.Total!.Median < slow.Total!.Median);
+ Assert.True(cheap.Purchases.CountMedian > quick.Purchases.CountMedian);
+ Assert.Equal(DescentSim.Cheap, cheap.Scenario.Policy);
+ Assert.Equal(2, quick.Scenario.PolicyParams["shopSeconds"]);
+
+ await Assert.ThrowsAsync(() => lab.Engine.RunAsync(new Scenario { Policy = "nope" }));
+ await Assert.ThrowsAsync(() => lab.Engine.RunAsync(new Scenario { PolicyParams = { ["nope"] = 1 } }));
+ }
+
+ [Fact]
+ public async Task A_cheaper_fare_shortens_that_floor_and_the_run()
+ {
+ using var lab = new DescentFixture();
+
+ var baseline = await lab.Engine.RunAsync(new Scenario());
+ var cheaper = await lab.Engine.RunAsync(new Scenario { Changes = { ["FloorData[B3].Fare"] = 800 } });
+
+ var before = baseline.Stages.Single(s => s.Id == "B3").Median!.Value;
+ var after = cheaper.Stages.Single(s => s.Id == "B3").Median!.Value;
+ Assert.True(after < before, $"B3 took {after}s with the cheaper fare, {before}s before");
+ Assert.True(cheaper.Total!.Median < baseline.Total!.Median);
+ // The floors above B3 are played with the same luck and the same numbers.
+ Assert.Equal(baseline.Stages[0].Median, cheaper.Stages[0].Median);
+ }
+
+ [Fact]
+ public async Task A_knob_left_on_its_baseline_is_not_a_change()
+ {
+ using var lab = new DescentFixture();
+
+ var plain = await lab.Engine.RunAsync(new Scenario());
+ var same = await lab.Engine.RunAsync(new Scenario { Changes = { ["EconomyData.StepValue"] = 5 } });
+
+ Assert.Empty(same.Scenario.Changes);
+ Assert.Equal(Fingerprint(plain), Fingerprint(same));
+ }
+
+ [Fact]
+ public void A_bot_that_never_finishes_is_stopped_at_the_time_cap_and_reported()
+ {
+ var records = BotRunner.Run(new Stuck(), new DescentContext(new Datra.Providers.FileSystemRawDataProvider(".")),
+ new RunSettings { Bots = 3, MaxSimSeconds = 600 });
+ var result = ResultAggregator.Aggregate(records);
+
+ Assert.Equal(0, result.Finished);
+ Assert.Null(result.Total);
+ Assert.All(records, r => Assert.True(r.TotalSeconds >= 600));
+ Assert.Equal(3, result.Stages[0].Reached);
+ Assert.Equal(0, result.Stages[0].Completed);
+ Assert.Null(result.Stages[0].Median);
+ var problem = Assert.Single(result.Problems);
+ Assert.Equal("unfinished", problem.Kind);
+ Assert.Equal(3, problem.Bots);
+ }
+
+ [Fact]
+ public void A_simulator_that_never_advances_time_is_cut_off_and_reported()
+ {
+ var records = BotRunner.Run(new Frozen(), new DescentContext(new Datra.Providers.FileSystemRawDataProvider(".")),
+ new RunSettings { Bots = 2, MaxRecords = 1000 });
+
+ Assert.All(records, r => Assert.False(r.Finished));
+ Assert.All(records, r => Assert.Contains("looping", r.Error));
+ var result = ResultAggregator.Aggregate(records);
+ Assert.Equal("error", result.Problems[0].Kind);
+ Assert.Equal(2, result.Problems[0].Bots);
+ }
+
+ private sealed class Stuck : ISimulator
+ {
+ public void Play(DescentContext data, SimRun run)
+ {
+ run.Stage("only");
+ while (!run.OutOfTime) run.Tick(30, 0);
+ }
+ }
+
+ private sealed class Frozen : ISimulator
+ {
+ public void Play(DescentContext data, SimRun run)
+ {
+ while (!run.OutOfTime) run.Tick(0, 1);
+ }
+ }
+}
diff --git a/Datra.Lab.Tests/Datra.Lab.Tests.csproj b/Datra.Lab.Tests/Datra.Lab.Tests.csproj
new file mode 100644
index 0000000..f85a2b6
--- /dev/null
+++ b/Datra.Lab.Tests/Datra.Lab.Tests.csproj
@@ -0,0 +1,31 @@
+
+
+
+ net9.0
+ enable
+ enable
+ false
+ true
+ default
+
+
+
+
+
+
+
+
+
+
+
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+ all
+
+
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+ all
+
+
+
+
+
diff --git a/Datra.Lab.Tests/DescentFixture.cs b/Datra.Lab.Tests/DescentFixture.cs
new file mode 100644
index 0000000..65d93cc
--- /dev/null
+++ b/Datra.Lab.Tests/DescentFixture.cs
@@ -0,0 +1,50 @@
+using Datra.Lab.Sample;
+using Datra.Lab.Sample.Generated;
+using Datra.Providers;
+
+namespace Datra.Lab.Tests;
+
+///
+/// The toy game's data staged into a scratch directory, with a lab engine over it. Every test
+/// gets its own copy, so the "nothing was written" checks cannot see another test's files.
+///
+internal sealed class DescentFixture : IDisposable
+{
+ public string DataPath { get; }
+ public string SnapshotPath { get; }
+ public FileSystemRawDataProvider Provider { get; }
+ public LabEngine Engine { get; }
+
+ public DescentFixture(Action>? configure = null)
+ {
+ var root = Path.Combine(Path.GetTempPath(), "datra-lab-tests", Guid.NewGuid().ToString("N"));
+ DataPath = DescentData.WriteTo(Path.Combine(root, "data"));
+ SnapshotPath = Path.Combine(root, "snapshots");
+ Provider = new FileSystemRawDataProvider(DataPath);
+
+ var options = new LabOptions();
+ DescentLab.Configure(options);
+ options.SnapshotDirectory(SnapshotPath);
+ options.Outcomes = DescentPhysics.Bake(LoadSaved());
+ configure?.Invoke(options);
+
+ Engine = new LabEngine(Provider, new DescentSim(), options);
+ }
+
+ /// A context read straight from the staged files: what is actually saved.
+ public DescentContext LoadSaved()
+ {
+ var context = new DescentContext(new FileSystemRawDataProvider(DataPath));
+ context.LoadAllAsync().GetAwaiter().GetResult();
+ return context;
+ }
+
+ /// File name → bytes of every staged data file.
+ public Dictionary ReadFiles() =>
+ Directory.GetFiles(DataPath).ToDictionary(f => Path.GetFileName(f)!, File.ReadAllText);
+
+ public void Dispose()
+ {
+ try { Directory.Delete(Path.GetDirectoryName(DataPath)!, recursive: true); } catch { /* best-effort */ }
+ }
+}
diff --git a/Datra.Lab.Tests/ForkedContextTests.cs b/Datra.Lab.Tests/ForkedContextTests.cs
new file mode 100644
index 0000000..0db87cb
--- /dev/null
+++ b/Datra.Lab.Tests/ForkedContextTests.cs
@@ -0,0 +1,157 @@
+using Datra.Lab.Sample;
+using Datra.Lab.Sample.Generated;
+using Xunit;
+
+namespace Datra.Lab.Tests;
+
+///
+/// A scenario's knobs land in a fork. The saved files, a context loaded from them, and other
+/// forks must never see them.
+///
+public class ForkedContextTests
+{
+ private static readonly Dictionary Changes = new()
+ {
+ ["EconomyData.StepValue"] = 12, // single data, Set
+ ["FloorData[B3].Fare"] = 1234, // one row, Set
+ ["UpgradeData.BaseCost"] = 2, // every row, Scale
+ ["UpgradeData[carpet].Amount"] = 0.6, // one row of a repeated attribute
+ ["Floors.ValueGrowth"] = 3, // declared in code
+ };
+
+ [Fact]
+ public async Task Fork_reads_the_knob_values_through_the_ordinary_context_api()
+ {
+ using var lab = new DescentFixture();
+
+ var fork = await lab.Engine.ForkAsync(new Scenario { Changes = Changes });
+
+ Assert.Equal(12f, fork.Economy.Current!.StepValue);
+ Assert.Equal(1234, fork.Floor.LoadedItems["B3"].Fare);
+ Assert.Equal(600, fork.Floor.LoadedItems["B2"].Fare);
+ Assert.Equal(240f, fork.Upgrade.LoadedItems["push"].BaseCost);
+ Assert.Equal(180f, fork.Upgrade.LoadedItems["carpet"].BaseCost);
+ Assert.Equal(0.6f, fork.Upgrade.LoadedItems["carpet"].Amount);
+ Assert.Equal(0.5f, fork.Upgrade.LoadedItems["box"].Amount);
+ Assert.Equal(3, DescentData.ValueGrowth(fork), 4);
+ }
+
+ [Fact]
+ public async Task Running_a_scenario_leaves_the_saved_files_byte_for_byte()
+ {
+ using var lab = new DescentFixture();
+ var before = lab.ReadFiles();
+
+ await lab.Engine.RunAsync(new Scenario { Changes = Changes, Bots = 8 });
+
+ Assert.Equal(before, lab.ReadFiles());
+ Assert.Equal(before.Keys.OrderBy(k => k), Directory.GetFiles(lab.DataPath).Select(Path.GetFileName).OrderBy(k => k));
+ }
+
+ [Fact]
+ public async Task A_context_loaded_from_the_saved_data_does_not_see_the_scenario()
+ {
+ using var lab = new DescentFixture();
+
+ await lab.Engine.RunAsync(new Scenario { Changes = Changes, Bots = 8 });
+ var saved = lab.LoadSaved();
+
+ Assert.Equal(5f, saved.Economy.Current!.StepValue);
+ Assert.Equal(2000, saved.Floor.LoadedItems["B3"].Fare);
+ Assert.Equal(120f, saved.Upgrade.LoadedItems["push"].BaseCost);
+ Assert.Equal(0.25f, saved.Upgrade.LoadedItems["carpet"].Amount);
+ }
+
+ [Fact]
+ public async Task Forks_do_not_share_objects_with_each_other()
+ {
+ using var lab = new DescentFixture();
+
+ var changed = await lab.Engine.ForkAsync(new Scenario { Changes = Changes });
+ var plain = await lab.Engine.ForkAsync();
+
+ Assert.NotSame(changed.Floor.LoadedItems["B3"], plain.Floor.LoadedItems["B3"]);
+ Assert.Equal(2000, plain.Floor.LoadedItems["B3"].Fare);
+ Assert.Equal(5f, plain.Economy.Current!.StepValue);
+ }
+
+ [Fact]
+ public async Task The_baseline_in_the_schema_is_not_moved_by_a_scenario()
+ {
+ using var lab = new DescentFixture();
+
+ await lab.Engine.RunAsync(new Scenario { Changes = Changes, Bots = 8 });
+ var schema = await lab.Engine.GetSchemaAsync();
+
+ Assert.Equal(5, schema.Knobs.Single(k => k.Id == "EconomyData.StepValue").Baseline);
+ Assert.Equal(2000, schema.Knobs.Single(k => k.Id == "FloorData[B3].Fare").Baseline);
+ }
+
+ [Fact]
+ public async Task Saving_a_fork_writes_to_its_overlay_and_not_to_disk()
+ {
+ using var lab = new DescentFixture();
+ var before = lab.ReadFiles();
+ OverlayRawDataProvider? overlay = null;
+ var forker = new ContextForker(lab.Provider, provider =>
+ {
+ overlay = (OverlayRawDataProvider)provider;
+ return new DescentContext(provider);
+ });
+
+ var fork = await forker.ForkAsync();
+ var floor = fork.Floor.GetWorkingCopy("B1");
+ ForkedData.Set(floor, f => f.Fare, 99999);
+ fork.Floor.MarkAsModified("B1");
+ await fork.SaveAllAsync();
+
+ // The save happened, and it went to the overlay.
+ Assert.Contains("Floors.yaml", overlay!.WrittenPaths);
+ Assert.Contains("99999", await overlay.LoadTextAsync("Floors.yaml"));
+ Assert.Equal(before, lab.ReadFiles());
+ Assert.Equal(280, lab.LoadSaved().Floor.LoadedItems["B1"].Fare);
+ }
+
+ [Fact]
+ public async Task Overlay_provider_keeps_writes_and_deletes_to_itself()
+ {
+ using var lab = new DescentFixture();
+ var snapshot = new RawDataSnapshot(lab.Provider);
+ var overlay = new OverlayRawDataProvider(snapshot);
+ var other = new OverlayRawDataProvider(snapshot);
+ var original = await lab.Provider.LoadTextAsync("Economy.yaml");
+
+ await overlay.SaveTextAsync("Economy.yaml", "StepValue: 99");
+ await overlay.SaveTextAsync("New.yaml", "x: 1");
+ await overlay.DeleteAsync("Floors.yaml");
+
+ Assert.Equal("StepValue: 99", await overlay.LoadTextAsync("Economy.yaml"));
+ Assert.False(overlay.Exists("Floors.yaml"));
+ await Assert.ThrowsAsync(() => overlay.LoadTextAsync("Floors.yaml"));
+
+ Assert.Equal(original, await other.LoadTextAsync("Economy.yaml"));
+ Assert.True(other.Exists("Floors.yaml"));
+ Assert.False(other.Exists("New.yaml"));
+
+ Assert.Equal(original, await lab.Provider.LoadTextAsync("Economy.yaml"));
+ Assert.False(lab.Provider.Exists("New.yaml"));
+ Assert.True(lab.Provider.Exists("Floors.yaml"));
+ }
+
+ [Fact]
+ public async Task Baseline_is_cached_until_invalidated()
+ {
+ using var lab = new DescentFixture();
+ var first = await lab.Engine.GetSchemaAsync();
+
+ File.WriteAllText(Path.Combine(lab.DataPath, "Economy.yaml"), "StepValue: 7\nIntactBonus: 40\nBottlesPerRun: 3\nGlassToughness: 1\n");
+ var stale = await lab.Engine.GetSchemaAsync();
+ lab.Engine.InvalidateBaseline();
+ var fresh = await lab.Engine.GetSchemaAsync();
+
+ Assert.Equal(5, stale.Knobs.Single(k => k.Id == "EconomyData.StepValue").Baseline);
+ Assert.Equal(7, fresh.Knobs.Single(k => k.Id == "EconomyData.StepValue").Baseline);
+ Assert.Equal(first.BaselineHash, stale.BaselineHash);
+ Assert.NotEqual(first.BaselineHash, fresh.BaselineHash);
+ }
+}
diff --git a/Datra.Lab.Tests/KnobSchemaTests.cs b/Datra.Lab.Tests/KnobSchemaTests.cs
new file mode 100644
index 0000000..3d546eb
--- /dev/null
+++ b/Datra.Lab.Tests/KnobSchemaTests.cs
@@ -0,0 +1,142 @@
+using Datra.Attributes;
+using Xunit;
+
+namespace Datra.Lab.Tests;
+
+public class KnobSchemaTests
+{
+ [Fact]
+ public async Task Schema_lists_attribute_knobs_with_their_metadata()
+ {
+ using var lab = new DescentFixture();
+
+ var schema = await lab.Engine.GetSchemaAsync();
+
+ var step = schema.Knobs.Single(k => k.Id == "EconomyData.StepValue");
+ Assert.Equal("Step value", step.Label);
+ Assert.Equal("Rewards", step.Group);
+ Assert.Equal("coins/step", step.Unit);
+ Assert.Equal(1, step.Min);
+ Assert.Equal(15, step.Max);
+ Assert.Equal(0.5, step.Step);
+ Assert.Equal(KnobLayer.Economy, step.Layer);
+ Assert.Equal(KnobApply.Set, step.Apply);
+ Assert.Equal(5, step.Baseline);
+ Assert.False(step.Integer);
+ Assert.True(step.Editable);
+ Assert.Equal("EconomyData", step.Source!.DataType);
+ Assert.Equal("StepValue", step.Source.Property);
+ Assert.Null(step.Source.Row);
+ Assert.Equal("Economy.yaml", step.Source.File);
+ }
+
+ [Fact]
+ public async Task EachRow_expands_into_one_knob_per_row_in_file_order()
+ {
+ using var lab = new DescentFixture();
+
+ var schema = await lab.Engine.GetSchemaAsync();
+
+ var fares = schema.Knobs.Where(k => k.Source?.Property == "Fare").ToList();
+ Assert.Equal(new[] { "B1", "B2", "B3", "B4", "B5" }, fares.Select(k => k.Source!.Row));
+ Assert.Equal("FloorData[B3].Fare", fares[2].Id);
+ Assert.Equal("Fare · B3", fares[2].Label);
+ Assert.Equal(2000, fares[2].Baseline);
+ Assert.True(fares[2].Integer);
+ // No range on the attribute: each row gets one around its own value.
+ Assert.Equal(0, fares[2].Min);
+ Assert.Equal(4000, fares[2].Max);
+ Assert.Equal(64000, fares[4].Max);
+ }
+
+ [Fact]
+ public async Task Row_knob_addresses_a_single_row_and_the_attribute_can_repeat()
+ {
+ using var lab = new DescentFixture();
+
+ var schema = await lab.Engine.GetSchemaAsync();
+
+ var carpet = schema.Knobs.Single(k => k.Id == "UpgradeData[carpet].Amount");
+ Assert.Equal("Carpet value per level", carpet.Label);
+ Assert.Equal(0.25, carpet.Baseline, 6);
+ Assert.Equal("carpet", carpet.Source!.Row);
+
+ var push = schema.Knobs.Single(k => k.Id == "UpgradeData[push].Amount");
+ Assert.Equal(0.35, push.Baseline, 6);
+ }
+
+ [Fact]
+ public async Task Scale_knob_over_all_rows_rests_at_one()
+ {
+ using var lab = new DescentFixture();
+
+ var schema = await lab.Engine.GetSchemaAsync();
+
+ var prices = schema.Knobs.Single(k => k.Id == "UpgradeData.BaseCost");
+ Assert.Equal(KnobApply.Scale, prices.Apply);
+ Assert.Equal(1, prices.Baseline);
+ Assert.Null(prices.Source!.Row);
+ }
+
+ [Fact]
+ public async Task Physics_knobs_are_listed_but_not_editable()
+ {
+ using var lab = new DescentFixture();
+
+ var schema = await lab.Engine.GetSchemaAsync();
+
+ var glass = schema.Knobs.Single(k => k.Id == "EconomyData.GlassToughness");
+ Assert.Equal(KnobLayer.Physics, glass.Layer);
+ Assert.False(glass.Editable);
+
+ var error = await Assert.ThrowsAsync(() => lab.Engine.RunAsync(
+ new Scenario { Changes = { ["EconomyData.GlassToughness"] = 1.5 } }));
+ Assert.Contains("physics", error.Message);
+ }
+
+ [Fact]
+ public async Task Declared_knob_reads_its_baseline_from_the_data()
+ {
+ using var lab = new DescentFixture();
+
+ var schema = await lab.Engine.GetSchemaAsync();
+
+ var growth = schema.Knobs.Single(k => k.Id == "Floors.ValueGrowth");
+ Assert.Equal("Depth value growth", growth.Label);
+ Assert.Null(growth.Source);
+ Assert.Equal(Math.Pow(18, 0.25), growth.Baseline, 6);
+ // Declared knobs come before attribute knobs.
+ Assert.Equal(0, schema.Knobs.IndexOf(growth));
+ }
+
+ [Fact]
+ public async Task Schema_carries_policies_parameters_checks_and_defaults()
+ {
+ using var lab = new DescentFixture();
+
+ var schema = await lab.Engine.GetSchemaAsync();
+
+ Assert.Equal(new[] { "efficient", "cheap", "random" }, schema.Policies.Select(p => p.Id));
+ Assert.Equal("efficient", schema.Defaults.Policy);
+ Assert.Equal(40, schema.Defaults.Bots);
+ Assert.Equal(400, schema.Defaults.MaxBots);
+ var shop = Assert.Single(schema.PolicyParams);
+ Assert.Equal("shopSeconds", shop.Id);
+ Assert.Equal(8, shop.Default);
+ Assert.Equal(new[] { "First purchase", "Longest run" }, schema.Checks.Select(c => c.Name));
+ Assert.True(schema.Snapshots);
+ Assert.Equal("toy-1", schema.OutcomeVersion);
+ Assert.Equal(64, schema.BaselineHash.Length);
+ }
+
+ [Fact]
+ public async Task Unknown_knob_in_a_scenario_is_rejected_by_name()
+ {
+ using var lab = new DescentFixture();
+
+ var error = await Assert.ThrowsAsync(() => lab.Engine.RunAsync(
+ new Scenario { Changes = { ["EconomyData.Nope"] = 1 } }));
+
+ Assert.Contains("EconomyData.Nope", error.Message);
+ }
+}
diff --git a/Datra.Lab.Tests/SimRunTests.cs b/Datra.Lab.Tests/SimRunTests.cs
new file mode 100644
index 0000000..3b8deac
--- /dev/null
+++ b/Datra.Lab.Tests/SimRunTests.cs
@@ -0,0 +1,308 @@
+using Datra.Lab.Sample.Generated;
+using Datra.Providers;
+using Xunit;
+
+namespace Datra.Lab.Tests;
+
+/// The record contract: what a simulator writes and what the aggregator makes of it.
+public class SimRunTests
+{
+ private static readonly DescentContext NoData = new(new FileSystemRawDataProvider("."));
+
+ private sealed class Script : ISimulator
+ {
+ private readonly Action _play;
+ public Script(Action play) => _play = play;
+ public void Play(DescentContext data, SimRun run) => _play(run);
+ }
+
+ private static IReadOnlyList Run(Action play, int bots = 1, IOutcomeReader? outcomes = null) =>
+ BotRunner.Run(new Script(play), NoData, new RunSettings { Bots = bots }, outcomes);
+
+ [Fact]
+ public void Stages_ticks_purchases_and_marks_are_recorded_against_game_time()
+ {
+ var record = Run(run =>
+ {
+ run.Stage("A", targetSeconds: 60, label: "First");
+ run.Tick(20, earned: 10);
+ run.Purchase("hat", 5, group: "Account", label: "Hat Lv1");
+ run.Tick(10, earned: 0, kind: "shop");
+ run.Mark("first hat");
+ run.Stage("B");
+ run.Tick(40, earned: 30);
+ })[0];
+
+ Assert.True(record.Finished);
+ Assert.Equal(70, record.TotalSeconds);
+ Assert.Equal(40, record.TotalEarned);
+
+ Assert.Equal(new[] { "A", "B" }, record.Stages.Select(s => s.Id));
+ Assert.Equal("First", record.Stages[0].Label);
+ Assert.Equal(60, record.Stages[0].TargetSeconds);
+ Assert.Equal((0d, 30d), (record.Stages[0].StartSeconds, record.Stages[0].EndSeconds!.Value));
+ Assert.Equal((30d, 70d), (record.Stages[1].StartSeconds, record.Stages[1].EndSeconds!.Value));
+
+ var purchase = Assert.Single(record.Purchases);
+ Assert.Equal((20d, "hat", "Hat Lv1", 5d, "Account", 0),
+ (purchase.Time, purchase.Id, purchase.Label, purchase.Cost, purchase.Group, purchase.Stage));
+ Assert.Equal(20, record.FirstPurchaseSeconds);
+
+ var mark = Assert.Single(record.Marks);
+ Assert.Equal((30d, "first hat", 0), (mark.Time, mark.Name, mark.Stage));
+
+ Assert.Equal(new[] { "run", "shop", "run" }, record.Ticks.Select(t => t.Kind));
+ Assert.Equal(40, record.LongestTickSeconds("run"));
+ Assert.Equal(10, record.LongestTickSeconds("shop"));
+ }
+
+ [Fact]
+ public void Entering_the_stage_the_bot_is_already_in_does_nothing()
+ {
+ var record = Run(run =>
+ {
+ run.Stage("A");
+ run.Tick(10);
+ run.Stage("A");
+ run.Tick(10);
+ })[0];
+
+ var stage = Assert.Single(record.Stages);
+ Assert.Equal(20, stage.EndSeconds);
+ }
+
+ [Fact]
+ public void Progress_can_fall_when_spending_sets_the_bot_back()
+ {
+ var records = Run(run =>
+ {
+ run.Stage("A");
+ run.Tick(10, 60);
+ run.Progress(0.6);
+ run.Purchase("x", 40);
+ run.Progress(0.2); // the wallet is the fare box
+ run.Tick(10, 80);
+ run.Progress(1);
+ run.Stage("B");
+ run.Tick(20, 0);
+ });
+ var result = ResultAggregator.Aggregate(records);
+
+ double DepthAt(double t) => result.Progression.Points.Last(p => p.T <= t + 1e-9).Median;
+
+ Assert.Equal(40, result.Progression.TMax);
+ Assert.Equal(ResultAggregator.ProgressionSamples + 1, result.Progression.Points.Count);
+ Assert.Equal(0, DepthAt(5));
+ Assert.Equal(0.2, DepthAt(15), 6); // after the purchase, below where it was
+ Assert.Equal(1, DepthAt(25), 6); // in stage B, nothing done yet
+ Assert.Equal(2, DepthAt(40), 6); // finished: past the last stage
+ }
+
+ [Fact]
+ public void Stage_times_are_the_median_across_bots_with_a_p10_p90_range()
+ {
+ var records = Run(run =>
+ {
+ run.Stage("A", targetSeconds: 100);
+ run.Tick(100 + run.Bot * 10); // bots 0..10 take 100..200 s
+ run.Stage("B");
+ run.Tick(50);
+ }, bots: 11);
+ var result = ResultAggregator.Aggregate(records);
+
+ var a = result.Stages[0];
+ Assert.Equal((11, 11), (a.Reached, a.Completed));
+ Assert.Equal(150, a.Median);
+ Assert.Equal(110, a.P10);
+ Assert.Equal(190, a.P90);
+ Assert.Equal(100, a.TargetSeconds);
+ Assert.Equal(200, result.Total!.Median);
+ Assert.Equal(11, result.Finished);
+
+ // The representative bot is the one closest to the median total.
+ Assert.Equal(5, result.Purchases.Bot);
+ Assert.Equal(new[] { 150d, 200d }, result.Purchases.StageEnds.Select(s => s.T));
+ }
+
+ [Fact]
+ public void Purchase_timeline_is_the_representative_bots_with_medians_across_all()
+ {
+ var records = Run(run =>
+ {
+ run.Stage("A");
+ run.Tick(10 + run.Bot);
+ run.Purchase("a", 10, "Account");
+ run.Tick(10);
+ if (run.Bot % 2 == 0) run.Purchase("b", 20, "Floor device");
+ }, bots: 5);
+ var result = ResultAggregator.Aggregate(records);
+
+ Assert.Equal(12, result.Purchases.FirstSeconds);
+ Assert.Equal(2, result.Purchases.CountMedian);
+ Assert.Equal(2, result.Purchases.Bot);
+ Assert.Equal(new[] { "Account", "Floor device" }, result.Purchases.Groups);
+ Assert.Equal(new[] { "a", "b" }, result.Purchases.Items.Select(i => i.Id));
+ Assert.Equal("A", result.Purchases.Items[0].Stage);
+ }
+
+ [Fact]
+ public void Checks_report_the_median_against_the_target()
+ {
+ var records = Run(run =>
+ {
+ run.Stage("A");
+ run.Tick(30 + run.Bot * 30);
+ if (run.Bot < 4) run.Purchase("a", 1);
+ }, bots: 5);
+
+ var result = ResultAggregator.Aggregate(records, new[]
+ {
+ new LabCheck("First purchase", r => r.FirstPurchaseSeconds, "<= 60", "s"),
+ new LabCheck("Longest run", r => r.LongestTickSeconds("run"), "< 90", "s"),
+ new LabCheck("Never", r => double.NaN, ">= 1"),
+ });
+
+ // Bot 4 never bought: it has no value and is left out rather than counted as zero.
+ Assert.Equal((75d, false), (result.Checks[0].Value!.Value, result.Checks[0].Ok!.Value));
+ Assert.Equal("<= 60", result.Checks[0].Target);
+ Assert.Equal((90d, false), (result.Checks[1].Value!.Value, result.Checks[1].Ok!.Value));
+ Assert.Null(result.Checks[2].Value);
+ Assert.Null(result.Checks[2].Ok);
+ Assert.Throws(() => new LabCheck("bad", r => 0, "about 5"));
+ }
+
+ [Fact]
+ public void Explanations_and_marks_are_counted_per_bot()
+ {
+ var records = Run(run =>
+ {
+ run.Stage("A");
+ run.Tick(10);
+ run.Stage("B");
+ run.Tick(10 + run.Bot);
+ if (run.Bot > 0) run.Mark("late");
+ run.Explain("B", "slow stairs");
+ run.Explain("B", "slow stairs");
+ if (run.Bot == 0) run.Explain("A", "cold start");
+ }, bots: 3);
+ var result = ResultAggregator.Aggregate(records);
+
+ Assert.Equal(new[] { ("A", "cold start", 1), ("B", "slow stairs", 3) },
+ result.Explains.Select(e => (e.Stage, e.Text, e.Bots)));
+ var mark = Assert.Single(result.Marks);
+ Assert.Equal(("late", 2, 21.5), (mark.Name, mark.Bots, mark.FirstSeconds));
+ }
+
+ [Fact]
+ public void Outcome_draws_from_the_stored_pool_with_the_bots_own_randomness()
+ {
+ var key = PhysicsKey.Of(("floor", "B1"), ("push", 2));
+ var outcomes = new InMemoryOutcomes("v1").Add(key, Enumerable.Range(0, 50));
+ var drawn = new List[2];
+
+ for (var pass = 0; pass < 2; pass++)
+ {
+ var seen = new List();
+ Run(run => { for (var i = 0; i < 20; i++) seen.Add(run.Outcome(key)); }, outcomes: outcomes);
+ drawn[pass] = seen;
+ }
+
+ Assert.Equal(drawn[0], drawn[1]);
+ Assert.True(drawn[0].Distinct().Count() > 5);
+ Assert.All(drawn[0], v => Assert.InRange(v, 0, 49));
+ }
+
+ [Fact]
+ public void A_missing_physics_key_stops_that_bot_and_is_named_in_the_result()
+ {
+ var known = PhysicsKey.Of(("floor", "B1"));
+ var unknown = PhysicsKey.Of(("floor", "B9"));
+ var outcomes = new InMemoryOutcomes().Add(known, new[] { 1 });
+
+ var records = Run(run =>
+ {
+ run.Stage("A");
+ run.Tick(10, run.Outcome(known));
+ if (run.Bot == 1) run.Outcome(unknown);
+ run.Tick(10);
+ }, bots: 2, outcomes: outcomes);
+ var result = ResultAggregator.Aggregate(records);
+
+ Assert.True(records[0].Finished);
+ Assert.False(records[1].Finished);
+ Assert.Equal(new[] { "floor=B9" }, records[1].MissingOutcomes);
+ Assert.Contains(result.Problems, p => p.Kind == "missingOutcome" && p.Message == "floor=B9" && p.Bots == 1);
+ Assert.Contains(result.Problems, p => p.Kind == "error" && p.Bots == 1);
+ Assert.Equal(1, result.Finished);
+ }
+
+ [Fact]
+ public void TryOutcome_lets_the_simulator_fall_back_but_still_reports_the_key()
+ {
+ var records = Run(run =>
+ {
+ run.Stage("A");
+ var found = run.TryOutcome(PhysicsKey.Of(("floor", "B9")), out var value);
+ run.Tick(10, found ? value : 3);
+ });
+
+ Assert.True(records[0].Finished);
+ Assert.Equal(3, records[0].TotalEarned);
+ Assert.Equal(new[] { "floor=B9" }, records[0].MissingOutcomes);
+ }
+
+ [Fact]
+ public void Physics_key_is_the_same_whatever_order_its_parts_are_given_in()
+ {
+ var a = PhysicsKey.Of(("push", 2), ("floor", "B1"), ("scale", 1.5));
+ var b = PhysicsKey.Of(("floor", "B1"), ("scale", 1.5), ("push", 2));
+
+ Assert.Equal("floor=B1;push=2;scale=1.5", a.Text);
+ Assert.Equal(a, b);
+ Assert.Equal(a.Hash("v1"), b.Hash("v1"));
+ Assert.NotEqual(a.Hash("v1"), a.Hash("v2"));
+ Assert.Equal(a, PhysicsKey.Parse(a.Text));
+ }
+
+ [Fact]
+ public void Jsonl_reader_loads_one_pool_per_key_file()
+ {
+ var directory = Path.Combine(Path.GetTempPath(), "datra-lab-tests", Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(directory);
+ try
+ {
+ var reader = new JsonlOutcomeReader(directory, "pin-7");
+ var key = PhysicsKey.Of(("floor", "B1"), ("push", 0));
+ File.WriteAllLines(reader.PathFor(key), new[]
+ {
+ """{"steps":3,"intact":false,"seconds":5.4}""",
+ "",
+ """{"steps":8,"intact":true,"seconds":9.4}""",
+ });
+
+ var pool = reader.Pool(key);
+
+ Assert.Equal("pin-7", reader.Version);
+ Assert.Equal(new[] { 3, 8 }, pool!.Select(o => o.Steps));
+ Assert.True(pool![1].Intact);
+ Assert.Null(reader.Pool(PhysicsKey.Of(("floor", "B2"))));
+ }
+ finally
+ {
+ Directory.Delete(directory, recursive: true);
+ }
+ }
+
+ [Fact]
+ public void SimRandom_is_a_fixed_sequence_per_seed()
+ {
+ var a = new SimRandom(42);
+ var b = new SimRandom(42);
+ var first = Enumerable.Range(0, 5).Select(_ => a.NextULong()).ToList();
+
+ Assert.Equal(first, Enumerable.Range(0, 5).Select(_ => b.NextULong()));
+ // Pinned: a change to the generator would silently change every stored result.
+ Assert.Equal(13679457532755275413UL, first[0]);
+ Assert.All(Enumerable.Range(0, 1000).Select(_ => a.NextDouble()), v => Assert.InRange(v, 0, 0.9999999999999999));
+ }
+}
diff --git a/Datra.Lab.Tests/SnapshotTests.cs b/Datra.Lab.Tests/SnapshotTests.cs
new file mode 100644
index 0000000..73946b1
--- /dev/null
+++ b/Datra.Lab.Tests/SnapshotTests.cs
@@ -0,0 +1,85 @@
+using Xunit;
+
+namespace Datra.Lab.Tests;
+
+public class SnapshotTests
+{
+ [Fact]
+ public async Task Snapshot_round_trips_the_scenario_and_the_result_it_gave()
+ {
+ using var lab = new DescentFixture();
+ var scenario = new Scenario
+ {
+ Changes = { ["EconomyData.StepValue"] = 9, ["FloorData[B3].Fare"] = 1500 },
+ Policy = "cheap",
+ Bots = 16,
+ Seed = 4,
+ };
+
+ var saved = await lab.Engine.SaveSnapshotAsync("cheap fares v2", scenario);
+ var loaded = await lab.Engine.Snapshots!.LoadAsync("cheap fares v2");
+
+ Assert.NotNull(loaded);
+ Assert.Equal("cheap fares v2", loaded!.Name);
+ Assert.Equal(saved.BaselineHash, loaded.BaselineHash);
+ Assert.Equal(9, loaded.Scenario.Changes["EconomyData.StepValue"]);
+ Assert.Equal(1500, loaded.Scenario.Changes["FloorData[B3].Fare"]);
+ Assert.Equal(("cheap", 16, 4), (loaded.Scenario.Policy, loaded.Scenario.Bots, loaded.Scenario.Seed));
+ Assert.Equal(LabJson.Serialize(saved.Result), LabJson.Serialize(loaded.Result));
+ Assert.Equal(5, loaded.Result.Stages.Count);
+ }
+
+ [Fact]
+ public async Task A_loaded_scenario_reproduces_the_stored_result()
+ {
+ using var lab = new DescentFixture();
+ await lab.Engine.SaveSnapshotAsync("v1", new Scenario { Changes = { ["UpgradeData.BaseCost"] = 1.5 } });
+
+ var loaded = await lab.Engine.Snapshots!.LoadAsync("v1");
+ var again = await lab.Engine.RunAsync(loaded!.Scenario);
+
+ Assert.Equal(loaded.Result.Total!.Median, again.Total!.Median);
+ Assert.Equal(loaded.Result.Stages.Select(s => s.Median), again.Stages.Select(s => s.Median));
+ }
+
+ [Fact]
+ public async Task Snapshots_are_listed_newest_first_as_plain_json_files()
+ {
+ using var lab = new DescentFixture();
+ await lab.Engine.SaveSnapshotAsync("first", new Scenario());
+ await Task.Delay(20);
+ await lab.Engine.SaveSnapshotAsync("second", new Scenario { Changes = { ["EconomyData.StepValue"] = 6 } });
+
+ var list = await lab.Engine.Snapshots!.ListAsync();
+
+ Assert.Equal(new[] { "second", "first" }, list.Select(s => s.Name));
+ Assert.Equal(new[] { 1, 0 }, list.Select(s => s.ChangedKnobs));
+ Assert.True(File.Exists(Path.Combine(lab.SnapshotPath, "second.json")));
+ Assert.Contains("\"EconomyData.StepValue\": 6", File.ReadAllText(Path.Combine(lab.SnapshotPath, "second.json")));
+ }
+
+ [Theory]
+ [InlineData("../escape")]
+ [InlineData("a/b")]
+ [InlineData("")]
+ [InlineData(".hidden")]
+ [InlineData("trailing.")]
+ [InlineData("a..b")]
+ public async Task Names_that_could_leave_the_snapshot_directory_are_refused(string name)
+ {
+ using var lab = new DescentFixture();
+
+ await Assert.ThrowsAsync(() => lab.Engine.SaveSnapshotAsync(name, new Scenario()));
+ await Assert.ThrowsAsync(() => lab.Engine.Snapshots!.LoadAsync(name));
+ Assert.False(Directory.Exists(lab.SnapshotPath) && Directory.GetFiles(lab.SnapshotPath).Length > 0);
+ }
+
+ [Fact]
+ public async Task A_missing_snapshot_loads_as_null()
+ {
+ using var lab = new DescentFixture();
+
+ Assert.Null(await lab.Engine.Snapshots!.LoadAsync("nothing here"));
+ Assert.Empty(await lab.Engine.Snapshots.ListAsync());
+ }
+}
diff --git a/Datra.Lab/Context/ContextForker.cs b/Datra.Lab/Context/ContextForker.cs
new file mode 100644
index 0000000..717fa7a
--- /dev/null
+++ b/Datra.Lab/Context/ContextForker.cs
@@ -0,0 +1,77 @@
+#nullable enable
+using System;
+using System.Linq;
+using System.Reflection;
+using System.Threading.Tasks;
+using Datra.Interfaces;
+
+namespace Datra.Lab
+{
+ ///
+ /// Makes independent, loaded copies of a data context. A fork is an ordinary
+ /// , so a simulator reads data.Bottle the way game
+ /// code does, but it lives on an : its objects are its
+ /// own and nothing it does reaches the saved data.
+ ///
+ public sealed class ContextForker where TContext : class, IDataContext
+ {
+ private readonly RawDataSnapshot _snapshot;
+ private readonly Func _create;
+
+ /// Where the baseline data is read from. Only ever read.
+ ///
+ /// Builds a context on a given provider. Defaults to the generated constructor
+ /// new TContext(IRawDataProvider, ...optional...).
+ ///
+ public ContextForker(IRawDataProvider source, Func? create = null)
+ {
+ _snapshot = new RawDataSnapshot(source ?? throw new ArgumentNullException(nameof(source)));
+ _create = create ?? DefaultFactory();
+ }
+
+ /// The cached baseline files. Shared by every fork.
+ public RawDataSnapshot Snapshot => _snapshot;
+
+ /// A freshly loaded context holding the baseline values.
+ public async Task ForkAsync()
+ {
+ var context = _create(new OverlayRawDataProvider(_snapshot))
+ ?? throw new InvalidOperationException("The context factory returned null.");
+ await context.LoadAllAsync().ConfigureAwait(false);
+ return context;
+ }
+
+ /// Drop the cached baseline so the next fork re-reads the source (after a save or reload).
+ public void Invalidate() => _snapshot.Clear();
+
+ private static Func DefaultFactory()
+ {
+ // The source generator emits (IRawDataProvider, DataSerializerFactory = null,
+ // DatraConfigurationValue = null, ISerializationLogger = null). Any constructor whose
+ // first parameter takes the provider and whose remaining ones are optional will do.
+ var constructor = typeof(TContext)
+ .GetConstructors(BindingFlags.Public | BindingFlags.Instance)
+ .Select(c => new { Constructor = c, Parameters = c.GetParameters() })
+ .Where(c => c.Parameters.Length > 0
+ && c.Parameters[0].ParameterType.IsAssignableFrom(typeof(OverlayRawDataProvider))
+ && c.Parameters.Skip(1).All(p => p.HasDefaultValue))
+ .OrderBy(c => c.Parameters.Length)
+ .FirstOrDefault();
+
+ if (constructor is null)
+ {
+ throw new InvalidOperationException(
+ $"{typeof(TContext).Name} has no public constructor of the shape (IRawDataProvider, ...optional). " +
+ "Pass a context factory (LabOptions.CreateContext) instead.");
+ }
+
+ return provider =>
+ {
+ var arguments = constructor.Parameters
+ .Select((p, i) => i == 0 ? (object?)provider : p.DefaultValue)
+ .ToArray();
+ return (TContext)constructor.Constructor.Invoke(arguments);
+ };
+ }
+ }
+}
diff --git a/Datra.Lab/Context/OverlayRawDataProvider.cs b/Datra.Lab/Context/OverlayRawDataProvider.cs
new file mode 100644
index 0000000..a42bb2d
--- /dev/null
+++ b/Datra.Lab/Context/OverlayRawDataProvider.cs
@@ -0,0 +1,75 @@
+#nullable enable
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using Datra.Attributes;
+using Datra.Interfaces;
+
+namespace Datra.Lab
+{
+ ///
+ /// The raw data provider a forked context runs on. Reads fall through to the shared
+ /// baseline snapshot; writes and deletes stay in this overlay and never reach the source,
+ /// so nothing a simulator (or a stray SaveAllAsync) does can change saved data.
+ ///
+ public sealed class OverlayRawDataProvider : IFormatAwareRawDataProvider
+ {
+ private readonly RawDataSnapshot _baseline;
+ // A null value is a tombstone: the file was deleted in this overlay.
+ private readonly ConcurrentDictionary _writes =
+ new ConcurrentDictionary(StringComparer.Ordinal);
+
+ public OverlayRawDataProvider(RawDataSnapshot baseline)
+ {
+ _baseline = baseline ?? throw new ArgumentNullException(nameof(baseline));
+ }
+
+ /// Paths written in this overlay (deleted ones excluded).
+ public IReadOnlyCollection WrittenPaths =>
+ _writes.Where(p => p.Value != null).Select(p => p.Key).ToList();
+
+ public async Task LoadTextAsync(string path)
+ {
+ var text = _writes.TryGetValue(path, out var written)
+ ? written
+ : await _baseline.LoadTextAsync(path).ConfigureAwait(false);
+ return text ?? throw new FileNotFoundException($"File not found: {path}", path);
+ }
+
+ public Task SaveTextAsync(string path, string content)
+ {
+ _writes[path] = content;
+ return Task.CompletedTask;
+ }
+
+ public bool Exists(string path) =>
+ _writes.TryGetValue(path, out var written) ? written != null : _baseline.Exists(path);
+
+ public string ResolveFilePath(string path) => "overlay://" + path.Replace('\\', '/');
+
+ public async Task> LoadMultipleTextAsync(string folderPathOrLabel, string pattern = "*.json")
+ {
+ var files = await _baseline.LoadFolderAsync(folderPathOrLabel, pattern).ConfigureAwait(false);
+ // Copy: the caller owns the dictionary it gets, the snapshot keeps its own.
+ return new Dictionary(files, StringComparer.Ordinal);
+ }
+
+ public async Task> ListFilesAsync(string folderPathOrLabel, string pattern = "*.json")
+ {
+ var files = await _baseline.LoadFolderAsync(folderPathOrLabel, pattern).ConfigureAwait(false);
+ return files.Keys.ToList();
+ }
+
+ public Task DeleteAsync(string path)
+ {
+ var existed = Exists(path);
+ _writes[path] = null;
+ return Task.FromResult(existed);
+ }
+
+ public DataFormat? GetFormat(string path) => _baseline.GetFormat(path);
+ }
+}
diff --git a/Datra.Lab/Context/RawDataSnapshot.cs b/Datra.Lab/Context/RawDataSnapshot.cs
new file mode 100644
index 0000000..f557f5d
--- /dev/null
+++ b/Datra.Lab/Context/RawDataSnapshot.cs
@@ -0,0 +1,98 @@
+#nullable enable
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Security.Cryptography;
+using System.Text;
+using System.Threading.Tasks;
+using Datra.Attributes;
+using Datra.Interfaces;
+
+namespace Datra.Lab
+{
+ ///
+ /// A read-through cache of the raw files behind the baseline data. Every fork reads from
+ /// here, so a scenario run parses text from memory instead of going back to the source
+ /// provider. Nothing is ever written to the source.
+ ///
+ public sealed class RawDataSnapshot
+ {
+ private readonly IRawDataProvider _source;
+ private readonly ConcurrentDictionary _texts =
+ new ConcurrentDictionary(StringComparer.Ordinal);
+ private readonly ConcurrentDictionary> _folders =
+ new ConcurrentDictionary>(StringComparer.Ordinal);
+
+ public RawDataSnapshot(IRawDataProvider source)
+ {
+ _source = source ?? throw new ArgumentNullException(nameof(source));
+ }
+
+ /// The text at , or null when the source has no such file.
+ public async Task LoadTextAsync(string path)
+ {
+ if (_texts.TryGetValue(path, out var cached)) return cached;
+
+ string? text;
+ try
+ {
+ text = await _source.LoadTextAsync(path).ConfigureAwait(false);
+ }
+ catch (FileNotFoundException)
+ {
+ text = null;
+ }
+
+ return _texts.GetOrAdd(path, text);
+ }
+
+ public bool Exists(string path) =>
+ _texts.TryGetValue(path, out var cached) ? cached != null : _source.Exists(path);
+
+ public async Task> LoadFolderAsync(string folderPathOrLabel, string pattern)
+ {
+ var cacheKey = folderPathOrLabel + "\n" + pattern;
+ if (_folders.TryGetValue(cacheKey, out var cached)) return cached;
+
+ var files = await _source.LoadMultipleTextAsync(folderPathOrLabel, pattern).ConfigureAwait(false);
+ return _folders.GetOrAdd(cacheKey, files);
+ }
+
+ public DataFormat? GetFormat(string path) =>
+ _source is IFormatAwareRawDataProvider aware ? aware.GetFormat(path) : null;
+
+ /// Forget everything read so far. The next fork re-reads the source.
+ public void Clear()
+ {
+ _texts.Clear();
+ _folders.Clear();
+ }
+
+ ///
+ /// SHA-256 over every file read so far (path and content, ordered by path). Identifies
+ /// the baseline a result was computed from.
+ ///
+ public string ComputeHash()
+ {
+ var builder = new StringBuilder();
+ foreach (var pair in _texts.OrderBy(p => p.Key, StringComparer.Ordinal))
+ {
+ if (pair.Value is null) continue;
+ builder.Append(pair.Key).Append('\n').Append(pair.Value.Length).Append('\n').Append(pair.Value).Append('\n');
+ }
+ foreach (var folder in _folders.OrderBy(p => p.Key, StringComparer.Ordinal))
+ {
+ foreach (var file in folder.Value.OrderBy(p => p.Key, StringComparer.Ordinal))
+ builder.Append(folder.Key).Append('/').Append(file.Key).Append('\n').Append(file.Value).Append('\n');
+ }
+
+ using var sha = SHA256.Create();
+ var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(builder.ToString()));
+ var hex = new StringBuilder(hash.Length * 2);
+ foreach (var b in hash) hex.Append(b.ToString("x2"));
+ return hex.ToString();
+ }
+ }
+}
diff --git a/Datra.Lab/Datra.Lab.csproj b/Datra.Lab/Datra.Lab.csproj
new file mode 100644
index 0000000..763e54c
--- /dev/null
+++ b/Datra.Lab/Datra.Lab.csproj
@@ -0,0 +1,20 @@
+
+
+
+
+ netstandard2.1
+ latest
+ enable
+ Datra.Lab
+ Datra.Lab
+ true
+ Datra.Lab
+ Balance lab for Datra-managed game data: knob schema, forked data contexts, a simulator contract, a seeded bot runner and result aggregation. No UI.
+ datra;game;data;balance;simulation
+
+
+
+
+
+
+
diff --git a/Datra.Lab/Knobs/ForkedData.cs b/Datra.Lab/Knobs/ForkedData.cs
new file mode 100644
index 0000000..f18540f
--- /dev/null
+++ b/Datra.Lab/Knobs/ForkedData.cs
@@ -0,0 +1,31 @@
+#nullable enable
+using System;
+using System.Linq.Expressions;
+using System.Reflection;
+
+namespace Datra.Lab
+{
+ ///
+ /// Writes to data objects of a forked context. Datra's analyzer (DATRA001) rejects plain
+ /// assignments to data classes because loaded game data is meant to be read-only; a knob's
+ /// write is the one place that has to change it, and only ever on a fork.
+ ///
+ public static class ForkedData
+ {
+ ///
+ /// Set of to .
+ ///
+ /// ForkedData.Set(floor, f => f.Fare, 1200);
+ public static void Set(TData target, Expression> property, TValue value)
+ where TData : class
+ {
+ if (target is null) throw new ArgumentNullException(nameof(target));
+ if (property is null) throw new ArgumentNullException(nameof(property));
+
+ if (!(property.Body is MemberExpression member) || !(member.Member is PropertyInfo info) || !info.CanWrite)
+ throw new ArgumentException("Expected a writable property, as in f => f.Fare.", nameof(property));
+
+ info.SetValue(target, value);
+ }
+ }
+}
diff --git a/Datra.Lab/Knobs/KnobBuilder.cs b/Datra.Lab/Knobs/KnobBuilder.cs
new file mode 100644
index 0000000..b2f9d91
--- /dev/null
+++ b/Datra.Lab/Knobs/KnobBuilder.cs
@@ -0,0 +1,84 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using Datra.Attributes;
+using Datra.Interfaces;
+
+namespace Datra.Lab
+{
+ ///
+ /// A group of knobs declared in code, for values an attribute cannot express: one knob that
+ /// rewrites several fields (a fare curve, a price multiplier over a whole table).
+ ///
+ public interface IKnobSet where TContext : class, IDataContext
+ {
+ void Declare(KnobBuilder knobs);
+ }
+
+ /// Collects knobs declared in code. See .
+ public sealed class KnobBuilder where TContext : class, IDataContext
+ {
+ internal List> Knobs { get; } = new List>();
+
+ ///
+ /// Declare a knob by how to read its value from a context and how to write one back.
+ ///
+ /// Name shown on the knob.
+ /// The knob's value in the given data. Called once on the baseline.
+ /// Applies a value to a forked context. Never called on the baseline.
+ /// Stable id. Defaults to a slug of .
+ public KnobBuilder Add(
+ string label,
+ Func read,
+ Action write,
+ double min,
+ double max,
+ double step = 0,
+ string group = "",
+ string unit = "",
+ string hint = "",
+ KnobLayer layer = KnobLayer.Economy,
+ string? id = null)
+ {
+ if (string.IsNullOrWhiteSpace(label)) throw new ArgumentException("A knob needs a label.", nameof(label));
+ if (read is null) throw new ArgumentNullException(nameof(read));
+ if (write is null) throw new ArgumentNullException(nameof(write));
+ if (!(max > min)) throw new ArgumentException($"Knob '{label}': max must be greater than min.");
+
+ Knobs.Add(new DeclaredKnob(
+ id ?? "knob:" + Slug(label), label, group, unit, hint, min, max, step, layer, read, write));
+ return this;
+ }
+
+ private static string Slug(string label)
+ {
+ var chars = new char[label.Length];
+ for (var i = 0; i < label.Length; i++)
+ chars[i] = char.IsLetterOrDigit(label[i]) ? char.ToLowerInvariant(label[i]) : '-';
+ return new string(chars).Trim('-');
+ }
+ }
+
+ internal sealed class DeclaredKnob where TContext : class, IDataContext
+ {
+ public DeclaredKnob(string id, string label, string group, string unit, string hint,
+ double min, double max, double step, KnobLayer layer,
+ Func read, Action write)
+ {
+ Id = id; Label = label; Group = group; Unit = unit; Hint = hint;
+ Min = min; Max = max; Step = step; Layer = layer; Read = read; Write = write;
+ }
+
+ public string Id { get; }
+ public string Label { get; }
+ public string Group { get; }
+ public string Unit { get; }
+ public string Hint { get; }
+ public double Min { get; }
+ public double Max { get; }
+ public double Step { get; }
+ public KnobLayer Layer { get; }
+ public Func Read { get; }
+ public Action Write { get; }
+ }
+}
diff --git a/Datra.Lab/Knobs/KnobInfo.cs b/Datra.Lab/Knobs/KnobInfo.cs
new file mode 100644
index 0000000..092cace
--- /dev/null
+++ b/Datra.Lab/Knobs/KnobInfo.cs
@@ -0,0 +1,55 @@
+#nullable enable
+using Datra.Attributes;
+
+namespace Datra.Lab
+{
+ ///
+ /// A knob as a tool sees it: identity, presentation, range and the value it rests at in
+ /// the baseline data. Serialised as part of .
+ ///
+ public sealed class KnobInfo
+ {
+ /// Stable id, e.g. Economy.StepValue or Floors[B3].Fare.
+ public string Id { get; set; } = string.Empty;
+ public string Label { get; set; } = string.Empty;
+ public string Group { get; set; } = string.Empty;
+ public string Unit { get; set; } = string.Empty;
+ public string Hint { get; set; } = string.Empty;
+ public double Min { get; set; }
+ public double Max { get; set; }
+ public double Step { get; set; }
+ public KnobLayer Layer { get; set; }
+ public KnobApply Apply { get; set; }
+
+ /// The value the knob has when the scenario does not mention it.
+ public double Baseline { get; set; }
+
+ /// The field behind the knob holds whole numbers.
+ public bool Integer { get; set; }
+
+ ///
+ /// A knob over several rows that do not share one value:
+ /// moving it overwrites the per-row differences.
+ ///
+ public bool Mixed { get; set; }
+
+ /// False for knobs the tool shows but does not let a scenario change yet (physics in P0).
+ public bool Editable { get; set; } = true;
+
+ /// Where the value lives in the data. Null for knobs declared in code.
+ public KnobSource? Source { get; set; }
+ }
+
+ /// The table field a knob writes to.
+ public sealed class KnobSource
+ {
+ public string DataType { get; set; } = string.Empty;
+ public string Property { get; set; } = string.Empty;
+
+ /// The row Id, or null when the knob covers every row (or the data is single).
+ public string? Row { get; set; }
+
+ /// The data file, as declared on [TableData] / [SingleData].
+ public string File { get; set; } = string.Empty;
+ }
+}
diff --git a/Datra.Lab/Knobs/KnobSchemaReader.cs b/Datra.Lab/Knobs/KnobSchemaReader.cs
new file mode 100644
index 0000000..3b9e9fd
--- /dev/null
+++ b/Datra.Lab/Knobs/KnobSchemaReader.cs
@@ -0,0 +1,344 @@
+#nullable enable
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Reflection;
+using Datra.Attributes;
+using Datra.Interfaces;
+
+namespace Datra.Lab
+{
+ ///
+ /// One knob bound to a context type: its description plus the code that writes a value
+ /// into a (forked) context.
+ ///
+ public sealed class KnobBinding where TContext : class, IDataContext
+ {
+ private readonly Action _apply;
+
+ internal KnobBinding(KnobInfo info, int order, Action apply)
+ {
+ Info = info;
+ Order = order;
+ _apply = apply;
+ }
+
+ public KnobInfo Info { get; }
+
+ /// Position in the schema. Knobs are applied in this order within one pass.
+ internal int Order { get; }
+
+ /// Write into .
+ public void Apply(TContext data, double value) => _apply(data, value);
+ }
+
+ ///
+ /// Builds the knob list for a context by reflection: every on
+ /// the properties of the context's data types, plus knobs declared in code.
+ ///
+ public static class KnobSchemaReader
+ {
+ ///
+ /// Read the knobs of . The context must be loaded: baseline
+ /// values and the rows of knobs are read from it.
+ ///
+ public static IReadOnlyList> Read(
+ TContext baseline,
+ IEnumerable>? declared = null)
+ where TContext : class, IDataContext
+ {
+ if (baseline is null) throw new ArgumentNullException(nameof(baseline));
+
+ var result = new List>();
+
+ // Declared knobs first: they usually rewrite a whole column (a curve), and the
+ // attribute knobs that follow refine single fields on top.
+ if (declared != null)
+ {
+ foreach (var set in declared)
+ {
+ var builder = new KnobBuilder();
+ set.Declare(builder);
+ foreach (var knob in builder.Knobs)
+ {
+ var info = new KnobInfo
+ {
+ Id = knob.Id,
+ Label = knob.Label,
+ Group = knob.Group,
+ Unit = knob.Unit,
+ Hint = knob.Hint,
+ Min = knob.Min,
+ Max = knob.Max,
+ Layer = knob.Layer,
+ Apply = KnobApply.Set,
+ Baseline = knob.Read(baseline),
+ };
+ info.Step = knob.Step > 0 ? knob.Step : NiceStep(info.Min, info.Max);
+ info.Editable = info.Layer == KnobLayer.Economy;
+ result.Add(new KnobBinding(info, result.Count, knob.Write));
+ }
+ }
+ }
+
+ foreach (var typeInfo in baseline.GetDataTypeInfos())
+ {
+ var repositoryProperty = typeof(TContext).GetProperty(
+ typeInfo.PropertyName, BindingFlags.Public | BindingFlags.Instance);
+ if (repositoryProperty is null) continue;
+
+ foreach (var property in typeInfo.DataType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
+ {
+ var attributes = property.GetCustomAttributes(inherit: true).ToList();
+ if (attributes.Count == 0) continue;
+
+ if (!IsNumeric(property.PropertyType) || !property.CanRead || !property.CanWrite)
+ {
+ throw new InvalidOperationException(
+ $"[Knob] on {typeInfo.DataType.Name}.{property.Name}: a knob needs a readable, writable " +
+ $"numeric property, and this one is {property.PropertyType.Name}.");
+ }
+
+ foreach (var attribute in attributes)
+ {
+ foreach (var row in RowsFor(attribute, typeInfo, repositoryProperty, baseline))
+ {
+ result.Add(BindField(
+ baseline, typeInfo, repositoryProperty, property, attribute, row, result.Count));
+ }
+ }
+ }
+ }
+
+ var duplicate = result.GroupBy(k => k.Info.Id, StringComparer.Ordinal).FirstOrDefault(g => g.Count() > 1);
+ if (duplicate != null)
+ {
+ throw new InvalidOperationException(
+ $"Two knobs share the id '{duplicate.Key}'. Give each [Knob] on one property its own Row, " +
+ "or pass an explicit id to the declared knob.");
+ }
+
+ return result;
+ }
+
+ private static IEnumerable RowsFor(
+ KnobAttribute attribute, DataTypeInfo typeInfo, PropertyInfo repositoryProperty, TContext baseline)
+ where TContext : class, IDataContext
+ {
+ if (!string.IsNullOrEmpty(attribute.Row))
+ {
+ if (typeInfo.RepositoryKind != RepositoryKind.Table)
+ throw new InvalidOperationException(
+ $"[Knob(\"{attribute.Label}\")] on {typeInfo.DataType.Name}: Row only applies to table data.");
+ yield return attribute.Row;
+ yield break;
+ }
+
+ if (attribute.EachRow && typeInfo.RepositoryKind == RepositoryKind.Table)
+ {
+ foreach (var item in Items(repositoryProperty, baseline))
+ yield return KeyOf(item);
+ yield break;
+ }
+
+ yield return null;
+ }
+
+ private static KnobBinding BindField(
+ TContext baseline,
+ DataTypeInfo typeInfo,
+ PropertyInfo repositoryProperty,
+ PropertyInfo property,
+ KnobAttribute attribute,
+ string? row,
+ int order)
+ where TContext : class, IDataContext
+ {
+ var typeName = typeInfo.DataType.Name;
+ var integer = IsInteger(property.PropertyType);
+ var targets = Targets(repositoryProperty, baseline, row).ToList();
+ if (targets.Count == 0)
+ {
+ throw new InvalidOperationException(row is null
+ ? $"[Knob(\"{attribute.Label}\")] on {typeName}.{property.Name}: the data has no rows to address."
+ : $"[Knob(\"{attribute.Label}\")] on {typeName}.{property.Name}: no row with Id '{row}'.");
+ }
+
+ var values = targets.Select(t => ToDouble(property.GetValue(t))).ToList();
+ var info = new KnobInfo
+ {
+ Id = row is null ? $"{typeName}.{property.Name}" : $"{typeName}[{row}].{property.Name}",
+ Label = attribute.EachRow && row != null && string.IsNullOrEmpty(attribute.Row)
+ ? $"{attribute.Label} · {row}"
+ : attribute.Label,
+ Group = attribute.Group,
+ Unit = attribute.Unit,
+ Hint = attribute.Hint,
+ Layer = attribute.Layer,
+ Apply = attribute.Apply,
+ Integer = integer && attribute.Apply != KnobApply.Scale,
+ Editable = attribute.Layer == KnobLayer.Economy,
+ Source = new KnobSource
+ {
+ DataType = typeName,
+ Property = property.Name,
+ Row = row,
+ File = typeInfo.FilePath,
+ },
+ };
+
+ switch (attribute.Apply)
+ {
+ case KnobApply.Scale:
+ info.Baseline = 1;
+ info.Min = double.IsNaN(attribute.Min) ? 0 : attribute.Min;
+ info.Max = double.IsNaN(attribute.Max) ? 2 : attribute.Max;
+ break;
+ case KnobApply.Offset:
+ {
+ info.Baseline = 0;
+ var span = Math.Max(1, values.Max(Math.Abs));
+ info.Min = double.IsNaN(attribute.Min) ? -span : attribute.Min;
+ info.Max = double.IsNaN(attribute.Max) ? span : attribute.Max;
+ break;
+ }
+ default:
+ {
+ info.Baseline = values[0];
+ info.Mixed = values.Any(v => Math.Abs(v - values[0]) > 1e-9);
+ var top = Math.Max(1, Math.Abs(info.Baseline) * 2);
+ info.Min = double.IsNaN(attribute.Min) ? Math.Min(0, info.Baseline * 2) : attribute.Min;
+ info.Max = double.IsNaN(attribute.Max) ? top : attribute.Max;
+ break;
+ }
+ }
+
+ if (!(info.Max > info.Min))
+ throw new InvalidOperationException($"[Knob(\"{attribute.Label}\")] on {typeName}.{property.Name}: Max must be greater than Min.");
+
+ info.Step = attribute.Step > 0 ? attribute.Step
+ : info.Integer ? Math.Max(1, Math.Round(NiceStep(info.Min, info.Max)))
+ : NiceStep(info.Min, info.Max);
+
+ var apply = attribute.Apply;
+ void Apply(TContext data, double value)
+ {
+ foreach (var target in Targets(repositoryProperty, data, row))
+ {
+ var current = ToDouble(property.GetValue(target));
+ var next = apply switch
+ {
+ KnobApply.Scale => current * value,
+ KnobApply.Offset => current + value,
+ _ => value,
+ };
+ property.SetValue(target, FromDouble(next, property.PropertyType));
+ }
+ }
+
+ return new KnobBinding(info, order, Apply);
+ }
+
+ private static IEnumerable