Skip to content

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

Rust

fix(nix): drop the binary wrapper and finish the #1275 staging fixes

AkitaOnRailsf2ec95a08304
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8252c97b..23f504d7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,10 +11,6 @@ version in [`docs/changelog/`](docs/changelog/):
## [Unreleased]
-### Added
-- Added shell completions (bash, fish, zsh) to the Nix package output via
- `installShellFiles`.
-
### Fixed
- 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`
@@ -53,15 +49,22 @@ version in [`docs/changelog/`](docs/changelog/):
`.claude/CLAUDE.md`, or `CLAUDE.local.md` is present, and reads that file
instead when one exists. The `@AGENTS.md` import is how a canonical
`AGENTS.md` reaches sessions that read only `CLAUDE.md`. (#1276)
-- Fixed bundled hook discovery when `ai-memory` is installed in a standard Unix
- prefix layout (such as Nix), probing `<prefix>/share/ai-memory/hooks/` from
- `<prefix>/bin/ai-memory`.
-- Fixed `ai-memory install-hooks` and `setup-agent` failing when staging
- support scripts over existing read-only copies from a read-only store.
-- Avoided baking absolute `/nix/store/...` paths into generated hook scripts,
- resolving `ai-memory` dynamically via `$PATH` so hooks survive Nix garbage
- collection.
-- Wrapped the `ai-memory` binary in the Nix flake package with `git` on `PATH`.
+- Fixed bundled hook discovery for a binary installed in a standard Unix
+ prefix such as Nix: `install-hooks` and `setup-agent` now probe
+ `<prefix>/share/ai-memory/hooks/` from `<prefix>/bin/ai-memory`, and
+ `setup-agent` checks it before the fixed `/usr/local/share` and
+ `/usr/share` locations. (#1275)
+- Fixed `ai-memory install-hooks` and `setup-agent` failing on a second run
+ when the staged hook scripts were read-only copies from a read-only package
+ store (the Nix store ships them `0444`). Staging now replaces a read-only
+ copy instead of erroring. (#1275)
+- Fixed generated hook commands baking an absolute `/nix/store/...` binary
+ path that Nix garbage collection later deletes. A binary running from the
+ Nix store now renders the bare `ai-memory` command, resolved through `PATH`
+ when the hook runs. (#1275)
+- Fixed the NixOS service lacking `git` on `PATH`: the module now adds
+ `pkgs.git` to the unit's `path`. The package binary stays unwrapped so the
+ live-process guard can still see a running server. (#1275)
- Fixed Windows capture dropping the body of file and shell tool events
the client had kept. With `[capture] ignore_paths` active, server
re-inspection compiled a POSIX never-match sentinel and treated the
@@ -114,8 +117,6 @@ version in [`docs/changelog/`](docs/changelog/):
`CLAUDE.local.md` exists in the directory or above it, so a developer's
`CLAUDE.local.md` hid the block. The command now names the file Claude Code
reads instead and how to import `@AGENTS.md` from it. (#1297)
-
-### Fixed
- Fixed `move-session` leaving prompt profile candidates and ingest keys in the
source project. When a session is moved or re-homed into another project, its
prompt `profile_candidates` (`source_ref = 'session:<id>'`) and `ingest_keys`
diff --git a/README.md b/README.md
index 65c4a6f4..ca9b0c18 100644
--- a/README.md
+++ b/README.md
@@ -520,6 +520,14 @@ All options and defaults are in [`nix/nixos-module.nix`](nix/nixos-module.nix).
The module is entirely opt-in: `nix build`, `nix run`, `nix develop`, and the CLI are
unchanged if you don't import it.
+`git` is a runtime dependency. Hook capture and `ai-memory doctor` run it to
+read the repository a session works in. The module puts `pkgs.git` on the
+service's `PATH`. The package itself leaves the binary unwrapped, because a
+wrapper renames the running process and the live-process guard in `reset`,
+`restore`, `reindex` and `uninstall --purge-data` looks for a process named
+`ai-memory`. If you install the package without the module (`nix profile
+install`, `home.packages`), install `git` next to it.
+
## Everyday use
Day to day, you mostly do not think about ai-memory. Hooks capture
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 562816b3..c8aea8de 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -6147,15 +6147,32 @@ fn same_canonical_dir(a: &Path, b: &Path) -> bool {
}
}
+/// Copy `from` onto `to`, replacing a read-only `to` left by an earlier
+/// staging run. Package stores (Nix) ship hook sources as 0444, `fs::copy`
+/// carries that mode over, and a second copy onto the read-only destination
+/// fails with `PermissionDenied`. Only that failure removes the stale copy
+/// and retries, so a writable destination is overwritten exactly as before.
+pub(crate) fn copy_replacing(from: &Path, to: &Path) -> Result<()> {
+ let context = || format!("copying {} → {}", from.display(), to.display());
+ match fs::copy(from, to) {
+ Ok(_) => Ok(()),
+ Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied && to.is_file() => {
+ fs::remove_file(to)
+ .with_context(|| format!("removing read-only staged copy {}", to.display()))?;
+ fs::copy(from, to).with_context(context)?;
+ Ok(())
+ }
+ Err(err) => Err(err).with_context(context),
+ }
+}
+
/// Copy a single hook file (event script or shared `_lib.sh`) into the
/// staging dir, preserving the executable bit on Unix. Centralised so
/// the script bulk-copy and the `_lib.sh` companion follow the same
/// rules without duplicating permission-handling.
fn copy_hook_file(from: &Path, dest_root: &Path) -> Result<()> {
let to = dest_root.join(from.file_name().context("bad source file name")?);
- let _ = fs::remove_file(&to);
- fs::copy(from, &to)
- .with_context(|| format!("copying {} → {}", from.display(), to.display()))?;
+ copy_replacing(from, &to)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
@@ -6192,9 +6209,7 @@ fn copy_support_hook_scripts(source_dir: &Path, dest_root: &Path) -> Result<()>
continue;
}
let to = dest_lib.join(from.file_name().context("bad support file name")?);
- let _ = fs::remove_file(&to);
- fs::copy(&from, &to)
- .with_context(|| format!("copying {} → {}", from.display(), to.display()))?;
+ copy_replacing(&from, &to)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
@@ -6274,18 +6289,17 @@ fn hook_source_candidates(
// Standard Unix prefix layout: binary at `<prefix>/bin/ai-memory`,
// hooks installed under `<prefix>/share/ai-memory/hooks/<sub>` (Nix,
// Homebrew, /opt/local, custom prefix installs).
- if let Some(dir) = exe_dir.as_ref() {
- if dir.file_name().is_some_and(|name| name == "bin") {
- if let Some(prefix) = dir.parent() {
- candidates.push(
- prefix
- .join("share")
- .join("ai-memory")
- .join(crate::install_layout::HOOKS_DIR_NAME)
- .join(sub),
- );
- }
- }
+ if let Some(dir) = exe_dir.as_ref()
+ && dir.file_name().is_some_and(|name| name == "bin")
+ && let Some(prefix) = dir.parent()
+ {
+ candidates.push(
+ prefix
+ .join("share")
+ .join("ai-memory")
+ .join(crate::install_layout::HOOKS_DIR_NAME)
+ .join(sub),
+ );
}
// Docker image lays them out under /usr/local/share/ai-memory/.
candidates.push(PathBuf::from(format!(
@@ -10821,6 +10835,45 @@ model = "gpt-5"
);
}
+ /// Nix ships hook sources 0444 and `fs::copy` keeps that mode, so a
+ /// second `install-hooks` used to fail copying onto its own staged copy.
+ #[cfg(unix)]
+ #[test]
+ fn staging_replaces_read_only_existing_copies() {
+ use std::os::unix::fs::PermissionsExt;
+ let tmp = tempfile::TempDir::new().unwrap();
+ let source = tmp.path().join("src/hooks/claude-code");
+ fs::create_dir_all(source.parent().unwrap().join("lib")).unwrap();
+ fs::create_dir_all(&source).unwrap();
+ let script = source.join("session-start.sh");
+ let support = source.parent().unwrap().join("lib/helper.ps1");
+ fs::write(&script, "new\n").unwrap();
+ fs::write(&support, "new\n").unwrap();
+ let dest = tmp.path().join("dest/hooks/claude-code");
+ fs::create_dir_all(dest.parent().unwrap().join("lib")).unwrap();
+ fs::create_dir_all(&dest).unwrap();
+ let staged = [
+ dest.join("session-start.sh"),
+ dest.parent().unwrap().join("lib/helper.ps1"),
+ ];
+ for path in &staged {
+ fs::write(path, "old\n").unwrap();
+ fs::set_permissions(path, fs::Permissions::from_mode(0o444)).unwrap();
+ }
+
+ copy_hook_file(&script, &dest).unwrap();
+ copy_support_hook_scripts(&source, &dest).unwrap();
+
+ for path in &staged {
+ assert_eq!(
+ fs::read_to_string(path).unwrap(),
+ "new\n",
+ "{}",
+ path.display()
+ );
+ }
+ }
+
#[test]
fn hook_source_candidates_include_standard_prefix_share_dir() {
let candidates = hook_source_candidates(
@@ -10848,9 +10901,7 @@ model = "gpt-5"
);
assert!(
- !candidates.contains(&PathBuf::from(
- "/opt/share/ai-memory/hooks/claude-code"
- )),
+ !candidates.contains(&PathBuf::from("/opt/share/ai-memory/hooks/claude-code")),
"non-bin exe dir must not probe parent share dir; got {candidates:?}"
);
}
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index ec58bbba..dfaafc38 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -1999,24 +1999,39 @@ fn strip_deleted_suffix(exe: PathBuf) -> PathBuf {
/// binary. A missing file or a failed resolution falls back to
/// [`FALLBACK_HOOK_EXE`] instead of baking a dead absolute path into every
/// hook command.
+///
+/// A binary inside the Nix store also falls back to the bare command: the
+/// store path names one immutable package version, which `nix-collect-garbage`
+/// deletes after the next profile switch, while the profile's `bin/` on PATH
+/// keeps pointing at the current build.
fn embedded_exe_from(raw: Option<PathBuf>) -> PathBuf {
+ embedded_exe_with(raw, Path::is_file)
+}
+
+/// [`embedded_exe_from`] with the existence probe injected, so the store-path
+/// fallback is testable on hosts without a `/nix/store`.
+fn embedded_exe_with(raw: Option<PathBuf>, is_file: impl Fn(&Path) -> bool) -> PathBuf {
let Some(exe) = raw else {
return PathBuf::from(FALLBACK_HOOK_EXE);
};
- if exe.starts_with("/nix/store") {
+ if is_nix_store_path(&exe) {
return PathBuf::from(FALLBACK_HOOK_EXE);
}
- if exe.is_file() {
+ if is_file(&exe) {
return exe;
}
let stripped = strip_deleted_suffix(exe);
- if stripped.is_file() {
+ if is_file(&stripped) {
stripped
} else {
PathBuf::from(FALLBACK_HOOK_EXE)
}
}
+fn is_nix_store_path(path: &Path) -> bool {
+ path.starts_with("/nix/store")
+}
+
/// [`embedded_exe_from`] over this process's own executable.
pub(crate) fn hook_embedded_exe_path() -> PathBuf {
embedded_exe_from(std::env::current_exe().ok())
@@ -2786,20 +2801,61 @@ mod tests {
);
}
+ fn rendered_exec_command(exe: &Path) -> String {
+ let spec = windows_native_exec_spec_with_exe(
+ exe,
+ Path::new("/hooks/post-tool-use.sh"),
+ "http://h:49374",
+ None,
+ HookCommandContext::new(
+ HookCommandPlatform::WindowsNative,
+ "claude-code",
+ None,
+ None,
+ ),
+ );
+ let HookHandlerSpec::Exec { command, .. } = spec else {
+ panic!("expected exec spec")
+ };
+ command
+ }
+
+ /// The existence probe reports the store binary as present, so only the
+ /// store-path guard can produce the bare command: without it the hook
+ /// would name a path garbage collection later deletes.
#[test]
- fn embedded_exe_falls_back_for_nix_store_paths() {
+ fn hook_rendered_from_a_nix_store_exe_names_the_bare_command() {
+ let store = PathBuf::from("/nix/store/abc123xyz-ai-memory-2.6.3/bin/ai-memory");
+ let exe = embedded_exe_with(Some(store.clone()), |_| true);
+ assert_eq!(exe, PathBuf::from(FALLBACK_HOOK_EXE));
+ assert_eq!(rendered_exec_command(&exe), FALLBACK_HOOK_EXE);
+ let deleted = PathBuf::from(format!("{} (deleted)", store.display()));
assert_eq!(
- embedded_exe_from(Some(PathBuf::from(
- "/nix/store/abc123xyz-ai-memory-2.6.3/bin/ai-memory"
- ))),
+ embedded_exe_with(Some(deleted), |_| true),
PathBuf::from(FALLBACK_HOOK_EXE)
);
}
+ #[test]
+ fn hook_rendered_from_a_normal_exe_keeps_the_absolute_path() {
+ for normal in [
+ "/usr/bin/ai-memory",
+ "/home/dev/.nix-profile/bin/ai-memory",
+ "/opt/nix/store/bin/ai-memory",
+ ] {
+ let exe = embedded_exe_with(Some(PathBuf::from(normal)), |_| true);
+ assert_eq!(exe, PathBuf::from(normal));
+ assert_eq!(rendered_exec_command(&exe), normal);
+ }
+ }
+
#[test]
fn hook_embedded_exe_path_names_an_existing_file_without_marker() {
let exe = hook_embedded_exe_path();
- if exe == Path::new(FALLBACK_HOOK_EXE) {
+ // A test binary built inside a Nix sandbox runs from the store, where
+ // the resolver deliberately renders the bare command.
+ if std::env::current_exe().is_ok_and(|current| is_nix_store_path(&current)) {
+ assert_eq!(exe, PathBuf::from(FALLBACK_HOOK_EXE));
return;
}
assert!(exe.is_file(), "{} should exist", exe.display());
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index 48a9e4a0..9e4d5fbc 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -151,8 +151,7 @@ pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {
.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()))?;
+ install_hooks::copy_replacing(&from, &to)?;
// Preserve executable bit so the agent CLI can actually run
// the scripts. On Windows this is a no-op.
#[cfg(unix)]
@@ -654,8 +653,7 @@ fn copy_support_hook_scripts(source_dir: &Path, dest_dir: &Path) -> Result<()> {
let shared_lib = source_hooks_root.join("_lib.sh");
if shared_lib.is_file() {
let to = dest_hooks_root.join("_lib.sh");
- fs::copy(&shared_lib, &to)
- .with_context(|| format!("copying {} → {}", shared_lib.display(), to.display()))?;
+ install_hooks::copy_replacing(&shared_lib, &to)?;
}
let source_lib = source_hooks_root.join("lib");
@@ -678,8 +676,7 @@ fn copy_support_hook_scripts(source_dir: &Path, dest_dir: &Path) -> Result<()> {
from.file_name()
.with_context(|| format!("invalid hook support path {}", from.display()))?,
);
- fs::copy(&from, &to)
- .with_context(|| format!("copying {} → {}", from.display(), to.display()))?;
+ install_hooks::copy_replacing(&from, &to)?;
}
Ok(())
}
@@ -715,28 +712,33 @@ fn source_candidates(explicit: Option<&Path>, sub: &str, exe: Option<PathBuf>) -
if let Some(p) = explicit {
return vec![p.join(sub)];
}
- let mut v = vec![
- // Docker image lays them out under /usr/local/share/.
- PathBuf::from(format!("/usr/local/share/ai-memory/hooks/{sub}")),
- // Native Linux packages install hook sources under /usr/share.
- PathBuf::from(format!("/usr/share/ai-memory/hooks/{sub}")),
- ];
+ let mut v = Vec::with_capacity(5);
+ // Standard Unix prefix layout: `<prefix>/bin/<bin>` ships its bundle at
+ // `<prefix>/share/ai-memory/hooks/<sub>` (Nix, Homebrew, custom prefix).
+ // Probed before the fixed /usr paths, as install-hooks does, so a prefix
+ // install never stages a stale system-wide bundle.
+ if let Some(dir) = exe.as_deref().and_then(Path::parent)
+ && dir.file_name().is_some_and(|name| name == "bin")
+ && let Some(prefix) = dir.parent()
+ {
+ v.push(
+ prefix
+ .join("share")
+ .join("ai-memory")
+ .join(crate::install_layout::HOOKS_DIR_NAME)
+ .join(sub),
+ );
+ }
+ // Docker image lays them out under /usr/local/share/.
+ v.push(PathBuf::from(format!(
+ "/usr/local/share/ai-memory/hooks/{sub}"
+ )));
+ // Native Linux packages install hook sources under /usr/share.
+ v.push(PathBuf::from(format!("/usr/share/ai-memory/hooks/{sub}")));
if let Some(exe) = exe {
// Release tarball: `hooks/` sits in the same dir as the binary.
if let Some(dir) = exe.parent() {
v.push(dir.join(crate::install_layout::HOOKS_DIR_NAME).join(sub));
- // Standard Unix prefix layout: `<prefix>/bin/<bin>` -> `<prefix>/share/ai-memory/hooks/<sub>`
- if dir.file_name().is_some_and(|name| name == "bin") {
- if let Some(prefix) = dir.parent() {
- v.push(
- prefix
- .join("share")
- .join("ai-memory")
- .join(crate::install_layout::HOOKS_DIR_NAME)
- .join(sub),
- );
- }
- }
}
// Repo-local fallback for `cargo run setup-agent` during dev:
// target/<profile>/<bin> → repo root.
@@ -800,6 +802,54 @@ mod tests {
)),
"prefix share hooks/ dir must be probed; got {candidates:?}"
);
+ let position = |p: &str| candidates.iter().position(|c| c == Path::new(p));
+ assert!(
+ position("/nix/store/pkg/share/ai-memory/hooks/claude-code")
+ < position("/usr/share/ai-memory/hooks/claude-code"),
+ "prefix share must be probed before /usr/share; got {candidates:?}"
+ );
+ }
+
+ /// Nix ships hook sources 0444 and `fs::copy` keeps that mode, so a
+ /// second `setup-agent` used to fail copying onto its own staged copy.
+ #[cfg(unix)]
+ #[test]
+ fn staging_replaces_read_only_existing_copies() {
+ use std::os::unix::fs::PermissionsExt;
+ let tmp = tempfile::TempDir::new().unwrap();
+ let source = tmp.path().join("src/hooks/claude-code");
+ fs::create_dir_all(source.parent().unwrap().join("lib")).unwrap();
+ fs::create_dir_all(&source).unwrap();
+ let script = source.join("session-start.sh");
+ let shared = source.parent().unwrap().join("_lib.sh");
+ let support = source.parent().unwrap().join("lib/helper.ps1");
+ for path in [&script, &shared, &support] {
+ fs::write(path, "new\n").unwrap();
+ }
+ let dest = tmp.path().join("dest/hooks/claude-code");
+ fs::create_dir_all(dest.parent().unwrap().join("lib")).unwrap();
+ fs::create_dir_all(&dest).unwrap();
+ let staged = [
+ dest.join("session-start.sh"),
+ dest.parent().unwrap().join("_lib.sh"),
+ dest.parent().unwrap().join("lib/helper.ps1"),
+ ];
+ for path in &staged {
+ fs::write(path, "old\n").unwrap();
+ fs::set_permissions(path, fs::Permissions::from_mode(0o444)).unwrap();
+ }
+
+ install_hooks::copy_replacing(&script, &staged[0]).unwrap();
+ copy_support_hook_scripts(&source, &dest).unwrap();
+
+ for path in &staged {
+ assert_eq!(
+ fs::read_to_string(path).unwrap(),
+ "new\n",
+ "{}",
+ path.display()
+ );
+ }
}
#[test]
@@ -807,9 +857,7 @@ mod tests {
let exe = PathBuf::from("/opt/ai-memory/ai-memory");
let candidates = source_candidates(None, "claude-code", Some(exe));
assert!(
- !candidates.contains(&PathBuf::from(
- "/opt/share/ai-memory/hooks/claude-code"
- )),
+ !candidates.contains(&PathBuf::from("/opt/share/ai-memory/hooks/claude-code")),
"flat tarball directory must not treat parent as prefix; got {candidates:?}"
);
}
diff --git a/docs/install.md b/docs/install.md
index 2b306527..5d113ce6 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1111,6 +1111,10 @@ section](../README.md#nixos) (`nixosModules.default`,
`services.ai-memory.enable`). This section is the maintainer test ladder
for the flake and module: what CI runs, and what each tier proves.
+The package does not bundle `git`: the module adds `pkgs.git` to the
+service's `PATH`, and a package-only install needs `git` installed beside it.
+Do not wrap the binary to supply it (see the README section for why).
+
### Maintainer test ladder
1. **Package smoke**: `nix build .#packages.<system>.default` then
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index ba1d0a8f..0d876fac 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -78,7 +78,7 @@ means the boundary is not built yet.
| 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH |
| 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks; `--check-capture` refuses a rejected server-profile selection without printing its token or URL; once `[auth].bearer_token_file` names `auth-tokens/default` (this install's root bearer), `commands/server.rs` `refuse_the_root_token_name` refuses `server add default` and `server remove default` so no profile can be handed, overwrite or delete the root bearer | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `muse_hooks_honour_marker_scope_profiles_exclusions_and_allowlist` (the Meta Muse Code settings-hook front door: marker workspace/project, the profile's server and token never the install's, the payload's session id, an ignored relative `read_file` dropped with a kept control, allowlist silence from an unmarked checkout with a denylist control), `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `hook.rs` `a_selection_that_does_not_resolve_emits_nothing` (rejected routes refuse preflight; resolved profile control passes); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does); `server.rs` `the_root_bearer_file_name_cannot_be_registered_or_removed` (refused at the root bearer path; another name and an install without a root bearer file are the controls); `server_profiles.rs` `a_default_profile_shares_the_root_bearer_only_at_its_path`, `clear_tokens_keeps_the_root_bearer_and_removes_profile_tokens` | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |
| 11e | Native self-upgrade archive confinement (#1025) | `ai-memory-cli/src/commands/upgrade.rs` normalizes every tar/zip path, rejects links and special entries, extracts only the binary and `hooks/`, accepts only the exact non-runtime support layout emitted by `release.yml`, and caps both entry count and declared expanded bytes before writing | `upgrade.rs` `release_workflow_support_assets_are_exact_and_ignored` (shipped support paths admitted, near-miss docs/packaging/template paths refused), `extracts_archive_built_like_release_yml` and `extracts_zip_happy_path_with_hooks` (real workflow-shaped archives succeed but support assets are not written), `validate_rejects_path_traversal`, `zip_extract_rejects_path_traversal`, `tar_extract_rejects_declared_expansion_past_limit`, with binary/hooks extraction as the legitimate control | STRONG |
-| 11f | Native hook executable-path integrity after self-replacement (#1027) | `ai-memory-cli/src/commands/render_shared.rs` `hook_embedded_exe_path` is the single executable resolver for every persisted native hook form (POSIX/Windows command, Windows exec, Zero, ZCode, OpenCode 2 assistant capture): it prefers an existing literal path, strips Linux's trailing ` (deleted)` procfs marker only when the stripped installed binary exists, and otherwise falls back to the platform command name. Upgrade keeps the already-loaded config and refreshes in-process | `render_shared.rs` `embedded_exe_strips_the_marker_when_the_stripped_path_exists`, `embedded_exe_preserves_a_real_file_whose_name_has_the_marker_suffix`, `embedded_exe_falls_back_when_the_resolved_path_is_missing`, `hook_embedded_exe_path_names_an_existing_file_without_marker`; `upgrade_e2e.rs` `native_upgrade_refreshes_hooks_without_a_deleted_path_or_losing_cli_data_dir` reproduces the replacement window through the shipped binary, plants the corrupt suffix, and proves refresh removes it while preserving a CLI-only data dir | STRONG on Linux reproduction plus platform-neutral resolver/render coverage; Windows path rendering remains covered by its existing command/exec tests and full Windows CI |
+| 11f | Native hook executable-path integrity after self-replacement (#1027) | `ai-memory-cli/src/commands/render_shared.rs` `hook_embedded_exe_path` is the single executable resolver for every persisted native hook form (POSIX/Windows command, Windows exec, Zero, ZCode, OpenCode 2 assistant capture): it prefers an existing literal path, strips Linux's trailing ` (deleted)` procfs marker only when the stripped installed binary exists, and otherwise falls back to the platform command name. A binary running from `/nix/store` always renders the bare command (#1275): the store path names one package version that garbage collection deletes, while the profile's `bin/` on `PATH` follows upgrades. Upgrade keeps the already-loaded config and refreshes in-process | `render_shared.rs` `embedded_exe_strips_the_marker_when_the_stripped_path_exists`, `embedded_exe_preserves_a_real_file_whose_name_has_the_marker_suffix`, `embedded_exe_falls_back_when_the_resolved_path_is_missing`, `hook_embedded_exe_path_names_an_existing_file_without_marker` (asserts the bare command only when the test binary itself runs from the Nix store), `hook_rendered_from_a_nix_store_exe_names_the_bare_command` (the existence probe reports the store binary present, so only the store-path guard yields the bare command in the rendered exec hook) with its control `hook_rendered_from_a_normal_exe_keeps_the_absolute_path` (`/usr/bin`, `~/.nix-profile/bin`, and a non-root `.../nix/store/...` keep the absolute path); `upgrade_e2e.rs` `native_upgrade_refreshes_hooks_without_a_deleted_path_or_losing_cli_data_dir` reproduces the replacement window through the shipped binary, plants the corrupt suffix, and proves refresh removes it while preserving a CLI-only data dir | STRONG on Linux reproduction plus platform-neutral resolver/render coverage; Windows path rendering remains covered by its existing command/exec tests and full Windows CI |
| 11g | Cross-project tool attribution cannot bypass source or destination capture, or destination server routing (#932, #1199) | `ai-memory-hooks/src/capture_policy.rs` `absolute_tool_location_paths` accepts only bounded, recognized, absolute locations: file-tool targets, a search/list tool's explicit `path`, or a shell command's structured `workdir` (command text is never parsed for a location); `ai-memory-cli/src/commands/hook.rs` `tool_location_routing_cwd` requires every path to prove the same repository/marker boundary, refuses the reroute when the payload cwd's own capture policy would not keep the event (source `ignore_paths` may name paths outside the source checkout, and a command may name source files while its `workdir` points elsewhere), and resolves that destination before capture policy, allowlist marker, server profile, scope hints, or spool credentials. Relative, mixed-project, unsupported, and arbitrary non-project paths keep the payload cwd | `hook.rs` `absolute_file_target_uses_destination_scope_and_capture_policy` (hostile content under the destination exclusion is never spooled; a public control is routed there), `absolute_file_target_cannot_escape_a_destination_server_profile` (unregistered destination profile drops instead of falling back to source/install default), `file_target_routing_refuses_relative_external_and_mixed_project_paths`, `workdir_reroute_applies_the_destination_capture_policy` (a `workdir`-rerouted command reading a destination-excluded path is dropped, public control kept), **`a_reroute_cannot_escape_the_source_capture_exclusions`** (adversarial: a file read under a source pattern that names another project's directory, and a shell command naming an excluded source file with `workdir` in another project, are both refused; public file and shell controls still reroute; fails with the source-policy check removed), `hermes_tool_location_finds_the_marker_the_process_cwd_lacks` (Hermes `terminal` `workdir`, `read_file` `path` and `search_files` `path` reach the repository marker under allowlist; no-workdir, relative-workdir and relative-search controls stay with the unmarked process cwd); `capture_policy.rs` `absolute_tool_location_paths_cover_search_dirs_and_shell_workdirs` (relative workdir, command-text paths, workdir without a command, and Hermes `process` yield no location) | STRONG for native `ai-memory hook`; generated and compatibility hooks retain cwd-only routing |
| 11h | Docker-wrapper capture-policy capability (#1002) | `bin/ai-memory` routes ordinary Linux/macOS `install-hooks`, upgrade refreshes, and every `hook`/`hook-drain` invocation through the stable checksum-verified native host client, so the hook process executes the capture-policy boundary in 11b before spool/network; a hook config that calls the wrapper never runs in the helper container, and an unavailable client drops the event with exit 0 instead of falling back to it. Only an explicit `AI_MEMORY_HOOK_PLATFORM=posix|windows` retains the documented script compatibility path and its warning; `AI_MEMORY_NATIVE_BIN` may not point back to the wrapper. For a server initialized on the named volume, `bin/ai-memory` `refresh_volume_token` (run only by `install-hooks`) copies `/data/auth-tokens/default` (only when `/data/config.toml` names it) to an owner-only `native-runner/server-token` through the helper's stdout, and `use_volume_token` points the native client at that copy (the managed host commands and `mcp-bridge` only read it and never enter the container engine) with `AI_MEMORY_AUTH__BEARER_TOKEN_FILE`, so it is a file-sourced token (never rendered into a harness config) and never an argv; a refresh that reads no token from a reachable volume deletes the copy, and a successful full `uninstall --apply` deletes it after the container returns; a bind-mounted `AI_MEMORY_DATA_DIR` is read directly and an explicit `AI_MEMORY_AUTH_TOKEN` wins | `scripts/check-native-packaging.sh` `Checking host-launch wrapper routing`: a default allowlist install reaches the fake native client while a Docker executable that always fails proves no container fallback occurred; the explicit `posix` control reaches fake Docker and adds no native invocation; the self-referential native override is refused. `tests/wrapper_upgrade.sh` `lifecycle hook native host routing`: `hook --event session-start` and `hook-drain` reach the fake native client with the stdin payload while `docker`/`podman` stubs on PATH and in `AI_MEMORY_DOCKER` stay unused, and a non-executable `AI_MEMORY_NATIVE_BIN` exits 0 without reaching the engine; `Checking the wrapper hands host commands the volume's root bearer`: for `mcp-bridge`, `install-hooks` and `run` the fake native client receives the token file (mode 600, right content) and the token is absent from its argv; controls: a bind-mounted data dir and an explicit `AI_MEMORY_AUTH_TOKEN` make no copy and ask no container (bite: dropping the export fails the check); `Checking the host token copy goes with the volume's token and with uninstall`: a volume answering with no token removes the copy and hands none over, while an unreachable engine keeps it; a dry-run, `--only hooks` or failing `uninstall` keeps it and a successful `uninstall --apply` removes it (bite: without either removal the check fails); `auth_default_e2e.rs` `a_host_client_given_the_token_file_by_env_authenticates` (the native side of the handoff, with a no-variable control) | STRONG on the shipped Linux/macOS wrapper. Windows and remote/manual script installers remain explicitly outside capture-policy v1 |
| 11j | Offline recovery journal and transcript replay | `ai-memory-cli/src/commands/recovery.rs` keeps bounded locators, ordered semantic transcript digests, pre-launch cursors and persistent correlated-delivery/loss evidence in an atomic journal, refuses a symlinked data dir and any symlinked component inside it (ancestors above the data dir are trusted, so macOS `/var` → `/private/var` works), sanitizes/caps failure reasons, and bounds each replay plus the whole pass; `hook_spool` coordinates enqueue and quarantine with short filesystem locks, canonically resolves partial scope from the recorded cwd, bounds per-file reads and current global occupancy across the main spool and recovery directories, sweeps completed tombstones, and holds correlated events outside drain until replay succeeds or restores them on failure; degraded resumes use `ai-memory-workstream`'s adapter-validated delta export, whose blocking parse and baseline scans are capped by record, event-count, source-byte and serialized-byte totals; `backfill::import_exact_session` chunks by item and byte limits and requires per-item durable acknowledgements; `run.rs` journals every session launch, including explicit spool-only evidence for unsupported exporters, and journals a resumed export only after capturing its exact pre-launch cursor; `workstream.rs` `/recover/finish` retains owner/project authorization, rejects superseded runs, and validates a finished retry by durable transcript/native/cursor/exit identity without regenerating its checkpoint; validated recovery ingest keys bind session, agent, event kind and sanitized event identity until session purge | `transcript.rs` `persisted_baseline_exports_only_offline_append_and_rejects_rewrite`, parser/baseline cap and ordered-semantic digest tests; CLI `run_offline.rs` real degraded spool-only and overlap/idempotency tests; `recovery.rs` `spool_only_without_correlated_evidence_never_auto_clears`, `a_dropped_spool_event_stays_lost_on_the_next_empty_pass`, loss/time-budget tests, `symlinked_journal_and_ancestor_are_refused`, `a_symlinked_ancestor_of_the_data_dir_is_trusted`, `a_symlink_inside_a_data_dir_under_a_symlinked_ancestor_is_refused`; `hook_spool.rs` partial-scope late enqueue, completion-race, occupancy churn/active-cap, bounded-read and tombstone-sweep tests, plus interval isolation (`completed_tombstone_keeps_a_later_resume_of_the_same_session` proves a post-interval resume hook is delivered, `completing_one_recovery_interval_leaves_the_other_intervals_entries_intact` proves one interval's completion never consumes another's evidence and ambiguous entries fail closed into the main spool); `backfill.rs` `two_sequential_recovery_intervals_on_one_resumed_session_replay_exactly_once` proves the second interval's content and session-end are stored with end-of-session effects while reruns stay pure replays; `transcript.rs` `an_oversized_first_record_is_skipped_by_session_listing_caps` proves the first-record byte caps bite before allocation; store `insert_observation_ingest_dedups_on_key` rejects cross-session and changed-event preclaims; hooks `expired_run_recovery_is_owner_only_and_refuses_superseded_runs` proves changed transcript refusal and changed-checkpoint no-op | STRONG on Unix integration coverage; Unix lock opens use no-follow and atomic replacement rechecks the destination. Windows owner-only ACL/reparse and lock semantics require the PR `windows` lane |
diff --git a/flake.nix b/flake.nix
index 0d284b9e..6ec71ceb 100644
--- a/flake.nix
+++ b/flake.nix
@@ -365,10 +365,14 @@
src = ./.;
cargoLock.lockFile = ./Cargo.lock;
- nativeBuildInputs = [
- pkgs.makeBinaryWrapper
- pkgs.installShellFiles
- ];
+ # No nativeBuildInputs needed — the build is fully self-contained
+ # (SQLite bundled, libgit2 vendored, rustls with webpki-roots).
+ #
+ # The binary is deliberately NOT wrapped (wrapProgram renames it
+ # to `.ai-memory-wrapped`, which hides a running server from the
+ # live-process guard that matches the process name `ai-memory`).
+ # Commands that shell out to `git` find it on PATH; the NixOS
+ # module adds git to the service's PATH.
# Skip the Tailwind CLI download in the sandbox. The build script
# falls back to the vendored static/tailwind.css committed to the
@@ -402,17 +406,6 @@
mkdir -p $out/etc/ai-memory
cp crates/ai-memory-cli/templates/config.default.toml \
$out/etc/ai-memory/config.default.toml
- ''
- + lib.optionalString (pkgs.stdenv.buildPlatform.canExecute pkgs.stdenv.hostPlatform) ''
- installShellCompletion --cmd ai-memory \
- --bash <($out/bin/ai-memory completions bash) \
- --fish <($out/bin/ai-memory completions fish) \
- --zsh <($out/bin/ai-memory completions zsh)
- '';
-
- # Wrap git on PATH so cli operations shelling out to git succeed in minimal environments.
- postFixup = ''
- wrapProgram $out/bin/ai-memory --prefix PATH : ${lib.makeBinPath [ pkgs.git ]}
'';
meta = {
diff --git a/nix/nixos-module.nix b/nix/nixos-module.nix
index 6d412d14..4a728866 100644
--- a/nix/nixos-module.nix
+++ b/nix/nixos-module.nix
@@ -310,6 +310,10 @@ in
after = if isLoopback then [ "network.target" ] else [ "network-online.target" ];
wants = lib.optionals (!isLoopback) [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
+ # The package binary is not wrapped (a wrapper renames the process
+ # and blinds the live-process guard), so the git it shells out to
+ # comes from the unit's PATH.
+ path = [ pkgs.git ];
serviceConfig = lib.mkMerge [
{