From 2ea2f4e92cac8a693cf18f445fa75adb60972766 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 01:00:10 +0100 Subject: [PATCH] StressSession: the cause's schedule writes the setting's emitters, the player silences stressors, per tick Headless StressSimulation and StressSweep drive the same Tick and Silence a client will. The office breaks near 90 s at pull 0.6 with its own sense nerve; the tests pin the tuning check, monotone load, silence as the lever, quiet recovery, stress = 1 - resolve, and the pain box output by hash. Co-Authored-By: Claude Sonnet 5.5 --- src/BadDay.Core/StressParameters.cs | 25 +++++ src/BadDay.Core/StressResult.cs | 51 +++++++++ src/BadDay.Core/StressSession.cs | 153 +++++++++++++++++++++++++++ src/BadDay.Core/StressSimulation.cs | 57 ++++++++++ tests/BadDay.Tests/Program.cs | 157 ++++++++++++++++++++++++++++ 5 files changed, 443 insertions(+) create mode 100644 src/BadDay.Core/StressParameters.cs create mode 100644 src/BadDay.Core/StressResult.cs create mode 100644 src/BadDay.Core/StressSession.cs create mode 100644 src/BadDay.Core/StressSimulation.cs diff --git a/src/BadDay.Core/StressParameters.cs b/src/BadDay.Core/StressParameters.cs new file mode 100644 index 0000000..c74f069 --- /dev/null +++ b/src/BadDay.Core/StressParameters.cs @@ -0,0 +1,25 @@ +namespace BadDay.Core; + +/// +/// Every tunable of the office stress scenario: the clock, the setting, the cause, and Lodur's parameter records +/// as members. The cause's pull and sense nerve win over Drive.ObjectivePull and are the only senses. +/// Defaults are placeholders, not measured. +/// +public sealed record StressParameters +{ + public double TickSeconds { get; init; } = 0.01; + public double MaxSeconds { get; init; } = 180.0; + public double SampleEverySeconds { get; init; } = 1.0; + + public Setting Setting { get; init; } = Setting.Office; + public Cause Cause { get; init; } = Cause.Office; + + // Lodur's records. The noxious nerve and the reflex idle here (no box); Hold is the body's, which this run ignores. + public Lodur.NerveParameters Nerve { get; init; } = new(); + public Lodur.DriveParameters Drive { get; init; } = new(); + public Lodur.WithdrawalParameters Reflex { get; init; } = new(); + public Lodur.HoldParameters Hold { get; init; } = new(); + + /// Per-seed trait spread (fraction): the senses' gain and resolve drain. + public double TraitJitter { get; init; } = 0.2; +} diff --git a/src/BadDay.Core/StressResult.cs b/src/BadDay.Core/StressResult.cs new file mode 100644 index 0000000..fe17c30 --- /dev/null +++ b/src/BadDay.Core/StressResult.cs @@ -0,0 +1,51 @@ +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace BadDay.Core; + +public enum StressEntryKind { Sample, Silenced, WillBroke, Endured } + +/// One timeline row: end-of-tick state read from the Actor. Audio, Visual and Interrupt are the stimulus that reached the head on each channel. +public readonly record struct StressEntry( + long TimeMs, StressEntryKind Kind, double Audio, double Visual, double Interrupt, + double Load, double Arousal, double Resolve, Goal Goal); + +/// A player's command to silence one stressor from on. +public readonly record struct SilenceCommand(string StressorId, double AtSeconds); + +public sealed record StressResult( + ulong Seed, + /// WillBroke or Endured; the office has no box to disable. + Outcome Outcome, + long EndMs, + /// Time resolve hit zero, ms; null unless the will broke. + long? TimeToBreakMs, + /// The lowest resolve at any tick of the run. + double MinResolve, + IReadOnlyList Timeline) +{ + /// What the stress bar means (lodur:question:stress-bar-meaning, recommendation taken): composure already lost, 1 - resolve. + public const string StressBarLabel = "lost composure"; + + /// Deterministic text form (invariant culture, fixed precision). The stress column is 1 - resolve, display only. + public string Render() + { + var sb = new StringBuilder(); + sb.Append("time_ms kind audio visual interrupt load arousal resolve stress goal\n"); + foreach (var e in Timeline) + { + sb.Append(e.TimeMs.ToString(CultureInfo.InvariantCulture)).Append(' ').Append(e.Kind); + foreach (var v in new[] { e.Audio, e.Visual, e.Interrupt, e.Load, e.Arousal, e.Resolve, 1.0 - e.Resolve }) + { + sb.Append(' ').Append(v.ToString("F3", CultureInfo.InvariantCulture)); + } + sb.Append(' ').Append(e.Goal).Append('\n'); + } + return sb.ToString(); + } + + public string Summary() => Outcome == Outcome.WillBroke + ? $"seed {Seed}: will broke at {TimeToBreakMs} ms" + : $"seed {Seed}: endured to {EndMs} ms, will held, min resolve {MinResolve.ToString("F3", CultureInfo.InvariantCulture)}"; +} diff --git a/src/BadDay.Core/StressSession.cs b/src/BadDay.Core/StressSession.cs new file mode 100644 index 0000000..b06fd51 --- /dev/null +++ b/src/BadDay.Core/StressSession.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using Lodur; + +namespace BadDay.Core; + +/// +/// One run of the office: the seed's traits, the cause's schedule writing the setting's emitters, a Lodur +/// , and the recorder. The headless run, the sweep, the CLI and a client all drive it one +/// per step, and the player's lever is . The session never writes drive +/// state, computes load or arousal, or holds a stress field: rows are end-of-tick state read from the Actor, and +/// nothing reads them back. It ends where the will breaks (rung 4 continues past it) or at MaxSeconds. +/// +public sealed class StressSession +{ + private readonly StressParameters _p; + private readonly SplitMix64 _rng; + private readonly Stressor[] _stressors; + private readonly int[] _emitterOf; + private readonly bool[] _silenced; + private readonly Emitter[] _emitters; + private readonly List _timeline = new(); + private readonly long _maxTick; + private readonly long _sampleEvery; + private long _breakTick = -1; + private double _minResolve = 1.0; + private Outcome _outcome = Outcome.Endured; + private long _endTick; + + public StressSession(StressParameters p, ulong seed, int regionCount, + ReadOnlySpan holdPose, ReadOnlySpan withdrawPose, int senseRegion = 0) + { + _p = p; + _stressors = new Stressor[p.Cause.Stressors.Count]; + _emitterOf = new int[_stressors.Length]; + _silenced = new bool[_stressors.Length]; + _emitters = new Emitter[p.Setting.Emitters.Count]; + for (int e = 0; e < _emitters.Length; e++) + { + _emitters[e] = p.Setting.Emitters[e].Emitter; + for (int f = 0; f < e; f++) + { + if (p.Setting.Emitters[f].Id == p.Setting.Emitters[e].Id) throw new ArgumentException($"two emitters named '{p.Setting.Emitters[e].Id}'"); + } + } + for (int i = 0; i < _stressors.Length; i++) + { + _stressors[i] = p.Cause.Stressors[i]; + for (int f = 0; f < i; f++) + { + if (_stressors[f].Id == _stressors[i].Id) throw new ArgumentException($"two stressors named '{_stressors[i].Id}'"); + } + _emitterOf[i] = EmitterIndex(_stressors[i].EmitterId); + if (_emitterOf[i] < 0) throw new ArgumentException($"stressor '{_stressors[i].Id}' names unknown emitter '{_stressors[i].EmitterId}'"); + } + + _rng = new SplitMix64(seed); + // Per-seed traits, drawn first and in fixed order so the stream never shifts: the senses' gain and the resolve drain. + double gainTrait = 1.0 + p.TraitJitter * _rng.NextSigned(); + double drainTrait = 1.0 + p.TraitJitter * _rng.NextSigned(); + Seed = seed; + Actor = new Actor(p.TickSeconds, regionCount, p.Nerve, p.Reflex, + p.Drive with { ObjectivePull = p.Cause.ObjectivePull, DrainTrait = p.Drive.DrainTrait * drainTrait }, + p.Hold, holdPose, withdrawPose, + p.Cause.Senses with { Gain = p.Cause.Senses.Gain * gainTrait }, senseRegion); + _maxTick = Ticks(p.MaxSeconds); + _sampleEvery = Math.Max(1, Ticks(p.SampleEverySeconds)); + _endTick = _maxTick; + } + + public ulong Seed { get; } + public Actor Actor { get; } + + /// The setting's emitters in its order, with the last tick's intensities written. + public ReadOnlySpan Emitters => _emitters; + + /// Ticks run so far; the tick the next runs. + public long TickIndex => Actor.TickCount; + + /// True once the will has broken or the time ran out. + public bool Finished { get; private set; } + + /// + /// The player silences a stressor: from the current tick on it writes nothing. Silencing a silenced stressor + /// changes nothing; an unknown id is refused. + /// + public void Silence(string stressorId) + { + int i = Array.FindIndex(_stressors, s => s.Id == stressorId); + if (i < 0) throw new ArgumentException($"unknown stressor '{stressorId}'", nameof(stressorId)); + if (_silenced[i]) return; + _silenced[i] = true; + Log(TickIndex, StressEntryKind.Silenced); + } + + /// + /// One step: each stressor draws its jitter (always, so the stream never depends on state) and writes its + /// schedule value; each emitter takes the largest of its unsilenced stressors; the Actor runs on the caller's + /// points; the tick's rows are logged from the flags and the end-of-tick state. + /// + public TickEvents Tick(ReadOnlySpan x, ReadOnlySpan y, ReadOnlySpan z, + Span strengths, Span targets) + { + long tick = TickIndex; + for (int e = 0; e < _emitters.Length; e++) _emitters[e].Intensity = 0.0; + for (int i = 0; i < _stressors.Length; i++) + { + double value = _stressors[i].Value(tick, _p.TickSeconds, _rng.NextSigned()); + if (!_silenced[i] && value > _emitters[_emitterOf[i]].Intensity) _emitters[_emitterOf[i]].Intensity = value; + } + + var events = Actor.Tick(x, y, z, default, strengths, targets, _emitters); + _minResolve = Math.Min(_minResolve, Actor.Drive.Resolve); + + if ((events & TickEvents.WillBroke) != 0) + { + _breakTick = tick; + _outcome = Outcome.WillBroke; + _endTick = tick; + Log(tick, StressEntryKind.WillBroke); + } + if (tick % _sampleEvery == 0) Log(tick, StressEntryKind.Sample); + if (_outcome == Outcome.WillBroke) Finished = true; + else if (tick >= _maxTick) + { + Log(tick, StressEntryKind.Endured); + Finished = true; + } + return events; + } + + public StressResult Result() => new( + Seed, _outcome, Ms(_endTick), _breakTick >= 0 ? Ms(_breakTick) : null, _minResolve, _timeline); + + public long Ms(long tick) => (long)Math.Round(tick * _p.TickSeconds * 1000.0); + + private long Ticks(double seconds) => (long)Math.Round(seconds / _p.TickSeconds); + + private int EmitterIndex(string id) + { + for (int e = 0; e < _p.Setting.Emitters.Count; e++) if (_p.Setting.Emitters[e].Id == id) return e; + return -1; + } + + private void Log(long tick, StressEntryKind kind) + { + var d = Actor.Drive; + _timeline.Add(new StressEntry(Ms(tick), kind, + Actor.ChannelStimulus(Channel.Audio), Actor.ChannelStimulus(Channel.Visual), Actor.ChannelStimulus(Channel.Interrupt), + Actor.Load, d.Arousal, d.Resolve, + Actor.Goal == Lodur.Goal.Withdraw ? Goal.Withdraw : Goal.HoldHand)); + } +} diff --git a/src/BadDay.Core/StressSimulation.cs b/src/BadDay.Core/StressSimulation.cs new file mode 100644 index 0000000..d47ec51 --- /dev/null +++ b/src/BadDay.Core/StressSimulation.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Lodur; + +namespace BadDay.Core; + +/// +/// The headless office: one virtual human with the head fixed at the sense point, run through +/// to the break or MaxSeconds. The silences are what a player would have done, each +/// applied at the tick its time falls on, before that tick runs. +/// +public static class StressSimulation +{ + public static StressResult Run(StressParameters p, ulong seed, IReadOnlyList? silences = null) + { + var pose = new[] { Quat.Identity }; + var session = new StressSession(p, seed, 1, pose, pose); + var point = new float[1]; // the head sits at the origin + var strengths = new float[1]; // the behaviour's output has no body to move + var targets = new Quat[1]; + var pending = (silences ?? Array.Empty()).OrderBy(s => s.AtSeconds).ToList(); + while (!session.Finished) + { + while (pending.Count > 0 && Math.Round(pending[0].AtSeconds / p.TickSeconds) <= session.TickIndex) + { + session.Silence(pending[0].StressorId); + pending.RemoveAt(0); + } + session.Tick(point, point, point, strengths, targets); + } + return session.Result(); + } +} + +/// Consecutive seeds of the office, summarised: how many broke, when, and how close the others came. +public sealed record StressSweep( + int Runs, int Broke, int Endured, + long? MinBreakMs, long? MedianBreakMs, long? MaxBreakMs, + double? MinEnduredResolve, + IReadOnlyList Results) +{ + public static StressSweep Run(StressParameters p, ulong firstSeed, int count, IReadOnlyList? silences = null) + { + var results = new List(count); + for (int i = 0; i < count; i++) results.Add(StressSimulation.Run(p, firstSeed + (ulong)i, silences)); + var breaks = results.Where(r => r.TimeToBreakMs.HasValue).Select(r => r.TimeToBreakMs!.Value).OrderBy(x => x).ToList(); + var endured = results.Where(r => r.Outcome == Outcome.Endured).ToList(); + return new StressSweep( + count, breaks.Count, endured.Count, + breaks.Count > 0 ? breaks[0] : null, + breaks.Count > 0 ? breaks[breaks.Count / 2] : null, + breaks.Count > 0 ? breaks[^1] : null, + endured.Count > 0 ? endured.Min(r => r.MinResolve) : null, + results); + } +} diff --git a/tests/BadDay.Tests/Program.cs b/tests/BadDay.Tests/Program.cs index 079decb..49909bb 100644 --- a/tests/BadDay.Tests/Program.cs +++ b/tests/BadDay.Tests/Program.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using BadDay.Core; using BadDay.Ymir; +using Quat = Lodur.Quat; namespace BadDay.Tests; @@ -281,8 +282,164 @@ public static class Program Check(Cause.Office.Senses.Threshold == 0.05 && Cause.Office.Senses.SensitisationGrowth == 0.0 && Cause.Office.Senses.ConductionDelaySeconds == 0.0, "the office does not pass its own sense parameters"); }), + + ("office: the same seed gives the same bytes, and sessions stepped in turn equal each run alone", () => + { + var p = new StressParameters(); + Check(Office(p, 1).Render() == Office(p, 1).Render(), "rendered timelines differ"); + var a = NewOffice(p, 1); + var b = NewOffice(p, 2); + while (!a.Finished || !b.Finished) + { + if (!a.Finished) Step(a); + if (!b.Finished) Step(b); + } + Check(a.Result().Render() == Office(p, 1).Render() && b.Result().Render() == Office(p, 2).Render(), "stepped sessions differ from runs alone"); + }), + + ("office: an empty cause gives no load, resolve 1 on every row, and the run endures", () => + { + var r = Office(new StressParameters { Cause = Cause.Office with { Stressors = Array.Empty() } }, 1); + Check(r.Outcome == Outcome.Endured && r.TimeToBreakMs is null && r.EndMs == 180000, $"outcome {r.Outcome} at {r.EndMs}"); + Check(r.Timeline.All(e => e.Load == 0.0 && e.Arousal == 0.0 && e.Resolve == 1.0), "an empty office loaded the character"); + Check(r.Timeline[^1].Kind == StressEntryKind.Endured, "no Endured row"); + }), + + ("office tuning [P]: seeds 1..50, at least 80% break within 180 s, and p10 and p90 break times differ by more than 20%", () => + { + var sweep = StressSweep.Run(new StressParameters(), 1, 50); + Check(sweep.Broke >= 40, $"only {sweep.Broke} of 50 broke"); + var b = sweep.Results.Where(r => r.TimeToBreakMs.HasValue).Select(r => (double)r.TimeToBreakMs!.Value).OrderBy(x => x).ToArray(); + double p10 = b[(int)(b.Length * 0.1)], p90 = b[(int)(b.Length * 0.9)]; + Check((p90 - p10) / p10 > 0.2, $"p10 {p10} and p90 {p90} ms differ by under 20%"); + }), + + ("office: the break sits near 90 s at pull 0.6 with the office sense nerve, and Lodur's default nerve breaks later", () => + { + long own = MedianBreak(new StressParameters(), 1, 20); + long lodurDefault = MedianBreak(new StressParameters { Cause = Cause.Office with { Senses = new Lodur.NerveParameters() } }, 1, 20); + Check(own is > 75000 and < 100000, $"median break {own} ms"); + Check(lodurDefault > own * 1.05, $"default nerve breaks at {lodurDefault} ms, office nerve at {own} ms"); + }), + + ("office: monotone in load: scale 1.5 breaks no later, and removing any stressor breaks no sooner", () => + { + var p = new StressParameters(); + long baseline = MedianBreak(p, 1, 20); + Check(MedianBreak(p with { Cause = p.Cause.Scaled(1.5) }, 1, 20) <= baseline, "scale 1.5 lengthened the median break"); + foreach (var s in p.Cause.Stressors) + { + long without = MedianBreak(p with { Cause = p.Cause.Without(s.Id) }, 1, 20); + Check(without >= baseline, $"removing {s.Id} shortened the median break ({without} < {baseline})"); + } + }), + + ("office: silencing is the player lever: the silenced emitter writes nothing from that tick, one Silenced row is logged, and the median break comes later", () => + { + var p = new StressParameters(); + long baseline = MedianBreak(p, 1, 20); + Check(MedianBreak(p, 1, 20, new SilenceCommand("printer", 20)) > baseline, "silencing the printer at 20 s did not delay the median break"); + + var silenced = NewOffice(p, 1); + var control = NewOffice(p, 1); + while (silenced.TickIndex < 2000) { Step(silenced); Step(control); } + silenced.Silence("printer"); + silenced.Silence("printer"); // again: no second row + bool controlSounded = false; + while (silenced.TickIndex < 4000) + { + Step(silenced); Step(control); + controlSounded |= control.Emitters[0].Intensity > 0.0; + Check(silenced.Emitters[0].Intensity == 0.0, $"the silenced printer wrote {silenced.Emitters[0].Intensity} at tick {silenced.TickIndex}"); + } + Check(controlSounded, "the control printer never sounded, so the check proved nothing"); + var rows = silenced.Result().Timeline.Where(e => e.Kind == StressEntryKind.Silenced).ToArray(); + Check(rows.Length == 1 && rows[0].TimeMs == 20000, "expected exactly one Silenced row at 20000 ms"); + bool threw = false; + try { silenced.Silence("no-such-stressor"); } catch (ArgumentException) { threw = true; } + Check(threw, "an unknown stressor id was accepted"); + }), + + ("office: a stressor naming an emitter the setting lacks is refused before any tick", () => + { + var p = new StressParameters { Cause = Cause.Office with { Stressors = new[] { new Stressor("x", "nowhere", 0, 0, null, 1, 0.5, 0) } } }; + bool threw = false; + try { NewOffice(p, 1); } catch (ArgumentException) { threw = true; } + Check(threw, "an unknown emitter id was accepted"); + }), + + ("office: after one 10 s burst resolve does not rise while arousal is at or above the threshold, then it rises", () => + { + var burst = new Stressor("burst", "printer", 0, 0, null, 10, 0.5, 0); + var p = new StressParameters { MaxSeconds = 120, Cause = Cause.Office with { Stressors = new[] { burst } } }; + var s = NewOffice(p, 1); + double gate = p.Drive.ResolveRecoversBelowArousal, prev = 1.0, lowest = 1.0; + int heldDown = 0, rose = 0; + while (!s.Finished) + { + Step(s); + var d = s.Actor.Drive; + if (d.Arousal >= gate) + { + Check(d.Resolve <= prev, $"resolve rose to {d.Resolve} at tick {s.TickIndex} with arousal {d.Arousal}"); + if (d.Resolve < 1.0) heldDown++; + } + else if (d.Resolve > prev) rose++; + lowest = Math.Min(lowest, d.Resolve); + prev = d.Resolve; + } + Check(heldDown > 1000, "arousal never held the gate shut, so the check proved nothing"); + Check(rose > 1000 && prev > lowest + 0.001, "resolve never recovered once the room was quiet"); + Check(s.Result().Outcome == Outcome.Endured, "the burst broke the will"); + }), + + ("office: the stress column is 1 - resolve on every rendered row", () => + { + var lines = Office(new StressParameters(), 3).Render().Split('\n', StringSplitOptions.RemoveEmptyEntries).Skip(1).ToArray(); + Check(lines.Length > 10, "too few rows"); + foreach (var line in lines) + { + var f = line.Split(' '); + double resolve = double.Parse(f[7], System.Globalization.CultureInfo.InvariantCulture); + double stress = double.Parse(f[8], System.Globalization.CultureInfo.InvariantCulture); + Check(f.Length == 10 && Math.Abs(stress - (1.0 - resolve)) < 0.0015, $"row '{line}'"); + } + }), + + ("the pain box is untouched: run --seed 1 and sweep --seed 1 --count 20 hash to the output captured before the office existed", () => + { + string Hash(params string[] a) + { + var w = new StringWriter(); + BadDay.Cli.Program.Execute(a, w); + var bytes = System.Text.Encoding.UTF8.GetBytes(w.ToString().Replace("\r\n", "\n")); + return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes)).ToLowerInvariant(); + } + Check(Hash("run", "--seed", "1") == "a3a800612f1e610deb8c648ea74a0a3e2f4639541a46d92af0d1bcfbdd8cfb45", "run --seed 1 changed"); + Check(Hash("sweep", "--seed", "1", "--count", "20") == "2cc88f9ffbbf301b8264c0be600edb34b21a3b572f927ed96ea49eda20dc73db", "sweep --seed 1 --count 20 changed"); + }), }; + private static readonly Quat[] Pose = { Quat.Identity }; + private static readonly float[] Point = new float[1], Strengths = new float[1]; + private static readonly Quat[] Targets = new Quat[1]; + + private static StressSession NewOffice(StressParameters p, ulong seed) => new(p, seed, 1, Pose, Pose); + + private static void Step(StressSession s) => s.Tick(Point, Point, Point, Strengths, Targets); + + private static StressResult Office(StressParameters p, ulong seed, params SilenceCommand[] silences) => + StressSimulation.Run(p, seed, silences); + + /// The median break time over seeds; a run that endured counts as never. + private static long MedianBreak(StressParameters p, ulong first, int count, params SilenceCommand[] silences) + { + var times = new List(); + for (int i = 0; i < count; i++) times.Add(Office(p, first + (ulong)i, silences).TimeToBreakMs ?? long.MaxValue); + times.Sort(); + return times[times.Count / 2]; + } + private static int Tick(long ms) => (int)Math.Round(ms * Hz / 1000.0); private static float Dist(HandSample h)