Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): scrub workstream ledger content before the byte caps (#1113)
AkitaOnRails8a751739f95e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3d152681..fc647f55 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -34,6 +34,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0the #980 / #1109 fixes established — so a straddling secret can no longerreach the spool (and through it the server) as an unredacted fragment.(#1114)+- Fixed the managed-workstream ledger capping event content *before* the+ sanitizer ever saw it: the 64 KiB per-event cap in+ `hooks::workstream::sanitize_events` truncated first, so a secret+ straddling the cutoff was cut into a prefix too short to match any+ pattern and persisted unredacted in the immutable raw segment — the same+ ordering bug as the #980 title-hint and #1109 feedback-reason leaks. The+ cap now runs after scrubbing, the server-generated checkpoint and losses+ boundary events get the same ordering, and the store's `finish_run`+ scrubs with the caller's sanitizer before its own 16 KiB bound as+ defense in depth. The stored shapes and byte limits are unchanged.+ (#1113)- Fixed the hook spool charging a spooled event's retry budget while theserver was unreachable: an endpoint-level delivery failure (connectionrefused, timeout, DNS — the existing `Unreachable` classification) nodiff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsindex 3eefa347..56e3b9c4 100644--- a/crates/ai-memory-hooks/src/workstream.rs+++ b/crates/ai-memory-hooks/src/workstream.rs@@ -1086,15 +1086,12 @@ fn sanitize_events(if event.event_id.trim().is_empty() || event.event_id.len() > MAX_EVENT_ID_BYTES {return Err("invalid workstream event id".to_string());}- if event.content.len() > MAX_EVENT_CONTENT_BYTES {- let mut end = MAX_EVENT_CONTENT_BYTES;- while !event.content.is_char_boundary(end) {- end -= 1;- }- event.content.truncate(end);- event.content.push_str("\n[truncated by ai-memory]");- }+ // Scrub the full content before the cap: truncating first could cut a+ // secret straddling the cap into a fragment too short for any pattern+ // to match, persisting the prefix verbatim (#1113, same class as+ // #980/#1109).event.content = sanitizer.scrub(&event.content);+ truncate_owned(&mut event.content, MAX_EVENT_CONTENT_BYTES);if let Some(role) = &event.role&& (role.len() > 32|| !role@@ -1138,6 +1135,8 @@ fn append_boundary_events(if checkpoint.is_empty() {checkpoint.push_str("No Git repository checkpoint was available.");}+ // Scrub-then-cap, same ordering as `sanitize_events` above (#1113).+ let mut checkpoint = sanitizer.scrub(&checkpoint);truncate_owned(&mut checkpoint, MAX_EVENT_CONTENT_BYTES);request.events.push(NewWorkstreamEvent {event_id: format!("managed-run:{run_id}:checkpoint"),@@ -1146,7 +1145,7 @@ fn append_boundary_events(source_record_id: None,kind: WorkstreamEventKind::Checkpoint,role: None,- content: sanitizer.scrub(&checkpoint),+ content: checkpoint,occurred_at: None,metadata: serde_json::json!({ "exit_code": request.exit_code }),});@@ -1155,6 +1154,7 @@ fn append_boundary_events(for loss in &request.losses {let _ = writeln!(content, "- {loss}");}+ let mut content = sanitizer.scrub(&content);truncate_owned(&mut content, MAX_EVENT_CONTENT_BYTES);request.events.push(NewWorkstreamEvent {event_id: format!("managed-run:{run_id}:losses"),@@ -1163,7 +1163,7 @@ fn append_boundary_events(source_record_id: None,kind: WorkstreamEventKind::Annotation,role: None,- content: sanitizer.scrub(&content),+ content,occurred_at: None,metadata: serde_json::json!({ "loss_count": request.losses.len() }),});@@ -2004,6 +2004,225 @@ mod tests {);}+ /// A credential straddling the 64 KiB event cap must be scrubbed before+ /// the cap runs (#1113): truncating first leaves an `sk-` prefix too short+ /// to match any pattern, persisting it verbatim. The segment file is the+ /// durable artifact written from the sanitized events.+ #[tokio::test]+ async fn finish_run_scrubs_event_content_before_the_byte_cap() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());+ let (workspace_id, project_id) = seed_scope(&store).await;+ let run = store+ .writer+ .prepare_workstream_run(prepare_input(+ workspace_id,+ project_id,+ AgentKind::Codex,+ "launcher",+ ))+ .await+ .unwrap();+ // The key starts 18 bytes before the cap: capping first would keep+ // `sk-` plus 15 characters, one short of the 16 the pattern needs.+ // The space before the tail matters — without it the greedy key+ // pattern would swallow the tail into the same match and the+ // scrubbed text would never reach the cap.+ let credential = format!("sk-{}", "A".repeat(40));+ let content = format!(+ "{}{credential} {}",+ "x".repeat(MAX_EVENT_CONTENT_BYTES - 18),+ "y".repeat(2 * 1024),+ );+ let response = finish_run(+ State(state.clone()),+ None,+ None,+ None,+ None,+ AxumPath(run.run_id.to_string()),+ Json(FinishManagedRunRequest {+ native_session_id: Some("native-1".into()),+ source_cursor: None,+ events: vec![+ NewWorkstreamEvent {+ event_id: "straddling".into(),+ agent: AgentKind::Codex,+ native_session_id: "native-1".into(),+ source_record_id: Some("record-1".into()),+ kind: WorkstreamEventKind::Message,+ role: Some("assistant".into()),+ content,+ occurred_at: None,+ metadata: serde_json::Value::Null,+ },+ NewWorkstreamEvent {+ event_id: "control".into(),+ agent: AgentKind::Codex,+ native_session_id: "native-1".into(),+ source_record_id: Some("record-2".into()),+ kind: WorkstreamEventKind::Message,+ role: Some("assistant".into()),+ content: "plain ledger note".into(),+ occurred_at: None,+ metadata: serde_json::Value::Null,+ },+ ],+ complete: false,+ checkpoint: Default::default(),+ exit_code: None,+ losses: Vec::new(),+ }),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ let segment_dir = temp+ .path()+ .join("raw/workstreams")+ .join(run.workstream_id.to_string())+ .join("segments");+ let path = std::fs::read_dir(segment_dir)+ .unwrap()+ .next()+ .unwrap()+ .unwrap()+ .path();+ let raw = std::fs::read_to_string(path).unwrap();+ let events: Vec<serde_json::Value> = raw+ .lines()+ .map(|line| serde_json::from_str(line).unwrap())+ .collect();+ let straddling = events+ .iter()+ .find(|event| event["event_id"] == "straddling")+ .unwrap();+ let stored = straddling["content"].as_str().unwrap();+ assert!(+ stored.contains("[REDACTED:api_key]"),+ "straddling credential must be redacted before the cap: {stored:?}"+ );+ assert!(+ !stored.contains("sk-"),+ "cap-straddling credential prefix leaked: {stored:?}"+ );+ assert!(+ stored.ends_with("[truncated by ai-memory]"),+ "len {} tail {:?}",+ stored.len(),+ &stored[stored.len().saturating_sub(80)..]+ );+ assert!(+ stored.len() <= MAX_EVENT_CONTENT_BYTES + "\n[truncated by ai-memory]".len(),+ "stored content exceeds the cap plus its marker: {} bytes",+ stored.len()+ );+ let control = events+ .iter()+ .find(|event| event["event_id"] == "control")+ .unwrap();+ assert_eq!(control["content"], "plain ledger note");+ let hits = store+ .reader+ .search_workstream_events(+ run.workstream_id,+ String::new(),+ 10,+ state.sanitizer.clone(),+ )+ .await+ .unwrap();+ assert!(+ hits.iter().all(|hit| !hit.content.contains("sk-")),+ "indexed content leaked the credential prefix"+ );+ }++ /// The server-generated checkpoint and losses events get the same+ /// scrub-before-cap ordering (#1113).+ #[tokio::test]+ async fn finish_run_scrubs_boundary_events_before_the_byte_cap() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());+ let (workspace_id, project_id) = seed_scope(&store).await;+ let run = store+ .writer+ .prepare_workstream_run(prepare_input(+ workspace_id,+ project_id,+ AgentKind::Codex,+ "launcher",+ ))+ .await+ .unwrap();+ let credential = || format!("sk-{}", "A".repeat(40));+ // "Changed paths:\n" (15) + "- {filler}\n" (2 + 65498 + 1) + "- " (2)+ // places the key 18 bytes before the cap.+ let checkpoint = ai_memory_core::WorkstreamCheckpoint {+ changed_paths: vec!["x".repeat(65_498), credential(), "y".repeat(2 * 1024)],+ ..Default::default()+ };+ // "Transcript extraction losses:\n" (30) + "- {filler}\n" + "- "+ // places the key at the same offset.+ let losses = vec!["x".repeat(65_483), credential(), "y".repeat(2 * 1024)];+ let response = finish_run(+ State(state.clone()),+ None,+ None,+ None,+ None,+ AxumPath(run.run_id.to_string()),+ Json(FinishManagedRunRequest {+ native_session_id: Some("native-1".into()),+ source_cursor: None,+ events: Vec::new(),+ complete: true,+ checkpoint,+ exit_code: Some(0),+ losses,+ }),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ let segment_dir = temp+ .path()+ .join("raw/workstreams")+ .join(run.workstream_id.to_string())+ .join("segments");+ let path = std::fs::read_dir(segment_dir)+ .unwrap()+ .next()+ .unwrap()+ .unwrap()+ .path();+ let raw = std::fs::read_to_string(path).unwrap();+ for suffix in ["checkpoint", "losses"] {+ let event: serde_json::Value = raw+ .lines()+ .map(|line| serde_json::from_str(line).unwrap())+ .find(|event: &serde_json::Value| {+ event["event_id"] == format!("managed-run:{}:{suffix}", run.run_id)+ })+ .unwrap();+ let stored = event["content"].as_str().unwrap();+ assert!(+ stored.contains("[REDACTED:api_key]"),+ "{suffix} must be redacted before the cap: {stored:?}"+ );+ assert!(+ !stored.contains("sk-"),+ "{suffix} leaked the cap-straddling credential prefix"+ );+ assert!(stored.ends_with("[truncated by ai-memory]"));+ assert!(+ stored.len() <= MAX_EVENT_CONTENT_BYTES + "\n[truncated by ai-memory]".len(),+ "{suffix} exceeds the cap plus its marker: {} bytes",+ stored.len()+ );+ }+ }+/// The launcher reads whether the run's child linked a session from the/// run status, so the route must carry it.#[tokio::test]diff --git a/crates/ai-memory-store/src/workstream.rs b/crates/ai-memory-store/src/workstream.rsindex 87227430..3fb23419 100644--- a/crates/ai-memory-store/src/workstream.rs+++ b/crates/ai-memory-store/src/workstream.rs@@ -1175,13 +1175,17 @@ pub(crate) fn finish_run(&event.metadata,);let metadata_json = serde_json::to_string(&metadata)?;- let content =- ai_memory_core::truncate_utf8_bytes(&event.content, WORKSTREAM_CONTENT_MAX_BYTES);- latest += 1;// Store-boundary bound (defense in depth): the hook layer already- // scrubs and normalizes event content, but the store is the last gate- // before durable persistence — bound the free-text `content` so a- // caller that ever forgets cannot write unbounded prose to the DB.+ // scrubs and caps event content, but the store is the last gate+ // before durable persistence — scrub with the caller's sanitizer and+ // then bound the free-text `content`, so a caller that ever forgets+ // cannot write unbounded prose (or a secret straddling the cap, cut+ // into an unmatched prefix, #1113) to the DB.+ let content = ai_memory_core::truncate_utf8_bytes(+ &input.sanitizer.scrub(&event.content),+ WORKSTREAM_CONTENT_MAX_BYTES,+ );+ latest += 1;tx.execute("INSERT INTO workstream_events( \workstream_id, sequence, event_id, agent_kind, native_session_id, \diff --git a/crates/ai-memory-store/tests/suite/workstream_provenance.rs b/crates/ai-memory-store/tests/suite/workstream_provenance.rsindex 126553fb..02b90ecf 100644--- a/crates/ai-memory-store/tests/suite/workstream_provenance.rs+++ b/crates/ai-memory-store/tests/suite/workstream_provenance.rs@@ -546,6 +546,77 @@ async fn workstream_provenance_retry_with_marker_matching_pattern_is_idempotent();}+/// Defense in depth at the store boundary (#1113): even a caller that hands+/// `finish_workstream_run` an unscrubbed event gets the credential scrubbed+/// before the 16 KiB content cap, so a secret straddling the cap is never+/// cut into an unmatchable prefix and persisted verbatim.+#[tokio::test]+async fn workstream_content_is_scrubbed_before_the_store_cap() {+ const CONTENT_CAP: usize = 16 * 1024;+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let run = prepare(&store).await;+ // The key starts 18 bytes before the truncation cut (the cap minus the+ // ellipsis reserve): capping first would keep `sk-` plus 15 characters,+ // one short of the 16 the pattern needs, leaking the prefix verbatim.+ // The space before the tail keeps the greedy key pattern from swallowing+ // the tail, so the scrubbed text still crosses the cap.+ let mut hostile = event("straddling", "record-1", json!({}));+ hostile.content = format!(+ "{}sk-{} {}",+ "x".repeat(CONTENT_CAP - 21),+ "A".repeat(40),+ "y".repeat(2 * 1024),+ );+ let mut control = event("control", "record-2", json!({}));+ control.content = "plain ledger note".into();+ assert_eq!(+ store+ .writer+ .finish_workstream_run(+ local_authority(),+ finish(run.run_id, vec![hostile, control])+ )+ .await+ .unwrap()+ .imported_events,+ 2+ );+ let conn = Connection::open(store.db_path()).unwrap();+ let content: String = conn+ .query_row(+ "SELECT content FROM workstream_events WHERE event_id = 'straddling'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert!(+ content.contains("[REDACTED:api_key]"),+ "straddling credential must be redacted before the cap: {content:?}"+ );+ assert!(+ !content.contains("sk-"),+ "cap-straddling credential prefix leaked"+ );+ assert!(+ content.ends_with('…'),+ "scrubbed content must still cross the cap and be truncated"+ );+ assert!(+ content.len() <= CONTENT_CAP,+ "stored content exceeds the cap: {} bytes",+ content.len()+ );+ let control: String = conn+ .query_row(+ "SELECT content FROM workstream_events WHERE event_id = 'control'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(control, "plain ledger note");+}+/// A single-user (no database users) caller: the finish gate admits it, so/// these provenance tests exercise only the storage boundary.fn local_authority() -> ai_memory_store::ManagedRunAuthority {diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 9b48baaa..aa1c1d9f 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -74,7 +74,7 @@ boundary not yet built.| 11h | Docker-wrapper capture-policy capability (#1002) | `bin/ai-memory` routes ordinary Linux/macOS `install-hooks` and upgrade refreshes through the stable checksum-verified native host client, so the hook process executes the capture-policy boundary in 11b before spool/network. Only an explicit `AI_MEMORY_HOOK_PLATFORM=posix|windows` retains the documented script compatibility path and its warning; `AI_MEMORY_NATIVE_BIN` may not point back to the wrapper | `scripts/check-native-packaging.sh` `Checking host-launch wrapper routing`: a default allowlist install reaches the fake native client while a Docker executable that always fails proves no container fallback occurred; the explicit `posix` control reaches fake Docker and adds no native invocation; the self-referential native override is refused | STRONG on the shipped Linux/macOS wrapper. Windows and remote/manual script installers remain explicitly outside capture-policy v1 || 11i | OpenCode executable probing and generated-config cleanup (#1097) | `ai-memory-cli/src/config.rs` captures the full process environment once in typed `RuntimeEnv`; `run.rs` overlays explicit `run --env` values with platform key semantics and uses that same effective environment for executable resolution, probing, and launch without rereading process environment; `opencode_dialect.rs` invokes only direct argv `--version`, caps output and time, and rejects malformed/future majors. Automatic launch skips only OpenCode on probe failure; explicit OpenCode fails. `install_hooks.rs` quarantines the incompatible sibling before reading its exact ownership markers, restores unowned content with an atomic no-replace link, and never deletes or overwrites a concurrent replacement; `install_mcp.rs` owns the shared dual-schema endpoint/token inference used by both installers, rejects conflicting generated V1/V2 entries before mutation, and migrates an alternate-major entry only when endpoint, generated shape, and absent-or-Authorization-only headers match, preserving custom headers and ambiguous entries; auto-wire migrates MCP before hooks infer from that exact config path and skips hook mutation when transition preflight fails | `run.rs` `automatic_opencode_probe_failure_keeps_another_harness_available`, `opencode_executable_probe_selects_v2_for_launch_and_autowire`, effective-child-environment PATH casing controls, fake V1/V2/env-derived-major/malformed/future/timeout executable tests, `setup-agent` V1/V2 no-probe integration controls; `install_hooks.rs` `opencode_plugin_cleanup_removes_only_exact_owned_incompatible_sibling`, `opencode_plugin_cleanup_preserves_a_concurrent_user_replacement`, `opencode_plugin_restore_moves_quarantine_when_destination_is_free`, `opencode_plugin_restore_preserves_an_existing_replacement`, `opencode_plugin_restore_does_not_replace_a_file_created_at_restore_window`, `opencode_plugin_cleanup_does_not_escape_custom_target_directory`; `install_mcp.rs` `opencode_install_reuses_owned_endpoint_and_token_across_major_transitions`, `opencode_install_refuses_conflicting_owned_transition_entries`, `opencode_install_does_not_infer_from_a_user_owned_transition_entry`, `opencode_mcp_migration_moves_only_owned_alternate_shape`, `opencode_mcp_migration_preserves_ambiguous_user_entry`, `opencode_mcp_migration_preserves_custom_headers`, `opencode_mcp_migration_accepts_only_historical_generated_headers` | STRONG for Unix process probes and platform-neutral ownership gates; exact Windows executable resolution remains covered by `run.rs` resolver tests and requires the PR `windows` label || 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls | STRONG |-| 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments; `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, using an explicitly supplied configured sanitizer; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`; `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten |+| 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments, with `sanitize_events` and `append_boundary_events` scrubbing event/checkpoint/losses content *before* the 64 KiB cap so a cap-straddling secret is never cut into an unmatchable prefix (#1113); `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, scrubbing content with the explicitly supplied configured sanitizer before its 16 KiB store-boundary bound; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`, `workstream_content_is_scrubbed_before_the_store_cap` (a credential straddling the 16 KiB store cap is redacted, not persisted as an unmatchable prefix; benign control verbatim; #1113); `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls), `finish_run_scrubs_event_content_before_the_byte_cap` and `finish_run_scrubs_boundary_events_before_the_byte_cap` (a credential straddling the 64 KiB event cap is redacted in the raw segment and never reaches the index; checkpoint/losses and benign controls; #1113); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten || 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_attached_background_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050); `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `claude_attached_background_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`; `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous || 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet || 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users |