Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(hooks): add ZCode (z.ai) lifecycle-hook integration (#512) (#532)
Bruno Costa3f0af7d9ac82
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 57cffc06..281cc02c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- ZCode (z.ai) lifecycle-hook integration as `install-hooks --agent zcode`+ (alias `zai`), following the Zero model: exec-form native commands+ (`type: "process"`, no shell) merged into the root `hooks` block of+ `~/.zcode/cli/config.json` around third-party hooks, covering the six+ documented triggers (`SessionStart`, `UserPromptSubmit`, `PreToolUse`,+ `PostToolUse`, `PostToolUseFailure`, `Stop`) with capture exclusions+ enforced natively (#512). `PermissionRequest` is deliberately not+ installed — its hook chain races the interactive permission client, so+ passive capture of that event is unreliable — and there is no true+ session-end, so finished sessions are closed with+ `ai-memory finalize-session --agent zcode`. 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.+## [1.37.0] - 2026-08-30### Addeddiff --git a/README.md b/README.mdindex 9b71446d..05b27f66 100644--- a/README.md+++ b/README.md@@ -43,6 +43,7 @@| 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. `ai-memory run kiro` manages v2; add `--v3`, `--mode`, or `--agent-engine v3` for version-safe v3 resume. || Pool | Hooks-only | Poolside Agent CLI (`pool`). Lifecycle-hook capture via `install-hooks --agent pool` (alias `poolside`): Pool reads project-scoped hooks from the repo-root `.poolside/settings.yaml`, so ai-memory stages the scripts and prints a ready-to-paste `hooks:` snippet rather than writing project-local files; native commands enforce capture exclusions. Five Claude-shaped events (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `Stop`) and no true session-end — `Stop` is a turn boundary, so run `ai-memory finalize-session --agent pool` after the final turn. `SessionStart` stdout injection is not demonstrated, so capture works but handoff injection does not — recover handoffs via MCP `memory_handoff_accept`. No first-party `install-mcp` client and no managed workstream (`ai-memory run pool`) are claimed: Pool's native session-store contract is not demonstrated (see [`docs/managed-harness-contributions.md`](docs/managed-harness-contributions.md)). Verified against Poolside CLI v1.0.16. |+| ZCode | Hooks-only | 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. || VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). || Zed | MCP-only | Native remote MCP under `context_servers` in Zed's user `settings.json`; no lifecycle hooks or managed-workstream support. || Hermes Agent | Community | Core hook ingestion recognizes `agent=hermes` and Hermes' documented shell-hook `tool_name` / `tool_input` payload for concrete session attribution, tool-family titles, and capture exclusions. A community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) is available, but no first-party installer is shipped; review its compatibility matrix, install/uninstall scripts, and secret handling before using it. Hermes ignores session-start hook stdout, so recover handoffs through MCP. |@@ -172,7 +173,8 @@ priors are at the [bottom](#influences-and-prior-art)./ OMP (`omp` / `oh-my-pi`), Pi via generated bridge extension, VS CodeGitHub Copilot agent mode (MCP-only, workspace `.vscode/mcp.json`), Kiro CLI(MCP + v2 lifecycle hooks), Pool (hooks-only, project- `.poolside/settings.yaml` snippet), and Zed (MCP-only, user `settings.json`).+ `.poolside/settings.yaml` snippet), ZCode (hooks-only, exec-form native+ commands in `~/.zcode/cli/config.json`), and Zed (MCP-only, user `settings.json`).Server runs local (loopback) OR on a homelab box (LAN/VPN/cloud)with bearer-token auth. Shared servers can opt into[`[auto_scope]` modes](docs/auto-scope.md) for per-user or@@ -509,6 +511,10 @@ ai-memory install-hooks --agent claude-code --apply# Pool (Poolside Agent CLI) example — stages scripts and prints the# .poolside/settings.yaml snippet to paste into each repo (no MCP client yet):# ai-memory install-hooks --agent pool --apply+# ZCode (z.ai) example — merges exec-form native commands into the root+# hooks block of ~/.zcode/cli/config.json (handoff injection works; no true+# session-end, so run `ai-memory finalize-session --agent zcode` at the end):+# ai-memory install-hooks --agent zcode --apply```On Linux/macOS, that's it. Start a Claude Code session as usual - everydiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 2a77f5d3..a6ee88c0 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -1139,6 +1139,17 @@ pub enum AgentChoice {/// session-end event).#[value(alias = "poolside")]Pool,+ /// ZCode (z.ai) — JSON-config lifecycle hooks in the root `hooks` block+ /// of `~/.zcode/cli/config.json` (the same file `install-mcp --client+ /// zcode` registers MCP servers in). Entries are exec-form+ /// `type: "process"` (`command` + `args`, no shell), so ai-memory's+ /// native `hook` command runs directly. ZCode injects `SessionStart`+ /// stdout as model context (`hookSpecificOutput.additionalContext`,+ /// verified live against engine v0.16.5), so handoff delivery works.+ /// `Stop` fires at the end of every turn and there is no `SessionEnd`,+ /// so close sessions with `ai-memory finalize-session --agent zcode`.+ #[value(alias = "zai")]+ Zcode,}impl AgentChoice {@@ -1167,6 +1178,7 @@ impl AgentChoice {Self::KiroCli | Self::KiroCliV3 => AgentKind::KiroCli,Self::CommandCode => AgentKind::CommandCode,Self::Pool => AgentKind::Pool,+ Self::Zcode => AgentKind::Zcode,}}@@ -1178,7 +1190,9 @@ impl AgentChoice {#[must_use]pub const fn script_hook_subdir(self) -> Option<&'static str> {match self {- Self::OpenCode | Self::Pi | Self::Omp | Self::Openclaw | Self::Zero => None,+ Self::OpenCode | Self::Pi | Self::Omp | Self::Openclaw | Self::Zero | Self::Zcode => {+ None+ }_ => Some(self.kind().as_str()),}}@@ -1188,7 +1202,8 @@ impl AgentChoice {#[derive(Debug, Args)]pub struct FinalizeSessionArgs {/// Agent kind to finalize. Defaults to Codex for backward compatibility;- /// Codex, Antigravity CLI, and Pool have no reliable true SessionEnd hook.+ /// Codex, Antigravity CLI, Pool, and ZCode have no reliable true+ /// SessionEnd hook.#[arg(long, value_enum, default_value_t = AgentChoice::Codex)]pub agent: AgentChoice,/// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's@@ -2475,6 +2490,34 @@ mod tests {assert_eq!(args.agent, AgentChoice::Pool);}+ #[test]+ fn zcode_hook_and_finalize_aliases_parse() {+ for alias in ["zcode", "zai"] {+ let cli = Cli::try_parse_from([+ "ai-memory",+ "install-hooks",+ "--agent",+ alias,+ "--server-url",+ "http://127.0.0.1:49374",+ ])+ .unwrap_or_else(|error| panic!("failed to parse ZCode alias {alias}: {error}"));+ let Command::InstallHooks(args) = cli.command else {+ panic!("expected install-hooks for ZCode alias {alias}");+ };+ assert_eq!(args.agent, AgentChoice::Zcode);+ assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::Zcode);+ // Native exec-form integration: no script bundle to stage.+ assert_eq!(args.agent.script_hook_subdir(), None);+ }+ let cli = Cli::try_parse_from(["ai-memory", "finalize-session", "--agent", "zcode"])+ .expect("failed to parse finalize-session --agent zcode");+ let Command::FinalizeSession(args) = cli.command else {+ panic!("expected finalize-session for zcode");+ };+ assert_eq!(args.agent, AgentChoice::Zcode);+ }+#[test]fn command_code_mcp_and_hook_aliases_parse() {for alias in ["command-code", "commandcode", "cmdc", "cmd"] {diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex fbcdab96..09acd9ef 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -139,6 +139,20 @@ pub(crate) fn zero_hooks_path() -> anyhow::Result<std::path::PathBuf> {.join("hooks.json"))}+/// `~/.zcode/cli/config.json` — ZCode's user-scope config. The root+/// `hooks` block lives in the same file `install-mcp --client zcode`+/// registers MCP servers in; user scope runs headless with no trust+/// gate, while ZCode's workspace scopes (`.zcode/config.json`,+/// `zcode.json`) are trust-gated and off by default, so they are never+/// targeted (#512).+pub(crate) fn zcode_config_path() -> anyhow::Result<std::path::PathBuf> {+ Ok(home_dir()+ .context("could not locate $HOME for ~/.zcode/cli/config.json")?+ .join(".zcode")+ .join("cli")+ .join("config.json"))+}+/// `~/.devin/hooks.v1.json` — Devin CLI lifecycle hooks (default target).pub(crate) fn devin_hooks_path() -> anyhow::Result<std::path::PathBuf> {Ok(home_dir()@@ -447,6 +461,7 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {apply_to_grok_settings(&hooks_dir, &server_url, auth, &config.data_dir, &args)}AgentChoice::Zero => apply_to_zero_hooks(&server_url, auth, &config.data_dir, &args),+ AgentChoice::Zcode => apply_to_zcode_hooks(&server_url, auth, &config.data_dir, &args),AgentChoice::Devin => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;apply_to_devin_settings(&hooks_dir, &server_url, auth, &config.data_dir, &args)@@ -562,6 +577,7 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {render_grok(&hooks_dir, &server_url, auth, &config.data_dir, strategy)}AgentChoice::Zero => render_zero(&server_url, auth, &config.data_dir, strategy),+ AgentChoice::Zcode => render_zcode(&server_url, auth, &config.data_dir, strategy),AgentChoice::Devin => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;render_devin(&hooks_dir, &server_url, auth, &config.data_dir, strategy)@@ -701,6 +717,7 @@ fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {AgentChoice::AntigravityCli => antigravity_hooks_path().ok()?,AgentChoice::Grok => grok_hooks_path().ok()?,AgentChoice::Zero => zero_hooks_path().ok()?,+ AgentChoice::Zcode => zcode_config_path().ok()?,AgentChoice::Devin => devin_hooks_path().ok()?,AgentChoice::KimiCode => kimi_code_config_path().ok()?,AgentChoice::KiroCli => return None,@@ -1070,6 +1087,10 @@ fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {// No first-party Pool MCP installer ships yet, so there is no// config file to infer a server URL or token from.AgentChoice::Pool => None,+ // The ZCode MCP client ships with #511; until that lands there is+ // no `McpClient::Zcode` whose config the installer could scrape a+ // server URL or token from.+ AgentChoice::Zcode => None,}}@@ -4455,6 +4476,160 @@ fn render_zero(Ok(())}+/// Whether a hook entry in ZCode's `hooks.events` map is one ai-memory+/// wrote. Our entries carry a `statusMessage` starting with `ai-memory`+/// — the only schema-documented free-form key, so ownership is marked+/// without emitting keys ZCode would drop.+fn is_our_zcode_hook(hook: &serde_json::Value) -> bool {+ hook.get("statusMessage")+ .and_then(|v| v.as_str())+ .is_some_and(|msg| msg.starts_with("ai-memory"))+}++/// Merge ai-memory hooks into the root `hooks` block of ZCode's+/// user-scope `~/.zcode/cli/config.json` (#512). Sibling config keys+/// (`model`, `provider`, `mcp.servers`, …) always survive: the merge+/// touches only `hooks.enabled` (defaulted, never flipped),+/// `hooks.maxOutputBytes` (set only when absent), and `hooks.events`,+/// replaces entries ai-memory owns (idempotent re-apply), and never+/// edits matcher groups it did not write.+fn apply_to_zcode_hooks(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ args: &InstallHooksArgs,+) -> Result<()> {+ let path = match &args.config_file {+ Some(p) => p.clone(),+ None => zcode_config_path()?,+ };+ let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);+ let payload = super::render_shared::build_zcode_hooks_config(+ server_url,+ auth_token,+ Some(data_dir),+ strategy,+ );+ let our_events = payload+ .get("events")+ .and_then(|v| v.as_object())+ .context("internal: build_zcode_hooks_config didn't return an events map")?+ .clone();+ let mut hooks_disabled = false;+ let outcome = apply_atomic(&path, |existing| {+ mutate_json(existing, |root| {+ // `hooks` sits beside sibling config keys that must survive.+ let hooks = root+ .entry("hooks")+ .or_insert_with(|| serde_json::json!({}))+ .as_object_mut()+ .context("`hooks` is present in the ZCode config but not an object")?;+ hooks_disabled = hooks.get("enabled").and_then(|v| v.as_bool()) == Some(false);+ if !hooks.contains_key("enabled") {+ hooks.insert("enabled".into(), serde_json::Value::Bool(true));+ }+ // Raise the stdout ceiling above ZCode's 32 KiB default so a+ // fetched handoff is not truncated mid-JSON before injection.+ // Only when the user has not chosen their own value: the key+ // is block-level and would also bound third-party hooks.+ if !hooks.contains_key("maxOutputBytes")+ && let Some(ceiling) = payload.get("maxOutputBytes")+ {+ hooks.insert("maxOutputBytes".into(), ceiling.clone());+ }+ let events = hooks+ .entry("events")+ .or_insert_with(|| serde_json::json!({}))+ .as_object_mut()+ .context("`hooks.events` is present in the ZCode config but not an object")?;+ for (event, ours) in &our_events {+ let ours = ours+ .as_array()+ .context("internal: zcode event payload is not a matcher-group array")?;+ let slot = events+ .entry(event.clone())+ .or_insert_with(|| serde_json::Value::Array(Vec::new()));+ let slot = slot.as_array_mut().context(+ "`hooks.events.{event}` is present in the ZCode config but not an array",+ )?;+ for group in slot.iter_mut() {+ if let Some(hooks) = group+ .as_object_mut()+ .and_then(|group| group.get_mut("hooks"))+ .and_then(|v| v.as_array_mut())+ {+ hooks.retain(|hook| !is_our_zcode_hook(hook));+ }+ }+ slot.retain(|group| match group.get("hooks") {+ Some(serde_json::Value::Array(hooks)) => !hooks.is_empty(),+ _ => true,+ });+ slot.extend(ours.iter().cloned());+ }+ Ok(())+ })+ })?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ if hooks_disabled {+ eprintln!(+ "# warning: this config sets \"enabled\": false inside `hooks`, \+ so ZCode will not run ANY hooks (including ai-memory's) until \+ you re-enable them."+ );+ }+ println!("# NOTE: ZCode injects SessionStart stdout as model context, so the");+ println!("# prior session's handoff is delivered automatically.");+ println!("# NOTE: ZCode fires `Stop` at the end of every turn and has no");+ println!("# SessionEnd — close sessions with");+ println!("# `ai-memory finalize-session --agent zcode`.");+ Ok(())+}++/// Print ZCode's `hooks` block to stdout (dry-run counterpart of+/// [`apply_to_zcode_hooks`]).+fn render_zcode(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,+) -> Result<()> {+ let payload = super::render_shared::build_zcode_hooks_config(+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );+ let serialized =+ serde_json::to_string_pretty(&payload).context("serializing zcode hook config")?;+ println!("# ZCode (z.ai) hooks config — merge the `hooks` block into");+ println!("# ~/.zcode/cli/config.json (the same file `install-mcp --client");+ println!("# zcode` registers MCP servers in), or re-run with --apply to");+ println!("# merge it in place, preserving the rest of the config.");+ println!("# AI-memory server URL: {server_url}");+ if auth_token.is_some() {+ println!("# Auth: token embedded in each hook's args below.");+ println!("# Treat the config as sensitive (chmod 600).");+ }+ println!("# NOTE: ZCode injects SessionStart stdout as model context, so the");+ println!("# prior session's handoff is delivered automatically.");+ println!("# NOTE: ZCode fires `Stop` at the end of every turn and has no");+ println!("# SessionEnd — close sessions with");+ println!("# `ai-memory finalize-session --agent zcode`.");+ println!();+ println!("{serialized}");+ Ok(())+}+fn render_devin(hooks_dir: &Path,server_url: &str,@@ -4823,6 +4998,7 @@ mod tests {KiroCli,KiroCliV3,Pool,+ Zcode,] {assert!(!capture_assistant_allowed(agent),@@ -4857,6 +5033,7 @@ mod tests {KiroCli,KiroCliV3,Pool,+ Zcode,] {assert!(!prompt_capture_options_allowed(agent), "{agent:?}");}@@ -5782,6 +5959,225 @@ command = "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/a);}+ #[test]+ fn zcode_hooks_config_covers_all_events_with_strict_entries() {+ let payload = super::super::render_shared::build_zcode_hooks_config(+ "http://127.0.0.1:49374",+ Some("tok-test"),+ Some(Path::new("/data")),+ Some("repo-root"),+ );+ assert_eq!(payload["enabled"], serde_json::json!(true));+ // Raised above ZCode's 32 KiB default so a fetched handoff is not+ // truncated before injection.+ assert_eq!(payload["maxOutputBytes"], serde_json::json!(65536));+ let events = payload["events"].as_object().unwrap();+ assert_eq!(+ events.len(),+ super::super::render_shared::ZCODE_EVENTS.len(),+ "one entry per documented ZCode trigger"+ );+ for (zcode_event, our_event) in super::super::render_shared::ZCODE_EVENTS {+ let groups = events[zcode_event].as_array().unwrap();+ assert_eq!(groups.len(), 1, "{zcode_event}: one matcher group");+ let hooks = groups[0]["hooks"].as_array().unwrap();+ assert_eq!(hooks.len(), 1, "{zcode_event}: one hook entry");+ let hook = &hooks[0];+ // Exec form: `type: "process"` spawns command + args with no+ // shell, so every key must be from ZCode's documented schema —+ // undocumented keys make it drop the entry.+ assert_eq!(hook["type"], serde_json::json!("process"), "{zcode_event}");+ assert_eq!(+ hook["statusMessage"].as_str().unwrap(),+ "ai-memory capture",+ "{zcode_event}: ownership marker"+ );+ assert_eq!(hook["timeoutMs"], serde_json::json!(10_000));+ for key in hook.as_object().unwrap().keys() {+ assert!(+ matches!(+ key.as_str(),+ "type" | "command" | "args" | "enabled" | "timeoutMs" | "statusMessage"+ ),+ "{zcode_event}: undocumented hook key {key}"+ );+ }+ let args: Vec<&str> = hook["args"]+ .as_array()+ .unwrap()+ .iter()+ .map(|a| a.as_str().unwrap())+ .collect();+ assert!(args.contains(&"hook"), "{args:?}");+ assert!(+ args.contains(&"--event") && args.contains(&our_event),+ "{args:?}"+ );+ assert!(+ args.contains(&"--agent") && args.contains(&"zcode"),+ "{args:?}"+ );+ assert!(args.contains(&"--server-url") && args.contains(&"http://127.0.0.1:49374"));+ assert!(args.contains(&"--auth-token") && args.contains(&"tok-test"));+ assert!(args.contains(&"--data-dir") && args.contains(&"/data"));+ assert!(args.contains(&"--project-strategy") && args.contains(&"repo-root"));+ }+ // PostToolUseFailure fires instead of PostToolUse when the tool+ // throws; the loop above already proved it forwards onto the same+ // `post-tool-use` channel as its success sibling.+ assert!(events.contains_key("PostToolUseFailure"));+ }++ #[test]+ fn zcode_apply_preserves_siblings_and_is_idempotent() {+ let tmp = TempDir::new().unwrap();+ let path = tmp.path().join("config.json");+ fs::write(+ &path,+ r#"{+ "theme": "dark",+ "model": {"main": "zai/glm-5.1"},+ "mcp": {"servers": {"other": {"type": "http", "url": "https://other.example/mcp"}}},+ "hooks": {+ "enabled": true,+ "events": {+ "SessionStart": [+ {"matcher": "Bash", "hooks": [+ {"type": "process", "command": "/usr/bin/true", "args": [], "enabled": true}+ ]},+ {"hooks": [+ {"type": "process", "command": "/old/ai-memory", "args": [],+ "enabled": true, "statusMessage": "ai-memory capture"}+ ]}+ ]+ }+ }+}"#,+ )+ .unwrap();+ let args = InstallHooksArgs {+ agent: AgentChoice::Zcode,+ capture_assistant: false,+ config_file: Some(path.clone()),+ ..default_hook_args()+ };++ apply_to_zcode_hooks(+ "http://127.0.0.1:49374",+ Some("tok-test"),+ Path::new("/data"),+ &args,+ )+ .unwrap();+ let first = fs::read_to_string(&path).unwrap();+ apply_to_zcode_hooks(+ "http://127.0.0.1:49374",+ Some("tok-test"),+ Path::new("/data"),+ &args,+ )+ .unwrap();+ let second = fs::read_to_string(&path).unwrap();++ assert_eq!(first, second, "re-apply must be a no-op");+ let root: serde_json::Value = serde_json::from_str(&second).unwrap();+ // Sibling config keys survive: hooks share the file with the model+ // and MCP registration (#511).+ assert_eq!(root["theme"], serde_json::json!("dark"));+ assert_eq!(root["model"]["main"], serde_json::json!("zai/glm-5.1"));+ assert_eq!(+ root["mcp"]["servers"]["other"]["url"],+ serde_json::json!("https://other.example/mcp")+ );+ // The handoff-injection stdout ceiling lands with the hooks block.+ assert_eq!(root["hooks"]["maxOutputBytes"], serde_json::json!(65536));+ let session_start = root["hooks"]["events"]["SessionStart"].as_array().unwrap();+ assert_eq!(+ session_start.len(),+ 2,+ "the third-party matcher group must survive the merge"+ );+ let third_party = &session_start[0];+ assert_eq!(+ third_party["matcher"],+ serde_json::json!("Bash"),+ "third-party matcher groups are preserved untouched"+ );+ assert_eq!(+ third_party["hooks"][0]["command"],+ serde_json::json!("/usr/bin/true")+ );+ let ours = &session_start[1];+ assert_eq!(+ ours["hooks"][0]["command"],+ super::super::render_shared::build_zcode_hooks_config(+ "http://127.0.0.1:49374",+ Some("tok-test"),+ Some(Path::new("/data")),+ None+ )["events"]["SessionStart"][0]["hooks"][0]["command"],+ "the stale ai-memory command path must be replaced"+ );+ for (zcode_event, _) in super::super::render_shared::ZCODE_EVENTS {+ assert!(+ root["hooks"]["events"][zcode_event].is_array(),+ "missing {zcode_event}"+ );+ }+ }++ #[test]+ fn zcode_apply_flags_a_user_disabled_hooks_block() {+ let tmp = TempDir::new().unwrap();+ let path = tmp.path().join("config.json");+ fs::write(&path, r#"{"hooks": {"enabled": false, "events": {}}}"#).unwrap();+ let args = InstallHooksArgs {+ agent: AgentChoice::Zcode,+ capture_assistant: false,+ config_file: Some(path.clone()),+ ..default_hook_args()+ };++ apply_to_zcode_hooks("http://127.0.0.1:49374", None, Path::new("/data"), &args).unwrap();++ let root: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();+ assert_eq!(+ root["hooks"]["enabled"],+ serde_json::json!(false),+ "a user-disabled hooks block must stay disabled (we warn instead)"+ );+ assert_eq!(+ root["hooks"]["events"].as_object().unwrap().len(),+ super::super::render_shared::ZCODE_EVENTS.len()+ );+ }++ #[test]+ fn zcode_apply_respects_a_user_chosen_output_ceiling() {+ // `maxOutputBytes` is block-level and would also bound third-party+ // hooks, so a value the user chose is never overwritten.+ let tmp = TempDir::new().unwrap();+ let path = tmp.path().join("config.json");+ fs::write(+ &path,+ r#"{"hooks": {"enabled": true, "maxOutputBytes": 4096, "events": {}}}"#,+ )+ .unwrap();+ let args = InstallHooksArgs {+ agent: AgentChoice::Zcode,+ capture_assistant: false,+ config_file: Some(path.clone()),+ ..default_hook_args()+ };++ apply_to_zcode_hooks("http://127.0.0.1:49374", None, Path::new("/data"), &args).unwrap();++ let root: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();+ assert_eq!(root["hooks"]["maxOutputBytes"], serde_json::json!(4096));+ }+#[test]fn resolve_hooks_dir_uses_devin_bundle_for_devin() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 178ed357..af13982f 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -457,6 +457,111 @@ pub(crate) fn build_zero_hooks_config(serde_json::json!({ "enabled": true, "hooks": hooks })}+/// ZCode (z.ai) lifecycle events ai-memory hooks (#512). Each pair is+/// `(event-name-in-config.json, native `hook --event` value)`.+///+/// ZCode's hook vocabulary is exactly these six triggers (verified live+/// against the embedded engine v0.16.5): no `SessionEnd` — `Stop` fires at+/// the end of every turn, so `ai-memory finalize-session --agent zcode` is+/// the close path. `PermissionRequest` is deliberately not installed: its+/// hook chain races the interactive permission client and the loser is+/// aborted (`racePermissionResponders`), so a fast client decision silently+/// kills the hook — passive capture of that event is unreliable by design.+/// `PostToolUseFailure` fires *instead of* `PostToolUse` when the tool+/// throws; it forwards onto the same `post-tool-use` channel and the+/// payload's `error` field marks the outcome.+pub(crate) const ZCODE_EVENTS: [(&str, &str); 6] = [+ ("SessionStart", "session-start"),+ ("UserPromptSubmit", "user-prompt-submit"),+ ("PreToolUse", "pre-tool-use"),+ ("PostToolUse", "post-tool-use"),+ ("PostToolUseFailure", "post-tool-use"),+ ("Stop", "stop"),+];++/// ZCode hooks config (#512): the root `hooks` block of+/// `~/.zcode/cli/config.json` —+/// `{"enabled": true, "maxOutputBytes": …, "events": {Event: [{hooks: […]}]}}`.+///+/// Entries are exec-form `{"type":"process","command":…,"args":[…]}`: ZCode+/// spawns them without a shell and pipes the event JSON to stdin, which the+/// native `ai-memory hook` command reads directly — same wiring as Zero, so+/// ZCode gets the local spool + OIDC fallback with zero glue scripts. Every+/// key is from ZCode's documented hook schema (`type`, `command`, `args`,+/// `enabled`, `timeoutMs`, `statusMessage`); ZCode drops entries with+/// undocumented keys, so none are emitted. `statusMessage` doubles as the+/// ownership marker apply/uninstall merge around. `timeoutMs` bounds each+/// invocation (the capture POST is fire-and-forget; session-start also+/// fetches a handoff), and `maxOutputBytes` is raised above the 32 KiB+/// default so a fetched handoff is not truncated mid-JSON before ZCode+/// injects it as session context.+pub(crate) fn build_zcode_hooks_config(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> serde_json::Value {+ let exe = std::env::current_exe()+ .map(|p| p.to_string_lossy().into_owned())+ .unwrap_or_else(|_| "ai-memory".to_string());+ let mut events = serde_json::Map::new();+ for (zcode_event, our_event) in ZCODE_EVENTS {+ let mut args: Vec<String> = Vec::new();+ if let Some(dir) = data_dir {+ args.push("--data-dir".into());+ args.push(dir.to_string_lossy().into_owned());+ }+ args.extend(+ [+ "hook",+ "--event",+ our_event,+ "--agent",+ "zcode",+ "--server-url",+ server_url,+ ]+ .map(String::from),+ );+ if let Some(token) = auth_token {+ args.push("--auth-token".into());+ args.push(token.to_string());+ }+ if let Some(strategy) = project_strategy {+ args.push("--project-strategy".into());+ args.push(strategy.to_string());+ }+ let entry = serde_json::json!({+ "type": "process",+ "command": exe,+ "args": args,+ "enabled": true,+ "timeoutMs": ZCODE_HOOK_TIMEOUT_MS,+ "statusMessage": "ai-memory capture",+ });+ events.insert(+ (*zcode_event).to_string(),+ serde_json::json!([{ "hooks": [entry] }]),+ );+ }+ serde_json::json!({+ "enabled": true,+ "maxOutputBytes": ZCODE_HOOK_MAX_OUTPUT_BYTES,+ "events": events,+ })+}++/// Per-hook wall-clock bound for ZCode invocations of the native command.+/// Generous enough for the synchronous session-start handoff fetch on a+/// slow machine; capture POSTs themselves are fire-and-forget.+pub(crate) const ZCODE_HOOK_TIMEOUT_MS: u64 = 10_000;++/// Session-start stdout ceiling for ZCode (`maxOutputBytes`). ZCode+/// truncates hook stdout beyond this before injecting it; 64 KiB+/// comfortably covers a handoff plus a `[briefing]`-budgeted brief+/// (same reasoning as Kiro v2's `max_output_size`).+pub(crate) const ZCODE_HOOK_MAX_OUTPUT_BYTES: usize = 64 * 1024;+/// Devin hook payload for docker/setup-agent script snippets./// Devin uses HookShape::Nested (same as Claude Code/Grok) but with/// DEVIN_EVENTS (PostCompaction instead of PreCompact, no subagent events).diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex 3e4e8c26..84b8f90c 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -68,12 +68,16 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {emit_extension_setup_hint(&args)?;return Ok(());}- // Zero runs ai-memory's native `hook` command directly (exec form,- // no scripts to stage) — setup-agent just prints the hooks.json.+ // Zero and ZCode run ai-memory's native `hook` command directly (exec+ // form, no scripts to stage) — setup-agent just prints their config.if matches!(args.agent, AgentChoice::Zero) {emit_zero(&args)?;return Ok(());}+ if matches!(args.agent, AgentChoice::Zcode) {+ emit_zcode(&args)?;+ return Ok(());+ }let Some(agent_sub) = args.agent.script_hook_subdir() else {bail!("internal: generated integration should have returned before staging hooks")};@@ -164,7 +168,8 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {| AgentChoice::Pi| AgentChoice::Omp| AgentChoice::Openclaw- | AgentChoice::Zero => {+ | AgentChoice::Zero+ | AgentChoice::Zcode => {bail!("internal: generated integration should have returned before emitting staged hooks")@@ -202,6 +207,37 @@ fn emit_zero(args: &SetupAgentArgs) -> Result<()> {Ok(())}+/// Print ZCode's `hooks` block (#512). No scripts are staged: ZCode+/// spawns the ai-memory binary exec-form (`type: "process"`) with the+/// event JSON on stdin, so the only artifact is the config block. The+/// binary must be reachable on the host that runs ZCode — for+/// docker-wrapper setups install the native binary or point `command`+/// at the wrapper.+fn emit_zcode(args: &SetupAgentArgs) -> Result<()> {+ let payload = crate::commands::render_shared::build_zcode_hooks_config(+ &args.server_url,+ args.auth_token.as_deref(),+ None,+ None,+ );+ let serialized =+ serde_json::to_string_pretty(&payload).context("serializing ZCode hook config")?;+ println!("# ZCode (z.ai) — merge the `hooks` block into ~/.zcode/cli/config.json");+ println!("# The `command` must be an ai-memory binary reachable on the host");+ println!("# that runs ZCode; prefer `ai-memory install-hooks --agent zcode --apply`");+ println!("# from that host so the path is resolved for you.");+ if args.auth_token.is_some() {+ println!("# Treat the config as sensitive (chmod 600).");+ }+ println!("# NOTE: ZCode injects SessionStart stdout as model context, so the");+ println!("# prior session's handoff is delivered automatically.");+ println!("# NOTE: ZCode fires `Stop` per turn and has no SessionEnd — close");+ println!("# sessions with `ai-memory finalize-session --agent zcode`.");+ println!();+ println!("{serialized}");+ Ok(())+}+fn normalise_hook_server_url(url: &str) -> String {url.trim().trim_end_matches('/').to_string()}diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex 1610a6cd..b3343ecc 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -245,6 +245,8 @@ pub enum AgentKind {Hermes,/// Pool (Poolside Agent CLI).Pool,+ /// ZCode (z.ai) coding agent.+ Zcode,/// Anything else (manual capture, future agents).Other,}@@ -255,7 +257,7 @@ impl AgentKind {/// CHECK constraint accepts every kind (the Zero integration shipped/// with the enum variant but without the V26 migration and only a/// live test caught it). Extend together with the enum.- pub const ALL: [Self; 20] = [+ pub const ALL: [Self; 21] = [Self::ClaudeCode,Self::Codex,Self::OpenCode,@@ -275,6 +277,7 @@ impl AgentKind {Self::CommandCode,Self::Hermes,Self::Pool,+ Self::Zcode,Self::Other,];@@ -301,6 +304,7 @@ impl AgentKind {Self::CommandCode => "command-code",Self::Hermes => "hermes",Self::Pool => "pool",+ Self::Zcode => "zcode",Self::Other => "other",}}@@ -330,6 +334,7 @@ impl AgentKind {"command-code" | "commandcode" | "cmdc" | "cmd" => Self::CommandCode,"hermes" | "hermes-agent" => Self::Hermes,"pool" | "poolside" => Self::Pool,+ "zcode" | "zai" => Self::Zcode,_ => Self::Other,}}@@ -361,6 +366,12 @@ impl AgentKind {/// (verified against Poolside CLI v1.0.16), so Pool fails safe like other/// unproven agents: the handoff stays available on demand via the MCP/// `memory_handoff_accept` tool.+ ///+ /// ZCode (z.ai) DOES inject: a `hookSpecificOutput.additionalContext`+ /// canary printed by the session-start hook appeared verbatim inside a+ /// `<system-reminder>` text block of the first user message sent to the+ /// model (verified live against the embedded engine v0.16.5, capture logs+ /// 2026-08-28), so its native hook fetches the handoff like Claude Code's.#[must_use]pub fn session_start_injects_handoff(self) -> bool {!matches!(@@ -511,6 +522,28 @@ mod tests {assert!(!AgentKind::Pool.user_prompt_injects_handoff());}+ #[test]+ fn agent_kind_zcode_round_trips_and_injects_session_start_handoff() {+ assert_eq!(AgentKind::Zcode.as_str(), "zcode");+ assert_eq!(AgentKind::from_wire("zcode"), AgentKind::Zcode);+ assert_eq!(AgentKind::from_wire("zai"), AgentKind::Zcode);+ assert_eq!(+ serde_json::to_string(&AgentKind::Zcode).unwrap(),+ "\"zcode\""+ );+ assert_eq!(+ serde_json::from_str::<AgentKind>("\"zcode\"").unwrap(),+ AgentKind::Zcode+ );+ // Unknown tags still degrade to Other.+ assert_eq!(AgentKind::from_wire("zcode-2"), AgentKind::Other);+ // ZCode injects SessionStart stdout as additionalContext (live canary+ // capture against engine v0.16.5), so the destructive handoff fetch+ // is safe from its native hook.+ assert!(AgentKind::Zcode.session_start_injects_handoff());+ assert!(!AgentKind::Zcode.user_prompt_injects_handoff());+ }+#[test]fn agent_kind_command_code_round_trips_and_injects_session_start_handoff() {assert_eq!(AgentKind::CommandCode.as_str(), "command-code");diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rsindex 68a359c5..1baa33db 100644--- a/crates/ai-memory-hooks/src/capture_policy.rs+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@ -161,7 +161,10 @@ pub(crate) fn tool_observation_metadata() -> Option<ToolObservationMetadata> {let object = raw.as_object()?;let (name, id) = match agent {- AgentKind::ClaudeCode | AgentKind::CommandCode => (+ // ZCode tool payloads carry Claude Code's snake_case aliases+ // (`tool_name`, `tool_use_id`, `tool_input`) alongside the native+ // camelCase — all captured live (engine v0.16.5, #512).+ AgentKind::ClaudeCode | AgentKind::CommandCode | AgentKind::Zcode => (object.get("tool_name")?.as_str()?,object.get("tool_use_id").and_then(Value::as_str),),@@ -206,6 +209,7 @@ pub(crate) fn tool_observation_metadata(| AgentKind::Hermes| AgentKind::KiroCli| AgentKind::Pool+ | AgentKind::Zcode) {"tool_input"} else {@@ -245,6 +249,19 @@ pub(crate) fn tool_observation_outcome(agent: AgentKind, raw: &Value) -> ToolOut{ToolOutcome::Error}+ // ZCode fires `PostToolUseFailure` instead of `PostToolUse` when the+ // tool throws; that payload carries `error` (string) + `error_details`+ // (live-captured, #512). `exitCode` is deliberately not mapped to+ // Success: the same `tool_response` object carries `timedOut` /+ // `interrupted`, so exit code alone does not prove success.+ AgentKind::Zcode+ if raw+ .get("error")+ .and_then(Value::as_str)+ .is_some_and(|error| !error.is_empty()) =>+ {+ ToolOutcome::Error+ }_ => ToolOutcome::Unknown,}}@@ -580,7 +597,10 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted {| AgentKind::Devin| AgentKind::Hermes| AgentKind::KiroCli- | AgentKind::Pool => object+ | AgentKind::Pool+ // ZCode mirrors Claude Code's snake_case `tool_name`/`tool_input`+ // aliases on every tool event (live-captured, #512).+ | AgentKind::Zcode => object.get("tool_name").and_then(Value::as_str).map(|name| (name, object.get("tool_input"))),@@ -1187,6 +1207,74 @@ mod tests {}}+ #[test]+ fn zcode_documented_tool_shape_is_closed_and_honors_exclusions() {+ // Live-captured ZCode payload (engine v0.16.5, #512): the snake_case+ // aliases carry exactly the fields Claude Code sends, including a+ // real provider-format tool call id (`call_…`).+ let raw = json!({+ "hookEventName": "PostToolUse",+ "toolName": "Write",+ "tool_name": "Write",+ "tool_use_id": "call_6d8f8fd5d9eb4888b0f9d5c6",+ "toolInput": {"file_path": "/repo/secret/token.txt", "content": "do not retain"},+ "tool_input": {"file_path": "/repo/secret/token.txt", "content": "do not retain"},+ "session_id": "sess_0a5ba797",+ "cwd": "/repo"+ });+ let metadata = tool_observation_metadata(AgentKind::Zcode, &raw, true).unwrap();+ assert_eq!(metadata.tool_family, ToolFamily::File);+ assert_eq!(+ metadata.tool_call_id.as_deref(),+ Some("call_6d8f8fd5d9eb4888b0f9d5c6")+ );++ let policy = CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec!["secret/**".into()],+ }),+ "/repo",+ None,+ );+ let decision = policy.inspect(AgentKind::Zcode, &raw, "/repo");+ assert_eq!(decision.protocol().tool_family(), ToolFamily::File);+ assert_eq!(decision.protocol().disposition(), CaptureDisposition::Drop);++ let unknown = policy.inspect(AgentKind::Other, &raw, "/repo");+ assert_eq!(+ unknown.protocol().extraction_state(),+ ExtractionState::UnsupportedSchema+ );+ assert_eq!(unknown.protocol().tool_family(), ToolFamily::Unknown);+ }++ #[test]+ fn zcode_post_tool_use_failure_error_maps_to_error_outcome() {+ // Live-captured PostToolUseFailure payload (run 10, real model, #512):+ // `error` is a plain string, `error_details` carries the internal+ // error class.+ let raw = json!({+ "hook_event_name": "PostToolUseFailure",+ "tool_name": "Write",+ "error": "File not found: /proc/capture-test.txt",+ "error_details": {+ "message": "File not found: /proc/capture-test.txt",+ "type": "FileSystemPortError"+ }+ });+ assert_eq!(+ tool_observation_outcome(AgentKind::Zcode, &raw),+ ToolOutcome::Error+ );+ // exitCode is deliberately not trusted for Success: the same+ // tool_response object carries timedOut / interrupted flags.+ let ok = json!({"tool_response": {"exitCode": 0}});+ assert_eq!(+ tool_observation_outcome(AgentKind::Zcode, &ok),+ ToolOutcome::Unknown+ );+ }+#[test]fn command_code_official_tool_shape_is_closed_and_honors_exclusions() {let policy = CapturePolicy::resolve(diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex c48c4977..134cdff7 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -600,6 +600,7 @@ const fn closed_tool_agent(agent: AgentKind) -> bool {| AgentKind::AntigravityCli| AgentKind::Hermes| AgentKind::Pool+ | AgentKind::Zcode)}@@ -1723,6 +1724,38 @@ mod tests {assert_eq!(env.cwd.as_deref(), Some("/repo"));}+ #[test]+ fn zcode_tool_payload_uses_the_captured_dual_casing_shape() {+ // Live-captured PostToolUse payload (embedded engine v0.16.5, #512):+ // native camelCase plus Claude Code-compatible snake_case aliases on+ // every shared field.+ let raw = serde_json::json!({+ "hookEventName": "PostToolUse",+ "hook_event_name": "PostToolUse",+ "toolName": "Bash",+ "tool_name": "Bash",+ "toolCallId": "call_86cedcb9c40a4a40856e9ee7",+ "tool_use_id": "call_86cedcb9c40a4a40856e9ee7",+ "toolInput": {"command": "echo capture-ok"},+ "tool_input": {"command": "echo capture-ok"},+ "sessionId": "sess_4fc06da3",+ "session_id": "sess_4fc06da3",+ "cwd": "/tmp/zcode-capture"+ });+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("zcode".into()),+ ..Default::default()+ },+ raw,+ );+ assert_eq!(env.agent, AgentKind::Zcode);+ assert_eq!(env.session_id.as_deref(), Some("sess_4fc06da3"));+ assert_eq!(env.cwd.as_deref(), Some("/tmp/zcode-capture"));+ assert_eq!(env.title_hint.as_deref(), Some("tool non-file"));+ }+/// Body is well-formed JSON but the expected `session_id` //// `cwd` keys are missing — extraction returns None per key.#[test]diff --git a/crates/ai-memory-store/migrations/V51__sessions_zcode_agent_kind.sql b/crates/ai-memory-store/migrations/V51__sessions_zcode_agent_kind.sqlnew file mode 100644index 00000000..fc4396d6--- /dev/null+++ b/crates/ai-memory-store/migrations/V51__sessions_zcode_agent_kind.sql@@ -0,0 +1,73 @@+-- Expand sessions.agent_kind CHECK for ZCode (z.ai).+--+-- Keep the complete V50 schema, indexes, and scope-pairing triggers while+-- adding the `zcode` wire value.++PRAGMA foreign_keys = OFF;++DROP TRIGGER IF EXISTS auto_improve_scheduler_claims_session_pairing_ai;+DROP TRIGGER IF EXISTS session_consolidation_jobs_session_pairing_ai;++CREATE TABLE sessions_new (+ id BLOB PRIMARY KEY NOT NULL,+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,+ agent_kind TEXT NOT NULL CHECK (agent_kind IN ('claude-code','codex','open-code','cursor','gemini-cli','claude-desktop','openclaw','antigravity-cli','omp','pi','crush','grok','zero','devin','kimi-code','kiro-cli','command-code','hermes','pool','zcode','other')),+ cwd TEXT,+ started_at INTEGER NOT NULL,+ ended_at INTEGER,+ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL,+ ended_observation_count INTEGER NOT NULL DEFAULT 0 CHECK (ended_observation_count >= 0),+ actor_user TEXT+);++INSERT INTO sessions_new (+ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,+ summary_page_id, ended_observation_count, actor_user+)+SELECT+ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,+ summary_page_id, ended_observation_count, actor_user+FROM sessions;++DROP TABLE sessions;++ALTER TABLE sessions_new RENAME TO sessions;++CREATE INDEX idx_sessions_recent ON sessions(workspace_id, project_id, started_at DESC);+CREATE INDEX idx_sessions_project ON sessions(project_id);+CREATE INDEX idx_sessions_started_at ON sessions(started_at DESC);+CREATE INDEX idx_sessions_scope_ended+ ON sessions(workspace_id, project_id, ended_at ASC)+ WHERE ended_at IS NOT NULL;+CREATE INDEX idx_sessions_open_owner+ ON sessions(workspace_id, project_id, agent_kind, actor_user)+ WHERE ended_at IS NULL;++CREATE TRIGGER sessions_ws_proj_pairing_ai+BEFORE INSERT ON sessions+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)+BEGIN+ SELECT RAISE(ABORT, 'sessions.workspace_id does not match the project''s workspace');+END;++CREATE TRIGGER auto_improve_scheduler_claims_session_pairing_ai+BEFORE INSERT ON auto_improve_scheduler_claims+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)+BEGIN+ SELECT RAISE(ABORT, 'auto_improve_scheduler_claims scope does not match the session scope');+END;++CREATE TRIGGER session_consolidation_jobs_session_pairing_ai+BEFORE INSERT ON session_consolidation_jobs+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)+BEGIN+ SELECT RAISE(ABORT, 'session_consolidation_jobs scope does not match the session scope');+END;++PRAGMA foreign_keys = ON;diff --git a/crates/ai-memory-store/src/migrations.rs b/crates/ai-memory-store/src/migrations.rsindex ba3e51e3..6feb9559 100644--- a/crates/ai-memory-store/src/migrations.rs+++ b/crates/ai-memory-store/src/migrations.rs@@ -805,6 +805,73 @@ mod tests {}}+ #[test]+ fn v50_to_v51_preserves_session_state_and_accepts_zcode() {+ let mut conn = Connection::open_in_memory().unwrap();+ run_to(&mut conn, 50).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();+ let workspace_id = crate::ops::get_or_create_workspace(&mut conn, "default").unwrap();+ let project_id =+ crate::ops::get_or_create_project(&mut conn, &workspace_id, "project", None).unwrap();+ let existing = SessionId::new();+ conn.execute(+ "INSERT INTO sessions \+ (id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at, \+ ended_observation_count, actor_user) \+ VALUES (?1, ?2, ?3, 'pool', '/repo', 1, 2, 7, 'user:alice')",+ params![+ existing.as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ ],+ )+ .unwrap();++ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();+ run(&mut conn).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();++ let preserved: (String, String, i64, Option<String>) = conn+ .query_row(+ "SELECT agent_kind, cwd, ended_observation_count, actor_user \+ FROM sessions WHERE id = ?1",+ params![existing.as_bytes()],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),+ )+ .unwrap();+ assert_eq!(+ preserved,+ ("pool".into(), "/repo".into(), 7, Some("user:alice".into()))+ );++ crate::ops::begin_session(+ &mut conn,+ &NewSession {+ id: SessionId::new(),+ workspace_id,+ project_id,+ agent_kind: AgentKind::Zcode,+ cwd: Some("/repo".into()),+ actor_user: Some("user:alice".into()),+ },+ )+ .unwrap();++ for name in [+ "idx_sessions_open_owner",+ "sessions_ws_proj_pairing_ai",+ "auto_improve_scheduler_claims_session_pairing_ai",+ "session_consolidation_jobs_session_pairing_ai",+ ] {+ let kind = if name.starts_with("idx_") {+ "index"+ } else {+ "trigger"+ };+ assert_eq!(schema_object_count(&conn, kind, name), 1, "missing {name}");+ }+ }+#[test]fn v48_to_v49_replaces_the_decay_tombstone_index_predicate() {let mut conn = Connection::open_in_memory().unwrap();diff --git a/docs/install.md b/docs/install.mdindex db2b7930..9b58f787 100644--- a/docs/install.md+++ b/docs/install.md@@ -1035,6 +1035,56 @@ handoff via the MCP `memory_handoff_accept` tool. No first-partyclaimed: Pool's native session-store contract is not demonstrated, per[managed-harness contributions](managed-harness-contributions.md).+### ZCode (z.ai)++ZCode wires lifecycle hooks in the root `hooks` block of+`~/.zcode/cli/config.json` — the same file that holds its other CLI+registration. `install-hooks --agent zcode` (alias `zai`) merges ai-memory's+entries into that block around any third-party hooks you already have, and is+idempotent: re-running strips only ai-memory's own entries (marked by+`statusMessage: "ai-memory capture"`) and rewrites them in place.++```bash+ai-memory install-hooks --agent zcode --apply \+ --server-url "http://homelab:49374" \+ --auth-token "$TOKEN"++# Preview the exact hooks block without writing anything:+ai-memory install-hooks --agent zcode \+ --server-url "http://homelab:49374"+```++Entries are exec-form `{"type": "process", "command": <ai-memory>, "args":+[…]}` — ZCode spawns them with the event JSON on stdin and no shell, which the+native `ai-memory hook` command reads directly, so the local spool, bearer+auth, and `[capture] ignore_paths` exclusions all apply. Every emitted key is+from ZCode's documented hook schema (`type`, `command`, `args`, `enabled`,+`timeoutMs`, `statusMessage`); ZCode drops entries carrying undocumented keys,+so none are emitted. Six documented triggers are wired: `SessionStart`,+`UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and+`Stop` (verified live against the embedded engine v0.16.5).+`PostToolUseFailure` fires *instead of* `PostToolUse` when a tool throws and+is forwarded onto the same capture channel with the error preserved as the+observation outcome. `PermissionRequest` is deliberately not installed: its+hook chain races the interactive permission client, and a fast client decision+aborts the losing hook, so passive capture of that event is unreliable by+design.++ZCode injects `SessionStart` stdout as model context+(`hookSpecificOutput.additionalContext`), so unlike Pool, Zero, and Grok the+prior session's handoff is delivered automatically at session start. There is+no true session-end event — `Stop` fires at the end of every turn — so close+finished sessions explicitly; use the exact id when several ZCode sessions are+open in the same project:++```bash+ai-memory finalize-session --agent zcode+ai-memory finalize-session --agent zcode --session-id <uuid>+```++No first-party `install-mcp` client and no managed workstream+(`ai-memory run zcode`) are claimed yet.+### OpenCode```bash