Skip to content

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

Rust

Merge main into release/3.1

AkitaOnRails6a75a1eb55a6
diff --cc CHANGELOG.md
index 3439e0fe,4a1e94dc..4a936f50
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -11,160 -11,63 +11,208 @@@ version in [`docs/changelog/`](docs/cha
## [Unreleased]
+### Added
+- Added opt-in session inspection and owned-session purging for signed-in
+ browser users, enabled at runtime with `serve --enable-session-management`
+ (`AI_MEMORY_ENABLE_SESSION_MANAGEMENT`). A user can purge only a session they
+ own in a project they may write; an Admin can purge any. Requested in #1231.
+ (#1267)
+- Added opt-in self-service `aim_` API keys for signed-in browser users,
+ enabled at runtime with `serve --enable-self-service-keys`
+ (`AI_MEMORY_ENABLE_SELF_SERVICE_KEYS`). Labels must be 1 to 128 characters
+ and a user may hold at most 20 active keys. A self-issued key survives a
+ password reset or account disable and must be revoked separately. Requested
+ in #1231. (#1268)
+- Added `ai-memory search --global`, which searches the wiki pages of every
+ project from the terminal instead of only the current one. Each hit shows
+ its `workspace/project` in the text output and carries `workspace` and
+ `project` fields in `--json`. The flag cannot be combined with
+ `--workspace` or `--project`, and a search without it still resolves its
+ scope from the current directory. The server side is `GET /admin/search`
+ with no `workspace`/`project`: its hits now include `workspace` and
+ `project` next to the fields they already had, and the route stays
+ root-only on a multi-user server. Global search covers wiki pages only;
+ raw observations and a search limited to one workspace are not part of
+ this change. (#1253)
+- Added kind and tier filters to the web search. The search page in `/web`
+ has "Kind" and "Tier" selects, and `/web/search` accepts `kind` and `tier`
+ for both a project search and a cross-project one. Every retrieval stream
+ applies the filter in its own query, so other kinds cannot crowd out a rare
+ one, a filtered search asks the streams for no more candidates than an
+ unfiltered one, and the reranker scores only pages the filter keeps. Kind
+ and tier both ignore case, a nonstandard kind is flagged on an empty
+ result, and "Search all projects" keeps the filters. An unknown `tier` is
+ a 400. (#1248)
+- Added `ai-memory setup --plan`, which prints the plan and changes nothing,
+ and `--plan --json`, which prints it as a JSON document with a `format`
+ version for a script or front end to render. The plan now says what each
+ detected agent was found by (its session store, its MCP config, or Muse's
+ directory), numbers the agents, and lists the other agents `--agent`
+ accepts. At the prompt you can type the numbers of the agents to wire
+ instead of `y`; a number outside the plan changes nothing. (#1270)
+- Added a native Windows path to the two-command install. `install.ps1`,
+ published with each release next to its own `.sha256`, checks the release
+ zip against that checksum, refuses archive entries that are absolute or
+ hold `..`, unpacks it under `%LOCALAPPDATA%\Programs\ai-memory` and adds
+ that directory to the user `PATH` (`AI_MEMORY_NO_MODIFY_PATH=1` skips it),
+ with no administrator rights. `ai-memory setup` now has a service step on
+ Windows: it writes an `ai-memory` value under the per-user `Run` key that
+ starts a hidden `ai-memory service-host` at logon, and starts it right away.
+ The value is written and read through the registry API, not by running
+ `reg.exe`: an unsigned binary running `reg.exe add` on the `Run` key is a
+ common persistence signal, and Bitdefender's behavioral engine quarantined
+ `ai-memory.exe` for it (#1280). Its paths are written plainly, without the
+ `\\?\` prefix a canonical path carries. Stopping the host does not run
+ `taskkill` either: `setup` and `uninstall` leave a stop request in the data
+ dir, and the host kills the server it started and exits. `taskkill` is
+ only the fallback for a host that does not answer within ten seconds (one
+ started by an older binary, or a hung one) or a server whose host already
+ died.
+ The host runs the server with no console window and restarts it after a
+ failure, giving up after five failures within ten seconds of starting.
+ `ai-memory uninstall --apply` stops the host and removes the value when it
+ still has the shape `setup` writes and names this install's data dir, so an
+ uninstall against another data dir (a second install, a test's temporary
+ one) leaves the entry alone. `ai-memory doctor` and `ai-memory status`
+ warn (`logon_binary_missing`, also in their `--json` output and when
+ `status` cannot reach the server) when that entry names an
+ `ai-memory.exe` that no longer exists, which is what an antivirus
+ quarantine leaves behind, and say how to restore the binary or remove the
+ entry. (#1271, #1280, #1300, #1311)
+- Added `ai-memory setup --web`, which shows the setup plan as a page in
+ your browser and applies the agents you tick there by running `ai-memory
+ setup --yes --agent ...` and streaming its output to the page. The page is
+ served on `127.0.0.1` behind a one-time address printed in the terminal
+ (opened in the browser unless `--no-open` or there is no desktop), refuses
+ requests with another `Host`, without the address's secret, or, for a
+ change, without the page's own `Origin` and CSRF token, and holds no token.
+ It stops on Finish, after 15 minutes without a request, or on Ctrl-C. (#1272)
+- Added a desktop installer preview, `companions/ai-memory-desktop`: a Tauri
+ app that uses an existing `ai-memory` install or copies its bundled one into
+ the same per-user location as `install.sh` and `install.ps1`, then shows the
+ `ai-memory setup --web` page in its own window. CI builds unsigned Linux,
+ macOS and Windows installers on manual dispatch; they are not attached to
+ releases until the project signs them. `setup --web` gained a hidden
+ `--stop-on-stdin-eof` flag so the page stops when the app does. (#1273)
+- A prompt that starts with `reload context` (for example `reload context
+ after last compaction, then …`) now puts the stretch of the session that
+ its last compaction dropped back in front of the agent: the prompts typed
+ between the latest two compactions, verbatim; the last captured reply (with
+ the assistant-capture opt-in); and the project's open handoffs, listed
+ without claiming them. The new read-only `GET /recap` route builds it from
+ captured observations. Claude Code and Codex receive it with that prompt
+ through `UserPromptSubmit` `additionalContext`, OpenCode V1/V2 through the
+ plugin's system/context hook, and Grok Build on the next `PostToolUse`.
+ Serving the recap writes nothing, so a reload never consumes a baton (#1230).
+- Added first-party CodeBuddy Code (Tencent) support. `codebuddy` is an
+ `AgentKind` (migration V81), so hook events are attributed to it and a
+ Claude Code-shaped tool payload (`tool_name`, `tool_input`, `tool_response`)
+ is stored as a closed tool observation instead of an empty `other` capture.
+ `install-hooks --agent codebuddy` (alias `code-buddy`) merges native
+ `ai-memory hook --event … --agent codebuddy` commands for seven events
+ (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`,
+ `PreCompact`, `Stop`, `SessionEnd`) into the `hooks` key of
+ `~/.codebuddy/settings.json`, keeps sibling settings and your own hooks,
+ and changes nothing on a re-run. There is no script bundle. The
+ `SessionStart` hook delivers the pending handoff through
+ `hookSpecificOutput.additionalContext`, and a capture-only `SessionStart` or
+ `UserPromptSubmit` prints nothing, since CodeBuddy appends that output to
+ the session. A `SessionStart` without `cwd` falls back to
+ `CODEBUDDY_PROJECT_DIR`. `setup` wires CodeBuddy when
+ `~/.codebuddy` exists, `setup-agent --agent codebuddy` prints the hook
+ block, and `uninstall` removes the entries. Transcript backfill and
+ headless `codebuddy -p` session close are not part of this change.
+ Requested in #1299. (#1312)
+- Added the `memory_restore_page` MCP tool: without `rev` it lists the git
+ checkpoints that changed a page, and with `rev` it writes that version back
+ through the wiki write path (sanitizer, admission, slots and supersession
+ apply), keeping the checkpoint's frontmatter. Restoring can bring back text
+ a root deleted or purged, so both listing and restoring need the same admin
+ authority as `/admin/restore-page`. The MCP surface is now 24 tools. (#1307)
+
+### Changed
+- `ai-memory setup` now ends by naming the agents to restart and the question
+ to ask one of them, "What do you remember about this project?", instead of
+ a generic restart line. `install.sh` names the link's full path in its
+ `next:` line when `~/.local/bin` is not on `PATH`, so the suggested command
+ no longer fails with "command not found". The AUR install and upgrade
+ messages, and the README Fedora, Arch and macOS app steps, point to
+ `ai-memory setup` instead of the manual `init`, `systemctl` and
+ `install-*` commands. (#1270)
+- Changed how the opt-in session-start brief (`[briefing]
+ inject_on_session_start`) spends `max_chars`. Every pinned, `_rules/` and
+ `_slots/` page now gets a short excerpt first, taken from its frontmatter
+ `abstract:` or `summary:`, or else from the prose it opens with (read on
+ into its first list items). The budget left deepens pages to a longer
+ excerpt and then the whole body: pinned and `_slots/` pages first, then
+ pages a few bytes short of whole, then the cheapest bodies. Before, the
+ brief printed whole bodies in order, so one long `_rules/` page was cut with
+ a `[truncated by ...]` note and every page after it became an "omitted"
+ path. Bodies are no longer cut: a body that does not fit whole shows its
+ excerpt. Four or more unpinned excerpts from one folder share a heading,
+ and the omitted list and the closing note point at `memory_read_page`.
+ Small wikis whose pages fit still get every body whole. A project with many
+ standing pages now sees all of them, fewer in full: pin a page, or give it
+ an `abstract:`, to control what it shows. The change adds no marker key
+ and no migration. (#1264)
+
### Fixed
- - Fixed the native hook claiming a handoff from the wrong project when an
- event named no directory. A `SessionStart` (or Kimi Code's
- `UserPromptSubmit`, or Grok's first `PostToolUse`) whose payload carried no
- `cwd` sent `GET /handoff` with no scope, so the server resolved its default
- project or the caller's last active one and the hook consumed that
- project's baton. The hook now fetches no handoff without a directory and
- says so on stderr; the handoff stays open for `memory_handoff_accept`.
- (#1312)
+ - Fixed a hook claiming a handoff from the wrong project when an event named
+ no directory. A `SessionStart` (or Kimi Code's `UserPromptSubmit`, or Grok's
+ first `PostToolUse`) whose payload carried no `cwd` sent `GET /handoff` with
+ no scope, so the server resolved its default project or the caller's last
+ active one, and the hook consumed that project's handoff. The native hook,
+ the shell and PowerShell hook bundles, and the generated OpenCode, OpenCode 2,
+ OMP and Pi integrations now fetch no handoff without a directory, for every
+ agent; the native hook says so on stderr at session start. The handoff stays
+ open for `memory_handoff_accept`. Devin still falls back to
+ `DEVIN_PROJECT_DIR`, then the hook's own directory. (#1312)
+ - Fixed `ai-memory setup` reporting "ai-memory is set up" after it installed
+ Codex hooks that Codex had not trusted yet. Codex skips an untrusted hook,
+ so Codex sessions went uncaptured. When Codex was wired, `setup` now asks
+ Codex for the hooks' trust state, the way `doctor` does, and when any are
+ untrusted or modified it names them and says to open Codex, run `/hooks`,
+ and trust them. It still exits 0. (#1313)
+ - Fixed `install-instructions` treating a line that is exactly `@AGENTS.md` as
+ proof that Claude Code loads the `AGENTS.md` being written. Claude Code
+ resolves `@path` from the file that contains the import, including in the
+ middle of a sentence, expands `~/` from the home directory, and ignores
+ imports inside code spans and fenced blocks. `@AGENTS.md` in
+ `.claude/CLAUDE.md` loads `.claude/AGENTS.md`, a fenced `@AGENTS.md` loads
+ nothing, and `@AGENTS.md` in a parent directory loads that directory's file.
+ The note now compares the resolved path with the file being written and
+ names the import that reaches it. (#1298)
+ - Fixed Antigravity CLI posting a session start and claiming a handoff on every
+ user turn: `invocationNum` restarts at 0 each turn, so only the first turn of
+ a conversation (keyed by `conversationId`) now maps to SessionStart, in the
+ native, shell and PowerShell hooks. Payloads without a `conversationId` keep
+ the previous per-turn behavior. A conversation resumed in a new process does
+ not start a new session, so a handoff left meanwhile is read with
+ `memory_handoff_list` rather than injected. (#1306)
+ - Fixed `llm-test --provider anthropic-oauth` reporting Anthropic's refusal of a
+ `claude setup-token` token as a plain rate limit: that 429 now carries a hint
+ that it is not a real rate limit and names the alternatives, which
+ `docs/llm-providers.md` already describes. (#1170)
+ - Fixed the curator report treating a per-user focus slot
+ (`_slots/<operator>/current-focus.md`) as an ordinary slot. It only
+ recognised the shared `_slots/current-focus.md`, so with per-user slots the
+ focus slot got the 30-day stale threshold instead of the 7-day one and was
+ reported three weeks late. (#1314)
+ - Fixed multi-page consolidation losing every page of a batch when the
+ model gave one page a path that cannot be repaired: a leading slash, a
+ `..` or `.` segment, or an empty segment. Path validation failed the whole
+ session's consolidation, so the valid pages in the same answer were never
+ written. That page is now skipped with a warning and the others are
+ written, as already happened for paths that fail the portability check.
+ (#1315)
+ - Fixed auto-improve patches losing track of a page's sections after a code
+ block that contains a different fence. A line of three backticks inside a
+ `~~~` block (or a shorter run inside a longer fence) ended the block early,
+ so the headings after it were missed, and a `replace_section` on the
+ section before them replaced those sections too. Profile harvesting had the
+ same flaw: the code after such a line was read as prose and could be
+ harvested as a preference. A fence now closes only on a run of the same
+ character that is at least as long. (#1316)
- Fixed the thin-client commands ignoring a custom `bind`, which could write
into the wrong store. `server_url` defaulted to `http://127.0.0.1:49374`
and was never derived from `bind`, so `ai-memory --data-dir X status` (and
diff --cc crates/ai-memory-cli/src/commands/hook.rs
index 2c021ec7,99942548..b6aab8d9
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@@ -2680,8 -2539,8 +2720,9 @@@ mod tests
#[tokio::test]
async fn a_handoff_is_never_claimed_without_a_project_directory() {
let cases = [
+ ("codebuddy", "session-start", serde_json::json!({})),
("claude-code", "session-start", serde_json::json!({})),
+ ("codex", "session-start", serde_json::json!({})),
(
"kimi-code",
"user-prompt-submit",
diff --cc crates/ai-memory-cli/src/commands/setup.rs
index 5948ae88,648a69e7..754f87e7
--- a/crates/ai-memory-cli/src/commands/setup.rs
+++ b/crates/ai-memory-cli/src/commands/setup.rs
@@@ -827,7 -530,8 +827,11 @@@ async fn execute
println!("{hint}");
}
if problems.is_empty() {
- println!("{}", next_step(&plan.agents));
+ let codex = codex_hook_trust(&config, &plan).await;
- println!("{}", ready_message(codex.as_ref()));
++ println!(
++ "{}",
++ ready_message(codex.as_ref(), &next_step(&plan.agents))
++ );
return Ok(());
}
for problem in &problems {
@@@ -839,6 -543,57 +843,62 @@@
)
}
+ /// Codex's trust state for the ai-memory hooks setup left in place: the
+ /// hooks file `install-hooks` wrote, or the enabled plugin's hooks. `None`
+ /// when Codex was not wired or its state is unknown (Codex not installed or
+ /// not answering).
+ async fn codex_hook_trust(
+ config: &Config,
+ plan: &SetupPlan,
+ ) -> Option<super::codex_hook_trust::CodexHookTrust> {
+ let codex = plan
+ .agents
+ .iter()
+ .find(|agent| agent.agent == AgentChoice::Codex)?;
+ let cwd = std::env::current_dir().ok()?;
+ if codex.plugin {
+ super::codex_hook_trust::probe(
+ Path::new("codex"),
+ super::codex_hook_trust::HookSource::Plugin(agent_plugins::PLUGIN_ID),
+ &cwd,
+ )
+ .await
+ } else {
+ doctor::codex_hook_trust(&config.runtime_env, &cwd).await
+ }
+ }
+
+ /// The closing line of a run with no problems. Codex skips a hook the user
+ /// has not trusted in its `/hooks` review, so with any skipped the install
+ /// is not ready for Codex yet. Setup still succeeds: only the user can grant
+ /// that trust, inside Codex, and re-running setup would not change it.
-fn ready_message(codex: Option<&super::codex_hook_trust::CodexHookTrust>) -> String {
- let restart = "Restart your agents so they load the new hooks and MCP entry.";
++fn ready_message(codex: Option<&super::codex_hook_trust::CodexHookTrust>, closing: &str) -> String {
++ // The closing line names the agents to restart and the question to ask;
++ // with Codex hooks still unapproved it follows the action required
++ // instead of claiming the install is ready.
++ let restart = closing
++ .strip_prefix("ai-memory is set up. ")
++ .unwrap_or(closing);
+ match codex.filter(|trust| !trust.skipped.is_empty()) {
- None => format!("ai-memory is set up. {restart}"),
++ None => closing.to_owned(),
+ Some(trust) => {
+ let skipped: Vec<String> = trust
+ .skipped
+ .iter()
+ .map(|(event, status)| format!("{event} ({status})"))
+ .collect();
+ format!(
+ "ai-memory is installed, but Codex has not approved its {} ai-memory hook(s) \
+ yet: {}. Codex skips a hook until you trust it, so Codex sessions are not \
+ captured until then. Action required: open Codex, run /hooks, and trust \
+ them. {restart}",
+ trust.skipped.len(),
+ skipped.join(", "),
+ )
+ }
+ }
+ }
+
/// How a browser signs in to the web UI on a token-file install. With no
/// human accounts the server answers `/web` with a Basic challenge, and the
/// token file's contents are the password. The token itself is never printed.
@@@ -1169,19 -892,52 +1229,55 @@@ mod tests
};
let home = tempfile::tempdir().unwrap();
let env = |_: &str| None;
- assert!(!AgentPlan::detect(AgentChoice::ClaudeCode, home.path(), &env).plugin);
+ assert!(!AgentPlan::detect(AgentChoice::ClaudeCode, None, home.path(), &env).plugin);
install_claude_plugin(home.path(), "3.0.0", false);
- assert!(!AgentPlan::detect(AgentChoice::ClaudeCode, home.path(), &env).plugin);
+ assert!(!AgentPlan::detect(AgentChoice::ClaudeCode, None, home.path(), &env).plugin);
install_claude_plugin(home.path(), "3.0.0", true);
- assert!(AgentPlan::detect(AgentChoice::ClaudeCode, home.path(), &env).plugin);
- assert!(!AgentPlan::detect(AgentChoice::Codex, home.path(), &env).plugin);
- assert!(!AgentPlan::detect(AgentChoice::Grok, home.path(), &env).plugin);
+ assert!(AgentPlan::detect(AgentChoice::ClaudeCode, None, home.path(), &env).plugin);
+ assert!(!AgentPlan::detect(AgentChoice::Codex, None, home.path(), &env).plugin);
+ assert!(!AgentPlan::detect(AgentChoice::Grok, None, home.path(), &env).plugin);
install_codex_plugin(home.path());
- assert!(AgentPlan::detect(AgentChoice::Codex, home.path(), &env).plugin);
+ assert!(AgentPlan::detect(AgentChoice::Codex, None, home.path(), &env).plugin);
}
+ /// Codex skips an untrusted hook, so a run that left any unapproved says
+ /// so and names `/hooks` instead of claiming the install is ready; all
+ /// trusted, or an unknown state, keeps the plain ready line.
+ #[test]
+ fn untrusted_codex_hooks_are_not_reported_as_ready() {
+ use super::super::codex_hook_trust::CodexHookTrust;
+ let ready = "ai-memory is set up.";
+
+ let untrusted = CodexHookTrust {
+ trusted: vec!["stop".to_owned()],
+ skipped: vec![
+ ("sessionStart".to_owned(), "untrusted".to_owned()),
+ ("userPromptSubmit".to_owned(), "modified".to_owned()),
+ ],
+ };
- let message = ready_message(Some(&untrusted));
++ let closing = next_step(&[AgentPlan::new(AgentChoice::Codex, None)]);
++ let message = ready_message(Some(&untrusted), &closing);
+ assert!(!message.contains(ready), "{message}");
+ assert!(message.contains("run /hooks"), "{message}");
+ assert!(
+ message.contains("2 ai-memory hook(s)")
+ && message.contains("sessionStart (untrusted)")
+ && message.contains("userPromptSubmit (modified)"),
+ "{message}"
+ );
+
+ let trusted = CodexHookTrust {
+ trusted: vec!["sessionStart".to_owned()],
+ skipped: Vec::new(),
+ };
- assert!(ready_message(Some(&trusted)).starts_with(ready));
- assert!(ready_message(None).starts_with(ready));
++ assert!(message.contains(FIRST_QUESTION), "{message}");
++ assert_eq!(ready_message(Some(&trusted), &closing), closing);
++ assert_eq!(ready_message(None, &closing), closing);
++ assert!(closing.starts_with(ready));
+ }
+
/// A token-file install learns how to open the web UI: the URL and the
/// file to read, never the token. An inline or absent token prints no hint.
#[test]
diff --cc crates/ai-memory-store/src/writer.rs
index 4a27c258,0aeb723f..984e5fcb
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@@ -489,9 -489,19 +489,20 @@@ pub(crate) enum WriteCmd
/// [`crate::ops::PurgeMode::Preview`] stops right after counting and
/// never issues the delete — see [`crate::ops::PurgeMode`]'s doc.
mode: crate::ops::PurgeMode,
+ owner: Option<IdentityKey>,
reply: oneshot::Sender<StoreResult<crate::ops::PurgeSessionSummary>>,
},
+ /// Final `wal_checkpoint(TRUNCATE)`, then close the connection and stop
+ /// the actor. See [`WriterHandle::checkpoint_and_close`].
+ Close {
+ reply: oneshot::Sender<()>,
+ },
+ /// Test seam: read `PRAGMA journal_size_limit` off the writer's own
+ /// connection, the only place the pragma is set.
+ #[cfg(test)]
+ JournalSizeLimit {
+ reply: oneshot::Sender<StoreResult<i64>>,
+ },
/// Reclaim free pages on demand: rebuild the FTS indexes and `VACUUM`,
/// deleting nothing. See [`ops::compact`].
Compact {
diff --cc docs/install.md
index 48a7c2b0,7cb0b379..788b0426
--- a/docs/install.md
+++ b/docs/install.md
@@@ -154,42 -127,21 +154,46 @@@ runs, in order, the commands a native i
`install-skills --scope global`. With no `--agent`, `setup` wires every
harness whose session store or MCP config exists under your home, using the
same store locations as `doctor` (including `CLAUDE_CONFIG_DIR`,
- `CODEX_HOME` and similar relocations). OpenCode 2 and the Kiro CLI v3
- engine share a store with OpenCode and Kiro CLI, so they are wired only
- when named, for example `--agent opencode2`.
+ `CODEX_HOME` and similar relocations). The plan numbers each agent and
+ says what it was found by (its session store, its MCP config, or for Muse
+ its directory), then lists the other agents `--agent` accepts. Cursor,
+ Gemini CLI, Droid and the other agents with no store to look for are
+ wired by naming them. OpenCode 2 and the Kiro CLI v3 engine share a store
+ with OpenCode and Kiro CLI, so they are wired only when named, for example
+ `--agent opencode2`.
4. A self-check that writes nothing: `GET /healthz`, a `memory_status` call
- over MCP with the install's credential, and `doctor`.
+ over MCP with the install's credential, and `doctor`. When Codex was wired,
+ `setup` also asks Codex whether it will run the ai-memory hooks. If Codex
+ has not trusted them yet, the closing line says so and tells you to open
+ Codex, run `/hooks`, and trust them, instead of reporting the install as
+ ready. That still exits 0, because only you can grant the trust in Codex.
-Without `--yes`, `setup` prints this plan and asks on a terminal; with no
-terminal (a script, an agent's tool call) it changes nothing and exits
-non-zero, asking for `--yes`. Each step is idempotent: a second run rewrites no
+Without `--yes`, `setup` prints this plan and asks on a terminal. `y` applies
+it. With more than one agent in the plan you can instead type the numbers of
+the agents to wire (`1 3` or `1,3`); every other step still runs, and an answer
+naming a number outside the plan changes nothing. With no terminal (a script,
+an agent's tool call) it changes nothing and exits non-zero, asking for
+`--yes`. `--plan` prints the plan and exits without changing anything;
+`--plan --json` prints it as a JSON document for a script or front end, with a
+`format` field that is bumped only when a field changes meaning or is removed.
+
+`ai-memory setup --web` shows the same plan as a page in your browser instead
+of the terminal. It prints a one-time address on `127.0.0.1` (and opens it,
+unless `--no-open` or there is no desktop), where you tick the agents to wire
+and press Apply. Apply runs `ai-memory setup --yes --agent <each one you
+picked>` and streams its output to the page, so the result is the same as the
+terminal command; `--no-service` is passed through. The page answers only
+requests that name its own address, carry the secret part of the URL, and,
+for a change, come from the page itself, so another site open in the same
+browser cannot drive it. It holds no token. It stops when you press Finish,
+after 15 minutes without a request, or on Ctrl-C. On a remote machine,
+forward the port it prints (`ssh -L <port>:127.0.0.1:<port> <host>`) and open
+the same address locally. Each step is idempotent: a second run rewrites no
file and leaves a running service alone. A step that fails does not stop the
-others; `setup` lists each `problem:` at the end and exits non-zero. The token
+others; `setup` lists each `problem:` at the end and exits non-zero. When every step
+passed it ends by naming the agents to restart and the question to ask one of
+them, "What do you remember about this project?": answering it takes a call
+to ai-memory's tools, so the reply shows the wiring works. The token
is never printed or passed on a command line, and no harness config holds it:
hooks read the credential files `init` writes, and MCP clients reach the
server through `ai-memory mcp-bridge`.
diff --cc docs/lifecycle-ops.md
index 9412ae0e,1e44637c..5ba34347
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@@ -945,45 -961,52 +962,91 @@@ What it does not recover
embeddings. Those live only in SQLite and require a full `backup` / `restore`
if you need to roll them back.
+### MCP `memory_restore_page`
+
+The agent-facing counterpart of `restore-page`. Without `rev` it lists the git
+checkpoints that changed one page, newest first, including the one that
+deleted it; with `rev` it writes that version back as the page's new current
+version.
+
+It differs from `restore-page` in how the text gets back in. The checkpoint's
+body and frontmatter (`title`, `tier`, `tags`, `pinned`, `expires_at`, `kind`,
+`entities`, `abstract`, `relations`, `applies_to`, `enforced_by`) go through the
+same path as `memory_write_page`: the sanitizer, the admission chain, write
+attribution and supersession all apply, and the version it replaces stays
+reachable. Metadata that `memory_write_page` would refuse is refused here too,
+before anything is written. Other frontmatter keys are not carried over.
+Scope is resolved once, without creating anything, and the listing, the read
+and the write all use that one project.
+
+Who may call it: an admin, the same authority as `/admin/restore-page`. Git
+history keeps every version the live wiki dropped, including pages a root
+deleted, pages a session purge removed and expired pages the forget sweep
+hard-deleted, so listing names them and restoring brings their text back. A DB
+user or proxied operator is refused for both, even on a project they can write
+and even for their own per-user slot. On a server that tells no operators
+apart (anonymous loopback, or a root bearer with no users) the caller is root
+and nothing changes. Over stdio there is no auth layer, and the caller already
+holds the data directory.
+
+Limits:
+
+- Project pages only. Pages written with `scope: "profile"` live in the
+ operator's profile and are not addressable here; restore them with
+ `restore-page` on the profile's project.
+- Listing walks at most 5,000 commits back from `HEAD`, off the async runtime,
+ so a page untouched for longer than that lists no checkpoints. Use
+ `ai-memory checkpoints` and `restore-page --from` for older history.
+- A restored `expires_at` is kept as written. If it is already past, the page
+ is hidden again at once and removed by the next forget sweep; restore an
+ expired page with `memory_write_page` and a new expiry instead.
+
+ ### Hook event ledgers are not in the wiki's git history
+
+ The raw hook event ledgers (`log.md` and `log-YYYY-MM.md` under each project)
+ are append-only logs that can reach hundreds of megabytes. Git stores every new
+ version of a file as a whole blob, and the server never packs or prunes the wiki
+ repository, so each checkpoint that followed a hook append added another copy of
+ the ledger: one install's `wiki/.git` grew to 3.49 GB. Nothing reads ledger
+ history back from git: `restore-page` and `checkpoints` work on pages, and
+ `backup` copies the data directory from disk.
+
+ Since this change a checkpoint leaves ledgers out of the commit. A file counts as
+ a ledger only when its name has the ledger shape **and** its first 8 KiB open
+ with a hook log entry (`## [timestamp] ...`, under optional frontmatter), the
+ same test the indexer and `reclaim-ledger-versions` use. A page that merely is
+ named `log-2026-09.md` stays versioned. The ledger file itself is never touched.
+ A ledger that an earlier version already committed is dropped from the git index
+ (`git rm --cached`) by the first checkpoint that sees it, so existing installs
+ stop growing without any step from you. The check runs when a checkpoint stages
+ files and does a bounded prefix read (at most 8 KiB) per check, never the
+ whole file; a ledger appended between that read and the commit is simply not in
+ the commit.
+
+ What this does **not** do: history already written keeps its old blobs, so
+ `wiki/.git` does not shrink by itself, and checkpoints taken before the upgrade
+ still contain old ledger versions. The server never rewrites or garbage-collects
+ that history. Shrinking it is an operator task, and it is destructive: every
+ commit id changes, so OIDs you noted from `ai-memory checkpoints` stop resolving,
+ and `git gc --prune=now` makes the old blobs unrecoverable. Stop the server, take
+ a `backup` first, and only then, as an example:
+
+ ```bash
+ cd <data-dir>/wiki
+ # Let the upgraded server take one checkpoint first, so HEAD no longer tracks the
+ # ledgers, and copy them aside anyway: a history rewrite resets the working tree.
+ # The globs match by name only. If you keep an ordinary page named like a
+ # ledger, they also delete that page's history, so narrow them first.
+ git filter-repo --force --invert-paths \
+ --path-glob '*/log.md' \
+ --path-glob '*/log-[0-9][0-9][0-9][0-9]-[0-9][0-9].md'
+ git reflog expire --expire=now --all
+ git gc --prune=now --aggressive
+ ```
+
+ Start the server again afterwards. `git filter-repo` is a separate tool and is
+ not installed with ai-memory.
+
### `backup`
```bash
diff --cc docs/security-boundaries.md
index c5e4160a,68898e66..44e418d6
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@@ -48,8 -47,7 +48,8 @@@ means the boundary is not built yet
| 4f | Finalize-on-exit closes only a session the run provably owns (invariant #16) | `ai-memory-cli/src/commands/run.rs` `finalize_hookless_session` runs only for `harness.lacks_session_end_hook()` harnesses (Command Code, Kiro v2/v3, Antigravity); `own_native_session` returns a session only when it is named, chosen before the spawn, or linked under this run's own id in this checkout — a merely *discovered* native session (possibly a concurrent launch's) is never finalized | `run.rs` `a_session_linked_during_the_run_wins_over_discovery` — `own_native_session` returns `None` for the unlinked and other-checkout (`nested`) cases, so a foreign/concurrent session is refused; the named/linked control is finalized (#944) | STRONG |
| 4g | `memory_handoff_accept` `status` never points a caller at another session's baton | `ai-memory-store/src/reader.rs` `handoff_claimed_by_live_session` — the caller-supplied session id (header or native `_meta`, routing-only per row 6b) selects which claim to check, but the answer is bounded by the resolved `(workspace_id, project_id)`, the authenticated `handoff_owner_sql` owner filter, `state='accepted'`, and a still-open receiving session; `ai-memory-mcp/src/server.rs` `unclaimed_handoff` reports `consumed_by_hook` only on that match (and, for a requested `handoff_id`, only when it is the matched row), `none_pending` otherwise | `handoff_ownership.rs` `a_session_start_claim_is_confirmed_only_to_its_own_live_session` (forged session id under another operator, unattributed reader, foreign project, sibling session and ended session all empty; owner and root controls see the claim); `ai-memory-mcp` `tests/suite/handoff_identity.rs` `consumed_by_hook_is_reported_only_to_the_session_that_claimed_it` (over the production transport: a colleague forwarding the session id, the owner from another session, and a request with no session id all get `none_pending`; the claiming session gets `consumed_by_hook`) | STRONG |
| 4h | Offer-mode SessionStart never consumes or injects handoff-controlled text | `ai-memory-hooks/src/router.rs` `fetch_and_accept_handoff_at` branches on the startup configuration before admission/claim and `render_handoff_notice` emits only typed metadata (`HandoffId`, `AgentKind`, computed age); the normal writer CAS remains the only later claim path | `router.rs` `handoff_notice_is_metadata_only_and_never_carries_the_summary` plants hostile summary/questions/steps/files; `offer_mode_leaves_the_baton_open_and_notice_omits_the_summary` exercises the production hook route, asserts the row remains open, then proves the legitimate exact-id writer claim still consumes it (#1030) | STRONG |
-| 4i | A hook never claims a handoff for an event that names no project directory | `GET /handoff` claims the newest open handoff in whatever project the server resolves; a request without `cwd` lets the server use its default or the caller's last active project, so the claim could consume another repository's handoff. Every front door gates the claim on a resolved directory and leaves the handoff open for `memory_handoff_accept`: the native hook in `ai-memory-cli/src/commands/hook.rs` `run_with_payload` (`handoff_scoped`, a resolved `policy_cwd`, gates SessionStart, Kimi's UserPromptSubmit and Grok's PostToolUse, with a stderr warning at SessionStart); the shell bundle's `hooks/_lib.sh` `ai_memory_get_handoff` (refuses a URL without the `&cwd=` that `ai_memory_marker_qs` adds for every named directory); the PowerShell `hooks/lib/ai-memory-hook.ps1` `Invoke-AiMemoryHook` (`$FetchHandoff -and $Cwd`); and the generated OpenCode, OpenCode 2, OMP and Pi integrations' `fetchHandoff` (`if (!cwd) return undefined;`). OpenClaw's `fetchHandoff` already required a directory. The only fallbacks are Devin's documented ones (`DEVIN_PROJECT_DIR`, then the hook's own directory), in `resolve_hook_cwd_with`, `ai_memory_resolve_cwd` and `Resolve-AiMemoryCwd` | `hook.rs` `a_handoff_is_never_claimed_without_a_project_directory` (Claude Code and Codex SessionStart, Kimi UserPromptSubmit and Grok PostToolUse with no `cwd` send no `GET /handoff`; control: the same events with a `cwd` claim once, naming it); `tests/hooks/test_lib.sh` "a handoff is never claimed without a project directory" (every shell script that fetches a handoff, discovered from the bundle and run from an unrelated directory: no payload directory, no claim; control: a directory claims and names it; Devin claims for its own directory; the PowerShell helper runs the same pair where a PowerShell exists, else a static pin); `install_hooks.rs` `generated_integrations_never_fetch_a_handoff_without_a_directory` and, running the generated OMP extension in Node, `slow_generated_handoff_runtime::omp_extension_never_claims_a_handoff_without_a_directory` (an empty `ctx.cwd` sends no claim; control: a directory claims). Each fails with its guard removed | STRONG for the native hook, the shell bundle and the generated integrations; the PowerShell runtime case runs only where a PowerShell is installed |
+| 4i | The compaction recap reads one session's own captured text and never writes or claims | `ai-memory-hooks/src/recap.rs` `handle_recap`/`build_recap` — anchored on the session row (`session_project_ids`), then `grants::authorize_resolved(.., ProjectAccess::Read)` on that project, whose refusal answers exactly like an unknown id (`200` with the no-session notice: no `403`, no project name), and `session_summary_scoped` with the `/handoff` owner filter (`User(key)` or `Unattributed`), so another operator's session answers like an unknown id; open handoffs are read with `list_handoffs` under the same owner filter and never claimed; nothing is written (no claim, active-project publish, observation, or page); stored text is rendered inside the untrusted-history fence with its markers escaped (`escape_untrusted_history_markers`) | `recap.rs` `recap_returns_the_window_and_writes_nothing` (the handoff stays open and the session's row count is unchanged), `another_operator_cannot_read_an_owned_session` (owner control: `owner_reads_own_session`), `db_user_without_grant_reads_a_session_as_unknown` (no status, project name or prompt text gives the refusal away; control: a read grant restores it); through the production `require_bearer` with real `aim_` tokens, `ai-memory-mcp/tests/suite/recap_identity.rs` `a_db_user_cannot_read_another_users_session_through_the_middleware` (owner control), `an_unattributed_caller_cannot_read_an_owned_session` (control: an unowned session stays readable) and `a_db_user_without_a_grant_reads_their_own_restricted_session_as_unknown` (control: a read grant), `recap_for_unknown_session_is_a_notice`, `fence_markers_in_stored_text_are_escaped` | STRONG |
- | 4j | A native hook never claims a handoff for an event that names no project directory | `ai-memory-cli/src/commands/hook.rs` `run_with_payload`: `handoff_scoped` (a resolved `policy_cwd`) gates every destructive `GET /handoff` the native hook sends, at SessionStart, Kimi's UserPromptSubmit and Grok's PostToolUse. Without it the request carries no `cwd`, the server resolves its default project or the caller's last active one, and the claim consumes another repository's baton; the handoff stays open for `memory_handoff_accept` and the hook says so on stderr. `resolve_hook_cwd_with` supplies the only fallbacks: Devin's `DEVIN_PROJECT_DIR` then process cwd, CodeBuddy's documented `CODEBUDDY_PROJECT_DIR` (never its process cwd) (#1299) | `hook.rs` `a_handoff_is_never_claimed_without_a_project_directory` (CodeBuddy and Claude Code SessionStart, Kimi UserPromptSubmit and Grok PostToolUse with no `cwd` send no `GET /handoff`; control: the same events with a `cwd` claim once, naming that directory) and `codebuddy_missing_cwd_uses_codebuddy_project_dir_only`; end to end against a real server, `ai-memory-cli/tests/suite/external_capture.rs` `codebuddy_start_without_a_directory_leaves_the_default_projects_handoff` (a CodeBuddy SessionStart with no `cwd`, run from inside the project, leaves the server-default project's handoff open; controls: the payload's `cwd`, then `CODEBUDDY_PROJECT_DIR`, claim it). Both fail with the guard removed | PARTIAL: STRONG for the native hook; the staged shell and PowerShell bundles have no such guard and still send the claim with whatever `cwd` the payload gave |
++| 4j | A hook never claims a handoff for an event that names no project directory | `GET /handoff` claims the newest open handoff in whatever project the server resolves; a request without `cwd` lets the server use its default or the caller's last active project, so the claim could consume another repository's handoff. Every front door gates the claim on a resolved directory and leaves the handoff open for `memory_handoff_accept`: the native hook in `ai-memory-cli/src/commands/hook.rs` `run_with_payload` (`handoff_scoped`, a resolved `policy_cwd`, gates SessionStart, Kimi's UserPromptSubmit and Grok's PostToolUse, with a stderr warning at SessionStart); the shell bundle's `hooks/_lib.sh` `ai_memory_get_handoff` (refuses a URL without the `&cwd=` that `ai_memory_marker_qs` adds for every named directory); the PowerShell `hooks/lib/ai-memory-hook.ps1` `Invoke-AiMemoryHook` (`$FetchHandoff -and $Cwd`); and the generated OpenCode, OpenCode 2, OMP and Pi integrations' `fetchHandoff` (`if (!cwd) return undefined;`). OpenClaw's `fetchHandoff` already required a directory. The only fallbacks are Devin's documented ones (`DEVIN_PROJECT_DIR`, then the hook's own directory), in `resolve_hook_cwd_with`, `ai_memory_resolve_cwd` and `Resolve-AiMemoryCwd`, and CodeBuddy's documented `CODEBUDDY_PROJECT_DIR` in the native hook (never its process cwd) (#1299) | `hook.rs` `a_handoff_is_never_claimed_without_a_project_directory` (CodeBuddy, Claude Code and Codex SessionStart, Kimi UserPromptSubmit and Grok PostToolUse with no `cwd` send no `GET /handoff`; control: the same events with a `cwd` claim once, naming it); `codebuddy_missing_cwd_uses_codebuddy_project_dir_only` and, end to end against a real server, `ai-memory-cli/tests/suite/external_capture.rs` `codebuddy_start_without_a_directory_leaves_the_default_projects_handoff` (a CodeBuddy SessionStart with no `cwd`, run from inside the project, leaves the server-default project's handoff open; controls: the payload's `cwd`, then `CODEBUDDY_PROJECT_DIR`, claim it); `tests/hooks/test_lib.sh` "a handoff is never claimed without a project directory" (every shell script that fetches a handoff, discovered from the bundle and run from an unrelated directory: no payload directory, no claim; control: a directory claims and names it; Devin claims for its own directory; the PowerShell helper runs the same pair where a PowerShell exists, else a static pin); `install_hooks.rs` `generated_integrations_never_fetch_a_handoff_without_a_directory` and, running the generated OMP extension in Node, `slow_generated_handoff_runtime::omp_extension_never_claims_a_handoff_without_a_directory` (an empty `ctx.cwd` sends no claim; control: a directory claims). Each fails with its guard removed | STRONG for the native hook, the shell bundle and the generated integrations; the PowerShell runtime case runs only where a PowerShell is installed |
| 5a | Pages shared: `author_id` is never a read filter (invariant #16) | `ai-memory-store/src/reader.rs` `search_pages`/`page_body_by_ids` — `author_id` is an attribution JOIN only, never a WHERE term; `observation_stream_votes` lets every session vote whatever its owner (the owner filter only withholds the observation excerpt and ids, never the vote or the page) | `multi_session.rs` — a page with a **non-null** `author_id` (operator A) is readable by operator B in the same project; `multi_session.rs` `another_operators_observations_lift_their_session_page_in_a_shared_project` (operator B's owned session, authored page and observations lift that page for operator A's query); `ai-memory-mcp` `server.rs` `observation_stream_evidence_stays_inside_a_restricted_project` (a second operator with only a read grant gets the session page lifted by the first operator's observation); `multi_session.rs` `observation_excerpts_follow_the_session_owner_while_the_vote_stays_shared` (B still gets A's session page ranked by A's observation, with the page's own snippet) | STRONG |
| 5b | Page supersession (loser stays reachable) | `ai-memory-store/src/ops.rs` `upsert_page_in_tx` — demote `is_latest=0` (never delete) + `supersedes` chain; read side: `reader.rs` `page_versions` lists every row at the path, with no `is_latest` filter, for `/web/w/…/h/*path` and `/api/v1/…/history/*path`. It does apply TTL expiry (`reader.rs` `history_visible`): a version whose own `expires_at` passed is neither listed nor readable by id, a path whose live version expired shows no history at all (the forget sweep hard-deletes every row there), and a `supersedes` link to a hidden version reads as `null`. Expiry is the only thing that hides a superseded version; a concurrent write never does | `multi_session.rs` `concurrent_writes_to_one_path_supersede_rather_than_destroy`; `retrieval_superseded.rs`; `multi_session.rs` `page_history_keeps_the_overwritten_version_and_stays_in_scope`; `ai-memory-web` `history_replay.rs` `history_keeps_both_sides_of_a_concurrent_divergent_write` (two attributed writers on one base: all three versions and both authors listed, one `is_latest`, the two writers' versions diff by id) and `history_lists_k_plus_one_versions_newest_first_and_diffs_the_latest`; bite: an `is_latest = 1` filter in `page_versions` fails both; `history_hides_expired_versions_and_expired_pages` (an expired superseded version and every version of a page whose live version expired answer 404 by path and by id on HTML and JSON, and the live successor's `supersedes` is `null`; control: a TTL in the future is listed and diffable; bites with the per-row predicate removed, with the live-version clause disabled, and with the `supersedes` hiding removed) | STRONG |
| 5c | Watcher reindex and Wiki writes share per-page serialization (invariant #16) | `ai-memory-wiki/src/wiki.rs` `reindex_page` takes `mutation_lock.read` before `reindex_page_locked` takes `lock_page`, covering disk read through the single-writer upsert; callers already holding the exclusive global guard do not reacquire it. `write_page` uses the same page mutex and `apply_batch` retains sorted, deduplicated locks; embedding runs after both guards are released | `wiki.rs` `reindex_page_lock_waits_before_reading_and_allows_another_path` (transient snapshot refused while locked, another path progresses, release indexes the committed bytes without rewriting disk), `reindex_page_lock_serializes_write_through_the_upsert` and `reindex_page_lock_and_reversed_duplicate_batches_do_not_deadlock` (real concurrent operations, final disk/SQL winner and supersession ancestry preserved); all three fail with the reindex page guard removed. `reindex_page_lock_releases_both_guards_before_embedding` checks both body and abstract embedding; `decay_cleanup_reindex_does_not_embed_under_the_exclusive_lock` covers the exclusive caller | STRONG for a shared Wiki handle and its clones. External editors and independently constructed Wiki handles do not participate in these locks |
diff --cc docs/support-matrix.md
index cc057cdd,b7d7f6e7..dd1f2fe8
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@@ -32,8 -32,8 +32,8 @@@
| Claude Desktop (Chat) | MCP-only | Uses `mcp-remote`; the ordinary Chat surface does not run lifecycle hooks. macOS, Windows, and Linux (Anthropic's Debian/Ubuntu beta, `~/.config/Claude/claude_desktop_config.json`). Cowork capture is not claimed; see the explicit boundary in [`mcp-install.md`](mcp-install.md#claude-desktop). |
| Claude Desktop (Code tab) | Supported | Local Code-tab sessions run Claude Code with the user's `~/.claude/settings.json`, so the Claude Code hooks capture them as `claude-code`; a session without a project folder lands in its own scratch-directory project. |
| OpenClaw | Supported | MCP config + native plugin lifecycle hooks; generated plugin enforces capture exclusions. |
- | 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). |
+ | Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). Only `PreInvocation` with `invocationNum = 0` on the first turn of a conversation maps to SessionStart (the counter restarts every turn, so later turns and 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). `install-hooks --agent grok --apply` and `install-skills --scope global --agent grok` also write `$GROK_HOME/rules/ai-memory-handoff.md` so the first turn calls `memory_handoff_list` through `use_tool` with the qualified catalog key `ai-memory__memory_handoff_list` (Grok reaches MCP tools only through that meta-tool) ahead of any file read, correcting `workspace`/`project` from `./.ai-memory.toml` only when that list is empty or a scope error; the first `PostToolUse` then prints `hookSpecificOutput.additionalContext` with the pending handoff and an opted-in `[briefing]`. If that rule is absent and 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`). |
+| 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). `install-hooks --agent grok --apply` and `install-skills --scope global --agent grok` also write `$GROK_HOME/rules/ai-memory-handoff.md` so the first turn calls `memory_handoff_list` through `use_tool` with the qualified catalog key `ai-memory__memory_handoff_list` (Grok reaches MCP tools only through that meta-tool) ahead of any file read, correcting `workspace`/`project` from `./.ai-memory.toml` only when that list is empty or a scope error; the first `PostToolUse` then prints `hookSpecificOutput.additionalContext` with the pending handoff and an opted-in `[briefing]`. If that rule is absent and 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`). A prompt starting with `reload context` receives a compaction recap on the next `PostToolUse` `additionalContext`, not with the prompt (see [`usage.md`](usage.md#reload-context-after-a-compaction)). |
| 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` when the token is passed explicitly; a token-file install gets a stdio `ai-memory mcp-bridge --no-session-id` entry instead) + 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. It is refused when the bearer lives in a token file (every fresh `init`), because ZCode keeps only a literal header; add the entry by hand there. 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 managed workstream is claimed yet. |