Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(serve): require a client marker on handoff fetches through LAN hosts
AkitaOnRailsd480ab87f563
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 92e98c07..8d8788af 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,7 +15,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0that are not script calls from a page, such as links and images; hooks, theCLI, MCP clients and the built-in web UI are unaffected, and servers with abearer token are unchanged. Images in wiki pages rendered by the web UI are- also limited to relative paths that stay inside the UI.+ also limited to relative paths that stay inside the UI. When an+ unauthenticated server is reached through a non-loopback host name in its+ allowlist (a LAN address or name, or `host.docker.internal`), where browsers+ do not send the request metadata the check relies on, the session-start+ handoff fetch now also requires an `X-AI-Memory-Client` header that every+ ai-memory hook, CLI command and generated integration sends. Hooks on such a+ server must be re-staged with `ai-memory install-hooks` (or+ `ai-memory upgrade`); loopback installs need nothing.(GHSA-6mc4-46pr-w82w)- Fixed approving or rejecting an unknown pending write(`POST /admin/pending-writes/{id}/approve` or `/reject`) answering 500 insteaddiff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex 9adb4e91..027099d6 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -17,7 +17,8 @@ use crate::marker::{};use ai_memory_hooks::capture_policy::MAX_MARKER_BYTES;use ai_memory_hooks::{- CaptureConfig, CapturePolicy, CaptureSource, PolicyState, describe_invalid_capture_config,+ CLIENT_MARKER_HEADER, CaptureConfig, CapturePolicy, CaptureSource, PolicyState,+ describe_invalid_capture_config,};/// Resolve the nearest marker's capture policy without changing routing parsing.@@ -717,6 +718,12 @@ fn repository_identity(.filter(|identity| identity.source.routes_by_identity())}+/// [`CLIENT_MARKER_HEADER`] value the native hook sends on+/// every request to the server. Set per request rather than as a client+/// default because the same client also refreshes OIDC tokens with a third+/// party, which has no use for it.+const NATIVE_HOOK_CLIENT_KIND: &str = "hook";+/// Build a reqwest client for the hook's one-shot requests. `no_proxy`/// skips Windows proxy auto-detection (registry / WinINET lookups), which/// is pure overhead for a loopback/LAN POST. Built once per invocation and@@ -786,6 +793,7 @@ pub async fn post_hook(let mut req = client.post(url).header("Content-Type", "application/json")+ .header(CLIENT_MARKER_HEADER, NATIVE_HOOK_CLIENT_KIND).timeout(timeout).body(body.to_owned());if let Some(t) = token {@@ -861,6 +869,7 @@ pub async fn post_batch(let mut req = client.post(batch_url).header("Content-Type", "application/json")+ .header(CLIENT_MARKER_HEADER, NATIVE_HOOK_CLIENT_KIND).timeout(timeout).body(payload.to_owned());if let Some(t) = token {@@ -938,7 +947,10 @@ pub async fn get_handoff(token: Option<&str>,timeout: Duration,) -> Option<String> {- let mut req = client.get(url).timeout(timeout);+ let mut req = client+ .get(url)+ .header(CLIENT_MARKER_HEADER, NATIVE_HOOK_CLIENT_KIND)+ .timeout(timeout);if let Some(t) = token {req = req.bearer_auth(t);}@@ -1162,6 +1174,73 @@ mod tests {assert!(got.is_none(), "non-2xx body must not become context");}+ /// Like `serve_once`, but answers 200 and hands back the raw request.+ async fn capture_once() -> (String, tokio::task::JoinHandle<String>) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let handle = tokio::spawn(async move {+ let (mut stream, _) = listener.accept().await.unwrap();+ // Read until the end of the headers; the body is irrelevant.+ let mut head = Vec::new();+ let mut buf = [0_u8; 4096];+ while !head.windows(4).any(|w| w == b"\r\n\r\n") {+ let n = stream.read(&mut buf).await.unwrap();+ if n == 0 {+ break;+ }+ head.extend_from_slice(&buf[..n]);+ }+ let body = "ok";+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ let _ = stream.write_all(response.as_bytes()).await;+ String::from_utf8_lossy(&head).to_ascii_lowercase()+ });+ (format!("http://{addr}"), handle)+ }++ #[tokio::test]+ async fn every_native_hook_request_carries_the_client_marker() {+ // An unauthenticated server reached by a LAN name refuses a handoff+ // fetch without it, and hook events ride the same contract.+ let marker = format!("{CLIENT_MARKER_HEADER}: hook\r\n");+ let (base, request) = capture_once().await;+ get_handoff(+ &build_client(),+ &format!("{base}/handoff?agent=claude-code"),+ None,+ Duration::from_secs(2),+ )+ .await;+ let request = request.await.unwrap();+ assert!(request.starts_with("get /handoff?"), "{request}");+ assert!(request.contains(&marker), "handoff GET: {request}");++ let (base, request) = capture_once().await;+ post_hook(+ &build_client(),+ &format!("{base}/hook?event=stop"),+ "{}",+ None,+ Duration::from_secs(2),+ )+ .await;+ assert!(request.await.unwrap().contains(&marker), "hook POST");++ let (base, request) = capture_once().await;+ post_batch(+ &build_client(),+ &format!("{base}/hook/batch"),+ "[]",+ None,+ Duration::from_secs(2),+ )+ .await;+ assert!(request.await.unwrap().contains(&marker), "batch POST");+ }+// The marker parser's own tests (`parse_toml_key`, `find_marker`) moved to// `crate::marker` along with the code. What stays here is hook-specific:// the strict `[capture]` section and the query-string suffix.diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 0af26931..e76a209b 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -37,8 +37,8 @@ use crate::commands::render_shared::{build_grok_payload_with_data_dir, build_kiro_cli_v2_hooks_value, build_kiro_cli_v3_hooks_value,build_pool_settings_yaml_with_data_dir, build_profile_payload_for_agent,hook_embedded_exe_path, hook_script_for_claude_code, hook_script_for_current_platform,- kimi_code_hook_commands, local_hook_policy_v1_supported, ts_capture_policy_v1,- ts_string_literal, ts_timeout_signal,+ kimi_code_hook_commands, local_hook_policy_v1_supported, ts_auth_headers_fn,+ ts_capture_policy_v1, ts_string_literal, ts_timeout_signal,};use crate::commands::uninstall::hook_command_is_ours;use crate::config::{Config, DEFAULT_SERVER_URL};@@ -4635,6 +4635,7 @@ fn build_opencode_plugin(let apply_marker_params = ts_apply_marker_params(project_strategy, true);let capture_policy = ts_capture_policy_v1(capture_mode);let timeout_signal = ts_timeout_signal();+ let auth_headers = ts_auth_headers_fn();let body = format!(r#"// Auto-generated by `ai-memory install-hooks --agent opencode --apply`.// Edit by re-running the command, not by hand — install-hooks@@ -4653,11 +4654,7 @@ const AGENT = "open-code";{capture_policy}{timeout_signal}-function authHeaders(): Record<string, string> {{- const token = resolveToken();- return token ? {{ Authorization: `Bearer ${{token}}` }} : {{}};-}}-+{auth_headers}const HOOK_QUEUE_MAX = 100;const HOOK_FLUSH_INTERVAL_MS = 2000;const HOOK_FLUSH_THRESHOLD = 20;@@ -5387,6 +5384,7 @@ fn build_omp_extension(let apply_marker_params = ts_apply_marker_params(project_strategy, true);let capture_policy = ts_capture_policy_v1(capture_mode);let timeout_signal = ts_timeout_signal();+ let auth_headers = ts_auth_headers_fn();let body = format!(r#"// Auto-generated by `ai-memory install-hooks --agent omp --apply`.// Edit by re-running the command, not by hand — install-hooks@@ -5404,11 +5402,7 @@ const AGENT = "omp";{capture_policy}{timeout_signal}-function authHeaders(): Record<string, string> {{- const token = resolveToken();- return token ? {{ Authorization: `Bearer ${{token}}` }} : {{}};-}}-+{auth_headers}const HOOK_QUEUE_MAX = 100;const HOOK_FLUSH_INTERVAL_MS = 2000;const HOOK_FLUSH_THRESHOLD = 20;diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rsindex e7256569..9a993487 100644--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs@@ -9,8 +9,8 @@ use anyhow::{Context, Result};use crate::cli::InstallHooksArgs;use crate::commands::apply_shared::{ApplyOutcome, apply_atomic};use crate::commands::render_shared::{- ts_capture_policy_v1, ts_resolve_token_fn, ts_spool_runtime, ts_string_literal,- ts_timeout_signal,+ ts_auth_headers_fn, ts_capture_policy_v1, ts_resolve_token_fn, ts_spool_runtime,+ ts_string_literal, ts_timeout_signal,};pub(crate) const PLUGIN_ID: &str = "ai-memory";@@ -249,11 +249,7 @@ const AGENT = "openclaw";{capture_policy}{timeout_signal}-function authHeaders(): Record<string, string> {{- const token = resolveToken();- return token ? {{ Authorization: `Bearer ${{token}}` }} : {{}};-}}-+{auth_headers}function findMarker(cwd: string | undefined): string | undefined {{if (!cwd) return undefined;let dir = resolve(cwd);@@ -491,6 +487,7 @@ export default definePluginEntry({{token_line = token_line,repo_root_project = super::install_hooks::TS_REPO_ROOT_PROJECT,timeout_signal = ts_timeout_signal(),+ auth_headers = ts_auth_headers_fn(),spool_runtime = ts_spool_runtime(),)}diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 0d492c8e..99d05a58 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -2060,7 +2060,7 @@ fn claude_code_windows_command_is_unchanged_by_the_codex_fix() {/// TypeScript runtime shared by every generated integration that must/// survive an unreachable server (#580): a spool writer emitting the CLI/// `hook-spool` on-disk contract (same filenames, same `SpoolEntry` JSON,-/// same permissions) plus a self-drain. Callers only need `TOKEN`,+/// same permissions) plus a self-drain. Callers only need `TOKEN`, `AGENT`,/// `timeoutSignal`, and the node `join`/`homedir`/fs imports in scope./// Runtime credential fallback shared by every generated TypeScript/// integration. #552 moved the bearer out of generated files into a 0600@@ -2102,6 +2102,25 @@ function resolveToken(): string | null {"#}+/// `authHeaders()`, shared by every generated TypeScript integration: the+/// headers every request to the server carries. Besides the bearer (resolved+/// per request by `ts_resolve_token_fn`), that is+/// [`ai_memory_hooks::CLIENT_MARKER_HEADER`] naming the integration: an+/// unauthenticated server reached through a non-loopback host name refuses a+/// handoff fetch without it. Needs `AGENT` and `resolveToken` in scope.+pub(crate) fn ts_auth_headers_fn() -> &'static str {+ r#"// Every request names this client: an unauthenticated server reached through+// a non-loopback host name refuses a handoff fetch without X-AI-Memory-Client,+// because a web page cannot add that header to a request it makes.+function authHeaders(): Record<string, string> {+ const headers: Record<string, string> = { "X-AI-Memory-Client": AGENT };+ const token = resolveToken();+ if (token) headers.Authorization = `Bearer ${token}`;+ return headers;+}+"#+}+/// `timeoutSignal`, shared by every generated TypeScript integration: a/// request deadline composed with `hookAbort`. A host that tears its capture/// state down aborts `hookAbort` once its final deliveries had their drain@@ -2212,7 +2231,10 @@ async function drainHookSpool(): Promise<void> {}if (!entry.url || typeof entry.body !== "string") continue;try {- const headers: Record<string, string> = { "Content-Type": "application/json" };+ const headers: Record<string, string> = {+ "Content-Type": "application/json",+ "X-AI-Memory-Client": AGENT,+ };if (entry.token) headers["Authorization"] = `Bearer ${entry.token}`;const resp = await fetch(entry.url, {method: "POST",@@ -2299,6 +2321,56 @@ pub(crate) fn assert_shared_ts_delivery_runtime(name: &str, source: &str) {source.contains("resp.status < 500 && !hookStatusRetryable(resp.status)"),"{name}: the drain must keep an entry the server only asked to retry");+ assert_every_ts_request_carries_client_marker(name, source);+}++/// An unauthenticated server reached through a non-loopback host name refuses+/// a handoff fetch without the client marker, so every `fetch` a generated+/// integration makes must send it: through `authHeaders()` (hook POSTs, the+/// handoff GET), `mcpHeaders()` (which spreads `authHeaders()`), or the spool+/// drain's own header table.+#[cfg(test)]+fn assert_every_ts_request_carries_client_marker(name: &str, source: &str) {+ assert_eq!(+ source.matches(ts_auth_headers_fn()).count(),+ 1,+ "{name}: exactly one shared authHeaders()"+ );+ assert!(+ source.contains(+ "\"Content-Type\": \"application/json\",\n \"X-AI-Memory-Client\": AGENT,"+ ),+ "{name}: the spool drain must send the client marker"+ );+ if source.contains("function mcpHeaders(") {+ assert!(+ source.contains(" ...authHeaders(),\n"),+ "{name}: mcpHeaders"+ );+ }+ let mut requests = 0;+ for (at, _) in source.match_indices("fetch(") {+ // Skip identifiers that merely end in `fetch(`, e.g. `prefetch(`.+ if source[..at]+ .chars()+ .next_back()+ .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_')+ {+ continue;+ }+ requests += 1;+ let call: String = source[at..].chars().take(240).collect();+ assert!(+ call.contains("authHeaders()")+ || call.contains("mcpHeaders(")+ || call.contains(" headers,\n"),+ "{name}: a fetch without the client marker:\n{call}"+ );+ }+ assert!(+ requests >= 3,+ "{name}: expected the hook, handoff and drain requests"+ );}#[cfg(test)]diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 4fa5e93c..3e482d05 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -13,8 +13,8 @@ use ai_memory_consolidate::{};use ai_memory_core::{ActiveProject, ProjectId, Sanitizer, WorkspaceId};use ai_memory_hooks::{- DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, ProjectCacheStore, WorkstreamState, hook_router,- workstream_router,+ CLIENT_MARKER_HEADER, DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, ProjectCacheStore,+ WorkstreamState, hook_router, workstream_router,};use ai_memory_llm::{Embedder, LlmProvider, ProviderHealth, build_embedder};use ai_memory_mcp::human_auth::{Cidr, HumanAuthRuntime, LoginLimiter};@@ -2950,6 +2950,17 @@ async fn require_allowed_host(/// a link opened from another application, off these routes even when the/// browser labels it `same-origin` or `none`. Non-browser clients send no/// fetch metadata and are unaffected.+///+/// Both checks rely on fetch metadata, which browsers send only to+/// potentially trustworthy origins: loopback names and addresses, and HTTPS.+/// A server reached over plain HTTP through a LAN address or another allowed+/// host name gets an `<img>` request with neither fetch metadata nor `Origin`.+/// For that case the session-start handoff fetch, the one state-changing `GET`+/// on these routes, must also carry [`CLIENT_MARKER_HEADER`], which a page+/// cannot add without a preflight these routes never answer. Loopback hosts+/// keep working without it, so hook scripts staged before the header existed+/// still deliver handoffs on a default install. `POST`s need no marker: a+/// browser sends `Origin` on every cross-origin `POST`, metadata or not.fn refuse_cross_origin_browser_requests(router: axum::Router, auth_enabled: bool) -> axum::Router {if auth_enabled {return router;@@ -2957,20 +2968,75 @@ fn refuse_cross_origin_browser_requests(router: axum::Router, auth_enabled: boolrouter.layer(axum::middleware::from_fn(require_same_origin_browser))}+/// Body of the 403 a handoff fetch without [`CLIENT_MARKER_HEADER`] gets. It+/// reaches an operator through a hook staged before the header existed, so it+/// names both ways out.+const CLIENT_MARKER_REFUSAL: &str = "handoff fetch refused: this server has no bearer token and \+ was reached through a non-loopback host name, so it accepts the handoff fetch only from \+ current ai-memory hooks; re-stage them with `ai-memory install-hooks` (or `ai-memory \+ upgrade`), or configure AI_MEMORY_AUTH_TOKEN\n";+async fn require_same_origin_browser(req: Request<Body>, next: Next) -> Response {let headers = req.headers();- if !is_cross_origin_browser_request(headers) && !is_non_script_browser_request(headers) {- return next.run(req).await;+ if is_cross_origin_browser_request(headers) || is_non_script_browser_request(headers) {+ // Any page the operator opens can trigger this at will, so it stays+ // out of the default log level.+ tracing::debug!(+ path = req.uri().path(),+ origin = ?headers.get(header::ORIGIN),+ dest = ?headers.get("sec-fetch-dest"),+ "rejected browser request to an unauthenticated server"+ );+ return (StatusCode::FORBIDDEN, "browser request refused\n").into_response();}- // Any page the operator opens can trigger this at will, so it stays out- // of the default log level.- tracing::debug!(- path = req.uri().path(),- origin = ?req.headers().get(header::ORIGIN),- dest = ?req.headers().get("sec-fetch-dest"),- "rejected browser request to an unauthenticated server"- );- (StatusCode::FORBIDDEN, "browser request refused\n").into_response()+ if handoff_fetch_lacks_client_marker(req.method(), req.uri().path(), headers) {+ tracing::debug!(+ host = ?headers.get(header::HOST),+ "rejected handoff fetch without the client marker on a non-loopback host"+ );+ return (StatusCode::FORBIDDEN, CLIENT_MARKER_REFUSAL).into_response();+ }+ next.run(req).await+}++/// Whether this is a handoff fetch (`GET`, or `HEAD`, which axum routes to the+/// same handler) without [`CLIENT_MARKER_HEADER`] on a host where a browser+/// sends no fetch metadata. The path is the one inside any `--base-path`+/// mount, which strips its prefix before this layer runs.+fn handoff_fetch_lacks_client_marker(+ method: &axum::http::Method,+ path: &str,+ headers: &axum::http::HeaderMap,+) -> bool {+ if path != "/handoff" || !matches!(*method, axum::http::Method::GET | axum::http::Method::HEAD)+ {+ return false;+ }+ if headers+ .get(CLIENT_MARKER_HEADER)+ .is_some_and(|value| !value.as_bytes().is_empty())+ {+ return false;+ }+ !headers+ .get(header::HOST)+ .and_then(|host| host.to_str().ok())+ .is_some_and(is_loopback_host)+}++/// Whether a browser treats this `Host` as a potentially trustworthy origin+/// and so sends fetch metadata to it over plain HTTP: `localhost`, a+/// `*.localhost` name, `127.0.0.0/8` or `[::1]`. Anything else, including a+/// LAN address, `0.0.0.0` or `host.docker.internal`, is not.+fn is_loopback_host(host: &str) -> bool {+ let name = host_without_port(host).to_ascii_lowercase();+ name == "localhost"+ || name+ .strip_suffix(".localhost")+ .is_some_and(|label| !label.is_empty())+ || name+ .parse::<std::net::IpAddr>()+ .is_ok_and(|ip| ip.is_loopback())}/// Whether a browser marks this request as issued by a page of another origin.@@ -5126,6 +5192,171 @@ mod tests {);}+ #[test]+ fn loopback_host_detection() {+ for (host, loopback) in [+ ("127.0.0.1:49374", true),+ ("127.0.0.1", true),+ ("127.8.9.10:49374", true),+ ("[::1]:49374", true),+ ("localhost:49374", true),+ ("LOCALHOST", true),+ ("ai-memory.localhost:49374", true),+ ("a.b.LocalHost", true),+ // Not potentially trustworthy to a browser: no fetch metadata.+ ("192.168.1.20:49374", false),+ ("10.0.0.5", false),+ ("0.0.0.0:49374", false),+ ("host.docker.internal:49374", false),+ ("memory.lan:49374", false),+ ("[::ffff:127.0.0.1]:49374", false),+ ("notlocalhost:49374", false),+ ("localhost.evil.example", false),+ (".localhost", false),+ ("", false),+ ] {+ assert_eq!(is_loopback_host(host), loopback, "{host:?}");+ }+ }++ #[test]+ fn handoff_fetch_client_marker_decision() {+ use axum::http::Method;++ let headers = |host: &'static str, marker: Option<&'static str>| {+ let mut headers = axum::http::HeaderMap::new();+ headers.insert(header::HOST, host.parse().unwrap());+ if let Some(marker) = marker {+ headers.insert(CLIENT_MARKER_HEADER, marker.parse().unwrap());+ }+ headers+ };+ for (method, path, host, marker, refused) in [+ // Attack: an `<img>` to a LAN host carries no fetch metadata.+ (Method::GET, "/handoff", "192.168.1.20:49374", None, true),+ (Method::HEAD, "/handoff", "192.168.1.20:49374", None, true),+ (+ Method::GET,+ "/handoff",+ "host.docker.internal:49374",+ None,+ true,+ ),+ (Method::GET, "/handoff", "memory.lan", Some(""), true),+ // Controls: a current hook names itself on any host.+ (+ Method::GET,+ "/handoff",+ "192.168.1.20:49374",+ Some("hook"),+ false,+ ),+ (+ Method::GET,+ "/handoff",+ "memory.lan",+ Some("hook-sh"),+ false,+ ),+ // Loopback: browsers send fetch metadata there, and hooks staged+ // before the marker existed must keep working.+ (Method::GET, "/handoff", "127.0.0.1:49374", None, false),+ (Method::GET, "/handoff", "localhost:49374", None, false),+ (Method::GET, "/handoff", "[::1]:49374", None, false),+ // Other routes and methods are not the state-changing GET.+ (Method::POST, "/hook", "192.168.1.20:49374", None, false),+ (+ Method::GET,+ "/admin/handoffs",+ "192.168.1.20:49374",+ None,+ false,+ ),+ (Method::GET, "/handoff/x", "192.168.1.20:49374", None, false),+ (Method::POST, "/handoff", "192.168.1.20:49374", None, false),+ ] {+ assert_eq!(+ handoff_fetch_lacks_client_marker(&method, path, &headers(host, marker)),+ refused,+ "{method} {path} host={host} marker={marker:?}"+ );+ }+ let mut no_host = axum::http::HeaderMap::new();+ assert!(handoff_fetch_lacks_client_marker(+ &Method::GET,+ "/handoff",+ &no_host+ ));+ no_host.insert(CLIENT_MARKER_HEADER, "hook".parse().unwrap());+ assert!(!handoff_fetch_lacks_client_marker(+ &Method::GET,+ "/handoff",+ &no_host+ ));+ }++ #[tokio::test]+ async fn handoff_client_marker_guard_on_lan_hosts_and_under_a_base_path() {+ use tower::ServiceExt as _;++ let send = |auth_enabled: bool,+ base: &'static str,+ host: &'static str,+ marker: Option<&'static str>| async move {+ let guarded = refuse_cross_origin_browser_requests(+ axum::Router::new().route("/handoff", axum::routing::get(|| async { "claimed" })),+ auth_enabled,+ );+ let app = if base.is_empty() {+ guarded+ } else {+ axum::Router::new().nest(base, guarded)+ };+ let mut request = Request::builder()+ .uri(format!("{base}/handoff?workspace=w&project=p"))+ .header(header::HOST, host);+ if let Some(marker) = marker {+ request = request.header(CLIENT_MARKER_HEADER, marker);+ }+ let response = app+ .oneshot(request.body(Body::empty()).unwrap())+ .await+ .unwrap();+ let status = response.status();+ let body = axum::body::to_bytes(response.into_body(), 4096)+ .await+ .unwrap();+ (status, String::from_utf8_lossy(&body).into_owned())+ };+ for base in ["", "/memory"] {+ // Attack: no metadata, no Origin, no marker, LAN host.+ let (status, body) = send(false, base, "192.168.1.20:49374", None).await;+ assert_eq!(status, StatusCode::FORBIDDEN, "base={base:?}");+ assert!(+ body.contains("install-hooks") && body.contains("AI_MEMORY_AUTH_TOKEN"),+ "the refusal must name both remedies: {body}"+ );+ // Control: the same request from a current hook.+ assert_eq!(+ send(false, base, "192.168.1.20:49374", Some("hook")).await,+ (StatusCode::OK, "claimed".to_string()),+ "base={base:?}"+ );+ // Legacy hook on a loopback install.+ assert_eq!(+ send(false, base, "127.0.0.1:49374", None).await.0,+ StatusCode::OK,+ "base={base:?}"+ );+ // Auth on: the bearer gate decides.+ assert_eq!(+ send(true, base, "192.168.1.20:49374", None).await.0,+ StatusCode::OK,+ "base={base:?}"+ );+ }+ }+#[test]fn web_ui_dir_requires_enable_web() {let ui = TempDir::new().unwrap();diff --git a/crates/ai-memory-cli/src/http_client.rs b/crates/ai-memory-cli/src/http_client.rsindex 78c15992..a7601bd5 100644--- a/crates/ai-memory-cli/src/http_client.rs+++ b/crates/ai-memory-cli/src/http_client.rs@@ -24,6 +24,9 @@ use serde::de::DeserializeOwned;use crate::config::{Config, DEFAULT_SERVER_URL};use ai_memory_web::normalize_prefix;+/// [`ai_memory_hooks::CLIENT_MARKER_HEADER`] value for CLI subcommands.+const CLI_CLIENT_KIND: &str = "cli";+/// Non-success response returned by the configured ai-memory server.#[derive(Debug)]pub(crate) struct ServerResponseError {@@ -238,8 +241,11 @@ impl ServerEndpoint {parsed.as_str().trim_end_matches('/').to_owned()}- /// Apply auth header to a `reqwest::RequestBuilder` if a token is set.+ /// Mark a request to this server as first-party+ /// ([`ai_memory_hooks::CLIENT_MARKER_HEADER`]) and attach the bearer when a+ /// token is set.pub(crate) fn authenticate(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {+ let req = req.header(ai_memory_hooks::CLIENT_MARKER_HEADER, CLI_CLIENT_KIND);match &self.auth_token {Some(t) => req.bearer_auth(t),None => req,@@ -822,7 +828,7 @@ mod tests {// ----------------------------------------------------------------#[test]- fn authenticate_no_token_leaves_request_unchanged() {+ fn authenticate_no_token_sets_only_the_client_marker() {let ep = ServerEndpoint::from_pair(None, None);let client = reqwest::Client::new();// Build a request, authenticate it, then build to inspect.@@ -835,6 +841,14 @@ mod tests {req.headers().get("authorization").is_none(),"no Authorization header expected");+ // An unauthenticated server reached by a LAN name refuses a handoff+ // fetch without the marker, so every CLI request carries it.+ assert_eq!(+ req.headers()+ .get(ai_memory_hooks::CLIENT_MARKER_HEADER)+ .and_then(|v| v.to_str().ok()),+ Some("cli")+ );}#[test]diff --git a/crates/ai-memory-cli/tests/suite/cross_origin_e2e.rs b/crates/ai-memory-cli/tests/suite/cross_origin_e2e.rsindex 72bfe300..89b68f14 100644--- a/crates/ai-memory-cli/tests/suite/cross_origin_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/cross_origin_e2e.rs@@ -25,6 +25,11 @@//! the three simple content types with 415, so a preflight-free `POST`//! cannot deliver a body even past guard 1.//! 3. The `Host` allowlist refuses a rebinding hostname with 403.+//! 4. On a host a browser sends no fetch metadata to (a LAN address or name in+//! the allowlist, over plain HTTP), an `<img>` request carries neither+//! fetch metadata nor `Origin`. There the handoff fetch must also carry the+//! `X-AI-Memory-Client` marker every first-party client sends and a page+//! cannot add; loopback hosts keep accepting legacy hooks without it.//!//! Every attack carries a canary string. After the attacks the test scans the//! whole data directory, SQLite and wiki alike, for it, and checks that the@@ -382,6 +387,145 @@ mod slow {.is_success()}+ /// A LAN name and a LAN address the operator put in the allowlist.+ const LAN_NAME: &str = "a0-memory.lan";+ const LAN_ADDR: &str = "192.168.77.5";++ async fn handoff_status(+ client: &reqwest::Client,+ base: &str,+ method: Method,+ host: &str,+ marker: Option<&str>,+ ) -> (StatusCode, String) {+ let mut req = client+ .request(+ method,+ format!("{base}/handoff?agent=claude-code&workspace={WORKSPACE}&project={PROJECT}"),+ )+ .header("host", host);+ if let Some(marker) = marker {+ req = req.header("x-ai-memory-client", marker);+ }+ let resp = req.send().await.expect("handoff request");+ let status = resp.status();+ (status, resp.text().await.expect("handoff body"))+ }++ async fn begin_handoff(client: &reqwest::Client, base: &str) {+ legit_mcp(+ client,+ base,+ "memory_handoff_begin",+ json!({+ "workspace": WORKSPACE,+ "project": PROJECT,+ "summary": HANDOFF_SUMMARY,+ "shared": true,+ }),+ )+ .await;+ assert_eq!(open_handoffs(client, base).await, 1, "baton must be open");+ }++ #[tokio::test]+ async fn handoff_fetch_on_a_lan_host_requires_the_client_marker() {+ let root = tempfile::tempdir().expect("tempdir");+ let data_dir = root.path().join("data");+ let home = root.path().join("home");+ fs::create_dir_all(&home).expect("home");+ let client = reqwest::Client::new();+ let (_server, base) = start_serve(&client, &root.path().join("serve.log"), |port| {+ let mut cmd = serve(&data_dir, &home, port);+ cmd.env(+ "AI_MEMORY_ALLOWED_HOSTS",+ format!("localhost,127.0.0.1,::1,{LAN_NAME},{LAN_ADDR}"),+ );+ cmd+ })+ .await;+ let port = base.rsplit(':').next().expect("port").to_string();+ let lan_hosts = [format!("{LAN_NAME}:{port}"), format!("{LAN_ADDR}:{port}")];++ legit_mcp(+ &client,+ &base,+ "memory_write_page",+ json!({+ "workspace": WORKSPACE,+ "project": BASELINE_PROJECT,+ "path": "notes/baseline.md",+ "body": "Baseline project.",+ }),+ )+ .await;+ legit_handoff_fetch(&client, &base, BASELINE_PROJECT).await;+ let baseline = (WORKSPACE.to_string(), BASELINE_PROJECT.to_string());+ begin_handoff(&client, &base).await;++ // Attack: what an `<img>` on a foreign page sends to a LAN host over+ // plain HTTP: no fetch metadata, no Origin, no marker.+ for host in &lan_hosts {+ for method in [Method::GET, Method::HEAD] {+ let (status, body) =+ handoff_status(&client, &base, method.clone(), host, None).await;+ assert_eq!(+ status,+ StatusCode::FORBIDDEN,+ "{method} /handoff via {host} without the marker must be refused"+ );+ if method == Method::GET {+ assert!(+ body.contains("install-hooks") && body.contains("AI_MEMORY_AUTH_TOKEN"),+ "the refusal must tell the operator what to do: {body}"+ );+ }+ }+ // An empty marker is no marker.+ let (status, _) = handoff_status(&client, &base, Method::GET, host, Some("")).await;+ assert_eq!(status, StatusCode::FORBIDDEN, "empty marker via {host}");+ }+ assert_eq!(+ open_handoffs(&client, &base).await,+ 1,+ "a refused LAN fetch must not claim the baton"+ );+ assert_eq!(+ unscoped_scope(&client, &base).await,+ baseline,+ "a refused LAN fetch must not move the active-project pointer"+ );++ // Control: a current hook names itself and claims through the LAN name.+ let (status, body) =+ handoff_status(&client, &base, Method::GET, &lan_hosts[0], Some("hook")).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert!(+ body.contains(HANDOFF_SUMMARY),+ "marked fetch claims: {body}"+ );+ assert_eq!(open_handoffs(&client, &base).await, 0);++ // Legacy hooks on a loopback install send no marker and must keep+ // working: browsers send fetch metadata to loopback, which guard 1+ // already checks.+ begin_handoff(&client, &base).await;+ let (status, body) = handoff_status(+ &client,+ &base,+ Method::GET,+ &format!("127.0.0.1:{port}"),+ None,+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert!(+ body.contains(HANDOFF_SUMMARY),+ "legacy loopback fetch: {body}"+ );+ assert_eq!(open_handoffs(&client, &base).await, 0);+ }+#[tokio::test]async fn browser_cross_origin_requests_cannot_write_to_an_unauthenticated_loopback_server() {let root = tempfile::tempdir().expect("tempdir");diff --git a/crates/ai-memory-cli/tests/suite/external_capture_powershell.rs b/crates/ai-memory-cli/tests/suite/external_capture_powershell.rsindex 395ccf83..5d8f411a 100644--- a/crates/ai-memory-cli/tests/suite/external_capture_powershell.rs+++ b/crates/ai-memory-cli/tests/suite/external_capture_powershell.rs@@ -44,7 +44,7 @@ function Invoke-WebRequest {[string] $ContentType,$Body)- Add-Content -LiteralPath $env:AI_MEMORY_TEST_LOG -Value ('{0} {1}' -f $Method.ToUpperInvariant(), $Uri)+ Add-Content -LiteralPath $env:AI_MEMORY_TEST_LOG -Value ('{0} {1} client={2}' -f $Method.ToUpperInvariant(), $Uri, $Headers['X-AI-Memory-Client'])if ($Method -eq 'Post') { return $null }return [pscustomobject]@{ Content = 'HANDOFF FROM SERVER' }}@@ -165,6 +165,20 @@ Invoke-AiMemoryHook -Event 'session-start' -Agent 'claude-code' -FetchHandoff);}+ #[test]+ fn every_request_carries_the_client_marker() {+ // An unauthenticated server reached by a LAN name refuses a handoff+ // fetch without it; the event POST rides the same header table.+ let run = run(None);+ assert_eq!(run.methods(), vec!["POST", "GET"], "{:?}", run.requests);+ for request in &run.requests {+ assert!(+ request.ends_with(" client=hook-ps"),+ "request without the client marker: {request}"+ );+ }+ }+#[test]fn blank_capture_owner_keeps_capture_on() {// An empty value may reach the child as "unset" on Windows; either waydiff --git a/crates/ai-memory-cli/tests/suite/external_capture_ts.rs b/crates/ai-memory-cli/tests/suite/external_capture_ts.rsindex 52781482..c01e1f7d 100644--- a/crates/ai-memory-cli/tests/suite/external_capture_ts.rs+++ b/crates/ai-memory-cli/tests/suite/external_capture_ts.rs@@ -100,9 +100,11 @@ const port = Number(process.argv[2]);const directory = process.argv[3]!;const events: string[] = [];let handoffs = 0;+const unmarked: string[] = [];const server = createServer((req, res) => {const url = new URL(req.url ?? "/", "http://127.0.0.1");req.resume();+ if (req.headers["x-ai-memory-client"] !== "open-code") unmarked.push(url.pathname);if (url.pathname === "/hook") {events.push(url.searchParams.get("event") ?? "?");res.writeHead(204);@@ -134,7 +136,7 @@ const transformed: { system: string[] } = { system: [] };await hooks["experimental.chat.system.transform"]({ sessionID: "s1" }, transformed);await hooks.dispose();server.close();-console.log(JSON.stringify({ events, handoffs, system: transformed.system }));+console.log(JSON.stringify({ events, handoffs, unmarked, system: transformed.system }));"#;/// One plugin run. `hermetic` drops every ambient `AI_MEMORY_*` var, and@@ -247,6 +249,7 @@ console.log(JSON.stringify({ events, handoffs, system: transformed.system }));assert_eq!(spooled_entries(&dir), 0, "owned run must spool nothing new");// Context delivery is a separate path and must survive the handover.assert_eq!(owned["handoffs"], 1, "{owned}");+ assert_eq!(owned["unmarked"], serde_json::json!([]), "{owned}");assert_eq!(owned["system"][0], "HANDOFF_SENTINEL", "{owned}");// Controls: unset and whitespace-only are not an owner, so the same@@ -262,6 +265,13 @@ console.log(JSON.stringify({ events, handoffs, system: transformed.system })););}assert_eq!(captured["handoffs"], 1, "{label}: {captured}");+ // An unauthenticated server reached by a LAN name refuses a+ // handoff fetch without the client marker.+ assert_eq!(+ captured["unmarked"],+ serde_json::json!([]),+ "{label}: requests without the client marker: {captured}"+ );assert_eq!(captured["system"][0], "HANDOFF_SENTINEL","{label}: {captured}"diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rsindex 017eb57c..aa0629a8 100644--- a/crates/ai-memory-hooks/src/lib.rs+++ b/crates/ai-memory-hooks/src/lib.rs@@ -61,6 +61,17 @@ pub use router::{pub use synth::synthesize_session_page;pub use workstream::{WorkstreamState, workstream_router};+/// Request header every first-party client (native hook and CLI, the shell and+/// PowerShell hook bundles, the generated TypeScript integrations) sends to the+/// server's machine routes. The value names the client kind and is+/// informational; the server only checks that the header is present.+///+/// A web page cannot attach a custom header to a cross-site request without a+/// CORS preflight, and the machine routes answer no preflight, so the header+/// separates a first-party client from a page in the operator's browser where+/// fetch metadata is absent (see `serve`'s browser guard).+pub const CLIENT_MARKER_HEADER: &str = "x-ai-memory-client";+// Integration tests compile into this crate's test harness instead of a// separate binary: every test binary is another link and, on macOS and// Windows, another first-run malware scan. They still exercise only thediff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 41249460..55fb0690 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -75,7 +75,7 @@ means the boundary is not built yet.| 11i | OpenCode executable probing and generated-config cleanup (#1097) | `ai-memory-cli/src/config.rs` captures the full process environment once in typed `RuntimeEnv`; `run.rs` overlays explicit `run --env` values with platform key semantics and uses that same effective environment for executable resolution, probing, and launch without rereading process environment; `opencode_dialect.rs` invokes only direct argv `--version`, caps output and time, and rejects malformed/future majors. Automatic launch skips only OpenCode on probe failure; explicit OpenCode fails. `install_hooks.rs` quarantines the incompatible sibling before reading its exact ownership markers, restores unowned content with an atomic no-replace link, and never deletes or overwrites a concurrent replacement; `install_mcp.rs` owns the shared dual-schema endpoint/token inference used by both installers, rejects conflicting generated V1/V2 entries before mutation, and migrates an alternate-major entry only when endpoint, generated shape, and absent-or-Authorization-only headers match, preserving custom headers and ambiguous entries; auto-wire migrates MCP before hooks infer from that exact config path and skips hook mutation when transition preflight fails | `run.rs` `automatic_opencode_probe_failure_keeps_another_harness_available`, `opencode_executable_probe_selects_v2_for_launch_and_autowire`, effective-child-environment PATH casing controls, fake V1/V2/env-derived-major/malformed/future/timeout executable tests, `setup-agent` V1/V2 no-probe integration controls; `install_hooks.rs` `opencode_plugin_cleanup_removes_only_exact_owned_incompatible_sibling`, `opencode_plugin_cleanup_preserves_a_concurrent_user_replacement`, `opencode_plugin_restore_moves_quarantine_when_destination_is_free`, `opencode_plugin_restore_preserves_an_existing_replacement`, `opencode_plugin_restore_does_not_replace_a_file_created_at_restore_window`, `opencode_plugin_cleanup_does_not_escape_custom_target_directory`; `install_mcp.rs` `opencode_install_reuses_owned_endpoint_and_token_across_major_transitions`, `opencode_install_refuses_conflicting_owned_transition_entries`, `opencode_install_does_not_infer_from_a_user_owned_transition_entry`, `opencode_mcp_migration_moves_only_owned_alternate_shape`, `opencode_mcp_migration_preserves_ambiguous_user_entry`, `opencode_mcp_migration_preserves_custom_headers`, `opencode_mcp_migration_accepts_only_historical_generated_headers` | STRONG for Unix process probes and platform-neutral ownership gates; exact Windows executable resolution remains covered by `run.rs` resolver tests and requires the PR `windows` label || 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 || 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments, with `sanitize_events` and `append_boundary_events` scrubbing event/checkpoint/losses content *before* the 64 KiB cap so a cap-straddling secret is never cut into an unmatchable prefix (#1113); `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, scrubbing content with the explicitly supplied configured sanitizer before its 16 KiB store-boundary bound; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`, `workstream_content_is_scrubbed_before_the_store_cap` (a credential straddling the 16 KiB store cap is redacted, not persisted as an unmatchable prefix; benign control verbatim; #1113); `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls), `finish_run_scrubs_event_content_before_the_byte_cap` and `finish_run_scrubs_boundary_events_before_the_byte_cap` (a credential straddling the 64 KiB event cap is redacted in the raw segment and never reaches the index; checkpoint/losses and benign controls; #1113); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten |-| 12c | Browser cross-origin writes refused on an unauthenticated loopback server (a foreign page in the operator's browser, and DNS rebinding) | `serve.rs` `refuse_cross_origin_browser_requests` / `is_cross_origin_browser_request`, layered on the machine (`/mcp`, `/hook*`, `/handoff`, `/workstream/*`, `/identity`) and admin (`/admin/*`) routes when auth is off: `Sec-Fetch-Site` other than `same-origin`/`none` → 403, or, without fetch metadata, an `Origin` whose authority is not the `Host` → 403; and `is_non_script_browser_request`: any `Sec-Fetch-Dest` other than `empty` (case-insensitive; non-UTF-8 refused) → 403 whatever `Sec-Fetch-Site` says, so links, images, navigations, iframes and form posts are refused even as `same-origin` or `none`. Hooks, the CLI and MCP clients send none of these headers; the web UI's same-origin `/admin/pending-writes` calls are `fetch()` (`Sec-Fetch-Dest: empty`) and pass. Behind it, axum `Json` and rmcp's `Content-Type: application/json` check refuse the preflight-free content types (`text/plain`, form-urlencoded, multipart) with 415; `require_allowed_host` (and rmcp `allowed_hosts` on `/mcp`) refuses a rebinding `Host`; machine/admin routes carry no CORS layer, so a preflight never comes back permissive. A stored wiki page viewed in the built-in web UI could otherwise turn the guard's same-origin allowance into a claim: `ai-memory-web/src/markdown.rs` `safe_image_url` / `is_safe_image_target` render as `#` any image target that is root-relative, a network path, carries a `..` segment (also percent-encoded), or, for a UI mounted at the base-path root, starts with a server route segment | `cli/tests/suite/cross_origin_e2e.rs` `browser_cross_origin_requests_cannot_write_to_an_unauthenticated_loopback_server`, against the shipped `serve`: every write route (`/hook`, `/hook/batch`, MCP `memory_write_page`/`memory_delete_page`/`memory_message_send`/`memory_handoff_accept`, `/admin/write-page`/`delete-page`/`purge-project`/`messages/send`, `/workstream/runs`) × each simple content type × modern, Origin-only and fetch-metadata-only browser shapes → 4xx; body-less `GET /handoff` (which claims the single-use baton), `POST /admin/profile/rebuild` and `POST /admin/backup` → 403; a rebinding `Host` → 403; preflights answer no `Access-Control-Allow-*`; `GET /handoff` as a same-origin `document` or `image` and as a `Sec-Fetch-Site: none` `document` → 403 with the baton still open. Then a canary scan of the whole data dir, page/project/handoff survival, and legitimate controls (JSON MCP calls, a JSON hook → 202, the web UI's same-origin `/admin/pending-writes` list and approve reach their handlers, the anonymous active-project pointer is unmoved after the refused `/handoff` fetches while the closing hook-style fetch claims the baton and moves it). `serve.rs` `cross_origin_browser_request_detection` and `non_script_browser_request_detection` (header tables) and `cross_origin_browser_guard_applies_only_without_auth` (same-origin `image` and `none` `document` refused, same-origin `empty` passes, both pass with auth on); `ai-memory-web` `markdown.rs` `neutralises_images_that_reach_server_routes` (`/handoff?…`, `/admin/backup`, `//host/…`, `../` and `%2e%2e/` traversal, root-mounted route names refused) with `preserves_relative_images` as the legitimate control | STRONG with listed residuals. Bite checks: with the guard removed, the cross-origin `GET /handoff` returns 200, consumes the baton and moves the active-project pointer (the pre-fix behaviour); with the guard treating `same-origin` as foreign, the web UI control gets 403; with the `Sec-Fetch-Dest` check removed, the same-origin `document` `GET /handoff` returns 200 and the unit guard test lets a same-origin image through; with the host layer removed, a rebound `/hook` returns 202; a permissive `CorsLayer` fails the preflight assertion; reverting `is_safe_image_target` to the pre-fix rule fails the markdown test on `/handoff?…`, dropping the percent-decoding fails it on `%2e%2e/`, and emptying the route list fails it on a root-mounted `handoff`. To reproduce the bite on the 415 layer, remove the guard and make `/hook` read a raw body instead of `Json`: a `text/plain` hook then returns 202 and the test fails. Residual, closed by setting a bearer token: a browser without fetch metadata (Safari before 16.4) sends no `Sec-Fetch-*` header and no `Origin` on an image `GET` or a link click, so such a request still reaches `/handoff` and the other `GET` routes. Browsers that send fetch metadata no longer have the earlier link residuals: a link opened from another app (`Sec-Fetch-Site: none`) and a link clicked in a stored page (`same-origin` navigation) both carry a non-`empty` destination and are refused. With auth on, the bearer token and the session CSRF token are the gate and this layer is a no-op |+| 12c | Browser cross-origin writes refused on an unauthenticated server (a foreign page in the operator's browser, DNS rebinding, and a LAN host where browsers send no fetch metadata) | `serve.rs` `refuse_cross_origin_browser_requests` / `is_cross_origin_browser_request`, layered on the machine (`/mcp`, `/hook*`, `/handoff`, `/workstream/*`, `/identity`) and admin (`/admin/*`) routes when auth is off: `Sec-Fetch-Site` other than `same-origin`/`none` → 403, or, without fetch metadata, an `Origin` whose authority is not the `Host` → 403; and `is_non_script_browser_request`: any `Sec-Fetch-Dest` other than `empty` (case-insensitive; non-UTF-8 refused) → 403 whatever `Sec-Fetch-Site` says, so links, images, navigations, iframes and form posts are refused even as `same-origin` or `none`. Browsers send fetch metadata over plain HTTP only to a potentially trustworthy host, so on any other `Host` (a LAN address or name in the allowlist, `0.0.0.0`, `host.docker.internal`; `is_loopback_host` admits only `localhost`, `*.localhost`, `127.0.0.0/8` and `[::1]`) `handoff_fetch_lacks_client_marker` also refuses `GET`/`HEAD /handoff` without a non-empty `X-AI-Memory-Client` header (`ai_memory_hooks::CLIENT_MARKER_HEADER`) → 403 whose body names both remedies (re-stage hooks, or set a bearer token). A page cannot add that header without a preflight these routes never answer. `/handoff` is the one state-changing `GET` on these routes; the other `GET`s are reads a foreign page cannot see the answer to, and every cross-origin `POST` carries `Origin`. Every first-party client sends the marker: the native hook (`hook_capture.rs` `post_hook`/`post_batch`/`get_handoff`), CLI subcommands (`http_client.rs` `ServerEndpoint::authenticate`), every curl in `hooks/_lib.sh`, both header tables in `hooks/lib/ai-memory-hook.ps1`, and the generated TypeScript integrations (`render_shared.rs` `ts_auth_headers_fn` plus the spool drain). Loopback hosts keep accepting a fetch without it, so hooks staged before the header existed still work on a default install. Hooks, the CLI and MCP clients send none of these headers; the web UI's same-origin `/admin/pending-writes` calls are `fetch()` (`Sec-Fetch-Dest: empty`) and pass. Behind it, axum `Json` and rmcp's `Content-Type: application/json` check refuse the preflight-free content types (`text/plain`, form-urlencoded, multipart) with 415; `require_allowed_host` (and rmcp `allowed_hosts` on `/mcp`) refuses a rebinding `Host`; machine/admin routes carry no CORS layer, so a preflight never comes back permissive. A stored wiki page viewed in the built-in web UI could otherwise turn the guard's same-origin allowance into a claim: `ai-memory-web/src/markdown.rs` `safe_image_url` / `is_safe_image_target` render as `#` any image target that is root-relative, a network path, carries a `..` segment (also percent-encoded), or, for a UI mounted at the base-path root, starts with a server route segment | `cli/tests/suite/cross_origin_e2e.rs` `browser_cross_origin_requests_cannot_write_to_an_unauthenticated_loopback_server`, against the shipped `serve`: every write route (`/hook`, `/hook/batch`, MCP `memory_write_page`/`memory_delete_page`/`memory_message_send`/`memory_handoff_accept`, `/admin/write-page`/`delete-page`/`purge-project`/`messages/send`, `/workstream/runs`) × each simple content type × modern, Origin-only and fetch-metadata-only browser shapes → 4xx; body-less `GET /handoff` (which claims the single-use baton), `POST /admin/profile/rebuild` and `POST /admin/backup` → 403; a rebinding `Host` → 403; preflights answer no `Access-Control-Allow-*`; `GET /handoff` as a same-origin `document` or `image` and as a `Sec-Fetch-Site: none` `document` → 403 with the baton still open. Then a canary scan of the whole data dir, page/project/handoff survival, and legitimate controls (JSON MCP calls, a JSON hook → 202, the web UI's same-origin `/admin/pending-writes` list and approve reach their handlers, the anonymous active-project pointer is unmoved after the refused `/handoff` fetches while the closing hook-style fetch claims the baton and moves it). `serve.rs` `cross_origin_browser_request_detection` and `non_script_browser_request_detection` (header tables) and `cross_origin_browser_guard_applies_only_without_auth` (same-origin `image` and `none` `document` refused, same-origin `empty` passes, both pass with auth on); `ai-memory-web` `markdown.rs` `neutralises_images_that_reach_server_routes` (`/handoff?…`, `/admin/backup`, `//host/…`, `../` and `%2e%2e/` traversal, root-mounted route names refused) with `preserves_relative_images` as the legitimate control. `cross_origin_e2e.rs` `handoff_fetch_on_a_lan_host_requires_the_client_marker`, against a `serve` that allowlists a LAN name and address: `GET` and `HEAD /handoff` through either without the marker, and with an empty one → 403 carrying the remedy text, with the baton still open and the active-project pointer unmoved; controls: a marked fetch through the LAN name claims the baton, and a marker-less fetch through `127.0.0.1` (a hook staged before the marker) claims the next one. `serve.rs` `loopback_host_detection`, `handoff_fetch_client_marker_decision` and `handoff_client_marker_guard_on_lan_hosts_and_under_a_base_path` (also under a `--base-path` nest; inactive with auth on). Front-door parity: `hook_capture.rs` `every_native_hook_request_carries_the_client_marker` (handoff GET, hook POST, batch POST), `http_client.rs` `authenticate_no_token_sets_only_the_client_marker`, the client-marker block of `tests/hooks/test_lib.sh` (every curl branch of the GET, the POST and the drain, plus a static check that every PowerShell header table carries it and every `Invoke-WebRequest` passes one), `render_shared.rs` `assert_every_ts_request_carries_client_marker` run for OpenCode, OpenCode 2, OMP, Pi and OpenClaw, `external_capture_ts.rs` (the rendered OpenCode plugin under Node sends no unmarked request) and `external_capture_powershell.rs` `every_request_carries_the_client_marker` (Windows leg) | STRONG with listed residuals. Bite checks: with the marker check disabled, the LAN e2e marker-less `GET /handoff` returns 200 and the unit layer test fails; dropping the marker from the native handoff GET, the shell token-drain curl, a PowerShell header table or the TypeScript spool drain fails the matching front-door test. With the guard removed, the cross-origin `GET /handoff` returns 200, consumes the baton and moves the active-project pointer (the pre-fix behaviour); with the guard treating `same-origin` as foreign, the web UI control gets 403; with the `Sec-Fetch-Dest` check removed, the same-origin `document` `GET /handoff` returns 200 and the unit guard test lets a same-origin image through; with the host layer removed, a rebound `/hook` returns 202; a permissive `CorsLayer` fails the preflight assertion; reverting `is_safe_image_target` to the pre-fix rule fails the markdown test on `/handoff?…`, dropping the percent-decoding fails it on `%2e%2e/`, and emptying the route list fails it on a root-mounted `handoff`. To reproduce the bite on the 415 layer, remove the guard and make `/hook` read a raw body instead of `Json`: a `text/plain` hook then returns 202 and the test fails. Residual, closed by setting a bearer token: a browser that sends no fetch metadata even to a loopback host (Safari before 16.4) sends no `Sec-Fetch-*` header and no `Origin` on an image `GET` or a link click, so such a request to a loopback host still reaches `/handoff` (loopback keeps accepting marker-less legacy hooks) and the other, read-only `GET` routes. On a non-loopback host the marker requirement closes `/handoff` for every browser. Browsers that send fetch metadata no longer have the earlier link residuals: a link opened from another app (`Sec-Fetch-Site: none`) and a link clicked in a stored page (`same-origin` navigation) both carry a non-`empty` destination and are refused. With auth on, the bearer token and the session CSRF token are the gate and this layer is a no-op || 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; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_continued_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050), and to a `/clear`ed session only when that session's own transcript records the `/clear` command and names the run's session as its launch `session_id` from this checkout or below it; `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` `claude_continued_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `transcript.rs` `claude_continued_session_follows_only_this_launchs_clear` (an uncleared transcript, a quoted `/clear`, another checkout's clear, a concurrent launch's clear, a subagent file, and a pre-run clear refused; own clear and the newest of two as controls); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`, `a_claude_run_that_was_cleared_follows_the_new_session`; `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous || 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet || 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `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. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users |diff --git a/docs/security.md b/docs/security.mdindex 72528036..7f75aaf1 100644--- a/docs/security.md+++ b/docs/security.md@@ -63,9 +63,22 @@ machine and admin routes: a request the browser marks as cross-site(`Sec-Fetch-Dest` other than `empty`): a link, image or navigation is refusedeven when it comes from the server's own pages or from another application.Hooks, the CLI and MCP clients never send those headers, and the web UI's own-admin calls use `fetch()`. A browser without fetch metadata (Safari before-16.4) only gets the `Origin` check, which an image or link does not trigger;-set a bearer token if you use one. The `Host`+admin calls use `fetch()`.++Browsers send that fetch metadata over plain HTTP only to `localhost`,+`*.localhost`, `127.0.0.0/8` and `[::1]`. When an unauthenticated server is+reached through any other name in the `Host` allowlist (a LAN address or name+with `--allow-insecure-no-auth`, or `host.docker.internal` in the Docker+image's default list), an image request carries neither fetch metadata nor+`Origin`. There the session-start handoff fetch, the only state-changing `GET`,+must also carry the `X-AI-Memory-Client` header that every ai-memory hook,+CLI command and generated integration sends; a web page cannot add it without+a CORS preflight, which these routes never answer. Hooks staged before this+header existed get a 403 on such a server until you re-run+`ai-memory install-hooks` (or `ai-memory upgrade`); on a loopback host they+keep working unchanged. A browser that sends no fetch metadata even to loopback+(Safari before 16.4) only gets the `Origin` check there, which an image or link+does not trigger; set a bearer token if you use one. The `Host`allowlist refuses DNS-rebinding hostnames, and the JSON-only routes refuse thecontent types a browser can send without a CORS preflight. Images in wiki pagesrendered by the web UI may only use relative paths that stay inside the UI, sodiff --git a/hooks/_lib.sh b/hooks/_lib.shindex fddc2735..06afd683 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -924,7 +924,7 @@ ai_memory_post_hook() {_ambody=$(cat)_amhdr=$(ai_memory_auth_header_file || printf '')if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then- _amcode=$(printf '%s' "$_ambody" | curl -s --max-time 0.2 -o /dev/null \+ _amcode=$(printf '%s' "$_ambody" | curl -s --max-time 0.2 -H "X-AI-Memory-Client: hook-sh" -o /dev/null \-w '%{http_code}' -X POST "$_amurl" \-H "Content-Type: application/json" \-H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \@@ -932,13 +932,13 @@ ai_memory_post_hook() {elif [ -n "$_amhdr" ]; then# `-H @file`: curl reads the header from disk, so the bearer never# appears in curl's argv the way an inline `-H` would (#552).- _amcode=$(printf '%s' "$_ambody" | curl -s --max-time 0.2 -o /dev/null \+ _amcode=$(printf '%s' "$_ambody" | curl -s --max-time 0.2 -H "X-AI-Memory-Client: hook-sh" -o /dev/null \-w '%{http_code}' -X POST "$_amurl" \-H "Content-Type: application/json" \-H @"$_amhdr" \--data-binary @- 2>/dev/null) || _amcode=000else- _amcode=$(printf '%s' "$_ambody" | curl -s --max-time 0.2 -o /dev/null \+ _amcode=$(printf '%s' "$_ambody" | curl -s --max-time 0.2 -H "X-AI-Memory-Client: hook-sh" -o /dev/null \-w '%{http_code}' -X POST "$_amurl" \-H "Content-Type: application/json" \--data-binary @- 2>/dev/null) || _amcode=000@@ -958,18 +958,21 @@ ai_memory_post_hook() {# generous than POST because the result is *synchronously* fed to# stdout (and prepended to the agent's context), so we want to avoid# truncating a handoff that was almost ready.+# Every request in this bundle sends `X-AI-Memory-Client`: an unauthenticated+# server reached through a non-loopback host name refuses a handoff fetch+# without it, because a web page cannot add that header to a request it makes.ai_memory_get_handoff() {case "$1" in*"$AI_MEMORY_SERVER_ROUTED_QS"*|*'ai_memory_invalid_home_routes=1'*) return 0 ;;esac_amhdr=$(ai_memory_auth_header_file)if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then- curl -s --max-time 1.0 "$1" \+ curl -s --max-time 1.0 -H "X-AI-Memory-Client: hook-sh" "$1" \-H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN"elif [ -n "$_amhdr" ]; then- curl -s --max-time 1.0 "$1" -H @"$_amhdr"+ curl -s --max-time 1.0 -H "X-AI-Memory-Client: hook-sh" "$1" -H @"$_amhdr"else- curl -s --max-time 1.0 "$1"+ curl -s --max-time 1.0 -H "X-AI-Memory-Client: hook-sh" "$1"fi}@@ -1187,13 +1190,13 @@ ai_memory_drain_spool() {if [ -n "$_amdtok" ]; then_amdhdr="$_amddir/.drain-header.$$"(umask 077; printf 'Authorization: Bearer %s\n' "$_amdtok" >"$_amdhdr") 2>/dev/null || continue- _amdcode=$(printf '%s' "$_amdbody" | curl -s --max-time 2.0 -o /dev/null \+ _amdcode=$(printf '%s' "$_amdbody" | curl -s --max-time 2.0 -H "X-AI-Memory-Client: hook-sh" -o /dev/null \-w '%{http_code}' -X POST "$_amdurl" \-H "Content-Type: application/json" -H @"$_amdhdr" \--data-binary @- 2>/dev/null) || _amdcode=000rm -f "$_amdhdr" 2>/dev/null || trueelse- _amdcode=$(printf '%s' "$_amdbody" | curl -s --max-time 2.0 -o /dev/null \+ _amdcode=$(printf '%s' "$_amdbody" | curl -s --max-time 2.0 -H "X-AI-Memory-Client: hook-sh" -o /dev/null \-w '%{http_code}' -X POST "$_amdurl" \-H "Content-Type: application/json" \--data-binary @- 2>/dev/null) || _amdcode=000diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index aa1af94f..8ebff055 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -780,6 +780,7 @@ function Invoke-AiMemoryDrainSpool {}if (-not $entry.url) { continue }$headers = @{}+ $headers["X-AI-Memory-Client"] = "hook-ps"if ($entry.auth_mode -eq "static" -and $entry.token) {$headers["Authorization"] = "Bearer $($entry.token)"}@@ -1014,7 +1015,11 @@ function Invoke-AiMemoryHook {if ($Agent -eq "devin") {$SessionQS = Get-AiMemorySessionIdQuery -Agent $Agent -Event $Event}+ # Every request names this client: an unauthenticated server reached+ # through a non-loopback host name refuses a handoff fetch without the+ # header, because a web page cannot add it to a request it makes.$Headers = @{}+ $Headers["X-AI-Memory-Client"] = "hook-ps"if ($env:AI_MEMORY_AUTH_TOKEN) {$Headers["Authorization"] = "Bearer $env:AI_MEMORY_AUTH_TOKEN"diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.shindex 75e26d40..57c2a184 100755--- a/tests/hooks/test_lib.sh+++ b/tests/hooks/test_lib.sh@@ -1075,6 +1075,72 @@ PS_BRIEF_STATIC=$(grep -Fq 'if ($Event -eq "session-start" -and -not $BriefingOn&& printf 'ok' || printf 'missing')assert_eq "powershell session-start handoff GET carries the briefing keys" "ok" "$PS_BRIEF_STATIC"+# --- client marker header on every request ------------------------------+# An unauthenticated server reached through a non-loopback host name refuses+# a handoff fetch without `X-AI-Memory-Client`, which a web page cannot add.+# Every curl branch (env token, header file, no auth) of the GET, the event+# POST and the spool drain must send it. The stub logs one line per request:+# "marked" or "UNMARKED".+curl() {+ _tmk=UNMARKED+ _tdata=""+ while [ "$#" -gt 0 ]; do+ case "$1" in+ -H) shift; [ "$#" -gt 0 ] || break+ [ "$1" = "X-AI-Memory-Client: hook-sh" ] && _tmk=marked ;;+ -X) shift ;;+ --data-binary) shift; [ "$#" -gt 0 ] || break; _tdata="$1" ;;+ esac+ shift+ done+ [ "$_tdata" = "@-" ] && cat >/dev/null+ printf '%s\n' "$_tmk" >>"$MARKER_LOG"+ printf '200'+ return 0+}+AI_MEMORY_DATA_DIR="$TMP/client-marker"+export AI_MEMORY_DATA_DIR+mkdir -p "$AI_MEMORY_DATA_DIR"+MARKER_LOG="$AI_MEMORY_DATA_DIR/marker.log"+: >"$MARKER_LOG"+marker_round() {+ # The hooks call it under `|| true`; without that, `set -e` stops at the+ # missing auth-header file lookup inside it.+ ai_memory_get_handoff "http://127.0.0.1:49374/handoff?agent=cursor" >/dev/null 2>&1 || true+ printf '%s' '{"e":"marker"}' \+ | ai_memory_post_hook "http://127.0.0.1:49374/hook?event=stop&agent=cursor" >/dev/null 2>&1+}+marker_round # no auth+(umask 077; printf 'Authorization: Bearer file-token\n' >"$AI_MEMORY_DATA_DIR/auth-header")+marker_round # header file+rm -f "$AI_MEMORY_DATA_DIR/auth-header"+ai_memory_spool_event "http://127.0.0.1:49374/hook?event=stop&agent=cursor" '{"e":"m1"}'+ai_memory_drain_spool 64 >/dev/null 2>&1 # drain without a token+AI_MEMORY_AUTH_TOKEN=env-token+export AI_MEMORY_AUTH_TOKEN+marker_round # env token+ai_memory_spool_event "http://127.0.0.1:49374/hook?event=stop&agent=cursor" '{"e":"m2"}'+unset AI_MEMORY_AUTH_TOKEN+ai_memory_drain_spool 64 >/dev/null 2>&1 # drain with the spooled token+unset -f curl+assert_eq "client marker: every curl branch was exercised" "yes" \+ "$([ "$(awk 'END { print NR + 0 }' "$MARKER_LOG")" -ge 8 ] && printf 'yes' || printf 'no')"+assert_eq "client marker: no request went out without it" "0" \+ "$(grep -c UNMARKED "$MARKER_LOG")"+unset AI_MEMORY_DATA_DIR++# The PowerShell helper builds its request headers in one hashtable per call+# site; each must carry the marker, and every Invoke-WebRequest must pass one.+PS_HELPER=hooks/lib/ai-memory-hook.ps1+PS_HEADER_TABLES=$(grep -Ec '^[[:space:]]*\$[Hh]eaders = @\{\}' "$PS_HELPER")+PS_MARKED_TABLES=$(grep -Ec '^[[:space:]]*\$[Hh]eaders\["X-AI-Memory-Client"\] = "hook-ps"' "$PS_HELPER")+PS_REQUESTS=$(grep -c 'Invoke-WebRequest `' "$PS_HELPER")+PS_REQUESTS_WITH_HEADERS=$(grep -A6 'Invoke-WebRequest `' "$PS_HELPER" | grep -Ec -- '-Headers \$[Hh]eaders')+assert_eq "powershell: header tables found" "yes" \+ "$([ "$PS_HEADER_TABLES" -ge 2 ] && printf 'yes' || printf 'no (%s)' "$PS_HEADER_TABLES")"+assert_eq "powershell: every header table carries the client marker" "$PS_HEADER_TABLES" "$PS_MARKED_TABLES"+assert_eq "powershell: every request passes the header table" "$PS_REQUESTS" "$PS_REQUESTS_WITH_HEADERS"+# A spooled fixture event names this run's temp tree or targets the fake# `memory.test` host. Live sessions share the spool and may mention that host# in their own payloads, where it is JSON-escaped, so match only the URL field.