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:
@@ -0,0 +1,124 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace FinalToken.Core.Collectors;
|
||||
|
||||
public sealed record ScanResult(int AddedEvents, IReadOnlyList<LimitWindow> CodexFallback,
|
||||
int ClaudeAdded = 0, int CodexAdded = 0);
|
||||
|
||||
/// <summary>Only opens transcript/rollout jsonl paths. Offsets advance through complete lines only.
|
||||
/// Prefix and consumed-tail fingerprints detect replacements without rereading whole files.</summary>
|
||||
public sealed class IncrementalScanner(HistoryStore history, DiagnosticLog diagnostics,
|
||||
string claudeDirectory, string codexDirectory)
|
||||
{
|
||||
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
|
||||
public async Task<ScanResult> ScanAsync(CancellationToken cancellationToken = default,
|
||||
bool claudeEnabled = true, bool codexEnabled = true)
|
||||
{
|
||||
var added = 0;
|
||||
var claudeFiles = claudeEnabled ? FindFiles(Path.Combine(claudeDirectory, "projects"), "*.jsonl", Provider.Claude) : [];
|
||||
foreach (var path in claudeFiles)
|
||||
added += await ScanFileAsync(path, Provider.Claude, [], cancellationToken);
|
||||
var claudeAdded = added;
|
||||
var codexFiles = !codexEnabled ? [] : FindFiles(Path.Combine(codexDirectory, "sessions"), "rollout-*.jsonl", Provider.Codex)
|
||||
.Concat(FindFiles(Path.Combine(codexDirectory, "archived_sessions"), "rollout-*.jsonl", Provider.Codex))
|
||||
.OrderBy(File.GetLastWriteTimeUtc).ToArray();
|
||||
// D4 fallback belongs to the newest rollout, even when it had no appended bytes this time.
|
||||
var latest = codexFiles.LastOrDefault();
|
||||
List<LimitWindow> fallback = [];
|
||||
foreach (var path in codexFiles)
|
||||
{
|
||||
List<LimitWindow> limits = [];
|
||||
added += await ScanFileAsync(path, Provider.Codex, limits, cancellationToken);
|
||||
if (path == latest && limits.Count > 0) fallback = limits;
|
||||
}
|
||||
if (latest is not null && fallback.Count == 0) fallback = history.Cursor(latest).LatestLimits;
|
||||
return new(added, fallback, claudeAdded, added - claudeAdded);
|
||||
}
|
||||
private IReadOnlyList<string> FindFiles(string directory, string pattern, Provider provider)
|
||||
{
|
||||
try { return Directory.Exists(directory) ? Directory.GetFiles(directory, pattern, SearchOption.AllDirectories) : []; }
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
|
||||
{ diagnostics.Add(provider, "scan-directory", "Source directory cannot be enumerated."); return []; }
|
||||
}
|
||||
private async Task<int> ScanFileAsync(string path, Provider provider, List<LimitWindow> latestLimits, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete,
|
||||
65536, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
var cursor = history.Cursor(path);
|
||||
var creation = File.GetCreationTimeUtc(path).Ticks;
|
||||
if (stream.Length < cursor.Offset || cursor.CreationTicks != creation ||
|
||||
cursor.PrefixHash != Fingerprint(stream, 0, cursor.PrefixLength) ||
|
||||
cursor.TailHash != Fingerprint(stream, Math.Max(0, cursor.Offset - 256), (int)Math.Min(256, cursor.Offset)))
|
||||
{
|
||||
cursor.Offset = 0;
|
||||
cursor.SessionId = Path.GetFileNameWithoutExtension(path);
|
||||
cursor.Model = null;
|
||||
cursor.Project = null;
|
||||
cursor.LatestLimits = [];
|
||||
}
|
||||
var added = 0;
|
||||
stream.Position = cursor.Offset;
|
||||
var readBuffer = new byte[65536];
|
||||
using var line = new MemoryStream();
|
||||
var consumed = cursor.Offset;
|
||||
int read;
|
||||
while ((read = await stream.ReadAsync(readBuffer, cancellationToken)) > 0)
|
||||
{
|
||||
for (var i = 0; i < read; i++)
|
||||
{
|
||||
consumed++;
|
||||
if (readBuffer[i] != (byte)'\n')
|
||||
{
|
||||
line.WriteByte(readBuffer[i]);
|
||||
continue;
|
||||
}
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Source entries can contain large tool results. An output-capture bound
|
||||
// belongs to child processes, not to valid transcript records (D3).
|
||||
{
|
||||
try
|
||||
{
|
||||
var text = StrictUtf8.GetString(line.GetBuffer(), 0, (int)line.Length).TrimEnd('\r');
|
||||
if (text.Length > 0 && provider == Provider.Claude)
|
||||
{
|
||||
if (TranscriptParser.Parse(text, diagnostics) is { } usage && history.Add(usage)) added++;
|
||||
}
|
||||
else if (text.Length > 0)
|
||||
{
|
||||
var entry = RolloutParser.Parse(text, cursor, DateTimeOffset.UtcNow, diagnostics);
|
||||
if (entry.CumulativeUsage is { } usage && history.AddCodex(cursor.SessionId!, usage)) added++;
|
||||
if (entry.Limits.Count > 0)
|
||||
{
|
||||
latestLimits.Clear(); latestLimits.AddRange(entry.Limits);
|
||||
cursor.LatestLimits = entry.Limits.ToList();
|
||||
}
|
||||
history.AddLimits(entry.Limits);
|
||||
}
|
||||
}
|
||||
catch (DecoderFallbackException) { diagnostics.Add(provider, "scan-encoding", "Invalid UTF-8 source line skipped."); }
|
||||
}
|
||||
cursor.Offset = consumed;
|
||||
line.SetLength(0);
|
||||
}
|
||||
}
|
||||
cursor.CreationTicks = creation;
|
||||
cursor.PrefixLength = (int)Math.Min(256, cursor.Offset);
|
||||
cursor.PrefixHash = Fingerprint(stream, 0, cursor.PrefixLength);
|
||||
cursor.TailHash = Fingerprint(stream, Math.Max(0, cursor.Offset - 256), (int)Math.Min(256, cursor.Offset));
|
||||
return added;
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
|
||||
{ diagnostics.Add(provider, "scan-file", "Source file cannot be read."); return 0; }
|
||||
}
|
||||
private static string Fingerprint(FileStream stream, long offset, int length)
|
||||
{
|
||||
if (length == 0) return "";
|
||||
stream.Position = offset;
|
||||
var bytes = new byte[length];
|
||||
var count = stream.ReadAtLeast(bytes, length, false);
|
||||
return Convert.ToHexString(SHA256.HashData(bytes.AsSpan(0, count)));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user