Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(run): follow a /clear'd Claude session in the managed workstream

geeksilva97d61a31ea3abb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c9359fc..cb07897e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -54,6 +54,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
is now kept by both, and by the PreCompact and PostCompaction checkpoints,
which rewrote it the same way. The write no longer stamps
`observation_generation`. (#1138)
+- Fixed `ai-memory run claude` resuming the launch session forever after a
+ `/clear`: Claude Code continues a cleared conversation in a new session,
+ and the workstream now follows it — the newest one after several clears —
+ so the next launch resumes where the work actually went and that
+ transcript, not the abandoned one, is imported. Only a transcript that
+ records the `/clear` command, names this launch's session as its origin,
+ and stays in this checkout (or a directory below it) is followed. (#1135)
- Fixed the hook spool charging a spooled event's retry budget while the
server was unreachable: an endpoint-level delivery failure (connection
refused, timeout, DNS — the existing `Unreachable` classification) no
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index e7ce3f01..9034d675 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -12,11 +12,11 @@ use ai_memory_core::{
PrepareManagedRunResponse, Sanitizer, SessionId,
};
use ai_memory_workstream::{
- AmbiguousNativeSession, ExportedTranscript, FORWARDED_ENV_NAMES, JailChecklistItem,
- JailHostFacts, JailSupport, JailToggleChoice, JailToggleKind, LaunchMode, LaunchPlan,
- LaunchRoots, ManagedHarness, NativeSessionCandidate, ai_jail_support,
+ AmbiguousNativeSession, ClaudeContinuation, ExportedTranscript, FORWARDED_ENV_NAMES,
+ JailChecklistItem, JailHostFacts, JailSupport, JailToggleChoice, JailToggleKind, LaunchMode,
+ LaunchPlan, LaunchRoots, ManagedHarness, NativeSessionCandidate, ai_jail_support,
allows_native_session_adoption, apply_claude_true_yolo, apply_yolo, build_ai_jail_invocation,
- build_launch_plan, build_launch_plan_with_env_lookup, claude_attached_background_session,
+ build_launch_plan, build_launch_plan_with_env_lookup, claude_continued_session,
claude_live_background_attach_id, claude_session_ran_in_background, clean_path,
crush_global_config_path, discover_native_session, export_transcript,
has_native_session_selector, inside_ai_jail_here, inspect_repository,
@@ -2204,10 +2204,10 @@ fn own_native_session(
}
/// A Claude session that attached to a background session (`/resume` on one
-/// the Claude Code daemon hosts) went on in that session's transcript, so the
-/// workstream follows it. Otherwise the next launch resumes the foreground
-/// session, which holds none of the conversation.
-fn follow_claude_background_session(
+/// the Claude Code daemon hosts) or was `/clear`ed went on in another
+/// transcript, so the workstream follows it. Otherwise the next launch resumes
+/// the launch session, which holds none of the later conversation.
+fn follow_claude_continued_session(
plan: &LaunchPlan,
harness: ManagedHarness,
home: &Path,
@@ -2218,25 +2218,23 @@ fn follow_claude_background_session(
if harness != ManagedHarness::Claude {
return own;
}
- match claude_attached_background_session(
- home,
- cwd,
- plan.session_dir.as_deref(),
- &own,
- started_at,
- ) {
- Ok(Some(background)) => {
+ match claude_continued_session(home, cwd, plan.session_dir.as_deref(), &own, started_at) {
+ Ok(Some(continuation)) => {
+ let how = match &continuation {
+ ClaudeContinuation::Background(_) => "continued in background session",
+ ClaudeContinuation::Cleared(_) => "was cleared into session",
+ };
eprintln!(
- "ai-memory: Claude session {} continued in background session {}; the workstream now follows it",
+ "ai-memory: Claude session {} {how} {}; the workstream now follows it",
display_session_id(&own),
- display_session_id(&background)
+ display_session_id(continuation.session_id())
);
- background
+ continuation.session_id().to_owned()
}
Ok(None) => own,
Err(error) => {
eprintln!(
- "ai-memory: could not check whether Claude session {} moved to a background session ({error}); keeping it",
+ "ai-memory: could not check whether Claude session {} moved to another session ({error}); keeping it",
display_session_id(&own)
);
own
@@ -2261,7 +2259,7 @@ async fn resolve_native_session_after_run(
NativeSessionIdentity::parse(id, sanitizer)?;
}
if let Ok(Some(own)) = own_native_session(plan, harness, home, cwd, server_status, sanitizer) {
- return Ok(Some(follow_claude_background_session(
+ return Ok(Some(follow_claude_continued_session(
plan, harness, home, cwd, own, started_at,
)));
}
@@ -7019,6 +7017,68 @@ mod tests {
assert_eq!(resolve(&plan).await.as_deref(), Some("bg"));
}
+ #[tokio::test]
+ async fn a_claude_run_that_was_cleared_follows_the_new_session() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ let project = temp.path().join(".claude/projects/-repo");
+ std::fs::create_dir_all(&cwd).unwrap();
+ std::fs::create_dir_all(&project).unwrap();
+ let started_at = SystemTime::now() - std::time::Duration::from_secs(60);
+ let turn = |session: &str| {
+ serde_json::json!({
+ "type": "user",
+ "sessionId": session,
+ "session_id": "launch",
+ "cwd": cwd,
+ })
+ };
+ std::fs::write(
+ project.join("launch.jsonl"),
+ format!("{}\n", turn("launch")),
+ )
+ .unwrap();
+ let mut plan =
+ build_launch_plan(ManagedHarness::Claude, None, Vec::new(), Some("launch")).unwrap();
+ // CLAUDE_CONFIG_DIR in the developer's environment would point the
+ // scan away from the transcripts planted under `temp`.
+ plan.session_dir = None;
+ let resolve = || {
+ let plan = plan.clone();
+ let home = temp.path().to_path_buf();
+ let cwd = cwd.clone();
+ async move {
+ resolve_native_session_after_run(
+ &plan,
+ ManagedHarness::Claude,
+ &home,
+ &cwd,
+ started_at,
+ None,
+ &Sanitizer::builtin(),
+ )
+ .await
+ .unwrap()
+ }
+ };
+ assert_eq!(resolve().await.as_deref(), Some("launch"));
+
+ // `/clear` inside the resumed session: the conversation goes on in a
+ // new transcript, so the next launch must resume that one.
+ let clear = serde_json::json!({
+ "type": "user",
+ "sessionId": "cleared",
+ "cwd": cwd,
+ "message": {"role": "user", "content": "<command-name>/clear</command-name>"},
+ });
+ std::fs::write(
+ project.join("cleared.jsonl"),
+ format!("{clear}\n{}\n", turn("cleared")),
+ )
+ .unwrap();
+ assert_eq!(resolve().await.as_deref(), Some("cleared"));
+ }
+
/// A session linked during the run was reported by this run's child, so
/// it wins over a newer session another launch made in the same checkout,
/// even when it repeats the session the run was prepared with. A child's
diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rs
index e00ad78f..b2d7ecff 100644
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@ -25,10 +25,10 @@ pub use repository::{
RepositoryFingerprints, RepositoryIdentity, inspect_repository, inspect_repository_fingerprints,
};
pub use transcript::{
- AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate,
- claude_attached_background_session, claude_live_background_attach_id,
- claude_session_ran_in_background, discover_native_session, export_transcript,
- kiro_harness_from_source_cursor, kiro_v3_resume_uses_default_store, list_native_sessions,
- native_memory_dir, native_session_exists, native_session_in_checkout, native_store_root,
+ AmbiguousNativeSession, ClaudeContinuation, ExportedTranscript, NativeSessionCandidate,
+ claude_continued_session, claude_live_background_attach_id, claude_session_ran_in_background,
+ discover_native_session, export_transcript, kiro_harness_from_source_cursor,
+ kiro_v3_resume_uses_default_store, list_native_sessions, native_memory_dir,
+ native_session_exists, native_session_in_checkout, native_store_root,
wait_for_transcript_flush,
};
diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rs
index 20c9f03b..d01bb877 100644
--- a/crates/ai-memory-workstream/src/transcript.rs
+++ b/crates/ai-memory-workstream/src/transcript.rs
@@ -280,27 +280,53 @@ pub fn claude_live_background_attach_id(
})
}
-/// Find the Claude Code background session that `native_session_id` attached
-/// to during this run, if any.
+/// Where a Claude Code launch's conversation went on, when it left the
+/// session the launcher started or resumed.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ClaudeContinuation {
+ /// `/resume` attached to a background session the daemon hosts.
+ Background(String),
+ /// `/clear` started a new session in the same process.
+ Cleared(String),
+}
+
+impl ClaudeContinuation {
+ /// The native session the conversation continued in.
+ pub fn session_id(&self) -> &str {
+ match self {
+ Self::Background(id) | Self::Cleared(id) => id,
+ }
+ }
+}
+
+/// Find the session `native_session_id`'s Claude Code process continued in
+/// during this run, if it left it.
+///
+/// Every record a Claude Code process writes names the session the process
+/// launched with in `session_id`, while `sessionId` names the transcript's own
+/// session. Two moves leave that launch session behind:
+///
+/// - `/resume` on a background session (one hosted by the Claude Code daemon)
+/// keeps going in the background session's transcript, whose records carry
+/// `"sessionKind": "bg"`. The daemon's hooks never see this run's id.
+/// - `/clear` starts a new session whose transcript records the `/clear`
+/// command itself.
///
-/// `/resume` on a background session (one hosted by the Claude Code daemon)
-/// does not continue the foreground session: the conversation keeps going in
-/// the background session's own transcript, whose records carry
-/// `"sessionKind": "bg"` and name the attached foreground session in
-/// `session_id`. The daemon's hooks never see this run's id, so without this
-/// the workstream stays on the foreground session and the next launch resumes
-/// a transcript with no conversation in it.
+/// Without this the workstream stays on the launch session, and the next
+/// launch resumes a transcript that holds none of the later conversation.
///
-/// Only transcripts written since `started_at` are read, the newest first,
-/// and a record must also match this checkout. Transcripts without those
-/// fields (older Claude Code builds) never match.
-pub fn claude_attached_background_session(
+/// Only transcripts written since `started_at` are read, the newest first, so
+/// a chain of `/clear`s ends on the last one. A background record must match
+/// this checkout exactly; a cleared session may have moved into a directory
+/// below it. Transcripts without those fields (older Claude Code builds)
+/// never match.
+pub fn claude_continued_session(
home: &Path,
cwd: &Path,
session_dir: Option<&Path>,
native_session_id: &str,
started_at: SystemTime,
-) -> Result<Option<String>> {
+) -> Result<Option<ClaudeContinuation>> {
if !valid_native_session_id(native_session_id) {
return Ok(None);
}
@@ -315,44 +341,65 @@ pub fn claude_attached_background_session(
if modified(&path).is_some_and(|time| time + Duration::from_secs(2) < started_at) {
break;
}
- if path
- .file_stem()
- .is_some_and(|stem| stem == std::ffi::OsStr::new(native_session_id))
- {
+ let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
+ continue;
+ };
+ if stem == native_session_id {
continue;
}
let reader = BufReader::new(File::open(&path)?);
+ let mut cleared = false;
+ let mut cleared_in_checkout = false;
for line in reader.lines() {
let line = line?;
- if !line.contains(&attached_marker) {
+ let clear_command = line.contains(CLAUDE_CLEAR_COMMAND);
+ if !clear_command && !line.contains(&attached_marker) {
continue;
}
let Ok(value) = serde_json::from_str::<Value>(&line) else {
continue;
};
- let background = value.get("sessionKind").and_then(Value::as_str) == Some("bg");
- let attached =
- value.get("session_id").and_then(Value::as_str) == Some(native_session_id);
- let in_checkout = value
- .get("cwd")
- .and_then(Value::as_str)
- .is_some_and(|recorded| same_path(Path::new(recorded), cwd));
let Some(session) = value.get("sessionId").and_then(Value::as_str) else {
continue;
};
- if background
- && attached
- && in_checkout
- && session != native_session_id
- && valid_native_session_id(session)
+ if session == native_session_id || !valid_native_session_id(session) {
+ continue;
+ }
+ let recorded_cwd = value.get("cwd").and_then(Value::as_str).map(Path::new);
+ if clear_command && session == stem && is_claude_clear_command(&value) {
+ cleared = true;
+ }
+ if value.get("session_id").and_then(Value::as_str) != Some(native_session_id) {
+ continue;
+ }
+ if value.get("sessionKind").and_then(Value::as_str) == Some("bg") {
+ if recorded_cwd.is_some_and(|recorded| same_path(recorded, cwd)) {
+ return Ok(Some(ClaudeContinuation::Background(session.to_string())));
+ }
+ } else if session == stem
+ && recorded_cwd.is_some_and(|recorded| path_within(recorded, cwd))
{
- return Ok(Some(session.to_string()));
+ cleared_in_checkout = true;
}
}
+ if cleared && cleared_in_checkout {
+ return Ok(Some(ClaudeContinuation::Cleared(stem.to_string())));
+ }
}
Ok(None)
}
+const CLAUDE_CLEAR_COMMAND: &str = "<command-name>/clear</command-name>";
+
+/// The user record Claude Code writes for a `/clear` typed at its prompt.
+fn is_claude_clear_command(value: &Value) -> bool {
+ value.get("type").and_then(Value::as_str) == Some("user")
+ && value
+ .pointer("/message/content")
+ .and_then(Value::as_str)
+ .is_some_and(|content| content.trim_start().starts_with(CLAUDE_CLEAR_COMMAND))
+}
+
/// List newest native sessions whose recorded working directory matches the
/// current checkout. Native stores are opened read-only and unrelated paths are
/// excluded before candidates reach the launcher prompt.
@@ -4598,7 +4645,7 @@ mod tests {
}
#[test]
- fn claude_attached_background_session_follows_only_this_checkouts_bg_records() {
+ fn claude_continued_session_follows_only_this_checkouts_bg_records() {
let temp = tempfile::tempdir().unwrap();
let cwd = temp.path().join("repo");
let other = temp.path().join("other");
@@ -4629,7 +4676,9 @@ mod tests {
value
};
let find = |id: &str| {
- claude_attached_background_session(temp.path(), &cwd, None, id, started_at).unwrap()
+ claude_continued_session(temp.path(), &cwd, None, id, started_at)
+ .unwrap()
+ .map(|continuation| continuation.session_id().to_owned())
};
// The foreground transcript names itself; it is never the answer.
@@ -4675,6 +4724,126 @@ mod tests {
assert_eq!(find("unrelated"), None);
}
+ #[test]
+ fn claude_continued_session_follows_only_this_launchs_clear() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ let nested = cwd.join("packages/app");
+ let other = temp.path().join("other");
+ let project = temp.path().join(".claude/projects/-repo");
+ fs::create_dir_all(&nested).unwrap();
+ fs::create_dir_all(&other).unwrap();
+ fs::create_dir_all(&project).unwrap();
+ let started_at = SystemTime::now() - Duration::from_secs(60);
+ let write = |name: &str, records: &[Value], age: Duration| {
+ let path = project.join(format!("{name}.jsonl"));
+ let body = records
+ .iter()
+ .map(|record| format!("{record}\n"))
+ .collect::<String>();
+ fs::write(&path, body).unwrap();
+ File::options()
+ .write(true)
+ .open(&path)
+ .unwrap()
+ .set_modified(SystemTime::now() - age)
+ .unwrap();
+ };
+ // Claude Code's real shape: the `/clear` record carries no
+ // `session_id`; later records name the launch session there.
+ let clear = |session: &str, cwd: &Path| {
+ json!({
+ "type": "user",
+ "sessionId": session,
+ "cwd": cwd,
+ "message": {"role": "user", "content": format!(
+ "{CLAUDE_CLEAR_COMMAND}\n <command-message>clear</command-message>"
+ )},
+ })
+ };
+ let turn = |session: &str, launch: &str, cwd: &Path| json!({"type": "user", "sessionId": session, "session_id": launch, "cwd": cwd});
+ let find =
+ |id: &str| claude_continued_session(temp.path(), &cwd, None, id, started_at).unwrap();
+ let recent = Duration::from_secs(5);
+
+ write("launch", &[turn("launch", "launch", &cwd)], recent);
+ assert_eq!(find("launch"), None);
+
+ // A transcript that names the launch session without having been
+ // cleared is neither a clear nor a background continuation.
+ write("plain", &[turn("plain", "launch", &cwd)], recent);
+ // Text that merely quotes `/clear` is not the command record.
+ write(
+ "quoted",
+ &[
+ json!({"type": "user", "sessionId": "quoted", "cwd": cwd,
+ "message": {"role": "user", "content": format!("what does {CLAUDE_CLEAR_COMMAND} do?")}}),
+ turn("quoted", "launch", &cwd),
+ ],
+ recent,
+ );
+ // Another checkout's clear, and a concurrent launch's clear here.
+ write(
+ "elsewhere",
+ &[
+ clear("elsewhere", &other),
+ turn("elsewhere", "launch", &other),
+ ],
+ recent,
+ );
+ write(
+ "concurrent",
+ &[
+ clear("concurrent", &cwd),
+ turn("concurrent", "other-launch", &cwd),
+ ],
+ recent,
+ );
+ // A subagent file holds the cleared session's records under its own
+ // stem; it is not a session to resume.
+ write(
+ "agent-1",
+ &[clear("subagent", &cwd), turn("subagent", "launch", &cwd)],
+ recent,
+ );
+ // A clear made before this run started is not read.
+ write(
+ "stale",
+ &[clear("stale", &cwd), turn("stale", "launch", &cwd)],
+ Duration::from_secs(600),
+ );
+ assert_eq!(find("launch"), None);
+ assert_eq!(
+ find("other-launch"),
+ Some(ClaudeContinuation::Cleared("concurrent".into()))
+ );
+
+ // The clear this launch made, even after moving below the checkout.
+ write(
+ "cleared",
+ &[clear("cleared", &cwd), turn("cleared", "launch", &nested)],
+ Duration::from_secs(3),
+ );
+ assert_eq!(
+ find("launch"),
+ Some(ClaudeContinuation::Cleared("cleared".into()))
+ );
+
+ // A second `/clear` in the same process: the newest one wins.
+ write(
+ "cleared-again",
+ &[
+ clear("cleared-again", &cwd),
+ turn("cleared-again", "launch", &cwd),
+ ],
+ Duration::from_secs(1),
+ );
+ assert_eq!(
+ find("launch"),
+ Some(ClaudeContinuation::Cleared("cleared-again".into()))
+ );
+ }
+
#[test]
fn claude_adapter_excludes_thinking_and_keeps_tools() {
let value = json!({"type":"assistant","uuid":"record","timestamp":"2026-01-01T00:00:00Z","message":{"role":"assistant","content":[
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index aa1c1d9f..1a5f5739 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -75,7 +75,7 @@ boundary not yet built.
| 11i | OpenCode executable probing and generated-config cleanup (#1097) | `ai-memory-cli/src/config.rs` captures the full process environment once in typed `RuntimeEnv`; `run.rs` overlays explicit `run --env` values with platform key semantics and uses that same effective environment for executable resolution, probing, and launch without rereading process environment; `opencode_dialect.rs` invokes only direct argv `--version`, caps output and time, and rejects malformed/future majors. Automatic launch skips only OpenCode on probe failure; explicit OpenCode fails. `install_hooks.rs` quarantines the incompatible sibling before reading its exact ownership markers, restores unowned content with an atomic no-replace link, and never deletes or overwrites a concurrent replacement; `install_mcp.rs` owns the shared dual-schema endpoint/token inference used by both installers, rejects conflicting generated V1/V2 entries before mutation, and migrates an alternate-major entry only when endpoint, generated shape, and absent-or-Authorization-only headers match, preserving custom headers and ambiguous entries; auto-wire migrates MCP before hooks infer from that exact config path and skips hook mutation when transition preflight fails | `run.rs` `automatic_opencode_probe_failure_keeps_another_harness_available`, `opencode_executable_probe_selects_v2_for_launch_and_autowire`, effective-child-environment PATH casing controls, fake V1/V2/env-derived-major/malformed/future/timeout executable tests, `setup-agent` V1/V2 no-probe integration controls; `install_hooks.rs` `opencode_plugin_cleanup_removes_only_exact_owned_incompatible_sibling`, `opencode_plugin_cleanup_preserves_a_concurrent_user_replacement`, `opencode_plugin_restore_moves_quarantine_when_destination_is_free`, `opencode_plugin_restore_preserves_an_existing_replacement`, `opencode_plugin_restore_does_not_replace_a_file_created_at_restore_window`, `opencode_plugin_cleanup_does_not_escape_custom_target_directory`; `install_mcp.rs` `opencode_install_reuses_owned_endpoint_and_token_across_major_transitions`, `opencode_install_refuses_conflicting_owned_transition_entries`, `opencode_install_does_not_infer_from_a_user_owned_transition_entry`, `opencode_mcp_migration_moves_only_owned_alternate_shape`, `opencode_mcp_migration_preserves_ambiguous_user_entry`, `opencode_mcp_migration_preserves_custom_headers`, `opencode_mcp_migration_accepts_only_historical_generated_headers` | STRONG for Unix process probes and platform-neutral ownership gates; exact Windows executable resolution remains covered by `run.rs` resolver tests and requires the PR `windows` label |
| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls | STRONG |
| 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments, with `sanitize_events` and `append_boundary_events` scrubbing event/checkpoint/losses content *before* the 64 KiB cap so a cap-straddling secret is never cut into an unmatchable prefix (#1113); `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, scrubbing content with the explicitly supplied configured sanitizer before its 16 KiB store-boundary bound; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`, `workstream_content_is_scrubbed_before_the_store_cap` (a credential straddling the 16 KiB store cap is redacted, not persisted as an unmatchable prefix; benign control verbatim; #1113); `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls), `finish_run_scrubs_event_content_before_the_byte_cap` and `finish_run_scrubs_boundary_events_before_the_byte_cap` (a credential straddling the 64 KiB event cap is redacted in the raw segment and never reaches the index; checkpoint/losses and benign controls; #1113); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten |
-| 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 |
+| 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_continued_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050), and to a `/clear`ed session only when that session's own transcript records the `/clear` command and names the run's session as its launch `session_id` from this checkout or below it; `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `claude_continued_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `transcript.rs` `claude_continued_session_follows_only_this_launchs_clear` (an uncleared transcript, a quoted `/clear`, another checkout's clear, a concurrent launch's clear, a subagent file, and a pre-run clear refused; own clear and the newest of two as controls); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`, `a_claude_run_that_was_cleared_follows_the_new_session`; `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous |
| 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet |
| 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users |
| 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 |