Skip to content

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

Rust

feat: add `ai-memory completions <shell>` for shell tab completion

Marcelo788921b70d81a9e8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 577384f8..013e82f0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- `ai-memory completions <shell>` prints a shell-completion script for bash,
+ zsh, fish, PowerShell, or elvish. The script is generated from the binary's
+ own command tree, so it always matches the installed version; install paths
+ per shell are documented in `docs/shell-completions.md`. The command reads no
+ config and needs no data directory, so it works before `ai-memory init`.
+
## [1.17.1] - 2026-07-20
### Fixed
diff --git a/Cargo.lock b/Cargo.lock
index 36c10146..1945c35e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -46,6 +46,7 @@ dependencies = [
"axum",
"base64",
"clap",
+ "clap_complete",
"dirs",
"figment",
"flate2",
@@ -639,6 +640,15 @@ dependencies = [
"strsim",
]
+[[package]]
+name = "clap_complete"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db8b397918185f0161ff3d6fcaa9e4bfc09b8367caf6e1d4a2848e5477ed027b"
+dependencies = [
+ "clap",
+]
+
[[package]]
name = "clap_derive"
version = "4.6.1"
diff --git a/Cargo.toml b/Cargo.toml
index 17ee3631..12e798e2 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -68,6 +68,10 @@ uuid = { version = "1", features = ["v4", "v5", "v7", "serde"] }
# Config & CLI.
figment = { version = "0.10", features = ["toml", "env"] }
clap = { version = "4", features = ["derive", "env"] }
+# Shell-completion generator for `ai-memory completions <shell>`. Reads the
+# same derived `Command` the parser uses, so completions can never drift
+# from the actual CLI surface.
+clap_complete = "4"
dirs = "5"
# Format-preserving TOML editor for install-mcp --apply against
# Codex's config.toml. Plain `toml` round-trips destroy comments;
diff --git a/README.md b/README.md
index 00389245..10fe955d 100644
--- a/README.md
+++ b/README.md
@@ -405,6 +405,16 @@ For every client in the [Support Matrix](#support-matrix), plus curl-based hook
installs, source builds, CLI environment variables, and the full subcommand
reference, see [`docs/install.md`](docs/install.md).
+Tab completion for the CLI is available in bash, zsh, fish, PowerShell, and
+elvish:
+
+```bash
+ai-memory completions fish > ~/.config/fish/completions/ai-memory.fish
+```
+
+See [`docs/shell-completions.md`](docs/shell-completions.md) for the other
+shells' install paths.
+
## Security
Loopback-only (`127.0.0.1:49374`) with no auth is the default because
diff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.toml
index 78502b29..e35be30b 100644
--- a/crates/ai-memory-cli/Cargo.toml
+++ b/crates/ai-memory-cli/Cargo.toml
@@ -30,6 +30,7 @@ base64.workspace = true
anyhow.workspace = true
axum.workspace = true
clap.workspace = true
+clap_complete.workspace = true
dirs.workspace = true
figment.workspace = true
flate2.workspace = true
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index dad4a3f8..166aa86a 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -4,6 +4,7 @@ use std::ffi::OsString;
use std::path::PathBuf;
use clap::{Args, Parser, Subcommand};
+use clap_complete::Shell;
/// Top-level CLI for the `ai-memory` binary.
#[derive(Debug, Parser)]
@@ -158,6 +159,10 @@ pub enum Command {
/// these endpoints 503 until `[auth].token_pepper` is set
/// (auto-generated by `ai-memory init`).
User(UserArgs),
+ /// Print a shell-completion script to stdout. Generated from this
+ /// binary's own command tree, so it never drifts from the real CLI
+ /// surface. See `docs/shell-completions.md` for install paths.
+ Completions(CompletionsArgs),
}
/// Arguments for `run`. Wrapper-owned flags must precede `harness`; the
@@ -239,6 +244,14 @@ pub struct UserArgs {
pub command: UserCommand,
}
+/// Arguments for `completions`.
+#[derive(Debug, Args)]
+pub struct CompletionsArgs {
+ /// Shell to generate a completion script for.
+ #[arg(value_enum)]
+ pub shell: Shell,
+}
+
/// Subcommands for `user`.
#[derive(Debug, Subcommand)]
pub enum UserCommand {
@@ -2033,4 +2046,31 @@ mod tests {
assert_eq!(args.model, "claude-sonnet-4-6");
assert_eq!(args.prompt, "ping");
}
+
+ #[test]
+ fn completions_parses_every_supported_shell() {
+ for (arg, expected) in [
+ ("bash", Shell::Bash),
+ ("elvish", Shell::Elvish),
+ ("fish", Shell::Fish),
+ ("powershell", Shell::PowerShell),
+ ("zsh", Shell::Zsh),
+ ] {
+ let cli = Cli::try_parse_from(["ai-memory", "completions", arg]).unwrap();
+ let Command::Completions(args) = cli.command else {
+ panic!("expected completions command for {arg}");
+ };
+ assert_eq!(args.shell, expected);
+ }
+ }
+
+ #[test]
+ fn completions_rejects_an_unknown_shell() {
+ assert!(Cli::try_parse_from(["ai-memory", "completions", "nushell"]).is_err());
+ }
+
+ #[test]
+ fn completions_requires_a_shell() {
+ assert!(Cli::try_parse_from(["ai-memory", "completions"]).is_err());
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/completions.rs b/crates/ai-memory-cli/src/commands/completions.rs
new file mode 100644
index 00000000..a107d661
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/completions.rs
@@ -0,0 +1,43 @@
+//! `ai-memory completions <shell>` — print a shell-completion script.
+//!
+//! Operator workflow (fish shown; see `docs/shell-completions.md` for the
+//! other shells):
+//! $ ai-memory completions fish > ~/.config/fish/completions/ai-memory.fish
+//!
+//! The script is generated from the same derived `clap::Command` the parser
+//! builds, so every subcommand, flag, and help string stays in lockstep with
+//! the binary that produced it. Nothing is vendored into the repo: a stale
+//! checked-in script is worse than no script at all.
+
+use std::io::Write;
+
+use anyhow::{Context, Result};
+use clap::CommandFactory;
+use clap_complete::generate;
+
+use crate::cli::{Cli, CompletionsArgs};
+
+/// Run the `completions` subcommand.
+///
+/// Writes to stdout so the caller can redirect into their shell's completion
+/// directory. Deliberately takes no `&Config`: generating a script must work
+/// before `ai-memory init`, on a machine with no data directory, and inside a
+/// container build step.
+///
+/// # Errors
+/// Propagates I/O failures from writing to stdout.
+pub fn run(args: CompletionsArgs) -> Result<()> {
+ let mut cmd = Cli::command();
+ let bin_name = cmd.get_name().to_string();
+
+ // Render into a buffer rather than straight at stdout: clap_complete
+ // `.expect()`s on write errors, so a closed pipe (`... | head`) would
+ // surface as a panic instead of the silent exit every other CLI gives.
+ let mut script = Vec::new();
+ generate(args.shell, &mut cmd, bin_name, &mut script);
+
+ match std::io::stdout().write_all(&script) {
+ Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => Ok(()),
+ other => other.context("writing completion script to stdout"),
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index f863b5c8..cb1249f2 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -13,6 +13,7 @@ pub mod backup;
pub mod bootstrap;
pub mod checkpoints;
pub mod commit;
+pub mod completions;
pub mod curator;
pub mod data_purge;
pub mod delete_page;
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 413ad34e..5dab2628 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -42,6 +42,12 @@ async fn main() -> Result<()> {
let command = match command {
Command::Hook(args) => return commands::hook::run(data_dir, args).await,
Command::HookDrain(_args) => return commands::hook::run_drain(data_dir).await,
+ // Completions are pure text derived from the command tree. Emitting
+ // them must not require a loadable config or an initialised data dir
+ // (they are typically generated before `init`, or in a packaging
+ // step), and tracing must not get the chance to interleave anything
+ // into the script on stdout.
+ Command::Completions(args) => return commands::completions::run(args),
other => other,
};
@@ -118,5 +124,7 @@ async fn main() -> Result<()> {
Command::Uninstall(args) => commands::uninstall::run(&config, args),
Command::Auth(args) => commands::auth::run(&config, args).await,
Command::User(args) => commands::user::run(&config, args).await,
+ // `Completions` is handled in the fast-path above (before config/tracing).
+ Command::Completions(args) => commands::completions::run(args),
}
}
diff --git a/crates/ai-memory-cli/tests/completions.rs b/crates/ai-memory-cli/tests/completions.rs
new file mode 100644
index 00000000..4601354c
--- /dev/null
+++ b/crates/ai-memory-cli/tests/completions.rs
@@ -0,0 +1,75 @@
+//! `ai-memory completions <shell>` output regression tests.
+//!
+//! The generator is clap_complete's, so these assert the contract the
+//! *project* owns: a script actually lands on stdout, it is addressed to the
+//! `ai-memory` binary name, it covers the real subcommand surface, and it is
+//! produced without touching a data directory or config file.
+
+use std::process::Command;
+
+fn ai_memory_bin() -> std::path::PathBuf {
+ // CARGO_BIN_EXE_<name> is set by cargo for integration tests.
+ std::path::PathBuf::from(env!("CARGO_BIN_EXE_ai-memory"))
+}
+
+fn completions_for(shell: &str) -> String {
+ let out = Command::new(ai_memory_bin())
+ // Point config + data dir at a path that does not exist: generating a
+ // completion script must not read, create, or require either.
+ .env("AI_MEMORY_DATA_DIR", "/nonexistent/ai-memory-completions")
+ .args(["completions", shell])
+ .output()
+ .unwrap_or_else(|e| panic!("failed to run `completions {shell}`: {e}"));
+
+ assert!(
+ out.status.success(),
+ "`completions {shell}` exited with {:?}: {}",
+ out.status.code(),
+ String::from_utf8_lossy(&out.stderr),
+ );
+ String::from_utf8(out.stdout).expect("completion script should be UTF-8")
+}
+
+#[test]
+fn every_supported_shell_emits_a_script_naming_the_binary() {
+ for shell in ["bash", "elvish", "fish", "powershell", "zsh"] {
+ let script = completions_for(shell);
+ assert!(
+ !script.trim().is_empty(),
+ "{shell} completion script was empty",
+ );
+ assert!(
+ script.contains("ai-memory"),
+ "{shell} completion script never mentions the binary name",
+ );
+ }
+}
+
+#[test]
+fn scripts_cover_subcommands_from_across_the_tree() {
+ // A spread of shallow, hyphenated, and nested commands: enough that a
+ // regression in how the command tree is handed to the generator shows up.
+ for shell in ["bash", "fish", "zsh"] {
+ let script = completions_for(shell);
+ for subcommand in ["init", "serve", "write-page", "purge-project", "user"] {
+ assert!(
+ script.contains(subcommand),
+ "{shell} completion script is missing `{subcommand}`",
+ );
+ }
+ }
+}
+
+#[test]
+fn an_unknown_shell_fails_without_emitting_a_script() {
+ let out = Command::new(ai_memory_bin())
+ .args(["completions", "nushell"])
+ .output()
+ .expect("failed to run completions");
+
+ assert!(!out.status.success(), "unknown shell should be rejected");
+ assert!(
+ out.stdout.is_empty(),
+ "nothing should reach stdout for an unknown shell",
+ );
+}
diff --git a/docs/install.md b/docs/install.md
index 29013861..060a8da1 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1116,6 +1116,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree
| `install-skills [--scope] [--agent]` | same host environment used for the agent skill dirs | Install or update only the managed ai-memory Agent Skills |
| `uninstall --apply` | same host environment used for install | Remove only ai-memory-owned hooks, MCP entries, instruction blocks, managed skill files, and generated plugin files after content/marker validation. Use `--mcp-url` for custom MCP endpoints and `--mcp-name` only to narrow removal. |
| `llm-test --provider …` | `docker run --rm -e …` | Smoke-test an LLM provider |
+| `completions <shell>` | `docker run --rm` or native binary | Print a bash/zsh/fish/PowerShell/elvish completion script; see [`shell-completions.md`](shell-completions.md) |
### Managed routing snippets and Agent Skills
diff --git a/docs/shell-completions.md b/docs/shell-completions.md
new file mode 100644
index 00000000..fdf7dc64
--- /dev/null
+++ b/docs/shell-completions.md
@@ -0,0 +1,88 @@
+# Shell completions
+
+`ai-memory completions <shell>` prints a completion script to stdout for
+`bash`, `zsh`, `fish`, `powershell`, or `elvish`. The script is generated from
+the binary's own command tree, so it covers every subcommand and flag of the
+version that produced it — including nested commands like `user rotate-token`
+and `auth login`.
+
+The command reads no config and does not need a data directory, so it can be
+run before `ai-memory init` or inside a packaging step.
+
+## Install
+
+### fish
+
+```fish
+ai-memory completions fish > ~/.config/fish/completions/ai-memory.fish
+```
+
+Fish loads that path lazily on first use — no shell restart, no `config.fish`
+edit.
+
+### zsh
+
+```zsh
+mkdir -p ~/.zfunc
+ai-memory completions zsh > ~/.zfunc/_ai-memory
+```
+
+`~/.zfunc` must be on `$fpath` before `compinit` runs. If it is not already,
+add this to `~/.zshrc` above the `compinit` call:
+
+```zsh
+fpath=(~/.zfunc $fpath)
+autoload -Uz compinit && compinit
+```
+
+Zsh caches completion metadata, so run `rm -f ~/.zcompdump` and start a new
+shell if a freshly regenerated script does not take effect.
+
+### bash
+
+Requires [bash-completion](https://github.com/scop/bash-completion).
+
+```bash
+mkdir -p ~/.local/share/bash-completion/completions
+ai-memory completions bash > ~/.local/share/bash-completion/completions/ai-memory
+```
+
+Start a new shell to pick it up. To load it for the current shell only:
+
+```bash
+source <(ai-memory completions bash)
+```
+
+### PowerShell
+
+```powershell
+ai-memory completions powershell | Out-String | Invoke-Expression
+```
+
+To persist it, append that line to the file at `$PROFILE`:
+
+```powershell
+ai-memory completions powershell >> $PROFILE
+```
+
+### elvish
+
+```elvish
+ai-memory completions elvish > ~/.config/elvish/lib/ai-memory.elv
+```
+
+Then add `use ai-memory` to `~/.config/elvish/rc.elv`.
+
+## Upgrades
+
+The script is a snapshot of the command tree at the moment it was generated.
+Re-run the same command after upgrading `ai-memory` so completions pick up new
+subcommands and flags. Nothing is checked into the repository, precisely so a
+stale script cannot ship alongside a newer binary.
+
+Docker users can generate a script without a local install:
+
+```bash
+docker run --rm akitaonrails/ai-memory:latest completions fish \
+ > ~/.config/fish/completions/ai-memory.fish
+```