core: add the solution, Core engine, CLI and tests

Core implements the CLI-only collectors for Claude and Codex (D2 to D4),
the history store (D5), the refresh engine (D6), pace and popup
decisions (D7, D8), the snapshot contract (D9) and the Stream Deck
installer contract (D11). finaltoken status runs one refresh and prints
the snapshot. The app and plugin projects are placeholders so the
solution file is complete before they are built in parallel.

Refs #1
This commit is contained in:
Florian Schmidt
2026-10-14 19:09:54 +02:00
parent db890c5f68
commit 14223b05df
60 changed files with 2287 additions and 0 deletions
+230
View File
@@ -0,0 +1,230 @@
using FinalToken.Core.Collectors;
using FinalToken.Core.Processes;
namespace FinalToken.Core;
/// <summary>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.</summary>
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 IncrementalScanner scanner;
private readonly LimitProbe probe;
private readonly Func<Provider, string?, CliDiscoveryResult> discover;
private readonly PopupDecider popups = new();
private readonly Dictionary<Provider, DateTimeOffset> lastProbe = [];
private readonly Dictionary<Provider, (ProviderStatus Status, string? Reason)> statuses = [];
private readonly HashSet<Provider> pendingProbe = [];
private readonly List<FileSystemWatcher> 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<Provider, string?, CliDiscoveryResult>? cliDiscovery = null)
{
directory = dataDirectory ?? DataPaths.DataDirectory;
Directory.CreateDirectory(directory);
clock = timeProvider ?? TimeProvider.System;
Diagnostics = new(clock);
settings = SettingsFile.Load(directory, Diagnostics);
History = new(directory, Diagnostics);
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;
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<Diagnostic> RecentDiagnostics => Diagnostics.Recent;
public event Action<Snapshot>? SnapshotChanged;
public event Action<PopupEvent>? 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<Snapshot> 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);
}
/// <summary>One scheduler tick, also usable with a fake TimeProvider. Changes debounce for two seconds.</summary>
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 (Exception e) when (e is IOException or UnauthorizedAccessException)
{ Diagnostics.Add(null, "refresh-write", "Refresh could not persist files."); }
} while (await timer.WaitForNextTickAsync(token));
}
private async Task<Snapshot> 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<ProviderSnapshot> providers = [];
List<PopupEvent> 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));
var totals = History.Totals(provider, now, session);
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));
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 };
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<T>(Action<T>? handlers, T value)
{
if (handlers is null) return;
foreach (var handler in handlers.GetInvocationList().Cast<Action<T>>())
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<Action>())
try { handler(); } catch (Exception) { Diagnostics.Add(null, "event-handler", "A host event handler failed."); }
}
public async ValueTask DisposeAsync() => await StopAsync();
}