Skip to content

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

Rust

M17: docker-primary install flow + setup-agent + curl installer

AkitaOnRails622082f3cde4
diff --git a/README.md b/README.md
index 198c7dfb..17deb54f 100644
--- a/README.md
+++ b/README.md
@@ -1,245 +1,134 @@
# ai-memory
-> Long-term memory for AI coding agents. Quit Claude Code mid-task, start
-> OpenAI Codex in the same directory, continue without re-explaining the
-> architecture, the failed approaches, or the open questions.
+> Long-term memory for AI coding agents. Quit Claude Code mid-task,
+> start OpenAI Codex in the same directory, continue without
+> re-explaining the architecture, the failed approaches, or the open
+> questions.
[![status: v0.2 milestones complete](https://img.shields.io/badge/status-v0.2--complete-green)](docs/ARCHITECTURE.md)
[![Rust](https://img.shields.io/badge/rust-1.95+-blue)](rust-toolchain.toml)
[![License](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue)](#license)
-## Why this exists
+## What it is
-LLM coding agents lose all context when a session ends. Today's
-"memory" tools either (a) require the user to manually invoke
-`write_note` every time something matters, or (b) wrap a vector
-database in a chat shim and call it RAG.
+LLM coding agents lose all context when a session ends. ai-memory
+gives them a shared, persistent wiki: every prompt, tool call, and
+decision is captured automatically; when a session ends, the relevant
+pages get rewritten as a coherent narrative; when the next agent
+starts (Claude Code, Codex, OpenCode, …) it sees a handoff with
+"where you left off" already prepended.
-ai-memory takes a different bet, faithful to
-[Andrej Karpathy's "LLM Wiki"](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f)
-pattern: knowledge is **compiled** at ingest time into a structured,
-cross-linked, supersedeable wiki on disk — not retrieved over raw logs
-at query time. The wiki is plain markdown in a git repo, so you can
-`grep` it, open it in Obsidian, diff it, and back it up with `rsync`.
+The wiki is plain markdown in a git repo — `grep`-able, openable in
+Obsidian, backed up with `rsync`. No vector database to babysit, no
+`write_note` ceremony, no manual context-loading. The full design is
+in [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md); the influences and
+priors are at the [bottom](#influences-and-prior-art).
-Capture is **fully automatic** via the agent CLI's lifecycle hooks; there
-is no `write_note` ceremony. Consolidation runs in the background when
-a session ends and when the agent's own context window is about to be
-compacted — both moments where state would otherwise be lost.
+## Quick start
-## Status
-
-**v0.2 complete.** Milestones M0 through M10 have shipped. Single
-package; 57+ unit + integration tests passing, `cargo clippy
---workspace -D warnings` clean, `cargo fmt --check` clean.
-
-## Quick start (Docker)
-
-The recommended way to run ai-memory is as a long-lived container on
-your dev machine or homelab. The image is published to Docker Hub at
-[`akitaonrails/ai-memory:latest`](https://hub.docker.com/r/akitaonrails/ai-memory).
+You need: Docker + an agent CLI (Claude Code, Codex, OpenCode, Cursor,
+or anything else that speaks MCP).
```bash
-# Zero-LLM mode: pure FTS5 search, rule-based session summaries.
-# No API keys needed. Good for trying it out.
-docker run -d --name ai-memory \
- -p 49374:49374 \
- -v ai-memory-data:/data \
- akitaonrails/ai-memory:latest
-```
+# 1. Generate a bearer token (one-time; save the output).
+export TOKEN=$(docker run --rm akitaonrails/ai-memory:latest generate-auth-token)
-```bash
-# Full mode: LLM-driven consolidation + hybrid search.
-# Recommended defaults: Claude Sonnet for consolidation,
-# OpenAI text-embedding-3-small for embeddings.
+# 2. Start the server. Replace the API keys (or omit the four
+# -e AI_MEMORY_LLM_* / EMBEDDING_* lines for zero-LLM mode — FTS5
+# search still works without any keys).
docker run -d --name ai-memory \
-p 49374:49374 \
-v ai-memory-data:/data \
+ -e AI_MEMORY_AUTH_TOKEN="$TOKEN" \
-e AI_MEMORY_LLM_PROVIDER=anthropic \
-e ANTHROPIC_API_KEY=sk-ant-... \
-e AI_MEMORY_EMBEDDING_PROVIDER=openai \
-e OPENAI_API_KEY=sk-... \
akitaonrails/ai-memory:latest
-```
-
-The server listens on `127.0.0.1:49374` (port `0xC0DE` — "CODE" in hex,
-in IANA's dynamic/private range so it won't clash with registered
-services). MCP endpoint: `http://127.0.0.1:49374/mcp`. Hook ingress:
-`http://127.0.0.1:49374/hook`.
-
-Inspect state with `docker exec ai-memory ai-memory status --json`.
-Wiki and SQLite live in the `ai-memory-data` volume; back up with
-`docker run --rm -v ai-memory-data:/data busybox tar -czf - /data >
-ai-memory-$(date +%F).tar.gz`.
-
-## Configure your agent CLI
-
-Each agent CLI needs two things wired up:
-
-1. **MCP connection** — so the agent can call `memory_query`,
- `memory_recent`, etc.
-2. **Lifecycle hooks** — so the server auto-captures session events.
- This is what makes capture "free".
-
-### Claude Code
-
-```bash
-# 1. Register the MCP server (HTTP transport).
-claude mcp add --transport http ai-memory http://127.0.0.1:49374/mcp
-
-# 2. Install the lifecycle hooks. Clone the repo to get the scripts:
-git clone https://github.com/akitaonrails/ai-memory ~/.ai-memory
-cd ~/.ai-memory && cargo build --release
-# Then print the JSON to merge into ~/.claude/settings.json:
-~/.ai-memory/target/release/ai-memory install-hooks --agent claude-code
-```
-
-The hook scripts are tiny POSIX shell wrappers that `curl` the event
-JSON to `127.0.0.1:49374/hook` with sub-second timeouts. They never
-block the agent.
-
-### OpenAI Codex
-
-```bash
-# 1. MCP — add to ~/.codex/config.toml:
-[mcp_servers.ai-memory]
-url = "http://127.0.0.1:49374/mcp"
-
-# 2. Lifecycle hooks — Codex uses its own hooks file; the install
-# helper prints the snippet to merge:
-~/.ai-memory/target/release/ai-memory install-hooks --agent codex
-```
-
-### OpenCode
-
-```bash
-# Same pattern; see `ai-memory install-hooks --agent opencode` for
-# the agent-specific config format.
-~/.ai-memory/target/release/ai-memory install-hooks --agent opencode
-```
-### Other MCP clients — Cursor, Claude Desktop, Gemini CLI, OpenClaw, pi
+# 3. Wire your agent CLI to it. Claude Code shown below; for Codex,
+# OpenCode, Cursor, Claude Desktop, Gemini CLI, OpenClaw, see
+# docs/install.md.
-These clients don't currently have lifecycle-hook bundles in
-`hooks/`, but ai-memory still works with them via MCP. See
-[**`docs/mcp-install.md`**](docs/mcp-install.md) for the per-client
-config-file path and snippet.
+# 3a. Register the MCP endpoint
+claude mcp add --transport http ai-memory http://localhost:49374/mcp \
+ --header "Authorization: Bearer $TOKEN"
-Quick reference:
+# 3b. Extract the bundled hook scripts to your home dir
+docker cp ai-memory:/usr/local/share/ai-memory/hooks ~/.ai-memory/
-```bash
-ai-memory install-mcp --client cursor # ~/.cursor/mcp.json
-ai-memory install-mcp --client claude-desktop # Claude Desktop config
-ai-memory install-mcp --client gemini-cli # ~/.gemini/settings.json
-ai-memory install-mcp --client openclaw # ~/.openclaw/config.json
-ai-memory install-mcp --client pi # prints why pi is not MCP-supported
+# 3c. Render the settings.json snippet, then merge the printed JSON
+# into ~/.claude/settings.json (chmod 600 the file)
+docker run --rm akitaonrails/ai-memory:latest \
+ install-hooks --agent claude-code \
+ --hooks-dir ~/.ai-memory/hooks \
+ --server-url "http://localhost:49374" \
+ --auth-token "$TOKEN"
```
-The MCP-only clients get the read/query side (the LLM can call
-`memory_query`, `memory_recent`, `memory_handoff_accept`), but not
-auto-capture — you nudge the model to call those tools yourself
-(see [the CLAUDE.md snippet](#nudging-the-agent-to-use-memory-proactively)).
-
-## LLM provider, models, and API keys
-
-ai-memory works in three intensity tiers. **The default Docker run is
-the zero-LLM tier** — no API keys required, everything still works,
-just with deterministic rule-based summaries and FTS5-only retrieval.
-
-| Tier | What you get | Env vars | Cost |
-|---|---|---|---|
-| **Zero-LLM** | FTS5 search, rule-based session pages, auto-handoffs | (none) | $0 |
-| **+ LLM consolidation** | LLM rewrites session pages as coherent narratives; LLM-driven contradiction lint; PreCompact checkpoints | `AI_MEMORY_LLM_PROVIDER=anthropic` + `ANTHROPIC_API_KEY` | ~$0.01–0.05 per session |
-| **+ Hybrid retrieval** | RRF over FTS5 + vector cosine similarity. Better recall on paraphrased queries | `AI_MEMORY_EMBEDDING_PROVIDER=openai` + `OPENAI_API_KEY` | ~$0.0001 per page on backfill |
-
-### Recommended models (chosen as defaults)
-
-If you set the **provider** but not the model, ai-memory picks
-sensible defaults. Override with the corresponding env var.
-
-| Setting | Default | Why this default | Override |
-|---|---|---|---|
-| Anthropic LLM | `claude-sonnet-4-6` | Smart enough to summarise a session into coherent narrative; cheap enough to run on every session-end without thinking about it. Not a reasoning model — consolidation doesn't benefit from extended thinking. | `AI_MEMORY_LLM_MODEL` |
-| OpenAI LLM | `gpt-4o-mini` | Closest OpenAI equivalent to the Sonnet tier in price/quality. | `AI_MEMORY_LLM_MODEL` |
-| OpenAI embedding | `text-embedding-3-small` (1536-dim) | Best price/quality from OpenAI; 5× cheaper than `text-embedding-3-large` with marginal recall loss. | `AI_MEMORY_EMBEDDING_MODEL` + `AI_MEMORY_EMBEDDING_DIM` |
-| Voyage embedding | `voyage-3` (1024-dim) | Voyage's current general-purpose recommendation. | same |
+That's it. Start a Claude Code session as usual — every prompt and
+tool call now lands in ai-memory, and the next session you open in
+this project will see a handoff with where you left off.
-For **self-hosted LLMs** (Ollama, vLLM, LM Studio):
+**For everything else** — Codex, OpenCode, Cursor, Claude Desktop,
+Gemini CLI, OpenClaw, the curl-based hook installer (no docker
+needed), running ai-memory without docker, the full subcommand
+reference, the homelab deploy pattern, security hardening — see
+[**`docs/install.md`**](docs/install.md).
-```bash
-docker run -d --name ai-memory \
- -p 49374:49374 \
- -v ai-memory-data:/data \
- -e AI_MEMORY_LLM_PROVIDER=openai-compat \
- -e AI_MEMORY_LLM_BASE_URL=http://host.docker.internal:11434/v1 \
- -e AI_MEMORY_LLM_MODEL=qwen2.5-coder:14b \
- akitaonrails/ai-memory:latest
-```
+## How it works in practice
-There is no safe default model for `openai-compat` — what you can run
-depends on your local setup, so the model env var is required.
+You mostly don't think about it. Hooks capture every prompt + tool
+call + session boundary automatically. The agent gains awareness of
+prior work without you typing anything special. A few patterns are
+worth knowing:
-## How to use it in practice
-
-The point of ai-memory is that you mostly **don't** think about it.
-Lifecycle hooks capture every prompt + tool call + session boundary
-automatically. The agent gains awareness of prior work without you
-typing anything special. That said, a few patterns are worth knowing:
-
-### Cross-agent handoff (the headline feature)
+### Cross-agent handoff
```
$ claude
-> "Working on the auth refactor. The current approach uses JWT but
- we found the rotation story is broken. Investigating session
- cookies as an alternative."
+> "Working on the auth refactor. JWT rotation story is broken; trying
+ session cookies as an alternative."
[work for an hour]
> /exit
$ codex # in the same directory, hours or days later
-[Codex starts; the SessionStart hook synchronously fetches the open
- handoff and prepends it to the session.]
-> "Picking up from prior work: you were investigating session cookies
- as an alternative to broken JWT rotation. Continuing?"
+[SessionStart hook fetches the handoff; the next agent sees it.]
+> "Picking up: you were investigating session cookies as an
+ alternative to broken JWT rotation. Continuing?"
```
-You did nothing special. The handoff was created automatically on
-Claude Code's session-end, and surfaced automatically on Codex's
-session-start.
+You did nothing special. Handoff created automatically on Claude
+Code's session-end, surfaced automatically on Codex's session-start.
-### Context-window compaction recovery
+### Compaction recovery
When Claude Code or Codex compact their working context, the
`PreCompact` hook fires and ai-memory writes a fresh
-`sessions/<id>.md` page summarising the session so far (LLM-driven
-if you've configured a provider, rule-based otherwise). After
-compaction, the agent can call `memory_recent` to recover the
-high-signal summary even though its raw history is gone.
+`sessions/<id>.md` page summarising the session so far. After
+compaction, the agent can recover the summary via `memory_recent`
+even though its raw history is gone.
### Spelunking your own history
-The wiki dir is plain markdown in a git repo:
-
```bash
docker exec ai-memory ls /data/wiki/sessions/
docker exec ai-memory cat /data/wiki/sessions/<uuid>.md
-# Open in Obsidian or any markdown viewer:
+# Open in Obsidian / any markdown viewer:
docker cp ai-memory:/data/wiki ./my-ai-memory-wiki
-obsidian ./my-ai-memory-wiki
# Time-travel:
docker exec ai-memory git -C /data/wiki log --oneline
```
-### Nudging the agent to use memory proactively
+### Nudge the agent to *use* memory proactively
Lifecycle hooks handle *capture* and *handoff resume* without you
-typing anything. Proactive *querying* (e.g. "did we already decide
-on this?") still depends on the agent thinking to call
-`memory_query`. The tool descriptions already nudge in that
-direction, but for projects where memory is load-bearing, drop this
-snippet into your project's `CLAUDE.md`:
+typing anything. Proactive *querying* still depends on the agent
+thinking to call `memory_query`. The tool descriptions nudge in that
+direction; for projects where memory matters, drop this in your
+`CLAUDE.md` / agent system prompt:
```markdown
## Long-term memory
@@ -248,64 +137,58 @@ This project uses ai-memory. The SessionStart hook auto-fetches any
pending handoff. Beyond that, proactively use:
- `memory_query` — before proposing architecture, when the user
- references prior work you don't recognise, or when investigating
- a bug that might have a known root cause.
-- `memory_recent` — at session start (in addition to the auto-fetched
- handoff) to scan the last few pages.
-- `memory_handoff_begin` — optional; only if you want to capture
- extra context beyond what the SessionEnd hook captures by default.
+ references prior work you don't recognise, or when investigating a
+ bug that might have a known root cause.
+- `memory_recent` — at session start to scan the last few pages.
+- `memory_handoff_begin` — optional; only if you want extra context
+ beyond what the SessionEnd hook captures by default.
```
-This is the least obtrusive way to encourage proactive use — it
-lives in the project's own instructions rather than every user
-prompt.
+## LLM provider — recommended defaults
-## CLI reference (when not using Docker)
+You can run ai-memory entirely without an LLM (FTS5 search +
+rule-based summaries, $0). When you do configure one, sensible
+defaults kick in for the model:
-If you'd rather run ai-memory directly:
+| Provider env | Default model | Notes |
+|---|---|---|
+| `AI_MEMORY_LLM_PROVIDER=anthropic` | `claude-sonnet-4-6` | Smart enough to summarise a session, cheap enough to run on every session-end. |
+| `AI_MEMORY_LLM_PROVIDER=openai` | `gpt-4o-mini` | OpenAI equivalent of the Sonnet tier in price/quality. |
+| `AI_MEMORY_LLM_PROVIDER=openai-compat` | (required) | Set `AI_MEMORY_LLM_BASE_URL` + `AI_MEMORY_LLM_MODEL`. Use for Ollama, OpenRouter, vLLM, LM Studio. |
-```bash
-cargo build --release --workspace
-./target/release/ai-memory init # create data dir
-./target/release/ai-memory serve --transport http \
- --bind 127.0.0.1:49374 # MCP HTTP + hooks
-./target/release/ai-memory status --json # counts + paths
-./target/release/ai-memory search "karpathy" # FTS5 query
-./target/release/ai-memory backup --to bak.tar.gz # snapshot
-./target/release/ai-memory restore --from bak.tar.gz # restore
-./target/release/ai-memory forget-sweep [--dry-run] # retention
-./target/release/ai-memory lint [--dry-run] # contradiction + orphan audit
-./target/release/ai-memory embed [--dry-run] # backfill embeddings
-./target/release/ai-memory --help # full subcommand tree
-```
+Embedding defaults (when `AI_MEMORY_EMBEDDING_PROVIDER` is set):
+
+| Provider | Default model | Dim |
+|---|---|---|
+| `openai` | `text-embedding-3-small` | 1536 |
+| `voyage` | `voyage-3` | 1024 |
-Data dir defaults to `~/.local/share/ai-memory` on Linux,
-`~/Library/Application Support/ai-memory` on macOS. Override with
-`AI_MEMORY_DATA_DIR=/path`.
+Per-tier feature breakdown + the openai-compat / Ollama setup is in
+[`docs/install.md`](docs/install.md#llm-provider-tiers).
## Architecture in 60 seconds
A single Rust binary, optionally containerised. Runs as an
-[MCP](https://modelcontextprotocol.io/) server over stdio + HTTP. Owns
-a data directory containing:
+[MCP](https://modelcontextprotocol.io/) server over stdio + HTTP.
+Owns a data directory containing:
```
<data_dir>/
-├── wiki/ # markdown source of truth (git-versioned)
-├── raw/ # immutable session log archive
-├── db/ # SQLite (FTS5 + page_embeddings) — derived index
-├── models/ # reserved for local embedding model (v0.3+)
-└── logs/ # rolling daily tracing output
+├── wiki/ # markdown source of truth (git-versioned)
+├── raw/ # immutable session log archive
+├── db/ # SQLite (FTS5 + page_embeddings) — derived index
+├── models/ # reserved for local embedding model (v0.3+)
+└── logs/ # rolling daily tracing output
```
Agent lifecycle hooks fire-and-forget POST to the server's HTTP
ingress. The server queues writes through a single SQLite writer
(no `database is locked`). On session end an optional LLM-driven pass
rewrites pages atomically with supersession (`is_latest=false` +
-`supersedes` chain) and opens a typed handoff for the next agent. The
-retention sweep decays unused episodic content while semantic concept
-pages compound forever; pinned pages are exempt. Retrieval is FTS5
-by default; when an embedder is configured, hybrid RRF over
+`supersedes` chain) and opens a typed handoff for the next agent.
+The retention sweep decays unused episodic content while semantic
+concept pages compound forever; pinned pages are exempt. Retrieval
+is FTS5 by default; when an embedder is configured, hybrid RRF over
`page_embeddings` joins the FTS5 ranks.
See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for the canonical
@@ -315,18 +198,12 @@ data-flow diagram + crate breakdown + cross-cutting invariants.
| File | What it is |
|---|---|
-| [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | **Read first.** Operational summary: data flow, crate layout, cross-cutting invariants, current schema. |
-| [`docs/design-decisions.md`](docs/design-decisions.md) | The full v1 spec — storage, MCP surface, hooks, lifecycle, mistakes-to-avoid checklist. |
-| [`research-karpathy-llm-wiki.md`](docs/research-karpathy-llm-wiki.md) | What Karpathy actually said + community extensions, with sources. |
-| [`research-agentmemory.md`](docs/research-agentmemory.md) | Deep-dive on the TypeScript predecessor; ideas to reuse and substrate to drop. |
-| [`research-basic-memory.md`](docs/research-basic-memory.md) | The manual-write-note model we explicitly diverge from. |
-| [`research-cognee.md`](docs/research-cognee.md) | Knowledge-graph pipeline ideas to adopt + dependency landmines to avoid. |
-| [`issues-agentmemory.md`](docs/issues-agentmemory.md) | Operational landmines from the upstream tracker. |
-| [`issues-basic-memory.md`](docs/issues-basic-memory.md) | File-watcher + capture-friction landmines. |
-| [`issues-cognee.md`](docs/issues-cognee.md) | LLM-gateway + multi-store landmines. |
-
-[`CLAUDE.md`](CLAUDE.md) at the repo root holds the per-session
-operating rules for the maintainer's own Claude Code sessions.
+| [`docs/install.md`](docs/install.md) | **Installation cookbook.** Every agent CLI, every alternative (curl, source build, no-docker, no-auth). Read after the Quick start if your setup doesn't match the happy path. |
+| [`docs/mcp-install.md`](docs/mcp-install.md) | Per-client MCP config snippets (Cursor, Claude Desktop, Gemini CLI, OpenClaw, pi). |
+| [`docs/deploy.md`](docs/deploy.md) | Homelab deploy: bin/deploy, bearer-token auth, TLS via cloudflared. |
+| [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | Operational summary: data flow, crate layout, cross-cutting invariants, schema. |
+| [`docs/design-decisions.md`](docs/design-decisions.md) | The full v1 spec. |
+| Research docs under `docs/` | Karpathy LLM Wiki notes, agentmemory / basic-memory / cognee deep-dives, lessons-learned from upstream issues. |
## Influences and prior art
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index a398ff46..9c6b1f9e 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -63,6 +63,46 @@ pub enum Command {
Embed(EmbedArgs),
/// Generate a random hex bearer token for AI_MEMORY_AUTH_TOKEN.
GenerateAuthToken(GenerateAuthTokenArgs),
+ /// One-shot agent setup for docker deploys: extract the bundled
+ /// hook scripts to a host-mounted directory AND print the matching
+ /// config snippet. Replaces the "clone the repo + cargo build"
+ /// workflow for users who never want a local Rust toolchain.
+ SetupAgent(SetupAgentArgs),
+}
+
+/// Arguments for `setup-agent`.
+#[derive(Debug, Args)]
+pub struct SetupAgentArgs {
+ /// Which agent's hook bundle to extract + render.
+ #[arg(long, value_enum, default_value_t = AgentChoice::ClaudeCode)]
+ pub agent: AgentChoice,
+ /// Filesystem directory the hook scripts get copied into. In a
+ /// docker context this is the in-container path; mount a host
+ /// directory there. Example:
+ /// docker run --rm -v $HOME/.ai-memory:/host ai-memory \
+ /// setup-agent --to /host/hooks ...
+ #[arg(long)]
+ pub to: PathBuf,
+ /// Directory the rendered config JSON should reference for the
+ /// hook commands. Defaults to `--to`. Set this when the path on
+ /// the host (where the agent CLI runs) differs from the in-
+ /// container path. Example:
+ /// --to /host/hooks --host-prefix $HOME/.ai-memory/hooks
+ #[arg(long)]
+ pub host_prefix: Option<PathBuf>,
+ /// MCP / hook ingress URL the agent should POST to.
+ #[arg(long, default_value = "http://127.0.0.1:49374")]
+ pub server_url: String,
+ /// Bearer token embedded into each hook's env block. Picked up
+ /// from `AI_MEMORY_AUTH_TOKEN` if unset.
+ #[arg(long, env = "AI_MEMORY_AUTH_TOKEN", hide_env_values = true)]
+ pub auth_token: Option<String>,
+ /// Source directory for the embedded hook bundle. Defaults to
+ /// `/usr/local/share/ai-memory/hooks` (the docker image's
+ /// bundled path) and falls back to a repo-local `hooks/` for
+ /// `cargo run setup-agent` during development.
+ #[arg(long)]
+ pub source: Option<PathBuf>,
}
/// Arguments for `generate-auth-token`.
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index ad58ca64..192d34ae 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -102,27 +102,38 @@ fn repo_root_guess() -> Option<PathBuf> {
.and_then(|p| p.parent()?.parent()?.parent().map(Path::to_path_buf))
}
-fn render_claude_code(hooks_dir: &Path, server_url: &str, auth_token: Option<&str>) -> Result<()> {
- let scripts: [(&str, &str); 7] = [
- ("SessionStart", "session-start.sh"),
- ("UserPromptSubmit", "user-prompt-submit.sh"),
- ("PreToolUse", "pre-tool-use.sh"),
- ("PostToolUse", "post-tool-use.sh"),
- ("PreCompact", "pre-compact.sh"),
- ("Stop", "stop.sh"),
- ("SessionEnd", "session-end.sh"),
- ];
+/// The seven Claude Code hook events ai-memory wires up, paired with
+/// the vendored script filename. Used by both `install-hooks` and
+/// `setup-agent`.
+pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 7] = [
+ ("SessionStart", "session-start.sh"),
+ ("UserPromptSubmit", "user-prompt-submit.sh"),
+ ("PreToolUse", "pre-tool-use.sh"),
+ ("PostToolUse", "post-tool-use.sh"),
+ ("PreCompact", "pre-compact.sh"),
+ ("Stop", "stop.sh"),
+ ("SessionEnd", "session-end.sh"),
+];
+/// Build the Claude Code settings-fragment JSON for the given paths.
+///
+/// `emit_root` is the directory the JSON snippet will reference as
+/// the home of the hook scripts. It does NOT need to exist on the
+/// filesystem this binary is running on — that's exactly the docker
+/// case where `setup-agent` writes to a mounted volume and emits
+/// host-side paths.
+///
+/// `auth_token`, when set, lands in each hook's `env` block as
+/// `AI_MEMORY_AUTH_TOKEN`, which the shell scripts forward as
+/// `Authorization: Bearer …` to the server.
+pub(crate) fn build_claude_code_payload(
+ emit_root: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+) -> serde_json::Value {
let mut hooks_block = serde_json::Map::new();
- for (event, script) in scripts {
- let abs = hooks_dir.join(script);
- if !abs.exists() {
- anyhow::bail!("missing hook script: {}", abs.display());
- }
- // The env block is passed to the hook command by Claude Code.
- // We always include AI_MEMORY_HOOK_URL; when an auth token is
- // configured, we also include AI_MEMORY_AUTH_TOKEN so the
- // hook scripts can forward it as `Authorization: Bearer …`.
+ for (event, script) in CLAUDE_CODE_EVENTS {
+ let abs = emit_root.join(script);
let mut env = serde_json::Map::new();
env.insert(
"AI_MEMORY_HOOK_URL".into(),
@@ -142,8 +153,27 @@ fn render_claude_code(hooks_dir: &Path, server_url: &str, auth_token: Option<&st
}]),
);
}
- let payload = json!({ "hooks": hooks_block });
+ json!({ "hooks": hooks_block })
+}
+fn render_claude_code(hooks_dir: &Path, server_url: &str, auth_token: Option<&str>) -> Result<()> {
+ // Soft check: warn (don't bail) if a script is missing. The user
+ // may be running this command inside docker against a host path
+ // that exists only on the host's filesystem — bailing would
+ // sabotage the docker-only flow `setup-agent` enables.
+ for (_, script) in CLAUDE_CODE_EVENTS {
+ let abs = hooks_dir.join(script);
+ if !abs.exists() {
+ eprintln!(
+ "# warning: {} not present on this filesystem. \
+ If this command is running inside docker against a \
+ host path, you can ignore this; otherwise extract \
+ the scripts first with `ai-memory setup-agent`.",
+ abs.display()
+ );
+ }
+ }
+ let payload = build_claude_code_payload(hooks_dir, server_url, auth_token);
let serialized =
serde_json::to_string_pretty(&payload).context("serializing claude code hook config")?;
println!("# Claude Code hook config — merge into ~/.claude/settings.json");
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 81f0458f..a9aafdd5 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -14,6 +14,7 @@ pub mod reset;
pub mod restore;
pub mod search;
pub mod serve;
+pub mod setup_agent;
pub mod status;
pub mod watch;
pub mod write_page;
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
new file mode 100644
index 00000000..167091c4
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -0,0 +1,176 @@
+//! `ai-memory setup-agent` — one-shot agent integration for the
+//! docker-primary workflow.
+//!
+//! Solves the problem that `install-hooks` alone can't handle in a
+//! docker-only deploy: the JSON snippet `install-hooks` emits
+//! references absolute paths to hook scripts, and those paths must
+//! exist on the host machine that runs the agent CLI (Claude Code et
+//! al. shell out from the host, not inside the container).
+//!
+//! `setup-agent` bundles the extract + render into one command:
+//!
+//! docker run --rm \
+//! -v "$HOME/.ai-memory:/host" \
+//! akitaonrails/ai-memory:latest \
+//! setup-agent \
+//! --agent claude-code \
+//! --to /host/hooks \
+//! --host-prefix "$HOME/.ai-memory/hooks" \
+//! --auth-token "$TOKEN"
+//!
+//! 1. Copies `/usr/local/share/ai-memory/hooks/claude-code/*.sh` into
+//! `/host/hooks/claude-code/` (which on the host is
+//! `$HOME/.ai-memory/hooks/claude-code/`).
+//! 2. Prints the JSON config snippet whose `command` fields point at
+//! `$HOME/.ai-memory/hooks/claude-code/*.sh` (via `--host-prefix`)
+//! so Claude Code on the host can exec them.
+//!
+//! When `--host-prefix` is omitted it defaults to `--to`, which is
+//! the right behaviour for a non-docker (`cargo run`) invocation
+//! where the in-container path and the host path are the same thing.
+
+use std::fs;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, bail};
+
+use crate::cli::{AgentChoice, SetupAgentArgs};
+use crate::commands::install_hooks::{CLAUDE_CODE_EVENTS, build_claude_code_payload};
+use crate::config::Config;
+
+/// Run the `setup-agent` subcommand.
+///
+/// # Errors
+/// Returns an error if the source bundle can't be located, the
+/// destination directory can't be created, any script copy fails,
+/// or the JSON config can't be serialised.
+pub fn run(_config: &Config, args: SetupAgentArgs) -> Result<()> {
+ let agent_sub = match args.agent {
+ AgentChoice::ClaudeCode => "claude-code",
+ AgentChoice::Codex => "codex",
+ AgentChoice::OpenCode => "opencode",
+ };
+
+ let source = resolve_source(args.source.as_deref(), agent_sub)?;
+ let dest_dir = args.to.join(agent_sub);
+
+ fs::create_dir_all(&dest_dir)
+ .with_context(|| format!("creating destination {}", dest_dir.display()))?;
+
+ let mut copied = 0_usize;
+ for entry in fs::read_dir(&source)
+ .with_context(|| format!("reading source bundle {}", source.display()))?
+ {
+ let entry = entry?;
+ let from = entry.path();
+ if !from.is_file() || from.extension().and_then(|s| s.to_str()) != Some("sh") {
+ continue;
+ }
+ let file_name = from
+ .file_name()
+ .with_context(|| format!("invalid hook script path {}", from.display()))?;
+ let to = dest_dir.join(file_name);
+ fs::copy(&from, &to)
+ .with_context(|| format!("copying {} → {}", from.display(), to.display()))?;
+ // Preserve executable bit so the agent CLI can actually run
+ // the scripts. On Windows this is a no-op.
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mut perms = fs::metadata(&to)?.permissions();
+ perms.set_mode(0o755);
+ fs::set_permissions(&to, perms)?;
+ }
+ copied += 1;
+ }
+
+ eprintln!(
+ "✓ Extracted {copied} hook script(s) from {} to {}",
+ source.display(),
+ dest_dir.display(),
+ );
+
+ // The path the rendered JSON should reference. Defaults to where
+ // we just copied the scripts; override with --host-prefix when
+ // running inside docker against a mounted volume.
+ let emit_root = args
+ .host_prefix
+ .as_deref()
+ .unwrap_or(&args.to)
+ .join(agent_sub);
+
+ match args.agent {
+ AgentChoice::ClaudeCode => emit_claude_code(&emit_root, &args)?,
+ AgentChoice::Codex | AgentChoice::OpenCode => emit_other(&emit_root, agent_sub, &args),
+ }
+ Ok(())
+}
+
+fn emit_claude_code(emit_root: &Path, args: &SetupAgentArgs) -> Result<()> {
+ let payload =
+ build_claude_code_payload(emit_root, &args.server_url, args.auth_token.as_deref());
+ let serialized =
+ serde_json::to_string_pretty(&payload).context("serializing Claude Code hook config")?;
+ println!("# Claude Code — merge into ~/.claude/settings.json");
+ println!("# Hook scripts (must be reachable from the host that runs Claude Code):");
+ println!("# {}", emit_root.display());
+ println!("# AI-memory server: {}", args.server_url);
+ if args.auth_token.is_some() {
+ println!("# Auth: AI_MEMORY_AUTH_TOKEN embedded in each hook's env block.");
+ println!("# Treat ~/.claude/settings.json as sensitive (chmod 600).");
+ }
+ println!("# Tip: also run `ai-memory install-mcp --client claude-code --auth-token <…>`");
+ println!("# to register the MCP endpoint (separate from hooks).");
+ println!();
+ println!("{serialized}");
+ Ok(())
+}
+
+fn emit_other(emit_root: &Path, label: &str, args: &SetupAgentArgs) {
+ // Codex + OpenCode hook configs vary by version; we just point at
+ // the extracted scripts and let the user wire them up. Future
+ // versions can render structured JSON/TOML once those formats
+ // settle upstream.
+ println!("# {label} hook scripts (manual wire-up — formats still evolving upstream)");
+ println!("# Scripts located at: {}", emit_root.display());
+ println!("# Server URL: {}", args.server_url);
+ if args.auth_token.is_some() {
+ println!("# Auth: set AI_MEMORY_AUTH_TOKEN in each hook's environment to the");
+ println!("# value you passed via --auth-token (not echoed).");
+ }
+ println!();
+ for (_, script) in CLAUDE_CODE_EVENTS {
+ println!("- {}", emit_root.join(script).display());
+ }
+ println!();
+ println!("Set AI_MEMORY_HOOK_URL in each hook's environment to override the default.");
+ println!("Also run `ai-memory install-mcp --client {label}` to wire MCP separately.");
+}
+
+fn resolve_source(explicit: Option<&Path>, sub: &str) -> Result<PathBuf> {
+ let candidates: Vec<PathBuf> = if let Some(p) = explicit {
+ vec![p.join(sub)]
+ } else {
+ let mut v = vec![
+ // Docker image lays them out under /usr/local/share/.
+ PathBuf::from(format!("/usr/local/share/ai-memory/hooks/{sub}")),
+ ];
+ // Repo-local fallback for `cargo run setup-agent` during dev.
+ if let Some(p) = std::env::current_exe()
+ .ok()
+ .and_then(|p| p.parent()?.parent()?.parent().map(Path::to_path_buf))
+ {
+ v.push(p.join("hooks").join(sub));
+ }
+ v
+ };
+ for path in &candidates {
+ if path.is_dir() {
+ return Ok(path.clone());
+ }
+ }
+ bail!(
+ "could not locate hook source bundle for {sub}. \
+ Tried: {candidates:?}. Pass --source <dir> to override."
+ );
+}
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 87959152..31b69b3e 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -55,5 +55,6 @@ async fn main() -> Result<()> {
Command::Lint(args) => commands::lint::run(&config, args).await,
Command::Embed(args) => commands::embed::run(&config, args).await,
Command::GenerateAuthToken(args) => commands::generate_auth_token::run(&config, args),
+ Command::SetupAgent(args) => commands::setup_agent::run(&config, args),
}
}
diff --git a/docker/Dockerfile b/docker/Dockerfile
index f7eac6c2..3458a8a5 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -28,6 +28,11 @@ RUN apt-get update \
&& mkdir -p /data \
&& chown -R ai-memory:ai-memory /data
COPY --from=builder /usr/local/bin/ai-memory /usr/local/bin/ai-memory
+# Lifecycle-hook scripts bundled into the image so docker-only users
+# can `ai-memory setup-agent` without needing a repo checkout. The
+# scripts live on a path scanned by `install_hooks::resolve_hooks_dir`
+# (and by `setup_agent::resolve_source`).
+COPY hooks /usr/local/share/ai-memory/hooks
USER ai-memory
ENV AI_MEMORY_DATA_DIR=/data
WORKDIR /data
diff --git a/docs/install.md b/docs/install.md
new file mode 100644
index 00000000..94d0a9fb
--- /dev/null
+++ b/docs/install.md
@@ -0,0 +1,326 @@
+# Installation cookbook
+
+The [README quick-start](../README.md#quick-start) covers the happy
+path (docker + Claude Code). This page covers everything else:
+
+- [Configuring other agent CLIs](#configuring-other-agent-clis)
+ (Codex, OpenCode, Cursor, Claude Desktop, Gemini CLI, OpenClaw, pi)
+- [Installing hooks without docker](#installing-hooks-without-docker)
+ (curl-based installer)
+- [Running ai-memory without docker](#running-ai-memory-without-docker)
+ (cargo install, building from source)
+- [LLM provider tiers + self-hosted Ollama](#llm-provider-tiers)
+- [Subcommand reference](#subcommand-reference)
+- [Operating without auth](#operating-without-auth) (local-only)
+
+> **Shorthand.** Most snippets use `$TOKEN` and `homelab:49374`. If
+> you're following along verbatim:
+> ```bash
+> export TOKEN=$(docker run --rm akitaonrails/ai-memory:latest generate-auth-token)
+> ```
+> and replace `homelab` with `localhost` if the server runs on the
+> same machine as the agent CLI.
+
+---
+
+## Configuring other agent CLIs
+
+Each agent CLI needs two things:
+
+1. **MCP registration** — so the agent can call `memory_query`,
+ `memory_recent`, `memory_handoff_accept`.
+2. **Lifecycle hooks** — so the server auto-captures session events.
+ Without this, the agent can still query memory but capture
+ becomes manual.
+
+The five clients on the [MCP install page](mcp-install.md) (Cursor,
+Claude Desktop, Gemini CLI, OpenClaw, pi) get MCP only — no
+lifecycle hooks ship for them today. For the three flagship CLIs
+(Claude Code, Codex, OpenCode), both are wired up.
+
+> **Two-step hook install pattern.** All three flagship CLIs use the
+> same shape: (1) `docker cp` the bundled scripts to your home dir,
+> (2) `docker run --rm install-hooks` to render the config snippet.
+> `docker cp` works on every docker setup (including rootless and
+> userns-remap); a `setup-agent` one-shot exists but has bind-mount
+> caveats — see [Bind mounts vs docker cp](#bind-mounts-vs-docker-cp).
+
+### OpenAI Codex
+
+```bash
+# MCP snippet (merge into ~/.codex/config.toml):
+docker run --rm akitaonrails/ai-memory:latest \
+ install-mcp --client codex \
+ --server-url "http://homelab:49374/mcp" \
+ --auth-token "$TOKEN"
+
+# Hooks — extract scripts + render config:
+docker cp ai-memory:/usr/local/share/ai-memory/hooks ~/.ai-memory/
+docker run --rm akitaonrails/ai-memory:latest \
+ install-hooks --agent codex \
+ --hooks-dir ~/.ai-memory/hooks \
+ --server-url "http://homelab:49374" \
+ --auth-token "$TOKEN"
+```
+
+### OpenCode
+
+```bash
+docker run --rm akitaonrails/ai-memory:latest \
+ install-mcp --client opencode \
+ --server-url "http://homelab:49374/mcp" \
+ --auth-token "$TOKEN"
+
+docker cp ai-memory:/usr/local/share/ai-memory/hooks ~/.ai-memory/
+docker run --rm akitaonrails/ai-memory:latest \
+ install-hooks --agent opencode \
+ --hooks-dir ~/.ai-memory/hooks \
+ --server-url "http://homelab:49374" \
+ --auth-token "$TOKEN"
+```
+
+### Bind mounts vs docker cp
+
+The `setup-agent` subcommand does the extract + render in one shot
+using a bind mount:
+
+```bash
+docker run --rm -v "$HOME/.ai-memory:/host" \
+ akitaonrails/ai-memory:latest \
+ setup-agent --agent claude-code --to /host/hooks \
+ --host-prefix "$HOME/.ai-memory/hooks" \
+ --server-url "http://homelab:49374" --auth-token "$TOKEN"
+```
+
+This works cleanly when the container user's UID matches the host
+user's UID (e.g. the homelab where both are 1000). It **fails on
+rootless Docker** and on hosts with `userns-remap` enabled — the
+container can't write to a host directory that belongs to a UID
+outside the user-namespace mapping.
+
+The `docker cp` pattern recommended above sidesteps all of that
+because `docker cp` is mediated by the docker daemon and outputs
+files owned by the user running the command. Prefer it as the
+default; reach for `setup-agent` only when your docker setup is
+known not to remap UIDs.
+
+### Cursor, Claude Desktop, Gemini CLI, OpenClaw, pi
+
+These are MCP-only — no lifecycle-hook bundles ship for them. See
+[**`docs/mcp-install.md`**](mcp-install.md) for the per-client config
+file path and snippet, or one-shot it via:
+
+```bash
+docker run --rm akitaonrails/ai-memory:latest \
+ install-mcp --client cursor --auth-token "$TOKEN" \
+ --server-url "http://homelab:49374/mcp"
+
+docker run --rm akitaonrails/ai-memory:latest \
+ install-mcp --client claude-desktop --auth-token "$TOKEN" \
+ --server-url "http://homelab:49374/mcp"
+
+docker run --rm akitaonrails/ai-memory:latest \
+ install-mcp --client gemini-cli --auth-token "$TOKEN" \
+ --server-url "http://homelab:49374/mcp"
+
+docker run --rm akitaonrails/ai-memory:latest \
+ install-mcp --client openclaw --auth-token "$TOKEN" \
+ --server-url "http://homelab:49374/mcp"
+
+# pi: prints the "not supported via MCP" explanation
+docker run --rm akitaonrails/ai-memory:latest install-mcp --client pi
+```
+
+For these MCP-only clients you'll need to nudge the model to call
+`memory_query` / `memory_handoff_accept` itself (see the
+[CLAUDE.md snippet](../README.md#nudge-the-agent-to-use-memory-proactively)
+in the README).
+
+---
+
+## Installing hooks without docker
+
+If you only need to use ai-memory *from* a machine (i.e. that
+machine doesn't run the server), the curl installer pulls the seven
+hook scripts straight from GitHub:
+
+```bash
+curl -sSL https://raw.githubusercontent.com/akitaonrails/ai-memory/main/scripts/install-hooks.sh \
+ | bash -s -- --agent claude-code
+
+# Then render the JSON config (still wants `ai-memory` somewhere —
+# either via docker as a one-shot, or installed locally):
+docker run --rm akitaonrails/ai-memory:latest \
+ install-hooks --agent claude-code \
+ --hooks-dir "$HOME/.ai-memory/hooks" \
+ --server-url "http://homelab:49374" \
+ --auth-token "$TOKEN"
+```
+
+The installer supports `--agent codex|opencode|claude-code` and
+`--to <dir>`; `--help` prints the full flag list.
+
+This path is friction-free when:
+- You have curl + bash but not docker
+- You don't need to run a local ai-memory server (you're a client of
+ a homelab/remote ai-memory)
+
+---
+
+## Running ai-memory without docker
+
+```bash
+git clone https://github.com/akitaonrails/ai-memory ~/.ai-memory
+cd ~/.ai-memory
+cargo build --release --workspace
+./target/release/ai-memory init # one-time
+./target/release/ai-memory serve --transport http \
+ --bind 127.0.0.1:49374 # MCP + hook HTTP server
+```
+
+Data dir defaults to `~/.local/share/ai-memory` on Linux,
+`~/Library/Application Support/ai-memory` on macOS. Override with
+`AI_MEMORY_DATA_DIR=/path`. To require bearer-token auth, set
+`AI_MEMORY_AUTH_TOKEN` in the server's environment.
+
+When run from source, `install-hooks` finds the bundled scripts in
+the repo's `hooks/` automatically:
+
+```bash
+./target/release/ai-memory install-hooks --agent claude-code --auth-token "$TOKEN"
+```
+
+(No need for `setup-agent` in this case — the scripts already live
+at the right host path.)
+
+---
+
+## LLM provider tiers
+
+ai-memory works in three intensity tiers:
+
+| Tier | What you get | Env vars | Cost |
+|---|---|---|---|
+| **Zero-LLM** (default) | FTS5 search, rule-based session summaries, auto-handoffs from prompt + tool-call history | (none) | $0 |
+| **+ LLM consolidation** | LLM rewrites session pages as coherent narratives; PreCompact checkpoints; LLM-driven contradiction lint | `AI_MEMORY_LLM_PROVIDER=anthropic` + `ANTHROPIC_API_KEY` | ~$0.01–0.05 / session |
+| **+ Hybrid retrieval** | RRF over FTS5 + vector cosine similarity. Better recall on paraphrased queries | `AI_MEMORY_EMBEDDING_PROVIDER=openai` + `OPENAI_API_KEY` | ~$0.0001 / page on backfill |
+
+### Recommended models (chosen as defaults)
+
+If you set only the provider, ai-memory picks a sensible default:
+
+| Setting | Default | Why |
+|---|---|---|
+| `AI_MEMORY_LLM_PROVIDER=anthropic` | `claude-sonnet-4-6` | Smart enough to summarise; cheap enough to run on every session-end. Not a reasoning model. |
+| `AI_MEMORY_LLM_PROVIDER=openai` | `gpt-4o-mini` | OpenAI equivalent to the Sonnet tier in price/quality. |
+| `AI_MEMORY_EMBEDDING_PROVIDER=openai` | `text-embedding-3-small` (1536-dim) | 5× cheaper than `-3-large` with marginal recall loss. |
+| `AI_MEMORY_EMBEDDING_PROVIDER=voyage` | `voyage-3` (1024-dim) | Voyage's current general-purpose recommendation. |
+
+### Self-hosted LLMs (Ollama / vLLM / LM Studio / OpenRouter)
+
+```bash
+docker run -d --name ai-memory \
+ -p 49374:49374 \
+ -v ai-memory-data:/data \
+ -e AI_MEMORY_AUTH_TOKEN="$TOKEN" \
+ -e AI_MEMORY_LLM_PROVIDER=openai-compat \
+ -e AI_MEMORY_LLM_BASE_URL=http://host.docker.internal:11434/v1 \
+ -e AI_MEMORY_LLM_MODEL=qwen2.5-coder:14b \
+ akitaonrails/ai-memory:latest
+```
+
+There is no safe default model for `openai-compat`; the env var is
+required. For OpenRouter (Kimi, DeepSeek, etc.):
+
+```bash
+-e AI_MEMORY_LLM_PROVIDER=openai-compat
+-e AI_MEMORY_LLM_BASE_URL=https://openrouter.ai/api/v1
+-e AI_MEMORY_LLM_MODEL=moonshotai/kimi-k2.6
+-e LLM_API_KEY=sk-or-v1-...
+```
+
+---
+
+## Subcommand reference
+
+Two ways to invoke a subcommand against the docker deploy:
+
+```bash
+# A) Against the running container (stateful: status, search, backup,
+# forget-sweep, lint, embed).
+docker exec ai-memory ai-memory status --json
+docker exec ai-memory ai-memory search "karpathy"
+docker exec ai-memory ai-memory backup --to /data/snapshot.tar.gz
+
+# B) One-shot, no running container needed (pure-stdout: generate-
+# auth-token, install-mcp, install-hooks, setup-agent, llm-test).
+docker run --rm akitaonrails/ai-memory:latest generate-auth-token
+docker run --rm akitaonrails/ai-memory:latest install-mcp --client cursor
+docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree
+```
+
+| Subcommand | Pattern | What it does |
+|---|---|---|
+| `serve` | `docker compose up -d` (already done) | Run the HTTP MCP server |
+| `status` | `docker exec` | Counts + paths + provider config |
+| `search "<query>"` | `docker exec` | FTS5 query against the wiki |
+| `write-page` | `docker exec` | Manual page write (atomic + indexed) |
+| `backup --to` / `restore --from` | `docker exec` | Snapshot or restore the data dir |
+| `forget-sweep` / `lint` / `embed` | `docker exec` | Periodic maintenance |
+| `commit -m "…"` | `docker exec` | Stage + commit the wiki tree |
+| `reset --confirm` | `docker exec` | Wipe data (refuses while siblings alive) |
+| `generate-auth-token` | `docker run --rm` | Print a random hex bearer token |
+| `install-mcp --client` | `docker run --rm` | MCP-config snippet per client |
+| `install-hooks --agent` | `docker run --rm` | Hook-config snippet for an existing hooks dir |
+| `setup-agent --agent --to --host-prefix` | `docker run --rm -v` | Extract bundled scripts + print config (one-shot) |
+| `llm-test --provider …` | `docker run --rm -e …` | Smoke-test an LLM provider |
+
+Data dir inside the container is `/data` (mounted via the compose
+volume). Outside docker, override with `AI_MEMORY_DATA_DIR=/path`.
+
+---
+
+## Operating without auth
+
+For local-only / single-machine deploys you can skip the bearer
+token:
+
+```bash
+docker run -d --name ai-memory \
+ -p 127.0.0.1:49374:49374 \
+ -v ai-memory-data:/data \
+ akitaonrails/ai-memory:latest
+```
+
+Notice the bind: `127.0.0.1:49374`, not `0.0.0.0:49374`. This is the
+critical pairing — **no bearer token AND loopback only** is the only
+safe combination. The startup log will warn loudly if you bind to a
+LAN address without setting `AI_MEMORY_AUTH_TOKEN`.
+
+Then register the agent CLI without the `Authorization` header:
+
+```bash
+claude mcp add --transport http ai-memory http://localhost:49374/mcp
+```
+
+And register hooks without `--auth-token`:
+
+```bash
+docker run --rm -v "$HOME/.ai-memory:/host" \
+ akitaonrails/ai-memory:latest \
+ setup-agent --agent claude-code \
+ --to /host/hooks \
+ --host-prefix "$HOME/.ai-memory/hooks" \
+ --server-url "http://localhost:49374"
+```
+
+---
+
+## See also
+
+- [`docs/deploy.md`](deploy.md) — homelab deploy walkthrough
+ (`bin/deploy`, cloudflared TLS, env-file management)
+- [`docs/mcp-install.md`](mcp-install.md) — per-client MCP config
+ reference for Cursor, Claude Desktop, Gemini CLI, OpenClaw, pi
+- [`docs/ARCHITECTURE.md`](ARCHITECTURE.md) — what's actually
+ running inside ai-memory
diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.sh
new file mode 100755
index 00000000..5392cde7
--- /dev/null
+++ b/scripts/install-hooks.sh
@@ -0,0 +1,88 @@
+#!/usr/bin/env bash
+# Curl-based installer for ai-memory's lifecycle-hook scripts.
+#
+# Use when you don't want to clone the repo and don't want to use the
+# docker image to extract the bundle. Pulls each hook script for the
+# requested agent straight from the published GitHub raw URL.
+#
+# Usage:
+# curl -sSL https://raw.githubusercontent.com/akitaonrails/ai-memory/main/scripts/install-hooks.sh \
+# | bash -s -- --agent claude-code
+#
+# Options:
+# --agent <claude-code|codex|opencode> which agent (default: claude-code)
+# --to <dir> install root (default: $HOME/.ai-memory/hooks)
+# --ref <git-ref> repo ref to pull from (default: main)
+#
+# After installation, render the matching agent config snippet:
+# ai-memory install-hooks --agent claude-code --hooks-dir ~/.ai-memory/hooks
+#
+# If you only have docker:
+# docker run --rm ai-memory install-hooks --agent claude-code \
+# --hooks-dir ~/.ai-memory/hooks
+
+set -euo pipefail
+
+AGENT="claude-code"
+TO="$HOME/.ai-memory/hooks"
+REF="main"
+REPO="akitaonrails/ai-memory"
+
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --agent) AGENT="$2"; shift 2 ;;
+ --to) TO="$2"; shift 2 ;;
+ --ref) REF="$2"; shift 2 ;;
+ --repo) REPO="$2"; shift 2 ;;
+ -h|--help)
+ sed -n '2,18p' "$0"
+ exit 0 ;;
+ *)
+ echo "unknown flag: $1" >&2
+ exit 64 ;;
+ esac
+done
+
+case "$AGENT" in
+ claude-code|codex|opencode) ;;
+ *)
+ echo "unsupported agent: $AGENT (expected claude-code | codex | opencode)" >&2
+ exit 64 ;;
+esac
+
+SCRIPTS=(
+ "session-start"
+ "user-prompt-submit"
+ "pre-tool-use"
+ "post-tool-use"
+ "pre-compact"
+ "stop"
+ "session-end"
+)
+
+DEST="$TO/$AGENT"
+mkdir -p "$DEST"
+
+echo "Installing ai-memory hooks for $AGENT into $DEST"
+for name in "${SCRIPTS[@]}"; do
+ url="https://raw.githubusercontent.com/$REPO/$REF/hooks/$AGENT/${name}.sh"
+ out="$DEST/${name}.sh"
+ if curl -fsSL "$url" -o "$out"; then
+ chmod +x "$out"
+ echo " ✓ $name"
+ else
+ echo " ✗ $name (failed to fetch $url)" >&2
+ exit 1
+ fi
+done
+
+echo
+echo "Done. Next steps:"
+echo
+echo " 1. Render the config snippet to merge into your agent's settings:"
+echo " ai-memory install-hooks --agent $AGENT --hooks-dir $TO"
+echo " (Or via docker if you don't have the binary locally:"
+echo " docker run --rm $REPO:latest install-hooks --agent $AGENT --hooks-dir $TO)"
+echo
+echo " 2. If your server uses bearer-token auth, pass --auth-token <token>"
+echo " to the install-hooks command so the snippet wires it in."