using FinalToken.Core.Collectors;
using FinalToken.Core.Processes;
namespace FinalToken.Core;
/// Shared app/CLI host (D6). Caller holds StoreLock. SnapshotChanged, PopupRequested,
/// ActivationRequested run on worker threads, never the caller's UI synchronization context.
/// UI hosts must marshal events. History query results are safe copies.
public sealed class RefreshEngine : IAsyncDisposable
{
private readonly SemaphoreSlim refreshGate = new(1, 1);
private readonly SemaphoreSlim lifecycleGate = new(1, 1);
private readonly string directory;
private readonly TimeProvider clock;
private readonly string? appPath;
private readonly IncrementalScanner scanner;
private readonly LimitProbe probe;
private readonly Func discover;
private readonly PopupDecider popups = new();
private readonly Dictionary lastProbe = [];
private readonly Dictionary statuses = [];
private readonly HashSet pendingProbe = [];
private readonly List watchers = [];
private CancellationTokenSource? lifetime = new();
private Task? loop;
private Snapshot? current;
private Settings settings;
private long changedTicks;
private DateTimeOffset lastRefresh = DateTimeOffset.MinValue;
private string? activation;
public RefreshEngine(string? dataDirectory = null, TimeProvider? timeProvider = null, IProcessRunner? processRunner = null,
string? claudeDirectory = null, string? codexDirectory = null,
Func? cliDiscovery = null, string? appPath = null)
{
directory = dataDirectory ?? DataPaths.DataDirectory;
Directory.CreateDirectory(directory);
clock = timeProvider ?? TimeProvider.System;
Diagnostics = new(clock);
settings = SettingsFile.Load(directory, Diagnostics);
History = new(directory, Diagnostics, clock);
ClaudeDirectory = claudeDirectory ?? DataPaths.ClaudeDirectory;
CodexDirectory = codexDirectory ?? DataPaths.CodexDirectory;
scanner = new(History, Diagnostics, ClaudeDirectory, CodexDirectory);
probe = new(processRunner ?? new ProcessRunner(clock), Diagnostics, directory);
discover = cliDiscovery ?? ((provider, path) => CliDiscovery.Find(provider, path));
current = SnapshotFile.Read(directory, clock.GetUtcNow()).Snapshot;
this.appPath = appPath ?? current?.AppPath;
activation = ActivationFile.ReadRequest(directory);
}
public string DataDirectory => directory;
public string ClaudeDirectory { get; }
public string CodexDirectory { get; }
public Snapshot? CurrentSnapshot => Volatile.Read(ref current);
public Settings Settings => Volatile.Read(ref settings);
public HistoryStore History { get; }
public DiagnosticLog Diagnostics { get; }
public IReadOnlyList RecentDiagnostics => Diagnostics.Recent;
public event Action? SnapshotChanged;
public event Action? PopupRequested;
public event Action? ActivationRequested;
public Task UpdateSettingsAsync(Settings value, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
await refreshGate.WaitAsync(cancellationToken);
try
{
await SettingsFile.SaveAsync(directory, value, cancellationToken);
Volatile.Write(ref settings, value);
}
finally { refreshGate.Release(); }
}, cancellationToken);
public async Task StartAsync(CancellationToken cancellationToken = default)
{
await lifecycleGate.WaitAsync(cancellationToken);
try
{
if (loop is not null) return;
lifetime ??= new();
foreach (var path in new[] { Path.Combine(ClaudeDirectory, "projects"), Path.Combine(CodexDirectory, "sessions"), Path.Combine(CodexDirectory, "archived_sessions") })
{
if (!Directory.Exists(path)) continue;
var watcher = new FileSystemWatcher(path, "*.jsonl") { IncludeSubdirectories = true };
watcher.Changed += (_, _) => NotifySourceChanged();
watcher.Created += (_, _) => NotifySourceChanged();
watcher.Deleted += (_, _) => NotifySourceChanged();
watcher.Renamed += (_, _) => NotifySourceChanged();
watcher.Error += (_, _) => { Diagnostics.Add(null, "watcher", "File watcher failed; periodic scans continue."); NotifySourceChanged(); };
watcher.EnableRaisingEvents = true;
watchers.Add(watcher);
}
loop = Task.Run(() => RunLoopAsync(lifetime.Token), CancellationToken.None);
}
finally { lifecycleGate.Release(); }
}
public async Task StopAsync()
{
await lifecycleGate.WaitAsync();
try
{
foreach (var watcher in watchers) watcher.Dispose();
watchers.Clear();
if (lifetime is not null) await lifetime.CancelAsync();
if (loop is not null)
try { await loop; } catch (OperationCanceledException) { }
// Also wait for any manually requested refresh, which shares the lifetime token.
await refreshGate.WaitAsync();
refreshGate.Release();
lifetime?.Dispose();
lifetime = null;
loop = null;
}
finally { lifecycleGate.Release(); }
}
public void NotifySourceChanged() => Interlocked.Exchange(ref changedTicks, clock.GetUtcNow().UtcTicks);
public Task RefreshNowAsync(bool noProbe = false, CancellationToken cancellationToken = default)
{
var shutdown = lifetime?.Token ?? CancellationToken.None;
return Task.Run(async () =>
{
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, shutdown);
return await RefreshAsync(noProbe, linked.Token);
}, cancellationToken);
}
/// One scheduler tick, also usable with a fake TimeProvider. Changes debounce for two seconds.
public Task TickAsync(CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var request = ActivationFile.ReadRequest(directory);
if (request is not null && request != activation) { activation = request; Dispatch(ActivationRequested); }
var now = clock.GetUtcNow();
var changes = Interlocked.Read(ref changedTicks);
if (now - lastRefresh >= Settings.RefreshInterval || changes > 0 && now.UtcTicks - changes >= TimeSpan.FromSeconds(2).Ticks)
{
Interlocked.CompareExchange(ref changedTicks, 0, changes);
await RefreshAsync(false, cancellationToken);
}
}, cancellationToken);
private async Task RunLoopAsync(CancellationToken token)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1), clock);
do
{
try { await TickAsync(token); }
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
// D6: isolate a failed tick, including a malformed stored partition, and retry.
catch (Exception)
{ Diagnostics.Add(null, "refresh-failed", "Refresh failed; the scheduler will retry."); }
} while (await timer.WaitForNextTickAsync(token));
}
private async Task RefreshAsync(bool noProbe, CancellationToken token)
{
await refreshGate.WaitAsync(token);
try
{
var config = Settings;
var scan = await scanner.ScanAsync(token, config.Claude.Enabled, config.Codex.Enabled);
if (scan.ClaudeAdded > 0) pendingProbe.Add(Provider.Claude);
if (scan.CodexAdded > 0) pendingProbe.Add(Provider.Codex);
var now = clock.GetUtcNow();
List providers = [];
List alerts = [];
foreach (var provider in new[] { Provider.Claude, Provider.Codex })
{
var providerSettings = config.For(provider);
if (!providerSettings.Enabled) statuses[provider] = (ProviderStatus.Disabled, "Disabled in settings.");
else
{
var cli = discover(provider, providerSettings.CliPath);
if (cli.Command is null) statuses[provider] = (ProviderStatus.Unavailable, cli.Reason);
else
{
if (!statuses.ContainsKey(provider) || statuses[provider].Status == ProviderStatus.Disabled)
statuses[provider] = (ProviderStatus.Available, null);
var previousProbe = lastProbe.GetValueOrDefault(provider, DateTimeOffset.MinValue);
var since = now - previousProbe;
if (!noProbe && since >= TimeSpan.FromMinutes(1) && (since >= config.ProbeInterval || pendingProbe.Contains(provider)))
{
lastProbe[provider] = now;
pendingProbe.Remove(provider);
var result = await probe.RunAsync(provider, cli.Command, now, token);
if (result.Success)
{
History.AddLimits(result.Windows);
statuses[provider] = (ProviderStatus.Available, null);
}
else
{
if (provider == Provider.Codex && scan.CodexFallback.Count > 0)
statuses[provider] = (ProviderStatus.Available, "Probe failed; using rollout limits.");
else statuses[provider] = (ProviderStatus.Unavailable, result.Reason);
}
}
}
}
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));
// 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, 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);
}
var snapshot = new Snapshot { MadeAt = clock.GetUtcNow(), RefreshInterval = config.RefreshInterval,
Providers = providers, AppPath = appPath };
await History.SaveAsync(token);
await SnapshotFile.WriteAsync(directory, snapshot, token);
Volatile.Write(ref current, snapshot);
lastRefresh = clock.GetUtcNow();
Dispatch(SnapshotChanged, snapshot);
foreach (var alert in alerts) Dispatch(PopupRequested, alert);
return snapshot;
}
finally { refreshGate.Release(); }
}
private void Dispatch(Action? handlers, T value)
{
if (handlers is null) return;
foreach (var handler in handlers.GetInvocationList().Cast>())
try { handler(value); } catch (Exception) { Diagnostics.Add(null, "event-handler", "A host event handler failed."); }
}
private void Dispatch(Action? handlers)
{
if (handlers is null) return;
foreach (var handler in handlers.GetInvocationList().Cast())
try { handler(); } catch (Exception) { Diagnostics.Add(null, "event-handler", "A host event handler failed."); }
}
public async ValueTask DisposeAsync() => await StopAsync();
}