Skip to content

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

Rust

fix(hooks): drain Zero's session-end in-process (#1172)

AkitaOnRails4b0f2c952209
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 87bd2d84..1fa812be 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Fixed
+- Fixed Zero's `sessionEnd` never delivering spooled events even with
+ network allowed in Zero's sandbox. Zero kills a hook's detached children
+ when the hook exits, which took the background drainer down with it. For
+ Zero, `session-end` now drains in-process within a fixed 10-second budget
+ (hard stop at 20 seconds, inside Zero's 30-second hook timeout); events
+ that cannot be delivered stay spooled. Other agents keep the detached
+ drainer. (#1172)
- Fixed generated TypeScript integrations (OpenCode, OpenCode 2, OMP,
Pi, OpenClaw) flashing a console window on Windows.
`discoverRemoteIdentity` spawned `git config --get remote.<name>.url`
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index ed2228c2..9d8d4df4 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -7,7 +7,8 @@
//! cleanup pass before fetching handoff context. `session-end` returns quickly:
//! after enqueue it spawns a detached `hook-drain` process, whose stdout/stderr
//! are redirected away from the agent, and that process drains under an
-//! exclusive spool lock with a longer bounded budget.
+//! exclusive spool lock with a longer bounded budget. Zero, whose hook sandbox
+//! kills detached children, drains in-process within a short fixed budget.
//!
//! See `docs/windows.md#native-hook-command-claude-code-on-windows`.
@@ -66,6 +67,18 @@ const MAX_BRIEFED_MARKERS: usize = 512;
/// well under a second so a `post-tool-use` hook never stalls a tool call (one
/// in-flight POST against a slow server is bounded by this too).
const INCREMENTAL_DRAIN_BUDGET: Duration = Duration::from_millis(250);
+/// Total budget, lock wait included, for a `session-end` drained in-process
+/// ([`session_end_drains_in_process`]). Fixed rather than env-overridable:
+/// together with [`IN_PROCESS_SESSION_END_DEADLINE`] it has to stay inside
+/// Zero's 30-second hook timeout.
+const IN_PROCESS_SESSION_END_DRAIN_BUDGET: Duration = Duration::from_secs(10);
+/// Hard stop for that drain, the request in flight at the budget included.
+const IN_PROCESS_SESSION_END_DEADLINE: Duration = Duration::from_secs(20);
+// Zero kills a hook after 30 seconds; the hard stop must land first.
+const _: () = assert!(
+ IN_PROCESS_SESSION_END_DRAIN_BUDGET.as_secs() < IN_PROCESS_SESSION_END_DEADLINE.as_secs()
+ && IN_PROCESS_SESSION_END_DEADLINE.as_secs() < 30
+);
/// Per-event POST timeout during a drain. Env: `AI_MEMORY_HOOK_DRAIN_TIMEOUT_MINUTES`.
fn drain_event_timeout() -> Duration {
@@ -136,6 +149,34 @@ fn should_spawn_background_drainer(event: &str) -> bool {
matches!(event, "session-end" | "stop" | "pre-compact")
}
+/// Zero runs hooks in a sandbox started with `--die-with-parent`, which kills
+/// a detached drainer the moment the hook exits, so its `session-end` drains
+/// in-process within [`IN_PROCESS_SESSION_END_DRAIN_BUDGET`] instead (#1172).
+fn session_end_drains_in_process(agent: AgentKind, event: &str) -> bool {
+ agent == AgentKind::Zero && event == "session-end"
+}
+
+/// Drain the spool from the hook process itself, for a harness that kills the
+/// detached drainer. Undelivered events stay spooled for the next boundary.
+async fn drain_session_end_in_process(
+ spool: &Path,
+ data_dir: &Path,
+ max_attempts: hook_spool::MaxAttempts,
+) {
+ let drain = hook_spool::drain_exclusive_within_budget(
+ spool,
+ data_dir,
+ IN_PROCESS_SESSION_END_DRAIN_BUDGET,
+ drain_event_timeout().min(IN_PROCESS_SESSION_END_DRAIN_BUDGET),
+ max_attempts,
+ );
+ // The budget stops new requests; this also stops one already in flight
+ // (an old server's per-event fallback, a token refresh). Cancelling only
+ // at an await point leaves every spool file whole: at worst an accepted
+ // event is re-sent and the server's ingest key skips it.
+ let _ = tokio::time::timeout(IN_PROCESS_SESSION_END_DEADLINE, drain).await;
+}
+
fn session_id_state_path(data_dir: &Path, agent: AgentKind) -> PathBuf {
data_dir
.join("hook-state")
@@ -1131,7 +1172,9 @@ where
// to flush the shared spool. `session-end` remains the primary close path,
// but `stop` and `pre-compact` also trigger the helper so delivery does not
// rely on the single hook most likely to be cancelled during agent shutdown.
- if !external_capture
+ if !external_capture && session_end_drains_in_process(agent_kind, &args.event) {
+ drain_session_end_in_process(&spool, &dd, max_attempts).await;
+ } else if !external_capture
&& should_spawn_background_drainer(&args.event)
&& let Err(err) = after_background_drain_event_enqueue(
&dd,
@@ -1520,6 +1563,26 @@ mod tests {
assert!(!should_spawn_background_drainer("user-prompt"));
}
+ #[test]
+ fn only_zero_session_end_drains_in_process() {
+ assert!(session_end_drains_in_process(
+ AgentKind::Zero,
+ "session-end"
+ ));
+ for event in ["session-start", "post-tool-use", "subagent-stop"] {
+ assert!(
+ !session_end_drains_in_process(AgentKind::Zero, event),
+ "{event}"
+ );
+ }
+ for agent in [AgentKind::ClaudeCode, AgentKind::Codex, AgentKind::Zcode] {
+ assert!(
+ !session_end_drains_in_process(agent, "session-end"),
+ "{agent:?}"
+ );
+ }
+ }
+
#[test]
fn antigravity_preinvocation_only_maps_invocation_zero_to_session_start() {
for (raw, expected) in [
@@ -2335,6 +2398,83 @@ mod tests {
}
}
+ fn zero_hook_args(event: &str, server_url: &str) -> HookArgs {
+ HookArgs {
+ event: event.into(),
+ agent: "zero".into(),
+ server_url: server_url.into(),
+ auth_token: None,
+ project_strategy: None,
+ check_capture: false,
+ capture_assistant: false,
+ capture_mode: None,
+ }
+ }
+
+ /// Zero's sandbox kills the detached drainer with the hook (#1172), so its
+ /// session-end must deliver before the hook returns.
+ #[tokio::test]
+ async fn zero_session_end_delivers_in_process_without_a_detached_drainer() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data_dir = tmp.path().to_path_buf();
+ let spool = hook_spool::spool_dir(&data_dir);
+ let (base, mut requests) = serve_requests("200 OK", r#"{"accepted":1}"#).await;
+ let mut stdout = Vec::new();
+
+ run_with_payload(
+ Some(data_dir.clone()),
+ zero_hook_args("session-end", &base),
+ r#"{"sessionId":"s","cwd":"/tmp"}"#.into(),
+ &mut stdout,
+ |_, _| panic!("zero's session-end must not spawn a detached drainer"),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(stdout, b"{}\n");
+ let request = first_request(&mut requests)
+ .await
+ .expect("drained in-process");
+ assert!(request.starts_with("POST /hook/batch"), "{request}");
+ assert_eq!(
+ hook_spool::spool_len(&spool),
+ 0,
+ "delivered event left the spool"
+ );
+ }
+
+ /// With the sandbox's network denied the in-process drain fails fast and
+ /// the event stays spooled for `hook-drain` or the next session.
+ #[tokio::test]
+ async fn zero_session_end_without_network_keeps_the_event_spooled() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data_dir = tmp.path().to_path_buf();
+ let spool = hook_spool::spool_dir(&data_dir);
+ let refused = {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ format!("http://{}", listener.local_addr().unwrap())
+ };
+ let mut stdout = Vec::new();
+
+ run_with_payload(
+ Some(data_dir.clone()),
+ zero_hook_args("session-end", &refused),
+ r#"{"sessionId":"s","cwd":"/tmp"}"#.into(),
+ &mut stdout,
+ |_, _| panic!("zero's session-end must not spawn a detached drainer"),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(stdout, b"{}\n");
+ let entries = read_spooled_entries(&spool);
+ assert_eq!(entries.len(), 1);
+ assert_eq!(
+ entries[0].attempts, 0,
+ "an unreachable server costs no retry"
+ );
+ }
+
#[tokio::test]
async fn session_end_run_spawn_failure_keeps_event_queued_and_stdout_clean() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 87d2f12d..3f426535 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -6364,8 +6364,10 @@ pub(crate) fn zero_install_notes(data_dir: impl std::fmt::Display) -> String {
# \"sandbox\": {{\"network\": \"allow\",\n\
# \"additionalWriteRoots\": [\"{}\"]}}\n\
# (network allow applies to every Zero shell command), or\n\
- # \"sandbox\": {{\"enabled\": false}}. Otherwise run `ai-memory\n\
- # hook-drain` from a normal shell to deliver spooled events.\n",
+ # \"sandbox\": {{\"enabled\": false}}. With network allowed,\n\
+ # sessionEnd delivers in-process (the sandbox kills detached\n\
+ # drainers). Otherwise run `ai-memory hook-drain` from a\n\
+ # normal shell to deliver spooled events.\n",
data_dir
)
}
@@ -8314,6 +8316,7 @@ command = "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/a
);
assert!(notes.contains(r#""enabled": false"#), "{notes}");
assert!(notes.contains("hook-drain"), "{notes}");
+ assert!(notes.contains("sessionEnd delivers in-process"), "{notes}");
assert!(notes.lines().all(|l| l.starts_with('#')), "{notes}");
}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 65a664af..a6c2491d 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -49,7 +49,9 @@ from hook paths.
with a short timeout. Native `ai-memory hook --event ...` commands spool
events locally with a stable per-entry idempotency key, do a short bounded
cleanup at session start, and hand
- session-end delivery to a detached lock-aware `hook-drain` helper;
+ session-end delivery to a detached lock-aware `hook-drain` helper (Zero,
+ whose hook sandbox kills detached children, drains in-process within a
+ fixed 10-second budget instead);
high-latency operators can raise the drain/handoff/background caps with
minute-based env vars.
Agent hot paths never block on the network; saturated servers return HTTP
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index cc27743d..44ad1139 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -803,8 +803,10 @@ it), and ai-memory does not edit that file. Either add
```
(network access is all-or-nothing and applies to every shell command Zero
-runs, not only hooks), or set `"sandbox": {"enabled": false}`. Without
-either, run `ai-memory hook-drain` from a normal shell to deliver the
+runs, not only hooks), or set `"sandbox": {"enabled": false}`. With network
+allowed, `sessionEnd` delivers the spool from the hook process itself within a
+fixed 10-second budget, because the sandbox would kill the detached drainer
+other agents use; whatever does not make it stays spooled. Without either, run `ai-memory hook-drain` from a normal shell to deliver the
spooled events. A leftover empty `hook-spool/.drain.lock` does not block
that drain: the lock is an OS file lock released when its holder exits.
diff --git a/docs/support-matrix.md b/docs/support-matrix.md
index d9fdb92c..e0624903 100644
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@ -30,7 +30,7 @@
| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). Only `PreInvocation` with `invocationNum = 0` maps to SessionStart; later model calls cannot consume a next-session handoff. No automatic true session-end hook, so run `ai-memory finalize-session --agent antigravity-cli` after the final turn when you need a summary, handoff, and opt-in SessionEnd consolidation; an interactive session launched with `ai-memory run antigravity` is finalized automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `ai-memory run antigravity` (aliases `antigravity-cli`, `agy`) adds managed workstream resume via `--conversation`; its conversation store is not decoded, so the ledger takes user prompts from `agy`'s `history.jsonl` (only this conversation's lines typed in this checkout) and assistant and tool steps from hook capture. Tool outputs (`run_command`, `view_file`, `list_dir`, etc.) are resolved directly from `.system_generated/steps/<stepIdx>/output.txt` during `post-tool-use` while mutation tools preserve code from arguments (#966). |
| Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works. `SessionStart` and `UserPromptSubmit` do not accept the handoff (Grok discards that stdout). The first `PostToolUse` prints `hookSpecificOutput.additionalContext` with the pending handoff and an opted-in `[briefing]`; the model sees it after that tool result. If no tool runs, recover via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. `ai-memory run grok` adds managed workstream resume with the context packet delivered natively through `--rules`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). |
| Swival CLI | MCP-only | `install-mcp --client swival --apply` merges a native HTTP entry into the project-root `.swival/mcp.json`, preserving sibling servers. Lifecycle and managed-workstream support are not claimed because Swival's callback contract does not expose a stable session identifier. |
-| Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. Zero runs hooks in its sandbox, which by default denies network (loopback too) and writes outside the workspace, so events stay in the hook spool: allow `sandbox.network` and add the ai-memory data dir to `sandbox.additionalWriteRoots` in the global `~/.config/zero/config.json` (network allow covers every Zero shell command), or run `ai-memory hook-drain` from a normal shell (see [`mcp-install.md`](mcp-install.md#zero-gitlawbzero)). |
+| Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. Zero runs hooks in its sandbox, which by default denies network (loopback too) and writes outside the workspace, so events stay in the hook spool: allow `sandbox.network` and add the ai-memory data dir to `sandbox.additionalWriteRoots` in the global `~/.config/zero/config.json` (network allow covers every Zero shell command; `sessionEnd` then delivers in-process within a fixed 10-second budget, since the sandbox kills detached drainers), or run `ai-memory hook-drain` from a normal shell (see [`mcp-install.md`](mcp-install.md#zero-gitlawbzero)). |
| ZCode | Supported | `install-mcp --client zcode --apply` merges a native HTTP entry (strict schema: `type`/`url`/`headers` only) into the `mcp.servers` map of `~/.zcode/cli/config.json`, preserving sibling servers. ZCode (z.ai, `zcode`, alias `zai`). Lifecycle-hook capture via `install-hooks --agent zcode --apply`: exec-form native commands (`type: "process"`, no shell) merged into the root `hooks` block of `~/.zcode/cli/config.json` around any third-party hooks; native commands enforce capture exclusions. Six documented triggers (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`); `PostToolUseFailure` fires instead of `PostToolUse` when a tool throws and lands on the same capture channel with the error preserved. `PermissionRequest` is deliberately not installed — its hook chain races the interactive permission client, so passive capture of that event is unreliable by design. No true session-end — `Stop` is a per-turn boundary, so run `ai-memory finalize-session --agent zcode` after the final turn. Unlike Pool and Zero, `SessionStart` stdout injection works (`hookSpecificOutput.additionalContext`, verified live against the embedded engine v0.16.5), so the prior session's handoff is delivered automatically. No first-party `install-mcp` client and no managed workstream are claimed yet. |
| Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 10 events including subagent start/stop and `PostToolUseFailure` for tool-failure capture); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `UserPromptSubmit` stdout (Kimi Code discards `SessionStart` hook stdout); `ai-memory run kimi` adds managed workstream resume. |
| Kiro CLI | Supported | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges v2 hooks into existing agent configs; the explicit `--agent kiro-cli-v3` target writes the incompatible standalone v3 registration. Both preserve unrelated entries, honor `$KIRO_HOME`, enforce capture exclusions, and inject pending handoffs at session start. Kiro has no true SessionEnd hook; use `ai-memory finalize-session --agent kiro-cli`, with `--session-id <uuid>` for concurrent sessions, unless it is an interactive session launched with `ai-memory run kiro`, which finalizes it automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `ai-memory run kiro` manages v2; add `--v3`, `--mode`, or `--agent-engine v3` for version-safe v3 resume. |