Skip to content

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

Rust

Merge pull request #1028 from MarconiVini/fix/upgrade-deleted-hook-path

AkitaOnRails53985bddc466
diff --cc CHANGELOG.md
index 4573bb1d,b1c64caa..44845d36
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -12,29 -12,16 +12,36 @@@ and this project adheres to [Semantic V
provider. (#1026)
### Fixed
-- `ai-memory upgrade` no longer corrupts every hook command with the kernel's
- ` (deleted)` path suffix. The upgrade replaced its own binary and then
- re-rendered the staged hook configs from the same, now exe-deleted process:
- on Linux `/proc/<pid>/exe` came back as `<path> (deleted)` and that string
- was embedded verbatim, so every hook failed with `not found` until the
- suffix was stripped from the settings file by hand. The refresh now re-runs
- `install-hooks --apply` from the freshly installed binary in a child
- process, and hook rendering strips the kernel marker — falling back to the
- bare `ai-memory` command name when the resolved path is missing — instead of
- embedding a dead absolute path. (#1027)
++- Fixed `ai-memory upgrade` rewriting native hook commands with Linux's
++ ` (deleted)` executable-path suffix after replacing its own binary. Every
++ hook renderer now keeps a still-existing literal path, otherwise strips the
++ kernel suffix only when the resulting installed binary exists, and finally
++ falls back to the bare `ai-memory` command instead of embedding a dead path.
++ The in-process refresh continues using the already-loaded CLI/config scope.
++ (#1027)
+- Fixed native `ai-memory upgrade` rejecting every current Linux, macOS, and
+ Windows release archive when it encountered the packaging, config-template,
+ or documentation entries shipped beside the binary. The extractor now
+ validates the exact support-file layout emitted by `release.yml`, ignores
+ those non-runtime files during self-upgrade, and still extracts only the
+ binary and hooks. Archive entry-count and expanded-size caps now complement
+ the existing compressed-download limit. (#1025)
+- Fixed the recommended Linux/macOS Docker-wrapper `install-hooks` path
+ silently installing shell hooks that cannot enforce client-side capture
+ controls such as `[capture] ignore_paths` and allowlist mode. The wrapper now
+ uses its existing checksum-verified native host client for hook installation
+ and refresh, while an explicit `AI_MEMORY_HOOK_PLATFORM=posix|windows` keeps
+ the documented compatibility fallback and warning. Wrapper upgrades refresh
+ that stable native client before rewriting existing hook registrations.
+ (#1002)
+- Fixed managed Codex sessions losing their startup continuity when a shared
+ Codex app-server daemon reports a finished run's stale `AI_MEMORY_RUN_ID`.
+ SessionStart now recovers only the sole live, undelivered Codex run in the
+ already-authorized repository, checkout cwd, and operator bucket, and links
+ it atomically to the new native session. Active boundary mismatches,
+ concurrent matching runs, cross-project or cross-worktree candidates,
+ cross-operator candidates, and a second linker all fail closed instead of
+ guessing or rebinding a run. (#987)
- `ai-memory doctor` now warns when the nearest `.ai-memory.toml`'s
`[capture]` section is invalid. This fails closed today — every file and
shell tool event is reduced to metadata until the marker is fixed, nothing
diff --cc crates/ai-memory-cli/src/commands/install_hooks.rs
index 9503b32c,35056f16..1f66f043
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@@ -32,8 -32,9 +32,9 @@@ use crate::commands::render_shared::
build_devin_payload_with_data_dir, build_grok_payload_with_data_dir,
build_kiro_cli_v2_hooks_value, build_kiro_cli_v3_hooks_value,
build_pool_settings_yaml_with_data_dir, build_profile_payload_for_agent,
-- hook_script_for_claude_code, hook_script_for_current_platform, kimi_code_hook_commands,
- local_hook_policy_v1_supported, ts_capture_policy_v1, ts_string_literal, ts_timeout_signal,
- local_hook_policy_v1_supported, strip_deleted_suffix, ts_capture_policy_v1, ts_string_literal,
- ts_timeout_signal,
++ hook_embedded_exe_path, hook_script_for_claude_code, hook_script_for_current_platform,
++ kimi_code_hook_commands, local_hook_policy_v1_supported, ts_capture_policy_v1,
++ ts_string_literal, ts_timeout_signal,
};
use crate::commands::uninstall::hook_command_is_ours;
use crate::config::{Config, DEFAULT_SERVER_URL};
@@@ -3244,8 -3245,12 +3245,7 @@@ fn build_opencode2_plugin
// path as invoked, like every other native hook config: a canonicalized
// one pins the target behind a versioned symlink or junction.
let native_hook = if capture_assistant {
- let exe =
- std::env::current_exe().context("cannot locate ai-memory native hook executable")?;
- // Strip the kernel's ` (deleted)` readlink marker before baking: a
- // re-apply from a process whose binary was just replaced under it must
- // not bake the artifact into the generated module.
- let exe = strip_deleted_suffix(
- std::env::current_exe().context("cannot locate ai-memory native hook executable")?,
- );
++ let exe = hook_embedded_exe_path();
ts_string_literal(&strip_windows_verbatim_prefix(&exe.to_string_lossy()))
} else {
"undefined".to_string()
diff --cc crates/ai-memory-cli/src/commands/render_shared.rs
index 81fe726e,3d0e549e..0f7f0ef8
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@@ -1582,6 -1578,53 +1578,58 @@@ pub(crate) fn local_hook_policy_v1_supp
)
}
+ /// Fallback when no usable executable path can be embedded: the bare command
-/// name, resolved through `PATH` when each hook runs. Every embed site already
-/// fell back to this spelling when `current_exe()` errored.
++/// name, resolved through `PATH` when each hook runs.
++#[cfg(not(windows))]
+ const FALLBACK_HOOK_EXE: &str = "ai-memory";
++#[cfg(windows)]
++const FALLBACK_HOOK_EXE: &str = "ai-memory.exe";
+
+ /// Strip the ` (deleted)` marker the Linux kernel appends to the
+ /// `/proc/<pid>/exe` readlink once the executable's inode has been unlinked or
+ /// replaced (Rust std passes the marker through verbatim —
-/// rust-lang/rust#40284). It is a read artifact, never part of a real file
-/// name.
-pub(crate) fn strip_deleted_suffix(exe: PathBuf) -> PathBuf {
++/// rust-lang/rust#40284). A real executable may itself use that suffix, so
++/// callers must prefer the unmodified path when it still exists.
++fn strip_deleted_suffix(exe: PathBuf) -> PathBuf {
+ match exe.to_str() {
+ Some(text) => text
+ .strip_suffix(" (deleted)")
+ .map(PathBuf::from)
+ .unwrap_or(exe),
+ None => exe,
+ }
+ }
+
+ /// The executable path to embed in a rendered hook command, given what
+ /// `current_exe()` produced.
+ ///
+ /// The classic corrupting sequence is `ai-memory upgrade`: it replaces its own
+ /// binary and then re-renders the staged hook configs from the same, now
+ /// exe-deleted process, so `current_exe()` comes back as `<path> (deleted)`.
+ /// Stripping the marker yields the path that now holds the freshly installed
+ /// 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.
+ fn embedded_exe_from(raw: Option<PathBuf>) -> PathBuf {
+ let Some(exe) = raw else {
+ return PathBuf::from(FALLBACK_HOOK_EXE);
+ };
++ if exe.is_file() {
++ return exe;
++ }
+ let stripped = strip_deleted_suffix(exe);
+ if stripped.is_file() {
+ stripped
+ } else {
+ PathBuf::from(FALLBACK_HOOK_EXE)
+ }
+ }
+
+ /// [`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())
+ }
+
fn hook_command(
script: &Path,
server_url: &str,
@@@ -1651,9 -1694,9 +1699,7 @@@
// out; double quotes + the native Windows path work in cmd.exe and
// Git Bash. The event name is a fixed slug with no shell
// metacharacters, so it is left unquoted.
-- let exe = std::env::current_exe()
-- .map(|p| p.to_string_lossy().into_owned())
-- .unwrap_or_else(|_| "ai-memory".to_string());
++ let exe = hook_embedded_exe_path().to_string_lossy().into_owned();
let event = script
.file_stem()
.and_then(|s| s.to_str())
@@@ -1697,9 -1740,9 +1743,7 @@@
// gets the local spool + OIDC fallback, instead of the `.sh` script
// that POSTs via curl. Mirrors `WindowsNative` but with POSIX
// single-quote quoting. The event name is the script stem.
-- let exe = std::env::current_exe()
-- .map(|p| p.to_string_lossy().into_owned())
-- .unwrap_or_else(|_| "ai-memory".to_string());
++ let exe = hook_embedded_exe_path().to_string_lossy().into_owned();
let event = script
.file_stem()
.and_then(|s| s.to_str())
@@@ -1738,7 -1781,7 +1782,7 @@@ fn windows_native_exec_spec
auth_token: Option<&str>,
context: HookCommandContext<'_>,
) -> HookHandlerSpec {
-- let exe = std::env::current_exe().unwrap_or_else(|_| Path::new("ai-memory.exe").to_path_buf());
++ let exe = hook_embedded_exe_path();
windows_native_exec_spec_with_exe(&exe, script, server_url, auth_token, context)
}
@@@ -2210,6 -2253,52 +2254,63 @@@ mod tests
#[cfg(windows)]
use std::process::Stdio;
+ #[test]
+ fn strip_deleted_suffix_removes_only_the_trailing_kernel_marker() {
+ assert_eq!(
+ strip_deleted_suffix(PathBuf::from("/opt/ai-memory/bin/ai-memory (deleted)")),
+ PathBuf::from("/opt/ai-memory/bin/ai-memory")
+ );
+ // A marker mid-path is a legitimate directory name, not the kernel's
+ // artifact; only the trailing suffix reads as one.
+ let mid = PathBuf::from("/opt/dir (deleted)/ai-memory");
+ assert_eq!(strip_deleted_suffix(mid.clone()), mid);
+ let clean = PathBuf::from("/opt/ai-memory/bin/ai-memory");
+ assert_eq!(strip_deleted_suffix(clean.clone()), clean);
+ }
+
+ #[test]
+ fn embedded_exe_strips_the_marker_when_the_stripped_path_exists() {
+ // The exact corruption window of `ai-memory upgrade`: the process is
+ // still executing the old inode after the rename-over replace, so
+ // `current_exe()` carries the marker while the stripped path already
+ // holds the freshly installed binary.
+ let dir = tempfile::tempdir().expect("tempdir");
+ let exe = dir.path().join("ai-memory");
+ fs::write(&exe, b"binary").expect("write exe");
+ let deleted = PathBuf::from(format!("{} (deleted)", exe.display()));
+ assert_eq!(embedded_exe_from(Some(deleted)), exe);
+ }
+
++ #[test]
++ fn embedded_exe_preserves_a_real_file_whose_name_has_the_marker_suffix() {
++ let dir = tempfile::tempdir().expect("tempdir");
++ let literal = dir.path().join("ai-memory (deleted)");
++ let stripped = dir.path().join("ai-memory");
++ fs::write(&literal, b"literal binary").expect("write literal exe");
++ fs::write(&stripped, b"decoy binary").expect("write stripped decoy");
++
++ assert_eq!(embedded_exe_from(Some(literal.clone())), literal);
++ }
++
+ #[test]
+ fn embedded_exe_falls_back_when_the_resolved_path_is_missing() {
+ // A failed resolution or a dead path must not bake a broken absolute
+ // path into hook commands; the bare name resolves through PATH when
+ // each hook runs.
- assert_eq!(embedded_exe_from(None), PathBuf::from("ai-memory"));
++ assert_eq!(embedded_exe_from(None), PathBuf::from(FALLBACK_HOOK_EXE));
+ assert_eq!(
+ embedded_exe_from(Some(PathBuf::from("/nonexistent/ai-memory (deleted)"))),
- PathBuf::from("ai-memory")
++ PathBuf::from(FALLBACK_HOOK_EXE)
+ );
+ }
+
+ #[test]
+ fn hook_embedded_exe_path_names_an_existing_file_without_marker() {
+ let exe = hook_embedded_exe_path();
+ assert!(exe.is_file(), "{} should exist", exe.display());
+ assert!(!exe.to_string_lossy().ends_with(" (deleted)"));
+ }
+
fn decode_powershell_encoded_command(command: &str) -> String {
let (_, encoded) = command
.split_once(" -EncodedCommand ")
diff --cc crates/ai-memory-cli/tests/suite/upgrade_e2e.rs
index 5ddfd478,5ddfd478..120c416c
--- a/crates/ai-memory-cli/tests/suite/upgrade_e2e.rs
+++ b/crates/ai-memory-cli/tests/suite/upgrade_e2e.rs
@@@ -248,4 -248,4 +248,99 @@@ mod slow
server.abort();
}
++
++ #[cfg(target_os = "linux")]
++ #[tokio::test]
++ async fn native_upgrade_refreshes_hooks_without_a_deleted_path_or_losing_cli_data_dir() {
++ let asset = host_asset_name().to_string();
++ let archive = Arc::new(build_release_archive());
++ let hash = format!("{:x}", Sha256::digest(archive.as_ref()));
++ let fixture = ReleaseFixture {
++ checksum_body: format!("{hash} {asset}\n"),
++ asset,
++ archive,
++ };
++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
++ .await
++ .expect("bind release fixture");
++ let addr = listener.local_addr().expect("fixture addr");
++ let app = Router::new()
++ .route("/releases/latest/tag", get(latest_tag))
++ .route("/releases/download/{tag}/{name}", get(download))
++ .with_state(fixture);
++ let server = tokio::spawn(async move {
++ axum::serve(listener, app).await.expect("fixture serve");
++ });
++
++ let prefix = tempfile::tempdir().expect("install prefix");
++ let data_dir = tempfile::tempdir().expect("data dir");
++ let home = tempfile::tempdir().expect("home");
++ let exe = install_writable_prefix(prefix.path());
++ // This case needs install-hooks to resolve its source from the staged
++ // data dir after replacement, not from the intentionally minimal
++ // sibling hooks fixture used by the replacement test above.
++ fs::remove_dir_all(prefix.path().join("bin/hooks")).expect("remove sibling hooks");
++ let hooks_source = Path::new(env!("CARGO_MANIFEST_DIR"))
++ .parent()
++ .and_then(Path::parent)
++ .expect("workspace root")
++ .join("hooks");
++ let settings = home.path().join(".claude/settings.json");
++
++ let mut install = hermetic(exe.to_str().expect("utf-8 exe path"));
++ install
++ .arg("--data-dir")
++ .arg(data_dir.path())
++ .args(["install-hooks", "--agent", "claude-code", "--hooks-dir"])
++ .arg(&hooks_source)
++ .arg("--apply")
++ .env("HOME", home.path());
++ let installed = tokio::process::Command::from(install)
++ .output()
++ .await
++ .expect("install initial hooks");
++ assert!(
++ installed.status.success(),
++ "initial hook install failed: {}",
++ String::from_utf8_lossy(&installed.stderr)
++ );
++
++ // Force proof that the post-replacement refresh actually rewrites the
++ // config. A child process that loses the CLI-only --data-dir, or a
++ // no-op refresh, leaves this exact reported corruption behind.
++ let clean = fs::read_to_string(&settings).expect("read initial settings");
++ let exe_text = exe.to_string_lossy();
++ assert!(clean.contains(exe_text.as_ref()), "missing native exe path");
++ let corrupted = clean.replace(exe_text.as_ref(), &format!("{} (deleted)", exe.display()));
++ assert_ne!(clean, corrupted, "fixture did not corrupt any hook path");
++ fs::write(&settings, corrupted).expect("plant deleted-path suffix");
++
++ let base = format!("http://{addr}/releases");
++ let mut upgrade = hermetic(exe.to_str().expect("utf-8 exe path"));
++ upgrade
++ .arg("--data-dir")
++ .arg(data_dir.path())
++ .args(["upgrade", "--version", TAG, "--force"])
++ .env("AI_MEMORY_RELEASE_BASE_URL", &base)
++ .env("HOME", home.path());
++ let output = tokio::process::Command::from(upgrade)
++ .output()
++ .await
++ .expect("spawn upgrade");
++ assert!(
++ output.status.success(),
++ "upgrade failed: stdout={}\nstderr={}",
++ String::from_utf8_lossy(&output.stdout),
++ String::from_utf8_lossy(&output.stderr)
++ );
++
++ let refreshed = fs::read_to_string(&settings).expect("read refreshed settings");
++ assert!(!refreshed.contains(" (deleted)"), "{refreshed}");
++ assert!(refreshed.contains(exe_text.as_ref()), "{refreshed}");
++ assert!(
++ refreshed.contains(&data_dir.path().to_string_lossy().into_owned()),
++ "CLI-only data dir was lost: {refreshed}"
++ );
++ server.abort();
++ }
}
diff --cc docs/security-boundaries.md
index dd8ff2b7,5738ced6..845b9f25
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@@ -53,13 -53,10 +53,14 @@@ boundary not yet built
| 10f | Session-time repair is scope-bound (no cross-project timestamp rewrite) | `ai-memory-store/src/ops.rs` `repair_session_times` — every candidate is read back and updated with `WHERE id=? AND workspace_id=? AND project_id=?`; a row outside that 3-tuple is reported `NotFound` and untouched, same code path as an id that does not exist at all; `ai-memory-mcp/src/admin.rs` `handle_repair_session_times` passes the caller's `(workspace, project)` straight through, never the candidate's own | `ops.rs` `repair_session_times_does_not_touch_a_session_of_another_project` (control: sibling session in-scope repaired in the same batch); `admin_repair_session_times.rs` `cross_project_session_is_not_found_and_untouched`; both bite-checked by dropping the `project_id` filter | STRONG |
| 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded` | STRONG |
| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized); an invalid marker makes file and shell calls metadata-only, and the server admits a metadata-only shell body only under an invalid marker (`router.rs` `metadata_protocol_is_legal`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`; `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 vectors, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job) | STRONG |
+| 11c | Docker-wrapper capture-policy capability (#1002) | `bin/ai-memory` routes ordinary Linux/macOS `install-hooks` and upgrade refreshes through the stable checksum-verified native host client, so the hook process executes the capture-policy boundary in 11b before spool/network. 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 | `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 | STRONG on the shipped Linux/macOS wrapper. Windows and remote/manual script installers remain explicitly outside capture-policy v1 |
| 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 | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `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); `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) | 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 |
| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401 | STRONG |
| 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous |
+| 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet |
| 13b | Managed-run lease exclusivity (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and refuses any other `active` run on the workstream inside one transaction (`StoreError::WorkstreamBusy`), regardless of the `lease_owner` label; `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` `wait_out_held_lease` (interactive relaunch) only waits for a reported expiry and retries — it never cancels or claims another run, so the server's busy check stays the sole arbiter | `store/src/lib.rs` `managed_workstream_batches_are_idempotent_and_release_the_lease` (second prepare refused while active); `run.rs` `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over` (renewing holder is reported, never displaced), with controls `interactive_launch_waits_out_a_lapsing_lease_then_proceeds` and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key |
| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository`; `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |
| 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`; `router.rs` `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others |