Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

feat(antigravity): record every prompt and sync conversations from the session store (#1256)

kyle-elliott-asymptote68c666b64d9e
diff --git a/CLAUDE.md b/CLAUDE.md
index c4728887..0b54fc99 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -59,16 +59,17 @@ Supported runtime surfaces today:
- DeepSeek Harness (`dsh`) is installed through two user-level files: `$DSH_HOME/beacon-endpoint-hooks.json` and a row in `$DSH_HOME/cordis.patch.yml`; there is no project scope. The `@deepseek-ai/dsh-hooks-claude-code` bridge that row mounts is not shipped with the CLI (dev dependency only) and must be installed per profile with `@deepseek-ai/dsh-hook-protocol` at exactly the dsh version; a mount dsh cannot load is skipped at boot with only a warning. So `InstallDsh` first runs `hooks.InspectDshBridge` (`internal/endpoint/hooks/dsh_bridge.go`, read-only: the installation found from the `dsh` launcher on PATH, each `$DSH_HOME/profiles/*` resolved Node-style, and rows in any patch layer that mount a bridge by absolute path at Beacon's hooks file) and returns `*DshBridgeUnavailableError` without writing anything when nothing loads a matching bridge; explicit `--harness dsh` fails, `--all` and endpoint install skip with a warning. A healthy by-path mount (how Nix installs it; it must also resolve its declared dsh peers from its own location, because dsh's host-package interception applies only to profile plugins, else `peers_missing`) counts as installed and Beacon writes no row of its own (removing one it wrote earlier) so hooks never run twice. Beacon never installs the packages. `DshStatus.Active`/`Bridge`, discovery (misconfigured when inactive), doctor `dsh_hook_bridge`, and inventory (each profile's patch layer) surface it; tests build on-disk fixtures with `internal/endpoint/hooks/dshtest`. It also installs a Beacon-owned local skill at `$DSH_HOME/skills/beacon-endpoint/SKILL.md` and supports native session backfill from `$DSH_HOME/sessions` through `beacon endpoint dsh sync`, which fills assistant text/reasoning, tool failures, and token usage that the hook bridge does not expose. It rides the Claude-shaped envelope on the hook path, but `run_code` remains `tool.invoked` because nested commands fire their own hooks.
- fx (vercel-labs/fx) telemetry read from the session store fx commits under `~/.fx/sessions/`, covering session start, prompts, tool calls, commands with exit codes and output, file reads/creates/edits with diffs, MCP tool calls, agent messages, history compaction, and per-turn token usage plus reported cost. fx exposes no third-party hook, plugin, or OTLP surface -- its lifecycle hooks are compiled into the binary -- so collection is a read of fx's own records, run by `beacon endpoint fx sync`. Every event carries `harness.collection_method=poll`; approvals are not synthesized (fx persists permission feedback text, not a per-call decision, matching the Cline and Pi posture) and no session-end event is invented, since fx sessions are resumable. Implementation lives in `cli/beacon/internal/fxsession` and `cli/beacon/cmd/endpoint_fx.go`.
- Harness² (google-research/harness2) rollouts, read from the executor event streams Harness² records under its runs directory (`$HARNESS2_RUNS_DIR`, `~/harness2/runs`, or a `--runs-dir` an earlier sync was given and the cursor file remembers): OpenCode `run --format json` and Codex `exec --json`, recognized by their first event rather than by file name. Harness² runs Codex under its own `CODEX_HOME` with `--ephemeral` and OpenCode from a source checkout, so Beacon's Codex/OpenCode integrations do not record these sessions. Events carry `harness.name=harness2`, `harness.collection_method=poll`, the executor's own session id, and the rollout's benchmark/task/label/run/trial/attempt/harness fingerprint under `raw.harness2`. Codex `turn.completed` usage is the thread's running total and is differenced per turn; Codex exec lines carry no times, so they take the file's mtime. No prompts (an argv argument, absent from both streams) and no approvals are recorded or synthesized. `testdata/recorded` holds streams recorded from the exact OpenCode and Codex releases Harness² pins; re-record them when it bumps either. Implementation lives in `cli/beacon/internal/harness2session` and `cli/beacon/cmd/endpoint_harness2.go`.
+- Antigravity CLI (`agy`) conversation backfill, read from the transcripts Antigravity commits under `~/.gemini/antigravity-cli/brain/<conversationId>/.system_generated/logs/` (`transcript_full.jsonl`; `transcript.jsonl`, whose tool arguments are JSON-encoded strings, only when the full one is absent) with the working directory, title, project and parent conversation from `conversation_summaries.db` beside the brain directory (read through `sessionsync.OpenSQLite`; a missing database or row means no working directory, not an error), by `beacon endpoint antigravity sync` (alias `antigravity-cli`, `--brain-dir`). Events carry `harness.name=antigravity_cli`, `harness.collection_method=poll` and the `conversationId` as the session id, the same id the live hooks write. Overlap with the hooks follows Devin CLI: `CollectOptions.LiveCoverage` is the earliest `antigravity_cli` hook event per conversation in the retained runtime log the sweep writes to (`integrations.HookCoverage` in `cli/beacon/internal/endpoint/integrations`, shared with Devin; computed by the sync command, `--print` included, and by the backfill runner, so install, connect and scheduled sweeps too), and `sessionsync.LiveCoverage.Suppresses`, also shared with Devin, drops for steps at or after it (two-second skew allowance) `session.started` and every tool/command/file/MCP event, while prompts are dropped only when the hooks recorded one with the same `content.hash` in that conversation (`LiveCoverage.RecordedPrompt`, from the hook prompts `HookCoverage` collects; a handoff link follows its prompt), because v1.3.60 hook blocks and a failed `PreInvocation` hook leave prompts unrecorded; Devin still drops prompts by time, keeping `agent.message`, `agent.reasoning` and `token.usage`, which the hook payloads never carry; suppressed events advance the cursor and are counted in `events_suppressed_live`. Antigravity's prompt unwrapping, tool classification and tool path arguments are `asymptoteobserve.AntigravityPrompt`, `AntigravityToolAction` and `AntigravityToolPath` (`pkg/asymptoteobserve/antigravity.go`), read by both this collector and the hook adapter so the two paths classify a call the same way. Prompts are the text inside `<USER_REQUEST>`; planner responses yield reasoning, agent messages, one `tool.invoked` per call and per-response token usage (cache reads taken out of input); the next `GENERIC` steps are those calls' results in order (Antigravity gives calls no id), with `run_command`'s exit code and output parsed from the result text. `SYSTEM_MESSAGE` steps are skipped and no session end or approval is synthesized. Implementation lives in `cli/beacon/internal/antigravitysession` and `cli/beacon/cmd/endpoint_antigravity.go`.
- Attribution of OTLP events: every account on a machine exports to the same loopback collector, and the exporter's base `user` is the collector process's own account (`asymptoteobserve.NewEvent` reads `$USER`/`$USERNAME`). On Linux, macOS and Windows the collector replaces it with the account that owns the sending socket (peer attribution): `collector.ConfigYAML` renders, only where `collector.PeerAttribution` (`runtime.GOOS` is `linux`, `darwin` or `windows`), the `beacon_otlp_http` receiver (`collector-builder/exporter/beaconjsonexporter/otlphttpreceiver`, the upstream OTLP/HTTP protocol rebuilt on confighttp so `client.Info.Addr` keeps the client port that upstream drops; it replaces `otlp.protocols.http` on the same port and carries the same `include_metadata` and `loopback_host` authenticator, so non-loopback Host headers are refused there too) and the `beacon_peer` processor (`peerprocessor`, right after `memory_limiter` and before `batch`, which loses the connection) on Beacon's own pipelines, never the OTLP forward's, plus `peer_user: true` on beaconjson. `beacon_peer` removes `beacon.peer.uid`/`beacon.peer.user` wherever a sender put them (resource, scope, record, span, span event and link, every datapoint type), then asks `internal/peercred` for the owner of the client socket of exactly this connection: the client address from `client.Info.Addr` and the collector's end from the gRPC peer's `LocalAddr` or net/http's `LocalAddrContextKey` (no server address, no lookup). On Linux `peercred` first asks the kernel with one `NETLINK_SOCK_DIAG` exact four-tuple lookup (`diag_linux.go`, constant cost per export) and scans `/proc/net/tcp{,6}` for the same four-tuple when sock_diag itself is unavailable or, until sock_diag has once answered with a socket, when it says ENOENT (the kernel says that for a missing `tcp_diag` handler too; a socket `/proc` finds then marks sock_diag blind for good); inode 0 (TIME_WAIT/orphan, uid printed 0), no match, or two owners are unknown, never guessed, and an unrelated TIME_WAIT on the same port is skipped. On macOS (`peercred_darwin.go`, parser `pcblist.go`, no cgo) it reads the whole `net.inet.tcp.pcblist_n` sysctl table netstat reads (one read per export, proportional to the machine's TCP sockets) and takes `so_uid` from the `xsocket_n` of the pcb whose `xinpcb_n` is exactly the client four-tuple (IPv4 in the last four address bytes, IPv6 and v4-mapped in all sixteen; offsets from xnu's `#pragma pack(4)` structs, records walked by length and kind and padded to 8, a table without its closing `xinpgen` refused); a pcb with no socket, `SS_NOFDREF` (closed by its owner), or `t_state` CLOSED/LISTEN/TIME_WAIT is passed over even though xnu keeps the creator's uid there. On Windows (`peercred_windows.go`, parser `tcptable.go`) `GetExtendedTcpTable` (`TCP_TABLE_OWNER_PID_ALL`, AF_INET and, for an IPv4 pair too, AF_INET6 for v4-mapped rows; ports in network byte order) gives the owning PID of exactly the four-tuple, skipping PID 0/4 and CLOSED/LISTEN/TIME_WAIT/DELETE_TCB rows and client ends already closed (FIN_WAIT1/2, CLOSING, LAST_ACK, which can keep an exited process's PID); the process is opened (`PROCESS_QUERY_LIMITED_INFORMATION`), the table is read again and must still name that PID (a PID is not reused while a handle is open), and the answer is its token's `TokenUser` SID. A user-mode Windows collector can open only its own account's processes, so other accounts' exports are unknown there. Byte-fixture tests for both parsers run on every OS; the live-socket tests (`peercred_live_test.go`) run only on macOS and Windows CI. The name comes from `internal/accountname` (shared with `beacon_ingest`). The converter reads the peer attributes from the resource only (`mergeSignalAttrs`), and `applyPeerUser` copies them into `user` only with `Options.PeerUser`, and with it every `claude_cowork` event, log, span or datapoint, has an empty `user` (`applyPeerUser`, which every signal passes through, and `normalizeClaudeCoworkContext` for logs; Cowork reaches a collector only through a relay such as `beacon endpoint cowork --ngrok`, so the kernel names the relay's account, and the cloud identity is the sender's own claim; both stay in raw attributes; without `PeerUser` the cloud identity still replaces the collector's account); the `falcon_hec` exporter gets `peer_user: true` too, so LogScale matches the log; with `PeerUser` an unidentified sender gets an empty `user`, never the collector's root, so a recorded root always means root sent it. On macOS and Windows the config renders peer attribution only for a collector that lists the no-op marker extension `beacon_peer_lookup` (`peerlookupextension`, in `builder.yaml`, named by no config) in `beacon-otelcol components` (`collector.PeerAttributionFor`, `peerLookupMarkerRequired`): older collectors already carry `beacon_peer` and `beacon_otlp_http` with a lookup that is unsupported there, and `peer_user` would leave their events with no `user`, so a new CLI with one (`--collector`, a CLI-only upgrade, a repair before the collector is replaced) or with a collector that cannot list its components keeps the previous config. `ConfigYAML` decides from the binary `cfg.Collector.BinaryPath` resolves to, the one install, repair and the CI session check (`ConfigYAMLWithPeer` takes the decision explicitly); Linux needs no marker and is unchanged. `CheckComponentsFor` refuses a collector without both where they are rendered, from the same listing. A platform without a lookup (anything but these three) keeps the collector's account, as did macOS and Windows collectors before this (root, or `COMPUTERNAME$` under LocalSystem). Hook and plugin events carry the person's uid or SID from `os/user.Current()` (verified by the OS in restricted mode). The person is also on the session's hook and plugin events, joined by `session.id`; the Sentinel guide carries the KQL. Peer attribution names the account that owns the sending socket, not necessarily the person who ran the agent (a relay, a shared service account, a process that inherited a socket), so never describe it as more than that.
- Claude Cowork admin-configured OpenTelemetry setup guidance and local validation.
- OpenClaw Gateway uses a Beacon-managed plugin directory plus OpenClaw's own diagnostics OTLP guidance (`beacon endpoint integrations openclaw`). The plugin's `before_tool_call` hook is fail-closed, so the handler dispatches synchronously and returns without awaiting. Conversation hooks, including `llm_output`, require `plugins.entries.beacon-endpoint.hooks.allowConversationAccess`; without it, token and agent-message coverage is partial. Beacon reads OpenClaw JSON/JSON5 config for advice but does not rewrite it.
- GitHub Copilot CLI uses MDM/customer-managed OTLP HTTP for live spans and approval-like activity, plus `beacon endpoint copilot sync` to backfill local session records from `~/.copilot/session-state`. Poll events carry assistant text, complete tool results, command/file details, and token usage with `harness.collection_method=poll`, plus the shutdown's session-wide `totalNanoAiu` differenced into `gen_ai.usage.cost_usd` once per shutdown (10^9 nano-AIU = one AI credit = US$0.01), only for sessions started on or after the 2026-06-01 AI-credit cutover (`cli/beacon/internal/copilotsession/cost.go`); approvals still come only from the live OTLP path and are not synthesized from persisted records.
-- Runtimes that ride shared hook/OTLP paths without a special contract worth expanding here include Antigravity CLI, Devin CLI, Devin Desktop, Factory Droid, Gemini CLI, Grok Build, Hermes Agent, Qwen Code, and VS Code. Installed hook/endpoint support is governed by `cli/beacon/cmd/endpoint_targets.go` plus the install/status switches in `cli/beacon/cmd/endpoint_hooks.go`; discovery rows live in `cli/beacon/internal/endpoint/harness`.
+- Runtimes that ride shared hook/OTLP paths without a special contract worth expanding here include Antigravity CLI (its session-store backfill is above), Devin CLI, Devin Desktop, Factory Droid, Gemini CLI, Grok Build, Hermes Agent, Qwen Code, and VS Code. Installed hook/endpoint support is governed by `cli/beacon/cmd/endpoint_targets.go` plus the install/status switches in `cli/beacon/cmd/endpoint_hooks.go`; discovery rows live in `cli/beacon/internal/endpoint/harness`.
- Browser chat telemetry through an optional MV3 extension (`browser-extension/`; Chrome, with a beta Firefox build) covering claude.ai and chatgpt.com. A main-world interceptor tees the streamed response, a per-site adapter parses it into a normalized turn, and the service worker POSTs OTLP GenAI logs to the local collector on `127.0.0.1:4318`; the extension never writes files and never contacts a remote endpoint. `harness.name` resolves to `claude_web` or `chatgpt_web` (already handled by `NormalizeHarnessName` in `pkg/asymptoteobserve/harness.go`, where the browser cases must stay above the generic `claude` rule) and `harness.collection_method` is `otlp`. The one build serves every Chromium browser; each event names the browser it came from in the typed `user_agent.name`/`user_agent.version` fields (OTel semconv, promoted by the exporter so Metadata-only forwarding keeps them), resolved in `browser-extension/src/shared/browser-identity.ts` from UA Client Hints brands, with a UA-string fallback that also names Firefox. Scope is deliberately narrow: only those origins' chat streams, never other tabs or general browsing. Retention defaults to `full`, so prompt and response text is retained by default; this is documented rather than defaulted down, because browser chat telemetry without content has no investigative value. Treat the adapters as experimental, since both sites' stream formats are private and undocumented. Per-browser differences live only in `browser-extension/tools/targets.mjs` (one entry per target, deriving its manifest from `src/manifest.json`; Chrome ships that file verbatim to `dist/`, Firefox gets `dist-firefox/`), and every extension API call goes through the `src/shared/browser.ts` shim (a unit test fails on direct `chrome.*` use). The Firefox Gecko ID `[email protected]` is pinned and must never change. Managed fleets install a signed, self-hosted Chrome build instead of the unpacked zip: Chrome policy (`ExtensionSettings` `force_installed`) installs the CRX from the `update_url` feed (`CHROME_UPDATE_URL` in `tools/targets.mjs`, also the manifest's `update_url`, dropped from the Firefox manifest), and the pinned `CHROME_EXTENSION_ID` there, derived from the CRX signing key, must never change either, because every fleet's policy names it. `tools/pack-crx.mjs` signs CRX3 files and writes the feed with `node:crypto` only, so the signing job runs it without `npm ci`. Admins lock settings through Chrome managed storage (`src/managed_schema.json`): `getSettingsState` in `src/background/settings.ts` lays those values over the stored ones on every read, each held to `parseSettingsPatch`, never writes them to `storage.local`, and reports them as `locked`, which the popup and options page show disabled and `SET_SETTINGS` refuses to change. A managed-storage read that fails (anything but a missing area or Firefox's no-manifest refusal) sets `managedError`: nothing is captured, changed or delivered until it reads. Delivery (`src/background/delivery.ts`) applies the locks in force at send time (`underPolicy`): a locked endpoint retargets queued batches, and a locked-off site or capture, or a locked retention stricter than the batch was built with, drops them. A copy installed by policy (`management.getSelf().installType === 'admin'`) holds delivery for `POLICY_GRACE_MS` after an install or update until Chrome delivers any managed value, because turns captured before then were shaped without the locks.
- `beaconjson` OpenTelemetry Collector exporter that converts OTLP logs, traces, metrics, and resource attributes into Beacon endpoint JSONL.
- OTLP forward (`beacon endpoint install|repair --otlp-forward-endpoint`, `--otlp-forward-protocol grpc|http/protobuf`, `--otlp-forward-harness`, repeatable `--otlp-forward-header`, `--no-otlp-forward`; `config.json` `destinations.otlp_forward`): for machines whose runtimes already exported OTLP to another backend before Beacon pointed them at its collector. The collector renders an `otlp/forward` or `otlphttp/forward` exporter (both in `collector-builder/builder.yaml`) on `logs/forward`, `traces/forward` and `metrics/forward` pipelines fed by the same receiver: `memory_limiter`, `beacon_forward_filter` (`forwardfilterprocessor`; keeps only resources whose harness, resolved like beaconjson resolves it, is listed, default Claude Code and Codex, so browser-extension chats and other runtimes never leave), `claude_api_body` on logs, `beacon_privacy`, `batch`. The exporter's queue and retries are bounded so a down backend sheds data instead of pushing `memory_limiter` into refusing Beacon's own pipelines. It is a customer-chosen destination like the HEC exporters, not a Beacon network channel, and carries no hook or session-store data. Install and repair carry it over (`buildConfig`) until `--no-otlp-forward` removes it. Header values never go in `config.json` (ordinary accounts read the system one to find the system log): they live in `OTLPForwardSecretsPath` (`otlp-forward-headers.json`, 0600) and the 0600 collector config, `config.json` keeps `header_names`, and status, doctor and `config show` show names only. Guide: `docs/guides/kandji-otlp-forward-mdm.mdx`.
- Managed Microsoft Sentinel forwarder (`beacon endpoint sentinel forwarder install|status|remove --system`, hidden `reconcile`; `cli/beacon/internal/endpoint/sentinel/forwarder.go`, `cli/beacon/cmd/endpoint_sentinel_forwarder.go`; docs in `docs/log-forwarding/microsoft-sentinel.mdx#vector-and-the-logs-ingestion-api` and `docs/cli/sentinel.mdx`): the bundled Vector (the MSI ships `vector.exe` beside `beacon.exe`, checked against the pinned `packaging/vector/` checksums by `packaging/windows/fetch-vector.ps1`) run as a system service (`BeaconSentinelForwarder`, `beacon-sentinel-forwarder.service`, `com.beacon.endpoint.sentinel-forwarder`) through `service.ForwarderManager` with a `ForwarderSpec`; the Asymptote forwarder's spec is the zero value, byte-identical units, and has no Windows service, so `connect` stays refused there. System mode only. Its state is `<SystemBaseDir>/forwarders/sentinel/` (`forwarder.json` non-secret settings, `secrets.json` read by Vector's `file` secret backend, optional `client.pfx`, `vector.toml` with literal values, `data/` checkpoints, `logs/vector-<date>.log` warnings), `sysacl.SecureSecretDir`/`WriteSecretFile` (root-only 0700/0600 on POSIX), apart from `config.json` so repair never touches it. The credential is never a flag value (env or stdin). Install validates a scratch copy with Vector before writing anything, so a rejected install leaves the old forwarder. The config (`pack/vector.toml.tmpl`, shared with the manual env-var pack via `manualVectorConfig`) reads `runtime.jsonl` and `.1` with the default checksum fingerprint, acknowledgements on, a custom `retry_strategy` (401/403/408/429/5xx, unlimited), 512 KB batches. Vector recognizes a file by its first line, so after the log is replaced with a copy (the log-access switch) it keeps reading the old file until restarted: `lifecycle.Install` therefore reconciles with `Restart` on every install, repair and package upgrade (the macOS postinstall runs the hidden `reconcile`), which is also how the MSI upgrade re-registers the service its uninstall step removed. `lifecycle.Uninstall` always removes the service (so `vector.exe` can be replaced) and keeps the state under `KeepConfig`; repair keeps it running (`KeepForwarders`). `AZURE_AUTHORITY_HOST` (`--authority-host`) goes into the service environment. `sentinelmock` (and `cmd/sentinel-mock`) stands in for Entra ID and the Logs Ingestion API; `TestForwarderConfigDeliversThroughRealVector` runs real Vector against it in `linux-test` and `windows-test` (`BEACON_TEST_VECTOR_BIN`, `BEACON_TEST_SENTINEL_TRUST_STORE=1` on Windows), and `packaging/windows/smoke-sentinel-forwarder.ps1` drives the installed MSI through setup, upgrade, log-access switches and uninstall in `windows-package-smoke`.
-- Scheduled session sync (`beacon endpoint install|repair --session-sync`, `--no-session-sync`; `config.json` `session_sync.enabled`, opt-in; docs in `docs/cli/endpoint-install.mdx#scheduled-session-sync`): a one-shot job, `com.beacon.endpoint.session-sync` / `beacon-session-sync.timer` (`service.SessionSyncManager`), every 15 minutes starting one interval after load (`jobSpec.runAtLoad` false, unlike inventory: a run fired at load would take the sweep lock ahead of the install backfill that follows it), running the hidden-flagged `beacon endpoint sessions sync --scheduled` (`cli/beacon/cmd/endpoint_session_sync.go`), which is `runEndpointBackfill`: the install backfill's sweep, window, budget and system-mode confinement, with cursors so each run reads only what is new. `lifecycle.ReconcileSessionSyncJob` installs it when on and removes it when off on every install, repair and package upgrade (`beacon endpoint sessions install-daemon`), and `buildConfig` carries the setting. It and the inventory job share `service.scheduledJob` (`jobSpec` per job). The scheduled run reports failures and exits 0 so the scheduler keeps it; a manual run fails on them. Every sweep (install, connect, manual and scheduled) and every writing `beacon endpoint <runtime> sync` (through `collectUnderSweepLock`, once or per `--watch` tick; a test fails on a collector called directly from `cmd`) holds `<BaseDir>/state/session-sweep.lock` for its whole run, because collectors load cursors at the start and save them at the end; the scheduled run and watch ticks skip when it is held, `--print` takes no lock, and the scheduled run returns early unless `session_sync.enabled` is on. An install or connect that skips its backfill (`--no-backfill`, `BEACON_BACKFILL=0`) records per-runtime floors in `session-sync-floor.json` beside the lock (`recordSkippedBackfill`), and a session sync then reads only that runtime's sessions active since (`sessionwindow.Recent` is per session, so an ongoing one is read whole); only a runtime with none of its own cursor files (`endpointBackfillRunner.State`, resolved in the console user's home for a system endpoint) gets one, an existing floor is never moved later, and a backfill that runs removes them all. A scheduled system run copies each `SQLite` runner's store at most every `endpointSnapshotInterval` (an hour; times in `session-sync-snapshots.json`), because the confined copy can approach `sessionfs.MaxSnapshotBytes`. Tests point `endpointSweepLockPath` at a temp dir in `TestMain`. `beacon endpoint sessions enable|disable` (`lifecycle.SetSessionSync`) changes only that key of config.json (`setConfigFileKey`) and reconciles the job, because a repair rebuilds the config from its flags and resets harnesses, ports and HEC destinations it is not given. Package installs set it with `BEACON_SESSION_SYNC=1|0` (unset keeps it) in `install-endpoint.sh` (macOS and Linux). A user-mode job carries `sessionSyncJobEnv` (the inventory job's variables plus `sessionSyncJobPathEnv`/`sessionSyncJobNameEnv`), and a test fails when a session-store collector reads a variable it does not carry.
+- Scheduled session sync (`beacon endpoint install|repair --session-sync`, `--no-session-sync`; `config.json` `session_sync.enabled`, opt-in; docs in `docs/cli/endpoint-install.mdx#scheduled-session-sync`): a one-shot job, `com.beacon.endpoint.session-sync` / `beacon-session-sync.timer` (`service.SessionSyncManager`), every 15 minutes starting one interval after load (`jobSpec.runAtLoad` false, unlike inventory: a run fired at load would take the sweep lock ahead of the install backfill that follows it), running the hidden-flagged `beacon endpoint sessions sync --scheduled` (`cli/beacon/cmd/endpoint_session_sync.go`), which is `runEndpointBackfill`: the install backfill's sweep, window, budget and system-mode confinement, with cursors so each run reads only what is new. `lifecycle.ReconcileSessionSyncJob` installs it when on and removes it when off on every install, repair and package upgrade (`beacon endpoint sessions install-daemon`), and `buildConfig` carries the setting. It and the inventory job share `service.scheduledJob` (`jobSpec` per job). The scheduled run reports failures and exits 0 so the scheduler keeps it; a manual run fails on them. Every sweep (install, connect, manual and scheduled) and every writing `beacon endpoint <runtime> sync` (through `collectUnderSweepLock`, once or per `--watch` tick; a test fails on a collector called directly from `cmd`) holds `<BaseDir>/state/session-sweep.lock` for its whole run, because collectors load cursors at the start and save them at the end; the scheduled run and watch ticks skip when it is held, `--print` takes no lock, and the scheduled run returns early unless `session_sync.enabled` is on. An install or connect that skips its backfill (`--no-backfill`, `BEACON_BACKFILL=0`) records per-runtime floors in `session-sync-floor.json` beside the lock (`recordSkippedBackfill`), and a session sync then reads only that runtime's sessions active since (`sessionwindow.Recent` is per session, so an ongoing one is read whole); only a runtime with none of its own cursor files (`endpointBackfillRunner.State`, resolved in the console user's home for a system endpoint) gets one, an existing floor is never moved later, a runtime added after the skip (no floor, no cursors) gets the earliest recorded floor, written to the file by the first session sync that sees it (`floorRuntimesAddedSinceTheSkip`) so it outlasts the cursors that sync saves, and a backfill that runs removes them all. A scheduled system run copies each `SQLite` runner's store at most every `endpointSnapshotInterval` (an hour; times in `session-sync-snapshots.json`), because the confined copy can approach `sessionfs.MaxSnapshotBytes`. Tests point `endpointSweepLockPath` at a temp dir in `TestMain`. `beacon endpoint sessions enable|disable` (`lifecycle.SetSessionSync`) changes only that key of config.json (`setConfigFileKey`) and reconciles the job, because a repair rebuilds the config from its flags and resets harnesses, ports and HEC destinations it is not given. Package installs set it with `BEACON_SESSION_SYNC=1|0` (unset keeps it) in `install-endpoint.sh` (macOS and Linux). A user-mode job carries `sessionSyncJobEnv` (the inventory job's variables plus `sessionSyncJobPathEnv`/`sessionSyncJobNameEnv`), and a test fails when a session-store collector reads a variable it does not carry.
- Endpoint inventory (`inventory.heartbeat` / `inventory.snapshot` in `inventory_state.jsonl`) is written by a scheduled job, `com.beacon.endpoint.inventory` (`service.InventoryManager`, user LaunchAgent or system LaunchDaemon, `beacon-inventory.timer` on systemd), every six hours and once at load, on by default and reconciled by `lifecycle.ReconcileInventoryJob` on every install, repair and package upgrade (`beacon endpoint inventory install-daemon`). Agent hooks do not trigger inventory any more; the hook binary's `--cli` flag and `inventory-heartbeat` subcommand survive only as no-ops for hook commands written by older versions, and `beacon endpoint inventory heartbeat --trigger hook` is likewise retired. A system-mode run inventories the active console user's home and still writes the liveness heartbeat when nobody is logged in; the scheduled scan has no working directory, so project-scoped config is only in `beacon endpoint inventory`.
- Beacon Cloud forwarding, the one Beacon-hosted network channel for endpoint telemetry: user-mode `beacon endpoint connect` authorizes device enrollment with the signed-in CLI account; system mode uses browser PKCE at `/cli/enroll`. Both store only the per-device key in `<BaseDir>/asymptote/vector-secrets.json` (0600, 0700 dir), render the selected privacy mode into `vector.toml` (re-rendered in place by install, repair and package upgrades, see above), validate it, and run Vector as `com.beacon.endpoint.asymptote-forwarder` / `beacon-asymptote-forwarder.service` through `service.ForwarderManager` (refused in supervised mode). `enrollment.json` and `config.json`'s `managed_ingest` block carry only non-secret identity and privacy mode; `beacon endpoint status` reports forwarder state and a live credential check (`GET /v1/ingest/health`, 3 s timeout); `disconnect` and `uninstall` remove the forwarder and credentials but never revoke server-side.
- Asymptote Observe TypeScript SDK instrumentation for cloud applications, starting from OpenTelemetry/OpenLLMetry patterns and `observe()` wrappers.
@@ -223,6 +224,14 @@ go run . endpoint fx status # sessions fx has written and how much Beacon
go run . endpoint fx sync --print # map records to events without writing anything
```
+Collect Antigravity CLI conversations the same way (`--print` never writes the runtime log):
+
+```bash
+cd cli/beacon
+go run . endpoint antigravity status
+go run . endpoint antigravity sync --print
+```
+
Connect an endpoint to Asymptote Managed during manual testing (needs Vector 0.50+ on the machine;
`/opt/beacon/bin/vector` from the signed package works, and a browser signed in to an org that has
managed ingest enabled):
diff --git a/README.md b/README.md
index c1cc442f..fb00d2af 100644
--- a/README.md
+++ b/README.md
@@ -314,7 +314,7 @@ Beacon supports local agents, browser agents, cloud agents, CI workflows, and ag
| Runtime | Collection | Session | Prompt | Tool | Command | File | Approval | MCP | Tokens | Skills |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
-| Antigravity CLI | Hooks | ✅ | ~ | ✅ | ✅ | ✅ | – | – | – | ✅ skills CLI |
+| Antigravity CLI | Hooks + poll | ✅ | ✅ | ✅ | ✅ | ✅ | – | – | ✅ | ✅ skills CLI |
| Claude Code | OTLP + hooks + poll | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ Plugin |
| Claude Cowork | OTLP | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ Plugin |
| Cline | Plugin + poll | ✅ | ✅ | ✅ | ✅ | ✅ | – | ✅ | ✅ | ✅ `.cline/skills` |
diff --git a/cli/beacon-hooks/cmd/agent_thought.go b/cli/beacon-hooks/cmd/agent_thought.go
index c095cf35..a706ca83 100644
--- a/cli/beacon-hooks/cmd/agent_thought.go
+++ b/cli/beacon-hooks/cmd/agent_thought.go
@@ -68,6 +68,18 @@ func retainedContentFields(text string) map[string]interface{} {
return asymptoteobserve.RetainedContentFields(text, asymptoteobserve.DefaultStringLimit)
}
+// setPromptFields records prompt on fields the one way every hook path does: prompt.text, the
+// semconv gen_ai.input.messages a message-oriented reader looks for, and the content marker that
+// says the text was retained. The marker's hash is also how a session-store sync recognizes a
+// prompt the hooks already recorded, so every path has to build it from the same text.
+func setPromptFields(fields map[string]interface{}, prompt string) {
+ fields["prompt"] = map[string]interface{}{"text": prompt}
+ fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{
+ "input": map[string]interface{}{"messages": asymptoteobserve.TextInputMessages(prompt)},
+ })
+ fields["content"] = retainedContentFields(prompt)
+}
+
// retainedDiffFields puts diff, its diff_hash and its diff_bytes into file and
// returns the content marker for it, all from one redaction of diff at the
// limit retainedContentFields uses, so diff_hash and diff_bytes always equal the
diff --git a/cli/beacon-hooks/cmd/cline_event.go b/cli/beacon-hooks/cmd/cline_event.go
index 30519854..b7d95a7c 100644
--- a/cli/beacon-hooks/cmd/cline_event.go
+++ b/cli/beacon-hooks/cmd/cline_event.go
@@ -208,11 +208,7 @@ func clinePromptEvents(fields map[string]interface{}, prompt string) []normalize
}
func clinePromptEvent(fields map[string]interface{}, prompt string) normalizedEvent {
- fields["prompt"] = map[string]interface{}{"text": prompt}
- fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{
- "input": map[string]interface{}{"messages": asymptoteobserve.TextInputMessages(prompt)},
- })
- fields["content"] = retainedContentFields(prompt)
+ setPromptFields(fields, prompt)
return normalizedEvent{
action: "prompt.submitted", category: "prompt", severity: "info",
message: "Prompt submitted to Cline", fields: fields,
diff --git a/cli/beacon-hooks/cmd/endpoint_events.go b/cli/beacon-hooks/cmd/endpoint_events.go
index 809c62c0..d781682c 100644
--- a/cli/beacon-hooks/cmd/endpoint_events.go
+++ b/cli/beacon-hooks/cmd/endpoint_events.go
@@ -345,6 +345,12 @@ func toolFieldsWithResponse(toolName string, toolInput, toolResponse map[string]
if path == "" && platformFlag == goosePlatform {
path = gooseToolPath(toolName, toolInput)
}
+ // Antigravity names a file tool's target TargetFile (its write and replace tools) or
+ // SearchDirectory (find_by_name), neither in the shared list above. Asked after it for the Kiro
+ // reason, from the vocabulary the session-store collector reads too.
+ if path == "" && platformFlag == "antigravity" {
+ path = asymptoteobserve.AntigravityToolPath(toolInput)
+ }
if path != "" {
fields["file"] = map[string]interface{}{
"path": path,
@@ -1030,13 +1036,8 @@ func actionForTool(hookEvent, toolName string, toolInput, toolResponse map[strin
}
}
if platformFlag == "antigravity" {
- switch lower {
- case "run_command":
- return "command.executed"
- case "view_file", "list_dir", "grep_search", "find_by_name":
- return "file.read"
- case "edit_file", "write_file", "apply_patch":
- return "file.modified"
+ if action := asymptoteobserve.AntigravityToolAction(toolName); action != "" {
+ return action
}
}
switch {
diff --git a/cli/beacon-hooks/cmd/openclaw_event.go b/cli/beacon-hooks/cmd/openclaw_event.go
index 1d816df9..71ec094f 100644
--- a/cli/beacon-hooks/cmd/openclaw_event.go
+++ b/cli/beacon-hooks/cmd/openclaw_event.go
@@ -5,7 +5,6 @@ import (
"strings"
hookdiff "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/diff"
- "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
"github.com/spf13/cobra"
)
@@ -336,11 +335,7 @@ func openClawPromptEvents(input, event, fields map[string]interface{}) []normali
if prompt == "" {
return nil
}
- fields["prompt"] = map[string]interface{}{"text": prompt}
- fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{
- "input": map[string]interface{}{"messages": asymptoteobserve.TextInputMessages(prompt)},
- })
- fields["content"] = retainedContentFields(prompt)
+ setPromptFields(fields, prompt)
// Who sent it, and over which chat app. On a single-user coding CLI this is implied; on a
// gateway that fans several people's chat accounts into one agent it is the difference between
diff --git a/cli/beacon-hooks/cmd/opencode_event.go b/cli/beacon-hooks/cmd/opencode_event.go
index ffa0b2fd..1a5e9b9b 100644
--- a/cli/beacon-hooks/cmd/opencode_event.go
+++ b/cli/beacon-hooks/cmd/opencode_event.go
@@ -58,11 +58,7 @@ func opencodeEndpointEvents(input map[string]interface{}, sessionID string) []no
switch eventType {
case "chat.message":
if prompt := opencodePromptText(input); prompt != "" {
- fields["prompt"] = map[string]interface{}{"text": prompt}
- fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{
- "input": map[string]interface{}{"messages": asymptoteobserve.TextInputMessages(prompt)},
- })
- fields["content"] = retainedContentFields(prompt)
+ setPromptFields(fields, prompt)
}
events := one("prompt.submitted", "prompt", "info", "Prompt submitted to opencode", fields)
if link, ok := handoffLinkEvent(fields, opencodePromptText(input)); ok {
diff --git a/cli/beacon-hooks/cmd/pi_family.go b/cli/beacon-hooks/cmd/pi_family.go
index e8dea8b5..af26fa11 100644
--- a/cli/beacon-hooks/cmd/pi_family.go
+++ b/cli/beacon-hooks/cmd/pi_family.go
@@ -288,11 +288,7 @@ func (f piFamily) baseFields(input map[string]interface{}, sessionID string) map
}
func (f piFamily) promptEvent(fields map[string]interface{}, prompt, source string) normalizedEvent {
- fields["prompt"] = map[string]interface{}{"text": prompt}
- fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{
- "input": map[string]interface{}{"messages": asymptoteobserve.TextInputMessages(prompt)},
- })
- fields["content"] = retainedContentFields(prompt)
+ setPromptFields(fields, prompt)
if source != "" {
// These runtimes distinguish interactive input from input delivered over their RPC surface
// or injected by another extension. Retained because "a human typed this" and "a script
diff --git a/cli/beacon-hooks/cmd/post_tool.go b/cli/beacon-hooks/cmd/post_tool.go
index 230218b1..a51351e8 100644
--- a/cli/beacon-hooks/cmd/post_tool.go
+++ b/cli/beacon-hooks/cmd/post_tool.go
@@ -642,11 +642,7 @@ func isFileEditTool(platform, toolName string) bool {
strings.Contains(lower, "patch")
}
if platform == "antigravity" {
- lower := strings.ToLower(toolName)
- return strings.Contains(lower, "edit") ||
- strings.Contains(lower, "write") ||
- strings.Contains(lower, "create") ||
- strings.Contains(lower, "patch")
+ return asymptoteobserve.AntigravityToolAction(toolName) == "file.modified"
}
if platform == "qwen" {
return isQwenFileEditTool(toolName)
diff --git a/cli/beacon-hooks/cmd/post_tool_test.go b/cli/beacon-hooks/cmd/post_tool_test.go
index cf26bb92..cf6072f9 100644
--- a/cli/beacon-hooks/cmd/post_tool_test.go
+++ b/cli/beacon-hooks/cmd/post_tool_test.go
@@ -354,6 +354,36 @@ func TestRunPostToolEmitsAntigravityFileModifiedEvent(t *testing.T) {
}
}
+// Antigravity's documented edit tools, replace_file_content and multi_replace_file_content, carry
+// no edit/write verb the substring rule matches and name their file TargetFile. They are file
+// edits on the live path as on the session-store path, with the path recorded.
+func TestRunPostToolRecordsAntigravityReplaceToolsAsFileEdits(t *testing.T) {
+ for _, tool := range []string{"replace_file_content", "multi_replace_file_content", "write_to_file"} {
+ t.Run(tool, func(t *testing.T) {
+ setupHookConfigDirs(t)
+ platformFlag = "antigravity"
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+
+ runHookWithInput(t, runPostTool, map[string]interface{}{
+ "conversationId": "ag-session",
+ "toolCall": map[string]interface{}{
+ "name": tool,
+ "args": map[string]interface{}{"TargetFile": "/repo/main.go", "Instruction": "rename the handler"},
+ },
+ })
+
+ event := lastEndpointEvent(t, logPath)
+ if action := event["event"].(map[string]interface{})["action"]; action != "file.modified" {
+ t.Fatalf("event.action = %q, want file.modified", action)
+ }
+ if file, _ := event["file"].(map[string]interface{}); file["path"] != "/repo/main.go" {
+ t.Fatalf("file = %#v, want the TargetFile path", event["file"])
+ }
+ })
+ }
+}
+
func TestRunPostToolEmitsAntigravityFileReadPathFields(t *testing.T) {
setupHookConfigDirs(t)
platformFlag = "antigravity"
diff --git a/cli/beacon-hooks/cmd/pre_tool.go b/cli/beacon-hooks/cmd/pre_tool.go
index 9fd95011..219c99b7 100644
--- a/cli/beacon-hooks/cmd/pre_tool.go
+++ b/cli/beacon-hooks/cmd/pre_tool.go
@@ -298,15 +298,8 @@ func emitAntigravityPromptFromTranscript(logger *logging.Logger, input map[strin
return
}
fields := sessionFields(sessionID, input)
- fields["prompt"] = map[string]interface{}{"text": prompt}
- fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{
- "input": map[string]interface{}{"messages": asymptoteobserve.TextInputMessages(prompt)},
- })
- fields["content"] = retainedContentFields(prompt)
- emitHookEvent(logger, "prompt.submitted", "prompt", "info", "Prompt submitted to agent", input, fields)
- if link, ok := handoffLinkEvent(fields, prompt); ok {
- emitHookEvent(logger, link.action, link.category, link.severity, link.message, input, link.fields)
- }
+ setPromptFields(fields, prompt)
+ emitPromptSubmitted(logger, input, fields, prompt)
}
func antigravityPromptFromTranscript(input map[string]interface{}, sessionID string) string {
@@ -326,13 +319,11 @@ func antigravityPromptFromTranscript(input map[string]interface{}, sessionID str
if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil {
continue
}
- source := strings.ToUpper(getFirstStr(entry, "source"))
- entryType := strings.ToUpper(getFirstStr(entry, "type"))
- if source != "USER_EXPLICIT" && entryType != "USER_INPUT" {
+ if !asymptoteobserve.IsAntigravityUserInput(getFirstStr(entry, "source"), getFirstStr(entry, "type")) {
continue
}
if content := getFirstStr(entry, "content"); content != "" {
- return stripAntigravityPromptWrappers(content)
+ return asymptoteobserve.AntigravityPrompt(content)
}
}
return ""
@@ -345,13 +336,3 @@ func defaultAntigravityTranscriptPath(sessionID string) string {
}
return filepath.Join(home, ".gemini", "antigravity-cli", "brain", sessionID, ".system_generated", "logs", "transcript.jsonl")
}
-
-func stripAntigravityPromptWrappers(content string) string {
- if start := strings.Index(content, "<USER_REQUEST>"); start >= 0 {
- content = content[start+len("<USER_REQUEST>"):]
- if end := strings.Index(content, "</USER_REQUEST>"); end >= 0 {
- content = content[:end]
- }
- }
- return strings.TrimSpace(content)
-}
diff --git a/cli/beacon-hooks/cmd/pre_tool_test.go b/cli/beacon-hooks/cmd/pre_tool_test.go
index f33da7a1..a9e59b49 100644
--- a/cli/beacon-hooks/cmd/pre_tool_test.go
+++ b/cli/beacon-hooks/cmd/pre_tool_test.go
@@ -15,6 +15,7 @@ import (
"github.com/spf13/cobra"
hookconfig "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)
// Cursor reads the pre-tool answer as the call's permission; a payload with no session must still
@@ -285,39 +286,66 @@ func TestRunPromptSubmitEmitsFactoryPromptEvent(t *testing.T) {
}
}
-// Antigravity names the prompt `prompt` on one hook and `userPrompt` on another.
-func TestRunPromptSubmitEmitsAntigravityPromptEvent(t *testing.T) {
- for _, key := range []string{"prompt", "userPrompt"} {
- t.Run(key, func(t *testing.T) {
- setupHookConfigDirs(t)
- platformFlag = "antigravity"
- logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
- t.Setenv("BEACON_ENDPOINT_LOG", logPath)
- t.Setenv("BEACON_CONTENT_RETENTION", "full")
+// Antigravity's PreInvocation runs before every model call and carries the turn's prompt as
+// `lastUserInput` each time; `invocationNum` restarts at 0 on every turn. The sequence below is
+// what agy 1.5.3 sent for a two-turn conversation whose first turn ran one tool. Each turn's
+// prompt is recorded once, and the first tool call does not replay the first prompt from the
+// transcript. A prompt is normalized the way the session-store sync normalizes the transcript's
+// copy, so both hash alike and the sync recognizes it as recorded.
+func TestRunPromptSubmitRecordsEachAntigravityTurnOnce(t *testing.T) {
+ setupHookConfigDirs(t)
+ platformFlag = "antigravity"
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+ t.Setenv("BEACON_CONTENT_RETENTION", "full")
+ transcriptPath := filepath.Join(t.TempDir(), "transcript.jsonl")
+ if err := os.WriteFile(transcriptPath, []byte(`{"source":"USER_EXPLICIT","type":"USER_INPUT","content":"<USER_REQUEST>\nsummarize token=ag-secret\n</USER_REQUEST>"}`+"\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ invocation := func(n int, prompt string) map[string]interface{} {
+ return map[string]interface{}{
+ "conversationId": "ag-session",
+ "workspacePaths": []interface{}{"/repo"},
+ "transcriptPath": transcriptPath,
+ "invocationNum": float64(n),
+ "lastUserInput": prompt,
+ }
+ }
- out := runHookWithInput(t, runPromptSubmit, map[string]interface{}{
- "conversationId": "ag-session",
- "workspacePaths": []interface{}{"/repo"},
- key: "summarize token=ag-secret",
- })
- if len(out) != 0 {
- t.Fatalf("antigravity prompt response = %#v, want empty response", out)
- }
+ if out := runHookWithInput(t, runPromptSubmit, invocation(0, "summarize token=ag-secret")); len(out) != 0 {
+ t.Fatalf("antigravity prompt response = %#v, want empty response", out)
+ }
+ toolCall := invocation(0, "summarize token=ag-secret")
+ delete(toolCall, "invocationNum")
+ toolCall["toolCall"] = map[string]interface{}{"name": "run_command", "args": map[string]interface{}{"CommandLine": "ls"}}
+ runHookWithInput(t, runPreTool, toolCall)
+ if out := runHookWithInput(t, runPromptSubmit, invocation(1, "summarize token=ag-secret")); len(out) != 0 {
+ t.Fatalf("antigravity prompt response = %#v, want empty response", out)
+ }
+ runHookWithInput(t, runPromptSubmit, invocation(0, "\n now say done \n"))
- event := lastEndpointEvent(t, logPath)
- if action := event["event"].(map[string]interface{})["action"]; action != "prompt.submitted" {
- t.Fatalf("event.action = %q, want prompt.submitted", action)
- }
- if harness := event["harness"].(map[string]interface{})["name"]; harness != "antigravity_cli" {
- t.Fatalf("harness = %q, want antigravity_cli", harness)
- }
- if got := event["prompt"].(map[string]interface{})["text"]; got != "summarize token=[REDACTED]" {
- t.Fatalf("prompt.text = %q, want redacted prompt", got)
- }
- if got := event["repository"]; got != "/repo" {
- t.Fatalf("repository = %q, want /repo", got)
- }
- })
+ var prompts []map[string]interface{}
+ for _, event := range endpointEvents(t, logPath) {
+ if event["event"].(map[string]interface{})["action"] == "prompt.submitted" {
+ prompts = append(prompts, event)
+ }
+ }
+ if len(prompts) != 2 {
+ t.Fatalf("prompt.submitted events = %d, want one per turn: %#v", len(prompts), prompts)
+ }
+ for i, want := range []string{"summarize token=[REDACTED]", "now say done"} {
+ if got := prompts[i]["prompt"].(map[string]interface{})["text"]; got != want {
+ t.Errorf("turn %d prompt.text = %q, want %q", i+1, got, want)
+ }
+ if harness := prompts[i]["harness"].(map[string]interface{})["name"]; harness != "antigravity_cli" {
+ t.Errorf("turn %d harness = %q, want antigravity_cli", i+1, harness)
+ }
+ if got := prompts[i]["repository"]; got != "/repo" {
+ t.Errorf("turn %d repository = %q, want /repo", i+1, got)
+ }
+ }
+ if got, want := prompts[1]["content"].(map[string]interface{})["hash"], asymptoteobserve.RetainedContent(asymptoteobserve.AntigravityPrompt("<USER_REQUEST>\nnow say done\n</USER_REQUEST>"), 0).Hash; got != want {
+ t.Errorf("turn 2 content.hash = %v, want the hash the sync gives the transcript's copy (%s)", got, want)
}
}
diff --git a/cli/beacon-hooks/cmd/prompt_submit.go b/cli/beacon-hooks/cmd/prompt_submit.go
index ce4bd720..b5b9988b 100644
--- a/cli/beacon-hooks/cmd/prompt_submit.go
+++ b/cli/beacon-hooks/cmd/prompt_submit.go
@@ -3,6 +3,7 @@ package cmd
import (
"github.com/spf13/cobra"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"
"github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/state"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)
@@ -25,6 +26,10 @@ func runPromptSubmit(cmd *cobra.Command, args []string) {
outputJSON(hookNoopResponse())
return
}
+ if platformFlag == "antigravity" && !antigravityTurnStart(input) {
+ outputJSON(hookNoopResponse())
+ return
+ }
sessionID := resolveSessionID(input, platformFlag)
logger := newHookLogger("prompt-submit", platformFlag, sessionID)
@@ -47,23 +52,16 @@ func runPromptSubmit(cmd *cobra.Command, args []string) {
if platformFlag == goosePlatform {
prompt = goosePrompt(input)
}
+ if platformFlag == "antigravity" {
+ // The same normalization the transcript fallback and the session-store sync apply, so
+ // the prompt hashes the same on every path and a sync recognizes it as recorded.
+ prompt = asymptoteobserve.AntigravityPrompt(getFirstStr(input, "lastUserInput"))
+ }
hasPrompt := prompt != ""
if hasPrompt {
- fields["prompt"] = map[string]interface{}{"text": prompt}
- // The same two fields the Cline, opencode and Pi prompt mappers already
- // write. This path serves Claude Code, Cursor and the rest of the hook
- // runtimes, and wrote neither -- so a prompt captured here was readable only
- // as prompt.text, with nothing recording that the text was retained and
- // nothing in the semconv shape a message-oriented reader looks for.
- fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{
- "input": map[string]interface{}{"messages": asymptoteobserve.TextInputMessages(prompt)},
- })
- fields["content"] = retainedContentFields(prompt)
- }
- emitHookEvent(logger, "prompt.submitted", "prompt", "info", "Prompt submitted to agent", input, fields)
- if link, ok := handoffLinkEvent(fields, prompt); ok {
- emitHookEvent(logger, link.action, link.category, link.severity, link.message, input, link.fields)
+ setPromptFields(fields, prompt)
}
+ emitPromptSubmitted(logger, input, fields, prompt)
if platformFlag == "antigravity" && sessionID != "" && hasPrompt {
st := state.NewSessionState(sessionID, "antigravity")
@@ -75,3 +73,23 @@ func runPromptSubmit(cmd *cobra.Command, args []string) {
maybeUploadCursorCloudTelemetry(logger)
outputJSON(hookNoopResponse())
}
+
+// emitPromptSubmitted writes the prompt.submitted event for fields, and the session.handoff link
+// when prompt carries a handoff marker.
+func emitPromptSubmitted(logger *logging.Logger, input, fields map[string]interface{}, prompt string) {
+ emitHookEvent(logger, "prompt.submitted", "prompt", "info", "Prompt submitted to agent", input, fields)
+ if link, ok := handoffLinkEvent(fields, prompt); ok {
+ emitHookEvent(logger, link.action, link.category, link.severity, link.message, input, link.fields)
+ }
+}
+
+// antigravityTurnStart reports whether an Antigravity PreInvocation payload is the first model
+// call of a turn. Antigravity has no prompt-submit hook: PreInvocation runs before every model
+// call, carrying the turn's prompt as `lastUserInput` each time, and `invocationNum` counts the
+// calls from 0 again at the start of every turn, resumed conversations included. Recording only
+// invocation 0 records each prompt once. A payload without the counter is recorded, because a
+// duplicate prompt beats a lost one.
+func antigravityTurnStart(input map[string]interface{}) bool {
+ n, ok := jsonInt(input["invocationNum"])
+ return !ok || n == 0
+}
diff --git a/cli/beacon/cmd/endpoint_antigravity.go b/cli/beacon/cmd/endpoint_antigravity.go
new file mode 100644
index 00000000..51d403c4
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_antigravity.go
@@ -0,0 +1,212 @@
+package cmd
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/antigravitysession"
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ endpointintegrations "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/integrations"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionsync"
+ "github.com/spf13/cobra"
+)
+
+var endpointAntigravityCmd = &cobra.Command{
+ Use: "antigravity",
+ Aliases: []string{"antigravity-cli"},
+ Short: "Collect telemetry from Antigravity CLI conversations",
+ Long: `Collect endpoint telemetry from Antigravity CLI's local conversation store.
+
+The live Antigravity hook integration remains available through
+'beacon endpoint hooks install --harness antigravity'. This command reads the
+transcripts Antigravity commits under ~/.gemini/antigravity-cli/brain, with each
+conversation's working directory from conversation_summaries.db beside it, and
+converts them into endpoint events marked harness.collection_method=poll, so it
+can backfill historical conversations and the agent messages, reasoning and
+token usage the hook payloads do not carry, but cannot hold, allow, or deny
+tool calls. Conversations the live hooks already cover, from the first hook
+event in the runtime log, get only what the hook payload cannot carry: agent
+messages, reasoning and token usage.`,
+}
+
+var endpointAntigravitySyncCmd = &cobra.Command{
+ Use: "sync",
+ Short: "Read new Antigravity CLI conversation steps into the runtime log",
+ SilenceUsage: true,
+ RunE: runEndpointAntigravitySync,
+}
+
+var endpointAntigravityStatusCmd = &cobra.Command{
+ Use: "status",
+ Short: "Show Antigravity CLI conversations on this machine and how much has been collected",
+ SilenceUsage: true,
+ RunE: runEndpointAntigravityStatus,
+}
+
+var endpointAntigravityOpts struct {
+ brainDir string
+ statePath string
+ logPath string
+ print bool
+ watch bool
+ interval time.Duration
+ rotateBytes int64
+}
+
+func init() {
+ endpointCmd.AddCommand(endpointAntigravityCmd)
+ endpointAntigravityCmd.AddCommand(endpointAntigravitySyncCmd)
+ endpointAntigravityCmd.AddCommand(endpointAntigravityStatusCmd)
+
+ for _, c := range []*cobra.Command{endpointAntigravitySyncCmd, endpointAntigravityStatusCmd} {
+ f := c.Flags()
+ f.StringVar(&endpointAntigravityOpts.brainDir, "brain-dir", "", "Antigravity CLI brain directory; conversation_summaries.db is read from beside it (default ~/.gemini/antigravity-cli/brain)")
+ f.StringVar(&endpointAntigravityOpts.statePath, "state", "", "Collector cursor file (default ~/.beacon/endpoint/state/antigravity-sessions.json)")
+ f.BoolVar(&endpointOpts.jsonOutput, "json", false, "Print the result as JSON")
+ f.BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")
+ f.BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths")
+ }
+
+ sync := endpointAntigravitySyncCmd.Flags()
+ sync.StringVar(&endpointAntigravityOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")
+ sync.BoolVar(&endpointAntigravityOpts.print, "print", false, "Print mapped events as JSON without writing them or advancing the cursor (dry run)")
+ sync.BoolVar(&endpointAntigravityOpts.watch, "watch", false, "Sweep continuously on --interval (default: one sweep then exit)")
+ sync.DurationVar(&endpointAntigravityOpts.interval, "interval", time.Minute, "Sweep interval for --watch")
+ addSyncRotateBytesFlag(sync, &endpointAntigravityOpts.rotateBytes)
+}
+
+func runEndpointAntigravitySync(cmd *cobra.Command, args []string) error {
+ if err := checkSyncRotateBytes(endpointAntigravityOpts.rotateBytes); err != nil {
+ return err
+ }
+ userMode := endpointUserMode()
+ logPath := lifecycle.ResolveRuntimeLog(userMode, endpointAntigravityOpts.logPath).EffectiveLogPath
+ opts := antigravitysession.CollectOptions{
+ RotateBytes: endpointAntigravityOpts.rotateBytes,
+ BrainDir: endpointAntigravityOpts.brainDir,
+ Print: endpointAntigravityOpts.print,
+ Out: cmd.OutOrStdout(),
+ Write: !endpointAntigravityOpts.print,
+ UserMode: userMode,
+ // Live coverage comes from the log this sweep writes to, in print and write modes
+ // alike: a dry run should show exactly what a real sweep would emit.
+ LiveCoverage: endpointAntigravityLiveCoverage(logPath),
+ }
+ if !endpointAntigravityOpts.print {
+ opts.StatePath = resolveAntigravityStatePath(endpointAntigravityOpts.statePath, userMode)
+ opts.LogPath = logPath
+ }
+
+ ctx := cmd.Context()
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ if endpointAntigravityOpts.watch && !endpointAntigravityOpts.print {
+ return watchAntigravity(ctx, cmd, opts)
+ }
+ summary, err := collectUnderSweepLock(opts.Write, opts.UserMode, endpointSweepLockWait, antigravitysession.CollectOnce, opts)
+ reportAntigravitySweep(cmd, summary)
+ return err
+}
+
+func watchAntigravity(ctx context.Context, cmd *cobra.Command, opts antigravitysession.CollectOptions) error {
+ interval := endpointAntigravityOpts.interval
+ if interval < 5*time.Second {
+ interval = 5 * time.Second
+ }
+ for {
+ // Coverage is rebuilt every tick: a conversation the hooks start recording after the watch
+ // began would otherwise be missing from it, and every tick would record it a second time.
+ opts.LiveCoverage = endpointAntigravityLiveCoverage(opts.LogPath)
+ summary, err := collectUnderSweepLock(opts.Write, opts.UserMode, 0, antigravitysession.CollectOnce, opts)
+ if err != nil {
+ fmt.Fprintf(cmd.ErrOrStderr(), "antigravity sync error: %v\n", err)
+ }
+ reportAntigravitySweep(cmd, summary)
+ select {
+ case <-ctx.Done():
+ return nil
+ case <-time.After(interval):
+ }
+ }
+}
+
+func reportAntigravitySweep(cmd *cobra.Command, summary antigravitysession.SummaryResult) {
+ if endpointAntigravityOpts.print {
+ return
+ }
+ if endpointOpts.jsonOutput {
+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(summary)
+ return
+ }
+ fmt.Fprintf(cmd.OutOrStdout(), "antigravity sync: %d conversations, %d changed, %d events, %d errors\n",
+ summary.Sessions, summary.SessionsChanged, summary.EventsEmitted, summary.Errors)
+ reportSyncRetention(cmd.OutOrStdout(), summary.Retention)
+ if summary.MalformedLines > 0 {
+ fmt.Fprintf(cmd.OutOrStdout(), " %d unreadable line(s) in Antigravity CLI transcripts\n", summary.MalformedLines)
+ }
+ if summary.EventsSuppressedLive > 0 {
+ fmt.Fprintf(cmd.OutOrStdout(), " %d event(s) skipped as already recorded by the live Antigravity hooks\n", summary.EventsSuppressedLive)
+ }
+}
+
+func runEndpointAntigravityStatus(cmd *cobra.Command, args []string) error {
+ // The conversations come back even when the summaries database could not be read; the status
+ // is still right about them, so the error is a warning here.
+ refs, listErr := antigravitysession.NewStore(endpointAntigravityOpts.brainDir).List()
+ if listErr != nil && len(refs) == 0 {
+ return listErr
+ }
+ if listErr != nil {
+ fmt.Fprintf(cmd.ErrOrStderr(), "warning: %v\n", listErr)
+ }
+ statePath := resolveAntigravityStatePath(endpointAntigravityOpts.statePath, endpointUserMode())
+ state, err := antigravitysession.LoadState(statePath)
+ if err != nil {
+ return err
+ }
+ type status struct {
+ Sessions int `json:"sessions"`
+ Collected int `json:"collected"`
+ StatePath string `json:"state_path"`
+ }
+ out := status{Sessions: len(refs), StatePath: statePath}
+ for _, ref := range refs {
+ cursor := state.Sessions[ref.ID]
+ if cursor != nil && cursor.UpdatedAtMS >= ref.ModTimeUnixMS && cursor.Events > 0 {
+ out.Collected++
+ }
+ }
+ if endpointOpts.jsonOutput {
+ return json.NewEncoder(cmd.OutOrStdout()).Encode(out)
+ }
+ fmt.Fprintf(cmd.OutOrStdout(), "antigravity conversations: %d found, %d collected\n", out.Sessions, out.Collected)
+ if out.Collected < out.Sessions {
+ fmt.Fprintln(cmd.OutOrStdout(), " run `beacon endpoint antigravity sync` to collect new committed conversations")
+ }
+ return nil
+}
+
+// resolveAntigravityStatePath picks the cursor file for the mode the sweep is running in, the same
+// split resolveGrokStatePath makes: a system sweep collects on behalf of the machine, so its cursor
+// belongs beside the system state rather than in one operator's home.
+func resolveAntigravityStatePath(path string, userMode bool) string {
+ if strings.TrimSpace(path) != "" {
+ return path
+ }
+ if userMode {
+ return antigravitysession.DefaultStatePath()
+ }
+ return filepath.Join(endpointconfig.BaseDir(false), "state", "antigravity-sessions.json")
+}
+
+// endpointAntigravityLiveCoverage is the live hook coverage of each Antigravity conversation in the
+// retained runtime log, for the sync command and the backfill runner alike.
+func endpointAntigravityLiveCoverage(logPath string) sessionsync.LiveCoverage {
+ return endpointintegrations.HookCoverage(logPath, "antigravity", antigravitysession.Harness)
+}
diff --git a/cli/beacon/cmd/endpoint_backfill.go b/cli/beacon/cmd/endpoint_backfill.go
index 432aa048..3e04481c 100644
--- a/cli/beacon/cmd/endpoint_backfill.go
+++ b/cli/beacon/cmd/endpoint_backfill.go
@@ -11,6 +11,7 @@ import (
"strings"
"time"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/antigravitysession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/claudesession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/clinesession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/codexsession"
@@ -148,6 +149,10 @@ var endpointBackfillRunners = func() []endpointBackfillRunner {
s, err := groksession.CollectOnce(groksession.CollectOptions{Write: true, UserMode: r.UserMode, LogPath: r.LogPath, StatePath: resolveGrokStatePath("", r.UserMode), Since: r.Since, Budget: r.Budget})
return s.EventsEmitted, err
}},
+ {Name: "Antigravity CLI", Sync: "beacon endpoint antigravity sync", State: func(m bool) []string { return []string{resolveAntigravityStatePath("", m)} }, Run: func(r endpointBackfillRun) (int, error) {
+ s, err := antigravitysession.CollectOnce(antigravitysession.CollectOptions{Write: true, UserMode: r.UserMode, LogPath: r.LogPath, StatePath: resolveAntigravityStatePath("", r.UserMode), Since: r.Since, Budget: r.Budget, LiveCoverage: endpointAntigravityLiveCoverage(r.LogPath)})
+ return s.EventsEmitted, err
+ }, SQLite: true},
{Name: "Harness²", Sync: "beacon endpoint harness2 sync", State: func(m bool) []string { return []string{resolveHarness2StatePath("", m)} }, Run: func(r endpointBackfillRun) (int, error) {
opts := harness2session.CollectOptions{Write: true, UserMode: r.UserMode, LogPath: r.LogPath, StatePath: resolveHarness2StatePath("", r.UserMode), Since: r.Since, Budget: r.Budget}
opts.ExtraRoots = harness2BackfillExtraRoots(r.UserMode)
@@ -287,6 +292,7 @@ func runEndpointBackfillLocked(logPath string, userMode bool, wait time.Duration
_ = os.Remove(sessionSyncFloorPath(userMode))
} else {
sweep.Floors = readSessionSyncFloors(userMode)
+ floorRuntimesAddedSinceTheSkip(userMode, sweep.Floors)
}
return runEndpointBackfillUnlocked(logPath, userMode, sweep)
}
@@ -298,6 +304,61 @@ type endpointSweep struct {
ThrottleSnapshots bool
}
+// floorRuntimesAddedSinceTheSkip gives every runtime a skipped backfill did not floor, because an
+// upgrade added it later, the earliest recorded floor, and records it. The operator opted out of
+// the window before then for every runtime, not only the ones that existed at the time. The floor
+// is persisted rather than derived per sweep: the first floored sweep saves the runtime's cursors,
+// and a derived floor would then lapse and let the next sweep read the window the skip excluded.
+// A runtime with cursors reads on from them and gets none, as in recordSkippedBackfill. Without
+// recorded floors, nothing was skipped and nothing changes.
+func floorRuntimesAddedSinceTheSkip(userMode bool, floors map[string]time.Time) {
+ var earliest time.Time
+ for _, floor := range floors {
+ if earliest.IsZero() || floor.Before(earliest) {
+ earliest = floor
+ }
+ }
+ if earliest.IsZero() || !floorUnreadRuntimes(userMode, floors, earliest) {
+ return
+ }
+ // Unwritten, the floor still holds for this sweep; the next one derives it again only while
+ // the runtime has no cursors, which is the best a sweep that cannot write its state can do.
+ _ = writeSessionSyncFloors(userMode, floors)
+}
+
+// floorUnreadRuntimes sets at as the floor of every runtime with neither a floor nor cursors, and
+// reports whether it set any.
+func floorUnreadRuntimes(userMode bool, floors map[string]time.Time, at time.Time) bool {
+ changed := false
+ withSweepHome(userMode, func() {
+ for _, runner := range endpointBackfillRunners() {
+ if _, ok := floors[runner.Name]; ok || runnerHasCursors(runner, userMode) {
+ continue
+ }
+ floors[runner.Name] = at
+ changed = true
+ }
+ })
+ return changed
+}
+
+func writeSessionSyncFloors(userMode bool, floors map[string]time.Time) error {
+ path := sessionSyncFloorPath(userMode)
+ data, _ := json.Marshal(sessionSyncFloors{NotBefore: floors})
+ tmp := path + ".tmp"
+ err := os.MkdirAll(filepath.Dir(path), 0o700)
+ if err == nil {
+ err = os.WriteFile(tmp, append(data, '\n'), 0o600)
+ }
+ if err == nil {
+ err = os.Rename(tmp, path)
+ }
+ if err != nil {
+ _ = os.Remove(tmp)
+ }
+ return err
+}
+
// endpointSnapshotInterval is how often the scheduled system session sync copies a SQLite store
// (Cursor's state.vscdb, OpenCode, Devin CLI, Hermes Agent) to read it. A copy can approach
// sessionfs.MaxSnapshotBytes, and those runtimes are captured live by their hooks or plugins, so
@@ -356,32 +417,10 @@ func recordSkippedBackfill(out io.Writer, userMode bool) {
return
}
floors := readSessionSyncFloors(userMode)
- now := endpointBackfillNow().UTC()
- changed := false
- withSweepHome(userMode, func() {
- for _, runner := range endpointBackfillRunners() {
- if _, ok := floors[runner.Name]; ok || runnerHasCursors(runner, userMode) {
- continue
- }
- floors[runner.Name] = now
- changed = true
- }
- })
- if !changed {
+ if !floorUnreadRuntimes(userMode, floors, endpointBackfillNow().UTC()) {
return
}
- path := sessionSyncFloorPath(userMode)
- data, _ := json.Marshal(sessionSyncFloors{NotBefore: floors})
- tmp := path + ".tmp"
- err := os.MkdirAll(filepath.Dir(path), 0o700)
- if err == nil {
- err = os.WriteFile(tmp, append(data, '\n'), 0o600)
- }
- if err == nil {
- err = os.Rename(tmp, path)
- }
- if err != nil {
- _ = os.Remove(tmp)
+ if err := writeSessionSyncFloors(userMode, floors); err != nil {
fmt.Fprintf(out, "Warning: could not record the skipped session backfill (%v); a scheduled session sync may read the last %d days.\n", err, int(endpointBackfillWindow/(24*time.Hour)))
}
}
diff --git a/cli/beacon/cmd/endpoint_devin.go b/cli/beacon/cmd/endpoint_devin.go
index 8ca79a5e..c66e0ac6 100644
--- a/cli/beacon/cmd/endpoint_devin.go
+++ b/cli/beacon/cmd/endpoint_devin.go
@@ -1,20 +1,17 @@
package cmd
import (
- "bufio"
- "bytes"
"context"
"encoding/json"
"fmt"
- "os"
"path/filepath"
"strings"
"time"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/devinsession"
+ endpointintegrations "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/integrations"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
- "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
- "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionsync"
"github.com/spf13/cobra"
)
@@ -141,6 +138,9 @@ func watchEndpointDevin(ctx context.Context, cmd *cobra.Command, opts devinsessi
interval = 5 * time.Second
}
for {
+ // Coverage is rebuilt every tick: a session the hooks start recording after the watch began
+ // would otherwise be missing from it, and every tick would record it a second time.
+ opts.LiveCoverage = endpointDevinLiveCoverage(opts.LogPath)
summary, err := collectUnderSweepLock(opts.Write, opts.UserMode, 0, devinsession.CollectOnce, opts)
if err != nil {
fmt.Fprintf(cmd.ErrOrStderr(), "Devin CLI sync error: %v\n", err)
@@ -175,64 +175,10 @@ func reportEndpointDevinSweep(cmd *cobra.Command, summary devinsession.Summary)
}
}
-// endpointDevinLiveCoverage finds, per Devin session id, the earliest hook event the retained
-// runtime log holds. The poll sweep uses it to skip what the hooks already recorded: a session
-// the hooks never saw is collected whole, while a covered one keeps only the events the hook
-// payload cannot carry.
-//
-// Every retained archive is read because coverage can sit several rotations back on a busy
-// machine; a missing file is simply not evidence. The scan decodes only the three fields it
-// needs, so a runtime.jsonl of any size costs a line at a time, and only lines that could be a
-// Devin event are unmarshalled.
-func endpointDevinLiveCoverage(logPath string) map[string]time.Time {
- coverage := map[string]time.Time{}
- for _, path := range writer.RetainedLogPaths(logPath) {
- f, err := os.Open(path)
- if err != nil {
- continue
- }
- scanner := bufio.NewScanner(f)
- scanner.Buffer(make([]byte, 0, 64*1024), 1<<20)
- for scanner.Scan() {
- line := scanner.Bytes()
- if !bytes.Contains(line, []byte("devin")) {
- continue
- }
- var event struct {
- Timestamp string `json:"timestamp"`
- Harness struct {
- Name string `json:"name"`
- CollectionMethod string `json:"collection_method"`
- } `json:"harness"`
- Session struct {
- ID string `json:"id"`
- } `json:"session"`
- }
- if json.Unmarshal(line, &event) != nil {
- continue
- }
- name := asymptoteobserve.NormalizeHarnessName(event.Harness.Name)
- if (name != "devin-cli" && name != "devin") || event.Harness.CollectionMethod != asymptoteobserve.CollectionMethodHook {
- continue
- }
- sessionID := strings.TrimSpace(event.Session.ID)
- if sessionID == "" {
- continue
- }
- ts, err := asymptoteobserve.ParseTimestamp(event.Timestamp)
- if err != nil {
- continue
- }
- if earliest, ok := coverage[sessionID]; !ok || ts.Before(earliest) {
- coverage[sessionID] = ts
- }
- }
- _ = f.Close()
- }
- if len(coverage) == 0 {
- return nil
- }
- return coverage
+// endpointDevinLiveCoverage is the live hook coverage of each Devin session in the retained runtime
+// log, under either platform spelling, for the sync command and the backfill runner alike.
+func endpointDevinLiveCoverage(logPath string) sessionsync.LiveCoverage {
+ return endpointintegrations.HookCoverage(logPath, "devin", "devin-cli", "devin")
}
type devinSessionStatus struct {
diff --git a/cli/beacon/cmd/endpoint_devin_test.go b/cli/beacon/cmd/endpoint_devin_test.go
index 13c4d95c..44920288 100644
--- a/cli/beacon/cmd/endpoint_devin_test.go
+++ b/cli/beacon/cmd/endpoint_devin_test.go
@@ -15,8 +15,9 @@ import (
)
// endpointDevinLiveCoverage scans the retained log for the earliest hook event per Devin
-// session: hook events from either platform spelling count, poll events and other harnesses do
-// not, and a malformed line or a rotated archive neither stops nor fools the scan.
+// session and the content hash of each hook prompt: hook events from either platform spelling
+// count, poll events and other harnesses do not, and a malformed line or a rotated archive neither
+// stops nor fools the scan.
func TestEndpointDevinLiveCoverage(t *testing.T) {
dir := t.TempDir()
logPath := filepath.Join(dir, "runtime.jsonl")
@@ -26,7 +27,8 @@ func TestEndpointDevinLiveCoverage(t *testing.T) {
lines := []string{
`{"timestamp":"2026-10-01T10:00:00Z","harness":{"name":"devin-cli","collection_method":"poll"},"session":{"id":"sess-poll"}}`,
`{"timestamp":"2026-10-01T10:00:00Z","harness":{"name":"claude_code","collection_method":"hook"},"session":{"id":"sess-claude"}}`,
- hook("sess-1", "2026-10-02T10:00:00Z"),
+ `{"timestamp":"2026-10-02T10:00:00Z","harness":{"name":"devin-cli","collection_method":"hook"},"session":{"id":"sess-1"},"event":{"action":"prompt.submitted"},"content":{"hash":"prompt-hash"}}`,
+ `{"timestamp":"2026-10-02T10:00:01Z","harness":{"name":"devin-cli","collection_method":"poll"},"session":{"id":"sess-1"},"event":{"action":"prompt.submitted"},"content":{"hash":"poll-hash"}}`,
hook("sess-1", "2026-10-01T09:00:00Z"), // the earliest wins
`{malformed devin line`,
`{"timestamp":"2026-10-01T10:00:00Z","harness":{"name":"devin","collection_method":"hook"},"session":{"id":"sess-legacy"}}`,
@@ -41,28 +43,31 @@ func TestEndpointDevinLiveCoverage(t *testing.T) {
}
coverage := endpointDevinLiveCoverage(logPath)
- if len(coverage) != 3 {
- t.Fatalf("coverage = %v, want three hook-covered sessions", coverage)
+ if len(coverage.From) != 3 {
+ t.Fatalf("coverage = %v, want three hook-covered sessions", coverage.From)
}
- if got := coverage["sess-1"]; !got.Equal(time.Date(2026, 10, 1, 9, 0, 0, 0, time.UTC)) {
+ if got := coverage.From["sess-1"]; !got.Equal(time.Date(2026, 10, 1, 9, 0, 0, 0, time.UTC)) {
t.Fatalf("sess-1 coverage = %s, want the earliest hook event", got)
}
- if _, ok := coverage["sess-legacy"]; !ok {
+ if !coverage.RecordedPrompt("sess-1", "prompt-hash") || coverage.RecordedPrompt("sess-1", "poll-hash") {
+ t.Fatalf("prompts = %v, want the hook prompt's hash and not the poll prompt's", coverage.Prompts)
+ }
+ if _, ok := coverage.From["sess-legacy"]; !ok {
t.Fatal("the legacy devin platform spelling was not counted as live coverage")
}
- if got := coverage["sess-archived"]; !got.Equal(time.Date(2026, 9, 15, 8, 0, 0, 0, time.UTC)) {
+ if got := coverage.From["sess-archived"]; !got.Equal(time.Date(2026, 9, 15, 8, 0, 0, 0, time.UTC)) {
t.Fatalf("sess-archived coverage = %s", got)
}
for _, absent := range []string{"sess-poll", "sess-claude"} {
- if _, ok := coverage[absent]; ok {
+ if _, ok := coverage.From[absent]; ok {
t.Fatalf("%s counted as hook coverage though it is not a devin hook event", absent)
}
}
}
func TestEndpointDevinLiveCoverageWithoutALog(t *testing.T) {
- if got := endpointDevinLiveCoverage(filepath.Join(t.TempDir(), "runtime.jsonl")); got != nil {
- t.Fatalf("coverage = %v, want nil for a missing log", got)
+ if got := endpointDevinLiveCoverage(filepath.Join(t.TempDir(), "runtime.jsonl")); got.From != nil || got.Prompts != nil {
+ t.Fatalf("coverage = %+v, want none for a missing log", got)
}
}
diff --git a/cli/beacon/cmd/endpoint_session_sync_test.go b/cli/beacon/cmd/endpoint_session_sync_test.go
index 81808191..e1462b51 100644
--- a/cli/beacon/cmd/endpoint_session_sync_test.go
+++ b/cli/beacon/cmd/endpoint_session_sync_test.go
@@ -260,6 +260,35 @@ func TestSkippedBackfillFloorsOnlyRuntimesWithoutCursors(t *testing.T) {
}
}
+// A runtime an upgrade adds after a skipped backfill was not there to be floored and has no cursors.
+// It reads from the earliest recorded floor, not the whole window the operator opted out of, and
+// keeps reading from it once its first sweep has saved cursors.
+func TestRuntimeAddedAfterASkippedBackfillReadsFromTheEarliestFloor(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ isolateSweepState(t)
+ stubBackfill(t, 1<<20, 1<<20, writingRunner("Claude", 1, nil))
+ skipped := endpointBackfillNow()
+ recordSkippedBackfill(&bytes.Buffer{}, true)
+
+ var since time.Time
+ cursor := filepath.Join(t.TempDir(), "antigravity-sessions.json")
+ added := endpointBackfillRunner{Name: "Antigravity", Sync: "beacon endpoint antigravity sync",
+ State: func(bool) []string { return []string{cursor} },
+ Run: func(r endpointBackfillRun) (int, error) {
+ since = r.Since
+ return 0, os.WriteFile(cursor, []byte("{}"), 0o600)
+ }}
+ stubBackfill(t, 1<<20, 1<<20, writingRunner("Claude", 1, nil), added)
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ for sweep, after := range []time.Duration{72 * time.Hour, 72*time.Hour + 15*time.Minute} {
+ endpointBackfillNow = func() time.Time { return skipped.Add(after) }
+ runSessionSweep(logPath, true, true)
+ if !since.Equal(skipped) {
+ t.Fatalf("sweep %d read a runtime added after the skip from %s, want the skip's floor %s", sweep+1, since, skipped)
+ }
+ }
+}
+
// Every session-store runner names its cursor files in both modes, so a skipped backfill can tell
// which runtimes a sweep has already read.
func TestEveryBackfillRunnerNamesItsCursors(t *testing.T) {
diff --git a/cli/beacon/cmd/session_sync_retention_test.go b/cli/beacon/cmd/session_sync_retention_test.go
index 8d9a9e4f..805640ac 100644
--- a/cli/beacon/cmd/session_sync_retention_test.go
+++ b/cli/beacon/cmd/session_sync_retention_test.go
@@ -22,6 +22,7 @@ func TestEverySessionSyncRefusesARotateBytesBelowTheDefault(t *testing.T) {
run func(*cobra.Command, []string) error
opt *int64
}{
+ {"antigravity", endpointAntigravitySyncCmd, runEndpointAntigravitySync, &endpointAntigravityOpts.rotateBytes},
{"claude", endpointClaudeSyncCmd, runEndpointClaudeSync, &endpointClaudeOpts.rotateBytes},
{"devin", endpointDevinSyncCmd, runEndpointDevinSync, &endpointDevinOpts.rotateBytes},
{"codex", endpointCodexSyncCmd, runEndpointCodexSync, &endpointCodexOpts.rotateBytes},
diff --git a/cli/beacon/internal/antigravitysession/collect.go b/cli/beacon/internal/antigravitysession/collect.go
new file mode 100644
index 00000000..f4a9ce2a
--- /dev/null
+++ b/cli/beacon/internal/antigravitysession/collect.go
@@ -0,0 +1,283 @@
+package antigravitysession
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionsync"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionwindow"
+)
+
+const StateVersion = 1
+
+// Cursor records how far Beacon has read one conversation.
+//
+// A transcript is appended to while the conversation runs and again when it is resumed, so the
+// cursor keeps the last line written rather than a count: remembering only the modification time
+// and an event total would make every sweep after the conversation grew re-map it from its first
+// line and append a duplicate set to the runtime log.
+type Cursor struct {
+ // UpdatedAtMS is the transcript's last-seen modification time, used to skip conversations
+ // that cannot have changed. It is a cheap pre-filter, not the record of what was written.
+ UpdatedAtMS int64 `json:"updated_at_ms,omitempty"`
+ // Events is the running total of events handled for this conversation across all sweeps:
+ // written, or suppressed as already recorded by the live hooks.
+ Events int `json:"events,omitempty"`
+ // Line is the last transcript line whose events were all written, as a physical line number.
+ Line int `json:"line,omitempty"`
+ // Started records that session.started was written. It has no line of its own.
+ Started bool `json:"started,omitempty"`
+}
+
+type State struct {
+ Version int `json:"version"`
+ Sessions map[string]*Cursor `json:"sessions"`
+}
+
+func DefaultStatePath() string {
+ base := filepath.Join(os.TempDir(), "beacon")
+ if home, err := os.UserHomeDir(); err == nil && strings.TrimSpace(home) != "" {
+ base = filepath.Join(home, ".beacon")
+ }
+ return filepath.Join(base, "endpoint", "state", "antigravity-sessions.json")
+}
+
+var stateFile = sessionsync.StateFile[State]{
+ Name: "Antigravity CLI session",
+ New: func() *State { return &State{Version: StateVersion, Sessions: map[string]*Cursor{}} },
+ Valid: func(s *State) bool { return s.Version == StateVersion && s.Sessions != nil },
+ Stamp: func(s *State) {
+ if s.Sessions == nil {
+ s.Sessions = map[string]*Cursor{}
+ }
+ s.Version = StateVersion
+ },
+}
+
+func LoadState(path string) (*State, error) { return stateFile.Load(path) }
+
+func (s *State) Save(path string) error { return stateFile.Save(path, s) }
+
+func (s *State) cursor(id string) *Cursor {
+ if s.Sessions == nil {
+ s.Sessions = map[string]*Cursor{}
+ }
+ c := s.Sessions[id]
+ if c == nil {
+ c = &Cursor{}
+ s.Sessions[id] = c
+ }
+ return c
+}
+
+type CollectOptions struct {
+ // BrainDir is Antigravity's brain directory; empty is DefaultBrainDir. The summaries database
+ // is read from beside it.
+ BrainDir string
+ StatePath string
+ LogPath string
+ Write bool
+ UserMode bool
+ Print bool
+ Out io.Writer
+ // Since, when set, limits the sweep to conversations modified at or after it, newest first.
+ // Older ones are not read and their cursors do not move, so a later sync still collects them.
+ // The install-time backfill sets it; an ordinary sync leaves it zero.
+ Since time.Time
+ // Budget, when set, caps the bytes this sweep may append. The sweep stops at the first event
+ // that does not fit and returns writer.ErrBudgetSpent, with cursors past only what was written.
+ Budget *writer.Budget
+ // RotateBytes is the size the runtime log rotates at while this sweep writes it; zero is
+ // writer.DefaultRotateBytes.
+ RotateBytes int64
+ // LiveCoverage, when set, is what the live Antigravity hooks already recorded. The hook payload
+ // carries prompts and tool calls but no assistant text, reasoning or token counts, so for a
+ // covered conversation the sweep keeps what hooks cannot see, and every prompt they did not
+ // record (see liveDuplicate).
+ LiveCoverage sessionsync.LiveCoverage
+
+ // guard keeps the sweep from rotating its own output out of the log; CollectOnce sets it.
+ guard *writer.RetentionGuard
+}
+
+type SummaryResult struct {
+ Sessions int `json:"sessions"`
+ SessionsChanged int `json:"sessions_changed"`
+ EventsEmitted int `json:"events_emitted"`
+ Errors int `json:"errors"`
+ MalformedLines int `json:"malformed_lines"`
+ // EventsSuppressedLive counts events the sweep mapped but did not emit because live hook
+ // coverage made them duplicates (see CollectOptions.LiveCoverage).
+ EventsSuppressedLive int `json:"events_suppressed_live"`
+ sessionsync.Retention
+}
+
+func CollectOnce(opts CollectOptions) (summary SummaryResult, err error) {
+ if opts.Print && !opts.Write {
+ opts.StatePath = ""
+ }
+ store := NewStore(opts.BrainDir)
+ refs, listErr := store.List()
+ if listErr != nil && len(refs) == 0 {
+ return summary, listErr
+ }
+ refs = sessionwindow.Recent(refs, opts.Since, func(r SessionRef) int64 { return r.ModTimeUnixMS })
+ summary.Sessions = len(refs)
+ if len(refs) == 0 {
+ return summary, listErr
+ }
+ state, err := LoadState(opts.StatePath)
+ if err != nil {
+ return summary, err
+ }
+ defer func() {
+ if saveErr := state.Save(opts.StatePath); saveErr != nil && err == nil {
+ err = fmt.Errorf("save Antigravity CLI session collector state: %w", saveErr)
+ }
+ }()
+
+ var errs []error
+ if listErr != nil {
+ summary.Errors++
+ errs = append(errs, listErr)
+ }
+ opts.guard = sessionsync.NewRetentionGuard(opts.Print, opts.Write)
+ var stopErr error
+ for _, ref := range refs {
+ changed, collectErr := collectSession(store, ref, state, opts, &summary)
+ if sessionsync.Stopped(collectErr) {
+ // Not a failed conversation: this one and the rest are left for a later sync, with
+ // cursors that have not moved past anything that was not written.
+ if changed {
+ summary.SessionsChanged++
+ }
+ stopErr = collectErr
+ errs = append(errs, collectErr)
+ break
+ }
+ if collectErr != nil {
+ summary.Errors++
+ errs = append(errs, fmt.Errorf("Antigravity CLI conversation %s: %w", ref.ID, collectErr))
+ continue
+ }
+ if changed {
+ summary.SessionsChanged++
+ }
+ }
+ if rotatedOut := summary.Finish(opts.sink(), stopErr); rotatedOut != nil {
+ errs = append(errs, rotatedOut)
+ }
+ if len(errs) > 0 {
+ return summary, errors.Join(errs...)
+ }
+ return summary, nil
+}
+
+func collectSession(store *Store, ref SessionRef, state *State, opts CollectOptions, summary *SummaryResult) (bool, error) {
+ cursor := state.cursor(ref.ID)
+ if cursor.UpdatedAtMS >= ref.ModTimeUnixMS && cursor.Events > 0 {
+ return false, nil
+ }
+ data, stats, err := store.Read(ref)
+ summary.MalformedLines += stats.Malformed
+ if err != nil {
+ return false, err
+ }
+ // A transcript that came back shorter than the cursor was rewritten, not appended to, and every
+ // line of the new one would sit at or below the cursor and be skipped forever. Reset the
+ // position so the rewritten content is read; Started is left alone, so session.started is not
+ // written twice. The comparison is against the lines the file held, not the steps that parsed,
+ // so one malformed line is not read as a rewrite; and a file that yielded no lines at all --
+ // absent, or truncated to nothing for a moment -- never resets a good cursor.
+ minLine := cursor.Line
+ if data.Lines > 0 && data.Lines < cursor.Line {
+ minLine = 0
+ cursor.Line = 0
+ }
+ mapped := MapSession(data, MapOptions{MinLine: minLine, SkipStarted: cursor.Started})
+ if len(mapped) == 0 {
+ cursor.UpdatedAtMS = ref.ModTimeUnixMS
+ return false, nil
+ }
+ // written is how far through mapped the sweep got: an event suppressed as a live duplicate is
+ // passed over exactly as if it had been written, so the cursor moves past it.
+ written, recordedPromptLine := 0, 0
+ for _, item := range mapped {
+ if liveDuplicate(item, ref.ID, opts.LiveCoverage, &recordedPromptLine) {
+ written++
+ summary.EventsSuppressedLive++
+ continue
+ }
+ if err := opts.sink().Emit(item.Event); err != nil {
+ commit(cursor, mapped, written)
+ return true, err
+ }
+ written++
+ summary.EventsEmitted++
+ }
+ commit(cursor, mapped, written)
+ cursor.UpdatedAtMS = ref.ModTimeUnixMS
+ return true, nil
+}
+
+// liveDuplicate reports whether the live hooks already recorded item. Prompts are matched by
+// content hash, not by time: hooks written by Beacon v1.3.60 record only a conversation's first
+// prompt, and a PreInvocation hook that failed records none of its turn, so a prompt the hooks never
+// saw is backfilled even in a covered conversation. A handoff link goes with the prompt it was read
+// from, since the hook path records the two together; recordedPromptLine carries the line of the
+// last prompt found recorded. Everything else is sessionsync.LiveCoverage.Suppresses.
+func liveDuplicate(item MappedEvent, conversationID string, coverage sessionsync.LiveCoverage, recordedPromptLine *int) bool {
+ switch item.Event.Event.Action {
+ case "prompt.submitted":
+ hash := ""
+ if item.Event.Content != nil {
+ hash = item.Event.Content.Hash
+ }
+ if !coverage.RecordedPrompt(conversationID, hash) {
+ return false
+ }
+ *recordedPromptLine = item.SourceLine
+ return true
+ case "session.handoff":
+ return item.SourceLine > 0 && item.SourceLine == *recordedPromptLine
+ }
+ return coverage.Suppresses(conversationID, item.Event.Event.Action, item.TimestampMS)
+}
+
+// commit advances the cursor over the events that were actually written.
+//
+// One step can produce several events -- a planner response yields reasoning, a message, one event
+// per tool call and its token usage -- so a line counts as collected only once every event it
+// produced has been written. A line with an unwritten event left on it stays behind the cursor, and
+// the next sweep re-emits the whole line, under the same event ids, rather than dropping its tail.
+func commit(cursor *Cursor, mapped []MappedEvent, written int) {
+ blocked := -1
+ for _, item := range mapped[written:] {
+ if item.SourceKind == SourceTranscript && (blocked < 0 || item.SourceLine < blocked) {
+ blocked = item.SourceLine
+ }
+ }
+ for _, item := range mapped[:written] {
+ if item.SourceKind == SourceSession {
+ cursor.Started = true
+ continue
+ }
+ if blocked >= 0 && item.SourceLine >= blocked {
+ continue
+ }
+ if item.SourceLine > cursor.Line {
+ cursor.Line = item.SourceLine
+ }
+ }
+ cursor.Events += written
+}
+
+func (o CollectOptions) sink() sessionsync.Sink {
+ return sessionsync.Sink{Print: o.Print, Out: o.Out, Write: o.Write, Log: writer.Options{Path: o.LogPath, UserMode: o.UserMode, RotateSize: o.RotateBytes, Budget: o.Budget, Guard: o.guard}}
+}
diff --git a/cli/beacon/internal/antigravitysession/collect_test.go b/cli/beacon/internal/antigravitysession/collect_test.go
new file mode 100644
index 00000000..9518f527
--- /dev/null
+++ b/cli/beacon/internal/antigravitysession/collect_test.go
@@ -0,0 +1,767 @@
+package antigravitysession
+
+import (
+ "bufio"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionsync"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionsync/sessionsynctest"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+const fixtureConversation = "11111111-2222-4333-8444-555555555555"
+
+// fixtureSteps is a two-turn conversation shaped like the one agy 1.5.3 commits: a prompt wrapped
+// in USER_REQUEST/ADDITIONAL_METADATA/USER_SETTINGS_CHANGE, a planner response with reasoning and a
+// run_command call, the call's GENERIC result, the reply, then a resumed turn with a system notice
+// before its reply.
+var fixtureSteps = []string{
+ `{"step_index":0,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-05-01T10:00:00Z","content":"<USER_REQUEST>\nRun: cat notes.txt\n</USER_REQUEST>\n<ADDITIONAL_METADATA>\nThe current local time is: 2026-05-01T06:00:00-04:00.\n</ADDITIONAL_METADATA>\n<USER_SETTINGS_CHANGE>\nThe user changed setting ` + "`Model Selection`" + `.\n</USER_SETTINGS_CHANGE>"}`,
+ `{"step_index":1,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-05-01T10:00:01Z","input_tokens":5000,"cache_read_tokens":1200,"output_tokens":150,"thinking":"Run the command.","tool_calls":[{"name":"run_command","args":{"CommandLine":"cat notes.txt","Cwd":"/work/probe","WaitMsBeforeAsync":5000}}]}`,
+ `{"step_index":2,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-05-01T10:00:03Z","content":"Created At: 2026-05-01T06:00:03-04:00\nCompleted At: 2026-05-01T06:00:04-04:00\nCommand exited with code 0.\n\nCommand output:\nhello\r\n"}`,
+ `{"step_index":3,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-05-01T10:00:04Z","input_tokens":5300,"cache_read_tokens":0,"output_tokens":20,"content":"hello"}`,
+ `{"step_index":4,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-05-01T10:05:00Z","content":"<USER_REQUEST>\nNow reply with: done\n</USER_REQUEST>\n<ADDITIONAL_METADATA>\nThe current local time is: 2026-05-01T06:05:00-04:00.\n</ADDITIONAL_METADATA>"}`,
+ `{"step_index":5,"source":"SYSTEM","type":"SYSTEM_MESSAGE","status":"DONE","created_at":"2026-05-01T10:05:00Z","content":"<SYSTEM_MESSAGE>notice</SYSTEM_MESSAGE>"}`,
+ `{"step_index":6,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-05-01T10:05:01Z","input_tokens":6000,"cache_read_tokens":0,"output_tokens":5,"content":"done"}`,
+}
+
+// fixtureEvents is what fixtureSteps maps to, in order.
+var fixtureEvents = []string{
+ "session.started",
+ "prompt.submitted",
+ "agent.reasoning", "tool.invoked", "token.usage",
+ "command.executed",
+ "agent.message", "token.usage",
+ "prompt.submitted",
+ "agent.message", "token.usage",
+}
+
+type fixture struct {
+ brainDir string
+ statePath string
+ logPath string
+}
+
+func newFixture(t *testing.T) fixture {
+ t.Helper()
+ root := t.TempDir()
+ return fixture{
+ brainDir: filepath.Join(root, "antigravity-cli", "brain"),
+ statePath: filepath.Join(root, "state", "antigravity.json"),
+ logPath: filepath.Join(root, "logs", "runtime.jsonl"),
+ }
+}
+
+func (f fixture) options() CollectOptions {
+ return CollectOptions{BrainDir: f.brainDir, StatePath: f.statePath, LogPath: f.logPath, Write: true, UserMode: true}
+}
+
+func (f fixture) transcript(id, name string) string {
+ return filepath.Join(f.brainDir, id, ".system_generated", "logs", name)
+}
+
+// writeConversation writes a conversation's transcript under the given file name.
+func (f fixture) writeConversation(t *testing.T, id, name string, steps []string) string {
+ t.Helper()
+ path := f.transcript(id, name)
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ writeFile(t, path, strings.Join(steps, "\n")+"\n")
+ return path
+}
+
+// writeSummaries creates conversation_summaries.db beside the brain directory with the columns
+// Beacon reads, one row per id, each with the given workspace URIs.
+func (f fixture) writeSummaries(t *testing.T, rows map[string]string) {
+ t.Helper()
+ path := filepath.Join(filepath.Dir(f.brainDir), "conversation_summaries.db")
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ if _, err := db.Exec("CREATE TABLE `conversation_summaries` (`conversation_id` text,`title` text NOT NULL DEFAULT \"\",`workspace_uris` text NOT NULL,`project_id` text NOT NULL DEFAULT \"\",`parent_conversation_id` text NOT NULL DEFAULT \"\",`nesting_depth` integer NOT NULL DEFAULT 0,`blob` blob)"); err != nil {
+ t.Fatal(err)
+ }
+ for id, uris := range rows {
+ if _, err := db.Exec("INSERT INTO conversation_summaries (conversation_id, title, workspace_uris, project_id, parent_conversation_id, nesting_depth, blob) VALUES (?, ?, ?, ?, ?, ?, ?)",
+ id, "Probe", uris, "default-cli-project", "99999999-0000-4000-8000-000000000000", 1, []byte{0x0a, 0x01}); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func TestStoreListsAndMapsAConversation(t *testing.T) {
+ f := newFixture(t)
+ f.writeConversation(t, fixtureConversation, fullTranscriptName, fixtureSteps)
+ f.writeSummaries(t, map[string]string{fixtureConversation: `["file:///work/agy%20probe","file:///work/other"]`})
+
+ refs, err := NewStore(f.brainDir).List()
+ if err != nil || len(refs) != 1 {
+ t.Fatalf("List() = %d refs, %v", len(refs), err)
+ }
+ ref := refs[0]
+ if ref.ID != fixtureConversation || !ref.Full || ref.Summary == nil || ref.Summary.WorkingDirectory != "/work/agy probe" {
+ t.Fatalf("ref = %+v summary=%+v", ref, ref.Summary)
+ }
+ data, stats, err := NewStore(f.brainDir).Read(ref)
+ if err != nil || stats.Malformed != 0 {
+ t.Fatalf("Read() = %v, %d malformed", err, stats.Malformed)
+ }
+ mapped := MapSession(data, MapOptions{})
+ if got := actionsOf(mapped); strings.Join(got, ",") != strings.Join(fixtureEvents, ",") {
+ t.Fatalf("actions = %v\nwant %v", got, fixtureEvents)
+ }
+ for _, item := range mapped {
+ ev := item.Event
+ if ev.Harness.Name != "antigravity_cli" || ev.Harness.CollectionMethod != "poll" || ev.Event.Fidelity != "observed" {
+ t.Fatalf("%s provenance = %+v %+v", ev.Event.Action, ev.Harness, ev.Event)
+ }
+ if ev.Session == nil || ev.Session.ID != fixtureConversation || ev.Session.WorkingDirectory != "/work/agy probe" {
+ t.Fatalf("%s session = %+v", ev.Event.Action, ev.Session)
+ }
+ if ev.Event.ID == "" {
+ t.Fatalf("%s has no id", ev.Event.Action)
+ }
+ }
+ // The harness name the collector writes is the one the hooks' platform name normalizes to.
+ if asymptoteobserve.NormalizeHarnessName("antigravity") != Harness {
+ t.Fatalf("NormalizeHarnessName(antigravity) = %q, want %q", asymptoteobserve.NormalizeHarnessName("antigravity"), Harness)
+ }
+
+ prompts := byAction(mapped, "prompt.submitted")
+ if prompts[0].Prompt.Text != "Run: cat notes.txt" || prompts[1].Prompt.Text != "Now reply with: done" {
+ t.Fatalf("prompts = %q, %q", prompts[0].Prompt.Text, prompts[1].Prompt.Text)
+ }
+ if prompts[0].Timestamp != "2026-05-01T10:00:00.000000000Z" {
+ t.Fatalf("prompt timestamp = %q, want the step's created_at", prompts[0].Timestamp)
+ }
+
+ invoked := byAction(mapped, "tool.invoked")[0]
+ if invoked.Tool.Name != "run_command" || invoked.Command == nil || invoked.Command.Command != "cat notes.txt" ||
+ callArgs(invoked)["Cwd"] != "/work/probe" {
+ t.Fatalf("tool.invoked = %+v %+v", invoked.Tool, invoked.GenAI.Tool)
+ }
+ command := byAction(mapped, "command.executed")[0]
+ if command.Command == nil || command.Command.Command != "cat notes.txt" || command.Command.Output != "hello" ||
+ command.Command.ExitCode == nil || *command.Command.ExitCode != 0 {
+ t.Fatalf("command = %+v", command.Command)
+ }
+ if command.Timestamp != "2026-05-01T10:00:03.000000000Z" {
+ t.Fatalf("command timestamp = %q, want the GENERIC step's created_at", command.Timestamp)
+ }
+
+ usage := byAction(mapped, "token.usage")[0].GenAI.Usage
+ if usage == nil || *usage.InputTokens != 3800 || *usage.CacheRead.InputTokens != 1200 || *usage.OutputTokens != 150 {
+ t.Fatalf("usage = %+v, want uncached input 3800, cache read 1200, output 150", usage)
+ }
+ reasoning := byAction(mapped, "agent.reasoning")[0]
+ if reasoning.Content == nil || reasoning.GenAI == nil || reasoning.GenAI.Output == nil {
+ t.Fatalf("reasoning = %+v", reasoning)
+ }
+ if messages := byAction(mapped, "agent.message"); messageContent(messages[0]) != "hello" || messageContent(messages[1]) != "done" {
+ t.Fatalf("messages = %+v", messages)
+ }
+
+ started := byAction(mapped, "session.started")[0]
+ detail, _ := started.Raw["antigravity"].(map[string]interface{})
+ if detail["title"] != "Probe" || detail["project_id"] != "default-cli-project" ||
+ detail["parent_conversation_id"] != "99999999-0000-4000-8000-000000000000" || detail["nesting_depth"] != int64(1) {
+ t.Fatalf("session.started raw = %v", started.Raw)
+ }
+ for _, action := range []string{"session.ended", "approval.requested", "approval.allowed"} {
+ if len(byAction(mapped, action)) != 0 {
+ t.Fatalf("%s was invented", action)
+ }
+ }
+}
+
+// The full transcript is preferred, and transcript.jsonl -- whose argument values are JSON-encoded
+// strings -- is read only without it. The two hold the same steps, so they map to the same events
+// under the same ids.
+func TestTheShortTranscriptIsReadWhenTheFullOneIsAbsentAndMapsTheSame(t *testing.T) {
+ full := newFixture(t)
+ full.writeConversation(t, fixtureConversation, fullTranscriptName, fixtureSteps)
+ short := newFixture(t)
+ encoded := append([]string{}, fixtureSteps...)
+ encoded[1] = `{"step_index":1,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-05-01T10:00:01Z","input_tokens":5000,"cache_read_tokens":1200,"output_tokens":150,"thinking":"Run the command.","tool_calls":[{"name":"run_command","args":{"CommandLine":"\"cat notes.txt\"","Cwd":"\"/work/probe\"","WaitMsBeforeAsync":"5000"}}]}`
+ short.writeConversation(t, fixtureConversation, transcriptName, encoded)
+
+ fullEvents := mapAll(t, full.brainDir)
+ shortRefs, _ := NewStore(short.brainDir).List()
+ if len(shortRefs) != 1 || shortRefs[0].Full {
+ t.Fatalf("refs = %+v, want the short transcript", shortRefs)
+ }
+ shortEvents := mapAll(t, short.brainDir)
+ if len(fullEvents) != len(shortEvents) {
+ t.Fatalf("%d events from the full transcript, %d from the short one", len(fullEvents), len(shortEvents))
+ }
+ for i := range fullEvents {
+ if fullEvents[i].Event.Event.ID != shortEvents[i].Event.Event.ID {
+ t.Fatalf("event %d (%s) has a different id read from each transcript", i, fullEvents[i].Event.Event.Action)
+ }
+ }
+ invoked := byAction(shortEvents, "tool.invoked")[0]
+ args := callArgs(invoked)
+ if invoked.Command.Command != "cat notes.txt" || args["Cwd"] != "/work/probe" || args["WaitMsBeforeAsync"] != float64(5000) {
+ t.Fatalf("decoded arguments = %v, command %q", args, invoked.Command.Command)
+ }
+}
+
+func callArgs(ev schema.Event) map[string]interface{} {
+ args, _ := ev.GenAI.Tool.Call.Arguments.(map[string]interface{})
+ return args
+}
+
+// messageContent is the text of an event's first output message part, in the gen_ai.output.messages
+// shape the dashboard and trace readers expect.
+func messageContent(ev schema.Event) interface{} {
+ messages, _ := ev.GenAI.Output.Messages.([]interface{})
+ if len(messages) == 0 {
+ return nil
+ }
+ message, _ := messages[0].(map[string]interface{})
+ parts, _ := message["parts"].([]interface{})
+ if len(parts) == 0 {
+ return nil
+ }
+ part, _ := parts[0].(map[string]interface{})
+ return part["content"]
+}
+
+// Without the summaries database, or without the conversation's row in it, there is no working
+// directory to report -- except the one a command names -- and the conversation is still collected.
+func TestAMissingSummaryMeansNoWorkingDirectoryNotAnError(t *testing.T) {
+ f := newFixture(t)
+ f.writeConversation(t, fixtureConversation, fullTranscriptName, fixtureSteps)
+ check := func(label string) {
+ t.Helper()
+ events := mapAll(t, f.brainDir)
+ if len(events) != len(fixtureEvents) {
+ t.Fatalf("%s: %d events, want %d", label, len(events), len(fixtureEvents))
+ }
+ for _, item := range events {
+ want := ""
+ if item.Event.Command != nil {
+ want = "/work/probe"
+ }
+ if item.Event.Session.WorkingDirectory != want {
+ t.Fatalf("%s: %s working directory = %q, want %q", label, item.Event.Event.Action, item.Event.Session.WorkingDirectory, want)
+ }
+ }
+ }
+ check("no database")
+ f.writeSummaries(t, map[string]string{"another-conversation": `["file:///elsewhere"]`})
+ check("no row")
+}
+
+// Antigravity on Windows records workspaces as file:///C:/... URIs, and a share as file://host/...;
+// the working directory is the drive or UNC path, not the URI's path with its leading slash.
+func TestWorkspaceURIsBecomeLocalPaths(t *testing.T) {
+ for raw, want := range map[string]string{
+ `["file:///C:/Users/dev/proj"]`: filepath.FromSlash("C:/Users/dev/proj"),
+ `["file://server/share/proj"]`: filepath.FromSlash("//server/share/proj"),
+ `["file:///tmp/agy%20probe", "file:///other"]`: filepath.FromSlash("/tmp/agy probe"),
+ `["https://example.com/repo"]`: "",
+ `not json`: "",
+ } {
+ if got := firstWorkspacePath(raw); got != want {
+ t.Errorf("firstWorkspacePath(%s) = %q, want %q", raw, got, want)
+ }
+ }
+}
+
+// A summaries database that exists but cannot be read costs the working directories, not the
+// conversations: the sweep collects every transcript and reports the database error.
+func TestAnUnreadableSummariesDatabaseStillCollectsTheTranscripts(t *testing.T) {
+ f := newFixture(t)
+ f.writeConversation(t, fixtureConversation, fullTranscriptName, fixtureSteps)
+ writeFile(t, filepath.Join(filepath.Dir(f.brainDir), summariesDBName), "this is not a SQLite database, but it is long enough to have a header")
+
+ summary, err := CollectOnce(f.options())
+ if err == nil || summary.Errors != 1 {
+ t.Fatalf("CollectOnce = %+v, %v; want the database error reported", summary, err)
+ }
+ if summary.EventsEmitted != len(fixtureEvents) {
+ t.Fatalf("events emitted = %d, want every transcript event (%d)", summary.EventsEmitted, len(fixtureEvents))
+ }
+}
+
+// A transcript is appended to while the conversation runs and again when it is resumed. Only the
+// steps that were added may be emitted; a planner line written before its GENERIC result is
+// completed by the result alone on the next sweep.
+func TestCollectOnceEmitsOnlyNewStepsWhenTheConversationGrows(t *testing.T) {
+ f := newFixture(t)
+ path := f.writeConversation(t, fixtureConversation, fullTranscriptName, fixtureSteps[:2])
+
+ first, err := CollectOnce(f.options())
+ if err != nil {
+ t.Fatalf("first CollectOnce: %v", err)
+ }
+ if got := logActions(t, f.logPath); strings.Join(got, ",") != strings.Join(fixtureEvents[:5], ",") {
+ t.Fatalf("first sweep wrote %v", got)
+ }
+
+ for _, step := range fixtureSteps[2:] {
+ appendLine(t, path, step)
+ }
+ touchNewer(t, path)
+ second, err := CollectOnce(f.options())
+ if err != nil {
+ t.Fatalf("second CollectOnce: %v", err)
+ }
+ if first.EventsEmitted+second.EventsEmitted != len(fixtureEvents) {
+ t.Fatalf("sweeps emitted %d + %d events, want %d in all", first.EventsEmitted, second.EventsEmitted, len(fixtureEvents))
+ }
+ if got := logActions(t, f.logPath); strings.Join(got, ",") != strings.Join(fixtureEvents, ",") {
+ t.Fatalf("log holds %v\nwant %v", got, fixtureEvents)
+ }
+
+ touchNewer(t, path)
+ third, err := CollectOnce(f.options())
+ if err != nil || third.EventsEmitted != 0 {
+ t.Fatalf("third sweep emitted %d events (%v), want none", third.EventsEmitted, err)
+ }
+}
+
+// A sweep can catch the tail of a live transcript mid-write. The torn line counts as malformed,
+// and once it lands it is collected rather than skipped.
+func TestCollectOnceCollectsALineThatWasTornOnTheFirstSweep(t *testing.T) {
+ f := newFixture(t)
+ path := f.writeConversation(t, fixtureConversation, fullTranscriptName, fixtureSteps[:4])
+ appendLine(t, path, `{"step_index":4,"source":"USER_EXPLICIT","type":"USER_IN`)
+
+ first, err := CollectOnce(f.options())
+ if err != nil || first.MalformedLines != 1 {
+ t.Fatalf("first sweep: %v, %d malformed", err, first.MalformedLines)
+ }
+ rewriteLine(t, path, 5, fixtureSteps[4])
+ for _, step := range fixtureSteps[5:] {
+ appendLine(t, path, step)
+ }
+ touchNewer(t, path)
+ if _, err := CollectOnce(f.options()); err != nil {
+ t.Fatal(err)
+ }
+ if got := logActions(t, f.logPath); strings.Join(got, ",") != strings.Join(fixtureEvents, ",") {
+ t.Fatalf("log holds %v\nwant %v", got, fixtureEvents)
+ }
+}
+
+// A transcript that comes back shorter than the cursor was rewritten, and its content is read
+// again rather than skipped forever; session.started is not written a second time.
+func TestARewrittenShorterTranscriptIsNotSkipped(t *testing.T) {
+ f := newFixture(t)
+ path := f.writeConversation(t, fixtureConversation, fullTranscriptName, fixtureSteps)
+ if _, err := CollectOnce(f.options()); err != nil {
+ t.Fatal(err)
+ }
+ writeFile(t, path, strings.Join([]string{
+ `{"step_index":0,"source":"USER_EXPLICIT","type":"USER_INPUT","created_at":"2026-05-02T09:00:00Z","content":"<USER_REQUEST>\nrewritten\n</USER_REQUEST>"}`,
+ `{"step_index":1,"source":"MODEL","type":"PLANNER_RESPONSE","created_at":"2026-05-02T09:00:01Z","content":"rewritten reply"}`,
+ }, "\n")+"\n")
+ touchNewer(t, path)
+
+ second, err := CollectOnce(f.options())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if second.EventsEmitted != 2 {
+ t.Fatalf("sweep after the rewrite emitted %d events, want the rewritten prompt and reply", second.EventsEmitted)
+ }
+ actions := countActions(logActions(t, f.logPath))
+ if actions["session.started"] != 1 {
+ t.Fatalf("session.started written %d times, want 1", actions["session.started"])
+ }
+ touchNewer(t, path)
+ if third, err := CollectOnce(f.options()); err != nil || third.EventsEmitted != 0 {
+ t.Fatalf("third sweep emitted %d events (%v), want none", third.EventsEmitted, err)
+ }
+}
+
+// One malformed line in the middle leaves the step count below the line cursor; that is not a
+// rewrite, and the conversation must not be appended to the log again.
+func TestAMalformedLineIsNotMistakenForARewrite(t *testing.T) {
+ f := newFixture(t)
+ steps := append(append(append([]string{}, fixtureSteps[:2]...), `{"step_index":`), fixtureSteps[2:]...)
+ path := f.writeConversation(t, fixtureConversation, fullTranscriptName, steps)
+ first, err := CollectOnce(f.options())
+ if err != nil || first.MalformedLines != 1 {
+ t.Fatalf("first sweep: %v, %d malformed", err, first.MalformedLines)
+ }
+ appendLine(t, path, `{"step_index":7,"source":"USER_EXPLICIT","type":"USER_INPUT","created_at":"2026-05-01T10:10:00Z","content":"<USER_REQUEST>\nthird\n</USER_REQUEST>"}`)
+ touchNewer(t, path)
+ second, err := CollectOnce(f.options())
+ if err != nil || second.EventsEmitted != 1 {
+ t.Fatalf("second sweep emitted %d events (%v), want only the appended prompt", second.EventsEmitted, err)
+ }
+}
+
+// Since keeps the sweep to recently modified conversations and leaves the cursors of the rest
+// untouched, so a later sync still collects them.
+func TestSinceLeavesOlderConversationsForALaterSync(t *testing.T) {
+ f := newFixture(t)
+ oldPath := f.writeConversation(t, "old-conversation", fullTranscriptName, fixtureSteps)
+ f.writeConversation(t, fixtureConversation, fullTranscriptName, fixtureSteps)
+ past := time.Now().Add(-90 * 24 * time.Hour)
+ if err := os.Chtimes(oldPath, past, past); err != nil {
+ t.Fatal(err)
+ }
+
+ opts := f.options()
+ opts.Since = time.Now().Add(-30 * 24 * time.Hour)
+ summary, err := CollectOnce(opts)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if summary.Sessions != 1 || summary.EventsEmitted != len(fixtureEvents) {
+ t.Fatalf("windowed sweep = %+v, want only the recent conversation", summary)
+ }
+ state, err := LoadState(f.statePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := state.Sessions["old-conversation"]; ok {
+ t.Fatal("the windowed sweep moved the cursor of a conversation it did not read")
+ }
+
+ summary, err = CollectOnce(f.options())
+ if err != nil || summary.EventsEmitted != len(fixtureEvents) {
+ t.Fatalf("unwindowed sweep emitted %d events (%v), want the older conversation", summary.EventsEmitted, err)
+ }
+}
+
+// A spent budget stops the sweep with the cursor past only the lines whose events were all
+// written; the next sweep writes the rest, and nothing twice.
+func TestABudgetStopsTheSweepWithTheCursorPastOnlyWhatWasWritten(t *testing.T) {
+ f := newFixture(t)
+ f.writeConversation(t, fixtureConversation, fullTranscriptName, fixtureSteps)
+
+ probe := newFixture(t)
+ probe.writeConversation(t, fixtureConversation, fullTranscriptName, fixtureSteps[:1])
+ probeBudget := writer.NewBudget(1 << 30)
+ probeOpts := probe.options()
+ probeOpts.Budget = probeBudget
+ if _, err := CollectOnce(probeOpts); err != nil {
+ t.Fatal(err)
+ }
+
+ // Room for session.started and the first prompt, and not for the planner response's events.
+ opts := f.options()
+ opts.Budget = writer.NewBudget(probeBudget.Used() + 64)
+ summary, err := CollectOnce(opts)
+ if !errors.Is(err, writer.ErrBudgetSpent) {
+ t.Fatalf("err = %v, want ErrBudgetSpent", err)
+ }
+ if summary.Errors != 0 || summary.EventsEmitted == 0 || summary.EventsEmitted >= len(fixtureEvents) {
+ t.Fatalf("budgeted sweep = %+v", summary)
+ }
+
+ rest, err := CollectOnce(f.options())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if summary.EventsEmitted+rest.EventsEmitted < len(fixtureEvents) {
+ t.Fatalf("the two sweeps wrote %d + %d events, want at least %d", summary.EventsEmitted, rest.EventsEmitted, len(fixtureEvents))
+ }
+ ids := map[string]int{}
+ for _, ev := range readLog(t, f.logPath) {
+ ids[ev.Event.ID]++
+ }
+ if len(ids) != len(fixtureEvents) {
+ t.Fatalf("log holds %d distinct events, want %d", len(ids), len(fixtureEvents))
+ }
+}
+
+// A conversation the hooks covered from its start, whose hooks recorded only its first prompt --
+// what Beacon v1.3.60's hooks do, having no PreInvocation handler. The sweep suppresses the session
+// start, the recorded prompt and the tool events, keeps what hooks cannot carry (agent messages,
+// reasoning, token usage), and backfills the second prompt the hooks never saw. The cursor moves
+// past the suppressed events, so they are not retried.
+func TestLiveCoverageBackfillsThePromptsTheHooksDidNotRecord(t *testing.T) {
+ f := newFixture(t)
+ f.writeConversation(t, fixtureConversation, fullTranscriptName, fixtureSteps)
+ opts := f.options()
+ opts.LiveCoverage = sessionsync.LiveCoverage{
+ From: map[string]time.Time{fixtureConversation: time.Date(2026, 5, 1, 10, 0, 0, 0, time.UTC)},
+ Prompts: map[string]map[string]bool{fixtureConversation: {asymptoteobserve.RetainedContent("Run: cat notes.txt", 0).Hash: true}},
+ }
+
+ summary, err := CollectOnce(opts)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []string{
+ // session.started, the first prompt, tool.invoked and command.executed are the hooks'.
+ "agent.reasoning", "token.usage",
+ "agent.message", "token.usage",
+ "prompt.submitted",
+ "agent.message", "token.usage",
+ }
+ if got := logActions(t, f.logPath); strings.Join(got, ",") != strings.Join(want, ",") {
+ t.Fatalf("log holds %v\nwant %v", got, want)
+ }
+ if summary.EventsEmitted != len(want) || summary.EventsSuppressedLive != 4 {
+ t.Fatalf("summary = %+v, want %d emitted and 4 suppressed", summary, len(want))
+ }
+
+ touchNewer(t, f.transcript(fixtureConversation, fullTranscriptName))
+ again, err := CollectOnce(opts)
+ if err != nil || again.EventsEmitted != 0 || again.EventsSuppressedLive != 0 {
+ t.Fatalf("second sweep = %+v (%v), want nothing re-read", again, err)
+ }
+
+ // Coverage for another conversation changes nothing here.
+ other := newFixture(t)
+ other.writeConversation(t, fixtureConversation, fullTranscriptName, fixtureSteps)
+ otherOpts := other.options()
+ otherOpts.LiveCoverage = sessionsync.LiveCoverage{From: map[string]time.Time{"another-conversation": time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC)}}
+ if s, err := CollectOnce(otherOpts); err != nil || s.EventsEmitted != len(fixtureEvents) || s.EventsSuppressedLive != 0 {
+ t.Fatalf("uncovered conversation = %+v (%v)", s, err)
+ }
+}
+
+// `beacon endpoint antigravity sync --print` maps and prints every event without writing or
+// advancing a cursor, so a real sync afterwards writes the same events.
+func TestPrintShowsEveryEventAndLeavesTheConversationForSync(t *testing.T) {
+ f := newFixture(t)
+ f.writeConversation(t, fixtureConversation, fullTranscriptName, fixtureSteps)
+ var printed strings.Builder
+ summary, err := CollectOnce(CollectOptions{BrainDir: f.brainDir, Print: true, Out: &printed})
+ if err != nil {
+ t.Fatal(err)
+ }
+ lines := strings.Split(strings.TrimSpace(printed.String()), "\n")
+ if summary.EventsEmitted != len(fixtureEvents) || len(lines) != len(fixtureEvents) {
+ t.Fatalf("printed %d lines for %d events", len(lines), summary.EventsEmitted)
+ }
+ real, err := CollectOnce(f.options())
+ if err != nil || real.EventsEmitted != len(fixtureEvents) {
+ t.Fatalf("sync after --print wrote %d events (%v), want %d", real.EventsEmitted, err, len(fixtureEvents))
+ }
+}
+
+func TestMapSessionRecordsAHandoffLink(t *testing.T) {
+ marker := asymptoteobserve.HandoffMarker("claude_code", "src-1")
+ content, _ := json.Marshal("<USER_REQUEST>\nContinue the work.\n\n" + marker + "\n</USER_REQUEST>")
+ f := newFixture(t)
+ f.writeConversation(t, fixtureConversation, fullTranscriptName, []string{
+ `{"step_index":0,"source":"USER_EXPLICIT","type":"USER_INPUT","created_at":"2026-05-01T10:00:00Z","content":` + string(content) + `}`,
+ })
+ if _, err := CollectOnce(f.options()); err != nil {
+ t.Fatal(err)
+ }
+ var links []schema.Event
+ for _, ev := range readLog(t, f.logPath) {
+ if ev.Event.Action == "session.handoff" {
+ links = append(links, ev)
+ }
+ }
+ if len(links) != 1 || links[0].Handoff == nil || links[0].Handoff.SourceHarness != "claude_code" || links[0].Handoff.SourceSessionID != "src-1" {
+ t.Fatalf("links = %+v", links)
+ }
+ if links[0].Prompt != nil || links[0].Session.ID != fixtureConversation {
+ t.Fatalf("link = %+v", links[0])
+ }
+
+ // Collected again from scratch, the link carries the same id.
+ if err := os.Remove(f.statePath); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := CollectOnce(f.options()); err != nil {
+ t.Fatal(err)
+ }
+ var ids []string
+ for _, ev := range readLog(t, f.logPath) {
+ if ev.Event.Action == "session.handoff" {
+ ids = append(ids, ev.Event.ID)
+ }
+ }
+ if len(ids) != 2 || ids[0] != ids[1] {
+ t.Fatalf("link ids = %q, want the same id both times", ids)
+ }
+}
+
+// Results pair with calls by order: two calls in one planner response take the next two GENERIC
+// steps, and a call whose result never came does not take the next turn's step.
+func TestGenericStepsPairWithCallsInOrder(t *testing.T) {
+ data := SessionData{Ref: SessionRef{ID: "c"}, Steps: []Step{
+ {Type: stepPlannerResponse, Line: 1, ToolCalls: []ToolCall{
+ {Name: "view_file", Arguments: map[string]interface{}{"AbsolutePath": "/w/a.go"}},
+ {Name: "write_to_file", Arguments: map[string]interface{}{"TargetFile": "/w/b.go"}},
+ }},
+ {Type: stepGeneric, Line: 2, Content: "package a"},
+ {Type: stepGeneric, Line: 3, Content: "Created file"},
+ {Type: stepPlannerResponse, Line: 4, ToolCalls: []ToolCall{{Name: "replace_file_content", Arguments: map[string]interface{}{"TargetFile": "/w/c.go"}}}},
+ {Type: "USER_INPUT", Line: 5, Content: "<USER_REQUEST>next</USER_REQUEST>"},
+ {Type: stepGeneric, Line: 6, Content: "unpaired"},
+ {Type: stepPlannerResponse, Line: 7, ToolCalls: []ToolCall{{Name: "mcp_github_search", Arguments: map[string]interface{}{"q": "x"}}}},
+ {Type: stepGeneric, Line: 8, Content: "results"},
+ }}
+ var results []schema.Event
+ for _, item := range MapSession(data, MapOptions{SkipStarted: true}) {
+ if item.Event.Event.Action != "tool.invoked" && item.Event.Event.Action != "prompt.submitted" {
+ results = append(results, item.Event)
+ }
+ }
+ if len(results) != 3 {
+ t.Fatalf("results = %d, want 3: %+v", len(results), results)
+ }
+ read, write, mcp := results[0], results[1], results[2]
+ if read.Event.Action != "file.read" || read.File.Path != "/w/a.go" || read.File.Operation != "read" || read.GenAI.Tool.Call.Result != "package a" {
+ t.Fatalf("read = %+v %+v", read.Event, read.File)
+ }
+ if write.Event.Action != "file.modified" || write.File.Path != "/w/b.go" || write.File.Operation != "write" {
+ t.Fatalf("write = %+v %+v", write.Event, write.File)
+ }
+ if mcp.Event.Action != "mcp.tool_invoked" || mcp.MCP == nil || mcp.MCP.Tool != "mcp_github_search" {
+ t.Fatalf("mcp = %+v", mcp)
+ }
+}
+
+func TestCollectOnceKeepsWhatItWritesAcrossTheRotationWindow(t *testing.T) {
+ f := newFixture(t)
+ for i := range 60 {
+ f.writeConversation(t, fmt.Sprintf("conversation-%03d", i), fullTranscriptName, fixtureSteps)
+ }
+ opts := CollectOptions{BrainDir: f.brainDir, Write: true, UserMode: true}
+ sessionsynctest.CheckSweepKeepsItsOutput(t, func(statePath, logPath string, rotateBytes int64) (sessionsynctest.Result, error) {
+ opts.StatePath, opts.LogPath, opts.RotateBytes = statePath, logPath, rotateBytes
+ s, err := CollectOnce(opts)
+ return sessionsynctest.Result{EventsEmitted: s.EventsEmitted, Errors: s.Errors, Retention: s.Retention}, err
+ })
+}
+
+func mapAll(t *testing.T, brainDir string) []MappedEvent {
+ t.Helper()
+ store := NewStore(brainDir)
+ refs, err := store.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []MappedEvent
+ for _, ref := range refs {
+ data, _, err := store.Read(ref)
+ if err != nil {
+ t.Fatal(err)
+ }
+ out = append(out, MapSession(data, MapOptions{})...)
+ }
+ return out
+}
+
+func actionsOf(mapped []MappedEvent) []string {
+ out := make([]string, 0, len(mapped))
+ for _, item := range mapped {
+ out = append(out, item.Event.Event.Action)
+ }
+ return out
+}
+
+func byAction(mapped []MappedEvent, action string) []schema.Event {
+ var out []schema.Event
+ for _, item := range mapped {
+ if item.Event.Event.Action == action {
+ out = append(out, item.Event)
+ }
+ }
+ return out
+}
+
+func readLog(t *testing.T, path string) []schema.Event {
+ t.Helper()
+ f, err := os.Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ var out []schema.Event
+ scanner := bufio.NewScanner(f)
+ scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
+ for scanner.Scan() {
+ var ev schema.Event
+ if err := json.Unmarshal(scanner.Bytes(), &ev); err != nil {
+ t.Fatalf("unmarshal runtime line: %v", err)
+ }
+ out = append(out, ev)
+ }
+ if err := scanner.Err(); err != nil {
+ t.Fatal(err)
+ }
+ return out
+}
+
+func logActions(t *testing.T, path string) []string {
+ t.Helper()
+ var out []string
+ for _, ev := range readLog(t, path) {
+ out = append(out, ev.Event.Action)
+ }
+ return out
+}
+
+func countActions(actions []string) map[string]int {
+ out := map[string]int{}
+ for _, action := range actions {
+ out[action]++
+ }
+ return out
+}
+
+func writeFile(t *testing.T, path, content string) {
+ t.Helper()
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ t.Fatalf("write %s: %v", path, err)
+ }
+}
+
+func appendLine(t *testing.T, path, line string) {
+ t.Helper()
+ f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ if _, err := f.WriteString(line + "\n"); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func rewriteLine(t *testing.T, path string, lineNo int, content string) {
+ t.Helper()
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ lines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")
+ lines[lineNo-1] = content
+ writeFile(t, path, strings.Join(lines, "\n")+"\n")
+}
+
+// touchNewer moves the transcript's modification time forward, so a test that writes twice inside
+// one filesystem timestamp tick is not skipped by the collector's modification-time pre-filter.
+func touchNewer(t *testing.T, path string) {
+ t.Helper()
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ next := info.ModTime().Add(2 * time.Second)
+ if err := os.Chtimes(path, next, next); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/cli/beacon/internal/antigravitysession/mapper.go b/cli/beacon/internal/antigravitysession/mapper.go
new file mode 100644
index 00000000..41044ce7
--- /dev/null
+++ b/cli/beacon/internal/antigravitysession/mapper.go
@@ -0,0 +1,370 @@
+package antigravitysession
+
+import (
+ "crypto/sha1"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// Step types Antigravity writes beyond the user's own input (asymptoteobserve.IsAntigravityUserInput).
+// Anything else is skipped by name, so a type a later agy adds is not mistaken for one Beacon maps.
+const (
+ stepPlannerResponse = "PLANNER_RESPONSE"
+ stepGeneric = "GENERIC"
+)
+
+// MapSession converts one conversation into endpoint events.
+//
+// It always walks the whole transcript, because a GENERIC step is only meaningful next to the
+// planner response before it: Antigravity gives a tool call no id, and its result is the next
+// GENERIC step in order. What opts controls is what gets *emitted* -- everything at or below the
+// cursor is rebuilt for context and dropped -- so a conversation that grew since the last sweep
+// yields only the steps that grew.
+func MapSession(data SessionData, opts MapOptions) []MappedEvent {
+ m := &mapper{data: data, opts: opts}
+ if len(data.Steps) == 0 {
+ return nil
+ }
+ m.emitStart()
+ for _, step := range data.Steps {
+ m.consume(step)
+ }
+ return m.out
+}
+
+type mapper struct {
+ data SessionData
+ opts MapOptions
+ out []MappedEvent
+ // pending are the calls of the latest planner response whose GENERIC results have not been
+ // read yet, in the order Antigravity runs them.
+ pending []ToolCall
+ // step and ordinal number the events mapped from one step, so each is named by where it was
+ // read (see eventID).
+ step string
+ ordinal int
+}
+
+func (m *mapper) consume(step Step) {
+ switch {
+ case asymptoteobserve.IsAntigravityUserInput(step.Source, step.Type):
+ // A new turn: a call the last turn never reported a result for has none coming.
+ m.pending = nil
+ text := asymptoteobserve.AntigravityPrompt(step.Content)
+ if text == "" {
+ return
+ }
+ ev := m.base(step, "prompt.submitted", "prompt", "Antigravity CLI prompt submitted")
+ ev.Prompt = &schema.PromptInfo{Text: text}
+ ev.GenAI = &schema.GenAIInfo{Input: &schema.GenAIInputInfo{Messages: asymptoteobserve.TextInputMessages(text)}}
+ ev.Content = contentMarker(text)
+ m.append(ev, step)
+ if info, ok := asymptoteobserve.ParseHandoffMarker(text); ok {
+ link := m.base(step, "session.handoff", "session", "Session continued from a "+info.SourceHarness+" session")
+ link.Handoff = &info
+ m.append(link, step)
+ }
+ case step.Type == stepPlannerResponse:
+ m.pending = nil
+ if thinking := strings.TrimSpace(step.Thinking); thinking != "" {
+ ev := m.base(step, "agent.reasoning", "agent", "Antigravity CLI agent reasoning")
+ ev.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: asymptoteobserve.ReasoningOutputMessages(step.Thinking)}}
+ ev.Content = contentMarker(step.Thinking)
+ m.append(ev, step)
+ }
+ if strings.TrimSpace(step.Content) != "" {
+ ev := m.base(step, "agent.message", "agent", "Antigravity CLI agent message")
+ ev.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: asymptoteobserve.TextOutputMessages(step.Content)}}
+ ev.Content = contentMarker(step.Content)
+ m.append(ev, step)
+ }
+ for _, call := range step.ToolCalls {
+ m.append(m.toolCallEvent(step, call), step)
+ m.pending = append(m.pending, call)
+ }
+ if usage := usageFor(step); usage != nil {
+ ev := m.base(step, "token.usage", "metric", "Antigravity CLI token usage observed")
+ ev.GenAI = &schema.GenAIInfo{Usage: usage}
+ m.append(ev, step)
+ }
+ case step.Type == stepGeneric:
+ if len(m.pending) == 0 {
+ return
+ }
+ call := m.pending[0]
+ m.pending = m.pending[1:]
+ m.append(m.toolResultEvent(step, call), step)
+ }
+}
+
+// emitStart writes session.started at the conversation's first step. Antigravity writes no
+// session-end record -- a conversation is resumed with `agy --conversation <id>` -- so none is
+// invented.
+func (m *mapper) emitStart() {
+ first := m.data.Steps[0]
+ ev := m.base(first, "session.started", "session", "Antigravity CLI session started")
+ ev.Event.ID = antigravityEventID(m.data.Ref.ID + ":session.started")
+ if summary := m.data.Ref.Summary; summary != nil {
+ detail := map[string]interface{}{}
+ if summary.Title != "" {
+ detail["title"] = summary.Title
+ }
+ if summary.ProjectID != "" {
+ detail["project_id"] = summary.ProjectID
+ }
+ if summary.ParentConversationID != "" {
+ detail["parent_conversation_id"] = summary.ParentConversationID
+ }
+ if summary.NestingDepth > 0 {
+ detail["nesting_depth"] = summary.NestingDepth
+ }
+ if len(detail) > 0 {
+ ev.Raw = map[string]interface{}{"antigravity": detail}
+ }
+ }
+ if !m.opts.SkipStarted {
+ m.out = append(m.out, MappedEvent{Event: ev, SourceKind: SourceSession, TimestampMS: stepMillis(first)})
+ }
+}
+
+func (m *mapper) toolCallEvent(step Step, call ToolCall) schema.Event {
+ ev := m.base(step, "tool.invoked", "tool", "Antigravity CLI tool invoked")
+ m.applyTool(&ev, call, actionForTool(call.Name))
+ ev.GenAI = &schema.GenAIInfo{Tool: &schema.GenAIToolInfo{
+ Name: call.Name,
+ Call: &schema.GenAIToolCallInfo{Arguments: call.Arguments},
+ }}
+ return ev
+}
+
+func (m *mapper) toolResultEvent(step Step, call ToolCall) schema.Event {
+ action := actionForTool(call.Name)
+ ev := m.base(step, action, categoryForAction(action), "Antigravity CLI tool completed")
+ m.applyTool(&ev, call, action)
+ result := step.Content
+ if action == "command.executed" {
+ output, exitCode := parseCommandResult(step.Content)
+ result = output
+ ev.Command.Output = output
+ ev.Command.ExitCode = exitCode
+ ev.Content = contentMarker(output)
+ }
+ if action == "mcp.tool_invoked" {
+ ev.MCP = &schema.MCPInfo{Tool: call.Name}
+ }
+ ev.GenAI = &schema.GenAIInfo{Tool: &schema.GenAIToolInfo{
+ Name: call.Name,
+ Call: &schema.GenAIToolCallInfo{Arguments: call.Arguments, Result: result},
+ }}
+ return ev
+}
+
+// applyTool fills the tool, command and file blocks from a call's arguments.
+func (m *mapper) applyTool(ev *schema.Event, call ToolCall, action string) {
+ ev.Tool = &schema.ToolInfo{Name: call.Name}
+ if action == "command.executed" {
+ command := asymptoteobserve.ToolCommandLine(call.Name, call.Arguments)
+ ev.Tool.Command = command
+ ev.Command = &schema.CommandInfo{Command: command}
+ // The working directory the command ran in, when the conversation has none recorded.
+ if cwd, ok := call.Arguments["Cwd"].(string); ok && ev.Session.WorkingDirectory == "" {
+ ev.Session.WorkingDirectory = strings.TrimSpace(cwd)
+ }
+ }
+ if path := asymptoteobserve.AntigravityToolPath(call.Arguments); path != "" {
+ ev.Tool.Path = path
+ if strings.HasPrefix(action, "file.") {
+ ev.File = &schema.FileInfo{Path: path, Operation: fileOperation(call.Name)}
+ }
+ }
+}
+
+func (m *mapper) base(step Step, action, category, message string) schema.Event {
+ ev := schema.NewEvent(schema.NewEventOptions{
+ Action: action,
+ Category: category,
+ Severity: schema.SeverityInfo,
+ Fidelity: schema.FidelityObserved,
+ Message: message,
+ Origin: schema.OriginLocal,
+ Harness: schema.HarnessInfo{
+ Name: Harness,
+ CollectionMethod: schema.CollectionMethodPoll,
+ },
+ })
+ ev.Timestamp = normalizeTimestamp(step.CreatedAt)
+ ev.Session = &schema.SessionInfo{ID: m.data.Ref.ID}
+ if summary := m.data.Ref.Summary; summary != nil {
+ ev.Session.WorkingDirectory = summary.WorkingDirectory
+ }
+ return ev
+}
+
+// append records an event mapped from step unless the collector has already written its line, and
+// names it by where it was read.
+func (m *mapper) append(ev schema.Event, step Step) {
+ ev.Event.ID = m.eventID(ev, step)
+ if step.Line <= m.opts.MinLine {
+ return
+ }
+ m.out = append(m.out, MappedEvent{Event: ev, SourceKind: SourceTranscript, SourceLine: step.Line, TimestampMS: stepMillis(step)})
+}
+
+func stepMillis(step Step) int64 {
+ if t := parseTime(step.CreatedAt); !t.IsZero() {
+ return t.UnixMilli()
+ }
+ return 0
+}
+
+// eventID names an event by the conversation, the step and its place among that step's events.
+// The step index rather than the line or the file is the coordinate, so the same step read from
+// transcript_full.jsonl or from transcript.jsonl is the same event, and a sync resent after it
+// stopped partway names the events it already wrote the same way.
+func (m *mapper) eventID(ev schema.Event, step Step) string {
+ key := "line." + strconv.Itoa(step.Line)
+ if step.StepIndex != nil {
+ key = "step." + strconv.FormatInt(*step.StepIndex, 10)
+ }
+ if key != m.step {
+ m.step, m.ordinal = key, 0
+ }
+ m.ordinal++
+ return antigravityEventID(fmt.Sprintf("%s:%s:%d:%s", m.data.Ref.ID, key, m.ordinal, ev.Event.Action))
+}
+
+var exitCodePattern = regexp.MustCompile(`Command exited with code (-?\d+)`)
+
+// parseCommandResult reads a run_command result: the exit code from "Command exited with code N"
+// and the output after "Command output:". The output is from a terminal, so its line endings are
+// CRLF; they are folded to LF and the trailing line ending dropped. A result with neither marker,
+// such as a command still running in the background, is kept whole with no exit code.
+func parseCommandResult(content string) (string, *int) {
+ var exitCode *int
+ if match := exitCodePattern.FindStringSubmatch(content); match != nil {
+ if code, err := strconv.Atoi(match[1]); err == nil {
+ exitCode = &code
+ }
+ }
+ output := content
+ if idx := strings.Index(content, "Command output:"); idx >= 0 {
+ output = strings.TrimPrefix(content[idx+len("Command output:"):], "\n")
+ }
+ output = strings.ReplaceAll(output, "\r\n", "\n")
+ return strings.TrimRight(output, "\r\n"), exitCode
+}
+
+// usageFor is a planner response's own token counts. Each response reports the counts of the one
+// model call that produced it, so they are recorded as reported rather than differenced.
+//
+// Beacon keeps gen_ai.usage counts disjoint. Antigravity is Gemini-backed, and Gemini's prompt
+// count includes cached content, so the cache reads are taken out of the input count -- unless the
+// input is smaller than they are and is therefore already uncached, the same rule Beacon applies to
+// any source using the semconv names.
+func usageFor(step Step) *schema.GenAIUsageInfo {
+ input, cacheRead, output := value(step.InputTokens), value(step.CacheReadTokens), value(step.OutputTokens)
+ if input <= 0 && cacheRead <= 0 && output <= 0 {
+ return nil
+ }
+ usage := &schema.GenAIUsageInfo{}
+ if cacheRead > 0 {
+ usage.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: &cacheRead}
+ if input >= cacheRead {
+ input -= cacheRead
+ }
+ }
+ if input > 0 {
+ usage.InputTokens = &input
+ }
+ if output > 0 {
+ usage.OutputTokens = &output
+ }
+ return usage
+}
+
+func value(p *int64) int64 {
+ if p == nil {
+ return 0
+ }
+ return *p
+}
+
+// actionForTool classifies a call by Antigravity's tool name, from the vocabulary the live hook
+// adapter reads too; a call that is no command, file or MCP activity completes as a tool.
+func actionForTool(name string) string {
+ if action := asymptoteobserve.AntigravityToolAction(name); action != "" {
+ return action
+ }
+ return "tool.completed"
+}
+
+func categoryForAction(action string) string {
+ switch {
+ case strings.HasPrefix(action, "command."):
+ return "command"
+ case strings.HasPrefix(action, "file."):
+ return "file"
+ case strings.HasPrefix(action, "mcp."):
+ return "mcp"
+ default:
+ return "tool"
+ }
+}
+
+func fileOperation(tool string) string {
+ switch strings.ToLower(tool) {
+ case "view_file", "list_dir", "grep_search", "find_by_name":
+ return "read"
+ case "write_to_file", "write_file":
+ return "write"
+ default:
+ return "modify"
+ }
+}
+
+func contentMarker(text string) *schema.ContentInfo {
+ return asymptoteobserve.RetainedContent(text, 0)
+}
+
+func normalizeTimestamp(ts string) string {
+ t := parseTime(ts)
+ if t.IsZero() {
+ return schema.FormatTimestamp(time.Now())
+ }
+ return schema.FormatTimestamp(t)
+}
+
+func parseTime(ts string) time.Time {
+ t, err := asymptoteobserve.ParseTimestamp(ts)
+ if err != nil {
+ return time.Time{}
+ }
+ return t
+}
+
+var antigravityIDNamespace = [16]byte{
+ 0x3f, 0x8a, 0x1d, 0x62, 0xc4, 0x57, 0x4e, 0x0b,
+ 0x9d, 0x26, 0xe1, 0x70, 0x5b, 0xa3, 0x48, 0xcf,
+}
+
+// antigravityEventID is a version 5 UUID of coordinate under antigravityIDNamespace.
+func antigravityEventID(coordinate string) string {
+ digest := sha1.New()
+ digest.Write(antigravityIDNamespace[:])
+ io.WriteString(digest, coordinate)
+ var id [16]byte
+ copy(id[:], digest.Sum(nil))
+ id[6] = (id[6] & 0x0f) | 0x50
+ id[8] = (id[8] & 0x3f) | 0x80
+ out := make([]byte, 32)
+ hex.Encode(out, id[:])
+ return fmt.Sprintf("%s-%s-%s-%s-%s", out[0:8], out[8:12], out[12:16], out[16:20], out[20:32])
+}
diff --git a/cli/beacon/internal/antigravitysession/store.go b/cli/beacon/internal/antigravitysession/store.go
new file mode 100644
index 00000000..b3b844d2
--- /dev/null
+++ b/cli/beacon/internal/antigravitysession/store.go
@@ -0,0 +1,264 @@
+package antigravitysession
+
+import (
+ "bufio"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionsync"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+const (
+ fullTranscriptName = "transcript_full.jsonl"
+ transcriptName = "transcript.jsonl"
+ summariesDBName = "conversation_summaries.db"
+ summariesTable = "conversation_summaries"
+)
+
+// Store reads Antigravity CLI conversations from a brain directory.
+type Store struct {
+ // BrainDir holds one directory per conversation, named by its conversationId.
+ BrainDir string
+ // DBPath is conversation_summaries.db, which sits beside the brain directory.
+ DBPath string
+}
+
+// DefaultBrainDir is ~/.gemini/antigravity-cli/brain.
+func DefaultBrainDir() string {
+ home, err := os.UserHomeDir()
+ if err != nil || strings.TrimSpace(home) == "" {
+ return filepath.Join(".", ".gemini", "antigravity-cli", "brain")
+ }
+ return filepath.Join(home, ".gemini", "antigravity-cli", "brain")
+}
+
+// NewStore reads dir as the brain directory, or DefaultBrainDir when dir is empty. The summaries
+// database is looked for beside it, which is where Antigravity keeps it.
+func NewStore(dir string) *Store {
+ if strings.TrimSpace(dir) == "" {
+ dir = DefaultBrainDir()
+ }
+ return &Store{BrainDir: dir, DBPath: filepath.Join(filepath.Dir(dir), summariesDBName)}
+}
+
+func (s *Store) Exists() bool {
+ info, err := sessionfs.Stat(s.BrainDir)
+ return err == nil && info.IsDir()
+}
+
+// List returns every conversation with a transcript, oldest first.
+//
+// A conversation without a summaries row, or a machine without the database, is listed with no
+// Summary: the row only adds the working directory and title, and the transcript is collectable
+// without them. A database that exists but cannot be read is the same, except that the error is
+// returned alongside the conversations, as Cursor's and OpenCode's stores do with a store they
+// could not read: the sweep reports it and still collects every transcript.
+func (s *Store) List() ([]SessionRef, error) {
+ entries, err := sessionfs.ReadDir(s.BrainDir)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ var refs []SessionRef
+ for _, entry := range entries {
+ if !entry.IsDir() {
+ continue
+ }
+ sourcePath := filepath.Join(s.BrainDir, entry.Name())
+ logs := filepath.Join(sourcePath, ".system_generated", "logs")
+ ref := SessionRef{ID: entry.Name(), SourcePath: sourcePath}
+ // The full transcript is preferred because its tool arguments are typed. transcript.jsonl
+ // holds the same steps with every argument JSON-encoded as a string, and is read only when
+ // the full one is not there.
+ if info, err := sessionfs.Stat(filepath.Join(logs, fullTranscriptName)); err == nil && !info.IsDir() {
+ ref.TranscriptPath, ref.Full, ref.ModTimeUnixMS = filepath.Join(logs, fullTranscriptName), true, info.ModTime().UnixMilli()
+ } else if info, err := sessionfs.Stat(filepath.Join(logs, transcriptName)); err == nil && !info.IsDir() {
+ ref.TranscriptPath, ref.ModTimeUnixMS = filepath.Join(logs, transcriptName), info.ModTime().UnixMilli()
+ } else {
+ continue
+ }
+ refs = append(refs, ref)
+ }
+ if len(refs) == 0 {
+ return nil, nil
+ }
+ summaries, summariesErr := s.readSummaries()
+ for i := range refs {
+ if summary, ok := summaries[refs[i].ID]; ok {
+ summary := summary
+ refs[i].Summary = &summary
+ }
+ }
+ sort.Slice(refs, func(i, j int) bool {
+ if refs[i].ModTimeUnixMS == refs[j].ModTimeUnixMS {
+ return refs[i].ID < refs[j].ID
+ }
+ return refs[i].ModTimeUnixMS < refs[j].ModTimeUnixMS
+ })
+ return refs, summariesErr
+}
+
+// readSummaries reads the conversation_summaries rows, by conversation id.
+//
+// A missing database or table is not an error: it means no working directory or title, not a
+// conversation that cannot be collected. The columns are looked up rather than assumed, so a
+// column Antigravity drops reads as empty instead of failing every sweep; only conversation_id
+// is required.
+func (s *Store) readSummaries() (map[string]Summary, error) {
+ if info, err := sessionfs.Stat(s.DBPath); err != nil || info.IsDir() {
+ return nil, nil
+ }
+ db, err := sessionsync.OpenSQLite(s.DBPath, "busy_timeout(1000)")
+ if err != nil {
+ return nil, fmt.Errorf("open Antigravity conversation summaries: %w", err)
+ }
+ defer db.Close()
+
+ columns, err := sessionsync.TableColumns(db, summariesTable)
+ if err != nil {
+ return nil, fmt.Errorf("read Antigravity conversation summaries: %w", err)
+ }
+ if !columns["conversation_id"] {
+ return nil, nil
+ }
+ selected := []string{"conversation_id"}
+ for _, column := range []string{"title", "workspace_uris", "project_id", "parent_conversation_id", "nesting_depth"} {
+ if columns[column] {
+ selected = append(selected, column)
+ } else {
+ selected = append(selected, "NULL")
+ }
+ }
+ rows, err := db.Query("SELECT " + strings.Join(selected, ", ") + " FROM " + summariesTable)
+ if err != nil {
+ return nil, fmt.Errorf("read Antigravity conversation summaries: %w", err)
+ }
+ defer rows.Close()
+ out := map[string]Summary{}
+ for rows.Next() {
+ var id, title, workspaces, project, parent sql.NullString
+ var depth sql.NullInt64
+ if err := rows.Scan(&id, &title, &workspaces, &project, &parent, &depth); err != nil {
+ return nil, fmt.Errorf("read Antigravity conversation summaries: %w", err)
+ }
+ if strings.TrimSpace(id.String) == "" {
+ continue
+ }
+ out[id.String] = Summary{
+ Title: strings.TrimSpace(title.String),
+ WorkingDirectory: firstWorkspacePath(workspaces.String),
+ ProjectID: strings.TrimSpace(project.String),
+ ParentConversationID: strings.TrimSpace(parent.String),
+ NestingDepth: depth.Int64,
+ }
+ }
+ if err := rows.Err(); err != nil {
+ return nil, fmt.Errorf("read Antigravity conversation summaries: %w", err)
+ }
+ return out, nil
+}
+
+// firstWorkspacePath is the first entry of workspace_uris, a JSON array of file:// URIs, as a
+// local path. The first workspace is the one Antigravity was started in.
+func firstWorkspacePath(raw string) string {
+ var uris []string
+ if json.Unmarshal([]byte(raw), &uris) != nil || len(uris) == 0 {
+ return ""
+ }
+ path := asymptoteobserve.FilePathFromURI(strings.TrimSpace(uris[0]))
+ if path == "" {
+ return ""
+ }
+ return filepath.FromSlash(path)
+}
+
+// Read parses the conversation's transcript.
+func (s *Store) Read(ref SessionRef) (SessionData, Stats, error) {
+ data := SessionData{Ref: ref}
+ steps, lines, malformed, err := readTranscript(ref.TranscriptPath, ref.Full)
+ data.Steps, data.Lines = steps, lines
+ return data, Stats{Malformed: malformed}, err
+}
+
+// readTranscript parses a transcript, returning the steps, the number of lines it scanned, how many
+// did not parse, and whether the file could be read through.
+//
+// The line count is reported separately from len(steps) and the two are not interchangeable: the
+// collector compares the count against its line cursor to notice a transcript rewritten shorter,
+// and a single malformed line would otherwise read as a rewrite. A scan that stops on an error is a
+// read failure rather than a short file for the same reason, so the session fails this sweep with
+// its cursor untouched.
+func readTranscript(path string, full bool) ([]Step, int, int, error) {
+ f, err := sessionfs.Open(path)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, 0, 0, nil
+ }
+ return nil, 0, 0, fmt.Errorf("read %s: %w", path, err)
+ }
+ defer f.Close()
+ var out []Step
+ malformed, lineNo := 0, 0
+ scanner := bufio.NewScanner(f)
+ scanner.Buffer(make([]byte, 0, 64*1024), 16*1024*1024)
+ for scanner.Scan() {
+ // Physical line numbers, so a half-written line at the tail of a live conversation does
+ // not renumber the lines after it once it lands.
+ lineNo++
+ line := strings.TrimSpace(scanner.Text())
+ if line == "" {
+ continue
+ }
+ var step Step
+ if err := json.Unmarshal([]byte(line), &step); err != nil {
+ malformed++
+ continue
+ }
+ step.Line = lineNo
+ for i := range step.ToolCalls {
+ step.ToolCalls[i].Arguments = decodeArgs(step.ToolCalls[i].Args, !full)
+ }
+ out = append(out, step)
+ }
+ if err := scanner.Err(); err != nil {
+ return out, lineNo, malformed, fmt.Errorf("read %s: %w", path, err)
+ }
+ return out, lineNo, malformed, nil
+}
+
+// decodeArgs decodes a call's arguments. transcript.jsonl writes each value JSON-encoded as a
+// string ("\"cat notes.txt\"", "5000"), so with encoded set each string that holds JSON is decoded
+// once more; a string that does not is kept as written.
+func decodeArgs(raw json.RawMessage, encoded bool) map[string]interface{} {
+ if len(raw) == 0 {
+ return nil
+ }
+ var args map[string]interface{}
+ if err := json.Unmarshal(raw, &args); err != nil {
+ return nil
+ }
+ if !encoded {
+ return args
+ }
+ for key, value := range args {
+ text, ok := value.(string)
+ if !ok {
+ continue
+ }
+ var decoded interface{}
+ if json.Unmarshal([]byte(text), &decoded) == nil {
+ args[key] = decoded
+ }
+ }
+ return args
+}
diff --git a/cli/beacon/internal/antigravitysession/types.go b/cli/beacon/internal/antigravitysession/types.go
new file mode 100644
index 00000000..46fab25f
--- /dev/null
+++ b/cli/beacon/internal/antigravitysession/types.go
@@ -0,0 +1,122 @@
+// Package antigravitysession reads the conversations Antigravity CLI (`agy`) commits under
+// ~/.gemini/antigravity-cli and maps them to endpoint events marked
+// harness.collection_method=poll.
+//
+// One conversation is one brain directory, ~/.gemini/antigravity-cli/brain/<conversationId>/, whose
+// .system_generated/logs/transcript_full.jsonl holds one step per line. The conversation's working
+// directory, title and parent conversation live beside it in conversation_summaries.db.
+package antigravitysession
+
+import (
+ "encoding/json"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+)
+
+// Harness is the canonical harness name every event from this collector carries. It is the name
+// asymptoteobserve.NormalizeHarnessName gives "antigravity" and the one the live hooks write, so
+// a conversation collected both ways is one runtime in every report.
+const Harness = "antigravity_cli"
+
+// SessionRef locates one conversation.
+type SessionRef struct {
+ // ID is the conversationId, the brain directory's name, which is also the session id the live
+ // hooks put on their events.
+ ID string
+ // SourcePath is the brain directory.
+ SourcePath string
+ // TranscriptPath is the transcript the conversation is read from: transcript_full.jsonl, or
+ // transcript.jsonl when the full transcript is absent.
+ TranscriptPath string
+ // Full says TranscriptPath is transcript_full.jsonl, whose tool arguments are typed values.
+ // transcript.jsonl carries each argument JSON-encoded as a string.
+ Full bool
+ // ModTimeUnixMS is the transcript's modification time.
+ ModTimeUnixMS int64
+ // Summary is the conversation's row in conversation_summaries.db, or nil when there is none.
+ Summary *Summary
+}
+
+// Summary is what Beacon reads from a conversation_summaries.db row. The table also holds a
+// protobuf blob, which is not read.
+type Summary struct {
+ Title string
+ // WorkingDirectory is the first of the row's workspace_uris, as a local path.
+ WorkingDirectory string
+ ProjectID string
+ ParentConversationID string
+ NestingDepth int64
+}
+
+// Step is one line of a transcript.
+type Step struct {
+ // StepIndex is a pointer because the first step is numbered zero, and a step with no index
+ // must not be mistaken for it.
+ StepIndex *int64 `json:"step_index,omitempty"`
+ Source string `json:"source,omitempty"`
+ Type string `json:"type"`
+ Status string `json:"status,omitempty"`
+ CreatedAt string `json:"created_at,omitempty"`
+ Content string `json:"content,omitempty"`
+ Thinking string `json:"thinking,omitempty"`
+ InputTokens *int64 `json:"input_tokens,omitempty"`
+ CacheReadTokens *int64 `json:"cache_read_tokens,omitempty"`
+ OutputTokens *int64 `json:"output_tokens,omitempty"`
+ ToolCalls []ToolCall `json:"tool_calls,omitempty"`
+ // Line is the step's physical line number in the transcript, which the collector's cursor
+ // counts in.
+ Line int `json:"-"`
+}
+
+// ToolCall is one call in a planner response. Antigravity gives a call no id: its result is the
+// next GENERIC step in order.
+type ToolCall struct {
+ Name string `json:"name"`
+ Args json.RawMessage `json:"args,omitempty"`
+ // Arguments is Args decoded, with transcript.jsonl's string-encoded values decoded too.
+ Arguments map[string]interface{} `json:"-"`
+}
+
+// SessionData is one conversation as read.
+type SessionData struct {
+ Ref SessionRef
+ Steps []Step
+ // Lines is how many lines the transcript held, which is not len(Steps): a blank or
+ // unparseable line counts here and produces no step. It is what the collector's line cursor
+ // is comparable against.
+ Lines int
+}
+
+// SourceKind names where a mapped event came from.
+type SourceKind string
+
+const (
+ // SourceSession marks session.started, which is derived from the conversation as a whole and
+ // is recorded in the cursor as a flag rather than a position.
+ SourceSession SourceKind = "session"
+ // SourceTranscript marks an event mapped from a numbered transcript line.
+ SourceTranscript SourceKind = "transcript"
+)
+
+// MapOptions carries the collector's cursor into the mapper. The mapper always reads the whole
+// conversation -- a GENERIC step is the result of a call named on an earlier planner line, so the
+// pairing has to be rebuilt every sweep -- but emits only what lies past the cursor.
+type MapOptions struct {
+ // MinLine is the last transcript line already written; lines at or below it are skipped.
+ MinLine int
+ // SkipStarted suppresses session.started once it has been written for this conversation.
+ SkipStarted bool
+}
+
+type MappedEvent struct {
+ Event schema.Event
+ SourceKind SourceKind
+ SourceLine int
+ // TimestampMS is the source step's created_at, zero when it had none. The collector compares
+ // it against live hook coverage.
+ TimestampMS int64
+}
+
+type Stats struct {
+ Malformed int
+}
diff --git a/cli/beacon/internal/devinsession/collect.go b/cli/beacon/internal/devinsession/collect.go
index a6b42975..19a8b36b 100644
--- a/cli/beacon/internal/devinsession/collect.go
+++ b/cli/beacon/internal/devinsession/collect.go
@@ -108,13 +108,11 @@ type CollectOptions struct {
// Budget, when set, caps the bytes this sweep may append. The sweep stops at the first event
// that does not fit and returns writer.ErrBudgetSpent, with cursors past only what was written.
Budget *writer.Budget
- // LiveCoverage, when set, marks the sessions the live Devin hooks have already reported, by
- // the earliest hook event timestamp per session id. The hook payload carries prompts and tool
- // calls but no assistant text, reasoning, token metrics or model, so for rows at or after
- // live coverage began the sweep suppresses the actions hooks would double-count (prompts,
- // tool invocations and tool results, session.started and handoffs) and keeps the ones hooks
- // cannot see.
- LiveCoverage map[string]time.Time
+ // LiveCoverage, when set, marks the sessions the live Devin hooks have already reported. The
+ // hook payload carries prompts and tool calls but no assistant text, reasoning, token metrics
+ // or model, so the sweep keeps only what hooks cannot see from each covered session's first
+ // hook event on (see sessionsync.LiveCoverage.Suppresses).
+ LiveCoverage sessionsync.LiveCoverage
}
type Summary struct {
@@ -327,7 +325,7 @@ func collectSession(store *Store, session Session, state *State, opts CollectOpt
}
}
started := m.mapSessionStarted(startTS)
- if suppressedLive(started.Event.Event.Action, started.TimestampMS, session, opts) {
+ if opts.LiveCoverage.Suppresses(session.ID, started.Event.Event.Action, started.TimestampMS) {
summary.EventsSuppressedLive++
} else if err := sink.Emit(started.Event); err != nil {
return true, err
@@ -358,7 +356,7 @@ func collectSession(store *Store, session Session, state *State, opts CollectOpt
for _, row := range rows {
journal := m.beginRow()
for _, item := range m.mapRow(row, priorIDs) {
- if suppressedLive(item.Event.Event.Action, item.TimestampMS, session, opts) {
+ if opts.LiveCoverage.Suppresses(session.ID, item.Event.Event.Action, item.TimestampMS) {
summary.EventsSuppressedLive++
continue
}
@@ -374,29 +372,6 @@ func collectSession(store *Store, session Session, state *State, opts CollectOpt
}
}
-// suppressedLive reports whether this event is one the live hook path already recorded. Devin
-// hooks see the prompt and every tool call as it happens but the payload carries no assistant
-// text, reasoning, token metrics or model, so actions hooks would double-count are skipped for
-// rows at or after live coverage began (with a small clock-skew allowance), while agent.message,
-// agent.reasoning, token.usage, session.context, session.compacted and approval.denied always
-// emit -- the hook never saw them.
-func suppressedLive(action string, timestampMS int64, session Session, opts CollectOptions) bool {
- cutover, ok := opts.LiveCoverage[session.ID]
- if !ok {
- return false
- }
- if timestampMS < cutover.UnixMilli()-2000 {
- return false
- }
- switch action {
- case "session.started", "prompt.submitted", "session.handoff",
- "tool.invoked", "mcp.tool_invoked",
- "command.executed", "file.read", "file.modified", "tool.completed", "tool.failed":
- return true
- }
- return false
-}
-
func (o CollectOptions) sink() sessionsync.Sink {
return sessionsync.Sink{Print: o.Print, Out: o.Out, Write: o.Write, Log: writer.Options{Path: o.LogPath, UserMode: o.UserMode, RotateSize: o.RotateBytes, Budget: o.Budget}}
}
@@ -420,7 +395,7 @@ func OpenStore(path string) (*Store, error) {
}
store := &Store{path: path, db: db}
for _, table := range []string{"sessions", "message_nodes"} {
- columns, err := tableColumns(db, table)
+ columns, err := sessionsync.TableColumns(db, table)
if err != nil {
_ = db.Close()
return nil, err
@@ -455,30 +430,6 @@ func (s *Store) Close() error { return s.db.Close() }
func (s *Store) Path() string { return s.path }
-// tableColumns lists a table's columns, so the queries below can select optional columns when
-// they exist and NULL when they do not. Columns or JSON keys this collector does not know are
-// ignored either way.
-func tableColumns(db *sql.DB, table string) (map[string]bool, error) {
- rows, err := db.Query(fmt.Sprintf(`SELECT name FROM pragma_table_info(%s)`, quoteIdent(table)))
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- columns := map[string]bool{}
- for rows.Next() {
- var name string
- if err := rows.Scan(&name); err != nil {
- return nil, err
- }
- columns[name] = true
- }
- return columns, rows.Err()
-}
-
-func quoteIdent(name string) string {
- return `'` + strings.ReplaceAll(name, `'`, `''`) + `'`
-}
-
// pick renders a column name for SELECT when it exists and NULL aliased to it when it does not.
func pick(columns map[string]bool, name string) string {
if columns[name] {
diff --git a/cli/beacon/internal/devinsession/collect_test.go b/cli/beacon/internal/devinsession/collect_test.go
index 13e012e4..d608dbf8 100644
--- a/cli/beacon/internal/devinsession/collect_test.go
+++ b/cli/beacon/internal/devinsession/collect_test.go
@@ -15,6 +15,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionsync"
)
// The store's real DDL, verbatim: a fixture must break if this collector drifts from the schema
@@ -665,7 +666,7 @@ func TestLiveCoverageSuppressesWhatHooksAlreadyRecorded(t *testing.T) {
}), 1700000300, nil)
opts := collectOptions(p)
- opts.LiveCoverage = map[string]time.Time{"s1": cutover}
+ opts.LiveCoverage = sessionsync.LiveCoverage{From: map[string]time.Time{"s1": cutover}}
summary, err := CollectOnce(opts)
if err != nil {
t.Fatalf("CollectOnce: %v", err)
diff --git a/cli/beacon/internal/endpoint/hooks/antigravity.go b/cli/beacon/internal/endpoint/hooks/antigravity.go
index df0bfd65..8a6b1ab7 100644
--- a/cli/beacon/internal/endpoint/hooks/antigravity.go
+++ b/cli/beacon/internal/endpoint/hooks/antigravity.go
@@ -116,8 +116,11 @@ func installAntigravityHooks(path, binaryPath, logPath, configPath string) error
return err
}
prefix := endpointCommandPrefix("antigravity", binaryPath, logPath, configPath)
+ // PreInvocation runs before every model call; the adapter records the turn's prompt only on
+ // the first call of each turn (invocationNum 0), so it is the per-turn prompt hook.
block := antigravityHookBlock{
- SessionStart: []antigravityHookRef{{Type: "command", Command: prefix + " session-start"}},
+ SessionStart: []antigravityHookRef{{Type: "command", Command: prefix + " session-start"}},
+ PreInvocation: []antigravityHookRef{{Type: "command", Command: prefix + " prompt-submit"}},
PreToolUse: []antigravityHookGroup{{
Matcher: "*",
Hooks: []antigravityHookRef{{Type: "command", Command: prefix + " pre-tool"}},
diff --git a/cli/beacon/internal/endpoint/hooks/antigravity_test.go b/cli/beacon/internal/endpoint/hooks/antigravity_test.go
index 79d8e0bc..2297d8cc 100644
--- a/cli/beacon/internal/endpoint/hooks/antigravity_test.go
+++ b/cli/beacon/internal/endpoint/hooks/antigravity_test.go
@@ -42,14 +42,14 @@ func TestInstallAntigravityHooksPreservesNonBeaconBlocks(t *testing.T) {
t.Fatal(err)
}
managed := blocks["beacon-endpoint"]
- if len(managed) != 4 {
- t.Errorf("managed hook events = %v, want four lifecycle and tool events", managed)
+ if len(managed) != 5 {
+ t.Errorf("managed hook events = %v, want five lifecycle and tool events", managed)
}
type handler struct {
Type string `json:"type"`
Command string `json:"command"`
}
- for event, suffix := range map[string]string{"SessionStart": " session-start", "Stop": " stop"} {
+ for event, suffix := range map[string]string{"SessionStart": " session-start", "PreInvocation": " prompt-submit", "Stop": " stop"} {
var handlers []handler
if err := json.Unmarshal(managed[event], &handlers); err != nil {
t.Errorf("%s must be a direct handler list: %v", event, err)
diff --git a/cli/beacon/internal/endpoint/integrations/hookcoverage.go b/cli/beacon/internal/endpoint/integrations/hookcoverage.go
new file mode 100644
index 00000000..eaaa08fe
--- /dev/null
+++ b/cli/beacon/internal/endpoint/integrations/hookcoverage.go
@@ -0,0 +1,91 @@
+package integrations
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "os"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionsync"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// HookCoverage finds, per session id, the earliest hook event the retained runtime log holds for
+// any of harnesses (canonical names, compared after NormalizeHarnessName), and the content hash of
+// every prompt those hooks recorded. A session collector whose runtime also has live hooks takes it
+// as its sessionsync.LiveCoverage, so a poll sweep skips what the hooks already recorded and keeps
+// only what the hook payload cannot carry.
+//
+// Every retained archive is read because coverage can sit several rotations back on a busy
+// machine; a missing file is simply not evidence. The scan decodes only the fields it needs, so a
+// runtime.jsonl of any size costs a line at a time, and only lines containing marker are
+// unmarshalled.
+func HookCoverage(logPath, marker string, harnesses ...string) sessionsync.LiveCoverage {
+ var coverage sessionsync.LiveCoverage
+ for _, path := range writer.RetainedLogPaths(logPath) {
+ f, err := os.Open(path)
+ if err != nil {
+ continue
+ }
+ scanner := bufio.NewScanner(f)
+ scanner.Buffer(make([]byte, 0, 64*1024), 1<<20)
+ for scanner.Scan() {
+ line := scanner.Bytes()
+ if !bytes.Contains(line, []byte(marker)) {
+ continue
+ }
+ var event struct {
+ Timestamp string `json:"timestamp"`
+ Event struct {
+ Action string `json:"action"`
+ } `json:"event"`
+ Harness struct {
+ Name string `json:"name"`
+ CollectionMethod string `json:"collection_method"`
+ } `json:"harness"`
+ Session struct {
+ ID string `json:"id"`
+ } `json:"session"`
+ Content struct {
+ Hash string `json:"hash"`
+ } `json:"content"`
+ }
+ if json.Unmarshal(line, &event) != nil {
+ continue
+ }
+ name := asymptoteobserve.NormalizeHarnessName(event.Harness.Name)
+ if !slices.Contains(harnesses, name) || event.Harness.CollectionMethod != asymptoteobserve.CollectionMethodHook {
+ continue
+ }
+ sessionID := strings.TrimSpace(event.Session.ID)
+ if sessionID == "" {
+ continue
+ }
+ ts, err := asymptoteobserve.ParseTimestamp(event.Timestamp)
+ if err != nil {
+ continue
+ }
+ if coverage.From == nil {
+ coverage.From = map[string]time.Time{}
+ }
+ if earliest, ok := coverage.From[sessionID]; !ok || ts.Before(earliest) {
+ coverage.From[sessionID] = ts
+ }
+ if event.Event.Action == "prompt.submitted" && event.Content.Hash != "" {
+ if coverage.Prompts == nil {
+ coverage.Prompts = map[string]map[string]bool{}
+ }
+ if coverage.Prompts[sessionID] == nil {
+ coverage.Prompts[sessionID] = map[string]bool{}
+ }
+ coverage.Prompts[sessionID][event.Content.Hash] = true
+ }
+ }
+ _ = f.Close()
+ }
+ return coverage
+}
diff --git a/cli/beacon/internal/hermessession/collect.go b/cli/beacon/internal/hermessession/collect.go
index d547e3f3..6d72ab4a 100644
--- a/cli/beacon/internal/hermessession/collect.go
+++ b/cli/beacon/internal/hermessession/collect.go
@@ -365,8 +365,8 @@ func OpenStore(path string) (*Store, error) {
return nil, err
}
store := &Store{path: path, db: db}
- if store.sessionCols, err = tableColumns(db, "sessions"); err == nil {
- store.messageCols, err = tableColumns(db, "messages")
+ if store.sessionCols, err = sessionsync.TableColumns(db, "sessions"); err == nil {
+ store.messageCols, err = sessionsync.TableColumns(db, "messages")
}
if err != nil {
_ = db.Close()
@@ -375,23 +375,6 @@ func OpenStore(path string) (*Store, error) {
return store, nil
}
-func tableColumns(db *sql.DB, table string) (map[string]bool, error) {
- rows, err := db.Query(`SELECT name FROM pragma_table_info(?)`, table)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- cols := map[string]bool{}
- for rows.Next() {
- var name string
- if err := rows.Scan(&name); err != nil {
- return nil, err
- }
- cols[name] = true
- }
- return cols, rows.Err()
-}
-
// column is alias.name when the table has the column, and fallback when it does not.
func column(cols map[string]bool, alias, name, fallback string) string {
if !cols[name] {
diff --git a/cli/beacon/internal/sessionfs/collectors_test.go b/cli/beacon/internal/sessionfs/collectors_test.go
index f6213475..2c98f8bd 100644
--- a/cli/beacon/internal/sessionfs/collectors_test.go
+++ b/cli/beacon/internal/sessionfs/collectors_test.go
@@ -17,7 +17,7 @@ var backfillCollectors = []string{
"claudesession", "codexsession", "cursorsession", "opencodesession", "copilotsession",
"clinesession", "factorysession", "pisession", "primesession", "hermessession",
"dshsession", "fxsession", "groksession", "openclawsession", "devinsession",
- "harness2session",
+ "harness2session", "antigravitysession",
}
// directReads are the calls that would read a session store around the confinement.
diff --git a/cli/beacon/internal/sessionsync/livecoverage.go b/cli/beacon/internal/sessionsync/livecoverage.go
new file mode 100644
index 00000000..7609e8e8
--- /dev/null
+++ b/cli/beacon/internal/sessionsync/livecoverage.go
@@ -0,0 +1,49 @@
+package sessionsync
+
+import "time"
+
+// liveCoverageSkew is how far before a session's first hook event a poll event still counts as
+// covered, for the clock difference between the hook process and the runtime's own timestamps.
+const liveCoverageSkew = 2 * time.Second
+
+// LiveCoverage is what a runtime's live hooks already wrote to the runtime log
+// (integrations.HookCoverage). A collector whose runtime also has hooks consults it so a poll sweep
+// does not record twice what the hooks already recorded.
+type LiveCoverage struct {
+ // From is, per session id, the earliest event the hooks wrote for it.
+ From map[string]time.Time
+ // Prompts is, per session id, the content.hash of every prompt the hooks recorded. Both paths
+ // hash a prompt with asymptoteobserve.RetainedContent, so the same prompt has the same hash on
+ // either, in every retention mode.
+ Prompts map[string]map[string]bool
+}
+
+// Suppresses reports whether a poll event with action, mapped from a record at timestampMS in
+// sessionID, duplicates one the live hooks recorded. Hook payloads carry the prompt and every tool
+// call as it happens, so those actions are suppressed from the session's first hook event on.
+// What hooks cannot see -- agent messages, reasoning, token usage, context and compaction,
+// approvals -- is never suppressed, and neither is anything from before the hooks started or a
+// record with no timestamp, which cannot be placed after it.
+//
+// A runtime whose hooks can miss a prompt matches prompts with RecordedPrompt instead.
+func (c LiveCoverage) Suppresses(sessionID, action string, timestampMS int64) bool {
+ cutover, ok := c.From[sessionID]
+ if !ok || timestampMS == 0 || timestampMS < cutover.Add(-liveCoverageSkew).UnixMilli() {
+ return false
+ }
+ switch action {
+ case "session.started", "prompt.submitted", "session.handoff",
+ "tool.invoked", "mcp.tool_invoked",
+ "command.executed", "file.read", "file.modified", "tool.completed", "tool.failed":
+ return true
+ }
+ return false
+}
+
+// RecordedPrompt reports whether the hooks recorded a prompt with contentHash in sessionID. It
+// answers by the prompt itself rather than by time, for a runtime whose hooks record some of a
+// session's prompts and not others. Identical prompts in one session share a hash, so a repeat of
+// a recorded prompt counts as recorded.
+func (c LiveCoverage) RecordedPrompt(sessionID, contentHash string) bool {
+ return contentHash != "" && c.Prompts[sessionID][contentHash]
+}
diff --git a/cli/beacon/internal/sessionsync/sessionsync.go b/cli/beacon/internal/sessionsync/sessionsync.go
index 4bab66bc..47390f40 100644
--- a/cli/beacon/internal/sessionsync/sessionsync.go
+++ b/cli/beacon/internal/sessionsync/sessionsync.go
@@ -251,3 +251,23 @@ func OpenSQLite(path string, pragmas ...string) (*sql.DB, error) {
}
return sql.Open("sqlite", sqliteuri.File(path, url.Values{"mode": {"ro"}, "_pragma": pragmas}))
}
+
+// TableColumns lists a table's columns, so a collector can select a column when its runtime's
+// schema has it and NULL when it does not, instead of failing every sweep on a column a runtime
+// release renamed or dropped.
+func TableColumns(db *sql.DB, table string) (map[string]bool, error) {
+ rows, err := db.Query(`SELECT name FROM pragma_table_info(?)`, table)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ columns := map[string]bool{}
+ for rows.Next() {
+ var name string
+ if err := rows.Scan(&name); err != nil {
+ return nil, err
+ }
+ columns[name] = true
+ }
+ return columns, rows.Err()
+}
diff --git a/cli/beacon/internal/tokens/coverage.go b/cli/beacon/internal/tokens/coverage.go
index 698de7d7..be6e410f 100644
--- a/cli/beacon/internal/tokens/coverage.go
+++ b/cli/beacon/internal/tokens/coverage.go
@@ -129,8 +129,11 @@ var usageExpectation = map[string]struct {
// carries the semconv names -- the generic-OTLP case exactly, not a runtime Beacon reads.
"grok_bot": {ExpectGenericOTLP, "only if Cursor's server-side OTel export carries GenAI semconv usage"},
- "cursor": {ExpectNone, "no usage on any hook payload; preCompact reports context only"},
- "antigravity_cli": {ExpectNone, "hook payloads carry no token counts"},
+ "cursor": {ExpectNone, "no usage on any hook payload; preCompact reports context only"},
+ // Antigravity CLI's hooks carry no token counts, but every planner response it commits to its
+ // transcript does, and `beacon endpoint antigravity sync` reads them -- same shape as Hermes
+ // above and Devin CLI below.
+ "antigravity_cli": {ExpectReported, "beacon endpoint antigravity sync reads per-response token counts; hook payloads carry none"},
"grok": {ExpectNone, "hook payloads carry no token counts"},
// Devin reaches the log under three names, and all three need an entry. The hook installer
// writes --platform devin-cli and devin-desktop, an older install still writes plain devin,
diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdx
index f9aa9f89..71c34624 100644
--- a/docs/changelog/cli.mdx
+++ b/docs/changelog/cli.mdx
@@ -13,6 +13,11 @@ Stay up to date with the latest changes to the Agent Beacon CLI.
Changes on `main` since v1.3.60. They ship in the next release.
+- **Antigravity CLI records every prompt** · Antigravity has no prompt hook, so Beacon recovered only a session's first prompt, from its transcript on the first tool call: later prompts, and turns that ran no tool, were never recorded. The managed hook block now also runs `beacon-hooks` on `PreInvocation`, which Antigravity calls before every model call with the turn's prompt as `lastUserInput`, and Beacon records it on the first call of each turn (`invocationNum` 0), resumed conversations included. Package repair adds the handler to installed user-level hooks; for project-level or manual installs, rerun `beacon endpoint hooks install --harness antigravity` at the same level.
+- **Antigravity CLI session sync** · `beacon endpoint antigravity sync|status` (alias `antigravity-cli`) reads the conversations Antigravity keeps under `~/.gemini/antigravity-cli/brain` and records them as `harness.collection_method=poll` events: prompts, agent messages, reasoning, tool calls, commands with exit code and output, file reads and edits, and per-response token usage, with the working directory from `conversation_summaries.db`. The install-time backfill and the scheduled session sync include it, so conversations from before the hooks worked are recorded. For a conversation the hooks already recorded, sync adds only agent messages, reasoning, and token usage from the point the hooks started, plus any prompt the hooks did not record, matched by content hash, such as the later prompts of a conversation recorded by v1.3.60 hooks. `beacon token-usage --coverage` now expects Antigravity usage from the sync instead of reporting it as not instrumented.
+- **Antigravity CLI file edits are recorded as edits** · Antigravity edits files with `replace_file_content` and `multi_replace_file_content`, whose names the hook adapter's edit rule did not match, so a live edit was recorded as a plain `tool.invoked`; and its write and replace tools name their file `TargetFile`, which the adapter did not read, so even `write_to_file` carried no path. All three are now `file.modified` with the file's path. The hook adapter and `beacon endpoint antigravity sync` classify Antigravity tools from one table, so a call reads the same on either path.
+- **A skipped backfill also covers runtimes added later** · An install or connect with `--no-backfill` or `BEACON_BACKFILL=0` floors each session-store runtime that existed then, so a session sync does not read the 30 days the operator opted out of. A runtime a later upgrade added had no floor and no cursor, so the first session sync read and, on a connected endpoint, forwarded its whole 30-day window. Such a runtime now reads from the earliest recorded floor.
+- **`devin sync --watch` no longer records hooked sessions twice** · The watch computed which sessions the Devin hooks already cover once, at start, so a session the hooks began recording afterwards had its prompts and tool events written again by every sweep. Coverage is now read again before each sweep; `antigravity sync --watch` does the same.
- **Inventory names each MCP server's package and each skill's source** · An inventory snapshot knew an MCP server or skill only by its configured name, which several Beacon Intel artifacts can share. Each MCP server record now carries `package` (`npm:<name>` or `pypi:<name>`, no version) and `package_registry` `public` when its launch command runs a package from the public registry. When the command, the server's env, or the npm, pip or uv configuration in the home, the system's locations or the project a server runs in points that ecosystem elsewhere, `package_registry` is `private` and the name stays off the record. On Windows that configuration includes the per-user `AppData` and machine `ProgramData` locations even when the scanning job's environment does not name them. A skill the skills CLI (`npx skills add`) installed from GitHub carries `intel_key`, `skill:<owner>/<repo>#<name>`, from the CLI's `~/.agents/.skill-lock.json`; a lock beside a repository's own skills is ignored, since the repository could claim any source. The system inventory job runs as root, so it reads that configuration in a short-lived child process running as the console user with their groups: what the user's own launchers cannot read, Beacon does not either, and a snapshot never reflects a file only root can see. Configuration that exists but cannot be read (a file or folder the user may not open, a folder macOS privacy protection guards, a FIFO) holds its ecosystem back as `private`. `intel_check_installed` now checks such a skill by default, by its exact key; other skills still go by name only with `include_private_names`. Every endpoint sends one fresh snapshot after upgrading.
## November 2026
diff --git a/docs/cli/endpoint-install.mdx b/docs/cli/endpoint-install.mdx
index f2fcb681..6fd3235b 100644
--- a/docs/cli/endpoint-install.mdx
+++ b/docs/cli/endpoint-install.mdx
@@ -75,7 +75,7 @@ runtime's own session store into the runtime log, so the [local dashboard](/cli/
your recent sessions before any agent runs again. It is the same sweep each runtime's sync command
runs (`beacon endpoint claude sync`, `codex sync`, `cursor sync`, `opencode sync`, `copilot sync`,
`cline sync`, `factory sync`, `pi sync`, `prime sync`, `hermes sync`, `devin sync`, `dsh sync`,
-`fx sync`, `grok sync`, `harness2 sync`, and `integrations openclaw sessions sync`), and its events carry
+`fx sync`, `grok sync`, `antigravity sync`, `harness2 sync`, and `integrations openclaw sessions sync`), and its events carry
`harness.collection_method=poll` like theirs. It is local only and never touches the network.
The backfill is bounded so a machine with a lot of history cannot crowd live telemetry out of the
diff --git a/docs/cli/handoff.mdx b/docs/cli/handoff.mdx
index 76919b0b..2369b88a 100644
--- a/docs/cli/handoff.mdx
+++ b/docs/cli/handoff.mdx
@@ -274,7 +274,7 @@ The link event keeps the new session's id, workspace and harness, and leaves the
Two paths record the link:
- **Live hooks and plugins.** Every runtime whose prompts Beacon captures as they are sent records it: the shared prompt hook (Claude Code, Cursor, Factory Droid, Qwen Code, Kiro, Kimi Code, Devin, Muse Code, OpenHands, Grok Build, DeepSeek Harness, Hermes Agent, VS Code), Antigravity (including the prompt it recovers from its transcript when the prompt hook does not fire), the Cline, OpenCode and OpenClaw plugins, and the Pi, Oh My Pi, Prime Agent and Senpi extensions (`harness.collection_method` `hook` or `plugin`).
-- **Session-store sync.** `beacon endpoint claude sync`, `codex sync`, `opencode sync`, `cline sync`, `pi sync`, `prime sync`, `factory sync`, `copilot sync`, `hermes sync`, `dsh sync`, `fx sync`, `grok sync`, `openclaw sessions sync` and `cursor sync` record it when they read the prompt back from the runtime's store (`harness.collection_method: poll`).
+- **Session-store sync.** `beacon endpoint claude sync`, `codex sync`, `opencode sync`, `cline sync`, `pi sync`, `prime sync`, `factory sync`, `copilot sync`, `hermes sync`, `dsh sync`, `fx sync`, `grok sync`, `antigravity sync`, `openclaw sessions sync` and `cursor sync` record it when they read the prompt back from the runtime's store (`harness.collection_method: poll`).
Codex CLI prompts reach Beacon over OTLP and through `beacon endpoint codex sync`, not a prompt hook, so a session continued in Codex is linked by the sync. The same holds for GitHub Copilot CLI, whose live path is OTLP: `beacon endpoint copilot sync` records the link. For a runtime that also has a prompt hook or plugin, a sync can record the same link the hook already did; the two carry different `collection_method` values, as every other event those runtimes report through both paths does. A sync's link has a deterministic `event.id`, so syncing again never duplicates it.
diff --git a/docs/cli/hooks.mdx b/docs/cli/hooks.mdx
index cc55fa5d..071df94d 100644
--- a/docs/cli/hooks.mdx
+++ b/docs/cli/hooks.mdx
@@ -75,7 +75,7 @@ Beacon validates the embedded `beacon-hooks` binary before writing hook configur
beacon endpoint hooks install --harness cursor
```
-The hook adapter records local endpoint events for sessions, prompt submission, tool use, command execution, MCP-like tool activity, approval decisions, permissions, diffs, and file edits where the selected runtime exposes those hook payloads. Antigravity hooks cover `SessionStart`, `PreToolUse`, `PostToolUse`, and `Stop`; Antigravity's prompt is recovered from the session transcript on the first tool call, so only the first prompt of a session is recorded. Claude Code hooks cover `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`, `SubagentStart`, `SubagentStop`, `PermissionRequest`, and `SessionEnd`. Codex CLI uses `SessionStart` for metadata-only OS-user context; Codex prompt, tool, and token telemetry still comes from its local OpenTelemetry export path, and inventory comes from the scheduled inventory job rather than a hook. Devin CLI hooks cover `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PermissionRequest`, `PostToolUse`, `Stop`, and `SessionEnd`. Devin Desktop hooks use Cascade/Windsurf payloads for prompt submission, file writes, command execution, MCP tool use, and file reads. Factory hooks cover `SessionStart`, `UserPromptSubmit`, `PostToolUse` for write/edit/create operations, `Stop`, and `SessionEnd`. Grok Build hooks cover `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`, and `SessionEnd`. Hermes Agent hooks cover session lifecycle, `pre_llm_call`, `pre_tool_call`, `post_tool_call`, approval request and response, and subagent stop events. OpenCode hooks use Beacon's managed local plugin to forward `chat.message`, session, command, permission, diff, and error events. Cline hooks use Beacon's managed local plugin to forward `beforeRun`, `beforeTool`, `afterTool`, and `afterRun`, and also accept Cline's file-based hook names (`TaskStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`) so one adapter serves both of Cline's hook surfaces.
+The hook adapter records local endpoint events for sessions, prompt submission, tool use, command execution, MCP-like tool activity, approval decisions, permissions, diffs, and file edits where the selected runtime exposes those hook payloads. Antigravity hooks cover `SessionStart`, `PreInvocation`, `PreToolUse`, `PostToolUse`, and `Stop`; `PreInvocation` runs before every model call, and Beacon records the turn's prompt from its first call of each turn, so every prompt is recorded once. Claude Code hooks cover `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`, `SubagentStart`, `SubagentStop`, `PermissionRequest`, and `SessionEnd`. Codex CLI uses `SessionStart` for metadata-only OS-user context; Codex prompt, tool, and token telemetry still comes from its local OpenTelemetry export path, and inventory comes from the scheduled inventory job rather than a hook. Devin CLI hooks cover `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PermissionRequest`, `PostToolUse`, `Stop`, and `SessionEnd`. Devin Desktop hooks use Cascade/Windsurf payloads for prompt submission, file writes, command execution, MCP tool use, and file reads. Factory hooks cover `SessionStart`, `UserPromptSubmit`, `PostToolUse` for write/edit/create operations, `Stop`, and `SessionEnd`. Grok Build hooks cover `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`, and `SessionEnd`. Hermes Agent hooks cover session lifecycle, `pre_llm_call`, `pre_tool_call`, `post_tool_call`, approval request and response, and subagent stop events. OpenCode hooks use Beacon's managed local plugin to forward `chat.message`, session, command, permission, diff, and error events. Cline hooks use Beacon's managed local plugin to forward `beforeRun`, `beforeTool`, `afterTool`, and `afterRun`, and also accept Cline's file-based hook names (`TaskStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`) so one adapter serves both of Cline's hook surfaces.
### Examples
diff --git a/docs/cli/token-usage.mdx b/docs/cli/token-usage.mdx
index e36f3843..cc789910 100644
--- a/docs/cli/token-usage.mdx
+++ b/docs/cli/token-usage.mdx
@@ -56,11 +56,14 @@ from. A turn with no token attribution is a turn whose runtime never reported an
| GitHub Copilot CLI | input, output, cache read, cache creation, reasoning | Reported (`cost_usd`) for sessions started on or after 2026-06-01, from AI credits | Yes | Yes |
| OpenClaw Gateway | input, output, cache read, cache creation | Not reported on the hook | Yes, per model response | Yes |
| Gemini CLI | input, output, cache read, reasoning | Not emitted by Gemini CLI | Yes, per model response | When local user context is present |
+| Antigravity CLI | input, output, cache read | Not reported by Antigravity | Yes, per model response from `beacon endpoint antigravity sync` | Yes |
OpenClaw reports usage on its `llm_output` hook, which is a *conversation* hook -- OpenClaw withholds those from every non-bundled plugin until `plugins.entries.beacon-endpoint.hooks.allowConversationAccess` is set in its config. An OpenClaw endpoint collecting prompts, tools, commands and files while reporting no tokens at all is almost always that key, and `beacon endpoint hooks status --harness openclaw` says so. OpenClaw does compute a per-turn price, from an operator-configured cost table rather than from a provider report, so Beacon does not record it as a reported cost. The session-file sync, `beacon endpoint integrations openclaw sessions sync`, reads the usage OpenClaw commits on each assistant message and needs no grant. See [OpenClaw Gateway](/runtimes/openclaw-gateway).
Hermes Agent and Factory Droid report usage only through their session-store sync: neither runtime's hooks carry a token count, so their usage arrives when `beacon endpoint hermes sync` or `beacon endpoint factory sync` runs. Both keep running session totals, which the sync differences into deltas. Until the sync runs, the coverage report lists them as `silent`, with a note naming the command.
+Antigravity CLI is the same case with per-response counts: its hooks carry no token count, but every planner response it commits to its transcript records `input_tokens`, `cache_read_tokens` and `output_tokens`, and `beacon endpoint antigravity sync` records them once per response. Antigravity is Gemini-backed and Gemini's input count includes cached content, so Beacon stores input minus the cache reads (unless the input is smaller than they are). Until the sync runs, the coverage report lists Antigravity CLI as `silent`, with a note naming the command.
+
Gemini CLI reports each model response on its `gemini_cli.api_response` log record and again on the `gemini_cli.token.usage` counter, under Gemini's own counts rather than the semconv names. Those counts are not disjoint: Gemini's input (`promptTokenCount`) already includes the cached content, its output (`candidatesTokenCount`) leaves out thinking tokens, and its tool-use prompt tokens are input that the prompt count does not hold. Beacon therefore records input as prompt minus cached plus tool-use prompt, cache read as the cached count, and output as candidates plus thoughts with the thoughts as its reasoning breakdown, so a response's Beacon total equals Gemini's own `total_token_count`. Gemini also restates input and output on a `gen_ai.client.inference.operation.details` record; Beacon reads usage only from `api_response`, so a response is counted once, and the counter is de-duplicated against the log because both carry Gemini's `session.id`. These shapes are pinned from Gemini CLI's telemetry source rather than from a recorded session.
Cline reports usage once per task rather than per model call, because Beacon's rollups sum `gen_ai.usage` across events and reporting at both granularities would count every token twice. fx reports cumulative totals, which Beacon differences into per-turn deltas for the same reason, and so does a Harness² Codex rollout, whose `turn.completed` carries the thread total. GitHub Copilot CLI reports assistant message output tokens and cumulative shutdown model totals; Beacon records the message output directly, then differences shutdown totals for input, cache, reasoning, and any output not already counted. Cost comes from the shutdown's session-wide `totalNanoAiu`, differenced the same way and converted at one AI credit = 10^9 nano-AIU = US$0.01. It is recorded once per shutdown: on the model's usage event when the shutdown names one model, otherwise on one usage event with no model, so a multi-model session is not counted once per model. Sessions started before GitHub moved Copilot to AI credits on 2026-06-01 were billed per premium request, so they record no cost; the raw nano-AIU total stays in `raw.copilot`. Annual Copilot Pro and Pro+ subscribers stay on premium-request billing until their plan renews, and the session record does not say which plan applies, so for them the recorded cost is what the session would cost in AI credits rather than their bill.
@@ -96,7 +99,7 @@ A runtime that reports occupancy and no spend still shows as `not_instrumented`
| Runtime | Why |
|---------|-----|
| Cursor | No hook payload carries a token count. Cursor does report context occupancy on `preCompact`, which is recorded separately -- see [Context occupancy](#context-occupancy) below |
-| Antigravity CLI, Grok Build, Devin CLI, Devin Desktop | No token counts on the hook payloads Beacon receives |
+| Grok Build, Devin CLI, Devin Desktop | No token counts on the hook payloads Beacon receives |
| Muse Code | Usage arrives on `PostLLMCall` and in Muse's own session log, neither of which Beacon reads. See [Muse Code](/runtimes/muse-code) |
| Qwen Code | The `Stop` payload carries session-level context counters, not per-call usage. Those counters are recorded as context occupancy rather than spend -- see [Context occupancy](#context-occupancy) below. See [Qwen Code](/runtimes/qwen-code) |
| OpenHands | None of the six hook payloads carries token counts, and OpenHands exposes no other hook that would. See [OpenHands](/runtimes/openhands) |
diff --git a/docs/runtimes/antigravity-cli.mdx b/docs/runtimes/antigravity-cli.mdx
index 0f51e882..4419bc8f 100644
--- a/docs/runtimes/antigravity-cli.mdx
+++ b/docs/runtimes/antigravity-cli.mdx
@@ -19,7 +19,20 @@ Before enabling Antigravity hooks, make sure:
## Collection path
-Antigravity invokes Beacon's hook adapter from Antigravity hook configuration. The adapter writes normalized endpoint events to the configured runtime JSONL log.
+Beacon collects Antigravity CLI two ways:
+
+- **Hooks.** Antigravity invokes Beacon's hook adapter from Antigravity hook configuration. The adapter writes normalized endpoint events to the configured runtime JSONL log as they happen.
+- **Session sync.** `beacon endpoint antigravity sync` (alias `antigravity-cli`) reads the conversations Antigravity keeps under `~/.gemini/antigravity-cli/brain/<conversationId>/.system_generated/logs/transcript_full.jsonl`, with each conversation's working directory from `~/.gemini/antigravity-cli/conversation_summaries.db`, and writes events marked `harness.collection_method=poll` under the same session id the hooks use. It records prompts, agent messages and reasoning, tool calls, commands with exit code and output, file reads and edits, and per-response token usage. The install-time backfill and the scheduled session sync run it too, so conversations from before the hooks were installed are recorded.
+
+For a conversation the hooks already recorded, sync writes only what the hooks cannot see: agent messages, reasoning, and token usage from the point the hooks started reporting it, plus any prompt the hooks did not record. Prompts are matched to the hooks' by content hash, so the later prompts of a conversation recorded by v1.3.60 hooks, or a turn whose `PreInvocation` hook failed, are still backfilled; a prompt identical to one the hooks recorded in the same conversation counts as recorded. Prompts and tool events from before the hooks started are backfilled too. Sync runs after the fact, so it cannot hold, allow, or deny a tool call.
+
+```bash title="Preview, run, and inspect Antigravity session sync"
+beacon endpoint antigravity sync --print # map conversations without writing or moving the cursor
+beacon endpoint antigravity sync # write new events to the runtime log
+beacon endpoint antigravity status # conversations found and collected
+```
+
+Use `--brain-dir` to read another brain directory.
## Discovery and status
@@ -47,13 +60,15 @@ Beacon writes user-level Antigravity hooks to `~/.gemini/config/hooks.json` and
| Area | Support |
|------|---------|
-| Prompt telemetry | The first prompt in a session can be recovered from the transcript by `PreToolUse`. Sessions without tool calls do not use this fallback |
-| Session, command, tool, and file telemetry | Uses `SessionStart`, `PreToolUse`, `PostToolUse`, and `Stop`, where Antigravity emits those hooks and exposes the corresponding payloads |
+| Prompt telemetry | Every prompt, recorded by `PreInvocation`. Antigravity runs that hook before each model call and counts the calls from 0 again at the start of every turn, so Beacon records the turn's prompt (`lastUserInput`) on call 0 only, resumed conversations included |
+| Session, command, tool, and file telemetry | Uses `SessionStart`, `PreToolUse`, `PostToolUse`, and `Stop`, where Antigravity emits those hooks and exposes the corresponding payloads. `run_command` is a command; `view_file`, `list_dir`, `grep_search`, and `find_by_name` are file reads; `write_to_file`, `replace_file_content`, and `multi_replace_file_content` are file edits with the `TargetFile` path. Antigravity runs `SessionStart` only for a new conversation, not when one is resumed. `Stop` records the end of each turn |
+| Agent messages, reasoning, and token usage | From session sync only: Antigravity's hook payloads carry no response text, reasoning, or token counts. Token usage records input, output, and cache-read tokens per model response |
+| History from before the hooks | From session sync, including the install-time backfill |
| Approvals | Not recorded or synthesized. The `PreToolUse` hook writes nothing to stdout, so Antigravity's own permission settings decide every call: Antigravity reads a hook's `allow` as approving the call automatically and an object without a decision as a deny. A deny from a `BEACON_POLICY_PROVIDER` policy provider still returns `{"decision":"deny"}` |
| Local JSONL and dashboard | Supported |
| MDM deployment | Supported for the endpoint agent. Antigravity hooks are installed separately in the logged-in user's context or project context |
-Antigravity can invoke a pre-tool hook before its transcript file contains readable prompt text. Beacon waits until the transcript is available before marking `prompt.submitted` as emitted, so the next hook in the same session can still record the prompt event. Beacon remembers that a session's first prompt was recorded for 14 days, so a conversation resumed within that time does not record it again.
+Hooks written by Beacon v1.3.60 have no `PreInvocation` handler. For them, the first prompt of a session is recovered from the transcript on its first tool call, and later prompts are not recorded; package repair, or rerunning `beacon endpoint hooks install --harness antigravity` at the same level, adds the handler. Beacon remembers that a session's first prompt was recorded for 14 days, so neither path records it again when a conversation is resumed within that time.
## Deployment notes
diff --git a/docs/runtimes/index.mdx b/docs/runtimes/index.mdx
index d2927aea..5317ba11 100644
--- a/docs/runtimes/index.mdx
+++ b/docs/runtimes/index.mdx
@@ -20,7 +20,7 @@ These integrations are grouped by where the agent runs and how telemetry is coll
| Agent harness | Collection path | Telemetry coverage |
|----------------|-----------------|--------------------|
-| [Antigravity CLI](/runtimes/antigravity-cli) | Native hooks | Session, pre-tool, post-tool, stop, command, and file telemetry where Antigravity exposes hook payloads. Prompt capture is limited to the first prompt of a session, recovered from the transcript on its first tool call |
+| [Antigravity CLI](/runtimes/antigravity-cli) | Native hooks plus poll of `~/.gemini/antigravity-cli/brain` through `beacon endpoint antigravity sync` | Hooks: session, prompt (once per turn, from `PreInvocation`), tool, stop, command, and file telemetry. Poll: historical prompts, agent messages, reasoning, tool results, commands, files, and token usage; for conversations the hooks recorded, only messages, reasoning, tokens, and prompts the hooks missed |
| [Claude Code](/runtimes/claude-code) | Local OTLP export plus optional hooks and poll of `~/.claude/projects` through `beacon endpoint claude sync` | OTLP/hooks: prompt, command, tool, file, lifecycle, subagent, permission, token, and cost telemetry. Poll: historical prompts, assistant messages, tool results, commands, files, MCP-shaped activity, sidechains, and session lifecycle where persisted |
| [Cline](/runtimes/cline) | Managed plugin hooks plus optional poll of Cline's local task/session stores through `beacon endpoint cline sync` | Plugin: prompts, task lifecycle, tool lifecycle, commands, file reads and edits with diffs, MCP activity, and token usage. Poll: historical prompts, assistant messages, reasoning, tool results, commands, files, MCP-shaped activity, and token counts where persisted |
| [Codex CLI](/runtimes/codex-cli) | Local OTLP logs, selective usage trace, endpoint hooks, and poll of `~/.codex/sessions` through `beacon endpoint codex sync` | OTLP/hooks: session, prompt, approval, and tool-result activity plus per-user/session/model turn token usage. Poll: historical prompts, assistant messages, commands, files, tool calls, MCP-shaped activity, and token snapshots where persisted |
diff --git a/pkg/asymptoteobserve/antigravity.go b/pkg/asymptoteobserve/antigravity.go
new file mode 100644
index 00000000..2faa4b58
--- /dev/null
+++ b/pkg/asymptoteobserve/antigravity.go
@@ -0,0 +1,73 @@
+package asymptoteobserve
+
+import "strings"
+
+// Antigravity CLI's own vocabulary, shared by the live hook adapter and the session-store
+// collector so a prompt, a tool call and its path read the same whichever path recorded them.
+
+// IsAntigravityUserInput reports whether an Antigravity transcript step is something the user
+// typed: a USER_INPUT step, or any step whose source is USER_EXPLICIT. The hook adapter's
+// first-prompt fallback and the session-store collector both read prompts by this rule, so they
+// agree on which steps are prompts.
+func IsAntigravityUserInput(source, stepType string) bool {
+ return strings.EqualFold(stepType, "USER_INPUT") || strings.EqualFold(source, "USER_EXPLICIT")
+}
+
+// AntigravityPrompt returns the user's text from an Antigravity prompt, wherever it was read: a
+// USER_INPUT step's content, or a hook payload's lastUserInput. It is the text inside
+// <USER_REQUEST>, without the ADDITIONAL_METADATA and USER_SETTINGS_CHANGE blocks Antigravity writes
+// around it, trimmed; text with no <USER_REQUEST> is returned trimmed. Every path normalizes a
+// prompt through it, so the same prompt has the same content hash on the hook and the sync path.
+func AntigravityPrompt(content string) string {
+ if start := strings.Index(content, "<USER_REQUEST>"); start >= 0 {
+ content = content[start+len("<USER_REQUEST>"):]
+ if end := strings.Index(content, "</USER_REQUEST>"); end >= 0 {
+ content = content[:end]
+ }
+ }
+ return strings.TrimSpace(content)
+}
+
+// AntigravityToolAction is the endpoint action a completed Antigravity tool call represents, or ""
+// for a tool that is none of command, file or MCP activity. The named tools are Antigravity's
+// documented ones (https://antigravity.google/docs/hooks/) plus edit_file, write_file and
+// apply_patch, which earlier Antigravity releases used. A name it does not know is classified by
+// substring: mcp, a command or shell word, read, then an edit, write, create or patch verb.
+func AntigravityToolAction(toolName string) string {
+ lower := strings.ToLower(strings.TrimSpace(toolName))
+ switch lower {
+ case "run_command":
+ return "command.executed"
+ case "view_file", "list_dir", "grep_search", "find_by_name":
+ return "file.read"
+ case "write_to_file", "replace_file_content", "multi_replace_file_content", "edit_file", "write_file", "apply_patch":
+ return "file.modified"
+ }
+ switch {
+ case strings.Contains(lower, "mcp"):
+ return "mcp.tool_invoked"
+ case strings.Contains(lower, "shell") || strings.Contains(lower, "terminal") || strings.Contains(lower, "command"):
+ return "command.executed"
+ case strings.Contains(lower, "read"):
+ return "file.read"
+ case strings.Contains(lower, "edit") || strings.Contains(lower, "write") || strings.Contains(lower, "create") || strings.Contains(lower, "patch"):
+ return "file.modified"
+ }
+ return ""
+}
+
+// antigravityPathKeys are the arguments Antigravity's file tools name their target with:
+// write_to_file, replace_file_content and multi_replace_file_content (TargetFile), view_file
+// (AbsolutePath), list_dir (DirectoryPath), grep_search (SearchPath) and find_by_name
+// (SearchDirectory).
+var antigravityPathKeys = []string{"TargetFile", "AbsolutePath", "DirectoryPath", "SearchPath", "SearchDirectory"}
+
+// AntigravityToolPath returns the file or directory an Antigravity tool call names, or "".
+func AntigravityToolPath(args map[string]interface{}) string {
+ for _, key := range antigravityPathKeys {
+ if value, ok := args[key].(string); ok && strings.TrimSpace(value) != "" {
+ return value
+ }
+ }
+ return ""
+}