using System.Security.Cryptography; using System.Text; namespace FinalToken.Core.Collectors; public sealed record ScanResult(int AddedEvents, IReadOnlyList CodexFallback, int ClaudeAdded = 0, int CodexAdded = 0); /// Only opens transcript/rollout jsonl paths. Offsets advance through complete lines only. /// Prefix and consumed-tail fingerprints detect replacements without rereading whole files. public sealed class IncrementalScanner(HistoryStore history, DiagnosticLog diagnostics, string claudeDirectory, string codexDirectory, Action? observe = null) { private static readonly UTF8Encoding StrictUtf8 = new(false, true); public async Task 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 fallback = []; foreach (var path in codexFiles) { List 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 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 ScanFileAsync(string path, Provider provider, List 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) { observe?.Invoke(usage, cursor.SessionId); if (history.Add(usage)) added++; } } else if (text.Length > 0) { var entry = RolloutParser.Parse(text, cursor, DateTimeOffset.UtcNow, diagnostics); if (entry.CumulativeUsage is { } usage) { observe?.Invoke(usage, cursor.SessionId); if (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))); } }