// Package transcript reads Claude Code's session logs to estimate recent // activity when the quota endpoint does not answer. // // ~/.claude/projects/ is READ-ONLY: those are the user's real logs, and Claude // Code is writing to them while dipstick reads. Files are opened for reading // only, and no cache or state file ever lands inside that tree. // // Local data is not a quota: it knows the tokens, not the limits. It exists to // tell whether there has been recent activity - which drives the adaptive poll // interval - and to show something honest when the percentage is missing. package transcript import ( "bufio" "bytes" "encoding/json" "errors" "fmt" "io" "io/fs" "os" "path/filepath" "sort" "time" ) // Root is the transcript tree. Read-only, always. func Root() (string, error) { home, err := os.UserHomeDir() if err != nil { return "", err } return filepath.Join(home, ".claude", "projects"), nil } // Activity is everything that can be said by looking at local files alone. type Activity struct { ScannedAt time.Time LastActivity time.Time // zero if nothing was found SessionTokens int64 // last 5 hours TodayTokens int64 // since local midnight WeekTokens int64 // last 7 days MonthTokens int64 // the same span the daily series covers Messages int // distinct messages counted // FilesScanned is how many files the totals account for, whether they // were read this round or found unchanged since the last one. FilesScanned int // BytesRead is how much transcript was actually read this round: the // whole tree on a first round, only what was appended on later ones. BytesRead int64 // Models is per-model consumption over the same span as Daily, so that the // legend and the chart describe the same period. Models []ModelUsage // Daily is day-by-day consumption, split by model. Oldest first, one entry // per day even when it is zero: a chart that skips empty days would // compress time and make intermittent work look steady. Daily []DayUsage } // ModelUsage is what one model cost over the scanned span. type ModelUsage struct { // ID is the identifier exactly as it appears in the transcripts // ("claude-opus-5"). It is not normalised here: the set is not closed and // the names are chosen by whoever writes the logs. ID string `json:"id"` Tokens int64 `json:"tokens"` Messages int `json:"messages"` } // DayUsage is one local calendar day. type DayUsage struct { Date string `json:"date"` // YYYY-MM-DD, local time Tokens int64 `json:"tokens"` Models map[string]int64 `json:"models,omitempty"` } const ( sessionWindow = 5 * time.Hour weekWindow = 7 * 24 * time.Hour // dailyDays is how many calendar days the chart covers. dailyDays = 30 // maxLine bounds one transcript line. Tool output makes these long, so the // scanner's default buffer is far too small. maxLine = 16 * 1024 * 1024 ) // midnight is the start of the current day in local time. "Today" is a // calendar notion, not a rolling window: at 02:00, today is two hours old, not // twenty-four. func midnight(now time.Time) time.Time { y, m, d := now.Date() return time.Date(y, m, d, 0, 0, 0, 0, now.Location()) } // spanStart is the oldest instant every total covers. // // It is a calendar boundary, not a rolling one, because the daily series is // made of calendar days. Using `now - 30*24h` for the totals while the chart // started at a midnight left a sliver of up to a day whose messages counted // towards the month and the per-model legend but belonged to no drawn column: // they vanished from the chart without a trace. func spanStart(now time.Time) time.Time { return midnight(now).AddDate(0, 0, -(dailyDays - 1)) } // One transcript line, reduced to the fields that matter. type line struct { Timestamp string `json:"timestamp"` RequestID string `json:"requestId"` Message struct { ID string `json:"id"` Model string `json:"model"` Usage *struct { Input int64 `json:"input_tokens"` CacheCreat int64 `json:"cache_creation_input_tokens"` CacheRead int64 `json:"cache_read_input_tokens"` Output int64 `json:"output_tokens"` } `json:"usage"` } `json:"message"` } func (l *line) tokens() int64 { u := l.Message.Usage return u.Input + u.CacheCreat + u.CacheRead + u.Output } // dedupKey identifies a message. It is needed because the same message appears // several times in the transcripts - measured on a real tree: 3927 lines with // usage for 2026 distinct ids. Summing without deduplicating nearly doubles // the total. func (l *line) dedupKey() string { if l.Message.ID != "" { return l.Message.ID } return l.RequestID } // message is one deduplicated message. type message struct { at time.Time model string tokens int64 } // Scan walks the transcripts and summarises recent activity, reading every // file from the start. It is the one-shot form, for the CLI; the daemon keeps // a Scanner so that each round only pays for what was appended since the last. // // The returned Activity is always usable, even when the error is non-nil: a // file that could not be read fully is reported so the caller can say the // totals are incomplete, rather than silently presenting them as whole. func Scan(root string, now time.Time) (*Activity, error) { return NewScanner().Scan(root, now) } // Scanner reads the transcripts incrementally, remembering per file how far // it has read and what it found there. // // The full rescan grew with the history: at 316 files and 1.5 GB, all of them // touched within the month, the mtime filter skips nothing and a round costs // ~11 s, 93% of it in json.Unmarshal stepping over tool output that was // already parsed five minutes earlier. Claude Code only ever appends to a // transcript, so what was read stays read: a round reopens only the files // that grew, and reads them only from where it stopped. // // The cache lives in memory and nowhere else. On disk it would be one more // piece of state to invalidate, for a saving that only matters to a // long-running process anyway; and it could never go next to the transcripts, // which are read-only. // // A Scanner is not safe for concurrent use: the daemon calls it from its one // loop. type Scanner struct { files map[string]*cachedFile } // cachedFile is what one transcript has yielded so far. type cachedFile struct { // info identifies the file the offset belongs to (os.SameFile): a // transcript replaced by a rename keeps the path but not the content. info os.FileInfo // offset is always just past the last complete line, so a read resumes on // a line boundary even when the previous one ended in a half-written line. offset int64 // seen holds this file's messages, already deduplicated by the same rule // as the whole scan: the largest usage per key. seen map[string]message } func NewScanner() *Scanner { return &Scanner{files: map[string]*cachedFile{}} } // Scan is the incremental form of the package-level Scan, with the same // semantics and the same totals: a file unchanged since the last round is not // even opened, one that grew is read only from where the last round stopped, // and one that shrank or was replaced is read again from the start. func (s *Scanner) Scan(root string, now time.Time) (*Activity, error) { act := &Activity{ScannedAt: now} start := spanStart(now) // The mtime cutoff is deliberately the wider of the two bounds: it only // decides which files to open, and skipping one that might hold relevant // lines would lose data. mtimeCutoff := now.Add(-(dailyDays + 1) * 24 * time.Hour) // Walk order, kept so the merge breaks ties between files the way a // one-shot scan does: the first file holding the largest figure wins. var order []*cachedFile walked := make(map[string]bool, len(s.files)) var problems []error err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { if err != nil { // An unreadable directory is no reason to throw away the rest of // the scan: skip it and carry on. return nil } if d.IsDir() || filepath.Ext(path) != ".jsonl" { return nil } info, err := d.Info() if err != nil || info.ModTime().Before(mtimeCutoff) { return nil } walked[path] = true cf, n, err := s.update(path, info, start) act.BytesRead += n if err != nil { // What was read before the failure still counts this round, but // the file is not cached: the next round reads it again and // reports it again. Cached, the problem would be reported once and // then vanish, leaving a short total that looks whole. delete(s.files, path) if cf != nil { order = append(order, cf) } problems = append(problems, err) return nil } s.files[path] = cf order = append(order, cf) act.FilesScanned++ return nil }) if err != nil { return act, err } // Deleted files, and files that have aged past the cutoff, take their // messages with them: a one-shot scan would not have seen them either. for path := range s.files { if !walked[path] { delete(s.files, path) } } act.aggregate(merge(order, start), now) if len(problems) > 0 { return act, fmt.Errorf("%d transcript(s) read incompletely: %w", len(problems), errors.Join(problems...)) } return act, nil } // update brings one file's cache up to date and returns it with the number of // bytes read. On error the returned entry, if any, holds what was read before // the failure. func (s *Scanner) update(path string, info os.FileInfo, start time.Time) (*cachedFile, int64, error) { prev := s.files[path] if prev != nil && os.SameFile(prev.info, info) && info.Size() == prev.offset { return prev, 0, nil } // os.Open is read-only: the project's constraint, made explicit. f, err := os.Open(path) if err != nil { return nil, 0, fmt.Errorf("%s: %w", path, err) } defer f.Close() // The identity that counts is the one of the file actually opened: the // path may have been replaced between the walk and the open. opened, err := f.Stat() if err != nil { return nil, 0, fmt.Errorf("%s: %w", path, err) } cf := prev if cf == nil || !os.SameFile(cf.info, opened) || opened.Size() < cf.offset || !endsLine(f, cf.offset) { cf = &cachedFile{seen: map[string]message{}} } cf.info = opened if _, err := f.Seek(cf.offset, io.SeekStart); err != nil { return cf, 0, fmt.Errorf("%s: %w", path, err) } r := &countingReader{r: f} err = cf.read(r, start) if err != nil { err = fmt.Errorf("%s: %w", path, err) } return cf, r.n, err } // endsLine says whether the byte before offset is a newline, as it is for an // offset this scanner recorded. Claude Code only appends, but a file // rewritten in place under the same inode would otherwise be read from the // middle of a line: one byte is a cheap way to notice most of those, and the // price of a false alarm is only a full read. func endsLine(f *os.File, offset int64) bool { if offset == 0 { return true } var b [1]byte _, err := f.ReadAt(b[:], offset-1) return err == nil && b[0] == '\n' } // read folds the lines from r into the file's messages, keeping the largest // usage per message, and advances the offset past every complete line. func (cf *cachedFile) read(r io.Reader, start time.Time) error { sc := bufio.NewScanner(r) sc.Buffer(make([]byte, 0, 64*1024), maxLine) // Only a line ending in a newline is known to be complete. A trailing // segment without one is most likely the line Claude Code is writing right // now, so it never moves the offset: the next round starts from its first // byte. It is still parsed, because a file whose last line is whole but // unterminated would otherwise lose that line for good; if it parses it // counts now, and reading it again next round is harmless, since the key // deduplicates it. complete := false sc.Split(func(data []byte, atEOF bool) (int, []byte, error) { if i := bytes.IndexByte(data, '\n'); i >= 0 { complete = true return i + 1, data[:i], nil } if atEOF && len(data) > 0 { complete = false return len(data), data, nil } return 0, nil, nil }) for sc.Scan() { if complete { cf.offset += int64(len(sc.Bytes())) + 1 } cf.fold(sc.Bytes(), start) } // Without this check a line over maxLine, or an I/O error, would stop the // scan and lose the rest of the file with no trace: a figure too low, // presented as if it were complete. return sc.Err() } // fold adds one line to the file's messages, if it is one that counts. func (cf *cachedFile) fold(raw []byte, start time.Time) { var l line // Claude Code writes while we read: a line can be cut short. Skip it; a // later round will find it complete. if json.Unmarshal(raw, &l) != nil { return } if l.Message.Usage == nil { return } // is not a call to the model: it consumes no quota. if l.Message.Model == "" { return } // The span start only moves forward, so a line older than it now can // never become relevant: dropping it here is final, not a deferral. at, err := time.Parse(time.RFC3339, l.Timestamp) if err != nil || at.Before(start) { return } key := l.dedupKey() if key == "" { return } // Duplicates are not identical copies: they are progressive snapshots of // the same message, so a later one can report more output tokens than an // earlier one. Keeping the largest keeps the finished figure; keeping the // first one seen understates it. n := l.tokens() if prev, ok := cf.seen[key]; ok && prev.tokens >= n { return } cf.seen[key] = message{at: at, model: l.Message.Model, tokens: n} } // merge deduplicates across files - the same message can show up in more // than one transcript - by the same largest-usage rule used within a file. // // It also drops what has aged out of the span since it was cached, from the // totals and from the caches themselves: the chart starts at a later midnight // every day, and without the pruning a long-running daemon would hold every // message it ever read. func merge(files []*cachedFile, start time.Time) map[string]message { seen := make(map[string]message, 16384) for _, cf := range files { for key, m := range cf.seen { if m.at.Before(start) { delete(cf.seen, key) continue } if prev, ok := seen[key]; ok && prev.tokens >= m.tokens { continue } seen[key] = m } } return seen } // countingReader counts the bytes actually read: it is how a round tells how // much it cost, and how the tests prove an unchanged file is not read again. type countingReader struct { r io.Reader n int64 } func (c *countingReader) Read(p []byte) (int, error) { n, err := c.r.Read(p) c.n += int64(n) return n, err } // aggregate turns deduplicated messages into the totals and the series. func (a *Activity) aggregate(seen map[string]message, now time.Time) { sessionStart := now.Add(-sessionWindow) todayStart := midnight(now) weekStart := now.Add(-weekWindow) models := map[string]*ModelUsage{} days := map[string]*DayUsage{} for _, m := range seen { if m.at.After(a.LastActivity) { a.LastActivity = m.at } a.MonthTokens += m.tokens if !m.at.Before(weekStart) { a.WeekTokens += m.tokens } if !m.at.Before(todayStart) { a.TodayTokens += m.tokens } if !m.at.Before(sessionStart) { a.SessionTokens += m.tokens } if m.model != "" { mu := models[m.model] if mu == nil { mu = &ModelUsage{ID: m.model} models[m.model] = mu } mu.Tokens += m.tokens mu.Messages++ } key := m.at.Local().Format("2006-01-02") d := days[key] if d == nil { d = &DayUsage{Date: key, Models: map[string]int64{}} days[key] = d } d.Tokens += m.tokens if m.model != "" { d.Models[m.model] += m.tokens } } a.Messages = len(seen) a.Models = sortedModels(models) a.Daily = dailySeries(days, now) } // sortedModels orders from most expensive to least, which is the order they // matter in. func sortedModels(m map[string]*ModelUsage) []ModelUsage { out := make([]ModelUsage, 0, len(m)) for _, v := range m { out = append(out, *v) } sort.Slice(out, func(i, j int) bool { if out[i].Tokens != out[j].Tokens { return out[i].Tokens > out[j].Tokens } return out[i].ID < out[j].ID }) return out } // dailySeries produces a continuous series, oldest first. Days without // activity stay in the series with a zero: dropping them would compress time // and make intermittent work look steady. func dailySeries(days map[string]*DayUsage, now time.Time) []DayUsage { out := make([]DayUsage, 0, dailyDays) start := spanStart(now) for i := 0; i < dailyDays; i++ { key := start.AddDate(0, 0, i).Format("2006-01-02") if d, ok := days[key]; ok { out = append(out, *d) continue } out = append(out, DayUsage{Date: key}) } return out } // Idle says how long there has been no activity. With LastActivity at zero - // no data at all - it returns false: better to ask the network than to assume // we are idle. func (a *Activity) Idle(threshold time.Duration) bool { if a.LastActivity.IsZero() { return false } return a.ScannedAt.Sub(a.LastActivity) > threshold }