Skip to content

feat(stats): ingest Antigravity CLI (agy) usage into omp stats - #21240

Open
jerryfane wants to merge 1 commit into
can1357:mainfrom
jerryfane:upstream/agy-stats-ingestion
Open

jerryfane wants to merge 1 commit into
can1357:mainfrom
jerryfane:upstream/agy-stats-ingestion

Conversation

@jerryfane

@jerryfane jerryfane commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

What

Adds standalone incremental ingestion of local Google Antigravity CLI (agy) session transcripts into packages/stats (omp stats):

  • Canonical agy transcript parser (packages/stats/src/agy-parser.ts): Incrementally parses <agy-data>/brain/<conversation-id>/.system_generated/logs/transcript.jsonl (PLANNER_RESPONSE token/usage records), resolves workspace/title metadata from conversation_summaries.db with lock-coalescing backoff and change-counter fingerprinting, and keeps test/named/isolated profiles hermetic using @oh-my-pi/pi-utils ($env, isBunTestRuntime, getActiveProfile, getConfigDirName, CONFIG_DIR_NAME).
  • Live brain watcher (packages/stats/src/live.ts, parser.ts, aggregator.ts): Watches the agy brain directory alongside OMP sessions in StatsLive and re-syncs transcripts when summary metadata changes.

Why

Following Google DeepMind's Antigravity Terms of Service update permitting calling the official agy harness from other harnesses (https://x.com/_mohansolo/status/2127598572006744189), users running agy locally can view their agy token and request usage inside omp stats.

Per review feedback, this PR is now strictly standalone: the initDb lock-retry fix was split into its own PR, agy_session mirror-dedup logic was removed (to follow #21239), and hard-coded TS pricing fallbacks/backfills were removed pending maintainer preference on KDL pricing-status "included" vs pricing-peer.

Testing

  • bun --cwd=packages/stats run check (oxlint + oxfmt --check + check:types): 0 errors, 0 warnings.
  • bun test --timeout 20000 packages/stats/test/: 350 pass, 1 skip, 0 fail (4,060 expect() calls across 44 files), including 300-case deterministic seeded fuzz testing on agy-parser.ts and real non-test subprocess profile-isolation probes.
  • test-check prove --pieces: integration seams in aggregator.ts, live.ts, and parser.ts verified guarded.

  • bun --cwd=packages/stats run check passes
  • Tested locally
  • CHANGELOG updated with the required attribution (#21240 by @jerryfane)

@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-12-01T05:57:03.581645Z
We couldn’t complete this review. Comment @codex review to try again.
0abad9a PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@roboomp roboomp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @jerryfane for the thorough work and tests. Rank P3: a large, default-on feature (omp stats reads ~/.gemini/antigravity-cli for every user) with no linked issue or confirmed maintainer intent.
Blocking: agy-cli peer pricing and the effort-suffix regex are hard-coded in db.ts instead of KDL (pricing-peer/taxonomy), and the mirror-dedup half of the PR targets agy-cli/agy_session records that exist only in the unmerged #21239, so on main it is dead code.
Should-fix: steady-state sync re-reads full canonical transcripts on the unchanged-file fast path; getAgyMirrorFilesForConversations does a LIKE scan over parser_state JSON; hand-rolled ~/.omp/agent profile guard; as-never casts; inline await import() in tests; no packages/stats/CHANGELOG.md entry.
The initDb change (singleton published only after a successful migration, with a regression test) is a real fix and could land on its own.
Maintainer question: should standalone agy usage show API-equivalent dollars when the in-repo antigravity-cli provider marks the same models pricing-status "included"?

Comment thread packages/stats/src/db.ts Outdated
Comment on lines 661 to 678
const AGY_EFFORT_SUFFIX_RE = /-(?:low|medium|high|xhigh)$/;

function agyPricingFallbacks(modelId: string): readonly (readonly [string, string])[] {
const stripped = modelId.replace(AGY_EFFORT_SUFFIX_RE, "");
const candidates = stripped !== modelId ? [modelId, stripped] : [modelId];
const fallbacks: Array<readonly [string, string]> = [];
for (const id of candidates) {
fallbacks.push(
["google", id],
["anthropic", id],
["openrouter", `google/${id}`],
["openrouter", `anthropic/${id}`],
["openrouter", `openai/${id}`],
["openrouter", id],
);
}
return fallbacks;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blocking (convention): agyPricingFallbacks() (and the provider === AGY_CLI_PROVIDER branch in getCatalogCost() at L703) hard-codes provider-conditional pricing policy and a model-id regex (AGY_EFFORT_SUFFIX_RE) in TS. AGENTS.md: model/provider policy lives in KDL. Peer pricing belongs in a pricing-peer provider="agy-cli" peers=... rule in packages/catalog/src/compat/rules/runtime/behavior.kdl (compiled via bun run gen:compat); effort-suffix collapse belongs in taxonomy/. The six-way google/anthropic/openrouter guess list also means an unrelated id that happens to exist on OpenRouter gets priced silently.

Comment thread packages/stats/src/db.ts Outdated
Comment on lines +803 to +808
// An unknown `agy-cli` model with no matching public peer rate card stays
// unpriced subscription usage rather than reporting as free ($0).
if (stats.provider === AGY_CLI_PROVIDER) {
return { cost: storedCost ?? ZERO_USAGE_COST, unpriced: true };
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should-fix / maintainer question: in-repo providers/antigravity-cli.kdl declares pricing-status "included" with a zero rate card for the same Gemini 4 models, because agy runs on plan quota. This PR prices identical usage at public API peer rates when it comes from standalone agy and special-cases unpriced by provider id here. Result: the same model shows as included via omps provider and as dollars via agy-cliin one dashboard. If the intent is "API-equivalent cost", that needs a maintainer call and should be expressed through the catalogpricing-status` axis, not a TS provider check.

Comment thread packages/stats/src/db.ts Outdated
SELECT id, provider, model, timestamp, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens
FROM messages
WHERE cost_total = 0 AND total_tokens > 0
WHERE total_tokens > 0 AND (cost_total = 0 OR (provider = ? AND cost_unpriced = 1))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: backfillMissingCatalogCosts now also selects agy-cli unpriced rows, and backfillAgyCliCatalogCosts (L885) selects the same rows again under a separate sentinel. One of the two is redundant; keep a single path. Separately, this backfill now writes cost_no_cache_input and cost_unpriced = 0 for every provider (via repriceCatalogCostRows), which changes behaviour for non-agy rows beyond the PR`s stated scope; please call that out or split it.

Comment thread packages/stats/src/db.ts Outdated
const wanted = new Set(conversationIds);
const rows = db
.query<{ session_file: string; parser_state: string | null }, []>(
`SELECT session_file, parser_state FROM file_offsets WHERE parser_state LIKE '%"agyMirror"%'`,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should-fix (perf): getAgyMirrorFilesForConversations() runs a LIKE %"agyMirror"% full scan over file_offsets.parser_state (which carries spotlight state and pendingReplies, so rows are large) and JSON.parses every hit, on every live-watcher flush that touches an agy transcript. Store the conversation ids in an indexed column/side table instead of scanning serialized cursor JSON.

Comment thread packages/stats/src/parser.ts Outdated
// data exists for the recorded `agy_session` conversation ID; suppress OMP
// child mirror rows only when that canonical data exists so usage is neither
// dropped nor double-counted.
if (msg.provider === AGY_CLI_PROVIDER && suppressAgyCli) return null;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blocking (scope): agy-cli provider rows and agy_session custom entries do not exist on main; the only in-tree agy integration is the antigravity-cli provider (packages/ai/src/providers/antigravity-cli.ts), which runs agy under an omp-private getAntigravityCliDir()/gemini/<account> dir and never writes agy_session. All mirror-dedup logic in parseSessionFile (~150 lines, plus AgyMirrorParserState, needsAgyMirrorReparse, getAgyMirrorFilesForConversations, and the aggregator expansion) is dead code until #21239 lands, contradicting the "intentionally standalone" claim. Suggest moving it into #21239 so each PR carries only code it exercises.

Comment thread packages/stats/src/aggregator.ts Outdated
Comment on lines +425 to +426
!(await needsAgySummaryReparse(sessionFile, stored.parserState)) &&
!(await needsAgyMirrorReparse(stored.parserState))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should-fix (perf): this runs on the unchanged-file fast path for every tracked file on every sync. needsAgyMirrorReparse() calls hasUsableCanonicalAgyTranscript(), which fs.readFiles and JSON-parses the whole canonical transcript for each recorded conversation id. A mirror that is re-parsed then reads the same transcripts twice more (parser.ts:1041 and the Promise.all at ~L1071). Agy transcripts grow unbounded, so steady-state sync cost now scales with total agy history instead of with what changed. Use the canonical files stored file_offsets` cursor (or an mtime/size fingerprint) instead of re-reading it.

Comment thread packages/stats/src/agy-parser.ts Outdated
}
const agyEnv = process.env.AGY_APP_DATA_DIR?.trim();
if (agyEnv) return path.resolve(agyEnv);
const defaultAgentDir = path.resolve(os.homedir(), ".omp", "agent");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should-fix: the isolated-profile guard rebuilds ~/.omp/agent by hand instead of using pi-utils dir/profile resolution (getActiveProfile(), DirResolverinpackages/utils/src/dirs.ts). Anyone with PI_CODING_AGENT_DIRpointed at a non-default path, or using a named profile, silently gets agy ingestion disabled, and the check breaks ifCONFIG_DIR_NAMEchanges. Also, this module readsprocess.envdirectly where the package uses$env/$envpos`.

Comment thread packages/stats/src/agy-parser.ts Outdated
Comment on lines +836 to +838
content: content as never,
api: AGY_CLI_API as never,
provider: AGY_CLI_PROVIDER as never,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should-fix (convention): as never casts on content, api, and provider bypass the SessionMessageEntry type. "agy-cli" is not a registered Api/provider, so the synthetic entry violates the type it claims. Either type the payload honestly (content as the real block union) or widen the consumer type; repo rules ban as type hacks.

Comment thread packages/stats/test/agy-stats.test.ts Outdated
delete process.env[STATS_AGY_DATA_DIR_ENV];
delete process.env.AGY_APP_DATA_DIR;
try {
const { getAgyAppDataDir } = await import("@oh-my-pi/omp-stats/agy-parser");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should-fix (convention): five inline await import(...) calls in this file (L450, 550, 551, 775, 905). AGENTS.md bans inline imports; hoist them to top-level imports.

@jerryfane

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review — every point here makes sense.

Plan to clean this up:

  1. Split out initDb: I'll move the initDb singleton-publication/lock-retry fix and db-open-lock.test.ts into its own small standalone PR so it can land independently.
  2. Remove dead mirror-dedup code from this PR: I'll drop the agy_session mirror-dedup path (AgyMirrorParserState, needsAgyMirrorReparse, getAgyMirrorFilesForConversations, and the aggregator mirror expansion) from feat(stats): ingest Antigravity CLI (agy) usage into omp stats #21240 so it contains only standalone agy transcript ingestion. When that logic lands alongside/after feat(coding-agent,utils): delegate subagents to the official Antigravity CLI (agy) #21239, I'll replace the LIKE scan over parser_state with an indexed lookup and check canonical freshness via stored file_offsets/mtime instead of re-reading full transcripts.
  3. Drop TS pricing fallbacks & fix conventions: I'll remove agyPricingFallbacks(), AGY_EFFORT_SUFFIX_RE, and the redundant backfill/non-agy repriceCatalogCostRows changes; switch the profile check to pi-utils (getActiveProfile() / DirResolver / $env); remove the as never casts in agy-parser.ts; and hoist the inline await import(...) calls in agy-stats.test.ts (packages/stats/CHANGELOG.md was pushed in 1d502c6).

Before I push the revised branch, two quick maintainer calls:

  • Pricing: Matching in-repo providers/antigravity-cli.kdl (pricing-status "included" on plan quota) keeps one consistent dashboard model across both paths — does included match what you want here, or would you prefer KDL pricing-peer + taxonomy/ API-equivalent dollars?
  • Default-on vs opt-in: Should standalone ~/.gemini/antigravity-cli ingestion be opt-in (e.g. a setting/env flag) rather than enabled by default?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI commands and arguments feat provider:antigravity-cli providers LLM provider-specific issues review:p3 triaged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants