Repository navigation
feat(aicode): add Cursor and Antigravity usage backfill and daemon sync - #364
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codecov Report❌ Patch coverage is
❌ Your patch check has failed because the patch coverage (68.60%) is below the target coverage (80.00%). You can increase the patch coverage or adjust the target coverage.
Flags with carried forward coverage won't be shown. Click here to find out more.
... and 3 files with indirect coverage changes 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e7c84f75a8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if st.Status == model.AICodeBackfillStatusBackfilled && st.EventCount >= len(sess.Events) { | ||
| continue |
There was a problem hiding this comment.
Avoid comparing incremental usage against total session counts
For Cursor, syncTokenUsage fetches only the interval since the saved watermark minus 15 minutes, but this check compares that partial session against the server's cumulative event count. For example, after uploading 100 events for a daily bucket, a subsequent window containing 10 new events is skipped because 100 >= 10, even though those events have never been uploaded. The watermark then advances, eventually moving the missing events outside the overlap. Upload incremental Cursor events using their stable event IDs for deduplication, or fetch complete sessions before applying this count-based shortcut.
Useful? React with 👍 / 👎.
| for path, fp := range nextFPs { | ||
| s.fingerprints[path] = fp |
There was a problem hiding this comment.
Retain failed Antigravity databases for retry
If reading a changed database fails transiently, such as when SQLite remains locked beyond its 100 ms busy timeout, ParseAntigravityDBFiles increments BadLines and returns a successful result without that database's events. This loop nevertheless caches its fingerprint, so subsequent ticks skip it until the database changes again or the daemon restarts. A conversation's final usage can therefore remain unuploaded after the lock clears. Cache fingerprints only for successfully parsed databases, or leave failed scans eligible for retry.
Useful? React with 👍 / 👎.
| if st.Status == model.AICodeBackfillStatusLive || st.Status == model.AICodeBackfillStatusArchived { | ||
| continue | ||
| } | ||
| if st.Status == model.AICodeBackfillStatusBackfilled && st.EventCount >= len(sess.Events) { |
There was a problem hiding this comment.
Important: new Cursor usage can be dropped for a session the server already has. The check st.Status == Backfilled && st.EventCount >= len(sess.Events) compares the server's count for the whole session with the number of events in this run. But syncTokenUsage only fetches the window since the last sync minus 15 minutes, so a session is only partly in sess.Events.
Example: a conversation (or a cursor-day-YYYY-MM-DD bucket) was uploaded with 100 events, and 2 more arrive. The next window holds about 5 events, so 5 < 100 and the session is skipped. The new events are never sent, and saveState still advances, so they are lost for good.
Fix: for the Cursor path, skip the EventCount shortcut and let the server dedupe by event id. Alternatively, only skip when the status is live or archived, or fetch the full session range. The same uploadDaemonUsageSessions is shared with Antigravity, which re-parses whole DBs, so make the shortcut a parameter.
⏱️
|
| Scenario | base | head | Δ | p | |
|---|---|---|---|---|---|
Startup/floor |
523 µs ±2% | 527 µs ±2% | ~ | 0.436 | A/A |
Startup/version |
5.26 ms ±4% | 5.83 ms ±2% | +10.88% | 0.000 | |
Track/daemon/pre |
5.52 ms ±4% | 6.10 ms ±4% | +10.51% | 0.000 | |
Track/daemon/post |
5.66 ms ±3% | 6.19 ms ±5% | +9.25% | 0.000 | ✅ |
Track/direct/pre |
5.50 ms ±4% | 6.01 ms ±4% | +9.25% | 0.000 | ✅ |
Track/direct/post |
7.59 ms ±3% | 8.25 ms ±2% | +8.67% | 0.000 | ✅ |
Track/direct/post-sync |
10.66 ms ±2% | 11.36 ms ±2% | +6.56% | 0.000 | ✅ |
Binary size: 19.5 MiB → 23.6 MiB (+21.0%).
CPU, tail latency and memory
Per exec, base → head (Δ when significant).
| Scenario | p95 wall | user CPU | sys CPU | peak RSS |
|---|---|---|---|---|
Startup/floor |
591 µs → 597 µs | 283 µs → 286 µs | 189 µs → 183 µs | 9.2 MiB → 9.2 MiB |
Startup/version |
5.86 ms → 6.37 ms (+8.80%) | 2.15 ms → 2.25 ms (+4.23%) | 3.77 ms → 4.28 ms (+13.49%) | 15.8 MiB → 17.3 MiB (+9.55%) |
Track/daemon/pre |
6.13 ms → 6.70 ms (+9.41%) | 2.32 ms → 2.48 ms (+7.15%) | 3.97 ms → 4.35 ms (+9.47%) | 16.2 MiB → 18.0 MiB (+11.22%) |
Track/daemon/post |
6.25 ms → 6.82 ms (+9.11%) | 2.28 ms → 2.63 ms (+15.22%) | 4.10 ms → 4.45 ms (+8.42%) | 16.2 MiB → 18.0 MiB (+11.20%) |
Track/direct/pre |
6.08 ms → 6.63 ms (+9.06%) | 2.21 ms → 2.39 ms (+7.83%) | 3.97 ms → 4.42 ms (+11.31%) | 16.1 MiB → 17.9 MiB (+11.48%) |
Track/direct/post |
8.15 ms → 8.97 ms (+10.05%) | 3.76 ms → 4.02 ms (+6.90%) | 4.66 ms → 5.19 ms (+11.53%) | 16.8 MiB → 18.5 MiB (+10.34%) |
Track/direct/post-sync |
11.47 ms → 12.15 ms (+5.87%) | 6.29 ms → 6.71 ms (+6.55%) | 6.91 ms → 7.76 ms (+12.36%) | 19.2 MiB → 21.1 MiB (+9.66%) |
benchstat
goos: linux
goarch: amd64
pkg: github.com/malamtime/cli/perf
cpu: AMD EPYC 7763 64-Core Processor
│ base │ head │
│ sec/op │ sec/op vs base │
Startup/floor-4 522.6µ ± 2% 527.4µ ± 2% ~ (p=0.436 n=10)
Startup/version-4 5.257m ± 4% 5.829m ± 2% +10.88% (p=0.000 n=10)
Track/daemon/pre-4 5.523m ± 4% 6.104m ± 4% +10.51% (p=0.000 n=10)
Track/daemon/post-4 5.663m ± 3% 6.186m ± 5% +9.25% (p=0.000 n=10)
Track/direct/pre-4 5.498m ± 4% 6.006m ± 4% +9.25% (p=0.000 n=10)
Track/direct/post-4 7.592m ± 3% 8.250m ± 2% +8.67% (p=0.000 n=10)
Track/direct/post-sync-4 10.66m ± 2% 11.36m ± 2% +6.56% (p=0.000 n=10)
geomean 4.515m 4.874m +7.96%
│ base │ head │
│ p50-sec/op │ p50-sec/op vs base │
Startup/floor-4 515.5µ ± 2% 513.6µ ± 1% ~ (p=0.869 n=10)
Startup/version-4 5.257m ± 4% 5.807m ± 2% +10.46% (p=0.000 n=10)
Track/daemon/pre-4 5.522m ± 5% 6.085m ± 5% +10.19% (p=0.000 n=10)
Track/daemon/post-4 5.609m ± 4% 6.144m ± 5% +9.53% (p=0.000 n=10)
Track/direct/pre-4 5.491m ± 3% 5.988m ± 5% +9.05% (p=0.000 n=10)
Track/direct/post-4 7.589m ± 3% 8.246m ± 2% +8.66% (p=0.000 n=10)
Track/direct/post-sync-4 10.62m ± 2% 11.34m ± 2% +6.78% (p=0.000 n=10)
geomean 4.496m 4.843m +7.70%
│ base │ head │
│ p95-sec/op │ p95-sec/op vs base │
Startup/floor-4 590.5µ ± 4% 596.8µ ± 3% ~ (p=0.912 n=10)
Startup/version-4 5.858m ± 4% 6.374m ± 4% +8.80% (p=0.000 n=10)
Track/daemon/pre-4 6.126m ± 4% 6.702m ± 3% +9.41% (p=0.000 n=10)
Track/daemon/post-4 6.249m ± 4% 6.819m ± 3% +9.11% (p=0.000 n=10)
Track/direct/pre-4 6.080m ± 4% 6.631m ± 3% +9.06% (p=0.000 n=10)
Track/direct/post-4 8.154m ± 4% 8.973m ± 4% +10.05% (p=0.002 n=10)
Track/direct/post-sync-4 11.47m ± 3% 12.15m ± 2% +5.87% (p=0.001 n=10)
geomean 4.974m 5.351m +7.58%
│ base │ head │
│ peak-rss-B │ peak-rss-B vs base │
Startup/floor-4 9.216Mi ± 2% 9.247Mi ± 2% ~ (p=0.481 n=10)
Startup/version-4 15.76Mi ± 0% 17.26Mi ± 0% +9.55% (p=0.000 n=10)
Track/daemon/pre-4 16.21Mi ± 0% 18.02Mi ± 0% +11.22% (p=0.000 n=10)
Track/daemon/post-4 16.20Mi ± 0% 18.01Mi ± 0% +11.20% (p=0.000 n=10)
Track/direct/pre-4 16.09Mi ± 0% 17.94Mi ± 0% +11.48% (p=0.000 n=10)
Track/direct/post-4 16.80Mi ± 0% 18.54Mi ± 0% +10.34% (p=0.000 n=10)
Track/direct/post-sync-4 19.23Mi ± 0% 21.09Mi ± 0% +9.66% (p=0.000 n=10)
geomean 15.32Mi 16.71Mi +9.05%
│ base │ head │
│ sys-sec/op │ sys-sec/op vs base │
Startup/floor-4 189.1µ ± 10% 182.6µ ± 14% ~ (p=0.912 n=10)
Startup/version-4 3.772m ± 7% 4.281m ± 3% +13.49% (p=0.000 n=10)
Track/daemon/pre-4 3.971m ± 4% 4.347m ± 4% +9.47% (p=0.000 n=10)
Track/daemon/post-4 4.102m ± 3% 4.448m ± 5% +8.42% (p=0.000 n=10)
Track/direct/pre-4 3.973m ± 4% 4.422m ± 4% +11.31% (p=0.000 n=10)
Track/direct/post-4 4.655m ± 3% 5.192m ± 5% +11.53% (p=0.000 n=10)
Track/direct/post-sync-4 6.910m ± 3% 7.764m ± 5% +12.36% (p=0.000 n=10)
geomean 2.838m 3.091m +8.89%
│ base │ head │
│ user-sec/op │ user-sec/op vs base │
Startup/floor-4 283.4µ ± 7% 286.1µ ± 8% ~ (p=0.739 n=10)
Startup/version-4 2.154m ± 8% 2.245m ± 4% +4.23% (p=0.007 n=10)
Track/daemon/pre-4 2.316m ± 7% 2.482m ± 5% +7.15% (p=0.011 n=10)
Track/daemon/post-4 2.282m ± 8% 2.629m ± 9% +15.22% (p=0.001 n=10)
Track/direct/pre-4 2.212m ± 7% 2.385m ± 6% +7.83% (p=0.015 n=10)
Track/direct/post-4 3.758m ± 8% 4.017m ± 5% +6.90% (p=0.015 n=10)
Track/direct/post-sync-4 6.295m ± 3% 6.707m ± 3% +6.55% (p=0.000 n=10)
geomean 2.081m 2.224m +6.91%
Δ compares medians; ~ means no significant difference (Mann-Whitney U, p ≥ 0.05). A scenario is flagged when it is more than 10% and more than 250µs slower with p < 0.05. Startup/floor runs true, not shelltime: it is an A/A check of runner noise. Runner: linux/amd64, AMD EPYC 7763 64-Core Processor . go1.27.1, 10 rounds × 100 execs per scenario and binary.
| if isStep && len(blob) == 0 { | ||
| continue | ||
| } | ||
| entry, err := parseAgyMetadata(blob, isStep) |
There was a problem hiding this comment.
Important: one bad row discards a whole Antigravity DB. If parseAgyMetadata fails for a single gen_metadata or steps blob (truncated protobuf, an unsupported wire type, or a generation row without field 1), readMeta returns the error. ParseAntigravityDBFiles then counts the entire file as bad and uploads none of its usage. A row whose idx is NULL also fails Scan and has the same effect.
In the daemon the fingerprint is then never recorded for that DB (the parse error is swallowed as badFiles), so it is re-read every 10 minutes with the same outcome.
Fix: continue past rows that fail to parse or scan, and count them as bad lines, instead of aborting the DB.
| generations, err = readMeta( | ||
| "SELECT rowid AS row_id, idx, data FROM gen_metadata WHERE rowid > ? ORDER BY rowid LIMIT ?", | ||
| 1, | ||
| false, |
There was a problem hiding this comment.
Nit: the gen_metadata page size is 1, while steps uses 64. That is one SQL query per generation row, plus one more empty query when the count is 0. For a long conversation DB this is thousands of round trips on every daemon scan of a changed DB and on every agy backfill. Fix: use a real page size such as 64, like the steps query.
|
|
||
| func readAntigravityDatabase(path, sessionID string, fallbackTimestampMs int64) ([]agyUsageCandidate, map[int]agyLearnedModel, error) { | ||
| // Open read-only with query_only pragma so WAL files are read without writing. | ||
| dsn := "file:" + path + "?_pragma=busy_timeout(100)&_pragma=query_only(ON)" |
There was a problem hiding this comment.
Nit: the Antigravity DB is opened as file:<path>?_pragma=... with a raw path and without mode=ro. A path containing ?, # or % is mis-parsed as a URI, so that DB is reported as bad. Without mode=ro, SQLite may create -wal and -shm files next to a database owned by a running agent, or try to checkpoint on close. readAccessTokenFromVscdb in model/cursor_auth.go already uses mode=ro. Fix: build the DSN with url.URL{Scheme: "file", Path: path} and add mode=ro.
| antigravityProcessKeywords = []string{"antigravity", "agy"} | ||
| ) | ||
|
|
||
| // listProcessNamesFunc lists running process names. It is a var so tests can stub it. |
There was a problem hiding this comment.
Nit: isProcessRunning matches with strings.Contains on the lower-cased basename. The keyword agy therefore matches any process whose name contains those letters (for example legacy-* or *agy* helpers), and cursor matches cursor-* helpers. The Antigravity DB scan then runs on false positives. Fix: match agy exactly (basename equal to agy), or keep substring matching only for antigravity.
| return nil, err | ||
| } | ||
| modelName, _ := m["model"].(string) | ||
| if strings.TrimSpace(modelName) == "" { |
There was a problem hiding this comment.
Nit: strict validation turns one odd event into a total failure. An event with a tokenUsage object but an empty or missing model makes normalizeCursorUsageEvent return an error. The error propagates out of fetchCursorScopeUsage and FetchCursorUsageSessions, so the whole fetch fails for every scope. In the daemon the sync state never advances and the same failure repeats every 10 minutes. The same applies to the float64-only token fields and timestamp checks. Fix: skip (and log) the offending event rather than failing the whole scan.
| modernc.org/libc v1.80.1 // indirect | ||
| modernc.org/mathutil v1.7.1 // indirect | ||
| modernc.org/memory v1.12.1 // indirect | ||
| modernc.org/sqlite v1.63.0 // indirect |
There was a problem hiding this comment.
Nit: modernc.org/sqlite is imported directly (model/cursor_auth.go, model/aicode_backfill_antigravity.go) but is listed as // indirect. Its siblings modernc.org/libc, mathutil and memory are indirect, and go-isatty and x/sys are bumped alongside, so go mod tidy will rewrite this file. Fix: run go mod tidy and move it to the direct require block.
Since model is linked into every shelltime invocation, the pure-Go SQLite driver and libc also add binary size and package init work to the track hot path, where CLAUDE.md says latency matters (about 8 ms). Please check the perf/ benchmark, or move the sqlite code behind a package only the daemon and backfill commands import.
| since := now.Add(-cursorUsageInitialLookback) | ||
| if st := s.loadState(); st.LastSyncedUnix > 0 { | ||
| candidate := time.Unix(st.LastSyncedUnix, 0).Add(-cursorUsageSyncOverlap) | ||
| if candidate.After(since) && candidate.Before(now) { |
There was a problem hiding this comment.
Important: Cursor usage is lost whenever the daemon was down or Cursor was closed for more than about 24 hours. since starts at now-24h, and the saved cursor only wins when candidate.After(since), so an older LastSyncedUnix is ignored and the 24h window is used instead. Example: last sync 3 days ago, daemon restarts, and days 3 to 1 ago are never fetched. Fix: use the saved cursor whenever it is set and before now (cap the lookback at cursorDefaultLookback, 90 days, if you want a limit), and use the 24h default only when there is no saved state. The Antigravity service has the same shape: antigravityUsageInitialLookback plus the in-memory fingerprints mean files last modified more than 48h ago are never picked up.
| if count < pageRows { | ||
| break | ||
| } | ||
| after = lastRowID |
There was a problem hiding this comment.
Important: readMeta can loop forever, and the daemon would hang with it. lastRowID is set only after a successful Scan, and after = lastRowID is taken whenever count == pageRows. If every row of a full page of 64 fails Scan (for example a non-integer idx, or a type mismatch), lastRowID stays 0, after becomes 0, and the same page is requested again forever. rows.Err() is also never checked, so a mid-iteration error looks like a short page. Nothing here takes a context, so the 30s timeout in the daemon's sync() does not stop it, and Stop() blocks in wg.Wait(), so SIGTERM never finishes. Fix: use rows.Next's own rowid (scan it into a separate variable first, or SELECT rowid alone) and advance after for every row read, including bad ones. Check qRows.Err(), and break if after did not advance.
| // idempotently via /api/v1/cc/backfill, followed by /api/v1/cc/backfill/complete. | ||
| // When skipCountCheck is true (for incremental window fetches like Cursor), already-backfilled | ||
| // sessions are still uploaded so server-side event_id deduplication accepts new events. | ||
| func uploadDaemonUsageSessions( |
There was a problem hiding this comment.
Important: the daemon uploads sessions that are still running and marks them complete, which the CLI backfill deliberately avoids. runAICodeBackfill passes sessions through SelectBackfillSessions (the backfillSettleWindow hold-back, and the Since/Until range), because a session is listed in completedSessionIds only once all its events are stored and the server then builds its summary. uploadDaemonUsageSessions skips that filter, then calls CompleteAICodeBackfill on every 10-minute tick. A Cursor conversation or an Antigravity DB being written right now is therefore uploaded partially and finalized (summary, dashboard refresh and cache flush) on every tick. For Cursor, the incremental window also means cursor-day-* and conversation sessions carry only the events inside the window, with skipCountCheck=true. Fix: apply model.SelectBackfillSessions (or the same settle window) before uploading, or only list a session as complete once it has settled. Note too that ParseAntigravityDBFiles ignores opts.Since/opts.Until, so the daemon's 24h lookback does not bound what is uploaded.
| } | ||
| } | ||
|
|
||
| cursorUsageSyncService := daemon.NewCursorUsageSyncService(cfg) |
There was a problem hiding this comment.
Important: the Cursor and Antigravity sync services start unconditionally, with no config switch and no AI-cloud-only check. They read Cursor's bearer token from state.vscdb, ~/.cursor/auth.json or env, call Cursor's API, and upload token and cost events and quota to ShellTime for every user with a token, without opting in. CLAUDE.md says optional daemon services are "feature-gated via config" and that "Services initialize in cmd/daemon/main.go: check enabled flag -> create -> start -> defer stop". These two skip that step and run in AI cloud only mode too, which CLAUDE.md describes as sending only the allowed OTEL, cc pr and session-project paths. The uploaded events also carry machine.apply (user name and machine name). Fix: add an enable flag, for example under the new cursor config and aiCodeOtel, default off or documented as default on. Decide explicitly whether they run in AI cloud only mode, and update the CLAUDE.md "Optional daemon services" text.
| } | ||
| for _, ev := range prev { | ||
| if m, ok := ev.(map[string]any); ok { | ||
| if m["timestamp"] == firstTs { |
There was a problem hiding this comment.
Nit (optional): m["timestamp"] == firstTs compares two any values read from decoded JSON. If the server ever returns a non-scalar timestamp (object or array) on both pages, Go panics with "comparing uncomparable type map[string]interface {}". In the daemon that is an unrecovered panic in a service goroutine, so it kills the daemon. Fix: compare parseCursorTimestampMs results, or use reflect.DeepEqual or a type switch for scalars only.
| if _, err := os.Stat(dbPath); err != nil { | ||
| return "" | ||
| } | ||
| dsn := "file:" + dbPath + "?mode=ro&_pragma=busy_timeout(100)&_pragma=query_only(ON)" |
There was a problem hiding this comment.
Nit (optional): the DSN is built as "file:" + dbPath + "?mode=ro..." without URL-escaping the path. A path containing ?, # or % (for example an XDG_CONFIG_HOME with those characters) is parsed as a different file or query and the token is silently not found. readAntigravityDatabase already does this correctly with url.URL{Scheme: "file", Path: ...}. Fix: build the DSN the same way here. Also, mode=ro on a WAL-mode state.vscdb can fail when there is no -shm file (Cursor closed), which is silently treated as "no token".
| return | ||
| } | ||
|
|
||
| ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
There was a problem hiding this comment.
Nit (optional): the sync context is built from context.Background() rather than the service's ctx, so SIGTERM/SIGINT does not cancel an in-flight sync. Stop() then waits in wg.Wait() for up to the 30s timeout, and for parseAntigravityDBFilesFunc, which takes no context at all, as long as the SQLite scan runs. The same applies to CursorUsageSyncService.sync (cursor_usage_sync.go:98). Fix: derive the timeout context from the ctx passed to Start and check ctx.Err() between DB files.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3a8e524d2f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return nil | ||
| } | ||
|
|
||
| uploaded, _, err := uploadDaemonUsageSessions(ctx, s.config, model.AICodeClientCursor, parsed.Sessions, opts, true) |
There was a problem hiding this comment.
Preserve the watermark while Cursor sessions remain unsettled
When Cursor keeps producing requests less than 30 minutes apart in the same conversation or fallback daily bucket, SelectBackfillSessions excludes that entire session as active. This call discards the returned active count and still advances the watermark, so subsequent fetches retain only the 45-minute overlap. Requests age out of that overlap without ever being uploaded; once the session settles, only its final portion remains available. Retain the earliest pending watermark until held-back sessions upload, or upload individually settled events instead of withholding the entire bucket.
Useful? React with 👍 / 👎.
| activeCount := 0 | ||
| if parsed != nil && len(parsed.Sessions) > 0 { | ||
| var uploaded int | ||
| uploaded, activeCount, err = uploadDaemonUsageSessions(ctx, s.config, model.AICodeClientAntigravity, parsed.Sessions, opts, false) |
There was a problem hiding this comment.
Include recent usage from older Antigravity conversations
When a user resumes an Antigravity conversation whose first request is more than 24 hours old, the modified database is discovered and parsed, but this upload passes the rolling Since bound to SelectBackfillSessions, which filters on the session's first event rather than its recent activity. Because the parser reconstructs the entire conversation, all newly added usage is discarded, and the database fingerprint is subsequently cached. Apply the daemon lookback to recent events or session activity rather than the conversation's original start so resumed conversations continue syncing.
Useful? React with 👍 / 👎.
| return nil | ||
| } | ||
|
|
||
| uploaded, _, err := uploadDaemonUsageSessions(ctx, s.config, model.AICodeClientCursor, parsed.Sessions, opts, true) |
There was a problem hiding this comment.
Important: Events of a long Cursor session are lost. uploadDaemonUsageSessions skips every session whose last event is inside the 30-minute settle window and returns activeCount, but this call discards it (_). syncTokenUsage then saves LastSyncedUnix = now, and the next fetch starts at lastSynced - 45min, which is later than the start of any session that has been active for more than about 45 minutes.
Example: a 2-hour continuous session is skipped as active on every tick. When it finally settles, only its last ~45 to 55 minutes of events are fetched (the earlier ones are filtered out by normalizeCursorUsageEvent as older than since), so the early events are never uploaded.
Fix: when activeCount > 0, do not advance the state beyond the oldest start of the skipped sessions, or keep the previous LastSyncedUnix. The overlap should also cover backfillSettleWindow plus the session length.
| } | ||
|
|
||
| opts := model.BackfillOptions{ | ||
| Since: since, |
There was a problem hiding this comment.
Important: New usage in an older Antigravity conversation is never synced. ParseAntigravityDBFiles builds one session per DB file (id = file name) with Start = the earliest event, and does not filter events by opts.Since. uploadDaemonUsageSessions then calls SelectBackfillSessions, which drops any session whose Start is before opts.Since, and here Since is now - 24h.
Example: a conversation begun two days ago and used again today has Start two days back, so the whole session is dropped on every tick. The fingerprint is then recorded as handled, so the DB is never retried until it changes again.
Fix: don't pass the 24h Since to SelectBackfillSessions (only to the file pruning), or filter events by time and rebuild session Start from the retained events.
| if count < pageRows { | ||
| break | ||
| } | ||
| after = lastRowID |
There was a problem hiding this comment.
Important: Pagination can loop forever. lastRowID is only set after a successful Scan. If every row of a 64-row page fails Scan (for example a non-integer idx), lastRowID stays 0. count == pageRows holds, so after becomes 0 and the same page is read again, forever, inside the daemon sync goroutine or the CLI.
Fix: scan rowid first and set lastRowID before any other error handling. Also check qRows.Err() and bail out if the cursor does not advance.
| parts := strings.Split(token, ".") | ||
| if len(parts) < 2 { | ||
| // Allow non-JWT opaque tokens by hashing the token itself as account key. | ||
| sum := sha256.Sum256([]byte(token)) |
There was a problem hiding this comment.
Important: Cursor events are uploaded again when a token that is not a JWT rotates. For such tokens, and for JWTs whose payload is not raw base64url, the account key is a SHA-256 of the whole token. The key goes into every dedupeKey (cursor-account:<key>:...), so each new token gives every event a new id and the server's event-id dedupe no longer matches. This applies to opaque CURSOR_AUTH_TOKEN values, and to the state.vscdb or auth.json tokens that Cursor refreshes regularly. Re-fetching the 45-minute overlap window then double-counts usage.
Fix: derive a stable account identity (the GetMe userId, which is already fetched), or fail when no stable sub is available. Do not hash the credential.
| } | ||
|
|
||
| rawCount := len(normalized) | ||
| if total != nil && rawCount < *total { |
There was a problem hiding this comment.
Important: A sync fails whenever Cursor is used while it is paginating. totalUsageEventsCount is re-read on every page, and a change aborts the whole scope with "changed mid-pagination". The rawCount < *total check (and the later removalsRemaining check) also fail when a new event lands between pages. This needs more than one page (over 1000 events, so mainly shelltime cursor backfill with its 90-day default), and the daemon only syncs while Cursor is running, so new events are likely.
Fix: pin endDate/untilMs (already fixed) and tolerate a larger total instead of erroring. Alternatively retry the scope once, or treat a count that grew as a re-fetch rather than a fatal error.
| }) | ||
| } | ||
|
|
||
| return &CursorRateLimitData{ |
There was a problem hiding this comment.
Nit (optional): CursorRateLimitData.Plan is never populated. mapCursorCurrentPeriodUsage returns only Windows, so /api/v1/cursor-usage always receives "plan": "". Either fill it from the response (if Cursor returns it) or drop the field from the payload.
…, and fix Antigravity scan
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3efdb6a4ea
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if !isAntigravityRunning() { | ||
| slog.Debug("Skipping antigravity usage sync", slog.String("reason", "antigravity_not_running")) | ||
| return |
There was a problem hiding this comment.
Drain pending usage after the client exits
When a user closes Antigravity within 30 minutes of their last request, SelectBackfillSessions still considers the conversation active during every scan while the application is running. After exit, this early return prevents the pending conversation from ever being scanned once it settles, so its usage remains unuploaded unless the user reopens Antigravity; reopening after the file-discovery lookback can lose it entirely. Cursor's sync has the same running-process gate and settle-window interaction. Allow pending token-usage scans to continue after client exit, even if quota polling remains restricted to running clients.
Useful? React with 👍 / 👎.
| } | ||
| } | ||
|
|
||
| dedupeKey := fmt.Sprintf("antigravity:%s:%s:%d:%d", sessionID, source, index, usageIdx) |
There was a problem hiding this comment.
Important: a usage record with no id in fields 11, 12 or 7 gets a key built from its source and position (antigravity:<session>:step|generation:<index>:<n>), and steps and generations are both processed. The same LLM call recorded in both tables then gets two different keys, so the union-find never merges them and its tokens are counted twice. Only the keyed case is tested. Fix: also merge unkeyed step and generation records that share idx, model and token counts, or key them by item.idx and not by source, and add a test with usages that have no ids.
The same happens for an unkeyed session found under two roots (for example antigravity and antigravity-backup): both copies carry the same event id but stay separate events in Session.Events, which inflates printBackfillDays and the count in uploadDaemonUsageSessions.
| Until: now, | ||
| Now: now, | ||
| } | ||
| parsed, err := parseAntigravityDBFilesFunc(changed, parseOpts) |
There was a problem hiding this comment.
Nit (optional): only the changed DBs are parsed (changed), but the parser learns model ids and merges duplicate usage across all the files it is given. A DB that did not change this tick therefore contributes no learned model names and no cross-DB merging. A changed DB whose records need a name learned from another DB gets antigravity-model-N or the offline fallback name. Records shared with a backup root are merged only if both copies are in the same call. Fix: parse every file in files and upload only the sessions of the changed ones, or at least feed the unchanged DBs to the model-learning pass.
| previousEvents []any | ||
| ) | ||
|
|
||
| for page := 1; ; page++ { |
There was a problem hiding this comment.
Nit (optional): the page loop ends only when a page has fewer than cursorUsagePageSize events. totalUsageEventsCount is read into total, but nothing uses it, and there is no page cap. If the server ignores page or keeps returning a full page, shelltime cursor backfill loops forever and normalized grows without limit. The CLI has no overall deadline, since each request has 15 s but the loop does not. The daemon's 30 s context bounds it. Fix: add a maximum page count, or stop when a page repeats the previous one exactly, or when the number of events seen reaches total.
| return nil | ||
| } | ||
|
|
||
| uploaded, activeCount, err := uploadDaemonUsageSessions(ctx, s.config, model.AICodeClientCursor, parsed.Sessions, opts, true) |
There was a problem hiding this comment.
Nit (optional): with skipCountCheck=true every settled session in the window is re-uploaded in full on every tick, and CompleteAICodeBackfill (dashboard refresh and cache flush) runs each time. The window always overlaps the last run by 45 min. While any session is still inside the 30-minute settle window (activeCount > 0) the state is not saved, so since stays at the 24 h lookback. A long Cursor conversation therefore re-uploads all sessions of the last 24 h every 10 min. Fix: remember per session the last uploaded event count or timestamp in the state file and upload only sessions with newer events.
| if len(entries) == 0 || !entries[0].isNum { | ||
| return 0 | ||
| } | ||
| return int(entries[0].num) |
There was a problem hiding this comment.
Nit (optional): int(entries[0].num) converts a uint64 straight to int. A 10-byte varint (a negative int64, or a corrupt record) becomes a negative int. Token counts can then go negative, and the uncachedIn+cachedIn+cacheCreate+outTok == 0 skip is fooled by values that sum to zero. Fix: treat values above math.MaxInt32 (or MaxInt64) as bad rows and skip the record.
| continue | ||
| } | ||
| sessionID := strings.TrimSuffix(filepath.Base(path), ".db") | ||
| cands, models, rowBad, err := readAntigravityDatabase(path, sessionID, st.ModTime().UnixMilli()) |
There was a problem hiding this comment.
Nit (optional): the fallback timestamp for events with no timestamp is st.ModTime() of the .db file only. A live Antigravity DB in WAL mode keeps its main file untouched until a checkpoint, while AntigravityDBFingerprint reads the -wal mtime. Such events get a stale timestamp, which can place them before --since or in the wrong day of printBackfillDays. Because the stat is repeated each scan, the same event also changes timestamp whenever the DB is checkpointed. Fix: use the later of the .db and -wal mtimes, as the fingerprint does.
| "time" | ||
| "unicode/utf8" | ||
|
|
||
| _ "modernc.org/sqlite" |
There was a problem hiding this comment.
Nit (optional): CLAUDE.md treats shelltime track latency as a core constraint (under 8 ms with the daemon). This blank import, and the one in model/cursor_auth.go, link modernc.org/sqlite and modernc.org/libc into every package that imports model, cmd/cli included. That adds binary size and package init work to every hook-time shelltime track invocation, although only agy backfill and the Cursor state.vscdb lookup use SQLite. Fix: check the Track Perf report on this PR. If it regresses, move the SQLite code behind a separate package that only the backfill and daemon paths import.
|
|
||
| color.Yellow.Printf("Scanning %s transcripts...\n", src.name) | ||
| parsed, err := src.parse(src.roots(), opts) | ||
| color.Yellow.Printf("Scanning %s usage...\n", src.name) |
There was a problem hiding this comment.
Nit (optional): the messages after this scan still assume transcript files. parsed.Files is the number of API scopes for Cursor, so a Cursor user with no sessions sees "No finished Cursor sessions found in 1 files." The slog.Warn("skipped unreadable transcript lines") also reads wrongly for DB rows and API events, and the new parsed.FailedFiles is never reported by the CLI. Fix: use wording that fits all sources, such as "in N sources", and log FailedFiles.
…ed Antigravity duplicates
| if st.Status == model.AICodeBackfillStatusLive || st.Status == model.AICodeBackfillStatusArchived { | ||
| continue | ||
| } | ||
| if !skipCountCheck && st.Status == model.AICodeBackfillStatusBackfilled && st.EventCount >= len(sess.Events) { |
There was a problem hiding this comment.
Important: with skipCountCheck=true, every session the server already holds as Backfilled is uploaded again on every tick. syncTokenUsage reads from lastSynced - 45min, so each event is re-sent about five times. Each tick that has any session in the window also ends with CompleteAICodeBackfill, which refreshes dashboards and flushes the server cache. This runs every 10 minutes while Cursor is open, even when nothing is new.
Fix: compare the fetched events against st.EventCount for the window, or drop sessions whose events the server already has. At minimum, skip the /complete call when accepted == 0.
| s.mu.Lock() | ||
| s.hasPending = false | ||
| s.mu.Unlock() | ||
| s.saveState(cursorUsageSyncState{LastSyncedUnix: now.Unix()}) |
There was a problem hiding this comment.
Nit (optional): LastSyncedUnix is set to now after any successful fetch, including one that returned nothing. The next window then starts at now - 45min. Cursor billed usage events can show up in GetFilteredUsageEvents later than that. Any event that arrives after the 45-minute overlap is never fetched, and the state has already moved on. The hasPending and activeCount logic only covers sessions that are still active, not events that arrive late.
Fix: widen the overlap, or advance the cursor to the newest event timestamp seen, minus a margin, instead of now.
| return isProcessRunning(codexProcessKeywords) | ||
| } | ||
|
|
||
| func isCursorRunning() bool { |
There was a problem hiding this comment.
Nit (optional): isCursorRunning goes through matchKnownName, which uses strings.Contains. The keyword cursor therefore matches any process whose name contains it, such as macOS's CursorUIViewService system process and Cursor's Cursor Helper (...) processes. The daemon then treats Cursor as running when the editor is closed. It reads state.vscdb and calls the quota API every 10 minutes, which contradicts "only while a cursor process is running".
Fix: match the exact basenames (cursor, Cursor, cursor-agent) like isAntigravityRunning does for agy, or exclude known system helpers.
| } | ||
|
|
||
| s.mu.Lock() | ||
| s.hasPending = activeCount > 0 || (parsed != nil && len(parsed.FailedFiles) > 0) |
There was a problem hiding this comment.
Nit (optional): two retry-state problems in syncOnce. (1) hasPending is set to true whenever parsed.FailedFiles is non-empty. A permanently unreadable DB (corrupt, or an unsupported schema that errors) keeps hasPending true for good. The service then re-parses every changed file every 10 minutes, even after agy exits, which defeats the "only while agy is running" gate. (2) When uploadDaemonUsageSessions returns an error (line 162), hasPending is not set, and the fingerprints are not stored either. If agy quits before the next tick, the scan stops and that upload is not retried until a DB changes or the daemon restarts.
Fix: set hasPending on the upload-error path, and bound retries for failed files with a counter or backoff.
| return f, true, nil | ||
| } | ||
|
|
||
| inF, _, err := parseNonNeg("inputTokens") |
There was a problem hiding this comment.
Nit (optional): normalizeCursorUsageEvent ignores whether any token field was present (the _ discards the bool). An event whose tokenUsage is {}, or has only totalCents, becomes an api_request event with 0/0/0/0 tokens. That inflates request counts and day totals. The Antigravity path skips records where all token counts are 0.
Fix: return nil, nil when input, output, cache read and cache write are all absent or 0, as the Antigravity path does.
| if len(events) > 0 && len(previousEvents) > 0 { | ||
| if cursorPagesMayOverlap(previousEvents, events) { | ||
| overlap = cursorBoundaryOverlap(cursorCanonicalList(previousEvents), cursorCanonicalList(events)) | ||
| } |
There was a problem hiding this comment.
Nit (optional): the cursorUsageMaxPages = 200 loop ends silently. If a scope has more than 200,000 events, the result is truncated and no error or partial flag is returned. The daemon then advances LastSyncedUnix to now, so the remainder is permanently skipped. The total count is collected but never compared with what was fetched.
Fix: return an error, or mark the result incomplete, when the page cap is hit or len(normalized) is less than total.
| func readAntigravityDatabase(path, sessionID string, fallbackTimestampMs int64) ([]agyUsageCandidate, map[int]agyLearnedModel, int, error) { | ||
| // Open strictly read-only with URI-encoded path so paths containing ?, #, or % work safely | ||
| // and SQLite never creates -wal/-shm files next to a live agent DB. | ||
| dsnURL := url.URL{ |
There was a problem hiding this comment.
Nit (optional): the comment says mode=ro means "SQLite never creates -wal/-shm files next to a live agent DB". That is not true for WAL-mode databases. A read-only connection to a WAL DB with no -shm or -wal file (the agent has closed it cleanly) still creates them when the directory is writable. Also, ParseAntigravityDBFiles ignores opts.Since and opts.Until entirely, so the daemon parses and uploads every event in each changed DB, not just the recent ones.
Fix: correct the comment, or open with immutable=1 on a copy if no side effects are required. Apply the time window to events if only recent usage is wanted.
Summary
Adds usage collection for Cursor and Google Antigravity (
agy) following the existing Claude Code and Codex workflows, modeled onpingdotgg/t3code's Cursor DashboardService and Antigravity SQLite/protobuf usage readers.Changes
CGO_ENABLED=0): Addedmodernc.org/sqliteso GoReleaser andperf/builds remainCGO_ENABLED=0.CURSOR_AUTH_TOKEN,CURSOR_API_KEY,config.cursor.apiKey,~/.cursor/auth.json/~/.config/cursor/auth.json, or Cursor IDEstate.vscdb(exchanging API keys via/auth/exchange_user_api_keywith redirects disabled).aiserver.v1.DashboardService/GetFilteredUsageEventswith page-boundary deduplication andtotalCents / 100cost mapping.shelltime cursor backfillCLI command andCursorUsageSyncService(syncs monthly quota viaGetCurrentPeriodUsage->POST /api/v1/cursor-usageand incremental token usage via/api/v1/cc/backfillevery 10 minutes while Cursor is running).agy) backfill & daemon sync:*.db+-walfingerprinting), decodes protobufgen_metadata/steps/trajectory_metadata_blob, resolves model IDs + cross-DB learned models, and deduplicates across steps/retries.shelltime agy backfillCLI command andAntigravityUsageSyncService(syncs changed DBs every 10 minutes whileantigravity/agyis running).cursorconfig (apiKey,apiEndpoint) with masked logging, and updatedREADME.md,docs/CONFIG.md, andCLAUDE.md.Testing
mockery&go vet ./...CGO_ENABLED=0 go buildfor both./cmd/cli/main.goand./cmd/daemon/main.goCGO_ENABLED=0 go test -timeout 3m -coverprofile=coverage.txt -covermode=atomic ./...(all packages passed:agenthook93.8%,commands85.0%,daemon88.6%,model83.6%,stloader97.2%)ROUNDS=3 ITERS=20 perf/compare.sh HEAD: no significant change inshelltime tracklatency (Startup/version9.47 ms -> 9.60 ms,Track/daemon/pre9.39 ms -> 9.87 ms,Track/daemon/post9.65 ms -> 9.80 ms).Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.