package transcript import ( "fmt" "os" "path/filepath" "reflect" "strings" "testing" "time" ) // A fixed midday instant: far enough from midnight that "today" and a rolling // 24 hours differ, which is exactly where the window bugs live. var now = time.Date(2026, 8, 27, 12, 0, 0, 0, time.Local) func ago(d time.Duration) string { return now.Add(-d).Format(time.RFC3339) } func msg(id, model, ts string, in, cacheCreate, cacheRead, out int64) string { return fmt.Sprintf(`{"type":"assistant","timestamp":%q,"requestId":"req_%s","message":`+ `{"id":%q,"model":%q,"usage":{"input_tokens":%d,"cache_creation_input_tokens":%d,`+ `"cache_read_input_tokens":%d,"output_tokens":%d}}}`, ts, id, id, model, in, cacheCreate, cacheRead, out) } // write creates a transcript and pins its mtime: the mtime filter is the heart // of the strategy, so tests must be able to control it. func write(t *testing.T, dir, name string, mtime time.Time, lines ...string) string { t.Helper() path := filepath.Join(dir, name) if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { t.Fatal(err) } body := strings.Join(lines, "\n") + "\n" if err := os.WriteFile(path, []byte(body), 0o644); err != nil { t.Fatal(err) } if err := os.Chtimes(path, mtime, mtime); err != nil { t.Fatal(err) } return path } func scan(t *testing.T, dir string) *Activity { t.Helper() act, err := Scan(dir, now) if err != nil { t.Fatalf("scan failed: %v", err) } return act } // The case that matters: on a real tree 3927 lines with usage yield 2026 // distinct ids. Without deduplication the total nearly doubles. func TestScanDeduplicatesRepeatedMessages(t *testing.T) { dir := t.TempDir() dup := msg("msg_a", "claude-opus-5", ago(time.Hour), 100, 0, 0, 10) write(t, dir, "proj/a.jsonl", now, dup, dup, dup) act := scan(t, dir) if act.SessionTokens != 110 { t.Errorf("SessionTokens = %d, want 110 (the line counts once)", act.SessionTokens) } if act.Messages != 1 { t.Errorf("Messages = %d, want 1", act.Messages) } } // Duplicates are progressive snapshots, not identical copies: the finished // figure is the largest one, and keeping the first seen understates it. func TestScanKeepsTheLargestUsagePerMessage(t *testing.T) { dir := t.TempDir() write(t, dir, "proj/a.jsonl", now, msg("streamed", "claude-opus-5", ago(time.Hour), 100, 0, 0, 5), msg("streamed", "claude-opus-5", ago(time.Hour), 100, 0, 0, 900), msg("streamed", "claude-opus-5", ago(time.Hour), 100, 0, 0, 40)) act := scan(t, dir) if act.SessionTokens != 1000 { t.Errorf("SessionTokens = %d, want 1000 (the completed snapshot)", act.SessionTokens) } if act.Models[0].Tokens != 1000 { t.Errorf("model total = %d, want 1000", act.Models[0].Tokens) } if act.Daily[len(act.Daily)-1].Tokens != 1000 { t.Errorf("daily total = %d, want 1000", act.Daily[len(act.Daily)-1].Tokens) } } // Deduplication must hold across files too: the same session can show up in // more than one transcript. func TestScanDeduplicatesAcrossFiles(t *testing.T) { dir := t.TempDir() m := msg("msg_shared", "claude-opus-5", ago(time.Hour), 50, 0, 0, 5) write(t, dir, "proj-a/x.jsonl", now, m) write(t, dir, "proj-b/y.jsonl", now, m) if act := scan(t, dir); act.SessionTokens != 55 { t.Errorf("SessionTokens = %d, want 55", act.SessionTokens) } } func TestScanSplitsWindows(t *testing.T) { dir := t.TempDir() write(t, dir, "p/a.jsonl", now, msg("recent", "claude-opus-5", ago(2*time.Hour), 100, 0, 0, 0), msg("older", "claude-opus-5", ago(48*time.Hour), 200, 0, 0, 0), msg("ancient", "claude-opus-5", ago(10*24*time.Hour), 999, 0, 0, 0)) act := scan(t, dir) if act.SessionTokens != 100 { t.Errorf("SessionTokens = %d, want 100", act.SessionTokens) } if act.WeekTokens != 300 { t.Errorf("WeekTokens = %d, want 300", act.WeekTokens) } if !act.LastActivity.Equal(now.Add(-2 * time.Hour)) { t.Errorf("LastActivity = %v", act.LastActivity) } } // "Today" is a calendar day, not a rolling 24 hours: at midday, something from // twenty hours ago happened yesterday. func TestScanSplitsTodayWeekMonth(t *testing.T) { dir := t.TempDir() write(t, dir, "p/a.jsonl", now, msg("this-morning", "claude-opus-5", ago(3*time.Hour), 10, 0, 0, 0), msg("yesterday", "claude-opus-5", ago(20*time.Hour), 100, 0, 0, 0), msg("this-week", "claude-opus-5", ago(4*24*time.Hour), 1000, 0, 0, 0), msg("this-month", "claude-opus-5", ago(20*24*time.Hour), 10000, 0, 0, 0), msg("too-old", "claude-opus-5", ago(40*24*time.Hour), 999999, 0, 0, 0)) act := scan(t, dir) if act.TodayTokens != 10 { t.Errorf("today = %d, want 10 (local midnight, not a rolling 24h)", act.TodayTokens) } if act.WeekTokens != 1110 { t.Errorf("week = %d, want 1110", act.WeekTokens) } if act.MonthTokens != 11110 { t.Errorf("month = %d, want 11110", act.MonthTokens) } } // The invariant the README promises: every message in the month total is drawn // in the chart. A rolling boundary for the totals against a calendar boundary // for the chart left a sliver of messages counted but never drawn. func TestMonthTotalMatchesTheChart(t *testing.T) { dir := t.TempDir() // Just inside the oldest drawn day, and just outside it. firstDay := spanStart(now) write(t, dir, "p/a.jsonl", now, msg("oldest-drawn", "claude-opus-5", firstDay.Add(time.Minute).Format(time.RFC3339), 1000, 0, 0, 0), msg("just-before", "claude-opus-5", firstDay.Add(-time.Minute).Format(time.RFC3339), 7777, 0, 0, 0), msg("today", "claude-opus-5", ago(time.Hour), 1, 0, 0, 0)) act := scan(t, dir) var charted int64 for _, d := range act.Daily { charted += d.Tokens } if charted != act.MonthTokens { t.Errorf("chart = %d, month total = %d: some messages are counted but never drawn", charted, act.MonthTokens) } if act.MonthTokens != 1001 { t.Errorf("month = %d, want 1001 (the message before the first drawn day is out)", act.MonthTokens) } var perModel int64 for _, m := range act.Models { perModel += m.Tokens } if perModel != act.MonthTokens { t.Errorf("legend = %d, month total = %d: they must describe the same span", perModel, act.MonthTokens) } } // A file with an old mtime cannot contain recent lines: skipping it is exact, // not approximate. This checks it really is skipped. func TestScanSkipsFilesByModTime(t *testing.T) { dir := t.TempDir() write(t, dir, "p/old.jsonl", now.Add(-60*24*time.Hour), msg("inside-an-old-file", "claude-opus-5", ago(time.Hour), 1000, 0, 0, 0)) act := scan(t, dir) if act.FilesScanned != 0 { t.Errorf("FilesScanned = %d, want 0", act.FilesScanned) } if act.MonthTokens != 0 { t.Errorf("MonthTokens = %d, want 0", act.MonthTokens) } } // Claude Code writes while dipstick reads: the last line can be truncated, and // that must not cost the good lines before it. func TestScanToleratesTruncatedLastLine(t *testing.T) { dir := t.TempDir() write(t, dir, "p/a.jsonl", now, msg("good", "claude-opus-5", ago(time.Minute), 42, 0, 0, 0), `{"type":"assistant","timestamp":"2026-08-27T11:5`) if act := scan(t, dir); act.SessionTokens != 42 { t.Errorf("SessionTokens = %d, want 42", act.SessionTokens) } } // A line past the scanner's limit stops the read. Reporting it is the whole // point: silently returning a smaller number looks exactly like a quiet day. func TestScanReportsAnOversizedLine(t *testing.T) { dir := t.TempDir() huge := `{"padding":"` + strings.Repeat("x", maxLine+1024) + `"}` write(t, dir, "p/a.jsonl", now, msg("before", "claude-opus-5", ago(time.Minute), 42, 0, 0, 0), huge, msg("after", "claude-opus-5", ago(time.Minute), 1000, 0, 0, 0)) act, err := Scan(dir, now) if err == nil { t.Fatal("an unreadable file must be reported, not swallowed") } if act == nil { t.Fatal("the partial result must still be usable") } if act.SessionTokens != 42 { t.Errorf("SessionTokens = %d: the lines before the failure should survive", act.SessionTokens) } } // One bad file must not cost the others. func TestScanKeepsGoingAfterABadFile(t *testing.T) { dir := t.TempDir() write(t, dir, "p/bad.jsonl", now, `{"padding":"`+strings.Repeat("x", maxLine+1024)+`"}`) write(t, dir, "p/good.jsonl", now, msg("good", "claude-opus-5", ago(time.Minute), 500, 0, 0, 0)) act, err := Scan(dir, now) if err == nil { t.Error("the failure must be reported") } if act.SessionTokens != 500 { t.Errorf("SessionTokens = %d, want 500 from the readable file", act.SessionTokens) } } // is not a call to the model and consumes no quota. func TestScanIgnoresSyntheticModel(t *testing.T) { dir := t.TempDir() write(t, dir, "p/a.jsonl", now, msg("fake", "", ago(time.Minute), 500, 0, 0, 0), msg("real", "claude-opus-5", ago(time.Minute), 7, 0, 0, 0)) if act := scan(t, dir); act.SessionTokens != 7 { t.Errorf("SessionTokens = %d, want 7", act.SessionTokens) } } func TestScanCountsAllTokenKinds(t *testing.T) { dir := t.TempDir() write(t, dir, "p/a.jsonl", now, msg("m", "claude-opus-5", ago(time.Minute), 1, 20, 300, 4000)) if act := scan(t, dir); act.SessionTokens != 4321 { t.Errorf("SessionTokens = %d, want 4321", act.SessionTokens) } } func TestScanMissingRootIsNotFatal(t *testing.T) { act, err := Scan(filepath.Join(t.TempDir(), "does-not-exist"), now) if err != nil { t.Fatalf("a missing root must not be an error: %v", err) } if act.FilesScanned != 0 { t.Errorf("FilesScanned = %d", act.FilesScanned) } if len(act.Daily) != dailyDays { t.Errorf("the series must still be complete: %d days", len(act.Daily)) } } func TestScanBreaksDownByModel(t *testing.T) { dir := t.TempDir() write(t, dir, "p/a.jsonl", now, msg("m1", "claude-sonnet-5", ago(time.Hour), 10, 0, 0, 0), msg("m2", "claude-opus-5", ago(time.Hour), 100, 0, 0, 0), msg("m3", "claude-opus-5", ago(2*time.Hour), 50, 0, 0, 0), msg("m4", "", ago(time.Hour), 999, 0, 0, 0)) act := scan(t, dir) if len(act.Models) != 2 { t.Fatalf("models = %+v, want 2 ( excluded)", act.Models) } // Most expensive first: that is the order they matter in. if act.Models[0].ID != "claude-opus-5" || act.Models[0].Tokens != 150 { t.Errorf("first = %+v, want opus with 150", act.Models[0]) } if act.Models[0].Messages != 2 { t.Errorf("opus messages = %d, want 2", act.Models[0].Messages) } if act.Models[1].ID != "claude-sonnet-5" || act.Models[1].Tokens != 10 { t.Errorf("second = %+v", act.Models[1]) } } // The daily series must be continuous, or the chart compresses time. func TestDailySeriesIsContinuous(t *testing.T) { dir := t.TempDir() write(t, dir, "p/a.jsonl", now, msg("today", "claude-opus-5", ago(time.Hour), 10, 0, 0, 0), msg("three-days-ago", "claude-sonnet-5", ago(3*24*time.Hour), 70, 0, 0, 0)) act := scan(t, dir) if len(act.Daily) != dailyDays { t.Fatalf("days = %d, want %d", len(act.Daily), dailyDays) } if act.Daily[0].Date >= act.Daily[len(act.Daily)-1].Date { t.Errorf("series is not ordered: %s -> %s", act.Daily[0].Date, act.Daily[len(act.Daily)-1].Date) } last := act.Daily[len(act.Daily)-1] if last.Tokens != 10 || last.Models["claude-opus-5"] != 10 { t.Errorf("last day = %+v, want 10 tokens of opus", last) } empty := 0 for _, d := range act.Daily { if d.Tokens == 0 { empty++ } } if empty != dailyDays-2 { t.Errorf("empty days = %d, want %d", empty, dailyDays-2) } } func TestIdle(t *testing.T) { a := &Activity{ScannedAt: now, LastActivity: now.Add(-2 * time.Hour)} if !a.Idle(time.Hour) { t.Error("two hours of silence with a one-hour threshold should be idle") } if a.Idle(3 * time.Hour) { t.Error("with a three-hour threshold it should not be idle") } // No data does not mean idle: better to ask the network. if (&Activity{ScannedAt: now}).Idle(time.Minute) { t.Error("with no known activity we must not conclude we are idle") } } // appendTo adds raw text to a transcript, exactly as given - no newline is // added, because where the newline falls is what several tests are about - // and pins the mtime again, as write does. func appendTo(t *testing.T, path string, text string) { t.Helper() f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0) if err != nil { t.Fatal(err) } if _, err := f.WriteString(text); err != nil { t.Fatal(err) } if err := f.Close(); err != nil { t.Fatal(err) } if err := os.Chtimes(path, now, now); err != nil { t.Fatal(err) } } func round(t *testing.T, s *Scanner, dir string, at time.Time) *Activity { t.Helper() act, err := s.Scan(dir, at) if err != nil { t.Fatalf("scan failed: %v", err) } return act } // sameTotals compares everything the state is built from. ScannedAt and // BytesRead are left out: they describe the round, not the transcripts. func sameTotals(t *testing.T, got, want *Activity) { t.Helper() g, w := *got, *want g.ScannedAt, w.ScannedAt = time.Time{}, time.Time{} g.BytesRead, w.BytesRead = 0, 0 if !reflect.DeepEqual(g, w) { t.Errorf("incremental and one-shot scans disagree:\n got %+v\n want %+v", g, w) } } // The promise the Scanner makes: whatever happened between rounds, its answer // is the one a fresh scan of the same tree would give. func TestScannerMatchesAOneShotScan(t *testing.T) { dir := t.TempDir() a := write(t, dir, "p/a.jsonl", now, msg("a1", "claude-opus-5", ago(3*time.Hour), 100, 0, 0, 1)) b := write(t, dir, "q/b.jsonl", now, msg("b1", "claude-sonnet-5", ago(3*24*time.Hour), 10, 0, 0, 0)) s := NewScanner() steps := []func(){ func() {}, func() { appendTo(t, a, msg("a2", "claude-opus-5", ago(2*time.Hour), 5, 0, 0, 5)+"\n") }, func() { // The same message in both files, and a later snapshot of a1. appendTo(t, b, msg("shared", "claude-opus-5", ago(time.Hour), 7, 0, 0, 0)+"\n") appendTo(t, a, msg("shared", "claude-opus-5", ago(time.Hour), 7, 0, 0, 3)+"\n"+ msg("a1", "claude-opus-5", ago(3*time.Hour), 100, 0, 0, 900)+"\n") }, func() { write(t, dir, "r/c.jsonl", now, msg("c1", "claude-haiku-5", ago(20*time.Hour), 1, 2, 3, 4), msg("synthetic", "", ago(time.Hour), 999, 0, 0, 0)) appendTo(t, b, `{"type":"assistant","timestamp":"2026-08`) }, func() { appendTo(t, b, "-27T11:00:00Z\"}\n"+msg("b2", "claude-opus-5", ago(time.Minute), 1, 0, 0, 1)+"\n") }, } for i, step := range steps { step() got := round(t, s, dir, now) want := scan(t, dir) if t.Failed() { t.Fatalf("after step %d", i) } sameTotals(t, got, want) if got.FilesScanned != want.FilesScanned { t.Errorf("step %d: FilesScanned = %d, want %d", i, got.FilesScanned, want.FilesScanned) } } } // The reason the Scanner exists: a round with nothing new must cost nothing, // and a round after an append must cost the append. func TestScannerReadsOnlyWhatWasAppended(t *testing.T) { dir := t.TempDir() a := write(t, dir, "p/a.jsonl", now, msg("a1", "claude-opus-5", ago(time.Hour), 10, 0, 0, 0)) b := write(t, dir, "p/b.jsonl", now, msg("b1", "claude-opus-5", ago(time.Hour), 20, 0, 0, 0)) s := NewScanner() if act := round(t, s, dir, now); act.BytesRead == 0 { t.Fatal("the first round must read the files") } // Not just read for nothing: not opened at all. A file that could not be // opened would make the round fail, so this proves it was left alone. if err := os.Chmod(b, 0); err != nil { t.Fatal(err) } act := round(t, s, dir, now) if act.BytesRead != 0 { t.Errorf("BytesRead = %d with nothing changed, want 0", act.BytesRead) } if act.FilesScanned != 2 || act.SessionTokens != 30 { t.Errorf("unchanged round: files = %d, tokens = %d, want 2 and 30", act.FilesScanned, act.SessionTokens) } tail := msg("a2", "claude-opus-5", ago(time.Minute), 5, 0, 0, 0) + "\n" appendTo(t, a, tail) act = round(t, s, dir, now) if act.BytesRead != int64(len(tail)) { t.Errorf("BytesRead = %d after appending %d bytes", act.BytesRead, len(tail)) } if act.SessionTokens != 35 { t.Errorf("SessionTokens = %d, want 35", act.SessionTokens) } } // Claude Code writes while dipstick reads. Half a line must not count, and // must not be skipped either: once finished, it counts exactly once. func TestScannerWaitsForAHalfWrittenLine(t *testing.T) { dir := t.TempDir() a := write(t, dir, "p/a.jsonl", now, msg("first", "claude-opus-5", ago(time.Hour), 10, 0, 0, 0)) s := NewScanner() round(t, s, dir, now) line := msg("second", "claude-opus-5", ago(time.Minute), 32, 0, 0, 0) half := len(line) / 2 appendTo(t, a, line[:half]) if act := round(t, s, dir, now); act.SessionTokens != 10 || act.Messages != 1 { t.Errorf("half a line counted: tokens = %d, messages = %d", act.SessionTokens, act.Messages) } appendTo(t, a, line[half:]+"\n") act := round(t, s, dir, now) if act.SessionTokens != 42 || act.Messages != 2 { t.Errorf("finished line: tokens = %d, messages = %d, want 42 and 2", act.SessionTokens, act.Messages) } // The read resumes at the start of the line, not after the half already // seen, and not from the start of the file either. if act.BytesRead != int64(len(line)+1) { t.Errorf("BytesRead = %d, want %d: the whole line and nothing else", act.BytesRead, len(line)+1) } if act := round(t, s, dir, now); act.SessionTokens != 42 || act.BytesRead != 0 { t.Errorf("next round: tokens = %d, BytesRead = %d, want 42 and 0", act.SessionTokens, act.BytesRead) } } // A later snapshot can arrive rounds after the first one, in the same file or // in another: the cached figure must give way to the larger one. func TestScannerTakesALaterLargerSnapshot(t *testing.T) { dir := t.TempDir() a := write(t, dir, "p/a.jsonl", now, msg("streamed", "claude-opus-5", ago(time.Hour), 100, 0, 0, 5)) b := write(t, dir, "q/b.jsonl", now, msg("other", "claude-opus-5", ago(time.Hour), 1, 0, 0, 0)) s := NewScanner() round(t, s, dir, now) appendTo(t, a, msg("streamed", "claude-opus-5", ago(time.Hour), 100, 0, 0, 400)+"\n") if act := round(t, s, dir, now); act.SessionTokens != 501 { t.Errorf("same file: SessionTokens = %d, want 501", act.SessionTokens) } appendTo(t, b, msg("streamed", "claude-opus-5", ago(time.Hour), 100, 0, 0, 900)+"\n") act := round(t, s, dir, now) if act.SessionTokens != 1001 || act.Messages != 2 { t.Errorf("other file: tokens = %d, messages = %d, want 1001 and 2", act.SessionTokens, act.Messages) } sameTotals(t, act, scan(t, dir)) } // A file that is not the one the offset was taken on is read from the start, // and nothing from its previous content survives. func TestScannerRereadsARewrittenFile(t *testing.T) { dir := t.TempDir() a := write(t, dir, "p/a.jsonl", now, msg("old-1", "claude-opus-5", ago(time.Hour), 100, 0, 0, 0), msg("old-2", "claude-opus-5", ago(time.Hour), 200, 0, 0, 0)) s := NewScanner() round(t, s, dir, now) // Truncated in place: same inode, shorter. write(t, dir, "p/a.jsonl", now, msg("short", "claude-opus-5", ago(time.Hour), 7, 0, 0, 0)) act := round(t, s, dir, now) if act.SessionTokens != 7 || act.Messages != 1 { t.Errorf("truncated: tokens = %d, messages = %d, want 7 and 1", act.SessionTokens, act.Messages) } // Rewritten in place and longer: the offset no longer falls on a line // boundary, because the new first line is longer than the old one. write(t, dir, "p/a.jsonl", now, msg("a-much-longer-identifier", "claude-opus-5", ago(time.Hour), 3, 0, 0, 0), msg("another-one", "claude-opus-5", ago(time.Hour), 4, 0, 0, 0)) act = round(t, s, dir, now) if act.SessionTokens != 7 || act.Messages != 2 { t.Errorf("rewritten in place: tokens = %d, messages = %d, want 7 and 2", act.SessionTokens, act.Messages) } // Replaced through a rename: a different file under the same path, whose // lines have the same lengths as the old ones plus one more, so the old // offset still falls on a newline. Only the identity gives it away. tmp := write(t, dir, "p/a.jsonl.tmp", now, msg("b-much-longer-identifier", "claude-opus-5", ago(time.Hour), 5, 0, 0, 0), msg("another-two", "claude-opus-5", ago(time.Hour), 6, 0, 0, 0), msg("new", "claude-opus-5", ago(time.Hour), 7, 0, 0, 0)) if err := os.Rename(tmp, a); err != nil { t.Fatal(err) } act = round(t, s, dir, now) if act.SessionTokens != 18 || act.Messages != 3 { t.Errorf("replaced: tokens = %d, messages = %d, want 6 and 3", act.SessionTokens, act.Messages) } sameTotals(t, act, scan(t, dir)) } func TestScannerForgetsADeletedFile(t *testing.T) { dir := t.TempDir() a := write(t, dir, "p/a.jsonl", now, msg("a", "claude-opus-5", ago(time.Hour), 100, 0, 0, 0)) write(t, dir, "p/b.jsonl", now, msg("b", "claude-opus-5", ago(time.Hour), 5, 0, 0, 0)) s := NewScanner() round(t, s, dir, now) if err := os.Remove(a); err != nil { t.Fatal(err) } act := round(t, s, dir, now) if act.SessionTokens != 5 || act.FilesScanned != 1 { t.Errorf("tokens = %d, files = %d, want 5 and 1", act.SessionTokens, act.FilesScanned) } if len(s.files) != 1 { t.Errorf("the cache still holds %d files", len(s.files)) } } // The chart starts at a later midnight every day. Messages cached when they // were inside it must leave the totals once they are not, and the cache too. func TestScannerDropsWhatAgesOutOfTheSpan(t *testing.T) { dir := t.TempDir() a := write(t, dir, "p/a.jsonl", now, msg("oldest", "claude-opus-5", spanStart(now).Add(time.Hour).Format(time.RFC3339), 1000, 0, 0, 0), msg("recent", "claude-opus-5", ago(time.Hour), 1, 0, 0, 0)) s := NewScanner() if act := round(t, s, dir, now); act.MonthTokens != 1001 { t.Fatalf("MonthTokens = %d, want 1001", act.MonthTokens) } later := now.Add(2 * 24 * time.Hour) act := round(t, s, dir, later) if act.MonthTokens != 1 { t.Errorf("MonthTokens = %d two days later, want 1", act.MonthTokens) } if n := len(s.files[a].seen); n != 1 { t.Errorf("the cache still holds %d messages, want 1", n) } oneShot, err := Scan(dir, later) if err != nil { t.Fatal(err) } sameTotals(t, act, oneShot) } // A problem must be reported on every round until it is gone: reported once // and then cached away, it would leave a short total that looks whole. func TestScannerReportsAnOversizedLineEveryRound(t *testing.T) { dir := t.TempDir() bad := write(t, dir, "p/a.jsonl", now, msg("before", "claude-opus-5", ago(time.Minute), 42, 0, 0, 0), `{"padding":"`+strings.Repeat("x", maxLine+1024)+`"}`, msg("after", "claude-opus-5", ago(time.Minute), 1000, 0, 0, 0)) write(t, dir, "p/good.jsonl", now, msg("good", "claude-opus-5", ago(time.Minute), 8, 0, 0, 0)) s := NewScanner() for i := 0; i < 3; i++ { act, err := s.Scan(dir, now) if err == nil { t.Fatalf("round %d: the oversized line was not reported", i) } if act.SessionTokens != 50 { t.Errorf("round %d: SessionTokens = %d, want 50", i, act.SessionTokens) } if act.FilesScanned != 1 { t.Errorf("round %d: FilesScanned = %d, want 1", i, act.FilesScanned) } // Nothing from a read that failed is trusted: the file is read again // from the start, so once it is fixed the totals are whole again // rather than assembled around a gap. if _, ok := s.files[bad]; ok { t.Errorf("round %d: a file that failed was cached", i) } } } // A last line that is whole but has no newline counts, as it always did - and // reading it again on the next round, since the offset stops before it, does // not count it twice. func TestScannerCountsAnUnterminatedLastLine(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "a.jsonl") body := msg("first", "claude-opus-5", ago(time.Hour), 10, 0, 0, 0) + "\n" + msg("last", "claude-opus-5", ago(time.Hour), 32, 0, 0, 0) if err := os.WriteFile(path, []byte(body), 0o644); err != nil { t.Fatal(err) } if err := os.Chtimes(path, now, now); err != nil { t.Fatal(err) } s := NewScanner() for i := 0; i < 2; i++ { if act := round(t, s, dir, now); act.SessionTokens != 42 || act.Messages != 2 { t.Errorf("round %d: tokens = %d, messages = %d, want 42 and 2", i, act.SessionTokens, act.Messages) } } appendTo(t, path, "\n"+msg("next", "claude-opus-5", ago(time.Minute), 100, 0, 0, 0)+"\n") act := round(t, s, dir, now) if act.SessionTokens != 142 || act.Messages != 3 { t.Errorf("after the append: tokens = %d, messages = %d, want 142 and 3", act.SessionTokens, act.Messages) } sameTotals(t, act, scan(t, dir)) }