From 14223b05df6fde7f2d6c22f5f0e9d3278f3bd899 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Wed, 14 Oct 2026 19:09:54 +0200 Subject: [PATCH] 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 --- .editorconfig | 16 ++ .gitignore | 8 + Directory.Build.props | 17 ++ Directory.Packages.props | 8 + FinalToken.slnx | 14 ++ global.json | 4 + src/FinalToken.App/AGENTS.md | 4 + src/FinalToken.App/CLAUDE.md | 1 + src/FinalToken.App/FinalToken.App.csproj | 8 + src/FinalToken.App/Program.cs | 1 + src/FinalToken.Cli/AGENTS.md | 4 + src/FinalToken.Cli/CLAUDE.md | 1 + src/FinalToken.Cli/CliApplication.cs | 52 ++++ src/FinalToken.Cli/FinalToken.Cli.csproj | 8 + src/FinalToken.Cli/Program.cs | 3 + src/FinalToken.Core/AGENTS.md | 21 ++ src/FinalToken.Core/AtomicFile.cs | 51 ++++ src/FinalToken.Core/CLAUDE.md | 1 + .../Collectors/ClaudeUsageParser.cs | 61 +++++ .../Collectors/IncrementalScanner.cs | 124 ++++++++++ src/FinalToken.Core/Collectors/JsonFields.cs | 33 +++ src/FinalToken.Core/Collectors/LimitProbe.cs | 30 +++ .../Collectors/RolloutParser.cs | 88 +++++++ .../Collectors/TranscriptParser.cs | 25 ++ src/FinalToken.Core/FinalToken.Core.csproj | 1 + src/FinalToken.Core/HistoryStore.cs | 160 ++++++++++++ src/FinalToken.Core/Model.cs | 52 ++++ src/FinalToken.Core/Pace.cs | 49 ++++ src/FinalToken.Core/Processes/CliDiscovery.cs | 77 ++++++ .../Processes/ProcessRunner.cs | 108 ++++++++ src/FinalToken.Core/RefreshEngine.cs | 230 ++++++++++++++++++ src/FinalToken.Core/Settings.cs | 64 +++++ src/FinalToken.Core/Snapshot.cs | 46 ++++ src/FinalToken.Core/StreamDeck/Installer.cs | 29 +++ src/FinalToken.StreamDeck/AGENTS.md | 4 + src/FinalToken.StreamDeck/CLAUDE.md | 1 + .../FinalToken.StreamDeck.csproj | 7 + src/FinalToken.StreamDeck/Program.cs | 1 + tests/FinalToken.App.Tests/AGENTS.md | 4 + tests/FinalToken.App.Tests/CLAUDE.md | 1 + .../FinalToken.App.Tests.csproj | 12 + .../FinalToken.App.Tests/PlaceholderTests.cs | 3 + tests/FinalToken.Cli.Tests/AGENTS.md | 4 + tests/FinalToken.Cli.Tests/CLAUDE.md | 1 + tests/FinalToken.Cli.Tests/CliTests.cs | 69 ++++++ .../FinalToken.Cli.Tests.csproj | 12 + tests/FinalToken.Core.Tests/AGENTS.md | 4 + tests/FinalToken.Core.Tests/CLAUDE.md | 1 + .../DiscoveryAndPolicyTests.cs | 72 ++++++ tests/FinalToken.Core.Tests/EngineTests.cs | 160 ++++++++++++ .../FinalToken.Core.Tests.csproj | 12 + tests/FinalToken.Core.Tests/PaceTests.cs | 73 ++++++ tests/FinalToken.Core.Tests/ParserTests.cs | 107 ++++++++ tests/FinalToken.Core.Tests/ProcessTests.cs | 39 +++ tests/FinalToken.Core.Tests/StorageTests.cs | 190 +++++++++++++++ tests/FinalToken.Core.Tests/TestSupport.cs | 91 +++++++ tests/FinalToken.StreamDeck.Tests/AGENTS.md | 4 + tests/FinalToken.StreamDeck.Tests/CLAUDE.md | 1 + .../FinalToken.StreamDeck.Tests.csproj | 12 + .../PlaceholderTests.cs | 3 + 60 files changed, 2287 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 Directory.Build.props create mode 100644 Directory.Packages.props create mode 100644 FinalToken.slnx create mode 100644 global.json create mode 100644 src/FinalToken.App/AGENTS.md create mode 100644 src/FinalToken.App/CLAUDE.md create mode 100644 src/FinalToken.App/FinalToken.App.csproj create mode 100644 src/FinalToken.App/Program.cs create mode 100644 src/FinalToken.Cli/AGENTS.md create mode 100644 src/FinalToken.Cli/CLAUDE.md create mode 100644 src/FinalToken.Cli/CliApplication.cs create mode 100644 src/FinalToken.Cli/FinalToken.Cli.csproj create mode 100644 src/FinalToken.Cli/Program.cs create mode 100644 src/FinalToken.Core/AGENTS.md create mode 100644 src/FinalToken.Core/AtomicFile.cs create mode 100644 src/FinalToken.Core/CLAUDE.md create mode 100644 src/FinalToken.Core/Collectors/ClaudeUsageParser.cs create mode 100644 src/FinalToken.Core/Collectors/IncrementalScanner.cs create mode 100644 src/FinalToken.Core/Collectors/JsonFields.cs create mode 100644 src/FinalToken.Core/Collectors/LimitProbe.cs create mode 100644 src/FinalToken.Core/Collectors/RolloutParser.cs create mode 100644 src/FinalToken.Core/Collectors/TranscriptParser.cs create mode 100644 src/FinalToken.Core/FinalToken.Core.csproj create mode 100644 src/FinalToken.Core/HistoryStore.cs create mode 100644 src/FinalToken.Core/Model.cs create mode 100644 src/FinalToken.Core/Pace.cs create mode 100644 src/FinalToken.Core/Processes/CliDiscovery.cs create mode 100644 src/FinalToken.Core/Processes/ProcessRunner.cs create mode 100644 src/FinalToken.Core/RefreshEngine.cs create mode 100644 src/FinalToken.Core/Settings.cs create mode 100644 src/FinalToken.Core/Snapshot.cs create mode 100644 src/FinalToken.Core/StreamDeck/Installer.cs create mode 100644 src/FinalToken.StreamDeck/AGENTS.md create mode 100644 src/FinalToken.StreamDeck/CLAUDE.md create mode 100644 src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj create mode 100644 src/FinalToken.StreamDeck/Program.cs create mode 100644 tests/FinalToken.App.Tests/AGENTS.md create mode 100644 tests/FinalToken.App.Tests/CLAUDE.md create mode 100644 tests/FinalToken.App.Tests/FinalToken.App.Tests.csproj create mode 100644 tests/FinalToken.App.Tests/PlaceholderTests.cs create mode 100644 tests/FinalToken.Cli.Tests/AGENTS.md create mode 100644 tests/FinalToken.Cli.Tests/CLAUDE.md create mode 100644 tests/FinalToken.Cli.Tests/CliTests.cs create mode 100644 tests/FinalToken.Cli.Tests/FinalToken.Cli.Tests.csproj create mode 100644 tests/FinalToken.Core.Tests/AGENTS.md create mode 100644 tests/FinalToken.Core.Tests/CLAUDE.md create mode 100644 tests/FinalToken.Core.Tests/DiscoveryAndPolicyTests.cs create mode 100644 tests/FinalToken.Core.Tests/EngineTests.cs create mode 100644 tests/FinalToken.Core.Tests/FinalToken.Core.Tests.csproj create mode 100644 tests/FinalToken.Core.Tests/PaceTests.cs create mode 100644 tests/FinalToken.Core.Tests/ParserTests.cs create mode 100644 tests/FinalToken.Core.Tests/ProcessTests.cs create mode 100644 tests/FinalToken.Core.Tests/StorageTests.cs create mode 100644 tests/FinalToken.Core.Tests/TestSupport.cs create mode 100644 tests/FinalToken.StreamDeck.Tests/AGENTS.md create mode 100644 tests/FinalToken.StreamDeck.Tests/CLAUDE.md create mode 100644 tests/FinalToken.StreamDeck.Tests/FinalToken.StreamDeck.Tests.csproj create mode 100644 tests/FinalToken.StreamDeck.Tests/PlaceholderTests.cs diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..7b4cb48 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{json,xml,csproj,props,slnx}] +indent_size = 2 + +[*.cs] +csharp_style_namespace_declarations = file_scoped:warning +dotnet_sort_system_directives_first = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8e2e04c --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +artifacts/ +**/bin/ +**/obj/ +.vs/ +.idea/ +*.user +*.suo +TestResults/ diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..bf5bb9a --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,17 @@ + + + net10.0 + 14 + enable + enable + true + true + true + true + true + false + + $(MSBuildThisFileDirectory)artifacts/bin/$(MSBuildProjectName)/ + $(MSBuildThisFileDirectory)artifacts/obj/$(MSBuildProjectName)/ + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..8afd472 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,8 @@ + + + true + + + + + diff --git a/FinalToken.slnx b/FinalToken.slnx new file mode 100644 index 0000000..530ee06 --- /dev/null +++ b/FinalToken.slnx @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/global.json b/global.json new file mode 100644 index 0000000..3a426e7 --- /dev/null +++ b/global.json @@ -0,0 +1,4 @@ +{ + "sdk": { "version": "10.0.100", "rollForward": "latestFeature" }, + "test": { "runner": "Microsoft.Testing.Platform" } +} diff --git a/src/FinalToken.App/AGENTS.md b/src/FinalToken.App/AGENTS.md new file mode 100644 index 0000000..6f572b6 --- /dev/null +++ b/src/FinalToken.App/AGENTS.md @@ -0,0 +1,4 @@ +# App +Buildable placeholder only. W2 replaces Program.cs and this guidance with the Avalonia host (D8). +Use RefreshEngine and source-generated snapshot DTOs from Core. Marshal Core events to the UI. +Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. diff --git a/src/FinalToken.App/CLAUDE.md b/src/FinalToken.App/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/src/FinalToken.App/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/FinalToken.App/FinalToken.App.csproj b/src/FinalToken.App/FinalToken.App.csproj new file mode 100644 index 0000000..9dda08d --- /dev/null +++ b/src/FinalToken.App/FinalToken.App.csproj @@ -0,0 +1,8 @@ + + + Exe + FinalToken + true + + + diff --git a/src/FinalToken.App/Program.cs b/src/FinalToken.App/Program.cs new file mode 100644 index 0000000..d46ab8e --- /dev/null +++ b/src/FinalToken.App/Program.cs @@ -0,0 +1 @@ +Console.WriteLine("FinalToken app placeholder; W2 supplies the Avalonia host."); diff --git a/src/FinalToken.Cli/AGENTS.md b/src/FinalToken.Cli/AGENTS.md new file mode 100644 index 0000000..4d7979a --- /dev/null +++ b/src/FinalToken.Cli/AGENTS.md @@ -0,0 +1,4 @@ +# CLI +NativeAOT console host for D1, D5, D6 and D9. Exit codes: success 0, failure 1, usage 2. +A busy store is read-only. Keep argument parsing in CliApplication for tests. +Run `dotnet test --project tests/FinalToken.Cli.Tests -c Release` from the root. diff --git a/src/FinalToken.Cli/CLAUDE.md b/src/FinalToken.Cli/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/src/FinalToken.Cli/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/FinalToken.Cli/CliApplication.cs b/src/FinalToken.Cli/CliApplication.cs new file mode 100644 index 0000000..3517cb6 --- /dev/null +++ b/src/FinalToken.Cli/CliApplication.cs @@ -0,0 +1,52 @@ +using System.Globalization; +using System.Text.Json; +using FinalToken.Core; + +namespace FinalToken.Cli; + +public static class CliApplication +{ + public static async Task RunAsync(string[] args, TextWriter output, TextWriter error, + string? dataDirectory = null, Func? engineFactory = null, CancellationToken cancellationToken = default) + { + if (args.Length == 0 || args[0] != "status" || args.Skip(1).Any(a => a is not ("--json" or "--no-probe")) || + args.Skip(1).Distinct().Count() != args.Length - 1) + { await error.WriteLineAsync("Usage: finaltoken status [--json] [--no-probe]"); return 2; } + try + { + var directory = dataDirectory ?? DataPaths.DataDirectory; + using var storeLock = StoreLock.TryAcquire(directory); + Snapshot snapshot; + if (storeLock is null) + { + await error.WriteLineAsync("Store is in use; reading the existing snapshot without refreshing."); + var result = SnapshotFile.Read(directory); + if (result.Snapshot is not { } existing) { await error.WriteLineAsync(result.Error); return 1; } + if (result.IsStale) await error.WriteLineAsync("Snapshot is stale."); + snapshot = existing; + } + else + { + await using var engine = engineFactory?.Invoke(directory) ?? new RefreshEngine(directory); + snapshot = await engine.RefreshNowAsync(args.Contains("--no-probe"), cancellationToken); + foreach (var diagnostic in engine.RecentDiagnostics) + await error.WriteLineAsync($"{diagnostic.Code}: {diagnostic.Summary}"); + } + if (args.Contains("--json")) await output.WriteLineAsync(JsonSerializer.Serialize(snapshot, CoreJsonContext.Default.Snapshot)); + else + { + await output.WriteLineAsync($"FinalToken {snapshot.MadeAt:O}"); + foreach (var provider in snapshot.Providers) + { + 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}"); + 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}")); + } + } + return 0; + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException or OperationCanceledException) + { await error.WriteLineAsync("FinalToken could not complete the refresh or read the snapshot."); return 1; } + } +} diff --git a/src/FinalToken.Cli/FinalToken.Cli.csproj b/src/FinalToken.Cli/FinalToken.Cli.csproj new file mode 100644 index 0000000..6b008f4 --- /dev/null +++ b/src/FinalToken.Cli/FinalToken.Cli.csproj @@ -0,0 +1,8 @@ + + + Exe + finaltoken + true + + + diff --git a/src/FinalToken.Cli/Program.cs b/src/FinalToken.Cli/Program.cs new file mode 100644 index 0000000..1aa4cee --- /dev/null +++ b/src/FinalToken.Cli/Program.cs @@ -0,0 +1,3 @@ +using FinalToken.Cli; + +return await CliApplication.RunAsync(args, Console.Out, Console.Error); diff --git a/src/FinalToken.Core/AGENTS.md b/src/FinalToken.Core/AGENTS.md new file mode 100644 index 0000000..e2ba3fc --- /dev/null +++ b/src/FinalToken.Core/AGENTS.md @@ -0,0 +1,21 @@ +# Core +UI-free domain and file/CLI integration. Implements D1–D7, D9 and the D11 installer contract. +Keep parsers total. Only metadata leaves them. JSON uses CoreJsonContext. Hosts own StoreLock. +Events from RefreshEngine run on a worker thread; UI hosts must marshal them. +Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root. + +## Host contract + +- Acquire `StoreLock.TryAcquire(dataDirectory)` before creating a writing engine. A busy app calls + `ActivationFile.RequestAsync` and exits; a busy CLI uses `SnapshotFile.Read`. +- Construct `RefreshEngine`, subscribe to `SnapshotChanged`, `PopupRequested` and + `ActivationRequested`, then `StartAsync`. `StopAsync` cancels and waits. Dispose asynchronously. +- 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 + reset and length of a known short limit. Hourly storage includes whole boundary hours (D5). +- `SnapshotFile.Read` returns a DTO, staleness and a metadata-only error. Serialize with + `CoreJsonContext.Default.Snapshot`. `WindowSnapshot.Window` holds the limit; `.Pace` holds D7. +- W3 owns `StreamDeck/`: `IPluginInstaller`, `PluginInstallStatus`, `InstallPolicy` and its stub. + No shipped production dependency is needed in Core. Source parsers use temporary memory for one + complete line; memory usage therefore scales with the largest transcript entry. diff --git a/src/FinalToken.Core/AtomicFile.cs b/src/FinalToken.Core/AtomicFile.cs new file mode 100644 index 0000000..8b9e72c --- /dev/null +++ b/src/FinalToken.Core/AtomicFile.cs @@ -0,0 +1,51 @@ +using System.Text; + +namespace FinalToken.Core; + +public static class AtomicFile +{ + // D5: same-directory rename; a reader sees either complete version. + public static async Task WriteAsync(string path, string contents, CancellationToken cancellationToken = default) + { + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!); + var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + await using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None, + 4096, FileOptions.Asynchronous | FileOptions.WriteThrough)) + { + await stream.WriteAsync(Encoding.UTF8.GetBytes(contents), cancellationToken); + await stream.FlushAsync(cancellationToken); + stream.Flush(true); + } + cancellationToken.ThrowIfCancellationRequested(); + File.Move(temporary, path, true); + } + finally { if (File.Exists(temporary)) File.Delete(temporary); } + } +} + +/// The host must hold this for the entire lifetime of a writing HistoryStore/RefreshEngine (D5). +public sealed class StoreLock : IDisposable +{ + private readonly FileStream stream; + private StoreLock(FileStream stream) => this.stream = stream; + public static StoreLock? TryAcquire(string directory) + { + Directory.CreateDirectory(directory); + try { return new(new FileStream(Path.Combine(directory, "store.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)); } + catch (IOException) { return null; } + } + public void Dispose() => stream.Dispose(); +} + +public static class ActivationFile +{ + public static Task RequestAsync(string directory, CancellationToken cancellationToken = default) => + AtomicFile.WriteAsync(Path.Combine(directory, "activate.request"), Guid.NewGuid().ToString("N"), cancellationToken); + public static string? ReadRequest(string directory) + { + try { return File.ReadAllText(Path.Combine(directory, "activate.request")); } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return null; } + } +} diff --git a/src/FinalToken.Core/CLAUDE.md b/src/FinalToken.Core/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/src/FinalToken.Core/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/FinalToken.Core/Collectors/ClaudeUsageParser.cs b/src/FinalToken.Core/Collectors/ClaudeUsageParser.cs new file mode 100644 index 0000000..beaade7 --- /dev/null +++ b/src/FinalToken.Core/Collectors/ClaudeUsageParser.cs @@ -0,0 +1,61 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace FinalToken.Core.Collectors; + +public static partial class ClaudeUsageParser +{ + [GeneratedRegex(@"^Current (?