Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
184 lines
6.8 KiB
C#
184 lines
6.8 KiB
C#
using System.Globalization;
|
||
using Febe.Core.Abstractions;
|
||
using Febe.Core.Domain;
|
||
using Febe.Core.Pacing;
|
||
using Febe.Core.Storage;
|
||
|
||
namespace Febe.Core.Engine;
|
||
|
||
/// <summary>
|
||
/// The active window of one day (spec §7.2): the engine works only inside it. A window belongs to the local day it
|
||
/// starts on and may end after midnight (e.g. 06:30–00:30).
|
||
/// </summary>
|
||
public sealed record ActiveWindow(DateOnly Day, DateTimeOffset Start, DateTimeOffset End)
|
||
{
|
||
public TimeSpan Length => End - Start;
|
||
|
||
public bool Contains(DateTimeOffset instant) => instant >= Start && instant < End;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Plans the active window of every day: the profile's start and end, each shifted every day by a random amount within
|
||
/// ± the profile's jitter (a normal draw with σ = jitter/2 truncated to ± jitter, never uniform), only on active
|
||
/// weekdays. The shifts of a day are derived from a seed drawn once from the engine's random source and persisted, so
|
||
/// they are deterministic per day and a restart never redraws them.
|
||
/// </summary>
|
||
public sealed class DayPlanner
|
||
{
|
||
private const double ShiftSigma = 0.5;
|
||
private static readonly TimeSpan MinimumLength = TimeSpan.FromMinutes(30);
|
||
|
||
private readonly ISettingsStore _settings;
|
||
private readonly IRandomSource _random;
|
||
private readonly Func<CautionProfile> _profile;
|
||
private readonly SemaphoreSlim _seedGate = new(1, 1);
|
||
private ulong? _seed;
|
||
|
||
public DayPlanner(ISettingsStore settings, IRandomSource random, Func<CautionProfile> profile, TimeZoneInfo zone)
|
||
{
|
||
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||
_random = random ?? throw new ArgumentNullException(nameof(random));
|
||
_profile = profile ?? throw new ArgumentNullException(nameof(profile));
|
||
Zone = zone ?? throw new ArgumentNullException(nameof(zone));
|
||
}
|
||
|
||
public TimeZoneInfo Zone { get; }
|
||
|
||
/// <summary>The window of a local day, or null when the weekday is not active.</summary>
|
||
public async Task<ActiveWindow?> GetWindowAsync(DateOnly day, CancellationToken ct = default)
|
||
{
|
||
var profile = _profile();
|
||
if (!profile.ActiveDays.Contains(day.DayOfWeek))
|
||
{
|
||
return null;
|
||
}
|
||
|
||
var seed = await GetSeedAsync(ct).ConfigureAwait(false);
|
||
return Compute(day, profile, seed, Zone);
|
||
}
|
||
|
||
/// <summary>The window containing <paramref name="instant"/> (today's, or yesterday's when it crosses midnight); null at night.</summary>
|
||
public async Task<ActiveWindow?> GetWindowAtAsync(DateTimeOffset instant, CancellationToken ct = default)
|
||
{
|
||
var today = LocalCalendar.Today(instant, Zone);
|
||
foreach (var day in new[] { today.AddDays(-1), today })
|
||
{
|
||
var window = await GetWindowAsync(day, ct).ConfigureAwait(false);
|
||
if (window is not null && window.Contains(instant))
|
||
{
|
||
return window;
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/// <summary>The window containing <paramref name="instant"/>, or the next one to start; null only without active days.</summary>
|
||
public async Task<ActiveWindow?> GetNextWindowAsync(DateTimeOffset instant, CancellationToken ct = default)
|
||
{
|
||
var today = LocalCalendar.Today(instant, Zone);
|
||
for (var offset = -1; offset <= 8; offset++)
|
||
{
|
||
var window = await GetWindowAsync(today.AddDays(offset), ct).ConfigureAwait(false);
|
||
if (window is not null && window.End > instant)
|
||
{
|
||
return window;
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/// <summary>The window of a day from a seed: pure, used by the planner and by tests.</summary>
|
||
public static ActiveWindow Compute(DateOnly day, CautionProfile profile, ulong seed, TimeZoneInfo zone)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(profile);
|
||
var (startShift, endShift) = Shifts(seed, day);
|
||
var endDay = profile.WindowEnd > profile.WindowStart ? day : day.AddDays(1);
|
||
var baseStart = LocalCalendar.FromLocal(day.ToDateTime(profile.WindowStart), zone);
|
||
var baseEnd = LocalCalendar.FromLocal(endDay.ToDateTime(profile.WindowEnd), zone);
|
||
var start = baseStart + (profile.WindowJitter * startShift);
|
||
var end = baseEnd + (profile.WindowJitter * endShift);
|
||
if (end - start < MinimumLength)
|
||
{
|
||
end = start + MinimumLength;
|
||
}
|
||
|
||
// Whole seconds: easier to read and to compare with stored times (milliseconds).
|
||
return new ActiveWindow(day, TruncateToSecond(start), TruncateToSecond(end));
|
||
}
|
||
|
||
/// <summary>Daily shifts of start and end as fractions of the jitter, in [-1, 1].</summary>
|
||
internal static (double Start, double End) Shifts(ulong seed, DateOnly day)
|
||
{
|
||
var random = new SplitMixRandom(seed ^ ((ulong)day.DayNumber * 0x9E3779B97F4A7C15UL));
|
||
return (TruncatedNormal(random), TruncatedNormal(random));
|
||
}
|
||
|
||
private static double TruncatedNormal(IRandomSource random)
|
||
{
|
||
for (var attempt = 0; attempt < 64; attempt++)
|
||
{
|
||
var value = random.Normal(0, ShiftSigma);
|
||
if (value is >= -1 and <= 1)
|
||
{
|
||
return value;
|
||
}
|
||
}
|
||
|
||
return 0;
|
||
}
|
||
|
||
private static DateTimeOffset TruncateToSecond(DateTimeOffset value) =>
|
||
new(value.Ticks - (value.Ticks % TimeSpan.TicksPerSecond), value.Offset);
|
||
|
||
private async Task<ulong> GetSeedAsync(CancellationToken ct)
|
||
{
|
||
if (_seed is { } known)
|
||
{
|
||
return known;
|
||
}
|
||
|
||
await _seedGate.WaitAsync(ct).ConfigureAwait(false);
|
||
try
|
||
{
|
||
if (_seed is { } again)
|
||
{
|
||
return again;
|
||
}
|
||
|
||
var text = await _settings.GetAsync(EngineSettingKeys.WindowSeed, ct).ConfigureAwait(false);
|
||
if (!ulong.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var seed))
|
||
{
|
||
var high = (ulong)(_random.NextDouble() * uint.MaxValue);
|
||
var low = (ulong)(_random.NextDouble() * uint.MaxValue);
|
||
seed = (high << 32) | low;
|
||
await _settings.SetAsync(EngineSettingKeys.WindowSeed, seed.ToString(CultureInfo.InvariantCulture), ct).ConfigureAwait(false);
|
||
}
|
||
|
||
_seed = seed;
|
||
return seed;
|
||
}
|
||
finally
|
||
{
|
||
_seedGate.Release();
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>SplitMix64: a tiny deterministic generator for values derived from a stored seed.</summary>
|
||
internal sealed class SplitMixRandom(ulong seed) : IRandomSource
|
||
{
|
||
private ulong _state = seed;
|
||
|
||
public double NextDouble() => (Next() >> 11) * (1.0 / (1UL << 53));
|
||
|
||
private ulong Next()
|
||
{
|
||
var z = _state += 0x9E3779B97F4A7C15UL;
|
||
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
|
||
z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
|
||
return z ^ (z >> 31);
|
||
}
|
||
}
|