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 Claude background session the run attached to

Éverton Toffanetto285101b51203
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c0229db6..403b6db5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
provider. (#1026)
### Fixed
+- Fixed a managed Claude Code run losing its conversation after `/resume` on a
+ Claude Code background session. The run used to finish on the foreground
+ session it started with, which held none of the conversation, so the next
+ `ai-memory run claude` or `continue` resumed it and Claude opened an empty
+ session. A Claude run now finishes on the background session its own
+ session attached to in this checkout, found from that transcript's
+ `sessionKind: "bg"` records; another launch's background session is never
+ taken. (#1050)
- Fixed interrupted launchers blocking an immediate managed-workstream restart
by adding explicit `ai-memory run --force-unlock` recovery. The server
atomically expires and replaces only a lease attributed to the same
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index 80be0fda..4bfc3d58 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -16,14 +16,14 @@ use ai_memory_workstream::{
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, crush_global_config_path,
- discover_native_session, export_transcript, has_native_session_selector, inside_ai_jail_here,
- inspect_repository, jail_checklist, jail_toggle, kiro_explicit_session_id,
- kiro_harness_from_source_cursor, kiro_selects_non_default_engine, kiro_selects_v2_engine,
- kiro_selects_v3_engine, kiro_v3_resume_uses_default_store, list_native_sessions,
- marked_choices, native_session_exists, native_session_in_checkout, omp_profile_flag,
- omp_profile_flag_env, parse_jail_toggles, store_override_vars, usable_ai_jail_here,
- wait_for_transcript_flush,
+ build_launch_plan, build_launch_plan_with_env, claude_attached_background_session,
+ crush_global_config_path, discover_native_session, export_transcript,
+ has_native_session_selector, inside_ai_jail_here, inspect_repository, jail_checklist,
+ jail_toggle, kiro_explicit_session_id, kiro_harness_from_source_cursor,
+ kiro_selects_non_default_engine, kiro_selects_v2_engine, kiro_selects_v3_engine,
+ kiro_v3_resume_uses_default_store, list_native_sessions, marked_choices, native_session_exists,
+ native_session_in_checkout, omp_profile_flag, omp_profile_flag_env, parse_jail_toggles,
+ store_override_vars, usable_ai_jail_here, wait_for_transcript_flush,
};
use anyhow::{Context as _, Result, anyhow};
use tokio::process::Command;
@@ -1386,6 +1386,47 @@ fn own_native_session(
Ok(in_checkout.then(|| linked.to_string()))
}
+/// 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(
+ plan: &LaunchPlan,
+ harness: ManagedHarness,
+ home: &Path,
+ cwd: &Path,
+ own: String,
+ started_at: SystemTime,
+) -> String {
+ if harness != ManagedHarness::Claude {
+ return own;
+ }
+ match claude_attached_background_session(
+ home,
+ cwd,
+ plan.session_dir.as_deref(),
+ &own,
+ started_at,
+ ) {
+ Ok(Some(background)) => {
+ eprintln!(
+ "ai-memory: Claude session {} continued in background session {}; the workstream now follows it",
+ display_session_id(&own),
+ display_session_id(&background)
+ );
+ background
+ }
+ Ok(None) => own,
+ Err(error) => {
+ eprintln!(
+ "ai-memory: could not check whether Claude session {} moved to a background session ({error}); keeping it",
+ display_session_id(&own)
+ );
+ own
+ }
+ }
+}
+
async fn resolve_native_session_after_run(
plan: &LaunchPlan,
harness: ManagedHarness,
@@ -1398,7 +1439,9 @@ async fn resolve_native_session_after_run(
return Ok(None);
}
if let Ok(Some(own)) = own_native_session(plan, harness, home, cwd, server_status) {
- return Ok(Some(own));
+ return Ok(Some(follow_claude_background_session(
+ plan, harness, home, cwd, own, started_at,
+ )));
}
let linked = server_status
.filter(|status| status.native_session_linked)
@@ -4327,6 +4370,58 @@ mod tests {
assert!(error.to_string().contains("--fresh cannot be combined"));
}
+ #[tokio::test]
+ async fn a_claude_run_that_attached_to_a_background_session_follows_it() {
+ 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 record = |session: &str, kind: Option<&str>| {
+ let mut value = serde_json::json!({
+ "type": "user",
+ "sessionId": session,
+ "session_id": "fg",
+ "cwd": cwd,
+ });
+ if let Some(kind) = kind {
+ value["sessionKind"] = serde_json::json!(kind);
+ }
+ format!("{value}\n")
+ };
+ std::fs::write(project.join("fg.jsonl"), record("fg", None)).unwrap();
+ let mut plan =
+ build_launch_plan(ManagedHarness::Claude, None, Vec::new(), Some("fg")).unwrap();
+ // CLAUDE_CONFIG_DIR in the developer's environment would point the
+ // scan away from the transcripts planted under `temp`.
+ plan.session_dir = None;
+ assert_eq!(plan.expected_session_id.as_deref(), Some("fg"));
+ let resolve = |plan: &LaunchPlan| {
+ 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,
+ )
+ .await
+ .unwrap()
+ }
+ };
+ assert_eq!(resolve(&plan).await.as_deref(), Some("fg"));
+
+ // `/resume` on a daemon-hosted session: the conversation continues in
+ // that transcript, so the workstream must not stay on "fg".
+ std::fs::write(project.join("bg.jsonl"), record("bg", Some("bg"))).unwrap();
+ assert_eq!(resolve(&plan).await.as_deref(), Some("bg"));
+ }
+
/// 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 32b804ff..e4036fe1 100644
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@ -22,8 +22,8 @@ pub use jail::{
};
pub use repository::{RepositoryIdentity, inspect_repository};
pub use transcript::{
- AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate, discover_native_session,
- export_transcript, kiro_harness_from_source_cursor, kiro_v3_resume_uses_default_store,
- list_native_sessions, native_session_exists, native_session_in_checkout,
- wait_for_transcript_flush,
+ AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate,
+ claude_attached_background_session, discover_native_session, export_transcript,
+ kiro_harness_from_source_cursor, kiro_v3_resume_uses_default_store, list_native_sessions,
+ native_session_exists, native_session_in_checkout, wait_for_transcript_flush,
};
diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rs
index 498a3d0d..5d93c131 100644
--- a/crates/ai-memory-workstream/src/transcript.rs
+++ b/crates/ai-memory-workstream/src/transcript.rs
@@ -209,6 +209,79 @@ pub async fn discover_native_session(
Ok(None)
}
+/// Find the Claude Code background session that `native_session_id` attached
+/// to during this run, if any.
+///
+/// `/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.
+///
+/// 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(
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ native_session_id: &str,
+ started_at: SystemTime,
+) -> Result<Option<String>> {
+ if !valid_native_session_id(native_session_id) {
+ return Ok(None);
+ }
+ let mut candidates = collect_session_files(ManagedHarness::Claude, home, session_dir)?;
+ candidates.sort_by(|left, right| {
+ modified(right)
+ .cmp(&modified(left))
+ .then_with(|| left.cmp(right))
+ });
+ let attached_marker = format!("\"session_id\":\"{native_session_id}\"");
+ for path in candidates.into_iter().take(512) {
+ 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))
+ {
+ continue;
+ }
+ let reader = BufReader::new(File::open(&path)?);
+ for line in reader.lines() {
+ let line = line?;
+ if !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)
+ {
+ return Ok(Some(session.to_string()));
+ }
+ }
+ }
+ Ok(None)
+}
+
/// 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.
@@ -4310,6 +4383,84 @@ mod tests {
assert_eq!(found.as_deref(), Some(path.as_path()));
}
+ #[test]
+ fn claude_attached_background_session_follows_only_this_checkouts_bg_records() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ let other = temp.path().join("other");
+ let project = temp.path().join(".claude/projects/-repo");
+ fs::create_dir_all(&cwd).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]| {
+ let path = project.join(format!("{name}.jsonl"));
+ let body = records
+ .iter()
+ .map(|record| format!("{record}\n"))
+ .collect::<String>();
+ fs::write(&path, body).unwrap();
+ path
+ };
+ let record = |session: &str, attached: &str, kind: Option<&str>, cwd: &Path| {
+ let mut value = json!({
+ "type": "user",
+ "sessionId": session,
+ "session_id": attached,
+ "cwd": cwd,
+ });
+ if let Some(kind) = kind {
+ value["sessionKind"] = json!(kind);
+ }
+ value
+ };
+ let find = |id: &str| {
+ claude_attached_background_session(temp.path(), &cwd, None, id, started_at).unwrap()
+ };
+
+ // The foreground transcript names itself; it is never the answer.
+ write("fg", &[record("fg", "fg", None, &cwd)]);
+ assert_eq!(find("fg"), None);
+
+ // Without `sessionKind: bg`, or from another checkout, a record that
+ // names the foreground session is not a background continuation.
+ write("plain", &[record("plain", "fg", None, &cwd)]);
+ write(
+ "elsewhere",
+ &[record("elsewhere", "fg", Some("bg"), &other)],
+ );
+ assert_eq!(find("fg"), None);
+
+ // A concurrent launch in this checkout attached its own foreground
+ // session to a background one; that conversation is not this run's.
+ write(
+ "concurrent",
+ &[record("concurrent", "other-fg", Some("bg"), &cwd)],
+ );
+ assert_eq!(find("fg"), None);
+ assert_eq!(find("other-fg").as_deref(), Some("concurrent"));
+
+ // A transcript last written before the run started is not read.
+ let stale = write("stale", &[record("stale", "fg", Some("bg"), &cwd)]);
+ File::options()
+ .write(true)
+ .open(&stale)
+ .unwrap()
+ .set_modified(started_at - Duration::from_secs(60))
+ .unwrap();
+ assert_eq!(find("fg"), None);
+
+ write(
+ "bg",
+ &[
+ record("bg", "earlier-client", Some("bg"), &cwd),
+ record("bg", "fg", Some("bg"), &cwd),
+ ],
+ );
+ assert_eq!(find("fg").as_deref(), Some("bg"));
+ assert_eq!(find("unrelated"), None);
+ }
+
#[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/managed-workstreams.md b/docs/managed-workstreams.md
index 9b42d59d..90f180df 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -419,6 +419,17 @@ Codex's `resume`, or Antigravity's `--conversation` / `--continue` wins.
ai-memory links the selected native session and resets an unrelated adapter
cursor rather than assuming it belongs to the old session.
+Claude Code background sessions run inside the Claude Code daemon, not in the
+process `ai-memory run` spawned, so their hooks never carry the run's id. When a
+managed Claude session attaches to one (`/resume` on a session shown as
+"running in the background"), the conversation goes on in the background
+session's transcript. At the end of the run, ai-memory looks for a transcript
+written during the run whose `sessionKind: "bg"` records name the run's own
+session as the attached client and this checkout as `cwd`, and finishes the run
+on that background session, so the next launch resumes it instead of the empty
+foreground session. A background session attached by another launch is never
+taken. (#1050)
+
Crush has no hooks to link its session: a fresh Crush launch claims the one top-level session
created while it ran (its title and sub-agent sessions do not count), and
imports nothing, with a warning, when another launch on the same store created
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index d2344cbe..49eca078 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -59,7 +59,7 @@ boundary not yet built.
| 11e | Native self-upgrade archive confinement (#1025) | `ai-memory-cli/src/commands/upgrade.rs` normalizes every tar/zip path, rejects links and special entries, extracts only the binary and `hooks/`, accepts only the exact non-runtime support layout emitted by `release.yml`, and caps both entry count and declared expanded bytes before writing | `upgrade.rs` `release_workflow_support_assets_are_exact_and_ignored` (shipped support paths admitted, near-miss docs/packaging/template paths refused), `extracts_archive_built_like_release_yml` and `extracts_zip_happy_path_with_hooks` (real workflow-shaped archives succeed but support assets are not written), `validate_rejects_path_traversal`, `zip_extract_rejects_path_traversal`, `tar_extract_rejects_declared_expansion_past_limit`, with binary/hooks extraction as the legitimate control | STRONG |
| 11f | Native hook executable-path integrity after self-replacement (#1027) | `ai-memory-cli/src/commands/render_shared.rs` `hook_embedded_exe_path` is the single executable resolver for every persisted native hook form (POSIX/Windows command, Windows exec, Zero, ZCode, OpenCode 2 assistant capture): it prefers an existing literal path, strips Linux's trailing ` (deleted)` procfs marker only when the stripped installed binary exists, and otherwise falls back to the platform command name. Upgrade keeps the already-loaded config and refreshes in-process | `render_shared.rs` `embedded_exe_strips_the_marker_when_the_stripped_path_exists`, `embedded_exe_preserves_a_real_file_whose_name_has_the_marker_suffix`, `embedded_exe_falls_back_when_the_resolved_path_is_missing`, `hook_embedded_exe_path_names_an_existing_file_without_marker`; `upgrade_e2e.rs` `native_upgrade_refreshes_hooks_without_a_deleted_path_or_losing_cli_data_dir` reproduces the replacement window through the shipped binary, plants the corrupt suffix, and proves refresh removes it while preserving a CLI-only data dir | STRONG on Linux reproduction plus platform-neutral resolver/render coverage; Windows path rendering remains covered by its existing command/exec tests and full Windows CI |
| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401 | STRONG |
-| 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; `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` `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_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 |
| 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 | `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`; `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 | 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 |