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 (?