Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): link a managed run from later hook events only within its boundary
AkitaOnRails42bc0a5310a7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8e0815f6..980ec21a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -234,6 +234,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0stored history; the CLI also protected reads from older servers. (#1079)### Fixed+- Fixed a later hook event carrying a managed-run id linking its native session+ to that run without the checks SessionStart applies. It now links only from+ the run's own project and operator; an event from elsewhere is still captured+ but no longer repoints the run. (#1082)- Fixed completed retries and no-op session endings advancing`last_persisted_ms` without a durable write. Recovery still advances thetimestamp when it commits a new page or terminal effect. (#1015)diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex cc7685cb..7222c68b 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -3355,10 +3355,27 @@ async fn process_authorized(ai_memory_core::NativeSessionIdentity::parse(value, &state.sanitizer).ok()}){- let _ = state+ // The same run boundary as the SessionStart binding: the event's+ // admitted scope and operator, not the run id alone.+ let linked = state.writer- .link_managed_run_session(run_id, env.agent, native_session_id.into_string())+ .link_managed_run_session_in_scope(ai_memory_store::LinkManagedRunSessionInScope {+ run_id,+ workspace_id: ws,+ project_id: proj,+ agent: env.agent,+ native_session_id: native_session_id.into_string(),+ owner_user: owner_stamp.clone(),+ }).await?;+ if linked == ai_memory_store::ManagedRunSessionLink::Refused {+ warn!(+ managed_run = %run_id,+ agent = %env.agent.as_str(),+ event = ?env.event,+ "hook event outside its managed run's project or operator; link refused"+ );+ }}if publishable_scope {publish_active_project_for_event(@@ -9563,6 +9580,122 @@ mod tests {);}+ async fn prepare_link_test_run(+ state: &HookState,+ owner: Option<&IdentityKey>,+ ) -> ai_memory_store::PreparedWorkstreamRun {+ let owner_user = ai_memory_core::owner_stamp(owner, owner.is_some());+ state+ .writer+ .prepare_workstream_run_owned(+ PrepareWorkstreamRun {+ workspace_id: state.workspace_id,+ project_id: state.project_id,+ repo_fingerprint: "link-repo".into(),+ worktree_fingerprint: "link-worktree".into(),+ cwd: "/tmp/scratch".into(),+ agent: AgentKind::ClaudeCode,+ automatic_harness: false,+ available_agents: Vec::new(),+ selection: WorkstreamSelection::Current,+ lease_owner: "test:link".into(),+ },+ owner_user,+ )+ .await+ .unwrap()+ }++ async fn run_native_session(state: &HookState, run_id: ManagedRunId) -> Option<String> {+ state+ .reader+ .managed_run_status(run_id)+ .await+ .unwrap()+ .unwrap()+ .native_session_id+ }++ /// #1082: a later hook event carrying a managed-run id links its native+ /// session only from the run's own operator and project — the SessionStart+ /// boundary. A run id obtained out of band must not let another operator+ /// repoint the run, while that operator's own event is still captured.+ #[tokio::test]+ async fn hook_event_links_a_managed_run_only_from_its_operator() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.trusted_proxy_identity = true;+ let alice = IdentityKey::User("alice".into());+ let bob = IdentityKey::User("bob".into());+ let run = prepare_link_test_run(&state, Some(&alice)).await;++ // Before the owner's session has linked, a foreign event must not+ // claim the run.+ let mut foreign = session_envelope("user-prompt-submit", "bob-native", "/tmp/scratch");+ foreign.managed_run = Some(run.run_id.to_string());+ process(&state, foreign.clone(), Some(bob), Vec::new())+ .await+ .unwrap();+ assert_eq!(+ run_native_session(&state, run.run_id).await,+ None,+ "another operator's event linked the run"+ );+ let bob_session = resolve_session_id(&foreign).unwrap();+ assert!(+ !state+ .reader+ .observations_for_session(bob_session)+ .await+ .unwrap()+ .is_empty(),+ "the refused link must not drop the event itself"+ );++ let mut owned = session_envelope("user-prompt-submit", "alice-native", "/tmp/scratch");+ owned.managed_run = Some(run.run_id.to_string());+ process(&state, owned, Some(alice), Vec::new())+ .await+ .unwrap();+ assert_eq!(+ run_native_session(&state, run.run_id).await.as_deref(),+ Some("alice-native"),+ "the run's own operator links its session"+ );+ }++ /// #1082: an event admitted to a different project than the run's never+ /// links, even from the run's own operator.+ #[tokio::test]+ async fn hook_event_in_another_project_does_not_link_the_run() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let run = prepare_link_test_run(&state, None).await;++ let mut elsewhere = session_envelope("user-prompt-submit", "elsewhere", "/tmp/elsewhere");+ elsewhere.project_override = Some("elsewhere".into());+ elsewhere.managed_run = Some(run.run_id.to_string());+ process(&state, elsewhere, None, Vec::new()).await.unwrap();+ assert_eq!(run_native_session(&state, run.run_id).await, None);+ }++ /// #1082 control: a single-operator server keeps linking runs from later+ /// hook events exactly as before.+ #[tokio::test]+ async fn hook_event_links_a_shared_run_on_a_single_operator_server() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let run = prepare_link_test_run(&state, None).await;++ let mut event = session_envelope("user-prompt-submit", "shared-native", "/tmp/scratch");+ event.managed_run = Some(run.run_id.to_string());+ process(&state, event, None, Vec::new()).await.unwrap();+ assert_eq!(+ run_native_session(&state, run.run_id).await.as_deref(),+ Some("shared-native")+ );+ }+/// A rejected foreign delivery must stop at the store admission boundary:/// it cannot create any router-side artifact or claim its key.#[tokio::test]diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 52c60af0..3077c8c3 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -98,10 +98,10 @@ pub use users::{};pub use web_sessions::{LiveWebSession, WebSession, hash_session_secret};pub use workstream::{- FinishWorkstreamRun, FinishedWorkstreamRun, LinkOrAdoptManagedRunSession, ManagedRunAuthority,- ManagedRunContext, ManagedRunSessionLink, PrepareWorkstreamRun, PreparedWorkstreamRun,- RenameWorkstream, RenamedWorkstream, StoredManagedRunStatus, StoredWorkstreamSummary,- WorkstreamSelection, WorkstreamSelector,+ FinishWorkstreamRun, FinishedWorkstreamRun, LinkManagedRunSessionInScope,+ LinkOrAdoptManagedRunSession, ManagedRunAuthority, ManagedRunContext, ManagedRunSessionLink,+ PrepareWorkstreamRun, PreparedWorkstreamRun, RenameWorkstream, RenamedWorkstream,+ StoredManagedRunStatus, StoredWorkstreamSummary, WorkstreamSelection, WorkstreamSelector,};pub use writer::{StartupContextAcceptance, WriterHandle};diff --git a/crates/ai-memory-store/src/workstream.rs b/crates/ai-memory-store/src/workstream.rsindex 8d19e700..cba4bbac 100644--- a/crates/ai-memory-store/src/workstream.rs+++ b/crates/ai-memory-store/src/workstream.rs@@ -221,6 +221,27 @@ pub struct LinkOrAdoptManagedRunSession {pub owner_user: Option<String>,}+/// Scope a later hook event of a managed run resolved to.+///+/// The SessionStart binding goes through [`LinkOrAdoptManagedRunSession`];+/// every later event carrying the run id goes through this, and both enforce+/// the same run boundary.+#[derive(Debug, Clone)]+pub struct LinkManagedRunSessionInScope {+ /// Run id the hook event carried.+ pub run_id: ManagedRunId,+ /// Workspace the event was admitted to.+ pub workspace_id: WorkspaceId,+ /// Project the event was admitted to.+ pub project_id: ProjectId,+ /// Harness reporting the native session.+ pub agent: AgentKind,+ /// Harness-native session id to bind.+ pub native_session_id: String,+ /// Topology-aware qualified operator identity, or shared `None`.+ pub owner_user: Option<String>,+}+/// Store-level finish input after the raw segment has been made durable.#[derive(Debug, Clone)]pub struct FinishWorkstreamRun {@@ -379,6 +400,48 @@ struct ManagedRunBoundaryRow {cwd: String,agent: String,owner_user: Option<String>,+ native_session: Option<String>,+}++impl ManagedRunBoundaryRow {+ const SELECT: &str = "SELECT mr.state, w.workspace_id, w.project_id, w.cwd, mr.agent_kind, \+ mr.owner_user, mr.native_session_id \+ FROM managed_runs mr JOIN workstreams w ON w.id = mr.workstream_id \+ WHERE mr.id = ?1";++ fn read(tx: &Transaction<'_>, run_id: ManagedRunId) -> StoreResult<Option<Self>> {+ Ok(tx+ .query_row(Self::SELECT, params![run_id.as_bytes()], |row| {+ Ok(Self {+ state: row.get(0)?,+ workspace: row.get(1)?,+ project: row.get(2)?,+ cwd: row.get(3)?,+ agent: row.get(4)?,+ owner_user: row.get(5)?,+ native_session: row.get(6)?,+ })+ })+ .optional()?)+ }++ /// The scope and operator a native session may join this run from: the+ /// run's own project and its launching operator (a shared run admits only+ /// shared callers). SessionStart also pins the checkout `cwd`; a later+ /// event's `cwd` follows the agent around the checkout, so it is not+ /// compared there.+ fn admits(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ cwd: Option<&str>,+ owner_user: Option<&str>,+ ) -> bool {+ self.workspace.as_slice() == workspace_id.as_bytes()+ && self.project.as_slice() == project_id.as_bytes()+ && cwd.is_none_or(|cwd| self.cwd == cwd)+ && self.owner_user.as_deref() == owner_user+ }}/// Atomically select a workstream, expire stale leases, and open one run.@@ -801,32 +864,16 @@ pub(crate) fn link_or_adopt_native_session(};let now = Timestamp::now().as_microsecond();let tx = conn.transaction()?;- let supplied: Option<ManagedRunBoundaryRow> = tx- .query_row(- "SELECT mr.state, w.workspace_id, w.project_id, w.cwd, mr.agent_kind, mr.owner_user \- FROM managed_runs mr JOIN workstreams w ON w.id = mr.workstream_id \- WHERE mr.id = ?1",- params![input.supplied_run_id.as_bytes()],- |row| {- Ok(ManagedRunBoundaryRow {- state: row.get(0)?,- workspace: row.get(1)?,- project: row.get(2)?,- cwd: row.get(3)?,- agent: row.get(4)?,- owner_user: row.get(5)?,- })- },- )- .optional()?;+ let supplied = ManagedRunBoundaryRow::read(&tx, input.supplied_run_id)?;let selected = match supplied {Some(run) if run.state == "active" => {- let boundary_matches = run.workspace.as_slice() == input.workspace_id.as_bytes()- && run.project.as_slice() == input.project_id.as_bytes()- && run.cwd == input.cwd- && run.agent == input.agent.as_str()- && run.owner_user == input.owner_user;+ let boundary_matches = run.admits(+ input.workspace_id,+ input.project_id,+ Some(&input.cwd),+ input.owner_user.as_deref(),+ ) && run.agent == input.agent.as_str();if !boundary_matches {tx.commit()?;return Ok(ManagedRunSessionLink::Refused);@@ -886,6 +933,62 @@ pub(crate) fn link_or_adopt_native_session(})}+/// Bind the native session a later hook event of a managed run reported.+///+/// The event's admitted scope and operator must match the run's boundary, as+/// at SessionStart: a run id alone, obtained out of band, must not let another+/// operator or another project repoint the run's current session. A boundary+/// mismatch that would change nothing (the run already holds this session) is+/// a quiet no-op rather than a refusal.+pub(crate) fn link_native_session_in_scope(+ conn: &mut Connection,+ input: &LinkManagedRunSessionInScope,+) -> StoreResult<ManagedRunSessionLink> {+ if input+ .owner_user+ .as_deref()+ .is_some_and(|owner| ai_memory_core::IdentityKey::from_storage_key(owner).is_none())+ {+ return Ok(ManagedRunSessionLink::Refused);+ }+ let native_identity =+ match NativeSessionIdentity::parse(&input.native_session_id, &Sanitizer::builtin()) {+ Ok(id) => id,+ Err(_) => return Ok(ManagedRunSessionLink::NoMatch),+ };+ let now = Timestamp::now().as_microsecond();+ let tx = conn.transaction()?;+ let Some(run) =+ ManagedRunBoundaryRow::read(&tx, input.run_id)?.filter(|run| run.state == "active")+ else {+ tx.commit()?;+ return Ok(ManagedRunSessionLink::NoMatch);+ };+ if !run.admits(+ input.workspace_id,+ input.project_id,+ None,+ input.owner_user.as_deref(),+ ) {+ tx.commit()?;+ return Ok(+ if run.native_session.as_deref() == Some(native_identity.as_str()) {+ ManagedRunSessionLink::NoMatch+ } else {+ ManagedRunSessionLink::Refused+ },+ );+ }+ let linked =+ link_native_session_in_transaction(&tx, input.run_id, input.agent, &native_identity, now)?;+ tx.commit()?;+ Ok(if linked {+ ManagedRunSessionLink::Exact(input.run_id)+ } else {+ ManagedRunSessionLink::NoMatch+ })+}+/// Mark the assigned synchronization packet delivered to SessionStart.pub(crate) fn accept_context(conn: &mut Connection, run_id: ManagedRunId) -> StoreResult<bool> {let tx = conn.transaction()?;diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 9d1ed739..0aab45cc 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -36,9 +36,9 @@ use crate::session_consolidation::SessionConsolidationJob;use crate::users::{self, TOKEN_HASH_LEN};use crate::web_sessions::{self, WebSession};use crate::workstream::{- FinishWorkstreamRun, FinishedWorkstreamRun, LinkOrAdoptManagedRunSession,- ManagedRunSessionLink, PrepareWorkstreamRun, PreparedWorkstreamRun, RenameWorkstream,- RenamedWorkstream,+ FinishWorkstreamRun, FinishedWorkstreamRun, LinkManagedRunSessionInScope,+ LinkOrAdoptManagedRunSession, ManagedRunSessionLink, PrepareWorkstreamRun,+ PreparedWorkstreamRun, RenameWorkstream, RenamedWorkstream,};/// Result of atomically claiming the startup context assembled for one hook.@@ -737,6 +737,10 @@ pub(crate) enum WriteCmd {input: LinkOrAdoptManagedRunSession,reply: oneshot::Sender<StoreResult<ManagedRunSessionLink>>,},+ LinkManagedRunSessionInScope {+ input: LinkManagedRunSessionInScope,+ reply: oneshot::Sender<StoreResult<ManagedRunSessionLink>>,+ },AcceptManagedRunContext {run_id: ManagedRunId,reply: oneshot::Sender<StoreResult<bool>>,@@ -3088,6 +3092,18 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Link the native session a later hook event of a managed run reported,+ /// within the run's own project and operator boundary.+ pub async fn link_managed_run_session_in_scope(+ &self,+ input: LinkManagedRunSessionInScope,+ ) -> StoreResult<ManagedRunSessionLink> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::LinkManagedRunSessionInScope { input, reply: tx })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Acknowledge successful SessionStart delivery for a managed run.pub async fn accept_managed_run_context(&self, run_id: ManagedRunId) -> StoreResult<bool> {let (tx, rx) = oneshot::channel();@@ -4332,6 +4348,10 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {let result = crate::workstream::link_or_adopt_native_session(&mut conn, &input);send_or_warn(reply, result, "link_or_adopt_managed_run_session");}+ WriteCmd::LinkManagedRunSessionInScope { input, reply } => {+ let result = crate::workstream::link_native_session_in_scope(&mut conn, &input);+ send_or_warn(reply, result, "link_managed_run_session_in_scope");+ }WriteCmd::AcceptManagedRunContext { run_id, reply } => {let result = crate::workstream::accept_context(&mut conn, run_id);send_or_warn(reply, result, "accept_managed_run_context");diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex b88dfdde..00abb7c2 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -72,7 +72,7 @@ boundary not yet built.| 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, 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 |-| 14ap | Managed-run mutation owner and current project access (finish, cancel, heartbeat, native-session link, context acceptance) | `hooks/src/workstream.rs` `authorize_run_owner` derives `ManagedRunAuthority` only from authenticated middleware extensions and checks the real run before any mutation — for finish before status/payload/segment handling; cancel, heartbeat, link and context acceptance go through the same helper, so none is a side door around finish's rule; `ReaderPool::authorize_managed_run` and `store/src/workstream.rs` `authorize_run_mutation` use a read snapshot and the existing writer transaction, respectively. Strict resolution (`project_authz.rs` `resolve_project_authz_strict`, the canonical decision with a fail-closed resolution mode, so the reserved global-scope write gate applies here too) requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`; hooks `workstream.rs` `run_mutation_routes_refuse_another_operator` (another operator and root under another identity refused on heartbeat/link/accept/cancel, run left active; owner admitted); store `project_authz.rs` `strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within finish's writer transaction; a revocation after preflight can leave an unindexed raw segment. Cancel, heartbeat, link and acceptance check one read snapshot immediately before a single-row update (a run's owner never changes). The hook-ingress SessionStart link by `AI_MEMORY_RUN_ID` is a separate server-internal path not covered here. Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional |+| 14ap | Managed-run mutation owner and current project access (finish, cancel, heartbeat, native-session link, context acceptance) | `hooks/src/workstream.rs` `authorize_run_owner` derives `ManagedRunAuthority` only from authenticated middleware extensions and checks the real run before any mutation — for finish before status/payload/segment handling; cancel, heartbeat, link and context acceptance go through the same helper, so none is a side door around finish's rule; `ReaderPool::authorize_managed_run` and `store/src/workstream.rs` `authorize_run_mutation` use a read snapshot and the existing writer transaction, respectively. Strict resolution (`project_authz.rs` `resolve_project_authz_strict`, the canonical decision with a fail-closed resolution mode, so the reserved global-scope write gate applies here too) requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`; hooks `workstream.rs` `run_mutation_routes_refuse_another_operator` (another operator and root under another identity refused on heartbeat/link/accept/cancel, run left active; owner admitted); store `project_authz.rs` `strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within finish's writer transaction; a revocation after preflight can leave an unindexed raw segment. Cancel, heartbeat, link and acceptance check one read snapshot immediately before a single-row update (a run's owner never changes). A later hook event carrying `AI_MEMORY_RUN_ID` links its native session only through `link_native_session_in_scope`, which applies the SessionStart boundary (`ManagedRunBoundaryRow::admits`: the run's own project and operator) and refuses a foreign run id while the event itself is still captured (`router.rs` `hook_event_links_a_managed_run_only_from_its_operator`, `hook_event_in_another_project_does_not_link_the_run`, control `hook_event_links_a_shared_run_on_a_single_operator_server`; #1082). Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional || 14au | Exact native managed identity and privacy (invariant #16) | `core/src/workstream.rs` `NativeSessionIdentity` validates original bytes and exact scrub equality; `workstream/src/harness.rs` and `transcript.rs` retain selector/path restrictions; CLI `run.rs` validates old-server prepare/status, planned selectors and finish transport; hooks `workstream.rs` checks payload and selected identity before raw segments, with the existing owner/current Write preflight first; `router.rs` validates both managed auto-links while preserving legacy shared capture; store `workstream.rs` carries validated identities into link/finish SQL after finish authority and before mutation. Store, HTTP search and CLI search project invalid historical identity to empty String without rewriting history | Core `native_identity_original_bytes_limits_privacy_and_collisions`; harness `native_identity_selector_rejects_original_before_resume_arguments`; transcript `native_identity_adapter_preserves_exact_and_rejects_privacy_changes`; store multi-session `native_identity_store_link_refuses_original_dirty_bytes`, `native_identity_store_adoption_refuses_before_link`, `native_identity_store_finish_refuses_without_sql_or_index_mutation`, `native_identity_store_history_projects_unknown_without_rewriting`; hooks `native_identity_http_link_refuses_before_status_or_sql`, `native_identity_http_finish_refuses_before_segment_or_sql`, `native_identity_http_event_guard_and_configured_history_projection`, `native_identity_http_stored_identity_refuses_before_raw_segment`, router `native_identity_managed_start_refuses_but_keeps_shared_legacy_capture`; CLI `native_identity_run_preflight_refuses_before_resume_or_private_path`, `native_identity_run_old_server_refusal_prevents_child_and_transport`, `native_identity_finish_transport_refuses_before_request_and_preserves_exact_control`, `native_identity_run_status_and_expected_refuse_before_discovery`, `native_identity_run_configured_selector_refuses_before_link_or_child`, `native_identity_run_configured_old_status_refuses_before_native_io_and_finish`, `native_identity_run_configured_discovery_refuses_before_export`, suite `native_identity_search_old_server_json_projects_unknown_and_keeps_history` | Representation/privacy only: no native authenticity, file-existence, run/event correlation or outcome proof. Original legacy rows and shared observation semantics remain intact; parent finish owner/current Write rules remain mandatory || 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`; under `identity_style = "path"` (#1033) a project it creates takes `path_style_name` only while no project in the workspace holds that name (checked in the same transaction), so the same path on another forge falls back instead of being merged, and no existing project is renamed or claimed differently; `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`, `the_same_path_on_another_forge_falls_back_instead_of_merging` and `an_unclaimed_project_holding_the_path_name_is_not_taken` (both fail with the free-name check removed; controls: `the_path_style_names_a_new_project_from_the_host_less_path`, `opting_in_leaves_existing_projects_where_they_are`), `multi_session.rs` `two_operators_on_two_clones_of_one_repository_share_its_path_named_project`; `router.rs` `the_path_style_names_a_new_repository_and_never_merges_another_forge`, `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) |