Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
security: owner-guarded hook sessions, private file modes, fail-closed binds
AkitaOnRails1a5806e75c94
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a0dc3377..3f679f4b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,7 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]-### Fixed+### Added+- Added `[auth].secure_cookie` for HTTPS reverse-proxy deployments to mark+ `/web` browser authentication cookies `Secure` while preserving plain-HTTP+ loopback compatibility by default (<PR>).++### Changed+- Unauthenticated HTTP binds beyond loopback now fail closed before accepting+ requests. Intentional insecure LAN use requires `--allow-insecure-no-auth`;+ authenticated non-loopback HTTP remains available with its TLS warning+ (<PR>).++### Fixed+- Hook session UUIDs now reject cross-owner reuse atomically before ingest-key,+ observation, summary, handoff, or end-state mutation; explicit root+ `finalize-session --all-owners` recovery remains available (#security-audit).+- Newly created data directories, configuration files, SQLite databases,+ managed-workstream segments, and downloaded backups now receive owner-only+ Unix permissions before sensitive content is written, independent of the+ ambient umask. Existing installations are left unchanged; Windows relies on+ filesystem ACLs (#security-audit).- Under the `repo-root` project strategy, mid-session events whose cwd sitsoutside any git repository and any `.ai-memory.toml` marker (agent scratchdirectories, `/tmp`, data folders) now inherit the session's project insteaddiff --git a/README.md b/README.mdindex f3333078..289c2de3 100644--- a/README.md+++ b/README.md@@ -639,6 +639,14 @@ Loopback-only (`127.0.0.1:49374`) with no auth is the default becauseit is safe for a single-user laptop: no process outside the machine canreach the server.+Unauthenticated non-loopback HTTP now fails closed. Set+`AI_MEMORY_AUTH_TOKEN` or bind loopback; `--allow-insecure-no-auth` is an+intentional, dangerous exception for plain HTTP only. Authentication does not+encrypt bearer tokens: for LAN or remote access, use the ready+[Caddy](docker/compose.tls.caddy.yml) or+[Cloudflare Tunnel](docker/compose.tls.cloudflared.yml) templates described in+the [HTTPS reverse-proxy guide](docs/https-via-proxy.md).+Enable bearer auth when the server is exposed beyond loopback, whenuntrusted local processes share the machine, or when the data dir holdssensitive project history:@@ -662,7 +670,9 @@ ai-memory install-hooks --agent claude-code --apply \Bearer auth protects `/mcp`, `/hook`, `/handoff`, `/admin/*`, and`/web/*`. Browser access to `/web` uses HTTP Basic auth with the token-as the password. Non-loopback binds should also set+as the password. When `/web` is exposed through an HTTPS reverse proxy, set+`AI_MEMORY_AUTH__SECURE_COOKIE=true`; it makes the browser cookie HTTPS-only.+Close or redirect direct HTTP access to that hostname. Non-loopback binds should also set`AI_MEMORY_ALLOWED_HOSTS` to guard against DNS rebinding.Busy shared hook servers can also set `AI_MEMORY_HOOK_RATE_PER_SEC` (tokens perdiff --git a/SECURITY.md b/SECURITY.mdindex beb8f3c3..dd5131e8 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -21,7 +21,12 @@ what the project is and is not designed to defend against.- **Local data confidentiality.** Wiki files and the SQLite database liveunder a single data directory controlled by the operating-system user whoruns the server. We rely on filesystem permissions; no additional- encryption at rest is provided in v1.+ encryption at rest is provided in v1. On Unix, newly created data+ directories are owner-only (`0700`) and newly created configuration,+ SQLite, managed-workstream segment, and downloaded backup files are owner+ read/write only (`0600`), independent of umask. Existing installations are+ not chmodded automatically. Windows uses its filesystem ACLs rather than+ POSIX mode bits.- **Network exposure when binding to non-loopback addresses.** If you run`ai-memory serve --bind 0.0.0.0:…` you are exposing the MCP and admin@@ -30,8 +35,16 @@ what the project is and is not designed to defend against.checked on every request).- Firewall rules or a reverse proxy with TLS.- The server logs a loud warning if it detects a non-loopback bind without a- configured auth token.+ The server fails closed before serving unauthenticated non-loopback HTTP.+ `--allow-insecure-no-auth` is a deliberate dangerous override for an+ intentional plain-HTTP LAN deployment. Authentication does not encrypt+ bearer tokens, so use a TLS reverse proxy for traffic beyond loopback; see+ [`docs/https-via-proxy.md`](docs/https-via-proxy.md).++ For `/web` behind that proxy, set `AI_MEMORY_AUTH__SECURE_COOKIE=true` to+ make its browser session cookie HTTPS-only. ai-memory does not trust+ forwarded-protocol headers to decide this. Close or redirect direct HTTP+ access; browsers intentionally withhold Secure cookies over HTTP.- **Host-header DNS rebinding.** The HTTP server enforces an`AI_MEMORY_ALLOWED_HOSTS` allowlist (defaulting to `127.0.0.1` anddiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex dd14741b..26470549 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -1644,6 +1644,12 @@ pub struct ServeArgs {/// Bind address for `--transport http` (default: from config).#[arg(long)]pub bind: Option<String>,+ /// DANGEROUS: allow unauthenticated plain HTTP on a non-loopback bind.+ ///+ /// HTTP-only. Unnecessary for loopback binds; prefer AI_MEMORY_AUTH_TOKEN+ /// or a loopback bind instead.+ #[arg(long)]+ pub allow_insecure_no_auth: bool,/// Skip the filesystem watcher; useful for transient debugging.#[arg(long)]pub no_watcher: bool,@@ -1746,6 +1752,22 @@ mod tests {use clap::{CommandFactory, Parser};use std::collections::BTreeSet;+ #[test]+ fn serve_parses_insecure_no_auth_override() {+ let parsed = Cli::try_parse_from([+ "ai-memory",+ "serve",+ "--transport",+ "http",+ "--allow-insecure-no-auth",+ ])+ .expect("serve override parses");+ let Command::Serve(args) = parsed.command else {+ panic!("expected serve command");+ };+ assert!(args.allow_insecure_no_auth);+ }+#[test]fn finalize_session_parses_typed_id_and_rejects_ambiguous_selection() {let session_id = ai_memory_core::SessionId::new();diff --git a/crates/ai-memory-cli/src/commands/finalize_session.rs b/crates/ai-memory-cli/src/commands/finalize_session.rsindex 64d3057e..e02361ba 100644--- a/crates/ai-memory-cli/src/commands/finalize_session.rs+++ b/crates/ai-memory-cli/src/commands/finalize_session.rs@@ -82,6 +82,7 @@ pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {&workspace,&project,agent,+ args.all_owners,).await?;finalized.push(session.session_id.clone());@@ -165,6 +166,7 @@ fn print_report(Ok(())}+#[allow(clippy::too_many_arguments)]async fn post_session_end_batch(client: &reqwest::Client,endpoint: &ServerEndpoint,@@ -173,9 +175,10 @@ async fn post_session_end_batch(workspace: &str,project: &str,agent: AgentKind,+ all_owners: bool,) -> Result<()> {let cwd = session.cwd.as_deref().unwrap_or(fallback_cwd);- let hook_url = session_end_hook_url(endpoint, cwd, workspace, project, agent)?;+ let hook_url = session_end_hook_url(endpoint, cwd, workspace, project, agent, all_owners)?;let batch_url = endpoint.build_url("/hook/batch");let items = [HookBatchItem {url: hook_url,@@ -214,6 +217,7 @@ fn session_end_hook_url(workspace: &str,project: &str,agent: AgentKind,+ all_owners: bool,) -> Result<String> {let mut url = reqwest::Url::parse(&endpoint.build_url("/hook")).context("building synthetic session-end hook URL")?;@@ -223,6 +227,9 @@ fn session_end_hook_url(.append_pair("cwd", cwd).append_pair("workspace", workspace).append_pair("project", project);+ if all_owners {+ url.query_pairs_mut().append_pair("all_owners", "true");+ }Ok(url.into())}@@ -378,7 +385,37 @@ mod tests {}#[test]- fn synthetic_end_url_uses_requested_antigravity_agent() {+ fn synthetic_end_url_propagates_all_owners_once_when_requested() {+ let endpoint =+ ServerEndpoint::from_pair(Some("http://127.0.0.1:49374/base".to_string()), None);+ let url = session_end_hook_url(+ &endpoint,+ "/tmp/project",+ "default",+ "project",+ AgentKind::AntigravityCli,+ true,+ )+ .unwrap();+ let parsed = reqwest::Url::parse(&url).unwrap();+ let query: Vec<_> = parsed.query_pairs().into_owned().collect();++ assert_eq!(parsed.path(), "/base/hook");+ assert_eq!(+ query,+ vec![+ ("event".to_string(), "session-end".to_string()),+ ("agent".to_string(), "antigravity-cli".to_string()),+ ("cwd".to_string(), "/tmp/project".to_string()),+ ("workspace".to_string(), "default".to_string()),+ ("project".to_string(), "project".to_string()),+ ("all_owners".to_string(), "true".to_string()),+ ]+ );+ }++ #[test]+ fn synthetic_end_url_omits_all_owners_when_not_requested() {let endpoint =ServerEndpoint::from_pair(Some("http://127.0.0.1:49374/base".to_string()), None);let url = session_end_hook_url(@@ -387,18 +424,22 @@ mod tests {"default","project",AgentKind::AntigravityCli,+ false,).unwrap();let parsed = reqwest::Url::parse(&url).unwrap();- let query: std::collections::HashMap<_, _> = parsed.query_pairs().into_owned().collect();+ let query: Vec<_> = parsed.query_pairs().into_owned().collect();assert_eq!(parsed.path(), "/base/hook");- assert_eq!(query.get("event").map(String::as_str), Some("session-end"));assert_eq!(- query.get("agent").map(String::as_str),- Some("antigravity-cli")+ query,+ vec![+ ("event".to_string(), "session-end".to_string()),+ ("agent".to_string(), "antigravity-cli".to_string()),+ ("cwd".to_string(), "/tmp/project".to_string()),+ ("workspace".to_string(), "default".to_string()),+ ("project".to_string(), "project".to_string()),+ ]);- assert_eq!(query.get("workspace").map(String::as_str), Some("default"));- assert_eq!(query.get("project").map(String::as_str), Some("project"));}}diff --git a/crates/ai-memory-cli/src/commands/init.rs b/crates/ai-memory-cli/src/commands/init.rsindex d2fcf1e1..1e2423ad 100644--- a/crates/ai-memory-cli/src/commands/init.rs+++ b/crates/ai-memory-cli/src/commands/init.rs@@ -2,6 +2,8 @@use std::fs;use std::io::Write;+#[cfg(unix)]+use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _};use std::path::{Path, PathBuf};use anyhow::{Context, Result};@@ -31,7 +33,6 @@ fn render_default_auth_block(pepper: &str) -> String {# the first user is added** — rotating invalidates every existing# token. Only used when multi-user is enabled (at least one row in# the `users` table); single-user / bearer-only setups don't read it.-[auth]token_pepper = \"{pepper}\"# Multi-user attribution (all optional).@@ -70,11 +71,12 @@ token_pepper = \"{pepper}\"/// cannot be written.pub fn run(config: &Config, args: InitArgs, config_path: Option<&Path>) -> Result<()> {let root = &config.data_dir;- fs::create_dir_all(root).with_context(|| format!("creating data root {}", root.display()))?;+ create_private_dir_all(root)+ .with_context(|| format!("creating data root {}", root.display()))?;for sub in SUBDIRS {let path = root.join(sub);- fs::create_dir_all(&path).with_context(|| format!("creating {}", path.display()))?;+ create_private_dir_all(&path).with_context(|| format!("creating {}", path.display()))?;tracing::info!(path = %path.display(), "ensured directory");}@@ -86,7 +88,7 @@ pub fn run(config: &Config, args: InitArgs, config_path: Option<&Path>) -> Resul);} else {if let Some(parent) = cfg_path.parent() {- fs::create_dir_all(parent)+ create_private_dir_all(parent).with_context(|| format!("creating config dir {}", parent.display()))?;}// Pepper is generated NOW (not at first server start) so it's@@ -100,7 +102,7 @@ pub fn run(config: &Config, args: InitArgs, config_path: Option<&Path>) -> ResulDEFAULT_CONFIG_TOML,render_default_auth_block(&pepper));- let mut f = fs::File::create(&cfg_path)+ let mut f = private_config_file(&cfg_path, args.force).with_context(|| format!("creating {}", cfg_path.display()))?;f.write_all(body.as_bytes()).with_context(|| format!("writing {}", cfg_path.display()))?;@@ -111,6 +113,29 @@ pub fn run(config: &Config, args: InitArgs, config_path: Option<&Path>) -> ResulOk(())}+/// Create missing directory components with owner-only access without changing+/// the permissions of an existing installation.+fn create_private_dir_all(path: &Path) -> std::io::Result<()> {+ let mut builder = fs::DirBuilder::new();+ builder.recursive(true);+ #[cfg(unix)]+ builder.mode(0o700);+ builder.create(path)+}++/// Open a config file so a newly created file is private before its secret+/// token pepper is written. Forced rewrites preserve existing permissions.+fn private_config_file(path: &Path, force: bool) -> std::io::Result<fs::File> {+ let mut options = fs::OpenOptions::new();+ options.write(true).truncate(true).create(true);+ if !force {+ options.create_new(true);+ }+ #[cfg(unix)]+ options.mode(0o600);+ options.open(path)+}+fn init_config_path(data_dir: &Path, explicit: Option<&Path>) -> PathBuf {explicit.map(PathBuf::from)@@ -209,6 +234,10 @@ mod tests {.extract().expect("rendered config must round-trip via figment (full Config extract)");+ assert!(+ !loaded.auth.secure_cookie,+ "generated config must preserve direct loopback HTTP browser compatibility"+ );assert!(loaded.auth@@ -278,4 +307,31 @@ mod tests {"explicit --config must not also write data-dir config");}++ #[cfg(unix)]+ #[test]+ fn init_creates_private_directories_and_config() {+ use std::os::unix::fs::PermissionsExt as _;++ let tmp = TempDir::new().unwrap();+ let root = tmp.path().join("data");+ run(&cfg_in(&root), InitArgs { force: false }, None).unwrap();++ for path in std::iter::once(root.clone()).chain(SUBDIRS.iter().map(|sub| root.join(sub))) {+ assert_eq!(+ fs::metadata(&path).unwrap().permissions().mode() & 0o777,+ 0o700,+ "{}",+ path.display()+ );+ }+ assert_eq!(+ fs::metadata(root.join("config.toml"))+ .unwrap()+ .permissions()+ .mode()+ & 0o777,+ 0o600+ );+ }}diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 6e45eee7..b25c1d8d 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -1,6 +1,7 @@//! `ai-memory serve` — MCP server with optional filesystem watcher.use std::future::Future;+use std::net::SocketAddr;use std::path::Path;use std::sync::Arc;use std::time::Duration;@@ -93,6 +94,22 @@ fn configured(value: Option<&String>) -> bool {value.is_some_and(|v| !v.trim().is_empty())}+/// Refuse accidental unauthenticated network exposure after the listener has+/// selected its actual local address (which may differ from the bind input).+fn validate_http_exposure(+ local_addr: SocketAddr,+ auth_enabled: bool,+ allow_insecure_no_auth: bool,+) -> Result<()> {+ if local_addr.ip().is_loopback() || auth_enabled || allow_insecure_no_auth {+ return Ok(());+ }++ anyhow::bail!(+ "refusing unauthenticated plain HTTP on non-loopback address {local_addr}: anyone on the network could access ai-memory. Configure AI_MEMORY_AUTH_TOKEN or bind to a loopback address. For intentional LAN use, pass --allow-insecure-no-auth explicitly and review TLS options in docs/https-via-proxy.md."+ );+}+/// Validate the trusted proxy's least-privilege credential and optional stable/// root identity before binding the server.fn validate_trusted_proxy_auth(auth: &AuthSettings) -> Result<()> {@@ -654,7 +671,8 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {// the users-table lookup, including before the first user is// created. Admin mode separately switches on a fresh// store-backed users-exist read.- let mut auth_state = AuthState::new(config.auth.bearer_token.clone());+ let mut auth_state = AuthState::new(config.auth.bearer_token.clone())+ .with_secure_cookie(config.auth.secure_cookie);let root_user = config.auth.root_username@@ -765,24 +783,24 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {let listener = tokio::net::TcpListener::bind(&bind).await.with_context(|| format!("binding {bind}"))?;+ let local_addr = listener+ .local_addr()+ .context("reading bound HTTP listener address")?;+ validate_http_exposure(local_addr, auth_enabled, args.allow_insecure_no_auth)?;info!(- %bind,+ %local_addr,auth = auth_enabled,body_limit_mb = MAX_BODY_BYTES / 1024 / 1024,"MCP HTTP server ready (POST /mcp, POST /hook, Ctrl-C to stop)",);- if !auth_enabled && !bind.starts_with("127.") {- // Loud warning: a non-loopback bind with no auth is- // the audit's critical-#1 scenario. The operator gets- // a one-line "you sure?" instead of silent exposure.+ if !auth_enabled && !local_addr.ip().is_loopback() {tracing::warn!(- %bind,- "no AI_MEMORY_AUTH_TOKEN configured AND binding to a non-loopback \- address — anyone on the network can call destructive MCP tools. \- Generate a token with `ai-memory generate-auth-token` and set \- AI_MEMORY_AUTH_TOKEN in the server's environment."+ %local_addr,+ "starting unauthenticated plain HTTP on a non-loopback address because \+ --allow-insecure-no-auth was supplied — anyone on the network can call \+ destructive MCP tools");- } else if auth_enabled && !bind.starts_with("127.") {+ } else if auth_enabled && !local_addr.ip().is_loopback() {// Auth IS configured but the server is reachable from// the network on plain HTTP. The bearer token (and// multi-user per-user tokens from `ai-memory user@@ -791,7 +809,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {// log at startup, not refusal to serve (operators may// be testing, behind their own proxy already, etc.).tracing::warn!(- %bind,+ %local_addr,"AI_MEMORY_AUTH_TOKEN is set but the server is bound to a \non-loopback address on plain HTTP — bearer tokens travel \cleartext on the network. Front ai-memory with a TLS-terminating \@@ -1623,6 +1641,31 @@ mod tests {}}+ #[test]+ fn unauthenticated_non_loopback_http_requires_explicit_override() {+ let addresses = [+ ("127.0.0.1:49374", true),+ ("[::1]:49374", true),+ ("0.0.0.0:49374", false),+ ("[::]:49374", false),+ ("192.168.1.90:49374", false),+ ];++ for (address, loopback) in addresses {+ let local_addr: SocketAddr = address.parse().expect("valid test address");+ for auth_enabled in [false, true] {+ for allow_override in [false, true] {+ let allowed = loopback || auth_enabled || allow_override;+ assert_eq!(+ validate_http_exposure(local_addr, auth_enabled, allow_override).is_ok(),+ allowed,+ "address={address}, auth={auth_enabled}, override={allow_override}"+ );+ }+ }+ }+ }+#[test]fn trusted_proxy_configuration_requires_distinct_credentials() {let missing_root = AuthSettings {diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex e12eef46..69f7063e 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -399,13 +399,17 @@ where}/// `[auth]` section of `config.toml`.-#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[derive(Clone, Default, Serialize, Deserialize)]#[serde(default)]pub struct AuthSettings {/// Shared bearer token. When set, all HTTP routes require/// `Authorization: Bearer <token>`. Generate one with/// `ai-memory generate-auth-token`.pub bearer_token: Option<String>,+ /// Mark the browser session cookie `Secure`. Enable this only when a+ /// trusted reverse proxy terminates HTTPS for `/web`; direct HTTP browsers+ /// deliberately will not send a Secure cookie.+ pub secure_cookie: bool,/// Username attributed to writes authenticated by the bearer/// token (rung 1: "identified single-user"). When set, the/// auth middleware injects an@@ -450,6 +454,31 @@ pub struct AuthSettings {pub actor_proxy_bearer_token: Option<String>,}+impl std::fmt::Debug for AuthSettings {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("AuthSettings")+ .field(+ "bearer_token",+ &self.bearer_token.as_ref().map(|_| "<redacted>"),+ )+ .field("secure_cookie", &self.secure_cookie)+ .field("root_username", &self.root_username)+ .field("root_issuer", &self.root_issuer)+ .field("root_subject", &self.root_subject)+ .field("root_email", &self.root_email)+ .field("root_name", &self.root_name)+ .field(+ "token_pepper",+ &self.token_pepper.as_ref().map(|_| "<redacted>"),+ )+ .field(+ "actor_proxy_bearer_token",+ &self.actor_proxy_bearer_token.as_ref().map(|_| "<redacted>"),+ )+ .finish()+ }+}+/// `[auto_scope]` — controls how the hook-published "currently active/// project" pointer is shared across concurrent callers. The legacy default/// is `single` (process-wide slot, last-write-wins). Opt-in modes isolate@@ -1211,6 +1240,33 @@ mod tests {use secrecy::ExposeSecret;use tempfile::TempDir;+ #[test]+ fn auth_settings_debug_redacts_secrets_in_auth_and_config() {+ let auth = AuthSettings {+ bearer_token: Some("bearer-secret-sentinel".into()),+ root_username: Some("operator".into()),+ token_pepper: Some("pepper-secret-sentinel".into()),+ actor_proxy_bearer_token: Some("proxy-secret-sentinel".into()),+ ..AuthSettings::default()+ };+ let config = Config {+ auth: auth.clone(),+ ..Config::default()+ };++ for rendered in [format!("{auth:?}"), format!("{config:?}")] {+ assert!(rendered.contains("root_username: Some(\"operator\")"));+ assert!(rendered.contains("<redacted>"));+ for secret in [+ "bearer-secret-sentinel",+ "pepper-secret-sentinel",+ "proxy-secret-sentinel",+ ] {+ assert!(!rendered.contains(secret), "Debug output exposed {secret}");+ }+ }+ }+#[test]fn defaults_have_canonical_endings() {let cfg = Config::default();@@ -1218,6 +1274,7 @@ mod tests {assert_eq!(cfg.bind, DEFAULT_BIND);assert_eq!(cfg.server_url, DEFAULT_SERVER_URL);assert_eq!(cfg.log_level, "info");+ assert!(!cfg.auth.secure_cookie);assert!(cfg.maintenance.enabled);assert_eq!(cfg.maintenance.forget_sweep_interval_secs, 86_400);assert_eq!(cfg.maintenance.lint_interval_secs, 86_400);@@ -1440,6 +1497,9 @@ mod tests {hook_rate_per_sec = 7.5hook_rate_burst = 12.0+ [auth]+ secure_cookie = true+[maintenance]enabled = falselint_interval_secs = 3600@@ -1491,6 +1551,7 @@ mod tests {assert_eq!(cfg.log_level, "debug");assert_eq!(cfg.hook_rate_per_sec, 7.5);assert_eq!(cfg.hook_rate_burst, 12.0);+ assert!(cfg.auth.secure_cookie);assert!(!cfg.maintenance.enabled);assert_eq!(cfg.maintenance.lint_interval_secs, 3600);assert!(cfg.auto_improve.scheduler.enabled);diff --git a/crates/ai-memory-cli/src/http_client.rs b/crates/ai-memory-cli/src/http_client.rsindex fd3d445c..4aa1d342 100644--- a/crates/ai-memory-cli/src/http_client.rs+++ b/crates/ai-memory-cli/src/http_client.rs@@ -12,6 +12,8 @@use std::fmt;use std::io::{BufWriter, Write as _};+#[cfg(unix)]+use std::os::unix::fs::OpenOptionsExt as _;use std::path::Path;use anyhow::{Context, Result};@@ -398,7 +400,7 @@ pub async fn post_to_file(endpoint: &ServerEndpoint, path: &str, dest: &Path) ->let body = resp.text().await.unwrap_or_default();return Err(server_response_error(status, body));}- let file = std::fs::File::create(dest)+ let file = private_output_file(dest).with_context(|| format!("creating output file {}", dest.display()))?;let mut writer = BufWriter::new(file);let mut written = 0_u64;@@ -418,10 +420,35 @@ pub async fn post_to_file(endpoint: &ServerEndpoint, path: &str, dest: &Path) ->Ok(written)}+/// Open a downloaded backup output file with private permissions before the+/// first response bytes are written. Existing user-selected output files keep+/// their existing permissions when overwritten.+fn private_output_file(path: &Path) -> std::io::Result<std::fs::File> {+ let mut options = std::fs::OpenOptions::new();+ options.write(true).create(true).truncate(true);+ #[cfg(unix)]+ options.mode(0o600);+ options.open(path)+}+#[cfg(test)]mod tests {use super::*;+ #[cfg(unix)]+ #[test]+ fn downloaded_backup_output_is_private_when_created() {+ use std::os::unix::fs::PermissionsExt as _;++ let temp = tempfile::tempdir().unwrap();+ let output = temp.path().join("backup.tar.gz");+ private_output_file(&output).unwrap();+ assert_eq!(+ std::fs::metadata(output).unwrap().permissions().mode() & 0o777,+ 0o600+ );+ }+// ----------------------------------------------------------------// ServerEndpoint::from_pair// ----------------------------------------------------------------diff --git a/crates/ai-memory-cli/templates/config.default.toml b/crates/ai-memory-cli/templates/config.default.tomlindex 5afdeca0..49a72e62 100644--- a/crates/ai-memory-cli/templates/config.default.toml+++ b/crates/ai-memory-cli/templates/config.default.toml@@ -161,3 +161,10 @@ enabled = trueinterval_secs = 3600max_sessions_per_tick = 1 # per projectmin_session_age_secs = 600++# Browser session cookies are safe on plain loopback HTTP by default. For `/web`+# behind a trusted HTTPS-terminating reverse proxy, set this to true so browsers+# send the cookie only over HTTPS. Do not enable it for direct HTTP: browsers+# will not send a Secure cookie there.+[auth]+secure_cookie = falsediff --git a/crates/ai-memory-core/src/active_project.rs b/crates/ai-memory-core/src/active_project.rsindex 8e3aaae5..e0334bae 100644--- a/crates/ai-memory-core/src/active_project.rs+++ b/crates/ai-memory-core/src/active_project.rs@@ -94,6 +94,8 @@ pub enum ActiveProjectMode {}/// Composite identity used to key per-actor entries.+/// This cache key namespaces active-project pointers only; it does not+/// namespace durable hook `SessionId` records.////// - `PerSession` mode populates only `session_id`./// - `PerActor` mode populates both (`user` holds the qualified identity key:diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex 0899ed0b..f32d682b 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -83,6 +83,8 @@ pub struct HookQuery {/// clients; older servers ignore it — both directions keep today's/// behavior.pub ingest_key: Option<String>,+ /// Explicit root-only recovery propagation from `finalize-session --all-owners`.+ pub all_owners: Option<String>,}/// Coalesced view of an incoming hook event after light parsing of the@@ -118,6 +120,8 @@ pub struct HookEnvelope {/// router publishes it on the actor's `ActiveProject` so default-scoped/// read tools broaden to a global search.pub recall_default_global_requested: bool,+ /// Explicit cross-owner recovery request (never honored for ordinary hooks).+ pub all_owners_requested: bool,/// Invocation-scoped managed-run id forwarded by the host hook.pub managed_run: Option<String>,/// Optional third-party extension namespace.@@ -395,6 +399,7 @@ impl HookEnvelope {let project_strategy = ProjectStrategy::parse(query.project_strategy.as_deref());let drop_subagent_requested = query_flag_truthy(query.drop_subagent.as_deref());let recall_default_global_requested = query_flag_truthy(query.default_global.as_deref());+ let all_owners_requested = query_flag_truthy(query.all_owners.as_deref());let managed_run = query.managed_run.filter(|value| !value.trim().is_empty());let capture_assistant_requested = query_flag_truthy(query.capture_assistant.as_deref());let extension = normalize_extension_name(query.extension.as_deref());@@ -454,6 +459,7 @@ impl HookEnvelope {project_strategy,drop_subagent_requested,recall_default_global_requested,+ all_owners_requested,managed_run,capture_assistant_requested,ingest_key,diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex dd870a5c..6fcc2abf 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -19,7 +19,7 @@ use ai_memory_core::{ObservationKind, ProjectId, Sanitized, Sanitizer, SessionId, WorkspaceId, WorkstreamEvent,WorkstreamEventKind,};-use ai_memory_store::{IngestObservationOutcome, WriterHandle};+use ai_memory_store::{HookSessionAdmission, IngestObservationOutcome, StoreError, WriterHandle};use ai_memory_wiki::{AdmissionContext, AdmissionOp, Wiki};use axum::Json;use axum::Router;@@ -628,7 +628,14 @@ async fn handle_hook(}tokio::spawn(async move {let _permit = permit;- process_envelope(state, env, actor, skip_webhooks).await;+ process_envelope(+ state,+ env,+ actor,+ level_ext.map_or(ai_memory_core::AuthLevel::Anonymous, |v| v.0),+ skip_webhooks,+ )+ .await;});(StatusCode::ACCEPTED, "queued")}@@ -794,7 +801,23 @@ async fn handle_hook_batch(continue;}let _permit = permit;- if let Err(e) = process(&state, env, actor.clone(), skip_webhooks.clone()).await {+ if let Err(e) = process_authorized(+ &state,+ env,+ actor.clone(),+ level_ext.map_or(ai_memory_core::AuthLevel::Anonymous, |v| v.0),+ skip_webhooks.clone(),+ )+ .await+ {+ if matches!(+ e.downcast_ref::<StoreError>(),+ Some(StoreError::SessionCollision)+ ) {+ warn!("hook batch session collision/recovery rejection dropped");+ accepted_indices.push(idx);+ continue;+ }warn!(error = %e, accepted = accepted_indices.len(), "hook batch item failed; stopping (fail-fast)");return (StatusCode::OK,@@ -2095,10 +2118,18 @@ async fn process_envelope(state: Arc<HookState>,env: HookEnvelope,actor: Option<IdentityKey>,+ level: ai_memory_core::AuthLevel,skip_webhooks: Vec<String>,) {- if let Err(e) = process(&state, env, actor, skip_webhooks).await {- warn!(error = %e, "hook processing failed");+ if let Err(e) = process_authorized(&state, env, actor, level, skip_webhooks).await {+ if matches!(+ e.downcast_ref::<StoreError>(),+ Some(StoreError::SessionCollision)+ ) {+ warn!("hook session collision dropped");+ } else {+ warn!(error = %e, "hook processing failed");+ }}}@@ -2161,10 +2192,41 @@ fn publish_active_project_for_event(}}+#[cfg(test)]async fn process(state: &HookState,env: HookEnvelope,actor: Option<IdentityKey>,+ skip_webhooks: Vec<String>,+) -> anyhow::Result<()> {+ match process_authorized(+ state,+ env,+ actor,+ ai_memory_core::AuthLevel::Anonymous,+ skip_webhooks,+ )+ .await+ {+ // Match the asynchronous hook envelope: collisions are terminal+ // rejections, but fire-and-forget ingress acknowledges the delivery.+ Err(error)+ if matches!(+ error.downcast_ref::<StoreError>(),+ Some(StoreError::SessionCollision)+ ) =>+ {+ Ok(())+ }+ result => result,+ }+}++async fn process_authorized(+ state: &HookState,+ env: HookEnvelope,+ actor: Option<IdentityKey>,+ level: ai_memory_core::AuthLevel,// Admission webhooks this request opted out of (see `admission_skips`).// Empty for every caller with no HTTP request behind it.skip_webhooks: Vec<String>,@@ -2239,66 +2301,6 @@ async fn process(}};- if matches!(env.event, HookEvent::SessionEnd) {- match state- .reader- .session_end_disposition(session_id, ws, proj, env.agent)- .await?- {- ai_memory_store::SessionEndDisposition::Open => {}- ai_memory_store::SessionEndDisposition::DropInvalid => {- info!(- session = %session_id,- agent = %env.agent.as_str(),- "ignoring SessionEnd for missing, mismatched, or cross-agent session"- );- return Ok(());- }- ai_memory_store::SessionEndDisposition::AlreadyEnded => {- // End stamping and the legacy handoff commit atomically. A- // first delivery can still be cancelled after that transaction- // but before the wiki commit, durable LLM enqueue, or ingest-key- // completion. Re-run those idempotent tail effects before- // acknowledging the already-ended session.- let commit_msg = format!("repair session {}", short_id(&session_id.to_string()),);- match state.wiki.commit_all(&commit_msg) {- Ok(Some(oid)) => debug!(commit = %oid, "wiki recovery auto-commit"),- Ok(None) => debug!("wiki clean during SessionEnd recovery"),- Err(e) => warn!(error = %e, "SessionEnd recovery auto-commit failed"),- }- let observations = state.reader.observations_for_session(session_id).await?;- if !is_lifecycle_only_session(&observations) {- enqueue_session_end_consolidation(state, session_id, ws, proj).await?;- }- if let Some(key) = env.ingest_key {- let completed = state- .writer- .complete_observation_ingest_if_claimed(proj, key.clone())- .await?;- debug!(key, completed, "SessionEnd recovery ingest-key completion");- }- info!(- session = %session_id,- agent = %env.agent.as_str(),- "recovered tail effects for already-ended SessionEnd"- );- return Ok(());- }- // The agent resumed an ended session under the same id and kept- // working (issue #152). Run the full end path again — page- // rewrite, ended_at bump, handoff, opt-in LLM consolidation — so- // the resumed work reaches the compiled session page instead of- // living only in raw observations.- ai_memory_store::SessionEndDisposition::ReEndWithNewWork => {- info!(- session = %session_id,- agent = %env.agent.as_str(),- "SessionEnd re-ends a resumed session with new work; re-running end path"- );- }- }- }-// Hooks are fire-and-forget and may arrive out of order. Begin the// session idempotently before every observation so a resumed agent// session, or a prompt racing ahead of SessionStart, cannot trip the@@ -2310,66 +2312,112 @@ async fn process(// shared, as before. The same value owns the SessionEnd handoff below, so// the session and its baton can never disagree about who they belong to.let owner_stamp = owner_stamp_for_event(state, actor.as_ref()).await;- let new_session = NewSession {- id: session_id,- workspace_id: ws,- project_id: proj,- agent_kind: env.agent,- cwd: env.cwd.as_ref().map(std::path::PathBuf::from),- actor_user: owner_stamp.clone(),+ // A keyed event claims its project-scoped key in the same transaction as+ // the observation. A pending replay resumes the downstream wiki/handoff+ // effects without duplicating the observation; only a delivery whose+ // effects were marked complete is skipped.+ let ingest_key = env.ingest_key.clone();+ let owner_filter = if env.all_owners_requested {+ if !matches!(env.event, HookEvent::SessionEnd) {+ return Err(StoreError::SessionCollision.into());+ }+ let distinguishes = state+ .reader+ .distinguishes_operators(state.trusted_proxy_identity)+ .await?;+ if level+ .authorize(ai_memory_core::Capability::Admin, distinguishes)+ .is_err()+ {+ return Err(StoreError::SessionCollision.into());+ }+ ai_memory_core::OwnerFilter::Any+ } else {+ actor+ .as_ref()+ .map_or(ai_memory_core::OwnerFilter::Unattributed, |id| {+ ai_memory_core::OwnerFilter::User(id.storage_key())+ })};- if let Err(e) = state.writer.begin_session(new_session).await {- // The cached (workspace, project) may have been deleted out from- // under us — e.g. `purge-project` on a live server drops the row- // but leaves this in-memory cache pointing at the old id, so- // begin_session trips the project foreign key. Evict the stale- // slot, re-resolve (which recreates the project), and retry once.- warn!(error = %e, "begin_session failed; evicting stale project cache and retrying");- let cwd_norm = env- .cwd- .as_deref()- .filter(|s| !s.is_empty())- .map(normalize_project_path_key);- let key = cache_key_for(- cwd_norm.as_deref(),- env.workspace_override.as_deref(),- env.project_override.as_deref(),- env.project_strategy,- );- state.project_cache.lock().await.remove(&key);- let refreshed = resolve_project_ids_inner(- state,- env.cwd.as_deref(),- env.workspace_override.as_deref(),- env.project_override.as_deref(),- env.project_strategy,- )- .await?;- ws = refreshed.0;- proj = refreshed.1;- state+ let cwd_norm = env+ .cwd+ .as_deref()+ .filter(|value| !value.is_empty())+ .map(normalize_project_path_key);+ let cache_key = cache_key_for(+ cwd_norm.as_deref(),+ env.workspace_override.as_deref(),+ env.project_override.as_deref(),+ env.project_strategy,+ );+ let mut attempts = 0;+ // Keep the successful keyed-ingest gate until every downstream effect has+ // completed. A replay that observes `ResumePending` must not race the first+ // delivery's page, handoff, consolidation, or key-completion tail.+ let (admission, log_title, _ingest_guard) = loop {+ // Rebuild both records on retry: the store validates and persists this+ // exact scope pair atomically with the keyed observation claim.+ let new_session = NewSession {+ id: session_id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: env.agent,+ cwd: env.cwd.as_ref().map(std::path::PathBuf::from),+ actor_user: owner_stamp.clone(),+ };+ let kind = env.event.to_observation_kind();+ let raw_obs = NewObservation {+ session_id,+ workspace_id: ws,+ project_id: proj,+ kind,+ extension: env.extension.clone(),+ source_event: env.source_event.clone(),+ title: env+ .title_hint+ .clone()+ .unwrap_or_else(|| kind.as_str().to_string()),+ body: env.body_excerpt.clone().unwrap_or_default(),+ importance: importance_for(env.event),+ };+ let sanitized = Sanitized::new(raw_obs, &state.sanitizer);+ let log_title = sanitized.inner().title.clone();+ let ingest_guard = if let Some(key) = ingest_key.as_deref() {+ Some(state.ingest_gates.lock(proj, key).await)+ } else {+ None+ };+ let result = state.writer- .begin_session(NewSession {- id: session_id,- workspace_id: ws,- project_id: proj,- agent_kind: env.agent,- cwd: env.cwd.as_ref().map(std::path::PathBuf::from),- actor_user: owner_stamp.clone(),- })- .await?;- }-- if publishable_scope {- publish_active_project_for_event(- state,- env.event,- &actor_key,- ws,- proj,- env.recall_default_global_requested,- );- }+ .admit_hook_session_event(+ new_session,+ sanitized,+ owner_filter.clone(),+ ingest_key.clone(),+ )+ .await;+ match result {+ Ok(admission) => break (admission, log_title, ingest_guard),+ Err(error) if attempts == 0 && error.is_stale_session_scope_reference() => {+ // Do not hold an old-project gate while resolving and acquiring+ // the refreshed scope's gate; that would permit nested gates.+ drop(ingest_guard);+ attempts += 1;+ warn!(error = %error, "hook admission used a stale project cache entry; evicting and retrying once");+ state.project_cache.lock().await.remove(&cache_key);+ (ws, proj) = resolve_project_ids_inner(+ state,+ env.cwd.as_deref(),+ env.workspace_override.as_deref(),+ env.project_override.as_deref(),+ env.project_strategy,+ )+ .await?;+ }+ Err(error) => return Err(error.into()),+ }+ };+ // Admission is the first mutation/effect after scope resolution.// `AI_MEMORY_RUN_ID` is invocation-scoped. A valid active run links the// native session and switches only this hook invocation to managed@@ -2383,6 +2431,48 @@ async fn process(}).ok()});+ let (admitted, ingest) = match admission {+ HookSessionAdmission::InvalidMissingEnd => {+ info!(session = %session_id, "ignoring missing SessionEnd");+ return Ok(());+ }+ HookSessionAdmission::AlreadyEnded { session } => {+ let commit_msg = format!("repair session {}", short_id(&session_id.to_string()));+ match state.wiki.commit_all(&commit_msg) {+ Ok(Some(oid)) => debug!(commit = %oid, "wiki recovery auto-commit"),+ Ok(None) => debug!("wiki clean during SessionEnd recovery"),+ Err(e) => warn!(error = %e, "SessionEnd recovery auto-commit failed"),+ }+ let observations = state.reader.observations_for_session(session_id).await?;+ if !is_lifecycle_only_session(&observations) {+ enqueue_session_end_consolidation(+ state,+ session_id,+ session.workspace_id(),+ session.project_id(),+ )+ .await?;+ }+ if let Some(key) = ingest_key {+ let _ = state+ .writer+ .complete_observation_ingest_if_claimed(session.project_id(), key)+ .await?;+ }+ return Ok(());+ }+ HookSessionAdmission::Observation { session, ingest }+ | HookSessionAdmission::EndOpen { session, ingest }+ | HookSessionAdmission::ReEnd { session, ingest } => (session, ingest),+ };+ if ingest == IngestObservationOutcome::AlreadyComplete {+ return Ok(());+ }+ if ingest == IngestObservationOutcome::ResumePending {+ debug!("resuming incomplete keyed hook event");+ }+ ws = admitted.workspace_id();+ proj = admitted.project_id();if let Some(run_id) = managed_run&& let Some(native_session_id) = env.session_id@@ -2394,57 +2484,15 @@ async fn process(.link_managed_run_session(run_id, env.agent, native_session_id).await?;}-- // Persist the observation row.- let kind = env.event.to_observation_kind();- let title = env- .title_hint- .clone()- .unwrap_or_else(|| kind.as_str().to_string());- let body = env.body_excerpt.clone().unwrap_or_default();- let raw_obs = NewObservation {- session_id,- workspace_id: ws,- project_id: proj,- kind,- extension: env.extension.clone(),- source_event: env.source_event.clone(),- title,- body,- importance: importance_for(env.event),- };- // The store boundary takes `Sanitized<NewObservation>` directly — no- // unwrap-and-clone; the type proves the scrub happened. The log line- // below wants the scrubbed title, so keep a copy before the move.- let sanitized = Sanitized::new(raw_obs, &state.sanitizer);- let log_title = sanitized.inner().title.clone();- // A keyed event claims its project-scoped key in the same transaction as- // the observation. A pending replay resumes the downstream wiki/handoff- // effects without duplicating the observation; only a delivery whose- // effects were marked complete is skipped.- let ingest_key = env.ingest_key.clone();- let _ingest_guard = if let Some(key) = ingest_key.as_deref() {- Some(state.ingest_gates.lock(proj, key).await)- } else {- None- };- if let Some(key) = ingest_key.as_ref() {- match state- .writer- .insert_observation_ingest(sanitized, key.clone())- .await?- {- IngestObservationOutcome::Inserted(_) => {}- IngestObservationOutcome::ResumePending => {- debug!(key, "resuming incomplete keyed hook event");- }- IngestObservationOutcome::AlreadyComplete => {- debug!(key, "completed ingest_key replay; skipping event");- return Ok(());- }- }- } else {- let _ = state.writer.insert_observation(sanitized).await?;+ if publishable_scope {+ publish_active_project_for_event(+ state,+ env.event,+ &actor_key,+ ws,+ proj,+ env.recall_default_global_requested,+ );}// Append the log line to the per-project log.md.@@ -2481,7 +2529,7 @@ async fn process(// and current actorless sessions use the same value; attributing either to// whoever delivers SessionEnd would silently rebucket shared context. A// store failure aborts this event rather than guessing an owner.- let session_owner = parse_session_owner(state.reader.session_actor_user(session_id).await?)?;+ let session_owner = parse_session_owner(admitted.owner().map(str::to_owned))?;let session_actor = session_owner.as_ref().map(IdentityKey::to_actor_context)@@ -2505,7 +2553,10 @@ async fn process(if matches!(env.event, HookEvent::SessionEnd) {let mut observations = state.reader.observations_for_session(session_id).await?;if is_lifecycle_only_session(&observations) {- let outcome = state.writer.end_lifecycle_only_session(session_id).await?;+ let outcome = state+ .writer+ .end_admitted_lifecycle_only_session(admitted.clone())+ .await?;match outcome {ai_memory_store::LifecycleOnlyEndOutcome::Ended { reopened_handoff } => {let commit_msg = format!(@@ -2631,11 +2682,14 @@ async fn process(Some(handoff) => Some(state.writer- .end_session_with_handoff(session_id, Some(page_id), handoff)+ .end_admitted_session_with_handoff(admitted.clone(), Some(page_id), handoff).await?,),None => {- state.writer.end_session(session_id, Some(page_id)).await?;+ state+ .writer+ .end_admitted_session(admitted.clone(), Some(page_id))+ .await?;None}};@@ -6127,81 +6181,700 @@ mod tests {}#[tokio::test]- async fn process_self_heal_evicts_project_strategy_cache_slot() {+ async fn session_collision_does_not_evict_or_retry_project_cache() {let tmp = TempDir::new().unwrap();- let state = make_state(&tmp).await;+ let mut state = make_state(&tmp).await;+ state.trusted_proxy_identity = true;+ let cwd = "/home/user/collision-project";+ let alice = Some(IdentityKey::User("alice".into()));+ let bob = Some(IdentityKey::User("bob".into()));- let repo_dir = tmp.path().join("repo-root-project");- init_repo_with_commit(&repo_dir);- let app_dir = repo_dir.join("app");- std::fs::create_dir_all(&app_dir).unwrap();- let cwd = app_dir.to_str().unwrap();+ let mut alice_event = session_envelope("user-prompt-submit", "collision-session", cwd);+ alice_event.ingest_key = Some("alice-event".into());+ process(&state, alice_event, alice, Vec::new())+ .await+ .unwrap();- let env1 = HookEnvelope::from_query_and_body(- HookQuery {- event: "user-prompt".into(),- agent: Some("claude-code".into()),- cwd: Some(cwd.into()),- project_strategy: Some("repo-root".into()),- ..Default::default()- },- serde_json::json!({ "sessionID": "heal-repo-root-1" }),- );- process(&state, env1, None, Vec::new()).await.unwrap();- let (ws, proj) = resolve_project_ids(+ let (cached_ws, cached_proj) = resolve_project_ids(&state,Some(cwd),- None,- None,- ProjectStrategy::RepoRoot,+ Some("default"),+ Some("scratch"),+ ProjectStrategy::Basename,&ai_memory_core::ActorKey::default(),).await.unwrap();-- state- .writer- .purge_project(ws, proj, "default/repo-root-project", None, false)+ let session_id = resolve_session_id(&session_envelope(+ "user-prompt-submit",+ "collision-session",+ cwd,+ ))+ .unwrap();+ let observations_before = state+ .reader+ .observations_for_session(session_id).await.unwrap();- let env2 = HookEnvelope::from_query_and_body(- HookQuery {- event: "user-prompt".into(),- agent: Some("claude-code".into()),- cwd: Some(cwd.into()),- project_strategy: Some("repo-root".into()),- ..Default::default()- },- serde_json::json!({ "sessionID": "heal-repo-root-2" }),- );- process(&state, env2, None, Vec::new())- .await- .expect("repo-root cache slot must be evicted and recreated");-- let (_, proj_new) = resolve_project_ids(+ let mut bob_event = session_envelope("user-prompt-submit", "collision-session", cwd);+ bob_event.ingest_key = Some("bob-event".into());+ let error = process_authorized(&state,- Some(cwd),- None,- None,- ProjectStrategy::RepoRoot,- &ai_memory_core::ActorKey::default(),+ bob_event,+ bob,+ ai_memory_core::AuthLevel::Anonymous,+ Vec::new(),).await- .unwrap();- assert_ne!(proj_new, proj);+ .unwrap_err();+ assert!(matches!(+ error.downcast_ref::<StoreError>(),+ Some(StoreError::SessionCollision)+ ));++ let cache_key = cache_key_for(+ Some(&normalize_project_path_key(cwd)),+ Some("default"),+ Some("scratch"),+ ProjectStrategy::Basename,+ );+ let mut cache = state.project_cache.lock().await;+ assert_eq!(cache.get(&cache_key), Some((cached_ws, cached_proj)));+ drop(cache);+ assert_eq!(+ state.reader.find_session_scope(session_id).await.unwrap(),+ Some((cached_ws, cached_proj, Some(cwd.into()))),+ "the existing session must not be replaced or moved"+ );+ assert_eq!(+ state+ .reader+ .observations_for_session(session_id)+ .await+ .unwrap()+ .len(),+ observations_before.len(),+ "the rejected delivery must not insert an observation or ingest key"+ );}- /// A hook event fires end-to-end through `process`. Validates that- /// the session + observation rows land in the resolved project, not- /// the server-default scratch project.+ /// A rejected foreign delivery must stop at the store admission boundary:+ /// it cannot create any router-side artifact or claim its key.#[tokio::test]- async fn process_routes_observation_to_cwd_project() {+ async fn foreign_prompt_is_a_terminal_collision_without_router_side_effects() {let tmp = TempDir::new().unwrap();- let state = make_state(&tmp).await;+ let mut state = make_state(&tmp).await;+ state.trusted_proxy_identity = true;+ let alice = Some(IdentityKey::User("alice".into()));+ let bob = Some(IdentityKey::User("bob".into()));+ let mut first = session_envelope("user-prompt-submit", "owned-prompt", "/tmp/scratch");+ first.ingest_key = Some("alice-prompt".into());+ process(&state, first, alice, Vec::new()).await.unwrap();+ let session_id = resolve_session_id(&session_envelope(+ "user-prompt-submit",+ "owned-prompt",+ "/tmp/scratch",+ ))+ .unwrap();+ let observations = state+ .reader+ .observations_for_session(session_id)+ .await+ .unwrap();+ let pages = session_pages(&state).await;+ let active = state.active_project.get();+ let run = state+ .writer+ .prepare_workstream_run(PrepareWorkstreamRun {+ workspace_id: state.workspace_id,+ project_id: state.project_id,+ repo_fingerprint: "collision-repo".into(),+ worktree_fingerprint: "collision-worktree".into(),+ cwd: "/tmp/scratch".into(),+ agent: AgentKind::ClaudeCode,+ automatic_harness: false,+ available_agents: Vec::new(),+ selection: WorkstreamSelection::Current,+ lease_owner: "test:collision".into(),+ })+ .await+ .unwrap();- let env = HookEnvelope::from_query_and_body(- HookQuery {+ let mut foreign = session_envelope("user-prompt-submit", "owned-prompt", "/tmp/scratch");+ foreign.ingest_key = Some("bob-must-not-claim".into());+ foreign.managed_run = Some(run.run_id.to_string());+ let error = process_authorized(+ &state,+ foreign,+ bob,+ ai_memory_core::AuthLevel::User,+ Vec::new(),+ )+ .await+ .unwrap_err();+ assert!(matches!(+ error.downcast_ref::<StoreError>(),+ Some(StoreError::SessionCollision)+ ));+ assert!(+ !error.to_string().contains("alice"),+ "collision must not disclose the owner"+ );+ assert_eq!(+ state+ .reader+ .observations_for_session(session_id)+ .await+ .unwrap()+ .len(),+ observations.len()+ );+ assert_eq!(session_pages(&state).await, pages);+ assert_eq!(state.active_project.get(), active);+ assert!(!open_handoff_exists(&state).await);+ assert!(+ state+ .reader+ .managed_run_status(run.run_id)+ .await+ .unwrap()+ .unwrap()+ .native_session_id+ .is_none(),+ "rejected delivery linked Alice's native session to Bob's run"+ );+ assert!(+ matches!(+ state+ .writer+ .insert_observation_ingest(+ Sanitized::new(+ NewObservation {+ session_id,+ workspace_id: state.workspace_id,+ project_id: state.project_id,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "probe".into(),+ body: String::new(),+ importance: 1,+ },+ &state.sanitizer+ ),+ "bob-must-not-claim".into(),+ )+ .await+ .unwrap(),+ IngestObservationOutcome::Inserted(_)+ ),+ "foreign delivery must not claim its ingest key"+ );+ }++ #[tokio::test]+ async fn foreign_session_end_and_reend_are_terminal_collisions() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.trusted_proxy_identity = true;+ let alice = Some(IdentityKey::User("alice".into()));+ let bob = Some(IdentityKey::User("bob".into()));+ process(+ &state,+ session_envelope("user-prompt-submit", "owned-end", "/tmp/scratch"),+ alice.clone(),+ Vec::new(),+ )+ .await+ .unwrap();+ let sid = resolve_session_id(&session_envelope(+ "session-end",+ "owned-end",+ "/tmp/scratch",+ ))+ .unwrap();+ let before = state+ .reader+ .observations_for_session(sid)+ .await+ .unwrap()+ .len();+ let err = process_authorized(+ &state,+ session_envelope("session-end", "owned-end", "/tmp/scratch"),+ bob.clone(),+ ai_memory_core::AuthLevel::User,+ Vec::new(),+ )+ .await+ .unwrap_err();+ assert!(matches!(+ err.downcast_ref::<StoreError>(),+ Some(StoreError::SessionCollision)+ ));+ assert_eq!(+ state+ .reader+ .observations_for_session(sid)+ .await+ .unwrap()+ .len(),+ before+ );+ assert!(+ state+ .reader+ .latest_completed_session_for_project(state.workspace_id, state.project_id)+ .await+ .unwrap()+ .is_none()+ );++ process(+ &state,+ session_envelope("session-end", "owned-end", "/tmp/scratch"),+ alice.clone(),+ Vec::new(),+ )+ .await+ .unwrap();+ process(+ &state,+ session_envelope("user-prompt-submit", "owned-end", "/tmp/scratch"),+ alice,+ Vec::new(),+ )+ .await+ .unwrap();+ let resumed_count = state+ .reader+ .observations_for_session(sid)+ .await+ .unwrap()+ .len();+ let handoff_count = state+ .reader+ .briefing_for_project(+ state.workspace_id,+ state.project_id,+ 1,+ ai_memory_core::OwnerFilter::Any,+ )+ .await+ .unwrap()+ .pending_handoff_count;+ let page_path = ai_memory_core::PagePath::new(format!("sessions/{sid}.md")).unwrap();+ let page_before = state+ .reader+ .recent_pages_for_project(state.workspace_id, state.project_id, 20)+ .await+ .unwrap()+ .into_iter()+ .find(|page| page.path == page_path)+ .expect("Alice's first end wrote a session page");+ let body_before = state+ .wiki+ .read_page(state.workspace_id, state.project_id, &page_path)+ .unwrap()+ .body;+ let err = process_authorized(+ &state,+ session_envelope("session-end", "owned-end", "/tmp/scratch"),+ bob,+ ai_memory_core::AuthLevel::User,+ Vec::new(),+ )+ .await+ .unwrap_err();+ assert!(matches!(+ err.downcast_ref::<StoreError>(),+ Some(StoreError::SessionCollision)+ ));+ assert_eq!(+ state+ .reader+ .observations_for_session(sid)+ .await+ .unwrap()+ .len(),+ resumed_count+ );+ assert_eq!(+ state+ .reader+ .briefing_for_project(+ state.workspace_id,+ state.project_id,+ 1,+ ai_memory_core::OwnerFilter::Any+ )+ .await+ .unwrap()+ .pending_handoff_count,+ handoff_count+ );+ let page_after = state+ .reader+ .recent_pages_for_project(state.workspace_id, state.project_id, 20)+ .await+ .unwrap()+ .into_iter()+ .find(|page| page.path == page_path)+ .expect("foreign re-end must not remove Alice's page");+ assert_eq!(page_after.id, page_before.id);+ assert_eq!(+ state+ .wiki+ .read_page(state.workspace_id, state.project_id, &page_path)+ .unwrap()+ .body,+ body_before,+ "foreign re-end rewrote Alice's session summary"+ );+ }++ #[tokio::test]+ async fn all_owners_recovery_is_root_session_end_only() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.trusted_proxy_identity = true;+ let alice = Some(IdentityKey::User("alice".into()));+ process(+ &state,+ session_envelope("user-prompt-submit", "recover-owned", "/tmp/scratch"),+ alice,+ Vec::new(),+ )+ .await+ .unwrap();+ let mut end = session_envelope("session-end", "recover-owned", "/tmp/scratch");+ end.all_owners_requested = true;+ process_authorized(+ &state,+ end,+ Some(IdentityKey::User("root".into())),+ ai_memory_core::AuthLevel::Root,+ Vec::new(),+ )+ .await+ .unwrap();+ let handoff = state+ .reader+ .latest_open_handoff(+ state.workspace_id,+ state.project_id,+ None,+ ai_memory_core::OwnerFilter::Any,+ )+ .await+ .unwrap()+ .unwrap();+ assert_eq!(handoff.owner_user.as_deref(), Some("user:alice"));++ let no_flag = session_envelope("session-end", "recover-owned", "/tmp/scratch");+ let error = process_authorized(+ &state,+ no_flag,+ Some(IdentityKey::User("root".into())),+ ai_memory_core::AuthLevel::Root,+ Vec::new(),+ )+ .await+ .unwrap_err();+ assert!(matches!(+ error.downcast_ref::<StoreError>(),+ Some(StoreError::SessionCollision)+ ));+ let mut forbidden = session_envelope("session-end", "recover-owned", "/tmp/scratch");+ forbidden.all_owners_requested = true;+ let error = process_authorized(+ &state,+ forbidden,+ Some(IdentityKey::User("bob".into())),+ ai_memory_core::AuthLevel::User,+ Vec::new(),+ )+ .await+ .unwrap_err();+ assert!(matches!(+ error.downcast_ref::<StoreError>(),+ Some(StoreError::SessionCollision)+ ));+ let mut non_end = session_envelope("user-prompt-submit", "recover-owned", "/tmp/scratch");+ non_end.all_owners_requested = true;+ let error = process_authorized(+ &state,+ non_end,+ Some(IdentityKey::User("root".into())),+ ai_memory_core::AuthLevel::Root,+ Vec::new(),+ )+ .await+ .unwrap_err();+ assert!(matches!(+ error.downcast_ref::<StoreError>(),+ Some(StoreError::SessionCollision)+ ));+ }++ #[tokio::test]+ async fn batch_acknowledges_foreign_collision_then_commits_next_item() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.trusted_proxy_identity = true;+ process(+ &state,+ session_envelope("user-prompt-submit", "batch-owned", "/tmp/scratch"),+ Some(IdentityKey::User("alice".into())),+ Vec::new(),+ )+ .await+ .unwrap();+ let owned = resolve_session_id(&session_envelope(+ "user-prompt-submit",+ "batch-owned",+ "/tmp/scratch",+ ))+ .unwrap();+ let owned_before = state+ .reader+ .observations_for_session(owned)+ .await+ .unwrap()+ .len();+ let state = Arc::new(state);+ let items = vec![+ HookBatchItem {+ url: "http://h/hook?event=user-prompt-submit&agent=claude-code".into(),+ body: serde_json::json!({"session_id":"batch-owned", "prompt":"foreign"}),+ },+ HookBatchItem {+ url: "http://h/hook?event=user-prompt-submit&agent=claude-code".into(),+ body: serde_json::json!({"session_id":"batch-valid", "prompt":"valid"}),+ },+ ];+ let response = handle_hook_batch(+ State(state.clone()),+ Some(axum::Extension(+ IdentityKey::User("bob".into()).to_actor_context(),+ )),+ Some(axum::Extension(ai_memory_core::AuthLevel::User)),+ HeaderMap::new(),+ Json(items),+ )+ .await+ .into_response();+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(ack["accepted"], 2, "both contiguous entries are cleared");+ assert!(ack.get("accepted_indices").is_none() || ack["accepted_indices"].is_null());+ assert!(ack.get("failed_index").is_none() || ack["failed_index"].is_null());+ assert_eq!(+ state+ .reader+ .observations_for_session(owned)+ .await+ .unwrap()+ .len(),+ owned_before,+ "the acknowledged collision must not mutate batch-owned"+ );+ let valid = resolve_session_id(&session_envelope(+ "user-prompt-submit",+ "batch-valid",+ "/tmp/scratch",+ ))+ .unwrap();+ assert_eq!(+ state+ .reader+ .observations_for_session(valid)+ .await+ .unwrap()+ .len(),+ 1+ );+ }++ #[tokio::test]+ async fn missing_session_end_is_a_no_op_and_single_hook_acknowledges_foreign_collision() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.trusted_proxy_identity = true;+ let missing = resolve_session_id(&session_envelope(+ "session-end",+ "missing-end",+ "/tmp/scratch",+ ))+ .unwrap();+ process_authorized(+ &state,+ session_envelope("session-end", "missing-end", "/tmp/scratch"),+ None,+ ai_memory_core::AuthLevel::Anonymous,+ Vec::new(),+ )+ .await+ .unwrap();+ assert!(+ state+ .reader+ .observations_for_session(missing)+ .await+ .unwrap()+ .is_empty()+ );++ process(+ &state,+ session_envelope("user-prompt-submit", "async-owned", "/tmp/scratch"),+ Some(IdentityKey::User("alice".into())),+ Vec::new(),+ )+ .await+ .unwrap();+ let sid = resolve_session_id(&session_envelope(+ "user-prompt-submit",+ "async-owned",+ "/tmp/scratch",+ ))+ .unwrap();+ let before = state+ .reader+ .observations_for_session(sid)+ .await+ .unwrap()+ .len();+ let state = Arc::new(state);+ let response = handle_hook(+ State(state.clone()),+ Query(HookQuery {+ event: "user-prompt-submit".into(),+ agent: Some("claude-code".into()),+ cwd: Some("/tmp/scratch".into()),+ workspace: Some("default".into()),+ project: Some("scratch".into()),+ ..Default::default()+ }),+ Some(axum::Extension(+ IdentityKey::User("bob".into()).to_actor_context(),+ )),+ Some(axum::Extension(ai_memory_core::AuthLevel::User)),+ HeaderMap::new(),+ Json(serde_json::json!({"session_id":"async-owned", "prompt":"foreign"})),+ )+ .await+ .into_response();+ assert_eq!(response.status(), StatusCode::ACCEPTED);+ // The background worker holds one ingress permit through processing.+ // Acquiring the entire pool is therefore a bounded, deterministic join+ // point without instrumenting production collision handling.+ let deadline = std::time::Instant::now() + Duration::from_secs(2);+ let _all_permits = loop {+ if let Ok(permits) = state+ .ingest_semaphore+ .clone()+ .try_acquire_many_owned(DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT as u32)+ {+ break permits;+ }+ assert!(+ std::time::Instant::now() < deadline,+ "asynchronous hook worker did not finish"+ );+ tokio::task::yield_now().await;+ };+ assert_eq!(+ state+ .reader+ .observations_for_session(sid)+ .await+ .unwrap()+ .len(),+ before,+ "foreign asynchronous hook inserted an observation"+ );+ }++ #[tokio::test]+ async fn process_self_heal_evicts_project_strategy_cache_slot() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;++ let repo_dir = tmp.path().join("repo-root-project");+ init_repo_with_commit(&repo_dir);+ let app_dir = repo_dir.join("app");+ std::fs::create_dir_all(&app_dir).unwrap();+ let cwd = app_dir.to_str().unwrap();++ let env1 = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "user-prompt".into(),+ agent: Some("claude-code".into()),+ cwd: Some(cwd.into()),+ project_strategy: Some("repo-root".into()),+ ..Default::default()+ },+ serde_json::json!({ "sessionID": "heal-repo-root-1" }),+ );+ process(&state, env1, None, Vec::new()).await.unwrap();+ let (ws, proj) = resolve_project_ids(+ &state,+ Some(cwd),+ None,+ None,+ ProjectStrategy::RepoRoot,+ &ai_memory_core::ActorKey::default(),+ )+ .await+ .unwrap();++ state+ .writer+ .purge_project(ws, proj, "default/repo-root-project", None, false)+ .await+ .unwrap();++ let env2 = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "user-prompt".into(),+ agent: Some("claude-code".into()),+ cwd: Some(cwd.into()),+ project_strategy: Some("repo-root".into()),+ ..Default::default()+ },+ serde_json::json!({ "sessionID": "heal-repo-root-2" }),+ );+ process(&state, env2, None, Vec::new())+ .await+ .expect("repo-root cache slot must be evicted and recreated");++ let (_, proj_new) = resolve_project_ids(+ &state,+ Some(cwd),+ None,+ None,+ ProjectStrategy::RepoRoot,+ &ai_memory_core::ActorKey::default(),+ )+ .await+ .unwrap();+ assert_ne!(proj_new, proj);+ }++ /// A hook event fires end-to-end through `process`. Validates that+ /// the session + observation rows land in the resolved project, not+ /// the server-default scratch project.+ #[tokio::test]+ async fn process_routes_observation_to_cwd_project() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;++ let env = HookEnvelope::from_query_and_body(+ HookQuery {event: "session-start".into(),agent: Some("claude-code".into()),..Default::default()@@ -6929,6 +7602,123 @@ mod tests {state}+ #[tokio::test]+ async fn keyed_session_end_replay_waits_for_the_first_delivery_tail() {+ let entered = Arc::new(tokio::sync::Notify::new());+ let release = Arc::new(tokio::sync::Notify::new());+ let entered_hook = entered.clone();+ let release_hook = release.clone();+ let app = axum::Router::new().route(+ "/admission",+ axum::routing::post(move || {+ let entered = entered_hook.clone();+ let release = release_hook.clone();+ async move {+ entered.notify_one();+ release.notified().await;+ StatusCode::NO_CONTENT+ }+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });++ let tmp = TempDir::new().unwrap();+ let state = Arc::new(+ make_state_with_admission(+ &tmp,+ ai_memory_wiki::AdmissionChain::new(vec![ai_memory_wiki::WebhookConfig {+ name: "pause-tail".into(),+ url: format!("http://{addr}/admission"),+ timeout_ms: 5_000,+ failure_policy: ai_memory_wiki::FailurePolicy::Reject,+ events: vec![ai_memory_wiki::AdmissionOp::HandoffBegin],+ blocking: true,+ }])+ .unwrap(),+ )+ .await,+ );+ process(+ &state,+ session_envelope("user-prompt-submit", "gated-end", "/tmp/scratch"),+ None,+ Vec::new(),+ )+ .await+ .unwrap();+ let mut end = session_envelope("session-end", "gated-end", "/tmp/scratch");+ end.ingest_key = Some("same-end".into());+ let first_state = state.clone();+ let first = tokio::spawn(async move {+ process_authorized(+ &first_state,+ end,+ None,+ ai_memory_core::AuthLevel::Anonymous,+ Vec::new(),+ )+ .await+ });+ tokio::time::timeout(Duration::from_secs(2), entered.notified())+ .await+ .expect("first SessionEnd reached the paused tail");++ let mut retry_end = session_envelope("session-end", "gated-end", "/tmp/scratch");+ retry_end.ingest_key = Some("same-end".into());+ let retry_state = state.clone();+ let mut retry = tokio::spawn(async move {+ process_authorized(+ &retry_state,+ retry_end,+ None,+ ai_memory_core::AuthLevel::Anonymous,+ Vec::new(),+ )+ .await+ });+ assert!(+ tokio::time::timeout(Duration::from_millis(100), &mut retry)+ .await+ .is_err(),+ "same keyed replay passed the gate before the first tail completed"+ );+ release.notify_one();+ first.await.unwrap().unwrap();+ retry.await.unwrap().unwrap();++ let session_id = resolve_session_id(&session_envelope(+ "session-end",+ "gated-end",+ "/tmp/scratch",+ ))+ .unwrap();+ let observations = state+ .reader+ .observations_for_session(session_id)+ .await+ .unwrap();+ assert_eq!(+ observations+ .iter()+ .filter(|observation| observation.kind == ObservationKind::SessionEnd)+ .count(),+ 1,+ "same keyed replay duplicated SessionEnd"+ );+ assert_eq!(+ state.reader.reindex_target_status().await.unwrap().handoffs,+ 1,+ "same keyed replay created a second automatic handoff, including expired rows"+ );+ assert_eq!(+ state.reader.status_counts().await.unwrap().pages_all,+ 1,+ "same keyed replay rewrote the summary page"+ );+ }+fn session_envelope(event: &str, session: &str, cwd: &str) -> HookEnvelope {HookEnvelope::from_query_and_body(HookQuery {@@ -7834,6 +8624,16 @@ mod tests {briefing.pending_handoff_count, 1,"recovery must preserve exactly one automatic handoff");+ assert_eq!(+ state+ .reader+ .observations_for_session(session_id)+ .await+ .unwrap()+ .len(),+ 2,+ "already-ended recovery repairs only the tail, never duplicates SessionEnd"+ );assert!(state.wikidiff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsindex afbbdfc1..40558063 100644--- a/crates/ai-memory-hooks/src/workstream.rs+++ b/crates/ai-memory-hooks/src/workstream.rs@@ -1,6 +1,8 @@//! Authenticated HTTP ingress for optional managed workstreams.use std::fmt::Write as _;+#[cfg(unix)]+use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _};use std::path::{Path, PathBuf};use std::str::FromStr as _;@@ -690,17 +692,18 @@ fn write_segment(let parent = target.parent().ok_or_else(|| std::io::Error::other("managed segment has no parent"))?;- std::fs::create_dir_all(parent)?;+ create_private_dir_all(parent)?;if target.exists() {return Ok(relative.to_string_lossy().replace('\\', "/"));}let temp = parent.join(format!(".{run_id}-{}.tmp", ManagedRunId::new()));{use std::io::Write as _;- let mut file = std::fs::OpenOptions::new()- .write(true)- .create_new(true)- .open(&temp)?;+ let mut options = std::fs::OpenOptions::new();+ options.write(true).create_new(true);+ #[cfg(unix)]+ options.mode(0o600);+ let mut file = options.open(&temp)?;file.write_all(&bytes)?;file.sync_all()?;}@@ -714,6 +717,14 @@ fn write_segment(Ok(relative.to_string_lossy().replace('\\', "/"))}+fn create_private_dir_all(path: &Path) -> std::io::Result<()> {+ let mut builder = std::fs::DirBuilder::new();+ builder.recursive(true);+ #[cfg(unix)]+ builder.mode(0o700);+ builder.create(path)+}+fn truncate_owned(value: &mut String, max: usize) {if value.len() <= max {return;@@ -1317,4 +1328,56 @@ mod tests {let packet: ManagedRunContextResponse = serde_json::from_slice(&body).unwrap();assert!(packet.context.is_none());}++ #[cfg(unix)]+ #[test]+ fn segment_files_and_directories_are_private() {+ use std::os::unix::fs::PermissionsExt as _;++ let temp = TempDir::new().unwrap();+ let workstream_id = WorkstreamId::new();+ let run_id = ManagedRunId::new();+ let relative = write_segment(+ temp.path(),+ workstream_id,+ run_id,+ &[NewWorkstreamEvent {+ event_id: "event-1".into(),+ agent: AgentKind::Codex,+ native_session_id: "session-1".into(),+ source_record_id: None,+ kind: WorkstreamEventKind::Message,+ role: None,+ content: "sensitive transcript".into(),+ occurred_at: None,+ metadata: serde_json::json!({}),+ }],+ )+ .unwrap();+ let segment_dir = temp+ .path()+ .join("raw/workstreams")+ .join(workstream_id.to_string())+ .join("segments");+ for path in [+ temp.path().join("raw"),+ temp.path().join("raw/workstreams"),+ segment_dir.clone(),+ ] {+ assert_eq!(+ std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,+ 0o700,+ "{}",+ path.display()+ );+ }+ assert_eq!(+ std::fs::metadata(temp.path().join("raw").join(relative))+ .unwrap()+ .permissions()+ .mode()+ & 0o777,+ 0o600+ );+ }}diff --git a/crates/ai-memory-mcp/src/auth.rs b/crates/ai-memory-mcp/src/auth.rsindex 79cb4762..f3149304 100644--- a/crates/ai-memory-mcp/src/auth.rs+++ b/crates/ai-memory-mcp/src/auth.rs@@ -88,6 +88,9 @@ pub struct AuthState {/// Bearer token that authenticates as **root**. `None` means/// "auth disabled at the wire level" — rung 0.expected: Option<String>,+ /// Whether browser session cookies must be marked `Secure`. This is an+ /// explicit operator setting: proxy headers are untrusted input.+ secure_cookie: bool,/// Actor template stamped onto requests that authenticate with the/// `expected` token. Populated from `[auth].root_username` //// `root_email` / `root_name`. When all three are unset the root@@ -117,6 +120,13 @@ impl AuthState {}}+ /// Require HTTPS for browser session cookies.+ #[must_use]+ pub fn with_secure_cookie(mut self, secure_cookie: bool) -> Self {+ self.secure_cookie = secure_cookie;+ self+ }+/// Attach the root actor template — see [`Self::root_actor`]. The/// auth middleware injects this on every request that authenticates/// with [`Self::expected`]; rung-2 (DB user) lookups override it@@ -327,7 +337,7 @@ pub async fn require_bearer(// browser session. Subsequent navigations ride the cookie alone.if from_basic.is_some() && from_cookie.is_none() {let mut resp = next.run(req).await;- if let Ok(cookie) = build_session_cookie(provided).parse() {+ if let Ok(cookie) = build_session_cookie(provided, state.secure_cookie).parse() {resp.headers_mut().insert(header::SET_COOKIE, cookie);}return resp;@@ -398,7 +408,8 @@ pub async fn require_bearer(if from_basic.is_some() && from_cookie.is_none() {let mut resp = next.run(req).await;- if let Ok(cookie) = build_session_cookie(provided).parse() {+ if let Ok(cookie) = build_session_cookie(provided, state.secure_cookie).parse()+ {resp.headers_mut().insert(header::SET_COOKIE, cookie);}return resp;@@ -463,14 +474,13 @@ fn extract_cookie(req: &Request<axum::body::Body>) -> Option<String> {None}-fn build_session_cookie(token: &str) -> String {+fn build_session_cookie(token: &str, secure_cookie: bool) -> String {// 30-day Max-Age — long enough that re-entering the credential- // every month is rare. HttpOnly hides it from any inline JS;- // SameSite=Lax keeps cross-site POSTs from riding it.- // No Secure attribute: homelab deployments are often plain HTTP- // on a LAN. A TLS-terminating reverse proxy is the right place to- // add Secure if the service is exposed publicly.- format!("{AUTH_COOKIE}={token}; HttpOnly; SameSite=Lax; Path=/; Max-Age=2592000")+ // every month is rare. HttpOnly hides it from inline JS and Strict keeps+ // cross-site requests from riding it. `Secure` remains opt-in so direct+ // loopback/plain-HTTP browser use works; never infer it from proxy headers.+ let secure = if secure_cookie { "; Secure" } else { "" };+ format!("{AUTH_COOKIE}={token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=2592000{secure}")}/// The proxy's identity headers contradict themselves. Not a 401 — the@@ -551,7 +561,12 @@ mod tests {use tower::ServiceExt;fn router_with_auth(token: Option<&str>) -> Router {- let state = Arc::new(AuthState::new(token.map(str::to_string)));+ router_with_auth_secure_cookie(token, false)+ }++ fn router_with_auth_secure_cookie(token: Option<&str>, secure_cookie: bool) -> Router {+ let state =+ Arc::new(AuthState::new(token.map(str::to_string)).with_secure_cookie(secure_cookie));Router::new().route("/probe", get(|| async { "ok" })).layer(axum::middleware::from_fn_with_state(state, require_bearer))@@ -740,7 +755,7 @@ mod tests {}#[tokio::test]- async fn basic_auth_with_right_token_passes_get_and_sets_cookie() {+ async fn basic_auth_with_right_token_passes_get_and_sets_non_secure_cookie() {let r = router_with_auth(Some("right-token"));let resp = r.oneshot(@@ -761,10 +776,34 @@ mod tests {.expect("set-cookie on first Basic-auth success").to_str().unwrap();- assert!(cookie.contains("ai_memory_auth=right-token"));- assert!(cookie.contains("HttpOnly"));- assert!(cookie.contains("SameSite=Lax"));- assert!(cookie.contains("Path=/"));+ assert_eq!(+ cookie,+ "ai_memory_auth=right-token; HttpOnly; SameSite=Strict; Path=/; Max-Age=2592000"+ );+ }++ #[tokio::test]+ async fn basic_auth_sets_secure_cookie_only_when_explicitly_enabled() {+ let r = router_with_auth_secure_cookie(Some("right-token"), true);+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", basic_auth("right-token"))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ assert_eq!(+ resp.headers()+ .get(header::SET_COOKIE)+ .expect("set-cookie on first Basic-auth success")+ .to_str()+ .unwrap(),+ "ai_memory_auth=right-token; HttpOnly; SameSite=Strict; Path=/; Max-Age=2592000; Secure"+ );}#[tokio::test]diff --git a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs b/crates/ai-memory-mcp/tests/autoscope_multiuser.rsindex fc7c1bd5..8dd2713e 100644--- a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs+++ b/crates/ai-memory-mcp/tests/autoscope_multiuser.rs@@ -17,11 +17,8 @@//! `user.username` into the actor key would split the per-actor map//! across rungs, which is exactly what this test pins.-use ai_memory_core::{ActiveProject, ActiveProjectMode, ActorContext, NewUser, Tier};-use ai_memory_hooks::{- DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, ProjectCacheStore, SubagentSessionSet,- hook_router,-};+use ai_memory_core::{ActiveProject, ActiveProjectMode, ActorContext, NewUser, SessionId, Tier};+use ai_memory_hooks::{HookState, ProjectCacheStore, SubagentSessionSet, hook_router};use ai_memory_mcp::AiMemoryServer;use ai_memory_store::{Store, TokenPepper, generate_token, hash_token};use ai_memory_wiki::Wiki;@@ -48,9 +45,12 @@ struct SeededUser {struct MultiUserHarness {router: Router,- _store: Store,+ store: Store,_tmp: TempDir,users: Vec<SeededUser>,+ /// A hook owns its permit from the 202 response until all downstream+ /// processing, including active-pointer publication, has completed.+ ingest_semaphore: Arc<tokio::sync::Semaphore>,}impl MultiUserHarness {@@ -146,6 +146,9 @@ impl MultiUserHarness {let project_cache: ai_memory_hooks::ProjectCache =Arc::new(tokio::sync::Mutex::new(ProjectCacheStore::default()));+ // One permit makes the test harness's completion barrier exact: after+ // a 202, zero permits means the spawned hook task still owns it.+ let ingest_semaphore = Arc::new(tokio::sync::Semaphore::new(1));let hooks = hook_router(HookState {workspace_id: ws,project_id: baked,@@ -156,9 +159,7 @@ impl MultiUserHarness {sanitizer: ai_memory_core::Sanitizer::default(),project_cache,active_project: active_project.clone(),- ingest_semaphore: Arc::new(tokio::sync::Semaphore::new(- DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,- )),+ ingest_semaphore: ingest_semaphore.clone(),ingest_gates: ai_memory_hooks::IngestGates::default(),consolidate_on_session_end: false,session_consolidation_notify: None,@@ -190,9 +191,10 @@ impl MultiUserHarness {MultiUserHarness {router,- _store: store,+ store,_tmp: tmp,users,+ ingest_semaphore,}}}@@ -318,51 +320,56 @@ fn tool_text(body: &str) -> String {.join("\n")}-async fn fire_hook_and_settle(router: &Router, token: &str, session_id: &str, proj: &str) {- let resp = router+async fn fire_hook_and_settle(h: &MultiUserHarness, token: &str, session_id: &str, proj: &str) {+ let resp = h+ .router.clone().oneshot(hook_request(token, session_id, proj)).await.expect("hook oneshot");assert_eq!(resp.status(), StatusCode::ACCEPTED, "hook must accept");let _ = response_text(resp).await;- for _ in 0..20 {- tokio::task::yield_now().await;- }- tokio::time::sleep(Duration::from_millis(15)).await;+ // The handler acquires this permit before it returns 202 and the spawned+ // task releases it only after `process_envelope` finishes. Polling the+ // semaphore therefore waits for completion rather than guessing a sleep.+ tokio::time::timeout(Duration::from_secs(5), async {+ while h.ingest_semaphore.available_permits() != 1 {+ tokio::task::yield_now().await;+ }+ })+ .await+ .expect("hook processing must release its harness permit");}// ────────────────────────────────────────────────────────────────────────────// Each user, authenticated by their real Bearer token, hooks their own// project; concurrent reads must resolve into their OWN slot, never any-// sibling user's, even though they all share the same `session_id` value.+// sibling user's, provided each native agent run has its own `session_id`.// ────────────────────────────────────────────────────────────────────────────#[tokio::test(flavor = "multi_thread", worker_threads = 4)]-async fn per_actor_isolates_real_bearer_users() {+async fn per_actor_isolates_real_bearer_users_with_distinct_native_sessions() {let h = MultiUserHarness::build(3).await;- // Intentionally shared session id across all users: the per_actor map- // must key by `(user, session)`, so even with collisions on the- // session-id half, the user-half from the auth middleware partitions- // them correctly. If a regression dropped `user` from the actor key,- // ALL three users would collapse into one slot and the assertion- // below would fail.- let shared_sess = "shared-session-across-users";+ let sessions: Vec<String> = (0..h.users.len())+ .map(|_| SessionId::new().to_string())+ .collect();for u in &h.users {let proj = format!("user{}-proj", u.project_index);- fire_hook_and_settle(&h.router, &u.token, shared_sess, &proj).await;+ let session_id = &sessions[u.project_index - 1];+ fire_hook_and_settle(&h, &u.token, session_id, &proj).await;}- // Concurrent reads, one per user, with the shared session id.+ // Concurrent reads, each with the matching native session id.let mut handles = Vec::new();for u in &h.users {let router = h.router.clone();let token = u.token.clone();let i = u.project_index;+ let session_id = sessions[i - 1].clone();handles.push(tokio::spawn(async move {let resp = router- .oneshot(mcp_query_request(&token, shared_sess))+ .oneshot(mcp_query_request(&token, &session_id)).await.expect("mcp oneshot");assert_eq!(resp.status(), StatusCode::OK, "user{i} read status");@@ -391,6 +398,99 @@ async fn per_actor_isolates_real_bearer_users() {}}+// A native SessionId is durable and global, not namespaced by the per-actor+// active-pointer key. A second owner cannot claim it in another project or+// publish a pointer under the colliding actor/session pair.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn cross_owner_same_session_collision_is_dropped_before_pointer_publication() {+ let h = MultiUserHarness::build(2).await;+ let alice = &h.users[0];+ let bob = &h.users[1];+ let session = SessionId::new();+ let session_id = session.to_string();++ fire_hook_and_settle(&h, &alice.token, &session_id, "user1-proj").await;+ let owner_before = h+ .store+ .reader+ .session_actor_user(session)+ .await+ .expect("alice session owner");+ let observations_before = h+ .store+ .reader+ .observations_for_session(session)+ .await+ .expect("alice observations")+ .len();+ let alice_before = tool_text(+ &response_text(+ h.router+ .clone()+ .oneshot(mcp_query_request(&alice.token, &session_id))+ .await+ .expect("alice pointer lookup"),+ )+ .await,+ );+ assert_eq!(owner_before.as_deref(), Some("user:user1"));+ assert_eq!(observations_before, 1);+ assert!(alice_before.contains(number_word(1)));++ fire_hook_and_settle(&h, &bob.token, &session_id, "user2-proj").await;++ assert_eq!(+ h.store+ .reader+ .session_actor_user(session)+ .await+ .expect("session owner after collision"),+ owner_before,+ "foreign hook must not take ownership"+ );+ assert_eq!(+ h.store+ .reader+ .observations_for_session(session)+ .await+ .expect("observations after collision")+ .len(),+ observations_before,+ "foreign hook must not append an observation"+ );++ let alice_after = tool_text(+ &response_text(+ h.router+ .clone()+ .oneshot(mcp_query_request(&alice.token, &session_id))+ .await+ .expect("alice pointer after collision"),+ )+ .await,+ );+ assert!(alice_after.contains(number_word(1)));++ let bob_same_id = tool_text(+ &response_text(+ h.router+ .clone()+ .oneshot(mcp_query_request(&bob.token, &session_id))+ .await+ .expect("bob colliding pointer lookup"),+ )+ .await,+ );+ assert!(+ !bob_same_id.contains(number_word(2)),+ "Bob's colliding hook published user2's pointer:\n{bob_same_id}"+ );+ assert!(+ !bob_same_id.contains(number_word(1)),+ "Bob's colliding lookup resolved Alice's pointer instead of the baked default:\n{bob_same_id}"+ );+}+// ────────────────────────────────────────────────────────────────────────────// A request without a Bearer token authenticates as anonymous → no// `user` in the actor key. If it still carries a session id, PerActor@@ -408,7 +508,7 @@ async fn anonymous_request_does_not_inherit_user_slot() {let user1 = &h.users[0]; // owns user1-proj (alphaone marker)// user1 publishes their per_actor slot.- fire_hook_and_settle(&h.router, &user1.token, sess, "user1-proj").await;+ fire_hook_and_settle(&h, &user1.token, sess, "user1-proj").await;// Anonymous read with the SAME session id. Because `user` differs// (`None` vs `Some("user1")`), the per_actor slot is a different@@ -464,7 +564,7 @@ async fn unknown_bearer_does_not_match_any_user_slot() {let sess = "unknown-bearer-probe";let user1 = &h.users[0];- fire_hook_and_settle(&h.router, &user1.token, sess, "user1-proj").await;+ fire_hook_and_settle(&h, &user1.token, sess, "user1-proj").await;// Forged Bearer of the right shape but unknown to the users table.let forged = "deadbeef".repeat(8);diff --git a/crates/ai-memory-mcp/tests/autoscope_stress.rs b/crates/ai-memory-mcp/tests/autoscope_stress.rsindex 9a96577a..83211784 100644--- a/crates/ai-memory-mcp/tests/autoscope_stress.rs+++ b/crates/ai-memory-mcp/tests/autoscope_stress.rs@@ -540,7 +540,13 @@ async fn per_session_isolates_concurrent_writes() {}// ────────────────────────────────────────────────────────────────────────────-// Scenario 3 — per_actor: users sharing a session_id are still isolated.+// Scenario 3 — per_actor: users are isolated by their own run ids.+//+// Durable `SessionId`s are globally unique: a foreign user reusing another+// operator's owned session id is a terminal collision and never publishes a+// pointer (see `autoscope_multiuser::cross_owner_same_session_collision_…`).+// What per_actor isolates here is the pointer cache key `(user, session_id)`,+// exercised the supported way: each user runs their own session.// ────────────────────────────────────────────────────────────────────────────#[tokio::test(flavor = "multi_thread", worker_threads = 4)]@@ -552,18 +558,20 @@ async fn per_actor_isolates_users_sharing_session_id() {).await;- // Alice and Bob send hooks with the SAME `session_id` but DIFFERENT- // users. In `per_actor` mode they must land in distinct map slots- // because the key is `(user, session_id)`, not `session_id` alone.- let shared_sess = "shared-session-x";- fire_hook_and_settle(&h.router, Some("alice"), shared_sess, 1).await;- fire_hook_and_settle(&h.router, Some("bob"), shared_sess, 5).await;+ // Alice and Bob each send hooks from their OWN `session_id`. The+ // per_actor map keys by `(user, session_id)`, so even identical session+ // ids across users would land in distinct slots — the cross-owner+ // durable-session case is covered by the collision regression instead.+ let alice_sess = "alice-session-x";+ let bob_sess = "bob-session-x";+ fire_hook_and_settle(&h.router, Some("alice"), alice_sess, 1).await;+ fire_hook_and_settle(&h.router, Some("bob"), bob_sess, 5).await;// Alice reads — must see proj-1's marker, never proj-5's.let resp = h.router.clone()- .oneshot(mcp_query_request(Some("alice"), Some(shared_sess)))+ .oneshot(mcp_query_request(Some("alice"), Some(alice_sess))).await.expect("alice read");let alice_text = extract_tool_text(&response_body_text(resp).await);@@ -580,7 +588,7 @@ async fn per_actor_isolates_users_sharing_session_id() {let resp = h.router.clone()- .oneshot(mcp_query_request(Some("bob"), Some(shared_sess)))+ .oneshot(mcp_query_request(Some("bob"), Some(bob_sess))).await.expect("bob read");let bob_text = extract_tool_text(&response_body_text(resp).await);diff --git a/crates/ai-memory-store/src/error.rs b/crates/ai-memory-store/src/error.rsindex 587b0eee..cf36f1ea 100644--- a/crates/ai-memory-store/src/error.rs+++ b/crates/ai-memory-store/src/error.rs@@ -53,6 +53,11 @@ pub enum StoreError {#[error("writer actor is no longer running")]WriterClosed,+ /// A hook tried to reuse a session id that belongs to another immutable+ /// session tuple or operator. Deliberately carries no row details.+ #[error("session collision")]+ SessionCollision,+/// A `spawn_blocking` task panicked or was cancelled.#[error("reader pool task did not complete: {0}")]PoolPanic(String),@@ -136,3 +141,57 @@ pub enum StoreError {#[error("workstream is already active: {0}")]WorkstreamBusy(String),}++impl StoreError {+ /// Whether a hook admission failed because its cached scope was deleted or+ /// moved after resolution.+ #[must_use]+ pub fn is_stale_session_scope_reference(&self) -> bool {+ let Self::Sqlite(rusqlite::Error::SqliteFailure(error, message)) = self else {+ return false;+ };++ error.code == rusqlite::ErrorCode::ConstraintViolation+ && (error.extended_code == rusqlite::ffi::SQLITE_CONSTRAINT_FOREIGNKEY+ || (error.extended_code == rusqlite::ffi::SQLITE_CONSTRAINT_TRIGGER+ && message.as_deref()+ == Some("sessions.workspace_id does not match the project's workspace")))+ }+}++#[cfg(test)]+mod tests {+ use super::StoreError;++ #[test]+ fn stale_session_scope_reference_only_matches_fk_or_exact_pairing_trigger() {+ let foreign_key = StoreError::Sqlite(rusqlite::Error::SqliteFailure(+ rusqlite::ffi::Error {+ code: rusqlite::ErrorCode::ConstraintViolation,+ extended_code: rusqlite::ffi::SQLITE_CONSTRAINT_FOREIGNKEY,+ },+ Some("FOREIGN KEY constraint failed".into()),+ ));+ assert!(foreign_key.is_stale_session_scope_reference());++ let pairing_trigger = StoreError::Sqlite(rusqlite::Error::SqliteFailure(+ rusqlite::ffi::Error {+ code: rusqlite::ErrorCode::ConstraintViolation,+ extended_code: rusqlite::ffi::SQLITE_CONSTRAINT_TRIGGER,+ },+ Some("sessions.workspace_id does not match the project's workspace".into()),+ ));+ assert!(pairing_trigger.is_stale_session_scope_reference());++ let other_trigger = StoreError::Sqlite(rusqlite::Error::SqliteFailure(+ rusqlite::ffi::Error {+ code: rusqlite::ErrorCode::ConstraintViolation,+ extended_code: rusqlite::ffi::SQLITE_CONSTRAINT_TRIGGER,+ },+ Some("other trigger".into()),+ ));+ assert!(!other_trigger.is_stale_session_scope_reference());+ assert!(!StoreError::SessionCollision.is_stale_session_scope_reference());+ assert!(!StoreError::InvalidState("invalid".into()).is_stale_session_scope_reference());+ }+}diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex d8280da7..333077c1 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -8,6 +8,8 @@//! Reader-side APIs land in milestone M1-B; the writer + migrations are//! sufficient for M1-A's "drop a page in, see it persisted" demo.+#[cfg(unix)]+use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _};use std::path::{Path, PathBuf};use rusqlite::Connection;@@ -43,8 +45,8 @@ pub use decay::{pub use error::{StoreError, StoreResult};pub use maintenance::MaintenanceJob;pub use ops::{- DeleteWorkspaceSummary, EmbeddingWrite, IngestObservationOutcome, LifecycleOnlyEndOutcome,- MoveSummary, PurgeSummary, ReorgSummary,+ AdmittedSession, DeleteWorkspaceSummary, EmbeddingWrite, HookSessionAdmission,+ IngestObservationOutcome, LifecycleOnlyEndOutcome, MoveSummary, PurgeSummary, ReorgSummary,};pub use reader::{ActivityWindow, AgentSessionCount, AutoImproveCandidateSession, BriefPageBody, BriefingPage,@@ -102,8 +104,9 @@ impl Store {/// cannot be applied, or the writer thread fails to start.pub fn open(data_dir: &Path) -> StoreResult<Self> {let db_dir = data_dir.join("db");- std::fs::create_dir_all(&db_dir)?;+ create_private_dir_all(&db_dir)?;let db_path = db_dir.join(DB_FILENAME);+ create_private_file_if_missing(&db_path)?;let mut conn = Connection::open(&db_path)?;conn.pragma_update(None, "journal_mode", "WAL")?;@@ -133,6 +136,30 @@ impl Store {}}+/// Create missing database-directory components with owner-only access while+/// leaving an existing installation's permissions untouched.+fn create_private_dir_all(path: &Path) -> std::io::Result<()> {+ let mut builder = std::fs::DirBuilder::new();+ builder.recursive(true);+ #[cfg(unix)]+ builder.mode(0o700);+ builder.create(path)+}++/// Reserve a new SQLite file with restrictive permissions before SQLite writes+/// its first page. Existing databases retain their current permissions.+fn create_private_file_if_missing(path: &Path) -> std::io::Result<()> {+ let mut options = std::fs::OpenOptions::new();+ options.write(true).create_new(true);+ #[cfg(unix)]+ options.mode(0o600);+ match options.open(path) {+ Ok(_) => Ok(()),+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),+ Err(error) => Err(error),+ }+}+#[cfg(test)]mod tests {use super::*;@@ -146,6 +173,33 @@ mod tests {use sha2::{Digest, Sha256};use tempfile::TempDir;+ #[cfg(unix)]+ #[test]+ fn open_creates_private_database_directory_and_file() {+ use std::os::unix::fs::PermissionsExt as _;++ let tmp = TempDir::new().unwrap();+ let root = tmp.path().join("data");+ let store = Store::open(&root).unwrap();++ assert_eq!(+ std::fs::metadata(root.join("db"))+ .unwrap()+ .permissions()+ .mode()+ & 0o777,+ 0o700+ );+ assert_eq!(+ std::fs::metadata(store.db_path())+ .unwrap()+ .permissions()+ .mode()+ & 0o777,+ 0o600+ );+ }+fn sample_page(ws: WorkspaceId, proj: ProjectId, path: &str, body: &str) -> NewPage {NewPage {workspace_id: ws,diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex ec6c9593..2bfde5af 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -35,6 +35,70 @@ pub enum IngestObservationOutcome {AlreadyComplete,}+/// Unforgeable writer-issued session capability for hook follow-up mutations.+#[derive(Clone, Debug)]+pub struct AdmittedSession {+ session_id: SessionId,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ agent_kind: AgentKind,+ owner: Option<String>,+}+impl AdmittedSession {+ /// Persisted session identifier authorized by this guard.+ pub fn session_id(&self) -> SessionId {+ self.session_id+ }+ /// Persisted workspace identifier authorized by this guard.+ pub fn workspace_id(&self) -> WorkspaceId {+ self.workspace_id+ }+ /// Persisted project identifier authorized by this guard.+ pub fn project_id(&self) -> ProjectId {+ self.project_id+ }+ /// Persisted agent kind authorized by this guard.+ pub fn agent_kind(&self) -> AgentKind {+ self.agent_kind+ }+ /// Persisted owner storage key, or `None` for a shared session.+ pub fn owner(&self) -> Option<&str> {+ self.owner.as_deref()+ }+}++/// Result of atomic hook admission.+#[derive(Clone, Debug)]+pub enum HookSessionAdmission {+ /// An ordinary observation was admitted for this persisted session.+ Observation {+ /// Writer-issued guard for the persisted session.+ session: AdmittedSession,+ /// Result of claiming and inserting the observation.+ ingest: IngestObservationOutcome,+ },+ /// A terminal event was admitted for a session that was still open.+ EndOpen {+ /// Writer-issued guard for the persisted session.+ session: AdmittedSession,+ /// Result of claiming and inserting the observation.+ ingest: IngestObservationOutcome,+ },+ /// A terminal event was admitted after new observations followed an end.+ ReEnd {+ /// Writer-issued guard for the persisted session.+ session: AdmittedSession,+ /// Result of claiming and inserting the observation.+ ingest: IngestObservationOutcome,+ },+ /// A terminal event was already fully represented by this persisted session.+ AlreadyEnded {+ /// Writer-issued guard for the persisted session.+ session: AdmittedSession,+ },+ /// A terminal event named no persisted session and created nothing.+ InvalidMissingEnd,+}/// Result of conditionally ending a session whose persisted observations are/// all lifecycle boundaries.#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -944,6 +1008,15 @@ pub fn end_lifecycle_only_session(session_id: &SessionId,) -> StoreResult<LifecycleOnlyEndOutcome> {let tx = conn.transaction()?;+ let outcome = end_lifecycle_only_session_in_tx(&tx, session_id)?;+ tx.commit()?;+ Ok(outcome)+}++fn end_lifecycle_only_session_in_tx(+ tx: &Transaction<'_>,+ session_id: &SessionId,+) -> StoreResult<LifecycleOnlyEndOutcome> {let has_substantive_observation: bool = tx.query_row("SELECT EXISTS( \SELECT 1 FROM observations \@@ -955,7 +1028,7 @@ pub fn end_lifecycle_only_session(if has_substantive_observation {return Ok(LifecycleOnlyEndOutcome::Substantive);}- end_session_row(&tx, session_id, None)?;+ end_session_row(tx, session_id, None)?;let reopened: Option<(Vec<u8>, Vec<u8>, Vec<u8>)> = tx.query_row("UPDATE handoffs \@@ -977,7 +1050,7 @@ pub fn end_lifecycle_only_session(let workspace_id = WorkspaceId::from_slice(&workspace_id)?;let project_id = ProjectId::from_slice(&project_id)?;audit(- &tx,+ tx,"release_lifecycle_only_handoff",Some(workspace_id.as_bytes()),Some(project_id.as_bytes()),@@ -988,7 +1061,6 @@ pub fn end_lifecycle_only_session(Ok(handoff_id)}).transpose()?;- tx.commit()?;Ok(LifecycleOnlyEndOutcome::Ended {reopened_handoff: reopened,})@@ -1075,6 +1147,192 @@ pub fn insert_observation_keyed(Ok(IngestObservationOutcome::Inserted(id))}+/// Find or create the hook session, validate its immutable tuple and owner,+/// optionally claim an ingest key, and append the observation in one writer+/// transaction. Validation always precedes key mutation.+pub fn admit_hook_session_event(+ conn: &mut Connection,+ session: &NewSession,+ obs: &NewObservation,+ owner_filter: &OwnerFilter,+ ingest_key: Option<&str>,+) -> StoreResult<HookSessionAdmission> {+ if obs.session_id != session.id+ || obs.workspace_id != session.workspace_id+ || obs.project_id != session.project_id+ {+ return Err(StoreError::InvalidState(+ "hook observation does not match its session tuple".into(),+ ));+ }+ let session_end = obs.kind == ObservationKind::SessionEnd;+ let now = Timestamp::now().as_microsecond();+ let tx = conn.transaction()?;+ type Row = (Vec<u8>, Vec<u8>, String, Option<String>, Option<i64>, u64);+ let existing: Option<Row> = tx.query_row(+ "SELECT workspace_id, project_id, agent_kind, actor_user, ended_at, ended_observation_count FROM sessions WHERE id = ?1",+ params![session.id.as_bytes()],+ |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)),+ ).optional()?;+ let (owner, ended_at, ended_count) = match existing {+ Some((ws, project, agent, owner, ended_at, ended_count)) => {+ // Corrupt owners fail closed, including for Any recovery.+ if owner+ .as_deref()+ .is_some_and(|value| IdentityKey::from_storage_key(value).is_none())+ || ws.as_slice() != session.workspace_id.as_bytes()+ || project.as_slice() != session.project_id.as_bytes()+ || agent != session.agent_kind.as_str()+ || !owner_filter.admits(owner.as_deref())+ {+ return Err(StoreError::SessionCollision);+ }+ (owner, ended_at, ended_count)+ }+ None if session_end => {+ tx.commit()?;+ return Ok(HookSessionAdmission::InvalidMissingEnd);+ }+ None => {+ validate_identity_storage_key(session.actor_user.as_deref(), "session owner")?;+ if !owner_filter.admits(session.actor_user.as_deref()) {+ return Err(StoreError::SessionCollision);+ }+ tx.execute(+ "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, cwd, started_at, actor_user) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",+ params![session.id.as_bytes(), session.workspace_id.as_bytes(), session.project_id.as_bytes(), session.agent_kind.as_str(), session.cwd.as_ref().map(|p| p.to_string_lossy().into_owned()), now, session.actor_user.as_deref()],+ )?;+ (session.actor_user.clone(), None, 0)+ }+ };+ let guard = AdmittedSession {+ session_id: session.id,+ workspace_id: session.workspace_id,+ project_id: session.project_id,+ agent_kind: session.agent_kind,+ owner,+ };+ if session_end && ended_at.is_some() {+ let count: u64 = tx.query_row(+ "SELECT COUNT(*) FROM observations WHERE session_id = ?1",+ params![session.id.as_bytes()],+ |r| r.get(0),+ )?;+ if count <= ended_count {+ tx.commit()?;+ return Ok(HookSessionAdmission::AlreadyEnded { session: guard });+ }+ }+ let ingest = if let Some(key) = ingest_key {+ tx.execute(+ "DELETE FROM ingest_keys WHERE seen_at < ?1",+ params![now - INGEST_KEY_TTL_MICROS],+ )?;+ let old: Option<Option<i64>> = tx+ .query_row(+ "SELECT completed_at FROM ingest_keys WHERE project_id = ?1 AND key = ?2",+ params![obs.project_id.as_bytes(), key],+ |r| r.get(0),+ )+ .optional()?;+ match old {+ Some(done) => {+ if done.is_some() {+ IngestObservationOutcome::AlreadyComplete+ } else {+ IngestObservationOutcome::ResumePending+ }+ }+ None => {+ tx.execute("INSERT INTO ingest_keys (project_id, key, seen_at, completed_at) VALUES (?1, ?2, ?3, NULL)", params![obs.project_id.as_bytes(), key, now])?;+ IngestObservationOutcome::Inserted(insert_observation_row(&tx, obs)?)+ }+ }+ } else {+ IngestObservationOutcome::Inserted(insert_observation_row(&tx, obs)?)+ };+ tx.commit()?;+ if !session_end {+ Ok(HookSessionAdmission::Observation {+ session: guard,+ ingest,+ })+ } else if ended_at.is_some() {+ Ok(HookSessionAdmission::ReEnd {+ session: guard,+ ingest,+ })+ } else {+ Ok(HookSessionAdmission::EndOpen {+ session: guard,+ ingest,+ })+ }+}++fn validate_admitted_session(tx: &Transaction<'_>, admitted: &AdmittedSession) -> StoreResult<()> {+ let owner: Option<String> = tx.query_row(+ "SELECT actor_user FROM sessions WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3 AND agent_kind = ?4",+ params![admitted.session_id.as_bytes(), admitted.workspace_id.as_bytes(), admitted.project_id.as_bytes(), admitted.agent_kind.as_str()],+ |r| r.get(0),+ ).optional()?.ok_or(StoreError::SessionCollision)?;+ if owner != admitted.owner+ || owner+ .as_deref()+ .is_some_and(|v| IdentityKey::from_storage_key(v).is_none())+ {+ return Err(StoreError::SessionCollision);+ }+ Ok(())+}++/// Guarded hook equivalent of [`end_session`].+pub fn end_admitted_session(+ conn: &mut Connection,+ admitted: &AdmittedSession,+ page: Option<&PageId>,+) -> StoreResult<()> {+ let tx = conn.transaction()?;+ validate_admitted_session(&tx, admitted)?;+ end_session_row(&tx, &admitted.session_id, page)?;+ tx.commit()?;+ Ok(())+}++/// Guarded hook lifecycle-only end.+pub fn end_admitted_lifecycle_only_session(+ conn: &mut Connection,+ admitted: &AdmittedSession,+) -> StoreResult<LifecycleOnlyEndOutcome> {+ let tx = conn.transaction()?;+ validate_admitted_session(&tx, admitted)?;+ let outcome = end_lifecycle_only_session_in_tx(&tx, &admitted.session_id)?;+ tx.commit()?;+ Ok(outcome)+}++/// Guarded hook end plus automatic handoff in one transaction.+pub fn end_admitted_session_with_handoff(+ conn: &mut Connection,+ admitted: &AdmittedSession,+ page: Option<&PageId>,+ handoff: &NewHandoff,+) -> StoreResult<HandoffId> {+ if handoff.from_session_id != Some(admitted.session_id)+ || handoff.workspace_id != admitted.workspace_id+ || handoff.project_id != admitted.project_id+ || handoff.owner_user != admitted.owner+ {+ return Err(StoreError::SessionCollision);+ }+ let tx = conn.transaction()?;+ validate_admitted_session(&tx, admitted)?;+ end_session_row(&tx, &admitted.session_id, page)?;+ let id = insert_handoff_row(&tx, handoff)?;+ tx.commit()?;+ Ok(id)+}+/// Mark a keyed hook event complete after its downstream effects finish.////// This transition is idempotent so two resumed processors can converge on the@@ -3155,6 +3413,65 @@ pub(crate) mod tests {(tmp, conn, ws, proj)}+ fn hook_session(+ id: SessionId,+ ws: WorkspaceId,+ proj: ProjectId,+ owner: Option<&str>,+ ) -> NewSession {+ NewSession {+ id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::Codex,+ cwd: None,+ actor_user: owner.map(str::to_owned),+ }+ }++ fn hook_observation(session: &NewSession) -> NewObservation {+ NewObservation {+ session_id: session.id,+ workspace_id: session.workspace_id,+ project_id: session.project_id,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "hook".into(),+ body: "observation".into(),+ importance: 5,+ }+ }++ fn session_end_observation(session: &NewSession) -> NewObservation {+ let mut observation = hook_observation(session);+ observation.kind = ObservationKind::SessionEnd;+ observation+ }++ fn seed_ingest_key(conn: &Connection, project_id: ProjectId, key: &str, completed: bool) {+ conn.execute(+ "INSERT INTO ingest_keys (project_id, key, seen_at, completed_at) VALUES (?1, ?2, ?3, ?4)",+ params![+ project_id.as_bytes(),+ key,+ Timestamp::now().as_microsecond(),+ completed.then_some(Timestamp::now().as_microsecond()),+ ],+ )+ .unwrap();+ }++ fn admitted_session(admission: HookSessionAdmission) -> AdmittedSession {+ match admission {+ HookSessionAdmission::Observation { session, .. }+ | HookSessionAdmission::EndOpen { session, .. }+ | HookSessionAdmission::ReEnd { session, .. }+ | HookSessionAdmission::AlreadyEnded { session } => session,+ HookSessionAdmission::InvalidMissingEnd => panic!("expected admitted session"),+ }+ }+fn page(ws: ai_memory_core::WorkspaceId,proj: ai_memory_core::ProjectId,@@ -6082,4 +6399,411 @@ pub(crate) mod tests {"path absent on this host must be preserved (multi-user/unmounted safety)");}++ #[test]+ fn hook_admission_rejects_cross_owner_fresh_key_without_claiming_it() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let alice = "user:alice";+ let bob = "user:bob";+ let session = hook_session(SessionId::new(), ws, proj, Some(alice));+ begin_session(&mut conn, &session).unwrap();+ let bob_event = hook_observation(&session);++ assert!(matches!(+ admit_hook_session_event(+ &mut conn,+ &session,+ &bob_event,+ &OwnerFilter::User(bob.into()),+ Some("fresh-key"),+ ),+ Err(StoreError::SessionCollision)+ ));+ let observations: u64 = conn+ .query_row("SELECT COUNT(*) FROM observations", [], |row| row.get(0))+ .unwrap();+ let keys: u64 = conn+ .query_row("SELECT COUNT(*) FROM ingest_keys", [], |row| row.get(0))+ .unwrap();+ assert_eq!((observations, keys), (0, 0));++ assert!(matches!(+ admit_hook_session_event(+ &mut conn,+ &session,+ &bob_event,+ &OwnerFilter::User(alice.into()),+ Some("fresh-key"),+ )+ .unwrap(),+ HookSessionAdmission::Observation {+ ingest: IngestObservationOutcome::Inserted(_),+ ..+ }+ ));+ }++ #[test]+ fn concurrent_alice_and_bob_events_only_admit_alice_observation() {+ let (tmp, mut conn, ws, proj) = fresh_db();+ let session = hook_session(SessionId::new(), ws, proj, Some("user:alice"));+ begin_session(&mut conn, &session).unwrap();+ drop(conn);+ let path = tmp.path().join("test.sqlite");+ let gate = Arc::new(std::sync::Barrier::new(2));+ let run = |owner: &'static str, key: &'static str, gate: Arc<std::sync::Barrier>| {+ let path = path.clone();+ let session = session.clone();+ std::thread::spawn(move || {+ let mut conn = Connection::open(path).unwrap();+ conn.pragma_update(None, "busy_timeout", 5_000).unwrap();+ gate.wait();+ admit_hook_session_event(+ &mut conn,+ &session,+ &hook_observation(&session),+ &OwnerFilter::User(owner.into()),+ Some(key),+ )+ })+ };+ let alice = run("user:alice", "alice-key", Arc::clone(&gate));+ let bob = run("user:bob", "bob-key", gate);+ assert!(matches!(+ alice.join().unwrap(),+ Ok(HookSessionAdmission::Observation { .. })+ ));+ assert!(matches!(+ bob.join().unwrap(),+ Err(StoreError::SessionCollision)+ ));++ let conn = Connection::open(path).unwrap();+ let observations: u64 = conn+ .query_row("SELECT COUNT(*) FROM observations", [], |row| row.get(0))+ .unwrap();+ assert_eq!(observations, 1);+ }++ #[test]+ fn hook_admission_rejects_tuple_mismatches_before_mutation() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let other = get_or_create_project(&mut conn, &ws, "other", None).unwrap();+ let session = hook_session(SessionId::new(), ws, proj, Some("user:alice"));+ let mut observation = hook_observation(&session);+ observation.project_id = other;++ assert!(matches!(+ admit_hook_session_event(+ &mut conn,+ &session,+ &observation,+ &OwnerFilter::User("user:alice".into()),+ Some("tuple-key"),+ ),+ Err(StoreError::InvalidState(_))+ ));+ let counts: (u64, u64, u64) = conn+ .query_row(+ "SELECT (SELECT COUNT(*) FROM sessions), (SELECT COUNT(*) FROM observations), (SELECT COUNT(*) FROM ingest_keys)",+ [],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ )+ .unwrap();+ assert_eq!(counts, (0, 0, 0));++ let alice_session = hook_session(session.id, ws, proj, Some("user:alice"));+ begin_session(&mut conn, &alice_session).unwrap();+ let mut agent_mismatch = alice_session.clone();+ agent_mismatch.agent_kind = AgentKind::ClaudeCode;+ let observation = hook_observation(&alice_session);+ assert!(matches!(+ admit_hook_session_event(+ &mut conn,+ &agent_mismatch,+ &observation,+ &OwnerFilter::User("user:alice".into()),+ Some("agent-key"),+ ),+ Err(StoreError::SessionCollision)+ ));+ let counts: (u64, u64) = conn+ .query_row(+ "SELECT (SELECT COUNT(*) FROM observations), (SELECT COUNT(*) FROM ingest_keys)",+ [],+ |row| Ok((row.get(0)?, row.get(1)?)),+ )+ .unwrap();+ assert_eq!(counts, (0, 0));+ }++ #[test]+ fn hook_admission_rejects_unadmitted_new_owner_and_accepts_shared_session() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let owned = hook_session(SessionId::new(), ws, proj, Some("user:alice"));+ assert!(matches!(+ admit_hook_session_event(+ &mut conn,+ &owned,+ &hook_observation(&owned),+ &OwnerFilter::User("user:bob".into()),+ Some("denied-owner"),+ ),+ Err(StoreError::SessionCollision)+ ));+ let counts: (u64, u64, u64) = conn+ .query_row("SELECT (SELECT COUNT(*) FROM sessions), (SELECT COUNT(*) FROM observations), (SELECT COUNT(*) FROM ingest_keys)", [], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))+ .unwrap();+ assert_eq!(counts, (0, 0, 0));++ let shared = hook_session(SessionId::new(), ws, proj, None);+ let admission = admit_hook_session_event(+ &mut conn,+ &shared,+ &hook_observation(&shared),+ &OwnerFilter::User("user:alice".into()),+ None,+ )+ .unwrap();+ assert!(admitted_session(admission).owner().is_none());+ let owner: Option<String> = conn+ .query_row(+ "SELECT actor_user FROM sessions WHERE id = ?1",+ params![shared.id.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert!(owner.is_none());++ assert!(matches!(+ admit_hook_session_event(+ &mut conn,+ &shared,+ &hook_observation(&shared),+ &OwnerFilter::User("user:bob".into()),+ Some("shared-bob"),+ )+ .unwrap(),+ HookSessionAdmission::Observation { .. }+ ));+ let owner: Option<String> = conn+ .query_row(+ "SELECT actor_user FROM sessions WHERE id = ?1",+ params![shared.id.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert!(owner.is_none());+ }++ #[test]+ fn open_session_end_admissions_preserve_all_ingest_outcomes() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ for (key, completed, expected_complete) in [+ ("open-inserted", None, false),+ ("open-pending", Some(false), false),+ ("open-complete", Some(true), true),+ ] {+ let session = hook_session(SessionId::new(), ws, proj, Some("user:alice"));+ begin_session(&mut conn, &session).unwrap();+ if let Some(completed) = completed {+ seed_ingest_key(&conn, proj, key, completed);+ }+ let admission = admit_hook_session_event(+ &mut conn,+ &session,+ &session_end_observation(&session),+ &OwnerFilter::User("user:alice".into()),+ Some(key),+ )+ .unwrap();+ match admission {+ HookSessionAdmission::EndOpen { ingest, .. } if key == "open-inserted" => {+ assert!(matches!(ingest, IngestObservationOutcome::Inserted(_)));+ }+ HookSessionAdmission::EndOpen { ingest, .. } if key == "open-pending" => {+ assert_eq!(ingest, IngestObservationOutcome::ResumePending);+ }+ HookSessionAdmission::EndOpen { ingest, .. } if expected_complete => {+ assert_eq!(ingest, IngestObservationOutcome::AlreadyComplete);+ }+ other => panic!("unexpected open SessionEnd admission: {other:?}"),+ }+ }+ }++ #[test]+ fn reend_session_end_admissions_preserve_all_ingest_outcomes() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ for (key, completed, expected_complete) in [+ ("reend-inserted", None, false),+ ("reend-pending", Some(false), false),+ ("reend-complete", Some(true), true),+ ] {+ let session = hook_session(SessionId::new(), ws, proj, Some("user:alice"));+ begin_session(&mut conn, &session).unwrap();+ end_session(&mut conn, &session.id, None).unwrap();+ insert_observation(&mut conn, &hook_observation(&session)).unwrap();+ if let Some(completed) = completed {+ seed_ingest_key(&conn, proj, key, completed);+ }+ let admission = admit_hook_session_event(+ &mut conn,+ &session,+ &session_end_observation(&session),+ &OwnerFilter::User("user:alice".into()),+ Some(key),+ )+ .unwrap();+ match admission {+ HookSessionAdmission::ReEnd { ingest, .. } if key == "reend-inserted" => {+ assert!(matches!(ingest, IngestObservationOutcome::Inserted(_)));+ }+ HookSessionAdmission::ReEnd { ingest, .. } if key == "reend-pending" => {+ assert_eq!(ingest, IngestObservationOutcome::ResumePending);+ }+ HookSessionAdmission::ReEnd { ingest, .. } if expected_complete => {+ assert_eq!(ingest, IngestObservationOutcome::AlreadyComplete);+ }+ other => panic!("unexpected re-end SessionEnd admission: {other:?}"),+ }+ }+ }++ #[test]+ fn missing_session_end_creates_no_session_key_or_observation() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let session = hook_session(SessionId::new(), ws, proj, Some("user:alice"));+ assert!(matches!(+ admit_hook_session_event(+ &mut conn,+ &session,+ &session_end_observation(&session),+ &OwnerFilter::User("user:alice".into()),+ Some("missing-end"),+ )+ .unwrap(),+ HookSessionAdmission::InvalidMissingEnd+ ));+ let counts: (u64, u64, u64) = conn+ .query_row(+ "SELECT (SELECT COUNT(*) FROM sessions), (SELECT COUNT(*) FROM observations), (SELECT COUNT(*) FROM ingest_keys)",+ [],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ )+ .unwrap();+ assert_eq!(counts, (0, 0, 0));+ }++ #[test]+ fn ordinary_observation_already_complete_remains_observation_admission() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let session = hook_session(SessionId::new(), ws, proj, Some("user:alice"));+ begin_session(&mut conn, &session).unwrap();+ seed_ingest_key(&conn, proj, "ordinary-complete", true);+ assert!(matches!(+ admit_hook_session_event(+ &mut conn,+ &session,+ &hook_observation(&session),+ &OwnerFilter::User("user:alice".into()),+ Some("ordinary-complete"),+ )+ .unwrap(),+ HookSessionAdmission::Observation {+ ingest: IngestObservationOutcome::AlreadyComplete,+ ..+ }+ ));+ }++ #[test]+ fn admitted_guard_revalidates_and_lifecycle_preserves_handoff_release_audit() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let session = hook_session(SessionId::new(), ws, proj, Some("user:alice"));+ let guard = admitted_session(+ admit_hook_session_event(+ &mut conn,+ &session,+ &hook_observation(&session),+ &OwnerFilter::User("user:alice".into()),+ None,+ )+ .unwrap(),+ );+ conn.execute(+ "DELETE FROM sessions WHERE id = ?1",+ params![session.id.as_bytes()],+ )+ .unwrap();+ assert!(matches!(+ end_admitted_session(&mut conn, &guard, None),+ Err(StoreError::SessionCollision)+ ));+ begin_session(&mut conn, &session).unwrap();+ conn.execute(+ "UPDATE sessions SET actor_user = 'user:bob' WHERE id = ?1",+ params![session.id.as_bytes()],+ )+ .unwrap();+ assert!(matches!(+ end_admitted_lifecycle_only_session(&mut conn, &guard),+ Err(StoreError::SessionCollision)+ ));+ let handoff = NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_session_id: Some(session.id),+ from_agent: AgentKind::Codex,+ to_agent: None,+ cwd: None,+ summary: "x".into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ owner_user: Some("user:alice".into()),+ };+ assert!(matches!(+ end_admitted_session_with_handoff(&mut conn, &guard, None, &handoff),+ Err(StoreError::SessionCollision)+ ));++ let receiver = hook_session(SessionId::new(), ws, proj, None);+ let mut lifecycle_observation = hook_observation(&receiver);+ lifecycle_observation.kind = ObservationKind::SessionStart;+ let receiver_guard = admitted_session(+ admit_hook_session_event(+ &mut conn,+ &receiver,+ &lifecycle_observation,+ &OwnerFilter::User("user:alice".into()),+ None,+ )+ .unwrap(),+ );+ let handoff = NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_session_id: None,+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ cwd: None,+ summary: "x".into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ owner_user: None,+ };+ let handoff_id = insert_handoff(&mut conn, &handoff).unwrap();+ let mut acceptance = handoff_acceptance(handoff_id, ws, proj);+ acceptance.accepting_session = Some(receiver.id);+ assert!(accept_handoff(&mut conn, &acceptance).unwrap());+ assert_eq!(+ end_admitted_lifecycle_only_session(&mut conn, &receiver_guard).unwrap(),+ LifecycleOnlyEndOutcome::Ended {+ reopened_handoff: Some(handoff_id)+ }+ );+ assert_eq!(audit_row_for(&conn, "release_lifecycle_only_handoff").0, 1);+ }}diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 6f2b1f26..db506185 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -25,8 +25,8 @@ use crate::auto_improve::{};use crate::error::{StoreError, StoreResult};use crate::ops::{- self, DeleteWorkspaceSummary, EmbeddingWrite, IngestObservationOutcome,- LifecycleOnlyEndOutcome, MoveSummary, PurgeSummary, ReorgSummary,+ self, AdmittedSession, DeleteWorkspaceSummary, EmbeddingWrite, HookSessionAdmission,+ IngestObservationOutcome, LifecycleOnlyEndOutcome, MoveSummary, PurgeSummary, ReorgSummary,};use crate::session_consolidation::SessionConsolidationJob;use crate::users::{self, TOKEN_HASH_LEN};@@ -128,6 +128,28 @@ pub(crate) enum WriteCmd {ingest_key: String,reply: oneshot::Sender<StoreResult<IngestObservationOutcome>>,},+ AdmitHookSessionEvent {+ session: NewSession,+ obs: NewObservation,+ owner_filter: OwnerFilter,+ ingest_key: Option<String>,+ reply: oneshot::Sender<StoreResult<HookSessionAdmission>>,+ },+ EndAdmittedSession {+ admitted: AdmittedSession,+ summary_page_id: Option<PageId>,+ reply: oneshot::Sender<StoreResult<()>>,+ },+ EndAdmittedSessionWithHandoff {+ admitted: AdmittedSession,+ summary_page_id: Option<PageId>,+ handoff: NewHandoff,+ reply: oneshot::Sender<StoreResult<HandoffId>>,+ },+ EndAdmittedLifecycleOnlySession {+ admitted: AdmittedSession,+ reply: oneshot::Sender<StoreResult<LifecycleOnlyEndOutcome>>,+ },CompleteObservationIngest {project_id: ProjectId,ingest_key: String,@@ -665,6 +687,74 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Atomically validate/admit a hook session and insert its observation.+ pub async fn admit_hook_session_event(+ &self,+ session: NewSession,+ obs: Sanitized<NewObservation>,+ owner_filter: OwnerFilter,+ ingest_key: Option<String>,+ ) -> StoreResult<HookSessionAdmission> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::AdmitHookSessionEvent {+ session,+ obs: obs.into_inner(),+ owner_filter,+ ingest_key,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Guarded hook end.+ pub async fn end_admitted_session(+ &self,+ admitted: AdmittedSession,+ summary_page_id: Option<PageId>,+ ) -> StoreResult<()> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::EndAdmittedSession {+ admitted,+ summary_page_id,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Guarded hook end plus automatic handoff.+ pub async fn end_admitted_session_with_handoff(+ &self,+ admitted: AdmittedSession,+ summary_page_id: Option<PageId>,+ handoff: NewHandoff,+ ) -> StoreResult<HandoffId> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::EndAdmittedSessionWithHandoff {+ admitted,+ summary_page_id,+ handoff,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Guarded hook lifecycle-only end.+ pub async fn end_admitted_lifecycle_only_session(+ &self,+ admitted: AdmittedSession,+ ) -> StoreResult<LifecycleOnlyEndOutcome> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::EndAdmittedLifecycleOnlySession {+ admitted,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Mark a keyed hook event complete after all downstream effects finish.////// # Errors@@ -1748,6 +1838,49 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {let result = ops::insert_observation_keyed(&mut conn, &obs, &ingest_key);send_or_warn(reply, result, "insert_observation_ingest");}+ WriteCmd::AdmitHookSessionEvent {+ session,+ obs,+ owner_filter,+ ingest_key,+ reply,+ } => {+ let result = ops::admit_hook_session_event(+ &mut conn,+ &session,+ &obs,+ &owner_filter,+ ingest_key.as_deref(),+ );+ send_or_warn(reply, result, "admit_hook_session_event");+ }+ WriteCmd::EndAdmittedSession {+ admitted,+ summary_page_id,+ reply,+ } => {+ let result =+ ops::end_admitted_session(&mut conn, &admitted, summary_page_id.as_ref());+ send_or_warn(reply, result, "end_admitted_session");+ }+ WriteCmd::EndAdmittedSessionWithHandoff {+ admitted,+ summary_page_id,+ handoff,+ reply,+ } => {+ let result = ops::end_admitted_session_with_handoff(+ &mut conn,+ &admitted,+ summary_page_id.as_ref(),+ &handoff,+ );+ send_or_warn(reply, result, "end_admitted_session_with_handoff");+ }+ WriteCmd::EndAdmittedLifecycleOnlySession { admitted, reply } => {+ let result = ops::end_admitted_lifecycle_only_session(&mut conn, &admitted);+ send_or_warn(reply, result, "end_admitted_lifecycle_only_session");+ }WriteCmd::CompleteObservationIngest {project_id,ingest_key,diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rsindex d0b4e012..5f3d99c0 100644--- a/crates/ai-memory-web/src/routes/api.rs+++ b/crates/ai-memory-web/src/routes/api.rs@@ -866,7 +866,8 @@ async fn enrich_hits(state: &WebState, hits: Vec<PageHit>) -> Result<Vec<ApiSear}fn internal_error(e: impl std::fmt::Display) -> Response {- json_error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())+ tracing::error!(error = %e, "web API internal error");+ json_error(StatusCode::INTERNAL_SERVER_ERROR, "internal server error")}fn not_found(message: impl Into<String>) -> Response {@@ -1161,9 +1162,9 @@ fn hex_value(byte: u8) -> Option<u8> {#[cfg(test)]mod tests {- use super::serves_handoff_body;+ use super::{internal_error, serves_handoff_body};use ai_memory_core::{AuthLevel, OwnerFilter};- use axum::Extension;+ use axum::{Extension, body::to_bytes};/// The `all_owners` recovery switch routes `Any` into the listing. Reading/// past ownership must cost root — not merely a token the server accepted,@@ -1211,4 +1212,22 @@ mod tests {Some(Extension(AuthLevel::User))));}++ #[tokio::test]+ async fn internal_errors_do_not_expose_their_cause() {+ let sentinel = "web-api-secret /srv/ai-memory/db/memory.sqlite";+ let response = internal_error(sentinel);++ assert_eq!(+ response.status(),+ axum::http::StatusCode::INTERNAL_SERVER_ERROR+ );+ let body = to_bytes(response.into_body(), usize::MAX)+ .await+ .expect("error response body should be readable");+ let body = std::str::from_utf8(&body).expect("error response body should be UTF-8");+ assert_eq!(body, r#"{"error":"internal server error"}"#);+ assert!(!body.contains(sentinel));+ assert!(!body.contains("/srv/ai-memory"));+ }}diff --git a/docs/auto-scope.md b/docs/auto-scope.mdindex b75ef1ce..4cf44467 100644--- a/docs/auto-scope.md+++ b/docs/auto-scope.md@@ -105,6 +105,11 @@ match a hook-published keyed entry; if it does not, ai-memory falls backto the server's baked default rather than another session's latestproject.+The composite `(identity, session_id)` key namespaces only these active-project+pointers. The durable `SessionId` stored for hook observations remains global:+if another owner reuses an already-owned id, ai-memory drops that hook before it+can append observations or publish a pointer for the foreign actor.+## Client requirementsLifecycle hooks already include the agent-run session id in theirdiff --git a/docs/https-via-proxy.md b/docs/https-via-proxy.mdindex e4b8ec01..9cacd92b 100644--- a/docs/https-via-proxy.md+++ b/docs/https-via-proxy.md@@ -32,11 +32,12 @@ apply:- **You access `/web` from a different machine** than the one running ai-memory. The browser session cookie set after Basic auth lives in the clear over HTTP.- **You're exposing ai-memory beyond the LAN.** Cloudflare Tunnel or a public-domain Caddy with Let's Encrypt are the two patterns most homelab operators land on.-ai-memory will warn at startup when it binds to a non-loopback address-without auth, and again (one-shot) on the first request that didn't-arrive via `X-Forwarded-Proto: https`. The warnings are advisory —-the server doesn't refuse to start over plain HTTP. The decision to-add TLS is yours; this page is the recipes.+ai-memory refuses to start unauthenticated non-loopback HTTP by default.+Configure `AI_MEMORY_AUTH_TOKEN` or bind loopback; the dangerous+`--allow-insecure-no-auth` escape hatch exists only for intentional plain-HTTP+LAN use. Authenticated non-loopback plain HTTP remains available and logs a+loud warning: bearer tokens and `/web` cookies are still sniffable without+TLS. The decision to add TLS is yours; this page is the recipes.## Pick a path@@ -122,6 +123,7 @@ Caddy will:```bashAI_MEMORY_AUTH_TOKEN=...long-random-token-from-generate-auth-token...+AI_MEMORY_AUTH__SECURE_COOKIE=trueAI_MEMORY_ALLOWED_HOSTS=memory.example.com,localhost,127.0.0.1AI_MEMORY_BIND=0.0.0.0:49374```@@ -305,6 +307,7 @@ step above (Cloudflare manages the CNAME automatically).```bashAI_MEMORY_AUTH_TOKEN=...long-random-token...+AI_MEMORY_AUTH__SECURE_COOKIE=trueAI_MEMORY_ALLOWED_HOSTS=memory.example.com,localhost,127.0.0.1AI_MEMORY_BIND=0.0.0.0:49374CLOUDFLARE_TUNNEL_TOKEN=eyJ...long-base64-from-the-cf-dashboard...@@ -414,12 +417,17 @@ Nothing special — the server intentionally generates no absolute URLsin responses, so it doesn't matter whether `https://` or `http://`sits in front. The bearer token middleware reads `Authorization`directly off the request, which proxies forward verbatim. The-`/api/v1` ETag is computed from request-independent fields. The-`/web` cookie set after Basic auth uses `SameSite=Lax` without-`Secure` so local plain-HTTP use continues to work. An HTTPS proxy does not add-that cookie attribute automatically: close direct HTTP access to the public-hostname, or redirect it to HTTPS, so the browser never has an insecure route-on which it could resend the cookie.+`/api/v1` ETag is computed from request-independent fields.++For browser access to `/web` through HTTPS, set+`AI_MEMORY_AUTH__SECURE_COOKIE=true` (or `[auth] secure_cookie = true`). This+marks the Basic-auth session cookie `Secure`; it is always `HttpOnly`,+`SameSite=Strict`, and `Path=/`. ai-memory intentionally does **not** infer+HTTPS from `X-Forwarded-Proto` or any other proxy header. Close direct HTTP+access to the public hostname, or redirect it to HTTPS. Enabling+`secure_cookie` on a direct HTTP deployment makes browsers withhold the cookie,+which is expected safety behavior. It remains false by default so loopback and+plain-HTTP local `/web` continue to work.The only thing to mind: **`AI_MEMORY_ALLOWED_HOSTS` must include thepublic hostname**, not just `localhost`. The host-allowlist middlewarediff --git a/docs/install.md b/docs/install.mdindex 33f37a0f..fb281c55 100644--- a/docs/install.md+++ b/docs/install.md@@ -61,8 +61,15 @@ docker run -d --name ai-memory \```See [Security](../README.md#security) in the README for why-`AI_MEMORY_AUTH_TOKEN` and `AI_MEMORY_ALLOWED_HOSTS` are both-required for any non-loopback bind.+`AI_MEMORY_AUTH_TOKEN` and `AI_MEMORY_ALLOWED_HOSTS` are both required for+normal non-loopback binds. Bearer auth does not encrypt traffic: use the ready+[Caddy](../docker/compose.tls.caddy.yml) or+[Cloudflare Tunnel](../docker/compose.tls.cloudflared.yml) templates from the+[HTTPS reverse-proxy guide](https-via-proxy.md) for LAN or remote access.+When the proxy serves `/web` over HTTPS, also set+`AI_MEMORY_AUTH__SECURE_COOKIE=true` in the server environment and close or+redirect direct HTTP access to that hostname. Do not set it for direct HTTP:+browsers then correctly withhold the session cookie.### Client side (the laptop)@@ -1703,8 +1710,10 @@ docker run -d --name ai-memory \Notice the bind: `127.0.0.1:49374`, not `0.0.0.0:49374`. This is thecritical pairing - **no bearer token AND loopback only** is the only-safe combination. The startup log will warn loudly if you bind to a-LAN address without setting `AI_MEMORY_AUTH_TOKEN`.+safe combination. The server refuses an unauthenticated LAN bind before it+accepts requests. `--allow-insecure-no-auth` can override that refusal only+for an intentional dangerous plain-HTTP deployment; prefer+`AI_MEMORY_AUTH_TOKEN` or loopback instead.Then wire up the agent CLI. Both commands default to no auth and`http://127.0.0.1:49374` - no extra flags needed for the local case:diff --git a/docs/users.md b/docs/users.mdindex 2b2aa6ba..23031855 100644--- a/docs/users.md+++ b/docs/users.md@@ -15,6 +15,16 @@ default. Every `/admin/*` endpoint stays root-only once the deployment has aDB user or trusted-proxy identities, including read-onlystatus/search/read-page helpers.+Hook session identifiers are also owner-bound. A hook authenticated as one+operator cannot reuse another operator's UUID to append events or trigger a+summary/handoff/end transition. Shared legacy sessions remain available to all+callers. Cross-owner recovery is limited to root's explicit+`finalize-session --all-owners` path.++Authenticated clients sharing one server must emit a distinct agent-run id for+each run and forward that same id on their MCP requests when using session-aware+auto-scope. Legacy sessions whose stored owner is `NULL` remain shared.+If you run ai-memory alone, you can skip this page — your installkeeps working unchanged.@@ -71,6 +81,7 @@ Configure a distinct proxy credential:[auth]bearer_token = "<root-token>" # direct administrationactor_proxy_bearer_token = "<different-token>" # SSO proxy only+secure_cookie = true # when `/web` is HTTPS-only# Optional stable identity for the root human behind an OIDC proxy.root_issuer = "https://idp.example"@@ -81,6 +92,9 @@ root_subject = "<root-subject>"differ from `bearer_token`, and `serve` refuses startup otherwise or when theroot bearer is absent.- Only set it when the server is reachable *only* through that proxy.+- `secure_cookie` is independent of proxy identity. Enable it when a trusted+ reverse proxy terminates HTTPS for `/web`; ai-memory never trusts forwarded+ protocol headers to infer it. Direct HTTP browsers will not send that cookie.- **The proxy MUST strip client-supplied `X-Memory-Actor-*` headers beforesetting its own.** Use a directive that *replaces* the header rather thanappending to it (nginx `proxy_set_header`, Traefik `customRequestHeaders`) —