Skip to content

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

Rust

fix(backfill): look up explicitly named native sessions

Samir Hanna Verza48b2ac17db08
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 67a4da09..d2c7a8f2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,10 @@ version in [`docs/changelog/`](docs/changelog/):
not be opened. Other users still see only their own sessions plus shared
ones (#1867).
+- `backfill --session <id>` now finds an explicitly named native session beyond
+ the newest 200-session listing, instead of reporting a successful empty import.
+ Exact lookups retain the adapter's checkout and top-level-session checks;
+ automatic enumeration remains bounded (#PR).
- Excluded Codex's generated approval-review transcripts and background
suggestion prompts from transcript backfill and profile harvesting, and
kept a hand-reworded profile page attached to its ledger topic even when a
diff --git a/crates/ai-memory-cli/src/commands/backfill.rs b/crates/ai-memory-cli/src/commands/backfill.rs
index 8b528afc..537a1bf8 100644
--- a/crates/ai-memory-cli/src/commands/backfill.rs
+++ b/crates/ai-memory-cli/src/commands/backfill.rs
@@ -43,8 +43,8 @@ use ai_memory_core::{NewWorkstreamEvent, WorkstreamEventKind};
use ai_memory_hooks::capture_policy::metadata_only_body;
use ai_memory_workstream::{
LaunchRoots, ManagedHarness, OVERSIZED_RECORD_LOSS, build_launch_plan_with_env,
- export_transcript, export_transcript_delta, export_transcript_range, list_native_sessions,
- wait_for_transcript_flush,
+ export_transcript, export_transcript_delta, export_transcript_range, find_native_session,
+ list_native_sessions, wait_for_transcript_flush,
};
use super::doctor::{SCANNED_HARNESSES, relocated_session_dir};
@@ -622,6 +622,21 @@ pub(crate) async fn collect_local_sessions_with(
let mut limit_hit = Vec::new();
for &harness in SCANNED_HARNESSES {
let session_dir = session_dir_for(harness);
+ if let Some(id) = only_session {
+ // A named recovery target may be older than every session in the
+ // bounded listing. Resolve it directly, with the adapter's same
+ // checkout checks, rather than broadening the automatic scan.
+ if let Ok(Some(session)) =
+ find_native_session(harness, home, cwd, session_dir.as_deref(), id)
+ {
+ out.push(SessionRef {
+ harness,
+ native_session_id: session.native_session_id,
+ updated_at: session.updated_at,
+ });
+ }
+ continue;
+ }
let Ok(sessions) = list_native_sessions(
harness,
home,
@@ -637,9 +652,6 @@ pub(crate) async fn collect_local_sessions_with(
limit_hit.push(harness);
}
for session in sessions {
- if only_session.is_some_and(|want| want != session.native_session_id) {
- continue;
- }
out.push(SessionRef {
harness,
native_session_id: session.native_session_id,
@@ -2504,6 +2516,189 @@ mod tests {
assert!(only.is_empty(), "no session matches the filter: {only:?}");
}
+ // This exercises the real listing cap with 201 on-disk transcripts.
+ // Creating, listing and cleaning them takes more than a second on macOS.
+ mod slow_explicit_session_lookup {
+ use super::*;
+
+ #[tokio::test]
+ async fn collect_local_sessions_explicit_file_target_bypasses_listing_cap() {
+ let home = tempfile::tempdir().unwrap();
+ let cwd = tempfile::tempdir().unwrap();
+ let session_dir = home
+ .path()
+ .join(".claude/projects")
+ .join(ai_memory_workstream::claude_project_dir_name(cwd.path()));
+ std::fs::create_dir_all(&session_dir).unwrap();
+ let target = "11111111-2222-4333-8444-000000000000";
+ for index in 0..=PER_HARNESS_SCAN_LIMIT {
+ let id = format!("11111111-2222-4333-8444-{index:012}");
+ let header = serde_json::json!({ "sessionId": id, "cwd": cwd.path() });
+ let path = session_dir.join(format!("{id}.jsonl"));
+ std::fs::write(&path, format!("{header}\n")).unwrap();
+ std::fs::File::options()
+ .write(true)
+ .open(path)
+ .unwrap()
+ .set_times(std::fs::FileTimes::new().set_modified(
+ SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000 + index as u64),
+ ))
+ .unwrap();
+ }
+
+ let (listed, limit_hit) =
+ collect_local_sessions_with(home.path(), cwd.path(), None, |_| None).await;
+ assert_eq!(listed.len(), PER_HARNESS_SCAN_LIMIT);
+ assert_eq!(limit_hit, vec![ManagedHarness::Claude]);
+ assert!(
+ listed
+ .iter()
+ .all(|session| session.native_session_id != target)
+ );
+
+ let (selected, limit_hit) =
+ collect_local_sessions_with(home.path(), cwd.path(), Some(target), |_| None).await;
+ assert_eq!(selected.len(), 1, "the explicit old session must be found");
+ assert_eq!(selected[0].harness, ManagedHarness::Claude);
+ assert_eq!(selected[0].native_session_id, target);
+ assert_eq!(
+ selected[0].updated_at,
+ SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000),
+ );
+ assert!(
+ limit_hit.is_empty(),
+ "an exact lookup is not a capped listing"
+ );
+
+ for missing in ["no-such-session", "../outside", ""] {
+ let (selected, _) =
+ collect_local_sessions_with(home.path(), cwd.path(), Some(missing), |_| None)
+ .await;
+ assert!(selected.is_empty(), "must not select {missing:?}");
+ }
+ let foreign = tempfile::tempdir().unwrap();
+ let (selected, _) =
+ collect_local_sessions_with(home.path(), foreign.path(), Some(target), |_| None)
+ .await;
+ assert!(
+ selected.is_empty(),
+ "the exact ID must still belong to this cwd"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn collect_local_sessions_explicit_sql_target_bypasses_listing_cap() {
+ let home = tempfile::tempdir().unwrap();
+ let cwd = tempfile::tempdir().unwrap();
+ let store = home.path().join("opencode");
+ std::fs::create_dir_all(&store).unwrap();
+ let mut db = rusqlite::Connection::open(store.join("opencode.db")).unwrap();
+ let transaction = db.transaction().unwrap();
+ for table in ["session", "session_v2"] {
+ transaction.execute_batch(&format!(
+ "CREATE TABLE {table}(id TEXT PRIMARY KEY, directory TEXT, time_updated INTEGER);"
+ ))
+ .unwrap();
+ for index in 0..=PER_HARNESS_SCAN_LIMIT {
+ transaction
+ .execute(
+ &format!("INSERT INTO {table} VALUES (?1, ?2, ?3)"),
+ rusqlite::params![
+ format!("{table}-{index:04}"),
+ cwd.path().to_string_lossy(),
+ 1_700_000_000_000_i64 + index as i64,
+ ],
+ )
+ .unwrap();
+ }
+ }
+ transaction.commit().unwrap();
+ let session_dir_for = |harness| {
+ matches!(
+ harness,
+ ManagedHarness::OpenCode | ManagedHarness::OpenCode2
+ )
+ .then(|| store.clone())
+ };
+ let (listed, limit_hit) =
+ collect_local_sessions_with(home.path(), cwd.path(), None, session_dir_for).await;
+ assert_eq!(listed.len(), 2 * PER_HARNESS_SCAN_LIMIT);
+ assert_eq!(
+ limit_hit,
+ vec![ManagedHarness::OpenCode, ManagedHarness::OpenCode2]
+ );
+
+ for (table, harness) in [
+ ("session", ManagedHarness::OpenCode),
+ ("session_v2", ManagedHarness::OpenCode2),
+ ] {
+ let target = format!("{table}-0000");
+ let (selected, limit_hit) = collect_local_sessions_with(
+ home.path(),
+ cwd.path(),
+ Some(&target),
+ session_dir_for,
+ )
+ .await;
+ assert_eq!(selected.len(), 1, "the explicit old {harness:?} session");
+ assert_eq!(selected[0].harness, harness);
+ assert_eq!(selected[0].native_session_id, target);
+ assert_eq!(
+ selected[0].updated_at,
+ SystemTime::UNIX_EPOCH + Duration::from_millis(1_700_000_000_000),
+ );
+ assert!(limit_hit.is_empty());
+
+ let foreign = tempfile::tempdir().unwrap();
+ let (selected, _) = collect_local_sessions_with(
+ home.path(),
+ foreign.path(),
+ Some(&target),
+ session_dir_for,
+ )
+ .await;
+ assert!(
+ selected.is_empty(),
+ "must not import a foreign {harness:?} session"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn collect_local_sessions_explicit_crush_target_keeps_subagents_excluded() {
+ let home = tempfile::tempdir().unwrap();
+ let cwd = tempfile::tempdir().unwrap();
+ let store = cwd.path().join(".crush");
+ std::fs::create_dir_all(&store).unwrap();
+ let db = rusqlite::Connection::open(store.join("crush.db")).unwrap();
+ db.execute_batch(
+ "CREATE TABLE sessions(id TEXT PRIMARY KEY, parent_session_id TEXT, updated_at INTEGER); \
+ INSERT INTO sessions VALUES ('parent', NULL, 1700000000); \
+ INSERT INTO sessions VALUES ('child', 'parent', 1700000001); \
+ INSERT INTO sessions VALUES ('invalid-time', NULL, -1);",
+ )
+ .unwrap();
+ let session_dir_for = |harness| (harness == ManagedHarness::Crush).then(|| store.clone());
+ let (selected, limit_hit) =
+ collect_local_sessions_with(home.path(), cwd.path(), Some("parent"), session_dir_for)
+ .await;
+ assert_eq!(selected.len(), 1);
+ assert_eq!(selected[0].harness, ManagedHarness::Crush);
+ assert_eq!(selected[0].native_session_id, "parent");
+ assert_eq!(
+ selected[0].updated_at,
+ SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000),
+ );
+ assert!(limit_hit.is_empty());
+ for id in ["child", "invalid-time", "missing"] {
+ let (selected, _) =
+ collect_local_sessions_with(home.path(), cwd.path(), Some(id), session_dir_for)
+ .await;
+ assert!(selected.is_empty(), "must not select {id}");
+ }
+ }
+
/// GHSA-gcpc-88hm-3xqr: a planted Claude transcript reads one file under
/// the checkout's `[capture] ignore_paths` and one outside it. The
/// excluded read's call and output never reach `/hook/batch`; the public
diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rs
index 9f4d0548..ef3b4cd2 100644
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@ -29,8 +29,8 @@ pub use transcript::{
OVERSIZED_RECORD_LOSS, RECORD_CWD_KEY, SKIPPED_RECORD_KEY, claude_continued_session,
claude_continued_sessions, claude_live_background_attach_id, claude_project_dir_name,
claude_session_ran_in_background, discover_native_session, export_transcript,
- export_transcript_delta, export_transcript_range, 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, transcript_baseline,
- transcript_interval_digests, wait_for_transcript_flush,
+ export_transcript_delta, export_transcript_range, find_native_session,
+ 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,
+ transcript_baseline, transcript_interval_digests, wait_for_transcript_flush,
};
diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rs
index 75f15f79..56e56b7a 100644
--- a/crates/ai-memory-workstream/src/transcript.rs
+++ b/crates/ai-memory-workstream/src/transcript.rs
@@ -983,6 +983,68 @@ pub async fn list_native_sessions(
Ok(sessions)
}
+/// Find one named session without truncating it out of a recent-session list.
+/// Uses the same native identity, checkout and top-level-session checks as
+/// listing: file adapters verify the transcript header, OpenCode checks the
+/// recorded directory, and Crush excludes sub-agent/title sessions.
+pub fn find_native_session(
+ harness: ManagedHarness,
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ native_session_id: &str,
+) -> Result<Option<NativeSessionCandidate>> {
+ if !valid_native_session_id(native_session_id) {
+ return Ok(None);
+ }
+ let updated_at = match harness {
+ ManagedHarness::OpenCode | ManagedHarness::OpenCode2 | ManagedHarness::Crush => {
+ let db = if harness == ManagedHarness::Crush {
+ crush_db(home, cwd, session_dir)
+ } else {
+ opencode_db(home, session_dir)
+ };
+ if !db.is_file() {
+ return Ok(None);
+ }
+ let connection = Connection::open_with_flags(
+ db,
+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
+ )?;
+ if harness == ManagedHarness::Crush {
+ connection
+ .query_row(
+ "SELECT updated_at FROM sessions WHERE id = ?1 AND parent_session_id IS NULL",
+ [native_session_id],
+ |row| row.get::<_, i64>(0),
+ )
+ .optional()?
+ .and_then(native_timestamp)
+ } else {
+ let sql = if harness == ManagedHarness::OpenCode {
+ "SELECT time_updated FROM session WHERE id = ?1 AND directory IN (?2, ?3)"
+ } else {
+ "SELECT time_updated FROM session_v2 WHERE id = ?1 AND directory IN (?2, ?3)"
+ };
+ let (native, forward) = opencode_directories(cwd);
+ connection
+ .query_row(sql, params![native_session_id, native, forward], |row| {
+ row.get::<_, i64>(0)
+ })
+ .optional()?
+ .and_then(|updated| u64::try_from(updated).ok())
+ .and_then(|updated| UNIX_EPOCH.checked_add(Duration::from_millis(updated)))
+ }
+ }
+ _ => locate_session_file(harness, home, cwd, session_dir, native_session_id)?
+ .and_then(|path| modified(&path)),
+ };
+ Ok(updated_at.map(|updated_at| NativeSessionCandidate {
+ native_session_id: native_session_id.to_owned(),
+ updated_at,
+ }))
+}
+
/// Resolve the on-disk directory holding this harness's native "memory"
/// store for the given checkout, when the harness has one and a session
/// recorded for this cwd can be found.
diff --git a/docs/design-boot-backfill.md b/docs/design-boot-backfill.md
index f9ddcdf2..7c1eaa5a 100644
--- a/docs/design-boot-backfill.md
+++ b/docs/design-boot-backfill.md
@@ -32,6 +32,10 @@ the local sentinel, so it does not suppress a later automatic attempt.
The automatic path runs detached and silent (like Claude Code's own auto-memory); the
`📼 imported N session(s)` summary is shown on a **manual** `ai-memory backfill` only.
+`backfill --session <id>` looks up that exact native session, including one older
+than the newest 200 sessions enumerated per harness. It retains the adapter's
+checkout and top-level-session checks. The automatic scan and `--max-sessions`
+limit still apply to the normal newest-session listing.
Failed imports are always written to stderr (the detached worker's
`logs/backfill.log`), including with `--quiet`. Any failed session makes the
command exit nonzero after emitting its report; `--json` still produces the
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 9eab6ef6..577b7ec5 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -130,6 +130,7 @@ the legitimate restricted-project control and the failed-query cases.
| 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 |
| 13c | A native store shared by every project yields only this checkout's records (Antigravity `history.jsonl` or its print-mode brain transcript) | `ai-memory-workstream/src/transcript.rs` `export_antigravity` — the conversation must first pass `locate_session_file` (UUID file name + `.db` workspace == `cwd`); every `history.jsonl` line must match both that `conversationId` and, by `same_path`, this `cwd` (a conversation resumed in another directory keeps its id but records that directory, so the id alone is not enough); an id-less opening prompt is attributed only when exactly one same-workspace candidate falls within 5 s of the `.db` creation time and no other conversation of this checkout was created within 5 s of it; slash/shell entries and oversized lines are dropped, and only records naming this conversation are reported as its losses; when history yields no prompt, `antigravity_brain_prompt_events` opens only a regular transcript canonically contained below this conversation, caps the file at 8 MiB and each line at 1 MiB, and accepts only explicit `USER_INPUT` steps | `transcript.rs` `antigravity_history_exports_only_this_conversations_prompts_in_this_workspace` (other conversation in this and another workspace refused; own control passes), `antigravity_history_drops_prompts_from_a_resumed_conversation_in_another_workspace` (same id, foreign workspace refused), `antigravity_export_rejects_a_conversation_from_another_workspace`, `antigravity_export_rejects_unknown_or_traversal_ids`, `antigravity_opening_prompt_is_refused_when_another_conversation_started_with_it` (an opener another conversation of this checkout could own is refused), `antigravity_opening_prompt_covers_a_single_prompt_conversation` (control), `antigravity_history_reports_no_losses_for_foreign_records`, `antigravity_print_mode_falls_back_to_explicit_brain_prompts`; `backfill_e2e.rs` `backfill_imports_antigravity_prompts_from_history_and_nothing_foreign` (foreign prompts absent from wiki and db) | STRONG |
+| 13d | An explicit backfill session ID retains the native adapter's selection boundaries | `ai-memory-workstream/src/transcript.rs` `find_native_session` validates the native ID, reuses the file adapter's exact lookup and header/cwd match, checks OpenCode v1/v2 `directory` in the same SQL query as the ID, and excludes Crush sub-agent/title sessions with `parent_session_id IS NULL`; `backfill.rs` uses this lookup only for `--session`, leaving automatic listing caps intact | `backfill.rs` `collect_local_sessions_explicit_file_target_bypasses_listing_cap` rejects missing/invalid IDs and a matching ID from another cwd while selecting the old local session; `collect_local_sessions_explicit_sql_target_bypasses_listing_cap` checks both OpenCode versions, preserving each timestamp and refusing another cwd; `collect_local_sessions_explicit_crush_target_keeps_subagents_excluded` admits the parent but refuses its child and an invalid timestamp | STRONG |
| 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 otherwise never taken from a caller (only derived from already-authorized hits); the one exception, the web page-history `from`/`to` version ids, is looked up only inside the scope `routes/mod.rs` `resolve_read_scope` (`lookup_existing_scope_guarded`, `ProjectAccess::Read`) has already authorized and the requested path (`page_version_body`), so a foreign id reads as not found; 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`, `observation_stream_evidence_stays_inside_a_restricted_project` (with `[retrieval] observation_stream` on, a non-grantee naming the restricted project, listing it in `scopes`, or searching their own project never sees the session page or its observation excerpt; the writer and a read-grant holder do; fails with the read check in `ProjectAuthz::authorize` neutralized), `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`, `a_reader_cannot_change_a_projects_profile_flags_at_session_start` (a Read grant's `profile_contribute`/`profile_consume` at session start neither opts the project out nor back in; Write-grant control records both; fails with the Write check forced on), `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` (also a paginated namespace URL, `/p/secrets/?page=2`), `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (19 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); `ai-memory-web` `history_replay.rs` `history_and_timeline_honour_grants_in_a_restricted_project` (page history in HTML and JSON and the session timeline: a non-grantee gets 403 without the body, a grantee and root get 200; bite: resolving through the unguarded `lookup_existing_scope` fails it) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |
| 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch`; importer agentmemory routes `vault::plan`, `export::plan`, `export::replay_session`, `agentmemory::validate_id` | SDK secret-position, nested key, numeric metric (11 names plus numeric `*_tokens` counts; string values still redact), bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session`, `unsafe_legacy_native_identity_is_dropped_and_its_session_continues`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`, agentmemory `page_bodies_are_redacted_before_planning`, `text_is_redacted_before_the_plan_exists` (page bodies and replayed observations), `ids_that_look_like_credentials_or_carry_controls_are_refused`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. An unsafe item queued before these checks never reaches the wire (body or request line); it leaves the queue as a local `dropped_policy` receipt so the rest of its session ships. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative |
| 14ap | Managed-run mutation owner and current project access (finish, cancel, heartbeat, native-session link, context acceptance) | `hooks/src/workstream.rs` `authorize_run_owner` derives `ManagedRunAuthority` only from authenticated middleware extensions and checks the real run before any mutation — for finish before status/payload/segment handling; cancel, heartbeat, link and context acceptance go through the same helper, so none is a side door around finish's rule; `ReaderPool::authorize_managed_run` and `store/src/workstream.rs` `authorize_run_mutation` use a read snapshot and the existing writer transaction, respectively. Strict resolution (`project_authz.rs` `resolve_project_authz_strict`, the canonical decision with a fail-closed resolution mode, so the reserved global-scope write gate applies here too) requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`; hooks `workstream.rs` `run_mutation_routes_refuse_another_operator` (another operator and root under another identity refused on heartbeat/link/accept/cancel, run left active; owner admitted); store `project_authz.rs` `strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within finish's writer transaction; a revocation after preflight can leave an unindexed raw segment. Cancel, heartbeat, link and acceptance check one read snapshot immediately before a single-row update (a run's owner never changes). A later hook event carrying `AI_MEMORY_RUN_ID` links its native session only through `link_native_session_in_scope`, which applies the SessionStart boundary (`ManagedRunBoundaryRow::admits`: the run's own project and operator) and refuses a foreign run id while the event itself is still captured (`router.rs` `hook_event_links_a_managed_run_only_from_its_operator`, `hook_event_in_another_project_does_not_link_the_run`, control `hook_event_links_a_shared_run_on_a_single_operator_server`; #1082). Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional |