Skip to content

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

Rust

docs: reload context after a compaction

Giovanni Coutinhof785785f997c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b40eda8d..56f9eb83 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -457,6 +457,16 @@ and [0.x](docs/changelog/0.x.md).
server built from the same commit, including a schema drift test that fails
when an MCP tool changes without an SDK update. See
`companions/ai-memory-ts/README.md` and `docs/design-client-sdk.md`. (#1165)
+- 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`.
+ Nothing is written, so a reload never consumes a baton (#NNN).
### Changed
- Documented the 2.x to 3.0 upgrade in `docs/upgrading-to-3.0.md`: what
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md
index 3d5300a0..4649dfd6 100644
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md
@@ -21,6 +21,10 @@ The SessionStart hook usually fetches and consumes any pending handoff before th
If no pending handoff block is visible, inspect with `memory_handoff_list` first. Listing does not claim or expire anything. When the user asks where we left off, claim one listed row with `memory_handoff_accept` and that `handoff_id`, using the client-aware project scope below. Do not treat list as a second accept path.
+## Reloading context after a compaction
+
+A prompt that starts with `reload context` gets a "compaction recap" block from the hooks: the user's prompts and the last captured reply from the stretch of this session that the last compaction dropped, plus the project's open handoffs, none of them claimed. Claude Code, Codex and OpenCode add it to that turn; Grok shows it after the first tool result. Answer from that block, then do what the rest of the prompt asks. If no recap block is in context, use the ai-memory retrieval skill to read this session's raw prompts and replies (`kinds: ["user-prompt", "stop"]`).
+
## Creating a handoff
Create a handoff only at session end or when the user explicitly asks to save context for the next session. Do not use handoffs for status checks, briefings, project notes, or permanent memory. Keep the summary to two or three concise sentences, and put details in open questions and next steps bullets.
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index e97bc1ab..7f4d061f 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -274,6 +274,13 @@ same transaction expires older eligible automatic handoffs while preserving
manual and sibling-directory work. Insertion also expires prior open automatic
handoffs from the exact cwd, bounding repeated SessionEnds before any receiver
starts.
+`GET /recap?session_id=` answers a prompt that starts with `reload context`
+(Claude Code and Codex in the `UserPromptSubmit` envelope, Grok on the next
+`PostToolUse`, OpenCode through its system/context hooks). It is read-only and
+anchored on the session row rather than a cwd: project read authorization and
+the handoff owner filter gate it, and it renders the captured prompts and last
+reply between the session's latest two `pre-compact` observations plus the
+project's open handoffs, listed without a claim.
ai-memory opens native stores read-only. Raw sanitized JSONL segments are
immutable, while SQLite supplies monotonic sequences, FTS, native
source/delivery cursors, and idempotent retry state. A full-ledger
diff --git a/docs/support-matrix.md b/docs/support-matrix.md
index 306cc8a2..d3485f87 100644
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@ -16,11 +16,11 @@
| macOS | Supported | Workspace tests run in CI; tagged releases publish native `ai-memory-macos-aarch64.tar.gz` and `ai-memory-macos-x86_64.tar.gz` binaries, which include a per-user launchd agent. The native binary is the recommended path on Apple Silicon. A source-built menu bar app (`companions/ai-memory-macos`) bundles that binary, starts the LaunchAgent, and opens `/web` and `ai-memory status` — README quick-start and [`docs/macos.md`](macos.md) Scenario D. |
| Windows via WSL2 | Supported | Use the Linux install path inside WSL2 when the agent runs there. |
| Native Windows | Experimental | Tagged releases publish `ai-memory-windows-x86_64.zip` with `ai-memory.exe`; Docker Desktop wrapper and source builds are also available. Native `ai-memory upgrade` is supported for writable x86_64 zip installs (checksum-verified zip + rename-aside self-replace + sibling `hooks/` refresh). Local supported profiles default to host-native hook commands; Claude Code may use its Windows exec form, while other agents use native single command strings matching their hook schema. PowerShell/Git Bash scripts are compatibility fallbacks. See [`docs/windows.md`](windows.md). |
-| Claude Code | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. The same hooks, MCP tools and skills also ship as a marketplace plugin (ai-memory 3.0 or later; see [`install.md`](install.md#marketplace-plugins)). `install-mcp --session-aware` optionally enables per-session auto-scope isolation through a local stdio bridge; on a token-file install (every fresh `init`) the session-aware bridge entry is automatic. Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default). |
-| Codex | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. The same hooks, MCP tools and skills also ship as a marketplace plugin (ai-memory 3.0 or later; see [`install.md`](install.md#marketplace-plugins)). `SessionEnd` is wired since Codex CLI 0.145.0 (openai/codex#33895), so finished sessions get an automatic end-of-session summary/handoff; on older Codex the event is inert and `ai-memory finalize-session --agent codex` is the fallback. Managed runs (`ai-memory run codex`) recover when Codex's shared daemon reports a stale run id, provided exactly one live run matches the authorized project, checkout, and operator; ambiguous matches fail closed. `--no-daemon` remains available as an isolation and diagnostic option (see [`docs/managed-workstreams.md`](managed-workstreams.md)). Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default) — Codex's `Stop` payload carries `last_assistant_message`, same as Claude Code. |
+| Claude Code | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. The same hooks, MCP tools and skills also ship as a marketplace plugin (ai-memory 3.0 or later; see [`install.md`](install.md#marketplace-plugins)). `install-mcp --session-aware` optionally enables per-session auto-scope isolation through a local stdio bridge; on a token-file install (every fresh `init`) the session-aware bridge entry is automatic. Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default). A prompt starting with `reload context` receives a compaction recap through `UserPromptSubmit` `additionalContext` (see [`usage.md`](usage.md#reload-context-after-a-compaction)). |
+| Codex | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. The same hooks, MCP tools and skills also ship as a marketplace plugin (ai-memory 3.0 or later; see [`install.md`](install.md#marketplace-plugins)). `SessionEnd` is wired since Codex CLI 0.145.0 (openai/codex#33895), so finished sessions get an automatic end-of-session summary/handoff; on older Codex the event is inert and `ai-memory finalize-session --agent codex` is the fallback. Managed runs (`ai-memory run codex`) recover when Codex's shared daemon reports a stale run id, provided exactly one live run matches the authorized project, checkout, and operator; ambiguous matches fail closed. `--no-daemon` remains available as an isolation and diagnostic option (see [`docs/managed-workstreams.md`](managed-workstreams.md)). Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default) — Codex's `Stop` payload carries `last_assistant_message`, same as Claude Code. A prompt starting with `reload context` receives a compaction recap as `UserPromptSubmit` developer context, capped at 6,000 chars (see [`usage.md`](usage.md#reload-context-after-a-compaction)). |
| Command Code | Supported | MCP config (`~/.commandcode/mcp.json`) + its four stable lifecycle-hook events (`~/.commandcode/settings.json`); native commands enforce capture exclusions and `SessionStart` injects handoffs. `Stop` is only a turn boundary, so use `ai-memory finalize-session --agent command-code` after the final turn; an interactive session launched with `ai-memory run command-code` 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 command-code` adds exact v3 native-session resume and visible-event import; experimental unsandboxed Mods remain excluded. |
| Devin CLI | Supported | MCP config + lifecycle hooks. Hooks use Devin's `PostCompaction` event, inject handoffs via `hookSpecificOutput.additionalContext`, and omit subagent events because Devin does not expose them. |
-| OpenCode (V1/V2 auto-detected) | Supported | Host-side generic `opencode` commands probe the exact executable and select the V1 direct MCP/function-plugin/transcript contracts or V2 nested `mcp.servers`/`{ id, setup }` plugin/`session_v2` contracts. The result is reused through managed discovery, launch, auto-wire, and transcript import; an automatic run skips OpenCode when probing fails but continues other harness discovery. Container-oriented `setup-agent` requires `--opencode-dialect v1|v2`. Generated sibling plugins and alternate MCP entries are migrated only when ai-memory ownership is proven. |
+| OpenCode (V1/V2 auto-detected) | Supported | Host-side generic `opencode` commands probe the exact executable and select the V1 direct MCP/function-plugin/transcript contracts or V2 nested `mcp.servers`/`{ id, setup }` plugin/`session_v2` contracts. The result is reused through managed discovery, launch, auto-wire, and transcript import; an automatic run skips OpenCode when probing fails but continues other harness discovery. Container-oriented `setup-agent` requires `--opencode-dialect v1|v2`. Generated sibling plugins and alternate MCP entries are migrated only when ai-memory ownership is proven. A prompt starting with `reload context` receives a compaction recap through the plugin's system/context hook until the next compaction (see [`usage.md`](usage.md#reload-context-after-a-compaction)). |
| OpenCode V2 compatibility aliases | Supported | `opencode2`, `opencode-v2`, and `open-code2` force V2 compatibility without probing. V2 completed root turns checkpoint the session page and baton without ending the shared service's session; MCP calls route by the native `_meta` session id, and `--capture-assistant` is supported (double opt-in). |
| Cursor | Supported | MCP config + lifecycle hooks. |
| Gemini CLI | Supported | MCP config + lifecycle hooks. |
@@ -33,7 +33,7 @@
| 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). |
-| 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. |
diff --git a/docs/usage.md b/docs/usage.md
index edab69a1..a05b81ba 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -151,6 +151,44 @@ consolidation. Checkpoints and superseding versions therefore keep the same
origin. Manual `memory_write_page` and `ai-memory write-page` calls do not
infer an agent.
+### Reload context after a compaction
+
+A compaction keeps a model-written summary of the conversation, and the
+summary can drop or soften what you asked. Start a prompt with
+`reload context` to put the stretch it dropped back in front of the agent:
+
+```
+reload context after last compaction, then finish the screenshots for guide 12
+```
+
+The hooks see the phrase at the start of the prompt (any case; a sentence
+that only mentions it does not count) and inject a **compaction recap** built
+from what ai-memory captured for this session between its latest compaction
+and the one before it (or the session start):
+
+- your prompts in that stretch, verbatim, oldest first; harness markup and
+ task notifications are left out, and when they do not all fit the oldest
+ are dropped first;
+- the agent's last reply before the compaction. Replies are captured only
+ with the assistant-capture double opt-in (`install-hooks --capture-assistant`
+ plus `capture_assistant` on the server); without it the recap says so;
+- the project's open handoffs, listed and never claimed, this session's own
+ first.
+
+The rest of the prompt runs as usual with the recap in context. Nothing is
+written: no handoff is claimed, no observation or page is added.
+
+| Harness | When the agent sees the recap |
+|---|---|
+| Claude Code | With that prompt (`UserPromptSubmit` `additionalContext`, up to 8,000 chars) |
+| Codex | With that prompt (developer context, up to 6,000 chars to stay under Codex's hook-output preview limit) |
+| OpenCode V1 / V2 | With that prompt and later model calls, until the next compaction |
+| Grok Build | After the first tool result of that turn: Grok discards `UserPromptSubmit` output. A request with no tool call expires after 30 minutes or at session end |
+
+A session that has not been compacted yet answers with a one-line notice. The
+full record stays available through `memory_read_session_observations` with
+the session id and `kinds: ["user-prompt", "stop"]`.
+
## Proactive memory queries
Hooks handle capture without prompting. Proactive querying depends on
diff --git a/plugins/claude-code/skills/ai-memory-handoff/SKILL.md b/plugins/claude-code/skills/ai-memory-handoff/SKILL.md
index 3d5300a0..4649dfd6 100644
--- a/plugins/claude-code/skills/ai-memory-handoff/SKILL.md
+++ b/plugins/claude-code/skills/ai-memory-handoff/SKILL.md
@@ -21,6 +21,10 @@ The SessionStart hook usually fetches and consumes any pending handoff before th
If no pending handoff block is visible, inspect with `memory_handoff_list` first. Listing does not claim or expire anything. When the user asks where we left off, claim one listed row with `memory_handoff_accept` and that `handoff_id`, using the client-aware project scope below. Do not treat list as a second accept path.
+## Reloading context after a compaction
+
+A prompt that starts with `reload context` gets a "compaction recap" block from the hooks: the user's prompts and the last captured reply from the stretch of this session that the last compaction dropped, plus the project's open handoffs, none of them claimed. Claude Code, Codex and OpenCode add it to that turn; Grok shows it after the first tool result. Answer from that block, then do what the rest of the prompt asks. If no recap block is in context, use the ai-memory retrieval skill to read this session's raw prompts and replies (`kinds: ["user-prompt", "stop"]`).
+
## Creating a handoff
Create a handoff only at session end or when the user explicitly asks to save context for the next session. Do not use handoffs for status checks, briefings, project notes, or permanent memory. Keep the summary to two or three concise sentences, and put details in open questions and next steps bullets.
diff --git a/plugins/codex/skills/ai-memory-handoff/SKILL.md b/plugins/codex/skills/ai-memory-handoff/SKILL.md
index 3d5300a0..4649dfd6 100644
--- a/plugins/codex/skills/ai-memory-handoff/SKILL.md
+++ b/plugins/codex/skills/ai-memory-handoff/SKILL.md
@@ -21,6 +21,10 @@ The SessionStart hook usually fetches and consumes any pending handoff before th
If no pending handoff block is visible, inspect with `memory_handoff_list` first. Listing does not claim or expire anything. When the user asks where we left off, claim one listed row with `memory_handoff_accept` and that `handoff_id`, using the client-aware project scope below. Do not treat list as a second accept path.
+## Reloading context after a compaction
+
+A prompt that starts with `reload context` gets a "compaction recap" block from the hooks: the user's prompts and the last captured reply from the stretch of this session that the last compaction dropped, plus the project's open handoffs, none of them claimed. Claude Code, Codex and OpenCode add it to that turn; Grok shows it after the first tool result. Answer from that block, then do what the rest of the prompt asks. If no recap block is in context, use the ai-memory retrieval skill to read this session's raw prompts and replies (`kinds: ["user-prompt", "stop"]`).
+
## Creating a handoff
Create a handoff only at session end or when the user explicitly asks to save context for the next session. Do not use handoffs for status checks, briefings, project notes, or permanent memory. Keep the summary to two or three concise sentences, and put details in open questions and next steps bullets.