Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(web): let root open every user's sessions in the drilldowns
geeksilva979f0c8d2c1ee8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c520ce4a..67a4da09 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,14 @@ version in [`docs/changelog/`](docs/changelog/):### Fixed+- The web UI's root operator now sees every user's sessions in a project's+ Sessions, Agents and Token usage tabs, on each agent's page and on each+ session's page, and so do the `/api/v1` session list and observations+ routes. The dashboard counted every user's sessions while these drilldowns+ listed only root's own, so on a shared server most counted sessions could+ not be opened. Other users still see only their own sessions plus shared+ ones (#1867).+- Excluded Codex's generated approval-review transcripts and backgroundsuggestion prompts from transcript backfill and profile harvesting, andkept a hand-reworded profile page attached to its ledger topic even when adiff --git a/crates/ai-memory-web/src/routes/agents.rs b/crates/ai-memory-web/src/routes/agents.rsindex c4f5aae2..b55473e0 100644--- a/crates/ai-memory-web/src/routes/agents.rs+++ b/crates/ai-memory-web/src/routes/agents.rs@@ -26,6 +26,7 @@ pub(crate) async fn handler(State(state): State<Arc<WebState>>,viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,actor: Option<axum::Extension<ai_memory_core::ActorContext>>,+ auth: Option<axum::Extension<ai_memory_core::AuthLevel>>,Path((workspace, project, raw)): Path<(String, String, String)>,Query(query): Query<AgentQuery>,) -> Response {@@ -40,7 +41,7 @@ pub(crate) async fn handler(Ok(scope) => scope,Err(e) => return super::page::refusal_response(&e),};- let owner = super::api::owner_filter_for(actor);+ let owner = super::api::session_owner_filter_for(actor, auth);let rows = match state.reader.agent_usage(scope.workspace_id, scope.project_id, owner.clone())diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rsindex 011856e0..758b6fbd 100644--- a/crates/ai-memory-web/src/routes/api.rs+++ b/crates/ai-memory-web/src/routes/api.rs@@ -889,6 +889,23 @@ pub(crate) fn owner_filter_for()}+/// The owner filter for reading sessions and the token usage recorded on them.+///+/// Root is the operator: it already lists every handoff with `all_owners`, and+/// the dashboard counts every user's sessions. Filtering root's drilldowns by+/// its own identity hid the sessions those counts promise (#1867). Every other+/// caller keeps [`owner_filter_for`]: their own sessions plus shared ones.+pub(crate) fn session_owner_filter_for(+ actor: Option<axum::Extension<ai_memory_core::ActorContext>>,+ auth: Option<axum::Extension<ai_memory_core::AuthLevel>>,+) -> ai_memory_core::OwnerFilter {+ if matches!(auth, Some(axum::Extension(ai_memory_core::AuthLevel::Root))) {+ ai_memory_core::OwnerFilter::Any+ } else {+ owner_filter_for(actor)+ }+}+/// May this request read the prompt-derived body of a handoff?////// Three ways to qualify: an authenticated caller resolved to an identity and@@ -1178,6 +1195,7 @@ async fn sessions_handler(State(state): State<Arc<WebState>>,viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,actor: Option<axum::Extension<ai_memory_core::ActorContext>>,+ auth: Option<axum::Extension<ai_memory_core::AuthLevel>>,Path((workspace, project)): Path<(String, String)>,Query(query): Query<SessionListQuery>,) -> Result<Response, Response> {@@ -1188,7 +1206,7 @@ async fn sessions_handler(.sessions_for_scope(workspace_id,project_id,- owner_filter_for(actor),+ session_owner_filter_for(actor, auth),query.include_open,query.limit.clamp(1, SESSION_LIST_MAX_LIMIT),query.offset,@@ -1204,6 +1222,7 @@ async fn session_observations_handler(State(state): State<Arc<WebState>>,viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,actor: Option<axum::Extension<ai_memory_core::ActorContext>>,+ auth: Option<axum::Extension<ai_memory_core::AuthLevel>>,Path((workspace, project, session_id)): Path<(String, String, String)>,Query(query): Query<SessionObservationsQuery>,) -> Result<Response, Response> {@@ -1263,7 +1282,7 @@ async fn session_observations_handler(workspace_id,project_id,session_id,- owner_filter_for(actor),+ session_owner_filter_for(actor, auth),).await.map_err(internal_error)?diff --git a/crates/ai-memory-web/src/routes/project.rs b/crates/ai-memory-web/src/routes/project.rsindex 9370cdbc..cd66b61b 100644--- a/crates/ai-memory-web/src/routes/project.rs+++ b/crates/ai-memory-web/src/routes/project.rs@@ -50,6 +50,7 @@ pub(crate) async fn handler(State(state): State<Arc<WebState>>,viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,actor: Option<axum::Extension<ai_memory_core::ActorContext>>,+ auth: Option<axum::Extension<ai_memory_core::AuthLevel>>,Path((workspace, project)): Path<(String, String)>,Query(query): Query<crate::operations::UsageQuery>,) -> Response {@@ -58,7 +59,7 @@ pub(crate) async fn handler(Ok(authorized) => authorized,Err(refusal) => return super::page::refusal_response(&refusal),};- let owner = super::api::owner_filter_for(actor);+ let owner = super::api::session_owner_filter_for(actor, auth);render(&state, workspace, project, viewer_id, authorized, owner, query,)diff --git a/crates/ai-memory-web/src/routes/session.rs b/crates/ai-memory-web/src/routes/session.rsindex 031d4473..2a766084 100644--- a/crates/ai-memory-web/src/routes/session.rs+++ b/crates/ai-memory-web/src/routes/session.rs@@ -19,7 +19,7 @@ use serde::Deserialize;use super::api::{SESSION_OBSERVATIONS_DEFAULT_BODY_CHARS, SESSION_OBSERVATIONS_MAX_LIMIT, cap_body,- owner_filter_for,+ session_owner_filter_for,};use crate::state::WebState;use crate::templates::{SessionObservationRow, SessionView, humanize, project_href, session_href};@@ -49,9 +49,11 @@ pub(crate) async fn handler(State(state): State<Arc<WebState>>,viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,actor: Option<axum::Extension<ai_memory_core::ActorContext>>,+ auth: Option<axum::Extension<ai_memory_core::AuthLevel>>,Path((workspace, project, raw_session)): Path<(String, String, String)>,Query(query): Query<SessionQuery>,) -> Response {+ let owner = session_owner_filter_for(actor, auth);let viewer = viewer.map(|axum::Extension(viewer)| viewer.user());let scope = match super::resolve_read_scope(&state, viewer, &workspace, &project).await {Ok(scope) => scope,@@ -72,7 +74,7 @@ pub(crate) async fn handler(scope.workspace_id,scope.project_id,session_id,- owner_filter_for(actor.clone()),+ owner.clone(),).await{@@ -146,7 +148,7 @@ pub(crate) async fn handler(.token_usage_report_page(scope.workspace_id,scope.project_id,- owner_filter_for(actor),+ owner,Some(session_id),calls_query,)diff --git a/crates/ai-memory-web/tests/suite/operations.rs b/crates/ai-memory-web/tests/suite/operations.rsindex 760025b8..c429c941 100644--- a/crates/ai-memory-web/tests/suite/operations.rs+++ b/crates/ai-memory-web/tests/suite/operations.rs@@ -1,11 +1,11 @@//! Browser writes, directed delivery and scoped operational views.use ai_memory_core::{- AgentKind, AuthLevel, AuthorizedViewer, MessageBox, NewSession, NewUser, OwnerFilter,- SessionId, TokenCall, UserRole,+ ActorContext, AgentKind, AuthLevel, AuthorizedViewer, MessageBox, NewSession, NewUser,+ OwnerFilter, SessionId, TokenCall, UserRole,};use ai_memory_store::{GrantLevel, Store};-use ai_memory_web::router;+use ai_memory_web::{api_router, router};use ai_memory_wiki::Wiki;use axum::{body::Body,@@ -1195,6 +1195,128 @@ async fn operations_agent_aggregates_and_drilldowns_apply_ownership_before_totalassert_eq!(foreign.call_count, 0);}+#[tokio::test]+async fn operations_root_drilldowns_reach_every_users_sessions_and_users_stay_owned() {+ // The dashboard counts every user's sessions; root's drilldowns must reach+ // them (#1867), while a user still sees only their own and shared ones.+ let (_tmp, store, wiki, ws, project, shared) = fixture().await;+ let mut users = Vec::new();+ for name in ["alice", "bob"] {+ let id = store+ .writer+ .create_human_user(+ NewUser {+ username: name.into(),+ name: None,+ email: None,+ },+ UserRole::User,+ None,+ false,+ )+ .await+ .unwrap();+ let sid = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id: sid,+ workspace_id: ws,+ project_id: project,+ agent_kind: AgentKind::Codex,+ cwd: None,+ actor_user: Some(ai_memory_core::IdentityKey::User(name.into()).storage_key()),+ occurred_at: None,+ })+ .await+ .unwrap();+ store.writer.end_session(sid, None).await.unwrap();+ users.push((name, id, sid));+ }+ let (_, alice, alice_session) = users[0];+ let (_, _, bob_session) = users[1];+ let as_alice = |uri: &str| {+ Request::builder()+ .uri(uri)+ .extension(AuthLevel::User)+ .extension(AuthorizedViewer(alice))+ .extension(ActorContext {+ user: Some("alice".into()),+ ..ActorContext::anonymous()+ })+ .body(Body::empty())+ .unwrap()+ };+ let as_root = |uri: &str| {+ Request::builder()+ .uri(uri)+ .extension(AuthLevel::Root)+ .extension(ActorContext {+ user: Some("admin".into()),+ ..ActorContext::anonymous()+ })+ .body(Body::empty())+ .unwrap()+ };+ let app = router(store.reader.clone(), wiki.clone());+ let api = api_router(store.reader.clone(), wiki);++ for uri in ["/w/team/app/agents/codex", "/w/team/app?tab=sessions"] {+ let user_view = text(app.clone().oneshot(as_alice(uri)).await.unwrap()).await;+ assert!(user_view.contains(&alice_session.to_string()), "{uri}");+ assert!(user_view.contains(&shared.to_string()), "{uri}");+ assert!(+ !user_view.contains(&bob_session.to_string()),+ "{uri}: foreign session"+ );+ let root_view = text(app.clone().oneshot(as_root(uri)).await.unwrap()).await;+ for sid in [alice_session, bob_session, shared] {+ assert!(+ root_view.contains(&sid.to_string()),+ "{uri}: root misses {sid}"+ );+ }+ }++ let bob_page = format!("/w/team/app/s/{bob_session}");+ assert_eq!(+ app.clone()+ .oneshot(as_alice(&bob_page))+ .await+ .unwrap()+ .status(),+ StatusCode::NOT_FOUND+ );+ assert_eq!(+ app.oneshot(as_root(&bob_page)).await.unwrap().status(),+ StatusCode::OK+ );++ let list = "/workspaces/team/projects/app/sessions?include_open=true";+ let user_list = text(api.clone().oneshot(as_alice(list)).await.unwrap()).await;+ assert!(user_list.contains(&alice_session.to_string()));+ assert!(!user_list.contains(&bob_session.to_string()));+ let root_list = text(api.clone().oneshot(as_root(list)).await.unwrap()).await;+ assert!(root_list.contains(&bob_session.to_string()));+ let bob_observations =+ format!("/workspaces/team/projects/app/sessions/{bob_session}/observations");+ assert_eq!(+ api.clone()+ .oneshot(as_alice(&bob_observations))+ .await+ .unwrap()+ .status(),+ StatusCode::NOT_FOUND+ );+ assert_eq!(+ api.oneshot(as_root(&bob_observations))+ .await+ .unwrap()+ .status(),+ StatusCode::OK+ );+}+#[tokio::test]async fn operations_legacy_login_requires_an_explicit_nonpersistent_write_token() {let (_tmp, store, wiki, _, _, _) = fixture().await;diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex ac7f5d8e..9eab6ef6 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -167,6 +167,7 @@ the legitimate restricted-project control and the failed-query cases.| 28 | An Antigravity hook reads, and uploads as prompts, only the named conversation's own transcript, within bounds | `ai-memory-hooks/src/antigravity.rs` `antigravity_transcript_path` accepts the payload's `transcriptPath` only when it is absolute, has no `..`, names `transcript.jsonl` or `transcript_full.jsonl`, and its canonical directory equals `canonical(<home>/.gemini/<app>/brain)/<conversationId>/.system_generated/logs` for `<app>` `antigravity`, `antigravity-cli` or `antigravity-ide`, with `conversationId` a plain id (`antigravity_conversation_id`); `read_transcript_prompts` opens only a regular, non-symlink file that is still the same file once open (`open_regular_file`, opened with `O_NOFOLLOW | O_NONBLOCK` so a symlink or FIFO swapped in after the check is refused without blocking, and on Linux only when the opened descriptor's `/proc/self/fd` path is the checked one, so a directory swapped for a symlink after the containment check is refused too), reads at most `MAX_TRANSCRIPT_SCAN_BYTES` per hook and parses lines up to `MAX_TRANSCRIPT_LINE_BYTES`, and returns only `USER_INPUT` steps whose `source` is absent or `USER_EXPLICIT`; `ai-memory-cli/src/commands/hook.rs` `antigravity_transcript_prompt_events` runs inside the spool block, so after the capture allowlist, routing, server-profile and external-capture gates, with the home `run_with_payload` resolved once; its path checks, bounded cursor load and transcript read run behind `ANTIGRAVITY_TRANSCRIPT_READ_BUDGET`, and a timeout advances no cursor so a later hook retries; cursor replacement uses the canonical atomic writer; each prompt is capped and scrubbed client-side, keyed by conversation and step, and sanitized again by the server (row 7) | `antigravity.rs` `transcript_path_refuses_anything_outside_the_conversations_own_logs` (another conversation's transcript, the same layout outside the home, another file in the logs directory, an unknown app directory, `..`, a traversal or empty id, a relative path, a missing or non-string path; the conversation's own transcript is the control), `transcript_path_refuses_symlinked_directories_that_leave_the_conversation` (a symlinked `.system_generated` and `brain/<id>` refused; a symlinked `~/.gemini` accepted as the control), `transcript_reader_refuses_symlinks_and_special_files` (a symlinked transcript and a directory refused; the same bytes as a regular file are read), `skips_injected_malformed_empty_and_non_prompt_steps`, `a_line_longer_than_the_scan_budget_is_skipped_across_reads`, `one_read_returns_a_bounded_number_of_prompts`; `hook.rs` `antigravity_transcript_reads_are_confined_to_the_conversations_own_logs` (end to end through the native hook: a forged path outside the home, another conversation's transcript and an arbitrary JSONL file under the home spool no prompt; the conversation's own transcript spools one), `antigravity_transcript_prompts_follow_the_capture_allowlist` (a repository the allowlist leaves out is not read), `antigravity_transcript_read_deadline_does_not_wait_for_blocked_work`, and `antigravity_transcript_cursor_store_is_atomic_and_bounded` (oversized cursor refused) | STRONG on Linux, including the opened descriptor path. Stable symlink escapes and special files are refused on every platform; without Linux `/proc/self/fd`, a same-user process able to replace an ancestor in the narrow interval between canonicalization and open could redirect the read, which still remains size- and time-bounded. The directory-swap bite test is Linux-only; the other symlink cases are `cfg(unix)` || 29 | Interrupted-session recovery stays scope-, owner-, and receiver-bound | `ReaderPool::latest_interrupted_session_candidate` filters before selection; hooks render only the admitted candidate and exclude the receiving session | `multi_session.rs` `interrupted_recovery_refuses_foreign_scope_owner_and_receiver_with_controls`; hooks `unfinished_session_recovery_is_owner_scoped_and_excludes_receiver` | STRONG || 30 | Per-response usage remains project/session/owner scoped and replay-monotonic | `ReaderPool::token_usage_report_page` applies scope, owner, search, and signal filters before pagination; `ops::upsert_token_calls` keys native response ids by session and merges counters with maxima in one writer transaction | `live_token_usage.rs` scope, owner, pagination, replay, and mutation controls | STRONG |+| 30a | Session drilldowns are owner-scoped for a user and complete for root | `ai-memory-web/src/routes/api.rs` `session_owner_filter_for`: `AuthLevel::Root` → `OwnerFilter::Any`, every other caller → `owner_filter_for` (own plus shared). Used by `routes/agents.rs`, `routes/project.rs` (sessions, agent and token-usage tabs), `routes/session.rs`, and the `/api/v1` `sessions_handler` and `session_observations_handler`. Handoff reads keep `owner_filter_for` and root's explicit `all_owners` | `ai-memory-web` `operations.rs` `operations_root_drilldowns_reach_every_users_sessions_and_users_stay_owned`: a user's agent page, Sessions tab and session list omit another user's session and its session page and observations answer 404; root's list it and answer 200 (control: the user's own and the shared session stay visible) | STRONG. Bite checks: with root mapped to `owner_filter_for`, root's agent page misses the other user's session; with every caller mapped to `Any`, the user's agent page lists it || 31 | Browser inbox operations hide restricted projects and preserve both-coordinate write authorization | Inbox and notification routes derive choices and counts from viewer-filtered projects; sends and edits require write access to the recipient and sender coordinates, sanitization, admission, CSRF, and fixed capabilities | `operations.rs` restricted-project, foreign-workspace, authorization, and notification tests; dashboard browser mutation cases | STRONG || 32 | Directed and held messages cannot be claimed by the wrong harness or while editing | Both message claim guards require `state = 'pending'` and match `to_agent`; begin/finish edit are coordinate- and state-guarded single-writer updates | `agent_messages.rs` addressed claim-once and editing-state tests; web authorization tests; mutation probes for wrong-harness and held-message claims | STRONG |diff --git a/docs/users.md b/docs/users.mdindex 586ee333..4b72e3fe 100644--- a/docs/users.md+++ b/docs/users.md@@ -228,6 +228,13 @@ to, and consumed by, the next session to start, whoever it belongs to.descending and then agent name. An unknown scope returns 404 without creatingit. Like every `/admin/*` route, this endpoint is root-only when thedeployment distinguishes operators.+- The web session views (a project's Sessions, Agents and Token usage tabs,+ each agent's page and each session's page) and the read-only+ `GET /api/v1/workspaces/{ws}/projects/{p}/sessions` and+ `.../sessions/{id}/observations` routes follow the same rule for a user:+ their own sessions plus the shared ones, and another operator's session+ reads as not found. The root operator sees every operator's sessions there,+ matching the dashboard's counts, which already include everyone.- The read-only handoff listing (`GET/api/v1/workspaces/{ws}/projects/{p}/handoffs`) serves its prompt-derivedfields (`summary`, `open_questions`, `next_steps`) to a caller the server