Skip to content

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

Rust

fix(upgrade): accept complete release archives

AkitaOnRails9e5bfe9f9c34
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f8a96e42..4573bb1d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
provider. (#1026)
### Fixed
+- 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
diff --git a/crates/ai-memory-cli/src/commands/upgrade.rs b/crates/ai-memory-cli/src/commands/upgrade.rs
index 191e413c..0288853f 100644
--- a/crates/ai-memory-cli/src/commands/upgrade.rs
+++ b/crates/ai-memory-cli/src/commands/upgrade.rs
@@ -16,8 +16,9 @@
//! CLI fetch, the extract `TempDir` is discarded after the replace, and a
//! cached archive would only add a stale-binary risk; **rate limit / load
//! shedding** — n/a (single outbound GET from a user-invoked CLI command,
-//! no ingress). The 128 MiB body cap is a security limit, not a resilience
-//! decision (see [`MAX_RELEASE_DOWNLOAD_BYTES`]).
+//! no ingress). The 128 MiB body cap plus entry-count and 512 MiB expanded-size
+//! caps are security limits, not resilience decisions (see
+//! [`MAX_RELEASE_DOWNLOAD_BYTES`]).
//!
//! Ownership (live CLI command — kept in one module by convention):
//! - install classification (container / package-managed / writable)
@@ -49,6 +50,12 @@ const USER_AGENT: &str = concat!("ai-memory-cli/", env!("CARGO_PKG_VERSION"));
/// headroom while refusing multi-GB DoS if a mirror or compromised host
/// advertises / streams an oversized payload.
const MAX_RELEASE_DOWNLOAD_BYTES: usize = 128 * 1024 * 1024;
+/// Refuse an archive whose directory contains an unreasonable number of
+/// records, even when every individual path is allowed.
+const MAX_RELEASE_ARCHIVE_ENTRIES: usize = 4_096;
+/// Limit declared expanded bytes separately from the compressed HTTP body so
+/// an otherwise valid-looking archive cannot exhaust the install disk.
+const MAX_RELEASE_EXPANDED_BYTES: u64 = 512 * 1024 * 1024;
const HTTP_TIMEOUT_SECS: u64 = 120;
#[cfg(unix)]
const UNIX_EXECUTABLE_MODE: u32 = 0o755;
@@ -407,14 +414,18 @@ fn extract_release_tar_gz(bytes: &[u8], dest: &Path) -> Result<()> {
let decoder = GzDecoder::new(bytes);
let mut archive = tar::Archive::new(decoder);
archive.set_preserve_permissions(false);
+ let mut budget = ReleaseArchiveBudget::default();
for entry in archive.entries()? {
let mut entry = entry?;
let path = entry.path()?.into_owned();
let entry_type = entry.header().entry_type();
- validate_release_tar_entry(&path, entry_type)?;
- entry
- .unpack_in(dest)
- .with_context(|| format!("extracting {}", path.display()))?;
+ let action = validate_release_tar_entry(&path, entry_type)?;
+ budget.account(entry.header().size()?)?;
+ if action == ReleaseEntryAction::Extract {
+ entry
+ .unpack_in(dest)
+ .with_context(|| format!("extracting {}", path.display()))?;
+ }
}
Ok(())
}
@@ -422,6 +433,7 @@ fn extract_release_tar_gz(bytes: &[u8], dest: &Path) -> Result<()> {
fn extract_release_zip(bytes: &[u8], dest: &Path) -> Result<()> {
let cursor = Cursor::new(bytes);
let mut archive = zip::ZipArchive::new(cursor).context("opening release zip")?;
+ let mut budget = ReleaseArchiveBudget::default();
for i in 0..archive.len() {
let mut file = archive
.by_index(i)
@@ -435,7 +447,11 @@ fn extract_release_zip(bytes: &[u8], dest: &Path) -> Result<()> {
enclosed.display()
);
}
- validate_release_path(&enclosed, file.is_dir())?;
+ let action = validate_release_path(&enclosed, file.is_dir())?;
+ budget.account(file.size())?;
+ if action == ReleaseEntryAction::Ignore {
+ continue;
+ }
let out_path = dest.join(&enclosed);
if file.is_dir() {
fs::create_dir_all(&out_path)
@@ -457,7 +473,10 @@ fn is_regular_file(entry_type: tar::EntryType) -> bool {
entry_type.is_file() || entry_type == tar::EntryType::GNUSparse
}
-fn validate_release_tar_entry(path: &Path, entry_type: tar::EntryType) -> Result<()> {
+fn validate_release_tar_entry(
+ path: &Path,
+ entry_type: tar::EntryType,
+) -> Result<ReleaseEntryAction> {
if entry_type.is_symlink() || entry_type.is_hard_link() {
bail!(
"release archive contains unsupported link entry: {}",
@@ -473,24 +492,71 @@ fn validate_release_tar_entry(path: &Path, entry_type: tar::EntryType) -> Result
validate_release_path(path, entry_type.is_dir())
}
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum ReleaseEntryAction {
+ Extract,
+ Ignore,
+}
+
+#[derive(Default)]
+struct ReleaseArchiveBudget {
+ entries: usize,
+ expanded_bytes: u64,
+}
+
+impl ReleaseArchiveBudget {
+ fn account(&mut self, expanded_bytes: u64) -> Result<()> {
+ self.entries = self
+ .entries
+ .checked_add(1)
+ .context("release archive entry count overflow")?;
+ if self.entries > MAX_RELEASE_ARCHIVE_ENTRIES {
+ bail!("release archive contains more than {MAX_RELEASE_ARCHIVE_ENTRIES} entries");
+ }
+ self.expanded_bytes = self
+ .expanded_bytes
+ .checked_add(expanded_bytes)
+ .context("release archive expanded size overflow")?;
+ if self.expanded_bytes > MAX_RELEASE_EXPANDED_BYTES {
+ bail!("release archive expands past the {MAX_RELEASE_EXPANDED_BYTES}-byte limit");
+ }
+ Ok(())
+ }
+}
+
/// Shared path gates for tar and zip entries (allowlist + traversal).
-fn validate_release_path(path: &Path, is_dir: bool) -> Result<()> {
+fn validate_release_path(path: &Path, is_dir: bool) -> Result<ReleaseEntryAction> {
let normalized = normalize_release_entry_path(path)?;
// `tar -C dist/$artifact -czf … .` (release.yml) emits `./` as the
// archive root — empty after stripping CurDir; allow that directory only.
if normalized.as_os_str().is_empty() {
if is_dir {
- return Ok(());
+ return Ok(ReleaseEntryAction::Ignore);
}
bail!("release archive contains unsafe path: {}", path.display());
}
- if !is_allowed_release_path(&normalized) {
- bail!(
+ let key = release_path_key(&normalized);
+ let is_runtime_file = !is_dir && matches!(key.as_str(), "ai-memory" | "ai-memory.exe");
+ let is_hook_entry = (is_dir && key == HOOKS_DIR_NAME)
+ || key
+ .strip_prefix(HOOKS_DIR_NAME)
+ .is_some_and(|rest| rest.starts_with('/'));
+ let action = if is_runtime_file || is_hook_entry {
+ Some(ReleaseEntryAction::Extract)
+ } else if (is_dir && RELEASE_SUPPORT_DIRS.contains(&key.as_str()))
+ || (!is_dir && RELEASE_SUPPORT_FILES.contains(&key.as_str()))
+ {
+ Some(ReleaseEntryAction::Ignore)
+ } else {
+ None
+ };
+ match action {
+ Some(action) => Ok(action),
+ None => bail!(
"release archive contains unexpected path: {}",
path.display()
- );
+ ),
}
- Ok(())
}
/// Drop `Component::CurDir` (release tarballs use `./ai-memory`); reject
@@ -519,21 +585,37 @@ fn release_path_key(path: &Path) -> String {
.join("/")
}
-fn is_allowed_release_path(path: &Path) -> bool {
- let path_str = release_path_key(path);
- // Accept both release basenames so the zip extractor can be unit-tested
- // on Unix CI (archive root is always `ai-memory.exe` per release.yml).
- path_str == "ai-memory"
- || path_str == "ai-memory.exe"
- || path_str == HOOKS_DIR_NAME
- || path_str
- .strip_prefix(HOOKS_DIR_NAME)
- .is_some_and(|rest| rest.starts_with('/'))
- || path_str == "README.md"
- || path_str == "LICENSE"
- || path_str.starts_with("docs/")
- || path_str.starts_with("crates/")
-}
+/// Directory entries emitted by the Linux, macOS, and Windows release jobs.
+/// These are validated but not copied into the temporary self-upgrade tree.
+const RELEASE_SUPPORT_DIRS: &[&str] = &[
+ "crates",
+ "crates/ai-memory-cli",
+ "crates/ai-memory-cli/templates",
+ "docs",
+ "packaging",
+ "packaging/env",
+ "packaging/launchd",
+ "packaging/systemd",
+ "packaging/sysusers",
+ "packaging/tmpfiles",
+];
+
+/// Non-runtime files copied into release archives by `release.yml`. Keep this
+/// exact rather than admitting whole documentation or packaging subtrees.
+const RELEASE_SUPPORT_FILES: &[&str] = &[
+ "LICENSE",
+ "README.md",
+ "crates/ai-memory-cli/templates/config.default.toml",
+ "docs/install.md",
+ "docs/macos.md",
+ "docs/windows.md",
+ "packaging/env/ai-memory.env",
+ "packaging/launchd/com.github.akitaonrails.ai-memory.plist",
+ "packaging/systemd/ai-memory-user.service",
+ "packaging/systemd/ai-memory.service",
+ "packaging/sysusers/ai-memory.conf",
+ "packaging/tmpfiles/ai-memory.conf",
+];
fn replace_file_atomic(src: &Path, dest: &Path) -> Result<()> {
let tmp = dest.with_extension("new");
@@ -954,9 +1036,20 @@ mod tests {
}
#[test]
- fn allowlist_accepts_shipped_binary_basename() {
- assert!(is_allowed_release_path(Path::new(shipped_binary_name())));
- assert!(is_allowed_release_path(Path::new("hooks/claude-code/x.sh")));
+ fn allowlist_extracts_only_runtime_assets() -> Result<()> {
+ assert_eq!(
+ validate_release_path(Path::new(shipped_binary_name()), false)?,
+ ReleaseEntryAction::Extract
+ );
+ assert_eq!(
+ validate_release_path(Path::new("hooks/claude-code/x.sh"), false)?,
+ ReleaseEntryAction::Extract
+ );
+ assert_eq!(
+ validate_release_path(Path::new("docs/install.md"), false)?,
+ ReleaseEntryAction::Ignore
+ );
+ Ok(())
}
#[test]
@@ -1081,7 +1174,7 @@ mod tests {
#[test]
fn validate_rejects_path_traversal() -> Result<()> {
match validate_release_tar_entry(Path::new("../evil"), tar::EntryType::Regular) {
- Ok(()) => bail!("path traversal must fail"),
+ Ok(_) => bail!("path traversal must fail"),
Err(err) => assert!(err.to_string().contains("unsafe"), "{err}"),
}
Ok(())
@@ -1090,7 +1183,7 @@ mod tests {
#[test]
fn validate_rejects_unexpected_paths() -> Result<()> {
match validate_release_tar_entry(Path::new("etc/passwd"), tar::EntryType::Regular) {
- Ok(()) => bail!("unexpected path must fail"),
+ Ok(_) => bail!("unexpected path must fail"),
Err(err) => assert!(err.to_string().contains("unexpected"), "{err}"),
}
Ok(())
@@ -1098,8 +1191,44 @@ mod tests {
#[test]
fn validate_accepts_dot_slash_prefixed_binary() -> Result<()> {
- validate_release_tar_entry(Path::new("./ai-memory"), tar::EntryType::Regular)?;
- validate_release_tar_entry(Path::new("./"), tar::EntryType::Directory)?;
+ assert_eq!(
+ validate_release_tar_entry(Path::new("./ai-memory"), tar::EntryType::Regular)?,
+ ReleaseEntryAction::Extract
+ );
+ assert_eq!(
+ validate_release_tar_entry(Path::new("./"), tar::EntryType::Directory)?,
+ ReleaseEntryAction::Ignore
+ );
+ Ok(())
+ }
+
+ #[test]
+ fn release_workflow_support_assets_are_exact_and_ignored() -> Result<()> {
+ for directory in RELEASE_SUPPORT_DIRS {
+ assert_eq!(
+ validate_release_path(Path::new(directory), true)?,
+ ReleaseEntryAction::Ignore,
+ "support directory {directory}"
+ );
+ }
+ for file in RELEASE_SUPPORT_FILES {
+ assert_eq!(
+ validate_release_path(Path::new(file), false)?,
+ ReleaseEntryAction::Ignore,
+ "support file {file}"
+ );
+ }
+
+ for near_miss in [
+ "docs/unshipped.md",
+ "packaging/launchd/extra.plist",
+ "crates/ai-memory-cli/templates/extra.toml",
+ ] {
+ match validate_release_path(Path::new(near_miss), false) {
+ Ok(_) => bail!("unshipped support path {near_miss} must fail"),
+ Err(err) => assert!(err.to_string().contains("unexpected"), "{err}"),
+ }
+ }
Ok(())
}
@@ -1109,6 +1238,29 @@ mod tests {
fs::write(src.path().join(shipped_binary_name()), b"bin")?;
fs::create_dir_all(src.path().join("hooks/claude-code"))?;
fs::write(src.path().join("hooks/claude-code/x.sh"), b"#!/bin/sh")?;
+ for directory in [
+ "packaging/launchd",
+ "crates/ai-memory-cli/templates",
+ "docs",
+ ] {
+ fs::create_dir_all(src.path().join(directory))?;
+ }
+ for (path, body) in [
+ (
+ "packaging/launchd/com.github.akitaonrails.ai-memory.plist",
+ b"plist".as_slice(),
+ ),
+ (
+ "crates/ai-memory-cli/templates/config.default.toml",
+ b"config".as_slice(),
+ ),
+ ("docs/install.md", b"install".as_slice()),
+ ("docs/macos.md", b"macos".as_slice()),
+ ("README.md", b"readme".as_slice()),
+ ("LICENSE", b"license".as_slice()),
+ ] {
+ fs::write(src.path().join(path), body)?;
+ }
let out = tempfile::tempdir()?;
let archive = out.path().join("a.tar.gz");
// Same invocation as .github/workflows/release.yml. COPYFILE_DISABLE
@@ -1130,6 +1282,58 @@ mod tests {
"ai-memory-macos-aarch64.tar.gz",
)?;
assert!(dest.path().join(shipped_binary_name()).is_file());
+ assert!(dest.path().join("hooks/claude-code/x.sh").is_file());
+ assert!(!dest.path().join("docs/install.md").exists());
+ assert!(!dest.path().join("packaging").exists());
+ assert!(!dest.path().join("README.md").exists());
+ Ok(())
+ }
+
+ #[test]
+ fn release_archive_budget_rejects_entry_count_and_expanded_size() -> Result<()> {
+ let mut count_budget = ReleaseArchiveBudget::default();
+ for _ in 0..MAX_RELEASE_ARCHIVE_ENTRIES {
+ count_budget.account(0)?;
+ }
+ match count_budget.account(0) {
+ Ok(()) => bail!("entry count past the cap must fail"),
+ Err(err) => assert!(err.to_string().contains("entries"), "{err}"),
+ }
+
+ let mut size_budget = ReleaseArchiveBudget::default();
+ size_budget.account(MAX_RELEASE_EXPANDED_BYTES)?;
+ match size_budget.account(1) {
+ Ok(()) => bail!("expanded size past the cap must fail"),
+ Err(err) => assert!(err.to_string().contains("expands past"), "{err}"),
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn tar_extract_rejects_declared_expansion_past_limit() -> Result<()> {
+ let mut header = Header::new_gnu();
+ header.set_entry_type(tar::EntryType::Regular);
+ header.set_path("ai-memory")?;
+ header.set_size(MAX_RELEASE_EXPANDED_BYTES + 1);
+ header.set_mode(0o755);
+ header.set_cksum();
+
+ let mut tar_bytes = header.as_bytes().to_vec();
+ tar_bytes.extend_from_slice(&[0_u8; 1_024]);
+ let mut gz_bytes = Vec::new();
+ {
+ use flate2::Compression;
+ use flate2::write::GzEncoder;
+ let mut encoder = GzEncoder::new(&mut gz_bytes, Compression::fast());
+ encoder.write_all(&tar_bytes)?;
+ encoder.finish()?;
+ }
+ let dest = tempfile::tempdir()?;
+ match extract_release_archive(&gz_bytes, dest.path(), "ai-memory-linux-x86_64.tar.gz") {
+ Ok(()) => bail!("declared expanded size past the cap must fail"),
+ Err(err) => assert!(err.to_string().contains("expands past"), "{err:#}"),
+ }
+ assert!(!dest.path().join("ai-memory").exists());
Ok(())
}
@@ -1192,6 +1396,18 @@ mod tests {
("ai-memory.exe", b"win-bin"),
("hooks/", b""),
("hooks/claude-code/x.ps1", b"hook"),
+ ("crates/", b""),
+ ("crates/ai-memory-cli/", b""),
+ ("crates/ai-memory-cli/templates/", b""),
+ (
+ "crates/ai-memory-cli/templates/config.default.toml",
+ b"config",
+ ),
+ ("docs/", b""),
+ ("docs/install.md", b"install"),
+ ("docs/windows.md", b"windows"),
+ ("README.md", b"readme"),
+ ("LICENSE", b"license"),
])?;
let dest = tempfile::tempdir()?;
extract_release_archive(&bytes, dest.path(), "ai-memory-windows-x86_64.zip")?;
@@ -1200,6 +1416,9 @@ mod tests {
fs::read(dest.path().join("hooks/claude-code/x.ps1"))?,
b"hook"
);
+ assert!(!dest.path().join("docs").exists());
+ assert!(!dest.path().join("crates").exists());
+ assert!(!dest.path().join("README.md").exists());
Ok(())
}
diff --git a/docs/install.md b/docs/install.md
index dcdf80d8..dde4a627 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -2631,7 +2631,11 @@ The native path downloads the matching release archive
Windows) and its `.sha256` sidecar from GitHub Releases, verifies the
checksum, replaces the on-disk binary (and a sibling `hooks/` directory when
present), then re-stages hooks for agents already under the data-dir hooks
-tree. Windows uses rename-aside (`.exe` → `.old`, then promote `.new`) because
+tree. The archive's packaged service files, default config, and documentation
+are checked against the release workflow's exact layout but are not extracted
+during self-upgrade. Archives are capped at 4,096 entries and 512 MiB expanded,
+in addition to the 128 MiB response-body cap. Windows uses rename-aside
+(`.exe` → `.old`, then promote `.new`) because
a running image cannot be overwritten in place. It refuses Homebrew/AUR/`/usr`
installs (use the package manager), unwritable prefixes (for example Program
Files — download the zip manually), and in-container binaries (upgrade the
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index ac565a82..dd8ff2b7 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -56,6 +56,7 @@ boundary not yet built.
| 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 |
| 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 |