Skip to content

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

Rust

feat(hooks): inspect capture policy and scope

Éverton Toffanetto24f4246a63e5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4ce62d08..9b49b6fb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- Added scope and policy preflight to `ai-memory hook --check-capture`, including
+ event eligibility, sanitized routing hints and server-remapping information.
+ Partial scope, excluded events, rejected profiles and oversized hints refuse
+ capture. Inspection neither ingests events nor claims handoffs. (#1010)
+
## [2.5.2] - 2026-10-01
### Added
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index db657a09..43e5d0e7 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -29,9 +29,9 @@ use crate::server_profiles::{self, ProfileName, Rejection, ResolvedServer};
use sha2::{Digest as _, Sha256};
use super::hook_capture::{
- build_client, canonical_context, capture_policy, extract_cwd, get_handoff, marker_query_suffix,
- marker_query_suffix_without_briefing, marker_requests_briefing, resolve_cwd_with_fallbacks,
- url_encode,
+ build_client, canonical_context, capture_policy, extract_cwd, get_handoff, hook_scope,
+ marker_query_suffix, marker_query_suffix_without_briefing, marker_requests_briefing,
+ resolve_cwd_with_fallbacks, url_encode,
};
use super::hook_drain_process;
use super::hook_spool;
@@ -597,13 +597,13 @@ where
// fires before every model call; invocation zero is the only startup
// boundary. Fail closed when the documented counter is absent so a later
// invocation can never consume a handoff intended for the next session.
- if !should_process_hook_event(agent_kind, hook_event, &json)
- || is_redundant_cursor_copy(
+ let event_admits_capture = should_process_hook_event(agent_kind, hook_event, &json)
+ && !is_redundant_cursor_copy(
agent_kind,
&json,
super::install_hooks::cursor_native_hooks_installed,
- )
- {
+ );
+ if !event_admits_capture && !args.check_capture {
write_success_response(stdout, agent_kind, hook_event)?;
return Ok(());
}
@@ -665,10 +665,34 @@ where
let admits_capture = repository_admits_capture(capture_mode, marker_present);
if args.check_capture {
let protocol = decision.as_ref().map(|decision| decision.protocol());
+ let scope = policy_cwd.as_deref().map(|cwd| {
+ hook_scope(
+ cwd,
+ args.project_strategy
+ .and_then(crate::cli::ProjectStrategyArg::baked),
+ )
+ });
+ let scope_resolution = match scope.as_ref() {
+ None => "unavailable",
+ Some(scope) if !scope.is_inspectable() => "unavailable",
+ Some(scope) if scope.is_partial() => "partial",
+ Some(scope) if scope.is_explicit() => "explicit",
+ Some(_) => "server-derived",
+ };
+ let policy_admits_capture = admits_capture
+ && event_admits_capture
+ && !matches!(route, HookRoute::Rejected { .. })
+ && scope_resolution != "partial"
+ && scope_resolution != "unavailable"
+ && protocol.is_none_or(|p| p.disposition() != CaptureDisposition::Drop);
let mut output = serde_json::json!({
"capture_mode": capture_mode,
"marker_present": marker_present,
"admits_capture": admits_capture && !external_capture,
+ "policy_admits_capture": policy_admits_capture,
+ "event_admits_capture": event_admits_capture,
+ "scope": scope,
+ "scope_resolution": scope_resolution,
"version": protocol.map_or(1, |protocol| protocol.version()),
"policy_state": protocol.map_or(PolicyState::Inactive, |protocol| protocol.policy_state()),
"tool_family": protocol.map_or(ai_memory_hooks::ToolFamily::Unknown, |protocol| protocol.tool_family()),
@@ -2585,10 +2609,14 @@ mod tests {
"admits_capture",
"capture_mode",
"disposition",
+ "event_admits_capture",
"extraction_state",
"marker_present",
"path_count",
+ "policy_admits_capture",
"policy_state",
+ "scope",
+ "scope_resolution",
"server_profile",
"server_resolution",
"tool_family",
@@ -2599,6 +2627,123 @@ mod tests {
assert!(!String::from_utf8(stdout).unwrap().contains("SENTINEL"));
}
+ #[tokio::test]
+ async fn check_capture_refuses_partial_scope_and_excluded_content() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data_dir = tmp.path().join("data");
+ let marker = tmp.path().join(".ai-memory.toml");
+ for (declaration, path, admits, resolution) in [
+ ("workspace = \"team\"\n", "public.txt", false, "partial"),
+ (
+ "workspace = \"team\"\nproject = \"app\"\n",
+ "secret/token.txt",
+ false,
+ "explicit",
+ ),
+ (
+ "workspace = \"team\"\nproject = \"app\"\n",
+ "public.txt",
+ true,
+ "explicit",
+ ),
+ ] {
+ std::fs::write(
+ &marker,
+ format!("{declaration}[capture]\nignore_paths = [\"secret/**\"]\n"),
+ )
+ .unwrap();
+ let mut args = devin_hook_args("post-tool-use");
+ args.check_capture = true;
+ let mut stdout = Vec::new();
+ run_with_payload(
+ Some(data_dir.clone()), args,
+ serde_json::json!({"cwd":tmp.path(), "tool_name":"Edit", "tool_input":{"path":path,"content":"PRIVATE_CONTENT_SENTINEL"}}).to_string(),
+ &mut stdout,
+ |_, _| Err(std::io::Error::other("inspection must not spawn")),
+ ).await.unwrap();
+ let report: serde_json::Value = serde_json::from_slice(&stdout).unwrap();
+ assert_eq!(report["policy_admits_capture"], admits, "{report}");
+ assert_eq!(report["scope_resolution"], resolution);
+ assert_eq!(report["scope"]["workspace"], "team");
+ let printed = String::from_utf8(stdout).unwrap();
+ assert!(!printed.contains("PRIVATE_CONTENT_SENTINEL"));
+ assert!(!printed.contains("token.txt"));
+ assert!(!data_dir.exists());
+ }
+ }
+
+ #[tokio::test]
+ async fn check_capture_bounds_marker_hints_and_refuses_oversized_scope() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data_dir = tmp.path().join("data");
+ for (workspace, identity, admits) in [
+ ("x".repeat(513), "app".to_owned(), false),
+ ("team".to_owned(), "y".repeat(513), false),
+ ("team".to_owned(), "y".repeat(512), true),
+ ] {
+ std::fs::write(
+ tmp.path().join(".ai-memory.toml"),
+ format!(
+ "workspace = \"{workspace}\"\nproject = \"app\"\nidentity = \"{identity}\"\n"
+ ),
+ )
+ .unwrap();
+ let mut args = devin_hook_args("post-tool-use");
+ args.check_capture = true;
+ let mut stdout = Vec::new();
+ run_with_payload(
+ Some(data_dir.clone()), args,
+ serde_json::json!({"cwd":tmp.path(), "tool_name":"Edit", "tool_input":{"path":"public.txt"}}).to_string(),
+ &mut stdout,
+ |_, _| Err(std::io::Error::other("inspection must not spawn")),
+ ).await.unwrap();
+ let report: serde_json::Value = serde_json::from_slice(&stdout).unwrap();
+ assert_eq!(report["policy_admits_capture"], admits, "{report}");
+ assert_eq!(
+ report["scope_resolution"],
+ if admits { "explicit" } else { "unavailable" }
+ );
+ assert_eq!(report["scope"]["project"], "app");
+ let printed = String::from_utf8(stdout).unwrap();
+ for (field, value) in [("workspace", &workspace), ("identity", &identity)] {
+ if value.len() > 512 {
+ assert!(report["scope"][field].is_null(), "{report}");
+ assert!(!printed.contains(value));
+ } else {
+ assert_eq!(report["scope"][field], value.as_str());
+ }
+ }
+ assert!(!data_dir.exists());
+ // Inspection bounds do not change the native routing contract.
+ let suffix = marker_query_suffix(tmp.path().to_str().unwrap(), None);
+ assert!(suffix.contains(&workspace));
+ assert!(suffix.contains(&format!("&identity={identity}")));
+ }
+ }
+
+ #[tokio::test]
+ async fn check_capture_reports_rejected_lifecycle_without_delivery() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data_dir = tmp.path().join("data");
+ let mut args = devin_hook_args("session-start");
+ args.agent = "antigravity-cli".into();
+ args.check_capture = true;
+ let mut stdout = Vec::new();
+ run_with_payload(
+ Some(data_dir.clone()),
+ args,
+ serde_json::json!({"cwd":tmp.path(),"invocationNum":4}).to_string(),
+ &mut stdout,
+ |_, _| Err(std::io::Error::other("inspection must not spawn")),
+ )
+ .await
+ .unwrap();
+ let report: serde_json::Value = serde_json::from_slice(&stdout).unwrap();
+ assert_eq!(report["event_admits_capture"], false);
+ assert_eq!(report["policy_admits_capture"], false);
+ assert!(!data_dir.exists());
+ }
+
#[tokio::test]
async fn inactive_preserves_bytes_and_active_keep_adds_protocol() {
let tmp = tempfile::tempdir().unwrap();
@@ -3156,6 +3301,7 @@ mod tests {
let stdout = run_prompt(&data_dir, args, cwd).await;
let output: serde_json::Value = serde_json::from_slice(&stdout).unwrap();
assert_eq!(output["server_resolution"], resolution, "{}", cwd.display());
+ assert_eq!(output["policy_admits_capture"], resolution == "marker");
let printed = String::from_utf8(stdout).unwrap();
for secret in ["tok-", "https://", &*tmp.path().to_string_lossy()] {
assert!(!printed.contains(secret), "{printed}");
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index 98ce8413..d380a35f 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -251,24 +251,135 @@ pub fn marker_requests_briefing(cwd: &str) -> bool {
.is_some_and(|value| is_truthy(&value))
}
+/// Host-side routing hints sent with native lifecycle events.
+/// Missing names are left to the server; this inspection creates no scope.
+#[derive(Debug, serde::Serialize)]
+pub struct HookScope {
+ #[serde(serialize_with = "serialize_scope_hint")]
+ workspace: Option<String>,
+ #[serde(serialize_with = "serialize_scope_hint")]
+ project: Option<String>,
+ project_src: Option<&'static str>,
+ #[serde(serialize_with = "serialize_scope_hint")]
+ project_strategy: Option<String>,
+ #[serde(serialize_with = "serialize_scope_hint")]
+ identity: Option<String>,
+ identity_src: Option<&'static str>,
+ server_may_remap: bool,
+}
+
+const MAX_SCOPE_HINT_BYTES: usize = 512;
+
+fn serialize_scope_hint<S: serde::Serializer>(
+ value: &Option<String>,
+ serializer: S,
+) -> Result<S::Ok, S::Error> {
+ serde::Serialize::serialize(
+ &value
+ .as_deref()
+ .filter(|value| value.len() <= MAX_SCOPE_HINT_BYTES),
+ serializer,
+ )
+}
+
+impl HookScope {
+ /// Whether all routing hints fit the bounded inspection response.
+ #[must_use]
+ pub fn is_inspectable(&self) -> bool {
+ [
+ &self.workspace,
+ &self.project,
+ &self.project_strategy,
+ &self.identity,
+ ]
+ .into_iter()
+ .all(|value| {
+ value
+ .as_ref()
+ .is_none_or(|value| value.len() <= MAX_SCOPE_HINT_BYTES)
+ })
+ }
+
+ /// Whether only one name was explicitly declared in the marker.
+ #[must_use]
+ pub fn is_partial(&self) -> bool {
+ (self.workspace.is_some() || self.project_src == Some("marker")) && !self.is_explicit()
+ }
+
+ /// Whether both names were resolved on the host.
+ #[must_use]
+ pub fn is_explicit(&self) -> bool {
+ self.workspace
+ .as_deref()
+ .is_some_and(|v| !v.trim().is_empty())
+ && self
+ .project
+ .as_deref()
+ .is_some_and(|v| !v.trim().is_empty())
+ }
+}
+
+/// Inspect the same marker, worktree and repository identity as hook routing.
+#[must_use]
+pub fn hook_scope(cwd: &str, default_strategy: Option<&str>) -> HookScope {
+ let marker = find_settings_marker(cwd);
+ hook_scope_from_marker(cwd, default_strategy, marker.as_deref())
+}
+
+fn hook_scope_from_marker(
+ cwd: &str,
+ default_strategy: Option<&str>,
+ marker: Option<&Path>,
+) -> HookScope {
+ let mut workspace = None;
+ let mut project = None;
+ let mut strategy = None;
+ let mut explicit_identity = None;
+ if let Some(marker) = marker {
+ workspace = parse_toml_key(marker, "workspace");
+ project = parse_toml_key(marker, "project");
+ strategy = parse_toml_key(marker, "project_strategy");
+ explicit_identity = parse_toml_key(marker, "identity");
+ }
+ let mut project_src = project.as_ref().map(|_| "marker");
+ let identity = repository_identity(cwd, explicit_identity.as_deref(), project.as_deref());
+ if strategy.is_none() {
+ strategy = default_strategy.map(str::to_owned);
+ }
+ if project.is_none() && matches!(strategy.as_deref(), Some("repo-root" | "repo_root")) {
+ project = repo_root_project(cwd);
+ project_src = project.as_ref().map(|_| "repo-root");
+ }
+ let (identity, identity_src) = match identity {
+ Some(identity) => (Some(identity.identity), Some(identity.source.as_str())),
+ None => (None, None),
+ };
+ let server_may_remap = project_src != Some("marker") || identity.is_some();
+ HookScope {
+ workspace,
+ project,
+ project_src,
+ project_strategy: strategy,
+ identity,
+ identity_src,
+ server_may_remap,
+ }
+}
+
fn marker_query_suffix_impl(
cwd: &str,
default_strategy: Option<&str>,
include_briefing: bool,
) -> String {
let mut qs = format!("&cwd={}", url_encode(cwd));
- let (mut workspace, mut project, mut strategy, mut drop_subagent, mut default_global) =
- (None, None, None, None, None);
+ let marker = find_settings_marker(cwd);
+ let scope = hook_scope_from_marker(cwd, default_strategy, marker.as_deref());
+ let (mut drop_subagent, mut default_global) = (None, None);
let (mut briefing, mut briefing_budget) = (None, None);
- let mut explicit_identity = None;
// The nearest marker that declares more than `[capture]` (#668): a
// nested capture-only marker (e.g. one that only sets `ignore_paths`)
// must not shadow an outer marker's workspace/project/briefing/etc.
- if let Some(marker) = find_settings_marker(cwd) {
- workspace = parse_toml_key(&marker, "workspace");
- project = parse_toml_key(&marker, "project");
- explicit_identity = parse_toml_key(&marker, "identity");
- strategy = parse_toml_key(&marker, "project_strategy");
+ if let Some(marker) = marker {
drop_subagent = parse_toml_key(&marker, "drop_subagent_captures");
// `[recall] default_global = true` (or top-level; quoted or bare) —
// a meta-repo opts every default-scoped read into a global search.
@@ -279,38 +390,23 @@ fn marker_query_suffix_impl(
briefing = parse_toml_flag(&marker, "inject_on_session_start");
briefing_budget = parse_toml_flag(&marker, "max_chars");
}
- // Provenance of `project`, forwarded as `project_src` so the server can
- // tell a deliberate marker rescope from a host-derived repo-root name.
- // Only the latter may yield to session-sticky attribution (#394).
- let mut project_src = project.as_ref().map(|_| "marker");
- // Resolved before repo-root can fill `project` below: a repo-root name is
- // an inference, while the chain's `manifest` rung means a name somebody
- // wrote in the marker.
- let identity = repository_identity(cwd, explicit_identity.as_deref(), project.as_deref());
- if strategy.is_none() {
- strategy = default_strategy.map(str::to_owned);
- }
- if project.is_none() && matches!(strategy.as_deref(), Some("repo-root" | "repo_root")) {
- project = repo_root_project(cwd);
- project_src = project.as_ref().map(|_| "repo-root");
- }
- if let Some(val) = workspace {
+ if let Some(val) = scope.workspace {
qs.push_str(&format!("&workspace={}", url_encode(&val)));
}
- if let Some(val) = project {
+ if let Some(val) = scope.project {
qs.push_str(&format!("&project={}", url_encode(&val)));
}
- if let Some(val) = project_src {
+ if let Some(val) = scope.project_src {
qs.push_str(&format!("&project_src={val}"));
}
- if let Some(val) = strategy {
+ if let Some(val) = scope.project_strategy {
qs.push_str(&format!("&project_strategy={}", url_encode(&val)));
}
- if let Some(identity) = identity {
+ if let (Some(identity), Some(source)) = (scope.identity, scope.identity_src) {
qs.push_str(&format!(
"&identity={}&identity_src={}",
- url_encode(&identity.identity),
- identity.source.as_str()
+ url_encode(&identity),
+ source
));
}
// Per-project `drop_subagent_captures` opt-in: forward the marker's value as
@@ -954,6 +1050,11 @@ mod tests {
"{qs}"
);
assert!(!qs.contains("s3cret"), "{qs}");
+ let scope =
+ serde_json::to_value(hook_scope(origin_only.path().to_str().unwrap(), None)).unwrap();
+ assert_eq!(scope["identity"], "git.example.test/fork/api");
+ assert_eq!(scope["identity_src"], "git_remote");
+ assert!(!scope.to_string().contains("s3cret"));
}
/// A declared `project` outranks the remote and routes by name, so nothing
@@ -1176,7 +1277,7 @@ drop_subagent_captures = "true"
if !std::process::Command::new("git")
.arg("-C")
.arg(&repo)
- .args(["worktree", "add", "-q"])
+ .args(["worktree", "add", "-q", "-b", "feat/worktree-inspection"])
.arg(&wt)
.status()
.unwrap()
@@ -1194,6 +1295,13 @@ drop_subagent_captures = "true"
assert!(qs.contains("&workspace=oss"), "{qs}");
assert!(qs.contains("&project=acme-api"), "{qs}");
assert!(qs.contains("&project_strategy=repo-root"), "{qs}");
+ let scope = hook_scope(wt.to_str().unwrap(), None);
+ assert!(scope.is_explicit());
+ let scope = serde_json::to_value(scope).unwrap();
+ assert_eq!(scope["workspace"], "oss");
+ assert_eq!(scope["project"], "acme-api");
+ assert_eq!(scope["project_src"], "repo-root");
+ assert_eq!(scope["server_may_remap"], true);
}
// ── install-time default strategy (#128), no marker required ──────
diff --git a/crates/ai-memory-cli/tests/suite/external_capture.rs b/crates/ai-memory-cli/tests/suite/external_capture.rs
index 6ebca1e1..256190a2 100644
--- a/crates/ai-memory-cli/tests/suite/external_capture.rs
+++ b/crates/ai-memory-cli/tests/suite/external_capture.rs
@@ -93,6 +93,11 @@ fn external_devin_end_still_clears_native_identity() {
#[test]
fn capture_inspection_reports_external_ownership_without_side_effects() {
let tmp = tempfile::tempdir().unwrap().keep();
+ std::fs::write(
+ tmp.join(".ai-memory.toml"),
+ "workspace = \"demo\"\nproject = \"app\"\n",
+ )
+ .unwrap();
let output = hook(
tmp.as_path(),
"claude-code",
@@ -103,6 +108,11 @@ fn capture_inspection_reports_external_ownership_without_side_effects() {
let report: Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(report["external_capture"], true);
assert_eq!(report["admits_capture"], false);
+ assert_eq!(report["policy_admits_capture"], true);
+ assert_eq!(report["scope"]["workspace"], "demo");
+ assert_eq!(report["scope"]["project"], "app");
+ assert_eq!(report["scope_resolution"], "explicit");
+ assert!(!String::from_utf8_lossy(&output.stdout).contains("orchestrator-a"));
assert!(!tmp.as_path().join("data").exists());
}
diff --git a/docs/external-lifecycle.md b/docs/external-lifecycle.md
index b085d80b..30335e20 100644
--- a/docs/external-lifecycle.md
+++ b/docs/external-lifecycle.md
@@ -34,7 +34,7 @@ Older installations do not understand this context.
| Supported handoff, briefing and inbox-notice delivery | Preserved |
| Native identity used by handoff/session-aware MCP | Preserved |
| MCP recall and deliberate writes | Unchanged |
-| Existing repository capture policy | Unchanged; an opted-out repository stays opted out |
+| Repository capture policy | The producer checks and applies it before queueing each event |
Claude Code receives context through SessionStart. Kimi Code receives it through
UserPromptSubmit because it discards SessionStart output. The same existing
@@ -53,6 +53,16 @@ installed ai-memory integrations; it must manage finer capture ownership itself.
`admits_capture: false` when this context is active. It performs no ingestion or
handoff delivery. The producer namespace itself is not printed or authenticated.
+Use `policy_admits_capture` for the external producer's preflight: it ignores
+capture ownership but checks repository policy, event eligibility, exclusions,
+scope completeness and server-profile resolution. Partial scope and a rejected
+profile return `false`. Apply `disposition`, including metadata-only stripping,
+before queueing. `scope` contains sanitized local routing hints of at most 512
+bytes each; oversized hints are omitted and preflight fails closed.
+`scope_resolution` distinguishes explicit, partial, server-derived and
+unavailable scope. `server_may_remap` warns that the server may choose different
+coordinates. Native routing values are unaffected by the inspection bound.
+
## Reuse the public event contract
For a live harness, send its actual wire `agent` (such as `claude-code` or `codex`)
diff --git a/docs/marker-file.md b/docs/marker-file.md
index aac8cbda..6b1c6d88 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -438,6 +438,23 @@ printf '%s\n' '{"session_id":"demo","cwd":"/example/workspace","tool_name":"Edit
--server-url http://127.0.0.1:49374 --check-capture
```
+The same inspection also reports sanitized `scope` hints (`workspace`, `project`,
+`project_src`, `project_strategy`, `identity`, `identity_src`,
+`server_may_remap`) and `scope_resolution`. These are local hints, not a
+server lookup: inspection creates no project and may report server-derived
+coordinates that the server later remaps. Partial marker scope fails closed.
+`event_admits_capture` reports lifecycle eligibility. External producers use
+`policy_admits_capture`, which also checks exclusions and server-profile
+resolution while ignoring `AI_MEMORY_CAPTURE_OWNER`. The existing
+`admits_capture` field still reports native capture admission. Each scope hint
+is limited to 512 bytes. Oversized names are omitted (`null`), report
+`scope_resolution: "unavailable"` and refuse producer admission; native
+routing remains unchanged.
+The native hook can derive a project for a marker that declares only
+`workspace`. Producer preflight is stricter: declare both names, or provide
+`repo-root` so both resolve locally. An absent cwd also returns unavailable
+scope and refuses producer admission.
+
The normal capture contract is intentionally narrow: supported Claude Code,
OpenCode, Pi, OMP, and Antigravity tool events retain only canonical tool family,
an agent-provided validated call ID when their documented schema proves one,
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 9027f977..f384e4d9 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -52,9 +52,9 @@ boundary not yet built.
| 10e | Reconcile-tombstone of a disk-deleted page is opt-in, soft, scope-bound, and false-positive-guarded (invariant #16, #929 delete-half) | `ai-memory-wiki/src/watcher.rs` — off by default (`[maintenance] reconcile_tombstones_deleted_pages`); a page is tombstoned only after its file is observed missing on two consecutive passes (streak resets if the path's `PageId` changed), re-verified against the live filesystem immediately before acting, with reserved/indexed-but-unwalked paths (`bootstrap.md`, `_meta.md`, `_pending/`, `sessions/*.md`) excluded and a circuit breaker that skips a whole scope when `> max(3, 50%)` of its pages look missing or a non-partial walk finds nothing; `ai-memory-store/src/ops.rs` `soft_delete_for_reconcile_if_latest` is a soft tombstone (`is_latest=0` + `superseded_at`, decay's shape) through the single writer actor in one transaction — never a filesystem write — scoped to the page's own `(workspace_id, project_id)` | `watcher.rs` `reconcile_delete_disabled_by_default_never_tombstones_a_missing_page`, `reconcile_delete_cross_project_isolation` (project A's deletion never tombstones project B's same-path page), `reconcile_tombstone_refuses_a_stale_latest_id`, `reconcile_tombstone_refuses_when_the_file_still_exists`, `reconcile_tombstone_never_touches_the_filesystem`; `ops.rs` `reconcile_tombstone_resurrects_instead_of_orphaning_on_recreate` | STRONG |
| 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 |
+| 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; `hook.rs` `--check-capture` preflight uses the same capture policy before any spool or spawn | `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); `hook.rs` `check_capture_refuses_partial_scope_and_excluded_content` (ignored-path and partial-scope violations refused, complete public-path control passes), `check_capture_bounds_marker_hints_and_refuses_oversized_scope` (513-byte hints refused, 512-byte control passes; native routing preserved) | STRONG |
| 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) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |
+| 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) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |
| 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 |
| 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 |