diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index 13642790..b9dafb37 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -12,7 +12,7 @@ CodeBurn discovers Antigravity sessions from local directories on disk, then que 1. **Session Discovery:** It scans the following folders for `.pb` or `.db` files: - **Antigravity CLI:** `%USERPROFILE%\.gemini\antigravity-cli\conversations` (and `implicit`) - - **Antigravity App/older path:** `%USERPROFILE%\.gemini\antigravity\conversations` + - **Antigravity App/older path:** `%USERPROFILE%\.gemini\antigravity\conversations`. The standalone app (2.19+, `language_server --standalone --subclient_type hub --app_data_dir antigravity`) writes here too: new conversations as `.db`, older ones stay `.pb`. - **Antigravity IDE:** `%USERPROFILE%\.gemini\antigravity-ide\conversations` (and `implicit`). The IDE also maintains VSCode-style global state at `%APPDATA%\Antigravity IDE\User\globalStorage\state.vscdb`, but that DB stores trajectory metadata (titles, timestamps, workspace paths) — not token usage. Token usage data still comes from the `.db` conversation files. 2. **Language Server RPC Query:** It locates the active language-server process via `ps` on POSIX or `Get-CimInstance Win32_Process` on Windows. It extracts the port and CSRF token from the process arguments, and queries the local HTTPS RPC endpoint `GetCascadeTrajectoryGeneratorMetadata` to parse the session. 3. **Cache Fallback:** If the language server is not running, it falls back to the local results cache. @@ -44,7 +44,7 @@ Native Antigravity Desktop, IDE, and CLI sessions store structured state in SQLi 1. **`gen_metadata` (Model Generations)**: - Each row represents a completed LLM completion turn. - `data` BLOB Protobuf: - - **Field 1 (`ChatModel`)**: Token usage (`Field 4`: input, output, cached, thinking), canonical model ID (`Field 9`), display name (`Field 21`), and generation timestamp (`Field 9 -> Field 4`). + - **Field 1 (`ChatModel`)**: Token usage (`Field 4`, see Accuracy), model config id (`Field 19`, e.g. `gemini-pro-default`), key/value metadata including `model_enum` (`Field 20`), display name (`Field 21`, absent in the standalone app), and generation timestamp (`Field 9 -> Field 4`). - **Field 2 (`stepIndices`)**: Packed varints listing the exact `steps.idx` rows produced during that generation turn. - **Field 4**: Generation UUID used for deduplication (`:`). 2. **`steps` (Execution Steps & Tools)**: @@ -65,9 +65,51 @@ Native Antigravity Desktop, IDE, and CLI sessions store structured state in SQLi For older `.pb` files, cascade and response objects map to `ParsedProviderCall` directly via the language-server RPC. +## Accuracy + +The usage message is `exa.codeium_common_pb.ModelUsageStats`; field numbers +come from the descriptor embedded in the `language_server` binary and match the +RPC JSON names: + +| Field | Name | CodeBurn | +|---|---|---| +| 1 | `model` (enum, e.g. 1016 = `MODEL_PLACEHOLDER_M16`) | not read; the same id comes from the `model_enum` key | +| 2 | `input_tokens` (uncached) | `inputTokens` | +| 3 | `output_tokens` (= 9 + 10) | fills `outputTokens` when 9 and 10 are missing or disagree | +| 4 | `cache_write_tokens` | `cacheCreationInputTokens` | +| 5 | `cache_read_tokens` | `cacheReadInputTokens` | +| 6 | `api_provider` (24 = `API_PROVIDER_GOOGLE_GEMINI`) | ignored | +| 9 | `thinking_output_tokens` | `reasoningTokens`, billed at the output rate | +| 10 | `response_output_tokens` | `outputTokens` | +| 11 | `response_id` | dedup key | + +- **Exact:** call count, input, output, thinking and cache-read tokens, from + both `.db` files and the RPC. Cache read is separate from input (it is often + larger), so it is priced at the cache-read rate on top of input. +- **Estimated:** the model of `.db` calls that carry only a placeholder. The + standalone app writes `model_enum=MODEL_PLACEHOLDER_M16` and + `gemini-pro-default`, with no display name. CodeBurn maps the placeholder + through a small table taken from the app's own `GetAvailableModels` catalog + (6 Oct 2026, app 2.19.1): `M16` and `M37` are Gemini 3.1 Pro (High), `M36` + Gemini 3.1 Pro (Low), `M84` Gemini 3.5 Flash (High), `M18` Gemini 3 Flash, + `M35` Claude Sonnet 4.6, `M26` Claude Opus 4.6 (Thinking). These calls carry + `costIsEstimated`, because a later app build can repoint a placeholder. + `.pb` calls resolve the placeholder through the live catalog at parse time + and are not flagged. Gemini 3.1 Pro prices as `gemini-3.1-pro-preview`: + $2/M input, $12/M output, $0.20/M cache read, and $4/$18/$0.40 per request + whose prompt (input + cache read) reaches 200,000 tokens. Google's rule is + "over 200k", so a prompt of exactly 200,000 gets the higher rate one token + early; the shared threshold check uses `>=` for every tiered provider. +- **Timestamps:** `ChatStartMetadata.created_at` when present. Standalone-app + rows leave it out; they take the time of the generation's first step + (`steps.metadata` #1), which equals `created_at` to the second wherever both + exist. The file mtime is the last resort. +- A placeholder that is in neither the table nor the live catalog stays + unpriced and shows as `$0` under `codeburn models --unpriced`. + ## Caching -Custom file cache at `$CODEBURN_CACHE_DIR/antigravity-results.v.json` (version 6, defaults to `~/.cache/codeburn/`). The unsuffixed `antigravity-results.json` is left for older binaries; a matching-version copy is adopted once and never overwritten. The cache is also used as the data source when the RPC endpoint is unavailable, not just as an optimization. Bumping the cache version forces a recompute. +Custom file cache at `$CODEBURN_CACHE_DIR/antigravity-results.v.json` (version 8, defaults to `~/.cache/codeburn/`). The unsuffixed `antigravity-results.json` is left for older binaries; a matching-version copy is adopted once and never overwritten. The cache is also used as the data source when the RPC endpoint is unavailable, not just as an optimization. Bumping the cache version forces a recompute. ## Deduplication @@ -79,13 +121,13 @@ double-counted. ## Quirks -- **Antigravity is the only provider that requires a live process.** A user who closes Antigravity loses the most-recent data until next launch (the cache covers older runs). +- **`.pb` conversations need the live process.** `.db` conversations are read straight from SQLite; `.pb` ones only through the RPC, so with Antigravity closed they come from the results cache. After a cache-version bump, a `.pb` cascade missing from the new file is served from the previous version's file (stored with `mtimeMs: -1`) until a run with Antigravity open re-fetches it. +- `~/.gemini/antigravity-backup` is not scanned. On the machine checked it held only a copy of a conversation also under `antigravity` and `antigravity-ide`, which the cascade-id dedup would drop anyway. - **Antigravity CLI has a shorter capture window than the desktop app.** `agy` exposes its language server only while the CLI session is active. The status line hook closes that gap for future sessions; older CLI `.pb` files still cannot be priced exactly unless an RPC snapshot was captured. - The 16 MB cap on RPC responses is necessary because individual cascades can balloon. Raising it risks OOM on the user's machine. -- Token types are split across `inputTokens`, `responseOutputTokens`, and `thinkingOutputTokens`. Thinking is billed at output rate. ## When fixing a bug here diff --git a/src/daily-cache.ts b/src/daily-cache.ts index 533e2d5f..bc33c6cb 100644 --- a/src/daily-cache.ts +++ b/src/daily-cache.ts @@ -288,7 +288,14 @@ import type { DateRange, ProjectSummary } from './types.js' // tag instead of the session's last write. Settled days re-derive; a session // that crossed midnight moves calls to an earlier day, so cursor-agent joins // PENDING_REDERIVE_PROVIDER_VERSIONS at 58. -export const DAILY_CACHE_VERSION = 58 +// v59: Antigravity reads cache-read tokens from gen_metadata and the RPC usage, +// and the standalone app's placeholder-only model (MODEL_PLACEHOLDER_M16, stored +// as "gemini-pro-default") prices as gemini-3.1-pro-high instead of $0, with +// the above-200k tier. Cache read and cost only rise. Standalone rows without +// created_at move from the file-mtime day to their first step's day, so a +// session that crossed midnight moves calls to an earlier day, and antigravity +// joins PENDING_REDERIVE_PROVIDER_VERSIONS at 59. +export const DAILY_CACHE_VERSION = 59 const MIN_SUPPORTED_VERSION = 28 /// Providers whose per-day CALL COUNT means something different at @@ -331,6 +338,9 @@ const PENDING_REDERIVE_PROVIDER_VERSIONS: Readonly> = { devin: 46, // 58: transcript turns moved from the session's last write to prompt time. 'cursor-agent': 58, + // 59: standalone rows without created_at moved from the file mtime to the + // first step's time. + antigravity: 59, } function providersPendingRederiveFrom(fromVersion: number): string[] { diff --git a/src/models.ts b/src/models.ts index 34fcfb2d..bd5b292b 100644 --- a/src/models.ts +++ b/src/models.ts @@ -179,7 +179,9 @@ const GROK_4_6_HIGH_PROMPT_COSTS = buildCosts(4e-6, 12e-6, null, 1e-6, null) // codex sites and the parser.ts central recompute pass it; the Claude journal // paths and the copilot residual path do not, so a newly added provider whose // calls flow through those sites would silently stay tierless). -export const TIERED_PRICING_PROVIDERS: ReadonlySet = new Set(['codex']) +// antigravity has no per-token bill of its own; its cost is the Gemini API +// equivalent, and the Gemini API bills the above-200k tier per request. +export const TIERED_PRICING_PROVIDERS: ReadonlySet = new Set(['codex', 'antigravity']) // Swap in the vendor's high tier when a request's prompt crosses the published // threshold. A user-set priceOverride wins over any tier: the override row diff --git a/src/parser.ts b/src/parser.ts index 36cae99b..864ef1ea 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -10,7 +10,7 @@ import { resolveSubagentAttribution, sessionIdentity } from './sessions-report.j import { normalizeContentBlocks, flatSlice, flatString } from './content-utils.js' import { discoverAllSessions, discoverAllSessionsWithFailures, getProvider } from './providers/index.js' import { evictCachedCodexResults, flushCodexCache, readCachedCodexResults, withCodexCacheDirectory, writeCachedCodexResults } from './codex-cache.js' -import { antigravityCascadeIdFromPath, flushAntigravityCache, shouldReparseAntigravitySource } from './providers/antigravity.js' +import { antigravityCascadeIdFromPath, flushAntigravityCache, preloadAntigravityCache, shouldReparseAntigravitySource } from './providers/antigravity.js' import { getClaudeConfigDirs, getDesktopSessionsDirs } from './providers/claude.js' import { kimicodeLineageForSource } from './providers/kimicode.js' import { isSqliteBusyError } from './sqlite.js' @@ -3483,6 +3483,7 @@ export async function parseProviderSources( // for this whole parse transaction so a host changing CODEBURN_CACHE_DIR // before the final flush cannot redirect A's dirty state into (or past) B. const antigravityCacheDir = providerName === 'antigravity' ? getCodeburnCacheDir() : undefined + if (antigravityCacheDir && !readOnly) await preloadAntigravityCache(antigravityCacheDir) const section = getOrCreateProviderSection(diskCache, providerName) if (providerName === 'hermes' && !readOnly) { diff --git a/src/providers/antigravity.ts b/src/providers/antigravity.ts index 2122cdee..c79e0500 100644 --- a/src/providers/antigravity.ts +++ b/src/providers/antigravity.ts @@ -50,7 +50,7 @@ function conversationRoots(): readonly AntigravityConversationRoot[] { }, ] } -const CACHE_VERSION = 7 +const CACHE_VERSION = 8 export const ANTIGRAVITY_CACHE_VERSION = CACHE_VERSION export const ANTIGRAVITY_LEGACY_CACHE_FILE = 'antigravity-results.json' export function antigravityCacheFileName(version = CACHE_VERSION): string { @@ -77,6 +77,8 @@ type UsageEntry = { outputTokens: string thinkingOutputTokens?: string responseOutputTokens?: string + cacheReadTokens?: string + cacheWriteTokens?: string apiProvider: string responseId?: string } @@ -190,6 +192,7 @@ const cachedServers = new Map>() const cachedModelMaps = new Map>() type AntigravityCacheState = { cache: AntigravityCache; dirty: boolean } const cacheStates = new Map() +const previousVersionCascades = new Map>() // Dropped by the resident RSS guard. A dirty state holds cascades not yet on // disk, so it stays resident until its own flush publishes it. The server and @@ -198,6 +201,7 @@ const cacheStates = new Map() export function clearAntigravityCacheStates(): void { cachedServers.clear() cachedModelMaps.clear() + previousVersionCascades.clear() for (const [dir, state] of cacheStates) { if (!state.dirty) cacheStates.delete(dir) } @@ -418,6 +422,28 @@ async function loadCache(cacheDir: string): Promise { return state } +// A cache-version bump drops every .pb cascade, and .pb files are readable +// only through the RPC, so with Antigravity closed they would vanish until it +// is next opened. Serve the previous version's entry meanwhile; mtimeMs -1 +// makes the next run with the server up re-fetch it. +async function adoptPreviousVersionCascade(cacheDir: string, state: AntigravityCacheState, cascadeId: string): Promise { + let cascades = previousVersionCascades.get(cacheDir) + if (!cascades) { + cascades = {} + try { + const cache = JSON.parse(await readFile(join(cacheDir, antigravityCacheFileName(CACHE_VERSION - 1)), 'utf-8')) as AntigravityCache + if (cache.version === CACHE_VERSION - 1 && cache.cascades && typeof cache.cascades === 'object') cascades = cache.cascades + } catch { /* no previous cache */ } + previousVersionCascades.set(cacheDir, cascades) + } + const previous = cascades[cascadeId] + if (!previous?.calls?.length) return undefined + const adopted = { mtimeMs: -1, sizeBytes: previous.sizeBytes, calls: previous.calls } + state.cache.cascades[cascadeId] = adopted + state.dirty = true + return adopted +} + async function flushCache(liveCascadeIds?: Set, cacheDir = currentCacheDir()): Promise { const state = cacheStates.get(cacheDir) if (!state) return @@ -782,15 +808,32 @@ function antigravitySqliteMetadataAttributes(chatFields: readonly ProtoField[]): return attributes } -function antigravitySqliteModel(chatFields: readonly ProtoField[]): string { +// The standalone app (2.19) writes only the placeholder enum and a generic +// "gemini-pro-default" into gen_metadata, no display name. These are the ids +// its own GetAvailableModels catalog resolved those placeholders to on 6 Oct +// 2026 (the same ids the RPC path derives). A later app build can repoint a +// placeholder, so calls resolved here are flagged as estimated. +const PLACEHOLDER_MODELS: Record = { + MODEL_PLACEHOLDER_M16: 'gemini-3.1-pro-high', + MODEL_PLACEHOLDER_M37: 'gemini-3.1-pro-high', + MODEL_PLACEHOLDER_M36: 'gemini-3.1-pro-low', + MODEL_PLACEHOLDER_M84: 'gemini-3.5-flash-high', + MODEL_PLACEHOLDER_M18: 'gemini-3-flash', + MODEL_PLACEHOLDER_M35: 'claude-sonnet-4-6', + MODEL_PLACEHOLDER_M26: 'claude-opus-4-6-thinking', +} + +function antigravitySqliteModel(chatFields: readonly ProtoField[]): { model: string; estimated: boolean } { const attributes = antigravitySqliteMetadataAttributes(chatFields) const displayName = protoFieldText(firstProtoField(chatFields, 21)) + const placeholderModel = PLACEHOLDER_MODELS[attributes.get('model_enum') ?? ''] + if (!displayName && placeholderModel) return { model: placeholderModel, estimated: true } const rawModel = protoFieldText(firstProtoField(chatFields, 19)) ?? attributes.get('model_enum') ?? displayName ?? 'unknown' - return getCanonicalModelId(rawModel, displayName) + return { model: getCanonicalModelId(rawModel, displayName), estimated: false } } // Decode a proto field that carries a time into an ISO-8601 string. Antigravity @@ -963,16 +1006,21 @@ function buildCallFromSqliteGenMetadataRow( row: AntigravityGenMetadataRow, rootFields: readonly ProtoField[], turnTools?: TurnTools, + firstStepTimestamp = '', ): ParsedProviderCall | null { const chatFields = parseProtoFields(protoFieldBytes(firstProtoField(rootFields, 1)) ?? new Uint8Array()) const usageFields = parseProtoFields(protoFieldBytes(firstProtoField(chatFields, 4)) ?? new Uint8Array()) if (usageFields.length === 0) return null + // exa.codeium_common_pb.ModelUsageStats: 1 model enum, 2 input (uncached), + // 3 output (thinking + response), 4 cache write, 5 cache read, + // 9 thinking output, 10 response output, 11 response id. const inputTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 2)) - || protoFieldPositiveInteger(firstProtoField(usageFields, 1)) const totalOutputTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 3)) - let responseTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 9)) - let thinkingTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 10)) + const cacheWriteTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 4)) + const cacheReadTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 5)) + let thinkingTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 9)) + let responseTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 10)) if (responseTokens === 0 && thinkingTokens === 0) { responseTokens = totalOutputTokens @@ -984,26 +1032,27 @@ function buildCallFromSqliteGenMetadataRow( if (inputTokens === 0 && totalOutputTokens === 0) return null const responseId = antigravitySqliteResponseId(usageFields, String(row.idx)) - const model = antigravitySqliteModel(chatFields) + const { model, estimated } = antigravitySqliteModel(chatFields) const pricingModel = normalizePricingModel(model) - const costUSD = calculateCost(pricingModel, inputTokens, responseTokens + thinkingTokens, 0, 0, 0) + const costUSD = calculateCost(pricingModel, inputTokens, responseTokens + thinkingTokens, cacheWriteTokens, cacheReadTokens, 0, 'standard', 0, 'antigravity') return { provider: 'antigravity', model, inputTokens, outputTokens: responseTokens, - cacheCreationInputTokens: 0, - cacheReadInputTokens: 0, + cacheCreationInputTokens: cacheWriteTokens, + cacheReadInputTokens: cacheReadTokens, cachedInputTokens: 0, reasoningTokens: thinkingTokens, webSearchRequests: 0, costUSD, + ...(estimated ? { costIsEstimated: true } : {}), tools: turnTools?.tools ?? [], bashCommands: turnTools?.bashCommands ?? [], ...(turnTools?.skills && turnTools.skills.length > 0 ? { skills: turnTools.skills } : {}), ...(turnTools?.subagentTypes && turnTools.subagentTypes.length > 0 ? { subagentTypes: turnTools.subagentTypes } : {}), - timestamp: antigravitySqliteCreatedAt(chatFields), + timestamp: antigravitySqliteCreatedAt(chatFields) || firstStepTimestamp, speed: 'standard', deduplicationKey: `antigravity:${cascadeId}:${responseId}`, userMessage: '', @@ -1039,7 +1088,15 @@ function buildCallsFromSqliteGenMetadata( } } - const call = buildCallFromSqliteGenMetadataRow(cascadeId, row, rootFields, turnTools) + // The standalone app leaves out ChatStartMetadata.created_at; the + // generation's first step carries the same time (steps.metadata #1, a + // Timestamp), which matches created_at to the second where both exist. + const firstStep = stepIndices.length > 0 ? stepMap.get(stepIndices[0]!) : undefined + const firstStepTimestamp = firstStep?.metadata + ? protoTimestampToIso(firstProtoField(parseProtoFields(genMetadataDataBytes(firstStep.metadata)), 1)) + : '' + + const call = buildCallFromSqliteGenMetadataRow(cascadeId, row, rootFields, turnTools, firstStepTimestamp) if (!call) continue if (seenResponseIds.has(call.deduplicationKey)) continue seenResponseIds.add(call.deduplicationKey) @@ -1144,6 +1201,8 @@ function buildCallsFromGeneratorMetadata( const outputTokens = parseInt(usage.outputTokens ?? '0', 10) const thinkingTokens = parseInt(usage.thinkingOutputTokens ?? '0', 10) const responseTokens = parseInt(usage.responseOutputTokens ?? '0', 10) + const cacheReadTokens = parseInt(usage.cacheReadTokens ?? '0', 10) + const cacheWriteTokens = parseInt(usage.cacheWriteTokens ?? '0', 10) if (inputTokens === 0 && outputTokens === 0) continue @@ -1153,15 +1212,15 @@ function buildCallsFromGeneratorMetadata( const model = dropPlaceholderModelId(modelMap[usage.model] ?? usage.model) const pricingModel = normalizePricingModel(model) const timestamp = entry.chatModel?.chatStartMetadata?.createdAt ?? '' - const costUSD = calculateCost(pricingModel, inputTokens, responseTokens + thinkingTokens, 0, 0, 0) + const costUSD = calculateCost(pricingModel, inputTokens, responseTokens + thinkingTokens, cacheWriteTokens, cacheReadTokens, 0, 'standard', 0, 'antigravity') results.push({ provider: 'antigravity', model, inputTokens, outputTokens: responseTokens, - cacheCreationInputTokens: 0, - cacheReadInputTokens: 0, + cacheCreationInputTokens: cacheWriteTokens, + cacheReadInputTokens: cacheReadTokens, cachedInputTokens: 0, reasoningTokens: thinkingTokens, webSearchRequests: 0, @@ -1408,9 +1467,16 @@ async function parseStatusLineCalls(source: SessionSource, seenKeys: Set export function shouldReparseAntigravitySource(path: string, cachedTurnCount: number): boolean { if (cachedTurnCount === 0) return true + if (cacheStates.get(currentCacheDir())?.cache.cascades[antigravityCascadeIdFromPath(path)]?.mtimeMs === -1) return true return isAntigravityStatusLineEventsPath(path) } +// Loads the results cache before the session cache decides which sources to +// reparse, so a cascade served from the previous cache version is retried. +export async function preloadAntigravityCache(cacheDir: string): Promise { + await loadCache(resolve(cacheDir)) +} + async function findCascadeSource(cascadeId: string): Promise { const sources = await discoverAntigravitySessionSources() return sources.find(source => { @@ -1604,8 +1670,11 @@ function createParser(source: SessionSource, seenKeys: Set): SessionPars const server = await detectServer(antigravityAppDataDirFromSourcePath(source.path)) if (!server) { - if (cached) { - for (const call of cached.calls) { + const fallback = cached ?? (source.path.toLowerCase().endsWith('.pb') + ? await adoptPreviousVersionCascade(currentCacheDir(), state, cascadeId) + : undefined) + if (fallback) { + for (const call of fallback.calls) { applyAntigravityProject(call, source, projectPath) if (seenKeys.has(call.deduplicationKey)) continue seenKeys.add(call.deduplicationKey) diff --git a/src/session-cache.ts b/src/session-cache.ts index c61a6dfc..cf0c0e2c 100644 --- a/src/session-cache.ts +++ b/src/session-cache.ts @@ -587,7 +587,10 @@ export const PROVIDER_PARSE_VERSIONS: Record = { // token floor on every read, so they must re-parse once for the real dollars // to land. warp: 'worktree-project-grouping-v1-est-cost-billing-cost-v1', - antigravity: 'worktree-project-grouping-v7', + // cache-read-v1-est-cost: gen_metadata and RPC usage now carry cache-read + // tokens, fields 9/10 read as thinking/response (they were swapped), and + // placeholder-only models are priced and flagged costIsEstimated. + antigravity: 'worktree-project-grouping-v7-cache-read-v1-est-cost', // pr-attribution-v1: the parser now reads the `message`/`part` tables for // per-turn user prompt text and the GitHub PR URLs it references. Cached // ZCode sessions hold empty userMessage turns and no session prLinks, so diff --git a/tests/daily-cache-carry-forward.test.ts b/tests/daily-cache-carry-forward.test.ts index 45a124df..30ba5749 100644 --- a/tests/daily-cache-carry-forward.test.ts +++ b/tests/daily-cache-carry-forward.test.ts @@ -812,9 +812,9 @@ describe('#946: a migration re-derives copilot instead of carrying it', () => { ) const loaded = await loadDailyCache() - // From v32, Copilot (v56), Codex, Hermes, Devin and Cursor Agent (v58) are owed + // From v32, Copilot (v56), Codex, Hermes, Devin, Cursor Agent (v58) and Antigravity (v59) are owed // re-derivation; dsh's v32 contract is already satisfied. - expect(loaded.pendingRederive).toEqual(['copilot', 'codex', 'hermes', 'devin', 'cursor-agent']) + expect(loaded.pendingRederive).toEqual(['copilot', 'codex', 'hermes', 'devin', 'cursor-agent', 'antigravity']) }) it('preserves an older cache pending repair while adding a newer provider repair', async () => { @@ -834,7 +834,7 @@ describe('#946: a migration re-derives copilot instead of carrying it', () => { ) const loaded = await loadDailyCache() - expect(loaded.pendingRederive).toEqual(['copilot', 'codex', 'hermes', 'devin', 'cursor-agent']) + expect(loaded.pendingRederive).toEqual(['copilot', 'codex', 'hermes', 'devin', 'cursor-agent', 'antigravity']) }) it('still carries the slice whole when the sources are gone (never-lose, #1033)', async () => { @@ -868,7 +868,7 @@ describe('#946: a migration re-derives copilot instead of carrying it', () => { it('a PARTIAL parse does not spend the entitlement', async () => { await seedOlderCache([day(settled, { copilot: PRE_STORE })]) const partial = await ensureCacheHydrated(noSessions, () => [], 'cfg-A', () => false) - expect(partial.pendingRederive).toEqual(['copilot', 'codex', 'hermes', 'dsh', 'devin', 'cursor-agent']) + expect(partial.pendingRederive).toEqual(['copilot', 'codex', 'hermes', 'dsh', 'devin', 'cursor-agent', 'antigravity']) // The next COMPLETE run still gets to re-derive. const out = await ensureCacheHydrated(noSessions, () => [day(settled, { copilot: STORE_BACKED })], 'cfg-A') expect(out.days.find(d => d.date === settled)!.providers['copilot']) diff --git a/tests/fixtures/antigravity-standalone/gen-metadata.json b/tests/fixtures/antigravity-standalone/gen-metadata.json new file mode 100644 index 00000000..f6163664 --- /dev/null +++ b/tests/fixtures/antigravity-standalone/gen-metadata.json @@ -0,0 +1,50 @@ +{ + "conversationId": "fixture-standalone-app", + "layout": "~/.gemini/antigravity/conversations/.db written by the standalone Antigravity app 2.19.1 (language_server --standalone --subclient_type hub). Real gen_metadata from a 2-prompt \"Gemini 3.1 Pro (High)\" session, token counts kept, ids and strings redacted, opaque root fields 3 and 8 dropped.", + "rows": [ + { + "idx": 0, + "hex": "120201022214666978747572652d67656e65726174696f6e2d300a810318f807225508f80710cc6918b30230183a11666978747572652d6d6573736167652d30421c0a10782d666978747572652d6865616465721208726564616374656448ee0150455a12666978747572652d726573706f6e73652d304a1510ffffffffffffffffff015208088597012080e8075a08080710ece0e7fc0262070801108fb0ea498a01009a011267656d696e692d70726f2d64656661756c74a201140a0f6c6173745f737465705f696e646578120130a201230a0a6d6f64656c5f656e756d12154d4f44454c5f504c414345484f4c4445525f4d3136a201260a0d7472616a6563746f72795f69641215666978747572652d7472616a6563746f72795f6964a201200a0a726571756573745f69641212666978747572652d726571756573745f6964a201140a0b757365645f636c61756465120566616c7365a201210a18757365645f636c617564655f636f6e736572766174697665120566616c7365a2011e0a15757365645f6e6f6e5f67656d696e695f6d6f64656c120566616c7365" + }, + { + "idx": 1, + "hex": "120203042214666978747572652d67656e65726174696f6e2d310a810318f807225708f80710f82e18a201289e3f30183a11666978747572652d6d6573736167652d31421c0a10782d666978747572652d68656164657212087265646163746564486b50375a12666978747572652d726573706f6e73652d314a1510ffffffffffffffffff01520808f19b012080e8075a08080510afbafaac03620510ceccd6558a01009a011267656d696e692d70726f2d64656661756c74a201210a18757365645f636c617564655f636f6e736572766174697665120566616c7365a2011e0a15757365645f6e6f6e5f67656d696e695f6d6f64656c120566616c7365a201140a0f6c6173745f737465705f696e646578120132a201230a0a6d6f64656c5f656e756d12154d4f44454c5f504c414345484f4c4445525f4d3136a201260a0d7472616a6563746f72795f69641215666978747572652d7472616a6563746f72795f6964a201200a0a726571756573745f69641212666978747572652d726571756573745f6964a201140a0b757365645f636c61756465120566616c7365" + }, + { + "idx": 2, + "hex": "120205062214666978747572652d67656e65726174696f6e2d320a820318f807225908f80710c21218970228ea5e30183a11666978747572652d6d6573736167652d32421c0a10782d666978747572652d686561646572120872656461637465644893015084015a12666978747572652d726573706f6e73652d324a1510ffffffffffffffffff01520808ef9e012080e8075a07080510cd91ac54620510899ccd0b8a01009a011267656d696e692d70726f2d64656661756c74a201260a0d7472616a6563746f72795f69641215666978747572652d7472616a6563746f72795f6964a201200a0a726571756573745f69641212666978747572652d726571756573745f6964a201140a0b757365645f636c61756465120566616c7365a201210a18757365645f636c617564655f636f6e736572766174697665120566616c7365a2011e0a15757365645f6e6f6e5f67656d696e695f6d6f64656c120566616c7365a201140a0f6c6173745f737465705f696e646578120134a201230a0a6d6f64656c5f656e756d12154d4f44454c5f504c414345484f4c4445525f4d3136" + }, + { + "idx": 3, + "hex": "120207082214666978747572652d67656e65726174696f6e2d330a810318f807225708f80710d516189c0128e75e30183a11666978747572652d6d6573736167652d33421c0a10782d666978747572652d68656164657212087265646163746564485750455a12666978747572652d726573706f6e73652d334a1510ffffffffffffffffff01520808f3a2012080e8075a08080410a3cfe7a701620510849b94378a01009a011267656d696e692d70726f2d64656661756c74a2011e0a15757365645f6e6f6e5f67656d696e695f6d6f64656c120566616c7365a201140a0f6c6173745f737465705f696e646578120136a201230a0a6d6f64656c5f656e756d12154d4f44454c5f504c414345484f4c4445525f4d3136a201260a0d7472616a6563746f72795f69641215666978747572652d7472616a6563746f72795f6964a201200a0a726571756573745f69641212666978747572652d726571756573745f6964a201140a0b757365645f636c61756465120566616c7365a201210a18757365645f636c617564655f636f6e736572766174697665120566616c7365" + }, + { + "idx": 4, + "hex": "1201092214666978747572652d67656e65726174696f6e2d340a820318f807225708f80710e21818810128e25e30183a11666978747572652d6d6573736167652d34421c0a10782d666978747572652d686561646572120872656461637465644816506b5a12666978747572652d726573706f6e73652d344a1510ffffffffffffffffff01520808dfa4012080e8075a0808081088848b8801620610aaeb8dce018a01009a011267656d696e692d70726f2d64656661756c74a201260a0d7472616a6563746f72795f69641215666978747572652d7472616a6563746f72795f6964a201200a0a726571756573745f69641212666978747572652d726571756573745f6964a201140a0b757365645f636c61756465120566616c7365a201210a18757365645f636c617564655f636f6e736572766174697665120566616c7365a2011e0a15757365645f6e6f6e5f67656d696e695f6d6f64656c120566616c7365a201140a0f6c6173745f737465705f696e646578120138a201230a0a6d6f64656c5f656e756d12154d4f44454c5f504c414345484f4c4445525f4d3136" + }, + { + "idx": 5, + "hex": "12020b0c2214666978747572652d67656e65726174696f6e2d350ab40318f807225808f80710c91a18d60228db5e30183a11666978747572652d6d6573736167652d35421c0a10782d666978747572652d68656164657212087265646163746564489b02503b5a12666978747572652d726573706f6e73652d354a1510ffffffffffffffffff01520808b2a6012080e8075a0808051091d49adb01620510deb9fd378a01009a011267656d696e692d70726f2d64656661756c74a201230a0a6d6f64656c5f656e756d12154d4f44454c5f504c414345484f4c4445525f4d3136a2012e0a116c6173745f657865637574696f6e5f69641219666978747572652d6c6173745f657865637574696f6e5f6964a201260a0d7472616a6563746f72795f69641215666978747572652d7472616a6563746f72795f6964a201200a0a726571756573745f69641212666978747572652d726571756573745f6964a201140a0b757365645f636c61756465120566616c7365a201210a18757365645f636c617564655f636f6e736572766174697665120566616c7365a2011e0a15757365645f6e6f6e5f67656d696e695f6d6f64656c120566616c7365a201150a0f6c6173745f737465705f696e64657812023130" + }, + { + "idx": 6, + "hex": "12020d0e2214666978747572652d67656e65726174696f6e2d360ab40318f807225908f80710ee1f18a70228da5e30183a11666978747572652d6d6573736167652d36421c0a10782d666978747572652d6865616465721208726564616374656448840150a3015a12666978747572652d726573706f6e73652d364a1510ffffffffffffffffff01520808adab012080e8075a0708041085b0cd0c620510c6def8018a01009a011267656d696e692d70726f2d64656661756c74a201140a0b757365645f636c61756465120566616c7365a201210a18757365645f636c617564655f636f6e736572766174697665120566616c7365a2011e0a15757365645f6e6f6e5f67656d696e695f6d6f64656c120566616c7365a201150a0f6c6173745f737465705f696e64657812023132a201230a0a6d6f64656c5f656e756d12154d4f44454c5f504c414345484f4c4445525f4d3136a2012e0a116c6173745f657865637574696f6e5f69641219666978747572652d6c6173745f657865637574696f6e5f6964a201260a0d7472616a6563746f72795f69641215666978747572652d7472616a6563746f72795f6964a201200a0a726571756573745f69641212666978747572652d726571756573745f6964" + }, + { + "idx": 7, + "hex": "12020f102214666978747572652d67656e65726174696f6e2d370ab30318f807225708f80710962318b90128d75e30183a11666978747572652d6d6573736167652d37421c0a10782d666978747572652d68656164657212087265646163746564484250775a12666978747572652d726573706f6e73652d374a1510ffffffffffffffffff01520808b7ae012080e8075a08080510ac8ee4af02620510ceaf93378a01009a011267656d696e692d70726f2d64656661756c74a201210a18757365645f636c617564655f636f6e736572766174697665120566616c7365a2011e0a15757365645f6e6f6e5f67656d696e695f6d6f64656c120566616c7365a201150a0f6c6173745f737465705f696e64657812023134a201230a0a6d6f64656c5f656e756d12154d4f44454c5f504c414345484f4c4445525f4d3136a2012e0a116c6173745f657865637574696f6e5f69641219666978747572652d6c6173745f657865637574696f6e5f6964a201260a0d7472616a6563746f72795f69641215666978747572652d7472616a6563746f72795f6964a201200a0a726571756573745f69641212666978747572652d726571756573745f6964a201140a0b757365645f636c61756465120566616c7365" + }, + { + "idx": 8, + "hex": "120211122214666978747572652d67656e65726174696f6e2d380ab30318f807225808f80710c82618e70128d45e30183a11666978747572652d6d6573736167652d38421c0a10782d666978747572652d68656164657212087265646163746564480a50dd015a12666978747572652d726573706f6e73652d384a1510ffffffffffffffffff01520808e6b1012080e8075a070806108186b62b62051094f7fa5c8a01009a011267656d696e692d70726f2d64656661756c74a201150a0f6c6173745f737465705f696e64657812023136a201230a0a6d6f64656c5f656e756d12154d4f44454c5f504c414345484f4c4445525f4d3136a2012e0a116c6173745f657865637574696f6e5f69641219666978747572652d6c6173745f657865637574696f6e5f6964a201260a0d7472616a6563746f72795f69641215666978747572652d7472616a6563746f72795f6964a201200a0a726571756573745f69641212666978747572652d726571756573745f6964a201140a0b757365645f636c61756465120566616c7365a201210a18757365645f636c617564655f636f6e736572766174697665120566616c7365a2011e0a15757365645f6e6f6e5f67656d696e695f6d6f64656c120566616c7365" + }, + { + "idx": 9, + "hex": "120213142214666978747572652d67656e65726174696f6e2d390ab20318f807225608f80710ed2a184928d35e30183a11666978747572652d6d6573736167652d39421c0a10782d666978747572652d68656164657212087265646163746564480450455a12666978747572652d726573706f6e73652d394a1510ffffffffffffffffff01520808f0b5012080e8075a08080310a0e0bedb016205109bb2f50a8a01009a011267656d696e692d70726f2d64656661756c74a201140a0b757365645f636c61756465120566616c7365a201210a18757365645f636c617564655f636f6e736572766174697665120566616c7365a2011e0a15757365645f6e6f6e5f67656d696e695f6d6f64656c120566616c7365a201150a0f6c6173745f737465705f696e64657812023138a201230a0a6d6f64656c5f656e756d12154d4f44454c5f504c414345484f4c4445525f4d3136a2012e0a116c6173745f657865637574696f6e5f69641219666978747572652d6c6173745f657865637574696f6e5f6964a201260a0d7472616a6563746f72795f69641215666978747572652d7472616a6563746f72795f6964a201200a0a726571756573745f69641212666978747572652d726571756573745f6964" + }, + { + "idx": 10, + "hex": "1201152215666978747572652d67656e65726174696f6e2d31300ab50318f807225808f80710a72c186928ce5e30183a12666978747572652d6d6573736167652d3130421c0a10782d666978747572652d68656164657212087265646163746564480a505f5a13666978747572652d726573706f6e73652d31304a1510ffffffffffffffffff015208088ab7012080e8075a080803108d81d3e701620610d5fddda5028a01009a011267656d696e692d70726f2d64656661756c74a201260a0d7472616a6563746f72795f69641215666978747572652d7472616a6563746f72795f6964a201200a0a726571756573745f69641212666978747572652d726571756573745f6964a201140a0b757365645f636c61756465120566616c7365a201210a18757365645f636c617564655f636f6e736572766174697665120566616c7365a2011e0a15757365645f6e6f6e5f67656d696e695f6d6f64656c120566616c7365a201150a0f6c6173745f737465705f696e64657812023230a201230a0a6d6f64656c5f656e756d12154d4f44454c5f504c414345484f4c4445525f4d3136a2012e0a116c6173745f657865637574696f6e5f69641219666978747572652d6c6173745f657865637574696f6e5f6964" + } + ] +} diff --git a/tests/providers/antigravity.test.ts b/tests/providers/antigravity.test.ts index 88e72ee6..32cee5b0 100644 --- a/tests/providers/antigravity.test.ts +++ b/tests/providers/antigravity.test.ts @@ -19,6 +19,8 @@ import { recordAntigravityStatusLinePayload, shouldReparseAntigravitySource, normalizeAntigravityToolCall, + antigravityCacheFileName, + flushAntigravityCache, } from '../../src/providers/antigravity.js' import type { ParsedProviderCall } from '../../src/providers/types.js' import { classifyTurn } from '../../src/classifier.js' @@ -596,8 +598,8 @@ describe('antigravity provider helpers', () => { provider: 'antigravity', model: 'gemini-3.1-pro-high', inputTokens: 30265, - outputTokens: 659, - reasoningTokens: 71, + outputTokens: 71, + reasoningTokens: 659, sessionId: fixture.conversationId, project: 'antigravity-cli', }) @@ -646,6 +648,116 @@ describe('antigravity provider helpers', () => { } }) + it('reads cache reads, thinking split and the placeholder model from standalone app gen_metadata', async () => { + if (!isSqliteAvailable()) return + + await withTempAntigravityHome('codeburn-antigravity-standalone-', async (tempHome) => { + const fixture = JSON.parse(await readFile( + new URL('../fixtures/antigravity-standalone/gen-metadata.json', import.meta.url), + 'utf-8', + )) as CurrentCliFixture + const conversationsDir = join(tempHome, '.gemini', 'antigravity', 'conversations') + await mkdir(conversationsDir, { recursive: true }) + const dbPath = join(conversationsDir, `${fixture.conversationId}.db`) + createCurrentAntigravityCliDb(dbPath, fixture) + + const calls = await collectAntigravityCalls({ path: dbPath, project: 'antigravity', provider: 'antigravity' }) + const sum = (pick: (call: ParsedProviderCall) => number) => calls.reduce((total, call) => total + pick(call), 0) + + expect(calls).toHaveLength(11) + expect(new Set(calls.map(call => call.model))).toEqual(new Set(['gemini-3.1-pro-high'])) + expect(calls.every(call => call.costIsEstimated === true)).toBe(true) + expect(sum(call => call.inputTokens)).toBe(56038) + expect(sum(call => call.cacheReadInputTokens)).toBe(117202) + expect(sum(call => call.reasoningTokens)).toBe(1106) + expect(sum(call => call.outputTokens)).toBe(1158) + expect(calls[0]!.cacheReadInputTokens).toBe(0) + // gemini-3.1-pro-preview: $2/M input, $12/M output (thinking included), $0.20/M cache read. + expect(sum(call => call.costUSD)).toBeCloseTo(56038 * 2e-6 + 2264 * 12e-6 + 117202 * 0.2e-6, 9) + }) + }) + + it('dates standalone rows without created_at from their first step', async () => { + if (!isSqliteAvailable()) return + + await withTempAntigravityHome('codeburn-antigravity-step-time-', async (tempHome) => { + const fixture = JSON.parse(await readFile( + new URL('../fixtures/antigravity-standalone/gen-metadata.json', import.meta.url), + 'utf-8', + )) as CurrentCliFixture + const conversationsDir = join(tempHome, '.gemini', 'antigravity', 'conversations') + await mkdir(conversationsDir, { recursive: true }) + const dbPath = join(conversationsDir, `${fixture.conversationId}.db`) + createCurrentAntigravityCliDb(dbPath, { ...fixture, rows: fixture.rows.slice(0, 1) }) + const { DatabaseSync: Database } = requireForTest('node:sqlite') + const db = new Database(dbPath) as TestDb + db.exec('CREATE TABLE steps (idx integer, metadata blob, PRIMARY KEY (idx))') + // Row 0 references steps 1 and 2; step 1 metadata #1 = Timestamp{1791307489s, 891504000ns}. + db.prepare('INSERT INTO steps (idx, metadata) VALUES (?, ?)').run(1, Buffer.from('0a0c08e1dd94d60610808b8da903', 'hex')) + db.close() + + const calls = await collectAntigravityCalls({ path: dbPath, project: 'antigravity', provider: 'antigravity' }) + expect(calls).toHaveLength(1) + expect(calls[0]!.timestamp).toBe(new Date(1791307489891).toISOString()) + }) + }) + + it('prices Gemini 3.1 Pro prompts from 200k tokens (input + cache read) at the long-context tier', async () => { + if (!isSqliteAvailable()) return + + await withTempAntigravityHome('codeburn-antigravity-tier-', async (tempHome) => { + const conversationsDir = join(tempHome, '.gemini', 'antigravity', 'conversations') + await mkdir(conversationsDir, { recursive: true }) + const dbPath = join(conversationsDir, 'fixture-tier.db') + createCurrentAntigravityCliDb(dbPath, { + conversationId: 'fixture-tier', + rows: [ + // input 150,000 + cache read 60,000, output 1,000 (400 thinking + 600 response) + { idx: 0, hex: '0a6c18f807222c08f80710f0930918e80728e0d403301848900350d8045a14666978747572652d6c6f6e672d636f6e746578749a011267656d696e692d70726f2d64656661756c74a201230a0a6d6f64656c5f656e756d12154d4f44454c5f504c414345484f4c4445525f4d3136' }, + // input 139,999 + cache read 60,000: one token under the threshold + { idx: 1, hex: '0a6a18f807222a08f80710dfc50818e80728e0d403301848900350d8045a12666978747572652d62656c6f772d746965729a011267656d696e692d70726f2d64656661756c74a201230a0a6d6f64656c5f656e756d12154d4f44454c5f504c414345484f4c4445525f4d3136' }, + ], + }) + + const calls = await collectAntigravityCalls({ path: dbPath, project: 'antigravity', provider: 'antigravity' }) + expect(calls).toHaveLength(2) + expect(calls[0]!.costUSD).toBeCloseTo(150000 * 4e-6 + 1000 * 18e-6 + 60000 * 0.4e-6, 9) + expect(calls[1]!.costUSD).toBeCloseTo(139999 * 2e-6 + 1000 * 12e-6 + 60000 * 0.2e-6, 9) + }) + }) + + it('serves .pb cascades from the previous results cache while the server is down', async () => { + await withTempAntigravityHome('codeburn-antigravity-prev-cache-', async (tempHome) => { + const cacheDir = join(tempHome, 'cache') + // antigravity-cli: no CLI language server runs during tests, even where the app does. + const conversationsDir = join(tempHome, '.gemini', 'antigravity-cli', 'conversations') + await mkdir(conversationsDir, { recursive: true }) + await mkdir(cacheDir, { recursive: true }) + const pbPath = join(conversationsDir, 'fixture-pb.pb') + await writeFile(pbPath, 'opaque') + const previousCall = { + provider: 'antigravity', model: 'gemini-3.1-pro-high', inputTokens: 100, outputTokens: 10, + cacheCreationInputTokens: 0, cacheReadInputTokens: 0, cachedInputTokens: 0, reasoningTokens: 5, + webSearchRequests: 0, costUSD: 0.00038, tools: [], bashCommands: [], timestamp: '2026-05-22T08:19:07.000Z', + speed: 'standard', deduplicationKey: 'antigravity:fixture-pb:r1', userMessage: '', sessionId: 'fixture-pb', + } + const previousVersion = Number(antigravityCacheFileName().match(/\.v(\d+)\.json$/)![1]) - 1 + await writeFile(join(cacheDir, antigravityCacheFileName(previousVersion)), JSON.stringify({ + version: previousVersion, + cascades: { 'fixture-pb': { mtimeMs: 1, sizeBytes: 6, calls: [previousCall] } }, + })) + + const calls = await collectAntigravityCalls({ path: pbPath, project: 'antigravity-cli', provider: 'antigravity' }) + expect(calls.map(call => call.deduplicationKey)).toEqual(['antigravity:fixture-pb:r1']) + + await flushAntigravityCache(undefined, cacheDir) + const current = JSON.parse(await readFile(join(cacheDir, antigravityCacheFileName()), 'utf-8')) + expect(current.cascades['fixture-pb'].mtimeMs).toBe(-1) + expect(current.cascades['fixture-pb'].calls).toHaveLength(1) + expect(shouldReparseAntigravitySource(pbPath, 1)).toBe(true) + }) + }) + async function withTempAntigravityHome(prefix: string, fn: (tempHome: string) => Promise): Promise { const tempHome = await mkdtemp(join(tmpdir(), prefix)) const previousCacheDir = process.env['CODEBURN_CACHE_DIR']