core: plan the daily budget per day, start forecasts at 2 % and follow the limit week
agent-review agent review: fail

The budget was the rest of the week over the time left, so each use today
lowered it and a partial first day was held to a full day. Now each day of
the instance has its share, its even pace and its budget. Today's budget
starts from the use at the day start and does not move with today's use
(D7). Forecasts start at 2 % of a window, so an early reset no longer hides
them for most of a day.

Limit tiles of one kind show the same rows, with placeholders that say why
a value is missing. The week chart draws per-day steps and marks the
instance start and reset (D8). Week token totals follow the provider's
limit week and say since when, with the calendar week as fallback (D9).

Refs #13
This commit is contained in:
Florian Schmidt
2026-10-18 09:55:41 +02:00
parent a8785fa453
commit 941a597680
22 changed files with 422 additions and 66 deletions
+3 -2
View File
@@ -30,7 +30,7 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
Slots in order: dark `#3987e5 #d95926 #199e70 #c98500 #d55181 #9085e9`;
light `#2a78d6 #eb6834 #1baf7a #eda100 #e87ba4 #6250d6`. Other is muted.
- Status chips always have icon and label: `#0ca30c` ✓ On track, `#ec835a` ▲ Ahead,
`#fab219` ▼ Behind. Forecasts start at 10% elapsed or as soon as Ahead, using the configured pace (D7);
`#fab219` ▼ Behind. Forecasts start at 2% elapsed or as soon as Ahead, using the configured pace (D7);
until then, tiles and window charts show the Core forecast start time. Dates remain visible for every positive pace delta, but
only Ahead gets the critical `#d03b3b` mark and ⚠. Other states say "At this pace 100 % on …"
in secondary ink. Text paragraphs stay in ink colours; colour belongs to marks and meters.
@@ -41,7 +41,8 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
- Show one composition legend in the Tokens header. Cache reads are neutral; input/output/cache
write use full/65%/40% provider colour. Reasoning is part of output; Codex cache read is part
of input. Never add either subset twice.
- Week charts show dashed muted even pace and thin solid secondary budget, with labels beside
- Week charts show per-day steps: dashed muted even pace, and thin solid secondary budget from
today onward. Mark partial start and reset times. Keep labels beside
their own right endpoints and separated when close. No known day values means a collecting
message. Use CalendarDays, including partial dates at both ends of a window (D7).
Use `LimitAnalysis.SameInstance` for reset membership, history gaps and previous-window lookup;
+45 -17
View File
@@ -183,21 +183,25 @@ public sealed class CompositionBar(TokenCounts counts, Provider provider, bool i
}
}
public sealed class DailyLimitChart(WindowDays days, Provider provider) : Control
public sealed class DailyLimitChart(WindowDays days, Provider provider, TimeProvider? clock = null) : Control
{
private readonly TimeProvider clock = clock ?? TimeProvider.System;
private readonly List<(Rect Rect, Func<DataTooltip> Tip)> hits = [];
public DailyLimitChart() : this(new([], [], null, 0, null), Provider.Claude) { }
public IReadOnlyList<string> AxisLabels => days.Current.Select((day, i) => day.Start.DateTime.ToString("ddd") +
(i == 0 && days.InstanceStart is { } start && start != CalendarDays.Start(start, clock.LocalTimeZone) ? "\nfrom " + Display.Time(start, clock) : "") +
(i == days.Current.Count - 1 && days.Reset is { } reset && reset != CalendarDays.Start(reset, clock.LocalTimeZone) ? "\nreset " + Display.Time(reset, clock) : "")).ToArray();
protected override void OnInitialized()
{
base.OnInitialized(); Height = 248; ToolTip.SetShowDelay(this, 0);
base.OnInitialized(); Height = 264; ToolTip.SetShowDelay(this, 0);
PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Tip?.Invoke());
}
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear();
var dark = Ui.Dark(this); var ink = Ui.Colour("Muted", dark); var colour = Ui.ProviderColour(provider, dark);
var plot = new Rect(40, 24, Math.Max(1, Bounds.Width - 174), Math.Max(1, Bounds.Height - 60));
var maximum = Math.Max(days.EvenPace, Math.Max(days.DailyBudget ?? 0, days.Current.Concat(days.Previous).Select(d => d.Used ?? 0).DefaultIfEmpty(0).Max()));
var plot = new Rect(40, 24, Math.Max(1, Bounds.Width - 174), Math.Max(1, Bounds.Height - 76));
var maximum = days.Current.Concat(days.Previous).Select(d => Math.Max(d.Used ?? 0, Math.Max(d.EvenPace, d.Budget ?? 0))).DefaultIfEmpty(0).Max();
var ticks = UsageChart.AxisTicks(maximum * 1.15); var max = Math.Max(1, ticks[^1]);
double Y(double value) => plot.Bottom - value / max * plot.Height;
foreach (var tick in ticks)
@@ -206,11 +210,12 @@ public sealed class DailyLimitChart(WindowDays days, Provider provider) : Contro
ChartText.Draw(context, $"{tick:0.#}%", new(0, Y(tick) - 7), ink);
}
var width = plot.Width / Math.Max(1, days.Current.Count);
var labels = AxisLabels;
for (var i = 0; i < days.Current.Count; i++)
{
var day = days.Current[i]; var x = plot.Left + i * width;
if (i < days.Previous.Count && days.Previous[i].Used is { } prior)
using (context.PushOpacity(.18)) context.DrawRectangle(null, new Pen(colour, 2), new Rect(x + 4, Y(prior), width - 8, plot.Bottom - Y(prior)), 3, 3);
using (context.PushOpacity(.18)) context.DrawRectangle(null, new Pen(colour, 2), new Rect(x + 4, Y(prior), Math.Max(1, width - 8), plot.Bottom - Y(prior)), 3, 3);
if (day.Used is { } use)
{
var rect = new Rect(x + 8, Y(use), Math.Max(1, width - 16), Math.Max(0, plot.Bottom - Y(use)));
@@ -227,23 +232,46 @@ public sealed class DailyLimitChart(WindowDays days, Provider provider) : Contro
}
if (day.IsToday) ChartText.Draw(context, $"{use:0.#}%", new(x + 8, Y(use) - 18), Ui.Colour("Ink", dark), 12);
}
ChartText.Draw(context, day.Start.DateTime.ToString("ddd"), new(x + 8, plot.Bottom + 8), day.IsToday ? Ui.Colour("Ink", dark) : ink);
hits.Add((new Rect(x, plot.Top, width, plot.Height + 30), () => DataTooltip.Day(day)));
ChartText.Draw(context, labels[i], new(x + 4, plot.Bottom + 8), day.IsToday ? Ui.Colour("Ink", dark) : ink);
hits.Add((new Rect(x, plot.Top, width, plot.Height + 48), () => DataTooltip.Day(day)));
}
var evenLabel = Math.Clamp(Y(days.EvenPace) - 7, plot.Top, plot.Bottom - 14);
var budgetLabel = days.DailyBudget is { } b ? Math.Clamp(Y(b) - 7, plot.Top, plot.Bottom - 14) : 0;
if (days.DailyBudget is { } budget && Math.Abs(evenLabel - budgetLabel) < 18)
if (days.Current.Count == 0) return;
if (days.Reset is { } reset && reset != CalendarDays.Start(reset, clock.LocalTimeZone))
{
var start = CalendarDays.Start(reset, clock.LocalTimeZone);
var fraction = (reset - start).TotalSeconds / (CalendarDays.NextStart(start, clock.LocalTimeZone) - start).TotalSeconds;
var x = plot.Left + (days.Current.Count - 1 + fraction) * width;
context.DrawLine(new Pen(ink, 1, new DashStyle([3, 3], 0)), new(x, plot.Top), new(x, plot.Bottom));
}
var even = days.Current[^1].EvenPace; var budget = days.Current[^1].Budget;
var evenLabel = Math.Clamp(Y(even) - 7, plot.Top, plot.Bottom - 14);
var budgetLabel = budget is { } b ? Math.Clamp(Y(b) - 7, plot.Top, plot.Bottom - 14) : 0;
if (budget is { } value && Math.Abs(evenLabel - budgetLabel) < 18)
{
var middle = Math.Clamp((evenLabel + budgetLabel) / 2, plot.Top + 9, plot.Bottom - 23);
evenLabel = middle + (budget >= days.EvenPace ? 9 : -9);
budgetLabel = middle + (budget >= days.EvenPace ? -9 : 9);
evenLabel = middle + (value >= even ? 9 : -9);
budgetLabel = middle + (value >= even ? -9 : 9);
}
Reference(days.EvenPace, $"Even {days.EvenPace:0.#}%/day", ink, evenLabel, true);
if (days.DailyBudget is { } dailyBudget) Reference(dailyBudget, $"Budget {dailyBudget:0.#}%/day", Ui.Colour("Secondary", dark), budgetLabel, false);
void Reference(double value, string label, IBrush brush, double labelY, bool dashed)
// Labels name the full-day rates of the tile's plan row; partial days draw their share of it.
Reference(d => d.EvenPace, $"Even {days.EvenPace:0.#}%/day", ink, evenLabel, true);
if (budget is { } lastBudget) Reference(d => d.Budget, days.LaterBudget is { } later ? $"Budget {later:0.#}%/day" : $"Budget {lastBudget:0.#}%",
Ui.Colour("Secondary", dark), budgetLabel, false);
void Reference(Func<LimitDay, double?> select, string label, IBrush brush, double labelY, bool dashed)
{
context.DrawLine(new Pen(brush, 1, dashed ? new DashStyle([4, 4], 0) : null), new(plot.Left, Y(value)), new(plot.Right, Y(value)));
if (Math.Abs(labelY + 7 - Y(value)) > 3) context.DrawLine(new Pen(brush, 1), new(plot.Right, Y(value)), new(plot.Right + 6, labelY + 7));
var pen = new Pen(brush, 1, dashed ? new DashStyle([4, 4], 0) : null);
double? prior = null;
for (var i = 0; i < days.Current.Count; i++)
{
var current = select(days.Current[i]); var x = plot.Left + i * width;
if (current is { } v)
{
if (prior is { } p) context.DrawLine(pen, new(x, Y(p)), new(x, Y(v)));
context.DrawLine(pen, new(x, Y(v)), new(x + width, Y(v)));
}
prior = current;
}
if (prior is { } end && Math.Abs(labelY + 7 - Y(end)) > 3)
context.DrawLine(new Pen(brush, 1), new(plot.Right, Y(end)), new(plot.Right + 6, labelY + 7));
ChartText.Draw(context, label, new(plot.Right + 8, labelY), brush);
}
}
+3
View File
@@ -40,6 +40,9 @@ public sealed class DataTooltip : Border
var rows = new List<TooltipRow> { new("Use", day.IsFuture ? "Future day" : day.Used is { } use ? $"{use:0.##} % of the week" : "Collecting history") };
if (!day.IsFuture && day.Used is not null) rows.Add(new("Source", day.Origin == UseOrigin.Estimated ? "Estimated from tokens" : "Measured"));
if (!day.IsFuture && day.Cumulative is { } cumulative) rows.Add(new("Cumulative", $"{cumulative:0.##} %"));
if (day.IsPartial) rows.Add(new("Share", $"{day.Share.TotalHours:0.##} h"));
rows.Add(new("Even pace", $"{day.EvenPace:0.##} %"));
rows.Add(new("Budget", day.Budget is { } budget ? $"{budget:0.##} %" + (day.BudgetOrigin == UseOrigin.Estimated ? " (estimated)" : "") : "Unavailable"));
return new(day.Start.DateTime.ToString("D"), rows.ToArray());
}
public override string ToString() => Title + "\n" + string.Join('\n', Rows.Select(r => r.Label + ": " + r.Value));
+2
View File
@@ -112,6 +112,8 @@ public static class Display
return local.ToString(local.Date == clock.GetLocalNow().Date ? "t" : "g",
culture ?? System.Globalization.CultureInfo.CurrentCulture);
}
public static string Time(DateTimeOffset time, TimeProvider? clock = null) =>
TimeZoneInfo.ConvertTime(time, (clock ?? TimeProvider.System).LocalTimeZone).ToString("t");
public static string Duration(TimeSpan span) => span <= TimeSpan.Zero ? "now" : span.TotalDays >= 1
? $"{(int)span.TotalDays} d {span.Hours} h" : span.TotalHours >= 1 ? $"{(int)span.TotalHours} h {span.Minutes} min" : $"{Math.Ceiling(span.TotalMinutes):0} min";
public static string Span(TimeSpan span) => span.TotalHours >= 1 ? $"{span.TotalHours:0.#} h" : $"{span.TotalMinutes:0} min";
+34 -22
View File
@@ -120,7 +120,7 @@ public sealed class PanelWindow : Window
if (index < 0) index = 0;
var labels = entries.Select(d => providers.SelectMany(p => p.Windows).First(w => w.Window.Provider == d.Provider && w.Window.Id == d.Id).Window.Label).ToArray();
Control DayView(LimitDetail item) => item.Days!.Current.Any(d => d.Used is not null)
? new DailyLimitChart(item.Days, item.Provider)
? new DailyLimitChart(item.Days, item.Provider, clock)
: Ui.Text($"Collecting history since {(item.Since ?? providers.SelectMany(p => p.Windows).First(w => w.Window.Provider == item.Provider && w.Window.Id == item.Id).Window.SampleTime).LocalDateTime:dd.MM. HH:mm}", 12, "Muted");
var chart = new Border { Child = DayView(entries[index]) };
var title = Ui.Text(group.Key + " · " + labels[index], 15);
@@ -154,9 +154,11 @@ public sealed class PanelWindow : Window
var totals = providers.Select(p =>
{
var row = new WrapPanel();
row.Children.Add(TokenTile(p, "Today", p.Today));
if (p.Session is { } session && p.Windows.Any(w => w.Window.Length <= TimeSpan.FromDays(1))) row.Children.Add(TokenTile(p, "Current session", session));
row.Children.Add(TokenTile(p, "This week", p.Week));
row.Children.Add(TokenTile(p, "Today", "since 00:00", p.Today));
if (p.Session is { } session && p.Windows.FirstOrDefault(w => w.Window.Length <= TimeSpan.FromHours(5) && w.Window.ResetsAt > now) is { Window: { ResetsAt: { } reset, Length: { } length } })
row.Children.Add(TokenTile(p, "Current session", "since " + Display.Time(reset - length, clock), session));
row.Children.Add(TokenTile(p, p.WeekWindow is not null ? "Limit week" : "Calendar week",
p.WeekWindow is not null ? "since " + TimeZoneInfo.ConvertTime(p.WeekStart, clock.LocalTimeZone).ToString("ddd HH:mm") : "since Mon 00:00", p.Week));
return (Control)Ui.Card(Ui.Stack(Ui.Text(p.Provider.ToString(), 15), row));
});
content.Add(Ui.Columns(totals, wide));
@@ -191,48 +193,58 @@ public sealed class PanelWindow : Window
{
var w = window.Window; var pace = window.Pace;
var detail = model.History.Details.FirstOrDefault(d => d.Provider == w.Provider && d.Id == w.Id);
var title = new DockPanel();
var title = new DockPanel { Name = "Title" };
var chip = new Border { Child = Ui.Mark(Display.State(pace.State), Brush.Parse("#0b0b0b")), Background = PaceBar.Colour(pace.State), CornerRadius = new CornerRadius(6), Padding = new Thickness(8, 4) };
DockPanel.SetDock(chip, Dock.Right); title.Children.Add(chip); title.Children.Add(Ui.Text(w.Provider + " · " + w.Label, 15));
var card = Ui.Stack(title, Ui.Text($"{w.UsedPercent:0.#} %", 36), Ui.Text("used", 12, "Muted"), new PaceBar(window, now) { Height = 10 });
card.Children.Add(Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset, clock)}" : "Reset unknown", 13, "Secondary"));
var card = Ui.Stack(title);
void Row(string name, Control control) { control.Name = name; card.Children.Add(control); }
Row("Percent", Ui.Text($"{w.UsedPercent:0.#} %", 36)); Row("Used", Ui.Text("used", 12, "Muted"));
Row("Pace", new PaceBar(window, now) { Height = 10 });
Row("Reset", Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset, clock)}" : "Reset unknown", 13, "Secondary"));
if (pace.Projection is { } projection)
{
var caption = Display.Forecast(projection, pace.State, clock) + $" ({Display.Duration(w.ResetsAt!.Value - projection)} before reset)";
if (pace.State == PaceState.Ahead)
{
var line = new DockPanel(); var mark = Ui.Mark("⚠ ", Brush.Parse("#d03b3b"), 13);
DockPanel.SetDock(mark, Dock.Left); line.Children.Add(mark); line.Children.Add(Ui.Text(caption[2..], 13, "Secondary")); card.Children.Add(line);
DockPanel.SetDock(mark, Dock.Left); line.Children.Add(mark); line.Children.Add(Ui.Text(caption[2..], 13, "Secondary")); Row("Forecast", line);
}
else card.Children.Add(Ui.Text(caption, 13, "Secondary"));
else Row("Forecast", Ui.Text(caption, 13, "Secondary"));
}
else if (LimitAnalysis.AverageUseAtReset(w, now, pace) is { } average)
card.Children.Add(Ui.Text($"≈ {average:0.#} % at reset", 13, "Secondary"));
else if (Display.ForecastWaiting(window, now, clock) is { } waiting)
card.Children.Add(Ui.Text(waiting, 13, "Muted"));
Row("Forecast", Ui.Text($"≈ {average:0.#} % at reset", 13, "Secondary"));
else Row("Forecast", Ui.Text(Display.ForecastWaiting(window, now, clock) ?? "No forecast: pace unknown", 13, "Muted"));
if (detail?.Recent is { } recent)
{
var line = Ui.Text($"Last {Display.Span(recent.Span)}: +{recent.Increase:0.#} %" + (recent.ReachesLimit is { } date ? $" · 100 % on {Display.Projection(date, clock)}" : $" · ≈ {recent.UseAtReset:0.#} % at reset"), 13, "Secondary");
ToolTip.SetTip(line, new DataTooltip("Recent rate", new("Rate", $"{recent.PercentPerDay:0.##} %/day"), new("Observed span", Display.Duration(recent.Span)))); card.Children.Add(line);
ToolTip.SetTip(line, new DataTooltip("Recent rate", new("Rate", $"{recent.PercentPerDay:0.##} %/day"), new("Observed span", Display.Duration(recent.Span)))); Row("Recent", line);
}
if (detail?.Days is { } days)
else Row("Recent", Ui.Text(Display.ForecastWaiting(window, now, clock) is not null && Pace.ForecastStartsAt(w) is { } forecastStart
? "Recent rate from " + Display.Projection(forecastStart, clock) : "Recent rate needs 3 h of samples", 13, "Muted"));
if (w.Length > TimeSpan.FromDays(1))
{
card.Children.Add(Ui.Text(days.Today is { } today ? days.TodayOrigin == UseOrigin.Estimated
? $"Today ≈ +{today:0.#} % of the week (estimated)" : $"Today +{today:0.#} % of the week" : "Today · collecting a day baseline", 15));
card.Children.Add(Ui.Text($"Even pace {days.EvenPace:0.#} %/day", 13, "Secondary"));
if (days.DailyBudget is { } budget) card.Children.Add(Ui.Text($"Budget {budget:0.#} %/day for {Display.Duration(w.ResetsAt!.Value - now)}", 15));
var days = detail?.Days;
var estimated = days?.TodayOrigin == UseOrigin.Estimated || days?.BudgetOrigin == UseOrigin.Estimated;
Row("Today", Ui.Text(days?.Today is { } today
? $"Today {(estimated ? "≈ " : "")}+{today:0.#} %" + (days.TodayBudget is { } budget ? $" of {budget:0.#} % budget" : " of the week") + (estimated ? " (estimated)" : "")
: "Today · collecting a day baseline", 15, days?.Today is null ? "Muted" : "Ink"));
var plan = $"Even pace {days?.EvenPace ?? 100 / w.Length.Value.TotalDays:0.#} %/day";
if (days?.LaterBudget is { } later) plan += $" · from tomorrow {later:0.#} %/day";
else if (days?.TodayBudget is not null && w.ResetsAt is { } lastReset) plan += " · last day, resets " + Display.Time(lastReset, clock);
Row("Plan", Ui.Text(plan, 13, "Secondary"));
}
if (now - w.SampleTime > model.ProbeInterval * 2) card.Children.Add(Ui.Text($"⚠ sample {Display.Duration(now - w.SampleTime)} old", 12, "Muted"));
if (now - w.SampleTime > model.ProbeInterval * 2) Row("Stale", Ui.Text($"⚠ sample {Display.Duration(now - w.SampleTime)} old", 12, "Muted"));
var tile = Ui.Card(card); tile.Name = $"LimitTile-{w.Provider}-{w.Id}";
ToolTip.SetTip(tile, new DataTooltip(w.Provider + " · " + w.Label, new("Used", $"{w.UsedPercent:0.##} %"), new("Expected", $"{pace.ElapsedFraction * 100:0.##} %"),
new("State", Display.State(pace.State)), new("Reset", w.ResetsAt is { } r ? Display.Projection(r, clock) : "Unknown"), new("Sample", w.SampleTime.LocalDateTime.ToString("g")))); return tile;
}
private Control TokenTile(ProviderSnapshot provider, string label, TokenCounts counts)
private Control TokenTile(ProviderSnapshot provider, string label, string caption, TokenCounts counts)
{
var tile = Ui.Stack(Ui.Text(label, 12, "Secondary"), Ui.Text(Display.Compact(Math.Max(0, counts.Total - (model.IncludeCacheReads ? 0 : counts.CacheRead))), 32),
new CompositionBar(counts, provider.Provider, model.IncludeCacheReads) { Height = 6 });
new CompositionBar(counts, provider.Provider, model.IncludeCacheReads) { Height = 6 }, Ui.Text(caption, 12, "Muted"));
tile.Name = $"TokenTile-{provider.Provider}-{label.Replace(' ', '-')}";
tile.Width = wide ? 164 : 188; tile.Margin = new Thickness(0, 8, 16, 0);
ToolTip.SetTip(tile, DataTooltip.Tokens(provider.Provider + " · " + label, counts)); return tile;
ToolTip.SetTip(tile, DataTooltip.Tokens(provider.Provider + " · " + label + " · " + caption, counts)); return tile;
}
private Control CompositionLegend()
{
+2
View File
@@ -40,6 +40,8 @@ public static class CliApplication
{
await output.WriteLineAsync($"{provider.Provider}: {provider.Status} {provider.Reason}");
await output.WriteLineAsync($" Tokens today: {provider.Today.Total}; session: {provider.Session?.Total.ToString(CultureInfo.InvariantCulture) ?? "unknown"}; week: {provider.Week.Total}");
await output.WriteLineAsync($" {(provider.WeekWindow is null ? "Calendar week" : "Limit week")}: since {provider.WeekStart:O}" +
(provider.WeekWindow is { } weekWindow ? $" ({weekWindow})" : ""));
foreach (var window in provider.Windows)
await output.WriteLineAsync(FormattableString.Invariant($" {window.Window.Label}: {window.Window.UsedPercent:0.##}% used; resets {window.Window.ResetsAt:O}; {window.Pace.State}; delta {window.Pace.Delta:0.##}; sampled {window.Window.SampleTime:O}"));
}
+2 -1
View File
@@ -18,7 +18,8 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root
propagates. The background engine records other tick failures and retries without faulting its loop.
- Use `CurrentSnapshot`, `Settings`, `UpdateSettingsAsync`, `RefreshNowAsync` and
`RecentDiagnostics`. `History` offers token series, model/project breakdowns and limit samples.
- Snapshot provider totals use local today and Monday-based calendar week. Session totals use the
- Snapshot provider totals use local today and the current provider-wide limit week, falling back
to the Monday-based local calendar week (D9). Session totals use the
reset and length of a known short limit. Hourly storage includes whole boundary hours (D5).
Day series use local calendar days, including DST. Tests can supply a zone to `TokenSeries`.
Use `CalendarDays.NextStart` for daily query ends; adding 24 hours is wrong on DST days.
+5 -4
View File
@@ -245,17 +245,18 @@ public sealed class HistoryStore
}
public TokenCounts Total(Provider provider, DateTimeOffset from, DateTimeOffset to)
{ lock (gate) return Sum(Range(provider, from, to).Select(b => b.Counts)); }
public (TokenCounts Today, TokenCounts? Session, TokenCounts Week) Totals(Provider provider, DateTimeOffset now,
LimitWindow? session, TimeZoneInfo? zone = null)
public (TokenCounts Today, TokenCounts? Session, TokenCounts Week, DateTimeOffset WeekStart, string? WeekWindow) Totals(Provider provider, DateTimeOffset now,
LimitWindow? session, TimeZoneInfo? zone = null, LimitWindow? weekWindow = null)
{
zone ??= TimeZoneInfo.Local;
var local = TimeZoneInfo.ConvertTime(now, zone);
var today = local.Date;
var week = today.AddDays(-(((int)today.DayOfWeek + 6) % 7));
var todayUtc = CalendarDays.Start(today, zone);
var weekUtc = CalendarDays.Start(week, zone);
var followsLimit = weekWindow is { ResetsAt: { } r, Length: { Ticks: > 0 } l } && r > now;
var weekUtc = followsLimit ? weekWindow!.ResetsAt!.Value - weekWindow.Length!.Value : CalendarDays.Start(week, zone);
return (Total(provider, todayUtc, now), session is { ResetsAt: { } reset, Length: { } length } && reset > now
? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now));
? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now), weekUtc, followsLimit ? weekWindow!.Id : null);
}
private IEnumerable<TokenBucket> Range(Provider provider, DateTimeOffset from, DateTimeOffset to) =>
SelectMonths(from, to).SelectMany(m => GetPartition(m).Buckets.Values)
+4 -2
View File
@@ -3,9 +3,11 @@ namespace FinalToken.Core;
public sealed record RateForecast(double PercentPerDay, double UseAtReset, DateTimeOffset? ReachesLimit,
double Increase = 0, TimeSpan Span = default);
public sealed record LimitDay(DateTimeOffset Start, DateTimeOffset End, double? Used, double? Cumulative,
bool IsToday, bool IsFuture, UseOrigin Origin = UseOrigin.Measured);
bool IsToday, bool IsFuture, UseOrigin Origin = UseOrigin.Measured, TimeSpan Share = default, double EvenPace = 0, double? Budget = null,
bool IsPartial = false, UseOrigin? BudgetOrigin = null);
public sealed record WindowDays(IReadOnlyList<LimitDay> Current, IReadOnlyList<LimitDay> Previous,
double? Today, double EvenPace, double? DailyBudget, UseOrigin TodayOrigin = UseOrigin.Measured);
double? Today, double EvenPace, double? TodayBudget, double? LaterBudget = null, UseOrigin TodayOrigin = UseOrigin.Measured,
UseOrigin? BudgetOrigin = null, DateTimeOffset? InstanceStart = null, DateTimeOffset? Reset = null);
/// <summary>Pure D7 calculations. Missing baselines use marked token estimates when calibration is available.</summary>
public static partial class LimitAnalysis
+41
View File
@@ -0,0 +1,41 @@
namespace FinalToken.Core;
public static partial class LimitAnalysis
{
// D7: plan from the day baseline; spending within that plan does not take from later days.
private static WindowDays PlanDays(LimitWindow window, LimitInstance current, LimitInstance? previous,
LimitDay? today, IReadOnlyList<LimitWindow> observations, DateTimeOffset now, TimeZoneInfo zone)
{
var length = window.Length!.Value;
double? baseline = null; UseOrigin? origin = null;
double? todayBudget = null, laterBudget = null;
if (today is not null && current.Start <= now && current.Reset > now)
{
var start = today.Start > current.Start ? today.Start : current.Start;
if (start == current.Start) { baseline = 0; origin = UseOrigin.Measured; }
else if (Instance(window, observations).LastOrDefault(s => s.SampleTime >= current.Start && s.SampleTime <= start) is { } sample)
{ baseline = sample.UsedPercent; origin = UseOrigin.Measured; }
else if (today is { Origin: UseOrigin.Estimated, Cumulative: { } cumulative, Used: { } use })
{ baseline = Math.Max(0, cumulative - use); origin = UseOrigin.Estimated; }
if (baseline is { } used)
{
todayBudget = Math.Max(0, 100 - used) * (today.End - start).TotalDays / (current.Reset - start).TotalDays;
if (today.End < current.Reset)
laterBudget = Math.Max(0, 100 - Math.Max(window.UsedPercent, used + todayBudget.Value)) / (current.Reset - today.End).TotalDays;
}
}
LimitDay Plan(LimitDay day, bool isCurrent)
{
var instance = isCurrent ? current : previous!;
var start = day.Start > instance.Start ? day.Start : instance.Start;
var share = day.End - start;
return day with { Share = share, EvenPace = 100 * share.TotalDays / (instance.Reset - instance.Start).TotalDays,
Budget = !isCurrent ? null : day.IsToday ? todayBudget : day.IsFuture ? laterBudget * share.TotalDays : null,
IsPartial = share != CalendarDays.NextStart(day.Start, zone) - day.Start,
BudgetOrigin = isCurrent && (day.IsToday || day.IsFuture) ? origin : null };
}
return new(current.Days.Select(d => Plan(d, true)).ToArray(), previous?.Days.Select(d => Plan(d, false)).ToArray() ?? [],
today?.Used, 100 / length.TotalDays, todayBudget, laterBudget, today?.Origin ?? UseOrigin.Measured,
origin, current.Start, current.Reset);
}
}
+1 -2
View File
@@ -66,8 +66,7 @@ public static partial class LimitAnalysis
if (length > TimeSpan.FromDays(1))
{
var today = current.Days.FirstOrDefault(d => d.IsToday);
days = new(current.Days, past.FirstOrDefault()?.Days ?? [], today?.Used, 100 / length.TotalDays,
reset > now ? (100 - window.UsedPercent) / (reset - now).TotalDays : null, today?.Origin ?? UseOrigin.Measured);
days = PlanDays(window, current, past.FirstOrDefault(), today, observations, now, zone);
}
return new(current, past, days);
+2 -2
View File
@@ -2,10 +2,10 @@ namespace FinalToken.Core;
public static class Pace
{
// D7: use ticks at the boundary so exactly 10% is eligible despite floating-point rounding.
// D7: use ticks at the boundary so exactly 2% is eligible despite floating-point rounding.
public static DateTimeOffset? ForecastStartsAt(LimitWindow window) =>
window.Length is { Ticks: > 0 } length && window.ResetsAt is { } reset
? reset - TimeSpan.FromTicks(length.Ticks - length.Ticks / 10) : null;
? reset - TimeSpan.FromTicks(length.Ticks - length.Ticks / 50) : null;
public static bool CanForecast(LimitWindow window, DateTimeOffset now, double threshold = 10) =>
CanForecast(window, now, Calculate(window, now, threshold));
+5 -2
View File
@@ -199,10 +199,13 @@ public sealed class RefreshEngine : IAsyncDisposable
var windows = History.LatestLimits(provider);
// Session totals follow an explicitly short limit window, never a week mislabeled primary.
var session = windows.FirstOrDefault(w => w.Length is { } length && length <= TimeSpan.FromHours(5));
var totals = History.Totals(provider, now, session);
// D9: the longest provider-wide limit defines the week; family limits do not.
var week = windows.Where(w => w.Length > TimeSpan.FromDays(1) && TokenWeights.Family(w) is null)
.OrderByDescending(w => w.Length).FirstOrDefault();
var totals = History.Totals(provider, now, session, clock.LocalTimeZone, week);
var state = statuses[provider];
var snapshots = windows.Select(w => new WindowSnapshot(w, Pace.Calculate(w, now, config.PaceThreshold))).ToArray();
providers.Add(new(provider, state.Status, state.Reason, snapshots, totals.Today, totals.Session, totals.Week));
providers.Add(new(provider, state.Status, state.Reason, snapshots, totals.Today, totals.Session, totals.Week, totals.WeekStart, totals.WeekWindow));
foreach (var window in snapshots)
if (state.Status == ProviderStatus.Available && popups.Observe(window.Window, window.Pace, config) is { } alert)
alerts.Add(alert);
+2 -1
View File
@@ -8,7 +8,8 @@ public sealed record WindowSnapshot(LimitWindow Window, PaceResult Pace)
public TimeSpan Age(DateTimeOffset now) => now - Window.SampleTime;
}
public sealed record ProviderSnapshot(Provider Provider, ProviderStatus Status, string? Reason,
IReadOnlyList<WindowSnapshot> Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week);
IReadOnlyList<WindowSnapshot> Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week, DateTimeOffset WeekStart = default,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? WeekWindow = null);
public sealed record Snapshot
{
// Keep this initializer for omitted properties in source-generated JSON (D9).