Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(relay): drop pre-sanitation unsafe items locally instead of holding their session
AkitaOnRailsab86d67e7b88
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d306fc3a..a12b6c2a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,12 +8,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added-- Added shared private capture privacy helpers used by the relay and conversation- importer before body hashes, local persistence, previews and delivery. Sensitive- native identities were refused without renaming; nested credentials were scrubbed- with bounded body validation and an exact numeric token-metric allowlist. Unsafe- legacy relay heads retained their bytes and retry state while deferring only their- session, and importer byte caps preserved complete redaction markers. (#1072)+- Added shared capture privacy checks to the relay and the conversation importer,+ run before an event is hashed, persisted, previewed or delivered: they refuse+ credential-shaped native identities, scrub nested credentials while keeping+ numeric token counts, and drop locally a relay item queued before them that+ fails them, so it no longer holds its session. (#1072)- Added `install-hooks --agent claude-code --scope project`, which writes thehook configuration to the checkout's gitignored `.claude/settings.local.json`(where Claude Code reads it: the git root, or the launch directory ondiff --git a/companions/ai-memory-client/src/lib.rs b/companions/ai-memory-client/src/lib.rsindex ff8ed040..6304c738 100644--- a/companions/ai-memory-client/src/lib.rs+++ b/companions/ai-memory-client/src/lib.rs@@ -83,11 +83,24 @@ fn sensitive_key(key: &str, value: &Value) -> bool {"output_tokens total_tokens cache_read_input_tokens cache_creation_input_tokens ","prompt_tokens completion_tokens reasoning_tokens");- let is_metric = metrics.split(' ').any(|metric| metric == name);+ let parts: Vec<_> = name.split('_').filter(|part| !part.is_empty()).collect();+ // Beyond the exact list, a `*_tokens` number is a usage count+ // (`cached_tokens`, `thinking_tokens`) unless a credential qualifier names+ // it (`access_tokens`, `refresh_tokens`); string values still redact.+ let usage_count = parts.len() > 1+ && parts.last() == Some(&"tokens")+ && !parts[..parts.len() - 1].iter().any(|part| {+ concat!(+ "access refresh id auth authorization bearer session api private ",+ "client oauth secret password credential cookie"+ )+ .split(' ')+ .any(|qualifier| qualifier == *part)+ });+ let is_metric = metrics.split(' ').any(|metric| metric == name) || usage_count;if value.is_number() && is_metric {return false;}- let parts: Vec<_> = name.split('_').filter(|part| !part.is_empty()).collect();let sensitive = concat!("authorization auth jwt pwd bearer password passwd secret token cookie ","credential apikey privatekey accesskey signature"diff --git a/companions/ai-memory-client/tests/suite/mod.rs b/companions/ai-memory-client/tests/suite/mod.rsindex 5a7b45ce..a2f48f87 100644--- a/companions/ai-memory-client/tests/suite/mod.rs+++ b/companions/ai-memory-client/tests/suite/mod.rs@@ -144,6 +144,24 @@ fn sensitive_key_forms_redact_opaque_values_and_preserve_numeric_metrics() {reject_sensitive(&safe).unwrap();}+#[test]+fn unlisted_numeric_token_counts_survive_while_their_string_form_redacts() {+ let counts = json!({"cached_tokens": 7, "thinking_tokens": 1024, "cacheTokens": 3});+ let mut safe = counts.clone();+ sanitize_external_value(&mut safe).unwrap();+ assert_eq!(+ safe, counts,+ "numeric usage counts keep their value and type"+ );+ reject_sensitive(&safe).unwrap();++ let mut strings = json!({"cached_tokens": "fixture-value", "thinking_tokens": "fixture-value"});+ assert!(reject_sensitive(&strings).is_err());+ sanitize_external_value(&mut strings).unwrap();+ assert_eq!(strings["cached_tokens"], "[REDACTED]");+ assert_eq!(strings["thinking_tokens"], "[REDACTED]");+}+#[test]fn numeric_token_metrics_preserve_representation_without_credential_bypass() {let metrics = json!({"max_tokens":12,"input_tokens":34,"token_count":0,"token_usage":1.25,"output_tokens":9007199254740993_u64,"total_tokens":89,"totalTokens":89,"cache_read_input_tokens":2,"cache_creation_input_tokens":3,"prompt_tokens":5,"completion_tokens":7,"reasoning_tokens":11});diff --git a/companions/ai-memory-relay/README.md b/companions/ai-memory-relay/README.mdindex 8f83a386..cb0a6280 100644--- a/companions/ai-memory-relay/README.md+++ b/companions/ai-memory-relay/README.md@@ -155,10 +155,12 @@ print event bodies. Receipts count acknowledgements, including policy drops.New queue bodies receive local credential sanitation before persistence, thencross the normal server sanitizer on delivery. Legacy pending bytes, digest,-native identity, ingest key and attempt state remain exact. An unsafe stored-head is retained with a payload-free `privacy/validation` diagnostic; only its-session is deferred while clean sessions continue. No attempt or receipt is-recorded for the refused item. See the [shared privacy helpers](../ai-memory-client).+native identity, ingest key and attempt state remain exact. A stored item that+fails the privacy check (only possible for one queued before local sanitation)+is never sent: the flush drops it locally as `dropped_policy`, keeps a receipt+so its key stays replay-protected, and reports the count without payload. Its+session's later events continue instead of waiting behind it. See the [shared+privacy helpers](../ai-memory-client).The producer must apply its capture exclusions before enqueueing. The relaydoes not load the project's `[capture] ignore_paths` settings or inspect tooldiff --git a/companions/ai-memory-relay/src/relay.rs b/companions/ai-memory-relay/src/relay.rsindex 646e68fc..ea02fed9 100644--- a/companions/ai-memory-relay/src/relay.rs+++ b/companions/ai-memory-relay/src/relay.rs@@ -290,6 +290,7 @@ fn flush_locked(dir: &Path, options: &FlushOptions) -> Result<Report> {let mut outcomes = ack::outcome_counts();let mut batches = 0usize;let mut blocked_sessions = 0usize;+ let mut dropped_unsafe = 0usize;let mut failure: Option<String> = None;let mut backed_off = false;@@ -311,6 +312,7 @@ fn flush_locked(dir: &Path, options: &FlushOptions) -> Result<Report> {break;}let mut items = Vec::new();+ let mut unsafe_keys: Vec<(String, &str)> = Vec::new();for item in &batch.items {let wire = serde_json::from_str(&item.body_json).ok().and_then(|body| {ai_memory_client::reject_sensitive(&serde_json::json!([@@ -328,16 +330,19 @@ fn flush_locked(dir: &Path, options: &FlushOptions) -> Result<Report> {if let Some(wire) = wire {items.push(wire);} else {- queue.record_failure(&item.ingest_key, "privacy/validation")?;- deferred.insert(item.session());- failure.get_or_insert_with(|| {- "privacy/validation: unsafe stored body retained; its session deferred".into()- });+ // Only an item queued before local sanitation can fail here. It+ // is never sent, and retaining it would hold its session's later+ // events on every flush, so it leaves the queue as a local+ // policy drop; the receipt keeps its key replay-protected.+ unsafe_keys.push((item.ingest_key.clone(), "dropped_policy"));}}- batch- .items- .retain(|item| !deferred.contains(&item.session()));+ if !unsafe_keys.is_empty() {+ dropped_unsafe += queue.confirm(&unsafe_keys, now)?;+ batch+ .items+ .retain(|item| !unsafe_keys.iter().any(|(key, _)| *key == item.ingest_key));+ }if items.is_empty() {continue;}@@ -496,9 +501,15 @@ fn flush_locked(dir: &Path, options: &FlushOptions) -> Result<Report> {.to_owned(),);}+ if dropped_unsafe > 0 {+ summary.push(format!(+ "{dropped_unsafe} event(s) queued before local sanitation failed privacy/validation \+ and were dropped locally, never sent; their sessions continued"+ ));+ }if !deferred.is_empty() {summary.push(format!(- "{} session(s) deferred to a later flush (an unsafe, failed or rate-limited head); \+ "{} session(s) deferred to a later flush (a failed or rate-limited head); \their later events were never sent ahead of it",deferred.len()));diff --git a/companions/ai-memory-relay/tests/relay.rs b/companions/ai-memory-relay/tests/relay.rsindex 86130383..4c6b9d96 100644--- a/companions/ai-memory-relay/tests/relay.rs+++ b/companions/ai-memory-relay/tests/relay.rs@@ -2353,7 +2353,7 @@ fn new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry() {}#[test]-fn unsafe_legacy_pending_is_retained_exactly_and_never_sent() {+fn unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session() {let root = fixture("unsafe-legacy-pending");let server = stub(vec![Reply::AcceptAll, Reply::AcceptAll]);let dir = bind(&root, &server.url());@@ -2363,88 +2363,55 @@ fn unsafe_legacy_pending_is_retained_exactly_and_never_sent() {queue.enqueue(&[legacy.clone()], ai_memory_relay::now_ms()).unwrap();- let first_attempt = ai_memory_relay::now_ms() - 1000;- queue- .stamp_attempt(&[legacy.ingest_key.clone()], first_attempt)- .unwrap();- queue- .stamp_attempt(&[legacy.ingest_key.clone()], first_attempt)- .unwrap();+ let later = valid("later-clean", "codex", "session-end", "native-session");let clean = valid("clean-event", "codex", "session-start", "clean-session");queue- .enqueue(- &[- valid("later-dirty", "codex", "session-end", "native-session"),- clean.clone(),- ],- ai_memory_relay::now_ms(),- )+ .enqueue(&[later.clone(), clean.clone()], ai_memory_relay::now_ms()).unwrap();drop(queue);- for _ in 0..2 {- let report = relay::flush(&dir, &FlushOptions::default()).unwrap();- assert!(- report- .failure- .as_ref()- .is_some_and(|failure| failure.contains("privacy/validation"))- );- assert!(!format!("{report:?}").contains("abcdefghijklmnop"));- assert!(report.pending);- assert_eq!(pending_count(&dir), 2);- }- let sent = server.bodies();- assert_eq!(sent.len(), 1);- assert_eq!(- sent[0][0]["body"],- serde_json::from_str::<serde_json::Value>(&clean.body_json).unwrap()++ let report = relay::flush(&dir, &FlushOptions::default()).unwrap();+ assert!(report.failure.is_none(), "{report:?}");+ assert!(!format!("{report:?}").contains("abcdefghijklmnop"));+ assert!(+ report+ .summary+ .iter()+ .any(|line| line.starts_with("1 event(s) queued before local sanitation")),+ "{report:?}");- assert_eq!(- Queue::open(&dir)- .unwrap()- .stats(ai_memory_relay::now_ms())+ assert!(!report.pending);+ assert_eq!(pending_count(&dir), 0);++ // The unsafe head never reached the wire; the clean session and the unsafe+ // session's later event both did.+ let sent: Vec<serde_json::Value> = server+ .bodies()+ .iter()+ .flat_map(|batch| batch.as_array().unwrap().clone())+ .collect();+ assert!(+ !serde_json::to_string(&sent).unwrap()- .receipts,- 1+ .contains("abcdefghijklmnop"));+ let ids: Vec<&str> = sent+ .iter()+ .map(|item| item["body"]["session_id"].as_str().unwrap())+ .collect();+ assert_eq!(ids.len(), 2);+ assert!(ids.contains(&"clean-session"));+ assert!(ids.contains(&"native-session"));+let conn = rusqlite::Connection::open(dir.join(ai_memory_relay::fsguard::DB_FILE)).unwrap();- let preserved: (String, String, String, String, Option<i64>, i64) = conn+ let outcome: Option<String> = conn.query_row(- "SELECT ingest_key,session_id,body_json,body_sha256,first_attempt_ms,attempts FROM pending WHERE event_id=?1",- [&legacy.event_id],- |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?, row.get(5)?)),+ "SELECT outcome FROM receipt WHERE ingest_key = ?1",+ [&legacy.ingest_key],+ |row| row.get(0),).unwrap();- assert!(- preserved- == (- legacy.ingest_key,- legacy.session_id,- legacy.body_json,- legacy.body_sha256,- Some(first_attempt),- 2- ),- "unsafe legacy identity, bytes, digest and attempt state must remain unchanged"- );- let errors: Vec<(String, Option<String>, Option<i64>)> = conn- .prepare("SELECT event_id,last_error,first_attempt_ms FROM pending ORDER BY seq")- .unwrap()- .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))- .unwrap()- .map(Result::unwrap)- .collect();- assert_eq!(- errors,- [- (- "native-event".into(),- Some("privacy/validation".into()),- Some(first_attempt)- ),- ("later-dirty".into(), None, None)- ]- );+ assert_eq!(outcome.as_deref(), Some("dropped_policy"));}#[test]@@ -2593,7 +2560,7 @@ fn sensitive_binding_is_refused_before_queue_creation() {}#[test]-fn unsafe_legacy_native_identity_defers_only_its_session() {+fn unsafe_legacy_native_identity_is_dropped_and_its_session_continues() {let root = fixture("privacy-legacy-native-id");let server = stub(vec![Reply::AcceptAll, Reply::AcceptAll]);let dir = bind(&root, &server.url());@@ -2606,42 +2573,35 @@ fn unsafe_legacy_native_identity_defers_only_its_session() {.unwrap();drop(queue);let report = flush(&dir);- assert!(- report- .failure- .is_some_and(|failure| failure.contains("privacy/validation")),- "unsafe legacy native identity must be refused"- );- assert_eq!(pending_count(&dir), 1);+ assert!(report.failure.is_none(), "{report:?}");+ assert!(!format!("{report:?}").contains("abcdefghijklmnop"));+ assert_eq!(pending_count(&dir), 0);+enqueue(&dir,&root,"after.json",- serde_json::json!([event("after", "codex", "session-start", "clean-after")]),+ serde_json::json!([event("after", "codex", "session-end", "old-session")]),).unwrap();let report = flush(&dir);- assert!(report.failure.is_some());- assert_eq!(pending_count(&dir), 1);+ assert!(report.failure.is_none(), "{report:?}");+ assert_eq!(pending_count(&dir), 0);+let sent = server.bodies();assert_eq!(sent.len(), 2);assert_eq!(sent[0][0]["body"],serde_json::from_str::<serde_json::Value>(&before.body_json).unwrap());- assert_eq!(sent[1][0]["body"]["session_id"], "clean-after");- let conn = rusqlite::Connection::open(dir.join(ai_memory_relay::fsguard::DB_FILE)).unwrap();- let stored: (String,String,String,String,String,Option<i64>,i64) = conn.query_row("SELECT event_id,session_id,ingest_key,body_json,body_sha256,first_attempt_ms,attempts FROM pending", [], |row| Ok((row.get(0)?,row.get(1)?,row.get(2)?,row.get(3)?,row.get(4)?,row.get(5)?,row.get(6)?))).unwrap();- assert_eq!(- stored,- (- legacy.event_id,- legacy.session_id,- legacy.ingest_key,- legacy.body_json,- legacy.body_sha256,- None,- 0- )+ assert_eq!(sent[1][0]["body"]["session_id"], "old-session");+ assert!(+ server+ .heads+ .lock()+ .unwrap()+ .iter()+ .all(|head| !head.contains("abcdefghijklmnop")),+ "the unsafe native identity must never reach a request line");}diff --git a/docs/companion-crates.md b/docs/companion-crates.mdindex 1a0a0c2e..7074ef41 100644--- a/docs/companion-crates.md+++ b/docs/companion-crates.md@@ -84,9 +84,9 @@ MCP page arguments are documented in [programmatic memory](programmatic-memory.m[`ai-memory-client`](../companions/ai-memory-client) supplies four privacyfunctions consumed by both the relay and external-conversation importer. Newbodies are scrubbed before serialization, hashes and local persistence; native-identities containing credentials are refused without being renamed. Unsafe-legacy relay heads retain their exact bytes and retry metadata and defer only-their own session. The package has its own workspace and focused tests, with no+identities containing credentials are refused without being renamed. A relay+item queued before these checks that fails them is never sent: it is dropped+locally with a `dropped_policy` receipt, so its session keeps flowing. The package has its own workspace and focused tests, with noserver dependency. Server authorization and capture exclusions remain theauthoritative boundaries.diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 2f580ee1..4b9fc3a3 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -69,7 +69,7 @@ boundary not yet built.| 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet || 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users || 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository` (foreign raw workstream id refuses populated provenance; granted reader receives the source record and tool correlation); `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |-| 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch` | SDK secret-position, nested key, 11-name numeric metric, bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_retained_exactly_and_never_sent`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. Unsafe legacy bodies keep exact bytes/digest/identity/key and existing attempt state; only their session is deferred while clean sessions ship. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative |+| 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch` | SDK secret-position, nested key, numeric metric (11 names plus numeric `*_tokens` counts; string values still redact), bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session`, `unsafe_legacy_native_identity_is_dropped_and_its_session_continues`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. An unsafe item queued before these checks never reaches the wire (body or request line); it leaves the queue as a local `dropped_policy` receipt so the rest of its session ships. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative || 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`; `router.rs` `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others || 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) || 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG |diff --git a/tests/e2e/__pycache__/external_relay_smoke.cpython-312.pyc b/tests/e2e/__pycache__/external_relay_smoke.cpython-312.pycnew file mode 100644index 00000000..4faefae8Binary files /dev/null and b/tests/e2e/__pycache__/external_relay_smoke.cpython-312.pyc differdiff --git a/tests/e2e/__pycache__/test_external_relay_smoke.cpython-312-pytest-9.0.2.pyc b/tests/e2e/__pycache__/test_external_relay_smoke.cpython-312-pytest-9.0.2.pycnew file mode 100644index 00000000..a8b3b1aaBinary files /dev/null and b/tests/e2e/__pycache__/test_external_relay_smoke.cpython-312-pytest-9.0.2.pyc differ