Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(cli): replay Antigravity prompts in finalize-session

Peterson Salme934673694de9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7942303b..09b3fd77 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- `finalize-session --agent antigravity-cli` now replays the session's typed
+ prompts from `agy`'s `history.jsonl` before its synthetic session-end, so
+ live Antigravity sessions — whose hooks carry no prompt event — get a summary
+ page titled by the first prompt, a handoff with "Started/Last", and prompts
+ that `memory_query` and `memory_recent` can find. Only lines whose
+ conversation and workspace match the session are read; each prompt carries
+ the key `backfill` mints for it, so a repeated `--reopen` stores it once and a
+ prompt typed after the first finalize arrives with the next one. A checkout
+ the capture allowlist does not admit and `--all-owners` runs replay nothing,
+ and a missing `history.jsonl` only warns. (#1160)
- `ai-memory run` accepts `copilot` (alias `copilot-cli`) and manages GitHub
Copilot CLI as a workstream harness: a fresh session gets a generated
`--session-id`, a returning one is resumed with `--resume=<id>`, user
diff --git a/crates/ai-memory-cli/src/commands/backfill.rs b/crates/ai-memory-cli/src/commands/backfill.rs
index 74195a85..88de8778 100644
--- a/crates/ai-memory-cli/src/commands/backfill.rs
+++ b/crates/ai-memory-cli/src/commands/backfill.rs
@@ -663,6 +663,79 @@ async fn import_exported_transcript(
Ok(content)
}
+/// Replay only the user prompts of one session the server already knows,
+/// for harnesses whose live hooks carry no prompt event (Antigravity CLI).
+/// `finalize-session` sends these before its synthetic `session-end`, so the
+/// summary page and the automatic handoff are built with the prompts.
+///
+/// No session boundaries are sent: the caller owns the `session-end`, and a
+/// keyed one would be deduplicated on a later `--reopen`. Each prompt carries
+/// the same [`replay_ingest_key`] that `backfill` mints for that event, so
+/// repeated finalizes (and a backfill of the same session) store it once.
+/// Returns the number of prompts sent.
+#[allow(clippy::too_many_arguments)]
+pub(crate) async fn replay_session_prompts(
+ endpoint: &ServerEndpoint,
+ workspace: &str,
+ project: &str,
+ home: &Path,
+ cwd: &Path,
+ harness: ManagedHarness,
+ native_session_id: &str,
+) -> Result<usize> {
+ let transcript = export_transcript(harness, home, cwd, None, native_session_id, None)
+ .await
+ .with_context(|| format!("reading the {} transcript", harness.as_str()))?;
+ let items = prompt_hook_items(
+ endpoint,
+ workspace,
+ project,
+ harness,
+ native_session_id,
+ &transcript.events,
+ )?;
+ if !items.is_empty() {
+ post_hook_items(endpoint, &items).await?;
+ }
+ Ok(items.len())
+}
+
+/// The `user-prompt` hook items of a transcript, in transcript order, each
+/// dated at its own event time and keyed with [`replay_ingest_key`]. Every
+/// other event kind is dropped.
+fn prompt_hook_items(
+ endpoint: &ServerEndpoint,
+ workspace: &str,
+ project: &str,
+ harness: ManagedHarness,
+ native_session_id: &str,
+ events: &[NewWorkstreamEvent],
+) -> Result<Vec<HookItem>> {
+ let agent = harness.agent_kind().as_str();
+ let resolved = resolve_occurred_at(events);
+ let mut items = Vec::new();
+ for (event, occurred_at) in events.iter().zip(&resolved.per_event) {
+ let Some(mapped) = map_event(None, native_session_id, event, occurred_at.as_deref()) else {
+ continue;
+ };
+ if mapped.event != "user-prompt" {
+ continue;
+ }
+ items.push(hook_item(
+ endpoint,
+ workspace,
+ project,
+ agent,
+ &mapped.event,
+ native_session_id,
+ &mapped.ingest_key,
+ None,
+ mapped.body,
+ )?);
+ }
+ Ok(items)
+}
+
/// Per-event `occurred_at` resolution for one transcript, plus the session's
/// overall boundary times.
struct ResolvedOccurredAt {
@@ -1125,6 +1198,67 @@ mod tests {
);
}
+ #[test]
+ fn prompt_replay_keeps_only_user_prompts_with_backfill_keys() {
+ let endpoint = ServerEndpoint::for_hook_target("http://127.0.0.1:1".into(), None);
+ let with_id = |id: &str, mut e: NewWorkstreamEvent| {
+ e.event_id = id.to_string();
+ e
+ };
+ let events = [
+ with_id(
+ "p1",
+ event(WorkstreamEventKind::Message, Some("user"), "first ask"),
+ ),
+ with_id(
+ "a1",
+ event(WorkstreamEventKind::Message, Some("assistant"), "an answer"),
+ ),
+ with_id(
+ "t1",
+ event(WorkstreamEventKind::ToolCall, None, "run tests"),
+ ),
+ with_id(
+ "p2",
+ event(WorkstreamEventKind::Message, Some("user"), "second ask"),
+ ),
+ ];
+ let items = prompt_hook_items(
+ &endpoint,
+ "ws",
+ "proj",
+ ManagedHarness::Antigravity,
+ "sid",
+ &events,
+ )
+ .unwrap();
+ assert_eq!(items.len(), 2, "only the two user prompts are replayed");
+ for (item, (id, prompt)) in items
+ .iter()
+ .zip([("p1", "first ask"), ("p2", "second ask")])
+ {
+ let url = reqwest::Url::parse(&item.url).unwrap();
+ let query = |name: &str| {
+ url.query_pairs()
+ .find(|(key, _)| key == name)
+ .map(|(_, value)| value.into_owned())
+ };
+ assert_eq!(query("event").as_deref(), Some("user-prompt"));
+ assert_eq!(query("agent").as_deref(), Some("antigravity-cli"));
+ assert_eq!(
+ query("extension"),
+ None,
+ "a prompt is not a backfill extension"
+ );
+ assert_eq!(
+ query("ingest_key"),
+ Some(replay_ingest_key(None, "sid", "message", id)),
+ "the key matches what backfill mints for the same event"
+ );
+ assert_eq!(item.body["prompt"], prompt);
+ }
+ }
+
#[test]
fn recovery_hook_batches_respect_count_and_serialized_byte_limits() {
let endpoint = ServerEndpoint::for_hook_target("http://127.0.0.1:1".into(), None);
diff --git a/crates/ai-memory-cli/src/commands/finalize_session.rs b/crates/ai-memory-cli/src/commands/finalize_session.rs
index 46fa84cf..0b918c65 100644
--- a/crates/ai-memory-cli/src/commands/finalize_session.rs
+++ b/crates/ai-memory-cli/src/commands/finalize_session.rs
@@ -1,6 +1,9 @@
//! `ai-memory finalize-session` — manually synthesize SessionEnd for an agent.
+use std::path::Path;
+
use ai_memory_core::{AgentKind, SessionId};
+use ai_memory_workstream::ManagedHarness;
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
@@ -87,6 +90,18 @@ pub(crate) async fn finalize(
let fallback_cwd = effective_cwd(config)?;
let mut finalized = Vec::with_capacity(sessions.len());
for session in &sessions {
+ if replays_prompts(agent, args.all_owners) {
+ let cwd = session.cwd.as_deref().unwrap_or(fallback_cwd.as_str());
+ replay_prompts(
+ config,
+ &endpoint,
+ &workspace,
+ &project,
+ cwd,
+ &session.session_id,
+ )
+ .await;
+ }
post_session_end_batch(
&client,
&endpoint,
@@ -110,6 +125,52 @@ pub(crate) async fn finalize(
Ok((workspace, project, finalized))
}
+/// Antigravity CLI's live hooks carry no prompt event, so its sessions reach
+/// the server without a single prompt; its `history.jsonl` has them. Other
+/// agents capture prompts live. `--all-owners` finalizes sessions owned by
+/// other users, whose prompts this machine's history does not hold.
+fn replays_prompts(agent: AgentKind, all_owners: bool) -> bool {
+ agent == AgentKind::AntigravityCli && !all_owners
+}
+
+/// Send the session's prompts from the local transcript before its
+/// session-end, so the summary page and handoff see them. Best effort: a
+/// checkout outside the capture allowlist sends none, and any failure is a
+/// warning, leaving the session-end exactly as before.
+async fn replay_prompts(
+ config: &Config,
+ endpoint: &ServerEndpoint,
+ workspace: &str,
+ project: &str,
+ cwd: &str,
+ session_id: &str,
+) {
+ if !super::hook::admits_capture_at(&config.data_dir, Path::new(cwd)) {
+ return;
+ }
+ let Some(home) = super::run::native_home(config) else {
+ eprintln!(
+ "ai-memory: no home directory; session {session_id} is finalized without its prompts"
+ );
+ return;
+ };
+ if let Err(error) = super::backfill::replay_session_prompts(
+ endpoint,
+ workspace,
+ project,
+ &home,
+ Path::new(cwd),
+ ManagedHarness::Antigravity,
+ session_id,
+ )
+ .await
+ {
+ eprintln!(
+ "ai-memory: could not replay the prompts of session {session_id} ({error:#}); finalizing without them"
+ );
+ }
+}
+
/// List open sessions for the scope + agent via the server. An unknown
/// workspace/project fails closed server-side with a 404; that maps to
/// "nothing to finalize" here, matching the previous direct-DB behavior
@@ -277,6 +338,21 @@ mod tests {
use ai_memory_store::Store;
use tempfile::TempDir;
+ #[test]
+ fn only_own_antigravity_sessions_replay_prompts() {
+ assert!(replays_prompts(AgentKind::AntigravityCli, false));
+ assert!(
+ !replays_prompts(AgentKind::AntigravityCli, true),
+ "other owners' prompts are not in this machine's history"
+ );
+ for agent in [AgentKind::ClaudeCode, AgentKind::Codex, AgentKind::OpenCode] {
+ assert!(
+ !replays_prompts(agent, false),
+ "{agent:?} captures prompts live"
+ );
+ }
+ }
+
#[tokio::test]
async fn selects_latest_scoped_session_for_requested_agent_by_default() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index a666d2e7..0484f7cf 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -1355,6 +1355,14 @@ fn persisted_capture_mode(data_dir: &Path) -> CaptureMode {
}
}
+/// Whether this install's capture mode admits a checkout at `cwd`: the same
+/// gate a live hook applies, for callers that replay events outside a hook
+/// (`finalize-session`).
+pub(crate) fn admits_capture_at(data_dir: &Path, cwd: &Path) -> bool {
+ let marker_present = crate::marker::find_marker(&cwd.to_string_lossy()).is_some();
+ repository_admits_capture(persisted_capture_mode(data_dir), marker_present)
+}
+
fn is_tool_event(event: &str) -> bool {
matches!(
event.to_ascii_lowercase().replace(['-', '_'], "").as_str(),
@@ -1436,6 +1444,27 @@ mod tests {
assert_eq!(persisted_capture_mode(tmp.path()), CaptureMode::Denylist);
}
+ #[test]
+ fn admits_capture_at_applies_the_allowlist_to_unmarked_checkouts() {
+ let data_dir = tempfile::tempdir().unwrap();
+ let checkout = tempfile::tempdir().unwrap();
+ assert!(
+ admits_capture_at(data_dir.path(), checkout.path()),
+ "denylist mode (the default) admits any checkout"
+ );
+ std::fs::write(data_dir.path().join(CAPTURE_MODE_FILE), "allowlist\n").unwrap();
+ assert!(
+ !admits_capture_at(data_dir.path(), checkout.path()),
+ "allowlist mode admits no checkout without a marker"
+ );
+ std::fs::write(
+ checkout.path().join(".ai-memory.toml"),
+ "workspace = \"ws\"\nproject = \"proj\"\n",
+ )
+ .unwrap();
+ assert!(admits_capture_at(data_dir.path(), checkout.path()));
+ }
+
/// "The server is down": a loopback endpoint that accepts and immediately
/// closes every connection. A closed port would do, but Windows takes ~2s
/// to report a refused loopback connect, which made every test that posts
diff --git a/crates/ai-memory-cli/tests/suite/backfill_e2e.rs b/crates/ai-memory-cli/tests/suite/backfill_e2e.rs
index 7be8d0bb..3407bcea 100644
--- a/crates/ai-memory-cli/tests/suite/backfill_e2e.rs
+++ b/crates/ai-memory-cli/tests/suite/backfill_e2e.rs
@@ -517,4 +517,146 @@ mod slow {
drop(server);
}
+
+ /// Open a live Antigravity session the way its `PreInvocation` hook would.
+ async fn open_antigravity_session(client: &reqwest::Client, base: &str, cwd: &Path) {
+ let url = format!(
+ "{base}/hook?event=session-start&agent=antigravity-cli&workspace={WORKSPACE}\
+ &project={PROJECT}&session_id={AG_MINE}"
+ );
+ let status = client
+ .post(url)
+ .json(&json!({ "session_id": AG_MINE, "cwd": cwd.to_string_lossy() }))
+ .send()
+ .await
+ .expect("session-start hook")
+ .status();
+ assert!(status.is_success(), "session-start rejected: {status}");
+ }
+
+ fn finalize_antigravity(data_dir: &Path, home: &Path, cwd: &Path, base: &str, reopen: bool) {
+ let mut args = vec![
+ "finalize-session",
+ "--agent",
+ "antigravity-cli",
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ PROJECT,
+ ];
+ if reopen {
+ args.extend(["--reopen", "--session-id", AG_MINE]);
+ }
+ run_cli(&args, data_dir, home, Some(cwd), base);
+ }
+
+ async fn stored_prompts(client: &reqwest::Client, base: &str) -> usize {
+ let text = call_tool(
+ client,
+ base,
+ "memory_read_session_observations",
+ json!({
+ "workspace": WORKSPACE,
+ "project": PROJECT,
+ "session_id": AG_MINE,
+ "kinds": ["user-prompt"],
+ "limit": 100,
+ }),
+ )
+ .await;
+ let v: Value = serde_json::from_str(&text)
+ .unwrap_or_else(|e| panic!("non-JSON observations: {text}: {e}"));
+ v["observations"]
+ .as_array()
+ .unwrap_or_else(|| panic!("missing observations: {text}"))
+ .len()
+ }
+
+ /// Antigravity's live hooks carry no prompt, so `finalize-session` replays
+ /// the session's prompts from `history.jsonl` before its session-end: the
+ /// summary page is titled by the first prompt, a foreign prompt never
+ /// lands, a repeated `--reopen` stores nothing twice, and a prompt typed
+ /// after the first finalize arrives with the next one.
+ #[tokio::test]
+ async fn finalize_session_replays_antigravity_prompts_once() {
+ let data_dir = tempfile::tempdir().expect("data dir");
+ let home = tempfile::tempdir().expect("home");
+ let project = tempfile::tempdir().expect("project cwd");
+ let elsewhere = tempfile::tempdir().expect("other project");
+ let cwd = fs::canonicalize(project.path()).expect("canonicalize project cwd");
+ let other = fs::canonicalize(elsewhere.path()).expect("canonicalize other project");
+ plant_antigravity_conversation(home.path(), AG_MINE, &cwd);
+ let history = home.path().join(".gemini/antigravity-cli/history.jsonl");
+ let past = 1_780_000_000_000;
+ let mut lines = vec![
+ agy_prompt(AG_MINE, &cwd, &format!("first {AG_OWN} prompt"), past),
+ agy_prompt(
+ AG_THEIRS,
+ &other,
+ &format!("{AG_FOREIGN} elsewhere"),
+ past + 1,
+ ),
+ agy_prompt(AG_MINE, &cwd, "second prompt", past + 2),
+ ];
+ write_jsonl(&history, &lines);
+ let client = reqwest::Client::new();
+ let (server, base) =
+ start_backfill_server(&client, data_dir.path(), home.path(), &cwd).await;
+ open_antigravity_session(&client, &base, &cwd).await;
+
+ finalize_antigravity(data_dir.path(), home.path(), &cwd, &base, false);
+
+ assert_eq!(stored_prompts(&client, &base).await, 2);
+ let page = call_tool(
+ &client,
+ &base,
+ "memory_read_page",
+ json!({
+ "workspace": WORKSPACE,
+ "project": PROJECT,
+ "path": format!("sessions/{AG_MINE}.md"),
+ }),
+ )
+ .await;
+ assert!(
+ page.contains(AG_OWN),
+ "the summary page must be built from the replayed prompts: {page}"
+ );
+ if let Some(path) = tree_contains(data_dir.path(), AG_FOREIGN) {
+ panic!("{AG_FOREIGN} leaked into {}", path.display());
+ }
+
+ finalize_antigravity(data_dir.path(), home.path(), &cwd, &base, true);
+ assert_eq!(
+ stored_prompts(&client, &base).await,
+ 2,
+ "a repeated --reopen must not store the prompts twice"
+ );
+
+ lines.push(agy_prompt(AG_MINE, &cwd, "third prompt", past + 3));
+ write_jsonl(&history, &lines);
+ finalize_antigravity(data_dir.path(), home.path(), &cwd, &base, true);
+ assert_eq!(stored_prompts(&client, &base).await, 3);
+
+ drop(server);
+ }
+
+ /// A live Antigravity session without `history.jsonl` still finalizes.
+ #[tokio::test]
+ async fn finalize_session_succeeds_on_antigravity_without_history() {
+ let data_dir = tempfile::tempdir().expect("data dir");
+ let home = tempfile::tempdir().expect("home");
+ let project = tempfile::tempdir().expect("project cwd");
+ let cwd = fs::canonicalize(project.path()).expect("canonicalize project cwd");
+ plant_antigravity_conversation(home.path(), AG_MINE, &cwd);
+ let client = reqwest::Client::new();
+ let (server, base) =
+ start_backfill_server(&client, data_dir.path(), home.path(), &cwd).await;
+ open_antigravity_session(&client, &base, &cwd).await;
+
+ finalize_antigravity(data_dir.path(), home.path(), &cwd, &base, false);
+
+ assert_eq!(stored_prompts(&client, &base).await, 0);
+ drop(server);
+ }
}
diff --git a/docs/install.md b/docs/install.md
index 4dcfbf80..52e6ad0a 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -997,6 +997,17 @@ ai-memory finalize-session --agent antigravity-cli
ai-memory finalize-session --agent antigravity-cli --reopen --session-id <uuid>
```
+Antigravity's hooks carry no prompt, so before the session-end
+`finalize-session` replays the session's typed prompts from `agy`'s
+`~/.gemini/antigravity-cli/history.jsonl` (only lines whose conversation and
+workspace match the session), and the summary page and handoff are built with
+them. Each prompt is keyed as `backfill` keys it, so a re-close stores it once
+and a prompt typed after the first finalize arrives with the next. A checkout
+the capture allowlist does not admit sends none, `--all-owners` replays none
+(other users' prompts are not in this machine's history), and a missing or
+unreadable `history.jsonl` only prints a warning. `agy -p` runs write no
+`history.jsonl` line, so they have no prompt to replay.
+
### Devin CLI
Devin uses `~/.devin/config.json` for MCP servers and `~/.devin/hooks.v1.json`