Skip to content

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

Rust

feat(hooks): attribute absolute file targets across projects

AkitaOnRailsf5882eeba2cd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0f76fa47..fd4bbeca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Added cross-project attribution for native lifecycle file-tool events whose
+ harness keeps reporting the parent session's cwd. A bounded, recognized
+ absolute target reroutes only when every path proves the same repository or
+ marker boundary; destination capture exclusions and server profiles are
+ resolved before the event is spooled. Relative, mixed-project, unsupported,
+ and arbitrary non-project paths keep the original route. (#932)
- Added `serve --enable-api` / `AI_MEMORY_ENABLE_API=true` to mount the
authenticated read-only `/api/v1` surface without the browser UI. Existing
`--enable-web` behavior is unchanged and still includes the API. Documented
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index 43e5d0e7..6d74a5bf 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -19,7 +19,8 @@ use std::time::Duration;
use ai_memory_core::{AgentKind, ManagedRunId, SessionId};
use ai_memory_hooks::capture_policy::metadata_only_body;
use ai_memory_hooks::{
- CaptureDisposition, CaptureMode, HookEvent, PolicyState, repository_admits_capture,
+ CaptureDisposition, CaptureMode, HookEvent, PolicyState, absolute_file_tool_paths,
+ repository_admits_capture,
};
use ai_memory_llm::OidcToken;
@@ -638,10 +639,31 @@ where
{
payload = serde_json::to_string(&json)?;
}
- let (policy_cwd, canonical_session_id) = hook_context(&args.agent, &json);
+ let (payload_cwd, canonical_session_id) = hook_context(&args.agent, &json);
+ let tool_event = is_tool_event(&args.event);
+ // Some harnesses keep a subagent's parent cwd in every payload even when
+ // a file tool operates in another checkout (#932). A recognized absolute
+ // target may select that checkout, but only when every path proves the
+ // same repository/marker boundary. This must precede capture policy and
+ // server-profile resolution so the destination's privacy and credentials
+ // remain authoritative.
+ let file_routing_cwd = payload_cwd.as_deref().and_then(|cwd| {
+ tool_event
+ .then(|| file_tool_routing_cwd(agent_kind, &json, cwd))
+ .flatten()
+ });
+ if let Some(cwd) = file_routing_cwd.as_deref()
+ && let Some(object) = json.as_object_mut()
+ {
+ // `HookEnvelope` deliberately gives the native body cwd precedence
+ // over the query fallback. Stamp the proven destination into that
+ // canonical field too, or a URL-only reroute would be cosmetic.
+ object.insert("cwd".into(), cwd.into());
+ payload = serde_json::to_string(&json)?;
+ }
+ let policy_cwd = file_routing_cwd.or(payload_cwd);
let inspection_cwd = policy_cwd.as_deref().map(lexical_capture_cwd);
let policy = policy_cwd.as_deref().map(capture_policy);
- let tool_event = is_tool_event(&args.event);
let decision = policy.as_ref().filter(|_| tool_event).map(|policy| {
policy.inspect(
AgentKind::from_wire(&args.agent),
@@ -765,10 +787,15 @@ where
}
}
- let qs = cwd_query_suffix(
- &args.agent,
- &json,
- args.project_strategy.and_then(|s| s.baked()),
+ let qs = policy_cwd.as_deref().map_or_else(
+ || {
+ cwd_query_suffix(
+ &args.agent,
+ &json,
+ args.project_strategy.and_then(|s| s.baked()),
+ )
+ },
+ |cwd| marker_query_suffix(cwd, args.project_strategy.and_then(|s| s.baked())),
);
let spool = hook_spool::spool_dir(&dd);
let session_qs = session_id_query_suffix(&dd, &args.agent, &args.event, &json);
@@ -1088,6 +1115,65 @@ fn hook_context(agent: &str, raw: &serde_json::Value) -> (Option<String>, Option
}
}
+#[derive(Debug, PartialEq, Eq)]
+struct FileRouteAnchor {
+ marker: Option<PathBuf>,
+ repository: Option<PathBuf>,
+}
+
+/// Find the existing directory that can establish routing for a file target.
+/// New files may name one or more not-yet-created parent directories.
+fn existing_target_dir(path: &Path) -> Option<PathBuf> {
+ let mut candidate = if path.is_dir() {
+ path.to_path_buf()
+ } else {
+ path.parent()?.to_path_buf()
+ };
+ loop {
+ if candidate.is_dir() {
+ return Some(candidate);
+ }
+ candidate = candidate.parent()?.to_path_buf();
+ }
+}
+
+fn file_route_anchor(cwd: &Path) -> FileRouteAnchor {
+ let cwd_text = cwd.to_string_lossy();
+ FileRouteAnchor {
+ marker: crate::marker::find_marker(&cwd_text),
+ repository: ai_memory_consolidate::discover_main_repo_root(cwd).ok(),
+ }
+}
+
+/// Pick a destination cwd only when absolute file-tool paths prove a single
+/// repository/marker boundary different from the payload cwd.
+fn file_tool_routing_cwd(
+ agent: AgentKind,
+ raw: &serde_json::Value,
+ payload_cwd: &str,
+) -> Option<String> {
+ let paths = absolute_file_tool_paths(agent, raw, payload_cwd)?;
+ let source_dir = existing_target_dir(Path::new(payload_cwd))?;
+ let source_anchor = file_route_anchor(&source_dir);
+ let mut selected: Option<(FileRouteAnchor, PathBuf)> = None;
+ for path in paths {
+ let dir = existing_target_dir(Path::new(&path))?;
+ let anchor = file_route_anchor(&dir);
+ // An arbitrary absolute path is not a project and must not mint a new
+ // scope merely because a file tool happened to inspect it.
+ if anchor.marker.is_none() && anchor.repository.is_none() {
+ return None;
+ }
+ match &selected {
+ Some((expected, _)) if *expected != anchor => return None,
+ Some(_) => {}
+ None => selected = Some((anchor, dir)),
+ }
+ }
+ let (target_anchor, dir) = selected?;
+ (target_anchor != source_anchor).then(|| dir.to_string_lossy().into_owned())
+}
+
/// Where one event is delivered (#992).
#[derive(Debug)]
enum HookRoute {
@@ -2325,6 +2411,170 @@ mod tests {
assert_eq!(hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)), 0);
}
+ #[tokio::test]
+ async fn absolute_file_target_uses_destination_scope_and_capture_policy() {
+ let tmp = tempfile::tempdir().unwrap();
+ let source = tmp.path().join("source");
+ let destination = tmp.path().join("destination");
+ std::fs::create_dir_all(&destination).unwrap();
+ std::fs::create_dir_all(&source).unwrap();
+ std::fs::write(
+ source.join(".ai-memory.toml"),
+ "workspace = \"shared\"\nproject = \"source\"\n",
+ )
+ .unwrap();
+ std::fs::write(
+ destination.join(".ai-memory.toml"),
+ "workspace = \"shared\"\nproject = \"destination\"\n[capture]\nignore_paths = [\"secret/**\"]\n",
+ )
+ .unwrap();
+ let data_dir = tmp.path().join("data");
+
+ let mut args = devin_hook_args("post-tool-use");
+ args.agent = "claude-code".into();
+ let excluded = serde_json::json!({
+ "session_id": "cross-project",
+ "cwd": source,
+ "tool_name": "Edit",
+ "tool_input": {"file_path": destination.join("secret/private.txt")},
+ "tool_response": {"content": "SENTINEL_MUST_NOT_BE_SPOOLED"}
+ });
+ run_with_payload(
+ Some(data_dir.clone()),
+ args,
+ excluded.to_string(),
+ &mut Vec::new(),
+ |_, _| panic!("a dropped tool event must not start a drainer"),
+ )
+ .await
+ .unwrap();
+ let spool = hook_spool::spool_dir(&data_dir);
+ assert_eq!(hook_spool::spool_len(&spool), 0);
+
+ let mut args = devin_hook_args("post-tool-use");
+ args.agent = "claude-code".into();
+ let public = serde_json::json!({
+ "session_id": "cross-project",
+ "cwd": source,
+ "tool_name": "Edit",
+ "tool_input": {"file_path": destination.join("public.txt")},
+ "tool_response": {"content": "public"}
+ });
+ run_with_payload(
+ Some(data_dir),
+ args,
+ public.to_string(),
+ &mut Vec::new(),
+ |_, _| panic!("a tool event below the threshold must only spool"),
+ )
+ .await
+ .unwrap();
+ let entries = read_spooled_entries(&spool);
+ assert_eq!(entries.len(), 1);
+ assert_eq!(query_param(&entries[0].url, "workspace"), Some("shared"));
+ assert_eq!(query_param(&entries[0].url, "project"), Some("destination"));
+ assert_eq!(
+ query_param(&entries[0].url, "cwd"),
+ Some(url_encode(destination.to_str().unwrap()).as_str())
+ );
+ let body: serde_json::Value = serde_json::from_str(&entries[0].body).unwrap();
+ assert_eq!(body["cwd"], destination.to_string_lossy().as_ref());
+ }
+
+ #[tokio::test]
+ async fn absolute_file_target_cannot_escape_a_destination_server_profile() {
+ let tmp = tempfile::tempdir().unwrap();
+ let source = tmp.path().join("source");
+ let destination = tmp.path().join("destination");
+ std::fs::create_dir_all(&source).unwrap();
+ std::fs::create_dir_all(&destination).unwrap();
+ std::fs::write(
+ source.join(".ai-memory.toml"),
+ "workspace = \"shared\"\nproject = \"source\"\n",
+ )
+ .unwrap();
+ std::fs::write(
+ destination.join(".ai-memory.toml"),
+ "server = \"unregistered\"\nworkspace = \"shared\"\nproject = \"destination\"\n",
+ )
+ .unwrap();
+ let data_dir = tmp.path().join("data");
+ let mut args = devin_hook_args("post-tool-use");
+ args.agent = "claude-code".into();
+ let raw = serde_json::json!({
+ "session_id": "cross-profile",
+ "cwd": source,
+ "tool_name": "Edit",
+ "tool_input": {"file_path": destination.join("public.txt")}
+ });
+
+ run_with_payload(
+ Some(data_dir.clone()),
+ args,
+ raw.to_string(),
+ &mut Vec::new(),
+ |_, _| panic!("a refused destination route must not start a drainer"),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)),
+ 0,
+ "the event must not fall back to the source repository's server"
+ );
+ }
+
+ #[test]
+ fn file_target_routing_refuses_relative_external_and_mixed_project_paths() {
+ let tmp = tempfile::tempdir().unwrap();
+ let source = tmp.path().join("source");
+ let destination = tmp.path().join("destination");
+ std::fs::create_dir_all(&source).unwrap();
+ std::fs::create_dir_all(&destination).unwrap();
+ std::fs::write(source.join(".ai-memory.toml"), "project = \"source\"\n").unwrap();
+ std::fs::write(
+ destination.join(".ai-memory.toml"),
+ "project = \"destination\"\n",
+ )
+ .unwrap();
+ let cwd = source.to_str().unwrap();
+ let relative = serde_json::json!({
+ "tool_name": "Edit",
+ "tool_input": {"file_path": "../destination/file.txt"}
+ });
+ assert_eq!(
+ file_tool_routing_cwd(AgentKind::ClaudeCode, &relative, cwd),
+ None,
+ "a relative path cannot independently prove a destination"
+ );
+
+ let external_dir = tmp.path().join("not-a-project");
+ std::fs::create_dir_all(&external_dir).unwrap();
+ let external = serde_json::json!({
+ "tool_name": "Edit",
+ "tool_input": {"file_path": external_dir.join("file.txt")}
+ });
+ assert_eq!(
+ file_tool_routing_cwd(AgentKind::ClaudeCode, &external, cwd),
+ None,
+ "an arbitrary absolute path must not mint a project"
+ );
+
+ let mixed = serde_json::json!({
+ "tool_name": "read",
+ "tool_input": {"paths": [
+ source.join("one.txt"),
+ destination.join("two.txt")
+ ]}
+ });
+ assert_eq!(
+ file_tool_routing_cwd(AgentKind::ClaudeCode, &mixed, cwd),
+ None,
+ "one event cannot be attributed to two projects"
+ );
+ }
+
#[tokio::test]
async fn shell_command_reading_an_ignored_path_is_dropped_before_spool() {
for (command, spooled) in [("cat ./secret/*.md | head", 0), ("cat public/readme.md", 1)] {
diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rs
index 851585f2..1c6ddb87 100644
--- a/crates/ai-memory-hooks/src/capture_policy.rs
+++ b/crates/ai-memory-hooks/src/capture_policy.rs
@@ -875,6 +875,34 @@ fn extract_paths(name: &str, args: &Value) -> Option<Vec<String>> {
}))
.then_some(paths)
}
+
+/// Return the bounded, normalized absolute paths named by a recognized file
+/// tool call.
+///
+/// Native hook clients use this only to notice a file operation that targets
+/// another checkout while the harness keeps reporting the parent session's
+/// cwd. Relative paths are intentionally excluded: joining them to any cwd
+/// other than the payload's would be ambiguous, and they cannot independently
+/// prove a cross-project target. Unknown schemas and mixed/oversized inputs
+/// fail closed with `None`, matching capture-policy extraction.
+#[must_use]
+pub fn absolute_file_tool_paths(agent: AgentKind, raw: &Value, cwd: &str) -> Option<Vec<String>> {
+ let extracted = extract(agent, raw);
+ if extracted.family != ToolFamily::File {
+ return None;
+ }
+ let paths = extracted.paths?;
+ paths
+ .iter()
+ .map(|path| {
+ is_absolute(path)
+ .then(|| normalize_candidate(path, cwd))
+ .flatten()
+ .map(|candidate| candidate.path)
+ })
+ .collect()
+}
+
fn direct_paths(object: &Map<String, Value>) -> Option<Vec<String>> {
let mut paths = Vec::new();
for key in [
diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rs
index 12f99e3e..9383a252 100644
--- a/crates/ai-memory-hooks/src/lib.rs
+++ b/crates/ai-memory-hooks/src/lib.rs
@@ -47,7 +47,7 @@ pub use assistant_capture::{
pub use capture_policy::{
CaptureConfig, CaptureDecision, CaptureDisposition, CaptureMode, CapturePolicy,
CaptureProtocol, CaptureSource, ExtractionState, PolicyState, ToolFamily,
- describe_invalid_capture_config, repository_admits_capture,
+ absolute_file_tool_paths, describe_invalid_capture_config, repository_admits_capture,
};
pub use payload::{
HookEnvelope, HookEvent, NOTIFICATION_EXCERPT_MAX_BYTES, POST_COMPACTION_EXCERPT_MAX_BYTES,
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 2173d9cd..92d01eb8 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -236,6 +236,14 @@ normalises them to exactly one of these `ObservationKind` values:
| `session-end` | Agent session ended; summary/handoff path may run. |
| `other` | Unknown or unsupported hook event. |
+Native hook clients correct one otherwise invisible cross-project case before
+spooling: if a recognized file-tool payload names only absolute paths in one
+other repository/marker boundary, that destination becomes the event cwd.
+Destination capture policy, server profile, and scope therefore travel
+together. Relative, mixed-project, unsupported, and non-project targets keep
+the harness cwd. Session identity and compiled-session ownership do not move;
+only the raw observations are attributed to the touched project (#932).
+
Antigravity CLI has no native SessionStart event. Its `PreInvocation` hook
fires before every model call, so the bridge maps only the documented
`invocationNum = 0` payload to `session-start`; later invocations are ignored
diff --git a/docs/marker-file.md b/docs/marker-file.md
index e74852ee..f34a7105 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -670,6 +670,19 @@ Two guarantees hold in **both** modes:
Session-creating events are unaffected in both modes: opening a session in a
plain non-git folder still names the project after that folder.
+Some harnesses keep reporting the parent session's cwd when a subagent uses a
+file tool in another checkout. Native `ai-memory hook` commands compensate for
+that case before applying `follow-cwd` or `sticky`: a fixture-backed file-tool
+schema with absolute target paths is routed from the target when every path
+proves the same repository or marker boundary. The destination's capture
+policy and `server` profile are authoritative, so a cross-project call cannot
+use the source repository's policy or credentials. Relative paths,
+mixed-project calls, unknown schemas, and absolute paths outside a recognized
+repository/marker keep the payload cwd. Free-form shell commands are not
+reinterpreted as project routing instructions. This changes raw observation
+attribution only; the session row and its compiled session page remain in the
+project where the session began.
+
Independently of this setting, under `project_strategy = "repo-root"` a
mid-session event whose cwd is outside any git repo *and* any marker (agent
scratch directories, `/tmp`, data folders) already inherits the session's
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 08116adc..ea05ed5b 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -58,6 +58,7 @@ boundary not yet built.
| 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 | `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); `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) | 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 |
+| 11g | Cross-project file attribution cannot bypass destination capture or server routing (#932) | `ai-memory-hooks/src/capture_policy.rs` `absolute_file_tool_paths` accepts only bounded, recognized, absolute file-tool candidates; `ai-memory-cli/src/commands/hook.rs` `file_tool_routing_cwd` requires every path to prove the same repository/marker boundary and resolves that destination before capture policy, 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` | STRONG for native `ai-memory hook`; generated and compatibility hooks retain cwd-only routing |
| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls | 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 |