Files
FinalToken/src/FinalToken.Core/Collectors/IncrementalScanner.cs
T
Florian Schmidt c2f97e9384 core: write only new history and share files on Windows
The store rewrote all of history.json, 19 MB here, on every 60 s
refresh. It now appends each refresh's changes to a journal and compacts
into monthly files and a state checkpoint at 8 MiB, so an idle refresh
writes only snapshot.json. Bucket updates are keyed, unchanged limit
samples are kept at most hourly, Codex replays are bounded by session
totals, and Claude dedupe keys expire after 60 days.

Readers of atomically replaced files allow delete sharing, and the
replace retries briefly, so the Stream Deck plugin reading snapshot.json
cannot make a refresh fail. Claude's <synthetic> entries are skipped,
and repeated diagnostics fold into one entry with a count.

Refs #1
2026-10-14 19:59:58 +02:00

137 lines
7.3 KiB
C#

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
{
cancellationToken.ThrowIfCancellationRequested();
var info = new FileInfo(path);
var cursor = history.Cursor(path);
var length = info.Length;
var lastWrite = info.LastWriteTimeUtc.Ticks;
var creation = info.CreationTimeUtc.Ticks;
if (cursor.ObservedLength == length && cursor.LastWriteTicks == lastWrite && cursor.CreationTicks == creation)
return 0;
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete,
65536, FileOptions.Asynchronous | FileOptions.SequentialScan);
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)
{
var start = 0;
while (start < read)
{
var newline = readBuffer.AsSpan(start, read - start).IndexOf((byte)'\n');
var segmentLength = newline < 0 ? read - start : newline;
line.Write(readBuffer.AsSpan(start, segmentLength));
consumed += segmentLength;
start += segmentLength;
if (newline < 0) break;
consumed++;
start++;
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));
cursor.ObservedLength = length;
cursor.LastWriteTicks = lastWrite;
history.CursorChanged(path);
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)));
}
}