using FinalToken.Core; namespace FinalToken.Fleet; public static class FleetAnalysis { public static DashboardView Build(ServerConfig config, FleetState state, DateTimeOffset now) { var machines = config.Machines.Select(m => { var saved = state.Machines.SingleOrDefault(s => s.MachineId == m.Id); return new MachineView(m.Id, m.Label, m.OsUser, saved is not null && now - saved.SeenAt <= TimeSpan.FromSeconds(90), saved?.SeenAt, saved?.Report.Profiles.Where(p => m.Profiles.Any(b => b.Id == p.Id)).Select(p => p with { Usage = [], Samples = [], LegacyTokens = [] }).ToArray() ?? [], m.Profiles, saved?.Report.Profiles.Where(p => m.Profiles.Any(b => b.Id == p.Id)).Select(p => { var account = config.Accounts.Single(a => a.Id == m.Profiles.Single(b => b.Id == p.Id).AccountId); var usage = Reconcile(p.Usage, p.Provider, []); return new ProfileConsumption(p.Id, string.Equals(p.DataEmail, account.ExpectedEmail, StringComparison.OrdinalIgnoreCase) ? Sum(usage) : null, usage.Where(u => u.Session is not null).Select(u => u.Session).Distinct().Count()); }).ToArray() ?? []); }).ToArray(); var accounts = config.Accounts.Select(account => Account(account, config, state, now)).ToArray(); return new(now, accounts.OrderByDescending(a => a.Windows.Any(w => !w.Stale)).ToArray(), machines); } private static AccountView Account(AccountConfig account, ServerConfig config, FleetState state, DateTimeOffset now) { List warnings = []; var profiles = (from machine in config.Machines from binding in machine.Profiles where binding.AccountId == account.Id let saved = state.Machines.SingleOrDefault(s => s.MachineId == machine.Id) let profile = saved?.Report.Profiles.SingleOrDefault(p => p.Id == binding.Id) where profile is not null select (Machine: machine.Id, Profile: profile, Saved: saved!)).ToArray(); var verified = profiles.Where(p => p.Profile.Provider == account.Provider && string.Equals(p.Profile.DataEmail, account.ExpectedEmail, StringComparison.OrdinalIgnoreCase)).ToArray(); if (verified.Length != profiles.Length) warnings.Add("Unverified or mismatched profiles excluded from this account's analysis."); if (profiles.Any(p => p.Profile.Auth.State != "Healthy")) warnings.Add("One or more CLI logins need attention; previously attributed history is retained."); if (profiles.Length == 0) warnings.Add("No machine has reported this account yet."); if (verified.Any(p => p.Profile.CollectionError is not null)) warnings.Add("A collector failed; retained metadata may be incomplete or stale."); warnings.AddRange(verified.Select(p => p.Profile.CollectionNote).OfType()); if (verified.Select(p => (p.Profile.Settings.PaceThreshold,p.Profile.Settings.ProbeInterval)).Distinct().Count() > 1) warnings.Add("Profile analysis settings differ; each window uses the newest observation's source settings."); var records = verified.SelectMany(p => p.Profile.Usage).ToArray(); // D4/D14: compute cumulative increases before clipping, or the first post-cutoff // event would charge the already-imported pre-cutoff session total a second time. var allUsage = Reconcile(records, account.Provider, warnings); if (account.Provider == Provider.Codex && account.HistoryBefore is { } cutoff) { var uncertain = allUsage.GroupBy(u => u.Session).Where(g => g.Min(u => u.Time) >= cutoff) .Select(g => g.OrderBy(u => u.Time).First()).ToHashSet(); if (uncertain.Count > 0) warnings.Add("Migration baseline unknown for some Codex sessions: their first cumulative totals are omitted; consumption history is incomplete."); allUsage = allUsage.Where(u => !uncertain.Contains(u)).ToArray(); } var reconciled = allUsage.Where(u => account.HistoryBefore is null || u.Time >= account.HistoryBefore).ToArray(); List tokens = reconciled.Select(u => new ModelTokenPoint(Hour(u.Time), u.Model, u.Counts)).ToList(); if (account.HistoryBefore is { } before) { var legacy = verified.SingleOrDefault(p => p.Machine == account.LegacyMachine && p.Profile.Id == account.LegacyProfile).Profile; if (legacy is null) warnings.Add("Designated legacy history source is unavailable or unverified."); else tokens.AddRange(legacy.LegacyTokens.Where(t => t.Time < before)); warnings.Add("Before the migration cutoff, history uses one designated machine; cross-machine attribution is unavailable."); } tokens = tokens.GroupBy(t => (t.Time, t.Model)).Select(g => new ModelTokenPoint(g.Key.Time, g.Key.Model, g.Aggregate(new TokenCounts(), (sum, t) => sum + t.Counts))).OrderBy(t => t.Time).ToList(); var observations = verified.SelectMany(p => p.Profile.Samples).Distinct().ToArray(); List windows = []; foreach (var series in observations.GroupBy(WindowSeries.For)) { var window = series.OrderBy(w => w.SampleTime).ThenBy(w => w.Id, StringComparer.Ordinal).Last(); var owner = verified.Where(p => p.Profile.Samples.Contains(window)).OrderByDescending(p => p.Saved.SeenAt).First(); var stale = now - window.SampleTime > owner.Profile.Settings.ProbeInterval * 3 || owner.Profile.Auth.State != "Healthy" || !owner.Profile.Settings.For(account.Provider).Enabled || now - owner.Saved.SeenAt > TimeSpan.FromSeconds(90) || window.ResetsAt <= now; var settings = owner.Profile.Settings; if (settings.For(account.Provider).IsHidden(window)) continue; var pace = stale ? new PaceResult(PaceState.Unknown) : Pace.Calculate(window, now, settings.PaceThreshold); var forecast = stale ? null : LimitAnalysis.AverageUseAtReset(window, now, pace); var zone = TimeZoneInfo.FindSystemTimeZoneById(account.TimeZone); windows.Add(new(window, stale, pace, forecast, forecast is null ? null : 100 - forecast, stale ? null : LimitAnalysis.Recent(window, series, now, pace), stale ? null : LimitAnalysis.Analyze(window, series, tokens, now, zone), window.Length > TimeSpan.FromDays(1) ? LimitAnalysis.Resets(window, series, tokens, now.AddDays(-90), now, zone) : null)); } if (windows.Count == 0) warnings.Add("Provider allowance unknown. Token costs cannot establish subscription capacity."); if (windows.Any(w => w.Stale)) warnings.Add("Stale or expired allowance: forecasts withheld until a fresh CLI observation."); var costs = tokens.Select(t => (Point: t, Value: ApiPrices.Value(account.Provider, t.Model, t.Counts))).ToArray(); var priced = costs.Where(c => c.Value is not null).ToArray(); return new(account, windows.OrderByDescending(w => w.Window.Length).ToArray(), tokens, tokens.Aggregate(new TokenCounts(), (sum, t) => sum + t.Counts), priced.Length == 0 ? null : priced.Sum(c => c.Value!.Value), costs.Where(c => c.Value is null).Sum(c => c.Point.Counts.Total), warnings.Distinct().ToArray(), ApiPrices.CheckedOn, reconciled.Where(u => u.Session is not null).GroupBy(u => u.Session!).Select(g => new SessionConsumption(g.Key, Sum(g))) .OrderByDescending(s => s.Tokens.Total).ToArray(), verified.Length > 0); } private static TokenCounts Sum(IEnumerable events) => events.Aggregate(new TokenCounts(), (sum,u) => sum + u.Counts); private static IReadOnlyList Reconcile(IEnumerable records, Provider provider, List warnings) { List result = []; if (provider == Provider.Claude) { foreach (var group in records.GroupBy(u => u.Key)) { if (group.Select(u => (u.Time,u.Model,u.Counts)).Distinct().Count() != 1) { warnings.Add("Conflicting response metadata excluded; consumption is incomplete."); continue; } if (group.Select(u => u.Session).Distinct().Count() > 1) warnings.Add("Shared/resumed responses are assigned once to a stable session id; session attribution is approximate."); result.Add(group.OrderBy(u => u.Session, StringComparer.Ordinal).First()); } } else foreach (var session in records.GroupBy(u => u.Session)) { var previous = new TokenCounts(); foreach (var group in session.GroupBy(u => u.Time).OrderBy(g => g.Key)) { if (group.Select(u => (u.Model,u.Counts)).Distinct().Count() != 1) { warnings.Add("Conflicting session metadata excluded; consumption is incomplete."); continue; } var value = group.First(); result.Add(value with { Counts = value.Counts.IncreaseFrom(previous) }); previous = value.Counts; } } return result; } private static DateTimeOffset Hour(DateTimeOffset t) => new(t.UtcTicks - t.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero); }